Skip to content

Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook

Render the transcript natively: tables, code, HTML-lite, math, progressive streaming (#148)

Andrey Mikhaylovd20d0df8f949
diff --git a/Package.resolved b/Package.resolved
index 5d6cd2ac..04bc2c2d 100644
--- a/Package.resolved
+++ b/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "794fbf949f0e97118a7640964bafcb54454e69c994c870b072392cd249f5f136",
+ "originHash" : "f4ad04f231fe8b0dd69f316ef5b53acec48ee85d69800ef3399b9dd19ef5c49d",
"pins" : [
{
"identity" : "eventsource",
@@ -91,6 +91,14 @@
"version" : "1.3.3"
}
},
+ {
+ "identity" : "swiftmath",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/mgriebling/SwiftMath.git",
+ "state" : {
+ "revision" : "1d2c90827e9c3908269d810d055fb03b7da5fd53"
+ }
+ },
{
"identity" : "yyjson",
"kind" : "remoteSourceControl",
diff --git a/Package.swift b/Package.swift
index 127f8138..829209b2 100644
--- a/Package.swift
+++ b/Package.swift
@@ -18,6 +18,12 @@ let package = Package(
dependencies: [
.package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),
.package(url: "https://github.com/apple/swift-nio.git", exact: "2.101.3"),
+ // Pinned by revision: tag 1.7.3 predates the `\left...\right`
+ // duplication fix and typesets 433 of the 607-string coverage sweep
+ // against this revision's 479.
+ .package(
+ url: "https://github.com/mgriebling/SwiftMath.git",
+ revision: "1d2c90827e9c3908269d810d055fb03b7da5fd53"),
],
targets: [
.target(
@@ -67,7 +73,10 @@ let package = Package(
),
.target(
name: "TurboFieldfareMacPresentation",
- dependencies: ["TurboFieldfareAppCore"],
+ dependencies: [
+ "TurboFieldfareAppCore",
+ .product(name: "SwiftMath", package: "SwiftMath"),
+ ],
path: "Sources/TurboFieldfareApp/MacPresentation"
),
.target(
@@ -148,7 +157,8 @@ let package = Package(
.testTarget(
name: "TurboFieldfareMacPresentationTests",
dependencies: ["TurboFieldfareAppCore", "TurboFieldfareMacPresentation"],
- path: "Tests/TurboFieldfareApp/MacPresentation"
+ path: "Tests/TurboFieldfareApp/MacPresentation",
+ resources: [.copy("Fixtures")]
),
.testTarget(
name: "TurboFieldfareServerTests",
diff --git a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift
index 60bd37a5..4f4e53bd 100644
--- a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift
+++ b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift
@@ -595,8 +595,17 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
updatePrefillAnimationTimer()
guard update.mutation != .none else { return }
+ // A rewritten stretch is different text, so a selection that
+ // reached into it is dropped back to the boundary rather than
+ // kept at its old length over characters it never covered.
+ let adjusted = update.replaced.map {
+ InstructionTranscriptDocumentController.adjustedRanges(
+ selection,
+ replacing: $0.previous,
+ newLength: $0.length)
+ } ?? selection
let restored = InstructionTranscriptDocumentController.clampedRanges(
- selection,
+ adjusted,
toLength: storage.length)
if restored.isEmpty {
textView.setSelectedRange(NSRange(location: storage.length, length: 0))
@@ -717,7 +726,7 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
scrollView.autohidesScrollers = true
scrollView.drawsBackground = false
- let textView = NSTextView()
+ let textView = TranscriptTextView()
textView.isEditable = false
textView.isSelectable = true
textView.isRichText = true
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
index 5aff1037..efd49661 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
@@ -17,7 +17,7 @@ public enum AboutPanelPresentation {
// Most users build from a clone, where there is no Info.plist to read a
// version from, so this constant is what they see. Scripts/check_app_version.rb
// fails CI when it falls behind the newest published release.
- public static let fallbackShortVersion = "0.5.0"
+ public static let fallbackShortVersion = "0.6.0"
private static let licenseURL = URL(
string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!
diff --git a/Sources/TurboFieldfareApp/MacPresentation/ContainerPrefix.swift b/Sources/TurboFieldfareApp/MacPresentation/ContainerPrefix.swift
new file mode 100644
index 00000000..78e7511e
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/ContainerPrefix.swift
@@ -0,0 +1,131 @@
+import Foundation
+
+/// The two container prefixes a line can wear, read the way CommonMark reads
+/// them. A list item's content column decides what belongs to the item and what
+/// interrupts it, and both the splitter and the tail auto-close need the same
+/// answer: a fence at the column is the item's own listing, one before it ends
+/// the list.
+enum ContainerPrefix {
+ struct ListItem: Equatable {
+ /// Columns of indentation before the marker.
+ let markerIndent: Int
+ /// Column the item's content starts at. CommonMark 5.2: the marker's
+ /// indent plus its width plus the spaces after it, except that a marker
+ /// which ends the line or is followed by five or more spaces starts its
+ /// content one column past itself.
+ let contentColumn: Int
+ }
+
+ static func listItem(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ in content: Range<Int>
+ ) -> ListItem? {
+ var index = content.lowerBound
+ var indent = 0
+ while index < content.upperBound {
+ if bytes[index] == UInt8(ascii: " ") {
+ indent += 1
+ } else if bytes[index] == UInt8(ascii: "\t") {
+ indent += 4
+ } else {
+ break
+ }
+ index += 1
+ }
+ guard index < content.upperBound else { return nil }
+ var width = 0
+ let first = bytes[index]
+ if first == UInt8(ascii: "-") || first == UInt8(ascii: "*")
+ || first == UInt8(ascii: "+") {
+ width = 1
+ } else {
+ var digits = 0
+ var cursor = index
+ while cursor < content.upperBound, bytes[cursor] >= UInt8(ascii: "0"),
+ bytes[cursor] <= UInt8(ascii: "9") {
+ digits += 1
+ cursor += 1
+ }
+ guard digits > 0, digits <= 9, cursor < content.upperBound,
+ bytes[cursor] == UInt8(ascii: ".") || bytes[cursor] == UInt8(ascii: ")") else {
+ return nil
+ }
+ width = digits + 1
+ }
+ var spaces = 0
+ var cursor = index + width
+ let markerEnd = cursor
+ while cursor < content.upperBound {
+ if bytes[cursor] == UInt8(ascii: " ") {
+ spaces += 1
+ } else if bytes[cursor] == UInt8(ascii: "\t") {
+ spaces += 4
+ } else {
+ break
+ }
+ cursor += 1
+ }
+ guard markerEnd >= content.upperBound || spaces > 0 else { return nil }
+ return item(indent: indent, width: width, spaces: spaces, endsLine: markerEnd >= content.upperBound)
+ }
+
+ static func listItem(_ line: some Collection<Character>) -> ListItem? {
+ var rest = line[...]
+ var indent = 0
+ while let first = rest.first, first == " " || first == "\t" {
+ indent += first == "\t" ? 4 : 1
+ rest = rest.dropFirst()
+ }
+ guard let first = rest.first else { return nil }
+ var width = 0
+ if first == "-" || first == "*" || first == "+" {
+ width = 1
+ } else {
+ let digits = rest.prefix { $0.isASCII && $0.isNumber }
+ let after = rest.dropFirst(digits.count).first
+ guard !digits.isEmpty, digits.count <= 9, after == "." || after == ")" else {
+ return nil
+ }
+ width = digits.count + 1
+ }
+ let afterMarker = rest.dropFirst(width)
+ var spaces = 0
+ for character in afterMarker {
+ guard character == " " || character == "\t" else { break }
+ spaces += character == "\t" ? 4 : 1
+ }
+ guard afterMarker.isEmpty || spaces > 0 else { return nil }
+ return item(indent: indent, width: width, spaces: spaces, endsLine: afterMarker.isEmpty)
+ }
+
+ private static func item(
+ indent: Int,
+ width: Int,
+ spaces: Int,
+ endsLine: Bool
+ ) -> ListItem {
+ let column = endsLine || spaces >= 5 ? indent + width + 1 : indent + width + spaces
+ return ListItem(markerIndent: indent, contentColumn: column)
+ }
+
+ /// The line with its blockquote markers removed, and how many there were.
+ /// A closer written back into the tail has to carry them again or the
+ /// parser reads it as prose after the quote.
+ static func strippingQuoteMarkers(_ line: Substring) -> (depth: Int, rest: Substring) {
+ var rest = line
+ var depth = 0
+ while true {
+ var probe = rest
+ var indent = 0
+ while let first = probe.first, first == " " || first == "\t", indent < 3 {
+ indent += first == "\t" ? 4 : 1
+ probe = probe.dropFirst()
+ }
+ guard probe.first == ">" else { return (depth, rest) }
+ probe = probe.dropFirst()
+ if probe.first == " " { probe = probe.dropFirst() }
+ depth += 1
+ rest = probe
+ }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/FenceLine.swift b/Sources/TurboFieldfareApp/MacPresentation/FenceLine.swift
new file mode 100644
index 00000000..578d7dcb
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/FenceLine.swift
@@ -0,0 +1,123 @@
+import Foundation
+
+/// What a fenced-code fence line is, in one place.
+///
+/// Four scanners carried their own copy of this grammar and disagreed with
+/// CommonMark and with each other. A backtick fence's info string may not
+/// contain a backtick, so ```` ```bash``` ```` in a sentence is a code span:
+/// the splitter, the bold-heading promotion, the tail auto-close and the code
+/// mask all read it as an opener and boxed the rest of the answer as code,
+/// while the renderer's raw-fallback gate counted delimiters instead of lines
+/// and sent an answer with one mid-line ```` ``` ```` to raw text entirely.
+enum FenceLine {
+ static let backtick = UInt8(ascii: "`")
+ static let tilde = UInt8(ascii: "~")
+
+ struct Run: Equatable {
+ /// ASCII `` ` `` or `~`.
+ let marker: UInt8
+ let length: Int
+ /// The line's own indentation in columns, container included.
+ let indent: Int
+ /// Nothing after the marker run but spaces, which is what a closing
+ /// fence is; an opener carries an info string.
+ let isBare: Bool
+
+ var character: Character { Character(UnicodeScalar(marker)) }
+
+ func closes(marker: UInt8, length: Int) -> Bool {
+ isBare && self.marker == marker && self.length >= length
+ }
+ }
+
+ /// - Parameter containerIndent: the content column of the block the line
+ /// sits in — a list item's text column, zero at top level. CommonMark
+ /// allows a fence up to three columns past it, and a fence further left
+ /// than the column belongs to whatever encloses the container.
+ static func run(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ in content: Range<Int>,
+ containerIndent: Int = 0
+ ) -> Run? {
+ var index = content.lowerBound
+ var indent = 0
+ while index < content.upperBound {
+ if bytes[index] == UInt8(ascii: " ") {
+ indent += 1
+ } else if bytes[index] == UInt8(ascii: "\t") {
+ indent += 4
+ } else {
+ break
+ }
+ index += 1
+ }
+ guard index < content.upperBound else { return nil }
+ let marker = bytes[index]
+ var length = 0
+ while index < content.upperBound, bytes[index] == marker {
+ length += 1
+ index += 1
+ }
+ var bare = true
+ var infoHasBacktick = false
+ while index < content.upperBound {
+ let byte = bytes[index]
+ if byte != UInt8(ascii: " "), byte != UInt8(ascii: "\t"),
+ byte != UInt8(ascii: "\r") {
+ bare = false
+ if byte == backtick { infoHasBacktick = true }
+ }
+ index += 1
+ }
+ return validated(
+ marker: marker,
+ length: length,
+ indent: indent,
+ containerIndent: containerIndent,
+ isBare: bare,
+ infoHasBacktick: infoHasBacktick)
+ }
+
+ static func run(
+ _ characters: some Collection<Character>,
+ containerIndent: Int = 0
+ ) -> Run? {
+ var indent = 0
+ var rest = characters[...]
+ while let first = rest.first, first == " " || first == "\t" {
+ indent += first == "\t" ? 4 : 1
+ rest = rest.dropFirst()
+ }
+ guard let first = rest.first, let marker = first.asciiValue else { return nil }
+ let length = rest.prefix { $0 == first }.count
+ var bare = true
+ var infoHasBacktick = false
+ for character in rest.dropFirst(length)
+ where character != " " && character != "\t" && character != "\r" {
+ bare = false
+ if character == "`" { infoHasBacktick = true }
+ }
+ return validated(
+ marker: marker,
+ length: length,
+ indent: indent,
+ containerIndent: containerIndent,
+ isBare: bare,
+ infoHasBacktick: infoHasBacktick)
+ }
+
+ private static func validated(
+ marker: UInt8,
+ length: Int,
+ indent: Int,
+ containerIndent: Int,
+ isBare: Bool,
+ infoHasBacktick: Bool
+ ) -> Run? {
+ guard marker == backtick || marker == tilde, length >= 3 else { return nil }
+ let relative = indent - containerIndent
+ guard relative >= 0, relative <= 3 else { return nil }
+ guard marker != backtick || !infoHasBacktick else { return nil }
+ return Run(marker: marker, length: length, indent: indent, isBare: isBare)
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
index 4ce0519e..fa9b92af 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
@@ -7,16 +7,93 @@ public final class InstructionTranscriptDocumentController {
case none
case rebuilt
case appended
+ /// The open block was re-rendered in place. The completed blocks above
+ /// it did not move, so the reader keeps their position.
+ case tailReplaced
case finalized
}
+ /// The stretch of the document this update rewrote, in the coordinates the
+ /// document had *before* it. Everything below `previous.location` is the
+ /// same text it was, which is what lets a selection there keep its exact
+ /// indices instead of being clamped onto different characters.
+ public struct ReplacedRange: Equatable {
+ public let previous: NSRange
+ public let length: Int
+
+ public init(previous: NSRange, length: Int) {
+ self.previous = previous
+ self.length = length
+ }
+
+ /// The part of `previous` that actually changed.
+ ///
+ /// A tail re-render rewrites the same sentence with a few characters
+ /// added, and reporting the whole tail as replaced collapsed every
+ /// selection inside it — including one over text that had not moved.
+ /// Trimming the common prefix and suffix leaves only what differs;
+ /// nil when the two are the same text.
+ public static func differing(
+ previous: NSRange,
+ old: NSString,
+ new: NSString
+ ) -> ReplacedRange? {
+ let shorter = min(old.length, new.length)
+ var prefix = 0
+ while prefix < shorter, old.character(at: prefix) == new.character(at: prefix) {
+ prefix += 1
+ }
+ guard prefix < old.length || prefix < new.length else { return nil }
+ var suffix = 0
+ while suffix < shorter - prefix,
+ old.character(at: old.length - 1 - suffix)
+ == new.character(at: new.length - 1 - suffix) {
+ suffix += 1
+ }
+
+ // Neither boundary may land inside a composed character sequence,
+ // or the replacement writes half a character.
+ var start = prefix
+ if start > 0, start < old.length {
+ start = min(start, old.rangeOfComposedCharacterSequence(at: start).location)
+ }
+ if start > 0, start < new.length {
+ start = min(start, new.rangeOfComposedCharacterSequence(at: start).location)
+ }
+ var oldEnd = max(start, old.length - suffix)
+ var newEnd = max(start, new.length - suffix)
+ if oldEnd > start, oldEnd < old.length {
+ let sequence = old.rangeOfComposedCharacterSequence(at: oldEnd)
+ if sequence.location < oldEnd { oldEnd = sequence.upperBound }
+ }
+ if newEnd > start, newEnd < new.length {
+ let sequence = new.rangeOfComposedCharacterSequence(at: newEnd)
+ if sequence.location < newEnd { newEnd = sequence.upperBound }
+ }
+ // The two ends move together or the suffixes they leave behind
+ // stop matching.
+ let kept = min(old.length - oldEnd, new.length - newEnd)
+ return ReplacedRange(
+ previous: NSRange(
+ location: previous.location + start,
+ length: old.length - kept - start),
+ length: new.length - kept - start)
+ }
+ }
+
public struct UpdateResult {
public let mutation: Mutation
public let assistantRange: NSRange
+ public let replaced: ReplacedRange?
- public init(mutation: Mutation, assistantRange: NSRange) {
+ public init(
+ mutation: Mutation,
+ assistantRange: NSRange,
+ replaced: ReplacedRange? = nil
+ ) {
self.mutation = mutation
self.assistantRange = assistantRange
+ self.replaced = replaced
}
}
@@ -29,10 +106,25 @@ public final class InstructionTranscriptDocumentController {
private var prefillPlaceholderRange: NSRange?
private var prefillDotCount = 0
- private let renderer: ResponseMarkdownRenderer
+ private let renderer: any TranscriptBlockRendering
+ private let progressiveRendering: Bool
+ private var progressive = ProgressiveState()
- public init(renderer: ResponseMarkdownRenderer = ResponseMarkdownRenderer()) {
+ public init(
+ renderer: any TranscriptBlockRendering = ResponseMarkdownRenderer(),
+ environment: [String: String] = ProcessInfo.processInfo.environment
+ ) {
self.renderer = renderer
+ progressiveRendering = environment["TURBO_FIELDFARE_PROGRESSIVE_RENDER"] != "0"
+ }
+
+ /// The part of the assistant range that is still being written. Only this
+ /// range is rewritten while an answer streams; in the raw streaming mode
+ /// the whole answer is unrendered and the two ranges are the same.
+ public var tailRange: NSRange {
+ NSRange(
+ location: assistantRange.location + progressive.prefixLength,
+ length: max(0, assistantRange.length - progressive.prefixLength))
}
public static func clampedRanges(
@@ -46,6 +138,37 @@ public final class InstructionTranscriptDocumentController {
}
}
+ /// Where a selection lands after part of the document was rewritten.
+ ///
+ /// Clamping the old ranges onto the new length kept their lengths and so
+ /// kept selecting *something* — whatever now sits at those indices. When
+ /// the open tail is redrawn on a streaming tick that is different text,
+ /// so a selection that reached into the tail loses the part that no longer
+ /// exists and keeps the part above it, which has not moved.
+ public static func adjustedRanges(
+ _ ranges: [NSRange],
+ replacing replaced: NSRange,
+ newLength: Int
+ ) -> [NSRange] {
+ let end = replaced.location + newLength
+ let delta = newLength - replaced.length
+ return ranges.map { range in
+ guard range.upperBound > replaced.location else { return range }
+ // Below the rewrite the characters are the same ones, just moved.
+ // Collapsing them too dropped a selection over a heading the
+ // finalize pass never touched.
+ guard range.location < replaced.upperBound else {
+ return NSRange(location: range.location + delta, length: range.length)
+ }
+ guard range.location < replaced.location else {
+ return NSRange(location: min(range.location, end), length: 0)
+ }
+ return NSRange(
+ location: range.location,
+ length: replaced.location - range.location)
+ }
+ }
+
public static func shouldScrollToBottom(
wasAtBottom: Bool,
mutation: Mutation
@@ -61,6 +184,52 @@ public final class InstructionTranscriptDocumentController {
requested && response.isEmpty && !isTerminal
}
+ /// Whether `response` starts with the exact bytes of `previous`.
+ /// `hasPrefix` compares by canonical equivalence, so a decomposed prefix
+ /// that arrives recomposed passes it while the UTF-8 offsets the delta is
+ /// cut at no longer line up, and the append writes the wrong characters
+ /// onto a document drawn from different ones.
+ private static func extendsExactly(_ response: String, _ previous: String) -> Bool {
+ let count = previous.utf8.count
+ guard count > 0 else { return true }
+ guard response.utf8.count >= count else { return false }
+ // Through contiguous storage, not an element-wise walk of two UTF8
+ // views: this runs on every streaming tick, and iterating one costs a
+ // measurable fraction of the tick by the end of a long answer.
+ return Self.withUTF8(response) { response in
+ Self.withUTF8(previous) { previous in
+ guard let left = response.baseAddress, let right = previous.baseAddress else {
+ return response.prefix(count).elementsEqual(previous)
+ }
+ return memcmp(left, right, count) == 0
+ }
+ }
+ }
+
+ private static func withUTF8<R>(
+ _ text: String,
+ _ body: (UnsafeBufferPointer<UInt8>) -> R
+ ) -> R {
+ if let result = text.utf8.withContiguousStorageIfAvailable(body) { return result }
+ var copy = text
+ return copy.withUTF8 { body($0) }
+ }
+
+ /// The text `response` adds on top of `previous`, or nil when the two do
+ /// not share a Character-aligned UTF-8 prefix and the document must be
+ /// rebuilt instead. Grapheme-based `count`/`dropFirst` walk the whole
+ /// response on every streaming tick, which is quadratic across a
+ /// generation; UTF-8 offsets are constant time on native strings.
+ private static func appendedSuffix(of response: String, after previous: String) -> String? {
+ let previousBytes = previous.utf8.count
+ guard response.utf8.count > previousBytes else { return nil }
+ let boundary = response.utf8.index(
+ response.utf8.startIndex,
+ offsetBy: previousBytes)
+ guard let start = boundary.samePosition(in: response) else { return nil }
+ return String(response[start...])
+ }
+
@discardableResult
public func synchronize(
storage: NSMutableAttributedString,
@@ -76,13 +245,23 @@ public final class InstructionTranscriptDocumentController {
response: response,
isTerminal: isTerminal,
requested: showsPrefillPlaceholder)
- let needsRebuild = prompt != self.prompt
+ var needsRebuild = prompt != self.prompt
|| promptPrefixIdentifier != self.promptPrefixIdentifier
- || !response.hasPrefix(self.response)
+ || !Self.extendsExactly(response, self.response)
|| (isFinalized && !isTerminal)
|| displaysPrefillPlaceholder != self.showsPrefillPlaceholder
+ var appendedDelta: String?
+ if !needsRebuild, response.utf8.count > self.response.utf8.count {
+ appendedDelta = Self.appendedSuffix(of: response, after: self.response)
+ needsRebuild = appendedDelta == nil
+ }
var mutation: Mutation = .none
+ var replaced: ReplacedRange?
+ // In progressive mode a terminal response is closed block by block, so
+ // the tick that carries it is an ordinary extension. The raw mode is
+ // replaced wholesale below and has nothing to gain from writing the
+ // delta first.
if needsRebuild
|| storage.length == 0
&& (!prompt.isEmpty || promptPrefix.length > 0
@@ -92,15 +271,20 @@ public final class InstructionTranscriptDocumentController {
prompt: prompt,
promptPrefix: promptPrefix,
response: response,
- showsPrefillPlaceholder: displaysPrefillPlaceholder)
+ showsPrefillPlaceholder: displaysPrefillPlaceholder,
+ closingTail: isTerminal)
mutation = .rebuilt
- } else if response.count > self.response.count {
- let delta = String(response.dropFirst(self.response.count))
- storage.append(NSAttributedString(
- string: delta,
- attributes: Self.responseAttributes()))
- assistantRange.length += (delta as NSString).length
- mutation = .appended
+ } else if let delta = appendedDelta {
+ if progressiveRendering {
+ let update = extendProgressiveRender(
+ storage: storage,
+ response: response,
+ closingTail: isTerminal)
+ mutation = update.mutation
+ replaced = update.replaced
+ } else if !isTerminal {
+ mutation = appendRaw(delta, to: storage)
+ }
}
self.prompt = prompt
@@ -109,16 +293,33 @@ public final class InstructionTranscriptDocumentController {
self.showsPrefillPlaceholder = displaysPrefillPlaceholder
if isTerminal && (!isFinalized || responseChanged) {
- let rendered = renderer.render(response).attributedString
- storage.replaceCharacters(in: assistantRange, with: rendered)
- assistantRange.length = rendered.length
+ if progressiveRendering {
+ // Finalize closes the open block and leaves everything above it
+ // exactly as it was drawn. Re-rendering the whole answer put it
+ // back through message-wide gates the streaming pass applies
+ // per block — an unclosed fence anywhere, a table in a list, a
+ // block-level HTML tag — so an answer that streamed styled
+ // flipped to raw source the moment it finished.
+ if let update = closeTail(storage: storage, response: response) {
+ replaced = update
+ }
+ } else {
+ let rendered = renderer.render(response, typesetsMath: true).attributedString
+ replaced = ReplacedRange(previous: assistantRange, length: rendered.length)
+ storage.replaceCharacters(in: assistantRange, with: rendered)
+ assistantRange.length = rendered.length
+ progressive.reset()
+ }
isFinalized = true
mutation = .finalized
} else if !isTerminal {
isFinalized = false
}
- return UpdateResult(mutation: mutation, assistantRange: assistantRange)
+ return UpdateResult(
+ mutation: mutation,
+ assistantRange: assistantRange,
+ replaced: replaced)
}
@discardableResult
@@ -138,12 +339,24 @@ public final class InstructionTranscriptDocumentController {
return true
}
+ private func appendRaw(
+ _ delta: String,
+ to storage: NSMutableAttributedString
+ ) -> Mutation {
+ storage.append(NSAttributedString(
+ string: delta,
+ attributes: Self.responseAttributes()))
+ assistantRange.length += (delta as NSString).length
+ return .appended
+ }
+
private func rebuild(
storage: NSMutableAttributedString,
prompt: String,
promptPrefix: NSAttributedString,
response: String,
- showsPrefillPlaceholder: Bool
+ showsPrefillPlaceholder: Bool,
+ closingTail: Bool
) {
let document = NSMutableAttributedString()
if !prompt.isEmpty || promptPrefix.length > 0 {
@@ -171,10 +384,11 @@ public final class InstructionTranscriptDocumentController {
string: "Answer\n",
attributes: Self.assistantLabelAttributes()))
assistantRange = NSRange(location: document.length, length: 0)
- document.append(NSAttributedString(
- string: response,
- attributes: Self.responseAttributes()))
- assistantRange.length = (response as NSString).length
+ let assistant = progressiveRendering
+ ? progressiveRender(response, closingTail: closingTail)
+ : NSAttributedString(string: response, attributes: Self.responseAttributes())
+ document.append(assistant)
+ assistantRange.length = assistant.length
prefillDotCount = 0
prefillPlaceholderRange = nil
if showsPrefillPlaceholder {
@@ -190,6 +404,458 @@ public final class InstructionTranscriptDocumentController {
isFinalized = false
}
+ // MARK: - Progressive rendering
+
+ /// What the transcript shows while an answer is still arriving: every
+ /// completed block already styled, and the block being written re-rendered
+ /// from an auto-closed copy of itself. Finalize closes that last block the
+ /// same way, so nothing above it is ever looked at twice.
+ ///
+ /// The cost of rendering block by block is that a block cannot see the
+ /// rest of the answer: a `[label][ref]` whose definition sits in a later
+ /// block keeps its brackets. Resolving it per tick is the quadratic shape
+ /// the timing gate forbids, and resolving it only at finalize would
+ /// reintroduce the flip this pass removed.
+ private struct ProgressiveState {
+ var split = ResponseBlockSplitter.Split()
+ /// Completed blocks that are already drawn.
+ var renderedBlocks = 0
+ /// NSString length of those blocks and the separators between them,
+ /// including the separator that precedes the open tail.
+ var prefixLength = 0
+ /// UTF-8 offset of the open block the drawn tail was made from.
+ var tailStart: Int?
+ var fence: FenceTail?
+ /// Rendered blocks keyed by position and text. Position is part of the
+ /// key because two identical tables must not share one `NSTextTable`,
+ /// which TextKit would draw as a single merged table.
+ var cache: [BlockKey: NSAttributedString] = [:]
+
+ mutating func reset() {
+ split = ResponseBlockSplitter.Split()
+ renderedBlocks = 0
+ prefixLength = 0
+ tailStart = nil
+ fence = nil
+ }
+ }
+
+ private struct BlockKey: Hashable {
+ let start: Int
+ let text: String
+ }
+
+ /// A fenced block that is still arriving. It is drawn directly rather than
+ /// through the markdown pass because it is the one block with no size
+ /// bound: re-parsing a 10 KB listing on each of the ~1,200 ticks it takes
+ /// to stream is quadratic, while appending the bytes that arrived is not.
+ private struct FenceTail {
+ let attributes: [NSAttributedString.Key: Any]
+ let bodyStart: Int
+ var bodyEnd: Int
+ var filter: CodeBodyFilter
+ /// The drawn tail ends with a newline this controller added because the
+ /// body has none of its own yet; the next delta replaces it.
+ var synthetic: Bool
+ }
+
+ /// Turns raw fenced-body bytes into what the markdown parser would have
+ /// produced: CRLF and a lone CR become LF, and the opening fence's own
+ /// indentation comes off every line. Deltas arrive one at a time, so the CR
+ /// that ends one and the LF that starts the next still collapse into a
+ /// single line break.
+ private struct CodeBodyFilter {
+ let indent: Int
+ private var pendingCarriageReturn = false
+ /// Columns of the current line consumed while the opening fence's own
+ /// indentation comes off. A tab is four columns wide, so one that
+ /// reaches past the fence's indent keeps the columns it owns beyond
+ /// it: dropping the whole tab lost the listing's indentation until the
+ /// answer finalized and the markdown pass drew it properly.
+ private var column = 0
+ private var stripping: Bool
+ private(set) var endsWithNewline = true
+
+ init(indent: Int) {
+ self.indent = indent
+ stripping = indent > 0
+ }
+
+ /// Scalars, not characters: Swift reads CRLF as one `Character`, so a
+ /// character loop would carry the carriage return straight through into
+ /// the transcript.
+ mutating func append(_ raw: String) -> String {
+ var output = String.UnicodeScalarView()
+ output.reserveCapacity(raw.unicodeScalars.count)
+ for scalar in raw.unicodeScalars {
+ if scalar == "\n" {
+ if pendingCarriageReturn {
+ pendingCarriageReturn = false
+ continue
+ }
+ output.append("\n")
+ startLine()
+ endsWithNewline = true
+ continue
+ }
+ pendingCarriageReturn = false
+ if scalar == "\r" {
+ pendingCarriageReturn = true
+ output.append("\n")
+ startLine()
+ endsWithNewline = true
+ continue
+ }
+ if stripping, scalar == " " {
+ column += 1
+ stripping = column < indent
+ continue
+ }
+ if stripping, scalar == "\t" {
+ let reached = column + 4 - column % 4
+ column = reached
+ stripping = false
+ if reached > indent {
+ for _ in 0..<(reached - indent) { output.append(" ") }
+ endsWithNewline = false
+ }
+ continue
+ }
+ stripping = false
+ endsWithNewline = false
+ output.append(scalar)
+ }
+ return String(output)
+ }
+
+ private mutating func startLine() {
+ column = 0
+ stripping = indent > 0
+ }
+ }
+
+ private func progressiveRender(
+ _ response: String,
+ closingTail: Bool
+ ) -> NSAttributedString {
+ progressive.reset()
+ let split = ResponseBlockSplitter.split(response)
+ progressive.split = split
+ let content = NSMutableAttributedString()
+ var trailing = 0
+ for block in split.completed {
+ // With the separator the incremental path writes. Without it a
+ // rebuild mid-answer — an image thumbnail landing and changing the
+ // prompt prefix — glued every completed block to the one above it
+ // and left the answer that way until finalize.
+ append(
+ block,
+ of: response,
+ to: content,
+ trailing: &trailing,
+ isFirst: content.length == 0)
+ }
+ progressive.renderedBlocks = split.completed.count
+ if let open = split.open {
+ content.append(separator(trailingNewlines: trailing, isFirst: content.length == 0))
+ progressive.prefixLength = content.length
+ if closingTail {
+ // A terminal rebuild draws the last block finished. Rendering it
+ // as a tail and then re-rendering the whole answer cost N+2
+ // passes over an answer that was already on screen.
+ progressive.tailStart = open.start
+ progressive.fence = nil
+ content.append(renderedBlock(open, of: response))
+ } else {
+ content.append(renderTail(open, of: response))
+ }
+ } else {
+ progressive.prefixLength = content.length
+ }
+ return content
+ }
+
+ private struct ProgressiveUpdate {
+ let mutation: Mutation
+ var replaced: ReplacedRange?
+ }
+
+ private func extendProgressiveRender(
+ storage: NSMutableAttributedString,
+ response: String,
+ closingTail: Bool
+ ) -> ProgressiveUpdate {
+ let split = ResponseBlockSplitter.split(response, resuming: progressive.split)
+ progressive.split = split
+
+ if !closingTail,
+ split.completed.count == progressive.renderedBlocks,
+ let open = split.open,
+ open.start == progressive.tailStart,
+ let fence = open.fence,
+ let drawn = progressive.fence,
+ fence.bodyStart == drawn.bodyStart {
+ return growFence(fence, storage: storage, response: response)
+ }
+
+ var replacedTail = false
+ let drawnTail = tailRange
+ let drawnTailText = (storage.string as NSString).substring(with: NSRange(
+ location: min(drawnTail.location, storage.length),
+ length: min(drawnTail.length, max(0, storage.length - drawnTail.location)))) as NSString
+ if progressive.tailStart != nil {
+ if let promoted = split.completed[safe: progressive.renderedBlocks],
+ promoted.start == progressive.tailStart,
+ keepsDrawnBytes(promoted) {
+ // The tail was a fenced block drawn from exactly this body; its
+ // closing line adds nothing to the render, so the bytes stay
+ // where they are and only the boundary moves.
+ progressive.prefixLength += drawnTail.length
+ progressive.renderedBlocks += 1
+ } else if drawnTail.length > 0 {
+ storage.deleteCharacters(in: drawnTail)
+ assistantRange.length = progressive.prefixLength
+ replacedTail = true
+ }
+ progressive.tailStart = nil
+ progressive.fence = nil
+ }
+
+ let addition = NSMutableAttributedString()
+ var trailing = trailingNewlines(in: storage)
+ while progressive.renderedBlocks < split.completed.count {
+ let block = split.completed[progressive.renderedBlocks]
+ append(
+ block,
+ of: response,
+ to: addition,
+ trailing: &trailing,
+ isFirst: assistantRange.length == 0 && addition.length == 0)
+ progressive.renderedBlocks += 1
+ }
+ if let open = split.open {
+ addition.append(separator(
+ trailingNewlines: trailing,
+ isFirst: assistantRange.length == 0 && addition.length == 0))
+ progressive.prefixLength = assistantRange.length + addition.length
+ if closingTail {
+ progressive.tailStart = open.start
+ progressive.fence = nil
+ addition.append(renderedBlock(open, of: response))
+ } else {
+ addition.append(renderTail(open, of: response))
+ }
+ } else {
+ progressive.prefixLength = assistantRange.length + addition.length
+ }
+ guard addition.length > 0 else {
+ guard replacedTail else { return ProgressiveUpdate(mutation: .none) }
+ return ProgressiveUpdate(
+ mutation: .tailReplaced,
+ replaced: ReplacedRange(previous: drawnTail, length: 0))
+ }
+ storage.replaceCharacters(
+ in: NSRange(location: assistantRange.upperBound, length: 0),
+ with: addition)
+ assistantRange.length += addition.length
+ guard replacedTail else { return ProgressiveUpdate(mutation: .appended) }
+ return ProgressiveUpdate(
+ mutation: .tailReplaced,
+ replaced: ReplacedRange.differing(
+ previous: drawnTail,
+ old: drawnTailText,
+ new: addition.string as NSString)
+ ?? ReplacedRange(previous: drawnTail, length: addition.length))
+ }
+
+ /// Closes the block that was still being written, in place.
+ ///
+ /// The blocks above it are the ones already drawn: nothing above the open
+ /// block is looked at again, so a message-wide gate cannot turn a styled
+ /// answer back into raw source at the moment it finishes.
+ private func closeTail(
+ storage: NSMutableAttributedString,
+ response: String
+ ) -> ReplacedRange? {
+ let update = extendProgressiveRender(
+ storage: storage,
+ response: response,
+ closingTail: true)
+ return update.replaced
+ }
+
+ /// Appends one completed block and remembers how many newlines it left
+ /// behind, so the next separator matches what a whole-document render puts
+ /// between the same two blocks.
+ private func append(
+ _ block: ResponseBlockSplitter.Block,
+ of response: String,
+ to content: NSMutableAttributedString,
+ trailing: inout Int,
+ isFirst: Bool
+ ) {
+ let rendered = renderedBlock(block, of: response)
+ // A block that draws nothing — an empty fence — takes no separator
+ // with it either, or the gap around it is written twice.
+ guard rendered.length > 0 else { return }
+ let separator = self.separator(trailingNewlines: trailing, isFirst: isFirst)
+ content.append(separator)
+ content.append(rendered)
+ // The separator's own newlines count too. Seeding with the previous
+ // block's count instead left a fence whose body is one blank line with
+ // an extra paragraph gap under it that the whole render does not have.
+ trailing = min(2, Self.trailingNewlines(
+ rendered.string,
+ seed: trailing + separator.length))
+ }
+
+ private func separator(trailingNewlines: Int, isFirst: Bool) -> NSAttributedString {
+ guard !isFirst else { return NSAttributedString() }
+ return renderer.blockSeparator(trailingNewlines: trailingNewlines)
+ }
+
+ private func renderedBlock(
+ _ block: ResponseBlockSplitter.Block,
+ of response: String
+ ) -> NSAttributedString {
+ // Empty body included: a fence with nothing in it renders nothing.
+ // Sending it to the markdown pass instead produced an empty document,
+ // which the renderer turns into raw fallback, so a rebuild mid-answer
+ // put "```" back on screen where the streamed render had drawn nothing.
+ if let fence = block.fence {
+ return code(fence, of: response, attributes: renderer.streamingCodeAttributes()).text
+ }
+ let text = ResponseBlockSplitter.text(block.utf8Range, in: response)
+ let key = BlockKey(start: block.start, text: text)
+ if let cached = progressive.cache[key] { return cached }
+ let rendered = renderer.render(text, typesetsMath: true).attributedString
+ // A session cannot grow this without bound; block renders are already
+ // held by the storage, and dropping the whole table beats ageing it.
+ if progressive.cache.count >= 512 { progressive.cache.removeAll(keepingCapacity: true) }
+ progressive.cache[key] = rendered
+ return rendered
+ }
+
+ /// The open block, styled. Math stays as source here: a half-typed equation
+ /// cannot typeset, so asking per tick only produces a failed parse and a
+ /// log line, and the block is typeset once when it completes.
+ private func renderTail(
+ _ block: ResponseBlockSplitter.Block,
+ of response: String
+ ) -> NSAttributedString {
+ progressive.tailStart = block.start
+ if let fence = block.fence {
+ let drawn = code(
+ fence,
+ of: response,
+ attributes: renderer.streamingCodeAttributes())
+ progressive.fence = drawn.state
+ return drawn.text
+ }
+ progressive.fence = nil
+ let text = ResponseBlockSplitter.text(block.utf8Range, in: response)
+ let closed = TailAutoClose.close(text, typesetsMath: false)
+ return renderer.render(closed, typesetsMath: false).attributedString
+ }
+
+ private func code(
+ _ fence: ResponseBlockSplitter.Fence,
+ of response: String,
+ attributes: [NSAttributedString.Key: Any]
+ ) -> (text: NSAttributedString, state: FenceTail) {
+ var filter = CodeBodyFilter(indent: fence.indent)
+ var body = filter.append(ResponseBlockSplitter.text(
+ fence.bodyStart..<fence.bodyEnd,
+ in: response))
+ // Every code line is a paragraph; the last one needs its terminator or
+ // the container closes mid-line.
+ let synthetic = !filter.endsWithNewline
+ if synthetic { body.append("\n") }
+ return (
+ NSAttributedString(string: body, attributes: attributes),
+ FenceTail(
+ attributes: attributes,
+ bodyStart: fence.bodyStart,
+ bodyEnd: fence.bodyEnd,
+ filter: filter,
+ synthetic: synthetic))
+ }
+
+ private func growFence(
+ _ fence: ResponseBlockSplitter.Fence,
+ storage: NSMutableAttributedString,
+ response: String
+ ) -> ProgressiveUpdate {
+ guard var drawn = progressive.fence else { return ProgressiveUpdate(mutation: .none) }
+ guard fence.bodyEnd >= drawn.bodyEnd else {
+ // A closing fence line took bytes back out of the body. Redrawing
+ // costs one pass over a block that is about to stop growing.
+ let redrawn = code(fence, of: response, attributes: drawn.attributes)
+ progressive.fence = redrawn.state
+ let previous = tailRange
+ let before = (storage.string as NSString).substring(with: previous) as NSString
+ storage.replaceCharacters(in: previous, with: redrawn.text)
+ assistantRange.length = progressive.prefixLength + redrawn.text.length
+ return ProgressiveUpdate(
+ mutation: .tailReplaced,
+ replaced: ReplacedRange.differing(
+ previous: previous,
+ old: before,
+ new: redrawn.text.string as NSString)
+ ?? ReplacedRange(previous: previous, length: redrawn.text.length))
+ }
+ let raw = ResponseBlockSplitter.text(drawn.bodyEnd..<fence.bodyEnd, in: response)
+ guard !raw.isEmpty else { return ProgressiveUpdate(mutation: .none) }
+ var delta = drawn.filter.append(raw)
+ let synthetic = !drawn.filter.endsWithNewline
+ if synthetic { delta.append("\n") }
+ // The newline that goes away is the one the previous tick added, not
+ // the one this tick is about to.
+ let removal = NSRange(
+ location: assistantRange.upperBound - (drawn.synthetic ? 1 : 0),
+ length: drawn.synthetic ? 1 : 0)
+ drawn.bodyEnd = fence.bodyEnd
+ drawn.synthetic = synthetic
+ progressive.fence = drawn
+ guard !delta.isEmpty || removal.length > 0 else {
+ return ProgressiveUpdate(mutation: .none)
+ }
+ storage.replaceCharacters(
+ in: removal,
+ with: NSAttributedString(string: delta, attributes: drawn.attributes))
+ assistantRange.length += (delta as NSString).length - removal.length
+ return ProgressiveUpdate(mutation: .appended)
+ }
+
+ /// True when the drawn tail is already exactly what this newly completed
+ /// block renders to, so its bytes can stay in place.
+ private func keepsDrawnBytes(_ block: ResponseBlockSplitter.Block) -> Bool {
+ guard let fence = block.fence, let drawn = progressive.fence else { return false }
+ return fence.bodyStart == drawn.bodyStart && fence.bodyEnd == drawn.bodyEnd
+ }
+
+ private func trailingNewlines(in storage: NSMutableAttributedString) -> Int {
+ guard assistantRange.length > 0 else { return 0 }
+ let text = storage.string as NSString
+ var count = 0
+ var index = min(assistantRange.upperBound, text.length) - 1
+ while index >= assistantRange.location, count < 2,
+ text.character(at: index) == 10 {
+ count += 1
+ index -= 1
+ }
+ return count
+ }
+
+ private static func trailingNewlines(_ text: String, seed: Int) -> Int {
+ var count = 0
+ for character in text.reversed() {
+ guard character == "\n" else { return count }
+ count += 1
+ }
+ return count + seed
+ }
+
private static func userLabelAttributes() -> [NSAttributedString.Key: Any] {
labelAttributes(color: .secondaryLabelColor)
}
@@ -243,3 +909,9 @@ public final class InstructionTranscriptDocumentController {
"Processing your prompt" + String(repeating: ".", count: dotCount)
}
}
+
+extension Array {
+ fileprivate subscript(safe index: Int) -> Element? {
+ indices.contains(index) ? self[index] : nil
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/MathCommandNormalizer.swift b/Sources/TurboFieldfareApp/MacPresentation/MathCommandNormalizer.swift
new file mode 100644
index 00000000..7f10d9e2
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/MathCommandNormalizer.swift
@@ -0,0 +1,589 @@
+import Foundation
+
+/// Rewrites the LaTeX commands language models emit constantly but the pinned
+/// typesetter rejects, into forms it accepts. Every rule either preserves the
+/// meaning (delimiter spellings, environment aliases) or drops
+/// presentation-only decoration (`\boxed`, `\tag`, `\color`) rather than losing
+/// the whole equation to a raw-text fallback. A command the pinned revision
+/// already renders gets no rule, because rewriting it would trade real
+/// notation for an approximation; a command with no rule passes through and
+/// fails visibly instead of being silently mangled.
+enum MathCommandNormalizer {
+ /// A rewritten argument is rewritten in turn, so `\boxed{\boxed{...}}`
+ /// costs one stack frame per level. Real answers nest a handful deep;
+ /// thousands deep is a runaway generation, and overflowing the stack there
+ /// takes the app down. Past this depth the span is handed back untouched
+ /// and renders as raw text instead.
+ private static let maximumDepth = 256
+
+ static func normalize(_ latex: String) -> String {
+ var overflowed = false
+ let rewritten = rewrite(Array(latex), depth: 0, overflowed: &overflowed)
+ return overflowed ? latex : rewritten
+ }
+
+ private enum Rule {
+ /// Replace the command token itself; any arguments stay in the stream.
+ case token(String)
+ /// Consume `count` brace groups and emit the one at `keep`.
+ case keepArgument(keep: Int, count: Int)
+ /// Consume `count` brace groups and emit `replacement` instead.
+ case replaceArguments(String, count: Int)
+ /// `\underbrace{x}_{y}`: keep the group, drop the annotation script.
+ case keepArgumentDroppingScript
+ /// `\overset{a}{b}`: `{b}^{a}` when `a` is one token, otherwise `b`.
+ case script(String)
+ }
+
+ private static let rules: [String: Rule] = [
+ "boxed": .keepArgument(keep: 0, count: 1),
+ "fbox": .keepArgument(keep: 0, count: 1),
+ "mbox": .keepArgument(keep: 0, count: 1),
+ "cancel": .keepArgument(keep: 0, count: 1),
+ "xcancel": .keepArgument(keep: 0, count: 1),
+ "sout": .keepArgument(keep: 0, count: 1),
+ "textcolor": .keepArgument(keep: 1, count: 2),
+ "colorbox": .keepArgument(keep: 1, count: 2),
+ "color": .replaceArguments("", count: 1),
+ "tag": .replaceArguments("", count: 1),
+ "label": .replaceArguments("", count: 1),
+ "xrightarrow": .replaceArguments("\\rightarrow", count: 1),
+ "xleftarrow": .replaceArguments("\\leftarrow", count: 1),
+ "underbrace": .keepArgumentDroppingScript,
+ "overbrace": .keepArgumentDroppingScript,
+ "overset": .script("^"),
+ "underset": .script("_"),
+ "stackrel": .script("^"),
+ "nonumber": .token(""),
+ "middle": .token(""),
+ "hline": .token(""),
+ "lvert": .token("|"),
+ "rvert": .token("|"),
+ "lVert": .token("\\|"),
+ "rVert": .token("\\|"),
+ "dots": .token("\\ldots"),
+ "dotsc": .token("\\ldots"),
+ "therefore": .token("\\text{\u{2234}}"),
+ "because": .token("\\text{\u{2235}}"),
+ ":": .token("\\,"),
+ "bmod": .token("\\ \\mathrm{mod}\\ "),
+ "pmb": .token("\\mathbf"),
+ "mathscr": .token("\\mathcal"),
+ "coloneqq": .token(":="),
+ "eqqcolon": .token("=:"),
+ ]
+
+ /// Mathematical characters a model writes as Unicode instead of as
+ /// commands. The pinned typesetter rejects every one of these outright, so
+ /// an answer that says "x ≤ 5" lost the whole equation to raw text; the
+ /// command spellings render identically and cost nothing. A character the
+ /// typesetter already draws gets no entry, by the same rule the command
+ /// table follows.
+ static let symbols: [Character: String] = [
+ "α": #"\alpha"#,
+ "β": #"\beta"#,
+ "γ": #"\gamma"#,
+ "δ": #"\delta"#,
+ "ε": #"\epsilon"#,
+ "ϵ": #"\epsilon"#,
+ "ζ": #"\zeta"#,
+ "η": #"\eta"#,
+ "θ": #"\theta"#,
+ "ϑ": #"\theta"#,
+ "ι": #"\iota"#,
+ "κ": #"\kappa"#,
+ "λ": #"\lambda"#,
+ "μ": #"\mu"#,
+ "ν": #"\nu"#,
+ "ξ": #"\xi"#,
+ "π": #"\pi"#,
+ "ρ": #"\rho"#,
+ "σ": #"\sigma"#,
+ "ς": #"\sigma"#,
+ "τ": #"\tau"#,
+ "υ": #"\upsilon"#,
+ "φ": #"\phi"#,
+ "ϕ": #"\phi"#,
+ "χ": #"\chi"#,
+ "ψ": #"\psi"#,
+ "ω": #"\omega"#,
+ "Γ": #"\Gamma"#,
+ "Δ": #"\Delta"#,
+ "Θ": #"\Theta"#,
+ "Λ": #"\Lambda"#,
+ "Ξ": #"\Xi"#,
+ "Π": #"\Pi"#,
+ "Σ": #"\Sigma"#,
+ "Υ": #"\Upsilon"#,
+ "Φ": #"\Phi"#,
+ "Ψ": #"\Psi"#,
+ "Ω": #"\Omega"#,
+ "×": #"\times"#,
+ "÷": #"\div"#,
+ "±": #"\pm"#,
+ "∓": #"\mp"#,
+ "·": #"\cdot"#,
+ "⋅": #"\cdot"#,
+ "∗": #"\ast"#,
+ "≤": #"\le"#,
+ "≥": #"\ge"#,
+ "≠": #"\ne"#,
+ "≈": #"\approx"#,
+ "≡": #"\equiv"#,
+ "∼": #"\sim"#,
+ "∝": #"\propto"#,
+ "→": #"\to"#,
+ "←": #"\leftarrow"#,
+ "↔": #"\leftrightarrow"#,
+ "⇒": #"\Rightarrow"#,
+ "⇐": #"\Leftarrow"#,
+ "⇔": #"\Leftrightarrow"#,
+ "∞": #"\infty"#,
+ "∑": #"\sum"#,
+ "∏": #"\prod"#,
+ "∫": #"\int"#,
+ "∂": #"\partial"#,
+ "∇": #"\nabla"#,
+ "∠": #"\angle"#,
+ "∈": #"\in"#,
+ "∉": #"\notin"#,
+ "⊂": #"\subset"#,
+ "⊆": #"\subseteq"#,
+ "∪": #"\cup"#,
+ "∩": #"\cap"#,
+ "∅": #"\emptyset"#,
+ "∀": #"\forall"#,
+ "∃": #"\exists"#,
+ "−": #"-"#,
+ "…": #"\ldots"#,
+ "½": #"\frac{1}{2}"#,
+ "¼": #"\frac{1}{4}"#,
+ "¾": #"\frac{3}{4}"#,
+ "ℝ": #"\mathbb{R}"#,
+ "ℕ": #"\mathbb{N}"#,
+ "ℤ": #"\mathbb{Z}"#,
+ "ℚ": #"\mathbb{Q}"#,
+ "ℂ": #"\mathbb{C}"#,
+ // The pinned build drops every one of these without an error, so an
+ // answer that used them typeset with the operator simply missing.
+ "%": "\\%",
+ "#": "\\#",
+ "$": "\\$",
+ "°": #"^{\circ}"#,
+ "¬": #"\neg"#,
+ "∨": #"\lor"#,
+ "∧": #"\land"#,
+ "∘": #"\circ"#,
+ "⊕": #"\oplus"#,
+ "⊗": #"\otimes"#,
+ "≪": #"\ll"#,
+ "≫": #"\gg"#,
+ "⟨": #"\langle"#,
+ "⟩": #"\rangle"#,
+ "⌊": #"\lfloor"#,
+ "⌋": #"\rfloor"#,
+ "⌈": #"\lceil"#,
+ "⌉": #"\rceil"#,
+ "ℓ": #"\ell"#,
+ "ℏ": #"\hbar"#,
+ "ℵ": #"\aleph"#,
+ "ℜ": #"\Re"#,
+ "ℑ": #"\Im"#,
+ "∮": #"\oint"#,
+ "∬": #"\iint"#,
+ "⋯": #"\cdots"#,
+ "⋮": #"\vdots"#,
+ "⋱": #"\ddots"#,
+ "↦": #"\mapsto"#,
+ "↑": #"\uparrow"#,
+ "↓": #"\downarrow"#,
+ "∖": #"\setminus"#,
+ "∣": #"\mid"#,
+ "∥": #"\parallel"#,
+ "⊥": #"\perp"#,
+ "⊤": #"\top"#,
+ "≅": #"\cong"#,
+ "≃": #"\simeq"#,
+ "⊃": #"\supset"#,
+ "⊇": #"\supseteq"#,
+ // U+2206 and U+00B5 and U+03F1 are the look-alikes of characters the
+ // table already carries, and the build treats them as different.
+ "∆": #"\Delta"#,
+ "µ": #"\mu"#,
+ "ϱ": #"\rho"#,
+ "□": #"\square"#,
+ "∴": "\\text{\u{2234}}",
+ "∵": "\\text{\u{2235}}",
+ ]
+
+ /// Spacing the build drops. These are not in `symbols` because a lone
+ /// space produces a zero-size image, which the conformer rejects: they are
+ /// pinned in context instead.
+ static let spacing: [Character: String] = [
+ "~": #"\ "#,
+ "\u{00A0}": #"\ "#,
+ "\u{2002}": #"\ "#,
+ "\u{2003}": #"\ "#,
+ "\u{2009}": #"\,"#,
+ ]
+
+ /// Invisible characters a model pastes in from formatted text. They mean
+ /// nothing in an equation and the build drops them anyway. A zero-width
+ /// joiner or non-joiner is not here: Unicode grapheme breaking keeps those
+ /// inside the character before them, so they never arrive on their own and
+ /// the build draws the grapheme they made.
+ static let removed: Set<Character> = ["\u{200B}", "\u{FEFF}"]
+
+ /// Prime marks, and how many primes each one is.
+ static let primes: [Character: Int] = ["\u{2032}": 1, "\u{2019}": 1, "\u{2033}": 2, "\u{2034}": 3]
+
+ /// Environments the pinned typesetter rejects, mapped onto the closest one
+ /// it renders. `aligned` is the workhorse: it accepts `&` and `\\` rows,
+ /// which is all the rejected alignment environments need.
+ private static let environments: [String: String] = [
+ "align": "aligned",
+ "align*": "aligned",
+ "aligned*": "aligned",
+ "alignat": "aligned",
+ "alignat*": "aligned",
+ "gather*": "aligned",
+ "equation": "aligned",
+ "equation*": "aligned",
+ "array": "matrix",
+ "rcases": "cases",
+ ]
+
+ /// Environments whose `\begin` carries an extra brace argument that the
+ /// replacement does not take: `array`'s column spec, `alignat`'s count.
+ private static let environmentsWithArgument: Set<String> = [
+ "array", "alignat", "alignat*",
+ ]
+
+ private static func rewrite(
+ _ chars: [Character],
+ depth: Int,
+ overflowed: inout Bool
+ ) -> String {
+ guard depth <= maximumDepth else {
+ overflowed = true
+ return ""
+ }
+ var out = ""
+ var index = 0
+ while index < chars.count {
+ guard chars[index] == "\\", index + 1 < chars.count else {
+ index = appendLiteral(
+ chars,
+ at: index,
+ depth: depth,
+ overflowed: &overflowed,
+ out: &out)
+ continue
+ }
+ let command = name(chars, after: index)
+ if command.name == "begin" || command.name == "end" {
+ if let rewritten = environment(chars, command: command, out: &out) {
+ index = rewritten
+ continue
+ }
+ }
+ guard let rule = rules[command.name] else {
+ out.append(contentsOf: chars[index..<command.end])
+ index = command.end
+ continue
+ }
+ index = apply(
+ rule,
+ chars: chars,
+ command: command,
+ start: index,
+ depth: depth,
+ overflowed: &overflowed,
+ out: &out)
+ }
+ return out
+ }
+
+ private static func appendLiteral(
+ _ chars: [Character],
+ at index: Int,
+ depth: Int,
+ overflowed: inout Bool,
+ out: inout String
+ ) -> Int {
+ let character = chars[index]
+ if removed.contains(character) { return index + 1 }
+ if let space = spacing[character] {
+ out += space
+ return index + 1
+ }
+ if primes[character] != nil {
+ var count = 0
+ var cursor = index
+ while cursor < chars.count, let width = primes[chars[cursor]] {
+ count += width
+ cursor += 1
+ }
+ out += "^{" + String(repeating: #"\prime"#, count: count) + "}"
+ return cursor
+ }
+ if character == "\u{221A}" {
+ return appendRadical(
+ chars,
+ at: index,
+ depth: depth,
+ overflowed: &overflowed,
+ out: &out)
+ }
+ return appendSymbol(chars, at: index, out: &out)
+ }
+
+ /// `\u{221A}` is a character, not a command: the build has no atom for it,
+ /// so `\u{221A}2` typeset pixel-identical to `2`. What follows it is the
+ /// radicand — a group, a parenthesised expression, a run of digits, one
+ /// letter, or one command.
+ private static func appendRadical(
+ _ chars: [Character],
+ at index: Int,
+ depth: Int,
+ overflowed: inout Bool,
+ out: inout String
+ ) -> Int {
+ var cursor = index + 1
+ while cursor < chars.count, chars[cursor] == " " { cursor += 1 }
+ guard cursor < chars.count else {
+ out += #"\sqrt{}"#
+ return cursor
+ }
+ if chars[cursor] == "{", let group = arguments(chars, from: cursor, count: 1) {
+ out += #"\sqrt{"# + rewrite(group.values[0], depth: depth + 1, overflowed: &overflowed) + "}"
+ return group.end
+ }
+ if chars[cursor] == "(", let close = closingParenthesis(chars, from: cursor) {
+ let inner = Array(chars[(cursor + 1)..<close])
+ out += #"\sqrt{"# + rewrite(inner, depth: depth + 1, overflowed: &overflowed) + "}"
+ return close + 1
+ }
+ if chars[cursor].isNumber {
+ var end = cursor
+ while end < chars.count, chars[end].isNumber || chars[end] == "." { end += 1 }
+ out += #"\sqrt{"# + String(chars[cursor..<end]) + "}"
+ return end
+ }
+ if chars[cursor].isLetter {
+ out += #"\sqrt{"# + String(chars[cursor]) + "}"
+ return cursor + 1
+ }
+ if chars[cursor] == "\\" {
+ let command = name(chars, after: cursor)
+ out += #"\sqrt{"# + String(chars[cursor..<command.end]) + "}"
+ return command.end
+ }
+ out += #"\sqrt{}"#
+ return cursor
+ }
+
+ private static func closingParenthesis(_ chars: [Character], from start: Int) -> Int? {
+ var depth = 0
+ var index = start
+ while index < chars.count {
+ if chars[index] == "\\" {
+ index += 2
+ continue
+ }
+ if chars[index] == "(" { depth += 1 }
+ if chars[index] == ")" {
+ depth -= 1
+ if depth == 0 { return index }
+ }
+ index += 1
+ }
+ return nil
+ }
+
+ private static func appendSymbol(
+ _ chars: [Character],
+ at index: Int,
+ out: inout String
+ ) -> Int {
+ guard let replacement = symbols[chars[index]] else {
+ out.append(chars[index])
+ return index + 1
+ }
+ out += replacement
+ // A command may not run into the letter after it: `α` before `b` would
+ // otherwise spell the unknown command `\alphab`.
+ if replacement.last?.isLetter == true,
+ index + 1 < chars.count, chars[index + 1].isLetter {
+ out.append(" ")
+ }
+ return index + 1
+ }
+
+ private struct Command {
+ let name: String
+ /// Index just past the command token.
+ let end: Int
+ }
+
+ private static func name(_ chars: [Character], after backslash: Int) -> Command {
+ var index = backslash + 1
+ guard index < chars.count else { return Command(name: "", end: index) }
+ guard chars[index].isLetter else {
+ return Command(name: String(chars[index]), end: index + 1)
+ }
+ while index < chars.count, chars[index].isLetter { index += 1 }
+ var text = String(chars[(backslash + 1)..<index])
+ if index < chars.count, chars[index] == "*" {
+ text += "*"
+ index += 1
+ }
+ return Command(name: text, end: index)
+ }
+
+ private static func apply(
+ _ rule: Rule,
+ chars: [Character],
+ command: Command,
+ start: Int,
+ depth: Int,
+ overflowed: inout Bool,
+ out: inout String
+ ) -> Int {
+ switch rule {
+ case .token(let replacement):
+ out += replacement
+ return command.end
+ case .keepArgument(let keep, let count):
+ guard let groups = arguments(chars, from: command.end, count: count) else {
+ return verbatim(chars, command: command, start: start, out: &out)
+ }
+ out += rewrite(groups.values[keep], depth: depth + 1, overflowed: &overflowed)
+ return groups.end
+ case .replaceArguments(let replacement, let count):
+ guard let groups = arguments(chars, from: command.end, count: count) else {
+ return verbatim(chars, command: command, start: start, out: &out)
+ }
+ out += replacement
+ return groups.end
+ case .keepArgumentDroppingScript:
+ guard let groups = arguments(chars, from: command.end, count: 1) else {
+ return verbatim(chars, command: command, start: start, out: &out)
+ }
+ out += rewrite(groups.values[0], depth: depth + 1, overflowed: &overflowed)
+ return skippingScript(chars, from: groups.end)
+ case .script(let operatorCharacter):
+ guard let groups = arguments(chars, from: command.end, count: 2) else {
+ return verbatim(chars, command: command, start: start, out: &out)
+ }
+ let annotation = rewrite(
+ groups.values[0], depth: depth + 1, overflowed: &overflowed)
+ let base = rewrite(groups.values[1], depth: depth + 1, overflowed: &overflowed)
+ guard isSingleToken(annotation) else {
+ out += "{" + base + "}"
+ return groups.end
+ }
+ out += "{" + base + "}" + operatorCharacter + "{" + annotation + "}"
+ return groups.end
+ }
+ }
+
+ private static func verbatim(
+ _ chars: [Character],
+ command: Command,
+ start: Int,
+ out: inout String
+ ) -> Int {
+ out.append(contentsOf: chars[start..<command.end])
+ return command.end
+ }
+
+ private static func environment(
+ _ chars: [Character],
+ command: Command,
+ out: inout String
+ ) -> Int? {
+ guard let groups = arguments(chars, from: command.end, count: 1) else { return nil }
+ let raw = String(groups.values[0]).trimmingCharacters(in: .whitespaces)
+ guard let mapped = environments[raw] else { return nil }
+ out += "\\" + command.name + "{" + mapped + "}"
+ guard command.name == "begin", environmentsWithArgument.contains(raw) else {
+ return groups.end
+ }
+ guard let spec = arguments(chars, from: groups.end, count: 1) else { return groups.end }
+ return spec.end
+ }
+
+ private struct Arguments {
+ let values: [[Character]]
+ /// Index just past the last consumed group.
+ let end: Int
+ }
+
+ private static func arguments(
+ _ chars: [Character],
+ from start: Int,
+ count: Int
+ ) -> Arguments? {
+ var values: [[Character]] = []
+ var index = start
+ for _ in 0..<count {
+ while index < chars.count, chars[index] == " " { index += 1 }
+ guard index < chars.count, chars[index] == "{" else { return nil }
+ var depth = 0
+ var cursor = index
+ var closing: Int?
+ while cursor < chars.count {
+ if chars[cursor] == "\\" {
+ cursor += 2
+ continue
+ }
+ if chars[cursor] == "{" { depth += 1 }
+ if chars[cursor] == "}" {
+ depth -= 1
+ if depth == 0 {
+ closing = cursor
+ break
+ }
+ }
+ cursor += 1
+ }
+ guard let closing else { return nil }
+ values.append(Array(chars[(index + 1)..<closing]))
+ index = closing + 1
+ }
+ return Arguments(values: values, end: index)
+ }
+
+ /// Drops the `_{...}` or `^{...}` annotation that follows a brace command
+ /// whose decoration was removed, so the annotation does not reattach to
+ /// the surviving base and change what the equation says.
+ private static func skippingScript(_ chars: [Character], from start: Int) -> Int {
+ guard start < chars.count, chars[start] == "_" || chars[start] == "^" else {
+ return start
+ }
+ if let group = arguments(chars, from: start + 1, count: 1) { return group.end }
+ let next = start + 1
+ guard next < chars.count else { return start }
+ guard chars[next] == "\\" else { return next + 1 }
+ // The unbraced form `_\text{total}` is one script token: the command
+ // and the group it takes. Dropping only the command left the group
+ // behind, so `\underbrace{a+b}_\text{total}` became `a+b{total}` and
+ // typeset as "a+btotal". A group separated by a space is not the
+ // command's argument and stays part of the equation.
+ var end = name(chars, after: next).end
+ while end < chars.count, chars[end] == "{",
+ let group = arguments(chars, from: end, count: 1) {
+ end = group.end
+ }
+ return end
+ }
+
+ private static func isSingleToken(_ text: String) -> Bool {
+ let trimmed = text.trimmingCharacters(in: .whitespaces)
+ if trimmed.count == 1 { return true }
+ guard trimmed.hasPrefix("\\") else { return false }
+ let body = trimmed.dropFirst()
+ return !body.isEmpty && body.allSatisfy { $0.isLetter }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/MathSpanDetector.swift b/Sources/TurboFieldfareApp/MacPresentation/MathSpanDetector.swift
new file mode 100644
index 00000000..bbf635fb
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/MathSpanDetector.swift
@@ -0,0 +1,901 @@
+import Foundation
+
+struct MathSpan: Equatable {
+ enum Mode: Equatable {
+ case inline
+ case display
+ }
+
+ /// Character offsets into the string the span was found in.
+ let range: Range<Int>
+ let mode: Mode
+ /// The exact source text, delimiters included.
+ let source: String
+ /// What goes to the typesetter: the text between the delimiters.
+ let latex: String
+ /// A partial equation from an interrupted generation. It is substituted
+ /// like any other span so the markdown pass cannot eat its backslashes,
+ /// then restored verbatim instead of typeset.
+ let isLiteralProtect: Bool
+}
+
+/// Finds the math in a model answer before the markdown parser gets to mangle
+/// it. Every rule here exists because a real answer broke without it: currency
+/// pairs, shell variables in prose, `$` inside link destinations, `\$` inside
+/// an equation, and code regions that must never be searched at all.
+enum MathSpanDetector {
+ static let openSentinel: Character = "\u{E000}"
+ static let closeSentinel: Character = "\u{E001}"
+
+ struct Substitution: Equatable {
+ /// The source with each span replaced by its indexed sentinel.
+ let working: String
+ let spans: [MathSpan]
+ }
+
+ /// Environments KaTeX auto-renders at block level. Anything outside this
+ /// set is left to the markdown pass, which is the current behaviour.
+ private static let displayEnvironments: Set<String> = [
+ "equation", "equation*",
+ "align", "align*",
+ "gather", "gather*",
+ "alignat", "alignat*",
+ "CD",
+ ]
+
+ /// Model output cannot be allowed to alias a placeholder, so the private
+ /// use characters the substitution reserves are removed up front.
+ static func strippingSentinels(_ source: String) -> String {
+ guard source.contains(openSentinel) || source.contains(closeSentinel) else {
+ return source
+ }
+ return String(source.filter { $0 != openSentinel && $0 != closeSentinel })
+ }
+
+ static func substitute(_ source: String) -> Substitution {
+ let stripped = strippingSentinels(source)
+ let spans = self.spans(in: stripped)
+ guard !spans.isEmpty else { return Substitution(working: stripped, spans: spans) }
+
+ let chars = scanUnits(stripped)
+ var working = ""
+ var cursor = 0
+ for (index, span) in spans.enumerated() {
+ working.append(contentsOf: chars[cursor..<span.range.lowerBound])
+ let sentinel = "\(openSentinel)\(index)\(closeSentinel)"
+ // Two display blocks separated by a single newline parse into one
+ // paragraph, with the break collapsing to a space. Promoting a
+ // standalone block to its own paragraph is what keeps consecutive
+ // equations from sharing a line.
+ if span.mode == .display, isAloneOnItsLine(span, chars: chars) {
+ working += "\n\n" + sentinel + "\n\n"
+ } else {
+ working += sentinel
+ }
+ cursor = span.range.upperBound
+ }
+ working.append(contentsOf: chars[cursor...])
+ return Substitution(working: working, spans: spans)
+ }
+
+ static func spans(in source: String) -> [MathSpan] {
+ let chars = scanUnits(source)
+ return spans(chars, masked: codeMask(chars), escaped: escapeMask(chars))
+ }
+
+ /// What the streaming tail pass must not treat as markdown.
+ ///
+ /// The tail is auto-closed with the math kept as source, so nothing masked
+ /// `$...$` and every `_` in a subscript and `*` in an equation read as an
+ /// emphasis marker: `The value $x_{1}$ is small` came back as
+ /// `The value $x_{1}$ is small_`.
+ struct TailProtection {
+ /// The tail split the way the detector scans it, CRLF apart.
+ let units: [Character]
+ /// Code regions and completed equations. A span the model was cut off
+ /// in the middle of is deliberately live: completing it is the tail
+ /// pass's own job.
+ let masked: [Bool]
+ /// The last inline opener on the last line that nothing closes.
+ /// Everything from there on is inside an equation still being written.
+ let openInlineDollar: Int?
+ }
+
+ static func tailProtection(_ source: String) -> TailProtection {
+ let units = scanUnits(source)
+ var masked = codeMask(units)
+ let escaped = escapeMask(units)
+ for span in spans(units, masked: masked, escaped: escaped)
+ where !span.isLiteralProtect {
+ for index in span.range { masked[index] = true }
+ }
+ return TailProtection(
+ units: units,
+ masked: masked,
+ openInlineDollar: openInlineDollar(units, masked: masked, escaped: escaped))
+ }
+
+ /// A digit-led opener is currency — `costs $20 and *very goo` still has
+ /// live emphasis after it — and a single-dollar span cannot cross a line,
+ /// so only the last line can hold one that is still open.
+ private static func openInlineDollar(
+ _ units: [Character],
+ masked: [Bool],
+ escaped: [Bool]
+ ) -> Int? {
+ var lineStart = units.count
+ while lineStart > 0, units[lineStart - 1] != "\n" { lineStart -= 1 }
+ var opener: Int?
+ for index in lineStart..<units.count {
+ guard units[index] == "$", !masked[index], !escaped[index] else { continue }
+ let after = index + 1
+ guard after < units.count, !isSpace(units[after]), units[after] != "$",
+ !isASCIIDigit(units[after]) else {
+ continue
+ }
+ if index > 0 {
+ let before = units[index - 1]
+ guard !isASCIIAlphanumeric(before), before != "/" else { continue }
+ }
+ opener = index
+ }
+ return opener
+ }
+
+ private static func spans(
+ _ chars: [Character],
+ masked: [Bool],
+ escaped: [Bool]
+ ) -> [MathSpan] {
+ var found: [MathSpan] = []
+ var index = 0
+ while index < chars.count {
+ guard !masked[index] else {
+ index += 1
+ continue
+ }
+ if chars[index] == "$", !escaped[index] {
+ index = scanDollar(
+ chars, masked: masked, escaped: escaped, at: index, into: &found)
+ continue
+ }
+ if chars[index] == "\\", !escaped[index] {
+ index = scanBackslash(
+ chars, masked: masked, escaped: escaped, at: index, into: &found)
+ continue
+ }
+ index += 1
+ }
+ return found
+ }
+
+ // MARK: - Dollar forms
+
+ private static func scanDollar(
+ _ chars: [Character],
+ masked: [Bool],
+ escaped: [Bool],
+ at start: Int,
+ into found: inout [MathSpan]
+ ) -> Int {
+ var run = 0
+ while start + run < chars.count, chars[start + run] == "$", !masked[start + run] {
+ run += 1
+ }
+ // `$$$` is emphasis on a price, a rating, or a typo — never a
+ // delimiter. Accepting it made `It costs $$$ a lot.` an opener and
+ // shielded everything under it as raw source.
+ guard run <= 2 else { return start + run }
+ guard run == 2 else {
+ switch inlineDollarClose(
+ chars, masked: masked, escaped: escaped, opener: start) {
+ case .closed(let close):
+ found.append(span(chars, from: start, to: close + 1, delimiter: 1, mode: .inline))
+ return close + 1
+ case .exhausted(let resume):
+ return resume
+ }
+ }
+
+ let contentStart = start + 2
+ // A blank line ends a display block (pandoc). It bounds both passes:
+ // nothing past one can close this opener, and an opener nothing closes
+ // shields only as far as the boundary.
+ let blockEnd = displayBlockEnd(chars, from: contentStart)
+ guard let close = displayDollarClose(
+ chars,
+ masked: masked,
+ escaped: escaped,
+ from: contentStart,
+ to: blockEnd) else {
+ guard let end = literalProtectEnd(
+ chars,
+ opener: start,
+ from: contentStart,
+ to: blockEnd) else {
+ return contentStart
+ }
+ found.append(span(
+ chars,
+ from: start,
+ to: end,
+ delimiter: 2,
+ mode: .display,
+ literalProtect: true))
+ return end
+ }
+ guard close > contentStart else { return contentStart }
+ found.append(span(chars, from: start, to: close + 2, delimiter: 2, mode: .display))
+ return close + 2
+ }
+
+ /// What the inline pass found, and where the next opener may start.
+ ///
+ /// Reporting how far a failed scan looked is what keeps the pass linear.
+ /// The closer test depends only on the candidate's own neighbours, so a
+ /// `$` that cannot close for this opener cannot close for any opener
+ /// between them either, and the region is walked once per message instead
+ /// of once per dollar. 180 KB of `$a ` took 16.1 s the other way.
+ private enum InlineClose {
+ case closed(Int)
+ case exhausted(resumeAt: Int)
+ }
+
+ /// The pandoc `tex_math_dollars` rules plus the adjacency extensions that
+ /// reject `x=$a$b`, `$FOO/bar$BAZ`, and `https://ex.com/$a/$b`. Pandoc
+ /// forbids only a digit after the closer; ASCII letters are included here
+ /// because shell and URL text is the common false positive, not prose.
+ /// `isLetter` and `isNumber` are Unicode-wide, so `质量为$m$的物体` read as
+ /// one word and its equation stayed raw.
+ private static func inlineDollarClose(
+ _ chars: [Character],
+ masked: [Bool],
+ escaped: [Bool],
+ opener: Int
+ ) -> InlineClose {
+ let after = opener + 1
+ guard after < chars.count, !isSpace(chars[after]), chars[after] != "$" else {
+ return .exhausted(resumeAt: after)
+ }
+ if opener > 0 {
+ let before = chars[opener - 1]
+ guard !isASCIIAlphanumeric(before), before != "/" else {
+ return .exhausted(resumeAt: after)
+ }
+ }
+ var index = after
+ while index < chars.count {
+ let character = chars[index]
+ // Both stops end the region a closer could live in, so the next
+ // opener starts here rather than one character past this one.
+ if character == "\n" || masked[index] { return .exhausted(resumeAt: index) }
+ guard character == "$", !escaped[index] else {
+ index += 1
+ continue
+ }
+ // A `$` after whitespace cannot close anything, and walking past it
+ // let a candidate swallow the closer of the span after it:
+ // `It costs $5 (or $10 for two). The formula $E=mc^2$ applies.`
+ // came back as one span from the `$5` to the equation's closer.
+ // The refused closer is where the next candidate starts.
+ if isSpace(chars[index - 1]) { return .exhausted(resumeAt: index) }
+ let next = index + 1 < chars.count ? chars[index + 1] : nil
+ guard !isASCIIAlphanumeric(next) else {
+ index += 1
+ continue
+ }
+ guard closesAsMath(chars, opener: opener, closer: index) else {
+ return .exhausted(resumeAt: after)
+ }
+ return .closed(index)
+ }
+ return .exhausted(resumeAt: chars.count)
+ }
+
+ /// A candidate opened on a digit and spanning whitespace is two amounts in
+ /// a sentence — `$50 item$` — unless its content actually reads as math.
+ private static func closesAsMath(
+ _ chars: [Character],
+ opener: Int,
+ closer: Int
+ ) -> Bool {
+ let content = (opener + 1)..<closer
+ guard isASCIIDigit(chars[opener + 1]),
+ content.contains(where: { chars[$0] == " " || chars[$0] == "\t" }) else {
+ return true
+ }
+ return looksLikeMath(String(chars[content]))
+ }
+
+ private static func displayDollarClose(
+ _ chars: [Character],
+ masked: [Bool],
+ escaped: [Bool],
+ from start: Int,
+ to limit: Int
+ ) -> Int? {
+ var index = start
+ while index + 1 < limit {
+ if chars[index] == "$", chars[index + 1] == "$",
+ !masked[index], !masked[index + 1],
+ !escaped[index] {
+ return index
+ }
+ index += 1
+ }
+ return nil
+ }
+
+ // MARK: - Backslash forms
+
+ private static func scanBackslash(
+ _ chars: [Character],
+ masked: [Bool],
+ escaped: [Bool],
+ at start: Int,
+ into found: inout [MathSpan]
+ ) -> Int {
+ guard start + 1 < chars.count else { return start + 1 }
+ switch chars[start + 1] {
+ case "[":
+ let blockEnd = displayBlockEnd(chars, from: start + 2)
+ guard let close = closingPair(
+ chars,
+ masked: masked,
+ escaped: escaped,
+ from: start + 2,
+ to: blockEnd,
+ closer: "]") else {
+ guard let end = literalProtectEnd(
+ chars,
+ opener: start,
+ from: start + 2,
+ to: blockEnd) else {
+ return start + 2
+ }
+ found.append(span(
+ chars,
+ from: start,
+ to: end,
+ delimiter: 2,
+ mode: .display,
+ literalProtect: true))
+ return end
+ }
+ // Prose that happens to bracket a list — `\[1, 2, 3\]`, an
+ // escaped `\[optional\]` flag — is not math. The `\(` branch has
+ // required a command or an operator all along; this one accepted
+ // anything and fed the words to a typesetter that failed on them.
+ guard looksLikeMath(String(chars[(start + 2)..<close]))
+ || ownsItsLine(chars, from: start, to: close + 2) else {
+ return start + 2
+ }
+ found.append(span(chars, from: start, to: close + 2, delimiter: 2, mode: .display))
+ return close + 2
+ case "(":
+ guard let close = closingPair(
+ chars,
+ masked: masked,
+ escaped: escaped,
+ from: start + 2,
+ to: displayBlockEnd(chars, from: start + 2),
+ closer: ")") else {
+ return start + 2
+ }
+ // Prose that happens to bracket a word — a regex group, a Swift
+ // escape, `\(count\)` — is not math. Requiring a command or an
+ // operator is what separates the two.
+ guard looksLikeMath(String(chars[(start + 2)..<close])) else {
+ return start + 2
+ }
+ found.append(span(chars, from: start, to: close + 2, delimiter: 2, mode: .inline))
+ return close + 2
+ default:
+ guard isLineStart(chars, before: start),
+ let environment = environmentName(chars, at: start, keyword: "begin"),
+ displayEnvironments.contains(environment.name),
+ let close = environmentEnd(
+ chars,
+ masked: masked,
+ from: environment.end,
+ name: environment.name) else {
+ return start + 1
+ }
+ let source = String(chars[start..<close])
+ found.append(MathSpan(
+ range: start..<close,
+ mode: .display,
+ source: source,
+ latex: source,
+ isLiteralProtect: false))
+ return close
+ }
+ }
+
+ private static func closingPair(
+ _ chars: [Character],
+ masked: [Bool],
+ escaped: [Bool],
+ from start: Int,
+ to limit: Int,
+ closer: Character
+ ) -> Int? {
+ var index = start
+ while index + 1 < limit {
+ if chars[index] == "\\", chars[index + 1] == closer,
+ !masked[index], !escaped[index] {
+ return index
+ }
+ index += 1
+ }
+ return nil
+ }
+
+ private struct EnvironmentKeyword {
+ let name: String
+ /// Index just past `\begin{name}`.
+ let end: Int
+ }
+
+ private static func environmentName(
+ _ chars: [Character],
+ at start: Int,
+ keyword: String
+ ) -> EnvironmentKeyword? {
+ var index = start + 1
+ for character in keyword {
+ guard index < chars.count, chars[index] == character else { return nil }
+ index += 1
+ }
+ guard index < chars.count, chars[index] == "{" else { return nil }
+ index += 1
+ var name = ""
+ while index < chars.count, chars[index] != "}" {
+ name.append(chars[index])
+ index += 1
+ }
+ guard index < chars.count else { return nil }
+ return EnvironmentKeyword(name: name, end: index + 1)
+ }
+
+ /// A blank line is the display block's boundary here too. Without it a
+ /// `\begin{align}` in one block paired with an `\end{align}` in another,
+ /// which the whole-message render resolved and the per-block finalize
+ /// cannot.
+ private static func environmentEnd(
+ _ chars: [Character],
+ masked: [Bool],
+ from start: Int,
+ name: String
+ ) -> Int? {
+ let limit = displayBlockEnd(chars, from: start)
+ var index = start
+ while index < limit {
+ if chars[index] == "\\", !masked[index],
+ let keyword = environmentName(chars, at: index, keyword: "end"),
+ keyword.name == name {
+ return keyword.end
+ }
+ index += 1
+ }
+ return nil
+ }
+
+ // MARK: - Shared helpers
+
+ /// Swift reads CRLF as a single `Character`, which is neither `\n` nor
+ /// `\r` to any rule below: a CRLF answer never ended a line, so its
+ /// fences went unmasked, its blank lines went unseen, and a currency
+ /// dollar paired with one on the next line. CRLF is the only grapheme
+ /// cluster that can contain a line break, so splitting it is enough;
+ /// every other cluster stays whole and the offsets still land on
+ /// boundaries of the source.
+ private static func scanUnits(_ source: String) -> [Character] {
+ guard source.contains("\r\n") else { return Array(source) }
+ var units: [Character] = []
+ units.reserveCapacity(source.unicodeScalars.count)
+ for character in source {
+ guard character == "\r\n" else {
+ units.append(character)
+ continue
+ }
+ units.append("\r")
+ units.append("\n")
+ }
+ return units
+ }
+
+ private static func span(
+ _ chars: [Character],
+ from start: Int,
+ to end: Int,
+ delimiter: Int,
+ mode: MathSpan.Mode,
+ literalProtect: Bool = false
+ ) -> MathSpan {
+ let source = String(chars[start..<end])
+ let latex = literalProtect
+ ? source
+ : String(chars[(start + delimiter)..<(end - delimiter)])
+ return MathSpan(
+ range: start..<end,
+ mode: mode,
+ source: source,
+ latex: latex,
+ isLiteralProtect: literalProtect)
+ }
+
+ /// An unterminated display opener shields everything up to the end of its
+ /// block, minus trailing newlines so the shielded text does not swallow
+ /// the paragraph break after it.
+ ///
+ /// Two conditions earn that. The opener starts its own line, because a
+ /// mid-sentence `$$` is a rating or a price — `Rated $$ on the price
+ /// scale.` — not a generation cut off mid-equation. And what follows reads
+ /// as TeX, because `$$x = 1` in prose is a sentence and shielding it shows
+ /// every heading, list and table under it as raw source.
+ private static func literalProtectEnd(
+ _ chars: [Character],
+ opener: Int,
+ from start: Int,
+ to limit: Int
+ ) -> Int? {
+ var end = limit
+ while end > start, chars[end - 1] == "\n" || chars[end - 1] == "\r" { end -= 1 }
+ guard end > start, chars[start..<end].contains(where: { !isSpace($0) }) else {
+ return nil
+ }
+ guard isLineStart(chars, before: opener), hasTeXContent(chars, in: start..<end) else {
+ return nil
+ }
+ return end
+ }
+
+ /// Where the display block that starts at `start` ends: the first blank
+ /// line, or the end of the message.
+ private static func displayBlockEnd(_ chars: [Character], from start: Int) -> Int {
+ var newline: Int?
+ for index in start..<chars.count {
+ let character = chars[index]
+ if character == "\n" {
+ if let first = newline { return first }
+ newline = index
+ continue
+ }
+ if character == " " || character == "\t" || character == "\r" { continue }
+ newline = nil
+ }
+ return chars.count
+ }
+
+ private static func hasTeXContent(_ chars: [Character], in range: Range<Int>) -> Bool {
+ var previous: Character?
+ for index in range {
+ let character = chars[index]
+ if previous == "\\", character.isLetter || character == "{" || character == "\\" {
+ return true
+ }
+ if character == "^" || character == "_" || character == "{" { return true }
+ previous = character
+ }
+ return false
+ }
+
+ /// The span is the whole line, indentation aside: what makes a delimiter
+ /// pair a display block even when its content is a bare list of numbers.
+ private static func ownsItsLine(_ chars: [Character], from start: Int, to end: Int) -> Bool {
+ guard isLineStart(chars, before: start) else { return false }
+ var cursor = end
+ while cursor < chars.count, chars[cursor] != "\n" {
+ guard isSpace(chars[cursor]) else { return false }
+ cursor += 1
+ }
+ return true
+ }
+
+ private static func looksLikeMath(_ content: String) -> Bool {
+ var previous: Character?
+ for character in content {
+ if previous == "\\", character.isLetter { return true }
+ if "^_=<>+-/*".contains(character) { return true }
+ previous = character
+ }
+ return false
+ }
+
+ /// Which characters a backslash run has escaped, in one forward pass.
+ /// Counting the run backwards per candidate is quadratic in a run of
+ /// backslashes: 80 KB of them measured 86.5 s, re-run on the open block on
+ /// every streaming tick.
+ private static func escapeMask(_ chars: [Character]) -> [Bool] {
+ var escaped = [Bool](repeating: false, count: chars.count)
+ var backslashes = 0
+ for index in chars.indices {
+ escaped[index] = !backslashes.isMultiple(of: 2)
+ backslashes = chars[index] == "\\" ? backslashes + 1 : 0
+ }
+ return escaped
+ }
+
+ private static func isASCIIAlphanumeric(_ character: Character?) -> Bool {
+ guard let value = character?.asciiValue else { return false }
+ return (value >= UInt8(ascii: "0") && value <= UInt8(ascii: "9"))
+ || (value >= UInt8(ascii: "A") && value <= UInt8(ascii: "Z"))
+ || (value >= UInt8(ascii: "a") && value <= UInt8(ascii: "z"))
+ }
+
+ private static func isASCIIDigit(_ character: Character) -> Bool {
+ guard let value = character.asciiValue else { return false }
+ return value >= UInt8(ascii: "0") && value <= UInt8(ascii: "9")
+ }
+
+ private static func isSpace(_ character: Character) -> Bool {
+ character == " " || character == "\t" || character == "\n" || character == "\r"
+ }
+
+ private static func isLineStart(_ chars: [Character], before index: Int) -> Bool {
+ var cursor = index - 1
+ while cursor >= 0 {
+ if chars[cursor] == "\n" { return true }
+ guard chars[cursor] == " " || chars[cursor] == "\t" || chars[cursor] == "\r" else {
+ return false
+ }
+ cursor -= 1
+ }
+ return true
+ }
+
+ private static func isAloneOnItsLine(_ span: MathSpan, chars: [Character]) -> Bool {
+ let start = span.range.lowerBound
+ // Column 0 only: an indented, quoted, or listed block keeps the
+ // paragraph style of whatever encloses it.
+ guard start == 0 || chars[start - 1] == "\n" else { return false }
+ var cursor = span.range.upperBound
+ while cursor < chars.count, chars[cursor] != "\n" {
+ guard isSpace(chars[cursor]) else { return false }
+ cursor += 1
+ }
+ return true
+ }
+
+ // MARK: - Code masking
+
+ /// Fenced blocks, indented code, and backtick spans are masked before any
+ /// dollar is looked at. Without this a `bash` fence containing
+ /// `"$HOME/$PATH"` renders as an equation.
+ static func codeMask(_ chars: [Character]) -> [Bool] {
+ var masked = [Bool](repeating: false, count: chars.count)
+ maskBlocks(chars, into: &masked)
+ maskBacktickSpans(chars, into: &masked)
+ return masked
+ }
+
+ private struct Line {
+ let start: Int
+ /// Index just past the last content character, excluding the newline.
+ let end: Int
+ /// Index just past the newline, or the end of input.
+ let next: Int
+ }
+
+ private static func lines(_ chars: [Character]) -> [Line] {
+ var result: [Line] = []
+ var start = 0
+ while start <= chars.count {
+ var end = start
+ while end < chars.count, chars[end] != "\n" { end += 1 }
+ let next = end < chars.count ? end + 1 : end
+ var content = end
+ if content > start, chars[content - 1] == "\r" { content -= 1 }
+ result.append(Line(start: start, end: content, next: next))
+ if end >= chars.count { break }
+ start = next
+ }
+ return result
+ }
+
+ /// What kind of line the previous one was. An indented chunk is code only
+ /// where a new block can start; after a paragraph line it is a lazy
+ /// continuation of that paragraph.
+ private enum LineKind {
+ case blank
+ case fence
+ case thematicBreak
+ case heading
+ case listItem
+ case code
+ case paragraph
+
+ var startsAChunk: Bool {
+ switch self {
+ case .blank, .fence, .thematicBreak, .heading, .code: true
+ case .listItem, .paragraph: false
+ }
+ }
+ }
+
+ /// Classifies each line in the splitter's order — fence, thematic break,
+ /// heading, list, paragraph — against the container it sits in.
+ ///
+ /// Reading every fence at column zero meant a listing indented into a
+ /// nested item was not a fence at all, so its shell variables typeset as
+ /// equations. Reading `- - -` as a bullet kept a list open across the rule,
+ /// so the indented block under it was item continuation instead of code.
+ /// And an indented block after a heading was neither, because the old scan
+ /// only started one after a blank line.
+ private static func maskBlocks(_ chars: [Character], into masked: inout [Bool]) {
+ var fence: (run: FenceLine.Run, containerIndent: Int)?
+ /// Content column of the innermost open list item.
+ var column: Int?
+ var previous = LineKind.blank
+ for line in lines(chars) {
+ let body = chars[line.start..<line.end]
+ let indent = indentWidth(chars, line: line)
+ let trimmed = trimmedStart(chars, line: line)
+
+ if let open = fence {
+ mask(line, into: &masked)
+ if let run = FenceLine.run(body, containerIndent: open.containerIndent),
+ run.closes(marker: open.run.marker, length: open.run.length) {
+ fence = nil
+ }
+ previous = .fence
+ continue
+ }
+ if trimmed >= line.end {
+ previous = .blank
+ continue
+ }
+ // Code comes first: inside a fenced or indented block a rule, a
+ // heading and a bullet are all literal text.
+ if indent >= (column ?? 0) + 4, previous.startsAChunk {
+ mask(line, into: &masked)
+ previous = .code
+ continue
+ }
+ if let run = FenceLine.run(body, containerIndent: column ?? 0) {
+ mask(line, into: &masked)
+ fence = (run, column ?? 0)
+ previous = .fence
+ continue
+ }
+ // A fence left of the item's content column is a block of its own,
+ // and the list ends where it starts.
+ if column != nil, let run = FenceLine.run(body) {
+ mask(line, into: &masked)
+ fence = (run, 0)
+ column = nil
+ previous = .fence
+ continue
+ }
+ if isThematicBreak(chars, from: trimmed, to: line.end) {
+ column = nil
+ previous = .thematicBreak
+ continue
+ }
+ if let item = ContainerPrefix.listItem(body) {
+ column = item.contentColumn
+ previous = .listItem
+ continue
+ }
+ if isATXHeading(chars, from: trimmed, to: line.end) {
+ if indent < (column ?? 0) { column = nil }
+ previous = .heading
+ continue
+ }
+ // A line back at the left margin after a blank one has left the
+ // list; one that is still indented is item continuation.
+ if previous == .blank, indent < 2 { column = nil }
+ previous = .paragraph
+ }
+ }
+
+ private static func isThematicBreak(
+ _ chars: [Character],
+ from start: Int,
+ to end: Int
+ ) -> Bool {
+ guard start < end else { return false }
+ let marker = chars[start]
+ guard marker == "-" || marker == "*" || marker == "_" else { return false }
+ var count = 0
+ for index in start..<end {
+ let character = chars[index]
+ if character == marker {
+ count += 1
+ } else if character != " " && character != "\t" && character != "\r" {
+ return false
+ }
+ }
+ return count >= 3
+ }
+
+ private static func isATXHeading(
+ _ chars: [Character],
+ from start: Int,
+ to end: Int
+ ) -> Bool {
+ var index = start
+ var hashes = 0
+ while index < end, chars[index] == "#" {
+ hashes += 1
+ index += 1
+ }
+ guard hashes >= 1, hashes <= 6 else { return false }
+ return index >= end || chars[index] == " " || chars[index] == "\t"
+ }
+
+ private static func mask(_ line: Line, into masked: inout [Bool]) {
+ for index in line.start..<line.next where index < masked.count {
+ masked[index] = true
+ }
+ }
+
+ private static func indentWidth(_ chars: [Character], line: Line) -> Int {
+ var width = 0
+ var index = line.start
+ while index < line.end {
+ if chars[index] == " " { width += 1 } else if chars[index] == "\t" { width += 4 } else { break }
+ index += 1
+ }
+ return width
+ }
+
+ private static func trimmedStart(_ chars: [Character], line: Line) -> Int {
+ var index = line.start
+ while index < line.end, chars[index] == " " || chars[index] == "\t" { index += 1 }
+ return index
+ }
+
+ /// CommonMark code spans: a run of N backticks closes on the next run of
+ /// exactly N, within one paragraph. An unmatched run is literal text and
+ /// cannot hide anything.
+ ///
+ /// The paragraph bound is load-bearing. Two prose sentences a few
+ /// paragraphs apart — "press the ` key", "use the ` character" — paired
+ /// across everything between them, so an equation in the middle was masked
+ /// at finalize and shown as raw source, while the streaming pass rendered
+ /// each paragraph on its own and typeset it.
+ private static func maskBacktickSpans(_ chars: [Character], into masked: inout [Bool]) {
+ var index = 0
+ while index < chars.count {
+ guard chars[index] == "`", !masked[index] else {
+ index += 1
+ continue
+ }
+ let openStart = index
+ while index < chars.count, chars[index] == "`", !masked[index] { index += 1 }
+ let length = index - openStart
+ var cursor = index
+ var closeStart: Int?
+ var sawNewline = false
+ while cursor < chars.count {
+ let character = chars[cursor]
+ if character == "\n" {
+ if sawNewline { break }
+ sawNewline = true
+ cursor += 1
+ continue
+ }
+ if character == " " || character == "\t" || character == "\r" {
+ cursor += 1
+ continue
+ }
+ sawNewline = false
+ guard character == "`", !masked[cursor] else {
+ cursor += 1
+ continue
+ }
+ let runStart = cursor
+ while cursor < chars.count, chars[cursor] == "`", !masked[cursor] { cursor += 1 }
+ if cursor - runStart == length {
+ closeStart = runStart
+ break
+ }
+ }
+ guard let closeStart else { continue }
+ for position in openStart..<(closeStart + length) { masked[position] = true }
+ index = closeStart + length
+ }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/MathTypesetter.swift b/Sources/TurboFieldfareApp/MacPresentation/MathTypesetter.swift
new file mode 100644
index 00000000..fd07358f
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/MathTypesetter.swift
@@ -0,0 +1,266 @@
+import AppKit
+import Foundation
+import SwiftMath
+import os
+
+public enum MathRenderMode: Sendable {
+ case inline
+ case display
+}
+
+/// A typeset equation plus the metrics an `NSTextAttachment` needs to sit on
+/// the surrounding text baseline. Project-owned so the transcript API never
+/// exposes the typesetting library, and so tests can inject a deterministic
+/// stand-in without importing it either.
+public struct MathRender {
+ public let image: NSImage
+ public let ascent: CGFloat
+ public let descent: CGFloat
+
+ public init(image: NSImage, ascent: CGFloat, descent: CGFloat) {
+ self.image = image
+ self.ascent = ascent
+ self.descent = descent
+ }
+}
+
+@MainActor
+public protocol MathTypesetting {
+ func render(
+ latex: String,
+ fontSize: CGFloat,
+ tint: NSColor,
+ mode: MathRenderMode
+ ) -> MathRender?
+}
+
+/// Carries the exact source span so `plainText` and the accessibility layer can
+/// recover the LaTeX a reader can no longer select out of the image.
+public final class MathAttachment: NSTextAttachment {
+ public let latexSource: String
+
+ public init(latexSource: String) {
+ self.latexSource = latexSource
+ super.init(data: nil, ofType: nil)
+ }
+
+ /// Nothing archives the transcript. The pasteboard flavours write the
+ /// LaTeX itself rather than the attachment, so an archived one could only
+ /// come back as an object-replacement character where an equation was —
+ /// which is the failure the attachment exists to prevent. Decoding refuses
+ /// instead of returning a source-less attachment.
+ public required init?(coder: NSCoder) { nil }
+}
+
+@MainActor
+public struct SwiftMathTypesetter: MathTypesetting {
+ /// SwiftMath bakes the glyph color into the CoreText run at typeset time,
+ /// so a single image cannot follow a light/dark switch. Typesetting once in
+ /// an opaque color and keeping only the coverage lets the attachment fill
+ /// with the run's dynamic color at draw time instead.
+ private static let maskScale: CGFloat = 3
+
+ private static let log = Logger(
+ subsystem: "TurboFieldfare",
+ category: "math-typesetting")
+
+ private let cache: MathRenderCache
+
+ public init(cache: MathRenderCache = .shared) {
+ self.cache = cache
+ }
+
+ public func render(
+ latex: String,
+ fontSize: CGFloat,
+ tint: NSColor,
+ mode: MathRenderMode
+ ) -> MathRender? {
+ let key = MathRenderCache.Key(
+ latex: latex,
+ fontSize: fontSize,
+ tint: tint.description,
+ mode: mode)
+ if let cached = cache.value(for: key) { return cached }
+ guard let mask = Self.mask(latex: latex, fontSize: fontSize, mode: mode) else {
+ return nil
+ }
+ let render = MathRender(
+ image: Self.tinted(mask.image, size: mask.size, tint: tint),
+ ascent: mask.ascent,
+ descent: mask.descent)
+ cache.store(render, cost: mask.bytes, for: key)
+ return render
+ }
+
+ private struct Mask {
+ let image: CGImage
+ let size: CGSize
+ let ascent: CGFloat
+ let descent: CGFloat
+ /// What the tinted image retains: the drawing handler clips to this
+ /// bitmap, so the mask is the memory the cache is spending.
+ let bytes: Int
+ }
+
+ private static func mask(
+ latex: String,
+ fontSize: CGFloat,
+ mode: MathRenderMode
+ ) -> Mask? {
+ // The builder skips a character it has no atom for and reports nothing,
+ // so an equation can come back looking finished with an operator
+ // missing from it. Refusing here restores the span's own source, which
+ // the reader can at least see.
+ if let dropped = PinnedMathCoverage.firstDroppedCharacter(in: latex) {
+ let code = dropped.unicodeScalars
+ .map { String(format: "%04X", $0.value) }
+ .joined(separator: "+")
+ log.error("""
+ math typeset refused: pinned build drops U+\(code, privacy: .public) \
+ length=\(latex.count, privacy: .public)
+ """)
+ return nil
+ }
+ var image = MathImage(
+ latex: latex,
+ fontSize: fontSize,
+ textColor: .black,
+ labelMode: mode == .display ? .display : .text)
+ let (error, typeset, layout) = image.asImage()
+ if let error {
+ log.error("""
+ math typeset failed: domain=\(error.domain, privacy: .public) \
+ code=\(error.code, privacy: .public) \
+ length=\(latex.count, privacy: .public)
+ """)
+ return nil
+ }
+ guard let typeset, let layout else {
+ log.error("""
+ math typeset produced no image without an error: \
+ length=\(latex.count, privacy: .public)
+ """)
+ return nil
+ }
+ let size = typeset.size
+ // A zero-width or zero-height bitmap rep cannot be allocated, and an
+ // empty attachment would be an invisible hole where an equation was.
+ guard size.width >= 1, size.height >= 1 else {
+ log.error("""
+ math typeset produced an empty image: \
+ length=\(latex.count, privacy: .public)
+ """)
+ return nil
+ }
+ guard let rep = NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: Int(ceil(size.width * maskScale)),
+ pixelsHigh: Int(ceil(size.height * maskScale)),
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0) else {
+ log.error("""
+ math mask allocation failed: \
+ length=\(latex.count, privacy: .public)
+ """)
+ return nil
+ }
+ rep.size = size
+ // Without this the equation draws into no context at all and the
+ // blank rep still yields a `cgImage`, so a transparent attachment
+ // would be cached in place of the equation with nothing logged.
+ guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
+ log.error("""
+ math mask has no drawing context: \
+ length=\(latex.count, privacy: .public)
+ """)
+ return nil
+ }
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = context
+ typeset.draw(in: NSRect(origin: .zero, size: size))
+ NSGraphicsContext.restoreGraphicsState()
+ guard let mask = rep.cgImage else {
+ log.error("""
+ math mask has no bitmap: length=\(latex.count, privacy: .public)
+ """)
+ return nil
+ }
+ return Mask(
+ image: mask,
+ size: size,
+ ascent: layout.ascent,
+ descent: layout.descent,
+ bytes: rep.bytesPerRow * rep.pixelsHigh)
+ }
+
+ private static func tinted(
+ _ mask: CGImage,
+ size: CGSize,
+ tint: NSColor
+ ) -> NSImage {
+ NSImage(size: size, flipped: false) { rect in
+ guard let context = NSGraphicsContext.current?.cgContext else { return false }
+ context.saveGState()
+ context.clip(to: rect, mask: mask)
+ tint.setFill()
+ context.fill(rect)
+ context.restoreGState()
+ return true
+ }
+ }
+}
+
+/// Memo for typeset equations. Measured on the fifty-equation corpus fixture:
+/// a finalize pass costs 36.7 ms, well past a 16 ms frame, and a rebuild while
+/// the answer is terminal re-renders the whole transcript. The memo removes the
+/// repeat cost; the first pass over an answer still pays for every equation.
+@MainActor
+public final class MathRenderCache {
+ public static let shared = MathRenderCache()
+
+ struct Key: Hashable {
+ let latex: String
+ let fontSize: CGFloat
+ let tint: String
+ let mode: MathRenderMode
+ }
+
+ /// Bounded by what the images cost rather than by how many there are. A
+ /// display equation's 3x mask runs to hundreds of kilobytes and an inline
+ /// one to tens, so a count limit is either far too small for a page of
+ /// prose or far too large for a page of derivations. 16 MiB is roughly a
+ /// hundred display equations at 13 pt, or a thousand inline ones.
+ private let byteLimit: Int
+ private var entries: [Key: MathRender] = [:]
+ private var bytes = 0
+
+ public init(byteLimit: Int = 16 << 20) {
+ self.byteLimit = byteLimit
+ }
+
+ var count: Int { entries.count }
+ var byteCount: Int { bytes }
+
+ func value(for key: Key) -> MathRender? { entries[key] }
+
+ func store(_ render: MathRender, cost: Int, for key: Key) {
+ // One equation bigger than the whole budget is not worth emptying the
+ // table for; it is typeset again if it comes back.
+ guard cost <= byteLimit else { return }
+ if bytes + cost > byteLimit {
+ // Equations are cheap to typeset again, so dropping the table beats
+ // tracking per-entry age.
+ entries.removeAll(keepingCapacity: true)
+ bytes = 0
+ }
+ if entries.updateValue(render, forKey: key) == nil { bytes += cost }
+ }
+}
+
+extension MathRenderMode: Hashable {}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/MathTypesetterCoverage.swift b/Sources/TurboFieldfareApp/MacPresentation/MathTypesetterCoverage.swift
new file mode 100644
index 00000000..3ccd90ab
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/MathTypesetterCoverage.swift
@@ -0,0 +1,122 @@
+import Foundation
+
+/// What the pinned typesetter can draw, character by character.
+///
+/// `MTMathListBuilder` asks `MTMathAtomFactory.atom(forCharacter:)` for every
+/// literal character and, in math mode, *skips* the ones it has no atom for —
+/// no error, no diagnostic, nothing missing from the returned image except the
+/// character itself. So `√2` typeset pixel-identical to `2` and `f′(x)` to
+/// `f(x)`, and the reader had no way to know an operator had gone.
+///
+/// This mirrors that function's own order: the Cyrillic range and the accented
+/// table first, then everything outside printable ASCII refused, then the set
+/// LaTeX reserves, then the ranges each remaining character falls in. The order
+/// is why a base character carrying a combining mark is drawn — its string
+/// sorts inside the range its base falls in — and the empirical probe measures
+/// every scalar of this against the build.
+enum PinnedMathCoverage {
+ static func renders(_ character: Character) -> Bool {
+ let text = String(character)
+ if text >= "\u{0410}", text <= "\u{044F}" { return true }
+ if accented.contains(character) { return true }
+ guard let first = character.unicodeScalars.first,
+ first.value >= 0x21, first.value <= 0x7E else {
+ return false
+ }
+ guard !reserved.contains(text) else { return false }
+ if singles.contains(text) { return true }
+ return ranges.contains { text >= $0.0 && text <= $0.1 }
+ }
+
+ /// The first character in `latex` the pinned build would drop, or nil.
+ ///
+ /// Command names are skipped, because the letters after a backslash are a
+ /// command rather than literal text, and so are `\text{...}` groups, which
+ /// is the one place the builder accepts anything at all.
+ static func firstDroppedCharacter(in latex: String) -> Character? {
+ let characters = Array(latex)
+ var index = 0
+ while index < characters.count {
+ let character = characters[index]
+ guard character != "\\" else {
+ index = skippingCommand(characters, from: index)
+ continue
+ }
+ if structural.contains(character) {
+ index += 1
+ continue
+ }
+ guard renders(character) else { return character }
+ index += 1
+ }
+ return nil
+ }
+
+ private static func skippingCommand(_ characters: [Character], from start: Int) -> Int {
+ var index = start + 1
+ guard index < characters.count else { return index }
+ guard characters[index].isLetter else { return index + 1 }
+ var name = ""
+ while index < characters.count, characters[index].isLetter {
+ name.append(characters[index])
+ index += 1
+ }
+ // `spacesAllowed` is set for `\text` alone in the pinned builder, and
+ // that is the only mode in which an unrecognised character survives.
+ guard name == "text", index < characters.count, characters[index] == "{" else {
+ return index
+ }
+ var depth = 0
+ while index < characters.count {
+ if characters[index] == "\\" {
+ index += 2
+ continue
+ }
+ if characters[index] == "{" { depth += 1 }
+ if characters[index] == "}" {
+ depth -= 1
+ if depth == 0 { return index + 1 }
+ }
+ index += 1
+ }
+ return index
+ }
+
+ /// Characters the builder consumes as structure before it ever asks for an
+ /// atom: scripts, groups, the alignment separator, the escape itself, and
+ /// ASCII whitespace, which math mode drops on purpose — the spacing comes
+ /// from `\ ` and `\,`. A non-breaking or thin space is not in here: those
+ /// the builder drops without meaning to.
+ ///
+ /// The empirical probe skips these, because what they draw is a script or
+ /// a group rather than the character itself.
+ static let structural: Set<Character> = ["^", "_", "{", "}", "&", "\\", " ", "\t", "\n", "\r"]
+
+ /// What `atom(forCharacter:)` returns nil for by name. `'` is not here: the
+ /// pinned build routes it through the accented table and draws it.
+ private static let reserved: Set<String> = ["$", "%", "#", "&", "~", "^", "_", "{", "}", "\\"]
+
+ private static let singles: Set<String> = [
+ "(", "[", ")", "]", "!", "?", ",", ";", "=", ">", "<", ":",
+ "-", "+", "*", ".", "\"", "/", "@", "`", "|",
+ ]
+
+ private static let ranges: [(String, String)] = [("0", "9"), ("a", "z"), ("A", "Z")]
+
+ /// `MTMathAtomFactory.supportedAccentedCharacters`, which is consulted
+ /// before the ASCII rules and so also carries `'`.
+ private static let accented: Set<Character> = [
+ "á", "é", "í", "ó", "ú", "ý",
+ "à", "è", "ì", "ò", "ù",
+ "â", "ê", "î", "ĵ", "ô", "û",
+ "ä", "ë", "ï", "ö", "ü", "ÿ",
+ "ã", "ñ", "õ",
+ "ç", "ø", "å", "æ", "œ", "ß", "'",
+ "Á", "É", "Í", "Ó", "Ú", "Ý",
+ "À", "È", "Ì", "Ò", "Ù",
+ "Â", "Ê", "Î", "Ô", "Û",
+ "Ä", "Ë", "Ï", "Ö", "Ü",
+ "Ã", "Ñ", "Õ",
+ "Ç", "Ø", "Å", "Æ", "Œ",
+ ]
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/ResponseBlockSplitter.swift b/Sources/TurboFieldfareApp/MacPresentation/ResponseBlockSplitter.swift
new file mode 100644
index 00000000..39d004d4
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/ResponseBlockSplitter.swift
@@ -0,0 +1,497 @@
+import Foundation
+
+/// Splits a response into the top-level blocks that can be styled while the
+/// answer is still arriving, and names the trailing block that is still being
+/// written.
+///
+/// Blank lines are almost the only splitter, and a fence line is the one
+/// exception. Everything else stays with the block above it: `Title` followed
+/// by `---` is a setext heading, a `|` row that follows a paragraph line
+/// belongs to that paragraph, a list item that follows another keeps its
+/// ordinal from the list it is in — and a progressive render is only worth
+/// having if a completed block looks exactly like the final one. A fenced
+/// block therefore absorbs the blank lines inside it, and a list absorbs the
+/// blank lines between its items, because the parser reads both as one block.
+/// A fence opener has to split, for the same reason: CommonMark lets it
+/// interrupt a paragraph, so a parser handed the two together reads the
+/// listing as code where this scanner would have read prose.
+///
+/// One thing a block cannot carry is a reference to something outside it. A
+/// `[label][ref]` whose `[ref]: url` definition sits in a later block renders
+/// with its brackets showing, because the block that uses the label is parsed
+/// on its own. Resolving it would mean scanning the whole response on every
+/// tick, which is the shape the streaming timing gate exists to catch, and
+/// doing it only at finalize would put the flip back that the per-block
+/// finalize removed. The target models emit reference links rarely.
+///
+/// Boundaries are UTF-8 offsets and the scan is resumable so a tick costs the
+/// bytes that arrived, not the bytes that are there: re-scanning a 10 KB fenced
+/// block on each of the ~1,200 ticks it takes to stream is the quadratic shape
+/// the streaming timing gate exists to catch.
+enum ResponseBlockSplitter {
+ enum Kind: Equatable {
+ case paragraph
+ case heading
+ case fencedCode
+ case indentedCode
+ case table
+ case list
+ case quote
+ case displayMath
+ case thematicBreak
+ }
+
+ struct Fence: Equatable {
+ let marker: UInt8
+ let length: Int
+ let indent: Int
+ /// First byte after the opening fence line.
+ let bodyStart: Int
+ /// First byte of the closing fence line, or the end of the block.
+ let bodyEnd: Int
+ let isClosed: Bool
+ }
+
+ struct Block: Equatable {
+ /// UTF-8 offset of the block's first byte.
+ let start: Int
+ /// UTF-8 offset one past the block's last non-blank byte; the line
+ /// terminator that follows is not part of the block.
+ let end: Int
+ let kind: Kind
+ let fence: Fence?
+
+ var utf8Range: Range<Int> { start..<end }
+ }
+
+ /// Scanner position that survives an append. Only complete lines commit,
+ /// so nothing already in `completed` can change when more text arrives.
+ struct ScanState: Equatable {
+ var cursor = 0
+ var current: Current?
+ /// A blank line has ended the current block's content, but a list or an
+ /// indented code block may still continue past it.
+ var pendingBlank = false
+ }
+
+ struct Current: Equatable {
+ var start: Int
+ var contentEnd: Int
+ var kind: Kind
+ var fenceMarker: UInt8 = 0
+ var fenceLength = 0
+ var fenceIndent = 0
+ var fenceBodyStart = 0
+ var fenceBodyEnd = 0
+ var fenceClosed = false
+ /// Content column of the outermost item a list block is inside. A
+ /// fence at or past it is the item's own listing; one before it ends
+ /// the list.
+ var listContentColumn = 0
+ /// A fence opened inside a list item. The block stays a list — the
+ /// whole thing goes through the markdown pass — but until the fence
+ /// closes its lines are code, so no blank line inside it commits the
+ /// block and no line inside it opens anything.
+ var innerFenceMarker: UInt8 = 0
+ var innerFenceLength = 0
+ }
+
+ struct Split: Equatable {
+ var completed: [Block] = []
+ var open: Block?
+ var scan = ScanState()
+
+ var blocks: [Block] { completed + (open.map { [$0] } ?? []) }
+ }
+
+ static func split(_ response: String) -> Split {
+ scan(response, from: Split())
+ }
+
+ /// Resumes `previous`. The caller must have established that `response`
+ /// extends the string `previous` was produced from; a shorter or diverging
+ /// response has to go through `split(_:)` instead, because the committed
+ /// blocks are not re-examined.
+ static func split(_ response: String, resuming previous: Split) -> Split {
+ scan(response, from: previous)
+ }
+
+ static func text(_ range: Range<Int>, in response: String) -> String {
+ withUTF8(response) { bytes in
+ let lower = min(max(range.lowerBound, 0), bytes.count)
+ let upper = min(max(range.upperBound, lower), bytes.count)
+ return String(decoding: UnsafeBufferPointer(
+ rebasing: bytes[lower..<upper]), as: UTF8.self)
+ }
+ }
+
+ // MARK: - Scanning
+
+ private static func scan(_ response: String, from previous: Split) -> Split {
+ withUTF8(response) { bytes in
+ var state = previous.scan
+ var completed = previous.completed
+ var index = min(state.cursor, bytes.count)
+ while index < bytes.count {
+ guard let terminator = newlineIndex(bytes, from: index) else { break }
+ consume(
+ bytes,
+ line: index..<terminator,
+ lineEnd: terminator + 1,
+ terminated: true,
+ state: &state,
+ completed: &completed)
+ index = terminator + 1
+ state.cursor = index
+ }
+
+ // The trailing partial line is scanned into a copy: a block may
+ // only be completed by a line that has already ended, or a block
+ // the caller has drawn as finished could re-open on the next tick.
+ var derived = state
+ var ignored = completed
+ if index < bytes.count {
+ consume(
+ bytes,
+ line: index..<bytes.count,
+ lineEnd: bytes.count,
+ terminated: false,
+ state: &derived,
+ completed: &ignored)
+ }
+
+ var split = Split()
+ split.completed = completed
+ split.scan = state
+ if let current = derived.current {
+ split.open = block(from: current)
+ }
+ return split
+ }
+ }
+
+ private static func consume(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ line: Range<Int>,
+ lineEnd: Int,
+ terminated: Bool,
+ state: inout ScanState,
+ completed: inout [Block]
+ ) {
+ let content = contentRange(bytes, line)
+
+ if var current = state.current, current.kind == .fencedCode, !current.fenceClosed {
+ if let run = FenceLine.run(bytes, in: content),
+ run.closes(marker: current.fenceMarker, length: current.fenceLength) {
+ current.fenceClosed = true
+ current.fenceBodyEnd = line.lowerBound
+ current.contentEnd = content.upperBound
+ if terminated {
+ completed.append(block(from: current))
+ state.current = nil
+ state.pendingBlank = false
+ } else {
+ state.current = current
+ }
+ return
+ }
+ current.contentEnd = content.upperBound
+ current.fenceBodyEnd = lineEnd
+ state.current = current
+ return
+ }
+
+ if var current = state.current, current.innerFenceMarker != 0 {
+ let indent = indentWidth(bytes, content)
+ let blank = isBlank(bytes, content)
+ // An unclosed fence inside an item cannot hold the rest of the
+ // answer: a line indented before the item's content column has
+ // left the item, and the fence with it.
+ if blank || indent >= current.listContentColumn {
+ if let run = FenceLine.run(
+ bytes,
+ in: content,
+ containerIndent: current.listContentColumn),
+ run.closes(
+ marker: current.innerFenceMarker,
+ length: current.innerFenceLength) {
+ current.innerFenceMarker = 0
+ current.innerFenceLength = 0
+ }
+ if !blank { current.contentEnd = content.upperBound }
+ state.current = current
+ state.pendingBlank = false
+ return
+ }
+ current.innerFenceMarker = 0
+ current.innerFenceLength = 0
+ state.current = current
+ }
+
+ guard !isBlank(bytes, content) else {
+ guard let current = state.current else { return }
+ if terminated, current.kind != .list, current.kind != .indentedCode {
+ completed.append(block(from: current))
+ state.current = nil
+ state.pendingBlank = false
+ } else {
+ state.pendingBlank = true
+ }
+ return
+ }
+
+ let indent = indentWidth(bytes, content)
+ guard var current = state.current else {
+ state.current = opening(bytes, content: content, lineEnd: lineEnd, indent: indent)
+ state.pendingBlank = false
+ return
+ }
+
+ if state.pendingBlank {
+ let continues = continuation(
+ of: current.kind,
+ bytes: bytes,
+ content: content,
+ indent: indent)
+ // An unterminated line may still turn into a list item, so the
+ // block it would continue stays open until the line ends.
+ guard continues || !terminated else {
+ completed.append(block(from: current))
+ state.current = opening(
+ bytes, content: content, lineEnd: lineEnd, indent: indent)
+ state.pendingBlank = false
+ return
+ }
+ state.pendingBlank = false
+ }
+
+ if current.kind == .list {
+ // A nested item is inside the item above it; a sibling or an outer
+ // one is the item the block's fences are measured against now.
+ if let item = ContainerPrefix.listItem(bytes, in: content),
+ item.markerIndent < current.listContentColumn {
+ current.listContentColumn = item.contentColumn
+ }
+ if terminated, let run = FenceLine.run(
+ bytes,
+ in: content,
+ containerIndent: current.listContentColumn) {
+ current.innerFenceMarker = run.marker
+ current.innerFenceLength = run.length
+ current.contentEnd = content.upperBound
+ state.current = current
+ return
+ }
+ }
+
+ // The one boundary a blank line does not draw. A fence interrupts a
+ // paragraph in CommonMark, and absorbing it instead hands the rest of
+ // the listing to the prose block: the blank line inside the code then
+ // commits it, and the lines below open an indented-code block that
+ // swallows the closing fence and the sentence after it. A list is
+ // interrupted the same way once the fence is left of its content
+ // column, which is where the item's own listing would have started.
+ if terminated, current.kind != .indentedCode,
+ FenceLine.run(bytes, in: content) != nil {
+ completed.append(block(from: current))
+ state.current = opening(bytes, content: content, lineEnd: lineEnd, indent: indent)
+ return
+ }
+
+ current.contentEnd = content.upperBound
+ state.current = current
+ }
+
+ private static func opening(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ content: Range<Int>,
+ lineEnd: Int,
+ indent: Int
+ ) -> Current {
+ var current = Current(
+ start: content.lowerBound,
+ contentEnd: content.upperBound,
+ kind: kind(bytes, content: content, indent: indent))
+ if current.kind == .fencedCode, let fence = FenceLine.run(bytes, in: content) {
+ current.fenceMarker = fence.marker
+ current.fenceLength = fence.length
+ current.fenceIndent = fence.indent
+ current.fenceBodyStart = lineEnd
+ current.fenceBodyEnd = lineEnd
+ }
+ if current.kind == .list, let item = ContainerPrefix.listItem(bytes, in: content) {
+ current.listContentColumn = item.contentColumn
+ }
+ return current
+ }
+
+ private static func block(from current: Current) -> Block {
+ var fence: Fence?
+ if current.kind == .fencedCode {
+ fence = Fence(
+ marker: current.fenceMarker,
+ length: current.fenceLength,
+ indent: current.fenceIndent,
+ bodyStart: current.fenceBodyStart,
+ bodyEnd: max(current.fenceBodyStart, current.fenceBodyEnd),
+ isClosed: current.fenceClosed)
+ }
+ return Block(
+ start: current.start,
+ end: current.contentEnd,
+ kind: current.kind,
+ fence: fence)
+ }
+
+ // MARK: - Line classification
+
+ private static func kind(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ content: Range<Int>,
+ indent: Int
+ ) -> Kind {
+ if indent >= 4 { return .indentedCode }
+ if FenceLine.run(bytes, in: content) != nil { return .fencedCode }
+ let start = firstNonSpace(bytes, content)
+ guard start < content.upperBound else { return .paragraph }
+ if isThematicBreak(bytes, content) { return .thematicBreak }
+ switch bytes[start] {
+ case UInt8(ascii: "#"):
+ var hashes = 0
+ var index = start
+ while index < content.upperBound, bytes[index] == UInt8(ascii: "#") {
+ hashes += 1
+ index += 1
+ }
+ if hashes <= 6, index >= content.upperBound || isSpace(bytes[index]) {
+ return .heading
+ }
+ case UInt8(ascii: ">"):
+ return .quote
+ case UInt8(ascii: "|"):
+ return .table
+ case UInt8(ascii: "$"):
+ if start + 1 < content.upperBound, bytes[start + 1] == UInt8(ascii: "$") {
+ return .displayMath
+ }
+ default:
+ break
+ }
+ if ContainerPrefix.listItem(bytes, in: content) != nil { return .list }
+ return .paragraph
+ }
+
+ private static func continuation(
+ of kind: Kind,
+ bytes: UnsafeBufferPointer<UInt8>,
+ content: Range<Int>,
+ indent: Int
+ ) -> Bool {
+ switch kind {
+ case .list:
+ return indent >= 2 || ContainerPrefix.listItem(bytes, in: content) != nil
+ case .indentedCode:
+ return indent >= 4
+ default:
+ return false
+ }
+ }
+
+ private static func isThematicBreak(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ _ content: Range<Int>
+ ) -> Bool {
+ var index = firstNonSpace(bytes, content)
+ guard index < content.upperBound else { return false }
+ let marker = bytes[index]
+ guard marker == UInt8(ascii: "-") || marker == UInt8(ascii: "*")
+ || marker == UInt8(ascii: "_") else {
+ return false
+ }
+ var count = 0
+ while index < content.upperBound {
+ let byte = bytes[index]
+ if byte == marker {
+ count += 1
+ } else if !isSpace(byte) {
+ return false
+ }
+ index += 1
+ }
+ return count >= 3
+ }
+
+ // MARK: - Bytes
+
+ private static func newlineIndex(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ from index: Int
+ ) -> Int? {
+ var cursor = index
+ while cursor < bytes.count {
+ if bytes[cursor] == UInt8(ascii: "\n") { return cursor }
+ cursor += 1
+ }
+ return nil
+ }
+
+ private static func contentRange(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ _ line: Range<Int>
+ ) -> Range<Int> {
+ var end = line.upperBound
+ while end > line.lowerBound, bytes[end - 1] == UInt8(ascii: "\r") { end -= 1 }
+ return line.lowerBound..<end
+ }
+
+ private static func isBlank(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ _ content: Range<Int>
+ ) -> Bool {
+ for index in content where !isSpace(bytes[index]) { return false }
+ return true
+ }
+
+ /// Byte offset of the first byte that is not indentation.
+ private static func firstNonSpace(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ _ content: Range<Int>
+ ) -> Int {
+ var index = content.lowerBound
+ while index < content.upperBound,
+ bytes[index] == UInt8(ascii: " ") || bytes[index] == UInt8(ascii: "\t") {
+ index += 1
+ }
+ return index
+ }
+
+ private static func indentWidth(
+ _ bytes: UnsafeBufferPointer<UInt8>,
+ _ content: Range<Int>
+ ) -> Int {
+ var width = 0
+ for index in content {
+ if bytes[index] == UInt8(ascii: " ") {
+ width += 1
+ } else if bytes[index] == UInt8(ascii: "\t") {
+ width += 4
+ } else {
+ break
+ }
+ }
+ return width
+ }
+
+ private static func isSpace(_ byte: UInt8) -> Bool {
+ byte == UInt8(ascii: " ") || byte == UInt8(ascii: "\t") || byte == UInt8(ascii: "\r")
+ }
+
+ private static func withUTF8<R>(
+ _ text: String,
+ _ body: (UnsafeBufferPointer<UInt8>) -> R
+ ) -> R {
+ if let result = text.utf8.withContiguousStorageIfAvailable(body) { return result }
+ var copy = text
+ return copy.withUTF8 { body($0) }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift b/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift
index a6f13c05..9e9a3637 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift
@@ -1,8 +1,18 @@
import AppKit
import Foundation
+/// The renderer surface the transcript controller depends on. Narrow on
+/// purpose: it is also the seam a test uses to count how many times a block is
+/// rendered while an answer streams.
@MainActor
-public struct ResponseMarkdownRenderer {
+public protocol TranscriptBlockRendering {
+ func render(_ source: String, typesetsMath: Bool) -> ResponseMarkdownRenderer.Result
+ func blockSeparator(trailingNewlines: Int) -> NSAttributedString
+ func streamingCodeAttributes() -> [NSAttributedString.Key: Any]
+}
+
+@MainActor
+public struct ResponseMarkdownRenderer: TranscriptBlockRendering {
public struct Result {
public let attributedString: NSAttributedString
public let usedFallback: Bool
@@ -13,6 +23,15 @@ public struct ResponseMarkdownRenderer {
}
}
+ private struct TableCell: Equatable {
+ let table: Int
+ let columns: Int
+ let row: Int
+ let column: Int
+ let isHeader: Bool
+ let alignment: NSTextAlignment
+ }
+
private enum BlockKind: Equatable {
case paragraph
case heading(Int)
@@ -21,6 +40,7 @@ public struct ResponseMarkdownRenderer {
case unorderedList(indent: Int)
case orderedList(ordinal: Int, indent: Int)
case thematicBreak
+ case tableCell(TableCell)
var isList: Bool {
switch self {
@@ -28,6 +48,22 @@ public struct ResponseMarkdownRenderer {
default: false
}
}
+
+ /// A header row reads as a header from its weight, not only from its
+ /// fill, which is barely visible in dark mode.
+ var isHeaderCell: Bool {
+ switch self {
+ case .tableCell(let cell): cell.isHeader
+ default: false
+ }
+ }
+
+ var tableIdentity: Int? {
+ switch self {
+ case .tableCell(let cell): cell.table
+ default: nil
+ }
+ }
}
private struct Block: Equatable {
@@ -35,17 +71,40 @@ public struct ResponseMarkdownRenderer {
let kind: BlockKind
}
- public init() {}
+ private struct Item {
+ let text: String
+ let inlineIntent: InlinePresentationIntent?
+ let link: URL?
+ let imageURL: URL?
+ let block: Block
+ }
+
+ private let mathEnabled: Bool
+ private let typesetter: any MathTypesetting
+
+ public init(
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ typesetter: any MathTypesetting = SwiftMathTypesetter()
+ ) {
+ mathEnabled = environment["TURBO_FIELDFARE_DISABLE_MATH"] != "1"
+ self.typesetter = typesetter
+ }
- public func render(_ source: String) -> Result {
+ /// `typesetsMath: false` still lifts every equation out of the markdown
+ /// pass — which would eat its backslashes — but puts the source back
+ /// instead of an image. The block being streamed uses it: a half-typed
+ /// equation cannot typeset, and asking a failing parse per tick buys a
+ /// log line and nothing else.
+ public func render(_ source: String, typesetsMath: Bool = true) -> Result {
guard !source.isEmpty else {
return Result(attributedString: NSAttributedString(), usedFallback: false)
}
guard !requiresRawFallback(source) else { return fallback(source) }
- let presentationSource = source.replacingOccurrences(
- of: #"(?m)^([ \t]*\*\*[^*\n]+\*\*[ \t]*)\n(?=\S)"#,
- with: "$1\n\n",
- options: .regularExpression)
+ // Math is lifted out before the markdown pass, which eats backslashes,
+ // unescapes braces, and drops `\[` delimiters outright. Every fallback
+ // below returns the untouched `source`, never this working copy.
+ let substitution = mathEnabled ? MathSpanDetector.substitute(source) : nil
+ let presentationSource = Self.promotingBoldHeadings(substitution?.working ?? source)
do {
let parsed = try AttributedString(
@@ -55,71 +114,298 @@ public struct ResponseMarkdownRenderer {
failurePolicy: .returnPartiallyParsedIfPossible))
guard !containsUnsupportedBlock(in: parsed) else { return fallback(source) }
+ let items = Self.completingTables(parsed.runs.map { run in
+ let text = String(parsed[run.range].characters)
+ return Item(
+ // An image is its alt text, or its destination when the
+ // model wrote none: the parser hands back a bare
+ // object-replacement character, which draws as nothing at
+ // all where the reader expected a picture.
+ text: Self.imageText(text, url: run.imageURL) ?? text,
+ inlineIntent: run.inlinePresentationIntent,
+ link: Self.openable(run.link),
+ imageURL: Self.openable(run.imageURL),
+ block: block(for: run.presentationIntent))
+ })
+
let output = NSMutableAttributedString()
+ let decoration = BlockDecoration()
var previousBlock: Block?
-
- for run in parsed.runs {
- let block = block(for: run.presentationIntent)
- if block != previousBlock {
- appendSeparator(to: output, previous: previousBlock, next: block)
- appendPrefix(for: block.kind, to: output)
- if block.kind == .thematicBreak {
- output.append(NSAttributedString(
- string: "────────────────",
- attributes: attributes(
- inlineIntent: nil,
- link: nil,
- block: block.kind)))
- }
- previousBlock = block
- }
-
- guard block.kind != .thematicBreak else { continue }
- let text = String(parsed[run.range].characters)
- guard !text.isEmpty else { continue }
- output.append(NSAttributedString(
- string: text,
- attributes: attributes(
- inlineIntent: run.inlinePresentationIntent,
- link: run.link,
- block: block.kind)))
+ var index = 0
+ while index < items.count {
+ let block = items[index].block
+ var end = index
+ while end < items.count, items[end].block == block { end += 1 }
+ appendSeparator(to: output, previous: previousBlock, next: block)
+ append(
+ Array(items[index..<end]),
+ block: block,
+ to: output,
+ decoration: decoration)
+ previousBlock = block
+ index = end
}
guard output.length > 0 else { return fallback(source) }
+ if let substitution, !substitution.spans.isEmpty {
+ guard resolveMath(
+ substitution.spans,
+ in: output,
+ typesetsMath: typesetsMath) else {
+ return fallback(source)
+ }
+ }
return Result(attributedString: output, usedFallback: false)
} catch {
return fallback(source)
}
}
+ /// Copy actions read the raw response, but this is the transcript's own
+ /// text projection and must never start returning the object-replacement
+ /// character where an equation used to be.
public func plainText(_ source: String) -> String {
- render(source).attributedString.string
+ TranscriptPlainText.string(of: render(source).attributedString)
+ }
+
+ /// Replaces every sentinel with its attachment, or with the raw span text
+ /// when the equation does not typeset. Returns false when an emitted index
+ /// never turns up: a sentinel inside a link destination is percent-encoded
+ /// into the `.link` attribute and disappears from the character stream, and
+ /// a whole-message raw fallback beats a silently deleted equation.
+ private func resolveMath(
+ _ spans: [MathSpan],
+ in output: NSMutableAttributedString,
+ typesetsMath: Bool
+ ) -> Bool {
+ let open = String(MathSpanDetector.openSentinel)
+ let close = String(MathSpanDetector.closeSentinel)
+ var consumed: Set<Int> = []
+ var searchStart = 0
+ while true {
+ let text = output.string as NSString
+ let tail = NSRange(
+ location: searchStart,
+ length: max(0, text.length - searchStart))
+ let opened = text.range(of: open, range: tail)
+ guard opened.location != NSNotFound else { break }
+ let afterOpen = NSRange(
+ location: opened.upperBound,
+ length: text.length - opened.upperBound)
+ let closed = text.range(of: close, range: afterOpen)
+ guard closed.location != NSNotFound else { return false }
+ let digits = text.substring(with: NSRange(
+ location: opened.upperBound,
+ length: closed.location - opened.upperBound))
+ guard let index = Int(digits), spans.indices.contains(index),
+ consumed.insert(index).inserted else {
+ return false
+ }
+ let sentinel = NSRange(
+ location: opened.location,
+ length: closed.upperBound - opened.location)
+ let resolved = resolution(
+ for: spans[index],
+ sentinel: sentinel,
+ in: output,
+ typesetsMath: typesetsMath)
+ output.replaceCharacters(in: sentinel, with: resolved.text)
+ if resolved.centered {
+ let paragraph = (output.string as NSString).paragraphRange(
+ for: NSRange(location: sentinel.location, length: resolved.text.length))
+ center(paragraph, in: output)
+ }
+ searchStart = sentinel.location + resolved.text.length
+ }
+ return consumed.count == spans.count
+ }
+
+ private struct MathResolution {
+ let text: NSAttributedString
+ let centered: Bool
+ }
+
+ private func resolution(
+ for span: MathSpan,
+ sentinel: NSRange,
+ in output: NSMutableAttributedString,
+ typesetsMath: Bool
+ ) -> MathResolution {
+ // `NSAttributedString(attachment:)` carries no attributes at all, so
+ // the sentinel run's font, colour, and paragraph style are copied
+ // first; without them math inside a list or quote loses its indent.
+ let attributes = output.attributes(at: sentinel.location, effectiveRange: nil)
+ guard typesetsMath, !span.isLiteralProtect else {
+ return MathResolution(
+ text: NSAttributedString(string: span.source, attributes: attributes),
+ centered: false)
+ }
+ let blockShaped = span.mode == .display || Self.isBlockShaped(span.latex)
+ let alone = blockShaped && Self.isAloneInParagraph(output, sentinel: sentinel)
+ let mode: MathRenderMode = span.mode == .display || alone ? .display : .inline
+ let font = attributes[.font] as? NSFont
+ ?? NSFont.systemFont(ofSize: NSFont.systemFontSize)
+ let tint = attributes[.foregroundColor] as? NSColor ?? .labelColor
+ guard let render = typesetter.render(
+ latex: MathCommandNormalizer.normalize(span.latex),
+ fontSize: font.pointSize,
+ tint: tint,
+ mode: mode) else {
+ return MathResolution(
+ text: NSAttributedString(string: span.source, attributes: attributes),
+ centered: false)
+ }
+ let attachment = MathAttachment(latexSource: span.source)
+ // A stored property is not in the accessibility tree; the image is.
+ // The typesetter memoises by latex, size, and tint, so two spans
+ // written with different delimiters share one image and the second
+ // description overwrote the first for both of them. The attachment
+ // takes its own handle on the same drawing instead.
+ let image = render.image.copy() as? NSImage ?? render.image
+ image.accessibilityDescription = span.source
+ attachment.image = image
+ attachment.bounds = CGRect(
+ x: 0,
+ y: -render.descent,
+ width: image.size.width,
+ height: image.size.height)
+ let replacement = NSMutableAttributedString(
+ string: "\u{FFFC}",
+ attributes: attributes)
+ replacement.addAttribute(
+ .attachment,
+ value: attachment,
+ range: NSRange(location: 0, length: replacement.length))
+ return MathResolution(text: replacement, centered: alone)
}
+ /// Inline environments and hard row breaks are block notation wearing
+ /// inline delimiters: Gemma writes `$\begin{cases} ... \end{cases}$`.
+ private static func isBlockShaped(_ latex: String) -> Bool {
+ latex.contains("\\begin{aligned}")
+ || latex.contains("\\begin{cases}")
+ || latex.contains("\\\\")
+ }
+
+ /// Paragraph styles are per-paragraph in AppKit, so centring is only safe
+ /// when the equation is the whole paragraph. A cell or code container owns
+ /// its own style through `textBlocks` and keeps it.
+ private static func isAloneInParagraph(
+ _ output: NSAttributedString,
+ sentinel: NSRange
+ ) -> Bool {
+ let text = output.string as NSString
+ let paragraph = text.paragraphRange(for: sentinel)
+ let before = text.substring(with: NSRange(
+ location: paragraph.location,
+ length: sentinel.location - paragraph.location))
+ let after = text.substring(with: NSRange(
+ location: sentinel.upperBound,
+ length: max(0, paragraph.upperBound - sentinel.upperBound)))
+ guard before.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ after.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
+ return false
+ }
+ let style = output.attribute(
+ .paragraphStyle,
+ at: sentinel.location,
+ effectiveRange: nil) as? NSParagraphStyle
+ return style?.textBlocks.isEmpty ?? true
+ }
+
+ private func center(_ range: NSRange, in output: NSMutableAttributedString) {
+ guard range.length > 0 else { return }
+ let existing = output.attribute(
+ .paragraphStyle,
+ at: range.location,
+ effectiveRange: nil) as? NSParagraphStyle
+ let style = (existing?.mutableCopy() as? NSMutableParagraphStyle)
+ ?? NSMutableParagraphStyle()
+ style.alignment = .center
+ output.addAttribute(.paragraphStyle, value: style, range: range)
+ }
+
+ /// True when the answer ends inside a fenced block the model never closed.
+ /// Counting ```` ``` ```` delimiters instead read a single mid-line run as
+ /// an unclosed fence and sent a whole styled answer — heading, table and
+ /// all — to raw source.
private func requiresRawFallback(_ source: String) -> Bool {
- let fenceCount = source.components(separatedBy: "```").count - 1
- if !fenceCount.isMultiple(of: 2) { return true }
- if source.range(
- of: #"</?[A-Za-z][^>]*>"#,
- options: .regularExpression) != nil {
- return true
+ var open: FenceLine.Run?
+ for line in source.split(separator: "\n", omittingEmptySubsequences: false) {
+ guard let run = FenceLine.run(line) else { continue }
+ guard let current = open else {
+ open = run
+ continue
+ }
+ if run.closes(marker: current.marker, length: current.length) { open = nil }
}
- return source.range(
- of: #"!\[[^\]]*\]\([^\)]*\)"#,
- options: .regularExpression) != nil
+ return open != nil
}
private func containsUnsupportedBlock(in parsed: AttributedString) -> Bool {
parsed.runs.contains { run in
- run.presentationIntent?.components.contains { component in
- switch component.kind {
- case .table, .tableHeaderRow, .tableRow, .tableCell:
- return true
- default:
- return false
+ run.inlinePresentationIntent?.contains(.blockHTML) == true
+ || Self.isEnclosedTable(run.presentationIntent)
+ }
+ }
+
+ /// A table nested in a quote or a list item. The cell walk owns the
+ /// paragraph style through `textBlocks`, so the enclosing indent, bar, and
+ /// marker are all lost and the rows draw as a bare table hanging in the
+ /// message. Raw fallback keeps the content with its markers instead;
+ /// rendering the nesting properly is separate work.
+ private static func isEnclosedTable(_ intent: PresentationIntent?) -> Bool {
+ guard let components = intent?.components else { return false }
+ var table = false
+ var enclosing = false
+ for component in components {
+ switch component.kind {
+ case .table: table = true
+ case .blockQuote, .orderedList, .unorderedList, .listItem: enclosing = true
+ default: break
+ }
+ }
+ return table && enclosing
+ }
+
+ /// A bold-only line is how models write a heading they did not mark up.
+ /// Giving it its own paragraph is what keeps the line under it from
+ /// joining it, but a fenced listing is the one block whose bytes have to
+ /// survive this pass exactly: promoting a `**Note**` line inside code
+ /// inserted a blank line the model never wrote, so the finalize render
+ /// stopped matching the bytes the stream had already drawn.
+ private static func promotingBoldHeadings(_ source: String) -> String {
+ let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
+ var segments: [(lines: [Substring], isCode: Bool)] = []
+ var fence: FenceLine.Run?
+ for line in lines {
+ let run = FenceLine.run(line)
+ let isCode: Bool
+ if let open = fence {
+ isCode = true
+ if let run, run.closes(marker: open.marker, length: open.length) {
+ fence = nil
}
- } == true
+ } else if let run {
+ isCode = true
+ fence = run
+ } else {
+ isCode = false
+ }
+ if segments.last?.isCode == isCode {
+ segments[segments.count - 1].lines.append(line)
+ } else {
+ segments.append(([line], isCode))
+ }
}
+ return segments.map { segment in
+ let text = segment.lines.joined(separator: "\n")
+ guard !segment.isCode else { return text }
+ return text.replacingOccurrences(
+ of: #"(?m)^([ \t]*\*\*[^*\n]+\*\*[ \t]*)\n(?=\S)"#,
+ with: "$1\n\n",
+ options: .regularExpression)
+ }.joined(separator: "\n")
}
private func block(for intent: PresentationIntent?) -> Block {
@@ -131,10 +417,12 @@ public struct ResponseMarkdownRenderer {
var code = false
var quote = false
var thematicBreak = false
- var ordinal: Int?
- var ordered = false
- var unordered = false
var listDepth = 0
+ var tableIdentity: Int?
+ var tableColumns: [PresentationIntent.TableColumn] = []
+ var tableRow: Int?
+ var tableColumn: Int?
+ var isHeaderRow = false
for component in components {
switch component.kind {
@@ -142,17 +430,38 @@ public struct ResponseMarkdownRenderer {
case .codeBlock: code = true
case .blockQuote: quote = true
case .thematicBreak: thematicBreak = true
- case .listItem(let itemOrdinal): ordinal = itemOrdinal
- case .orderedList:
- ordered = true
- listDepth += 1
- case .unorderedList:
- unordered = true
+ case .orderedList, .unorderedList:
listDepth += 1
+ case .table(let columns):
+ tableIdentity = component.identity
+ tableColumns = columns
+ case .tableHeaderRow:
+ isHeaderRow = true
+ tableRow = 0
+ case .tableRow(let index):
+ tableRow = index
+ case .tableCell(let index):
+ tableColumn = index
default: break
}
}
+ if let tableIdentity, let tableRow, let tableColumn {
+ let alignment = tableColumn < tableColumns.count
+ ? Self.alignment(for: tableColumns[tableColumn].alignment)
+ : NSTextAlignment.natural
+ return Block(
+ identity: leaf.identity,
+ kind: .tableCell(TableCell(
+ table: tableIdentity,
+ columns: tableColumns.count,
+ row: tableRow,
+ column: tableColumn,
+ isHeader: isHeaderRow,
+ alignment: alignment)))
+ }
+
+ let marker = Self.innermostListMarker(components)
let kind: BlockKind
if thematicBreak {
kind = .thematicBreak
@@ -160,9 +469,9 @@ public struct ResponseMarkdownRenderer {
kind = .heading(headingLevel)
} else if code {
kind = .code
- } else if ordered, let ordinal {
- kind = .orderedList(ordinal: ordinal, indent: max(0, listDepth - 1))
- } else if unordered {
+ } else if let marker, marker.isOrdered {
+ kind = .orderedList(ordinal: marker.ordinal, indent: max(0, listDepth - 1))
+ } else if marker != nil {
kind = .unorderedList(indent: max(0, listDepth - 1))
} else if quote {
kind = .quote
@@ -172,6 +481,43 @@ public struct ResponseMarkdownRenderer {
return Block(identity: leaf.identity, kind: kind)
}
+ /// The marker a nested item actually wears. `components` runs
+ /// innermost-first, so the item is the first `listItem` in the array and
+ /// its list is the first list container after it. Reading the whole array
+ /// last-write-wins handed every item the *outermost* list's kind and
+ /// ordinal, so a bullet under an ordered item rendered as a number and
+ /// every nested ordered item repeated its parent's ordinal as "1. 1.".
+ private static func innermostListMarker(
+ _ components: [PresentationIntent.IntentType]
+ ) -> (ordinal: Int, isOrdered: Bool)? {
+ guard let item = components.firstIndex(where: {
+ if case .listItem = $0.kind { return true }
+ return false
+ }) else {
+ return nil
+ }
+ guard case .listItem(let ordinal) = components[item].kind else { return nil }
+ for component in components[(item + 1)...] {
+ switch component.kind {
+ case .orderedList: return (ordinal, true)
+ case .unorderedList: return (ordinal, false)
+ default: continue
+ }
+ }
+ return nil
+ }
+
+ private static func alignment(
+ for column: PresentationIntent.TableColumn.Alignment?
+ ) -> NSTextAlignment {
+ switch column {
+ case .left: .left
+ case .center: .center
+ case .right: .right
+ default: .natural
+ }
+ }
+
private func appendSeparator(
to output: NSMutableAttributedString,
previous: Block?,
@@ -179,56 +525,348 @@ public struct ResponseMarkdownRenderer {
) {
guard let previous else { return }
let adjacentListItems = previous.kind.isList && next.kind.isList
- let requiredNewlines = adjacentListItems ? 1 : 2
+ let sameTable = previous.kind.tableIdentity != nil
+ && previous.kind.tableIdentity == next.kind.tableIdentity
+ let requiredNewlines = adjacentListItems || sameTable ? 1 : 2
let trailingNewlines = output.string.reversed().prefix { $0 == "\n" }.count
- guard trailingNewlines < requiredNewlines else { return }
- output.append(NSAttributedString(
- string: String(repeating: "\n", count: requiredNewlines - trailingNewlines),
- attributes: baseAttributes()))
+ output.append(separator(
+ trailingNewlines: trailingNewlines,
+ required: requiredNewlines))
+ }
+
+ /// What the whole-document walk puts between two top-level blocks. The
+ /// progressive render appends one block at a time and has to reproduce it
+ /// exactly, or a streamed answer would not match its own finalize pass.
+ public func blockSeparator(trailingNewlines: Int) -> NSAttributedString {
+ separator(trailingNewlines: trailingNewlines, required: 2)
+ }
+
+ private func separator(trailingNewlines: Int, required: Int) -> NSAttributedString {
+ let missing = required - max(0, trailingNewlines)
+ guard missing > 0 else { return NSAttributedString() }
+ return NSAttributedString(
+ string: String(repeating: "\n", count: missing),
+ attributes: baseAttributes())
+ }
+
+ private func append(
+ _ items: [Item],
+ block: Block,
+ to output: NSMutableAttributedString,
+ decoration: BlockDecoration
+ ) {
+ if block.kind == .thematicBreak {
+ output.append(NSAttributedString(
+ string: "────────────────",
+ attributes: attributes(block: block)))
+ return
+ }
+ if block.kind == .code {
+ appendCode(
+ items.map(\.text).joined(),
+ block: block,
+ to: output,
+ decoration: decoration)
+ return
+ }
+ var cellStyle: NSParagraphStyle?
+ if case .tableCell(let cell) = block.kind {
+ cellStyle = tableCellStyle(cell, decoration: decoration)
+ }
+
+ var texts = items.map(\.text)
+ var taskGlyph: String?
+ if block.kind.isList,
+ let first = texts.first,
+ let glyph = Self.taskMarker(first) {
+ taskGlyph = glyph
+ texts[0] = String(first.dropFirst(Self.taskMarkerLength))
+ }
+ let prefix = self.prefix(for: block.kind, taskGlyph: taskGlyph)
+ if !prefix.isEmpty {
+ output.append(NSAttributedString(
+ string: prefix,
+ attributes: attributes(block: block)))
+ }
+
+ var html = InlineHTMLState()
+ for (item, text) in zip(items, texts) {
+ if item.inlineIntent?.contains(.inlineHTML) == true {
+ appendInlineHTML(
+ text,
+ state: &html,
+ block: block,
+ paragraphStyle: cellStyle,
+ to: output)
+ continue
+ }
+ guard !text.isEmpty else { continue }
+ var values = attributes(
+ inlineIntent: item.inlineIntent,
+ link: item.link ?? item.imageURL,
+ html: html.style,
+ block: block)
+ if let cellStyle { values[.paragraphStyle] = cellStyle }
+ output.append(NSAttributedString(string: text, attributes: values))
+ }
+ // A markdown cell is one paragraph terminated by a newline, so math
+ // sentinels, inline HTML, and wrapping all behave as they do elsewhere.
+ // An empty cell is that terminator and nothing else.
+ guard let cellStyle else { return }
+ var terminator = attributes(block: block)
+ terminator[.paragraphStyle] = cellStyle
+ output.append(NSAttributedString(string: "\n", attributes: terminator))
+ }
+
+ /// Inline HTML runs carry the tag text itself. A recognised tag becomes an
+ /// attribute on the runs it encloses and its text is dropped; anything
+ /// else is shown as written, because the parser reports `Vec<String>` and
+ /// `x < y` as inline HTML too and deleting them lost the reader's words.
+ private func appendInlineHTML(
+ _ text: String,
+ state: inout InlineHTMLState,
+ block: Block,
+ paragraphStyle: NSParagraphStyle? = nil,
+ to output: NSMutableAttributedString
+ ) {
+ if let tokens = Self.tagTokens(text) {
+ for token in tokens {
+ guard let tag = InlineHTMLTag(rawValue: token.name) else {
+ var values = attributes(html: state.style, block: block)
+ if let paragraphStyle { values[.paragraphStyle] = paragraphStyle }
+ output.append(NSAttributedString(string: "\u{2028}", attributes: values))
+ continue
+ }
+ if token.isClosing {
+ state.close(tag)
+ } else {
+ state.open(tag)
+ }
+ }
+ return
+ }
+ guard !text.isEmpty else { return }
+ var values = attributes(html: state.style, block: block)
+ if let paragraphStyle { values[.paragraphStyle] = paragraphStyle }
+ output.append(NSAttributedString(string: text, attributes: values))
}
- private func appendPrefix(for block: BlockKind, to output: NSMutableAttributedString) {
- let prefix: String
+ private struct TableShape {
+ var columns = 0
+ var lastRow = 0
+ /// Taken from the cells that do exist. A table's header row is always
+ /// complete, so every column is covered.
+ var alignments: [Int: NSTextAlignment] = [:]
+ }
+
+ /// Fills in the cells the parser never reported.
+ ///
+ /// Foundation emits no run for an empty cell, and none at all for the
+ /// cells a short row never wrote, so no `NSTextTableBlock` was created for
+ /// those positions: a three-column table came back with blocks at
+ /// (0,0..2), (1,0), (1,1), (2,0), (2,2), (3,0), (3,1) and TextKit laid
+ /// every body row out with the wrong column count. An all-empty last row
+ /// still cannot be recovered — the parser reports nothing for it at all.
+ private static func completingTables(_ items: [Item]) -> [Item] {
+ var shapes: [Int: TableShape] = [:]
+ for item in items {
+ guard case .tableCell(let cell) = item.block.kind else { continue }
+ var shape = shapes[cell.table] ?? TableShape()
+ shape.columns = max(shape.columns, cell.columns, cell.column + 1)
+ shape.lastRow = max(shape.lastRow, cell.row)
+ shape.alignments[cell.column] = cell.alignment
+ shapes[cell.table] = shape
+ }
+ guard !shapes.isEmpty else { return items }
+
+ var completed: [Item] = []
+ completed.reserveCapacity(items.count)
+ var openTable: Int?
+ var cursor = (row: 0, column: 0)
+ var drawn: (row: Int, column: Int)?
+
+ func fill(to target: (row: Int, column: Int)) {
+ guard let table = openTable, let shape = shapes[table] else { return }
+ while cursor.row < target.row
+ || (cursor.row == target.row && cursor.column < target.column) {
+ completed.append(Item(
+ text: "",
+ inlineIntent: nil,
+ link: nil,
+ imageURL: nil,
+ block: Block(identity: -1, kind: .tableCell(TableCell(
+ table: table,
+ columns: shape.columns,
+ row: cursor.row,
+ column: cursor.column,
+ isHeader: cursor.row == 0,
+ alignment: shape.alignments[cursor.column] ?? .natural)))))
+ cursor = advanced(cursor, columns: shape.columns)
+ }
+ }
+
+ func closeTable() {
+ guard let table = openTable, let shape = shapes[table] else { return }
+ fill(to: (row: shape.lastRow, column: shape.columns))
+ openTable = nil
+ drawn = nil
+ }
+
+ for item in items {
+ guard case .tableCell(let cell) = item.block.kind else {
+ closeTable()
+ completed.append(item)
+ continue
+ }
+ if openTable != cell.table {
+ closeTable()
+ openTable = cell.table
+ cursor = (row: 0, column: 0)
+ }
+ if drawn?.row != cell.row || drawn?.column != cell.column {
+ fill(to: (row: cell.row, column: cell.column))
+ drawn = (row: cell.row, column: cell.column)
+ cursor = advanced(cursor, columns: shapes[cell.table]?.columns ?? cell.columns)
+ }
+ completed.append(item)
+ }
+ closeTable()
+ return completed
+ }
+
+ private static func advanced(
+ _ position: (row: Int, column: Int),
+ columns: Int
+ ) -> (row: Int, column: Int) {
+ position.column + 1 < max(columns, 1)
+ ? (row: position.row, column: position.column + 1)
+ : (row: position.row + 1, column: 0)
+ }
+
+ private func tableCellStyle(
+ _ cell: TableCell,
+ decoration: BlockDecoration
+ ) -> NSParagraphStyle {
+ let style = NSMutableParagraphStyle()
+ style.lineSpacing = 3
+ style.paragraphSpacing = 0
+ style.alignment = cell.alignment
+ style.textBlocks = [decoration.tableCell(
+ table: cell.table,
+ columns: cell.columns,
+ row: cell.row,
+ column: cell.column,
+ isHeader: cell.isHeader)]
+ return style
+ }
+
+ private func appendCode(
+ _ text: String,
+ block: Block,
+ to output: NSMutableAttributedString,
+ decoration: BlockDecoration
+ ) {
+ var body = text
+ if body.hasSuffix("\n") { body.removeLast() }
+ let attributes = codeAttributes(cell: decoration.codeCell(for: block.identity))
+ for line in body.components(separatedBy: "\n") {
+ output.append(NSAttributedString(string: line + "\n", attributes: attributes))
+ }
+ }
+
+ /// Attributes for a fenced block that is still arriving. The caller keeps
+ /// the dictionary for the life of that block: the container is an
+ /// `NSTextTableBlock`, and TextKit only joins consecutive paragraphs into
+ /// one cell when they carry the same block object, so a fresh dictionary
+ /// per tick would draw a new box per line.
+ public func streamingCodeAttributes() -> [NSAttributedString.Key: Any] {
+ codeAttributes(cell: BlockDecoration.codeCell())
+ }
+
+ private func codeAttributes(cell: NSTextTableBlock) -> [NSAttributedString.Key: Any] {
+ let style = NSMutableParagraphStyle()
+ style.lineSpacing = 2
+ style.paragraphSpacing = 0
+ style.textBlocks = [cell]
+ return [
+ .font: font(for: .code, inlineIntent: nil, html: InlineHTMLStyle()),
+ .foregroundColor: NSColor.labelColor,
+ .paragraphStyle: style,
+ ]
+ }
+
+ private static let taskMarkerLength = 4
+
+ private static func taskMarker(_ text: String) -> String? {
+ if text.hasPrefix("[ ] ") { return "\u{2610}" }
+ if text.hasPrefix("[x] ") || text.hasPrefix("[X] ") { return "\u{2611}" }
+ return nil
+ }
+
+ private func prefix(for block: BlockKind, taskGlyph: String?) -> String {
switch block {
case .unorderedList:
- prefix = "•\t"
+ return (taskGlyph ?? "\u{2022}") + "\t"
case .orderedList(let ordinal, _):
- prefix = "\(ordinal).\t"
+ guard let taskGlyph else { return "\(ordinal).\t" }
+ return "\(ordinal).\t\(taskGlyph) "
case .quote:
- prefix = "│\t"
+ return "\u{2502}\t"
default:
- return
+ return ""
}
- output.append(NSAttributedString(
- string: prefix,
- attributes: attributes(inlineIntent: nil, link: nil, block: block)))
}
private func attributes(
- inlineIntent: InlinePresentationIntent?,
- link: URL?,
- block: BlockKind
+ inlineIntent: InlinePresentationIntent? = nil,
+ link: URL? = nil,
+ html: InlineHTMLStyle = InlineHTMLStyle(),
+ block: Block
) -> [NSAttributedString.Key: Any] {
var values = baseAttributes()
- values[.paragraphStyle] = paragraphStyle(for: block)
- values[.font] = font(for: block, inlineIntent: inlineIntent)
+ values[.paragraphStyle] = paragraphStyle(for: block.kind)
+ let font = self.font(for: block.kind, inlineIntent: inlineIntent, html: html)
+ values[.font] = font
- if block == .quote {
+ if block.kind == .quote {
values[.foregroundColor] = NSColor.secondaryLabelColor
}
- if block == .code || inlineIntent?.contains(.code) == true {
- values[.backgroundColor] = NSColor.controlBackgroundColor
+ if inlineIntent?.contains(.code) == true || html.monospaced {
+ values[.backgroundColor] = NSColor.quaternarySystemFill
}
if inlineIntent?.contains(.strikethrough) == true {
values[.strikethroughStyle] = NSUnderlineStyle.single.rawValue
}
- if link != nil {
+ if html.scriptDepth > 0 {
+ values[.baselineOffset] = font.pointSize * 0.34 * CGFloat(html.scriptDirection)
+ }
+ if let link {
+ values[.link] = link
values[.foregroundColor] = NSColor.linkColor
values[.underlineStyle] = NSUnderlineStyle.single.rawValue
}
return values
}
+ private static func imageText(_ text: String, url: URL?) -> String? {
+ guard let url, text.allSatisfy({ $0 == "\u{FFFC}" }) else { return nil }
+ return url.absoluteString
+ }
+
+ /// The destination reaches the text view as a real `.link` now, so a scheme
+ /// this transcript is not willing to open has to arrive as plain text
+ /// instead. `javascript:` and `data:` are the reason; `file:` is the one a
+ /// local model reaches for on its own.
+ private static let openableSchemes: Set<String> = ["http", "https", "mailto"]
+
+ private static func openable(_ url: URL?) -> URL? {
+ guard let url, let scheme = url.scheme?.lowercased(),
+ openableSchemes.contains(scheme) else {
+ return nil
+ }
+ return url
+ }
+
private func baseAttributes() -> [NSAttributedString.Key: Any] {
[
.font: NSFont.systemFont(ofSize: NSFont.systemFontSize),
@@ -239,31 +877,37 @@ public struct ResponseMarkdownRenderer {
private func font(
for block: BlockKind,
- inlineIntent: InlinePresentationIntent?
+ inlineIntent: InlinePresentationIntent?,
+ html: InlineHTMLStyle
) -> NSFont {
- if block == .code || inlineIntent?.contains(.code) == true {
- return NSFont.monospacedSystemFont(
- ofSize: NSFont.systemFontSize - 0.5,
- weight: .regular)
- }
+ let bold = inlineIntent?.contains(.stronglyEmphasized) == true || html.bold
+ || block.isHeaderCell
+ let italic = inlineIntent?.contains(.emphasized) == true || html.italic
+ let monospaced = block == .code
+ || inlineIntent?.contains(.code) == true
+ || html.monospaced
- let size: CGFloat
- let baseWeight: NSFont.Weight
- switch block {
- case .heading(let level):
+ var size: CGFloat
+ var baseWeight: NSFont.Weight
+ if monospaced {
+ size = NSFont.systemFontSize - 0.5
+ baseWeight = .regular
+ } else if case .heading(let level) = block {
size = max(NSFont.systemFontSize + 1, 22 - CGFloat(level - 1) * 2)
baseWeight = .semibold
- default:
+ } else {
size = NSFont.systemFontSize
baseWeight = .regular
}
+ if html.scriptDepth > 0 {
+ size *= pow(0.72, CGFloat(min(html.scriptDepth, 2)))
+ }
- let stronglyEmphasized = inlineIntent?.contains(.stronglyEmphasized) == true
- let emphasized = inlineIntent?.contains(.emphasized) == true
- var font = NSFont.systemFont(
- ofSize: size,
- weight: stronglyEmphasized ? .semibold : baseWeight)
- if emphasized {
+ let weight: NSFont.Weight = bold ? .semibold : baseWeight
+ var font = monospaced
+ ? NSFont.monospacedSystemFont(ofSize: size, weight: weight)
+ : NSFont.systemFont(ofSize: size, weight: weight)
+ if italic {
let descriptor = font.fontDescriptor.withSymbolicTraits(.italic)
font = NSFont(descriptor: descriptor, size: size) ?? font
}
@@ -279,13 +923,6 @@ public struct ResponseMarkdownRenderer {
case .heading:
style.paragraphSpacingBefore = 8
style.paragraphSpacing = 4
- case .code:
- style.firstLineHeadIndent = 10
- style.headIndent = 10
- style.tailIndent = -10
- style.paragraphSpacingBefore = 6
- style.paragraphSpacing = 6
- style.lineSpacing = 2
case .quote:
style.firstLineHeadIndent = 4
style.headIndent = 20
@@ -301,7 +938,9 @@ public struct ResponseMarkdownRenderer {
style.alignment = .center
style.paragraphSpacingBefore = 8
style.paragraphSpacing = 8
- case .paragraph:
+ // A table cell's style comes from `tableCellStyle`, which owns the
+ // text block the cell is drawn in.
+ case .paragraph, .code, .tableCell:
break
}
return style
@@ -315,3 +954,220 @@ public struct ResponseMarkdownRenderer {
usedFallback: true)
}
}
+
+private struct InlineHTMLStyle {
+ var bold = false
+ var italic = false
+ var monospaced = false
+ var scriptDepth = 0
+ /// Superscripts minus subscripts, so nested pairs cancel their offset.
+ var scriptDirection = 0
+}
+
+private enum InlineHTMLTag: String {
+ case b, strong, i, em, code, kbd, sub, sup
+}
+
+private struct InlineHTMLState {
+ private var stack: [InlineHTMLTag] = []
+
+ mutating func open(_ tag: InlineHTMLTag) {
+ stack.append(tag)
+ }
+
+ /// Closing an unbalanced tag drops everything opened after it rather than
+ /// leaving a style that never ends.
+ mutating func close(_ tag: InlineHTMLTag) {
+ guard let index = stack.lastIndex(of: tag) else { return }
+ stack.removeSubrange(index...)
+ }
+
+ var style: InlineHTMLStyle {
+ var style = InlineHTMLStyle()
+ for tag in stack {
+ switch tag {
+ case .b, .strong: style.bold = true
+ case .i, .em: style.italic = true
+ case .code, .kbd: style.monospaced = true
+ case .sub:
+ style.scriptDepth += 1
+ style.scriptDirection -= 1
+ case .sup:
+ style.scriptDepth += 1
+ style.scriptDirection += 1
+ }
+ }
+ return style
+ }
+}
+
+extension ResponseMarkdownRenderer {
+ fileprivate struct HTMLTagToken {
+ let name: String
+ let isClosing: Bool
+ }
+
+ /// Tags this renderer can honour. `br` is the void element; the rest map
+ /// onto `InlineHTMLTag`.
+ fileprivate static let handledTags: Set<String> = [
+ "b", "strong", "i", "em", "code", "kbd", "sub", "sup", "br",
+ ]
+
+ /// The whole run read as complete tags, or nil when any of it is the
+ /// reader's own words.
+ ///
+ /// Reading the leading letters alone made `if a<b then c>d` an opening
+ /// `<b>` tag — which it is, to CommonMark, with two bare attributes — so
+ /// the run was dropped and everything after it went bold. Requiring every
+ /// attribute to carry a value is the one tightening that separates markup
+ /// from prose. A sequence is accepted because Foundation coalesces
+ /// adjacent inline-HTML runs into one.
+ fileprivate static func tagTokens(_ text: String) -> [HTMLTagToken]? {
+ var rest = Substring(text)
+ var tokens: [HTMLTagToken] = []
+ while !rest.isEmpty {
+ guard let token = tagToken(&rest) else { return nil }
+ tokens.append(token)
+ }
+ return tokens.isEmpty ? nil : tokens
+ }
+
+ private static func tagToken(_ rest: inout Substring) -> HTMLTagToken? {
+ var scan = rest
+ guard scan.first == "<" else { return nil }
+ scan = scan.dropFirst()
+ let isClosing = scan.first == "/"
+ if isClosing { scan = scan.dropFirst() }
+ let name = scan.prefix { $0.isLetter || $0.isNumber }.lowercased()
+ guard handledTags.contains(name) else { return nil }
+ // A closing `</br>` is not a tag this renderer can honour; the reader
+ // sees what the model wrote.
+ guard !isClosing || name != "br" else { return nil }
+ scan = scan.dropFirst(name.count)
+
+ var selfClosing = false
+ while true {
+ let spaces = scan.prefix(while: isTagSpace)
+ scan = scan.dropFirst(spaces.count)
+ guard let next = scan.first else { return nil }
+ if next == ">" {
+ scan = scan.dropFirst()
+ break
+ }
+ if next == "/" {
+ scan = scan.dropFirst()
+ guard scan.first == ">" else { return nil }
+ scan = scan.dropFirst()
+ selfClosing = true
+ break
+ }
+ guard !isClosing, !spaces.isEmpty, consumeAttribute(&scan) else { return nil }
+ }
+ // `<br/>` is a void element. `<b/>` is a formatting tag that closes
+ // nothing, so it is shown rather than silently dropped.
+ guard !selfClosing || name == "br" else { return nil }
+ rest = scan
+ return HTMLTagToken(name: name, isClosing: isClosing)
+ }
+
+ private static func consumeAttribute(_ scan: inout Substring) -> Bool {
+ let name = scan.prefix {
+ $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" || $0 == ":"
+ }
+ guard !name.isEmpty else { return false }
+ var rest = scan.dropFirst(name.count).drop(while: isTagSpace)
+ guard rest.first == "=" else { return false }
+ rest = rest.dropFirst().drop(while: isTagSpace)
+ guard let quote = rest.first else { return false }
+ if quote == "\"" || quote == "'" {
+ rest = rest.dropFirst()
+ guard let end = rest.firstIndex(of: quote) else { return false }
+ rest = rest[rest.index(after: end)...]
+ } else {
+ let value = rest.prefix { !isTagSpace($0) && $0 != ">" && $0 != "/" }
+ guard !value.isEmpty else { return false }
+ rest = rest.dropFirst(value.count)
+ }
+ scan = rest
+ return true
+ }
+
+ private static func isTagSpace(_ character: Character) -> Bool {
+ character == " " || character == "\t" || character == "\n" || character == "\r"
+ }
+}
+
+/// Owns the `NSTextTable` instances a render pass creates. TextKit 1 groups
+/// consecutive paragraphs into one cell only when they share the same
+/// `NSTextBlock` object, so the table must outlive the individual paragraph
+/// styles that reference it.
+@MainActor
+private final class BlockDecoration {
+ private var codeCells: [Int: NSTextTableBlock] = [:]
+ private var tables: [Int: NSTextTable] = [:]
+ private var tableCells: [TableCellKey: NSTextTableBlock] = [:]
+
+ struct TableCellKey: Hashable {
+ let table: Int
+ let row: Int
+ let column: Int
+ }
+
+ static func codeCell() -> NSTextTableBlock {
+ let table = NSTextTable()
+ table.numberOfColumns = 1
+ table.collapsesBorders = true
+ let cell = NSTextTableBlock(
+ table: table,
+ startingRow: 0,
+ rowSpan: 1,
+ startingColumn: 0,
+ columnSpan: 1)
+ cell.setContentWidth(100, type: .percentageValueType)
+ cell.setWidth(8, type: .absoluteValueType, for: .padding)
+ cell.setWidth(1, type: .absoluteValueType, for: .border)
+ cell.setBorderColor(.separatorColor)
+ cell.backgroundColor = .quaternarySystemFill
+ return cell
+ }
+
+ func codeCell(for identity: Int) -> NSTextTableBlock {
+ if let existing = codeCells[identity] { return existing }
+ let cell = Self.codeCell()
+ codeCells[identity] = cell
+ return cell
+ }
+
+ func tableCell(
+ table identity: Int,
+ columns: Int,
+ row: Int,
+ column: Int,
+ isHeader: Bool
+ ) -> NSTextTableBlock {
+ let key = TableCellKey(table: identity, row: row, column: column)
+ if let existing = tableCells[key] { return existing }
+ let table = self.table(for: identity, columns: columns)
+ let cell = NSTextTableBlock(
+ table: table,
+ startingRow: row,
+ rowSpan: 1,
+ startingColumn: column,
+ columnSpan: 1)
+ cell.setWidth(6, type: .absoluteValueType, for: .padding)
+ cell.setWidth(1, type: .absoluteValueType, for: .border)
+ cell.setBorderColor(.separatorColor)
+ if isHeader { cell.backgroundColor = .quaternarySystemFill }
+ tableCells[key] = cell
+ return cell
+ }
+
+ private func table(for identity: Int, columns: Int) -> NSTextTable {
+ if let existing = tables[identity] { return existing }
+ let table = NSTextTable()
+ table.numberOfColumns = columns
+ table.collapsesBorders = true
+ tables[identity] = table
+ return table
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/TailAutoClose.swift b/Sources/TurboFieldfareApp/MacPresentation/TailAutoClose.swift
new file mode 100644
index 00000000..62cb4761
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/TailAutoClose.swift
@@ -0,0 +1,382 @@
+import Foundation
+
+/// Closes the syntax the model has opened but not yet finished, so the block
+/// being written can go through the markdown pass instead of sitting there as
+/// raw source until its closing marker arrives.
+///
+/// Display only. The response string itself is never touched: copy actions,
+/// `plainText`, and the finalize render all keep reading the real bytes.
+///
+/// Two rules decide every case here. A marker that has content after it is
+/// closed, because the reader is already looking at the styled text and only
+/// the closer is missing. A marker with nothing after it is removed instead,
+/// because closing `**` with `**` writes `****`, which is new structure rather
+/// than the emphasis the model is about to open.
+enum TailAutoClose {
+ /// U+200B. Breaks the "only `-` or `=`" rule that would otherwise turn the
+ /// line above a half-typed rule into a setext heading for one tick.
+ static let setextGuard: Character = "\u{200B}"
+
+ /// - Parameter typesetsMath: whether the caller is going to typeset the
+ /// result. An unfinished `$$` is only worth closing for a pass that turns
+ /// it into an equation; a pass that keeps the LaTeX as source would just
+ /// show two dollars the model never wrote.
+ static func close(_ tail: String, typesetsMath: Bool = true) -> String {
+ guard !tail.isEmpty else { return tail }
+ if let fence = unclosedFence(tail) {
+ var closed = tail
+ if !closed.hasSuffix("\n") { closed.append("\n") }
+ closed.append(fence.closerPrefix)
+ closed.append(String(repeating: fence.run.character, count: fence.run.length))
+ return closed
+ }
+ var text = strippingIncompleteTag(tail)
+ text = flatteningIncompleteLink(text)
+ text = balancingInlineMarkers(text, typesetsMath: typesetsMath)
+ return guardingSetextRule(text)
+ }
+
+ // MARK: - Fences
+
+ private struct OpenFence {
+ let run: FenceLine.Run
+ /// Content column of the item the fence was opened in.
+ let containerIndent: Int
+ /// What a closing line needs in front of the marker to be read as this
+ /// fence's closer. Written flush left instead, the parser reads it as
+ /// prose after the item and the listing keeps its markers on screen.
+ let closerPrefix: String
+ }
+
+ /// The fence a tail ends inside, if any. Nothing inside a fenced block is
+ /// markdown, so this case returns before every other rule.
+ private static func unclosedFence(_ text: String) -> OpenFence? {
+ var open: OpenFence?
+ var column = 0
+ for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
+ let quote = ContainerPrefix.strippingQuoteMarkers(line)
+ if let current = open {
+ if let run = FenceLine.run(quote.rest, containerIndent: current.containerIndent),
+ run.closes(marker: current.run.marker, length: current.run.length) {
+ open = nil
+ }
+ continue
+ }
+ if let item = ContainerPrefix.listItem(quote.rest),
+ item.markerIndent < column || column == 0 {
+ column = item.contentColumn
+ }
+ guard let run = FenceLine.run(quote.rest, containerIndent: column) else { continue }
+ open = OpenFence(
+ run: run,
+ containerIndent: column,
+ closerPrefix: String(repeating: "> ", count: quote.depth)
+ + String(repeating: " ", count: run.indent))
+ }
+ return open
+ }
+
+ // MARK: - Trailing fragments
+
+ /// A tag the model is still typing is markup the reader should not see.
+ /// The remainder has to look like a bare tag name — `a < b` in prose ends
+ /// in an unclosed `<` too, and cutting the sentence there would be worse
+ /// than showing it.
+ private static func strippingIncompleteTag(_ text: String) -> String {
+ guard let open = text.lastIndex(of: "<") else { return text }
+ var rest = text[text.index(after: open)...]
+ if rest.first == "/" { rest = rest.dropFirst() }
+ guard let first = rest.first, first.isLetter else { return text }
+ guard rest.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "-" }) else { return text }
+ return String(text[text.startIndex..<open])
+ }
+
+ /// `[label](https://exa` renders as its label until the destination is
+ /// complete. Leaving it alone shows the raw destination mid-sentence.
+ private static func flatteningIncompleteLink(_ text: String) -> String {
+ guard let paren = text.range(of: "](", options: .backwards) else { return text }
+ guard !text[paren.upperBound...].contains(")") else { return text }
+ guard !text[paren.upperBound...].contains("\n") else { return text }
+ guard let bracket = text.range(of: "[", options: .backwards, range: text.startIndex..<paren.lowerBound)
+ else {
+ return text
+ }
+ let label = String(text[bracket.upperBound..<paren.lowerBound])
+ var head = String(text[text.startIndex..<bracket.lowerBound])
+ if head.hasSuffix("!") {
+ head.removeLast()
+ }
+ return head + label
+ }
+
+ /// A trailing `---` or `===` line promotes the line above it to a setext
+ /// heading the moment it appears, and demotes it again when the next
+ /// character lands. The guard character keeps the paragraph a paragraph.
+ private static func guardingSetextRule(_ text: String) -> String {
+ let lines = text.components(separatedBy: "\n")
+ guard lines.count >= 2, let last = lines.last, !last.isEmpty else { return text }
+ let trimmed = last.trimmingCharacters(in: CharacterSet(charactersIn: " \t\r"))
+ guard !trimmed.isEmpty else { return text }
+ let marker = trimmed.first
+ guard marker == "-" || marker == "=", trimmed.allSatisfy({ $0 == marker }) else {
+ return text
+ }
+ let previous = lines[lines.count - 2].trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !previous.isEmpty else { return text }
+ return text + String(setextGuard)
+ }
+
+ // MARK: - Inline markers
+
+ private enum Marker {
+ case code(length: Int)
+ case displayMath
+ case strong(Character)
+ case emphasis(Character)
+
+ var closer: String {
+ switch self {
+ case .code(let length): String(repeating: "`", count: length)
+ case .displayMath: "$$"
+ case .strong(let character): String(repeating: character, count: 2)
+ case .emphasis(let character): String(character)
+ }
+ }
+ }
+
+ private struct Opening {
+ let marker: Marker
+ let start: Int
+ let end: Int
+ }
+
+ /// Walks the tail once, keeping a stack of what is open. Order matters:
+ /// text after an unterminated backtick is code, and text after an
+ /// unterminated `$$` is math, so neither can hold live emphasis. Closing
+ /// the stack in reverse produces the right nesting.
+ ///
+ /// The walk is over the detector's own units, with its code and equation
+ /// masks: `$x_{1}$` in a sentence is an equation, and the `_` inside it is
+ /// a subscript. Per-line state is carried rather than rescanned — the old
+ /// pass re-read the line from its start for every marker on it, which is
+ /// quadratic in the line and measured 164 ms a tick on an 8 KB paragraph.
+ private static func balancingInlineMarkers(
+ _ text: String,
+ typesetsMath: Bool
+ ) -> String {
+ let protection = MathSpanDetector.tailProtection(text)
+ let units = protection.units
+ var stack: [Opening] = []
+ var index = 0
+ var lineHasContent = false
+ var lineIsThematicBreak = isThematicBreakLine(units, from: 0)
+
+ while index < units.count {
+ let character = units[index]
+ if character == "\n" {
+ index += 1
+ lineHasContent = false
+ lineIsThematicBreak = isThematicBreakLine(units, from: index)
+ continue
+ }
+ let hadContent = lineHasContent
+ if character != " ", character != "\t", character != "\r" {
+ lineHasContent = true
+ }
+ if protection.masked[index] {
+ index += 1
+ continue
+ }
+ // Everything from an unclosed inline opener on is the equation the
+ // model is still writing.
+ if let dollar = protection.openInlineDollar, index >= dollar {
+ index += 1
+ continue
+ }
+ if character == "\\" {
+ // A backslash is literal inside code; outside it, it escapes
+ // the character after it.
+ if case .code? = stack.last?.marker {
+ index += 1
+ } else {
+ index += min(2, units.count - index)
+ }
+ continue
+ }
+ if character == "`" {
+ var end = index
+ while end < units.count, units[end] == "`" { end += 1 }
+ if case .code(let length)? = stack.last?.marker {
+ if end - index == length { stack.removeLast() }
+ } else if end >= units.count || !units[end].isWhitespace {
+ // "Press the ` key" is prose: a run followed by whitespace
+ // is not the start of a code span, and closing it would
+ // style the rest of the sentence as code while it is the
+ // open tail. Closers stay unconditional above.
+ stack.append(Opening(
+ marker: .code(length: end - index),
+ start: index,
+ end: end))
+ }
+ index = end
+ continue
+ }
+ if case .code? = stack.last?.marker {
+ index += 1
+ continue
+ }
+ if character == "$", index + 1 < units.count, units[index + 1] == "$" {
+ let end = index + 2
+ if case .displayMath? = stack.last?.marker {
+ stack.removeLast()
+ } else if typesetsMath, !hadContent {
+ // Single `$` is never closed — the ambiguity with currency
+ // is exactly the bug every surveyed chat UI reports — so
+ // only a `$$` that starts its own line counts as an opener.
+ stack.append(Opening(marker: .displayMath, start: index, end: end))
+ }
+ index = end
+ continue
+ }
+ if case .displayMath? = stack.last?.marker {
+ index += 1
+ continue
+ }
+ if character == "*" || character == "_" {
+ index = consumeEmphasis(
+ units,
+ at: index,
+ marker: character,
+ lineHasContent: hadContent,
+ lineIsThematicBreak: lineIsThematicBreak,
+ stack: &stack)
+ continue
+ }
+ index += 1
+ }
+
+ // A marker with nothing after it is the model mid-keystroke, not an
+ // opener the reader has already seen content for.
+ var cut = units.count
+ while let last = stack.last, last.end == units.count, last.start < cut {
+ cut = last.start
+ stack.removeLast()
+ }
+ let body = cut == units.count ? text : String(units[0..<cut])
+ guard let innermost = stack.last else { return body }
+ var closers = stack.dropLast().reversed().map(\.marker.closer).joined()
+ // The first half of a `$$` closer is already on screen; completing it
+ // with another pair would leave a stray dollar behind.
+ if case .displayMath = innermost.marker, body.hasSuffix("$"), !body.hasSuffix("$$") {
+ closers = "$" + closers
+ } else {
+ closers = innermost.marker.closer + closers
+ }
+ return body + closers
+ }
+
+ private static func consumeEmphasis(
+ _ units: [Character],
+ at index: Int,
+ marker: Character,
+ lineHasContent: Bool,
+ lineIsThematicBreak: Bool,
+ stack: inout [Opening]
+ ) -> Int {
+ var end = index
+ while end < units.count, units[end] == marker { end += 1 }
+ // A bullet and a thematic break are block structure; closing them
+ // would turn a list into bold text.
+ if lineIsThematicBreak { return end }
+ if end - index == 1, !lineHasContent,
+ end >= units.count || units[end] == " " || units[end] == "\t" {
+ return end
+ }
+
+ let before: Character? = index > 0 ? units[index - 1] : nil
+ let after: Character? = end < units.count ? units[end] : nil
+ // CommonMark 0.31 flanking, with two deliberate deviations. A `*`
+ // between word characters is multiplication or a glob, never emphasis,
+ // so `2*3` and `x**2` neither open nor close. And `x *= 2` is an
+ // operator that reads as left-flanking only because `=` is punctuation;
+ // closing it would italicise the rest of the line.
+ if marker == "*", isWord(before), isWord(after) { return end }
+ let beforeWhitespace = before?.isWhitespace ?? true
+ let afterWhitespace = after?.isWhitespace ?? true
+ let beforePunctuation = before.map(isPunctuation) ?? false
+ let afterPunctuation = after.map(isPunctuation) ?? false
+ let leftFlanking = !afterWhitespace
+ && (!afterPunctuation || beforeWhitespace || beforePunctuation)
+ let rightFlanking = !beforeWhitespace
+ && (!beforePunctuation || afterWhitespace || afterPunctuation)
+ var canOpen = leftFlanking && after != "="
+ var canClose = rightFlanking
+ if marker == "_" {
+ // `snake_case` is not emphasis: an intraword underscore neither
+ // opens nor closes.
+ canOpen = leftFlanking && (!rightFlanking || beforePunctuation)
+ canClose = rightFlanking && (!leftFlanking || afterPunctuation)
+ }
+
+ var remaining = end - index
+ var cursor = index
+ while remaining > 0 {
+ let width = remaining >= 2 ? 2 : 1
+ let wanted: Marker = width == 2 ? .strong(marker) : .emphasis(marker)
+ if canClose, matches(stack.last?.marker, wanted) {
+ stack.removeLast()
+ } else if canOpen || end >= units.count {
+ // A run that ends the tail has nothing to emphasise yet. It is
+ // pushed so the trailing-marker rule can drop it instead of
+ // leaving the asterisks on screen.
+ stack.append(Opening(marker: wanted, start: cursor, end: end))
+ }
+ cursor += width
+ remaining -= width
+ }
+ return end
+ }
+
+ private static func isPunctuation(_ character: Character) -> Bool {
+ character.isPunctuation || character.isSymbol
+ }
+
+ /// Computed once per line, and it stops at the first character that is not
+ /// the rule's own marker.
+ private static func isThematicBreakLine(_ units: [Character], from start: Int) -> Bool {
+ var marker: Character?
+ var count = 0
+ var index = start
+ while index < units.count, units[index] != "\n" {
+ let character = units[index]
+ if character == " " || character == "\t" || character == "\r" {
+ index += 1
+ continue
+ }
+ if let marker {
+ guard character == marker else { return false }
+ } else {
+ guard character == "*" || character == "-" || character == "_" else {
+ return false
+ }
+ marker = character
+ }
+ count += 1
+ index += 1
+ }
+ return count >= 3
+ }
+
+ private static func isWord(_ character: Character?) -> Bool {
+ guard let character else { return false }
+ return character.isLetter || character.isNumber
+ }
+
+ private static func matches(_ open: Marker?, _ wanted: Marker) -> Bool {
+ switch (open, wanted) {
+ case (.strong(let a), .strong(let b)): a == b
+ case (.emphasis(let a), .emphasis(let b)): a == b
+ default: false
+ }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift
new file mode 100644
index 00000000..d3cb0f99
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift
@@ -0,0 +1,138 @@
+import AppKit
+import Foundation
+
+/// The transcript's text projection. A typeset equation occupies one
+/// object-replacement character and carries its LaTeX on the attachment, so
+/// anything that reads the string back — a pasteboard flavour, an
+/// accessibility client, the renderer's own `plainText` — has to put the
+/// source back or hand out U+FFFC where the equation was.
+public enum TranscriptPlainText {
+ public static func string(of attributed: NSAttributedString) -> String {
+ let characters = attributed.string as NSString
+ var text = ""
+ attributed.enumerateAttribute(
+ .attachment,
+ in: NSRange(location: 0, length: attributed.length),
+ options: []) { value, range, _ in
+ if let attachment = value as? MathAttachment {
+ text += attachment.latexSource
+ } else {
+ text += characters.substring(with: range)
+ }
+ }
+ return text
+ }
+
+ /// The same projection kept as an attributed string: each typeset equation
+ /// becomes its LaTeX carrying the run's own attributes, and every other
+ /// attachment — an image in the prompt strip — is left where it is.
+ ///
+ /// Every rich flavour is serialised from this copy. AppKit rasterises an
+ /// attachment that has no file wrapper, so Cmd-C on a fifty-equation answer
+ /// wrote a 12.3 MB RTFD of fifty TIFFs and logged a hundred
+ /// `CGImageDestinationFinalize` lines, while the RTF flavour, which cannot
+ /// carry attachments at all, dropped every equation on the floor.
+ public static func replacingMath(in attributed: NSAttributedString) -> NSAttributedString {
+ let replaced = NSMutableAttributedString()
+ attributed.enumerateAttribute(
+ .attachment,
+ in: NSRange(location: 0, length: attributed.length),
+ options: []) { value, range, _ in
+ guard let attachment = value as? MathAttachment else {
+ replaced.append(attributed.attributedSubstring(from: range))
+ return
+ }
+ var attributes = attributed.attributes(at: range.location, effectiveRange: nil)
+ attributes.removeValue(forKey: .attachment)
+ replaced.append(NSAttributedString(
+ string: attachment.latexSource,
+ attributes: attributes))
+ }
+ return replaced
+ }
+}
+
+/// The transcript view.
+///
+/// `NSTextView` builds every pasteboard flavour from the character stream and
+/// the attachments in it, so a reader who selected part of an answer got U+FFFC
+/// for each equation in plain text, nothing at all in RTF, and a rasterised
+/// TIFF per equation in RTFD. The Copy buttons elsewhere in the app write the
+/// raw response and are unaffected; this is the selection path, which has no
+/// source string to fall back on.
+///
+/// Every route out of a selection — Cmd-C, a drag, a Services provider — goes
+/// through `writeSelection`, so they cannot drift apart.
+public final class TranscriptTextView: NSTextView {
+ public override var writablePasteboardTypes: [NSPasteboard.PasteboardType] {
+ selectedAttributedText() == nil ? [] : [.rtfd, .rtf, .string]
+ }
+
+ public override func writeSelection(
+ to pasteboard: NSPasteboard,
+ types: [NSPasteboard.PasteboardType]
+ ) -> Bool {
+ guard let selection = selectedAttributedText() else { return false }
+ let flattened = TranscriptPlainText.replacingMath(in: selection)
+ let range = NSRange(location: 0, length: flattened.length)
+ var wrote = false
+ for type in types {
+ switch type {
+ case .rtfd:
+ guard let data = flattened.rtfd(from: range, documentAttributes: [:]) else {
+ continue
+ }
+ pasteboard.setData(data, forType: .rtfd)
+ wrote = true
+ case .rtf:
+ guard let data = flattened.rtf(from: range, documentAttributes: [:]) else {
+ continue
+ }
+ pasteboard.setData(data, forType: .rtf)
+ wrote = true
+ case .string:
+ pasteboard.setString(flattened.string, forType: .string)
+ wrote = true
+ default:
+ continue
+ }
+ }
+ return wrote
+ }
+
+ public override func writeSelection(
+ to pasteboard: NSPasteboard,
+ type: NSPasteboard.PasteboardType
+ ) -> Bool {
+ writeSelection(to: pasteboard, types: [type])
+ }
+
+ public override func copy(_ sender: Any?) {
+ copySelection(to: .general)
+ }
+
+ /// The pasteboard is a parameter so the behaviour can be measured without
+ /// writing to the reader's clipboard.
+ func copySelection(to pasteboard: NSPasteboard) {
+ let types = writablePasteboardTypes
+ guard !types.isEmpty else { return }
+ pasteboard.clearContents()
+ pasteboard.declareTypes(types, owner: nil)
+ _ = writeSelection(to: pasteboard, types: types)
+ }
+
+ private func selectedAttributedText() -> NSAttributedString? {
+ guard let storage = textStorage else { return nil }
+ let document = NSRange(location: 0, length: storage.length)
+ let selected = NSMutableAttributedString()
+ for value in selectedRanges {
+ let range = NSIntersectionRange(value.rangeValue, document)
+ guard range.length > 0 else { continue }
+ if selected.length > 0 {
+ selected.append(NSAttributedString(string: "\n"))
+ }
+ selected.append(storage.attributedSubstring(from: range))
+ }
+ return selected.length > 0 ? selected : nil
+ }
+}
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 15a89780..27da045f 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -43,6 +43,7 @@ The following table covers the complete graph reported by
| [swift-crypto](https://github.com/apple/swift-crypto) | 4.5.0 | Apache-2.0; upstream NOTICE applies |
| [swift-asn1](https://github.com/apple/swift-asn1) | 1.7.0 | Apache-2.0; upstream NOTICE applies |
| [yyjson](https://github.com/ibireme/yyjson) | 0.12.0 | MIT |
+| [SwiftMath](https://github.com/mgriebling/SwiftMath) | revision `1d2c908` | MIT; bundled math fonts are GUST and OFL |
No copyleft or custom non-commercial license was found in this resolved graph.
The dependency license files remain authoritative. For binary distribution,
diff --git a/Tests/TurboFieldfareApp/MacPresentation/FenceLineTests.swift b/Tests/TurboFieldfareApp/MacPresentation/FenceLineTests.swift
new file mode 100644
index 00000000..1ba6983c
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/FenceLineTests.swift
@@ -0,0 +1,109 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+/// The grammar four scanners share. Every row runs through both entry points,
+/// because the byte reference and the `Character` mirror disagreeing is the
+/// class of bug this file exists to remove.
+@Suite struct FenceLineTests {
+ struct Row: Sendable, CustomStringConvertible {
+ let line: String
+ let containerIndent: Int
+ let marker: Character?
+ let length: Int
+ let indent: Int
+ let isBare: Bool
+
+ init(
+ _ line: String,
+ containerIndent: Int = 0,
+ marker: Character? = nil,
+ length: Int = 0,
+ indent: Int = 0,
+ isBare: Bool = false
+ ) {
+ self.line = line
+ self.containerIndent = containerIndent
+ self.marker = marker
+ self.length = length
+ self.indent = indent
+ self.isBare = isBare
+ }
+
+ var description: String { "\(line.debugDescription) at \(containerIndent)" }
+ }
+
+ static func byteRun(_ row: Row) -> FenceLine.Run? {
+ var line = row.line
+ return line.withUTF8 { bytes in
+ FenceLine.run(bytes, in: 0..<bytes.count, containerIndent: row.containerIndent)
+ }
+ }
+
+ static func characterRun(_ row: Row) -> FenceLine.Run? {
+ FenceLine.run(row.line, containerIndent: row.containerIndent)
+ }
+
+ static let rows: [Row] = [
+ Row("```", marker: "`", length: 3, isBare: true),
+ Row("````", marker: "`", length: 4, isBare: true),
+ Row("~~~", marker: "~", length: 3, isBare: true),
+ Row("```swift", marker: "`", length: 3),
+ Row("``` ", marker: "`", length: 3, isBare: true),
+ Row("```\r", marker: "`", length: 3, isBare: true),
+ Row(" ```", marker: "`", length: 3, indent: 3, isBare: true),
+ // Four columns of indentation is indented code, not a fence.
+ Row(" ```"),
+ Row("\t```"),
+ Row("``"),
+ Row("~~"),
+ Row(""),
+ Row(" "),
+ Row("plain text"),
+ Row("x```"),
+ // CommonMark: a backtick fence's info string may not contain a
+ // backtick. A tilde fence's may.
+ Row("```bash```"),
+ Row("```a`b"),
+ Row("~~~bash```", marker: "~", length: 3),
+ // A container moves the whole 0...3 window with it.
+ Row(" ```", containerIndent: 4, marker: "`", length: 3, indent: 4, isBare: true),
+ Row(" ```", containerIndent: 4, marker: "`", length: 3, indent: 7, isBare: true),
+ Row(" ```", containerIndent: 4),
+ Row(" ```", containerIndent: 4),
+ ]
+
+ @Test(arguments: rows)
+ func bothEntryPointsReadTheSameGrammar(_ row: Row) throws {
+ let bytes = Self.byteRun(row)
+ let characters = Self.characterRun(row)
+ #expect(bytes == characters, "\(row) read differently by the two entry points")
+
+ guard let marker = row.marker else {
+ #expect(bytes == nil, "\(row) is not a fence line")
+ return
+ }
+ let run = try #require(bytes, "\(row) is a fence line")
+ #expect(run.character == marker)
+ #expect(run.length == row.length)
+ #expect(run.indent == row.indent)
+ #expect(run.isBare == row.isBare)
+ }
+
+ @Test func onlyABareRunOfTheSameMarkerCloses() throws {
+ let opener = try #require(FenceLine.run("```swift"))
+ #expect(try #require(FenceLine.run("```")).closes(marker: opener.marker, length: 3))
+ #expect(try #require(FenceLine.run("````")).closes(marker: opener.marker, length: 3))
+ // Shorter, wrong marker, or carrying an info string: not a closer.
+ #expect(!(try #require(FenceLine.run("~~~")).closes(marker: opener.marker, length: 3)))
+ #expect(!(try #require(FenceLine.run("```text")).closes(marker: opener.marker, length: 3)))
+ #expect(try #require(FenceLine.run("```")).closes(marker: opener.marker, length: 4) == false)
+ }
+
+ /// Multi-byte text before the marker must not shift the column count: the
+ /// byte entry point measures indentation in spaces and tabs, not bytes.
+ @Test func nonASCIIContentIsNotAFenceLine() {
+ #expect(FenceLine.run("\u{4E2D}\u{6587}```") == nil)
+ #expect(FenceLine.run("\u{2018}```") == nil)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/latex-sweep-failures.txt b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/latex-sweep-failures.txt
new file mode 100644
index 00000000..4df2af92
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/latex-sweep-failures.txt
@@ -0,0 +1,90 @@
+\quad
+\qquad
+\,
+\:
+\;
+\!
+\
+\hspace{1em}
+\phantom{x}
+\not=
+\&
+\argmax
+\it x
+\small x
+\large x
+\label{eq}
+\newline
+\dbinom{n}{k}
+\tbinom{n}{k}
+\digamma
+中
+\ce{H2O}
+\si{m}
+\num{1e3}
+\unicode{x263A}
+\href{x}{y}
+\url{x}
+\includegraphics{x}
+\mathstrut
+\strut
+\vphantom{x}
+\hphantom{x}
+\smash{x}
+\raisebox{1pt}{x}
+\kern1pt
+\mkern1mu
+\mskip1mu
+\hskip1pt
+\vspace{1pt}
+\,\!
+\;\;
+\ang{90}
+\textdegree
+\mathrel{\smash{=}}
+\mathbin{+}
+\mathop{x}
+\mathord{x}
+\mathpunct{,}
+\mathopen{(}
+\mathclose{)}
+\fcolorbox{red}{blue}{x}
+\rule{1pt}{1pt}
+\def\x{y}
+\newcommand{\x}{y}
+\mathbin{\text{and}}
+\surd
+\blacksquare
+\S
+\P
+\copyright
+\pounds
+\euro
+\checkmark
+\maltese
+\smile
+\frown
+\flat
+\sharp
+\natural
+\clubsuit
+\heartsuit
+\spadesuit
+\diamondsuit
+\rightharpoonup
+\leadsto
+\abs{x}
+\norm{x}
+\set{x}
+\ifmmode x \fi
+\lbrack x \rbrack
+\smallsetminus
+\triangleq
+\defeq
+\lesssim
+\gtrsim
+\Join
+\varlimsup
+\varinjlim
+\DeclareMathOperator{\x}{y}
+a\&b
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/latex-sweep.txt b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/latex-sweep.txt
new file mode 100644
index 00000000..8f37191c
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/latex-sweep.txt
@@ -0,0 +1,647 @@
+\begin{cases} x & \text{if } x \geq 0 \\ -x & \text{if } x < 0 \end{cases}
+\begin{aligned} a &= b \\ c &= d \end{aligned}
+\begin{align*} a &= b \\ c &= d \end{align*}
+\begin{equation} a = b \end{equation}
+\operatorname{softmax}(x)_i = \frac{e^{x_i}}{\sum_j e^{x_j}}
+\mathbb{R}^n \to \mathcal{L}
+\hat{y} = \mathbf{W}^\top \mathbf{x} + \mathbf{b}
+a \; b \: c \! d \quad e \qquad f
+\dfrac{1}{2} \tfrac{1}{2}
+\text{rate} = 5\%
+\boxed{x}
+x \in \{1, 2\} \land y \lor z \neg w \implies q \iff r
+\nabla \cdot \vec{E} = \frac{\rho}{\varepsilon_0}
+\underbrace{a+b}_{\text{sum}} \overbrace{c}^{d}
+\lim_{x \to \infty} \frac{1}{x} = 0
+\int_{-\infty}^{\infty} e^{-x^2} \, dx = \sqrt{\pi}
+\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} \begin{bmatrix} a \\ b \end{bmatrix}
+\mathrm{d}x \, \mathit{v}
+\cancel{x}
+\textbf{bold} \textit{it}
+\frac{\partial f}{\partial x} \approx \Delta
+\mathcal{O}(n \log n)
+\sigma(z) = \frac{1}{1 + e^{-z}}
+x \ge 0,\ y \le 1
+\left\{ a \right\}
+\left. \frac{a}{b} \right|_{x=0}
+\binom{n}{k} \sqrt[3]{x}
+\ldots \cdots \vdots \ddots
+\hbar \ell \Re \Im \aleph
+\stackrel{?}{=}
+\overline{AB} \underline{x} \vec{v} \dot{x} \ddot{x} \tilde{n} \bar{x}
+\color{red}{x} \textcolor{blue}{y}
+\mathbf{A}^{-1}\mathbf{A}=\mathbf{I}
+\text{if } x > 0 \text{ then } y
+\sum\limits_{i=1}^n \prod\nolimits_{j} x_{ij}
+\substack{a \\ b}
+e^{i\pi}+1=0
+\begin{array}{cc} 1 & 2 \\ 3 & 4 \end{array}
+\begin{vmatrix} a & b \\ c & d \end{vmatrix}
+\mathsf{sans} \mathtt{mono} \mathfrak{F}
+\quad
+\qquad
+\,
+\:
+\;
+\!
+\
+\hspace{1em}
+\phantom{x}
+\wedge
+\vee
+\lnot
+\neg
+\land
+\lor
+\Rightarrow
+\Leftrightarrow
+\implies
+\iff
+\to
+\mapsto
+\rightarrow
+\leftarrow
+\longrightarrow
+\overset{a}{b}
+\underset{a}{b}
+\stackrel{a}{b}
+\mathrm{x}
+\operatorname{x}
+\operatorname*{x}
+\fbox{x}
+\boxed{x}
+\mbox{x}
+\not=
+\neq
+\ne
+\leq
+\geq
+\ll
+\gg
+\%
+\#
+\&
+\_
+\{
+\}
+\|
+\langle x \rangle
+\lfloor x \rfloor
+\lceil x \rceil
+\in
+\notin
+\subset
+\subseteq
+\cup
+\cap
+\emptyset
+\varnothing
+\forall
+\exists
+\therefore
+\because
+\circ
+\star
+\oplus
+\otimes
+\times
+\div
+\pm
+\mp
+\sim
+\simeq
+\approx
+\equiv
+\propto
+\degree
+^\circ
+\prime
+x'
+x''
+\colon
+\max
+\min
+\log
+\ln
+\exp
+\sin
+\cos
+\tan
+\det
+\dim
+\gcd
+\Pr
+\sup
+\inf
+\arg
+\arg\max
+\argmax
+a \mod b
+a \pmod{b}
+a \bmod b
+{a \over b}
+{n \choose k}
+{a \atop b}
+\rm x
+\bf x
+\it x
+\displaystyle x
+\textstyle x
+\scriptstyle x
+\small x
+\large x
+\left| x \right|
+\left\| x \right\|
+\left\langle x \right\rangle
+\left\lfloor x \right\rfloor
+\left. x \right|
+\left( x \middle| y \right)
+\bigl( x \bigr)
+\Bigl( x \Bigr)
+\big( x \big)
+\Big( x \Big)
+\bigg( x \bigg)
+\Bigg( x \Bigg)
+\cdots
+\dots
+\dotsc
+\ldots
+\vdots
+x \tag{1}
+\label{eq}
+x \nonumber
+a \\[6pt] b
+\newline
+\begin{split} a &= b \\ &= c \end{split}
+\begin{gather} a \\ b \end{gather}
+\begin{gather*} a \\ b \end{gather*}
+\begin{align} a &= b \end{align}
+\begin{alignat}{2} a &= b \end{alignat}
+\begin{smallmatrix} a & b \end{smallmatrix}
+\begin{Bmatrix} a & b \end{Bmatrix}
+\begin{Vmatrix} a & b \end{Vmatrix}
+\begin{matrix} a & b \end{matrix}
+\begin{array}{c} a \end{array}
+\begin{array}{|c|c|} \hline a & b \\ \hline \end{array}
+\begin{equation*} a \end{equation*}
+\begin{eqnarray} a &=& b \end{eqnarray}
+\begin{cases} a & b \\ c & d \end{cases}
+\begin{rcases} a \end{rcases}
+\text{\textbf{x}}
+\textbf{x}
+\textit{x}
+\textsf{x}
+\texttt{x}
+\textrm{x}
+\mathbf{x}
+\boldsymbol{x}
+\bm{x}
+\pmb{x}
+\mathbb{R}
+\mathcal{L}
+\mathfrak{g}
+\mathscr{L}
+\mathsf{x}
+\mathtt{x}
+\mathit{x}
+\mathnormal{x}
+\hat{x}
+\widehat{xy}
+\tilde{x}
+\widetilde{xy}
+\bar{x}
+\overline{xy}
+\underline{x}
+\vec{x}
+\overrightarrow{AB}
+\overleftarrow{AB}
+\dot{x}
+\ddot{x}
+\acute{x}
+\grave{x}
+\check{x}
+\breve{x}
+\underbrace{x}
+\overbrace{x}
+\underbrace{x}_{y}
+\cancel{x}
+\sout{x}
+\xcancel{x}
+\dfrac{a}{b}
+\tfrac{a}{b}
+\frac{a}{b}
+\cfrac{a}{b}
+\binom{n}{k}
+\dbinom{n}{k}
+\tbinom{n}{k}
+\sqrt{x}
+\sqrt[n]{x}
+\sum
+\prod
+\coprod
+\int
+\iint
+\iiint
+\oint
+\bigcup
+\bigcap
+\bigoplus
+\lim
+\limsup
+\liminf
+\partial
+\nabla
+\infty
+\hbar
+\ell
+\Re
+\Im
+\aleph
+\epsilon
+\varepsilon
+\phi
+\varphi
+\theta
+\vartheta
+\Gamma
+\Delta
+\Omega
+\mu
+\sigma
+\Sigma
+\alpha
+\beta
+\gamma
+\lambda
+\pi
+\tau
+\omega
+\xi
+\zeta
+\eta
+\kappa
+\rho
+\varrho
+\upsilon
+\chi
+\psi
+\nu
+\iota
+\digamma
+π
+×
+≤
+→
+−
+α
+∞
+∑
+√2
+½
+…
+ℝ
+é
+中
+\ce{H2O}
+\si{m}
+\num{1e3}
+\unicode{x263A}
+\href{x}{y}
+\url{x}
+\includegraphics{x}
+\mathstrut
+\strut
+\vphantom{x}
+\hphantom{x}
+\smash{x}
+\raisebox{1pt}{x}
+\kern1pt
+\mkern1mu
+\mskip1mu
+\hskip1pt
+\vspace{1pt}
+\,\!
+\;\;
+\ang{90}
+\textdegree
+\%
+100\%
+\$
+\mathrel{\smash{=}}
+\mathbin{+}
+\mathop{x}
+\mathord{x}
+\mathpunct{,}
+\mathopen{(}
+\mathclose{)}
+\color{red} x
+\color{#ff0000} x
+\textcolor{red}{x}
+\colorbox{red}{x}
+\fcolorbox{red}{blue}{x}
+\rule{1pt}{1pt}
+\def\x{y}
+\newcommand{\x}{y}
+\text{a b}
+\text{a \$ b}
+\text{if}~x
+a~b
+\mathbin{\text{and}}
+\not\in
+\not\subset
+\surd
+\top
+\bot
+\vdash
+\models
+\perp
+\parallel
+\angle
+\triangle
+\square
+\Box
+\blacksquare
+\diamond
+\bullet
+\cdot
+\ast
+\dagger
+\ddagger
+\S
+\P
+\copyright
+\pounds
+\euro
+\checkmark
+\maltese
+\smile
+\frown
+\flat
+\sharp
+\natural
+\clubsuit
+\heartsuit
+\spadesuit
+\diamondsuit
+\hookrightarrow
+\leftrightarrow
+\Longrightarrow
+\xrightarrow{f}
+\xleftarrow{f}
+\uparrow
+\downarrow
+\Uparrow
+\nearrow
+\searrow
+\rightharpoonup
+\leadsto
+\lvert x \rvert
+\lVert x \rVert
+\left\lvert x \right\rvert
+\abs{x}
+\norm{x}
+\set{x}
+\ifmmode x \fi
+\lbrace x \rbrace
+\lbrack x \rbrack
+\backslash
+\setminus
+\smallsetminus
+\triangleq
+\coloneqq
+\eqqcolon
+:=
+\defeq
+\leqslant
+\geqslant
+\lesssim
+\gtrsim
+\prec
+\succ
+\preceq
+\succeq
+\subsetneq
+\supset
+\supseteq
+\sqsubseteq
+\sqcup
+\sqcap
+\uplus
+\amalg
+\wr
+\bowtie
+\Join
+\ltimes
+\rtimes
+\ominus
+\odot
+\oslash
+\bigodot
+\bigotimes
+\bigsqcup
+\biguplus
+\bigvee
+\bigwedge
+\varlimsup
+\varinjlim
+\ker
+\deg
+\hom
+\lg
+\sec
+\csc
+\cot
+\arcsin
+\arccos
+\arctan
+\sinh
+\cosh
+\tanh
+\coth
+\operatorname{ReLU}(x)
+\mathrm{ReLU}(x)
+\text{ReLU}(x)
+\mathrm{softmax}
+\mathrm{argmax}_x
+\operatorname*{argmax}_x
+\underset{x}{\operatorname{argmax}}
+\underset{x}{\mathrm{argmax}}
+\underset{x}{\arg\max}
+\DeclareMathOperator{\x}{y}
+\mathrm{d}
+\partial_x f
+f'(x)
+f^{(n)}(x)
+x_{i,j}
+x_{ij}^{2}
+10^{-3}
+1{,}000
+1\,000
+\$5
+5\%
+\#1
+a\&b
+x_1, x_2, \ldots, x_n
+(x_1, \dots, x_n)
+\{x_i\}_{i=1}^n
+\left\{x_i\right\}_{i=1}^n
+\sum_{i=1}^{n}
+\sum_{\substack{i \\ j}}
+\sum_{i \in S}
+\prod_{k=1}^K
+\int_a^b
+\int\limits_a^b
+\lim_{n\to\infty}
+\max_{x}
+\min_{x}
+\sup_{x}
+\sup\limits_{x}
+e^{i\theta}
+\exp(x)
+\log_2 n
+\ln(x)
+\sqrt{a^2+b^2}
+\frac{1}{2}
+\frac12
+\frac{\partial L}{\partial w}
+\nabla_\theta J(\theta)
+\theta \leftarrow \theta - \eta \nabla_\theta J
+\mathbb{E}[X]
+\mathbb{E}_{x \sim p}[f(x)]
+\mathrm{Var}(X)
+\operatorname{Var}(X)
+P(A \mid B)
+P(A | B)
+\Pr[A]
+\mathcal{N}(\mu, \sigma^2)
+\sim
+x \sim \mathcal{N}(0,1)
+\|x\|_2
+\|x\|_\infty
+\langle x, y \rangle
+x^\top y
+x^T y
+x^{\mathsf{T}} y
+A^{-1}
+A^\dagger
+A^*
+\det(A)
+\mathrm{tr}(A)
+\operatorname{tr}(A)
+\mathrm{rank}(A)
+\mathbf{I}_n
+\mathbf{0}
+\vec{0}
+\hat{\beta}
+\tilde{\theta}
+\bar{x}
+\dot{q}
+\mathbf{x}^{(i)}
+x^{(i)}
+y^{(i)}
+h_\theta(x)
+J(\theta) = \frac{1}{2m}\sum_{i=1}^m (h_\theta(x^{(i)}) - y^{(i)})^2
+O(n^2)
+\Theta(n)
+\Omega(n \log n)
+o(1)
+\mathcal{O}(1)
+\text{softmax}(z)_i = \frac{e^{z_i}}{\sum_{j} e^{z_j}}
+\text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V
+\mathrm{Attention}(Q,K,V)
+\operatorname{Attention}(Q,K,V)
+\frac{d}{dx}
+\frac{\mathrm{d}y}{\mathrm{d}x}
+\frac{dy}{dx}
+\ddot{x} + \omega^2 x = 0
+F = ma
+E = mc^2
+\vec{F} = m\vec{a}
+\mathbf{F} = m\mathbf{a}
+\nabla \times \mathbf{B}
+\oint_C \mathbf{E}\cdot d\mathbf{l}
+\iint_S
+\mathrm{d}^3x
+\hbar\omega
+\psi(x,t)
+\langle \psi | \phi \rangle
+|\psi\rangle
+\langle\psi|
+\hat{H}|\psi\rangle = E|\psi\rangle
+\ket{\psi}
+\bra{\psi}
+\braket{\psi|\phi}
+\vec{r} = (x, y, z)
+\|\vec{r}\|
+\mathbf{r}
+\boldsymbol{\mu}
+\boldsymbol{\Sigma}
+\Sigma^{-1}
+\mu_i
+\sigma_{ij}
+\rho_{XY}
+\chi^2
+\alpha = 0.05
+p < 0.05
+H_0: \mu = 0
+H_a: \mu \neq 0
+\bar{X} \pm z_{\alpha/2}\frac{\sigma}{\sqrt{n}}
+t = \frac{\bar{x} - \mu}{s/\sqrt{n}}
+\binom{n}{k} p^k (1-p)^{n-k}
+\frac{\lambda^k e^{-\lambda}}{k!}
+n!
+(n-1)!
+\Gamma(n) = (n-1)!
+\zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s}
+\forall \epsilon > 0\, \exists \delta > 0
+\exists! x
+A \subseteq B \iff \forall x (x \in A \Rightarrow x \in B)
+\neg p \lor q
+p \land q
+p \to q
+p \leftrightarrow q
+\top
+\bot
+\mathbb{Z}_n
+\mathbb{Z}/n\mathbb{Z}
+a \equiv b \pmod{n}
+a \equiv b \ (\mathrm{mod}\ n)
+\gcd(a,b)
+\operatorname{lcm}(a,b)
+\lfloor x \rfloor
+\lceil x \rceil
+|x|
+\left|x\right|
+\|x\|
+x \bmod 2
+\text{mod}
+\texttt{mod}
+\mathtt{0x1F}
+\mathrm{0x1F}
+2^{32}
+2^{32}-1
+\log_2(n)
+\lg n
+n \log n
+\Theta(n \lg n)
+T(n) = 2T(n/2) + O(n)
+T(n) = 2T\left(\frac{n}{2}\right) + \Theta(n)
+f(n) = \begin{cases} 1 & n = 0 \\ n f(n-1) & n > 0 \end{cases}
+\begin{cases} x, & x \ge 0 \\ -x, & x < 0 \end{cases}
+\begin{cases} x & \text{if } x \ge 0, \\ -x & \text{otherwise.} \end{cases}
+\left\{ \begin{array}{ll} x & x \ge 0 \\ -x & x < 0 \end{array} \right.
+\left\{\begin{aligned} a &= b \\ c &= d \end{aligned}\right.
+\begin{aligned} a &= b \\ &= c \\ &= d \end{aligned}
+\begin{aligned} a &= b & c &= d \end{aligned}
+\begin{aligned} a &= b \\[4pt] c &= d \end{aligned}
+\begin{aligned} a &= b \\ \\ c &= d \end{aligned}
+\begin{pmatrix} a & b \\ c & d \end{pmatrix}^{-1} = \frac{1}{ad-bc}\begin{pmatrix} d & -b \\ -c & a \end{pmatrix}
+\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}
+\begin{pmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{pmatrix}
+\begin{pmatrix} a_{11} & \cdots & a_{1n} \\ \vdots & \ddots & \vdots \\ a_{m1} & \cdots & a_{mn} \end{pmatrix}
+\begin{vmatrix} a & b \\ c & d \end{vmatrix} = ad - bc
+\det\begin{pmatrix} a & b \\ c & d \end{pmatrix}
+\begin{matrix} a & b \\ c & d \end{matrix}
+\left[\begin{matrix} a & b \\ c & d \end{matrix}\right]
+\left(\begin{matrix} a & b \\ c & d \end{matrix}\right)
+\left[ \begin{array}{cc|c} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array} \right]
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/unicode-math-mode.txt b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/unicode-math-mode.txt
new file mode 100644
index 00000000..b8140ea6
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/math-coverage/unicode-math-mode.txt
@@ -0,0 +1,209 @@
+0021
+0022
+0027
+0028
+0029
+002A
+002B
+002C
+002D
+002E
+002F
+0030
+0031
+0032
+0033
+0034
+0035
+0036
+0037
+0038
+0039
+003A
+003B
+003C
+003D
+003E
+003F
+0040
+0041
+0042
+0043
+0044
+0045
+0046
+0047
+0048
+0049
+004A
+004B
+004C
+004D
+004E
+004F
+0050
+0051
+0052
+0053
+0054
+0055
+0056
+0057
+0058
+0059
+005A
+005B
+005D
+0060
+0061
+0062
+0063
+0064
+0065
+0066
+0067
+0068
+0069
+006A
+006B
+006C
+006D
+006E
+006F
+0070
+0071
+0072
+0073
+0074
+0075
+0076
+0077
+0078
+0079
+007A
+007C
+00C0
+00C1
+00C2
+00C3
+00C4
+00C5
+00C6
+00C7
+00C8
+00C9
+00CA
+00CB
+00CC
+00CD
+00CE
+00CF
+00D1
+00D2
+00D3
+00D4
+00D5
+00D6
+00D8
+00D9
+00DA
+00DB
+00DC
+00DD
+00DF
+00E0
+00E1
+00E2
+00E3
+00E4
+00E5
+00E6
+00E7
+00E8
+00E9
+00EA
+00EB
+00EC
+00ED
+00EE
+00EF
+00F1
+00F2
+00F3
+00F4
+00F5
+00F6
+00F8
+00F9
+00FA
+00FB
+00FC
+00FD
+00FF
+0135
+0152
+0153
+0410
+0411
+0412
+0413
+0414
+0415
+0416
+0417
+0418
+0419
+041A
+041B
+041C
+041D
+041E
+041F
+0420
+0421
+0422
+0423
+0424
+0425
+0426
+0427
+0428
+0429
+042A
+042B
+042C
+042D
+042E
+042F
+0430
+0431
+0432
+0433
+0434
+0435
+0436
+0437
+0438
+0439
+043A
+043B
+043C
+043D
+043E
+043F
+0440
+0441
+0442
+0443
+0444
+0445
+0446
+0447
+0448
+0449
+044A
+044B
+044C
+044D
+044E
+044F
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/arithmetic-prose.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/arithmetic-prose.md
new file mode 100644
index 00000000..9015e4b1
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/arithmetic-prose.md
@@ -0,0 +1,5 @@
+Multiply 2*3 to get 6, and note that x**2 is not emphasis either.
+
+The value $x_{1}$ is small, and `a * b` inside a code span stays literal.
+
+An in-place update reads x *= 2 in most languages.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/backtick-info-string.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/backtick-info-string.md
new file mode 100644
index 00000000..10510474
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/backtick-info-string.md
@@ -0,0 +1,12 @@
+# Fence syntax
+
+Write ```bash``` when you mean the fence syntax inline; CommonMark reads it as a code span, because a backtick fence's info string may not contain a backtick.
+
+A mid-line ``` in a sentence used to send the whole answer to raw text, headings and tables included.
+
+| Marker | Meaning |
+| --- | --- |
+| Backtick fence | code block |
+| Backtick span | inline code |
+
+Done.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/blank-line-fence.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/blank-line-fence.md
new file mode 100644
index 00000000..4245a9ec
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/blank-line-fence.md
@@ -0,0 +1,7 @@
+Intro.
+
+```
+
+```
+
+After.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/br-only-paragraph.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/br-only-paragraph.md
new file mode 100644
index 00000000..c9a72aa4
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/br-only-paragraph.md
@@ -0,0 +1,5 @@
+First paragraph.
+
+<br>
+
+Second paragraph.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/cjk.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/cjk.md
new file mode 100644
index 00000000..e20ae228
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/cjk.md
@@ -0,0 +1,12 @@
+### 中文与数学
+
+这是一个句子,包含内联公式 $E = mc^2$ 以及行内代码 `let x = 1`。
+
+| 特性 | 说明 |
+| :--- | :--- |
+| **模型** | 低层级、基于闭包。 |
+| 安全性 | 内置数据竞争保护。 |
+
+质量为$m$的物体在自由落体中加速。
+
+日本語のテキストも同じ段落に入ります。한국어 텍스트도 포함됩니다。
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/crlf.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/crlf.md
new file mode 100644
index 00000000..835a89ab
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/crlf.md
@@ -0,0 +1,14 @@
+# CRLF document
+
+A paragraph with **bold** text and `code`.
+
+| A | B |
+| :--- | :--- |
+| 1 | 2 |
+
+```swift
+let a = 1
+let b = 2
+```
+
+Trailing paragraph.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/currency.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/currency.md
new file mode 100644
index 00000000..e6ac98ac
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/currency.md
@@ -0,0 +1,16 @@
+### Pricing
+
+The base plan is $20 per month and the pro plan is $30 per month.
+
+Refunds under $5 are processed automatically; anything over $100 needs review.
+
+It costs $5 (or $10 for two). The formula $E=mc^2$ applies to both.
+
+A single amount on its own line:
+
+$49.99
+
+| Tier | Monthly | Yearly |
+| :--- | ---: | ---: |
+| Basic | $20 | $200 |
+| Pro | $30 | $300 |
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/display-math-blank-line.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/display-math-blank-line.md
new file mode 100644
index 00000000..9b8caf43
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/display-math-blank-line.md
@@ -0,0 +1,9 @@
+Intro.
+
+$$
+\frac{a}{b}
+
+c = d
+$$
+
+After $x$ the answer continues.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fence-in-list-item.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fence-in-list-item.md
new file mode 100644
index 00000000..cd6b537b
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fence-in-list-item.md
@@ -0,0 +1,13 @@
+1. Install the tool:
+
+ ```bash
+ brew install x
+ ```
+
+2. Check the version:
+
+ ```bash
+ x --version
+ ```
+
+Both steps stay inside their items.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fence-in-quote.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fence-in-quote.md
new file mode 100644
index 00000000..677452b0
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fence-in-quote.md
@@ -0,0 +1,7 @@
+> Run the installer first:
+>
+> ```bash
+> brew install x
+> ```
+
+Then continue with the setup.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fifty-equations.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fifty-equations.md
new file mode 100644
index 00000000..a43edda0
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/fifty-equations.md
@@ -0,0 +1,155 @@
+### Fifty equations
+
+A dense derivation that ends with a summary paragraph.
+
+Step 1.
+$$\sum_{i=1}^{1} i = \frac{1(1+1)}{2}$$
+
+Step 2.
+$$\int_0^{2} x^2 \, dx = \frac{2^3}{3}$$
+
+Step 3.
+$$\sigma(z_{3}) = \frac{1}{1 + e^{-z_{3}}}$$
+
+Step 4.
+$$\nabla_\theta J(\theta)_{4} = \frac{1}{4}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 5.
+$$x_{5} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 6.
+$$\sum_{i=1}^{6} i = \frac{6(6+1)}{2}$$
+
+Step 7.
+$$\int_0^{7} x^2 \, dx = \frac{7^3}{3}$$
+
+Step 8.
+$$\sigma(z_{8}) = \frac{1}{1 + e^{-z_{8}}}$$
+
+Step 9.
+$$\nabla_\theta J(\theta)_{9} = \frac{1}{9}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 10.
+$$x_{10} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 11.
+$$\sum_{i=1}^{11} i = \frac{11(11+1)}{2}$$
+
+Step 12.
+$$\int_0^{12} x^2 \, dx = \frac{12^3}{3}$$
+
+Step 13.
+$$\sigma(z_{13}) = \frac{1}{1 + e^{-z_{13}}}$$
+
+Step 14.
+$$\nabla_\theta J(\theta)_{14} = \frac{1}{14}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 15.
+$$x_{15} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 16.
+$$\sum_{i=1}^{16} i = \frac{16(16+1)}{2}$$
+
+Step 17.
+$$\int_0^{17} x^2 \, dx = \frac{17^3}{3}$$
+
+Step 18.
+$$\sigma(z_{18}) = \frac{1}{1 + e^{-z_{18}}}$$
+
+Step 19.
+$$\nabla_\theta J(\theta)_{19} = \frac{1}{19}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 20.
+$$x_{20} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 21.
+$$\sum_{i=1}^{21} i = \frac{21(21+1)}{2}$$
+
+Step 22.
+$$\int_0^{22} x^2 \, dx = \frac{22^3}{3}$$
+
+Step 23.
+$$\sigma(z_{23}) = \frac{1}{1 + e^{-z_{23}}}$$
+
+Step 24.
+$$\nabla_\theta J(\theta)_{24} = \frac{1}{24}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 25.
+$$x_{25} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 26.
+$$\sum_{i=1}^{26} i = \frac{26(26+1)}{2}$$
+
+Step 27.
+$$\int_0^{27} x^2 \, dx = \frac{27^3}{3}$$
+
+Step 28.
+$$\sigma(z_{28}) = \frac{1}{1 + e^{-z_{28}}}$$
+
+Step 29.
+$$\nabla_\theta J(\theta)_{29} = \frac{1}{29}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 30.
+$$x_{30} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 31.
+$$\sum_{i=1}^{31} i = \frac{31(31+1)}{2}$$
+
+Step 32.
+$$\int_0^{32} x^2 \, dx = \frac{32^3}{3}$$
+
+Step 33.
+$$\sigma(z_{33}) = \frac{1}{1 + e^{-z_{33}}}$$
+
+Step 34.
+$$\nabla_\theta J(\theta)_{34} = \frac{1}{34}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 35.
+$$x_{35} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 36.
+$$\sum_{i=1}^{36} i = \frac{36(36+1)}{2}$$
+
+Step 37.
+$$\int_0^{37} x^2 \, dx = \frac{37^3}{3}$$
+
+Step 38.
+$$\sigma(z_{38}) = \frac{1}{1 + e^{-z_{38}}}$$
+
+Step 39.
+$$\nabla_\theta J(\theta)_{39} = \frac{1}{39}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 40.
+$$x_{40} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 41.
+$$\sum_{i=1}^{41} i = \frac{41(41+1)}{2}$$
+
+Step 42.
+$$\int_0^{42} x^2 \, dx = \frac{42^3}{3}$$
+
+Step 43.
+$$\sigma(z_{43}) = \frac{1}{1 + e^{-z_{43}}}$$
+
+Step 44.
+$$\nabla_\theta J(\theta)_{44} = \frac{1}{44}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 45.
+$$x_{45} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+Step 46.
+$$\sum_{i=1}^{46} i = \frac{46(46+1)}{2}$$
+
+Step 47.
+$$\int_0^{47} x^2 \, dx = \frac{47^3}{3}$$
+
+Step 48.
+$$\sigma(z_{48}) = \frac{1}{1 + e^{-z_{48}}}$$
+
+Step 49.
+$$\nabla_\theta J(\theta)_{49} = \frac{1}{49}\sum_{j} (h_\theta(x^{(j)}) - y^{(j)}) x^{(j)}$$
+
+Step 50.
+$$x_{50} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+All fifty steps reduce to the same closed form.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-comparison-table.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-comparison-table.md
new file mode 100644
index 00000000..97919f6c
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-comparison-table.md
@@ -0,0 +1,32 @@
+### Concurrency Comparison
+
+| Feature | GCD Queues | Swift Actors |
+| :--- | :--- | :--- |
+| **Model** | Low-level, closure-based. | High-level, language-level. |
+| **Safety** | Manual management; prone to data races. | Built-in protection against data races. |
+| **Mechanism** | Thread pools and dispatching. | Actor isolation and cooperative multitasking. |
+
+* **GCD Queues**
+ * Manual control over priority.
+ * Risk of priority inversion.
+* **Swift Actors**
+ * Automatic synchronization.
+ * Uses `await` to manage suspension points.
+
+#### Task Checklist
+- [x] Define data model
+- [x] Implement synchronization
+- [ ] Optimize performance
+
+> "Concurrency is not just about running tasks in parallel, but about managing access to shared state safely."
+
+[Apple Documentation: Swift Concurrency](https://developer.apple.com/documentation/swift/concurrency)
+
+```swift
+actor BankAccount {
+ var balance = 0
+ func deposit(amount: Int) { balance += amount }
+}
+```
+
+The system uses $HOME to locate user files and $PATH to find executable binaries.
\ No newline at end of file
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-derivation-table.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-derivation-table.md
new file mode 100644
index 00000000..79b10ac2
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-derivation-table.md
@@ -0,0 +1,50 @@
+### 1. Derivation of the Quadratic Formula
+
+To solve $ax^2 + bx + c = 0$ for $x$, we use the method of **completing the square**.
+
+**Step 1: Isolate the $x$ terms**
+Subtract $c$ from both sides:
+$$ax^2 + bx = -c$$
+
+**Step 2: Divide by $a$**
+To make the leading coefficient 1:
+$$x^2 + \frac{b}{a}x = -\frac{c}{a}$$
+
+**Step 3: Complete the square**
+Take half of the coefficient of $x$ (which is $\frac{b}{2a}$), square it ($\frac{b^2}{4a^2}$), and add it to both sides:
+$$x^2 + \frac{b}{a}x + \frac{b^2}{4a^2} = \frac{b^2}{4a^2} - \frac{c}{a}$$
+
+**Step 4: Factor and simplify**
+The left side is now a perfect square. On the right side, find a common denominator ($4a^2$):
+$$\left(x + \frac{b}{2a}\right)^2 = \frac{b^2 - 4ac}{4a^2}$$
+
+**Step 5: Take the square root**
+Take the square root of both sides, remembering to include $\pm$:
+$$x + \frac{b}{2a} = \pm \sqrt{\frac{b^2 - 4ac}{4a^2}}$$
+$$x + \frac{b}{2a} = \pm \frac{\sqrt{b^2 - 4ac}}{2a}$$
+
+**Step 6: Solve for $x$**
+Subtract $\frac{b}{2a}$ from both sides:
+$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+---
+
+### 2. Cosine Similarity Formula
+Cosine similarity measures the cosine of the angle between two non-zero vectors. It is calculated as:
+$$\text{similarity}(\mathbf{A}, \mathbf{B}) = \frac{\mathbf{A} \cdot \mathbf{B}}{\|\mathbf{A}\| \|\mathbf{B}\|} = \frac{\sum_{i=1}^{n} A_i B_i}{\sqrt{\sum_{i=1}^{n} A_i^2} \sqrt{\sum_{i=1}^{n} B_i^2}}$$
+
+---
+
+### 3. Pricing Logic: $20 vs $30
+The price difference typically depends on **value-added variables** such as:
+* **Quality/Material:** A $30 product might use premium materials compared to a $20 budget version.
+* **Features/Complexity:** The $30 version may include advanced features or higher capacity.
+* **Service/Warranty:** The higher price might include extended support or faster shipping.
+
+---
+
+### 4. Comparison Table
+
+| Feature | Case A ($20) | Case B ($30) |
+| :--- | :--- | :--- |
+| **Target Market** | Budget-
\ No newline at end of file
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-inline-environments.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-inline-environments.md
new file mode 100644
index 00000000..952aa34a
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/gemma-inline-environments.md
@@ -0,0 +1,15 @@
+**Bayes' Theorem:** $P(A|B) = \frac{P(B|A)P(A)}{P(B)}$
+
+**Normal Distribution PDF:** $f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}$
+
+**Absolute Value:** $|x| = \begin{cases} x & \text{if } x \geq 0 \\ -x & \text{if } x < 0 \end{cases}$
+
+**Expectation of a fair die:**
+$\begin{aligned} E[X] &= \sum_{i=1}^{6} i \cdot P(X=i) \\ &= \sum_{i=1}^{6} i \cdot \frac{1}{6} = \frac{21}{6} = 3.5 \end{aligned}$
+
+```bash
+echo $HOME
+echo $PATH
+```
+
+The pattern `\d+` matches one or more digits.
\ No newline at end of file
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/heading-with-math.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/heading-with-math.md
new file mode 100644
index 00000000..dc56bbe4
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/heading-with-math.md
@@ -0,0 +1,5 @@
+## Solving $ax^2 + bx + c = 0$
+
+### The discriminant $\Delta = b^2 - 4ac$
+
+Both headings above contain inline math and must keep their heading size.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/html-details.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/html-details.md
new file mode 100644
index 00000000..bc10add6
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/html-details.md
@@ -0,0 +1,8 @@
+Here is the summary:
+
+<details>
+<summary>More detail</summary>
+Hidden body text.
+</details>
+
+Done.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/large-code-block.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/large-code-block.md
new file mode 100644
index 00000000..fa517389
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/large-code-block.md
@@ -0,0 +1,359 @@
+### Streaming buffer implementation
+
+The full source of the ring buffer follows.
+
+```swift
+import Foundation
+
+struct RingSlot000 {
+ let index: Int = 0
+ var payload: [UInt8] = Array(repeating: 0, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 7 }
+}
+
+struct RingSlot001 {
+ let index: Int = 1
+ var payload: [UInt8] = Array(repeating: 1, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 8 }
+}
+
+struct RingSlot002 {
+ let index: Int = 2
+ var payload: [UInt8] = Array(repeating: 2, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 9 }
+}
+
+struct RingSlot003 {
+ let index: Int = 3
+ var payload: [UInt8] = Array(repeating: 3, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 10 }
+}
+
+struct RingSlot004 {
+ let index: Int = 4
+ var payload: [UInt8] = Array(repeating: 4, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 11 }
+}
+
+struct RingSlot005 {
+ let index: Int = 5
+ var payload: [UInt8] = Array(repeating: 5, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 12 }
+}
+
+struct RingSlot006 {
+ let index: Int = 6
+ var payload: [UInt8] = Array(repeating: 6, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 13 }
+}
+
+struct RingSlot007 {
+ let index: Int = 7
+ var payload: [UInt8] = Array(repeating: 7, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 14 }
+}
+
+struct RingSlot008 {
+ let index: Int = 8
+ var payload: [UInt8] = Array(repeating: 8, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 15 }
+}
+
+struct RingSlot009 {
+ let index: Int = 9
+ var payload: [UInt8] = Array(repeating: 9, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 16 }
+}
+
+struct RingSlot010 {
+ let index: Int = 10
+ var payload: [UInt8] = Array(repeating: 10, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 17 }
+}
+
+struct RingSlot011 {
+ let index: Int = 11
+ var payload: [UInt8] = Array(repeating: 11, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 18 }
+}
+
+struct RingSlot012 {
+ let index: Int = 12
+ var payload: [UInt8] = Array(repeating: 12, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 19 }
+}
+
+struct RingSlot013 {
+ let index: Int = 13
+ var payload: [UInt8] = Array(repeating: 13, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 20 }
+}
+
+struct RingSlot014 {
+ let index: Int = 14
+ var payload: [UInt8] = Array(repeating: 14, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 21 }
+}
+
+struct RingSlot015 {
+ let index: Int = 15
+ var payload: [UInt8] = Array(repeating: 15, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 22 }
+}
+
+struct RingSlot016 {
+ let index: Int = 16
+ var payload: [UInt8] = Array(repeating: 16, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 23 }
+}
+
+struct RingSlot017 {
+ let index: Int = 17
+ var payload: [UInt8] = Array(repeating: 17, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 24 }
+}
+
+struct RingSlot018 {
+ let index: Int = 18
+ var payload: [UInt8] = Array(repeating: 18, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 25 }
+}
+
+struct RingSlot019 {
+ let index: Int = 19
+ var payload: [UInt8] = Array(repeating: 19, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 26 }
+}
+
+struct RingSlot020 {
+ let index: Int = 20
+ var payload: [UInt8] = Array(repeating: 20, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 27 }
+}
+
+struct RingSlot021 {
+ let index: Int = 21
+ var payload: [UInt8] = Array(repeating: 21, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 28 }
+}
+
+struct RingSlot022 {
+ let index: Int = 22
+ var payload: [UInt8] = Array(repeating: 22, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 29 }
+}
+
+struct RingSlot023 {
+ let index: Int = 23
+ var payload: [UInt8] = Array(repeating: 23, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 30 }
+}
+
+struct RingSlot024 {
+ let index: Int = 24
+ var payload: [UInt8] = Array(repeating: 24, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 31 }
+}
+
+struct RingSlot025 {
+ let index: Int = 25
+ var payload: [UInt8] = Array(repeating: 25, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 32 }
+}
+
+struct RingSlot026 {
+ let index: Int = 26
+ var payload: [UInt8] = Array(repeating: 26, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 33 }
+}
+
+struct RingSlot027 {
+ let index: Int = 27
+ var payload: [UInt8] = Array(repeating: 27, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 34 }
+}
+
+struct RingSlot028 {
+ let index: Int = 28
+ var payload: [UInt8] = Array(repeating: 28, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 35 }
+}
+
+struct RingSlot029 {
+ let index: Int = 29
+ var payload: [UInt8] = Array(repeating: 29, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 36 }
+}
+
+struct RingSlot030 {
+ let index: Int = 30
+ var payload: [UInt8] = Array(repeating: 30, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 37 }
+}
+
+struct RingSlot031 {
+ let index: Int = 31
+ var payload: [UInt8] = Array(repeating: 31, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 38 }
+}
+
+struct RingSlot032 {
+ let index: Int = 32
+ var payload: [UInt8] = Array(repeating: 32, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 39 }
+}
+
+struct RingSlot033 {
+ let index: Int = 33
+ var payload: [UInt8] = Array(repeating: 33, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 40 }
+}
+
+struct RingSlot034 {
+ let index: Int = 34
+ var payload: [UInt8] = Array(repeating: 34, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 41 }
+}
+
+struct RingSlot035 {
+ let index: Int = 35
+ var payload: [UInt8] = Array(repeating: 35, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 42 }
+}
+
+struct RingSlot036 {
+ let index: Int = 36
+ var payload: [UInt8] = Array(repeating: 36, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 43 }
+}
+
+struct RingSlot037 {
+ let index: Int = 37
+ var payload: [UInt8] = Array(repeating: 37, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 44 }
+}
+
+struct RingSlot038 {
+ let index: Int = 38
+ var payload: [UInt8] = Array(repeating: 38, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 45 }
+}
+
+struct RingSlot039 {
+ let index: Int = 39
+ var payload: [UInt8] = Array(repeating: 39, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 46 }
+}
+
+struct RingSlot040 {
+ let index: Int = 40
+ var payload: [UInt8] = Array(repeating: 40, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 47 }
+}
+
+struct RingSlot041 {
+ let index: Int = 41
+ var payload: [UInt8] = Array(repeating: 41, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 48 }
+}
+
+struct RingSlot042 {
+ let index: Int = 42
+ var payload: [UInt8] = Array(repeating: 42, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 49 }
+}
+
+struct RingSlot043 {
+ let index: Int = 43
+ var payload: [UInt8] = Array(repeating: 43, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 50 }
+}
+
+struct RingSlot044 {
+ let index: Int = 44
+ var payload: [UInt8] = Array(repeating: 44, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 51 }
+}
+
+struct RingSlot045 {
+ let index: Int = 45
+ var payload: [UInt8] = Array(repeating: 45, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 52 }
+}
+
+struct RingSlot046 {
+ let index: Int = 46
+ var payload: [UInt8] = Array(repeating: 46, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 53 }
+}
+
+struct RingSlot047 {
+ let index: Int = 47
+ var payload: [UInt8] = Array(repeating: 47, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 54 }
+}
+
+struct RingSlot048 {
+ let index: Int = 48
+ var payload: [UInt8] = Array(repeating: 48, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 55 }
+}
+
+struct RingSlot049 {
+ let index: Int = 49
+ var payload: [UInt8] = Array(repeating: 49, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 56 }
+}
+
+struct RingSlot050 {
+ let index: Int = 50
+ var payload: [UInt8] = Array(repeating: 50, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 57 }
+}
+
+struct RingSlot051 {
+ let index: Int = 51
+ var payload: [UInt8] = Array(repeating: 51, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 58 }
+}
+
+struct RingSlot052 {
+ let index: Int = 52
+ var payload: [UInt8] = Array(repeating: 52, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 59 }
+}
+
+struct RingSlot053 {
+ let index: Int = 53
+ var payload: [UInt8] = Array(repeating: 53, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 60 }
+}
+
+struct RingSlot054 {
+ let index: Int = 54
+ var payload: [UInt8] = Array(repeating: 54, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 61 }
+}
+
+struct RingSlot055 {
+ let index: Int = 55
+ var payload: [UInt8] = Array(repeating: 55, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 62 }
+}
+
+struct RingSlot056 {
+ let index: Int = 56
+ var payload: [UInt8] = Array(repeating: 56, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 63 }
+}
+
+struct RingSlot057 {
+ let index: Int = 57
+ var payload: [UInt8] = Array(repeating: 57, count: 64)
+ func advance(by step: Int) -> Int { (index + step) % 64 }
+}
+
+```
+
+The buffer wraps once the write cursor passes the capacity.
+
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/latex-paren-bracket.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/latex-paren-bracket.md
new file mode 100644
index 00000000..33bd4994
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/latex-paren-bracket.md
@@ -0,0 +1,5 @@
+The area of a circle is \(A = \pi r^2\) and the volume of a sphere is
+
+\[V = \frac{4}{3}\pi r^3\]
+
+Escaped braces stay literal: \{a, b\} and \\ is a hard break in LaTeX.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/link-dollar-url.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/link-dollar-url.md
new file mode 100644
index 00000000..6cde585f
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/link-dollar-url.md
@@ -0,0 +1,4 @@
+See [the pricing page](https://example.com/checkout?amount=$20&tier=$pro)
+and [the docs](https://example.com/docs#section-$1) for details.
+
+An autolink style reference: <https://example.com/plain>
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/list-nested-fence.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/list-nested-fence.md
new file mode 100644
index 00000000..a2b449f1
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/list-nested-fence.md
@@ -0,0 +1,12 @@
+1. Outer step
+
+ - Inner step, which owns the listing below it:
+
+ ~~~bash
+ cost $a$ per run
+ export TARGET="$HOME/$PATH"
+ ~~~
+
+ - Next step uses $x$ directly
+
+Then $y$ closes the answer.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/list-then-fence.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/list-then-fence.md
new file mode 100644
index 00000000..2886f09b
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/list-then-fence.md
@@ -0,0 +1,8 @@
+- Install the tool:
+```bash
+brew install x
+
+brew link x
+```
+
+Done.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/lone-display-dollars.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/lone-display-dollars.md
new file mode 100644
index 00000000..664a0482
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/lone-display-dollars.md
@@ -0,0 +1,13 @@
+Rated $$ on the price scale.
+
+# Pricing notes
+
+| Tier | Cost |
+| :--- | ---: |
+| Basic | 20 |
+| Pro | 49 |
+
+- The scale is a rating, not an equation.
+- A single $ in prose is left alone too.
+
+That is all.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/long-prose-line.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/long-prose-line.md
new file mode 100644
index 00000000..95316db6
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/long-prose-line.md
@@ -0,0 +1 @@
+word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text. word *emph* and more text.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/nested-lists.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/nested-lists.md
new file mode 100644
index 00000000..be371c79
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/nested-lists.md
@@ -0,0 +1,15 @@
+### Build order
+
+1. Configure the toolchain
+ - Install Xcode 26
+ - Select the toolchain
+ - `xcode-select --switch`
+ - Verify with `swift --version`
+2. Build the package
+ 1. `swift build`
+ 2. `swift build --build-tests`
+3. Run the focused filters
+
+* Three-space marker level one
+ * Four-space nested level two
+ * Level three
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/prose-display-dollars.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/prose-display-dollars.md
new file mode 100644
index 00000000..74e7266f
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/prose-display-dollars.md
@@ -0,0 +1,10 @@
+It costs $$$ a lot. Rated $$ on the price scale.
+**Bold** line above the heading.
+# Heading
+
+The array \[1, 2, 3\] holds three values, and \[optional\] flags stay literal.
+
+- The rating is not an equation.
+- Neither is the bracket pair.
+
+Done.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/prose-fence.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/prose-fence.md
new file mode 100644
index 00000000..010dc180
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/prose-fence.md
@@ -0,0 +1,16 @@
+Here is the fix:
+```swift
+func apply(_ value: Int) -> Int {
+
+ return value + 1
+}
+```
+Done.
+
+The tilde form behaves the same way:
+~~~text
+first line
+
+second line
+~~~
+Both fences interrupt the sentence above them.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/quote-with-math.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/quote-with-math.md
new file mode 100644
index 00000000..49a66f00
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/quote-with-math.md
@@ -0,0 +1,4 @@
+> The identity $e^{i\pi} + 1 = 0$ links five fundamental constants.
+> It follows from $$e^{i\theta} = \cos\theta + i\sin\theta$$ evaluated at $\theta = \pi$.
+
+Ordinary text after the quote.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/reference-links.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/reference-links.md
new file mode 100644
index 00000000..97e7e5fa
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/reference-links.md
@@ -0,0 +1,4 @@
+See [the docs][docs] and [the guide][guide] for details.
+
+[docs]: https://example.com/docs
+[guide]: https://example.com/guide
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/shell-dollars.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/shell-dollars.md
new file mode 100644
index 00000000..a7f99afa
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/shell-dollars.md
@@ -0,0 +1,12 @@
+Set the search path before running the tool.
+
+```bash
+echo $HOME
+echo $PATH
+export TARGET="$HOME/$PATH"
+test $x = $y && echo ok
+```
+
+In prose the same variables appear as $HOME and $PATH, and the joined form
+`"$HOME/$PATH"` stays inside a backtick span. A shell comparison such as
+$x=$y on one line must not become an equation.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/tab-indented-fence.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/tab-indented-fence.md
new file mode 100644
index 00000000..ccb0998e
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/tab-indented-fence.md
@@ -0,0 +1,8 @@
+Here is the listing:
+
+ ```text
+ tab indented
+ space indented
+ ```
+
+Done.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-empty-cells.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-empty-cells.md
new file mode 100644
index 00000000..0b0cdee8
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-empty-cells.md
@@ -0,0 +1,7 @@
+| Feature | Basic | Pro |
+| --- | ---: | :---: |
+| Price | $20 | |
+| SSO | | yes |
+| Notes | short |
+
+The blank cells keep their columns.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-html-bold.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-html-bold.md
new file mode 100644
index 00000000..4b821e91
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-html-bold.md
@@ -0,0 +1,10 @@
+### Comparison
+
+| Feature | GCD Queues | Swift Actors |
+| :--- | :---: | ---: |
+| **Model** | Low-level.<br>Closure based. | High-level. |
+| **Safety** | Manual management.<br/>Prone to races. | **Built-in** protection. |
+| Notes | H<sub>2</sub>O and x<sup>2</sup> | `await` suspension |
+
+The table above is followed by an ordinary paragraph, which must render
+natively rather than forcing the whole message to raw text.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-in-list.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-in-list.md
new file mode 100644
index 00000000..a91aebaf
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/table-in-list.md
@@ -0,0 +1,9 @@
+Compare the two plans:
+
+- The table below sits inside this item:
+
+ | Tier | Cost |
+ | --- | --- |
+ | Basic | 20 |
+
+Done.
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/task-lists.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/task-lists.md
new file mode 100644
index 00000000..3d084bfd
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/task-lists.md
@@ -0,0 +1,10 @@
+#### Release checklist
+
+- [x] Define data model
+- [X] Implement synchronization
+- [ ] Optimize performance
+- [ ] Write the release note
+- plain item without a checkbox
+
+1. [x] Ordered done
+2. [ ] Ordered open
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/unclosed-display-math.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/unclosed-display-math.md
new file mode 100644
index 00000000..93970507
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/unclosed-display-math.md
@@ -0,0 +1,3 @@
+The derivative of the loss with respect to the weights is
+
+$$\frac{\partial L}{\partial w} = \sum_{i=1}^{n} (\hat{y}_i - y_i) x_i
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/unclosed-fence.md b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/unclosed-fence.md
new file mode 100644
index 00000000..1102c780
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Fixtures/transcript-corpus/unclosed-fence.md
@@ -0,0 +1,7 @@
+Here is the kernel so far:
+
+```metal
+kernel void reduce(device float *out [[buffer(0)]],
+ device const float *in [[buffer(1)]],
+ uint tid [[thread_position_in_threadgroup]]) {
+ out[tid] = in[tid] * 2.0f;
diff --git a/Tests/TurboFieldfareApp/MacPresentation/MathCommandNormalizerTests.swift b/Tests/TurboFieldfareApp/MacPresentation/MathCommandNormalizerTests.swift
new file mode 100644
index 00000000..c52a81df
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/MathCommandNormalizerTests.swift
@@ -0,0 +1,321 @@
+import AppKit
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+/// The 647-string coverage sweep the pin decision was made on: the 607-entry
+/// command sweep first, then the 40 longer expression probes.
+///
+/// Fourteen entries were stored double-encoded and measured as Latin letters
+/// rather than as the mathematical characters they name. Rewritten as real
+/// UTF-8 they moved the command sweep from 465 raw / 518 normalized to
+/// 453 raw / 506 normalized; the Unicode symbol table brings the normalized
+/// figure back to 517, and the one that stays out is a CJK word character with
+/// no command to map onto.
+///
+/// The raw figure then moved again, from 453 to 450, when the conformer began
+/// refusing what the pinned build drops without an error. `\u{221A}2`, `a~b`
+/// and `\text{if}~x` had been counted as passing because an image came back;
+/// the character they name was missing from it.
+enum MathCoverageFixture {
+ static let commandSweepCount = 607
+
+ static let sweep: [String] = load("latex-sweep")
+ static let expectedFailures: [String] = load("latex-sweep-failures")
+
+ /// Lines are exact LaTeX, including one entry that is a lone backslash and
+ /// a space, so nothing here may be trimmed.
+ private static func load(_ name: String) -> [String] {
+ guard let url = Bundle.module.url(
+ forResource: name,
+ withExtension: "txt",
+ subdirectory: "Fixtures/math-coverage"),
+ let text = try? String(contentsOf: url, encoding: .utf8) else {
+ return []
+ }
+ return text
+ .components(separatedBy: "\n")
+ .filter { !$0.isEmpty }
+ }
+}
+
+struct MathRewriteCase: Sendable {
+ let input: String
+ let output: String
+ /// Every rewrite exists so the result typesets; a row that does not is
+ /// a rule that is not earning its place.
+ var typesets = true
+}
+
+/// One row per rule in the table. Each is measured twice: the rewrite text
+/// itself, and the fact that the pinned typesetter accepts the result.
+enum MathRewriteCases {
+ static let all: [MathRewriteCase] = [
+ MathRewriteCase(input: #"\boxed{x+1}"#, output: #"x+1"#),
+ MathRewriteCase(input: #"\fbox{x}"#, output: #"x"#),
+ MathRewriteCase(input: #"\mbox{x}"#, output: #"x"#),
+ MathRewriteCase(input: #"\cancel{x}"#, output: #"x"#),
+ MathRewriteCase(input: #"\xcancel{x}"#, output: #"x"#),
+ MathRewriteCase(input: #"\sout{x}"#, output: #"x"#),
+ MathRewriteCase(input: #"\textcolor{red}{x}"#, output: #"x"#),
+ MathRewriteCase(input: #"\colorbox{red}{x}"#, output: #"x"#),
+ MathRewriteCase(input: #"\color{red} x"#, output: #" x"#),
+ MathRewriteCase(input: #"x \tag{1}"#, output: #"x "#),
+ MathRewriteCase(input: #"x \label{eq}"#, output: #"x "#),
+ MathRewriteCase(input: #"a \xrightarrow{f} b"#, output: #"a \rightarrow b"#),
+ MathRewriteCase(input: #"a \xleftarrow{f} b"#, output: #"a \leftarrow b"#),
+ MathRewriteCase(input: #"\underbrace{a+b}_{\text{sum}}"#, output: #"a+b"#),
+ MathRewriteCase(input: #"\overbrace{a+b}^{n}"#, output: #"a+b"#),
+ // The unbraced script form. Skipping only the command left its group
+ // behind, so the annotation glued onto the base as "a+btotal".
+ MathRewriteCase(input: #"\underbrace{a+b}_\text{total}"#, output: #"a+b"#),
+ MathRewriteCase(input: #"\overbrace{a+b}^\mathrm{sum}"#, output: #"a+b"#),
+ MathRewriteCase(input: #"\underbrace{a+b}_\alpha"#, output: #"a+b"#),
+ MathRewriteCase(input: #"\overset{a}{b}"#, output: #"{b}^{a}"#),
+ MathRewriteCase(input: #"\overset{\alpha}{b}"#, output: #"{b}^{\alpha}"#),
+ // A multi-token annotation would stack an expression over the base,
+ // which the replacement cannot express, so the base wins.
+ MathRewriteCase(input: #"\overset{a+b}{c}"#, output: #"{c}"#),
+ MathRewriteCase(input: #"\underset{a}{b}"#, output: #"{b}_{a}"#),
+ MathRewriteCase(input: #"\stackrel{?}{=}"#, output: #"{=}^{?}"#),
+ MathRewriteCase(input: #"x \nonumber"#, output: #"x "#),
+ MathRewriteCase(
+ input: #"\left( x \middle| y \right)"#,
+ output: #"\left( x | y \right)"#),
+ MathRewriteCase(
+ input: #"\begin{array}{|c|c|} \hline a & b \end{array}"#,
+ output: #"\begin{matrix} a & b \end{matrix}"#),
+ MathRewriteCase(input: #"\lvert x \rvert"#, output: #"| x |"#),
+ MathRewriteCase(input: #"\lVert x \rVert"#, output: #"\| x \|"#),
+ MathRewriteCase(input: #"x \dots y"#, output: #"x \ldots y"#),
+ MathRewriteCase(input: #"x \dotsc y"#, output: #"x \ldots y"#),
+ MathRewriteCase(input: #"x \therefore y"#, output: "x \\text{\u{2234}} y"),
+ MathRewriteCase(input: #"x \because y"#, output: "x \\text{\u{2235}} y"),
+ MathRewriteCase(input: #"a \: b"#, output: #"a \, b"#),
+ MathRewriteCase(input: #"a \bmod b"#, output: #"a \ \mathrm{mod}\ b"#),
+ MathRewriteCase(input: #"\pmb{x}"#, output: #"\mathbf{x}"#),
+ MathRewriteCase(input: #"\mathscr{L}"#, output: #"\mathcal{L}"#),
+ MathRewriteCase(input: #"a \coloneqq b"#, output: #"a := b"#),
+ MathRewriteCase(input: #"a \eqqcolon b"#, output: #"a =: b"#),
+ MathRewriteCase(
+ input: #"\begin{align} a &= b \end{align}"#,
+ output: #"\begin{aligned} a &= b \end{aligned}"#),
+ MathRewriteCase(
+ input: #"\begin{align*} a &= b \end{align*}"#,
+ output: #"\begin{aligned} a &= b \end{aligned}"#),
+ MathRewriteCase(
+ input: #"\begin{alignat}{2} a &= b \end{alignat}"#,
+ output: #"\begin{aligned} a &= b \end{aligned}"#),
+ MathRewriteCase(
+ input: #"\begin{alignat*}{2} a &= b \end{alignat*}"#,
+ output: #"\begin{aligned} a &= b \end{aligned}"#),
+ MathRewriteCase(
+ input: #"\begin{aligned*} a \end{aligned*}"#,
+ output: #"\begin{aligned} a \end{aligned}"#),
+ MathRewriteCase(
+ input: #"\begin{gather*} a \\ b \end{gather*}"#,
+ output: #"\begin{aligned} a \\ b \end{aligned}"#),
+ MathRewriteCase(
+ input: #"\begin{equation} a = b \end{equation}"#,
+ output: #"\begin{aligned} a = b \end{aligned}"#),
+ MathRewriteCase(
+ input: #"\begin{equation*} a = b \end{equation*}"#,
+ output: #"\begin{aligned} a = b \end{aligned}"#),
+ MathRewriteCase(
+ input: #"\begin{array}{cc} a & b \end{array}"#,
+ output: #"\begin{matrix} a & b \end{matrix}"#),
+ MathRewriteCase(
+ input: #"\begin{rcases} a \\ b \end{rcases}"#,
+ output: #"\begin{cases} a \\ b \end{cases}"#),
+ // The radical is a character, not a command: the build had no atom for
+ // it, so it drew nothing and the equation looked complete without it.
+ MathRewriteCase(input: "\u{221A}2", output: #"\sqrt{2}"#),
+ MathRewriteCase(input: "\u{221A}16.5", output: #"\sqrt{16.5}"#),
+ MathRewriteCase(input: "\u{221A}x", output: #"\sqrt{x}"#),
+ MathRewriteCase(input: "\u{221A}{x+1}", output: #"\sqrt{x+1}"#),
+ MathRewriteCase(input: "\u{221A}(a+b)", output: #"\sqrt{a+b}"#),
+ MathRewriteCase(input: "\u{221A}\\alpha", output: #"\sqrt{\alpha}"#),
+ MathRewriteCase(input: "f\u{2032}(x)", output: #"f^{\prime}(x)"#),
+ MathRewriteCase(input: "f\u{2033}(x)", output: #"f^{\prime\prime}(x)"#),
+ MathRewriteCase(input: "f\u{2032}\u{2032}(x)", output: #"f^{\prime\prime}(x)"#),
+ MathRewriteCase(input: "90\u{00B0}", output: #"90^{\circ}"#),
+ MathRewriteCase(input: "50%", output: #"50\%"#),
+ MathRewriteCase(input: "a~b", output: #"a\ b"#),
+ MathRewriteCase(input: "a\u{00A0}b", output: #"a\ b"#),
+ MathRewriteCase(input: "a\u{2009}b", output: #"a\,b"#),
+ MathRewriteCase(input: "x\u{200B}y", output: "xy"),
+ MathRewriteCase(input: "\u{00AC}p \u{2228} q", output: #"\neg p \lor q"#),
+ MathRewriteCase(input: "x \u{226A} y", output: #"x \ll y"#),
+ MathRewriteCase(input: "\u{2308}x\u{2309}", output: #"\lceil x\rceil"#),
+ ]
+}
+
+@MainActor
+@Suite struct MathCommandNormalizerTests {
+ static func typesets(_ latex: String) -> Bool {
+ SwiftMathTypesetter().render(
+ latex: latex,
+ fontSize: 13,
+ tint: .black,
+ mode: .inline) != nil
+ }
+
+ @Test(arguments: MathRewriteCases.all)
+ func eachRewriteProducesLatexThePinnedTypesetterAccepts(_ rewrite: MathRewriteCase) {
+ #expect(MathCommandNormalizer.normalize(rewrite.input) == rewrite.output,
+ "\(rewrite.input.debugDescription)")
+ #expect(Self.typesets(rewrite.output) == rewrite.typesets,
+ "\(rewrite.output.debugDescription)")
+ }
+
+ /// Every rule must be pulling its weight: if the pinned revision already
+ /// renders the input, the rewrite is trading real notation for an
+ /// approximation and should be deleted instead.
+ @Test(arguments: MathRewriteCases.all)
+ func noRewriteReplacesLatexThatAlreadyTypesets(_ rewrite: MathRewriteCase) {
+ #expect(!Self.typesets(rewrite.input), "\(rewrite.input.debugDescription)")
+ }
+
+ static func nested(_ command: String, depth: Int, body: String = "x") -> String {
+ String(repeating: "\\\(command){", count: depth)
+ + body
+ + String(repeating: "}", count: depth)
+ }
+
+ /// A rewritten argument is rewritten in turn, so nesting depth is stack
+ /// depth. Without the cap this crashes the process with SIGSEGV rather
+ /// than failing: the recursion died at 8000 levels with 4000 completing.
+ @Test func runawayNestingReturnsTheInputInsteadOfOverflowingTheStack() {
+ let runaway = Self.nested("boxed", depth: 8000)
+ #expect(MathCommandNormalizer.normalize(runaway) == runaway)
+ }
+
+ /// The cap has to sit far above anything a real answer nests, or a fix for
+ /// the crash becomes a rendering regression.
+ @Test func nestingWellInsideTheCapIsStillRewritten() {
+ #expect(MathCommandNormalizer.normalize(Self.nested("boxed", depth: 20)) == "x")
+ #expect(MathCommandNormalizer.normalize(
+ Self.nested("boxed", depth: 200, body: #"\frac{a}{b}"#)) == #"\frac{a}{b}"#)
+ }
+
+ @Test func unknownCommandsPassThroughUnchanged() {
+ let unknown = #"\unknowncmd{x} + \frac{a}{b}"#
+ #expect(MathCommandNormalizer.normalize(unknown) == unknown)
+ #expect(!Self.typesets(unknown))
+ }
+
+ /// What Gemma 4 actually emits must survive the normalizer byte for byte;
+ /// a rewrite that fires on working input is a mangling, not a fix.
+ @Test(arguments: [
+ #"ax^2 + bx + c = 0"#,
+ #"x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}"#,
+ #"|x| = \begin{cases} x & \text{if } x \geq 0 \\ -x & \text{if } x < 0 \end{cases}"#,
+ #"\begin{aligned} E[X] &= \sum_{i=1}^{6} i \cdot P(X=i) \\ &= 3.5 \end{aligned}"#,
+ #"\frac{\mathbf{A} \cdot \mathbf{B}}{\|\mathbf{A}\| \|\mathbf{B}\|}"#,
+ #"e^{i\pi} + 1 = 0"#,
+ ])
+ func workingLatexIsLeftAlone(_ latex: String) {
+ #expect(MathCommandNormalizer.normalize(latex) == latex)
+ #expect(Self.typesets(latex))
+ }
+
+ @Test func coverageFixturesLoadAtTheRecordedSize() {
+ #expect(MathCoverageFixture.sweep.count == 647)
+ #expect(MathCoverageFixture.expectedFailures.count == 90)
+ #expect(MathCoverageFixture.sweep.count > MathCoverageFixture.commandSweepCount)
+ }
+
+ /// Spacing has no replacement that typesets on its own — a lone space is a
+ /// zero-size image, which the conformer refuses — so it is pinned in
+ /// context instead of through the symbol-table row test.
+ @Test func everySpacingRuleReplacesADroppedCharacterWithAnAcceptedCommand() {
+ for (character, command) in MathCommandNormalizer.spacing {
+ #expect(!Self.typesets("a\(character)b"), "a\(character)b already typesets")
+ #expect(MathCommandNormalizer.normalize("a\(character)b") == "a\(command)b")
+ #expect(Self.typesets("a\(command)b"), "\(command) does not typeset")
+ }
+ for character in MathCommandNormalizer.removed {
+ #expect(!Self.typesets("a\(character)b"))
+ #expect(MathCommandNormalizer.normalize("a\(character)b") == "ab")
+ }
+ }
+
+ /// The sweep's fourteen Unicode entries were stored double-encoded, so what
+ /// the fixture actually measured was a run of Latin letters: twelve of them
+ /// passed for the wrong reason. Rewritten as the characters they were meant
+ /// to be, they fail the pinned typesetter outright and the symbol table is
+ /// what carries them.
+ @Test(arguments: [
+ "\u{03C0}", "\u{00D7}", "\u{2264}", "\u{2192}", "\u{2212}",
+ "\u{03B1}", "\u{221E}", "\u{2211}", "\u{00BD}", "\u{2026}",
+ "\u{211D}",
+ ])
+ func unicodeMathCharactersTypesetOnlyAfterNormalization(_ character: String) {
+ #expect(!Self.typesets(character), "\(character.debugDescription)")
+ #expect(Self.typesets(MathCommandNormalizer.normalize(character)),
+ "\(character.debugDescription)")
+ }
+
+ /// `\u{221A}2` looked like an entry the pinned revision already drew, and
+ /// it is not: the build has no atom for the radical and skipped it, so the
+ /// image was `2` and nothing said so. The accented letter is drawn for
+ /// real, through the table `atom(forCharacter:)` consults first.
+ @Test func theRadicalOnlyLookedLikeSomethingThePinnedRevisionDrew() {
+ #expect(!Self.typesets("\u{221A}2"))
+ #expect(MathCommandNormalizer.normalize("\u{221A}2") == #"\sqrt{2}"#)
+ #expect(Self.typesets(MathCommandNormalizer.normalize("\u{221A}2")))
+
+ #expect(Self.typesets("\u{00E9}"))
+ #expect(MathCommandNormalizer.normalize("\u{00E9}") == "\u{00E9}")
+ // A CJK word character is not mathematical notation and has no command
+ // to map onto; it stays in the expected-failure list.
+ #expect(!Self.typesets("\u{4E2D}"))
+ #expect(MathCoverageFixture.expectedFailures.contains("\u{4E2D}"))
+ }
+
+ /// Every row of the symbol table, measured in both directions: the
+ /// character on its own is rejected, so the rule is earning its place, and
+ /// what it rewrites to is accepted.
+ @Test func everySymbolRuleReplacesARejectedCharacterWithAnAcceptedCommand() {
+ for (character, command) in MathCommandNormalizer.symbols {
+ #expect(!Self.typesets(String(character)), "\(character) already typesets")
+ #expect(MathCommandNormalizer.normalize(String(character)) == command,
+ "\(character)")
+ #expect(Self.typesets(command), "\(command) does not typeset")
+ }
+ }
+
+ /// A command may not run into the letter after it, or the two spell an
+ /// unknown command and the whole equation falls back to raw text.
+ @Test func aSymbolFollowedByALetterKeepsItsCommandSeparate() {
+ #expect(MathCommandNormalizer.normalize("\u{03B1}b") == "\\alpha b")
+ #expect(MathCommandNormalizer.normalize("\u{03B1}2") == "\\alpha2")
+ #expect(MathCommandNormalizer.normalize("x \u{2264} 5") == "x \\le 5")
+ #expect(Self.typesets(MathCommandNormalizer.normalize("\u{03B1}b")))
+ }
+
+ /// The sweep is the pin's regression gate: moving SwiftMath, or adding a
+ /// normalizer rule, shows up here as a named string that changed side.
+ @Test(arguments: MathCoverageFixture.sweep)
+ func sweepStringMatchesRecordedCoverage(_ latex: String) {
+ let expected = !MathCoverageFixture.expectedFailures.contains(latex)
+ #expect(Self.typesets(MathCommandNormalizer.normalize(latex)) == expected,
+ "\(latex.debugDescription)")
+ }
+
+ /// Records the two numbers the pin decision is argued from, so a rerun
+ /// prints them rather than requiring a separate probe.
+ @Test func sweepCoverageImprovesWithNormalization() {
+ let commands = MathCoverageFixture.sweep.prefix(
+ MathCoverageFixture.commandSweepCount)
+ let raw = commands.count { Self.typesets($0) }
+ let normalized = commands.count { Self.typesets(MathCommandNormalizer.normalize($0)) }
+ print("MATH-SWEEP commands=\(commands.count) raw=\(raw) normalized=\(normalized)")
+ #expect(normalized > raw)
+ // Three entries left the raw column when the conformer started refusing
+ // what the build silently drops: the radical and the two tilde spaces.
+ // The rewrites below carry all three, so the normalized figure holds.
+ #expect(raw == 450)
+ #expect(normalized == 517)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/MathSpanDetectorTests.swift b/Tests/TurboFieldfareApp/MacPresentation/MathSpanDetectorTests.swift
new file mode 100644
index 00000000..e3aa8985
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/MathSpanDetectorTests.swift
@@ -0,0 +1,461 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@Suite struct MathSpanDetectorTests {
+ static func sources(_ text: String) -> [String] {
+ MathSpanDetector.spans(in: text).map(\.source)
+ }
+
+ static func modes(_ text: String) -> [MathSpan.Mode] {
+ MathSpanDetector.spans(in: text).map(\.mode)
+ }
+
+ // MARK: - Inline basics
+
+ @Test func findsOneSpanWithItsSurroundingTextIntact() {
+ let spans = MathSpanDetector.spans(in: "Solve $x^2 + 1$ now.")
+ #expect(spans.count == 1)
+ #expect(spans[0].source == "$x^2 + 1$")
+ #expect(spans[0].latex == "x^2 + 1")
+ #expect(spans[0].mode == .inline)
+ #expect(spans[0].range == 6..<15)
+ }
+
+ @Test(arguments: [
+ ("$a$ and $b$", ["$a$", "$b$"]),
+ ("$a$ start of line", ["$a$"]),
+ ("ends with $b$", ["$b$"]),
+ ("$$x = 1$$", ["$$x = 1$$"]),
+ ("no math here", []),
+ ])
+ func findsEverySpanInALine(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0)")
+ }
+
+ // MARK: - Pandoc conditions
+
+ @Test(arguments: [
+ ("$x$", ["$x$"]),
+ ("$ x$", []),
+ ("$x $", []),
+ ("$20,000 and $30,000", []),
+ (#"\$5 is cheap"#, []),
+ // Two backslashes are an escaped backslash, so the dollar after them
+ // still opens a span.
+ (#"\\$x$"#, ["$x$"]),
+ ("$a\nb$", []),
+ ("$$", []),
+ ("$", []),
+ ])
+ func appliesThePandocDollarConditions(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ /// Gemma 4 writes currency inside math as `$\$0.60$`; the escaped dollar
+ /// must not be mistaken for the closer.
+ @Test func escapedDollarInsideASpanDoesNotCloseIt() {
+ let spans = MathSpanDetector.spans(in: #"Unit cost $\$0.60$ each."#)
+ #expect(spans.map(\.source) == [#"$\$0.60$"#])
+ #expect(spans[0].latex == #"\$0.60"#)
+ }
+
+ // MARK: - Adjacency extensions
+
+ @Test(arguments: [
+ ("x=$a$b", []),
+ ("$FOO/bar$BAZ", []),
+ ("https://ex.com/$a/$b", []),
+ ("($x$)", ["$x$"]),
+ ("word $x$.", ["$x$"]),
+ ("cost $x$2 apples", []),
+ ("path/$x$", []),
+ ])
+ func appliesTheAdjacencyExtensions(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ /// The scan walked past a `$` it had already refused as a closer, so the
+ /// currency before an equation and the equation itself became one span and
+ /// the whole sentence typeset as prose. A `$` after whitespace cannot
+ /// close anything; it is where the next candidate starts.
+ @Test(arguments: [
+ ("It costs $5 (or $10 for two). The formula $E=mc^2$ applies.", ["$E=mc^2$"]),
+ ("the $n$th term is $a_n$", ["$a_n$"]),
+ ("Costs $20 and $30 each; $x$ is the count", ["$x$"]),
+ ("Refunds under $5 today; anything over $100 needs review.", []),
+ ("| Basic | $20 | $200 |", []),
+ // The candidate is abandoned at the second opener rather than swallowing
+ // the space between them.
+ ("$a $b$", ["$b$"]),
+ // A `$<digit>` candidate that spans whitespace is currency unless its
+ // content reads as math.
+ ("I paid $20 for the $50 item$", []),
+ (#"The result is $5 \times 10^3$ exactly."#, [#"$5 \times 10^3$"#]),
+ ])
+ func aWhitespacePrecededDollarStartsTheNextCandidate(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ /// `isLetter` and `isNumber` are Unicode-wide, so a Han or Cyrillic
+ /// character beside a delimiter read as a word character and the equation
+ /// stayed raw. The adjacency rules exist for shell and URL text, which is
+ /// ASCII; the `/` rule is unchanged.
+ @Test(arguments: [
+ ("\u{8D28}\u{91CF}\u{4E3A}$m$\u{7684}\u{7269}\u{4F53}", ["$m$"]),
+ ("\u{044D}\u{043D}\u{0435}\u{0440}\u{0433}\u{0438}\u{044F}$E$\u{0440}\u{0430}\u{0432}\u{043D}\u{0430}", ["$E$"]),
+ ("\u{516C}\u{5F0F}$E = mc^2$\u{6210}\u{7ACB}\u{3002}", ["$E = mc^2$"]),
+ (#"\u{534A}\u{5F84}$r$\u{FF0C}\u{9762}\u{79EF}$A = \pi r^2$\u{3002}"#, ["$r$", #"$A = \pi r^2$"#]),
+ ("caf\u{E9}$x$", ["$x$"]),
+ ])
+ func adjacencyRulesOnlyCountASCIIWordCharacters(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ // MARK: - Display
+
+ @Test func findsSingleLineAndMultilineDisplaySpans() {
+ #expect(Self.sources("$$x = 1$$") == ["$$x = 1$$"])
+ #expect(Self.sources("$$\nx = 1\n$$") == ["$$\nx = 1\n$$"])
+ #expect(Self.sources("$$ x = 1 $$") == ["$$ x = 1 $$"])
+ }
+
+ /// A rejected `$$` opener resumes at the character after itself, never
+ /// after the blank line, so the rest of the answer is untouched.
+ @Test func aBlankLineRejectsTheCandidateAndLeavesTheRestOfTheMessage() {
+ let source = "$$broken\n\nstill here $x$ and $$y$$"
+ #expect(Self.sources(source) == ["$x$", "$$y$$"])
+ }
+
+ @Test func displayTakesPrecedenceOverInline() {
+ #expect(Self.modes("$$x$$") == [.display])
+ #expect(Self.sources("$$$$") == [])
+ }
+
+ /// A `$$` region that was rejected is never re-offered to the single
+ /// dollar pass, so the two dollars it consumed cannot pair with later
+ /// text.
+ @Test func adjacentDollarsResolveWithoutReofferingConsumedText() {
+ #expect(Self.sources("$a$$b$") == ["$a$", "$b$"])
+ }
+
+ @Test func twoDisplayBlocksSeparatedByOneNewlineAreTwoSpans() {
+ let source = "$$a = 1$$\n$$b = 2$$"
+ #expect(Self.sources(source) == ["$$a = 1$$", "$$b = 2$$"])
+ #expect(MathSpanDetector.substitute(source).working
+ == "\n\n\u{E000}0\u{E001}\n\n\n\n\n\u{E000}1\u{E001}\n\n")
+ }
+
+ /// A `$$` was an opener anywhere, and an unclosed one shielded the rest of
+ /// the answer as raw source unless a blank line happened to follow. Three
+ /// or more dollars are never an opener, and only a line-start opener whose
+ /// content reads as TeX earns the shield.
+ @Test(arguments: [
+ ("It costs $$$ a lot.\n**Bold** line\n# Heading", []),
+ ("Rated $$ on the price scale.\n- item", []),
+ ("See \\[ in the note.\n# Heading", []),
+ ("$$$x$$$", []),
+ ("a $$$ b $$ c $$", ["$$ c $$"]),
+ // Line start is necessary but not sufficient: the content has to look
+ // like an equation the model was cut off in the middle of.
+ ("Text\n\n$$x = 1", []),
+ ("Text\n\n$$x = \\frac{1", ["$$x = \\frac{1"]),
+ ("- Step:\n $$\\frac{a}{b}", ["$$\\frac{a}{b}"]),
+ ])
+ func onlyALineStartOpenerWithTeXContentProtectsTheRest(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ /// A blank line is the display block's hard boundary in both directions:
+ /// nothing past one can close an opener, and an opener nothing closes
+ /// protects only as far as the boundary.
+ @Test func aDisplayBlockNeverCrossesABlankLine() {
+ let source = "Intro.\n\n$$\n\\frac{a}{b}\n\nc = d\n$$\n\nAfter $x$"
+ let spans = MathSpanDetector.spans(in: source)
+ #expect(spans.map(\.source) == ["$$\n\\frac{a}{b}", "$x$"])
+ #expect(spans.first?.isLiteralProtect == true)
+ #expect(spans.last?.isLiteralProtect == false)
+ }
+
+ // MARK: - Backslash forms
+
+ @Test(arguments: [
+ (#"\[x = 1\]"#, [#"\[x = 1\]"#]),
+ (#"\(x^2\)"#, [#"\(x^2\)"#]),
+ // No command and no operator: prose, not math.
+ (#"\(count\)"#, []),
+ (#"Regex groups like \(abc\) read as prose."#, []),
+ (#"\(\alpha\)"#, [#"\(\alpha\)"#]),
+ ])
+ func findsBackslashDelimiters(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ @Test func findsKnownEnvironmentsAtLineStartOnly() {
+ let known = "\\begin{align}\na &= b\n\\end{align}"
+ #expect(Self.sources(known) == [known])
+ #expect(Self.modes(known) == [.display])
+ #expect(Self.sources("\\begin{unknown}\na\n\\end{unknown}").isEmpty)
+ #expect(Self.sources("text \\begin{align}\na\n\\end{align}").isEmpty)
+ // `aligned` is an inline environment, not a block one: Gemma emits it
+ // inside a single-dollar span and KaTeX does not auto-render it.
+ #expect(Self.sources("\\begin{aligned}\na\n\\end{aligned}").isEmpty)
+ }
+
+ /// `\[ ... \]` was math wherever it appeared, so an escaped bracket pair in
+ /// prose became an equation and the words inside it disappeared into a
+ /// failed typeset. It is math when the content reads as math, or when the
+ /// pair owns its line.
+ @Test(arguments: [
+ (#"the array \[1, 2, 3\] holds"#, []),
+ (#"\[1, 2, 3\]"#, [#"\[1, 2, 3\]"#]),
+ (#"\[ x \]"#, [#"\[ x \]"#]),
+ (#"Set \[optional\] flag"#, []),
+ (#"Note \[x = 1\] inline"#, [#"\[x = 1\]"#]),
+ ])
+ func bracketDelimitersNeedMathContentOrTheirOwnLine(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ // MARK: - Code protection
+
+ @Test(arguments: [
+ "`$x$`",
+ "```\n$$x$$\n```",
+ "```bash\necho $HOME\nexport T=\"$HOME/$PATH\"\n```",
+ "Before\n\n $a$ indented code\n\nAfter",
+ "~~~\n$a$\n~~~",
+ ])
+ func codeRegionsHideTheirDollars(_ source: String) {
+ #expect(Self.sources(source).isEmpty, "\(source.debugDescription)")
+ }
+
+ /// Two lone backticks in different paragraphs are prose, not a code span.
+ /// Pairing them masked everything between, so an equation in the middle
+ /// typeset while it streamed and reverted to raw source at finalize.
+ @Test func backtickSpansDoNotPairAcrossABlankLine() {
+ let source = """
+ Press the ` key to open the console.
+
+ The relation is $E = mc^2$ exactly.
+
+ Use the ` character to quote a word.
+ """
+ #expect(Self.sources(source) == ["$E = mc^2$"])
+ }
+
+ /// The bound is the blank line, not the line end: a genuine code span
+ /// still hides its dollars, wrapped or not.
+ @Test func aCodeSpanWithinOneParagraphStillMasksItsDollars() {
+ #expect(Self.sources("Run `echo $HOME now` please").isEmpty)
+ #expect(Self.sources("Run `echo\n$HOME now` please").isEmpty)
+ }
+
+ @Test func fourSpaceListContinuationIsNotCode() {
+ let source = "- item\n\n continues with $a$ inside\n"
+ #expect(Self.sources(source) == ["$a$"])
+ }
+
+ /// The mask opened a fence on "```bash```" and hid every dollar below it,
+ /// so an answer that names the fence syntax lost all of its math.
+ @Test func aBacktickInfoStringDoesNotOpenACodeFence() {
+ #expect(Self.sources("```bash``` is the fence syntax for $x$ here.") == ["$x$"])
+ #expect(Self.sources("```bash```\n\n$$y$$") == ["$$y$$"])
+ }
+
+ /// The mask read every fence at column zero, so a listing indented into a
+ /// nested item was never a fence and its shell variables typeset as
+ /// equations. It also read `- - -` as a bullet, which kept a list open
+ /// across the rule and stopped the indented block under it being code.
+ @Test(arguments: [
+ // A fence two levels in: only the span outside it survives. Tilde
+ // fences, so the backtick-span mask cannot cover for the block mask.
+ (
+ "1. Outer\n - Inner\n ~~~bash\n cost $a$ here\n ~~~\n - Next $x$",
+ ["$x$"]
+ ),
+ ("- item\n ~~~\n $a$\n ~~~\n- next $b$", ["$b$"]),
+ // An indented block after a heading is code; the heading is a leaf
+ // block, so there is no paragraph for it to be a continuation of.
+ ("# Title\n let x = $a$\n\nAfter $b$", ["$b$"]),
+ ("- - -\n\n $a$ code", []),
+ // A deep indent that continues the item's own paragraph is lazy
+ // continuation, not code.
+ ("- item\n lazy $a$", ["$a$"]),
+ ])
+ func theCodeMaskFollowsContainerIndentation(_ probe: (String, [String])) {
+ #expect(Self.sources(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ @Test func mathImmediatelyAfterACodeRegionIsStillFound() {
+ #expect(Self.sources("`code` then $x$") == ["$x$"])
+ #expect(Self.sources("```\ncode\n```\n\n$$y$$") == ["$$y$$"])
+ }
+
+ /// An unmatched backtick opens nothing, but the two that do match hide the
+ /// dollars between them, so this string yields no math at all.
+ @Test func unbalancedBackticksStillPairByCommonMarkRules() {
+ #expect(Self.sources("$a`$ and $b`$").isEmpty)
+ }
+
+ // MARK: - Streaming shapes
+
+ @Test func unclosedDisplayOpenersBecomeLiteralProtectSpans() {
+ for source in ["Text\n\n$$\\frac{a}{b} = c", "Text\n\n\\[\\frac{a}{b} = c"] {
+ let spans = MathSpanDetector.spans(in: source)
+ #expect(spans.count == 1, "\(source.debugDescription)")
+ #expect(spans.first?.isLiteralProtect == true)
+ #expect(spans.first?.mode == .display)
+ #expect(spans.first?.source.hasSuffix("= c") == true)
+ #expect(spans.first?.latex == spans.first?.source)
+ }
+ }
+
+ @Test func unclosedSingleDollarStaysPlainText() {
+ #expect(Self.sources("The price is $5 and rising").isEmpty)
+ #expect(Self.sources("Half an equation $x = ").isEmpty)
+ }
+
+ /// Two dollars in a sentence are not a cut-off equation. Protecting from
+ /// there to the end of the answer showed every heading, table, and list
+ /// below it as raw source.
+ @Test(arguments: [
+ "Rated $$ on the price scale.\n\n# Heading\n\n| A | B |\n| --- | --- |\n| 1 | 2 |",
+ "See \\[ in the note.\n\n# Heading\n\nBody text.",
+ ])
+ func anOpenerWithABlankLineAfterItIsPlainText(_ source: String) {
+ #expect(Self.sources(source).isEmpty, "\(source.debugDescription)")
+ }
+
+ /// The interrupted-generation case the protection exists for: nothing
+ /// follows the opener but the half-typed equation.
+ @Test func aTrailingOpenerWithNoBlankLineAfterItStaysProtected() {
+ for source in ["Text\n\n$$\\frac{", "Text\n\n\\[\\frac{"] {
+ let spans = MathSpanDetector.spans(in: source)
+ #expect(spans.count == 1, "\(source.debugDescription)")
+ #expect(spans.first?.isLiteralProtect == true)
+ }
+ }
+
+ @Test func aTrailingDisplayOpenerWithNoContentIsNotASpan() {
+ #expect(Self.sources("Text\n\n$$").isEmpty)
+ #expect(Self.sources("Text\n\n$$\n").isEmpty)
+ }
+
+ // MARK: - Robustness
+
+ @Test func handlesCRLFAndNonASCIINeighbours() {
+ #expect(Self.sources("Line\r\n$$x = 1$$\r\nAfter\r\n") == ["$$x = 1$$"])
+ #expect(Self.sources("\u{4E2D}\u{6587} $E = mc^2$ \u{4E2D}\u{6587}") == ["$E = mc^2$"])
+ #expect(Self.sources("caf\u{E9} $x$ caf\u{E9}") == ["$x$"])
+ }
+
+ /// Swift reads CRLF as one `Character`, so every line rule in the detector
+ /// looked straight through it. Each of these behaves one way for LF and
+ /// another for CRLF until the scan splits the pair.
+ @Test func everyLineRuleTreatsCRLFExactlyAsLF() {
+ // A single-dollar span may not cross a line end.
+ #expect(Self.sources("Costs $20\nUSD$ each").isEmpty)
+ #expect(Self.sources("Costs $20\r\nUSD$ each").isEmpty)
+
+ // A fence hides its dollars and releases the math after it.
+ #expect(Self.sources("```bash\necho $HOME\n```\n\n$$x = 1$$") == ["$$x = 1$$"])
+ #expect(Self.sources("```bash\r\necho $HOME\r\n```\r\n\r\n$$x = 1$$") == ["$$x = 1$$"])
+
+ // A blank line rejects a `$$` opener instead of protecting the rest.
+ #expect(Self.sources("$$broken\n\nstill here $x$") == ["$x$"])
+ #expect(Self.sources("$$broken\r\n\r\nstill here $x$") == ["$x$"])
+ }
+
+ /// The working copy is a substitution over the original bytes, never a
+ /// normalized copy: whatever is not a span comes back exactly as written,
+ /// CRLF included, because raw fallbacks re-emit it.
+ @Test func substitutionOverCRLFKeepsTheOriginalLineEndings() {
+ let source = "Line one\r\n\r\nCosts $x$ here\r\n"
+ let substitution = MathSpanDetector.substitute(source)
+ #expect(substitution.working == "Line one\r\n\r\nCosts \u{E000}0\u{E001} here\r\n")
+ #expect(substitution.spans.map(\.source) == ["$x$"])
+ }
+
+ /// Every opener used to rescan the whole region ahead of it, so an answer
+ /// full of unclosable dollars cost one pass per dollar: 180 KB of `$a `
+ /// took 16.1 s and froze the transcript. The bound is generous on purpose
+ /// — what it catches is the quadratic shape, not a few milliseconds.
+ @Test func inlineScanningStaysLinearOnALargeAnswer() {
+ let source = String(repeating: "$a ", count: 60_000)
+ #expect(source.utf8.count == 180_000)
+ let elapsed = ContinuousClock().measure {
+ #expect(MathSpanDetector.spans(in: source).isEmpty)
+ }
+ // Generous on purpose, and it has to hold on a shared CI runner as well
+ // as a fast laptop: what it catches is the quadratic shape, not a few
+ // milliseconds. The defect it exists for took 16.1 s.
+ #expect(elapsed < .seconds(1), "180 KB inline scan took \(elapsed)")
+ }
+
+ /// `isEscaped` counted the backslashes before every candidate, so a run of
+ /// them cost one backward walk per character: 80 KB measured 0.98 s, and
+ /// the open block is rescanned on every streaming tick. The parity is a
+ /// mask built once per message instead.
+ @Test func escapeScanningStaysLinearOnALongBackslashRun() {
+ let even = String(repeating: #"\"#, count: 80_000) + "$x$"
+ let odd = String(repeating: #"\"#, count: 80_001) + "$x$"
+ let elapsed = ContinuousClock().measure {
+ #expect(Self.sources(even) == ["$x$"])
+ #expect(Self.sources(odd).isEmpty)
+ }
+ // Same bound and the same reason as the inline scan above: the defect
+ // this exists for took 86.5 s, so a second still leaves 86x of margin
+ // while tolerating a runner that is not a fast laptop.
+ #expect(elapsed < .seconds(1), "80 KB of backslashes took \(elapsed)")
+ }
+
+ /// A model that emits the sentinel characters itself must not be able to
+ /// alias a placeholder, so they are stripped before anything is indexed.
+ @Test func preExistingSentinelCharactersAreStrippedBeforeSubstitution() {
+ let source = "Odd \u{E000}7\u{E001} output with $x$"
+ let substitution = MathSpanDetector.substitute(source)
+ #expect(substitution.working == "Odd 7 output with \u{E000}0\u{E001}")
+ #expect(substitution.spans.map(\.source) == ["$x$"])
+ }
+
+ // MARK: - Substitution
+
+ @Test func substitutionIndexesEverySpanAndKeepsTheRestOfTheText() {
+ let substitution = MathSpanDetector.substitute("a $x$ b $y$ c")
+ #expect(substitution.working == "a \u{E000}0\u{E001} b \u{E000}1\u{E001} c")
+ #expect(substitution.spans.count == 2)
+ }
+
+ /// The Gemma derivation shape: a `$$` line directly under a text line with
+ /// no blank line between them. Without promotion the two share a
+ /// paragraph and the soft break becomes a space.
+ @Test func standaloneDisplayMathIsPromotedToItsOwnParagraph() {
+ let substitution = MathSpanDetector.substitute("Subtract $c$:\n$$ax^2 + bx = -c$$\nNext")
+ #expect(substitution.working
+ == "Subtract \u{E000}0\u{E001}:\n\n\n\u{E000}1\u{E001}\n\n\nNext")
+ }
+
+ @Test func displayMathInsideAQuoteIsNotPromoted() {
+ let substitution = MathSpanDetector.substitute("> from $$e^{i\\theta}$$ at zero")
+ #expect(substitution.working == "> from \u{E000}0\u{E001} at zero")
+ }
+
+ // MARK: - Measured markdown mangling
+
+ /// Each of these is altered by `AttributedString(markdown:)` today, so the
+ /// detector has to hand the typesetter the source bytes instead.
+ @Test(arguments: [
+ #"$a \, b$"#,
+ #"$\{x\}$"#,
+ #"\[x = 1\]"#,
+ #"$a*b*c$"#,
+ #"$|x| = \begin{cases} x & x \ge 0 \\ -x & x < 0 \end{cases}$"#,
+ #"$\begin{aligned} a &= b \\ &= c \end{aligned}$"#,
+ ])
+ func mangledFormsReachTheTypesetterByteIdentical(_ source: String) {
+ let spans = MathSpanDetector.spans(in: source)
+ #expect(spans.count == 1, "\(source.debugDescription)")
+ #expect(spans.first?.source == source)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/MathTypesetterCoverageTests.swift b/Tests/TurboFieldfareApp/MacPresentation/MathTypesetterCoverageTests.swift
new file mode 100644
index 00000000..bbb39db9
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/MathTypesetterCoverageTests.swift
@@ -0,0 +1,102 @@
+import AppKit
+import Foundation
+import SwiftMath
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+/// The one place that reaches the typesetting library directly rather than
+/// through the production conformer. `PinnedMathCoverage` is a model of what
+/// the pinned build draws, and a model is only worth having if something
+/// measures it against the build; the conformer now refuses what the model
+/// says is dropped, so asking it would be asking the model about itself.
+@MainActor
+@Suite struct MathTypesetterCoverageTests {
+ /// The range the probe walks: ASCII through Sinhala, which covers every
+ /// alphabet and every mathematical block a model writes into an equation.
+ static let probed = 0x21...0x0DFF
+
+ static func recorded() throws -> [String] {
+ let url = try #require(Bundle.module.url(
+ forResource: "unicode-math-mode",
+ withExtension: "txt",
+ subdirectory: "Fixtures/math-coverage"))
+ return try String(contentsOf: url, encoding: .utf8)
+ .components(separatedBy: "\n")
+ .filter { !$0.isEmpty }
+ }
+
+ /// Draws the equation the way the conformer does, minus the refusal.
+ static func pixels(_ latex: String) -> Data? {
+ var image = MathImage(latex: latex, fontSize: 13, textColor: .black, labelMode: .text)
+ let (error, typeset, _) = image.asImage()
+ guard error == nil, let typeset else { return nil }
+ let size = typeset.size
+ guard size.width >= 1, size.height >= 1, let rep = NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: Int(ceil(size.width * 3)),
+ pixelsHigh: Int(ceil(size.height * 3)),
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0) else {
+ return nil
+ }
+ rep.size = size
+ guard let context = NSGraphicsContext(bitmapImageRep: rep) else { return nil }
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = context
+ typeset.draw(in: NSRect(origin: .zero, size: size))
+ NSGraphicsContext.restoreGraphicsState()
+ return rep.representation(using: .png, properties: [:])
+ }
+
+ /// `x<s>x` against `xx`: a scalar the build draws changes the pixels, and
+ /// one it drops leaves them identical. That silence is the whole defect —
+ /// the image comes back looking finished with the character gone.
+ @Test func pinnedMathModeCoverageMatchesTheBuild() throws {
+ let baseline = try #require(Self.pixels("xx"))
+ var drawn: [String] = []
+ for value in Self.probed {
+ guard let scalar = Unicode.Scalar(value) else { continue }
+ let character = Character(scalar)
+ guard !PinnedMathCoverage.structural.contains(character) else { continue }
+ let probe = "x\(character)x"
+ // A combining mark is never its own character in real input: it
+ // joins whatever precedes it, and the build is asked about the
+ // grapheme rather than the mark.
+ guard probe.count == 3 else { continue }
+
+ let differs = Self.pixels(probe).map { $0 != baseline } ?? false
+ #expect(
+ differs == PinnedMathCoverage.renders(character),
+ "U+\(String(format: "%04X", value)) drawn=\(differs)")
+ if differs { drawn.append(String(format: "%04X", value)) }
+ }
+ #expect(drawn == (try Self.recorded()))
+ }
+
+ /// `\text{}` is the one mode that accepts anything, which is what carries
+ /// the two characters the normalizer rewrites through it.
+ @Test(arguments: ["\u{4E2D}", "\u{2234}", "\u{2235}", "\u{221A}", "\u{00B0}"])
+ func unicodeInsideTextIsAccepted(_ character: String) {
+ #expect(PinnedMathCoverage.firstDroppedCharacter(in: "\\text{\(character)}") == nil)
+ #expect(SwiftMathTypesetter().render(
+ latex: "\\text{\(character)}",
+ fontSize: 13,
+ tint: .black,
+ mode: .inline) != nil)
+ }
+
+ @Test func commandNamesAreNotLiteralText() {
+ #expect(PinnedMathCoverage.firstDroppedCharacter(in: #"\alpha + \beta"#) == nil)
+ #expect(PinnedMathCoverage.firstDroppedCharacter(in: #"\frac{a}{b}^2_1"#) == nil)
+ #expect(PinnedMathCoverage.firstDroppedCharacter(in: #"\begin{matrix} a & b \end{matrix}"#)
+ == nil)
+ // An escaped reserved character is a command, not the character.
+ #expect(PinnedMathCoverage.firstDroppedCharacter(in: #"5\% of \$3"#) == nil)
+ #expect(PinnedMathCoverage.firstDroppedCharacter(in: "5% of $3") == "%")
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/MathTypesetterTests.swift b/Tests/TurboFieldfareApp/MacPresentation/MathTypesetterTests.swift
new file mode 100644
index 00000000..de7cafd0
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/MathTypesetterTests.swift
@@ -0,0 +1,226 @@
+import AppKit
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+/// Exercises the typesetting library only through the production conformer, so
+/// what these tests pin is the behaviour the transcript actually gets. A pin
+/// change that breaks a command shows up here rather than as a blank equation.
+@MainActor
+@Suite struct MathTypesetterTests {
+ static let fontSize: CGFloat = 13
+
+ static func render(
+ _ latex: String,
+ mode: MathRenderMode = .inline,
+ tint: NSColor = .black
+ ) -> MathRender? {
+ SwiftMathTypesetter().render(
+ latex: latex,
+ fontSize: fontSize,
+ tint: tint,
+ mode: mode)
+ }
+
+ /// Draws the attachment image the way the text view does and returns its
+ /// pixels, so a tint difference is a measured difference and not an
+ /// identity comparison on two `NSImage` objects.
+ static func pixels(_ image: NSImage) -> [UInt8]? {
+ let width = Int(ceil(image.size.width))
+ let height = Int(ceil(image.size.height))
+ guard width > 0, height > 0, let rep = NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: width,
+ pixelsHigh: height,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0) else {
+ return nil
+ }
+ rep.size = image.size
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
+ image.draw(in: NSRect(origin: .zero, size: image.size))
+ NSGraphicsContext.restoreGraphicsState()
+ guard let data = rep.bitmapData else { return nil }
+ return Array(UnsafeBufferPointer(
+ start: data,
+ count: rep.bytesPerRow * rep.pixelsHigh))
+ }
+
+ @Test(arguments: [
+ #"\frac{a}{b}"#,
+ #"\sqrt{b^2 - 4ac}"#,
+ #"\sum_{i=1}^{n} i"#,
+ #"\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}"#,
+ #"\alpha + \beta = \gamma"#,
+ // The pin probe: tag 1.7.3 duplicates the fenced content here, the
+ // pinned revision does not.
+ #"\left( \frac{a}{b} \right)"#,
+ ])
+ func typesetsTheCommandsGemmaEmits(_ latex: String) throws {
+ let render = try #require(Self.render(latex))
+ #expect(render.ascent > 0)
+ #expect(render.descent > 0)
+ #expect(render.image.size.width > 0)
+ #expect(render.image.size.height > 0)
+ }
+
+ @Test(arguments: [
+ (#"\begin{cases} x & x \ge 0 \\ -x & x < 0 \end{cases}"#, true),
+ (#"\begin{aligned} a &= b \\ c &= d \end{aligned}"#, true),
+ (#"\begin{matrix} a & b \end{matrix}"#, true),
+ // Rejected by the pinned revision with an error; the normalizer
+ // rewrites these before the transcript reaches the typesetter, and an
+ // unrewritten one falls back to raw text rather than disappearing.
+ // A character with no atom is a different failure: the build drops it
+ // without an error at all, which is what the refusal above catches.
+ (#"\begin{align*} a &= b \end{align*}"#, false),
+ (#"\begin{array}{cc} 1 & 2 \end{array}"#, false),
+ ])
+ func environmentCoverageIsPinnedInBothDirections(_ probe: (String, Bool)) {
+ #expect((Self.render(probe.0) != nil) == probe.1, "\(probe.0)")
+ }
+
+ /// The pinned build skips a character it has no atom for and reports
+ /// nothing, so these came back as finished-looking images with the
+ /// operator missing: `\u{221A}2` was pixel-identical to `2`. Refusing
+ /// restores the span's own source, which the reader can at least read.
+ @Test(arguments: [
+ "\u{221A}2",
+ "f\u{2032}(x)",
+ "90\u{00B0}",
+ "\u{00AC}p \u{2228} q",
+ "a \u{2218} b",
+ "x \u{226A} y",
+ "a~b",
+ "x\u{200B}y",
+ "50% of it",
+ ])
+ func scalarsThePinnedBuildDropsAreRefusedNotDrawn(_ latex: String) {
+ #expect(Self.render(latex) == nil, "\(latex.debugDescription)")
+ }
+
+ /// The two the plan expected to be refused and the build actually draws.
+ /// `'` is in the accented table, which `atom(forCharacter:)` consults
+ /// before its ASCII rules, and a combining mark joins the letter before it
+ /// into a grapheme that sorts inside the a-z range.
+ @Test(arguments: ["f'(x)", "e\u{301} = 1"])
+ func theTwoLookAlikesThePinnedBuildDoesDraw(_ latex: String) {
+ #expect(Self.render(latex) != nil, "\(latex.debugDescription)")
+ }
+
+ @Test(arguments: [#"\frac{"#, #"\unknowncmd"#, #"\left( x"#])
+ func invalidLatexProducesNoImage(_ latex: String) {
+ #expect(Self.render(latex) == nil)
+ }
+
+ /// The attachment bounds are `-descent` tall below the baseline and
+ /// `ascent` above it, so the image must be exactly that tall or the
+ /// equation sits off the line. SwiftMath rounds the height up to a whole
+ /// point, which is the only slack allowed here.
+ @Test func imageHeightIsTheCeilingOfAscentPlusDescent() throws {
+ for latex in [#"\frac{a}{b}"#, #"x"#, #"\sum_{i=1}^{n} i"#, #"\sqrt{x}"#] {
+ let render = try #require(Self.render(latex))
+ #expect(render.image.size.height == ceil(render.ascent + render.descent),
+ "\(latex)")
+ }
+ }
+
+ @Test func maskTintProducesVisibleGlyphsInTheRequestedColor() throws {
+ let render = try #require(Self.render(#"x = \frac{a}{b}"#, tint: .red))
+ let pixels = try #require(Self.pixels(render.image))
+ let opaqueRed = stride(from: 0, to: pixels.count, by: 4).contains { index in
+ pixels[index] > 200 && pixels[index + 1] < 80 && pixels[index + 3] > 200
+ }
+ #expect(opaqueRed, "the tint must paint the glyph coverage, not the background")
+ }
+
+ @Test func twoTintsProduceDifferentPixels() throws {
+ let latex = #"E = mc^2"#
+ let redRender = try #require(Self.render(latex, tint: .red))
+ let blueRender = try #require(Self.render(latex, tint: .blue))
+ let red = try #require(Self.pixels(redRender.image))
+ let blue = try #require(Self.pixels(blueRender.image))
+ #expect(red.count == blue.count)
+ #expect(red != blue)
+ }
+
+ /// Finalising a fifty-equation answer costs 36.7 ms, and a rebuild while
+ /// the answer is terminal re-renders all of it, so the same equation at the
+ /// same size and colour must come back as the same image.
+ @Test func repeatedRendersOfTheSameEquationReuseOneImage() throws {
+ let cache = MathRenderCache()
+ let typesetter = SwiftMathTypesetter(cache: cache)
+ let first = try #require(typesetter.render(
+ latex: #"\frac{a}{b}"#,
+ fontSize: 13,
+ tint: .labelColor,
+ mode: .inline))
+ let second = try #require(typesetter.render(
+ latex: #"\frac{a}{b}"#,
+ fontSize: 13,
+ tint: .labelColor,
+ mode: .inline))
+ #expect(first.image === second.image)
+ #expect(cache.count == 1)
+
+ // Anything that changes the pixels is a different entry.
+ _ = typesetter.render(latex: #"\frac{a}{b}"#, fontSize: 22, tint: .labelColor, mode: .inline)
+ _ = typesetter.render(latex: #"\frac{a}{b}"#, fontSize: 13, tint: .red, mode: .inline)
+ _ = typesetter.render(latex: #"\frac{a}{b}"#, fontSize: 13, tint: .labelColor, mode: .display)
+ #expect(cache.count == 4)
+ // The bound is what the masks cost, not how many there are: a display
+ // equation's is about ten times an inline one's.
+ #expect(cache.byteCount > 0)
+ }
+
+ /// A count limit is either far too small for a page of prose or far too
+ /// large for a page of derivations, because the two differ by an order of
+ /// magnitude in what they retain.
+ @Test func theRenderCacheIsBoundedByBytesAndDropsWhenItOverflows() throws {
+ let measure = MathRenderCache()
+ let typesetter = SwiftMathTypesetter(cache: measure)
+ _ = try #require(typesetter.render(
+ latex: #"\frac{a}{b}"#, fontSize: 13, tint: .labelColor, mode: .inline))
+ let one = measure.byteCount
+ #expect(one > 0)
+
+ // Room for one entry and not two: storing the second empties the table.
+ let tight = MathRenderCache(byteLimit: one + one / 2)
+ let bounded = SwiftMathTypesetter(cache: tight)
+ _ = bounded.render(latex: #"\frac{a}{b}"#, fontSize: 13, tint: .labelColor, mode: .inline)
+ #expect(tight.count == 1)
+ #expect(tight.byteCount == one)
+ _ = bounded.render(latex: #"\frac{c}{d}"#, fontSize: 13, tint: .labelColor, mode: .inline)
+ #expect(tight.count == 1)
+ #expect(tight.byteCount <= tight.byteCount)
+
+ // An entry bigger than the whole budget is drawn and not kept, rather
+ // than emptying the table for something that cannot fit.
+ let tiny = MathRenderCache(byteLimit: one / 2)
+ let unbounded = SwiftMathTypesetter(cache: tiny)
+ #expect(unbounded.render(
+ latex: #"\frac{a}{b}"#, fontSize: 13, tint: .labelColor, mode: .inline) != nil)
+ #expect(tiny.count == 0)
+ #expect(tiny.byteCount == 0)
+ }
+
+ /// Measured on the pinned revision: `.text` mode shrinks a fraction (19 pt
+ /// against 24 pt at 13 pt type) but still stacks big-operator limits, so
+ /// `\sum_{i=1}^n i` is 34 pt tall in both modes and is not a valid pin for
+ /// the mode mapping.
+ @Test func inlineAndDisplayModesDifferInHeight() throws {
+ let inline = try #require(Self.render(#"\frac{a}{b}"#, mode: .inline))
+ let display = try #require(Self.render(#"\frac{a}{b}"#, mode: .display))
+ #expect(display.image.size.height > inline.image.size.height)
+
+ let inlineSum = try #require(Self.render(#"\sum_{i=1}^n i"#, mode: .inline))
+ let displaySum = try #require(Self.render(#"\sum_{i=1}^n i"#, mode: .display))
+ #expect(displaySum.image.size.height == inlineSum.image.size.height)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/ProgressiveTranscriptRenderTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ProgressiveTranscriptRenderTests.swift
new file mode 100644
index 00000000..1312be20
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/ProgressiveTranscriptRenderTests.swift
@@ -0,0 +1,617 @@
+import AppKit
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@MainActor
+@Suite struct ProgressiveTranscriptRenderTests {
+ static func controller(
+ renderer: any TranscriptBlockRendering = ResponseMarkdownRenderer(),
+ progressive: Bool = true
+ ) -> InstructionTranscriptDocumentController {
+ InstructionTranscriptDocumentController(
+ renderer: renderer,
+ environment: ["TURBO_FIELDFARE_PROGRESSIVE_RENDER": progressive ? "1" : "0"])
+ }
+
+ /// What the transcript shows when an answer finishes: a fresh controller
+ /// handed the whole answer as terminal. Finalize closes the open block in
+ /// place and never re-renders the message, so this is the reference every
+ /// other path is measured against.
+ static func finalized(_ source: String) -> NSAttributedString {
+ let storage = NSMutableAttributedString()
+ let controller = controller()
+ _ = controller.synchronize(
+ storage: storage,
+ prompt: "Explain this",
+ response: source,
+ isTerminal: true)
+ return assistant(storage, controller)
+ }
+
+ static func stream(
+ _ source: String,
+ renderer: any TranscriptBlockRendering = ResponseMarkdownRenderer(),
+ step: Int = 1
+ ) -> (controller: InstructionTranscriptDocumentController, storage: NSMutableAttributedString) {
+ let storage = NSMutableAttributedString()
+ let controller = controller(renderer: renderer)
+ var seen = ""
+ var index = source.startIndex
+ while index < source.endIndex {
+ let next = source.index(index, offsetBy: step, limitedBy: source.endIndex)
+ ?? source.endIndex
+ seen.append(contentsOf: source[index..<next])
+ index = next
+ controller.synchronize(
+ storage: storage,
+ prompt: "Explain this",
+ response: seen,
+ isTerminal: false)
+ }
+ return (controller, storage)
+ }
+
+ static func assistant(
+ _ storage: NSMutableAttributedString,
+ _ controller: InstructionTranscriptDocumentController
+ ) -> NSAttributedString {
+ storage.attributedSubstring(from: controller.assistantRange)
+ }
+
+ // MARK: - What the reader sees
+
+ @Test func completedBlocksAreStyledWhileTheAnswerIsStillArriving() {
+ let (controller, storage) = Self.stream("## Title\n\n**Bold** text.\n\nStill writ")
+ let text = Self.assistant(storage, controller).string
+ #expect(text == "Title\n\nBold text.\n\nStill writ")
+ #expect(!controller.isFinalized)
+ // The completed blocks are above the open one and are not rewritten.
+ #expect(controller.tailRange.length == "Still writ".utf16.count)
+ #expect((storage.string as NSString).substring(with: controller.tailRange)
+ == "Still writ")
+ }
+
+ @Test func openBlockIsAutoClosedForDisplayWithoutTouchingTheResponse() {
+ let (controller, storage) = Self.stream("Intro.\n\nA **bold sta")
+ #expect(Self.assistant(storage, controller).string == "Intro.\n\nA bold sta")
+ #expect(controller.response == "Intro.\n\nA **bold sta")
+ }
+
+ /// The cancel shape from the corpus: the reader stops a code answer in the
+ /// middle of the fence and has to be left with readable code, not with the
+ /// fence markers and an unstyled listing.
+ @Test func cancellingInsideAFenceLeavesReadableCode() throws {
+ let source = try TranscriptCorpus.source("unclosed-fence")
+ let (controller, storage) = Self.stream(source, step: 8)
+ let text = Self.assistant(storage, controller).string
+ #expect(text.hasPrefix("Here is the kernel so far:\n\n"))
+ #expect(!text.contains("```"))
+ #expect(text.contains("kernel void reduce"))
+ // The listing is inside a code container, which is what makes it read
+ // as code rather than as a paragraph of prose.
+ let code = (text as NSString).range(of: "kernel void reduce")
+ let style = storage.attribute(
+ .paragraphStyle,
+ at: controller.assistantRange.location + code.location,
+ effectiveRange: nil) as? NSParagraphStyle
+ #expect(style?.textBlocks.count == 1)
+
+ // Finishing there is what a cancel is. The whole-message render falls
+ // back to raw source for an unclosed fence, so the listing used to
+ // lose its box and show its markers the moment the reader stopped it.
+ controller.synchronize(
+ storage: storage, prompt: "Explain this", response: source, isTerminal: true)
+ let finalized = Self.assistant(storage, controller).string
+ #expect(!finalized.contains("```"))
+ #expect(finalized.contains("kernel void reduce"))
+ let finalStyle = storage.attribute(
+ .paragraphStyle,
+ at: controller.assistantRange.location
+ + (finalized as NSString).range(of: "kernel void reduce").location,
+ effectiveRange: nil) as? NSParagraphStyle
+ #expect(finalStyle?.textBlocks.count == 1)
+ }
+
+ @Test func mathInTheOpenBlockStaysAsSourceAndTypesetsWhenTheBlockCloses() {
+ let typesetter = FakeMathTypesetter()
+ let renderer = ResponseMarkdownRenderer(typesetter: typesetter)
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller(renderer: renderer)
+ let answer = "Step 1.\n$$x = 1$$"
+
+ var seen = ""
+ for character in answer {
+ seen.append(character)
+ controller.synchronize(
+ storage: storage, prompt: "Solve", response: seen, isTerminal: false)
+ }
+ #expect(typesetter.calls.isEmpty)
+ #expect(storage.string.hasSuffix("$$x = 1$$"))
+
+ // The blank line that closes the block is what typesets it.
+ controller.synchronize(
+ storage: storage, prompt: "Solve", response: answer + "\n\n", isTerminal: false)
+ #expect(typesetter.calls.map(\.latex) == ["x = 1"])
+ #expect(storage.string.hasSuffix("Step 1.\n\n\u{FFFC}"))
+ }
+
+ /// The progressive counterpart of the raw path's multi-byte delta test: a
+ /// CJK or combining-mark delta has to land in the drawn document exactly
+ /// once, and the tail keeps math as source rather than mangling it.
+ @Test func multiByteDeltasReachTheDrawnDocumentExactly() {
+ let answer = "\u{4E2D}\u{6587}: caf\u{E9} \u{30C6}\u{30B9}\u{30C8} $x^2$ done"
+ let (controller, storage) = Self.stream(answer)
+ #expect(storage.string == "You\nExplain this\n\nAnswer\n" + answer)
+ #expect((storage.string as NSString).substring(with: controller.assistantRange)
+ == answer)
+ #expect(controller.response == answer)
+ }
+
+ // MARK: - Cost
+
+ @Test func eachCompletedBlockIsRenderedExactlyOnce() {
+ let renderer = RecordingBlockRenderer()
+ let source = "# Title\n\nFirst paragraph.\n\nSecond paragraph.\n\nThird."
+ _ = Self.stream(source, renderer: renderer)
+
+ #expect(renderer.completedSources == ["# Title", "First paragraph.", "Second paragraph."])
+ // The last block is still open at the end of the stream, so it is only
+ // ever rendered as a tail.
+ #expect(renderer.tailSources.last == "Third.")
+ }
+
+ @Test func theOpenBlockIsRenderedOnEveryTickAndNothingElseIs() {
+ let renderer = RecordingBlockRenderer()
+ let source = "Done.\n\nabcd"
+ _ = Self.stream(source, renderer: renderer)
+
+ #expect(renderer.completedSources == ["Done."])
+ // One tail render per tick from the first character of the open block.
+ #expect(renderer.tailSources.suffix(4) == ["a", "ab", "abc", "abcd"])
+ }
+
+ /// A fenced block never reaches the markdown pass while it streams: it is
+ /// the one block with no size bound, and re-parsing it per tick is the
+ /// quadratic cost the streaming timing gate exists to catch.
+ @Test func fencedBlocksDoNotGoThroughTheMarkdownPass() {
+ let renderer = RecordingBlockRenderer()
+ let source = "Intro.\n\n```swift\nlet a = 1\nlet b = 2\n```\n\nOutro."
+ let (_, storage) = Self.stream(source, renderer: renderer)
+
+ #expect(renderer.calls.allSatisfy { !$0.source.contains("```") })
+ #expect(storage.string.contains("let a = 1\nlet b = 2"))
+ #expect(!storage.string.contains("```"))
+ }
+
+ @Test func aClosedFenceKeepsTheBytesItWasStreamedInto() {
+ let renderer = RecordingBlockRenderer()
+ let source = "```swift\nlet a = 1\n```\n\nAfter."
+ let (controller, storage) = Self.stream(source, renderer: renderer)
+ #expect(Self.assistant(storage, controller).string == "let a = 1\n\nAfter.")
+ #expect(renderer.completedSources == [])
+ }
+
+ /// The closer the tail adds has to carry the container's prefix. Written
+ /// flush left it lands outside the quote, so the quote's own fence is
+ /// still open when the renderer looks: the whole tail falls back to raw
+ /// source and the listing keeps its markers on screen.
+ @Test(arguments: [
+ "> Run this:\n> ```bash\n> brew install x\n> ```\n\nDone.",
+ "1. Install:\n\n ```bash\n brew install x\n ```\n\nDone.",
+ ])
+ func aFenceInsideAContainerNeverShowsItsMarkersWhileStreaming(_ source: String) {
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller()
+ var seen = ""
+ for character in source {
+ seen.append(character)
+ controller.synchronize(
+ storage: storage, prompt: "Ask", response: seen, isTerminal: false)
+ #expect(!storage.string.contains("```"), "markers shown at \(seen.debugDescription)")
+ }
+ #expect(Self.assistant(storage, controller).string.contains("brew install x"))
+ }
+
+ /// Block renders are memoised so a rebuild mid-answer does not re-render
+ /// the whole transcript. The memo is keyed by position as well as text:
+ /// handing two identical tables the same render would hand them the same
+ /// `NSTextTable`, and TextKit draws that as one table with eight rows.
+ @Test func twoIdenticalTablesGetTheirOwnContainers() {
+ let table = "| A | B |\n| --- | --- |\n| 1 | 2 |"
+ let (controller, storage) = Self.stream("\(table)\n\n\(table)\n\nEnd.", step: 4)
+ let digest = AttributedStringDigest(Self.assistant(storage, controller))
+ var containers: Set<String> = []
+ for run in digest.runs {
+ guard let marker = run.paragraph.range(of: #"block#\d+"#, options: .regularExpression)
+ else {
+ continue
+ }
+ containers.insert(String(run.paragraph[marker]))
+ }
+ #expect(containers.count == 8, "two 2x2 tables are eight cells, not four")
+ }
+
+ // MARK: - Equality with the finalize render
+
+ /// The whole-document render stays the oracle: the per-block finalize has
+ /// to reach the same document for every answer whose blocks the message
+ /// pass agrees about. The exceptions are pinned rather than tolerated —
+ /// they are the difference this pass exists to make.
+ @Test(arguments: TranscriptCorpus.fixtures)
+ func perBlockFinalizeMatchesTheWholeDocumentRender(_ fixture: String) throws {
+ let source = try TranscriptCorpus.source(fixture)
+ let result = ResponseMarkdownRenderer().render(source)
+ let drawn = Self.finalized(source)
+
+ if TranscriptCorpus.wholeRenderFallbacks.contains(fixture) {
+ // One block trips a message-wide gate and takes the whole answer
+ // to raw source with it. Per block, only that block is raw.
+ #expect(result.usedFallback)
+ #expect(result.attributedString.string == source)
+ #expect(drawn.string != source, "\(fixture) finalized wholly raw")
+ return
+ }
+ if TranscriptCorpus.perBlockLimitations.contains(fixture) { return }
+
+ let finalDigest = AttributedStringDigest(result.attributedString)
+ let drawnDigest = AttributedStringDigest(drawn)
+ #expect(finalDigest.text == drawnDigest.text, "\(fixture) finalized different text")
+ guard finalDigest != drawnDigest else { return }
+
+ let expectedRuns = finalDigest.perCharacter
+ let actualRuns = drawnDigest.perCharacter
+ try #require(expectedRuns.count == actualRuns.count)
+ for (left, right) in zip(expectedRuns, actualRuns) where left != right {
+ #expect(
+ left.text == "\n",
+ "\(fixture) differs on \(left.text.debugDescription), not on a separator")
+ var probe = left
+ probe.paragraph = right.paragraph
+ #expect(probe == right, "\(fixture) differs in more than the paragraph style")
+ #expect(
+ left.paragraph.replacingOccurrences(of: "align=1", with: "align=4")
+ == right.paragraph,
+ "\(fixture) differs in more than the alignment of a separator")
+ }
+ for dark in [false, true] {
+ let expected = try TranscriptFrameRenderer.image(result.attributedString, dark: dark)
+ let actual = try TranscriptFrameRenderer.image(drawn, dark: dark)
+ #expect(
+ Self.png(expected) == Self.png(actual),
+ "\(fixture) draws differently in \(dark ? "dark" : "light")")
+ }
+ }
+
+ static func png(_ image: NSImage) -> Data? {
+ (image.representations.first as? NSBitmapImageRep)?
+ .representation(using: .png, properties: [:])
+ }
+
+ /// What the controller actually draws while streaming, finished the way a
+ /// real answer finishes. A reader who watched it arrive and a reader who
+ /// opened it afterwards have to be looking at the same document, with no
+ /// exceptions at all.
+ @Test(arguments: TranscriptCorpus.fixtures)
+ func streamedThenFinalizedMatchesAFreshTerminalRebuild(_ fixture: String) throws {
+ let source = try TranscriptCorpus.source(fixture)
+ let (controller, storage) = Self.stream(source, step: 8)
+ controller.synchronize(
+ storage: storage,
+ prompt: "Explain this",
+ response: source,
+ isTerminal: true)
+
+ #expect(AttributedStringDigest(Self.assistant(storage, controller))
+ == AttributedStringDigest(Self.finalized(source)),
+ "\(fixture) streamed into a different document")
+ }
+
+ /// An image thumbnail landing mid-answer rebuilds the whole document. What
+ /// it finalizes to must not depend on that having happened.
+ @Test func aRebuildMidStreamStillFinalizesToTheSameDocument() throws {
+ let source = try TranscriptCorpus.source("gemma-derivation-table")
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller()
+ var seen = ""
+ var index = source.startIndex
+ while index < source.endIndex {
+ let next = source.index(index, offsetBy: 8, limitedBy: source.endIndex)
+ ?? source.endIndex
+ seen.append(contentsOf: source[index..<next])
+ index = next
+ let halfway = seen.count > source.count / 2
+ controller.synchronize(
+ storage: storage,
+ prompt: "Explain this",
+ response: seen,
+ isTerminal: false,
+ promptPrefix: halfway ? NSAttributedString(string: "[image]") : NSAttributedString(),
+ promptPrefixIdentifier: halfway ? "image-1" : "")
+ }
+ controller.synchronize(
+ storage: storage,
+ prompt: "Explain this",
+ response: source,
+ isTerminal: true,
+ promptPrefix: NSAttributedString(string: "[image]"),
+ promptPrefixIdentifier: "image-1")
+
+ #expect(AttributedStringDigest(Self.assistant(storage, controller))
+ == AttributedStringDigest(Self.finalized(source)))
+ }
+
+ /// The streamed render draws a fenced body from the raw bytes, so a
+ /// finalize pass that promotes a `**Note**` line inside the fence changed
+ /// the listing under the reader the moment the answer ended.
+ @Test func aBoldLineInsideAFenceStreamsAndFinalizesToTheSameBytes() {
+ let source = "Intro.\n\n```text\n**Note**\nkeep this line attached\n```\n\nAfter."
+ let (controller, storage) = Self.stream(source, step: 4)
+ let streamed = Self.assistant(storage, controller).string
+ controller.synchronize(
+ storage: storage, prompt: "Explain this", response: source, isTerminal: true)
+ let finalized = Self.assistant(storage, controller).string
+
+ #expect(streamed.contains("**Note**\nkeep this line attached"))
+ #expect(finalized == streamed)
+ }
+
+ /// An empty fence renders nothing. The fence fast path used to require a
+ /// non-empty body, so a rebuild sent "```\n```" through the markdown pass,
+ /// which produces an empty document and falls back to raw source — the
+ /// fence markers reappeared on screen where the stream had drawn nothing.
+ @Test func anEmptyFenceDrawsNothingOnEveryPath() {
+ let source = "Intro.\n\n```\n```\n\nAfter."
+ let (streamedController, streamedStorage) = Self.stream(source, step: 3)
+ let streamed = Self.assistant(streamedStorage, streamedController).string
+
+ let rebuiltStorage = NSMutableAttributedString()
+ let rebuiltController = Self.controller()
+ _ = rebuiltController.synchronize(
+ storage: rebuiltStorage, prompt: "Ask", response: source, isTerminal: false)
+ let rebuilt = Self.assistant(rebuiltStorage, rebuiltController).string
+
+ let finalStorage = NSMutableAttributedString()
+ let finalController = Self.controller()
+ _ = finalController.synchronize(
+ storage: finalStorage, prompt: "Ask", response: source, isTerminal: true)
+ let finalized = Self.assistant(finalStorage, finalController).string
+
+ #expect(!streamed.contains("```"))
+ #expect(rebuilt == streamed)
+ #expect(finalized == streamed)
+ }
+
+ /// The separator count carried the previous block's trailing newlines only
+ /// when the new block was newlines all the way down, so a fence whose body
+ /// is one blank line left an extra paragraph gap behind it that the whole
+ /// render does not have.
+ @Test func aFenceWhoseBodyIsOneBlankLineKeepsOneGapOnEveryPath() {
+ let source = "Intro.\n\n```\n\n```\n\nAfter."
+ let whole = ResponseMarkdownRenderer().render(source).attributedString.string
+ #expect(whole == "Intro.\n\n\nAfter.")
+
+ let (streamedController, streamedStorage) = Self.stream(source, step: 3)
+ #expect(Self.assistant(streamedStorage, streamedController).string == whole)
+
+ let rebuiltStorage = NSMutableAttributedString()
+ let rebuiltController = Self.controller()
+ _ = rebuiltController.synchronize(
+ storage: rebuiltStorage, prompt: "Ask", response: source, isTerminal: false)
+ #expect(Self.assistant(rebuiltStorage, rebuiltController).string == whole)
+
+ let finalStorage = NSMutableAttributedString()
+ let finalController = Self.controller()
+ _ = finalController.synchronize(
+ storage: finalStorage, prompt: "Ask", response: source, isTerminal: true)
+ #expect(Self.assistant(finalStorage, finalController).string == whole)
+ }
+
+ /// A tab is four columns wide, so stripping a one-space fence indent off it
+ /// leaves three. The filter dropped the whole tab instead and the streamed
+ /// listing lost its indentation until the answer finalized.
+ @Test func aTabWiderThanTheFenceIndentKeepsTheColumnsItOwns() {
+ let source = " ```\n\tfoo\n ```"
+ let whole = ResponseMarkdownRenderer().render(source).attributedString.string
+ #expect(whole == " foo\n")
+
+ let (controller, storage) = Self.stream(source, step: 2)
+ #expect(Self.assistant(storage, controller).string.contains(" foo"))
+ }
+
+ /// A rebuild mid-answer draws the completed blocks with the separators the
+ /// incremental path writes. Without them the prefix arrived glued —
+ /// "One.Two." — and stayed that way until the answer finalized.
+ @Test func aRebuildMidStreamKeepsTheSeparatorsBetweenCompletedBlocks() {
+ let source = "One.\n\nTwo.\n\nThree is still writ"
+ let (reference, referenceStorage) = Self.stream(source)
+ let expected = Self.assistant(referenceStorage, reference).string
+ #expect(expected == "One.\n\nTwo.\n\nThree is still writ")
+
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller()
+ var seen = ""
+ for character in source {
+ seen.append(character)
+ controller.synchronize(
+ storage: storage, prompt: "Ask", response: seen, isTerminal: false)
+ }
+ // What an image thumbnail landing mid-answer does: the prompt prefix
+ // identifier changes and the whole document is rebuilt.
+ let rebuilt = controller.synchronize(
+ storage: storage,
+ prompt: "Ask",
+ response: source,
+ isTerminal: false,
+ promptPrefix: NSAttributedString(string: "[image]"),
+ promptPrefixIdentifier: "image-1")
+ #expect(rebuilt.mutation == .rebuilt)
+ #expect(Self.assistant(storage, controller).string == expected)
+
+ let finalized = controller.synchronize(
+ storage: storage,
+ prompt: "Ask",
+ response: source,
+ isTerminal: true,
+ promptPrefix: NSAttributedString(string: "[image]"),
+ promptPrefixIdentifier: "image-1")
+ #expect(finalized.mutation == .finalized)
+ #expect(Self.assistant(storage, controller).string == expected)
+ }
+
+ /// `hasPrefix` compares by canonical equivalence, so a prefix that arrives
+ /// recomposed passed the gate while the byte offsets the delta is cut at
+ /// no longer matched: the append wrote the wrong characters onto a
+ /// document drawn from different ones.
+ @Test func aCanonicallyEqualButRewrittenPrefixForcesARebuild() {
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller()
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "cafe\u{301}", isTerminal: false)
+
+ let update = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "caf\u{E9} au lait", isTerminal: false)
+ #expect(update.mutation == .rebuilt)
+ #expect(Self.assistant(storage, controller).string == "caf\u{E9} au lait")
+
+ // A byte-identical extension is still an append, not a rebuild.
+ let appended = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "caf\u{E9} au lait now", isTerminal: false)
+ #expect(appended.mutation != .rebuilt)
+ }
+
+ // MARK: - Finalize and resume
+
+ /// Finalize closes the block that was still being written and leaves the
+ /// blocks above it exactly as they were drawn.
+ @Test func finalizeClosesTheOpenBlockAndLeavesTheRestInPlace() {
+ let renderer = RecordingBlockRenderer()
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller(renderer: renderer)
+ let answer = "# Title\n\nA **bold** claim."
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: answer, isTerminal: false)
+ let drawnPrefix = controller.tailRange.location
+ let final = controller.synchronize(
+ storage: storage, prompt: "Ask", response: answer, isTerminal: true)
+
+ #expect(final.mutation == .finalized)
+ #expect(controller.isFinalized)
+ #expect(storage.string == "You\nAsk\n\nAnswer\nTitle\n\nA bold claim.")
+ // Only the open block was rewritten; the heading above it did not move.
+ #expect(final.replaced?.previous.location ?? 0 >= drawnPrefix)
+ // The heading is rendered once, as a completed block, and never again.
+ #expect(renderer.completedSources.filter { $0 == "# Title" }.count == 1)
+ }
+
+ /// A terminal rebuild used to render every block once as a block and then
+ /// the whole answer once more, so a finished answer cost N+2 passes.
+ @Test func aTerminalRebuildRendersEachBlockOnceAndNeverTheTail() {
+ let renderer = RecordingBlockRenderer()
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller(renderer: renderer)
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "A.\n\nB.\n\nC.", isTerminal: true)
+
+ #expect(renderer.completedSources == ["A.", "B.", "C."])
+ #expect(renderer.tailSources.isEmpty)
+ }
+
+ /// An image thumbnail landing after the answer is finished rebuilds the
+ /// document from blocks that are all in the memo already.
+ @Test func aLatePromptPrefixOnAFinishedTurnRendersNothingNew() {
+ let renderer = RecordingBlockRenderer()
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller(renderer: renderer)
+ let answer = "A.\n\nB.\n\nC."
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: answer, isTerminal: true)
+ let before = renderer.calls.count
+
+ let rebuilt = controller.synchronize(
+ storage: storage,
+ prompt: "Ask",
+ response: answer,
+ isTerminal: true,
+ promptPrefix: NSAttributedString(string: "[image]"),
+ promptPrefixIdentifier: "image-1")
+
+ #expect(rebuilt.mutation == .finalized)
+ #expect(renderer.calls.count == before)
+ #expect(storage.string.hasSuffix("A.\n\nB.\n\nC."))
+ }
+
+ /// A terminal response that extends a finalized one is extended, not
+ /// rebuilt: the blocks already drawn are not rendered again.
+ @Test func aFinalizedAnswerThatGrowsIsExtendedNotRebuilt() {
+ let renderer = RecordingBlockRenderer()
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller(renderer: renderer)
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "One.\n\nTwo is open", isTerminal: true)
+ let grown = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "One.\n\nTwo is open now", isTerminal: true)
+
+ #expect(grown.mutation == .finalized)
+ #expect(renderer.completedSources.filter { $0 == "One." }.count == 1)
+ #expect(Self.assistant(storage, controller).string == "One.\n\nTwo is open now")
+ }
+
+ @Test func resumingAfterFinalizeGoesBackToTheProgressiveDocument() {
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller()
+ let answer = "Partial **answer**"
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: answer, isTerminal: true)
+ #expect(storage.string.hasSuffix("Partial answer"))
+
+ let resumed = controller.synchronize(
+ storage: storage, prompt: "Ask", response: answer, isTerminal: false)
+ #expect(resumed.mutation == .rebuilt)
+ #expect(!controller.isFinalized)
+ #expect(storage.string.hasSuffix("Partial answer"))
+ #expect(controller.response == answer)
+
+ let grown = controller.synchronize(
+ storage: storage, prompt: "Ask", response: answer + " more", isTerminal: false)
+ #expect(grown.mutation == .tailReplaced)
+ #expect(storage.string.hasSuffix("Partial answer more"))
+ }
+
+ // MARK: - The flag
+
+ @Test func theFlagOffRestoresRawStreamingAppends() {
+ let storage = NSMutableAttributedString()
+ let controller = Self.controller(progressive: false)
+ let first = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "# Title\n\nBod", isTerminal: false)
+ let second = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "# Title\n\nBody", isTerminal: false)
+
+ #expect(first.mutation == .rebuilt)
+ #expect(second.mutation == .appended)
+ #expect(storage.string == "You\nAsk\n\nAnswer\n# Title\n\nBody")
+ #expect(controller.tailRange == controller.assistantRange)
+ }
+
+ @Test func theFlagDefaultsToProgressiveWhenUnset() {
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController(environment: [:])
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "# Title\n\nBody", isTerminal: false)
+ #expect(storage.string == "You\nAsk\n\nAnswer\nTitle\n\nBody")
+ }
+
+ // MARK: - Scroll follow
+
+ /// A tail re-render must not pull a reader who has scrolled up back to the
+ /// bottom; only the finalize restyle does that.
+ @Test func tailReplacementFollowsTheSameScrollRuleAsAnAppend() {
+ #expect(!InstructionTranscriptDocumentController.shouldScrollToBottom(
+ wasAtBottom: false, mutation: .tailReplaced))
+ #expect(InstructionTranscriptDocumentController.shouldScrollToBottom(
+ wasAtBottom: true, mutation: .tailReplaced))
+ #expect(InstructionTranscriptDocumentController.shouldScrollToBottom(
+ wasAtBottom: false, mutation: .finalized))
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/ResponseBlockSplitterTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ResponseBlockSplitterTests.swift
new file mode 100644
index 00000000..706a1de8
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/ResponseBlockSplitterTests.swift
@@ -0,0 +1,326 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@Suite struct ResponseBlockSplitterTests {
+ static func texts(_ source: String) -> [String] {
+ let split = ResponseBlockSplitter.split(source)
+ return split.blocks.map { ResponseBlockSplitter.text($0.utf8Range, in: source) }
+ }
+
+ static func kinds(_ source: String) -> [ResponseBlockSplitter.Kind] {
+ ResponseBlockSplitter.split(source).blocks.map(\.kind)
+ }
+
+ // MARK: - One block per shape
+
+ @Test func fencedBlockKeepsItsBlankLinesAndInfoString() {
+ let source = """
+ Intro paragraph.
+
+ ```swift
+ struct A {}
+
+ struct B {}
+ ```
+
+ Outro.
+ """
+ #expect(Self.texts(source) == [
+ "Intro paragraph.",
+ "```swift\nstruct A {}\n\nstruct B {}\n```",
+ "Outro.",
+ ])
+ #expect(Self.kinds(source) == [.paragraph, .fencedCode, .paragraph])
+ }
+
+ @Test func tildeFenceClosesOnlyOnItsOwnMarker() {
+ let source = "~~~text\n```\nstill inside\n~~~\n\nAfter."
+ #expect(Self.texts(source) == ["~~~text\n```\nstill inside\n~~~", "After."])
+ }
+
+ /// The shape a model writes constantly: a lead-in sentence, then the fence
+ /// on the very next line. Absorbing the fence into the paragraph makes the
+ /// blank line inside the code commit that paragraph, turns the indented
+ /// lines below into an indented-code block, and boxes the sentence that
+ /// follows the closing fence along with them.
+ @Test func aFenceLineInterruptsTheParagraphAboveIt() {
+ let source = "Here is the fix:\n```swift\nfunc apply() {\n\n return 1\n}\n```\nDone."
+ #expect(Self.texts(source) == [
+ "Here is the fix:",
+ "```swift\nfunc apply() {\n\n return 1\n}\n```",
+ "Done.",
+ ])
+ #expect(Self.kinds(source) == [.paragraph, .fencedCode, .paragraph])
+ }
+
+ @Test func aTildeFenceInterruptsAParagraphTheSameWay() {
+ let source = "Here is the fix:\n~~~swift\nlet a = 1\n~~~\n\nDone."
+ #expect(Self.texts(source) == [
+ "Here is the fix:",
+ "~~~swift\nlet a = 1\n~~~",
+ "Done.",
+ ])
+ }
+
+ /// A blank line is a boundary everywhere except inside an open fence,
+ /// where it is code.
+ @Test func aBlankLineInsideAnOpenFenceDoesNotCommitTheBlock() {
+ let source = "```swift\nfunc apply() {\n\n return 1\n"
+ let split = ResponseBlockSplitter.split(source)
+ #expect(split.completed.isEmpty)
+ #expect(split.open?.fence?.isClosed == false)
+ #expect(ResponseBlockSplitter.text(
+ (split.open?.fence?.bodyStart ?? 0)..<(split.open?.fence?.bodyEnd ?? 0),
+ in: source) == "func apply() {\n\n return 1\n")
+ }
+
+ /// A list owns the fences inside its items, so the interrupt rule stops at
+ /// the list boundary.
+ @Test func aFenceIndentedInsideAListStaysWithTheList() {
+ let source = "- item one\n ```swift\n let a = 1\n ```\n\nAfter.\n"
+ #expect(Self.texts(source) == [
+ "- item one\n ```swift\n let a = 1\n ```",
+ "After.",
+ ])
+ #expect(Self.kinds(source) == [.list, .paragraph])
+ }
+
+ /// CommonMark forbids a backtick inside a backtick fence's info string,
+ /// so "```bash```" in a sentence is a code span. Reading it as an opener
+ /// put the rest of the answer in a code box while it streamed.
+ @Test func aBacktickInTheInfoStringIsNotAFenceLine() {
+ let source = "```bash``` is the fence syntax.\n\nDone."
+ #expect(Self.texts(source) == ["```bash``` is the fence syntax.", "Done."])
+ #expect(Self.kinds(source) == [.paragraph, .paragraph])
+ // The rule is the backtick fence's alone; a tilde fence takes any info.
+ #expect(Self.kinds("~~~bash`\nbody\n~~~") == [.fencedCode])
+ }
+
+ /// The interrupt rule exempted every list without knowing where the item's
+ /// content starts, so a fence written flush left under a bullet was
+ /// absorbed into the list: the blank line inside the listing then committed
+ /// it and the closing fence and the sentence after it drew as code.
+ @Test func aFenceBeforeTheItemContentColumnInterruptsTheList() {
+ let source = "- Install:\n```bash\nbrew install x\n\nbrew link x\n```\n\nDone.\n"
+ #expect(Self.kinds(source) == [.list, .fencedCode, .paragraph])
+ #expect(Self.texts(source) == [
+ "- Install:",
+ "```bash\nbrew install x\n\nbrew link x\n```",
+ "Done.",
+ ])
+ }
+
+ /// The same listing indented to the item's content column belongs to the
+ /// item, blank line included, and the list stays one block.
+ @Test func aFenceAtTheItemContentColumnStaysInsideTheItem() {
+ let source = "1. Install:\n ```bash\n brew install x\n\n brew link x\n ```\n\nDone.\n"
+ #expect(Self.kinds(source) == [.list, .paragraph])
+ #expect(Self.texts(source).first?.hasSuffix(" ```") == true)
+ }
+
+ @Test func theItemContentColumnFollowsTheMarkerWidth() {
+ // "10. " is four columns wide, so its listing is indented four.
+ let wide = "10. Install:\n ```bash\n brew install x\n ```\n\nDone.\n"
+ #expect(Self.kinds(wide) == [.list, .paragraph])
+ // Three is inside the marker, so the fence is a block of its own.
+ let narrow = "10. Install:\n ```bash\n brew install x\n ```\n\nDone.\n"
+ #expect(Self.kinds(narrow) == [.list, .fencedCode, .paragraph])
+ }
+
+ /// A nested item does not move the column the outer item's listing is
+ /// measured against; a sibling or an outer one does.
+ @Test func onlyASiblingOrOuterItemReplacesTheContentColumn() {
+ let nested = "- Outer\n - Inner\n ```bash\n x\n ```\n\nDone.\n"
+ #expect(Self.kinds(nested) == [.list, .paragraph])
+ let sibling = " - Indented\n- Flush\n```bash\nx\n```\n\nDone.\n"
+ #expect(Self.kinds(sibling) == [.list, .fencedCode, .paragraph])
+ }
+
+ /// An unclosed fence inside an item cannot hold the rest of the answer:
+ /// a non-blank line indented below the column ends the item and the fence.
+ @Test func aLessIndentedLineClosesAnInnerFence() {
+ let source = "1. Install:\n ```bash\n brew install x\nDone.\n\nAfter.\n"
+ #expect(Self.kinds(source) == [.list, .paragraph])
+ #expect(Self.texts(source).last == "After.")
+ }
+
+ @Test func tableRowsAreOneBlock() {
+ let source = "| A | B |\n| :--- | ---: |\n| 1 | 2 |\n\nAfter the table."
+ #expect(Self.texts(source) == ["| A | B |\n| :--- | ---: |\n| 1 | 2 |", "After the table."])
+ #expect(Self.kinds(source) == [.table, .paragraph])
+ }
+
+ /// Ordinals come from the parser, so a loose list has to reach it whole:
+ /// splitting on the blank line between items would restart the numbering
+ /// and separate the items by a paragraph gap.
+ @Test func listAbsorbsBlankLinesNestingAndContinuationText() {
+ let source = """
+ 1. First item
+ continued on the next line
+
+ A second paragraph inside the item
+
+ 2. Second item
+ - nested bullet
+ - deeper bullet
+
+ Ordinary paragraph.
+
+ """
+ let blocks = Self.texts(source)
+ #expect(blocks.count == 2)
+ #expect(blocks[0].hasPrefix("1. First item"))
+ #expect(blocks[0].hasSuffix(" - deeper bullet"))
+ #expect(blocks[0].contains("2. Second item"))
+ #expect(blocks[1] == "Ordinary paragraph.")
+ #expect(Self.kinds(source) == [.list, .paragraph])
+ }
+
+ /// A line that has not ended yet may still turn into a list item, so the
+ /// list it would continue cannot be closed around it. The open tail then
+ /// covers both, which costs nothing: it is one markdown pass over the same
+ /// bytes the whole-document pass would have seen.
+ @Test func openTailSpansAListAndTheUnfinishedLineAfterIt() {
+ let source = "- one\n\nOrdinary par"
+ let split = ResponseBlockSplitter.split(source)
+ #expect(split.completed.isEmpty)
+ #expect(split.open?.kind == .list)
+ #expect(ResponseBlockSplitter.text(
+ split.open?.utf8Range ?? 0..<0,
+ in: source) == source)
+
+ let terminated = ResponseBlockSplitter.split("- one\n\nOrdinary paragraph.\n")
+ #expect(terminated.completed.count == 1)
+ #expect(terminated.open?.kind == .paragraph)
+ }
+
+ @Test func listEndsWhenAnUnindentedParagraphFollowsABlankLine() {
+ let source = "- one\n- two\n\nNot a list line.\n"
+ #expect(Self.texts(source) == ["- one\n- two", "Not a list line."])
+ }
+
+ @Test func quoteAndHeadingAndDisplayMathAreTheirOwnBlocks() {
+ let source = """
+ ### Heading
+
+ > quoted line one
+ > quoted line two
+
+ $$
+ x = 1
+ $$
+
+ Tail paragraph.
+ """
+ #expect(Self.kinds(source) == [.heading, .quote, .displayMath, .paragraph])
+ #expect(Self.texts(source)[2] == "$$\nx = 1\n$$")
+ }
+
+ /// The parser reads a `#` line and the text under it as a heading plus a
+ /// paragraph whether or not a blank line separates them. Splitting there
+ /// would be safe, but the blank-line rule is the one that also keeps
+ /// `Title` above `---` in the same block, where splitting is not.
+ @Test func blankLinesAreTheOnlyBoundary() {
+ #expect(Self.texts("#### Checklist\n- [x] done\n- [ ] open")
+ == ["#### Checklist\n- [x] done\n- [ ] open"])
+ #expect(Self.texts("Title\n---\n\nBody") == ["Title\n---", "Body"])
+ #expect(Self.kinds("Title\n---\n\nBody") == [.paragraph, .paragraph])
+ #expect(Self.kinds("\n---\n\nBody") == [.thematicBreak, .paragraph])
+ }
+
+ @Test func carriageReturnsAreTolerated() {
+ let source = "# CRLF\r\n\r\n```swift\r\nlet a = 1\r\n```\r\n\r\nEnd.\r\n"
+ #expect(Self.texts(source) == ["# CRLF", "```swift\r\nlet a = 1\r\n```", "End."])
+ }
+
+ // MARK: - The open tail
+
+ @Test func trailingBlockIsOpenUntilABlankLineFollowsIt() {
+ let closed = ResponseBlockSplitter.split("One paragraph.\n\n")
+ #expect(closed.open == nil)
+ #expect(closed.completed.count == 1)
+
+ let open = ResponseBlockSplitter.split("One paragraph.\n")
+ #expect(open.completed.isEmpty)
+ #expect(ResponseBlockSplitter.text(
+ open.open?.utf8Range ?? 0..<0,
+ in: "One paragraph.\n") == "One paragraph.")
+ }
+
+ /// A list can still grow across the blank line that already follows it, so
+ /// it stays open where a paragraph would have been completed.
+ @Test func trailingListStaysOpenAcrossItsBlankLine() {
+ let split = ResponseBlockSplitter.split("- one\n\n")
+ #expect(split.completed.isEmpty)
+ #expect(split.open?.kind == .list)
+ }
+
+ @Test func unclosedFenceIsReportedWithItsBody() {
+ let source = "```metal\nkernel void reduce() {\n"
+ let split = ResponseBlockSplitter.split(source)
+ #expect(split.completed.isEmpty)
+ let fence = split.open?.fence
+ #expect(fence?.isClosed == false)
+ #expect(fence?.marker == UInt8(ascii: "`"))
+ #expect(ResponseBlockSplitter.text(
+ (fence?.bodyStart ?? 0)..<(fence?.bodyEnd ?? 0),
+ in: source) == "kernel void reduce() {\n")
+ }
+
+ @Test func closedFenceReportsItsBodyWithoutTheClosingLine() {
+ let source = "```swift\nlet a = 1\n```\n"
+ let split = ResponseBlockSplitter.split(source)
+ #expect(split.open == nil)
+ let fence = split.completed.first?.fence
+ #expect(fence?.isClosed == true)
+ #expect(ResponseBlockSplitter.text(
+ (fence?.bodyStart ?? 0)..<(fence?.bodyEnd ?? 0),
+ in: source) == "let a = 1\n")
+ }
+
+ /// A closing fence that has not reached its newline yet could still turn
+ /// into ```` ```json ````, so it closes the block for display without
+ /// committing it.
+ @Test func partialClosingFenceLineDoesNotCommitTheBlock() {
+ let split = ResponseBlockSplitter.split("```swift\nlet a = 1\n```")
+ #expect(split.completed.isEmpty)
+ #expect(split.open?.fence?.isClosed == true)
+ }
+
+ @Test func aDisplayMathLineIsItsOwnBlockOpenOrClosed() {
+ #expect(ResponseBlockSplitter.split("$$\\frac{a}{b}").open?.kind == .displayMath)
+ #expect(ResponseBlockSplitter.split("$$\\frac{a}{b}$$").open?.kind == .displayMath)
+ // A dollar pair inside a sentence is prose, not a display block.
+ #expect(ResponseBlockSplitter.split("Costs \\$$5 today").open?.kind == .paragraph)
+ }
+
+ // MARK: - Incremental scanning
+
+ /// The controller re-splits on every streaming tick and may not re-read the
+ /// whole answer to do it. Resuming has to land on exactly the state a fresh
+ /// scan would have produced, including the scanner position, for every
+ /// prefix of every corpus fixture.
+ @Test(arguments: TranscriptCorpus.fixtures)
+ func resumedSplitMatchesAFullSplitForEveryPrefix(_ fixture: String) throws {
+ let source = try TranscriptCorpus.source(fixture)
+ var incremental = ResponseBlockSplitter.Split()
+ var prefix = ""
+ for character in source {
+ prefix.append(character)
+ incremental = ResponseBlockSplitter.split(prefix, resuming: incremental)
+ let full = ResponseBlockSplitter.split(prefix)
+ #expect(incremental == full, "\(fixture) diverged at \(prefix.count) characters")
+ if incremental != full { return }
+ }
+ // Every byte of the answer is covered exactly once by the blocks.
+ let blocks = incremental.blocks
+ var cursor = 0
+ for block in blocks {
+ #expect(block.start >= cursor)
+ #expect(block.end > block.start)
+ cursor = block.end
+ }
+ #expect(cursor <= source.utf8.count)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift
index 4cebe1ca..a4e0cf7f 100644
--- a/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift
+++ b/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift
@@ -39,7 +39,8 @@ import Testing
let linkRange = (text as NSString).range(of: "link")
#expect(result.attributedString.attribute(.link, at: linkRange.location,
- effectiveRange: nil) == nil)
+ effectiveRange: nil) as? URL
+ == URL(string: "https://example.com"))
let linkColor = result.attributedString.attribute(
.foregroundColor, at: linkRange.location, effectiveRange: nil) as? NSColor
#expect(linkColor?.isEqual(NSColor.linkColor) == true)
@@ -68,12 +69,34 @@ import Testing
#expect(result.attributedString.string == source)
}
- @Test func unsupportedHTMLTableAndImageStayReadableAsRawText() {
+ /// The gate counted "```" delimiters, so one in the middle of a sentence
+ /// was an odd count and the whole answer — heading, table and all — was
+ /// shown as raw source. Only a line that is a fence line opens a block.
+ @Test func aMidLineBacktickRunNoLongerForcesRawText() {
+ let source = "# Title\n\nA mid-line ``` in a sentence.\n\n| A | B |\n| --- | --- |\n| 1 | 2 |"
+ let result = ResponseMarkdownRenderer().render(source)
+
+ #expect(!result.usedFallback)
+ #expect(!result.attributedString.string.contains("# Title"))
+ #expect(result.attributedString.string.contains("A mid-line ``` in a sentence."))
+ }
+
+ /// A backtick fence's info string may not contain a backtick, so this is a
+ /// closed code span and the answer after it is not inside a code block.
+ @Test func aBacktickInfoStringIsACodeSpanNotAnOpenFence() {
+ let source = "```bash``` is the fence syntax.\n\n# Heading\n\nDone."
+ let result = ResponseMarkdownRenderer().render(source)
+
+ #expect(!result.usedFallback)
+ #expect(result.attributedString.string
+ == "bash is the fence syntax.\n\nHeading\n\nDone.")
+ }
+
+ @Test func blockLevelHTMLStaysReadableAsRawText() {
let renderer = ResponseMarkdownRenderer()
let samples = [
"<div>Never execute this</div>",
- "| A | B |\n|---|---|\n| 1 | 2 |",
- "![remote](https://example.com/image.png)",
+ "<details>\n<summary>open</summary>\nbody\n</details>",
]
for source in samples {
@@ -83,13 +106,547 @@ import Testing
}
}
- @Test func latexRemainsReadableText() {
- let source = "Cosine is $\\frac{u \\cdot v}{||u|| ||v||}$."
+ // The old gate matched any `</?[A-Za-z][^>]*>` in the source, so a
+ // comparison between two math spans read as an HTML tag and pushed the
+ // whole answer to raw text.
+ @Test func comparisonOperatorsBetweenMathSpansNoLongerForceRawText() {
+ let typesetter = FakeMathTypesetter()
+ let result = ResponseMarkdownRenderer(typesetter: typesetter)
+ .render("Prove $a<b$ and $b>c$.")
+
+ #expect(!result.usedFallback)
+ #expect(result.attributedString.string == "Prove \u{FFFC} and \u{FFFC}.")
+ #expect(typesetter.calls.map(\.latex) == ["a<b", "b>c"])
+ }
+
+ @Test func realHTMLTagsStillFallBackToRawText() {
+ let source = "<div>markup</div>"
+ let result = ResponseMarkdownRenderer().render(source)
+
+ #expect(result.usedFallback)
+ #expect(result.attributedString.string == source)
+ }
+
+ @Test func codeBlockLinesShareOneContainerAndDropParagraphSpacing() throws {
+ let source = "Before\n\n```swift\nlet a = 1\nlet b = 2\n```\n\nAfter"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string
+
+ #expect(!result.usedFallback)
+ #expect(text.contains("let a = 1\nlet b = 2"))
+
+ let first = (text as NSString).range(of: "let a = 1")
+ let second = (text as NSString).range(of: "let b = 2")
+ let firstStyle = try #require(result.attributedString.attribute(
+ .paragraphStyle, at: first.location, effectiveRange: nil) as? NSParagraphStyle)
+ let secondStyle = try #require(result.attributedString.attribute(
+ .paragraphStyle, at: second.location, effectiveRange: nil) as? NSParagraphStyle)
+
+ #expect(firstStyle.paragraphSpacing == 0)
+ #expect(firstStyle.lineSpacing == 2)
+ let firstBlock = try #require(firstStyle.textBlocks.first as? NSTextTableBlock)
+ let secondBlock = try #require(secondStyle.textBlocks.first as? NSTextTableBlock)
+ // TextKit 1 merges consecutive paragraphs into one cell only when they
+ // reference the same block object, so a per-line block would draw a
+ // separate box around every line.
+ #expect(firstBlock === secondBlock)
+ #expect(firstBlock.backgroundColor?.isEqual(NSColor.quaternarySystemFill) == true)
+ #expect(firstBlock.width(for: .padding, edge: .minX) == 8)
+ #expect(firstBlock.width(for: .border, edge: .minX) == 1)
+ #expect(firstBlock.borderColor(for: .minX)?.isEqual(NSColor.separatorColor) == true)
+
+ let paragraphStyle = try #require(result.attributedString.attribute(
+ .paragraphStyle,
+ at: (text as NSString).range(of: "Before").location,
+ effectiveRange: nil) as? NSParagraphStyle)
+ #expect(paragraphStyle.textBlocks.isEmpty)
+ }
+
+ @Test func twoCodeBlocksGetSeparateContainers() throws {
+ let source = "```\nfirst\n```\n\ntext\n\n```\nsecond\n```"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string
+
+ let firstStyle = try #require(result.attributedString.attribute(
+ .paragraphStyle,
+ at: (text as NSString).range(of: "first").location,
+ effectiveRange: nil) as? NSParagraphStyle)
+ let secondStyle = try #require(result.attributedString.attribute(
+ .paragraphStyle,
+ at: (text as NSString).range(of: "second").location,
+ effectiveRange: nil) as? NSParagraphStyle)
+ #expect(firstStyle.textBlocks.first !== secondStyle.textBlocks.first)
+ }
+
+ @Test func inlineCodeUsesTheVisibleFillRatherThanTheControlBackground() throws {
+ let result = ResponseMarkdownRenderer().render("Call `reduce(into:)` first.")
+ let range = (result.attributedString.string as NSString).range(of: "reduce(into:)")
+ let fill = try #require(result.attributedString.attribute(
+ .backgroundColor, at: range.location, effectiveRange: nil) as? NSColor)
+
+ #expect(fill.isEqual(NSColor.quaternarySystemFill))
+ }
+
+ @Test func inlineHTMLBreakBecomesALineSeparatorWithinTheParagraph() {
+ let result = ResponseMarkdownRenderer().render("first<br>second<br/>third<br />fourth")
+
+ #expect(!result.usedFallback)
+ #expect(result.attributedString.string
+ == "first\u{2028}second\u{2028}third\u{2028}fourth")
+ }
+
+ @Test func subscriptAndSuperscriptShiftTheBaselineAndShrinkTheFont() throws {
+ let result = ResponseMarkdownRenderer().render("H<sub>2</sub>O and x<sup>2</sup> end")
+ let text = result.attributedString.string
+ #expect(text == "H2O and x2 end")
+
+ let subscriptRange = (text as NSString).range(of: "2O")
+ let superscriptRange = (text as NSString).range(of: "2 end")
+ let baseFont = try #require(result.attributedString.attribute(
+ .font,
+ at: (text as NSString).range(of: "H").location,
+ effectiveRange: nil) as? NSFont)
+
+ let subscriptOffset = try #require(result.attributedString.attribute(
+ .baselineOffset, at: subscriptRange.location, effectiveRange: nil) as? CGFloat)
+ let superscriptOffset = try #require(result.attributedString.attribute(
+ .baselineOffset, at: superscriptRange.location, effectiveRange: nil) as? CGFloat)
+ #expect(subscriptOffset < 0)
+ #expect(superscriptOffset > 0)
+
+ let subscriptFont = try #require(result.attributedString.attribute(
+ .font, at: subscriptRange.location, effectiveRange: nil) as? NSFont)
+ #expect(subscriptFont.pointSize < baseFont.pointSize)
+ #expect(result.attributedString.attribute(
+ .baselineOffset,
+ at: (text as NSString).range(of: "O and").location,
+ effectiveRange: nil) == nil)
+ }
+
+ @Test func inlineHTMLEmphasisTagsMapToTraitsAndUnknownTagsKeepTheirText() throws {
+ let result = ResponseMarkdownRenderer().render(
+ "a<b>bold</b> c<i>it</i> d<kbd>Cmd</kbd> e<span class=\"x\">plain</span>")
+ let text = result.attributedString.string
+ // A tag with no mapping is shown as written: the parser reports
+ // `Vec<String>` as inline HTML too, and deleting it lost the words.
+ #expect(text == "abold cit dCmd e<span class=\"x\">plain</span>")
+
+ let boldFont = try #require(result.attributedString.attribute(
+ .font, at: (text as NSString).range(of: "bold").location,
+ effectiveRange: nil) as? NSFont)
+ #expect(boldFont.fontDescriptor.symbolicTraits.contains(.bold))
+
+ let italicFont = try #require(result.attributedString.attribute(
+ .font, at: (text as NSString).range(of: "it ").location,
+ effectiveRange: nil) as? NSFont)
+ #expect(italicFont.fontDescriptor.symbolicTraits.contains(.italic))
+
+ let kbdFont = try #require(result.attributedString.attribute(
+ .font, at: (text as NSString).range(of: "Cmd").location,
+ effectiveRange: nil) as? NSFont)
+ #expect(kbdFont.fontDescriptor.symbolicTraits.contains(.monoSpace))
+
+ let plainFont = try #require(result.attributedString.attribute(
+ .font, at: (text as NSString).range(of: "plain").location,
+ effectiveRange: nil) as? NSFont)
+ #expect(!plainFont.fontDescriptor.symbolicTraits.contains(.bold))
+ #expect(!plainFont.fontDescriptor.symbolicTraits.contains(.monoSpace))
+ }
+
+ /// Generic parameters and comparisons are the common case: the parser
+ /// calls them inline HTML, and dropping the run deleted the type name from
+ /// the sentence while the reader watched.
+ @Test func unrecognisedAngleBracketTextSurvivesTheHTMLPass() {
+ let source = "Use Vec<String> and a <b>bold</b> word"
+ let renderer = ResponseMarkdownRenderer()
+ let text = renderer.render(source).attributedString.string
+ #expect(text == "Use Vec<String> and a bold word")
+ #expect(renderer.plainText(source) == "Use Vec<String> and a bold word")
+ }
+
+ @Test func inlineHTMLStyleDoesNotLeakPastItsBlock() throws {
+ let result = ResponseMarkdownRenderer().render("<b>opened but never closed\n\nnext paragraph")
+ let text = result.attributedString.string
+ let font = try #require(result.attributedString.attribute(
+ .font, at: (text as NSString).range(of: "next paragraph").location,
+ effectiveRange: nil) as? NSFont)
+
+ #expect(!font.fontDescriptor.symbolicTraits.contains(.bold))
+ }
+
+ @Test func imageRendersItsAltTextAsALinkAndNeverFetches() throws {
+ let result = ResponseMarkdownRenderer().render(
+ "Look ![remote](https://example.com/image.png) here")
+ let text = result.attributedString.string
+
+ #expect(!result.usedFallback)
+ #expect(text == "Look remote here")
+ let range = (text as NSString).range(of: "remote")
+ #expect(result.attributedString.attribute(.link, at: range.location,
+ effectiveRange: nil) as? URL
+ == URL(string: "https://example.com/image.png"))
+ #expect(result.attributedString.attribute(.attachment, at: range.location,
+ effectiveRange: nil) == nil)
+ let color = try #require(result.attributedString.attribute(
+ .foregroundColor, at: range.location, effectiveRange: nil) as? NSColor)
+ #expect(color.isEqual(NSColor.linkColor))
+ }
+
+ /// An image whose alt text is empty produced an empty run, so the picture
+ /// left nothing at all on screen where the reader expected something.
+ @Test func anImageWithNoAltTextShowsItsDestination() {
+ let result = ResponseMarkdownRenderer().render("Look ![](https://example.com/a.png) here")
+ let text = result.attributedString.string
+
+ #expect(text == "Look https://example.com/a.png here")
+ #expect(!text.unicodeScalars.contains { $0.value == 0xFFFC })
+ let range = (text as NSString).range(of: "https://example.com/a.png")
+ #expect(result.attributedString.attribute(
+ .attachment, at: range.location, effectiveRange: nil) == nil)
+ #expect(result.attributedString.attribute(
+ .link, at: range.location, effectiveRange: nil) != nil)
+ }
+
+ /// The destination reaches the text view as a real `.link`, so anything but
+ /// a scheme this transcript is willing to open has to be plain text.
+ @Test(arguments: [
+ "javascript:alert(1)",
+ "file:///etc/passwd",
+ "data:text/html,<b>x</b>",
+ ])
+ func aLinkWithADisallowedSchemeRendersAsPlainText(_ destination: String) throws {
+ let result = ResponseMarkdownRenderer().render("Click [here](\(destination)) now")
+ let text = result.attributedString.string
+ let range = (text as NSString).range(of: "here")
+
+ #expect(!result.usedFallback)
+ #expect(text == "Click here now")
+ #expect(result.attributedString.attribute(
+ .link, at: range.location, effectiveRange: nil) == nil)
+ let color = try #require(result.attributedString.attribute(
+ .foregroundColor, at: range.location, effectiveRange: nil) as? NSColor)
+ #expect(!color.isEqual(NSColor.linkColor))
+ }
+
+ @Test func aLinkInsideATableCellKeepsItsDestinationAndItsCell() throws {
+ let source = "| Name | Where |\n| --- | --- |\n| Docs | [site](https://example.com) |"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string as NSString
+ let range = text.range(of: "site")
+
+ #expect(result.attributedString.attribute(
+ .link, at: range.location, effectiveRange: nil) as? URL
+ == URL(string: "https://example.com"))
+ let style = try #require(result.attributedString.attribute(
+ .paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle)
+ #expect(style.textBlocks.first is NSTextTableBlock)
+ }
+
+ /// `<b then c>` is a valid CommonMark open tag with two bare attributes, so
+ /// the run was dropped and everything after it went bold. Requiring every
+ /// attribute to carry a value is what separates markup from prose.
+ @Test(arguments: [
+ ("if a<b then c>d holds", "if a<b then c>d holds"),
+ ("<b/>x", "<b/>x"),
+ ("</b y>x", "</b y>x"),
+ ("<b =\"v\">x", "<b =\"v\">x"),
+ ("<B>x</B> y", "x y"),
+ ("<b><i>x</i></b> y", "x y"),
+ ])
+ func onlyCompleteTagsAreTreatedAsMarkup(_ probe: (String, String)) {
+ let result = ResponseMarkdownRenderer().render(probe.0)
+ #expect(result.attributedString.string == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ @Test func proseThatParsesAsATagIsNeverStyled() throws {
+ let source = "if a<b then c>d holds for every d"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string as NSString
+ let font = try #require(result.attributedString.attribute(
+ .font, at: text.range(of: "holds").location, effectiveRange: nil) as? NSFont)
+ #expect(!font.fontDescriptor.symbolicTraits.contains(.bold))
+ }
+
+ @Test func anAttributeWithAValueStillApplies() throws {
+ let result = ResponseMarkdownRenderer().render(
+ "a<code class=\"x\">mono</code> b<sup id='n'>up</sup>")
+ let text = result.attributedString.string
+ #expect(text == "amono bup")
+
+ let mono = try #require(result.attributedString.attribute(
+ .font, at: (text as NSString).range(of: "mono").location,
+ effectiveRange: nil) as? NSFont)
+ #expect(mono.fontDescriptor.symbolicTraits.contains(.monoSpace))
+ #expect(result.attributedString.attribute(
+ .baselineOffset,
+ at: (text as NSString).range(of: "up").location,
+ effectiveRange: nil) as? CGFloat ?? 0 > 0)
+ }
+
+ /// Marker and ordinal come from the innermost list, not the outermost.
+ /// Reading the whole intent chain last-write-wins numbered a nested bullet
+ /// and made every nested ordered item repeat its parent's ordinal.
+ @Test func nestedListItemsWearTheirOwnMarker() {
+ let source = """
+ 1. First
+ - bullet under an ordered item
+ - a second bullet
+ 2. Second
+ 1. inner one
+ 2. inner two
+ """
+ let text = ResponseMarkdownRenderer().render(source).attributedString.string
+ #expect(text.contains("1.\tFirst"))
+ #expect(text.contains("\u{2022}\tbullet under an ordered item"))
+ #expect(text.contains("\u{2022}\ta second bullet"))
+ #expect(text.contains("2.\tSecond"))
+ #expect(text.contains("1.\tinner one"))
+ #expect(text.contains("2.\tinner two"))
+ #expect(!text.contains("1.\tbullet"))
+ #expect(!text.contains("2.\t1."))
+ }
+
+ /// A bold-only line becomes its own paragraph, except inside a fence,
+ /// where the bytes are code and the streamed render already drew them.
+ @Test func boldHeadingPromotionStopsAtAFence() {
+ let renderer = ResponseMarkdownRenderer()
+ let promoted = renderer.render("**Note**\nbody text").attributedString.string
+ #expect(promoted == "Note\n\nbody text")
+
+ let fenced = renderer.render(
+ "Intro.\n\n```text\n**Note**\nkeep this line attached\n```\n\nAfter.")
+ #expect(!fenced.usedFallback)
+ #expect(fenced.attributedString.string.contains("**Note**\nkeep this line attached"))
+ }
+
+ @Test func taskListMarkersBecomeCheckboxGlyphs() {
+ let source = "- [x] done\n- [X] also done\n- [ ] open\n- plain\n\n1. [x] first\n2. [ ] second"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string
+
+ #expect(!result.usedFallback)
+ #expect(text.contains("\u{2611}\tdone"))
+ #expect(text.contains("\u{2611}\talso done"))
+ #expect(text.contains("\u{2610}\topen"))
+ #expect(text.contains("\u{2022}\tplain"))
+ #expect(text.contains("1.\t\u{2611} first"))
+ #expect(text.contains("2.\t\u{2610} second"))
+ #expect(!text.contains("[x]"))
+ #expect(!text.contains("[ ]"))
+ }
+
+ @Test func tableRendersAsNativeCellsWithColumnAlignment() throws {
+ let source = "| L | C | R |\n| :--- | :---: | ---: |\n| **a** | b<br>c | d |"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string
+
+ #expect(!result.usedFallback)
+ #expect(text == "L\nC\nR\na\nb\u{2028}c\nd\n")
+
+ func style(_ needle: String) throws -> NSParagraphStyle {
+ let range = (text as NSString).range(of: needle)
+ return try #require(result.attributedString.attribute(
+ .paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle)
+ }
+ #expect(try style("L").alignment == .left)
+ #expect(try style("C").alignment == .center)
+ #expect(try style("R").alignment == .right)
+ #expect(try style("a").alignment == .left)
+ #expect(try style("d").alignment == .right)
+ }
+
+ @Test func tableCellsShareOneTableAndOnlyTheHeaderRowIsFilled() throws {
+ let source = "| L | C | R |\n| :--- | :---: | ---: |\n| a | b | c |"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string
+
+ func cell(_ needle: String) throws -> NSTextTableBlock {
+ let range = (text as NSString).range(of: needle)
+ let style = try #require(result.attributedString.attribute(
+ .paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle)
+ return try #require(style.textBlocks.first as? NSTextTableBlock)
+ }
+
+ let header = try cell("L")
+ let body = try cell("a")
+ let last = try cell("c")
+ #expect(header.table === body.table)
+ #expect(header.table === last.table)
+ #expect(header.table.numberOfColumns == 3)
+ #expect(header.table.collapsesBorders)
+ #expect(header.startingRow == 0)
+ #expect(header.startingColumn == 0)
+ #expect(body.startingRow == 1)
+ #expect(body.startingColumn == 0)
+ #expect(last.startingColumn == 2)
+ #expect(header.backgroundColor?.isEqual(NSColor.quaternarySystemFill) == true)
+ #expect(body.backgroundColor == nil)
+ #expect(header.width(for: .padding, edge: .minX) == 6)
+ #expect(header.width(for: .border, edge: .minX) == 1)
+ #expect(header.borderColor(for: .minX)?.isEqual(NSColor.separatorColor) == true)
+ }
+
+ /// Foundation emits no run for an empty cell, and none at all for the
+ /// cells a short row never wrote, so no text block was created for those
+ /// positions and TextKit laid every body row out with the wrong column
+ /// count. The grid has to be complete before anything is drawn.
+ static let raggedTable = """
+ | Feature | Basic | Pro |
+ | --- | --- | --- |
+ | Price | $20 | |
+ | SSO | | yes |
+ | Notes | short |
+ """
+
+ @Test func aTableWithEmptyAndMissingCellsStillDrawsAFullGrid() throws {
+ let result = ResponseMarkdownRenderer().render(Self.raggedTable)
+ let text = result.attributedString.string
+
+ #expect(!result.usedFallback)
+ #expect(text == "Feature\nBasic\nPro\nPrice\n$20\n\nSSO\n\nyes\nNotes\nshort\n\n")
+
+ var blocks: [NSTextTableBlock] = []
+ result.attributedString.enumerateAttribute(
+ .paragraphStyle,
+ in: NSRange(location: 0, length: result.attributedString.length),
+ options: []) { value, _, _ in
+ guard let block = (value as? NSParagraphStyle)?.textBlocks
+ .first as? NSTextTableBlock else {
+ return
+ }
+ if blocks.last !== block { blocks.append(block) }
+ }
+ #expect(blocks.count == 12)
+ #expect(blocks.map { ($0.startingRow, $0.startingColumn) }.map { "\($0.0),\($0.1)" }
+ == ["0,0", "0,1", "0,2", "1,0", "1,1", "1,2", "2,0", "2,1", "2,2", "3,0", "3,1", "3,2"])
+ #expect(Set(blocks.map { ObjectIdentifier($0.table) }).count == 1)
+ #expect(blocks[0].table.numberOfColumns == 3)
+ // The filler keeps its row's identity: a header fill, a body cell not.
+ #expect(blocks[2].backgroundColor?.isEqual(NSColor.quaternarySystemFill) == true)
+ #expect(blocks[5].backgroundColor == nil)
+ }
+
+ @Test func anEmptyHeaderCellKeepsTheHeaderFill() throws {
+ let source = "| A | | C |\n| --- | --- | --- |\n| 1 | 2 | 3 |"
+ let result = ResponseMarkdownRenderer().render(source)
+
+ #expect(result.attributedString.string == "A\n\nC\n1\n2\n3\n")
+ let text = result.attributedString.string as NSString
+ // The empty header cell is the newline between "A" and "C".
+ let style = try #require(result.attributedString.attribute(
+ .paragraphStyle,
+ at: text.range(of: "A\n\nC").location + 2,
+ effectiveRange: nil) as? NSParagraphStyle)
+ let block = try #require(style.textBlocks.first as? NSTextTableBlock)
+ #expect(block.startingRow == 0)
+ #expect(block.startingColumn == 1)
+ #expect(block.backgroundColor?.isEqual(NSColor.quaternarySystemFill) == true)
+ }
+
+ @Test func theRaggedTablePlainTextKeepsEveryCellBoundary() {
+ #expect(ResponseMarkdownRenderer().plainText(Self.raggedTable)
+ == "Feature\nBasic\nPro\nPrice\n$20\n\nSSO\n\nyes\nNotes\nshort\n\n")
+ }
+
+ @Test func tableHeaderCellsAreSemiboldAndBodyCellsAreNot() throws {
+ let source = "| Tier | Price |\n| --- | --- |\n| Basic | 20 |"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string as NSString
+
+ let header = try #require(result.attributedString.attribute(
+ .font, at: text.range(of: "Tier").location, effectiveRange: nil) as? NSFont)
+ let body = try #require(result.attributedString.attribute(
+ .font, at: text.range(of: "Basic").location, effectiveRange: nil) as? NSFont)
+ #expect(header.fontDescriptor.symbolicTraits.contains(.bold))
+ #expect(!body.fontDescriptor.symbolicTraits.contains(.bold))
+ }
+
+ @Test func twoTablesInOneAnswerDoNotShareATable() throws {
+ let source = "| A |\n| --- |\n| 1 |\n\ntext\n\n| B |\n| --- |\n| 2 |"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string
+
+ func table(_ needle: String) throws -> NSTextTable {
+ let range = (text as NSString).range(of: needle)
+ let style = try #require(result.attributedString.attribute(
+ .paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle)
+ return try #require((style.textBlocks.first as? NSTextTableBlock)?.table)
+ }
+ #expect(try table("A") !== table("B"))
+ }
+
+ @Test func tableCellKeepsBoldAndInlineHTMLBreaks() throws {
+ let source = "| Feature | Detail |\n| --- | --- |\n| **Model** | one<br>two |"
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string
+
+ #expect(text.contains("one\u{2028}two"))
+ let boldRange = (text as NSString).range(of: "Model")
+ let font = try #require(result.attributedString.attribute(
+ .font, at: boldRange.location, effectiveRange: nil) as? NSFont)
+ #expect(font.fontDescriptor.symbolicTraits.contains(.bold))
+ let breakStyle = try #require(result.attributedString.attribute(
+ .paragraphStyle,
+ at: (text as NSString).range(of: "two").location,
+ effectiveRange: nil) as? NSParagraphStyle)
+ #expect(breakStyle.textBlocks.first is NSTextTableBlock)
+ }
+
+ /// A table nested in a quote or a list loses the quote bar and the list
+ /// marker entirely, because the cell walk owns the paragraph style. Raw
+ /// fallback keeps the content with its markers until the renderer can nest
+ /// containers.
+ @Test func aTableInsideAQuoteOrAListFallsBackToRawText() {
+ let renderer = ResponseMarkdownRenderer()
+ for source in [
+ "> | A | B |\n> | --- | --- |\n> | 1 | 2 |",
+ "- item\n\n | A | B |\n | --- | --- |\n | 1 | 2 |",
+ ] {
+ let result = renderer.render(source)
+ #expect(result.usedFallback, "\(source.debugDescription)")
+ #expect(result.attributedString.string == source, "\(source.debugDescription)")
+ }
+ // The other direction: a table of its own still renders natively.
+ let plain = renderer.render("| A | B |\n| --- | --- |\n| 1 | 2 |")
+ #expect(!plain.usedFallback)
+ #expect(!plain.attributedString.string.contains("| --- |"))
+ }
+
+ @Test func tableIsSeparatedFromNeighbouringParagraphs() {
+ let source = "Before the table.\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\nAfter the table."
let result = ResponseMarkdownRenderer().render(source)
#expect(!result.usedFallback)
- #expect(result.attributedString.string.contains("\\frac"))
- #expect(result.attributedString.string.contains("\\cdot"))
+ #expect(result.attributedString.string
+ == "Before the table.\n\nA\nB\n1\n2\n\nAfter the table.")
+ }
+
+ @Test func plainTextOfATableIsReadableCellText() {
+ let renderer = ResponseMarkdownRenderer()
+ let source = "| Tier | Price |\n| --- | ---: |\n| Basic | $20 |"
+
+ #expect(renderer.plainText(source) == "Tier\nPrice\nBasic\n$20\n")
+ }
+
+ /// Replaces the old `latexRemainsReadableText` pin: with math on, the same
+ /// answer typesets; with the kill switch set, it is the raw text again.
+ @Test func killSwitchRestoresRawLatexText() {
+ let source = "Cosine is $\\frac{u \\cdot v}{||u|| ||v||}$."
+ let typesetter = FakeMathTypesetter()
+ let enabled = ResponseMarkdownRenderer(
+ environment: [:],
+ typesetter: typesetter).render(source)
+ #expect(!enabled.usedFallback)
+ #expect(enabled.attributedString.string == "Cosine is \u{FFFC}.")
+
+ let disabled = ResponseMarkdownRenderer(
+ environment: ["TURBO_FIELDFARE_DISABLE_MATH": "1"],
+ typesetter: typesetter).render(source)
+ #expect(!disabled.usedFallback)
+ #expect(disabled.attributedString.string.contains("\\frac"))
+ #expect(disabled.attributedString.string.contains("\\cdot"))
+ // The disabled render must not have reached the typesetter at all.
+ #expect(typesetter.calls.count == 1)
}
@Test func boldOnlyModelHeadingStaysOnItsOwnLine() {
@@ -100,10 +657,305 @@ import Testing
#expect(result.attributedString.string
== "Origins\n\nFieldfares arrive from northern Europe.")
}
+
+ // MARK: - Math
+
+ static func attachment(
+ _ result: ResponseMarkdownRenderer.Result,
+ at location: Int
+ ) -> MathAttachment? {
+ result.attributedString.attribute(
+ .attachment,
+ at: location,
+ effectiveRange: nil) as? MathAttachment
+ }
+
+ static func paragraphStyle(
+ _ result: ResponseMarkdownRenderer.Result,
+ at location: Int
+ ) -> NSParagraphStyle? {
+ result.attributedString.attribute(
+ .paragraphStyle,
+ at: location,
+ effectiveRange: nil) as? NSParagraphStyle
+ }
+
+ @Test func inlineMathBecomesAnAttachmentAndLeavesTheMarkdownAroundItStyled() throws {
+ let typesetter = FakeMathTypesetter()
+ let result = ResponseMarkdownRenderer(typesetter: typesetter)
+ .render("- **Root** of $x^2 = 4$ is two")
+ let text = result.attributedString.string
+
+ #expect(!result.usedFallback)
+ #expect(text == "\u{2022}\tRoot of \u{FFFC} is two")
+ let placeholder = (text as NSString).range(of: "\u{FFFC}")
+ let attachment = try #require(Self.attachment(result, at: placeholder.location))
+ #expect(attachment.latexSource == "$x^2 = 4$")
+ #expect(attachment.image?.accessibilityDescription == "$x^2 = 4$")
+ #expect(typesetter.calls.map(\.latex) == ["x^2 = 4"])
+
+ let boldRange = (text as NSString).range(of: "Root")
+ let boldFont = try #require(result.attributedString.attribute(
+ .font, at: boldRange.location, effectiveRange: nil) as? NSFont)
+ #expect(boldFont.fontDescriptor.symbolicTraits.contains(.bold))
+ }
+
+ /// Every one of these is altered by `AttributedString(markdown:)`: the
+ /// backslash before `,` disappears, `\{`/`\}` unescape, and `\[...\]` loses
+ /// its delimiters entirely. The typesetter must see the source bytes.
+ @Test func mangledLatexReachesTheTypesetterByteIdentical() {
+ let typesetter = FakeMathTypesetter()
+ _ = ResponseMarkdownRenderer(typesetter: typesetter).render(
+ #"$a \, b$ then $\{x\}$ then \[x = 1\] then $a*b*c$"#)
+
+ #expect(typesetter.calls.map(\.latex) == [
+ #"a \, b"#, #"\{x\}"#, #"x = 1"#, #"a*b*c"#,
+ ])
+ }
+
+ @Test func aTypesetFailureLeavesTheRawSpanTextInPlace() throws {
+ let typesetter = FakeMathTypesetter()
+ typesetter.failing = [#"\bogus"#]
+ let result = ResponseMarkdownRenderer(typesetter: typesetter)
+ .render(#"Broken $\bogus$ but $x$ works."#)
+ let text = result.attributedString.string
+
+ #expect(!result.usedFallback)
+ #expect(text == #"Broken $\bogus$ but "# + "\u{FFFC} works.")
+ let rawRange = (text as NSString).range(of: #"\bogus"#)
+ #expect(Self.attachment(result, at: rawRange.location) == nil)
+ let font = try #require(result.attributedString.attribute(
+ .font, at: rawRange.location, effectiveRange: nil) as? NSFont)
+ #expect(font.pointSize == NSFont.systemFontSize)
+ }
+
+ @Test func standaloneDisplayMathGetsItsOwnCentredParagraph() throws {
+ let typesetter = FakeMathTypesetter()
+ let result = ResponseMarkdownRenderer(typesetter: typesetter)
+ .render("Subtract $c$:\n$$ax^2 = -c$$\nDone.")
+ let text = result.attributedString.string
+
+ #expect(text == "Subtract \u{FFFC}:\n\n\u{FFFC}\n\nDone.")
+ let display = (text as NSString).range(
+ of: "\u{FFFC}",
+ options: .backwards)
+ let style = try #require(Self.paragraphStyle(result, at: display.location))
+ #expect(style.alignment == .center)
+
+ let inline = (text as NSString).range(of: "\u{FFFC}")
+ let inlineStyle = try #require(Self.paragraphStyle(result, at: inline.location))
+ #expect(inlineStyle.alignment != .center)
+ #expect(typesetter.calls.map(\.mode) == [.inline, .display])
+ }
+
+ @Test func twoConsecutiveDisplayBlocksBecomeTwoParagraphs() {
+ let typesetter = FakeMathTypesetter()
+ let result = ResponseMarkdownRenderer(typesetter: typesetter)
+ .render("$$a = 1$$\n$$b = 2$$")
+
+ #expect(result.attributedString.string == "\u{FFFC}\n\n\u{FFFC}")
+ #expect(typesetter.calls.map(\.latex) == ["a = 1", "b = 2"])
+ }
+
+ @Test func displayMathInsideAListItemKeepsTheListIndentAndIsNotCentred() throws {
+ let typesetter = FakeMathTypesetter()
+ let result = ResponseMarkdownRenderer(typesetter: typesetter)
+ .render("- step $$x = 1$$ here")
+ let text = result.attributedString.string
+
+ #expect(text == "\u{2022}\tstep \u{FFFC} here")
+ let placeholder = (text as NSString).range(of: "\u{FFFC}")
+ let style = try #require(Self.paragraphStyle(result, at: placeholder.location))
+ #expect(style.alignment != .center)
+ #expect(style.headIndent == 22)
+ #expect(typesetter.calls.map(\.mode) == [.display])
+ }
+
+ /// Gemma writes `cases` and `aligned` inside single dollars. Alone in a
+ /// paragraph they are block notation and typeset in display style; in the
+ /// middle of a sentence they stay inline.
+ @Test func inlineEnvironmentsTypesetAsDisplayOnlyWhenTheyOwnTheParagraph() {
+ let typesetter = FakeMathTypesetter()
+ let source = #"$\begin{aligned} a &= b \end{aligned}$"#
+ _ = ResponseMarkdownRenderer(typesetter: typesetter).render(source)
+ _ = ResponseMarkdownRenderer(typesetter: typesetter).render("Value \(source) here")
+
+ #expect(typesetter.calls.map(\.mode) == [.display, .inline])
+ }
+
+ @Test func mathInAHeadingAndAQuoteInheritsTheirFontSizeAndColour() throws {
+ let typesetter = FakeMathTypesetter()
+ _ = ResponseMarkdownRenderer(typesetter: typesetter).render("## Solve $x$")
+ let headingSize = try #require(typesetter.calls.first?.fontSize)
+ #expect(headingSize > NSFont.systemFontSize)
+
+ let quoteTypesetter = FakeMathTypesetter()
+ _ = ResponseMarkdownRenderer(typesetter: quoteTypesetter).render("> cite $x$")
+ let quote = try #require(quoteTypesetter.calls.first)
+ #expect(quote.fontSize == NSFont.systemFontSize)
+ #expect(quote.tint.isEqual(NSColor.secondaryLabelColor))
+ }
+
+ @Test func attachmentSitsOnTheBaselineUsingTheReportedDescent() throws {
+ let result = ResponseMarkdownRenderer(typesetter: FakeMathTypesetter())
+ .render("Inline $x$ here")
+ let placeholder = (result.attributedString.string as NSString).range(of: "\u{FFFC}")
+ let attachment = try #require(Self.attachment(result, at: placeholder.location))
+
+ #expect(attachment.bounds.origin.y == -FakeMathTypesetter.descent)
+ #expect(attachment.bounds.height == FakeMathTypesetter.ascent + FakeMathTypesetter.descent)
+ }
+
+ /// A sentinel inside a link destination is percent-encoded into the `.link`
+ /// attribute and vanishes from the character stream. A whole-message raw
+ /// fallback is the only honest answer: the alternative is a silently
+ /// deleted equation.
+ @Test func aSentinelSwallowedByALinkDestinationFallsBackToRawText() {
+ let source = "See [tier](http://example.com/?q=$a$) now."
+ let result = ResponseMarkdownRenderer(typesetter: FakeMathTypesetter())
+ .render(source)
+
+ #expect(result.usedFallback)
+ #expect(result.attributedString.string == source)
+ }
+
+ /// Whichever gate fires, the raw text shown must be the original source and
+ /// never the sentinel working copy.
+ @Test func fallbackGatesShowTheOriginalSourceNotTheWorkingCopy() {
+ let renderer = ResponseMarkdownRenderer(typesetter: FakeMathTypesetter())
+ for source in [
+ "Math $x$ then\n\n```swift\nlet a = 1",
+ "<div>block</div>\n\nMath $x$ after",
+ ] {
+ let result = renderer.render(source)
+ #expect(result.usedFallback, "\(source.debugDescription)")
+ #expect(result.attributedString.string == source)
+ #expect(!result.attributedString.string.unicodeScalars
+ .contains { $0.value == 0xE000 })
+ }
+ }
+
+ @Test func plainTextReturnsTheLatexSourceRatherThanThePlaceholder() {
+ let renderer = ResponseMarkdownRenderer(typesetter: FakeMathTypesetter())
+ let plain = renderer.plainText("Roots of $x^2 = 4$ and\n$$y = 1$$\ndone.")
+
+ #expect(plain == "Roots of $x^2 = 4$ and\n\n$$y = 1$$\n\ndone.")
+ #expect(!plain.unicodeScalars.contains { $0.value == 0xFFFC })
+ }
+
+ @Test func literalProtectSpansAreRestoredVerbatimAndNeverTypeset() {
+ let typesetter = FakeMathTypesetter()
+ let source = "Gradient is\n\n$$\\frac{\\partial L}{\\partial w} = \\sum_i x_i"
+ let result = ResponseMarkdownRenderer(typesetter: typesetter).render(source)
+
+ #expect(!result.usedFallback)
+ #expect(result.attributedString.string
+ == "Gradient is\n\n$$\\frac{\\partial L}{\\partial w} = \\sum_i x_i")
+ #expect(typesetter.calls.isEmpty)
+ }
+
+ /// The shield turned an ordinary sentence into raw source for the rest of
+ /// the answer: the heading, the bold run and the list below it all showed
+ /// their markers.
+ @Test(arguments: [
+ "It costs $$$ a lot.\n**Bold** line\n# Heading",
+ "Rated $$ on the price scale.\n- item one\n- item two",
+ "See \\[ in the note.\n# Heading",
+ ])
+ func aStrayDisplayOpenerInProseLeavesTheAnswerStyled(_ source: String) {
+ let typesetter = FakeMathTypesetter()
+ let result = ResponseMarkdownRenderer(typesetter: typesetter).render(source)
+ let text = result.attributedString.string
+
+ #expect(!result.usedFallback, "\(source.debugDescription)")
+ #expect(!text.contains("**"), "\(source.debugDescription)")
+ #expect(!text.contains("# Heading"), "\(source.debugDescription)")
+ #expect(typesetter.calls.isEmpty)
+ }
+
+ /// The bracket pair carried prose into the typesetter, which failed, and
+ /// the words came back as raw source with their backslashes.
+ @Test func anEscapedBracketPairInProseRendersAsBrackets() {
+ let typesetter = FakeMathTypesetter()
+ let result = ResponseMarkdownRenderer(typesetter: typesetter)
+ .render(#"the array \[1, 2, 3\] holds three values"#)
+
+ #expect(!result.usedFallback)
+ #expect(result.attributedString.string == "the array [1, 2, 3] holds three values")
+ #expect(typesetter.calls.isEmpty)
+ }
+
+ /// Two lone backticks paragraphs apart used to pair into one code span
+ /// across everything between them. The equation in the middle typeset
+ /// while the answer streamed, because each paragraph was rendered on its
+ /// own, and then reverted to raw source at finalize when the whole message
+ /// went through one pass.
+ @Test func loneBackticksInSeparateParagraphsDoNotMaskTheMathBetweenThem() {
+ let typesetter = FakeMathTypesetter()
+ let source = """
+ Press the ` key to open the console.
+
+ The relation is $E = mc^2$ exactly.
+
+ Use the ` character to quote a word.
+ """
+ let result = ResponseMarkdownRenderer(typesetter: typesetter).render(source)
+
+ #expect(!result.usedFallback)
+ #expect(typesetter.calls.map(\.latex) == ["E = mc^2"])
+ #expect(!result.attributedString.string.contains("$E = mc^2$"))
+ // Each paragraph keeps the backtick it wrote; only the span between
+ // them was ever in question.
+ #expect(result.attributedString.string.contains("Press the ` key"))
+ #expect(result.attributedString.string.contains("Use the ` character"))
+ }
+
+ /// Two spans with the same LaTeX share one memoised image, so writing the
+ /// accessibility description onto it gave both attachments whichever
+ /// description was written last.
+ @Test func eachEquationKeepsItsOwnAccessibilityDescription() throws {
+ let result = ResponseMarkdownRenderer()
+ .render(#"Both $x^2$ and \(x^2\) say the same thing."#)
+ var descriptions: [String] = []
+ result.attributedString.enumerateAttribute(
+ .attachment,
+ in: NSRange(location: 0, length: result.attributedString.length),
+ options: []) { value, _, _ in
+ guard let attachment = value as? MathAttachment else { return }
+ descriptions.append(attachment.image?.accessibilityDescription ?? "")
+ }
+ #expect(descriptions == ["$x^2$", #"\(x^2\)"#])
+ }
+
+ @Test func currencyAndShellDollarsNeverReachTheTypesetter() {
+ let typesetter = FakeMathTypesetter()
+ let renderer = ResponseMarkdownRenderer(typesetter: typesetter)
+ for source in [
+ "The base plan is $20 per month and the pro plan is $30 per month.",
+ "In prose the variables are $HOME and $PATH on one line.",
+ "A shell comparison such as $x=$y must stay text.",
+ "```bash\necho $HOME\nexport T=\"$HOME/$PATH\"\n```",
+ ] {
+ let result = renderer.render(source)
+ #expect(!result.usedFallback, "\(source.debugDescription)")
+ }
+ #expect(typesetter.calls.isEmpty)
+ }
}
@MainActor
@Suite struct InstructionTranscriptDocumentControllerTests {
+ /// Streaming without the progressive render: the answer is appended as raw
+ /// text and only the finalize pass styles it. These tests are what
+ /// `TURBO_FIELDFARE_PROGRESSIVE_RENDER=0` has to keep doing.
+ static func rawStreamingController(
+ renderer: any TranscriptBlockRendering = ResponseMarkdownRenderer()
+ ) -> InstructionTranscriptDocumentController {
+ InstructionTranscriptDocumentController(
+ renderer: renderer,
+ environment: ["TURBO_FIELDFARE_PROGRESSIVE_RENDER": "0"])
+ }
+
@Test func appAccentMatchesProductRGB() {
let color = TurboFieldfareMacTheme.accentNSColor
.usingColorSpace(.sRGB)
@@ -113,9 +965,12 @@ import Testing
#expect(abs((color?.blueComponent ?? 0) - 113.0 / 255.0) < 0.000_001)
}
+ /// The raw streaming path, which `TURBO_FIELDFARE_PROGRESSIVE_RENDER=0`
+ /// restores. Its progressive counterpart is in
+ /// `ProgressiveTranscriptRenderTests`.
@Test func rebuildsThenAppendsOnlyNewResponseSuffix() {
let storage = NSMutableAttributedString()
- let controller = InstructionTranscriptDocumentController()
+ let controller = Self.rawStreamingController()
let first = controller.synchronize(
storage: storage,
@@ -242,7 +1097,7 @@ import Testing
@Test func terminalPartialOutputIsReadableAndNextRunRestoresStreamingSource() {
let storage = NSMutableAttributedString()
- let controller = InstructionTranscriptDocumentController()
+ let controller = Self.rawStreamingController()
_ = controller.synchronize(
storage: storage,
prompt: "Question",
@@ -272,7 +1127,11 @@ import Testing
response: partial,
isTerminal: true)
#expect(first.mutation == .finalized)
- #expect(storage.string.hasSuffix(partial))
+ // The unclosed fence is drawn as code, not shown as raw source: the
+ // per-block finalize never puts the answer through the message-wide
+ // gate that the whole-document render applies.
+ #expect(storage.string.hasSuffix("kernel void matmul() {}\n"))
+ #expect(!storage.string.contains("```"))
let updated = controller.synchronize(
storage: storage,
@@ -287,6 +1146,156 @@ import Testing
#expect(!storage.string.contains("```"))
}
+ @Test func streamingAppendsMultiByteAndCJKDeltasExactly() {
+ let storage = NSMutableAttributedString()
+ let controller = Self.rawStreamingController()
+ let answer = "\u{4E2D}\u{6587}: caf\u{E9} \u{30C6}\u{30B9}\u{30C8} $x^2$ done"
+
+ var seen = ""
+ for character in answer {
+ seen.append(character)
+ let result = controller.synchronize(
+ storage: storage,
+ prompt: "Ask",
+ response: seen,
+ isTerminal: false)
+ #expect(result.mutation == .appended || result.mutation == .rebuilt)
+ #expect((storage.string as NSString).substring(with: result.assistantRange) == seen)
+ }
+ #expect(storage.string == "You\nAsk\n\nAnswer\n" + answer)
+ }
+
+ // A combining mark grows the response in bytes while leaving its grapheme
+ // count unchanged, so neither the byte-length test nor a grapheme-length
+ // test can be trusted on its own to decide that nothing was added.
+ @Test func combiningMarkThatKeepsTheGraphemeCountStillReachesTheStorage() {
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController()
+
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "caf e", isTerminal: false)
+ let result = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "caf e\u{301}", isTerminal: false)
+
+ #expect(result.mutation != .none)
+ #expect(storage.string == "You\nAsk\n\nAnswer\ncaf e\u{301}")
+ #expect((storage.string as NSString).substring(with: result.assistantRange)
+ == "caf e\u{301}")
+ }
+
+ /// Clamping alone kept a selection's length over whatever now sits at
+ /// those indices, so a reader with text selected watched the highlight
+ /// slide onto different characters on every streaming tick.
+ @Test func selectionThatReachedIntoTheRewrittenRangeStopsAtItsBoundary() {
+ let adjusted = InstructionTranscriptDocumentController.adjustedRanges(
+ [
+ NSRange(location: 0, length: 4),
+ NSRange(location: 2, length: 10),
+ NSRange(location: 10, length: 6),
+ NSRange(location: 40, length: 3),
+ NSRange(location: 6, length: 0),
+ ],
+ replacing: NSRange(location: 6, length: 30),
+ newLength: 5)
+
+ #expect(adjusted == [
+ // Entirely in the stable prefix: exact indices kept.
+ NSRange(location: 0, length: 4),
+ // Started in the prefix and ran into the rewrite: the prefix part
+ // survives, the rest is gone.
+ NSRange(location: 2, length: 4),
+ // Entirely inside the rewrite: collapsed where it began.
+ NSRange(location: 10, length: 0),
+ // Below the rewrite: the same characters, moved by the delta.
+ // Collapsing these too dropped a selection over text that had not
+ // changed at all.
+ NSRange(location: 15, length: 3),
+ // A caret at the boundary is not inside the rewrite.
+ NSRange(location: 6, length: 0),
+ ])
+ }
+
+ /// A tail re-render rewrites the same sentence with a few characters
+ /// added. Reporting the whole tail as replaced collapsed every selection
+ /// inside it, including one over text that had not moved.
+ @Test(arguments: [
+ // old, new, expected offset into `previous`, expected old length, new length
+ ("abc", "abcd", 3, 0, 1),
+ ("abcd", "abc", 3, 1, 0),
+ ("hello world", "hello brave world", 6, 0, 6),
+ ("same", "same", -1, 0, 0),
+ // A surrogate pair and a composed sequence may not be split.
+ ("a\u{1F600}b", "a\u{1F600}c", 3, 1, 1),
+ ("cafe\u{301} x", "cafe\u{301} y", 6, 1, 1),
+ ])
+ func differingTrimsWhatBothSidesShare(_ probe: (String, String, Int, Int, Int)) {
+ let replaced = InstructionTranscriptDocumentController.ReplacedRange.differing(
+ previous: NSRange(location: 10, length: (probe.0 as NSString).length),
+ old: probe.0 as NSString,
+ new: probe.1 as NSString)
+ guard probe.2 >= 0 else {
+ #expect(replaced == nil, "\(probe.0.debugDescription)")
+ return
+ }
+ #expect(replaced?.previous == NSRange(location: 10 + probe.2, length: probe.3),
+ "\(probe.0.debugDescription)")
+ #expect(replaced?.length == probe.4, "\(probe.0.debugDescription)")
+ }
+
+ /// The whole point of trimming: a selection over a completed block above
+ /// the open one keeps its exact indices through a streaming tick and
+ /// through finalize.
+ @Test func aSelectionOverACompletedBlockSurvivesATickAndFinalize() {
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController(environment: [:])
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "# Title\n\nBody sta", isTerminal: false)
+ let heading = (storage.string as NSString).range(of: "Title")
+ let selection = [heading]
+
+ let tick = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "# Title\n\nBody star", isTerminal: false)
+ let afterTick = InstructionTranscriptDocumentController.adjustedRanges(
+ selection,
+ replacing: try! #require(tick.replaced).previous,
+ newLength: try! #require(tick.replaced).length)
+ #expect(afterTick == selection)
+ #expect((storage.string as NSString).substring(with: afterTick[0]) == "Title")
+
+ let final = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "# Title\n\nBody star", isTerminal: true)
+ let afterFinalize = final.replaced.map {
+ InstructionTranscriptDocumentController.adjustedRanges(
+ afterTick, replacing: $0.previous, newLength: $0.length)
+ } ?? afterTick
+ #expect((storage.string as NSString).substring(with: afterFinalize[0]) == "Title")
+ }
+
+ /// The coordinator can only adjust a selection if the controller says what
+ /// it rewrote, so the range is part of the result rather than something the
+ /// caller infers from `tailRange` after the fact.
+ @Test func aTailReplacementReportsTheRangeItRewrote() {
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController(environment: [:])
+ _ = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "Done.\n\nab", isTerminal: false)
+ let before = controller.tailRange
+
+ let update = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "Done.\n\nabc", isTerminal: false)
+ #expect(update.mutation == .tailReplaced)
+ // Only the character that arrived: the "ab" above it is the same text
+ // at the same indices, so a selection over it is not disturbed.
+ #expect(update.replaced?.previous
+ == NSRange(location: before.upperBound, length: 0))
+ #expect(update.replaced?.length == 1)
+
+ // An append that rewrites nothing reports nothing.
+ let appended = controller.synchronize(
+ storage: storage, prompt: "Ask", response: "Done.\n\nabc\n\nNext.", isTerminal: false)
+ #expect(appended.mutation == .tailReplaced || appended.mutation == .appended)
+ }
+
@Test func selectionRangesClampToCurrentStorage() {
let ranges = InstructionTranscriptDocumentController.clampedRanges([
NSRange(location: 3, length: 20),
@@ -299,6 +1308,177 @@ import Testing
])
}
+ // MARK: - Math at finalize time
+
+ @Test func streamingShowsRawMathAndFinalizationTypesetsIt() {
+ let storage = NSMutableAttributedString()
+ let typesetter = FakeMathTypesetter()
+ let controller = Self.rawStreamingController(
+ renderer: ResponseMarkdownRenderer(typesetter: typesetter))
+ let answer = "Roots:\n$$x = 1$$"
+
+ var seen = ""
+ for character in answer {
+ seen.append(character)
+ let streaming = controller.synchronize(
+ storage: storage,
+ prompt: "Solve",
+ response: seen,
+ isTerminal: false)
+ #expect((storage.string as NSString).substring(with: streaming.assistantRange)
+ == seen)
+ }
+ #expect(typesetter.calls.isEmpty)
+ #expect(storage.string.hasSuffix("$$x = 1$$"))
+
+ let final = controller.synchronize(
+ storage: storage,
+ prompt: "Solve",
+ response: answer,
+ isTerminal: true)
+ #expect(final.mutation == .finalized)
+ #expect(controller.response == answer)
+ #expect(typesetter.calls.map(\.latex) == ["x = 1"])
+ #expect((storage.string as NSString).substring(with: final.assistantRange)
+ == "Roots:\n\n\u{FFFC}")
+ #expect(final.assistantRange.upperBound == storage.length)
+ }
+
+ /// Mirror of the late-closing-fence case: a `$$` that closes after the
+ /// terminal flag must re-render, not stay half typeset.
+ @Test func lateClosingDisplayMathRefinalizesAndTypesets() {
+ let storage = NSMutableAttributedString()
+ let typesetter = FakeMathTypesetter()
+ let controller = InstructionTranscriptDocumentController(
+ renderer: ResponseMarkdownRenderer(typesetter: typesetter))
+ let partial = "Answer\n\n$$x = \\frac{1}{2}"
+ let complete = partial + "$$"
+
+ let first = controller.synchronize(
+ storage: storage,
+ prompt: "Solve",
+ response: partial,
+ isTerminal: true)
+ #expect(first.mutation == .finalized)
+ #expect(typesetter.calls.isEmpty)
+ #expect(storage.string.hasSuffix("$$x = \\frac{1}{2}"))
+
+ let updated = controller.synchronize(
+ storage: storage,
+ prompt: "Solve",
+ response: complete,
+ isTerminal: true)
+ #expect(updated.mutation == .finalized)
+ #expect(typesetter.calls.map(\.latex) == [#"x = \frac{1}{2}"#])
+ #expect((storage.string as NSString).substring(with: updated.assistantRange)
+ == "Answer\n\n\u{FFFC}")
+ }
+
+ @Test func resumingAfterFinalizationRestoresTheRawStreamingSource() {
+ let storage = NSMutableAttributedString()
+ let typesetter = FakeMathTypesetter()
+ let controller = InstructionTranscriptDocumentController(
+ renderer: ResponseMarkdownRenderer(typesetter: typesetter))
+ let answer = "Roots $x = 1$ found"
+
+ _ = controller.synchronize(
+ storage: storage,
+ prompt: "Solve",
+ response: answer,
+ isTerminal: true)
+ #expect(storage.string.hasSuffix("Roots \u{FFFC} found"))
+
+ let resumed = controller.synchronize(
+ storage: storage,
+ prompt: "Solve",
+ response: answer,
+ isTerminal: false)
+ #expect(resumed.mutation == .rebuilt)
+ #expect(!controller.isFinalized)
+ #expect(storage.string.hasSuffix(answer))
+ }
+
+ /// The mailbox can drain after the terminal flag is set, so `apply` runs
+ /// the terminal path more than once; typesetting must not run again with
+ /// it.
+ @Test func repeatedTerminalSynchronizeTypesetsTheAnswerOnce() {
+ let storage = NSMutableAttributedString()
+ let typesetter = FakeMathTypesetter()
+ let controller = InstructionTranscriptDocumentController(
+ renderer: ResponseMarkdownRenderer(typesetter: typesetter))
+
+ for _ in 0..<3 {
+ _ = controller.synchronize(
+ storage: storage,
+ prompt: "Solve",
+ response: "Roots $x = 1$ found",
+ isTerminal: true)
+ }
+ #expect(typesetter.calls.count == 1)
+ }
+
+ /// Records the finalize cost of the worst corpus fixture. Fifty equations
+ /// is well past one frame cold, which is why the typesetter memoises; the
+ /// warm pass is what a rebuild of an already-finalised answer costs.
+ @Test func fiftyEquationFinalizeCostIsRecorded() throws {
+ let source = try TranscriptCorpus.source("fifty-equations")
+ let clock = ContinuousClock()
+ // Font registration happens on the first equation of the process.
+ _ = ResponseMarkdownRenderer().render("$x$")
+
+ func milliseconds(_ duration: Duration) -> Double {
+ Double(duration.components.seconds) * 1e3
+ + Double(duration.components.attoseconds) * 1e-15
+ }
+
+ // A private cache makes the cold number independent of whatever else
+ // ran in this process first.
+ let cache = MathRenderCache()
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController(
+ renderer: ResponseMarkdownRenderer(
+ typesetter: SwiftMathTypesetter(cache: cache)))
+ let cold = clock.measure {
+ controller.synchronize(
+ storage: storage,
+ prompt: "Derive",
+ response: source,
+ isTerminal: true)
+ }
+ #expect(cache.count == 50)
+
+ // A rebuild while the answer is terminal re-renders the whole
+ // transcript; this is the path the memo exists for.
+ let warmStorage = NSMutableAttributedString()
+ let warmController = InstructionTranscriptDocumentController(
+ renderer: ResponseMarkdownRenderer(
+ typesetter: SwiftMathTypesetter(cache: cache)))
+ let warm = clock.measure {
+ warmController.synchronize(
+ storage: warmStorage,
+ prompt: "Derive",
+ response: source,
+ isTerminal: true)
+ }
+
+ let unchanged = clock.measure {
+ controller.synchronize(
+ storage: storage,
+ prompt: "Derive",
+ response: source,
+ isTerminal: true)
+ }
+ print("""
+ MATH-FINALIZE fifty-equations \
+ cold=\(String(format: "%.1f", milliseconds(cold)))ms \
+ warm=\(String(format: "%.1f", milliseconds(warm)))ms \
+ unchanged=\(String(format: "%.1f", milliseconds(unchanged)))ms
+ """)
+ #expect(milliseconds(warm) < milliseconds(cold))
+ // An unchanged terminal response must not render at all.
+ #expect(milliseconds(unchanged) < 1)
+ }
+
@Test func terminalFormattingAlwaysScrollsToBottom() {
#expect(InstructionTranscriptDocumentController.shouldScrollToBottom(
wasAtBottom: false,
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Support/AttributedStringDigest.swift b/Tests/TurboFieldfareApp/MacPresentation/Support/AttributedStringDigest.swift
new file mode 100644
index 00000000..346b8e1d
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Support/AttributedStringDigest.swift
@@ -0,0 +1,150 @@
+import AppKit
+import Foundation
+@testable import TurboFieldfareMacPresentation
+
+/// A comparable description of what an attributed string draws.
+///
+/// Two renders of the same markdown are never `isEqual` — an `NSTextTable`, an
+/// `NSTextTableBlock`, and an `NSTextAttachment` all compare by object
+/// identity, and every render pass makes its own. Runs are also cut in
+/// different places depending on how a string was assembled, which changes
+/// nothing on screen. The digest keeps the values and merges adjacent runs that
+/// carry the same ones, so a comparison fails on a real difference and only on
+/// a real difference.
+struct AttributedStringDigest: Equatable, CustomStringConvertible {
+ struct Run: Equatable {
+ var text: String
+ let font: String
+ let foreground: String
+ let background: String
+ var paragraph: String
+ let link: String
+ let attachment: String
+ let underline: Int
+ let strikethrough: Int
+ let baselineOffset: Double
+ }
+
+ let runs: [Run]
+
+ var text: String { runs.map(\.text).joined() }
+
+ /// One entry per character, so two renders can be compared position by
+ /// position even when their runs are cut in different places.
+ var perCharacter: [Run] {
+ runs.flatMap { run in
+ run.text.map { character in
+ var single = run
+ single.text = String(character)
+ return single
+ }
+ }
+ }
+
+ var description: String {
+ runs.map { run in
+ "\(run.text.debugDescription) font=\(run.font) fg=\(run.foreground) "
+ + "bg=\(run.background) para=\(run.paragraph) link=\(run.link) "
+ + "att=\(run.attachment) u=\(run.underline) s=\(run.strikethrough) "
+ + "base=\(run.baselineOffset)"
+ }.joined(separator: "\n")
+ }
+
+ @MainActor
+ init(_ attributed: NSAttributedString) {
+ var runs: [Run] = []
+ // Distinct container objects get distinct numbers: two tables that
+ // should be separate digest the same as one merged table otherwise,
+ // and that is exactly the bug a shared cached render would cause.
+ var identities: [ObjectIdentifier: Int] = [:]
+ let string = attributed.string as NSString
+ attributed.enumerateAttributes(
+ in: NSRange(location: 0, length: attributed.length),
+ options: []) { attributes, range, _ in
+ let run = Run(
+ text: string.substring(with: range),
+ font: Self.describe(attributes[.font] as? NSFont),
+ foreground: Self.describe(attributes[.foregroundColor] as? NSColor),
+ background: Self.describe(attributes[.backgroundColor] as? NSColor),
+ paragraph: Self.describe(
+ attributes[.paragraphStyle] as? NSParagraphStyle,
+ identities: &identities),
+ link: (attributes[.link] as? URL)?.absoluteString
+ ?? attributes[.link] as? String ?? "",
+ attachment: Self.describe(attributes[.attachment] as? NSTextAttachment),
+ underline: attributes[.underlineStyle] as? Int ?? 0,
+ strikethrough: attributes[.strikethroughStyle] as? Int ?? 0,
+ baselineOffset: (attributes[.baselineOffset] as? CGFloat).map(Double.init) ?? 0)
+ if var last = runs.last, Self.sameAttributes(last, run) {
+ last.text += run.text
+ runs[runs.count - 1] = last
+ } else {
+ runs.append(run)
+ }
+ }
+ self.runs = runs
+ }
+
+ private static func sameAttributes(_ lhs: Run, _ rhs: Run) -> Bool {
+ var probe = lhs
+ probe.text = rhs.text
+ return probe == rhs
+ }
+
+ private static func describe(_ font: NSFont?) -> String {
+ guard let font else { return "-" }
+ let traits = font.fontDescriptor.symbolicTraits
+ return "\(font.fontName)@\(String(format: "%.2f", font.pointSize))/\(traits.rawValue)"
+ }
+
+ private static func describe(_ color: NSColor?) -> String {
+ color?.description ?? "-"
+ }
+
+ private static func describe(_ attachment: NSTextAttachment?) -> String {
+ guard let attachment else { return "-" }
+ guard let math = attachment as? MathAttachment else { return "attachment" }
+ let bounds = attachment.bounds
+ return "math(\(math.latexSource))@"
+ + "\(String(format: "%.1fx%.1f", bounds.width, bounds.height))"
+ }
+
+ private static func describe(
+ _ style: NSParagraphStyle?,
+ identities: inout [ObjectIdentifier: Int]
+ ) -> String {
+ guard let style else { return "-" }
+ var identifiers = identities
+ let blocks = style.textBlocks
+ .map { describe($0, identities: &identifiers) }
+ .joined(separator: ",")
+ identities = identifiers
+ return [
+ "align=\(style.alignment.rawValue)",
+ "line=\(style.lineSpacing)",
+ "space=\(style.paragraphSpacing)",
+ "before=\(style.paragraphSpacingBefore)",
+ "first=\(style.firstLineHeadIndent)",
+ "head=\(style.headIndent)",
+ "tail=\(style.tailIndent)",
+ "tabs=\(style.tabStops.map(\.location))",
+ "blocks=[\(blocks)]",
+ ].joined(separator: " ")
+ }
+
+ private static func describe(
+ _ block: NSTextBlock,
+ identities: inout [ObjectIdentifier: Int]
+ ) -> String {
+ let identity = identities[ObjectIdentifier(block)]
+ ?? { let next = identities.count; identities[ObjectIdentifier(block)] = next; return next }()
+ var description = "block#\(identity)(bg=\(block.backgroundColor?.description ?? "-")"
+ description += " pad=\(block.width(for: .padding, edge: .minX))"
+ description += " border=\(block.width(for: .border, edge: .minX))"
+ if let cell = block as? NSTextTableBlock {
+ description += " cell=\(cell.startingRow),\(cell.startingColumn)"
+ description += " cols=\(cell.table.numberOfColumns)"
+ }
+ return description + ")"
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Support/FakeMathTypesetter.swift b/Tests/TurboFieldfareApp/MacPresentation/Support/FakeMathTypesetter.swift
new file mode 100644
index 00000000..f7b6c0f0
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Support/FakeMathTypesetter.swift
@@ -0,0 +1,38 @@
+import AppKit
+import Foundation
+@testable import TurboFieldfareMacPresentation
+
+/// Deterministic stand-in for the typesetter. Renderer tests assert what the
+/// pipeline hands over — byte-identical LaTeX, the run's font size and colour,
+/// the chosen mode — without depending on any glyph the real library draws.
+@MainActor
+final class FakeMathTypesetter: MathTypesetting {
+ struct Call: Equatable {
+ let latex: String
+ let fontSize: CGFloat
+ let tint: NSColor
+ let mode: MathRenderMode
+ }
+
+ static let ascent: CGFloat = 9
+ static let descent: CGFloat = 3
+
+ private(set) var calls: [Call] = []
+ /// LaTeX that must come back as a typeset failure, keyed on what the
+ /// renderer passes in.
+ var failing: Set<String> = []
+
+ func render(
+ latex: String,
+ fontSize: CGFloat,
+ tint: NSColor,
+ mode: MathRenderMode
+ ) -> MathRender? {
+ calls.append(Call(latex: latex, fontSize: fontSize, tint: tint, mode: mode))
+ guard !failing.contains(latex) else { return nil }
+ return MathRender(
+ image: NSImage(size: NSSize(width: 20, height: Self.ascent + Self.descent)),
+ ascent: Self.ascent,
+ descent: Self.descent)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Support/RecordingBlockRenderer.swift b/Tests/TurboFieldfareApp/MacPresentation/Support/RecordingBlockRenderer.swift
new file mode 100644
index 00000000..4e1de920
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Support/RecordingBlockRenderer.swift
@@ -0,0 +1,45 @@
+import AppKit
+import Foundation
+@testable import TurboFieldfareMacPresentation
+
+/// Records what the transcript controller asks the renderer for. "Each
+/// completed block is rendered once" is otherwise invisible from the outside:
+/// the document looks the same whether a block was rendered once or on every
+/// tick, and only the clock would tell the difference.
+@MainActor
+final class RecordingBlockRenderer: TranscriptBlockRendering {
+ struct Call: Equatable {
+ let source: String
+ let typesetsMath: Bool
+ }
+
+ private let base: ResponseMarkdownRenderer
+ private(set) var calls: [Call] = []
+
+ init(base: ResponseMarkdownRenderer = ResponseMarkdownRenderer()) {
+ self.base = base
+ }
+
+ /// Blocks that were rendered as finished, in order.
+ var completedSources: [String] {
+ calls.filter(\.typesetsMath).map(\.source)
+ }
+
+ /// Renders of the block that was still being written.
+ var tailSources: [String] {
+ calls.filter { !$0.typesetsMath }.map(\.source)
+ }
+
+ func render(_ source: String, typesetsMath: Bool) -> ResponseMarkdownRenderer.Result {
+ calls.append(Call(source: source, typesetsMath: typesetsMath))
+ return base.render(source, typesetsMath: typesetsMath)
+ }
+
+ func blockSeparator(trailingNewlines: Int) -> NSAttributedString {
+ base.blockSeparator(trailingNewlines: trailingNewlines)
+ }
+
+ func streamingCodeAttributes() -> [NSAttributedString.Key: Any] {
+ base.streamingCodeAttributes()
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptCorpus.swift b/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptCorpus.swift
new file mode 100644
index 00000000..f3ffa321
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptCorpus.swift
@@ -0,0 +1,81 @@
+import Foundation
+
+/// The rendering corpus: three verbatim Gemma 4 IT answers plus the synthetic
+/// shapes that historically broke the renderer. The list is explicit so a new
+/// fixture cannot land without an expectation entry.
+enum TranscriptCorpus {
+ static let fixtures: [String] = [
+ "backtick-info-string",
+ "arithmetic-prose",
+ "blank-line-fence",
+ "br-only-paragraph",
+ "cjk",
+ "crlf",
+ "currency",
+ "display-math-blank-line",
+ "fence-in-list-item",
+ "fence-in-quote",
+ "fifty-equations",
+ "gemma-comparison-table",
+ "gemma-derivation-table",
+ "gemma-inline-environments",
+ "heading-with-math",
+ "html-details",
+ "large-code-block",
+ "latex-paren-bracket",
+ "link-dollar-url",
+ "list-nested-fence",
+ "list-then-fence",
+ "lone-display-dollars",
+ "long-prose-line",
+ "nested-lists",
+ "prose-display-dollars",
+ "prose-fence",
+ "quote-with-math",
+ "reference-links",
+ "shell-dollars",
+ "table-empty-cells",
+ "table-in-list",
+ "table-html-bold",
+ "tab-indented-fence",
+ "task-lists",
+ "unclosed-display-math",
+ "unclosed-fence",
+ ]
+
+ /// Fixtures the whole-document render sends to raw source, where the
+ /// per-block finalize keeps everything but the block that trips the gate.
+ /// This is the difference the per-block finalize exists to make: an
+ /// unclosed fence anywhere, a table in a list item, a block-level HTML tag
+ /// used to take the whole answer down with them at the moment it finished.
+ static let wholeRenderFallbacks: Set<String> = [
+ "br-only-paragraph",
+ "html-details",
+ "table-in-list",
+ "unclosed-fence",
+ ]
+
+ /// What the per-block render cannot do. A reference definition lives in a
+ /// block of its own, so the block that uses the label cannot resolve it.
+ /// Scanning the whole response per tick is the shape the streaming timing
+ /// gate forbids, and resolving it only at finalize would reintroduce the
+ /// flip the per-block pass removes.
+ static let perBlockLimitations: Set<String> = ["reference-links"]
+
+ /// Fixtures whose completed blocks end inside a display opener the model
+ /// never closed. Completing it is exactly what the pass is for, so these
+ /// are only pinned through the call the tail render actually makes, which
+ /// keeps the LaTeX as source and leaves the dollars alone.
+ static let unclosedDisplayBlocks: Set<String> = ["display-math-blank-line"]
+
+ static func source(_ fixture: String) throws -> String {
+ guard let url = Bundle.module.url(
+ forResource: fixture,
+ withExtension: "md",
+ subdirectory: "Fixtures/transcript-corpus") else {
+ throw TranscriptFrameError(
+ description: "corpus fixture \(fixture).md is not in the test bundle")
+ }
+ return try String(contentsOf: url, encoding: .utf8)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptFrameRenderer.swift b/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptFrameRenderer.swift
new file mode 100644
index 00000000..985600a5
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptFrameRenderer.swift
@@ -0,0 +1,113 @@
+import AppKit
+import Foundation
+import Testing
+
+struct TranscriptFrameError: Error, CustomStringConvertible {
+ let description: String
+}
+
+/// Offscreen renderer for transcript frames. The text view is configured to
+/// match `IncrementalTranscriptView.makeNSView` so a frame shows what the app
+/// shows; the only deliberate differences are an opaque background (the app
+/// lets the SwiftUI surface show through, which would render as transparent
+/// pixels here) and a fixed width so frames stay comparable across runs.
+@MainActor
+enum TranscriptFrameRenderer {
+ static let defaultWidth: CGFloat = 560
+
+ /// Beyond this the bitmap allocation and the hosting window stop being
+ /// reliable; taller documents are cropped rather than dropped.
+ static let maximumHeight: CGFloat = 4000
+
+ private static let verticalInset: CGFloat = 4
+
+ static func image(
+ _ attributed: NSAttributedString,
+ width: CGFloat = defaultWidth,
+ dark: Bool
+ ) throws -> NSImage {
+ let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: width, height: 10))
+ textView.isEditable = false
+ textView.isSelectable = true
+ textView.isRichText = true
+ textView.drawsBackground = true
+ textView.backgroundColor = .textBackgroundColor
+ textView.textContainerInset = NSSize(width: 0, height: verticalInset)
+ textView.isVerticallyResizable = true
+ textView.isHorizontallyResizable = false
+ textView.autoresizingMask = [.width]
+ textView.textContainer?.widthTracksTextView = true
+ textView.textContainer?.lineFragmentPadding = 0
+ textView.isAutomaticLinkDetectionEnabled = false
+ textView.isAutomaticDataDetectionEnabled = false
+
+ guard let storage = textView.textStorage,
+ let container = textView.textContainer,
+ let layoutManager = textView.layoutManager else {
+ throw TranscriptFrameError(description: "text view has no TextKit 1 stack")
+ }
+ storage.setAttributedString(attributed)
+ layoutManager.ensureLayout(for: container)
+ let used = layoutManager.usedRect(for: container)
+ let height = min(max(used.height + verticalInset * 2, 12), maximumHeight)
+ textView.frame.size.height = height
+
+ let window = NSWindow(
+ contentRect: textView.bounds,
+ styleMask: [.borderless],
+ backing: .buffered,
+ defer: false)
+ window.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)
+ window.contentView = textView
+ window.layoutIfNeeded()
+
+ let bounds = textView.bounds
+ guard let rep = NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: Int(bounds.width * 2),
+ pixelsHigh: Int(bounds.height * 2),
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0) else {
+ throw TranscriptFrameError(
+ description: "cannot allocate a 2x bitmap for \(bounds.size)")
+ }
+ rep.size = bounds.size
+ textView.cacheDisplay(in: bounds, to: rep)
+
+ let image = NSImage(size: bounds.size)
+ image.addRepresentation(rep)
+ return image
+ }
+
+ /// Records the frame as a test attachment and, when
+ /// `TURBO_FIELDFARE_FRAME_DIR` is set, also writes it there so frames can
+ /// be reviewed without passing `--attachments-path`.
+ static func record(_ image: NSImage, named name: String) throws {
+ Attachment.record(image, named: name, as: .png)
+ guard let directory = ProcessInfo.processInfo
+ .environment["TURBO_FIELDFARE_FRAME_DIR"], !directory.isEmpty else {
+ return
+ }
+ guard let rep = image.representations.first as? NSBitmapImageRep,
+ let data = rep.representation(using: .png, properties: [:]) else {
+ throw TranscriptFrameError(description: "frame \(name) has no PNG representation")
+ }
+ let root = URL(fileURLWithPath: directory, isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ try data.write(to: root.appendingPathComponent(name))
+ }
+
+ static func record(
+ _ attributed: NSAttributedString,
+ named name: String,
+ width: CGFloat = defaultWidth,
+ dark: Bool
+ ) throws {
+ try record(try image(attributed, width: width, dark: dark), named: name)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TailAutoCloseTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TailAutoCloseTests.swift
new file mode 100644
index 00000000..8baf034d
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/TailAutoCloseTests.swift
@@ -0,0 +1,285 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@Suite struct TailAutoCloseTests {
+ static let guardCharacter = String(TailAutoClose.setextGuard)
+
+ // MARK: - Fences
+
+ @Test func unclosedFenceGetsItsClosingLine() {
+ #expect(TailAutoClose.close("```swift\nlet a = 1") == "```swift\nlet a = 1\n```")
+ #expect(TailAutoClose.close("```swift\nlet a = 1\n") == "```swift\nlet a = 1\n```")
+ #expect(TailAutoClose.close("~~~~text\nbody") == "~~~~text\nbody\n~~~~")
+ }
+
+ @Test func aLoneBacktickInProseIsNotAnOpener() {
+ // "Press the ` key" is prose, not the start of a code span; closing it
+ // briefly styles the rest of the sentence as code while it is the tail.
+ let prose = "Press the ` key to open the console."
+ #expect(TailAutoClose.close(prose) == prose)
+ let pair = "The ` and ` keys are both literal here."
+ #expect(TailAutoClose.close(pair) == pair)
+ }
+
+ @Test func aCodeLikeBacktickOpenerIsStillClosed() {
+ #expect(TailAutoClose.close("Use `swift bui") == "Use `swift bui`")
+ let closed = "Wrap it in `code ` with a padded closer."
+ #expect(TailAutoClose.close(closed) == closed)
+ }
+
+ /// Counting the marker run alone made "```bash```" an unclosed fence, so
+ /// the tail grew a closing line and the sentence turned into a code box.
+ @Test func aBacktickInfoStringIsNotAnOpenFence() {
+ let tail = "```bash``` is the fence syn"
+ #expect(TailAutoClose.close(tail) == tail)
+ }
+
+ @Test func closedFenceIsLeftAlone() {
+ let closed = "```swift\nlet a = 1\n```"
+ #expect(TailAutoClose.close(closed) == closed)
+ }
+
+ /// Nothing inside a fence is markdown. A half-written `**` or a stray
+ /// backtick in code must survive exactly as the model wrote it.
+ @Test func markersInsideAFenceAreNeverBalanced() {
+ let tail = "```bash\necho \"**\" `date` $$\ngrep -o 'a"
+ #expect(TailAutoClose.close(tail) == tail + "\n```")
+ }
+
+ /// The closer was written flush left whatever container the fence was
+ /// opened in, so the parser read it as prose after the item and the
+ /// listing kept its markers on screen while it streamed.
+ @Test(arguments: [
+ ("1. Install:\n ```bash\n brew install x", "\n ```"),
+ ("> ```bash\n> brew install x", "\n> ```"),
+ ("> 1. Install:\n> ```bash\n> brew install x", "\n> ```"),
+ ("- Install:\n ~~~text\n body", "\n ~~~"),
+ ])
+ func aFenceInsideAContainerIsClosedInsideIt(_ probe: (String, String)) {
+ #expect(TailAutoClose.close(probe.0) == probe.0 + probe.1,
+ "\(probe.0.debugDescription)")
+ }
+
+ @Test func aClosedFenceInsideAnItemIsLeftAlone() {
+ let closed = "1. Install:\n ```bash\n brew install x\n ```"
+ #expect(TailAutoClose.close(closed) == closed)
+ }
+
+ // MARK: - Inline code
+
+ @Test func unterminatedInlineCodeIsClosedWithItsOwnRun() {
+ #expect(TailAutoClose.close("Run `swift bui") == "Run `swift bui`")
+ #expect(TailAutoClose.close("Use ``a ` b") == "Use ``a ` b``")
+ }
+
+ @Test func balancedInlineCodeIsLeftAlone() {
+ #expect(TailAutoClose.close("Run `swift build` now") == "Run `swift build` now")
+ }
+
+ /// Emphasis that opened before an unterminated code span is still open, and
+ /// its closer has to land outside the code, not inside it.
+ @Test func closersNestInTheOrderTheyWereOpened() {
+ #expect(TailAutoClose.close("**bold `cod") == "**bold `cod`**")
+ }
+
+ // MARK: - Emphasis
+
+ @Test func unbalancedStrongAndEmphasisAreClosed() {
+ #expect(TailAutoClose.close("A **bold sta") == "A **bold sta**")
+ #expect(TailAutoClose.close("An *italic sta") == "An *italic sta*")
+ #expect(TailAutoClose.close("An _italic sta") == "An _italic sta_")
+ #expect(TailAutoClose.close("***both sta") == "***both sta***")
+ }
+
+ @Test func balancedEmphasisIsLeftAlone() {
+ #expect(TailAutoClose.close("A **bold** word") == "A **bold** word")
+ #expect(TailAutoClose.close("A *thin* word") == "A *thin* word")
+ }
+
+ /// The reader should never see the marker itself. Closing it instead would
+ /// write `****`, which is a new run of literal asterisks rather than the
+ /// emphasis the model is one keystroke away from opening.
+ @Test func aMarkerWithNothingAfterItIsRemovedRatherThanClosed() {
+ #expect(TailAutoClose.close("A sentence and **") == "A sentence and ")
+ #expect(TailAutoClose.close("A sentence and *") == "A sentence and ")
+ #expect(TailAutoClose.close("A sentence and `") == "A sentence and ")
+ #expect(TailAutoClose.close("Half **bold** and *") == "Half **bold** and ")
+ }
+
+ /// Closing these would create structure the source does not have: a bullet
+ /// would turn into bold text and a rule would turn into emphasis.
+ @Test func listBulletsAndThematicBreaksAreNotEmphasisOpeners() {
+ #expect(TailAutoClose.close("* first item") == "* first item")
+ #expect(TailAutoClose.close("- one\n* two") == "- one\n* two")
+ #expect(TailAutoClose.close("Above\n\n***") == "Above\n\n***")
+ }
+
+ @Test func intrawordUnderscoresAreNotEmphasis() {
+ #expect(TailAutoClose.close("Call snake_case_name now") == "Call snake_case_name now")
+ #expect(TailAutoClose.close("Call snake_case_na") == "Call snake_case_na")
+ }
+
+ @Test func escapedMarkersAreNotOpeners() {
+ #expect(TailAutoClose.close("Literal \\*star and more") == "Literal \\*star and more")
+ }
+
+ // MARK: - Math
+
+ @Test func standaloneDisplayMathIsClosed() {
+ #expect(TailAutoClose.close("$$x = \\frac{1}{2") == "$$x = \\frac{1}{2$$")
+ #expect(TailAutoClose.close("Step 1.\n$$a + b") == "Step 1.\n$$a + b$$")
+ }
+
+ /// The closer arrives one character at a time. Adding a whole `$$` to the
+ /// half of it that is already there would show a third dollar for a tick.
+ @Test func aHalfTypedDisplayCloserIsCompletedNotDoubled() {
+ #expect(TailAutoClose.close("$$x = 1$") == "$$x = 1$$")
+ #expect(TailAutoClose.close("Step 1.\n$$a + b$") == "Step 1.\n$$a + b$$")
+ }
+
+ /// The transcript keeps the open block's math as source rather than
+ /// typesetting a half-typed equation, and a closer nothing will typeset is
+ /// two dollars on screen that the model never wrote.
+ @Test func displayMathIsNotClosedForACallerThatKeepsTheSource() {
+ #expect(TailAutoClose.close("$$x = \\frac{1}{2", typesetsMath: false)
+ == "$$x = \\frac{1}{2")
+ #expect(TailAutoClose.close("A **bold sta", typesetsMath: false) == "A **bold sta**")
+ }
+
+ @Test func closedDisplayMathIsLeftAlone() {
+ #expect(TailAutoClose.close("$$x = 1$$") == "$$x = 1$$")
+ }
+
+ /// Currency is the reason single `$` is never closed by anyone: `$20` and
+ /// `$30` in one sentence would become an equation.
+ @Test func singleDollarsAreNeverClosed() {
+ #expect(TailAutoClose.close("The plan costs $20 and the pro plan $3")
+ == "The plan costs $20 and the pro plan $3")
+ #expect(TailAutoClose.close("A mid-sentence $$ pair is not a block")
+ == "A mid-sentence $$ pair is not a block")
+ }
+
+ @Test func mathContentIsNotTreatedAsEmphasis() {
+ #expect(TailAutoClose.close("$$a * b * c") == "$$a * b * c$$")
+ }
+
+ /// The tail keeps its math as source, so nothing masked it and every `_`
+ /// in a subscript and `*` in an equation read as an emphasis marker.
+ @Test(arguments: [
+ ("The value $x_{1}$ is small", "The value $x_{1}$ is small"),
+ ("The value $x_{1", "The value $x_{1"),
+ (#"where $\alpha*\beta"#, #"where $\alpha*\beta"#),
+ // Currency is not an equation, so the emphasis after it is still live.
+ ("costs $20 and *very goo", "costs $20 and *very goo*"),
+ ])
+ func mathOnTheTailIsNotEmphasis(_ probe: (String, String)) {
+ #expect(TailAutoClose.close(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ @Test func displayMathOnTheTailIsNotEmphasisForASourceKeepingCaller() {
+ let tail = "$$\n\\sum_{i=1}^n x_i"
+ #expect(TailAutoClose.close(tail, typesetsMath: false) == tail)
+ }
+
+ /// CommonMark flanking, with the deviations arithmetic prose needs: a `*`
+ /// between word characters is multiplication, and `*=` is an operator.
+ @Test(arguments: [
+ ("Multiply 2*3 to get", "Multiply 2*3 to get"),
+ ("Multiply 2*3 to get *nine", "Multiply 2*3 to get *nine*"),
+ ("The exponent x**2 stays", "The exponent x**2 stays"),
+ ("a *= 2", "a *= 2"),
+ ("**Note:** value_1 and *bo", "**Note:** value_1 and *bo*"),
+ ("(*paren", "(*paren*"),
+ ])
+ func emphasisFollowsTheFlankingRule(_ probe: (String, String)) {
+ #expect(TailAutoClose.close(probe.0) == probe.1, "\(probe.0.debugDescription)")
+ }
+
+ /// Every marker on a line re-read the line from its start, so an 8 KB
+ /// paragraph cost 164 ms a tick. Per-line state is carried instead.
+ @Test func closingCostIsLinearInTheLine() {
+ func line(_ bytes: Int) -> String {
+ let unit = "word *emph* and more text. "
+ return String(repeating: unit, count: bytes / unit.utf8.count) + "trailing *ope"
+ }
+ let small = line(2_048)
+ let large = line(8_192)
+ let clock = ContinuousClock()
+ func cost(_ text: String) -> Double {
+ let elapsed = clock.measure {
+ for _ in 0..<5 { _ = TailAutoClose.close(text) }
+ }
+ return Double(elapsed.components.seconds)
+ + Double(elapsed.components.attoseconds) * 1e-18
+ }
+ _ = cost(small)
+ let smallCost = cost(small)
+ let largeCost = cost(large)
+ let ratio = largeCost / smallCost
+ print(String(
+ format: "TAIL-CLOSE 2KB=%.2fms 8KB=%.2fms ratio=%.2f",
+ smallCost * 1e3 / 5,
+ largeCost * 1e3 / 5,
+ ratio))
+ #expect(ratio < 8, "four times the line cost \(ratio) times as much")
+ }
+
+ // MARK: - Trailing fragments
+
+ @Test func incompleteTagIsStripped() {
+ #expect(TailAutoClose.close("Line one<br") == "Line one")
+ #expect(TailAutoClose.close("Closing </su") == "Closing ")
+ }
+
+ @Test func comparisonsAndCompleteTagsSurvive() {
+ #expect(TailAutoClose.close("If a < b then") == "If a < b then")
+ #expect(TailAutoClose.close("Line one<br>Line two") == "Line one<br>Line two")
+ }
+
+ @Test func incompleteLinkRendersItsLabel() {
+ #expect(TailAutoClose.close("See [the docs](https://exa") == "See the docs")
+ #expect(TailAutoClose.close("![alt text](https://exa") == "alt text")
+ }
+
+ @Test func completeLinkIsLeftAlone() {
+ let link = "See [the docs](https://example.com) now"
+ #expect(TailAutoClose.close(link) == link)
+ }
+
+ // MARK: - Setext
+
+ /// `Title` plus a half-typed rule turns into a large heading for one tick
+ /// and back into a paragraph on the next. The guard keeps it a paragraph.
+ @Test func trailingRuleUnderAParagraphIsNeutralized() {
+ #expect(TailAutoClose.close("Title\n---") == "Title\n---" + Self.guardCharacter)
+ #expect(TailAutoClose.close("Title\n===") == "Title\n===" + Self.guardCharacter)
+ }
+
+ @Test func ruleAfterABlankLineStaysAThematicBreak() {
+ #expect(TailAutoClose.close("Paragraph.\n\n---") == "Paragraph.\n\n---")
+ }
+
+ @Test func emptyTailIsUnchanged() {
+ #expect(TailAutoClose.close("") == "")
+ }
+
+ /// A finished answer must survive the pass untouched: whatever the model
+ /// closed itself is the text the finalize render will see. The
+ /// source-keeping call is the one the tail render makes and holds for every
+ /// fixture; the typesetting call completes an unclosed `$$`, which is what
+ /// it is for, so a fixture whose block ends inside one is pinned through
+ /// the source-keeping call alone.
+ @Test(arguments: TranscriptCorpus.fixtures)
+ func closedCorpusBlocksAreUnchanged(_ fixture: String) throws {
+ let source = try TranscriptCorpus.source(fixture)
+ let split = ResponseBlockSplitter.split(source)
+ for block in split.completed {
+ let text = ResponseBlockSplitter.text(block.utf8Range, in: source)
+ #expect(TailAutoClose.close(text, typesetsMath: false) == text,
+ "\(fixture) rewrote a completed block")
+ guard !TranscriptCorpus.unclosedDisplayBlocks.contains(fixture) else { continue }
+ #expect(TailAutoClose.close(text) == text, "\(fixture) rewrote a completed block")
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptRenderCorpusTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptRenderCorpusTests.swift
new file mode 100644
index 00000000..fb5aff0c
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptRenderCorpusTests.swift
@@ -0,0 +1,376 @@
+import AppKit
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@MainActor
+@Suite struct TranscriptRenderCorpusTests {
+ struct Expectation {
+ let usedFallback: Bool
+ var mustContain: [String] = []
+ var mustNotContain: [String] = []
+ /// Typeset equations, counted as attachment runs. A fixture whose math
+ /// stops being typeset drops to zero here rather than failing silently.
+ var attachments = 0
+ }
+
+ /// One entry per corpus fixture, recording what the renderer actually does
+ /// today. A fixture that flips when a renderer capability lands must flip
+ /// here in the same change.
+ static let expectations: [String: Expectation] = [
+ "backtick-info-string": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "Fence syntax",
+ "bash when you mean",
+ "A mid-line ``` in a sentence",
+ "Backtick span",
+ "inline code",
+ "Done.",
+ ],
+ mustNotContain: ["# Fence syntax", "| --- |"]),
+ "arithmetic-prose": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "Multiply 2*3 to get 6",
+ "x**2 is not emphasis",
+ "a * b",
+ "x *= 2",
+ ],
+ attachments: 1),
+ "blank-line-fence": Expectation(
+ usedFallback: false,
+ mustContain: ["Intro.\n\n\nAfter."],
+ mustNotContain: ["```"]),
+ "br-only-paragraph": Expectation(
+ usedFallback: true,
+ mustContain: ["<br>"]),
+ "cjk": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "内联公式",
+ "let x = 1",
+ "低层级",
+ "特性",
+ "内置数据竞争保护。",
+ // A Han character on both sides of the delimiters: the
+ // adjacency rules used to read the whole run as one word.
+ "质量为\u{FFFC}的物体",
+ ],
+ mustNotContain: ["###", "**", "| :--- |"],
+ attachments: 2),
+ "crlf": Expectation(
+ usedFallback: false,
+ mustContain: ["CRLF document", "let a = 1", "Trailing paragraph."],
+ mustNotContain: ["# CRLF", "**", "```", "\r"]),
+ "currency": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "$20 per month",
+ "$49.99",
+ "Basic",
+ "$200",
+ // Only the equation typesets; the two amounts beside it stay
+ // as written.
+ "It costs $5 (or $10 for two). The formula \u{FFFC} applies",
+ ],
+ mustNotContain: ["###", "| :--- |"],
+ attachments: 1),
+ "display-math-blank-line": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "Intro.",
+ // The opener shields only as far as the blank line under it.
+ "$$\n\\frac{a}{b}",
+ "c = d",
+ "the answer continues.",
+ ],
+ attachments: 1),
+ "fence-in-list-item": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "1.\tInstall the tool:",
+ "brew install x",
+ "2.\tCheck the version:",
+ "x --version",
+ "Both steps stay inside their items.",
+ ],
+ mustNotContain: ["```"]),
+ "fence-in-quote": Expectation(
+ usedFallback: false,
+ mustContain: ["Run the installer first:", "brew install x", "Then continue"],
+ mustNotContain: ["```", "> "]),
+ "fifty-equations": Expectation(
+ usedFallback: false,
+ mustContain: ["Fifty equations", "Step 50.", "closed form"],
+ mustNotContain: ["###"],
+ attachments: 50),
+ "gemma-comparison-table": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "Concurrency Comparison",
+ "GCD Queues",
+ "Swift Actors",
+ "\u{2611}\tDefine data model",
+ "\u{2610}\tOptimize performance",
+ "actor BankAccount {",
+ ],
+ mustNotContain: ["###", "**", "```", "- [x]", "| :--- |"]),
+ "gemma-derivation-table": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "1. Derivation of the Quadratic Formula",
+ "completing the square",
+ "4. Comparison Table",
+ "Case A ($20)",
+ "Target Market",
+ ],
+ mustNotContain: ["###", "**", "| Feature |", "| :--- |"],
+ attachments: 20),
+ "gemma-inline-environments": Expectation(
+ usedFallback: false,
+ mustContain: ["Bayes' Theorem:", "Absolute Value:", "echo $HOME", "\\d+"],
+ mustNotContain: ["**", "```", "\\begin{cases}", "\\begin{aligned}"],
+ attachments: 4),
+ "heading-with-math": Expectation(
+ usedFallback: false,
+ mustContain: ["Solving", "discriminant", "heading size"],
+ mustNotContain: ["##"],
+ attachments: 2),
+ "html-details": Expectation(
+ usedFallback: true,
+ mustContain: ["<details>", "Hidden body text.", "Done."]),
+ "large-code-block": Expectation(
+ usedFallback: false,
+ mustContain: ["Streaming buffer implementation", "struct RingSlot057", "capacity."],
+ mustNotContain: ["```", "###"]),
+ "latex-paren-bracket": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "area of a circle",
+ "volume of a sphere",
+ "Escaped braces stay literal",
+ ],
+ mustNotContain: ["\\pi r^2", "\\frac{4}{3}", "\\(", "\\["],
+ attachments: 2),
+ "link-dollar-url": Expectation(
+ usedFallback: false,
+ mustContain: ["the pricing page", "the docs", "https://example.com/plain"],
+ mustNotContain: ["](", "<https"]),
+ "list-nested-fence": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "1.\tOuter step",
+ "\u{2022}\tInner step",
+ // Inside the listing the dollars are shell, not math.
+ "cost $a$ per run",
+ "export TARGET=\"$HOME/$PATH\"",
+ "Then \u{FFFC} closes the answer.",
+ ],
+ mustNotContain: ["~~~"],
+ attachments: 2),
+ "list-then-fence": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "\u{2022}\tInstall the tool:",
+ "brew install x",
+ "brew link x",
+ "Done.",
+ ],
+ mustNotContain: ["```", "- Install"]),
+ "lone-display-dollars": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "Rated $$ on the price scale.",
+ "Pricing notes",
+ "Basic",
+ "\u{2022}\tThe scale is a rating, not an equation.",
+ "A single $ in prose is left alone too.",
+ "That is all.",
+ ],
+ mustNotContain: ["# Pricing", "| :--- |", "- The scale"]),
+ "long-prose-line": Expectation(
+ usedFallback: false,
+ mustContain: ["word emph and more text."],
+ mustNotContain: ["*"]),
+ "nested-lists": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "Build order",
+ "1.\tConfigure the toolchain",
+ "\u{2022}\tInstall Xcode 26",
+ "\u{2022}\tSelect the toolchain",
+ "\u{2022}\txcode-select --switch",
+ "2.\tBuild the package",
+ "1.\tswift build",
+ "2.\tswift build --build-tests",
+ "3.\tRun the focused filters",
+ "\u{2022}\tThree-space marker level one",
+ "\u{2022}\tFour-space nested level two",
+ "\u{2022}\tLevel three",
+ ],
+ // The marker used to come from the outermost list, so a nested
+ // bullet wore its parent's number and nested ordered items
+ // repeated the parent ordinal.
+ mustNotContain: ["###", "* ", "1.\t1.", "1.\tInstall Xcode 26"]),
+ "prose-display-dollars": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "It costs $$$ a lot. Rated $$ on the price scale.",
+ "Bold line above the heading.",
+ "Heading",
+ "The array [1, 2, 3] holds three values",
+ "[optional] flags stay literal",
+ "\u{2022}\tThe rating is not an equation.",
+ "Done.",
+ ],
+ mustNotContain: ["**", "# Heading", "- The rating"]),
+ "prose-fence": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "Here is the fix:",
+ "func apply(_ value: Int) -> Int {",
+ "return value + 1",
+ "Done.",
+ "first line",
+ "second line",
+ "Both fences interrupt the sentence above them.",
+ ],
+ mustNotContain: ["```", "~~~"]),
+ "quote-with-math": Expectation(
+ usedFallback: false,
+ mustContain: ["│\t", "fundamental constants", "Ordinary text after the quote."],
+ mustNotContain: ["> "],
+ attachments: 3),
+ "reference-links": Expectation(
+ usedFallback: false,
+ // The whole render resolves the definitions; the per-block one
+ // cannot, which is recorded in `TranscriptCorpus.perBlockLimitations`.
+ mustContain: ["See the docs and the guide for details."],
+ mustNotContain: ["][", "https://example.com/docs"]),
+ "shell-dollars": Expectation(
+ usedFallback: false,
+ mustContain: ["echo $HOME", "$HOME/$PATH", "$x=$y"],
+ mustNotContain: ["```"]),
+ "table-empty-cells": Expectation(
+ usedFallback: false,
+ // Every position is a cell, blank ones included.
+ mustContain: [
+ "Feature\nBasic\nPro\nPrice\n$20\n\nSSO\n\nyes\nNotes\nshort\n",
+ "The blank cells keep their columns.",
+ ],
+ mustNotContain: ["| --- |", "|"]),
+ "table-in-list": Expectation(
+ usedFallback: true,
+ mustContain: ["| Tier | Cost |", "- The table below sits inside this item:"]),
+ "table-html-bold": Expectation(
+ usedFallback: false,
+ mustContain: [
+ "Comparison",
+ "GCD Queues",
+ "Low-level.\u{2028}Closure based.",
+ "H2O and x2",
+ "ordinary paragraph",
+ ],
+ mustNotContain: ["###", "**", "<br>", "<br/>", "<sub>", "| :--- |"]),
+ "tab-indented-fence": Expectation(
+ usedFallback: false,
+ // A tab is four columns; one column of fence indent comes off it.
+ mustContain: [" tab indented\n space indented"],
+ mustNotContain: ["```", "\t"]),
+ "task-lists": Expectation(
+ usedFallback: false,
+ mustContain: ["Release checklist", "Define data model", "plain item without a checkbox"],
+ mustNotContain: ["####"]),
+ "unclosed-display-math": Expectation(
+ usedFallback: false,
+ mustContain: ["derivative of the loss", "\\frac{\\partial L}{\\partial w}"]),
+ "unclosed-fence": Expectation(
+ usedFallback: true,
+ mustContain: ["```metal", "kernel void reduce"]),
+ ]
+
+ static func attachments(in attributed: NSAttributedString) -> [String] {
+ var sources: [String] = []
+ attributed.enumerateAttribute(
+ .attachment,
+ in: NSRange(location: 0, length: attributed.length),
+ options: []) { value, _, _ in
+ if let attachment = value as? MathAttachment {
+ sources.append(attachment.latexSource)
+ }
+ }
+ return sources
+ }
+
+ @Test func everyFixtureHasAnExpectation() {
+ for fixture in TranscriptCorpus.fixtures {
+ #expect(Self.expectations[fixture] != nil, "missing expectation for \(fixture)")
+ }
+ #expect(Self.expectations.count == TranscriptCorpus.fixtures.count)
+ }
+
+ @Test(arguments: TranscriptCorpus.fixtures)
+ func rendersFixtureAndEmitsFrames(_ fixture: String) throws {
+ let source = try TranscriptCorpus.source(fixture)
+ let expectation = try #require(Self.expectations[fixture])
+ let result = ResponseMarkdownRenderer().render(source)
+ let text = result.attributedString.string
+
+ #expect(result.usedFallback == expectation.usedFallback, "fallback for \(fixture)")
+ if expectation.usedFallback {
+ #expect(text == source, "raw fallback must be byte-exact for \(fixture)")
+ }
+ for needle in expectation.mustContain {
+ #expect(text.contains(needle), "\(fixture) is missing \(needle.debugDescription)")
+ }
+ for needle in expectation.mustNotContain {
+ #expect(!text.contains(needle), "\(fixture) still shows \(needle.debugDescription)")
+ }
+ // Sentinels are the substitution's own bookkeeping and must never
+ // survive into the visible string; a U+FFFC is only legitimate where a
+ // typeset equation replaced one.
+ #expect(!text.unicodeScalars.contains { $0.value == 0xE000 })
+ #expect(!text.unicodeScalars.contains { $0.value == 0xE001 })
+ let attachments = Self.attachments(in: result.attributedString)
+ #expect(attachments.count == expectation.attachments, "attachments for \(fixture)")
+ #expect(text.unicodeScalars.count { $0.value == 0xFFFC } == expectation.attachments)
+
+ // Every destination that reached the text view as a real `.link` is one
+ // this transcript is willing to open.
+ result.attributedString.enumerateAttribute(
+ .link,
+ in: NSRange(location: 0, length: result.attributedString.length),
+ options: []) { value, range, _ in
+ guard value != nil else { return }
+ let url = value as? URL
+ #expect(
+ ["http", "https", "mailto"].contains(url?.scheme?.lowercased() ?? ""),
+ "\(fixture) links to \(String(describing: value)) at \(range)")
+ }
+
+ // `plainText` is the transcript's text projection: every attachment
+ // maps back to the LaTeX it replaced, so no placeholder escapes.
+ let plain = ResponseMarkdownRenderer().plainText(source)
+ #expect(!plain.unicodeScalars.contains { $0.value == 0xFFFC })
+ var expected = text
+ for latex in attachments.reversed() {
+ guard let placeholder = expected.range(of: "\u{FFFC}", options: .backwards) else {
+ Issue.record("attachment count does not match the placeholders")
+ break
+ }
+ expected.replaceSubrange(placeholder, with: latex)
+ }
+ #expect(plain == expected)
+ for latex in attachments {
+ #expect(source.contains(latex), "\(fixture) lost the source of \(latex)")
+ }
+
+ for dark in [false, true] {
+ try TranscriptFrameRenderer.record(
+ result.attributedString,
+ named: "\(fixture).final.\(dark ? "dark" : "light").png",
+ dark: dark)
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptStreamingTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptStreamingTests.swift
new file mode 100644
index 00000000..a7f5ef12
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptStreamingTests.swift
@@ -0,0 +1,132 @@
+import AppKit
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@MainActor
+@Suite struct TranscriptStreamingTests {
+ /// Both streaming paths are measured and framed, so the progressive render
+ /// can be compared against the raw appends it replaces rather than only
+ /// against a threshold.
+ enum Mode: String, CaseIterable, CustomStringConvertible {
+ case progressive
+ case raw
+
+ var description: String { rawValue }
+
+ var environment: [String: String] {
+ ["TURBO_FIELDFARE_PROGRESSIVE_RENDER": self == .raw ? "0" : "1"]
+ }
+ }
+
+ /// 20 tok/s at a 0.1 s tick is two tokens per tick; Gemma 4 averages close
+ /// to four characters per token on English prose. No wall-clock sleeping:
+ /// only the chunk size models the rate.
+ static let charactersPerTick = 8
+
+ /// Fixtures long enough for decile statistics to mean anything. Both are
+ /// the shapes that an O(n^2) re-render would blow up on first.
+ static let timingGated: Set<String> = ["large-code-block", "fifty-equations"]
+
+ struct TickTiming {
+ let headDecileMean: Double
+ let tailDecileMean: Double
+ var ratio: Double { headDecileMean > 0 ? tailDecileMean / headDecileMean : .infinity }
+ }
+
+ static func ticks(_ source: String) -> [String] {
+ var prefixes: [String] = []
+ var index = source.startIndex
+ while index < source.endIndex {
+ let next = source.index(
+ index,
+ offsetBy: charactersPerTick,
+ limitedBy: source.endIndex) ?? source.endIndex
+ index = next
+ prefixes.append(String(source[source.startIndex..<next]))
+ }
+ return prefixes
+ }
+
+ static func seconds(_ duration: Duration) -> Double {
+ Double(duration.components.seconds)
+ + Double(duration.components.attoseconds) * 1e-18
+ }
+
+ static func timing(_ durations: [Duration]) -> TickTiming? {
+ let decile = durations.count / 10
+ guard decile > 0 else { return nil }
+ let head = durations.prefix(decile).map(seconds).reduce(0, +) / Double(decile)
+ let tail = durations.suffix(decile).map(seconds).reduce(0, +) / Double(decile)
+ return TickTiming(headDecileMean: head, tailDecileMean: tail)
+ }
+
+ @Test(arguments: TranscriptCorpus.fixtures, Mode.allCases)
+ func streamsFixtureWithoutSuperlinearTickCost(_ fixture: String, _ mode: Mode) throws {
+ let source = try TranscriptCorpus.source(fixture)
+ let prefixes = Self.ticks(source)
+ try #require(!prefixes.isEmpty)
+
+ var milestones: [Int: String] = [:]
+ for (label, percent) in [("p10", 10), ("p50", 50), ("p90", 90)] {
+ milestones[max(0, prefixes.count * percent / 100 - 1)] = label
+ }
+ if let index = prefixes.firstIndex(where: { $0.contains("$$") }) {
+ milestones[index] = "first-display-math"
+ }
+ if let index = prefixes.firstIndex(where: { $0.contains("```") }) {
+ milestones[index] = "first-fence"
+ }
+
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController(
+ environment: mode.environment)
+ let clock = ContinuousClock()
+ var durations: [Duration] = []
+ durations.reserveCapacity(prefixes.count)
+
+ for (index, prefix) in prefixes.enumerated() {
+ let elapsed = clock.measure {
+ controller.synchronize(
+ storage: storage,
+ prompt: "Explain this",
+ response: prefix,
+ isTerminal: false)
+ }
+ durations.append(elapsed)
+ if let label = milestones[index] {
+ try TranscriptFrameRenderer.record(
+ storage,
+ named: "\(fixture).stream-\(label).\(mode).light.png",
+ dark: false)
+ }
+ }
+
+ let finalize = clock.measure {
+ controller.synchronize(
+ storage: storage,
+ prompt: "Explain this",
+ response: source,
+ isTerminal: true)
+ }
+ #expect(controller.response == source)
+ #expect(controller.isFinalized)
+
+ guard let timing = Self.timing(durations) else {
+ #expect(prefixes.count < 10)
+ return
+ }
+ print("""
+ STREAM \(fixture) \(mode): ticks=\(prefixes.count) \
+ head=\(String(format: "%.1f", timing.headDecileMean * 1e6))us \
+ tail=\(String(format: "%.1f", timing.tailDecileMean * 1e6))us \
+ ratio=\(String(format: "%.2f", timing.ratio)) \
+ finalize=\(String(format: "%.1f", Self.seconds(finalize) * 1e3))ms
+ """)
+ if Self.timingGated.contains(fixture) {
+ #expect(
+ timing.ratio < 3,
+ "\(fixture) \(mode) tail decile is \(timing.ratio)x the head decile")
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptTextViewTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptTextViewTests.swift
new file mode 100644
index 00000000..5cf0c1e6
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptTextViewTests.swift
@@ -0,0 +1,203 @@
+import AppKit
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@MainActor
+@Suite struct TranscriptTextViewTests {
+ /// Never the general pasteboard: these tests must not touch what the
+ /// person running them has copied.
+ static func pasteboard(_ name: String) -> NSPasteboard {
+ let board = NSPasteboard(name: NSPasteboard.Name("test-transcript-\(name)"))
+ board.clearContents()
+ return board
+ }
+
+ static func view(_ attributed: NSAttributedString) -> TranscriptTextView {
+ let view = TranscriptTextView()
+ view.textStorage?.setAttributedString(attributed)
+ return view
+ }
+
+ static let answer = "The relation is $E = mc^2$ and it holds."
+
+ // MARK: - The shared projection
+
+ @Test func theProjectionPutsTheLatexBackWhereTheAttachmentIs() {
+ let renderer = ResponseMarkdownRenderer()
+ let rendered = renderer.render(Self.answer).attributedString
+ let projected = TranscriptPlainText.string(of: rendered)
+
+ #expect(rendered.string.contains("\u{FFFC}"))
+ #expect(projected == "The relation is $E = mc^2$ and it holds.")
+ // Copy actions and `plainText` are one code path, so they cannot drift.
+ #expect(projected == renderer.plainText(Self.answer))
+ }
+
+ // MARK: - Selection copy
+
+ @Test func copyingASelectionWritesTheLatexRatherThanThePlaceholder() throws {
+ let rendered = ResponseMarkdownRenderer().render(Self.answer).attributedString
+ let view = Self.view(rendered)
+ view.setSelectedRange(NSRange(location: 0, length: rendered.length))
+
+ let board = Self.pasteboard("whole")
+ view.copySelection(to: board)
+
+ let copied = board.string(forType: .string)
+ #expect(copied == "The relation is $E = mc^2$ and it holds.")
+ #expect(copied?.contains("\u{FFFC}") == false)
+ // The rich flavours carry the LaTeX too. RTF cannot hold an attachment
+ // at all, so it used to lose every equation; RTFD held one rasterised
+ // TIFF each.
+ for type in [NSPasteboard.PasteboardType.rtf, .rtfd] {
+ let data = try #require(board.data(forType: type))
+ let decoded = try #require(NSAttributedString(
+ rtfd: data, documentAttributes: nil)
+ ?? NSAttributedString(rtf: data, documentAttributes: nil))
+ #expect(decoded.string.contains("$E = mc^2$"), "\(type.rawValue)")
+ #expect(!decoded.string.contains("\u{FFFC}"), "\(type.rawValue)")
+ }
+ }
+
+ /// Cmd-C on the fifty-equation answer wrote a 12.3 MB RTFD of fifty TIFFs
+ /// and logged a hundred `CGImageDestinationFinalize` lines, because AppKit
+ /// rasterises an attachment that has no file wrapper.
+ @Test func copyingAnAnswerFullOfEquationsWritesTextNotImages() throws {
+ let source = try TranscriptCorpus.source("fifty-equations")
+ let rendered = ResponseMarkdownRenderer().render(source).attributedString
+ let attachments = TranscriptRenderCorpusTests.attachments(in: rendered)
+ #expect(attachments.count == 50)
+
+ let view = Self.view(rendered)
+ view.setSelectedRange(NSRange(location: 0, length: rendered.length))
+ let board = Self.pasteboard("fifty")
+ view.copySelection(to: board)
+
+ let rtfd = try #require(board.data(forType: .rtfd))
+ #expect(rtfd.count < 200_000, "RTFD is \(rtfd.count) bytes")
+ let text = try #require(String(data: rtfd, encoding: .isoLatin1))
+ #expect(!text.contains("NeXTGraphic"))
+ // Nothing was serialised as an attachment, which is what stopped AppKit
+ // asking each one for a file wrapper and rasterising it. Reading
+ // `fileWrapper` back here would create the wrapper this is about.
+ let decoded = try #require(NSAttributedString(rtfd: rtfd, documentAttributes: nil))
+ var kept = 0
+ decoded.enumerateAttribute(
+ .attachment,
+ in: NSRange(location: 0, length: decoded.length),
+ options: []) { value, _, _ in
+ if value != nil { kept += 1 }
+ }
+ #expect(kept == 0)
+ #expect(decoded.string.contains("\\frac"))
+ }
+
+ /// A drag and a Services provider go out through `writeSelection` too, so
+ /// they cannot drift from what Cmd-C writes.
+ @Test func dragAndServicesWriteTheSameBytesAsCopy() throws {
+ let rendered = ResponseMarkdownRenderer().render(Self.answer).attributedString
+ let view = Self.view(rendered)
+ view.setSelectedRange(NSRange(location: 0, length: rendered.length))
+
+ let copied = Self.pasteboard("copy-route")
+ view.copySelection(to: copied)
+
+ let dragged = Self.pasteboard("drag-route")
+ let types = view.writablePasteboardTypes
+ #expect(types == [.rtfd, .rtf, .string])
+ dragged.declareTypes(types, owner: nil)
+ #expect(view.writeSelection(to: dragged, types: types))
+
+ let service = Self.pasteboard("service-route")
+ service.declareTypes([.string], owner: nil)
+ #expect(view.writeSelection(to: service, type: .string))
+
+ for type in types {
+ #expect(copied.data(forType: type) == dragged.data(forType: type),
+ "\(type.rawValue)")
+ }
+ #expect(service.string(forType: .string) == copied.string(forType: .string))
+ }
+
+ /// An image in the prompt strip is not a math attachment and still travels
+ /// in the rich flavour the way it did before.
+ @Test func aPromptImageStillTravelsInTheRichFlavour() throws {
+ let image = NSImage(size: NSSize(width: 8, height: 8))
+ image.lockFocus()
+ NSColor.red.setFill()
+ NSBezierPath.fill(NSRect(x: 0, y: 0, width: 8, height: 8))
+ image.unlockFocus()
+ let attachment = NSTextAttachment()
+ attachment.image = image
+ let document = NSMutableAttributedString(attachment: attachment)
+ document.append(ResponseMarkdownRenderer().render(Self.answer).attributedString)
+
+ let view = Self.view(document)
+ view.setSelectedRange(NSRange(location: 0, length: document.length))
+ let board = Self.pasteboard("prompt-image")
+ view.copySelection(to: board)
+
+ let rtfd = try #require(board.data(forType: .rtfd))
+ let decoded = try #require(NSAttributedString(rtfd: rtfd, documentAttributes: nil))
+ var kept = 0
+ decoded.enumerateAttribute(
+ .attachment,
+ in: NSRange(location: 0, length: decoded.length),
+ options: []) { value, _, _ in
+ if value != nil { kept += 1 }
+ }
+ #expect(kept == 1)
+ #expect(decoded.string.contains("$E = mc^2$"))
+ }
+
+ /// Nothing archives the transcript, so the attachment refuses to be
+ /// decoded rather than coming back without the source it exists to carry.
+ @Test func aMathAttachmentRefusesToBeDecoded() throws {
+ let attachment = MathAttachment(latexSource: "E = mc^2")
+ let archived = try NSKeyedArchiver.archivedData(
+ withRootObject: attachment, requiringSecureCoding: false)
+ let decoded = try? NSKeyedUnarchiver.unarchivedObject(
+ ofClass: MathAttachment.self, from: archived)
+ #expect(decoded == nil)
+ }
+
+ @Test func copyingPartOfALineKeepsOnlyThatPart() {
+ let rendered = ResponseMarkdownRenderer().render(Self.answer).attributedString
+ let view = Self.view(rendered)
+ let equation = (rendered.string as NSString).range(of: "\u{FFFC}")
+ view.setSelectedRange(NSRange(location: equation.location, length: equation.length + 4))
+
+ let board = Self.pasteboard("partial")
+ view.copySelection(to: board)
+
+ #expect(board.string(forType: .string) == "$E = mc^2$ and")
+ }
+
+ @Test func anEmptySelectionWritesNothing() {
+ let rendered = ResponseMarkdownRenderer().render(Self.answer).attributedString
+ let view = Self.view(rendered)
+ view.setSelectedRange(NSRange(location: 3, length: 0))
+
+ let board = Self.pasteboard("empty")
+ board.declareTypes([.string], owner: nil)
+ board.setString("untouched", forType: .string)
+ view.copySelection(to: board)
+
+ #expect(board.string(forType: .string) == "untouched")
+ }
+
+ /// Text with no maths in it must come back exactly as it reads, so the
+ /// override cannot become a second, divergent way of producing plain text.
+ @Test func copyingPlainProseIsUnchangedByTheOverride() {
+ let rendered = ResponseMarkdownRenderer()
+ .render("First line.\n\nSecond line.").attributedString
+ let view = Self.view(rendered)
+ view.setSelectedRange(NSRange(location: 0, length: rendered.length))
+
+ let board = Self.pasteboard("prose")
+ view.copySelection(to: board)
+
+ #expect(board.string(forType: .string) == rendered.string)
+ }
+}
diff --git a/docs/assets/turbofieldfare-app.webp b/docs/assets/turbofieldfare-app.webp
index 42ed0083..fc9c38e1 100644
Binary files a/docs/assets/turbofieldfare-app.webp and b/docs/assets/turbofieldfare-app.webp differ