diff --git a/README.md b/README.md index c4a4bf3..64fd40e 100644 --- a/README.md +++ b/README.md @@ -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 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 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. diff --git a/Sources/AIStudioApp.swift b/Sources/AIStudioApp.swift index 718a3b0..bed191f 100644 --- a/Sources/AIStudioApp.swift +++ b/Sources/AIStudioApp.swift @@ -94,6 +94,9 @@ struct ChatView: View { @State private var showingLibrary = false @State private var useDocuments = false + @State private var filePreview: ChatFilePreview? + @State private var fileError = "" + var body: some View { NavigationSplitView(columnVisibility: $columns) { List(visibleChats, selection: $studio.selected) { chat in @@ -142,8 +145,25 @@ struct ChatView: View { .sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) } .sheet(isPresented: $showingPerformance) { PerformanceDashboard(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) { - ToolboxSheet(studio: studio).frame(width: 650, height: 620) + ToolboxSheet(studio: studio).frame(width: 880, height: 620) } .sheet(isPresented: $showingPromptBuilder) { PromptBuilder(customPrompt: $customPrompt) { instructions, global in @@ -211,7 +231,7 @@ struct ChatView: View { } .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 { Text(activity.joined(separator: " · ")) .font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled) @@ -226,6 +246,9 @@ struct ChatView: View { .background(.background, in: RoundedRectangle(cornerRadius: 8)) .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary)) HStack { + Button("Attach Files", systemImage: "paperclip", action: pickLocalFile) + .labelStyle(.iconOnly).buttonStyle(.bordered) + .help("Attach a local file or folder listing").disabled(studio.running) Button { showingToolbox = true } label: { @@ -266,6 +289,23 @@ struct ChatView: View { } .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() { studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking, failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments, diff --git a/Sources/Library.swift b/Sources/Library.swift index f0ead6e..ae64e07 100644 --- a/Sources/Library.swift +++ b/Sources/Library.swift @@ -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) + } +} diff --git a/Sources/MCP.swift b/Sources/MCP.swift index b64da5b..dafd0ad 100644 --- a/Sources/MCP.swift +++ b/Sources/MCP.swift @@ -230,7 +230,6 @@ struct MCPSettings: View { @State private var importingConfig = false @State private var configStatus = "" @State private var selected: MCPConnectionID? - @State private var scrollRequest = UUID() @State private var tool = "" @State private var arguments = "{}" @State private var confirm = false @@ -241,7 +240,7 @@ struct MCPSettings: View { } var body: some View { - ScrollViewReader { proxy in + HSplitView { Form { Section("Built-In Tools") { 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") { - HStack { + VStack(alignment: .leading, spacing: 6) { Button("Import mcp.json…") { importingConfig = true } Button("Use LM Studio Config") { loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")) @@ -291,6 +290,10 @@ struct MCPSettings: View { connect: connectManual) } } + } + .formStyle(.grouped) + .frame(minWidth: 300, idealWidth: 340) + Form { if let selection, let state = studio.mcpConnections[selection], let toolset = state.toolset { Section("Run a Tool") { 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) .fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in do { loadConfig(try result.get()) } @@ -348,13 +356,7 @@ struct MCPSettings: View { } selectFirstTool() } - .onChange(of: selection) { _, value in - 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: selection) { _, _ in selectFirstTool() } .onChange(of: tool) { _, _ in arguments = "{}" } .onChange(of: endpoint) { _, _ in studio.disconnectMCP(.manual) } .onChange(of: transport) { _, _ in studio.disconnectMCP(.manual) } @@ -371,7 +373,6 @@ struct MCPSettings: View { } message: { Text("Send these arguments to \(selection.flatMap { studio.mcpConnections[$0]?.toolset?.name } ?? "the server"):\n\(arguments.prefix(800))") } - } } private func connectionRow( @@ -388,7 +389,7 @@ struct MCPSettings: View { Button("Cancel") { studio.cancelMCP(id) } } else if let toolset = state?.toolset { 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) } } else { Button(local ? "Start & Connect" : "Connect") { diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index 60ca55f..6f66597 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -818,3 +818,19 @@ final class ConnectedChatTests: XCTestCase { 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")) + } +}