1835 lines
100 KiB
Swift
1835 lines
100 KiB
Swift
import XCTest
|
|
import AppKit
|
|
import SQLite3
|
|
@testable import AIStudio
|
|
|
|
final class StudioTests: XCTestCase {
|
|
func testHybridSearchPromotesAgreementBetweenRankings() throws {
|
|
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let store = try Store(url: directory.appending(path: "documents.sqlite"))
|
|
let chat = try store.create(title: "Research").id
|
|
let query = DocumentVector(language: "test", values: [1, 0])
|
|
try store.addDocument(title: "Both", chunks: ["orchid growing conditions"], vectors: [query], in: chat)
|
|
try store.addDocument(title: "Keyword", chunks: ["orchid orchid orchid"], in: chat)
|
|
try store.addDocument(title: "Vector", chunks: ["greenhouse"], vectors: [query], in: chat)
|
|
XCTAssertEqual(try store.excerpts(matching: "orchid", in: chat, vector: query).first?.title, "Both")
|
|
}
|
|
|
|
func testTemplateExamplesAndBudgetPreserveTheLatestInput() throws {
|
|
let example = PromptExample(input: "Translate red.", output: "Rouge")
|
|
let template = PromptTemplate(body: "Translate {{input}}.", examples: [example])
|
|
let source = DocumentCitation(number: 1, title: "Glossary", excerpt: String(repeating: "a", count: 400), documentID: nil, chunkID: nil)
|
|
let user = Message(role: .user, content: "blue", documentCitations: [source])
|
|
let history = [
|
|
Message(role: .system, content: "Use French."),
|
|
Message(role: .user, content: String(repeating: "history ", count: 50)),
|
|
Message(role: .assistant, content: "Earlier answer"),
|
|
user
|
|
]
|
|
let full = try StudioPromptRequest.prepare(history, template: template, options: .init(), parameters: .init())
|
|
XCTAssertEqual(full.messages.prefix(3).map(\.content), ["Use French.", "Translate red.", "Rouge"])
|
|
XCTAssertEqual(full.messages.last?.role, .user)
|
|
XCTAssertTrue(full.messages.last?.content.hasPrefix("Translate blue.\n\n") == true)
|
|
XCTAssertTrue(full.messages.last?.content.contains("[D1] Glossary") == true)
|
|
XCTAssertEqual(full.citations, [source])
|
|
|
|
let tight = try StudioPromptRequest.prepare(history, template: template,
|
|
options: AgentPromptSettings(contextBudget: "64", outputTokens: "16"), parameters: .init())
|
|
XCTAssertEqual(tight.messages.map(\.content), ["Use French.", "Translate blue."])
|
|
XCTAssertEqual(tight.parameters.maxTokens, 16)
|
|
XCTAssertTrue(tight.citations.isEmpty)
|
|
XCTAssertThrowsError(try StudioPromptRequest.prepare(history, template: template,
|
|
options: AgentPromptSettings(contextBudget: "64", outputTokens: "64"), parameters: .init()))
|
|
XCTAssertTrue(PromptEvaluation.matches(" Bleu\nclair ", expected: "bleu clair"))
|
|
XCTAssertFalse(PromptEvaluation.matches("Bleu.", expected: "bleu"))
|
|
}
|
|
|
|
func testPromptExamplesAndCitationsSurviveWorkspaceBackup() 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 store = try Store(url: folder.appending(path: "studio.sqlite"))
|
|
let backup = folder.appending(path: "backup.sqlite")
|
|
let id = UUID()
|
|
let old = PromptExample(input: "red", output: "rouge")
|
|
let new = PromptExample(input: "blue", output: "bleu")
|
|
try store.savePrompt(id: id, title: "Translate", content: "Translate {{input}}", notes: "", tags: "", examples: [old])
|
|
try store.savePrompt(id: id, title: "Translate", content: "To French: {{input}}", notes: "", tags: "", examples: [new])
|
|
let chat = try store.create(title: "Sources").id
|
|
try store.addDocument(title: "Glossary", chunks: ["bleu means blue"], in: chat)
|
|
let excerpt = try XCTUnwrap(store.excerpts(matching: "bleu", in: chat, includeLocations: true).first)
|
|
let citation = DocumentCitation(number: 1, title: excerpt.title, excerpt: excerpt.text,
|
|
documentID: try XCTUnwrap(excerpt.documentID), chunkID: try XCTUnwrap(excerpt.chunkID))
|
|
try store.save(Message(role: .assistant, content: "See [D1].", documentCitations: [citation]), in: chat)
|
|
try store.deleteDocument(try XCTUnwrap(citation.documentID), in: chat)
|
|
try store.exportWorkspace(to: backup)
|
|
try store.deleteSnippet(id)
|
|
try store.delete(chat)
|
|
try store.restoreWorkspace(from: backup)
|
|
XCTAssertEqual(try store.snippets().first?.examples, [new])
|
|
XCTAssertEqual(try store.promptVersions(id).map(\.examples), [[new], [old]])
|
|
XCTAssertEqual(try store.messages(in: chat).first?.documentCitations, [citation])
|
|
}
|
|
|
|
@MainActor
|
|
func testAgentTemplatesAndCitationsReachOllamaWithStageSettings() 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 folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let studio = StudioModel()
|
|
studio.open(databaseURL: folder.appending(path: "studio.sqlite"))
|
|
studio.activeRemoteStack = .off
|
|
let id = UUID()
|
|
XCTAssertTrue(studio.saveSnippet(id: id, kind: .prompt, title: "Translate", content: "Translate {{input}}",
|
|
examples: [PromptExample(input: "Translate red", output: "rouge")]))
|
|
let planner = AgentRole.custom(AgentProfile(name: "Planning", instructions: "Draft a translation.",
|
|
promptSettings: AgentPromptSettings(templateID: id, contextBudget: "512", outputTokens: "32", useDocuments: false)))
|
|
studio.attachToolResult(name: "Glossary", output: "blue means bleu", isDocument: true)
|
|
studio.prompt = "Translate the word blue"
|
|
studio.send(endpoint: base.appending(path: "agent-prompt").absoluteString, model: "fixture",
|
|
mlxPath: "", thinking: .off, failover: false, mlxOnly: false, compatible: false,
|
|
recall: false, useDocuments: true, instructions: "", settings: .init(), agents: [planner, .reviewer])
|
|
let deadline = ContinuousClock.now + .seconds(5)
|
|
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
|
XCTAssertEqual(studio.messages.last?.content, "Bleu [D1].", studio.status)
|
|
XCTAssertEqual(studio.messages.last?.documentCitations.map(\.title), ["Glossary"])
|
|
XCTAssertEqual(studio.messages.first?.content, "Translate the word blue")
|
|
}
|
|
|
|
func testEmptyFailureFallsBack() async throws {
|
|
let output = try await collect(Router.stream(primary: { failing() }, fallback: { success() }))
|
|
XCTAssertEqual(output, [.answer("fallback")])
|
|
}
|
|
|
|
func testThinkingCommitsRoute() async throws {
|
|
var received: [Delta] = []
|
|
do {
|
|
for try await delta in Router.stream(
|
|
primary: { failing(after: .thinking("working")) }, fallback: { success() }
|
|
) {
|
|
received.append(delta)
|
|
}
|
|
XCTFail("Expected an error")
|
|
} catch {
|
|
XCTAssertEqual(received, [.thinking("working")])
|
|
}
|
|
}
|
|
|
|
func testCancellationDoesNotFallBack() async throws {
|
|
let primary: Router.Producer = {
|
|
AsyncThrowingStream { $0.finish(throwing: CancellationError()) }
|
|
}
|
|
do {
|
|
_ = try await collect(Router.stream(primary: primary, fallback: { success() }))
|
|
XCTFail("Expected cancellation")
|
|
} catch is CancellationError {}
|
|
}
|
|
|
|
func testToolCommitPreventsFallbackBeforeText() async throws {
|
|
do {
|
|
_ = try await collect(Router.stream(
|
|
primary: { failing(after: .committed) }, fallback: { success() }
|
|
))
|
|
XCTFail("Expected the original failure")
|
|
} catch let error as StudioError {
|
|
XCTAssertEqual(error.message, "test failure")
|
|
}
|
|
}
|
|
|
|
func testDisabledFallbackSurfacesOriginalError() async throws {
|
|
do {
|
|
_ = try await collect(Router.stream(primary: { failing() }, fallback: nil))
|
|
XCTFail("Expected the original failure")
|
|
} catch let error as StudioError {
|
|
XCTAssertEqual(error.message, "test failure")
|
|
}
|
|
}
|
|
|
|
func testThinkingEncodingAndResponseDecoding() throws {
|
|
let data = try JSONEncoder().encode(Thinking.high)
|
|
XCTAssertEqual(String(decoding: data, as: UTF8.self), #""high""#)
|
|
XCTAssertEqual(try JSONDecoder().decode(Thinking.self, from: Data("false".utf8)), .off)
|
|
let line = #"{"message":{"content":"hello","thinking":"reason"},"done":true}"#
|
|
let frame = try Ollama.Frame.decode(line)
|
|
XCTAssertEqual(frame.message?.content, "hello")
|
|
XCTAssertEqual(frame.message?.thinking, "reason")
|
|
XCTAssertEqual(frame.done, true)
|
|
XCTAssertThrowsError(try Ollama.Frame.decode(#"{"error":"missing model"}"#))
|
|
}
|
|
|
|
func testEndpointRejectsCredentialsAndFragments() throws {
|
|
XCTAssertThrowsError(try Ollama(endpoint: "https://user:[email protected]"))
|
|
XCTAssertThrowsError(try Ollama(endpoint: "https://example.com/#chat"))
|
|
XCTAssertNoThrow(try Ollama(endpoint: "http://127.0.0.1:11434"))
|
|
XCTAssertNoThrow(try Ollama(endpoint: "https://example.com/ollama"))
|
|
XCTAssertNoThrow(try Ollama(endpoint: "https://example.com/ollama", token: "fixture"))
|
|
XCTAssertThrowsError(try Ollama(endpoint: "http://example.com/ollama", token: "fixture"))
|
|
XCTAssertThrowsError(try Ollama(endpoint: "https://example.com", token: "bad\nheader"))
|
|
}
|
|
|
|
func testSQLiteRoundTripAndScopedMemory() throws {
|
|
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let url = directory.appending(path: "chat.sqlite")
|
|
let first = try Store(url: url)
|
|
let chat = try first.create(title: "A chat")
|
|
let other = try first.create(title: "Another")
|
|
let message = Message(role: .user, content: "SQLite's café")
|
|
try first.save(message, in: chat.id)
|
|
try first.save(Message(role: .user, content: "SQLite café"), in: other.id)
|
|
let reopened = try Store(url: url)
|
|
XCTAssertEqual(try reopened.messages(in: chat.id), [message])
|
|
XCTAssertEqual(try reopened.memory(matching: "SQLite", in: chat.id), [message.content])
|
|
XCTAssertEqual(try reopened.memory(matching: "SQLite", in: chat.id, excluding: [message.id]), [])
|
|
try reopened.delete(chat.id)
|
|
XCTAssertEqual(try reopened.messages(in: chat.id), [])
|
|
}
|
|
}
|
|
|
|
private func collect(_ stream: AsyncThrowingStream<Delta, Error>) async throws -> [Delta] {
|
|
var result: [Delta] = []
|
|
for try await delta in stream { result.append(delta) }
|
|
return result
|
|
}
|
|
|
|
private func failing(after delta: Delta? = nil) -> AsyncThrowingStream<Delta, Error> {
|
|
AsyncThrowingStream {
|
|
if let delta { $0.yield(delta) }
|
|
$0.finish(throwing: StudioError("test failure"))
|
|
}
|
|
}
|
|
|
|
private func success() -> AsyncThrowingStream<Delta, Error> {
|
|
AsyncThrowingStream {
|
|
$0.yield(.answer("fallback"))
|
|
$0.finish()
|
|
}
|
|
}
|
|
|
|
final class LiveInferenceTests: XCTestCase {
|
|
func testLocalOrRemoteOllama() async throws {
|
|
let environment = ProcessInfo.processInfo.environment
|
|
guard let endpoint = environment["AISTUDIO_TEST_OLLAMA_URL"],
|
|
let tag = environment["AISTUDIO_TEST_OLLAMA_MODEL"] else {
|
|
throw XCTSkip("Set the Ollama smoke-test endpoint and installed model.")
|
|
}
|
|
let ollama = try Ollama(endpoint: endpoint, token: environment["AISTUDIO_TEST_OLLAMA_TOKEN"] ?? "")
|
|
let models = try await ollama.models()
|
|
XCTAssertTrue(models.contains { $0.name == tag })
|
|
_ = try await ollama.details(for: tag)
|
|
let stream = ollama.generate(InferenceRequest(
|
|
model: tag, messages: [Message(role: .user, content: "Reply with one word: hello.")],
|
|
thinking: .off, parameters: GenerationParameters(temperature: 0, maxTokens: 64)
|
|
))
|
|
var answer = ""
|
|
for try await event in stream {
|
|
if case .answer(let text) = event { answer += text }
|
|
}
|
|
XCTAssertFalse(answer.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
|
}
|
|
|
|
func testNativeMLXAndRouterFallback() async throws {
|
|
guard let directory = ProcessInfo.processInfo.environment["AISTUDIO_TEST_MLX_PATH"] else {
|
|
throw XCTSkip("Set the MLX smoke-test model folder.")
|
|
}
|
|
let mlx = MLXProvider()
|
|
await mlx.configureRuntime(idle: nil, weightLimit: 1)
|
|
let prepared = try StudioPromptRequest.prepare([Message(role: .user, content: "hello")],
|
|
template: PromptTemplate(body: "Repeat this word: {{input}}.",
|
|
examples: [PromptExample(input: "Repeat this word: goodbye.", output: "goodbye")]),
|
|
options: AgentPromptSettings(contextBudget: "512", outputTokens: "64"),
|
|
parameters: GenerationParameters(temperature: 0))
|
|
let request = InferenceRequest(model: directory, messages: prepared.messages,
|
|
thinking: .off, parameters: prepared.parameters)
|
|
do {
|
|
_ = try await collect(mlx.generate(request))
|
|
XCTFail("Expected the runtime weight limit to reject model loading.")
|
|
} catch let error as StudioError {
|
|
XCTAssertTrue(error.message.contains("weight limit"))
|
|
}
|
|
await mlx.configureRuntime(idle: nil, weightLimit: nil)
|
|
let output = try await collect(Router.stream(primary: { failing() }, fallback: { mlx.generate(request) }))
|
|
XCTAssertTrue(output.contains {
|
|
guard case .backend(let name) = $0 else { return false }
|
|
return name.hasPrefix("MLX")
|
|
})
|
|
XCTAssertTrue(output.contains {
|
|
guard case .answer(let text) = $0 else { return false }
|
|
return !text.isEmpty
|
|
})
|
|
let loaded = await mlx.modelName()
|
|
XCTAssertNotNil(loaded)
|
|
await mlx.configureRuntime(idle: .milliseconds(50), weightLimit: nil)
|
|
let deadline = ContinuousClock.now + .seconds(3)
|
|
while await mlx.modelName() != nil && ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(25))
|
|
}
|
|
let evicted = await mlx.modelName()
|
|
XCTAssertNil(evicted)
|
|
}
|
|
}
|
|
|
|
final class ExpandedStudioTests: XCTestCase {
|
|
func testDocumentIndexIsScopedAndDeletesItsExcerpts() throws {
|
|
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let path = directory.appending(path: "documents.sqlite")
|
|
let store = try Store(url: path)
|
|
let selected = try store.create(title: "Research")
|
|
let other = try store.create(title: "Separate")
|
|
let vector = DocumentVector(language: "fixture", values: [1, 0])
|
|
try store.addDocument(title: "Field notes", chunks: ["A telescope observed Io."], vectors: [vector], in: selected.id)
|
|
try store.addDocument(title: "Other notes", chunks: ["A telescope observed Titan."], vectors: [vector], in: other.id)
|
|
let reopened = try Store(url: path)
|
|
let expected = [DocumentExcerpt(title: "Field notes", text: "A telescope observed Io.")]
|
|
XCTAssertEqual(try reopened.excerpts(matching: "telescope", in: selected.id), expected)
|
|
XCTAssertEqual(try reopened.excerpts(matching: "instrument", in: selected.id, vector: vector), expected)
|
|
let document = try XCTUnwrap(reopened.documents(in: selected.id).first)
|
|
try reopened.deleteDocument(document.id, in: other.id)
|
|
XCTAssertEqual(try reopened.documents(in: selected.id), [document])
|
|
try reopened.delete(selected.id)
|
|
XCTAssertTrue(try reopened.documents(in: selected.id).isEmpty)
|
|
XCTAssertTrue(try reopened.excerpts(matching: "telescope", in: selected.id, vector: vector).isEmpty)
|
|
}
|
|
|
|
func testReasoningMarkersCanCrossStreamChunks() {
|
|
var stream = MLXThinking()
|
|
XCTAssertEqual(stream.append(" <thi"), [])
|
|
XCTAssertEqual(stream.append("nk>reason</th"), [.thinking("reason")])
|
|
XCTAssertEqual(stream.append("ink>hello"), [.answer("hello")])
|
|
XCTAssertEqual(stream.finish(), [])
|
|
}
|
|
|
|
func testMLXThinkingDoesNotConsumeOrdinaryAnswer() {
|
|
var stream = MLXThinking()
|
|
XCTAssertEqual(stream.append("Hello"), [.answer("Hello")])
|
|
XCTAssertEqual(stream.append(" <think>inside answer"), [.answer(" <think>inside answer")])
|
|
}
|
|
|
|
func testMCPMatchesOnlyExpectedResponseAndValidatesArguments() throws {
|
|
let data = Data(#"{"jsonrpc":"2.0","id":"ok","result":{"tools":[]}}"#.utf8)
|
|
XCTAssertNil(try HTTPMCPClient.result(data, id: "other"))
|
|
XCTAssertNotNil(try HTTPMCPClient.result(data, id: "ok"))
|
|
XCTAssertThrowsError(try HTTPMCPClient.arguments(Data("[]".utf8)))
|
|
XCTAssertNoThrow(try HTTPMCPClient.arguments(Data(#"{"q":"example"}"#.utf8)))
|
|
}
|
|
|
|
func testLiveModelCatalogsBrowseAndSearch() async throws {
|
|
guard ProcessInfo.processInfo.environment["AISTUDIO_TEST_LIVE_CATALOGS"] == "1" else {
|
|
throw XCTSkip("Enable live catalog checks explicitly.")
|
|
}
|
|
let mlx = try await CatalogModel.search("")
|
|
let ollama = try await OllamaCatalog.search("")
|
|
let qwen = try await OllamaCatalog.search("qwen")
|
|
XCTAssertFalse(mlx.isEmpty)
|
|
XCTAssertFalse(ollama.isEmpty)
|
|
XCTAssertTrue(qwen.contains { $0.hasPrefix("qwen") })
|
|
}
|
|
|
|
func testHuggingFaceCatalogRejectsNonModelFilesAndAdapters() throws {
|
|
let data = Data("""
|
|
[{"id":"mlx-community/Test-4bit","sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
"siblings":[{"rfilename":"config.json"},{"rfilename":"model.safetensors"},
|
|
{"rfilename":"tokenizer.json"},{"rfilename":"../escape.json"},{"rfilename":"README.md"}],
|
|
"downloads":42,"likes":3},
|
|
{"id":"mlx-community/Adapter","sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
|
"siblings":[{"rfilename":"config.json"},{"rfilename":"adapter_model.safetensors"}]}]
|
|
""".utf8)
|
|
let models = try CatalogModel.decodeSearch(data)
|
|
XCTAssertEqual(models.map(\.title), ["Test-4bit"])
|
|
XCTAssertEqual(models.first?.files, ["config.json", "model.safetensors", "tokenizer.json"])
|
|
XCTAssertEqual(models.first?.downloads, 42)
|
|
XCTAssertEqual(models.first?.likes, 3)
|
|
}
|
|
|
|
func testDownloadedCatalogModelAndRuntime() async throws {
|
|
guard let id = ProcessInfo.processInfo.environment["AISTUDIO_TEST_MODEL_DOWNLOAD"],
|
|
let model = CatalogModel.all.first(where: { $0.id == id }) else {
|
|
throw XCTSkip("Set AISTUDIO_TEST_MODEL_DOWNLOAD to a catalog model ID.")
|
|
}
|
|
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
try await model.install(to: folder) { _, _ in }
|
|
XCTAssertTrue(model.installed(at: folder))
|
|
let provider = MLXProvider()
|
|
try await provider.load(folder.path)
|
|
let loadedName = await provider.modelName()
|
|
XCTAssertEqual(loadedName, folder.lastPathComponent)
|
|
let messages = [Message(role: .user, content: "Reply with one word: hello.")]
|
|
let events = try await collect(provider.generate(.init(model: folder.path, messages: messages, thinking: .off)))
|
|
XCTAssertTrue(events.contains { if case .answer(let text) = $0 { return !text.isEmpty }; return false })
|
|
XCTAssertFalse(events.contains { if case .thinking = $0 { return true }; return false })
|
|
if id == "qwen3-0.6b-4bit" {
|
|
XCTAssertTrue(MLXThinking.supports(folder.path))
|
|
let reasoning = try await collect(provider.generate(.init(model: folder.path, messages: messages, thinking: .on)))
|
|
XCTAssertTrue(reasoning.contains { if case .thinking(let text) = $0 { return !text.isEmpty }; return false })
|
|
}
|
|
}
|
|
|
|
func testAuthenticatedOllamaGatewayAndRedirect() async throws {
|
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_OLLAMA_GATEWAY_URL"],
|
|
let base = URL(string: endpoint)?.deletingLastPathComponent() else {
|
|
throw XCTSkip("Set AISTUDIO_TEST_OLLAMA_GATEWAY_URL to the disposable gateway fixture.")
|
|
}
|
|
let client = try Ollama(endpoint: endpoint, token: "fixture-token")
|
|
let models = try await client.models()
|
|
XCTAssertEqual(models.map(\.name), ["fixture:latest"])
|
|
let request = InferenceRequest(model: "fixture:latest", messages: [
|
|
Message(role: .user, content: "Hello")
|
|
], thinking: .off)
|
|
let events = try await collect(client.generate(request))
|
|
XCTAssertTrue(events.contains(.answer("fixture answer")))
|
|
|
|
let unauthorized = try Ollama(endpoint: endpoint, token: "incorrect")
|
|
do {
|
|
_ = try await unauthorized.models()
|
|
XCTFail("Expected authentication failure")
|
|
} catch let error as StudioError {
|
|
XCTAssertEqual(error.message, "Ollama returned HTTP 401.")
|
|
}
|
|
|
|
let redirect = try Ollama(endpoint: base.appending(path: "redirect").absoluteString, token: "fixture-token")
|
|
do {
|
|
_ = try await redirect.models()
|
|
XCTFail("Expected redirect rejection")
|
|
} catch let error as StudioError {
|
|
XCTAssertEqual(error.message, "Ollama returned HTTP 302.")
|
|
}
|
|
}
|
|
|
|
func testOllamaModelManagementAgainstFixture() async throws {
|
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_OLLAMA_FIXTURE_URL"] else {
|
|
throw XCTSkip("Set AISTUDIO_TEST_OLLAMA_FIXTURE_URL to the disposable model-management fixture.")
|
|
}
|
|
let client = try Ollama(endpoint: endpoint)
|
|
let tag = "fixture:latest"
|
|
var progress: [String] = []
|
|
for try await value in client.pull(tag) { progress.append(value) }
|
|
XCTAssertEqual(progress, ["pulling · 70%", "success"])
|
|
let installed = try await client.models()
|
|
XCTAssertEqual(installed.map(\.name), [tag])
|
|
let details = try await client.details(for: tag)
|
|
XCTAssertEqual(details.capabilities, ["completion"])
|
|
let clone = "fixture-clone:latest"
|
|
try await client.copy(tag, to: clone)
|
|
let afterCopy = try await client.models()
|
|
XCTAssertEqual(Set(afterCopy.map(\.name)), [tag, clone])
|
|
try await client.delete(clone)
|
|
try await client.delete(tag)
|
|
let afterDeletion = try await client.models()
|
|
XCTAssertTrue(afterDeletion.isEmpty)
|
|
}
|
|
|
|
func testMCPDiscoveryAndExecutionAgainstFixture() async throws {
|
|
let endpoints = ProcessInfo.processInfo.environment["AISTUDIO_TEST_MCP_URLS"]?.split(separator: ",") ?? []
|
|
guard !endpoints.isEmpty else { throw XCTSkip("Set AISTUDIO_TEST_MCP_URLS to fixture endpoints.") }
|
|
for endpoint in endpoints {
|
|
let client = try HTTPMCPClient(endpoint: String(endpoint))
|
|
let tools = try await client.listTools()
|
|
XCTAssertEqual(tools.map(\.name), ["echo"])
|
|
let data = try await client.callTool("echo", argumentsJSON: Data(#"{"text":"AI Studio"}"#.utf8))
|
|
XCTAssertTrue(String(decoding: data, as: UTF8.self).contains("AI Studio"))
|
|
}
|
|
}
|
|
}
|
|
|
|
final class WorkspaceExperienceTests: XCTestCase {
|
|
func testMstyImportAndPromptHistory() 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 source = folder.appending(path: "msty.db")
|
|
var db: OpaquePointer?
|
|
XCTAssertEqual(sqlite3_open(source.path, &db), SQLITE_OK)
|
|
let sql = """
|
|
CREATE TABLE conversationTexts(id,title,createdAt);
|
|
CREATE TABLE conversationTextChatSplits(id,conversationId,createdAt);
|
|
CREATE TABLE conversationTextMessages(chatSplitId,role,content,createdAt);
|
|
INSERT INTO conversationTexts VALUES('chat','Imported','1');
|
|
INSERT INTO conversationTextChatSplits VALUES('split','chat','1');
|
|
INSERT INTO conversationTextMessages VALUES('split','user','Question','1'),('split','assistant','Answer','2');
|
|
"""
|
|
let result = sqlite3_exec(db, sql, nil, nil, nil)
|
|
sqlite3_close(db)
|
|
XCTAssertEqual(result, SQLITE_OK)
|
|
let store = try Store(url: folder.appending(path: "studio.sqlite"))
|
|
XCTAssertEqual(try store.importMstyChats(from: source), 1)
|
|
XCTAssertEqual(try store.importMstyChats(from: source), 0)
|
|
let chat = try XCTUnwrap(store.conversations().first)
|
|
XCTAssertEqual(try store.messages(in: chat.id).map(\.content), ["Question", "Answer"])
|
|
let prompt = UUID()
|
|
try store.savePrompt(id: prompt, title: "Prompt", content: "First", notes: "", tags: "")
|
|
try store.savePrompt(id: prompt, title: "Prompt", content: "Second", notes: "Edited", tags: "swift")
|
|
XCTAssertEqual(try store.snippets().first?.tags, "swift")
|
|
XCTAssertEqual(try store.promptVersions(prompt).map(\.content), ["Second", "First"])
|
|
}
|
|
|
|
func testPromptBuilderRendersOnlyPopulatedSectionsInOrder() {
|
|
var draft = PromptDraft()
|
|
draft.role = " Teacher "
|
|
draft.task = "Explain tides"
|
|
draft.audience = " "
|
|
draft.format = "One example"
|
|
XCTAssertEqual(draft.rendered, "## Role\nTeacher\n\n## Task\nExplain tides\n\n## Output format\nOne example")
|
|
XCTAssertEqual(PromptMode.standard.instructions(custom: "ignored"), "")
|
|
XCTAssertEqual(PromptMode.custom.instructions(custom: " Custom "), "Custom")
|
|
}
|
|
|
|
func testProviderThroughputUsesGenerationTime() {
|
|
XCTAssertEqual(ProviderMetrics(tokens: 60, seconds: 2).tokensPerSecond, 30)
|
|
XCTAssertNil(ProviderMetrics(tokens: 60, seconds: 0).tokensPerSecond)
|
|
}
|
|
|
|
func testMarkdownSeparatesCodeFromProse() {
|
|
let blocks = ChatMarkdown.blocks("Example\n```swift\nlet answer = 42\n```\nDone")
|
|
XCTAssertEqual(blocks.map(\.language), [nil, "swift", nil])
|
|
XCTAssertEqual(blocks[1].content, "let answer = 42")
|
|
XCTAssertEqual(ChatMarkdown.blocks("```swift\nunclosed").first?.language, nil)
|
|
}
|
|
|
|
func testConversationSearchAndRename() 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 store = try Store(url: folder.appending(path: "chat.sqlite"))
|
|
let first = try store.create(title: "Original")
|
|
_ = try store.create(title: "Unrelated")
|
|
try store.save(Message(role: .assistant, content: "A literal 100% match."), in: first.id)
|
|
try store.rename(first.id, title: "Renamed")
|
|
XCTAssertEqual(try store.searchConversations("renamed").map(\.id), [first.id])
|
|
XCTAssertEqual(try store.searchConversations("100% MATCH").map(\.id), [first.id])
|
|
XCTAssertTrue(try store.searchConversations("original").isEmpty)
|
|
}
|
|
}
|
|
|
|
final class GenerationConfigurationTests: XCTestCase {
|
|
func testOllamaOverridesAndSilentSystemRole() throws {
|
|
var settings = GenerationSettings()
|
|
settings.temperature = "0"
|
|
settings.maxTokens = "128"
|
|
settings.context = "4096"
|
|
settings.stop = "END\nDONE"
|
|
let options = try settings.parameters(mlxOnly: false)
|
|
let request = InferenceRequest(model: "fixture", messages: [
|
|
Message(role: .system, content: "Quiet instruction"),
|
|
Message(role: .user, content: "First visible message")
|
|
], thinking: .off, parameters: options)
|
|
let json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(Ollama.ChatBody(request))) as? [String: Any])
|
|
let wire = try XCTUnwrap(json["options"] as? [String: Any])
|
|
let messages = try XCTUnwrap(json["messages"] as? [[String: String]])
|
|
XCTAssertEqual(messages.map { $0["role"] }, ["system", "user"])
|
|
XCTAssertEqual(wire["temperature"] as? Double, 0)
|
|
XCTAssertEqual(wire["num_predict"] as? Int, 128)
|
|
XCTAssertEqual(wire["num_ctx"] as? Int, 4096)
|
|
XCTAssertEqual(wire["stop"] as? [String], ["END", "DONE"])
|
|
XCTAssertNil(wire["top_k"])
|
|
settings.temperature = "NaN"
|
|
XCTAssertThrowsError(try settings.parameters(mlxOnly: false))
|
|
}
|
|
|
|
func testStopMatcherHandlesStreamingBoundaries() {
|
|
var matcher = StopMatcher(sequences: ["[stop]", "END"])
|
|
XCTAssertEqual(matcher.append("Hello [st"), "Hello ")
|
|
XCTAssertEqual(matcher.append("op]ignore"), "")
|
|
XCTAssertTrue(matcher.stopped)
|
|
XCTAssertEqual(matcher.finish(), "")
|
|
}
|
|
|
|
func testDockerArgumentsPreserveQuotedValues() throws {
|
|
XCTAssertEqual(try DockerCommand.arguments(#"docker logs --since "1 hour" 'my container'"#),
|
|
["logs", "--since", "1 hour", "my container"])
|
|
XCTAssertEqual(try DockerCommand.arguments("ps ; echo"), ["ps", ";", "echo"])
|
|
XCTAssertThrowsError(try DockerCommand.arguments("docker logs 'unclosed"))
|
|
}
|
|
}
|
|
|
|
final class CompatibleEndpointTests: XCTestCase {
|
|
func testRequiresHTTPSForRemoteAndRejectsEmbeddedCredentials() throws {
|
|
XCTAssertThrowsError(try CompatibleEndpoint(endpoint: "http://example.com/v1"))
|
|
XCTAssertThrowsError(try CompatibleEndpoint(endpoint: "https://user:[email protected]/v1"))
|
|
XCTAssertNoThrow(try CompatibleEndpoint(endpoint: "http://127.0.0.1:1234/v1"))
|
|
}
|
|
|
|
func testLiveLMStudioDiscoveryAndStreaming() async throws {
|
|
let env = ProcessInfo.processInfo.environment
|
|
guard let endpoint = env["AISTUDIO_TEST_LM_STUDIO_URL"],
|
|
let model = env["AISTUDIO_TEST_LM_STUDIO_MODEL"] else {
|
|
throw XCTSkip("Configure a running LM Studio server and loaded model.")
|
|
}
|
|
let client = try CompatibleEndpoint(endpoint: endpoint, token: "")
|
|
let models = try await client.models()
|
|
XCTAssertTrue(models.contains(model))
|
|
let output = try await collect(client.generate(InferenceRequest(model: model, messages: [
|
|
Message(role: .user, content: "Reply with only OK. /no_think")
|
|
], thinking: .off, parameters: GenerationParameters(temperature: 0, maxTokens: 64))))
|
|
XCTAssertTrue(output.contains { if case .answer(let answer) = $0 { return !answer.isEmpty }; return false })
|
|
}
|
|
|
|
func testAuthenticatedDiscoveryAndStreaming() async throws {
|
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COMPATIBLE_URL"] else {
|
|
throw XCTSkip("Set AISTUDIO_TEST_COMPATIBLE_URL to the compatible endpoint fixture.")
|
|
}
|
|
let client = try CompatibleEndpoint(endpoint: endpoint, token: "fixture-token")
|
|
let models = try await client.models()
|
|
XCTAssertEqual(models, ["fixture-model"])
|
|
let output = try await collect(client.generate(InferenceRequest(model: "fixture-model", messages: [
|
|
Message(role: .system, content: "Silent instruction"),
|
|
Message(role: .user, content: "Hello")
|
|
], thinking: .automatic, parameters: GenerationParameters(temperature: 0, maxTokens: 32))))
|
|
XCTAssertEqual(output, [.backend("Compatible API · fixture-model"),
|
|
.thinking("Thinking"), .answer("Fixture response")])
|
|
}
|
|
}
|
|
|
|
final class StdioMCPTests: XCTestCase {
|
|
private func client() throws -> StdioMCPClient {
|
|
let env = ProcessInfo.processInfo.environment
|
|
guard let python = env["AISTUDIO_TEST_STDIO_PYTHON"],
|
|
let fixture = env["AISTUDIO_TEST_STDIO_FIXTURE"] else {
|
|
throw XCTSkip("Run Scripts/test.sh to configure the stdio fixture.")
|
|
}
|
|
return try StdioMCPClient(path: python, arguments: ["-u", fixture])
|
|
}
|
|
|
|
func testLocalDiscoveryInvocationAndDisconnect() async throws {
|
|
let local = try client()
|
|
let tools = try await local.listTools()
|
|
XCTAssertEqual(tools.map(\.name), ["echo"])
|
|
let response = try await local.callTool("echo", argumentsJSON: Data(#"{"text":"line one\nline two"}"#.utf8))
|
|
XCTAssertTrue(String(decoding: response, as: UTF8.self).contains("line two"))
|
|
await local.disconnect()
|
|
do {
|
|
_ = try await local.callTool("echo", argumentsJSON: Data("{}".utf8))
|
|
XCTFail("Expected a disconnected client error.")
|
|
} catch let error as StudioError {
|
|
XCTAssertTrue(error.message.contains("Discover"))
|
|
}
|
|
}
|
|
|
|
func testCancellationStopsWaitingForTheLocalServer() async throws {
|
|
let local = try client()
|
|
_ = try await local.listTools()
|
|
let request = Task {
|
|
try await local.callTool("echo", argumentsJSON: Data(#"{"wait":true}"#.utf8))
|
|
}
|
|
try await Task.sleep(for: .milliseconds(200))
|
|
request.cancel()
|
|
do {
|
|
_ = try await request.value
|
|
XCTFail("Expected cancellation.")
|
|
} catch is CancellationError {}
|
|
let tools = try await local.listTools()
|
|
XCTAssertEqual(tools.map(\.name), ["echo"])
|
|
await local.disconnect()
|
|
}
|
|
}
|
|
|
|
final class DesktopRuntimeTests: XCTestCase {
|
|
func testTextPreviewRespectsUTF8BoundaryAndRejectsBinary() throws {
|
|
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let file = directory.appending(path: "example.txt")
|
|
try Data("ab🙂xyz".utf8).write(to: file)
|
|
XCTAssertEqual(try LocalFilePreview.read(file, limit: 4), "ab\n[Preview truncated]")
|
|
XCTAssertEqual(try LocalFilePreview.read(file, limit: 10), "ab🙂xyz")
|
|
try Data([0, 255]).write(to: file)
|
|
XCTAssertThrowsError(try LocalFilePreview.read(file))
|
|
XCTAssertThrowsError(try LocalFilePreview.read(directory))
|
|
}
|
|
|
|
func testMLXWeightSizingCountsShardsAndDeduplicatesSymlinks() throws {
|
|
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
let manager = FileManager.default
|
|
try manager.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
defer { try? manager.removeItem(at: directory) }
|
|
let first = directory.appending(path: "first.safetensors")
|
|
try Data(repeating: 7, count: 32).write(to: first)
|
|
try Data(repeating: 8, count: 18).write(to: directory.appending(path: "second.safetensors"))
|
|
try Data(repeating: 9, count: 9).write(to: directory.appending(path: "config.json"))
|
|
try manager.createSymbolicLink(at: directory.appending(path: "alias.safetensors"), withDestinationURL: first)
|
|
XCTAssertEqual(try MLXRuntimeLimits.weightBytes(in: directory), 50)
|
|
}
|
|
}
|
|
|
|
final class CustomMCPConfigurationTests: XCTestCase {
|
|
func testCustomProfileParsesEnvAndHeaders() throws {
|
|
let configuration = try JSONDecoder().decode(MCPServerConfiguration.File.self, from: Data(#"""
|
|
{"mcpServers":{"remote":{"url":"https://example.com/mcp","headers":{"X-Example":"token"}},
|
|
"local":{"command":"sh","args":["one","two with spaces"],"env":{"TEST_MCP_SETTING":"example"}}}}
|
|
"""#.utf8))
|
|
let local = try XCTUnwrap(configuration.mcpServers["local"])
|
|
XCTAssertEqual(local.args, ["one", "two with spaces"])
|
|
let launch = try MCPServerConfiguration.resolveCommand("sh", environment: local.env ?? [:], cwd: "/private/tmp")
|
|
XCTAssertTrue(launch.executable.path.hasSuffix("/sh"))
|
|
XCTAssertEqual(launch.environment["TEST_MCP_SETTING"], "example")
|
|
XCTAssertEqual(launch.workingDirectory?.path, "/private/tmp")
|
|
XCTAssertNoThrow(try configuration.mcpServers["remote"]?.makeClient())
|
|
XCTAssertThrowsError(try HTTPMCPClient(endpoint: "https://example.com/mcp", headers: ["Host": "elsewhere"]))
|
|
}
|
|
|
|
func testInstalledKnowledgeServerDiscovery() async throws {
|
|
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_MCP_CONFIG"] else {
|
|
throw XCTSkip("Set AISTUDIO_TEST_REAL_MCP_CONFIG to the installed configuration.")
|
|
}
|
|
let configuration = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path))
|
|
let profile = try XCTUnwrap(configuration.mcpServers["local-knowledge"])
|
|
let client = try profile.makeClient()
|
|
let tools = try await client.listTools()
|
|
XCTAssertTrue(tools.contains { $0.name == "search_knowledge" })
|
|
}
|
|
|
|
func testRepairedGiteaProfileDiscovery() 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 profile smoke test explicitly.")
|
|
}
|
|
let config = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path))
|
|
let profile = try XCTUnwrap(config.mcpServers["absdev-gitea"])
|
|
let client = try profile.makeClient()
|
|
let tools = try await client.listTools()
|
|
XCTAssertFalse(tools.isEmpty)
|
|
}
|
|
|
|
func testGenerationMeasurementsRoundTripAndCharacterRate() throws {
|
|
let run = GenerationMeasurement(backend: "Fixture", firstOutput: 1, seconds: 3, characters: 40,
|
|
provider: ProviderMetrics(tokens: 7, seconds: 0), outcome: "Complete")
|
|
let copy = try JSONDecoder().decode(GenerationMeasurement.self, from: JSONEncoder().encode(run))
|
|
XCTAssertEqual(copy.id, run.id)
|
|
XCTAssertEqual(copy.charactersPerSecond, 20)
|
|
XCTAssertEqual(copy.provider?.tokens, 7)
|
|
XCTAssertNil(copy.provider?.tokensPerSecond)
|
|
}
|
|
}
|
|
|
|
final class WorkspaceLibraryTests: XCTestCase {
|
|
func testStackIsReusableAndBackupRestoresWorkspaceResources() 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 store = try Store(url: folder.appending(path: "workspace.sqlite"))
|
|
let backup = folder.appending(path: "backup.sqlite")
|
|
let stack = try store.createKnowledgeStack(title: "Customer Help")
|
|
let chat = try store.create(title: "Chat")
|
|
let key = UUID()
|
|
try store.addDocument(title: "Reference", chunks: ["This answer describes tides."],
|
|
vectors: [DocumentVector(language: "fixture", values: [1, 0])], in: stack.id)
|
|
try store.saveSnippet(id: key, kind: .prompt, title: "Reusable Prompt", content: "Explain tides")
|
|
try store.exportWorkspace(to: backup)
|
|
XCTAssertEqual(try store.conversations().map(\.id), [chat.id])
|
|
XCTAssertTrue(try store.searchConversations("Customer Help").isEmpty)
|
|
try store.delete(stack.id)
|
|
try store.deleteSnippet(key)
|
|
try store.restoreWorkspace(from: backup)
|
|
XCTAssertEqual(try store.knowledgeStacks().map(\.id), [stack.id])
|
|
XCTAssertEqual(try store.vectorCount(in: stack.id), 1)
|
|
XCTAssertEqual(try store.excerpts(matching: "tides", in: stack.id).first?.title, "Reference")
|
|
XCTAssertEqual(try store.snippets().first?.content, "Explain tides")
|
|
}
|
|
|
|
func testReturnSendsWithoutInterruptingNewlinesOrInputComposition() {
|
|
XCTAssertTrue(ChatComposerInput.sendsReturn(modifiers: [], marked: false))
|
|
XCTAssertFalse(ChatComposerInput.sendsReturn(modifiers: .shift, marked: false))
|
|
XCTAssertFalse(ChatComposerInput.sendsReturn(modifiers: .option, marked: false))
|
|
XCTAssertFalse(ChatComposerInput.sendsReturn(modifiers: [], marked: true))
|
|
}
|
|
|
|
func testWebClipExtractsStaticText() throws {
|
|
let content = WebClipCapture.plainText("""
|
|
<head><title>Hidden</title></head><script>ignore()</script><h1>Title</h1><p>Two & three</p>
|
|
""")
|
|
XCTAssertEqual(content, "Title\nTwo & three")
|
|
XCTAssertThrowsError(try WebClipCapture.url("file:///etc/hosts"))
|
|
XCTAssertNoThrow(try WebClipCapture.url("https://example.com"))
|
|
}
|
|
}
|
|
|
|
final class WebToolsTests: XCTestCase {
|
|
func testSearchAndRetrieveKeepSourceURLs() async throws {
|
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"] else {
|
|
throw XCTSkip("Run Scripts/test.sh to configure the web fixture.")
|
|
}
|
|
let results = try await WebSearch.results(endpoint: endpoint, query: "tides & moon")
|
|
XCTAssertEqual(results.count, 1)
|
|
let result = try XCTUnwrap(results.first)
|
|
XCTAssertEqual(result.title, "Moon and tides")
|
|
XCTAssertEqual(result.snippet, "A fixture & summary")
|
|
let page = try await WebClipCapture.page(from: result.url.absoluteString)
|
|
XCTAssertEqual(page.url, result.url)
|
|
XCTAssertEqual(page.text, "Moon and tides\nTest passage.")
|
|
XCTAssertTrue(page.reference.contains(result.url.absoluteString))
|
|
}
|
|
}
|
|
|
|
final class BuiltInToolsetTests: XCTestCase {
|
|
func testDiscoveryAndEmptyQueryValidationWithoutExternalServer() async throws {
|
|
let client = BuiltInWebTools(searchEndpoint: "")
|
|
let tools = try await client.listTools()
|
|
XCTAssertEqual(tools.map(\.name), ["retrieve_page", "web_search"])
|
|
do {
|
|
_ = try await client.callTool("web_search", argumentsJSON: Data(#"{}"#.utf8))
|
|
XCTFail("Expected a missing query error")
|
|
} catch let error as StudioError {
|
|
XCTAssertTrue(error.message.contains("query"))
|
|
}
|
|
}
|
|
|
|
func testBuiltInToolsReturnSourcesThroughMCPInterface() async throws {
|
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"] else {
|
|
throw XCTSkip("Run Scripts/test.sh to configure the web fixture.")
|
|
}
|
|
let client: any MCPToolClient = BuiltInWebTools(searchEndpoint: endpoint)
|
|
let result = try await client.callTool("web_search", argumentsJSON: Data(#"{"query":"tides & moon"}"#.utf8))
|
|
let items = try XCTUnwrap(JSONSerialization.jsonObject(with: result) as? [[String: String]])
|
|
let address = try XCTUnwrap(items.first?["url"])
|
|
let args = try JSONEncoder().encode(["url": address])
|
|
let response = try await client.callTool("retrieve_page", argumentsJSON: args)
|
|
let page = try XCTUnwrap(JSONSerialization.jsonObject(with: response) as? [String: String])
|
|
XCTAssertEqual(page["url"], address)
|
|
XCTAssertEqual(page["text"], "Moon and tides\nTest passage.")
|
|
}
|
|
}
|
|
|
|
final class ToolboxRepairTests: XCTestCase {
|
|
func testChatDetectsLaravelDocumentationWithoutAScheme() throws {
|
|
let lookup = try XCTUnwrap(ChatWebLookup(message: "Explain Laravel Gates using laravel.com/docs/13.x"))
|
|
guard case .pages(let urls) = lookup else { return XCTFail("Expected page retrieval") }
|
|
XCTAssertEqual(urls.first?.absoluteString, "https://laravel.com/docs/13.x")
|
|
}
|
|
|
|
func testWebExcerptIncludesRelevantSectionAfterNavigation() {
|
|
let navigation = String(repeating: "Home · Releases · Upgrade\n", count: 100)
|
|
let passage = "Service Container\nThe container resolves dependencies."
|
|
let excerpt = ChatWebLookup.excerpt(navigation + passage, matching: ["service", "container"], limit: 100)
|
|
XCTAssertTrue(excerpt.contains(passage))
|
|
}
|
|
|
|
func testChatWebLookupResolvesTypedURLAndExplicitSearch() 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.")
|
|
}
|
|
XCTAssertNil(ChatWebLookup(message: "Explain tides generally"))
|
|
let page = base.appending(path: "article")
|
|
let retrieval = try XCTUnwrap(ChatWebLookup(message: "Can you see \(page.absoluteString)?"))
|
|
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."))
|
|
let follow = try XCTUnwrap(ChatWebLookup(message: "Find tides documentation at \(base.appending(path: "follow-root"))"))
|
|
let followed = try await follow.resolve(searchEndpoint: "", prompt: "Find tides documentation")
|
|
XCTAssertTrue(followed.reference.contains("The tides documentation was followed."))
|
|
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.")
|
|
}
|
|
let lookup = try XCTUnwrap(ChatWebLookup(message: "Can you look up " + query))
|
|
let result = try await lookup.resolve(searchEndpoint: "")
|
|
XCTAssertTrue(result.reference.contains("Source: https://"), result.status)
|
|
XCTAssertTrue(result.diagnostics.contains { $0.hasPrefix("Fetched ") }, result.status)
|
|
}
|
|
|
|
func testLiveLaravelRetrieval() async throws {
|
|
guard let address = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_WEB_PAGE"] else {
|
|
throw XCTSkip("Set AISTUDIO_TEST_REAL_WEB_PAGE to check a real page.")
|
|
}
|
|
let lookup = try XCTUnwrap(ChatWebLookup(message: "Can you see \(address)"))
|
|
let result = try await lookup.resolve(searchEndpoint: "")
|
|
XCTAssertTrue(result.reference.contains("Laravel"))
|
|
XCTAssertEqual(result.status, "Retrieved 1 web source(s).")
|
|
}
|
|
|
|
func testModelDecodingAndMLXFolderScan() throws {
|
|
let model = try JSONDecoder().decode(Ollama.Model.self, from: Data(#"{"model":"example:latest"}"#.utf8))
|
|
XCTAssertEqual(model.name, "example:latest")
|
|
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let modelFolder = root.appending(path: "team/example")
|
|
try FileManager.default.createDirectory(at: modelFolder, withIntermediateDirectories: true)
|
|
try Data("{}".utf8).write(to: modelFolder.appending(path: "config.json"))
|
|
try Data([1]).write(to: modelFolder.appending(path: "model.safetensors"))
|
|
let found = try MLXLibrary.discover(in: root)
|
|
XCTAssertEqual(found.map(\.lastPathComponent), ["example"])
|
|
}
|
|
|
|
func testExternalVectorQueryReferencesSources() async throws {
|
|
struct Knowledge: MCPToolClient {
|
|
func listTools() async throws -> [MCPTool] { [] }
|
|
func callTool(_ name: String, argumentsJSON: Data) async throws -> Data {
|
|
XCTAssertEqual(name, "search_knowledge")
|
|
let data = try HTTPMCPClient.arguments(argumentsJSON)
|
|
XCTAssertEqual(data["query"] as? String, "tides")
|
|
XCTAssertEqual(data["limit"] as? Int, 5)
|
|
return Data(#"{"content":[{"type":"text","text":"{\"source\":\"notes.md\",\"content\":\"Tides excerpt.\"}"}]}"#.utf8)
|
|
}
|
|
}
|
|
let context = try await ExternalKnowledgeSearch.references(client: Knowledge(), query: "tides")
|
|
XCTAssertEqual(context.sources, ["notes.md"])
|
|
XCTAssertTrue(context.reference.contains("Tides excerpt."))
|
|
}
|
|
}
|
|
|
|
final class MultipleToolsetsTests: XCTestCase {
|
|
private struct MockClient: MCPToolClient {
|
|
let identifier: String
|
|
|
|
func listTools() async throws -> [MCPTool] {
|
|
[MCPTool(name: "echo", description: "", inputSchemaJSON: Data("{}".utf8))]
|
|
}
|
|
|
|
func callTool(_ name: String, argumentsJSON: Data) async throws -> Data {
|
|
try await Task.sleep(for: .milliseconds(150))
|
|
return Data(identifier.utf8)
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
func testStartupRestoresEnabledProfilesAndBuiltInWeb() async throws {
|
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_MCP_URLS"]?
|
|
.split(separator: ",").first else { throw XCTSkip("Run Scripts/test.sh to start the MCP fixture.") }
|
|
let id = UUID().uuidString
|
|
let defaults = try XCTUnwrap(UserDefaults(suiteName: id))
|
|
let file = FileManager.default.temporaryDirectory.appending(path: "\(id).json")
|
|
defer {
|
|
defaults.removePersistentDomain(forName: id)
|
|
try? FileManager.default.removeItem(at: file)
|
|
}
|
|
let profile = ["url": String(endpoint)]
|
|
try JSONEncoder().encode(["mcpServers": ["enabled": profile, "unused": profile]]).write(to: file)
|
|
defaults.set(file.path, forKey: "mcpConfigPath")
|
|
let first = StudioModel()
|
|
first.restoreToolsets(defaults: defaults)
|
|
try await waitUntil { first.activeToolsets.map(\.id) == [.web] }
|
|
first.setMCPProfile("enabled", enabled: true, path: file.path, defaults: defaults)
|
|
try await waitUntil { first.mcpConnections[.profile("enabled")]?.toolset != nil }
|
|
|
|
let reopened = StudioModel()
|
|
reopened.restoreToolsets(defaults: defaults)
|
|
try await waitUntil { reopened.activeToolsets.count == 2 }
|
|
XCTAssertNotNil(reopened.mcpConnections[.web]?.toolset)
|
|
XCTAssertNotNil(reopened.mcpConnections[.profile("enabled")]?.toolset)
|
|
XCTAssertNil(reopened.mcpConnections[.profile("unused")])
|
|
|
|
reopened.setMCPProfile("enabled", enabled: false, path: file.path, defaults: defaults)
|
|
let afterDisable = StudioModel()
|
|
afterDisable.restoreToolsets(defaults: defaults)
|
|
try await waitUntil { afterDisable.activeToolsets.map(\.id) == [.web] }
|
|
XCTAssertNil(afterDisable.mcpConnections[.profile("enabled")])
|
|
defaults.set(false, forKey: "builtInWebEnabled")
|
|
afterDisable.restoreToolsets(defaults: defaults)
|
|
XCTAssertNil(afterDisable.mcpConnections[.web])
|
|
}
|
|
|
|
@MainActor
|
|
func testSeparateConnectionsRunCallsAndRetainResultsIndependently() async throws {
|
|
let studio = StudioModel()
|
|
let first = MCPConnectionID.profile("First")
|
|
let second = MCPConnectionID.profile("Second")
|
|
studio.connectMCP(first, name: "First") { MockClient(identifier: "first result") }
|
|
studio.connectMCP(second, name: "Second") { MockClient(identifier: "second result") }
|
|
try await waitUntil { studio.activeToolsets.count == 2 }
|
|
studio.invokeMCP(first, tool: "echo", arguments: Data("{}".utf8), searchEndpoint: "")
|
|
studio.invokeMCP(second, tool: "echo", arguments: Data("{}".utf8), searchEndpoint: "")
|
|
XCTAssertNotNil(studio.mcpConnections[first]?.progress)
|
|
XCTAssertNotNil(studio.mcpConnections[second]?.progress)
|
|
try await waitUntil {
|
|
studio.mcpConnections[first]?.completedTool == "echo" &&
|
|
studio.mcpConnections[second]?.completedTool == "echo"
|
|
}
|
|
XCTAssertEqual(studio.mcpConnections[first]?.output, "first result")
|
|
XCTAssertEqual(studio.mcpConnections[second]?.output, "second result")
|
|
studio.disconnectMCP(first)
|
|
XCTAssertNil(studio.mcpConnections[first])
|
|
XCTAssertEqual(studio.activeToolsets.map(\.id), [second])
|
|
}
|
|
|
|
@MainActor
|
|
func testInstalledServersAndBuiltInWebCanStayConnectedTogether() 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 MCP profiles smoke test explicitly.")
|
|
}
|
|
let config = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path))
|
|
let studio = StudioModel()
|
|
for name in ["absdev-gitea", "local-knowledge"] {
|
|
let profile = try XCTUnwrap(config.mcpServers[name])
|
|
studio.connectMCP(.profile(name), name: name) { try profile.makeClient() }
|
|
}
|
|
studio.connectMCP(.web, name: BuiltInWebTools.name) { BuiltInWebTools(searchEndpoint: "") }
|
|
try await waitUntil { studio.activeToolsets.count == 3 }
|
|
XCTAssertNotNil(studio.connectedKnowledge)
|
|
studio.disconnectMCP(.profile("absdev-gitea"))
|
|
XCTAssertNotNil(studio.mcpConnections[.web]?.toolset)
|
|
XCTAssertNotNil(studio.connectedKnowledge)
|
|
studio.disconnectMCP(.profile("local-knowledge"))
|
|
studio.disconnectMCP(.web)
|
|
}
|
|
|
|
@MainActor
|
|
private func waitUntil(_ condition: @escaping () -> Bool) async throws {
|
|
let deadline = ContinuousClock.now + .seconds(5)
|
|
while !condition(), ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
XCTAssertTrue(condition())
|
|
}
|
|
}
|
|
|
|
final class ConnectedChatTests: XCTestCase {
|
|
struct Server: MCPToolClient {
|
|
let name: String
|
|
let result: Data
|
|
func listTools() async throws -> [MCPTool] {
|
|
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.") }
|
|
return result
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
func testWorkspaceRelocationPreservesDatabase() throws {
|
|
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
let defaults = try XCTUnwrap(UserDefaults(suiteName: root.lastPathComponent))
|
|
defer {
|
|
defaults.removePersistentDomain(forName: root.lastPathComponent)
|
|
try? FileManager.default.removeItem(at: root)
|
|
}
|
|
let studio = StudioModel()
|
|
let original = root.appending(path: "original.sqlite")
|
|
studio.open(databaseURL: original)
|
|
studio.newChat()
|
|
let first = try XCTUnwrap(studio.selected)
|
|
let target = root.appending(path: "Relocated")
|
|
try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
|
|
try studio.relocateWorkspace(to: target, defaults: defaults)
|
|
XCTAssertEqual(defaults.string(forKey: "workspaceLocation"), target.path)
|
|
let copy = target.appending(path: "studio.sqlite")
|
|
XCTAssertTrue(Store.isWorkspaceBackup(copy))
|
|
XCTAssertEqual(try Store(url: copy).conversations().map(\.id), [first])
|
|
XCTAssertEqual(try Store(url: original).conversations().map(\.id), [first])
|
|
XCTAssertThrowsError(try studio.relocateWorkspace(to: target, defaults: defaults))
|
|
}
|
|
|
|
@MainActor
|
|
func testDeleteChatTargetsRequestedConversation() throws {
|
|
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let url = folder.appending(path: "studio.sqlite")
|
|
let studio = StudioModel()
|
|
studio.open(databaseURL: url)
|
|
studio.newChat()
|
|
let first = try XCTUnwrap(studio.selected)
|
|
studio.newChat()
|
|
let second = try XCTUnwrap(studio.selected)
|
|
studio.deleteChat(first)
|
|
XCTAssertEqual(studio.selected, second)
|
|
XCTAssertEqual(studio.conversations.map(\.id), [second])
|
|
XCTAssertEqual(try Store(url: url).conversations().map(\.id), [second])
|
|
}
|
|
|
|
@MainActor
|
|
func testLiveKnowledgeInventoryAnswersWithoutModel() async throws {
|
|
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_MCP_CONFIG"] else {
|
|
throw XCTSkip("Set a local knowledge MCP configuration to verify its inventory.")
|
|
}
|
|
let config = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path))
|
|
let profile = try XCTUnwrap(config.mcpServers["local-knowledge"])
|
|
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let studio = StudioModel()
|
|
studio.open(databaseURL: folder.appending(path: "studio.sqlite"))
|
|
studio.connectMCP(.profile("local-knowledge"), name: "local-knowledge") { try profile.makeClient() }
|
|
studio.prompt = "List all documents in our knowledge base"
|
|
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(30)
|
|
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(50)) }
|
|
XCTAssertFalse(studio.running)
|
|
let reply = try XCTUnwrap(studio.messages.last)
|
|
XCTAssertEqual(reply.role, .assistant, studio.knowledgeStatus)
|
|
XCTAssertEqual(reply.backend, "Knowledge Inventory · local-knowledge")
|
|
let listed = reply.content.split(separator: "\n").filter { $0.hasPrefix("• ") }
|
|
XCTAssertGreaterThan(listed.count, 200)
|
|
XCTAssertEqual(Set(listed).count, listed.count)
|
|
studio.prompt = "What is in our knowledge base?"
|
|
studio.send(endpoint: "", model: "", mlxPath: "", thinking: .off, failover: false,
|
|
mlxOnly: false, compatible: false, recall: false, useDocuments: false,
|
|
instructions: "", settings: GenerationSettings())
|
|
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(50)) }
|
|
XCTAssertFalse(studio.running)
|
|
let overview = try XCTUnwrap(studio.messages.last)
|
|
XCTAssertTrue(overview.content.contains("Topic overview for \(listed.count.formatted()) indexed sources"))
|
|
XCTAssertTrue(overview.content.contains("**Development standards**"))
|
|
XCTAssertTrue(overview.content.contains("**PHP and Laravel**"))
|
|
}
|
|
|
|
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")
|
|
XCTAssertGreaterThan(result.count, 0)
|
|
XCTAssertFalse(result.sources.isEmpty)
|
|
}
|
|
|
|
@MainActor
|
|
func testGreetingSkipsConnectedKnowledgeAndAutomaticThinking() async throws {
|
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_OLLAMA_GATEWAY_URL"] else {
|
|
throw XCTSkip("Run Scripts/test.sh to configure the Ollama 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.setOllamaToken("fixture-token", endpoint: endpoint)
|
|
studio.connectMCP(.profile("knowledge"), name: "Knowledge") {
|
|
Server(name: "search_knowledge", result: Data(#"{"structuredContent":{"result":[{"source":"unrelated.pdf","content":"A passage about Python."}]}}"#.utf8))
|
|
}
|
|
let deadline = ContinuousClock.now + .seconds(8)
|
|
while studio.connectedKnowledge == nil && ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
XCTAssertNotNil(studio.connectedKnowledge)
|
|
studio.prompt = "hello"
|
|
studio.send(endpoint: endpoint, model: "fixture:latest", mlxPath: "", thinking: .automatic,
|
|
failover: false, mlxOnly: false, compatible: false, recall: true,
|
|
useDocuments: false, instructions: "", settings: GenerationSettings())
|
|
while studio.running && ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
XCTAssertEqual(studio.messages.last?.content, "Hello!", studio.status)
|
|
XCTAssertTrue(studio.knowledgeSources.isEmpty)
|
|
XCTAssertTrue(studio.knowledgeStatus.isEmpty)
|
|
}
|
|
|
|
@MainActor
|
|
func testChatSendsConnectedKnowledgeAndGiteaWithoutExtraSelection() 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.connectMCP(.profile("knowledge"), name: "Knowledge") {
|
|
Server(name: "search_knowledge", result: Data(#"{"structuredContent":{"result":[{"source":"knowledge.md","content":"A matching passage."}]}}"#.utf8))
|
|
}
|
|
studio.connectMCP(.profile("gitea"), name: "Gitea") {
|
|
Server(name: "list_repositories", result: Data(#"{"structuredContent":{"result":[{"full_name":"fixture/visible-repo"}]}}"#.utf8))
|
|
}
|
|
let deadline = ContinuousClock.now + .seconds(8)
|
|
XCTAssertTrue(studio.activeToolsets.isEmpty)
|
|
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())
|
|
while studio.running && ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
XCTAssertEqual(studio.messages.last?.content, "Repository and knowledge received.")
|
|
XCTAssertEqual(studio.webStatus, "Gitea repositories checked.")
|
|
XCTAssertEqual(studio.knowledgeSources, ["knowledge.md"])
|
|
}
|
|
|
|
@MainActor
|
|
func testTwoChatSessionsGenerateConcurrentlyAndPersistSeparately() 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 folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let database = folder.appending(path: "studio.sqlite")
|
|
let left = StudioModel()
|
|
let right = StudioModel()
|
|
left.open(databaseURL: database)
|
|
right.open(databaseURL: database)
|
|
left.newChat()
|
|
right.newChat()
|
|
let first = try XCTUnwrap(left.selected)
|
|
let second = try XCTUnwrap(right.selected)
|
|
for studio in [left, right] {
|
|
studio.prompt = "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())
|
|
}
|
|
XCTAssertTrue(left.running && right.running)
|
|
let deadline = ContinuousClock.now + .seconds(8)
|
|
while (left.running || right.running) && ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
let store = try Store(url: database)
|
|
XCTAssertNotEqual(first, second)
|
|
XCTAssertEqual(try store.messages(in: first).last?.content, "Page received.")
|
|
XCTAssertEqual(try store.messages(in: second).last?.content, "Page received.")
|
|
}
|
|
|
|
@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.")
|
|
XCTAssertEqual(studio.messages.last?.webSources.first?.kind, .page)
|
|
}
|
|
|
|
@MainActor
|
|
func testLiveOllamaChatUsesRetrievedPage() async throws {
|
|
guard let model = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_OLLAMA_MODEL"] else {
|
|
throw XCTSkip("Choose a local Ollama model to verify live chat.")
|
|
}
|
|
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 = "Read https://laravel.com and reply with the name of the framework and the source URL."
|
|
var settings = GenerationSettings()
|
|
settings.maxTokens = "128"
|
|
studio.send(endpoint: "http://127.0.0.1:11434", model: model, mlxPath: "",
|
|
thinking: .off, failover: false, mlxOnly: false, compatible: false,
|
|
recall: false, useDocuments: false, instructions: "", settings: settings)
|
|
let deadline = ContinuousClock.now + .seconds(60)
|
|
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(100)) }
|
|
XCTAssertFalse(studio.running)
|
|
XCTAssertTrue(studio.webDiagnostics.contains { $0.contains("Fetched laravel.com") })
|
|
XCTAssertEqual(studio.messages.last?.role, .assistant)
|
|
XCTAssertTrue(studio.messages.last?.content.contains("https://laravel.com") == true, studio.status)
|
|
}
|
|
|
|
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 client = try await GiteaRepositoryLookup.configuredClient(pathOverride: path)
|
|
let result = try await GiteaRepositoryLookup.references(client: client)
|
|
XCTAssertFalse(result.contains("Gitea returned no repository entries."))
|
|
}
|
|
}
|
|
|
|
final class ChatFilePreviewTests: XCTestCase {
|
|
func testChatCanTraverseAndWriteWithinSelectedFolder() throws {
|
|
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let nested = root.appending(path: "nested/deep")
|
|
try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true)
|
|
let write = try ChatFileRequest.Write("/write nested/deep/note.txt\nhello")
|
|
let destination = try ChatFileRequest.write(write, inside: root.path, replace: false)
|
|
XCTAssertEqual(try String(contentsOf: destination, encoding: .utf8), "hello")
|
|
XCTAssertThrowsError(try ChatFileRequest.write(write, inside: root.path, replace: false))
|
|
let updated = try ChatFileRequest.Write("/write nested/deep/note.txt\nupdated")
|
|
_ = try ChatFileRequest.write(updated, inside: root.path, replace: true)
|
|
XCTAssertEqual(try ChatFileRequest.read("nested/deep/note.txt", inside: root.path).text, "updated")
|
|
XCTAssertTrue(try ChatFileRequest.read(root.path, inside: root.path, recursive: true).text.contains("nested/deep/note.txt"))
|
|
let escape = try ChatFileRequest.Write("/write ../outside.txt\nblocked")
|
|
XCTAssertThrowsError(try ChatFileRequest.write(escape, inside: root.path, replace: false))
|
|
}
|
|
|
|
func testExplicitChatFileAccessUsesSelectedScope() throws {
|
|
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let allowed = root.appending(path: "Project")
|
|
try FileManager.default.createDirectory(at: allowed, withIntermediateDirectories: true)
|
|
let outside = root.appending(path: "outside.txt")
|
|
try "Outside".write(to: outside, atomically: true, encoding: .utf8)
|
|
let file = allowed.appending(path: "hello world.txt")
|
|
try "Inside".write(to: file, atomically: true, encoding: .utf8)
|
|
let alias = allowed.appending(path: "escape.txt")
|
|
try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: outside)
|
|
XCTAssertEqual(ChatFileRequest.path(in: #"/read "hello world.txt""#), "hello world.txt")
|
|
XCTAssertEqual(try ChatFileRequest.read("hello world.txt", inside: allowed.path).text, "Inside")
|
|
XCTAssertThrowsError(try ChatFileRequest.read("escape.txt", inside: allowed.path))
|
|
XCTAssertThrowsError(try ChatFileRequest.read(file.path, inside: ""))
|
|
XCTAssertEqual(try ChatFileRequest.read(outside.path, inside: "/").text, "Outside")
|
|
}
|
|
|
|
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"))
|
|
}
|
|
}
|
|
|
|
final class AgentWorkflowTests: XCTestCase {
|
|
@MainActor
|
|
func testAgentsHandOffWorkAndReturnReviewerAnswer() async throws {
|
|
var prompts: [[Message]] = []
|
|
var stages: [AgentRole] = []
|
|
let result = try await AgentWorkflow.run(
|
|
roles: [.planner, .specialist, .reviewer],
|
|
context: [.init(role: .user, content: "Compare these designs.")],
|
|
generate: { messages in
|
|
prompts.append(messages)
|
|
let answer = "result \(prompts.count)"
|
|
return AsyncThrowingStream { continuation in
|
|
continuation.yield(.answer(answer))
|
|
continuation.finish()
|
|
}
|
|
},
|
|
progress: { stages.append($0) }
|
|
)
|
|
XCTAssertEqual(stages, [.planner, .specialist, .reviewer])
|
|
XCTAssertEqual(prompts.count, 3)
|
|
XCTAssertTrue(prompts[2].contains { $0.content.contains("result 1") })
|
|
XCTAssertTrue(prompts[2].contains { $0.content.contains("result 2") })
|
|
XCTAssertEqual(result.content, "result 3")
|
|
}
|
|
|
|
func testMissingAndInvalidSizesAreExplicit() {
|
|
XCTAssertEqual(ModelLibrarySize.label(nil), "Size unknown")
|
|
XCTAssertEqual(ModelLibrarySize.label(0), "Size unknown")
|
|
XCTAssertEqual(ModelLibrarySize.label(-1), "Size unknown")
|
|
XCTAssertNotEqual(ModelLibrarySize.label(6_600_000_000), "Size unknown")
|
|
}
|
|
|
|
func testSelectionIncludesBackendAndNormalizesMLXFolders() {
|
|
let mlx = ModelLibrarySelection(mlxOnly: true, compatible: true, mlxPath: "/tmp/models/A/", ollamaModel: "a")
|
|
XCTAssertTrue(mlx.isMLX("/tmp/models/A"))
|
|
XCTAssertFalse(mlx.isOllama("a"))
|
|
let ollama = ModelLibrarySelection(mlxOnly: false, compatible: false, mlxPath: "/tmp/models/A", ollamaModel: "a")
|
|
XCTAssertTrue(ollama.isOllama("a"))
|
|
XCTAssertFalse(ollama.isMLX("/tmp/models/A"))
|
|
let compatible = ModelLibrarySelection(mlxOnly: false, compatible: true, mlxPath: "", ollamaModel: "a")
|
|
XCTAssertFalse(compatible.isOllama("a"))
|
|
}
|
|
}
|
|
|
|
extension AgentWorkflowTests {
|
|
@MainActor
|
|
func testSpecialistToolResultReturnsToModelBeforeReview() async throws {
|
|
var prompts: [[Message]] = []
|
|
var requests: [AgentToolRequest] = []
|
|
_ = try await AgentWorkflow.run(
|
|
roles: [.specialist, .reviewer],
|
|
context: [.init(role: .user, content: "Summarize the connected index.")],
|
|
generate: { messages in
|
|
prompts.append(messages)
|
|
let answer = prompts.count == 1 ? #"{"tool":1,"arguments":{"query":"index"}}"# : "Summary"
|
|
return AsyncThrowingStream { continuation in
|
|
continuation.yield(.answer(answer))
|
|
continuation.finish()
|
|
}
|
|
},
|
|
progress: { _ in },
|
|
tools: ["1: Search the index"],
|
|
callTool: { request in
|
|
requests.append(request)
|
|
return "Index evidence"
|
|
}
|
|
)
|
|
XCTAssertEqual(requests.map(\.tool), [1])
|
|
XCTAssertEqual(prompts.count, 3)
|
|
XCTAssertTrue(prompts[1].contains { $0.content.contains("Index evidence") })
|
|
XCTAssertTrue(prompts[2].contains { $0.content.contains("Summary") })
|
|
}
|
|
|
|
@MainActor
|
|
func testAgentChatUsesAuthenticatedOllamaAndPersistsFinalReply() async throws {
|
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_OLLAMA_GATEWAY_URL"] else {
|
|
throw XCTSkip("Run Scripts/test.sh to configure the Ollama fixture.")
|
|
}
|
|
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: folder) }
|
|
let database = folder.appending(path: "studio.sqlite")
|
|
let studio = StudioModel()
|
|
studio.open(databaseURL: database)
|
|
studio.setOllamaToken("fixture-token", endpoint: endpoint)
|
|
studio.prompt = "Compare two designs."
|
|
studio.send(endpoint: endpoint, model: "fixture:latest", mlxPath: "", thinking: .off,
|
|
failover: false, mlxOnly: false, compatible: false, recall: false,
|
|
useDocuments: false, instructions: "", settings: GenerationSettings(),
|
|
agents: [.planner, .specialist, .reviewer])
|
|
let deadline = ContinuousClock.now + .seconds(10)
|
|
while studio.running && ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
XCTAssertFalse(studio.running)
|
|
XCTAssertEqual(studio.agentSteps.count, 3, studio.status)
|
|
XCTAssertNil(studio.agentStage)
|
|
let chat = try XCTUnwrap(studio.selected)
|
|
let messages = try Store(url: database).messages(in: chat)
|
|
XCTAssertEqual(messages.map(\.content), ["Compare two designs.", "fixture answer"])
|
|
XCTAssertEqual(messages.last?.backend, "Ollama · fixture:latest")
|
|
}
|
|
}
|
|
|
|
extension AgentWorkflowTests {
|
|
@MainActor
|
|
func testSavedCustomAgentReceivesItsInstructions() async throws {
|
|
let profile = AgentProfile(name: "Technical Editor", instructions: "Keep the public API examples intact.")
|
|
let profiles = AgentProfile.read(try JSONEncoder().encode([profile]))
|
|
XCTAssertEqual(profiles, [profile])
|
|
var inputs: [[Message]] = []
|
|
_ = try await AgentWorkflow.run(
|
|
roles: [.custom(profile), .reviewer],
|
|
context: [.init(role: .user, content: "Revise this manual.")],
|
|
generate: { messages in
|
|
inputs.append(messages)
|
|
return AsyncThrowingStream { continuation in
|
|
continuation.yield(.answer("Edited manual"))
|
|
continuation.finish()
|
|
}
|
|
}, progress: { _ in }
|
|
)
|
|
XCTAssertTrue(inputs[0][0].content.contains("Technical Editor"))
|
|
XCTAssertTrue(inputs[0][0].content.contains("Keep the public API examples intact."))
|
|
XCTAssertTrue(inputs[1].contains { $0.content.contains("Technical Editor handoff") })
|
|
}
|
|
}
|
|
|
|
final class ModelPreviewTests: XCTestCase {
|
|
func testHubWeightSizeRequiresEverySelectedShard() throws {
|
|
let data = Data(#"{"siblings":[{"rfilename":"a.safetensors","size":1200},{"rfilename":"b.safetensors","lfs":{"size":3400}},{"rfilename":"unused.safetensors","size":5000}]}"#.utf8)
|
|
let metadata = try JSONDecoder().decode(HubModelMetadata.self, from: data)
|
|
XCTAssertEqual(metadata.weightBytes(files: ["a.safetensors", "b.safetensors", "config.json"]), 4600)
|
|
XCTAssertNil(metadata.weightBytes(files: ["a.safetensors", "missing.safetensors"]))
|
|
}
|
|
|
|
func testRegistryManifestAndInstalledOllamaMetadata() throws {
|
|
let data = Data(#"{"config":{"size":200},"layers":[{"size":10000},{"size":400},{"size":400}]}"#.utf8)
|
|
let manifest = try JSONDecoder().decode(OllamaRegistryManifest.self, from: data)
|
|
XCTAssertEqual(manifest.bytes, 11000)
|
|
let tags = try JSONDecoder().decode(Ollama.Model.self, from: Data(#"{"name":"test","details":{"family":"qwen","quantization_level":"Q4_K_M"}}"#.utf8))
|
|
XCTAssertEqual(tags.details?.family, "qwen")
|
|
XCTAssertEqual(tags.details?.quantization, "Q4_K_M")
|
|
let info = try JSONDecoder().decode(Ollama.ModelDetails.self, from: Data(#"{"capabilities":["completion"],"model_info":{"general.architecture":"qwen2","qwen2.context_length":32768,"qwen2.example":[1,2]}}"#.utf8))
|
|
XCTAssertEqual(info.architecture, "qwen2")
|
|
XCTAssertEqual(info.contextLength, 32768)
|
|
|
|
let mlx = try MLXModelConfiguration.decode(Data(#"{"architectures":["QwenForCausalLM"],"quantization_config":{"bits":4},"text_config":{"max_position_embeddings":32768}}"#.utf8))
|
|
XCTAssertEqual(mlx.architectures, ["QwenForCausalLM"])
|
|
XCTAssertEqual(mlx.quantizationConfig?.bits, 4)
|
|
XCTAssertEqual(mlx.textConfig?.maxPositionEmbeddings, 32768)
|
|
}
|
|
|
|
func testBuiltInOverridePreservesRoleAndAppliesEditedNameAndPrompt() throws {
|
|
let profile = AgentProfile(name: "Evidence Researcher", instructions: "Check the supplied sources.")
|
|
let data = try JSONEncoder().encode(["Specialist": profile])
|
|
let role = AgentRole.specialist.applyingOverrides(data)
|
|
XCTAssertEqual(role.name, profile.name)
|
|
XCTAssertEqual(role.instructions, profile.instructions)
|
|
XCTAssertTrue(role.isSpecialist)
|
|
XCTAssertEqual(AgentRole.reviewer.applyingOverrides(data).name, "Reviewer")
|
|
}
|
|
}
|
|
|
|
final class ModelPopularityTests: XCTestCase {
|
|
func testMatchesKnownFamiliesAcrossOllamaTagsAndMLXRepositories() {
|
|
XCTAssertEqual(ModelPopularity.family(for: "llama3.2:3b"), "Llama")
|
|
XCTAssertEqual(ModelPopularity.family(for: "mlx-community/Qwen3-0.6B-4bit"), "Qwen")
|
|
XCTAssertEqual(ModelPopularity.family(for: "DeepSeek-R1-Distill-Qwen-7B"), "DeepSeek")
|
|
XCTAssertEqual(ModelPopularity.family(for: "google/gemma-3-4b-it"), "Gemma")
|
|
XCTAssertEqual(ModelPopularity.family(for: "mistralai/Mistral-7B-Instruct"), "Mistral")
|
|
}
|
|
|
|
func testIgnoresUnrelatedNamesAndTags() {
|
|
XCTAssertNil(ModelPopularity.family(for: "my-org/llamafarm"))
|
|
XCTAssertNil(ModelPopularity.family(for: "my-org/other:qwen3"))
|
|
XCTAssertNil(ModelPopularity.family(for: "some-finetune-based-on-gemma3"))
|
|
}
|
|
}
|
|
|
|
final class NativeTrainingTests: XCTestCase {
|
|
func testCloneCopiesSnapshotWeightsAndRejectsOverwrite() throws {
|
|
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let source = root.appending(path: "base")
|
|
let destination = root.appending(path: "new")
|
|
try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)
|
|
try Data("{}".utf8).write(to: source.appending(path: "config.json"))
|
|
let weights = root.appending(path: "weights")
|
|
try Data("weights".utf8).write(to: weights)
|
|
let link = source.appending(path: "model.safetensors")
|
|
try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: "../weights")
|
|
|
|
try MLXTraining.clone(source, to: destination)
|
|
let copy = destination.appending(path: "model.safetensors")
|
|
XCTAssertEqual(try Data(contentsOf: copy), Data("weights".utf8))
|
|
XCTAssertFalse(try copy.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink ?? true)
|
|
XCTAssertThrowsError(try MLXTraining.clone(source, to: destination))
|
|
XCTAssertThrowsError(try MLXTraining.clone(source, to: source.appending(path: "nested")))
|
|
}
|
|
|
|
func testTrainingJobBuildsArgumentsWithoutShellInterpolation() throws {
|
|
let runner = URL(fileURLWithPath: "/some path/train-mlx.py")
|
|
let base = URL(fileURLWithPath: "/local models/base")
|
|
let data = URL(fileURLWithPath: "/data/folder")
|
|
let output = URL(fileURLWithPath: "/results")
|
|
let job = MLXTraining(base: base, dataset: data, project: output, iterations: 80, layers: 6)
|
|
XCTAssertEqual(try job.arguments(for: .train, runner: runner), [
|
|
runner.path, "train", "--base", base.path, "--adapter", "/results/adapter",
|
|
"--data", data.path, "--iters", "80", "--layers", "6"
|
|
])
|
|
XCTAssertEqual(try job.arguments(for: .fuse, runner: runner).suffix(2), ["--out", "/results/trained-model"])
|
|
}
|
|
|
|
func testTrainingToolIsInApplicationResources() throws {
|
|
let url = try XCTUnwrap(Bundle.main.url(forResource: "train-mlx", withExtension: "py"))
|
|
XCTAssertTrue(try String(contentsOf: url, encoding: .utf8).contains("validate_dataset"))
|
|
}
|
|
}
|
|
|
|
|
|
extension NativeTrainingTests {
|
|
func testConversionArgumentsPreserveRevisionAndQuantizationChoice() {
|
|
let runner = URL(fileURLWithPath: "/app/train-mlx.py")
|
|
let output = URL(fileURLWithPath: "/models/new model")
|
|
XCTAssertEqual(MLXTraining.conversionArguments(runner: runner, source: "example/model",
|
|
revision: "exact-revision", output: output, quantize: true), [
|
|
runner.path, "convert", "--source", "example/model", "--out", output.path,
|
|
"--revision", "exact-revision", "--quantize"
|
|
])
|
|
}
|
|
|
|
@MainActor
|
|
func testTrainingOperationCapturesOutputAndCancelsRunningProcess() async throws {
|
|
let operation = TrainingOperation()
|
|
operation.run("Read output") {
|
|
try await operation.execute(URL(fileURLWithPath: "/usr/bin/printf"), ["ready"])
|
|
}
|
|
let deadline = ContinuousClock.now + .seconds(5)
|
|
while operation.active != nil && ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
XCTAssertEqual(operation.log, "ready")
|
|
XCTAssertEqual(operation.status, "Read output complete.")
|
|
|
|
operation.run("Wait") {
|
|
try await operation.execute(URL(fileURLWithPath: "/bin/sleep"), ["10"])
|
|
}
|
|
try await Task.sleep(for: .milliseconds(100))
|
|
operation.stop()
|
|
let stopDeadline = ContinuousClock.now + .seconds(3)
|
|
while operation.active != nil && ContinuousClock.now < stopDeadline {
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
XCTAssertEqual(operation.status, "Stopped.")
|
|
}
|
|
}
|
|
|
|
final class AutomaticWebRoutingTests: XCTestCase {
|
|
func testPublicQuestionAndFollowupResolveToTopic() {
|
|
let question = "How do I plaster a wall"
|
|
let history = [Message(role: .user, content: question)]
|
|
for input in [question, "So search teh web", "Can you search the web?"] {
|
|
guard case .search(let query)? = ChatWebLookup.forChat(message: input, recent: history, automatic: true) else {
|
|
XCTFail("Expected a web lookup for \(input)")
|
|
continue
|
|
}
|
|
XCTAssertEqual(query, question)
|
|
}
|
|
}
|
|
|
|
func testDefaultsRespectPersonalAndLocalRequestsAndOptOut() {
|
|
for input in ["How do I update our internal API?", "What is in the knowledge base?",
|
|
"How does this file work?", "Can you see my git repos?", "Hello"] {
|
|
XCTAssertNil(ChatWebLookup.forChat(message: input, recent: [], automatic: true))
|
|
}
|
|
XCTAssertNil(ChatWebLookup.forChat(message: "How do I plaster a wall", recent: [], automatic: false))
|
|
guard case .search("plastering")? = ChatWebLookup.forChat(
|
|
message: "/search plastering", recent: [], automatic: false
|
|
) else { return XCTFail("Explicit searches should remain available.") }
|
|
}
|
|
}
|
|
|
|
final class StudioWorkspaceCreationTests: XCTestCase {
|
|
@MainActor
|
|
func testSavesEachWorkspaceResourceAndReopensIt() throws {
|
|
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
let database = root.appending(path: "studio.sqlite")
|
|
let studio = StudioModel()
|
|
studio.open(databaseURL: database)
|
|
for kind in [WorkspaceSnippet.Kind.skill, .context, .webClip] {
|
|
XCTAssertTrue(studio.saveSnippet(id: UUID(), kind: kind, title: " New \(kind.rawValue) ", content: "Saved contents"))
|
|
}
|
|
XCTAssertFalse(studio.saveSnippet(id: UUID(), kind: .skill, title: " ", content: "Contents"))
|
|
let reopened = StudioModel()
|
|
reopened.open(databaseURL: database)
|
|
XCTAssertEqual(Set(reopened.snippets.map(\.title)), ["New Skill", "New Context", "New Web Clip"])
|
|
}
|
|
|
|
func testMatchesLocalAgentInventoryAndReadsEnabledProfiles() throws {
|
|
XCTAssertTrue(AgentInventory.matches("Can you see my local agents?"))
|
|
XCTAssertTrue(AgentInventory.matches("List my agents in AI Studio"))
|
|
XCTAssertFalse(AgentInventory.matches("How do I create agents in Laravel?"))
|
|
let name = UUID().uuidString
|
|
let defaults = try XCTUnwrap(UserDefaults(suiteName: name))
|
|
defer { defaults.removePersistentDomain(forName: name) }
|
|
defaults.set(false, forKey: "agentPlannerEnabled")
|
|
defaults.set(try JSONEncoder().encode([AgentProfile(name: "Editor", instructions: "Edit.")]), forKey: AgentProfile.storageKey)
|
|
XCTAssertTrue(AgentInventory.report(defaults: defaults).contains("Planner (Planner) · Disabled"))
|
|
XCTAssertTrue(AgentInventory.report(defaults: defaults).contains("Editor (Custom) · Enabled"))
|
|
}
|
|
|
|
func testPegasusStatsKeepExternalIndexingDistinct() throws {
|
|
let json = #"{"mounted":true,"documents":"/docs","database":"/index","running":false,"externalRunning":true,"sources":45,"chunks":56,"currentRootChunks":50}"#
|
|
let result = try JSONDecoder().decode(PegasusIndexStatus.self, from: Data(json.utf8))
|
|
XCTAssertTrue(result.indexing)
|
|
XCTAssertEqual(result.activity, "Indexing outside AI Studio")
|
|
XCTAssertEqual(result.currentRootChunks, 50)
|
|
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"))
|
|
}
|
|
}
|