Build AI Studio for macOS
Add branded startup, Ollama and MLX inference, persistent chat and document retrieval, confirmed MCP tools, and reproducible build and test scripts.
This commit is contained in:
@@ -0,0 +1,254 @@
|
||||
import XCTest
|
||||
@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)
|
||||
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
|
||||
))
|
||||
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()
|
||||
let request = InferenceRequest(
|
||||
model: directory, messages: [Message(role: .user, content: "Reply with one word: hello.")],
|
||||
thinking: .automatic
|
||||
)
|
||||
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
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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 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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user