From a79bab404d855ead94416a7fc1d0574d26713156 Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Tue, 17 Nov 2026 10:02:02 +0000 Subject: [PATCH] Wait for enabled knowledge servers on the first chat turn --- Sources/StudioModel.swift | 33 +++++++++++++++++++++++++-------- Tests/StudioTests.swift | 21 ++++++++++++++++----- 2 files changed, 41 insertions(+), 13 deletions(-) diff --git a/Sources/StudioModel.swift b/Sources/StudioModel.swift index a4ad985..35c618f 100644 --- a/Sources/StudioModel.swift +++ b/Sources/StudioModel.swift @@ -134,7 +134,6 @@ final class StudioModel: ObservableObject { let parameters = try settings.parameters(mlxOnly: mlxOnly, compatible: compatible) let store = try database() let attachment = toolAttachment - let knowledge = connectedKnowledge let chat = try selected ?? create(String(text.prefix(48))) let user = Message(role: .user, content: text) let recent = Array(messages.suffix(32)) @@ -184,10 +183,6 @@ final class StudioModel: ObservableObject { } let lookup = UserDefaults.standard.object(forKey: "builtInWebEnabled") as? Bool == false ? nil : 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 let searchEndpoint = UserDefaults.standard.string(forKey: "webSearchEndpoint") ?? "" try store.save(user, in: chat) messages.append(user) @@ -197,7 +192,7 @@ final class StudioModel: ObservableObject { webDiagnostics = [] webSearchLink = nil webStatus = lookup == nil ? "" : "Looking up web sources…" - knowledgeStatus = knowledge == nil ? "" : "Searching the connected knowledge index…" + knowledgeStatus = connectedKnowledge == nil ? "" : "Searching the connected knowledge index…" running = true partial = Message(role: .assistant, content: "") let start = ProcessInfo.processInfo.systemUptime @@ -219,7 +214,25 @@ final class StudioModel: ObservableObject { return } } - if let knowledge { + if connectedKnowledge == nil || wantsRepositories { + let connecting = mcpOperations.compactMap { id, operation in + mcpConnections[id]?.progress == "Connecting…" && id != .web ? operation.task : nil + } + if !connecting.isEmpty && knowledgeStatus.isEmpty { + knowledgeStatus = "Checking enabled knowledge servers…" + } + for task in connecting { await task.value } + if Task.isCancelled { + knowledgeStatus = "" + status = "Generation stopped." + partial = nil + running = false + generation = nil + return + } + } + if let knowledge = connectedKnowledge { + knowledgeStatus = "Searching the connected knowledge index…" do { let material = try await ExternalKnowledgeSearch.references(client: knowledge, query: text) try Task.checkCancellation() @@ -237,11 +250,15 @@ final class StudioModel: ObservableObject { knowledgeStatus = "Knowledge search failed: \(error.localizedDescription)" systemParts.append("External knowledge retrieval failed for this turn. Do not claim to have searched the index.") } + } else if knowledgeStatus == "Checking enabled knowledge servers…" { + knowledgeStatus = "" } if wantsRepositories { webStatus = "Listing Gitea repositories…" do { - guard let repositoryClient else { + guard let repositoryClient = activeToolsets.first(where: { + $0.toolset.tools.contains { $0.name == "list_repositories" } + })?.toolset.client else { throw StudioError("Enable the Gitea server in Toolbox → MCP Servers and check its connection.") } let repositories = try await GiteaRepositoryLookup.references(client: repositoryClient) diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index fca9fb4..87099fd 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -840,7 +840,8 @@ final class ConnectedChatTests: XCTestCase { let name: String let result: Data func listTools() async throws -> [MCPTool] { - [MCPTool(name: name, description: "", inputSchemaJSON: Data("{}".utf8))] + try await Task.sleep(for: .milliseconds(100)) + return [MCPTool(name: name, description: "", inputSchemaJSON: Data("{}".utf8))] } func callTool(_ name: String, argumentsJSON: Data) async throws -> Data { guard name == self.name else { throw StudioError("Unexpected tool.") } @@ -865,6 +866,19 @@ final class ConnectedChatTests: XCTestCase { XCTAssertEqual(try Store(url: url).conversations().map(\.id), [second]) } + func testLiveLocalKnowledgeSearch() async throws { + guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_MCP_CONFIG"] else { + throw XCTSkip("Set the installed MCP configuration to verify knowledge search.") + } + let config = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path)) + let profile = try XCTUnwrap(config.mcpServers["local-knowledge"]) + let client = try profile.makeClient() + let tools = try await client.listTools() + XCTAssertTrue(tools.contains { $0.name == "search_knowledge" }) + let result = try await ExternalKnowledgeSearch.references(client: client, query: "Laravel Gates authorization") + XCTAssertFalse(result.isEmpty) + } + @MainActor func testChatSendsConnectedKnowledgeAndGiteaWithoutExtraSelection() async throws { guard let address = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"], @@ -882,10 +896,7 @@ final class ConnectedChatTests: XCTestCase { Server(name: "list_repositories", result: Data(#"{"structuredContent":{"result":[{"full_name":"fixture/visible-repo"}]}}"#.utf8)) } let deadline = ContinuousClock.now + .seconds(8) - while studio.activeToolsets.count < 2 && ContinuousClock.now < deadline { - try await Task.sleep(for: .milliseconds(10)) - } - XCTAssertEqual(studio.activeToolsets.count, 2) + XCTAssertTrue(studio.activeToolsets.isEmpty) studio.prompt = "can you see my git repos" studio.send(endpoint: base.appending(path: "chat-tools").absoluteString, model: "fixture", mlxPath: "", thinking: .off, failover: false, mlxOnly: false, compatible: false, recall: false,