2602 lines
144 KiB
Swift
2602 lines
144 KiB
Swift
import XCTest
|
||
import AppKit
|
||
import CoreText
|
||
import PDFKit
|
||
import SQLite3
|
||
@testable import AIStudio
|
||
|
||
final class StudioTests: XCTestCase {
|
||
func testGGUFHeaderRecognizesSupportedVersionsAndRejectsInvalidFiles() throws {
|
||
for version: UInt8 in [2, 3] {
|
||
XCTAssertEqual(try GGUFHeader.version(in: Data([71, 71, 85, 70, version, 0, 0, 0])), UInt32(version))
|
||
}
|
||
for bytes: [UInt8] in [[], [71, 71, 85, 70], [71, 71, 85, 70, 4, 0, 0, 0], [0, 71, 85, 70, 3, 0, 0, 0]] {
|
||
XCTAssertThrowsError(try GGUFHeader.version(in: Data(bytes)))
|
||
}
|
||
}
|
||
|
||
func testGGUFModelChoiceRoundTripsWithExistingBackends() throws {
|
||
let records = Dictionary(uniqueKeysWithValues: [
|
||
ChatModelChoice(backend: .gguf, model: "/Models/Example-Q4_K_M.gguf"),
|
||
ChatModelChoice(backend: .mlx, model: "/Models/MLX"),
|
||
ChatModelChoice(backend: .ollama, model: "test:latest"),
|
||
ChatModelChoice(backend: .compatible, model: "api-model")
|
||
].map { (UUID(), $0) })
|
||
XCTAssertEqual(ChatModelChoice.read(try JSONEncoder().encode(records)), records)
|
||
XCTAssertEqual(records.values.first(where: { $0.backend == .gguf })?.displayName, "Example-Q4_K_M")
|
||
}
|
||
|
||
func testGGUFProviderRejectsImagesBeforeLoadingAFile() async throws {
|
||
let request = InferenceRequest(model: "/missing.gguf", messages: [
|
||
Message(role: .user, content: "Describe this", imagePNG: Data([1]))
|
||
], thinking: .automatic)
|
||
do {
|
||
for try await _ in GGUFProvider().generate(request) {
|
||
XCTFail("Unexpected output for an image request")
|
||
}
|
||
XCTFail("Expected a text-only error")
|
||
} catch {
|
||
XCTAssertEqual(error.localizedDescription, "This GGUF backend supports text input.")
|
||
}
|
||
}
|
||
|
||
func testGGUFMetalStreamingWithLocalFixture() async throws {
|
||
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_GGUF_PATH"] else {
|
||
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_GGUF_PATH to a local GGUF chat fixture.")
|
||
}
|
||
var parameters = GenerationParameters()
|
||
parameters.temperature = 0
|
||
parameters.maxTokens = 8
|
||
var answer = ""
|
||
var backend = ""
|
||
var metrics: ProviderMetrics?
|
||
let request = InferenceRequest(model: path, messages: [.init(role: .user, content: "Once upon a time")],
|
||
thinking: .automatic, parameters: parameters)
|
||
for try await delta in GGUFProvider().generate(request) {
|
||
switch delta {
|
||
case .answer(let text): answer += text
|
||
case .backend(let value): backend = value
|
||
case .metrics(let value): metrics = value
|
||
case .thinking, .committed: break
|
||
}
|
||
}
|
||
XCTAssertFalse(answer.isEmpty)
|
||
XCTAssertEqual(backend, "GGUF · Metal")
|
||
XCTAssertTrue((1...8).contains(try XCTUnwrap(metrics).tokens))
|
||
}
|
||
|
||
func testLocalModelImportDetectsMLXAndRejectsIncompleteOrUnsupportedItems() throws {
|
||
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||
defer { try? FileManager.default.removeItem(at: root) }
|
||
XCTAssertThrowsError(try LocalModelImport.inspect(root))
|
||
let unsupported = root.appending(path: "weights.bin")
|
||
try Data([1]).write(to: unsupported)
|
||
XCTAssertThrowsError(try LocalModelImport.inspect(unsupported))
|
||
try Data("{}".utf8).write(to: root.appending(path: "config.json"))
|
||
try Data([1]).write(to: root.appending(path: "model.safetensors"))
|
||
XCTAssertEqual(try LocalModelImport.inspect(root), .mlx(root.resolvingSymlinksInPath().path))
|
||
}
|
||
|
||
func testLocalModelImportRecognizesGGUFByContentsAndRejectsTruncation() throws {
|
||
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_GGUF_PATH"] else {
|
||
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_GGUF_PATH to a local GGUF chat fixture.")
|
||
}
|
||
let source = URL(fileURLWithPath: path)
|
||
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||
defer { try? FileManager.default.removeItem(at: root) }
|
||
let renamed = root.appending(path: "renamed.weights")
|
||
let contents = try Data(contentsOf: source)
|
||
try contents.write(to: renamed)
|
||
guard case .gguf(let metadata) = try LocalModelImport.inspect(renamed) else {
|
||
return XCTFail("Expected GGUF metadata")
|
||
}
|
||
XCTAssertEqual(metadata.architectureName, "Llama")
|
||
let truncated = root.appending(path: "truncated.gguf")
|
||
try contents.prefix(contents.count / 2).write(to: truncated)
|
||
XCTAssertThrowsError(try LocalModelImport.inspect(truncated))
|
||
}
|
||
|
||
func testHubGGUFMetadataPinsRevisionAndFiltersUnsupportedFiles() throws {
|
||
let revision = String(repeating: "a", count: 40)
|
||
let digest = String(repeating: "b", count: 64)
|
||
let data = Data("""
|
||
{"id":"owner/model","sha":"\(revision)","private":false,"gated":false,"siblings":[
|
||
{"rfilename":"model-Q4_K.gguf","size":100,"lfs":{"size":100,"sha256":"\(digest)"}},
|
||
{"rfilename":"../bad.gguf","size":100},
|
||
{"rfilename":"split-00001-of-00002.gguf","size":100},
|
||
{"rfilename":"weights.safetensors","size":100}
|
||
]}
|
||
""".utf8)
|
||
let assets = try HubGGUFAsset.decodeRepository(data, requested: "owner/model")
|
||
let model = try XCTUnwrap(assets.first)
|
||
XCTAssertEqual(assets.count, 1)
|
||
XCTAssertEqual(model.bytes, 100)
|
||
XCTAssertEqual(model.sha256, digest)
|
||
XCTAssertEqual(model.url.absoluteString, "https://huggingface.co/owner/model/resolve/\(revision)/model-Q4_K.gguf")
|
||
XCTAssertThrowsError(try HubGGUFAsset.decodeRepository(data, requested: "owner/other"))
|
||
let gated = Data(String(decoding: data, as: UTF8.self).replacingOccurrences(of: "\"gated\":false", with: "\"gated\":\"auto\"").utf8)
|
||
XCTAssertThrowsError(try HubGGUFAsset.decodeRepository(gated, requested: "owner/model"))
|
||
}
|
||
|
||
func testHubGGUFInstallVerifiesDigestBeforePublishingFile() async throws {
|
||
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_GGUF_PATH"] else {
|
||
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_GGUF_PATH to a local GGUF chat fixture.")
|
||
}
|
||
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||
defer { try? FileManager.default.removeItem(at: root) }
|
||
let contents = try Data(contentsOf: URL(fileURLWithPath: path))
|
||
let asset = HubGGUFAsset(repository: "owner/model", revision: String(repeating: "a", count: 40),
|
||
filename: "model.gguf", bytes: Int64(contents.count), sha256: nil)
|
||
let destination = root.appending(path: "install/model.gguf")
|
||
let imported = try await asset.install(to: destination, progress: { _, _ in }, transfer: { _, target, _ in
|
||
try contents.write(to: target)
|
||
})
|
||
XCTAssertEqual(imported.architectureName, "Llama")
|
||
XCTAssertEqual(try Data(contentsOf: destination), contents)
|
||
let corrupt = HubGGUFAsset(repository: asset.repository, revision: asset.revision, filename: asset.filename,
|
||
bytes: asset.bytes, sha256: String(repeating: "0", count: 64))
|
||
let rejected = root.appending(path: "invalid/model.gguf")
|
||
do {
|
||
_ = try await corrupt.install(to: rejected, progress: { _, _ in }, transfer: { _, target, _ in
|
||
try contents.write(to: target)
|
||
})
|
||
XCTFail("The checksum mismatch should reject the download")
|
||
} catch {
|
||
XCTAssertTrue(error.localizedDescription.contains("checksum"))
|
||
}
|
||
XCTAssertFalse(FileManager.default.fileExists(atPath: rejected.path))
|
||
XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: rejected.deletingLastPathComponent().path).isEmpty)
|
||
}
|
||
|
||
func testLiveHubGGUFDownloadInstallsAndStreams() async throws {
|
||
let env = ProcessInfo.processInfo.environment
|
||
guard let repository = env["AISTUDIO_TEST_GGUF_HUB_REPO"], let filename = env["AISTUDIO_TEST_GGUF_HUB_FILE"] else {
|
||
throw XCTSkip("Set the TEST_RUNNER_AISTUDIO_TEST_GGUF_HUB_REPO and TEST_RUNNER_AISTUDIO_TEST_GGUF_HUB_FILE variables.")
|
||
}
|
||
let assets = try await HubGGUFAsset.resolve(repository)
|
||
let asset = try XCTUnwrap(assets.first { $0.filename == filename })
|
||
XCTAssertNotNil(asset.sha256)
|
||
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||
defer { try? FileManager.default.removeItem(at: folder) }
|
||
let updates = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1))
|
||
let model = try await asset.install(to: folder.appending(path: filename), progress: { written, _ in
|
||
updates.continuation.yield(written)
|
||
})
|
||
updates.continuation.finish()
|
||
var reportedBytes: Int64?
|
||
for await written in updates.stream { reportedBytes = written }
|
||
XCTAssertEqual(reportedBytes, asset.bytes)
|
||
var settings = GenerationParameters()
|
||
settings.temperature = 0
|
||
settings.maxTokens = 8
|
||
let request = InferenceRequest(model: model.path, messages: [.init(role: .user, content: "What is 2 + 2?")],
|
||
thinking: .automatic, parameters: settings)
|
||
var reply = ""
|
||
for try await delta in GGUFProvider().generate(request) {
|
||
if case .answer(let text) = delta { reply += text }
|
||
}
|
||
XCTAssertFalse(reply.isEmpty)
|
||
}
|
||
|
||
func testGGUFCatalogFiltersRestrictedAndDuplicateRepositories() throws {
|
||
let json = Data("""
|
||
[{"id":"owner/open","downloads":73,"gated":false},
|
||
{"id":"Owner/Open"},{"id":"owner/gated","gated":"auto"},
|
||
{"id":"owner/private","private":true},{"id":"../unsafe"}]
|
||
""".utf8)
|
||
let models = try HubGGUFAsset.decodeSearch(json)
|
||
XCTAssertEqual(models.map(\.id), ["owner/open"])
|
||
XCTAssertEqual(models.first?.downloads, 73)
|
||
}
|
||
|
||
@MainActor
|
||
func testInstalledLMStudioModelsAndHuggingFaceDiscovery() async throws {
|
||
guard ProcessInfo.processInfo.environment["AISTUDIO_TEST_LM_STUDIO"] == "1" else {
|
||
throw XCTSkip("Enable the installed LM Studio library and live Hugging Face smoke test.")
|
||
}
|
||
let library = try LocalModelImport.discover(in: LocalModelImport.lmStudioFolder)
|
||
let folders = try MLXLibrary.discover(in: LocalModelImport.lmStudioFolder)
|
||
for name in ["Qwen3.5-9B-MLX-4bit", "Mistral-Nemo-Instruct-2407-4bit"] {
|
||
let folder = try XCTUnwrap(folders.first { $0.lastPathComponent == name })
|
||
XCTAssertTrue(library.contains(.mlx(folder.path)))
|
||
}
|
||
let gguf = library.compactMap { entry -> GGUFModelMetadata? in
|
||
guard case .gguf(let model) = entry else { return nil }
|
||
return model
|
||
}
|
||
XCTAssertFalse(gguf.contains { URL(fileURLWithPath: $0.path).lastPathComponent.hasPrefix("mmproj") })
|
||
let model = try XCTUnwrap(gguf.first { $0.architecture == "qwen35" })
|
||
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.prompt = "Hello"
|
||
var settings = GenerationSettings()
|
||
settings.temperature = "0"
|
||
settings.maxTokens = "24"
|
||
settings.context = "1024"
|
||
studio.send(endpoint: "unused", model: model.path, mlxPath: "", thinking: .off,
|
||
failover: false, mlxOnly: false, compatible: false, recall: false,
|
||
useDocuments: false, instructions: "", settings: settings, gguf: true)
|
||
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(where: { $0.role == .assistant }), studio.status)
|
||
XCTAssertFalse(reply.content.isEmpty)
|
||
XCTAssertEqual(reply.backend, "GGUF · Metal")
|
||
XCTAssertTrue(model.supportsThinking)
|
||
var parameters = GenerationParameters()
|
||
parameters.temperature = 0
|
||
parameters.maxTokens = 24
|
||
parameters.context = 1024
|
||
let thinkingRequest = InferenceRequest(model: model.path,
|
||
messages: [.init(role: .user, content: "What is 2 + 2?")],
|
||
thinking: .on, parameters: parameters)
|
||
var reasoning = ""
|
||
for try await delta in GGUFProvider().generate(thinkingRequest) {
|
||
if case .thinking(let text) = delta { reasoning += text }
|
||
}
|
||
XCTAssertFalse(reasoning.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||
let candidates = try await HubGGUFAsset.search("Qwen3.5")
|
||
XCTAssertFalse(candidates.isEmpty)
|
||
let mlx = try await CatalogModel.search("Qwen")
|
||
XCTAssertFalse(mlx.isEmpty)
|
||
}
|
||
|
||
func testLocalHistoryCoalescesAdjacentTurnsAndKeepsTheirText() {
|
||
let messages: [Message] = [
|
||
.init(role: .assistant, content: "Earlier reply"),
|
||
.init(role: .system, content: "Be concise"),
|
||
.init(role: .user, content: "Stopped turn"),
|
||
.init(role: .user, content: "Next question"),
|
||
.init(role: .assistant, content: "Reply"),
|
||
.init(role: .user, content: "Follow-up")
|
||
]
|
||
let result = LocalChatHistory.prepare(messages)
|
||
XCTAssertEqual(result.map(\.role), [.system, .user, .assistant, .user])
|
||
XCTAssertEqual(result[0].content, "Be concise")
|
||
XCTAssertTrue(result[1].content.contains("Earlier reply"))
|
||
XCTAssertTrue(result[1].content.hasSuffix("Stopped turn\n\nNext question"))
|
||
XCTAssertEqual(result.last?.content, "Follow-up")
|
||
XCTAssertEqual(messages.count, 6)
|
||
}
|
||
|
||
func testGGUFThinkingSetsSupportedPromptAndSeparatesReasoning() {
|
||
let prompt = "<|im_start|>assistant\n"
|
||
let template = "enable_thinking <|im_start|>assistant <think> </think>"
|
||
let enabled = GGUFThinking.prepare(prompt, template: template, mode: .on)
|
||
XCTAssertEqual(enabled.prompt, prompt + "<think>\n")
|
||
var output = ThinkingOutput(prefilled: enabled.prefilled)
|
||
XCTAssertEqual(output.append("Reason</think>Answer"), [.thinking("Reason"), .answer("Answer")])
|
||
let disabled = GGUFThinking.prepare(prompt, template: template, mode: .off)
|
||
XCTAssertEqual(disabled.prompt, prompt + "<think>\n\n</think>\n\n")
|
||
XCTAssertEqual(GGUFThinking.prepare(prompt, template: "plain", mode: .on).prompt, prompt)
|
||
}
|
||
|
||
func testMemoryBudgetFlagsWeightSizesAboveTheLimit() {
|
||
XCTAssertTrue(ModelMemoryBudget.exceeds(bytes: 101, budget: 100))
|
||
XCTAssertFalse(ModelMemoryBudget.exceeds(bytes: 100, budget: 100))
|
||
XCTAssertFalse(ModelMemoryBudget.exceeds(bytes: nil, budget: 100))
|
||
XCTAssertFalse(ModelMemoryBudget.exceeds(bytes: 100, budget: nil))
|
||
}
|
||
|
||
func testCoreMLImportedModelChoiceAndCausalMask() throws {
|
||
let choice = ChatModelChoice(backend: .coreML, model: "/Models/Chat.mlpackage")
|
||
let id = UUID()
|
||
XCTAssertEqual(ChatModelChoice.read(try JSONEncoder().encode([id: choice]))[id], choice)
|
||
XCTAssertEqual(choice.displayName, "Chat")
|
||
XCTAssertEqual(CoreMLInputs.mask(queryCount: 2, pastCount: 1), [0, 0, -65504, 0, 0, 0])
|
||
}
|
||
|
||
@MainActor
|
||
func testLiveAppleCoreMLChat() async throws {
|
||
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COREML_PATH"] else {
|
||
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_COREML_PATH to the compatible Core ML package.")
|
||
}
|
||
let model = try CoreMLLibrary.inspect(URL(fileURLWithPath: path))
|
||
XCTAssertGreaterThan(model.bytes, 0)
|
||
let defaults = UserDefaults.standard
|
||
let previousSearch = defaults.object(forKey: "automaticChatWebSearch")
|
||
defaults.set(false, forKey: "automaticChatWebSearch")
|
||
defer { defaults.set(previousSearch, forKey: "automaticChatWebSearch") }
|
||
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.prompt = "What is two plus two?"
|
||
var config = GenerationSettings()
|
||
config.maxTokens = "32"
|
||
config.temperature = "0"
|
||
studio.send(endpoint: "unused", model: model.path, mlxPath: "", thinking: .off,
|
||
failover: false, mlxOnly: false, compatible: false, recall: false,
|
||
useDocuments: false, instructions: "", settings: config, ragEnabled: false, coreML: true)
|
||
let deadline = ContinuousClock.now + .seconds(180)
|
||
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(50)) }
|
||
XCTAssertFalse(studio.running)
|
||
let reply = try XCTUnwrap(studio.messages.last(where: { $0.role == .assistant }), studio.status)
|
||
XCTAssertEqual(reply.backend, "Core ML")
|
||
XCTAssertTrue(reply.content.localizedCaseInsensitiveContains("four") || reply.content.contains("4"), reply.content)
|
||
let results = try await HubGGUFAsset.search("mistral", format: "coreml")
|
||
XCTAssertFalse(results.isEmpty)
|
||
}
|
||
|
||
func testThinkingControlKeepsDefaultForUnsupportedBackends() {
|
||
XCTAssertEqual(ChatThinkingControl.options(backend: .coreML, supportsLocalThinking: false), [.automatic])
|
||
XCTAssertEqual(ChatThinkingControl.options(backend: .gguf, supportsLocalThinking: true), [.automatic, .off, .on])
|
||
XCTAssertEqual(ChatThinkingControl.options(backend: .mlx, supportsLocalThinking: false), [.automatic])
|
||
XCTAssertEqual(ChatThinkingControl.options(backend: .ollama, supportsLocalThinking: false), Thinking.allCases)
|
||
}
|
||
|
||
func testImagePreviewScalesAndEncodesPNG() throws {
|
||
let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 80, pixelsHigh: 40,
|
||
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,
|
||
bytesPerRow: 0, bitsPerPixel: 0))
|
||
let source = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
|
||
let preview = try StudioImagePreview(data: source, name: "Test", maxDimension: 20)
|
||
XCTAssertEqual(preview.width, 80)
|
||
XCTAssertEqual(preview.height, 40)
|
||
let thumbnail = try XCTUnwrap(NSBitmapImageRep(data: preview.png))
|
||
XCTAssertEqual(thumbnail.pixelsWide, 20)
|
||
XCTAssertEqual(thumbnail.pixelsHigh, 10)
|
||
XCTAssertThrowsError(try StudioImagePreview(data: Data([1]), name: "Invalid"))
|
||
}
|
||
|
||
func testGenerationTimingCapturesReasoningAndProviderThroughput() {
|
||
var capture = GenerationCapture(start: 10)
|
||
capture.observe(.backend("GGUF · Metal"), at: 10.1)
|
||
capture.observe(.answer(""), at: 10.2)
|
||
capture.observe(.thinking("Plan"), at: 11)
|
||
capture.observe(.answer("Reply"), at: 12)
|
||
capture.observe(.metrics(.init(tokens: 10, seconds: 2)), at: 12)
|
||
let result = capture.finish(at: 14, requested: "GGUF", model: "Test", outcome: "Complete", benchmark: true)
|
||
XCTAssertEqual(result.backend, "GGUF · Metal")
|
||
XCTAssertEqual(result.firstOutput, 1)
|
||
XCTAssertEqual(result.seconds, 4)
|
||
XCTAssertEqual(result.charactersPerSecond, 3)
|
||
XCTAssertEqual(result.provider?.tokensPerSecond, 5)
|
||
XCTAssertEqual(result.benchmark, true)
|
||
}
|
||
|
||
func testChatPersistsTimingAndReadsExistingMeasurements() 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: "studio.sqlite")
|
||
let store = try Store(url: url)
|
||
let conversation = try store.create(title: "Performance")
|
||
let legacy = Data("""
|
||
[{"id":"00000000-0000-0000-0000-000000000001","backend":"MLX","firstOutput":1,"seconds":2,"characters":10,"outcome":"Complete"}]
|
||
""".utf8)
|
||
let timing = try XCTUnwrap(JSONDecoder().decode([GenerationMeasurement].self, from: legacy).first)
|
||
XCTAssertNil(timing.model)
|
||
try store.save(Message(role: .user, content: "Hello"), in: conversation.id)
|
||
try store.save(Message(role: .assistant, content: "Hello", performance: timing), in: conversation.id)
|
||
let messages = try Store(url: url).messages(in: conversation.id)
|
||
XCTAssertNil(messages.first?.performance)
|
||
XCTAssertEqual(messages.last?.performance, timing)
|
||
}
|
||
|
||
@MainActor
|
||
func testBenchmarkUsesCompatibleServerWithoutCreatingChat() async throws {
|
||
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COMPATIBLE_URL"] else {
|
||
throw XCTSkip("Run Scripts/test.sh to launch the compatible API fixture.")
|
||
}
|
||
let defaults = UserDefaults.standard
|
||
let previous = defaults.data(forKey: GenerationMeasurement.key)
|
||
defer { defaults.set(previous, forKey: GenerationMeasurement.key) }
|
||
let studio = StudioModel()
|
||
let benchmarkEndpoint = endpoint.replacingOccurrences(of: "/compatible/v1", with: "/benchmark/v1")
|
||
studio.benchmark(.init(backend: .compatible, model: "fixture-model"), endpoint: benchmarkEndpoint, repetitions: 1)
|
||
let deadline = ContinuousClock.now + .seconds(10)
|
||
while studio.benchmarkRunning && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) }
|
||
let run = try XCTUnwrap(studio.measurements.first, studio.benchmarkStatus)
|
||
XCTAssertEqual(run.benchmark, true)
|
||
XCTAssertEqual(run.model, "fixture-model")
|
||
XCTAssertEqual(run.outcome, "Complete", studio.benchmarkStatus)
|
||
XCTAssertNotNil(run.firstOutput)
|
||
XCTAssertTrue(studio.messages.isEmpty)
|
||
XCTAssertTrue(studio.conversations.isEmpty)
|
||
}
|
||
|
||
func testLiveCoreMLDownloadStagesWeightsAndReusesInstallation() async throws {
|
||
guard ProcessInfo.processInfo.environment["AISTUDIO_TEST_COREML_DOWNLOAD"] == "1" else {
|
||
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_COREML_DOWNLOAD=1 for the 4.08 GB Hugging Face test.")
|
||
}
|
||
let destination = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||
defer { try? FileManager.default.removeItem(at: destination) }
|
||
let progress = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1))
|
||
let model = try await CoreMLDownloads.install(in: destination) { bytes, _ in progress.continuation.yield(bytes) }
|
||
progress.continuation.finish()
|
||
var observed: Int64?
|
||
for await bytes in progress.stream { observed = bytes }
|
||
XCTAssertGreaterThan(try XCTUnwrap(observed), CoreMLDownloads.modelBytes)
|
||
XCTAssertEqual(model.bytes, CoreMLDownloads.modelBytes)
|
||
XCTAssertEqual(CoreMLDownloads.installed(in: destination)?.path, model.path)
|
||
let existing = try await CoreMLDownloads.install(in: destination) { _, _ in }
|
||
XCTAssertEqual(existing.path, model.path)
|
||
}
|
||
|
||
func testCoreImageExposureKeepsPreviewDimensionsAndIncreasesBrightness() throws {
|
||
// A flat 2 × 2 RGBA fixture with 64 in each color channel.
|
||
let data = try XCTUnwrap(Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAEUlEQVR4nGNwcHD4D8IMMAYAOnQG/e3tajcAAAAASUVORK5CYII="))
|
||
let original = try XCTUnwrap(NSBitmapImageRep(data: data))
|
||
let preview = try StudioImagePreview(data: data, name: "Dark")
|
||
let rendered = try preview.adjusted(exposure: 1)
|
||
let result = try XCTUnwrap(NSBitmapImageRep(data: rendered.png))
|
||
XCTAssertEqual(result.pixelsWide, 2)
|
||
XCTAssertEqual(result.pixelsHigh, 2)
|
||
let originalColor = try XCTUnwrap(original.colorAt(x: 0, y: 0)?.usingColorSpace(.deviceRGB))
|
||
let adjustedColor = try XCTUnwrap(result.colorAt(x: 0, y: 0)?.usingColorSpace(.deviceRGB))
|
||
XCTAssertGreaterThan(adjustedColor.redComponent, originalColor.redComponent)
|
||
}
|
||
|
||
func testCatalogSizesCompareVariantsWithoutSummingAlternatives() throws {
|
||
let data = Data("""
|
||
{"siblings":[{"rfilename":"chat-Q4.gguf","size":100},{"rfilename":"chat-Q8.gguf","size":300},
|
||
{"rfilename":"mmproj-chat.gguf","size":500},{"rfilename":"A.mlpackage/Manifest.json","size":10},
|
||
{"rfilename":"A.mlpackage/Data/weights/weight.bin","lfs":{"size":200}},
|
||
{"rfilename":"B.mlpackage/Manifest.json","size":10},{"rfilename":"B.mlpackage/Data/weights/weight.bin","size":400},
|
||
{"rfilename":"C.mlpackage/Data/weights/weight.bin"}]}
|
||
""".utf8)
|
||
let info = try JSONDecoder().decode(HubModelMetadata.self, from: data)
|
||
let gguf = info.variantSizes(format: .gguf)
|
||
XCTAssertEqual(gguf.known.sorted(), [100, 300])
|
||
XCTAssertTrue(gguf.someExceed(budget: 150))
|
||
XCTAssertFalse(gguf.someExceed(budget: 400))
|
||
let coreML = info.variantSizes(format: .coreML)
|
||
XCTAssertEqual(coreML.known.sorted(), [210, 410])
|
||
XCTAssertEqual(coreML.totalVariants, 3)
|
||
XCTAssertTrue(coreML.someExceed(budget: 300))
|
||
XCTAssertFalse(coreML.allExceed(budget: 100))
|
||
XCTAssertTrue(gguf.allExceed(budget: 99))
|
||
}
|
||
|
||
func testMarkdownExportIncludesEntireStoredConversationInOrder() 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: "workspace.sqlite"))
|
||
let chat = try store.create(title: "Café [notes]")
|
||
let other = try store.create(title: "Another chat")
|
||
try store.save(Message(role: .user, content: "Separate conversation"), in: other.id)
|
||
for index in 0..<40 {
|
||
try store.save(Message(role: .user, content: "Saved message \(index)",
|
||
documentNames: index == 0 ? ["report.pdf"] : []), in: chat.id)
|
||
}
|
||
let url = try XCTUnwrap(URL(string: "https://example.com/page"))
|
||
let answer = "Sample code\n\n```swift\nprint(42)\n```"
|
||
try store.save(Message(role: .assistant, content: answer, thinking: "First line\nSecond line",
|
||
backend: "Ollama · example", webSources: [
|
||
WebReplySource(url: url, title: "Source [one]", kind: .page)
|
||
], documentCitations: [
|
||
DocumentCitation(number: 1, title: "report.pdf", excerpt: "Page 1\nFull excerpt",
|
||
documentID: nil, chunkID: nil)
|
||
]), in: chat.id)
|
||
|
||
let destination = directory.appending(path: "export.md")
|
||
try store.exportChat(chat.id, to: destination)
|
||
let markdown = try String(contentsOf: destination, encoding: .utf8)
|
||
XCTAssertTrue(markdown.hasPrefix("# Café \\[notes\\]\n\n## You\n\nSaved message 0\n"))
|
||
let messagesInOrder = (0..<40).map { "Saved message \($0)" }
|
||
XCTAssertEqual(markdown.components(separatedBy: .newlines).filter { $0.hasPrefix("Saved message ") },
|
||
messagesInOrder)
|
||
XCTAssertTrue(markdown.contains("## Assistant\n\n*Ollama · example*\n\n" + answer))
|
||
XCTAssertTrue(markdown.contains("> First line\n> Second line"))
|
||
XCTAssertTrue(markdown.contains("- report.pdf"))
|
||
XCTAssertTrue(markdown.contains("**\\[D1\\] report.pdf**\n\n> Page 1\n> Full excerpt"))
|
||
XCTAssertTrue(markdown.contains("- [Source \\[one\\]](<https://example.com/page>)"))
|
||
XCTAssertFalse(markdown.contains("Separate conversation"))
|
||
}
|
||
|
||
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 testEmptySuccessfulStreamFallsBack() async throws {
|
||
let output = try await collect(Router.stream(
|
||
primary: { AsyncThrowingStream { $0.finish() } }, 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))
|
||
var history = prepared.messages
|
||
history.insert(Message(role: .user, content: "An earlier message whose generation was stopped."), at: history.count - 1)
|
||
let request = InferenceRequest(model: directory, messages: history,
|
||
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 = ThinkingOutput()
|
||
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 = ThinkingOutput()
|
||
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 custom = try await CatalogModel.resolve("mlx-community/Qwen3-0.6B-4bit")
|
||
XCTAssertEqual(custom.repository, "mlx-community/Qwen3-0.6B-4bit")
|
||
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 testCatalogRejectsDotRepositoryAndAnotherRuntime() throws {
|
||
let sha = String(repeating: "a", count: 40)
|
||
let data = Data("""
|
||
[{"id":"mlx-community/..","sha":"\(sha)",
|
||
"siblings":[{"rfilename":"config.json"},{"rfilename":"model.safetensors"}]},
|
||
{"id":"mlx-community/GPTQ","sha":"\(sha)","library_name":"transformers",
|
||
"siblings":[{"rfilename":"config.json"},{"rfilename":"model.safetensors"}]}]
|
||
""".utf8)
|
||
XCTAssertTrue(try CatalogModel.decodeSearch(data).isEmpty)
|
||
}
|
||
|
||
func testCustomMLXRepositoryKeepsOwnerInInstallationIdentity() throws {
|
||
let sha = String(repeating: "a", count: 40)
|
||
func entry(_ owner: String) -> Data {
|
||
Data("""
|
||
{"id":"\(owner)/Shared-4bit","sha":"\(sha)","library_name":"mlx","gated":false,
|
||
"siblings":[{"rfilename":"config.json"},{"rfilename":"model.safetensors"}]}
|
||
""".utf8)
|
||
}
|
||
let first = try CatalogModel.decodeRepository(entry("team-a"), requested: "team-a/Shared-4bit")
|
||
let second = try CatalogModel.decodeRepository(entry("team-b"), requested: "team-b/Shared-4bit")
|
||
XCTAssertNotEqual(first.localFolder, second.localFolder)
|
||
XCTAssertEqual(first.source.absoluteString, "https://huggingface.co/team-a/Shared-4bit")
|
||
XCTAssertThrowsError(try CatalogModel.decodeRepository(entry("team-a"), requested: "team-b/Shared-4bit"))
|
||
}
|
||
|
||
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(ThinkingOutput.supportsMLX(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 JavaScriptSandboxTests: XCTestCase {
|
||
func testSandboxRunsJavaScriptWithoutHostAPIs() throws {
|
||
XCTAssertEqual(try JavaScriptSandbox.run("console.log(6 * 7); ({ready: true})"),
|
||
"42 \n{\"ready\":true}")
|
||
XCTAssertEqual(try JavaScriptSandbox.run("[typeof require, typeof fetch, typeof process]"),
|
||
"[\"undefined\",\"undefined\",\"undefined\"]")
|
||
XCTAssertThrowsError(try JavaScriptSandbox.run("throw new Error('expected')")) {
|
||
XCTAssertEqual($0.localizedDescription, "Error: expected")
|
||
}
|
||
}
|
||
|
||
func testSandboxStopsInfiniteLoops() throws {
|
||
XCTAssertThrowsError(try JavaScriptSandbox.run("while (true) {}")) {
|
||
XCTAssertTrue($0.localizedDescription.contains("time limit"))
|
||
}
|
||
}
|
||
}
|
||
|
||
final class CompatibleEndpointTests: XCTestCase {
|
||
func testLMStudioPluginRequestAndStream() async throws {
|
||
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COMPATIBLE_URL"] else {
|
||
throw XCTSkip("Run Scripts/test.sh to configure the local fixture.")
|
||
}
|
||
let client = try CompatibleEndpoint(endpoint: endpoint, token: "fixture-token")
|
||
let plugins = CompatibleEndpoint.pluginIDs("fixture, mcp/fixture")
|
||
XCTAssertEqual(plugins, ["mcp/fixture"])
|
||
let request = InferenceRequest(model: "fixture-model", messages: [
|
||
Message(role: .system, content: "Silent instruction"),
|
||
Message(role: .user, content: "Earlier question"),
|
||
Message(role: .assistant, content: "Earlier answer"),
|
||
Message(role: .user, content: "Use the fixture")
|
||
], thinking: .automatic)
|
||
var deltas: [Delta] = []
|
||
for try await delta in client.generateWithPlugins(request, plugins: plugins) {
|
||
deltas.append(delta)
|
||
}
|
||
XCTAssertEqual(deltas, [.backend("LM Studio Plugins · fixture-model"), .committed,
|
||
.thinking("Checking"), .answer("Plugin response"),
|
||
.metrics(ProviderMetrics(tokens: 2, seconds: 0))])
|
||
}
|
||
|
||
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 {
|
||
@MainActor
|
||
func testClipboardDistinguishesFilesFromOrdinaryText() throws {
|
||
let clipboard = NSPasteboard.withUniqueName()
|
||
defer { clipboard.releaseGlobally() }
|
||
let url = FileManager.default.temporaryDirectory.appending(path: "\(UUID()).txt")
|
||
defer { try? FileManager.default.removeItem(at: url) }
|
||
try Data("Pasted file contents".utf8).write(to: url)
|
||
let file = NSPasteboardItem()
|
||
XCTAssertTrue(file.setString(url.absoluteString, forType: .fileURL))
|
||
XCTAssertTrue(file.setData(Data([0]), forType: .tiff))
|
||
clipboard.clearContents()
|
||
XCTAssertTrue(clipboard.writeObjects([file]))
|
||
XCTAssertTrue(ComposerPaste.isAvailable(on: clipboard))
|
||
let paste = try XCTUnwrap(ComposerPaste.read(clipboard))
|
||
XCTAssertEqual(paste, .files([url]))
|
||
XCTAssertEqual(try paste.preview().text, "Pasted file contents")
|
||
XCTAssertThrowsError(try ComposerPaste.files([url, url]).preview())
|
||
|
||
clipboard.clearContents()
|
||
XCTAssertTrue(clipboard.setString("Ordinary draft text", forType: .string))
|
||
XCTAssertFalse(ComposerPaste.isAvailable(on: clipboard))
|
||
XCTAssertNil(ComposerPaste.read(clipboard))
|
||
}
|
||
|
||
@MainActor
|
||
func testScreenshotPreviewAndImageRequests() throws {
|
||
let file = FileManager.default.temporaryDirectory.appending(path: "\(UUID()).png")
|
||
defer { try? FileManager.default.removeItem(at: file) }
|
||
let bitmap = try XCTUnwrap(CGContext(data: nil, width: 640, height: 480,
|
||
bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
|
||
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
|
||
bitmap.setFillColor(CGColor.white)
|
||
bitmap.fill(CGRect(x: 0, y: 0, width: 640, height: 480))
|
||
bitmap.textPosition = CGPoint(x: 40, y: 400)
|
||
CTLineDraw(CTLineCreateWithAttributedString(NSAttributedString(string: "Screenshot attachment", attributes: [
|
||
.font: NSFont.systemFont(ofSize: 32), .foregroundColor: NSColor.black
|
||
])), bitmap)
|
||
let image = try XCTUnwrap(bitmap.makeImage())
|
||
let original = try XCTUnwrap(NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]))
|
||
try original.write(to: file)
|
||
|
||
let preview = try ChatFilePreview.read(file)
|
||
let clipboard = NSPasteboard.withUniqueName()
|
||
defer { clipboard.releaseGlobally() }
|
||
clipboard.clearContents()
|
||
XCTAssertTrue(clipboard.setData(original, forType: .png))
|
||
XCTAssertTrue(ComposerPaste.isAvailable(on: clipboard))
|
||
let paste = try XCTUnwrap(ComposerPaste.read(clipboard))
|
||
XCTAssertEqual(paste, .image(original))
|
||
let pasted = try paste.preview()
|
||
XCTAssertEqual(pasted.name, "Pasted Image.png")
|
||
XCTAssertEqual(pasted.text, preview.text)
|
||
XCTAssertEqual(pasted.imagePNG, preview.imagePNG)
|
||
let png = try XCTUnwrap(preview.imagePNG)
|
||
let previewImage = try XCTUnwrap(NSBitmapImageRep(data: png))
|
||
XCTAssertEqual(previewImage.pixelsWide, 640)
|
||
XCTAssertEqual(previewImage.pixelsHigh, 480)
|
||
XCTAssertTrue(preview.text.contains("Screenshot attachment"))
|
||
|
||
let messages = [
|
||
Message(role: .system, content: "Answer clearly."),
|
||
Message(role: .user, content: "Describe this screenshot.", imagePNG: png)
|
||
]
|
||
let prepared = try StudioPromptRequest.prepare(messages, template: nil, options: .init(), parameters: .init())
|
||
let request = InferenceRequest(model: "test", messages: prepared.messages, thinking: .off, parameters: prepared.parameters)
|
||
func object(_ value: some Encodable) throws -> [String: Any] {
|
||
try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(value)) as? [String: Any])
|
||
}
|
||
|
||
let ollama = try XCTUnwrap(object(Ollama.ChatBody(request))["messages"] as? [[String: Any]])
|
||
XCTAssertNil(ollama[0]["images"])
|
||
XCTAssertEqual(ollama[1]["images"] as? [String], [png.base64EncodedString()])
|
||
|
||
let compatible = try XCTUnwrap(object(CompatibleEndpoint.Body(request))["messages"] as? [[String: Any]])
|
||
XCTAssertEqual(compatible[0]["content"] as? String, "Answer clearly.")
|
||
let parts = try XCTUnwrap(compatible[1]["content"] as? [[String: Any]])
|
||
let url = "data:image/png;base64," + png.base64EncodedString()
|
||
XCTAssertEqual(parts[0]["text"] as? String, "Describe this screenshot.")
|
||
XCTAssertEqual((parts[1]["image_url"] as? [String: String])?["url"], url)
|
||
|
||
let plugin = try XCTUnwrap(object(CompatibleEndpoint.PluginChatBody(request, plugins: ["mcp/test"]))["input"] as? [[String: Any]])
|
||
XCTAssertEqual(plugin[0]["content"] as? String, "Describe this screenshot.")
|
||
XCTAssertEqual(plugin[1]["data_url"] as? String, url)
|
||
}
|
||
|
||
func testPDFAttachmentKeepsLatePagesAndRecognizesScans() throws {
|
||
let file = FileManager.default.temporaryDirectory.appending(path: "\(UUID()).PDF")
|
||
defer { try? FileManager.default.removeItem(at: file) }
|
||
var bounds = CGRect(x: 0, y: 0, width: 612, height: 792)
|
||
let pdf = try XCTUnwrap(CGContext(file as CFURL, mediaBox: &bounds, nil))
|
||
|
||
func draw(_ text: String, in context: CGContext, at position: CGPoint) {
|
||
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [
|
||
.font: NSFont.systemFont(ofSize: 24), .foregroundColor: NSColor.black
|
||
]))
|
||
context.textPosition = position
|
||
CTLineDraw(line, context)
|
||
}
|
||
|
||
for _ in 0..<10 {
|
||
pdf.beginPDFPage(nil)
|
||
for row in 0..<35 {
|
||
draw("Embedded document text", in: pdf, at: CGPoint(x: 24, y: 760 - row * 20))
|
||
}
|
||
pdf.endPDFPage()
|
||
}
|
||
let scan = try XCTUnwrap(CGContext(data: nil, width: 612, height: 792,
|
||
bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
|
||
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
|
||
scan.setFillColor(CGColor.white)
|
||
scan.fill(bounds)
|
||
draw("Final page reference", in: scan, at: CGPoint(x: 24, y: 700))
|
||
pdf.beginPDFPage(nil)
|
||
pdf.draw(try XCTUnwrap(scan.makeImage()), in: bounds)
|
||
pdf.endPDFPage()
|
||
pdf.closePDF()
|
||
|
||
let document = try XCTUnwrap(PDFDocument(url: file))
|
||
XCTAssertEqual(document.page(at: 10)?.string?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "", "")
|
||
let preview = try ChatFilePreview.read(file)
|
||
XCTAssertTrue(preview.isPDF)
|
||
XCTAssertGreaterThan(preview.text.count, 8000)
|
||
XCTAssertTrue(preview.text.contains("Page 11\nFinal page reference"))
|
||
XCTAssertFalse(preview.text.contains("[Preview truncated]"))
|
||
|
||
let attachment = DocumentCitation(number: 1, title: preview.name, excerpt: preview.text,
|
||
documentID: nil, chunkID: nil, requiresFullText: true)
|
||
let user = Message(role: .user, content: "Read the PDF", documentCitations: [attachment])
|
||
var options = AgentPromptSettings()
|
||
options.useDocuments = false
|
||
let request = try StudioPromptRequest.prepare([user], template: nil, options: options, parameters: .init())
|
||
XCTAssertEqual(request.citations, [attachment])
|
||
XCTAssertTrue(request.messages.last?.content.hasSuffix(preview.text) == true)
|
||
XCTAssertThrowsError(try PromptBudget.fit([user], limit: 512, reserve: 128)) { error in
|
||
XCTAssertTrue(error.localizedDescription.contains("full attachment text"))
|
||
}
|
||
}
|
||
|
||
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 testMLXScanSkipsIncompleteSnapshotsAndKeepsUsableOnes() throws {
|
||
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||
defer { try? FileManager.default.removeItem(at: root) }
|
||
let snapshots = root.appending(path: "models--team--test/snapshots")
|
||
let ready = snapshots.appending(path: "ready")
|
||
let partial = snapshots.appending(path: "partial")
|
||
for folder in [ready, partial] {
|
||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||
try Data(#"{"model_type":"llama"}"#.utf8).write(to: folder.appending(path: "config.json"))
|
||
try Data([1]).write(to: folder.appending(path: "model-00001.safetensors"))
|
||
try Data(#"{"weight_map":{"a":"model-00001.safetensors","b":"model-00002.safetensors"}}"#.utf8)
|
||
.write(to: folder.appending(path: "model.safetensors.index.json"))
|
||
}
|
||
try Data([2]).write(to: ready.appending(path: "model-00002.safetensors"))
|
||
XCTAssertEqual(try MLXLibrary.discover(in: root).map(\.lastPathComponent), ["ready"])
|
||
}
|
||
|
||
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 testMCPToolFailureIsNotAttachable() async throws {
|
||
let studio = StudioModel()
|
||
let id = MCPConnectionID.profile("Failure")
|
||
studio.connectMCP(id, name: "Failure") {
|
||
MockClient(identifier: #"{"isError":true,"content":[{"type":"text","text":"Access denied"}]}"#)
|
||
}
|
||
try await waitUntil { studio.mcpConnections[id]?.toolset != nil }
|
||
studio.invokeMCP(id, tool: "echo", arguments: Data("{}".utf8), searchEndpoint: "")
|
||
try await waitUntil { studio.mcpConnections[id]?.progress == nil }
|
||
XCTAssertEqual(studio.mcpConnections[id]?.failed, true)
|
||
XCTAssertNil(studio.mcpConnections[id]?.completedTool)
|
||
XCTAssertTrue(studio.mcpConnections[id]?.output.contains("Access denied") == true)
|
||
}
|
||
|
||
@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 testGGUFSelectionSuppressesStaleDefaultsAndNormalizesPaths() {
|
||
let gguf = ModelLibrarySelection(mlxOnly: true, compatible: false, mlxPath: "/tmp/models/MLX",
|
||
ollamaModel: "legacy", ggufPath: "/tmp/models/./chat.gguf")
|
||
XCTAssertTrue(gguf.isGGUF("/tmp/models/chat.gguf"))
|
||
XCTAssertFalse(gguf.isGGUF("/tmp/models/other.gguf"))
|
||
XCTAssertFalse(gguf.isMLX("/tmp/models/MLX"))
|
||
XCTAssertFalse(gguf.isOllama("legacy"))
|
||
}
|
||
|
||
func testGGUFLibraryDisplaysRecognizableArchitectureNames() {
|
||
for (architecture, label) in [("llama", "Llama"), ("mpt", "MPT"), ("openelm", "OpenELM"), ("future", "future")] {
|
||
let model = GGUFModelMetadata(path: "/tmp/chat.gguf", version: 3, tensorFormat: "Q4_K",
|
||
architecture: architecture)
|
||
XCTAssertEqual(model.architectureName, label)
|
||
}
|
||
}
|
||
|
||
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"), ["\u{001B}[1mready\u{001B}[0m"])
|
||
}
|
||
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 defaults = UserDefaults.standard
|
||
let previousSearch = defaults.object(forKey: "automaticChatWebSearch")
|
||
defaults.set(false, forKey: "automaticChatWebSearch")
|
||
defer { defaults.set(previousSearch, forKey: "automaticChatWebSearch") }
|
||
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, ragEnabled) in [(false, false), (true, true), (true, false)] {
|
||
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"
|
||
let includeExcerpt = !imported || ragEnabled
|
||
let route = includeExcerpt ? "chat-document" : "chat-rag-off"
|
||
studio.send(endpoint: base.appending(path: route).absoluteString, model: "fixture",
|
||
mlxPath: "", thinking: .off, failover: false, mlxOnly: false, compatible: false,
|
||
recall: false, useDocuments: imported, instructions: "", settings: GenerationSettings(),
|
||
ragEnabled: ragEnabled)
|
||
let deadline = ContinuousClock.now + .seconds(5)
|
||
while studio.running && ContinuousClock.now < deadline {
|
||
try await Task.sleep(for: .milliseconds(10))
|
||
}
|
||
XCTAssertEqual(studio.messages.last?.content, includeExcerpt ? "Document received." : "RAG is off.", 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, includeExcerpt ? ["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"))
|
||
}
|
||
}
|
||
|
||
extension RemoteStackSelectionTests {
|
||
func testGiteaRepositoryEnvelopeUnderData() async throws {
|
||
let payload = #"{"structuredContent":{"data":{"repositories":[{"full_name":"team/project"}]}}}"#
|
||
let client = ConnectedChatTests.Server(name: "list_repositories", result: Data(payload.utf8))
|
||
let entries = try await GiteaRepositoryLookup.entries(client: client)
|
||
XCTAssertEqual(entries, ["team/project"])
|
||
}
|
||
}
|