new features

This commit is contained in:
Mark Gregory
2026-11-16 13:41:54 +00:00
parent 87cdc990c3
commit 5338ae5751
16 changed files with 546 additions and 55 deletions
+266 -5
View File
@@ -1,5 +1,6 @@
import SwiftUI
import AppKit
import Charts
import UniformTypeIdentifiers
@main
@@ -45,20 +46,41 @@ struct ChatView: View {
@AppStorage("failover") private var failover = true
@AppStorage("mlxOnly") private var mlxOnly = false
@AppStorage("recall") private var recall = true
@AppStorage("globalPromptMode") private var promptMode = PromptMode.standard
@AppStorage("globalCustomPrompt") private var customPrompt = ""
@State private var showingPromptBuilder = false
@State private var showingPerformance = false
@State private var confirmDelete = false
@State private var search = ""
@State private var renaming = false
@State private var newTitle = ""
private var visibleChats: [Conversation] {
search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? studio.conversations : studio.searchConversations(search)
}
@State private var showingLibrary = false
@State private var useDocuments = false
var body: some View {
NavigationSplitView {
List(studio.conversations, selection: $studio.selected) { chat in
List(visibleChats, selection: $studio.selected) { chat in
Label(chat.title, systemImage: "bubble.left").tag(chat.id)
}
.searchable(text: $search, placement: .sidebar, prompt: "Search Chats")
.disabled(studio.running)
.navigationSplitViewColumnWidth(min: 180, ideal: 235)
.toolbar {
Button("New Chat", systemImage: "square.and.pencil") { studio.newChat() }
Button("New Chat", systemImage: "square.and.pencil") {
search = ""
studio.newChat()
}
.disabled(studio.running)
Button("Rename Chat", systemImage: "pencil") {
newTitle = studio.conversations.first(where: { $0.id == studio.selected })?.title ?? ""
renaming = true
}
.disabled(studio.running || studio.selected == nil)
Button("Delete Chat", systemImage: "trash") { confirmDelete = true }
.disabled(studio.running || studio.selected == nil)
}
@@ -76,11 +98,29 @@ struct ChatView: View {
.toolbar {
Button("Documents", systemImage: "doc.on.doc") { showingLibrary = true }
.disabled(studio.selected == nil)
Button("Prompt Builder", systemImage: "wand.and.stars") { showingPromptBuilder = true }
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
SettingsLink { Label("Settings", systemImage: "gear") }
}
}
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
.sheet(isPresented: $showingPromptBuilder) {
PromptBuilder(customPrompt: $customPrompt) { instructions, global in
if global {
customPrompt = instructions
promptMode = .custom
} else {
studio.prompt = instructions
}
}
}
.onChange(of: studio.selected) { _, _ in useDocuments = false }
.alert("Rename Chat", isPresented: $renaming) {
TextField("Title", text: $newTitle)
Button("Rename") { studio.renameSelectedChat(newTitle) }
Button("Cancel", role: .cancel) {}
}
.confirmationDialog("Delete this conversation?", isPresented: $confirmDelete, titleVisibility: .visible) {
Button("Delete Conversation", role: .destructive) { studio.deleteChat() }
} message: {
@@ -93,7 +133,7 @@ struct ChatView: View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 18) {
ForEach(studio.messages) { MessageView(message: $0) }
if let partial = studio.partial { MessageView(message: partial) }
if let partial = studio.partial { MessageView(message: partial, streaming: true) }
Color.clear.frame(height: 1).id("end")
}
.frame(maxWidth: 800)
@@ -127,6 +167,17 @@ 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)
@@ -157,7 +208,8 @@ struct ChatView: View {
} else {
Button("Send", systemImage: "arrow.up") {
studio.send(endpoint: endpoint, model: model, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, recall: recall, useDocuments: useDocuments)
failover: failover, mlxOnly: mlxOnly, recall: recall, useDocuments: useDocuments,
instructions: promptMode.instructions(custom: customPrompt))
}
.buttonStyle(.borderedProminent)
.keyboardShortcut(.return, modifiers: .command)
@@ -171,6 +223,7 @@ struct ChatView: View {
struct MessageView: View {
let message: Message
var streaming = false
var body: some View {
VStack(alignment: .leading, spacing: 8) {
@@ -181,6 +234,13 @@ struct MessageView: View {
if !message.backend.isEmpty {
Text(message.backend).font(.caption).foregroundStyle(.secondary)
}
Spacer()
if !streaming, !message.content.isEmpty {
Button("Copy Message", systemImage: "doc.on.doc") { copyChatText(message.content) }
.labelStyle(.iconOnly)
.buttonStyle(.borderless)
.help("Copy message")
}
}
if !message.thinking.isEmpty {
DisclosureGroup("Thinking") {
@@ -188,7 +248,13 @@ struct MessageView: View {
.frame(maxWidth: .infinity, alignment: .leading)
}
}
if !message.content.isEmpty { Text(message.content).textSelection(.enabled) }
if !message.content.isEmpty {
if message.role == .assistant && !streaming {
ChatMarkdown(text: message.content)
} else {
Text(message.content).textSelection(.enabled)
}
}
if message.content.isEmpty && message.thinking.isEmpty { ProgressView().controlSize(.small) }
}
.frame(maxWidth: .infinity, alignment: .leading)
@@ -383,3 +449,198 @@ struct DocumentLibraryView: View {
}
}
}
private func copyChatText(_ text: String) {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
}
struct ChatMarkdown: View {
let text: String
struct Block: Equatable {
let content: String
let language: String?
}
static func blocks(_ markdown: String) -> [Block] {
var blocks: [Block] = []
var lines: [String] = []
var language: String?
var opener = ""
for line in markdown.components(separatedBy: .newlines) {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if language != nil && trimmed == "```" {
blocks.append(Block(content: lines.joined(separator: "\n"), language: language))
lines = []
language = nil
} else if language == nil && trimmed.hasPrefix("```") {
if !lines.isEmpty {
blocks.append(Block(content: lines.joined(separator: "\n"), language: nil))
}
lines = []
opener = line
language = String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespaces)
} else {
lines.append(line)
}
}
if language != nil { lines.insert(opener, at: 0) }
if !lines.isEmpty {
blocks.append(Block(content: lines.joined(separator: "\n"), language: nil))
}
return blocks.filter { $0.language != nil || !$0.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
}
var body: some View {
let blocks = Self.blocks(text)
VStack(alignment: .leading, spacing: 10) {
ForEach(blocks.indices, id: \.self) { index in
let block = blocks[index]
if let language = block.language {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text(language.isEmpty ? "Code" : String(language.prefix(60)))
.font(.caption).foregroundStyle(.secondary)
Spacer()
Button("Copy Code", systemImage: "doc.on.doc") { copyChatText(block.content) }
.buttonStyle(.borderless)
}
ScrollView(.horizontal) {
Text(block.content).font(.system(.body, design: .monospaced)).textSelection(.enabled)
}
}
.padding(10)
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
} else {
let parsed = try? AttributedString(markdown: block.content,
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))
Text(parsed ?? AttributedString(block.content)).textSelection(.enabled)
}
}
}
}
}
struct PromptBuilder: View {
@Environment(\.dismiss) private var dismiss
@Binding var customPrompt: String
let apply: (String, Bool) -> Void
@State private var draft = PromptDraft()
@State private var edited = ""
@State private var editingDirectly = false
private var output: String {
editingDirectly ? edited.trimmingCharacters(in: .whitespacesAndNewlines) : draft.rendered
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Prompt Builder").font(.title2.bold())
HSplitView {
Form {
TextField("Role", text: $draft.role, prompt: Text("Who should the model act as?"))
TextField("Task", text: $draft.task, prompt: Text("What should it do?"), axis: .vertical)
TextField("Context", text: $draft.context, axis: .vertical)
TextField("Audience", text: $draft.audience)
TextField("Requirements and constraints", text: $draft.constraints, axis: .vertical)
TextField("Output format", text: $draft.format, axis: .vertical)
TextField("Examples", text: $draft.examples, axis: .vertical)
TextField("Success criteria", text: $draft.success, axis: .vertical)
}
.formStyle(.grouped)
.disabled(editingDirectly)
.frame(minWidth: 310)
VStack(alignment: .leading) {
HStack {
Text("Preview").font(.headline)
Spacer()
Toggle("Edit directly", isOn: Binding(
get: { editingDirectly },
set: { enabled in
if enabled { edited = draft.rendered }
editingDirectly = enabled
}
))
}
if editingDirectly {
TextEditor(text: $edited).accessibilityLabel("Prompt text")
} else {
ScrollView {
Text(output.isEmpty ? "Fill in any field to build your prompt." : output)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
.padding(12)
.frame(minWidth: 285, maxHeight: .infinity, alignment: .top)
}
HStack {
Button("Load Global Custom Prompt") {
editingDirectly = true
edited = customPrompt
}
.disabled(customPrompt.isEmpty)
Spacer()
Button("Copy") { copyChatText(output) }.disabled(output.isEmpty)
Button("Use in Composer") { submit(global: false) }.disabled(output.isEmpty)
Button("Set as Global Prompt") { submit(global: true) }.disabled(output.isEmpty)
Button("Close") { dismiss() }.keyboardShortcut(.cancelAction)
}
}
.padding(20)
.frame(minWidth: 780, minHeight: 520)
}
private func submit(global: Bool) {
apply(output, global)
dismiss()
}
}
struct PerformanceDashboard: View {
@Environment(\.dismiss) private var dismiss
@ObservedObject var studio: StudioModel
var body: some View {
VStack(alignment: .leading, spacing: 14) {
HStack {
Text("Inference Performance").font(.title2.bold())
Spacer()
Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
}
Text("Up to 50 generations from this session. First output includes model loading and any fallback.")
.foregroundStyle(.secondary)
if studio.measurements.isEmpty {
ContentUnavailableView("No measurements yet", systemImage: "chart.xyaxis.line",
description: Text("Send a chat message to collect timing and throughput."))
} else {
Chart {
ForEach(Array(studio.measurements.reversed().enumerated()), id: \.element.id) { index, run in
BarMark(x: .value("Run", index + 1), y: .value("Seconds", run.seconds))
.foregroundStyle(by: .value("Backend", run.backend))
}
}
.chartXAxisLabel("Generation")
.chartYAxisLabel("Total seconds")
.frame(height: 160)
Table(studio.measurements) {
TableColumn("Backend", value: \.backend)
TableColumn("First output") { Text(seconds($0.firstOutput)) }
TableColumn("Total") { Text(seconds($0.seconds)) }
TableColumn("Tokens/s") { Text($0.provider?.tokensPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—") }
TableColumn("Tokens") { Text($0.provider?.tokens.formatted() ?? "—") }
TableColumn("Characters") { Text($0.characters.formatted()) }
TableColumn("Outcome", value: \.outcome)
}
}
}
.padding(20)
.frame(minWidth: 800, minHeight: 475)
}
private func seconds(_ value: Double?) -> String {
value.map { $0.formatted(.number.precision(.fractionLength(2))) + " s" } ?? "—"
}
}