Repository Public License
1import Foundation2import NavigatorCore3import Testing4@testable import ProviderKit56/// A value shared between a test and the closures it hands to the code under test.7final class Locked<Value: Sendable>: @unchecked Sendable {8 private let lock = NSLock()9 private var value: Value10 init(_ value: Value) { self.value = value }11 func get() -> Value { lock.withLock { value } }12 func set(_ new: Value) { lock.withLock { value = new } }13 func mutate(_ body: (inout Value) -> Void) { lock.withLock { body(&value) } }14}1516/// In-process transport that plays back scripted responses and records every request. Never touches the network.17final class ScriptedTransport: HTTPTransport, @unchecked Sendable {18 struct Step: Sendable {19 var status = 20020 var headers: [String: String] = [:]21 var chunks: [Data] = []22 /// Thrown instead of answering (a connection failure before any response).23 var failure: URLError.Code?24 /// Thrown after the chunks were delivered (a connection lost mid-stream).25 var failureAfterChunks: URLError.Code?26 /// Never finish the body after the chunks: the request stays in flight until it is cancelled.27 var hangs = false2829 static func sse(_ text: String, status: Int = 200) -> Step { Step(status: status, chunks: [Data(text.utf8)]) }30 static func json(_ text: String, status: Int = 200, headers: [String: String] = [:]) -> Step {31 Step(status: status, headers: headers, chunks: [Data(text.utf8)])32 }33 static func fail(_ code: URLError.Code) -> Step { Step(failure: code) }34 }3536 private let lock = NSLock()37 private var steps: [Step]38 private var recorded: [URLRequest] = []39 private var terminated = 04041 init(_ steps: [Step]) { self.steps = steps }4243 var requests: [URLRequest] { lock.withLock { recorded } }44 var terminatedStreams: Int { lock.withLock { terminated } }4546 /// The JSON body of request `index`.47 func body(_ index: Int = 0) -> JSONValue {48 let all = requests49 guard all.indices.contains(index), let data = all[index].httpBody, let json = JSONValue.parse(data) else { return .null }50 return json51 }5253 private func next(_ request: URLRequest) throws -> Step {54 let step: Step? = lock.withLock {55 recorded.append(request)56 return steps.isEmpty ? nil : steps.removeFirst()57 }58 guard let step else { throw URLError(.badServerResponse) }59 if let failure = step.failure { throw URLError(failure) }60 return step61 }6263 private func head(_ request: URLRequest, _ step: Step) -> HTTPURLResponse {64 HTTPURLResponse(url: request.url!, statusCode: step.status, httpVersion: "HTTP/1.1", headerFields: step.headers)!65 }6667 func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {68 let step = try next(request)69 return (step.chunks.reduce(Data(), +), head(request, step))70 }7172 func bytes(for request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<Data, Error>) {73 let step = try next(request)74 let (stream, continuation) = AsyncThrowingStream<Data, Error>.makeStream(bufferingPolicy: .unbounded)75 continuation.onTermination = { [weak self] _ in76 guard let self else { return }77 self.lock.withLock { self.terminated += 1 }78 }79 for chunk in step.chunks { continuation.yield(chunk) }80 if let failure = step.failureAfterChunks { continuation.finish(throwing: URLError(failure)) }81 else if !step.hangs { continuation.finish() }82 else { hanging.mutate { $0.append(continuation) } } // kept alive so the stream stays open83 return (head(request, step), stream)84 }8586 private let hanging = Locked<[AsyncThrowingStream<Data, Error>.Continuation]>([])87}8889/// Environment with no real waiting: sleeps and log lines are recorded.90struct TestEnvironment {91 let transport: ScriptedTransport92 let sleeps = Locked<[TimeInterval]>([])93 let logs = Locked<[String]>([])94 let environment: ProviderEnvironment9596 init(_ steps: [ScriptedTransport.Step], retry: RetryPolicy = RetryPolicy(maxAttempts: 3, baseDelay: 0.5, maxDelay: 8, maxRetryAfter: 30)) {97 let transport = ScriptedTransport(steps)98 let sleeps = self.sleeps, logs = self.logs99 self.transport = transport100 self.environment = ProviderEnvironment(transport: transport, retry: retry, sleep: { delay in sleeps.mutate { $0.append(delay) } },101 random: { 0.5 }, logObserver: { line in logs.mutate { $0.append(line) } })102 }103}104105let testKey = "sk-test-NAVIGATORSECRET0123456789abcdefXYZ"106/// A key with no recognisable shape, as a self-hosted server may use: only the exact-match scrub can catch it.107let shapelessKey = "correct horse battery staple 42"108109/// The four families that speak HTTP, with the fixtures each one needs.110enum HTTPFamily: String, CaseIterable, Sendable, CustomTestStringConvertible {111 case anthropic, openAI, openRouter, compatible112113 var testDescription: String { rawValue }114 var isAnthropic: Bool { self == .anthropic }115116 func provider(_ test: TestEnvironment, key: String? = testKey) -> any ChatProvider {117 let source: KeySource = { key }118 switch self {119 case .anthropic: return AnthropicProvider(apiKey: source, environment: test.environment)120 case .openAI: return OpenAIProvider(apiKey: source, environment: test.environment)121 case .openRouter: return OpenRouterProvider(apiKey: source, environment: test.environment)122 case .compatible:123 return CompatibleProvider(endpoint: .init(baseURL: "http://localhost:11434/v1", headers: ["X-Team": "browser"]), apiKey: source, environment: test.environment)124 }125 }126127 var chatURL: String {128 switch self {129 case .anthropic: "https://api.anthropic.com/v1/messages"130 case .openAI: "https://api.openai.com/v1/chat/completions"131 case .openRouter: "https://openrouter.ai/api/v1/chat/completions"132 case .compatible: "http://localhost:11434/v1/chat/completions"133 }134 }135136 /// "Hello, wörld" in two deltas, with usage and an ordinary end of turn.137 var textStream: String {138 if isAnthropic {139 return """140 event: message_start141 data: {"type":"message_start","message":{"id":"msg_1","model":"served-model","usage":{"input_tokens":10,"cache_read_input_tokens":5,"cache_creation_input_tokens":2,"output_tokens":1}}}142143 event: content_block_start144 data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}145146 event: ping147 data: {"type":"ping"}148149 event: content_block_delta150 data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}151152 event: content_block_delta153 data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":", wörld"}}154155 event: content_block_stop156 data: {"type":"content_block_stop","index":0}157158 event: message_delta159 data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}160161 event: message_stop162 data: {"type":"message_stop"}163164165 """166 }167 return """168 : keep-alive169170 data: {"id":"cmpl_1","model":"served-model","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello"}}]}171172 data: {"id":"cmpl_1","model":"served-model","choices":[{"index":0,"delta":{"content":", wörld"}}]}173174 data: {"id":"cmpl_1","model":"served-model","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}175176 data: {"id":"cmpl_1","model":"served-model","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":7,"prompt_tokens_details":{"cached_tokens":5}}}177178 data: [DONE]179180181 """182 }183184 /// One call to `open_tab` whose arguments arrive in three fragments.185 var toolStream: String {186 if isAnthropic {187 return """188 data: {"type":"message_start","message":{"id":"msg_2","model":"served-model","usage":{"input_tokens":30,"output_tokens":1}}}189190 data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}191192 data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"The user wants a tab."}}193194 data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"c2lnbmF0dXJl"}}195196 data: {"type":"content_block_stop","index":0}197198 data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_1","name":"open_tab","input":{}}}199200 data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\\"url\\":"}}201202 data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" \\"https://exam"}}203204 data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"ple.com\\"}"}}205206 data: {"type":"content_block_stop","index":1}207208 data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":25}}209210 data: {"type":"message_stop"}211212213 """214 }215 return """216 data: {"id":"cmpl_2","choices":[{"index":0,"delta":{"role":"assistant","content":null,"reasoning":"The user wants a tab.","tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"open_tab","arguments":""}}]}}]}217218 data: {"id":"cmpl_2","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"url\\":"}}]}}]}219220 data: {"id":"cmpl_2","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" \\"https://exam"}}]}}]}221222 data: {"id":"cmpl_2","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ple.com\\"}"}}]}}]}223224 data: {"id":"cmpl_2","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":30,"completion_tokens":25}}225226 data: [DONE]227228229 """230 }231232 func errorBody(_ message: String, type: String = "invalid_request_error", code: String? = nil) -> String {233 let escaped = JSONValue.string(message).serialized()234 if isAnthropic { return #"{"type":"error","error":{"type":"\#(type)","message":\#(escaped)}}"# }235 let codeField = code.map { #","code":"\#($0)""# } ?? ""236 return #"{"error":{"message":\#(escaped),"type":"\#(type)"\#(codeField)}}"#237 }238239 var modelNotFoundBody: String {240 isAnthropic ? errorBody("model: nope", type: "not_found_error") : errorBody("The model `nope` does not exist", code: "model_not_found")241 }242}243244let sampleTool = ToolDefinition(name: "open_tab", description: "Opens a URL in a new tab.",245 parameters: ["type": "object", "properties": ["url": ["type": "string"]], "required": ["url"]])246247func sampleRequest(tools: [ToolDefinition] = [], options: GenerationOptions = GenerationOptions()) -> ChatRequest {248 ChatRequest(model: "test-model", system: "You are a browser assistant.", messages: [.user("Hi")], tools: tools, options: options)249}250251/// Runs a stream to its end and returns the events with the error that ended it, if any.252func collect(_ stream: AsyncThrowingStream<ChatEvent, Error>) async -> (events: [ChatEvent], error: ProviderError?) {253 var events: [ChatEvent] = []254 do {255 for try await event in stream { events.append(event) }256 return (events, nil)257 } catch {258 return (events, error as? ProviderError ?? .configuration("unexpected error type \(type(of: error))"))259 }260}261262func text(_ events: [ChatEvent]) -> String {263 events.compactMap { if case .textDelta(let delta) = $0 { delta } else { nil } }.joined()264}265266/// Polls until `condition` holds or two seconds pass.267func eventually(_ condition: @Sendable () -> Bool) async -> Bool {268 for _ in 0..<400 {269 if condition() { return true }270 try? await Task.sleep(nanoseconds: 5_000_000)271 }272 return condition()273}274275/// Every string an error can turn into: what the UI shows and what a log or a crash report could print.276func renderings(_ error: Error) -> [String] {277 var out = [String(describing: error), String(reflecting: error), error.localizedDescription]278 if let provider = error as? ProviderError { out += [provider.title, provider.message, provider.description] }279 return out280}281