From 4ebf2b82be743f71444b3fe27065eff8acfe47d5 Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Mon, 16 Nov 2026 16:18:39 +0000 Subject: [PATCH] Use saved web and Gitea access from a fresh chat --- README.md | 11 ++++++----- Sources/AIStudioApp.swift | 3 +++ Sources/Library.swift | 32 +++++++++++++++++++++++++++++--- Sources/StudioModel.swift | 16 ++++++++++++---- Tests/Fixtures/server.py | 7 +++++++ Tests/StudioTests.swift | 25 ++++++++++++++++++++++--- 6 files changed, 79 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index ad3e6a0..c4a4bf3 100644 --- a/README.md +++ b/README.md @@ -97,14 +97,15 @@ running page scripts. It keeps the final source URL. Attach an individual result or a retrieved page to your next message after reviewing it. Choose **Connect** on **Built-In Web** in the **MCP Servers** tab to access the same operations through Toolbox. Web and custom MCP servers can stay -connected at the same time. With Built-In Web active, chat retrieves -up to two explicitly typed HTTP(S) URLs and adds their source text to the -request. Use `/search your query` or `Search the web for your query` to search -from chat using the configured SearXNG endpoint. +connected at the same time. Chat retrieves up to two explicitly typed +HTTP(S) URLs without requiring a Toolbox connection. Use `/search your query` +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. ## Build and test -From the project root, run `Scripts/build.sh` to build and open AI Studio. It defaults to Debug. Use `./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. For opt-in live provider checks, use installed models or select a catalog download: diff --git a/Sources/AIStudioApp.swift b/Sources/AIStudioApp.swift index 571baa8..718a3b0 100644 --- a/Sources/AIStudioApp.swift +++ b/Sources/AIStudioApp.swift @@ -216,6 +216,9 @@ struct ChatView: View { Text(activity.joined(separator: " · ")) .font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled) } + if let link = studio.webSearchLink { + Link("Open search in browser", destination: link).font(.caption) + } ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck, autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage) .frame(height: 62) diff --git a/Sources/Library.swift b/Sources/Library.swift index 7f71f3a..f0ead6e 100644 --- a/Sources/Library.swift +++ b/Sources/Library.swift @@ -243,7 +243,8 @@ enum ChatWebLookup { init?(message: String) { let text = message.trimmingCharacters(in: .whitespacesAndNewlines) - let prefixes = ["/search ", "search the web for ", "search online for "] + let prefixes = ["/search ", "can you search the web for ", "please search the web for ", + "search the web for ", "search online for ", "look up online ", "web search for "] if let prefix = prefixes.first(where: { text.lowercased().hasPrefix($0) }) { let query = String(text.dropFirst(prefix.count)).trimmingCharacters(in: .whitespacesAndNewlines) if !query.isEmpty { self = .search(query); return } @@ -263,9 +264,10 @@ enum ChatWebLookup { self = .pages(urls) } - func resolve(searchEndpoint: String) async throws -> (reference: String, status: String) { + func resolve(searchEndpoint: String) async throws -> (reference: String, status: String, browserFallback: URL?) { var references: [String] = [] var failures: [String] = [] + var browserFallback: URL? switch self { case .pages(let urls): for url in urls { @@ -289,6 +291,11 @@ enum ChatWebLookup { try Task.checkCancellation() failures.append(error.localizedDescription) } + if references.isEmpty { + var browser = URLComponents(string: "https://duckduckgo.com/") + browser?.queryItems = [.init(name: "q", value: query)] + browserFallback = browser?.url + } } let status = failures.isEmpty ? "Retrieved \(references.count) web source(s)." : failures.joined(separator: " ") let notice = failures.isEmpty ? "" : "\n\nWeb lookup errors: \(failures.joined(separator: " "))" @@ -297,7 +304,7 @@ enum ChatWebLookup { \(references.joined(separator: "\n\n"))\(notice) """ - return (reference, status) + return (reference, status, browserFallback) } } @@ -334,6 +341,25 @@ enum GiteaRepositoryLookup { return repository && inventory && account } + static func configuredClient(pathOverride: String? = nil) async throws -> any MCPToolClient { + let saved = pathOverride ?? UserDefaults.standard.string(forKey: "mcpConfigPath") ?? "" + let path = saved.isEmpty + ? FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json") + : URL(fileURLWithPath: saved) + guard FileManager.default.fileExists(atPath: path.path) else { + throw StudioError("Import your Gitea MCP configuration in Toolbox → MCP Servers.") + } + let profiles = try MCPServerConfiguration.File.read(path).mcpServers + guard let profile = profiles["absdev-gitea"] ?? profiles["gitea"] else { + throw StudioError("Connect your Gitea server in Toolbox → MCP Servers.") + } + let client = try profile.makeClient() + guard try await client.listTools().contains(where: { $0.name == "list_repositories" }) else { + throw StudioError("The configured Gitea server does not expose list_repositories.") + } + return client + } + static func references(client: any MCPToolClient) async throws -> String { let data = try await client.callTool("list_repositories", argumentsJSON: Data("{}".utf8)) guard let result = try JSONSerialization.jsonObject(with: data) as? [String: Any], diff --git a/Sources/StudioModel.swift b/Sources/StudioModel.swift index 14918f2..6e90c8c 100644 --- a/Sources/StudioModel.swift +++ b/Sources/StudioModel.swift @@ -20,6 +20,7 @@ final class StudioModel: ObservableObject { @Published private(set) var managing = false @Published private(set) var running = false @Published private(set) var webStatus = "" + @Published private(set) var webSearchLink: URL? @Published private(set) var knowledgeStatus = "" var connectedKnowledge: (any MCPToolClient)? { @@ -177,8 +178,9 @@ final class StudioModel: ObservableObject { \(toolAttachment.output) """) } - let lookup = mcpConnections[.web]?.toolset != nil ? ChatWebLookup(message: text) : nil - let repositoryClient = GiteaRepositoryLookup.matches(text) ? + let lookup = ChatWebLookup(message: text) + let wantsRepositories = GiteaRepositoryLookup.matches(text) + let repositoryClient = wantsRepositories ? activeToolsets.first(where: { entry in entry.toolset.tools.contains { $0.name == "list_repositories" } })?.toolset.client : nil @@ -188,6 +190,7 @@ final class StudioModel: ObservableObject { prompt = "" toolAttachment = nil status = "" + webSearchLink = nil webStatus = lookup == nil ? "" : "Looking up web sources…" knowledgeStatus = knowledge == nil ? "" : "Searching the connected knowledge index…" running = true @@ -199,6 +202,7 @@ final class StudioModel: ObservableObject { let sources = try await lookup.resolve(searchEndpoint: searchEndpoint) try Task.checkCancellation() webStatus = sources.status + webSearchLink = sources.browserFallback systemParts.append(sources.reference) } catch { webStatus = "" @@ -228,10 +232,13 @@ final class StudioModel: ObservableObject { systemParts.append("External knowledge retrieval failed for this turn. Do not claim to have searched the index.") } } - if let repositoryClient { + if wantsRepositories { webStatus = "Listing Gitea repositories…" do { - let repositories = try await GiteaRepositoryLookup.references(client: repositoryClient) + let client: any MCPToolClient + if let repositoryClient { client = repositoryClient } + else { client = try await GiteaRepositoryLookup.configuredClient() } + let repositories = try await GiteaRepositoryLookup.references(client: client) try Task.checkCancellation() systemParts.append(repositories) webStatus = "Gitea repositories checked." @@ -553,6 +560,7 @@ final class StudioModel: ObservableObject { private func loadMessages() { messages = [] webStatus = "" + webSearchLink = nil knowledgeStatus = "" toolAttachment = nil documents = [] diff --git a/Tests/Fixtures/server.py b/Tests/Fixtures/server.py index 3313ff8..a596b74 100644 --- a/Tests/Fixtures/server.py +++ b/Tests/Fixtures/server.py @@ -40,6 +40,13 @@ class Handler(BaseHTTPRequestHandler): payload = ''.join(f'data: {json.dumps(frame)}\n\n' for frame in frames) self.reply(200, (payload + 'data: [DONE]\n\n').encode(), 'text/event-stream') return + if self.path == '/chat-web/api/chat': + system, user = message['messages'] + if system['role'] != 'system' or 'Test passage.' not in system['content'] or '/article' not in user['content']: + self.reply(400) + return + self.reply(200, b'{"message":{"content":"Page received."},"done":true}\n', 'application/x-ndjson') + return if self.path == '/chat-tools/api/chat': system, user = message['messages'] valid = (system['role'] == 'system' and 'fixture/visible-repo' in system['content'] diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index dd8a77f..60ca55f 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -632,6 +632,7 @@ final class ToolboxRepairTests: XCTestCase { XCTAssertTrue(found.reference.contains("A fixture & summary")) let unavailable = try await search.resolve(searchEndpoint: "") XCTAssertTrue(unavailable.status.contains("SearXNG")) + XCTAssertEqual(unavailable.browserFallback?.host, "duckduckgo.com") } func testLiveLaravelRetrieval() async throws { @@ -787,14 +788,32 @@ final class ConnectedChatTests: XCTestCase { XCTAssertEqual(studio.webStatus, "Gitea repositories checked.") } + @MainActor + func testChatRetrievesPageWithoutToolboxConnection() async throws { + guard let address = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"], + let base = URL(string: address)?.deletingLastPathComponent() else { + throw XCTSkip("Run Scripts/test.sh to configure the fixture.") + } + let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let studio = StudioModel() + studio.open(databaseURL: directory.appending(path: "studio.sqlite")) + studio.prompt = "Can you read \(base.appending(path: "article").absoluteString)?" + studio.send(endpoint: base.appending(path: "chat-web").absoluteString, model: "fixture", mlxPath: "", + thinking: .off, failover: false, mlxOnly: false, compatible: false, recall: false, + useDocuments: false, instructions: "", settings: GenerationSettings()) + let deadline = ContinuousClock.now + .seconds(8) + while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertTrue(studio.activeToolsets.isEmpty) + XCTAssertEqual(studio.messages.last?.content, "Page received.") + } + func testLiveConnectedGiteaRepositoryLookup() async throws { let env = ProcessInfo.processInfo.environment guard let path = env["AISTUDIO_TEST_REAL_MCP_CONFIG"], env["AISTUDIO_TEST_REAL_GITEA"] == "1" else { throw XCTSkip("Enable the installed Gitea smoke test explicitly.") } - let file = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path)) - let client = try XCTUnwrap(file.mcpServers["absdev-gitea"]).makeClient() - _ = try await client.listTools() + let client = try await GiteaRepositoryLookup.configuredClient(pathOverride: path) let result = try await GiteaRepositoryLookup.references(client: client) XCTAssertFalse(result.contains("Gitea returned no repository entries.")) }