Configure silent prompts, generation parameters, and local tools

This commit is contained in:
Mark Gregory
2026-11-16 13:54:57 +00:00
parent 0287c85e2a
commit afeba270f4
8 changed files with 517 additions and 27 deletions
+240 -12
View File
@@ -29,6 +29,10 @@ struct AIStudioApp: App {
.tabItem { Label("Models", systemImage: "cpu") }
ModelCatalogView(studio: studio)
.tabItem { Label("MLX Catalog", systemImage: "arrow.down.circle") }
GenerationSettingsView()
.tabItem { Label("Generation", systemImage: "slider.horizontal.3") }
LocalToolsView(studio: studio)
.tabItem { Label("Local Tools", systemImage: "terminal") }
MCPSettings(studio: studio)
.tabItem { Label("MCP Tools", systemImage: "wrench.and.screwdriver") }
}
@@ -48,6 +52,7 @@ struct ChatView: View {
@AppStorage("recall") private var recall = true
@AppStorage("globalPromptMode") private var promptMode = PromptMode.standard
@AppStorage("globalCustomPrompt") private var customPrompt = ""
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
@State private var showingPromptBuilder = false
@State private var showingPerformance = false
@State private var confirmDelete = false
@@ -167,17 +172,6 @@ struct ChatView: View {
.disabled(studio.running)
}
}
HStack {
Picker("Global Prompt", selection: $promptMode) {
ForEach(PromptMode.allCases) { Text($0.rawValue).tag($0) }
}
.fixedSize()
.disabled(studio.running)
Button("Edit Custom Prompt…") { showingPromptBuilder = true }
.buttonStyle(.borderless)
Spacer()
}
.font(.caption)
if !studio.documents.isEmpty {
Toggle(mlxOnly ? "Include matching document excerpts" :
"Send matching document excerpts to Ollama", isOn: $useDocuments)
@@ -209,7 +203,8 @@ struct ChatView: View {
Button("Send", systemImage: "arrow.up") {
studio.send(endpoint: endpoint, model: model, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, recall: recall, useDocuments: useDocuments,
instructions: promptMode.instructions(custom: customPrompt))
instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings))
}
.buttonStyle(.borderedProminent)
.keyboardShortcut(.return, modifiers: .command)
@@ -644,3 +639,236 @@ struct PerformanceDashboard: View {
value.map { $0.formatted(.number.precision(.fractionLength(2))) + " s" } ?? "—"
}
}
struct GenerationSettingsView: View {
@AppStorage("globalPromptMode") private var promptMode = PromptMode.standard
@AppStorage("globalCustomPrompt") private var prompt = ""
@AppStorage("thinking") private var thinking = Thinking.automatic
@AppStorage(GenerationSettings.key) private var stored = Data()
@State private var draft = GenerationSettings()
@State private var status = ""
var body: some View {
VStack(spacing: 0) {
Form {
Section("System Prompt") {
Picker("Global preset", selection: $promptMode) {
ForEach(PromptMode.allCases) { Text($0.rawValue).tag($0) }
}
if promptMode == .custom {
TextEditor(text: $prompt)
.font(.body).frame(minHeight: 88).accessibilityLabel("Global system instructions")
} else if promptMode != .standard {
Text(promptMode.instructions(custom: prompt)).foregroundStyle(.secondary).textSelection(.enabled)
}
Text("Applied automatically to new replies across chats. System instructions stay out of the transcript.")
.foregroundStyle(.secondary)
}
Section("Shared Generation") {
Picker("Thinking", selection: $thinking) {
ForEach(Thinking.allCases) { Text($0.rawValue.capitalized).tag($0) }
}
field("Temperature", $draft.temperature)
field("Maximum output tokens", $draft.maxTokens)
field("Top P", $draft.topP)
field("Repeat penalty", $draft.repeatPenalty)
field("Repeat window", $draft.repeatLastN)
TextField("Stop sequences (one per line)", text: $draft.stop, axis: .vertical)
}
Section("Ollama") {
field("Context length", $draft.context)
field("Top K", $draft.topK)
field("Min P", $draft.minP)
field("Seed", $draft.seed)
field("Frequency penalty", $draft.frequencyPenalty)
field("Presence penalty", $draft.presencePenalty)
field("Keep alive (e.g. 5m or 0)", $draft.keepAlive)
Toggle("JSON output", isOn: $draft.json)
}
Section("MLX") {
field("Rolling KV cache tokens", $draft.mlxCache)
field("Prefill step size", $draft.mlxPrefill)
Text("MLX uses Default, Off, or On for supported thinking templates. Its default output cap is 1,024 tokens.")
.foregroundStyle(.secondary)
}
}
.formStyle(.grouped)
Divider()
HStack {
Text(status.isEmpty ? "Blank fields use backend defaults." : status)
.foregroundStyle(.secondary).font(.caption).textSelection(.enabled)
Spacer()
Button("Reset Overrides") {
draft = GenerationSettings()
save()
}
Button("Apply Parameters", action: save).buttonStyle(.borderedProminent)
}
.padding(12)
}
.onAppear { draft = GenerationSettings.read(stored) }
}
private func field(_ title: String, _ value: Binding<String>) -> some View {
TextField(title, text: value, prompt: Text("Default"))
}
private func save() {
do {
_ = try draft.parameters(mlxOnly: false)
stored = try JSONEncoder().encode(draft)
status = "Parameters saved for future replies."
} catch { status = error.localizedDescription }
}
}
enum DockerCommand {
static func arguments(_ line: String) throws -> [String] {
var arguments: [String] = []
var word = ""
var quote: Character?
var escaped = false
var started = false
for character in line {
if escaped {
word.append(character)
escaped = false
} else if character == "\\" && quote != "'" {
escaped = true
started = true
} else if let activeQuote = quote {
if character == activeQuote { quote = nil }
else { word.append(character) }
} else if character == "'" || character == "\"" {
quote = character
started = true
} else if character.isWhitespace {
if started { arguments.append(word); word = ""; started = false }
} else {
word.append(character)
started = true
}
}
guard quote == nil, !escaped else { throw StudioError("Close the quoted argument or remove the trailing backslash.") }
if started { arguments.append(word) }
if arguments.first == "docker" { arguments.removeFirst() }
guard let first = arguments.first, !first.isEmpty else { throw StudioError("Enter a Docker command.") }
return arguments
}
static var executable: URL? {
let paths = ["/usr/local/bin/docker", "/opt/homebrew/bin/docker",
FileManager.default.homeDirectoryForCurrentUser.appending(path: ".docker/bin/docker").path,
"/Applications/Docker.app/Contents/Resources/bin/docker"]
return paths.first(where: FileManager.default.isExecutableFile(atPath:)).map { URL(fileURLWithPath: $0) }
}
}
struct LocalToolsView: View {
@ObservedObject var studio: StudioModel
@State private var line = "docker ps"
@State private var pending: [String]?
@State private var output = ""
@State private var process: Process?
@State private var file: URL?
@State private var picking = false
@State private var status = ""
@State private var confirm = false
var body: some View {
Form {
Section("Docker") {
TextField("Command", text: $line, prompt: Text("docker ps --all"))
.font(.system(.body, design: .monospaced))
.disabled(process != nil)
Text("Commands run through the local Docker CLI. Interactive input is unavailable.")
.foregroundStyle(.secondary)
HStack {
Button("Review Command…") {
do {
pending = try DockerCommand.arguments(line)
confirm = true
status = ""
} catch { status = error.localizedDescription }
}
.disabled(process != nil)
if let process { Button("Stop") { if process.isRunning { process.terminate() } } }
}
if !status.isEmpty { Text(status).foregroundStyle(.secondary) }
if !output.isEmpty {
ScrollView {
Text(output).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(height: 140)
HStack {
Button("Copy Output") { copyChatText(output) }
Button("Attach to Active Chat") { studio.attachToolResult(name: "Docker", output: output) }
.disabled(studio.selected == nil || studio.running)
}
}
}
Section("Finder") {
Button("Choose File or Folder…") { picking = true }
if let file {
Text(file.path).textSelection(.enabled)
HStack {
Button("Open") { NSWorkspace.shared.open(file) }
Button("Reveal in Finder") { NSWorkspace.shared.activateFileViewerSelecting([file]) }
}
}
}
}
.formStyle(.grouped)
.fileImporter(isPresented: $picking, allowedContentTypes: [.item, .folder]) { result in
do { file = try result.get() }
catch { status = error.localizedDescription }
}
.confirmationDialog("Run Docker command?", isPresented: $confirm, titleVisibility: .visible) {
Button("Run Command") { if let pending { run(pending) } }
} message: {
Text(line)
}
}
private func run(_ args: [String]) {
guard process == nil else { return }
guard let executable = DockerCommand.executable else {
status = "Docker CLI was not found in the standard install locations."
return
}
let child = Process()
let pipe = Pipe()
child.executableURL = executable
child.arguments = args
child.standardInput = FileHandle.nullDevice
child.standardOutput = pipe
child.standardError = pipe
do {
try child.run()
process = child
output = ""
status = "Running…"
} catch {
status = error.localizedDescription
return
}
Task {
let result = await Task.detached {
let reader = pipe.fileHandleForReading
var captured = Data()
var truncated = false
while let bytes = try? reader.read(upToCount: 8192), !bytes.isEmpty {
let remaining = max(0, 131_072 - captured.count)
captured.append(bytes.prefix(remaining))
truncated = truncated || bytes.count > remaining
}
child.waitUntilExit()
return (String(decoding: captured, as: UTF8.self), child.terminationStatus, truncated)
}.value
output = result.0 + (result.2 ? "\n[Output truncated]" : "")
status = "Exited with status \(result.1)."
process = nil
}
}
}