Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,10 +256,20 @@ render fixup.

**Conversation Render**:
The token-only rendering contract — family message-forming plus chat-template
application, no pixel work — shared by the planner's re-render and the leaf probes,
identical to the shape prepare uses, so a probe render cannot drift from prepare's.
application, no pixel work — shared by the request edge, the planner's
re-render, and the leaf probes, identical to the shape prepare uses, so a probe
render cannot drift from prepare's. Since 2026-09 a module, not a convention:
one per-request value (`ConversationRender`) built at **Request Keying** where
instance truth lives, sealed for the settled **Cache Key Space**, whose render
verbs own the whole choreography — cache eligibility, the Render+Token Cache
resolve, the template fallback, the no-generation-prompt merged context — so a
call site can no longer wire an ingredient wrong (the issue #439 defect class).
The render cache stays the implementation below it.
_Avoid_: re-render (unqualified), probe tokenization, per-call-site
`applyChatTemplate` (the rendering it standardizes, not a synonym for it).
`applyChatTemplate` (the rendering it standardizes, not a synonym for it);
RenderTokenSource (the dissolved predecessor — eligibility as a free-standing
value each call site wired by hand); per-site resolve-or-fallback ladders (the
retired shape).

**Position Anchor**:
The M-RoPE continuation state a warm-restored conversation resumes generation at —
Expand Down
46 changes: 29 additions & 17 deletions tesseract/Features/Agent/Benchmark/AgentCpuBenchRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -263,26 +263,19 @@ final class AgentCpuBenchRunner {
log("FAIL: conversation build returned nil on \(fixtures[index].label)")
throw NSError(domain: "AgentCpuBench", code: 2)
}
let resolution = try RenderTokenCache.shared.resolve(
tokenizer: tokenizer,
messages: conversation.promptMessages,
tools: canonicalTools,
additionalContext: nil,
modelFingerprint: fingerprint
let render = Self.makeRender(
tokenizer: tokenizer, canonicalTools: canonicalTools, fingerprint: fingerprint
)
guard let resolution else {
guard let fullTokens = render.fullRender(messages: conversation.promptMessages) else {
log("FAIL: resolve returned nil on \(fixtures[index].label)")
throw NSError(domain: "AgentCpuBench", code: 1)
}
fixtures[index].fullTokens = resolution.tokens
fixtures[index].fullTokens = fullTokens
let boundaries = try PrefillPlanner.detectBoundaries(
conversation: conversation,
toolSpecs: canonicalTools,
promptStartsThinking: true,
tokenizer: tokenizer,
keySpace: .identity(keyPath: fixtures[index].fullTokens),
renderContext: .canonical,
modelFingerprint: fingerprint
render: render
)
if index == 0, let offset = boundaries.stablePrefixOffset {
stablePrefixOffset = offset
Expand All @@ -295,6 +288,24 @@ final class AgentCpuBenchRunner {
)
}

/// The bench's **Conversation Render** — the exact request-edge value the
/// production keying phase builds for a text-only request, so the seed
/// resolve and both boundary detects measure the production verbs.
private static func makeRender(
tokenizer: any MLXLMCommon.Tokenizer,
canonicalTools: [ToolSpec]?,
fingerprint: String
) -> ConversationRender {
ConversationRender.forTextOnlyRequest(
tokenizer: tokenizer,
toolSpecs: canonicalTools,
renderContext: .canonical,
hasMedia: false,
producesFlatTextTokens: true,
modelFingerprint: fingerprint
)
}

// MARK: - Timed phases

/// One pass over all seven phases for one turn; each phase's median-of-reps
Expand Down Expand Up @@ -351,17 +362,18 @@ final class AgentCpuBenchRunner {
)
}

// p4 — boundary detection, memo-warm steady state.
// p4 — boundary detection, memo-warm steady state. The render is
// loop-invariant setup, built before the timed span starts.
let render = Self.makeRender(
tokenizer: tokenizer, canonicalTools: canonicalTools, fingerprint: fingerprint
)
var p4 = 0.0
let p4Start = ContinuousClock.now
_ = try PrefillPlanner.detectBoundaries(
conversation: conversation,
toolSpecs: canonicalTools,
promptStartsThinking: true,
tokenizer: tokenizer,
keySpace: .identity(keyPath: fixture.fullTokens),
renderContext: .canonical,
modelFingerprint: fingerprint
render: render
)
p4 = Self.ms(since: p4Start)

Expand Down
35 changes: 14 additions & 21 deletions tesseract/Features/Agent/LLMActor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -347,37 +347,30 @@ actor LLMActor {
/// MLXLLM, the app-side ParoQuant processor) captured at load — so the
/// dicts rendered here are the dicts the processor would render.
///
/// The eligibility decision goes through `RenderTokenSource`, the shared
/// home for the predicate: notably, a `nil` fingerprint BYPASSES rather
/// than resolving under a synthetic key, because the cache's repeat path
/// trusts (bytes, fingerprint) with no arbiter behind it.
/// The eligibility decision and resolve go through the **Conversation
/// Render**'s agent edge, the shared home for the choreography: notably,
/// a `nil` fingerprint BYPASSES rather than resolving under a synthetic
/// key, because the cache's repeat path trusts (bytes, fingerprint) with
/// no arbiter behind it.
private static func prepareViaRenderTokenCache(
context: ModelContext,
input: UserInput,
modelFingerprint: String?
) -> LMInput? {
let llmModel = context.model as? any LLMModel
let source = RenderTokenSource.forTextOnlyRequest(
hasMedia: !(input.images.isEmpty && input.videos.isEmpty && input.audios.isEmpty),
producesFlatTextTokens: llmModel != nil,
modelFingerprint: modelFingerprint
)
guard let cacheFingerprint = source.cacheFingerprint, let llmModel else {
return nil
}
let messages = llmModel.messageGenerator(tokenizer: context.tokenizer).generate(from: input)
guard let llmModel = context.model as? any LLMModel else { return nil }
guard
let resolution = try? RenderTokenCache.shared.resolve(
let tokens = ConversationRender.agentEdgeFullRender(
tokenizer: context.tokenizer,
messages: messages,
messages: llmModel.messageGenerator(tokenizer: context.tokenizer)
.generate(from: input),
tools: input.tools,
additionalContext: input.additionalContext,
modelFingerprint: cacheFingerprint
hasMedia: !(input.images.isEmpty && input.videos.isEmpty && input.audios.isEmpty),
producesFlatTextTokens: true,
modelFingerprint: modelFingerprint
)
else {
return nil
}
return LMInput(tokens: MLXArray(resolution.tokens))
else { return nil }
return LMInput(tokens: MLXArray(tokens))
}

/// Thinking-loop safeguard continuation for the HTTP prefix-cache path.
Expand Down
34 changes: 25 additions & 9 deletions tesseract/Features/Agent/Views/ChatItemViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,23 +117,39 @@ struct AssistantPartView: View {
}

/// Assistant prose — the document body. Markdown by default; the toolbar
/// toggle falls back to plain text.
/// toggle falls back to plain text. The live row passes `isLive` to swap in
/// the chunked streaming renderers, whose publishes cost O(new tail); the
/// committed row renders whole, restoring one selection surface and full
/// markdown fidelity. One view owns the mode branch and the plain-text
/// modifier stack, so the live→committed hand-off cannot drift visually.
struct AssistantProseView: View {
let text: String
var isLive = false
@Environment(SettingsManager.self) private var settings

var body: some View {
#if DEBUG
let _ = ChatViewPerf.signposter.emitEvent("AssistantProseView.body")
let _ = ChatViewPerf.signposter.emitEvent(
isLive ? "AssistantProseView.live" : "AssistantProseView.body")
#endif
if settings.agentUseMarkdown {
ChatMarkdownView(text: text)
if isLive {
ChunkedStreamingMarkdown(text: text)
} else {
ChatMarkdownView(text: text)
}
} else {
Text(text.chatDisplayTrimmed)
.font(.system(size: chatBodyFontSize))
.lineSpacing(chatLineSpacing)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
Group {
if isLive {
ChunkedStreamingText(text: text)
} else {
Text(text.chatDisplayTrimmed)
}
}
.font(.system(size: chatBodyFontSize))
.lineSpacing(chatLineSpacing)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
Expand Down Expand Up @@ -471,7 +487,7 @@ struct LivePartView: View {
#endif
switch live.kind {
case .text:
AssistantProseView(text: live.displayText)
AssistantProseView(text: live.displayText, isLive: true)
case .thinking:
LiveThinkingRowView(live: live)
}
Expand Down
20 changes: 18 additions & 2 deletions tesseract/Features/Agent/Views/ChatMarkdownStyle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,26 @@ struct ChatMarkdownStyle: StructuredText.Style {
let thematicBreakStyle: StructuredText.GitHubThematicBreakStyle = .gitHub
}

/// The vertical gaps Textual's GitHub styles draw between blocks. Textual
/// keeps them as private literals inside the style bodies
/// (`GitHubParagraphStyle` bottom 16, `GitHubHeadingStyle` /
/// `GitHubThematicBreakStyle` top 24), so they cannot be imported — they are
/// mirrored here, beside the style bundle that picks those styles, and must
/// be re-checked whenever the Textual pin moves. `ChunkedStreamingMarkdown`
/// draws them at its chunk seams so a seam is indistinguishable from the gap
/// Textual would draw inside one document.
nonisolated enum ChatMarkdownBlockSpacing {
/// GitHub paragraph / code / table bottom spacing.
static let betweenBlocks: CGFloat = 16
/// GitHub heading / thematic-break top spacing.
static let beforeHeading: CGFloat = 24
}

/// The one way chat markdown is rendered: the style bundle above plus the
/// copyable code blocks, the Code Accent highlighter, and the transcript type
/// size. The transcript (`AssistantProseView`) and the Markdown Gallery both
/// render through this view, so the gallery cannot drift from the chat.
/// size. The transcript (`AssistantProseView`), the live row's frozen chunks
/// (`ChunkedStreamingMarkdown`), and the Markdown Gallery all render through
/// this view, so no caller can drift from the chat.
struct ChatMarkdownView: View {
let text: String

Expand Down
10 changes: 10 additions & 0 deletions tesseract/Features/Agent/Views/ChatViewSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ extension StringProtocol {
}
}

extension String {
/// `String.Index` for a UTF-8 byte offset from the start — O(1) on native
/// strings (the index stores the byte offset directly). Callers guarantee
/// the offset lands on a grapheme boundary; the chunk accumulators only
/// record offsets at line starts.
nonisolated func index(atUTF8Offset offset: Int) -> Index {
utf8.index(utf8.startIndex, offsetBy: offset)
}
}

extension ContentPart {
/// Whether this part would render as an empty row: a whitespace-only text
/// part — the model's cosmetic "\n\n" between tool calls. The stored
Expand Down
Loading
Loading