new features

This commit is contained in:
Mark Gregory
2026-11-17 16:39:43 +00:00
parent d1a1b454f6
commit 713d021454
13 changed files with 1100 additions and 141 deletions
+452 -62
View File
@@ -111,16 +111,77 @@ struct ChatView: View {
@State private var renaming = false
@State private var newTitle = ""
private var backendName: String { compatibleEnabled ? "Compatible API" : "Ollama" }
private var activeEndpoint: String { compatibleEnabled ? compatibleEndpoint : endpoint }
private var activeModel: String { compatibleEnabled ? compatibleModel : model }
@AppStorage(ChatModelChoice.settingsKey) private var chatModelData = Data()
@AppStorage("mlxRegisteredPaths") private var registeredMLX = Data()
@AppStorage("managedMLXModels") private var managedMLX = Data()
private var defaultChatModel: ChatModelChoice {
if mlxOnly { return ChatModelChoice(backend: .mlx, model: mlxPath) }
if compatibleEnabled { return ChatModelChoice(backend: .compatible, model: compatibleModel) }
return ChatModelChoice(backend: .ollama, model: model)
}
private var chatChoices: [UUID: ChatModelChoice] { ChatModelChoice.read(chatModelData) }
private var chatModel: ChatModelChoice { modelForChat(studio.selected) }
private var backendName: String { chatModel.backend.rawValue }
private func modelForChat(_ id: UUID?) -> ChatModelChoice {
id.flatMap { chatChoices[$0] } ?? defaultChatModel
}
private func setChatModel(_ choice: ChatModelChoice?, for id: UUID?) {
var target = id
if target == nil && choice != nil {
studio.newChat()
target = studio.selected
}
guard let target else { return }
var choices = chatChoices
choices[target] = choice
if let data = try? JSONEncoder().encode(choices) { chatModelData = data }
}
private var mlxChoices: [String] {
let registered = (try? JSONDecoder().decode([String].self, from: registeredMLX)) ?? []
let managed = (try? JSONDecoder().decode([CatalogModel].self, from: managedMLX)) ?? []
let paths = (managed + CatalogModel.all).map { $0.localFolder.path } + registered + [mlxPath]
let installed = paths.filter { !$0.isEmpty && MLXLibrary.isModel(at: URL(fileURLWithPath: $0)) }
return Array(Set(installed)).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
}
private func modelPicker(for id: UUID?, running: Bool) -> some View {
ChatModelPicker(studio: studio, choice: modelForChat(id), defaultChoice: defaultChatModel,
hasOverride: id.flatMap { chatChoices[$0] } != nil,
endpoint: endpoint, ollamaDefault: model, mlxPaths: { mlxChoices },
compatibleEndpoint: compatibleEndpoint, compatibleDefault: compatibleModel,
select: { setChatModel($0, for: id) })
.disabled(running)
}
private var visibleChats: [Conversation] {
search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? studio.conversations : studio.searchConversations(search)
}
@State private var showingLibrary = false
@State private var useDocuments = false
@AppStorage("documentExcerptOptOuts") private var documentExcerptOptOuts = Data()
private var documentOptOuts: Set<UUID> {
(try? JSONDecoder().decode(Set<UUID>.self, from: documentExcerptOptOuts)) ?? []
}
private func includesDocuments(_ target: StudioModel) -> Bool {
guard let id = target.selected else { return false }
return !target.documents.isEmpty && !documentOptOuts.contains(id)
}
private var documentExcerptsEnabled: Binding<Bool> {
Binding(get: { includesDocuments(studio) }, set: { enabled in
guard let id = studio.selected else { return }
var next = documentOptOuts
if enabled { next.remove(id) } else { next.insert(id) }
if let data = try? JSONEncoder().encode(next) { documentExcerptOptOuts = data }
})
}
@State private var pendingWrite: ChatFileRequest.Write?
@State private var writeDestination: URL?
@@ -220,7 +281,7 @@ struct ChatView: View {
Spacer()
Button("Cancel") { filePreview = nil }.keyboardShortcut(.cancelAction)
Button("Attach to Next Message") {
studio.attachToolResult(name: preview.name, output: preview.text)
studio.attachToolResult(name: preview.name, output: preview.text, isDocument: true)
filePreview = nil
}.keyboardShortcut(.defaultAction)
}
@@ -247,9 +308,9 @@ struct ChatView: View {
compatibleEnabled = defaults.bool(forKey: "compatibleEnabled")
}
.onChange(of: studio.selected) { old, _ in
useDocuments = false
if old != nil {
studio.activeStack = nil
studio.activeRemoteStack = .automatic
studio.activeSkill = nil
studio.activeContext = nil
studio.activeWebClip = nil
@@ -277,7 +338,10 @@ struct ChatView: View {
Text(destination.path)
}
.alert("Delete Chat?", isPresented: $confirmDelete, presenting: chatToDelete) { chat in
Button("Delete", role: .destructive) { studio.deleteChat(chat.id) }
Button("Delete", role: .destructive) {
studio.deleteChat(chat.id)
if !studio.conversations.contains(where: { $0.id == chat.id }) { setChatModel(nil, for: chat.id) }
}
Button("Cancel", role: .cancel) {}
} message: { chat in
Text("“\(chat.title)” and its messages will be permanently deleted.")
@@ -303,6 +367,7 @@ struct ChatView: View {
.padding(10)
.disabled(splitStudio.running)
.onChange(of: comparisonChat) { _, value in
if splitStudio.selected != value { splitStudio.activeRemoteStack = .automatic }
splitStudio.selected = value
splitStudio.prompt = ""
}
@@ -313,18 +378,21 @@ struct ChatView: View {
LazyVStack(alignment: .leading, spacing: 12) {
ForEach(splitStudio.messages) { MessageView(message: $0) }
if let partial = splitStudio.partial { MessageView(message: partial, streaming: true) }
if showDebugOutput { ChatDebugOutput(studio: splitStudio) }
}.padding(12)
}
.font(chatFont.font(size: chatSize))
Divider()
VStack(alignment: .leading, spacing: 6) {
let feedback = [showDebugOutput ? splitStudio.knowledgeStatus : "", splitStudio.webStatus, splitStudio.status]
let feedback = [showDebugOutput ? "" : splitStudio.webStatus, splitStudio.status]
.filter { !$0.isEmpty }.joined(separator: " · ")
if !feedback.isEmpty { Text(feedback).font(.caption).foregroundStyle(.secondary) }
ChatComposerInput(text: $splitStudio.prompt, canSend: !splitStudio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendSplitMessage)
.frame(height: 54)
HStack {
resourceMenu(for: splitStudio)
modelPicker(for: splitStudio.selected, running: splitStudio.running)
if let role = splitStudio.agentStage {
Label(role.name, systemImage: "person.2").font(.caption)
}
@@ -355,6 +423,7 @@ struct ChatView: View {
LazyVStack(alignment: .leading, spacing: 18) {
ForEach(studio.messages) { MessageView(message: $0) }
if let partial = studio.partial { MessageView(message: partial, streaming: true) }
if showDebugOutput { ChatDebugOutput(studio: studio) }
Color.clear.frame(height: 1).id("end")
}
.frame(maxWidth: 800)
@@ -364,57 +433,36 @@ struct ChatView: View {
.font(chatFont.font(size: chatSize))
.onChange(of: studio.messages.count, initial: true) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
.onChange(of: studio.partial) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
.onChange(of: showDebugOutput) { _, enabled in
if enabled { proxy.scrollTo("end", anchor: .bottom) }
}
}
}
private var composer: some View {
VStack(alignment: .leading, spacing: 8) {
if !studio.documents.isEmpty {
Toggle(mlxOnly ? "Include matching document excerpts" :
"Send matching document excerpts to \(backendName)", isOn: $useDocuments)
Toggle(chatModel.backend == .mlx ? "Include matching document excerpts" :
"Send matching document excerpts to \(backendName)", isOn: documentExcerptsEnabled)
.font(.caption)
.disabled(studio.running)
}
if let attachment = studio.toolAttachment {
HStack {
Label("Attach \(attachment.name) result to next message", systemImage: "paperclip")
if !mlxOnly { Text("Sent to \(backendName)").foregroundStyle(.secondary) }
if chatModel.backend != .mlx { Text("Sent to \(backendName)").foregroundStyle(.secondary) }
Spacer()
Button("Remove", systemImage: "xmark.circle") { studio.removeToolAttachment() }
}
.font(.caption)
}
let activity = [fileError, showDebugOutput ? studio.knowledgeStatus : "", studio.webStatus, studio.status].filter { !$0.isEmpty }
let activity = [fileError, showDebugOutput ? "" : studio.webStatus, studio.status].filter { !$0.isEmpty }
if !activity.isEmpty {
Text(activity.joined(separator: " · "))
.font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled)
}
if showDebugOutput, !studio.knowledgeSources.isEmpty {
DisclosureGroup("Knowledge Sources (\(studio.knowledgeSources.count))") {
ScrollView {
Text(studio.knowledgeSources.joined(separator: "\n"))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxHeight: 80)
}
.font(.caption)
}
if showDebugOutput, !studio.webDiagnostics.isEmpty || !studio.webStatus.isEmpty {
let diagnostics = studio.webDiagnostics.isEmpty
? [studio.webStatus]
: studio.webDiagnostics
ScrollView {
Text(diagnostics.joined(separator: "\n"))
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxHeight: 96)
.accessibilityLabel("Web lookup debug output")
}
if let link = studio.webSearchLink {
Link("Open search in browser", destination: link).font(.caption)
Link("Open in Browser", destination: link).font(.caption)
}
ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage)
@@ -452,18 +500,14 @@ struct ChatView: View {
}
.buttonStyle(.bordered)
.help(studio.activeToolsets.map { $0.toolset.name }.joined(separator: ", "))
if studio.activeStack != nil || studio.activeSkill != nil ||
studio.activeContext != nil || studio.activeWebClip != nil {
Button("Resources", systemImage: "square.stack") { showingWorkspace = true }
.buttonStyle(.borderless)
}
Label(mlxOnly && !mlxPath.isEmpty ? URL(fileURLWithPath: mlxPath).lastPathComponent : activeModel.isEmpty || mlxOnly ? "Choose a model" : activeModel,
systemImage: mlxOnly ? "cpu" : "server.rack")
.font(.caption).foregroundStyle(.secondary).lineLimit(1)
.help(mlxOnly ? "On-device MLX" : "\(backendName) · \(activeEndpoint)")
resourceMenu(for: studio)
Spacer()
if (!mlxOnly && !compatibleEnabled) || (mlxOnly && MLXThinking.supports(mlxPath)) {
let modes: [Thinking] = mlxOnly ? [.automatic, .off, .on] : Thinking.allCases
}
HStack(spacing: 10) {
modelPicker(for: studio.selected, running: studio.running)
Spacer()
if chatModel.backend == .ollama || (chatModel.backend == .mlx && MLXThinking.supports(chatModel.model)) {
let modes: [Thinking] = chatModel.backend == .mlx ? [.automatic, .off, .on] : Thinking.allCases
Picker("Thinking", selection: Binding(
get: { modes.contains(thinking) ? thinking : .automatic },
set: { thinking = $0 }
@@ -510,13 +554,16 @@ struct ChatView: View {
}
}
private func resourceMenu(for target: StudioModel) -> some View {
ChatResourcesMenu(target: target, stacks: studio.knowledgeStacks, snippets: studio.snippets,
openWorkspace: { showingWorkspace = true })
}
private func sendSplitMessage() {
guard splitStudio.selected != nil, splitStudio.selected != studio.selected else { return }
splitStudio.copyInferenceCredentials(from: studio)
splitStudio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: false,
instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings), agents: selectedAgents)
try? splitStudio.refreshWorkspace()
send(splitStudio, choice: modelForChat(splitStudio.selected), useDocuments: includesDocuments(splitStudio), allowAgentTools: false)
}
private func sendMessage() {
@@ -534,12 +581,238 @@ struct ChatView: View {
} catch { fileError = error.localizedDescription }
return
}
studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments,
instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings), agents: selectedAgents, agentTools: agentMCPEnabled)
send(studio, choice: chatModel, useDocuments: includesDocuments(studio), allowAgentTools: agentMCPEnabled)
}
private func send(_ target: StudioModel, choice: ChatModelChoice, useDocuments: Bool, allowAgentTools: Bool) {
target.send(endpoint: choice.backend == .compatible ? compatibleEndpoint : endpoint,
model: choice.model, mlxPath: choice.backend == .mlx ? choice.model : mlxPath,
thinking: choice.thinkingMode(thinking), failover: failover,
mlxOnly: choice.backend == .mlx, compatible: choice.backend == .compatible,
recall: recall, useDocuments: useDocuments, instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings), agents: selectedAgents, agentTools: allowAgentTools)
}
}
private struct ChatDebugOutput: View {
@ObservedObject var studio: StudioModel
private var sections: [(title: String, lines: [String])] {
[
("Web retrieval", [studio.webStatus] + studio.webDiagnostics),
("Knowledge base", [studio.knowledgeStatus] + studio.knowledgeSources),
("Agent run", studio.agentSteps)
].compactMap { title, lines in
let entries = lines.filter { !$0.isEmpty }
return entries.isEmpty ? nil : (title, entries)
}
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Label("Debug Output", systemImage: "ladybug")
.font(.caption.weight(.semibold))
.accessibilityAddTraits(.isHeader)
let diagnostics = sections
if diagnostics.isEmpty {
Text("Web, knowledge base, and agent diagnostics appear here when available.")
.font(.caption).foregroundStyle(.secondary)
}
ForEach(diagnostics.indices, id: \.self) { index in
let section = diagnostics[index]
VStack(alignment: .leading, spacing: 3) {
Text(section.title).font(.caption.weight(.semibold))
Text(section.lines.joined(separator: "\n"))
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
}
}
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.45), in: RoundedRectangle(cornerRadius: 10))
.accessibilityElement(children: .contain)
}
}
private struct ChatResourcesMenu: View {
@ObservedObject var target: StudioModel
let stacks: [Conversation]
let snippets: [WorkspaceSnippet]
let openWorkspace: () -> Void
private var count: Int {
let local = [target.activeStack, target.activeSkill, target.activeContext, target.activeWebClip].compactMap { $0 }.count
if case .server = target.activeRemoteStack { return local + 1 }
return local
}
var body: some View {
Menu {
Menu("Knowledge Stacks") {
Picker("Knowledge Stack", selection: $target.activeStack) {
Text("None").tag(UUID?.none)
ForEach(stacks) { Text($0.title).tag(Optional($0.id)) }
}
}
Menu("Remote Stacks") { RemoteStackPicker(studio: target, label: "Remote Stack") }
snippetMenu("Skills", kind: .skill, selection: $target.activeSkill)
snippetMenu("Contexts", kind: .context, selection: $target.activeContext)
Menu("Prompt Library") {
let prompts = snippets.filter { $0.kind == .prompt }
if prompts.isEmpty { Text("No saved prompts") }
ForEach(prompts) { prompt in
Button(prompt.title) {
if target.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
target.prompt = prompt.content
} else {
target.prompt += "\n\n" + prompt.content
}
}
}
}
snippetMenu("Web Clips", kind: .webClip, selection: $target.activeWebClip)
Divider()
Button("Open Workspace…", action: openWorkspace)
} label: {
Label(count == 0 ? "Resources" : "Resources \(count)", systemImage: "square.stack")
}
.menuStyle(.borderlessButton)
.fixedSize()
.disabled(target.running)
.help("Use saved workspace resources in this conversation")
}
private func snippetMenu(_ title: String, kind: WorkspaceSnippet.Kind, selection: Binding<UUID?>) -> some View {
Menu(title) {
Picker(kind.rawValue, selection: selection) {
Text("None").tag(UUID?.none)
ForEach(snippets.filter { $0.kind == kind }) { Text($0.title).tag(Optional($0.id)) }
}
}
}
}
private struct ChatModelPicker: View {
@ObservedObject var studio: StudioModel
let choice: ChatModelChoice
let defaultChoice: ChatModelChoice
let hasOverride: Bool
let endpoint: String
let ollamaDefault: String
let mlxPaths: () -> [String]
let compatibleEndpoint: String
let compatibleDefault: String
let select: (ChatModelChoice?) -> Void
@State private var showing = false
@State private var compatibleModels: [String] = []
@State private var compatibleStatus = ""
@State private var loadingCompatible = false
var body: some View {
Button {
showing.toggle()
} label: {
Label(choice.displayName, systemImage: choice.backend == .mlx ? "cpu" : "server.rack")
.lineLimit(1)
}
.buttonStyle(.bordered)
.accessibilityLabel("Chat model: " + choice.displayName)
.help("Switch models for this conversation")
.popover(isPresented: $showing) {
Form {
Section("Model for This Chat") {
Button {
choose(nil)
} label: {
optionLabel("Use Default · " + defaultChoice.displayName, selected: !hasOverride)
}
}
Section("Ollama") {
let installed = studio.modelListEndpoint == endpoint ? studio.models.map(\.name) : []
ForEach(names(installed + [ollamaDefault]), id: \.self) { name in
modelButton(.ollama, name)
}
Button("Refresh Ollama Models") { studio.refresh(endpoint: endpoint) }.disabled(studio.managing)
if studio.managing {
ProgressView().controlSize(.small)
} else if installed.isEmpty && !studio.modelStatus.isEmpty {
Text(studio.modelStatus).font(.caption).foregroundStyle(.secondary)
}
}
let installedMLX = mlxPaths()
if !installedMLX.isEmpty {
Section("MLX") {
ForEach(installedMLX, id: \.self) { path in
modelButton(.mlx, path).help(path)
}
}
}
Section("Compatible API") {
ForEach(names(compatibleModels + [compatibleDefault]), id: \.self) { model in
modelButton(.compatible, model)
}
Button("Refresh Compatible Models") { Task { await refreshCompatible() } }.disabled(loadingCompatible)
if loadingCompatible { ProgressView().controlSize(.small) }
if !compatibleStatus.isEmpty {
Text(compatibleStatus).font(.caption).foregroundStyle(.secondary)
}
}
}
.formStyle(.grouped)
.frame(width: 340, height: 420)
.task {
if studio.modelListEndpoint != endpoint { studio.refresh(endpoint: endpoint) }
}
.onChange(of: compatibleEndpoint) {
compatibleModels = []
compatibleStatus = ""
}
}
}
private func names(_ values: [String]) -> [String] {
Array(Set(values.filter { !$0.isEmpty })).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
}
private func choose(_ model: ChatModelChoice?) {
select(model)
showing = false
}
private func modelButton(_ backend: ChatModelChoice.Backend, _ name: String) -> some View {
let model = ChatModelChoice(backend: backend, model: name)
return Button { choose(model) } label: {
optionLabel(model.displayName, selected: hasOverride && choice == model)
}
}
private func optionLabel(_ title: String, selected: Bool) -> some View {
HStack {
Text(title).lineLimit(1)
Spacer()
if selected { Image(systemName: "checkmark").accessibilityLabel("Selected") }
}
}
private func refreshCompatible() async {
let endpoint = compatibleEndpoint
loadingCompatible = true
compatibleStatus = ""
defer { loadingCompatible = false }
do {
let models = try await studio.compatibleClient(endpoint: endpoint).models()
if endpoint == compatibleEndpoint {
compatibleModels = models
if models.isEmpty { compatibleStatus = "No models reported." }
}
} catch {
if endpoint == compatibleEndpoint { compatibleStatus = error.localizedDescription }
}
}
}
struct MessageView: View {
@@ -555,6 +828,16 @@ struct MessageView: View {
@AppStorage("expandChatThinking") private var expandThinking = false
@State private var thinkingExpanded = false
@State private var webSourcesExpanded = false
private var webSourcesLabel: String {
let kinds = Set(message.webSources.map(\.kind))
if kinds == [.page] { return "Web pages" }
if kinds == [.searchSnippet] { return "Search snippets" }
if kinds == [.savedClip] { return "Saved web clips" }
return "Web sources"
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
@@ -592,6 +875,33 @@ struct MessageView: View {
Text(message.content).textSelection(.enabled)
}
}
ForEach(message.documentNames, id: \.self) { name in
Label(name, systemImage: "paperclip")
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
.accessibilityLabel("Attached document: " + name)
}
if !message.webSources.isEmpty {
DisclosureGroup(isExpanded: $webSourcesExpanded) {
VStack(alignment: .leading, spacing: 6) {
ForEach(message.webSources) { source in
if let url = try? WebClipCapture.url(source.url.absoluteString) {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Link(source.title.isEmpty ? url.absoluteString : source.title, destination: url)
Text(source.kind.rawValue).foregroundStyle(.secondary)
}
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 5)
} label: {
Label("\(webSourcesLabel) (\(message.webSources.count))", systemImage: "globe")
.font(.caption.weight(.semibold))
.foregroundStyle(Color.accentColor)
}
.font(.caption)
}
if message.content.isEmpty && message.thinking.isEmpty { ProgressView().controlSize(.small) }
}
.frame(maxWidth: .infinity, alignment: .leading)
@@ -766,7 +1076,7 @@ struct DocumentLibraryView: View {
var body: some View {
VStack(alignment: .leading, spacing: 14) {
Text("Conversation Documents").font(.title2.bold())
Text("Import PDF, text, Markdown, or CSV. Enable excerpts in the composer to use matching passages.")
Text("Import PDF, text, Markdown, or CSV. AI Studio includes excerpts when you send a message. Use the composer toggle to turn this off.")
.foregroundStyle(.secondary)
List(studio.documents) { document in
HStack {
@@ -1579,6 +1889,62 @@ struct WorkspaceResourcesView: View {
}
}
private struct RemoteStackPicker: View {
@ObservedObject var studio: StudioModel
let label: String
var body: some View {
Picker(label, selection: $studio.activeRemoteStack) {
Text("Automatic").tag(RemoteStackChoice.automatic)
Text("Off").tag(RemoteStackChoice.off)
ForEach(studio.remoteKnowledgeStacks) { stack in
Text(stack.name).tag(RemoteStackChoice.server(stack.id))
}
if case .server(let id) = studio.activeRemoteStack,
!studio.remoteKnowledgeStacks.contains(where: { $0.id == id }) {
Text("Selected stack disconnected").tag(RemoteStackChoice.server(id))
}
}
}
}
private struct RemoteStackInventory: View {
@Environment(\.dismiss) private var dismiss
let stack: RemoteKnowledgeStack
@State private var sources: [String]?
@State private var search = ""
@State private var error = ""
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text(stack.name).font(.headline)
Spacer()
Button("Done") { dismiss() }.keyboardShortcut(.cancelAction)
}
if let sources {
Text("\(sources.count.formatted()) indexed source paths").foregroundStyle(.secondary)
TextField("Filter paths", text: $search)
List(sources.filter { search.isEmpty || $0.localizedCaseInsensitiveContains(search) }, id: \.self) { path in
Text(path).textSelection(.enabled)
}
} else if !error.isEmpty {
Text(error).foregroundStyle(.secondary).textSelection(.enabled)
Spacer()
} else {
ProgressView("Loading indexed sources…")
Spacer()
}
}
.padding(16)
.frame(width: 566, height: 410)
.task {
do { sources = try await KnowledgeInventory.sources(client: stack.client) }
catch { if !Task.isCancelled { self.error = error.localizedDescription } }
}
}
}
struct KnowledgeStacksView: View {
@ObservedObject var studio: StudioModel
@State private var selected: UUID?
@@ -1588,10 +1954,11 @@ struct KnowledgeStacksView: View {
@State private var importing = false
@State private var busy = false
@State private var removing = false
@State private var inventory: RemoteKnowledgeStack?
var body: some View {
Form {
Section("Knowledge Stacks") {
Section("Local Stacks") {
HStack {
TextField("New stack name", text: $name, prompt: Text("Enter a name for the stack"))
.labelsHidden()
@@ -1635,8 +2002,27 @@ struct KnowledgeStacksView: View {
}
}
}
Section("Remote Stacks") {
RemoteStackPicker(studio: studio, label: "Use in this chat").disabled(studio.running)
if studio.remoteKnowledgeStacks.isEmpty {
Text("Connect a knowledge server in Settings → Toolbox to use its index here.")
.foregroundStyle(.secondary)
}
ForEach(studio.remoteKnowledgeStacks) { stack in
HStack {
Label(stack.name, systemImage: "externaldrive.connected.to.line.below")
Spacer()
if stack.supportsInventory {
Button("Browse Sources…") { inventory = stack }
} else {
Text("Search available").foregroundStyle(.secondary)
}
}
}
}
}
.formStyle(.grouped)
.sheet(item: $inventory) { RemoteStackInventory(stack: $0) }
.onAppear { selected = studio.activeStack; refresh() }
.onChange(of: selected) { _, _ in refresh() }
.fileImporter(isPresented: $importing, allowedContentTypes: [
@@ -2372,7 +2758,9 @@ struct WebToolsView: View {
section = .retrieve
retrieve(result.url.absoluteString)
}.disabled(operation != nil)
Button("Attach Result") { attach(result.title, result.reference) }
Button("Attach Result") {
attach(result.title, result.reference, source: .init(url: result.url, title: result.title, kind: .searchSnippet))
}
.disabled(studio.running || operation != nil)
}
}
@@ -2389,7 +2777,9 @@ struct WebToolsView: View {
ScrollView {
Text(page.text).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
}.frame(height: 145)
Button("Attach Page to Chat") { attach("Web page", page.reference) }
Button("Attach Page to Chat") {
attach("Web page", page.reference, source: .init(url: page.url, title: page.title, kind: .page))
}
.disabled(studio.running || operation != nil)
}
}
@@ -2426,8 +2816,8 @@ struct WebToolsView: View {
}
}
private func attach(_ title: String, _ reference: String) {
studio.attachToolResult(name: title, output: reference)
private func attach(_ title: String, _ reference: String, source: WebReplySource) {
studio.attachToolResult(name: title, output: reference, webSource: source)
done()
}
}