Skip to content

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

Add code-block copying and chat fixes for 0.9.4 (#195)

Andrey Mikhaylovd994a65da908
diff --git a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
index 5d687db9..2e3d6cea 100644
--- a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
+++ b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
@@ -332,14 +332,16 @@ public struct GFTokenizer: @unchecked Sendable {
public func applyChatTemplate(_ messages: [Message]) throws -> String {
var s = Self.bosMark
- for (index, message) in messages.enumerated() {
+ var sawConversation = false
+ for message in messages {
guard let rawContent = message.content else {
throw GFTokenizerError.invalidChatTemplate("text-only messages require content")
}
let content = rawContent.trimmingCharacters(in: .whitespacesAndNewlines)
- if message.role == .system && index != 0 {
- throw GFTokenizerError.invalidChatTemplate("system message must be first")
+ if message.role == .system && sawConversation {
+ throw GFTokenizerError.invalidChatTemplate("system messages must precede conversation")
}
+ if message.role != .system { sawConversation = true }
let role = message.role == .assistant ? "model" : message.role.rawValue
s += Self.turnOpen + role + "\n" + content + Self.turnClose + "\n"
}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
index 7fab77a5..f22b2f04 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.9.3"
+ public static let fallbackShortVersion = "0.9.4"
private static let licenseURL = URL(
string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift b/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift
index 2d6b5287..a4c7751e 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift
@@ -100,6 +100,7 @@ public enum AccessibilityID: String, CaseIterable, Sendable {
/// Identifiers minted per item carry one of these prefixes, so a case can
/// name the family and the driver can match one member exactly.
public enum Prefix: String, CaseIterable, Sendable {
+ case transcriptCopyCode = "transcript.copyCode."
case historyRow = "history.row."
case historyRowMenu = "history.row.menu."
case composerRemove = "composer.remove."
diff --git a/Sources/TurboFieldfareApp/MacPresentation/ContainerPrefix.swift b/Sources/TurboFieldfareApp/MacPresentation/ContainerPrefix.swift
index 78e7511e..4a58e5dc 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/ContainerPrefix.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/ContainerPrefix.swift
@@ -6,6 +6,12 @@ import Foundation
/// answer: a fence at the column is the item's own listing, one before it ends
/// the list.
enum ContainerPrefix {
+ static func markdownLines(_ source: String) -> [Substring] {
+ // CommonMark line endings exclude Unicode separators such as U+2028,
+ // which remain literal characters in code even though isNewline is true.
+ source.split(omittingEmptySubsequences: false) { $0 == "\n" || $0 == "\r" || $0 == "\r\n" }
+ }
+
struct ListItem: Equatable {
/// Columns of indentation before the marker.
let markerIndent: Int
@@ -111,21 +117,27 @@ enum ContainerPrefix {
/// 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) {
+ static func strippingQuoteMarkers(_ line: Substring, limit: Int = .max) -> (depth: Int, rest: Substring) {
var rest = line
var depth = 0
- while true {
+ var column = 0
+ while depth < limit {
var probe = rest
- var indent = 0
- while let first = probe.first, first == " " || first == "\t", indent < 3 {
- indent += first == "\t" ? 4 : 1
+ var probeColumn = column
+ while let first = probe.first, first == " " || first == "\t", probeColumn - column < 3 {
+ probeColumn += first == "\t" ? 4 - probeColumn % 4 : 1
probe = probe.dropFirst()
}
- guard probe.first == ">" else { return (depth, rest) }
+ guard probeColumn - column <= 3, probe.first == ">" else { return (depth, rest) }
+ column = probeColumn + 1
probe = probe.dropFirst()
- if probe.first == " " { probe = probe.dropFirst() }
+ if probe.first == " " {
+ probe = probe.dropFirst()
+ column += 1
+ }
depth += 1
rest = probe
}
+ return (depth, rest)
}
}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
index d25372d7..208798d8 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
@@ -269,7 +269,10 @@ public final class InstructionTranscriptDocumentController {
|| displaysPrefillPlaceholder != self.showsPrefillPlaceholder
var appendedDelta: String?
if !needsRebuild, response.utf8.count > self.response.utf8.count {
- appendedDelta = Self.appendedSuffix(of: response, after: self.response)
+ // The progressive scanner consumes UTF-8 offsets itself. Requiring
+ // a Character boundary here rebuilt a fence when CR and LF arrived
+ // separately, losing its identity despite an exact byte append.
+ appendedDelta = progressiveRendering ? "" : Self.appendedSuffix(of: response, after: self.response)
needsRebuild = appendedDelta == nil
}
@@ -531,6 +534,8 @@ public final class InstructionTranscriptDocumentController {
/// UTF-8 offset of the open block the drawn tail was made from.
var tailStart: Int?
var fence: FenceTail?
+ var codeStyle: (bodyStart: Int, attributes: [NSAttributedString.Key: Any])?
+ var nestedCodes: (start: Int, blocks: [TranscriptCodeBlock])?
/// 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.
@@ -542,6 +547,8 @@ public final class InstructionTranscriptDocumentController {
prefixLength = 0
tailStart = nil
fence = nil
+ codeStyle = nil
+ nestedCodes = nil
}
}
@@ -819,6 +826,45 @@ public final class InstructionTranscriptDocumentController {
return renderer.blockSeparator(trailingNewlines: trailingNewlines)
}
+ private func codeAttributes(for fence: ResponseBlockSplitter.Fence) -> [NSAttributedString.Key: Any] {
+ if let style = progressive.codeStyle, style.bodyStart == fence.bodyStart { return style.attributes }
+ let attributes = renderer.streamingCodeAttributes()
+ progressive.codeStyle = (fence.bodyStart, attributes)
+ return attributes
+ }
+
+ private func preservingCodeIdentity(_ rendered: NSAttributedString, blockStart: Int) -> NSAttributedString {
+ // Lists and quotes are reparsed as their tail grows. Reuse identities
+ // by code order within that same block so a focused button survives.
+ let previous = progressive.nestedCodes?.start == blockStart ? progressive.nestedCodes?.blocks ?? [] : []
+ var blocks: [TranscriptCodeBlock] = []
+ var replacement: NSMutableAttributedString?
+ rendered.enumerateAttribute(.transcriptCodeBlock, in: NSRange(location: 0, length: rendered.length)) { value, range, _ in
+ guard let fresh = value as? TranscriptCodeBlock else { return }
+ let stable = previous[safe: blocks.count] ?? fresh
+ stable.syntheticTerminator = fresh.syntheticTerminator
+ blocks.append(stable)
+ if stable !== fresh {
+ if replacement == nil { replacement = NSMutableAttributedString(attributedString: rendered) }
+ replacement?.addAttribute(.transcriptCodeBlock, value: stable, range: range)
+ }
+ }
+ progressive.nestedCodes = (blockStart, blocks)
+ return replacement ?? rendered
+ }
+
+ private func blockSource(_ block: ResponseBlockSplitter.Block, in response: String) -> String {
+ var text = ResponseBlockSplitter.text(block.utf8Range, in: response)
+ // Splitter ranges omit line terminators. Markdown needs that last real
+ // newline to distinguish indented code from a synthetic paragraph end.
+ guard block.kind == .indentedCode || block.kind == .list || block.kind == .quote else { return text }
+ let suffix = ResponseBlockSplitter.text(block.end..<min(block.end + 2, response.utf8.count), in: response)
+ if suffix.hasPrefix("\r\n") { text += "\r\n" }
+ else if suffix.hasPrefix("\n") { text += "\n" }
+ else if suffix.hasPrefix("\r") { text += "\r" }
+ return text
+ }
+
private func renderedBlock(
_ block: ResponseBlockSplitter.Block,
of response: String
@@ -828,16 +874,23 @@ public final class InstructionTranscriptDocumentController {
// 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
+ return code(fence, of: response, attributes: codeAttributes(for: fence)).text
}
- let text = ResponseBlockSplitter.text(block.utf8Range, in: response)
+ let text = blockSource(block, 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
+ let rendered = preservingCodeIdentity(
+ renderer.render(text, typesetsMath: true).attributedString, blockStart: block.start)
// 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
+ // Code runs carry mutable occurrence identities and TextKit cells.
+ // Reusing them across turns or resets resurrects obsolete controls.
+ var containsCode = false
+ rendered.enumerateAttribute(.transcriptCodeBlock, in: NSRange(location: 0, length: rendered.length)) { value, _, stop in
+ if value != nil { containsCode = true; stop.pointee = true }
+ }
+ if !containsCode { progressive.cache[key] = rendered }
return rendered
}
@@ -853,14 +906,19 @@ public final class InstructionTranscriptDocumentController {
let drawn = code(
fence,
of: response,
- attributes: renderer.streamingCodeAttributes())
+ attributes: codeAttributes(for: fence))
progressive.fence = drawn.state
return drawn.text
}
progressive.fence = nil
- let text = ResponseBlockSplitter.text(block.utf8Range, in: response)
+ let text = blockSource(block, in: response)
let closed = TailAutoClose.close(text, typesetsMath: false)
- return renderer.render(closed, typesetsMath: false).attributedString
+ let rendered = renderer.render(closed, typesetsMath: false).attributedString
+ if !TranscriptCodeBlock.endsWithLineBreak(text), closed.hasPrefix(text + "\n"), rendered.length > 0,
+ let block = rendered.attribute(.transcriptCodeBlock, at: rendered.length - 1, effectiveRange: nil) as? TranscriptCodeBlock {
+ block.syntheticTerminator = true
+ }
+ return preservingCodeIdentity(rendered, blockStart: block.start)
}
private func code(
@@ -876,6 +934,7 @@ public final class InstructionTranscriptDocumentController {
// the container closes mid-line.
let synthetic = !filter.endsWithNewline
if synthetic { body.append("\n") }
+ (attributes[.transcriptCodeBlock] as? TranscriptCodeBlock)?.syntheticTerminator = synthetic
return (
NSAttributedString(string: body, attributes: attributes),
FenceTail(
@@ -921,6 +980,7 @@ public final class InstructionTranscriptDocumentController {
length: drawn.synthetic ? 1 : 0)
drawn.bodyEnd = fence.bodyEnd
drawn.synthetic = synthetic
+ (drawn.attributes[.transcriptCodeBlock] as? TranscriptCodeBlock)?.syntheticTerminator = synthetic
progressive.fence = drawn
guard !delta.isEmpty || removal.length > 0 else {
return ProgressiveUpdate(mutation: .none)
diff --git a/Sources/TurboFieldfareApp/MacPresentation/MathSpanDetector.swift b/Sources/TurboFieldfareApp/MacPresentation/MathSpanDetector.swift
index bbf635fb..24de67cf 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/MathSpanDetector.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/MathSpanDetector.swift
@@ -670,6 +670,13 @@ enum MathSpanDetector {
return masked
}
+ static func endsInCodeBlock(_ source: String) -> Bool {
+ let chars = scanUnits(source)
+ var masked = [Bool](repeating: false, count: chars.count)
+ maskBlocks(chars, into: &masked)
+ return masked.last == true
+ }
+
private struct Line {
let start: Int
/// Index just past the last content character, excluding the newline.
diff --git a/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift b/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift
index 3da45992..b78c62b2 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift
@@ -77,6 +77,7 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {
let link: URL?
let imageURL: URL?
let block: Block
+ var syntheticCodeTerminator = false
}
private let typography: ConversationTypography
@@ -114,7 +115,8 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {
markdown: presentationSource,
options: .init(
interpretedSyntax: .full,
- failurePolicy: .returnPartiallyParsedIfPossible))
+ failurePolicy: .returnPartiallyParsedIfPossible,
+ appliesSourcePositionAttributes: true))
guard !containsUnsupportedBlock(in: parsed) else { return fallback(source) }
let items = Self.completingTables(parsed.runs.map { run in
@@ -128,7 +130,9 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {
inlineIntent: run.inlinePresentationIntent,
link: Self.openable(run.link),
imageURL: Self.openable(run.imageURL),
- block: block(for: run.presentationIntent))
+ block: block(for: run.presentationIntent),
+ syntheticCodeTerminator: TranscriptCodeBlock.hasSyntheticTerminator(
+ position: run.markdownSourcePosition, source: presentationSource))
})
let output = NSMutableAttributedString()
@@ -568,6 +572,7 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {
appendCode(
items.map(\.text).joined(),
block: block,
+ syntheticTerminator: items.last?.syntheticCodeTerminator ?? false,
to: output,
decoration: decoration)
return
@@ -766,12 +771,16 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {
private func appendCode(
_ text: String,
block: Block,
+ syntheticTerminator: Bool,
to output: NSMutableAttributedString,
decoration: BlockDecoration
) {
var body = text
if body.hasSuffix("\n") { body.removeLast() }
- let attributes = codeAttributes(cell: decoration.codeCell(for: block.identity))
+ var attributes = codeAttributes(cell: decoration.codeCell(for: block.identity))
+ let codeBlock = TranscriptCodeBlock()
+ codeBlock.syntheticTerminator = syntheticTerminator || !text.hasSuffix("\n")
+ attributes[.transcriptCodeBlock] = codeBlock
for line in body.components(separatedBy: "\n") {
output.append(NSAttributedString(string: line + "\n", attributes: attributes))
}
@@ -783,7 +792,9 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {
/// 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(typography: typography))
+ var attributes = codeAttributes(cell: BlockDecoration.codeCell(typography: typography))
+ attributes[.transcriptCodeBlock] = TranscriptCodeBlock()
+ return attributes
}
private func codeAttributes(cell: NSTextTableBlock) -> [NSAttributedString.Key: Any] {
@@ -1125,7 +1136,9 @@ private final class BlockDecoration {
static func codeCell(typography: ConversationTypography) -> NSTextTableBlock {
let table = NSTextTable()
table.numberOfColumns = 1
- table.collapsesBorders = true
+ // A single cell has no shared borders. Collapsing shifts its right
+ // stroke beyond the text container, where NSTextView clips it away.
+ table.collapsesBorders = false
let cell = NSTextTableBlock(
table: table,
startingRow: 0,
@@ -1134,6 +1147,7 @@ private final class BlockDecoration {
columnSpan: 1)
cell.setContentWidth(100, type: .percentageValueType)
cell.setWidth(typography.scaled(8), type: .absoluteValueType, for: .padding)
+ cell.setWidth(typography.scaled(TranscriptCodeBlock.headerPadding), type: .absoluteValueType, for: .padding, edge: .minY)
cell.setWidth(1, type: .absoluteValueType, for: .border)
cell.setBorderColor(.separatorColor)
cell.backgroundColor = .quaternarySystemFill
diff --git a/Sources/TurboFieldfareApp/MacPresentation/TailAutoClose.swift b/Sources/TurboFieldfareApp/MacPresentation/TailAutoClose.swift
index 62cb4761..e9e9a894 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/TailAutoClose.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/TailAutoClose.swift
@@ -25,11 +25,12 @@ enum TailAutoClose {
guard !tail.isEmpty else { return tail }
if let fence = unclosedFence(tail) {
var closed = tail
- if !closed.hasSuffix("\n") { closed.append("\n") }
+ if !TranscriptCodeBlock.endsWithLineBreak(closed) { closed.append("\n") }
closed.append(fence.closerPrefix)
closed.append(String(repeating: fence.run.character, count: fence.run.length))
return closed
}
+ guard !endsInIndentedCode(tail) else { return tail }
var text = strippingIncompleteTag(tail)
text = flatteningIncompleteLink(text)
text = balancingInlineMarkers(text, typesetsMath: typesetsMath)
@@ -38,10 +39,32 @@ enum TailAutoClose {
// MARK: - Fences
+ static func endsWithClosedFence(_ text: String) -> Bool { fenceState(text).closedAtEnd }
+
+ private static func endsInIndentedCode(_ text: String) -> Bool {
+ let lines = ContainerPrefix.markdownLines(text)
+ guard let last = lines.last(where: { !$0.isEmpty }) else { return false }
+ let container = ContainerPrefix.strippingQuoteMarkers(last)
+ let tail = container.rest
+ let indentation = tail.prefix { $0 == " " || $0 == "\t" }.reduce(0) { $0 + ($1 == "\t" ? 4 : 1) }
+ guard indentation >= 4 else { return false }
+ // Classify within the final quote's own context. Parent lists cannot
+ // set its indentation; returning from a child retains the parent list.
+ var unquoted: [Substring] = []
+ for line in lines {
+ let quote = ContainerPrefix.strippingQuoteMarkers(line)
+ if quote.depth < container.depth { unquoted.removeAll(keepingCapacity: true) }
+ else if quote.depth == container.depth { unquoted.append(quote.rest) }
+ else if unquoted.last?.isEmpty == false { unquoted.append("") }
+ }
+ return MathSpanDetector.endsInCodeBlock(unquoted.joined(separator: "\n"))
+ }
+
private struct OpenFence {
let run: FenceLine.Run
/// Content column of the item the fence was opened in.
let containerIndent: Int
+ let quoteDepth: 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.
@@ -51,29 +74,57 @@ enum TailAutoClose {
/// 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? {
+ fenceState(text).open
+ }
+
+ private static func fenceState(_ text: String) -> (open: OpenFence?, closedAtEnd: Bool) {
var open: OpenFence?
- var column = 0
- for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
- let quote = ContainerPrefix.strippingQuoteMarkers(line)
+ var columns: [Int: Int] = [:]
+ var previousDepth = 0
+ var closedAtEnd = false
+ var lines = ContainerPrefix.markdownLines(text)
+ // A terminal delimiter has not started a new container-less line yet.
+ if lines.last?.isEmpty == true { lines.removeLast() }
+ for line in lines {
+ closedAtEnd = false
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
+ // Additional '>' characters inside a fence are code, not a
+ // deeper quote. Leaving its actual quote ends that container.
+ let quote = ContainerPrefix.strippingQuoteMarkers(line, limit: current.quoteDepth)
+ if quote.depth == current.quoteDepth {
+ if let run = FenceLine.run(quote.rest, containerIndent: current.containerIndent),
+ run.closes(marker: current.run.marker, length: current.run.length) {
+ open = nil
+ closedAtEnd = true
+ }
+ continue
}
- continue
+ open = nil
}
+ let quote = ContainerPrefix.strippingQuoteMarkers(line)
+ if quote.depth < previousDepth { columns = columns.filter { $0.key <= quote.depth } }
+ else if quote.depth > previousDepth { columns[quote.depth] = 0 }
+ previousDepth = quote.depth
+ var column = columns[quote.depth] ?? 0
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 }
+ var candidate = FenceLine.run(quote.rest, containerIndent: column)
+ if candidate == nil, column > 0, let dedented = FenceLine.run(quote.rest) {
+ column = 0
+ candidate = dedented
+ }
+ columns[quote.depth] = column
+ guard let run = candidate else { continue }
open = OpenFence(
run: run,
containerIndent: column,
+ quoteDepth: quote.depth,
closerPrefix: String(repeating: "> ", count: quote.depth)
+ String(repeating: " ", count: run.indent))
}
- return open
+ return (open, closedAtEnd)
}
// MARK: - Trailing fragments
diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptCodeBlock.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptCodeBlock.swift
new file mode 100644
index 00000000..8c36521f
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptCodeBlock.swift
@@ -0,0 +1,48 @@
+import AppKit
+
+extension NSAttributedString.Key {
+ static let transcriptCodeBlock = NSAttributedString.Key("TurboFieldfare.transcriptCodeBlock")
+}
+
+/// Shared by a block's runs for its entire streamed lifetime. The text stays
+/// in NSTextStorage; copying allocates only the clicked block's current body.
+final class TranscriptCodeBlock: NSObject {
+ static let headerPadding: CGFloat = 34
+ let id = UUID()
+ var syntheticTerminator = false
+
+ static func endsWithLineBreak(_ text: String) -> Bool {
+ text.utf8.last == 10 || text.utf8.last == 13
+ }
+
+ static func body(at index: Int, in text: NSAttributedString, matching block: TranscriptCodeBlock) -> String? {
+ guard index >= 0, index < text.length else { return nil }
+ var range = NSRange()
+ guard let current = text.attribute(.transcriptCodeBlock, at: index,
+ longestEffectiveRange: &range,
+ in: NSRange(location: 0, length: text.length)) as? TranscriptCodeBlock,
+ current === block else { return nil }
+ var body = TranscriptPlainText.string(of: text.attributedSubstring(from: range))
+ if block.syntheticTerminator, body.hasSuffix("\n") { body.removeLast() }
+ return body.isEmpty ? nil : body
+ }
+
+ /// Foundation terminates code paragraphs even when the source body does
+ /// not. Its source ranges can extend through blank container-only lines.
+ static func hasSyntheticTerminator(position: AttributedString.MarkdownSourcePosition?, source: String) -> Bool {
+ guard let position, let range = Range(position, in: source), range.upperBound == source.endIndex,
+ !endsWithLineBreak(source) else { return false }
+ let raw = source[range]
+ if raw.hasPrefix("```") || raw.hasPrefix("~~~") {
+ return !TailAutoClose.endsWithClosedFence(source)
+ }
+ let lines = ContainerPrefix.markdownLines(String(raw))
+ if lines.count > 1, let last = lines.last,
+ ContainerPrefix.strippingQuoteMarkers(last).rest.allSatisfy({ $0 == " " || $0 == "\t" }) {
+ // Indented code drops trailing blank container lines. Their
+ // preceding line break belongs to the final code-content line.
+ return false
+ }
+ return true
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift
index 5b1d82b6..5f5fdea2 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift
@@ -64,6 +64,163 @@ public enum TranscriptPlainText {
/// 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 {
+ private(set) var codeCopyButtons: [UUID: TranscriptCodeCopyButton] = [:]
+ private var codeRefreshScheduled = false
+ private weak var observedCodeStorage: NSTextStorage?
+ private weak var observedCodeClip: NSClipView?
+ var writeCodeToPasteboard: (String) -> Bool = { text in
+ let pasteboard = NSPasteboard.general
+ pasteboard.clearContents()
+ return pasteboard.setString(text, forType: .string)
+ }
+
+ public override func viewDidMoveToSuperview() {
+ super.viewDidMoveToSuperview()
+ observeCodeLayout()
+ }
+
+ public override func viewDidMoveToWindow() {
+ super.viewDidMoveToWindow()
+ observeCodeLayout()
+ }
+
+ public override func setFrameSize(_ newSize: NSSize) {
+ let changed = frame.size != newSize
+ super.setFrameSize(newSize)
+ if changed { scheduleCodeCopyRefresh() }
+ }
+
+ private func observeCodeLayout() {
+ let center = NotificationCenter.default
+ guard superview != nil else {
+ center.removeObserver(self, name: NSTextStorage.didProcessEditingNotification, object: observedCodeStorage)
+ center.removeObserver(self, name: NSView.boundsDidChangeNotification, object: observedCodeClip)
+ observedCodeStorage = nil
+ observedCodeClip = nil
+ for button in codeCopyButtons.values { button.removeFromSuperview() }
+ codeCopyButtons.removeAll()
+ return
+ }
+ if observedCodeStorage !== textStorage {
+ if let old = observedCodeStorage { center.removeObserver(self, name: NSTextStorage.didProcessEditingNotification, object: old) }
+ observedCodeStorage = textStorage
+ if let storage = textStorage {
+ center.addObserver(self, selector: #selector(codeLayoutChanged(_:)),
+ name: NSTextStorage.didProcessEditingNotification, object: storage)
+ }
+ }
+ let clip = enclosingScrollView?.contentView
+ if observedCodeClip !== clip {
+ if let old = observedCodeClip { center.removeObserver(self, name: NSView.boundsDidChangeNotification, object: old) }
+ observedCodeClip = clip
+ clip?.postsBoundsChangedNotifications = true
+ if let clip {
+ center.addObserver(self, selector: #selector(codeLayoutChanged(_:)),
+ name: NSView.boundsDidChangeNotification, object: clip)
+ }
+ }
+ scheduleCodeCopyRefresh()
+ }
+
+ @objc private func codeLayoutChanged(_: Notification) {
+ scheduleCodeCopyRefresh()
+ }
+
+ private func scheduleCodeCopyRefresh() {
+ guard !codeRefreshScheduled else { return }
+ codeRefreshScheduled = true
+ // didProcessEditing precedes layout-manager invalidation. Waiting until
+ // the next main-queue turn also coalesces edit, resize and scroll events.
+ DispatchQueue.main.async { [weak self] in
+ guard let self else { return }
+ self.codeRefreshScheduled = false
+ self.refreshCodeCopyButtons()
+ }
+ }
+
+ func refreshCodeCopyButtons() {
+ guard superview != nil, let storage = textStorage, let layout = layoutManager, let container = textContainer else { return }
+ let origin = textContainerOrigin
+ let viewport = visibleRect
+ var containerRect = viewport.offsetBy(dx: -origin.x, dy: -origin.y)
+ // A code header precedes its first glyph. Look ahead by the largest
+ // supported header plus one text line, then clip actual button frames.
+ containerRect.size.height += ConversationTypography(.largest).scaled(TranscriptCodeBlock.headerPadding + NSFont.systemFontSize)
+ let glyphs = layout.glyphRange(forBoundingRect: containerRect, in: container)
+ let visible = layout.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil)
+ var retained = Set<UUID>()
+ if storage.length > 0, visible.length > 0 {
+ storage.enumerateAttribute(.transcriptCodeBlock, in: NSIntersectionRange(visible, NSRange(location: 0, length: storage.length))) { value, range, _ in
+ guard let block = value as? TranscriptCodeBlock, !retained.contains(block.id),
+ let style = storage.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle,
+ let cell = style.textBlocks.first as? NSTextTableBlock else { return }
+ var blockRange = NSRange()
+ _ = storage.attribute(.transcriptCodeBlock, at: range.location, longestEffectiveRange: &blockRange,
+ in: NSRange(location: 0, length: storage.length))
+ if block.syntheticTerminator, blockRange.length == 1,
+ (storage.string as NSString).character(at: blockRange.location) == 10 { return }
+ let runGlyphs = layout.glyphRange(forCharacterRange: blockRange, actualCharacterRange: nil)
+ let rect = layout.boundsRect(for: cell, glyphRange: runGlyphs).offsetBy(dx: origin.x, dy: origin.y)
+ guard rect.width > 0, rect.height > 0 else { return }
+ let font = storage.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont
+ let scale = (font?.pointSize ?? NSFont.systemFontSize) / (NSFont.systemFontSize - 0.5)
+ let side = 24 * scale
+ let inset = 4 * scale
+ let frame = NSRect(x: max(rect.minX + inset, rect.maxX - inset - side),
+ y: rect.minY + inset,
+ width: min(side, max(0, rect.width - 2 * inset)), height: side)
+ guard frame.intersects(viewport), frame.width > 0 else { return }
+ retained.insert(block.id)
+ let button: TranscriptCodeCopyButton
+ if let existing = codeCopyButtons[block.id] { button = existing }
+ else {
+ button = TranscriptCodeCopyButton(block: block)
+ button.target = self
+ button.action = #selector(copyCodeBlock(_:))
+ codeCopyButtons[block.id] = button
+ addSubview(button)
+ }
+ button.characterIndex = blockRange.location
+ button.symbolConfiguration = .init(pointSize: 12 * scale, weight: .regular)
+ button.frame = frame
+ }
+ }
+ for id in codeCopyButtons.keys where !retained.contains(id) {
+ codeCopyButtons.removeValue(forKey: id)?.removeFromSuperview()
+ }
+ }
+
+ @objc private func copyCodeBlock(_ sender: TranscriptCodeCopyButton) {
+ refreshCodeCopyButtons()
+ guard codeCopyButtons[sender.block.id] === sender, let storage = textStorage,
+ let body = TranscriptCodeBlock.body(at: sender.characterIndex, in: storage, matching: sender.block) else { return }
+ sender.feedbackGeneration += 1
+ let generation = sender.feedbackGeneration
+ guard writeCodeToPasteboard(body) else {
+ sender.setCopied(false)
+ sender.setCopyLabel("Copy code failed; try again")
+ return
+ }
+ sender.setCopied(true)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak sender] in
+ guard let sender, sender.feedbackGeneration == generation else { return }
+ sender.setCopied(false)
+ }
+ }
+
+ deinit { NotificationCenter.default.removeObserver(self) }
+
+ public override func accessibilityChildren() -> [Any]? {
+ let children = super.accessibilityChildren() ?? []
+ // NSTextView exposes its text and links but omits native subviews.
+ // Keep those semantics and make the visible code controls reachable.
+ let buttons = codeCopyButtons.values.sorted { $0.characterIndex < $1.characterIndex }
+ let elements = NSAccessibility.unignoredChildren(from: buttons)
+ return children + elements.filter { element in
+ !children.contains { ($0 as AnyObject) === (element as AnyObject) }
+ }
+ }
+
/// The answer of the turn containing a character index, if it has one.
public var answerAtCharacterIndex: ((Int) -> String?)?
/// The newest answer, the whole chat, and New chat. Supplied by the pane so
@@ -203,3 +360,38 @@ public final class TranscriptTextView: NSTextView {
return selected.length > 0 ? selected : nil
}
}
+
+@MainActor
+final class TranscriptCodeCopyButton: NSButton {
+ let block: TranscriptCodeBlock
+ var characterIndex = 0
+ var feedbackGeneration = 0
+
+ init(block: TranscriptCodeBlock) {
+ self.block = block
+ super.init(frame: .zero)
+ title = ""
+ imagePosition = .imageOnly
+ isBordered = false
+ bezelStyle = .roundRect
+ setButtonType(.momentaryPushIn)
+ let identifier = AccessibilityID.Prefix.transcriptCopyCode.rawValue + block.id.uuidString
+ setAccessibilityIdentifier(identifier)
+ (cell as? NSAccessibilityProtocol)?.setAccessibilityIdentifier(identifier)
+ setCopied(false)
+ }
+
+ func setCopied(_ copied: Bool) {
+ image = NSImage(systemSymbolName: copied ? "checkmark" : "doc.on.doc", accessibilityDescription: nil)
+ contentTintColor = copied ? .controlAccentColor : .secondaryLabelColor
+ setCopyLabel(copied ? "Code copied" : "Copy code")
+ }
+
+ func setCopyLabel(_ label: String) {
+ setAccessibilityLabel(label)
+ (cell as? NSAccessibilityProtocol)?.setAccessibilityLabel(label)
+ toolTip = label
+ }
+
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
+}
diff --git a/Sources/TurboFieldfareServer/Core/ServerInference.swift b/Sources/TurboFieldfareServer/Core/ServerInference.swift
index e94925e8..7e288c75 100644
--- a/Sources/TurboFieldfareServer/Core/ServerInference.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerInference.swift
@@ -950,14 +950,17 @@ public actor ServerModelSession: ServerInferenceBackend {
// the cached prefix is untouched and stays valid for the retry.
throw CancellationError()
} catch {
- ServerLog.promptCacheBridgeFailed(error: error)
+ ServerLog.promptCacheMiss(reason: .continuationBridgeUnavailable)
promptCache.invalidate()
let rendered = try await renderMultimodal(request)
effectivePromptIDs = rendered.effectiveTokenIDs
multimodalInput = rendered
completionStart = .reset
}
- case .miss:
+ case .miss(let reason):
+ if promptCacheMode == .singlePrefix {
+ ServerLog.promptCacheMiss(reason: reason)
+ }
promptCache.invalidate()
if let renderedTextIDs {
effectivePromptIDs = renderedTextIDs
@@ -1109,13 +1112,14 @@ public actor ServerModelSession: ServerInferenceBackend {
// `imagesDiverged` rather than resumed onto a KV built from a different
// picture.
if promptCacheMode == .singlePrefix {
- promptCache.publish(
+ let publication = promptCache.publish(
domain: promptCacheDomain,
request: request,
content: content,
calls: calls,
result: result,
stopStringFiltered: stopMatcher.isStopped)
+ ServerLog.promptCachePublication(publication)
}
completed = true
return ServerCompletion(
diff --git a/Sources/TurboFieldfareServer/Core/ServerLog.swift b/Sources/TurboFieldfareServer/Core/ServerLog.swift
index 77b6137b..7da9bbe7 100644
--- a/Sources/TurboFieldfareServer/Core/ServerLog.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerLog.swift
@@ -55,10 +55,6 @@ enum ServerLog {
+ "finish=\(completion.finishReason)"
}
- /// The session is an actor, so generation is serialized: this line always
- /// belongs to the request between the preceding `generating` and the
- /// following `completed`. Carries a reason code only, never prompt content.
-
static func visionPackInvalid(at url: URL, error: Error) {
write("vision pack at \(url.path) is invalid: \(String(reflecting: error))")
}
@@ -72,12 +68,24 @@ enum ServerLog {
write("vision runtime is unsupported: the image tower requires an M2 or newer Mac")
}
- /// A prefix that could not be continued because its bridge failed to
- /// render. Carries the underlying error, because this miss means the
- /// template and the cached turn disagree, which no other miss does.
- static func promptCacheBridgeFailed(error: Error) {
- write("prompt cache miss reason=bridge-render-failed "
- + "error=\(String(reflecting: error))")
+ /// The session is an actor, so generation is serialized: this line always
+ /// belongs to the request between the preceding `generating` and the
+ /// following `completed`. Carries a reason code only, never prompt content.
+ static func promptCacheMiss(reason: ServerPromptCacheMissReason) {
+ write(promptCacheMissMessage(reason: reason))
+ }
+
+ static func promptCacheMissMessage(reason: ServerPromptCacheMissReason) -> String {
+ "prompt cache miss reason=\(reason.rawValue)"
+ }
+
+ static func promptCachePublication(_ result: ServerPromptCachePublishResult) {
+ if let message = promptCachePublicationMessage(result) { write(message) }
+ }
+
+ static func promptCachePublicationMessage(_ result: ServerPromptCachePublishResult) -> String? {
+ guard case .rejected(let reason) = result else { return nil }
+ return "prompt cache publication rejected reason=\(reason.rawValue)"
}
/// A request whose client stopped listening. Kept distinct from `failed`
diff --git a/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift b/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift
index c5cc8f10..e5ceb100 100644
--- a/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift
@@ -39,8 +39,10 @@ struct ServerPromptCacheEntry: Sendable, Equatable {
/// Why a prefix could not be reused. Carried so a miss is diagnosable rather
/// than indistinguishable from every other miss: a bridge that fails to render
/// is a defect worth seeing, and a history that simply diverged is not.
-enum ServerPromptCacheMissReason: String, Sendable, Equatable {
+enum ServerPromptCacheMissReason: String, Sendable, Equatable, CaseIterable {
case noEntry = "no-entry"
+ case domainChanged = "domain-changed"
+ case toolsChanged = "tools-changed"
case unusableEntry = "unusable-entry"
case historyDiverged = "history-diverged"
case unsupportedContinuation = "unsupported-continuation"
@@ -48,6 +50,21 @@ enum ServerPromptCacheMissReason: String, Sendable, Equatable {
case bridgeRenderFailed = "bridge-render-failed"
case missingImageIdentity = "missing-image-identity"
case imagesDiverged = "images-diverged"
+ case continuationBridgeUnavailable = "continuation-bridge-unavailable"
+}
+
+enum ServerPromptCachePublishRejection: String, Sendable, Equatable, CaseIterable {
+ case invalidKVPosition = "invalid-kv-position"
+ case emptyKV = "empty-kv"
+ case invalidBoundaryCount = "invalid-boundary-count"
+ case stopStringFiltered = "stop-string-filtered"
+ case unsupportedStopReason = "unsupported-stop-reason"
+ case missingImageIdentity = "missing-image-identity"
+}
+
+enum ServerPromptCachePublishResult: Sendable, Equatable {
+ case published
+ case rejected(ServerPromptCachePublishRejection)
}
enum ServerPromptCacheMatch: Sendable, Equatable {
@@ -91,6 +108,7 @@ struct ServerPromptCache: Sendable {
return request.imageIdentities
}
+ @discardableResult
mutating func publish(
domain: ServerPromptCacheDomain,
request: ValidatedChatRequest,
@@ -98,16 +116,20 @@ struct ServerPromptCache: Sendable {
calls: [ParsedToolCall],
result: RawDecodeResult,
stopStringFiltered: Bool = false
- ) {
- guard result.kvPosition == result.kvBackedTokenIDs.count,
- !result.kvBackedTokenIDs.isEmpty,
- result.uncommittedBoundaryTokenIDs.count == 1,
- !stopStringFiltered,
- result.reason == .endOfTurn
- || result.reason == .toolCalls
- || result.reason == .maxTokens else {
- entry = nil
- return
+ ) -> ServerPromptCachePublishResult {
+ // First-failure order is diagnostic policy. The old prefix must also
+ // go: its KV no longer belongs to us after this generation.
+ entry = nil
+ guard result.kvPosition == result.kvBackedTokenIDs.count else {
+ return .rejected(.invalidKVPosition)
+ }
+ guard !result.kvBackedTokenIDs.isEmpty else { return .rejected(.emptyKV) }
+ guard result.uncommittedBoundaryTokenIDs.count == 1 else {
+ return .rejected(.invalidBoundaryCount)
+ }
+ guard !stopStringFiltered else { return .rejected(.stopStringFiltered) }
+ guard result.reason == .endOfTurn || result.reason == .toolCalls || result.reason == .maxTokens else {
+ return .rejected(.unsupportedStopReason)
}
let historicalCalls = calls.map {
GFTokenizer.HistoricalToolCall(
@@ -120,8 +142,7 @@ struct ServerPromptCache: Sendable {
content: calls.isEmpty ? content : nil,
toolCalls: historicalCalls)
guard let identities = Self.identities(for: request) else {
- entry = nil
- return
+ return .rejected(.missingImageIdentity)
}
entry = ServerPromptCacheEntry(
domain: domain,
@@ -134,6 +155,7 @@ struct ServerPromptCache: Sendable {
kvBackedTokenIDs: result.kvBackedTokenIDs,
uncommittedBoundaryTokenIDs: result.uncommittedBoundaryTokenIDs,
kvPosition: result.kvPosition)
+ return .published
}
/// `renderedPromptIDs` is nil for multimodal requests, where the rendered
@@ -145,10 +167,10 @@ struct ServerPromptCache: Sendable {
renderedPromptIDs: [Int32]?,
tokenizer: GFTokenizer
) -> ServerPromptCacheMatch {
- guard let entry,
- entry.domain == domain,
- entry.tools == request.tools,
- entry.kvPosition == entry.kvBackedTokenIDs.count,
+ guard let entry else { return .miss(.noEntry) }
+ guard entry.domain == domain else { return .miss(.domainChanged) }
+ guard entry.tools == request.tools else { return .miss(.toolsChanged) }
+ guard entry.kvPosition == entry.kvBackedTokenIDs.count,
entry.kvPosition > 0,
entry.uncommittedBoundaryTokenIDs.count == 1 else {
return .miss(.unusableEntry)
@@ -284,7 +306,6 @@ struct ServerPromptCache: Sendable {
incomingMessages: request.messages,
tools: request.tools)
} catch {
- ServerLog.promptCacheBridgeFailed(error: error)
return .miss(.bridgeRenderFailed)
}
guard bridge.first == entry.uncommittedBoundaryTokenIDs.first else {
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPromptRendererTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPromptRendererTests.swift
index dca2e85f..78be06c1 100644
--- a/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPromptRendererTests.swift
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPromptRendererTests.swift
@@ -3,6 +3,25 @@ import Testing
@testable import TurboFieldfare
@Suite struct MultimodalPromptRendererTests {
+ @Test func leadingGuidancePreservesImageBoundary() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let context = try MetalContext()
+ let id = UUID()
+ let input = try MultimodalPromptRenderer.render(
+ messages: [
+ MultimodalMessage(role: .system, content: [.text("First instruction.")]),
+ MultimodalMessage(role: .system, content: [.text("Second instruction.")]),
+ MultimodalMessage(role: .user, content: [.text("Describe"), .image(id: id)]),
+ ], featuresByID: [id: try features(rows: 2, context: context)], tokenizer: tokenizer)
+ let span = try #require(input.imageSpans.first)
+ #expect(input.imageSpans.count == 1)
+ #expect(span.tokenRange.count == 2)
+ #expect(input.effectiveTokenIDs[span.tokenRange.lowerBound - 1] == MultimodalPromptRenderer.beginImageTokenID)
+ #expect(input.effectiveTokenIDs[span.tokenRange.upperBound] == MultimodalPromptRenderer.endImageTokenID)
+ let prefix = tokenizer.encode("<bos><|turn>system\nFirst instruction.<turn|>\n<|turn>system\nSecond instruction.<turn|>\n", addBOS: false)
+ #expect(input.effectiveTokenIDs.starts(with: prefix))
+ }
+
@Test func expandsImagesInContentOrderAndZerosEmbeddingRows() async throws {
let tokenizer = try await GFTokenizer.load()
let context = try MetalContext()
diff --git a/Tests/TurboFieldfare/Core/Tokenization/ChatTemplateTests.swift b/Tests/TurboFieldfare/Core/Tokenization/ChatTemplateTests.swift
index df1b07d8..6b2ac767 100644
--- a/Tests/TurboFieldfare/Core/Tokenization/ChatTemplateTests.swift
+++ b/Tests/TurboFieldfare/Core/Tokenization/ChatTemplateTests.swift
@@ -15,6 +15,32 @@ struct ChatTemplateTests {
private typealias Message = GFTokenizer.Message
+ // Validation accepted these requests, but rendering rejected their second
+ // system message before generation could begin.
+ @Test(arguments: 0...3)
+ func leadingSystemTurnsPreserveGuidanceOrder(_ count: Int) throws {
+ let instructions = [" Be terse.\n", "\t", " Réponds en français. "]
+ let messages = instructions.prefix(count).map { Message(role: .system, content: $0) }
+ + [Message(role: .user, content: "Hi")]
+ let expected = "<bos>" + instructions.prefix(count).map {
+ "<|turn>system\n" + $0.trimmingCharacters(in: .whitespacesAndNewlines) + "<turn|>\n"
+ }.joined() + "<|turn>user\nHi<turn|>\n<|turn>model\n<|channel>thought\n<channel|>"
+ let rendered = try tok.applyChatTemplate(messages)
+ #expect(rendered == expected)
+ #expect(tok.encode(rendered, addBOS: false) == tok.encode(expected, addBOS: false))
+ }
+
+ @Test(arguments: [GFTokenizer.Role.user, .assistant, .tool])
+ func guidanceAfterConversationIsRejected(_ role: GFTokenizer.Role) {
+ #expect(throws: GFTokenizerError.self) {
+ try tok.applyChatTemplate([
+ Message(role: .system, content: "first"),
+ Message(role: role, content: "conversation"),
+ Message(role: .system, content: "late"),
+ ])
+ }
+ }
+
@Test("Single user turn has the documented marker structure")
func singleUserTurn() throws {
let p = try tok.applyChatTemplate([Message(role: .user, content: "Hi")])
diff --git a/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptFrameRenderer.swift b/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptFrameRenderer.swift
index 2484c303..c32eea4a 100644
--- a/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptFrameRenderer.swift
+++ b/Tests/TurboFieldfareApp/MacPresentation/Support/TranscriptFrameRenderer.swift
@@ -1,6 +1,7 @@
import AppKit
import Foundation
import Testing
+@testable import TurboFieldfareMacPresentation
struct TranscriptFrameError: Error, CustomStringConvertible {
let description: String
@@ -26,7 +27,7 @@ enum TranscriptFrameRenderer {
width: CGFloat = defaultWidth,
dark: Bool
) throws -> NSImage {
- let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: width, height: 10))
+ let textView = TranscriptTextView(frame: NSRect(x: 0, y: 0, width: width, height: 10))
textView.isEditable = false
textView.isSelectable = true
textView.isRichText = true
@@ -60,6 +61,7 @@ enum TranscriptFrameRenderer {
window.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)
window.contentView = textView
window.layoutIfNeeded()
+ textView.refreshCodeCopyButtons()
let bounds = textView.bounds
guard let rep = NSBitmapImageRep(
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TailAutoCloseTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TailAutoCloseTests.swift
index 8baf034d..a8b4a179 100644
--- a/Tests/TurboFieldfareApp/MacPresentation/TailAutoCloseTests.swift
+++ b/Tests/TurboFieldfareApp/MacPresentation/TailAutoCloseTests.swift
@@ -264,6 +264,28 @@ import Testing
#expect(TailAutoClose.close("") == "")
}
+ @Test func lazyIndentedProseEndingInInlineCodeStillClosesItsEmphasis() {
+ // Inline code at the end does not make the containing paragraph a code block.
+ #expect(TailAutoClose.close("paragraph\n **bold `code`") == "paragraph\n **bold `code`**")
+ }
+
+ @Test func returningToParentQuotePreservesItsListContext() {
+ let source = "> - list\n> > child quote\n> **bold"
+ #expect(TailAutoClose.close(source) == source + "**")
+ }
+
+ @Test(arguments: ["\n", "\r", "\r\n"])
+ func finalLineEndingKeepsTheQuotedFenceOpen(_ newline: String) {
+ let source = "> ```" + newline + "> x" + newline
+ #expect(TailAutoClose.close(source) == source + "> ```")
+ }
+
+ @Test func quoteIndentationUsesTabStopsFromTheSourceColumn() {
+ #expect(ContainerPrefix.strippingQuoteMarkers("\t>").depth == 0)
+ #expect(ContainerPrefix.strippingQuoteMarkers("> \t>").depth == 2)
+ #expect(ContainerPrefix.strippingQuoteMarkers(">\t>").depth == 2)
+ }
+
/// 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
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptCodeControlRegressionTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptCodeControlRegressionTests.swift
new file mode 100644
index 00000000..9cfb4818
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptCodeControlRegressionTests.swift
@@ -0,0 +1,22 @@
+import AppKit
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@MainActor
+@Suite struct TranscriptCodeControlRegressionTests {
+ // A hosted NSTextView had no per-block control at all before 0.9.4.
+ // This uses only entry points present before the feature.
+ @Test func aRenderedCodeCellExposesAnAccessibleCopyButton() async throws {
+ let view = TranscriptTextView(frame: NSRect(x: 0, y: 0, width: 560, height: 300))
+ let window = NSWindow(contentRect: view.bounds, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.contentView = view
+ view.textStorage?.setAttributedString(ResponseMarkdownRenderer().render("```swift\nlet x = 1\n```").attributedString)
+ view.layoutManager?.ensureLayout(for: try #require(view.textContainer))
+ window.layoutIfNeeded()
+ try await Task.sleep(for: .milliseconds(50))
+ let buttons = view.subviews.compactMap { $0 as? NSButton }
+ #expect(buttons.count == 1)
+ #expect(buttons.first?.accessibilityLabel() == "Copy code")
+ #expect(buttons.first?.accessibilityIdentifier().hasPrefix("transcript.copyCode.") == true)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptCodeCopyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptCodeCopyTests.swift
new file mode 100644
index 00000000..dad32770
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptCodeCopyTests.swift
@@ -0,0 +1,423 @@
+import AppKit
+import Testing
+import TurboFieldfareAppCore
+@testable import TurboFieldfareMacPresentation
+
+@MainActor
+@Suite struct TranscriptCodeCopyTests {
+ static func blocks(_ text: NSAttributedString) -> [(TranscriptCodeBlock, Int)] {
+ var result: [(TranscriptCodeBlock, Int)] = []
+ text.enumerateAttribute(.transcriptCodeBlock, in: NSRange(location: 0, length: text.length)) { value, range, _ in
+ if let block = value as? TranscriptCodeBlock { result.append((block, range.location)) }
+ }
+ return result
+ }
+
+ static func bodies(_ text: NSAttributedString) -> [String] {
+ blocks(text).compactMap { TranscriptCodeBlock.body(at: $0.1, in: text, matching: $0.0) }
+ }
+
+ @Test(arguments: [
+ ("```swift\nlet a = 1\n```", "let a = 1\n"),
+ ("~~~text\n\tλ = e\u{301}\n\n next\n~~~", "\tλ = e\u{301}\n\n next\n"),
+ (" let a = 1", "let a = 1"),
+ (" let a = 1\n", "let a = 1\n"),
+ ("> ```swift\n> let a = 1\n> ```", "let a = 1\n"),
+ ("- item\n\n ```\n first\n second\n ```", "first\n second\n"),
+ ("```\r\nfirst\r\nsecond\r\n```", "first\nsecond\n"),
+ ])
+ func semanticCodePreservesExactBody(_ source: String, _ expected: String) {
+ let rendered = ResponseMarkdownRenderer().render(source)
+ #expect(!rendered.usedFallback)
+ #expect(Self.bodies(rendered.attributedString) == [expected])
+ let finalized = ProgressiveTranscriptRenderTests.finalized(source)
+ #expect(Self.bodies(finalized) == [expected])
+ }
+
+ @Test func syntheticNewlineTracksStreamingAndClosingFenceRetraction() throws {
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController()
+ var identity: TranscriptCodeBlock?
+ for (source, expected) in [
+ ("```\na", "a"), ("```\na\r", "a\n"), ("```\na\r\nb", "a\nb"),
+ ("```\na\r\nb\n`", "a\nb\n`"), ("```\na\r\nb\n```", "a\nb\n"),
+ ("```\na\r\nb\n```\n\nProse", "a\nb\n"),
+ ] {
+ controller.synchronize(storage: storage, prompt: "prompt", response: source, isTerminal: false)
+ let block = try #require(Self.blocks(storage).first?.0)
+ if let identity { #expect(identity === block) } else { identity = block }
+ #expect(Self.bodies(storage) == [expected])
+ }
+ controller.synchronize(storage: storage, prompt: "prompt", response: controller.response, isTerminal: true)
+ controller.sealTurn(storage: storage)
+ controller.synchronize(storage: storage, prompt: "next", response: "```\nx", isTerminal: false)
+ #expect(Self.bodies(storage) == ["a\nb\n", "x"])
+ #expect(Self.blocks(storage).first?.0 === identity)
+ controller.synchronize(storage: storage, prompt: "next", response: "```\nx", isTerminal: true)
+ #expect(Self.bodies(storage) == ["a\nb\n", "x"])
+ }
+
+ @Test func nestedCodeKeepsIdentityAcrossStreamingAndPromotion() throws {
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController()
+ var first: TranscriptCodeBlock?
+ for source in ["> ```\n> first", "> ```\n> first\n> second", "> ```\n> first\n> second\n> ```", "> ```\n> first\n> second\n> ```\n\nDone"] {
+ controller.synchronize(storage: storage, prompt: "p", response: source, isTerminal: false)
+ let block = try #require(Self.blocks(storage).first?.0)
+ if let first { #expect(first === block) } else { first = block }
+ }
+ }
+
+ @Test func nestedAutoClosureDoesNotInventClipboardNewline() {
+ let (_, storage) = ProgressiveTranscriptRenderTests.stream("> ```\n> x")
+ #expect(Self.bodies(storage) == ["x"])
+ }
+
+ @Test func emptyInlineQuotedAndRawFallbackTextHaveNoTargets() {
+ for source in ["`inline`", "> quote", "```\n```", "```\nunclosed", "<div>raw</div>", "- ```\n x\n ```"] {
+ #expect(Self.blocks(ResponseMarkdownRenderer().render(source).attributedString).isEmpty)
+ }
+ let storage = NSMutableAttributedString()
+ let controller = InstructionTranscriptDocumentController(environment: ["TURBO_FIELDFARE_PROGRESSIVE_RENDER": "0"])
+ controller.synchronize(storage: storage, prompt: "p", response: "```\nx\n```", isTerminal: false)
+ #expect(Self.blocks(storage).isEmpty)
+ controller.synchronize(storage: storage, prompt: "p", response: "```\nx\n```", isTerminal: true)
+ #expect(Self.bodies(storage) == ["x\n"])
+ }
+
+ static func host(_ text: NSAttributedString, width: CGFloat = 560) throws -> (NSWindow, TranscriptTextView) {
+ let view = TranscriptTextView(frame: NSRect(x: 0, y: 0, width: width, height: 500))
+ view.isEditable = false
+ view.textContainerInset = NSSize(width: 0, height: 4)
+ view.textContainer?.lineFragmentPadding = 0
+ let window = NSWindow(contentRect: view.bounds, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = view
+ view.textStorage?.setAttributedString(text)
+ view.layoutManager?.ensureLayout(for: try #require(view.textContainer))
+ view.refreshCodeCopyButtons()
+ return (window, view)
+ }
+
+ @Test(arguments: [5, 10, 20, 200])
+ func tallCodeKeepsItsVisibleHeader(_ lines: Int) throws {
+ let source = "```\n" + Array(repeating: "line", count: lines).joined(separator: "\n") + "\n```"
+ let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 180))
+ let view = TranscriptTextView(frame: scroll.bounds)
+ view.isVerticallyResizable = true
+ view.textContainer?.widthTracksTextView = true
+ scroll.documentView = view
+ let window = NSWindow(contentRect: scroll.bounds, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.contentView = scroll
+ defer { window.contentView = nil }
+ view.textStorage?.setAttributedString(ProgressiveTranscriptRenderTests.finalized(source))
+ let layout = try #require(view.layoutManager)
+ let container = try #require(view.textContainer)
+ layout.ensureLayout(for: container)
+ view.setFrameSize(NSSize(width: 400, height: max(180, layout.usedRect(for: container).height)))
+ view.refreshCodeCopyButtons()
+ // A viewport-truncated attribute range cannot resolve TextKit's cell bounds.
+ #expect(view.codeCopyButtons.count == 1)
+ if lines >= 20 {
+ scroll.contentView.scroll(to: NSPoint(x: 0, y: 150))
+ view.refreshCodeCopyButtons()
+ #expect(view.codeCopyButtons.isEmpty)
+ }
+ }
+
+ @Test func cachedCodeHasDistinctIdentitiesInSeparateTurnsAndAfterReset() throws {
+ let (window, view) = try Self.host(NSAttributedString())
+ defer { window.contentView = nil }
+ let storage = try #require(view.textStorage)
+ let controller = InstructionTranscriptDocumentController()
+ let source = "> ```\n> same\n> ```"
+ controller.synchronize(storage: storage, prompt: "first", response: source, isTerminal: true)
+ view.refreshCodeCopyButtons()
+ let obsolete = try #require(view.codeCopyButtons.values.first)
+ controller.sealTurn(storage: storage)
+ controller.synchronize(storage: storage, prompt: "second", response: source, isTerminal: true)
+ view.refreshCodeCopyButtons()
+ #expect(Self.bodies(storage) == ["same\n", "same\n"])
+ #expect(Set(Self.blocks(storage).map { $0.0.id }).count == 2)
+ #expect(view.codeCopyButtons.count == 2)
+ controller.resetTranscript(storage: storage)
+ controller.synchronize(storage: storage, prompt: "first", response: source, isTerminal: true)
+ view.refreshCodeCopyButtons()
+ #expect(!view.codeCopyButtons.keys.contains(obsolete.block.id))
+ view.writeCodeToPasteboard = { _ in Issue.record("retired occurrence copied new transcript"); return true }
+ obsolete.performClick(nil)
+ }
+
+ @Test(arguments: [
+ (" abc<partial", "abc<partial"),
+ (" x\n ---", "x\n---"),
+ (" [label](https://exa", "[label](https://exa"),
+ ("> abc<partial", "abc<partial"),
+ ("> ```\n> x", "x"),
+ ("> ```\r\n> x\r\n", "x\n"),
+ ("> ```\r\n> x", "x"),
+ ("> ```\r\n> x\r\n> ```", "x\n"),
+ ("- item\n\n ```\n x\n ```", "x\n"),
+ (" ```", "```"),
+ (" ```\n literal\n ```", "```\nliteral\n```"),
+ ("> paragraph\n>\n> abc<partial", "abc<partial"),
+ ("- item\n\n abc<partial", "abc<partial"),
+ ("> $x$", "$x$"),
+ ("> $x$\n>", "$x$\n"),
+ ("> - list\n> > abc<partial", "abc<partial"),
+ ("> - list\n> > [label](url", "[label](url"),
+ ("> - item\n>\n> ```\n> x\n> ```", "x\n"),
+ ("> - item\n>\n> ~~~\n> x\n> ~~~", "x\n"),
+ ("> x\n>", "x\n"),
+ ("> x\n> ", "x\n"),
+ ("> x\r\n> \t", "x\n"),
+ ("> ```\n> x\u{2028}> ```", "x\u{2028}> ```"),
+ ("> ```\n> x\u{2028}> ```\n> abc<partial", "x\u{2028}> ```\nabc<partial"),
+ ("> ```\n> x\u{2029}> ```", "x\u{2029}> ```"),
+ ("> ```\n> x\u{0085}> ```", "x\u{0085}> ```"),
+ ("> ```\n> > ```\n> abc<partial", "> ```\nabc<partial"),
+ ("> ```\n> > ```\n> abc\n> ```", "> ```\nabc\n"),
+ ("> - item\n> > ```\n> > x\n> > ```", "x\n"),
+ ("> ```\n> x\n>", "x\n"),
+ ("> ```\n> x\n> \n>", "x\n\n"),
+ ("> x\n>\n> ", "x\n"),
+ (" x\n\t>", "x\n>"),
+ (" x\n >", "x\n>"),
+ ])
+ func sourceCodeSurvivesTailRepairsFinalizationAndHistory(_ source: String, _ expected: String) throws {
+ let (window, view) = try Self.host(NSAttributedString())
+ defer { window.contentView = nil }
+ let storage = try #require(view.textStorage)
+ let controller = InstructionTranscriptDocumentController()
+ func assertNativeCopy() throws {
+ view.refreshCodeCopyButtons()
+ #expect(Self.bodies(storage) == [expected])
+ let button = try #require(view.codeCopyButtons.values.first)
+ var copied: String?
+ view.writeCodeToPasteboard = { copied = $0; return true }
+ button.performClick(nil)
+ #expect(copied == expected)
+ }
+ for terminal in [false, true] {
+ controller.synchronize(storage: storage, prompt: "p", response: source, isTerminal: terminal)
+ try assertNativeCopy()
+ }
+ controller.resetTranscript(storage: storage)
+ controller.synchronize(storage: storage, prompt: "p", response: source, isTerminal: true)
+ try assertNativeCopy()
+ }
+
+ @Test(arguments: [AppTextSize.standard, .largest])
+ func visibleHeaderDoesNotRequireVisibleCodeGlyphs(_ size: AppTextSize) throws {
+ let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 100))
+ let view = TranscriptTextView(frame: scroll.bounds)
+ view.isVerticallyResizable = true
+ view.textContainer?.widthTracksTextView = true
+ view.textContainer?.lineFragmentPadding = 0
+ scroll.documentView = view
+ let window = NSWindow(contentRect: scroll.bounds, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.contentView = scroll
+ defer { window.contentView = nil }
+ let source = String(repeating: "Paragraph.\n\n", count: 10) + "```\nline\nline\n```"
+ let text = ResponseMarkdownRenderer(typography: .init(size)).render(source).attributedString
+ let storage = try #require(view.textStorage)
+ storage.setAttributedString(text)
+ let layout = try #require(view.layoutManager)
+ let container = try #require(view.textContainer)
+ layout.ensureLayout(for: container)
+ view.setFrameSize(NSSize(width: 400, height: layout.usedRect(for: container).height + 8))
+ let block = try #require(Self.blocks(storage).first)
+ let style = try #require(storage.attribute(.paragraphStyle, at: block.1, effectiveRange: nil) as? NSParagraphStyle)
+ var range = NSRange()
+ _ = storage.attribute(.transcriptCodeBlock, at: block.1, longestEffectiveRange: &range, in: NSRange(location: 0, length: storage.length))
+ let cell = try #require(style.textBlocks.first)
+ let rect = layout.boundsRect(for: cell, glyphRange: layout.glyphRange(forCharacterRange: range, actualCharacterRange: nil))
+ .offsetBy(dx: view.textContainerOrigin.x, dy: view.textContainerOrigin.y)
+ for points: CGFloat in [0, 3, 6, 10, 20, 30] {
+ scroll.contentView.scroll(to: NSPoint(x: 0, y: rect.minY - 100 + points * CGFloat(size.scale)))
+ view.refreshCodeCopyButtons()
+ #expect(view.codeCopyButtons.count == (points > 4 ? 1 : 0), "\(points) points of the cell are visible at \(size)")
+ }
+ }
+
+ @Test func emptyQuotedCodeHasNoControlUntilContentArrives() throws {
+ let (window, view) = try Self.host(NSAttributedString())
+ defer { window.contentView = nil }
+ let storage = try #require(view.textStorage)
+ let controller = InstructionTranscriptDocumentController()
+ for terminal in [false, true] {
+ controller.resetTranscript(storage: storage)
+ controller.synchronize(storage: storage, prompt: "p", response: "> ```\n> ", isTerminal: terminal)
+ view.refreshCodeCopyButtons()
+ #expect(view.codeCopyButtons.isEmpty)
+ #expect(Self.bodies(storage).isEmpty)
+ }
+ controller.resetTranscript(storage: storage)
+ controller.synchronize(storage: storage, prompt: "p", response: "> ```\n> ", isTerminal: false)
+ controller.synchronize(storage: storage, prompt: "p", response: "> ```\n> x", isTerminal: false)
+ view.refreshCodeCopyButtons()
+ let button = try #require(view.codeCopyButtons.values.first)
+ var copied: String?
+ view.writeCodeToPasteboard = { copied = $0; return true }
+ button.performClick(nil)
+ #expect(copied == "x")
+ }
+
+ @Test func nativeButtonsCopyCurrentBlockAndReportOnlySuccessfulWrites() throws {
+ let source = "```\nidentical\n```\n\n```\nidentical\n```"
+ let rendered = ProgressiveTranscriptRenderTests.finalized(source)
+ let (window, view) = try Self.host(rendered)
+ defer { window.contentView = nil }
+ #expect(view.codeCopyButtons.count == 2)
+ let buttons = view.codeCopyButtons.values.sorted { $0.characterIndex < $1.characterIndex }
+ let first = try #require(buttons.first)
+ let second = try #require(buttons.last)
+ #expect(first.block.id != second.block.id)
+ let copyImage = try #require(first.image)
+ #expect(first.title.isEmpty)
+ #expect(first.toolTip == "Copy code")
+ let board = TranscriptTextViewTests.pasteboard("code-block")
+ defer { board.releaseGlobally() }
+ view.writeCodeToPasteboard = { board.setString($0, forType: .string) }
+ view.setSelectedRange(NSRange(location: 0, length: 2))
+ let selection = view.selectedRanges
+ first.performClick(nil)
+ #expect(board.string(forType: .string) == "identical\n")
+ let copiedImage = try #require(first.image)
+ #expect(copiedImage !== copyImage)
+ #expect(first.title.isEmpty)
+ #expect(first.accessibilityLabel() == "Code copied")
+ #expect(first.toolTip == "Code copied")
+ #expect(view.selectedRanges == selection)
+ #expect(view.string == rendered.string)
+ view.writeCodeToPasteboard = { _ in false }
+ first.performClick(nil)
+ #expect(first.image != nil)
+ #expect(first.image !== copiedImage)
+ #expect(first.title.isEmpty)
+ #expect(first.accessibilityLabel()?.contains("failed") == true)
+ view.textStorage?.setAttributedString(NSAttributedString(string: "new chat"))
+ view.writeCodeToPasteboard = { _ in Issue.record("stale control wrote clipboard"); return true }
+ second.performClick(nil)
+ #expect(view.codeCopyButtons.isEmpty)
+ }
+
+ nonisolated static let layoutCases: [(AppTextSize, CGFloat, Bool)] = [AppTextSize.standard, .largest].flatMap { size in
+ [CGFloat(260), CGFloat(700)].flatMap { width in [false, true].map { (size, width, $0) } }
+ }
+
+ @Test(arguments: layoutCases)
+ func controlsFitCodeHeaderAndFrames(_ size: AppTextSize, _ width: CGFloat, _ dark: Bool) throws {
+ let text = ResponseMarkdownRenderer(typography: .init(size)).render("```swift\nlet value = 42\n```\n\nText with $x^2$.").attributedString
+ let (window, view) = try Self.host(text, width: width)
+ defer { window.contentView = nil }
+ let button = try #require(view.codeCopyButtons.values.first)
+ let layout = try #require(view.layoutManager)
+ let glyphs = layout.glyphRange(forCharacterRange: NSRange(location: button.characterIndex, length: 1), actualCharacterRange: nil)
+ let codeRect = layout.boundingRect(forGlyphRange: glyphs, in: try #require(view.textContainer)).offsetBy(dx: view.textContainerOrigin.x, dy: view.textContainerOrigin.y)
+ #expect(button.frame.maxY <= codeRect.minY)
+ #expect(button.frame.minX >= 0)
+ #expect(button.frame.maxX <= width)
+ let style = try #require(view.textStorage?.attribute(.paragraphStyle, at: button.characterIndex, effectiveRange: nil) as? NSParagraphStyle)
+ let cell = try #require(style.textBlocks.first)
+ var codeRange = NSRange()
+ _ = try #require(view.textStorage).attribute(.transcriptCodeBlock, at: button.characterIndex, longestEffectiveRange: &codeRange, in: NSRange(location: 0, length: text.length))
+ let cellRect = layout.boundsRect(for: cell, glyphRange: layout.glyphRange(forCharacterRange: codeRange, actualCharacterRange: nil))
+ #expect(cellRect.width > 0)
+ #expect(cellRect.maxX <= width)
+ #expect(button.frame.width == button.frame.height)
+ #expect(button.frame.width == 24 * CGFloat(size.scale))
+ #expect(button.title.isEmpty)
+ #expect(button.imagePosition == .imageOnly)
+ #expect(!button.isBordered)
+ try TranscriptFrameRenderer.record(text, named: "code-copy-\(size)-\(Int(width))-\(dark).png", width: width, dark: dark)
+ }
+
+ @Test func visibleControlsStayBoundedWhileReadingAboveALiveAnswer() throws {
+ let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 560, height: 240))
+ let view = TranscriptTextView(frame: scroll.bounds)
+ view.isVerticallyResizable = true
+ view.textContainer?.widthTracksTextView = true
+ view.textContainer?.lineFragmentPadding = 0
+ scroll.documentView = view
+ let window = NSWindow(contentRect: scroll.bounds, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.contentView = scroll
+ defer { window.contentView = nil }
+ let storage = try #require(view.textStorage)
+ let controller = InstructionTranscriptDocumentController()
+ let history = (0..<200).map { "```\nblock \($0)\n```" }.joined(separator: "\n\n")
+ controller.synchronize(storage: storage, prompt: "history", response: history, isTerminal: true)
+ controller.sealTurn(storage: storage)
+ let layout = try #require(view.layoutManager)
+ let container = try #require(view.textContainer)
+ layout.ensureLayout(for: container)
+ view.setFrameSize(NSSize(width: 560, height: layout.usedRect(for: container).height + 8))
+ view.refreshCodeCopyButtons()
+ let firstIDs = Set(view.codeCopyButtons.keys)
+ #expect(!firstIDs.isEmpty)
+ #expect(firstIDs.count < 8)
+ let clock = ContinuousClock()
+ var timings: [Duration] = []
+ let source = try TranscriptCorpus.source("large-code-block")
+ for prefix in TranscriptStreamingTests.ticks(source) {
+ timings.append(clock.measure {
+ controller.synchronize(storage: storage, prompt: "live", response: prefix, isTerminal: false)
+ view.refreshCodeCopyButtons()
+ })
+ #expect(Set(view.codeCopyButtons.keys) == firstIDs)
+ #expect(scroll.contentView.bounds.origin == .zero)
+ }
+ let timing = try #require(TranscriptStreamingTests.timing(timings))
+ print("CODE_COPY_VIEW head_us=\(timing.headDecileMean * 1e6) tail_us=\(timing.tailDecileMean * 1e6) ratio=\(timing.ratio)")
+ #expect(timing.ratio < 3)
+ layout.ensureLayout(for: container)
+ view.setFrameSize(NSSize(width: 560, height: layout.usedRect(for: container).height + 8))
+ scroll.contentView.scroll(to: NSPoint(x: 0, y: view.frame.height - 400))
+ view.refreshCodeCopyButtons()
+ #expect(Set(view.codeCopyButtons.keys).isDisjoint(with: firstIDs))
+ #expect(view.codeCopyButtons.count < 8)
+ }
+
+ @Test func accessibilityIncludesCodeButtonsWithoutReplacingTextSemantics() throws {
+ let (window, view) = try Self.host(ResponseMarkdownRenderer().render("```\nx\n```\n\n```\ny\n```").attributedString)
+ defer { window.contentView = nil }
+ // NSTextView omits native subviews from its default accessibility
+ // children, making visible buttons unreachable to VoiceOver and AXPress.
+ let children = (view.accessibilityChildren() ?? []).compactMap { $0 as? NSAccessibilityProtocol }
+ #expect(children.count == 2)
+ #expect(children.allSatisfy { $0.accessibilityRole() == .button })
+ #expect(children.map { $0.accessibilityLabel() } == ["Copy code", "Copy code"])
+ #expect(view.accessibilityRole() == .textArea)
+ }
+
+ @Test func selectionAcrossCodeAndMathKeepsItsTextAndRichFlavors() throws {
+ let rendered = ResponseMarkdownRenderer().render("```\nlet x = 1\n```\n\nValue $x^2$.").attributedString
+ let view = TranscriptTextViewTests.view(rendered)
+ view.setSelectedRange(NSRange(location: 0, length: rendered.length))
+ let board = TranscriptTextViewTests.pasteboard("code-and-math")
+ defer { board.releaseGlobally() }
+ view.copySelection(to: board)
+ #expect(board.string(forType: .string) == TranscriptPlainText.string(of: rendered))
+ #expect(board.string(forType: .string)?.contains("Copy") == false)
+ #expect(board.data(forType: .rtf) != nil)
+ #expect(board.data(forType: .rtfd) != nil)
+ }
+
+ @Test func detachedTranscriptRemovesControlsAndStopsRefreshing() async throws {
+ let parent = NSView(frame: NSRect(x: 0, y: 0, width: 560, height: 500))
+ let view = TranscriptTextView(frame: parent.bounds)
+ parent.addSubview(view)
+ let storage = try #require(view.textStorage)
+ storage.setAttributedString(ResponseMarkdownRenderer().render("```\nx\n```").attributedString)
+ view.refreshCodeCopyButtons()
+ #expect(view.codeCopyButtons.count == 1)
+ view.removeFromSuperview()
+ #expect(view.codeCopyButtons.isEmpty)
+ storage.append(ResponseMarkdownRenderer().render("```\ny\n```").attributedString)
+ try await Task.sleep(for: .milliseconds(50))
+ #expect(view.codeCopyButtons.isEmpty)
+ parent.addSubview(view)
+ try await Task.sleep(for: .milliseconds(50))
+ #expect(view.codeCopyButtons.count == 2)
+ }
+}
diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
index fa948bb9..d62ee398 100644
--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
@@ -5,6 +5,16 @@ import Testing
@Suite("OpenAI request validation")
struct OpenAIValidationTests {
+ @Test func openCodeShapedLeadingGuidanceRendersAfterValidation() async throws {
+ let json = #"{"model":"m","stream":true,"messages":[{"role":"system","content":"You are a coding assistant."},{"role":"system","content":"Keep replies short."},{"role":"user","content":"Hi"}]}"#
+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: Data(json.utf8))
+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")
+ let tokenizer = try await GFTokenizer.load()
+ let rendered = try tokenizer.applyChatTemplate(validated.messages)
+ #expect(rendered.hasPrefix("<bos><|turn>system\nYou are a coding assistant.<turn|>\n<|turn>system\nKeep replies short.<turn|>\n"))
+ #expect(tokenizer.encode(rendered, addBOS: false).filter { $0 == tokenizer.endOfTurnID }.count == 3)
+ }
+
@Test func capturedOpenCodeInitialRequestValidates() throws {
let request = try fixture("opencode-1.15.11-initial.json")
let validated = try OpenAIRequestValidator.validate(
diff --git a/Tests/TurboFieldfareServer/ServerLogTests.swift b/Tests/TurboFieldfareServer/ServerLogTests.swift
index a46f107c..38753a83 100644
--- a/Tests/TurboFieldfareServer/ServerLogTests.swift
+++ b/Tests/TurboFieldfareServer/ServerLogTests.swift
@@ -6,6 +6,17 @@ import Testing
/// left the request's last line as `generating` forever: reading the log, a
/// running request, an abandoned one and a crashed one were indistinguishable.
@Suite struct ServerLogTests {
+ @Test func cacheDiagnosticsContainOnlyBoundedReasonCodes() {
+ for reason in ServerPromptCacheMissReason.allCases {
+ #expect(ServerLog.promptCacheMissMessage(reason: reason) == "prompt cache miss reason=\(reason.rawValue)")
+ }
+ for reason in ServerPromptCachePublishRejection.allCases {
+ #expect(ServerLog.promptCachePublicationMessage(.rejected(reason)) ==
+ "prompt cache publication rejected reason=\(reason.rawValue)")
+ }
+ #expect(ServerLog.promptCachePublicationMessage(.published) == nil)
+ }
+
private func completion(promptTokens: Int,
cachedTokens: Int,
completionTokens: Int,
diff --git a/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift b/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
index 84d62221..04f95181 100644
--- a/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
+++ b/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
@@ -15,6 +15,53 @@ struct ServerPromptCacheTests {
fp16RingEnabled: true,
templateSHA256: "template")
+ @Test(arguments: ServerPromptCachePublishRejection.allCases)
+ func publicationExplainsRejectionAndInvalidatesPreviousEntry(_ reason: ServerPromptCachePublishRejection) {
+ let initial = request(messages: [.init(role: .user, content: "secret-prompt-sentinel")])
+ var cache = ServerPromptCache()
+ #expect(cache.publish(domain: domain, request: initial, content: "secret-output-sentinel",
+ calls: [], result: rawResult(prompt: [2], kvBacked: [2, 3], boundary: 106,
+ reason: .endOfTurn)) == .published)
+ let result = RawDecodeResult(
+ prefillTokens: 1, cachedPromptTokens: 0, computedPrefillTokens: 1,
+ prefillSeconds: 0, newTokens: 1, decodeSeconds: 0,
+ reason: reason == .unsupportedStopReason ? .eos : .endOfTurn,
+ kvPosition: reason == .invalidKVPosition ? 3 : (reason == .emptyKV ? 0 : 2),
+ kvBackedTokenIDs: reason == .emptyKV ? [] : [2, 3],
+ uncommittedBoundaryTokenIDs: reason == .invalidBoundaryCount ? [] : [106],
+ withheldTrailingKVTokens: 0)
+ let invalidIdentity = request(messages: initial.messages, imageIdentities: [[], ["secret-image"]])
+ let publication = cache.publish(
+ domain: domain, request: reason == .missingImageIdentity ? invalidIdentity : initial,
+ content: "secret-output-sentinel", calls: [], result: result,
+ stopStringFiltered: reason == .stopStringFiltered)
+ #expect(publication == .rejected(reason))
+ #expect(cache.entry == nil)
+ #expect(ServerLog.promptCachePublicationMessage(publication) ==
+ "prompt cache publication rejected reason=\(reason.rawValue)")
+ }
+
+ @Test func publicationRejectionPrecedenceIsDeterministic() {
+ let initial = request(messages: [.init(role: .user, content: "private")], imageIdentities: [[], []])
+ var cache = ServerPromptCache()
+ for (position, ids, boundary, filtered, stop, expected) in [
+ (1, [Int32](), [Int32](), true, StopReason.eos, ServerPromptCachePublishRejection.invalidKVPosition),
+ (0, [], [], true, .eos, .emptyKV),
+ (1, [2], [], true, .eos, .invalidBoundaryCount),
+ (1, [2], [106], true, .eos, .stopStringFiltered),
+ (1, [2], [106], false, .eos, .unsupportedStopReason),
+ (1, [2], [106], false, .endOfTurn, .missingImageIdentity),
+ ] {
+ let result = RawDecodeResult(
+ prefillTokens: 1, cachedPromptTokens: 0, computedPrefillTokens: 1,
+ prefillSeconds: 0, newTokens: 1, decodeSeconds: 0, reason: stop,
+ kvPosition: position, kvBackedTokenIDs: ids,
+ uncommittedBoundaryTokenIDs: boundary, withheldTrailingKVTokens: 0)
+ #expect(cache.publish(domain: domain, request: initial, content: "private", calls: [],
+ result: result, stopStringFiltered: filtered) == .rejected(expected))
+ }
+ }
+
@Test func textContinuationUsesActualGeneratedHistoryAndOnlyPrefillsSuffix() async throws {
let tokenizer = try await GFTokenizer.load()
let initial = request(messages: [
@@ -61,6 +108,33 @@ struct ServerPromptCacheTests {
#expect(effective[cached] == tokenizer.endOfTurnID)
}
+ @Test func missDiagnosticsSeparateNoEntryDomainAndToolsBeforePrefixReuse() async throws {
+ // The public cache used one unusable-entry reason for all three. A
+ // matching token prefix must still never bypass domain or tool checks.
+ let tokenizer = try await GFTokenizer.load()
+ let initial = request(messages: [.init(role: .user, content: "first")])
+ let prefix: [Int32] = [2, 3]
+ var cache = ServerPromptCache()
+ #expect(cache.match(domain: domain, request: initial, renderedPromptIDs: prefix + [4],
+ tokenizer: tokenizer).missReason == .noEntry)
+ cache.publish(domain: domain, request: initial, content: "answer", calls: [],
+ result: rawResult(prompt: [2], kvBacked: prefix, boundary: 106, reason: .endOfTurn))
+ let otherDomain = ServerPromptCacheDomain(
+ modelID: domain.modelID, sourceSnapshotHash: domain.sourceSnapshotHash,
+ runtimeProfileHash: "different-runtime", maximumContext: domain.maximumContext,
+ kvStorage: domain.kvStorage, fp16RingEnabled: domain.fp16RingEnabled,
+ templateSHA256: domain.templateSHA256)
+ #expect(cache.match(domain: otherDomain, request: initial, renderedPromptIDs: prefix + [4],
+ tokenizer: tokenizer).missReason == .domainChanged)
+ let tools = [GFTokenizer.FunctionDefinition(
+ name: "read", description: "Read a file.", parameters: .object(["type": .string("object")]))]
+ let changedTools = request(messages: initial.messages, tools: tools)
+ #expect(cache.match(domain: domain, request: changedTools, renderedPromptIDs: prefix + [4],
+ tokenizer: tokenizer).missReason == .toolsChanged)
+ #expect(cache.match(domain: domain, request: initial, renderedPromptIDs: prefix + [4],
+ tokenizer: tokenizer) == .hit(effectivePromptIDs: prefix + [4], cachedPromptTokens: 2))
+ }
+
@Test func capturedOpenCodeToolResultUsesFrozenToolBoundary() async throws {
let tokenizer = try await GFTokenizer.load()
let initial = try validatedFixture("opencode-1.15.11-initial.json")
diff --git a/docs/OPENAI_SERVER.md b/docs/OPENAI_SERVER.md
index 3d1e9f80..597e8477 100644
--- a/docs/OPENAI_SERVER.md
+++ b/docs/OPENAI_SERVER.md
@@ -183,6 +183,11 @@ usage.prompt_tokens_details.cached_tokens
The server retains one prefix. A different or incompatible history replaces
it. Use `--prompt-cache-mode off` to disable reuse.
+Cache misses and rejected prefix publication include a reason code in the
+server log, such as `history-diverged` or `stop-string-filtered`. These cache
+diagnostics contain no prompt, response, tool payload or image content. Cache
+diagnostics are silent when prompt reuse is disabled.
+
## Tool calls
The server can return OpenAI-style function calls, but it cannot authorize or
@@ -222,6 +227,9 @@ Chat Completions supports JSON and Server-Sent Events responses. Set
`"stream_options": {"include_usage": true}` to receive a final usage chunk.
Requests may contain system, developer, user, assistant, and tool messages.
+Multiple leading system messages retain their order. System and developer
+guidance must precede the conversation; guidance inserted after a user,
+assistant or tool message is rejected.
Supported options include `temperature`, `top_p`, `top_k`,
`repetition_penalty`, `seed`, `stop`, `max_tokens`,
`max_completion_tokens`, and function-tool fields.