Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook
Swift apple-silicongemmagemma4gemma4-26b-a4bgpgpullmllm-inferencelocal-aimacosmetalon-device-aion-device-llmswift
Add retained-KV multi-turn chat to the Mac app (#160)
Andrey Mikhaylov19730f87fbaa
diff --git a/AGENTS.md b/AGENTS.mdindex 2a30e5f4..8f186a97 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -57,11 +57,14 @@ Report the commit, hardware and RAM, macOS, Swift version, exact command, exit cThe Mac app sends prompts through the pinned Gemma 4 IT chat format. Itexposes context length, temperature, Top-K, Top-P, expert-cache slots, prefill,and RDADVISE. The defaults are temperature `0.2`, Top-K `64`, and Top-P `0.95`.-Responses can use the context space left after formatting the prompt, and FP16-is the runtime KV format. The HUD shows generation rate, token count, and-decode-service memory; Last run also shows time to first token and I/O. Build-the app with its sibling `TurboFieldfareDecodeService`; it never loads a second-in-process model. See [README](README.md) and [Runtime controls](docs/RUNTIME_CONTROLS.md).+The app retains one in-memory conversation and reuses its FP16 KV state across+turns. The HUD shows generation rate, context use, decode-service memory, and,+on hover, cached-token reuse; Last run also shows time to first token and I/O.+Use **New Chat** to clear the transcript, KV lineage, gauge, and retained+images. Reloading or unloading keeps the transcript but marks it outside the+new model context. Build the app with its sibling+`TurboFieldfareDecodeService`; it never loads a second in-process model. See+[README](README.md) and [Runtime controls](docs/RUNTIME_CONTROLS.md).## Imagesdiff --git a/README.md b/README.mdindex d26fac32..9b8be450 100644--- a/README.md+++ b/README.md@@ -169,7 +169,8 @@ After installation:1. Choose **Load Model**.2. Enter a prompt in the composer.3. Choose **Generate**, or press <kbd>Command</kbd>+<kbd>Return</kbd>. Use **Settings > Send Message With** to choose Return or Command-Return.-4. Use the stop button or <kbd>Escape</kbd> to end generation early.+4. Send another message to continue the conversation, or choose **New Chat** to start over.+5. Use the stop button or <kbd>Escape</kbd> to end generation early.The status bar shows generation progress, decode speed, and memory use. Use theright pane to configure sampling, context length, expert-cache slots, and@@ -352,12 +353,13 @@ TurboFieldfare currently includes:- Custom Metal kernels for quantized GEMV, attention, MoE, normalization,RoPE, sampling, and production fusions- SSD-backed routed-expert streaming with a bounded expert cache-- Chunked single-prompt prefill and token-by-token generation+- Chunked prefill for one-shot prompts and new conversational turns, followed+ by token-by-token generation- FP16 KV storage with bounded circular storage for 25 sliding-window layersand linear storage for 5 full-attention layers- Exact split-K/V decode attention with distinct normalized K and V paths- A Swift library, streaming installer, command-line interface, loopback- OpenAI-compatible server, and native SwiftUI/AppKit Mac app with a one-shot+ OpenAI-compatible server, and native SwiftUI/AppKit Mac app with a siblinglocal decode service- Optional image input from a separately installed companion pack: the visiontower runs on bounded scratch, image rows attend in both directions insidediff --git a/Sources/TurboFieldfare/Runtime/Generation/MultimodalConversation.swift b/Sources/TurboFieldfare/Runtime/Generation/MultimodalConversation.swiftnew file mode 100644index 00000000..f98423f6--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Generation/MultimodalConversation.swift@@ -0,0 +1,536 @@+import Foundation+import Metal++public enum MultimodalConversationError: Error, CustomStringConvertible {+ case closed+ case busy+ case lineageBroken+ case lineageRecoveryFailed(reason: String)+ case emptyTurn+ case contextExhausted(prompt: Int, maxContext: Int)+ case imageUnavailable(reason: String?)++ public var description: String {+ switch self {+ case .closed: "conversation is closed"+ case .busy: "a turn is already generating on this conversation"+ case .lineageBroken:+ "generation failed partway, so the KV no longer matches this "+ + "conversation; call reset() to start over"+ case .lineageRecoveryFailed(let reason):+ "generation failed partway and the KV could not be restored; "+ + "call reset() to start over. \(reason)"+ case .emptyTurn: "a turn needs text or an image"+ case .contextExhausted(let prompt, let maxContext):+ "conversation needs \(prompt) tokens, beyond the \(maxContext)-token context"+ case .imageUnavailable(let reason):+ reason.map { "image support is unavailable: \($0)" }+ ?? "image support is unavailable: no companion pack is installed"+ }+ }+}++enum MultimodalConversationKVRecovery {+ static func restoreAfterFailure(+ positionBefore: Int,+ generationError: Error,+ rewind: (Int) throws -> Void,+ reset: () -> Void+ ) throws {+ guard positionBefore > 0 else {+ reset()+ return+ }+ do {+ try rewind(positionBefore)+ } catch {+ throw MultimodalConversationError.lineageRecoveryFailed(+ reason: "The turn failed with \(generationError). Rewinding to "+ + "token \(positionBefore) then failed with \(error).")+ }+ }++ static func trimHiddenStopTokens(+ _ tokenIDs: [Int32],+ withheld: Int,+ rewind: (Int) throws -> Void,+ reset: () -> Void+ ) throws -> [Int32] {+ guard withheld > 0, withheld <= tokenIDs.count else {+ throw MultimodalConversationError.lineageRecoveryFailed(+ reason: "Stop-string cleanup reported \(withheld) hidden tokens "+ + "for a \(tokenIDs.count)-token KV.")+ }+ let target = tokenIDs.count - withheld+ if target == 0 {+ reset()+ } else {+ do {+ try rewind(target)+ } catch {+ throw MultimodalConversationError.lineageRecoveryFailed(+ reason: "Removing stop-string tokens required rewinding to "+ + "token \(target), which failed with \(error).")+ }+ }+ return Array(tokenIDs.prefix(target))+ }+}+public struct MultimodalTurnResult: Sendable {+ public let text: String+ public let promptTokens: Int+ /// Tokens served from the retained KV rather than prefilled again.+ public let cachedTokens: Int+ /// Tokens this turn put through prefill. `RawCompletion` computes it as+ /// `promptIds.count - cachedPromptTokens`, so it is a derivation of the two+ /// figures beside it, not an independent count: asserting that it equals+ /// `promptTokens - cachedTokens` cannot fail and proves nothing. What it is+ /// good for is reporting — the figure a reader wants when asking what a+ /// turn cost. The claim that the KV was reused rests on `cachedTokens`+ /// matching the previous turn's `kvTokens`, and on `prefillSeconds`.+ public let computedPrefillTokens: Int+ /// Tokens the KV holds after this turn. Not `promptTokens ++ /// completionTokens`: a run that stops on max tokens or is cancelled holds+ /// its final token outside the KV, so that sum is one too many.+ public let kvTokens: Int+ public let completionTokens: Int+ /// Why the turn ended; `.cancelled` when `checkCancellation` stopped the+ /// decode mid-turn, in which case `text` holds the partial reply and the+ /// conversation remains resumable.+ public let reason: StopReason+ /// Wall time spent prefilling this turn's own tokens. Reported so a caller+ /// can show what resuming actually saved rather than asserting that it did.+ public let prefillSeconds: Double+ public let decodeSeconds: Double+}++/// A stateful multi-turn conversation that owns its own KV lineage.+///+/// The server has to *match* a stateless request against a cached prefix and+/// fail closed when it cannot. A conversation does not: it appended every token+/// in the KV itself, so it always knows the boundary and always resumes. Each+/// turn prefills only the new tokens, and an image is encoded once, when its+/// turn is appended.+public actor MultimodalConversation {+ private let model: Model+ private let context: MetalContext+ private let tokenizer: GFTokenizer+ private let runner: RealForwardRunner+ private let scratch: RawCompletionScratch+ private let visionRuntime: VisionRuntime?+ private let visionRuntimeError: Error?+ private let visionResidency: VisionResidencyPolicy+ private let maxContext: Int++ /// Exactly the tokens the KV holds, in order.+ private var kvTokenIDs: [Int32] = []+ private var pending: (parts: [MultimodalContinuationPart], images: [URL])?+ private var closed = false+ /// One generation at a time. `RawCompletionScratch` documents that its+ /// buffers and sampler belong to a single run and that the guard is the+ /// caller's job; the actor alone does not provide it, because `generate`+ /// suspends for the whole decode.+ private var generating = false+ /// Resumed by `finishGeneration()`; see `waitForGeneration()`.+ private var generationWaiters: [CheckedContinuation<Void, Never>] = []+ /// Barrier for `reset()`, set before it awaits the in-flight decode so a+ /// `generate()` racing the reset cannot start and have its KV wiped.+ private var resetting = false+ /// Set when a run throws after prefill. The runner's KV has advanced but+ /// `kvTokenIDs` has not, so the lineage is unusable until reset.+ private var lineageBroken = false+ /// Tokens the model emitted that never entered the KV, which happens when+ /// a run stops on max tokens or is cancelled. The next turn must replay+ /// them, exactly as the server's prefix cache does.+ private var uncommittedBoundary: [Int32] = []+ private var boundaryNeedsReplay = false++ public init(model: Model,+ context: MetalContext,+ tokenizer: GFTokenizer,+ runner: RealForwardRunner,+ scratch: RawCompletionScratch,+ visionRuntime: VisionRuntime? = nil,+ visionRuntimeError: Error? = nil,+ visionResidency: VisionResidencyPolicy = .defaultPolicy,+ maxContext: Int) {+ self.model = model+ self.context = context+ self.tokenizer = tokenizer+ self.runner = runner+ self.scratch = scratch+ self.visionRuntime = visionRuntime+ self.visionRuntimeError = visionRuntimeError+ self.visionResidency = visionResidency+ self.maxContext = maxContext+ }++ public var kvTokenCount: Int { kvTokenIDs.count }+ public var hasStagedTurn: Bool { pending != nil }+ public var isClosed: Bool { closed }+ public var isUsable: Bool { !closed && !lineageBroken }++ /// Marks this conversation unusable without touching the shared runner or+ /// vision runtime. The session calls it when handing out a replacement, so a+ /// stale reference cannot reset or resume onto the live conversation's KV.+ public func invalidate() async {+ closed = true+ pending = nil+ // Wait for any run still decoding: the session resets the shared runner+ // straight after this, and resetting under a live decode either aborts+ // that turn mid-stream or lets two turns drive one runner at once.+ await waitForGeneration()+ }++ /// Suspends until no turn is decoding.+ ///+ /// This was a `while generating { await Task.yield() }` spin, which hot-looped+ /// the cooperative executor for the whole remaining decode — minutes at+ /// single-digit tok/s — and re-entered the actor it was waiting on at every+ /// iteration. Waiters are now resumed by the run itself.+ private func waitForGeneration() async {+ guard generating else { return }+ await withCheckedContinuation { continuation in+ generationWaiters.append(continuation)+ }+ }++ private func finishGeneration() {+ generating = false+ let waiters = generationWaiters+ generationWaiters = []+ for waiter in waiters { waiter.resume() }+ }++ /// Whether a turn is decoding right now.+ public var isGenerating: Bool { generating }++ /// Stages the next user turn without prefilling it.+ public func append(parts: [MultimodalContinuationPart], images: [URL] = []) throws {+ guard !closed else { throw MultimodalConversationError.closed }+ // A turn staged while another is decoding used to be accepted and then+ // dropped: `generate()` clears `pending` when it commits, so the newly+ // staged turn vanished and the next `generate()` reported an empty turn+ // with the user's message gone.+ guard !generating else { throw MultimodalConversationError.busy }+ let imageCount = parts.filter {+ if case .image = $0 { return true } else { return false }+ }.count+ guard !parts.isEmpty, imageCount == images.count else {+ throw MultimodalConversationError.emptyTurn+ }+ pending = (parts, images)+ }++ /// Drops a staged turn that has not been generated yet.+ ///+ /// It cannot undo a generated turn. The KV cache has no rewind — the runner+ /// only validates that a continuation resumes at the current position — so+ /// once a turn is prefilled it is part of the lineage. Use `reset()` to+ /// abandon it, at the cost of re-prefilling the conversation.+ public func clear() {+ pending = nil+ }++ /// Drops the KV and starts over. The model stays loaded.+ ///+ /// Waits for a decode in flight. The actor accepts calls while `generate()`+ /// is suspended mid-run, so resetting here used to wipe the KV under a live+ /// turn: it then attended against an empty cache and either produced garbage+ /// or died on the prefill cursor, leaving `kvTokenIDs` describing a KV that+ /// no longer existed.+ public func reset() async {+ guard !closed else { return }+ // The barrier mirrors `close()` and `invalidate()`, which set theirs+ // before awaiting. Without one, a `generate()` enqueued while this+ // waiter was suspended could win the actor, start decoding, and have+ // its KV wiped underneath it — leaving `kvTokenIDs` restored from the+ // run's own token array while the cursor sat at zero, and+ // `lineageBroken` false, so `isUsable` kept saying yes forever. It+ // also stops back-to-back turns from a higher-priority task starving+ // the reset: the loop alone re-raced each freshly enqueued turn.+ resetting = true+ defer { resetting = false }+ while generating {+ await waitForGeneration()+ }+ guard !closed else { return }+ runner.reset()+ kvTokenIDs.removeAll(keepingCapacity: true)+ pending = nil+ lineageBroken = false+ uncommittedBoundary = []+ boundaryNeedsReplay = false+ }++ /// Ends this conversation and clears the KV it was using. It deliberately+ /// does not touch the session-owned vision runtime: those mappings are+ /// shared, and releasing them here would corrupt another conversation's+ /// state. `TurboFieldfareModelSession.close()` owns that.+ public func close() async {+ guard !closed else { return }+ closed = true+ // Same hazard as `reset()`: the runner is shared and the decode is still+ // using it.+ await waitForGeneration()+ runner.reset()+ kvTokenIDs.removeAll(keepingCapacity: false)+ pending = nil+ }++ /// Appends one user turn and generates the reply, prefilling only the new+ /// tokens. `images` are file URLs in the order they appear among `parts`.+ /// Appends a turn, generates the reply, and commits it.+ public func send(+ parts: [MultimodalContinuationPart],+ images: [URL] = [],+ config: GenerationConfig,+ prefillConfig: PrefillRuntimeConfig = .defaultChunked,+ checkCancellation: @Sendable () throws -> Void = {},+ shouldStop: (@Sendable () -> Bool)? = nil,+ onProgress: (@Sendable (RawDecodeProgress) -> Void)? = nil+ ) async throws -> MultimodalTurnResult {+ try append(parts: parts, images: images)+ return try await generate(+ config: config, prefillConfig: prefillConfig,+ checkCancellation: checkCancellation, shouldStop: shouldStop,+ onProgress: onProgress)+ }++ /// Generates a reply to the staged turn. The turn joins the lineage as soon+ /// as it is prefilled, because the KV cannot rewind.+ /// `onProgress` receives the same events `runRawCompletion` reports, so a+ /// caller can stream tokens and prefill progress. Without it a turn was+ /// only observable once it had finished, which is unusable for a UI: the+ /// text was accumulated internally and returned in one piece.+ /// `shouldStop` ends the turn at a token boundary and **keeps** what it+ /// produced: the run returns normally with `.cancelled` as its stop reason,+ /// the partial reply is in the KV, and the next turn resumes on it. That is+ /// a different thing from cancelling the task, which throws out of the+ /// decode loop and makes this rewind the whole turn. A Stop button wants+ /// the first; a teardown wants the second.+ public func generate(+ config: GenerationConfig,+ prefillConfig: PrefillRuntimeConfig = .defaultChunked,+ checkCancellation: @Sendable () throws -> Void = {},+ shouldStop: (@Sendable () -> Bool)? = nil,+ onProgress: (@Sendable (RawDecodeProgress) -> Void)? = nil+ ) async throws -> MultimodalTurnResult {+ guard !closed else { throw MultimodalConversationError.closed }+ guard !lineageBroken else { throw MultimodalConversationError.lineageBroken }+ guard !generating, !resetting else { throw MultimodalConversationError.busy }+ guard let staged = pending else {+ throw MultimodalConversationError.emptyTurn+ }+ generating = true+ defer { finishGeneration() }+ let parts = staged.parts+ let images = staged.images+ let imageCount = parts.filter {+ if case .image = $0 { return true } else { return false }+ }.count+ if imageCount > 0, visionRuntime == nil {+ throw MultimodalConversationError.imageUnavailable(+ reason: visionRuntimeError.map(String.init(describing:)))+ }++ let cached = kvTokenIDs.count+ let turn = try await encodeTurn(parts: parts, images: images,+ checkCancellation: checkCancellation)+ // A run that stopped on max tokens or was cancelled left its final+ // token outside the KV. Replay it ahead of this turn, exactly as the+ // server's prefix cache does, or the model's context is missing a+ // token it already emitted.+ let boundary = boundaryNeedsReplay ? uncommittedBoundary : []+ let promptIDs = kvTokenIDs + boundary + turn.effectiveTokenIDs+ guard promptIDs.count + 1 <= maxContext else {+ throw MultimodalConversationError.contextExhausted(+ prompt: promptIDs.count, maxContext: maxContext)+ }++ // Same coercion as the other entry points: a turn carrying image spans+ // cannot run under a non-chunked mode, and refusing it after the images+ // are encoded helps nobody.+ var effectivePrefill = prefillConfig+ if turn.prefillInput != nil,+ let coerced = effectivePrefill.coercedForImagePrompt() {+ effectivePrefill = coerced+ }+ var generation = config+ generation.maxNewTokens = min(config.maxNewTokens, maxContext - promptIDs.count)+ var text = ""+ // Marked only once the run has actually written to the KV. Setting it+ // before the attempt condemned the conversation for failures that never+ // touched the cache — a cancellation caught by the first+ // `checkCancellation()`, a rejected prefill config, a resume-position+ // mismatch — where the recorded lineage still matched the KV exactly and+ // the turn could simply have been retried.+ // The runner's own cursor, not a progress callback. Inferring it from+ // the first `.prefill` report missed a chunk that committed and then+ // threw — the KV had moved, nothing said so, and every later turn+ // resumed at a position the runner no longer had, failing forever while+ // `isUsable` still said yes.+ let positionBefore = runner.continuationPosition+ var kvAdvanced = false+ let result: RawDecodeResult+ do {+ result = try await runRawCompletion(+ producer: runner,+ tokenizer: tokenizer,+ promptIds: promptIDs,+ multimodalInput: try turn.prefillInput?.prepending(boundary),+ config: generation,+ context: context,+ scratch: scratch,+ prefillConfig: effectivePrefill,+ start: cached == 0 ? .reset : .resume(cachedPromptTokens: cached),+ // Cancellation mid-decode ends the turn at a token boundary+ // and returns the partial result; throwing here instead would+ // condemn the lineage for a KV that is perfectly resumable.+ shouldStop: {+ if shouldStop?() == true { return true }+ do { try checkCancellation(); return false } catch { return true }+ }) { progress in+ onProgress?(progress)+ switch progress {+ case .token(_, _, let delta):+ text += delta+ case .tail(let tail):+ // The detokenizer flush at the stop boundary. Dropping+ // it returned turn text missing its final characters+ // while the KV kept those very tokens.+ text += tail+ case .prefill:+ // The first progress report is the proof the KV moved.+ kvAdvanced = true+ }+ }+ } catch let generationError {+ if runner.continuationPosition != positionBefore { kvAdvanced = true }+ // A failure that moved the KV used to condemn the lineage outright,+ // but the same rewind the stop-string path uses can usually put the+ // cursor back at the turn start: a cancellation caught between+ // prefill chunks or at a token boundary leaves the committed prefix+ // intact under a rewindable tail. The staged turn stays pending, so+ // a successful rewind makes the turn retryable. Only a rewind past+ // the SWA ring slack fails, and only then is the lineage unusable.+ if kvAdvanced {+ do {+ try MultimodalConversationKVRecovery.restoreAfterFailure(+ positionBefore: positionBefore,+ generationError: generationError,+ rewind: runner.rewind(to:),+ reset: runner.reset)+ } catch {+ lineageBroken = true+ throw error+ }+ }+ throw generationError+ }++ // The KV now holds exactly what the run reported, including the tokens+ // the model generated; keeping the model's own tokens rather than+ // re-tokenising its text is what makes the next turn resumable.+ // The turn is in the KV now, so it is no longer staged. Leaving it+ // pending let a repeated generate() append the same user turn again,+ // behind its own reply, and corrupt the rest of the conversation.+ pending = nil+ kvTokenIDs = result.kvBackedTokenIDs+ // A stop-string match discards the text of the tokens that formed it,+ // but all except the final one were already committed to the KV. Left+ // there, every later turn resumes on a context holding assistant text+ // the caller never saw. Drop them from the record and rewind the+ // runner so KV and transcript agree again; a token that showed a+ // visible prefix before the match began stays, so at most a few+ // characters of one boundary token remain hidden.+ if result.reason == .stopString, result.withheldTrailingKVTokens > 0 {+ do {+ kvTokenIDs = try MultimodalConversationKVRecovery.trimHiddenStopTokens(+ result.kvBackedTokenIDs,+ withheld: result.withheldTrailingKVTokens,+ rewind: runner.rewind(to:),+ reset: runner.reset)+ } catch {+ lineageBroken = true+ throw error+ }+ }+ uncommittedBoundary = result.uncommittedBoundaryTokenIDs+ boundaryNeedsReplay = result.reason == .maxTokens || result.reason == .cancelled+ return MultimodalTurnResult(+ text: text,+ promptTokens: promptIDs.count,+ cachedTokens: cached,+ // The runner's own count, not a reconstruction from KV lengths.+ // Reconstructing it made the figure depend on the stop reason —+ // end-of-turn, EOS, tool-call and stop-string stops each reported+ // one fewer — so the same run was counted differently here and in+ // `ServerInference`, which has always reported this value.+ computedPrefillTokens: result.computedPrefillTokens,+ kvTokens: kvTokenIDs.count,+ completionTokens: result.newTokens,+ reason: result.reason,+ prefillSeconds: result.prefillSeconds,+ decodeSeconds: result.decodeSeconds)+ }++ private struct EncodedTurn {+ let effectiveTokenIDs: [Int32]+ let prefillInput: MultimodalPrefillInput?+ }++ private func encodeTurn(+ parts: [MultimodalContinuationPart],+ images: [URL],+ checkCancellation: @Sendable () throws -> Void+ ) async throws -> EncodedTurn {+ guard !images.isEmpty, let visionRuntime else {+ var text = ""+ for part in parts { if case .text(let value) = part { text += value } }+ let ids = kvTokenIDs.isEmpty+ ? tokenizer.encode(+ try tokenizer.applyChatTemplate(+ [GFTokenizer.Message(role: .user, content: text)]),+ addBOS: false)+ : tokenizer.encodeTextContinuation(userContent: text)+ return EncodedTurn(effectiveTokenIDs: ids, prefillInput: nil)+ }++ // Token counts come from geometry, so the turn's shape is known before+ // any image is encoded.+ let preprocessor = Gemma4ImagePreprocessor(+ device: context.device, config: visionRuntime.config)+ // Kept, not discarded. Planning for the token count and then letting+ // `encodeImage(at:)` re-plan internally opened, sniffed and parsed every+ // image twice per turn — and a file rewritten between the two opens gave+ // a count that no longer matched the span the tokenizer had laid out,+ // failing the turn with a placeholder mismatch that names nothing the+ // user did.+ let plans = try images.map { try preprocessor.plan(fileURL: $0) }+ let counts = plans.map(\.geometry.softTokenCount)+ let bridge = try tokenizer.encodeMultimodalUserContinuation(+ textAndImages: parts, imageTokenCounts: counts,+ // An empty KV means this is the conversation's first turn, which+ // needs the chat template's opening rather than a continuation's.+ openingConversation: kvTokenIDs.isEmpty)+ var spans: [MultimodalImageSpan] = []+ for (range, plan) in zip(bridge.imageTokenRanges, plans) {+ try checkCancellation()+ let features = try visionRuntime.encodeImage(+ plan: plan, languageModel: model,+ residencyPolicy: visionResidency,+ checkCancellation: checkCancellation)+ guard features.tokenCount == range.count else {+ throw MultimodalPromptRendererError.placeholderMismatch+ }+ spans.append(MultimodalImageSpan(tokenRange: range, features: features))+ }+ return EncodedTurn(+ effectiveTokenIDs: bridge.effectiveTokenIDs,+ prefillInput: try MultimodalPrefillInput(+ effectiveTokenIDs: bridge.effectiveTokenIDs,+ embeddingTokenIDs: bridge.embeddingTokenIDs,+ imageSpans: spans))+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swiftindex 11428c44..bbd6cdb7 100644--- a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift+++ b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift@@ -28,6 +28,31 @@ public struct RawDecodeResult: Sendable {public let kvPosition: Intpublic let kvBackedTokenIDs: [Int32]public let uncommittedBoundaryTokenIDs: [Int32]+ public let withheldTrailingKVTokens: Int++ public init(prefillTokens: Int,+ cachedPromptTokens: Int,+ computedPrefillTokens: Int,+ prefillSeconds: Double,+ newTokens: Int,+ decodeSeconds: Double,+ reason: StopReason,+ kvPosition: Int,+ kvBackedTokenIDs: [Int32],+ uncommittedBoundaryTokenIDs: [Int32],+ withheldTrailingKVTokens: Int = 0) {+ self.prefillTokens = prefillTokens+ self.cachedPromptTokens = cachedPromptTokens+ self.computedPrefillTokens = computedPrefillTokens+ self.prefillSeconds = prefillSeconds+ self.newTokens = newTokens+ self.decodeSeconds = decodeSeconds+ self.reason = reason+ self.kvPosition = kvPosition+ self.kvBackedTokenIDs = kvBackedTokenIDs+ self.uncommittedBoundaryTokenIDs = uncommittedBoundaryTokenIDs+ self.withheldTrailingKVTokens = withheldTrailingKVTokens+ }}/// Preallocated per-generation buffers (two 512 KiB vocab buffers plus a token@@ -229,6 +254,7 @@ public func runRawCompletion(producer: any LogitProducer,var generated = 0var reason: StopReason = .maxTokensvar uncommittedBoundaryTokenIDs: [Int32] = []+ var trailingInvisibleTokens = 0while true {try Task.checkCancellation()@@ -276,6 +302,7 @@ public func runRawCompletion(producer: any LogitProducer,let cancelled = !hitStopString && shouldStop()let hitMax = generated >= config.maxNewTokensif hitStopString || cancelled || hitMax {+ if !visible.isEmpty { trailingInvisibleTokens = 0 }let tail = stopMatcher.push(detok.flush()) + stopMatcher.finish()if !tail.isEmpty { onProgress(.tail(tail)) }reason = hitStopString ? .stopString : (cancelled ? .cancelled : .maxTokens)@@ -283,6 +310,7 @@ public func runRawCompletion(producer: any LogitProducer,}history.append(tokenID)+ trailingInvisibleTokens = visible.isEmpty ? trailingInvisibleTokens + 1 : 0try await producer.produce(token: tokenID, position: position, into: scratch.logits)position += 1uncommittedBoundaryTokenIDs.removeAll(keepingCapacity: true)@@ -297,7 +325,9 @@ public func runRawCompletion(producer: any LogitProducer,reason: reason,kvPosition: position,kvBackedTokenIDs: history,- uncommittedBoundaryTokenIDs: uncommittedBoundaryTokenIDs)+ uncommittedBoundaryTokenIDs: uncommittedBoundaryTokenIDs,+ withheldTrailingKVTokens: reason == .stopString+ ? trailingInvisibleTokens : 0)}private func sampleOnce(scratch: RawCompletionScratch, context: MetalContext,diff --git a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swiftindex a5b13201..3027ede3 100644--- a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift+++ b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift@@ -383,6 +383,24 @@ public final class RealForwardRunner: ChunkedPrefillRunner, MultimodalPrefillRunresetTransientState()}+ /// Abandons the newest KV tokens so a stateful conversation can resume at+ /// an earlier visible boundary.+ public func rewind(to position: Int) throws {+ guard let kv else {+ throw PrefillError.prefillCursorMismatch(+ "rewind requires an initialized KV cache")+ }+ guard position > 0, position <= kv.position,+ kv.highWaterPosition - position <= kv.maxRewindTokens else {+ throw PrefillError.prefillCursorMismatch(+ "cannot rewind KV from \(kv.position) to \(position); "+ + "high water \(kv.highWaterPosition), "+ + "ring slack \(kv.maxRewindTokens)")+ }+ kv.rewind(to: position)+ resetTransientState()+ }+public var continuationPosition: Int {kv?.position ?? 0}diff --git a/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift b/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swiftindex 91336587..e8555f67 100644--- a/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift+++ b/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift@@ -57,8 +57,10 @@ public final class KVCacheManager {private let strides: [Int] // bytes per token, per layerprivate let kinds: [LayerKind]private let capacityTokens: [Int]+ private let slidingWindowTokens: Intpublic private(set) var position: Int = 0+ public private(set) var highWaterPosition: Int = 0private static let fp16Size = 2@@ -81,6 +83,7 @@ public final class KVCacheManager {let swaCapacity = min(maxContext,max(1, fp16RingCapacityOverride?? ((slidingWindow ?? config.slidingWindow) + maxPrefillChunkTokens)))+ self.slidingWindowTokens = slidingWindow ?? config.slidingWindowvar ks: [MTLBuffer] = []var vs: [MTLBuffer] = []@@ -206,6 +209,29 @@ public final class KVCacheManager {precondition(count >= 0, "advance count must be non-negative")precondition(position + count <= maxContext, "advance would exceed maxContext")position += count+ highWaterPosition = max(highWaterPosition, position)+ }++ /// Maximum safe rewind before a reused SWA ring slot could become visible.+ public var maxRewindTokens: Int {+ guard fp16RingEnabled else { return maxContext }+ var slack = maxContext+ for layer in 0..<config.numLayers where kinds[layer] == .swa {+ let capacity = capacityTokens[layer]+ guard capacity < maxContext else { continue }+ slack = min(slack, max(0, capacity - slidingWindowTokens))+ }+ return slack+ }++ /// Abandon the newest rows while keeping the remaining KV lineage intact.+ public func rewind(to newPosition: Int) {+ precondition(newPosition >= 0, "rewind target must be non-negative")+ precondition(newPosition <= position,+ "rewind target \(newPosition) is beyond position \(position)")+ precondition(highWaterPosition - newPosition <= maxRewindTokens,+ "rewind to \(newPosition) exceeds ring slack \(maxRewindTokens)")+ position = newPosition}/// Drop all cached positions and return physical pages to the OS.@@ -215,6 +241,7 @@ public final class KVCacheManager {/// releases resident memory between turns; pages fault back in on next write.public func reset() {position = 0+ highWaterPosition = 0let pageSize = Int(getpagesize())var advised = Set<ObjectIdentifier>()for layer in 0..<config.numLayers {diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swiftindex 14d256a2..8922541f 100644--- a/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift@@ -55,8 +55,12 @@ public enum VisionImageTokenBudget {maxContext: Int,reservedTextTokens: Int) -> Int {+ guard maxContext > 0,+ reservedTextTokens >= 0,+ reservedTextTokens < maxContext else {+ return 0+ }let available = maxContext - reservedTextTokens- guard available > 0 else { return 0 }- return max(0, available / maximumTokensPerImage)+ return available / maximumTokensPerImage}}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppSentPromptBehavior.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppSentPromptBehavior.swiftdeleted file mode 100644index 6bb32903..00000000--- a/Sources/TurboFieldfareApp/Core/Configuration/AppSentPromptBehavior.swift+++ /dev/null@@ -1,13 +0,0 @@-public enum AppSentPromptBehavior: String, CaseIterable, Codable, Sendable, Identifiable {- case keep- case clear-- public var id: String { rawValue }-- public var settingsLabel: String {- switch self {- case .keep: return "Keep Prompt"- case .clear: return "Clear Prompt"- }- }-}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swiftindex dfeefaca..625da095 100644--- a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift@@ -16,7 +16,6 @@ struct MacAppSettings: Codable, Equatable, Sendable {var prefillEnabled: Bool = truevar newlineShortcut: AppNewlineShortcut = .returnvar showPromptExamples: Bool = true- var sentPromptBehavior: AppSentPromptBehavior = .keepvar visionResidencyPolicy: VisionResidencyPolicy = .onDemandvar rdadvisePolicy: AppRDAdvicePolicy = .offvar loadModelOnLaunch: Bool = false@@ -33,7 +32,6 @@ struct MacAppSettings: Codable, Equatable, Sendable {case prefillEnabledcase newlineShortcutcase showPromptExamples- case sentPromptBehaviorcase visionResidencyPolicycase rdadvisePolicycase loadModelOnLaunch@@ -50,7 +48,6 @@ struct MacAppSettings: Codable, Equatable, Sendable {prefillEnabled: Bool = true,newlineShortcut: AppNewlineShortcut = .return,showPromptExamples: Bool = true,- sentPromptBehavior: AppSentPromptBehavior = .keep,visionResidencyPolicy: VisionResidencyPolicy = .onDemand,rdadvisePolicy: AppRDAdvicePolicy = .off,loadModelOnLaunch: Bool = false) {@@ -65,7 +62,6 @@ struct MacAppSettings: Codable, Equatable, Sendable {self.prefillEnabled = prefillEnabledself.newlineShortcut = newlineShortcutself.showPromptExamples = showPromptExamples- self.sentPromptBehavior = sentPromptBehaviorself.visionResidencyPolicy = visionResidencyPolicyself.rdadvisePolicy = rdadvisePolicyself.loadModelOnLaunch = loadModelOnLaunch@@ -88,9 +84,6 @@ struct MacAppSettings: Codable, Equatable, Sendable {showPromptExamples = try container.decodeIfPresent(Bool.self,forKey: .showPromptExamples) ?? true- sentPromptBehavior = try container.decodeIfPresent(- AppSentPromptBehavior.self,- forKey: .sentPromptBehavior) ?? .keepvisionResidencyPolicy = try container.decodeIfPresent(VisionResidencyPolicy.self,forKey: .visionResidencyPolicy) ?? .onDemanddiff --git a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swiftindex 4c615cf2..cae4f27b 100644--- a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift+++ b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift@@ -47,6 +47,16 @@ public struct AppDiagnostics: Equatable, Sendable {public var generatedTokens: Intpublic var stopReason: AppStopReasonpublic var promptTokenCount: Int?+ /// Prompt tokens served from the retained KV instead of prefilled again.+ /// Nil on the single-prompt path, where nothing is retained.+ public var cachedPromptTokens: Int?+ /// Tokens this turn put through prefill. A derivation of the two figures+ /// beside it (`RawCompletion` computes `promptIds.count -+ /// cachedPromptTokens`), so comparing it against them cannot fail. Carried+ /// for reporting, not as evidence.+ public var computedPrefillTokens: Int?+ /// Tokens the conversation's KV holds after this turn.+ public var conversationTokens: Int?public var prefillSeconds: Double?public var timeToFirstTokenSeconds: Double?public var decodeSeconds: Double@@ -63,20 +73,23 @@ public struct AppDiagnostics: Equatable, Sendable {}public var prefillTokensPerSecond: Double? {- guard let promptTokenCount,- promptTokenCount > 0,+ guard let tokenCount = computedPrefillTokens ?? promptTokenCount,+ tokenCount > 0,let prefillSeconds,prefillSeconds.isFinite,prefillSeconds > 0 else {return nil}- let rate = Double(promptTokenCount) / prefillSeconds+ let rate = Double(tokenCount) / prefillSecondsreturn rate.isFinite ? rate : nil}public init(generatedTokens: Int,stopReason: AppStopReason,promptTokenCount: Int? = nil,+ cachedPromptTokens: Int? = nil,+ computedPrefillTokens: Int? = nil,+ conversationTokens: Int? = nil,prefillSeconds: Double? = nil,timeToFirstTokenSeconds: Double?,decodeSeconds: Double,@@ -89,6 +102,9 @@ public struct AppDiagnostics: Equatable, Sendable {self.generatedTokens = generatedTokensself.stopReason = stopReasonself.promptTokenCount = promptTokenCount+ self.cachedPromptTokens = cachedPromptTokens+ self.computedPrefillTokens = computedPrefillTokens+ self.conversationTokens = conversationTokensself.prefillSeconds = prefillSecondsself.timeToFirstTokenSeconds = timeToFirstTokenSecondsself.decodeSeconds = decodeSecondsdiff --git a/Sources/TurboFieldfareApp/Core/Inference/AppConversation.swift b/Sources/TurboFieldfareApp/Core/Inference/AppConversation.swiftnew file mode 100644index 00000000..905606ea--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Inference/AppConversation.swift@@ -0,0 +1,164 @@+import Foundation++public struct AppChatTurn: Identifiable, Equatable, Sendable {+ public enum Role: Equatable, Sendable { case user, assistant }++ public let id: UUID+ public let role: Role+ public var text: String+ public var images: [AppImageAttachment]+ public var promptTokens: Int?+ public var cachedTokens: Int?+ public var generatedTokens: Int?+ public var stopReason: AppStopReason?++ public init(id: UUID = UUID(), role: Role, text: String,+ images: [AppImageAttachment] = [],+ promptTokens: Int? = nil, cachedTokens: Int? = nil,+ generatedTokens: Int? = nil, stopReason: AppStopReason? = nil) {+ self.id = id+ self.role = role+ self.text = text+ self.images = images+ self.promptTokens = promptTokens+ self.cachedTokens = cachedTokens+ self.generatedTokens = generatedTokens+ self.stopReason = stopReason+ }+}+/// The app's half of one conversation: what the transcript shows, and the turn+/// order the decode service's gate checks against.+///+/// The invariant this type exists to hold is that **the transcript equals the+/// model's context**. A turn shown here that is not in the KV is a lie the user+/// cannot see, and one in the KV but not here is context they cannot account+/// for. Both counts move together or not at all, which is why a turn is only+/// committed once its generation stream completed: a turn that threw was+/// rewound by the runtime, so it is in neither place.+public struct AppConversation: Equatable, Sendable {+ /// What a turn must present to the service to be admitted.+ public struct Ticket: Equatable, Sendable {+ public let epoch: UUID+ public let index: Int+ }++ public private(set) var epoch: UUID+ public private(set) var turns: [AppChatTurn]+ /// Turns whose tokens are in the KV. Must equal the service gate's count.+ public private(set) var committedTurns: Int+ /// Tokens the KV holds, for the context gauge and the image budget. `nil`+ /// means the client committed a turn without reporting its exact position.+ public private(set) var kvTokens: Int?+ /// Set when the runtime reports the KV no longer matches this conversation.+ /// Nothing can continue it; only a new chat clears it.+ public private(set) var isLineageLost: Bool+ private var pendingUserTurnID: UUID?++ public init(epoch: UUID = UUID()) {+ self.epoch = epoch+ self.turns = []+ self.committedTurns = 0+ self.kvTokens = 0+ self.isLineageLost = false+ }++ public var isEmpty: Bool { turns.isEmpty }++ /// The turns that are finished, as the pairs the transcript draws. A user+ /// turn still decoding is not here: it is the live turn, drawn separately+ /// so its answer can be appended token by token.+ public var completedPairs: [(user: AppChatTurn, assistant: AppChatTurn)] {+ var pairs: [(user: AppChatTurn, assistant: AppChatTurn)] = []+ var index = 0+ while index + 1 < turns.count {+ let user = turns[index]+ let assistant = turns[index + 1]+ guard user.role == .user, assistant.role == .assistant else { break }+ pairs.append((user, assistant))+ index += 2+ }+ return pairs+ }+ public var hasTurnInFlight: Bool { pendingUserTurnID != nil }+ public var canSend: Bool { !isLineageLost && pendingUserTurnID == nil }++ /// Starts a fresh lineage. The caller is responsible for telling the+ /// inference side about `epoch` before the next turn is sent.+ public mutating func startNew(epoch: UUID = UUID()) {+ self = AppConversation(epoch: epoch)+ }++ /// Shows the user's turn and reserves its position, or refuses.+ ///+ /// Refusing rather than trapping: a second send while one is decoding is a+ /// double-tap on Send, and a send after the lineage broke is a user who has+ /// not read the banner yet. Neither should crash, and neither may be+ /// admitted.+ public mutating func beginTurn(text: String,+ images: [AppImageAttachment] = []) -> Ticket? {+ guard canSend else { return nil }+ let turn = AppChatTurn(role: .user, text: text, images: images)+ turns.append(turn)+ pendingUserTurnID = turn.id+ return Ticket(epoch: epoch, index: committedTurns)+ }++ /// Attaches the retained image links to the turn that is in flight. They+ /// are staged after the turn is reserved, because retaining them can fail+ /// and a failure gives the position straight back.+ public mutating func attachImagesToPendingTurn(_ images: [AppImageAttachment]) {+ guard let pendingUserTurnID,+ let index = turns.firstIndex(where: { $0.id == pendingUserTurnID }) else {+ return+ }+ turns[index].images = images+ }++ /// Records the reply. Called only when the generation stream completed,+ /// including a turn the user stopped: that one ends at a token boundary+ /// with its partial reply committed to the KV.+ public mutating func completeTurn(text: String, diagnostics: AppDiagnostics?) {+ guard let pendingUserTurnID,+ let userIndex = turns.firstIndex(where: { $0.id == pendingUserTurnID }) else {+ return+ }+ turns[userIndex].promptTokens = diagnostics?.promptTokenCount+ turns[userIndex].cachedTokens = diagnostics?.cachedPromptTokens+ turns.append(AppChatTurn(+ role: .assistant, text: text,+ generatedTokens: diagnostics?.generatedTokens,+ stopReason: diagnostics?.stopReason))+ committedTurns += 1+ self.pendingUserTurnID = nil+ // Only the runtime knows the committed position. Sampled-token counts+ // include a boundary token that may not be in KV, and stop-string+ // cleanup can rewind more than one token. Missing data stays unknown so+ // capacity checks fail closed instead of trusting a stale lower bound.+ kvTokens = diagnostics?.conversationTokens+ }++ /// Drops the in-flight user turn and hands it back, because the runtime+ /// rewound it: it is not in the KV, so it must not stay in the transcript.+ /// The caller restores its text and images to the composer rather than+ /// making the user retype them.+ @discardableResult+ public mutating func abandonTurn() -> AppChatTurn? {+ guard let pendingUserTurnID,+ let index = turns.firstIndex(where: { $0.id == pendingUserTurnID }) else {+ return nil+ }+ let turn = turns.remove(at: index)+ self.pendingUserTurnID = nil+ return turn+ }++ /// The KV no longer matches this conversation. The transcript stays+ /// readable — losing what the user already read helps nobody — but nothing+ /// further can be sent.+ @discardableResult+ public mutating func markLineageLost() -> AppChatTurn? {+ let abandoned = abandonTurn()+ isLineageLost = true+ return abandoned+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swiftindex a10e4651..3eaa741b 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift@@ -12,6 +12,22 @@ public struct AppGenerationRequest: Equatable, Sendable {public var topP: Float?public var repetitionPenalty: Floatpublic var runtimeOptions: AppRuntimeOptions+ /// Append this turn to the retained conversation instead of resetting the+ /// KV and prefilling the whole prompt. The decode service sets it only+ /// after `DecodeConversationGate` has admitted the turn.+ public var continuesConversation: Bool+ /// Tokens the conversation's KV already holds. Only the image budget uses+ /// it, and getting it wrong is unsafe in one direction: a reserve of zero+ /// admits an image that fits an empty context into a nearly full one.+ public var conversationTokens: Int+ /// The conversation this turn belongs to, and its position in it.+ ///+ /// Set by `AppModel`, read only by the IPC client, which puts them on the+ /// wire for the service's gate to check. The in-process session reads+ /// `continuesConversation` instead: that is the post-gate decision, and+ /// only the service is entitled to make it.+ public var conversationEpoch: UUID?+ public var turnIndex: Int?public init(modelDirectory: URL,prompt: String,@@ -22,7 +38,15 @@ public struct AppGenerationRequest: Equatable, Sendable {topK: Int? = 64,topP: Float? = 0.95,repetitionPenalty: Float = 1.0,- runtimeOptions: AppRuntimeOptions = AppRuntimeOptions()) {+ runtimeOptions: AppRuntimeOptions = AppRuntimeOptions(),+ continuesConversation: Bool = false,+ conversationTokens: Int = 0,+ conversationEpoch: UUID? = nil,+ turnIndex: Int? = nil) {+ self.continuesConversation = continuesConversation+ self.conversationTokens = conversationTokens+ self.conversationEpoch = conversationEpoch+ self.turnIndex = turnIndexself.modelDirectory = modelDirectoryself.prompt = promptself.imageAttachments = imageAttachments@@ -50,8 +74,19 @@ public struct AppGenerationRequest: Equatable, Sendable {guard Set(imageAttachments.map(\.id)).count == imageAttachments.count else {throw AppInferenceError.invalidRequest("Images must be distinct.")}+ guard maxContextTokens > 0 else {+ throw AppInferenceError.invalidRequest("Max context must be greater than zero.")+ }+ guard conversationTokens >= 0, conversationTokens <= maxContextTokens else {+ throw AppInferenceError.invalidRequest(+ "Conversation tokens must be between zero and the max context.")+ }+ // The conversation already in the KV is text the next image has to fit+ // around. Reserving zero here admitted an image that fits an empty+ // context into a context that was almost full, and the turn then failed+ // deep in prefill instead of at the composer.let capacity = VisionImageTokenBudget.capacity(- maxContext: maxContextTokens, reservedTextTokens: 0)+ maxContext: maxContextTokens, reservedTextTokens: conversationTokens)guard imageAttachments.count <= capacity else {throw AppInferenceError.invalidRequest("\(imageAttachments.count) images need up to "@@ -73,9 +108,6 @@ public struct AppGenerationRequest: Equatable, Sendable {guard maxNewTokens > 0 else {throw AppInferenceError.invalidRequest("Max response length must be greater than zero.")}- guard maxContextTokens > 0 else {- throw AppInferenceError.invalidRequest("Max context must be greater than zero.")- }guard temperature >= 0 else {throw AppInferenceError.invalidRequest("Temperature cannot be negative.")}diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swiftindex eb3bbb01..6bcf85fd 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift@@ -13,6 +13,13 @@ public protocol AppModelLifecycleClient: AnyObject, AppInferenceClient {options: AppRuntimeOptions, forceLogitsHead: Bool,onState: @escaping @Sendable (AppModelLoadState) -> Void) async throwsfunc unload() async+ /// Ends the current conversation and opens `epoch` as the only lineage the+ /// inference side will accept turns for. The model stays loaded.+ ///+ /// Required rather than defaulted: a client that silently did nothing here+ /// would keep appending a new chat's turns onto the previous chat's KV, and+ /// nothing downstream could detect it.+ func resetConversation(epoch: UUID) async throws}public protocol AppInferenceMemoryReporting: AnyObject {diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swift b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swiftindex 061c7faa..5ef58ddc 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swift@@ -10,6 +10,10 @@ public enum AppInferenceError: Error, Equatable, Sendable, CustomStringConvertibcase modelNotLoadedcase reloadRequiredcase cancelled+ /// The KV no longer matches the conversation it recorded, so no further+ /// turn can resume onto it. Distinct from every other failure here: those+ /// leave the conversation usable, this one can only be cleared.+ case conversationLineageLost(String)case unknown(String)public var description: String { userMessage }@@ -34,6 +38,8 @@ public enum AppInferenceError: Error, Equatable, Sendable, CustomStringConvertibreturn "Model settings changed. Reload the model before generating."case .cancelled:return "Generation cancelled."+ case .conversationLineageLost(let message):+ return "This conversation can no longer continue: \(message) Start a new chat."case .unknown(let message):return message}diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swiftindex bcc4bc0e..abf3136d 100644--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift@@ -33,6 +33,57 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,DecodeUnixSocket.ignoreSIGPIPEProcessWide()}+ init(testInput: FileHandle, responseOutput: FileHandle) {+ self.serviceURL = Self.defaultServiceURL()+ DecodeUnixSocket.ignoreSIGPIPEProcessWide()+ let responses = makeRouter(output: responseOutput)+ connection.withLock {+ $0.input = testInput+ $0.responses = responses+ }+ }++ var connectionIsInstalled: Bool {+ connection.withLock { $0.input != nil && $0.responses != nil }+ }++ var installedRouter: DecodeServiceResponseRouter? {+ connection.withLock { $0.responses }+ }++ private func invalidateConnection(+ expecting router: DecodeServiceResponseRouter? = nil+ ) {+ let dead = connection.withLock { state -> Connection? in+ if let router, state.responses !== router { return nil }+ defer { state = Connection() }+ return state+ }+ guard let dead else { return }+ if let input = dead.input {+ try? input.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceCommand.shutdown))+ try? input.close()+ }+ dead.responses?.closeStream()+ if let label = dead.launchLabel { Self.removeLaunchJob(label: label) }+ if let socketPath = dead.socketPath { unlink(socketPath) }+ inferenceMemory.withLock { $0 = nil }+ inferenceTowerMemory.withLock { $0 = nil }+ }++ private func write(_ command: DecodeServiceCommand,+ to input: FileHandle,+ expecting responses: DecodeServiceResponseRouter) throws {+ do {+ try input.write(contentsOf: DecodeFrameCodec.encode(command))+ } catch {+ invalidateConnection(expecting: responses)+ throw AppInferenceError.unknown(+ "could not reach the decode service: \(error)")+ }+ }+public func ensureLoaded(modelDirectory: URL, maxContextTokens: Int,options: AppRuntimeOptions, forceLogitsHead: Bool,onState: @escaping @Sendable (AppModelLoadState) -> Void) async throws {@@ -44,8 +95,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,modelPath: modelDirectory.path, maxContextTokens: maxContextTokens,runtimeOptions: Self.decodeRuntimeOptions(options),forceLogitsHead: forceLogitsHead)- try handles.input.write(contentsOf: DecodeFrameCodec.encode(- DecodeServiceCommand.load(request)))+ try write(.load(request), to: handles.input, expecting: handles.responses)let event = try await handles.responses.next(matching: request.requestID)switch event.kind {case .ready:@@ -66,8 +116,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,public func unload() async {guard let handles = currentHandles() else { return }let requestID = UUID()- try? handles.input.write(contentsOf: DecodeFrameCodec.encode(- DecodeServiceCommand.unload(requestID)))+ try? write(.unload(requestID), to: handles.input, expecting: handles.responses)guard let event = try? await handles.responses.next(matching: requestID),event.kind == .unloaded else { return }connection.withLock { $0.loadedDirectory = nil }@@ -103,9 +152,11 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,topP: request.topP,repetitionPenalty: request.repetitionPenalty,runtimeOptions: Self.decodeRuntimeOptions(request.runtimeOptions),- generationID: generationID)- try handles.input.write(contentsOf: DecodeFrameCodec.encode(- DecodeServiceCommand.generate(command)))+ generationID: generationID,+ conversationEpoch: request.conversationEpoch,+ turnIndex: request.turnIndex)+ try write(.generate(command), to: handles.input,+ expecting: handles.responses)var expectedSequence: UInt64 = 1var lastMetricYield = Date.distantPast@@ -173,6 +224,15 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,event.error ?? "decode service failed")continuation.yield(.failed(error, partial: diagnostics))continuation.finish(throwing: error)+ case .lineageLost:+ // Carried across as its own case, not flattened into+ // `.unknown`: the app has to clear the conversation+ // rather than offer a retry that would fail the same+ // way every time.+ let error = AppInferenceError.conversationLineageLost(+ event.error ?? "the conversation's KV no longer matches it")+ continuation.yield(.failed(error, partial: diagnostics))+ continuation.finish(throwing: error)default:continue}@@ -189,10 +249,36 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,}}+ /// Opens `epoch` on the service and waits for it to say so.+ ///+ /// Not fire-and-forget: the app numbers the next turn from zero the moment+ /// this returns, and a turn numbered against a reset the service never+ /// applied is refused by its gate — which is the safe outcome, but the user+ /// sees a rejected message instead of a new chat.+ public func resetConversation(epoch: UUID) async throws {+ guard let handles = currentHandles() else {+ // Not "nothing is loaded" — `currentHandles` is nil when the+ // *connection* is gone. Returning normally let the caller record an+ // epoch the service had never heard of, and because it then matched+ // the app's own, the reset was never retried: every later turn was+ // refused and no recovery path could fire.+ throw AppInferenceError.unknown(+ "the decode service connection is gone; the new chat was not opened")+ }+ let requestID = UUID()+ try write(.resetConversation(+ DecodeResetConversationRequest(epoch: epoch, requestID: requestID)),+ to: handles.input, expecting: handles.responses)+ let event = try await handles.responses.next(matching: requestID)+ guard event.kind == .conversationReset else {+ throw AppInferenceError.unknown(+ event.error ?? "decode service refused to start a new conversation")+ }+ }+public func cancel() {- guard let input = currentHandles()?.input else { return }- try? input.write(contentsOf: DecodeFrameCodec.encode(- DecodeServiceCommand.cancel))+ guard let handles = currentHandles() else { return }+ try? write(.cancel, to: handles.input, expecting: handles.responses)}deinit {@@ -205,6 +291,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,DecodeServiceCommand.shutdown))try? input.close()}+ state.responses?.closeStream()if let label = state.launchLabel { Self.removeLaunchJob(label: label) }if let socketPath = state.socketPath { unlink(socketPath) }}@@ -291,7 +378,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,for _ in 0..<200 {do {let handles = try DecodeUnixSocket.connect(path: socketPath)- let responses = DecodeServiceResponseRouter(output: handles.output)+ let responses = makeRouter(output: handles.output)connection.withLock {$0.input = handles.input$0.responses = responses@@ -331,24 +418,40 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,private func currentHandles()-> (input: FileHandle, responses: DecodeServiceResponseRouter)? {- connection.withLock { state in+ let handles = connection.withLock { state+ -> (input: FileHandle, responses: DecodeServiceResponseRouter)? inguard let input = state.input, let responses = state.responses else {return nil}return (input, responses)}+ guard let handles else { return nil }+ if handles.responses.isTerminated {+ invalidateConnection(expecting: handles.responses)+ return nil+ }+ return handles+ }++ private func makeRouter(output: FileHandle) -> DecodeServiceResponseRouter {+ DecodeServiceResponseRouter(output: output) { [weak self] router, _ in+ self?.invalidateConnection(expecting: router)+ }}private static func diagnostics(_ event: DecodeServiceEvent,options: AppRuntimeOptions) -> AppDiagnostics {let stop = AppStopReason(rawValue: event.stopReason ?? "")- ?? (event.kind == .cancelled- ? .cancelled- : event.kind == .failed ? .failed : .maxTokens)+ ?? (event.kind == .cancelled ? .cancelled+ : (event.kind == .failed || event.kind == .lineageLost) ? .failed+ : .maxTokens)return AppDiagnostics(generatedTokens: event.tokenCount,stopReason: stop,promptTokenCount: event.promptTokenCount,+ cachedPromptTokens: event.cachedPromptTokens,+ computedPrefillTokens: event.computedPrefillTokens,+ conversationTokens: event.conversationTokenCount,prefillSeconds: event.prefillSeconds,timeToFirstTokenSeconds: event.timeToFirstTokenSeconds,decodeSeconds: event.decodeSeconds,diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swiftindex cbcbc79a..c494fbaf 100644--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swift@@ -1,3 +1,4 @@+import Darwinimport Foundationimport TurboFieldfareDecodeProtocol@@ -9,8 +10,16 @@ final class DecodeServiceResponseRouter: @unchecked Sendable {private let condition = NSCondition()private var state = State()+ private let output: FileHandle+ private let onTerminate: @Sendable (DecodeServiceResponseRouter, Error) -> Void- init(output: FileHandle) {+ init(+ output: FileHandle,+ onTerminate: @escaping @Sendable (DecodeServiceResponseRouter, Error) -> Void+ = { _, _ in }+ ) {+ self.output = output+ self.onTerminate = onTerminatelet reader = Thread { [weak self] inself?.readFrames(from: output)}@@ -19,6 +28,17 @@ final class DecodeServiceResponseRouter: @unchecked Sendable {reader.start()}+ var isTerminated: Bool {+ condition.lock()+ defer { condition.unlock() }+ return state.terminalError != nil+ }++ func closeStream() {+ shutdown(output.fileDescriptor, SHUT_RDWR)+ try? output.close()+ }+func next(matching requestID: UUID) async throws -> DecodeServiceEvent {try await Task.detached(priority: .userInitiated) { [self] intry waitForEvent(matching: requestID)@@ -56,9 +76,11 @@ final class DecodeServiceResponseRouter: @unchecked Sendable {}} catch {condition.lock()- state.terminalError = error+ let shouldNotify = state.terminalError == nil+ if shouldNotify { state.terminalError = error }condition.broadcast()condition.unlock()+ if shouldNotify { onTerminate(self, error) }}}}diff --git a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swiftindex ac6147c6..04aac32b 100644--- a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift@@ -87,6 +87,40 @@ public final class RealInferenceClient: AppModelLifecycleClient, @unchecked Sendawait session.unload()}+ /// Drops the KV so the next turn starts a fresh lineage. The model stays+ /// loaded: this ends a conversation, it does not unload ~1.6 GB.+ public func resetConversation() async {+ await session.resetConversation()+ }++ /// In-process, so there is no stale-epoch window to guard: the caller is+ /// the only writer. The epoch is accepted and ignored; the decode service+ /// holds the gate that uses it.+ public func resetConversation(epoch: UUID) async throws {+ await session.resetConversation()+ }++ /// Whether a conversation is still open on the session.+ ///+ /// Exists so a test can assert that `unload()` released it. It cannot be+ /// inferred from the outside, and not releasing it means unload freed+ /// nothing at all — the conversation holds the model, the runner, the+ /// scratch and the tower.+ public var hasOpenConversation: Bool {+ get async { await session.hasConversation }+ }++ /// Tokens the open conversation's KV holds, or zero when none is open.+ public var conversationTokenCount: Int {+ get async { await session.currentConversationTokens }+ }++ /// The same figure without awaiting the session, for the decode service's+ /// writer thread.+ public var currentConversationTokens: Int {+ session.conversationTokens.withLock { $0 }+ }+public func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {AsyncThrowingStream { continuation inlet generationID = UUID()@@ -113,6 +147,20 @@ public final class RealInferenceClient: AppModelLifecycleClient, @unchecked SendgenerationTasks.takeCurrent()?.cancel()}+ /// Ends the turn at the next token boundary and keeps what it produced.+ ///+ /// Only decode has token boundaries. A stop during prefill or an image+ /// encode has nothing to stop at, so it cancels instead and the+ /// conversation rewinds the turn — otherwise Stop did nothing at all until+ /// the first token, which on a long prompt is a long time.+ public func stop() {+ session.stopRequested.withLock { $0 = true }+ guard session.decodeBegan.withLock({ $0 }) else {+ generationTasks.takeCurrent()?.cancel()+ return+ }+ }+}struct SessionLoadKey: Equatable, Sendable {@@ -162,10 +210,29 @@ actor RealInferenceSession {private var runner: RealForwardRunner?private var scratch: RawCompletionScratch?private var model: Model?-+ /// The open conversation, when the app is in chat mode. Nil for the+ /// one-shot path, and dropped by any load, unload, or explicit reset.+ private var conversation: MultimodalConversation?/// Bytes of image tower held mapped right now, published outside the actor/// so a reader does not have to await it mid-decode.nonisolated let towerBytes = Mutex<UInt64?>(nil)+ /// Tokens the open conversation's KV holds, published outside the actor for+ /// the same reason `towerBytes` is: the decode service's writer thread+ /// stamps it on the turn's terminal event and cannot await this actor+ /// mid-decode.+ nonisolated let conversationTokens = Mutex<Int>(0)+ /// Set by Stop, read by the decode loop at each token boundary.+ ///+ /// Cancelling the task instead throws out of `runRawCompletion`'s loop+ /// before its `shouldStop` is consulted, and the conversation then rewinds+ /// the whole turn — measured: a stop after 13 tokens left the KV at zero.+ /// Stopping cooperatively keeps what was produced and lets the next turn+ /// continue from it.+ nonisolated let stopRequested = Mutex<Bool>(false)+ /// Whether the run has reached decode. Before that there are no token+ /// boundaries to stop at, and half a prefilled prompt is not a turn worth+ /// keeping — so a stop there has to cancel and let the conversation rewind.+ nonisolated let decodeBegan = Mutex<Bool>(false)private var visionRuntime: VisionRuntime? {didSet { publishTowerBytes() }@@ -178,10 +245,38 @@ actor RealInferenceSession {towerBytes.withLock { $0 = value }}+ /// A reader the decode loop can call from wherever it runs. The `Mutex` is+ /// a non-copyable stored property, so it is reached through `self` rather+ /// than captured.+ private nonisolated func stopFlagReader() -> @Sendable () -> Bool {+ { [weak self] in self?.stopRequested.withLock { $0 } ?? false }+ }++ func resetConversation() async {+ // Same hazard as `unload()`: `runner.reset()` under a live decode either+ // aborts that turn mid-stream or lets two turns drive one runner.+ if let conversation { await conversation.invalidate() }+ conversation = nil+ runner?.reset()+ conversationTokens.withLock { $0 = 0 }+ }++ var hasConversation: Bool { conversation != nil }++ var currentConversationTokens: Int {+ get async {+ let count = await conversation?.kvTokenCount ?? 0+ conversationTokens.withLock { $0 = count }+ return count+ }+ }+func ensureLoaded(key: SessionLoadKey,onState: @Sendable (AppModelLoadState) -> Void) async throws {if loadedKey == key, runner != nil { return }+ conversation = nil+ conversationTokens.withLock { $0 = 0 }runner = nilscratch = nilmodel = nil@@ -301,7 +396,15 @@ actor RealInferenceSession {min(requested, max(0, maxContext - promptTokenCount))}- func unload() {+ func unload() async {+ // Awaited, not just dropped. `MultimodalConversation` holds the model,+ // runner, scratch and vision runtime as strong `let`s, and a turn in+ // flight holds its own reference — so nilling this while a decode runs+ // frees nothing and the next load builds a second set beside the live+ // one. `invalidate()` is what waits for that decode.+ if let conversation { await conversation.invalidate() }+ conversation = nil+ conversationTokens.withLock { $0 = 0 }visionRuntime = nilvisionRuntimeError = nilmodel = nil@@ -312,36 +415,20 @@ actor RealInferenceSession {loadedKey = nil}- func run(request: AppGenerationRequest,- memorySampler: AppMemorySampler,- continuation: AsyncThrowingStream<AppInferenceEvent, Error>.Continuation) async {- var prefillConfig = request.runtimeOptions.prefillConfig- // Image spans only run under chunked prefill, and the app's prefill toggle- // can select `.off`. Coerce rather than fail after the encodes: whether- // images work is not a performance preference.- if !request.imageAttachments.isEmpty,- let coerced = prefillConfig.coercedForImagePrompt() {- prefillConfig = coerced- }- let progress = ProgressState()- do {- try request.validate()- let executedPrefillMode: PrefillExecutedMode =- prefillConfig.mode == .chunked ? .chunked : .off- let prefillDiagnostics = PrefillExecutionDiagnostics(config: prefillConfig,- executedMode: executedPrefillMode,- kvStorageMode: .fp16)- let requestKey = SessionLoadKey(- directory: request.modelDirectory.standardizedFileURL,- maxContext: request.maxContextTokens,- options: request.runtimeOptions,- forceLogitsHead: Self.forceLogitsHead(for: request))- guard let loadedKey else { throw AppInferenceError.modelNotLoaded }- guard loadedKey == requestKey else { throw AppInferenceError.reloadRequired }- guard let runner, let tokenizer, let ctx, let scratch else {- throw AppInferenceError.modelLoadFailed("session lost its loaded state")- }-+ /// The single-prompt path: reset the KV and prefill the whole rendered+ /// prompt. Unchanged behaviour, moved out of `run` so the conversational+ /// path sits beside it rather than inside it.+ private func runOneShot(+ request: AppGenerationRequest,+ runner: RealForwardRunner,+ tokenizer: GFTokenizer,+ ctx: MetalContext,+ scratch: RawCompletionScratch,+ prefillConfig: PrefillRuntimeConfig,+ progress: ProgressState,+ memorySampler: AppMemorySampler,+ report: @escaping @Sendable (RawDecodeProgress) -> Void+ ) async throws -> TurnOutcome {let promptIds: [Int32]let multimodalInput: MultimodalPrefillInput?if request.imageAttachments.isEmpty {@@ -403,14 +490,187 @@ actor RealInferenceSession {runner.reset()progress.prefillStart = Date()- let result = try await runRawCompletion(- producer: runner, tokenizer: tokenizer, promptIds: promptIds,- multimodalInput: multimodalInput,- config: config, context: ctx, scratch: scratch,- prefillConfig: prefillConfig) { event in++ let result = try await runRawCompletion(+ producer: runner, tokenizer: tokenizer, promptIds: promptIds,+ multimodalInput: multimodalInput,+ config: config, context: ctx, scratch: scratch,+ prefillConfig: prefillConfig,+ shouldStop: stopFlagReader(),+ onProgress: report)+ return TurnOutcome(+ reason: result.reason, prefillSeconds: result.prefillSeconds,+ decodeSeconds: result.decodeSeconds, newTokens: result.newTokens,+ computedPrefillTokens: result.computedPrefillTokens)+ }++ /// What both turn paths report back, so the terminal diagnostics do not+ /// have to know which one ran.+ struct TurnOutcome {+ let reason: StopReason+ let prefillSeconds: Double+ let decodeSeconds: Double+ let newTokens: Int+ /// Nil on the single-prompt path: nothing was retained to reuse.+ var cachedTokens: Int?+ var computedPrefillTokens: Int?+ var conversationTokens: Int?+ }++ /// The open conversation, or a new one on the same runner.+ ///+ /// Built lazily rather than at load: a load that is never followed by a+ /// conversational turn should not reset the runner, and the residency+ /// policy belongs to the turn that asks for it.+ private func conversationForTurn(+ _ request: AppGenerationRequest+ ) throws -> MultimodalConversation {+ if let conversation { return conversation }+ guard let model, let ctx, let tokenizer, let runner, let scratch else {+ throw AppInferenceError.modelLoadFailed("session lost its loaded state")+ }+ // A conversation starts from an empty KV. The runner may be carrying a+ // one-shot generation's tokens, and resuming a first turn onto those+ // would put a prompt the user never sent in front of this one.+ runner.reset()+ // The same waiver `TurboFieldfareModelSession` takes, and it holds for+ // the same reason: `Model` and `VisionRuntime` are not Sendable because+ // two conversations encoding at once would race the tower's per-encode+ // scratch. What prevents that here is this session's own invariant —+ // one conversation, and one generation at a time behind+ // `GenerationTaskRegistry` and the decode service's serial command loop+ // — not the type system. Anything that lets two turns run at once has+ // to make `VisionRuntime` an actor first.+ nonisolated(unsafe) let sharedModel = model+ nonisolated(unsafe) let sharedVision = visionRuntime+ let created = MultimodalConversation(+ model: sharedModel, context: ctx, tokenizer: tokenizer, runner: runner,+ scratch: scratch, visionRuntime: sharedVision,+ visionRuntimeError: visionRuntimeError,+ visionResidency: request.runtimeOptions.visionResidencyPolicy,+ maxContext: runner.maxContext)+ conversation = created+ return created+ }++ private func runConversationTurn(+ request: AppGenerationRequest,+ prefillConfig: PrefillRuntimeConfig,+ progress: ProgressState,+ memorySampler: AppMemorySampler,+ report: @escaping @Sendable (RawDecodeProgress) -> Void+ ) async throws -> TurnOutcome {+ let conversation = try conversationForTurn(request)+ var parts: [MultimodalContinuationPart] = []+ var imageURLs: [URL] = []+ for attachment in request.imageAttachments {+ try Task.checkCancellation()+ // Same check the one-shot path makes: the file was hashed when it+ // was staged, and a file rewritten since then is a different image+ // than the one the user attached.+ let actualDigest = try Sha256Verifier.hashFile(+ at: attachment.fileURL, chunkBytes: 256 * 1_024)+ guard actualDigest == attachment.sha256 else {+ throw AppInferenceError.invalidRequest(+ "Image \(attachment.displayName) changed after selection.")+ }+ parts.append(.image)+ imageURLs.append(attachment.fileURL)+ }+ if !request.prompt.isEmpty { parts.append(.text(request.prompt)) }++ memorySampler.resetPeak()+ _ = memorySampler.sample()+ progress.prefillStart = Date()+ defer { publishTowerBytes() }+ do {+ // `maxNewTokens` is clamped inside the conversation against what the+ // KV has room for, so it is passed through unmodified here.+ let turn = try await conversation.send(+ parts: parts, images: imageURLs,+ config: Self.generationConfig(+ for: request, maxNewTokens: request.maxNewTokens),+ prefillConfig: prefillConfig,+ checkCancellation: { try Task.checkCancellation() },+ shouldStop: stopFlagReader(),+ onProgress: report)+ progress.promptTokenCount = turn.promptTokens+ // The conversation's own count. `promptTokens + completionTokens`+ // is one too many whenever a run stops on max tokens or is+ // cancelled: that final token is held outside the KV for the next+ // turn to replay.+ conversationTokens.withLock { $0 = turn.kvTokens }+ return TurnOutcome(+ reason: turn.reason, prefillSeconds: turn.prefillSeconds,+ decodeSeconds: turn.decodeSeconds, newTokens: turn.completionTokens,+ cachedTokens: turn.cachedTokens,+ computedPrefillTokens: turn.computedPrefillTokens,+ conversationTokens: turn.kvTokens)+ } catch let error as MultimodalConversationError {+ // Mapped rather than flattened: a lineage that broke can only be+ // cleared, an exhausted context is the user's to act on, and an+ // unavailable image names the pack that failed to open. Reporting+ // all three as one generic failure is how a chat becomes+ // undiagnosable.+ switch error {+ case .lineageBroken, .lineageRecoveryFailed:+ throw AppInferenceError.conversationLineageLost("\(error)")+ case .contextExhausted(let prompt, let maxContext):+ throw AppInferenceError.contextOverflow(+ prompt: prompt, maxNew: request.maxNewTokens,+ maxContext: maxContext)+ case .imageUnavailable:+ throw AppInferenceError.invalidRequest("\(error)")+ case .closed, .busy, .emptyTurn:+ throw AppInferenceError.unknown("\(error)")+ }+ }+ }++ func run(request: AppGenerationRequest,+ memorySampler: AppMemorySampler,+ continuation: AsyncThrowingStream<AppInferenceEvent, Error>.Continuation) async {+ // Cleared here, before either branch and before anything a stop could+ // race. Resetting them inside the conversational branch left the+ // single-prompt path with a flag nothing ever lowered — after one Stop+ // every later generation returned exactly one token — and left a stale+ // `decodeBegan` that swallowed a Stop pressed while the next turn was+ // still hashing its images.+ stopRequested.withLock { $0 = false }+ decodeBegan.withLock { $0 = false }+ var prefillConfig = request.runtimeOptions.prefillConfig+ // Image spans only run under chunked prefill, and the app's prefill+ // toggle can select `.off`. Coerce rather than fail after the encodes:+ // whether images work is not a performance preference.+ if !request.imageAttachments.isEmpty,+ let coerced = prefillConfig.coercedForImagePrompt() {+ prefillConfig = coerced+ }+ let progress = ProgressState()+ do {+ try request.validate()+ let requestKey = SessionLoadKey(+ directory: request.modelDirectory.standardizedFileURL,+ maxContext: request.maxContextTokens,+ options: request.runtimeOptions,+ forceLogitsHead: Self.forceLogitsHead(for: request))+ guard let loadedKey else { throw AppInferenceError.modelNotLoaded }+ guard loadedKey == requestKey else { throw AppInferenceError.reloadRequired }+ guard let runner, let tokenizer, let ctx, let scratch else {+ throw AppInferenceError.modelLoadFailed("session lost its loaded state")+ }+ let executedPrefillMode: PrefillExecutedMode =+ prefillConfig.mode == .chunked ? .chunked : .off+ let prefillDiagnostics = PrefillExecutionDiagnostics(config: prefillConfig,+ executedMode: executedPrefillMode,+ kvStorageMode: .fp16)++ let report: @Sendable (RawDecodeProgress) -> Void = { event inswitch event {case .prefill(let done, let total):if done == total {+ // From here there are token boundaries to stop at.+ self.decodeBegan.withLock { $0 = true }progress.decodeStart = Date()progress.countersAtDecodeStart = RunnerCounterSnapshot(runner)}@@ -431,6 +691,21 @@ actor RealInferenceSession {}}+ let outcome: TurnOutcome+ if request.continuesConversation {+ outcome = try await runConversationTurn(+ request: request, prefillConfig: prefillConfig,+ progress: progress, memorySampler: memorySampler,+ report: report)+ } else {+ outcome = try await runOneShot(+ request: request, runner: runner, tokenizer: tokenizer,+ ctx: ctx, scratch: scratch, prefillConfig: prefillConfig,+ progress: progress, memorySampler: memorySampler,+ report: report)+ }+ let result = outcome+let diagnostics = makeDiagnostics(request: request,memorySampler: memorySampler,progress: progress,@@ -438,6 +713,9 @@ actor RealInferenceSession {prefillSeconds: result.prefillSeconds,decodeSeconds: result.decodeSeconds,generated: result.newTokens,+ cachedTokens: result.cachedTokens,+ computedPrefillTokens: result.computedPrefillTokens,+ conversationTokens: result.conversationTokens,prefill: prefillDiagnostics)continuation.yield(.finished(diagnostics))continuation.finish()@@ -451,7 +729,8 @@ actor RealInferenceSession {generated: progress.generated,prefill: PrefillExecutionDiagnostics(config: prefillConfig,- executedMode: prefillConfig.mode == .chunked ? .chunked : .off,+ executedMode: prefillConfig.mode == .chunked+ ? PrefillExecutedMode.chunked : .off,kvStorageMode: .fp16))continuation.yield(.cancelled(diagnostics))continuation.finish(throwing: AppInferenceError.cancelled)@@ -501,6 +780,9 @@ actor RealInferenceSession {prefillSeconds: Double? = nil,decodeSeconds: Double,generated: Int,+ cachedTokens: Int? = nil,+ computedPrefillTokens: Int? = nil,+ conversationTokens: Int? = nil,prefill: PrefillExecutionDiagnostics? = nil) -> AppDiagnostics {_ = memorySampler.sample()let ttft: Double?@@ -513,6 +795,9 @@ actor RealInferenceSession {generatedTokens: generated,stopReason: stopReason,promptTokenCount: progress.promptTokenCount,+ cachedPromptTokens: cachedTokens,+ computedPrefillTokens: computedPrefillTokens,+ conversationTokens: conversationTokens,prefillSeconds: prefillSeconds,timeToFirstTokenSeconds: ttft,decodeSeconds: decodeSeconds,diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swiftindex df4cd815..29f48e31 100644--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift@@ -29,6 +29,20 @@ public final class AppModel {public var isConfirmingVisionPackRemoval = falsepublic private(set) var outputPromptText: String = ""public private(set) var outputImageAttachments: [AppImageAttachment] = []+ /// The open chat. The transcript renders it, and its turn order is what the+ /// decode service's gate checks every turn against.+ public private(set) var conversation = AppConversation()+ /// Turns from conversations whose KV no longer exists — a reload or an+ /// unload took it. They stay on screen because the app deliberately keeps a+ /// transcript across lifecycle actions, but they are not in the model's+ /// context any more, and the transcript draws a break to say so. Keeping+ /// them here rather than in `conversation` is what preserves that type's+ /// invariant: its turns are exactly the model's context.+ public private(set) var archivedPairs: [(user: AppChatTurn, assistant: AppChatTurn)] = []+ /// The epoch the inference side has actually been told to open. Nil after a+ /// load or unload, both of which rebuild or release the KV; the next turn+ /// opens the conversation again before it sends anything.+ private var serviceEpoch: UUID?public var outputText: String = ""public var runState: RunState = .idlepublic var runtimeOptions = AppRuntimeOptions()@@ -41,10 +55,9 @@ public final class AppModel {public var topP: Double = 0.95public private(set) var newlineShortcut: AppNewlineShortcut = .returnpublic private(set) var showPromptExamples: Bool = true- public private(set) var sentPromptBehavior: AppSentPromptBehavior = .keep- public private(set) var loadModelOnLaunch: Bool = false/// Whether launching the app should load the model straight away. Off by/// default, because loading takes minutes and holds gigabytes.+ public private(set) var loadModelOnLaunch: Bool = falsepublic var diagnostics: AppDiagnostics?public var error: AppInferenceError?public var installState: AppModelInstallState = .idle@@ -159,7 +172,6 @@ public final class AppModel {self.topP = settings.topPself.newlineShortcut = settings.newlineShortcutself.showPromptExamples = settings.showPromptExamples- self.sentPromptBehavior = settings.sentPromptBehaviorself.loadModelOnLaunch = settings.loadModelOnLaunchself.installationStatus = AppModelInstallationProbe.status(at: directory)self.visionInstallationStatus = AppVisionPackInstallationProbe.status(at: directory)@@ -378,6 +390,9 @@ public final class AppModel {!isRunning && !isAddingImages && isModelAvailable && !loadState.isLoading&& !isVisionCompanionOperationInProgress&& !hasStaleLoadedRuntime+ // A conversation whose KV no longer matches it cannot take another+ // turn; only New chat clears that.+ && conversation.canSend&& (!promptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty|| !imageAttachments.isEmpty)}@@ -385,14 +400,62 @@ public final class AppModel {public var canCancel: Bool { isRunning && !isCancellationPending }public var hasOutputTranscript: Bool {- !outputPromptText.isEmpty || !outputImageAttachments.isEmpty || !outputText.isEmpty+ !archivedPairs.isEmpty+ || !conversation.isEmpty+ || !outputPromptText.isEmpty || !outputImageAttachments.isEmpty+ || !outputText.isEmpty+ }++ public var shouldShowPromptExamples: Bool {+ showPromptExamples+ && promptText.isEmpty+ && !isRunning+ && !hasOutputTranscript}public var outputResponsePlainText: String {generationTranscriptMailbox?.completeText ?? outputText}+ /// Completed turns the transcript draws *above* the live one.+ ///+ /// The live fields keep holding the last finished turn between runs — that+ /// is what leaves an answer on screen after it ends — so while nothing is+ /// decoding the newest pair is drawn live and must not also appear here.+ /// One property, used by both the transcript and Copy Conversation, so the+ /// two cannot disagree about which turn is which.+ public var transcriptHistory: [(user: AppChatTurn, assistant: AppChatTurn)] {+ let pairs = conversation.completedPairs+ let live = conversation.hasTurnInFlight ? pairs+ : (pairs.isEmpty ? pairs : Array(pairs.dropLast()))+ return archivedPairs + live+ }++ /// Where the transcript draws "earlier turns are no longer in context",+ /// counted in pairs from the top. Nil when everything on screen is still in+ /// the model's context.+ public var transcriptContextBreak: Int? {+ archivedPairs.isEmpty ? nil : archivedPairs.count+ }+public var outputConversationPlainText: String {+ var history: [String] = []+ for pair in transcriptHistory {+ var prompt = pair.user.text+ if !pair.user.images.isEmpty {+ let names = pair.user.images.map(\.displayName).joined(separator: ", ")+ prompt = prompt.isEmpty ? "[images: \(names)]" : "[images: \(names)]\n\(prompt)"+ }+ history.append("You:\n\(prompt)")+ history.append("Answer:\n\(pair.assistant.text)")+ }+ let live = liveConversationPlainText+ if history.isEmpty { return live }+ if live.isEmpty { return history.joined(separator: "\n\n") }+ return history.joined(separator: "\n\n") + "\n\n" + live+ }++ private var liveConversationPlainText: String {let response = outputResponsePlainTextswitch (outputPromptText.isEmpty, response.isEmpty) {case (true, true):@@ -485,6 +548,7 @@ public final class AppModel {activeRunRuntimeKey = nilloadedRuntimeKey = nilloadState = .notLoaded+ endConversationForReleasedKV()diagnostics = nilerror = nilphase = .idle@@ -533,11 +597,6 @@ public final class AppModel {persistSettings()}- public func setSentPromptBehavior(_ behavior: AppSentPromptBehavior) {- guard sentPromptBehavior != behavior else { return }- sentPromptBehavior = behavior- persistSettings()- }public func setLoadModelOnLaunch(_ enabled: Bool) {guard loadModelOnLaunch != enabled else { return }@@ -570,7 +629,7 @@ public final class AppModel {/// Room left for the prompt when working out how many images fit. The/// runtime still rejects a combination that does not fit, so this only has/// to be a defensible reserve rather than an exact prompt measurement.- static let reservedPromptTokens = 1_024+ nonisolated static let reservedPromptTokens = 1_024/// How many images this conversation can hold, derived from the context/// exactly as the server derives its budget. It used to be a fixed four,@@ -580,9 +639,24 @@ public final class AppModel {// The context a run will actually use, which is the loaded session's// until it is reloaded. Capping on the pending setting instead let the// composer accept images the request then refused.- max(1, VisionImageTokenBudget.capacity(- maxContext: effectiveMaxContextTokens,- reservedTextTokens: Self.reservedPromptTokens))+ //+ // The conversation counts against the same window, and the request+ // reserves it (`AppGenerationRequest.validate`). Reserving only a fixed+ // 1,024 here meant that past that point the composer kept offering+ // images Send would refuse — accepted on attach, rejected on the button.+ Self.imageAttachmentCapacity(+ maxContextTokens: effectiveMaxContextTokens,+ conversationTokens: conversation.kvTokens)+ }++ nonisolated static func imageAttachmentCapacity(+ maxContextTokens: Int,+ conversationTokens: Int?+ ) -> Int {+ guard let conversationTokens else { return 0 }+ return VisionImageTokenBudget.capacity(+ maxContext: maxContextTokens,+ reservedTextTokens: max(reservedPromptTokens, conversationTokens))}/// The context a generation would run with right now.@@ -823,10 +897,21 @@ public final class AppModel {guard let self, generation == self.unloadGeneration else { return }self.loadedRuntimeKey = nilself.loadState = .notLoaded+ endConversationForReleasedKV()self.clearUnloadTask(generation: generation)}}+ /// Ends the conversation because the KV behind it is gone.+ ///+ /// `applyLoadState`'s `.notLoaded` branch does this too, but nothing reaches+ /// it: every production transition to `.notLoaded` assigns `loadState`+ /// directly. Calling this from those sites is what actually runs it.+ private func endConversationForReleasedKV() {+ serviceEpoch = nil+ archiveConversationContext()+ }+public func unloadModel() {guard canUnloadModel, let lifecycle = client as? AppModelLifecycleClient else { return }loadState = .unloading@@ -838,6 +923,7 @@ public final class AppModel {self.loadedRuntimeKey = nilself.liveMemoryBytes = nilself.loadState = .notLoaded+ endConversationForReleasedKV()self.clearUnloadTask(generation: generation)}}@@ -1376,6 +1462,7 @@ public final class AppModel {installTask = nilmodelPathText = directory.pathloadState = .notLoaded+ endConversationForReleasedKV()refreshVisionInstallReadiness(at: directory)}}@@ -1474,7 +1561,6 @@ public final class AppModel {topP = settings.topPnewlineShortcut = settings.newlineShortcutshowPromptExamples = settings.showPromptExamples- sentPromptBehavior = settings.sentPromptBehaviorloadModelOnLaunch = settings.loadModelOnLaunch}@@ -1491,7 +1577,6 @@ public final class AppModel {prefillEnabled: runtimeOptions.prefillEnabled,newlineShortcut: newlineShortcut,showPromptExamples: showPromptExamples,- sentPromptBehavior: sentPromptBehavior,visionResidencyPolicy: runtimeOptions.visionResidencyPolicy,rdadvisePolicy: runtimeOptions.rdadvisePolicy,loadModelOnLaunch: loadModelOnLaunch)@@ -1555,9 +1640,24 @@ public final class AppModel {switch state {case .notLoaded:loadedRuntimeKey = nil+ // Unloading released the runner and the KV, so whatever lineage was+ // open no longer has tokens behind it.+ serviceEpoch = nil+ archiveConversationContext()case .loading, .cancelling, .unloading:breakcase .ready(_, let seconds):+ // A load builds a new runner and an empty KV. The service ends the+ // lineage on its side for the same reason; leaving the app's epoch+ // in place would have the next turn claim to resume onto a cache+ // that had just been rebuilt.+ serviceEpoch = nil+ // And the conversation itself is gone with that KV. Keeping the+ // turn list would leave the app numbering turns from where it left+ // off while the service, having just ended the lineage, expects+ // zero — so the gate would refuse the next turn and every turn+ // after it, for the rest of the session.+ archiveConversationContext()loadedRuntimeKey = pendingExplicitLoadRuntimeKey?? activeRunRuntimeKey?? currentRuntimeKey@@ -1574,6 +1674,18 @@ public final class AppModel {/// Releases the transcript's own references to the images it was showing./// They are separate files from the composer's, so nothing else frees them.+ /// Releases every image the conversation is holding — each turn's, the+ /// archived turns', and the newest turn's.+ private func releaseConversationImages() {+ for pair in archivedPairs {+ for attachment in pair.user.images { attachmentStore.remove(attachment) }+ }+ for turn in conversation.turns {+ for attachment in turn.images { attachmentStore.remove(attachment) }+ }+ releaseTranscriptImages()+ }+private func releaseTranscriptImages() {for attachment in outputImageAttachments { attachmentStore.remove(attachment) }outputImageAttachments = []@@ -1582,7 +1694,7 @@ public final class AppModel {/// Deletes every file this session staged. Called when the app is quitting,/// which is the only moment they are all certainly unwanted.public func releaseAllAttachments() {- releaseTranscriptImages()+ releaseConversationImages()for attachment in imageAttachments { attachmentStore.remove(attachment) }imageAttachments.removeAll()attachmentStore.removeAll()@@ -1623,26 +1735,90 @@ public final class AppModel {return memorySampler.occupiedSample()}- public func clearOutput() {+ /// Ends the conversation and starts an empty one.+ ///+ /// There is no history to recover it from, so the window confirms before+ /// calling this when the transcript is not empty.+ public func newChat() {guard !isRunning else { return }+ // Every turn holds its own hard links. Dropping the turn list without+ // releasing them leaked one staged file per image per turn until quit:+ // `releaseTranscriptImages` only ever covered the newest turn, which is+ // why a single-turn test passed.+ releaseConversationImages()+ archivedPairs.removeAll()+ conversation.startNew()outputPromptText = ""releaseTranscriptImages()outputText = ""generationTranscriptMailbox?.reset()diagnostics = nilerror = nil+ // Only the intent is recorded here; the next turn opens the new lineage+ // on the inference side. Resetting eagerly as well raced that opening+ // and sent two resets for one new chat, and it buys nothing: the KV+ // allocation is fixed, so an unsent new chat holds no extra memory.+ serviceEpoch = nil+ }++ /// Starts an empty conversation because the KV behind the old one is gone.+ ///+ /// Distinct from `newChat()`: the user did not ask for this. The transcript+ /// stays — lifecycle actions are not supposed to discard it — but its turns+ /// move to `archivedPairs`, because the model can no longer see them. The+ /// alternative, letting `conversation` keep counting, desynchronises the app+ /// from the service's gate, which has just gone back to expecting turn zero;+ /// the gate would then refuse every turn for the rest of the session.+ private func archiveConversationContext() {+ var carried = conversation.completedPairs+ // The live fields hold the newest finished turn between runs, and it is+ // already in `completedPairs`; nothing extra to carry.+ if carried.isEmpty, !outputPromptText.isEmpty {+ carried = [(user: AppChatTurn(role: .user, text: outputPromptText,+ images: outputImageAttachments),+ assistant: AppChatTurn(role: .assistant, text: outputText))]+ }+ archivedPairs.append(contentsOf: carried)+ conversation.startNew()+ // The archived pairs are what the transcript draws now. Leaving the+ // live fields holding the newest of them would draw that turn twice,+ // once as history and once as the turn still on screen.+ if !carried.isEmpty {+ outputPromptText = ""+ outputText = ""+ outputImageAttachments = []+ generationTranscriptMailbox?.reset()+ }+ }++ /// Opens the conversation on the inference side if it has not been opened+ /// yet. Called before every turn: a load or an unload ends the lineage+ /// there without the app being asked, and the next turn has to re-open it+ /// rather than resume onto a KV that was rebuilt empty.+ private func openConversationIfNeeded() async throws {+ guard serviceEpoch != conversation.epoch else { return }+ guard let lifecycle = client as? AppModelLifecycleClient else { return }+ try await lifecycle.resetConversation(epoch: conversation.epoch)+ serviceEpoch = conversation.epoch}public func run() {guard canRun else { return }+ // Reserved before the request is built, so the position the service+ // will check is the position the transcript shows.+ guard let ticket = conversation.beginTurn(text: promptText, images: []) else {+ return+ }var request: AppGenerationRequestdo {- request = try makeRequest()+ request = try makeRequest(ticket: ticket)} catch let appError as AppInferenceError {+ conversation.abandonTurn()error = appErrorreturn} catch {let appError = AppInferenceError.unknown("\(error)")+ conversation.abandonTurn()self.error = appErrorreturn}@@ -1660,6 +1836,7 @@ public final class AppModel {}} catch {for attachment in retained { attachmentStore.remove(attachment) }+ conversation.abandonTurn()imageAttachmentError = String(describing: error)self.error = .invalidRequest("Could not prepare the attached images for this run: \(error)")@@ -1671,8 +1848,12 @@ public final class AppModel {generationTranscriptMailbox?.reset()runIdentity &+= 1+ let generation = runIdentityoutputPromptText = request.prompt- releaseTranscriptImages()+ // Not released: every turn of a conversation keeps its own images for+ // as long as the conversation shows them. They are hard links to files+ // that already exist, so holding them costs no additional bytes.+ conversation.attachImagesToPendingTurn(retained)outputImageAttachments = retainedoutputText = ""diagnostics = nil@@ -1691,28 +1872,29 @@ public final class AppModel {sampleLiveMemory()phase = .prefillrunState = .running- if sentPromptBehavior == .clear {- promptText = ""- // Images used to survive a cleared prompt, so the next Run silently- // re-attached them to a completely different message. Dropping them- // is safe because the request above was repointed at the retained- // links: removing these files cannot pull the ground out from under- // a run that has not opened its images yet.- for attachment in imageAttachments { attachmentStore.remove(attachment) }- imageAttachments.removeAll()- imageAttachmentError = nil- }+ // A chat composer always clears. Keeping the sent turn in the box means+ // the next message starts as a copy of the last one, and the images+ // silently re-attach to a different message. Dropping them is safe+ // because the request above was repointed at the retained links:+ // removing these files cannot pull the ground out from under a run that+ // has not opened its images yet. A refused turn puts both back through+ // `restoreComposer`.+ promptText = ""+ for attachment in imageAttachments { attachmentStore.remove(attachment) }+ imageAttachments.removeAll()+ imageAttachmentError = nil- runTask = Task.detached { [weak self, client, request] in+ runTask = Task.detached { [weak self, client, request, generation] inguard let self else { return }do {+ try await self.openConversationIfNeeded()for try await event in client.generate(request) {- await self.apply(event)+ await self.apply(event, generation: generation)}} catch let appError as AppInferenceError {- await self.finishStreamFailure(appError)+ await self.finishStreamFailure(appError, generation: generation)} catch {- await self.finishStreamFailure(.unknown("\(error)"))+ await self.finishStreamFailure(.unknown("\(error)"), generation: generation)}}}@@ -1723,7 +1905,9 @@ public final class AppModel {client.cancel()}- public func makeRequest() throws -> AppGenerationRequest {+ public func makeRequest(+ ticket: AppConversation.Ticket? = nil+ ) throws -> AppGenerationRequest {// A run executes against the session that is actually loaded. Sending// the current settings instead meant that changing Context, Slots or// image residency and pressing Generate — without reloading first —@@ -1744,12 +1928,27 @@ public final class AppModel {repetitionPenalty: 1.0,runtimeOptions: effective.options(prefillEnabled: runtimeOptions.prefillEnabled,- prefillChunkTokens: runtimeOptions.prefillChunkTokens))+ prefillChunkTokens: runtimeOptions.prefillChunkTokens),+ // Carried whether or not a ticket exists: the image budget has to+ // fit around the conversation even while the composer is only being+ // validated.+ // The decode service overrides this from its own gate, but the+ // in-process client reads it directly — and without it that client+ // ran every turn through the single-prompt path while the app drew a+ // growing transcript, so the model saw only the newest message.+ continuesConversation: ticket != nil,+ // Unknown means the runtime committed a turn but did not report its+ // position. Reserve the whole window: text can still continue on+ // the service's own exact state, while every image fails closed.+ conversationTokens: conversation.kvTokens ?? effective.maxContextTokens,+ conversationEpoch: ticket?.epoch,+ turnIndex: ticket?.index)try request.validate(requireModelDirectory: true)return request}- func apply(_ event: AppInferenceEvent) {+ func apply(_ event: AppInferenceEvent, generation: Int? = nil) {+ guard generation == nil || generation == runIdentity else { return }switch event {case .memorySample:sampleLiveMemory()@@ -1783,6 +1982,7 @@ public final class AppModel {hasHandledTerminalEvent = truematerializeServiceTranscript()self.diagnostics = diagnostics+ conversation.completeTurn(text: outputText, diagnostics: diagnostics)finishTerminalRun()}@@ -1792,6 +1992,28 @@ public final class AppModel {materializeServiceTranscript()self.diagnostics = diagnosticserror = .cancelled+ // A `.cancelled` event means the run threw `CancellationError`, and the+ // conversation rewound the turn: its tokens are not in the KV, and the+ // service did not count it either. Counting it here put the app one+ // ahead for the rest of the conversation, so the next turn carried an+ // index the gate refused — and that refusal reached the user as+ // "decode service runtime profile changed during generation".+ //+ // A stop that lands at a token boundary is a different event: the run+ // returns normally with `.cancelled` as its *stop reason*, arrives as+ // `.finished`, and is committed by `finishSuccessfully`.+ // Not counted. The live fields are not part of `conversation.turns`, so+ // what stays on screen is the stopped turn as the current one, exactly+ // as the single-prompt path left it — the next run replaces it, and it+ // never enters the history the transcript freezes.+ //+ // The turn itself is handed back rather than dropped: discarding it lost+ // the user's message and stranded its retained image links, which the+ // next run overwrote without releasing — one staged file per image,+ // until quit.+ if let abandoned = conversation.abandonTurn() {+ restoreComposer(from: abandoned)+ }finishTerminalRun()}@@ -1804,10 +2026,42 @@ public final class AppModel {guard !hasHandledTerminalEvent else { return }hasHandledTerminalEvent = trueerror = appError+ let abandoned: AppChatTurn?+ if case .conversationLineageLost = appError {+ // The transcript stays readable; nothing further can be sent until+ // New chat.+ abandoned = conversation.markLineageLost()+ } else {+ // The runtime rewound this turn, so it is in neither the KV nor the+ // transcript. Give the user their message back instead of making+ // them retype it.+ abandoned = conversation.abandonTurn()+ }+ if let abandoned {+ restoreComposer(from: abandoned)+ }finishTerminalRun()}- private func finishStreamFailure(_ appError: AppInferenceError) {+ /// Puts a turn that never reached the model back in the composer.+ ///+ /// The images move with it: they are this turn's retained links, and the+ /// turn is gone from the transcript, so nothing else refers to them. Losing+ /// them here would silently drop attachments the user had picked.+ private func restoreComposer(from turn: AppChatTurn) {+ if promptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ promptText = turn.text+ }+ if imageAttachments.isEmpty, !turn.images.isEmpty {+ imageAttachments = turn.images+ } else {+ for attachment in turn.images { attachmentStore.remove(attachment) }+ }+ outputImageAttachments = []+ }++ private func finishStreamFailure(_ appError: AppInferenceError, generation: Int) {+ guard generation == runIdentity else { return }materializeServiceTranscript()finishWithError(appError)}diff --git a/Sources/TurboFieldfareApp/Mac/App/RootView.swift b/Sources/TurboFieldfareApp/Mac/App/RootView.swiftindex b90239fc..ad1bce9a 100644--- a/Sources/TurboFieldfareApp/Mac/App/RootView.swift+++ b/Sources/TurboFieldfareApp/Mac/App/RootView.swift@@ -91,7 +91,7 @@ struct RootView: View {private var conversationChrome: some View {VStack(spacing: 10) {ErrorBanner(model: model)- if model.promptText.isEmpty && model.showPromptExamples && !model.isRunning {+ if model.shouldShowPromptExamples {PromptExamplesView { preset inmodel.promptText = preset.prompt}diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swiftindex f7f7c86d..a4828727 100644--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift@@ -114,11 +114,6 @@ struct TurboFieldfareMacApp: App {Text("Show").tag(true)Text("Hide").tag(false)}- Picker("After Sending", selection: sentPromptBehaviorBinding) {- ForEach(AppSentPromptBehavior.allCases) { behavior in- Text(behavior.settingsLabel).tag(behavior)- }- }Picker("Load Model At Launch", selection: loadModelOnLaunchBinding) {Text("Off").tag(false)Text("On").tag(true)@@ -168,11 +163,4 @@ struct TurboFieldfareMacApp: App {}}- private var sentPromptBehaviorBinding: Binding<AppSentPromptBehavior> {- Binding {- model.sentPromptBehavior- } set: { behavior in- model.setSentPromptBehavior(behavior)- }- }}diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swiftindex dfc65a31..eedc1b02 100644--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift@@ -20,7 +20,14 @@ struct StatusHUDView: View {Spacer(minLength: 12)if showsMetrics {HUDMetricView(value: rateText, label: "tok/s", animated: !model.isRunning)- HUDMetricView(value: tokensText, label: "tokens", animated: !model.isRunning)+ if showsContext {+ // No info button beside this one. The memory figure has one+ // because `phys_footprint` is genuinely misread; "20/8.2K"+ // is not, and the same words are on hover.+ HUDMetricView(value: contextText, label: "context",+ animated: !model.isRunning)+ .help(contextHelp)+ }HStack(spacing: 2) {HUDMetricView(value: memoryText, label: "memory", animated: !model.isRunning).help(memoryHelp)@@ -41,17 +48,49 @@ struct StatusHUDView: View {.gesture(WindowDragGesture())}+ /// Shown once a conversation is holding anything. A gauge that reads 0 for+ /// the whole of a single-prompt session is noise.+ private var showsContext: Bool {+ liveContextTokens.map { $0 > 0 } ?? !model.conversation.isEmpty+ }++ /// The KV position now, not at the end of the last turn.+ private var liveContextTokens: Int? {+ guard model.isRunning else { return model.conversation.kvTokens }+ guard model.livePrefillDone > 0 || model.liveTokenCount > 0 else {+ return model.conversation.kvTokens+ }+ return ConversationContextPresentation.liveTokens(+ prefillDone: model.livePrefillDone,+ prefillTotal: model.livePrefillTotal,+ generated: model.liveTokenCount,+ committed: model.conversation.kvTokens ?? 0)+ }++ private var contextText: String {+ guard let liveContextTokens else { return "\u{2014}" }+ return ConversationContextPresentation.gauge(+ kvTokens: liveContextTokens,+ maxContext: model.effectiveMaxContextTokens)+ }++ private var contextHelp: String {+ guard let liveContextTokens else {+ return "The decode service did not report the committed context position. "+ + "Start a new chat before adding images."+ }+ return ConversationContextPresentation.explanation(+ kvTokens: liveContextTokens,+ maxContext: model.effectiveMaxContextTokens,+ cachedTokens: model.diagnostics?.cachedPromptTokens)+ }+private var rateText: String {if model.phase == .decode { return MetricFormat.rate(model.liveTokensPerSecond) }if let d = model.diagnostics { return MetricFormat.rate(d.tokensPerSecond) }return "\u{2014}"}- private var tokensText: String {- if model.isRunning { return "\(model.liveTokenCount)" }- if let d = model.diagnostics { return "\(d.generatedTokens)" }- return "\u{2014}"- }/// `phys_footprint`: what this process is charged. Measured, not assumed —/// the model and image tower weights are memory-mapped and read by the GPU,diff --git a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swiftindex 4f4e53bd..8d2cd4a4 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift@@ -24,27 +24,6 @@ struct OutputPaneView: View {responseCopyFeedbackID = nil}}- .contextMenu {- Button("Copy response") {- copyResponse()- }- .disabled(model.outputResponsePlainText.isEmpty)-- Button("Copy prompt") {- copy(model.outputPromptText)- }- .disabled(model.outputPromptText.isEmpty)-- Button("Copy conversation") {- copy(model.outputConversationPlainText)- }- .disabled(model.outputConversationPlainText.isEmpty)-- Divider()-- Button("Clear") { model.clearOutput() }- .disabled(model.isRunning || !model.hasOutputTranscript)- }}private var placeholder: some View {@@ -61,6 +40,12 @@ struct OutputPaneView: View {private var transcript: some View {IncrementalTranscriptView(+ history: model.transcriptHistory,+ contextBreak: model.transcriptContextBreak,+ conversationEpoch: model.conversation.epoch,+ lastAnswer: model.outputResponsePlainText,+ conversationPlainText: model.outputConversationPlainText,+ requestNewChat: model.isRunning ? nil : { model.newChat() },prompt: model.outputPromptText,images: model.outputImageAttachments,output: model.outputText,@@ -101,20 +86,20 @@ struct OutputPaneView: View {}.buttonStyle(.plain).accessibilityLabel(responseCopyFeedbackID == nil- ? "Copy response"+ ? "Copy last answer": "Response copied").accessibilityHint("Copies only the generated answer").help(responseCopyFeedbackID == nil- ? "Copy response"+ ? "Copy last answer": "Response copied")}private var emptyPlaceholderContent: some View {VStack(spacing: 8) {if !needsModelLoad {- Text("Choose a predefined example or write your own prompt.")+ Text("Start a chat, or choose a predefined example.").font(.headline)- Text("Describe the goal, relevant context, and any constraints.")+ Text("Each message keeps the ones before it in context.").font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center)@@ -350,6 +335,14 @@ private struct LoadingModelText: View {}private struct IncrementalTranscriptView: NSViewRepresentable {+ var history: [(user: AppChatTurn, assistant: AppChatTurn)] = []+ /// Pairs above this index are on screen but no longer in the model's+ /// context. Nil when everything drawn is still in the KV.+ var contextBreak: Int?+ var conversationEpoch: UUID = UUID()+ var lastAnswer: String = ""+ var conversationPlainText: String = ""+ var requestNewChat: (() -> Void)?var prompt: Stringvar images: [AppImageAttachment] = []var output: String@@ -388,6 +381,14 @@ private struct IncrementalTranscriptView: NSViewRepresentable {var isTerminal = falsevar showsPrefillPlaceholder = falsevar runIdentity = 0+ /// Decides what the transcript owes the conversation; see+ /// `TranscriptSyncPlanner`.+ var planner = TranscriptSyncPlanner()+ /// Supplied by the pane so the transcript's menu can offer the whole+ /// chat and New chat without reaching back into SwiftUI state.+ var lastAnswer = ""+ var conversationPlainText = ""+ var requestNewChat: (() -> Void)?/// Holds the view at the bottom from the moment a run starts until its/// answer begins. One scroll is not enough: image thumbnails finish/// loading after it and push the content back down, which is exactly@@ -401,6 +402,16 @@ private struct IncrementalTranscriptView: NSViewRepresentable {func attach(scrollView: NSScrollView, textView: NSTextView) {self.scrollView = scrollViewself.textView = textView+ // Right-click inside a turn offers that turn's answer, so a+ // transcript of several turns has an unambiguous copy affordance+ // rather than one floating button that reads as the first turn's.+ guard let transcript = textView as? TranscriptTextView else { return }+ transcript.answerAtCharacterIndex = { [weak self] index in+ self?.documentController.answer(at: index)+ }+ transcript.lastAnswerText = { [weak self] in self?.lastAnswer ?? "" }+ transcript.conversationText = { [weak self] in self?.conversationPlainText ?? "" }+ transcript.startNewChat = { [weak self] in self?.requestNewChat?() }guard timer == nil else { return }// Auto-follow yields the instant the reader scrolls. Without this,// holding the view at the bottom through prefill fought anyone@@ -423,6 +434,12 @@ private struct IncrementalTranscriptView: NSViewRepresentable {}func synchronize(+ history: [(user: AppChatTurn, assistant: AppChatTurn)],+ contextBreak: Int?,+ conversationEpoch: UUID,+ lastAnswer: String,+ conversationPlainText: String,+ requestNewChat: (() -> Void)?,prompt: String,images: [AppImageAttachment],output: String,@@ -434,7 +451,15 @@ private struct IncrementalTranscriptView: NSViewRepresentable {// A new run always goes to the bottom, whatever the reader was// looking at: it is the thing they just asked for.let startedNewRun = runIdentity != self.runIdentity+ let firstSynchronize = self.runIdentity == 0 && planner.renderedHistory == 0self.runIdentity = runIdentity+ self.lastAnswer = lastAnswer+ self.conversationPlainText = conversationPlainText+ self.requestNewChat = requestNewChat+ adoptConversation(conversationEpoch, history: history,+ contextBreak: contextBreak,+ startedNewRun: startedNewRun,+ firstSynchronize: firstSynchronize)self.mailbox = mailboxself.prompt = promptlet prefixIdentifier = images.map {@@ -462,6 +487,81 @@ private struct IncrementalTranscriptView: NSViewRepresentable {if startedNewRun || shouldFollowNow() { scrollToBottom() }}+ /// Keeps the drawn document in step with the conversation.+ ///+ /// Three cases, and only the middle one happens per turn:+ /// a new chat clears everything; a new run seals the turn already drawn+ /// into the history above it; and a coordinator that has drawn nothing+ /// but finds a conversation already under way redraws that history once.+ /// Sealing is what keeps the cost per token proportional to the answer+ /// rather than to the whole conversation.+ /// Executes the planner's steps. The decisions themselves live in+ /// `TranscriptSyncPlanner`, where they are testable — three defects hid+ /// here precisely because nothing could reach them.+ private func adoptConversation(+ _ epoch: UUID,+ history: [(user: AppChatTurn, assistant: AppChatTurn)],+ contextBreak: Int?,+ startedNewRun: Bool,+ firstSynchronize: Bool+ ) {+ guard let textView, let storage = textView.textStorage else { return }+ let steps = planner.plan(TranscriptSyncPlanner.Input(+ epoch: epoch, historyCount: history.count, contextBreak: contextBreak,+ startedNewRun: startedNewRun, firstSynchronize: firstSynchronize))+ guard !steps.isEmpty else { return }++ storage.beginEditing()+ for step in steps {+ switch step {+ case .reset:+ documentController.resetTranscript(storage: storage)+ promptPrefixIdentifier = ""+ promptPrefix = NSAttributedString()+ prompt = ""+ case .sealDrawnTurn:+ let before = documentController.frozenLength+ documentController.sealTurn(storage: storage)+ if documentController.frozenLength == before {+ // It froze nothing, so the pair is still owed; consuming+ // it would drop a turn that is in the KV from the+ // transcript for good.+ planner.sealFoundNothingToFreeze(historyCount: history.count)+ }+ case .drawPair(let index):+ guard index < history.count else { break }+ let pair = history[index]+ _ = documentController.synchronize(+ storage: storage,+ prompt: pair.user.text,+ response: pair.assistant.text,+ isTerminal: true,+ // Cached thumbnails only. A history image whose+ // thumbnail has not been decoded yet is dropped rather+ // than blocking the redraw; the same degradation the+ // live path already accepts.+ promptPrefix: Self.makePromptPrefix(pair.user.images),+ promptPrefixIdentifier: pair.user.images+ .map { "\($0.id.uuidString):\($0.sha256)" }+ .joined(separator: ","))+ documentController.sealTurn(storage: storage)+ prompt = ""+ promptPrefixIdentifier = ""+ case .appendContextBreak:+ let before = documentController.frozenLength+ documentController.appendContextBreak(+ storage: storage,+ text: "Earlier turns are no longer in the model's context")+ // Only marked when it actually wrote. Latching it on a+ // refusal suppressed the break for the rest of the session.+ if documentController.frozenLength != before {+ planner.markContextBreakDrawn()+ }+ }+ }+ storage.endEditing()+ }+func scrollToBottom() {guard let textView else { return }if let textContainer = textView.textContainer {@@ -748,6 +848,12 @@ private struct IncrementalTranscriptView: NSViewRepresentable {guard let textView = scrollView.documentView as? NSTextView else { return }context.coordinator.attach(scrollView: scrollView, textView: textView)context.coordinator.synchronize(+ history: history,+ contextBreak: contextBreak,+ conversationEpoch: conversationEpoch,+ lastAnswer: lastAnswer,+ conversationPlainText: conversationPlainText,+ requestNewChat: requestNewChat,prompt: prompt,images: images,output: output,@@ -786,9 +892,9 @@ private struct TranscriptPreview: View {Image(systemName: "cube.transparent").font(.title2).foregroundStyle(.quaternary)- Text("Choose a predefined example or write your own prompt.")+ Text("Start a chat, or choose a predefined example.").font(.headline)- Text("Describe the goal, relevant context, and any constraints.")+ Text("Each message keeps the ones before it in context.").foregroundStyle(.secondary)}.frame(width: 720, height: 420)diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swiftindex 2f6e406c..0dcfa744 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift@@ -67,13 +67,13 @@ struct PromptComposerView: View {"That clipboard content is not an image TurboFieldfare can read.")},onDropTargeted: { isImageDropTargeted = $0 })- .accessibilityLabel("Prompt")+ .accessibilityLabel("Message").frame(height: editorHeight).overlay(alignment: .topLeading) {if model.promptText.isEmpty {// Matches the NSTextView text origin: 5pt line fragment// padding, no vertical inset.- Text("Prompt")+ Text("Message").font(.body).foregroundStyle(.tertiary).padding(.leading, 5)@@ -90,7 +90,7 @@ struct PromptComposerView: View {}private var editorHeight: CGFloat {- model.promptText.isEmpty && model.showPromptExamples ? 46 : 84+ model.shouldShowPromptExamples ? 46 : 84}private var footer: some View {@@ -107,7 +107,9 @@ struct PromptComposerView: View {.disabled(model.isRunning || model.isAddingImages|| model.imageAttachments.count>= model.maximumImageAttachments)- .help("Add images")+ .help(model.maximumImageAttachments == 0+ ? "Start a new chat to make room for images."+ : "Add images")}promptTipsSpacer()@@ -219,15 +221,15 @@ struct PromptComposerView: View {.help("Clear text and images")} else if !model.isRunning && model.hasOutputTranscript {Button {- model.clearOutput()+ model.newChat()} label: {- Label("Clear output", systemImage: "trash")+ Label("New chat", systemImage: "trash").labelStyle(.iconOnly).frame(width: 28, height: 28).contentShape(Circle())}.buttonStyle(.borderless)- .help("Clear output")+ .help("Start a new chat")}}}@@ -265,7 +267,7 @@ private struct PromptTextEditor: NSViewRepresentable {textView.textContainerInset = .zerotextView.textContainer?.lineFragmentPadding = 5textView.textContainer?.widthTracksTextView = true- textView.setAccessibilityLabel("Prompt")+ textView.setAccessibilityLabel("Message")// A promise-only drag — Photos, Mail, most browsers — never reaches// `draggingEntered` unless its types are registered here.textView.registerForDraggedTypes(diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swiftindex efd49661..f62f499c 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.6.0"+ public static let fallbackShortVersion = "0.7.0"private static let licenseURL = URL(string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!diff --git a/Sources/TurboFieldfareApp/MacPresentation/ConversationContextPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/ConversationContextPresentation.swiftnew file mode 100644index 00000000..22878d36--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/ConversationContextPresentation.swift@@ -0,0 +1,93 @@+import Foundation++/// What the HUD says about the conversation's place in the context window, and+/// about how much of the last turn was served from the cache.+///+/// A cache nobody can see is one that can regress to nothing without a single+/// bug report — LM Studio and Ollama have both shipped that state, where reuse+/// silently stopped and users only noticed as slowness. The figure is reported+/// per turn for the same reason the OpenAI usage payload reports+/// `cached_tokens`.+public enum ConversationContextPresentation {+ /// Compact gauge for the HUD: tokens held against the window.+ public static func gauge(kvTokens: Int, maxContext: Int) -> String {+ guard maxContext > 0 else { return "\u{2014}" }+ return "\(compact(kvTokens))/\(compact(maxContext))"+ }++ /// What the KV holds *right now*, during a turn.+ ///+ /// The committed count only moves when a turn finishes, so a gauge reading+ /// it sits still through prefill and decode — exactly while the number it+ /// reports is changing — and then jumps. These three are the live figures+ /// the run already reports.+ ///+ /// `prefillDone` is absolute: `runRawCompletion` reports progress as+ /// `cachedPromptTokens + done`, so during prefill it *is* the KV position.+ /// Once a token has been sampled the prompt is fully in. The newest sampled+ /// token is still the boundary for the next producer call, so only the+ /// earlier generated tokens are committed.+ public static func liveTokens(prefillDone: Int,+ prefillTotal: Int,+ generated: Int,+ committed: Int) -> Int {+ if generated > 0 { return prefillTotal + generated - 1 }+ if prefillDone > 0 { return prefillDone }+ // Nothing reported yet — an image is still encoding, or the first chunk+ // has not landed. The committed figure is the last thing that was true.+ return committed+ }++ /// Percentage of the window in use, clamped, for a progress affordance.+ public static func fraction(kvTokens: Int, maxContext: Int) -> Double {+ guard maxContext > 0 else { return 0 }+ return min(1, max(0, Double(kvTokens) / Double(maxContext)))+ }++ /// True once the conversation is close enough to the wall that the user+ /// should be told before a turn is refused rather than after.+ public static func isNearingLimit(kvTokens: Int, maxContext: Int) -> Bool {+ fraction(kvTokens: kvTokens, maxContext: maxContext) >= 0.8+ }++ /// The words behind the gauge. Names the cached figure explicitly, because+ /// "it feels fast" is not evidence that anything was reused.+ public static func explanation(+ kvTokens: Int,+ maxContext: Int,+ cachedTokens: Int?+ ) -> String {+ var parts: [String] = []+ parts.append(+ "This chat is holding \(number(kvTokens)) of \(number(maxContext)) context tokens.")+ if let cachedTokens, cachedTokens > 0 {+ parts.append(+ "The last turn reused \(number(cachedTokens)) of them instead of "+ + "processing the conversation again.")+ } else if cachedTokens != nil {+ parts.append("The last turn had nothing to reuse; it started a conversation.")+ }+ if isNearingLimit(kvTokens: kvTokens, maxContext: maxContext) {+ parts.append(+ "When the window fills, a turn is refused rather than silently "+ + "dropping earlier ones. Start a new chat to reset it.")+ }+ return parts.joined(separator: " ")+ }++ private static func compact(_ value: Int) -> String {+ if value >= 1_000 {+ let thousands = Double(value) / 1_000+ return thousands >= 10+ ? "\(Int(thousands.rounded()))K"+ : String(format: "%.1fK", thousands)+ }+ return "\(value)"+ }++ private static func number(_ value: Int) -> String {+ let formatter = NumberFormatter()+ formatter.numberStyle = .decimal+ return formatter.string(from: NSNumber(value: value)) ?? "\(value)"+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swiftindex fa9b92af..75d8a21d 100644--- a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift@@ -103,6 +103,17 @@ public final class InstructionTranscriptDocumentController {public private(set) var isFinalized = falsepublic private(set) var showsPrefillPlaceholder = falsepublic private(set) var assistantRange = NSRange(location: 0, length: 0)+ /// Length of the completed turns above the live one. Everything below this+ /// offset is drawn once and never looked at again — which is the whole+ /// point: a chat that re-rendered its history on every token would make+ /// TextKit lay out the entire conversation per tick.+ public private(set) var frozenLength = 0+ /// Where each finished turn sits in the document, and the answer it holds.+ ///+ /// One floating copy button over a transcript of several turns reads as+ /// belonging to the first one. Knowing which turn a click landed in is what+ /// lets the menu offer that turn's answer instead of guessing.+ private var sealedTurns: [(range: NSRange, answer: String)] = []private var prefillPlaceholderRange: NSRange?private var prefillDotCount = 0@@ -262,8 +273,11 @@ public final class InstructionTranscriptDocumentController {// 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.+ // `frozenLength`, not zero: with completed turns above it the live turn+ // is empty at `storage.length == frozenLength`, and comparing against+ // zero meant the first tick of turn two never drew its prompt.if needsRebuild- || storage.length == 0+ || storage.length == frozenLength&& (!prompt.isEmpty || promptPrefix.length > 0|| !response.isEmpty || displaysPrefillPlaceholder) {rebuild(@@ -400,8 +414,89 @@ public final class InstructionTranscriptDocumentController {length: placeholder.length)document.append(placeholder)}- storage.setAttributedString(document)+ // Only the live turn is replaced. `setAttributedString` would take the+ // completed turns with it, and rebuilding is the common path — every+ // prompt change and every non-extending response goes through here.+ if frozenLength == 0 {+ storage.setAttributedString(document)+ } else {+ storage.replaceCharacters(+ in: NSRange(location: frozenLength,+ length: storage.length - frozenLength),+ with: document)+ assistantRange.location += frozenLength+ if prefillPlaceholderRange != nil {+ prefillPlaceholderRange?.location += frozenLength+ }+ }+ isFinalized = false+ }++ /// Freezes the live turn into the history above it and starts an empty one.+ ///+ /// Called when a turn is committed. The drawn turn is left exactly as it+ /// is: sealing is bookkeeping, not a re-render, so a finished answer never+ /// changes appearance after the fact.+ public func sealTurn(storage: NSMutableAttributedString) {+ guard storage.length > frozenLength else { return }+ let start = frozenLength+ let answer = response+ storage.append(NSAttributedString(+ string: "\n\n", attributes: Self.promptAttributes()))+ frozenLength = storage.length+ sealedTurns.append((+ range: NSRange(location: start, length: frozenLength - start),+ answer: answer))+ prompt = ""+ promptPrefixIdentifier = ""+ response = ""+ isFinalized = false+ showsPrefillPlaceholder = false+ assistantRange = NSRange(location: frozenLength, length: 0)+ prefillPlaceholderRange = nil+ prefillDotCount = 0+ progressive.reset()+ }++ /// The answer of the turn containing `index`, or nil if the index is not in+ /// a turn that has one. The live turn is included: it is the one a reader is+ /// most likely to want, and it is not sealed until the next run starts.+ public func answer(at index: Int) -> String? {+ for turn in sealedTurns where NSLocationInRange(index, turn.range) {+ return turn.answer.isEmpty ? nil : turn.answer+ }+ guard index >= frozenLength, !response.isEmpty else { return nil }+ return response+ }++ /// Marks where the model's context begins.+ ///+ /// Everything above this line is on screen but no longer in the KV — a+ /// reload or an unload took it. Saying so is the difference between a+ /// transcript the user can trust and one that quietly implies the model+ /// remembers what it cannot.+ public func appendContextBreak(storage: NSMutableAttributedString, text: String) {+ guard storage.length == frozenLength else { return }+ storage.append(NSAttributedString(+ string: "\(text)\n\n", attributes: Self.contextBreakAttributes()))+ frozenLength = storage.length+ assistantRange = NSRange(location: frozenLength, length: 0)+ }++ /// Empties the transcript, history included. New chat, not a new turn.+ public func resetTranscript(storage: NSMutableAttributedString) {+ storage.setAttributedString(NSAttributedString())+ frozenLength = 0+ sealedTurns.removeAll()+ prompt = ""+ promptPrefixIdentifier = ""+ response = ""isFinalized = false+ showsPrefillPlaceholder = false+ assistantRange = NSRange(location: 0, length: 0)+ prefillPlaceholderRange = nil+ prefillDotCount = 0+ progressive.reset()}// MARK: - Progressive rendering@@ -878,6 +973,19 @@ public final class InstructionTranscriptDocumentController {]}+ private static func contextBreakAttributes() -> [NSAttributedString.Key: Any] {+ let style = NSMutableParagraphStyle()+ style.alignment = .center+ style.paragraphSpacingBefore = 8+ style.paragraphSpacing = 8+ return [+ .font: NSFont.systemFont(+ ofSize: NSFont.smallSystemFontSize, weight: .regular),+ .foregroundColor: NSColor.tertiaryLabelColor,+ .paragraphStyle: style,+ ]+ }+private static func promptAttributes() -> [NSAttributedString.Key: Any] {let style = NSMutableParagraphStyle()style.lineSpacing = 3diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swiftnew file mode 100644index 00000000..00450654--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swift@@ -0,0 +1,101 @@+import Foundation++/// Decides what the transcript must do to catch up with the conversation.+///+/// Extracted from the view coordinator because that is where three defects hid+/// and none of them were reachable by a test: the context break was drawn+/// before the history it separates, its "already drawn" flag latched even when+/// the append was refused, and a seal that no-ops still advanced the rendered+/// count, dropping a turn from the transcript for good. The coordinator now+/// executes these steps rather than deciding them.+public enum TranscriptSyncStep: Equatable, Sendable {+ /// A different conversation: everything drawn belongs to the old one.+ case reset+ /// Freeze the turn already on screen into the history above it.+ case sealDrawnTurn+ /// Draw history pair `index`, then freeze it.+ case drawPair(index: Int)+ /// Mark where the model's context begins.+ case appendContextBreak+}++public struct TranscriptSyncPlanner: Equatable, Sendable {+ /// Pairs already frozen into the document.+ public private(set) var renderedHistory = 0+ /// The lineage the drawn document belongs to.+ public private(set) var renderedEpoch: UUID?+ public private(set) var renderedContextBreak = false++ public init() {}++ public struct Input: Equatable, Sendable {+ public let epoch: UUID+ public let historyCount: Int+ /// Pairs above this index are on screen but not in the model's context.+ public let contextBreak: Int?+ public let startedNewRun: Bool+ /// Whether the coordinator has ever drawn anything for this lineage.+ public let firstSynchronize: Bool++ public init(epoch: UUID, historyCount: Int, contextBreak: Int?,+ startedNewRun: Bool, firstSynchronize: Bool) {+ self.epoch = epoch+ self.historyCount = historyCount+ self.contextBreak = contextBreak+ self.startedNewRun = startedNewRun+ self.firstSynchronize = firstSynchronize+ }+ }++ public mutating func plan(_ input: Input) -> [TranscriptSyncStep] {+ var steps: [TranscriptSyncStep] = []+ if renderedEpoch != input.epoch {+ steps.append(.reset)+ renderedEpoch = input.epoch+ renderedHistory = 0+ renderedContextBreak = false+ }++ if renderedHistory < input.historyCount {+ if input.startedNewRun,+ renderedHistory == input.historyCount - 1,+ !input.firstSynchronize {+ steps.append(.sealDrawnTurn)+ renderedHistory = input.historyCount+ } else {+ while renderedHistory < input.historyCount {+ steps.append(.drawPair(index: renderedHistory))+ renderedHistory += 1+ }+ }+ }++ // After the history, not before it. Drawing the break first put it above+ // the very turns it is supposed to sit under, and on the pass that+ // resets for a new epoch it was skipped entirely — leaving archived+ // turns on screen unmarked until some unrelated change forced another+ // pass.+ if let contextBreak = input.contextBreak,+ !renderedContextBreak,+ renderedHistory >= contextBreak {+ steps.append(.appendContextBreak)+ }+ return steps+ }++ /// Records that the break was actually drawn.+ ///+ /// Separate from planning because the append can refuse — it only writes at+ /// the frozen boundary. Latching the flag regardless meant one refusal+ /// suppressed the break for the rest of the session.+ public mutating func markContextBreakDrawn() {+ renderedContextBreak = true+ }++ /// Records that a seal did nothing, so the pair it was meant to freeze is+ /// still owed. Advancing past it left a turn that is in the KV permanently+ /// absent from the transcript.+ public mutating func sealFoundNothingToFreeze(historyCount: Int) {+ renderedHistory = max(0, min(renderedHistory, historyCount) - 1)+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swiftindex d3cb0f99..5b1d82b6 100644--- a/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptTextView.swift@@ -64,6 +64,73 @@ 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 {+ /// 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+ /// this view owns the only context menu the transcript has.+ public var lastAnswerText: (() -> String)?+ public var conversationText: (() -> String)?+ public var startNewChat: (() -> Void)?++ /// The transcript's whole context menu, built here rather than added to+ /// AppKit's.+ ///+ /// Two reasons, both found by right-clicking the running app. The pane also+ /// carried a SwiftUI `.contextMenu`, and this view's menu wins everywhere+ /// the text is — so those commands were unreachable exactly where a reader+ /// would look for them. And AppKit's default menu for a text view offers+ /// Cut, Paste, Font, Spelling, Substitutions and Writing Tools on a+ /// transcript that cannot be edited.+ public override func menu(for event: NSEvent) -> NSMenu? {+ let menu = NSMenu()+ menu.allowsContextMenuPlugIns = false+ let point = convert(event.locationInWindow, from: nil)+ let index = characterIndexForInsertion(at: point)++ if let answer = answerAtCharacterIndex?(index), !answer.isEmpty {+ add(to: menu, title: "Copy This Answer", text: answer)+ }+ if selectedRange().length > 0 {+ let item = NSMenuItem(title: "Copy Selection",+ action: #selector(copy(_:)), keyEquivalent: "")+ item.target = self+ menu.addItem(item)+ }+ if let last = lastAnswerText?(), !last.isEmpty {+ add(to: menu, title: "Copy Last Answer", text: last)+ }+ if let conversation = conversationText?(), !conversation.isEmpty {+ add(to: menu, title: "Copy Conversation", text: conversation)+ }+ if startNewChat != nil {+ if !menu.items.isEmpty { menu.addItem(.separator()) }+ let item = NSMenuItem(title: "New Chat",+ action: #selector(newChat(_:)), keyEquivalent: "")+ item.target = self+ menu.addItem(item)+ }+ return menu.items.isEmpty ? nil : menu+ }++ private func add(to menu: NSMenu, title: String, text: String) {+ let item = NSMenuItem(title: title, action: #selector(copyText(_:)),+ keyEquivalent: "")+ item.target = self+ item.representedObject = text+ menu.addItem(item)+ }++ @objc private func copyText(_ sender: NSMenuItem) {+ guard let text = sender.representedObject as? String else { return }+ let pasteboard = NSPasteboard.general+ pasteboard.clearContents()+ pasteboard.setString(text, forType: .string)+ }++ @objc private func newChat(_ _: NSMenuItem) {+ startNewChat?()+ }+public override var writablePasteboardTypes: [NSPasteboard.PasteboardType] {selectedAttributedText() == nil ? [] : [.rtfd, .rtf, .string]}diff --git a/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swiftindex ae0a707c..08a3a9d6 100644--- a/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift+++ b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift@@ -63,6 +63,9 @@ public struct DecodeLoadRequest: Codable, Sendable {}public struct DecodeGenerationRequest: Codable, Sendable {+ /// One user turn, never a rendered transcript. In conversation mode the+ /// service appends exactly this onto the retained KV; re-rendering history+ /// here would destabilise the token prefix the cache is built on.public var prompt: Stringpublic var imageAttachments: [DecodeImageAttachment]?public var maxNewTokens: Int@@ -78,6 +81,19 @@ public struct DecodeGenerationRequest: Codable, Sendable {public var repetitionPenalty: Floatpublic var runtimeOptions: DecodeRuntimeOptionspublic var generationID: UUID+ /// The conversation this turn belongs to, or nil for the one-shot path that+ /// resets the KV before prefilling.+ ///+ /// Checked before the model is touched. A generate carrying a stale epoch+ /// is a turn composed against a conversation the user has since replaced,+ /// and appending it to the new lineage would put a message the user never+ /// sent into the model's context.+ public var conversationEpoch: UUID?+ /// Position of this turn within `conversationEpoch`, zero-based. The+ /// service rejects a turn that does not match the number of turns it has+ /// committed, so a dropped or duplicated turn is a refusal rather than a+ /// silently reordered conversation.+ public var turnIndex: Int?public init(prompt: String,imageAttachments: [DecodeImageAttachment]? = nil,@@ -85,7 +101,11 @@ public struct DecodeGenerationRequest: Codable, Sendable {temperature: Float, topK: Int? = nil, topP: Float? = nil,repetitionPenalty: Float = 1,runtimeOptions: DecodeRuntimeOptions = DecodeRuntimeOptions(),- generationID: UUID = UUID()) {+ generationID: UUID = UUID(),+ conversationEpoch: UUID? = nil,+ turnIndex: Int? = nil) {+ self.conversationEpoch = conversationEpoch+ self.turnIndex = turnIndexself.prompt = promptself.imageAttachments = imageAttachmentsself.maxNewTokens = maxNewTokens@@ -99,9 +119,22 @@ public struct DecodeGenerationRequest: Codable, Sendable {}}+/// Starts a new conversation lineage: the KV is dropped and `epoch` becomes the+/// only value the service will accept on a generate.+public struct DecodeResetConversationRequest: Codable, Sendable, Equatable {+ public var epoch: UUID+ public var requestID: UUID++ public init(epoch: UUID = UUID(), requestID: UUID = UUID()) {+ self.epoch = epoch+ self.requestID = requestID+ }+}+public enum DecodeServiceCommand: Codable, Sendable {case load(DecodeLoadRequest)case generate(DecodeGenerationRequest)+ case resetConversation(DecodeResetConversationRequest)case cancelcase unload(UUID)case shutdown@@ -118,6 +151,11 @@ public enum DecodeServiceEventKind: String, Codable, Sendable {case finishedcase cancelledcase failed+ /// The KV no longer matches the recorded conversation, so this lineage is+ /// unusable and only a reset can recover it. Distinct from `failed`, which+ /// leaves the conversation resumable.+ case lineageLost+ case conversationResetcase unloaded}@@ -178,6 +216,7 @@ public struct DecodeServiceEvent: Codable, Sendable {public var textDelta: Stringpublic var tokenCount: Intpublic var promptTokenCount: Int?+ public var computedPrefillTokens: Int?public var prefillDone: Int?public var prefillTotal: Int?public var prefillSeconds: Double?@@ -191,12 +230,23 @@ public struct DecodeServiceEvent: Codable, Sendable {/// Bytes of image tower the inference process holds mapped, or nil when/// it has no vision runtime.public var visionTowerMappedBytes: UInt64?+ /// Prompt tokens served from the retained KV instead of being prefilled+ /// again. Reported per turn because a cache nobody can see is a cache that+ /// can regress to nothing without a single bug report.+ public var cachedPromptTokens: Int?+ /// Tokens the conversation's KV holds after this turn, for the context+ /// gauge. Nil outside conversation mode.+ public var conversationTokenCount: Int?+ /// The lineage this event belongs to, so a late event from a replaced+ /// conversation can be dropped rather than shown under the new one.+ public var conversationEpoch: UUID?public var prefill: DecodePrefillDiagnostics?public var runner: DecodeRunnerDiagnostics?public init(kind: DecodeServiceEventKind, generationID: UUID,sequence: UInt64 = 0, textDelta: String = "",tokenCount: Int = 0, promptTokenCount: Int? = nil,+ computedPrefillTokens: Int? = nil,prefillDone: Int? = nil, prefillTotal: Int? = nil,prefillSeconds: Double? = nil,timeToFirstTokenSeconds: Double? = nil,@@ -204,6 +254,9 @@ public struct DecodeServiceEvent: Codable, Sendable {stopReason: String? = nil, error: String? = nil,currentMemoryBytes: UInt64? = nil, peakMemoryBytes: UInt64? = nil,visionTowerMappedBytes: UInt64? = nil,+ cachedPromptTokens: Int? = nil,+ conversationTokenCount: Int? = nil,+ conversationEpoch: UUID? = nil,prefill: DecodePrefillDiagnostics? = nil,runner: DecodeRunnerDiagnostics? = nil) {self.kind = kind@@ -212,6 +265,7 @@ public struct DecodeServiceEvent: Codable, Sendable {self.textDelta = textDeltaself.tokenCount = tokenCountself.promptTokenCount = promptTokenCount+ self.computedPrefillTokens = computedPrefillTokensself.prefillDone = prefillDoneself.prefillTotal = prefillTotalself.prefillSeconds = prefillSeconds@@ -223,6 +277,9 @@ public struct DecodeServiceEvent: Codable, Sendable {self.currentMemoryBytes = currentMemoryBytesself.peakMemoryBytes = peakMemoryBytesself.visionTowerMappedBytes = visionTowerMappedBytes+ self.cachedPromptTokens = cachedPromptTokens+ self.conversationTokenCount = conversationTokenCount+ self.conversationEpoch = conversationEpochself.prefill = prefillself.runner = runner}diff --git a/Sources/TurboFieldfareDecodeService/DecodeConversationGate.swift b/Sources/TurboFieldfareDecodeService/DecodeConversationGate.swiftnew file mode 100644index 00000000..424585c5--- /dev/null+++ b/Sources/TurboFieldfareDecodeService/DecodeConversationGate.swift@@ -0,0 +1,92 @@+import Foundation+import TurboFieldfareDecodeProtocol++/// Decides whether an incoming generate may join the open conversation.+///+/// Extracted from the service's command loop so the decision is testable+/// without a socket, a model, or a Metal device. The loop cannot express the+/// boundary cases this holds — a turn from a replaced conversation, a turn that+/// skips or repeats a position, a one-shot arriving while a lineage is open —+/// and every one of them ends with a message the user never sent being appended+/// to a KV, which no later check can detect.+struct DecodeConversationGate: Equatable {+ /// Why a turn cannot run. Typed rather than a string so a test pins the+ /// case, and the loop owns the wording.+ enum Rejection: Error, Equatable {+ /// The turn names a conversation that is no longer the open one.+ case staleConversation(requested: UUID, open: UUID?)+ /// The turn's position does not follow the committed turns.+ case outOfOrderTurn(requested: Int?, committed: Int)+ /// A one-shot generate arrived while a conversation was open. Running+ /// it would reset the KV under a lineage the app still believes in.+ case oneShotDuringConversation(open: UUID)+ }++ enum Admission: Equatable {+ /// No conversation is open: reset the KV and prefill the whole prompt.+ case oneShot+ /// Append to the open lineage at `index`.+ case turn(epoch: UUID, index: Int)+ }++ private(set) var openEpoch: UUID?+ private(set) var committedTurns = 0++ /// Starts a new lineage. The caller drops the KV; this only records that it+ /// did.+ mutating func reset(to epoch: UUID) {+ openEpoch = epoch+ committedTurns = 0+ }++ /// Ends any lineage. Both unload and load reach here: each releases or+ /// rebuilds the runner and the KV, so the tokens the epoch named are gone,+ /// and a turn resuming onto them would resume onto nothing.+ mutating func endLineage() {+ openEpoch = nil+ committedTurns = 0+ }++ func admit(_ request: DecodeGenerationRequest) -> Result<Admission, Rejection> {+ guard let requested = request.conversationEpoch else {+ if let openEpoch { return .failure(.oneShotDuringConversation(open: openEpoch)) }+ return .success(.oneShot)+ }+ guard requested == openEpoch else {+ return .failure(.staleConversation(requested: requested, open: openEpoch))+ }+ guard request.turnIndex == committedTurns else {+ return .failure(.outOfOrderTurn(requested: request.turnIndex,+ committed: committedTurns))+ }+ return .success(.turn(epoch: requested, index: committedTurns))+ }++ /// Records that a turn actually ran. Called after the generation, not at+ /// admission: a turn rejected downstream, or one that failed before+ /// touching the KV, must not advance the position the next turn has to+ /// match.+ mutating func commit(_ admission: Admission) {+ guard case .turn(let epoch, _) = admission, epoch == openEpoch else { return }+ committedTurns += 1+ }+}+extension DecodeConversationGate.Rejection {+ /// The wording the service sends back. Names what was asked for and what is+ /// actually open, because "rejected" alone is not a diagnosis.+ var message: String {+ switch self {+ case .staleConversation(let requested, let open):+ let openText = open.map(\.uuidString) ?? "none"+ return "turn belongs to conversation \(requested.uuidString), "+ + "and the open conversation is \(openText)"+ case .outOfOrderTurn(let requested, let committed):+ let requestedText = requested.map(String.init) ?? "unset"+ return "turn index \(requestedText) does not follow the "+ + "\(committed) turns committed to this conversation"+ case .oneShotDuringConversation(let open):+ return "a conversation is open (\(open.uuidString)); "+ + "a one-shot turn cannot run on it"+ }+ }+}diff --git a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swiftindex d3cd8a54..ff01698c 100644--- a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift+++ b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift@@ -28,9 +28,14 @@ final class DecodeServiceOutbox: @unchecked Sendable {/// vision runtime. Sampled per event so Keep Ready is visible while a run/// is happening, not only in its final diagnostics.private let towerBytes: @Sendable () -> UInt64?+ /// Nil outside conversation mode, so a one-shot turn reports no gauge+ /// rather than a misleading zero.+ private let conversationTokens: @Sendable () -> Int?init(generationID: UUID,- towerBytes: @escaping @Sendable () -> UInt64? = { nil }) {+ towerBytes: @escaping @Sendable () -> UInt64? = { nil },+ conversationTokens: @escaping @Sendable () -> Int? = { nil }) {+ self.conversationTokens = conversationTokensself.generationID = generationIDself.towerBytes = towerBytesmemorySampler.resetPeak()@@ -61,8 +66,15 @@ final class DecodeServiceOutbox: @unchecked Sendable {}case .failed(let error, let diagnostics):if !state.terminalCommitted {+ // A broken lineage is not the same terminal state as a failed+ // turn. The turn can be retried; the conversation cannot, and+ // the app has to clear it rather than offer a retry that would+ // fail identically forever.+ let kind: DecodeServiceEventKind+ if case .conversationLineageLost = error { kind = .lineageLost }+ else { kind = .failed }state.terminal = terminal(- .failed, diagnostics: diagnostics, error: error.userMessage)+ kind, diagnostics: diagnostics, error: error.userMessage)state.terminalCommitted = true}}@@ -158,6 +170,7 @@ final class DecodeServiceOutbox: @unchecked Sendable {kind: kind, generationID: generationID,tokenCount: diagnostics?.generatedTokens ?? 0,promptTokenCount: diagnostics?.promptTokenCount,+ computedPrefillTokens: diagnostics?.computedPrefillTokens,prefillSeconds: diagnostics?.prefillSeconds,timeToFirstTokenSeconds: diagnostics?.timeToFirstTokenSeconds,decodeSeconds: diagnostics?.decodeSeconds ?? 0,@@ -167,6 +180,8 @@ final class DecodeServiceOutbox: @unchecked Sendable {currentMemoryBytes: memorySampler.sample(),peakMemoryBytes: memorySampler.peakBytes,visionTowerMappedBytes: diagnostics?.visionTowerMappedBytes,+ cachedPromptTokens: diagnostics?.cachedPromptTokens,+ conversationTokenCount: conversationTokens(),prefill: diagnostics?.prefill.map(Self.prefillDiagnostics),runner: diagnostics?.runner.map(Self.runnerDiagnostics))}diff --git a/Sources/TurboFieldfareDecodeService/Entry.swift b/Sources/TurboFieldfareDecodeService/Entry.swiftindex 14cf4d2d..cbcf43e4 100644--- a/Sources/TurboFieldfareDecodeService/Entry.swift+++ b/Sources/TurboFieldfareDecodeService/Entry.swift@@ -43,7 +43,13 @@ enum DecodeServiceError: Error, CustomStringConvertible {while true {let command = try DecodeFrameCodec.read(DecodeServiceCommand.self, from: handles.input)- if case .cancel = command { client.cancel() }+ if case .cancel = command {+ // Cooperative: end the turn at the next token boundary+ // and keep what it produced, so the conversation can+ // continue from it. Cancelling the task instead throws+ // out of the decode loop and the turn is rewound.+ client.stop()+ }commands.append(command)if case .shutdown = command { break }}@@ -57,6 +63,7 @@ enum DecodeServiceError: Error, CustomStringConvertible {var modelDirectory: URL?var loadedOptions: DecodeRuntimeOptions?+ var conversation = DecodeConversationGate()while let command = await nextCommand(commands) {switch command {case .load(let request):@@ -70,6 +77,9 @@ enum DecodeServiceError: Error, CustomStringConvertible {forceLogitsHead: request.forceLogitsHead) { _ in }modelDirectory = directoryloadedOptions = request.runtimeOptions+ // A load builds a new runner and a new KV, so whatever+ // lineage was open no longer has tokens behind it.+ conversation.endLineage()let memory = AppMemorySampler().sample()try write(DecodeServiceEvent(kind: .ready, generationID: request.requestID,@@ -80,6 +90,25 @@ enum DecodeServiceError: Error, CustomStringConvertible {kind: .failed, generationID: request.requestID,error: "\(error)"), to: handles.output)}+ case .resetConversation(let request):+ conversation.reset(to: request.epoch)+ await client.resetConversation()+ // Not `try?`. The gate has already reset; if the app never+ // hears so it waits out the whole timeout for a reply that+ // cannot come, and then cannot tell that from a slow service.+ // Closing the stream makes it an EOF the client rebuilds from.+ do { try write(DecodeServiceEvent(+ kind: .conversationReset, generationID: request.requestID,+ conversationTokenCount: 0,+ conversationEpoch: request.epoch), to: handles.output)+ } catch {+ let message = "Decode service closing after a lost "+ + "conversation reset: \(error)\n"+ FileHandle.standardError.write(Data(message.utf8))+ await client.unload()+ try? handles.output.close()+ return+ }case .generate(let request):guard let modelDirectory else {try? write(DecodeServiceEvent(@@ -102,10 +131,29 @@ enum DecodeServiceError: Error, CustomStringConvertible {to: handles.output)continue}-+ // Fail closed before the model is touched. The decision+ // lives in `DecodeConversationGate`, where its boundary cases+ // are tested without a socket or a model.+ let admission: DecodeConversationGate.Admission+ switch conversation.admit(request) {+ case .success(let value):+ admission = value+ case .failure(let rejection):+ try? write(DecodeServiceEvent(+ kind: .failed, generationID: request.generationID,+ error: rejection.message,+ conversationEpoch: conversation.openEpoch), to: handles.output)+ continue+ }+ let isConversationTurn: Bool+ if case .turn = admission { isConversationTurn = true }+ else { isConversationTurn = false }let outbox = DecodeServiceOutbox(generationID: request.generationID,- towerBytes: { client.currentVisionTowerBytes })+ towerBytes: { client.currentVisionTowerBytes },+ conversationTokens: {+ isConversationTurn ? client.currentConversationTokens : nil+ })let writerFinished = DispatchSemaphore(value: 0)let writer = Thread {defer { writerFinished.signal() }@@ -130,6 +178,11 @@ enum DecodeServiceError: Error, CustomStringConvertible {path: outside.path)}let options = try appRuntimeOptions(request.runtimeOptions)+ // The conversation already in the KV is what the image+ // budget has to fit around; reserving zero admits an image+ // that only fits an empty context.+ let carried = await client.conversationTokenCount+ let continues = isConversationTurnlet generation = AppGenerationRequest(modelDirectory: modelDirectory, prompt: request.prompt,imageAttachments: (request.imageAttachments ?? []).map {@@ -146,10 +199,18 @@ enum DecodeServiceError: Error, CustomStringConvertible {topK: request.topK,topP: request.topP,repetitionPenalty: request.repetitionPenalty,- runtimeOptions: options)- for try await event in client.generate(generation) {- outbox.publish(event)- }+ runtimeOptions: options,+ continuesConversation: continues,+ conversationTokens: continues ? carried : 0)+ for try await event in client.generate(generation) { outbox.publish(event) }+ // Reached only when the stream completed. A turn that threw+ // was rewound by the conversation (or broke its lineage), so+ // its tokens are not in the KV and it must not advance the+ // order the next turn has to match — the app does not count+ // it either, and a one-sided count rejects every later turn.+ // A turn stopped by the user does reach here: it ends at a+ // token boundary with its partial reply committed.+ conversation.commit(admission)outbox.finish()} catch {outbox.finish(error: error)@@ -166,6 +227,7 @@ enum DecodeServiceError: Error, CustomStringConvertible {await client.unload()modelDirectory = nilloadedOptions = nil+ conversation.endLineage()try? write(DecodeServiceEvent(kind: .unloaded, generationID: requestID), to: handles.output)case .shutdown:diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/MultimodalConversationKVRecoveryTests.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/MultimodalConversationKVRecoveryTests.swiftnew file mode 100644index 00000000..a6d40efb--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/MultimodalConversationKVRecoveryTests.swift@@ -0,0 +1,81 @@+import Testing+@testable import TurboFieldfare++@Suite struct MultimodalConversationKVRecoveryTests {+ private enum FixtureError: Error, CustomStringConvertible {+ case generation+ case rewind++ var description: String {+ switch self {+ case .generation: "generation fixture"+ case .rewind: "rewind fixture"+ }+ }+ }++ @Test func failedTurnAtAnEmptyLineageResetsWithoutRewinding() throws {+ var reset = false+ try MultimodalConversationKVRecovery.restoreAfterFailure(+ positionBefore: 0,+ generationError: FixtureError.generation,+ rewind: { _ in Issue.record("empty lineage tried to rewind") },+ reset: { reset = true })++ #expect(reset)+ }++ @Test func failedRewindReportsLineageLossWithBothCauses() {+ do {+ try MultimodalConversationKVRecovery.restoreAfterFailure(+ positionBefore: 280,+ generationError: FixtureError.generation,+ rewind: { _ in throw FixtureError.rewind },+ reset: { Issue.record("nonempty lineage reset") })+ Issue.record("failed rewind was treated as recovered")+ } catch let error as MultimodalConversationError {+ guard case .lineageRecoveryFailed = error else {+ Issue.record("expected lineageRecoveryFailed, got \(error)")+ return+ }+ #expect(error.description.contains("generation fixture"))+ #expect(error.description.contains("rewind fixture"))+ } catch {+ Issue.record("unexpected error: \(error)")+ }+ }++ @Test func stopStringTrimRewindsToTheVisiblePrefix() throws {+ var target: Int?+ let kept = try MultimodalConversationKVRecovery.trimHiddenStopTokens(+ [1, 2, 3, 4],+ withheld: 2,+ rewind: { target = $0 },+ reset: { Issue.record("nonempty prefix reset") })++ #expect(target == 2)+ #expect(kept == [1, 2])+ }++ @Test func stopStringTrimToZeroResetsTheRunner() throws {+ var reset = false+ let kept = try MultimodalConversationKVRecovery.trimHiddenStopTokens(+ [1, 2],+ withheld: 2,+ rewind: { _ in Issue.record("zero target tried to rewind") },+ reset: { reset = true })++ #expect(reset)+ #expect(kept.isEmpty)+ }++ @Test func failedStopStringTrimReportsLineageLoss() {+ #expect(throws: MultimodalConversationError.self) {+ _ = try MultimodalConversationKVRecovery.trimHiddenStopTokens(+ [1, 2, 3],+ withheld: 1,+ rewind: { _ in throw FixtureError.rewind },+ reset: {})+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Stopping.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Stopping.swiftindex bb98561f..dd19abcc 100644--- a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Stopping.swift+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Stopping.swift@@ -1,6 +1,7 @@import Foundationimport Metalimport Testing+import TurboFieldfareValidationSupport@testable import TurboFieldfare@@ -48,4 +49,60 @@ extension RawCompletionLoopTests {#expect(result.reason == .stopString)}+ @Test func stopStringSpanningTokensReportsWithheldKVTokens() async throws {+ let tok = try await GFTokenizer.load()+ let idA = tok.encode("a", addBOS: false).first!+ let textA = tok.decode([idA], skipSpecialTokens: true)+ let (collected, result) = try await runLoop(+ seq: [idA, idA, idA], end: idA,+ config: GenerationConfig(maxNewTokens: 50, temperature: 0,+ stopStrings: [textA + textA]))+ #expect(result.reason == .stopString)+ #expect(result.withheldTrailingKVTokens == 1)+ #expect(result.kvBackedTokenIDs.count == result.kvPosition)+ #expect(result.kvBackedTokenIDs.last == idA)+ #expect(result.uncommittedBoundaryTokenIDs == [idA])+ #expect(collected.tails.isEmpty)+ }++ @Test func stopMatchThatFlushesHeldTextDoesNotOvercountWithheldTokens() async throws {+ let tok = try await GFTokenizer.load()+ let idA = try #require(tok.tokenizer.convertTokenToId("a").map(Int32.init))+ let idCab = try #require(tok.tokenizer.convertTokenToId("cab").map(Int32.init))+ let (collected, result) = try await runLoop(+ seq: [idA, idCab], end: idA,+ config: GenerationConfig(maxNewTokens: 50, temperature: 0, stopStrings: ["ab"]))+ #expect(result.reason == .stopString)+ #expect(result.withheldTrailingKVTokens == 0)+ #expect(result.kvBackedTokenIDs.last == idA)+ #expect(collected.tokens.map(\.2) == ["", "ac"])+ }++ @Test func shouldStopEndsDecodeWithCancelledReason() async throws {+ let ctx = try MetalContext()+ let tok = try await GFTokenizer.load()+ let idA = tok.encode("a", addBOS: false).first!+ let producer = ScriptedLogitProducer(vocabSize: tok.vocabSize,+ step: automaton([idA, idA], end: idA))+ let promptIds = tok.encode("go", addBOS: true)+ let scratch = try RawCompletionScratch(context: ctx, vocab: tok.vocabSize)+ var seen = 0+ var cancel = false+ let result = try await runRawCompletion(+ producer: producer, tokenizer: tok, promptIds: promptIds,+ config: GenerationConfig(maxNewTokens: 50, temperature: 0),+ context: ctx, scratch: scratch, prefillConfig: .off,+ shouldStop: { cancel }) { progress in+ if case .token = progress {+ seen += 1+ if seen == 2 { cancel = true }+ }+ }+ #expect(result.reason == .cancelled)+ #expect(result.newTokens == 2)+ #expect(result.withheldTrailingKVTokens == 0)+ #expect(result.kvBackedTokenIDs.count == promptIds.count + 1)+ #expect(result.uncommittedBoundaryTokenIDs.count == 1)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift b/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swiftindex 13a328c0..7d2343ae 100644--- a/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift+++ b/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift@@ -149,12 +149,48 @@ import Metal#expect(kv.position == 32)}+ @Test func rewindMovesCursorWithinRingSlack() throws {+ let (_, kv) = try makeManager(maxContext: 4_096, fp16RingEnabled: true)+ kv.advance(by: 2_000)+ #expect(kv.maxRewindTokens == 128)+ kv.rewind(to: 1_990)+ #expect(kv.position == 1_990)+ }++ @Test func rewindIsUnboundedForLinearStorage() throws {+ let (_, kv) = try makeManager(maxContext: 64)+ kv.advance(by: 50)+ #expect(kv.maxRewindTokens == 64)+ kv.rewind(to: 1)+ #expect(kv.position == 1)+ }++ @Test func rewindBoundsAgainstHighWaterMarkNotCursor() throws {+ let (_, kv) = try makeManager(maxContext: 4_096, fp16RingEnabled: true)+ kv.advance(by: 1_280)+ kv.rewind(to: 1_160)+ #expect(kv.highWaterPosition == 1_280)+ kv.rewind(to: 1_155)+ #expect(kv.position == 1_155)+ kv.advance(by: 200)+ #expect(kv.highWaterPosition == 1_355)+ }++ @Test func rewindShortSessionRingNeverWrapsSoDepthIsFree() throws {+ let (_, kv) = try makeManager(maxContext: 16, fp16RingEnabled: true)+ kv.advance(by: 10)+ #expect(kv.maxRewindTokens == 16)+ kv.rewind(to: 2)+ #expect(kv.position == 2)+ }+@Test func reset_clearsPosition() throws {let (_, kv) = try makeManager(maxContext: 128)for _ in 0..<100 { kv.advance() }#expect(kv.position == 100)kv.reset()#expect(kv.position == 0)+ #expect(kv.highWaterPosition == 0)// Cursor reusable after reset.kv.advance()#expect(kv.position == 1)diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swiftindex 7be69456..666ad1e6 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift@@ -82,7 +82,7 @@ import Testing#expect(!settings.prefillEnabled)#expect(settings.newlineShortcut == .return)#expect(settings.showPromptExamples)- #expect(settings.sentPromptBehavior == .keep)+ #expect(settings.visionResidencyPolicy == .onDemand)}@Test(arguments: AppNewlineShortcut.allCases)@@ -111,16 +111,6 @@ import Testing#expect(decoded == initial)}- @Test(arguments: AppSentPromptBehavior.allCases)- func sentPromptBehaviorRoundTrips(_ behavior: AppSentPromptBehavior) throws {- let initial = MacAppSettings(sentPromptBehavior: behavior)- let decoded = try JSONDecoder().decode(- MacAppSettings.self,- from: JSONEncoder().encode(initial))-- #expect(decoded == initial)- }-@Test func invalidNewlineShortcutIsReplacedWithDefaults() throws {let root = try makeTemporaryRoot()defer { try? FileManager.default.removeItem(at: root) }@@ -165,8 +155,7 @@ import TestingtopP: 0.8,prefillEnabled: false,newlineShortcut: .shiftReturn,- showPromptExamples: false,- sentPromptBehavior: .clear)+ showPromptExamples: false)try MacAppSettingsFileStore.save(initial, forModelDirectory: modelDirectory)let model = AppModel(@@ -182,7 +171,6 @@ import Testing#expect(!model.runtimeOptions.prefillEnabled)#expect(model.newlineShortcut == .shiftReturn)#expect(!model.showPromptExamples)- #expect(model.sentPromptBehavior == .clear)model.temperature = 0.6model.runtimeOptions.expertCacheSlots = 32@@ -201,7 +189,6 @@ import Testing#expect(saved.prefillEnabled)#expect(saved.newlineShortcut == .shiftReturn)#expect(!saved.showPromptExamples)- #expect(saved.sentPromptBehavior == .clear)model.cancel()}@@ -237,22 +224,6 @@ import Testing#expect(!saved.showPromptExamples)}- @MainActor- @Test func sentPromptBehaviorPersistsImmediately() throws {- let root = try makeTemporaryRoot()- defer { try? FileManager.default.removeItem(at: root) }- let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)- let model = AppModel(- modelDirectory: modelDirectory,- settingsPersistenceEnabled: true)-- model.setSentPromptBehavior(.clear)-- let saved = MacAppSettingsFileStore.loadOrCreate(- forModelDirectory: modelDirectory)- #expect(saved.sentPromptBehavior == .clear)- }-@MainActor@Test func changingModelDirectoryLoadsItsNewlineShortcut() throws {let root = try makeTemporaryRoot()diff --git a/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift b/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swiftindex aa266d05..364f0efb 100644--- a/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift+++ b/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift@@ -40,11 +40,12 @@ import Testing#expect(missingFirstToken.requestStartTimeToFirstTokenSeconds == nil)}- @Test func prefillRateUsesPromptTokensAndPrefillDuration() {+ @Test func prefillRateUsesComputedTokensAndPrefillDuration() {var diagnostics = AppDiagnostics(generatedTokens: 1,stopReason: .eos,promptTokenCount: 20,+ computedPrefillTokens: 5,prefillSeconds: 6.17,timeToFirstTokenSeconds: 0.5,decodeSeconds: 0.75,@@ -52,17 +53,33 @@ import TestingpeakMemoryBytes: nil,runtimeOptions: AppRuntimeOptions())- #expect(abs((diagnostics.prefillTokensPerSecond ?? 0) - 3.241491) < 0.000001)+ #expect(abs((diagnostics.prefillTokensPerSecond ?? 0) - 0.810373) < 0.000001)- diagnostics.promptTokenCount = 0+ diagnostics.computedPrefillTokens = 0#expect(diagnostics.prefillTokensPerSecond == nil)- diagnostics.promptTokenCount = 20+ diagnostics.computedPrefillTokens = 5diagnostics.prefillSeconds = 0#expect(diagnostics.prefillTokensPerSecond == nil)diagnostics.prefillSeconds = .nan#expect(diagnostics.prefillTokensPerSecond == nil)}+ @Test func prefillRateFallsBackToPromptTokensForOlderEvents() {+ let diagnostics = AppDiagnostics(+ generatedTokens: 1,+ stopReason: .eos,+ promptTokenCount: 20,+ computedPrefillTokens: nil,+ prefillSeconds: 5,+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 0,+ tokensPerSecond: 0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())++ #expect(diagnostics.prefillTokensPerSecond == 4)+ }+@Test func runnerDiagnosticsRetainPublicResultAndAdvancedMetrics() {let diagnostics = AppRunnerDiagnostics(cb1MillisecondsPerToken: 1,diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppConversationTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppConversationTests.swiftnew file mode 100644index 00000000..66c9cd99--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/AppConversationTests.swift@@ -0,0 +1,186 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++/// The invariant under test throughout: the transcript equals the model's+/// context. The decode service counts committed turns independently, and a+/// count that drifts by one on either side makes the gate reject every later+/// turn of the conversation.+@Suite struct AppConversationTests {+ private func diagnostics(prompt: Int?, cached: Int?, generated: Int,+ stopReason: AppStopReason = .endOfTurn,+ omitConversationTokens: Bool = false) -> AppDiagnostics {+ AppDiagnostics(+ generatedTokens: generated,+ stopReason: stopReason,+ promptTokenCount: prompt,+ cachedPromptTokens: cached,+ conversationTokens: omitConversationTokens+ ? nil : prompt.map { $0 + generated },+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 0,+ tokensPerSecond: 0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())+ }++ @Test func afirstTurnIsIndexZeroAndShowsBeforeItsReply() throws {+ var conversation = AppConversation()+ let started = conversation.beginTurn(text: "hello")+ let ticket = try #require(started)+ #expect(ticket.index == 0)+ #expect(ticket.epoch == conversation.epoch)+ // The user's message is on screen while the model is still thinking.+ #expect(conversation.turns.count == 1)+ #expect(conversation.turns[0].role == .user)+ #expect(conversation.committedTurns == 0, "nothing is in the KV yet")+ #expect(conversation.hasTurnInFlight)+ }++ @Test func acompletedTurnAdvancesTheIndexTheServiceChecks() throws {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "one")+ conversation.completeTurn(+ text: "first reply",+ diagnostics: diagnostics(prompt: 12, cached: 0, generated: 5))+ #expect(conversation.committedTurns == 1)+ #expect(conversation.turns.map(\.role) == [.user, .assistant])+ #expect(conversation.turns[0].cachedTokens == 0)+ #expect(conversation.turns[1].text == "first reply")+ #expect(conversation.kvTokens == 17)++ let began = conversation.beginTurn(text: "two")+ let second = try #require(began)+ #expect(second.index == 1)+ }++ @Test func asecondSendIsRefusedWhileATurnIsDecoding() {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "one")+ // A double-tap on Send must not reserve a second position: the service+ // would reject it, and the transcript would show a message that never+ // reached the model.+ #expect(conversation.beginTurn(text: "two") == nil)+ #expect(conversation.turns.count == 1)+ }++ /// A turn that threw was rewound by the runtime, so its tokens are not in+ /// the KV. Leaving it in the transcript would show the user a message the+ /// model never saw, and counting it would push every later turn one+ /// position out of step with the service's gate.+ @Test func anabandonedTurnLeavesNoTraceAndKeepsTheIndex() throws {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "one")+ conversation.completeTurn(+ text: "reply", diagnostics: diagnostics(prompt: 10, cached: 0, generated: 4))++ let began = conversation.beginTurn(text: "two", images: [])+ let ticket = try #require(began)+ #expect(ticket.index == 1)+ let abandoned = conversation.abandonTurn()+ let returned = try #require(abandoned)+ #expect(returned.text == "two", "the composer gets the text back")+ #expect(conversation.turns.count == 2)+ #expect(conversation.committedTurns == 1)+ // The next attempt reuses the same position.+ #expect(conversation.beginTurn(text: "two again")?.index == 1)+ }++ @Test func astoppedTurnStillCommits() throws {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "one")+ // Stopping ends the turn at a token boundary with the partial reply in+ // the KV, so it counts exactly like a finished one.+ conversation.completeTurn(+ text: "partial",+ diagnostics: diagnostics(prompt: 9, cached: 0, generated: 2,+ stopReason: .cancelled))+ #expect(conversation.committedTurns == 1)+ #expect(conversation.turns[1].stopReason == .cancelled)+ #expect(conversation.beginTurn(text: "two")?.index == 1)+ }++ @Test func alostLineageKeepsTheTranscriptAndRefusesEverySend() throws {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "one")+ conversation.completeTurn(+ text: "reply", diagnostics: diagnostics(prompt: 10, cached: 0, generated: 4))+ _ = conversation.beginTurn(text: "two")++ let lost = conversation.markLineageLost()+ let returned = try #require(lost)+ #expect(returned.text == "two")+ #expect(conversation.isLineageLost)+ // What the user already read stays readable.+ #expect(conversation.turns.count == 2)+ #expect(!conversation.canSend)+ #expect(conversation.beginTurn(text: "three") == nil)+ }++ @Test func anewChatClearsEverythingAndTakesAFreshEpoch() {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "one")+ conversation.completeTurn(+ text: "reply", diagnostics: diagnostics(prompt: 10, cached: 0, generated: 4))+ conversation.markLineageLost()+ let previous = conversation.epoch++ conversation.startNew()+ #expect(conversation.epoch != previous)+ #expect(conversation.turns.isEmpty)+ #expect(conversation.committedTurns == 0)+ #expect(conversation.kvTokens == 0)+ #expect(!conversation.isLineageLost)+ #expect(conversation.beginTurn(text: "fresh")?.index == 0)+ }++ @Test func cachedTokensGrowWithTheConversation() {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "one")+ conversation.completeTurn(+ text: "a", diagnostics: diagnostics(prompt: 10, cached: 0, generated: 5))+ _ = conversation.beginTurn(text: "two")+ conversation.completeTurn(+ text: "b", diagnostics: diagnostics(prompt: 20, cached: 15, generated: 6))+ // Turn two reused everything turn one left behind. This is the figure+ // the HUD shows, and the only way a regression to full re-prefill is+ // visible without a stopwatch.+ #expect(conversation.turns[2].cachedTokens == 15)+ #expect(conversation.kvTokens == 26)+ }++ @Test(arguments: [+ AppStopReason.endOfTurn,+ .maxTokens,+ .cancelled,+ .stopString+ ])+ func missingCommittedPositionMarksTheKVCountUnknown(_ stopReason: AppStopReason) {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "one")+ conversation.completeTurn(+ text: "a", diagnostics: diagnostics(prompt: 10, cached: 0, generated: 5))+ #expect(conversation.kvTokens == 15)++ _ = conversation.beginTurn(text: "two")+ conversation.completeTurn(+ text: "b",+ diagnostics: diagnostics(+ prompt: 40,+ cached: 15,+ generated: 9,+ stopReason: stopReason,+ omitConversationTokens: true))++ #expect(conversation.kvTokens == nil)+ #expect(conversation.committedTurns == 2)+ }++ @Test func completingWithoutAPendingTurnChangesNothing() {+ var conversation = AppConversation()+ conversation.completeTurn(+ text: "orphan", diagnostics: diagnostics(prompt: 3, cached: 0, generated: 1))+ #expect(conversation.turns.isEmpty)+ #expect(conversation.committedTurns == 0)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swiftindex 7d8d8d12..1d886751 100644--- a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift@@ -1,5 +1,6 @@import Foundationimport Testing+import TurboFieldfare@testable import TurboFieldfareAppCore@Suite struct AppGenerationRequestTests {@@ -131,4 +132,89 @@ import Testingtry request.validate()}+ private func image(_ name: String) -> AppImageAttachment {+ AppImageAttachment(+ fileURL: URL(fileURLWithPath: "/tmp/\(name)"),+ displayName: name, encodedBytes: 4,+ sha256: String(repeating: "a", count: 64))+ }++ @Test func imageCapacityShrinksAsTheConversationFills() throws {+ let capacity = VisionImageTokenBudget.capacity(+ maxContext: 8_192, reservedTextTokens: 0)+ #expect(capacity >= 2, "the fixture needs room for more than one image")+ let attachments = (0..<capacity).map { image("image-\($0).png") }++ try AppGenerationRequest(+ modelDirectory: existingDirectory, prompt: "describe these",+ imageAttachments: attachments, maxContextTokens: 8_192).validate()++ let carried = 8_192 - VisionImageTokenBudget.maximumTokensPerImage+ #expect(throws: AppInferenceError.self) {+ try AppGenerationRequest(+ modelDirectory: existingDirectory, prompt: "and these",+ imageAttachments: attachments, maxContextTokens: 8_192,+ continuesConversation: true,+ conversationTokens: carried).validate()+ }+ }++ @Test func aTurnCarryingOneImageStillFitsLateInAConversation() throws {+ let carried = 8_192 - VisionImageTokenBudget.maximumTokensPerImage - 16+ try AppGenerationRequest(+ modelDirectory: existingDirectory, prompt: "what is this",+ imageAttachments: [image("one.png")], maxContextTokens: 8_192,+ continuesConversation: true,+ conversationTokens: carried).validate()+ }++ @Test func aOneShotRequestReservesNothingAndKeepsItsOldCapacity() throws {+ let request = AppGenerationRequest(+ modelDirectory: existingDirectory, prompt: "hello")+ #expect(!request.continuesConversation)+ #expect(request.conversationTokens == 0)+ try request.validate()+ }++ @Test(arguments: [Int.min, -1, 8_193, Int.max])+ func invalidConversationTokenCountsAreRejectedBeforeBudgetArithmetic(_ tokens: Int) {+ let request = AppGenerationRequest(+ modelDirectory: existingDirectory,+ prompt: "hello",+ imageAttachments: [image("one.png")],+ maxContextTokens: 8_192,+ conversationTokens: tokens)++ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }++ @Test func conversationTokenBoundariesAreValid() throws {+ for tokens in [0, 8_192] {+ try AppGenerationRequest(+ modelDirectory: existingDirectory,+ prompt: "hello",+ maxContextTokens: 8_192,+ conversationTokens: tokens).validate()+ }+ }++ @Test func invalidContextCannotOverflowImageCapacity() {+ let request = AppGenerationRequest(+ modelDirectory: existingDirectory,+ prompt: "hello",+ imageAttachments: [image("one.png")],+ maxContextTokens: Int.min,+ conversationTokens: Int.max)++ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ #expect(VisionImageTokenBudget.capacity(+ maxContext: Int.min, reservedTextTokens: Int.max) == 0)+ #expect(VisionImageTokenBudget.capacity(+ maxContext: Int.max, reservedTextTokens: Int.min) == 0)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swiftindex 042291b9..f03d5a4c 100644--- a/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift@@ -47,6 +47,7 @@ import TurboFieldfareDecodeProtocolgenerationID: UUID(),tokenCount: 256,promptTokenCount: 1_017,+ computedPrefillTokens: 17,prefillSeconds: 10.2,timeToFirstTokenSeconds: 0.04,decodeSeconds: 7.7,@@ -64,6 +65,7 @@ import TurboFieldfareDecodeProtocol#expect(decoded.tokenCount == 256)#expect(decoded.promptTokenCount == 1_017)+ #expect(decoded.computedPrefillTokens == 17)#expect(decoded.currentMemoryBytes == 2_000_000_000)#expect(decoded.peakMemoryBytes == 2_100_000_000)#expect(decoded.runner == runner)diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceConnectionInvalidationTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceConnectionInvalidationTests.swiftnew file mode 100644index 00000000..36bfaf9c--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceConnectionInvalidationTests.swift@@ -0,0 +1,39 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct DecodeServiceConnectionInvalidationTests {+ @Test func lostResetAcknowledgementDiscardsTheDeadConnection() async throws {+ let commands = Pipe()+ let responses = Pipe()+ let client = DecodeServiceInferenceClient(+ testInput: commands.fileHandleForWriting,+ responseOutput: responses.fileHandleForReading)+ #expect(client.connectionIsInstalled)+ weak var releasedRouter: DecodeServiceResponseRouter?+ releasedRouter = client.installedRouter++ let reset = Task {+ try await client.resetConversation(epoch: UUID())+ }+ try await Task.sleep(for: .milliseconds(20))+ try responses.fileHandleForWriting.close()++ await #expect(throws: (any Error).self) { try await reset.value }+ let deadline = ContinuousClock.now + .seconds(5)+ while client.connectionIsInstalled, ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(!client.connectionIsInstalled,+ "the router ended but its handles stayed installed")++ let releaseDeadline = ContinuousClock.now + .seconds(5)+ while releasedRouter != nil, ContinuousClock.now < releaseDeadline {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(releasedRouter == nil,+ "the invalidated connection retained its response router")++ try? commands.fileHandleForReading.close()+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceConversationResetTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceConversationResetTests.swiftnew file mode 100644index 00000000..2b5f7c0e--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceConversationResetTests.swift@@ -0,0 +1,12 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct DecodeServiceConversationResetTests {+ @Test func aResetWithNoConnectionFailsRatherThanReportingSuccess() async throws {+ let client = DecodeServiceInferenceClient()+ await #expect(throws: AppInferenceError.self) {+ try await client.resetConversation(epoch: UUID())+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppConversationLifecycleTests.swift b/Tests/TurboFieldfareApp/Core/State/AppConversationLifecycleTests.swiftnew file mode 100644index 00000000..1293b964--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppConversationLifecycleTests.swift@@ -0,0 +1,138 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++/// The three gaps a review of this branch named: unload with a conversation+/// open, the Cancel semantics the app actually ships, and a reset the service+/// never heard. Each of these had no coverage, and each hid a defect.+@Suite struct AppConversationLifecycleTests {+ @MainActor+ private func readyModel(_ client: FakeInferenceClient) async throws -> AppModel {+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(modelDirectory: directory, client: client)+ model.modelPathText = directory.path+ try await client.ensureLoaded(+ modelDirectory: directory, maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions, forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ return model+ }++ @MainActor+ private func finish(_ model: AppModel) async {+ while model.isRunning { await Task.yield() }+ }++ /// The shipping client stops cooperatively: the turn ends at a token+ /// boundary and arrives as `.finished`, so it is committed and its partial+ /// reply stays. Every other cancel test models the in-process client, which+ /// does the opposite — so this path had no coverage at all.+ @MainActor+ @Test func acooperativeStopCommitsTheTurnAndKeepsWhatItProduced() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(40),+ cancelSemantics: .cooperativeStop)+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ while model.isRunning, model.liveTokenCount == 0 { await Task.yield() }+ model.cancel()+ await finish(model)++ // Not counting it would put the app behind the service, and the next+ // turn would be refused.+ #expect(model.conversation.committedTurns == 1)+ #expect(model.conversation.turns.map(\.role) == [.user, .assistant])+ #expect(model.diagnostics?.stopReason == .cancelled)+ #expect(model.error == nil, "stopping is not an error")++ // The conversation continues from it, with a turn that really ran:+ // a double that never lowered its stop flag made the next run break at+ // its first token, and this assertion passed on an empty reply.+ model.promptText = "two"+ model.run()+ await finish(model)+ #expect(model.conversation.committedTurns == 2)+ let reply = try #require(model.conversation.turns.last)+ #expect(reply.role == .assistant)+ #expect(!reply.text.isEmpty, "the follow-up turn produced nothing")+ #expect(model.diagnostics?.stopReason != .cancelled,+ "the follow-up turn was stopped by a flag left set")+ }++ /// Pins the *double's* flag hygiene, which every other cooperative-stop+ /// assertion depends on: a fake that never lowered its stop flag made the+ /// following run break at its first token, quietly emptying them. The real+ /// client's equivalent is pinned in the heavy suite, because only a loaded+ /// model exercises its flags.+ @MainActor+ @Test func astopDoesNotLeakIntoTheNextRun() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(30),+ cancelSemantics: .cooperativeStop)+ let model = try await readyModel(client)++ model.promptText = "one"+ model.run()+ while model.isRunning, model.liveTokenCount == 0 { await Task.yield() }+ model.cancel()+ await finish(model)+ #expect(model.diagnostics?.stopReason == .cancelled)++ model.promptText = "two"+ model.run()+ await finish(model)+ #expect(model.diagnostics?.stopReason != .cancelled,+ "the next run inherited the stop")+ #expect((model.diagnostics?.generatedTokens ?? 0) > 1,+ "the next run stopped at one token")+ }++ /// The in-process client rewinds the turn instead, and the app must not+ /// count it. Both clients exist, and the app has to be right for both.+ @MainActor+ @Test func ahardAbortDoesNotCountTheTurnItRewound() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(40),+ cancelSemantics: .hardAbort)+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ while model.isRunning, model.livePrefillDone == 0 { await Task.yield() }+ model.cancel()+ await finish(model)++ #expect(model.conversation.committedTurns == 0)+ #expect(model.conversation.turns.isEmpty)+ #expect(model.error == .cancelled)+ }++ /// `currentHandles()` is nil when the connection is gone, not when the model+ /// is unloaded. Returning normally let the app record an epoch the service+ /// had never heard of — and because it then matched, the reset was never+ /// retried and every later turn was refused with no way back.+ @MainActor+ @Test func aresetTheServiceNeverHeardIsNotRecordedAsOpen() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ await finish(model)+ #expect(client.conversationEpochs.count == 1)++ model.newChat()+ client.failNextReset(with: .unknown("the decode service connection is gone"))+ model.promptText = "after a lost reset"+ model.run()+ await finish(model)++ #expect(model.error != nil, "a lost reset was reported as success")+ #expect(model.conversation.committedTurns == 0,+ "the turn was counted against a lineage the service never opened")++ // And the next attempt opens it again rather than short-circuiting.+ model.promptText = "retry"+ model.run()+ await finish(model)+ #expect(client.conversationEpochs.count == 2,+ "the reset was never retried, so the conversation could not recover")+ #expect(model.conversation.committedTurns == 1)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppGenerationRunIdentityTests.swift b/Tests/TurboFieldfareApp/Core/State/AppGenerationRunIdentityTests.swiftnew file mode 100644index 00000000..328e27c1--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppGenerationRunIdentityTests.swift@@ -0,0 +1,95 @@+import Foundation+import Synchronization+import Testing+@testable import TurboFieldfareAppCore++private actor RunIdentityGate {+ private var isOpen = false+ private var waiters: [CheckedContinuation<Void, Never>] = []++ func wait() async {+ guard !isOpen else { return }+ await withCheckedContinuation { waiters.append($0) }+ }++ func open() {+ isOpen = true+ let pending = waiters+ waiters.removeAll()+ pending.forEach { $0.resume() }+ }+}++private final class RunIdentityInferenceClient: AppModelLifecycleClient, Sendable {+ private let callCount = Mutex(0)+ let firstThrow = RunIdentityGate()+ let secondTerminal = RunIdentityGate()++ func ensureLoaded(modelDirectory: URL,+ maxContextTokens: Int,+ options: AppRuntimeOptions,+ forceLogitsHead: Bool,+ onState: @escaping @Sendable (AppModelLoadState) -> Void) async throws {+ onState(.ready(modelDirectory: modelDirectory, loadSeconds: 0))+ }++ func unload() async {}+ func resetConversation(epoch: UUID) async throws {}+ func cancel() {}++ func generate(_ request: AppGenerationRequest)+ -> AsyncThrowingStream<AppInferenceEvent, Error> {+ let call = callCount.withLock { count in+ defer { count += 1 }+ return count+ }+ return AsyncThrowingStream { continuation in+ let task = Task { [firstThrow, secondTerminal] in+ let message = call == 0 ? "first terminal" : "second terminal"+ if call == 0 {+ continuation.yield(.failed(.unknown(message), partial: nil))+ await firstThrow.wait()+ } else {+ await secondTerminal.wait()+ continuation.yield(.failed(.unknown(message), partial: nil))+ }+ continuation.finish(throwing: AppInferenceError.unknown("\(message) throw"))+ }+ continuation.onTermination = { _ in task.cancel() }+ }+ }+}++@Suite struct AppGenerationRunIdentityTests {+ @MainActor+ @Test func staleStreamFailureCannotTerminateTheNextRun() async throws {+ let directory = FileManager.default.temporaryDirectory+ let client = RunIdentityInferenceClient()+ let model = AppModel(modelDirectory: directory, client: client)+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 0)++ model.promptText = "first"+ model.run()+ while model.isRunning { await Task.yield() }++ model.promptText = "second"+ model.run()+ let secondIdentity = model.runIdentity+ #expect(model.isRunning)+ #expect(model.conversation.hasTurnInFlight)+ #expect(model.outputPromptText == "second")++ await client.firstThrow.open()+ try await Task.sleep(for: .milliseconds(20))++ #expect(model.runIdentity == secondIdentity)+ #expect(model.isRunning, "the first stream's catch terminated the second run")+ #expect(model.conversation.hasTurnInFlight)+ #expect(model.outputPromptText == "second")+ #expect(model.error == nil)++ await client.secondTerminal.open()+ while model.isRunning { await Task.yield() }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swiftindex c10c1655..a819b1c3 100644--- a/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift@@ -119,7 +119,6 @@ import TurboFieldfarelet model = AppModel(modelDirectory: directory, client: client,attachmentStore: store)model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)- model.setSentPromptBehavior(.clear)await attach(model, [source])#expect(model.imageAttachments.count == 1)model.promptText = "describe it"@@ -138,7 +137,7 @@ import TurboFieldfaretry? await Task.sleep(nanoseconds: 5_000_000)}// Clearing the transcript is what finally frees them.- model.clearOutput()+ model.newChat()#expect(model.outputImageAttachments.isEmpty)#expect(stagedFileCount(store) == 0)}@@ -162,7 +161,6 @@ import TurboFieldfarelet model = AppModel(modelDirectory: directory, client: client,attachmentStore: store)model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)- model.setSentPromptBehavior(.clear)await attach(model, [source])model.promptText = "describe it"model.maxNewTokensOverride = 1@@ -316,10 +314,8 @@ import TurboFieldfare"the copies that did not fit were left staged and unreferenced")}- /// With the prompt kept, the composer keeps its images too — and clearing- /// them must still not disturb the answer already on screen.@MainActor- @Test func keepingTheSentPromptKeepsItsImagesWithoutSharingFiles() async throws {+ @Test func sendingMovesImagesFromComposerToTranscriptWithoutSharingFiles() async throws {let (root, store) = makeStore()defer { try? FileManager.default.removeItem(at: root) }let source = try writeSource(root, "source.png", "fixture")@@ -330,7 +326,6 @@ import TurboFieldfarelet model = AppModel(modelDirectory: directory, client: client,attachmentStore: store)model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)- model.setSentPromptBehavior(.keep)await attach(model, [source])model.promptText = "describe it"model.maxNewTokensOverride = 1@@ -339,7 +334,8 @@ import TurboFieldfaretry? await Task.sleep(nanoseconds: 5_000_000)}- #expect(model.imageAttachments.count == 1)+ #expect(model.imageAttachments.isEmpty)+ #expect(model.outputImageAttachments.count == 1)model.clearImages()#expect(model.imageAttachments.isEmpty)let shown = try #require(model.outputImageAttachments.first)@@ -347,6 +343,37 @@ import TurboFieldfare"clearing the composer deleted the transcript's image")}+ @MainActor+ @Test func newChatReleasesTheImagesOfEveryTurnNotJustTheLast() async throws {+ let (root, store) = makeStore()+ defer { try? FileManager.default.removeItem(at: root) }+ let first = try writeSource(root, "first.png", "one")+ let second = try writeSource(root, "second.png", "two")++ let directory = try makeVisionReadyModelInstall("lifetime-multi-turn")+ defer { try? FileManager.default.removeItem(at: directory) }+ let client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)+ let model = AppModel(modelDirectory: directory, client: client,+ attachmentStore: store)+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ model.maxNewTokensOverride = 1++ for source in [first, second] {+ await attach(model, [source])+ model.promptText = "describe it"+ model.run()+ for _ in 0..<200 where model.isRunning {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ }+ #expect(model.conversation.turns.compactMap { $0.images.first }.count == 2,+ "the fixture needs two turns each holding an image")++ model.newChat()+ #expect(stagedFileCount(store) == 0,+ "New chat left an earlier turn's staged image behind")+ }+/// Quitting is the one moment every staged file is certainly unwanted, and/// nothing called `removeAll()` at all.@MainActordiff --git a/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swiftindex 40b3d70d..a2c18067 100644--- a/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift@@ -19,9 +19,24 @@ import TurboFieldfarelet expected = VisionImageTokenBudget.capacity(maxContext: option.tokens,reservedTextTokens: AppModel.reservedPromptTokens)- #expect(model.maximumImageAttachments == max(1, expected))- // A bigger context must never allow fewer images.- #expect(model.maximumImageAttachments >= 1)+ #expect(model.maximumImageAttachments == expected)+ }++ @Test func capacityReachesZeroAtTheConversationBoundary() {+ let context = AppContextLengthOption.fourK.tokens+ let imageCost = VisionImageTokenBudget.maximumTokensPerImage+ #expect(AppModel.imageAttachmentCapacity(+ maxContextTokens: context,+ conversationTokens: context - imageCost) == 1)+ #expect(AppModel.imageAttachmentCapacity(+ maxContextTokens: context,+ conversationTokens: context - imageCost + 1) == 0)+ }++ @Test func unknownConversationPositionHasNoImageCapacity() {+ #expect(AppModel.imageAttachmentCapacity(+ maxContextTokens: AppContextLengthOption.fourK.tokens,+ conversationTokens: nil) == 0)}@MainActordiff --git a/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swiftnew file mode 100644index 00000000..778fa995--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift@@ -0,0 +1,314 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++/// The app and the decode service count committed turns independently, and the+/// service refuses a turn whose index does not match its own count. Every test+/// here pins one way the two counts used to be able to drift, each of which+/// ends the conversation with a rejection the user cannot act on.+@Suite struct AppModelConversationTests {+ @MainActor+ private func readyModel(_ client: FakeInferenceClient) async throws -> AppModel {+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(modelDirectory: directory, client: client)+ model.modelPathText = directory.path+ try await client.ensureLoaded(+ modelDirectory: directory,+ maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions,+ forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ return model+ }++ @MainActor+ private func finish(_ model: AppModel) async {+ while model.isRunning { await Task.yield() }+ }++ @MainActor+ @Test func afreshModelStartsOnTurnZeroOfItsOwnConversation() throws {+ let model = AppModel()+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.promptText = "hello"+ #expect(model.conversation.isEmpty)+ #expect(model.conversation.committedTurns == 0)++ let request = try model.makeRequest()+ // No ticket was taken, so the request is not yet a conversation turn.+ #expect(request.conversationEpoch == nil)+ #expect(request.turnIndex == nil)+ #expect(request.conversationTokens == 0)+ }++ @MainActor+ @Test func eachRunCarriesTheNextTurnIndexOfOneEpoch() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)++ model.promptText = "one"+ model.run()+ let firstEpoch = model.conversation.epoch+ #expect(model.conversation.turns.first?.role == .user,+ "the user's message shows while the model is still thinking")+ await finish(model)+ #expect(model.conversation.committedTurns == 1)++ model.promptText = "two"+ model.run()+ await finish(model)+ #expect(model.conversation.committedTurns == 2)+ #expect(model.conversation.epoch == firstEpoch,+ "one conversation, not one per turn")+ #expect(model.conversation.turns.map(\.role) == [.user, .assistant, .user, .assistant])+ }++ @MainActor+ @Test func theconversationIsOpenedOnceAndReusedAcrossTurns() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)++ model.promptText = "one"+ model.run()+ await finish(model)+ model.promptText = "two"+ model.run()+ await finish(model)++ // Opening it again per turn would reset the KV and undo the entire+ // point of the feature.+ #expect(client.conversationEpochs == [model.conversation.epoch])+ }++ @MainActor+ @Test func newChatOpensAFreshEpochAndEmptiesTheTranscript() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ await finish(model)+ let firstEpoch = model.conversation.epoch++ model.newChat()+ #expect(model.conversation.turns.isEmpty)+ #expect(model.conversation.committedTurns == 0)+ #expect(model.conversation.epoch != firstEpoch)++ model.promptText = "fresh"+ model.run()+ await finish(model)+ #expect(client.conversationEpochs.count == 2)+ #expect(client.conversationEpochs.last == model.conversation.epoch)+ #expect(model.conversation.committedTurns == 1)+ }++ /// A load rebuilds the runner and the KV, so the service's gate goes back+ /// to expecting turn zero. An app that kept its turn list would keep+ /// numbering from where it left off, and the gate would refuse that turn+ /// and every turn after it for the rest of the session.+ @MainActor+ @Test func areloadStartsAnEmptyConversationSoTheCountsCannotDesync() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ await finish(model)+ model.promptText = "two"+ model.run()+ await finish(model)+ #expect(model.conversation.committedTurns == 2)+ let before = model.conversation.epoch++ model.applyLoadState(.ready(+ modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1))++ #expect(model.conversation.committedTurns == 0)+ #expect(model.conversation.turns.isEmpty)+ #expect(model.conversation.epoch != before)+ // The transcript stays — lifecycle actions do not discard it — but the+ // turns move out of the model's context and the break says where.+ #expect(model.hasOutputTranscript)+ #expect(model.archivedPairs.count == 2)+ #expect(model.transcriptContextBreak == 2)++ model.promptText = "after reload"+ model.run()+ await finish(model)+ #expect(model.conversation.committedTurns == 1)+ #expect(client.conversationEpochs.last == model.conversation.epoch)+ }++ /// Pointing the app at a different model releases the runner and the KV,+ /// and the service ends its gate's lineage with it. `applyLoadState`'s+ /// branch for this is unreachable — every production transition to+ /// `.notLoaded` assigns `loadState` directly — so the app kept a turn count+ /// and an epoch for a conversation that no longer existed, and drew it with+ /// no break. Every such site now ends the conversation; this is the one+ /// reachable without a real install fixture.+ @MainActor+ @Test func releasingTheKVEndsTheConversationAndMarksTheTranscript() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ await finish(model)+ model.promptText = "two"+ model.run()+ await finish(model)+ #expect(model.conversation.committedTurns == 2)+ let before = model.conversation.epoch++ model.setModelURL(FileManager.default.temporaryDirectory+ .appendingPathComponent("another-model", isDirectory: true))++ #expect(model.conversation.committedTurns == 0)+ #expect(model.conversation.turns.isEmpty)+ #expect(model.conversation.epoch != before)+ // The transcript survives — lifecycle actions do not discard it — but+ // the turns are marked as out of the model's context.+ #expect(model.archivedPairs.count == 2)+ #expect(model.transcriptContextBreak == 2)+ }++ @MainActor+ @Test func areloadEndsTheLineageSoTheNextTurnReopensIt() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ await finish(model)+ #expect(client.conversationEpochs.count == 1)++ // A load rebuilds the runner and the KV. Resuming onto it would resume+ // onto a cache that no longer holds the conversation.+ model.loadState = .ready(+ modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1)+ model.applyLoadState(.ready(+ modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1))++ model.promptText = "two"+ model.run()+ await finish(model)+ #expect(client.conversationEpochs.count == 2,+ "the turn after a load has to open the conversation again")+ }++ /// The live fields keep holding the last finished turn so its answer stays+ /// on screen. Drawing that pair as history too would show it twice.+ @MainActor+ @Test func historyExcludesTheTurnTheLiveFieldsAreStillShowing() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)++ model.promptText = "one"+ model.run()+ await finish(model)+ #expect(model.conversation.completedPairs.count == 1)+ #expect(model.transcriptHistory.isEmpty,+ "the only finished turn is the one still drawn live")++ model.promptText = "two"+ model.run()+ await finish(model)+ #expect(model.conversation.completedPairs.count == 2)+ #expect(model.transcriptHistory.count == 1)+ #expect(model.transcriptHistory[0].user.text == "one")+ }++ @MainActor+ @Test func copyConversationSpansEveryTurn() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)+ model.promptText = "first question"+ model.run()+ await finish(model)+ model.promptText = "second question"+ model.run()+ await finish(model)++ let text = model.outputConversationPlainText+ #expect(text.contains("first question"))+ #expect(text.contains("second question"))+ let first = try #require(text.range(of: "first question"))+ let second = try #require(text.range(of: "second question"))+ #expect(first.lowerBound < second.lowerBound, "turns are out of order")+ }++ @MainActor+ @Test func newChatEmptiesTheHistoryTheTranscriptDraws() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ await finish(model)+ model.promptText = "two"+ model.run()+ await finish(model)+ #expect(!model.transcriptHistory.isEmpty)++ model.newChat()+ #expect(model.transcriptHistory.isEmpty)+ #expect(model.outputConversationPlainText.isEmpty)+ #expect(!model.hasOutputTranscript)+ }++ /// Stop, then send again. The cancelled turn was rewound by the runtime and+ /// the service did not count it; counting it here put the app one ahead for+ /// the rest of the conversation, and the gate's refusal of the next turn+ /// reached the user as "decode service runtime profile changed during+ /// generation" — a wrong diagnosis for a real fault.+ @MainActor+ @Test func acancelledTurnIsNotCountedSoTheNextOneStillFits() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(60))+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ await finish(model)+ #expect(model.conversation.committedTurns == 1)++ model.promptText = "two"+ model.run()+ // Wait for the run to actually be under way. Cancelling on the same+ // tick races the double's own task registration, not the product.+ while model.isRunning, model.livePrefillDone == 0 { await Task.yield() }+ model.cancel()+ await finish(model)++ #expect(model.conversation.committedTurns == 1,+ "a rewound turn was counted, so the next index will be refused")+ #expect(model.conversation.turns.count == 2,+ "the stopped turn entered the conversation the model can see")+ // What the user was looking at stays on screen as the current turn; it+ // simply never becomes history, because the model cannot see it.+ #expect(model.hasOutputTranscript)+ #expect(model.outputPromptText == "two")+ #expect(!model.conversation.hasTurnInFlight)++ // And the next turn takes the position the stopped one did not consume.+ // The position the stopped turn did not consume is still free, which is+ // the whole point: the service's gate expects exactly this index.+ #expect(model.conversation.committedTurns == 1)+ model.promptText = "three"+ #expect(model.canRun, "the app refused to send after a stop")+ }++ @MainActor+ @Test func arefusedRunGivesThePromptBackAndKeepsTheTurnIndex() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client)+ model.promptText = "one"+ model.run()+ await finish(model)++ // A request the client refuses never reaches the KV, so the app must+ // not count it — the service does not either.+ model.maxContextTokens = model.maxContextTokens * 2+ model.promptText = "two"+ model.run()+ await finish(model)++ #expect(model.conversation.committedTurns == 1)+ #expect(model.conversation.turns.count == 2, "the refused turn left no trace")+ #expect(model.promptText == "two", "the user gets their message back")+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swiftindex 48fd1883..e70789d7 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift@@ -16,7 +16,7 @@ import Testing#expect(model.outputResponsePlainText == "lossless output")#expect(model.outputConversationPlainText == "Answer:\nlossless output")- model.clearOutput()+ model.newChat()#expect(client.generationTranscriptMailbox.completeText.isEmpty)#expect(model.outputResponsePlainText.isEmpty)#expect(model.outputConversationPlainText.isEmpty)diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swiftindex fd5da17b..daab1472 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift@@ -149,6 +149,32 @@ import Testing#expect(!model.hasStaleLoadedRuntime)}+ @MainActor+ @Test func promptExamplesOnlyShowBeforeTheFirstTurnWithAnEmptyComposer() async {+ let model = readyModel(client: MockInferenceClient(response: "answer"))++ #expect(model.shouldShowPromptExamples)+ model.promptText = "draft"+ #expect(!model.shouldShowPromptExamples)++ model.promptText = ""+ model.setShowPromptExamples(false)+ #expect(!model.shouldShowPromptExamples)++ model.setShowPromptExamples(true)+ model.promptText = "first turn"+ model.run()+ await waitForIdle(model)++ #expect(model.promptText.isEmpty)+ #expect(model.hasOutputTranscript)+ #expect(!model.shouldShowPromptExamples,+ "an empty composer must not cover an existing conversation with examples")++ model.newChat()+ #expect(model.shouldShowPromptExamples)+ }+@MainActor@Test func mockRunUpdatesOutputAndDiagnostics() async throws {let client = MockInferenceClient(response: "alpha beta", tokenDelayNanos: 1)@@ -178,7 +204,7 @@ import Testingmodel.run()#expect(model.outputPromptText == "original prompt")- #expect(model.promptText == "original prompt")+ #expect(model.promptText.isEmpty)#expect(model.hasOutputTranscript)#expect(model.outputResponsePlainText.isEmpty)#expect(model.outputConversationPlainText == "You:\noriginal prompt")@@ -199,7 +225,6 @@ import Testingresponse: "answer",tokenDelayNanos: 20_000_000)let model = readyModel(client: client)- model.setSentPromptBehavior(.clear)model.promptText = "original prompt"model.maxNewTokensOverride = 1@@ -220,7 +245,6 @@ import Testing@MainActor@Test func failedValidationDoesNotClearPrompt() {let model = readyModel(client: MockInferenceClient(response: "answer"))- model.setSentPromptBehavior(.clear)model.promptText = "keep invalid prompt"model.maxNewTokensOverride = 0@@ -275,7 +299,7 @@ import Testing#expect(model.outputConversationPlainText.hasPrefix("You:\nstop after token\n\nAnswer:\n"))- model.clearOutput()+ model.newChat()#expect(!model.hasOutputTranscript)#expect(model.outputPromptText.isEmpty)#expect(model.outputText.isEmpty)@@ -307,7 +331,7 @@ import Testing#expect(model.outputConversationPlainText == "You:\nprefill prompt")#expect(model.hasOutputTranscript)- model.clearOutput()+ model.newChat()#expect(!model.hasOutputTranscript)}diff --git a/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swiftindex c6df5fe0..055dc6e5 100644--- a/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swift+++ b/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swift@@ -6,8 +6,13 @@ import Synchronizationfinal class FakeInferenceClient: AppModelLifecycleClient, Sendable {private struct State: Sendable {var loadedKey: AppLoadedRuntimeKey?+ var conversationEpochs: [UUID] = []+ var resetFailure: AppInferenceError?+ var stopRequested = false}+ enum CancelSemantics: Sendable { case hardAbort, cooperativeStop }+private final class StateBox: Sendable {let value = Mutex(State())}@@ -15,9 +20,16 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {private let state = StateBox()private let generationTasks = GenerationTaskRegistry()private let eventDelay: Duration+ private let cancelSemantics: CancelSemantics- init(eventDelay: Duration = .milliseconds(80)) {+ init(eventDelay: Duration = .milliseconds(80),+ cancelSemantics: CancelSemantics = .hardAbort) {self.eventDelay = eventDelay+ self.cancelSemantics = cancelSemantics+ }++ func failNextReset(with error: AppInferenceError) {+ state.value.withLock { $0.resetFailure = error }}func ensureLoaded(modelDirectory: URL,@@ -47,6 +59,20 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {state.value.withLock { $0.loadedKey = nil }}+ var conversationEpochs: [UUID] {+ state.value.withLock { $0.conversationEpochs }+ }++ func resetConversation(epoch: UUID) async throws {+ if let failure = state.value.withLock({ value -> AppInferenceError? in+ defer { value.resetFailure = nil }+ return value.resetFailure+ }) {+ throw failure+ }+ state.value.withLock { $0.conversationEpochs.append(epoch) }+ }+func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {AsyncThrowingStream { continuation indo {@@ -87,7 +113,12 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {}func cancel() {- generationTasks.takeCurrent()?.cancel()+ switch cancelSemantics {+ case .hardAbort:+ generationTasks.takeCurrent()?.cancel()+ case .cooperativeStop:+ state.value.withLock { $0.stopRequested = true }+ }}private func streamResponse(@@ -99,6 +130,8 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {var firstTokenDate: Date?var prefillEnd = startvar generated = 0+ var stoppedEarly = false+ state.value.withLock { $0.stopRequested = false }do {for step in 1...3 {@@ -117,6 +150,10 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {for (index, piece) in pieces.enumerated() {try await Task.sleep(for: eventDelay)try Task.checkCancellation()+ if state.value.withLock({ $0.stopRequested }) {+ stoppedEarly = true+ break+ }if firstTokenDate == nil { firstTokenDate = Date() }generated += 1continuation.yield(.token(AppTokenEvent(@@ -129,7 +166,8 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {let decodeSeconds = max(end.timeIntervalSince(prefillEnd), 0)continuation.yield(.finished(AppDiagnostics(generatedTokens: generated,- stopReason: generated >= request.maxNewTokens ? .maxTokens : .eos,+ stopReason: stoppedEarly ? .cancelled+ : (generated >= request.maxNewTokens ? .maxTokens : .eos),promptTokenCount: max(1, request.prompt.split(whereSeparator: \.isWhitespace).count),prefillSeconds: prefillEnd.timeIntervalSince(start),timeToFirstTokenSeconds: firstTokenDate.map { $0.timeIntervalSince(prefillEnd) },diff --git a/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swiftindex c7e7ba3c..055e351a 100644--- a/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift+++ b/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift@@ -191,10 +191,19 @@ final class MockInferenceClient: AppInferenceClient, @unchecked Sendable {_ = memorySampler.sample()let decodeStart = prefillEnd ?? startlet decodeElapsed = max(Date().timeIntervalSince(decodeStart), 0)+ let promptTokens = mockPromptTokenCount(request.prompt)+ let committedGenerated = stopReason == .maxTokens ? max(0, generated - 1) : generated+ let conversationTokens = request.continuesConversation+ ? min(request.maxContextTokens,+ request.conversationTokens + promptTokens + committedGenerated)+ : nilreturn AppDiagnostics(generatedTokens: generated,stopReason: stopReason,- promptTokenCount: mockPromptTokenCount(request.prompt),+ promptTokenCount: promptTokens,+ cachedPromptTokens: request.continuesConversation+ ? request.conversationTokens : nil,+ conversationTokens: conversationTokens,prefillSeconds: prefillEnd.map { max($0.timeIntervalSince(start), 0) },timeToFirstTokenSeconds: firstToken.map { max($0.timeIntervalSince(decodeStart), 0) },decodeSeconds: decodeElapsed,diff --git a/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swiftindex 2abeb36b..6add911c 100644--- a/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swift+++ b/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swift@@ -46,6 +46,8 @@ final class MockLifecycleInferenceClient: AppModelLifecycleClient, @unchecked Se}+ func resetConversation(epoch _: UUID) async throws {}+func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {AsyncThrowingStream { continuation inlet task = Task {diff --git a/Tests/TurboFieldfareApp/MacPresentation/ConversationContextPresentationTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ConversationContextPresentationTests.swiftnew file mode 100644index 00000000..4ba46bc2--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/ConversationContextPresentationTests.swift@@ -0,0 +1,96 @@+import Foundation+import Testing+@testable import TurboFieldfareMacPresentation++@Suite struct ConversationContextPresentationTests {+ @Test func gaugeIsCompactAtBothScales() {+ #expect(ConversationContextPresentation.gauge(kvTokens: 58, maxContext: 2_048)+ == "58/2.0K")+ #expect(ConversationContextPresentation.gauge(kvTokens: 1_500, maxContext: 16_384)+ == "1.5K/16K")+ #expect(ConversationContextPresentation.gauge(kvTokens: 0, maxContext: 0)+ == "\u{2014}", "an unknown window must not read as a full one")+ }++ /// The committed count only moves when a turn finishes, so a gauge reading+ /// it sits still through the whole run and then jumps. These pin the live+ /// figure through each phase of a turn.+ @Test func theLiveCountTracksTheTurnThroughEveryPhase() {+ // Nothing reported yet — an image encoding, or the first chunk not in.+ // The last thing that was true is the committed figure.+ #expect(ConversationContextPresentation.liveTokens(+ prefillDone: 0, prefillTotal: 0, generated: 0, committed: 56) == 56)+ // Prefill reports absolute position, so it is the KV position directly.+ #expect(ConversationContextPresentation.liveTokens(+ prefillDone: 70, prefillTotal: 120, generated: 0, committed: 56) == 70)+ // The newest sampled token is the next producer boundary and is not in+ // KV yet. The first sample therefore leaves the committed position at+ // the prompt boundary.+ #expect(ConversationContextPresentation.liveTokens(+ prefillDone: 120, prefillTotal: 120, generated: 1, committed: 56) == 120)+ #expect(ConversationContextPresentation.liveTokens(+ prefillDone: 120, prefillTotal: 120, generated: 9, committed: 56) == 128)+ }++ @Test func theLiveCountNeverGoesBackwardsWithinATurn() {+ var previous = 0+ for done in stride(from: 0, through: 120, by: 20) {+ let value = ConversationContextPresentation.liveTokens(+ prefillDone: done, prefillTotal: 120, generated: 0, committed: 0)+ #expect(value >= previous, "the gauge went backwards during prefill")+ previous = value+ }+ for generated in 1...10 {+ let value = ConversationContextPresentation.liveTokens(+ prefillDone: 120, prefillTotal: 120, generated: generated, committed: 0)+ #expect(value >= previous, "the gauge went backwards during decode")+ previous = value+ }+ }++ @Test func fractionIsClampedBothWays() {+ #expect(ConversationContextPresentation.fraction(kvTokens: 0, maxContext: 100) == 0)+ #expect(ConversationContextPresentation.fraction(kvTokens: 50, maxContext: 100) == 0.5)+ // A KV count larger than the window is a bug elsewhere, not a reason to+ // draw a gauge past its end.+ #expect(ConversationContextPresentation.fraction(kvTokens: 500, maxContext: 100) == 1)+ #expect(ConversationContextPresentation.fraction(kvTokens: 5, maxContext: 0) == 0)+ }++ @Test func theWarningArrivesBeforeTheWallNotAtIt() {+ #expect(!ConversationContextPresentation.isNearingLimit(+ kvTokens: 79, maxContext: 100))+ #expect(ConversationContextPresentation.isNearingLimit(+ kvTokens: 80, maxContext: 100), "the boundary is inclusive")+ #expect(ConversationContextPresentation.isNearingLimit(+ kvTokens: 100, maxContext: 100))+ }++ @Test func theExplanationNamesTheReusedCount() {+ let text = ConversationContextPresentation.explanation(+ kvTokens: 1_234, maxContext: 8_192, cachedTokens: 1_000)+ #expect(text.contains("1,234"))+ #expect(text.contains("8,192"))+ #expect(text.contains("1,000"))+ #expect(text.contains("reused"))+ }++ @Test func afirstTurnSaysItHadNothingToReuse() {+ let text = ConversationContextPresentation.explanation(+ kvTokens: 20, maxContext: 8_192, cachedTokens: 0)+ #expect(text.contains("nothing to reuse"))+ }++ @Test func aoneShotRunSaysNothingAboutReuseAtAll() {+ let text = ConversationContextPresentation.explanation(+ kvTokens: 20, maxContext: 8_192, cachedTokens: nil)+ #expect(!text.contains("reuse"))+ }++ @Test func nearingTheLimitExplainsTheRefusalInAdvance() {+ let text = ConversationContextPresentation.explanation(+ kvTokens: 7_500, maxContext: 8_192, cachedTokens: 7_000)+ #expect(text.contains("refused"))+ #expect(text.contains("New chat") || text.contains("new chat"))+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptMultiTurnTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptMultiTurnTests.swiftnew file mode 100644index 00000000..2cc85686--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptMultiTurnTests.swift@@ -0,0 +1,250 @@+import AppKit+import Foundation+import Testing+@testable import TurboFieldfareMacPresentation++/// A chat renders every completed turn above the live one. The rule that makes+/// that affordable is that history is drawn once: the controller replaces only+/// the live turn, so TextKit never lays out the conversation again per token.+/// Every test here pins one way that used to break — `rebuild` called+/// `setAttributedString`, which took the history with it.+@MainActor+@Suite struct TranscriptMultiTurnTests {+ private func controller() -> InstructionTranscriptDocumentController {+ InstructionTranscriptDocumentController()+ }++ private func firstTurn(+ _ controller: InstructionTranscriptDocumentController,+ _ storage: NSMutableAttributedString,+ prompt: String = "first question",+ response: String = "first answer"+ ) {+ _ = controller.synchronize(+ storage: storage, prompt: prompt, response: response, isTerminal: true)+ controller.sealTurn(storage: storage)+ }++ @Test func asealedTurnBecomesHistoryAndTheLiveTurnStartsAfterIt() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)++ #expect(controller.frozenLength == storage.length)+ #expect(storage.string.contains("first question"))+ #expect(storage.string.contains("first answer"))+ #expect(controller.assistantRange.location == controller.frozenLength)+ #expect(controller.assistantRange.length == 0)+ }++ @Test func asecondTurnLeavesTheFirstBytesUntouched() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)+ let history = storage.attributedSubstring(+ from: NSRange(location: 0, length: controller.frozenLength))++ _ = controller.synchronize(+ storage: storage, prompt: "second question", response: "", isTerminal: false)+ _ = controller.synchronize(+ storage: storage, prompt: "second question", response: "second", isTerminal: false)+ _ = controller.synchronize(+ storage: storage, prompt: "second question", response: "second answer",+ isTerminal: true)++ let after = storage.attributedSubstring(+ from: NSRange(location: 0, length: controller.frozenLength))+ #expect(after.isEqual(to: history), "the first turn was redrawn")+ #expect(storage.string.contains("first answer"))+ #expect(storage.string.contains("second answer"))+ }++ /// Streaming into turn two must still be an append, not a rebuild. If it+ /// rebuilds per token the conversation is laid out again on every tick, and+ /// the cost grows with the whole transcript rather than the answer.+ @Test func streamingTheSecondTurnAppendsRatherThanRebuilds() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)++ _ = controller.synchronize(+ storage: storage, prompt: "second", response: "a", isTerminal: false)+ var mutations: [InstructionTranscriptDocumentController.Mutation] = []+ for text in ["ab", "abc", "abcd"] {+ let update = controller.synchronize(+ storage: storage, prompt: "second", response: text, isTerminal: false)+ mutations.append(update.mutation)+ }+ #expect(!mutations.contains(.rebuilt), "a token tick rebuilt the document")+ #expect(controller.assistantRange.location >= controller.frozenLength)+ }++ /// A rebuild inside the live turn is ordinary — a prompt edit, a response+ /// that does not extend the last one. It must still not reach above the+ /// frozen mark.+ @Test func arebuildInTheLiveTurnDoesNotReachTheHistory() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)+ let frozen = controller.frozenLength+ let history = storage.attributedSubstring(+ from: NSRange(location: 0, length: frozen))++ _ = controller.synchronize(+ storage: storage, prompt: "second", response: "aaa", isTerminal: false)+ // Not an extension of "aaa", so this is the rebuild path.+ _ = controller.synchronize(+ storage: storage, prompt: "second", response: "bbb", isTerminal: false)++ #expect(controller.frozenLength == frozen)+ #expect(storage.attributedSubstring(+ from: NSRange(location: 0, length: frozen)).isEqual(to: history))+ #expect(storage.string.contains("bbb"))+ #expect(!storage.string.contains("aaa"))+ }++ @Test func threeTurnsAccumulateInOrder() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ for index in 1...3 {+ _ = controller.synchronize(+ storage: storage, prompt: "question \(index)",+ response: "answer \(index)", isTerminal: true)+ controller.sealTurn(storage: storage)+ }+ let text = storage.string+ let one = try? #require(text.range(of: "answer 1"))+ let two = try? #require(text.range(of: "answer 2"))+ let three = try? #require(text.range(of: "answer 3"))+ #expect(one != nil && two != nil && three != nil)+ if let one, let two, let three {+ #expect(one.lowerBound < two.lowerBound)+ #expect(two.lowerBound < three.lowerBound)+ }+ }++ @Test func sealingAnEmptyLiveTurnIsANoOp() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)+ let frozen = controller.frozenLength+ // A refused turn leaves nothing drawn; sealing it would insert a blank+ // gap the user never earned.+ controller.sealTurn(storage: storage)+ #expect(controller.frozenLength == frozen)+ #expect(storage.length == frozen)+ }++ /// A reload takes the KV but not the transcript, so the turns above the+ /// break are on screen and not in context. Saying so is the difference+ /// between a transcript the user can trust and one that quietly implies the+ /// model remembers what it cannot.+ @Test func acontextBreakFreezesAndSeparatesTheArchivedTurns() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)+ let beforeBreak = controller.frozenLength++ controller.appendContextBreak(+ storage: storage, text: "Earlier turns are no longer in the model's context")+ #expect(controller.frozenLength > beforeBreak)+ #expect(storage.string.contains("no longer in the model's context"))+ #expect(controller.assistantRange.location == controller.frozenLength)++ // The turn after the break draws below it and leaves it alone.+ _ = controller.synchronize(+ storage: storage, prompt: "after", response: "reply", isTerminal: true)+ let text = storage.string+ let marker = try? #require(text.range(of: "no longer in the model's context"))+ let after = try? #require(text.range(of: "after"))+ if let marker, let after { #expect(marker.lowerBound < after.lowerBound) }+ #expect(text.contains("first answer"))+ }++ @Test func acontextBreakIsRefusedWhileALiveTurnIsDrawn() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)+ _ = controller.synchronize(+ storage: storage, prompt: "live", response: "partial", isTerminal: false)+ let frozen = controller.frozenLength+ // Inserting it here would put the marker above the live turn's text+ // instead of between the turns, and strand `frozenLength` mid-turn.+ controller.appendContextBreak(storage: storage, text: "break")+ #expect(controller.frozenLength == frozen)+ #expect(!storage.string.contains("break"))+ }++ /// Right-clicking inside a turn has to name *that* turn's answer. Falling+ /// back to the newest one would copy the wrong text while looking correct,+ /// which is worse than offering nothing.+ @Test func eachTurnReportsItsOwnAnswerByCharacterIndex() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage, prompt: "q1", response: "answer one")+ let firstEnd = controller.frozenLength+ firstTurn(controller, storage, prompt: "q2", response: "answer two")+ let secondEnd = controller.frozenLength+ _ = controller.synchronize(+ storage: storage, prompt: "q3", response: "live answer", isTerminal: false)++ #expect(controller.answer(at: 1) == "answer one")+ #expect(controller.answer(at: firstEnd - 1) == "answer one")+ #expect(controller.answer(at: firstEnd + 1) == "answer two")+ #expect(controller.answer(at: secondEnd - 1) == "answer two")+ // The live turn is included: it is the one a reader most wants, and it+ // is not sealed until the next run starts.+ #expect(controller.answer(at: secondEnd + 1) == "live answer")+ }++ @Test func aturnWithNoAnswerOffersNothingToCopy() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ _ = controller.synchronize(+ storage: storage, prompt: "asked", response: "", isTerminal: false)+ #expect(controller.answer(at: 0) == nil)+ controller.sealTurn(storage: storage)+ #expect(controller.answer(at: 0) == nil, "an empty answer is not copyable")+ }++ @Test func resetTranscriptForgetsTheTurnAnswers() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage, prompt: "q", response: "old answer")+ controller.resetTranscript(storage: storage)+ #expect(controller.answer(at: 0) == nil)+ }++ @Test func resetTranscriptClearsHistoryAndTheFrozenMark() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)+ _ = controller.synchronize(+ storage: storage, prompt: "second", response: "live", isTerminal: false)++ controller.resetTranscript(storage: storage)+ #expect(storage.length == 0)+ #expect(controller.frozenLength == 0)+ #expect(controller.assistantRange == NSRange(location: 0, length: 0))++ // And the next turn behaves like a first turn again.+ _ = controller.synchronize(+ storage: storage, prompt: "fresh", response: "answer", isTerminal: true)+ #expect(storage.string.contains("fresh"))+ #expect(!storage.string.contains("first question"))+ }++ /// The single-turn path is what every existing test covers, so its+ /// behaviour must be identical while nothing has been sealed.+ @Test func withNothingSealedTheControllerStillReplacesTheWholeDocument() {+ let controller = controller()+ let storage = NSMutableAttributedString()+ _ = controller.synchronize(+ storage: storage, prompt: "one", response: "first", isTerminal: false)+ _ = controller.synchronize(+ storage: storage, prompt: "two", response: "second", isTerminal: true)+ #expect(controller.frozenLength == 0)+ #expect(!storage.string.contains("one"))+ #expect(storage.string.contains("two"))+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptSyncPlannerTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptSyncPlannerTests.swiftnew file mode 100644index 00000000..8611fcba--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptSyncPlannerTests.swift@@ -0,0 +1,117 @@+import Foundation+import Testing+@testable import TurboFieldfareMacPresentation++/// These decisions lived inside a private view coordinator, where no test could+/// reach them — which is why three defects survived two reviews. Each test here+/// pins one of them.+@Suite struct TranscriptSyncPlannerTests {+ private func input(epoch: UUID, history: Int, contextBreak: Int? = nil,+ startedNewRun: Bool = false,+ firstSynchronize: Bool = false) -> TranscriptSyncPlanner.Input {+ .init(epoch: epoch, historyCount: history, contextBreak: contextBreak,+ startedNewRun: startedNewRun, firstSynchronize: firstSynchronize)+ }++ @Test func afreshCoordinatorDrawsTheHistoryItFinds() {+ var planner = TranscriptSyncPlanner()+ let epoch = UUID()+ #expect(planner.plan(input(epoch: epoch, history: 3, firstSynchronize: true))+ == [.reset, .drawPair(index: 0), .drawPair(index: 1), .drawPair(index: 2)])+ // Nothing owed on the next pass.+ #expect(planner.plan(input(epoch: epoch, history: 3)).isEmpty)+ }++ @Test func anewRunSealsTheTurnAlreadyOnScreenRatherThanRedrawingIt() {+ var planner = TranscriptSyncPlanner()+ let epoch = UUID()+ _ = planner.plan(input(epoch: epoch, history: 0, firstSynchronize: true))+ // Turn one finished and a second run started: history grew by one and+ // that pair is already drawn as the live turn.+ #expect(planner.plan(input(epoch: epoch, history: 1, startedNewRun: true))+ == [.sealDrawnTurn])+ }++ @Test func anewEpochResetsBeforeAnythingElse() {+ var planner = TranscriptSyncPlanner()+ let first = UUID()+ _ = planner.plan(input(epoch: first, history: 2, firstSynchronize: true))+ let steps = planner.plan(input(epoch: UUID(), history: 0))+ #expect(steps == [.reset])+ #expect(planner.renderedHistory == 0)+ #expect(!planner.renderedContextBreak)+ }++ /// The break separates the turns above it from the model's context, so it+ /// has to be written after they are drawn. Planning it first put it above+ /// the very turns it sits under.+ @Test func thecontextBreakComesAfterTheHistoryItSeparates() {+ var planner = TranscriptSyncPlanner()+ let epoch = UUID()+ let steps = planner.plan(input(epoch: epoch, history: 2, contextBreak: 2,+ firstSynchronize: true))+ #expect(steps == [.reset, .drawPair(index: 0), .drawPair(index: 1),+ .appendContextBreak])+ let breakIndex = try? #require(steps.firstIndex(of: .appendContextBreak))+ let lastPair = try? #require(steps.lastIndex(of: .drawPair(index: 1)))+ if let breakIndex, let lastPair { #expect(lastPair < breakIndex) }+ }++ /// A reload archives its turns and changes the epoch in the same pass. The+ /// break used to be skipped on exactly that pass, and nothing scheduled+ /// another — archived turns sat on screen unmarked until an unrelated+ /// change forced one.+ @Test func areloadDrawsItsBreakOnTheSamePassAsTheReset() {+ var planner = TranscriptSyncPlanner()+ let before = UUID()+ _ = planner.plan(input(epoch: before, history: 1, firstSynchronize: true))+ let steps = planner.plan(input(epoch: UUID(), history: 1, contextBreak: 1))+ #expect(steps.contains(.appendContextBreak),+ "the archived turns were left with no break until some later pass")+ #expect(steps.first == .reset)+ }++ /// The append only writes at the frozen boundary and can refuse. Latching+ /// the flag anyway meant one refusal suppressed the break for good.+ @Test func arefusedBreakIsPlannedAgainInsteadOfBeingLatchedOff() {+ var planner = TranscriptSyncPlanner()+ let epoch = UUID()+ let first = planner.plan(input(epoch: epoch, history: 1, contextBreak: 1,+ firstSynchronize: true))+ #expect(first.contains(.appendContextBreak))+ // The coordinator does not call `markContextBreakDrawn` — the append+ // refused because a live turn was drawn.+ #expect(planner.plan(input(epoch: epoch, history: 1, contextBreak: 1))+ == [.appendContextBreak])++ planner.markContextBreakDrawn()+ #expect(planner.plan(input(epoch: epoch, history: 1, contextBreak: 1)).isEmpty,+ "the break was drawn twice")+ }++ /// A seal that finds nothing to freeze must not consume the pair it was+ /// meant to freeze, or that turn is in the KV and permanently absent from+ /// the transcript.+ @Test func asealThatFrozeNothingLeavesThePairStillOwed() {+ var planner = TranscriptSyncPlanner()+ let epoch = UUID()+ _ = planner.plan(input(epoch: epoch, history: 0, firstSynchronize: true))+ #expect(planner.plan(input(epoch: epoch, history: 1, startedNewRun: true))+ == [.sealDrawnTurn])+ #expect(planner.renderedHistory == 1)++ planner.sealFoundNothingToFreeze(historyCount: 1)+ #expect(planner.renderedHistory == 0)+ // So the next pass draws it properly instead of skipping it forever.+ #expect(planner.plan(input(epoch: epoch, history: 1))+ == [.drawPair(index: 0)])+ }++ @Test func nothingIsPlannedWhenTheTranscriptIsAlreadyInStep() {+ var planner = TranscriptSyncPlanner()+ let epoch = UUID()+ _ = planner.plan(input(epoch: epoch, history: 2, firstSynchronize: true))+ planner.markContextBreakDrawn()+ #expect(planner.plan(input(epoch: epoch, history: 2, contextBreak: 2)).isEmpty)+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptTextViewTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptTextViewTests.swiftindex 5cf0c1e6..9498daf6 100644--- a/Tests/TurboFieldfareApp/MacPresentation/TranscriptTextViewTests.swift+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptTextViewTests.swift@@ -200,4 +200,35 @@ import Testing#expect(board.string(forType: .string) == rendered.string)}++ @Test func contextMenuKeepsOnlyTheTranscriptCommands() throws {+ let view = Self.view(NSAttributedString(string: "Earlier answer"))+ view.answerAtCharacterIndex = { _ in "Earlier answer" }+ view.lastAnswerText = { "Last answer" }+ view.conversationText = { "Whole conversation" }+ view.startNewChat = {}+ view.setSelectedRange(NSRange(location: 0, length: 7))+ let event = try #require(NSEvent.mouseEvent(+ with: .rightMouseDown,+ location: .zero,+ modifierFlags: [],+ timestamp: 0,+ windowNumber: 0,+ context: nil,+ eventNumber: 0,+ clickCount: 1,+ pressure: 1))++ let menu = try #require(view.menu(for: event))++ #expect(!menu.allowsContextMenuPlugIns,+ "AppKit appends Services when contextual-menu plug-ins are enabled")+ #expect(menu.items.filter { !$0.isSeparatorItem }.map(\.title) == [+ "Copy This Answer",+ "Copy Selection",+ "Copy Last Answer",+ "Copy Conversation",+ "New Chat",+ ])+ }}diff --git a/Tests/TurboFieldfareDecodeService/DecodeConversationGateTests.swift b/Tests/TurboFieldfareDecodeService/DecodeConversationGateTests.swiftnew file mode 100644index 00000000..4bab0002--- /dev/null+++ b/Tests/TurboFieldfareDecodeService/DecodeConversationGateTests.swift@@ -0,0 +1,131 @@+import Foundation+import Testing+import TurboFieldfareDecodeProtocol+@testable import TurboFieldfareDecodeService++/// The service appends turns to a KV it cannot rewind past 280 tokens, so a+/// turn admitted against the wrong lineage is not a recoverable error: the+/// model's context permanently holds a message the user never sent in that+/// conversation. Every case here is one way that used to be possible before the+/// gate existed, when `generate` carried no conversation identity at all.+@Suite struct DecodeConversationGateTests {+ private func turn(_ epoch: UUID?, _ index: Int?) -> DecodeGenerationRequest {+ DecodeGenerationRequest(+ prompt: "hello", maxNewTokens: 16, maxContextTokens: 8_192,+ temperature: 0, conversationEpoch: epoch, turnIndex: index)+ }++ @Test func aOneShotRunsWhenNoConversationIsOpen() {+ let gate = DecodeConversationGate()+ #expect(gate.admit(turn(nil, nil)) == .success(.oneShot))+ }++ @Test func aOneShotIsRefusedWhileAConversationIsOpen() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: epoch)+ // A one-shot resets the KV before prefilling. Running it here would+ // wipe the lineage the app still believes it is talking to.+ #expect(gate.admit(turn(nil, nil))+ == .failure(.oneShotDuringConversation(open: epoch)))+ }++ @Test func turnsAreAdmittedInOrderAndOnlyAfterTheyCommit() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: epoch)+ #expect(gate.admit(turn(epoch, 0)) == .success(.turn(epoch: epoch, index: 0)))+ // Not yet committed, so turn 1 is still out of order.+ #expect(gate.admit(turn(epoch, 1))+ == .failure(.outOfOrderTurn(requested: 1, committed: 0)))+ gate.commit(.turn(epoch: epoch, index: 0))+ #expect(gate.committedTurns == 1)+ #expect(gate.admit(turn(epoch, 1)) == .success(.turn(epoch: epoch, index: 1)))+ }++ @Test func areplayedTurnIndexIsRefused() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: epoch)+ gate.commit(.turn(epoch: epoch, index: 0))+ // A retransmitted turn 0 would append the same user message twice,+ // behind its own reply.+ #expect(gate.admit(turn(epoch, 0))+ == .failure(.outOfOrderTurn(requested: 0, committed: 1)))+ }++ @Test func aturnWithoutAnIndexIsRefused() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: epoch)+ #expect(gate.admit(turn(epoch, nil))+ == .failure(.outOfOrderTurn(requested: nil, committed: 0)))+ }++ @Test func aturnFromAReplacedConversationIsRefused() {+ let first = UUID()+ let second = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: first)+ gate.commit(.turn(epoch: first, index: 0))+ gate.reset(to: second)+ #expect(gate.committedTurns == 0, "a reset restarts the turn order")+ #expect(gate.admit(turn(first, 1))+ == .failure(.staleConversation(requested: first, open: second)))+ }++ @Test func arejectedTurnDoesNotAdvanceTheOrder() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: epoch)+ _ = gate.admit(turn(epoch, 7))+ _ = gate.admit(turn(UUID(), 0))+ #expect(gate.committedTurns == 0)+ #expect(gate.admit(turn(epoch, 0)) == .success(.turn(epoch: epoch, index: 0)))+ }++ @Test func committingAnAdmissionFromASupersededEpochIsIgnored() {+ let first = UUID()+ let second = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: first)+ let admission = DecodeConversationGate.Admission.turn(epoch: first, index: 0)+ // The turn was admitted, then the user started a new chat while it was+ // still decoding. Counting it against the new lineage would push every+ // later turn one position out of step.+ gate.reset(to: second)+ gate.commit(admission)+ #expect(gate.committedTurns == 0)+ }++ @Test func endingTheLineageRestoresTheOneShotPath() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: epoch)+ gate.commit(.turn(epoch: epoch, index: 0))+ // Both unload and load reach here: each releases or rebuilds the KV, so+ // the tokens the epoch named are gone.+ gate.endLineage()+ #expect(gate.openEpoch == nil)+ #expect(gate.committedTurns == 0)+ #expect(gate.admit(turn(epoch, 1))+ == .failure(.staleConversation(requested: epoch, open: nil)))+ #expect(gate.admit(turn(nil, nil)) == .success(.oneShot))+ }++ @Test func rejectionsNameBothSidesSoTheLogDiagnosesItself() {+ let requested = UUID()+ let open = UUID()+ let stale = DecodeConversationGate.Rejection+ .staleConversation(requested: requested, open: open)+ #expect(stale.message.contains(requested.uuidString))+ #expect(stale.message.contains(open.uuidString))+ let order = DecodeConversationGate.Rejection+ .outOfOrderTurn(requested: 4, committed: 2)+ #expect(order.message.contains("4"))+ #expect(order.message.contains("2"))+ let unset = DecodeConversationGate.Rejection+ .outOfOrderTurn(requested: nil, committed: 0)+ #expect(unset.message.contains("unset"))+ }+}diff --git a/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift b/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swiftindex 632a992f..6029dceb 100644--- a/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift+++ b/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift@@ -16,6 +16,7 @@ import TurboFieldfareDecodeProtocol#expect(event.kind == .cancelled)#expect(event.generationID == generationID)+ #expect(event.computedPrefillTokens == 7)}@Test func failureFollowedByThrownErrorWritesOneTerminal() throws {@@ -32,6 +33,28 @@ import TurboFieldfareDecodeProtocol#expect(event.error == "first")}+ @Test func abrokenLineageIsItsOwnTerminalKind() throws {+ let outbox = DecodeServiceOutbox(generationID: UUID())+ let event = try firstTerminal(+ from: outbox,+ published: .failed(.conversationLineageLost("prefill cursor mismatch"),+ partial: nil),+ finishError: AppInferenceError.cancelled)++ #expect(event.kind == .lineageLost)+ #expect(event.error?.contains("prefill cursor mismatch") == true)+ #expect(event.error?.contains("Start a new chat") == true)+ }++ @Test func anordinaryFailureStaysFailed() throws {+ let outbox = DecodeServiceOutbox(generationID: UUID())+ let event = try firstTerminal(+ from: outbox,+ published: .failed(.unknown("something else"), partial: nil),+ finishError: AppInferenceError.cancelled)+ #expect(event.kind == .failed)+ }+/// Image encoding produces no progress or tokens, so the outbox must emit/// memory-only events during that otherwise silent interval.@Test func aSilentGenerationStillReportsMemory() throws {@@ -138,6 +161,7 @@ import TurboFieldfareDecodeProtocolAppDiagnostics(generatedTokens: 0,stopReason: stopReason,+ computedPrefillTokens: 7,timeToFirstTokenSeconds: nil,decodeSeconds: 0,tokensPerSecond: 0,diff --git a/docs/RUNTIME_CONTROLS.md b/docs/RUNTIME_CONTROLS.mdindex 525402ea..0f910e12 100644--- a/docs/RUNTIME_CONTROLS.md+++ b/docs/RUNTIME_CONTROLS.md@@ -2,8 +2,8 @@The Mac app, CLI, and local server expose generation and runtime controls. Theapp keeps them in its fixed right settings pane. FP16 is the fixed KV format.-Generation settings apply to the next request; app load-time settings require a-reload.+Generation settings apply to the next turn or request; app load-time settings+require a reload.## Generation controls@@ -11,8 +11,8 @@ The Mac app and CLI expose these generation controls:| Control | Mac values | CLI flag | Default | Effect || --- | --- | --- | --- | --- |-| Maximum response | Automatic | `--max-new` | App: remaining context; CLI: 1,024 tokens | The app can use the context space left after formatting the prompt. The CLI uses its explicit or default `--max-new` limit. |-| Maximum context | 4K, 8K, 16K, 32K, 64K | `--max-context` | CLI and app: 8K; server: 16K | Sets prompt plus response capacity, and 8K is what leaves room for an image and its prompt. The app shows the FP16 KV-memory delta. The server defaults higher still because agent clients routinely send prompts near 8K on their own. |+| Maximum response | Automatic | `--max-new` | App: remaining context; CLI: 1,024 tokens | The app can use the context space left after the retained conversation and new turn. The CLI uses its explicit or default `--max-new` limit. |+| Maximum context | 4K, 8K, 16K, 32K, 64K | `--max-context` | CLI and app: 8K; server: 16K | Sets conversation or prompt plus response capacity, and 8K is what leaves room for an image and its prompt. The app shows the FP16 KV-memory delta. The server defaults higher still because agent clients routinely send prompts near 8K on their own. || Temperature | 0...2 in 0.05 steps | `--temperature` | 0.2 | `0` is greedy; positive values sample. || Top-K | Off or 1...256 | `--top-k` | 64 | Keeps at most K candidates. CLI `0` turns it off. || Top-P | Off or 0.01...1 | `--top-p` | 0.95 | Applies nucleus truncation before Top-K and is effective only while Top-K is enabled. |@@ -41,9 +41,11 @@ model, so an unsupported combination fails immediately with the usage text.In the app, changing context length, expert-cache slots, or RDADVISE requires areload. Some sampling changes also require a reload because greedy and sampledgeneration use different output-head paths. Prompt-prefill settings apply to-each request and do not require a reload. Each CLI invocation loads a new model-process, so its selected runtime settings apply immediately. The server fixes-its runtime settings at startup, so changing one means restarting the process.+each turn and do not require a reload. A reload ends the retained KV lineage;+the app preserves the visible transcript and marks where the model's new+context begins. Each CLI invocation loads a new model process, so its selected+runtime settings apply immediately. The server fixes its runtime settings at+startup, so changing one means restarting the process.### macOS interactivity mitigation@@ -95,8 +97,8 @@ name the changed setting.## Read the results- **Decode rate** measures generated tokens per second after prompt prefill.-- **Request TTFT** includes prompt prefill and the wait for the first generated- token.+- **Request TTFT** includes prompt or new-turn prefill and the wait for the first+ generated token.- **Peak memory** in Last run is the highest decode-service memory observedduring the request. The HUD shows the service's current memory instead of themuch smaller foreground UI process.diff --git a/docs/SYSTEM_DESIGN.md b/docs/SYSTEM_DESIGN.mdindex 0903b327..ff0f1eb7 100644--- a/docs/SYSTEM_DESIGN.md+++ b/docs/SYSTEM_DESIGN.md@@ -457,6 +457,15 @@ attention, a 16-slot LFU expert cache, chunked prefill, staged affine MPPprefill, and batched routed MoE prefill. File-read advice (`RDADVISE`) is off bydefault.+## App conversations++The Mac app keeps one conversation in memory and reuses its KV cache, so later+turns prefill only new text and images. An epoch and turn index keep the app and+decode service in sync. The app rejects turns that exceed the context window+instead of trimming history. **New Chat** clears the transcript, KV cache, and+images; reload and unload keep the transcript but start fresh model context.+Conversations are not saved.+## Read next- [Local OpenAI-compatible server](OPENAI_SERVER.md)