Use saved web and Gitea access from a fresh chat

This commit is contained in:
Mark Gregory
2026-11-16 16:18:39 +00:00
parent 00ea78671b
commit 4ebf2b82be
6 changed files with 79 additions and 15 deletions
+6 -5
View File
@@ -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. 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 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 the same operations through Toolbox. Web and custom MCP servers can stay
connected at the same time. With Built-In Web active, chat retrieves connected at the same time. Chat retrieves up to two explicitly typed
up to two explicitly typed HTTP(S) URLs and adds their source text to the HTTP(S) URLs without requiring a Toolbox connection. Use `/search your query`
request. Use `/search your query` or `Search the web for your query` to search or `Search the web for your query` to use the configured SearXNG endpoint.
from chat using 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 ## 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: For opt-in live provider checks, use installed models or select a catalog download:
+3
View File
@@ -216,6 +216,9 @@ struct ChatView: View {
Text(activity.joined(separator: " · ")) Text(activity.joined(separator: " · "))
.font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled) .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, ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage) autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage)
.frame(height: 62) .frame(height: 62)
+29 -3
View File
@@ -243,7 +243,8 @@ enum ChatWebLookup {
init?(message: String) { init?(message: String) {
let text = message.trimmingCharacters(in: .whitespacesAndNewlines) 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) }) { if let prefix = prefixes.first(where: { text.lowercased().hasPrefix($0) }) {
let query = String(text.dropFirst(prefix.count)).trimmingCharacters(in: .whitespacesAndNewlines) let query = String(text.dropFirst(prefix.count)).trimmingCharacters(in: .whitespacesAndNewlines)
if !query.isEmpty { self = .search(query); return } if !query.isEmpty { self = .search(query); return }
@@ -263,9 +264,10 @@ enum ChatWebLookup {
self = .pages(urls) 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 references: [String] = []
var failures: [String] = [] var failures: [String] = []
var browserFallback: URL?
switch self { switch self {
case .pages(let urls): case .pages(let urls):
for url in urls { for url in urls {
@@ -289,6 +291,11 @@ enum ChatWebLookup {
try Task.checkCancellation() try Task.checkCancellation()
failures.append(error.localizedDescription) 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 status = failures.isEmpty ? "Retrieved \(references.count) web source(s)." : failures.joined(separator: " ")
let notice = failures.isEmpty ? "" : "\n\nWeb lookup errors: \(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) \(references.joined(separator: "\n\n"))\(notice)
""" """
return (reference, status) return (reference, status, browserFallback)
} }
} }
@@ -334,6 +341,25 @@ enum GiteaRepositoryLookup {
return repository && inventory && account 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 { static func references(client: any MCPToolClient) async throws -> String {
let data = try await client.callTool("list_repositories", argumentsJSON: Data("{}".utf8)) let data = try await client.callTool("list_repositories", argumentsJSON: Data("{}".utf8))
guard let result = try JSONSerialization.jsonObject(with: data) as? [String: Any], guard let result = try JSONSerialization.jsonObject(with: data) as? [String: Any],
+12 -4
View File
@@ -20,6 +20,7 @@ final class StudioModel: ObservableObject {
@Published private(set) var managing = false @Published private(set) var managing = false
@Published private(set) var running = false @Published private(set) var running = false
@Published private(set) var webStatus = "" @Published private(set) var webStatus = ""
@Published private(set) var webSearchLink: URL?
@Published private(set) var knowledgeStatus = "" @Published private(set) var knowledgeStatus = ""
var connectedKnowledge: (any MCPToolClient)? { var connectedKnowledge: (any MCPToolClient)? {
@@ -177,8 +178,9 @@ final class StudioModel: ObservableObject {
\(toolAttachment.output) \(toolAttachment.output)
""") """)
} }
let lookup = mcpConnections[.web]?.toolset != nil ? ChatWebLookup(message: text) : nil let lookup = ChatWebLookup(message: text)
let repositoryClient = GiteaRepositoryLookup.matches(text) ? let wantsRepositories = GiteaRepositoryLookup.matches(text)
let repositoryClient = wantsRepositories ?
activeToolsets.first(where: { entry in activeToolsets.first(where: { entry in
entry.toolset.tools.contains { $0.name == "list_repositories" } entry.toolset.tools.contains { $0.name == "list_repositories" }
})?.toolset.client : nil })?.toolset.client : nil
@@ -188,6 +190,7 @@ final class StudioModel: ObservableObject {
prompt = "" prompt = ""
toolAttachment = nil toolAttachment = nil
status = "" status = ""
webSearchLink = nil
webStatus = lookup == nil ? "" : "Looking up web sources…" webStatus = lookup == nil ? "" : "Looking up web sources…"
knowledgeStatus = knowledge == nil ? "" : "Searching the connected knowledge index…" knowledgeStatus = knowledge == nil ? "" : "Searching the connected knowledge index…"
running = true running = true
@@ -199,6 +202,7 @@ final class StudioModel: ObservableObject {
let sources = try await lookup.resolve(searchEndpoint: searchEndpoint) let sources = try await lookup.resolve(searchEndpoint: searchEndpoint)
try Task.checkCancellation() try Task.checkCancellation()
webStatus = sources.status webStatus = sources.status
webSearchLink = sources.browserFallback
systemParts.append(sources.reference) systemParts.append(sources.reference)
} catch { } catch {
webStatus = "" 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.") 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…" webStatus = "Listing Gitea repositories…"
do { 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() try Task.checkCancellation()
systemParts.append(repositories) systemParts.append(repositories)
webStatus = "Gitea repositories checked." webStatus = "Gitea repositories checked."
@@ -553,6 +560,7 @@ final class StudioModel: ObservableObject {
private func loadMessages() { private func loadMessages() {
messages = [] messages = []
webStatus = "" webStatus = ""
webSearchLink = nil
knowledgeStatus = "" knowledgeStatus = ""
toolAttachment = nil toolAttachment = nil
documents = [] documents = []
+7
View File
@@ -40,6 +40,13 @@ class Handler(BaseHTTPRequestHandler):
payload = ''.join(f'data: {json.dumps(frame)}\n\n' for frame in frames) 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') self.reply(200, (payload + 'data: [DONE]\n\n').encode(), 'text/event-stream')
return 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': if self.path == '/chat-tools/api/chat':
system, user = message['messages'] system, user = message['messages']
valid = (system['role'] == 'system' and 'fixture/visible-repo' in system['content'] valid = (system['role'] == 'system' and 'fixture/visible-repo' in system['content']
+22 -3
View File
@@ -632,6 +632,7 @@ final class ToolboxRepairTests: XCTestCase {
XCTAssertTrue(found.reference.contains("A fixture & summary")) XCTAssertTrue(found.reference.contains("A fixture & summary"))
let unavailable = try await search.resolve(searchEndpoint: "") let unavailable = try await search.resolve(searchEndpoint: "")
XCTAssertTrue(unavailable.status.contains("SearXNG")) XCTAssertTrue(unavailable.status.contains("SearXNG"))
XCTAssertEqual(unavailable.browserFallback?.host, "duckduckgo.com")
} }
func testLiveLaravelRetrieval() async throws { func testLiveLaravelRetrieval() async throws {
@@ -787,14 +788,32 @@ final class ConnectedChatTests: XCTestCase {
XCTAssertEqual(studio.webStatus, "Gitea repositories checked.") 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 { func testLiveConnectedGiteaRepositoryLookup() async throws {
let env = ProcessInfo.processInfo.environment let env = ProcessInfo.processInfo.environment
guard let path = env["AISTUDIO_TEST_REAL_MCP_CONFIG"], env["AISTUDIO_TEST_REAL_GITEA"] == "1" else { 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.") throw XCTSkip("Enable the installed Gitea smoke test explicitly.")
} }
let file = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path)) let client = try await GiteaRepositoryLookup.configuredClient(pathOverride: path)
let client = try XCTUnwrap(file.mcpServers["absdev-gitea"]).makeClient()
_ = try await client.listTools()
let result = try await GiteaRepositoryLookup.references(client: client) let result = try await GiteaRepositoryLookup.references(client: client)
XCTAssertFalse(result.contains("Gitea returned no repository entries.")) XCTAssertFalse(result.contains("Gitea returned no repository entries."))
} }