Files
ai_studio/Tests/StudioTests.swift
T

675 lines
35 KiB
Swift

import XCTest
import AppKit
@testable import AIStudio
final class StudioTests: XCTestCase {
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 request = InferenceRequest(
model: directory, messages: [Message(role: .user, content: "Reply with one word: hello.")],
thinking: .automatic, parameters: GenerationParameters(temperature: 0, maxTokens: 64)
)
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 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()
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"])
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 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 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 &amp; 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 testDiscoveryAndSetupErrorWithoutExternalServer() 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(#"{"query":"tides"}"#.utf8))
XCTFail("Expected a configuration error")
} catch let error as StudioError {
XCTAssertTrue(error.message.contains("SearXNG"))
}
}
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 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))
let search = try XCTUnwrap(ChatWebLookup(message: "Search the web for tides & moon"))
let found = try await search.resolve(searchEndpoint: endpoint)
XCTAssertTrue(found.reference.contains("A fixture & summary"))
let unavailable = try await search.resolve(searchEndpoint: "")
XCTAssertTrue(unavailable.status.contains("SearXNG"))
}
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"}]}"#.utf8)
}
}
let context = try await ExternalKnowledgeSearch.references(client: Knowledge(), query: "tides")
XCTAssertTrue(context.contains("source: notes.md"))
}
}