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
Improve Mac app interaction and recovery (#49)
Andrey Mikhaylovadd22ff12e4b
diff --git a/Package.swift b/Package.swiftindex f3ee04aa..efe109f3 100644--- a/Package.swift+++ b/Package.swift@@ -115,9 +115,14 @@ let package = Package(dependencies: ["TurboFieldfareAppCore", "TurboFieldfare", "TurboFieldfareRepackCore", "TurboFieldfareDecodeProtocol"],path: "Tests/TurboFieldfareApp/Core"),+ .testTarget(+ name: "TurboFieldfareDecodeServiceTests",+ dependencies: ["TurboFieldfareDecodeService", "TurboFieldfareAppCore", "TurboFieldfareDecodeProtocol"],+ path: "Tests/TurboFieldfareDecodeService"+ ),.testTarget(name: "TurboFieldfareMacPresentationTests",- dependencies: ["TurboFieldfareMacPresentation"],+ dependencies: ["TurboFieldfareAppCore", "TurboFieldfareMacPresentation"],path: "Tests/TurboFieldfareApp/MacPresentation"),.testTarget(diff --git a/README.md b/README.mdindex f18d56a3..e0734f59 100644--- a/README.md+++ b/README.md@@ -157,7 +157,7 @@ After installation:1. Choose **Load Model**.2. Enter a prompt in the composer.-3. Choose **Generate**, or press <kbd>Command</kbd>+<kbd>Return</kbd>.+3. Choose **Generate**, or press <kbd>Command</kbd>+<kbd>Return</kbd>. Use **Settings > Send Message With** to choose Return or Command-Return.4. Use the stop button or <kbd>Escape</kbd> to end generation early.The status bar shows generation progress, decode speed, and memory use. Use thediff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppNewlineShortcut.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppNewlineShortcut.swiftnew file mode 100644index 00000000..bedb88dc--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppNewlineShortcut.swift@@ -0,0 +1,15 @@+public enum AppNewlineShortcut: String, CaseIterable, Codable, Sendable, Identifiable {+ case `return`+ case shiftReturn = "shift-return"++ public var id: String { rawValue }++ public static let sendMessageOptions: [Self] = [.shiftReturn, .return]++ public var sendMessageLabel: String {+ switch self {+ case .return: return "Command-Return"+ case .shiftReturn: return "Return"+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swiftindex 8df215cb..6565fbd3 100644--- a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift@@ -13,6 +13,65 @@ struct MacAppSettings: Codable, Equatable, Sendable {var topPEnabled: Bool = truevar topP: Double = 0.95var prefillEnabled: Bool = true+ var newlineShortcut: AppNewlineShortcut = .return+ var showPromptExamples: Bool = true++ private enum CodingKeys: String, CodingKey {+ case version+ case contextTokens+ case expertCacheSlots+ case temperature+ case topKEnabled+ case topK+ case topPEnabled+ case topP+ case prefillEnabled+ case newlineShortcut+ case showPromptExamples+ }++ init(version: Int = currentVersion,+ contextTokens: Int = AppContextLengthOption.fourK.tokens,+ expertCacheSlots: Int = 16,+ temperature: Double = 0.2,+ topKEnabled: Bool = true,+ topK: Int = 64,+ topPEnabled: Bool = true,+ topP: Double = 0.95,+ prefillEnabled: Bool = true,+ newlineShortcut: AppNewlineShortcut = .return,+ showPromptExamples: Bool = true) {+ self.version = version+ self.contextTokens = contextTokens+ self.expertCacheSlots = expertCacheSlots+ self.temperature = temperature+ self.topKEnabled = topKEnabled+ self.topK = topK+ self.topPEnabled = topPEnabled+ self.topP = topP+ self.prefillEnabled = prefillEnabled+ self.newlineShortcut = newlineShortcut+ self.showPromptExamples = showPromptExamples+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ version = try container.decode(Int.self, forKey: .version)+ contextTokens = try container.decode(Int.self, forKey: .contextTokens)+ expertCacheSlots = try container.decode(Int.self, forKey: .expertCacheSlots)+ temperature = try container.decode(Double.self, forKey: .temperature)+ topKEnabled = try container.decode(Bool.self, forKey: .topKEnabled)+ topK = try container.decode(Int.self, forKey: .topK)+ topPEnabled = try container.decode(Bool.self, forKey: .topPEnabled)+ topP = try container.decode(Double.self, forKey: .topP)+ prefillEnabled = try container.decode(Bool.self, forKey: .prefillEnabled)+ newlineShortcut = try container.decodeIfPresent(+ AppNewlineShortcut.self,+ forKey: .newlineShortcut) ?? .return+ showPromptExamples = try container.decodeIfPresent(+ Bool.self,+ forKey: .showPromptExamples) ?? true+ }func isValid() -> Bool {version == Self.currentVersiondiff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swiftindex a4e9e286..e196cbd0 100644--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift@@ -8,7 +8,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,AppInferenceMemoryReporting, AppInferenceTranscriptReporting, @unchecked Sendable {private struct Connection {var input: FileHandle?- var output: FileHandle?+ var responses: DecodeServiceResponseRouter?var loadedDirectory: URL?var launchLabel: String?var socketPath: String?@@ -40,10 +40,16 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,forceLogitsHead: forceLogitsHead)try handles.input.write(contentsOf: DecodeFrameCodec.encode(DecodeServiceCommand.load(request)))- let event = try await readEvent(from: handles.output)- guard event.generationID == request.requestID, event.kind == .ready else {+ let event = try await handles.responses.next(matching: request.requestID)+ switch event.kind {+ case .ready:+ break+ case .failed:throw AppInferenceError.modelLoadFailed(event.error ?? "decode service load failed")+ default:+ throw AppInferenceError.modelLoadFailed(+ "decode service returned \(event.kind.rawValue) for a load request")}inferenceMemory.withLock { $0 = event.currentMemoryBytes }connection.withLock { $0.loadedDirectory = modelDirectory.standardizedFileURL }@@ -55,7 +61,8 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,let requestID = UUID()try? handles.input.write(contentsOf: DecodeFrameCodec.encode(DecodeServiceCommand.unload(requestID)))- _ = try? await readEvent(from: handles.output)+ guard let event = try? await handles.responses.next(matching: requestID),+ event.kind == .unloaded else { return }connection.withLock { $0.loadedDirectory = nil }inferenceMemory.withLock { $0 = nil }}@@ -85,8 +92,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,var lastMetricYield = Date.distantPastvar hasYieldedVisibleText = falsewhile true {- let event = try DecodeFrameCodec.read(- DecodeServiceEvent.self, from: handles.output)+ let event = try await handles.responses.next(matching: generationID)inferenceMemory.withLock { $0 = event.currentMemoryBytes }guard event.generationID == generationID else { continue }@@ -170,13 +176,14 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,if let socketPath = state.socketPath { unlink(socketPath) }}- private func ensureProcess() throws -> (input: FileHandle, output: FileHandle) {+ private func ensureProcess() throws+ -> (input: FileHandle, responses: DecodeServiceResponseRouter) {if let handles = currentHandles() { return handles }return try launchIndependentService()}private func launchIndependentService() throws- -> (input: FileHandle, output: FileHandle) {+ -> (input: FileHandle, responses: DecodeServiceResponseRouter) {guard FileManager.default.isExecutableFile(atPath: serviceURL.path) else {throw AppInferenceError.modelLoadFailed("decode service executable is missing at \(serviceURL.path); run swift build -c release before launching the app")@@ -226,13 +233,14 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,for _ in 0..<200 {do {let handles = try DecodeUnixSocket.connect(path: socketPath)+ let responses = DecodeServiceResponseRouter(output: handles.output)connection.withLock {$0.input = handles.input- $0.output = handles.output+ $0.responses = responses$0.launchLabel = label$0.socketPath = socketPath}- return handles+ return (handles.input, responses)} catch {lastError = errorusleep(10_000)@@ -243,22 +251,16 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,"decode service socket did not become ready: \(lastError.map(String.init(describing:)) ?? "unknown error")")}- private func currentHandles() -> (input: FileHandle, output: FileHandle)? {+ private func currentHandles()+ -> (input: FileHandle, responses: DecodeServiceResponseRouter)? {connection.withLock { state in- guard let input = state.input, let output = state.output else {+ guard let input = state.input, let responses = state.responses else {return nil}- return (input, output)+ return (input, responses)}}- private func readEvent(from output: FileHandle) async throws- -> DecodeServiceEvent {- try await Task.detached(priority: .userInitiated) {- try DecodeFrameCodec.read(DecodeServiceEvent.self, from: output)- }.value- }-private static func diagnostics(_ event: DecodeServiceEvent,options: AppRuntimeOptions) -> AppDiagnostics {let stop = AppStopReason(rawValue: event.stopReason ?? "")diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swiftnew file mode 100644index 00000000..cbcbc79a--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceResponseRouter.swift@@ -0,0 +1,64 @@+import Foundation+import TurboFieldfareDecodeProtocol++final class DecodeServiceResponseRouter: @unchecked Sendable {+ private struct State {+ var pending: [UUID: [DecodeServiceEvent]] = [:]+ var terminalError: Error?+ }++ private let condition = NSCondition()+ private var state = State()++ init(output: FileHandle) {+ let reader = Thread { [weak self] in+ self?.readFrames(from: output)+ }+ reader.name = "TurboFieldfare.DecodeService.ResponseRouter"+ reader.qualityOfService = .userInitiated+ reader.start()+ }++ func next(matching requestID: UUID) async throws -> DecodeServiceEvent {+ try await Task.detached(priority: .userInitiated) { [self] in+ try waitForEvent(matching: requestID)+ }.value+ }++ private func waitForEvent(matching requestID: UUID) throws -> DecodeServiceEvent {+ condition.lock()+ defer { condition.unlock() }+ while state.pending[requestID]?.isEmpty != false,+ state.terminalError == nil {+ condition.wait()+ }+ if var events = state.pending[requestID], !events.isEmpty {+ let event = events.removeFirst()+ if events.isEmpty {+ state.pending.removeValue(forKey: requestID)+ } else {+ state.pending[requestID] = events+ }+ return event+ }+ throw state.terminalError ?? DecodeFrameError.unexpectedEOF+ }++ 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()+ }+ } catch {+ condition.lock()+ state.terminalError = error+ condition.broadcast()+ condition.unlock()+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swiftindex 29f6a2cf..42c882f9 100644--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift@@ -23,6 +23,8 @@ public final class AppModel {public var topK: Int = 64public var topPEnabled: Bool = truepublic var topP: Double = 0.95+ public private(set) var newlineShortcut: AppNewlineShortcut = .return+ public private(set) var showPromptExamples: Bool = truepublic var diagnostics: AppDiagnostics?public var error: AppInferenceError?public var installState: AppModelInstallState = .idle@@ -79,6 +81,8 @@ public final class AppModel {self.topK = settings.topKself.topPEnabled = settings.topPEnabledself.topP = settings.topP+ self.newlineShortcut = settings.newlineShortcut+ self.showPromptExamples = settings.showPromptExamplesself.installationStatus = AppModelInstallationProbe.status(at: directory)self.client = clientself.installer = installer@@ -320,6 +324,18 @@ public final class AppModel {}}+ public func setNewlineShortcut(_ shortcut: AppNewlineShortcut) {+ guard newlineShortcut != shortcut else { return }+ newlineShortcut = shortcut+ persistSettings()+ }++ public func setShowPromptExamples(_ show: Bool) {+ guard showPromptExamples != show else { return }+ showPromptExamples = show+ persistSettings()+ }+public func reloadModel() {guard canReloadModel else { return }beginLoad()@@ -611,6 +627,8 @@ public final class AppModel {topK = settings.topKtopPEnabled = settings.topPEnabledtopP = settings.topP+ newlineShortcut = settings.newlineShortcut+ showPromptExamples = settings.showPromptExamples}private func persistSettings() {@@ -623,7 +641,9 @@ public final class AppModel {topK: topK,topPEnabled: topPEnabled,topP: topP,- prefillEnabled: runtimeOptions.prefillEnabled)+ prefillEnabled: runtimeOptions.prefillEnabled,+ newlineShortcut: newlineShortcut,+ showPromptExamples: showPromptExamples)let modelDirectory = URL(fileURLWithPath: modelPathText, isDirectory: true)try? MacAppSettingsFileStore.save(settings,diff --git a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swiftindex c518ee7d..34ca18a2 100644--- a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift@@ -78,6 +78,15 @@ public struct AppPresentationState: Equatable, Sendable {self.secondaryAction = secondaryAction}+ public var conversationAction: AppModelAction? {+ switch primaryAction {+ case .load, .retryLoad, .reload:+ return primaryAction+ case .install, .cancelInstall, .cancelLoad, .unload, nil:+ return nil+ }+ }+public static func resolve(_ snapshot: AppPresentationSnapshot) -> Self {if snapshot.installState.isInstalling {if case .cancelling = snapshot.installState {diff --git a/Sources/TurboFieldfareApp/Mac/App/RootView.swift b/Sources/TurboFieldfareApp/Mac/App/RootView.swiftindex f0b81a99..00493fe4 100644--- a/Sources/TurboFieldfareApp/Mac/App/RootView.swift+++ b/Sources/TurboFieldfareApp/Mac/App/RootView.swift@@ -32,6 +32,7 @@ struct RootView: View {.tint(TurboFieldfareMacTheme.accentColor).animation(.smooth(duration: 0.3), value: model.requiresModelInstallation).animation(.smooth(duration: 0.25), value: model.error)+ .animation(.smooth(duration: 0.2), value: model.presentation.conversationAction).transaction { transaction inif model.isRunning {transaction.animation = nil@@ -90,17 +91,20 @@ struct RootView: View {private var conversationChrome: some View {VStack(spacing: 10) {ErrorBanner(model: model)- if model.promptText.isEmpty {+ if model.promptText.isEmpty && model.showPromptExamples {PromptExamplesView { preset inmodel.promptText = preset.prompt}}+ ModelActionBanner(model: model)PromptComposerView(model: model)}.padding(.horizontal, 20).padding(.bottom, 16).animation(.smooth(duration: 0.2), value: model.promptText.isEmpty)+ .animation(.smooth(duration: 0.2), value: model.showPromptExamples)}+}private struct ConversationChromeHeightKey: PreferenceKey {diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swiftindex 1eb67e5b..577a7de0 100644--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift@@ -58,6 +58,33 @@ struct TurboFieldfareMacApp: App {Button("Unload Model", action: model.unloadModel).disabled(!model.canUnloadModel)}+ CommandMenu("Settings") {+ Picker("Send Message With", selection: newlineShortcutBinding) {+ ForEach(AppNewlineShortcut.sendMessageOptions) { shortcut in+ Text(shortcut.sendMessageLabel).tag(shortcut)+ }+ }+ Picker("Prompt Examples", selection: showPromptExamplesBinding) {+ Text("Show").tag(true)+ Text("Hide").tag(false)+ }+ }+ }+ }++ private var newlineShortcutBinding: Binding<AppNewlineShortcut> {+ Binding {+ model.newlineShortcut+ } set: { shortcut in+ model.setNewlineShortcut(shortcut)+ }+ }++ private var showPromptExamplesBinding: Binding<Bool> {+ Binding {+ model.showPromptExamples+ } set: { show in+ model.setShowPromptExamples(show)}}}diff --git a/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swift b/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swiftindex e42a6389..67fcfa12 100644--- a/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swift+++ b/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swift@@ -1,11 +1,13 @@import TurboFieldfareAppCore+import TurboFieldfareMacPresentationimport SwiftUIstruct ErrorBanner: View {@Bindable var model: AppModelvar body: some View {- if let error = model.error, error != .cancelled {+ if let error = model.error,+ GenericErrorBannerPolicy.shouldShow(error: error, loadState: model.loadState) {HStack(spacing: 8) {Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.red)diff --git a/Sources/TurboFieldfareApp/Mac/Components/ModelActionBanner.swift b/Sources/TurboFieldfareApp/Mac/Components/ModelActionBanner.swiftnew file mode 100644index 00000000..2e28aafd--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Components/ModelActionBanner.swift@@ -0,0 +1,76 @@+import TurboFieldfareAppCore+import SwiftUI++struct ModelActionBanner: View {+ @Bindable var model: AppModel++ var body: some View {+ if model.hasOutputTranscript,+ let action = model.presentation.conversationAction {+ HStack(spacing: 10) {+ Image(systemName: iconName(for: action))+ .foregroundStyle(iconColor(for: action))+ .accessibilityHidden(true)+ Text(message(for: action))+ .font(.callout)+ .lineLimit(2)+ Spacer(minLength: 8)+ Button(buttonTitle(for: action)) {+ model.perform(action)+ }+ .buttonStyle(.borderedProminent)+ .controlSize(.small)+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 8)+ .background {+ RoundedRectangle(cornerRadius: 14)+ .fill(Color(nsColor: .controlBackgroundColor))+ .overlay {+ RoundedRectangle(cornerRadius: 14)+ .stroke(iconColor(for: action).opacity(0.5), lineWidth: 1)+ }+ }+ .accessibilityElement(children: .contain)+ .transition(.move(edge: .bottom).combined(with: .opacity))+ }+ }++ private func message(for action: AppModelAction) -> String {+ switch action {+ case .load:+ return "The model is unloaded. Load it to generate."+ case .retryLoad:+ return model.presentation.detail ?? "The model could not be loaded."+ case .reload:+ return "Settings changed. Reload the model to continue."+ case .install, .cancelInstall, .cancelLoad, .unload:+ return model.presentation.label+ }+ }++ private func buttonTitle(for action: AppModelAction) -> String {+ switch action {+ case .load: return "Load Model"+ case .retryLoad: return "Retry Load"+ case .reload: return "Reload Model"+ case .install: return "Install"+ case .cancelInstall: return "Cancel"+ case .cancelLoad: return "Cancel Load"+ case .unload: return "Unload Model"+ }+ }++ private func iconName(for action: AppModelAction) -> String {+ switch action {+ case .retryLoad: return "exclamationmark.triangle.fill"+ case .reload: return "arrow.clockwise.circle.fill"+ case .load, .install, .cancelInstall, .cancelLoad, .unload:+ return "externaldrive.fill"+ }+ }++ private func iconColor(for action: AppModelAction) -> Color {+ action == .retryLoad ? .red : .orange+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swiftindex 00e5c84f..942e9c14 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift@@ -1,4 +1,6 @@+import AppKitimport TurboFieldfareAppCore+import TurboFieldfareMacPresentationimport SwiftUIstruct PromptComposerView: View {@@ -28,6 +30,22 @@ struct PromptComposerView: View {.font(.body).scrollContentBackground(.hidden).focused($promptFocused)+ .onKeyPress(.return, phases: [.down, .repeat]) { keyPress in+ switch PromptSubmissionPolicy.decision(+ newlineShortcut: model.newlineShortcut,+ modifiers: keyPress.modifiers,+ canRun: model.canRun,+ hasMarkedText: promptHasMarkedText,+ isRepeat: keyPress.phase.contains(.repeat)) {+ case .submit:+ model.run()+ return .handled+ case .consume:+ return .handled+ case .deferToEditor:+ return .ignored+ }+ }.frame(height: editorHeight).overlay(alignment: .topLeading) {if model.promptText.isEmpty {@@ -42,6 +60,10 @@ struct PromptComposerView: View {}}+ private var promptHasMarkedText: Bool {+ (NSApp.keyWindow?.firstResponder as? NSTextView)?.hasMarkedText() == true+ }+private var editorHeight: CGFloat {model.promptText.isEmpty ? 46 : 84}diff --git a/Sources/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicy.swift b/Sources/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicy.swiftnew file mode 100644index 00000000..e1397575--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicy.swift@@ -0,0 +1,10 @@+import TurboFieldfareAppCore++public enum GenericErrorBannerPolicy {+ public static func shouldShow(error: AppInferenceError?, loadState: AppModelLoadState)+ -> Bool {+ guard let error, error != .cancelled else { return false }+ if case .failed = loadState { return false }+ return true+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/PromptSubmissionPolicy.swift b/Sources/TurboFieldfareApp/MacPresentation/PromptSubmissionPolicy.swiftnew file mode 100644index 00000000..81df7003--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/PromptSubmissionPolicy.swift@@ -0,0 +1,28 @@+import SwiftUI+import TurboFieldfareAppCore++public enum PromptSubmissionDecision: Equatable, Sendable {+ case submit+ case consume+ case deferToEditor+}++public enum PromptSubmissionPolicy {+ public static func decision(+ newlineShortcut: AppNewlineShortcut,+ modifiers: EventModifiers,+ canRun: Bool,+ hasMarkedText: Bool,+ isRepeat: Bool = false+ ) -> PromptSubmissionDecision {+ guard newlineShortcut == .shiftReturn else { return .deferToEditor }++ let nativeModifiers: EventModifiers = [.command, .shift, .option, .control]+ guard modifiers.intersection(nativeModifiers).isEmpty else {+ return .deferToEditor+ }+ if isRepeat { return .consume }+ guard !hasMarkedText else { return .deferToEditor }+ return canRun ? .submit : .consume+ }+}diff --git a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swiftindex ca48f53a..5f65cd23 100644--- a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift+++ b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift@@ -14,6 +14,7 @@ final class DecodeServiceOutbox: @unchecked Sendable {var latestPrefill: PrefillProgress?var latestToken: AppTokenEvent?var terminal: DecodeServiceEvent?+ var terminalCommitted = falsevar finished = falsevar sequence: UInt64 = 0}@@ -38,12 +39,21 @@ final class DecodeServiceOutbox: @unchecked Sendable {state.pendingText += token.textDeltastate.latestToken = tokencase .finished(let diagnostics):- state.terminal = terminal(.finished, diagnostics: diagnostics)+ if !state.terminalCommitted {+ state.terminal = terminal(.finished, diagnostics: diagnostics)+ state.terminalCommitted = true+ }case .cancelled(let diagnostics):- state.terminal = terminal(.cancelled, diagnostics: diagnostics)+ if !state.terminalCommitted {+ state.terminal = terminal(.cancelled, diagnostics: diagnostics)+ state.terminalCommitted = true+ }case .failed(let error, let diagnostics):- state.terminal = terminal(- .failed, diagnostics: diagnostics, error: error.userMessage)+ if !state.terminalCommitted {+ state.terminal = terminal(+ .failed, diagnostics: diagnostics, error: error.userMessage)+ state.terminalCommitted = true+ }}if state.terminal != nil { condition.signal() }condition.unlock()@@ -51,9 +61,10 @@ final class DecodeServiceOutbox: @unchecked Sendable {func finish(error: Error? = nil) {condition.lock()- if state.terminal == nil, let error {+ if !state.terminalCommitted, let error {state.terminal = DecodeServiceEvent(kind: .failed, generationID: generationID, error: "\(error)")+ state.terminalCommitted = true}state.finished = truecondition.broadcast()diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swiftindex 1bc66aaf..461681c8 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift@@ -55,6 +55,87 @@ import Testing#expect(settings == MacAppSettings())}+ @Test func legacySettingsDefaultToReturnWithoutLosingValues() throws {+ let data = Data("""+ {+ "version": 1,+ "contextTokens": 8192,+ "expertCacheSlots": 24,+ "temperature": 0.4,+ "topKEnabled": false,+ "topK": 32,+ "topPEnabled": false,+ "topP": 0.8,+ "prefillEnabled": false+ }+ """.utf8)++ let settings = try JSONDecoder().decode(MacAppSettings.self, from: data)++ #expect(settings.contextTokens == 8_192)+ #expect(settings.expertCacheSlots == 24)+ #expect(settings.temperature == 0.4)+ #expect(!settings.topKEnabled)+ #expect(settings.topK == 32)+ #expect(!settings.topPEnabled)+ #expect(settings.topP == 0.8)+ #expect(!settings.prefillEnabled)+ #expect(settings.newlineShortcut == .return)+ #expect(settings.showPromptExamples)+ }++ @Test(arguments: AppNewlineShortcut.allCases)+ func newlineShortcutRoundTrips(_ shortcut: AppNewlineShortcut) throws {+ let initial = MacAppSettings(newlineShortcut: shortcut)+ let decoded = try JSONDecoder().decode(+ MacAppSettings.self,+ from: JSONEncoder().encode(initial))++ #expect(decoded == initial)+ }++ @Test func sendMessageOptionsUseUserFacingOrderAndLabels() {+ #expect(AppNewlineShortcut.sendMessageOptions == [.shiftReturn, .return])+ #expect(AppNewlineShortcut.shiftReturn.sendMessageLabel == "Return")+ #expect(AppNewlineShortcut.return.sendMessageLabel == "Command-Return")+ }++ @Test(arguments: [true, false])+ func showPromptExamplesRoundTrips(_ show: Bool) throws {+ let initial = MacAppSettings(showPromptExamples: show)+ let decoded = try JSONDecoder().decode(+ MacAppSettings.self,+ from: JSONEncoder().encode(initial))++ #expect(decoded == initial)+ }++ @Test func invalidNewlineShortcutIsReplacedWithDefaults() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: model)+ let invalid = Data("""+ {+ "version": 1,+ "contextTokens": 4096,+ "expertCacheSlots": 16,+ "temperature": 0.2,+ "topKEnabled": true,+ "topK": 64,+ "topPEnabled": true,+ "topP": 0.95,+ "prefillEnabled": true,+ "newlineShortcut": "invalid"+ }+ """.utf8)+ try invalid.write(to: fileURL)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)++ #expect(settings == MacAppSettings())+ }+@MainActor@Test func appModelLoadsAndSavesPersistedSettings() throws {let root = try makeTemporaryRoot()@@ -71,7 +152,9 @@ import TestingtopK: 32,topPEnabled: false,topP: 0.8,- prefillEnabled: false)+ prefillEnabled: false,+ newlineShortcut: .shiftReturn,+ showPromptExamples: false)try MacAppSettingsFileStore.save(initial, forModelDirectory: modelDirectory)let model = AppModel(@@ -85,6 +168,8 @@ import Testing#expect(!model.topPEnabled)#expect(model.topP == 0.8)#expect(!model.runtimeOptions.prefillEnabled)+ #expect(model.newlineShortcut == .shiftReturn)+ #expect(!model.showPromptExamples)model.temperature = 0.6model.runtimeOptions.expertCacheSlots = 32@@ -101,9 +186,65 @@ import Testing#expect(saved.temperature == 0.6)#expect(saved.expertCacheSlots == 32)#expect(saved.prefillEnabled)+ #expect(saved.newlineShortcut == .shiftReturn)+ #expect(!saved.showPromptExamples)model.cancel()}+ @MainActor+ @Test func newlineShortcutPersistsImmediately() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let model = AppModel(+ modelDirectory: modelDirectory,+ settingsPersistenceEnabled: true)++ model.setNewlineShortcut(.shiftReturn)++ let saved = MacAppSettingsFileStore.loadOrCreate(+ forModelDirectory: modelDirectory)+ #expect(saved.newlineShortcut == .shiftReturn)+ }++ @MainActor+ @Test func showPromptExamplesPersistsImmediately() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let model = AppModel(+ modelDirectory: modelDirectory,+ settingsPersistenceEnabled: true)++ model.setShowPromptExamples(false)++ let saved = MacAppSettingsFileStore.loadOrCreate(+ forModelDirectory: modelDirectory)+ #expect(!saved.showPromptExamples)+ }++ @MainActor+ @Test func changingModelDirectoryLoadsItsNewlineShortcut() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let first = root.appendingPathComponent("first/model.gturbo", isDirectory: true)+ let second = root.appendingPathComponent("second/model.gturbo", isDirectory: true)+ try MacAppSettingsFileStore.save(+ MacAppSettings(newlineShortcut: .return, showPromptExamples: true),+ forModelDirectory: first)+ try MacAppSettingsFileStore.save(+ MacAppSettings(newlineShortcut: .shiftReturn, showPromptExamples: false),+ forModelDirectory: second)+ let model = AppModel(modelDirectory: first, settingsPersistenceEnabled: true)+ #expect(model.newlineShortcut == .return)+ #expect(model.showPromptExamples)++ model.setModelURL(second)++ #expect(model.newlineShortcut == .shiftReturn)+ #expect(!model.showPromptExamples)+ }+private func makeTemporaryRoot() throws -> URL {let root = FileManager.default.temporaryDirectory.appendingPathComponent("MacAppSettingsTests-\(UUID().uuidString)",diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceResponseMatchingTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceResponseMatchingTests.swiftnew file mode 100644index 00000000..d781f5f3--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceResponseMatchingTests.swift@@ -0,0 +1,89 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore+import TurboFieldfareDecodeProtocol++@Suite struct DecodeServiceResponseMatchingTests {+ @Test func staleGenerationTerminalIsSkippedBeforeLoadResponse() async throws {+ let expectedID = UUID()+ let pipe = try pipe(containing: [+ DecodeServiceEvent(kind: .cancelled, generationID: UUID()),+ DecodeServiceEvent(kind: .ready, generationID: expectedID),+ ])++ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)+ let event = try await router.next(matching: expectedID)++ #expect(event.kind == .ready)+ #expect(event.generationID == expectedID)+ }++ @Test func staleGenerationTerminalIsSkippedBeforeUnloadResponse() async throws {+ let expectedID = UUID()+ let pipe = try pipe(containing: [+ DecodeServiceEvent(kind: .cancelled, generationID: UUID()),+ DecodeServiceEvent(kind: .unloaded, generationID: expectedID),+ ])++ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)+ let event = try await router.next(matching: expectedID)++ #expect(event.kind == .unloaded)+ #expect(event.generationID == expectedID)+ }++ @Test func matchingFailedLoadResponseIsReturned() async throws {+ let expectedID = UUID()+ let pipe = try pipe(containing: [+ DecodeServiceEvent(+ kind: .failed, generationID: expectedID, error: "load failed"),+ ])++ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)+ let event = try await router.next(matching: expectedID)++ #expect(event.kind == .failed)+ #expect(event.error == "load failed")+ }++ @Test func concurrentWaitersReceiveOnlyTheirOwnResponses() async throws {+ let loadID = UUID()+ let unloadID = UUID()+ let pipe = Pipe()+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)+ async let load = router.next(matching: loadID)+ async let unload = router.next(matching: unloadID)++ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .unloaded, generationID: unloadID)))+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceEvent(kind: .ready, generationID: loadID)))+ try pipe.fileHandleForWriting.close()++ let (loadEvent, unloadEvent) = try await (load, unload)+ #expect(loadEvent.kind == .ready)+ #expect(loadEvent.generationID == loadID)+ #expect(unloadEvent.kind == .unloaded)+ #expect(unloadEvent.generationID == unloadID)+ }++ @Test func endOfFileBeforeMatchingResponseFails() async throws {+ let pipe = try pipe(containing: [+ DecodeServiceEvent(kind: .cancelled, generationID: UUID()),+ ])+ let router = DecodeServiceResponseRouter(output: pipe.fileHandleForReading)++ await #expect(throws: DecodeFrameError.self) {+ _ = try await router.next(matching: UUID())+ }+ }++ private func pipe(containing events: [DecodeServiceEvent]) throws -> Pipe {+ let pipe = Pipe()+ for event in events {+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(event))+ }+ try pipe.fileHandleForWriting.close()+ return pipe+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swiftindex 0e49b676..9ee2ff18 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift@@ -70,6 +70,7 @@ import Testingclient.suspendUnloads = truelet model = AppModel(modelDirectory: directory, client: client)model.outputText = "keep me"+ model.promptText = "keep this draft"model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))model.unloadModel()@@ -81,6 +82,28 @@ import Testing}#expect(model.loadState == .notLoaded)#expect(model.outputText == "keep me")+ #expect(model.promptText == "keep this draft")+ }++ @MainActor+ @Test func reloadPreservesTranscriptAndDraft() async throws {+ let directory = try makeCompleteModelInstall("reload-preserves-conversation")+ defer { try? FileManager.default.removeItem(at: directory) }+ let client = MockLifecycleInferenceClient()+ let model = AppModel(modelDirectory: directory, client: client)+ model.outputText = "keep me"+ model.promptText = "keep this draft"+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))+ model.runtimeOptions.rdadvisePolicy = .bounded++ model.reloadModel()+ for _ in 0..<200 where !model.loadState.isReady {+ try? await Task.sleep(for: .milliseconds(5))+ }++ #expect(model.loadState.isReady)+ #expect(model.outputText == "keep me")+ #expect(model.promptText == "keep this draft")}@MainActor@@ -91,6 +114,8 @@ import Testingclient.suspendLoads = trueclient.suspendUnloads = truelet model = AppModel(modelDirectory: directory, client: client)+ model.outputText = "keep me"+ model.promptText = "keep this draft"model.loadModel()await client.waitForLoadStart()@@ -110,6 +135,8 @@ import Testingtry? await Task.sleep(for: .milliseconds(5))}#expect(model.loadState == .notLoaded)+ #expect(model.outputText == "keep me")+ #expect(model.promptText == "keep this draft")}@MainActor@@ -119,6 +146,8 @@ import Testinglet client = MockLifecycleInferenceClient()client.suspendLoads = truelet model = AppModel(modelDirectory: directory, client: client)+ model.outputText = "keep me"+ model.promptText = "keep this draft"model.loadModel()await client.waitForLoadStart()@@ -128,6 +157,8 @@ import Testing}#expect(model.loadState == .failed(.modelLoadFailed("synthetic")))#expect(model.canLoadModel)+ #expect(model.outputText == "keep me")+ #expect(model.promptText == "keep this draft")client.suspendLoads = truemodel.loadModel()@@ -142,6 +173,8 @@ import Testing}#expect(model.loadState.isReady)#expect(client.ensureLoadedCallCount() == 2)+ #expect(model.outputText == "keep me")+ #expect(model.promptText == "keep this draft")}@MainActordiff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swiftindex 197c373b..99f46172 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift@@ -120,6 +120,32 @@ import Testing#expect(!model.hasStaleLoadedRuntime)}+ @MainActor+ @Test func newlineShortcutDoesNotMarkReadySessionStale() {+ let model = AppModel(client: MockLifecycleInferenceClient())+ let directory = FileManager.default.temporaryDirectory+ model.modelPathText = directory.path+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))++ model.setNewlineShortcut(.shiftReturn)++ #expect(model.newlineShortcut == .shiftReturn)+ #expect(!model.hasStaleLoadedRuntime)+ }++ @MainActor+ @Test func promptExamplesPreferenceDoesNotMarkReadySessionStale() {+ let model = AppModel(client: MockLifecycleInferenceClient())+ let directory = FileManager.default.temporaryDirectory+ model.modelPathText = directory.path+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))++ model.setShowPromptExamples(false)++ #expect(!model.showPromptExamples)+ #expect(!model.hasStaleLoadedRuntime)+ }+@MainActor@Test func mockRunUpdatesOutputAndDiagnostics() async throws {let client = MockInferenceClient(response: "alpha beta", tokenDelayNanos: 1)diff --git a/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swiftindex 6a3bfb43..21de51d7 100644--- a/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swift@@ -51,6 +51,29 @@ import Testing#expect(state.label == "Ready")}+ @Test func conversationActionOnlyExposesIdleRecovery() {+ var snapshot = Self.installedSnapshot(loadState: .notLoaded)+ #expect(AppPresentationState.resolve(snapshot).conversationAction == .load)++ snapshot.loadState = .failed(.modelLoadFailed("synthetic"))+ #expect(AppPresentationState.resolve(snapshot).conversationAction == .retryLoad)++ snapshot.loadState = .ready(+ modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"),+ loadSeconds: 1)+ snapshot.hasStaleRuntime = true+ #expect(AppPresentationState.resolve(snapshot).conversationAction == .reload)++ snapshot.hasStaleRuntime = false+ #expect(AppPresentationState.resolve(snapshot).conversationAction == nil)++ snapshot.loadState = .loading(.tokenizer)+ #expect(AppPresentationState.resolve(snapshot).conversationAction == nil)++ snapshot.loadState = .unloading+ #expect(AppPresentationState.resolve(snapshot).conversationAction == nil)+ }+@Test func lifecyclePriorityTable() {let ready = AppModelLoadState.ready(modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"), loadSeconds: 1)diff --git a/Tests/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicyTests.swiftnew file mode 100644index 00000000..9097150b--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/GenericErrorBannerPolicyTests.swift@@ -0,0 +1,26 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore+@testable import TurboFieldfareMacPresentation++@Suite struct GenericErrorBannerPolicyTests {+ @Test func nilErrorIsHidden() {+ #expect(!GenericErrorBannerPolicy.shouldShow(error: nil, loadState: .notLoaded))+ }++ @Test func cancellationIsHidden() {+ #expect(!GenericErrorBannerPolicy.shouldShow(+ error: .cancelled, loadState: .notLoaded))+ }++ @Test func generationErrorIsShown() {+ #expect(GenericErrorBannerPolicy.shouldShow(+ error: .unknown("decode failed"), loadState: .notLoaded))+ }++ @Test func loadFailureIsOwnedByTheLoadPresentation() {+ let error = AppInferenceError.modelLoadFailed("broken")+ #expect(!GenericErrorBannerPolicy.shouldShow(+ error: error, loadState: .failed(error)))+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/PromptSubmissionPolicyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/PromptSubmissionPolicyTests.swiftnew file mode 100644index 00000000..f5af0493--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/PromptSubmissionPolicyTests.swift@@ -0,0 +1,67 @@+import SwiftUI+import Testing+@testable import TurboFieldfareAppCore+@testable import TurboFieldfareMacPresentation++@Suite struct PromptSubmissionPolicyTests {+ @Test(arguments: [true, false])+ func returnNewlineModeAlwaysDefersToEditor(canRun: Bool) {+ #expect(decision(.return, [], canRun: canRun) == .deferToEditor)+ #expect(decision(.return, .shift, canRun: canRun) == .deferToEditor)+ #expect(decision(.return, .command, canRun: canRun) == .deferToEditor)+ #expect(decision(.return, .option, canRun: canRun) == .deferToEditor)+ #expect(decision(.return, .control, canRun: canRun) == .deferToEditor)+ }++ @Test func plainReturnSubmitsOnlyWhenGenerationIsAvailable() {+ #expect(decision(.shiftReturn, [], canRun: true) == .submit)+ #expect(decision(.shiftReturn, [], canRun: false) == .consume)+ }++ @Test(arguments: [+ EventModifiers.shift,+ EventModifiers.command,+ EventModifiers.option,+ EventModifiers.control,+ [EventModifiers.command, .shift],+ ])+ func modifiedReturnDefersToEditor(_ modifiers: EventModifiers) {+ #expect(decision(.shiftReturn, modifiers, canRun: true) == .deferToEditor)+ }++ @Test func markedTextAlwaysDefersToEditor() {+ #expect(decision(.shiftReturn, [], canRun: true, hasMarkedText: true)+ == .deferToEditor)+ #expect(decision(.shiftReturn, [], canRun: false, hasMarkedText: true)+ == .deferToEditor)+ }++ @Test func plainReturnRepeatsAreConsumedInSendMode() {+ #expect(decision(.shiftReturn, [], canRun: true, isRepeat: true) == .consume)+ #expect(decision(.shiftReturn, [], canRun: false, isRepeat: true) == .consume)+ #expect(decision(+ .shiftReturn, [], canRun: true, hasMarkedText: true, isRepeat: true)+ == .consume)+ }++ @Test func newlineAndModifiedReturnRepeatsRemainNative() {+ #expect(decision(.return, [], canRun: true, isRepeat: true) == .deferToEditor)+ #expect(decision(+ .shiftReturn, .shift, canRun: true, isRepeat: true) == .deferToEditor)+ }++ private func decision(+ _ shortcut: AppNewlineShortcut,+ _ modifiers: EventModifiers,+ canRun: Bool,+ hasMarkedText: Bool = false,+ isRepeat: Bool = false+ ) -> PromptSubmissionDecision {+ PromptSubmissionPolicy.decision(+ newlineShortcut: shortcut,+ modifiers: modifiers,+ canRun: canRun,+ hasMarkedText: hasMarkedText,+ isRepeat: isRepeat)+ }+}diff --git a/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift b/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swiftnew file mode 100644index 00000000..55f42952--- /dev/null+++ b/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift@@ -0,0 +1,71 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore+@testable import TurboFieldfareDecodeService+import TurboFieldfareDecodeProtocol++@Suite struct DecodeServiceOutboxTests {+ @Test func cancellationFollowedByThrownCancellationWritesOneTerminal() throws {+ let generationID = UUID()+ let outbox = DecodeServiceOutbox(generationID: generationID)++ let event = try firstTerminal(+ from: outbox,+ published: .cancelled(diagnostics(stopReason: .cancelled)),+ finishError: AppInferenceError.cancelled)++ #expect(event.kind == .cancelled)+ #expect(event.generationID == generationID)+ }++ @Test func failureFollowedByThrownErrorWritesOneTerminal() throws {+ let generationID = UUID()+ let outbox = DecodeServiceOutbox(generationID: generationID)++ let event = try firstTerminal(+ from: outbox,+ published: .failed(.unknown("first"), partial: nil),+ finishError: AppInferenceError.unknown("second"))++ #expect(event.kind == .failed)+ #expect(event.generationID == generationID)+ #expect(event.error == "first")+ }++ private func firstTerminal(+ from outbox: DecodeServiceOutbox,+ published event: AppInferenceEvent,+ finishError: Error+ ) throws -> DecodeServiceEvent {+ 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(event)+ let terminal = try DecodeFrameCodec.read(+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)+ outbox.finish(error: finishError)++ #expect(writerFinished.wait(timeout: .now() + 2) == .success)+ #expect(pipe.fileHandleForReading.readDataToEndOfFile().isEmpty)+ return terminal+ }++ private func diagnostics(stopReason: AppStopReason) -> AppDiagnostics {+ AppDiagnostics(+ generatedTokens: 0,+ stopReason: stopReason,+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 0,+ tokensPerSecond: 0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())+ }+}