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 Mac conversation history and bump version to 0.8.0 (#174)
Andrey Mikhaylov4c6db1e698ea
diff --git a/AGENTS.md b/AGENTS.mdindex 8f186a97..e2cbbe17 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -57,8 +57,11 @@ 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`.-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,+The app saves conversation history locally and retains one live FP16 KV lineage.+Browsing the sidebar preserves that lineage; continuing another saved chat+replays its recorded tokens and replaces it. See+[Conversation history](README.md#conversation-history) for an overview.+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 retainedimages. Reloading or unloading keeps the transcript but marks it outside thediff --git a/Package.swift b/Package.swiftindex 829209b2..ff52f46c 100644--- a/Package.swift+++ b/Package.swift@@ -74,6 +74,7 @@ let package = Package(.target(name: "TurboFieldfareMacPresentation",dependencies: [+ "TurboFieldfare","TurboFieldfareAppCore",.product(name: "SwiftMath", package: "SwiftMath"),],@@ -146,7 +147,13 @@ let package = Package(),.testTarget(name: "TurboFieldfareAppCoreTests",- dependencies: ["TurboFieldfareAppCore", "TurboFieldfare", "TurboFieldfareRepackCore", "TurboFieldfareDecodeProtocol"],+ dependencies: [+ "TurboFieldfareAppCore", "TurboFieldfare", "TurboFieldfareRepackCore",+ "TurboFieldfareDecodeProtocol",+ // `SplitMix64`, for the seeded conversation-history walk. The+ // only seeded generator in the tree; a second copy would drift.+ "TurboFieldfareValidationSupport",+ ],path: "Tests/TurboFieldfareApp/Core"),.testTarget(diff --git a/README.md b/README.mdindex 9b8be450..9da9bfbf 100644--- a/README.md+++ b/README.md@@ -177,6 +177,13 @@ right pane to configure sampling, context length, expert-cache slots, andruntime options. See [Runtime controls](docs/RUNTIME_CONTROLS.md) for detailsand defaults.+#### Conversation history++The app saves chats locally so you can browse and continue them from the+sidebar. Only one conversation's model context (KV cache) stays in memory.+Browsing other chats keeps that cache intact; continuing another chat replaces+it. **New Chat** starts fresh.+### Command-line interfaceThe CLI uses an existing `.gturbo` installation. If you installed the modeldiff --git a/Sources/TurboFieldfare/Runtime/Generation/ConversationIdentity.swift b/Sources/TurboFieldfare/Runtime/Generation/ConversationIdentity.swiftnew file mode 100644index 00000000..eaee35ab--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Generation/ConversationIdentity.swift@@ -0,0 +1,77 @@+import Foundation++public enum ConversationIdentityError: Error, CustomStringConvertible {+ case snapshotHashUnavailable++ public var description: String {+ switch self {+ case .snapshotHashUnavailable:+ "the loaded model's manifest carries no source snapshot hash, so a "+ + "conversation recorded against it could not be told apart from "+ + "one recorded against a different checkpoint"+ }+ }+}++/// Everything that has to be the same for a stored conversation's token IDs to+/// mean what they meant when they were recorded.+///+/// Not a cache key: a conversation owns its lineage and never has to match+/// anything. It is a refusal test. Token IDs index a vocabulary, sit at+/// positions a template chose, and stand in for images a preprocessor produced;+/// change any of those and the same integers describe a different conversation.+/// The four fields are the four ways that can happen — a different checkpoint,+/// a different model, a different chat framing, or different pixels out of the+/// same file — and a mismatch in any of them leaves the transcript readable and+/// says so rather than continuing on a lineage the model never had.+public struct ConversationIdentity: Sendable, Equatable, Codable {+ public let modelID: String+ public let sourceSnapshotHash: String+ public let templateIdentity: String+ public let imageProcessingVersion: Int++ public init(modelID: String,+ sourceSnapshotHash: String,+ templateIdentity: String,+ imageProcessingVersion: Int) {+ self.modelID = modelID+ self.sourceSnapshotHash = sourceSnapshotHash+ self.templateIdentity = templateIdentity+ self.imageProcessingVersion = imageProcessingVersion+ }++ /// The identity of a loaded model. The chat framing is the tokenizer's+ /// declared template identity, which is a type-level constant because the+ /// renderer is hand-written Swift with no template file to hash.+ ///+ /// Throws rather than substituting a placeholder for a missing snapshot+ /// hash: an identity that cannot be established has to refuse replay, and a+ /// blank field would compare equal to the next blank field and admit it.+ public init(model: Model) throws {+ guard let snapshot = model.sourceSnapshotHash, !snapshot.isEmpty else {+ throw ConversationIdentityError.snapshotHashUnavailable+ }+ self.init(modelID: model.modelID,+ sourceSnapshotHash: snapshot,+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)+ }++ /// The identity of an installed model, from its manifest alone.+ ///+ /// The app process needs this and never loads the model: the decode service+ /// does. Reading the manifest costs a few kilobytes and stays well inside+ /// the rule that no path holds model-derived data in the heap.+ public static func forModelDirectory(_ directoryURL: URL) throws -> ConversationIdentity {+ let manifest = try ManifestReader.load(+ directoryURL: directoryURL, expecting: .gemma4_26B_A4B)+ guard let snapshot = manifest.sourceSnapshotHash, !snapshot.isEmpty else {+ throw ConversationIdentityError.snapshotHashUnavailable+ }+ return ConversationIdentity(+ modelID: manifest.modelID,+ sourceSnapshotHash: snapshot,+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Generation/MultimodalConversation.swift b/Sources/TurboFieldfare/Runtime/Generation/MultimodalConversation.swiftindex f98423f6..baf0d602 100644--- a/Sources/TurboFieldfare/Runtime/Generation/MultimodalConversation.swift+++ b/Sources/TurboFieldfare/Runtime/Generation/MultimodalConversation.swift@@ -7,8 +7,14 @@ public enum MultimodalConversationError: Error, CustomStringConvertible {case lineageBrokencase lineageRecoveryFailed(reason: String)case emptyTurn- case contextExhausted(prompt: Int, maxContext: Int)+ case contextExhausted(prompt: Int, reserve: Int, maxContext: Int)case imageUnavailable(reason: String?)+ case lineageNotEmpty(kvTokens: Int)+ case invalidReplayImage(reason: String)+ /// A recorded token ID is not one this model has. Restore is the one entry+ /// point that prefills IDs it did not tokenize itself, and the embedding+ /// lookup indexes its table by the raw value.+ case invalidReplayToken(index: Int, token: Int32, vocabSize: Int)public var description: String {switch self {@@ -21,15 +27,160 @@ public enum MultimodalConversationError: Error, CustomStringConvertible {"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 .contextExhausted(let prompt, let reserve, let maxContext):+ "conversation needs \(prompt) tokens plus \(reserve) kept free for a "+ + "reply, 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"+ case .lineageNotEmpty(let kvTokens):+ "a stored conversation can only be restored into an empty KV; this "+ + "one already holds \(kvTokens) tokens"+ case .invalidReplayImage(let reason):+ "a stored image cannot be replayed: \(reason)"+ case .invalidReplayToken(let index, let token, let vocabSize):+ "the stored record holds token \(token) at position \(index), "+ + "outside this model's \(vocabSize)-entry vocabulary"}}}+/// How much context a turn keeps free for the model to answer in.+///+/// The guard used to admit any turn whose prompt alone fit, leaving room for+/// exactly one generated token, while the refusal the user saw promised their+/// whole max response — so a chat near the ceiling was accepted and then+/// answered with a word. One constant now decides both that guard and whether a+/// stored conversation can be continued at the current context length, because+/// a row that says "continue" and a turn that then refuses are the same defect+/// seen from two places.+///+/// It is a floor, not the requested `maxNewTokens`: the reply length is a+/// setting the user can change at any time, and a stored conversation's+/// continuability must not move with it.+public enum ConversationGenerationReserve {+ public static let tokens = 256++ /// What the smallest continuation turn costs before its first word.+ ///+ /// `generate` prefills the lineage plus the message wrapped in the chat+ /// template's turn markers and thought-channel opener, so a lineage that+ /// fits with exactly `tokens` to spare fits nothing the user can type.+ /// Rows within that margin of the ceiling were offered as continuable,+ /// replayed in full, and then refused every message. The figure is an+ /// upper bound on `encodeTextContinuation` with a one-token message; the+ /// tokenizer test pins it against the real template.+ public static let turnEnvelope = 16++ /// Whether a prompt of `tokens` still leaves room to answer.+ ///+ /// The only place the ceiling is written down. `generate` asks it with+ /// the whole prompt; `fitsLineage` asks it for a stored conversation+ /// with the smallest turn added, so a row that offers to continue and a+ /// turn that then refuses cannot disagree — which they did while both+ /// asked this function with different inputs.+ public static func fits(tokens: Int, maxContext: Int) -> Bool {+ tokens + Self.tokens <= maxContext+ }++ /// Whether a stored lineage of `tokens` can take at least one turn.+ ///+ /// `tokens` counts everything the next turn's prompt starts with: the KV+ /// and any boundary token the last run left outside it.+ public static func fitsLineage(tokens: Int, maxContext: Int) -> Bool {+ fits(tokens: tokens + turnEnvelope, maxContext: maxContext)+ }++ /// The smallest context that lets a stored lineage of `tokens` take a+ /// turn: the figure `needsContext` reports.+ public static func contextRequired(forLineage tokens: Int) -> Int {+ tokens + turnEnvelope + Self.tokens+ }+}++/// One image of a stored conversation, as replay needs it: where its soft+/// tokens sit in the lineage, the model-input copy on disk, and the digest that+/// copy has to hash to.+public struct MultimodalReplayImage: Sendable {+ public let tokenRange: Range<Int>+ public let pixelsURL: URL+ public let expectedDigest: String++ public init(tokenRange: Range<Int>, pixelsURL: URL, expectedDigest: String) {+ self.tokenRange = tokenRange+ self.pixelsURL = pixelsURL+ self.expectedDigest = expectedDigest+ }+}++/// A conversation's KV as a sequence of token IDs, ready to be prefilled back.+///+/// `tokenIDs` is the effective sequence — every turn's prompt and reply+/// concatenated in order, exactly what `kvTokenIDs` held. The embedding+/// sequence is not carried: it differs from the effective one only inside image+/// spans, so it is derived from `images` rather than stored twice and given the+/// chance to disagree.+public struct MultimodalConversationLineage: Sendable {+ public let tokenIDs: [Int32]+ public let images: [MultimodalReplayImage]+ public let uncommittedBoundary: [Int32]+ public let boundaryNeedsReplay: Bool++ public init(tokenIDs: [Int32],+ images: [MultimodalReplayImage] = [],+ uncommittedBoundary: [Int32] = [],+ boundaryNeedsReplay: Bool = false) {+ self.tokenIDs = tokenIDs+ self.images = images+ self.uncommittedBoundary = uncommittedBoundary+ self.boundaryNeedsReplay = boundaryNeedsReplay+ }++ /// Everything the next turn will put in front of its message: the KV and+ /// the boundary token a stopped run left outside it, when that token is+ /// replayed ahead of the turn.+ public var promptPrefixCount: Int {+ tokenIDs.count + (boundaryNeedsReplay ? uncommittedBoundary.count : 0)+ }++ /// Refuses a record that names a token this model does not have.+ ///+ /// Every other prefill feeds the tokenizer's own output; this record came+ /// off disk, or over the decode service's socket, and the embedding kernel+ /// reads its table at `token * rowBytes` with nothing in between. A+ /// negative or too-large ID was an out-of-bounds GPU read: either a KV+ /// built from whatever memory lay past the table, reported as a restored+ /// conversation, or a GPU fault the app could only attribute to a lost+ /// connection. The boundary tokens are checked too; they enter the same+ /// prefill.+ public func validateTokenIDs(vocabSize: Int) throws {+ for (index, token) in tokenIDs.enumerated()+ where token < 0 || Int(token) >= vocabSize {+ throw MultimodalConversationError.invalidReplayToken(+ index: index, token: token, vocabSize: vocabSize)+ }+ for (offset, token) in uncommittedBoundary.enumerated()+ where token < 0 || Int(token) >= vocabSize {+ throw MultimodalConversationError.invalidReplayToken(+ index: tokenIDs.count + offset, token: token, vocabSize: vocabSize)+ }+ }+}++enum MultimodalTurnRecord {+ /// The tokens a turn's reply left in the KV.+ ///+ /// Taken as a suffix of the post-turn record rather than counted by the+ /// decode loop, so a stop-string trim is already applied: those tokens are+ /// gone from the cache, and a transcript that still listed them would+ /// replay a context the model no longer has. The clamp is not padding — a+ /// trim that lands on the prompt boundary leaves nothing generated at all.+ static func generatedTokenIDs(kvTokenIDs: [Int32], promptCount: Int) -> [Int32] {+ guard kvTokenIDs.count > promptCount else { return [] }+ return Array(kvTokenIDs.suffix(kvTokenIDs.count - promptCount))+ }+}+enum MultimodalConversationKVRecovery {static func restoreAfterFailure(positionBefore: Int,@@ -102,6 +253,23 @@ public struct MultimodalTurnResult: Sendable {/// can show what resuming actually saved rather than asserting that it did.public let prefillSeconds: Doublepublic let decodeSeconds: Double+ /// What this turn's user half put into the KV: the continuation-encoded+ /// prompt, behind any boundary token the previous run left outside the+ /// cache and this one replayed. Not the whole prompt — the earlier turns+ /// were already recorded when they ran.+ public let promptTokenIDs: [Int32]+ /// What this turn's assistant half left in the KV, after a stop-string+ /// match has had its hidden tokens trimmed. Not the tokens the model+ /// emitted: a run that stops on max tokens or is cancelled holds its final+ /// token outside the cache, and that token is in `uncommittedBoundaryTokenIDs`.+ ///+ /// Concatenating every turn's `promptTokenIDs` and `generatedTokenIDs` in+ /// order reproduces the KV exactly. Re-tokenising the transcript's text+ /// cannot: the pinned template strips historical thought spans and trims+ /// content, so the record has to be the IDs.+ public let generatedTokenIDs: [Int32]+ public let uncommittedBoundaryTokenIDs: [Int32]+ public let boundaryNeedsReplay: Bool}/// A stateful multi-turn conversation that owns its own KV lineage.@@ -343,9 +511,12 @@ public actor MultimodalConversation {// token it already emitted.let boundary = boundaryNeedsReplay ? uncommittedBoundary : []let promptIDs = kvTokenIDs + boundary + turn.effectiveTokenIDs- guard promptIDs.count + 1 <= maxContext else {+ guard ConversationGenerationReserve.fits(+ tokens: promptIDs.count, maxContext: maxContext) else {throw MultimodalConversationError.contextExhausted(- prompt: promptIDs.count, maxContext: maxContext)+ prompt: promptIDs.count,+ reserve: ConversationGenerationReserve.tokens,+ maxContext: maxContext)}// Same coercion as the other entry points: a turn carrying image spans@@ -458,6 +629,8 @@ public actor MultimodalConversation {}uncommittedBoundary = result.uncommittedBoundaryTokenIDsboundaryNeedsReplay = result.reason == .maxTokens || result.reason == .cancelled+ let generatedTokenIDs = MultimodalTurnRecord.generatedTokenIDs(+ kvTokenIDs: kvTokenIDs, promptCount: promptIDs.count)return MultimodalTurnResult(text: text,promptTokens: promptIDs.count,@@ -472,7 +645,150 @@ public actor MultimodalConversation {completionTokens: result.newTokens,reason: result.reason,prefillSeconds: result.prefillSeconds,- decodeSeconds: result.decodeSeconds)+ decodeSeconds: result.decodeSeconds,+ promptTokenIDs: boundary + turn.effectiveTokenIDs,+ generatedTokenIDs: generatedTokenIDs,+ uncommittedBoundaryTokenIDs: uncommittedBoundary,+ boundaryNeedsReplay: boundaryNeedsReplay)+ }++ /// Rebuilds the KV of a stored conversation by prefilling its own token IDs,+ /// with no decode.+ ///+ /// This is the whole of resume. There is no KV on disk: the record is the+ /// sequence the model saw, and replaying it is what makes the continued+ /// conversation the one the transcript shows. Restoring is refused unless+ /// the KV is empty, so a partially filled cache can never be mistaken for a+ /// restored one — the failure mode every checkpoint-restore bug in this+ /// space shares.+ ///+ /// The replayed KV is equivalent, not byte-identical: the original+ /// assistant tokens entered through the decode path and the chunk+ /// boundaries here are the planner's, not the turn's. The token sequence is+ /// exact, which is what the next turn resumes on.+ public func restore(+ lineage: MultimodalConversationLineage,+ prefillConfig: PrefillRuntimeConfig = .defaultChunked,+ checkCancellation: @Sendable () throws -> Void = {},+ onProgress: (@Sendable (RawDecodeProgress) -> Void)? = nil+ ) async throws {+ guard !closed else { throw MultimodalConversationError.closed }+ guard !lineageBroken else { throw MultimodalConversationError.lineageBroken }+ guard !generating, !resetting else { throw MultimodalConversationError.busy }+ guard kvTokenIDs.isEmpty else {+ throw MultimodalConversationError.lineageNotEmpty(kvTokens: kvTokenIDs.count)+ }+ guard !lineage.tokenIDs.isEmpty else {+ throw MultimodalConversationError.emptyTurn+ }+ try lineage.validateTokenIDs(vocabSize: model.config.vocabSize)+ // The headroom `generate` will require of the smallest turn, not just+ // of the lineage. Restoring a conversation that could not then take a+ // turn would put minutes of prefill behind a composer that refuses+ // everything typed into it.+ guard ConversationGenerationReserve.fitsLineage(+ tokens: lineage.promptPrefixCount, maxContext: maxContext) else {+ throw MultimodalConversationError.contextExhausted(+ prompt: lineage.promptPrefixCount+ + ConversationGenerationReserve.turnEnvelope,+ reserve: ConversationGenerationReserve.tokens,+ maxContext: maxContext)+ }+ if !lineage.images.isEmpty, visionRuntime == nil {+ throw MultimodalConversationError.imageUnavailable(+ reason: visionRuntimeError.map(String.init(describing:)))+ }+ generating = true+ defer { finishGeneration() }++ // Images are re-encoded before anything touches the KV, so a stored+ // image whose pixels no longer hash to what was recorded fails the+ // restore with the cache still empty and this conversation still usable.+ var embeddingTokenIDs = lineage.tokenIDs+ var spans: [MultimodalImageSpan] = []+ var previousUpperBound = 0+ for image in lineage.images {+ try checkCancellation()+ let range = image.tokenRange+ guard !range.isEmpty, range.lowerBound >= previousUpperBound,+ range.upperBound <= lineage.tokenIDs.count else {+ throw MultimodalConversationError.invalidReplayImage(+ reason: "token range \(range) does not fit the "+ + "\(lineage.tokenIDs.count)-token lineage in order")+ }+ previousUpperBound = range.upperBound+ let features: VisionFeatures+ do {+ features = try visionRuntime!.encodeStoredImage(+ at: image.pixelsURL,+ expectedDigest: image.expectedDigest,+ languageModel: model,+ residencyPolicy: visionResidency,+ checkCancellation: checkCancellation)+ } catch is CancellationError {+ // A cancelled restore is not a broken record; the caller asked+ // for it to stop and the KV is still empty.+ throw CancellationError()+ } catch {+ // Mapped here rather than let through as a vision error: to the+ // caller this is one thing — the stored conversation cannot be+ // replayed — and it has to be classifiable as that, with the+ // underlying reason kept so the row can say which image and why.+ throw MultimodalConversationError.invalidReplayImage(+ reason: "\(error)")+ }+ guard features.tokenCount == range.count else {+ throw MultimodalConversationError.invalidReplayImage(+ reason: "the stored image encodes to \(features.tokenCount) "+ + "soft tokens, not the \(range.count) its turn recorded")+ }+ spans.append(MultimodalImageSpan(tokenRange: range, features: features))+ // The encoder writes zero where an image's soft tokens go, and the+ // effective sequence carries the placeholder ID. Deriving the+ // embedding sequence here keeps the two from ever disagreeing on+ // disk.+ for index in range { embeddingTokenIDs[index] = 0 }+ }++ let prefillInput = spans.isEmpty ? nil : try MultimodalPrefillInput(+ effectiveTokenIDs: lineage.tokenIDs,+ embeddingTokenIDs: embeddingTokenIDs,+ imageSpans: spans)+ var effectivePrefill = prefillConfig+ if prefillInput != nil, let coerced = effectivePrefill.coercedForImagePrompt() {+ effectivePrefill = coerced+ }++ do {+ _ = try await runRawPrefill(+ producer: runner,+ promptIds: lineage.tokenIDs,+ multimodalInput: prefillInput,+ prefillConfig: effectivePrefill,+ start: .reset,+ // No decode follows, so the seed is discarded. Asking for logits+ // would only make the final row pay for a head nobody reads.+ outputMode: .greedyIfAvailable,+ seedUse: .discarded,+ historyReserve: lineage.tokenIDs.count,+ scratch: scratch,+ onProgress: { onProgress?($0) })+ } catch {+ // A mid-conversation failure has to condemn the lineage because+ // nothing knows how far the KV advanced past a recorded prefix.+ // Here it does: restore starts from an empty cache, so resetting+ // puts the conversation back exactly where it began and it stays+ // usable for a fresh chat.+ runner.reset()+ kvTokenIDs.removeAll(keepingCapacity: true)+ uncommittedBoundary = []+ boundaryNeedsReplay = false+ throw error+ }++ kvTokenIDs = lineage.tokenIDs+ uncommittedBoundary = lineage.uncommittedBoundary+ boundaryNeedsReplay = lineage.boundaryNeedsReplay}private struct EncodedTurn {diff --git a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swiftindex bbd6cdb7..905124d6 100644--- a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift+++ b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift@@ -15,6 +15,173 @@ public enum RawDecodeProgress: Sendable {public enum RawCompletionStart: Sendable, Equatable {case resetcase resume(cachedPromptTokens: Int)++ /// How many of `promptCount` tokens the producer's KV already holds.+ func cachedPromptTokens(promptCount: Int, producer: any LogitProducer) throws -> Int {+ switch self {+ case .reset:+ return 0+ case .resume(let count):+ guard count > 0, count < promptCount else {+ throw GeneratorError.invalidContinuation(+ "cached prompt token count must be greater than zero and less than the effective prompt")+ }+ guard producer is any ContinuableLogitProducer else {+ throw GeneratorError.invalidContinuation(+ "producer does not support continuation")+ }+ return count+ }+ }+}++/// What the prefill's seed is for. A decode consumes it, so a producer that+/// returned the wrong kind has to be refused before the loop reads it. A+/// restore has no decode and discards it.+enum RawPrefillSeedUse {+ case decode(isPureGreedy: Bool)+ case discarded+}++struct RawPrefillOutcome {+ let computedPrefillTokens: Int+ let position: Int+ let seed: PrefillSeed?+ let prefillSeconds: Double+ let history: [Int32]+}++/// The prefill half of `runRawCompletion`, on its own so that restoring a+/// stored conversation goes through it too.+///+/// A second implementation would be a second set of chunk boundaries, and chunk+/// boundaries are the one thing a replayed KV has to share with the KV it is+/// reproducing: image spans are indivisible work items, chunks under 32 tokens+/// take a different GEMV than larger ones, and `.prefill` progress is what the+/// app's gauge animates. Restore is a prefill with the decode left off, not a+/// different way to fill a cache.+func runRawPrefill(+ producer: any LogitProducer,+ promptIds: [Int32],+ multimodalInput: MultimodalPrefillInput?,+ prefillConfig requestedPrefillConfig: PrefillRuntimeConfig,+ start: RawCompletionStart,+ outputMode: PrefillOutputMode,+ seedUse: RawPrefillSeedUse,+ historyReserve: Int,+ scratch: RawCompletionScratch,+ onProgress: (RawDecodeProgress) -> Void+) async throws -> RawPrefillOutcome {+ let cachedPromptTokens = try start.cachedPromptTokens(+ promptCount: promptIds.count, producer: producer)+ let computedPrefillTokens = promptIds.count - cachedPromptTokens+ if let multimodalInput {+ // Under resume the multimodal input is the tail that still has to be+ // prefilled, so it must match the prompt suffix rather than the whole+ // prompt. `prefillMultimodal` already prefills from `startPosition`.+ guard multimodalInput.effectiveTokenIDs+ == Array(promptIds.dropFirst(cachedPromptTokens)) else {+ throw GeneratorError.invalidContinuation(+ "multimodal effective token IDs do not match the prompt")+ }+ }+ // Image spans are served only by the complete chunked prefill path, and a+ // prefill config that cannot serve them is a performance setting, not a+ // decision to drop the images. Coercing here rather than at each call site+ // is what makes it total: the default argument is `.current`, which the+ // environment can turn `.off`, so a caller that passes no config at all+ // reaches this too. The call sites still coerce first, to report it.+ let prefillConfig = multimodalInput == nil+ ? requestedPrefillConfig+ : (requestedPrefillConfig.coercedForImagePrompt() ?? requestedPrefillConfig)++ func checkSeed(_ seed: PrefillSeed, path: String, requiresWrittenLogits: Bool) throws {+ guard case .decode(let isPureGreedy) = seedUse else { return }+ if requiresWrittenLogits, outputMode == .logits, seed != .logitsWritten {+ throw PrefillError.unsupportedPrefillSeed(+ "RawCompletion \(path) prefill requested logits but producer returned \(seed)")+ }+ if case .greedyToken = seed, !isPureGreedy {+ throw PrefillError.unsupportedPrefillSeed(+ "RawCompletion \(path) prefill returned a greedy token for a sampling config")+ }+ }++ var history = Array(promptIds.prefix(cachedPromptTokens))+ history.reserveCapacity(historyReserve)++ switch start {+ case .reset:+ producer.reset()+ case .resume:+ let continuable = producer as! any ContinuableLogitProducer+ try continuable.prepareForContinuation(expectedPosition: cachedPromptTokens)+ }+ let prefillStart = Date()+ var position = cachedPromptTokens+ var prefillSeed: PrefillSeed?+ let prefillTokens = promptIds[cachedPromptTokens...]+ switch (multimodalInput, prefillConfig.mode) {+ case (.some(let input), .chunked) where producer is any MultimodalPrefillRunner:+ let multimodal = producer as! any MultimodalPrefillRunner+ let result = try await multimodal.prefillMultimodal(+ input: input,+ startPosition: position,+ outputMode: outputMode,+ config: prefillConfig,+ into: scratch.logits+ ) { done in+ // The suffix-local count plus what the KV already holds, as the+ // chunked text path reports it. Without the offset a+ // 300-token image turn on a 5,000-token KV showed 1 of 5,300.+ onProgress(.prefill(done: cachedPromptTokens + done,+ total: promptIds.count))+ }+ try checkSeed(result.seed, path: "multimodal", requiresWrittenLogits: true)+ position = result.newPosition+ prefillSeed = result.seed+ // Only the suffix: under resume the cached prefix is already in history,+ // and appending the whole prompt would duplicate it and desynchronise+ // history from the KV position.+ history.append(contentsOf: prefillTokens)+ case (.some, _):+ // The coercion above leaves an image prompt in chunked mode, so the+ // only way here is a producer that cannot run image spans at all —+ // which no config change can fix.+ throw PrefillError.chunkedUnsupported(+ "multimodal prefill requires a MultimodalPrefillRunner-backed runtime")+ case (.none, .chunked) where producer is any ChunkedPrefillRunner:+ let chunked = producer as! any ChunkedPrefillRunner+ let result = try await chunked.prefillChunked(tokens: prefillTokens,+ startPosition: position,+ outputMode: outputMode,+ config: prefillConfig,+ into: scratch.logits) { done in+ onProgress(.prefill(done: cachedPromptTokens + done, total: promptIds.count))+ }+ try checkSeed(result.seed, path: "chunked", requiresWrittenLogits: true)+ position = result.newPosition+ prefillSeed = result.seed+ history.append(contentsOf: prefillTokens)+ case (.none, .chunked):+ throw PrefillError.chunkedUnsupported(+ PrefillError.chunkedRequiresChunkedRunnerReason)+ case (.none, _):+ for t in prefillTokens {+ try Task.checkCancellation()+ try await producer.produce(token: t, position: position, into: scratch.logits)+ position += 1+ history.append(t)+ onProgress(.prefill(done: position, total: promptIds.count))+ }+ }++ return RawPrefillOutcome(+ computedPrefillTokens: computedPrefillTokens,+ position: position,+ seed: prefillSeed,+ prefillSeconds: Date().timeIntervalSince(prefillStart),+ history: history)}public struct RawDecodeResult: Sendable {@@ -125,43 +292,14 @@ public func runRawCompletion(producer: any LogitProducer,"the fused-head producer cannot serve this sampling configuration; use a logits head")}- let cachedPromptTokens: Int- switch start {- case .reset:- cachedPromptTokens = 0- case .resume(let count):- guard count > 0, count < promptIds.count else {- throw GeneratorError.invalidContinuation(- "cached prompt token count must be greater than zero and less than the effective prompt")- }- guard producer is any ContinuableLogitProducer else {- throw GeneratorError.invalidContinuation(- "producer does not support continuation")- }- cachedPromptTokens = count- }- if let multimodalInput {- // Under resume the multimodal input is the tail that still has to be- // prefilled, so it must match the prompt suffix rather than the whole- // prompt. `prefillMultimodal` already prefills from `startPosition`.- guard multimodalInput.effectiveTokenIDs- == Array(promptIds.dropFirst(cachedPromptTokens)) else {- throw GeneratorError.invalidContinuation(- "multimodal effective token IDs do not match the prompt")- }- }- // Image spans are served only by the chunked prefill path, and a prefill- // config that cannot serve them is a performance setting, not a decision to- // drop the images.- let prefillConfig = multimodalInput == nil- ? prefillConfig- : (prefillConfig.coercedForImagePrompt() ?? prefillConfig)- let computedPrefillTokens = promptIds.count - cachedPromptTokens+ // Derived here as well as inside `runRawPrefill` so an invalid resume count+ // is still refused before the context-overflow check, which is the order+ // callers have always seen.+ let cachedPromptTokens = try start.cachedPromptTokens(+ promptCount: promptIds.count, producer: producer)var detok = GFDetokenizer(tokenizer: tokenizer,barrierTokenIDs: tokenizer.structuralMarkerIDs)- var history = Array(promptIds.prefix(cachedPromptTokens))- history.reserveCapacity(promptIds.count + config.maxNewTokens)if let context = producer as? any ContextWindowReporting,promptIds.count + config.maxNewTokens > context.maxContext {@@ -169,87 +307,25 @@ public func runRawCompletion(producer: any LogitProducer,maxNew: config.maxNewTokens,maxContext: context.maxContext)}- switch start {- case .reset:- producer.reset()- case .resume:- let continuable = producer as! any ContinuableLogitProducer- try continuable.prepareForContinuation(expectedPosition: cachedPromptTokens)- }- let prefillStart = Date()- var position = cachedPromptTokens- var prefillSeed: PrefillSeed?- let prefillTokens = promptIds[cachedPromptTokens...]- switch (multimodalInput, prefillConfig.mode) {- case (.some(let input), .chunked) where producer is any MultimodalPrefillRunner:- let multimodal = producer as! any MultimodalPrefillRunner- let mode: PrefillOutputMode = fusedGreedy ? .greedyIfAvailable : .logits- let result = try await multimodal.prefillMultimodal(- input: input,- startPosition: position,- outputMode: mode,- config: prefillConfig,- into: scratch.logits- ) { done in- // The suffix-local count plus what the KV already holds. Without the- // offset a 300-token image turn on a 5,000-token KV showed 1 of 5,300.- onProgress(.prefill(done: cachedPromptTokens + done,- total: promptIds.count))- }- if mode == .logits, result.seed != .logitsWritten {- throw PrefillError.unsupportedPrefillSeed(- "RawCompletion multimodal prefill requested logits but producer returned \(result.seed)")- }- if case .greedyToken = result.seed, !config.isPureGreedy {- throw PrefillError.unsupportedPrefillSeed(- "RawCompletion multimodal prefill returned a greedy token for a sampling config")- }- position = result.newPosition- prefillSeed = result.seed- // Only the suffix: under resume the cached prefix is already in history,- // and appending the whole prompt would duplicate it.- history.append(contentsOf: prefillTokens)- case (.some, _):- // The coercion above leaves an image prompt in chunked mode, so the only- // way here is a producer that cannot run image spans at all.- throw PrefillError.chunkedUnsupported(- "multimodal prefill requires a MultimodalPrefillRunner-backed runtime")- case (.none, .chunked) where producer is any ChunkedPrefillRunner:- let chunked = producer as! any ChunkedPrefillRunner- let mode: PrefillOutputMode = fusedGreedy ? .greedyIfAvailable : .logits- let result = try await chunked.prefillChunked(tokens: prefillTokens,- startPosition: position,- outputMode: mode,- config: prefillConfig,- into: scratch.logits) { done in- onProgress(.prefill(done: cachedPromptTokens + done, total: promptIds.count))- }- if mode == .logits, result.seed != .logitsWritten {- throw PrefillError.unsupportedPrefillSeed(- "RawCompletion chunked prefill requested logits but producer returned \(result.seed)")- }- if case .greedyToken = result.seed, !config.isPureGreedy {- throw PrefillError.unsupportedPrefillSeed(- "RawCompletion chunked prefill returned a greedy token for a sampling config")- }- position = result.newPosition- prefillSeed = result.seed- history.append(contentsOf: prefillTokens)- case (.none, .chunked):- throw PrefillError.chunkedUnsupported(- PrefillError.chunkedRequiresChunkedRunnerReason)- case (.none, .off):- for t in prefillTokens {- try Task.checkCancellation()- try await producer.produce(token: t, position: position, into: scratch.logits)- position += 1- history.append(t)- onProgress(.prefill(done: position, total: promptIds.count))- }- }++ let prefill = try await runRawPrefill(+ producer: producer,+ promptIds: promptIds,+ multimodalInput: multimodalInput,+ prefillConfig: prefillConfig,+ start: start,+ outputMode: fusedGreedy ? .greedyIfAvailable : .logits,+ seedUse: .decode(isPureGreedy: config.isPureGreedy),+ historyReserve: promptIds.count + config.maxNewTokens,+ scratch: scratch,+ onProgress: onProgress)+ let computedPrefillTokens = prefill.computedPrefillTokens+ var history = prefill.history+ var position = prefill.position+ let prefillSeed = prefill.seedlet decodeStart = Date()- let prefillSeconds = decodeStart.timeIntervalSince(prefillStart)+ let prefillSeconds = prefill.prefillSecondsvar stopMatcher = StreamingStopMatcher(stops: config.stopStrings)var generated = 0var reason: StopReason = .maxTokensdiff --git a/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift b/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swiftindex 41a4ac60..515f2a65 100644--- a/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift+++ b/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift@@ -260,6 +260,9 @@ public struct PrefillRuntimeConfig: Sendable, Equatable {public let mode: Modepublic let chunkTokens: Int+ public func coercedForReplay() -> PrefillRuntimeConfig? {+ mode == .off ? .defaultChunked : nil+ }private init(mode: Mode, chunkTokens: Int) {self.mode = modediff --git a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImageGeometry.swift b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImageGeometry.swiftindex 11ea3eb2..74180989 100644--- a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImageGeometry.swift+++ b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImageGeometry.swift@@ -71,4 +71,43 @@ public struct Gemma4ImageGeometry: Sendable, Equatable {patchCount = patchessoftTokenCount = patches / (config.poolingKernel * config.poolingKernel)}++ /// Geometry for pixels that are already at the model's input size — the copy+ /// a stored conversation replays.+ ///+ /// Re-deriving this through the scaling rule above would be wrong: that rule+ /// maps a source *up* to the token budget as readily as down, so a 48x48+ /// model input would come back as 768x768 and the stored soft-token count+ /// would stop matching the span the tokenizer laid out.+ public init(+ processedWidth: Int,+ processedHeight: Int,+ config: VisionConfig = VisionConfig()+ ) throws {+ let sideMultiple = config.patchSize * config.poolingKernel+ guard processedWidth > 0, processedHeight > 0,+ processedWidth.isMultiple(of: sideMultiple),+ processedHeight.isMultiple(of: sideMultiple) else {+ throw VisionImageError.invalidMetadata(+ "stored model input must be a positive multiple of \(sideMultiple)")+ }+ let (processedPixels, overflow) = processedWidth.multipliedReportingOverflow(+ by: processedHeight)+ let targetPixels = config.maximumPatches * config.patchSize * config.patchSize+ guard !overflow, processedPixels <= targetPixels else {+ throw VisionImageError.invalidMetadata("target geometry exceeds patch budget")+ }+ let gridWidth = processedWidth / config.patchSize+ let gridHeight = processedHeight / config.patchSize+ let patches = gridWidth * gridHeight+ guard patches <= config.maximumPatches else {+ throw VisionImageError.invalidMetadata("target patch grid is invalid")+ }+ self.processedWidth = processedWidth+ self.processedHeight = processedHeight+ patchGridWidth = gridWidth+ patchGridHeight = gridHeight+ patchCount = patches+ softTokenCount = patches / (config.poolingKernel * config.poolingKernel)+ }}diff --git a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImagePreprocessor.swift b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImagePreprocessor.swiftindex 59d4192b..9ad79387 100644--- a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImagePreprocessor.swift+++ b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImagePreprocessor.swift@@ -1,8 +1,31 @@import CoreGraphics+import CryptoKitimport Foundationimport ImageIOimport Metal+/// The bytes a stored conversation replays: the model input's RGB channels,+/// tightly packed, with the drawing surface's row padding and its alpha channel+/// dropped. This — not the file the user attached — is what reproduces the+/// tower's input, because decode, EXIF transform and resampling all happen+/// before it and none of them has a documented pixel-stability contract across+/// macOS versions.+public struct VisionModelInputPixels: Sendable {+ public let rgb8: [UInt8]+ public let width: Int+ public let height: Int+ /// Lowercase hex SHA-256 of `rgb8`, the identity a replay checks.+ public let digest: String+}++public struct VisionPreprocessOutput {+ public let pixels: VisionPixelBuffer+ /// Present only when the caller asked for it. Packing and hashing ~1.9 MB+ /// is cheap beside the resize, but it is pure waste for the CLI and the+ /// server, which never store an image.+ public let modelInput: VisionModelInputPixels?+}+public final class Gemma4ImagePreprocessor {private static let unitBF16 = (0...255).map {Quantization.bf16Bits(Float($0) / 255)@@ -97,6 +120,20 @@ public final class Gemma4ImagePreprocessor {}public func preprocess(_ plan: VisionImagePlan) throws -> VisionPixelBuffer {+ try preprocess(plan, capturingModelInput: false).pixels+ }++ /// The same preprocessing, optionally returning the model-input copy a+ /// stored conversation keeps.+ ///+ /// The copy is taken from the very buffer `patchify` reads. Re-running the+ /// pipeline to produce it would not be a slower way to get the same bytes:+ /// it would be a second decode and a second resize, and therefore a second+ /// chance to produce different ones.+ public func preprocess(+ _ plan: VisionImagePlan,+ capturingModelInput: Bool+ ) throws -> VisionPreprocessOutput {let source = plan.opened.sourcelet metadata = plan.metadatalet geometry = plan.geometry@@ -185,6 +222,125 @@ public final class Gemma4ImagePreprocessor {destinationRowBytes: rowBytes)}+ let patchElements = try checkedMultiply(geometry.patchCount, config.patchDimension)+ let patchBytes = try checkedMultiply(patchElements, MemoryLayout<UInt16>.stride)+ let positionElements = try checkedMultiply(geometry.patchCount, 2)+ let positionBytes = try checkedMultiply(+ positionElements, MemoryLayout<Int32>.stride)+ guard let patches = device.makeBuffer(length: patchBytes, options: .storageModeShared),+ let positions = device.makeBuffer(+ length: positionBytes, options: .storageModeShared) else {+ throw VisionImageError.allocationFailed+ }+ let modelInput = capturingModelInput+ ? Self.modelInputPixels(+ rgba: rgba.assumingMemoryBound(to: UInt8.self),+ rowBytes: rowBytes,+ width: geometry.processedWidth,+ height: geometry.processedHeight)+ : nil+ patchify(+ rgba: rgba.assumingMemoryBound(to: UInt8.self),+ rowBytes: rowBytes,+ geometry: geometry,+ patches: patches,+ positions: positions)+ return VisionPreprocessOutput(+ pixels: VisionPixelBuffer(+ patchesBF16: patches,+ positionsInt32x2: positions,+ metadata: metadata,+ geometry: geometry,+ wallNanoseconds: nanoseconds(plan.started.duration(to: .now)),+ // Both full-resolution surfaces: ImageIO's decoded CGImage and+ // ours, which `draw` holds simultaneously.+ allocatedBytes: decodedSurfaceBytes + sourceBytes + rgbaBytes+ + resizeScratchBytes+ + patchBytes + positionBytes),+ modelInput: modelInput)+ }++ /// Plans an image that is already the model's input: the stored PNG a+ /// conversation replays.+ ///+ /// The scaling `plan(_:)` performs must not run here. The stored file's+ /// pixels *are* the processed pixels, so its geometry is read straight off+ /// its dimensions; putting them through the scaling rule again would resize+ /// a small model input up towards the token budget and change its span+ /// length.+ public func plan(storedModelInput fileURL: URL) throws -> VisionImagePlan {+ let started = ContinuousClock.now+ let opened = try VisionImageSource(fileURL: fileURL).open(+ maximumEncodedBytes: metadataReader.limits.maximumEncodedBytes)+ let metadata = try metadataReader.read(opened: opened)+ let geometry = try Gemma4ImageGeometry(+ processedWidth: metadata.orientedWidth,+ processedHeight: metadata.orientedHeight,+ config: config)+ return VisionImagePlan(+ metadata: metadata, geometry: geometry, opened: opened, started: started)+ }++ /// Patchifies a stored model-input image, refusing anything whose pixels are+ /// not the ones that were stored.+ ///+ /// Decode is unavoidable — a PNG has to be unpacked — but the resize is+ /// skipped, because the stored file is already at the tower's geometry. The+ /// digest check is not belt-and-braces: PNG decode of an sRGB 8-bit file is+ /// very likely an identity and nowhere documented as one, so replay verifies+ /// rather than assumes, and a mismatch fails the restore instead of quietly+ /// continuing a conversation on pixels the model never saw.+ public func preprocess(+ storedModelInput plan: VisionImagePlan,+ expectedDigest: String+ ) throws -> VisionPixelBuffer {+ let geometry = plan.geometry+ let width = geometry.processedWidth+ let height = geometry.processedHeight+ guard let decoded = CGImageSourceCreateImageAtIndex(+ plan.opened.source, 0, [+ kCGImageSourceShouldCacheImmediately: true,+ kCGImageSourceShouldAllowFloat: false,+ ] as CFDictionary) else {+ throw VisionImageError.decodeFailed+ }+ guard decoded.width == width, decoded.height == height else {+ throw VisionImageError.invalidMetadata(+ "stored model input decoded at \(decoded.width)x\(decoded.height), "+ + "not the \(width)x\(height) its header declares")+ }++ let rowBytes = try checkedMultiply(width, 4)+ let rgbaBytes = try checkedMultiply(rowBytes, height)+ let rgba = UnsafeMutableRawPointer.allocate(byteCount: rgbaBytes, alignment: 64)+ defer { rgba.deallocate() }+ rgba.initializeMemory(as: UInt8.self, repeating: 255, count: rgbaBytes)+ guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),+ let drawing = CGContext(+ data: rgba,+ width: width,+ height: height,+ bitsPerComponent: 8,+ bytesPerRow: rowBytes,+ space: colorSpace,+ bitmapInfo: CGBitmapInfo.byteOrder32Big.rawValue+ | CGImageAlphaInfo.premultipliedLast.rawValue) else {+ throw VisionImageError.allocationFailed+ }+ drawing.setFillColor(CGColor(gray: 1, alpha: 1))+ drawing.fill(CGRect(x: 0, y: 0, width: width, height: height))+ drawing.draw(decoded, in: CGRect(x: 0, y: 0, width: width, height: height))+ withExtendedLifetime(drawing) {}++ let modelInput = Self.modelInputPixels(+ rgba: rgba.assumingMemoryBound(to: UInt8.self),+ rowBytes: rowBytes, width: width, height: height)+ guard modelInput.digest == expectedDigest.lowercased() else {+ throw VisionImageError.invalidMetadata(+ "stored model input hashes to \(modelInput.digest), not the "+ + "\(expectedDigest.lowercased()) recorded with the turn")+ }+let patchElements = try checkedMultiply(geometry.patchCount, config.patchDimension)let patchBytes = try checkedMultiply(patchElements, MemoryLayout<UInt16>.stride)let positionElements = try checkedMultiply(geometry.patchCount, 2)@@ -204,14 +360,36 @@ public final class Gemma4ImagePreprocessor {return VisionPixelBuffer(patchesBF16: patches,positionsInt32x2: positions,- metadata: metadata,+ metadata: plan.metadata,geometry: geometry,wallNanoseconds: nanoseconds(plan.started.duration(to: .now)),- // Both full-resolution surfaces: ImageIO's decoded CGImage and- // ours, which `draw` holds simultaneously.- allocatedBytes: decodedSurfaceBytes + sourceBytes + rgbaBytes- + resizeScratchBytes- + patchBytes + positionBytes)+ allocatedBytes: rgbaBytes + patchBytes + positionBytes)+ }++ static func modelInputPixels(+ rgba: UnsafePointer<UInt8>,+ rowBytes: Int,+ width: Int,+ height: Int+ ) -> VisionModelInputPixels {+ var rgb8 = [UInt8](repeating: 0, count: width * height * 3)+ rgb8.withUnsafeMutableBufferPointer { out in+ var output = 0+ for y in 0..<height {+ var input = y * rowBytes+ for _ in 0..<width {+ out[output] = rgba[input]+ out[output + 1] = rgba[input + 1]+ out[output + 2] = rgba[input + 2]+ output += 3+ input += 4+ }+ }+ }+ let digest = SHA256.hash(data: rgb8)+ .map { String(format: "%02x", $0) }.joined()+ return VisionModelInputPixels(+ rgb8: rgb8, width: width, height: height, digest: digest)}private func patchify(diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionConfig.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionConfig.swiftindex 2ea2526e..10841a81 100644--- a/Sources/TurboFieldfare/Runtime/Vision/VisionConfig.swift+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionConfig.swift@@ -21,3 +21,15 @@ public struct VisionConfig: Sendable, Equatable {public init() {}}++/// Identifies the pipeline that turns an attached file into the tower's input.+///+/// A stored conversation keeps the post-resize pixels, so replay does not+/// re-run decode, orientation, compositing or resampling — but it does re-run+/// patchification and normalization. Bump this whenever a change to any stage+/// would give the same stored file different soft tokens; a conversation+/// recorded under an older version then fails identity and stays readable+/// instead of continuing on tokens this build would not have produced.+public enum VisionImageProcessing {+ public static let version = 1+}diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionRuntime.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionRuntime.swiftindex a8082e67..9ddb12aa 100644--- a/Sources/TurboFieldfare/Runtime/Vision/VisionRuntime.swift+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionRuntime.swift@@ -350,6 +350,42 @@ public final class VisionRuntime {languageModel: Model? = nil,residencyPolicy: VisionResidencyPolicy = .defaultPolicy,checkCancellation: () throws -> Void = {}+ ) throws -> VisionFeatures {+ try encode(languageModel: languageModel,+ residencyPolicy: residencyPolicy,+ checkCancellation: checkCancellation) { preprocessor in+ try preprocessor.preprocess(plan)+ }+ }++ /// Encodes the model-input copy a stored conversation kept, refusing it+ /// unless its pixels still hash to what the turn recorded.+ ///+ /// It shares the expert-residency dance with `encodeImage` deliberately:+ /// replaying a conversation with images pays exactly the encode a live turn+ /// pays, and a residency policy that behaved differently on reopen would+ /// make the reopen a different measurement from the turn it reproduces.+ public func encodeStoredImage(+ at fileURL: URL,+ expectedDigest: String,+ languageModel: Model? = nil,+ residencyPolicy: VisionResidencyPolicy = .defaultPolicy,+ checkCancellation: () throws -> Void = {}+ ) throws -> VisionFeatures {+ try encode(languageModel: languageModel,+ residencyPolicy: residencyPolicy,+ checkCancellation: checkCancellation) { preprocessor in+ try preprocessor.preprocess(+ storedModelInput: preprocessor.plan(storedModelInput: fileURL),+ expectedDigest: expectedDigest)+ }+ }++ private func encode(+ languageModel: Model?,+ residencyPolicy: VisionResidencyPolicy,+ checkCancellation: () throws -> Void,+ pixels: (Gemma4ImagePreprocessor) throws -> VisionPixelBuffer) throws -> VisionFeatures {try checkCancellation()let preprocessor = Gemma4ImagePreprocessor(device: context.device, config: config,@@ -361,7 +397,7 @@ public final class VisionRuntime {let transition = languageModel?.prepareExpertResidencyForVision(residencyPolicy, gpuDrainNanoseconds: gpuDrainNanoseconds)try checkCancellation()- let input = try preprocessor.preprocess(plan)+ let input = try pixels(preprocessor)return try encodePreparedPatches(patchesBF16: input.patchesBF16,positionsInt32x2: input.positionsInt32x2,diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swiftindex 625da095..47ac9b51 100644--- a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift@@ -16,9 +16,17 @@ struct MacAppSettings: Codable, Equatable, Sendable {var prefillEnabled: Bool = truevar newlineShortcut: AppNewlineShortcut = .returnvar showPromptExamples: Bool = true+ /// Whether the list of chats is showing. Remembered because hiding it is a+ /// choice about how the window looks, and a window that forgot it every+ /// launch would be making that choice again for the user each time.+ var sidebarVisible: Bool = true+ /// Whether the Inspector is showing. Remembered for the same reason the+ /// sidebar is: it is a choice about the window, not about one session.+ var inspectorVisible: Bool = truevar visionResidencyPolicy: VisionResidencyPolicy = .onDemandvar rdadvisePolicy: AppRDAdvicePolicy = .offvar loadModelOnLaunch: Bool = false+ var selectedConversationID: UUID?private enum CodingKeys: String, CodingKey {case version@@ -32,9 +40,12 @@ struct MacAppSettings: Codable, Equatable, Sendable {case prefillEnabledcase newlineShortcutcase showPromptExamples+ case sidebarVisible+ case inspectorVisiblecase visionResidencyPolicycase rdadvisePolicycase loadModelOnLaunch+ case selectedConversationID}init(version: Int = currentVersion,@@ -48,9 +59,12 @@ struct MacAppSettings: Codable, Equatable, Sendable {prefillEnabled: Bool = true,newlineShortcut: AppNewlineShortcut = .return,showPromptExamples: Bool = true,+ sidebarVisible: Bool = true,+ inspectorVisible: Bool = true,visionResidencyPolicy: VisionResidencyPolicy = .onDemand,rdadvisePolicy: AppRDAdvicePolicy = .off,- loadModelOnLaunch: Bool = false) {+ loadModelOnLaunch: Bool = false,+ selectedConversationID: UUID? = nil) {self.version = versionself.contextTokens = contextTokensself.expertCacheSlots = expertCacheSlots@@ -62,9 +76,12 @@ struct MacAppSettings: Codable, Equatable, Sendable {self.prefillEnabled = prefillEnabledself.newlineShortcut = newlineShortcutself.showPromptExamples = showPromptExamples+ self.sidebarVisible = sidebarVisible+ self.inspectorVisible = inspectorVisibleself.visionResidencyPolicy = visionResidencyPolicyself.rdadvisePolicy = rdadvisePolicyself.loadModelOnLaunch = loadModelOnLaunch+ self.selectedConversationID = selectedConversationID}init(from decoder: Decoder) throws {@@ -84,6 +101,15 @@ struct MacAppSettings: Codable, Equatable, Sendable {showPromptExamples = try container.decodeIfPresent(Bool.self,forKey: .showPromptExamples) ?? true+ // Additive, like every field around it: absent means the default, so+ // no version bump and no rewrite of a file an older build can still+ // read.+ sidebarVisible = try container.decodeIfPresent(+ Bool.self,+ forKey: .sidebarVisible) ?? true+ inspectorVisible = try container.decodeIfPresent(+ Bool.self,+ forKey: .inspectorVisible) ?? truevisionResidencyPolicy = try container.decodeIfPresent(VisionResidencyPolicy.self,forKey: .visionResidencyPolicy) ?? .onDemand@@ -93,6 +119,9 @@ struct MacAppSettings: Codable, Equatable, Sendable {loadModelOnLaunch = try container.decodeIfPresent(Bool.self,forKey: .loadModelOnLaunch) ?? false+ selectedConversationID = try container.decodeIfPresent(+ UUID.self,+ forKey: .selectedConversationID)}func isValid() -> Bool {diff --git a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swiftindex cae4f27b..258b7e29 100644--- a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift+++ b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift@@ -57,6 +57,20 @@ public struct AppDiagnostics: Equatable, Sendable {public var computedPrefillTokens: Int?/// Tokens the conversation's KV holds after this turn.public var conversationTokens: Int?+ /// What this turn added to the KV, in the model's own IDs: the+ /// continuation-encoded prompt, then the reply the cache kept. Nil on the+ /// single-prompt path and on any turn that never reached the KV.+ ///+ /// Carried as diagnostics because that is the channel the turn's terminal+ /// event already travels on, and because these are exactly a diagnostic of+ /// what the turn did — the difference being that this one is also the+ /// record the conversation is stored as.+ public var promptTokenIDs: [Int32]?+ public var generatedTokenIDs: [Int32]?+ /// A token the model emitted that the KV never took, left for the next turn+ /// to replay. Stored with the conversation so a reopened one replays it too.+ public var boundaryTokenIDs: [Int32]?+ public var boundaryNeedsReplay: Bool?public var prefillSeconds: Double?public var timeToFirstTokenSeconds: Double?public var decodeSeconds: Double@@ -90,6 +104,10 @@ public struct AppDiagnostics: Equatable, Sendable {cachedPromptTokens: Int? = nil,computedPrefillTokens: Int? = nil,conversationTokens: Int? = nil,+ promptTokenIDs: [Int32]? = nil,+ generatedTokenIDs: [Int32]? = nil,+ boundaryTokenIDs: [Int32]? = nil,+ boundaryNeedsReplay: Bool? = nil,prefillSeconds: Double? = nil,timeToFirstTokenSeconds: Double?,decodeSeconds: Double,@@ -105,6 +123,10 @@ public struct AppDiagnostics: Equatable, Sendable {self.cachedPromptTokens = cachedPromptTokensself.computedPrefillTokens = computedPrefillTokensself.conversationTokens = conversationTokens+ self.promptTokenIDs = promptTokenIDs+ self.generatedTokenIDs = generatedTokenIDs+ self.boundaryTokenIDs = boundaryTokenIDs+ self.boundaryNeedsReplay = boundaryNeedsReplayself.prefillSeconds = prefillSecondsself.timeToFirstTokenSeconds = timeToFirstTokenSecondsself.decodeSeconds = decodeSecondsdiff --git a/Sources/TurboFieldfareApp/Core/History/CompletedTurnPersistence.swift b/Sources/TurboFieldfareApp/Core/History/CompletedTurnPersistence.swiftnew file mode 100644index 00000000..2462ee3d--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/CompletedTurnPersistence.swift@@ -0,0 +1,19 @@+import Foundation++struct PersistenceLineageKey: Hashable, Sendable {+ let conversationID: UUID+ let epoch: UUID+ let bindingGeneration: UInt64+}++/// The immutable inputs needed to persist one exchange in KV commit order.+struct CompletedTurnPersistence: Sendable {+ let key: PersistenceLineageKey+ let store: ConversationStore+ let userText: String+ let assistantText: String+ let diagnostics: AppDiagnostics?+ let sampling: ConversationSampling+ let boundary: ConversationBoundary+ let imageWrite: Task<TurnImageWriteOutcome, Never>?+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationContinuability.swift b/Sources/TurboFieldfareApp/Core/History/ConversationContinuability.swiftnew file mode 100644index 00000000..a0a2d2b9--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationContinuability.swift@@ -0,0 +1,89 @@+import Foundation+import TurboFieldfare++/// Whether a stored conversation can be picked up again, and if not, why.+///+/// Computed from `conversation.json` alone — no transcript, no images, no model+/// — because the sidebar asks it for every row on every context change. Three+/// states, kept apart on purpose: "does not fit right now" is recoverable by+/// raising the context, "cannot be replayed" is not recoverable at all, and+/// collapsing them into one greyed-out row would tell the user neither.+public enum ConversationContinuability: Equatable, Sendable {+ case continuable+ /// The conversation is intact but does not fit the context in force.+ /// `required` is the smallest context that would hold it plus room to reply.+ case needsContext(required: Int)+ /// The stored token IDs no longer mean what they meant. Only a re-read into+ /// a new lineage can use this conversation, and that is a different chat.+ case cannotReplay(reason: Reason)++ public enum Reason: Equatable, Sendable {+ case newerFormat+ case differentModel+ case differentCheckpoint+ case differentTemplate+ case differentImageProcessing+ case tokenCountUnknown+ /// A picture of this conversation has no stored copy, while the turn+ /// that cites it still holds its placeholder tokens. Replaying it would+ /// hand the model a span of image tokens with nothing behind them.+ case imageRecordMissing+ }++ /// The rule, evaluated against the context currently loaded.+ ///+ /// `session.contextTokens` is deliberately not consulted: it records what+ /// the chat was made under, and a 3,000-token chat recorded at 8K continues+ /// perfectly well at 4K. What decides is the tokens it holds against the+ /// context in force.+ public static func evaluate(+ meta: ConversationMeta,+ currentContext: Int,+ identity: ConversationIdentity+ ) -> ConversationContinuability {+ if meta.version > ConversationMeta.currentVersion {+ return .cannotReplay(reason: .newerFormat)+ }+ if meta.identity.modelID != identity.modelID {+ return .cannotReplay(reason: .differentModel)+ }+ if meta.identity.sourceSnapshotHash != identity.sourceSnapshotHash {+ return .cannotReplay(reason: .differentCheckpoint)+ }+ if meta.identity.templateIdentity != identity.templateIdentity {+ return .cannotReplay(reason: .differentTemplate)+ }+ if meta.identity.imageProcessingVersion != identity.imageProcessingVersion,+ meta.imageCount > 0 {+ // A processing bump only matters to a conversation that has images+ // in it. Refusing a text chat for it would be a refusal with no+ // cause the user could act on.+ return .cannotReplay(reason: .differentImageProcessing)+ }+ // Checked before the count, which the projection also nils out for+ // this: "no replay record" would be true and would send the user+ // looking for the wrong thing.+ if meta.imageWriteFailed == true {+ return .cannotReplay(reason: .imageRecordMissing)+ }+ // Fail closed rather than trust a lower bound: a conversation whose+ // count was never reported would be restored, admitted, and only then+ // discovered not to fit.+ guard let kvTokens = meta.kvTokens else {+ return .cannotReplay(reason: .tokenCountUnknown)+ }+ // What the next turn's prompt starts with, and whether the smallest+ // turn then fits: the KV plus a boundary token the last run left+ // outside it. Asking whether the KV alone fit offered rows that every+ // message was then refused on.+ let prefix = kvTokens+ + (meta.boundary.needsReplay ? meta.boundary.tokens.count : 0)+ guard ConversationGenerationReserve.fitsLineage(+ tokens: prefix, maxContext: currentContext) else {+ return .needsContext(+ required: ConversationGenerationReserve.contextRequired(+ forLineage: prefix))+ }+ return .continuable+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationDocument.swift b/Sources/TurboFieldfareApp/Core/History/ConversationDocument.swiftnew file mode 100644index 00000000..5b1eba26--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationDocument.swift@@ -0,0 +1,216 @@+import Foundation+import TurboFieldfare++/// Why a stored conversation's records cannot be put back into a KV.+///+/// Typed rather than a string so a caller pins the case, and worded exactly as+/// the window has always worded it: these two sentences reach the user through+/// `AppInferenceError.conversationRestoreFailed`, and a conversation that was+/// refused yesterday must be refused in the same words today.+public enum ConversationRecordError: Error, Equatable, Sendable,+ CustomStringConvertible {+ /// A turn with no recorded IDs. Replaying the turns around it would hand+ /// the model a conversation with a hole in the middle.+ case turnWithoutTokens+ /// A stored image's placeholder run is not where the turn that cites it+ /// says. The tower's features would land on text.+ case imageSpanNotInItsTurn+ /// The turn reported that a picture's stored copy could not be written,+ /// while its recorded IDs still hold that picture's placeholders.+ case imageRecordMissing++ public var description: String {+ switch self {+ case .turnWithoutTokens:+ return "a stored turn has no recorded tokens"+ case .imageSpanNotInItsTurn:+ return "a stored image's soft tokens are not in the turn that cites it"+ case .imageRecordMissing:+ return "a stored image was never written, and its turn still cites it"+ }+ }+}++/// A stored conversation as the app uses it, built by one walk over the records.+///+/// Display and replay read the same value, so they cannot disagree about which+/// turn holds which image. They used to be three separate walks — one for the+/// chat turns, one for the pairs the transcript draws, one for the lineage —+/// and two of them disagreeing is what produced a reopened turn drawn with no+/// pictures at all, and a conversation with pictures in two turns that could+/// never be continued again.+public struct ConversationDocument: Sendable {+ public let id: UUID+ public let meta: ConversationMeta+ /// Every recorded turn, with its images resolved against the conversation's+ /// own folder: paths are stored store-relative so the folder can be moved.+ public let turns: [AppChatTurn]+ /// The same turns as the exchanges the transcript draws.+ public let pairs: [(user: AppChatTurn, assistant: AppChatTurn)]+ /// The records as the inference side needs them, or why they cannot be.+ ///+ /// A failure here is a permanent property of what is on disk, which is why+ /// it travels with the document rather than being raised from a call the+ /// display path also has to make.+ public let lineage: Result<AppConversationLineage, ConversationRecordError>++ public static func load(_ opened: ConversationOpenResult,+ directory: URL) -> ConversationDocument {+ var turns: [AppChatTurn] = []+ var pairs: [(user: AppChatTurn, assistant: AppChatTurn)] = []+ var pendingUser: AppChatTurn?+ var tokenIDs: [Int32] = []+ var images: [AppConversationReplayImage] = []+ var committedTurns = 0+ var failure: ConversationRecordError?++ for record in opened.records {+ guard case .turn(let turn) = record else { continue }++ let chatTurn = AppChatTurn(+ id: turn.id,+ role: turn.role == .user ? .user : .assistant,+ text: turn.text,+ images: turn.images.map {+ ChatImage.stored(storedAttachment($0, in: directory))+ },+ promptTokens: turn.promptTokens,+ cachedTokens: turn.cachedTokens,+ generatedTokens: turn.generatedTokens,+ tokenIDs: turn.tokens)+ turns.append(chatTurn)+ if chatTurn.role == .user {+ pendingUser = chatTurn+ } else if let user = pendingUser {+ pairs.append((user: user, assistant: chatTurn))+ pendingUser = nil+ }++ // The replay half of the same pass. It keeps walking after a+ // failure so the turns above are complete — the transcript is still+ // readable, and losing what the user already read helps nobody.+ guard failure == nil else { continue }+ guard turn.imageWriteFailed != true else {+ // The same refusal the projection makes, from the same fact:+ // the IDs below hold placeholder runs that no file backs.+ failure = .imageRecordMissing+ continue+ }+ guard let tokens = turn.tokens else {+ failure = .turnWithoutTokens+ continue+ }+ for (indexInTurn, image) in turn.images.enumerated() {+ // Counted within this turn, because that is what the search+ // walks. Passing the conversation-wide count made the second+ // image-bearing turn look for its own placeholders at an index+ // that only existed if every earlier image had been in the same+ // turn, so any chat with pictures in two different turns could+ // never be continued again.+ guard let span = imageSpan(+ in: tokens, softTokens: image.softTokens,+ offset: tokenIDs.count, alreadyPlaced: indexInTurn) else {+ failure = .imageSpanNotInItsTurn+ break+ }+ images.append(AppConversationReplayImage(+ tokenLowerBound: span,+ tokenCount: image.softTokens,+ fileURL: directory.appendingPathComponent(image.pixelsFile),+ expectedDigest: image.modelInputDigest))+ }+ tokenIDs += tokens+ if turn.role == .user { committedTurns += 1 }+ }++ let lineage: Result<AppConversationLineage, ConversationRecordError>+ if let failure {+ lineage = .failure(failure)+ } else {+ lineage = .success(AppConversationLineage(+ tokenIDs: tokenIDs, images: images,+ boundaryTokenIDs: opened.meta.boundary.tokens,+ boundaryNeedsReplay: opened.meta.boundary.needsReplay,+ committedTurns: committedTurns))+ }+ return ConversationDocument(+ id: opened.meta.id, meta: opened.meta, turns: turns, pairs: pairs,+ lineage: lineage)+ }++ /// Finds the nth run of image placeholders inside one turn's tokens, where+ /// n counts only the images of that same turn.+ ///+ /// Located rather than stored: a recorded offset and a recorded token+ /// sequence can disagree, and then the tower's features land on text.+ private static func imageSpan(in tokens: [Int32], softTokens: Int,+ offset: Int, alreadyPlaced: Int) -> Int? {+ let placeholder = MultimodalPromptRenderer.imageTokenID+ var index = 0+ var seen = 0+ while index < tokens.count {+ guard tokens[index] == placeholder else {+ index += 1+ continue+ }+ var end = index+ while end < tokens.count, tokens[end] == placeholder { end += 1 }+ if seen == alreadyPlaced {+ guard end - index == softTokens else { return nil }+ return offset + index+ }+ seen += 1+ index = end+ }+ return nil+ }++ /// The thumbnail, not the model input.+ ///+ /// The two copies exist for different readers: the PNG is the exact bytes+ /// the tower patchified and must not be resampled, while the thumbnail was+ /// written at the 720 points the transcript asks for and is lossy on+ /// purpose. `sha256` carries the source digest because that is the key the+ /// thumbnail cache uses, so a picture already on screen in the composer is+ /// not decoded a second time for the transcript.+ private static func storedAttachment(_ image: ConversationImageRecord,+ in directory: URL) -> StoredImage {+ let thumbnail = directory.appendingPathComponent(image.thumbnailFile)+ // The model input when the thumbnail is not there. It is the same+ // picture — 768 square, what the tower was shown — so a conversation+ // whose thumbnail was lost still shows what it was asked about rather+ // than a turn that looks like it never had an image. Reading it is a+ // read: the bytes replay needs are untouched.+ let fileURL = FileManager.default.fileExists(atPath: thumbnail.path)+ ? thumbnail+ : directory.appendingPathComponent(image.pixelsFile)+ // Display only, never a gate: this figure reaches the composer's+ // capacity arithmetic for staged pictures, and a stored one is already+ // in the conversation. A file whose size cannot be read is drawn as+ // zero bytes rather than refused, which is a decision rather than an+ // oversight.+ let bytes = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]))?.fileSize+ // The conversation store owns these, and the type says so: no release+ // path that finishes a turn can be handed one.+ return StoredImage(+ id: image.id,+ fileURL: fileURL,+ displayName: image.displayName,+ encodedBytes: bytes ?? 0,+ sha256: image.sourceDigest)+ }+}++extension ConversationDocument: Equatable {+ /// Written out rather than synthesized: `pairs` is an array of tuples, which+ /// has no `Equatable` conformance to derive from.+ public static func == (lhs: ConversationDocument,+ rhs: ConversationDocument) -> Bool {+ lhs.id == rhs.id && lhs.meta == rhs.meta && lhs.turns == rhs.turns+ && lhs.lineage == rhs.lineage+ && lhs.pairs.count == rhs.pairs.count+ && zip(lhs.pairs, rhs.pairs).allSatisfy {+ $0.user == $1.user && $0.assistant == $1.assistant+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationHistoryState.swift b/Sources/TurboFieldfareApp/Core/History/ConversationHistoryState.swiftnew file mode 100644index 00000000..80a07ec0--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationHistoryState.swift@@ -0,0 +1,57 @@+import Foundation+import Observation++/// What the sidebar shows: the stored conversations, which one is open, and+/// whether this instance may change them.+///+/// Separate from `AppConversation`, which is the live chat and whose invariant+/// is that its turns are exactly the model's context. This is a list of things+/// on disk, most of which the model has never seen.+@MainActor+@Observable+public final class ConversationHistoryState {+ public private(set) var entries: [ConversationMeta] = []+ /// The stored conversation the transcript is showing, or nil for a new chat+ /// that has not been written yet.+ public var selection: UUID?+ /// Another instance of the app holds the writer lock. The list still works;+ /// nothing in it can be changed.+ public private(set) var isReadOnlyStore = false++ public init() {}++ public func replaceEntries(_ entries: [ConversationMeta]) {+ self.entries = entries+ }++ public func replaceEntryAndResort(_ entry: ConversationMeta) {+ entries.removeAll { $0.id == entry.id }+ entries.append(entry)+ entries.sort {+ if $0.updatedAt == $1.updatedAt { return $0.id.uuidString < $1.id.uuidString }+ return $0.updatedAt > $1.updatedAt+ }+ }++ /// How many stored conversations the last listing could not read. The+ /// sidebar says so: they are absent from the list, and absent with no+ /// explanation is indistinguishable from deleted.+ public private(set) var unreadableCount = 0+ public private(set) var discardedLegacyTrashCount = 0++ public func setUnreadableCount(_ count: Int) {+ unreadableCount = count+ }++ public func setDiscardedLegacyTrashCount(_ count: Int) {+ discardedLegacyTrashCount = count+ }++ public func setReadOnlyStore(_ isReadOnly: Bool) {+ isReadOnlyStore = isReadOnly+ }++ public func entry(_ id: UUID) -> ConversationMeta? {+ entries.first { $0.id == id }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationImageWriter.swift b/Sources/TurboFieldfareApp/Core/History/ConversationImageWriter.swiftnew file mode 100644index 00000000..c7950d1a--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationImageWriter.swift@@ -0,0 +1,176 @@+import CoreGraphics+import Darwin+import Foundation+import ImageIO+import Metal+import TurboFieldfare+import TurboFieldfareRepackCore+import UniformTypeIdentifiers++public enum ConversationImageWriterError: Error, CustomStringConvertible {+ case noMetalDevice+ case modelInputUnavailable(name: String)+ case encodeFailed(path: String)++ public var description: String {+ switch self {+ case .noMetalDevice:+ return "no Metal device, so an image cannot be prepared for storage"+ case .modelInputUnavailable(let name):+ return "preprocessing \(name) produced no model-input copy"+ case .encodeFailed(let path):+ return "could not write \(path)"+ }+ }+}++/// Writes the two copies of an image a conversation keeps.+///+/// The model-input copy is a lossless PNG of the post-resize RGB8 at the+/// tower's geometry. Not the file the user attached: decode, EXIF transform and+/// resampling all sit between that file and the model, none of them has a+/// documented pixel-stability contract across macOS versions, and one changed+/// pixel changes a 768-value patch vector, its activation, and after pooling at+/// least one soft-token embedding — which is a different KV and a different+/// continuation. It is already downscaled, because the tower never sees more+/// than 645,120 pixels; the "store it smaller" instinct is satisfied by the+/// model input itself.+///+/// The thumbnail is lossy on purpose: it is only ever looked at.+public struct ConversationImageWriter: Sendable {+ /// The size the transcript already asks for, so the composer's 96 px tile+ /// can be derived from it rather than from the model-input copy.+ public static let thumbnailMaxPixelSize = 720+ public static let thumbnailQuality = 0.8++ private let device: MTLDevice++ public init(device: MTLDevice) {+ self.device = device+ }++ public init() throws {+ guard let device = MetalContext.makeSystemDefaultDevice() else {+ throw ConversationImageWriterError.noMetalDevice+ }+ self.device = device+ }++ /// Preprocesses `attachment` once and writes both copies into `imagesDirectory`.+ ///+ /// One preprocess, not two: the stored bytes are the ones this call+ /// patchified, so there is no second decode to disagree with the first.+ public func write(+ attachment: StagedImage,+ into imagesDirectory: URL+ ) throws -> ConversationImageRecord {+ let preprocessor = Gemma4ImagePreprocessor(device: device)+ let plan = try preprocessor.plan(fileURL: attachment.fileURL)+ let output = try preprocessor.preprocess(plan, capturingModelInput: true)+ guard let modelInput = output.modelInput else {+ throw ConversationImageWriterError.modelInputUnavailable(+ name: attachment.displayName)+ }++ try FileManager.default.createDirectory(+ at: imagesDirectory, withIntermediateDirectories: true)+ // A later OS can preprocess the same source differently. Its new+ // pixels must not replace a previous turn's digest-bound replay input.+ let stem = String(attachment.sha256.prefix(16))+ let pixelsName = "\(stem)-\(modelInput.digest).png"+ let thumbnailName = "\(stem).thumb.jpg"++ try Self.writeAtomically(to: imagesDirectory.appendingPathComponent(pixelsName)) {+ try writeModelInputPNG(modelInput, to: $0)+ }+ try Self.writeAtomically(to: imagesDirectory.appendingPathComponent(thumbnailName)) {+ try writeThumbnail(from: attachment.fileURL, to: $0)+ }++ return ConversationImageRecord(+ id: attachment.id,+ displayName: attachment.displayName,+ pixelsFile: "images/\(pixelsName)",+ thumbnailFile: "images/\(thumbnailName)",+ sourceDigest: attachment.sha256,+ modelInputDigest: modelInput.digest,+ width: modelInput.width,+ height: modelInput.height,+ softTokens: output.pixels.geometry.softTokenCount)+ }++ static func writeAtomically(to url: URL, encode: (URL) throws -> Void) throws {+ let directory = url.deletingLastPathComponent()+ let temporary = directory.appendingPathComponent("\(UUID()).tmp")+ // Encode to disk, not a second image-sized heap buffer. A non-hidden+ // temporary left by a crash is collected by the store's orphan sweep.+ defer {+ if Darwin.unlink(temporary.path) != 0 {+ let code = errno+ if code != ENOENT {+ FileHandle.standardError.write(Data(+ "Could not remove image temporary \(temporary.lastPathComponent): errno \(code)\n".utf8))+ }+ }+ }+ try encode(temporary)+ let descriptor = try Posix.openReadNoFollow(temporary.path)+ defer { Darwin.close(descriptor) }+ try Posix.fsync(descriptor, path: temporary.path)+ try Posix.rename(from: temporary.path, to: url.path)+ try Posix.fsyncDirectory(directory.path)+ }++ /// 24-bit sRGB, no alpha, no resampling: the bytes as they are, so decoding+ /// the file hands them straight back.+ private func writeModelInputPNG(+ _ pixels: VisionModelInputPixels, to url: URL+ ) throws {+ guard let provider = CGDataProvider(data: Data(pixels.rgb8) as CFData),+ let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),+ let image = CGImage(+ width: pixels.width, height: pixels.height,+ bitsPerComponent: 8, bitsPerPixel: 24,+ bytesPerRow: pixels.width * 3,+ space: colorSpace,+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue),+ provider: provider, decode: nil, shouldInterpolate: false,+ intent: .defaultIntent) else {+ throw ConversationImageWriterError.encodeFailed(path: url.path)+ }+ guard let destination = CGImageDestinationCreateWithURL(+ url as CFURL, UTType.png.identifier as CFString, 1, nil) else {+ throw ConversationImageWriterError.encodeFailed(path: url.path)+ }+ CGImageDestinationAddImage(destination, image, nil)+ guard CGImageDestinationFinalize(destination) else {+ throw ConversationImageWriterError.encodeFailed(path: url.path)+ }+ }++ /// From the original rather than the model input, so the display copy keeps+ /// the aspect ratio the user recognises rather than the tower's 48-aligned+ /// one. `kCGImageSourceThumbnailMaxPixelSize` is always passed: without it+ /// `CGImageSourceCreateThumbnailAtIndex` has returned nil since iOS 17.4.+ private func writeThumbnail(from source: URL, to url: URL) throws {+ guard let imageSource = CGImageSourceCreateWithURL(source as CFURL, nil),+ let thumbnail = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, [+ kCGImageSourceCreateThumbnailFromImageAlways: true,+ kCGImageSourceCreateThumbnailWithTransform: true,+ kCGImageSourceThumbnailMaxPixelSize: Self.thumbnailMaxPixelSize,+ kCGImageSourceShouldCacheImmediately: true,+ ] as CFDictionary) else {+ throw ConversationImageWriterError.encodeFailed(path: url.path)+ }+ guard let destination = CGImageDestinationCreateWithURL(+ url as CFURL, UTType.jpeg.identifier as CFString, 1, nil) else {+ throw ConversationImageWriterError.encodeFailed(path: url.path)+ }+ CGImageDestinationAddImage(destination, thumbnail, [+ kCGImageDestinationLossyCompressionQuality: Self.thumbnailQuality,+ ] as CFDictionary)+ guard CGImageDestinationFinalize(destination) else {+ throw ConversationImageWriterError.encodeFailed(path: url.path)+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationMetaProjection.swift b/Sources/TurboFieldfareApp/Core/History/ConversationMetaProjection.swiftnew file mode 100644index 00000000..c374875a--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationMetaProjection.swift@@ -0,0 +1,157 @@+import Foundation+import TurboFieldfare++/// `conversation.json` as a function of `transcript.jsonl`.+///+/// The records are the conversation; the meta is a cache of this function over+/// them. Six fields used to be assigned by hand after every turn — the turn+/// count from the live conversation, the token count from the runtime's report,+/// the image count by `+=` — and a copy maintained by hand is a copy that+/// drifts: a row once read 1,065 tokens over a file holding 22, and the+/// continuability rule believed it.+public enum ConversationMetaProjection {+ /// Pure. Same records in, same meta out.+ ///+ /// `legacy` is the cached meta, consulted only for creation facts that+ /// neither the header nor an `origin` record carries — a store written+ /// before those existed. It is never consulted for anything the records can+ /// answer, except that a newer format stamp in either file must survive+ /// projection so the app refuses replay as well as the store refusing writes.+ public static func project(directoryID: UUID,+ records: [TranscriptRecord],+ legacy: ConversationMeta?) throws -> ConversationMeta {+ guard case .header(let header)? = records.first else {+ throw ConversationStoreError.missingHeader(id: directoryID)+ }+ // The directory name is the identity; the header is a claim about it.+ // A transcript that migrated into the wrong directory would otherwise+ // be projected as a different conversation.+ guard header.id == directoryID else {+ throw ConversationStoreError.headerMismatch(+ directory: directoryID.uuidString, header: header.id)+ }++ var origin: ConversationOriginRecord?+ var turns: [ConversationTurnRecord] = []+ var lastTitle: ConversationTitleRecord?+ var lastUserTitle: ConversationTitleRecord?+ for record in records {+ switch record {+ case .turn(let turn):+ turns.append(turn)+ case .title(let title):+ lastTitle = title+ if title.source == .user { lastUserTitle = title }+ case .origin(let value):+ origin = value+ // A checkpoint of a reply still being generated is superseded by+ // the `turn` that follows it, and an unknown record is a later+ // build's. Neither says anything about what the conversation holds.+ case .header, .partial, .unknown:+ continue+ }+ }++ guard let identity = header.identity ?? origin?.identity ?? legacy?.identity,+ let session = header.session ?? origin?.session ?? legacy?.session else {+ // Fail closed. Without the identity there is no continuability rule+ // to apply, and guessing one would offer the user a conversation+ // that fails on its first turn. The directory is listed as+ // unreadable, exactly as an undecodable meta is.+ throw ConversationStoreError.missingOrigin(id: directoryID)+ }++ let firstUserText = turns.first { $0.role == .user }?.text+ let title: String+ let titleSource: ConversationTitleSource+ // A name the user typed is the conversation's name and nothing+ // supersedes it. A `firstMessage` record is the stand-in `create`+ // writes so the row reads something for the length of the first reply,+ // and it stops being the answer the moment the conversation has a first+ // message of its own. Left to win outright, a chat whose very first+ // turn was stopped kept the name of a message it does not contain, and+ // every turn that followed kept it too.+ if let lastUserTitle {+ title = lastUserTitle.title+ titleSource = .user+ } else if let firstUserText {+ title = ConversationTitle.fromFirstMessage(firstUserText)+ titleSource = .firstMessage+ } else if let lastTitle {+ title = lastTitle.title+ titleSource = lastTitle.source+ } else {+ title = ConversationTitle.untitled+ titleSource = .firstMessage+ }++ // A turn whose pictures were not stored cannot be replayed either: its+ // IDs hold their placeholder runs and no file backs them, so putting it+ // back would give the model image tokens with nothing behind them.+ let imageWriteFailed = turns.contains { $0.imageWriteFailed == true }++ // Every recorded turn's tokens, which is the KV. Nil the moment one+ // turn cannot account for its own — the same refusal `lineage` makes,+ // so a row can never claim a count the replay would not accept.+ let kvTokens: Int? = turns.isEmpty || imageWriteFailed+ || turns.contains(where: { $0.tokens == nil })+ ? nil+ : turns.reduce(0) { $0 + ($1.tokens?.count ?? 0) }++ // The last turn that could carry each, not the last that does: a store+ // upgraded mid-conversation has the newest turn carrying both, and+ // reaching further back for an older turn's answer would restore a+ // boundary the conversation has already moved past.+ let sampling = turns.last(where: { $0.role == .user })?.sampling+ ?? header.sampling ?? origin?.sampling ?? legacy?.sampling+ ?? ConversationSampling.windowDefaults+ let boundary = turns.last(where: { $0.role == .assistant })?.boundary+ ?? origin?.boundary ?? legacy?.boundary ?? ConversationBoundary()++ return ConversationMeta(+ version: max(header.version, legacy?.version ?? header.version),+ id: header.id,+ title: title,+ titleSource: titleSource,+ createdAt: header.createdAt,+ updatedAt: turns.last?.at ?? header.createdAt,+ turnCount: turns.count,+ kvTokens: kvTokens,+ imageCount: turns.reduce(0) { $0 + $1.images.count },+ identity: identity,+ session: session,+ sampling: sampling,+ boundary: boundary,+ imageWriteFailed: imageWriteFailed ? true : nil,+ // Written by every build and read by nothing. Kept in the file so a+ // reader with a non-optional field keeps decoding; removing it is a+ // separate decision.+ pinned: false)+ }++ /// The creation facts a legacy transcript has to be given before it can be+ /// projected, or nil when it already carries them.+ ///+ /// Nil is the ordinary answer: a header written by this build carries the+ /// facts, and a store already hoisted has an `origin` record. A transcript+ /// with neither, and no readable meta to lift them out of, is also nil —+ /// there is nothing to hoist, and `project` refuses it rather than+ /// inventing an identity.+ public static func hoist(records: [TranscriptRecord],+ legacy: ConversationMeta?) -> ConversationOriginRecord? {+ guard let legacy else { return nil }+ for record in records {+ switch record {+ case .header(let header) where header.identity != nil: return nil+ case .origin: return nil+ default: continue+ }+ }+ return ConversationOriginRecord(+ identity: legacy.identity,+ session: legacy.session,+ sampling: legacy.sampling,+ boundary: legacy.boundary,+ at: legacy.updatedAt)+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationRecord.swift b/Sources/TurboFieldfareApp/Core/History/ConversationRecord.swiftnew file mode 100644index 00000000..9fa37c00--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationRecord.swift@@ -0,0 +1,386 @@+import Foundation+import TurboFieldfare++/// Settings that were in force when a conversation was recorded.+///+/// Informational, not the continuability test: a 3,000-token chat recorded at+/// 8K continues perfectly well at 4K. What it is for is telling the user why+/// reopening will reload the model.+public struct ConversationSessionSettings: Codable, Equatable, Sendable {+ public var contextTokens: Int+ public var expertCacheSlots: Int+ public var visionResidencyPolicy: String++ public init(contextTokens: Int, expertCacheSlots: Int,+ visionResidencyPolicy: String) {+ self.contextTokens = contextTokens+ self.expertCacheSlots = expertCacheSlots+ self.visionResidencyPolicy = visionResidencyPolicy+ }+}++/// Sampling as it was when the chat was last used. Restored into the composer+/// on reopen; it never affects the KV, so it is not part of replay identity.+public struct ConversationSampling: Codable, Equatable, Sendable {+ public var temperature: Double+ public var topKEnabled: Bool+ public var topK: Int+ public var topPEnabled: Bool+ public var topP: Double+ public var maxNewTokens: Int++ public init(temperature: Double, topKEnabled: Bool, topK: Int,+ topPEnabled: Bool, topP: Double, maxNewTokens: Int) {+ self.temperature = temperature+ self.topKEnabled = topKEnabled+ self.topK = topK+ self.topPEnabled = topPEnabled+ self.topP = topP+ self.maxNewTokens = maxNewTokens+ }+}++extension ConversationSampling {+ /// What a conversation reads as when nothing recorded its sampling: a+ /// legacy store whose `conversation.json` is gone and whose transcript+ /// predates the `origin` record. Sampling never enters replay identity, so+ /// the window's own defaults are the right answer here — refusing to open+ /// a readable chat over a slider position would not be.+ public static let windowDefaults = ConversationSampling(+ temperature: MacAppSettings().temperature,+ topKEnabled: MacAppSettings().topKEnabled,+ topK: MacAppSettings().topK,+ topPEnabled: MacAppSettings().topPEnabled,+ topP: MacAppSettings().topP,+ // The window's default reply length, which the settings file does not+ // carry.+ maxNewTokens: 4_096)+}++/// The token a run left outside the KV, kept so a reopened conversation replays+/// it exactly as a live one would.+public struct ConversationBoundary: Codable, Equatable, Sendable {+ public var tokens: [Int32]+ public var needsReplay: Bool++ public init(tokens: [Int32] = [], needsReplay: Bool = false) {+ self.tokens = tokens+ self.needsReplay = needsReplay+ }+}++public enum ConversationTitleSource: String, Codable, Sendable {+ case firstMessage+ case user+}++/// The small file the sidebar reads: a cache of the transcript, not a second+/// copy of it.+///+/// Every field here is `ConversationMetaProjection.project` over the records in+/// `transcript.jsonl`, and nothing writes it by hand. It exists because listing+/// a hundred conversations must never mean parsing a hundred transcripts — and+/// because it is derived rather than maintained, it cannot drift from what the+/// conversation actually holds. A copy that disagrees is replaced on the next+/// open; a hand edit to this file does not survive one.+public struct ConversationMeta: Codable, Equatable, Sendable {+ /// A newer major is opened read-only and its bytes are left exactly as its+ /// owner wrote them.+ public static let currentVersion = 1+ public static let fileName = "conversation.json"++ public var version: Int+ public var id: UUID+ public var title: String+ public var titleSource: ConversationTitleSource+ public var createdAt: Date+ public var updatedAt: Date+ public var turnCount: Int+ /// Tokens the KV held when this conversation was last written. Optional and+ /// meant to stay that way: a conversation whose count was never reported+ /// cannot be replayed, and guessing one would put the user in front of a+ /// chat that fails on its first turn.+ public var kvTokens: Int?+ public var imageCount: Int+ public var identity: ConversationIdentity+ public var session: ConversationSessionSettings+ public var sampling: ConversationSampling+ public var boundary: ConversationBoundary+ /// A turn of this conversation reported a picture whose stored copy could+ /// not be written, so its recorded IDs cite placeholders no file backs.+ /// Projected from the turn records; `nil` means none of them reported one.+ public var imageWriteFailed: Bool?+ public var pinned: Bool++ public init(version: Int = ConversationMeta.currentVersion,+ id: UUID,+ title: String,+ titleSource: ConversationTitleSource = .firstMessage,+ createdAt: Date,+ updatedAt: Date,+ turnCount: Int = 0,+ kvTokens: Int? = nil,+ imageCount: Int = 0,+ identity: ConversationIdentity,+ session: ConversationSessionSettings,+ sampling: ConversationSampling,+ boundary: ConversationBoundary = ConversationBoundary(),+ imageWriteFailed: Bool? = nil,+ pinned: Bool = false) {+ self.version = version+ self.id = id+ self.title = title+ self.titleSource = titleSource+ self.createdAt = createdAt+ self.updatedAt = updatedAt+ self.turnCount = turnCount+ self.kvTokens = kvTokens+ self.imageCount = imageCount+ self.identity = identity+ self.session = session+ self.sampling = sampling+ self.boundary = boundary+ self.imageWriteFailed = imageWriteFailed+ self.pinned = pinned+ }+}++/// One image as the transcript records it.+///+/// Two digests, because they answer different questions: `sourceDigest` is the+/// file the user attached and names the stored copies, `modelInputDigest` is the+/// pixels the tower consumed and is what replay verifies. A file whose bytes+/// hash the same can still decode differently on a later macOS, which is why+/// the second one exists at all.+public struct ConversationImageRecord: Codable, Equatable, Sendable {+ public var id: UUID+ public var displayName: String+ /// Store-relative, so moving the conversations folder does not break it.+ public var pixelsFile: String+ public var thumbnailFile: String+ public var sourceDigest: String+ public var modelInputDigest: String+ public var width: Int+ public var height: Int+ public var softTokens: Int++ public init(id: UUID, displayName: String, pixelsFile: String,+ thumbnailFile: String, sourceDigest: String,+ modelInputDigest: String, width: Int, height: Int,+ softTokens: Int) {+ self.id = id+ self.displayName = displayName+ self.pixelsFile = pixelsFile+ self.thumbnailFile = thumbnailFile+ self.sourceDigest = sourceDigest+ self.modelInputDigest = modelInputDigest+ self.width = width+ self.height = height+ self.softTokens = softTokens+ }+}++public struct ConversationTurnRecord: Codable, Equatable, Sendable {+ public enum Role: String, Codable, Sendable { case user, assistant }++ public var id: UUID+ public var role: Role+ public var at: Date+ public var text: String+ public var images: [ConversationImageRecord]+ /// Exactly what this turn put into the KV. The replay record; `text` is the+ /// reading copy and cannot substitute for it.+ public var tokens: [Int32]?+ /// Kept for display and structurally excluded from replay: the tokens above+ /// already contain whatever the model emitted, thought spans included.+ public var thinking: String?+ public var promptTokens: Int?+ public var cachedTokens: Int?+ public var generatedTokens: Int?+ public var stopReason: String?+ /// Sampling as it was when this turn was sent. On the user half, because+ /// that is the half the settings applied to. Informational: it never enters+ /// replay identity.+ public var sampling: ConversationSampling?+ /// The token this turn left outside the KV. On the assistant half, because+ /// that is the half that produced it, and it is a fact about the end of the+ /// conversation rather than about the turn.+ public var boundary: ConversationBoundary?+ /// This turn carried pictures whose stored copies could not be written.+ ///+ /// `tokens` above still holds their placeholder runs, so a replay would+ /// hand the model a span of image tokens with nothing behind them and the+ /// context would silently differ from the one the answer was produced in.+ /// The write used to be attempted with `try?`: the picture vanished from+ /// the record, the placeholders stayed in the IDs, and nothing said so.+ /// Optional because a transcript written before this build has no answer to+ /// give; absent reads as "no failure was reported".+ public var imageWriteFailed: Bool?++ public init(id: UUID = UUID(), role: Role, at: Date, text: String,+ images: [ConversationImageRecord] = [],+ tokens: [Int32]? = nil, thinking: String? = nil,+ promptTokens: Int? = nil, cachedTokens: Int? = nil,+ generatedTokens: Int? = nil, stopReason: String? = nil,+ sampling: ConversationSampling? = nil,+ boundary: ConversationBoundary? = nil,+ imageWriteFailed: Bool? = nil) {+ self.id = id+ self.role = role+ self.at = at+ self.text = text+ self.images = images+ self.tokens = tokens+ self.thinking = thinking+ self.promptTokens = promptTokens+ self.cachedTokens = cachedTokens+ self.generatedTokens = generatedTokens+ self.stopReason = stopReason+ self.sampling = sampling+ self.boundary = boundary+ self.imageWriteFailed = imageWriteFailed+ }+}++/// The first line of every transcript: what the conversation is and what it was+/// made under.+///+/// The three creation facts are optional because a transcript written before+/// they moved here does not carry them; for those, `open` hoists them out of+/// the legacy `conversation.json` into an `origin` record once. An older build+/// reading this one's header simply does not ask for the extra keys.+public struct ConversationHeaderRecord: Codable, Equatable, Sendable {+ public var version: Int+ public var id: UUID+ public var createdAt: Date+ public var identity: ConversationIdentity?+ public var session: ConversationSessionSettings?+ /// Sampling as the window had it when the chat was started. Superseded by+ /// any turn that records its own, which is every turn this build writes.+ public var sampling: ConversationSampling?++ public init(version: Int = ConversationMeta.currentVersion,+ id: UUID, createdAt: Date,+ identity: ConversationIdentity? = nil,+ session: ConversationSessionSettings? = nil,+ sampling: ConversationSampling? = nil) {+ self.version = version+ self.id = id+ self.createdAt = createdAt+ self.identity = identity+ self.session = session+ self.sampling = sampling+ }+}++/// The creation facts of a conversation whose header predates them, lifted out+/// of its `conversation.json` once and appended so the projection has a record+/// to read them from.+///+/// Written by `open` under the writer lock and never again: a header carrying+/// identity, or an `origin` already in the file, means there is nothing to do.+/// A build older than this one reads the line as `.unknown("origin")` and+/// ignores it, which is what the record enum's default case is for.+public struct ConversationOriginRecord: Codable, Equatable, Sendable {+ public var identity: ConversationIdentity+ public var session: ConversationSessionSettings+ public var sampling: ConversationSampling+ public var boundary: ConversationBoundary+ public var at: Date++ public init(identity: ConversationIdentity,+ session: ConversationSessionSettings,+ sampling: ConversationSampling,+ boundary: ConversationBoundary,+ at: Date) {+ self.identity = identity+ self.session = session+ self.sampling = sampling+ self.boundary = boundary+ self.at = at+ }+}++public struct ConversationTitleRecord: Codable, Equatable, Sendable {+ public var title: String+ public var source: ConversationTitleSource+ public var at: Date++ public init(title: String, source: ConversationTitleSource, at: Date) {+ self.title = title+ self.source = source+ self.at = at+ }+}++/// One line of `transcript.jsonl`.+///+/// The `type` is read before anything else and an unrecognised one becomes+/// `.unknown` rather than an error, so a file written by a later build stays+/// readable to this one instead of taking the whole conversation down. The same+/// rule every surviving design in this space arrived at, and the reason+/// `MacAppSettings` already reads its version through a stamp.+public enum TranscriptRecord: Equatable, Sendable {+ case header(ConversationHeaderRecord)+ case turn(ConversationTurnRecord)+ /// A checkpoint of a reply still being generated. A later `turn` with the+ /// same id supersedes it.+ case partial(ConversationTurnRecord)+ case title(ConversationTitleRecord)+ /// A legacy conversation's creation facts, hoisted out of its meta once.+ case origin(ConversationOriginRecord)+ case unknown(type: String)+}++extension TranscriptRecord: Codable {+ private enum CodingKeys: String, CodingKey {+ case type, header, turn, partial, title, origin+ }++ public init(from decoder: any Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ let type = try container.decode(String.self, forKey: .type)+ switch type {+ case "header":+ self = .header(try container.decode(+ ConversationHeaderRecord.self, forKey: .header))+ case "turn":+ self = .turn(try container.decode(+ ConversationTurnRecord.self, forKey: .turn))+ case "partial":+ self = .partial(try container.decode(+ ConversationTurnRecord.self, forKey: .partial))+ case "title":+ self = .title(try container.decode(+ ConversationTitleRecord.self, forKey: .title))+ case "origin":+ self = .origin(try container.decode(+ ConversationOriginRecord.self, forKey: .origin))+ default:+ self = .unknown(type: type)+ }+ }++ public func encode(to encoder: any Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ switch self {+ case .header(let value):+ try container.encode("header", forKey: .type)+ try container.encode(value, forKey: .header)+ case .turn(let value):+ try container.encode("turn", forKey: .type)+ try container.encode(value, forKey: .turn)+ case .partial(let value):+ try container.encode("partial", forKey: .type)+ try container.encode(value, forKey: .partial)+ case .title(let value):+ try container.encode("title", forKey: .type)+ try container.encode(value, forKey: .title)+ case .origin(let value):+ try container.encode("origin", forKey: .type)+ try container.encode(value, forKey: .origin)+ case .unknown(let type):+ try container.encode(type, forKey: .type)+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationStore.swift b/Sources/TurboFieldfareApp/Core/History/ConversationStore.swiftnew file mode 100644index 00000000..140d7b5a--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationStore.swift@@ -0,0 +1,755 @@+import Darwin+import Foundation+import TurboFieldfare+import TurboFieldfareRepackCore++public enum ConversationStoreError: Error, Equatable, CustomStringConvertible {+ case readOnly(reason: String)+ case notFound(id: UUID)+ case lockUnavailable(path: String, errno: Int32)+ case headerMismatch(directory: String, header: UUID)+ case missingHeader(id: UUID)+ case tornRecord(id: UUID, line: Int)+ case newerVersion(id: UUID, version: Int)+ case writeFailed(path: String, reason: String)+ /// The transcript carries none of the creation facts and there is no+ /// readable meta to lift them out of, so there is no identity to check a+ /// replay against.+ case missingOrigin(id: UUID)++ public var description: String {+ switch self {+ case .readOnly(let reason):+ return "the conversation store is read-only: \(reason)"+ case .notFound(let id):+ return "no conversation \(id.uuidString) in the store"+ case .lockUnavailable(let path, let code):+ return "could not open the store lock at \(path): errno \(code)"+ case .headerMismatch(let directory, let header):+ return "conversation directory \(directory) holds a transcript "+ + "headed \(header.uuidString)"+ case .missingHeader(let id):+ return "conversation \(id.uuidString) has a transcript with no header"+ case .tornRecord(let id, let line):+ return "conversation \(id.uuidString) has an unreadable record at "+ + "line \(line); only a torn final line is recoverable"+ case .newerVersion(let id, let version):+ return "conversation \(id.uuidString) was written by a newer build "+ + "(version \(version))"+ case .writeFailed(let path, let reason):+ return "could not write \(path): \(reason)"+ case .missingOrigin(let id):+ return "conversation \(id.uuidString) records neither the model it "+ + "was written against nor a settings snapshot, and its "+ + "conversation.json cannot be read"+ }+ }+}++/// What `open` found, beside the records.+public struct ConversationOpenResult: Sendable {+ public let meta: ConversationMeta+ public let records: [TranscriptRecord]+ /// A newer build wrote this conversation. It is readable and must never be+ /// rewritten: an older build replacing a newer file with its own schema is+ /// the migration loss every client that has done it still hears about.+ public let isReadOnly: Bool+ /// A final line that was cut off mid-write, dropped and truncated away+ /// before the append handle opens. One lost turn, never a lost file.+ public let droppedTornFinalLine: Bool+ /// Why the cached meta had to be rebuilt from the records, or nil when it+ /// was already what the projection says.+ ///+ /// Reported rather than discarded: a `conversation.json` that could not be+ /// read is a real fault of the store even though the conversation survives+ /// it, and silently healing one leaves nobody able to say it ever happened.+ /// An ordinary disagreement — a stale copy, a hand edit — is not reported;+ /// it is simply replaced.+ public let metaRebuildReason: String?++ public init(meta: ConversationMeta,+ records: [TranscriptRecord],+ isReadOnly: Bool,+ droppedTornFinalLine: Bool,+ metaRebuildReason: String? = nil) {+ self.meta = meta+ self.records = records+ self.isReadOnly = isReadOnly+ self.droppedTornFinalLine = droppedTornFinalLine+ self.metaRebuildReason = metaRebuildReason+ }+}++struct ConversationLegacyTrashOperations: Sendable {+ let list: @Sendable (String) throws -> [String]+ let remove: @Sendable (URL) throws -> Void+}++struct ConversationStoreAppendOperations: Sendable {+ let beforeBatch: @Sendable () async throws -> Void+}++struct ConversationStoreListOperations: Sendable {+ let beforeList: @Sendable () async -> Void+}++/// The conversation store: a directory of plain-text conversations beside the+/// settings and the model.+///+/// One directory per conversation, because that makes delete an `rm -rf`, makes+/// a corrupt conversation one skippable directory rather than a broken store,+/// and lets images be sidecar files instead of base64 inside the transcript.+/// `conversation.json` is small and rewritten atomically; `transcript.jsonl` is+/// append-only and written one whole line at a time, so the worst a crash can+/// cost is the line that was in flight.+public actor ConversationStore {+ public let rootURL: URL+ private let fileManager: FileManager+ private let legacyTrashOperations: ConversationLegacyTrashOperations?+ private let appendOperations: ConversationStoreAppendOperations?+ private let listOperations: ConversationStoreListOperations?+ private var lock: ConversationStoreLock?+ /// Conversations a newer build wrote. Held so an append can refuse before+ /// it touches the file rather than after.+ private var readOnlyConversations: Set<UUID> = []++ public init(rootURL: URL, fileManager: FileManager = .default) {+ self.rootURL = rootURL+ self.fileManager = fileManager+ self.legacyTrashOperations = nil+ self.appendOperations = nil+ self.listOperations = nil+ }++ init(rootURL: URL,+ fileManager: FileManager = .default,+ legacyTrashOperations: ConversationLegacyTrashOperations) {+ self.rootURL = rootURL+ self.fileManager = fileManager+ self.legacyTrashOperations = legacyTrashOperations+ self.appendOperations = nil+ self.listOperations = nil+ }++ init(rootURL: URL,+ fileManager: FileManager = .default,+ appendOperations: ConversationStoreAppendOperations) {+ self.rootURL = rootURL+ self.fileManager = fileManager+ self.legacyTrashOperations = nil+ self.appendOperations = appendOperations+ self.listOperations = nil+ }++ init(rootURL: URL,+ fileManager: FileManager = .default,+ listOperations: ConversationStoreListOperations) {+ self.rootURL = rootURL+ self.fileManager = fileManager+ self.legacyTrashOperations = nil+ self.appendOperations = nil+ self.listOperations = listOperations+ }++ /// Takes the writer lock. A store that could not take it still lists and+ /// opens conversations; it just cannot change them.+ public func activate() throws {+ guard lock == nil else { return }+ lock = try ConversationStoreLock.acquire(storeRoot: rootURL)+ do {+ try discardLegacyTrash()+ } catch {+ lock = nil+ throw error+ }+ }++ /// Removes the `.trash` an older build left behind.+ ///+ /// Delete used to park a conversation there so an undo could restore it,+ /// and nothing ever emptied it — so every chat anyone deleted is still on+ /// disk, transcript and images, with the code that could have collected it+ /// now gone. Deleting means deleting, including retroactively. Once: after+ /// this the directory does not exist and there is nothing to do.+ private func discardLegacyTrash() throws {+ // Only the instance holding the writer lock. A second window is here to+ // read, and must not delete anything on the first one's behalf.+ guard lock != nil else { return }+ let trash = rootURL.appendingPathComponent(".trash", isDirectory: true)+ guard fileManager.fileExists(atPath: trash.path) else { return }+ let contents: [String]+ if let legacyTrashOperations {+ contents = try legacyTrashOperations.list(trash.path)+ try legacyTrashOperations.remove(trash)+ } else {+ contents = try fileManager.contentsOfDirectory(atPath: trash.path)+ try fileManager.removeItem(at: trash)+ }+ discardedLegacyTrashCount = contents.count+ }++ /// How many conversations the legacy `.trash` held when it was removed, so+ /// the app can say so rather than silently reclaiming someone's chats.+ public private(set) var discardedLegacyTrashCount = 0++ /// Tries again for a lock this store could not take at activation, and says+ /// why when it could not for a reason worth hearing.+ ///+ /// Never releases one it already holds. `EWOULDBLOCK` is the ordinary+ /// answer while another window is open, and returns nil; anything else — a+ /// read-only volume, a permission change, a store root that is now a file —+ /// used to read as "another instance holds it" for the rest of the session,+ /// with the window offering a retry that could never succeed.+ @discardableResult+ public func retryLock() -> String? {+ guard lock == nil else { return nil }+ do {+ lock = try ConversationStoreLock.acquire(storeRoot: rootURL)+ } catch {+ return "\(error)"+ }+ if lock != nil {+ do {+ try discardLegacyTrash()+ } catch {+ lock = nil+ return "\(error)"+ }+ }+ return nil+ }++ public var isReadOnly: Bool { lock == nil }++ public func directoryURL(for id: UUID) -> URL {+ rootURL.appendingPathComponent(id.uuidString, isDirectory: true)+ }++ // MARK: - Listing++ /// Every conversation the store holds, newest first.+ ///+ /// Reads only `conversation.json`: a sidebar that parsed transcripts would+ /// scale with the size of the conversations rather than their number. A+ /// directory whose meta will not decode is skipped rather than failing the+ /// list, because one bad conversation must not hide the rest.+ public func list() async throws -> [ConversationMeta] {+ await listOperations?.beforeList()+ skippedByLastList = []+ skipReasons = [:]+ guard fileManager.fileExists(atPath: rootURL.path) else { return [] }+ let entries = try fileManager.contentsOfDirectory(+ at: rootURL,+ includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey],+ options: [.skipsHiddenFiles])+ var result: [ConversationMeta] = []+ var skipped: [UUID] = []+ var reasons: [UUID: String] = [:]+ for entry in entries {+ guard let id = UUID(uuidString: entry.lastPathComponent) else { continue }+ // A directory whose meta names a different conversation is not that+ // conversation: it is a copy someone made, or a restore from a+ // recovery tool. Listed, its id collides with the original's, and+ // the sidebar — which keys rows by id — drew one of the two as a+ // blank row taking up space and doing nothing.+ var reason = "its conversation.json names another conversation"+ do {+ let meta = try readMeta(id: id)+ if meta.id == id {+ result.append(meta)+ continue+ }+ } catch {+ reason = "\(error)"+ }+ // The cache is missing, damaged, or names somebody else. It is only+ // a cache, so the records can rebuild it — one parse for this+ // directory, and none for the healthy ones. Only under the writer+ // lock: a second window must not repair the first one's store, and+ // a conversation whose transcript is genuinely unreadable still+ // ends up skipped.+ //+ // Skipping is right — one unreadable conversation must not hide the+ // rest — but it is not nothing, and a chat that disappears with no+ // trace is worse than one that shows as broken. The reason travels+ // with the id now, so the sidebar's "could not be read" can say what+ // stopped it instead of discarding the cause a second time.+ guard lock != nil else {+ skipped.append(id)+ reasons[id] = reason + "; this window cannot repair it because "+ + "another one holds the writer lock"+ continue+ }+ do {+ let rebuilt = try open(id: id).meta+ guard rebuilt.id == id else {+ skipped.append(id)+ reasons[id] = "its records are headed by another conversation"+ continue+ }+ result.append(rebuilt)+ } catch {+ skipped.append(id)+ reasons[id] = "\(error)"+ }+ }+ skippedByLastList = skipped+ skipReasons = reasons+ return result.sorted { $0.updatedAt > $1.updatedAt }+ }++ /// The conversations the last `list` could not read, and therefore left+ /// out. Reported rather than counted at the call site, because only this+ /// knows which directories it walked past.+ public private(set) var skippedByLastList: [UUID] = []++ /// Why each of them was left out.+ ///+ /// The sidebar counts the rows it could not read; without this it could say+ /// how many and nothing about why, which is the one question the person+ /// looking at that count has.+ public private(set) var skipReasons: [UUID: String] = [:]++ // MARK: - Lifecycle++ /// Starts a conversation: a directory, a header carrying what it was made+ /// under, and the name it starts with.+ ///+ /// `title` is written as a `title` record rather than into the meta. The+ /// meta is a projection of the records, so a name assigned only there would+ /// be gone at the next open — and the row would read "New Chat" for the+ /// length of the first reply, which is exactly when the user is looking at+ /// it.+ public func create(id: UUID = UUID(),+ title: String,+ identity: ConversationIdentity,+ session: ConversationSessionSettings,+ sampling: ConversationSampling,+ now: Date = Date()) throws -> ConversationMeta {+ try requireWritable()+ let directory = directoryURL(for: id)+ try fileManager.createDirectory(+ at: directory.appendingPathComponent("images", isDirectory: true),+ withIntermediateDirectories: true)+ var records: [TranscriptRecord] = [+ .header(ConversationHeaderRecord(+ id: id, createdAt: now, identity: identity, session: session,+ sampling: sampling)),+ ]+ let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)+ if !trimmed.isEmpty {+ records.append(.title(ConversationTitleRecord(+ title: trimmed, source: .firstMessage, at: now)))+ }+ for record in records { try appendLine(record, to: id) }+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ try writeMeta(meta)+ return meta+ }++ /// Reads a conversation's meta and every transcript record.+ ///+ /// A final line cut off mid-write is dropped and truncated away, so the+ /// append that follows starts on a clean boundary. A line that fails to+ /// parse anywhere else is an error: it means the file was written by two+ /// writers or damaged in place, and appending to it would bury the evidence+ /// under more records.+ public func open(id: UUID) throws -> ConversationOpenResult {+ try open(id: id, recoverIncompleteExchange: true)+ }++ private func open(id: UUID,+ recoverIncompleteExchange: Bool) throws -> ConversationOpenResult {+ // The cached meta is read for two things only: the version stamp, which+ // decides read-only, and the creation facts of a store written before+ // they moved into the header. Everything else comes from the records.+ // A failure here is not fatal and not silent either — it is the reason+ // the cache is about to be rebuilt, and it travels with the result.+ var legacy: ConversationMeta?+ var metaFailure: String?+ do {+ legacy = try readMeta(id: id)+ } catch {+ metaFailure = "\(error)"+ }+ // `readMeta` has already recorded a newer major it could not decode+ // past the version stamp, and that one must not be rewritten either.+ var isReadOnly = readOnlyConversations.contains(id)+ || (legacy?.version ?? ConversationMeta.currentVersion)+ > ConversationMeta.currentVersion+ if isReadOnly { readOnlyConversations.insert(id) }++ let transcript = transcriptURL(for: id)+ guard let data = fileManager.contents(atPath: transcript.path) else {+ throw ConversationStoreError.missingHeader(id: id)+ }++ var droppedTornFinalLine = false+ var complete = data+ if let lastNewline = data.lastIndex(of: 0x0A) {+ if lastNewline + 1 < data.count {+ complete = data.prefix(upTo: lastNewline + 1)+ droppedTornFinalLine = true+ }+ } else if !data.isEmpty {+ complete = Data()+ droppedTornFinalLine = true+ }++ struct PositionedRecord {+ let record: TranscriptRecord+ let byteOffset: Int+ }++ var positioned: [PositionedRecord] = []+ var line = 0+ let decoder = Self.makeDecoder()+ var lineStart = complete.startIndex+ while lineStart < complete.endIndex {+ guard let newline = complete[lineStart...].firstIndex(of: 0x0A) else {+ break+ }+ let chunk = complete[lineStart..<newline]+ defer { lineStart = complete.index(after: newline) }+ guard !chunk.isEmpty else { continue }+ line += 1+ guard let record = try? decoder.decode(+ TranscriptRecord.self, from: Data(chunk)) else {+ throw ConversationStoreError.tornRecord(id: id, line: line)+ }+ positioned.append(PositionedRecord(+ record: record,+ byteOffset: complete.distance(from: complete.startIndex, to: lineStart)))+ }++ // Metadata is disposable. Its loss must not let this build repair or+ // append to a newer writer's authoritative transcript.+ if case .header(let header)? = positioned.first?.record,+ header.version > ConversationMeta.currentVersion {+ isReadOnly = true+ readOnlyConversations.insert(id)+ }++ var incompleteExchangeOffset: Int?+ var pendingUserIndex: Int?+ for index in positioned.indices {+ guard case .turn(let turn) = positioned[index].record else { continue }+ switch turn.role {+ case .user:+ if pendingUserIndex == nil { pendingUserIndex = index }+ case .assistant:+ pendingUserIndex = nil+ }+ }+ if recoverIncompleteExchange, let pendingUserIndex {+ incompleteExchangeOffset = positioned[pendingUserIndex].byteOffset+ positioned.removeSubrange(pendingUserIndex...)+ }++ var records = positioned.map(\.record)+ if !isReadOnly, lock != nil {+ if let incompleteExchangeOffset {+ try truncate(transcript, to: incompleteExchangeOffset)+ } else if droppedTornFinalLine {+ try truncate(transcript, to: complete.count)+ }+ }++ let isWritable = !isReadOnly && lock != nil+ // A transcript that predates the header's creation facts gets them+ // once, lifted out of the meta that still has them. After this the+ // conversation projects from its own records alone, and the cache it+ // came from can be deleted without losing anything.+ if isWritable,+ let hoisted = ConversationMetaProjection.hoist(+ records: records, legacy: legacy) {+ try appendLine(.origin(hoisted), to: id)+ records.append(.origin(hoisted))+ }++ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: legacy)+ // Healed under the writer lock only. A read-only store — a second+ // window, or a conversation a newer build wrote — leaves the bytes+ // exactly as their owner wrote them.+ if isWritable, legacy != meta {+ try writeMeta(meta)+ }+ return ConversationOpenResult(+ meta: meta, records: records, isReadOnly: isReadOnly,+ droppedTornFinalLine: droppedTornFinalLine,+ metaRebuildReason: metaFailure)+ }++ /// Appends records and returns the meta they project to.+ ///+ /// A batch rather than one call per record because the meta is written once+ /// for the group: a turn is two records, and rebuilding the cache between+ /// them would publish a conversation with a question and no answer. Each+ /// record is still its own `write(2)` and `fsync`, so a crash still costs+ /// at most the line in flight.+ @discardableResult+ public func append(_ records: [TranscriptRecord],+ to id: UUID) async throws -> ConversationMeta {+ try requireWritable()+ try requireConversationWritable(id)+ try await appendOperations?.beforeBatch()+ try Task.checkCancellation()+ // Read first, with the repair every open makes: the torn line a crash+ // left. Only `open` used to make it, and a rename or a turn on a+ // conversation that had been listed but not opened since the crash+ // landed its record behind the fragment — a torn record in the middle,+ // which nothing recovers, so the conversation could never be opened+ // again. Not the unanswered-question repair: a caller may append the+ // answer on its own, and that repair would truncate the question it+ // is about to answer.+ let opened = try open(id: id, recoverIncompleteExchange: false)+ // Opening can discover a newer version that was not in the cache when+ // this append began. Its records and metadata must both stay untouched.+ try requireConversationWritable(id)+ for record in records {+ try Task.checkCancellation()+ try appendLine(record, to: id)+ }+ // Projected from the records just read plus the ones just written,+ // so the transcript is decoded once per append rather than read again+ // for the cache.+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: opened.records + records, legacy: opened.meta)+ try writeMeta(meta)+ return meta+ }++ /// Renames a conversation without touching `updatedAt`.+ ///+ /// The list is ordered by when a conversation was last *used*, and renaming+ /// one is not using it: bumping the timestamp jumped the row to the top of+ /// the sidebar, which is not what anyone tidying up their titles is asking+ /// for. The title record carries its own timestamp, so nothing is lost —+ /// and because the meta is projected from the records, the rule holds by+ /// construction rather than by remembering not to assign the field.+ public func rename(id: UUID, to title: String, now: Date = Date()) async throws {+ try requireWritable()+ try requireConversationWritable(id)+ // A rename reaches a conversation the sidebar listed but nobody opened+ // since a crash. The question that crash left unanswered is dropped+ // now, before the title lands: behind it, the next recovering open+ // truncated the question and the title together, and the rename+ // silently reverted.+ _ = try open(id: id, recoverIncompleteExchange: true)+ try await append(+ [.title(ConversationTitleRecord(title: title, source: .user, at: now))],+ to: id)+ }++ // MARK: - Delete++ /// Deletes a conversation and everything in it, for good.+ ///+ /// No staging area. A conversation used to be moved to `.trash` so an undo+ /// could bring it back, which meant a deleted chat kept its transcript and+ /// every image it held for the life of the store and nothing ever collected+ /// them. Delete means delete; the protection against deleting the wrong one+ /// is asking first, which is where it belongs.+ public func delete(id: UUID) throws {+ try requireWritable()+ let directory = directoryURL(for: id)+ guard fileManager.fileExists(atPath: directory.path) else {+ throw ConversationStoreError.notFound(id: id)+ }+ try fileManager.removeItem(at: directory)+ readOnlyConversations.remove(id)+ }++ /// Removes image files no surviving turn refers to.+ ///+ /// A turn that was rewound after its images were written leaves them+ /// behind, and nothing else would ever collect them: the transcript is+ /// append-only and the files are named by digest, so they are invisible to+ /// every other pass.+ @discardableResult+ public func sweepOrphanImages(in id: UUID) throws -> Int {+ try requireWritable()+ try requireConversationWritable(id)+ let opened = try open(id: id)+ try requireConversationWritable(id)+ var referenced: Set<String> = []+ for record in opened.records {+ let turn: ConversationTurnRecord+ switch record {+ case .turn(let value), .partial(let value): turn = value+ default: continue+ }+ for image in turn.images {+ referenced.insert(image.pixelsFile)+ referenced.insert(image.thumbnailFile)+ }+ }+ let imagesDirectory = directoryURL(for: id)+ .appendingPathComponent("images", isDirectory: true)+ guard fileManager.fileExists(atPath: imagesDirectory.path) else { return 0 }+ var removed = 0+ for file in try fileManager.contentsOfDirectory(+ at: imagesDirectory, includingPropertiesForKeys: nil,+ options: [.skipsHiddenFiles]) {+ let relative = "images/" + file.lastPathComponent+ guard !referenced.contains(relative) else { continue }+ try fileManager.removeItem(at: file)+ removed += 1+ }+ return removed+ }++ // MARK: - Files++ public func metaURL(for id: UUID) -> URL {+ directoryURL(for: id).appendingPathComponent(+ ConversationMeta.fileName, isDirectory: false)+ }++ public func transcriptURL(for id: UUID) -> URL {+ directoryURL(for: id).appendingPathComponent(+ "transcript.jsonl", isDirectory: false)+ }++ public func imagesURL(for id: UUID) -> URL {+ directoryURL(for: id).appendingPathComponent("images", isDirectory: true)+ }++ // MARK: - Internals++ private func requireWritable() throws {+ guard lock != nil else {+ throw ConversationStoreError.readOnly(+ reason: "another instance of the app holds the writer lock")+ }+ }++ private func requireConversationWritable(_ id: UUID) throws {+ guard !readOnlyConversations.contains(id) else {+ throw ConversationStoreError.readOnly(+ reason: "conversation \(id.uuidString) was written by a newer build")+ }+ }++ /// Reads the version on its own before decoding the rest.+ ///+ /// The same shape `MacAppSettings` uses, and for the same reason: every+ /// other field decodes strictly, so a newer build that moved any of them+ /// would throw here — and a throw is what an older build turns into+ /// "replace the file with my defaults".+ private func readMeta(id: UUID) throws -> ConversationMeta {+ let url = metaURL(for: id)+ guard let data = fileManager.contents(atPath: url.path) else {+ throw ConversationStoreError.notFound(id: id)+ }+ let decoder = Self.makeDecoder()+ let stamp = try decoder.decode(VersionStamp.self, from: data)+ guard stamp.version <= ConversationMeta.currentVersion else {+ // Enough to list and open it read-only. Decoding the rest could+ // throw on a field this build does not know, and the conversation+ // would then be invisible instead of merely uneditable.+ readOnlyConversations.insert(id)+ var placeholder = try? decoder.decode(ConversationMeta.self, from: data)+ placeholder?.version = stamp.version+ guard let placeholder else {+ throw ConversationStoreError.newerVersion(+ id: id, version: stamp.version)+ }+ return placeholder+ }+ return try decoder.decode(ConversationMeta.self, from: data)+ }++ private func writeMeta(_ meta: ConversationMeta) throws {+ let encoder = Self.makeEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ var data = try encoder.encode(meta)+ data.append(0x0A)+ let url = metaURL(for: meta.id)+ // Temp file, fsync, rename, fsync the parent. A half-written+ // conversation.json is a conversation the sidebar cannot list, and the+ // repack target already owns the only implementation of this the tree+ // needs.+ try Posix.atomicWrite(+ data, to: url.path,+ durableIn: url.deletingLastPathComponent().path)+ }++ /// One `write(2)` of the whole line plus its newline, then `fsync`.+ ///+ /// Whole-line writes are what keep a crash to one lost turn: a partial line+ /// can only ever be the last one, which `open` drops and truncates. Two+ /// writes per record would let a crash split a record in the middle of the+ /// file, which is not recoverable.+ private func appendLine(_ record: TranscriptRecord, to id: UUID) throws {+ let url = transcriptURL(for: id)+ var data = try Self.makeEncoder().encode(record)+ data.append(0x0A)+ let descriptor = Darwin.open(url.path, O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard descriptor >= 0 else {+ throw ConversationStoreError.writeFailed(+ path: url.path, reason: "open failed with errno \(errno)")+ }+ defer { close(descriptor) }+ var status = stat()+ guard fstat(descriptor, &status) == 0 else {+ throw ConversationStoreError.writeFailed(+ path: url.path, reason: "fstat failed with errno \(errno)")+ }+ let lengthBefore = status.st_size+ let written = data.withUnsafeBytes { raw -> Int in+ guard let base = raw.baseAddress else { return 0 }+ return Darwin.write(descriptor, base, raw.count)+ }+ guard written == data.count else {+ // A short write is a torn line that is not the last one for long:+ // the next append would land behind it. Cut back to the record+ // boundary so the file holds whole lines or nothing new.+ _ = Darwin.ftruncate(descriptor, lengthBefore)+ throw ConversationStoreError.writeFailed(+ path: url.path,+ reason: "wrote \(written) of \(data.count) bytes")+ }+ guard Darwin.fsync(descriptor) == 0 else {+ throw ConversationStoreError.writeFailed(+ path: url.path, reason: "fsync failed with errno \(errno)")+ }+ }++ private func truncate(_ url: URL, to length: Int) throws {+ let descriptor = Darwin.open(url.path, O_WRONLY | O_NOFOLLOW | O_CLOEXEC)+ guard descriptor >= 0 else {+ throw ConversationStoreError.writeFailed(+ path: url.path, reason: "open failed with errno \(errno)")+ }+ defer { close(descriptor) }+ guard Darwin.ftruncate(descriptor, off_t(length)) == 0 else {+ throw ConversationStoreError.writeFailed(+ path: url.path, reason: "ftruncate failed with errno \(errno)")+ }+ // A repair that did not reach the disk is a repair a crash undoes: the+ // torn line would be back under the record appended after it.+ guard Darwin.fsync(descriptor) == 0 else {+ throw ConversationStoreError.writeFailed(+ path: url.path, reason: "fsync failed with errno \(errno)")+ }+ }++ private struct VersionStamp: Decodable {+ let version: Int+ }++ private static func makeEncoder() -> JSONEncoder {+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ return encoder+ }++ private static func makeDecoder() -> JSONDecoder {+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601+ return decoder+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationStoreBinding.swift b/Sources/TurboFieldfareApp/Core/History/ConversationStoreBinding.swiftnew file mode 100644index 00000000..62ab3430--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationStoreBinding.swift@@ -0,0 +1,28 @@+import Foundation+import TurboFieldfare++/// The conversation store and model identity belonging to one model path.+///+/// Async store work captures the generation and must prove it is still current+/// before changing UI state. A path switch can otherwise let a slow list or+/// open from the old root overwrite the new model's history.+struct ConversationStoreBinding: Sendable {+ let modelDirectory: URL+ let rootURL: URL+ let store: ConversationStore+ var identity: ConversationIdentity?+ let generation: UInt64++ init(modelDirectory: URL, identity: ConversationIdentity?, generation: UInt64,+ storeProvider: @Sendable (URL) -> ConversationStore = {+ ConversationStore(rootURL: $0)+ }) {+ let modelDirectory = modelDirectory.standardizedFileURL+ self.modelDirectory = modelDirectory+ self.rootURL = ConversationStoreLocation.url(forModelDirectory: modelDirectory)+ .standardizedFileURL+ self.store = storeProvider(rootURL)+ self.identity = identity+ self.generation = generation+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationStoreLocation.swift b/Sources/TurboFieldfareApp/Core/History/ConversationStoreLocation.swiftnew file mode 100644index 00000000..3d087029--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationStoreLocation.swift@@ -0,0 +1,37 @@+import Foundation++/// Where conversations live: beside the settings file and the model, one+/// directory per conversation.+///+/// The same derivation as `mac-app-settings.json`, deliberately. One location+/// rule is the whole point: an installed app puts both under Application+/// Support, a dev checkout puts both under `scratch/`, and moving the model with+/// `TURBO_FIELDFARE_MODEL_PATH` moves both together.+public enum ConversationStoreLocation {+ public static let directoryName = "conversations"++ public static func url(forModelDirectory modelDirectory: URL) -> URL {+ modelDirectory.standardizedFileURL+ .deletingLastPathComponent()+ .appendingPathComponent(directoryName, isDirectory: true)+ }++ /// Whether `fileURL` names something inside the store for this model.+ ///+ /// The decode service is handed image paths over a socket and opens+ /// whatever they name, so this is a trust boundary, not a tidiness check:+ /// without it a peer could use the service to read any file the user can.+ /// Same shape as `AppImageAttachmentStore.contains` — resolve, then require+ /// a strict path-component prefix, so `.../conversations-elsewhere` cannot+ /// pass as `.../conversations`.+ public static func contains(_ fileURL: URL, forModelDirectory modelDirectory: URL) -> Bool {+ guard fileURL.isFileURL else { return false }+ let resolved = fileURL.standardizedFileURL.resolvingSymlinksInPath()+ let root = url(forModelDirectory: modelDirectory)+ .standardizedFileURL.resolvingSymlinksInPath()+ let fileComponents = resolved.pathComponents+ let rootComponents = root.pathComponents+ guard fileComponents.count > rootComponents.count else { return false }+ return Array(fileComponents.prefix(rootComponents.count)) == rootComponents+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationStoreLock.swift b/Sources/TurboFieldfareApp/Core/History/ConversationStoreLock.swiftnew file mode 100644index 00000000..52ed2602--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationStoreLock.swift@@ -0,0 +1,72 @@+import Darwin+import Foundation+import TurboFieldfareRepackCore++/// The single-writer lock on the conversation store.+///+/// Two processes appending to one JSONL file is the documented corruption in+/// every client that has hit it: out-of-order records, a torn line in the+/// middle rather than at the end, and a file that then fails to open at all.+/// A second instance of the app takes no lock, reads the store, and says so.+///+/// Held for the instance's lifetime, released when this object is deallocated.+/// `flock` is per open file description, so a crash releases it with the+/// process and no stale lock survives a kill.+public final class ConversationStoreLock: @unchecked Sendable {+ public static let fileName = ".writer.lock"++ private let descriptor: Int32++ private init(descriptor: Int32) {+ self.descriptor = descriptor+ }++ deinit {+ _ = flock(descriptor, LOCK_UN)+ close(descriptor)+ }++ /// Takes the exclusive lock, or returns nil when another instance holds it.+ ///+ /// Nil rather than a throw for the busy case: a second window is a normal+ /// thing for a user to open, and it is not an error — it is read-only, and+ /// the sidebar tells them so. Anything else that goes wrong opening the lock+ /// file still throws, because a store that cannot be locked for an unknown+ /// reason must not be written to.+ public static func acquire(storeRoot: URL) throws -> ConversationStoreLock? {+ try FileManager.default.createDirectory(+ at: storeRoot, withIntermediateDirectories: true)+ let path = storeRoot.appendingPathComponent(fileName, isDirectory: false).path+ let descriptor = open(path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard descriptor >= 0 else {+ throw ConversationStoreError.lockUnavailable(+ path: path, errno: errno)+ }+ guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {+ let saved = errno+ close(descriptor)+ if saved == EWOULDBLOCK { return nil }+ throw ConversationStoreError.lockUnavailable(path: path, errno: saved)+ }+ // The file could have been replaced between open and flock — the+ // store root removed and recreated under a running instance — in which+ // case this holds the lock on an unlinked inode while the next+ // instance takes the new file's, and both write the same transcripts.+ // The same check the install and companion-pack locks make.+ let matches: Bool+ do {+ matches = try Posix.descriptorMatchesPath(descriptor, path: path)+ } catch RepackError.fileStatFailed(_, let code) {+ close(descriptor)+ throw ConversationStoreError.lockUnavailable(path: path, errno: code)+ } catch {+ close(descriptor)+ throw ConversationStoreError.lockUnavailable(path: path, errno: EIO)+ }+ guard matches else {+ close(descriptor)+ throw ConversationStoreError.lockUnavailable(path: path, errno: ESTALE)+ }+ return ConversationStoreLock(descriptor: descriptor)+ }+}diff --git a/Sources/TurboFieldfareApp/Core/History/ConversationTitle.swift b/Sources/TurboFieldfareApp/Core/History/ConversationTitle.swiftnew file mode 100644index 00000000..95f0dcbe--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/History/ConversationTitle.swift@@ -0,0 +1,31 @@+import Foundation++/// The name a conversation gets before anyone renames it.+///+/// The first user message, trimmed on a word boundary. Not a model-generated+/// title: that needs a second generation against the one KV the app has, which+/// would either evict the conversation the user is in or make them wait for a+/// name. A rename wins forever afterwards.+public enum ConversationTitle {+ public static let maximumCharacters = 60+ public static let untitled = "New Chat"++ public static func fromFirstMessage(_ text: String) -> String {+ let collapsed = text+ .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)+ .trimmingCharacters(in: .whitespacesAndNewlines)+ guard !collapsed.isEmpty else { return untitled }+ guard collapsed.count > maximumCharacters else { return collapsed }+ let clipped = collapsed.prefix(maximumCharacters)+ // Cut at the last space so the title ends on a word rather than mid-way+ // through one. A single very long word has no space to cut at, and is+ // clipped as it stands rather than replaced by an ellipsis alone.+ guard let lastSpace = clipped.lastIndex(of: " ") else {+ return String(clipped) + "\u{2026}"+ }+ let trimmed = clipped[clipped.startIndex..<lastSpace]+ .trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else { return String(clipped) + "\u{2026}" }+ return trimmed + "\u{2026}"+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppConversation.swift b/Sources/TurboFieldfareApp/Core/Inference/AppConversation.swiftindex 905606ea..f1f15002 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppConversation.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppConversation.swift@@ -6,16 +6,26 @@ public struct AppChatTurn: Identifiable, Equatable, Sendable {public let id: UUIDpublic let role: Rolepublic var text: String- public var images: [AppImageAttachment]+ public var images: [ChatImage]public var promptTokens: Int?public var cachedTokens: Int?public var generatedTokens: Int?public var stopReason: AppStopReason?+ /// What this turn put into the KV, in the model's own IDs.+ ///+ /// A user turn carries the continuation-encoded prompt it contributed; an+ /// assistant turn carries the reply the cache kept. `text` is what the+ /// reader sees and these are what the model saw, and the two are not+ /// interchangeable: the pinned template strips historical thought spans, so+ /// re-rendering `text` produces a different sequence. Nil on the+ /// single-prompt path, and on any turn the runtime rewound.+ public var tokenIDs: [Int32]?public init(id: UUID = UUID(), role: Role, text: String,- images: [AppImageAttachment] = [],+ images: [ChatImage] = [],promptTokens: Int? = nil, cachedTokens: Int? = nil,- generatedTokens: Int? = nil, stopReason: AppStopReason? = nil) {+ generatedTokens: Int? = nil, stopReason: AppStopReason? = nil,+ tokenIDs: [Int32]? = nil) {self.id = idself.role = roleself.text = text@@ -24,6 +34,50 @@ public struct AppChatTurn: Identifiable, Equatable, Sendable {self.cachedTokens = cachedTokensself.generatedTokens = generatedTokensself.stopReason = stopReason+ self.tokenIDs = tokenIDs+ }+}++/// One image of a stored conversation as the app hands it back for replay.+///+/// The span is a lower bound and a count rather than a `Range`, matching the+/// wire type it becomes: this travels to another process, and a range that+/// arrives inverted has to be refusable rather than fatal.+public struct AppConversationReplayImage: Sendable, Equatable {+ public let tokenLowerBound: Int+ public let tokenCount: Int+ public let fileURL: URL+ public let expectedDigest: String++ public init(tokenLowerBound: Int, tokenCount: Int,+ fileURL: URL, expectedDigest: String) {+ self.tokenLowerBound = tokenLowerBound+ self.tokenCount = tokenCount+ self.fileURL = fileURL+ self.expectedDigest = expectedDigest+ }+}++/// A stored conversation as the inference side needs it: the token IDs the KV+/// held, the images those IDs stand in for, and the turn count the reopened+/// lineage continues from.+public struct AppConversationLineage: Sendable, Equatable {+ public let tokenIDs: [Int32]+ public let images: [AppConversationReplayImage]+ public let boundaryTokenIDs: [Int32]+ public let boundaryNeedsReplay: Bool+ public let committedTurns: Int++ public init(tokenIDs: [Int32],+ images: [AppConversationReplayImage] = [],+ boundaryTokenIDs: [Int32] = [],+ boundaryNeedsReplay: Bool = false,+ committedTurns: Int) {+ self.tokenIDs = tokenIDs+ self.images = images+ self.boundaryTokenIDs = boundaryTokenIDs+ self.boundaryNeedsReplay = boundaryNeedsReplay+ self.committedTurns = committedTurns}}/// The app's half of one conversation: what the transcript shows, and the turn@@ -52,6 +106,25 @@ public struct AppConversation: Equatable, Sendable {/// 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+ /// A token the model emitted that the KV never took, because the last turn+ /// stopped on max tokens or was cancelled. The next turn replays it, so a+ /// stored conversation has to carry it or the reopened context is missing a+ /// token the model already produced.+ public private(set) var boundaryTokenIDs: [Int32] = []+ public private(set) var boundaryNeedsReplay: Bool = false+ /// The turns of this window's conversation whose KV a load or an unload+ /// took.+ ///+ /// They stay on screen because the app deliberately keeps a transcript+ /// across lifecycle actions, and the transcript draws a break above them to+ /// say the model can no longer see them. They belong to the conversation+ /// rather than to what is being drawn: held in the same array as the+ /// read-only copy of a chat being browsed, a reload while browsing drew+ /// that chat as this conversation's own out-of-context turns.+ ///+ /// Kept as turns and paired on demand so `Equatable` stays synthesized: an+ /// array of tuples has no conformance to derive from.+ private var outOfContextTurns: [AppChatTurn] = []private var pendingUserTurnID: UUID?public init(epoch: UUID = UUID()) {@@ -68,6 +141,17 @@ public struct AppConversation: Equatable, Sendable {/// 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)] {+ Self.pairs(of: turns)+ }++ /// The exchanges the transcript draws above the context break: on screen,+ /// and out of the model's context.+ public var outOfContextPairs: [(user: AppChatTurn, assistant: AppChatTurn)] {+ Self.pairs(of: outOfContextTurns)+ }++ private static func pairs(of turns: [AppChatTurn])+ -> [(user: AppChatTurn, assistant: AppChatTurn)] {var pairs: [(user: AppChatTurn, assistant: AppChatTurn)] = []var index = 0while index + 1 < turns.count {@@ -79,13 +163,44 @@ public struct AppConversation: Equatable, Sendable {}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()) {+ /// Starts a fresh lineage, optionally carrying the exchanges a released KV+ /// left on screen. The caller is responsible for telling the inference side+ /// about `epoch` before the next turn is sent.+ public mutating func startNew(+ epoch: UUID = UUID(),+ carryingOutOfContext pairs: [(user: AppChatTurn, assistant: AppChatTurn)] = []+ ) {+ self = AppConversation(epoch: epoch)+ outOfContextTurns = pairs.flatMap { [$0.user, $0.assistant] }+ }++ /// Forgets the exchanges a released KV left on screen, because the window+ /// is drawing something else now.+ public mutating func dropOutOfContextPairs() {+ outOfContextTurns = []+ }++ /// Adopts a stored conversation whose token IDs are back in the KV.+ ///+ /// `committedTurns` is derived from the turns rather than passed in, so the+ /// count the service's gate was opened at and the count this type reports+ /// come from the same transcript. Two independently supplied numbers is+ /// exactly the drift that makes the gate refuse every later turn.+ public mutating func adoptRestored(epoch: UUID,+ turns: [AppChatTurn],+ kvTokens: Int,+ boundaryTokenIDs: [Int32],+ boundaryNeedsReplay: Bool) {self = AppConversation(epoch: epoch)+ self.turns = turns+ self.committedTurns = turns.filter { $0.role == .user }.count+ self.kvTokens = kvTokens+ self.boundaryTokenIDs = boundaryTokenIDs+ self.boundaryNeedsReplay = boundaryNeedsReplay}/// Shows the user's turn and reserves its position, or refuses.@@ -95,9 +210,10 @@ public struct AppConversation: Equatable, Sendable {/// not read the banner yet. Neither should crash, and neither may be/// admitted.public mutating func beginTurn(text: String,- images: [AppImageAttachment] = []) -> Ticket? {+ images: [StagedImage] = []) -> Ticket? {guard canSend else { return nil }- let turn = AppChatTurn(role: .user, text: text, images: images)+ let turn = AppChatTurn(role: .user, text: text,+ images: images.map(ChatImage.staged))turns.append(turn)pendingUserTurnID = turn.idreturn Ticket(epoch: epoch, index: committedTurns)@@ -106,12 +222,14 @@ public struct AppConversation: Equatable, Sendable {/// 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]) {+ /// Only staged files reach a live turn: a stored conversation's pictures+ /// arrive through `adoptRestored`, already owned by the conversation store.+ public mutating func attachImagesToPendingTurn(_ images: [StagedImage]) {guard let pendingUserTurnID,let index = turns.firstIndex(where: { $0.id == pendingUserTurnID }) else {return}- turns[index].images = images+ turns[index].images = images.map(ChatImage.staged)}/// Records the reply. Called only when the generation stream completed,@@ -124,11 +242,15 @@ public struct AppConversation: Equatable, Sendable {}turns[userIndex].promptTokens = diagnostics?.promptTokenCountturns[userIndex].cachedTokens = diagnostics?.cachedPromptTokens+ turns[userIndex].tokenIDs = diagnostics?.promptTokenIDsturns.append(AppChatTurn(role: .assistant, text: text,generatedTokens: diagnostics?.generatedTokens,- stopReason: diagnostics?.stopReason))+ stopReason: diagnostics?.stopReason,+ tokenIDs: diagnostics?.generatedTokenIDs))committedTurns += 1+ boundaryTokenIDs = diagnostics?.boundaryTokenIDs ?? []+ boundaryNeedsReplay = diagnostics?.boundaryNeedsReplay ?? falseself.pendingUserTurnID = nil// Only the runtime knows the committed position. Sampled-token counts// include a boundary token that may not be in KV, and stop-stringdiff --git a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swiftindex 3eaa741b..30352b78 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift@@ -4,7 +4,10 @@ import TurboFieldfarepublic struct AppGenerationRequest: Equatable, Sendable {public var modelDirectory: URLpublic var prompt: String- public var imageAttachments: [AppImageAttachment]+ /// Staged files only. A request carries what this session may open and,+ /// on the service path, what it may hand to another process; a stored+ /// conversation's pictures reach the runtime as replay images instead.+ public var imageAttachments: [StagedImage]public var maxNewTokens: Intpublic var maxContextTokens: Intpublic var temperature: Float@@ -31,7 +34,7 @@ public struct AppGenerationRequest: Equatable, Sendable {public init(modelDirectory: URL,prompt: String,- imageAttachments: [AppImageAttachment] = [],+ imageAttachments: [StagedImage] = [],maxNewTokens: Int = 4_096,maxContextTokens: Int = 4096,temperature: Float = 0.2,@@ -85,8 +88,12 @@ public struct AppGenerationRequest: Equatable, Sendable {// 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.+ // Plus the reply's reserve, which `generate` checks after every image+ // has been encoded; admitting a set that fits the context but not the+ // reserve failed the turn on the runtime instead of here.let capacity = VisionImageTokenBudget.capacity(- maxContext: maxContextTokens, reservedTextTokens: conversationTokens)+ maxContext: maxContextTokens,+ reservedTextTokens: conversationTokens + ConversationGenerationReserve.tokens)guard imageAttachments.count <= capacity else {throw AppInferenceError.invalidRequest("\(imageAttachments.count) images need up to "diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppImageAttachment.swift b/Sources/TurboFieldfareApp/Core/Inference/AppImageAttachment.swiftindex 0296ff39..407a960e 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppImageAttachment.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppImageAttachment.swift@@ -2,7 +2,17 @@ import Darwinimport Foundationimport TurboFieldfare-public struct AppImageAttachment: Sendable, Equatable {+/// A picture this session staged, which the attachment store owns and may+/// delete.+///+/// The composer holds these, a run's retained hard links are these, and+/// `AppImageAttachmentStore.remove` accepts nothing else. One type with an+/// `ownership` tag used to stand for both this and `StoredImage`, checked at+/// run time inside `remove` — and once a reopened conversation's turns carried+/// attachments pointing into the conversation store, opening any other chat+/// deleted the pictures out of the one just left. The files were gone from+/// disk, not merely absent from the window.+public struct StagedImage: Sendable, Equatable, Identifiable {public let id: UUIDpublic let fileURL: URLpublic let displayName: String@@ -19,6 +29,86 @@ public struct AppImageAttachment: Sendable, Equatable {}}+/// A picture the conversation store owns, kept for as long as the conversation+/// exists and released only by deleting it.+///+/// There is deliberately no path from one of these to `remove`: the compiler+/// refuses it, so a release path that finishes a turn cannot reach a stored+/// conversation's files however it is written.+public struct StoredImage: Sendable, Equatable, Identifiable {+ public let id: UUID+ public let fileURL: URL+ public let displayName: String+ public let encodedBytes: Int+ public let sha256: String++ public init(id: UUID = UUID(), fileURL: URL, displayName: String,+ encodedBytes: Int, sha256: String) {+ self.id = id+ self.fileURL = fileURL+ self.displayName = displayName+ self.encodedBytes = encodedBytes+ self.sha256 = sha256+ }+}++/// A picture a turn is showing, and therefore who may delete it.+///+/// The transcript draws both kinds the same way, which is why they share a+/// type here; everything that deletes takes `StagedImage` and cannot be handed+/// one of these.+public enum ChatImage: Sendable, Equatable, Identifiable {+ case staged(StagedImage)+ case stored(StoredImage)++ public var id: UUID {+ switch self {+ case .staged(let image): return image.id+ case .stored(let image): return image.id+ }+ }++ public var fileURL: URL {+ switch self {+ case .staged(let image): return image.fileURL+ case .stored(let image): return image.fileURL+ }+ }++ public var displayName: String {+ switch self {+ case .staged(let image): return image.displayName+ case .stored(let image): return image.displayName+ }+ }++ public var encodedBytes: Int {+ switch self {+ case .staged(let image): return image.encodedBytes+ case .stored(let image): return image.encodedBytes+ }+ }++ /// The digest of the file the user attached. Also the thumbnail cache's+ /// key, so a picture already decoded for the composer is not decoded again+ /// for the transcript.+ public var sha256: String {+ switch self {+ case .staged(let image): return image.sha256+ case .stored(let image): return image.sha256+ }+ }++ /// The staged file behind this picture, or nil when the conversation store+ /// owns it. The only route from a drawn picture to a deletable one.+ public var staged: StagedImage? {+ switch self {+ case .staged(let image): return image+ case .stored: return nil+ }+ }+}+public struct AppImageAttachmentStore: Sendable {public static let rootName = "TurboFieldfare-Attachments"@@ -114,7 +204,7 @@ public struct AppImageAttachmentStore: Sendable {/// clearing or replacing the composer's attachments deleted the images a/// finished answer was still showing. A hard link rather than a copy: the/// files are sealed read-only and can be up to 64 MB each.- public func retain(_ attachment: AppImageAttachment) throws -> AppImageAttachment {+ public func retain(_ attachment: StagedImage) throws -> StagedImage {let directory = directoryURL.appendingPathComponent("retained", isDirectory: true)try FileManager.default.createDirectory(@@ -124,7 +214,7 @@ public struct AppImageAttachmentStore: Sendable {throw VisionImageError.invalidSource("could not retain \(attachment.displayName): errno \(errno)")}- return AppImageAttachment(+ return StagedImage(id: attachment.id,fileURL: destination,displayName: attachment.displayName,@@ -132,7 +222,7 @@ public struct AppImageAttachmentStore: Sendable {sha256: attachment.sha256)}- public func stage(_ sourceURL: URL) throws -> AppImageAttachment {+ public func stage(_ sourceURL: URL) throws -> StagedImage {let accessed = sourceURL.startAccessingSecurityScopedResource()defer { if accessed { sourceURL.stopAccessingSecurityScopedResource() } }@@ -202,7 +292,7 @@ public struct AppImageAttachmentStore: Sendable {/// Stages bytes that never existed as a file — an image copied from another/// app arrives on the pasteboard as data, with no URL to open.- public func stage(data: Data, displayName: String) throws -> AppImageAttachment {+ public func stage(data: Data, displayName: String) throws -> StagedImage {let limit = VisionImageLimits().maximumEncodedBytesguard !data.isEmpty else {throw VisionImageError.invalidSource("the pasteboard image was empty")@@ -219,7 +309,7 @@ public struct AppImageAttachmentStore: Sendable {displayName: String,encodedBytes: Int,writeContents: (Int32) throws -> Void- ) throws -> AppImageAttachment {+ ) throws -> StagedImage {try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)let id = UUID()@@ -262,7 +352,7 @@ public struct AppImageAttachmentStore: Sendable {try? FileManager.default.removeItem(at: destination)throw error}- return AppImageAttachment(+ return StagedImage(id: id,fileURL: destination,displayName: displayName,@@ -288,7 +378,21 @@ public struct AppImageAttachmentStore: Sendable {}}- public func remove(_ attachment: AppImageAttachment) {+ /// Deletes a file this store staged, and nothing else.+ ///+ /// The type is the first condition and the compiler checks it: a+ /// `StoredImage` cannot be handed to this at all, where the tag it+ /// replaces was a run-time check on a value anybody could set.+ public func remove(_ attachment: StagedImage) {+ // This store's own directory, not the shared root: a store only+ // removes what it staged, and a test store points somewhere else+ // entirely.+ // Resolved the same way `contains` resolves, or the two answer+ // differently under a symlinked root (`/var` against `/private/var`):+ // a link `contains` accepted was refused here and never freed.+ let owned = directoryURL.standardizedFileURL.resolvingSymlinksInPath().path+ let file = attachment.fileURL.standardizedFileURL.resolvingSymlinksInPath().path+ guard file.hasPrefix(owned + "/") else { return }try? FileManager.default.removeItem(at: attachment.fileURL)}diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swiftindex 6bcf85fd..036eabd3 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift@@ -13,6 +13,9 @@ public protocol AppModelLifecycleClient: AnyObject, AppInferenceClient {options: AppRuntimeOptions, forceLogitsHead: Bool,onState: @escaping @Sendable (AppModelLoadState) -> Void) async throwsfunc unload() async+ /// Synchronously releases this client's descriptors and any service it+ /// launched. External services are disconnected, never shut down.+ func shutdownForTermination()/// Ends the current conversation and opens `epoch` as the only lineage the/// inference side will accept turns for. The model stays loaded.///@@ -20,6 +23,27 @@ public protocol AppModelLifecycleClient: AnyObject, AppInferenceClient {/// 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+ /// Replays a stored conversation's token IDs into the KV, opens `epoch` as+ /// its lineage, and returns the token count the cache then holds.+ ///+ /// The count comes back from the inference side rather than being assumed+ /// from the lineage: the gauge and the image budget both read it, and a+ /// figure the app made up would be wrong in exactly the case that matters —+ /// a replay that did not put back what the record said.+ ///+ /// `onPrefillProgress` receives the same events a live turn reports, so a+ /// reopen shows progress instead of a frozen window for minutes.+ func restoreConversation(+ _ lineage: AppConversationLineage,+ epoch: UUID,+ options: AppRuntimeOptions,+ maxContextTokens: Int,+ onPrefillProgress: @escaping @Sendable (Int, Int) -> Void+ ) async throws -> Int+}++extension AppModelLifecycleClient {+ public func shutdownForTermination() {}}public protocol AppInferenceMemoryReporting: AnyObject {diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swift b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swiftindex 5ef58ddc..a92c932c 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swift@@ -6,18 +6,57 @@ public enum AppInferenceError: Error, Equatable, Sendable, CustomStringConvertibcase modelLoadFailed(String)case tokenizerUnavailable(String)case contextOverflow(prompt: Int, maxNew: Int, maxContext: Int)+ /// A chat that no longer leaves room for a reply. Separate from+ /// `contextOverflow` because the figure that matters is not the user's+ /// requested reply length but the floor a turn keeps free, and because the+ /// way out is a longer context or a new chat rather than a shorter prompt.+ case conversationContextExhausted(prompt: Int, reserve: Int, maxContext: Int)case generationInFlightcase modelNotLoadedcase reloadRequired+ case connectionLost(String)case 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)+ /// A stored conversation could not be replayed into the KV. The transcript+ /// is intact and readable; what failed is continuing it, which is why this+ /// is separate from a lost lineage — there is nothing to clear.+ case conversationRestoreFailed(String)+ /// A stored conversation could not be read off disk at all. Distinct from+ /// `conversationRestoreFailed`, which is a transcript that reads fine and+ /// cannot be continued: this one has nothing to show. It exists because the+ /// alternative was what the app did before — select the row, draw the empty+ /// state, and say nothing, which is indistinguishable from a chat that was+ /// never written.+ case conversationUnreadable(String)+ case conversationPersistenceFailed(String)case unknown(String)public var description: String { userMessage }+ /// The cause on its own, without the sentence `userMessage` wraps it in.+ ///+ /// For sending across a process boundary. The decode service used to+ /// forward `"\(error)"`, which is the sentence, and the client then wrapped+ /// it again — so a failed replay read "This conversation could not be+ /// reopened: This conversation could not be reopened: …".+ public var diagnosticMessage: String {+ switch self {+ case .invalidRequest(let message), .modelNotFound(let message),+ .modelLoadFailed(let message), .tokenizerUnavailable(let message),+ .conversationLineageLost(let message),+ .conversationRestoreFailed(let message),+ .conversationPersistenceFailed(let message),+ .conversationUnreadable(let message), .connectionLost(let message),+ .unknown(let message):+ return message+ default:+ return userMessage+ }+ }+public var userMessage: String {switch self {case .invalidRequest(let message):@@ -30,16 +69,26 @@ public enum AppInferenceError: Error, Equatable, Sendable, CustomStringConvertibreturn "Tokenizer unavailable: \(message)"case .contextOverflow(let prompt, let maxNew, let maxContext):return "Prompt (\(prompt) tokens) plus max response (\(maxNew)) exceeds the \(maxContext)-token context."+ case .conversationContextExhausted(let prompt, let reserve, let maxContext):+ return "This chat holds \(prompt) tokens and keeps \(reserve) free for a reply, which is more than the \(maxContext)-token context. Raise the context length or start a new chat."case .generationInFlight:return "A generation is already running."case .modelNotLoaded:return "Load the model before generating."case .reloadRequired:return "Model settings changed. Reload the model before generating."+ case .connectionLost(let message):+ return "The decode service connection was lost: \(message). Retry Load to continue."case .cancelled:return "Generation cancelled."case .conversationLineageLost(let message):return "This conversation can no longer continue: \(message) Start a new chat."+ case .conversationRestoreFailed(let message):+ return "This conversation could not be reopened: \(message)"+ case .conversationUnreadable(let message):+ return "This conversation could not be read: \(message)"+ case .conversationPersistenceFailed(let message):+ return "The latest exchange could not be saved reliably. Copy the answer before leaving this chat. \(message)"case .unknown(let message):return message}diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swiftindex abf3136d..3925d2da 100644--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift@@ -14,8 +14,24 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,var socketPath: String?}+ /// How long a wait for a service event may go quiet before the connection+ /// is declared dead. A load is bounded by the model, not by the protocol,+ /// so it gets the long one; generation events include prefill progress and+ /// per-token snapshots, so silence there means something is wrong.+ public static let loadTimeout: Duration = .seconds(900)+ public static let generationTimeout: Duration = .seconds(300)+ /// A reset does no model work, but it queues behind the service's serial+ /// command loop. The app blocks New chat during a run, so this only has to+ /// cover a load or a teardown finishing, not a whole generation.+ public static let conversationResetTimeout: Duration = .seconds(60)+ /// Restore prefills the whole conversation, including its images. It needs+ /// a longer silence deadline than reset, but cannot wait forever if the+ /// service stops answering.+ public static let conversationRestoreTimeout: Duration = .seconds(1_800)+private let connection = Mutex(Connection())private let serviceURL: URL+ private let testConnection: (@Sendable () throws -> (input: FileHandle, output: FileHandle))?private let inferenceMemory = Mutex<UInt64?>(nil)private let inferenceTowerMemory = Mutex<UInt64?>(nil)public let generationTranscriptMailbox = GenerationTranscriptMailbox()@@ -30,11 +46,13 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,public init(serviceURL: URL? = nil) {self.serviceURL = serviceURL ?? Self.defaultServiceURL()+ self.testConnection = nilDecodeUnixSocket.ignoreSIGPIPEProcessWide()}init(testInput: FileHandle, responseOutput: FileHandle) {self.serviceURL = Self.defaultServiceURL()+ self.testConnection = nilDecodeUnixSocket.ignoreSIGPIPEProcessWide()let responses = makeRouter(output: responseOutput)connection.withLock {@@ -47,6 +65,12 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,connection.withLock { $0.input != nil && $0.responses != nil }}+ init(testConnection: @escaping @Sendable () throws -> (input: FileHandle, output: FileHandle)) {+ self.serviceURL = Self.defaultServiceURL()+ self.testConnection = testConnection+ DecodeUnixSocket.ignoreSIGPIPEProcessWide()+ }+var installedRouter: DecodeServiceResponseRouter? {connection.withLock { $0.responses }}@@ -60,18 +84,44 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,return state}guard let dead else { return }+ guard dead.input != nil || dead.launchLabel != nil else { return }+ let ownsService = dead.launchLabel != nilif let input = dead.input {- try? input.write(contentsOf: DecodeFrameCodec.encode(- DecodeServiceCommand.shutdown))+ if ownsService {+ 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) }+ if ownsService {+ if let label = dead.launchLabel { Self.removeLaunchJob(label: label) }+ if let socketPath = dead.socketPath { unlink(socketPath) }+ }inferenceMemory.withLock { $0 = nil }inferenceTowerMemory.withLock { $0 = nil }}+ /// Runs a transport operation, dropping the connection if it fails.+ /// Generation-level failures reported *by* the service are ordinary events+ /// and never reach here; only a broken transport does.+ private func transport<T>(expecting responses: DecodeServiceResponseRouter,+ _ body: () async throws -> T) async throws -> T {+ do {+ return try await body()+ } catch is CancellationError {+ // A caller that stopped listening, not a broken transport. Tearing+ // the connection down here would make an abandoned stream cost a+ // service relaunch and a full reload; `ensureLoaded` treats its own+ // cancellation the same way.+ throw CancellationError()+ } catch {+ invalidateConnection(expecting: responses)+ if let appError = error as? AppInferenceError { throw appError }+ throw AppInferenceError.connectionLost(String(describing: error))+ }+ }+private func write(_ command: DecodeServiceCommand,to input: FileHandle,expecting responses: DecodeServiceResponseRouter) throws {@@ -79,8 +129,8 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,try input.write(contentsOf: DecodeFrameCodec.encode(command))} catch {invalidateConnection(expecting: responses)- throw AppInferenceError.unknown(- "could not reach the decode service: \(error)")+ throw AppInferenceError.connectionLost(+ "could not write a request: \(error)")}}@@ -96,7 +146,22 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,runtimeOptions: Self.decodeRuntimeOptions(options),forceLogitsHead: forceLogitsHead)try write(.load(request), to: handles.input, expecting: handles.responses)- let event = try await handles.responses.next(matching: request.requestID)+ let event: DecodeServiceEvent+ do {+ event = try await handles.responses.next(+ matching: request.requestID, timeout: Self.loadTimeout)+ } catch is CancellationError {+ // The service runs commands serially, so an abandoned load would+ // block every later command including the unload the UI is waiting+ // on. Tell it to stop; the connection stays usable.+ try? write(.cancel, to: handles.input, expecting: handles.responses)+ throw CancellationError()+ } catch {+ invalidateConnection(expecting: handles.responses)+ if let appError = error as? AppInferenceError { throw appError }+ throw AppInferenceError.connectionLost(+ "the decode service ended during model load: \(error)")+ }switch event.kind {case .ready:break@@ -162,7 +227,10 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,var lastMetricYield = Date.distantPastvar hasYieldedVisibleText = falsewhile true {- let event = try await handles.responses.next(matching: generationID)+ let event = try await transport(expecting: handles.responses) {+ try await handles.responses.next(+ matching: generationID, timeout: Self.generationTimeout)+ }// Only when the event carries a figure: an event// without one says nothing about memory, and clearing// the last reading made the display flicker to empty.@@ -261,44 +329,123 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,// *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(+ // refused and no recovery path could fire. And the class the+ // transport uses for the same loss, so the app marks the model as+ // needing a reload rather than showing a generic failure with no+ // Retry Load behind it.+ throw AppInferenceError.connectionLost("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)+ let event = try await transport(expecting: handles.responses) {+ try await handles.responses.next(+ matching: requestID, timeout: Self.conversationResetTimeout)+ }guard event.kind == .conversationReset else {throw AppInferenceError.unknown(event.error ?? "decode service refused to start a new conversation")}}+ /// Replays a stored conversation onto the service and waits for it to say+ /// the KV holds it.+ ///+ /// Bounded and cancellable like `resetConversation`, but on its own+ /// deadline: a reset drops a cache, while this one prefills a whole+ /// conversation — minutes at 8K on the reference Mac. Sharing the reset's+ /// timeout would abandon every large reopen as a hang.+ public func restoreConversation(+ _ lineage: AppConversationLineage,+ epoch: UUID,+ options: AppRuntimeOptions,+ maxContextTokens: Int,+ onPrefillProgress: @escaping @Sendable (Int, Int) -> Void+ ) async throws -> Int {+ guard let handles = currentHandles() else {+ // The service died while idle and the router tore the connection+ // down with nothing telling the window. Reported as a refused+ // replay this ended the held lineage and left the model advertised+ // as ready; as a lost connection it puts Retry Load on screen.+ throw AppInferenceError.connectionLost(+ "the decode service connection is gone")+ }+ let requestID = UUID()+ try write(.restoreConversation(DecodeRestoreConversationRequest(+ epoch: epoch,+ tokenIDs: lineage.tokenIDs,+ images: lineage.images.map {+ DecodeReplayImage(+ tokenLowerBound: $0.tokenLowerBound,+ tokenCount: $0.tokenCount,+ path: $0.fileURL.path,+ expectedDigest: $0.expectedDigest)+ },+ boundaryTokenIDs: lineage.boundaryTokenIDs,+ boundaryNeedsReplay: lineage.boundaryNeedsReplay,+ committedTurns: lineage.committedTurns,+ maxContextTokens: maxContextTokens,+ runtimeOptions: Self.decodeRuntimeOptions(options),+ requestID: requestID)), to: handles.input, expecting: handles.responses)+ while true {+ let event = try await transport(expecting: handles.responses) {+ try await handles.responses.next(+ matching: requestID, timeout: Self.conversationRestoreTimeout)+ }+ if let bytes = event.currentMemoryBytes {+ inferenceMemory.withLock { $0 = bytes }+ }+ switch event.kind {+ case .prefill:+ if let done = event.prefillDone, let total = event.prefillTotal {+ onPrefillProgress(done, total)+ }+ case .memory:+ continue+ case .conversationRestored:+ // The service's count, not the lineage's length. They agree when+ // the replay did what the record said, and when they do not it+ // is the KV that decides what the next turn resumes onto.+ guard let tokens = event.conversationTokenCount else {+ throw AppInferenceError.conversationRestoreFailed(+ "the decode service restored a conversation without saying "+ + "how many tokens it holds")+ }+ return tokens+ default:+ throw AppInferenceError.conversationRestoreFailed(+ event.error ?? "the decode service refused to reopen this chat")+ }+ }+ }+public func cancel() {guard let handles = currentHandles() else { return }try? write(.cancel, to: handles.input, expecting: handles.responses)}+ public func shutdownForTermination() {+ invalidateConnection()+ }+deinit {- let state = connection.withLock { value -> Connection in- defer { value = Connection() }- return value- }- if let input = state.input {- try? input.write(contentsOf: DecodeFrameCodec.encode(- DecodeServiceCommand.shutdown))- try? input.close()- }- state.responses?.closeStream()- if let label = state.launchLabel { Self.removeLaunchJob(label: label) }- if let socketPath = state.socketPath { unlink(socketPath) }+ invalidateConnection()}private func ensureProcess() throws-> (input: FileHandle, responses: DecodeServiceResponseRouter) {if let handles = currentHandles() { return handles }+ if let testConnection {+ let handles = try testConnection()+ let responses = makeRouter(output: handles.output)+ connection.withLock {+ $0.input = handles.input+ $0.responses = responses+ }+ return (handles.input, responses)+ }return try launchIndependentService()}@@ -452,6 +599,10 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,cachedPromptTokens: event.cachedPromptTokens,computedPrefillTokens: event.computedPrefillTokens,conversationTokens: event.conversationTokenCount,+ promptTokenIDs: event.promptTokenIDs,+ generatedTokenIDs: event.generatedTokenIDs,+ boundaryTokenIDs: event.boundaryTokenIDs,+ boundaryNeedsReplay: event.boundaryNeedsReplay,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 c494fbaf..5be50b2e 100644--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swift@@ -2,24 +2,62 @@ import Darwinimport Foundationimport TurboFieldfareDecodeProtocol+/// Why a wait for a decode-service event ended without one.+public enum DecodeServiceTransportError: Error, CustomStringConvertible {+ /// The service stopped answering while still connected: no frame of any+ /// kind arrived within the deadline. A closed socket surfaces as the+ /// reader's own error instead.+ case timedOut(seconds: Double)+ /// The connection is already known to be dead; a new one must be built.+ case connectionLost(underlying: String)++ public var description: String {+ switch self {+ case .timedOut(let seconds):+ "the decode service stopped responding after \(Int(seconds))s"+ case .connectionLost(let underlying):+ "the decode service connection is gone: \(underlying)"+ }+ }+}++/// Demultiplexes the service's event stream onto the callers waiting for it.+///+/// Every wait is bounded and cancellable. A blocking wait meant that a service+/// which stayed alive but stopped answering — its writer thread died, or a+/// command buffer wedged — left the app in `.running` forever with Cancel+/// inert, because nothing downstream could observe that no event was coming.final class DecodeServiceResponseRouter: @unchecked Sendable {- private struct State {- var pending: [UUID: [DecodeServiceEvent]] = [:]- var terminalError: Error?+ private struct Waiter {+ let requestID: UUID+ let continuation: CheckedContinuation<DecodeServiceEvent, Error>}- private let condition = NSCondition()- private var state = State()- private let output: FileHandle+ private let lock = NSLock()+ private var pending: [UUID: [DecodeServiceEvent]] = [:]+ private var waiters: [UUID: Waiter] = [:]+ private var terminalError: Error?+ /// Requests whose waiter gave up. Their later events are dropped rather+ /// than buffered: a request that was cancelled or timed out is never waited+ /// on again, so buffering its remaining events grew the map for the life of+ /// the connection.+ private var abandoned: [UUID] = []+ private static let abandonedMemory = 32++ /// Called once, off the reader thread, when the stream ends for any reason.+ /// The client uses it to tear the connection down rather than keep handing+ /// out handles that can only fail.private let onTerminate: @Sendable (DecodeServiceResponseRouter, Error) -> Void+ private let output: FileHandle+init(output: FileHandle,onTerminate: @escaping @Sendable (DecodeServiceResponseRouter, Error) -> Void= { _, _ in }) {- self.output = outputself.onTerminate = onTerminate+ self.output = outputlet reader = Thread { [weak self] inself?.readFrames(from: output)}@@ -28,59 +66,170 @@ final class DecodeServiceResponseRouter: @unchecked Sendable {reader.start()}- var isTerminated: Bool {- condition.lock()- defer { condition.unlock() }- return state.terminalError != nil- }-+ /// Closes the stream this router reads.+ ///+ /// The reader owns a `dup` of the socket, so closing the client's write+ /// handle does not wake it: against a service that is alive but no longer+ /// answering commands — the case the deadlines exist for — the thread would+ /// otherwise stay blocked in `read` for the life of the process, holding a+ /// descriptor nothing will ever close.func closeStream() {+ // `shutdown` first. Closing a descriptor another thread is already+ // blocked reading is unspecified by POSIX — measured here it does wake+ // the reader, but this is called precisely when a thread is parked in+ // `read`, and shutting the socket down removes the reliance. On a pipe+ // it fails with ENOTSOCK and costs nothing.shutdown(output.fileDescriptor, SHUT_RDWR)try? output.close()}- func next(matching requestID: UUID) async throws -> DecodeServiceEvent {- try await Task.detached(priority: .userInitiated) { [self] in- try waitForEvent(matching: requestID)- }.value+ /// True once the stream has ended. The connection cannot recover from this;+ /// only a new one can.+ var isTerminated: Bool {+ lock.lock()+ defer { lock.unlock() }+ return terminalError != nil+ }++ func next(matching requestID: UUID, timeout: Duration = .seconds(300)) async throws+ -> DecodeServiceEvent {+ let waiterID = UUID()+ let timeoutSeconds = Double(timeout.components.seconds)+ + Double(timeout.components.attoseconds) / 1e18+ // Scheduled by libdispatch rather than the cooperative pool: this+ // deadline exists precisely for the moments when the machine is+ // saturated, which is when a cooperative timer is starved worst.+ let deadline = DispatchSource.makeTimerSource(+ queue: DispatchQueue.global(qos: .utility))+ deadline.schedule(deadline: .now() + timeoutSeconds)+ deadline.setEventHandler { [self] in+ fail(waiterID, with: DecodeServiceTransportError.timedOut(+ seconds: timeoutSeconds))+ }+ deadline.resume()+ defer { deadline.cancel() }+ return try await withTaskCancellationHandler {+ try await withCheckedThrowingContinuation { continuation in+ register(Waiter(requestID: requestID, continuation: continuation),+ id: waiterID)+ }+ } onCancel: {+ self.fail(waiterID, with: CancellationError())+ }}- private func waitForEvent(matching requestID: UUID) throws -> DecodeServiceEvent {- condition.lock()- defer { condition.unlock() }- while state.pending[requestID]?.isEmpty != false,- state.terminalError == nil {- condition.wait()+ private func register(_ waiter: Waiter, id: UUID) {+ lock.lock()+ // Cancellation before the wait even starts. `withTaskCancellationHandler`+ // runs its handler immediately when the task is already cancelled, which+ // is before this call, so `fail` had nothing to find and the waiter+ // registered here would have sat until its deadline — 900 s on a load,+ // which is the hang this router exists to end. The same applies to a+ // cancel landing between the handler being installed and this lock.+ if Task.isCancelled {+ pending.removeValue(forKey: waiter.requestID)+ abandoned.append(waiter.requestID)+ if abandoned.count > Self.abandonedMemory { abandoned.removeFirst() }+ lock.unlock()+ waiter.continuation.resume(throwing: CancellationError())+ return}- if var events = state.pending[requestID], !events.isEmpty {+ // A frame that arrived before this call, or a stream that has already+ // ended, resolves the wait without it ever being stored.+ if var events = pending[waiter.requestID], !events.isEmpty {let event = events.removeFirst()if events.isEmpty {- state.pending.removeValue(forKey: requestID)+ pending.removeValue(forKey: waiter.requestID)+ } else {+ pending[waiter.requestID] = events+ }+ lock.unlock()+ waiter.continuation.resume(returning: event)+ return+ }+ if let terminalError {+ lock.unlock()+ waiter.continuation.resume(throwing: terminalError)+ return+ }+ waiters[id] = waiter+ lock.unlock()+ }++ /// Resolves a waiter that timed out or was cancelled. A waiter already+ /// resumed by an arriving frame is simply absent.+ private func fail(_ id: UUID, with error: Error) {+ lock.lock()+ let waiter = waiters.removeValue(forKey: id)+ if let waiter {+ pending.removeValue(forKey: waiter.requestID)+ abandoned.append(waiter.requestID)+ if abandoned.count > Self.abandonedMemory { abandoned.removeFirst() }+ }+ lock.unlock()+ waiter?.continuation.resume(throwing: error)+ }++ private func deliver(_ event: DecodeServiceEvent) {+ lock.lock()+ if let entry = waiters.first(where: { $0.value.requestID == event.generationID }) {+ waiters.removeValue(forKey: entry.key)+ lock.unlock()+ entry.value.continuation.resume(returning: event)+ return+ }+ guard !abandoned.contains(event.generationID) else {+ lock.unlock()+ return+ }+ pending[event.generationID, default: []].append(event)+ lock.unlock()+ }++ private func terminate(with error: Error) {+ lock.lock()+ guard terminalError == nil else {+ lock.unlock()+ return+ }+ terminalError = error+ // Events that arrived before the stream ended are still answers; a+ // service that replies and then exits is ordinary. Only waiters with+ // nothing buffered learn the connection is gone.+ var delivered: [(Waiter, DecodeServiceEvent)] = []+ var stranded: [Waiter] = []+ for waiter in waiters.values {+ if var events = pending[waiter.requestID], !events.isEmpty {+ let event = events.removeFirst()+ if events.isEmpty {+ pending.removeValue(forKey: waiter.requestID)+ } else {+ pending[waiter.requestID] = events+ }+ delivered.append((waiter, event))} else {- state.pending[requestID] = events+ stranded.append(waiter)}- return event}- throw state.terminalError ?? DecodeFrameError.unexpectedEOF+ waiters.removeAll()+ lock.unlock()+ for (waiter, event) in delivered {+ waiter.continuation.resume(returning: event)+ }+ for waiter in stranded {+ waiter.continuation.resume(throwing: error)+ }+ onTerminate(self, error)}private func readFrames(from output: FileHandle) {do {while true {- let event = try DecodeFrameCodec.read(- DecodeServiceEvent.self, from: output)- condition.lock()- state.pending[event.generationID, default: []].append(event)- condition.broadcast()- condition.unlock()+ deliver(try DecodeFrameCodec.read(+ DecodeServiceEvent.self, from: output))}} catch {- condition.lock()- let shouldNotify = state.terminalError == nil- if shouldNotify { state.terminalError = error }- condition.broadcast()- condition.unlock()- if shouldNotify { onTerminate(self, error) }+ terminate(with: error)}}}diff --git a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swiftindex 04aac32b..1c7c14af 100644--- a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift@@ -11,6 +11,8 @@ final class GenerationTaskRegistry: Sendable {private let state = Mutex<Entry?>(nil)+ var hasActiveGeneration: Bool { state.withLock { $0 != nil } }+func reserve(_ id: UUID) -> Bool {state.withLock { entry inguard entry == nil else { return false }@@ -100,6 +102,55 @@ public final class RealInferenceClient: AppModelLifecycleClient, @unchecked Sendawait session.resetConversation()}+ /// Replays a stored conversation into the KV and returns the token count it+ /// holds afterwards.+ ///+ /// `onProgress` receives the same `.prefill` events a live turn reports, so+ /// a reopen shows the progress a first turn would; the decode service+ /// forwards them and the app animates its gauge from them.+ /// In-process, so `epoch` has no gate to open and `maxContextTokens` is+ /// already fixed by the loaded runner; both are accepted and ignored, the+ /// same way `resetConversation(epoch:)` treats its epoch. The decode+ /// service holds the gate that uses them.+ public func restoreConversation(+ _ lineage: AppConversationLineage,+ epoch: UUID = UUID(),+ options: AppRuntimeOptions,+ maxContextTokens: Int = 0,+ onPrefillProgress: @escaping @Sendable (Int, Int) -> Void = { _, _ in }+ ) async throws -> Int {+ return try await session.restoreConversation(+ MultimodalConversationLineage(+ tokenIDs: lineage.tokenIDs,+ images: try lineage.images.map {+ // Bounded by the lineage before the range is built. Both+ // figures arrive over the socket in the service, and a+ // sign check alone let a pair near `Int.max` overflow the+ // addition and trap the process instead of failing the+ // restore. `lineage.tokenIDs.count - tokenLowerBound`+ // cannot overflow once the bound is non-negative.+ guard $0.tokenLowerBound >= 0, $0.tokenCount > 0,+ $0.tokenCount <= lineage.tokenIDs.count - $0.tokenLowerBound+ else {+ throw AppInferenceError.conversationRestoreFailed(+ "a stored image claims \($0.tokenCount) tokens at "+ + "offset \($0.tokenLowerBound) of a "+ + "\(lineage.tokenIDs.count)-token conversation")+ }+ return MultimodalReplayImage(+ tokenRange: $0.tokenLowerBound+ ..< ($0.tokenLowerBound + $0.tokenCount),+ pixelsURL: $0.fileURL,+ expectedDigest: $0.expectedDigest)+ },+ uncommittedBoundary: lineage.boundaryTokenIDs,+ boundaryNeedsReplay: lineage.boundaryNeedsReplay),+ options: options) { progress in+ guard case .prefill(let done, let total) = progress else { return }+ onPrefillProgress(done, total)+ }+ }+/// Whether a conversation is still open on the session.////// Exists so a test can assert that `unload()` released it. It cannot be@@ -261,6 +312,77 @@ actor RealInferenceSession {conversationTokens.withLock { $0 = 0 }}+ /// Rebuilds a stored conversation's KV and returns how many tokens it holds.+ ///+ /// Always onto a conversation of its own, never onto whatever was open: the+ /// caller has just reset, and restoring into a live lineage is refused+ /// downstream anyway. The returned count is read back from the conversation+ /// rather than from the request, so the gauge shows what the KV has and not+ /// what the caller hoped it would have.+ func restoreConversation(+ _ lineage: MultimodalConversationLineage,+ options: AppRuntimeOptions,+ onProgress: @escaping @Sendable (RawDecodeProgress) -> Void+ ) async throws -> Int {+ var prefillConfig = options.prefillConfig+ // A replay is a prefill and nothing else; with the app's prefill+ // toggle off it ran at decode speed and outlived the restore deadline.+ if let coerced = prefillConfig.coercedForReplay() {+ prefillConfig = coerced+ }+ // Image spans only run under chunked prefill, and the app's prefill+ // toggle can select `.off`. Coerce rather than refuse a conversation+ // the user can see: whether its images replay is not a performance+ // preference.+ if !lineage.images.isEmpty,+ let coerced = prefillConfig.coercedForImagePrompt() {+ prefillConfig = coerced+ }+ await resetConversation()+ let conversation = try conversationForRestore(options: options)+ do {+ try await conversation.restore(+ lineage: lineage,+ prefillConfig: prefillConfig,+ checkCancellation: { try Task.checkCancellation() },+ onProgress: onProgress)+ } catch let error as MultimodalConversationError {+ // A refused restore leaves the KV empty and this session usable, so+ // the conversation is dropped rather than kept as an inert one the+ // next turn would resume onto.+ self.conversation = nil+ runner?.reset()+ conversationTokens.withLock { $0 = 0 }+ throw AppInferenceError.conversationRestoreFailed("\(error)")+ }+ publishTowerBytes()+ let count = await conversation.kvTokenCount+ conversationTokens.withLock { $0 = count }+ return count+ }++ private func conversationForRestore(+ options: AppRuntimeOptions+ ) throws -> MultimodalConversation {+ guard let model, let ctx, let tokenizer, let runner, let scratch else {+ throw AppInferenceError.modelLoadFailed("session lost its loaded state")+ }+ runner.reset()+ // The same waiver `conversationForTurn` takes, for the same reason: one+ // conversation and one generation at a time is this session's+ // invariant, not the type system's.+ 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: options.visionResidencyPolicy,+ maxContext: runner.maxContext)+ conversation = created+ return created+ }+var hasConversation: Bool { conversation != nil }var currentConversationTokens: Int {@@ -515,6 +637,12 @@ actor RealInferenceSession {var cachedTokens: Int?var computedPrefillTokens: Int?var conversationTokens: Int?+ /// What the turn put into the KV. Nil on the single-prompt path, which+ /// keeps nothing and therefore has nothing to record.+ var promptTokenIDs: [Int32]?+ var generatedTokenIDs: [Int32]?+ var boundaryTokenIDs: [Int32]?+ var boundaryNeedsReplay: Bool?}/// The open conversation, or a new one on the same runner.@@ -605,7 +733,11 @@ actor RealInferenceSession {decodeSeconds: turn.decodeSeconds, newTokens: turn.completionTokens,cachedTokens: turn.cachedTokens,computedPrefillTokens: turn.computedPrefillTokens,- conversationTokens: turn.kvTokens)+ conversationTokens: turn.kvTokens,+ promptTokenIDs: turn.promptTokenIDs,+ generatedTokenIDs: turn.generatedTokenIDs,+ boundaryTokenIDs: turn.uncommittedBoundaryTokenIDs,+ boundaryNeedsReplay: turn.boundaryNeedsReplay)} 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@@ -615,13 +747,16 @@ actor RealInferenceSession {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:+ case .contextExhausted(let prompt, let reserve, let maxContext):+ // Not `contextOverflow`: that message names the user's max+ // response, and the guard that refused this turn does not look+ // at it. Reporting a figure the check never used is how a user+ // lowers their reply length and sees no change.+ throw AppInferenceError.conversationContextExhausted(+ prompt: prompt, reserve: reserve, maxContext: maxContext)+ case .imageUnavailable, .invalidReplayImage, .invalidReplayToken:throw AppInferenceError.invalidRequest("\(error)")- case .closed, .busy, .emptyTurn:+ case .closed, .busy, .emptyTurn, .lineageNotEmpty:throw AppInferenceError.unknown("\(error)")}}@@ -716,6 +851,7 @@ actor RealInferenceSession {cachedTokens: result.cachedTokens,computedPrefillTokens: result.computedPrefillTokens,conversationTokens: result.conversationTokens,+ turnRecord: result,prefill: prefillDiagnostics)continuation.yield(.finished(diagnostics))continuation.finish()@@ -783,7 +919,9 @@ actor RealInferenceSession {cachedTokens: Int? = nil,computedPrefillTokens: Int? = nil,conversationTokens: Int? = nil,- prefill: PrefillExecutionDiagnostics? = nil) -> AppDiagnostics {+ turnRecord: TurnOutcome? = nil,+ prefill: PrefillExecutionDiagnostics? = nil,+ errorDescription: String? = nil) -> AppDiagnostics {_ = memorySampler.sample()let ttft: Double?if let first = progress.firstTokenDate, let start = progress.decodeStart {@@ -798,6 +936,10 @@ actor RealInferenceSession {cachedPromptTokens: cachedTokens,computedPrefillTokens: computedPrefillTokens,conversationTokens: conversationTokens,+ promptTokenIDs: turnRecord?.promptTokenIDs,+ generatedTokenIDs: turnRecord?.generatedTokenIDs,+ boundaryTokenIDs: turnRecord?.boundaryTokenIDs,+ boundaryNeedsReplay: turnRecord?.boundaryNeedsReplay,prefillSeconds: prefillSeconds,timeToFirstTokenSeconds: ttft,decodeSeconds: decodeSeconds,diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelStorageMetrics.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelStorageMetrics.swiftnew file mode 100644index 00000000..1ea4853a--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelStorageMetrics.swift@@ -0,0 +1,36 @@+import Foundation++public struct AppModelStorageMetrics: Equatable, Sendable {+ public let logicalBytes: UInt64+ public let allocatedBytes: UInt64+ public let availableBytes: UInt64?++ public static func measure(at directory: URL) throws -> Self {+ let keys: Set<URLResourceKey> = [+ .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey,+ .totalFileAllocatedSizeKey,+ ]+ guard let enumerator = FileManager.default.enumerator(+ at: directory,+ includingPropertiesForKeys: Array(keys),+ options: [.skipsHiddenFiles]) else {+ throw CocoaError(.fileReadUnknown)+ }+ var logical: UInt64 = 0+ var allocated: UInt64 = 0+ for case let url as URL in enumerator {+ let values = try url.resourceValues(forKeys: keys)+ guard values.isRegularFile == true, values.isSymbolicLink != true else {+ continue+ }+ logical += UInt64(max(0, values.fileSize ?? 0))+ allocated += UInt64(max(0, values.totalFileAllocatedSize ?? 0))+ }+ let volume = try directory.deletingLastPathComponent().resourceValues(+ forKeys: [.volumeAvailableCapacityForImportantUsageKey])+ return Self(+ logicalBytes: logical,+ allocatedBytes: allocated,+ availableBytes: volume.volumeAvailableCapacityForImportantUsage.map(UInt64.init))+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Installation/VisionSectionVisibility.swift b/Sources/TurboFieldfareApp/Core/Installation/VisionSectionVisibility.swiftindex 47a6ff74..50bf5f28 100644--- a/Sources/TurboFieldfareApp/Core/Installation/VisionSectionVisibility.swift+++ b/Sources/TurboFieldfareApp/Core/Installation/VisionSectionVisibility.swift@@ -6,13 +6,13 @@ import Foundation/// only way to check it was to launch the app and look. It decides four distinct/// situations, so it is worth being able to test all four.public enum VisionSectionVisibility {- /// Shown while the section has something to say, hidden once it does not.+ /// Shown whenever this build exposes the vision runtime.////// An installed text model is deliberately *not* required. Requiring one hid/// image support behind a 14.62 GB download, so the screen where someone/// decides whether this app does what they need never mentioned that it- /// handles images at all. The section still collapses once the pack is- /// installed and healthy, so it costs space only while it is actionable.+ /// handles images at all. A healthy installed pack remains visible because+ /// its Remove action is part of the supported lifecycle.public static func shows(visionRuntimeEnabled: Bool,visionRuntimeSupported: Bool = true,@@ -21,14 +21,6 @@ public enum VisionSectionVisibility {isCompanionOperationInProgress: Bool,installState: AppModelInstallState) -> Bool {- guard visionRuntimeEnabled else { return false }- if !visionRuntimeSupported { return true }- if !isModelInstalled { return true }- if !isVisionPackInstalled { return true }- if isCompanionOperationInProgress { return true }- switch installState {- case .failed, .recoverable: return true- default: return false- }+ visionRuntimeEnabled}}diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swiftindex 29f48e31..e645f16e 100644--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift@@ -2,7 +2,6 @@ import Foundationimport Synchronizationimport TurboFieldfareimport TurboFieldfareRepackCore-import TurboFieldfareimport Observation@MainActor@@ -13,10 +12,23 @@ public final class AppModel {case running}+ /// How a turn ended.+ ///+ /// `committed` covers a reply that finished and a stop that landed at a+ /// token boundary: both are in the KV and on disk. `rewound` is a turn the+ /// runtime took back — a hard stop, a stream failure, a lost lineage — so+ /// it is in neither, and its message goes back to the composer. The cause+ /// is already in `error` by the time this is read.+ private enum TurnOutcome {+ case committed+ case rewound+ }+public var modelPathText: Stringpublic var promptText: String = ""- public private(set) var imageAttachments: [AppImageAttachment] = []+ public private(set) var imageAttachments: [StagedImage] = []public private(set) var imageAttachmentError: String?+ private var visionAvailabilityAttachmentError: String?/// A count, not a flag. The picker and a drop can both be staging at once,/// and whichever finished first cleared a shared Bool — reopening `canRun`/// while the other was still copying, so Generate ran against a partial set@@ -27,27 +39,32 @@ public final class AppModel {/// Set by the Model menu's Remove Image Support item; the window presents/// the confirmation.public var isConfirmingVisionPackRemoval = false- public private(set) var outputPromptText: String = ""- public private(set) var outputImageAttachments: [AppImageAttachment] = []+ public internal(set) var outputPromptText: String = ""+ /// The newest turn's pictures, as the transcript draws them. A live turn's+ /// are staged; a reopened conversation's newest pair is drawn from its+ /// document, whose pictures the conversation store owns.+ public internal(set) var outputImageAttachments: [ChatImage] = []/// 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)] = []+ public internal(set) var conversation = AppConversation()+ /// What the window is showing, and in what state. One value: the six+ /// fields it replaces could disagree, and twelve defects were two of them+ /// disagreeing.+ var machine = ConversationScreenMachine()+ public var screen: ConversationScreen { machine.screen }/// 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?+ var serviceEpoch: UUID?public var outputText: String = ""public var runState: RunState = .idlepublic var runtimeOptions = AppRuntimeOptions()public var maxNewTokensOverride: Int?- public var maxContextTokens: Int = 4096+ /// Settable only through `setMaxContextTokens`, because changing it changes+ /// which stored conversations can be continued — and what is on screen has+ /// to be redrawn from the answer that now applies, not the one taken when+ /// the row was clicked.+ public private(set) var maxContextTokens: Int = AppContextLengthOption.eightK.tokenspublic var temperature: Double = 0.2public var topKEnabled: Bool = truepublic var topK: Int = 64@@ -55,6 +72,12 @@ public final class AppModel {public var topP: Double = 0.95public private(set) var newlineShortcut: AppNewlineShortcut = .returnpublic private(set) var showPromptExamples: Bool = true+ /// Whether the list of chats is showing. Persisted, so the window comes+ /// back the way it was left.+ public private(set) var isSidebarVisible: Bool = true+ /// Whether the Inspector is showing. Persisted alongside the sidebar, for+ /// the same reason: the window comes back the way it was left.+ public private(set) var isInspectorVisible: Bool = true/// 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 = false@@ -70,7 +93,9 @@ public final class AppModel {public private(set) var visionInstallETAPresentation: DownloadETAPresentation = .hiddenpublic private(set) var visionInstallETAText: String?public private(set) var installReadiness: AppModelInstallReadiness = .checking- public private(set) var installationStatus: AppModelInstallationStatus+ public internal(set) var installationStatus: AppModelInstallationStatus+ public private(set) var modelStorageMetrics: AppModelStorageMetrics?+ public private(set) var modelStorageMetricsError: String?public var visionInstallState: AppModelInstallState = .idle/// How far activation's hash of the companion weights has got, 0 to 1./// Activation reads about 1.5 GB, which was a bare spinner with no way to@@ -81,11 +106,11 @@ public final class AppModel {public var loadState: AppModelLoadState = .notLoadedpublic private(set) var loadedRuntimeKey: AppLoadedRuntimeKey?- public private(set) var phase: AppGenerationPhase = .idle+ public internal(set) var phase: AppGenerationPhase = .idlepublic private(set) var liveTokenCount: Int = 0public private(set) var liveElapsedDecodeSeconds: Double = 0- public private(set) var livePrefillDone: Int = 0- public private(set) var livePrefillTotal: Int = 0+ public internal(set) var livePrefillDone: Int = 0+ public internal(set) var livePrefillTotal: Int = 0public private(set) var liveMemoryBytes: UInt64?/// Resident bytes of the inference process. The footprint above is what/// the system counts against the process; this is what it actually holds,@@ -104,10 +129,14 @@ public final class AppModel {/// looking at their own attachments while the model worked.public private(set) var runIdentity: Int = 0- private let client: any AppInferenceClient+ let client: any AppInferenceClientprivate let installer: any AppModelInstallerClientprivate let visionInstaller: any AppVisionPackInstallerClient- private var runTask: Task<Void, Never>?+ /// The message currently on its way through the send pipeline, from the+ /// click to the commit or the hand-back. `isTurnInFlight` reads it, so a+ /// second Generate is refused for the whole journey and not only while the+ /// runtime is generating.+ private var sendTask: Task<Void, Never>?private var loadTask: Task<Void, Never>?private var installTask: Task<Void, Never>?private var visionInstallTask: Task<Void, Never>?@@ -126,14 +155,56 @@ public final class AppModel {private var pendingExplicitLoadRuntimeKey: AppLoadedRuntimeKey?private var activeRunRuntimeKey: AppLoadedRuntimeKey?private var hasHandledTerminalEvent = false+ private var hasShutDownForTermination = false+ /// What the generation stage left behind, read by the stage that decides+ /// whether the message is committed or goes back to the composer.+ private var turnOutcome: TurnOutcome = .committed+ /// The send waiting for its turn to end, with the run it belongs to.+ private var turnCompletion:+ (generation: Int, continuation: CheckedContinuation<Void, Never>)?private let memorySampler: AppMemorySampler- private let settingsPersistenceEnabled: Bool+ let settingsPersistenceEnabled: Boolprivate let installETAClock: SuspendingClockprivate let installETAOrigin: SuspendingClock.Instantprivate var installETAEstimator = DownloadETAEstimator()private var visionInstallETAEstimator = DownloadETAEstimator()- private let attachmentStore: AppImageAttachmentStore+ /// Internal rather than private: the history extension releases the staged+ /// copies of a conversation the KV is giving up, and lives in another file.+ let attachmentStore: AppImageAttachmentStorepublic let isVisionRuntimeSupported: Bool+ /// The stored conversations and which one is open.+ public let history = ConversationHistoryState()+ /// Nil when history is off for this instance — the tests that drive the+ /// model without a disk do exactly that, and so does a run with settings+ /// persistence disabled, which is the same "do not touch the user's files"+ /// switch.+ var conversationBinding: ConversationStoreBinding?+ var conversationStore: ConversationStore? { conversationBinding?.store }+ /// The directory the open chat is being written to. Created on the first+ /// send rather than at New Chat, so an empty chat never lands on disk.+ var storedConversationID: UUID?+ /// Read from the installed model's manifest, because the app process never+ /// loads the model. Nil until a model is installed.+ var conversationIdentity: ConversationIdentity? {+ get { conversationBinding?.identity }+ set { conversationBinding?.identity = newValue }+ }+ var conversationBindingGeneration: UInt64 = 0+ let conversationIdentityProvider: @Sendable (URL) throws -> ConversationIdentity+ let conversationStoreProvider: @Sendable (URL) -> ConversationStore+ var pendingRestoredConversationID: UUID?+ var pendingServiceRecoveryConversationID: UUID?+ /// Stored copies of the in-flight turn's images, written while the model is+ /// generating so the wait is not paid twice.+ var pendingTurnImageWrite: Task<TurnImageWriteOutcome, Never>?+ var persistenceTail: Task<Void, Never>?+ /// Reserves deletion across the persistence wait and the store actor hop.+ var conversationDeletionTask: Task<Void, Never>?+ var quarantinedPersistenceLineages: Set<PersistenceLineageKey> = []+ /// Why the store last refused to do something. Names, counts and paths+ /// only: a diagnostic carrying transcript text would put the user's+ /// conversation wherever this is collected.+ public internal(set) var historyDiagnostic: String?public static var currentDeviceSupportsVisionRuntime: Bool {VisionRuntime.isSupportedOnDefaultDevice@@ -146,7 +217,13 @@ public final class AppModel {memorySampler: AppMemorySampler = AppMemorySampler(),attachmentStore: AppImageAttachmentStore = AppImageAttachmentStore(),visionRuntimeSupported: Bool = true,- settingsPersistenceEnabled: Bool = false) {+ settingsPersistenceEnabled: Bool = false,+ conversationIdentityProvider: @escaping @Sendable (URL) throws -> ConversationIdentity = {+ try ConversationIdentity.forModelDirectory($0)+ },+ conversationStoreProvider: @escaping @Sendable (URL) -> ConversationStore = {+ ConversationStore(rootURL: $0)+ }) {let directory = (modelDirectory ?? AppModelLocation.defaultURL()).standardizedFileURLlet installETAClock = SuspendingClock()let settings = settingsPersistenceEnabled@@ -172,7 +249,10 @@ public final class AppModel {self.topP = settings.topPself.newlineShortcut = settings.newlineShortcutself.showPromptExamples = settings.showPromptExamples+ self.isSidebarVisible = settings.sidebarVisible+ self.isInspectorVisible = settings.inspectorVisibleself.loadModelOnLaunch = settings.loadModelOnLaunch+ self.pendingRestoredConversationID = settings.selectedConversationIDself.installationStatus = AppModelInstallationProbe.status(at: directory)self.visionInstallationStatus = AppVisionPackInstallationProbe.status(at: directory)self.client = client@@ -182,13 +262,39 @@ public final class AppModel {self.attachmentStore = attachmentStoreself.isVisionRuntimeSupported = visionRuntimeSupportedself.settingsPersistenceEnabled = settingsPersistenceEnabled+ self.conversationIdentityProvider = conversationIdentityProvider+ self.conversationStoreProvider = conversationStoreProviderself.installETAClock = installETAClockself.installETAOrigin = installETAClock.now+ // History follows the same switch as settings: a model driven by tests+ // must not write to the user's Application Support directory.+ if settingsPersistenceEnabled {+ conversationBindingGeneration = 1+ let identity: ConversationIdentity?+ if installationStatus == .complete {+ do {+ identity = try conversationIdentityProvider(directory)+ } catch {+ identity = nil+ historyDiagnostic = "the installed model identity could not be read: \(error)"+ }+ } else {+ identity = nil+ }+ conversationBinding = ConversationStoreBinding(+ modelDirectory: directory,+ identity: identity,+ generation: conversationBindingGeneration,+ storeProvider: conversationStoreProvider)+ } else {+ conversationBinding = nil+ }// Staged images of runs that were killed before they could clean up;// nothing else ever removes them.AppImageAttachmentStore.sweepAbandoned()refreshInstallReadiness()refreshVisionInstallReadiness()+ activateConversationStore()}public var isRunning: Bool { runState == .running }@@ -200,8 +306,13 @@ public final class AppModel {return loadedRuntimeKey != currentRuntimeKey}+ // The three lifecycle actions gate on the whole send, not on `isRunning`:+ // a deferred replay is a full prefill during which no turn is generating+ // yet, and an unload taken then dropped the KV under the replay, lost the+ // message it was carrying, and queued behind the prefill on the service+ // until the load timeout killed the connection.public var canLoadModel: Bool {- isModelInstalled && !isRunning && !isVisionCompanionOperationInProgress+ isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress&& (loadState == .notLoaded || loadState.isFailed)}@@ -211,12 +322,12 @@ public final class AppModel {}public var canReloadModel: Bool {- isModelInstalled && !isRunning && !isVisionCompanionOperationInProgress+ isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress&& loadState.isReady && hasStaleLoadedRuntime}public var canUnloadModel: Bool {- isModelInstalled && !isRunning && !isVisionCompanionOperationInProgress+ isModelInstalled && !isTurnInFlight && !isVisionFilesystemMutationInProgress&& loadState.isReady}@@ -249,22 +360,30 @@ public final class AppModel {visionInstaller.descriptor}- /// Every companion Download, Resume, Verify, Activate, Repair, and Remove- /// operation is one app-blocking state: model actions stay disabled until it- /// reaches a resting state, so a companion transaction never overlaps a- /// loaded session or another companion operation.+ /// Any companion operation currently owns the installer transaction.public var isVisionCompanionOperationInProgress: Bool {visionInstallState.isInstalling}- /// A companion operation may only begin against an unloaded model session- /// with no other transfer in flight; the draft, transcript, and attachments- /// are untouched by the gate.+ public var isVisionFilesystemMutationInProgress: Bool {+ switch visionInstallState {+ case .activating, .discarding: return true+ default: return false+ }+ }++ /// Pack activation, repair and removal mutate the runtime's files and need+ /// an unloaded model. Payload download does not use this gate.public var canBeginVisionCompanionOperation: Bool {!isRunning && !loadState.isLoading && !loadState.isReady&& !isInstallingModel && !isVisionCompanionOperationInProgress}+ private var canBeginVisionDownload: Bool {+ !isRunning && !loadState.isLoading && !isInstallingModel+ && !isVisionCompanionOperationInProgress+ }+public var canInstallVisionPack: Bool {guard isVisionRuntimeSupported else { return false }// A layout with nowhere to put a companion cannot be repaired by@@ -273,7 +392,7 @@ public final class AppModel {guard isModelInstalled, !isVisionPackInstalled,case .ready = visionInstallReadiness else { return false }if case .readyToActivate = visionInstallState { return false }- return canBeginVisionCompanionOperation+ return canBeginVisionDownload}public var canActivateVisionPack: Bool {@@ -387,23 +506,63 @@ public final class AppModel {// Staging copies the files a request will carry. Starting a run while// it is in flight sent a request without those images and then landed// them on the next message instead.- !isRunning && !isAddingImages && isModelAvailable && !loadState.isLoading- && !isVisionCompanionOperationInProgress+ // A deferred replay is not `isRunning` — no turn is generating yet —+ // but the message has been sent and the lineage it will be stamped+ // against does not exist yet. Without this a second Generate started a+ // second replay, and whichever finished last defined the epoch, so the+ // first one's request came back rejected as belonging to a conversation+ // that was no longer open.+ !isTurnInFlight && conversationDeletionTask == nil+ && !isAddingImages && isModelAvailable && !loadState.isLoading+ && !isVisionFilesystemMutationInProgress&& !hasStaleLoadedRuntime// A conversation whose KV no longer matches it cannot take another// turn; only New chat clears that.&& conversation.canSend+ // And the conversation on screen has to be one a message can go+ // to. The live one always is; a stored row only when the notice+ // says it can be continued. Asking only `conversation.canSend`+ // let a row the notice had refused be sent anyway.+ && screen.allowsSend&& (!promptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty|| !imageAttachments.isEmpty)+ && (imageAttachments.isEmpty || isImageInputAvailable)}public var canCancel: Bool { isRunning && !isCancellationPending }+ /// The message has been sent and nothing has come back yet.+ ///+ /// Wider than `isRunning`, which covers only a generation: a reopened+ /// conversation has to be replayed into the KV first, and that is a full+ /// prefill of everything it holds. For the length of it the window showed a+ /// composer that had been emptied and a transcript that had not changed, so+ /// the app looked like it had dropped the message.+ public var isTurnInFlight: Bool {+ isRunning || screen.isReplaying || sendTask != nil+ }++ /// Activity whose prompt/output has been published to the transcript.+ /// A queued send owns the composer before replacing the previous answer.+ public var isTranscriptTurnInFlight: Bool {+ isRunning || screen.isReplaying+ }+public var hasOutputTranscript: Bool {- !archivedPairs.isEmpty- || !conversation.isEmpty- || !outputPromptText.isEmpty || !outputImageAttachments.isEmpty- || !outputText.isEmpty+ // Same split as `transcriptHistory`: while a stored copy is on screen,+ // the live conversation belongs to another chat and is not what decides+ // whether this one has anything to show. A stored chat with no readable+ // turns has to fall through to the empty state rather than borrow the+ // held conversation's.+ switch screen {+ case .reading, .replaying:+ return !transcriptHistory.isEmpty+ case .live, .unreadable:+ return !conversation.outOfContextPairs.isEmpty+ || !conversation.isEmpty+ || !outputPromptText.isEmpty || !outputImageAttachments.isEmpty+ || !outputText.isEmpty+ }}public var shouldShowPromptExamples: Bool {@@ -414,7 +573,14 @@ public final class AppModel {}public var outputResponsePlainText: String {- generationTranscriptMailbox?.completeText ?? outputText+ // The mailbox wins only when it has something to say. `??` alone fell+ // back to `outputText` when the mailbox was *absent*, never when it was+ // merely empty — so a reopened conversation, whose newest reply is put+ // straight into `outputText` with the mailbox freshly reset, drew an+ // "Answer" heading with nothing under it. During a run the two agree,+ // and a genuinely empty reply is empty either way.+ let streamed = generationTranscriptMailbox?.completeText ?? ""+ return streamed.isEmpty ? outputText : streamed}/// Completed turns the transcript draws *above* the live one.@@ -424,18 +590,84 @@ public final class AppModel {/// 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.+ /// The chat on screen is not the one the KV is holding.+ public var isShowingStoredCopy: Bool { screen.isShowingStoredCopy }++ /// The state of the conversation on screen. `.continuable` for a live chat+ /// and for one being replayed; the other two say why the composer is+ /// closed.+ public var openedConversationState: ConversationContinuability {+ switch screen {+ case .live, .replaying:+ return .continuable+ case .reading(_, _, let state, _):+ return state+ case .unreadable:+ // Nothing to put back and nothing to read: the same dead end as a+ // record with no tokens, and the notice says the same thing.+ return .cannotReplay(reason: .tokenCountUnknown)+ }+ }++ /// Whether the live fields belong under what is on screen.+ ///+ /// While a stored copy is merely being read they do not: they hold the chat+ /// the KV is keeping, which is a different conversation. But a send starts+ /// by replaying the chat being read, and for that stretch the live fields+ /// hold the message that started it — so suppressing them there drew an+ /// "Answer / Processing your prompt" with no question above it.+ public var showsLiveTurn: Bool { isTranscriptTurnInFlight || !isShowingStoredCopy }++ /// What the transcript is drawing, as an identity the incremental renderer+ /// can key on.+ ///+ /// The renderer appends and cannot take pairs back, so it has to be told+ /// when the thing on screen is a different conversation. The live+ /// conversation's epoch used to be enough because every open started a new+ /// one; now that browsing leaves the lineage alone, going out to a stored+ /// copy and back would be two changes the epoch cannot express, and the+ /// chat that was read stayed on screen under the row that was returned to.+ public var displayedTranscriptID: UUID {+ switch screen {+ case .live, .unreadable:+ return conversation.epoch+ case .reading(_, _, _, let renderID):+ return renderID+ case .replaying(_, _, _, let renderID):+ return renderID+ }+ }+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+ // A stored conversation draws in full: its pairs are not+ // `completedPairs`, so none of them is being held back for the live+ // fields to draw — and the live conversation belongs to another chat.+ switch screen {+ case .reading, .replaying:+ return screen.document?.pairs ?? []+ case .live, .unreadable:+ let pairs = conversation.completedPairs+ let live = conversation.hasTurnInFlight ? pairs+ : (pairs.isEmpty ? pairs : Array(pairs.dropLast()))+ return conversation.outOfContextPairs + 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.+ ///+ /// A fact about the live conversation, so it is drawn only under one: a+ /// stored copy read off disk is not in the model's context at all, and a+ /// rule under every turn of it says nothing a reader can act on.public var transcriptContextBreak: Int? {- archivedPairs.isEmpty ? nil : archivedPairs.count+ switch screen {+ case .reading, .replaying:+ return nil+ case .live, .unreadable:+ return conversation.outOfContextPairs.isEmpty+ ? nil : conversation.outOfContextPairs.count+ }}public var outputConversationPlainText: String {@@ -480,13 +712,13 @@ public final class AppModel {installReadiness: installReadiness,loadState: loadState,hasStaleRuntime: hasStaleLoadedRuntime,- isRunning: isRunning,+ isRunning: isTurnInFlight,isGenerationCancellationPending: isCancellationPending,generationPhase: phase,livePrefillDone: livePrefillDone,livePrefillTotal: livePrefillTotal,lastStopReason: diagnostics?.stopReason,- isVisionCompanionOperationInProgress: isVisionCompanionOperationInProgress))+ isVisionFilesystemMutationInProgress: isVisionFilesystemMutationInProgress))}public var currentProcessMemoryBytes: UInt64? {@@ -521,7 +753,9 @@ public final class AppModel {}public func setModelURL(_ url: URL) {- guard !isRunning else { return }+ // Rebinding replaces the screen machine outright, so a replay in+ // flight would lose the message it is carrying.+ guard !isTurnInFlight else { return }let path = url.standardizedFileURL.pathguard path != modelPathText else { return }@@ -557,6 +791,9 @@ public final class AppModel {at: URL(fileURLWithPath: path))refreshInstallReadiness()refreshVisionInstallReadiness()+ replaceConversationBinding(+ for: URL(fileURLWithPath: path, isDirectory: true),+ reason: "the model location changed")if let lifecycle = client as? AppModelLifecycleClient {unloadGeneration &+= 1@@ -597,6 +834,83 @@ public final class AppModel {persistSettings()}+ /// Changes the context, and redraws a stored conversation against it.+ ///+ /// Continuability is a function of the conversation's size and the context+ /// in force, and the window took its answer once, when the row was clicked.+ /// So raising the context from the notice left the chat continuable but+ /// still drawn read-only, under a boundary rule saying earlier turns were+ /// out of context when they no longer were. Re-opening rebuilds it from the+ /// state that now applies, in both directions.+ public func setMaxContextTokens(_ tokens: Int) {+ guard maxContextTokens != tokens else { return }+ maxContextTokens = tokens+ persistSettings()+ guard !isRunning, !screen.isReplaying,+ let id = screen.conversationID,+ let meta = history.entry(id) else { return }+ perform(machine.apply(.contextChanged(+ state: continuability(of: meta),+ heldID: storedConversationID,+ kvMatchesHeld: serviceEpoch == conversation.epoch,+ renderID: UUID())))+ }++ public func setSidebarVisible(_ visible: Bool) {+ guard isSidebarVisible != visible else { return }+ isSidebarVisible = visible+ persistSettings()+ }++ /// One action behind the strip button, the View menu item and its+ /// shortcut, so the three cannot disagree about what "shown" means.+ public func toggleSidebar() {+ setSidebarVisible(!isSidebarVisible)+ }++ /// Retries the writer lock a second window could not take at launch.+ ///+ /// `isReadOnly` was decided once, when the store was activated, so a window+ /// that opened while another held the lock said "this one can read them but+ /// not change them" for the rest of its life — including long after the+ /// other one had quit. Becoming the frontmost window is exactly when that+ /// is worth asking again: it is what the user does after closing the other+ /// copy.+ public func reacquireStoreIfPossible() {+ guard history.isReadOnlyStore, let store = conversationStore else { return }+ Task { [weak self] in+ // Nil is the ordinary answer — another window is open — and anything+ // else is a fault this one can act on. Discarded, a store that could+ // not be locked for any other reason read as "another instance holds+ // it" for the rest of the session.+ if let reason = await store.retryLock() {+ self?.recordHistoryDiagnostic(+ "the conversation store could not be locked for writing: "+ + reason)+ }+ await self?.refreshHistory()+ }+ }++ public func setInspectorVisible(_ visible: Bool) {+ guard isInspectorVisible != visible else { return }+ isInspectorVisible = visible+ persistSettings()+ }++ public func toggleInspector() {+ setInspectorVisible(!isInspectorVisible)+ }++ /// Whether New Chat can run right now.+ ///+ /// The same guard `newChat()` already has, made askable so the button and+ /// the menu item can be disabled rather than silently doing nothing, plus+ /// the installer: there is no chat to start before a model exists.+ public var canStartNewChat: Bool {+ !isTurnInFlight && !requiresModelInstallation+ }+public func setLoadModelOnLaunch(_ enabled: Bool) {guard loadModelOnLaunch != enabled else { return }@@ -654,9 +968,13 @@ public final class AppModel {conversationTokens: Int?) -> Int {guard let conversationTokens else { return 0 }+ // The reply's reserve too: `generate` refuses a prompt that leaves+ // less than it free, after every image has been encoded on the GPU.+ // Without it the composer offered image sets the turn then refused.return VisionImageTokenBudget.capacity(maxContext: maxContextTokens,- reservedTextTokens: max(reservedPromptTokens, conversationTokens))+ reservedTextTokens: max(reservedPromptTokens, conversationTokens)+ + ConversationGenerationReserve.tokens)}/// The context a generation would run with right now.@@ -669,6 +987,7 @@ public final class AppModel {/// takes its own copy — so it must not outlive the staging that consumed/// it, which is exactly how it leaked.public func addImages(_ urls: [URL], discardingSourceDirectory: URL? = nil) {+ recheckVisionPackAtCurrentLocation()// Every early return has to discard the promise directory itself. The// staging task's `defer` below owns it only once that task exists, so a// return above it strands the full-size copies with nothing left to@@ -679,10 +998,17 @@ public final class AppModel {}}guard isImageInputAvailable, !urls.isEmpty else {+ if !isImageInputAvailable {+ recordVisionAvailabilityError(+ at: URL(fileURLWithPath: modelPathText, isDirectory: true))+ }discardSource()return}- guard !isRunning else {+ // The whole send, not just the generation: a picture attached during+ // a deferred replay met `restoreComposer`'s draft-wins rule when the+ // replay failed, which deleted the sent message's own pictures.+ guard !isTurnInFlight else {// A promise drop admitted before the run started can be delivered// after it. Returning silently made the images look as though they// had simply vanished.@@ -708,9 +1034,8 @@ public final class AppModel {imageAttachmentError = Self.imageCapacityMessage(capacity: capacity, context: effectiveMaxContextTokens)}- let store = attachmentStore- Task.detached(priority: .userInitiated) { [weak self] in- var staged: [AppImageAttachment] = []+ Task.detached(priority: .userInitiated) { [weak self, attachmentStore] in+ var staged: [StagedImage] = []defer {if let discardingSourceDirectory {try? FileManager.default.removeItem(at: discardingSourceDirectory)@@ -718,13 +1043,13 @@ public final class AppModel {}do {for url in selected {- staged.append(try store.stage(url))+ staged.append(try attachmentStore.stage(url))}await self?.finishAddingImages(staged)} catch {// The batch is all-or-nothing, so the copies made before the// failure are referenced by nothing and would never be deleted.- for attachment in staged { store.remove(attachment) }+ for attachment in staged { attachmentStore.remove(attachment) }await self?.finishAddingImages(error: error)}}@@ -734,7 +1059,17 @@ public final class AppModel {/// of another app arrives on the pasteboard as data, and a drag from an app/// that has not written the file yet arrives as a promise.public func addImageData(_ data: Data, displayName: String) {- guard isImageInputAvailable, !isRunning else { return }+ recheckVisionPackAtCurrentLocation()+ guard isImageInputAvailable else {+ recordVisionAvailabilityError(+ at: URL(fileURLWithPath: modelPathText, isDirectory: true))+ return+ }+ guard !isTurnInFlight else {+ imageAttachmentError =+ "Wait for the current run to finish before attaching images."+ return+ }let capacity = maximumImageAttachmentsguard imageAttachments.count < capacity else {imageAttachmentError = Self.imageCapacityMessage(@@ -743,10 +1078,10 @@ public final class AppModel {}addingImagesCount += 1imageAttachmentError = nil- let store = attachmentStore- Task.detached(priority: .userInitiated) { [weak self] in+ Task.detached(priority: .userInitiated) { [weak self, attachmentStore] indo {- let staged = try store.stage(data: data, displayName: displayName)+ let staged = try attachmentStore.stage(+ data: data, displayName: displayName)await self?.finishAddingImages([staged])} catch {await self?.finishAddingImages(error: error)@@ -769,21 +1104,30 @@ public final class AppModel {}public func removeImage(id: UUID) {- guard !isRunning,+ guard !isTurnInFlight,let index = imageAttachments.firstIndex(where: { $0.id == id }) else { return }let attachment = imageAttachments.remove(at: index)attachmentStore.remove(attachment)imageAttachmentError = nil}+ /// Puts the composer in the state a completed pick leaves it in.+ ///+ /// `addImages` needs a verifiable companion pack to reach its staging path,+ /// which no unit test has, and the lifetime rules around these files are+ /// exactly what needs covering.+ func setComposerAttachmentsForTesting(_ attachments: [StagedImage]) {+ imageAttachments = attachments+ }+public func clearImages() {- guard !isRunning else { return }+ guard !isTurnInFlight else { return }for attachment in imageAttachments { attachmentStore.remove(attachment) }imageAttachments.removeAll()imageAttachmentError = nil}- private func finishAddingImages(_ staged: [AppImageAttachment]) {+ private func finishAddingImages(_ staged: [StagedImage]) {// Two adds can be in flight at once — the picker and a drop — and each// sized itself against the count it saw at admission, so the second to// land can push past the cap. Re-check against the real count here and@@ -909,7 +1253,7 @@ public final class AppModel {/// directly. Calling this from those sites is what actually runs it.private func endConversationForReleasedKV() {serviceEpoch = nil- archiveConversationContext()+ presentStoredConversationAfterReleasedKV()}public func unloadModel() {@@ -1187,10 +1531,24 @@ public final class AppModel {refreshVisionInstallReadiness(at: directory)}+ public func recheckVisionPackAtCurrentLocation() {+ refreshVisionInstallReadiness(+ at: URL(fileURLWithPath: modelPathText, isDirectory: true)+ .standardizedFileURL)+ }+private func refreshInstallReadiness(at outputDirectory: URL) {installationStatus = AppModelInstallationProbe.status(at: outputDirectory,descriptor: installer.descriptor)+ do {+ modelStorageMetrics = FileManager.default.fileExists(atPath: outputDirectory.path)+ ? try AppModelStorageMetrics.measure(at: outputDirectory) : nil+ modelStorageMetricsError = nil+ } catch {+ modelStorageMetrics = nil+ modelStorageMetricsError = "installed storage could not be measured: \(error)"+ }guard !isModelInstalled else { return }installReadiness = .checkingdo {@@ -1213,21 +1571,20 @@ public final class AppModel {private func refreshVisionInstallReadiness(at textModelDirectory: URL) {visionInstallationStatus = AppVisionPackInstallationProbe.status(at: textModelDirectory)- // Removing the companion leaves any attached image unsendable, and the- // composer would keep offering it with nothing able to encode it.+ // Removing the companion leaves any attached image unsendable. Keep the+ // draft intact and refuse the send until the reproducibility input is+ // present again.// Only once the dust has settled: the probe verifies the pack on disk,// and a companion operation renames that directory underneath it, so// refreshing mid-operation can briefly report no image support. Acting// on that would delete images the user had staged.if !isImageInputAvailable, !isVisionCompanionOperationInProgress,!imageAttachments.isEmpty {- for attachment in imageAttachments { attachmentStore.remove(attachment) }- imageAttachments.removeAll()- // Say so. Clearing the error alongside the images removed them and- // the only explanation for their absence in one step, so the- // composer just quietly emptied itself.- imageAttachmentError =- "Image support is unavailable, so the attached images were removed."+ recordVisionAvailabilityError(at: textModelDirectory)+ } else if isImageInputAvailable,+ imageAttachmentError == visionAvailabilityAttachmentError {+ imageAttachmentError = nil+ visionAvailabilityAttachmentError = nil}guard isModelInstalled else {visionInstallReadiness = .failed("Install the text model first")@@ -1263,6 +1620,33 @@ public final class AppModel {}}+ private func recordVisionAvailabilityError(at textModelDirectory: URL) {+ let location: String+ do {+ location = try VisionPackLocation.companionURL(+ forTextModel: textModelDirectory).path+ } catch {+ location = "an unresolved companion path (\(error))"+ }+ let cause: String+ switch visionInstallationStatus {+ case .missing:+ cause = "the companion pack is missing"+ case .partial(let detail):+ cause = "the companion pack is incomplete: \(detail)"+ case .unsupportedLayout:+ cause = "this text-model layout cannot host a companion pack"+ case .complete:+ cause = isVisionRuntimeSupported+ ? "the companion pack is unavailable"+ : "image inference is unsupported on this device"+ }+ let message = "Image support is unavailable at \(location): \(cause). "+ + "Restore the companion pack before sending."+ visionAvailabilityAttachmentError = message+ imageAttachmentError = message+ }+private func applyVisionInstallEvent(_ event: AppModelInstallEvent,generation: UInt64@@ -1464,6 +1848,9 @@ public final class AppModel {loadState = .notLoadedendConversationForReleasedKV()refreshVisionInstallReadiness(at: directory)+ replaceConversationBinding(+ for: directory,+ reason: "the model installation completed")}}@@ -1561,10 +1948,13 @@ public final class AppModel {topP = settings.topPnewlineShortcut = settings.newlineShortcutshowPromptExamples = settings.showPromptExamples+ isSidebarVisible = settings.sidebarVisible+ isInspectorVisible = settings.inspectorVisibleloadModelOnLaunch = settings.loadModelOnLaunch+ pendingRestoredConversationID = settings.selectedConversationID}- private func persistSettings() {+ func persistSettings() {guard settingsPersistenceEnabled else { return }let settings = MacAppSettings(contextTokens: maxContextTokens,@@ -1577,13 +1967,19 @@ public final class AppModel {prefillEnabled: runtimeOptions.prefillEnabled,newlineShortcut: newlineShortcut,showPromptExamples: showPromptExamples,+ sidebarVisible: isSidebarVisible,+ inspectorVisible: isInspectorVisible,visionResidencyPolicy: runtimeOptions.visionResidencyPolicy,rdadvisePolicy: runtimeOptions.rdadvisePolicy,- loadModelOnLaunch: loadModelOnLaunch)+ loadModelOnLaunch: loadModelOnLaunch,+ selectedConversationID: history.selection)let modelDirectory = URL(fileURLWithPath: modelPathText, isDirectory: true)- try? MacAppSettingsFileStore.save(- settings,- forModelDirectory: modelDirectory)+ do {+ try MacAppSettingsFileStore.save(settings, forModelDirectory: modelDirectory)+ } catch {+ FileHandle.standardError.write(Data(+ "Saving Mac app settings failed: \(error)\n".utf8))+ }}private func finishInstallFailure(_ error: Error, generation: UInt64) {@@ -1651,13 +2047,35 @@ public final class AppModel {// 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.+ let isAlreadyWaitingForReplay = serviceEpoch == nil+ && storedConversationID != nil+ && screen.conversationID == storedConversationIDserviceEpoch = 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()+ if let id = pendingServiceRecoveryConversationID,+ screen.conversationID == id,+ storedConversationID == id {+ prepareServiceRecoveryForReplay()+ pendingServiceRecoveryConversationID = nil+ } else if let id = pendingServiceRecoveryConversationID,+ screen.conversationID == id {+ // A replay lost the service with this row on screen and its+ // message handed back; the failed replay already ended the+ // held lineage. The row stays for the send that follows Retry+ // Load. Archived instead, its selection went and the retried+ // message opened a brand-new chat.+ pendingServiceRecoveryConversationID = nil+ } else if isAlreadyWaitingForReplay {+ // An explicit unload already put the durable row on screen.+ // Loading the new runner must not archive that row a second+ // time or clear the selection before its deferred replay.+ } else {+ presentStoredConversationAfterReleasedKV()+ }loadedRuntimeKey = pendingExplicitLoadRuntimeKey?? activeRunRuntimeKey?? currentRuntimeKey@@ -1672,31 +2090,15 @@ 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 = []- }-/// Deletes every file this session staged. Called when the app is quitting,/// which is the only moment they are all certainly unwanted.+ ///+ /// The whole staging directory at once rather than picture by picture: a+ /// release that walks the window's own references can only free what the+ /// window still remembers, and quitting frees the rest as well.public func releaseAllAttachments() {- releaseConversationImages()- for attachment in imageAttachments { attachmentStore.remove(attachment) }imageAttachments.removeAll()+ outputImageAttachments = []attachmentStore.removeAll()}@@ -1737,19 +2139,36 @@ public final class AppModel {/// 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.+ /// No confirmation any more: the conversation being left is already on+ /// disk, turn by turn, and one click in the sidebar brings it back. An+ /// alert for something that is not lost is an alert for nothing.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()+ // Refused during a replay as well as during a generation. The replay is+ // putting a conversation into the KV for a turn that has already been+ // sent; starting an empty chat under it left the window on the new chat+ // and the model on the old one, and whichever landed last defined what+ // the next turn was numbered against.+ guard !isTurnInFlight else { return }+ quarantinedPersistenceLineages.removeAll()+ pendingServiceRecoveryConversationID = nil+ // The empty chat is not written until its first send, so it takes no+ // row in the sidebar and the previous conversation stops being the one+ // this window is appending to.+ storedConversationID = nil+ // Every turn holds its own hard links, and dropping the turn list+ // without releasing them leaked one staged file per image per turn+ // until quit. The release is the machine's+ // `.releaseImagesOfHeldConversation` effect, so the transitions that+ // give the KV up and the transitions that free its pictures are one+ // list rather than two that drifted apart.+ perform(machine.apply(.newChat))+ // The composer's own attachments too. Released only from the transcript+ // and the conversation, a picture attached but never sent stayed in the+ // box and followed the user into the new chat — and its staged copy+ // stayed on disk until the app quit.+ clearImages()conversation.startNew()outputPromptText = ""- releaseTranscriptImages()outputText = ""generationTranscriptMailbox?.reset()diagnostics = nil@@ -1765,7 +2184,7 @@ public final class AppModel {////// 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+ /// move out of context, 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.@@ -1778,8 +2197,24 @@ public final class AppModel {images: outputImageAttachments),assistant: AppChatTurn(role: .assistant, text: outputText))]}- archivedPairs.append(contentsOf: carried)- conversation.startNew()+ // The read-only copy of a chat that was merely being looked at is not+ // part of the live conversation's history, and it cannot be mistaken+ // for one now: it lives in the screen and goes with the screen. When+ // the two were one array, a reload or an unload while reading a chat+ // that could not be continued drew that chat as the live conversation's+ // own out-of-context turns, under a context break with nothing below+ // it, and Re-read into a new chat built its prompt from a conversation+ // the user had only been reading.+ perform(machine.apply(.lineageEnded))+ let outOfContext = conversation.outOfContextPairs + carried+ conversation.startNew(carryingOutOfContext: outOfContext)+ // The stored conversation keeps every turn it had, and its row will say+ // whether it can still be continued. What must not happen is the next+ // turn appending to that file while the KV holds only the new lineage:+ // the transcript on disk would then claim a context the model does not+ // have. So this window stops writing to it and the next send opens a+ // new one.+ storedConversationID = nil// 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.@@ -1791,6 +2226,24 @@ public final class AppModel {}}+ /// A persisted conversation remains the conversation on screen after its+ /// KV is released. It is now a readable stored copy, and the next send+ /// restores its exact token record before appending to the same directory.+ /// A non-persisted session has no such record and keeps the legacy visible+ /// context-break behavior instead.+ private func presentStoredConversationAfterReleasedKV() {+ // Browsing and KV ownership are independent. Releasing the held KV+ // must not switch the viewed row or redirect its next message.+ guard let id = screen.conversationID ?? storedConversationID,+ conversationStore != nil,+ history.entry(id) != nil else {+ archiveConversationContext()+ return+ }+ prepareServiceRecoveryForReplay()+ openConversation(id: id)+ }+/// 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@@ -1802,34 +2255,132 @@ public final class AppModel {serviceEpoch = conversation.epoch}- public func run() {+ // MARK: - The send path++ /// Hands a message over to the pipeline.+ ///+ /// Synchronous on purpose, and it empties the composer before it returns:+ /// `canRun` reads the composer, so a second Generate between the click and+ /// the pipeline's first suspension is refused by the same guard that+ /// refused the first one. Started inside the task instead, two clicks+ /// started two replays of the same chat under different epochs, and the+ /// turn the first had already stamped came back rejected as belonging to a+ /// conversation that was no longer open.+ public func send() {+ recheckVisionPackAtCurrentLocation()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 {+ let turn = takeComposer()+ sendTask = Task { [weak self] in+ guard let self else { return }+ await deliver(turn)+ sendTask = nil+ }+ }++ /// Takes the message out of the composer and gives it to the caller.+ ///+ /// The images move rather than being copied: the composer stops drawing+ /// them here and nothing deletes them, because the turn is now the only+ /// thing that refers to those files. A stage that fails puts both halves+ /// back through `restoreComposer`.+ private func takeComposer() -> PreparedTurn {+ let turn = PreparedTurn(prompt: promptText, images: imageAttachments)+ promptText = ""+ imageAttachments.removeAll()+ imageAttachmentError = nil+ return turn+ }++ /// The one path a message takes, in stages.+ ///+ /// Every stage either advances or ends in `restoreComposer`, and nothing+ /// here calls itself: the replay used to hand the message back to the+ /// composer and re-enter `run()`, so a replay that resolved without putting+ /// anything into the KV re-entered the same branch forever.+ private func deliver(_ turn: PreparedTurn) async {+ var turn = turn+ // The transcript draws this message as the current turn from the moment+ // a replay starts, so a stage that fails before the model saw it takes+ // the message off the screen with it. A turn the runtime rewound+ // afterwards keeps it: the window shows a stopped turn as the current+ // one until the next send replaces it.+ var isDrawnAsTheLiveTurn = false++ // 1. Replay. A reopened conversation is on screen but not in the+ // model's context, and the ticket below has to be reserved against+ // the restored lineage or the service's gate refuses a turn numbered+ // against the wrong epoch.+ //+ // Anything but the live conversation goes through here. Only+ // `.reading` used to, so a send while the screen named an unreadable+ // row skipped the replay and ran on the held chat: the turn was+ // written into that chat's file while the sidebar, the notice and+ // the saved selection all named the row that could not be read.+ if case .live = screen {} else {+ var replayID: UUID?+ for case .replay(let id, _) in machine.apply(.sendRequested(turn)) {+ replayID = id+ }+ guard let replayID else {+ // The machine refused: the row on screen cannot be continued,+ // which `canRun` already says. Handed back rather than run on+ // the held conversation under the wrong row.+ restoreComposer(turn, error: .invalidRequest(+ "The conversation on screen cannot be continued."),+ withdrawingFromTranscript: false)+ return+ }+ // The message moves into the transcript now, under the same prefill+ // placeholder an ordinary turn gets. A replay is a full prefill of+ // everything the conversation holds, and for the length of it the+ // window showed nothing at all — the composer was empty and the+ // transcript had not changed — which is what made a second Generate+ // the obvious thing to press.+ runIdentity &+= 1+ generationTranscriptMailbox?.reset()+ outputPromptText = turn.prompt+ outputImageAttachments = turn.images.map(ChatImage.staged)+ outputText = ""+ isDrawnAsTheLiveTurn = true+ if await !replayIntoKV(id: replayID, turn: turn) {+ // The machine's `.restoreComposer` effect has already handed+ // the message back with the reason it could not be replayed.+ return+ }+ }++ // 2. Reserve the position the service will check, before the request is+ // built, so the position the transcript shows is the position sent.+ guard let ticket = conversation.beginTurn(text: turn.prompt) else {+ // `canRun` already required `conversation.canSend`, and the emptied+ // composer refuses a second send, so nothing should reach this.+ // Refused with the message given back rather than dropped.+ restoreComposer(turn, error: .invalidRequest(+ "This conversation is already sending a turn."),+ withdrawingFromTranscript: isDrawnAsTheLiveTurn)return}++ // 3. Build the request from the message, not from the composer: the+ // composer was emptied at stage 1 and may already hold the next one.var request: AppGenerationRequestdo {- request = try makeRequest(ticket: ticket)- } catch let appError as AppInferenceError {- conversation.abandonTurn()- error = appError- return+ request = try makeRequest(turn, ticket: ticket)} catch {- let appError = AppInferenceError.unknown("\(error)")conversation.abandonTurn()- self.error = appError+ restoreComposer(+ turn,+ error: (error as? AppInferenceError) ?? .unknown("\(error)"),+ withdrawingFromTranscript: isDrawnAsTheLiveTurn)return}- // The run reads the transcript's own hard links rather than the- // composer's files, so clearing the composer below cannot delete an- // image this request has not opened yet. One set of files, one owner.- // A failed retain leaves no reference that is guaranteed to outlive- // the composer, so the run is refused instead of started against files- // that are about to be removed.- var retained: [AppImageAttachment] = []+ // 4. Retain the images. The run reads the transcript's own hard links+ // rather than the composer's files, so the hand-off below cannot+ // delete an image this request has not opened yet. A failed retain+ // leaves no reference guaranteed to outlive the composer, so the run+ // is refused instead of started against files about to be removed.+ var retained: [StagedImage] = []do {for attachment in request.imageAttachments {retained.append(try attachmentStore.retain(attachment))@@ -1838,14 +2389,21 @@ public final class AppModel {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)")+ restoreComposer(turn, error: .invalidRequest(+ "Could not prepare the attached images for this run: \(error)"),+ withdrawingFromTranscript: isDrawnAsTheLiveTurn)return}request.imageAttachments = retained-+ // The hand-off. The message is carried by its retained links from here,+ // and the copies it arrived with are referenced by nothing: handing+ // those back after a rewind would give the user thumbnails with no+ // files behind them.+ for attachment in turn.images { attachmentStore.remove(attachment) }+ turn = turn.carrying(retained)++ // 5. Start the turn.persistSettings()-generationTranscriptMailbox?.reset()runIdentity &+= 1let generation = runIdentity@@ -1854,11 +2412,12 @@ public final class AppModel {// 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 = retained+ outputImageAttachments = retained.map(ChatImage.staged)outputText = ""diagnostics = nilerror = nilhasHandledTerminalEvent = false+ turnOutcome = .committedactiveRunRuntimeKey = AppLoadedRuntimeKey(modelDirectory: request.modelDirectory,maxContextTokens: request.maxContextTokens,@@ -1872,19 +2431,17 @@ public final class AppModel {sampleLiveMemory()phase = .prefillrunState = .running- // 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, generation] in+ // 6. Generate. The directory is created here, on the first send, rather+ // than at New Chat: a chat the user opens and never uses must leave+ // nothing behind. The images start being written now, overlapped with+ // the reply the user is already waiting for.+ if let storedID = await ensureStoredConversation(firstMessage: request.prompt) {+ beginStoringTurnImages(request.imageAttachments, in: storedID)+ }+ // Off the main actor: an event stream whose producer runs inline would+ // hold the window for the length of the run.+ let stream = Task.detached { [weak self, client, request, generation] inguard let self else { return }do {try await self.openConversationIfNeeded()@@ -1897,6 +2454,100 @@ public final class AppModel {await self.finishStreamFailure(.unknown("\(error)"), generation: generation)}}+ // The turn is over at its terminal event, not when the stream happens+ // to close: a client that reports a failure and then goes quiet would+ // otherwise hold the composer, New Chat and every later send for as+ // long as it stayed quiet. The stream is watched as well, so a stream+ // that ends without a terminal event still releases this.+ await withCheckedContinuation { continuation in+ turnCompletion = (generation: generation, continuation: continuation)+ Task { [weak self] in+ await stream.value+ self?.endTurnWait(generation: generation)+ }+ }++ // 7. Commit or hand back. `finishSuccessfully` has already written the+ // turn; a rewind reaches here with the cause already in `error`.+ guard case .rewound = turnOutcome else { return }+ restoreComposer(turn, error: nil, withdrawingFromTranscript: false)+ // Its images were written while the reply was generating, and the turn+ // that would have cited them is gone. Ended before the sweep rather+ // than beside it: the sweep deletes every file no record names, and a+ // write still running would have raced it into the same directory.+ await discardPendingTurnImages()+ await sweepImagesOfRewoundTurn()+ }++ /// Puts a stored conversation back into the KV and says whether the turn+ /// waiting on it may go.+ private func replayIntoKV(id: UUID, turn: PreparedTurn) async -> Bool {+ phase = .prefill+ livePrefillDone = 0+ // A denominator from the record, so the gauge counts up from the first+ // moment rather than from whenever the first progress event lands.+ livePrefillTotal = history.entry(id)?.kvTokens ?? 0+ let outcome = await replayOutcome(id: id)+ // Back out of the prefill phase the send put the window into, or the+ // gauge keeps claiming a replay that has already finished.+ phase = .idle+ livePrefillDone = 0+ livePrefillTotal = 0+ let effects = machine.apply(outcome)+ perform(effects)+ return effects.contains { if case .startTurn = $0 { return true } else { return false } }+ }++ /// Puts a turn that never reached the model, or one the runtime rewound,+ /// back in the composer.+ ///+ /// The one function that hands a message back; every failing stage reaches+ /// it exactly once. `error` is nil when the failure has already recorded+ /// itself — a rewound generation sets `error` as it ends, and a second copy+ /// of the same cause would replace what the window is already showing.+ ///+ /// `withdrawingFromTranscript` takes the message off the screen as well.+ /// True for every stage that failed before the model saw the turn, because+ /// what is drawn there is this very message with nothing underneath it;+ /// false for a turn the runtime rewound, which the window keeps drawing as+ /// the current one until the next send replaces it.+ func restoreComposer(_ turn: PreparedTurn,+ error: AppInferenceError?,+ withdrawingFromTranscript: Bool) {+ if withdrawingFromTranscript {+ outputPromptText = ""+ outputText = ""+ generationTranscriptMailbox?.reset()+ }+ // Dropped, never released: these are the same links the turn below is+ // carrying, and deleting them here handed the composer back a set of+ // pictures whose files had just been removed. Only when they are this+ // message's, though. A refusal before the model saw the turn — a+ // request that did not validate, a retain that failed — reaches here+ // with the live fields still drawing the previous turn, and clearing+ // them made that turn's pictures vanish from the transcript.+ var own: Set<UUID> = []+ for image in turn.images { own.insert(image.id) }+ var drawsThisMessage = withdrawingFromTranscript+ for image in outputImageAttachments {+ if let staged = image.staged, own.contains(staged.id) {+ drawsThisMessage = true+ }+ }+ if drawsThisMessage {+ outputImageAttachments = []+ }+ if promptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ promptText = turn.prompt+ }+ if imageAttachments.isEmpty {+ imageAttachments = turn.images+ } else {+ // The composer was used again while the turn was in flight, and its+ // copies are the ones the next send will carry.+ for attachment in turn.images { attachmentStore.remove(attachment) }+ }+ if let error { self.error = error }}public func cancel() {@@ -1905,8 +2556,24 @@ public final class AppModel {client.cancel()}+ /// The request the composer would build right now, for the callers that+ /// only need to know whether what is in it is valid.public func makeRequest(ticket: AppConversation.Ticket? = nil+ ) throws -> AppGenerationRequest {+ try makeRequest(+ PreparedTurn(prompt: promptText, images: imageAttachments),+ ticket: ticket)+ }++ /// The request one message makes.+ ///+ /// Built from the turn rather than from the composer, which the send path+ /// emptied before this is reached and which may already hold the next+ /// message.+ func makeRequest(+ _ turn: PreparedTurn,+ 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@@ -1918,8 +2585,8 @@ public final class AppModel {let effective = loadedRuntimeKey ?? currentRuntimeKeylet request = AppGenerationRequest(modelDirectory: URL(fileURLWithPath: modelPathText),- prompt: promptText,- imageAttachments: imageAttachments,+ prompt: turn.prompt,+ imageAttachments: turn.images,maxNewTokens: maxNewTokensOverride ?? effective.maxContextTokens,maxContextTokens: effective.maxContextTokens,temperature: Float(temperature),@@ -1982,7 +2649,17 @@ public final class AppModel {hasHandledTerminalEvent = truematerializeServiceTranscript()self.diagnostics = diagnostics+ let userText = outputPromptText+ let assistantText = outputTextconversation.completeTurn(text: outputText, diagnostics: diagnostics)+ // Written here and nowhere else: this is the one path that commits a+ // turn to the KV, so it is the one path where the transcript on disk+ // and the model's context can be made to say the same thing. A turn+ // that threw was rewound by the runtime and reaches `finishWithError`,+ // which writes nothing.+ enqueueCompletedTurnPersistence(+ userText: userText, assistantText: assistantText,+ diagnostics: diagnostics)finishTerminalRun()}@@ -2010,10 +2687,9 @@ public final class AppModel {// 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)- }+ // until quit. Recorded rather than handed back here: the send pipeline+ // is holding the message, and it is the one place that gives it back.+ if conversation.abandonTurn() != nil { turnOutcome = .rewound }finishTerminalRun()}@@ -2037,27 +2713,31 @@ public final class AppModel {// them retype it.abandoned = conversation.abandonTurn()}- if let abandoned {- restoreComposer(from: abandoned)- }+ if abandoned != nil { turnOutcome = .rewound }finishTerminalRun()+ if case .connectionLost = appError {+ recordLostServiceConnection(appError)+ if let id = storedConversationID, let meta = history.entry(id) {+ pendingServiceRecoveryConversationID = id+ perform(machine.apply(.rowClicked(+ id: id, heldID: id, kvMatchesHeld: false,+ state: continuability(of: meta), renderID: UUID())))+ }+ }}- /// Puts a turn that never reached the model back in the composer.+ /// The loaded model is gone with the decode service that held it.///- /// 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 = []+ /// One place for the state a lost connection leaves, reached by a+ /// generation that ends on it and by a replay that does: the runtime key,+ /// the memory readings and the epoch all belonged to a process that no+ /// longer exists, and `.failed` is what puts Retry Load on screen.+ func recordLostServiceConnection(_ appError: AppInferenceError) {+ loadedRuntimeKey = nil+ liveMemoryBytes = nil+ liveResidentBytes = nil+ loadState = .failed(appError)+ serviceEpoch = nil}private func finishStreamFailure(_ appError: AppInferenceError, generation: Int) {@@ -2071,7 +2751,20 @@ public final class AppModel {runState = .idleisCancellationPending = falseactiveRunRuntimeKey = nil- runTask = nil+ endTurnWait(generation: runIdentity)+ }++ /// Releases the send's last stage.+ ///+ /// Keyed on the run it belongs to: a stream from an abandoned run can close+ /// long after the run that replaced it started, and resuming the newer+ /// turn's wait would commit it before it had generated anything.+ private func endTurnWait(generation: Int) {+ guard let pending = turnCompletion, pending.generation == generation else {+ return+ }+ turnCompletion = nil+ pending.continuation.resume()}private func clearLoadTask(generation: UInt64) {@@ -2084,4 +2777,14 @@ public final class AppModel {guard generation == unloadGeneration else { return }unloadTask = nil}++ public func shutdownForTermination() {+ guard !hasShutDownForTermination else { return }+ hasShutDownForTermination = true+ // Direct inspector bindings may have changed since the last saved action.+ persistSettings()+ client.cancel()+ (client as? AppModelLifecycleClient)?.shutdownForTermination()+ releaseAllAttachments()+ }}diff --git a/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift b/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swiftnew file mode 100644index 00000000..fee6077b--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift@@ -0,0 +1,1121 @@+import Foundation+import TurboFieldfare++/// What the stored copies of one turn's pictures came to.+///+/// The count of failures is the part that matters: the turn's recorded IDs+/// still hold each picture's placeholder run, so a picture with no stored copy+/// means a later replay would hand the model a span of image tokens with+/// nothing behind them, and the context would silently differ from the one the+/// answer came out of. Two `try?`s used to drop exactly that on the floor.+struct TurnImageWriteOutcome: Sendable {+ var records: [ConversationImageRecord] = []+ var failed = 0+ /// Why the first of them failed, in words that name no file: the count of+ /// lost pictures is a diagnostic, their names are the user's.+ var reason: String?+}++/// The shape of an image-write failure, without the path or the display name+/// the error itself carries.+private func imageWriteReason(_ error: Error) -> String {+ switch error {+ case ConversationImageWriterError.noMetalDevice:+ return "no Metal device is available to prepare them"+ case ConversationImageWriterError.modelInputUnavailable:+ return "preprocessing produced no model-input copy"+ case ConversationImageWriterError.encodeFailed:+ return "the copy could not be written into the conversation's folder"+ default:+ return "\(type(of: error))"+ }+}++/// The app's side of persisted conversations: writing the open chat as it is+/// used, listing what is on disk, and replaying one back into the KV.+///+/// The rule the whole file obeys is the one `AppConversation` already states —+/// the transcript equals the model's context. A turn is written when it is in+/// the KV and not before, so a stored conversation is always a sequence the+/// model actually saw, and replaying it cannot invent a turn.+extension AppModel {+ // MARK: - Store lifecycle++ func replaceConversationBinding(for modelDirectory: URL, reason: String) {+ guard settingsPersistenceEnabled else { return }+ let modelDirectory = modelDirectory.standardizedFileURL+ conversationBindingGeneration &+= 1++ let identity: ConversationIdentity?+ if AppModelInstallationProbe.status(at: modelDirectory) == .complete {+ do {+ identity = try conversationIdentityProvider(modelDirectory)+ } catch {+ identity = nil+ historyDiagnostic = "the installed model identity could not be read after \(reason): \(error)"+ }+ } else {+ identity = nil+ historyDiagnostic = nil+ }++ pendingTurnImageWrite?.cancel()+ pendingTurnImageWrite = nil+ persistenceTail?.cancel()+ persistenceTail = nil+ quarantinedPersistenceLineages.removeAll()+ storedConversationID = nil+ serviceEpoch = nil+ pendingServiceRecoveryConversationID = nil+ machine = ConversationScreenMachine()+ history.replaceEntries([])+ history.selection = pendingRestoredConversationID+ history.setUnreadableCount(0)+ history.setDiscardedLegacyTrashCount(0)+ history.setReadOnlyStore(false)+ conversationBinding = ConversationStoreBinding(+ modelDirectory: modelDirectory,+ identity: identity,+ generation: conversationBindingGeneration,+ storeProvider: conversationStoreProvider)+ activateConversationStore()+ }++ private func isCurrentConversationBinding(+ generation: UInt64, store: ConversationStore+ ) -> Bool {+ guard let binding = conversationBinding else { return false }+ return binding.generation == generation && binding.store === store+ }++ func activateConversationStore() {+ guard let binding = conversationBinding else { return }+ let store = binding.store+ let generation = binding.generation+ Task { [weak self] in+ do {+ try await store.activate()+ let discarded = await store.discardedLegacyTrashCount+ if discarded > 0,+ self?.isCurrentConversationBinding(+ generation: generation, store: store) == true {+ self?.history.setDiscardedLegacyTrashCount(discarded)+ self?.recordHistoryDiagnostic(+ "removed \(discarded) conversation(s) an older build had "+ + "left in .trash")+ }+ } catch {+ // A store that cannot be locked for an unknown reason stays+ // read-only rather than being written to anyway.+ if self?.isCurrentConversationBinding(+ generation: generation, store: store) == true {+ self?.recordHistoryDiagnostic("\(error)")+ }+ }+ await self?.refreshHistory(store: store, generation: generation)+ }+ }++ /// Re-reads the list. Cheap on purpose: it touches only `conversation.json`+ /// per directory, never a transcript.+ func refreshHistory() async {+ guard let binding = conversationBinding else { return }+ await refreshHistory(store: binding.store, generation: binding.generation)+ }++ private func refreshHistory(store: ConversationStore, generation: UInt64) async {+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return+ }+ let isReadOnly = await store.isReadOnly+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return+ }+ history.setReadOnlyStore(isReadOnly)+ let entries: [ConversationMeta]+ do {+ entries = try await store.list()+ } catch {+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return+ }+ // The last good list stays on screen. Emptied instead, a store that+ // could not be enumerated once — a permission change, a volume that+ // went away, a root that is now a file — looked exactly like a user+ // with no chats at all, and the window then offered New Chat over+ // conversations that were still there.+ recordHistoryDiagnostic(+ "the list of conversations could not be read, so the sidebar is "+ + "showing the last one that could: \(error)")+ history.setUnreadableCount(max(history.unreadableCount, 1))+ return+ }+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return+ }+ let skipped = await store.skippedByLastList+ let reasons = await store.skipReasons+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return+ }+ history.setUnreadableCount(skipped.count)+ if !skipped.isEmpty {+ // Names and reasons, never content: a skipped conversation's+ // transcript is exactly what could not be read anyway.+ recordHistoryDiagnostic(+ "\(skipped.count) conversation(s) could not be read: "+ + skipped.map {+ "\($0.uuidString) (\(reasons[$0] ?? "no reason recorded"))"+ }.joined(separator: ", "))+ }+ history.replaceEntries(entries)+ if let saved = pendingRestoredConversationID {+ pendingRestoredConversationID = nil+ if history.entry(saved) != nil {+ openConversation(id: saved)+ } else {+ history.selection = nil+ persistHistorySelection()+ }+ }+ }++ /// Says so when a conversation's `conversation.json` had to be rebuilt.+ ///+ /// The conversation survives it — the records are the conversation — but a+ /// cache that could not be read is a real fault of the store, and healing+ /// one silently leaves nobody able to say it ever happened.+ func recordMetaRebuild(_ opened: ConversationOpenResult) {+ guard let reason = opened.metaRebuildReason else { return }+ recordHistoryDiagnostic(+ "conversation \(opened.meta.id.uuidString) was rebuilt from its "+ + "records: \(reason)")+ }++ func recordHistoryDiagnostic(_ message: String) {+ // Names and counts only. A diagnostic that carried transcript text+ // would put the user's conversation into whatever collects it.+ historyDiagnostic = message+ }++ // MARK: - Writing the open chat++ /// The directory the open chat is written to, created on first use.+ ///+ /// Lazy so a New Chat the user never sends leaves nothing on disk: a+ /// sidebar full of empty rows is worse than no sidebar.+ func ensureStoredConversation(firstMessage: String) async -> UUID? {+ guard let binding = conversationBinding,+ let identity = binding.identity else {+ return nil+ }+ let store = binding.store+ guard !quarantinedPersistenceLineages.contains(where: {+ $0.epoch == conversation.epoch+ && $0.bindingGeneration == binding.generation+ }) else { return nil }+ // Read-only first, before the existing id: a store without the writer+ // lock must not be written to at all, and returning the id of a chat+ // another window owns had this one write image files into that+ // window's directory before the append itself was refused.+ guard await !store.isReadOnly else { return nil }+ if let existing = storedConversationID { return existing }+ // Storage may recover after an unsaved turn, but a new file cannot+ // stand in for the complete prefix still held by the live KV.+ guard conversation.committedTurns == 0 else {+ let reason = "Earlier exchanges in this chat were not saved. Start a new chat to resume saving."+ recordHistoryDiagnostic(reason)+ error = .conversationPersistenceFailed(reason)+ return nil+ }+ do {+ let meta = try await store.create(+ title: ConversationTitle.fromFirstMessage(firstMessage),+ identity: identity,+ session: ConversationSessionSettings(+ contextTokens: maxContextTokens,+ expertCacheSlots: runtimeOptions.expertCacheSlots,+ visionResidencyPolicy: runtimeOptions.visionResidencyPolicy.rawValue),+ sampling: currentSampling())+ storedConversationID = meta.id+ history.selection = meta.id+ persistHistorySelection()+ await refreshHistory()+ return meta.id+ } catch {+ recordHistoryDiagnostic("\(error)")+ self.error = .conversationPersistenceFailed("\(error)")+ return nil+ }+ }++ func currentSampling() -> ConversationSampling {+ ConversationSampling(+ temperature: temperature, topKEnabled: topKEnabled, topK: topK,+ topPEnabled: topPEnabled, topP: topP,+ maxNewTokens: maxNewTokensOverride ?? effectiveMaxContextTokens)+ }++ /// Starts writing the stored copies of a turn's images while the model is+ /// generating.+ ///+ /// Off the main actor and overlapped with the reply on purpose: preparing a+ /// model-input copy is a full decode and resize, seconds per image on the+ /// 8 GB host, and the user is already waiting for the answer. A turn the+ /// runtime then rewinds leaves its files behind, which is what the store's+ /// orphan sweep is for.+ func beginStoringTurnImages(_ attachments: [StagedImage], in id: UUID) {+ pendingTurnImageWrite?.cancel()+ guard !attachments.isEmpty, let store = conversationStore else {+ pendingTurnImageWrite = nil+ return+ }+ // The writer reads links of its own. The turn's retained links belong+ // to the transcript, and New Chat or a replay of another chat releases+ // them the moment the reply lands — while the writer, seconds into a+ // decode and resize, still had the thumbnail to read from the same+ // path. That failed the write, which marked the turn's record as+ // missing a picture and refused the conversation every replay after.+ var links: [StagedImage] = []+ for attachment in attachments {+ do {+ links.append(try attachmentStore.retain(attachment))+ } catch {+ let failed = attachments.count+ let reason = imageWriteReason(error)+ for link in links { attachmentStore.remove(link) }+ pendingTurnImageWrite = Task {+ TurnImageWriteOutcome(failed: failed, reason: reason)+ }+ return+ }+ }+ let taken = links+ let releasing = attachmentStore+ pendingTurnImageWrite = Task.detached(priority: .utility) {+ let directory = await store.imagesURL(for: id)+ return Self.writeStoredImages(taken, into: directory, releasing: releasing)+ }+ }++ /// Writes the stored copies of a turn's pictures from the writer's own+ /// links, and releases those links whatever came of it.+ nonisolated static func writeStoredImages(+ _ links: [StagedImage], into directory: URL,+ releasing attachmentStore: AppImageAttachmentStore+ ) -> TurnImageWriteOutcome {+ let outcome = writeStoredImages(links, into: directory)+ for link in links { attachmentStore.remove(link) }+ return outcome+ }++ /// Writes the stored copies of a turn's pictures, one outcome for all.+ nonisolated static func writeStoredImages(+ _ links: [StagedImage], into directory: URL+ ) -> TurnImageWriteOutcome {+ let writer: ConversationImageWriter+ do {+ writer = try ConversationImageWriter()+ } catch {+ // Every picture of the turn, not none of them. Discarded here,+ // each one vanished from the record while its placeholder+ // tokens stayed in the turn's IDs, and a later replay prefilled+ // that span with no pixels behind it.+ return TurnImageWriteOutcome(+ failed: links.count, reason: imageWriteReason(error))+ }+ var outcome = TurnImageWriteOutcome()+ for link in links {+ do {+ outcome.records.append(+ try writer.write(attachment: link, into: directory))+ } catch {+ outcome.failed += 1+ if outcome.reason == nil {+ outcome.reason = imageWriteReason(error)+ }+ }+ }+ return outcome+ }++ /// Waits for the turn writes already queued to reach disk.+ ///+ /// Quit and delete both need it: the last exchange's write starts when+ /// the reply lands and, with pictures, runs for seconds after the send+ /// pipeline has returned. Quitting under it lost the exchange; deleting+ /// under it left a headerless transcript behind.+ public func awaitPendingPersistence() async {+ await persistenceTail?.value+ }++ /// Whether the pending write finished before the termination deadline.+ public func awaitPendingPersistence(timeout: Duration) async -> Bool {+ guard !Task.isCancelled else { return false }+ guard let pending = persistenceTail else { return true }+ // A task group waits for every child even after cancelAll. Observing+ // an independent Task.value cannot be cancelled, so race notifications+ // instead and leave the write free to finish during termination.+ let (events, continuation) = AsyncStream<Bool>.makeStream(+ bufferingPolicy: .bufferingOldest(1))+ let completion = Task {+ await pending.value+ continuation.yield(true)+ continuation.finish()+ }+ let deadline = Task {+ do { try await Task.sleep(for: timeout) }+ // Sleep throws only on cancellation, including the cleanup below+ // when persistence wins the race.+ catch { return }+ continuation.yield(false)+ continuation.finish()+ }+ defer {+ completion.cancel()+ deadline.cancel()+ continuation.finish()+ }+ var iterator = events.makeAsyncIterator()+ return await iterator.next() ?? false+ }++ /// Writes a completed turn: the user's half, then the model's, then the+ /// small file the sidebar reads.+ ///+ /// Called only from the terminal path that commits the turn to+ /// `AppConversation`, so what lands on disk is exactly what the KV holds. A+ /// turn that threw is written nowhere, because the runtime rewound it.+ func enqueueCompletedTurnPersistence(userText: String,+ assistantText: String,+ diagnostics: AppDiagnostics?) {+ guard let binding = conversationBinding,+ let id = storedConversationID else { return }+ let operation = CompletedTurnPersistence(+ key: PersistenceLineageKey(+ conversationID: id,+ epoch: conversation.epoch,+ bindingGeneration: binding.generation),+ store: binding.store,+ userText: userText,+ assistantText: assistantText,+ diagnostics: diagnostics,+ sampling: currentSampling(),+ boundary: ConversationBoundary(+ tokens: conversation.boundaryTokenIDs,+ needsReplay: conversation.boundaryNeedsReplay),+ imageWrite: pendingTurnImageWrite)+ pendingTurnImageWrite = nil+ let prior = persistenceTail+ persistenceTail = Task { [weak self] in+ await withTaskCancellationHandler {+ await prior?.value+ } onCancel: {+ // The tail is the one binding replacement can reach. Carry+ // cancellation backward through the chain so an older write+ // cannot land in the model root that was just left behind.+ prior?.cancel()+ }+ guard !Task.isCancelled else {+ await self?.discardImages(for: operation)+ return+ }+ await self?.persistCompletedTurn(operation)+ }+ }++ private func persistCompletedTurn(_ operation: CompletedTurnPersistence) async {+ let store = operation.store+ let id = operation.key.conversationID+ guard isCurrentConversationBinding(+ generation: operation.key.bindingGeneration, store: store),+ !quarantinedPersistenceLineages.contains(operation.key) else {+ await discardImages(for: operation)+ return+ }+ let written = await operation.imageWrite?.value+ guard !Task.isCancelled,+ isCurrentConversationBinding(+ generation: operation.key.bindingGeneration, store: store),+ !quarantinedPersistenceLineages.contains(operation.key) else {+ await discardImages(for: operation)+ return+ }+ let images = written?.records ?? []+ let lostImages = written?.failed ?? 0+ let now = Date()+ do {+ // Both halves in one call: the meta is projected from the records+ // once, at the end, so the sidebar never sees a conversation with a+ // question and no answer in it.+ let meta = try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: now, text: operation.userText, images: images,+ tokens: operation.diagnostics?.promptTokenIDs,+ promptTokens: operation.diagnostics?.promptTokenCount,+ cachedTokens: operation.diagnostics?.cachedPromptTokens,+ sampling: operation.sampling,+ // Recorded on the turn that cites them, so the projection+ // can refuse the whole conversation a replay and the row+ // can say why instead of failing on its first turn back.+ imageWriteFailed: lostImages > 0 ? true : nil)),+ .turn(ConversationTurnRecord(+ role: .assistant, at: now, text: operation.assistantText,+ tokens: operation.diagnostics?.generatedTokenIDs,+ generatedTokens: operation.diagnostics?.generatedTokens,+ stopReason: operation.diagnostics.map {+ String(describing: $0.stopReason)+ },+ boundary: operation.boundary)),+ ], to: id)+ // The runtime's count and the record's are two answers to one+ // question, and they used to be reconciled by preferring the+ // runtime's and writing it into the meta by hand — which is how a+ // row came to read 1,065 tokens over 22 tokens of record. The+ // record wins now, because it is what a replay actually puts back;+ // a disagreement is a fault worth seeing rather than papering over.+ if let reported = operation.diagnostics?.conversationTokens,+ reported != meta.kvTokens {+ recordHistoryDiagnostic(+ "the runtime reports \(reported) token(s) in this "+ + "conversation and its records hold "+ + "\(meta.kvTokens.map(String.init) ?? "no countable"): "+ + "the record decides")+ }+ } catch {+ quarantinedPersistenceLineages.insert(operation.key)+ if isCurrentConversationBinding(+ generation: operation.key.bindingGeneration, store: store) {+ recordHistoryDiagnostic("\(error)")+ if storedConversationID == id,+ conversation.epoch == operation.key.epoch {+ self.error = .conversationPersistenceFailed("\(error)")+ storedConversationID = nil+ history.selection = nil+ persistHistorySelection()+ }+ }+ }+ // Last, so it is the diagnostic on screen: a conversation that can no+ // longer be reopened is worth more than a count that disagreed.+ if lostImages > 0 {+ recordHistoryDiagnostic(+ "\(lostImages) image(s) in this turn have no stored copy, so this "+ + "conversation cannot be put back into the model's context: "+ + (written?.reason ?? "no reason recorded"))+ }+ await refreshHistory(store: store, generation: operation.key.bindingGeneration)+ }++ private func discardImages(for operation: CompletedTurnPersistence) async {+ operation.imageWrite?.cancel()+ _ = await operation.imageWrite?.value+ do {+ _ = try await operation.store.sweepOrphanImages(+ in: operation.key.conversationID)+ } catch {+ if isCurrentConversationBinding(+ generation: operation.key.bindingGeneration,+ store: operation.store) {+ let original = historyDiagnostic ?? "the lineage is quarantined"+ recordHistoryDiagnostic(+ original + "; its orphan images could not be collected: \(error)")+ }+ }+ }++ // MARK: - Reopening++ /// The state a stored row is in right now, against the context in force.+ public func continuability(of meta: ConversationMeta) -> ConversationContinuability {+ guard let identity = conversationIdentity else {+ return .cannotReplay(reason: .differentModel)+ }+ return ConversationContinuability.evaluate(+ meta: meta, currentContext: maxContextTokens, identity: identity)+ }++ /// Opens a stored conversation and shows it.+ ///+ /// Reading a conversation and being able to continue it are two different+ /// costs, and this only pays the first. The transcript is a file, so it+ /// appears at once; the model's context is a full prefill of every token+ /// the conversation holds — tens of seconds at 8K — and nothing needs it+ /// until the next message. So the replay is deferred to the first send,+ /// where the user is already waiting for the model and the cost is part of+ /// a turn rather than the price of a click.+ ///+ /// A conversation that could not continue anyway is never replayed at all;+ /// the row says why instead.+ public func openConversation(id: UUID) {+ guard !isTurnInFlight, conversationStore != nil else { return }+ guard let meta = history.entry(id) else { return }+ if id == storedConversationID,+ serviceEpoch == conversation.epoch,+ continuability(of: meta) == .continuable {+ applySampling(meta.sampling)+ }+ // Reading copies only. The live conversation is left exactly as it is —+ // it is what the KV holds, and browsing must not drop it — so what is on+ // screen becomes the stored copy of the row that was clicked, and+ // `isShowingStoredCopy` keeps the live turn from being drawn under it.+ perform(machine.apply(.rowClicked(+ id: id,+ heldID: storedConversationID,+ kvMatchesHeld: serviceEpoch == conversation.epoch,+ state: continuability(of: meta),+ renderID: UUID())))+ }++ /// Reads a stored conversation off disk and puts it on screen.+ ///+ /// One loader for both the chat that can be continued and the one that+ /// cannot: they used to be two, which is how a failure reported in one of+ /// them and not the other left a row selected over the ordinary empty state+ /// — the thing an unwritten chat looks like.+ private func loadDocument(id: UUID, renderID: UUID) {+ guard let binding = conversationBinding else { return }+ let store = binding.store+ let generation = binding.generation+ let samplingAtStart = currentSampling()+ // The previous read's failure is not this row's. Cleared here rather+ // than as its own effect: a load is the only thing that can replace it.+ error = nil+ Task { [weak self] in+ guard let self else { return }+ let opened: ConversationOpenResult+ do {+ opened = try await store.open(id: id)+ } catch {+ guard self.isCurrentConversationBinding(+ generation: generation, store: store) else { return }+ guard screen.conversationID == id,+ screen.documentReadID == renderID else { return }+ recordHistoryDiagnostic("\(error)")+ perform(machine.apply(.documentFailed(+ id: id, renderID: renderID, .conversationUnreadable("\(error)"))))+ return+ }+ guard self.isCurrentConversationBinding(+ generation: generation, store: store) else { return }+ let directory = await store.directoryURL(for: id)+ guard isCurrentConversationBinding(generation: generation, store: store),+ screen.conversationID == id,+ screen.documentReadID == renderID else { return }+ recordMetaRebuild(opened)+ history.replaceEntryAndResort(opened.meta)+ let effects = machine.apply(.documentLoaded(+ id: id, renderID: renderID,+ document: ConversationDocument.load(opened, directory: directory),+ state: continuability(of: opened.meta)))+ // Opening restores defaults, but a later edit belongs to the user.+ perform(effects.filter { effect in+ if case .applySampling = effect {+ return currentSampling() == samplingAtStart+ }+ return true+ })+ }+ }++ /// Reads a stored conversation off disk and puts its tokens back into the+ /// KV, ahead of the turn that asked for it. Reached from a send, never from+ /// a click.+ ///+ /// Returns what happened rather than applying it: the send pipeline is+ /// holding the message this replay is for, and it is the only thing+ /// entitled to decide what happens to it next. Applying the outcome here+ /// and letting the effect hand the message onward is what made the send+ /// path call itself.+ func replayOutcome(id: UUID) async -> ConversationScreenMachine.Event {+ guard let binding = conversationBinding,+ let lifecycle = client as? AppModelLifecycleClient else {+ // Refused rather than returned as a success: the send is waiting on+ // this, and handing it back as if the conversation were in the KV+ // put the send straight back into the same branch, forever.+ let refusal = AppInferenceError.conversationRestoreFailed(+ "this build cannot restore a conversation into the model's context")+ return .replayRefused(id: id, error: refusal)+ }+ let store = binding.store+ let generation = binding.generation+ let document: ConversationDocument+ do {+ // Completed exchanges can still be waiting on image storage. Replay+ // must include that prefix before the next turn replaces the KV.+ await awaitPendingPersistence()+ guard !Task.isCancelled else {+ return .replayNotStarted(id: id, error: .cancelled)+ }+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return .replayNotStarted(id: id, error: .conversationRestoreFailed(+ "the model location changed while the conversation was being saved"))+ }+ let opened = try await store.open(id: id)+ guard isCurrentConversationBinding(+ generation: generation, store: store) else {+ return .replayNotStarted(id: id, error: .conversationRestoreFailed(+ "the model location changed while the conversation was being read"))+ }+ recordMetaRebuild(opened)+ // The row's answer, taken again from the record just read. The+ // click took it from the cached meta, which a crash between a+ // turn's append and its cache write leaves a turn behind; a send+ // before the click's own read lands would otherwise ask the+ // service to drop the held chat for a restore the context then+ // refuses.+ let fresh = continuability(of: opened.meta)+ switch fresh {+ case .continuable:+ break+ case .needsContext(let required):+ let reserve: Int = ConversationGenerationReserve.tokens+ let prompt: Int = required - reserve+ let refusal = AppInferenceError.conversationContextExhausted(+ prompt: prompt, reserve: reserve, maxContext: maxContextTokens)+ return .replayRefused(id: id, error: refusal, state: fresh)+ case .cannotReplay(let reason):+ let refusal = AppInferenceError.conversationRestoreFailed(+ "the stored record can no longer be replayed: \(reason)")+ return .replayRefused(id: id, error: refusal, state: fresh)+ }+ document = ConversationDocument.load(+ opened, directory: await store.directoryURL(for: id))+ if document.turns.contains(where: { !$0.images.isEmpty }) {+ recheckVisionPackAtCurrentLocation()+ guard isVisionPackInstalled else {+ let directory = URL(+ fileURLWithPath: modelPathText, isDirectory: true)+ let location: String+ do {+ location = try VisionPackLocation.companionURL(+ forTextModel: directory).path+ } catch {+ location = "an unresolved companion path (\(error))"+ }+ // Not `.replayFailed`: the service has not been asked for+ // anything, so the held conversation is still in the KV+ // and must not be ended for a restore that never ran.+ return .replayNotStarted(id: id, error: .conversationRestoreFailed(+ "image support is unavailable at \(location)"))+ }+ }+ } catch {+ // The transcript could not be read at all, which is a different+ // failure from one that reads and cannot be replayed — and a+ // permanent property of what is on disk either way.+ let refusal: AppInferenceError = (error as? AppInferenceError)+ ?? AppInferenceError.conversationRestoreFailed("\(error)")+ return .replayRefused(id: id, error: refusal)+ }+ let lineage: AppConversationLineage+ switch document.lineage {+ case .success(let value):+ lineage = value+ case .failure(let recordError):+ // The record itself cannot be replayed — a turn with no tokens, an+ // image whose placeholders are not where it says. That is a+ // permanent property of what is on disk, so the row says so.+ let refusal = AppInferenceError.conversationRestoreFailed(+ recordError.description)+ return .replayRefused(id: id, error: refusal)+ }+ do {+ let epoch = UUID()+ let kvTokens = try await lifecycle.restoreConversation(+ lineage, epoch: epoch, options: runtimeOptions,+ maxContextTokens: maxContextTokens+ ) { [weak self] done, total in+ Task { @MainActor in self?.applyRestoreProgress(done: done, total: total) }+ }+ // The KV is only given up here, which is why the machine emits the+ // release with this event and not at the click. Released before the+ // replay instead, a restore that then failed left the held+ // conversation on screen pointing at pictures that had already been+ // deleted off disk.+ return .replaySucceeded(+ id: id, document: document, epoch: epoch, kvTokens: kvTokens)+ } catch let restoreError {+ // The record was fine; putting it back failed. That can be the+ // service refusing a digest, the service being gone, a load in+ // flight — none of them a property of the conversation, and all of+ // them fixable. Marking the row as having no replay record said the+ // opposite, and pointed at "re-read into a new chat" when what was+ // needed was the service back.+ let appError = (restoreError as? AppInferenceError)+ ?? .conversationRestoreFailed("\(restoreError)")+ if case .connectionLost = appError {+ // The transport has already dropped the connection, so this is+ // the same loss a generation reports, and it has to leave the+ // same state: a model that needs reloading. Folded into an+ // ordinary failed replay, the window kept advertising a ready+ // model with no Retry Load, and every later send failed on a+ // connection that was already gone.+ recordLostServiceConnection(appError)+ // So Retry Load keeps this row on screen for the send that+ // follows, rather than archiving it as a released KV would.+ pendingServiceRecoveryConversationID = id+ }+ return .replayFailed(id: id, error: appError)+ }+ }++ private func adoptRestoredConversation(document: ConversationDocument,+ epoch: UUID,+ kvTokens: Int) {+ // No image release here. This is only ever reached from a deferred+ // replay, and by then `openConversation` has already released whatever+ // the window was showing — so the only images left are the ones the+ // turn about to be sent is holding. Releasing those deleted the staged+ // files out from under the send: the turn came back "could not retain+ // <name>: errno 2" and was refused.+ conversation.adoptRestored(+ epoch: epoch,+ turns: document.turns,+ kvTokens: kvTokens,+ boundaryTokenIDs: document.meta.boundary.tokens,+ boundaryNeedsReplay: document.meta.boundary.needsReplay)+ storedConversationID = document.id+ serviceEpoch = epoch+ quarantinedPersistenceLineages.removeAll()+ // The live fields are left exactly as they are. They were seeded here+ // with the restored conversation's newest pair back when a reopen+ // replayed on the click and the window then sat at rest showing it.+ // A replay now only ever runs inside a send, so what they hold is the+ // message that started it — overwriting that dropped the user's prompt+ // and deleted the images it was carrying. The newest stored pair is+ // drawn from the history instead: `transcriptHistory` only holds a pair+ // back while no turn is in flight, and by the time this returns one is+ // about to be.+ diagnostics = nil+ error = nil+ livePrefillDone = 0+ livePrefillTotal = 0+ // Back out of the prefill phase the click put the window into, or the+ // gauge keeps claiming a replay that has already finished.+ phase = .idle+ }++ /// The staged copies belonging to the conversation the KV is about to stop+ /// holding.+ ///+ /// The only place the window's own pictures are released. Ten call sites+ /// used to do this, each with its own idea of when it applied, and one of+ /// them deleting a stored conversation's files is the defect the two image+ /// types now make impossible — a `StoredImage` cannot reach `remove` at all.+ ///+ /// `includingLiveTurn` is false after a replay: by then the live fields+ /// hold the message that started it, and the send is about to hard-link+ /// exactly those files. New Chat takes them too, because nothing is left+ /// drawing any of it.+ private func releaseImagesOfTheConversationBeingLeft(includingLiveTurn: Bool) {+ for pair in conversation.outOfContextPairs {+ for image in pair.user.images {+ if let staged = image.staged { attachmentStore.remove(staged) }+ }+ }+ for turn in conversation.turns {+ for image in turn.images {+ if let staged = image.staged { attachmentStore.remove(staged) }+ }+ }+ guard includingLiveTurn else { return }+ for image in outputImageAttachments {+ if let staged = image.staged { attachmentStore.remove(staged) }+ }+ outputImageAttachments = []+ }++ private func applySampling(_ sampling: ConversationSampling) {+ temperature = sampling.temperature+ topKEnabled = sampling.topKEnabled+ topK = sampling.topK+ topPEnabled = sampling.topPEnabled+ topP = sampling.topP+ // The public app budgets responses automatically. A recorded request+ // limit must not become a fixed cap when a saved chat is opened.+ }++ private func applyRestoreProgress(done: Int, total: Int) {+ phase = .prefill+ livePrefillDone = done+ livePrefillTotal = total+ }++ // MARK: - Performing what a transition asks for++ /// The one place a screen transition turns into work.+ ///+ /// Ten `attachmentStore.remove` sites, two loaders, two hand-backs and four+ /// assignments to `history.selection` used to do this, each with its own+ /// idea of when it applied. A transition that forgets one of them is now a+ /// missing effect in a table test rather than a defect nobody can see.+ func perform(_ effects: [ConversationScreenMachine.Effect]) {+ for effect in effects {+ switch effect {+ case .select(let id):+ history.selection = id+ persistHistorySelection()+ case .dropOutOfContextTurns:+ conversation.dropOutOfContextPairs()+ case .loadDocument(let id, let renderID):+ loadDocument(id: id, renderID: renderID)+ case .applySampling(let sampling):+ // A send may be queued before its replay screen is installed.+ // Its settings cannot be replaced by the click's late read.+ if !isTurnInFlight { applySampling(sampling) }+ case .reportError(let failure):+ error = failure+ case .replay, .startTurn:+ // Read by the send pipeline, which is the thing holding the+ // message: `.replay` is a stage it awaits and `.startTurn` is+ // its permission to go on. Performing either here is what made+ // the send path call itself.+ continue+ case .releaseImagesOfHeldConversation(let includingLiveTurn):+ releaseImagesOfTheConversationBeingLeft(+ includingLiveTurn: includingLiveTurn)+ case .endFailedReplayLineage:+ endLineageAfterFailedReplay()+ case .adoptRestored(let document, let epoch, let kvTokens):+ adoptRestoredConversation(+ document: document, epoch: epoch, kvTokens: kvTokens)+ case .restoreComposer(let pending, let failure):+ // Withdrawn from the transcript as well: what is drawn there is+ // this very message under a prefill placeholder, with nothing+ // underneath it, because the replay it was waiting for never+ // landed.+ restoreComposer(pending, error: failure,+ withdrawingFromTranscript: true)+ }+ }+ }++ private func persistHistorySelection() {+ persistSettings()+ }++ /// The held chat's turns move out of context and keep their pictures:+ /// they are still drawn there, and New Chat releases them along with the+ /// rest. Releasing them here first carried pairs whose thumbnails pointed+ /// at files that no longer existed.+ private func endLineageAfterFailedReplay() {+ let carried = conversation.outOfContextPairs + conversation.completedPairs+ conversation.startNew(carryingOutOfContext: carried)+ storedConversationID = nil+ serviceEpoch = nil+ }++ func prepareServiceRecoveryForReplay(includingLiveTurn: Bool = false) {+ releaseImagesOfTheConversationBeingLeft(includingLiveTurn: includingLiveTurn)+ conversation.startNew(carryingOutOfContext: [])+ serviceEpoch = nil+ outputPromptText = ""+ outputText = ""+ outputImageAttachments = []+ generationTranscriptMailbox?.reset()+ }++ // MARK: - Rename, delete, undo++ public func renameConversation(id: UUID, to title: String) {+ guard canMutateConversation(id: id), let store = conversationStore else { return }+ let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else { return }+ Task { [weak self] in+ do { try await store.rename(id: id, to: trimmed) }+ catch { self?.recordHistoryDiagnostic("\(error)") }+ await self?.refreshHistory()+ }+ }++ /// Collects the image files of a turn the runtime rewound.+ ///+ /// A turn's images are written while the reply is still generating, so a+ /// turn that never reaches the KV leaves them behind — recorded nowhere,+ /// named by digest, and invisible to every other pass. `sweepOrphanImages`+ /// existed for exactly this and had no caller, so those bytes stayed for the+ /// life of the conversation.+ ///+ /// Only after a rewind, never after a completed turn: the sweep parses the+ /// whole transcript, and doing that on every turn would make each one cost+ /// more as the conversation grows.+ func sweepImagesOfRewoundTurn() async {+ guard let binding = conversationBinding, let id = storedConversationID else {+ return+ }+ let store = binding.store+ // An earlier committed turn may have written its images without yet+ // appending their records. They are not orphans until that save settles.+ await awaitPendingPersistence()+ guard !Task.isCancelled,+ isCurrentConversationBinding(generation: binding.generation, store: store) else {+ return+ }+ do {+ let removed = try await store.sweepOrphanImages(in: id)+ if removed > 0 {+ recordHistoryDiagnostic(+ "collected \(removed) image file(s) from a turn that was "+ + "rewound")+ }+ } catch {+ recordHistoryDiagnostic("\(error)")+ }+ }++ /// Ends the image write a rewound turn started.+ ///+ /// Only `persistCompletedTurn` used to clear `pendingTurnImageWrite`, which+ /// a cancelled or failed turn never reaches — so the app read as+ /// permanently mid-write to anything that asked whether a turn was+ /// finished, and the orphan sweep that follows a rewind raced the very+ /// write it exists to collect after. Awaited rather than only cancelled:+ /// a cancelled `Task` is not a finished one, and the sweep deletes every+ /// file no record names.+ func discardPendingTurnImages() async {+ guard let write = pendingTurnImageWrite else { return }+ pendingTurnImageWrite = nil+ write.cancel()+ _ = await write.value+ }++ /// The folder a stored conversation lives in, for opening in Finder.+ ///+ /// The folder rather than a file inside it: what is worth looking at is the+ /// transcript next to its images and its meta, and a directory shows all+ /// three. Nil is a real answer here — a row can outlive its directory if+ /// something outside the app moved it — so it is recorded rather than+ /// returned silently.+ public func conversationFolderURL(for id: UUID) async -> URL? {+ guard let store = conversationStore else {+ recordHistoryDiagnostic("no conversation store is open")+ return nil+ }+ let url = await store.directoryURL(for: id)+ guard FileManager.default.fileExists(atPath: url.path) else {+ recordHistoryDiagnostic("conversation \(id) has no folder on disk")+ return nil+ }+ return url+ }++ /// Deletes a conversation and everything in it, permanently.+ ///+ /// There is no undo, because there is no copy: the alternative was a+ /// `.trash` directory that kept every deleted transcript and image for the+ /// life of the store with nothing to collect them. The row's menu asks+ /// first — an alert for something irreversible is the case the guidelines+ /// make an exception for.+ public func deleteConversation(id: UUID) {+ guard canMutateConversation(id: id), let binding = conversationBinding else { return }+ let store = binding.store+ let generation = binding.generation+ conversationDeletionTask = Task { [weak self] in+ guard let self else { return }+ defer { conversationDeletionTask = nil }+ // The last turn's write may still be running: its image copies+ // are made after the reply lands, and `isTurnInFlight` is already+ // false by then. Deleting under it had the writer recreate the+ // directory and the append leave a headerless transcript behind,+ // which the list then counted as unreadable forever.+ await awaitPendingPersistence()+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return+ }+ do {+ try await store.delete(id: id)+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return+ }+ if storedConversationID == id {+ // The open chat was the one deleted, so its lineage ends+ // here. Keeping the KV and letting the next turn open a+ // fresh file broke the rule the whole design rests on —+ // the transcript equals the model's context. The new file+ // held one exchange while its meta described the whole+ // conversation behind it: a row reading "1,065 tokens" over+ // 22 tokens of record, which the sidebar believes, the+ // context gauge believes, and continuability decides+ // against. Deleting a conversation ends it.+ if let viewed = screen.conversationID, viewed != id {+ // Only the deleted lineage ends. The reader and its+ // composer belong to a different, still-durable chat.+ prepareServiceRecoveryForReplay(includingLiveTurn: true)+ storedConversationID = nil+ pendingServiceRecoveryConversationID = nil+ quarantinedPersistenceLineages.removeAll()+ diagnostics = nil+ } else {+ newChat()+ }+ }+ // If the chat being read is the one deleted, what comes back on+ // screen is the chat the KV is still holding, and that is the+ // row the sidebar highlights: nil left the window showing a+ // conversation whose row was not selected, which is the one+ // state every other path here is careful not to produce. Never+ // the row just deleted, which `newChat` above has usually+ // already cleared.+ let remainingHeldID = storedConversationID == id+ ? nil : storedConversationID+ let deletedViewedRow = screen.conversationID == id+ perform(machine.apply(.deleted(id: id, heldID: remainingHeldID)))+ // The machine's deleted transition returns to a live held row.+ // After an unload there is still a held durable row but no KV;+ // return to its stored copy instead so the next send replays it.+ if deletedViewedRow, let remainingHeldID,+ serviceEpoch != conversation.epoch {+ openConversation(id: remainingHeldID)+ }+ } catch {+ guard isCurrentConversationBinding(generation: generation, store: store) else {+ return+ }+ recordHistoryDiagnostic("\(error)")+ }+ await refreshHistory(store: store, generation: generation)+ }+ }++ public func canMutateConversation(id: UUID) -> Bool {+ conversationStore != nil && history.entry(id) != nil+ && !history.isReadOnlyStore && !isTurnInFlight+ && conversationDeletionTask == nil+ }++ /// Puts a conversation the app cannot replay into the composer as one+ /// message, to be read fresh.+ ///+ /// A different lineage, and labelled as one everywhere it appears: turn one+ /// renders through the chat template, which strips historical thought spans+ /// and trims content, so the model sees a summary of the conversation and+ /// not the conversation. Presenting it as "Continue" is the one thing this+ /// action must never do.+ /// Whether there is anything to re-read.+ ///+ /// The prompt is built from the turns on screen, so a conversation that+ /// could not be read at all has nothing to build from. Offered anyway, the+ /// button started a new chat with an empty composer, which looks like the+ /// action failing silently.+ public var canRereadIntoNewChat: Bool {+ guard case .reading(_, let document, _, _) = screen else { return false }+ return canStartNewChat && !(document?.pairs.isEmpty ?? true)+ }++ public func rereadIntoNewChat() {+ guard canRereadIntoNewChat,+ let document = screen.document else { return }+ let text = Self.rereadPrompt(from: document.pairs)+ newChat()+ promptText = text+ }++ static func rereadPrompt(+ from pairs: [(user: AppChatTurn, assistant: AppChatTurn)]+ ) -> String {+ pairs.map { pair in+ "You: \(pair.user.text)\n\nAssistant: \(pair.assistant.text)"+ }.joined(separator: "\n\n")+ }+}diff --git a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swiftindex d23e6ddc..209424e8 100644--- a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift@@ -30,11 +30,11 @@ public struct AppPresentationSnapshot: Equatable, Sendable {public var livePrefillDone: Intpublic var livePrefillTotal: Intpublic var lastStopReason: AppStopReason?- /// `canLoadModel` and its siblings refuse while a companion operation runs,- /// so the snapshot has to carry it: without it this resolved to+ /// Model lifecycle actions refuse while a companion filesystem mutation+ /// runs, so the snapshot has to carry it: without it this resolved to/// "Installed · Not loaded" with a `.load` action, and the banner rendered a/// fully enabled button that did nothing for the whole transfer.- public var isVisionCompanionOperationInProgress: Bool+ public var isVisionFilesystemMutationInProgress: Boolpublic init(requiresInstallation: Bool,installState: AppModelInstallState,@@ -47,7 +47,7 @@ public struct AppPresentationSnapshot: Equatable, Sendable {livePrefillDone: Int = 0,livePrefillTotal: Int = 0,lastStopReason: AppStopReason? = nil,- isVisionCompanionOperationInProgress: Bool = false) {+ isVisionFilesystemMutationInProgress: Bool = false) {self.requiresInstallation = requiresInstallationself.installState = installStateself.installReadiness = installReadiness@@ -59,7 +59,7 @@ public struct AppPresentationSnapshot: Equatable, Sendable {self.livePrefillDone = livePrefillDoneself.livePrefillTotal = livePrefillTotalself.lastStopReason = lastStopReason- self.isVisionCompanionOperationInProgress = isVisionCompanionOperationInProgress+ self.isVisionFilesystemMutationInProgress = isVisionFilesystemMutationInProgress}}@@ -143,7 +143,7 @@ public struct AppPresentationState: Equatable, Sendable {// Every model action is refused for the duration, so offering one here// would be offering a button that does nothing.- if snapshot.isVisionCompanionOperationInProgress {+ if snapshot.isVisionFilesystemMutationInProgress {return Self(label: "Preparing image support",severity: .active, showsActivity: true)}diff --git a/Sources/TurboFieldfareApp/Core/State/ConversationScreen.swift b/Sources/TurboFieldfareApp/Core/State/ConversationScreen.swiftnew file mode 100644index 00000000..3659e99f--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/State/ConversationScreen.swift@@ -0,0 +1,131 @@+import Foundation++/// What the transcript pane is showing.+///+/// Exactly one case at a time. The six stored fields this replaces —+/// `pendingReplayConversationID`, `storedDisplayPairs`, `archivedPairs`,+/// `storedCopyRenderID`, `isRestoringConversation`, `openedConversationState` —+/// admitted dozens of combinations for the four states that actually exist, and+/// twelve of the feature's defects were two of those fields disagreeing: the+/// chat that was read left on screen under the row returned to, a conversation+/// drawn twice, a replay landing on top of a New Chat.+public enum ConversationScreen: Equatable, Sendable {+ /// The conversation the KV holds, empty or not. Always continuable.+ case live+ /// A stored conversation drawn from disk while the KV keeps `live`.+ ///+ /// `document` is nil until the load lands: reading a conversation is a file+ /// read and continuing it is a full prefill, so the row is drawn at once+ /// and filled when the file has been walked. `renderID` is new on every+ /// entry, including a re-entry into the same conversation, because the+ /// transcript renderer appends and cannot take pairs back — it has to be+ /// told that what is on screen is a different thing to draw.+ case reading(id: UUID, document: ConversationDocument?,+ state: ConversationContinuability, renderID: UUID)+ /// A stored conversation being prefilled into the KV ahead of the turn that+ /// asked for it.+ ///+ /// `pending` is that turn, held out of the composer for the length of the+ /// replay and handed straight back if it fails. `renderID` is carried over+ /// from `reading` rather than derived from the conversation, so the+ /// transcript is not rebuilt at the moment a send starts.+ case replaying(id: UUID, document: ConversationDocument?,+ pending: PreparedTurn, renderID: UUID)+ /// A stored conversation whose transcript could not be read at all.+ ///+ /// The window draws the live conversation, exactly as it did before the row+ /// was clicked; this case only carries why the row that was clicked is not+ /// on screen, so the notice can say so instead of showing the empty state a+ /// chat that was never written also shows.+ case unreadable(id: UUID, error: AppInferenceError)++ /// Which case a screen is, without its payload.+ ///+ /// What the machine's matrix test enumerates. A new screen case forces a+ /// new `Shape` case through the exhaustive switch below, which grows+ /// `allCases`, which fails the completeness test until every event has a+ /// row for it.+ public enum Shape: String, CaseIterable, Sendable {+ case live, reading, replaying, unreadable+ }++ public var shape: Shape {+ switch self {+ case .live: return .live+ case .reading: return .reading+ case .replaying: return .replaying+ case .unreadable: return .unreadable+ }+ }++ public static var allShapes: [Shape] { Shape.allCases }++ /// The stored conversation this screen names, if any. Nil only for `live`.+ public var conversationID: UUID? {+ switch self {+ case .live: return nil+ case .reading(let id, _, _, _): return id+ case .replaying(let id, _, _, _): return id+ case .unreadable(let id, _): return id+ }+ }++ /// The stored conversation as it was read off disk, once it has landed.+ public var document: ConversationDocument? {+ switch self {+ case .live, .unreadable: return nil+ case .reading(_, let document, _, _): return document+ case .replaying(_, let document, _, _): return document+ }+ }++ /// Distinguishes repeated reads of the same conversation across actor hops.+ var documentReadID: UUID? {+ switch self {+ case .reading(_, _, _, let id), .replaying(_, _, _, let id): return id+ case .live, .unreadable: return nil+ }+ }++ /// A reopened conversation is being prefilled into the KV right now.+ ///+ /// Not `isRunning`: no turn is generating, so every guard written against+ /// that let New Chat through mid-replay — and the replay then landed on top+ /// of the empty chat the user had just asked for.+ public var isReplaying: Bool {+ if case .replaying = self { return true }+ return false+ }++ /// The chat on screen is not the one the KV is holding.+ ///+ /// Browsing does not disturb the model: the live conversation stays exactly+ /// where it is, and what is drawn is a copy read off disk. So the live+ /// fields belong to a different chat for as long as this is true, and+ /// nothing may draw them under the one being read.+ public var isShowingStoredCopy: Bool {+ switch self {+ case .reading, .replaying: return true+ case .live, .unreadable: return false+ }+ }++ /// Whether a message typed now has a conversation to go to.+ ///+ /// The composer used to ask only the live conversation, which is always+ /// willing. A row the notice had just called unable to continue could+ /// therefore be sent: its tokens were replayed under a checkpoint they were+ /// not recorded for, or the held chat's KV was dropped for a restore that+ /// was always going to be refused. What is on screen decides, and the+ /// answer is the same one the notice gives.+ public var allowsSend: Bool {+ switch self {+ case .live: return true+ case .reading(_, _, let state, _): return state == .continuable+ // A replay is already carrying a message; the composer is closed+ // until it lands. An unreadable row has nothing to replay, and a send+ // would silently land on the held conversation under the wrong row.+ case .replaying, .unreadable: return false+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/State/ConversationScreenMachine.swift b/Sources/TurboFieldfareApp/Core/State/ConversationScreenMachine.swiftnew file mode 100644index 00000000..1142cd20--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/State/ConversationScreenMachine.swift@@ -0,0 +1,324 @@+import Foundation++/// Every transition of what the window is showing, in one pure value.+///+/// The shape is the one `DecodeConversationGate` already proved in this tree: a+/// value, a typed event, a new value plus the effects the caller performs. The+/// gate has produced no defects while the flags around it produced twelve, and+/// the reason is that a transition nobody thought of is a cell in a table here+/// rather than an interaction between six fields nobody enumerated.+///+/// Two rules hold for every event:+///+/// 1. An event naming a conversation the screen no longer names is a no-op with+/// no effects. Two `guard` lines used to do this by hand for the async load;+/// a replay landing after a delete had no such guard at all.+/// 2. The machine performs nothing. It cannot read a file, start a task, or+/// touch the composer, so a transition cannot half-happen.+public struct ConversationScreenMachine: Equatable, Sendable {+ public private(set) var screen: ConversationScreen = .live++ public init() {}++ /// Starts at a given screen.+ ///+ /// Internal, and used only by the matrix test: it has to put the machine+ /// into every cell without replaying the events that reach one, and a+ /// settable `screen` would let production code do the same.+ init(screen: ConversationScreen) {+ self.screen = screen+ }++ public enum Event: Equatable, Sendable {+ /// A row in the sidebar was clicked. `heldID` and `kvMatchesHeld`+ /// describe the conversation the KV is holding, because clicking the+ /// row it is already holding costs nothing and must not rebuild it.+ case rowClicked(id: UUID, heldID: UUID?, kvMatchesHeld: Bool,+ state: ConversationContinuability, renderID: UUID)+ /// The context in force changed, so the row on screen is worth a+ /// different answer than the one taken when it was clicked. `state` is+ /// that answer, passed as data rather than as a closure so the event+ /// stays `Equatable` and the matrix test can name the cell.+ case contextChanged(state: ConversationContinuability, heldID: UUID?,+ kvMatchesHeld: Bool, renderID: UUID)+ case documentLoaded(id: UUID, renderID: UUID, document: ConversationDocument,+ state: ConversationContinuability)+ case documentFailed(id: UUID, renderID: UUID, AppInferenceError)+ /// A send while a stored conversation is on screen. Its tokens have to+ /// be back in the KV before the turn can be numbered against them.+ case sendRequested(PreparedTurn)+ case replaySucceeded(id: UUID, document: ConversationDocument,+ epoch: UUID, kvTokens: Int)+ /// Putting the conversation back failed for a reason outside it: the+ /// service refused the digest, the service died, a load is in flight.+ /// The record is intact, so the row stays continuable and the send can+ /// be retried once the cause is dealt with. The restore was attempted,+ /// so the held conversation's KV is gone with it.+ case replayFailed(id: UUID, error: AppInferenceError)+ /// The replay never reached the model: a check on this side refused it+ /// first, such as the companion pack being absent for a conversation+ /// with pictures. Distinct from `replayFailed` because nothing was+ /// asked of the service, so the held conversation is exactly where it+ /// was. Reported as a failed replay instead, its intact KV was+ /// abandoned and its staged images deleted for a restore that had not+ /// happened.+ case replayNotStarted(id: UUID, error: AppInferenceError)+ /// What is on disk cannot be replayed: a turn with no recorded tokens,+ /// an image whose placeholders are not where its turn says, a+ /// transcript that will not read. A permanent property of the record,+ /// so the row says so rather than offering the same failure again.+ ///+ /// `state` is what the row shows afterwards: a record that will not+ /// replay by default, or the answer a fresh read of the record gave+ /// when it disagreed with the cached one the click saw.+ case replayRefused(id: UUID, error: AppInferenceError,+ state: ConversationContinuability+ = .cannotReplay(reason: .tokenCountUnknown))+ case newChat+ case deleted(id: UUID, heldID: UUID?)+ /// A load, an unload, a reload or a gate refusal took the KV. Whatever+ /// was on screen stops being a conversation the model can be asked+ /// about.+ case lineageEnded++ /// Which case an event is, without its payload. See+ /// `ConversationScreen.Shape`.+ public enum Shape: String, CaseIterable, Sendable {+ case rowClicked, contextChanged, documentLoaded, documentFailed+ case sendRequested, replaySucceeded, replayFailed, replayNotStarted+ case replayRefused+ case newChat, deleted, lineageEnded+ }++ public var shape: Shape {+ switch self {+ case .rowClicked: return .rowClicked+ case .contextChanged: return .contextChanged+ case .documentLoaded: return .documentLoaded+ case .documentFailed: return .documentFailed+ case .sendRequested: return .sendRequested+ case .replaySucceeded: return .replaySucceeded+ case .replayFailed: return .replayFailed+ case .replayNotStarted: return .replayNotStarted+ case .replayRefused: return .replayRefused+ case .newChat: return .newChat+ case .deleted: return .deleted+ case .lineageEnded: return .lineageEnded+ }+ }++ public static var allShapes: [Shape] { Shape.allCases }+ }++ /// The work a transition asks for. Performed by `AppModel.perform`, which+ /// is the only place any of it happens.+ public enum Effect: Equatable, Sendable {+ /// Which row the sidebar highlights. Always the conversation on screen,+ /// including when that is the live one and including nil.+ case select(UUID?)+ /// The turns of a released KV that were still on screen. A click draws+ /// one conversation and only that one, so they go with everything else+ /// the window was drawing.+ case dropOutOfContextTurns+ case loadDocument(UUID, renderID: UUID)+ /// The window's sliders follow the conversation it is showing.+ case applySampling(ConversationSampling)+ case reportError(AppInferenceError)+ case replay(id: UUID, pending: PreparedTurn)+ /// The staged copies of the conversation the KV is about to stop+ /// holding. Emitted only where it is actually given up: after a replay+ /// succeeds, and on New Chat. Released before a replay instead, a+ /// restore that then failed left the held chat on screen pointing at+ /// files that had already been deleted.+ ///+ /// `includingLiveTurn` covers the pictures the live fields are still+ /// drawing. False after a replay, because by then those belong to the+ /// message that started it and the send is about to hard-link them.+ case releaseImagesOfHeldConversation(includingLiveTurn: Bool)+ /// A restore replaces the service KV before it can fail. The previously+ /// held lineage is therefore gone even though the requested row remains+ /// readable and retryable.+ case endFailedReplayLineage+ case adoptRestored(ConversationDocument, epoch: UUID, kvTokens: Int)+ /// The message the replay was holding goes back to the composer.+ ///+ /// The error is optional because a failure that has already recorded+ /// itself must not be recorded twice: a rewound generation sets+ /// `error` as it ends, and a second copy of the same cause would+ /// replace the one the window is already showing.+ case restoreComposer(PreparedTurn, AppInferenceError?)+ /// The message the replay was holding may start its turn.+ ///+ /// Read by the send pipeline, which is the thing holding the message.+ /// Performing it anywhere else is what made `run()` call itself.+ case startTurn(PreparedTurn)+ }++ public mutating func apply(_ event: Event) -> [Effect] {+ switch event {+ case .rowClicked(let id, let heldID, let kvMatchesHeld, let state,+ let renderID):+ // Refused while a replay runs. The conversation being put into the+ // KV is the one the next turn is numbered against, so drawing+ // another one over it would leave the window naming a chat the send+ // is not going to.+ if screen.isReplaying { return [] }+ return show(id: id, heldID: heldID, kvMatchesHeld: kvMatchesHeld,+ state: state, renderID: renderID)++ case .contextChanged(let state, let heldID, let kvMatchesHeld,+ let renderID):+ // Only the row being read is redrawn: the live conversation's own+ // continuability is not in question, and a replay owns the screen+ // until it lands.+ guard case .reading(let id, _, _, _) = screen else { return [] }+ return show(id: id, heldID: heldID, kvMatchesHeld: kvMatchesHeld,+ state: state, renderID: renderID)++ case .documentLoaded(let id, let requestID, let document, let refreshedState):+ switch screen {+ case .reading(let readingID, _, _, let renderID)+ where readingID == id && renderID == requestID:+ screen = .reading(id: id, document: document, state: refreshedState,+ renderID: renderID)+ // A row that cannot be continued does not move the window's+ // sliders: nothing is going to generate under them.+ return refreshedState == .continuable+ ? [.applySampling(document.meta.sampling)] : []+ case .replaying(let replayingID, _, let pending, let renderID)+ where replayingID == id && renderID == requestID:+ // The click's read can land after the send that started the+ // replay. The transcript still wants it: what is drawn under a+ // replay is the conversation being put back.+ screen = .replaying(id: id, document: document, pending: pending,+ renderID: renderID)+ // Send owns the sampling now; only the transcript may catch up.+ return []+ default:+ return []+ }++ case .documentFailed(let id, let requestID, let error):+ // Not while replaying: that path reads the same file itself and+ // reports its own failure, and taking the screen from it would+ // leave the turn it is holding with nowhere to go back to.+ guard case .reading(let readingID, _, _, let renderID) = screen,+ readingID == id, renderID == requestID else { return [] }+ screen = .unreadable(id: id, error: error)+ return [.reportError(error)]++ case .sendRequested(let pending):+ // A send on the live conversation changes nothing about what is on+ // screen, and a second one during a replay is refused before it+ // gets here. A row that cannot be continued is refused here as+ // well as at the composer: replaying it would put tokens recorded+ // under another checkpoint into the KV, or drop the held chat for+ // a restore the context cannot hold.+ guard case .reading(let id, let document, let state, let renderID)+ = screen, state == .continuable+ else { return [] }+ screen = .replaying(id: id, document: document, pending: pending,+ renderID: renderID)+ return [.replay(id: id, pending: pending)]++ case .replaySucceeded(let id, let document, let epoch, let kvTokens):+ guard case .replaying(let replayingID, _, let pending, _) = screen,+ replayingID == id else { return [] }+ screen = .live+ return [.releaseImagesOfHeldConversation(includingLiveTurn: false),+ .adoptRestored(document, epoch: epoch, kvTokens: kvTokens),+ .select(id),+ .startTurn(pending)]++ case .replayFailed(let id, let error):+ // Nothing about the conversation changed, so the row is what it+ // was. A replay is only ever started from a continuable row — the+ // composer and the `.sendRequested` guard both refuse the others —+ // so that is what it goes back to.+ var effects = endReplay(id: id, state: .continuable, error: error)+ if !effects.isEmpty { effects.insert(.endFailedReplayLineage, at: 0) }+ return effects++ case .replayNotStarted(let id, let error):+ // The same hand-back without the lineage end: the service was+ // never asked, so the held conversation and its pictures stay.+ return endReplay(id: id, state: .continuable, error: error)++ case .replayRefused(let id, let error, let state):+ return endReplay(id: id, state: state, error: error)++ case .newChat:+ screen = .live+ return [.releaseImagesOfHeldConversation(includingLiveTurn: true),+ .select(nil)]++ case .deleted(let id, let heldID):+ // The chat being read is gone, so there is nothing left to draw.+ // What comes back is the chat the KV is still holding, and that is+ // the row the sidebar highlights: nil left the window showing a+ // conversation whose row was not selected.+ guard screen.conversationID == id else { return [] }+ // A replay of the deleted chat cannot land any more, and the send+ // waiting on it stops when it finds the screen gone. The message+ // goes back here, as it does when the KV goes under a replay.+ if case .replaying(_, _, let pending, _) = screen {+ screen = .live+ return [.restoreComposer(pending, nil), .select(heldID)]+ }+ screen = .live+ return [.select(heldID)]++ case .lineageEnded:+ // A replay that loses the KV under it can no longer land: the+ // send waiting on it will find the screen gone and stop, so the+ // message it was holding goes back to the composer here. Dropped+ // with the screen instead, the prompt and its staged pictures were+ // never handed back to anything.+ if case .replaying(_, _, let pending, _) = screen {+ screen = .live+ return [.restoreComposer(pending, nil), .select(nil)]+ }+ screen = .live+ return [.select(nil)]+ }+ }++ /// The one rule both a click and a context change follow.+ private mutating func show(id: UUID, heldID: UUID?, kvMatchesHeld: Bool,+ state: ConversationContinuability,+ renderID: UUID) -> [Effect] {+ // The conversation the model is already holding. Looking at another+ // chat and coming back used to cost a full replay of a conversation the+ // KV had never let go of, because opening anything started a new+ // lineage on this side. Nothing here has to be rebuilt: the transcript,+ // the epoch and the service's cache all still agree.+ //+ // Whatever its record says. `.cannotReplay` is about putting the+ // record back, and the held chat is not being put back: a turn whose+ // stored picture failed to write is still in the KV. Requiring+ // `.continuable` here read that chat as a copy the composer refuses,+ // with New Chat as the only way out of a conversation the model was+ // still holding. `.needsContext` is different: the context in force+ // no longer holds the chat, so the copy and its notice are the truth.+ if id == heldID, kvMatchesHeld {+ if case .needsContext = state {} else {+ screen = .live+ return [.select(id), .dropOutOfContextTurns]+ }+ }+ screen = .reading(id: id, document: nil, state: state,+ renderID: renderID)+ return [.select(id), .dropOutOfContextTurns, .loadDocument(id, renderID: renderID)]+ }++ private mutating func endReplay(id: UUID,+ state: ConversationContinuability,+ error: AppInferenceError) -> [Effect] {+ guard case .replaying(let replayingID, let document, let pending,+ let renderID) = screen,+ replayingID == id else { return [] }+ screen = .reading(id: id, document: document, state: state,+ renderID: renderID)+ return [.restoreComposer(pending, error)]+ }+}diff --git a/Sources/TurboFieldfareApp/Core/State/PreparedTurn.swift b/Sources/TurboFieldfareApp/Core/State/PreparedTurn.swiftnew file mode 100644index 00000000..91bfcb7b--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/State/PreparedTurn.swift@@ -0,0 +1,31 @@+import Foundation++/// The message the composer handed over, carried as one value from the click to+/// the commit or back to the composer.+///+/// Its images are the composer's staged files, moved rather than copied: the+/// composer stops drawing them the moment this exists, and whichever stage+/// fails hands both halves back together. The prompt and the images used to+/// travel separately through the composer, the live fields and the screen, and+/// three defects were one half of the send path not knowing what the other had+/// already done with them — a replay overwriting the message that started it, a+/// hand-back that dropped the pictures, a second Generate starting a second+/// replay of the same chat.+public struct PreparedTurn: Equatable, Sendable {+ public let prompt: String+ public let images: [StagedImage]+ public init(prompt: String, images: [StagedImage]) {+ self.prompt = prompt+ self.images = images+ }++ /// The same message carried by different files.+ ///+ /// A turn that reaches the model is carried by the retained hard links, not+ /// by the composer's own copies: those are deleted at the hand-off, so+ /// handing them back after a rewind would give the user thumbnails with no+ /// files behind them.+ func carrying(_ images: [StagedImage]) -> PreparedTurn {+ PreparedTurn(prompt: prompt, images: images)+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/App/RootView.swift b/Sources/TurboFieldfareApp/Mac/App/RootView.swiftindex ad1bce9a..d94792e7 100644--- a/Sources/TurboFieldfareApp/Mac/App/RootView.swift+++ b/Sources/TurboFieldfareApp/Mac/App/RootView.swift@@ -7,16 +7,34 @@ struct RootView: View {@State private var conversationChromeHeight: CGFloat = 0var body: some View {+ // Three columns in one HStack, not a NavigationSplitView. The split+ // view brought a second sidebar toggle of its own, moved our controls+ // whenever the sidebar opened, and left the sidebar column inert to the+ // mouse. Both side panels are now the same shape — a fixed-width column+ // beside a flexible middle — which is also what keeps a narrow window+ // from slicing one in half: the sides hold their width and the+ // transcript gives up the space.HStack(spacing: 0) {- primaryContent- .frame(minWidth: 720, maxWidth: .infinity, maxHeight: .infinity)-- Divider()-- InspectorView(model: model)- .frame(width: 320)+ // Collapsed by animating an outer frame to zero and clipping, not+ // by leaving the hierarchy. A conditional panel with a `.move`+ // transition is torn down and rebuilt on every toggle, so its+ // contents relaid out mid-slide and the sibling `Divider()` — which+ // had no transition of its own — popped in and out a frame ahead of+ // the panel. Here the panel keeps its own width throughout, its+ // rule is part of it, and only the window the two are seen through+ // changes size.+ ConversationSidebarView(model: model)+ .frame(width: Self.sidebarWidth).frame(maxHeight: .infinity).background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .trailing) { verticalRule }+ // Trailing, so the panel slides out past the left edge rather+ // than being wiped away in place.+ .frame(width: model.isSidebarVisible ? Self.sidebarWidth : 0,+ alignment: .trailing)+ .clipped()++ detail}.containerBackground(for: .window) {LinearGradient(@@ -40,16 +58,84 @@ struct RootView: View {}}- private var primaryContent: some View {- Group {- if model.requiresModelInstallation {- ModelInstallView(model: model)- } else {- conversationView- }+ static let sidebarWidth: CGFloat = 260+ static let inspectorWidth: CGFloat = 320+ /// How a side panel opens and closes.+ ///+ /// Carried by `withAnimation` around the state change itself, not by an+ /// `.animation(value:)` on this view. Attached further down — to the panel+ /// frames — the surrounding `HStack` took the final widths immediately and+ /// only the panel slid. Attached here at the root it animated the whole+ /// subtree, and that swept up anything else changing in the same run loop+ /// turn: clicking a toggle put its own button into the pressed state, whose+ /// release then faded back in over the length of the slide, so the control+ /// just clicked read as having disappeared. An explicit transaction covers+ /// the state change and nothing else.+ static let panelSlide: Animation = .smooth(duration: 0.22)+ /// What the transcript keeps when both panels are open at the window's+ /// minimum width. Lower than the 720 the old two-column layout could+ /// afford, because a third panel has to come from somewhere — and the+ /// alternative, letting a panel be clipped, is the thing this layout exists+ /// to prevent.+ ///+ /// Measured against the status row, which is the widest thing this column+ /// has to hold: the two chat controls, the pill, and the Inspector toggle.+ /// At 440 the pill ran out of room and truncated the model's own name to+ /// "Gem…", which is the one string on that row that has to stay readable.+ static let transcriptMinimumWidth: CGFloat = 530++ private var detail: some View {+ HStack(spacing: 0) {+ primaryContent+ .frame(minWidth: Self.transcriptMinimumWidth,+ maxWidth: .infinity, maxHeight: .infinity)+ // Whatever this column holds stays inside it, including for+ // the frame or two of a slide when its width has not caught up.+ .clipped()++ InspectorView(model: model)+ .frame(width: Self.inspectorWidth)+ .frame(maxHeight: .infinity)+ .background(Color(nsColor: .windowBackgroundColor))+ .overlay(alignment: .leading) { verticalRule }+ .frame(width: model.isInspectorVisible ? Self.inspectorWidth : 0,+ alignment: .leading)+ .clipped()}- .safeAreaInset(edge: .top, spacing: 0) {+ }++ /// The rule between two columns, drawn as part of the panel it belongs to.+ ///+ /// `Divider()` has no orientation of its own in an overlay — it reads the+ /// enclosing layout, and an overlay has none to read — so this is an+ /// explicit one-point rule in the separator colour.+ private var verticalRule: some View {+ Rectangle()+ .fill(Color(nsColor: .separatorColor))+ .frame(width: 1)+ }++ /// The status row is stacked above the content, not attached as a safe-area+ /// inset.+ ///+ /// `safeAreaInset` resolves its content's width a layout pass behind the+ /// container's, which is invisible at rest and wrong for the length of a+ /// panel slide: the row stayed at the width it had before the column+ /// started moving, so its leading control fell outside the column and was+ /// clipped away mid-animation. A stack is laid out in the same pass as the+ /// column that holds it.+ private var primaryContent: some View {+ VStack(spacing: 0) {StatusHUDView(model: model)++ Group {+ if model.requiresModelInstallation {+ ModelInstallView(model: model)+ } else {+ conversationView+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)}}@@ -91,6 +177,7 @@ struct RootView: View {private var conversationChrome: some View {VStack(spacing: 10) {ErrorBanner(model: model)+ ConversationStateNoticeView(model: model)if model.shouldShowPromptExamples {PromptExamplesView { preset inmodel.promptText = preset.promptdiff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swiftindex a4828727..f8b3dc4a 100644--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift@@ -10,11 +10,65 @@ private final class ForegroundAppDelegate: NSObject, NSApplicationDelegate {/// Set by the scene so quitting can release this session's staged images.@MainActor static var model: AppModel?+ /// The last exchange's write finishes before the process goes.+ ///+ /// It starts when the reply lands and, with pictures, runs for seconds+ /// after the send has returned; quitting under it lost the exchange and+ /// released the staged files it was still reading. Bounded, so a write+ /// that hangs cannot keep the app alive.+ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {+ guard let model = MainActor.assumeIsolated({ Self.model }) else {+ return .terminateNow+ }+ Task { @MainActor in+ if await !model.awaitPendingPersistence(timeout: .seconds(30)) {+ FileHandle.standardError.write(Data(+ "Conversation persistence did not finish before the quit deadline; the latest exchange may not be saved.\n".utf8))+ }+ sender.reply(toApplicationShouldTerminate: true)+ }+ return .terminateLater+ }+func applicationWillTerminate(_ notification: Notification) {- MainActor.assumeIsolated { Self.model?.releaseAllAttachments() }+ MainActor.assumeIsolated { Self.model?.shutdownForTermination() }+ }++ /// A second window that opened while another held the store's lock can take+ /// it once that one quits.+ ///+ /// Two triggers, because one of them is not enough. Coming forward is what+ /// the user does after closing the other copy — but if this window is+ /// already frontmost when the other quits, that never fires, and the notice+ /// stayed until the next time they switched away and back. Watching for a+ /// peer of this app terminating covers exactly that case.+ func applicationDidBecomeActive(_ notification: Notification) {+ MainActor.assumeIsolated {+ Self.model?.reacquireStoreIfPossible()+ Self.model?.recheckVisionPackAtCurrentLocation()+ }+ }++ private var peerObserver: (any NSObjectProtocol)?++ private func watchForPeersQuitting() {+ peerObserver = NSWorkspace.shared.notificationCenter.addObserver(+ forName: NSWorkspace.didTerminateApplicationNotification,+ object: nil, queue: .main+ ) { notification in+ let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey]+ as? NSRunningApplication+ // Another copy of this same executable, not any app that quit.+ guard app?.bundleIdentifier == Bundle.main.bundleIdentifier+ || app?.executableURL == Bundle.main.executableURL else {+ return+ }+ MainActor.assumeIsolated { Self.model?.reacquireStoreIfPossible() }+ }}func applicationDidFinishLaunching(_ notification: Notification) {+ watchForPeersQuitting()NSApp.setActivationPolicy(.regular)if let icon = MacAppIcon.load() {NSApp.applicationIconImage = icon@@ -45,7 +99,8 @@ struct TurboFieldfareMacApp: App {var body: some Scene {Window("TurboFieldfare", id: "main") {RootView(model: model)- .frame(minWidth: 1040, minHeight: 560)+ // The three columns at their minimums, plus their dividers.+ .frame(minWidth: 1112, minHeight: 560)// Once, when the window first appears: the setting is read// from disk in init, and loadModelAtLaunchIfEnabled ignores a// model that is missing or already busy.@@ -67,10 +122,37 @@ struct TurboFieldfareMacApp: App {+ "pack again.")}}+ // No toolbar at all. The window's controls live in the status strip+ // beside the model name, so a title bar here would be an empty strip+ // above the content with nothing in it..windowStyle(.hiddenTitleBar)- .defaultSize(width: 1040, height: 720)+ // Above the minimum the three columns impose (260 + 530 + 320 plus+ // dividers), so the window never opens already clamped.+ .defaultSize(width: 1200, height: 780).windowResizability(.contentMinSize).commands {+ CommandGroup(replacing: .newItem) {+ Button("New Chat") { model.newChat() }+ .keyboardShortcut("n", modifiers: .command)+ .disabled(!model.canStartNewChat)+ }+ // `.sidebar` is the placement for commands that control the app's+ // panels, and replacing it is what makes these items ours: the+ // system's would route through the split view's own toggle, which+ // was removed so the button, the menu item and the shortcut are one+ // action against one persisted setting.+ CommandGroup(replacing: .sidebar) {+ Button(WindowControlsPresentation.sidebarToggleHelp(+ isVisible: model.isSidebarVisible)) {+ withAnimation(RootView.panelSlide) { model.toggleSidebar() }+ }+ .keyboardShortcut("s", modifiers: [.command, .control])+ Button(WindowControlsPresentation.inspectorToggleHelp(+ isVisible: model.isInspectorVisible)) {+ withAnimation(RootView.panelSlide) { model.toggleInspector() }+ }+ .keyboardShortcut("i", modifiers: [.command, .control])+ }CommandGroup(replacing: .appInfo) {Button("About TurboFieldfare") {NSApp.orderFrontStandardAboutPanel(diff --git a/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swift b/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swiftindex 67fcfa12..612f536a 100644--- a/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swift+++ b/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swift@@ -25,6 +25,7 @@ struct ErrorBanner: View {.contentShape(Circle())}.buttonStyle(.plain)+ .accessibilityIdentifier(.bannerErrorDismiss)}.padding(.horizontal, 14).padding(.vertical, 8)diff --git a/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swift b/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swiftindex 8c8f299c..f97f4648 100644--- a/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swift+++ b/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swift@@ -16,7 +16,7 @@ struct GenerateControl: View {private var generateButton: some View {Button {- model.run()+ model.send()} label: {Label("Generate", systemImage: "arrow.up").font(.callout.weight(.semibold))@@ -33,6 +33,7 @@ struct GenerateControl: View {.keyboardShortcut(.return, modifiers: .command).disabled(!model.canRun).opacity(model.canRun ? 1 : 0.62)+ .accessibilityIdentifier(.composerGenerate)}private var runningPill: some View {@@ -73,6 +74,7 @@ struct GenerateControl: View {.keyboardShortcut(.cancelAction).disabled(!model.canCancel).help("Stop generation")+ .accessibilityIdentifier(.composerStop).animation(.smooth(duration: 0.2), value: model.presentation.label)}}diff --git a/Sources/TurboFieldfareApp/Mac/Components/HUDMetricView.swift b/Sources/TurboFieldfareApp/Mac/Components/HUDMetricView.swiftindex 9c9d4fa5..7c2c54e4 100644--- a/Sources/TurboFieldfareApp/Mac/Components/HUDMetricView.swift+++ b/Sources/TurboFieldfareApp/Mac/Components/HUDMetricView.swift@@ -1,9 +1,11 @@import SwiftUI+import TurboFieldfareMacPresentationstruct HUDMetricView: View {let value: Stringlet label: Stringvar animated = true+ let identifier: AccessibilityIDvar body: some View {VStack(spacing: 1) {@@ -18,5 +20,8 @@ struct HUDMetricView: View {.foregroundStyle(.secondary)}.frame(minWidth: 56)+ // One element, so the driver reads the figure by its identifier.+ .accessibilityElement(children: .combine)+ .accessibilityIdentifier(identifier)}}diff --git a/Sources/TurboFieldfareApp/Mac/Components/ModelActionBanner.swift b/Sources/TurboFieldfareApp/Mac/Components/ModelActionBanner.swiftindex 2e28aafd..8b5f79c1 100644--- a/Sources/TurboFieldfareApp/Mac/Components/ModelActionBanner.swift+++ b/Sources/TurboFieldfareApp/Mac/Components/ModelActionBanner.swift@@ -1,5 +1,6 @@import TurboFieldfareAppCoreimport SwiftUI+import TurboFieldfareMacPresentationstruct ModelActionBanner: View {@Bindable var model: AppModel@@ -20,6 +21,7 @@ struct ModelActionBanner: View {}.buttonStyle(.borderedProminent).controlSize(.small)+ .accessibilityIdentifier(.bannerModelAction)}.padding(.horizontal, 14).padding(.vertical, 8)diff --git a/Sources/TurboFieldfareApp/Mac/Components/ModelStatusBadge.swift b/Sources/TurboFieldfareApp/Mac/Components/ModelStatusBadge.swiftindex a39d8688..cb5f6845 100644--- a/Sources/TurboFieldfareApp/Mac/Components/ModelStatusBadge.swift+++ b/Sources/TurboFieldfareApp/Mac/Components/ModelStatusBadge.swift@@ -1,5 +1,6 @@import TurboFieldfareAppCoreimport SwiftUI+import TurboFieldfareMacPresentationstruct ModelStatusBadge: View {let model: AppModel@@ -13,6 +14,7 @@ struct ModelStatusBadge: View {.help(model.installDescriptor.repoID).accessibilityLabel("Model").accessibilityValue(model.installDescriptor.repoID)+ .accessibilityIdentifier(.hudStatus)}}diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swiftindex 10a26d6c..4bf4d52a 100644--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift@@ -26,11 +26,9 @@ struct InspectorView: View {.background(Color(nsColor: .windowBackgroundColor))}- /// Shown while it has something to say, hidden once it does not. Unlike- /// root this does not require an installed text model: the empty state is- /// exactly where someone decides whether this app does what they need, and- /// hiding image support until after a 14.62 GB download meant nobody found- /// out it existed. It still collapses once the pack is installed and healthy.+ /// The section stays visible after installation because Remove is part of+ /// the supported lifecycle. It is also visible before text installation so+ /// image support is discoverable before the larger download starts.private var showsVisionSection: Bool {VisionSectionVisibility.shows(visionRuntimeEnabled: model.visionRuntimeEnabled,@@ -110,8 +108,8 @@ struct InspectorView: View {Text("Free \(MetricFormat.storage(requirement.shortfallBytes)) more storage.").font(.caption).foregroundStyle(.orange)- } else if model.isVisionCompanionOperationInProgress {- Text("Model actions stay unavailable until this finishes. "+ } else if model.isVisionFilesystemMutationInProgress {+ Text("Model actions stay unavailable until this filesystem change finishes. "+ "Your prompt, images, and transcript are kept.").font(.caption).foregroundStyle(.secondary)@@ -129,33 +127,39 @@ struct InspectorView: View {if model.isInstallingVisionPack {Button("Cancel", action: model.cancelVisionInstall).disabled(!model.canCancelVisionInstall)+ .accessibilityIdentifier(.visionCancel)} else if case .readyToActivate = model.visionInstallState {Button("Discard", role: .destructive) {model.discardVisionPackDownload()}.disabled(!model.canDiscardVisionPackDownload)+ .accessibilityIdentifier(.visionDiscard)if model.isVisionRuntimeSupported {Button("Activate", action: model.activateVisionPack).buttonStyle(.borderedProminent).disabled(!model.canActivateVisionPack)+ .accessibilityIdentifier(.visionActivate)}} else if model.isVisionPackInstalled {Button("Remove", role: .destructive) {model.requestVisionPackRemoval()}.disabled(!model.canRemoveVisionPack)+ .accessibilityIdentifier(.visionRemove)} else {if model.hasVisionPackDirectory {Button("Remove", role: .destructive) {model.requestVisionPackRemoval()}- .disabled(!model.canRemoveVisionPack)+ .disabled(!model.canRemoveVisionPack)+ .accessibilityIdentifier(.visionRemove)}if model.hasPartialVisionPackDownload {Button("Discard", role: .destructive) {model.discardVisionPackDownload()}.disabled(!model.canDiscardVisionPackDownload)+ .accessibilityIdentifier(.visionDiscard)}if model.isVisionRuntimeSupported {Button(visionInstallButtonLabel) {@@ -163,6 +167,7 @@ struct InspectorView: View {}.buttonStyle(.borderedProminent).disabled(!model.canInstallVisionPack)+ .accessibilityIdentifier(.visionInstall)}}}@@ -221,23 +226,47 @@ struct InspectorView: View {}.buttonStyle(.borderless).help("Copy model path")+ .accessibilityIdentifier(.inspectorCopyPath)}}if model.canUnloadModel {Button("Unload Model", action: model.unloadModel)+ .accessibilityIdentifier(.inspectorUnload)}LabeledContent("State") {Text(model.presentation.label).font(.caption).foregroundStyle(.secondary)}- if model.requiresModelInstallation {- LabeledContent("Download") {- Text(MetricFormat.storage(model.installDescriptor.approximateDownloadBytes))+ LabeledContent("Download") {+ Text(MetricFormat.storage(model.installDescriptor.approximateDownloadBytes))+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ if let metrics = model.modelStorageMetrics {+ LabeledContent("Installed logical") {+ Text(MetricFormat.storage(metrics.logicalBytes)).font(.caption.monospacedDigit()).foregroundStyle(.secondary)}- LabeledContent("Installed size") {+ LabeledContent("Installed allocated") {+ Text(MetricFormat.storage(metrics.allocatedBytes))+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ if let available = metrics.availableBytes {+ LabeledContent("Available") {+ Text(MetricFormat.storage(available))+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ }+ } else if let metricsError = model.modelStorageMetricsError {+ Text(metricsError)+ .font(.caption)+ .foregroundStyle(.orange)+ } else if model.requiresModelInstallation {+ LabeledContent("Expected installed") {Text(MetricFormat.storage(model.installDescriptor.installedBytes)).font(.caption.monospacedDigit()).foregroundStyle(.secondary)@@ -252,13 +281,25 @@ struct InspectorView: View {}}.disabled(model.isRunning || model.isInstallingModel- || model.isVisionCompanionOperationInProgress)+ || model.isVisionFilesystemMutationInProgress)+ }++ /// The context is settable only through the model, because changing it has+ /// to redraw a stored conversation against the new answer to "can this be+ /// continued". A plain binding would set the value and leave the window+ /// describing the old one.+ private var contextTokensBinding: Binding<Int> {+ Binding {+ model.maxContextTokens+ } set: { tokens in+ model.setMaxContextTokens(tokens)+ }}private var memorySection: some View {Section("Memory") {LabeledContent("Context") {- Picker("Context", selection: $model.maxContextTokens) {+ Picker("Context", selection: contextTokensBinding) {ForEach(AppContextLengthOption.allCases) { option inText(option.menuLabel).tag(option.tokens)}@@ -266,6 +307,7 @@ struct InspectorView: View {.pickerStyle(.menu).labelsHidden().fixedSize()+ .accessibilityIdentifier(.inspectorContext)}LabeledContent("Slots") {Picker("Slots", selection: $model.runtimeOptions.expertCacheSlots) {@@ -276,13 +318,14 @@ struct InspectorView: View {.pickerStyle(.menu).labelsHidden().fixedSize()+ .accessibilityIdentifier(.inspectorSlots)}Text("More slots can improve decode speed by keeping more experts in memory, but they also use more RAM. Changes are compared with 8K context and 16 slots and apply after reloading the model.").font(.caption).foregroundStyle(.secondary)}.disabled(model.isRunning || model.loadState.isLoading- || model.isVisionCompanionOperationInProgress)+ || model.isVisionFilesystemMutationInProgress)}private var generationSection: some View {@@ -290,6 +333,7 @@ struct InspectorView: View {LabeledContent("Temperature") {HStack(spacing: 8) {Slider(value: $model.temperature, in: 0...2, step: 0.05)+ .accessibilityIdentifier(.inspectorTemperature)Text(model.temperature, format: .number.precision(.fractionLength(2))).monospacedDigit().frame(width: 36, alignment: .trailing)@@ -300,21 +344,25 @@ struct InspectorView: View {.foregroundStyle(.secondary)Toggle("Top-K", isOn: $model.topKEnabled).toggleStyle(.switch)+ .accessibilityIdentifier(.inspectorTopK)if model.topKEnabled {LabeledContent("K value") {Stepper(value: $model.topK, in: 1...256, step: 1) {Text("\(model.topK)").monospacedDigit()}.fixedSize()+ .accessibilityIdentifier(.inspectorTopKValue)}}Toggle("Top-P", isOn: $model.topPEnabled).toggleStyle(.switch).disabled(!model.topKEnabled)+ .accessibilityIdentifier(.inspectorTopP)if model.topKEnabled && model.topPEnabled {LabeledContent("P value") {HStack(spacing: 8) {Slider(value: $model.topP, in: 0.01...1, step: 0.01)+ .accessibilityIdentifier(.inspectorTopPValue)Text(model.topP, format: .number.precision(.fractionLength(2))).monospacedDigit().frame(width: 36, alignment: .trailing)@@ -323,12 +371,13 @@ struct InspectorView: View {}}.disabled(model.isRunning || model.loadState.isLoading- || model.isVisionCompanionOperationInProgress)+ || model.isVisionFilesystemMutationInProgress)}private var runtimeSection: some View {Section("Runtime") {Toggle("Prefill", isOn: $model.runtimeOptions.prefillEnabled)+ .accessibilityIdentifier(.inspectorPrefill)VStack(alignment: .leading, spacing: 8) {Text("RDADVISE")Picker("RDADVISE", selection: $model.runtimeOptions.rdadvisePolicy) {@@ -338,6 +387,7 @@ struct InspectorView: View {}.pickerStyle(.segmented).labelsHidden()+ .accessibilityIdentifier(.inspectorRDAdvise)}Text("RDADVISE is experimental. It may speed up short decodes but slow down long decodes.").font(.caption)@@ -349,7 +399,7 @@ struct InspectorView: View {}}.disabled(model.isRunning || model.loadState.isLoading- || model.isVisionCompanionOperationInProgress)+ || model.isVisionFilesystemMutationInProgress)}}diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swiftindex eedc1b02..0057a8f5 100644--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift@@ -6,12 +6,36 @@ struct StatusHUDView: View {let model: AppModelvar body: some View {- strip- .padding(.top, 10)- .padding(.leading, 84)- .padding(.trailing, 20)+ // The controls flank the pill rather than sitting in it. The pill is+ // the model's state — what it is, what it is doing, what it costs — and+ // a button inside it reads as part of that reading rather than as+ // something to press. Outside, each toggle also sits on the side of the+ // window it opens.+ HStack(spacing: Self.gap) {+ chatControls+ // Yields first when the row is squeezed. Without this the HStack+ // takes the space out of every child at once and the two rigid+ // controls beside the pill end up drawn on top of each other.+ strip+ .layoutPriority(-1)+ inspectorToggle+ }+ .padding(.top, 10)+ // No clearance for the traffic lights. This row is not beside them:+ // the window's title-bar inset puts it 42 points down and the lights+ // end at 22, so nothing here ever reaches them. Insetting for them+ // anyway — first the whole column, then just this row — only opened a+ // hole to the left of the controls with nothing in it.+ .padding(.horizontal, Self.gap)}+ /// One spacing for the whole row: panel edge to button, button to pill,+ /// pill to button, button to panel edge. Two different values — 20 outside+ /// and 10 either side of the pill — made the controls read as sitting+ /// closer to the pill on one side than the other even though the numbers+ /// mirrored.+ private static let gap: CGFloat = 12+private var strip: some View {HStack(spacing: 12) {ModelStatusBadge(model: model)@@ -19,19 +43,22 @@ struct StatusHUDView: View {PhaseLabel(model: model)Spacer(minLength: 12)if showsMetrics {- HUDMetricView(value: rateText, label: "tok/s", animated: !model.isRunning)+ HUDMetricView(value: rateText, label: "tok/s", animated: !model.isRunning,+ identifier: .hudRate)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)+ animated: !model.isRunning, identifier: .hudContext).help(contextHelp)}HStack(spacing: 2) {- HUDMetricView(value: memoryText, label: "memory", animated: !model.isRunning)+ HUDMetricView(value: memoryText, label: "memory", animated: !model.isRunning,+ identifier: .hudMemory).help(memoryHelp)InfoPopoverButton(subject: "Memory", text: memoryHelp, arrowEdge: .bottom)+ .accessibilityIdentifier(.hudMemoryInfo)}}}@@ -48,6 +75,41 @@ struct StatusHUDView: View {.gesture(WindowDragGesture())}+ /// Show or hide the chat list, and start a new chat.+ ///+ /// These lived in the window toolbar, beside the traffic lights. That put+ /// them in a strip of their own above the content, in a corner with no+ /// relation to anything. They belong on the one row this window uses for+ /// its chrome, at the end nearest the list they open.+ private var chatControls: some View {+ HStack(spacing: 4) {+ StripControlButton(+ systemImage: "sidebar.leading",+ help: WindowControlsPresentation.sidebarToggleHelp(+ isVisible: model.isSidebarVisible),+ identifier: .stripSidebar,+ action: { withAnimation(RootView.panelSlide) { model.toggleSidebar() } })++ StripControlButton(+ systemImage: "square.and.pencil",+ help: WindowControlsPresentation.newChatHelp,+ identifier: .stripNewChat,+ action: model.newChat)+ .disabled(!model.canStartNewChat)+ }+ }++ /// The mirror of the sidebar toggle, at the end of the row nearest the+ /// panel it controls.+ private var inspectorToggle: some View {+ StripControlButton(+ systemImage: "sidebar.trailing",+ help: WindowControlsPresentation.inspectorToggleHelp(+ isVisible: model.isInspectorVisible),+ identifier: .stripInspector,+ action: { withAnimation(RootView.panelSlide) { model.toggleInspector() } })+ }+/// 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 {@@ -139,6 +201,7 @@ private struct PhaseLabel: View {.accessibilityElement(children: .ignore).accessibilityLabel("Model status").accessibilityValue(model.presentation.label)+ .accessibilityIdentifier(.hudPhase)}private enum Content {@@ -169,3 +232,53 @@ private struct PulsingDot: View {}}}++/// One icon control on the status row, beside the pill.+///+/// Plain, not bordered: the pill is the only filled shape on this row, and+/// giving each toggle one of its own would put three competing capsules across+/// the top of the window. The hover highlight is what says it is pressable.+private struct StripControlButton: View {+ let systemImage: String+ let help: String+ let identifier: AccessibilityID+ let action: () -> Void+ @State private var isHovering = false+ @Environment(\.isEnabled) private var isEnabled++ var body: some View {+ Button(action: action) {+ Image(systemName: systemImage)+ .font(.system(size: 16, weight: .regular))+ .frame(width: 32, height: 32)+ .background {+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ .fill(isHovering && isEnabled+ ? Color.primary.opacity(0.09)+ : Color.clear)+ }+ .contentShape(Rectangle())+ }+ .buttonStyle(StripControlButtonStyle())+ .foregroundStyle(isEnabled ? Color.primary : Color.secondary.opacity(0.5))+ .onHover { isHovering = $0 }+ .help(help)+ .accessibilityLabel(help)+ .accessibilityIdentifier(identifier)+ }+}++/// Press feedback that owns its own timing.+///+/// `.plain` dims the label while the mouse is down and restores it on release —+/// inside whatever animation is in flight. Clicking a panel toggle starts one+/// that covers the window, so the button that was just pressed faded back in+/// over the whole slide and read as having disappeared. This says how long a+/// press takes and refuses the ambient transaction.+private struct StripControlButtonStyle: ButtonStyle {+ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .opacity(configuration.isPressed ? 0.45 : 1)+ .animation(.easeOut(duration: 0.08), value: configuration.isPressed)+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Generation/ConversationStateNoticeView.swift b/Sources/TurboFieldfareApp/Mac/Generation/ConversationStateNoticeView.swiftnew file mode 100644index 00000000..41c1ddfc--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Generation/ConversationStateNoticeView.swift@@ -0,0 +1,57 @@+import SwiftUI+import TurboFieldfareAppCore+import TurboFieldfareMacPresentation++/// The banner above the composer when the chat on screen cannot be continued.+///+/// Above the composer rather than in an alert: alerts are not for information,+/// and this is information about something the user is looking at. It names the+/// consequence of the fix as well as the fix — raising the context reloads the+/// model and ends the open chat, which is not a thing to find out afterwards.+struct ConversationStateNoticeView: View {+ let model: AppModel++ var body: some View {+ if let content = ConversationStateNotice.content(+ for: model.openedConversationState,+ currentContext: model.maxContextTokens) {+ VStack(alignment: .leading, spacing: 8) {+ Text(content.title).font(.headline)+ Text(content.message)+ .font(.callout)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ HStack(spacing: 12) {+ if let required = content.requiredContext,+ let option = AppContextLengthOption.allCases.first(where: {+ $0.tokens >= required+ }) {+ Button("Raise Context to \(option.shortLabel)") {+ model.setMaxContextTokens(option.tokens)+ }+ .accessibilityIdentifier(.noticeRaiseContext)+ }+ Button("Start New Chat") { model.newChat() }+ .disabled(!model.canStartNewChat)+ .accessibilityIdentifier(.noticeNewChat)+ if content.offersReread {+ Button("Re-read Into a New Chat") { model.rereadIntoNewChat() }+ .disabled(!model.canRereadIntoNewChat)+ .accessibilityIdentifier(.noticeReread)+ .help("Starts a different conversation from the same "+ + "text. The model reads it fresh, so its replies "+ + "will not be the ones above.")+ }+ }+ }+ .padding(12)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(+ RoundedRectangle(cornerRadius: 10, style: .continuous)+ .fill(Color(nsColor: .controlBackgroundColor)))+ .overlay(+ RoundedRectangle(cornerRadius: 10, style: .continuous)+ .strokeBorder(Color.secondary.opacity(0.25)))+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swiftindex 8d2cd4a4..dcd35c69 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift@@ -42,16 +42,21 @@ struct OutputPaneView: View {IncrementalTranscriptView(history: model.transcriptHistory,contextBreak: model.transcriptContextBreak,- conversationEpoch: model.conversation.epoch,+ conversationEpoch: model.displayedTranscriptID,lastAnswer: model.outputResponsePlainText,conversationPlainText: model.outputConversationPlainText,- requestNewChat: model.isRunning ? nil : { model.newChat() },- prompt: model.outputPromptText,- images: model.outputImageAttachments,- output: model.outputText,- mailbox: model.generationTranscriptMailbox,- isTerminal: !model.isRunning,- showsPrefillPlaceholder: model.isRunning+ requestNewChat: model.isTurnInFlight ? nil : { model.newChat() },+ // Blank while a stored copy is on screen. The live fields hold the+ // chat the KV is still keeping, which is a different conversation+ // from the one being read, and drawing it here would append one+ // chat's newest exchange to another's transcript.+ prompt: model.showsLiveTurn ? model.outputPromptText : "",+ images: model.showsLiveTurn ? model.outputImageAttachments : [],+ output: model.showsLiveTurn ? model.outputText : "",+ mailbox: model.showsLiveTurn ? model.generationTranscriptMailbox : nil,+ // Include replay, but not a queued send still displaying the old answer.+ isTerminal: !model.isTranscriptTurnInFlight,+ showsPrefillPlaceholder: model.isTranscriptTurnInFlight&& model.outputResponsePlainText.isEmpty,runIdentity: model.runIdentity).frame(maxWidth: .infinity, maxHeight: .infinity)@@ -89,6 +94,7 @@ struct OutputPaneView: View {? "Copy last answer": "Response copied").accessibilityHint("Copies only the generated answer")+ .accessibilityIdentifier(.transcriptCopyResponse).help(responseCopyFeedbackID == nil? "Copy last answer": "Response copied")@@ -124,15 +130,16 @@ struct OutputPaneView: View {action: model.loadModel).buttonStyle(.borderedProminent).controlSize(.large)- } else if isLoadingModel {- Button("Load Model", action: {})+ .accessibilityIdentifier(.transcriptLoad)+ } else if model.canCancelLoad {+ Button("Cancel Load", action: model.cancelLoad).buttonStyle(.borderedProminent).controlSize(.large)- .hidden()- .accessibilityHidden(true)+ .accessibilityIdentifier(.bannerModelAction)} else if model.canReloadModel {Button("Reload Model", action: model.reloadModel).buttonStyle(.borderedProminent)+ .accessibilityIdentifier(.transcriptReload)}}.frame(maxWidth: .infinity)@@ -171,12 +178,12 @@ struct OutputPaneView: View {}struct SubmittedImageThumbnail: View {- let attachment: AppImageAttachment+ let attachment: ChatImagelet maximumSize: CGSize@State private var image: NSImage?init(- attachment: AppImageAttachment,+ attachment: ChatImage,maximumSize: CGSize = CGSize(width: 48, height: 48)) {self.attachment = attachment@@ -344,7 +351,7 @@ private struct IncrementalTranscriptView: NSViewRepresentable {var conversationPlainText: String = ""var requestNewChat: (() -> Void)?var prompt: String- var images: [AppImageAttachment] = []+ var images: [ChatImage] = []var output: Stringvar mailbox: GenerationTranscriptMailbox?var isTerminal: Bool@@ -441,7 +448,7 @@ private struct IncrementalTranscriptView: NSViewRepresentable {conversationPlainText: String,requestNewChat: (() -> Void)?,prompt: String,- images: [AppImageAttachment],+ images: [ChatImage],output: String,mailbox: GenerationTranscriptMailbox?,isTerminal: Bool,@@ -506,60 +513,35 @@ private struct IncrementalTranscriptView: NSViewRepresentable {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()+ let controller = documentController+ let steps = controller.synchronizeHistory(+ storage: storage, planner: &planner,+ input: TranscriptSyncPlanner.Input(+ epoch: epoch, historyCount: history.count, contextBreak: contextBreak,+ startedNewRun: startedNewRun, firstSynchronize: firstSynchronize)+ ) { index in+ let pair = history[index]+ _ = controller.synchronize(+ storage: storage, prompt: pair.user.text,+ response: pair.assistant.text, isTerminal: true,+ promptPrefix: Self.makePromptPrefix(pair.user.images),+ promptPrefixIdentifier: pair.user.images+ .map { "\($0.id.uuidString):\($0.sha256)" }+ .joined(separator: ","))+ }for step in steps {switch step {case .reset:- documentController.resetTranscript(storage: storage)- promptPrefixIdentifier = ""promptPrefix = NSAttributedString()+ promptPrefixIdentifier = ""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)+ case .drawPair: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()- }+ case .sealDrawnTurn, .appendContextBreak:+ break}}- storage.endEditing()}func scrollToBottom() {@@ -741,7 +723,7 @@ private struct IncrementalTranscriptView: NSViewRepresentable {/// stopped wanting is dropped rather than applied. Images arriving after/// the first paint is the case `follow` already exists for.private func buildPromptPrefix(- _ images: [AppImageAttachment], identifier: String+ _ images: [ChatImage], identifier: String) {guard !images.isEmpty else { return }Task { [weak self] in@@ -767,23 +749,22 @@ private struct IncrementalTranscriptView: NSViewRepresentable {}private static func makePromptPrefix(- _ images: [AppImageAttachment]+ _ images: [ChatImage]) -> NSAttributedString {+ let cells = TranscriptImageCells.images(+ for: images,+ load: { attachment in+ guard let image = SubmittedImageThumbnail.loadThumbnail(+ at: attachment.fileURL,+ maximumPixelSize: 720,+ cacheKey: attachment.sha256) else { return nil }+ image.size = SubmittedImageThumbnail.fittedSize(+ image.size, within: CGSize(width: 360, height: 240))+ return image+ },+ unreadable: Self.unreadableImageTile)let result = NSMutableAttributedString()- for attachment in images {- // A refused or unreadable image is dropped from the transcript,- // which is the same degradation the composer's placeholder tile- // gives. The separator therefore keys off what has actually- // been written, not off the attachment's index: keyed off the- // index, a first image the decode budget refused left the line- // starting with a bare gap.- guard let image = SubmittedImageThumbnail.loadThumbnail(- at: attachment.fileURL,- maximumPixelSize: 720,- cacheKey: attachment.sha256) else { continue }- image.size = SubmittedImageThumbnail.fittedSize(- image.size,- within: CGSize(width: 360, height: 240))+ for image in cells {let textAttachment = NSTextAttachment()textAttachment.attachmentCell = NSTextAttachmentCell(imageCell: Self.rounded(image))@@ -798,6 +779,39 @@ private struct IncrementalTranscriptView: NSViewRepresentable {/// The transcript draws its images as text attachments, which cannot be/// clipped by the view the way the composer's thumbnails are, so the/// corners have to be drawn into the image itself.+ /// Stands in for an image whose file is gone or will not decode.+ ///+ /// The same shape and the same symbol the composer already falls back+ /// to, so the two degrade alike. Its job is only to say a picture+ /// belongs here: what it was is in the answer, and why it cannot be+ /// read is not something the reader can act on from the transcript.+ private static func unreadableImageTile() -> NSImage {+ let size = NSSize(width: 160, height: 120)+ let tile = NSImage(size: size)+ tile.lockFocus()+ defer { tile.unlockFocus() }+ NSColor.quaternarySystemFill.setFill()+ NSRect(origin: .zero, size: size).fill()+ let configuration = NSImage.SymbolConfiguration(+ pointSize: 28, weight: .regular)+ if let symbol = NSImage(+ systemSymbolName: "photo", accessibilityDescription: nil)?+ .withSymbolConfiguration(configuration) {+ let tinted = NSImage(size: symbol.size)+ tinted.lockFocus()+ NSColor.tertiaryLabelColor.set()+ NSRect(origin: .zero, size: symbol.size).fill(using: .sourceOver)+ symbol.draw(in: NSRect(origin: .zero, size: symbol.size),+ from: .zero, operation: .destinationIn, fraction: 1)+ tinted.unlockFocus()+ tinted.draw(in: NSRect(+ x: (size.width - symbol.size.width) / 2,+ y: (size.height - symbol.size.height) / 2,+ width: symbol.size.width, height: symbol.size.height))+ }+ return tile+ }+private static func rounded(_ image: NSImage) -> NSImage {let size = image.sizeguard size.width > 1, size.height > 1 else { return image }diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swiftindex 0dcfa744..f369c9ea 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift@@ -8,7 +8,6 @@ import UniformTypeIdentifiersstruct PromptComposerView: View {@Bindable var model: AppModel@FocusState private var promptFocused: Bool- @State private var showingPromptTips = false@State private var showingImagePicker = false@State private var isImageDropTargeted = false@@ -50,9 +49,9 @@ struct PromptComposerView: View {newlineShortcut: model.newlineShortcut,canRun: model.canRun,canAcceptImages: model.isImageInputAvailable- && !model.isRunning+ && !model.isTurnInFlight&& !model.isAddingImages,- onSubmit: model.run,+ onSubmit: model.send,onImagesDropped: { model.addImages($0) },onImageDataPasted: model.addImageData,onPromisedImagesReceived: { urls, directory in@@ -104,12 +103,30 @@ struct PromptComposerView: View {.frame(width: 28, height: 28)}.buttonStyle(.borderless)- .disabled(model.isRunning || model.isAddingImages+ .disabled(model.isTurnInFlight || model.isAddingImages|| model.imageAttachments.count>= model.maximumImageAttachments).help(model.maximumImageAttachments == 0? "Start a new chat to make room for images.": "Add images")+ .accessibilityIdentifier(.composerAttach)+ } else if model.visionRuntimeEnabled {+ // Says why rather than leaving a gap. With the button simply+ // gone, the composer offered no account of itself at all, and+ // the only explanation was in the Inspector — which may not even+ // be open.+ Label(model.isVisionRuntimeSupported+ ? "Images need the companion pack"+ : "Images need Apple silicon with a supported GPU",+ systemImage: "photo.badge.exclamationmark")+ .font(.caption)+ .foregroundStyle(.tertiary)+ .labelStyle(.titleAndIcon)+ .help(model.isVisionRuntimeSupported+ ? "Install image support from the Inspector to attach "+ + "pictures. Chats that already have them still "+ + "show them."+ : "This Mac cannot run the image tower.")}promptTipsSpacer()@@ -126,7 +143,7 @@ struct PromptComposerView: View {// drifted out of line in the first place.HStack(alignment: .top, spacing: 8) {ForEach(model.imageAttachments, id: \.id) { attachment in- SubmittedImageThumbnail(attachment: attachment)+ SubmittedImageThumbnail(attachment: .staged(attachment)).overlay(alignment: .topTrailing) {Button {model.removeImage(id: attachment.id)@@ -137,6 +154,7 @@ struct PromptComposerView: View {.background(.regularMaterial, in: Circle()).offset(x: 5, y: -5).accessibilityLabel("Remove \(attachment.displayName)")+ .accessibilityIdentifier(AccessibilityID.remove("\(attachment.id)"))}.padding(.top, 5).padding(.trailing, 5)@@ -153,22 +171,12 @@ struct PromptComposerView: View {}private var promptTips: some View {- Button {- showingPromptTips.toggle()- } label: {- Label("Prompt tips", systemImage: "questionmark.circle")- .labelStyle(.iconOnly)- .frame(width: 28, height: 28)- .contentShape(Circle())- }- .buttonStyle(.borderless)- .foregroundStyle(.secondary)- .help("Prompt tips")- .popover(isPresented: $showingPromptTips,- attachmentAnchor: .point(.top),- arrowEdge: .top) {+ TransientPopoverButton(+ systemImage: "questionmark.circle", help: "Prompt tips") {promptGuide}+ .frame(width: 28, height: 28)+ .accessibilityIdentifier(.composerTips)}private var promptGuide: some View {@@ -204,7 +212,7 @@ struct PromptComposerView: View {@ViewBuilderprivate var clearAction: some View {- if !model.isRunning+ if !model.isTurnInFlight&& (!model.promptText.isEmpty || !model.imageAttachments.isEmpty) {Button {model.promptText = ""@@ -219,18 +227,12 @@ struct PromptComposerView: View {}.buttonStyle(.borderless).help("Clear text and images")- } else if !model.isRunning && model.hasOutputTranscript {- Button {- model.newChat()- } label: {- Label("New chat", systemImage: "trash")- .labelStyle(.iconOnly)- .frame(width: 28, height: 28)- .contentShape(Circle())- }- .buttonStyle(.borderless)- .help("Start a new chat")+ .accessibilityIdentifier(.composerClear)}+ // No trash-icon "new chat" here any more. The window control beside the+ // traffic lights and Cmd+N own that action, and once chats are kept a+ // trash glyph reads as delete — which, next to a list where delete is a+ // real and different thing, is the wrong promise to make.}}@@ -268,6 +270,7 @@ private struct PromptTextEditor: NSViewRepresentable {textView.textContainer?.lineFragmentPadding = 5textView.textContainer?.widthTracksTextView = truetextView.setAccessibilityLabel("Message")+ textView.setAccessibilityIdentifier(AccessibilityID.composerMessage.rawValue)// A promise-only drag — Photos, Mail, most browsers — never reaches// `draggingEntered` unless its types are registered here.textView.registerForDraggedTypes(@@ -376,37 +379,16 @@ private final class ImageDropTextView: NSTextView {return}let pasteboard = NSPasteboard.general- let urls = fileURLs(from: pasteboard)- if !urls.isEmpty {+ switch ImagePasteboardPayload.read(from: pasteboard) {+ case .fileURLs(let urls):onImagesDropped?(urls)- return- }- // Text on the pasteboard wins over a picture that came with it.- // Copying a range of cells from Numbers or Excel, or a text box from- // Keynote, writes TIFF alongside the RTF and plain text; so does a- // rich selection from many other apps. Taking the picture and- // returning swallowed the text the user actually selected, in a text- // editor, with nothing said about it. A screenshot or an image copied- // from an image editor carries no text, so it still attaches.- //- // Only the byte-carrying branches need this. A file paste is handled- // above, and Finder puts the path on the pasteboard as a string too.- if pasteboard.string(forType: .string)?.isEmpty == false {- super.paste(sender)- return- }- // An image copied from another app arrives as bytes with no file- // behind it, which used to be refused with an instruction to go and- // find one.- if let image = imageData(from: pasteboard) {- onImageDataPasted?(image.data, image.name)- return- }- if containsImage(in: pasteboard) {+ case .image(let data, let name):+ onImageDataPasted?(data, name)+ case .unsupportedImage:onUnsupportedImagePaste?()- return+ case .text, .none:+ super.paste(sender)}- super.paste(sender)}override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {@@ -535,28 +517,6 @@ private final class ImageDropTextView: NSTextView {!fileURLs(from: pasteboard).isEmpty || !filePromises(from: pasteboard).isEmpty}- /// The first pasteboard representation the vision pack can actually decode.- /// PNG and JPEG come through unchanged; anything else is re-encoded as PNG- /// rather than handing the decoder a format it was never validated against.- private func imageData(from pasteboard: NSPasteboard) -> (data: Data, name: String)? {- if let data = pasteboard.data(forType: .png) {- return (data, "Pasted image.png")- }- if let data = pasteboard.data(forType: NSPasteboard.PasteboardType("public.jpeg")) {- return (data, "Pasted image.jpeg")- }- guard let tiff = pasteboard.data(forType: .tiff),- let representation = NSBitmapImageRep(data: tiff),- let png = representation.representation(using: .png, properties: [:])- else { return nil }- return (png, "Pasted image.png")- }-- private func containsImage(in pasteboard: NSPasteboard) -> Bool {- (pasteboard.types ?? []).contains { type in- UTType(type.rawValue)?.conforms(to: .image) == true- }- }}/// Collects the results of a multi-file promise drop, which arrive onediff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swiftindex 854390be..f943c577 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swift@@ -1,5 +1,6 @@import TurboFieldfareAppCoreimport SwiftUI+import TurboFieldfareMacPresentationstruct PromptExamplesView: View {let select: (AppPromptPreset) -> Void@@ -66,6 +67,7 @@ struct PromptExamplesView: View {.accessibilityLabel(preset.title).accessibilityValue(preset.prompt).accessibilityHint("Copies this prompt into the prompt editor")+ .accessibilityIdentifier(AccessibilityID.example(preset.id))}}@@ -89,5 +91,6 @@ struct PromptExamplesView: View {.menuStyle(.borderlessButton).fixedSize().accessibilityHint("Shows additional prompts")+ .accessibilityIdentifier(.examplesMore)}}diff --git a/Sources/TurboFieldfareApp/Mac/History/ConversationSidebarView.swift b/Sources/TurboFieldfareApp/Mac/History/ConversationSidebarView.swiftnew file mode 100644index 00000000..99854678--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/History/ConversationSidebarView.swift@@ -0,0 +1,323 @@+import AppKit+import SwiftUI+import TurboFieldfareAppCore+import TurboFieldfareMacPresentation++/// The list of stored conversations, built as a panel rather than a+/// `NavigationSplitView` column.+///+/// The split view supplied a sidebar toggle of its own beside ours, moved our+/// toolbar group out from the traffic lights whenever the list was open, and+/// left its sidebar column inert to the mouse. A panel is the same shape the+/// Inspector already had on the other side, and every part of it — the search+/// field, the rows, the selection — is ours, so a click does what the code says+/// it does.+///+/// Rows are buttons, not `List` selection. Selection in a `List` is a binding+/// SwiftUI drives, and the row still has to report which conversation to open;+/// a button says that directly, and it cannot render as selectable while+/// refusing to be selected.+struct ConversationSidebarView: View {+ let model: AppModel+ @State private var search = ""+ @State private var renameTarget: ConversationMeta?+ @State private var renameText = ""+ @State private var deleteTarget: ConversationMeta?++ var body: some View {+ VStack(spacing: 0) {+ searchField++ if model.history.isReadOnlyStore {+ readOnlyNotice+ }++ if model.history.unreadableCount > 0 {+ unreadableNotice+ }++ if model.history.discardedLegacyTrashCount > 0 {+ Text("Removed \(model.history.discardedLegacyTrashCount) chat(s) left in legacy trash.")+ .font(.caption)+ .foregroundStyle(.secondary)+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ }++ if visibleSections.isEmpty {+ emptyState+ } else {+ list+ }+ }+ .alert("Rename Chat", isPresented: isRenaming, presenting: renameTarget) { target in+ TextField("Name", text: $renameText)+ .accessibilityIdentifier(.historyRenameField)+ Button("Rename") {+ model.renameConversation(id: target.id, to: renameText)+ renameTarget = nil+ }+ .keyboardShortcut(.defaultAction)+ .disabled(renameText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ .accessibilityIdentifier(.historyRenameConfirm)+ Button("Cancel", role: .cancel) { renameTarget = nil }+ } message: { target in+ Text("Rename \u{201C}\(ConversationRowPresentation.title(target))\u{201D}.")+ }+ // Asked, because it cannot be taken back. Delete used to move the+ // conversation to a `.trash` directory an Undo item could restore from,+ // which meant every deleted transcript and image stayed on disk for the+ // life of the store with nothing to collect them. Deleting for real is+ // the right behaviour; the cost is that this is the last chance to stop.+ .alert("Delete this chat?", isPresented: isDeleting, presenting: deleteTarget) { target in+ Button("Delete", role: .destructive) {+ model.deleteConversation(id: target.id)+ deleteTarget = nil+ }+ .disabled(!model.canMutateConversation(id: target.id))+ .accessibilityIdentifier(.historyDeleteConfirm)+ Button("Cancel", role: .cancel) { deleteTarget = nil }+ } message: { target in+ Text("\u{201C}\(ConversationRowPresentation.title(target))\u{201D} and "+ + "everything in it will be deleted. This cannot be undone.")+ }+ }++ private var isDeleting: Binding<Bool> {+ Binding(+ get: { deleteTarget != nil },+ set: { presented in if !presented { deleteTarget = nil } })+ }++ /// Renaming is a dialog, not an editable row.+ ///+ /// In place it was unusable: putting a focused `TextField` inside the+ /// `LazyVStack` made every row draw its selected background, and clicking+ /// away from the field left it focused with no way to commit or cancel+ /// except the keyboard. A dialog has one field, one Return and one Escape,+ /// and the list keeps rendering as a list.+ private var isRenaming: Binding<Bool> {+ Binding(+ get: { renameTarget != nil },+ set: { presented in if !presented { renameTarget = nil } })+ }++ // MARK: - Search++ /// Built to the pill's measurements, not to its own.+ ///+ /// The two boxes sit on the same row of the window either side of the+ /// divider, so any difference between them reads as a mistake. At 24 points+ /// against the pill's 50 this one looked like it had floated to the top of+ /// the sidebar. Same top inset, same height, same capsule.+ private var searchField: some View {+ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass")+ .foregroundStyle(.secondary)+ .font(.callout)+ TextField("Search Chats", text: $search)+ .textFieldStyle(.plain)+ .font(.callout)+ .accessibilityIdentifier(.historySearch)+ if !search.isEmpty {+ Button {+ search = ""+ } label: {+ Image(systemName: "xmark.circle.fill")+ .foregroundStyle(.secondary)+ }+ .buttonStyle(.plain)+ .help("Clear search")+ .accessibilityIdentifier(.historySearchClear)+ }+ }+ .frame(height: Self.chromeHeight)+ .padding(.horizontal, 12)+ .padding(.vertical, Self.chromeVerticalPadding)+ .background(Capsule().fill(Color(nsColor: .quaternarySystemFill)))+ .padding(.horizontal, 12)+ .padding(.top, Self.chromeTopInset)+ .padding(.bottom, 6)+ }++ /// `StatusHUDView`'s pill: 30 points of content, 10 above and below, 10 from+ /// the top of the window.+ private static let chromeHeight: CGFloat = 30+ private static let chromeVerticalPadding: CGFloat = 10+ private static let chromeTopInset: CGFloat = 10++ private var readOnlyNotice: some View {+ Label(+ "Another window has these chats open. This one can read them but "+ + "not change them.",+ systemImage: "lock")+ .font(.caption)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ .padding(.horizontal, 12)+ .padding(.bottom, 6)+ }++ /// Says that chats are missing from the list, because they are.+ ///+ /// A directory whose meta will not decode is skipped so one bad+ /// conversation cannot hide the rest — right, but on its own it means a+ /// chat can vanish with nothing anywhere to say it existed. The count is+ /// all this can honestly offer: the file that would have carried the title+ /// is the file that would not read.+ private var unreadableNotice: some View {+ Label(+ model.history.unreadableCount == 1+ ? "1 chat on disk could not be read and is not listed."+ : "\(model.history.unreadableCount) chats on disk could not be "+ + "read and are not listed.",+ systemImage: "exclamationmark.triangle")+ .font(.caption)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ .padding(.horizontal, 12)+ .padding(.bottom, 6)+ }++ @ViewBuilder+ private var emptyState: some View {+ Spacer(minLength: 0)+ VStack(spacing: 6) {+ Image(systemName: "bubble.left.and.bubble.right")+ .font(.largeTitle)+ .foregroundStyle(.tertiary)+ Text(search.isEmpty ? "No Chats Yet" : "No Matches")+ .font(.headline)+ Text(search.isEmpty+ ? "Chats are kept here once you send a message."+ : "No chat title contains \u{201C}\(search)\u{201D}.")+ .font(.caption)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ }+ .padding(.horizontal, 20)+ Spacer(minLength: 0)+ }++ // MARK: - List++ private var list: some View {+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 2, pinnedViews: [.sectionHeaders]) {+ ForEach(visibleSections, id: \.group) { section in+ Section {+ ForEach(section.entries, id: \.id) { entry in+ row(entry)+ }+ } header: {+ Text(section.group.rawValue)+ .font(.caption.weight(.semibold))+ .foregroundStyle(.secondary)+ .padding(.horizontal, 16)+ .padding(.top, 8)+ .padding(.bottom, 2)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color(nsColor: .windowBackgroundColor))+ }+ }+ }+ .padding(.bottom, 8)+ }+ .scrollContentBackground(.hidden)+ }++ private var visibleSections: [(group: ConversationDateGroup, entries: [ConversationMeta])] {+ let query = search.trimmingCharacters(in: .whitespacesAndNewlines)+ let entries = query.isEmpty+ ? model.history.entries+ : model.history.entries.filter {+ $0.title.localizedCaseInsensitiveContains(query)+ }+ return ConversationDateGroup.sections(entries, now: Date())+ }++ private func row(_ entry: ConversationMeta) -> some View {+ let state = model.continuability(of: entry)+ let isSelected = model.history.selection == entry.id+ return HStack(spacing: 4) {+ Button {+ model.openConversation(id: entry.id)+ } label: {+ VStack(alignment: .leading, spacing: 2) {+ Text(ConversationRowPresentation.title(entry))+ .lineLimit(1)+ .foregroundStyle(.primary)+ Text(ConversationRowPresentation.subtitle(entry, state: state))+ .font(.caption)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ }+ // The whole row is the target, not just the text it happens+ // to contain.+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityIdentifier(AccessibilityID.row(entry.id))++ // Rename and Delete on an explicit menu rather than only on a+ // right-click. A plain-styled button takes the control-click for+ // itself, so a context menu alone left both actions with no+ // reliable way in.+ Menu {+ Button("Rename") {+ renameText = entry.title+ renameTarget = entry+ }+ .disabled(!model.canMutateConversation(id: entry.id))+ // Not gated on the store being writable: looking at a+ // conversation's files is a read, and a second window holding+ // the lock is no reason to refuse it.+ Button("Open Folder in Finder") { openFolder(entry) }+ Divider()+ Button("Delete\u{2026}", role: .destructive) {+ deleteTarget = entry+ }+ .disabled(!model.canMutateConversation(id: entry.id))+ } label: {+ Image(systemName: "ellipsis")+ .foregroundStyle(.secondary)+ .frame(width: 22, height: 22)+ .contentShape(Rectangle())+ }+ .menuStyle(.borderlessButton)+ .menuIndicator(.hidden)+ .fixedSize()+ // The window's accent tint reaches in here and painted the glyph+ // green, which reads as a primary action rather than the secondary+ // affordance it is.+ .tint(.secondary)+ .help("Rename or delete this chat")+ .accessibilityIdentifier(AccessibilityID.rowMenu(entry.id))+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(rowBackground(isSelected: isSelected))+ .padding(.horizontal, 8)+ }++ /// Opens the folder itself rather than selecting it in its parent. The+ /// files are the point — `transcript.jsonl`, `conversation.json` and+ /// `images/` — and revealing the directory in the enclosing store would+ /// show a list of UUIDs instead.+ private func openFolder(_ entry: ConversationMeta) {+ Task {+ guard let url = await model.conversationFolderURL(for: entry.id) else {+ return+ }+ NSWorkspace.shared.open(url)+ }+ }++ private func rowBackground(isSelected: Bool) -> some View {+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .fill(isSelected+ ? Color(nsColor: .selectedContentBackgroundColor).opacity(0.35)+ : Color.clear)+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swiftindex 97f5ca39..6f9df9f4 100644--- a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift+++ b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift@@ -164,6 +164,7 @@ struct ModelInstallView: View {.buttonStyle(.bordered).keyboardShortcut(.cancelAction).disabled(!model.canCancelInstall)+ .accessibilityIdentifier(.installCancel)} else {if model.hasPartialModelDownload {Button("Discard Download", role: .destructive) {@@ -171,16 +172,19 @@ struct ModelInstallView: View {}.buttonStyle(.bordered).disabled(!model.canDiscardModelDownload)+ .accessibilityIdentifier(.installDiscard)}Button("Check Again", action: model.recheckModelAtCurrentLocation).buttonStyle(.bordered).disabled(model.isInstallingModel)+ .accessibilityIdentifier(.installCheckAgain)Button(model.hasPartialModelDownload ? "Resume" : "Download",action: model.installModel).buttonStyle(.borderedProminent).disabled(!model.canInstallModel)+ .accessibilityIdentifier(.installDownload)}}.controlSize(.large)diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swiftindex 524edc88..cdc0567a 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.7.2"+ public static let fallbackShortVersion = "0.8.0"private static let licenseURL = URL(string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!diff --git a/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift b/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swiftnew file mode 100644index 00000000..a42b90b6--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift@@ -0,0 +1,90 @@+import SwiftUI++/// Every control the Mac app exposes to an acceptance pass, named once.+///+/// The pass drives the app through the accessibility API and addresses+/// controls by these identifiers, never by coordinates: both false readings of+/// the 2026-09-01 manual pass were clicks at stale coordinates. Raw values are+/// the strings the accessibility tree carries as `AXIdentifier`;+/// `Scripts/check_app_case_coverage.rb` fails when one has no case in the+/// `mac-app-acceptance` skill, so a new control cannot land without its case.+public enum AccessibilityID: String, CaseIterable, Sendable {+ case stripSidebar = "strip.sidebar"+ case stripNewChat = "strip.newChat"+ case stripInspector = "strip.inspector"++ case hudStatus = "hud.status"+ case hudPhase = "hud.phase"+ case hudRate = "hud.rate"+ case hudContext = "hud.context"+ case hudMemory = "hud.memory"+ case hudMemoryInfo = "hud.memory.info"++ case historySearch = "history.search"+ case historySearchClear = "history.search.clear"+ case historyRenameField = "history.rename.field"+ case historyRenameConfirm = "history.rename.confirm"+ case historyDeleteConfirm = "history.delete.confirm"++ case composerMessage = "composer.message"+ case composerGenerate = "composer.generate"+ case composerStop = "composer.stop"+ case composerAttach = "composer.attach"+ case composerClear = "composer.clear"+ case composerTips = "composer.tips"+ case examplesMore = "examples.more"++ case transcriptCopyResponse = "transcript.copyResponse"+ case transcriptLoad = "transcript.load"+ case transcriptReload = "transcript.reload"++ case noticeRaiseContext = "notice.raiseContext"+ case noticeNewChat = "notice.newChat"+ case noticeReread = "notice.reread"++ case bannerErrorDismiss = "banner.error.dismiss"+ case bannerModelAction = "banner.model.action"++ case installDownload = "install.download"+ case installCancel = "install.cancel"+ case installDiscard = "install.discard"+ case installCheckAgain = "install.checkAgain"++ case visionInstall = "vision.install"+ case visionCancel = "vision.cancel"+ case visionDiscard = "vision.discard"+ case visionActivate = "vision.activate"+ case visionRemove = "vision.remove"++ case inspectorContext = "inspector.context"+ case inspectorSlots = "inspector.slots"+ case inspectorTemperature = "inspector.temperature"+ case inspectorTopK = "inspector.topK"+ case inspectorTopKValue = "inspector.topK.value"+ case inspectorTopP = "inspector.topP"+ case inspectorTopPValue = "inspector.topP.value"+ case inspectorPrefill = "inspector.prefill"+ case inspectorRDAdvise = "inspector.rdadvise"+ case inspectorCopyPath = "inspector.copyPath"+ case inspectorUnload = "inspector.unload"++ /// Identifiers minted per item carry one of these prefixes, so a case can+ /// name the family and the driver can match one member exactly.+ public enum Prefix: String, CaseIterable, Sendable {+ case historyRow = "history.row."+ case historyRowMenu = "history.row.menu."+ case composerRemove = "composer.remove."+ case example = "examples."+ }++ public static func row(_ id: UUID) -> String { Prefix.historyRow.rawValue + id.uuidString }+ public static func rowMenu(_ id: UUID) -> String { Prefix.historyRowMenu.rawValue + id.uuidString }+ public static func remove(_ id: String) -> String { Prefix.composerRemove.rawValue + id }+ public static func example(_ id: String) -> String { Prefix.example.rawValue + id }+}++public extension View {+ func accessibilityIdentifier(_ id: AccessibilityID) -> some View {+ accessibilityIdentifier(id.rawValue)+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/ConversationSidebarPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/ConversationSidebarPresentation.swiftnew file mode 100644index 00000000..50306053--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/ConversationSidebarPresentation.swift@@ -0,0 +1,189 @@+import Foundation+import TurboFieldfareAppCore++/// Which section of the sidebar a conversation belongs in.+///+/// Computed against an injected `now` rather than `Date()` so the day+/// boundaries are testable at all: a grouping that only works when the test+/// happens to run at midday is a grouping nobody has checked.+public enum ConversationDateGroup: String, CaseIterable, Sendable {+ case today = "Today"+ case yesterday = "Yesterday"+ case previousSevenDays = "Previous 7 Days"+ case older = "Older"++ public static func group(for date: Date,+ now: Date,+ calendar: Calendar = .current) -> ConversationDateGroup {+ if calendar.isDate(date, inSameDayAs: now) { return .today }+ guard let yesterday = calendar.date(byAdding: .day, value: -1, to: now) else {+ return .older+ }+ if calendar.isDate(date, inSameDayAs: yesterday) { return .yesterday }+ // Days apart, not hours: a conversation from four days ago belongs in+ // the same bucket whether it was morning or evening.+ let startOfToday = calendar.startOfDay(for: now)+ let startOfDate = calendar.startOfDay(for: date)+ let days = calendar.dateComponents(+ [.day], from: startOfDate, to: startOfToday).day ?? 0+ // A conversation dated in the future — a clock change, a restored+ // backup — is not "older". Today is the least surprising place for it.+ if days < 0 { return .today }+ return days <= 7 ? .previousSevenDays : .older+ }++ /// The stored conversations, grouped and ordered for the list.+ public static func sections(_ entries: [ConversationMeta], now: Date)+ -> [(group: ConversationDateGroup, entries: [ConversationMeta])] {+ var buckets: [ConversationDateGroup: [ConversationMeta]] = [:]+ for entry in entries.sorted(by: { $0.updatedAt > $1.updatedAt }) {+ buckets[group(for: entry.updatedAt, now: now), default: []].append(entry)+ }+ return allCases.compactMap { group in+ guard let entries = buckets[group], !entries.isEmpty else { return nil }+ return (group, entries)+ }+ }+}++/// One row of the sidebar.+public enum ConversationRowPresentation {+ public static func title(_ meta: ConversationMeta) -> String {+ meta.title.isEmpty ? ConversationTitle.untitled : meta.title+ }++ /// The line under the title.+ ///+ /// A row that cannot be continued says so here rather than being greyed+ /// out: a disabled row tells the user nothing, and the two reasons it can+ /// happen have completely different remedies.+ public static func subtitle(_ meta: ConversationMeta,+ state: ConversationContinuability) -> String {+ switch state {+ case .continuable:+ return meta.kvTokens.map { "\(decimal($0)) tokens" } ?? "\(meta.turnCount) turns"+ case .needsContext(let required):+ let held = meta.kvTokens.map(decimal) ?? "\(meta.turnCount) turns of"+ return "\(held) tokens \u{00B7} needs \(contextLabel(required)) context"+ case .cannotReplay(let reason):+ switch reason {+ case .newerFormat: return "recorded with a newer app version"+ case .differentModel: return "recorded with a different model"+ case .differentCheckpoint: return "recorded with a different checkpoint"+ case .differentTemplate: return "recorded with a different chat format"+ case .differentImageProcessing:+ return "recorded with different image processing"+ case .tokenCountUnknown: return "no replay record"+ case .imageRecordMissing: return "an image was not saved"+ }+ }+ }++ /// Rounded up to the next context the picker offers, because "needs 6,376+ /// tokens" is not something a user can select.+ public static func contextLabel(_ requiredTokens: Int) -> String {+ let option = AppContextLengthOption.allCases.first { $0.tokens >= requiredTokens }+ guard let option else { return "a longer" }+ return option.shortLabel+ }++ static func decimal(_ value: Int) -> String {+ let formatter = NumberFormatter()+ formatter.numberStyle = .decimal+ return formatter.string(from: NSNumber(value: value)) ?? "\(value)"+ }+}++/// The notice at the foot of a transcript that cannot be continued.+///+/// Not an alert: the guidelines are explicit that alerts are not for+/// information, and this is information about a conversation the user is+/// looking at. It names what is wrong, what it would take to fix, and what the+/// fix costs — a context change reloads the model and ends the open chat, which+/// is not something to discover afterwards.+public enum ConversationStateNotice {+ public struct Content: Equatable, Sendable {+ public let title: String+ public let message: String+ /// Nil when raising the context cannot help.+ public let requiredContext: Int?+ public let offersReread: Bool+ }++ public static func content(for state: ConversationContinuability,+ currentContext: Int) -> Content? {+ switch state {+ case .continuable:+ return nil+ case .needsContext(let required):+ let label = ConversationRowPresentation.contextLabel(required)+ return Content(+ title: "This chat can't continue at your current context length.",+ message: "It holds \(ConversationRowPresentation.decimal(required)) "+ + "tokens with room to reply; your context is "+ + "\(ConversationRowPresentation.decimal(currentContext)). "+ + "Raising the context to \(label) reloads the model and ends "+ + "the chat that's currently open.",+ requiredContext: required,+ offersReread: false)+ case .cannotReplay(let reason):+ return Content(+ title: "This chat can't be continued.",+ message: message(for: reason),+ requiredContext: nil,+ offersReread: reason != .newerFormat)+ }+ }++ private static func message(for reason: ConversationContinuability.Reason) -> String {+ switch reason {+ case .newerFormat:+ return "This chat uses a newer history format. Open it with a newer "+ + "version of the app to continue safely. Its saved files are unchanged."+ case .differentModel, .differentCheckpoint:+ return "It was recorded with a different model, so the tokens it "+ + "kept no longer mean the same thing. You can read it here, or "+ + "re-read it into a new chat, which starts a different "+ + "conversation from the same text."+ case .differentTemplate:+ return "It was recorded with a different chat format, so the tokens "+ + "it kept no longer line up. You can read it here, or re-read "+ + "it into a new chat, which starts a different conversation "+ + "from the same text."+ case .differentImageProcessing:+ return "Its images were prepared by an earlier build and would reach "+ + "the model differently now. You can read it here, or re-read "+ + "it into a new chat."+ case .tokenCountUnknown:+ return "It has no replay record, so there is nothing to put back "+ + "into the model's context. You can read it here, or re-read it "+ + "into a new chat."+ case .imageRecordMissing:+ return "One of its images could not be saved, so putting the chat "+ + "back would give the model a picture with nothing behind it. "+ + "You can read it here, or re-read it into a new chat."+ }+ }+}++/// Copy for the window controls in the status strip.+public enum WindowControlsPresentation {+ public static func sidebarToggleHelp(isVisible: Bool) -> String {+ isVisible ? "Hide Sidebar" : "Show Sidebar"+ }++ public static func sidebarToggleAccessibilityLabel(isVisible: Bool) -> String {+ sidebarToggleHelp(isVisible: isVisible)+ }++ public static func inspectorToggleHelp(isVisible: Bool) -> String {+ isVisible ? "Hide Inspector" : "Show Inspector"+ }++ public static func inspectorToggleAccessibilityLabel(isVisible: Bool) -> String {+ inspectorToggleHelp(isVisible: isVisible)+ }++ public static let newChatHelp = "New Chat"+ public static let newChatAccessibilityLabel = "New Chat"+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/ImagePasteboardPayload.swift b/Sources/TurboFieldfareApp/MacPresentation/ImagePasteboardPayload.swiftnew file mode 100644index 00000000..17c11cdc--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/ImagePasteboardPayload.swift@@ -0,0 +1,48 @@+import AppKit+import UniformTypeIdentifiers+import TurboFieldfare++public enum ImagePasteboardPayload {+ case fileURLs([URL])+ case image(data: Data, name: String)+ case text+ case unsupportedImage+ case none++ public static func read(from pasteboard: NSPasteboard) -> Self {+ let urls = pasteboard.readObjects(+ forClasses: [NSURL.self],+ options: [+ .urlReadingFileURLsOnly: true,+ .urlReadingContentsConformToTypes:+ Array(VisionImageLimits().allowedTypeIdentifiers),+ ]) as? [NSURL]+ if let urls, !urls.isEmpty { return .fileURLs(urls.map { $0 as URL }) }++ let hasText = pasteboard.string(forType: .string)?.isEmpty == false+ let hasRichText = pasteboard.data(forType: .rtf) != nil+ || pasteboard.data(forType: .rtfd) != nil+ if hasText && hasRichText { return .text }++ if let data = pasteboard.data(forType: .png), NSImage(data: data) != nil {+ return .image(data: data, name: "Pasted image.png")+ }+ if let data = pasteboard.data(+ forType: NSPasteboard.PasteboardType("public.jpeg")),+ NSImage(data: data) != nil {+ return .image(data: data, name: "Pasted image.jpeg")+ }+ if let tiff = pasteboard.data(forType: .tiff),+ let representation = NSBitmapImageRep(data: tiff),+ let png = representation.representation(using: .png, properties: [:]) {+ return .image(data: png, name: "Pasted image.png")+ }++ let declaresImage = (pasteboard.types ?? []).contains {+ UTType($0.rawValue)?.conforms(to: .image) == true+ }+ if declaresImage { return .unsupportedImage }+ if hasText { return .text }+ return .none+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swiftindex 75d8a21d..e4fbd55f 100644--- a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift@@ -184,7 +184,7 @@ public final class InstructionTranscriptDocumentController {wasAtBottom: Bool,mutation: Mutation) -> Bool {- wasAtBottom || mutation == .finalized+ wasAtBottom}public static func shouldRunPrefillAnimation(@@ -394,9 +394,13 @@ public final class InstructionTranscriptDocumentController {string: "\n\n",attributes: Self.promptAttributes()))}- document.append(NSAttributedString(- string: "Answer\n",- attributes: Self.assistantLabelAttributes()))+ // Recovery can clear the live turn while leaving completed history.+ if !prompt.isEmpty || promptPrefix.length > 0+ || !response.isEmpty || showsPrefillPlaceholder {+ document.append(NSAttributedString(+ string: "Answer\n",+ attributes: Self.assistantLabelAttributes()))+ }assistantRange = NSRange(location: document.length, length: 0)let assistant = progressiveRendering? progressiveRender(response, closingTail: closingTail)@@ -1023,3 +1027,42 @@ extension Array {indices.contains(index) ? self[index] : nil}}+++extension InstructionTranscriptDocumentController {+ /// Execute history updates as one storage edit before the new live turn.+ /// The view supplies cached image prefixes without moving image loading here.+ @discardableResult+ public func synchronizeHistory(+ storage: NSMutableAttributedString,+ planner: inout TranscriptSyncPlanner,+ input: TranscriptSyncPlanner.Input,+ drawPair: (Int) -> Void+ ) -> [TranscriptSyncStep] {+ let steps = planner.plan(input)+ guard !steps.isEmpty else { return steps }+ storage.beginEditing()+ defer { storage.endEditing() }+ for step in steps {+ switch step {+ case .reset:+ resetTranscript(storage: storage)+ case .sealDrawnTurn:+ let before = frozenLength+ sealTurn(storage: storage)+ if frozenLength == before {+ planner.sealFoundNothingToFreeze(historyCount: input.historyCount)+ }+ case .drawPair(let index):+ drawPair(index)+ sealTurn(storage: storage)+ case .appendContextBreak:+ let before = frozenLength+ appendContextBreak(storage: storage,+ text: "Earlier turns are no longer in the model's context")+ if frozenLength != before { planner.markContextBreakDrawn() }+ }+ }+ return steps+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageCells.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageCells.swiftnew file mode 100644index 00000000..d6d86fce--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageCells.swift@@ -0,0 +1,20 @@+import AppKit+import TurboFieldfareAppCore++/// Which images a turn's inline row is built from.+///+/// One cell per attachment, always. An image whose file is gone or will not+/// decode used to be dropped, and the turn then rendered as one that never had+/// a picture — under an answer that discusses it — so the transcript stopped+/// agreeing with the context the model was actually given. A conversation can+/// lose a stored file to anything outside this app, and the reader has to be+/// able to tell "there was a picture here" from "there was not".+public enum TranscriptImageCells {+ public static func images(+ for attachments: [ChatImage],+ load: (ChatImage) -> NSImage?,+ unreadable: () -> NSImage+ ) -> [NSImage] {+ attachments.map { load($0) ?? unreadable() }+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swiftindex 00450654..ac4b8867 100644--- a/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swift@@ -49,7 +49,8 @@ public struct TranscriptSyncPlanner: Equatable, Sendable {public mutating func plan(_ input: Input) -> [TranscriptSyncStep] {var steps: [TranscriptSyncStep] = []- if renderedEpoch != input.epoch {+ let sameEpoch = renderedEpoch == input.epoch+ if !sameEpoch {steps.append(.reset)renderedEpoch = input.epochrenderedHistory = 0@@ -57,7 +58,7 @@ public struct TranscriptSyncPlanner: Equatable, Sendable {}if renderedHistory < input.historyCount {- if input.startedNewRun,+ if sameEpoch, input.startedNewRun,renderedHistory == input.historyCount - 1,!input.firstSynchronize {steps.append(.sealDrawnTurn)diff --git a/Sources/TurboFieldfareApp/MacPresentation/TransientPopoverButton.swift b/Sources/TurboFieldfareApp/MacPresentation/TransientPopoverButton.swiftnew file mode 100644index 00000000..25339ea4--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/TransientPopoverButton.swift@@ -0,0 +1,61 @@+import AppKit+import SwiftUI++public enum TransientPopoverPresentation {+ public static let behavior: NSPopover.Behavior = .transient+}++@MainActor+public struct TransientPopoverButton<Content: View>: NSViewRepresentable {+ private let systemImage: String+ private let help: String+ private let content: Content++ public init(systemImage: String, help: String,+ @ViewBuilder content: () -> Content) {+ self.systemImage = systemImage+ self.help = help+ self.content = content()+ }++ public func makeCoordinator() -> Coordinator { Coordinator(content: content) }++ public func makeNSView(context: Context) -> NSButton {+ let button = NSButton(image: NSImage(+ systemSymbolName: systemImage, accessibilityDescription: help) ?? NSImage(),+ target: context.coordinator, action: #selector(Coordinator.toggle(_:)))+ button.isBordered = false+ button.toolTip = help+ button.setAccessibilityLabel(help)+ return button+ }++ public func updateNSView(_ button: NSButton, context: Context) {+ context.coordinator.host.rootView = content+ }++ public static func dismantleNSView(_ button: NSButton, coordinator: Coordinator) {+ coordinator.popover.close()+ }++ @MainActor+ public final class Coordinator: NSObject {+ let popover = NSPopover()+ let host: NSHostingController<Content>++ init(content: Content) {+ host = NSHostingController(rootView: content)+ super.init()+ popover.behavior = TransientPopoverPresentation.behavior+ popover.contentViewController = host+ }++ @objc func toggle(_ sender: NSButton) {+ if popover.isShown {+ popover.close()+ } else {+ popover.show(relativeTo: sender.bounds, of: sender, preferredEdge: .maxY)+ }+ }+ }+}diff --git a/Sources/TurboFieldfareDecodeService/DecodeConversationGate.swift b/Sources/TurboFieldfareDecodeProtocol/DecodeConversationGate.swiftsimilarity index 59%rename from Sources/TurboFieldfareDecodeService/DecodeConversationGate.swiftrename to Sources/TurboFieldfareDecodeProtocol/DecodeConversationGate.swiftindex 424585c5..b638ea78 100644--- a/Sources/TurboFieldfareDecodeService/DecodeConversationGate.swift+++ b/Sources/TurboFieldfareDecodeProtocol/DecodeConversationGate.swift@@ -1,5 +1,4 @@import Foundation-import TurboFieldfareDecodeProtocol/// Decides whether an incoming generate may join the open conversation.///@@ -9,10 +8,10 @@ import TurboFieldfareDecodeProtocol/// 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 {+public struct DecodeConversationGate: Equatable, Sendable {/// 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 {+ public enum Rejection: Error, Equatable, Sendable {/// 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.@@ -22,32 +21,61 @@ struct DecodeConversationGate: Equatable {case oneShotDuringConversation(open: UUID)}- enum Admission: Equatable {+ public enum Admission: Equatable, Sendable {/// 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+ public private(set) var openEpoch: UUID?+ public private(set) var committedTurns = 0++ public init() {}/// Starts a new lineage. The caller drops the KV; this only records that it/// did.- mutating func reset(to epoch: UUID) {+ public mutating func reset(to epoch: UUID) {openEpoch = epochcommittedTurns = 0}+ /// Opens a lineage that already has turns behind it: a stored conversation+ /// whose token IDs are back in the KV.+ ///+ /// Opening it at zero, as a reset does, would reject the reopened+ /// conversation's very next turn as out of order and keep rejecting every+ /// turn after it. A negative count is clamped rather than trusted: the+ /// figure arrives over a socket.+ public mutating func restore(to epoch: UUID, committedTurns: Int) {+ openEpoch = epoch+ self.committedTurns = max(0, committedTurns)+ }+/// 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() {+ public mutating func endLineage() {openEpoch = nilcommittedTurns = 0}- func admit(_ request: DecodeGenerationRequest) -> Result<Admission, Rejection> {+ /// A restore was asked for and did not complete.+ ///+ /// The session drops the KV it held before it prefills the requested+ /// record, so by the time a restore can fail — a digest that does not+ /// match, a token outside the vocabulary — the previous lineage's tokens+ /// are already gone. Leaving that epoch open admitted its next turn onto an+ /// empty cache as an opening turn, with the caller's transcript showing+ /// every exchange the model could no longer see. Fails closed for a+ /// restore refused before the session was touched too: the app treats+ /// every failed replay as the end of what it held, and the two sides must+ /// not disagree about which epoch is open.+ public mutating func restoreFailed() {+ endLineage()+ }++ public func admit(_ request: DecodeGenerationRequest) -> Result<Admission, Rejection> {guard let requested = request.conversationEpoch else {if let openEpoch { return .failure(.oneShotDuringConversation(open: openEpoch)) }return .success(.oneShot)@@ -66,27 +94,8 @@ struct DecodeConversationGate: Equatable {/// 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) {+ public 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/TurboFieldfareDecodeProtocol/DecodeProtocol.swift b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swiftindex 08a3a9d6..577228bd 100644--- a/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift+++ b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift@@ -131,10 +131,70 @@ public struct DecodeResetConversationRequest: Codable, Sendable, Equatable {}}+/// One image of a stored conversation, as the service needs it to replay.+///+/// The span is two integers rather than a `Range<Int>` because `Range`'s+/// decoder builds the range straight from the bounds it read and traps when+/// they arrive out of order. This arrives over a socket, so an inverted pair+/// has to be a refusal, not a crash.+public struct DecodeReplayImage: Codable, Sendable, Equatable {+ public var tokenLowerBound: Int+ public var tokenCount: Int+ public var path: String+ public var expectedDigest: String++ public init(tokenLowerBound: Int, tokenCount: Int,+ path: String, expectedDigest: String) {+ self.tokenLowerBound = tokenLowerBound+ self.tokenCount = tokenCount+ self.path = path+ self.expectedDigest = expectedDigest+ }+}++/// Rebuilds a stored conversation's KV from the token IDs it recorded, and+/// opens `epoch` as the lineage the service will accept turns for.+///+/// `committedTurns` is what the restored transcript already contains, so the+/// next generate's `turnIndex` follows it. Opening at zero would reject every+/// turn of a reopened conversation as out of order.+public struct DecodeRestoreConversationRequest: Codable, Sendable, Equatable {+ public var epoch: UUID+ public var tokenIDs: [Int32]+ public var images: [DecodeReplayImage]+ public var boundaryTokenIDs: [Int32]+ public var boundaryNeedsReplay: Bool+ public var committedTurns: Int+ public var maxContextTokens: Int+ public var runtimeOptions: DecodeRuntimeOptions+ public var requestID: UUID++ public init(epoch: UUID = UUID(),+ tokenIDs: [Int32],+ images: [DecodeReplayImage] = [],+ boundaryTokenIDs: [Int32] = [],+ boundaryNeedsReplay: Bool = false,+ committedTurns: Int,+ maxContextTokens: Int,+ runtimeOptions: DecodeRuntimeOptions = DecodeRuntimeOptions(),+ requestID: UUID = UUID()) {+ self.epoch = epoch+ self.tokenIDs = tokenIDs+ self.images = images+ self.boundaryTokenIDs = boundaryTokenIDs+ self.boundaryNeedsReplay = boundaryNeedsReplay+ self.committedTurns = committedTurns+ self.maxContextTokens = maxContextTokens+ self.runtimeOptions = runtimeOptions+ self.requestID = requestID+ }+}+public enum DecodeServiceCommand: Codable, Sendable {case load(DecodeLoadRequest)case generate(DecodeGenerationRequest)case resetConversation(DecodeResetConversationRequest)+ case restoreConversation(DecodeRestoreConversationRequest)case cancelcase unload(UUID)case shutdown@@ -156,6 +216,9 @@ public enum DecodeServiceEventKind: String, Codable, Sendable {/// leaves the conversation resumable.case lineageLostcase conversationReset+ /// A stored conversation's token IDs are back in the KV and its epoch is+ /// open. `conversationTokenCount` says how many tokens were replayed.+ case conversationRestoredcase unloaded}@@ -240,6 +303,19 @@ public struct DecodeServiceEvent: Codable, Sendable {/// 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?+ /// What this turn put into the KV, so the app can store the conversation as+ /// the model saw it rather than as the transcript reads. Set once, on the+ /// terminal event of a conversation turn, and nil everywhere else.+ ///+ /// Size is why they ride the terminal event rather than a channel of their+ /// own: an 8K-token turn is about 50 KB of JSON against a 4 MiB frame cap,+ /// and a 64K one about 400 KB.+ public var promptTokenIDs: [Int32]?+ public var generatedTokenIDs: [Int32]?+ /// A token the model emitted that never entered the KV, which happens when+ /// a run stops on max tokens or is cancelled. The next turn replays it.+ public var boundaryTokenIDs: [Int32]?+ public var boundaryNeedsReplay: Bool?public var prefill: DecodePrefillDiagnostics?public var runner: DecodeRunnerDiagnostics?@@ -257,6 +333,10 @@ public struct DecodeServiceEvent: Codable, Sendable {cachedPromptTokens: Int? = nil,conversationTokenCount: Int? = nil,conversationEpoch: UUID? = nil,+ promptTokenIDs: [Int32]? = nil,+ generatedTokenIDs: [Int32]? = nil,+ boundaryTokenIDs: [Int32]? = nil,+ boundaryNeedsReplay: Bool? = nil,prefill: DecodePrefillDiagnostics? = nil,runner: DecodeRunnerDiagnostics? = nil) {self.kind = kind@@ -280,6 +360,10 @@ public struct DecodeServiceEvent: Codable, Sendable {self.cachedPromptTokens = cachedPromptTokensself.conversationTokenCount = conversationTokenCountself.conversationEpoch = conversationEpoch+ self.promptTokenIDs = promptTokenIDs+ self.generatedTokenIDs = generatedTokenIDs+ self.boundaryTokenIDs = boundaryTokenIDs+ self.boundaryNeedsReplay = boundaryNeedsReplayself.prefill = prefillself.runner = runner}diff --git a/Sources/TurboFieldfareDecodeService/DecodeConversationRejectionMessage.swift b/Sources/TurboFieldfareDecodeService/DecodeConversationRejectionMessage.swiftnew file mode 100644index 00000000..dc34bddb--- /dev/null+++ b/Sources/TurboFieldfareDecodeService/DecodeConversationRejectionMessage.swift@@ -0,0 +1,39 @@+import Foundation+import TurboFieldfareDecodeProtocol++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"+ }+ }++ /// The terminal event a refused turn comes back as.+ ///+ /// `.lineageLost`, not `.failed`. A refusal means the turn was composed+ /// against a conversation the KV is no longer holding, so retrying it is+ /// refused identically forever — and `.failed` reaches the app as a+ /// retryable `.unknown`, which offers exactly that retry. `.lineageLost`+ /// is the kind that says the lineage is over and only a new chat clears it.+ ///+ func terminalEvent(generationID: UUID,+ conversationEpoch: UUID?) -> DecodeServiceEvent {+ DecodeServiceEvent(+ kind: .lineageLost,+ generationID: generationID,+ error: message,+ conversationEpoch: conversationEpoch)+ }+}diff --git a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swiftindex ff01698c..c4046872 100644--- a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift+++ b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift@@ -182,6 +182,14 @@ final class DecodeServiceOutbox: @unchecked Sendable {visionTowerMappedBytes: diagnostics?.visionTowerMappedBytes,cachedPromptTokens: diagnostics?.cachedPromptTokens,conversationTokenCount: conversationTokens(),+ // The turn's own record, carried once on the event that ends it.+ // The snapshots this outbox sends per 100 ms carry text, which is+ // what the transcript shows; these are what the model saw, and the+ // app cannot store the conversation without them.+ promptTokenIDs: diagnostics?.promptTokenIDs,+ generatedTokenIDs: diagnostics?.generatedTokenIDs,+ boundaryTokenIDs: diagnostics?.boundaryTokenIDs,+ boundaryNeedsReplay: diagnostics?.boundaryNeedsReplay,prefill: diagnostics?.prefill.map(Self.prefillDiagnostics),runner: diagnostics?.runner.map(Self.runnerDiagnostics))}diff --git a/Sources/TurboFieldfareDecodeService/Entry.swift b/Sources/TurboFieldfareDecodeService/Entry.swiftindex cbcf43e4..0c134b83 100644--- a/Sources/TurboFieldfareDecodeService/Entry.swift+++ b/Sources/TurboFieldfareDecodeService/Entry.swift@@ -1,4 +1,5 @@import Darwin+import Synchronizationimport TurboFieldfareimport Foundationimport TurboFieldfareAppCore@@ -6,11 +7,14 @@ import TurboFieldfareDecodeProtocolenum DecodeServiceError: Error, CustomStringConvertible {case attachmentOutsideStore(path: String)+ case replayImageOutsideStore(path: String)var description: String {switch self {case .attachmentOutsideStore(let path):"image attachment is not a staged attachment: \(path)"+ case .replayImageOutsideStore(let path):+ "replay image is not inside this model's conversation store: \(path)"}}}@@ -38,17 +42,20 @@ enum DecodeServiceError: Error, CustomStringConvertible {DecodeUnixSocket.ignoreSIGPIPEProcessWide()let client = RealInferenceClient()let commands = DecodeCommandQueue()+ let loadInFlight = ServiceLoadCancellation()let input = Thread {do {while true {let command = try DecodeFrameCodec.read(DecodeServiceCommand.self, from: handles.input)+ if case .load = command { loadInFlight.enqueueLoad() }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()+ loadInFlight.cancel()}commands.append(command)if case .shutdown = command { break }@@ -68,13 +75,39 @@ enum DecodeServiceError: Error, CustomStringConvertible {switch command {case .load(let request):let directory = URL(fileURLWithPath: request.modelPath)+ // Outside the `do`, because the queued load ends here even if+ // it never starts: its runtime options are parsed below and can+ // throw, and a load left counted as queued makes the next+ // generation's cancel latch onto a later load.+ defer { loadInFlight.finish() }+ // The session drops what it held before it loads, so a load+ // that then fails or is cancelled leaves nothing loaded. The+ // facts below have to say so, or the next generate passed the+ // directory and options checks, opened a writer thread and+ // failed inside the run with "model is not loaded".+ var loadStarted = false+ defer {+ if loadStarted, modelDirectory == nil {+ conversation.endLineage()+ loadedOptions = nil+ }+ }do {let options = try appRuntimeOptions(request.runtimeOptions)- try await client.ensureLoaded(- modelDirectory: directory,- maxContextTokens: request.maxContextTokens,- options: options,- forceLogitsHead: request.forceLogitsHead) { _ in }+ // The session load already checks for cancellation between+ // its stages; running it in a task is what gives the input+ // thread something to cancel.+ let load = Task {+ try await client.ensureLoaded(+ modelDirectory: directory,+ maxContextTokens: request.maxContextTokens,+ options: options,+ forceLogitsHead: request.forceLogitsHead) { _ in }+ }+ loadInFlight.begin(load)+ loadStarted = true+ modelDirectory = nil+ try await load.valuemodelDirectory = directoryloadedOptions = request.runtimeOptions// A load builds a new runner and a new KV, so whatever@@ -109,6 +142,85 @@ enum DecodeServiceError: Error, CustomStringConvertible {try? handles.output.close()return}+ case .restoreConversation(let request):+ guard let modelDirectory else {+ // Not `try?`: the app waits out the whole restore deadline+ // for a terminal event that never lands. A lost write is an+ // EOF the client rebuilds from, the same as below.+ do {+ try write(DecodeServiceEvent(+ kind: .failed, generationID: request.requestID,+ error: "model is not loaded"), to: handles.output)+ } catch {+ let message = "Decode service closing after a lost "+ + "conversation restore refusal: \(error)\n"+ FileHandle.standardError.write(Data(message.utf8))+ await client.unload()+ try? handles.output.close()+ return+ }+ continue+ }+ // The gate opens only after the KV actually holds the tokens.+ // Opening it first and failing the replay would leave the app+ // free to send turns onto a lineage that does not exist.+ do {+ let lineage = try restoreLineage(+ request, modelDirectory: modelDirectory)+ let options = try appRuntimeOptions(request.runtimeOptions)+ // Progress goes straight out: the writer thread belongs to a+ // generation, and a restore has none. The loop is awaiting+ // this call, so nothing else is writing to the handle.+ let writeFailure = Mutex<Error?>(nil)+ let tokens = try await client.restoreConversation(+ lineage, epoch: request.epoch, options: options,+ maxContextTokens: request.maxContextTokens+ ) { done, total in+ do {+ try write(DecodeServiceEvent(+ kind: .prefill, generationID: request.requestID,+ prefillDone: done, prefillTotal: total,+ conversationEpoch: request.epoch), to: handles.output)+ } catch {+ writeFailure.withLock { $0 = $0 ?? error }+ }+ }+ if let error = writeFailure.withLock({ $0 }) { throw error }+ conversation.restore(to: request.epoch,+ committedTurns: request.committedTurns)+ try write(DecodeServiceEvent(+ kind: .conversationRestored, generationID: request.requestID,+ conversationTokenCount: tokens,+ conversationEpoch: request.epoch), to: handles.output)+ } catch {+ // The lineage that was open is gone with the KV the restore+ // reset, and the event says so: reporting the old epoch as+ // still open, and leaving the gate to admit its next turn,+ // was a turn prefilled as an opening one under a transcript+ // showing every exchange before it.+ conversation.restoreFailed()+ // Same reasoning as the reset path: a terminal event that+ // never lands leaves the app waiting out its whole timeout+ // for a reply that cannot come.+ do {+ try write(DecodeServiceEvent(+ kind: .failed, generationID: request.requestID,+ // The cause, not the sentence: the client phrases+ // it, and forwarding the phrasing made the app show+ // it twice.+ error: (error as? AppInferenceError)?.diagnosticMessage+ ?? "\(error)",+ conversationEpoch: conversation.openEpoch),+ to: handles.output)+ } catch {+ let message = "Decode service closing after a lost "+ + "conversation restore: \(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(@@ -139,9 +251,8 @@ enum DecodeServiceError: Error, CustomStringConvertible {case .success(let value):admission = valuecase .failure(let rejection):- try? write(DecodeServiceEvent(- kind: .failed, generationID: request.generationID,- error: rejection.message,+ try? write(rejection.terminalEvent(+ generationID: request.generationID,conversationEpoch: conversation.openEpoch), to: handles.output)continue}@@ -186,7 +297,7 @@ enum DecodeServiceError: Error, CustomStringConvertible {let generation = AppGenerationRequest(modelDirectory: modelDirectory, prompt: request.prompt,imageAttachments: (request.imageAttachments ?? []).map {- AppImageAttachment(+ StagedImage(id: $0.id,fileURL: URL(fileURLWithPath: $0.path),displayName: $0.displayName,@@ -251,6 +362,38 @@ enum DecodeServiceError: Error, CustomStringConvertible {try handle.write(contentsOf: DecodeFrameCodec.encode(event))}+ /// The wire request as a lineage, with every path checked against the+ /// conversation store first.+ ///+ /// Same trust boundary as an image attachment: these paths arrive over a+ /// socket and this process opens and hashes whatever they name. Without the+ /// check a peer could use the service to read any file the user can, and a+ /// store rooted on the loaded model is the only place a stored conversation+ /// can legitimately live.+ private static func restoreLineage(+ _ request: DecodeRestoreConversationRequest,+ modelDirectory: URL+ ) throws -> AppConversationLineage {+ let images = try request.images.map { image -> AppConversationReplayImage in+ let url = URL(fileURLWithPath: image.path)+ guard ConversationStoreLocation.contains(+ url, forModelDirectory: modelDirectory) else {+ throw DecodeServiceError.replayImageOutsideStore(path: image.path)+ }+ return AppConversationReplayImage(+ tokenLowerBound: image.tokenLowerBound,+ tokenCount: image.tokenCount,+ fileURL: url,+ expectedDigest: image.expectedDigest)+ }+ return AppConversationLineage(+ tokenIDs: request.tokenIDs,+ images: images,+ boundaryTokenIDs: request.boundaryTokenIDs,+ boundaryNeedsReplay: request.boundaryNeedsReplay,+ committedTurns: request.committedTurns)+ }+private static func appRuntimeOptions(_ options: DecodeRuntimeOptions) throws-> AppRuntimeOptions {guard let cachePolicy = AppExpertCachePolicy(diff --git a/Sources/TurboFieldfareDecodeService/ServiceLoadCancellation.swift b/Sources/TurboFieldfareDecodeService/ServiceLoadCancellation.swiftnew file mode 100644index 00000000..1c576c2c--- /dev/null+++ b/Sources/TurboFieldfareDecodeService/ServiceLoadCancellation.swift@@ -0,0 +1,69 @@+import Foundation++/// Lets the input thread cancel the load the command loop is running.+///+/// The two threads race by design: the app writes `.load` and then, if the user+/// gives up, `.cancel`, and the cancel can arrive before the loop has even+/// started the load. So a cancel that finds nothing running has to be+/// remembered and applied to the load when it begins.+///+/// The mistake was remembering it unconditionally. `.cancel` is also what stops+/// a *generation*, and that cancel arrives when no load is queued at all — it+/// then sat latched indefinitely and cancelled the next load the user asked+/// for, however much later. Pressing Stop on an answer and then reloading the+/// model reported "decode service returned cancelled for a load request", with+/// nothing having cancelled anything.+///+/// A cancel is therefore only held when a load is actually queued and waiting+/// to start. Anything else is a generation's cancel and must not touch loads.+final class ServiceLoadCancellation: @unchecked Sendable {+ private let lock = NSLock()+ private var task: Task<Void, Error>?+ private var queuedLoads = 0+ private var cancelRequested = false++ /// The input thread has read a `.load` and put it on the queue. It has not+ /// started yet, so a cancel arriving now belongs to it.+ func enqueueLoad() {+ lock.lock(); defer { lock.unlock() }+ queuedLoads += 1+ }++ func begin(_ task: Task<Void, Error>) {+ lock.lock()+ let alreadyCancelled = cancelRequested+ cancelRequested = false+ self.task = task+ lock.unlock()+ // A cancel that raced ahead of the task still has to land on it.+ if alreadyCancelled { task.cancel() }+ }++ /// The queued load is over, whether it ran or never started.+ ///+ /// The count is cleared here rather than in `begin` because a load can fail+ /// before it starts — its runtime options may not parse — and a count left+ /// standing turns the next generation's `.cancel` into a held cancel, which+ /// is the latch this type exists to prevent.+ func finish() {+ lock.lock(); defer { lock.unlock() }+ task = nil+ if queuedLoads > 0 { queuedLoads -= 1 }+ if queuedLoads == 0 { cancelRequested = false }+ }++ func cancel() {+ lock.lock()+ let current = task+ // Only a load that exists, or one already on its way, may be cancelled.+ if current == nil, queuedLoads > 0 { cancelRequested = true }+ lock.unlock()+ current?.cancel()+ }++ /// Test-visible: whether a cancel is being held for a queued load.+ var isHoldingCancel: Bool {+ lock.lock(); defer { lock.unlock() }+ return cancelRequested+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/ConversationLineageRecordTests.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/ConversationLineageRecordTests.swiftnew file mode 100644index 00000000..b964c21e--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/ConversationLineageRecordTests.swift@@ -0,0 +1,132 @@+import Foundation+import Testing+@testable import TurboFieldfare++/// The split that turns one turn into two transcript records, and the identity+/// that decides whether those records may be replayed at all.+@Suite struct ConversationLineageRecordTests {+ // MARK: - A record's token IDs are checked before they reach the table++ private struct BadToken: Equatable {+ let index: Int+ let token: Int32+ }++ private func firstBadToken(_ body: () throws -> Void) -> BadToken? {+ do {+ try body()+ return nil+ } catch MultimodalConversationError.invalidReplayToken(+ let index, let token, _) {+ return BadToken(index: index, token: token)+ } catch {+ Issue.record("unexpected error: \(error)")+ return nil+ }+ }++ /// Restore is the one prefill of IDs the tokenizer did not produce, and the+ /// embedding kernel indexes its table by the raw value. A negative ID+ /// became `UInt32(bitPattern:)` of itself, a too-large one read past the+ /// table; both were GPU reads of memory that is not the model.+ @Test func aTokenOutsideTheVocabularyIsRefusedBeforeItReachesTheTable() {+ let vocab = 262_144+ let negative = MultimodalConversationLineage(tokenIDs: [2, -1, 3])+ #expect(firstBadToken { try negative.validateTokenIDs(vocabSize: vocab) }+ == BadToken(index: 1, token: -1))+ let past = MultimodalConversationLineage(tokenIDs: [2, 3, Int32(vocab)])+ #expect(firstBadToken { try past.validateTokenIDs(vocabSize: vocab) }+ == BadToken(index: 2, token: Int32(vocab)))+ let last = MultimodalConversationLineage(tokenIDs: [Int32(vocab - 1), 0])+ #expect(firstBadToken { try last.validateTokenIDs(vocabSize: vocab) } == nil)+ }++ /// The boundary token enters the same prefill, ahead of the next turn.+ @Test func aBoundaryTokenOutsideTheVocabularyIsRefusedToo() {+ let lineage = MultimodalConversationLineage(+ tokenIDs: [1, 2], uncommittedBoundary: [300_000], boundaryNeedsReplay: true)+ #expect(firstBadToken { try lineage.validateTokenIDs(vocabSize: 262_144) }+ == BadToken(index: 2, token: 300_000))+ }++ /// What the next turn's prompt starts with: the KV, plus the boundary only+ /// when it is going to be replayed.+ @Test func thePromptPrefixCountsAReplayedBoundaryOnly() {+ #expect(MultimodalConversationLineage(+ tokenIDs: [1, 2, 3], uncommittedBoundary: [4],+ boundaryNeedsReplay: true).promptPrefixCount == 4)+ #expect(MultimodalConversationLineage(+ tokenIDs: [1, 2, 3], uncommittedBoundary: [4],+ boundaryNeedsReplay: false).promptPrefixCount == 3)+ }++ @Test func generatedTokensAreWhatTheKVKeptPastThePrompt() {+ let kv: [Int32] = [1, 2, 3, 4, 5, 6, 7]+ #expect(MultimodalTurnRecord.generatedTokenIDs(kvTokenIDs: kv, promptCount: 4)+ == [5, 6, 7])+ }++ /// Without the suffix-of-the-record rule this returned the tokens the decode+ /// loop counted, including the ones a stop-string match had just rewound out+ /// of the KV. Replaying that transcript would prefill assistant text the+ /// cache never held and the reader never saw.+ @Test func aStopStringTrimIsAlreadyAppliedToTheGeneratedRecord() {+ let trimmed: [Int32] = [1, 2, 3, 4, 5]+ #expect(MultimodalTurnRecord.generatedTokenIDs(+ kvTokenIDs: trimmed, promptCount: 4) == [5])+ }++ @Test func aTrimBackToThePromptBoundaryLeavesNothingGenerated() {+ let kv: [Int32] = [1, 2, 3, 4]+ #expect(MultimodalTurnRecord.generatedTokenIDs(+ kvTokenIDs: kv, promptCount: 4).isEmpty)+ // A reset-to-empty after a trim leaves fewer tokens than the prompt had.+ #expect(MultimodalTurnRecord.generatedTokenIDs(+ kvTokenIDs: [], promptCount: 4).isEmpty)+ }++ /// Concatenating the per-turn records has to reproduce the KV exactly; that+ /// is the whole reason the record is token IDs rather than text.+ @Test func concatenatingTurnRecordsReproducesTheKV() {+ var kv: [Int32] = []+ var record: [Int32] = []+ for turn in 0..<3 {+ let prompt: [Int32] = [Int32(turn * 10), Int32(turn * 10 + 1)]+ let promptCount = kv.count + prompt.count+ kv += prompt+ kv += [Int32(turn * 10 + 2), Int32(turn * 10 + 3)]+ record += prompt+ record += MultimodalTurnRecord.generatedTokenIDs(+ kvTokenIDs: kv, promptCount: promptCount)+ }+ #expect(record == kv)+ }++ @Test func identityRoundTripsAndDistinguishesEveryField() throws {+ let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)+ let decoded = try JSONDecoder().decode(+ ConversationIdentity.self, from: try JSONEncoder().encode(identity))+ #expect(decoded == identity)++ #expect(decoded != ConversationIdentity(+ modelID: "other", sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version))+ #expect(decoded != ConversationIdentity(+ modelID: identity.modelID, sourceSnapshotHash: "deadbeef",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version))+ #expect(decoded != ConversationIdentity(+ modelID: identity.modelID, sourceSnapshotHash: identity.sourceSnapshotHash,+ templateIdentity: "gemma4-it-text-no-tools-v2",+ imageProcessingVersion: VisionImageProcessing.version))+ #expect(decoded != ConversationIdentity(+ modelID: identity.modelID, sourceSnapshotHash: identity.sourceSnapshotHash,+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version + 1))+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillReplayCoercionTests.swift b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillReplayCoercionTests.swiftnew file mode 100644index 00000000..2d9b8bb2--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillReplayCoercionTests.swift@@ -0,0 +1,20 @@+import Testing+@testable import TurboFieldfare++/// A stored conversation is replayed through prefill whatever the turn+/// preference says.+///+/// With prefill off, a replay ran through the per-token decode loop at decode+/// speed: a 12K-token reopen took longer than the service's restore deadline,+/// which then dropped the connection and forced a reload.+@Suite struct PrefillReplayCoercionTests {+ @Test func prefillOffIsCoercedToChunkedForAReplay() {+ let coerced = PrefillRuntimeConfig.off.coercedForReplay()+ #expect(coerced != nil)+ #expect(coerced?.mode == .chunked)+ }++ @Test func aPrefillThatAlreadyRunsIsLeftAlone() {+ #expect(PrefillRuntimeConfig.defaultChunked.coercedForReplay() == nil)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/StoredModelInputTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/StoredModelInputTests.swiftnew file mode 100644index 00000000..1eca84cb--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/StoredModelInputTests.swift@@ -0,0 +1,212 @@+import CoreGraphics+import CryptoKit+import Foundation+import ImageIO+import Metal+import Testing+import UniformTypeIdentifiers+@testable import TurboFieldfare++/// The stored copy of an image and the checks that decide whether it may stand+/// in for the file the user attached.+@Suite struct StoredModelInputTests {+ @Test(arguments: [false, true])+ func adversarialStoredImageDisappearsOrCorruptsBeforeReplay(corrupt: Bool) throws {+ let device = try #require(MTLCreateSystemDefaultDevice())+ let preprocessor = Gemma4ImagePreprocessor(device: device)+ let source = try Self.writeSourcePNG(width: 48, height: 48)+ defer { try? FileManager.default.removeItem(at: source) }+ _ = try preprocessor.plan(storedModelInput: source)+ if corrupt {+ try Data("not a PNG".utf8).write(to: source)+ } else {+ try FileManager.default.removeItem(at: source)+ }+ #expect(throws: VisionImageError.self) {+ try preprocessor.plan(storedModelInput: source)+ }+ }++ /// The scaling rule maps a source *towards* the token budget in both+ /// directions, so re-deriving a stored image's geometry through it turns a+ /// 48x48 model input into a 768x768 one and every recorded soft-token count+ /// stops matching its span.+ @Test func storedGeometryIsReadOffTheStoredDimensions() throws {+ let stored = try Gemma4ImageGeometry(processedWidth: 48, processedHeight: 48)+ #expect(stored.processedWidth == 48)+ #expect(stored.processedHeight == 48)+ #expect(stored.patchCount == 9)+ #expect(stored.softTokenCount == 1)++ let rescaled = try Gemma4ImageGeometry(sourceWidth: 48, sourceHeight: 48)+ #expect(rescaled.processedWidth == 768)+ }++ @Test func storedGeometryMatchesThePipelineForAnAlreadyProcessedSize() throws {+ let fromSource = try Gemma4ImageGeometry(sourceWidth: 8_000, sourceHeight: 6_000)+ let fromStored = try Gemma4ImageGeometry(+ processedWidth: fromSource.processedWidth,+ processedHeight: fromSource.processedHeight)+ #expect(fromStored == fromSource)+ }++ @Test func storedGeometryRefusesUnalignedAndOversizedPixels() {+ #expect(throws: VisionImageError.self) {+ try Gemma4ImageGeometry(processedWidth: 47, processedHeight: 48)+ }+ #expect(throws: VisionImageError.self) {+ try Gemma4ImageGeometry(processedWidth: 48, processedHeight: 0)+ }+ // 1,008 x 720 is 48-aligned but 725,760 pixels, past the 645,120 budget.+ #expect(throws: VisionImageError.self) {+ try Gemma4ImageGeometry(processedWidth: 1_008, processedHeight: 720)+ }+ }++ @Test func modelInputPixelsDropAlphaAndRowPadding() {+ // Two rows of two pixels in a surface whose rows are four pixels wide,+ // so both the alpha channel and the row remainder must be skipped.+ let rowBytes = 16+ var surface = [UInt8](repeating: 0xAA, count: rowBytes * 2)+ let pixels: [(Int, Int, [UInt8])] = [+ (0, 0, [1, 2, 3, 255]), (0, 1, [4, 5, 6, 255]),+ (1, 0, [7, 8, 9, 255]), (1, 1, [10, 11, 12, 255]),+ ]+ for (y, x, rgba) in pixels {+ for (offset, value) in rgba.enumerated() {+ surface[y * rowBytes + x * 4 + offset] = value+ }+ }+ let packed = surface.withUnsafeBufferPointer {+ Gemma4ImagePreprocessor.modelInputPixels(+ rgba: $0.baseAddress!, rowBytes: rowBytes, width: 2, height: 2)+ }+ #expect(packed.rgb8 == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])+ #expect(packed.width == 2)+ #expect(packed.height == 2)+ #expect(packed.digest == SHA256.hash(data: packed.rgb8)+ .map { String(format: "%02x", $0) }.joined())+ }++ /// The round trip the whole feature rests on: preprocess a source image,+ /// store the model-input copy, and get byte-identical patches back from the+ /// stored file. If this ever stops holding, a reopened conversation would+ /// continue on an image the model never saw, so the digest — not this+ /// test's optimism — is what production relies on.+ @Test func aStoredCopyPatchifiesToTheSameBytesAsTheSourceDid() throws {+ let device = try #require(MTLCreateSystemDefaultDevice())+ let preprocessor = Gemma4ImagePreprocessor(device: device)+ let source = try Self.writeSourcePNG(width: 200, height: 100)+ defer { try? FileManager.default.removeItem(at: source) }++ let live = try preprocessor.preprocess(+ try preprocessor.plan(fileURL: source), capturingModelInput: true)+ let modelInput = try #require(live.modelInput)+ #expect(modelInput.width == live.pixels.geometry.processedWidth)+ #expect(modelInput.height == live.pixels.geometry.processedHeight)++ let stored = try Self.writeModelInputPNG(modelInput)+ defer { try? FileManager.default.removeItem(at: stored) }++ let plan = try preprocessor.plan(storedModelInput: stored)+ #expect(plan.geometry == live.pixels.geometry)++ let replayed = try preprocessor.preprocess(+ storedModelInput: plan, expectedDigest: modelInput.digest)+ #expect(Self.bytes(of: replayed.patchesBF16)+ == Self.bytes(of: live.pixels.patchesBF16))+ #expect(Self.bytes(of: replayed.positionsInt32x2)+ == Self.bytes(of: live.pixels.positionsInt32x2))+ }++ @Test func aStoredCopyWhoseDigestChangedIsRefused() throws {+ let device = try #require(MTLCreateSystemDefaultDevice())+ let preprocessor = Gemma4ImagePreprocessor(device: device)+ let source = try Self.writeSourcePNG(width: 200, height: 100)+ defer { try? FileManager.default.removeItem(at: source) }+ let modelInput = try #require(try preprocessor.preprocess(+ try preprocessor.plan(fileURL: source),+ capturingModelInput: true).modelInput)+ let stored = try Self.writeModelInputPNG(modelInput)+ defer { try? FileManager.default.removeItem(at: stored) }++ // Case is not identity: the same digest in upper case still admits.+ _ = try preprocessor.preprocess(+ storedModelInput: try preprocessor.plan(storedModelInput: stored),+ expectedDigest: modelInput.digest.uppercased())++ // Fails closed rather than replaying pixels the model never saw. PNG+ // decode of an sRGB 8-bit file is very likely an identity and nowhere+ // documented as one, which is why the check is not optional.+ #expect(throws: VisionImageError.self) {+ try preprocessor.preprocess(+ storedModelInput: try preprocessor.plan(storedModelInput: stored),+ expectedDigest: String(repeating: "0", count: 64))+ }+ }++ @Test func aStoredImageOffTheAlignmentGridIsRefusedBeforeItIsDecoded() throws {+ let device = try #require(MTLCreateSystemDefaultDevice())+ let preprocessor = Gemma4ImagePreprocessor(device: device)+ let url = try Self.writeSourcePNG(width: 50, height: 48)+ defer { try? FileManager.default.removeItem(at: url) }+ #expect(throws: VisionImageError.self) {+ try preprocessor.plan(storedModelInput: url)+ }+ }++ private static func bytes(of buffer: MTLBuffer) -> [UInt8] {+ Array(UnsafeBufferPointer(+ start: buffer.contents().assumingMemoryBound(to: UInt8.self),+ count: buffer.length))+ }++ /// Writes the model-input RGB8 as a lossless PNG, the way the conversation+ /// store does: 24-bit, no alpha, sRGB, no resampling.+ private static func writeModelInputPNG(_ pixels: VisionModelInputPixels) throws -> URL {+ let provider = try #require(CGDataProvider(data: Data(pixels.rgb8) as CFData))+ let image = try #require(CGImage(+ width: pixels.width, height: pixels.height,+ bitsPerComponent: 8, bitsPerPixel: 24,+ bytesPerRow: pixels.width * 3,+ space: CGColorSpace(name: CGColorSpace.sRGB)!,+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue),+ provider: provider, decode: nil, shouldInterpolate: false,+ intent: .defaultIntent))+ return try write(image, name: "model-input")+ }++ private static func writeSourcePNG(width: Int, height: Int) throws -> URL {+ let rowBytes = width * 4+ var bytes = [UInt8](repeating: 255, count: rowBytes * height)+ for y in 0..<height {+ for x in 0..<width {+ let offset = y * rowBytes + x * 4+ bytes[offset] = UInt8((x * 5 + y * 3) % 256)+ bytes[offset + 1] = UInt8((x * 7) % 256)+ bytes[offset + 2] = UInt8((y * 11) % 256)+ }+ }+ let image = try bytes.withUnsafeMutableBytes { raw -> CGImage in+ let context = try #require(CGContext(+ data: raw.baseAddress,+ width: width, height: height,+ bitsPerComponent: 8, bytesPerRow: rowBytes,+ space: CGColorSpace(name: CGColorSpace.sRGB)!,+ bitmapInfo: CGBitmapInfo.byteOrder32Big.rawValue+ | CGImageAlphaInfo.premultipliedLast.rawValue))+ return try #require(context.makeImage())+ }+ return try write(image, name: "source")+ }++ private static func write(_ image: CGImage, name: String) throws -> URL {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("\(name)-\(UUID().uuidString).png")+ let destination = try #require(CGImageDestinationCreateWithURL(+ url as CFURL, UTType.png.identifier as CFString, 1, nil))+ CGImageDestinationAddImage(destination, image, nil)+ #expect(CGImageDestinationFinalize(destination))+ return url+ }+}diff --git a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swiftindex 8fb29152..5ebcd6db 100644--- a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift+++ b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift@@ -15,6 +15,20 @@ struct TokenizerTests {// MARK: - Special tokens+ /// The envelope the continuation rule reserves for a turn has to cover+ /// what the real template wraps a one-word message in. A template change+ /// that grew past it would put rows marked "continue" in front of a+ /// composer that refuses every message, which is the defect the envelope+ /// exists to prevent.+ @Test("The turn envelope covers the continuation template")+ func turnEnvelopeCoversTheContinuationTemplate() {+ let shortest = tok.encodeTextContinuation(userContent: "x").count+ #expect(shortest > 1)+ let envelope = ConversationGenerationReserve.turnEnvelope+ #expect(shortest <= envelope,+ "a one-word turn costs \(shortest) tokens, past the envelope of \(envelope)")+ }+@Test("Special token IDs are distinct and within vocab")func specialTokensDistinct() {let ids: [Int32] = [tok.bosID, tok.eosID, tok.padID, tok.endOfTurnID]diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swiftindex 666ad1e6..f876e0ff 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift@@ -85,6 +85,183 @@ import Testing#expect(settings.visionResidencyPolicy == .onDemand)}+ /// Additive, like every field around it: a settings file written before the+ /// sidebar existed decodes with the list shown, and a hidden one survives a+ /// round trip. Neither costs a version bump.+ @Test func aSettingsFileWithoutSidebarVisibleDecodesToShown() throws {+ let json = """+ {"version":2,"contextTokens":8192,"expertCacheSlots":16,\+ "temperature":0.2,"topKEnabled":true,"topK":64,"topPEnabled":true,\+ "topP":0.95,"prefillEnabled":true}+ """+ let settings = try JSONDecoder().decode(+ MacAppSettings.self, from: Data(json.utf8))+ #expect(settings.sidebarVisible)+ #expect(settings.version == 2)+ }++ @Test(arguments: [true, false])+ func sidebarVisibleRoundTrips(_ visible: Bool) throws {+ let initial = MacAppSettings(sidebarVisible: visible)+ let decoded = try JSONDecoder().decode(+ MacAppSettings.self, from: try JSONEncoder().encode(initial))+ #expect(decoded.sidebarVisible == visible)+ #expect(decoded.version == MacAppSettings.currentVersion)+ }++ @Test func selectedConversationRoundTripsAndIsAdditive() throws {+ let id = UUID()+ let initial = MacAppSettings(selectedConversationID: id)+ let decoded = try JSONDecoder().decode(+ MacAppSettings.self, from: try JSONEncoder().encode(initial))+ #expect(decoded.selectedConversationID == id)++ let oldJSON = """+ {"version":2,"contextTokens":8192,"expertCacheSlots":16,+ "temperature":0.2,"topKEnabled":true,"topK":64,"topPEnabled":true,+ "topP":0.95,"prefillEnabled":true}+ """+ let old = try JSONDecoder().decode(+ MacAppSettings.self, from: Data(oldJSON.utf8))+ #expect(old.selectedConversationID == nil)+ }++ @MainActor+ @Test func contextWithoutASelectedRowPersistsImmediately() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = root.appendingPathComponent("model.gturbo", isDirectory: true)+ let model = AppModel(modelDirectory: directory, settingsPersistenceEnabled: true)++ model.setMaxContextTokens(4_096)++ let saved = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: directory)+ #expect(saved.contextTokens == 4_096)+ }++ @MainActor+ @Test func unknownRestoredSelectionIsClearedFromSettings() async throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = root.appendingPathComponent("model.gturbo", isDirectory: true)+ try MacAppSettingsFileStore.save(+ MacAppSettings(selectedConversationID: UUID()),+ forModelDirectory: directory)++ let model = AppModel(modelDirectory: directory, settingsPersistenceEnabled: true)+ try await waitUntil {+ MacAppSettingsFileStore.loadOrCreate(+ forModelDirectory: directory).selectedConversationID == nil+ }++ #expect(model.history.selection == nil)+ }++ /// The Inspector's visibility is remembered on the same terms as the+ /// sidebar's: additive, no version bump, and a file that predates it opens+ /// with the panel shown rather than with the window missing a side.+ @Test func aSettingsFileWithoutInspectorVisibleDecodesToShown() throws {+ let json = """+ {"version":2,"contextTokens":8192,"expertCacheSlots":16,\+ "temperature":0.2,"topKEnabled":true,"topK":64,"topPEnabled":true,\+ "topP":0.95,"prefillEnabled":true,"sidebarVisible":false}+ """+ let settings = try JSONDecoder().decode(+ MacAppSettings.self, from: Data(json.utf8))+ #expect(settings.inspectorVisible)+ #expect(!settings.sidebarVisible)+ #expect(settings.version == 2)+ }++ @Test(arguments: [true, false])+ func inspectorVisibleRoundTrips(_ visible: Bool) throws {+ let initial = MacAppSettings(inspectorVisible: visible)+ let decoded = try JSONDecoder().decode(+ MacAppSettings.self, from: try JSONEncoder().encode(initial))+ #expect(decoded.inspectorVisible == visible)+ #expect(decoded.version == MacAppSettings.currentVersion)+ }++ /// The v1 file is restamped, and nothing else about it changes.+ ///+ /// 4K has never been the default — `AppContextLengthOption.eightK` is+ /// 8K in v1 too — so a stored 4,096 is a choice someone made to fit an 8 GB+ /// machine, not a stale default to repair. Rewriting it here doubled the+ /// full-attention KV of that session and wrote the original off disk, with+ /// 4K still offered in the picker.+ /// The mirror image of the migration test. A file written by a newer build+ /// decodes cleanly here — every key is `decodeIfPresent` — so rejecting it+ /// on the version number alone sent it through the catch that deletes the+ /// file, and running an older build once against the same model directory+ /// silently reset everything its owner had chosen, a deliberate 4K context+ /// included. This build runs on defaults and leaves the file alone.+ @Test func afileFromANewerBuildIsLeftAloneRatherThanDeleted() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: model)+ let future = MacAppSettings(+ version: MacAppSettings.currentVersion + 1,+ contextTokens: 4_096,+ expertCacheSlots: 24,+ temperature: 0.4)+ try JSONEncoder().encode(future).write(to: fileURL)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)++ #expect(settings == MacAppSettings(),+ "an unknown version should be run on defaults, not adopted")+ #expect(FileManager.default.fileExists(atPath: fileURL.path),+ "the newer build's settings file was deleted")+ let persisted = try JSONDecoder().decode(+ MacAppSettings.self, from: Data(contentsOf: fileURL))+ #expect(persisted == future,+ "the newer build's settings were overwritten by this one")+ }++ @Test func versionOneMigrationKeepsAChosen4KContext() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: model)+ let legacy = MacAppSettings(+ version: 1,+ contextTokens: 4_096,+ expertCacheSlots: 24,+ temperature: 0.4)+ try JSONEncoder().encode(legacy).write(to: fileURL)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)+ let persisted = try JSONDecoder().decode(+ MacAppSettings.self, from: Data(contentsOf: fileURL))++ #expect(settings.version == MacAppSettings.currentVersion)+ #expect(settings.contextTokens == 4_096,+ "a deliberately chosen 4K context was rewritten by the migration")+ #expect(settings.expertCacheSlots == 24)+ #expect(settings.temperature == 0.4)+ #expect(persisted == settings)+ #expect(AppContextLengthOption.eightK.tokens != 4_096,+ "if 4K ever becomes the default, this test is asking the wrong question")+ }++ /// A v1 file at any other context is restamped untouched too — the version+ /// bump must not be a licence to edit values.+ @Test func versionOneMigrationOnlyRestampsTheVersion() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: model)+ let legacy = MacAppSettings(version: 1, contextTokens: 8_192)+ try JSONEncoder().encode(legacy).write(to: fileURL)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)++ var expected = legacy+ expected.version = MacAppSettings.currentVersion+ #expect(settings == expected)+ }+@Test(arguments: AppNewlineShortcut.allCases)func newlineShortcutRoundTrips(_ shortcut: AppNewlineShortcut) throws {let initial = MacAppSettings(newlineShortcut: shortcut)@@ -138,7 +315,7 @@ import Testing}@MainActor- @Test func appModelLoadsAndSavesPersistedSettings() throws {+ @Test func appModelLoadsAndSavesPersistedSettings() async throws {let root = try makeTemporaryRoot()defer { try? FileManager.default.removeItem(at: root) }let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)@@ -181,7 +358,8 @@ import Testingmodel.loadState = .ready(modelDirectory: modelDirectory, loadSeconds: 0)model.promptText = "Save these settings"- model.run()+ model.send()+ await SendWaiting.generationStarts(model)let saved = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: modelDirectory)#expect(saved.temperature == 0.6)diff --git a/Tests/TurboFieldfareApp/Core/Configuration/VisionSectionVisibilityTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/VisionSectionVisibilityTests.swiftindex 228d2aa0..1f021d0b 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/VisionSectionVisibilityTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/VisionSectionVisibilityTests.swift@@ -32,10 +32,9 @@ import Testing#expect(shows(modelInstalled: true, packInstalled: false))}- /// Installed and healthy is the one case with nothing to say, so the section- /// collapses rather than occupying the inspector permanently.- @Test func anInstalledHealthyPackCollapsesTheSection() {- #expect(!shows(modelInstalled: true, packInstalled: true))+ /// Removal remains available after install, so the section must not vanish.+ @Test func anInstalledHealthyPackKeepsTheRemoveActionReachable() {+ #expect(shows(modelInstalled: true, packInstalled: true))}@Test func workInProgressKeepsTheSectionOpen() {diff --git a/Tests/TurboFieldfareApp/Core/Diagnostics/AppModelLiveMetricsTests.swift b/Tests/TurboFieldfareApp/Core/Diagnostics/AppModelLiveMetricsTests.swiftindex 92c50b09..ba6e92a2 100644--- a/Tests/TurboFieldfareApp/Core/Diagnostics/AppModelLiveMetricsTests.swift+++ b/Tests/TurboFieldfareApp/Core/Diagnostics/AppModelLiveMetricsTests.swift@@ -53,15 +53,14 @@ import Testingmodel.apply(.token(AppTokenEvent(index: 9, textDelta: "z", elapsedDecodeSeconds: 5)))model.promptText = "go"- model.run()+ model.send()+ await SendWaiting.generationStarts(model)#expect(model.phase == .prefill)#expect(model.liveTokenCount == 0)#expect(model.liveElapsedDecodeSeconds == 0)#expect(model.livePrefillDone == 0)model.cancel()- for _ in 0..<200 where model.isRunning {- try? await Task.sleep(nanoseconds: 5_000_000)- }+ await SendWaiting.turnEnds(model)}@MainActordiff --git a/Tests/TurboFieldfareApp/Core/History/ConversationContinuabilityTests.swift b/Tests/TurboFieldfareApp/Core/History/ConversationContinuabilityTests.swiftnew file mode 100644index 00000000..8f239d0e--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/History/ConversationContinuabilityTests.swift@@ -0,0 +1,186 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// The rule a sidebar row shows and a reopen obeys. It has to be the same rule+/// the runtime's admission guard uses, or a row offers to continue a chat whose+/// first turn is then refused.+@Suite struct ConversationContinuabilityTests {+ private let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private func meta(kvTokens: Int?,+ identity: ConversationIdentity? = nil,+ imageCount: Int = 0,+ recordedContext: Int = 8_192) -> ConversationMeta {+ ConversationMeta(+ id: UUID(), title: "t", createdAt: Date(), updatedAt: Date(),+ turnCount: 2, kvTokens: kvTokens, imageCount: imageCount,+ identity: identity ?? self.identity,+ session: ConversationSessionSettings(+ contextTokens: recordedContext, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: ConversationSampling(+ temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 4_096))+ }++ @Test func aNewerFormatCannotReplayEvenWhenItsIdentityAndTokensMatch() {+ var newer = meta(kvTokens: 32)+ newer.version = ConversationMeta.currentVersion + 1+ #expect(ConversationContinuability.evaluate(+ meta: newer, currentContext: 8_192, identity: identity)+ == .cannotReplay(reason: .newerFormat))+ }++ /// Both sides of the exact boundary, because an off-by-one here is a row+ /// that promises what the next turn refuses.+ @Test func theBoundaryIsTheSameOneAdmissionUses() {+ let context = 4_096+ let largest = context - ConversationGenerationReserve.tokens+ - ConversationGenerationReserve.turnEnvelope+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: largest), currentContext: context, identity: identity)+ == .continuable)+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: largest + 1), currentContext: context,+ identity: identity)+ == .needsContext(+ required: ConversationGenerationReserve.contextRequired(+ forLineage: largest + 1)))+ // The lineage the row admits still fits `generate`'s own check once+ // the smallest turn is on it: the rule that used to admit a row the+ // next message was then refused on.+ #expect(ConversationGenerationReserve.fits(+ tokens: largest + ConversationGenerationReserve.turnEnvelope,+ maxContext: context))+ }++ /// A boundary token the last run left outside the KV is replayed ahead of+ /// the next turn, so it is part of what has to fit.+ @Test func aBoundaryTokenAwaitingReplayCountsAgainstTheContext() {+ let context = 4_096+ let largest = context - ConversationGenerationReserve.tokens+ - ConversationGenerationReserve.turnEnvelope+ var withBoundary = meta(kvTokens: largest)+ withBoundary.boundary = ConversationBoundary(tokens: [7], needsReplay: true)+ #expect(ConversationContinuability.evaluate(+ meta: withBoundary, currentContext: context, identity: identity)+ == .needsContext(+ required: ConversationGenerationReserve.contextRequired(+ forLineage: largest + 1)))+ // A boundary that is not replayed costs nothing.+ var committed = meta(kvTokens: largest)+ committed.boundary = ConversationBoundary(tokens: [7], needsReplay: false)+ #expect(ConversationContinuability.evaluate(+ meta: committed, currentContext: context, identity: identity)+ == .continuable)+ }++ /// The recorded context is informational: a small chat made at 8K continues+ /// at 4K, and refusing it because of the number in the file would be a+ /// refusal with no cause.+ @Test func theRecordedContextDoesNotDecide() {+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: 3_000, recordedContext: 8_192),+ currentContext: 4_096, identity: identity) == .continuable)+ }++ /// Fail closed. A conversation whose count was never reported would+ /// otherwise be restored, admitted, and only then found not to fit.+ @Test func anUnknownTokenCountIsNotContinuable() {+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: nil), currentContext: 8_192, identity: identity)+ == .cannotReplay(reason: .tokenCountUnknown))+ }++ @Test func everyIdentityFieldRefusesReplayOnItsOwn() {+ func recorded(_ change: (inout ConversationIdentity) -> Void)+ -> ConversationIdentity {+ var value = identity+ change(&value)+ return value+ }+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: 100, identity: recorded { $0 = ConversationIdentity(+ modelID: "other", sourceSnapshotHash: $0.sourceSnapshotHash,+ templateIdentity: $0.templateIdentity,+ imageProcessingVersion: $0.imageProcessingVersion) }),+ currentContext: 8_192, identity: identity)+ == .cannotReplay(reason: .differentModel))+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: 100, identity: recorded { $0 = ConversationIdentity(+ modelID: $0.modelID, sourceSnapshotHash: "deadbeef",+ templateIdentity: $0.templateIdentity,+ imageProcessingVersion: $0.imageProcessingVersion) }),+ currentContext: 8_192, identity: identity)+ == .cannotReplay(reason: .differentCheckpoint))+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: 100, identity: recorded { $0 = ConversationIdentity(+ modelID: $0.modelID, sourceSnapshotHash: $0.sourceSnapshotHash,+ templateIdentity: "gemma4-it-text-no-tools-v2",+ imageProcessingVersion: $0.imageProcessingVersion) }),+ currentContext: 8_192, identity: identity)+ == .cannotReplay(reason: .differentTemplate))+ }++ /// A preprocessing bump only matters to a conversation that has images.+ /// Refusing a text chat for it would be a refusal the user cannot act on.+ @Test func anImageProcessingBumpOnlyRefusesConversationsWithImages() {+ let bumped = ConversationIdentity(+ modelID: identity.modelID,+ sourceSnapshotHash: identity.sourceSnapshotHash,+ templateIdentity: identity.templateIdentity,+ imageProcessingVersion: identity.imageProcessingVersion + 1)+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: 100, identity: bumped, imageCount: 0),+ currentContext: 8_192, identity: identity) == .continuable)+ #expect(ConversationContinuability.evaluate(+ meta: meta(kvTokens: 100, identity: bumped, imageCount: 2),+ currentContext: 8_192, identity: identity)+ == .cannotReplay(reason: .differentImageProcessing))+ }+}++@Suite struct ConversationTitleTests {+ @Test func aShortMessageIsItsOwnTitle() {+ #expect(ConversationTitle.fromFirstMessage("Explain RoPE")+ == "Explain RoPE")+ }++ @Test func whitespaceIsCollapsedSoARowIsOneLine() {+ #expect(ConversationTitle.fromFirstMessage(" Explain\n\n RoPE ")+ == "Explain RoPE")+ }++ @Test func anEmptyMessageFallsBackRatherThanShowingABlankRow() {+ #expect(ConversationTitle.fromFirstMessage(" \n ")+ == ConversationTitle.untitled)+ }++ /// Cut on a word boundary: clipping mid-word reads as damage rather than as+ /// a title.+ @Test func aLongMessageIsCutOnAWordBoundary() {+ let text = String(repeating: "alpha beta ", count: 20)+ let title = ConversationTitle.fromFirstMessage(text)+ #expect(title.count <= ConversationTitle.maximumCharacters + 1)+ #expect(title.hasSuffix("\u{2026}"))+ #expect(!title.dropLast().hasSuffix(" "))+ #expect(title.dropLast().split(separator: " ").allSatisfy {+ $0 == "alpha" || $0 == "beta"+ })+ }++ /// One very long word has no boundary to cut at, and must still produce a+ /// title rather than an ellipsis alone.+ @Test func aSingleLongWordIsStillATitle() {+ let title = ConversationTitle.fromFirstMessage(+ String(repeating: "x", count: 200))+ #expect(title.count == ConversationTitle.maximumCharacters + 1)+ #expect(title.hasPrefix("xxxx"))+ }+}diff --git a/Tests/TurboFieldfareApp/Core/History/ConversationDocumentTests.swift b/Tests/TurboFieldfareApp/Core/History/ConversationDocumentTests.swiftnew file mode 100644index 00000000..cb3608f5--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/History/ConversationDocumentTests.swift@@ -0,0 +1,358 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// One walk over the records, so display and replay cannot disagree about what+/// a conversation holds.+///+/// They used to be three walks, and two of them disagreeing is what produced+/// both defects pinned here: a reopened turn drawn with no pictures at all+/// (`e68b8fe1`), and a conversation with a picture in each of two turns that+/// could never be continued again (`2cfd1d84`). Every case checks the three+/// answers against each other rather than one at a time.+@Suite struct ConversationDocumentTests {+ private static let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private static let placeholder = MultimodalPromptRenderer.imageTokenID++ private static func meta(id: UUID = UUID(),+ boundary: ConversationBoundary = ConversationBoundary())+ -> ConversationMeta {+ ConversationMeta(+ id: id, title: "stored", createdAt: Date(), updatedAt: Date(),+ identity: identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "on-demand"),+ sampling: ConversationSampling(+ temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 8_192),+ boundary: boundary)+ }++ private static func opened(_ records: [TranscriptRecord],+ boundary: ConversationBoundary = ConversationBoundary())+ -> ConversationOpenResult {+ ConversationOpenResult(+ meta: meta(boundary: boundary), records: records,+ isReadOnly: false, droppedTornFinalLine: false)+ }++ private static func image(_ name: String, softTokens: Int)+ -> ConversationImageRecord {+ ConversationImageRecord(+ id: UUID(), displayName: name,+ pixelsFile: "images/\(name).png",+ thumbnailFile: "images/\(name).thumb.jpg",+ sourceDigest: name, modelInputDigest: "digest-\(name)",+ width: 768, height: 768, softTokens: softTokens)+ }++ private static let directory = URL(+ fileURLWithPath: "/tmp/conversations/xyz", isDirectory: true)++ // MARK: - The three answers agree++ /// Turns, pairs and lineage come out of the same walk, so what the+ /// transcript draws, what it pairs, and what a replay puts back all describe+ /// the same conversation.+ @Test func turnsPairsAndLineageDescribeTheSameConversation() throws {+ let records: [TranscriptRecord] = [+ .header(ConversationHeaderRecord(id: UUID(), createdAt: Date())),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "one", tokens: [1, 2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "a", tokens: [3])),+ .title(ConversationTitleRecord(+ title: "renamed", source: .user, at: Date())),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "two", tokens: [4])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "b", tokens: [5, 6])),+ ]+ let document = ConversationDocument.load(+ Self.opened(records, boundary: ConversationBoundary(+ tokens: [99], needsReplay: true)),+ directory: Self.directory)++ #expect(document.turns.map(\.text) == ["one", "a", "two", "b"])+ #expect(document.pairs.map(\.user.text) == ["one", "two"])+ #expect(document.pairs.map(\.assistant.text) == ["a", "b"])+ guard case .success(let lineage) = document.lineage else {+ Issue.record("a complete record refused to replay")+ return+ }+ // The lineage is the turns' own IDs, in the turns' own order.+ #expect(lineage.tokenIDs == document.turns.flatMap { $0.tokenIDs ?? [] })+ #expect(lineage.committedTurns == document.pairs.count)+ #expect(lineage.boundaryTokenIDs == [99])+ #expect(lineage.boundaryNeedsReplay)+ // Neither the header nor the rename is a turn.+ #expect(document.turns.count == 4)+ }++ /// An unpaired final user turn is in the turns and not in the pairs: it is+ /// the question of an exchange that has no answer yet.+ @Test func aUserTurnWithNoReplyIsNotAPair() throws {+ let records: [TranscriptRecord] = [+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "one", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "a", tokens: [2])),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "dangling", tokens: [3])),+ ]+ let document = ConversationDocument.load(+ Self.opened(records), directory: Self.directory)+ #expect(document.turns.count == 3)+ #expect(document.pairs.count == 1)+ guard case .success(let lineage) = document.lineage else {+ Issue.record("a complete record refused to replay")+ return+ }+ #expect(lineage.committedTurns == 2, "the dangling turn is still in the KV")+ }++ // MARK: - The two refusals++ /// A turn with no recorded IDs cannot be replayed, and the wording the+ /// window shows for it does not move: it reaches the user through+ /// `AppInferenceError.conversationRestoreFailed`.+ @Test func aTurnWithoutTokensRefusesTheLineageAndStaysReadable() throws {+ let records: [TranscriptRecord] = [+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "one", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "no ids", tokens: nil)),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "two", tokens: [2])),+ ]+ let document = ConversationDocument.load(+ Self.opened(records), directory: Self.directory)++ #expect(document.lineage == .failure(.turnWithoutTokens))+ #expect(ConversationRecordError.turnWithoutTokens.description+ == "a stored turn has no recorded tokens")+ // Refused for replay, still readable: losing what the user already read+ // helps nobody.+ #expect(document.turns.map(\.text) == ["one", "no ids", "two"])+ #expect(document.pairs.count == 1)+ }++ /// A picture whose placeholders are not where the turn says cannot be put+ /// back, because the tower's features would land on text.+ @Test func anImageWithNoPlaceholderRunRefusesTheLineage() throws {+ let records: [TranscriptRecord] = [+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "look",+ images: [Self.image("a", softTokens: 4)],+ // Three placeholders where the record claims four.+ tokens: [1] + Array(repeating: Self.placeholder, count: 3) + [2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "ok", tokens: [9])),+ ]+ let document = ConversationDocument.load(+ Self.opened(records), directory: Self.directory)++ #expect(document.lineage == .failure(.imageSpanNotInItsTurn))+ #expect(ConversationRecordError.imageSpanNotInItsTurn.description+ == "a stored image's soft tokens are not in the turn that cites it")+ #expect(document.turns.first?.images.count == 1,+ "the picture is still drawn")+ }++ // MARK: - `2cfd1d84`: pictures in two turns++ /// A conversation with pictures in two different turns can be replayed.+ ///+ /// The span search walks one turn's tokens looking for the nth run of image+ /// placeholders, and the caller was handing it the count of images placed+ /// across the whole conversation. So the second image-bearing turn looked+ /// for its own placeholders at an index that only existed if every earlier+ /// image had been in that same turn: the lineage refused it, and the chat+ /// could never be continued again. Found by hand, sending into a chat with+ /// one image in each of two turns.+ @Test func aconversationWithImagesInTwoTurnsReplays() throws {+ // Two user turns, one picture each, with text either side of the run.+ let first = [Int32(1)] + Array(repeating: Self.placeholder, count: 4) + [2]+ let second = [Int32(3), 4] + Array(repeating: Self.placeholder, count: 4) + [5]+ let records: [TranscriptRecord] = [+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "one",+ images: [Self.image("a", softTokens: 4)], tokens: first)),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "ok", tokens: [9])),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "two",+ images: [Self.image("b", softTokens: 4)], tokens: second)),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "ok", tokens: [9])),+ ]++ let document = ConversationDocument.load(+ Self.opened(records), directory: Self.directory)+ guard case .success(let lineage) = document.lineage else {+ Issue.record("a chat with pictures in two turns refused to replay")+ return+ }++ #expect(lineage.images.count == 2)+ // First turn: one text token, then the run.+ #expect(lineage.images[0].tokenLowerBound == 1)+ #expect(lineage.images[0].tokenCount == 4)+ // Second: six tokens of turn one, one of the reply, then two of text.+ #expect(lineage.images[1].tokenLowerBound == 6 + 1 + 2)+ #expect(lineage.images[1].tokenCount == 4)+ // And every placeholder the lineage points at really is one.+ for placed in lineage.images {+ let span = placed.tokenLowerBound..<(placed.tokenLowerBound + placed.tokenCount)+ #expect(span.allSatisfy { lineage.tokenIDs[$0] == Self.placeholder })+ }+ // The same walk drew the same two pictures, one per turn — which is the+ // agreement the separate walks did not have.+ #expect(document.turns.map(\.images.count) == [1, 0, 1, 0])+ #expect(document.turns[0].images.first?.id+ == document.pairs[0].user.images.first?.id)+ }++ // MARK: - `e68b8fe1`: the pictures the transcript dropped++ /// A reopened turn keeps the pictures that were attached to it.+ ///+ /// The images were written, recorded and replayed into the KV correctly all+ /// along; the transcript was the one reader that dropped them, because the+ /// records were mapped into chat turns without their attachments and every+ /// reopened turn came back with none. What the model still has in context+ /// and what the window shows have to agree.+ @Test func areopenedTurnKeepsItsImages() throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("stored-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(+ at: directory.appendingPathComponent("images", isDirectory: true),+ withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ // The thumbnail is on disk, so this is the ordinary case rather than+ // the model-input fallback.+ try Data("thumbnail".utf8).write(+ to: directory.appendingPathComponent("images/1a2b.thumb.jpg"))+ let image = ConversationImageRecord(+ id: UUID(),+ displayName: "roof.heic",+ pixelsFile: "images/1a2b.png",+ thumbnailFile: "images/1a2b.thumb.jpg",+ sourceDigest: "source-digest",+ modelInputDigest: "model-input-digest",+ width: 896, height: 896, softTokens: 256)+ let records: [TranscriptRecord] = [+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "what is this?",+ images: [image],+ tokens: [1] + Array(repeating: Self.placeholder, count: 256) + [2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "a roof.", tokens: [4, 5])),+ ]++ let document = ConversationDocument.load(+ Self.opened(records), directory: directory)+ let attached = try #require(document.turns.first?.images.first)+ #expect(document.turns.first?.images.count == 1)+ // The thumbnail, not the model input: the PNG is the exact bytes the+ // tower patchified and resampling it for display would be reading the+ // wrong copy.+ #expect(attached.fileURL == directory.appendingPathComponent("images/1a2b.thumb.jpg"))+ #expect(attached.displayName == "roof.heic")+ // The digest the thumbnail cache keys on, so a picture already drawn in+ // the composer is not decoded again for the transcript.+ #expect(attached.sha256 == "source-digest")+ #expect(attached.id == image.id)+ #expect(document.turns.last?.images.isEmpty == true,+ "the reply was given an image")+ // The pair the transcript draws is the same turn, not a second reading+ // of the record.+ #expect(document.pairs.first?.user.images.first?.fileURL == attached.fileURL)+ // And replay points at the model input, which is the other copy.+ guard case .success(let lineage) = document.lineage else {+ Issue.record("a turn with one picture refused to replay")+ return+ }+ #expect(lineage.images.first?.fileURL+ == directory.appendingPathComponent("images/1a2b.png"))+ #expect(lineage.images.first?.expectedDigest == "model-input-digest")+ }++ /// A conversation whose thumbnail is gone still shows its picture.+ ///+ /// The model input is the same image and is never resampled for replay, so+ /// reading it for the transcript costs nothing. Conversations damaged before+ /// the deletion was stopped would otherwise stay blank forever.+ @Test func amissingThumbnailFallsBackToTheModelInput() throws {+ let image = ConversationImageRecord(+ id: UUID(), displayName: "roof.heic",+ pixelsFile: "images/1a2b.png",+ thumbnailFile: "images/1a2b.thumb.jpg",+ sourceDigest: "source", modelInputDigest: "input",+ width: 768, height: 768, softTokens: 256)+ let records: [TranscriptRecord] = [+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "what is this?",+ images: [image], tokens: [1])),+ ]++ // Neither file exists under /tmp/conversations/xyz, so this is the+ // no-thumbnail case.+ let document = ConversationDocument.load(+ Self.opened(records), directory: Self.directory)+ let attached = try #require(document.turns.first?.images.first)+ #expect(attached.fileURL+ == Self.directory.appendingPathComponent("images/1a2b.png"))+ // The conversation store owns these, so no release path that finishes a+ // turn can be handed one: `AppImageAttachmentStore.remove` takes a+ // `StagedImage` and this is not one.+ #expect(attached.staged == nil)+ guard case .stored = attached else {+ Issue.record("a stored conversation's picture is not a StoredImage")+ return+ }+ }++ // MARK: - Records that are not turns++ @Test func headerTitleOriginPartialAndUnknownRecordsAreNotTurns() throws {+ let origin = ConversationOriginRecord(+ identity: Self.identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "on-demand"),+ sampling: ConversationSampling(+ temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 8_192),+ boundary: ConversationBoundary(), at: Date())+ let records: [TranscriptRecord] = [+ .header(ConversationHeaderRecord(id: UUID(), createdAt: Date())),+ .origin(origin),+ .title(ConversationTitleRecord(title: "t", source: .user, at: Date())),+ // A checkpoint of a reply still being generated, superseded below.+ .partial(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "half", tokens: [9, 9])),+ .unknown(type: "summary"),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "one", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "a", tokens: [2])),+ ]+ let document = ConversationDocument.load(+ Self.opened(records), directory: Self.directory)+ #expect(document.turns.count == 2)+ #expect(document.pairs.count == 1)+ guard case .success(let lineage) = document.lineage else {+ Issue.record("a complete record refused to replay")+ return+ }+ #expect(lineage.tokenIDs == [1, 2], "a partial reply entered the KV")+ }+}diff --git a/Tests/TurboFieldfareApp/Core/History/ConversationErrorReportingTests.swift b/Tests/TurboFieldfareApp/Core/History/ConversationErrorReportingTests.swiftnew file mode 100644index 00000000..243961c0--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/History/ConversationErrorReportingTests.swift@@ -0,0 +1,338 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// One test per row of the plan's "errors stay visible" table.+///+/// Every one of these was a `try?` or a `catch` that turned a real fault into a+/// benign-looking default: an empty sidebar over a store that could not be+/// listed, a picture dropped from a record while its placeholder tokens stayed+/// in the turn's IDs, a row that "could not be read" with no way to ask why, and+/// any lock failure at all reading as "another window has it". A failure that+/// changes what the user sees has to reach them with its cause.+@Suite struct ConversationErrorReportingTests {+ private static let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private static let session = ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16, visionResidencyPolicy: "on-demand")++ private static let sampling = ConversationSampling(+ temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 8_192)++ private static func header(_ id: UUID) -> TranscriptRecord {+ .header(ConversationHeaderRecord(+ id: id, createdAt: Date(timeIntervalSince1970: 1_000),+ identity: identity, session: session, sampling: sampling))+ }++ private static func makeRoot(_ label: String) throws -> URL {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("error-reporting-\(label)-\(UUID().uuidString)",+ isDirectory: true)+ try FileManager.default.createDirectory(+ at: root, withIntermediateDirectories: true)+ return root+ }++ @MainActor+ private func readyModel(_ client: FakeInferenceClient, root: URL,+ attachments: AppImageAttachmentStore) async throws+ -> AppModel {+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let fixture = try makeCompleteModelInstall("error-reporting")+ try FileManager.default.moveItem(at: fixture, to: directory)+ let receiptURL = directory.appendingPathComponent("verified-install.json")+ var receipt = try #require(+ JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL))+ as? [String: Any])+ receipt["modelDirectoryPath"] = directory.standardizedFileURL.path+ try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys])+ .write(to: receiptURL)+ try installVisionCompanion(forTextModel: directory)+ let model = AppModel(modelDirectory: directory, client: client,+ attachmentStore: attachments,+ settingsPersistenceEnabled: true)+ model.modelPathText = directory.path+ model.conversationIdentity = Self.identity+ model.installationStatus = .complete+ try await client.ensureLoaded(+ modelDirectory: directory,+ maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions,+ forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ try await model.waitForHistory()+ return model+ }++ // MARK: - Row 1: a list that cannot be read keeps the last one that could++ /// The sidebar used to empty itself. `(try? await store.list()) ?? []` made a+ /// store that could not be enumerated — a permission change, a volume that+ /// went away — look exactly like a user with no chats at all, and the window+ /// then offered New Chat over conversations that were still on disk.+ @MainActor+ @Test func alistThatCannotBeReadKeepsTheLastGoodOneAndSaysWhy() async throws {+ let root = try Self.makeRoot("list")+ defer { try? FileManager.default.removeItem(at: root) }+ let attachments = AppImageAttachmentStore(+ directoryURL: root.appendingPathComponent("staged", isDirectory: true))+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client, root: root, attachments: attachments)+ defer { model.releaseAllAttachments() }++ model.promptText = "the chat that must not vanish"+ model.send()+ await SendWaiting.turnEnds(model)+ try await waitUntil { await model.history.entries.count == 1 }+ model.historyDiagnostic = nil++ // The store's root is a file now, so enumerating it throws rather than+ // coming back empty.+ let storeRoot = await (try #require(model.conversationStore)).rootURL+ try FileManager.default.removeItem(at: storeRoot)+ try Data("not a directory".utf8).write(to: storeRoot)+ await model.refreshHistory()++ #expect(model.history.entries.count == 1,+ "the sidebar emptied itself over a store it could not read")+ #expect(model.history.unreadableCount >= 1)+ let diagnostic = try #require(model.historyDiagnostic)+ #expect(diagnostic.contains("could not be read"),+ Comment(rawValue: diagnostic))+ }++ // MARK: - Row 2: a picture that was not stored ends the replay record++ @Test func aturnWhosePicturesWereNotStoredHasNoReplayCount() throws {+ let id = UUID()+ let records: [TranscriptRecord] = [+ Self.header(id),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(timeIntervalSince1970: 1_010),+ text: "what is this?", tokens: [1, 2], imageWriteFailed: true)),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(timeIntervalSince1970: 1_011),+ text: "a roof", tokens: [3])),+ ]++ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)++ #expect(meta.imageWriteFailed == true)+ #expect(meta.kvTokens == nil,+ "a conversation with a picture behind nothing claimed a count")+ #expect(meta.turnCount == 2, "the turns are still there to read")+ }++ @Test func aconversationWithAnUnwrittenPictureSaysThatRatherThanNoRecord() {+ let meta = ConversationMeta(+ id: UUID(), title: "roofs", createdAt: Date(), updatedAt: Date(),+ turnCount: 2, kvTokens: nil, imageCount: 1,+ identity: Self.identity, session: Self.session, sampling: Self.sampling,+ imageWriteFailed: true)++ let state = ConversationContinuability.evaluate(+ meta: meta, currentContext: 8_192, identity: Self.identity)++ // Not `.tokenCountUnknown`: that is true as well and sends the reader+ // after the wrong thing.+ #expect(state == .cannotReplay(reason: .imageRecordMissing))+ }++ @Test func adocumentRefusesToReplayATurnWhosePictureWasNotStored() {+ let id = UUID()+ let meta = ConversationMeta(+ id: id, title: "roofs", createdAt: Date(), updatedAt: Date(),+ turnCount: 2, kvTokens: nil, imageCount: 1,+ identity: Self.identity, session: Self.session, sampling: Self.sampling,+ imageWriteFailed: true)+ let records: [TranscriptRecord] = [+ Self.header(id),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "what is this?", tokens: [1],+ imageWriteFailed: true)),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "a roof", tokens: [2])),+ ]++ let document = ConversationDocument.load(+ ConversationOpenResult(meta: meta, records: records, isReadOnly: false,+ droppedTornFinalLine: false),+ directory: URL(fileURLWithPath: "/tmp/conversations/\(id.uuidString)",+ isDirectory: true))++ // Still readable: the transcript is what the read-only view exists for.+ #expect(document.pairs.count == 1)+ #expect(document.lineage == .failure(.imageRecordMissing))+ #expect(ConversationRecordError.imageRecordMissing.description+ == "a stored image was never written, and its turn still cites it")+ }++ /// End to end: a picture the writer cannot prepare is said out loud, the+ /// record carries it, and the row stops offering a continuation it could+ /// not honour. Every one of these was silent — the image simply disappeared+ /// from the record while its placeholder tokens stayed in the turn's IDs.+ @MainActor+ @Test func apictureThatCouldNotBeStoredIsReportedAndEndsTheReplayRecord() async throws {+ let root = try Self.makeRoot("image-write")+ defer { try? FileManager.default.removeItem(at: root) }+ let attachments = AppImageAttachmentStore(+ directoryURL: root.appendingPathComponent("staged", isDirectory: true))+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client, root: root, attachments: attachments)+ defer { model.releaseAllAttachments() }++ // Bytes no preprocessor will take, staged exactly as a real picture is:+ // the write fails per image rather than per turn.+ let staged = try attachments.stage(+ data: Data("this is not a picture".utf8), displayName: "roof.png")+ model.promptText = "what is this?"+ model.setComposerAttachmentsForTesting([staged])+ model.send()+ await SendWaiting.turnEnds(model)+ // The turn is written from a task the terminal event starts, so the+ // record is the thing to wait for rather than the run.+ try await waitUntil {+ await model.history.entries.first?.imageWriteFailed == true+ }++ let diagnostic = try #require(model.historyDiagnostic)+ #expect(diagnostic.contains("1 image(s) in this turn have no stored copy"),+ Comment(rawValue: diagnostic))+ #expect(!diagnostic.contains("roof.png"),+ "the diagnostic named the user's file")+ let meta = try #require(model.history.entries.first)+ #expect(meta.imageWriteFailed == true)+ #expect(meta.kvTokens == nil)+ #expect(model.continuability(of: meta)+ == .cannotReplay(reason: .imageRecordMissing))+ }++ // MARK: - Row 5: a size that cannot be read is drawn as zero, on purpose++ /// The one discarded failure the table keeps.+ ///+ /// `encodedBytes` is display only: the capacity arithmetic it feeds is+ /// about pictures being attached, and a stored one is already in the+ /// conversation. So a file whose size cannot be read is drawn as zero bytes+ /// rather than costing the reader the turn it belongs to. Written down here+ /// so it is a decision rather than an oversight.+ @Test func astoredPictureWhoseSizeCannotBeReadIsDrawnAsZeroBytes() throws {+ let id = UUID()+ let image = ConversationImageRecord(+ id: UUID(), displayName: "roof.heic",+ pixelsFile: "images/1a2b.png",+ thumbnailFile: "images/1a2b.thumb.jpg",+ sourceDigest: "source", modelInputDigest: "input",+ width: 768, height: 768, softTokens: 256)+ let records: [TranscriptRecord] = [+ Self.header(id),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "what is this?",+ images: [image], tokens: [1])),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)++ // A directory that does not exist, so neither copy can be sized.+ let document = ConversationDocument.load(+ ConversationOpenResult(meta: meta, records: records, isReadOnly: false,+ droppedTornFinalLine: false),+ directory: URL(fileURLWithPath: "/tmp/no-such-conversation-\(id.uuidString)",+ isDirectory: true))++ let attached = try #require(document.turns.first?.images.first)+ #expect(attached.encodedBytes == 0)+ #expect(attached.displayName == "roof.heic",+ "the turn lost its picture over a size nobody reads")+ }++ // MARK: - Row 3: a skipped row says why it was skipped++ @Test func alistNamesTheReasonItSkippedADirectory() async throws {+ let root = try Self.makeRoot("skip")+ defer { try? FileManager.default.removeItem(at: root) }+ let store = ConversationStore(rootURL: root)+ try await store.activate()+ let meta = try await store.create(+ title: "readable", identity: Self.identity, session: Self.session,+ sampling: Self.sampling)+ let broken = try await store.create(+ title: "damaged", identity: Self.identity, session: Self.session,+ sampling: Self.sampling)++ // Damage in the middle of the transcript, which no rebuild can recover:+ // the meta goes too, so the directory has to be read from its records.+ let directory = await store.directoryURL(for: broken.id)+ try FileManager.default.removeItem(+ at: directory.appendingPathComponent(ConversationMeta.fileName))+ try Data("{not json}\n".utf8).write(+ to: directory.appendingPathComponent("transcript.jsonl"))++ let listed = try await store.list()++ #expect(listed.map(\.id) == [meta.id])+ #expect(await store.skippedByLastList == [broken.id])+ let reason = try #require(await store.skipReasons[broken.id])+ #expect(!reason.isEmpty)+ #expect(reason.contains("\(broken.id.uuidString)") || reason.contains("record"),+ Comment(rawValue: reason))+ }++ // MARK: - Row 4: a lock that failed for any other reason says so++ @Test func alockThatFailedForAnythingButAnotherWindowIsReported() async throws {+ let root = try Self.makeRoot("lock")+ defer { try? FileManager.default.removeItem(at: root) }+ let storeRoot = root.appendingPathComponent("conversations", isDirectory: true)+ let store = ConversationStore(rootURL: storeRoot)++ // A file where the store's root has to be, so taking the lock fails for+ // a reason that is not "another window holds it".+ try Data("not a directory".utf8).write(to: storeRoot)++ let reason = await store.retryLock()++ #expect(reason != nil, "a lock failure read as another window holding it")+ #expect(await store.isReadOnly)+ }++ /// And the window hears about it. A second instance holding the lock is the+ /// ordinary case and stays quiet; anything else reaches `historyDiagnostic`.+ @MainActor+ @Test func thewindowIsToldWhyItCouldNotTakeTheWriterLock() async throws {+ let root = try Self.makeRoot("lock-app")+ defer { try? FileManager.default.removeItem(at: root) }+ let attachments = AppImageAttachmentStore(+ directoryURL: root.appendingPathComponent("staged", isDirectory: true))+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = try await readyModel(client, root: root, attachments: attachments)+ defer { model.releaseAllAttachments() }+ let storeRoot = await (try #require(model.conversationStore)).rootURL++ // Another instance takes the lock first, which is the case that stays+ // quiet — and then the root becomes a file, which is the case that does+ // not.+ let peer = ConversationStore(rootURL: storeRoot)+ try FileManager.default.removeItem(at: storeRoot)+ try Data("not a directory".utf8).write(to: storeRoot)+ _ = peer+ model.history.setReadOnlyStore(true)+ model.historyDiagnostic = nil++ model.reacquireStoreIfPossible()+ try await waitUntil { await model.historyDiagnostic != nil }++ let diagnostic = try #require(model.historyDiagnostic)+ #expect(diagnostic.contains("could not be locked for writing")+ || diagnostic.contains("could not be read"),+ Comment(rawValue: diagnostic))+ }+}diff --git a/Tests/TurboFieldfareApp/Core/History/ConversationImageWriterTests.swift b/Tests/TurboFieldfareApp/Core/History/ConversationImageWriterTests.swiftnew file mode 100644index 00000000..602a5b52--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/History/ConversationImageWriterTests.swift@@ -0,0 +1,77 @@+import Foundation+import Testing+import TurboFieldfareRepackCore+@testable import TurboFieldfareAppCore++@Suite struct ConversationImageWriterTests {+ private enum EncodingFailure: Error { case interrupted }++ /// A failed later turn must not damage a file already referenced by an+ /// earlier turn, or publish a partial file for a new image.+ @Test(arguments: [false, true])+ func failedEncodingDoesNotPublishPartialBytes(existing: Bool) throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("image-atomic-\(UUID())")+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let destination = root.appendingPathComponent("image.png")+ let original = Data("previous complete image".utf8)+ if existing { try original.write(to: destination) }++ #expect(throws: EncodingFailure.self) {+ try ConversationImageWriter.writeAtomically(to: destination) { temporary in+ try Data("interrupted image".utf8).write(to: temporary)+ throw EncodingFailure.interrupted+ }+ }+ if existing {+ #expect(try Data(contentsOf: destination) == original)+ } else {+ #expect(!FileManager.default.fileExists(atPath: destination.path))+ }+ #expect(try FileManager.default.contentsOfDirectory(atPath: root.path)+ == (existing ? ["image.png"] : []))+ }++ @Test(arguments: [false, true])+ func successfulEncodingPublishesOnlyTheCompletedFile(existing: Bool) throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("image-atomic-\(UUID())")+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let destination = root.appendingPathComponent("image.thumb.jpg")+ let original = Data("previous thumbnail".utf8)+ let completed = Data("completed thumbnail".utf8)+ if existing { try original.write(to: destination) }++ try ConversationImageWriter.writeAtomically(to: destination) { temporary in+ try Data("partial thumbnail".utf8).write(to: temporary)+ if existing {+ #expect(try Data(contentsOf: destination) == original)+ } else {+ #expect(!FileManager.default.fileExists(atPath: destination.path))+ }+ try completed.write(to: temporary)+ }+ #expect(try Data(contentsOf: destination) == completed)+ #expect(try FileManager.default.contentsOfDirectory(atPath: root.path)+ == ["image.thumb.jpg"])+ }++ @Test func failedPromotionPreservesTheDestinationAndRemovesTheTemporary() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("image-promotion-\(UUID())")+ let destination = root.appendingPathComponent("image.png")+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let sentinel = destination.appendingPathComponent("keep")+ try Data("untouched".utf8).write(to: sentinel)+ #expect(throws: RepackError.self) {+ try ConversationImageWriter.writeAtomically(to: destination) {+ try Data("complete image".utf8).write(to: $0)+ }+ }+ #expect(try Data(contentsOf: sentinel) == Data("untouched".utf8))+ #expect(try FileManager.default.contentsOfDirectory(atPath: root.path) == ["image.png"])+ }+}diff --git a/Tests/TurboFieldfareApp/Core/History/ConversationMetaProjectionTests.swift b/Tests/TurboFieldfareApp/Core/History/ConversationMetaProjectionTests.swiftnew file mode 100644index 00000000..54255837--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/History/ConversationMetaProjectionTests.swift@@ -0,0 +1,483 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// `conversation.json` is a cache of this function, so every field it carries+/// has to have exactly one answer here. The cases are the field table of+/// `2026-09-02-conversation-meta-projection.md`, one per row, plus the two+/// refusals: a transcript in the wrong directory, and one with no identity to+/// check a replay against.+@Suite struct ConversationMetaProjectionTests {+ private static let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private static let otherIdentity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "deadbeef",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private static let session = ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand")++ private static let otherSession = ConversationSessionSettings(+ contextTokens: 16_384, expertCacheSlots: 24,+ visionResidencyPolicy: "keepReady")++ private static func sampling(_ temperature: Double) -> ConversationSampling {+ ConversationSampling(temperature: temperature, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 4_096)+ }++ private static let created = Date(timeIntervalSince1970: 1_756_000_000)++ private static func at(_ offset: TimeInterval) -> Date {+ created.addingTimeInterval(offset)+ }++ private static func header(+ id: UUID,+ identity: ConversationIdentity? = ConversationMetaProjectionTests.identity,+ session: ConversationSessionSettings? = ConversationMetaProjectionTests.session,+ sampling: ConversationSampling? = nil+ ) -> TranscriptRecord {+ .header(ConversationHeaderRecord(+ id: id, createdAt: created, identity: identity, session: session,+ sampling: sampling))+ }++ private static func image(_ name: String) -> ConversationImageRecord {+ ConversationImageRecord(+ id: UUID(), displayName: name,+ pixelsFile: "images/\(name).png",+ thumbnailFile: "images/\(name).thumb.jpg",+ sourceDigest: name, modelInputDigest: name,+ width: 768, height: 768, softTokens: 4)+ }++ private static func legacyMeta(id: UUID) -> ConversationMeta {+ ConversationMeta(+ id: id, title: "typed into the file", titleSource: .user,+ createdAt: at(-9_000), updatedAt: at(-9_000),+ turnCount: 99, kvTokens: 12_345, imageCount: 7,+ identity: otherIdentity, session: otherSession,+ sampling: sampling(0.9),+ boundary: ConversationBoundary(tokens: [42], needsReplay: true),+ pinned: true)+ }++ // MARK: - The shape of an empty conversation++ /// A conversation with nothing in it yet: everything comes from the header.+ @Test func aHeaderOnItsOwnProjectsAnEmptyConversation() throws {+ let id = UUID()+ let meta = try ConversationMetaProjection.project(+ directoryID: id,+ records: [Self.header(id: id, sampling: Self.sampling(0.4))],+ legacy: nil)++ #expect(meta.version == ConversationMeta.currentVersion)+ #expect(meta.id == id)+ #expect(meta.createdAt == Self.created)+ #expect(meta.updatedAt == Self.created, "an unused chat was last used at nothing")+ #expect(meta.turnCount == 0)+ #expect(meta.imageCount == 0)+ #expect(meta.kvTokens == nil, "an empty conversation cannot be replayed")+ #expect(meta.title == ConversationTitle.untitled)+ #expect(meta.titleSource == .firstMessage)+ #expect(meta.identity == Self.identity)+ #expect(meta.session == Self.session)+ #expect(meta.sampling == Self.sampling(0.4))+ #expect(meta.boundary == ConversationBoundary())+ #expect(!meta.pinned)+ }++ // MARK: - Counts++ @Test func turnsImagesAndTokensAreCountedFromTheRecords() throws {+ let id = UUID()+ let records: [TranscriptRecord] = [+ Self.header(id: id),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "what is this?",+ images: [Self.image("a"), Self.image("b")], tokens: [1, 2, 3])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(11), text: "a roof", tokens: [4])),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(20), text: "and this?",+ images: [Self.image("c")], tokens: [5, 6])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(21), text: "a wall", tokens: [7])),+ ]++ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ #expect(meta.turnCount == 4)+ #expect(meta.imageCount == 3)+ #expect(meta.kvTokens == 7)+ #expect(meta.updatedAt == Self.at(21), "the last turn is when it was last used")+ #expect(meta.title == "what is this?")+ #expect(meta.titleSource == .firstMessage)+ }++ /// A turn with no recorded IDs cannot be replayed, and neither can the+ /// conversation around it. The same refusal `lineage` makes, so a row can+ /// never claim a count the replay would then reject.+ @Test func aTurnWithoutTokensLeavesTheCountUnknown() throws {+ let id = UUID()+ let records: [TranscriptRecord] = [+ Self.header(id: id),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "hello", tokens: [1, 2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(11), text: "hi", tokens: nil)),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ #expect(meta.kvTokens == nil)+ #expect(meta.turnCount == 2, "the turns are still there to read")+ }++ // MARK: - Title++ @Test func aTitleRecordBeatsTheFirstMessageAndTheLastOneWins() throws {+ let id = UUID()+ let records: [TranscriptRecord] = [+ Self.header(id: id),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "the first message",+ tokens: [1])),+ .title(ConversationTitleRecord(+ title: "renamed once", source: .user, at: Self.at(30))),+ .title(ConversationTitleRecord(+ title: "renamed again", source: .user, at: Self.at(40))),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ #expect(meta.title == "renamed again")+ #expect(meta.titleSource == .user)+ // Renaming is not using: the row keeps its place in the list.+ #expect(meta.updatedAt == Self.at(10), "a rename reordered the list")+ }++ @Test func aLongFirstMessageIsClippedTheWayTheTitleRuleClipsIt() throws {+ let id = UUID()+ let long = String(repeating: "word ", count: 60)+ let records: [TranscriptRecord] = [+ Self.header(id: id),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: long, tokens: [1])),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ #expect(meta.title == ConversationTitle.fromFirstMessage(long))+ #expect(meta.title.count <= ConversationTitle.maximumCharacters + 1)+ }++ // MARK: - Records that say nothing++ /// A checkpoint of a reply still being generated is superseded by the turn+ /// that follows it, and a record from a later build is not this build's+ /// business. Counting either would put the sidebar ahead of the transcript.+ @Test func partialAndUnknownRecordsContributeNothing() throws {+ let id = UUID()+ let counted: [TranscriptRecord] = [+ Self.header(id: id),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "hello", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(11), text: "hi", tokens: [2])),+ ]+ let withNoise: [TranscriptRecord] = [+ counted[0],+ .partial(ConversationTurnRecord(+ role: .assistant, at: Self.at(5), text: "half a rep",+ images: [Self.image("d")], tokens: [9, 9, 9])),+ counted[1],+ .unknown(type: "summary"),+ counted[2],+ .unknown(type: "reaction"),+ ]++ #expect(try ConversationMetaProjection.project(+ directoryID: id, records: withNoise, legacy: nil)+ == ConversationMetaProjection.project(+ directoryID: id, records: counted, legacy: nil))+ }++ // MARK: - Sampling and boundary++ @Test func samplingComesFromTheLastUserTurnThatRecordedIt() throws {+ let id = UUID()+ let records: [TranscriptRecord] = [+ Self.header(id: id, sampling: Self.sampling(0.1)),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "one", tokens: [1],+ sampling: Self.sampling(0.5))),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(11), text: "a", tokens: [2])),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(20), text: "two", tokens: [3],+ sampling: Self.sampling(0.7))),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(21), text: "b", tokens: [4])),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ #expect(meta.sampling == Self.sampling(0.7))+ }++ @Test func theBoundaryComesFromTheLastAssistantTurn() throws {+ let id = UUID()+ let records: [TranscriptRecord] = [+ Self.header(id: id),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "one", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(11), text: "a", tokens: [2],+ boundary: ConversationBoundary(tokens: [77], needsReplay: true))),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(20), text: "two", tokens: [3])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(21), text: "b", tokens: [4],+ boundary: ConversationBoundary())),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ // The newest turn's answer, not the newest turn that had something to+ // say: the conversation has already moved past the earlier boundary.+ #expect(meta.boundary == ConversationBoundary())+ }++ // MARK: - Legacy stores++ /// The cache is consulted only for facts no record carries, and only when+ /// there is no `origin` record either.+ @Test func theCachedMetaIsReadOnlyForWhatTheRecordsCannotAnswer() throws {+ let id = UUID()+ let legacy = Self.legacyMeta(id: id)+ let records: [TranscriptRecord] = [+ .header(ConversationHeaderRecord(id: id, createdAt: Self.created)),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "hello", tokens: [1, 2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(11), text: "hi", tokens: [3])),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: legacy)++ // Taken from the cache, because nothing else records them.+ #expect(meta.identity == Self.otherIdentity)+ #expect(meta.session == Self.otherSession)+ #expect(meta.sampling == Self.sampling(0.9))+ #expect(meta.boundary == ConversationBoundary(tokens: [42], needsReplay: true))+ // Every one of these the cache also claimed, and every one is wrong.+ #expect(meta.title == "hello")+ #expect(meta.titleSource == .firstMessage)+ #expect(meta.turnCount == 2)+ #expect(meta.kvTokens == 3)+ #expect(meta.imageCount == 0)+ #expect(meta.createdAt == Self.created)+ #expect(meta.updatedAt == Self.at(11))+ #expect(!meta.pinned)+ }++ /// An `origin` record is the hoisted cache, and it wins over the cache+ /// itself: after the hoist the conversation projects from its own records+ /// and the file it came from can be deleted.+ @Test func anOriginRecordSuppliesWhatALegacyHeaderDoesNot() throws {+ let id = UUID()+ let origin = ConversationOriginRecord(+ identity: Self.identity, session: Self.session,+ sampling: Self.sampling(0.3),+ boundary: ConversationBoundary(tokens: [5], needsReplay: false),+ at: Self.at(1))+ let records: [TranscriptRecord] = [+ .header(ConversationHeaderRecord(id: id, createdAt: Self.created)),+ .origin(origin),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "hello", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(11), text: "hi", tokens: [2])),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: Self.legacyMeta(id: id))+ #expect(meta.identity == Self.identity)+ #expect(meta.session == Self.session)+ #expect(meta.sampling == Self.sampling(0.3))+ #expect(meta.boundary == ConversationBoundary(tokens: [5], needsReplay: false))+ }++ @Test func theHeaderBeatsAnOriginRecordAndBoth() throws {+ let id = UUID()+ let origin = ConversationOriginRecord(+ identity: Self.otherIdentity, session: Self.otherSession,+ sampling: Self.sampling(0.3), boundary: ConversationBoundary(),+ at: Self.at(1))+ let records: [TranscriptRecord] = [+ Self.header(id: id),+ .origin(origin),+ ]+ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: Self.legacyMeta(id: id))+ #expect(meta.identity == Self.identity)+ #expect(meta.session == Self.session)+ }++ // MARK: - Refusals++ @Test func aTranscriptInTheWrongDirectoryIsRefused() {+ let directory = UUID()+ let records = [Self.header(id: UUID())]+ #expect(throws: ConversationStoreError.self) {+ try ConversationMetaProjection.project(+ directoryID: directory, records: records, legacy: nil)+ }+ }++ @Test func aTranscriptWithNoHeaderIsRefused() {+ let id = UUID()+ #expect(throws: ConversationStoreError.missingHeader(id: id)) {+ try ConversationMetaProjection.project(+ directoryID: id,+ records: [.turn(ConversationTurnRecord(+ role: .user, at: Self.at(1), text: "orphan", tokens: [1]))],+ legacy: nil)+ }+ }++ /// Fail closed. Without an identity there is no continuability rule to+ /// apply, and guessing one hands the user a chat that fails on its first+ /// turn instead of a row that says it cannot be read.+ @Test func aTranscriptWithNoCreationFactsAnywhereIsRefused() {+ let id = UUID()+ #expect(throws: ConversationStoreError.missingOrigin(id: id)) {+ try ConversationMetaProjection.project(+ directoryID: id,+ records: [.header(ConversationHeaderRecord(+ id: id, createdAt: Self.created))],+ legacy: nil)+ }+ }++ // MARK: - The property that makes it a cache++ @Test func projectingTwiceGivesTheSameAnswer() throws {+ let id = UUID()+ let records: [TranscriptRecord] = [+ Self.header(id: id),+ .turn(ConversationTurnRecord(+ role: .user, at: Self.at(10), text: "hello",+ images: [Self.image("a")], tokens: [1, 2],+ sampling: Self.sampling(0.6))),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Self.at(11), text: "hi", tokens: [3],+ boundary: ConversationBoundary(tokens: [9], needsReplay: true))),+ .title(ConversationTitleRecord(+ title: "named", source: .user, at: Self.at(12))),+ ]+ let once = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ let twice = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: once)+ #expect(once == twice, "the projection is not a function of the records")+ }++ // MARK: - Cost++ /// What the projection costs at the sizes a real conversation reaches.+ ///+ /// It runs on every append and on every open, so the shape of the curve+ /// matters more than any single number — it is one pass over the records+ /// with no per-token work beyond counting. Reported rather than asserted:+ /// a wall-clock threshold in a test suite is a flake, and the number that+ /// decides anything belongs in a benchmark note.+ @Test func theProjectionCostAtRealTranscriptSizesIsReported() throws {+ for (tokens, turns) in [(600, 8), (6_060, 40), (8_192, 16), (8_192, 60)] {+ let id = UUID()+ let records = Self.synthesized(id: id, tokens: tokens, turns: turns)+ let bytes = try Self.encodedBytes(records)++ // Warm the decoder-free path once; the measurement is the projection.+ _ = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ let iterations = 20+ let start = ContinuousClock.now+ for _ in 0..<iterations {+ _ = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ }+ let each = (ContinuousClock.now - start) / iterations++ let meta = try ConversationMetaProjection.project(+ directoryID: id, records: records, legacy: nil)+ #expect(meta.kvTokens == tokens)+ #expect(meta.turnCount == turns)+ print("projection: \(tokens) tokens in \(turns) records "+ + "(\(bytes) bytes) took \(each)")+ }+ }++ /// A transcript of `turns` records holding `tokens` token IDs between them.+ private static func synthesized(id: UUID, tokens: Int,+ turns: Int) -> [TranscriptRecord] {+ var records: [TranscriptRecord] = [header(id: id)]+ let each = tokens / turns+ var remaining = tokens+ for index in 0..<turns {+ let count = index == turns - 1 ? remaining : each+ remaining -= count+ let isUser = index.isMultiple(of: 2)+ records.append(.turn(ConversationTurnRecord(+ role: isUser ? .user : .assistant,+ at: at(TimeInterval(index)),+ text: String(repeating: "word ", count: count),+ tokens: (0..<count).map { Int32(1_000 + $0) },+ sampling: isUser ? sampling(0.2) : nil,+ boundary: isUser ? nil : ConversationBoundary())))+ }+ return records+ }++ private static func encodedBytes(_ records: [TranscriptRecord]) throws -> Int {+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ return try records.reduce(0) { $0 + (try encoder.encode($1).count) + 1 }+ }++ // MARK: - The hoist++ @Test func theHoistFiresOnceAndOnlyForALegacyTranscript() {+ let id = UUID()+ let legacy = Self.legacyMeta(id: id)+ let legacyRecords: [TranscriptRecord] = [+ .header(ConversationHeaderRecord(id: id, createdAt: Self.created)),+ ]+ let hoisted = ConversationMetaProjection.hoist(+ records: legacyRecords, legacy: legacy)+ #expect(hoisted?.identity == Self.otherIdentity)+ #expect(hoisted?.session == Self.otherSession)+ #expect(hoisted?.sampling == Self.sampling(0.9))+ #expect(hoisted?.boundary+ == ConversationBoundary(tokens: [42], needsReplay: true))++ // Already hoisted: nothing to do.+ guard let hoisted else {+ Issue.record("a legacy transcript produced no origin record")+ return+ }+ #expect(ConversationMetaProjection.hoist(+ records: legacyRecords + [.origin(hoisted)], legacy: legacy) == nil)+ // Written by this build: the header already carries the facts.+ #expect(ConversationMetaProjection.hoist(+ records: [Self.header(id: id)], legacy: legacy) == nil)+ // Nothing to hoist from.+ #expect(ConversationMetaProjection.hoist(+ records: legacyRecords, legacy: nil) == nil)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/History/ConversationRecordCompatibilityTests.swift b/Tests/TurboFieldfareApp/Core/History/ConversationRecordCompatibilityTests.swiftnew file mode 100644index 00000000..0e3b670e--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/History/ConversationRecordCompatibilityTests.swift@@ -0,0 +1,152 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// The transcript has to stay readable in both directions across a build that+/// adds a field or a record kind, because both worktrees on this machine share+/// one store through the `scratch` symlink and either can be running.+///+/// Every case here is a way that could stop being true: a key a reader does not+/// know, a key a writer did not write, or a whole record type from a later+/// build. The first two passed before the projection landed and are pinned so+/// they keep passing; the third pins the downgrade direction against a copy of+/// the decoder as it was.+@Suite struct ConversationRecordCompatibilityTests {+ private static func decoder() -> JSONDecoder {+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601+ return decoder+ }++ private static func encoder() -> JSONEncoder {+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ return encoder+ }++ /// A later build adding a field to a turn must not make the line+ /// unreadable: `open` treats a line it cannot parse anywhere but the end as+ /// two writers or in-place damage, and refuses the whole conversation.+ @Test func aTurnLineWithAKeyThisBuildDoesNotKnowStillDecodes() throws {+ let line = """+ {"type":"turn","turn":{"id":"E621E1F8-C36C-495A-93FC-0C247A3E6E5F",\+ "role":"user","at":"2026-09-02T10:00:00Z","text":"hello","images":[],\+ "tokens":[1,2,3],"summary":"written by a later build",\+ "moodRing":{"colour":"amber"}}}+ """+ let record = try Self.decoder().decode(+ TranscriptRecord.self, from: Data(line.utf8))+ guard case .turn(let turn) = record else {+ Issue.record("the line decoded as something other than a turn")+ return+ }+ #expect(turn.text == "hello")+ #expect(turn.tokens == [1, 2, 3])+ #expect(turn.sampling == nil)+ #expect(turn.boundary == nil)+ }++ /// A header written before the creation facts moved into it.+ ///+ /// Every transcript in the developer store has one, and refusing them would+ /// hide every conversation written before this build.+ @Test func aHeaderWithoutTheCreationFactsStillDecodes() throws {+ let line = """+ {"type":"header","header":{"version":1,\+ "id":"E621E1F8-C36C-495A-93FC-0C247A3E6E5F",\+ "createdAt":"2026-09-01T09:00:00Z"}}+ """+ let record = try Self.decoder().decode(+ TranscriptRecord.self, from: Data(line.utf8))+ guard case .header(let header) = record else {+ Issue.record("the line decoded as something other than a header")+ return+ }+ #expect(header.id == UUID(uuidString: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"))+ #expect(header.identity == nil)+ #expect(header.session == nil)+ #expect(header.sampling == nil)+ }++ /// The extra header fields survive a round trip through this build.+ @Test func aHeaderCarryingTheCreationFactsRoundTrips() throws {+ let header = ConversationHeaderRecord(+ id: UUID(), createdAt: Date(timeIntervalSince1970: 1_756_800_000),+ identity: Self.identity, session: Self.session,+ sampling: Self.sampling)+ let data = try Self.encoder().encode(TranscriptRecord.header(header))+ let decoded = try Self.decoder().decode(TranscriptRecord.self, from: data)+ #expect(decoded == .header(header))+ }++ /// The downgrade direction: a build without the `origin` case reads the+ /// line as an unknown record and carries on.+ ///+ /// Decoded here through a copy of the enum's `CodingKeys` and `init` as+ /// they were before `origin` existed, because the point is what the *older*+ /// build does — asking the current one would prove nothing.+ @Test func anOriginLineReadsAsUnknownToABuildWithoutIt() throws {+ let origin = ConversationOriginRecord(+ identity: Self.identity, session: Self.session,+ sampling: Self.sampling, boundary: ConversationBoundary(),+ at: Date(timeIntervalSince1970: 1_756_800_000))+ let data = try Self.encoder().encode(TranscriptRecord.origin(origin))++ let asOlderBuildReadsIt = try Self.decoder().decode(+ PreOriginTranscriptRecord.self, from: data)+ #expect(asOlderBuildReadsIt == .unknown(type: "origin"))++ // And this build still reads it as itself.+ #expect(try Self.decoder().decode(TranscriptRecord.self, from: data)+ == .origin(origin))+ }++ /// `TranscriptRecord` as it decoded before the `origin` case existed.+ private enum PreOriginTranscriptRecord: Equatable, Decodable {+ case header(ConversationHeaderRecord)+ case turn(ConversationTurnRecord)+ case partial(ConversationTurnRecord)+ case title(ConversationTitleRecord)+ case unknown(type: String)++ private enum CodingKeys: String, CodingKey {+ case type, header, turn, partial, title+ }++ init(from decoder: any Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ let type = try container.decode(String.self, forKey: .type)+ switch type {+ case "header":+ self = .header(try container.decode(+ ConversationHeaderRecord.self, forKey: .header))+ case "turn":+ self = .turn(try container.decode(+ ConversationTurnRecord.self, forKey: .turn))+ case "partial":+ self = .partial(try container.decode(+ ConversationTurnRecord.self, forKey: .partial))+ case "title":+ self = .title(try container.decode(+ ConversationTitleRecord.self, forKey: .title))+ default:+ self = .unknown(type: type)+ }+ }+ }++ private static let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private static let session = ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand")++ private static let sampling = ConversationSampling(+ temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 4_096)+}diff --git a/Tests/TurboFieldfareApp/Core/History/ConversationStoreTests.swift b/Tests/TurboFieldfareApp/Core/History/ConversationStoreTests.swiftnew file mode 100644index 00000000..c30352af--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/History/ConversationStoreTests.swift@@ -0,0 +1,1078 @@+import CoreGraphics+import Foundation+import ImageIO+import Metal+import Testing+import TurboFieldfare+import UniformTypeIdentifiers+@testable import TurboFieldfareAppCore++/// The store is where a conversation survives a quit, so every case here is a+/// way it could survive as something other than what was written: a torn line+/// buried in the middle, an older build stamping its schema over a newer one's+/// file, two instances appending at once, a transcript that migrated into the+/// wrong directory.+@Suite struct ConversationStoreTests {+ @Test(arguments: 0...4)+ func adversarialSaveCutPointsRecoverIdempotently(cut: Int) async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "cut point", identity: identity, session: session, sampling: sampling)+ try await store.append([+ .turn(ConversationTurnRecord(role: .user, at: Date(), text: "kept", tokens: [1])),+ .turn(ConversationTurnRecord(role: .assistant, at: Date(), text: "kept answer", tokens: [2]))+ ], to: meta.id)+ let transcript = await store.transcriptURL(for: meta.id)+ let imageDir = await store.imagesURL(for: meta.id)+ try FileManager.default.createDirectory(at: imageDir, withIntermediateDirectories: true)+ let image = imageDir.appendingPathComponent("published.png")+ // Bounded sidecar bytes: this checks transaction recovery, not decoding.+ let pixels = Data("published sidecar".utf8)+ try pixels.write(to: image)+ let user = TranscriptRecord.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "new question",+ images: [ConversationImageRecord(+ id: UUID(), displayName: "fixture", pixelsFile: "images/published.png",+ thumbnailFile: "images/published.png", sourceDigest: "source",+ modelInputDigest: "pixels", width: 48, height: 48, softTokens: 1)],+ tokens: [MultimodalPromptRenderer.imageTokenID]))+ let assistant = TranscriptRecord.turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "new answer", tokens: [4]))+ if cut == 4 {+ try await store.append([user, assistant], to: meta.id)+ } else {+ if cut >= 1 { try appendRaw(user, to: transcript) }+ if cut == 2 {+ let handle = try FileHandle(forWritingTo: transcript)+ try handle.seekToEnd()+ try handle.write(contentsOf: Data(#"{"type":"turn","turn":{"id"#.utf8))+ try handle.close()+ }+ if cut == 3 { try appendRaw(assistant, to: transcript) }+ }+ let first = try await store.open(id: meta.id)+ let recoveredBytes = try Data(contentsOf: transcript)+ let second = try await store.open(id: meta.id)+ #expect(try Data(contentsOf: transcript) == recoveredBytes)+ #expect(first.meta.turnCount == (cut >= 3 ? 4 : 2))+ #expect(second.records == first.records)+ #expect(second.meta.kvTokens == (cut >= 3 ? 4 : 2))+ _ = try await store.sweepOrphanImages(in: meta.id)+ #expect(FileManager.default.fileExists(atPath: image.path) == (cut >= 3))+ if cut >= 3 { #expect(try Data(contentsOf: image) == pixels) }+ try await store.append([+ .turn(ConversationTurnRecord(role: .user, at: Date(), text: "retry", tokens: [5])),+ .turn(ConversationTurnRecord(role: .assistant, at: Date(), text: "retry answer", tokens: [6]))+ ], to: meta.id)+ let continued = try await store.open(id: meta.id)+ #expect(continued.meta.turnCount == (cut >= 3 ? 6 : 4))+ #expect(continued.meta.kvTokens == (cut >= 3 ? 6 : 4))+ #expect(Array(continued.records.prefix(first.records.count)) == first.records)+ }++ private enum TrashFailure: Error, CustomStringConvertible {+ case list+ case remove++ var description: String {+ switch self {+ case .list: "injected trash listing failure"+ case .remove: "injected trash removal failure"+ }+ }+ }++ private func makeRoot() -> URL {+ FileManager.default.temporaryDirectory+ .appendingPathComponent("conversations-\(UUID().uuidString)",+ isDirectory: true)+ }++ private var identity: ConversationIdentity {+ ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)+ }++ private var session: ConversationSessionSettings {+ ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand")+ }++ private var sampling: ConversationSampling {+ ConversationSampling(temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 4_096)+ }++ private func makeStore(_ root: URL) async throws -> ConversationStore {+ let store = ConversationStore(rootURL: root)+ try await store.activate()+ return store+ }++ private func appendRaw(_ record: TranscriptRecord, to url: URL) throws {+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ var data = try encoder.encode(record)+ data.append(0x0A)+ let handle = try FileHandle(forWritingTo: url)+ try handle.seekToEnd()+ try handle.write(contentsOf: data)+ try handle.close()+ }++ @Test func aThreeTurnConversationRoundTripsWithItsTokenIDs() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)++ let meta = try await store.create(+ title: "Hello there", identity: identity, session: session,+ sampling: sampling)+ var lineage: [Int32] = []+ for turn in 0..<3 {+ let prompt: [Int32] = [Int32(turn * 10), Int32(turn * 10 + 1)]+ let reply: [Int32] = [Int32(turn * 10 + 2)]+ try await store.append([.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "question \(turn)",+ tokens: prompt))], to: meta.id)+ try await store.append([.turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer \(turn)", tokens: reply,+ stopReason: "endOfTurn"))], to: meta.id)+ lineage += prompt + reply+ }++ let opened = try await store.open(id: meta.id)+ #expect(!opened.droppedTornFinalLine)+ // Nothing assigned these: the meta is the projection of the records+ // that were just appended.+ #expect(opened.meta.turnCount == 6)+ #expect(opened.meta.kvTokens == lineage.count)+ #expect(opened.meta.identity == identity)+ #expect(opened.meta.sampling == sampling)+ let tokens = opened.records.compactMap { record -> [Int32]? in+ guard case .turn(let turn) = record else { return nil }+ return turn.tokens+ }.flatMap { $0 }+ #expect(tokens == lineage, "the record no longer reproduces the KV")++ let listed = try await store.list()+ #expect(listed.count == 1)+ #expect(listed[0].id == meta.id)+ }++ /// A crash mid-append can only ever cut the last line. Dropping it costs one+ /// turn; refusing the file would cost the conversation.+ @Test func aTornFinalLineIsDroppedAndTruncatedAway() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "kept", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer", tokens: [2])),+ ], to: meta.id)++ let transcript = await store.transcriptURL(for: meta.id)+ let handle = try FileHandle(forWritingTo: transcript)+ try handle.seekToEnd()+ try handle.write(contentsOf: Data(#"{"type":"turn","turn":{"id"#.utf8))+ try handle.close()++ let opened = try await store.open(id: meta.id)+ #expect(opened.droppedTornFinalLine)+ // Header, the title, and the complete exchange survive.+ #expect(opened.records.count == 4)++ // Truncated before the next append, so the following record does not+ // land glued to the fragment and become unreadable in the middle.+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "after", tokens: [3])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "after answer", tokens: [4])),+ ], to: meta.id)+ let reopened = try await store.open(id: meta.id)+ #expect(!reopened.droppedTornFinalLine)+ #expect(reopened.records.count == 6)+ }++ /// An append heals the torn tail itself; it cannot rely on an open having+ /// done so.+ ///+ /// The sidebar lists a conversation from its cache without opening the+ /// transcript, so a rename after a crash reached `append` with the torn+ /// line still there and glued the title record onto it. That is a torn+ /// line in the middle, which nothing recovers: the chat could be listed+ /// and never opened again.+ @Test func anAppendAfterACrashDropsTheTornTailWithoutAnOpen() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "before", identity: identity, session: session,+ sampling: sampling)+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "kept", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer", tokens: [2])),+ ], to: meta.id)++ let transcript = await store.transcriptURL(for: meta.id)+ let handle = try FileHandle(forWritingTo: transcript)+ try handle.seekToEnd()+ try handle.write(contentsOf: Data(#"{"type":"turn","turn":{"id"#.utf8))+ try handle.close()++ // No open in between: this is the rename-from-the-sidebar path.+ try await store.rename(id: meta.id, to: "after")++ let opened = try await store.open(id: meta.id)+ #expect(opened.meta.title == "after")+ #expect(!opened.droppedTornFinalLine, "the fragment survived the append")+ // Header, the first title, the exchange, and the rename.+ #expect(opened.records.count == 5)+ }++ /// A rename lands after the repair, not after the damage.+ ///+ /// A crash between a turn's two records leaves a question with no answer.+ /// Only a recovering open used to drop it, so a rename first appended its+ /// title behind the orphan, and the next open truncated the orphan and the+ /// title together: the rename silently reverted. The repair belongs to the+ /// rename, not to every append: a caller appending the answer itself must+ /// not have its question truncated first.+ @Test func aRenameAfterAnUnansweredQuestionKeepsItsTitle() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "before", identity: identity, session: session,+ sampling: sampling)+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "kept", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer", tokens: [2])),+ ], to: meta.id)+ try appendRaw(.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "orphan", tokens: [3])),+ to: await store.transcriptURL(for: meta.id))++ try await store.rename(id: meta.id, to: "after")++ let opened = try await store.open(id: meta.id)+ #expect(opened.meta.title == "after", "the rename was truncated away")+ #expect(opened.meta.turnCount == 2, "the orphan survived the rename")+ #expect(opened.meta.kvTokens == 2)+ // Header, the first title, the exchange, the rename: no orphan.+ #expect(opened.records.count == 5)+ }++ /// A long fragment is still found and cut before the append.+ @Test func aTornTailLongerThanOneScanWindowIsStillDropped() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)++ let transcript = await store.transcriptURL(for: meta.id)+ let handle = try FileHandle(forWritingTo: transcript)+ try handle.seekToEnd()+ try handle.write(contentsOf: Data(+ (#"{"type":"turn","turn":{"text":""# + String(repeating: "x", count: 40_000)).utf8))+ try handle.close()++ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "after", tokens: [3])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "after answer", tokens: [4])),+ ], to: meta.id)++ let opened = try await store.open(id: meta.id)+ #expect(!opened.droppedTornFinalLine)+ #expect(opened.records.count == 4)+ #expect(opened.meta.turnCount == 2)+ }++ @Test func aCompleteUserWithoutAnAssistantIsRecoveredAsNoExchange() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ let transcript = await store.transcriptURL(for: meta.id)+ let recoveredBoundary = try Data(contentsOf: transcript).count+ try appendRaw(.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "never committed", tokens: [1])),+ to: transcript)++ let opened = try await store.open(id: meta.id)++ #expect(opened.records.compactMap { record -> ConversationTurnRecord? in+ guard case .turn(let turn) = record else { return nil }+ return turn+ }.isEmpty)+ #expect(opened.meta.turnCount == 0)+ #expect(try Data(contentsOf: transcript).count == recoveredBoundary)+ }++ @Test func aCompleteUserAndTornAssistantRecoverAtTheUsersBoundary() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ let transcript = await store.transcriptURL(for: meta.id)+ let recoveredBoundary = try Data(contentsOf: transcript).count+ try appendRaw(.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "never committed", tokens: [1])),+ to: transcript)+ let handle = try FileHandle(forWritingTo: transcript)+ try handle.seekToEnd()+ try handle.write(contentsOf: Data(#"{"type":"turn","turn":{"role":"assistant""#.utf8))+ try handle.close()++ let opened = try await store.open(id: meta.id)++ #expect(opened.droppedTornFinalLine)+ #expect(opened.meta.turnCount == 0)+ #expect(try Data(contentsOf: transcript).count == recoveredBoundary)+ }++ @Test func aReadOnlyOpenOmitsAnIncompleteExchangeWithoutChangingBytes() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let writer = try await makeStore(root)+ let meta = try await writer.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ let transcript = await writer.transcriptURL(for: meta.id)+ try appendRaw(.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "never committed", tokens: [1])),+ to: transcript)+ let before = try Data(contentsOf: transcript)+ let reader = ConversationStore(rootURL: root)+ try await reader.activate()+ #expect(await reader.isReadOnly)++ let opened = try await reader.open(id: meta.id)++ #expect(opened.meta.turnCount == 0)+ #expect(try Data(contentsOf: transcript) == before)+ }++ @Test func aCompleteExchangeAppendsAtTheRecoveredBoundary() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ let transcript = await store.transcriptURL(for: meta.id)+ try appendRaw(.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "never committed", tokens: [1])),+ to: transcript)+ _ = try await store.open(id: meta.id)++ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "kept", tokens: [2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer", tokens: [3])),+ ], to: meta.id)+ let opened = try await store.open(id: meta.id)+ let turns = opened.records.compactMap { record -> ConversationTurnRecord? in+ guard case .turn(let turn) = record else { return nil }+ return turn+ }+ #expect(turns.map(\.text) == ["kept", "answer"])+ #expect(opened.meta.turnCount == 2)+ }++ /// A damaged line anywhere but the end means two writers or in-place+ /// corruption. Appending to it would bury the evidence under more records.+ @Test func aTornLineInTheMiddleIsAnError() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ try await store.append([.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "one", tokens: [1]))], to: meta.id)++ let transcript = await store.transcriptURL(for: meta.id)+ var text = try String(contentsOf: transcript, encoding: .utf8)+ text = text.replacingOccurrences(of: "\"type\":\"header\"", with: "\"typ")+ try text.write(to: transcript, atomically: true, encoding: .utf8)++ await #expect(throws: ConversationStoreError.self) {+ _ = try await store.open(id: meta.id)+ }+ }++ /// The directory name is the identity; the header is a claim about it. A+ /// transcript that ended up in the wrong directory would otherwise be+ /// replayed as a different conversation.+ @Test func aHeaderNamingAnotherConversationIsRefused() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ let transcript = await store.transcriptURL(for: meta.id)+ let text = try String(contentsOf: transcript, encoding: .utf8)+ .replacingOccurrences(of: meta.id.uuidString,+ with: UUID().uuidString)+ try text.write(to: transcript, atomically: true, encoding: .utf8)++ await #expect(throws: ConversationStoreError.self) {+ _ = try await store.open(id: meta.id)+ }+ }++ /// An unrecognised record type is a later build's, not damage. Failing on it+ /// would make every conversation unreadable the moment one new record kind+ /// ships.+ @Test func anUnknownRecordTypeIsIgnoredRatherThanFatal() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ let transcript = await store.transcriptURL(for: meta.id)+ let handle = try FileHandle(forWritingTo: transcript)+ try handle.seekToEnd()+ try handle.write(contentsOf: Data(+ "{\"type\":\"summary\",\"summary\":{\"text\":\"later build\"}}\n".utf8))+ try handle.close()+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "after", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer", tokens: [2])),+ ], to: meta.id)++ let opened = try await store.open(id: meta.id)+ // Header, the title, the later-build record, and the complete exchange.+ #expect(opened.records.count == 5)+ #expect(opened.records[2] == .unknown(type: "summary"))+ guard case .turn(let turn) = opened.records[3] else {+ Issue.record("the record after an unknown one was lost")+ return+ }+ #expect(turn.text == "after")+ }++ /// An older build stamping its schema over a newer one's file is the+ /// migration loss the field is full of. The file's bytes must not move.+ @Test func aNewerMajorOpensReadOnlyAndItsBytesAreUntouched() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ var meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ meta.version = ConversationMeta.currentVersion + 1+ let metaURL = await store.metaURL(for: meta.id)+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ try encoder.encode(meta).write(to: metaURL)+ let before = try Data(contentsOf: metaURL)++ let opened = try await store.open(id: meta.id)+ #expect(opened.isReadOnly)+ #expect(opened.meta.version == meta.version)+ await #expect(throws: ConversationStoreError.self) {+ try await store.append([.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "no", tokens: [1]))], to: meta.id)+ }+ await #expect(throws: ConversationStoreError.self) {+ try await store.rename(id: meta.id, to: "no")+ }+ // Opening it projected a meta of its own and deliberately did not write+ // it: an older build stamping its schema over a newer one's file is the+ // migration loss the field is full of.+ #expect(try Data(contentsOf: metaURL) == before)+ }++ /// The first append must respect the version it discovers itself, without+ /// requiring an earlier list or open to populate the read-only cache.+ @Test(arguments: [false, true])+ func firstAppendRefusesANewerVersionWithoutChangingEitherFile(+ incompatibleSchema: Bool+ ) async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ var meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ meta.version = ConversationMeta.currentVersion + 1+ let metaURL = await store.metaURL(for: meta.id)+ let transcriptURL = await store.transcriptURL(for: meta.id)+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ let data = incompatibleSchema+ ? try JSONSerialization.data(withJSONObject: ["version": meta.version])+ : try encoder.encode(meta)+ try data.write(to: metaURL)+ let metaBefore = try Data(contentsOf: metaURL)+ let transcriptBefore = try Data(contentsOf: transcriptURL)++ await #expect(throws: ConversationStoreError.self) {+ try await store.append([.title(ConversationTitleRecord(+ title: "no", source: .user, at: Date()))], to: meta.id)+ }+ #expect(try Data(contentsOf: metaURL) == metaBefore)+ #expect(try Data(contentsOf: transcriptURL) == transcriptBefore)+ }++ @Test(arguments: 0...2, [false, true])+ func newerHeaderProtectsTranscriptWhenMetadataCannotProtectIt(+ cacheState: Int, sweepFirst: Bool+ ) async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ let transcript = await store.transcriptURL(for: meta.id)+ let metaURL = await store.metaURL(for: meta.id)+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ var bytes = try encoder.encode(TranscriptRecord.header(ConversationHeaderRecord(+ version: ConversationMeta.currentVersion + 1,+ id: meta.id, createdAt: meta.createdAt, identity: identity,+ session: session, sampling: sampling)))+ // Recovery must not truncate even a torn tail owned by a newer writer.+ bytes.append(contentsOf: "\n{\"type\":".utf8)+ try bytes.write(to: transcript)+ if cacheState == 0 { try FileManager.default.removeItem(at: metaURL) }+ if cacheState == 1 { try Data("invalid cache".utf8).write(to: metaURL) }+ let cachedBytes = FileManager.default.contents(atPath: metaURL.path)+ let image = await store.imagesURL(for: meta.id).appendingPathComponent("future.png")+ let imageBytes = Data("future format image".utf8)+ try imageBytes.write(to: image)++ if sweepFirst {+ await #expect(throws: ConversationStoreError.self) {+ try await store.sweepOrphanImages(in: meta.id)+ }+ }++ let opened = try await store.open(id: meta.id)+ #expect(opened.isReadOnly)+ #expect(opened.meta.version == ConversationMeta.currentVersion + 1)+ await #expect(throws: ConversationStoreError.self) {+ try await store.rename(id: meta.id, to: "must not write")+ }+ #expect(try Data(contentsOf: transcript) == bytes)+ #expect(FileManager.default.contents(atPath: metaURL.path) == cachedBytes)+ #expect(FileManager.default.contents(atPath: image.path) == imageBytes)+ }++ /// Two writers on one JSONL file is the documented corruption. The second+ /// instance reads and says so rather than appending beside the first.+ @Test func aSecondHolderOfTheStoreIsReadOnly() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let first = try await makeStore(root)+ let meta = try await first.create(+ title: "t", identity: identity, session: session, sampling: sampling)++ let second = ConversationStore(rootURL: root)+ try await second.activate()+ #expect(await second.isReadOnly)+ // Reading still works: a second window is a normal thing to open.+ #expect(try await second.list().count == 1)+ _ = try await second.open(id: meta.id)+ await #expect(throws: ConversationStoreError.self) {+ try await second.append([.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "no", tokens: [1]))], to: meta.id)+ }+ #expect(await first.isReadOnly == false)+ }++ /// Delete means delete. A conversation used to be parked in `.trash` so an+ /// undo could restore it, which left every deleted transcript and image on+ /// disk for the life of the store with nothing to collect them.+ @Test func deleteRemovesTheConversationAndEverythingInIt() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ try await store.append([.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "keep me", tokens: [1]))], to: meta.id)+ let directory = await store.directoryURL(for: meta.id)+ let image = directory.appendingPathComponent("images/abcd.png")+ try Data("pixels".utf8).write(to: image)++ try await store.delete(id: meta.id)++ #expect(try await store.list().isEmpty)+ #expect(!FileManager.default.fileExists(atPath: directory.path),+ "the conversation was parked rather than deleted")+ #expect(!FileManager.default.fileExists(atPath: image.path))+ // Nothing anywhere in the store still holds it.+ let leftovers = try FileManager.default.contentsOfDirectory(+ atPath: directory.deletingLastPathComponent().path)+ #expect(!leftovers.contains(".trash"))+ // And deleting it again is a real error, not a silent success.+ await #expect(throws: ConversationStoreError.self) {+ try await store.delete(id: meta.id)+ }+ }++ /// A second window can take the lock once the first gives it up.+ ///+ /// `isReadOnly` was decided once, at activation, so a window that opened+ /// while another held the lock said "this one can read them but not change+ /// them" for the rest of its life — including long after the other had+ /// quit.+ @Test func asecondStoreTakesTheLockOnceTheFirstReleasesIt() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }++ var first: ConversationStore? = try await makeStore(root)+ let second = ConversationStore(rootURL: root)+ try await second.activate()+ #expect(await second.isReadOnly, "two writers held the store at once")++ // Retrying while the first is still there changes nothing.+ await second.retryLock()+ #expect(await second.isReadOnly)++ first = nil+ _ = first+ await second.retryLock()+ #expect(await second.isReadOnly == false, "the notice would never clear")+ }++ /// A directory whose meta names a different conversation is not listed.+ ///+ /// That is what a copy looks like, and what an undelete tool produces.+ /// Listed, its id collides with the original's and the sidebar — which keys+ /// rows by id — drew one of the two as a blank row. Found running case C27+ /// by cloning a conversation directory without fixing the id inside.+ @Test func adirectoryWhoseMetaNamesAnotherConversationIsSkipped() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "original", identity: identity, session: session,+ sampling: sampling)+ let original = await store.directoryURL(for: meta.id)++ // A copy under a new name, its meta and header still naming the original.+ let cloneID = UUID()+ let clone = original.deletingLastPathComponent()+ .appendingPathComponent(cloneID.uuidString, isDirectory: true)+ try FileManager.default.copyItem(at: original, to: clone)++ let listed = try await store.list()+ #expect(listed.count == 1, "the clone was listed under the original's id")+ #expect(listed.first?.id == meta.id)+ #expect(await store.skippedByLastList == [cloneID],+ "the clone vanished with no trace")+ }++ /// Renaming does not count as using a conversation.+ ///+ /// The list is ordered by `updatedAt`, so bumping it on a rename jumped the+ /// row to the top of the sidebar — not what someone tidying up their titles+ /// is asking for.+ @Test func renamingDoesNotBumpTheConversationsPlaceInTheList() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "before", identity: identity, session: session,+ sampling: sampling)+ let before = try await store.open(id: meta.id).meta.updatedAt++ try await store.rename(id: meta.id, to: "after")++ let after = try await store.open(id: meta.id).meta+ #expect(after.title == "after")+ #expect(after.updatedAt == before, "the rename reordered the list")+ // The rename is still recorded, with its own time.+ let titles = try await store.open(id: meta.id).records.compactMap {+ record -> String? in+ if case .title(let value) = record { return value.title }+ return nil+ }+ #expect(titles.last == "after")+ }++ /// A `.trash` left by an older build is emptied on first activation.+ ///+ /// Delete used to park conversations there for an undo to restore, and+ /// nothing ever collected them — so upgrading with the purge removed would+ /// have stranded every chat anyone had ever deleted. Deleting means+ /// deleting, including for the ones deleted before.+ @Test func activationDiscardsATrashLeftByAnOlderBuild() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ // What the old build left, in place before the app ever opens the+ // store: a conversation parked under `.trash`.+ let trash = root.appendingPathComponent(".trash", isDirectory: true)+ let parked = trash.appendingPathComponent(UUID().uuidString, isDirectory: true)+ try FileManager.default.createDirectory(+ at: parked, withIntermediateDirectories: true)+ try Data("old".utf8).write(+ to: parked.appendingPathComponent("transcript.jsonl"))++ let store = try await makeStore(root)+ #expect(await store.discardedLegacyTrashCount == 1)+ #expect(!FileManager.default.fileExists(atPath: trash.path))++ // And the store is usable afterwards.+ _ = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ #expect(try await store.list().count == 1)+ }++ @Test func activationPropagatesLegacyTrashListingFailure() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let trash = root.appendingPathComponent(".trash", isDirectory: true)+ try FileManager.default.createDirectory(+ at: trash, withIntermediateDirectories: true)+ let store = ConversationStore(+ rootURL: root,+ legacyTrashOperations: ConversationLegacyTrashOperations(+ list: { _ in throw TrashFailure.list },+ remove: { _ in throw TrashFailure.remove }))++ await #expect(throws: TrashFailure.self) {+ try await store.activate()+ }+ #expect(await store.isReadOnly)+ #expect(FileManager.default.fileExists(atPath: trash.path))+ }++ @Test func retryLockReportsLegacyTrashRemovalFailureAndLeavesItRetryable()+ async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let trash = root.appendingPathComponent(".trash", isDirectory: true)+ try FileManager.default.createDirectory(+ at: trash, withIntermediateDirectories: true)+ let store = ConversationStore(+ rootURL: root,+ legacyTrashOperations: ConversationLegacyTrashOperations(+ list: { _ in ["parked"] },+ remove: { _ in throw TrashFailure.remove }))++ await #expect(throws: TrashFailure.self) {+ try await store.activate()+ }+ let first = await store.retryLock()+ let second = await store.retryLock()++ #expect(first?.contains("injected trash removal failure") == true)+ #expect(second?.contains("injected trash removal failure") == true)+ #expect(await store.isReadOnly)+ #expect(FileManager.default.fileExists(atPath: trash.path))+ }++ // MARK: - conversation.json as a cache++ /// The meta is a projection of the records, so losing it costs nothing.+ ///+ /// Before it was one, a `conversation.json` that would not decode cost the+ /// user the whole conversation: the listing skipped the directory and+ /// nothing ever put it back.+ @Test func aMetaThatIsGoneOrDamagedIsRebuiltFromTheRecords() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "keep me", identity: identity, session: session,+ sampling: sampling)+ try await store.append([.turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "keep me", tokens: [1, 2]))], to: meta.id)+ let expected = try await store.open(id: meta.id).meta+ let metaURL = await store.metaURL(for: meta.id)++ try FileManager.default.removeItem(at: metaURL)+ #expect(try await store.open(id: meta.id).meta == expected)+ #expect(FileManager.default.fileExists(atPath: metaURL.path),+ "the cache was not written back")++ try "{ not json".write(to: metaURL, atomically: true, encoding: .utf8)+ #expect(try await store.open(id: meta.id).meta == expected)+ // The rebuild is reported: the conversation survives it, but a cache+ // that could not be read is still a fault of the store.+ try "{ not json".write(to: metaURL, atomically: true, encoding: .utf8)+ #expect(try await store.open(id: meta.id).metaRebuildReason != nil)+ // And an agreeing cache is not a rebuild.+ #expect(try await store.open(id: meta.id).metaRebuildReason == nil)+ }++ /// A meta naming another conversation over a header that names this one is+ /// a damaged cache, not a damaged conversation.+ ///+ /// The directory name and the header agree, which is what identity is; the+ /// third copy was the one that drifted, and it is the one that is replaced.+ @Test func aMetaNamingAnotherConversationIsRepairedFromTheHeader() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "mine", identity: identity, session: session, sampling: sampling)+ let metaURL = await store.metaURL(for: meta.id)++ var stranger = meta+ stranger.id = UUID()+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ try encoder.encode(stranger).write(to: metaURL)++ #expect(try await store.open(id: meta.id).meta.id == meta.id)+ let listed = try await store.list()+ #expect(listed.map(\.id) == [meta.id], "the repaired chat was skipped")+ #expect(await store.skippedByLastList.isEmpty)+ }++ /// A hand edit to the cache does not survive the next open.+ ///+ /// The one behaviour the projection takes away, and stated as such in ADR+ /// 034: renaming from outside the app means appending a `title` line to the+ /// transcript, not typing into `conversation.json`.+ @Test func ahandEditToTheCacheIsReplacedRatherThanHonoured() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "as written", identity: identity, session: session,+ sampling: sampling)++ var edited = meta+ edited.title = "typed straight into the file"+ edited.turnCount = 99+ edited.kvTokens = 12_345+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ try encoder.encode(edited).write(to: await store.metaURL(for: meta.id))++ let reopened = try await store.open(id: meta.id).meta+ #expect(reopened.title == "as written")+ #expect(reopened.turnCount == 0)+ #expect(reopened.kvTokens == nil)+ // The supported way, which is a record and therefore survives.+ try await store.rename(id: meta.id, to: "renamed properly")+ #expect(try await store.open(id: meta.id).meta.title == "renamed properly")+ }++ /// A store that cannot take the writer lock projects in memory and writes+ /// nothing. Two instances repairing one store is the corruption the lock+ /// exists to prevent.+ @Test func aReadOnlyStoreRebuildsInMemoryAndLeavesTheBytesAlone() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let first = try await makeStore(root)+ let meta = try await first.create(+ title: "original", identity: identity, session: session,+ sampling: sampling)+ let metaURL = await first.metaURL(for: meta.id)+ try "{ not json".write(to: metaURL, atomically: true, encoding: .utf8)+ let damaged = try Data(contentsOf: metaURL)++ let second = ConversationStore(rootURL: root)+ try await second.activate()+ #expect(await second.isReadOnly)+ #expect(try await second.open(id: meta.id).meta.title == "original")+ #expect(try Data(contentsOf: metaURL) == damaged,+ "a reader repaired somebody else's store")+ // And it is left out of the reader's list rather than repaired into it.+ #expect(try await second.list().isEmpty)+ #expect(await second.skippedByLastList == [meta.id])+ }++ /// A transcript written before the header carried the creation facts gets+ /// them once, and only once.+ @Test func alegacyTranscriptIsHoistedExactlyOnce() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let id = UUID()+ let directory = await store.directoryURL(for: id)+ try FileManager.default.createDirectory(+ at: directory.appendingPathComponent("images", isDirectory: true),+ withIntermediateDirectories: true)+ let created = Date(timeIntervalSince1970: 1_756_000_000)+ let legacy = ConversationMeta(+ id: id, title: "from before", titleSource: .user,+ createdAt: created, updatedAt: created,+ identity: identity, session: session, sampling: sampling,+ boundary: ConversationBoundary(tokens: [7], needsReplay: true))+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ try encoder.encode(legacy).write(+ to: directory.appendingPathComponent(ConversationMeta.fileName))+ // A header with no identity, session or sampling: what the old build+ // wrote.+ var line = try encoder.encode(TranscriptRecord.header(+ ConversationHeaderRecord(id: id, createdAt: created)))+ line.append(0x0A)+ try line.write(to: directory.appendingPathComponent("transcript.jsonl"))++ let opened = try await store.open(id: id)+ #expect(opened.records.filter {+ if case .origin = $0 { return true } else { return false }+ }.count == 1)+ #expect(opened.meta.identity == identity)+ #expect(opened.meta.boundary == ConversationBoundary(tokens: [7], needsReplay: true))+ // The title still comes from the record the old build wrote, which+ // there is not one of — so the cache's is the only source, and after+ // the hoist it is the origin record that keeps the rest.+ #expect(opened.meta.title == ConversationTitle.untitled)++ // A second open has nothing to do.+ let again = try await store.open(id: id)+ #expect(again.records.filter {+ if case .origin = $0 { return true } else { return false }+ }.count == 1)+ // And the conversation reads the same with its cache thrown away.+ try FileManager.default.removeItem(+ at: directory.appendingPathComponent(ConversationMeta.fileName))+ #expect(try await store.open(id: id).meta == again.meta)+ }++ /// A turn the runtime rewound leaves its images behind, and nothing else+ /// would ever collect them: the transcript is append-only and the files are+ /// named by digest, so they are invisible to every other pass.+ @Test func theOrphanSweepKeepsWhatATurnStillReferences() async throws {+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)+ let images = await store.imagesURL(for: meta.id)+ try Data("kept".utf8).write(to: images.appendingPathComponent("kept.png"))+ try Data("kept".utf8).write(to: images.appendingPathComponent("kept.thumb.jpg"))+ try Data("gone".utf8).write(to: images.appendingPathComponent("orphan.png"))++ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "look",+ images: [ConversationImageRecord(+ id: UUID(), displayName: "kept.png",+ pixelsFile: "images/kept.png",+ thumbnailFile: "images/kept.thumb.jpg",+ sourceDigest: "aa", modelInputDigest: "bb",+ width: 48, height: 48, softTokens: 1)],+ tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer", tokens: [2])),+ ], to: meta.id)++ #expect(try await store.sweepOrphanImages(in: meta.id) == 1)+ let remaining = try FileManager.default.contentsOfDirectory(+ atPath: images.path).sorted()+ #expect(remaining == ["kept.png", "kept.thumb.jpg"])+ }++ /// The whole point of the stored copy: write it, read it back, and get the+ /// same model input. If this stops holding, a reopened conversation is+ /// looking at a different picture.+ @Test func aStoredImageReplaysToTheSameModelInput() async throws {+ let device = try #require(MTLCreateSystemDefaultDevice())+ let root = makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try await makeStore(root)+ let meta = try await store.create(+ title: "t", identity: identity, session: session, sampling: sampling)++ let source = try Self.writeSourcePNG(width: 200, height: 100)+ defer { try? FileManager.default.removeItem(at: source) }+ let attachment = StagedImage(+ fileURL: source, displayName: "photo.png",+ encodedBytes: 1_024, sha256: String(repeating: "a", count: 64))++ let images = await store.imagesURL(for: meta.id)+ let record = try ConversationImageWriter(device: device)+ .write(attachment: attachment, into: images)+ #expect(record.pixelsFile == "images/aaaaaaaaaaaaaaaa-\(record.modelInputDigest).png")+ #expect(record.thumbnailFile == "images/aaaaaaaaaaaaaaaa.thumb.jpg")+ #expect(record.softTokens > 0)++ let directory = await store.directoryURL(for: meta.id)+ let preprocessor = Gemma4ImagePreprocessor(device: device)+ let stored = directory.appendingPathComponent(record.pixelsFile)+ let plan = try preprocessor.plan(storedModelInput: stored)+ #expect(plan.geometry.processedWidth == record.width)+ #expect(plan.geometry.processedHeight == record.height)+ #expect(plan.geometry.softTokenCount == record.softTokens)+ // Accepts its own digest, and only its own.+ _ = try preprocessor.preprocess(+ storedModelInput: plan, expectedDigest: record.modelInputDigest)+ #expect(throws: VisionImageError.self) {+ try preprocessor.preprocess(+ storedModelInput: try preprocessor.plan(storedModelInput: stored),+ expectedDigest: String(repeating: "0", count: 64))+ }++ let thumbnail = directory.appendingPathComponent(record.thumbnailFile)+ #expect(FileManager.default.fileExists(atPath: thumbnail.path))++ let original = try Data(contentsOf: stored)+ let repeated = try ConversationImageWriter(device: device)+ .write(attachment: attachment, into: images)+ #expect(repeated.pixelsFile == record.pixelsFile)+ #expect(try Data(contentsOf: stored) == original)++ // Model a new preprocessing result under the same source identity.+ // Its digest must name a separate file so the older turn still replays.+ let changedSource = try Self.writeSourcePNG(width: 300, height: 100)+ defer { try? FileManager.default.removeItem(at: changedSource) }+ let changed = try ConversationImageWriter(device: device).write(+ attachment: StagedImage(+ fileURL: changedSource, displayName: "photo.png",+ encodedBytes: 1_024, sha256: attachment.sha256), into: images)+ #expect(changed.modelInputDigest != record.modelInputDigest)+ #expect(changed.pixelsFile != record.pixelsFile)+ #expect(try Data(contentsOf: stored) == original)+ #expect(try FileManager.default.contentsOfDirectory(atPath: images.path).count == 3)+ }++ private static func writeSourcePNG(width: Int, height: Int) throws -> URL {+ let rowBytes = width * 4+ var bytes = [UInt8](repeating: 255, count: rowBytes * height)+ for y in 0..<height {+ for x in 0..<width {+ let offset = y * rowBytes + x * 4+ bytes[offset] = UInt8((x * 5 + y * 3) % 256)+ bytes[offset + 1] = UInt8((x * 7) % 256)+ bytes[offset + 2] = UInt8((y * 11) % 256)+ }+ }+ let image = try bytes.withUnsafeMutableBytes { raw -> CGImage in+ let context = try #require(CGContext(+ data: raw.baseAddress, width: width, height: height,+ bitsPerComponent: 8, bytesPerRow: rowBytes,+ space: CGColorSpace(name: CGColorSpace.sRGB)!,+ bitmapInfo: CGBitmapInfo.byteOrder32Big.rawValue+ | CGImageAlphaInfo.premultipliedLast.rawValue))+ return try #require(context.makeImage())+ }+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("store-source-\(UUID().uuidString).png")+ let destination = try #require(CGImageDestinationCreateWithURL(+ url as CFURL, UTType.png.identifier as CFString, 1, nil))+ CGImageDestinationAddImage(destination, image, nil)+ #expect(CGImageDestinationFinalize(destination))+ return url+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppConversationRecordTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppConversationRecordTests.swiftnew file mode 100644index 00000000..5f9fe596--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/AppConversationRecordTests.swift@@ -0,0 +1,95 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++/// The transcript keeps two things per turn that must not be confused: the text+/// the reader sees, and the token IDs the model saw. Storing only the first is+/// what makes a reopened conversation a different conversation, because the+/// pinned template strips historical thought spans when it re-renders.+@Suite struct AppConversationRecordTests {+ private func diagnostics(+ prompt: [Int32]?, generated: [Int32]?,+ boundary: [Int32]? = nil, boundaryNeedsReplay: Bool? = nil,+ conversationTokens: Int? = nil+ ) -> AppDiagnostics {+ var value = AppDiagnostics(+ generatedTokens: generated?.count ?? 0,+ stopReason: .endOfTurn,+ promptTokenCount: prompt?.count,+ conversationTokens: conversationTokens,+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 0,+ tokensPerSecond: 0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())+ value.promptTokenIDs = prompt+ value.generatedTokenIDs = generated+ value.boundaryTokenIDs = boundary+ value.boundaryNeedsReplay = boundaryNeedsReplay+ return value+ }++ @Test func eachHalfOfATurnKeepsTheIDsItPutInTheKV() throws {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "hello")+ conversation.completeTurn(+ text: "hi there",+ diagnostics: diagnostics(prompt: [2, 105, 7], generated: [40, 41],+ conversationTokens: 5))+ #expect(conversation.turns[0].role == .user)+ #expect(conversation.turns[0].tokenIDs == [2, 105, 7])+ #expect(conversation.turns[1].role == .assistant)+ #expect(conversation.turns[1].tokenIDs == [40, 41])+ // Concatenating the record has to reproduce the KV the runtime reports.+ #expect(conversation.turns.compactMap(\.tokenIDs).flatMap { $0 }.count+ == conversation.kvTokens)+ }++ /// A run that stopped on max tokens or was cancelled left one emitted token+ /// outside the KV, and the next turn replays it. A stored conversation that+ /// dropped it would reopen with a context missing a token the model already+ /// produced.+ @Test func theUncommittedBoundaryIsPartOfTheRecord() {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "hello")+ conversation.completeTurn(+ text: "partial",+ diagnostics: diagnostics(prompt: [1], generated: [9],+ boundary: [77], boundaryNeedsReplay: true,+ conversationTokens: 2))+ #expect(conversation.boundaryTokenIDs == [77])+ #expect(conversation.boundaryNeedsReplay)++ // And a turn that ended cleanly clears it, rather than leaving the+ // previous turn's boundary to be replayed a second time.+ _ = conversation.beginTurn(text: "again")+ conversation.completeTurn(+ text: "done",+ diagnostics: diagnostics(prompt: [2], generated: [10],+ conversationTokens: 4))+ #expect(conversation.boundaryTokenIDs.isEmpty)+ #expect(!conversation.boundaryNeedsReplay)+ }++ /// The single-prompt path retains nothing, so it reports no IDs. The record+ /// has to stay nil rather than become an empty array that would later read+ /// as a turn which contributed nothing to the context.+ @Test func aTurnWithNoReportedRecordStoresNothing() {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "hello")+ conversation.completeTurn(+ text: "hi", diagnostics: diagnostics(prompt: nil, generated: nil))+ #expect(conversation.turns[0].tokenIDs == nil)+ #expect(conversation.turns[1].tokenIDs == nil)+ }++ /// A turn the runtime rewound is in neither the KV nor the transcript, so+ /// its IDs must not survive either.+ @Test func anAbandonedTurnTakesItsRecordWithIt() {+ var conversation = AppConversation()+ _ = conversation.beginTurn(text: "hello")+ conversation.abandonTurn()+ #expect(conversation.turns.isEmpty)+ #expect(conversation.committedTurns == 0)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swiftindex 1d886751..c66f8495 100644--- a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift@@ -92,35 +92,9 @@ import TurboFieldfaretry request.validate()}}- @Test func duplicateAndMalformedImageDescriptorsAreRejected() {- let id = UUID()- let attachment = AppImageAttachment(- id: id,- fileURL: URL(fileURLWithPath: "/tmp/image.png"),- displayName: "image.png",- encodedBytes: 4,- sha256: String(repeating: "a", count: 64))- #expect(throws: AppInferenceError.self) {- try AppGenerationRequest(- modelDirectory: existingDirectory,- prompt: "",- imageAttachments: [attachment, attachment]).validate()- }- let malformed = AppImageAttachment(- fileURL: URL(fileURLWithPath: "/tmp/image.png"),- displayName: "image.png",- encodedBytes: 4,- sha256: "not-a-digest")- #expect(throws: AppInferenceError.self) {- try AppGenerationRequest(- modelDirectory: existingDirectory,- prompt: "",- imageAttachments: [malformed]).validate()- }- }@Test func imageOnlyRequestIsValid() throws {- let attachment = AppImageAttachment(+ let attachment = StagedImage(fileURL: URL(fileURLWithPath: "/tmp/image.png"),displayName: "image.png",encodedBytes: 4,@@ -132,16 +106,17 @@ import TurboFieldfaretry request.validate()}- private func image(_ name: String) -> AppImageAttachment {- AppImageAttachment(+ private func image(_ name: String) -> StagedImage {+ StagedImage(fileURL: URL(fileURLWithPath: "/tmp/\(name)"),displayName: name, encodedBytes: 4,sha256: String(repeating: "a", count: 64))}@Test func imageCapacityShrinksAsTheConversationFills() throws {+ // An empty conversation still keeps the reply's reserve free.let capacity = VisionImageTokenBudget.capacity(- maxContext: 8_192, reservedTextTokens: 0)+ maxContext: 8_192, reservedTextTokens: ConversationGenerationReserve.tokens)#expect(capacity >= 2, "the fixture needs room for more than one image")let attachments = (0..<capacity).map { image("image-\($0).png") }@@ -160,12 +135,23 @@ import TurboFieldfare}@Test func aTurnCarryingOneImageStillFitsLateInAConversation() throws {- let carried = 8_192 - VisionImageTokenBudget.maximumTokensPerImage - 16+ // One image, the reply's reserve, and a little text still fit.+ let carried = 8_192 - VisionImageTokenBudget.maximumTokensPerImage+ - ConversationGenerationReserve.tokens - 16try AppGenerationRequest(modelDirectory: existingDirectory, prompt: "what is this",imageAttachments: [image("one.png")], maxContextTokens: 8_192,continuesConversation: true,conversationTokens: carried).validate()+ // Without room for the reply, the same image is refused here rather+ // than after the runtime has encoded it.+ #expect(throws: AppInferenceError.self) {+ try AppGenerationRequest(+ modelDirectory: existingDirectory, prompt: "what is this",+ imageAttachments: [image("one.png")], maxContextTokens: 8_192,+ continuesConversation: true,+ conversationTokens: carried + ConversationGenerationReserve.tokens).validate()+ }}@Test func aOneShotRequestReservesNothingAndKeepsItsOldCapacity() throws {@@ -217,4 +203,30 @@ import TurboFieldfaremaxContext: Int.max, reservedTextTokens: Int.min) == 0)}+ @Test func duplicateAndMalformedImageDescriptorsAreRejected() {+ let id = UUID()+ let attachment = StagedImage(+ id: id,+ fileURL: URL(fileURLWithPath: "/tmp/image.png"),+ displayName: "image.png",+ encodedBytes: 4,+ sha256: String(repeating: "a", count: 64))+ #expect(throws: AppInferenceError.self) {+ try AppGenerationRequest(+ modelDirectory: existingDirectory,+ prompt: "",+ imageAttachments: [attachment, attachment]).validate()+ }+ let malformed = StagedImage(+ fileURL: URL(fileURLWithPath: "/tmp/image.png"),+ displayName: "image.png",+ encodedBytes: 4,+ sha256: "not-a-digest")+ #expect(throws: AppInferenceError.self) {+ try AppGenerationRequest(+ modelDirectory: existingDirectory,+ prompt: "",+ imageAttachments: [malformed]).validate()+ }+ }}diff --git a/Tests/TurboFieldfareApp/Core/Inference/ConversationGenerationReserveTests.swift b/Tests/TurboFieldfareApp/Core/Inference/ConversationGenerationReserveTests.swiftnew file mode 100644index 00000000..120474ab--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/ConversationGenerationReserveTests.swift@@ -0,0 +1,83 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// Admission has to promise what it checks.+///+/// Before this, `generate` admitted any turn whose prompt alone fit — room for+/// exactly one generated token — while the refusal the user saw named their+/// whole max response. A chat near the ceiling was accepted and then answered+/// with a single word, and the same arithmetic now decides whether a stored+/// conversation can be continued, so an over-generous guard would put a row+/// marked "continue" in front of a composer that refuses everything.+@Suite struct ConversationGenerationReserveTests {+ /// The old guard was `prompt + 1 <= maxContext`. Anything that admits a+ /// prompt with only one token of headroom fails here.+ @Test func aTurnNeedsRoomForARealReplyNotOneToken() {+ let maxContext = 4_096+ let reserve = ConversationGenerationReserve.tokens+ #expect(reserve > 1, "a one-token reserve is what this test exists to reject")++ #expect(ConversationGenerationReserve.fits(+ tokens: maxContext - reserve, maxContext: maxContext))+ #expect(!ConversationGenerationReserve.fits(+ tokens: maxContext - reserve + 1, maxContext: maxContext))+ // The old guard was `prompt + 1 <= maxContext`, which admitted this.+ #expect(!ConversationGenerationReserve.fits(+ tokens: maxContext - 1, maxContext: maxContext))+ }++ /// The message names the figure the guard used. Reporting the user's max+ /// response instead is how someone lowers their reply length, sees no+ /// change, and has no way to find out why.+ @Test func theRefusalNamesTheReserveItActuallyChecked() {+ let error = AppInferenceError.conversationContextExhausted(+ prompt: 3_900, reserve: ConversationGenerationReserve.tokens,+ maxContext: 4_096)+ let message = error.userMessage+ #expect(message.contains("3900") || message.contains("3,900"))+ #expect(message.contains("\(ConversationGenerationReserve.tokens)"))+ #expect(message.contains("4096") || message.contains("4,096"))+ // The way out is a longer context or a new chat, not a shorter prompt.+ #expect(message.contains("context length"))+ #expect(message.contains("new chat"))+ }++ /// A conversation that could not take a turn must not be replayed at all:+ /// restoring it would spend minutes of prefill to arrive at a composer that+ /// refuses everything typed into it.+ ///+ /// The lineage rule leaves room for the smallest turn, not just for the+ /// reply. Asking `fits` with the lineage alone admitted a chat whose+ /// next message, once wrapped in the turn template, no longer fit — a+ /// row that said "continue" and refused every message.+ @Test func restoreAndSendAgreeOnTheSameCeiling() {+ let maxContext = 8_192+ let envelope = ConversationGenerationReserve.turnEnvelope+ let restorable = maxContext - ConversationGenerationReserve.tokens - envelope+ #expect(ConversationGenerationReserve.fitsLineage(+ tokens: restorable, maxContext: maxContext))+ #expect(!ConversationGenerationReserve.fitsLineage(+ tokens: restorable + 1, maxContext: maxContext))+ // The lineage the row admits still fits once the smallest turn is on+ // it, which is what `generate` will ask.+ #expect(ConversationGenerationReserve.fits(+ tokens: restorable + envelope, maxContext: maxContext))+ // The context `needsContext` suggests is one the same rule accepts.+ let required = ConversationGenerationReserve.contextRequired(+ forLineage: restorable + 1)+ #expect(ConversationGenerationReserve.fitsLineage(+ tokens: restorable + 1, maxContext: required))+ #expect(!ConversationGenerationReserve.fitsLineage(+ tokens: restorable + 1, maxContext: required - 1))+ }++ /// The envelope is what a one-word turn costs in template tokens, and a+ /// zero would put the rule back where it was.+ @Test func theTurnEnvelopeIsARealAllowance() {+ #expect(ConversationGenerationReserve.turnEnvelope > 1)+ #expect(ConversationGenerationReserve.turnEnvelope+ < ConversationGenerationReserve.tokens)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceLostConnectionTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceLostConnectionTests.swiftnew file mode 100644index 00000000..badb4fd8--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceLostConnectionTests.swift@@ -0,0 +1,65 @@+import Foundation+import Testing+import TurboFieldfareDecodeProtocol+@testable import TurboFieldfareAppCore++/// A service the client can no longer reach is one loss, whatever was asked+/// of it.+///+/// The router tears the connection down when the service dies while idle and+/// nothing tells the window. The next request then found no handles: a reset+/// reported that as an unknown failure and a restore as a refused replay, so+/// the model stayed advertised as ready with no Retry Load, and the held+/// lineage was ended for a service that was simply gone. `connectionLost` is+/// the class the app turns into a failed load.+@Suite struct DecodeServiceLostConnectionTests {+ @Test func connectionLostDuringResetIsReportedAsConnectionLost() async throws {+ let requests = Pipe()+ let responses = Pipe()+ let client = DecodeServiceInferenceClient(+ testInput: requests.fileHandleForWriting,+ responseOutput: responses.fileHandleForReading)+ defer {+ client.shutdownForTermination()+ try? requests.fileHandleForReading.close()+ }+ let peer = Task.detached {+ _ = try DecodeFrameCodec.read(+ DecodeServiceCommand.self, from: requests.fileHandleForReading)+ try responses.fileHandleForWriting.close()+ }+ do {+ try await client.resetConversation(epoch: UUID())+ Issue.record("reset succeeded after the peer disconnected")+ } catch AppInferenceError.connectionLost {+ } catch {+ Issue.record("transport failure did not reach Retry Load: \(error)")+ }+ try await peer.value+ }++ @Test func aRestoreWithNoConnectionIsALostConnection() async {+ let client = DecodeServiceInferenceClient()+ do {+ _ = try await client.restoreConversation(+ AppConversationLineage(tokenIDs: [1, 2], committedTurns: 1),+ epoch: UUID(), options: AppRuntimeOptions(),+ maxContextTokens: 8_192) { _, _ in }+ Issue.record("a restore with no connection returned")+ } catch AppInferenceError.connectionLost {+ } catch {+ Issue.record("a restore with no connection threw \(error)")+ }+ }++ @Test func aResetWithNoConnectionIsALostConnection() async {+ let client = DecodeServiceInferenceClient()+ do {+ try await client.resetConversation(epoch: UUID())+ Issue.record("a reset with no connection returned")+ } catch AppInferenceError.connectionLost {+ } catch {+ Issue.record("a reset with no connection threw \(error)")+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceReconnectTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceReconnectTests.swiftnew file mode 100644index 00000000..4ca451df--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceReconnectTests.swift@@ -0,0 +1,408 @@+import Darwin+import Foundation+import Synchronization+import Testing+@testable import TurboFieldfare+@testable import TurboFieldfareAppCore+import TurboFieldfareDecodeProtocol++/// A stand-in decode service: it speaks the wire protocol over a real socket+/// and can be killed, which is the whole point. A real service would need a+/// model, and the defect under test is in the transport, not the model.+private final class FakeDecodeService: @unchecked Sendable {+ let socketPath: String+ private let loads = Mutex(0)+ private let cancels = Mutex(0)+ private let generations = Mutex(0)+ private let shutdowns = Mutex(0)+ /// Makes the load slow enough to be cancelled mid-flight, the way a real+ /// multi-minute model load is.+ let loadDelay: Duration+ private var thread: Thread?+ private let stopped = Mutex(false)+ private let handles = Mutex<(input: FileHandle, output: FileHandle)?>(nil)++ init(loadDelay: Duration = .zero) {+ self.socketPath = "/private/tmp/turbofieldfare-fake-decode-\(UUID().uuidString).sock"+ self.loadDelay = loadDelay+ }++ var loadCount: Int { loads.withLock { $0 } }+ var cancelCount: Int { cancels.withLock { $0 } }+ var generationCount: Int { generations.withLock { $0 } }+ var shutdownCount: Int { shutdowns.withLock { $0 } }++ func start() {+ let thread = Thread { [self] in serve() }+ thread.name = "FakeDecodeService"+ thread.start()+ self.thread = thread+ // The file appears at bind(), before listen(), so waiting for it is not+ // waiting for readiness. The client under test retries its connect, so+ // this only has to give the listener a moment to exist at all.+ let deadline = ContinuousClock.now + .seconds(5)+ while !FileManager.default.fileExists(atPath: socketPath),+ ContinuousClock.now < deadline {+ usleep(5_000)+ }+ }++ /// Kills the service the way a jetsam or a crash would: the socket simply+ /// stops, mid-session, with no protocol-level goodbye.+ func kill() {+ stopped.withLock { $0 = true }+ let current = handles.withLock { value -> (FileHandle, FileHandle)? in+ defer { value = nil }+ return value.map { ($0.input, $0.output) }+ }+ try? current?.0.close()+ try? current?.1.close()+ unlink(socketPath)+ }++ private func serve() {+ guard let accepted = try? DecodeUnixSocket.listenAndAccept(path: socketPath)+ else { return }+ handles.withLock { $0 = accepted }+ while !(stopped.withLock { $0 }) {+ guard let command = try? DecodeFrameCodec.read(+ DecodeServiceCommand.self, from: accepted.input) else { return }+ switch command {+ case .load(let request):+ loads.withLock { $0 += 1 }+ if loadDelay != .zero {+ let seconds = Double(loadDelay.components.seconds)+ + Double(loadDelay.components.attoseconds) / 1e18+ usleep(useconds_t(seconds * 1_000_000))+ }+ try? accepted.output.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .ready, generationID: request.requestID)))+ case .resetConversation(let request):+ try? accepted.output.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .conversationReset,+ generationID: request.requestID,+ conversationTokenCount: 0,+ conversationEpoch: request.epoch)))+ case .restoreConversation(let request):+ try? accepted.output.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .conversationRestored,+ generationID: request.requestID,+ conversationTokenCount: request.tokenIDs.count,+ conversationEpoch: request.epoch)))+ case .generate(let request):+ generations.withLock { $0 += 1 }+ try? accepted.output.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .finished,+ generationID: request.generationID,+ textDelta: "answer",+ tokenCount: 1,+ stopReason: "eos")))+ case .unload(let id):+ try? accepted.output.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .unloaded, generationID: id)))+ case .cancel:+ cancels.withLock { $0 += 1 }+ case .shutdown:+ shutdowns.withLock { $0 += 1 }+ return+ }+ }+ }+}++/// The app talks to the decode service over a socket, so when that service dies+/// the client used to latch its handles and its router's terminal error and+/// fail identically on every later request — Ready in the UI, nothing but+/// errors underneath, recoverable only by quitting the app.+@Suite(.serialized) struct DecodeServiceReconnectTests {+ private func withSocketEnvironment<T>(+ _ path: String, _ body: () async throws -> T+ ) async rethrows -> T {+ setenv("TURBO_FIELDFARE_DECODE_SOCKET_PATH", path, 1)+ defer { unsetenv("TURBO_FIELDFARE_DECODE_SOCKET_PATH") }+ return try await body()+ }++ @Test func terminationDisconnectsButDoesNotShutdownAnExternalService() async throws {+ let options = AppRuntimeOptions()+ let model = FileManager.default.temporaryDirectory+ .appendingPathComponent("fake-model-\(UUID())")+ let service = FakeDecodeService()+ service.start()+ defer { service.kill() }++ try await withSocketEnvironment(service.socketPath) {+ let first = DecodeServiceInferenceClient(testConnection: {+ let path = try #require(ProcessInfo.processInfo.environment["TURBO_FIELDFARE_DECODE_SOCKET_PATH"])+ return try DecodeUnixSocket.connect(path: path)+ })+ try await first.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: options, forceLogitsHead: false, onState: { _ in })+ first.shutdownForTermination()+ #expect(service.shutdownCount == 0)+ }+ #expect(service.loadCount == 1)+ #expect(service.shutdownCount == 0)+ #expect(FileManager.default.fileExists(atPath: service.socketPath),+ "disconnecting unlinked an externally owned service socket")+ }++ @Test func aDeadServiceIsReplacedInsteadOfFailingForever() async throws {+ let options = AppRuntimeOptions()+ let model = FileManager.default.temporaryDirectory+ .appendingPathComponent("fake-model-\(UUID().uuidString)")++ let first = FakeDecodeService()+ first.start()+ defer { first.kill() }+ let client = DecodeServiceInferenceClient(testConnection: {+ let path = try #require(ProcessInfo.processInfo.environment["TURBO_FIELDFARE_DECODE_SOCKET_PATH"])+ return try DecodeUnixSocket.connect(path: path)+ })++ try await withSocketEnvironment(first.socketPath) {+ try await client.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: options, forceLogitsHead: false, onState: { _ in })+ }+ #expect(first.loadCount == 1)++ // The service dies mid-session.+ first.kill()++ // A second service is standing by on a new socket, exactly as launchd+ // would provide after the app relaunches it.+ let second = FakeDecodeService()+ second.start()+ defer { second.kill() }++ try await withSocketEnvironment(second.socketPath) {+ // The first attempt may still fail — the client can be holding a+ // handle to the dead socket — but it must recover by itself, not+ // stay broken until the app is quit.+ var lastError: Error?+ for _ in 0..<3 {+ do {+ try await client.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: options, forceLogitsHead: false, onState: { _ in })+ lastError = nil+ break+ } catch {+ lastError = error+ }+ }+ let detail = String(describing: lastError)+ #expect(lastError == nil,+ "the client never rebuilt its connection: \(detail)")+ }+ #expect(second.loadCount >= 1, "the replacement service was never reached")+ }++ /// Cancelling a load has to reach the service. It runs commands serially,+ /// so a load nobody wants still blocks the unload the UI is waiting on —+ /// which is why cancelling used to freeze every model and companion action+ /// for the rest of the load. The connection must survive it: throwing the+ /// whole service away for a cancel would cost a relaunch and a reload.+ @Test func cancellingALoadReachesTheServiceAndKeepsTheConnection() async throws {+ let options = AppRuntimeOptions()+ let model = FileManager.default.temporaryDirectory+ .appendingPathComponent("fake-model-\(UUID().uuidString)")+ // Long enough that a loaded machine cannot finish it before the+ // cancel: the test waits for the service to report the load, so the+ // only thing this delay buys is the window to cancel in.+ let service = FakeDecodeService(loadDelay: .seconds(10))+ service.start()+ defer { service.kill() }+ let client = DecodeServiceInferenceClient(testConnection: {+ let path = try #require(ProcessInfo.processInfo.environment["TURBO_FIELDFARE_DECODE_SOCKET_PATH"])+ return try DecodeUnixSocket.connect(path: path)+ })++ try await withSocketEnvironment(service.socketPath) {+ let loading = Task {+ try await client.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: options, forceLogitsHead: false, onState: { _ in })+ }+ // Cancel once the service has certainly received the load, rather+ // than after a fixed sleep that a busy machine can overrun.+ let handedOver = ContinuousClock.now + .seconds(20)+ while service.loadCount == 0, ContinuousClock.now < handedOver {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(service.loadCount == 1)+ loading.cancel()+ let started = ContinuousClock.now+ await #expect(throws: CancellationError.self) { try await loading.value }+ #expect(ContinuousClock.now - started < .seconds(60),+ "the cancel never reached the transport wait")++ let deadline = ContinuousClock.now + .seconds(30)+ while service.cancelCount == 0, ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(service.cancelCount >= 1,+ "the service was never told to abandon the load")++ // Same connection, still usable.+ try await client.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: options, forceLogitsHead: false, onState: { _ in })+ }+ #expect(service.loadCount == 2,+ "the client rebuilt the connection instead of reusing it")+ }++ /// A service that accepts the connection and then says nothing must not+ /// hang the caller: the wait is bounded, and the connection is dropped so+ /// the next request starts clean.+ /// A consumer that stops listening is not a broken transport.+ ///+ /// Dropping a generation stream cancels the wait underneath it, and treating+ /// that as a dead connection would shut the service down, bootout its launch+ /// job and unlink its socket — so abandoning one answer would cost a+ /// relaunch and a full model reload before the next one.+ @Test func abandoningAGenerationKeepsTheService() async throws {+ let options = AppRuntimeOptions()+ // A real directory: the client validates the request before it writes+ // anything, so a placeholder path would fail the stream on the spot and+ // never reach the transport this covers.+ let model = FileManager.default.temporaryDirectory+ .appendingPathComponent("fake-model-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: model, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: model) }+ let service = FakeDecodeService()+ service.start()+ defer { service.kill() }+ let client = DecodeServiceInferenceClient(testConnection: {+ let path = try #require(ProcessInfo.processInfo.environment["TURBO_FIELDFARE_DECODE_SOCKET_PATH"])+ return try DecodeUnixSocket.connect(path: path)+ })++ try await withSocketEnvironment(service.socketPath) {+ try await client.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: options, forceLogitsHead: false, onState: { _ in })+ #expect(service.loadCount == 1)++ // The service never answers a generate, so the stream is still+ // waiting when its consumer walks away.+ let reading = Task {+ for try await _ in client.generate(AppGenerationRequest(+ modelDirectory: model, prompt: "hello",+ maxNewTokens: 8, maxContextTokens: 512,+ runtimeOptions: options)) {}+ }+ try await Task.sleep(for: .milliseconds(300))+ reading.cancel()+ _ = try? await reading.value+ try await Task.sleep(for: .milliseconds(300))+ #expect(service.cancelCount >= 1,+ "the abandoned stream never reached the service, so this proves nothing")++ // Same socket, same process: the next load must reach it.+ try await client.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: options, forceLogitsHead: false, onState: { _ in })+ }+ #expect(service.loadCount == 2,+ "the service was torn down by a caller that stopped listening")+ }++ @Test func aMuteServiceFailsTheRequestAndDropsTheConnection() async throws {+ let options = AppRuntimeOptions()+ let model = FileManager.default.temporaryDirectory+ .appendingPathComponent("fake-model-\(UUID().uuidString)")+ let path = "/private/tmp/turbofieldfare-mute-\(UUID().uuidString).sock"+ // Accepts, then never answers.+ let listener = Thread {+ _ = try? DecodeUnixSocket.listenAndAccept(path: path)+ while !Thread.current.isCancelled { usleep(50_000) }+ }+ listener.start()+ defer { listener.cancel(); unlink(path) }+ let deadline = ContinuousClock.now + .seconds(5)+ while !FileManager.default.fileExists(atPath: path),+ ContinuousClock.now < deadline {+ usleep(5_000)+ }++ let client = DecodeServiceInferenceClient(testConnection: {+ let path = try #require(ProcessInfo.processInfo.environment["TURBO_FIELDFARE_DECODE_SOCKET_PATH"])+ return try DecodeUnixSocket.connect(path: path)+ })+ await withSocketEnvironment(path) {+ let waiting = Task {+ try await client.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: options, forceLogitsHead: false, onState: { _ in })+ }+ try? await Task.sleep(for: .milliseconds(200))+ waiting.cancel()+ let started = ContinuousClock.now+ await #expect(throws: (any Error).self) { try await waiting.value }+ #expect(ContinuousClock.now - started < .seconds(10),+ "cancelling a load never reached the transport wait")+ }+ }++ /// Prefill is outside the load key, so changing it must not turn a+ /// completed answer into a failure or require another model load.+ @Test func flippingPrefillAfterLoadDoesNotFailTheFinishedRun() async throws {+ let loaded = AppRuntimeOptions(prefillEnabled: true)+ // Generation validates its request, unlike a load, so this one needs a+ // directory that actually looks like a model.+ let model = try makeCompleteModelInstall("decode-service-prefill-toggle")+ defer { try? FileManager.default.removeItem(at: model) }++ let service = FakeDecodeService()+ service.start()+ defer { service.kill() }+ let client = DecodeServiceInferenceClient(testConnection: {+ let path = try #require(ProcessInfo.processInfo.environment["TURBO_FIELDFARE_DECODE_SOCKET_PATH"])+ return try DecodeUnixSocket.connect(path: path)+ })++ try await withSocketEnvironment(service.socketPath) {+ try await client.ensureLoaded(+ modelDirectory: model, maxContextTokens: 512,+ options: loaded, forceLogitsHead: false, onState: { _ in })++ // The Inspector's Prefill toggle, flipped after the load.+ var request = AppGenerationRequest(+ modelDirectory: model, prompt: "hello", maxNewTokens: 1,+ maxContextTokens: 512,+ runtimeOptions: AppRuntimeOptions(prefillEnabled: false))+ request.imageAttachments = []+ #expect(request.runtimeOptions.prefillEnabled != loaded.prefillEnabled)++ var events: [AppInferenceEvent] = []+ for try await event in client.generate(request) { events.append(event) }++ #expect(service.generationCount == 1)+ let finished = events.contains {+ if case .finished = $0 { return true }+ return false+ }+ #expect(finished, "a completed run was reported as a failure")+ }+ }+}++/// `currentHandles()` is nil when the connection is gone, not when the model is+/// unloaded. 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 with no way back.+@Suite struct DecodeServiceResetFailureTests {+ @Test func aresetWithNoConnectionFailsRatherThanReportingSuccess() async throws {+ let client = DecodeServiceInferenceClient(testConnection: {+ let path = try #require(ProcessInfo.processInfo.environment["TURBO_FIELDFARE_DECODE_SOCKET_PATH"])+ return try DecodeUnixSocket.connect(path: path)+ })+ await #expect(throws: AppInferenceError.self) {+ try await client.resetConversation(epoch: UUID())+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceTransportRecoveryTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceTransportRecoveryTests.swiftnew file mode 100644index 00000000..8b267163--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceTransportRecoveryTests.swift@@ -0,0 +1,295 @@+import Darwin+import Foundation+import Synchronization+import Testing+@testable import TurboFieldfareAppCore+import TurboFieldfareDecodeProtocol++/// The failure this covers is a decode service that is *alive but mute*: its+/// writer thread died, or a command buffer wedged. Nothing closes the socket,+/// so a blocking wait never returns, Cancel is inert, and the app stays in+/// `.running` until it is quit.+@Suite struct DecodeServiceTransportRecoveryTests {+ @Test func aSilentServiceEndsTheWaitInsteadOfHangingForever() async throws {+ // Open at both ends and never written to: alive, connected, mute.+ let pipe = Pipe()+ defer {+ try? pipe.fileHandleForWriting.close()+ try? pipe.fileHandleForReading.close()+ }+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)++ let started = ContinuousClock.now+ var description = ""+ do {+ _ = try await router.next(matching: UUID(), timeout: .milliseconds(300))+ Issue.record("a mute service produced an event")+ } catch let error as DecodeServiceTransportError {+ description = "\(error)"+ }+ let elapsed = ContinuousClock.now - started+ #expect(elapsed >= .milliseconds(250), "gave up before its deadline")+ // Generous upper bound: this runs alongside the GPU suites, and the+ // point is that the wait ends at all, not that it ends punctually.+ #expect(elapsed < .seconds(120), "the wait never ended")+ #expect(description.contains("stopped responding"),+ "the error must name the cause: \(description)")+ }++ /// The wait used to run in a detached task, so cancelling the caller left+ /// the thread parked and the caller waiting on it.+ @Test func cancellingTheCallerEndsTheWait() async throws {+ let pipe = Pipe()+ defer {+ try? pipe.fileHandleForWriting.close()+ try? pipe.fileHandleForReading.close()+ }+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)++ let waiting = Task {+ try await router.next(matching: UUID(), timeout: .seconds(60))+ }+ try await Task.sleep(for: .milliseconds(100))+ waiting.cancel()++ let started = ContinuousClock.now+ await #expect(throws: CancellationError.self) { try await waiting.value }+ #expect(ContinuousClock.now - started < .seconds(120),+ "cancellation never reached the wait")+ }++ /// A wait entered by a task that is *already* cancelled must end at once.+ ///+ /// `withTaskCancellationHandler` runs its handler immediately in that case+ /// — before the wait registers — so the handler found nothing to fail and+ /// the waiter that registered afterwards sat until its deadline. Fifteen+ /// minutes, for a load, which is indistinguishable from the hang the+ /// deadline was added to end. The app reaches this whenever Cancel is+ /// pressed while the client is still inside its connect retries.+ @Test func awaitEnteredAlreadyCancelledEndsImmediately() async throws {+ let pipe = Pipe()+ defer {+ try? pipe.fileHandleForWriting.close()+ try? pipe.fileHandleForReading.close()+ }+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)++ let waited = Mutex<Duration?>(nil)+ let waiting = Task {+ // Absorbed, so the wait below is entered by a task that is already+ // cancelled — the real ordering, since the client's connect retries+ // are not cancellable either.+ try? await Task.sleep(for: .milliseconds(50))+ let entered = ContinuousClock.now+ defer { waited.withLock { $0 = ContinuousClock.now - entered } }+ // Timed from inside the wait: this suite runs beside the GPU tests,+ // and scheduling delay outside it says nothing about the deadline.+ return try await router.next(matching: UUID(), timeout: .seconds(120))+ }+ waiting.cancel()++ await #expect(throws: CancellationError.self) { try await waiting.value }+ let elapsed = try #require(waited.withLock { $0 }, "the wait was never entered")+ #expect(elapsed < .seconds(30),+ "the wait ran on toward its deadline instead of ending: \(elapsed)")+ }++ /// Closing the stream from the owning side has to end the reader too.+ ///+ /// It holds its own `dup` of the socket, so closing the write handle does+ /// not wake it: against a service too wedged to act on the shutdown command+ /// the client sends first, the thread would stay in `read` for the life of+ /// the process, holding a descriptor nothing else can close.+ @Test func closingTheStreamEndsTheReader() async throws {+ let pipe = Pipe()+ defer { try? pipe.fileHandleForWriting.close() }+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)+ #expect(!router.isTerminated)++ router.closeStream()+ let deadline = ContinuousClock.now + .seconds(5)+ while !router.isTerminated, ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(router.isTerminated, "the reader outlived the connection it read")+ }++ /// The same, on the transport this actually runs over rather than a pipe:+ /// the reader is parked in `read` on a socket when the stream is closed,+ /// which is the shape of the real thing.+ @Test func closingTheStreamEndsTheReaderOnASocket() async throws {+ var pair: [Int32] = [0, 0]+ #expect(socketpair(AF_UNIX, SOCK_STREAM, 0, &pair) == 0)+ let peer = FileHandle(fileDescriptor: pair[0], closeOnDealloc: true)+ defer { try? peer.close() }+ let router = DecodeServiceResponseRouter(+ output: FileHandle(fileDescriptor: pair[1], closeOnDealloc: true))+ // Let the reader reach its blocking read before the stream is closed.+ try await Task.sleep(for: .milliseconds(100))+ #expect(!router.isTerminated)++ router.closeStream()+ let deadline = ContinuousClock.now + .seconds(5)+ while !router.isTerminated, ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(router.isTerminated,+ "the reader stayed blocked on a socket nothing else can close")+ }++ /// A closed stream must be reported once, so the owner can tear the+ /// connection down rather than keep handing out handles that only throw.+ @Test func theStreamEndingIsReportedOnceAndLatches() async throws {+ let pipe = Pipe()+ let notified = Mutex(0)+ let router = DecodeServiceResponseRouter(+ output: pipe.fileHandleForReading,+ onTerminate: { _, _ in notified.withLock { $0 += 1 } })+ #expect(!router.isTerminated)++ try pipe.fileHandleForWriting.close()+ let deadline = ContinuousClock.now + .seconds(5)+ while !router.isTerminated, ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(router.isTerminated)+ #expect(notified.withLock { $0 } == 1)++ // Every later wait fails at once rather than waiting out its timeout.+ let started = ContinuousClock.now+ await #expect(throws: (any Error).self) {+ _ = try await router.next(matching: UUID(), timeout: .seconds(60))+ }+ #expect(ContinuousClock.now - started < .seconds(30),+ "a wait on a dead router blocked for its full timeout")+ try? pipe.fileHandleForReading.close()+ }++ @Test func aTerminatedRouterCanDeallocateAfterItsCallback() async throws {+ let pipe = Pipe()+ let reportedIdentity = Mutex<ObjectIdentifier?>(nil)+ weak var releasedRouter: DecodeServiceResponseRouter?++ do {+ let router = DecodeServiceResponseRouter(+ output: pipe.fileHandleForReading,+ onTerminate: { router, _ in+ reportedIdentity.withLock { $0 = ObjectIdentifier(router) }+ })+ releasedRouter = router+ try pipe.fileHandleForWriting.close()+ let deadline = ContinuousClock.now + .seconds(5)+ while !router.isTerminated, ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(reportedIdentity.withLock { $0 } == ObjectIdentifier(router))+ }++ let deadline = ContinuousClock.now + .seconds(5)+ while releasedRouter != nil, ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(releasedRouter == nil, "the termination callback retained its router")+ }++ /// A service that answers and then exits is ordinary — launchd reaps it as+ /// soon as it is idle — so events that arrived before the stream ended are+ /// still answers and must be drainable after it.+ @Test func endOfStreamDoesNotDiscardEventsThatAlreadyArrived() async throws {+ let pipe = Pipe()+ let id = UUID()+ for index in 0..<4 {+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .snapshot, generationID: id,+ tokenCount: index)))+ }+ try pipe.fileHandleForWriting.close()+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)++ for index in 0..<4 {+ let event = try await router.next(matching: id, timeout: .seconds(5))+ #expect(event.tokenCount == index)+ }+ // Only once they are drained does the closed stream surface.+ await #expect(throws: (any Error).self) {+ _ = try await router.next(matching: id, timeout: .seconds(5))+ }+ try? pipe.fileHandleForReading.close()+ }++ /// Once a wait gives up, that request's later events must be dropped, not+ /// buffered: a stream abandoned early — a cancelled load, a timed-out+ /// generation — otherwise grew the map for the life of the connection.+ @Test func eventsForAnAbandonedRequestAreDropped() async throws {+ let pipe = Pipe()+ defer {+ try? pipe.fileHandleForWriting.close()+ try? pipe.fileHandleForReading.close()+ }+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)+ let abandoned = UUID()++ // Nobody answers, so this wait gives up.+ await #expect(throws: DecodeServiceTransportError.self) {+ _ = try await router.next(matching: abandoned, timeout: .milliseconds(150))+ }++ // The service keeps talking about that request anyway.+ for index in 0..<64 {+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .snapshot, generationID: abandoned,+ tokenCount: index)))+ }+ // A live request on the same connection still works, which is how we+ // know the reader is running and the drop is selective.+ let live = UUID()+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .finished, generationID: live)))+ let event = try await router.next(matching: live, timeout: .seconds(5))+ #expect(event.kind == .finished)++ // Nothing was kept for the abandoned one.+ await #expect(throws: DecodeServiceTransportError.self) {+ _ = try await router.next(matching: abandoned, timeout: .milliseconds(150))+ }+ }++ /// A frame that arrives before anyone waits for it must still be delivered.+ @Test func eventsBufferedBeforeAWaitAreDelivered() async throws {+ let id = UUID()+ let pipe = Pipe()+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .snapshot, generationID: id, tokenCount: 1)))+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .finished, generationID: id, tokenCount: 2)))+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)++ let first = try await router.next(matching: id, timeout: .seconds(5))+ let second = try await router.next(matching: id, timeout: .seconds(5))+ #expect(first.kind == .snapshot)+ #expect(second.kind == .finished)+ try? pipe.fileHandleForWriting.close()+ try? pipe.fileHandleForReading.close()+ }++ /// Writing to a socket whose peer has exited raises SIGPIPE, and the+ /// default disposition kills the process. This is the app's own guarantee,+ /// so assert it on a real closed socket pair rather than trusting the call.+ @Test func writingToADeadPeerFailsInsteadOfKillingTheProcess() throws {+ DecodeUnixSocket.ignoreSIGPIPEProcessWide()+ var descriptors: [Int32] = [0, 0]+ #expect(socketpair(AF_UNIX, SOCK_STREAM, 0, &descriptors) == 0)+ DecodeUnixSocket.disableSIGPIPE(on: descriptors[0])+ Darwin.close(descriptors[1])++ let payload = [UInt8](repeating: 0x41, count: 1_024)+ let written = payload.withUnsafeBytes {+ Darwin.send(descriptors[0], $0.baseAddress!, $0.count, 0)+ }+ // Reaching this line at all is the assertion: an unhandled SIGPIPE+ // would have killed the test process on the send above.+ #expect(written == -1)+ #expect(errno == EPIPE)+ Darwin.close(descriptors[0])+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/FakeInferenceClientTests.swift b/Tests/TurboFieldfareApp/Core/Inference/FakeInferenceClientTests.swiftindex c132d90b..16c3395e 100644--- a/Tests/TurboFieldfareApp/Core/Inference/FakeInferenceClientTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/FakeInferenceClientTests.swift@@ -19,7 +19,7 @@ import Testingmodel.loadModel()try await waitForFakeClient { model.loadState.isReady }model.promptText = "Hello from the test"- model.run()+ model.send()try await waitForFakeClient { model.diagnostics != nil && !model.isRunning }#expect(model.isModelInstalled)diff --git a/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swift b/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swiftindex fe179ad4..63eef687 100644--- a/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swift@@ -7,6 +7,47 @@ import TurboFieldfare/// before any network or Metal work, idle cancel is a no-op, and a bad/// request fails the stream with a typed error.@Suite struct RealInferenceClientStateTests {+ /// A replay image's range is bounded by the record before it is built.+ ///+ /// Both figures arrive over the socket in the service, and a sign check+ /// alone let a pair near `Int.max` overflow the addition: the decode+ /// service trapped mid-command, the app saw EOF and forced a full reload,+ /// and nothing named the record that caused it.+ @Test func aReplayImageRangeThatOverflowsIsRefusedNotTrapped() async {+ let client = RealInferenceClient()+ let overflowing = AppConversationLineage(+ tokenIDs: [1, 2, 3, 4],+ images: [AppConversationReplayImage(+ tokenLowerBound: Int.max - 8, tokenCount: 16,+ fileURL: URL(fileURLWithPath: "/tmp/roof.png"),+ expectedDigest: "roof")],+ committedTurns: 1)+ await #expect(throws: AppInferenceError.self) {+ try await client.restoreConversation(overflowing, options: AppRuntimeOptions())+ }+ }++ /// And a range past the end of the record is a bad record, not a request+ /// the session should see.+ @Test func aReplayImageRangePastTheRecordIsRefused() async {+ let client = RealInferenceClient()+ let past = AppConversationLineage(+ tokenIDs: [1, 2, 3, 4],+ images: [AppConversationReplayImage(+ tokenLowerBound: 3, tokenCount: 2,+ fileURL: URL(fileURLWithPath: "/tmp/roof.png"),+ expectedDigest: "roof")],+ committedTurns: 1)+ do {+ _ = try await client.restoreConversation(past, options: AppRuntimeOptions())+ Issue.record("a range past the record was accepted")+ } catch AppInferenceError.conversationRestoreFailed(let reason) {+ #expect(reason.contains("4-token"))+ } catch {+ Issue.record("unexpected error: \(error)")+ }+ }+@Test func generationRegistryScopesTerminationToOwningID() async {let registry = GenerationTaskRegistry()let first = UUID()diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swiftindex e3889a1b..1b39e187 100644--- a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift@@ -1,4 +1,33 @@import Foundation+private struct PreparedVisionAppFixture {+ let text: URL+ let output: URL+ let partial: URL+ let checkpoint: URL++ func remove() {+ try? FileManager.default.removeItem(at: text)+ try? FileManager.default.removeItem(at: partial)+ try? FileManager.default.removeItem(at: checkpoint)+ }+}++private func makePreparedVisionAppFixture(_ tag: String) throws+ -> PreparedVisionAppFixture {+ let text = try makeCompleteModelInstall(tag)+ let output = text.deletingLastPathComponent().appendingPathComponent(+ text.deletingPathExtension().lastPathComponent + ".vision.gturbo")+ let paths = try RemoteInstallPaths(outputDirectory: output.path)+ try FileManager.default.createDirectory(+ atPath: paths.partialDirectory,+ withIntermediateDirectories: true)+ try Data("checkpoint".utf8).write(to: URL(fileURLWithPath: paths.checkpointFile))+ return PreparedVisionAppFixture(+ text: text,+ output: output.standardizedFileURL,+ partial: URL(fileURLWithPath: paths.partialDirectory),+ checkpoint: URL(fileURLWithPath: paths.checkpointFile))+}import Testingimport TurboFieldfareRepackCore@@ -6,6 +35,55 @@ import TurboFieldfareRepackCore@Suite struct AppModelInstallTests {+ @MainActor+ @Test func completedInstallRebindsHistoryWithoutRelaunch() async throws {+ let fixture = try makeCompleteModelInstall("history-rebind")+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-rebind-\(UUID())", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer {+ try? FileManager.default.removeItem(at: fixture)+ try? FileManager.default.removeItem(at: root)+ }+ let installed = root.appendingPathComponent("model.gturbo", isDirectory: true)+ try FileManager.default.moveItem(at: fixture, to: installed)+ let receiptURL = installed.appendingPathComponent("verified-install.json")+ var receipt = try #require(+ JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL)) as? [String: Any])+ receipt["modelDirectoryPath"] = installed.standardizedFileURL.path+ try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys])+ .write(to: receiptURL)+ let missing = root+ .appendingPathComponent("missing-\(UUID()).gturbo", isDirectory: true)+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = AppModel(+ modelDirectory: missing,+ client: client,+ installer: MockModelInstallerClient(events: [.installed(installed)]),+ settingsPersistenceEnabled: true)++ model.installModel()+ try await waitUntil {+ if case .installed = model.installState { return true }+ return false+ }+ #expect(model.conversationStore != nil)+ #expect(model.conversationIdentity != nil)++ try await client.ensureLoaded(+ modelDirectory: installed, maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions, forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: installed, loadSeconds: 0)+ model.promptText = "persist after install"+ model.send()+ await SendWaiting.turnEnds(model)+ await model.persistenceTail?.value++ let id = try #require(model.storedConversationID)+ let opened = try await #require(model.conversationStore).open(id: id)+ #expect(opened.meta.turnCount == 2)+ }+@MainActor@Test func missingModelCanInstall() {let installer = MockModelInstallerClient()@@ -33,6 +111,180 @@ import TurboFieldfareRepackCore#expect(!model.requiresModelInstallation)#expect(!model.canInstallModel)#expect(model.canLoadModel)+ #expect(model.canInstallVisionPack)+ }++ @MainActor+ @Test func visionInstallProgressCanCancelAndResumeWithoutBlockingText() async throws {+ let directory = try makeCompleteModelInstall("vision-progress")+ defer { try? FileManager.default.removeItem(at: directory) }+ let visionInstaller = MockVisionPackInstallerClient(+ events: [.copyingPayload(+ reusedBytes: 4,+ downloadedThisRunBytes: 6,+ totalBytes: 20)],+ holdOpen: true)+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(),+ visionInstaller: visionInstaller)++ model.installVisionPack()+ try await waitUntil {+ model.visionInstallState == .copyingPayload(+ reusedBytes: 4,+ downloadedThisRunBytes: 6,+ totalBytes: 20)+ }+ #expect(model.visionInstallProgressFraction == 0.5)+ #expect(model.isModelInstalled)+ model.cancelVisionInstall()+ try await waitUntil { model.visionInstallState == .cancelled }+ #expect(model.canInstallVisionPack)+ #expect(model.canLoadModel)+ }++ @MainActor+ @Test func visionPrepareWaitsForExplicitActivation() async throws {+ let directory = try makeCompleteModelInstall("vision-ready")+ defer { try? FileManager.default.removeItem(at: directory) }+ let companion = directory.deletingLastPathComponent()+ .appendingPathComponent(+ directory.deletingPathExtension().lastPathComponent + ".vision.gturbo")+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(),+ visionInstaller: MockVisionPackInstallerClient(+ events: [.readyToActivate(companion)]))++ model.installVisionPack()+ try await waitUntil {+ model.visionInstallState == .readyToActivate(companion)+ }++ #expect(!model.isVisionPackInstalled)+ #expect(!model.canInstallVisionPack)+ #expect(model.canActivateVisionPack)+ #expect(model.canLoadModel)+ }++ @MainActor+ @Test func busyVisionActivationRemainsReadyWithoutRedownload() async throws {+ let fixture = try makePreparedVisionAppFixture("vision-activation-busy")+ defer { fixture.remove() }+ let model = AppModel(+ modelDirectory: fixture.text,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(),+ visionInstaller: MockVisionPackInstallerClient(+ preparedValid: true,+ activationError: .installBusy(path: fixture.output.path)))++ #expect(model.canActivateVisionPack)+ model.activateVisionPack()+ try await waitUntil {+ if case .readyToActivate = model.visionInstallState { return true }+ return false+ }+ #expect(model.canActivateVisionPack)+ }++ @MainActor+ @Test func corruptVisionActivationBecomesRecoverable() async throws {+ let fixture = try makePreparedVisionAppFixture("vision-activation-corrupt")+ defer { fixture.remove() }+ let model = AppModel(+ modelDirectory: fixture.text,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(),+ visionInstaller: MockVisionPackInstallerClient(+ preparedValid: true,+ activationError: .configurationInvalid(detail: "weights hash mismatch")))++ model.activateVisionPack()+ try await waitUntil {+ if case .recoverable = model.visionInstallState { return true }+ return false+ }+ #expect(model.canInstallVisionPack)+ }++ @MainActor+ @Test func loadedModelAllowsVisionPayloadDownload() throws {+ let directory = try makeCompleteModelInstall("vision-loaded-prepare")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(),+ visionInstaller: MockVisionPackInstallerClient(holdOpen: true))+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 0.5)++ #expect(!model.canBeginVisionCompanionOperation)+ #expect(model.canInstallVisionPack)+ model.installVisionPack()+ #expect(model.visionInstallState != .idle)+ }++ @MainActor+ @Test func loadedModelBlocksVisionActivationAndDiscard() throws {+ let fixture = try makePreparedVisionAppFixture("vision-loaded-activate")+ defer { fixture.remove() }+ let model = AppModel(+ modelDirectory: fixture.text,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(),+ visionInstaller: MockVisionPackInstallerClient(preparedValid: true))+ model.loadState = .ready(modelDirectory: fixture.text, loadSeconds: 0.5)++ #expect(!model.canActivateVisionPack)+ #expect(!model.canDiscardVisionPackDownload)+ model.activateVisionPack()+ guard case .readyToActivate = model.visionInstallState else {+ Issue.record("blocked activation left \(model.visionInstallState)")+ return+ }++ model.loadState = .notLoaded+ #expect(model.canActivateVisionPack)+ #expect(model.canDiscardVisionPackDownload)+ }++ @MainActor+ @Test func visionPayloadDownloadKeepsTextRuntimeAvailableAndDraftIntact() async throws {+ let directory = try makeCompleteModelInstall("vision-blocking")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(),+ visionInstaller: MockVisionPackInstallerClient(+ events: [.copyingPayload(+ reusedBytes: 4,+ downloadedThisRunBytes: 6,+ totalBytes: 20)],+ holdOpen: true))+ model.promptText = "describe this"+ model.outputText = "earlier answer"+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 0.5)++ model.installVisionPack()+ try await waitUntil { model.isVisionCompanionOperationInProgress }++ #expect(model.canUnloadModel)+ #expect(!model.canInstallModel)+ #expect(model.canRun)+ #expect(!model.canInstallVisionPack)++ model.cancelVisionInstall()+ try await waitUntil { model.visionInstallState == .cancelled }++ #expect(model.promptText == "describe this")+ #expect(model.outputText == "earlier answer")+ #expect(model.canUnloadModel)+ #expect(model.canInstallVisionPack)}@MainActordiff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swiftindex d039efd3..51655fc3 100644--- a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swift+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swift@@ -3,6 +3,24 @@ import Testing@testable import TurboFieldfareAppCore@Suite struct AppModelInstallationProbeTests {+ @Test func storageMetricsUseMetadataAndExcludeSymlinks() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("storage-metrics-\(UUID())", isDirectory: true)+ let nested = root.appendingPathComponent("nested", isDirectory: true)+ try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ try Data("abc".utf8).write(to: root.appendingPathComponent("a"))+ try Data("12345".utf8).write(to: nested.appendingPathComponent("b"))+ try FileManager.default.createSymbolicLink(+ at: root.appendingPathComponent("alias"),+ withDestinationURL: nested.appendingPathComponent("b"))++ let metrics = try AppModelStorageMetrics.measure(at: root)+ #expect(metrics.logicalBytes == 8)+ #expect(metrics.allocatedBytes >= metrics.logicalBytes)+ #expect(metrics.availableBytes != nil)+ }+@Test func missingDirectoryIsMissing() {let url = FileManager.default.temporaryDirectory.appendingPathComponent("turbofieldfare-missing-\(UUID().uuidString).gturbo")@@ -27,6 +45,14 @@ import Testing#expect(AppModelInstallationProbe.status(at: url) == .complete)}+ @Test func loadFailureFixturePassesProbeButOmitsResidentWeights() throws {+ let output = try makeCompleteModelInstall("load-failure")+ defer { try? FileManager.default.removeItem(at: output) }+ #expect(AppModelInstallationProbe.status(at: output) == .complete)+ #expect(!FileManager.default.fileExists(+ atPath: output.appendingPathComponent("model_weights.bin").path))+ }+@Test func receiptBoundToDifferentPathIsPartial() throws {let url = try makeCompleteModelInstall("wrong-path")defer { try? FileManager.default.removeItem(at: url) }diff --git a/Tests/TurboFieldfareApp/Core/Installation/DownloadETAEstimatorTests.swift b/Tests/TurboFieldfareApp/Core/Installation/DownloadETAEstimatorTests.swiftindex 55331294..bdd6d8a1 100644--- a/Tests/TurboFieldfareApp/Core/Installation/DownloadETAEstimatorTests.swift+++ b/Tests/TurboFieldfareApp/Core/Installation/DownloadETAEstimatorTests.swift@@ -118,4 +118,27 @@ struct DownloadETAEstimatorTests {#expect(DownloadETAFormatter.remainingString(390) == "About 7 min remaining")#expect(DownloadETAFormatter.remainingString(410) == "About 7 min remaining")}++ @Test func longElapsedClockValuesKeepTheEstimateFinite() {+ var estimator = DownloadETAEstimator()+ let mib = UInt64(1024 * 1024)+ let origin = 1_000_000_000_000.0+ _ = estimator.update(+ .init(reusedBytes: 0, downloadedThisRunBytes: 0, totalBytes: 128 * mib),+ timestamp: origin)++ let result = estimator.update(+ .init(reusedBytes: 0, downloadedThisRunBytes: 64 * mib,+ totalBytes: 128 * mib),+ timestamp: origin + 48 * 60 * 60)+ guard case .remaining(let seconds) = result else {+ Issue.record("expected an ETA after a long-running download")+ return+ }++ #expect(seconds.isFinite)+ #expect(seconds == 48 * 60 * 60)+ #expect(DownloadETAFormatter.string(for: result)+ == "More than a day remaining")+ }}diff --git a/Tests/TurboFieldfareApp/Core/State/AppConversationLifecycleTests.swift b/Tests/TurboFieldfareApp/Core/State/AppConversationLifecycleTests.swiftindex 1293b964..688b98b1 100644--- a/Tests/TurboFieldfareApp/Core/State/AppConversationLifecycleTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppConversationLifecycleTests.swift@@ -6,6 +6,26 @@ import Testing/// 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+ @Test func terminationShutdownIsIdempotentAndReleasesAttachments() throws {+ let client = MockLifecycleInferenceClient()+ let attachments = AppImageAttachmentStore(+ directoryURL: FileManager.default.temporaryDirectory+ .appendingPathComponent("shutdown-attachments-\(UUID())", isDirectory: true))+ defer { try? FileManager.default.removeItem(at: attachments.directoryURL) }+ let staged = try attachments.stage(+ data: Data("bounded".utf8), displayName: "attachment.bin")+ let model = AppModel(client: client, attachmentStore: attachments)+ model.setComposerAttachmentsForTesting([staged])++ model.shutdownForTermination()+ model.shutdownForTermination()++ #expect(client.shutdownCount == 1)+ #expect(!FileManager.default.fileExists(atPath: staged.fileURL.path))+ #expect(model.imageAttachments.isEmpty)+ }+@MainActorprivate func readyModel(_ client: FakeInferenceClient) async throws -> AppModel {let directory = FileManager.default.temporaryDirectory@@ -20,7 +40,7 @@ import Testing@MainActorprivate func finish(_ model: AppModel) async {- while model.isRunning { await Task.yield() }+ await SendWaiting.turnEnds(model)}/// The shipping client stops cooperatively: the turn ends at a token@@ -33,8 +53,8 @@ import TestingcancelSemantics: .cooperativeStop)let model = try await readyModel(client)model.promptText = "one"- model.run()- while model.isRunning, model.liveTokenCount == 0 { await Task.yield() }+ model.send()+ while model.isTurnInFlight, model.liveTokenCount == 0 { await Task.yield() }model.cancel()await finish(model)@@ -49,7 +69,7 @@ import Testing// 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()+ model.send()await finish(model)#expect(model.conversation.committedTurns == 2)let reply = try #require(model.conversation.turns.last)@@ -71,14 +91,14 @@ import Testinglet model = try await readyModel(client)model.promptText = "one"- model.run()- while model.isRunning, model.liveTokenCount == 0 { await Task.yield() }+ model.send()+ while model.isTurnInFlight, model.liveTokenCount == 0 { await Task.yield() }model.cancel()await finish(model)#expect(model.diagnostics?.stopReason == .cancelled)model.promptText = "two"- model.run()+ model.send()await finish(model)#expect(model.diagnostics?.stopReason != .cancelled,"the next run inherited the stop")@@ -94,8 +114,8 @@ import TestingcancelSemantics: .hardAbort)let model = try await readyModel(client)model.promptText = "one"- model.run()- while model.isRunning, model.livePrefillDone == 0 { await Task.yield() }+ model.send()+ while model.isTurnInFlight, model.livePrefillDone == 0 { await Task.yield() }model.cancel()await finish(model)@@ -113,14 +133,14 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(1))let model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()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()+ model.send()await finish(model)#expect(model.error != nil, "a lost reset was reported as success")@@ -129,7 +149,7 @@ import Testing// And the next attempt opens it again rather than short-circuiting.model.promptText = "retry"- model.run()+ model.send()await finish(model)#expect(client.conversationEpochs.count == 2,"the reset was never retried, so the conversation could not recover")diff --git a/Tests/TurboFieldfareApp/Core/State/AppGenerationRunIdentityTests.swift b/Tests/TurboFieldfareApp/Core/State/AppGenerationRunIdentityTests.swiftindex 328e27c1..e36a1ce0 100644--- a/Tests/TurboFieldfareApp/Core/State/AppGenerationRunIdentityTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppGenerationRunIdentityTests.swift@@ -35,6 +35,13 @@ private final class RunIdentityInferenceClient: AppModelLifecycleClient, Sendablfunc unload() async {}func resetConversation(epoch: UUID) async throws {}+ func restoreConversation(+ _ lineage: AppConversationLineage,+ epoch: UUID,+ options: AppRuntimeOptions,+ maxContextTokens: Int,+ onPrefillProgress: @escaping @Sendable (Int, Int) -> Void+ ) async throws -> Int { lineage.tokenIDs.count }func cancel() {}func generate(_ request: AppGenerationRequest)@@ -70,11 +77,12 @@ private final class RunIdentityInferenceClient: AppModelLifecycleClient, Sendablmodel.loadState = .ready(modelDirectory: directory, loadSeconds: 0)model.promptText = "first"- model.run()- while model.isRunning { await Task.yield() }+ model.send()+ await SendWaiting.turnEnds(model)model.promptText = "second"- model.run()+ model.send()+ await SendWaiting.generationStarts(model)let secondIdentity = model.runIdentity#expect(model.isRunning)#expect(model.conversation.hasTurnInFlight)@@ -90,6 +98,6 @@ private final class RunIdentityInferenceClient: AppModelLifecycleClient, Sendabl#expect(model.error == nil)await client.secondTerminal.open()- while model.isRunning { await Task.yield() }+ await SendWaiting.turnEnds(model)}}diff --git a/Tests/TurboFieldfareApp/Core/State/AppImageAddConcurrencyTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageAddConcurrencyTests.swiftindex 54f13fd5..5282b24f 100644--- a/Tests/TurboFieldfareApp/Core/State/AppImageAddConcurrencyTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppImageAddConcurrencyTests.swift@@ -22,7 +22,7 @@ import Testinglet model = AppModel(modelDirectory: directory,attachmentStore: AppImageAttachmentStore(directoryURL: staging))- model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.sixtyFourK.tokens)try #require(model.maximumImageAttachments >= 3)let first = try Self.writePNG(named: "first.png", in: staging)@@ -81,7 +81,7 @@ import Testinglet model = AppModel(modelDirectory: directory,attachmentStore: AppImageAttachmentStore(directoryURL: staging))- model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.sixtyFourK.tokens)try #require(model.maximumImageAttachments >= 2)let file = try Self.writePNG(named: "from-disk.png", in: staging)diff --git a/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swiftindex a819b1c3..c3396ce8 100644--- a/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift@@ -123,7 +123,8 @@ import TurboFieldfare#expect(model.imageAttachments.count == 1)model.promptText = "describe it"model.maxNewTokensOverride = 1- model.run()+ model.send()+ await SendWaiting.generationStarts(model)#expect(model.promptText.isEmpty)#expect(model.imageAttachments.isEmpty,@@ -133,9 +134,7 @@ import TurboFieldfarelet shown = try #require(model.outputImageAttachments.first)#expect(try Data(contentsOf: shown.fileURL) == Data("fixture".utf8))- for _ in 0..<200 where model.isRunning {- try? await Task.sleep(nanoseconds: 5_000_000)- }+ await SendWaiting.turnEnds(model)// Clearing the transcript is what finally frees them.model.newChat()#expect(model.outputImageAttachments.isEmpty)@@ -164,11 +163,9 @@ import TurboFieldfareawait attach(model, [source])model.promptText = "describe it"model.maxNewTokensOverride = 1- model.run()+ model.send()- for _ in 0..<400 where model.isRunning {- try? await Task.sleep(nanoseconds: 5_000_000)- }+ await SendWaiting.turnEnds(model)#expect(model.error == nil,"the run could not open the images the composer had just deleted")#expect(!model.outputText.isEmpty, "the run produced nothing")@@ -199,7 +196,8 @@ import TurboFieldfaretry Data().write(to: store.directoryURL.appendingPathComponent("retained", isDirectory: false))- model.run()+ model.send()+ await SendWaiting.turnEnds(model)#expect(!model.isRunning, "the run started without stable references")#expect(model.error != nil, "the refusal was silent")@@ -229,7 +227,8 @@ import TurboFieldfareattachmentStore: store)model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)model.promptText = "hello"- model.run()+ model.send()+ await SendWaiting.generationStarts(model)#expect(model.isRunning)let promises = root.appendingPathComponent("promises", isDirectory: true)@@ -329,10 +328,8 @@ import TurboFieldfareawait attach(model, [source])model.promptText = "describe it"model.maxNewTokensOverride = 1- model.run()- for _ in 0..<200 where model.isRunning {- try? await Task.sleep(nanoseconds: 5_000_000)- }+ model.send()+ await SendWaiting.turnEnds(model)#expect(model.imageAttachments.isEmpty)#expect(model.outputImageAttachments.count == 1)@@ -361,10 +358,8 @@ import TurboFieldfarefor 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)- }+ model.send()+ await SendWaiting.turnEnds(model)}#expect(model.conversation.turns.compactMap { $0.images.first }.count == 2,"the fixture needs two turns each holding an image")@@ -374,6 +369,38 @@ import TurboFieldfare"New chat left an earlier turn's staged image behind")}+ /// A short two-turn check cannot expose accumulation that grows by one+ /// conversation. This stages one image for each of 40 turns and verifies+ /// every completed chat releases all of its hard links before the next one.+ @MainActor+ @Test func twentyChatsWithFortyImageTurnsKeepStagingBounded() async throws {+ let (root, store) = makeStore()+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = try makeVisionReadyModelInstall("lifetime-soak")+ 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 chat in 0..<20 {+ for turn in 0..<2 {+ let source = try writeSource(+ root, "chat-\(chat)-turn-\(turn).png", "image \(chat) \(turn)")+ await attach(model, [source])+ model.promptText = "describe image \(chat)-\(turn)"+ model.send()+ await SendWaiting.turnEnds(model)+ }+ #expect(stagedFileCount(store) == 2,+ "chat \(chat) did not own exactly its two transcript images")+ model.newChat()+ #expect(stagedFileCount(store) == 0,+ "chat \(chat) left staged images after New chat")+ }+ }+/// Quitting is the one moment every staged file is certainly unwanted, and/// nothing called `removeAll()` at all.@MainActor@@ -480,7 +507,7 @@ import TurboFieldfarelet model = AppModel(modelDirectory: directory, attachmentStore: store)// The smallest context the app offers, so the cap is reached without// staging dozens of files.- model.maxContextTokens = AppContextLengthOption.fourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.fourK.tokens)let capacity = model.maximumImageAttachmentsfor index in 0..<(capacity + 1) {@@ -572,4 +599,57 @@ import TurboFieldfare.isImageInputAvailable,"an installed pack exposed image input on unsupported hardware")}++ /// The pack is external mutable state. Losing it after an image was staged+ /// must preserve that draft, close Generate, and identify the exact path;+ /// restoring the same pack should reopen the draft without reattachment.+ @MainActor+ @Test func aDisappearingCompanionPreservesTheDraftAndRecoversInPlace() async throws {+ let directory = try makeVisionReadyModelInstall("availability-disappears")+ defer { try? FileManager.default.removeItem(at: directory) }+ let companion = try VisionPackLocation.companionURL(forTextModel: directory)+ let removed = companion.appendingPathExtension("removed")+ defer {+ if FileManager.default.fileExists(atPath: removed.path),+ !FileManager.default.fileExists(atPath: companion.path) {+ try? FileManager.default.moveItem(at: removed, to: companion)+ }+ }++ let model = AppModel(modelDirectory: directory)+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ model.promptText = "describe it"+ withVisionEnabled {+ model.addImageData(Data("bounded image".utf8), displayName: "image.png")+ }+ let deadline = Date().addingTimeInterval(5)+ while model.isAddingImages, Date() < deadline {+ try await Task.sleep(nanoseconds: 5_000_000)+ }+ #expect(model.imageAttachments.count == 1)+ #expect(model.canRun)++ try FileManager.default.moveItem(at: companion, to: removed)+ model.recheckVisionPackAtCurrentLocation()++ #expect(model.imageAttachments.count == 1,+ "losing the pack deleted the user's staged image")+ #expect(!model.isImageInputAvailable)+ #expect(!model.canRun, "Generate stayed enabled without the companion")+ let diagnostic = try #require(model.imageAttachmentError)+ #expect(diagnostic.contains(companion.path))+ #expect(diagnostic.contains("missing"))++ withVisionEnabled {+ model.addImageData(Data("second".utf8), displayName: "second.png")+ }+ #expect(model.imageAttachments.count == 1,+ "another image was admitted while the pack was missing")++ try FileManager.default.moveItem(at: removed, to: companion)+ model.recheckVisionPackAtCurrentLocation()+ #expect(model.imageAttachmentError == nil)+ #expect(model.imageAttachments.count == 1)+ #expect(model.canRun, "restoring the pack did not recover the draft")+ }}diff --git a/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swiftindex a2c18067..b0713fd3 100644--- a/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift@@ -14,23 +14,51 @@ import TurboFieldfarelet directory = try makeVisionReadyModelInstall("capacity-\(option.tokens)")defer { try? FileManager.default.removeItem(at: directory) }let model = AppModel(modelDirectory: directory)- model.maxContextTokens = option.tokens+ model.setMaxContextTokens(option.tokens)let expected = VisionImageTokenBudget.capacity(maxContext: option.tokens,- reservedTextTokens: AppModel.reservedPromptTokens)+ reservedTextTokens: AppModel.reservedPromptTokens+ + ConversationGenerationReserve.tokens)#expect(model.maximumImageAttachments == expected)}@Test func capacityReachesZeroAtTheConversationBoundary() {let context = AppContextLengthOption.fourK.tokenslet imageCost = VisionImageTokenBudget.maximumTokensPerImage+ let reserve = ConversationGenerationReserve.tokens#expect(AppModel.imageAttachmentCapacity(maxContextTokens: context,- conversationTokens: context - imageCost) == 1)+ conversationTokens: context - imageCost - reserve) == 1)#expect(AppModel.imageAttachmentCapacity(maxContextTokens: context,- conversationTokens: context - imageCost + 1) == 0)+ conversationTokens: context - imageCost - reserve + 1) == 0)+ }++ /// What the composer offers, `generate` accepts: the images, the text+ /// they sit behind and the reply's reserve all fit the context. Without+ /// the reserve the composer offered sets the runtime refused after every+ /// image had been encoded.+ @Test func whatTheComposerOffersLeavesTheReplyItsReserve() {+ let imageCost = VisionImageTokenBudget.maximumTokensPerImage+ for context in AppContextLengthOption.allCases.map(\.tokens) {+ for held in stride(from: 0, through: context, by: 97) {+ let capacity: Int = AppModel.imageAttachmentCapacity(+ maxContextTokens: context, conversationTokens: held)+ let text: Int = max(AppModel.reservedPromptTokens, held)+ guard ConversationGenerationReserve.fits(tokens: text, maxContext: context) else {+ // The text alone leaves no room to reply; no image may be+ // offered on top of it.+ #expect(capacity == 0, "\(capacity) images offered at \(held) held tokens of \(context)")+ continue+ }+ let images: Int = capacity * imageCost+ let prompt: Int = text + images+ #expect(ConversationGenerationReserve.fits(+ tokens: prompt, maxContext: context),+ "\(capacity) images at \(held) held tokens do not fit \(context)")+ }+ }}@Test func unknownConversationPositionHasNoImageCapacity() {@@ -45,9 +73,9 @@ import TurboFieldfaredefer { try? FileManager.default.removeItem(at: directory) }let model = AppModel(modelDirectory: directory)- model.maxContextTokens = AppContextLengthOption.fourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.fourK.tokens)let small = model.maximumImageAttachments- model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.sixtyFourK.tokens)let large = model.maximumImageAttachments#expect(large > small,"raising the context did not raise the image capacity")@@ -62,10 +90,10 @@ import TurboFieldfarelet directory = try makeVisionReadyModelInstall("capacity-agreement")defer { try? FileManager.default.removeItem(at: directory) }let model = AppModel(modelDirectory: directory)- model.maxContextTokens = AppContextLengthOption.eightK.tokens+ model.setMaxContextTokens(AppContextLengthOption.eightK.tokens)let attachments = (0..<model.maximumImageAttachments).map { index in- AppImageAttachment(+ StagedImage(fileURL: URL(fileURLWithPath: "/tmp/image-\(index).png"),displayName: "image-\(index).png",encodedBytes: 1,@@ -89,7 +117,7 @@ import TurboFieldfarelet capacity = VisionImageTokenBudget.capacity(maxContext: context, reservedTextTokens: 0)let attachments = (0...capacity).map { index in- AppImageAttachment(+ StagedImage(fileURL: URL(fileURLWithPath: "/tmp/image-\(index).png"),displayName: "image-\(index).png",encodedBytes: 1,@@ -119,7 +147,7 @@ import TurboFieldfarelet store = AppImageAttachmentStore(directoryURL: root.appendingPathComponent("staged", isDirectory: true))let model = AppModel(modelDirectory: directory, attachmentStore: store)- model.maxContextTokens = AppContextLengthOption.fourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.fourK.tokens)let capacity = model.maximumImageAttachmentsvar urls: [URL] = []@@ -156,7 +184,7 @@ import TurboFieldfaredefer { try? FileManager.default.removeItem(at: directory) }let model = AppModel(modelDirectory: directory,client: MockLifecycleInferenceClient())- model.maxContextTokens = AppContextLengthOption.fourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.fourK.tokens)model.loadModel()let deadline = Date().addingTimeInterval(60)while !model.loadState.isReady, Date() < deadline {@@ -167,7 +195,7 @@ import TurboFieldfare// Raising the setting without reloading must not raise what the// composer accepts, or it accepts images the request then refuses.- model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.sixtyFourK.tokens)#expect(model.maximumImageAttachments == loadedCapacity,"the composer offered capacity the loaded session cannot serve")#expect(model.effectiveMaxContextTokens@@ -199,7 +227,7 @@ import TurboFieldfareelse { unsetenv("TURBO_FIELDFARE_VISION_RUNTIME") }}model.addImages([source])- var deadline = Date().addingTimeInterval(60)+ let deadline = Date().addingTimeInterval(60)while model.isAddingImages, Date() < deadline {try? await Task.sleep(nanoseconds: 5_000_000)}@@ -216,11 +244,13 @@ import TurboFieldfare#expect(model.imageAttachments.count == 1,"a refresh during a companion operation deleted staged images")- // Once the operation ends and support really is gone, they go: an- // attachment nothing can encode is worse than none.+ // Once the operation ends and support really is gone, the draft still+ // belongs to the user. Generate closes until the same companion is+ // restored, but a transient external rename must not destroy input.model.visionInstallState = .idlemodel.refreshVisionInstallReadiness()- #expect(model.imageAttachments.isEmpty)+ #expect(model.imageAttachments.count == 1)+ #expect(!model.canRun)model.releaseAllAttachments()}}diff --git a/Tests/TurboFieldfareApp/Core/State/AppLiveMemoryDuringPrefillTests.swift b/Tests/TurboFieldfareApp/Core/State/AppLiveMemoryDuringPrefillTests.swiftnew file mode 100644index 00000000..30affdac--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppLiveMemoryDuringPrefillTests.swift@@ -0,0 +1,413 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore+import TurboFieldfareDecodeProtocol++/// Prefill is the long phase for a large prompt or an image, and it is exactly+/// when someone watches the memory figure. It was sampled only when a token+/// arrived, so it stayed blank for the entire wait.+private final class PrefillOnlyClient: AppInferenceClient, AppInferenceMemoryReporting,+ @unchecked Sendable {+ private let lock = NSLock()+ private var memory: UInt64?++ var currentInferenceMemoryBytes: UInt64? {+ lock.lock(); defer { lock.unlock() }+ return memory+ }++ var currentInferenceResidentBytes: UInt64? {+ lock.lock(); defer { lock.unlock() }+ return memory.map { $0 + 1_144_373_248 }+ }++ /// The tower the process is holding, which is the only figure that moves+ /// between the two residency policies.+ var currentInferenceTowerBytes: UInt64? {+ lock.lock(); defer { lock.unlock() }+ return tower+ }++ private var tower: UInt64?++ func reportTower(_ bytes: UInt64?) {+ lock.lock(); defer { lock.unlock() }+ tower = bytes+ }++ /// Stands in for the decode service reporting memory alongside progress.+ func reportMemory(_ bytes: UInt64) {+ lock.lock(); defer { lock.unlock() }+ memory = bytes+ }++ func generate(_ request: AppGenerationRequest)+ -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream(AppInferenceEvent.self) { continuation in+ Task { [self] in+ for step in 1...3 {+ reportMemory(UInt64(step) * 1_000_000_000)+ continuation.yield(.prefillProgress(done: step, total: 3))+ try? await Task.sleep(for: .milliseconds(10))+ }+ continuation.yield(.finished(AppDiagnostics(+ generatedTokens: 0, stopReason: .eos,+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 0, tokensPerSecond: 0,+ peakMemoryBytes: currentInferenceMemoryBytes,+ runtimeOptions: request.runtimeOptions)))+ continuation.finish()+ }+ }+ }++ func cancel() {}+}++@Suite struct AppLiveMemoryDuringPrefillTests {+ @MainActor+ @Test func memoryIsReportedBeforeTheFirstToken() async throws {+ let client = PrefillOnlyClient()+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(client: client)+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ model.promptText = "describe this"+ model.send()++ let deadline = Date().addingTimeInterval(60)+ while model.liveMemoryBytes == nil,+ model.isTurnInFlight || model.phase == .prefill,+ Date() < deadline {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ #expect(model.liveMemoryBytes != nil,+ "memory stayed blank through prefill")+ #expect(model.liveMemoryBytes ?? 0 > 0)+ }++ /// What the HUD reads is what matters. It used to consult the client+ /// directly, which is invisible to observation, so the figure only+ /// refreshed when a generated token happened to redraw the view — never+ /// during prefill.+ @MainActor+ @Test func thedisplayedFigureMovesDuringPrefill() async throws {+ let client = PrefillOnlyClient()+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(client: client)+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)++ // Driven event by event rather than by polling a live run. Sampling a+ // background run at intervals is a race the test loses under load: the+ // three prefill events can all land between two samples, and the test+ // then reports the bug it is meant to catch. The property is that each+ // prefill event moves what the HUD reads, which is exactly this.+ var seen: [UInt64] = []+ for step in 1...3 {+ client.reportMemory(UInt64(step) * 1_000_000_000)+ model.apply(.prefillProgress(done: step, total: 3))+ seen.append(try #require(model.currentProcessMemoryBytes))+ }++ #expect(seen == [1_000_000_000, 2_000_000_000, 3_000_000_000],+ "the displayed memory did not follow prefill: \(seen)")+ #expect(model.liveTokenCount == 0,+ "this run must not reach decode, or it proves nothing")+ }++ /// The same for a service that has nothing else to say. Image encoding+ /// produces no progress and no tokens for seconds at a time, and the figure+ /// used to sit at its pre-run value for the whole of it.+ @MainActor+ @Test func thedisplayedFigureMovesWithNoProgressAtAll() async throws {+ let client = PrefillOnlyClient()+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(client: client)+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)++ // A first reading through the ordinary path, so the model holds a figure+ // of its own. Without it the display falls back to asking the client+ // directly and the test passes whatever the model does — which is how+ // the first version of this test managed to prove nothing.+ client.reportMemory(1_500_000_000)+ model.apply(.prefillProgress(done: 1, total: 2))+ #expect(model.liveMemoryBytes == 1_500_000_000)++ // Now the silent window: the service reports more memory and sends+ // nothing else, exactly as it does while encoding an image.+ client.reportMemory(2_100_000_000)+ model.apply(.memorySample)+ #expect(model.liveMemoryBytes == 2_100_000_000,+ "the held figure went stale through a silent phase")+ #expect(model.currentProcessMemoryBytes == 2_100_000_000,+ "a memory-only reading did not reach the display")+ #expect(model.livePrefillTotal == 2,+ "a memory reading moved the prefill counters")++ // And the display reads the tracked property, not the client. A figure+ // the client knows but the model has not observed cannot redraw the+ // view, so showing it would put a number on screen that only changes+ // when something else happens to trigger a redraw.+ client.reportMemory(9_000_000_000)+ #expect(model.currentProcessMemoryBytes == 2_100_000_000,+ "the display reached past the observed value into the client")+ }++ /// All three figures move together, and each answers a different question:+ /// what the process is charged, what is actually in RAM, and what the image+ /// tower is holding. Showing only the first is what made a 26B model read+ /// 2.26 GB and look impossible.+ @MainActor+ @Test func allThreeMemoryFiguresFollowARun() async throws {+ let client = PrefillOnlyClient()+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(client: client)+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)++ client.reportMemory(2_260_000_000)+ client.reportTower(1_144_373_248)+ model.apply(.memorySample)++ #expect(model.currentProcessMemoryBytes == 2_260_000_000)+ #expect(model.currentProcessResidentBytes == 2_260_000_000 + 1_144_373_248,+ "the in-RAM figure did not include the mapped pages")+ #expect(model.visionTowerMappedBytes == 1_144_373_248,+ "the tower figure did not reach the model during the run")++ // Load On Demand releases after each image, and that has to show.+ client.reportTower(0)+ model.apply(.memorySample)+ #expect(model.visionTowerMappedBytes == 0,+ "a released tower still reported as held")+ }++ /// An event that carries no memory reading says nothing about memory, and+ /// must not blank out the last one.+ @Test func anEventWithoutAReadingKeepsTheLastOne() async throws {+ let pipe = Pipe()+ let id = UUID()+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .prefill, generationID: id,+ prefillDone: 1, prefillTotal: 2,+ currentMemoryBytes: 4_000_000_000)))+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .prefill, generationID: id,+ prefillDone: 2, prefillTotal: 2)))+ try pipe.fileHandleForWriting.close()++ // The decoded events are what the client applies; assert the rule the+ // client follows rather than reaching through a live connection.+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)+ var reported: UInt64?+ for _ in 0..<2 {+ let event = try await router.next(matching: id, timeout: .seconds(5))+ if let bytes = event.currentMemoryBytes { reported = bytes }+ }+ #expect(reported == 4_000_000_000,+ "a reading-free event erased the last known figure")+ try? pipe.fileHandleForReading.close()+ }+}++/// With several images attached, the prompt and its thumbnails are tall enough+/// to push the answer out of view, so the transcript has to put the newest turn+/// on screen when a run starts rather than only when the reader is already at+/// the bottom.+@Suite struct AppRunIdentityTests {+ @MainActor+ @Test func eachRunGetsANewIdentity() async throws {+ let client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(client: client)+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ model.maxNewTokensOverride = 1++ let before = model.runIdentity+ model.promptText = "first"+ model.send()+ await SendWaiting.generationStarts(model)+ let afterFirst = model.runIdentity+ #expect(afterFirst != before, "starting a run did not change its identity")++ await SendWaiting.turnEnds(model)+ model.promptText = "second"+ model.send()+ await SendWaiting.generationStarts(model)+ #expect(model.runIdentity != afterFirst,+ "a second run reused the first run's identity")+ }++ /// A refused run must not claim a new turn: nothing was added to scroll to.+ @MainActor+ @Test func arefusedRunKeepsTheIdentity() throws {+ let model = AppModel(client: MockInferenceClient())+ model.loadState = .notLoaded+ model.promptText = "go"+ let before = model.runIdentity+ model.send()+ #expect(model.runIdentity == before)+ }+}++/// Loading takes minutes and holds gigabytes, so it stays opt-in — but when it+/// is opted into, launching must actually start it.+@Suite struct AppLaunchLoadTests {+ @MainActor+ @Test func launchDoesNotLoadByDefault() throws {+ let directory = try makeCompleteModelInstall("launch-default")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(modelDirectory: directory,+ client: MockLifecycleInferenceClient())+ #expect(!model.loadModelOnLaunch)++ model.loadModelAtLaunchIfEnabled()+ #expect(model.loadState == .notLoaded,+ "launch started a load nobody asked for")+ }++ @MainActor+ @Test func launchLoadsWhenTheSettingIsOn() async throws {+ let directory = try makeCompleteModelInstall("launch-on")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(modelDirectory: directory,+ client: MockLifecycleInferenceClient())+ model.setLoadModelOnLaunch(true)+ #expect(model.loadModelOnLaunch)++ model.loadModelAtLaunchIfEnabled()+ let deadline = Date().addingTimeInterval(60)+ while !model.loadState.isReady, Date() < deadline {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ #expect(model.loadState.isReady, "the launch load never ran")+ }++ /// A model that is not installed must not be loaded at launch, and the+ /// attempt must not leave an error on screen at startup.+ @MainActor+ @Test func launchLeavesAnUninstalledModelAlone() throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("missing-\(UUID().uuidString).gturbo")+ let model = AppModel(modelDirectory: directory,+ client: MockLifecycleInferenceClient())+ model.setLoadModelOnLaunch(true)+ model.loadModelAtLaunchIfEnabled()+ #expect(model.loadState == .notLoaded)+ #expect(model.error == nil)+ }++ @MainActor+ @Test func thesettingSurvivesRelaunch() throws {+ let directory = try makeCompleteModelInstall("launch-persist")+ defer { try? FileManager.default.removeItem(at: directory) }+ var settings = MacAppSettings()+ settings.loadModelOnLaunch = true+ let encoded = try JSONEncoder().encode(settings)+ let decoded = try JSONDecoder().decode(MacAppSettings.self, from: encoded)+ #expect(decoded.loadModelOnLaunch)++ // Settings written before this existed simply have it off.+ var object = try #require(+ try JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ object.removeValue(forKey: "loadModelOnLaunch")+ let older = try JSONSerialization.data(withJSONObject: object)+ #expect(!(try JSONDecoder().decode(MacAppSettings.self, from: older))+ .loadModelOnLaunch)+ }+}++/// Changing a runtime setting and pressing Generate without reloading was+/// refused outright: the request carried the new options while the session was+/// loaded with the old ones, and the service compares them. The settings still+/// apply on reload — they just no longer break the run in the meantime.+@Suite struct AppPendingSettingsRunTests {+ @MainActor+ private func readyModel() throws -> (AppModel, URL) {+ let directory = try makeCompleteModelInstall("pending-settings")+ let model = AppModel(modelDirectory: directory,+ client: MockLifecycleInferenceClient())+ return (model, directory)+ }++ @MainActor+ @Test func arunUsesTheLoadedSessionsOptionsNotThePendingOnes() async throws {+ let (model, directory) = try readyModel()+ defer { try? FileManager.default.removeItem(at: directory) }+ model.runtimeOptions.visionResidencyPolicy = .onDemand+ model.setMaxContextTokens(AppContextLengthOption.fourK.tokens)+ model.loadModel()+ let deadline = Date().addingTimeInterval(60)+ while !model.loadState.isReady, Date() < deadline {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ try #require(model.loadState.isReady)++ // The user changes settings and presses Generate without reloading.+ model.setMaxContextTokens(AppContextLengthOption.sixteenK.tokens)+ model.promptText = "go"+ #expect(model.hasStaleLoadedRuntime, "the reload prompt should be showing")++ let request = try model.makeRequest()+ #expect(request.maxContextTokens == AppContextLengthOption.fourK.tokens,+ "the run carried a context the loaded session does not have")+ }++ /// With nothing loaded there is no session to match, so the request simply+ /// carries the current settings.+ @MainActor+ @Test func withoutALoadedSessionTheCurrentSettingsAreUsed() throws {+ let (model, directory) = try readyModel()+ defer { try? FileManager.default.removeItem(at: directory) }+ model.setMaxContextTokens(AppContextLengthOption.sixteenK.tokens)+ model.promptText = "go"+ let request = try model.makeRequest()+ #expect(request.maxContextTokens == AppContextLengthOption.sixteenK.tokens)+ }+}++/// When inference runs in another process, its memory is the only memory worth+/// showing. The UI's own footprint must never appear in a row labelled as the+/// model's.+private final class SilentReporterClient: AppInferenceClient,+ AppInferenceMemoryReporting, @unchecked Sendable {+ var currentInferenceMemoryBytes: UInt64? { nil }+ var currentInferenceResidentBytes: UInt64? { nil }++ func generate(_ request: AppGenerationRequest)+ -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream(AppInferenceEvent.self) { $0.finish() }+ }++ func cancel() {}+}++@Suite struct AppInferenceOnlyMemoryTests {+ @MainActor+ @Test func anUnreportingServiceShowsNothingRatherThanTheAppsOwnMemory() throws {+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(client: SilentReporterClient())+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)++ #expect(model.currentProcessMemoryBytes == nil,+ "the app's own footprint was shown as the model's")+ #expect(model.currentProcessResidentBytes == nil)+ }++ /// With in-process inference the app *is* the inference process, so its own+ /// figure is the right one.+ @MainActor+ @Test func inProcessInferenceReportsThisProcess() throws {+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(client: MockInferenceClient())+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)++ #expect((model.currentProcessMemoryBytes ?? 0) > 0)+ #expect((model.currentProcessResidentBytes ?? 0) > 0)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swiftindex 778fa995..a4390dc1 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelConversationTests.swift@@ -23,7 +23,7 @@ import Testing@MainActorprivate func finish(_ model: AppModel) async {- while model.isRunning { await Task.yield() }+ await SendWaiting.turnEnds(model)}@MainActor@@ -47,7 +47,8 @@ import Testinglet model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()+ await SendWaiting.generationStarts(model)let firstEpoch = model.conversation.epoch#expect(model.conversation.turns.first?.role == .user,"the user's message shows while the model is still thinking")@@ -55,7 +56,7 @@ import Testing#expect(model.conversation.committedTurns == 1)model.promptText = "two"- model.run()+ model.send()await finish(model)#expect(model.conversation.committedTurns == 2)#expect(model.conversation.epoch == firstEpoch,@@ -69,10 +70,10 @@ import Testinglet model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()await finish(model)model.promptText = "two"- model.run()+ model.send()await finish(model)// Opening it again per turn would reset the KV and undo the entire@@ -85,7 +86,7 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(1))let model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()await finish(model)let firstEpoch = model.conversation.epoch@@ -95,7 +96,7 @@ import Testing#expect(model.conversation.epoch != firstEpoch)model.promptText = "fresh"- model.run()+ model.send()await finish(model)#expect(client.conversationEpochs.count == 2)#expect(client.conversationEpochs.last == model.conversation.epoch)@@ -111,10 +112,10 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(1))let model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()await finish(model)model.promptText = "two"- model.run()+ model.send()await finish(model)#expect(model.conversation.committedTurns == 2)let before = model.conversation.epoch@@ -128,11 +129,11 @@ import Testing// 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.conversation.outOfContextPairs.count == 2)#expect(model.transcriptContextBreak == 2)model.promptText = "after reload"- model.run()+ model.send()await finish(model)#expect(model.conversation.committedTurns == 1)#expect(client.conversationEpochs.last == model.conversation.epoch)@@ -150,10 +151,10 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(1))let model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()await finish(model)model.promptText = "two"- model.run()+ model.send()await finish(model)#expect(model.conversation.committedTurns == 2)let before = model.conversation.epoch@@ -166,7 +167,7 @@ import Testing#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.conversation.outOfContextPairs.count == 2)#expect(model.transcriptContextBreak == 2)}@@ -175,7 +176,7 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(1))let model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()await finish(model)#expect(client.conversationEpochs.count == 1)@@ -187,7 +188,7 @@ import TestingmodelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1))model.promptText = "two"- model.run()+ model.send()await finish(model)#expect(client.conversationEpochs.count == 2,"the turn after a load has to open the conversation again")@@ -201,14 +202,14 @@ import Testinglet model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()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()+ model.send()await finish(model)#expect(model.conversation.completedPairs.count == 2)#expect(model.transcriptHistory.count == 1)@@ -220,10 +221,10 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(1))let model = try await readyModel(client)model.promptText = "first question"- model.run()+ model.send()await finish(model)model.promptText = "second question"- model.run()+ model.send()await finish(model)let text = model.outputConversationPlainText@@ -239,10 +240,10 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(1))let model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()await finish(model)model.promptText = "two"- model.run()+ model.send()await finish(model)#expect(!model.transcriptHistory.isEmpty)@@ -262,15 +263,19 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(60))let model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()await finish(model)#expect(model.conversation.committedTurns == 1)model.promptText = "two"- model.run()+ model.send()// 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() }+ // tick races the double's own task registration, not the product — and+ // the gauge still holds the previous turn's figures until the send+ // reaches the stage that resets them, so waiting on the gauge alone+ // returned before this turn had started at all.+ await SendWaiting.generationStarts(model)+ while model.isTurnInFlight, model.livePrefillDone == 0 { await Task.yield() }model.cancel()await finish(model)@@ -297,14 +302,14 @@ import Testinglet client = FakeInferenceClient(eventDelay: .milliseconds(1))let model = try await readyModel(client)model.promptText = "one"- model.run()+ model.send()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.setMaxContextTokens(model.maxContextTokens * 2)model.promptText = "two"- model.run()+ model.send()await finish(model)#expect(model.conversation.committedTurns == 1)diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelHistorySequenceTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelHistorySequenceTests.swiftnew file mode 100644index 00000000..c064a512--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppModelHistorySequenceTests.swift@@ -0,0 +1,270 @@+import Foundation+import Testing+import TurboFieldfare+import TurboFieldfareValidationSupport+@testable import TurboFieldfareAppCore++/// Sequences, not steps.+///+/// Every defect this feature shipped needed three or four operations in a row —+/// delete the chat the KV is holding and send again, read one chat then another+/// then the first, send two pictures and reopen — and every test written+/// afterwards is one of those sequences, written once the defect was known.+/// This suite writes them down as fixed cases and then generates the ones+/// nobody has thought of yet, checking the same seven invariants after every+/// operation.+///+/// Serialized: each case drives an `AppModel` on the main actor and waits for+/// its tasks to finish, and cases competing for that actor turn a settle+/// deadline into a flake rather than a finding.+@Suite(.serialized) struct AppModelHistorySequenceTests {+ // MARK: - The defects that reached the user++ /// C23. Deleting the chat the KV is holding used to keep the conversation+ /// and let the next turn open a fresh file, whose meta then described+ /// everything behind it: a row reading 1,065 tokens over 22 tokens of+ /// record.+ @MainActor+ @Test func deletingTheHeldChatDoesNotCarryItsCountsIntoTheNextOne() async throws {+ let harness = try await HistoryHarness(label: "c23")+ defer { harness.tearDown() }++ try await harness.apply(.send(label: 1))+ try await harness.apply(.delete(row: 0))+ try await harness.apply(.send(label: 2))+ }++ /// The duplicated transcript. Opening a chat left part of the previous one+ /// on screen, so two conversations were drawn at once — the stored pairs+ /// were the one list not cleared, and the branch for a chat that could not+ /// be continued cleared nothing at all.+ @MainActor+ @Test func openingAChatDrawsThatChatAndNothingElse() async throws {+ let harness = try await HistoryHarness(label: "duplicate")+ defer { harness.tearDown() }++ // One long exchange, so this chat stops fitting when the context drops.+ try await harness.apply(.sendLong(label: 1))+ try await harness.apply(.newChat)+ try await harness.apply(.send(label: 2))+ try await harness.apply(.newChat)+ try await harness.apply(.send(label: 3))+ try await harness.apply(.setContext(tokens: AppContextLengthOption.fourK.tokens))+ // The long one, now refused for context: it draws through the read-only+ // path, which fills a different list from the one a continuable row+ // fills.+ try await harness.apply(.open(row: try harness.row(ofCreated: 0)))+ // And then one that is neither held nor refused, which has to replace+ // what the refused one left on screen rather than draw under it.+ try await harness.apply(.open(row: try harness.row(ofCreated: 1)))+ }++ /// A conversation with a picture in each of two turns could never be+ /// continued again: the second image-bearing turn looked for its+ /// placeholders at a position that only existed if every earlier image had+ /// been in the same turn.+ @MainActor+ @Test func aChatWithPicturesInTwoTurnsReplaysAndContinues() async throws {+ guard HistoryImageFixture.isAvailable else { return }+ let harness = try await HistoryHarness(label: "two-images")+ defer { harness.tearDown() }++ try await harness.apply(.sendWithImage(label: 1))+ try await harness.apply(.sendWithImage(label: 2))+ try await harness.apply(.newChat)+ try await harness.apply(.open(row: 0))+ try await harness.apply(.send(label: 3))+ }++ /// The release paths deleted a stored conversation's pictures off disk.+ /// Reopening one puts its images into the live conversation, and New Chat+ /// releases every image the live conversation holds.+ @MainActor+ @Test func reopeningAChatAndLeavingItKeepsItsPictures() async throws {+ guard HistoryImageFixture.isAvailable else { return }+ let harness = try await HistoryHarness(label: "image-lifetime")+ defer { harness.tearDown() }++ try await harness.apply(.sendWithImage(label: 1))+ try await harness.apply(.newChat)+ try await harness.apply(.open(row: 0))+ // The replay is what puts the stored copies into the live conversation.+ try await harness.apply(.send(label: 2))+ try await harness.apply(.newChat)+ }++ // MARK: - The defects the walk found++ /// Raising the context back to where the chat fits, and coming back to the+ /// chat the KV was holding, draws it once.+ ///+ /// Without the fix: the branch that returns to the held conversation+ /// cleared the stored pairs but not the archived ones, and a row refused+ /// for context draws through the archived list — so the transcript showed+ /// the chat from disk above the same chat live. Found by the seeded walk at+ /// seed 6, step 28.+ @MainActor+ @Test func comingBackToTheHeldChatAfterRaisingTheContextDrawsItOnce() async throws {+ let harness = try await HistoryHarness(label: "held-redraw")+ defer { harness.tearDown() }++ try await harness.apply(.sendLong(label: 1))+ // Too big for 4K, so opening it draws the read-only copy.+ try await harness.apply(.setContext(tokens: AppContextLengthOption.fourK.tokens))+ try await harness.apply(.open(row: 0))+ // And now it fits again, so the same click goes back to the live one.+ try await harness.apply(.setContext(tokens: AppContextLengthOption.eightK.tokens))+ }++ /// A replay that fails leaves the chat the KV is still holding with its+ /// pictures.+ ///+ /// Without the fix: the staged copies of the conversation being left were+ /// released at the top of the replay, before anything had been given up. A+ /// restore that then failed left that conversation held and on screen with+ /// every image in it deleted off disk. Found by the seeded walk at seed 2,+ /// step 17.+ @MainActor+ @Test func aFailedReplayLeavesTheHeldChatsPicturesAlone() async throws {+ guard HistoryImageFixture.isAvailable else { return }+ let harness = try await HistoryHarness(label: "failed-replay-images")+ defer { harness.tearDown() }++ try await harness.apply(.send(label: 1))+ try await harness.apply(.newChat)+ try await harness.apply(.sendWithImage(label: 2))+ // The first chat, which is not the one being held.+ try await harness.apply(.open(row: try harness.row(ofCreated: 0)))+ try await harness.apply(.failNextRestore)+ try await harness.apply(.send(label: 3))+ }++ /// Deleting the chat being read selects the chat that comes back on screen.+ ///+ /// Without the fix: the selection was cleared outright, so the window+ /// showed the conversation the KV was holding with no row highlighted for+ /// it — the one state every other path in this file is careful not to+ /// produce. Found by the seeded walk at seed 3, step 29.+ @MainActor+ @Test func deletingTheChatBeingReadSelectsTheOneThatComesBack() async throws {+ let harness = try await HistoryHarness(label: "delete-read")+ defer { harness.tearDown() }++ try await harness.apply(.send(label: 1))+ try await harness.apply(.newChat)+ try await harness.apply(.send(label: 2))+ try await harness.apply(.open(row: try harness.row(ofCreated: 0)))+ try await harness.apply(.delete(row: try harness.row(ofCreated: 0)))+ }++ /// Reloading while reading a chat that cannot be continued leaves that+ /// chat's transcript behind.+ ///+ /// Without the fix: a load rebuilds the KV, so the conversation it was+ /// holding moved out of context into the one array that also held the+ /// read-only copy of a chat refused for context. The copy being read was+ /// still in it, so the window drew a conversation the user was only+ /// looking at as the live one's own out-of-context turns, under a context+ /// break, and Re-read into a new chat would have built its prompt from it.+ /// Found by the seeded walk at seed 17, step 23, and again at seed 22 with+ /// an unload in place of the reload. The two are separate values now — the+ /// screen and `AppConversation.outOfContextPairs` — so this case is what+ /// keeps them separate.+ @MainActor+ @Test func reloadingWhileReadingAChatPreservesTheViewedOneOnScreen() async throws {+ let harness = try await HistoryHarness(label: "reload-reading")+ defer { harness.tearDown() }++ // One long chat, so it stops fitting when the context drops, and one+ // short chat for the KV to be holding when the reload lands.+ try await harness.apply(.sendLong(label: 1))+ try await harness.apply(.newChat)+ try await harness.apply(.send(label: 2))+ try await harness.apply(.setContext(tokens: AppContextLengthOption.fourK.tokens))+ // The refused row remains selected; it must not become the released+ // live conversation's out-of-context turns or be replaced by that row.+ try await harness.apply(.open(row: try harness.row(ofCreated: 0)))+ try await harness.apply(.reload)+ }++ /// An unload takes the same path.+ @MainActor+ @Test func unloadingWhileReadingAChatPreservesTheViewedOneOnScreen() async throws {+ let harness = try await HistoryHarness(label: "unload-reading")+ defer { harness.tearDown() }++ try await harness.apply(.sendLong(label: 1))+ try await harness.apply(.newChat)+ try await harness.apply(.send(label: 2))+ try await harness.apply(.setContext(tokens: AppContextLengthOption.fourK.tokens))+ try await harness.apply(.open(row: try harness.row(ofCreated: 0)))+ try await harness.apply(.unload)+ }++ /// A reload ends the in-memory lineage on both sides, but the durable row+ /// remains selected. The next send replays it and appends to that same row.+ @MainActor+ @Test func sendingAfterAReloadReplaysAndContinuesTheStoredConversation() async throws {+ let harness = try await HistoryHarness(label: "reload-send")+ defer { harness.tearDown() }++ try await harness.apply(.send(label: 1))+ try await harness.apply(.reload)+ try await harness.apply(.send(label: 2))+ }++ // MARK: - The ones nobody has thought of yet++ /// The reference model archived a durable row after reload as if its KV+ /// still existed. Deleting the row exposed those invented transcript turns.+ @MainActor+ @Test func failedReplayAfterReloadDoesNotInventOutOfContextTurns() async throws {+ let harness = try await HistoryHarness(label: "reload-failed-replay-delete")+ defer { harness.tearDown() }+ try await harness.apply(.send(label: 1))+ try await harness.apply(.failNextRestore)+ try await harness.apply(.reload)+ try await harness.apply(.send(label: 4))+ try await harness.apply(.delete(row: 0))+ }++ @MainActor+ @Test(arguments: 0..<64)+ func aSeededWalkHoldsEveryInvariant(seed: Int) async throws {+ var generator = SplitMix64(seed: UInt64(seed))+ let harness = try await HistoryHarness(label: "seed-\(seed)")+ defer { harness.tearDown() }++ for step in 1...40 {+ try await harness.apply(+ HistoryOperation.next(step: step, using: &generator))+ }+ }++ /// Replays one seed on its own and prints the trace.+ ///+ /// `TURBO_FIELDFARE_HISTORY_SEED=17 TURBO_FIELDFARE_HISTORY_STEPS=12+ /// swift test --filter aNamedSeedReplaysWithItsTrace`. The seed and the step+ /// index are the whole reproduction: there is no shrinking, so a walk that+ /// finds something is narrowed by re-running it shorter and then written+ /// down by hand as one of the cases above.+ @MainActor+ @Test func aNamedSeedReplaysWithItsTrace() async throws {+ let environment = ProcessInfo.processInfo.environment+ guard let raw = environment["TURBO_FIELDFARE_HISTORY_SEED"],+ let seed = UInt64(raw) else { return }+ let steps = environment["TURBO_FIELDFARE_HISTORY_STEPS"].flatMap(Int.init) ?? 40+ var generator = SplitMix64(seed: seed)+ let harness = try await HistoryHarness(label: "replay-\(seed)")+ defer {+ print("seed \(seed), \(harness.trace.count) step(s):")+ for line in harness.trace { print(" \(line)") }+ harness.tearDown()+ }++ for step in 1...steps {+ try await harness.apply(+ HistoryOperation.next(step: step, using: &generator))+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swiftnew file mode 100644index 00000000..d4f73d3d--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift@@ -0,0 +1,3232 @@+import Foundation+import Synchronization+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// Persisting a conversation is only worth anything if what lands on disk is+/// what the model saw. Every case here is a way the two could come apart: a+/// turn written before it reached the KV, a rewound turn written anyway, a+/// reopen that re-renders text instead of replaying IDs, or a new chat that+/// keeps appending to the old one's file.+@Suite struct AppModelHistoryTests {+ @MainActor+ @Test func reopeningHistoryKeepsAutomaticPublicResponseLimit() async throws {+ let (model, root) = try await readyModel(FakeInferenceClient(eventDelay: .milliseconds(1)))+ defer { try? FileManager.default.removeItem(at: root) }+ #expect(model.maxNewTokensOverride == nil)+ model.promptText = "saved exchange"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ // A recorded request budget is not a public app response-limit control.+ #expect(model.maxNewTokensOverride == nil)+ }++ @MainActor+ @Test func queuedSendKeepsTheCompletedAnswerTerminal() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "first"+ model.send()+ try await finish(model)+ let answer = model.outputText+ let run = model.runIdentity+ model.promptText = "second"+ model.send()+ // No actor hop: deliver has not published the new turn yet.+ #expect(model.isTurnInFlight)+ #expect(!model.canRun)+ #expect(model.outputText == answer)+ #expect(model.runIdentity == run)+ #expect(!model.isTranscriptTurnInFlight)+ try await finish(model)+ #expect(!model.isTranscriptTurnInFlight)+ }++ @MainActor+ @Test func queuedStoredSendDoesNotExposeTheHeldChat() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "stored A"+ model.send()+ try await finish(model)+ let a = try #require(model.storedConversationID)+ model.newChat()+ model.promptText = "held B"+ model.send()+ try await finish(model)+ model.openConversation(id: a)+ try await waitUntil { await model.screen.document?.id == a }+ model.promptText = "continue A"+ model.send()+ #expect(model.isTurnInFlight)+ #expect(!model.isTranscriptTurnInFlight)+ #expect(!model.showsLiveTurn)+ #expect(model.screen.document?.id == a)+ try await finish(model)+ #expect(model.storedConversationID == a)+ }++ @MainActor+ @Test func failedCreationCannotStartSavingHalfwayThroughLiveKV() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try #require(model.conversationStore)+ let storeRoot = await store.rootURL+ try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: storeRoot.path)+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: storeRoot.path) }+ model.promptText = "unsaved first exchange"+ model.send()+ await SendWaiting.turnEnds(model)+ await model.awaitPendingPersistence()+ #expect(model.conversation.committedTurns == 1)+ #expect(model.storedConversationID == nil)+ #expect(model.error?.userMessage.contains("not be saved") == true)+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: storeRoot.path)++ // Retrying storage must not publish a continuation without its KV prefix.+ model.promptText = "continue unsaved exchange"+ model.send()+ await SendWaiting.turnEnds(model)+ await model.awaitPendingPersistence()+ #expect(model.conversation.committedTurns == 2)+ #expect(model.storedConversationID == nil)+ #expect(try await store.list().isEmpty)+ #expect(model.error != nil)++ model.newChat()+ model.promptText = "fresh durable exchange"+ model.send()+ try await finish(model)+ #expect(try await store.list().count == 1)+ }++ @MainActor+ @Test(arguments: [false, true])+ func adversarialFailedReplayThenRetryAppendsExactlyOnce(connectionLost: Bool) async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "A"+ model.send()+ try await finish(model)+ let a = try #require(model.storedConversationID)+ model.newChat()+ model.promptText = "B"+ model.send()+ try await finish(model)+ let b = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)+ let aURL = await store.transcriptURL(for: a)+ let bURL = await store.transcriptURL(for: b)+ let aBefore = try Data(contentsOf: aURL)+ let bBefore = try Data(contentsOf: bURL)+ model.openConversation(id: a)+ try await waitUntil { await model.screen.document?.id == a }+ client.failNextRestore(with: connectionLost+ ? .connectionLost("injected EOF")+ : .conversationRestoreFailed("stored image digest mismatch"))+ model.promptText = "retry draft"+ model.send()+ await SendWaiting.turnEnds(model)+ await model.persistenceTail?.value+ #expect(model.error != nil)+ #expect(model.promptText == "retry draft")+ #expect(model.history.selection == a)+ #expect(model.serviceEpoch == nil)+ #expect(try Data(contentsOf: aURL) == aBefore)+ #expect(try Data(contentsOf: bURL) == bBefore)+ if connectionLost {+ #expect(model.canLoadModel)+ model.loadModel()+ try await waitUntil { await model.loadState.isReady }+ try await waitUntil { await model.screen.document?.id == a }+ }+ model.send()+ try await finish(model)+ #expect(model.storedConversationID == a)+ #expect(client.restoredLineages.count == 1)+ #expect(try await store.open(id: a).meta.turnCount == 4)+ #expect(try Data(contentsOf: bURL) == bBefore)+ }++ @MainActor+ @Test(arguments: [false, true])+ func adversarialContextRefusalThenRaiseAppendsOnce(boundary: Bool) async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "seed"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)+ let limit = 4_096 - ConversationGenerationReserve.tokens+ - ConversationGenerationReserve.turnEnvelope+ let current = try #require(try await store.open(id: id).meta.kvTokens)+ let padding = (boundary ? limit : limit + 1) - current+ try await store.append([+ .turn(ConversationTurnRecord(role: .user, at: Date(), text: "padding",+ tokens: Array(repeating: Int32(7), count: padding - 1))),+ .turn(ConversationTurnRecord(role: .assistant, at: Date(), text: "answer",+ tokens: [8], boundary: ConversationBoundary(+ tokens: boundary ? [7] : [], needsReplay: boundary)))+ ], to: id)+ await model.refreshHistory()+ model.newChat()+ model.setMaxContextTokens(4_096)+ client.setLoadedContext(4_096)+ model.applyLoadState(model.loadState)+ model.openConversation(id: id)+ try await waitUntil { await model.screen.document?.id == id }+ let url = await store.transcriptURL(for: id)+ let before = try Data(contentsOf: url)+ let count = try await store.open(id: id).meta.turnCount+ #expect(!model.screen.allowsSend)+ model.promptText = "continue"+ model.send()+ #expect(!model.isTurnInFlight)+ #expect(client.restoredLineages.isEmpty)+ #expect(try Data(contentsOf: url) == before)+ model.setMaxContextTokens(8_192)+ client.setLoadedContext(8_192)+ model.applyLoadState(model.loadState)+ try await waitUntil { @MainActor in model.screen.allowsSend && model.screen.document != nil }+ model.send()+ try await finish(model)+ #expect(model.storedConversationID == id)+ #expect(client.restoredLineages.count == 1)+ #expect(try await store.open(id: id).meta.turnCount == count + 2)+ }++ @MainActor+ @Test(arguments: [false, true])+ func adversarialDeletingHeldChatPreservesLatestViewedChat(delayed: Bool) async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let attachments = AppImageAttachmentStore()+ let (model, root) = try await readyModel(client, attachmentStore: attachments)+ defer { try? FileManager.default.removeItem(at: root) }+ var ids: [UUID] = []+ for label in ["A", "C", "B"] {+ model.newChat()+ model.promptText = label+ model.send()+ try await finish(model)+ ids.append(try #require(model.storedConversationID))+ }+ let viewed = delayed ? ids[1] : ids[0]+ let held = ids[2]+ let store = try #require(model.conversationStore)+ let otherURL = await store.transcriptURL(for: delayed ? ids[0] : ids[1])+ let otherBytes = try Data(contentsOf: otherURL)+ let first = ids[0]+ model.openConversation(id: first)+ try await waitUntil { await model.screen.document?.id == first }+ let gate = HistoryListGate()+ if delayed {+ model.persistenceTail = Task { await gate.wait() }+ await gate.waitUntilEntered()+ }+ model.deleteConversation(id: held)+ let deletion = try #require(model.conversationDeletionTask)+ if delayed {+ model.openConversation(id: viewed)+ try await waitUntil { await model.screen.document?.id == viewed }+ }+ model.promptText = "continue the viewed chat"+ let source = try Self.pngFixture()+ defer { try? FileManager.default.removeItem(at: source) }+ let staged = try attachments.stage(source)+ model.setComposerAttachmentsForTesting([staged])+ await gate.open()+ await deletion.value+ #expect(model.history.entry(held) == nil)+ #expect(model.history.selection == viewed)+ #expect(model.screen.conversationID == viewed)+ #expect(model.promptText == "continue the viewed chat")+ #expect(model.imageAttachments.map(\.id) == [staged.id])+ #expect(FileManager.default.fileExists(atPath: staged.fileURL.path))+ model.clearImages()+ model.send()+ try await finish(model)+ #expect(model.storedConversationID == viewed)+ #expect(client.restoredLineages.count == 1)+ #expect(try await store.open(id: viewed).meta.turnCount == 4)+ #expect(try Data(contentsOf: otherURL) == otherBytes)+ }++ @MainActor+ @Test func adversarialReadCannotResetEditsMadeBeforeItCompletes() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ model.newChat()+ model.openConversation(id: id)+ model.temperature = 0.9+ model.topK = 17+ try await waitUntil { await model.screen.document?.id == id }+ #expect(model.temperature == 0.9)+ #expect(model.topK == 17)+ }++ @MainActor+ @Test func adversarialDeletingUnrelatedRowAfterUnloadKeepsViewedChat() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ var ids: [UUID] = []+ for label in ["A", "C", "B"] {+ model.newChat()+ model.promptText = label+ model.send()+ try await finish(model)+ ids.append(try #require(model.storedConversationID))+ }+ model.unloadModel()+ try await waitUntil { await model.loadState == .notLoaded }+ let viewed = ids[0]+ model.openConversation(id: viewed)+ try await waitUntil { await model.screen.document?.id == viewed }+ model.deleteConversation(id: ids[1])+ await model.conversationDeletionTask?.value+ #expect(model.history.selection == viewed)+ #expect(model.screen.document?.id == viewed)+ #expect(model.history.entry(ids[1]) == nil)+ }++ @MainActor+ @Test func adversarialImmediateSendBeforeDocumentReadCompletes() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ model.newChat()+ // No suspension between opening and sending: the document task has+ // been scheduled but cannot yet have delivered its MainActor result.+ model.openConversation(id: id)+ #expect(model.screen.document == nil)+ model.temperature = 0.9+ model.topK = 17+ model.promptText = "second"+ model.send()+ try await finish(model)+ let store = try #require(model.conversationStore)+ let opened = try await store.open(id: id)+ #expect(opened.meta.turnCount == 4)+ #expect(model.storedConversationID == id)+ #expect(client.restoredLineages.count == 1)+ #expect(model.temperature == 0.9)+ #expect(model.topK == 17)+ #expect(opened.meta.sampling.temperature == 0.9)+ #expect(opened.meta.sampling.topK == 17)+ }++ /// KV release used to reopen the held row, silently replacing the viewed+ /// row and redirecting the next message after unload/load or reload.+ @MainActor+ @Test(arguments: [false, true], [false, true])+ func modelLifecyclePreservesViewedChat(reload: Bool, keepHeldChat: Bool) async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.applyLoadState(model.loadState)+ model.promptText = "viewed"+ model.send()+ try await finish(model)+ let viewed = try #require(model.history.selection)+ let store = try #require(model.conversationStore)+ let viewedRecord = try await store.open(id: viewed)+ let expectedTokens = viewedRecord.records.compactMap { record -> [Int32]? in+ guard case .turn(let turn) = record else { return nil }+ return turn.tokens+ }.flatMap { $0 }+ model.newChat()+ model.promptText = "held"+ model.send()+ try await finish(model)+ let held = try #require(model.history.selection)+ let heldURL = await store.transcriptURL(for: held)+ let heldBytes = try Data(contentsOf: heldURL)+ if !keepHeldChat { model.newChat() }+ model.openConversation(id: viewed)+ try await waitUntil { await model.screen.document?.id == viewed }+ model.promptText = "continue viewed"++ if reload {+ model.setMaxContextTokens(4_096)+ try #require(model.canReloadModel)+ model.reloadModel()+ } else {+ model.unloadModel()+ try await waitUntil { await model.loadState == .notLoaded }+ #expect(model.history.selection == viewed)+ model.loadModel()+ }+ try await waitUntil { await model.loadState.isReady }+ try await waitUntil { await model.screen.document != nil }+ #expect(model.history.selection == viewed)+ #expect(model.screen.conversationID == viewed)+ #expect(model.serviceEpoch == nil)+ #expect(model.conversation.turns.isEmpty)+ #expect(model.promptText == "continue viewed")+ #expect(client.restoredLineages.isEmpty, "loading must not replay before send")+ model.send()+ await SendWaiting.turnEnds(model)+ await model.persistenceTail?.value+ #expect(client.restoredLineages.count == 1)+ #expect(client.restoredLineages.first?.tokenIDs == expectedTokens)+ #expect(model.storedConversationID == viewed)+ #expect(try await store.open(id: viewed).meta.turnCount == 4)+ #expect(try Data(contentsOf: heldURL) == heldBytes)+ }++ @MainActor+ @Test(arguments: [false, true])+ func modelLifecycleKeepsUnreadableSelectionFailClosed(reload: Bool) async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.applyLoadState(model.loadState)+ model.promptText = "unreadable"+ model.send()+ try await finish(model)+ let viewed = try #require(model.history.selection)+ let store = try #require(model.conversationStore)+ model.newChat()+ model.promptText = "held"+ model.send()+ try await finish(model)+ let directory = await store.directoryURL(for: viewed)+ try FileManager.default.removeItem(at: directory)+ model.openConversation(id: viewed)+ try await waitUntil { await model.screen.shape == .unreadable }+ if reload {+ model.setMaxContextTokens(4_096)+ try #require(model.canReloadModel)+ model.reloadModel()+ } else {+ model.unloadModel()+ try await waitUntil { await model.loadState == .notLoaded }+ model.loadModel()+ }+ try await waitUntil { await model.loadState.isReady }+ try await waitUntil { await model.screen.shape != .reading }+ #expect(model.history.selection == viewed)+ #expect(model.screen.shape == .unreadable)+ #expect(!model.screen.allowsSend)+ #expect(model.serviceEpoch == nil)+ #expect(client.restoredLineages.isEmpty)+ }++ @MainActor+ @Test(arguments: [false, true])+ func modelLifecycleKeepsNewChatEmpty(reload: Bool) async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.applyLoadState(model.loadState)+ model.promptText = "previous"+ model.send()+ try await finish(model)+ let previous = try #require(model.history.selection)+ model.newChat()+ if reload {+ model.setMaxContextTokens(4_096)+ try #require(model.canReloadModel)+ model.reloadModel()+ } else {+ model.unloadModel()+ try await waitUntil { await model.loadState == .notLoaded }+ model.loadModel()+ }+ try await waitUntil { await model.loadState.isReady }+ #expect(model.history.selection == nil)+ #expect(model.screen == .live)+ #expect(model.conversation.turns.isEmpty)+ model.promptText = "new"+ model.send()+ try await finish(model)+ #expect(model.storedConversationID != previous)+ #expect(client.restoredLineages.isEmpty)+ }++ private static let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private func placeCompleteModel(at directory: URL, tag: String) throws {+ let fixture = try makeCompleteModelInstall(tag)+ defer { try? FileManager.default.removeItem(at: fixture) }+ try FileManager.default.createDirectory(+ at: directory.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.moveItem(at: fixture, to: directory)+ let receiptURL = directory.appendingPathComponent("verified-install.json")+ var receipt = try #require(+ JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL)) as? [String: Any])+ receipt["modelDirectoryPath"] = directory.standardizedFileURL.path+ try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys])+ .write(to: receiptURL)+ }++ @MainActor+ private func readyModel(+ _ client: FakeInferenceClient,+ attachmentStore: AppImageAttachmentStore = AppImageAttachmentStore()+ ) async throws -> (model: AppModel, root: URL) {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-\(UUID().uuidString)", isDirectory: true)+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(+ at: directory, withIntermediateDirectories: true)+ let model = AppModel(modelDirectory: directory, client: client,+ attachmentStore: attachmentStore,+ settingsPersistenceEnabled: true)+ model.modelPathText = directory.path+ // The app reads this from the installed model's manifest; a temporary+ // directory has none, and the identity is not what these tests are about.+ model.conversationIdentity = Self.identity+ try await client.ensureLoaded(+ modelDirectory: directory,+ maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions,+ forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ // Otherwise `requiresModelInstallation` is true and every+ // `canStartNewChat` assertion below passes for that reason instead of+ // the one it is testing.+ model.installationStatus = .complete+ try await model.waitForHistory()+ return (model, root)+ }++ @MainActor+ private func finish(_ model: AppModel) async throws {+ await SendWaiting.turnEnds(model)+ // The turn is written from a task the terminal event starts, so the+ // assertions have to wait for the store rather than for the run.+ try await model.waitForStoredTurns(atLeast: model.conversation.turns.count)+ }++ private func imageOutcome(_ name: String) -> TurnImageWriteOutcome {+ TurnImageWriteOutcome(records: [ConversationImageRecord(+ id: UUID(), displayName: name,+ pixelsFile: "images/\(name).png",+ thumbnailFile: "images/\(name).thumb.jpg",+ sourceDigest: name, modelInputDigest: "model-\(name)",+ width: 48, height: 48, softTokens: 1)])+ }++ /// A delete waiting for the previous reply's image write must reserve its+ /// mutation before another send can start against the same directory.+ @MainActor+ @Test func deletionExcludesSendsUntilPendingPersistenceAndRemovalFinish() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(100))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ let gate = HistoryListGate()+ model.promptText = "first"+ model.send()+ try await waitUntil { client.isGenerating }+ model.pendingTurnImageWrite = Task {+ await gate.wait()+ return TurnImageWriteOutcome()+ }+ try await waitUntil { await !model.isTurnInFlight }+ try #require(!model.isTurnInFlight)+ await gate.waitUntilEntered()+ let id = try #require(model.storedConversationID)+ let folder = try #require(await model.conversationFolderURL(for: id))+ model.deleteConversation(id: id)+ model.promptText = "second"+ #expect(!model.canRun)+ #expect(!model.canMutateConversation(id: id))+ try await Task.sleep(for: .milliseconds(20))+ model.send()+ #expect(!model.isTurnInFlight)+ #expect(model.promptText == "second")+ #expect(FileManager.default.fileExists(atPath: folder.path))+ await gate.open()+ await SendWaiting.turnEnds(model)+ await model.awaitPendingPersistence()+ try await waitUntil { await model.history.entry(id) == nil }+ #expect(!FileManager.default.fileExists(atPath: folder.path))+ #expect(model.storedConversationID == nil)+ #expect(model.historyDiagnostic == nil)+ #expect(model.canRun)+ }++ /// Cancelling the waiter of an independent Task.value does not end that+ /// wait. A task-group timeout therefore kept Quit blocked on the write.+ @MainActor+ @Test func terminationDeadlineReturnsWhilePersistenceIsStillBlocked() async throws {+ let model = AppModel(client: FakeInferenceClient())+ let gate = HistoryListGate()+ model.persistenceTail = Task { await gate.wait() }+ await gate.waitUntilEntered()+ var outcome: Bool?+ let waiting = Task {+ outcome = await model.awaitPendingPersistence(timeout: .milliseconds(10))+ }+ try await waitUntil { @MainActor in outcome != nil }+ #expect(outcome == false)+ #expect(model.persistenceTail?.isCancelled == false)+ await gate.open()+ await waiting.value+ }++ @MainActor+ @Test func deletionFailureReleasesTheSendReservationAndReportsTheCause() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)+ // Simulate a directory disappearing after the sidebar was populated.+ try await store.delete(id: id)+ model.deleteConversation(id: id)+ await model.conversationDeletionTask?.value+ model.promptText = "second"+ #expect(model.canRun)+ #expect(model.historyDiagnostic?.contains(id.uuidString) == true)+ }++ @MainActor+ @Test func deletionWaitingOnAnOldBindingDoesNotMutateEitherStore() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ let folder = try #require(await model.conversationFolderURL(for: id))+ let gate = HistoryListGate()+ model.persistenceTail = Task { await gate.wait() }+ await gate.waitUntilEntered()+ model.deleteConversation(id: id)+ let deletion = try #require(model.conversationDeletionTask)+ await Task.yield()+ let newDirectory = root.appendingPathComponent("other/gemma4.gturbo")+ model.setModelURL(newDirectory)+ await gate.open()+ await deletion.value+ try await model.waitForHistory(count: 0)+ #expect(FileManager.default.fileExists(atPath: folder.path))+ #expect(model.modelPathText == newDirectory.path)+ #expect(model.storedConversationID == nil)+ #expect(model.conversationDeletionTask == nil)+ #expect(model.historyDiagnostic == nil)+ }++ @MainActor+ @Test func cancelledTerminationWaitReturnsWithoutCancellingPersistence() async throws {+ let model = AppModel(client: FakeInferenceClient())+ let gate = HistoryListGate()+ model.persistenceTail = Task { await gate.wait() }+ await gate.waitUntilEntered()+ var outcome: Bool?+ let waiting = Task {+ outcome = await model.awaitPendingPersistence(timeout: .seconds(60))+ }+ await Task.yield()+ waiting.cancel()+ try await waitUntil { @MainActor in outcome != nil }+ #expect(outcome == false)+ #expect(model.persistenceTail?.isCancelled == false)+ await gate.open()+ await waiting.value+ }++ @MainActor+ @Test func terminationWaitReportsCompletedAndAbsentPersistence() async throws {+ let model = AppModel(client: FakeInferenceClient())+ #expect(await model.awaitPendingPersistence(timeout: .seconds(60)))+ let gate = HistoryListGate()+ model.persistenceTail = Task { await gate.wait() }+ await gate.waitUntilEntered()+ let waiting = Task {+ await model.awaitPendingPersistence(timeout: .seconds(60))+ }+ await gate.open()+ #expect(await waiting.value)+ }++ /// Opening restores the saved controls once. Replaying on Send must not+ /// replace the sampling choices made after that open.+ @MainActor+ @Test func replayPreservesSamplingChosenAfterOpeningTheChat() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(20))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.temperature = 0.2+ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await model.screen.document != nil }+ try #require(model.screen.document != nil)+ model.temperature = 0.9+ model.maxNewTokensOverride = 47+ model.topK = 17+ model.topP = 0.75+ model.promptText = "second"+ model.send()+ await SendWaiting.turnEnds(model)+ await model.awaitPendingPersistence()+ let store = try #require(model.conversationStore)+ let meta = try await store.open(id: id).meta+ #expect(client.restoredLineages.count == 1)+ #expect(meta.turnCount == 4)+ #expect(meta.sampling.temperature == 0.9)+ #expect(meta.sampling.maxNewTokens == 47)+ #expect(meta.sampling.topK == 17)+ #expect(meta.sampling.topP == 0.75)+ #expect(model.currentSampling() == meta.sampling)+ }++ @MainActor+ @Test func completedTurnsPersistInKVCommitOrderWithTheirCapturedState() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(20))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ let firstImageGate = HistoryListGate()++ model.temperature = 0.25+ model.maxNewTokensOverride = 31+ model.promptText = "first"+ model.send()+ try await waitUntil { client.isGenerating }+ let firstOutcome = imageOutcome("first")+ model.pendingTurnImageWrite = Task {+ await firstImageGate.wait()+ return firstOutcome+ }+ try await waitUntil { await !model.isTurnInFlight }++ model.temperature = 0.75+ model.maxNewTokensOverride = 47+ model.promptText = "second"+ model.send()+ try await waitUntil { client.isGenerating }+ let secondOutcome = imageOutcome("second")+ model.pendingTurnImageWrite = Task { secondOutcome }+ try await waitUntil { await !model.isTurnInFlight }+ #expect(model.persistenceTail != nil)++ await firstImageGate.open()+ await model.persistenceTail?.value+ let store = try #require(model.conversationStore)+ let id = try #require(model.storedConversationID)+ let turns = try await store.open(id: id).records.compactMap { record in+ if case .turn(let turn) = record { return turn }+ return nil+ }++ #expect(turns.map(\.text).filter { $0 == "first" || $0 == "second" }+ == ["first", "second"])+ #expect(turns[0].images.map(\.displayName) == ["first"])+ #expect(turns[2].images.map(\.displayName) == ["second"])+ #expect(turns[0].sampling?.temperature == 0.25)+ #expect(turns[0].sampling?.maxNewTokens == 31)+ #expect(turns[2].sampling?.temperature == 0.75)+ #expect(turns[2].sampling?.maxNewTokens == 47)+ #expect(turns[1].boundary != nil && turns[3].boundary != nil)+ }++ @MainActor+ @Test func rootSwitchCancelsAQueuedTurnBeforeItCanAppendOrReport() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(20))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ let gate = HistoryListGate()++ model.promptText = "old root"+ model.send()+ try await waitUntil { client.isGenerating }+ let outcome = imageOutcome("old-root")+ model.pendingTurnImageWrite = Task {+ await gate.wait()+ return outcome+ }+ try await waitUntil { await !model.isTurnInFlight }+ let oldTail = try #require(model.persistenceTail)+ let oldStore = try #require(model.conversationStore)+ let oldID = try #require(model.storedConversationID)++ let newDirectory = root.appendingPathComponent("other/model.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(+ at: newDirectory, withIntermediateDirectories: true)+ model.setModelURL(newDirectory)+ await gate.open()+ await oldTail.value++ let oldTurns = try await oldStore.open(id: oldID).records.filter {+ if case .turn = $0 { return true }+ return false+ }+ #expect(oldTurns.isEmpty)+ #expect(model.conversationBinding?.modelDirectory == newDirectory.standardizedFileURL)+ #expect(model.historyDiagnostic == nil)+ }++ @MainActor+ @Test func rootSwitchCancelsAnOlderWriteAtTheBatchBoundary() async throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-batch-cancel-\(UUID())", isDirectory: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ let gate = HistoryListGate()+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = AppModel(+ modelDirectory: directory,+ client: client,+ settingsPersistenceEnabled: true,+ conversationStoreProvider: { root in+ ConversationStore(+ rootURL: root,+ appendOperations: ConversationStoreAppendOperations(beforeBatch: {+ await gate.wait()+ }))+ })+ model.conversationIdentity = Self.identity+ model.installationStatus = .complete+ try await client.ensureLoaded(+ modelDirectory: directory, maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions, forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 0)+ try await model.waitForHistory()++ model.promptText = "old root"+ model.send()+ try await waitUntil { await !model.isTurnInFlight }+ await gate.waitUntilEntered()+ let oldTail = try #require(model.persistenceTail)+ let oldStore = try #require(model.conversationStore)+ let oldID = try #require(model.storedConversationID)++ let newDirectory = root.appendingPathComponent("other/model.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(+ at: newDirectory, withIntermediateDirectories: true)+ model.setModelURL(newDirectory)+ await gate.open()+ await oldTail.value++ let oldTurns = try await oldStore.open(id: oldID).records.filter {+ if case .turn = $0 { return true }+ return false+ }+ #expect(oldTurns.isEmpty,+ "cancellation after entering append must stop the old-root batch")+ #expect(model.conversationBinding?.modelDirectory == newDirectory.standardizedFileURL)+ #expect(model.historyDiagnostic == nil)+ }++ @MainActor+ @Test func appendUncertaintyQuarantinesTheLiveLineageUntilNewChat() async throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-quarantine-\(UUID())", isDirectory: true)+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let failuresRemaining = Mutex(1)+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let model = AppModel(+ modelDirectory: directory,+ client: client,+ settingsPersistenceEnabled: true,+ conversationStoreProvider: { root in+ ConversationStore(+ rootURL: root,+ appendOperations: ConversationStoreAppendOperations(beforeBatch: {+ let mustFail = failuresRemaining.withLock { remaining -> Bool in+ guard remaining > 0 else { return false }+ remaining -= 1+ return true+ }+ if mustFail {+ throw ConversationStoreError.writeFailed(+ path: "transcript.jsonl", reason: "injected full volume")+ }+ }))+ })+ model.conversationIdentity = Self.identity+ model.installationStatus = .complete+ try await client.ensureLoaded(+ modelDirectory: directory, maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions, forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 0)+ try await model.waitForHistory()++ model.promptText = "first"+ model.send()+ await SendWaiting.turnEnds(model)+ await model.persistenceTail?.value+ let store = try #require(model.conversationStore)+ let afterFailure = try await store.list()+ #expect(afterFailure.count == 1)+ #expect(model.storedConversationID == nil)+ #expect(model.historyDiagnostic?.contains("injected full volume") == true)+ #expect(model.error?.userMessage.contains("not be saved") == true,+ "a completed answer whose history write failed must show a visible warning")+ #expect(model.error?.technicalDetail.contains("injected full volume") == true)++ model.promptText = "same uncertain lineage"+ model.send()+ await SendWaiting.turnEnds(model)+ await model.persistenceTail?.value+ #expect(try await store.list().count == 1,+ "a replacement file was created for the uncertain live KV")++ model.newChat()+ model.promptText = "new lineage"+ model.send()+ try await finish(model)+ #expect(try await store.list().count == 2)+ }++ @MainActor+ @Test func lateListFromTheOldModelRootCannotReplaceTheNewBinding() async throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-root-switch-\(UUID())", isDirectory: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let directoryA = root.appendingPathComponent("a/model.gturbo", isDirectory: true)+ let directoryB = root.appendingPathComponent("b/model.gturbo", isDirectory: true)+ try placeCompleteModel(at: directoryA, tag: "binding-a")+ try placeCompleteModel(at: directoryB, tag: "binding-b")+ let identityA = Self.identity+ let identityB = ConversationIdentity(+ modelID: "model-b", sourceSnapshotHash: "snapshot-b",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)+ let gate = HistoryListGate()+ let storeRootA = ConversationStoreLocation.url(forModelDirectory: directoryA)+ let storeA = ConversationStore(+ rootURL: storeRootA,+ listOperations: ConversationStoreListOperations(beforeList: {+ await gate.wait()+ }))+ let storeB = ConversationStore(+ rootURL: ConversationStoreLocation.url(forModelDirectory: directoryB))+ try await storeA.activate()+ try await storeB.activate()+ let metaA = try await storeA.create(+ title: "root a", identity: identityA,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: ConversationSampling(+ temperature: 0, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 64))+ let metaB = try await storeB.create(+ title: "root b", identity: identityB,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: ConversationSampling(+ temperature: 0, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 64))++ let model = AppModel(+ modelDirectory: directoryA,+ client: FakeInferenceClient(),+ settingsPersistenceEnabled: true,+ conversationIdentityProvider: { directory in+ directory.standardizedFileURL == directoryA.standardizedFileURL+ ? identityA : identityB+ },+ conversationStoreProvider: { root in+ root.standardizedFileURL == storeRootA.standardizedFileURL+ ? storeA : storeB+ })+ await gate.waitUntilEntered()+ model.setModelURL(directoryB)+ try await model.waitForHistory(count: 1)+ await gate.open()+ try await Task.sleep(for: .milliseconds(30))++ #expect(model.conversationBinding?.modelDirectory == directoryB.standardizedFileURL)+ #expect(model.conversationIdentity == identityB)+ #expect(model.history.entries.map(\.id) == [metaB.id])+ #expect(model.history.entry(metaA.id) == nil)+ }++ @MainActor+ @Test func successfulLegacyTrashCleanupReachesHistoryState() async throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-trash-\(UUID())", isDirectory: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = root.appendingPathComponent("model.gturbo", isDirectory: true)+ let trash = ConversationStoreLocation.url(forModelDirectory: directory)+ .appendingPathComponent(".trash", isDirectory: true)+ try FileManager.default.createDirectory(+ at: trash.appendingPathComponent("one", isDirectory: true),+ withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: trash.appendingPathComponent("two", isDirectory: true),+ withIntermediateDirectories: true)++ let model = AppModel(+ modelDirectory: directory,+ client: FakeInferenceClient(),+ settingsPersistenceEnabled: true)+ try await waitUntil { await model.history.discardedLegacyTrashCount == 2 }++ #expect(!FileManager.default.fileExists(atPath: trash.path))+ #expect(model.historyDiagnostic?.contains("removed 2 conversation(s)") == true)+ }++ @MainActor+ @Test func unreadableInstalledIdentityKeepsHistoryReadableButDisablesReplayAndWrites() async throws {+ let fixture = try makeCompleteModelInstall("identity-failure")+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("identity-failure-\(UUID())", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer {+ try? FileManager.default.removeItem(at: fixture)+ try? FileManager.default.removeItem(at: root)+ }+ let directory = root.appendingPathComponent("model.gturbo", isDirectory: true)+ try FileManager.default.moveItem(at: fixture, to: directory)+ let receiptURL = directory.appendingPathComponent("verified-install.json")+ var receipt = try #require(+ JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL)) as? [String: Any])+ receipt["modelDirectoryPath"] = directory.standardizedFileURL.path+ try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys])+ .write(to: receiptURL)++ let store = ConversationStore(+ rootURL: ConversationStoreLocation.url(forModelDirectory: directory))+ try await store.activate()+ let meta = try await store.create(+ title: "readable",+ identity: Self.identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: ConversationSampling(+ temperature: 0, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 64))+ _ = try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "stored", tokens: [1])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer", tokens: [2],+ boundary: ConversationBoundary(tokens: [3], needsReplay: false))),+ ], to: meta.id)++ let model = AppModel(+ modelDirectory: directory,+ client: FakeInferenceClient(),+ settingsPersistenceEnabled: true,+ conversationIdentityProvider: { _ in+ throw ConversationIdentityError.snapshotHashUnavailable+ },+ conversationStoreProvider: { _ in store })+ try await model.waitForHistory(count: 1)+ model.openConversation(id: meta.id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ #expect(model.conversationIdentity == nil)+ #expect(model.openedConversationState == .cannotReplay(reason: .differentModel))+ #expect(model.transcriptHistory.map(\.user.text) == ["stored"])+ #expect(model.historyDiagnostic?.contains("source snapshot hash") == true)+ #expect(await model.ensureStoredConversation(firstMessage: "private prompt") == nil)+ #expect(model.historyDiagnostic?.contains("private prompt") == false)+ }++ /// The record has to be the token IDs, not the text: re-rendering the text+ /// through the template strips historical thought spans and produces a+ /// different sequence.+ @MainActor+ @Test func acompletedTurnIsOnDiskAsTheIDsTheKVTook() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)++ let id = try #require(model.history.selection)+ let store = try #require(model.conversationStore)+ let opened = try await store.open(id: id)+ let turns = opened.records.compactMap { record -> ConversationTurnRecord? in+ guard case .turn(let turn) = record else { return nil }+ return turn+ }+ #expect(turns.count == 2)+ #expect(turns[0].role == .user)+ #expect(turns[0].text == "hello")+ #expect(turns[0].tokens?.isEmpty == false)+ #expect(turns[1].role == .assistant)+ #expect(turns[1].tokens?.isEmpty == false)+ // The transcript on disk reproduces exactly the count the KV reported.+ #expect(opened.meta.kvTokens+ == turns.compactMap(\.tokens).flatMap { $0 }.count)+ #expect(opened.meta.turnCount == 2)+ #expect(opened.meta.title == "hello")+ #expect(model.history.entries.count == 1)+ }++ @MainActor+ @Test func deleteIsRefusedWhileATurnIsInFlight() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(50))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)++ model.promptText = "kept"+ model.send()+ await SendWaiting.generationStarts(model)+ let directory = await (try #require(model.conversationStore)).directoryURL(for: id)++ model.deleteConversation(id: id)+ try await Task.sleep(for: .milliseconds(20))++ #expect(FileManager.default.fileExists(atPath: directory.path))+ #expect(model.history.entry(id) != nil)+ await SendWaiting.turnEnds(model)+ }++ @MainActor+ @Test func deleteAndRenameAreRefusedDuringReplayThenAllowedAtRest() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(80))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)+ let directory = await store.directoryURL(for: id)+ let originalTitle = try await store.open(id: id).meta.title++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await model.screen.document != nil }+ model.promptText = "after replay"+ model.send()+ try await waitUntil { await model.screen.isReplaying }+ #expect(!model.canMutateConversation(id: id))+ model.renameConversation(id: id, to: "must not land")+ model.deleteConversation(id: id)+ try await Task.sleep(for: .milliseconds(20))+ #expect(FileManager.default.fileExists(atPath: directory.path))+ #expect(try await store.open(id: id).meta.title == originalTitle)++ await SendWaiting.turnEnds(model)+ await model.persistenceTail?.value+ #expect(model.canMutateConversation(id: id))+ model.deleteConversation(id: id)+ try await model.waitForHistory(count: 0)+ #expect(!FileManager.default.fileExists(atPath: directory.path))+ }++ @MainActor+ @Test func connectionLossRequiresReloadThenReplaysTheDurableRow() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "durable"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)++ client.failNextGeneration(with: .connectionLost("unexpected EOF"))+ model.promptText = "retry me"+ model.send()+ await SendWaiting.turnEnds(model)++ guard case .failed(.connectionLost(let cause)) = model.loadState else {+ Issue.record("connection loss did not invalidate Ready")+ return+ }+ #expect(cause.contains("unexpected EOF"))+ #expect(model.serviceEpoch == nil)+ #expect(model.promptText == "retry me")+ #expect(model.history.selection == id)+ #expect(model.openedConversationState == .continuable)+ #expect(try await store.open(id: id).meta.turnCount == 2,+ "the incomplete turn reached disk")++ model.loadModel()+ try await waitUntil { await model.loadState.isReady }+ model.send()+ await SendWaiting.turnEnds(model)+ await model.persistenceTail?.value++ #expect(client.restoredLineages.count == 1)+ #expect(model.storedConversationID == id)+ #expect(try await store.open(id: id).meta.turnCount == 4)+ }++ @MainActor+ @Test func relaunchRestoresTheSelectedTranscriptWhileSidebarStaysHidden() async throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-selection-\(UUID())", isDirectory: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(at: directory,+ withIntermediateDirectories: true)++ let firstClient = FakeInferenceClient(eventDelay: .milliseconds(1))+ var first: AppModel? = AppModel(+ modelDirectory: directory,+ client: firstClient,+ settingsPersistenceEnabled: true)+ first?.conversationIdentity = Self.identity+ first?.installationStatus = .complete+ first?.loadState = .ready(modelDirectory: directory, loadSeconds: 0)+ try await firstClient.ensureLoaded(+ modelDirectory: directory, maxContextTokens: 8_192,+ options: AppRuntimeOptions(), forceLogitsHead: true) { _ in }+ try await first?.waitForHistory()+ first?.promptText = "remember this"+ first?.send()+ if let first { await SendWaiting.turnEnds(first) }+ let selected = try #require(first?.history.selection)+ first?.setSidebarVisible(false)+ first = nil+ try await Task.sleep(for: .milliseconds(20))++ let second = AppModel(+ modelDirectory: directory,+ client: FakeInferenceClient(eventDelay: .milliseconds(1)),+ settingsPersistenceEnabled: true)+ second.conversationIdentity = Self.identity+ second.installationStatus = .complete+ try await second.waitForHistory(count: 1)+ try await waitUntil { await second.screen.document != nil }++ #expect(!second.isSidebarVisible)+ #expect(second.history.selection == selected)+ #expect(second.transcriptHistory.map(\.user.text) == ["remember this"])+ }++ /// A turn the runtime rewound is in neither the KV nor the transcript. A+ /// stored copy of it would be a message the model never saw, replayed into+ /// every future reopen.+ @MainActor+ @Test func athrownTurnIsWrittenNowhere() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let store = try #require(model.conversationStore)+ let before = try await store.open(id: id).records.count++ // A load key the client no longer recognises makes the next generate+ // throw before it reaches the KV.+ await client.unload()+ model.promptText = "second"+ model.send()+ await SendWaiting.turnEnds(model)+ try await Task.sleep(for: .milliseconds(50))++ #expect(try await store.open(id: id).records.count == before)+ #expect(model.error != nil)+ }++ /// Reopening must send the stored IDs. If it ever sent re-rendered text the+ /// conversation would continue as a different lineage while claiming to be+ /// the same one. The replay itself waits for the next message.+ @MainActor+ @Test func openThenSendReplaysTheStoredIDsRatherThanTheText() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let first = try #require(model.history.selection)+ let store = try #require(model.conversationStore)+ let stored = try await store.open(id: first)+ let expected = stored.records.compactMap { record -> [Int32]? in+ guard case .turn(let turn) = record else { return nil }+ return turn.tokens+ }.flatMap { $0 }++ model.newChat()+ model.promptText = "second"+ model.send()+ try await finish(model)+ #expect(model.history.entries.count == 2)++ model.openConversation(id: first)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ // Opening costs no replay at all.+ #expect(client.restoredLineages.isEmpty)+ #expect(model.screen.conversationID == first)++ model.promptText = "third"+ model.send()+ try await waitUntil { client.restoredLineages.count == 1 }++ let replayed = try #require(client.restoredLineages.first)+ #expect(replayed.tokenIDs == expected)+ #expect(replayed.committedTurns == 1)+ #expect(model.storedConversationID == first)+ #expect(!model.isShowingStoredCopy)+ }++ /// Opening a chat is a file read, so every exchange has to be on screen+ /// straight away — including the newest one, which the live fields draw for+ /// a conversation the KV is holding and which therefore has to come from+ /// somewhere else for one it is not.+ @MainActor+ @Test func areopenedChatShowsEveryExchangeWithoutReplaying() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first question"+ model.send()+ try await finish(model)+ model.promptText = "second question"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ #expect(client.restoredLineages.isEmpty, "opening paid for a replay")+ #expect(model.transcriptHistory.map(\.user.text)+ == ["first question", "second question"])+ #expect(model.hasOutputTranscript)+ // No context break: these turns are not out of the model's context,+ // they are simply not in it yet.+ #expect(model.transcriptContextBreak == nil)+ }++ /// The replay does not overwrite the message that started it.+ ///+ /// `adoptRestoredConversation` seeded the live fields with the restored+ /// conversation's newest pair - correct when a reopen replayed on the click+ /// and the window then sat at rest showing it, wrong now that a replay only+ /// runs inside a send. It replaced the user's prompt with an older one and+ /// cleared the attachments beside it, and since those attachments are the+ /// staged files the send is about to hard-link, clearing them deleted them:+ /// the turn came back "could not retain <name>: errno 2". Found by hand,+ /// sending a second picture into a reopened chat.+ @MainActor+ @Test func areplayDoesNotOverwriteTheMessageThatStartedIt() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(20))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "the first question"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ model.promptText = "the second question"+ model.send()+ try await waitUntil { await model.screen.isReplaying }+ try await waitUntil { await !model.screen.isReplaying }++ // Not "the first question", which is what adoption used to put here.+ #expect(model.outputPromptText == "the second question")+ try await finish(model)+ #expect(model.error == nil)+ #expect(model.conversation.turns.count == 4)+ // The restored exchange is drawn from the history, and the new turn+ // from the live fields, which is the split `transcriptHistory` states.+ #expect(model.transcriptHistory.map(\.user.text) == ["the first question"])+ #expect(model.outputPromptText == "the second question")+ }++ /// New Chat takes the composer's attachments with it.+ ///+ /// It released the conversation's images and the transcript's, and left the+ /// composer's alone — so a picture attached but never sent stayed in the box+ /// and came along into the new chat, ready to be sent with a message it had+ /// nothing to do with. Its staged copy also stayed on disk until the app+ /// quit. Found running case E41 by hand.+ @MainActor+ @Test func newChatReleasesAnAttachmentThatWasNeverSent() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let staging = FileManager.default.temporaryDirectory+ .appendingPathComponent("staging-\(UUID().uuidString)", isDirectory: true)+ let store = AppImageAttachmentStore(directoryURL: staging)+ defer { try? FileManager.default.removeItem(at: staging) }+ let (model, root) = try await readyModel(client, attachmentStore: store)+ defer { try? FileManager.default.removeItem(at: root) }++ // What the composer holds after a pick: a staged file this store owns.+ let source = try Self.pngFixture()+ defer { try? FileManager.default.removeItem(at: source) }+ let staged = try store.stage(source)+ model.setComposerAttachmentsForTesting([staged])+ #expect(FileManager.default.fileExists(atPath: staged.fileURL.path))++ model.newChat()++ #expect(model.imageAttachments.isEmpty,+ "the picture followed the user into the new chat")+ #expect(!FileManager.default.fileExists(atPath: staged.fileURL.path),+ "its staged copy was left on disk")+ }++ /// Re-read is not offered when there is nothing to re-read.+ ///+ /// The prompt is built from the turns on screen, so a conversation that+ /// could not be read at all has none. Offered anyway, the button started a+ /// new chat with an empty composer, which reads as the action having done+ /// nothing.+ @MainActor+ @Test func rereadIsRefusedWhenThereIsNothingToReread() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let folder = try #require(await model.conversationFolderURL(for: id))+ model.newChat()++ // Unreadable, so nothing is drawn from it.+ try FileManager.default.removeItem(+ at: folder.appendingPathComponent("transcript.jsonl"))+ model.openConversation(id: id)+ try await waitUntil { await model.error != nil }++ #expect(model.transcriptHistory.isEmpty)+ #expect(!model.canRereadIntoNewChat, "a re-read with nothing to read")+ model.promptText = ""+ model.rereadIntoNewChat()+ #expect(model.promptText.isEmpty, "it started a chat from nothing")+ }++ /// A rewound turn's images are collected.+ ///+ /// Images are written while the reply is still generating, so a turn the+ /// runtime rewinds leaves them on disk, cited by nothing and named by+ /// digest — invisible to every other pass. `sweepOrphanImages` existed for+ /// exactly this and had no caller anywhere in the app.+ @MainActor+ @Test func arewoundTurnsImagesAreCollected() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let folder = try #require(await model.conversationFolderURL(for: id))++ // What a rewound turn leaves: image files no surviving record names.+ let images = folder.appendingPathComponent("images", isDirectory: true)+ try FileManager.default.createDirectory(+ at: images, withIntermediateDirectories: true)+ let orphan = images.appendingPathComponent("deadbeef.png")+ let orphanThumb = images.appendingPathComponent("deadbeef.thumb.jpg")+ try Data("pixels".utf8).write(to: orphan)+ try Data("thumb".utf8).write(to: orphanThumb)++ // A turn that throws before it reaches the KV.+ await client.unload()+ model.promptText = "second"+ model.send()+ await SendWaiting.turnEnds(model)+ try await waitUntil {+ !FileManager.default.fileExists(atPath: orphan.path)+ }++ #expect(!FileManager.default.fileExists(atPath: orphan.path))+ #expect(!FileManager.default.fileExists(atPath: orphanThumb.path))+ // And the conversation itself is untouched: header, creation title,+ // and the one completed turn's two halves.+ let store = try #require(model.conversationStore)+ #expect(try await store.open(id: id).records.count == 4)+ }++ /// A stored conversation's pictures survive being looked at.+ ///+ /// `AppImageAttachmentStore.remove` deletes whatever a `fileURL` points at,+ /// and every path that finishes with a turn releases that turn's images+ /// through it. Once reopened turns carried attachments pointing into the+ /// conversation store, opening any other chat deleted the pictures out of+ /// the one just left, off disk. The record still named them, so the turn+ /// came back looking as though it had never had an image.+ ///+ /// Half of this is the compiler's now — a `StoredImage` cannot be handed to+ /// `remove` at all — and the half it cannot check is that the release paths+ /// walk a conversation whose pictures are stored ones and delete nothing.+ @MainActor+ @Test func openingAnotherChatDoesNotDeleteAStoredChatsImages() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let folder = try #require(await model.conversationFolderURL(for: id))++ // A stored image, written the way the store writes one, put where the+ // window holds a conversation's pictures: in a turn, in the turns a+ // released KV left on screen, and in the live fields.+ let images = folder.appendingPathComponent("images", isDirectory: true)+ try FileManager.default.createDirectory(+ at: images, withIntermediateDirectories: true)+ let thumbnail = images.appendingPathComponent("abcd.thumb.jpg")+ try Data("thumbnail".utf8).write(to: thumbnail)+ let stored = ChatImage.stored(StoredImage(+ fileURL: thumbnail, displayName: "roof.heic",+ encodedBytes: 9, sha256: "abcd"))+ model.conversation.adoptRestored(+ epoch: UUID(),+ turns: [AppChatTurn(role: .user, text: "look", images: [stored]),+ AppChatTurn(role: .assistant, text: "a roof")],+ kvTokens: 2, boundaryTokenIDs: [], boundaryNeedsReplay: false)+ model.outputImageAttachments = [stored]++ // Every release path a turn goes through.+ model.newChat()+ model.releaseAllAttachments()++ #expect(FileManager.default.fileExists(atPath: thumbnail.path),+ "a stored image was deleted by a release path")+ }++ /// A staged file is still released, or every session leaks its copies.+ @MainActor+ @Test func astagedAttachmentIsStillRemoved() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ // The model is built only so the store root exists to clean up.+ let (_, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ let store = AppImageAttachmentStore()+ let staged = try store.stage(Self.pngFixture())+ #expect(FileManager.default.fileExists(atPath: staged.fileURL.path))+ store.remove(staged)+ #expect(!FileManager.default.fileExists(atPath: staged.fileURL.path))+ }++ /// Raising the context redraws the chat that was refused for it.+ ///+ /// Continuability is a function of the conversation's size and the context+ /// in force, and the window took its answer once, when the row was clicked.+ /// So raising the context from the notice left the chat continuable but+ /// still drawn read-only, under a rule saying earlier turns were out of+ /// context when they no longer were.+ @MainActor+ @Test func raisingTheContextRedrawsAConversationThatNoLongerNeedsIt() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ // Recorded as bigger than a 4K context can hold. Given the tokens+ // rather than told a number: the meta is a projection of the records,+ // so a count written into it by hand would be gone at the next open.+ let store = try #require(model.conversationStore)+ try await Self.padStoredTokens(store, id: id, to: 7_000)+ await model.refreshHistory()++ model.newChat()+ model.setMaxContextTokens(4_096)+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ // Drawn read-only from disk, and drawn whole.+ #expect(model.isShowingStoredCopy)+ #expect(model.transcriptHistory.count == model.screen.document?.pairs.count)+ // And with no context break under it. The break says "the model can no+ // longer see the turns above this", which is a fact about the live+ // conversation; a stored copy is not in the context at all, so the rule+ // was drawn under every turn with nothing below it. This line asserted+ // that older behaviour.+ #expect(model.transcriptContextBreak == nil)+ guard case .needsContext = model.openedConversationState else {+ Issue.record("the chat was not refused for context")+ return+ }+ let refusedRenderID = model.displayedTranscriptID++ model.setMaxContextTokens(8_192)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ #expect(model.openedConversationState == .continuable)+ #expect(model.transcriptContextBreak == nil,+ "the boundary outlived the reason for it")+ #expect(model.conversation.outOfContextPairs.isEmpty)+ // And the renderer is told, or it keeps drawing the rule it already+ // appended: it can add to a transcript but not take anything back.+ #expect(model.displayedTranscriptID != refusedRenderID)+ }++ /// A replay that fails for a reason outside the conversation leaves the row+ /// continuable.+ ///+ /// Every restore failure used to mark the chat "It has no replay record, so+ /// there is nothing to put back into the model's context", and offer to+ /// re-read it into a new chat. For a conversation with images and the+ /// companion pack uninstalled that is simply false: the record is intact,+ /// the pack is missing, and the fix is to put the pack back. Found running+ /// case E46 with the vision pack moved aside.+ @MainActor+ @Test func afailedRestoreDoesNotBlameTheRecord() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ // The kind of failure that is about the runtime, not the record.+ client.failNextRestore(+ with: .conversationRestoreFailed("image support is unavailable"))+ model.promptText = "and again"+ model.send()+ try await waitUntil { await model.error != nil }++ #expect(model.error != nil)+ // Not `.cannotReplay`: nothing about the conversation changed, and the+ // notice that follows from it would tell the user to start again.+ #expect(model.openedConversationState == .continuable)+ }++ /// A record that genuinely cannot be replayed still says so.+ @MainActor+ @Test func aturnWithNoRecordedTokensIsReportedAsUnreplayable() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let folder = try #require(await model.conversationFolderURL(for: id))++ // Strip the tokens from the stored turns: the record cannot be put back+ // into a KV, whatever the runtime is doing.+ let transcript = folder.appendingPathComponent("transcript.jsonl")+ let lines = try String(contentsOf: transcript, encoding: .utf8)+ .split(separator: "\n", omittingEmptySubsequences: true)+ .map { line -> String in+ guard line.contains("\"tokens\"") else { return String(line) }+ guard let data = line.data(using: .utf8),+ var object = try? JSONSerialization.jsonObject(+ with: data) as? [String: Any],+ var turn = object["turn"] as? [String: Any] else {+ return String(line)+ }+ turn.removeValue(forKey: "tokens")+ object["turn"] = turn+ let stripped = try! JSONSerialization.data(withJSONObject: object)+ return String(data: stripped, encoding: .utf8)!+ }+ try (lines.joined(separator: "\n") + "\n").write(+ to: transcript, atomically: true, encoding: .utf8)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ model.promptText = "and again"+ model.send()+ try await waitUntil { await model.error != nil }++ #expect(model.openedConversationState+ == .cannotReplay(reason: .tokenCountUnknown))+ #expect(client.restoredLineages.isEmpty, "a broken record reached the runtime")+ }++ /// A conversation that cannot be read says so.+ ///+ /// The loader used to be `try?`, so a torn or missing transcript left the+ /// row selected over the ordinary empty state — which is exactly what an+ /// unwritten chat looks like. The user could not tell "your conversation is+ /// damaged" from "there is nothing here". Found by hand against a truncated+ /// `transcript.jsonl`.+ @MainActor+ @Test func atornTranscriptIsReportedRatherThanShownAsEmpty() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let folder = try #require(await model.conversationFolderURL(for: id))+ model.newChat()++ // A final record that will not decode. The store drops a torn final+ // *line* on purpose; this is the case it throws on.+ let transcript = folder.appendingPathComponent("transcript.jsonl")+ let data = try String(contentsOf: transcript, encoding: .utf8)+ try (String(data.dropLast(40)) + "\n").write(+ to: transcript, atomically: true, encoding: .utf8)++ model.openConversation(id: id)+ try await waitUntil { await model.error != nil }++ #expect(model.error != nil, "the read failure was swallowed")+ #expect(model.screen.document == nil)+ #expect(!model.hasOutputTranscript, "an unreadable chat drew a transcript")+ // And it is not left waiting to be replayed, which would fail the same+ // way on the next send.+ #expect(!model.isShowingStoredCopy)+ }++ /// A conversation the list cannot read is counted, not just skipped.+ ///+ /// Skipping is right — one bad directory must not hide the rest — but on+ /// its own a chat vanishes with nothing anywhere to say it was ever there.+ ///+ /// The transcript is what is unreadable here. A `conversation.json` that+ /// will not decode is no longer enough to lose a chat: it is a cache of the+ /// records, and the next listing rebuilds it.+ @MainActor+ @Test func aconversationWithAnUnreadableTranscriptIsCountedNotJustDropped()+ async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let folder = try #require(await model.conversationFolderURL(for: id))+ #expect(model.history.entries.count == 1)+ #expect(model.history.unreadableCount == 0)++ // Damage in the middle of the transcript, which is the case that is+ // genuinely unrecoverable: two writers, or corruption in place.+ let transcript = folder.appendingPathComponent("transcript.jsonl")+ var text = try String(contentsOf: transcript, encoding: .utf8)+ text = text.replacingOccurrences(of: "\"type\":\"header\"", with: "\"typ")+ try text.write(to: transcript, atomically: true, encoding: .utf8)+ try "{ not json".write(+ to: folder.appendingPathComponent("conversation.json"),+ atomically: true, encoding: .utf8)+ await model.refreshHistory()++ #expect(model.history.entries.isEmpty, "an unreadable chat was listed")+ #expect(model.history.unreadableCount == 1, "it vanished with no trace")+ #expect(model.historyDiagnostic?.contains(id.uuidString) == true)+ }++ /// A `conversation.json` that will not decode is a cache miss, not a lost+ /// conversation.+ ///+ /// Before the meta became a projection this cost the user the whole chat:+ /// the listing skipped it and nothing ever put it back. The records are the+ /// conversation, so the row comes back with everything it had.+ @MainActor+ @Test func adamagedMetaIsRebuiltFromTheRecordsRatherThanLosingTheChat()+ async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let before = try #require(model.history.entry(id))+ let folder = try #require(await model.conversationFolderURL(for: id))+ let metaURL = folder.appendingPathComponent("conversation.json")++ try "{ not json".write(to: metaURL, atomically: true, encoding: .utf8)+ await model.refreshHistory()++ #expect(model.history.unreadableCount == 0)+ #expect(model.history.entry(id) == before, "the rebuilt row is a different chat")++ // And a meta that is simply gone is the same case.+ try FileManager.default.removeItem(at: metaURL)+ await model.refreshHistory()+ #expect(model.history.entry(id) == before)+ }++ /// A title edited straight into `conversation.json` does not survive.+ ///+ /// Deliberate, and the one behaviour the projection takes away: the file is+ /// a cache of the records, so the only way to rename a conversation from+ /// outside the app is to append a `title` line to its transcript. Manual+ /// case F58 asserts exactly this.+ @MainActor+ @Test func ahandEditToTheStoredTitleIsReplacedAtTheNextOpen() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let store = try #require(model.conversationStore)+ let folder = try #require(await model.conversationFolderURL(for: id))+ let metaURL = folder.appendingPathComponent("conversation.json")++ var edited = try #require(model.history.entry(id))+ edited.title = "typed straight into the file"+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ try encoder.encode(edited).write(to: metaURL)++ #expect(try await store.open(id: id).meta.title == "hello")+ // Appending the record is the supported way, and it holds.+ try await store.rename(id: id, to: "renamed properly")+ #expect(try await store.open(id: id).meta.title == "renamed properly")+ }++ /// The row's Open Folder in Finder needs a folder that is actually there.+ ///+ /// A row can outlive its directory — something outside the app can move or+ /// delete it — and handing Finder a path that does not exist opens nothing+ /// and says nothing. The absence is recorded instead.+ @MainActor+ @Test func thefolderOfAStoredConversationIsFoundAndAMissingOneIsReported()+ async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ let folder = try #require(await model.conversationFolderURL(for: id))+ #expect(folder.lastPathComponent == id.uuidString)+ // The folder itself, holding the three things worth looking at.+ var isDirectory: ObjCBool = false+ #expect(FileManager.default.fileExists(+ atPath: folder.path, isDirectory: &isDirectory))+ #expect(isDirectory.boolValue)+ #expect(FileManager.default.fileExists(+ atPath: folder.appendingPathComponent("transcript.jsonl").path))+ #expect(FileManager.default.fileExists(+ atPath: folder.appendingPathComponent("conversation.json").path))++ model.historyDiagnostic = nil+ try FileManager.default.removeItem(at: folder)+ #expect(await model.conversationFolderURL(for: id) == nil)+ #expect(model.historyDiagnostic != nil, "the absence was swallowed")+ }++ /// One Generate is one replay, however many times it is pressed.+ ///+ /// A deferred replay is not `isRunning`, so nothing refused a second send+ /// while one was in flight — and the window gave no sign of the first, so+ /// pressing again is what a user does. Both replays restored the same+ /// conversation under a fresh epoch each, and the service ended up holding+ /// the second one while the first one's turn had already been stamped with+ /// the first: "turn belongs to conversation A, and the open conversation is+ /// B", with the message lost.+ @MainActor+ @Test func asecondSendDuringAReplayIsRefusedRatherThanStartingAnother() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(120))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ model.promptText = "second"+ model.send()+ // Synchronously, on the same run loop turn as the click: the guard has+ // to be up before the task that does the replay exists. `send()` takes+ // the composer and claims the pipeline before it returns, which is what+ // closes the window a second Generate used to fit through.+ #expect(model.isTurnInFlight)+ #expect(!model.canRun, "a second Generate was still offered")++ model.send()+ model.send()+ try await waitUntil { await model.screen.isReplaying }+ model.send()+ try await waitUntil { await !model.screen.isReplaying }+ try await finish(model)++ #expect(client.restoredLineages.count == 1, "the replay ran more than once")+ #expect(model.error == nil)+ }++ /// The message is on screen for the whole replay.+ ///+ /// The composer empties the moment it is sent, and a reopened conversation+ /// is then prefilled in full before its turn starts — tens of seconds at 8K.+ /// Keyed off `isRunning` the window drew nothing for all of it, so the app+ /// looked like it had swallowed the message.+ @MainActor+ @Test func thepromptIsShownWhileTheReplayRuns() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(120))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ model.promptText = "does this show up?"+ model.send()+ // And out of the composer on the same run loop turn as the click, or a+ // second Generate fits through underneath the first.+ #expect(model.promptText.isEmpty)+ #expect(model.isTurnInFlight)+ try await waitUntil { await model.screen.isReplaying }+ #expect(model.outputPromptText == "does this show up?")+ #expect(model.isTranscriptTurnInFlight, "the transcript would draw this as finished")+ // And the transcript is told to draw it. Gated on `isShowingStoredCopy`+ // alone this was false for the whole replay, so the window showed an+ // "Answer / Processing your prompt" with no question above it.+ #expect(model.showsLiveTurn, "the sent message would not be drawn")+ #expect(model.hasOutputTranscript)+ // And out of the composer at the same moment, or it is on screen twice.+ #expect(model.promptText.isEmpty)++ try await waitUntil { await !model.screen.isReplaying }+ try await finish(model)+ #expect(model.outputPromptText == "does this show up?")+ #expect(model.promptText.isEmpty)+ }++ /// A replay that fails takes the message back out of the transcript.+ ///+ /// The composer still holds it, so leaving a copy in the transcript would+ /// show the same message twice and imply a turn that never happened.+ @MainActor+ @Test func afailedReplayLeavesNoHalfTurnOnScreen() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ client.failNextRestore(with: .conversationRestoreFailed("digest mismatch"))+ model.promptText = "second"+ model.send()+ try await waitUntil { await !model.screen.isReplaying }++ #expect(model.error != nil)+ #expect(model.outputPromptText.isEmpty)+ #expect(model.outputImageAttachments.isEmpty)+ // The composer kept it, so the send can be retried.+ #expect(model.promptText == "second")+ #expect(model.canRun)+ #expect(model.storedConversationID == nil)+ #expect(model.serviceEpoch == nil)++ model.openConversation(id: id)+ try await waitUntil { await model.screen.document?.id == id }+ #expect(model.isShowingStoredCopy,+ "the failed restore left a fast path to a KV that no longer exists")+ }++ /// Switching between two stored chats shows the one that was clicked, and+ /// only that one.+ ///+ /// `openConversation` cleared the archive, the live conversation and the+ /// live fields, but not the stored pairs the display-only path had just+ /// filled, so the second chat's turns were drawn above the first chat's+ /// with both still on screen.+ @MainActor+ @Test func openingASecondChatReplacesTheFirstRatherThanAddingToIt() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "question in the first chat"+ model.send()+ try await finish(model)+ let first = try #require(model.history.selection)++ model.newChat()+ model.promptText = "question in the second chat"+ model.send()+ try await finish(model)+ let second = try #require(model.history.selection)+ #expect(first != second)++ model.newChat()+ model.openConversation(id: first)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ #expect(model.transcriptHistory.map(\.user.text) == ["question in the first chat"])++ model.openConversation(id: second)+ // Synchronously, before the second chat has been read off disk: the+ // first chat's turns are already gone rather than waiting to be+ // overwritten.+ #expect(model.screen.document == nil)+ #expect(model.transcriptHistory.isEmpty)++ try await waitUntil { await !model.transcriptHistory.isEmpty }+ #expect(model.transcriptHistory.map(\.user.text) == ["question in the second chat"])+ }++ /// Reading another chat and coming back costs nothing.+ ///+ /// The KV is untouched by browsing — opening a row only changes what is+ /// drawn — so the conversation the model is holding is still there when the+ /// user returns to it, and the next message continues it directly. Before+ /// this, opening anything started a new lineage on the app's side, so+ /// coming back meant replaying in full a conversation the cache had never+ /// let go of.+ @MainActor+ @Test func lookingAtAnotherChatAndComingBackCostsNoReplay() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let first = try #require(model.history.selection)++ model.newChat()+ model.temperature = 0.65+ model.topKEnabled = true+ model.topK = 23+ model.topPEnabled = true+ model.topP = 0.72+ model.maxNewTokensOverride = 91+ model.promptText = "second"+ model.send()+ try await finish(model)+ let second = try #require(model.history.selection)+ let heldEpoch = model.conversation.epoch++ // Look at the older chat, then come back to the one being held.+ model.openConversation(id: first)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ #expect(model.isShowingStoredCopy)+ #expect(model.displayedTranscriptID != heldEpoch,+ "the transcript would not know it is drawing something else")+ // The held conversation is exactly where it was.+ #expect(model.storedConversationID == second)+ #expect(model.conversation.epoch == heldEpoch)+ #expect(model.serviceEpoch == heldEpoch)++ model.temperature = 0+ model.topK = 1+ model.topP = 1+ model.maxNewTokensOverride = 2++ model.openConversation(id: second)+ #expect(model.screen == .live)+ #expect(model.conversation.epoch == heldEpoch, "the lineage was restarted")+ // The renderer appends and cannot take pairs back, so going out and+ // coming back has to read as two different things to draw. Keyed on the+ // epoch alone — which no longer changes — the chat that was read stayed+ // on screen under the row that was returned to.+ #expect(model.displayedTranscriptID == heldEpoch)+ #expect(model.temperature == 0.65)+ #expect(model.topKEnabled && model.topK == 23)+ #expect(model.topPEnabled && model.topP == 0.72)+ #expect(model.maxNewTokensOverride == 2)++ model.promptText = "third"+ model.send()+ try await finish(model)++ #expect(client.restoredLineages.isEmpty, "coming back paid for a replay")+ #expect(model.conversation.epoch == heldEpoch)+ #expect(model.conversation.turns.count == 4)+ }++ /// While another chat is being read, only that chat is on screen.+ ///+ /// The live conversation is still held, and its newest exchange is still in+ /// the live fields; drawn here it would append one chat's turn to another's+ /// transcript.+ @MainActor+ @Test func readingAnotherChatShowsOnlyThatChat() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "question in the first chat"+ model.send()+ try await finish(model)+ let first = try #require(model.history.selection)++ model.newChat()+ model.promptText = "question in the held chat"+ model.send()+ try await finish(model)++ model.openConversation(id: first)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ #expect(model.transcriptHistory.map(\.user.text)+ == ["question in the first chat"])+ #expect(model.hasOutputTranscript)+ // The held chat's newest exchange is still in the live fields, and is+ // not part of what this one shows.+ #expect(model.outputPromptText == "question in the held chat")+ #expect(!model.showsLiveTurn, "the held chat's turn would be drawn here")+ }++ /// Sending while another chat is on screen still replays that chat, and the+ /// held one is given up at that point rather than at the click.+ @MainActor+ @Test func sendingWhileReadingAnotherChatReplaysIt() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let first = try #require(model.history.selection)++ model.newChat()+ model.promptText = "second"+ model.send()+ try await finish(model)+ let heldEpoch = model.conversation.epoch++ model.openConversation(id: first)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ model.promptText = "into the older one"+ model.send()+ // The replay is a task, and `finish` only waits for a generation: it+ // would return before this one had even started.+ try await waitUntil { client.restoredLineages.count == 1 }+ try await waitUntil { await !model.screen.isReplaying }+ try await finish(model)++ #expect(client.restoredLineages.count == 1)+ #expect(model.storedConversationID == first)+ #expect(model.conversation.epoch != heldEpoch, "the KV was never handed over")+ #expect(!model.isShowingStoredCopy)+ }++ /// Opening a chat must be instant: the transcript is a file, and the+ /// model's context — a full prefill of every token, tens of seconds at 8K —+ /// is not needed until the next message. Paying it on the click made a row+ /// look dead for as long as the replay took.+ @MainActor+ @Test func openingAChatPaysNoReplayAndIsInstant() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(80))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ model.newChat()+ #expect(model.history.selection == nil)++ model.openConversation(id: id)+ // Synchronously, on the same turn of the run loop as the click.+ #expect(model.history.selection == id, "the row did not highlight")+ #expect(model.screen.conversationID == id)+ // `storedConversationID` names the chat the KV is holding, and opening+ // one to read does not make it that. It becomes this id when the replay+ // hands the cache over, not on the click.+ #expect(model.storedConversationID == nil)+ #expect(model.isShowingStoredCopy)+ // And nothing that costs time has started.+ #expect(!model.screen.isReplaying)+ #expect(model.phase == .idle)+ #expect(client.restoredLineages.isEmpty)+ }++ /// A replay is not a generation, so every guard written against `isRunning`+ /// let New Chat through while one was in flight — and the replay then landed+ /// on top of the empty chat, handing back the conversation the user had just+ /// left. The replay now happens inside a send, which is exactly when that+ /// race is reachable.+ @MainActor+ @Test func newChatIsRefusedWhileAReopenIsStillReplaying() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(120))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ // Sending is what triggers the replay.+ model.promptText = "second"+ model.send()+ try await waitUntil { await model.screen.isReplaying }+ #expect(!model.canStartNewChat, "New Chat was offered during a replay")+ // And calling it anyway must not race the replay.+ model.newChat()++ try await waitUntil { await !model.screen.isReplaying }+ #expect(model.storedConversationID == id)+ #expect(!model.isShowingStoredCopy)+ }++ /// A build with nothing to restore through refuses the send rather than+ /// retrying it forever.+ ///+ /// The replay returned successfully when the client had no model lifecycle+ /// behind it — the guard that looked for one treated its absence as "there+ /// is nothing to do" — and the send then handed the message back to the+ /// composer and called `run()` again, with the same conversation still+ /// waiting to be replayed. Nothing on screen changed and the main actor+ /// never came back. Without the fix this test does not fail, it hangs.+ @MainActor+ @Test func areplayWithNoLifecycleBehindItIsRefusedRatherThanRetried() async throws {+ let client = MockInferenceClient(tokenDelayNanos: 0)+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-\(UUID().uuidString)", isDirectory: true)+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(+ at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let model = AppModel(modelDirectory: directory, client: client,+ settingsPersistenceEnabled: true)+ model.modelPathText = directory.path+ model.conversationIdentity = Self.identity+ model.installationStatus = .complete+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ try await model.waitForHistory()++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ model.promptText = "second"+ model.send()+ try await waitUntil { await model.error != nil }++ #expect(!model.screen.isReplaying)+ #expect(model.promptText == "second", "the message was not handed back")+ #expect(model.openedConversationState+ == .cannotReplay(reason: .tokenCountUnknown))+ }++ /// A conversation that cannot take another turn must not be replayed at+ /// all: minutes of prefill to reach a composer that refuses everything.+ @MainActor+ @Test func aconversationThatNoLongerFitsIsNeverReplayed() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let store = try #require(model.conversationStore)++ // Lower the context under what the stored conversation holds. The+ // stored files must not move for it.+ try await Self.padStoredTokens(store, id: id, to: 4_000)+ await model.refreshHistory()+ model.setMaxContextTokens(4_096)++ let listed = try #require(model.history.entry(id))+ guard case .needsContext(let required) = model.continuability(of: listed) else {+ Issue.record("a chat past the ceiling still reported as continuable")+ return+ }+ #expect(required == ConversationGenerationReserve.contextRequired(+ forLineage: 4_000))++ let bytesBefore = try Data(contentsOf: await store.transcriptURL(for: id))+ model.newChat()+ model.openConversation(id: id)+ try await Task.sleep(for: .milliseconds(100))+ #expect(client.restoredLineages.isEmpty, "a chat that cannot fit was replayed")+ #expect(model.openedConversationState == .needsContext(required: required))+ // Readable, and untouched: the row changed, the files did not.+ #expect(!model.transcriptHistory.isEmpty)+ #expect(try Data(contentsOf: await store.transcriptURL(for: id)) == bytesBefore)+ }++ /// New Chat has to stop this window appending to the previous chat's file,+ /// or the transcript on disk would claim a context the model does not have.+ @MainActor+ @Test func newChatStartsItsOwnFileOnTheNextSend() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let first = try #require(model.history.selection)++ model.newChat()+ #expect(model.storedConversationID == nil)+ #expect(model.history.selection == nil)+ // Not written until it is used: an unsent new chat takes no row.+ #expect(model.history.entries.count == 1)++ model.promptText = "second"+ model.send()+ try await finish(model)+ let second = try #require(model.history.selection)+ #expect(second != first)+ #expect(model.history.entries.count == 2)+ }++ /// Delete takes the folder with it. There is no undo because there is no+ /// copy: the alternative kept every deleted conversation on disk for the+ /// life of the store.+ @MainActor+ @Test func deleteRemovesTheChatFromDiskWithNoCopyLeftBehind() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let folder = try #require(await model.conversationFolderURL(for: id))++ model.deleteConversation(id: id)+ try await model.waitForHistory(count: 0)++ #expect(model.history.entries.isEmpty)+ #expect(!FileManager.default.fileExists(atPath: folder.path),+ "the conversation was parked rather than deleted")+ // The open chat lost its file, not its KV, so it stops being written to.+ #expect(model.storedConversationID == nil)+ #expect(model.history.selection == nil)+ // The store keeps nothing on the side.+ let store = folder.deletingLastPathComponent()+ let leftovers = try FileManager.default.contentsOfDirectory(+ atPath: store.path)+ #expect(!leftovers.contains(".trash"))+ }++ /// Deleting the open chat ends its lineage, so the next one describes+ /// itself honestly.+ ///+ /// The KV used to be kept — the model had not forgotten anything — and the+ /// next turn opened a fresh file. But `turnCount` and `kvTokens` are taken+ /// from the live conversation, so that file held one exchange while its+ /// meta described everything behind it: a row reading 1,065 tokens over 22+ /// tokens of record, which the sidebar shows, the gauge shows, and+ /// continuability decides against. Found running case C23.+ @MainActor+ @Test func deletingTheOpenChatEndsItsLineage() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ model.promptText = "second"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ #expect(model.conversation.turns.count == 4)++ model.deleteConversation(id: id)+ try await model.waitForHistory(count: 0)++ // The conversation went with its file.+ #expect(model.conversation.turns.isEmpty, "the deleted chat is still live")+ #expect(!model.hasOutputTranscript)+ #expect(model.storedConversationID == nil)++ model.promptText = "after the delete"+ model.send()+ try await finish(model)++ let newID = try #require(model.history.selection)+ #expect(newID != id)+ let store = try #require(model.conversationStore)+ let opened = try await store.open(id: newID)+ let turns = opened.records.filter {+ if case .turn = $0 { return true } else { return false }+ }+ // What the meta claims is what the file holds.+ #expect(opened.meta.turnCount == turns.count)+ #expect(turns.count == 2)+ let recorded = opened.records.reduce(into: 0) { total, record in+ guard case .turn(let turn) = record else { return }+ total += turn.tokens?.count ?? 0+ }+ #expect(opened.meta.kvTokens == recorded,+ "the row would show a token count the file cannot back")+ }++ /// Deleting the chat being read clears what is on screen, rather than+ /// leaving a transcript with no conversation behind it.+ @MainActor+ @Test func deletingTheChatBeingReadClearsTheTranscript() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let first = try #require(model.history.selection)++ model.newChat()+ model.promptText = "second"+ model.send()+ try await finish(model)++ model.openConversation(id: first)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ #expect(model.isShowingStoredCopy)++ model.deleteConversation(id: first)+ try await model.waitForHistory(count: 1)++ #expect(model.screen == .live)+ // The window falls back to the chat the KV is still holding, so its row+ // is the one selected. Asserted as nil before, which left the second+ // chat on screen with nothing highlighted in the sidebar.+ #expect(model.history.selection == model.storedConversationID)+ #expect(model.history.selection != nil)+ }++ /// A turn carrying an epoch the service is no longer holding is refused+ /// before anything runs.+ ///+ /// The rule is the decode service's own `DecodeConversationGate`, and until+ /// the double ran it every app-side test admitted every turn: a stale epoch,+ /// a skipped position and a correct turn were indistinguishable here, so no+ /// test in this file could tell whether the app and the service agreed about+ /// which conversation was open. Without the gate in `FakeInferenceClient`+ /// this streams an ordinary reply and records nothing.+ @MainActor+ @Test func aturnStampedWithAStaleEpochIsRefusedRatherThanAdmitted() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)++ // Composed against a conversation the service has since replaced.+ model.promptText = "and again"+ let request = try model.makeRequest(+ ticket: AppConversation.Ticket(epoch: UUID(), index: 0))+ var failure: AppInferenceError?+ do {+ for try await event in client.generate(request) {+ if case .failed(let error, _) = event { failure = error }+ }+ Issue.record("the stale turn ran to completion")+ } catch {+ // The stream also throws, the way the real client's does.+ }++ guard case .conversationLineageLost = try #require(failure) else {+ Issue.record("a stale turn was not refused as a lost lineage")+ return+ }+ #expect(client.gateRejections.count == 1)+ guard case .staleConversation = try #require(client.gateRejections.first) else {+ Issue.record("the refusal was not attributed to the stale epoch")+ return+ }+ // And the position the next honest turn has to match is untouched.+ #expect(client.gateCommittedTurns == 1)+ }++ /// The position the service is holding is the position the app's next turn+ /// carries, on a live chat and on a reopened one alike.+ @MainActor+ @Test func theappAndTheGateAgreeOnThePositionAcrossAReopen() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ model.promptText = "second"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ #expect(client.gateCommittedTurns == model.conversation.committedTurns)++ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ model.promptText = "third"+ model.send()+ // A send on a reopened chat replays first, and a replay is not+ // `isRunning`: waiting only on that returns before the turn has begun.+ try await waitUntil { await !model.isTurnInFlight }+ try await finish(model)++ #expect(client.gateRejections.isEmpty,+ "the reopened conversation's turn was numbered against the wrong lineage")+ #expect(client.gateOpenEpoch == model.serviceEpoch)+ #expect(client.gateCommittedTurns == model.conversation.committedTurns)+ #expect(model.conversation.committedTurns == 3)+ }+}++extension AppModel {+ /// Waits for the history list to settle, since it is refreshed from a task.+ @MainActor+ func waitForHistory(count: Int? = nil, timeout: Duration = .seconds(5)) async throws {+ let deadline = Date().addingTimeInterval(5)+ while Date() < deadline {+ if let count {+ if history.entries.count == count { return }+ } else if conversationStore != nil {+ if !history.isReadOnlyStore { return }+ } else {+ return+ }+ try await Task.sleep(for: .milliseconds(5))+ }+ }++ /// Waits for a completed turn to be fully written, records *and* meta.+ ///+ /// The records are not the whole write. `persistCompletedTurn` appends both+ /// halves, then rewrites `conversation.json`, then refreshes the list — so a+ /// helper that waited on the records alone returned inside that window, and+ /// a reopen in the next line read a meta whose `kvTokens` was still nil and+ /// came back `.cannotReplay(.tokenCountUnknown)`. It failed roughly one run+ /// in four under parallel execution and never in isolation.+ @MainActor+ func waitForStoredTurns(atLeast expected: Int) async throws {+ await persistenceTail?.value+ guard let store = conversationStore, let id = storedConversationID else { return }+ let deadline = Date().addingTimeInterval(5)+ while Date() < deadline {+ if let opened = try? await store.open(id: id),+ opened.records.filter({ if case .turn = $0 { return true } else { return false } })+ .count >= expected,+ let entry = history.entry(id), entry.turnCount >= expected {+ return+ }+ try await Task.sleep(for: .milliseconds(5))+ }+ }++}++extension AppModelHistoryTests {+ /// A one-pixel PNG on disk, for the staging path.+ /// Gives a stored conversation exactly `tokens` tokens of record.+ ///+ /// `kvTokens` is projected from the turns now, so a test that needs a chat+ /// too big for a context makes it big rather than writing a number into its+ /// `conversation.json` — which the next open would replace.+ /// A row the notice has refused cannot be sent either.+ ///+ /// `canRun` asked only the live conversation, which is always willing, so+ /// Return on a row marked "needs more context" replayed it anyway: minutes+ /// of prefill, the held chat's KV dropped, and a refusal at the end that+ /// relabelled the row continuable for the next attempt.+ @MainActor+ @Test func arowThatCannotBeContinuedCannotBeSent() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "hello"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let store = try #require(model.conversationStore)+ try await Self.padStoredTokens(store, id: id, to: 4_000)+ await model.refreshHistory()+ model.setMaxContextTokens(4_096)+ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ guard case .needsContext = model.openedConversationState else {+ Issue.record("the padded chat still reported as continuable")+ return+ }++ model.promptText = "more"+ #expect(!model.canRun, "the composer offered a send on a refused row")+ model.send()+ try await Task.sleep(for: .milliseconds(100))++ #expect(client.restoredLineages.isEmpty, "the refused row was replayed")+ #expect(!model.screen.isReplaying)+ #expect(model.screen.conversationID == id)+ #expect(model.promptText == "more", "the message was taken")+ }++ /// A row that could not be read has nowhere for a message to go.+ ///+ /// `deliver` treated only `.reading` as a stored-copy send, so with an+ /// unreadable row on screen the replay stage was skipped and the turn ran+ /// on the held conversation: written into that chat's file while the+ /// sidebar, the notice and the saved selection all named the row that+ /// could not be read.+ @MainActor+ @Test func asendWhileTheRowIsUnreadableDoesNotLandOnTheHeldChat() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "held"+ model.send()+ try await finish(model)+ let held = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)++ // A second chat, written directly, whose transcript will not read.+ let other = try await store.create(+ title: "other", identity: Self.identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: model.currentSampling())+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "one", tokens: [1, 2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "two", tokens: [3])),+ ], to: other.id)+ await model.refreshHistory()+ let folder = try #require(await model.conversationFolderURL(for: other.id))+ let transcript = folder.appendingPathComponent("transcript.jsonl")+ let data = try String(contentsOf: transcript, encoding: .utf8)+ try (String(data.dropLast(40)) + "\n").write(+ to: transcript, atomically: true, encoding: .utf8)++ model.openConversation(id: other.id)+ try await waitUntil { await model.error != nil }+ guard case .unreadable = model.screen else {+ Issue.record("the damaged row did not report as unreadable")+ return+ }++ model.promptText = "where does this go"+ #expect(!model.canRun, "the composer offered a send under an unreadable row")+ model.send()+ try await Task.sleep(for: .milliseconds(100))++ #expect(model.promptText == "where does this go", "the message was taken")+ #expect(model.storedConversationID == held)+ #expect(try await store.open(id: held).meta.turnCount == 2,+ "the turn was written into the held chat under the wrong row")+ #expect(model.history.selection == other.id)+ }++ /// Unload and Reload are closed for the whole send, not just the+ /// generation.+ ///+ /// A deferred replay is a full prefill during which `isRunning` is still+ /// false, so Model > Unload was enabled. Taking it dropped the KV under the+ /// replay, the machine discarded the message it was carrying with no+ /// hand-back, and the unload queued behind the prefill on the service+ /// until the load timeout killed the connection.+ @MainActor+ @Test func unloadIsRefusedWhileAReopenIsStillReplaying() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(120))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ model.promptText = "second"+ model.send()+ try await waitUntil { await model.screen.isReplaying }+ #expect(!model.canUnloadModel, "Unload was offered during a replay")+ #expect(!model.canReloadModel, "Reload was offered during a replay")+ #expect(!model.canLoadModel)+ // And calling it anyway must not take the KV from under the replay.+ model.unloadModel()++ await SendWaiting.turnEnds(model)+ #expect(model.loadState.isReady)+ #expect(model.storedConversationID == id)+ #expect(client.restoredLineages.count == 1)+ #expect(model.conversation.turns.count == 4, "the replayed turn did not run")+ }++ /// A replay refused on this side leaves the held conversation alone.+ ///+ /// The companion pack check runs before the service is asked for anything,+ /// and reporting its refusal as a failed replay ended the held lineage+ /// anyway: its epoch was forgotten and its staged images deleted for a+ /// restore that never happened, while the service still held it.+ @MainActor+ @Test func areplayRefusedBeforeTheServiceKeepsTheHeldChat() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "held"+ model.send()+ try await finish(model)+ let held = try #require(model.storedConversationID)+ let heldEpoch = try #require(model.serviceEpoch)+ let store = try #require(model.conversationStore)++ // A stored chat with a picture in it, at a location with no companion+ // pack: the replay is refused before the restore request is built.+ let placeholder = MultimodalPromptRenderer.imageTokenID+ let pictured = try await store.create(+ title: "pictured", identity: Self.identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: model.currentSampling())+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "look",+ images: [ConversationImageRecord(+ id: UUID(), displayName: "roof.heic",+ pixelsFile: "images/roof.png",+ thumbnailFile: "images/roof.thumb.jpg",+ sourceDigest: "roof", modelInputDigest: "model-roof",+ width: 48, height: 48, softTokens: 2)],+ tokens: [1, placeholder, placeholder, 4])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "a roof", tokens: [5])),+ ], to: pictured.id)+ await model.refreshHistory()+ #expect(!model.isVisionPackInstalled)++ model.openConversation(id: pictured.id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ #expect(model.openedConversationState == .continuable)+ model.promptText = "and this one"+ model.send()+ try await waitUntil { await model.error != nil }++ #expect(client.restoredLineages.isEmpty, "the service was asked after all")+ // The held chat is exactly where it was: same epoch, same file.+ #expect(model.serviceEpoch == heldEpoch)+ #expect(model.storedConversationID == held)+ #expect(model.conversation.epoch == heldEpoch)+ // And the row that was refused is back to what it was.+ #expect(model.screen.conversationID == pictured.id)+ #expect(model.openedConversationState == .continuable)+ #expect(model.promptText == "and this one", "the message was not handed back")+ }++ /// The decode service dying during a replay is the same loss as during a+ /// generation, and has to leave the same state.+ ///+ /// Folded into an ordinary failed replay, the window kept advertising a+ /// ready model: no Retry Load, Generate enabled, and every later send+ /// re-entering the replay to fail on a connection that was already gone.+ @MainActor+ @Test func connectionLossDuringAReplayRequiresAReload() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }++ client.failNextRestore(with: .connectionLost("unexpected EOF"))+ model.promptText = "again"+ model.send()+ try await waitUntil { await model.error != nil }++ guard case .failed(.connectionLost(let cause)) = model.loadState else {+ Issue.record("connection loss during a replay did not invalidate Ready")+ return+ }+ #expect(cause.contains("unexpected EOF"))+ #expect(model.canLoadModel, "no Retry Load after the service died")+ #expect(!model.canRun, "Generate stayed enabled with no service behind it")+ #expect(model.serviceEpoch == nil)+ #expect(model.promptText == "again", "the message was not handed back")+ #expect(model.history.selection == id)++ // After the reload the row is still the one on screen, and sending+ // replays it. Retry Load used to archive the row, clear the selection+ // and send the retried message into a brand-new chat.+ model.loadModel()+ try await waitUntil { await model.loadState.isReady }+ #expect(model.screen.conversationID == id, "Retry Load took the row off screen")+ #expect(model.history.selection == id)+ #expect(model.canRun, "the handed-back message cannot be sent after the reload")+ model.send()+ await SendWaiting.turnEnds(model)+ #expect(client.restoredLineages.count == 1)+ #expect(model.storedConversationID == id)+ }++ /// The chat the KV holds is the live chat, whatever its record says.+ ///+ /// A turn whose stored picture failed to write is still in the KV; its+ /// record just cannot be replayed later. Clicking away and back read that+ /// chat as a copy the composer refuses, with New Chat as the only way out+ /// of a conversation the model was still holding.+ @MainActor+ @Test func clickingBackToTheHeldChatIsLiveEvenWhenItsRecordCannotReplay() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "held"+ model.send()+ try await finish(model)+ let held = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "look", tokens: [1, 2],+ imageWriteFailed: true)),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "a roof", tokens: [3])),+ ], to: held)+ let other = try await store.create(+ title: "other", identity: Self.identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: model.currentSampling())+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "one", tokens: [1, 2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "two", tokens: [3])),+ ], to: other.id)+ await model.refreshHistory()+ let listed = try #require(model.history.entry(held))+ #expect(model.continuability(of: listed)+ == .cannotReplay(reason: .imageRecordMissing))++ model.openConversation(id: other.id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ model.openConversation(id: held)++ #expect(model.screen == .live, "the held chat was read as a copy")+ #expect(model.history.selection == held)+ model.promptText = "more"+ #expect(model.canRun, "the composer refused the chat the KV holds")+ }++ /// A refusal before the model saw the turn leaves the previous turn's+ /// pictures on screen.+ ///+ /// The live fields draw the newest finished turn between sends, and every+ /// hand-back used to clear their pictures: a request that did not validate+ /// made the previous answer's photo vanish from the transcript.+ @MainActor+ @Test func aRefusedSendKeepsThePreviousTurnsPicturesOnScreen() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let folder = try #require(await model.conversationFolderURL(for: id))+ let images = folder.appendingPathComponent("images", isDirectory: true)+ try FileManager.default.createDirectory(+ at: images, withIntermediateDirectories: true)+ let thumbnail = images.appendingPathComponent("abcd.thumb.jpg")+ try Data("thumbnail".utf8).write(to: thumbnail)+ model.outputImageAttachments = [ChatImage.stored(StoredImage(+ fileURL: thumbnail, displayName: "roof.heic",+ encodedBytes: 9, sha256: "abcd"))]++ // Refused by `AppGenerationRequest.validate`, after the composer has+ // been handed over.+ model.maxNewTokensOverride = 0+ model.promptText = "second"+ model.send()+ await SendWaiting.turnEnds(model)++ #expect(model.promptText == "second", "the message was not handed back")+ #expect(model.error != nil, "the refusal was silent")+ #expect(model.outputImageAttachments.count == 1,+ "the previous turn's picture was cleared from the transcript")+ }++ /// The composer's pictures are closed for the whole send, replay included.+ ///+ /// The picture guards asked `isRunning`, which a deferred replay never+ /// sets, so a picture attached during the replay met the draft-wins rule+ /// when the replay failed and the sent message's own pictures were+ /// deleted.+ @MainActor+ @Test func theComposersPicturesCannotBeChangedDuringAReplay() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(120))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ let attachments = AppImageAttachmentStore()++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ model.promptText = "second"+ model.send()+ try await waitUntil { await model.screen.isReplaying }++ let source = try Self.pngFixture()+ defer { try? FileManager.default.removeItem(at: source) }+ let staged = try attachments.stage(source)+ defer { attachments.remove(staged) }+ model.setComposerAttachmentsForTesting([staged])+ model.clearImages()+ #expect(model.imageAttachments.count == 1,+ "the composer's pictures were cleared during a replay")+ model.removeImage(id: staged.id)+ #expect(model.imageAttachments.count == 1,+ "a picture was removed during a replay")+ await SendWaiting.turnEnds(model)+ model.setComposerAttachmentsForTesting([])+ }++ /// Quit waits for the last exchange to reach disk.+ @MainActor+ @Test func awaitingPersistenceLeavesTheLastExchangeOnDisk() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "durable"+ model.send()+ await SendWaiting.turnEnds(model)+ await model.awaitPendingPersistence()++ let id = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)+ #expect(try await store.open(id: id).meta.turnCount == 2,+ "the exchange was not on disk after the wait")+ }++ /// Deleting right after the reply waits for that reply's write.+ ///+ /// The write starts when the reply lands and `isTurnInFlight` is already+ /// false, so the delete used to run under it: the writer recreated the+ /// directory and the append left a headerless transcript the list then+ /// counted as unreadable, with no row left to delete.+ @MainActor+ @Test func deletingRightAfterTheReplyLeavesNothingBehind() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "gone"+ model.send()+ await SendWaiting.turnEnds(model)+ let id = try #require(model.storedConversationID)+ let folder = try #require(await model.conversationFolderURL(for: id))++ model.deleteConversation(id: id)+ try await waitUntil { await model.history.entries.isEmpty }++ #expect(!FileManager.default.fileExists(atPath: folder.path),+ "the delete left the directory behind")+ #expect(model.history.unreadableCount == 0)+ let diagnostic: String = model.historyDiagnostic ?? ""+ #expect(model.historyDiagnostic == nil, "the delete reported: \(diagnostic)")+ }++ /// The image writer reads links of its own.+ ///+ /// It read the turn's retained links, which New Chat or a replay of+ /// another chat releases the moment the reply lands; a write still in its+ /// decode then lost its source, the turn was recorded as missing a+ /// picture, and the conversation refused every replay after.+ @MainActor+ @Test func theImageWriterKeepsItsOwnLinkToTheSource() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let attachments = AppImageAttachmentStore()+ let (model, root) = try await readyModel(client, attachmentStore: attachments)+ defer { try? FileManager.default.removeItem(at: root) }++ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.history.selection)+ let source = try Self.pngFixture()+ defer { try? FileManager.default.removeItem(at: source) }+ let staged = try attachments.stage(source)++ model.beginStoringTurnImages([staged], in: id)+ // Released as early as a hand-off or New Chat would release it.+ attachments.remove(staged)+ let outcome = await model.pendingTurnImageWrite?.value++ #expect(outcome?.failed == 0,+ "the write lost its source: \(outcome?.reason ?? "no reason")")+ #expect(outcome?.records.count == 1)+ }++ /// A store without the writer lock writes nothing, including into a chat+ /// this window adopted from another window's files.+ ///+ /// The existing id used to be returned before the read-only check, so a+ /// replayed chat had its images written into the other window's directory+ /// before the append itself was refused.+ @MainActor+ @Test func aReadOnlyStoreNeverWritesIntoAnotherWindowsChat() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(1))+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-\(UUID().uuidString)", isDirectory: true)+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(+ at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ // Another instance holds the writer lock first.+ let holder = ConversationStore(+ rootURL: ConversationStoreLocation.url(forModelDirectory: directory))+ try await holder.activate()++ let model = AppModel(modelDirectory: directory, client: client,+ settingsPersistenceEnabled: true)+ model.modelPathText = directory.path+ model.conversationIdentity = Self.identity+ try await client.ensureLoaded(+ modelDirectory: directory,+ maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions,+ forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ model.installationStatus = .complete+ try await waitUntil { await model.history.isReadOnlyStore }+ #expect(model.history.isReadOnlyStore)++ model.storedConversationID = UUID()+ let written = await model.ensureStoredConversation(firstMessage: "x")+ #expect(written == nil, "a read-only store handed back a chat to write into")+ withExtendedLifetime(holder) {}+ }++ static func padStoredTokens(_ store: ConversationStore, id: UUID,+ to tokens: Int) async throws {+ let held = try await store.open(id: id).meta.kvTokens ?? 0+ let padding = tokens - held+ guard padding >= 2 else {+ Issue.record("the conversation already holds \(held) token(s)")+ return+ }+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "padding",+ tokens: Array(repeating: Int32(7), count: padding - 1))),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "ok", tokens: [8])),+ ], to: id)+ }++ static func pngFixture() throws -> URL {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("pixel-\(UUID().uuidString).png")+ let base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8"+ + "z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="+ try #require(Data(base64Encoded: base64)).write(to: url)+ return url+ }+}++private actor HistoryListGate {+ private var continuation: CheckedContinuation<Void, Never>?+ private var entered = false+ private var isOpen = false++ func wait() async {+ entered = true+ guard !isOpen else { return }+ await withCheckedContinuation { continuation = $0 }+ }++ func waitUntilEntered() async {+ while !entered { await Task.yield() }+ }++ func open() {+ isOpen = true+ continuation?.resume()+ continuation = nil+ }+}++/// Polls a condition the app satisfies from a task rather than synchronously.+func waitUntil(_ condition: @Sendable () async -> Bool) async throws {+ let deadline = Date().addingTimeInterval(5)+ while Date() < deadline {+ if await condition() { return }+ try await Task.sleep(for: .milliseconds(5))+ }+}+++extension AppModelHistoryTests {+ @MainActor+ @Test func replayWaitsForPreviouslyCommittedTurnsToReachDisk() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(20))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ let gate = HistoryListGate()+ model.promptText = "second"+ model.send()+ try await waitUntil { client.isGenerating }+ model.pendingTurnImageWrite = Task {+ await gate.wait()+ return TurnImageWriteOutcome()+ }+ try await waitUntil { await !model.isTurnInFlight }+ try #require(!model.isTurnInFlight)+ await gate.waitUntilEntered()+ model.newChat()+ model.openConversation(id: id)+ try await waitUntil { await model.screen.document != nil }+ model.promptText = "third"+ model.send()+ // Leave the save blocked long enough for an incorrect replay to finish.+ try await Task.sleep(for: .milliseconds(300))+ #expect(client.restoredLineages.isEmpty)+ await gate.open()+ await SendWaiting.turnEnds(model)+ await model.awaitPendingPersistence()+ let store = try #require(model.conversationStore)+ let disk = try await store.open(id: id).records.compactMap { record -> String? in+ if case .turn(let turn) = record, turn.role == .user { return turn.text }+ return nil+ }+ let live = model.conversation.turns.filter { $0.role == .user }.map(\.text)+ #expect(live == disk)+ }++ @MainActor+ @Test func rewindWaitsForPreviouslyCommittedImagesBeforeSweeping() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(20))+ let (model, root) = try await readyModel(client)+ defer { try? FileManager.default.removeItem(at: root) }+ model.promptText = "first"+ model.send()+ try await finish(model)+ let id = try #require(model.storedConversationID)+ let store = try #require(model.conversationStore)+ let directory = await store.imagesURL(for: id)+ let pixels = directory.appendingPathComponent("second.png")+ let thumbnail = directory.appendingPathComponent("second.thumb.jpg")+ try Data("pixels".utf8).write(to: pixels)+ try Data("thumb".utf8).write(to: thumbnail)+ let gate = HistoryListGate()+ let outcome = imageOutcome("second")+ model.promptText = "second"+ model.send()+ try await waitUntil { client.isGenerating }+ model.pendingTurnImageWrite = Task {+ await gate.wait()+ return outcome+ }+ try await waitUntil { await !model.isTurnInFlight }+ try #require(!model.isTurnInFlight)+ await gate.waitUntilEntered()+ let orphan = directory.appendingPathComponent("rewound.png")+ try Data("orphan".utf8).write(to: orphan)+ client.failNextGeneration(with: .unknown("injected rewind"))+ model.promptText = "third"+ model.send()+ try await Task.sleep(for: .milliseconds(300))+ #expect(FileManager.default.fileExists(atPath: pixels.path))+ #expect(FileManager.default.fileExists(atPath: thumbnail.path))+ await gate.open()+ await SendWaiting.turnEnds(model)+ let saved = try await store.open(id: id)+ #expect(saved.meta.imageCount == 1)+ #expect(model.promptText == "third")+ #expect(!FileManager.default.fileExists(atPath: orphan.path))+ #expect(FileManager.default.fileExists(atPath: pixels.path))+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelSendPipelineTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelSendPipelineTests.swiftnew file mode 100644index 00000000..204fe733--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppModelSendPipelineTests.swift@@ -0,0 +1,310 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// Every way the send path can fail, and the one thing all of them owe the+/// user: the message comes back, exactly once, with the pictures it was sent+/// with, and nothing is left behind in the conversation the model can see.+///+/// A table rather than seven hand-written tests, because the defect class here+/// is a stage nobody wrote a hand-back for. `run()` had two halves that passed+/// the composer between them, and three defects were one half not knowing what+/// the other had already done: a replay that overwrote the message that started+/// it, a hand-back that dropped the pictures, and a stop that stranded the+/// retained links its next run then overwrote.+@Suite(.serialized) struct AppModelSendPipelineTests {+ /// The stage that fails.+ enum Stage: String, CaseIterable, Sendable, CustomTestStringConvertible {+ /// What is on disk cannot be put back into the KV at all.+ case replayRefused+ /// The runtime could not put it back this time.+ case replayFailed+ /// The request does not validate.+ case requestInvalid+ /// The turn's images cannot be given a reference of their own.+ case retainFailed+ /// The stream failed after the turn had started.+ case generationFailed+ /// Stop reached the turn and the runtime rewound it.+ case generationCancelled+ /// The KV no longer holds the conversation the turn was composed+ /// against.+ case lineageLost++ var testDescription: String { rawValue }++ /// Whether the stage needs a stored conversation on screen to reach.+ var replaysFirst: Bool { self == .replayRefused || self == .replayFailed }+ }++ private static let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private static let message = "the message this stage must hand back"++ /// The whole world one stage needs, and the cleanup for it.+ @MainActor+ private struct Fixture {+ let model: AppModel+ let root: URL+ let attachments: AppImageAttachmentStore++ func tearDown() {+ model.releaseAllAttachments()+ try? FileManager.default.removeItem(at: root)+ }+ }++ @MainActor+ private func makeFixture(client: any AppInferenceClient) throws -> Fixture {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("send-pipeline-\(UUID().uuidString)",+ isDirectory: true)+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ let fixture = try makeCompleteModelInstall("send-pipeline")+ try FileManager.default.moveItem(at: fixture, to: directory)+ let receiptURL = directory.appendingPathComponent("verified-install.json")+ var receipt = try #require(+ JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL))+ as? [String: Any])+ receipt["modelDirectoryPath"] = directory.standardizedFileURL.path+ try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys])+ .write(to: receiptURL)+ try installVisionCompanion(forTextModel: directory)+ let attachments = AppImageAttachmentStore(+ directoryURL: root.appendingPathComponent("staged", isDirectory: true))+ let model = AppModel(modelDirectory: directory, client: client,+ attachmentStore: attachments,+ settingsPersistenceEnabled: true)+ model.modelPathText = directory.path+ // Read from the installed model's manifest in the app; a temporary+ // directory has none, and identity is not what this covers.+ model.conversationIdentity = Self.identity+ model.installationStatus = .complete+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ return Fixture(model: model, root: root, attachments: attachments)+ }++ private func client(for stage: Stage) -> any AppInferenceClient {+ switch stage {+ case .replayRefused:+ // The one double in the tree with no model lifecycle behind it, so+ // the replay has nothing to restore through.+ return MockInferenceClient(tokenDelayNanos: 0)+ case .generationFailed:+ return TerminalEventClient(+ .failed(.unknown("the stream broke"), partial: nil))+ case .generationCancelled:+ return TerminalEventClient(.cancelled(Self.diagnostics))+ case .lineageLost:+ return TerminalEventClient(+ .failed(.conversationLineageLost("the gate refused the turn"),+ partial: nil))+ case .replayFailed, .requestInvalid, .retainFailed:+ return FakeInferenceClient(eventDelay: .milliseconds(1))+ }+ }++ @MainActor+ @Test(arguments: Stage.allCases)+ func everyFailingStageHandsTheMessageBackOnceAndLeavesNoTurnBehind(+ _ stage: Stage+ ) async throws {+ let client = self.client(for: stage)+ let fixture = try makeFixture(client: client)+ defer { fixture.tearDown() }+ let model = fixture.model+ try await model.waitForHistory()++ if stage.replaysFirst {+ // A stored conversation to reopen, and a screen showing it rather+ // than the live chat. Written through the store rather than sent:+ // neither client here is loaded, so a send would rewind and leave+ // a row with no token record, which the composer now refuses to+ // send before either stage can be reached.+ let store = try #require(model.conversationStore)+ // Activation takes the writer lock on its own task, and+ // `waitForHistory` returns before it has; a write before then is+ // refused as read-only.+ try await waitUntil { await !store.isReadOnly }+ let stored = try await store.create(+ title: "the conversation this stage reopens",+ identity: Self.identity,+ session: ConversationSessionSettings(+ contextTokens: model.maxContextTokens, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: model.currentSampling())+ try await store.append([+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: "earlier", tokens: [1, 2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "before", tokens: [3])),+ ], to: stored.id)+ await model.refreshHistory()+ model.openConversation(id: stored.id)+ try await waitUntil { await !model.transcriptHistory.isEmpty }+ #expect(model.openedConversationState == .continuable,+ "the reopened row is not one the composer would send")+ }+ if stage == .replayFailed {+ (client as? FakeInferenceClient)?.failNextRestore(+ with: .conversationRestoreFailed("the restore was refused"))+ }+ if stage == .requestInvalid {+ // Refused by `AppGenerationRequest.validate`, which the pipeline+ // reaches after the composer has already been handed over.+ model.maxNewTokensOverride = 0+ }+ // A real picture, not a byte string: the stored copy is a preprocess+ // and a resize, so an unreadable one would make the write below finish+ // instantly with nothing to collect and the sweep assertions vacuous.+ let source = try AppModelHistoryTests.pngFixture()+ defer { try? FileManager.default.removeItem(at: source) }+ let staged = try fixture.attachments.stage(source)+ if stage == .retainFailed {+ // A regular file where `retain` needs a directory, so every hard+ // link fails the same way. After the stage above, which is what+ // creates the staging directory it goes in.+ try Data().write(to: fixture.attachments.directoryURL+ .appendingPathComponent("retained", isDirectory: false))+ }+ model.promptText = Self.message+ model.setComposerAttachmentsForTesting([staged])+ let turnsBefore = model.conversation.turns.count++ model.send()+ // Taken on the click, before any stage runs: this is what closes the+ // window a second Generate used to fit through.+ #expect(model.promptText.isEmpty, "the composer was not handed over")+ #expect(model.imageAttachments.isEmpty, "the pictures were not handed over")+ await SendWaiting.turnEnds(model)++ #expect(model.promptText == Self.message, "the message was not handed back")+ #expect(model.imageAttachments.count == 1,+ "the pictures did not come back with it")+ #expect(model.imageAttachments.first?.id == staged.id)+ // Handed back once. A second `restoreComposer` would find the composer+ // already holding this message and delete the very files it had just+ // put there, which is invisible in the array and obvious on disk.+ for attachment in model.imageAttachments {+ #expect(FileManager.default.fileExists(atPath: attachment.fileURL.path),+ "the hand-back ran twice and deleted its own files")+ }+ #expect(model.conversation.turns.count == turnsBefore,+ "a failed stage left its turn in the conversation")+ #expect(!model.conversation.hasTurnInFlight)+ #expect(model.error != nil, "the stage failed silently")+ #expect(!model.isTurnInFlight)+ #expect(model.outputImageAttachments.isEmpty,+ "the transcript kept a reference to the handed-back pictures")+ if stage == .lineageLost {+ #expect(model.conversation.isLineageLost)+ }+ }++ /// The message goes back once even when the composer was used again while+ /// the turn was in flight — and the turn's own copies are released rather+ /// than left behind.+ @MainActor+ @Test func acomposerUsedDuringTheTurnKeepsItsOwnDraft() async throws {+ let fixture = try makeFixture(+ client: TerminalEventClient(.failed(.unknown("broken"), partial: nil)))+ defer { fixture.tearDown() }+ let model = fixture.model+ try await model.waitForHistory()++ let sent = try fixture.attachments.stage(+ data: Data("sent".utf8), displayName: "sent.png")+ model.promptText = "the message that failed"+ model.setComposerAttachmentsForTesting([sent])+ model.send()+ model.promptText = "a new draft"+ let drafted = try fixture.attachments.stage(+ data: Data("drafted".utf8), displayName: "drafted.png")+ model.setComposerAttachmentsForTesting([drafted])+ await SendWaiting.turnEnds(model)++ #expect(model.promptText == "a new draft")+ #expect(model.imageAttachments.map(\.id) == [drafted.id])+ #expect(FileManager.default.fileExists(atPath: drafted.fileURL.path))+ #expect(model.conversation.turns.isEmpty)+ }++ /// A rewound turn's image write ends before the sweep that collects after+ /// it.+ ///+ /// `beginStoringTurnImages` set `pendingTurnImageWrite` and only+ /// `persistCompletedTurn` cleared it, which a cancelled or failed turn never+ /// reaches: the app read as permanently mid-write to anything that asked+ /// whether a turn was finished, and `sweepImagesOfRewoundTurn` raced the+ /// very write it exists to collect after — deleting nothing, or deleting a+ /// file being written. Without the fix `pendingTurnImageWrite` is still+ /// there when the send returns.+ @MainActor+ @Test func arewoundTurnEndsItsImageWriteBeforeTheSweepRuns() async throws {+ let fixture = try makeFixture(+ client: TerminalEventClient(.cancelled(Self.diagnostics)))+ defer { fixture.tearDown() }+ let model = fixture.model+ try await model.waitForHistory()++ // A committed turn first, so the conversation is on disk and the+ // rewound turn below has an images directory to be swept.+ model.promptText = "the turn that lands"+ model.send()+ await SendWaiting.turnEnds(model)++ let source = try AppModelHistoryTests.pngFixture()+ defer { try? FileManager.default.removeItem(at: source) }+ let staged = try fixture.attachments.stage(source)+ model.promptText = "the turn that is stopped"+ model.setComposerAttachmentsForTesting([staged])+ model.send()+ await SendWaiting.turnEnds(model)++ #expect(model.pendingTurnImageWrite == nil,+ "the app still reads as mid-write after a rewound turn")+ let id = try #require(model.storedConversationID)+ let images = try #require(await model.conversationFolderURL(for: id))+ .appendingPathComponent("images", isDirectory: true)+ let left = (try? FileManager.default.contentsOfDirectory(+ at: images, includingPropertiesForKeys: nil,+ options: [.skipsHiddenFiles])) ?? []+ #expect(left.isEmpty,+ "the sweep left \(left.count) file(s) no record names")+ }++ private static let diagnostics = AppDiagnostics(+ generatedTokens: 0, stopReason: .cancelled,+ timeToFirstTokenSeconds: 0, decodeSeconds: 0, tokensPerSecond: 0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())+}++/// A client whose generation is one terminal event and nothing else.+///+/// The stages a terminal event reaches — a rewind, a stream failure, a lost+/// lineage — are otherwise arranged by racing a double, and a race is not a+/// test of what the app does with the outcome.+private final class TerminalEventClient: AppInferenceClient, @unchecked Sendable {+ private let event: AppInferenceEvent++ init(_ event: AppInferenceEvent) {+ self.event = event+ }++ func generate(_ request: AppGenerationRequest)+ -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream { continuation in+ continuation.yield(event)+ continuation.finish()+ }+ }++ func cancel() {}+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swiftindex e70789d7..d685982c 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift@@ -23,7 +23,7 @@ import Testing}@MainActor- @Test func startingAnotherRunClearsPreviousServiceTranscriptSynchronously() {+ @Test func startingAnotherRunClearsThePreviousServiceTranscriptBeforeItsFirstToken() async {let client = ReportingInferenceClient(memoryBytes: 2_100_000_000)let model = AppModel(client: client)let directory = FileManager.default.temporaryDirectory@@ -32,7 +32,8 @@ import Testingclient.generationTranscriptMailbox.append("previous completion")model.promptText = "new prompt"- model.run()+ model.send()+ await SendWaiting.generationStarts(model)#expect(client.generationTranscriptMailbox.completeText.isEmpty)#expect(model.outputPromptText == "new prompt")diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelSidebarStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelSidebarStateTests.swiftnew file mode 100644index 00000000..1d2bcacd--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppModelSidebarStateTests.swift@@ -0,0 +1,121 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++/// The button, the View menu item and Cmd+Ctrl+S are one action against one+/// persisted setting. Three places reading three different states is how a+/// toggle ends up saying "Hide" while the sidebar is already hidden.+@Suite struct AppModelSidebarStateTests {+ @MainActor+ @Test func terminationPersistsUnsavedSamplingChanges() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("quit-settings-\(UUID().uuidString)", isDirectory: true)+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let model = AppModel(modelDirectory: directory, settingsPersistenceEnabled: true)+ model.modelPathText = directory.path+ // Slider bindings update the model without invoking a persistence action.+ model.temperature = 0.35+ model.topK = 17+ model.topP = 0.8+ model.shutdownForTermination()+ let reopened = AppModel(modelDirectory: directory, settingsPersistenceEnabled: true)+ #expect(reopened.temperature == 0.35)+ #expect(reopened.topK == 17)+ #expect(reopened.topP == 0.8)+ }++ @MainActor+ @Test func theToggleFlipsAndPersists() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("sidebar-\(UUID().uuidString)", isDirectory: true)+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(+ at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }++ let model = AppModel(modelDirectory: directory,+ settingsPersistenceEnabled: true)+ model.modelPathText = directory.path+ #expect(model.isSidebarVisible, "the list is shown by default")++ model.toggleSidebar()+ #expect(!model.isSidebarVisible)++ // A new model over the same directory has to come back hidden: the+ // window remembering its shape is the whole reason this is persisted.+ let reopened = AppModel(modelDirectory: directory,+ settingsPersistenceEnabled: true)+ #expect(!reopened.isSidebarVisible)++ model.setSidebarVisible(true)+ let again = AppModel(modelDirectory: directory,+ settingsPersistenceEnabled: true)+ #expect(again.isSidebarVisible)+ }++ /// The Inspector toggle is the sidebar toggle's mirror and is persisted+ /// separately: hiding one panel must not move the other, or the window+ /// comes back a shape nobody asked for.+ @MainActor+ @Test func theInspectorTogglePersistsIndependentlyOfTheSidebar() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("inspector-\(UUID().uuidString)", isDirectory: true)+ let directory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(+ at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }++ let model = AppModel(modelDirectory: directory,+ settingsPersistenceEnabled: true)+ model.modelPathText = directory.path+ #expect(model.isInspectorVisible, "the Inspector is shown by default")++ model.toggleInspector()+ #expect(!model.isInspectorVisible)+ #expect(model.isSidebarVisible, "hiding one panel moved the other")++ let reopened = AppModel(modelDirectory: directory,+ settingsPersistenceEnabled: true)+ #expect(!reopened.isInspectorVisible)+ #expect(reopened.isSidebarVisible)+ }++ /// New Chat is guarded rather than silently doing nothing, so the button+ /// and the menu item can be disabled instead of looking broken.+ @MainActor+ @Test func newChatIsRefusedWhileRunningAndBeforeAModelExists() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(20))+ let directory = FileManager.default.temporaryDirectory+ let model = AppModel(modelDirectory: directory, client: client)+ model.modelPathText = directory.path++ // No model installed yet: there is no chat to start.+ #expect(model.requiresModelInstallation)+ #expect(!model.canStartNewChat)++ try await client.ensureLoaded(+ modelDirectory: directory,+ maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions,+ forceLogitsHead: true) { _ in }+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)+ model.installationStatus = .complete+ #expect(model.canStartNewChat)++ model.promptText = "hello"+ model.send()+ await SendWaiting.generationStarts(model)+ #expect(model.isRunning)+ #expect(!model.canStartNewChat)+ let epoch = model.conversation.epoch+ // And the guard is real, not only advisory: calling it anyway must not+ // pull the lineage out from under a running turn.+ model.newChat()+ #expect(model.conversation.epoch == epoch)++ await SendWaiting.turnEnds(model)+ #expect(model.canStartNewChat)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swiftindex daab1472..c671eca9 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift@@ -2,6 +2,35 @@ import Foundationimport Testing@testable import TurboFieldfareAppCore+@Suite struct AppInferenceErrorDiagnosticTests {+ /// What crosses a process boundary is the cause, not the sentence. The+ /// decode service forwarded `"\(error)"` — which is the sentence — and the+ /// client wrapped it again, so a failed replay read "This conversation+ /// could not be reopened: This conversation could not be reopened: image+ /// support is unavailable: …". Found running case E46 with the vision pack+ /// moved aside.+ @Test func adiagnosticMessageCarriesTheCauseWithoutTheSentence() {+ let error = AppInferenceError.conversationRestoreFailed(+ "image support is unavailable")+ #expect(error.userMessage+ == "This conversation could not be reopened: image support is unavailable")+ #expect(error.diagnosticMessage == "image support is unavailable")+ // Re-wrapping the diagnostic says it once; re-wrapping the sentence+ // said it twice.+ let rewrapped = AppInferenceError.conversationRestoreFailed(+ error.diagnosticMessage)+ #expect(rewrapped.userMessage == error.userMessage)+ }++ /// A case with no message of its own falls back to its own wording rather+ /// than to an empty string.+ @Test func acaseWithoutAMessageStillReportsSomething() {+ #expect(!AppInferenceError.modelNotLoaded.diagnosticMessage.isEmpty)+ #expect(AppInferenceError.modelNotLoaded.diagnosticMessage+ == AppInferenceError.modelNotLoaded.userMessage)+ }+}+@Suite struct AppModelTests {@MainActor@Test func defaultsUseSampledRequest() throws {@@ -95,9 +124,8 @@ import Testingmodel.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))#expect(!model.hasStaleLoadedRuntime)- // Away from the default, which is 8K: setting the value it already has- // would prove nothing.- model.maxContextTokens = AppContextLengthOption.sixteenK.tokens+ // 8K is the default now, so changing to it changes nothing.+ model.setMaxContextTokens(AppContextLengthOption.sixteenK.tokens)#expect(model.hasStaleLoadedRuntime)}@@ -106,7 +134,7 @@ import Testinglet model = AppModel()model.modelPathText = FileManager.default.temporaryDirectory.pathmodel.promptText = "go"- model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens+ model.setMaxContextTokens(AppContextLengthOption.sixtyFourK.tokens)#expect(try model.makeRequest().maxNewTokens == AppContextLengthOption.sixtyFourK.tokens)}@@ -163,7 +191,7 @@ import Testingmodel.setShowPromptExamples(true)model.promptText = "first turn"- model.run()+ model.send()await waitForIdle(model)#expect(model.promptText.isEmpty)@@ -183,11 +211,9 @@ import Testingmodel.loadState = .ready(modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1)model.promptText = "go"model.maxNewTokensOverride = 4- model.run()+ model.send()- for _ in 0..<200 where model.isRunning {- try? await Task.sleep(nanoseconds: 5_000_000)- }+ await SendWaiting.turnEnds(model)#expect(!model.isRunning)#expect(model.outputText.contains("alpha beta"))@@ -201,10 +227,14 @@ import Testinglet model = readyModel(client: client)model.promptText = "original prompt"model.maxNewTokensOverride = 1- model.run()+ model.send()+ // The composer clears on the click; the transcript picks the message up+ // one stage later, when the request has been built and its images+ // retained.+ #expect(model.promptText.isEmpty)+ await SendWaiting.generationStarts(model)#expect(model.outputPromptText == "original prompt")- #expect(model.promptText.isEmpty)#expect(model.hasOutputTranscript)#expect(model.outputResponsePlainText.isEmpty)#expect(model.outputConversationPlainText == "You:\noriginal prompt")@@ -228,7 +258,8 @@ import Testingmodel.promptText = "original prompt"model.maxNewTokensOverride = 1- model.run()+ model.send()+ await SendWaiting.generationStarts(model)#expect(model.isRunning)#expect(model.outputPromptText == "original prompt")@@ -243,12 +274,15 @@ import Testing}@MainActor- @Test func failedValidationDoesNotClearPrompt() {+ @Test func failedValidationDoesNotClearPrompt() async {let model = readyModel(client: MockInferenceClient(response: "answer"))model.promptText = "keep invalid prompt"model.maxNewTokensOverride = 0- model.run()+ model.send()+ // The composer is handed over before the request is built, so the+ // message comes back a hop later rather than never having left.+ await SendWaiting.turnEnds(model)#expect(!model.isRunning)#expect(model.promptText == "keep invalid prompt")@@ -280,7 +314,7 @@ import Testinglet model = readyModel(client: client)model.promptText = "stop after token"model.maxNewTokensOverride = 10- model.run()+ model.send()for _ in 0..<200 where model.liveTokenCount == 0 {try? await Task.sleep(nanoseconds: 5_000_000)@@ -314,7 +348,7 @@ import Testingclient.prefillSteps = 20let model = readyModel(client: client)model.promptText = "prefill prompt"- model.run()+ model.send()for _ in 0..<200 where model.livePrefillDone == 0 {try? await Task.sleep(nanoseconds: 5_000_000)@@ -341,7 +375,7 @@ import Testinglet model = readyModel(client: client)model.promptText = "fail"- model.run()+ model.send()await waitForIdle(model)#expect(model.error?.userMessage == "synthetic failure")@@ -389,8 +423,6 @@ import Testing@MainActorprivate func waitForIdle(_ model: AppModel) async {- for _ in 0..<200 where model.isRunning {- try? await Task.sleep(nanoseconds: 5_000_000)- }+ await SendWaiting.turnEnds(model)}}diff --git a/Tests/TurboFieldfareApp/Core/State/AppPresentationVisionGateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppPresentationVisionGateTests.swiftindex 59f1a33b..6d1bf76d 100644--- a/Tests/TurboFieldfareApp/Core/State/AppPresentationVisionGateTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppPresentationVisionGateTests.swift@@ -5,7 +5,7 @@ import Testing/// The banner offers exactly the model actions the model will actually perform.////// `canLoadModel`, `canReloadModel` and `canUnloadModel` all refuse while a-/// companion operation is in flight, but the presentation snapshot carried no+/// companion filesystem mutation is in flight, but the presentation snapshot carried no/// vision state — so this resolved to "Installed · Not loaded" with a `.load`/// action, and `ModelActionBanner` rendered it as a fully enabled button whose/// click did nothing for the whole 1.5 GB transfer.@@ -27,7 +27,7 @@ import TestingisRunning: false,isGenerationCancellationPending: false,generationPhase: .idle,- isVisionCompanionOperationInProgress: companionOperationInProgress)+ isVisionFilesystemMutationInProgress: companionOperationInProgress)}@Test func anUnloadedModelOffersLoadWhenNoCompanionOperationRuns() {@@ -39,7 +39,7 @@ import Testing/// The case the banner got wrong: unloaded — which every companion/// operation requires — with a transfer running.- @Test func noModelActionIsOfferedWhileACompanionOperationRuns() {+ @Test func noModelActionIsOfferedWhileACompanionFilesystemMutationRuns() {let state = AppPresentationState.resolve(snapshot(companionOperationInProgress: true))#expect(state.primaryAction == nil,@@ -50,7 +50,7 @@ import Testing/// Not just the unloaded case: a stale runtime otherwise offers Reload, and/// `canReloadModel` refuses for the same reason.- @Test func astaleRuntimeOffersNoReloadWhileACompanionOperationRuns() {+ @Test func astaleRuntimeOffersNoReloadWhileACompanionFilesystemMutationRuns() {let ready = AppModelLoadState.ready(modelDirectory: Self.modelDirectory, loadSeconds: 1)diff --git a/Tests/TurboFieldfareApp/Core/State/AppVisionActivationTests.swift b/Tests/TurboFieldfareApp/Core/State/AppVisionActivationTests.swiftindex 17b41006..7f115b20 100644--- a/Tests/TurboFieldfareApp/Core/State/AppVisionActivationTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppVisionActivationTests.swift@@ -15,6 +15,25 @@ import TurboFieldfareRepackCorereturn model}+ @MainActor+ @Test func payloadDownloadCanCoexistWithTextGenerationButActivationCannot() throws {+ let directory = try makeCompleteModelInstall("vision-download-generation")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(modelDirectory: directory,+ client: FakeInferenceClient())+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 0)+ model.promptText = "text remains available"++ model.visionInstallState = .copyingPayload(+ reusedBytes: 0, downloadedThisRunBytes: 1, totalBytes: 2)+ #expect(model.canRun)+ #expect(model.canUnloadModel)++ model.visionInstallState = .activating+ #expect(!model.canRun)+ #expect(!model.canUnloadModel)+ }+@MainActor@Test func activationReportsHowFarItsVerificationHasGot() async throws {let installer = MockVisionPackInstallerClient(diff --git a/Tests/TurboFieldfareApp/Core/State/ConversationScreenMachineTests.swift b/Tests/TurboFieldfareApp/Core/State/ConversationScreenMachineTests.swiftnew file mode 100644index 00000000..6570f026--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/ConversationScreenMachineTests.swift@@ -0,0 +1,550 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// Every cell of `(screen, event)`, one row each.+///+/// The machine exists because the six fields it replaces were never enumerated:+/// each defect was one more combination nobody had thought about, and the fix+/// for each was one more line in one more branch. A table cannot be fixed that+/// way — a cell either has a row or the completeness test at the bottom fails —+/// and a new screen case or a new event fails to compile until every cell it+/// creates is written down.+@Suite struct ConversationScreenMachineTests {+ @Test(arguments: [false, true])+ func adversarialOldReadCannotReplaceReopenedSameChat(failure: Bool) {+ var machine = ConversationScreenMachine()+ let firstRead = UUID()+ let latestRead = Self.renderA+ for (id, readID) in [(Self.row, firstRead), (Self.other, UUID()), (Self.row, latestRead)] {+ _ = machine.apply(.rowClicked(+ id: id, heldID: Self.held, kvMatchesHeld: true,+ state: .continuable, renderID: readID))+ }+ _ = machine.apply(.documentLoaded(+ id: Self.row, renderID: Self.renderA, document: Self.reloaded, state: .continuable))+ let latest = machine.screen+ let effects = failure+ ? machine.apply(.documentFailed(id: Self.row, renderID: firstRead, Self.unreadableError))+ : machine.apply(.documentLoaded(+ id: Self.row, renderID: firstRead, document: Self.stored, state: .continuable))+ #expect(machine.screen == latest)+ #expect(effects.isEmpty)+ }++ @Test func adversarialLateDocumentDuringReplayCannotResetSampling() {+ var machine = ConversationScreenMachine()+ _ = machine.apply(Self.clicked(Self.row))+ _ = machine.apply(.sendRequested(Self.pending))+ let effects = machine.apply(.documentLoaded(+ id: Self.row, renderID: Self.renderB, document: Self.stored, state: .continuable))+ #expect(machine.screen.isReplaying)+ #expect(machine.screen.document == Self.stored)+ #expect(!effects.contains(.applySampling(Self.sampling)))+ if case .replaying(_, _, let pending, _) = machine.screen {+ #expect(pending == Self.pending)+ }+ }++ // MARK: - Fixtures++ private static let held = UUID()+ private static let row = UUID()+ private static let other = UUID()+ private static let renderA = UUID()+ private static let renderB = UUID()+ private static let epoch = UUID()++ private static let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private static let sampling = ConversationSampling(+ temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 8_192)++ private static func document(_ id: UUID, text: String) -> ConversationDocument {+ let meta = ConversationMeta(+ id: id, title: "stored", createdAt: Date(), updatedAt: Date(),+ identity: identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "on-demand"),+ sampling: sampling)+ let records: [TranscriptRecord] = [+ .header(ConversationHeaderRecord(id: id, createdAt: Date())),+ .turn(ConversationTurnRecord(+ role: .user, at: Date(), text: text, tokens: [1, 2])),+ .turn(ConversationTurnRecord(+ role: .assistant, at: Date(), text: "answer", tokens: [3])),+ ]+ return ConversationDocument.load(+ ConversationOpenResult(meta: meta, records: records,+ isReadOnly: false, droppedTornFinalLine: false),+ directory: URL(fileURLWithPath: "/tmp/conversations/\(id.uuidString)",+ isDirectory: true))+ }++ private static let stored = document(row, text: "as it was clicked")+ private static let reloaded = document(row, text: "as the load found it")+ private static let elsewhere = document(other, text: "another chat")++ private static let pending = PreparedTurn(+ prompt: "the message that started the replay", images: [])+ private static let unreadableError =+ AppInferenceError.conversationUnreadable("its final record will not read")+ private static let restoreError =+ AppInferenceError.conversationRestoreFailed("image support is unavailable")+ private static let recordError = AppInferenceError.conversationRestoreFailed(+ ConversationRecordError.turnWithoutTokens.description)++ private static let live = ConversationScreen.live+ private static let reading = ConversationScreen.reading(+ id: row, document: stored, state: .continuable, renderID: renderA)+ private static let readingHeld = ConversationScreen.reading(+ id: held, document: stored, state: .continuable, renderID: renderA)+ private static let readingRefused = ConversationScreen.reading(+ id: row, document: stored, state: .needsContext(required: 9_000),+ renderID: renderA)+ private static let replaying = ConversationScreen.replaying(+ id: row, document: stored, pending: pending, renderID: renderA)+ private static let unreadable = ConversationScreen.unreadable(+ id: row, error: unreadableError)++ /// A click on `id`, with the KV holding `held` and matching it.+ private static func clicked(+ _ id: UUID, state: ConversationContinuability = .continuable,+ heldID: UUID? = held, kvMatchesHeld: Bool = true+ ) -> ConversationScreenMachine.Event {+ .rowClicked(id: id, heldID: heldID, kvMatchesHeld: kvMatchesHeld,+ state: state, renderID: renderB)+ }++ struct Row: Sendable, CustomTestStringConvertible {+ let name: String+ let screen: ConversationScreen+ let event: ConversationScreenMachine.Event+ let expected: ConversationScreen+ let effects: [ConversationScreenMachine.Effect]++ var testDescription: String { name }+ }++ // MARK: - The matrix++ static let rows: [Row] = [+ // MARK: live+ Row(name: "live + a click on another row reads it",+ screen: live, event: clicked(other),+ expected: .reading(id: other, document: nil, state: .continuable,+ renderID: renderB),+ effects: [.select(other), .dropOutOfContextTurns,+ .loadDocument(other, renderID: renderB)]),+ Row(name: "live + a click on the row the KV holds rebuilds nothing",+ screen: live, event: clicked(held),+ expected: .live,+ effects: [.select(held), .dropOutOfContextTurns]),+ // The record's replayability is beside the point: the chat is in the+ // KV. Reading it as a copy instead locked the user out of the+ // conversation the model was holding.+ Row(name: "live + a click on the held row whose record cannot be replayed still rebuilds nothing",+ screen: live,+ event: clicked(held, state: .cannotReplay(reason: .imageRecordMissing)),+ expected: .live,+ effects: [.select(held), .dropOutOfContextTurns]),+ Row(name: "live + a click on the held row whose KV was rebuilt reads it",+ screen: live, event: clicked(held, kvMatchesHeld: false),+ expected: .reading(id: held, document: nil, state: .continuable,+ renderID: renderB),+ effects: [.select(held), .dropOutOfContextTurns,+ .loadDocument(held, renderID: renderB)]),+ Row(name: "live + a click on the held row that no longer fits reads it",+ screen: live,+ event: clicked(held, state: .needsContext(required: 9_000)),+ expected: .reading(id: held, document: nil,+ state: .needsContext(required: 9_000),+ renderID: renderB),+ effects: [.select(held), .dropOutOfContextTurns,+ .loadDocument(held, renderID: renderB)]),+ Row(name: "live + a context change redraws nothing",+ screen: live,+ event: .contextChanged(state: .continuable, heldID: held,+ kvMatchesHeld: true, renderID: renderB),+ expected: .live, effects: []),+ Row(name: "live + a document that landed after the screen went live",+ screen: live, event: .documentLoaded(id: row, renderID: Self.renderA, document: stored,+ state: .continuable),+ expected: .live, effects: []),+ Row(name: "live + a read that failed after the screen went live",+ screen: live,+ event: .documentFailed(id: row, renderID: Self.renderA, unreadableError),+ expected: .live, effects: []),+ Row(name: "live + a send is an ordinary turn",+ screen: live, event: .sendRequested(pending),+ expected: .live, effects: []),+ Row(name: "live + a replay that landed after the screen went live",+ screen: live,+ event: .replaySucceeded(id: row, document: stored, epoch: epoch,+ kvTokens: 12),+ expected: .live, effects: []),+ Row(name: "live + a replay failure that landed after the screen went live",+ screen: live, event: .replayFailed(id: row, error: restoreError),+ expected: .live, effects: []),+ Row(name: "live + a replay that never started, after the screen went live",+ screen: live, event: .replayNotStarted(id: row, error: restoreError),+ expected: .live, effects: []),+ Row(name: "live + a refused record that landed after the screen went live",+ screen: live, event: .replayRefused(id: row, error: recordError),+ expected: .live, effects: []),+ Row(name: "live + New Chat selects no row",+ screen: live, event: .newChat,+ expected: .live,+ effects: [.releaseImagesOfHeldConversation(includingLiveTurn: true),+ .select(nil)]),+ Row(name: "live + deleting a chat that is not on screen",+ screen: live, event: .deleted(id: other, heldID: held),+ expected: .live, effects: []),+ Row(name: "live + the KV going ends the chat and its selection",+ screen: live, event: .lineageEnded,+ expected: .live, effects: [.select(nil)]),++ // MARK: reading+ Row(name: "reading + a click on a third row replaces what is drawn",+ screen: reading, event: clicked(other),+ expected: .reading(id: other, document: nil, state: .continuable,+ renderID: renderB),+ effects: [.select(other), .dropOutOfContextTurns,+ .loadDocument(other, renderID: renderB)]),+ Row(name: "reading + a click back on the held row goes live",+ screen: reading, event: clicked(held),+ expected: .live,+ effects: [.select(held), .dropOutOfContextTurns]),+ Row(name: "reading + a context change redraws the row against the new answer",+ screen: reading,+ event: .contextChanged(state: .needsContext(required: 9_000),+ heldID: held, kvMatchesHeld: true,+ renderID: renderB),+ expected: .reading(id: row, document: nil,+ state: .needsContext(required: 9_000),+ renderID: renderB),+ effects: [.select(row), .dropOutOfContextTurns,+ .loadDocument(row, renderID: renderB)]),+ Row(name: "reading the held row + a context change that lets it fit again",+ screen: readingHeld,+ event: .contextChanged(state: .continuable, heldID: held,+ kvMatchesHeld: true, renderID: renderB),+ expected: .live,+ effects: [.select(held), .dropOutOfContextTurns]),+ Row(name: "reading + its document lands and moves the sliders with it",+ screen: reading, event: .documentLoaded(id: row, renderID: Self.renderA, document: reloaded,+ state: .continuable),+ expected: .reading(id: row, document: reloaded, state: .continuable,+ renderID: renderA),+ effects: [.applySampling(sampling)]),+ Row(name: "reading + a document for a row that is no longer on screen",+ screen: reading, event: .documentLoaded(id: other, renderID: Self.renderA, document: elsewhere,+ state: .continuable),+ expected: reading, effects: []),+ Row(name: "reading a row that cannot be continued + its document lands",+ screen: readingRefused, event: .documentLoaded(+ id: row, renderID: Self.renderA, document: reloaded, state: .continuable),+ expected: .reading(id: row, document: reloaded,+ state: .continuable,+ renderID: renderA),+ effects: [.applySampling(sampling)]),+ Row(name: "reading + the read failed, so the row says why",+ screen: reading,+ event: .documentFailed(id: row, renderID: Self.renderA, unreadableError),+ expected: .unreadable(id: row, error: unreadableError),+ effects: [.reportError(unreadableError)]),+ Row(name: "reading + a failure for a row that is no longer on screen",+ screen: reading,+ event: .documentFailed(id: other, renderID: Self.renderA, unreadableError),+ expected: reading, effects: []),+ Row(name: "reading + a send replays the row first",+ screen: reading, event: .sendRequested(pending),+ expected: .replaying(id: row, document: stored, pending: pending,+ renderID: renderA),+ effects: [.replay(id: row, pending: pending)]),+ // Refused at the machine as well as at the composer. Replaying a row+ // the notice has refused put tokens recorded under another checkpoint+ // into the KV, or dropped the held chat for a restore the context+ // could not hold, and a failure then relabelled the row continuable.+ Row(name: "reading a row that cannot be continued + a send is refused",+ screen: readingRefused, event: .sendRequested(pending),+ expected: readingRefused, effects: []),+ Row(name: "reading + a replay that belongs to an earlier send",+ screen: reading,+ event: .replaySucceeded(id: row, document: stored, epoch: epoch,+ kvTokens: 12),+ expected: reading, effects: []),+ Row(name: "reading + a replay failure that belongs to an earlier send",+ screen: reading, event: .replayFailed(id: row, error: restoreError),+ expected: reading, effects: []),+ Row(name: "reading + a replay that never started, from an earlier send",+ screen: reading, event: .replayNotStarted(id: row, error: restoreError),+ expected: reading, effects: []),+ Row(name: "reading + a refused record that belongs to an earlier send",+ screen: reading, event: .replayRefused(id: row, error: recordError),+ expected: reading, effects: []),+ Row(name: "reading + New Chat leaves the row",+ screen: reading, event: .newChat,+ expected: .live,+ effects: [.releaseImagesOfHeldConversation(includingLiveTurn: true),+ .select(nil)]),+ Row(name: "reading + deleting the row selects the chat that comes back",+ screen: reading, event: .deleted(id: row, heldID: held),+ expected: .live, effects: [.select(held)]),+ Row(name: "reading + deleting another chat leaves the screen alone",+ screen: reading, event: .deleted(id: other, heldID: held),+ expected: reading, effects: []),+ Row(name: "reading + the KV going takes the read copy with it",+ screen: reading, event: .lineageEnded,+ expected: .live, effects: [.select(nil)]),++ // MARK: replaying+ Row(name: "replaying + a click is refused",+ screen: replaying, event: clicked(other),+ expected: replaying, effects: []),+ Row(name: "replaying + a context change is refused",+ screen: replaying,+ event: .contextChanged(state: .continuable, heldID: held,+ kvMatchesHeld: true, renderID: renderB),+ expected: replaying, effects: []),+ Row(name: "replaying + the click's read lands under it",+ screen: replaying, event: .documentLoaded(id: row, renderID: Self.renderA, document: reloaded,+ state: .continuable),+ expected: .replaying(id: row, document: reloaded, pending: pending,+ renderID: renderA),+ effects: []),+ Row(name: "replaying + a document for another row",+ screen: replaying, event: .documentLoaded(id: other, renderID: Self.renderA, document: elsewhere,+ state: .continuable),+ expected: replaying, effects: []),+ Row(name: "replaying + the click's read failed, which the replay reports itself",+ screen: replaying,+ event: .documentFailed(id: row, renderID: Self.renderA, unreadableError),+ expected: replaying, effects: []),+ Row(name: "replaying + a second send is refused",+ screen: replaying,+ event: .sendRequested(PreparedTurn(+ prompt: "again", images: [])),+ expected: replaying, effects: []),+ Row(name: "replaying + it landed, so the held turn starts",+ screen: replaying,+ event: .replaySucceeded(id: row, document: reloaded, epoch: epoch,+ kvTokens: 12),+ expected: .live,+ effects: [.releaseImagesOfHeldConversation(includingLiveTurn: false),+ .adoptRestored(reloaded, epoch: epoch, kvTokens: 12),+ .select(row),+ .startTurn(pending)]),+ Row(name: "replaying + a replay of a chat that is no longer on screen",+ screen: replaying,+ event: .replaySucceeded(id: other, document: elsewhere, epoch: epoch,+ kvTokens: 12),+ expected: replaying, effects: []),+ Row(name: "replaying + it failed on the runtime, so the row stays continuable",+ screen: replaying, event: .replayFailed(id: row, error: restoreError),+ expected: .reading(id: row, document: stored, state: .continuable,+ renderID: renderA),+ effects: [.endFailedReplayLineage,+ .restoreComposer(pending, restoreError)]),+ // No lineage end: the service was never asked, so the held chat and+ // its pictures are exactly where they were. Ending it here deleted+ // the held chat's staged images for a restore that had not happened.+ Row(name: "replaying + it was refused before the service, so the held chat stays",+ screen: replaying,+ event: .replayNotStarted(id: row, error: restoreError),+ expected: .reading(id: row, document: stored, state: .continuable,+ renderID: renderA),+ effects: [.restoreComposer(pending, restoreError)]),+ Row(name: "replaying + a refusal for a chat that is no longer on screen",+ screen: replaying,+ event: .replayNotStarted(id: other, error: restoreError),+ expected: replaying, effects: []),+ Row(name: "replaying + the record cannot be replayed, so the row says so",+ screen: replaying, event: .replayRefused(id: row, error: recordError),+ expected: .reading(id: row, document: stored,+ state: .cannotReplay(reason: .tokenCountUnknown),+ renderID: renderA),+ effects: [.restoreComposer(pending, recordError)]),+ Row(name: "replaying + New Chat, whose replay can no longer land",+ screen: replaying, event: .newChat,+ expected: .live,+ effects: [.releaseImagesOfHeldConversation(includingLiveTurn: true),+ .select(nil)]),+ Row(name: "replaying + deleting the chat being replayed hands the message back",+ screen: replaying, event: .deleted(id: row, heldID: held),+ expected: .live,+ effects: [.restoreComposer(pending, nil), .select(held)]),+ Row(name: "replaying + a refused record whose fresh read said why",+ screen: replaying,+ event: .replayRefused(id: row, error: recordError,+ state: .needsContext(required: 9_000)),+ expected: .reading(id: row, document: stored,+ state: .needsContext(required: 9_000),+ renderID: renderA),+ effects: [.restoreComposer(pending, recordError)]),+ // The replay can no longer land, and the send waiting on it stops+ // when it finds the screen gone. The message goes back here or it+ // goes nowhere: dropped with the screen, the prompt and its staged+ // pictures were never handed back to anything.+ Row(name: "replaying + the KV going under it hands the message back",+ screen: replaying, event: .lineageEnded,+ expected: .live,+ effects: [.restoreComposer(pending, nil), .select(nil)]),++ // MARK: unreadable+ Row(name: "unreadable + a click on another row reads that one",+ screen: unreadable, event: clicked(other),+ expected: .reading(id: other, document: nil, state: .continuable,+ renderID: renderB),+ effects: [.select(other), .dropOutOfContextTurns,+ .loadDocument(other, renderID: renderB)]),+ Row(name: "unreadable + a context change cannot make it readable",+ screen: unreadable,+ event: .contextChanged(state: .continuable, heldID: held,+ kvMatchesHeld: true, renderID: renderB),+ expected: unreadable, effects: []),+ Row(name: "unreadable + a document that landed after the failure",+ screen: unreadable, event: .documentLoaded(id: row, renderID: Self.renderA, document: stored,+ state: .continuable),+ expected: unreadable, effects: []),+ Row(name: "unreadable + a second failure for the same row",+ screen: unreadable,+ event: .documentFailed(id: row, renderID: Self.renderA, unreadableError),+ expected: unreadable, effects: []),+ // Nothing to replay and nothing a message could go to: the composer+ // is closed for this screen, and a send that reached the pipeline+ // anyway is handed back rather than run on the held chat under the+ // row that could not be read.+ Row(name: "unreadable + a send is refused",+ screen: unreadable, event: .sendRequested(pending),+ expected: unreadable, effects: []),+ Row(name: "unreadable + a replay that landed after the failure",+ screen: unreadable,+ event: .replaySucceeded(id: row, document: stored, epoch: epoch,+ kvTokens: 12),+ expected: unreadable, effects: []),+ Row(name: "unreadable + a replay failure that landed after it",+ screen: unreadable, event: .replayFailed(id: row, error: restoreError),+ expected: unreadable, effects: []),+ Row(name: "unreadable + a replay that never started, landing after it",+ screen: unreadable,+ event: .replayNotStarted(id: row, error: restoreError),+ expected: unreadable, effects: []),+ Row(name: "unreadable + a refused record that landed after it",+ screen: unreadable, event: .replayRefused(id: row, error: recordError),+ expected: unreadable, effects: []),+ Row(name: "unreadable + New Chat clears the notice",+ screen: unreadable, event: .newChat,+ expected: .live,+ effects: [.releaseImagesOfHeldConversation(includingLiveTurn: true),+ .select(nil)]),+ Row(name: "unreadable + deleting the chat that could not be read",+ screen: unreadable, event: .deleted(id: row, heldID: held),+ expected: .live, effects: [.select(held)]),+ Row(name: "unreadable + the KV going",+ screen: unreadable, event: .lineageEnded,+ expected: .live, effects: [.select(nil)]),+ ]++ // MARK: - The table is the test++ @Test(arguments: rows)+ func themachineMakesExactlyTheTransitionTheTableStates(_ row: Row) {+ var machine = ConversationScreenMachine(screen: row.screen)++ let effects = machine.apply(row.event)++ #expect(machine.screen == row.expected)+ #expect(effects == row.effects)+ }++ /// A cell with no row is a transition nobody decided, which is what the six+ /// fields were made of. Adding a screen case or an event fails here until+ /// its cells are written down.+ @Test func everyCellOfTheMatrixHasARow() {+ var covered: Set<String> = []+ for row in Self.rows {+ covered.insert("\(row.screen.shape.rawValue) + \(row.event.shape.rawValue)")+ }+ var missing: [String] = []+ for screen in ConversationScreen.allShapes {+ for event in ConversationScreenMachine.Event.allShapes+ where !covered.contains("\(screen.rawValue) + \(event.rawValue)") {+ missing.append("\(screen.rawValue) + \(event.rawValue)")+ }+ }+ #expect(missing.isEmpty, "no row for \(missing.joined(separator: ", "))")+ #expect(covered.count+ == ConversationScreen.allShapes.count+ * ConversationScreenMachine.Event.allShapes.count)+ }++ /// A fresh machine shows the live conversation, which is what a window with+ /// no history at all shows.+ @Test func amachineStartsOnTheLiveConversation() {+ #expect(ConversationScreenMachine().screen == .live)+ }++ /// Two clicks on the same row are two different things to draw.+ ///+ /// Keyed on the conversation's own id instead, re-opening it after the+ /// context changed was not a change the renderer could see, so a chat that+ /// had just become continuable kept the boundary rule saying its earlier+ /// turns were out of context.+ @Test func reopeningTheSameRowIsANewThingToDraw() {+ var machine = ConversationScreenMachine()+ let first = UUID()+ let second = UUID()+ _ = machine.apply(.rowClicked(id: Self.row, heldID: Self.held,+ kvMatchesHeld: true, state: .continuable,+ renderID: first))+ guard case .reading(_, _, _, let one) = machine.screen else {+ Issue.record("the click did not read the row")+ return+ }+ _ = machine.apply(.rowClicked(id: Self.row, heldID: Self.held,+ kvMatchesHeld: true, state: .continuable,+ renderID: second))+ guard case .reading(_, _, _, let two) = machine.screen else {+ Issue.record("the second click did not read the row")+ return+ }+ #expect(one == first)+ #expect(two == second)+ #expect(one != two)+ }+++ /// The composer's answer is the notice's answer. `conversation.canSend`+ /// alone let a row the notice had refused be sent anyway.+ @Test func onlyTheLiveChatAndAContinuableRowAllowASend() {+ #expect(Self.live.allowsSend)+ #expect(Self.reading.allowsSend)+ #expect(!Self.readingRefused.allowsSend)+ #expect(!ConversationScreen.reading(+ id: Self.row, document: Self.stored,+ state: .cannotReplay(reason: .differentCheckpoint),+ renderID: Self.renderA).allowsSend)+ #expect(!Self.replaying.allowsSend)+ #expect(!Self.unreadable.allowsSend)+ }++ /// A send holds its render identity, so the transcript is not rebuilt at the+ /// moment the replay starts.+ @Test func asendKeepsTheTranscriptThatIsAlreadyOnScreen() {+ var machine = ConversationScreenMachine(screen: Self.reading)+ _ = machine.apply(.sendRequested(Self.pending))+ guard case .replaying(_, _, _, let renderID) = machine.screen else {+ Issue.record("the send did not start a replay")+ return+ }+ #expect(renderID == Self.renderA)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/ImageReleaseSitesTests.swift b/Tests/TurboFieldfareApp/Core/State/ImageReleaseSitesTests.swiftnew file mode 100644index 00000000..f76f937f--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/ImageReleaseSitesTests.swift@@ -0,0 +1,92 @@+import Foundation+import Testing++/// Where a staged picture may be deleted, and nowhere else.+///+/// The compiler already refuses a `StoredImage`, which is the half that used to+/// cost a stored conversation its pictures. The half it cannot check is *how+/// many* places delete a staged one: several call sites, each with its own idea of+/// when it applied, is how a release ran on a path nobody meant it to and how a+/// turn's copies were left behind on a path that forgot. This is a grep, and it+/// fails until a new call site is written down here with the reason it exists.+@Suite struct ImageReleaseSitesTests {+ /// Every file in the app that calls `AppImageAttachmentStore.remove`, and+ /// how many times.+ ///+ /// `AppModel.swift`, eight, all of them the composer's own lifecycle or the+ /// send's hand-off:+ ///+ /// 1. `addImages` — a staging batch is all-or-nothing, so the copies made+ /// before a failure are referenced by nothing.+ /// 2. `removeImage` — the user took one picture off the composer.+ /// 3. `clearImages` — the user emptied the composer.+ /// 4. `finishAddingImages` — a batch that landed after a run started, which+ /// has already snapshotted its own images.+ /// 5. `finishAddingImages` — the copies past the capacity two overlapping+ /// adds pushed it to.+ /// 6. `deliver`, stage 4 — the links made before a retain failed.+ /// 7. `deliver`, the hand-off — the composer's own copies, now that the turn+ /// is carried by its retained links.+ /// 8. `restoreComposer` — the turn's copies when the composer was used again+ /// while it was in flight, so the draft's are the ones that survive.+ ///+ /// `AppModelHistory.swift`, five. Three inside the one effect handler+ /// `releaseImagesOfHeldConversation`: the out-of-context turns, the live+ /// conversation's turns, and — only when the transition says so — the+ /// pictures the live fields are still drawing. Two for the writer's own+ /// links: `beginStoringTurnImages` releasing the ones made before a+ /// retain failed, and `writeStoredImages` releasing them all once the+ /// stored copies are written.+ private static let allowed: [String: Int] = [+ "Core/State/AppModel.swift": 8,+ "Core/State/AppModelHistory.swift": 5,+ ]++ private static let needle = "attachmentStore.remove("++ @Test func stagedPicturesAreDeletedOnlyWhereThisListSaysTheyAre() throws {+ let sources = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent() // State+ .deletingLastPathComponent() // Core+ .deletingLastPathComponent() // TurboFieldfareApp+ .deletingLastPathComponent() // Tests+ .deletingLastPathComponent() // the tree's root+ .appendingPathComponent("Sources/TurboFieldfareApp", isDirectory: true)+ var isDirectory: ObjCBool = false+ // Otherwise a scan that found nothing would read as a clean tree.+ #expect(FileManager.default.fileExists(+ atPath: sources.path, isDirectory: &isDirectory) && isDirectory.boolValue,+ "the app's sources are not at \(sources.path)")++ var found: [String: Int] = [:]+ let enumerator = try #require(FileManager.default.enumerator(+ at: sources, includingPropertiesForKeys: nil))+ var scanned = 0+ for case let url as URL in enumerator where url.pathExtension == "swift" {+ scanned += 1+ let text = try String(contentsOf: url, encoding: .utf8)+ let count = text.components(separatedBy: Self.needle).count - 1+ guard count > 0 else { continue }+ let relative = url.standardizedFileURL.path+ .replacingOccurrences(of: sources.standardizedFileURL.path + "/",+ with: "")+ found[relative] = count+ }+ #expect(scanned > 0, "no Swift files were scanned")++ for (file, count) in found.sorted(by: { $0.key < $1.key }) {+ guard let expected = Self.allowed[file] else {+ Issue.record(Comment(rawValue:+ "\(file) deletes staged pictures and is not on the "+ + "allow-list: add it with the reason it exists"))+ continue+ }+ #expect(count == expected,+ "\(file) has \(count) release site(s), \(expected) listed")+ }+ for file in Self.allowed.keys.sorted() where found[file] == nil {+ Issue.record(Comment(rawValue:+ "\(file) is on the allow-list and releases nothing: take it off"))+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swiftindex 055dc6e5..ac4a4edf 100644--- a/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swift+++ b/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swift@@ -1,5 +1,7 @@import Foundationimport Synchronization+import TurboFieldfare+import TurboFieldfareDecodeProtocol@testable import TurboFieldfareAppCore@@ -9,6 +11,24 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {var conversationEpochs: [UUID] = []var resetFailure: AppInferenceError?var stopRequested = false+ var restoredLineages: [AppConversationLineage] = []+ var restoreFailure: AppInferenceError?+ var generationFailure: AppInferenceError?+ /// What the KV would hold, so a stored conversation records a count.+ var conversationTokens = 0+ /// The service's own admission rule, running here rather than being+ /// restated. The app's agreement with it is the one thing no app-side+ /// test could observe while this double ignored the ticket entirely:+ /// every turn was admitted, so a stale epoch or a skipped position read+ /// exactly like a correct one.+ var gate = DecodeConversationGate()+ /// Every turn the gate refused, in order. A correct app produces none.+ var gateRejections: [DecodeConversationGate.Rejection] = []+ /// How many placeholder tokens one attached image contributes to a+ /// turn's recorded IDs. Zero until a caller measures a real+ /// preprocessed image, because replay locates an image by finding its+ /// placeholder run inside the turn that cites it.+ var imageSoftTokens = 0}enum CancelSemantics: Sendable { case hardAbort, cooperativeStop }@@ -48,6 +68,12 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {maxContextTokens: maxContextTokens,options: options,forceLogitsHead: forceLogitsHead)+ // A load builds a new runner and an empty KV, so whatever epoch was+ // open names tokens that no longer exist. The service ends the+ // lineage here for exactly that reason, and an app that resumed+ // onto the rebuilt cache would have every turn refused from then on.+ $0.gate.endLineage()+ $0.conversationTokens = 0}onState(.ready(modelDirectory: modelDirectory.standardizedFileURL,@@ -56,7 +82,48 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {func unload() async {cancel()- state.value.withLock { $0.loadedKey = nil }+ state.value.withLock {+ $0.loadedKey = nil+ // The runner and its KV are gone, so the epoch names tokens that no+ // longer exist. The service ends the lineage here for that reason.+ $0.gate.endLineage()+ }+ }++ /// What the gate holds right now, so a test can assert the app and the+ /// service agree about which conversation is open and how far into it.+ var gateOpenEpoch: UUID? { state.value.withLock { $0.gate.openEpoch } }+ var gateCommittedTurns: Int { state.value.withLock { $0.gate.committedTurns } }+ var gateRejections: [DecodeConversationGate.Rejection] {+ state.value.withLock { $0.gateRejections }+ }++ /// Whether a generation is still running. The app clears `isRunning` on the+ /// terminal event, which the stream yields before it finishes, so the two+ /// are not the same question.+ var isGenerating: Bool { generationTasks.hasActiveGeneration }++ /// Moves the loaded session's context without ending the lineage.+ ///+ /// The window requires a reload after a context change and the walk draws+ /// that reload as its own operation, so this is only the double keeping up+ /// with a setting the app has already applied. `ensureLoaded` ends the+ /// lineage the way a real load does, and calling it here would take the KV+ /// away from a conversation the window is still holding.+ func setLoadedContext(_ tokens: Int) {+ state.value.withLock { $0.loadedKey?.maxContextTokens = tokens }+ }++ /// Makes an attached image cost `tokens` placeholder IDs in the turn that+ /// carries it, the way a rendered prompt does.+ ///+ /// Replay finds an image by locating its placeholder run inside the turn+ /// that cites it, so a stored conversation with pictures cannot be replayed+ /// at all unless the recorded IDs actually contain those runs. The count+ /// has to come from a real preprocessed image, because it is what the+ /// stored record claims.+ func setImageSoftTokens(_ tokens: Int) {+ state.value.withLock { $0.imageSoftTokens = tokens }}var conversationEpochs: [UUID] {@@ -70,7 +137,63 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {}) {throw failure}- state.value.withLock { $0.conversationEpochs.append(epoch) }+ state.value.withLock {+ $0.conversationEpochs.append(epoch)+ $0.conversationTokens = 0+ $0.gate.reset(to: epoch)+ }+ }++ /// Every lineage the app asked to replay, so a test can assert it sent the+ /// stored IDs rather than a re-render of the transcript.+ var restoredLineages: [AppConversationLineage] {+ state.value.withLock { $0.restoredLineages }+ }++ /// Makes the next `restoreConversation` fail, as a digest mismatch or a+ /// dead connection does.+ func failNextRestore(with error: AppInferenceError) {+ state.value.withLock { $0.restoreFailure = error }+ }++ func failNextGeneration(with error: AppInferenceError) {+ state.value.withLock { $0.generationFailure = error }+ }++ func restoreConversation(+ _ lineage: AppConversationLineage,+ epoch: UUID,+ options: AppRuntimeOptions,+ maxContextTokens: Int,+ onPrefillProgress: @escaping @Sendable (Int, Int) -> Void+ ) async throws -> Int {+ if let failure = state.value.withLock({ value -> AppInferenceError? in+ defer { value.restoreFailure = nil }+ guard let failure = value.restoreFailure else { return nil }+ // Restore replaces the old KV before later work can fail. Model+ // that destructive ordering so app tests cannot accidentally keep+ // taking the former held-row fast path after a failed replay.+ value.gate.endLineage()+ value.conversationTokens = 0+ return failure+ }) {+ throw failure+ }+ // A real replay is a full prefill, so the double takes visible time+ // too: without it no test can observe the window during which a reopen+ // is in flight.+ try? await Task.sleep(for: eventDelay)+ onPrefillProgress(lineage.tokenIDs.count, lineage.tokenIDs.count)+ state.value.withLock {+ $0.restoredLineages.append(lineage)+ $0.conversationEpochs.append(epoch)+ $0.conversationTokens = lineage.tokenIDs.count+ // Opened at the turn count the transcript carries, not at zero: a+ // reopened conversation's next turn is numbered against what is+ // already in the KV.+ $0.gate.restore(to: epoch, committedTurns: lineage.committedTurns)+ }+ return lineage.tokenIDs.count}func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {@@ -93,6 +216,24 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {return}+ let admission: DecodeConversationGate.Admission+ switch state.value.withLock({ $0.gate.admit(Self.ticket(for: request)) }) {+ case .success(let value):+ admission = value+ case .failure(let rejection):+ state.value.withLock { $0.gateRejections.append(rejection) }+ // The turn was composed against a conversation the KV is no+ // longer holding, so retrying it would fail identically. That+ // is what `conversationLineageLost` means to the app, and what+ // `DecodeServiceInferenceClient` turns a `.lineageLost` event+ // into.+ let error = AppInferenceError.conversationLineageLost(+ String(describing: rejection))+ continuation.yield(.failed(error, partial: nil))+ continuation.finish(throwing: error)+ return+ }+let id = UUID()guard generationTasks.reserve(id) else {continuation.yield(.failed(.generationInFlight, partial: nil))@@ -102,7 +243,8 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {let task = Task { [self] inawait streamResponse(request: request,continuation: continuation,- generationID: id)+ generationID: id,+ admission: admission)}generationTasks.attach(task, to: id)@@ -121,10 +263,23 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {}}+ /// The wire request the gate actually inspects, built from the app's own+ /// ticket. Only the three fields the decision reads are carried across.+ private static func ticket(for request: AppGenerationRequest) -> DecodeGenerationRequest {+ DecodeGenerationRequest(+ prompt: request.prompt,+ maxNewTokens: request.maxNewTokens,+ maxContextTokens: request.maxContextTokens,+ temperature: request.temperature,+ conversationEpoch: request.conversationEpoch,+ turnIndex: request.turnIndex)+ }+private func streamResponse(request: AppGenerationRequest,continuation: AsyncThrowingStream<AppInferenceEvent, Error>.Continuation,- generationID: UUID+ generationID: UUID,+ admission: DecodeConversationGate.Admission) async {let start = Date()var firstTokenDate: Date?@@ -134,6 +289,18 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {state.value.withLock { $0.stopRequested = false }do {+ if let failure = state.value.withLock({ value -> AppInferenceError? in+ defer { value.generationFailure = nil }+ guard let failure = value.generationFailure else { return nil }+ value.loadedKey = nil+ value.gate.endLineage()+ value.conversationTokens = 0+ return failure+ }) {+ continuation.yield(.failed(failure, partial: nil))+ continuation.finish(throwing: failure)+ return+ }for step in 1...3 {try await Task.sleep(for: eventDelay)try Task.checkCancellation()@@ -164,17 +331,52 @@ final class FakeInferenceClient: AppModelLifecycleClient, Sendable {let end = Date()let decodeSeconds = max(end.timeIntervalSince(prefillEnd), 0)+ let softTokens = state.value.withLock { $0.imageSoftTokens }+ // Stand-in IDs, distinct per half so a test can tell which record a+ // stored turn came from. The real client reports what the KV took;+ // what matters here is that the app carries them to disk unchanged.+ //+ // Each image contributes a marker, its placeholder run and a second+ // marker, in that order, because that is the shape replay searches+ // for: one run per image, separated by something that is not a+ // placeholder. Emitting the runs back to back would merge them into+ // a single longer run and no image would be locatable.+ var promptTokenIDs: [Int32] = []+ for _ in request.imageAttachments {+ promptTokenIDs.append(1_500)+ promptTokenIDs += Array(+ repeating: MultimodalPromptRenderer.imageTokenID, count: softTokens)+ promptTokenIDs.append(1_501)+ }+ let textTokens = max(+ 1, request.prompt.split(whereSeparator: \.isWhitespace).count)+ promptTokenIDs += (0..<textTokens).map { Int32(1_000 + $0) }+ // The count and the IDs are one fact. A conversation whose meta+ // claims more tokens than its records hold is exactly the row the+ // history tests exist to catch, so the double must not invent one.+ let promptTokens = promptTokenIDs.count+ let generatedTokenIDs = (0..<generated).map { Int32(2_000 + $0) }continuation.yield(.finished(AppDiagnostics(generatedTokens: generated,stopReason: stoppedEarly ? .cancelled: (generated >= request.maxNewTokens ? .maxTokens : .eos),- promptTokenCount: max(1, request.prompt.split(whereSeparator: \.isWhitespace).count),+ promptTokenCount: promptTokens,+ conversationTokens: state.value.withLock {+ $0.conversationTokens += promptTokens + generated+ return $0.conversationTokens+ },+ promptTokenIDs: promptTokenIDs,+ generatedTokenIDs: generatedTokenIDs,prefillSeconds: prefillEnd.timeIntervalSince(start),timeToFirstTokenSeconds: firstTokenDate.map { $0.timeIntervalSince(prefillEnd) },decodeSeconds: decodeSeconds,tokensPerSecond: decodeSeconds > 0 ? Double(generated) / decodeSeconds : 0,peakMemoryBytes: nil,runtimeOptions: request.runtimeOptions)))+ // After the turn ran, not at admission: a turn that failed before+ // touching the KV must not advance the position the next one has to+ // match.+ state.value.withLock { $0.gate.commit(admission) }continuation.finish()} catch is CancellationError {let end = Date()diff --git a/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift b/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swiftnew file mode 100644index 00000000..5778af3f--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift@@ -0,0 +1,1023 @@+import Foundation+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// The one-pixel PNG, preprocessed once, so the harness knows what a stored+/// image record will claim before it writes one.+///+/// The soft-token count matters twice: the record stores it, and the double has+/// to emit that many placeholder IDs in the turn that carries the image or the+/// conversation can never be replayed — replay locates an image by finding its+/// placeholder run inside the turn that cites it. Measuring it here rather than+/// hard-coding it keeps the two ends of that from drifting apart.+enum HistoryImageFixture {+ static let softTokens: Int? = {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-image-probe-\(UUID().uuidString)",+ isDirectory: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ do {+ let store = AppImageAttachmentStore(+ directoryURL: directory.appendingPathComponent("staged", isDirectory: true))+ let staged = try store.stage(AppModelHistoryTests.pngFixture())+ let record = try ConversationImageWriter().write(+ attachment: staged,+ into: directory.appendingPathComponent("images", isDirectory: true))+ return record.softTokens+ } catch {+ // No Metal device, or a preprocessor that will not take the+ // fixture. The image operations stand down rather than the walk+ // failing for a reason that is not about history.+ return nil+ }+ }()++ static var isAvailable: Bool { softTokens != nil }+}++/// Drives `AppModel` and `ConversationStore` through a sequence of operations+/// and checks every invariant after each one.+///+/// It owns the app, the double, the store root and the reference model, and it+/// is the only thing in the app tests that knows how to wait for this feature+/// to be at rest: every write here finishes in a task the caller did not start,+/// so "the operation returned" and "the operation happened" are different+/// moments, and a check taken between them reads a conversation that is half+/// written.+@MainActor+final class HistoryHarness {+ enum Failure: Error, CustomStringConvertible {+ case notSettled(step: String, reason: String, trace: [String])+ case invariant(step: String, failures: [String], trace: [String])+ case storeUnavailable(String)++ var description: String {+ switch self {+ case .notSettled(let step, let reason, let trace):+ return "\(step) did not settle within 5 s: \(reason)\n"+ + Self.render(trace)+ case .invariant(let step, let failures, let trace):+ return "\(step) broke \(failures.count) invariant(s):\n"+ + failures.map { " - \($0)" }.joined(separator: "\n") + "\n"+ + Self.render(trace)+ case .storeUnavailable(let reason):+ return reason+ }+ }++ private static func render(_ trace: [String]) -> String {+ " trace:\n" + trace.map { " \($0)" }.joined(separator: "\n")+ }+ }++ private static let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ let root: URL+ let modelDirectory: URL+ let storeRoot: URL+ let client: FakeInferenceClient+ private(set) var model: AppModel!+ private(set) var reference: HistoryReferenceModel+ private(set) var trace: [String] = []+ private var attachmentStore = AppImageAttachmentStore()+ private var step = 0++ init(label: String) async throws {+ root = FileManager.default.temporaryDirectory+ .appendingPathComponent("history-walk-\(label)-\(UUID().uuidString)",+ isDirectory: true)+ modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ storeRoot = ConversationStoreLocation.url(forModelDirectory: modelDirectory)+ try FileManager.default.createDirectory(+ at: modelDirectory, withIntermediateDirectories: true)+ client = FakeInferenceClient(eventDelay: .milliseconds(1))+ client.setImageSoftTokens(HistoryImageFixture.softTokens ?? 0)+ // The context the app comes up at with no settings file, taken from+ // the same defaults it takes it from. Restating the number here made+ // the relaunch check a check on the harness rather than on the app.+ reference = HistoryReferenceModel(+ maxContextTokens: MacAppSettings().contextTokens)+ try await start()+ }++ /// Everything this harness put on disk. Called from the test's `defer`,+ /// because a walk that throws still has to leave the machine clean.+ func tearDown() {+ model?.releaseAllAttachments()+ try? FileManager.default.removeItem(at: root)+ }++ // MARK: - Lifecycle++ private func start() async throws {+ attachmentStore = AppImageAttachmentStore(+ directoryURL: root.appendingPathComponent(+ "staged-\(UUID().uuidString)", isDirectory: true))+ let model = AppModel(modelDirectory: modelDirectory, client: client,+ attachmentStore: attachmentStore,+ settingsPersistenceEnabled: true)+ model.modelPathText = modelDirectory.path+ // Read from the installed model's manifest in the app; a temporary+ // directory has none, and identity is not what this covers.+ model.conversationIdentity = Self.identity+ model.installationStatus = .complete+ model.loadState = .ready(modelDirectory: modelDirectory, loadSeconds: 1)+ // A long message is thousands of words, and the double answers with the+ // prompt echoed back one token at a time. Eight is enough reply to+ // pair every turn and keeps a long send as cheap as a short one.+ model.maxNewTokensOverride = 8+ self.model = model+ try await client.ensureLoaded(+ modelDirectory: modelDirectory,+ maxContextTokens: model.maxContextTokens,+ options: model.runtimeOptions,+ forceLogitsHead: true) { _ in }+ try await waitForWritableStore()+ try await settle("start")+ if let restored = reference.reading {+ try await settle("restore selection") {+ model.screen.conversationID == restored+ && model.screen.document != nil+ }+ }+ }++ private func waitForWritableStore() async throws {+ let deadline = Date().addingTimeInterval(5)+ while Date() < deadline {+ if !model.history.isReadOnlyStore { return }+ // The previous instance's `flock` is released when its store+ // deallocates, which is not synchronous with dropping the model.+ model.reacquireStoreIfPossible()+ try await Task.sleep(for: .milliseconds(1))+ }+ throw Failure.storeUnavailable(+ "the relaunched instance never took the writer lock")+ }++ // MARK: - Applying an operation++ func apply(_ operation: HistoryOperation) async throws {+ step += 1+ trace.append("\(step). \(operation)")+ switch operation {+ case .newChat: try await applyNewChat()+ case .send(let label): try await applySend(label: label)+ case .sendLong(let label): try await applySend(label: label, long: true)+ case .sendWithImage(let label): try await applySend(label: label, withImage: true)+ case .open(let row): try await applyOpen(row: row)+ case .delete(let row): try await applyDelete(row: row)+ case .rename(let row, let label): try await applyRename(row: row, label: label)+ case .setContext(let tokens): try await applySetContext(tokens)+ case .failNextRestore: try await applyFailNextRestore()+ case .relaunch: try await applyRelaunch()+ case .reload: try await applyReload()+ case .unload: try await applyUnload()+ case .stopMidTurn(let label): try await applySend(label: label, stopping: true)+ }+ try checkInvariants()+ }++ private func note(_ text: String) {+ trace[trace.count - 1] += " [\(text)]"+ }++ private func applyNewChat() async throws {+ guard model.canStartNewChat else {+ note("refused")+ return+ }+ model.newChat()+ reference.newChat()+ try await settle("newChat")+ }++ private func applySend(label: Int, long: Bool = false,+ withImage: Bool = false,+ stopping: Bool = false) async throws {+ // The composer is closed for a row that cannot be continued, so a send+ // there is not something a user can do. Driving `run()` anyway would+ // exercise a replay the window never offers.+ if model.isShowingStoredCopy, model.openedConversationState != .continuable {+ note("skipped: the row on screen cannot be continued")+ return+ }+ let word = "m\(label)"+ let prompt = long+ ? Array(repeating: word, count: HistoryOperation.longMessageWords)+ .joined(separator: " ")+ : word+ model.promptText = prompt+ guard model.canRun else {+ model.promptText = ""+ note("skipped: canRun is false")+ return+ }+ if withImage, HistoryImageFixture.isAvailable, model.maximumImageAttachments >= 1 {+ let staged = try attachmentStore.stage(AppModelHistoryTests.pngFixture())+ model.setComposerAttachmentsForTesting([staged])+ } else if withImage {+ note("no image: \(HistoryImageFixture.isAvailable ? "the context has no room" : "no preprocessor")")+ }+ // Whatever the composer is actually carrying, which is not only what+ // this step attached: a replay that failed hands the message and its+ // pictures back, and the next send is the one that delivers them.+ let images = model.imageAttachments.count++ // Stopping a turn that is carrying pictures would leave the write that+ // was started for it with nothing to finish into, and this operation is+ // about the turn, not the images. The composer can be holding some+ // without this step having attached any: a replay that failed hands the+ // message and its pictures back.+ let stops = stopping && images == 0++ let readingBefore = readingID+ let failsToReplay = readingBefore != nil && reference.restoreFailureArmed+ let heldBefore = reference.held+ let target = readingBefore ?? heldBefore+ let expectedRecords = ((target.map { reference.exchanges(in: $0) }) ?? 0) * 2 + 2++ model.send()+ guard model.isTurnInFlight else {+ // `send()` takes the composer synchronously, so the only way it+ // returns with nothing in flight is the `canRun` guard above.+ model.promptText = ""+ note("refused before it started")+ try await settle("send")+ return+ }+ if stopping, !stops { note("not stopped: the turn is carrying pictures") }+ if stops {+ // Stop reaches a decoding turn, not a replay: the button is not+ // offered while a reopened conversation is being prefilled. The+ // send runs the stages in its own task, so the button becomes live+ // a hop or two after `send()` returns — and whether the stop then+ // reaches the run before it finishes is the race+ // `applyStopOutcome` reads off the transcript.+ try await waitForCancellableTurn()+ if model.canCancel { model.cancel() }+ }++ if failsToReplay {+ reference.failRestoreDestructively()+ try await settle("send") { [self] in+ // The replay hands the message back to the composer, which is+ // the observable end of that path.+ !model.isTurnInFlight && model.promptText == prompt+ }+ model.promptText = ""+ note("replay refused")+ return+ }++ if readingBefore != nil {+ // The replay put the conversation back into the KV, so nothing on+ // screen is out of context any more.+ reference.adoptRestored()+ }+ if stops {+ try await applyStopOutcome(prompt: prompt, target: target,+ expectedRecords: expectedRecords)+ return+ }+ try await settle("send")+ if model.promptText == prompt {+ // The message came back, so a stage refused it: the request did not+ // validate, because what the conversation already holds leaves no+ // room for the images attached to this turn. Read off the composer+ // rather than off a synchronous return, because the stages that can+ // refuse now run in the send's own task.+ model.promptText = ""+ note("refused")+ try await settle("send")+ return+ }+ try await settle("send") { [self] in+ guard let id = model.storedConversationID else { return false }+ return model.history.entry(id)?.turnCount == expectedRecords+ }+ guard let landed = model.storedConversationID else {+ throw Failure.invariant(+ step: "send", failures: ["the turn was written to no conversation"],+ trace: trace)+ }+ if let target {+ guard landed == target else {+ throw Failure.invariant(+ step: "send",+ failures: ["the turn landed in \(landed) rather than \(target)"],+ trace: trace)+ }+ } else {+ guard reference.conversations[landed] == nil else {+ throw Failure.invariant(+ step: "send",+ failures: ["a new chat reused the existing conversation \(landed)"],+ trace: trace)+ }+ reference.create(landed)+ }+ reference.appendExchange(to: landed, userText: prompt, images: images)+ note("into \(short(landed))")+ }++ /// Records what a stopped turn actually did.+ ///+ /// Whether the stop reaches the run before it produces its whole answer is+ /// a race the harness must not pretend to win: a hard abort rewinds the+ /// turn and writes nothing, and a stop that lands after the terminal event+ /// leaves an ordinary completed exchange. Which of the two happened is read+ /// off the transcript, not off the app — the app's own answer would pass+ /// for a model that had silently done neither.+ private func applyStopOutcome(prompt: String, target: UUID?,+ expectedRecords: Int) async throws {+ try await settle("stopMidTurn")+ guard let landed = model.storedConversationID else {+ // The turn never reached the point where the directory is created.+ note("stopped before the chat was written")+ return+ }+ if let target {+ guard landed == target else {+ throw Failure.invariant(+ step: "stopMidTurn",+ failures: ["the turn landed in \(landed) rather than \(target)"],+ trace: trace)+ }+ } else if reference.conversations[landed] == nil {+ reference.create(landed)+ }+ let userTexts = try diskConversations()[landed]?.turns+ .filter { $0.role == .user }.map(\.text) ?? []+ if userTexts.count == reference.exchanges(in: landed) + 1 {+ // The stop lost the race; the turn is a committed exchange like any+ // other, and the record has to say so before the invariants run.+ try await settle("stopMidTurn") { [self] in+ model.history.entry(landed)?.turnCount == expectedRecords+ }+ reference.appendExchange(to: landed, userText: prompt, images: 0)+ note("finished before the stop landed, into \(short(landed))")+ return+ }+ reference.stopTurn(in: landed, userText: prompt)+ note("rewound in \(short(landed))")+ }++ /// Waits until the send has a generation Stop can reach, or until it has+ /// ended without one.+ private func waitForCancellableTurn() async throws {+ let deadline = Date().addingTimeInterval(5)+ while Date() < deadline {+ if model.canCancel || !model.isTurnInFlight { return }+ try await Task.sleep(for: .milliseconds(1))+ }+ throw Failure.notSettled(+ step: "stopMidTurn", reason: "the send never reached a turn Stop "+ + "could cancel", trace: trace)+ }++ private func applyReload() async throws {+ guard !model.isTurnInFlight, model.loadState.isReady || model.canLoadModel else {+ note("refused")+ return+ }+ // What the window's Reload does: the runner and its KV go, and a new+ // pair is built. Driven as the two actions the app exposes because the+ // Reload button itself is offered only for a session whose settings+ // have gone stale, and this harness deliberately never lets one.+ let released = reference.reading ?? reference.held+ if model.loadState.isReady {+ model.unloadModel()+ try await settle("reload") { [self] in model.loadState == .notLoaded }+ }+ model.loadModel()+ try await settle("reload") { [self] in model.loadState.isReady }+ reference.releaseKV()+ try await settle("reload") { [self] in+ guard let released else { return true }+ return model.screen.conversationID == released+ && model.screen.document != nil+ }+ note(released == nil ? "no durable row" : "durable row awaits replay")+ }++ private func applyUnload() async throws {+ guard !model.isTurnInFlight, model.canUnloadModel else {+ note("refused")+ return+ }+ let released = reference.reading ?? reference.held+ model.unloadModel()+ try await settle("unload") { [self] in model.loadState == .notLoaded }+ reference.releaseKV()+ try await settle("unload") { [self] in+ guard let released else { return true }+ return model.screen.conversationID == released+ && model.screen.document != nil+ }+ note(released == nil ? "no durable row" : "durable row awaits replay")+ }++ private func applyOpen(row: Int) async throws {+ guard let id = rowID(row) else {+ note("no rows")+ return+ }+ guard !model.isTurnInFlight else {+ note("refused")+ return+ }+ let state = continuability(of: id)+ // The one the KV is already holding stays live: browsing back to it+ // rebuilds nothing, whatever its record says. Only a context it no+ // longer fits reads it as a copy, because then the copy's notice is+ // the truth.+ var staysLive = id == model.storedConversationID+ && model.serviceEpoch == model.conversation.epoch+ if case .needsContext = state { staysLive = false }+ let exchanges = reference.exchanges(in: id)++ model.openConversation(id: id)++ if staysLive {+ reference.stopReading()+ try await settle("open") { [self] in+ !model.isShowingStoredCopy && model.history.selection == id+ }+ note("live \(short(id))")+ return+ }+ reference.read(id)+ try await settle("open") { [self] in+ guard exchanges > 0 else { return true }+ // One list now, whichever state the row is in: what the window+ // draws is the document the click asked for.+ return !model.transcriptHistory.isEmpty+ }+ note("reading \(short(id)) \(state)")+ }++ private func applyDelete(row: Int) async throws {+ guard let id = rowID(row) else {+ note("no rows")+ return+ }+ model.deleteConversation(id: id)+ reference.delete(id)+ try await settle("delete") { [self] in model.history.entry(id) == nil }+ note("removed \(short(id))")+ }++ private func applyRename(row: Int, label: Int) async throws {+ guard let id = rowID(row) else {+ note("no rows")+ return+ }+ let title = "t\(label)"+ let before = model.history.entry(id)?.updatedAt+ model.renameConversation(id: id, to: title)+ reference.rename(id, to: title)+ try await settle("rename") { [self] in model.history.entry(id)?.title == title }+ if let before, model.history.entry(id)?.updatedAt != before {+ throw Failure.invariant(+ step: "rename",+ failures: ["renaming \(short(id)) moved it up the list"], trace: trace)+ }+ note("renamed \(short(id))")+ }++ private func applySetContext(_ tokens: Int) async throws {+ guard tokens != model.maxContextTokens else {+ note("already \(tokens)")+ return+ }+ let reading = readingID+ model.setMaxContextTokens(tokens)+ reference.maxContextTokens = tokens+ reference.recordSettingsPersisted()+ // The double's loaded session has to move with the setting or every+ // later turn comes back as a runtime mismatch. Deliberately not a+ // load: a real one ends the lineage, and taking the KV away from the+ // conversation the window is still holding is what the `reload`+ // operation is for.+ client.setLoadedContext(tokens)++ guard let reading else {+ try await settle("setContext")+ note("live")+ return+ }+ // Re-opening the row rebuilds it from the answer that now applies, and+ // that answer can put it back into the live conversation.+ let state = continuability(of: reading)+ let staysLive = reading == model.storedConversationID+ && model.serviceEpoch == model.conversation.epoch+ && state == .continuable+ let exchanges = reference.exchanges(in: reading)+ if staysLive { reference.stopReading() }+ try await settle("setContext") { [self] in+ if staysLive { return !model.isShowingStoredCopy }+ guard exchanges > 0 else { return true }+ return !model.transcriptHistory.isEmpty+ }+ note("redrew \(short(reading)) as \(state)")+ }++ private func applyFailNextRestore() async throws {+ client.failNextRestore(with: .conversationRestoreFailed("harness"))+ reference.armRestoreFailure()+ try await settle("failNextRestore")+ }++ private func applyRelaunch() async throws {+ let before = try diskConversations()+ // What quitting does: the staged copies of this session go, the service+ // ends its lineage, and the window is gone before the next one starts.+ model.releaseAllAttachments()+ await client.unload()+ model = nil+ reference.relaunch()+ try await start()+ guard model.maxContextTokens == reference.maxContextTokens else {+ throw Failure.invariant(+ step: "relaunch",+ failures: ["the context came back as \(model.maxContextTokens), "+ + "not the \(reference.maxContextTokens) that was saved"],+ trace: trace)+ }+ let after = try diskConversations()+ var failures: [String] = []+ if Set(before.keys) != Set(after.keys) {+ failures.append("the store lost or gained conversations across a relaunch")+ }+ let store = try requireStore()+ for id in after.keys.sorted(by: { $0.uuidString < $1.uuidString }) {+ guard let opened = try? await store.open(id: id) else {+ failures.append("\(short(id)) could not be opened after a relaunch")+ continue+ }+ if opened.droppedTornFinalLine {+ failures.append("\(short(id)) had a torn final line after a clean quit")+ }+ }+ if !failures.isEmpty {+ throw Failure.invariant(step: "relaunch", failures: failures, trace: trace)+ }+ note("\(after.count) row(s) intact")+ }++ // MARK: - Settling++ /// Waits until nothing is in flight, with a deadline that throws.+ ///+ /// The existing `waitUntil` returns silently when its deadline expires,+ /// which turns a hang into a passing assertion about whatever state the app+ /// happened to be in. Nothing here may do that.+ func settle(_ what: String,+ _ extra: @MainActor () -> Bool = { true }) async throws {+ await model.persistenceTail?.value+ let deadline = Date().addingTimeInterval(5)+ var reason = "unknown"+ while Date() < deadline {+ if let pending = inFlightReason() {+ reason = pending+ } else if !extra() {+ reason = "the operation's own effect has not landed"+ } else {+ // A send can enqueue its final write after the initial wait.+ // Read the committed transcript only after that write settles.+ await model.persistenceTail?.value+ if inFlightReason() != nil || !extra() { continue }+ return+ }+ try await Task.sleep(for: .milliseconds(1))+ }+ throw Failure.notSettled(step: what, reason: reason, trace: trace)+ }++ private func inFlightReason() -> String? {+ if model.isRunning { return "a generation is running" }+ if model.screen.isReplaying { return "a replay is running" }+ // The send is one pipeline in its own task now, and its stages — the+ // replay, the ticket, the request, the retain, the hand-back — are not+ // all covered by the two flags above.+ if model.isTurnInFlight { return "a send is on its way" }+ if client.isGenerating { return "the client still holds a generation" }+ if model.pendingTurnImageWrite != nil { return "a turn's images are being written" }+ // Names only. Decoding every transcript on a one-millisecond poll made+ // settling cost more than the operations it was waiting for.+ guard let onDisk = try? diskConversationIDs() else {+ return "the store could not be read"+ }+ if Set(model.history.entries.map(\.id)) != onDisk {+ return "the list and the disk disagree"+ }+ return nil+ }++ // MARK: - Invariants++ func checkInvariants() throws {+ let disk: [UUID: StoredConversation]+ do { disk = try diskConversations() } catch {+ throw Failure.invariant(+ step: "invariants", failures: ["the store could not be read: \(error)"],+ trace: trace)+ }+ var failures: [String] = []+ failures += diskAgreesWithItself(disk)+ failures += oneThingIsOnScreen(disk)+ failures += theAppAndTheGateAgree()+ failures += everyReferencedImageExists(disk)+ failures += noOrphanImages(disk)+ failures += theListIsTheDisk(disk)+ guard failures.isEmpty else {+ throw Failure.invariant(+ step: trace.last ?? "step", failures: failures, trace: trace)+ }+ }++ /// 1. Every conversation on disk is what its own records say it is, and+ /// what the harness asked for.+ private func diskAgreesWithItself(_ disk: [UUID: StoredConversation]) -> [String] {+ var failures: [String] = []+ for id in disk.keys.sorted(by: { $0.uuidString < $1.uuidString }) {+ let stored = disk[id]!+ let name = short(id)+ let turns = stored.turns+ let images = turns.reduce(0) { $0 + $1.images.count }+ // One check for the whole file. `conversation.json` is a cache of+ // the projection over the records, so every field it carries has+ // exactly one right answer and anything else is drift — the class+ // that produced a row reading 1,065 tokens over 22 tokens of+ // record. `legacy: nil` on purpose: a store this harness wrote+ // carries its creation facts in its header, and letting the cache+ // answer for itself would pass for any field that had drifted.+ do {+ let projected = try ConversationMetaProjection.project(+ directoryID: id, records: stored.records, legacy: nil)+ let differing = Self.fieldsDiffering(projected, stored.meta)+ if !differing.isEmpty {+ failures.append("\(name): the file disagrees with its records "+ + "about \(differing.joined(separator: ", "))")+ }+ } catch {+ failures.append("\(name): its records do not project to a "+ + "conversation: \(error)")+ }+ guard let expected = reference.conversations[id] else {+ failures.append("\(name): on disk but not expected")+ continue+ }+ let userTexts = turns.filter { $0.role == .user }.map(\.text)+ if userTexts != expected.userTexts {+ failures.append("\(name): holds \(userTexts.count) message(s), "+ + "\(expected.userTexts.count) expected")+ }+ if images != expected.imageCount {+ failures.append("\(name): holds \(images) image(s), "+ + "\(expected.imageCount) expected")+ }+ if let title = reference.expectedTitle(of: id), stored.meta.title != title {+ failures.append("\(name): titled \(stored.meta.title), \(title) expected")+ }+ }+ for id in reference.conversations.keys where disk[id] == nil {+ failures.append("\(short(id)): expected on disk and not there")+ }+ return failures+ }++ /// 2. Exactly one conversation is on screen, and it is the one the window+ /// says it is.+ private func oneThingIsOnScreen(_ disk: [UUID: StoredConversation]) -> [String] {+ var failures: [String] = []+ if model.screen.isReplaying {+ failures.append("a replay was still running after the step settled")+ }+ let onScreen = model.transcriptHistory+ let ids = onScreen.map(\.user.id)+ if Set(ids).count != ids.count {+ failures.append("a turn is drawn twice in the transcript")+ }+ if case .unreadable(let id, let cause) = model.screen {+ failures.append("the window could not read \(short(id)): \(cause)")+ return failures+ }+ // A stored copy on screen, whether it is merely being read or is being+ // put back into the KV. There is no second list to check any more: the+ // screen either names a conversation or it does not.+ if let reading = model.screen.conversationID {+ if reference.reading != reading {+ failures.append("the window is reading \(short(reading)), "+ + "\(reference.reading.map(short) ?? "nothing") expected")+ }+ guard let stored = disk[reading] else {+ failures.append("the window is reading \(short(reading)), which is "+ + "not on disk")+ return failures+ }+ if model.history.selection != reading {+ failures.append("the row selected is "+ + "\(model.history.selection.map(short) ?? "none") while "+ + "\(short(reading)) is on screen")+ }+ let expected = stored.turns.filter { $0.role == .user }.map(\.text)+ if onScreen.map(\.user.text) != expected {+ failures.append("the transcript shows \(onScreen.count) exchange(s) of "+ + "\(short(reading)), which holds \(expected.count)")+ }+ return failures+ }+ // Live: the window is showing the conversation the KV is holding.+ if reference.reading != nil {+ failures.append("the window went live while \(short(reference.reading!)) "+ + "was expected on screen")+ }+ // Empty unless a load or an unload released the KV under a conversation+ // that was on screen: those turns stay drawn, above a context break,+ // and belong to no live conversation any more. A stored copy cannot be+ // drawn under them any more — there is nowhere left to hold one while+ // the screen is live — so the check for that is the compiler's now.+ let archived = model.conversation.outOfContextPairs.map(\.user.text)+ if archived != reference.outOfContext {+ failures.append("the transcript holds \(archived.count) exchange(s) out "+ + "of context, \(reference.outOfContext.count) expected")+ }+ if model.transcriptContextBreak != (archived.isEmpty ? nil : archived.count) {+ failures.append("the context break is drawn at "+ + "\(model.transcriptContextBreak.map(String.init) ?? "nowhere")")+ }+ if model.storedConversationID != reference.held {+ failures.append("the held conversation is "+ + "\(model.storedConversationID.map(short) ?? "none"), "+ + "\(reference.held.map(short) ?? "none") expected")+ }+ if model.history.selection != model.storedConversationID {+ failures.append("the row selected is "+ + "\(model.history.selection.map(short) ?? "none") while the window "+ + "shows \(model.storedConversationID.map(short) ?? "an empty chat")")+ }+ let expected = reference.held.flatMap { reference.conversations[$0]?.userTexts } ?? []+ let live = model.conversation.completedPairs.map(\.user.text)+ if live != expected {+ failures.append("the live conversation holds \(live.count) exchange(s), "+ + "\(expected.count) expected")+ }+ if onScreen.map(\.user.text) != reference.outOfContext + Array(live.dropLast()) {+ failures.append("the transcript above the live turn is not the rest of "+ + "the conversation")+ }+ return failures+ }++ /// 3. The app's turn numbering and the service's are the same numbering.+ private func theAppAndTheGateAgree() -> [String] {+ var failures: [String] = []+ for rejection in client.gateRejections {+ failures.append("the service refused a turn: \(rejection)")+ }+ if model.conversation.isLineageLost {+ failures.append("the live conversation's lineage was lost")+ }+ if model.conversation.committedTurns != reference.committedTurns {+ failures.append("the app has committed \(model.conversation.committedTurns) "+ + "turn(s), \(reference.committedTurns) expected")+ }+ guard let epoch = model.serviceEpoch, epoch == model.conversation.epoch else {+ return failures+ }+ if client.gateOpenEpoch != epoch {+ failures.append("the service is holding "+ + "\(client.gateOpenEpoch.map(short) ?? "no conversation") while the "+ + "app is sending against \(short(epoch))")+ }+ if client.gateCommittedTurns != model.conversation.committedTurns {+ failures.append("the service has committed \(client.gateCommittedTurns) "+ + "turn(s) and the app \(model.conversation.committedTurns)")+ }+ return failures+ }++ /// 4. Nothing on screen or on disk points at a picture that is gone.+ private func everyReferencedImageExists(_ disk: [UUID: StoredConversation]) -> [String] {+ var failures: [String] = []+ for (id, stored) in disk {+ for turn in stored.turns {+ for image in turn.images {+ for file in [image.pixelsFile, image.thumbnailFile] {+ let url = stored.directory.appendingPathComponent(file)+ if !FileManager.default.fileExists(atPath: url.path) {+ failures.append("\(short(id)) cites \(file), which is gone")+ }+ }+ }+ }+ }+ var shown: [ChatImage] = model.imageAttachments.map(ChatImage.staged)+ shown += model.outputImageAttachments+ shown += model.conversation.turns.flatMap(\.images)+ shown += model.conversation.outOfContextPairs+ .flatMap { $0.user.images + $0.assistant.images }+ shown += (model.screen.document?.pairs ?? [])+ .flatMap { $0.user.images + $0.assistant.images }+ for attachment in shown+ where !FileManager.default.fileExists(atPath: attachment.fileURL.path) {+ failures.append("the window is holding \(attachment.id), whose file is gone")+ }+ return failures+ }++ /// 5. A conversation's image directory holds nothing no record names.+ private func noOrphanImages(_ disk: [UUID: StoredConversation]) -> [String] {+ var failures: [String] = []+ for (id, stored) in disk {+ let images = stored.directory.appendingPathComponent("images", isDirectory: true)+ guard let files = try? FileManager.default.contentsOfDirectory(+ at: images, includingPropertiesForKeys: nil,+ options: [.skipsHiddenFiles]) else { continue }+ var referenced: Set<String> = []+ for turn in stored.turns {+ for image in turn.images {+ referenced.insert(image.pixelsFile)+ referenced.insert(image.thumbnailFile)+ }+ }+ for file in files where !referenced.contains("images/" + file.lastPathComponent) {+ failures.append("\(short(id)) keeps \(file.lastPathComponent), which no "+ + "record names")+ }+ }+ return failures+ }++ /// 6. The sidebar is the store, in the order the store defines.+ private func theListIsTheDisk(_ disk: [UUID: StoredConversation]) -> [String] {+ var failures: [String] = []+ let entries = model.history.entries+ if Set(entries.map(\.id)) != Set(disk.keys) {+ failures.append("the list holds \(entries.count) row(s) over "+ + "\(disk.count) conversation(s) on disk")+ return failures+ }+ for entry in entries where entry != disk[entry.id]?.meta {+ failures.append("the row for \(short(entry.id)) is not what the file says")+ }+ // Ordered by when a conversation was last used. Compared as a run+ // rather than against a sorted copy, because conversations written in+ // the same second tie and the sort is not specified to be stable.+ for (older, newer) in zip(entries.dropFirst(), entries)+ where newer.updatedAt < older.updatedAt {+ failures.append("the list is not ordered by when a chat was last used")+ break+ }+ if model.history.unreadableCount != 0 {+ failures.append("\(model.history.unreadableCount) conversation(s) could "+ + "not be read")+ }+ return failures+ }++ // MARK: - Reading the store directly++ struct StoredConversation {+ let directory: URL+ let meta: ConversationMeta+ let records: [TranscriptRecord]++ var turns: [ConversationTurnRecord] {+ records.compactMap { if case .turn(let turn) = $0 { return turn } else { return nil } }+ }++ }++ /// Which fields of the cache and the projection disagree.+ ///+ /// Named rather than compared whole so a failure says what drifted; the+ /// values themselves are not printed, because a title is content.+ private static func fieldsDiffering(_ projected: ConversationMeta,+ _ stored: ConversationMeta) -> [String] {+ var names: [String] = []+ if projected.version != stored.version { names.append("version") }+ if projected.id != stored.id { names.append("id") }+ if projected.title != stored.title { names.append("title") }+ if projected.titleSource != stored.titleSource { names.append("titleSource") }+ if projected.createdAt != stored.createdAt { names.append("createdAt") }+ if projected.updatedAt != stored.updatedAt { names.append("updatedAt") }+ if projected.turnCount != stored.turnCount {+ names.append("turnCount (\(stored.turnCount) stored, "+ + "\(projected.turnCount) recorded)")+ }+ if projected.kvTokens != stored.kvTokens {+ names.append("kvTokens (\(stored.kvTokens.map(String.init) ?? "none") "+ + "stored, \(projected.kvTokens.map(String.init) ?? "none") recorded)")+ }+ if projected.imageCount != stored.imageCount {+ names.append("imageCount (\(stored.imageCount) stored, "+ + "\(projected.imageCount) recorded)")+ }+ if projected.identity != stored.identity { names.append("identity") }+ if projected.session != stored.session { names.append("session") }+ if projected.sampling != stored.sampling { names.append("sampling") }+ if projected.boundary != stored.boundary { names.append("boundary") }+ if projected.imageWriteFailed != stored.imageWriteFailed {+ names.append("imageWriteFailed")+ }+ if projected.pinned != stored.pinned { names.append("pinned") }+ return names+ }++ /// The conversations on disk by name alone, without opening any of them.+ func diskConversationIDs() throws -> Set<UUID> {+ guard FileManager.default.fileExists(atPath: storeRoot.path) else { return [] }+ return Set(try FileManager.default.contentsOfDirectory(+ at: storeRoot, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])+ .compactMap { UUID(uuidString: $0.lastPathComponent) })+ }++ /// Reads the files, not the store.+ ///+ /// Deliberately its own decoder: an invariant that asked `ConversationStore`+ /// what is on disk would pass for any bug the two share.+ func diskConversations() throws -> [UUID: StoredConversation] {+ guard FileManager.default.fileExists(atPath: storeRoot.path) else { return [:] }+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601+ var result: [UUID: StoredConversation] = [:]+ for entry in try FileManager.default.contentsOfDirectory(+ at: storeRoot, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) {+ guard let id = UUID(uuidString: entry.lastPathComponent) else { continue }+ let metaData = try Data(+ contentsOf: entry.appendingPathComponent(ConversationMeta.fileName))+ let meta = try decoder.decode(ConversationMeta.self, from: metaData)+ let transcript = try Data(+ contentsOf: entry.appendingPathComponent("transcript.jsonl"))+ var records: [TranscriptRecord] = []+ for line in transcript.split(separator: 0x0A, omittingEmptySubsequences: true) {+ records.append(try decoder.decode(TranscriptRecord.self, from: Data(line)))+ }+ result[id] = StoredConversation(+ directory: entry, meta: meta, records: records)+ }+ return result+ }++ // MARK: - Small helpers++ private func requireStore() throws -> ConversationStore {+ guard let store = model.conversationStore else {+ throw Failure.storeUnavailable("the app has no conversation store")+ }+ return store+ }++ /// The row a conversation is drawn at right now.+ ///+ /// A fixed sequence names a conversation by when it was created; the+ /// sidebar orders by when a chat was last used, and `updatedAt` is written+ /// to whole seconds — so two chats used in the same second tie, and which+ /// of them is row 0 then depends on the order the directory enumerated. A+ /// literal row index is not a stable way to name one of them.+ func row(ofCreated index: Int) throws -> Int {+ guard index < reference.created.count else {+ throw Failure.storeUnavailable(+ "the harness has only \(reference.created.count) conversation(s)")+ }+ let id = reference.created[index]+ guard let row = model.history.entries.firstIndex(where: { $0.id == id }) else {+ throw Failure.storeUnavailable("\(short(id)) is not in the list")+ }+ return row+ }++ private func rowID(_ row: Int) -> UUID? {+ let entries = model.history.entries+ guard !entries.isEmpty else { return nil }+ return entries[row % entries.count].id+ }++ /// The stored conversation the window is drawing from disk, if any.+ ///+ /// Deliberately not `screen.conversationID`, which also names the row of a+ /// chat that could not be read: what the callers ask is whether a send has+ /// a conversation to replay first.+ private var readingID: UUID? {+ if case .reading(let id, _, _, _) = model.screen { return id }+ return nil+ }++ private func continuability(of id: UUID) -> ConversationContinuability {+ guard let meta = model.history.entry(id) else {+ return .cannotReplay(reason: .tokenCountUnknown)+ }+ return ConversationContinuability.evaluate(+ meta: meta, currentContext: reference.maxContextTokens,+ identity: Self.identity)+ }++ private func short(_ id: UUID) -> String { String(id.uuidString.prefix(8)) }+}diff --git a/Tests/TurboFieldfareApp/Core/Support/HistoryOperation.swift b/Tests/TurboFieldfareApp/Core/Support/HistoryOperation.swiftnew file mode 100644index 00000000..7b653ea7--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/HistoryOperation.swift@@ -0,0 +1,126 @@+import Foundation+import TurboFieldfareValidationSupport+@testable import TurboFieldfareAppCore++/// One thing a user can do to their conversation history.+///+/// The alphabet a seeded walk draws from. Every serious defect this feature+/// produced needed three or four of these in a row — delete the chat the KV is+/// holding and send again, read one chat then another then the first — and+/// every test written for those defects afterwards is one hand-written+/// sequence. This is the same thing generated.+enum HistoryOperation: Sendable, CustomStringConvertible {+ case newChat+ /// `label` names the message: prompts are `m<label>`, so a failure trace+ /// carries positions and counts and never any content.+ case send(label: Int)+ /// The same message repeated until the turn is thousands of tokens long.+ ///+ /// The only way this alphabet reaches a conversation that no longer fits.+ /// Continuability is `kvTokens + 256 <= context`, the smallest context the+ /// window offers is 4,096, and an ordinary synthetic turn here costs seven+ /// tokens — so without this a walk would need five hundred turns in one+ /// chat before a row stopped being continuable, and `needsContext`, the+ /// state the read-only transcript and the "raise the context" notice exist+ /// for, would never be entered at all.+ case sendLong(label: Int)+ case sendWithImage(label: Int)+ /// Row indices are drawn blind and taken modulo the row count when applied,+ /// so a draw is reproducible from the seed alone.+ case open(row: Int)+ case delete(row: Int)+ case rename(row: Int, label: Int)+ case setContext(tokens: Int)+ case failNextRestore+ case relaunch+ /// Reload the model. A load builds a new runner and an empty KV, so the+ /// service ends the lineage and the app's conversation moves out of+ /// context — the one lifecycle action that keeps the window open while+ /// taking the model's memory of it away.+ case reload+ /// Unload the model. The same release as a reload without the rebuild:+ /// nothing can be sent until it comes back.+ case unload+ /// Send, then press Stop while the reply is still decoding.+ ///+ /// The in-process client's Stop is a hard abort: the runtime rewinds the+ /// turn, so it is in neither the KV nor the transcript, and the message+ /// comes back to the composer. Whether the stop reaches the run before it+ /// finishes is a race, so the outcome is read off disk rather than assumed.+ case stopMidTurn(label: Int)++ var description: String {+ switch self {+ case .newChat: return "newChat"+ case .send(let label): return "send(m\(label))"+ case .sendLong(let label): return "sendLong(m\(label))"+ case .sendWithImage(let label): return "sendWithImage(m\(label))"+ case .open(let row): return "open(#\(row))"+ case .delete(let row): return "delete(#\(row))"+ case .rename(let row, let label): return "rename(#\(row), t\(label))"+ case .setContext(let tokens): return "setContext(\(tokens))"+ case .failNextRestore: return "failNextRestore"+ case .relaunch: return "relaunch"+ case .reload: return "reload"+ case .unload: return "unload"+ case .stopMidTurn(let label): return "stopMidTurn(m\(label))"+ }+ }++ /// The contexts the walk switches between.+ ///+ /// Only values the window offers. `MacAppSettings.isValid` rejects anything+ /// else, and an invalid settings file is deleted and replaced with the+ /// defaults on the next launch — so a walk that set 2,048 (which is not one+ /// of the options, whatever the plan said) came back from a relaunch at+ /// 8,192, and the mismatch was the harness's, not the app's.+ static let contexts = [+ AppContextLengthOption.fourK.tokens,+ AppContextLengthOption.eightK.tokens,+ AppContextLengthOption.sixteenK.tokens,+ ]++ /// How many words a long message repeats to.+ ///+ /// One of them makes a conversation too big for a 4K context and small+ /// enough for an 8K one, so a single `setContext` moves a row in and out of+ /// `needsContext`.+ static let longMessageWords = 5_000++ /// Weights from the plan, with its 0.35 for sending split six to one+ /// between short and long messages: sending and browsing dominate+ /// because they are what a user does, and the destructive operations are+ /// frequent enough that a forty-step walk sees several of each.+ ///+ /// The three lifecycle operations take their 0.05 each out of the plain+ /// send, which is the only draw with enough weight to give it up and still+ /// dominate. A reload or an unload releases the KV, and every send after+ /// one has to open a new file rather than append to a conversation the+ /// model can no longer see.+ private static let weights:+ [(cumulative: Float, make: @Sendable (Int, Int, Int) -> HistoryOperation)] = [+ (0.15, { step, _, _ in .send(label: step) }),+ (0.20, { step, _, _ in .sendLong(label: step) }),+ (0.40, { _, row, _ in .open(row: row) }),+ (0.50, { _, _, _ in .newChat }),+ (0.60, { _, row, _ in .delete(row: row) }),+ (0.65, { step, row, _ in .rename(row: row, label: step) }),+ (0.70, { _, _, pick in .setContext(tokens: contexts[pick % contexts.count]) }),+ (0.75, { step, _, _ in .sendWithImage(label: step) }),+ (0.80, { _, _, _ in .failNextRestore }),+ (0.85, { _, _, _ in .relaunch }),+ (0.90, { _, _, _ in .reload }),+ (0.95, { _, _, _ in .unload }),+ (1.00, { step, _, _ in .stopMidTurn(label: step) }),+ ]++ static func next(step: Int, using generator: inout SplitMix64) -> HistoryOperation {+ let roll = generator.uniform(0, 1)+ let row = Int(generator.next() % 16)+ let pick = Int(generator.next() % 16)+ for entry in weights where roll < entry.cumulative {+ return entry.make(step, row, pick)+ }+ return .send(label: step)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Support/HistoryReferenceModel.swift b/Tests/TurboFieldfareApp/Core/Support/HistoryReferenceModel.swiftnew file mode 100644index 00000000..a9f5dba1--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/HistoryReferenceModel.swift@@ -0,0 +1,190 @@+import Foundation+@testable import TurboFieldfareAppCore++/// What the store and the window should hold, kept independently of both.+///+/// Deliberately not derived from `AppModel`: a check that reads the app's own+/// answer back to itself passes for a model that has silently done nothing. The+/// only thing learned from the app is the identifier of a conversation the app+/// creates, because the app picks it — and the invariants then require that+/// identifier to be new when a new chat was expected and unchanged when it was+/// not.+struct HistoryReferenceModel {+ struct ExpectedConversation: Equatable {+ /// The user half of every stored exchange, in order. The assistant half+ /// is the double's fixed reply and carries no information.+ var userTexts: [String] = []+ var imageCount = 0+ /// The last title a rename recorded. Nil while the title is still the+ /// one derived from the first message.+ var renamedTo: String?+ }++ private(set) var conversations: [UUID: ExpectedConversation] = [:]+ /// The order they were created in, which is not the order they are drawn+ /// in: the sidebar sorts by when a chat was last used.+ private(set) var created: [UUID] = []+ /// The conversation the KV is holding and the next turn is written to.+ private(set) var held: UUID?+ private var heldIsInKV = false+ /// A stored conversation on screen in place of the live one.+ private(set) var reading: UUID?+ /// The user half of every exchange the window still draws but the model can+ /// no longer see: a load or an unload rebuilt or released the KV while the+ /// conversation was on screen. They stay above the live conversation with a+ /// context break between, and nothing appends to their file again.+ private(set) var outOfContext: [String] = []+ /// The message of a turn that was stopped and is still drawn as the current+ /// one. A rewound turn is in neither the KV nor the transcript, so it is not+ /// an exchange — but the window keeps showing it, and a release that finds+ /// nothing else in the conversation carries exactly that one turn out of+ /// context with it.+ private(set) var stoppedTurnOnScreen: String?+ /// The next replay will fail, because a test armed it.+ private(set) var restoreFailureArmed = false+ /// The context in force, and separately the one a send has written to the+ /// settings file — a relaunch comes back with the second, not the first.+ var maxContextTokens: Int+ private(set) var persistedContextTokens: Int++ init(maxContextTokens: Int) {+ self.maxContextTokens = maxContextTokens+ self.persistedContextTokens = maxContextTokens+ }++ /// Turns the service's gate should be holding for the live conversation.+ var committedTurns: Int {+ guard heldIsInKV, let held else { return 0 }+ return conversations[held]?.userTexts.count ?? 0+ }++ func exchanges(in id: UUID) -> Int { conversations[id]?.userTexts.count ?? 0 }++ mutating func newChat() {+ held = nil+ heldIsInKV = false+ reading = nil+ outOfContext = []+ stoppedTurnOnScreen = nil+ }++ mutating func create(_ id: UUID) {+ conversations[id] = ExpectedConversation()+ created.append(id)+ }++ /// A send lands on `id`: it becomes the held conversation, nothing is being+ /// read any more, and the exchange is on disk.+ mutating func appendExchange(to id: UUID, userText: String, images: Int) {+ conversations[id, default: ExpectedConversation()].userTexts.append(userText)+ conversations[id, default: ExpectedConversation()].imageCount += images+ held = id+ heldIsInKV = true+ reading = nil+ stoppedTurnOnScreen = nil+ recordSettingsPersisted()+ }++ /// A send that started and produced no exchange: the turn was stopped and+ /// the runtime rewound it. The conversation exists — its directory is+ /// created when the send starts, not when the turn lands — and the window+ /// is holding it.+ mutating func stopTurn(in id: UUID, userText: String) {+ held = id+ heldIsInKV = true+ reading = nil+ stoppedTurnOnScreen = userText+ recordSettingsPersisted()+ }++ /// Every send persists the settings, so this is the context a relaunch+ /// comes back with. A stopped turn persists them too: it happens when the+ /// run starts, not when it finishes.+ mutating func recordSettingsPersisted() {+ persistedContextTokens = maxContextTokens+ }++ /// Opening a row replaces everything the window was drawing, including the+ /// out-of-context turns of the live conversation.+ mutating func read(_ id: UUID) {+ reading = id+ outOfContext = []+ }++ mutating func stopReading() {+ reading = nil+ outOfContext = []+ }++ /// A replay put a stored conversation back into the KV, so nothing on+ /// screen is out of context any more.+ mutating func adoptRestored() {+ outOfContext = []+ heldIsInKV = true+ }++ /// A load or an unload rebuilt or released the KV.+ ///+ /// Keep the viewed conversation, or the held one when viewing it live.+ /// Its next send replays the exact record before appending to the same file.+ mutating func releaseKV() {+ reading = reading ?? held+ heldIsInKV = false+ outOfContext = []+ stoppedTurnOnScreen = nil+ }++ mutating func rename(_ id: UUID, to title: String) {+ conversations[id]?.renamedTo = title+ }++ /// Deleting held KV must not clear a different conversation being read.+ mutating func delete(_ id: UUID) {+ conversations[id] = nil+ created.removeAll { $0 == id }+ if held == id {+ let remainingRead = reading == id ? nil : reading+ newChat()+ reading = remainingRead+ } else if reading == id {+ reading = heldIsInKV ? nil : held+ }+ }++ mutating func armRestoreFailure() { restoreFailureArmed = true }++ mutating func consumeRestoreFailure() { restoreFailureArmed = false }++ mutating func failRestoreDestructively() {+ restoreFailureArmed = false+ // After reload, held identifies a durable row but its KV is gone.+ // A failed replay cannot archive turns from that empty cache.+ if heldIsInKV {+ outOfContext += held.flatMap { conversations[$0]?.userTexts } ?? []+ }+ held = nil+ heldIsInKV = false+ stoppedTurnOnScreen = nil+ }++ /// Quitting and starting again. The store and selected row survive; no KV+ /// does, so the selection returns as a stored copy awaiting replay.+ mutating func relaunch() {+ let selected = reading ?? held+ held = nil+ heldIsInKV = false+ reading = selected.flatMap { conversations[$0] == nil ? nil : $0 }+ outOfContext = []+ stoppedTurnOnScreen = nil+ maxContextTokens = persistedContextTokens+ }++ /// The title the meta must carry: the rename if there was one, otherwise+ /// the one derived from the first message.+ func expectedTitle(of id: UUID) -> String? {+ guard let conversation = conversations[id] else { return nil }+ if let renamedTo = conversation.renamedTo { return renamedTo }+ guard let first = conversation.userTexts.first else { return nil }+ return ConversationTitle.fromFirstMessage(first)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swiftindex 6add911c..13ebe73a 100644--- a/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swift+++ b/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swift@@ -9,6 +9,8 @@ final class MockLifecycleInferenceClient: AppModelLifecycleClient, @unchecked Seprivate var unloadContinuations: [CheckedContinuation<Void, Never>] = []private var unloadStartedCount = 0private var loadStartedCount = 0+ private var generateStartedCount = 0+ private var shutdownStartedCount = 0private var loadStateHandlers: [@Sendable (AppModelLoadState) -> Void] = []private var nextLoadFailure: AppInferenceError?private(set) var ensureLoadedCalls: [(URL, Int, AppRuntimeOptions, Bool)] = []@@ -37,6 +39,24 @@ final class MockLifecycleInferenceClient: AppModelLifecycleClient, @unchecked SeloadSeconds: 0))}+ private var openedEpochs: [UUID] = []+ var conversationEpochs: [UUID] { lock.withLock { openedEpochs } }++ func resetConversation(epoch: UUID) async throws {+ lock.withLock { openedEpochs.append(epoch) }+ }++ func restoreConversation(+ _ lineage: AppConversationLineage,+ epoch: UUID,+ options: AppRuntimeOptions,+ maxContextTokens: Int,+ onPrefillProgress: @escaping @Sendable (Int, Int) -> Void+ ) async throws -> Int {+ lock.withLock { openedEpochs.append(epoch) }+ return lineage.tokenIDs.count+ }+func unload() async {if beginUnload() {await withCheckedContinuation { continuation in@@ -46,7 +66,6 @@ final class MockLifecycleInferenceClient: AppModelLifecycleClient, @unchecked Se}- func resetConversation(epoch _: UUID) async throws {}func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {AsyncThrowingStream { continuation in@@ -70,6 +89,12 @@ final class MockLifecycleInferenceClient: AppModelLifecycleClient, @unchecked Sefunc cancel() {}+ func shutdownForTermination() {+ lock.withLock { shutdownStartedCount += 1 }+ }++ var shutdownCount: Int { lock.withLock { shutdownStartedCount } }+func releaseUnloads() {let continuations: [CheckedContinuation<Void, Never>]lock.lock()diff --git a/Tests/TurboFieldfareApp/Core/Support/SendWaiting.swift b/Tests/TurboFieldfareApp/Core/Support/SendWaiting.swiftnew file mode 100644index 00000000..571ecdd4--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/SendWaiting.swift@@ -0,0 +1,35 @@+import Foundation+@testable import TurboFieldfareAppCore++/// Waiting for a send, which is a pipeline rather than a call.+///+/// `send()` takes the composer synchronously — so a second Generate is refused+/// on the same run-loop turn — and then runs its stages in its own task: the+/// replay, the ticket, the request, the retained images, the generation, the+/// commit or the hand-back. `isRunning` is therefore true a hop or two after+/// the click rather than on the line below it, and a test that asserted either+/// state immediately after `send()` was asserting the scheduler.+@MainActor+enum SendWaiting {+ /// Until the runtime is generating, or the send ended without reaching a+ /// generation at all — which is what a refused request does.+ static func generationStarts(_ model: AppModel) async {+ let deadline = Date().addingTimeInterval(5)+ while Date() < deadline, model.isTurnInFlight, !model.isRunning {+ await Task.yield()+ }+ }++ /// Until the whole send has resolved: committed, refused, or handed back.+ ///+ /// Polled rather than yielded: a turn whose double answers a token a second+ /// is a real case here, and spinning the main actor through it costs more+ /// than the wait.+ static func turnEnds(_ model: AppModel) async {+ let deadline = Date().addingTimeInterval(30)+ while Date() < deadline, model.isTurnInFlight {+ try? await Task.sleep(for: .milliseconds(1))+ }+ await model.persistenceTail?.value+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/AccessibilityIDTests.swift b/Tests/TurboFieldfareApp/MacPresentation/AccessibilityIDTests.swiftnew file mode 100644index 00000000..e53a542f--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/AccessibilityIDTests.swift@@ -0,0 +1,30 @@+import Foundation+import Testing+import TurboFieldfareMacPresentation++struct AccessibilityIDTests {+ /// The driver matches identifiers exactly and the coverage script greps+ /// them, so a name outside the `surface.control` shape would be reachable+ /// by neither.+ @Test func everyIdentifierIsNamespacedBySurface() {+ for id in AccessibilityID.allCases {+ #expect(id.rawValue.range(of: #"^[a-z]+(\.[A-Za-z]+)+$"#, options: .regularExpression) != nil,+ "\(id.rawValue) is not surface.control")+ }+ for prefix in AccessibilityID.Prefix.allCases {+ #expect(prefix.rawValue.hasSuffix("."), "\(prefix.rawValue) must end in a dot")+ #expect(!AccessibilityID.allCases.contains { $0.rawValue == String(prefix.rawValue.dropLast()) },+ "\(prefix.rawValue) collides with a static identifier")+ }+ }++ /// A row and its menu share the row prefix; the driver tells them apart by+ /// exact match, and a case tells them apart by the family name.+ @Test func mintedIdentifiersCarryTheirFamilyPrefix() {+ let id = UUID()+ #expect(AccessibilityID.row(id) == "history.row." + id.uuidString)+ #expect(AccessibilityID.rowMenu(id) == "history.row.menu." + id.uuidString)+ #expect(AccessibilityID.remove("staged-1") == "composer.remove.staged-1")+ #expect(AccessibilityID.example("code") == "examples.code")+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/ConversationSidebarPresentationTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ConversationSidebarPresentationTests.swiftnew file mode 100644index 00000000..dba61b7b--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/ConversationSidebarPresentationTests.swift@@ -0,0 +1,197 @@+import Foundation+import SwiftUI+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore+@testable import TurboFieldfareMacPresentation++/// A row that cannot be continued has to say which of the two very different+/// things went wrong, and what it would take to fix. A greyed-out row says+/// neither, which is why none of these states is one.+@Suite struct ConversationSidebarPresentationTests {+ private let identity = ConversationIdentity(+ modelID: "google/gemma-4-26B-A4B-it",+ sourceSnapshotHash: "0d77464e",+ templateIdentity: GFTokenizer.chatTemplateIdentity,+ imageProcessingVersion: VisionImageProcessing.version)++ private func meta(_ title: String = "Explain RoPE",+ kvTokens: Int? = 1_200,+ updatedAt: Date = Date()) -> ConversationMeta {+ ConversationMeta(+ id: UUID(), title: title, createdAt: updatedAt, updatedAt: updatedAt,+ turnCount: 4, kvTokens: kvTokens, identity: identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "onDemand"),+ sampling: ConversationSampling(+ temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 4_096))+ }++ private var calendar: Calendar {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(secondsFromGMT: 0)!+ return calendar+ }++ /// The boundaries, against an injected `now`. A grouping only checked at+ /// whatever time the suite happened to run is a grouping nobody has checked.+ @Test func theDayBoundariesLandWhereTheHeadingsSayTheyDo() {+ let calendar = calendar+ let now = calendar.date(from: DateComponents(+ year: 2026, month: 8, day: 31, hour: 14))!+ func group(daysAgo: Int, hour: Int = 12) -> ConversationDateGroup {+ let day = calendar.date(byAdding: .day, value: -daysAgo, to: now)!+ let at = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: day)!+ return ConversationDateGroup.group(for: at, now: now, calendar: calendar)+ }+ // One minute after midnight today is still Today; one minute before it+ // is Yesterday, even though they are two minutes apart.+ #expect(group(daysAgo: 0, hour: 0) == .today)+ #expect(group(daysAgo: 1, hour: 23) == .yesterday)+ #expect(group(daysAgo: 2) == .previousSevenDays)+ #expect(group(daysAgo: 7) == .previousSevenDays)+ #expect(group(daysAgo: 8) == .older)+ // A clock change or a restored backup can date a chat in the future.+ // "Older" would be the one place it certainly does not belong.+ let tomorrow = calendar.date(byAdding: .day, value: 1, to: now)!+ #expect(ConversationDateGroup.group(+ for: tomorrow, now: now, calendar: calendar) == .today)+ }++ @Test func sectionsAreOrderedNewestFirstWithinAndBetween() {+ let now = Date()+ let today = meta("today", updatedAt: now.addingTimeInterval(-60))+ let earlierToday = meta("earlier", updatedAt: now.addingTimeInterval(-3_600))+ let old = meta("old", updatedAt: now.addingTimeInterval(-60 * 60 * 24 * 30))+ let sections = ConversationDateGroup.sections([old, earlierToday, today], now: now)+ #expect(sections.map(\.group) == [.today, .older])+ #expect(sections[0].entries.map(\.title) == ["today", "earlier"])+ }++ /// Exact numbers, because "needs more context" is not something a user can+ /// act on and the picker only offers certain sizes.+ @Test func eachStateHasItsOwnSubtitle() {+ #expect(ConversationRowPresentation.subtitle(+ meta(kvTokens: 6_120), state: .continuable).contains("6,120"))++ // What it holds, then the context it needs rounded up to a size the+ // picker actually offers. The raw requirement is not a thing anyone can+ // select, so the row names the option instead.+ #expect(ConversationRowPresentation.subtitle(+ meta(kvTokens: 6_120), state: .needsContext(required: 6_376))+ == "6,120 tokens \u{00B7} needs 8K context")++ #expect(ConversationRowPresentation.subtitle(+ meta(), state: .cannotReplay(reason: .differentModel))+ == "recorded with a different model")+ #expect(ConversationRowPresentation.subtitle(+ meta(), state: .cannotReplay(reason: .differentTemplate))+ == "recorded with a different chat format")+ #expect(ConversationRowPresentation.subtitle(+ meta(kvTokens: nil), state: .cannotReplay(reason: .tokenCountUnknown))+ == "no replay record")++ let missingImage = ConversationMeta(+ id: UUID(), title: "roofs", createdAt: Date(), updatedAt: Date(),+ turnCount: 2, kvTokens: nil, imageCount: 1,+ identity: identity,+ session: ConversationSessionSettings(+ contextTokens: 8_192, expertCacheSlots: 16,+ visionResidencyPolicy: "on-demand"),+ sampling: ConversationSampling(+ temperature: 0.2, topKEnabled: true, topK: 64,+ topPEnabled: true, topP: 0.95, maxNewTokens: 8_192),+ imageWriteFailed: true)+ let state = ConversationContinuability.evaluate(+ meta: missingImage, currentContext: 8_192, identity: identity)+ #expect(ConversationRowPresentation.subtitle(missingImage, state: state)+ == "an image was not saved")+ }++ /// Raising the context reloads the model and ends the chat that is open.+ /// Finding that out afterwards is the failure this copy exists to prevent.+ @Test func theNoticeNamesTheContextAndWhatRaisingItCosts() throws {+ let content = try #require(ConversationStateNotice.content(+ for: .needsContext(required: 6_376), currentContext: 4_096))+ #expect(content.message.contains("6,376"))+ #expect(content.message.contains("4,096"))+ #expect(content.message.contains("8K"))+ #expect(content.message.contains("reloads the model"))+ #expect(content.message.contains("ends the chat"))+ #expect(content.requiredContext == 6_376)+ // Re-reading is not offered here: the conversation replays fine, it+ // just does not fit, and a re-read would throw away a working lineage.+ #expect(!content.offersReread)+ }++ /// A re-read is a different conversation and has to be named as one+ /// wherever it appears. Presenting it as "Continue" is the one thing it+ /// must never do.+ @Test func theUnreplayableNoticeOffersARereadAndSaysItIsOne() throws {+ let content = try #require(ConversationStateNotice.content(+ for: .cannotReplay(reason: .differentModel), currentContext: 8_192))+ #expect(content.offersReread)+ #expect(content.requiredContext == nil)+ #expect(content.message.contains("re-read"))+ #expect(content.message.contains("different conversation"))+ }++ @Test func theMissingImageNoticeNamesTheStorageFailure() throws {+ let content = try #require(ConversationStateNotice.content(+ for: .cannotReplay(reason: .imageRecordMissing),+ currentContext: 8_192))+ #expect(content.offersReread)+ #expect(content.message.contains("could not be saved"))+ }++ @Test func aNewerFormatNoticeRefusesReplayAndNamesTheRequiredUpgrade() throws {+ let content = try #require(ConversationStateNotice.content(+ for: .cannotReplay(reason: .newerFormat), currentContext: 8_192))+ #expect(!content.offersReread)+ #expect(content.message.contains("newer history format"))+ #expect(content.message.contains("saved files are unchanged"))+ }++ @Test func aContinuableChatShowsNoNotice() {+ #expect(ConversationStateNotice.content(+ for: .continuable, currentContext: 8_192) == nil)+ }+}++@Suite struct WindowControlsPresentationTests {+ /// The toggle's help has to describe what clicking it will do, which is the+ /// opposite of the state it is in.+ @Test func theToggleHelpNamesTheActionNotTheState() {+ #expect(WindowControlsPresentation.sidebarToggleHelp(isVisible: true)+ == "Hide Sidebar")+ #expect(WindowControlsPresentation.sidebarToggleHelp(isVisible: false)+ == "Show Sidebar")+ #expect(WindowControlsPresentation.sidebarToggleAccessibilityLabel(isVisible: true)+ == "Hide Sidebar")+ #expect(WindowControlsPresentation.newChatHelp == "New Chat")+ }++ /// The Inspector toggle is the sidebar toggle's mirror, so it has to name+ /// the action the same way round.+ @Test func theInspectorToggleHelpNamesTheActionNotTheState() {+ #expect(WindowControlsPresentation.inspectorToggleHelp(isVisible: true)+ == "Hide Inspector")+ #expect(WindowControlsPresentation.inspectorToggleHelp(isVisible: false)+ == "Show Inspector")+ #expect(WindowControlsPresentation.inspectorToggleAccessibilityLabel(isVisible: false)+ == "Show Inspector")+ }+}++@Suite struct TransientPopoverPresentationTests {+ @MainActor+ @Test func promptTipsDismissesThroughTransientAppKitBehavior() {+ let coordinator = TransientPopoverButton(systemImage: "lightbulb", help: "Prompt Tips") {+ EmptyView()+ }.makeCoordinator()+ #expect(TransientPopoverPresentation.behavior == .transient)+ #expect(coordinator.popover.behavior == .transient)+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicyTests.swiftindex 9097150b..f344f4b6 100644--- a/Tests/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicyTests.swift+++ b/Tests/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicyTests.swift@@ -4,6 +4,14 @@ import Testing@testable import TurboFieldfareMacPresentation@Suite struct GenericErrorBannerPolicyTests {+ @Test func persistenceFailureIsVisibleWithAReadyModel() {+ let error = AppInferenceError.conversationPersistenceFailed("Permission denied")+ #expect(GenericErrorBannerPolicy.shouldShow(+ error: error, loadState: .ready(modelDirectory: URL(fileURLWithPath: "/fixture"), loadSeconds: 0)))+ #expect(error.userMessage.contains("not be saved"))+ #expect(error.technicalDetail.contains("Permission denied"))+ }+@Test func nilErrorIsHidden() {#expect(!GenericErrorBannerPolicy.shouldShow(error: nil, loadState: .notLoaded))}diff --git a/Tests/TurboFieldfareApp/MacPresentation/ImagePasteboardPayloadTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ImagePasteboardPayloadTests.swiftnew file mode 100644index 00000000..4b7c4519--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/ImagePasteboardPayloadTests.swift@@ -0,0 +1,106 @@+import AppKit+import Testing+@testable import TurboFieldfareMacPresentation++@Suite struct ImagePasteboardPayloadTests {+ private func board() -> NSPasteboard {+ let board = NSPasteboard(name: NSPasteboard.Name(UUID().uuidString))+ board.clearContents()+ return board+ }++ private func png() throws -> Data {+ let image = NSImage(size: NSSize(width: 1, height: 1))+ image.lockFocus()+ NSColor.red.setFill()+ NSRect(x: 0, y: 0, width: 1, height: 1).fill()+ image.unlockFocus()+ let tiff = try #require(image.tiffRepresentation)+ let bitmap = try #require(NSBitmapImageRep(data: tiff))+ return try #require(bitmap.representation(using: .png, properties: [:]))+ }++ private func bitmap() throws -> NSBitmapImageRep {+ let image = try #require(NSImage(data: png()))+ let tiff = try #require(image.tiffRepresentation)+ return try #require(NSBitmapImageRep(data: tiff))+ }++ @Test func incidentalStringDoesNotDefeatPureImage() throws {+ let board = board()+ board.declareTypes([.png, .string], owner: nil)+ board.setData(try png(), forType: .png)+ board.setString("Preview", forType: .string)++ guard case .image(_, let name) = ImagePasteboardPayload.read(from: board)+ else { Issue.record("a decodable image was not classified as an image"); return }+ #expect(name == "Pasted image.png")+ }++ @Test func richTextWithImageRemainsText() throws {+ let board = board()+ board.declareTypes([.png, .rtf, .string], owner: nil)+ board.setData(try png(), forType: .png)+ board.setData(Data("{\\rtf1 selected}".utf8), forType: .rtf)+ board.setString("selected", forType: .string)+ guard case .text = ImagePasteboardPayload.read(from: board)+ else { Issue.record("a genuine rich-text selection did not remain text"); return }+ }++ @Test func malformedDeclaredImageIsReportedUnsupported() {+ let board = board()+ board.declareTypes([.png], owner: nil)+ board.setData(Data("not an image".utf8), forType: .png)+ guard case .unsupportedImage = ImagePasteboardPayload.read(from: board)+ else { Issue.record("malformed image bytes were treated as usable"); return }+ }++ @Test func jpegAndTiffAreDecodedAndTiffIsNormalizedToPNG() throws {+ let jpegBoard = board()+ let jpegType = NSPasteboard.PasteboardType("public.jpeg")+ jpegBoard.declareTypes([jpegType], owner: nil)+ jpegBoard.setData(+ try bitmap().representation(using: .jpeg, properties: [:]),+ forType: jpegType)+ guard case .image(_, let jpegName) = ImagePasteboardPayload.read(from: jpegBoard)+ else { Issue.record("JPEG was not accepted"); return }+ #expect(jpegName.hasSuffix(".jpeg"))++ let tiffBoard = board()+ tiffBoard.declareTypes([.tiff], owner: nil)+ tiffBoard.setData(try #require(NSImage(data: png())?.tiffRepresentation), forType: .tiff)+ guard case .image(let normalized, let tiffName) = ImagePasteboardPayload.read(from: tiffBoard)+ else { Issue.record("TIFF was not accepted"); return }+ #expect(NSBitmapImageRep(data: normalized)?.representation(using: .png, properties: [:]) != nil)+ #expect(tiffName.hasSuffix(".png"))+ }++ @Test func supportedFileURLWinsAndPlainTextRemainsText() throws {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("paste-\(UUID()).png")+ try png().write(to: url)+ defer { try? FileManager.default.removeItem(at: url) }+ let fileBoard = board()+ fileBoard.writeObjects([url as NSURL])+ guard case .fileURLs(let urls) = ImagePasteboardPayload.read(from: fileBoard)+ else { Issue.record("supported file URL was not accepted"); return }+ #expect(urls == [url])++ let textBoard = board()+ textBoard.setString("plain text", forType: .string)+ guard case .text = ImagePasteboardPayload.read(from: textBoard)+ else { Issue.record("plain text was not preserved"); return }+ }++ @Test func unsupportedImageFlavorAndEmptyBoardAreDistinct() {+ let unsupported = board()+ let gif = NSPasteboard.PasteboardType("com.compuserve.gif")+ unsupported.declareTypes([gif], owner: nil)+ unsupported.setData(Data("GIF89a".utf8), forType: gif)+ guard case .unsupportedImage = ImagePasteboardPayload.read(from: unsupported)+ else { Issue.record("unsupported image flavor was not diagnosed"); return }++ guard case .none = ImagePasteboardPayload.read(from: board())+ else { Issue.record("an empty pasteboard was not empty"); return }+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/ProgressiveTranscriptRenderTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ProgressiveTranscriptRenderTests.swiftindex 1312be20..e16a9a33 100644--- a/Tests/TurboFieldfareApp/MacPresentation/ProgressiveTranscriptRenderTests.swift+++ b/Tests/TurboFieldfareApp/MacPresentation/ProgressiveTranscriptRenderTests.swift@@ -604,14 +604,14 @@ import Testing// MARK: - Scroll follow- /// A tail re-render must not pull a reader who has scrolled up back to the- /// bottom; only the finalize restyle does that.+ /// Neither a tail re-render nor final formatting may take the scroll from+ /// a reader who moved away from the bottom.@Test func tailReplacementFollowsTheSameScrollRuleAsAnAppend() {#expect(!InstructionTranscriptDocumentController.shouldScrollToBottom(wasAtBottom: false, mutation: .tailReplaced))#expect(InstructionTranscriptDocumentController.shouldScrollToBottom(wasAtBottom: true, mutation: .tailReplaced))- #expect(InstructionTranscriptDocumentController.shouldScrollToBottom(+ #expect(!InstructionTranscriptDocumentController.shouldScrollToBottom(wasAtBottom: false, mutation: .finalized))}}diff --git a/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swiftindex a4e0cf7f..87df6458 100644--- a/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift+++ b/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift@@ -1479,8 +1479,8 @@ import Testing#expect(milliseconds(unchanged) < 1)}- @Test func terminalFormattingAlwaysScrollsToBottom() {- #expect(InstructionTranscriptDocumentController.shouldScrollToBottom(+ @Test func terminalFormattingPreservesReaderOwnedScroll() {+ #expect(!InstructionTranscriptDocumentController.shouldScrollToBottom(wasAtBottom: false,mutation: .finalized))#expect(InstructionTranscriptDocumentController.shouldScrollToBottom(diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptImageCellsTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptImageCellsTests.swiftnew file mode 100644index 00000000..f533a38c--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptImageCellsTests.swift@@ -0,0 +1,55 @@+import AppKit+import Testing+import TurboFieldfareAppCore+@testable import TurboFieldfareMacPresentation++/// A turn's inline image row has to say how many pictures the turn had, not how+/// many of them happen to be readable right now.+@Suite struct TranscriptImageCellsTests {+ private func attachment(_ name: String) -> ChatImage {+ .staged(StagedImage(+ fileURL: URL(fileURLWithPath: "/tmp/\(name)"),+ displayName: name, encodedBytes: 1, sha256: name))+ }++ private func image(_ side: CGFloat) -> NSImage {+ NSImage(size: NSSize(width: side, height: side))+ }++ /// The regression. A stored conversation can lose a file to anything+ /// outside this app, and dropping the cell rendered the turn as one that+ /// never had a picture — under an answer discussing it. The reader could+ /// not tell the two apart.+ @Test func anUnreadableImageKeepsItsCell() {+ let attachments = [attachment("a"), attachment("b"), attachment("c")]+ let stand = image(160)+ let cells = TranscriptImageCells.images(+ for: attachments,+ load: { $0.displayName == "b" ? nil : self.image(10) },+ unreadable: { stand })++ #expect(cells.count == 3, "the unreadable image was dropped")+ #expect(cells[1] === stand)+ #expect(cells[0] !== stand)+ #expect(cells[2] !== stand)+ }++ /// And the stand-in is only reached when it is needed: building it for+ /// every turn would decode a symbol on each redraw of a transcript that has+ /// nothing wrong with it.+ @Test func areadableImageNeverBuildsTheStandIn() {+ var built = 0+ let cells = TranscriptImageCells.images(+ for: [attachment("a"), attachment("b")],+ load: { _ in self.image(10) },+ unreadable: { built += 1; return self.image(160) })++ #expect(cells.count == 2)+ #expect(built == 0)+ }++ @Test func noAttachmentsMakeNoCells() {+ #expect(TranscriptImageCells.images(+ for: [], load: { _ in nil }, unreadable: { self.image(160) }).isEmpty)+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptMultiTurnTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptMultiTurnTests.swiftindex 2cc85686..148a9a95 100644--- a/Tests/TurboFieldfareApp/MacPresentation/TranscriptMultiTurnTests.swift+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptMultiTurnTests.swift@@ -10,6 +10,25 @@ import Testing/// `setAttributedString`, which took the history with it.@MainActor@Suite struct TranscriptMultiTurnTests {+ @Test(arguments: [true, false])+ func clearingReplayLeavesNoEmptyAnswer(progressive: Bool) {+ let controller = InstructionTranscriptDocumentController(+ environment: ["TURBO_FIELDFARE_PROGRESSIVE_RENDER": progressive ? "1" : "0"])+ let storage = NSMutableAttributedString()+ firstTurn(controller, storage)+ let history = NSAttributedString(attributedString: storage)+ _ = controller.synchronize(storage: storage, prompt: "pending", response: "",+ isTerminal: false, showsPrefillPlaceholder: true)+ // Recovery restores the draft to the composer, leaving no live turn.+ _ = controller.synchronize(storage: storage, prompt: "", response: "", isTerminal: true)+ _ = controller.synchronize(storage: storage, prompt: "", response: "", isTerminal: false)+ #expect(storage.isEqual(to: history))+ #expect(controller.assistantRange == NSRange(location: history.length, length: 0))+ _ = controller.synchronize(storage: storage, prompt: "retry", response: "OK", isTerminal: true)+ #expect(storage.string.components(separatedBy: "Answer\n").count == 3)+ #expect(storage.string.hasSuffix("OK"))+ }+private func controller() -> InstructionTranscriptDocumentController {InstructionTranscriptDocumentController()}diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptScrollFollowTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptScrollFollowTests.swiftindex 788495e0..3d17e693 100644--- a/Tests/TurboFieldfareApp/MacPresentation/TranscriptScrollFollowTests.swift+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptScrollFollowTests.swift@@ -104,6 +104,14 @@ import CoreGraphicslet afterEnd = follow.shouldScrollToBottom(origin: 0, documentHeight: 10_000)#expect(!afterEnd)}++ @MainActor+ @Test func finalizationDoesNotOverrideReaderOwnership() {+ #expect(!InstructionTranscriptDocumentController.shouldScrollToBottom(+ wasAtBottom: false, mutation: .finalized))+ #expect(InstructionTranscriptDocumentController.shouldScrollToBottom(+ wasAtBottom: true, mutation: .finalized))+ }}/// The composer's attachment tiles. Aspect-fitting them gave a row ofdiff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptSyncPlannerTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptSyncPlannerTests.swiftindex 8611fcba..914b6a2a 100644--- a/Tests/TurboFieldfareApp/MacPresentation/TranscriptSyncPlannerTests.swift+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptSyncPlannerTests.swift@@ -13,6 +13,20 @@ import TestingstartedNewRun: startedNewRun, firstSynchronize: firstSynchronize)}+ @Test(arguments: [0, 1, 2, 3])+ func changedEpochDrawsHistoryInTheFirstUpdate(count: Int) {+ var planner = TranscriptSyncPlanner()+ let viewed = UUID()+ _ = planner.plan(input(epoch: viewed, history: 1, firstSynchronize: true))+ _ = planner.plan(input(epoch: viewed, history: 1, startedNewRun: true))+ let restored = UUID()+ let expected: [TranscriptSyncStep] = [.reset]+ + (0..<count).map { .drawPair(index: $0) }+ #expect(planner.plan(input(epoch: restored, history: count, startedNewRun: true))+ == expected)+ #expect(planner.plan(input(epoch: restored, history: count)).isEmpty)+ }+@Test func afreshCoordinatorDrawsTheHistoryItFinds() {var planner = TranscriptSyncPlanner()let epoch = UUID()diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptTransitionTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptTransitionTests.swiftnew file mode 100644index 00000000..b932bec7--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptTransitionTests.swift@@ -0,0 +1,85 @@+import AppKit+import Foundation+import Testing+@testable import TurboFieldfareMacPresentation++@MainActor+@Suite struct TranscriptTransitionTests {+ @Test(arguments: [true, false])+ func replayDrawsTheSavedPairBeforeThePendingImageTurn(progressive: Bool) {+ let controller = InstructionTranscriptDocumentController(+ environment: ["TURBO_FIELDFARE_PROGRESSIVE_RENDER": progressive ? "1" : "0"])+ let storage = NSMutableAttributedString()+ var planner = TranscriptSyncPlanner()+ let prefix = NSAttributedString(string: "[saved image]\n")+ func update(_ epoch: UUID, first: Bool, newRun: Bool) {+ controller.synchronizeHistory(storage: storage, planner: &planner,+ input: .init(epoch: epoch, historyCount: 1, contextBreak: nil,+ startedNewRun: newRun, firstSynchronize: first)) { _ in+ _ = controller.synchronize(storage: storage, prompt: "code word",+ response: "OK", isTerminal: true,+ promptPrefix: prefix, promptPrefixIdentifier: "saved-image")+ }+ }+ update(UUID(), first: true, newRun: false)+ let restored = UUID()+ update(restored, first: false, newRun: true)+ _ = controller.synchronize(storage: storage, prompt: "explain it", response: "",+ isTerminal: false, showsPrefillPlaceholder: true,+ promptPrefix: NSAttributedString(string: "[pending image]\n"),+ promptPrefixIdentifier: "pending-image")+ // Inspect the first update, with no later timer/model event to repair it.+ #expect(storage.string.contains("code word"))+ #expect(storage.string.contains("OK"))+ #expect(storage.string.contains("[saved image]"))+ #expect(storage.string.contains("explain it"))+ #expect(storage.string.contains("[pending image]"))+ let frozen = controller.frozenLength+ let history = storage.attributedSubstring(from: NSRange(location: 0, length: frozen))+ update(restored, first: false, newRun: false)+ #expect(controller.frozenLength == frozen)+ #expect(storage.attributedSubstring(from: NSRange(location: 0, length: frozen))+ .isEqual(to: history))+ #expect(storage.string.components(separatedBy: "code word").count == 2)+ }++ @Test(arguments: [true, false], ["$$x = 1$$", "$$x = 1$$\n\n",+ "Final paragraph $x^2$", "$$\\begin{bmatrix}1 & 2 \\\\ 3 & 4\\end{bmatrix}$$"])+ func completedMathSurvivesSealingAndLaterTokens(progressive: Bool, answer: String) {+ let typesetter = FakeMathTypesetter()+ let controller = InstructionTranscriptDocumentController(+ renderer: ResponseMarkdownRenderer(typesetter: typesetter),+ environment: ["TURBO_FIELDFARE_PROGRESSIVE_RENDER": progressive ? "1" : "0"])+ let storage = NSMutableAttributedString()+ var planner = TranscriptSyncPlanner()+ let epoch = UUID()+ controller.synchronizeHistory(storage: storage, planner: &planner,+ input: .init(epoch: epoch, historyCount: 0, contextBreak: nil,+ startedNewRun: false, firstSynchronize: true)) { _ in+ Issue.record("No history should be drawn")+ }+ _ = controller.synchronize(storage: storage, prompt: "formula", response: answer,+ isTerminal: true)+ let completed = NSAttributedString(attributedString: storage)+ let calls = typesetter.calls.count+ #expect(calls > 0)+ #expect(!storage.string.contains("$$"))+ // The queued-send model regression separately pins that this stays terminal.+ _ = controller.synchronize(storage: storage, prompt: "formula", response: answer,+ isTerminal: true)+ controller.synchronizeHistory(storage: storage, planner: &planner,+ input: .init(epoch: epoch, historyCount: 1, contextBreak: nil,+ startedNewRun: true, firstSynchronize: false)) { _ in+ Issue.record("Same-epoch history must be sealed without rerendering")+ }+ for response in ["", "next", "next answer"] {+ _ = controller.synchronize(storage: storage, prompt: "follow up", response: response,+ isTerminal: false)+ #expect(storage.attributedSubstring(from: NSRange(location: 0,+ length: completed.length)).isEqual(to: completed))+ }+ #expect(controller.answer(at: 0) == answer, "Copy must retain the original LaTeX")+ #expect(typesetter.calls.count == calls)+ #expect(storage.string.components(separatedBy: "follow up").count == 2)+ }+}diff --git a/Tests/TurboFieldfareDecodeService/DecodeConversationRestoreTests.swift b/Tests/TurboFieldfareDecodeService/DecodeConversationRestoreTests.swiftnew file mode 100644index 00000000..12a9ab52--- /dev/null+++ b/Tests/TurboFieldfareDecodeService/DecodeConversationRestoreTests.swift@@ -0,0 +1,238 @@+import Foundation+import Testing+import TurboFieldfareAppCore+import TurboFieldfareDecodeProtocol+@testable import TurboFieldfareDecodeService++/// Reopening a stored conversation puts turns back into a KV the service can+/// only append to. Every case here is a way the reopened lineage could end up+/// disagreeing with the transcript the user is reading, which no later check+/// can detect.+@Suite struct DecodeConversationRestoreTests {+ private func turn(_ epoch: UUID?, _ index: Int?) -> DecodeGenerationRequest {+ DecodeGenerationRequest(+ prompt: "hello", maxNewTokens: 16, maxContextTokens: 8_192,+ temperature: 0, conversationEpoch: epoch, turnIndex: index)+ }++ /// The bug this pins: opening a restored lineage at zero, the way a reset+ /// does, rejects the reopened conversation's next turn as out of order and+ /// keeps rejecting every turn after it.+ @Test func aRestoredLineageContinuesAtItsStoredTurnCount() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.restore(to: epoch, committedTurns: 4)+ #expect(gate.admit(turn(epoch, 4)) == .success(.turn(epoch: epoch, index: 4)))+ #expect(gate.admit(turn(epoch, 3))+ == .failure(.outOfOrderTurn(requested: 3, committed: 4)))+ #expect(gate.admit(turn(epoch, 5))+ == .failure(.outOfOrderTurn(requested: 5, committed: 4)))+ }++ @Test func aTurnForTheReplacedConversationIsStillRefusedAfterARestore() {+ let stale = UUID()+ let restored = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: stale)+ gate.commit(.turn(epoch: stale, index: 0))+ gate.restore(to: restored, committedTurns: 2)+ #expect(gate.admit(turn(stale, 2))+ == .failure(.staleConversation(requested: stale, open: restored)))+ // And a one-shot cannot run over the restored lineage either.+ #expect(gate.admit(turn(nil, nil))+ == .failure(.oneShotDuringConversation(open: restored)))+ }++ /// The count arrives over a socket. A negative one would make `committedTurns`+ /// unreachable by any turn index and lock the conversation out for good.+ @Test func aNegativeStoredTurnCountIsClampedRatherThanTrusted() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.restore(to: epoch, committedTurns: -3)+ #expect(gate.committedTurns == 0)+ #expect(gate.admit(turn(epoch, 0)) == .success(.turn(epoch: epoch, index: 0)))+ }++ /// A restore that fails has already taken the KV it was replacing.+ ///+ /// The session resets before it prefills, so by the time a digest mismatch+ /// or a bad token refuses the record, the previous lineage's tokens are+ /// gone. Leaving its epoch open admitted its next turn onto an empty cache+ /// as an opening turn, under a transcript showing three exchanges.+ @Test func aFailedRestoreEndsTheLineageItReplaced() {+ let previous = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: previous)+ gate.commit(.turn(epoch: previous, index: 0))+ gate.commit(.turn(epoch: previous, index: 1))+ gate.commit(.turn(epoch: previous, index: 2))++ gate.restoreFailed()++ #expect(gate.openEpoch == nil)+ #expect(gate.committedTurns == 0)+ #expect(gate.admit(turn(previous, 3))+ == .failure(.staleConversation(requested: previous, open: nil)))+ // Nothing is open, so a one-shot may reset the cache and run.+ #expect(gate.admit(turn(nil, nil)) == .success(.oneShot))+ }++ @Test func unloadEndsARestoredLineageToo() {+ let epoch = UUID()+ var gate = DecodeConversationGate()+ gate.restore(to: epoch, committedTurns: 2)+ gate.endLineage()+ #expect(gate.openEpoch == nil)+ #expect(gate.admit(turn(epoch, 2))+ == .failure(.staleConversation(requested: epoch, open: nil)))+ }++ /// A refused turn is a lost lineage, not a failure.+ ///+ /// The service used to send `kind: .failed`, which the app turns into a+ /// retryable `.unknown` — so it put the message back in the composer and+ /// offered a retry that the gate refuses identically every time. Nothing+ /// but a new chat can clear a refusal, and `.lineageLost` is the kind that+ /// says so. `DecodeServiceInferenceClient` maps it to+ /// `conversationLineageLost`; `.failed` it does not.+ @Test func agateRefusalIsSentBackAsALostLineage() throws {+ let stale = UUID()+ let open = UUID()+ var gate = DecodeConversationGate()+ gate.reset(to: open)+ guard case .failure(let rejection) = gate.admit(turn(stale, 0)) else {+ Issue.record("a turn from a replaced conversation was admitted")+ return+ }++ let generationID = UUID()+ let event = rejection.terminalEvent(+ generationID: generationID,+ conversationEpoch: gate.openEpoch)++ #expect(event.kind == .lineageLost, "the app would offer a doomed retry")+ #expect(event.generationID == generationID)+ #expect(event.error == rejection.message)+ #expect(event.conversationEpoch == open)+ // And it survives the wire as that kind, which is what the app reads.+ let frame = try DecodeFrameCodec.encode(event)+ let decoded = try JSONDecoder().decode(+ DecodeServiceEvent.self, from: frame.dropFirst(4))+ #expect(decoded.kind == .lineageLost)+ #expect(decoded.error == rejection.message)+ }++ /// Every rejection the gate can produce takes the same route.+ @Test func everyRefusalKindIsSentBackAsALostLineage() {+ let open = UUID()+ let rejections: [DecodeConversationGate.Rejection] = [+ .staleConversation(requested: UUID(), open: open),+ .outOfOrderTurn(requested: 3, committed: 1),+ .oneShotDuringConversation(open: open),+ ]+ for rejection in rejections {+ let event = rejection.terminalEvent(+ generationID: UUID(),+ conversationEpoch: open)+ #expect(event.kind == .lineageLost)+ #expect(event.error == rejection.message)+ }+ }++ @Test func theRestoreRequestSurvivesTheWireWithItsTokenIDs() throws {+ let request = DecodeRestoreConversationRequest(+ tokenIDs: [2, 105, -1, 262_143],+ images: [DecodeReplayImage(+ tokenLowerBound: 12, tokenCount: 256,+ path: "/tmp/a.png", expectedDigest: "ab12")],+ boundaryTokenIDs: [77],+ boundaryNeedsReplay: true,+ committedTurns: 3,+ maxContextTokens: 8_192)+ let frame = try DecodeFrameCodec.encode(+ DecodeServiceCommand.restoreConversation(request))+ let decoded = try JSONDecoder().decode(+ DecodeServiceCommand.self, from: frame.dropFirst(4))+ guard case .restoreConversation(let round) = decoded else {+ Issue.record("the command decoded as something else")+ return+ }+ #expect(round == request)+ }++ /// 8K `Int32` as JSON is about 50 KB against a 4 MiB frame cap, and 64K+ /// about 400 KB. The IDs ride the terminal event for that reason, so the+ /// headroom is worth pinning rather than assuming.+ @Test func aFullContextOfTokenIDsFitsTheFrameCap() throws {+ let event = DecodeServiceEvent(+ kind: .finished, generationID: UUID(),+ promptTokenIDs: (0..<32_768).map { Int32($0) },+ generatedTokenIDs: (0..<32_768).map { Int32(262_143 - $0) })+ let frame = try DecodeFrameCodec.encode(event)+ #expect(frame.count < DecodeFrameCodec.maximumPayloadBytes)+ }++ @Test func aTerminalEventCarriesTheTurnsRecord() throws {+ let generationID = UUID()+ let outbox = DecodeServiceOutbox(generationID: generationID)+ var record = AppDiagnostics(+ generatedTokens: 2,+ stopReason: .endOfTurn,+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 0,+ tokensPerSecond: 0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())+ record.promptTokenIDs = [1, 2, 3]+ record.generatedTokenIDs = [4, 5]+ record.boundaryTokenIDs = [6]+ record.boundaryNeedsReplay = true++ let pipe = Pipe()+ let writerFinished = DispatchSemaphore(value: 0)+ let writer = Thread {+ defer {+ try? pipe.fileHandleForWriting.close()+ writerFinished.signal()+ }+ try? outbox.runWriter(to: pipe.fileHandleForWriting)+ }+ writer.start()+ outbox.publish(.finished(record))+ let terminal = try DecodeFrameCodec.read(+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)+ outbox.finish()+ #expect(writerFinished.wait(timeout: .now() + 2) == .success)++ #expect(terminal.kind == .finished)+ #expect(terminal.promptTokenIDs == [1, 2, 3])+ #expect(terminal.generatedTokenIDs == [4, 5])+ #expect(terminal.boundaryTokenIDs == [6])+ #expect(terminal.boundaryNeedsReplay == true)+ }++ /// The service opens whatever path a replay image names, so the store root+ /// is a trust boundary and not a tidiness rule.+ @Test func onlyPathsInsideThisModelsStoreAreAccepted() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("store-\(UUID().uuidString)", isDirectory: true)+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let store = ConversationStoreLocation.url(forModelDirectory: model)+ #expect(store == root.appendingPathComponent("conversations", isDirectory: true))++ let inside = store.appendingPathComponent("abc/images/0.png")+ #expect(ConversationStoreLocation.contains(inside, forModelDirectory: model))++ // A sibling whose name merely starts the same must not pass as a prefix.+ let lookalike = root+ .appendingPathComponent("conversations-elsewhere/abc/images/0.png")+ #expect(!ConversationStoreLocation.contains(lookalike, forModelDirectory: model))+ #expect(!ConversationStoreLocation.contains(+ URL(fileURLWithPath: "/etc/passwd"), forModelDirectory: model))+ // Traversal has to lose: standardizing resolves it before the compare.+ #expect(!ConversationStoreLocation.contains(+ store.appendingPathComponent("../../secret.png"), forModelDirectory: model))+ // The root itself is not a file inside the root.+ #expect(!ConversationStoreLocation.contains(store, forModelDirectory: model))+ }+}diff --git a/Tests/TurboFieldfareDecodeService/ServiceLoadCancellationTests.swift b/Tests/TurboFieldfareDecodeService/ServiceLoadCancellationTests.swiftnew file mode 100644index 00000000..70272188--- /dev/null+++ b/Tests/TurboFieldfareDecodeService/ServiceLoadCancellationTests.swift@@ -0,0 +1,98 @@+import Foundation+import Testing+@testable import TurboFieldfareDecodeService++/// `.cancel` means two things on the wire — stop this generation, and abandon+/// this load — and the load half used to latch with no scope. Stopping an+/// answer left a cancel armed, and the next model load the user asked for died+/// on arrival with "decode service returned cancelled for a load request".+@Suite struct ServiceLoadCancellationTests {+ private func makeTask() -> Task<Void, Error> {+ Task { try await Task.sleep(for: .seconds(30)) }+ }++ @Test func stoppingAGenerationDoesNotPoisonTheNextLoad() async throws {+ let work = ServiceLoadCancellation()+ // No load queued: this cancel belongs to a generation.+ work.cancel()+ #expect(!work.isHoldingCancel,+ "a generation's cancel was held against a future load")++ // The user changes a setting and reloads, well after the stop.+ work.enqueueLoad()+ let load = makeTask()+ work.begin(load)+ defer { load.cancel() }+ #expect(!load.isCancelled, "the reload was cancelled by an unrelated stop")+ work.finish()+ }++ /// The race the latch exists for: the app writes `.load`, gives up, and+ /// writes `.cancel` before the command loop has started the load.+ @Test func acancelThatOvertakesItsLoadStillLands() async throws {+ let work = ServiceLoadCancellation()+ work.enqueueLoad()+ work.cancel()+ #expect(work.isHoldingCancel)++ let load = makeTask()+ work.begin(load)+ #expect(load.isCancelled, "the cancel never reached the load it was for")+ #expect(!work.isHoldingCancel, "the cancel was held past the load it was for")+ work.finish()+ }++ /// A cancel arriving while the load is running cancels that load and+ /// nothing else.+ @Test func acancelDuringALoadCancelsOnlyThatLoad() async throws {+ let work = ServiceLoadCancellation()+ work.enqueueLoad()+ let first = makeTask()+ work.begin(first)+ work.cancel()+ #expect(first.isCancelled)+ #expect(!work.isHoldingCancel)+ work.finish()++ work.enqueueLoad()+ let second = makeTask()+ work.begin(second)+ defer { second.cancel() }+ #expect(!second.isCancelled, "the next load inherited the last one's cancel")+ }++ /// A load can fail before it ever starts — its runtime options are parsed+ /// after the input thread has already counted it — and the count has to+ /// clear anyway. Otherwise the next `.cancel` from a generation finds a+ /// load still queued, holds itself, and kills the load after that.+ @Test func aloadThatNeverStartsStillClearsItsQueueSlot() async throws {+ let work = ServiceLoadCancellation()+ work.enqueueLoad()+ // The service's `.load` handler threw before `begin`; its defer runs.+ work.finish()++ // Now an ordinary generation stop.+ work.cancel()+ #expect(!work.isHoldingCancel,+ "an abandoned load left its slot counted, so a generation's cancel latched")++ work.enqueueLoad()+ let load = makeTask()+ work.begin(load)+ defer { load.cancel() }+ #expect(!load.isCancelled, "the next load paid for a load that never ran")+ work.finish()+ }++ /// Two cancels with no load between them must not accumulate a debt that a+ /// later load pays.+ @Test func repeatedGenerationCancelsAccumulateNothing() async throws {+ let work = ServiceLoadCancellation()+ for _ in 0..<5 { work.cancel() }+ work.enqueueLoad()+ let load = makeTask()+ work.begin(load)+ defer { load.cancel() }+ #expect(!load.isCancelled)+ }+}diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.mdindex 323dd5db..3f806844 100644--- a/docs/COMMUNITY_BENCHMARKS.md+++ b/docs/COMMUNITY_BENCHMARKS.md@@ -168,6 +168,9 @@ all affect decode speed.| [Benjamin Schilling](https://github.com/benjamin-schilling) · [issue #27](https://github.com/drumih/turbo-fieldfare/issues/27) | M3 Pro MacBook Pro | 18 GB | Internal SSD | 61 / 516 | 19.09 tok/s | One submitted run || [Benjamin Schilling](https://github.com/benjamin-schilling) · [issue #27](https://github.com/drumih/turbo-fieldfare/issues/27) | M3 Pro MacBook Pro | 18 GB | Internal SSD | 430 / 780 | 16.50 tok/s | One submitted run || [Benjamin Schilling](https://github.com/benjamin-schilling) · [issue #27](https://github.com/drumih/turbo-fieldfare/issues/27) | M3 Pro MacBook Pro | 18 GB | Internal SSD | 3,015 / 617 | 13.88 tok/s | One submitted run |+| [castillovas-arch](https://github.com/castillovas-arch) · [issue #172](https://github.com/drumih/turbo-fieldfare/issues/172) | M4 Mac mini | 16 GB | Internal SSD | 61 / 489 | 11.649 tok/s | One measured run after one discarded warmup |+| [castillovas-arch](https://github.com/castillovas-arch) · [issue #172](https://github.com/drumih/turbo-fieldfare/issues/172) | M4 Mac mini | 16 GB | Internal SSD | 430 / 760 | 10.119 tok/s | One measured run after one discarded warmup |+| [castillovas-arch](https://github.com/castillovas-arch) · [issue #172](https://github.com/drumih/turbo-fieldfare/issues/172) | M4 Mac mini | 16 GB | Internal SSD | 3,015 / 594 | 8.058 tok/s | One measured run after one discarded warmup || [gandalfk7](https://github.com/gandalfk7) · [issue #95](https://github.com/drumih/turbo-fieldfare/issues/95) | M4 Mac mini | 16 GB | Internal 256 GB SSD | 61 / 516 | 10.847 tok/s | One submitted run || [gandalfk7](https://github.com/gandalfk7) · [issue #95](https://github.com/drumih/turbo-fieldfare/issues/95) | M4 Mac mini | 16 GB | Internal 256 GB SSD | 430 / 780 | 9.878 tok/s | One submitted run || [gandalfk7](https://github.com/gandalfk7) · [issue #95](https://github.com/drumih/turbo-fieldfare/issues/95) | M4 Mac mini | 16 GB | Internal 256 GB SSD | 3,015 / 617 | 8.658 tok/s | One submitted run |@@ -208,3 +211,9 @@ all affect decode speed.These submissions use the public community prompts and generate until the endof the model turn. Compare rows only when the prompt and generated-token countsmatch.++[Issue #172](https://github.com/drumih/turbo-fieldfare/issues/172) reports macOS+26.6.2 (25G83), Swift 6.3.3, and commit `6c044011c24dd55595af823cfef10f26b525cfca`.+Each measured case ran in a fresh process with the sampling settings above;+all three ended with `stop=endOfTurn`. The reporter reviewed the outputs and+reported no loops, repeated blocks or protocol deviations.