new features

This commit is contained in:
Mark Gregory
2026-11-17 16:39:43 +00:00
parent d1a1b454f6
commit 713d021454
13 changed files with 1100 additions and 141 deletions
+220 -1
View File
@@ -722,6 +722,8 @@ final class ToolboxRepairTests: XCTestCase {
let result = try await retrieval.resolve(searchEndpoint: "")
XCTAssertTrue(result.reference.contains("Test passage."))
XCTAssertTrue(result.reference.contains(page.absoluteString))
XCTAssertEqual(result.sources.first?.url, page)
XCTAssertEqual(result.sources.first?.kind, .page)
let search = try XCTUnwrap(ChatWebLookup(message: "Search the web for tides & moon"))
let found = try await search.resolve(searchEndpoint: endpoint)
XCTAssertTrue(found.reference.contains("Test passage."))
@@ -731,6 +733,20 @@ final class ToolboxRepairTests: XCTestCase {
XCTAssertTrue(followed.reference.contains("/follow-detail"))
}
func testSearchRetainsSnippetsWhenThePageIsBlocked() async throws {
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"],
let base = URL(string: endpoint)?.deletingLastPathComponent() else {
throw XCTSkip("Run Scripts/test.sh to configure the web fixture.")
}
let search = ChatWebLookup.search("fusion")
let result = try await search.resolve(searchEndpoint: base.appending(path: "search-blocked").absoluteString)
XCTAssertTrue(result.reference.contains("Fusion combines nuclei."))
XCTAssertTrue(result.reference.contains("Search result snippet"))
XCTAssertEqual(result.sources.map(\.kind), [.searchSnippet])
XCTAssertTrue(result.diagnostics.contains { $0.contains("403") })
XCTAssertFalse(result.diagnostics.contains { $0.hasPrefix("Fetched ") })
}
func testLiveDefaultSearchRetrievesPages() async throws {
guard let query = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_WEB_QUERY"] else {
throw XCTSkip("Set AISTUDIO_TEST_REAL_WEB_QUERY to check live search and retrieval.")
@@ -1041,7 +1057,7 @@ final class ConnectedChatTests: XCTestCase {
}
let deadline = ContinuousClock.now + .seconds(8)
XCTAssertTrue(studio.activeToolsets.isEmpty)
studio.prompt = "can you see my git repos"
studio.prompt = "can you see my git repos and search the knowledge base for guidance"
studio.send(endpoint: base.appending(path: "chat-tools").absoluteString, model: "fixture", mlxPath: "",
thinking: .off, failover: false, mlxOnly: false, compatible: false, recall: false,
useDocuments: false, instructions: "", settings: GenerationSettings())
@@ -1105,6 +1121,7 @@ final class ConnectedChatTests: XCTestCase {
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertTrue(studio.activeToolsets.isEmpty)
XCTAssertEqual(studio.messages.last?.content, "Page received.")
XCTAssertEqual(studio.messages.last?.webSources.first?.kind, .page)
}
@MainActor
@@ -1513,3 +1530,205 @@ final class StudioWorkspaceCreationTests: XCTestCase {
XCTAssertNotNil(Bundle.main.url(forResource: "pegasus-index", withExtension: "py"))
}
}
extension AutomaticWebRoutingTests {
func testInternetFollowUpsResolveToPreviousQuestion() {
let history = [Message(role: .user, content: "How does fusion work")]
for input in ["Can you search teh internet for this information", "Look it up on the internet", "Search the web for that"] {
guard case .search(let query)? = ChatWebLookup.forChat(message: input, recent: history, automatic: false) else {
XCTFail("Expected a contextual lookup for \(input)")
continue
}
XCTAssertEqual(query, "How does fusion work")
}
}
}
extension AutomaticWebRoutingTests {
func testLatestInfoFollowUpUsesVoyagerTopicEvenWithAutomaticSearchOff() {
let history = [
Message(role: .user, content: "What is Voyager 1?"),
Message(role: .assistant, content: "Voyager 1 is a spacecraft."),
Message(role: .user, content: "Check the internet and get latest info")
]
for text in ["Check the internet and get latest info", "Get the latest information", "Look online for updates"] {
guard case .search(let query)? = ChatWebLookup.forChat(message: text, recent: history, automatic: false) else {
XCTFail("Expected explicit web lookup for \(text)")
continue
}
XCTAssertEqual(query, "What is Voyager 1 latest updates")
}
XCTAssertNil(ChatWebLookup.forChat(message: "Check the internet connection", recent: history, automatic: true))
}
}
extension AutomaticWebRoutingTests {
func testAutomaticSearchHandlesNamedTopicsAndPlainRequestsForInformation() {
for query in ["Voyager 1", "voyager 1", "Ca you tell me about voyager 1", "Tell me about Voyager 1", "Explain how photosynthesis works"] {
guard case .search(query)? = ChatWebLookup.forChat(message: query, recent: [], automatic: true) else {
XCTFail("Expected default search for \(query)")
continue
}
}
XCTAssertNil(ChatWebLookup.forChat(message: "How are you?", recent: [], automatic: true))
XCTAssertNil(ChatWebLookup.forChat(message: "Explain our internal billing", recent: [], automatic: true))
}
}
final class ChatModelChoiceTests: XCTestCase {
func testModelChoicesRoundTripIndependentlyAndResetToDefault() throws {
let first = UUID()
let second = UUID()
let defaultModel = ChatModelChoice(backend: .ollama, model: "default:latest")
var choices = ChatModelChoice.read(Data())
choices[first] = ChatModelChoice(backend: .mlx, model: "/models/test")
choices[second] = ChatModelChoice(backend: .compatible, model: "remote")
let restored = ChatModelChoice.read(try JSONEncoder().encode(choices))
XCTAssertEqual(restored[first]?.displayName, "test")
XCTAssertEqual(restored[second]?.backend, .compatible)
choices[first] = nil
XCTAssertEqual(choices[first] ?? defaultModel, defaultModel)
XCTAssertEqual(choices[second], restored[second])
}
}
final class WebReplySourcesTests: XCTestCase {
func testSourceKindsSurviveReopeningChat() throws {
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
let url = root.appending(path: "studio.sqlite")
let store = try Store(url: url)
let chat = try store.create(title: "Research")
let source = WebReplySource(url: URL(string: "https://example.org/article")!, title: "Article", kind: .page)
try store.save(Message(role: .user, content: "Read the article"), in: chat.id)
try store.save(Message(role: .assistant, content: "Summary", webSources: [source]), in: chat.id)
let messages = try Store(url: url).messages(in: chat.id)
XCTAssertEqual(messages[0].webSources, [])
XCTAssertEqual(messages[1].webSources, [source])
}
}
final class ChatDocumentFallbackTests: XCTestCase {
func testOpeningExcerptsIncludeNewestDocumentsAndRemainChatScoped() throws {
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: folder) }
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
let store = try Store(url: folder.appending(path: "studio.sqlite"))
let chat = try store.create(title: "Documents")
let other = try store.create(title: "Other")
try store.addDocument(title: "Old", chunks: ["Introduction A", "Later A"], in: chat.id)
try store.addDocument(title: "New", chunks: ["Introduction B", "Later B"], in: chat.id)
try store.addDocument(title: "Unrelated", chunks: ["Other chat"], in: other.id)
XCTAssertEqual(try store.openingExcerpts(in: chat.id), [
DocumentExcerpt(title: "New", text: "Introduction B"),
DocumentExcerpt(title: "Old", text: "Introduction A")
])
}
}
extension ChatDocumentFallbackTests {
@MainActor
func testDirectAndImportedDocumentReachTheModelAndShowOnUserMessages() async throws {
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"],
let base = URL(string: endpoint)?.deletingLastPathComponent() else {
throw XCTSkip("Run Scripts/test.sh to configure the local fixture.")
}
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
let database = root.appending(path: "studio.sqlite")
let studio = StudioModel()
studio.open(databaseURL: database)
for imported in [false, true] {
studio.newChat()
if imported {
let store = try Store(url: database)
let chat = try XCTUnwrap(studio.selected)
try store.addDocument(title: "brief.txt", chunks: ["Cobalt river trail"], in: chat)
} else {
studio.attachToolResult(name: "brief.txt", output: "Cobalt river trail", isDocument: true)
}
studio.prompt = "Tell me about this"
studio.send(endpoint: base.appending(path: "chat-document").absoluteString, model: "fixture",
mlxPath: "", thinking: .off, failover: false, mlxOnly: false, compatible: false,
recall: false, useDocuments: imported, instructions: "", settings: GenerationSettings())
let deadline = ContinuousClock.now + .seconds(5)
while studio.running && ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
XCTAssertEqual(studio.messages.last?.content, "Document received.", studio.status)
let saved = try Store(url: database).messages(in: XCTUnwrap(studio.selected))
XCTAssertEqual(saved.first?.content, "Tell me about this")
XCTAssertEqual(saved.first?.documentNames, ["brief.txt"])
}
}
}
final class RemoteStackSelectionTests: XCTestCase {
@MainActor
func testSelectionOnlyQueriesTheChosenRemoteStackAndDoesNotFallBack() async throws {
let studio = StudioModel()
let atlas = MCPConnectionID.profile("atlas")
let pegasus = MCPConnectionID.profile("pegasus")
studio.connectMCP(atlas, name: "Atlas") {
ConnectedChatTests.Server(name: "search_knowledge", result: Data(#"{"structuredContent":{"result":[{"source":"atlas.md","content":"Atlas passage"}]}}"#.utf8))
}
studio.connectMCP(pegasus, name: "Pegasus") {
ConnectedChatTests.Server(name: "search_knowledge", result: Data(#"{"structuredContent":{"result":[{"source":"pegasus.md","content":"Pegasus passage"}]}}"#.utf8))
}
let deadline = ContinuousClock.now + .seconds(5)
while studio.remoteKnowledgeStacks.count < 2 && ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
studio.activeRemoteStack = .server(pegasus)
let chosen = try XCTUnwrap(studio.selectedKnowledgeStack(for: studio.activeRemoteStack))
let result = try await ExternalKnowledgeSearch.references(client: chosen.client, query: "guidance")
XCTAssertEqual(result.sources, ["pegasus.md"])
studio.disconnectMCP(pegasus)
XCTAssertNil(studio.selectedKnowledgeStack(for: studio.activeRemoteStack))
XCTAssertNil(studio.selectedKnowledgeStack(for: .off))
XCTAssertEqual(studio.selectedKnowledgeStack(for: .automatic)?.id, atlas)
}
}
extension AutomaticWebRoutingTests {
func testTypoDoesNotFetchDictionaryResultsForOrdinaryTopic() async throws {
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"],
let base = URL(string: endpoint)?.deletingLastPathComponent() else {
throw XCTSkip("Run Scripts/test.sh to configure the web fixture.")
}
let query = ChatWebLookup.search("Explain teh prompts")
let data = try await query.resolve(searchEndpoint: base.appending(path: "search-relevance").absoluteString)
XCTAssertEqual(data.sources.map { $0.url.lastPathComponent }, ["prompt-page"])
XCTAssertFalse(data.diagnostics.contains { $0.contains("typo-page") || $0.contains("HTTP 500") })
}
}
extension RemoteStackSelectionTests {
@MainActor
func testRepositoryFollowupListsRealRowsWithoutSelectingAModel() async throws {
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let studio = StudioModel()
studio.open(databaseURL: root.appending(path: "studio.sqlite"))
studio.connectMCP(.profile("gitea"), name: "Gitea") {
let payload = #"{"structuredContent":{"result":[{"full_name":"team/one"},{"full_name":"team/two"},{"full_name":"team/three"},{"full_name":"team/four"},{"full_name":"team/five"}]}}"#
return ConnectedChatTests.Server(name: "list_repositories", result: Data(payload.utf8))
}
XCTAssertEqual(GiteaRepositoryLookup.inventoryLimit("Can you see my repos"), 100)
studio.prompt = "Ok list the first 4 repositories"
studio.send(endpoint: "", model: "", mlxPath: "", thinking: .off, failover: false,
mlxOnly: false, compatible: false, recall: false, useDocuments: false,
instructions: "", settings: GenerationSettings())
let deadline = ContinuousClock.now + .seconds(5)
while studio.running && ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
let reply = try XCTUnwrap(studio.messages.last)
XCTAssertTrue(reply.backend.hasPrefix("Gitea"))
XCTAssertTrue(reply.content.contains("4. team/four"))
XCTAssertFalse(reply.content.contains("team/five"))
XCTAssertFalse(reply.content.contains("github.com"))
}
}