Skip to content

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

Improve Mac prompt controls and tool validation (#75)

Andrey Mikhaylov615aa29650ba
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppSentPromptBehavior.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppSentPromptBehavior.swift
new file mode 100644
index 00000000..6bb32903
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppSentPromptBehavior.swift
@@ -0,0 +1,13 @@
+public enum AppSentPromptBehavior: String, CaseIterable, Codable, Sendable, Identifiable {
+ case keep
+ case clear
+
+ public var id: String { rawValue }
+
+ public var settingsLabel: String {
+ switch self {
+ case .keep: return "Keep Prompt"
+ case .clear: return "Clear Prompt"
+ }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
index 6565fbd3..8122a1a7 100644
--- a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
@@ -15,6 +15,7 @@ struct MacAppSettings: Codable, Equatable, Sendable {
var prefillEnabled: Bool = true
var newlineShortcut: AppNewlineShortcut = .return
var showPromptExamples: Bool = true
+ var sentPromptBehavior: AppSentPromptBehavior = .keep
private enum CodingKeys: String, CodingKey {
case version
@@ -28,6 +29,7 @@ struct MacAppSettings: Codable, Equatable, Sendable {
case prefillEnabled
case newlineShortcut
case showPromptExamples
+ case sentPromptBehavior
}
init(version: Int = currentVersion,
@@ -40,7 +42,8 @@ struct MacAppSettings: Codable, Equatable, Sendable {
topP: Double = 0.95,
prefillEnabled: Bool = true,
newlineShortcut: AppNewlineShortcut = .return,
- showPromptExamples: Bool = true) {
+ showPromptExamples: Bool = true,
+ sentPromptBehavior: AppSentPromptBehavior = .keep) {
self.version = version
self.contextTokens = contextTokens
self.expertCacheSlots = expertCacheSlots
@@ -52,6 +55,7 @@ struct MacAppSettings: Codable, Equatable, Sendable {
self.prefillEnabled = prefillEnabled
self.newlineShortcut = newlineShortcut
self.showPromptExamples = showPromptExamples
+ self.sentPromptBehavior = sentPromptBehavior
}
init(from decoder: Decoder) throws {
@@ -71,6 +75,9 @@ struct MacAppSettings: Codable, Equatable, Sendable {
showPromptExamples = try container.decodeIfPresent(
Bool.self,
forKey: .showPromptExamples) ?? true
+ sentPromptBehavior = try container.decodeIfPresent(
+ AppSentPromptBehavior.self,
+ forKey: .sentPromptBehavior) ?? .keep
}
func isValid() -> Bool {
diff --git a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift
index b6040277..46ba35a3 100644
--- a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift
+++ b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift
@@ -61,6 +61,18 @@ public struct AppDiagnostics: Equatable, Sendable {
return prefillSeconds + timeToFirstTokenSeconds
}
+ public var prefillTokensPerSecond: Double? {
+ guard let promptTokenCount,
+ promptTokenCount > 0,
+ let prefillSeconds,
+ prefillSeconds.isFinite,
+ prefillSeconds > 0 else {
+ return nil
+ }
+ let rate = Double(promptTokenCount) / prefillSeconds
+ return rate.isFinite ? rate : nil
+ }
+
public init(generatedTokens: Int,
stopReason: AppStopReason,
promptTokenCount: Int? = nil,
diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swift
index 42c882f9..2770f771 100644
--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift
+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift
@@ -25,6 +25,7 @@ public final class AppModel {
public var topP: Double = 0.95
public private(set) var newlineShortcut: AppNewlineShortcut = .return
public private(set) var showPromptExamples: Bool = true
+ public private(set) var sentPromptBehavior: AppSentPromptBehavior = .keep
public var diagnostics: AppDiagnostics?
public var error: AppInferenceError?
public var installState: AppModelInstallState = .idle
@@ -83,6 +84,7 @@ public final class AppModel {
self.topP = settings.topP
self.newlineShortcut = settings.newlineShortcut
self.showPromptExamples = settings.showPromptExamples
+ self.sentPromptBehavior = settings.sentPromptBehavior
self.installationStatus = AppModelInstallationProbe.status(at: directory)
self.client = client
self.installer = installer
@@ -336,6 +338,12 @@ public final class AppModel {
persistSettings()
}
+ public func setSentPromptBehavior(_ behavior: AppSentPromptBehavior) {
+ guard sentPromptBehavior != behavior else { return }
+ sentPromptBehavior = behavior
+ persistSettings()
+ }
+
public func reloadModel() {
guard canReloadModel else { return }
beginLoad()
@@ -629,6 +637,7 @@ public final class AppModel {
topP = settings.topP
newlineShortcut = settings.newlineShortcut
showPromptExamples = settings.showPromptExamples
+ sentPromptBehavior = settings.sentPromptBehavior
}
private func persistSettings() {
@@ -643,7 +652,8 @@ public final class AppModel {
topP: topP,
prefillEnabled: runtimeOptions.prefillEnabled,
newlineShortcut: newlineShortcut,
- showPromptExamples: showPromptExamples)
+ showPromptExamples: showPromptExamples,
+ sentPromptBehavior: sentPromptBehavior)
let modelDirectory = URL(fileURLWithPath: modelPathText, isDirectory: true)
try? MacAppSettingsFileStore.save(
settings,
@@ -742,6 +752,9 @@ public final class AppModel {
liveMemoryBytes = nil
phase = .prefill
runState = .running
+ if sentPromptBehavior == .clear {
+ promptText = ""
+ }
runTask = Task.detached { [weak self, client, request] in
guard let self else { return }
diff --git a/Sources/TurboFieldfareApp/Mac/App/RootView.swift b/Sources/TurboFieldfareApp/Mac/App/RootView.swift
index 00493fe4..b90239fc 100644
--- a/Sources/TurboFieldfareApp/Mac/App/RootView.swift
+++ b/Sources/TurboFieldfareApp/Mac/App/RootView.swift
@@ -91,7 +91,7 @@ struct RootView: View {
private var conversationChrome: some View {
VStack(spacing: 10) {
ErrorBanner(model: model)
- if model.promptText.isEmpty && model.showPromptExamples {
+ if model.promptText.isEmpty && model.showPromptExamples && !model.isRunning {
PromptExamplesView { preset in
model.promptText = preset.prompt
}
diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
index 577a7de0..8ac9dd86 100644
--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
@@ -68,6 +68,11 @@ struct TurboFieldfareMacApp: App {
Text("Show").tag(true)
Text("Hide").tag(false)
}
+ Picker("After Sending", selection: sentPromptBehaviorBinding) {
+ ForEach(AppSentPromptBehavior.allCases) { behavior in
+ Text(behavior.settingsLabel).tag(behavior)
+ }
+ }
}
}
}
@@ -87,4 +92,12 @@ struct TurboFieldfareMacApp: App {
model.setShowPromptExamples(show)
}
}
+
+ private var sentPromptBehaviorBinding: Binding<AppSentPromptBehavior> {
+ Binding {
+ model.sentPromptBehavior
+ } set: { behavior in
+ model.setSentPromptBehavior(behavior)
+ }
+ }
}
diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift
index ba5f451e..a824fd6c 100644
--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift
+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift
@@ -15,6 +15,12 @@ struct RunnerDiagnosticsSection: View {
groupLabel("Performance")
DiagnosticRow("Prompt prefill", MetricFormat.seconds(diagnostics.prefillSeconds))
+ if let prefillRate = diagnostics.prefillTokensPerSecond {
+ DiagnosticRow(
+ "Prefill rate",
+ "\(MetricFormat.rate(prefillRate)) tok/s",
+ help: "Prompt tokens divided by prefill time. Compare runs with similar prompt lengths and settings; short prompts include proportionally more fixed overhead.")
+ }
DiagnosticRow("First token wait", MetricFormat.seconds(diagnostics.timeToFirstTokenSeconds))
DiagnosticRow("Request TTFT", MetricFormat.seconds(diagnostics.requestStartTimeToFirstTokenSeconds))
DiagnosticRow("Decode duration", MetricFormat.seconds(diagnostics.decodeSeconds))
@@ -123,15 +129,21 @@ private struct DiagnosticRow: View {
let label: String
let value: String
let multiline: Bool
+ let help: String?
+ @State private var isShowingHelp = false
- init(_ label: String, _ value: String, multiline: Bool = false) {
+ init(_ label: String,
+ _ value: String,
+ multiline: Bool = false,
+ help: String? = nil) {
self.label = label
self.value = value
self.multiline = multiline
+ self.help = help
}
var body: some View {
- LabeledContent(label) {
+ LabeledContent {
Text(value)
.font(.caption)
.monospacedDigit()
@@ -140,6 +152,31 @@ private struct DiagnosticRow: View {
.multilineTextAlignment(.trailing)
.lineLimit(multiline ? nil : 2)
.fixedSize(horizontal: false, vertical: true)
+ } label: {
+ HStack(spacing: 4) {
+ Text(label)
+ if let help {
+ Button {
+ isShowingHelp.toggle()
+ } label: {
+ Image(systemName: "info.circle")
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ .frame(width: 16, height: 16)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help(help)
+ .popover(isPresented: $isShowingHelp, arrowEdge: .trailing) {
+ Text(help)
+ .font(.callout)
+ .frame(width: 280, alignment: .leading)
+ .padding()
+ }
+ .accessibilityLabel("\(label) information")
+ .accessibilityHint(help)
+ }
+ }
}
}
}
diff --git a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift b/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
index e6dfe64b..23b47a5d 100644
--- a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
+++ b/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
@@ -252,6 +252,30 @@ public struct ValidatedChatRequest: Sendable {
public let maximumCompletionTokens: Int
}
+private enum OpenAIToolName {
+ static let maximumLength = 64
+
+ static func isValid(_ name: String) -> Bool {
+ let bytes = name.utf8
+ guard !bytes.isEmpty, bytes.count <= maximumLength else { return false }
+ return bytes.allSatisfy { byte in
+ switch byte {
+ case 45, 48...57, 65...90, 95, 97...122:
+ true
+ default:
+ false
+ }
+ }
+ }
+
+ static func validationMessage(for name: String) -> String {
+ let prefix = name.prefix(maximumLength + 1)
+ let displayed = String(prefix.prefix(maximumLength))
+ + (prefix.count > maximumLength ? "..." : "")
+ return "tool name \(String(reflecting: displayed)) must contain 1 to 64 ASCII letters, numbers, underscores, or hyphens"
+ }
+}
+
public enum OpenAIRequestValidator {
public static func validate(_ request: OpenAIChatRequest,
modelID: String) throws -> ValidatedChatRequest {
@@ -335,8 +359,8 @@ public enum OpenAIRequestValidator {
throw invalid("only function tools are supported", "tools", "unsupported_tool")
}
let name = tool.function.name
- guard name.range(of: #"^[A-Za-z0-9_]{1,64}$"#, options: .regularExpression) != nil else {
- throw invalid("tool name must match [A-Za-z0-9_]{1,64}",
+ guard OpenAIToolName.isValid(name) else {
+ throw invalid(OpenAIToolName.validationMessage(for: name),
"tools", "invalid_tool_name")
}
guard tool.function.parameters.objectValue != nil else {
@@ -409,13 +433,14 @@ public enum OpenAIRequestValidator {
let content = try message.content?.textValue()
let calls: [GFTokenizer.HistoricalToolCall] = try (message.toolCalls ?? []).map { call in
guard role == .assistant, call.type == "function",
- !call.id.isEmpty, knownCalls[call.id] == nil,
- call.function.name.range(
- of: #"^[A-Za-z0-9_]{1,64}$"#,
- options: .regularExpression) != nil else {
+ !call.id.isEmpty, knownCalls[call.id] == nil else {
throw invalid("invalid or duplicate historical tool call",
"messages", "invalid_tool_call")
}
+ guard OpenAIToolName.isValid(call.function.name) else {
+ throw invalid(OpenAIToolName.validationMessage(for: call.function.name),
+ "messages", "invalid_tool_call")
+ }
let data = Data(call.function.arguments.utf8)
let arguments = try JSONDecoder().decode(JSONValue.self, from: data)
guard arguments.objectValue != nil else {
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
index 461681c8..6615758b 100644
--- a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
@@ -82,6 +82,7 @@ import Testing
#expect(!settings.prefillEnabled)
#expect(settings.newlineShortcut == .return)
#expect(settings.showPromptExamples)
+ #expect(settings.sentPromptBehavior == .keep)
}
@Test(arguments: AppNewlineShortcut.allCases)
@@ -110,6 +111,16 @@ import Testing
#expect(decoded == initial)
}
+ @Test(arguments: AppSentPromptBehavior.allCases)
+ func sentPromptBehaviorRoundTrips(_ behavior: AppSentPromptBehavior) throws {
+ let initial = MacAppSettings(sentPromptBehavior: behavior)
+ let decoded = try JSONDecoder().decode(
+ MacAppSettings.self,
+ from: JSONEncoder().encode(initial))
+
+ #expect(decoded == initial)
+ }
+
@Test func invalidNewlineShortcutIsReplacedWithDefaults() throws {
let root = try makeTemporaryRoot()
defer { try? FileManager.default.removeItem(at: root) }
@@ -154,7 +165,8 @@ import Testing
topP: 0.8,
prefillEnabled: false,
newlineShortcut: .shiftReturn,
- showPromptExamples: false)
+ showPromptExamples: false,
+ sentPromptBehavior: .clear)
try MacAppSettingsFileStore.save(initial, forModelDirectory: modelDirectory)
let model = AppModel(
@@ -170,6 +182,7 @@ import Testing
#expect(!model.runtimeOptions.prefillEnabled)
#expect(model.newlineShortcut == .shiftReturn)
#expect(!model.showPromptExamples)
+ #expect(model.sentPromptBehavior == .clear)
model.temperature = 0.6
model.runtimeOptions.expertCacheSlots = 32
@@ -188,6 +201,7 @@ import Testing
#expect(saved.prefillEnabled)
#expect(saved.newlineShortcut == .shiftReturn)
#expect(!saved.showPromptExamples)
+ #expect(saved.sentPromptBehavior == .clear)
model.cancel()
}
@@ -223,6 +237,22 @@ import Testing
#expect(!saved.showPromptExamples)
}
+ @MainActor
+ @Test func sentPromptBehaviorPersistsImmediately() throws {
+ let root = try makeTemporaryRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
+ let model = AppModel(
+ modelDirectory: modelDirectory,
+ settingsPersistenceEnabled: true)
+
+ model.setSentPromptBehavior(.clear)
+
+ let saved = MacAppSettingsFileStore.loadOrCreate(
+ forModelDirectory: modelDirectory)
+ #expect(saved.sentPromptBehavior == .clear)
+ }
+
@MainActor
@Test func changingModelDirectoryLoadsItsNewlineShortcut() throws {
let root = try makeTemporaryRoot()
diff --git a/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift b/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift
index 84711163..aa266d05 100644
--- a/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift
@@ -40,6 +40,29 @@ import Testing
#expect(missingFirstToken.requestStartTimeToFirstTokenSeconds == nil)
}
+ @Test func prefillRateUsesPromptTokensAndPrefillDuration() {
+ var diagnostics = AppDiagnostics(
+ generatedTokens: 1,
+ stopReason: .eos,
+ promptTokenCount: 20,
+ prefillSeconds: 6.17,
+ timeToFirstTokenSeconds: 0.5,
+ decodeSeconds: 0.75,
+ tokensPerSecond: 1.0,
+ peakMemoryBytes: nil,
+ runtimeOptions: AppRuntimeOptions())
+
+ #expect(abs((diagnostics.prefillTokensPerSecond ?? 0) - 3.241491) < 0.000001)
+
+ diagnostics.promptTokenCount = 0
+ #expect(diagnostics.prefillTokensPerSecond == nil)
+ diagnostics.promptTokenCount = 20
+ diagnostics.prefillSeconds = 0
+ #expect(diagnostics.prefillTokensPerSecond == nil)
+ diagnostics.prefillSeconds = .nan
+ #expect(diagnostics.prefillTokensPerSecond == nil)
+ }
+
@Test func runnerDiagnosticsRetainPublicResultAndAdvancedMetrics() {
let diagnostics = AppRunnerDiagnostics(
cb1MillisecondsPerToken: 1,
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
index 99f46172..ac711393 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
@@ -175,6 +175,7 @@ import Testing
model.run()
#expect(model.outputPromptText == "original prompt")
+ #expect(model.promptText == "original prompt")
#expect(model.hasOutputTranscript)
#expect(model.outputResponsePlainText.isEmpty)
#expect(model.outputConversationPlainText == "You:\noriginal prompt")
@@ -189,6 +190,45 @@ import Testing
#expect(!model.outputConversationPlainText.contains("edited prompt"))
}
+ @MainActor
+ @Test func clearAfterSendingPreservesTranscriptAndNextDraft() async throws {
+ let client = MockInferenceClient(
+ response: "answer",
+ tokenDelayNanos: 20_000_000)
+ let model = readyModel(client: client)
+ model.setSentPromptBehavior(.clear)
+ model.promptText = "original prompt"
+ model.maxNewTokensOverride = 1
+
+ model.run()
+
+ #expect(model.isRunning)
+ #expect(model.outputPromptText == "original prompt")
+ #expect(model.promptText.isEmpty)
+
+ model.promptText = "next draft"
+ await waitForIdle(model)
+
+ #expect(model.promptText == "next draft")
+ #expect(model.outputConversationPlainText.hasPrefix(
+ "You:\noriginal prompt\n\nAnswer:\n"))
+ }
+
+ @MainActor
+ @Test func failedValidationDoesNotClearPrompt() {
+ let model = readyModel(client: MockInferenceClient(response: "answer"))
+ model.setSentPromptBehavior(.clear)
+ model.promptText = "keep invalid prompt"
+ model.maxNewTokensOverride = 0
+
+ model.run()
+
+ #expect(!model.isRunning)
+ #expect(model.promptText == "keep invalid prompt")
+ #expect(model.outputPromptText.isEmpty)
+ #expect(model.error != nil)
+ }
+
@MainActor
@Test func staleReadySessionDisablesGenerationUntilReload() throws {
let client = MockLifecycleInferenceClient()
diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
index b39b14f4..11f07fcf 100644
--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
@@ -44,6 +44,57 @@ struct OpenAIValidationTests {
}
}
+ @Test func hyphenatedToolNamesValidateInDefinitionsAndHistory() throws {
+ let data = Data(#"""
+ {
+ "model":"m",
+ "messages":[
+ {"role":"user","content":"resolve it"},
+ {"role":"assistant","tool_calls":[{
+ "id":"call_0123456789abcdef01234567",
+ "type":"function",
+ "function":{"name":"resolve-library-id","arguments":"{\"name\":\"swift\"}"}
+ }]},
+ {"role":"tool","tool_call_id":"call_0123456789abcdef01234567","content":"42"}
+ ],
+ "tools":[{
+ "type":"function",
+ "function":{
+ "name":"resolve-library-id",
+ "parameters":{"type":"object","properties":{"name":{"type":"string"}}}
+ }
+ }]
+ }
+ """#.utf8)
+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)
+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")
+ #expect(validated.tools.first?.name == "resolve-library-id")
+ #expect(validated.messages[1].toolCalls.first?.name == "resolve-library-id")
+ }
+
+ @Test func invalidToolNameErrorIdentifiesTheName() throws {
+ for invalid in ["bad name", "bad.name", "bad@name"] {
+ let data = Data(#"""
+ {
+ "model":"m",
+ "messages":[{"role":"user","content":"x"}],
+ "tools":[{
+ "type":"function",
+ "function":{"name":"\#(invalid)","parameters":{"type":"object"}}
+ }]
+ }
+ """#.utf8)
+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)
+ do {
+ _ = try OpenAIRequestValidator.validate(request, modelID: "m")
+ Issue.record("invalid tool name was accepted: \(invalid)")
+ } catch let error as ServerRequestError {
+ #expect(error.envelope.error.code == "invalid_tool_name")
+ #expect(error.envelope.error.message.contains(String(reflecting: invalid)))
+ }
+ }
+ }
+
@Test func acceptsLeadingSystemAndDeveloperGuidance() throws {
let data = Data(#"""
{"model":"m","messages":[