Add local file previews to chat and split the Toolbox layout

This commit is contained in:
Mark Gregory
2026-11-16 16:21:32 +00:00
parent 4ebf2b82be
commit 0f4b6b03e4
5 changed files with 107 additions and 15 deletions
+8
View File
@@ -103,6 +103,14 @@ or `Search the web for your query` to use the configured SearXNG endpoint.
When search is unavailable, chat shows a browser search link. Repository When search is unavailable, chat shows a browser search link. Repository
listing can also open the saved Gitea profile on demand. listing can also open the saved Gitea profile on demand.
## Add local files to chat
Use the paperclip beside the composer. Select a UTF-8 text or source file,
a text PDF, or a folder. Review the preview and attach it to your next
message. Folder previews list immediate visible entries. Toolbox shows
server connections on the left and the selected server's tools and results
on the right.
## Build and test ## Build and test
From the project root, run `Scripts/build.sh` to build and open AI Studio. It defaults to Debug. Use `./Scripts/build.sh Release` for a Release build, or add `--no-launch` after the configuration to build without opening the app. Run `Scripts/test.sh` for XCTest, including the local MCP and Ollama management fixture. It requires Python 3 for the fixture and keeps its logs and results in the temporary build directory. From the project root, run `Scripts/build.sh` to build and open AI Studio. It defaults to Debug. Use `./Scripts/build.sh Release` for a Release build, or add `--no-launch` after the configuration to build without opening the app. Run `Scripts/test.sh` for XCTest, including the local MCP and Ollama management fixture. It requires Python 3 for the fixture and keeps its logs and results in the temporary build directory.
+42 -2
View File
@@ -94,6 +94,9 @@ struct ChatView: View {
@State private var showingLibrary = false @State private var showingLibrary = false
@State private var useDocuments = false @State private var useDocuments = false
@State private var filePreview: ChatFilePreview?
@State private var fileError = ""
var body: some View { var body: some View {
NavigationSplitView(columnVisibility: $columns) { NavigationSplitView(columnVisibility: $columns) {
List(visibleChats, selection: $studio.selected) { chat in List(visibleChats, selection: $studio.selected) { chat in
@@ -142,8 +145,25 @@ struct ChatView: View {
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) } .sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) } .sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
.sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) } .sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) }
.sheet(item: $filePreview) { preview in
VStack(alignment: .leading, spacing: 12) {
Text(preview.name).font(.headline)
ScrollView {
Text(preview.text).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
HStack {
Spacer()
Button("Cancel") { filePreview = nil }.keyboardShortcut(.cancelAction)
Button("Attach to Next Message") {
studio.attachToolResult(name: preview.name, output: preview.text)
filePreview = nil
}.keyboardShortcut(.defaultAction)
}
}.padding().frame(width: 560, height: 360)
}
.sheet(isPresented: $showingToolbox) { .sheet(isPresented: $showingToolbox) {
ToolboxSheet(studio: studio).frame(width: 650, height: 620) ToolboxSheet(studio: studio).frame(width: 880, height: 620)
} }
.sheet(isPresented: $showingPromptBuilder) { .sheet(isPresented: $showingPromptBuilder) {
PromptBuilder(customPrompt: $customPrompt) { instructions, global in PromptBuilder(customPrompt: $customPrompt) { instructions, global in
@@ -211,7 +231,7 @@ struct ChatView: View {
} }
.font(.caption) .font(.caption)
} }
let activity = [studio.knowledgeStatus, studio.webStatus, studio.status].filter { !$0.isEmpty } let activity = [fileError, studio.knowledgeStatus, studio.webStatus, studio.status].filter { !$0.isEmpty }
if !activity.isEmpty { if !activity.isEmpty {
Text(activity.joined(separator: " · ")) Text(activity.joined(separator: " · "))
.font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled) .font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled)
@@ -226,6 +246,9 @@ struct ChatView: View {
.background(.background, in: RoundedRectangle(cornerRadius: 8)) .background(.background, in: RoundedRectangle(cornerRadius: 8))
.overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary)) .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary))
HStack { HStack {
Button("Attach Files", systemImage: "paperclip", action: pickLocalFile)
.labelStyle(.iconOnly).buttonStyle(.bordered)
.help("Attach a local file or folder listing").disabled(studio.running)
Button { Button {
showingToolbox = true showingToolbox = true
} label: { } label: {
@@ -266,6 +289,23 @@ struct ChatView: View {
} }
.padding(16) .padding(16)
} }
private func pickLocalFile() {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = true
panel.allowsMultipleSelection = false
panel.prompt = "Preview"
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
Task { @MainActor in
do {
filePreview = try await Task.detached { try ChatFilePreview.read(url) }.value
fileError = ""
} catch { fileError = error.localizedDescription }
}
}
}
private func sendMessage() { private func sendMessage() {
studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking, studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments, failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments,
+27
View File
@@ -395,3 +395,30 @@ enum GiteaRepositoryLookup {
""" """
} }
} }
struct ChatFilePreview: Identifiable, Sendable {
let id = UUID()
let name: String
let text: String
static func read(_ url: URL) throws -> Self {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
let text: String
if try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true {
let entries = try FileManager.default.contentsOfDirectory(
at: url, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles]
).sorted { $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending }
let names = entries.prefix(75).map { $0.lastPathComponent + ($0.hasDirectoryPath ? "/" : "") }
text = "Folder: \(url.lastPathComponent)\n" +
(names.isEmpty ? "(Empty)" : names.joined(separator: "\n")) +
(entries.count > 75 ? "\n[Listing limited to 75 entries]" : "")
} else if url.pathExtension.lowercased() == "pdf" {
text = try LibraryImport.chunks(at: url).prefix(5).joined(separator: "\n\n")
} else {
text = try LocalFilePreview.read(url, limit: 7500)
}
let bounded = text.count > 8000 ? String(text.prefix(7960)) + "\n[Preview truncated]" : text
return Self(name: url.lastPathComponent, text: bounded)
}
}
+14 -13
View File
@@ -230,7 +230,6 @@ struct MCPSettings: View {
@State private var importingConfig = false @State private var importingConfig = false
@State private var configStatus = "" @State private var configStatus = ""
@State private var selected: MCPConnectionID? @State private var selected: MCPConnectionID?
@State private var scrollRequest = UUID()
@State private var tool = "" @State private var tool = ""
@State private var arguments = "{}" @State private var arguments = "{}"
@State private var confirm = false @State private var confirm = false
@@ -241,7 +240,7 @@ struct MCPSettings: View {
} }
var body: some View { var body: some View {
ScrollViewReader { proxy in HSplitView {
Form { Form {
Section("Built-In Tools") { Section("Built-In Tools") {
connectionRow(.web, title: BuiltInWebTools.name, subtitle: "Retrieve pages and search via SearXNG", icon: "globe") { connectionRow(.web, title: BuiltInWebTools.name, subtitle: "Retrieve pages and search via SearXNG", icon: "globe") {
@@ -250,7 +249,7 @@ struct MCPSettings: View {
} }
} }
Section("Custom MCP Servers") { Section("Custom MCP Servers") {
HStack { VStack(alignment: .leading, spacing: 6) {
Button("Import mcp.json…") { importingConfig = true } Button("Import mcp.json…") { importingConfig = true }
Button("Use LM Studio Config") { Button("Use LM Studio Config") {
loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")) loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json"))
@@ -291,6 +290,10 @@ struct MCPSettings: View {
connect: connectManual) connect: connectManual)
} }
} }
}
.formStyle(.grouped)
.frame(minWidth: 300, idealWidth: 340)
Form {
if let selection, let state = studio.mcpConnections[selection], let toolset = state.toolset { if let selection, let state = studio.mcpConnections[selection], let toolset = state.toolset {
Section("Run a Tool") { Section("Run a Tool") {
Picker("Connected server", selection: Binding( Picker("Connected server", selection: Binding(
@@ -327,9 +330,14 @@ struct MCPSettings: View {
} }
} }
} }
.id("mcp-tool-inspector") } else {
ContentUnavailableView("Select a connected server", systemImage: "wrench.and.screwdriver",
description: Text("Connect a server on the left to see and run its tools."))
} }
} }
.formStyle(.grouped)
.frame(minWidth: 320)
}
.formStyle(.grouped) .formStyle(.grouped)
.fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in .fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in
do { loadConfig(try result.get()) } do { loadConfig(try result.get()) }
@@ -348,13 +356,7 @@ struct MCPSettings: View {
} }
selectFirstTool() selectFirstTool()
} }
.onChange(of: selection) { _, value in .onChange(of: selection) { _, _ in selectFirstTool() }
selectFirstTool()
if value != nil { withAnimation { proxy.scrollTo("mcp-tool-inspector", anchor: .bottom) } }
}
.onChange(of: scrollRequest) { _, _ in
withAnimation { proxy.scrollTo("mcp-tool-inspector", anchor: .bottom) }
}
.onChange(of: tool) { _, _ in arguments = "{}" } .onChange(of: tool) { _, _ in arguments = "{}" }
.onChange(of: endpoint) { _, _ in studio.disconnectMCP(.manual) } .onChange(of: endpoint) { _, _ in studio.disconnectMCP(.manual) }
.onChange(of: transport) { _, _ in studio.disconnectMCP(.manual) } .onChange(of: transport) { _, _ in studio.disconnectMCP(.manual) }
@@ -371,7 +373,6 @@ struct MCPSettings: View {
} message: { } message: {
Text("Send these arguments to \(selection.flatMap { studio.mcpConnections[$0]?.toolset?.name } ?? "the server"):\n\(arguments.prefix(800))") Text("Send these arguments to \(selection.flatMap { studio.mcpConnections[$0]?.toolset?.name } ?? "the server"):\n\(arguments.prefix(800))")
} }
}
} }
private func connectionRow( private func connectionRow(
@@ -388,7 +389,7 @@ struct MCPSettings: View {
Button("Cancel") { studio.cancelMCP(id) } Button("Cancel") { studio.cancelMCP(id) }
} else if let toolset = state?.toolset { } else if let toolset = state?.toolset {
Text("\(toolset.tools.count) tools · Connected").font(.caption).foregroundStyle(.green) Text("\(toolset.tools.count) tools · Connected").font(.caption).foregroundStyle(.green)
Button("Tools") { selected = id; scrollRequest = UUID() } Button("Tools") { selected = id }
Button("Disconnect") { studio.disconnectMCP(id) } Button("Disconnect") { studio.disconnectMCP(id) }
} else { } else {
Button(local ? "Start & Connect" : "Connect") { Button(local ? "Start & Connect" : "Connect") {
+16
View File
@@ -818,3 +818,19 @@ final class ConnectedChatTests: XCTestCase {
XCTAssertFalse(result.contains("Gitea returned no repository entries.")) XCTAssertFalse(result.contains("Gitea returned no repository entries."))
} }
} }
final class ChatFilePreviewTests: XCTestCase {
func testPreviewsSelectedTextAndListsFolderWithoutReadingChildren() throws {
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: folder) }
let file = folder.appending(path: "main.swift")
try Data("let result = 42".utf8).write(to: file)
try Data("hidden contents".utf8).write(to: folder.appending(path: ".hidden"))
XCTAssertEqual(try ChatFilePreview.read(file).text, "let result = 42")
let listing = try ChatFilePreview.read(folder).text
XCTAssertTrue(listing.contains("main.swift"))
XCTAssertFalse(listing.contains("let result"))
XCTAssertFalse(listing.contains(".hidden"))
}
}