Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Chat/ChatInspector.swift3// Description: The conversation inspector: system prompt, sampling parameters, context and compaction, knowledge, agent, organisation, export.4import SwiftUI5import UniformTypeIdentifiers6import LocalChatCore78public struct ChatInspector: View {9 @Environment(AppModel.self) private var app10 @Bindable var controller: ChatController11 @State private var summaryPreview: String?12 @State private var summarizing = false13 @State private var newTag = ""14 @State private var exporting: ExportPayload?1516 public init(controller: ChatController) { self.controller = controller }1718 struct ExportPayload: Identifiable { let id = UUID(); let document: TextFile; let name: String; let type: UTType }1920 public var body: some View {21 ScrollView {22 VStack(alignment: .leading, spacing: DS.S.lg) {23 group("System prompt", symbol: "person.text.rectangle") {24 TextEditor(text: bind(\.systemPrompt)).font(DS.F.callout).scrollContentBackground(.hidden).frame(minHeight: 84, maxHeight: 180)25 .padding(6).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))26 .accessibilityIdentifier("system-prompt")27 Menu("Use a template") {28 ForEach(app.templates.filter { $0.kind == .system }) { t in Button(t.name) { controller.update { $0.systemPrompt = t.body } } }29 }.menuStyle(.borderlessButton).fixedSize().font(DS.F.caption)30 }31 group("Inference", symbol: "slider.horizontal.3") {32 Picker("Preset", selection: Binding(get: { controller.conversation.preset }, set: { if let p = $0 { controller.setPreset(p) } })) {33 ForEach(InferencePreset.allCases) { Text($0.title).tag(Optional($0)) }34 if controller.conversation.preset == nil { Text("Custom").tag(Optional<InferencePreset>.none) }35 }36 .pickerStyle(.menu).labelsHidden().fixedSize()37 if let preset = controller.conversation.preset { Text(preset.summary).font(DS.F.micro).foregroundStyle(DS.C.muted) }38 slider("Temperature", value: settings(\.temperature), range: 0...2, step: 0.05, format: "%.2f")39 slider("Top-p", value: settings(\.topP), range: 0.05...1, step: 0.01, format: "%.2f")40 stepper("Top-k", value: settings(\.topK), range: 0...200, step: 5, zeroLabel: "off")41 slider("Min-p", value: settings(\.minP), range: 0...0.5, step: 0.01, format: "%.2f")42 slider("Repetition penalty", value: settings(\.repetitionPenalty), range: 1...1.5, step: 0.01, format: "%.2f")43 stepper("Max answer tokens", value: settings(\.maxTokens), range: 64...32768, step: 256)44 stepper("Context length", value: settings(\.contextLength), range: 1024...(controller.model?.contextLength ?? 131072), step: 1024)45 SettingRow("Seed", detail: "Fix the seed for repeatable answers.") {46 HStack(spacing: 6) {47 Toggle("", isOn: Binding(get: { controller.conversation.settings.seed != nil }, set: { on in custom { $0.seed = on ? 42 : nil } })).labelsHidden()48 if controller.conversation.settings.seed != nil {49 TextField("seed", value: Binding(get: { Int(controller.conversation.settings.seed ?? 0) }, set: { v in custom { $0.seed = UInt64(max(0, v)) } }), format: .number)50 .textFieldStyle(.roundedBorder).frame(width: 90)51 }52 }53 }54 SettingRow("Reasoning", detail: "Ask models that support it to think before answering.") {55 Toggle("", isOn: Binding(get: { controller.conversation.settings.reasoningEnabled }, set: { v in custom { $0.reasoningEnabled = v } })).labelsHidden()56 }57 if controller.model?.backend == .mlx {58 SettingRow("KV-cache quantization", detail: "Lower memory for long contexts (MLX).") {59 Picker("", selection: Binding(get: { controller.conversation.settings.kvBits ?? 0 }, set: { v in custom { $0.kvBits = v == 0 ? nil : v } })) {60 Text("Off").tag(0); Text("8-bit").tag(8); Text("4-bit").tag(4)61 }.labelsHidden().fixedSize()62 }63 }64 }65 group("Context", symbol: "rectangle.stack") {66 if let context = controller.context { ContextWindowBar(context: context) }67 Picker("When the window is full", selection: bind(\.compaction)) { ForEach(CompactionPolicy.allCases) { Text($0.title).tag($0) } }68 Text("Compaction only changes what is sent to the model. Your messages are never modified or deleted.").font(DS.F.micro).foregroundStyle(DS.C.muted)69 HStack {70 Button(summarizing ? "Summarizing…" : "Summarize conversation") {71 summarizing = true72 Task { summaryPreview = await controller.summarizeNow(); summarizing = false }73 }74 .buttonStyle(.lcSecondaryCompact).disabled(summarizing || controller.isGenerating || controller.messages.isEmpty)75 if summarizing { ProgressView().controlSize(.small) }76 }77 if let summaryPreview {78 Text(summaryPreview).font(DS.F.caption).foregroundStyle(DS.C.text2).textSelection(.enabled)79 .padding(8).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))80 }81 }82 group("Knowledge", symbol: "books.vertical") {83 if app.collections.isEmpty { Text("No collection yet. Create one in the Knowledge Studio to ground answers in your documents.").font(DS.F.caption).foregroundStyle(DS.C.muted) }84 ForEach(app.collections) { collection in85 Toggle(isOn: Binding(get: { controller.conversation.collectionIDs.contains(collection.id) },86 set: { on in controller.update { c in if on { c.collectionIDs.append(collection.id) } else { c.collectionIDs.removeAll { $0 == collection.id } } } })) {87 Label(collection.name, systemImage: collection.symbol).font(DS.F.callout)88 }89 }90 }91 group("Agent", symbol: "sparkle") {92 Picker("Agent", selection: bind(\.agentID)) {93 Text("None").tag(Optional<UUID>.none)94 ForEach(app.agents) { Text($0.name).tag(Optional($0.id)) }95 }96 if let agent = controller.agent {97 Text("Tools: \(agent.enabledTools.isEmpty ? "none" : agent.enabledTools.joined(separator: ", ")) · \(agent.approval.title)").font(DS.F.micro).foregroundStyle(DS.C.muted)98 }99 }100 group("Organize", symbol: "folder") {101 TextField("Title", text: bind(\.title)).textFieldStyle(.roundedBorder)102 Picker("Folder", selection: bind(\.folderID)) {103 Text("None").tag(Optional<UUID>.none)104 ForEach(app.folders) { Text($0.name).tag(Optional($0.id)) }105 }106 Toggle("Favorite", isOn: bind(\.isFavorite))107 FlowTags(tags: controller.conversation.tags) { tag in controller.update { $0.tags.removeAll { $0 == tag } } }108 HStack {109 TextField("Add tag", text: $newTag).textFieldStyle(.roundedBorder).onSubmit(addTag)110 Button("Add", action: addTag).buttonStyle(.lcSecondaryCompact).disabled(newTag.trimmingCharacters(in: .whitespaces).isEmpty)111 }112 }113 group("Export", symbol: "square.and.arrow.up") {114 HStack {115 Button("Markdown") { exporting = ExportPayload(document: TextFile(text: controller.exportMarkdown()), name: fileName + ".md", type: .plainText) }116 Button("JSON") { exporting = ExportPayload(document: TextFile(data: controller.exportJSON()), name: fileName + ".json", type: .json) }117 Button("Copy Markdown") { Pasteboard.copy(controller.exportMarkdown()) }118 }119 .buttonStyle(.lcSecondaryCompact)120 Text("\(controller.tree.messages.count) messages · \(controller.tree.branchCount) branch\(controller.tree.branchCount == 1 ? "" : "es")").font(DS.F.micro).foregroundStyle(DS.C.muted)121 }122 }123 .padding(DS.S.md)124 .frame(maxWidth: .infinity, alignment: .leading)125 }126 .frame(maxWidth: .infinity)127 .clipped()128 .background(DS.C.surface.opacity(0.5))129 .fileExporter(isPresented: Binding(get: { exporting != nil }, set: { if !$0 { exporting = nil } }), document: exporting?.document,130 contentType: exporting?.type ?? .plainText, defaultFilename: exporting?.name ?? "Conversation") { _ in exporting = nil }131 }132133 private var fileName: String { controller.conversation.title.replacingOccurrences(of: "/", with: "-") }134 private func addTag() {135 let tag = newTag.trimmingCharacters(in: .whitespaces).lowercased()136 guard !tag.isEmpty else { return }137 controller.update { if !$0.tags.contains(tag) { $0.tags.append(tag) } }138 newTag = ""139 }140141 private func bind<T: Equatable>(_ keyPath: WritableKeyPath<Conversation, T>) -> Binding<T> {142 Binding(get: { controller.conversation[keyPath: keyPath] }, set: { value in controller.update { $0[keyPath: keyPath] = value } })143 }144 /// A manual change to a parameter leaves the preset ("Custom").145 private func custom(_ change: @escaping (inout GenerationSettings) -> Void) {146 controller.update { change(&$0.settings); $0.preset = nil }147 }148 private func settings<T: Equatable>(_ keyPath: WritableKeyPath<GenerationSettings, T>) -> Binding<T> {149 Binding(get: { controller.conversation.settings[keyPath: keyPath] }, set: { value in custom { $0[keyPath: keyPath] = value } })150 }151152 @ViewBuilder private func group<Content: View>(_ title: String, symbol: String, @ViewBuilder content: () -> Content) -> some View {153 VStack(alignment: .leading, spacing: 10) {154 SectionHeader(title, symbol: symbol)155 content()156 }157 .frame(maxWidth: .infinity, alignment: .leading)158 .card(padding: DS.S.md)159 }160 private func slider(_ title: String, value: Binding<Double>, range: ClosedRange<Double>, step: Double, format: String) -> some View {161 VStack(alignment: .leading, spacing: 2) {162 HStack { Text(title).font(DS.F.callout); Spacer(); Text(String(format: format, value.wrappedValue)).font(DS.F.mono(11.5)).foregroundStyle(DS.C.muted) }163 Slider(value: value, in: range, step: step).tint(DS.C.accent).accessibilityLabel(title)164 }165 }166 private func stepper(_ title: String, value: Binding<Int>, range: ClosedRange<Int>, step: Int, zeroLabel: String? = nil) -> some View {167 let upper = max(range.lowerBound, range.upperBound)168 return Stepper(value: value, in: range.lowerBound...upper, step: step) {169 HStack { Text(title).font(DS.F.callout); Spacer(); Text(value.wrappedValue == 0 && zeroLabel != nil ? zeroLabel! : value.wrappedValue.formatted()).font(DS.F.mono(11.5)).foregroundStyle(DS.C.muted) }170 }171 }172}173174struct FlowTags: View {175 let tags: [String]176 let onRemove: (String) -> Void177 var body: some View {178 if !tags.isEmpty {179 ScrollView(.horizontal, showsIndicators: false) {180 HStack(spacing: 6) {181 ForEach(tags, id: \.self) { tag in182 HStack(spacing: 4) {183 Text("#\(tag)").font(DS.F.micro)184 Button { onRemove(tag) } label: { Image(systemName: "xmark").font(.system(size: 8, weight: .bold)) }.buttonStyle(.plain).accessibilityLabel("Remove tag \(tag)")185 }186 .foregroundStyle(DS.C.accent).padding(.horizontal, 8).padding(.vertical, 4).background(DS.C.accent.opacity(0.12), in: Capsule())187 }188 }189 }190 }191 }192}193194/// A plain file for `fileExporter`.195struct TextFile: FileDocument {196 static let readableContentTypes: [UTType] = [.plainText, .json]197 var data: Data198 init(text: String) { data = Data(text.utf8) }199 init(data: Data) { self.data = data }200 init(configuration: ReadConfiguration) throws { data = configuration.file.regularFileContents ?? Data() }201 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) }202}203