diff --git a/Sources/HowlerCore/ChatClient.swift b/Sources/HowlerCore/ChatClient.swift index 78ec45f..5d226cc 100644 --- a/Sources/HowlerCore/ChatClient.swift +++ b/Sources/HowlerCore/ChatClient.swift @@ -7,6 +7,7 @@ public enum ChatClientError: Error, Equatable, LocalizedError { case http(status: Int, message: String) case stream(String) case invalidResponse + case replyTooLarge /// The connection closed before the provider signalled the end of the reply. case incomplete @@ -14,6 +15,7 @@ public enum ChatClientError: Error, Equatable, LocalizedError { switch self { case .http(_, let message): return message case .stream(let message): return message + case .replyTooLarge: return "The reply is larger than 8 MiB." case .invalidResponse: return "Unexpected response from server." case .incomplete: return "The connection closed before the reply finished; the answer may be incomplete." } @@ -25,6 +27,7 @@ public enum ChatClientError: Error, Equatable, LocalizedError { /// Uses an ephemeral `URLSession` so nothing (requests, responses, cookies) is /// cached to disk, and never logs request or response content. public final class ChatClient: @unchecked Sendable { + private static let maximumReplyBytes = 8 * 1024 * 1024 private let session: URLSession public init(session: URLSession? = nil) { @@ -87,6 +90,9 @@ public final class ChatClient: @unchecked Sendable { onText: @escaping (String) -> Void ) async throws { let (bytes, response) = try await responseBytes(for: request, local: local) + #if canImport(Darwin) + defer { bytes.task.cancel() } + #endif guard let http = response as? HTTPURLResponse else { throw ChatClientError.invalidResponse } guard (200..<300).contains(http.statusCode) else { @@ -102,11 +108,18 @@ public final class ChatClient: @unchecked Sendable { } var parser = SSEParser() + var replyByteCount = 0 // Returns true when the provider signalled the end of the reply. func handle(_ event: SSEEvent) throws -> Bool { for delta in StreamDecoder.decode(event, format: format) { switch delta { - case .text(let text): onText(text) + case .text(let text): + let byteCount = text.utf8.count + guard byteCount <= Self.maximumReplyBytes - replyByteCount else { + throw ChatClientError.replyTooLarge + } + replyByteCount += byteCount + onText(text) case .done: return true case .error(let message): throw ChatClientError.stream(message) } @@ -115,10 +128,11 @@ public final class ChatClient: @unchecked Sendable { } for try await byte in bytes { - if let event = parser.feed(byte), try handle(event) { return } + try Task.checkCancellation() + if let event = try parser.feed(byte), try handle(event) { return } } try Task.checkCancellation() - if let event = parser.finish(), try handle(event) { return } + if let event = try parser.finish(), try handle(event) { return } // Every supported provider ends a finished reply explicitly; a bare EOF means the // connection dropped and what arrived is only part of the answer. throw ChatClientError.incomplete diff --git a/Sources/HowlerCore/SSEParser.swift b/Sources/HowlerCore/SSEParser.swift index 06d96b0..e6ec445 100644 --- a/Sources/HowlerCore/SSEParser.swift +++ b/Sources/HowlerCore/SSEParser.swift @@ -12,12 +12,28 @@ public struct SSEEvent: Equatable, Sendable { } } +public enum SSEParserError: Error, Equatable, LocalizedError { + case lineTooLarge + case eventTooLarge + + public var errorDescription: String? { + switch self { + case .lineTooLarge: return "The server sent a line larger than 1 MiB." + case .eventTooLarge: return "The server sent an event larger than 1 MiB." + } + } +} + /// Incremental Server-Sent Events parser (WHATWG event-stream rules). /// /// Works on raw bytes so it can be fed straight from `URLSession.AsyncBytes` /// (whose `.lines` view drops the blank lines that delimit events) and so a /// multi-byte UTF-8 character split across network chunks decodes correctly. public struct SSEParser { + private static let maximumLineBytes = 1024 * 1024 + private static let maximumEventBytes = 1024 * 1024 + private var dataByteCount = 0 + private var dataValueOffset: Int? private var line: [UInt8] = [] private var dataLines: [String] = [] private var eventType: String? @@ -28,54 +44,73 @@ public struct SSEParser { public init() {} /// Feeds bytes and returns every event completed by them. - public mutating func feed(_ bytes: S) -> [SSEEvent] where S.Element == UInt8 { + public mutating func feed(_ bytes: S) throws -> [SSEEvent] where S.Element == UInt8 { var events: [SSEEvent] = [] for byte in bytes { - if let event = feed(byte) { events.append(event) } + if let event = try feed(byte) { events.append(event) } } return events } - public mutating func feed(_ string: String) -> [SSEEvent] { - feed(Array(string.utf8)) + public mutating func feed(_ string: String) throws -> [SSEEvent] { + try feed(string.utf8) } /// Feeds one byte; returns an event when a blank line completes one. - public mutating func feed(_ byte: UInt8) -> SSEEvent? { + public mutating func feed(_ byte: UInt8) throws -> SSEEvent? { switch byte { case 0x0A: // \n if previousWasCR { previousWasCR = false // second half of \r\n return nil } - return endLine() + return try endLine() case 0x0D: // \r previousWasCR = true - return endLine() + return try endLine() default: previousWasCR = false + guard line.count < Self.maximumLineBytes else { throw SSEParserError.lineTooLarge } line.append(byte) + try checkPendingEvent() return nil } } /// Call at end of stream: dispatches a trailing event that had no blank line after it. - public mutating func finish() -> SSEEvent? { + public mutating func finish() throws -> SSEEvent? { if !line.isEmpty { - processLine() + try processLine() } return dispatch() } - private mutating func endLine() -> SSEEvent? { + private mutating func endLine() throws -> SSEEvent? { if line.isEmpty { return dispatch() } - processLine() + try processLine() return nil } - private mutating func processLine() { + private mutating func checkPendingEvent() throws { + if (line.count == 5 && line == [0x64, 0x61, 0x74, 0x61, 0x3A]) || + (!sawFirstLine && line.count == 8 && line == [0xEF, 0xBB, 0xBF, 0x64, 0x61, 0x74, 0x61, 0x3A]) { + dataValueOffset = line.count + } + guard var offset = dataValueOffset else { return } + if (offset == 5 || offset == 8), line.count == offset + 1, line.last == 0x20 { + offset += 1 + dataValueOffset = offset + } + let byteCount = line.count - offset + (dataLines.isEmpty ? 0 : 1) + guard byteCount <= Self.maximumEventBytes - dataByteCount else { + throw SSEParserError.eventTooLarge + } + } + + private mutating func processLine() throws { + dataValueOffset = nil var bytes = line line.removeAll(keepingCapacity: true) if !sawFirstLine { @@ -97,7 +132,13 @@ public struct SSEParser { } switch field { - case "data": dataLines.append(String(value)) + case "data": + let byteCount = value.utf8.count + (dataLines.isEmpty ? 0 : 1) + guard byteCount <= Self.maximumEventBytes - dataByteCount else { + throw SSEParserError.eventTooLarge + } + dataByteCount += byteCount + dataLines.append(String(value)) case "event": eventType = String(value) case "id": if !value.contains("\0") { lastEventID = String(value) } default: break // "retry" and unknown fields are ignored @@ -107,6 +148,7 @@ public struct SSEParser { private mutating func dispatch() -> SSEEvent? { defer { dataLines.removeAll() + dataByteCount = 0 eventType = nil } guard !dataLines.isEmpty else { return nil } diff --git a/Tests/HowlerAppTests/CaptureLinkBundleTests.swift b/Tests/HowlerAppTests/CaptureLinkBundleTests.swift index bfb2461..ff41ca0 100644 --- a/Tests/HowlerAppTests/CaptureLinkBundleTests.swift +++ b/Tests/HowlerAppTests/CaptureLinkBundleTests.swift @@ -1,13 +1,69 @@ import XCTest final class CaptureLinkBundleTests: XCTestCase { - func testTheAppBundleRegistersTheCaptureLink() throws { - let root = URL(fileURLWithPath: #filePath) + private var root: URL { + URL(fileURLWithPath: #filePath) .deletingLastPathComponent() .deletingLastPathComponent() .deletingLastPathComponent() - let script = try String(contentsOf: root.appendingPathComponent("scripts/bundle.sh"), encoding: .utf8) - XCTAssertTrue(script.contains("CFBundleURLSchemes")) - XCTAssertTrue(script.contains("howler")) + } + + private func generatedPlist() throws -> Data { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/bash") + process.arguments = [root.appendingPathComponent("scripts/info-plist.sh").path] + process.currentDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let output = Pipe() + let errors = Pipe() + process.standardOutput = output + process.standardError = errors + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + XCTAssertEqual(process.terminationStatus, 0, + String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)) + return data + } + + private func registersCaptureLink(_ data: Data) throws -> Bool { + guard let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], + let types = plist["CFBundleURLTypes"] as? [[String: Any]] else { return false } + return types.contains { type in + (type["CFBundleURLSchemes"] as? [String])?.contains("howler") == true + } + } + + func testTheAppBundleRegistersTheCaptureLink() throws { + let data = try generatedPlist() + let plist = try XCTUnwrap(PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]) + XCTAssertEqual(plist["CFBundlePackageType"] as? String, "APPL") + let name = try XCTUnwrap(plist["CFBundleName"] as? String) + XCTAssertFalse(name.isEmpty) + XCTAssertEqual(plist["CFBundleExecutable"] as? String, name) + XCTAssertEqual(plist["LSUIElement"] as? Bool, true) + let types = try XCTUnwrap(plist["CFBundleURLTypes"] as? [[String: Any]]) + XCTAssertEqual(types.count, 1) + XCTAssertEqual(types.first?["CFBundleURLName"] as? String, plist["CFBundleIdentifier"] as? String) + XCTAssertEqual(types.first?["CFBundleURLSchemes"] as? [String], ["howler"]) + XCTAssertTrue(try registersCaptureLink(data)) + } + + func testCaptureSchemeInsideAnUnrelatedOuterDictionaryIsNotRegistered() throws { + let generated = try XCTUnwrap(PropertyListSerialization.propertyList(from: generatedPlist(), format: nil) as? [String: Any]) + let invalid = ["UnrelatedOuterKey": generated] + let data = try PropertyListSerialization.data(fromPropertyList: invalid, format: .xml, options: 0) + XCTAssertFalse(try registersCaptureLink(data)) + } + + func testCaptureSchemeWithoutURLTypesIsNotRegistered() throws { + let invalid: [String: Any] = ["CFBundleURLSchemes": ["howler"]] + let data = try PropertyListSerialization.data(fromPropertyList: invalid, format: .xml, options: 0) + XCTAssertFalse(try registersCaptureLink(data)) + } + + func testCaptureSchemeInAWronglyTypedURLTypesDictionaryIsNotRegistered() throws { + let invalid: [String: Any] = ["CFBundleURLTypes": ["CFBundleURLSchemes": ["howler"]]] + let data = try PropertyListSerialization.data(fromPropertyList: invalid, format: .xml, options: 0) + XCTAssertFalse(try registersCaptureLink(data)) } } diff --git a/Tests/HowlerAppTests/ConversationExecutionTests.swift b/Tests/HowlerAppTests/ConversationExecutionTests.swift index 5ecb2d5..b78c3e3 100644 --- a/Tests/HowlerAppTests/ConversationExecutionTests.swift +++ b/Tests/HowlerAppTests/ConversationExecutionTests.swift @@ -137,6 +137,63 @@ final class ConversationExecutionTests: XCTestCase { XCTAssertTrue(model.images.isEmpty) } + func testTransportSizeErrorsRetainHistoryAndPauseWaitingQuestions() async throws { + func frame(_ text: String) -> String { + "data: {\"choices\":[{\"delta\":{\"content\":\"\(text)\"}}]}\n\n" + } + let partial = "Partial" + let half = String(repeating: "a", count: 512 * 1024) + let chunk = String(repeating: "a", count: 256 * 1024) + let replyPrefix = String(repeating: frame(chunk), count: 31) + + frame(String(repeating: "a", count: chunk.utf8.count - partial.utf8.count)) + let cases = [ + (String(repeating: "a", count: 1024 * 1024 + 1) + "\n\n", partial, + "The server sent a line larger than 1 MiB."), + ("data: \(half)\ndata: \(half)\n\n", partial, + "The server sent an event larger than 1 MiB."), + (replyPrefix + frame("b"), partial + String(repeating: "a", count: 8 * 1024 * 1024 - partial.utf8.count), + "The reply is larger than 8 MiB.") + ] + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [QueueBoundaryURLProtocol.self] + let session = URLSession(configuration: configuration) + defer { session.invalidateAndCancel() } + let client = ChatClient(session: session) + for (suffix, expected, reason) in cases { + let model = model() + model.input = "Earlier question" + model.send() + streams.last?.yield("Earlier answer") + streams.last?.finish() + await waitUntil { model.queue.active == nil } + QueueBoundaryURLProtocol.body = Data((frame(partial) + suffix + "data: [DONE]\n\n").utf8) + var requestCount = 0 + model.streamFactory = { messages, options in + requestCount += 1 + return client.stream(service: Provider.openAI.service(), apiKey: "fixture-key", + messages: messages, options: options) + } + model.input = "Bounded question" + model.send() + model.input = "Waiting question" + model.send() + let deadline = ContinuousClock.now + .seconds(30) + while !model.queue.isPaused, model.queue.tasks[1].state != .completed, + ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + XCTAssertTrue(model.queue.isPaused) + XCTAssertEqual(model.queue.pauseReason, reason) + XCTAssertEqual(model.queue.tasks[0].answer, "Earlier answer") + XCTAssertEqual(model.queue.tasks[0].state, .completed) + XCTAssertTrue(model.queue.tasks[1].answer == expected) + XCTAssertEqual(model.queue.tasks[1].state, .paused) + XCTAssertEqual(model.queue.tasks[2].state, .queued) + XCTAssertEqual(requestCount, 1) + model.reset() + } + } + func testNewScreenshotPreservesDraftAssociationAndLanguageSnapshot() async { let model = model() model.settings.setReplyLanguage("zh-Hans") @@ -233,3 +290,20 @@ final class ConversationExecutionTests: XCTestCase { model.reset() } } + +private final class QueueBoundaryURLProtocol: URLProtocol { + static var body = Data() + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "text/event-stream"])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Self.body) + client?.urlProtocolDidFinishLoading(self) + } + + override func stopLoading() {} +} diff --git a/Tests/HowlerCoreTests/ChatStreamBoundaryTests.swift b/Tests/HowlerCoreTests/ChatStreamBoundaryTests.swift new file mode 100644 index 0000000..0a0aa45 --- /dev/null +++ b/Tests/HowlerCoreTests/ChatStreamBoundaryTests.swift @@ -0,0 +1,174 @@ +#if canImport(Darwin) +import Foundation +import XCTest +@testable import HowlerCore + +final class BoundaryURLProtocol: URLProtocol { + static var body = Data() + static var onStop: (() -> Void)? + private let lock = NSLock() + private var stopped = false + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "text/event-stream"])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Self.body) + let finish = DispatchWorkItem { [weak self] in + guard let self else { return } + lock.lock() + defer { lock.unlock() } + if !stopped { client?.urlProtocolDidFinishLoading(self) } + } + DispatchQueue.global().asyncAfter(deadline: .now() + 10, execute: finish) + } + + override func stopLoading() { + lock.lock() + let firstStop = !stopped + stopped = true + lock.unlock() + if firstStop { Self.onStop?() } + } +} + +final class ChatStreamBoundaryTests: XCTestCase { + private let replyLimit = 8 * 1024 * 1024 + private var session: URLSession! + + override func setUp() { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [BoundaryURLProtocol.self] + session = URLSession(configuration: configuration) + } + + override func tearDown() { + session.invalidateAndCancel() + BoundaryURLProtocol.onStop = nil + BoundaryURLProtocol.body = Data() + } + + private func frame(_ text: String, provider: Provider) -> String { + switch provider { + case .anthropic: + return "data: {\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_delta\",\"text\":\"\(text)\"}}\n\n" + case .gemini: + return "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"\(text)\"}]}}]}\n\n" + default: + return "data: {\"choices\":[{\"delta\":{\"content\":\"\(text)\"}}]}\n\n" + } + } + + private func done(_ provider: Provider) -> String { + switch provider { + case .anthropic: return "data: {\"type\":\"message_stop\"}\n\n" + case .gemini: return "data: {\"candidates\":[{\"finishReason\":\"STOP\"}]}\n\n" + default: return "data: [DONE]\n\n" + } + } + + private func transcript(_ text: String, provider: Provider) -> String { + let bytes = Array(text.utf8) + let chunkSize = 256 * 1024 + return stride(from: 0, to: bytes.count, by: chunkSize).map { offset in + frame(String(decoding: bytes[offset.. AsyncThrowingStream { + ChatClient(session: session).stream(service: provider.service(), apiKey: "fixture-key", + messages: [ChatMessage(role: .user, content: "Synthetic boundary probe")]) + } + + private func check(_ body: String, provider: Provider = .openAI, + expected: String, errorMessage: String? = nil, + file: StaticString = #filePath, line: UInt = #line) async { + BoundaryURLProtocol.body = Data(body.utf8) + let cancelled = expectation(description: "underlying request cancelled") + BoundaryURLProtocol.onStop = { cancelled.fulfill() } + var received = "" + do { + for try await delta in stream(provider) { received += delta } + XCTAssertNil(errorMessage, "Expected a size error", file: file, line: line) + } catch { + XCTAssertEqual(error.localizedDescription, errorMessage, file: file, line: line) + } + XCTAssertEqual(received.utf8.count, expected.utf8.count, file: file, line: line) + XCTAssertTrue(received == expected, "Previously yielded text must be retained", file: file, line: line) + await fulfillment(of: [cancelled], timeout: 2) + } + + func testVisibleReplyAtLimitCompletesForEveryWireFormat() async { + for provider in [Provider.openAI, .anthropic, .gemini] { + let text = String(repeating: "a", count: replyLimit - 4) + "πŸ‘‹" + let prefix = String(repeating: "a", count: replyLimit - 4) + await check(transcript(prefix, provider: provider) + frame("πŸ‘‹", provider: provider) + done(provider), + provider: provider, expected: text) + } + } + + func testReplyOneByteOverLimitKeepsTheCompletePriorDeltas() async { + let prefix = String(repeating: "a", count: replyLimit) + await check(transcript(prefix, provider: .openAI) + frame("b", provider: .openAI) + done(.openAI), + expected: prefix, errorMessage: "The reply is larger than 8 MiB.") + } + + func testMultibyteDeltaCrossingReplyLimitIsNotPartiallyYielded() async { + for provider in [Provider.openAI, .anthropic, .gemini] { + let prefix = String(repeating: "a", count: replyLimit - 3) + await check(transcript(prefix, provider: provider) + frame("πŸ‘‹", provider: provider) + done(provider), + provider: provider, expected: prefix, errorMessage: "The reply is larger than 8 MiB.") + } + } + + func testOversizedUnterminatedLineCancelsAndRetainsPriorText() async { + await check(frame("Prior text", provider: .openAI) + String(repeating: "a", count: 1024 * 1024 + 1), + expected: "Prior text", errorMessage: "The server sent a line larger than 1 MiB.") + } + + func testAccumulatedDataEventCancelsAndRetainsPriorText() async { + let half = String(repeating: "a", count: 512 * 1024) + await check(frame("Prior text", provider: .openAI) + "data: \(half)\ndata: \(half)\n\n" + done(.openAI), + expected: "Prior text", errorMessage: "The server sent an event larger than 1 MiB.") + } + + func testAccumulatedDataWithoutAFinalNewlineCancelsBeforeEOF() async { + let half = String(repeating: "a", count: 512 * 1024) + await check(frame("Prior text", provider: .openAI) + "data: \(half)\ndata: \(half)", + expected: "Prior text", errorMessage: "The server sent an event larger than 1 MiB.") + } + + func testDoneCancelsAnOtherwiseOpenRequest() async { + await check(frame("Normal reply", provider: .openAI) + done(.openAI), expected: "Normal reply") + } + + func testConsumerCancellationCancelsAnOtherwiseOpenRequest() async { + BoundaryURLProtocol.body = Data(frame("Partial", provider: .openAI).utf8) + let received = expectation(description: "first visible delta") + let cancelled = expectation(description: "underlying request cancelled") + BoundaryURLProtocol.onStop = { cancelled.fulfill() } + let reply = stream() + let consumer = Task { + do { + for try await delta in reply { + XCTAssertEqual(delta, "Partial") + received.fulfill() + } + } catch {} + } + await fulfillment(of: [received], timeout: 2) + consumer.cancel() + await consumer.value + await fulfillment(of: [cancelled], timeout: 2) + } + + func testIgnoredProviderTextDoesNotConsumeVisibleReplyBudget() async { + let ignored = "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"\(String(repeating: "a", count: 512 * 1024))\"}}]}\n\n" + let prefix = String(repeating: "a", count: replyLimit) + await check(ignored + transcript(prefix, provider: .openAI) + done(.openAI), expected: prefix) + } +} +#endif diff --git a/Tests/HowlerCoreTests/SSEParserTests.swift b/Tests/HowlerCoreTests/SSEParserTests.swift index 2413dc4..9b563a6 100644 --- a/Tests/HowlerCoreTests/SSEParserTests.swift +++ b/Tests/HowlerCoreTests/SSEParserTests.swift @@ -2,74 +2,170 @@ import XCTest @testable import HowlerCore final class SSEParserTests: XCTestCase { - func testParsesEventsSeparatedByBlankLines() { + func testParsesEventsSeparatedByBlankLines() throws { var parser = SSEParser() - let events = parser.feed("data: one\n\ndata: two\n\n") + let events = try parser.feed("data: one\n\ndata: two\n\n") XCTAssertEqual(events, [SSEEvent(data: "one"), SSEEvent(data: "two")]) } - func testEventFieldAndMultilineData() { + func testEventFieldAndMultilineData() throws { var parser = SSEParser() - let events = parser.feed("event: message_start\ndata: a\ndata: b\nid: 7\n\n") + let events = try parser.feed("event: message_start\ndata: a\ndata: b\nid: 7\n\n") XCTAssertEqual(events, [SSEEvent(event: "message_start", data: "a\nb", id: "7")]) } - func testCRLFAndCRLineEndings() { + func testCRLFAndCRLineEndings() throws { var parser = SSEParser() - XCTAssertEqual(parser.feed("data: crlf\r\n\r\n"), [SSEEvent(data: "crlf")]) - XCTAssertEqual(parser.feed("data: cr\r\r"), [SSEEvent(data: "cr")]) + XCTAssertEqual(try parser.feed("data: crlf\r\n\r\n"), [SSEEvent(data: "crlf")]) + XCTAssertEqual(try parser.feed("data: cr\r\r"), [SSEEvent(data: "cr")]) } - func testCRLFSplitAcrossChunks() { + func testCRLFSplitAcrossChunks() throws { var parser = SSEParser() - XCTAssertEqual(parser.feed("data: x\r"), []) + XCTAssertEqual(try parser.feed("data: x\r"), []) // The "\n" completes the first CRLF; the following "\r" is the blank line. - XCTAssertEqual(parser.feed("\n\r"), [SSEEvent(data: "x")]) + XCTAssertEqual(try parser.feed("\n\r"), [SSEEvent(data: "x")]) // Second half of the blank line's CRLF must not produce anything. - XCTAssertEqual(parser.feed("\n"), []) + XCTAssertEqual(try parser.feed("\n"), []) } - func testIgnoresCommentsAndUnknownFields() { + func testIgnoresCommentsAndUnknownFields() throws { var parser = SSEParser() - let events = parser.feed(": OPENROUTER PROCESSING\n\nretry: 1000\nfoo: bar\ndata: real\n\n") + let events = try parser.feed(": OPENROUTER PROCESSING\n\nretry: 1000\nfoo: bar\ndata: real\n\n") XCTAssertEqual(events, [SSEEvent(data: "real")]) } - func testValueWithoutSpaceAndColonsInValue() { + func testValueWithoutSpaceAndColonsInValue() throws { var parser = SSEParser() - XCTAssertEqual(parser.feed("data:{\"a\":\"b: c\"}\n\n"), [SSEEvent(data: "{\"a\":\"b: c\"}")]) + XCTAssertEqual(try parser.feed("data:{\"a\":\"b: c\"}\n\n"), [SSEEvent(data: "{\"a\":\"b: c\"}")]) } - func testByteByByteWithMultibyteUTF8Split() { + func testByteByByteWithMultibyteUTF8Split() throws { var parser = SSEParser() var events: [SSEEvent] = [] for byte in Array("data: δ½ ε₯½ πŸ‘‹\n\n".utf8) { - if let event = parser.feed(byte) { events.append(event) } + if let event = try parser.feed(byte) { events.append(event) } } XCTAssertEqual(events, [SSEEvent(data: "δ½ ε₯½ πŸ‘‹")]) } - func testFinishFlushesTrailingEventWithoutBlankLine() { + func testFinishFlushesTrailingEventWithoutBlankLine() throws { var parser = SSEParser() - XCTAssertEqual(parser.feed("data: tail"), []) - XCTAssertEqual(parser.finish(), SSEEvent(data: "tail")) - XCTAssertNil(parser.finish()) + XCTAssertEqual(try parser.feed("data: tail"), []) + XCTAssertEqual(try parser.finish(), SSEEvent(data: "tail")) + XCTAssertNil(try parser.finish()) } - func testEventTypeResetsBetweenEvents() { + func testEventTypeResetsBetweenEvents() throws { var parser = SSEParser() - let events = parser.feed("event: ping\ndata: {}\n\ndata: plain\n\n") + let events = try parser.feed("event: ping\ndata: {}\n\ndata: plain\n\n") XCTAssertEqual(events.map(\.event), ["ping", nil]) } - func testStripsLeadingBOM() { + func testStripsLeadingBOM() throws { var parser = SSEParser() let bytes: [UInt8] = [0xEF, 0xBB, 0xBF] + Array("data: bom\n\n".utf8) - XCTAssertEqual(parser.feed(bytes), [SSEEvent(data: "bom")]) + XCTAssertEqual(try parser.feed(bytes), [SSEEvent(data: "bom")]) } - func testBlankLineWithoutDataDispatchesNothing() { + func testBlankLineWithoutDataDispatchesNothing() throws { var parser = SSEParser() - XCTAssertEqual(parser.feed("\n\nevent: x\n\n"), []) + XCTAssertEqual(try parser.feed("\n\nevent: x\n\n"), []) + } +} + +final class SSEParserBoundaryTests: XCTestCase { + private let limit = 1024 * 1024 + + func testLineAtLimitAcceptsASplitMultibyteCharacterAndCRLF() throws { + var parser = SSEParser() + let text = String(repeating: "a", count: limit - 10) + "πŸ‘‹" + let bytes = Array(("data: " + text).utf8) + XCTAssertEqual(bytes.count, limit) + XCTAssertTrue(try parser.feed(bytes.dropLast(2)).isEmpty) + XCTAssertTrue(try parser.feed(bytes.suffix(2)).isEmpty) + let events = try parser.feed("\r\n\r\n") + XCTAssertEqual(events.count, 1) + XCTAssertEqual(events.first?.data, text) + } + + func testLineOverLimitThrowsBeforeAnyNewline() throws { + var parser = SSEParser() + XCTAssertTrue(try parser.feed(repeatElement(UInt8(0x61), count: limit)).isEmpty) + XCTAssertThrowsError(try parser.feed(UInt8(0x61))) { + XCTAssertEqual($0.localizedDescription, "The server sent a line larger than 1 MiB.") + } + } + + func testMultibyteLineOverLimitCountsUTF8Bytes() throws { + var parser = SSEParser() + let line = "data: " + String(repeating: "η•Œ", count: (limit - 6) / 3) + XCTAssertTrue(try parser.feed(line).isEmpty) + let remaining = limit - line.utf8.count + XCTAssertTrue(try parser.feed(repeatElement(UInt8(0x61), count: remaining)).isEmpty) + XCTAssertThrowsError(try parser.feed(UInt8(0xE7))) + } + + func testCommentsAndUnknownFieldsHaveTheSameLineLimit() throws { + for prefix in [":", "unknown:", "event:", "id:"] { + var parser = SSEParser() + XCTAssertTrue(try parser.feed(prefix + String(repeating: "a", count: limit - prefix.utf8.count)).isEmpty) + XCTAssertThrowsError(try parser.feed(UInt8(0x61)), prefix) + } + } + + func testEventAtLimitIncludesJoinedNewlinesAndResetsAfterDispatch() throws { + var parser = SSEParser() + let first = String(repeating: "a", count: limit / 2) + let second = String(repeating: "η•Œ", count: (limit / 2 - 1) / 3) + + String(repeating: "b", count: (limit / 2 - 1) % 3) + XCTAssertTrue(try parser.feed("data: \(first)\ndata: \(second)\n").isEmpty) + let events = try parser.feed("\ndata: next\n\n") + XCTAssertEqual(events.count, 2) + XCTAssertEqual(events.first?.data.utf8.count, limit) + XCTAssertEqual(events.last?.data, "next") + } + + func testMultipleDataLinesOverLimitThrowWithoutDispatch() throws { + var parser = SSEParser() + let half = String(repeating: "a", count: limit / 2) + XCTAssertTrue(try parser.feed("data: \(half)\n").isEmpty) + XCTAssertThrowsError(try parser.feed("data: \(half)\n")) { + XCTAssertEqual($0.localizedDescription, "The server sent an event larger than 1 MiB.") + } + } + + func testAccumulatedDataLimitThrowsBeforeTheNextLineEnds() throws { + var parser = SSEParser() + let half = String(repeating: "a", count: limit / 2) + XCTAssertTrue(try parser.feed("data: \(half)\n").isEmpty) + XCTAssertThrowsError(try parser.feed("data: \(half)")) + } + + func testFinishCountsUTF8ReplacementBytesTowardTheEventLimit() throws { + var parser = SSEParser() + let half = String(repeating: "a", count: limit / 2) + let almostHalf = String(repeating: "a", count: limit / 2 - 4) + XCTAssertTrue(try parser.feed("data: \(half)\ndata: \(almostHalf)\ndata: ").isEmpty) + XCTAssertNil(try parser.feed(UInt8(0xFF))) + XCTAssertThrowsError(try parser.finish()) + } + + func testBOMAndTheOptionalSpaceDoNotChangeTheEventPayloadBudget() throws { + var parser = SSEParser() + let first = String(repeating: "a", count: limit / 2) + let second = " " + String(repeating: "b", count: limit / 2 - 2) + XCTAssertTrue(try parser.feed("\u{FEFF}data: \(first)\ndata: \(second)").isEmpty) + let event = try parser.finish() + XCTAssertEqual(event?.data.utf8.count, limit) + XCTAssertTrue(event?.data.hasSuffix(second) == true) + } + + func testManyEmptyDataLinesCountTheirJoinedNewlines() throws { + var parser = SSEParser() + for _ in 0...limit { + _ = try parser.feed("data:\n") + } + XCTAssertThrowsError(try parser.feed("data:\n")) } } diff --git a/Tests/HowlerCoreTests/StreamDecoderTests.swift b/Tests/HowlerCoreTests/StreamDecoderTests.swift index 17dc350..1b7b6ea 100644 --- a/Tests/HowlerCoreTests/StreamDecoderTests.swift +++ b/Tests/HowlerCoreTests/StreamDecoderTests.swift @@ -7,10 +7,10 @@ final class StreamDecoderTests: XCTestCase { } /// Runs a raw SSE transcript through parser + decoder like `ChatClient` does. - private func run(_ transcript: String, _ format: WireFormat) -> (text: String, done: Bool, error: String?) { + private func run(_ transcript: String, _ format: WireFormat) throws -> (text: String, done: Bool, error: String?) { var parser = SSEParser() - var events = parser.feed(transcript) - if let tail = parser.finish() { events.append(tail) } + var events = try parser.feed(transcript) + if let tail = try parser.finish() { events.append(tail) } var text = "" for event in events { for delta in StreamDecoder.decode(event, format: format) { @@ -83,7 +83,7 @@ final class StreamDecoderTests: XCTestCase { XCTAssertEqual(decode(chunk, .openAICompatible), [.error("Provider returned error")]) } - func testOpenAITranscript() { + func testOpenAITranscript() throws { let transcript = """ : OPENROUTER PROCESSING @@ -99,7 +99,7 @@ final class StreamDecoderTests: XCTestCase { """ - let result = run(transcript, .openAICompatible) + let result = try run(transcript, .openAICompatible) XCTAssertEqual(result.text, "2 + 2 = **4**") XCTAssertTrue(result.done) XCTAssertNil(result.error) @@ -107,7 +107,7 @@ final class StreamDecoderTests: XCTestCase { // MARK: Anthropic - func testAnthropicTranscript() { + func testAnthropicTranscript() throws { let transcript = """ event: message_start data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-opus-5-5"}} @@ -147,7 +147,7 @@ final class StreamDecoderTests: XCTestCase { """ - let result = run(transcript, .anthropic) + let result = try run(transcript, .anthropic) XCTAssertEqual(result.text, "Hello, δΈ–η•Œ") XCTAssertTrue(result.done) XCTAssertNil(result.error) @@ -202,10 +202,10 @@ final class StreamDecoderTests: XCTestCase { guard case .error = decode(safety, .gemini).first else { return XCTFail("safety stop should be an error") } } - func testGeminiStopReasonEndsTheReply() { + func testGeminiStopReasonEndsTheReply() throws { let transcript = "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Line 1\\n\"}],\"role\":\"model\"}}]}\r\n\r\n" + "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Line 2\"}],\"role\":\"model\"},\"finishReason\":\"STOP\"}]}\r\n\r\n" - let result = run(transcript, .gemini) + let result = try run(transcript, .gemini) XCTAssertEqual(result.text, "Line 1\nLine 2") XCTAssertTrue(result.done) XCTAssertNil(result.error) diff --git a/scripts/bundle.sh b/scripts/bundle.sh index 035bf9f..8280430 100755 --- a/scripts/bundle.sh +++ b/scripts/bundle.sh @@ -84,64 +84,7 @@ install_name_tool -add_rpath "@executable_path/../Frameworks" "$APP/Contents/Mac # The icon is rendered from source by scripts/icon.sh and committed. cp "$ROOT/Resources/AppIcon.icns" "$APP/Contents/Resources/AppIcon.icns" -cat > "$APP/Contents/Info.plist" < - - - - CFBundleDevelopmentRegion - en - CFBundleDisplayName - ${APP_NAME} - CFBundleExecutable - ${APP_NAME} - CFBundleIconFile - AppIcon - CFBundleIdentifier - ${BUNDLE_ID} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${APP_NAME} - CFBundlePackageType - APPL - CFBundleShortVersionString - ${VERSION} - CFBundleVersion - ${BUILD_NUMBER} - LSApplicationCategoryType - public.app-category.productivity - LSMinimumSystemVersion - ${MIN_MACOS} - LSUIElement - - NSHighResolutionCapable - - NSPrincipalClass - NSApplication - SUFeedURL - ${SPARKLE_FEED_URL} - SUPublicEDKey - ${SPARKLE_PUBLIC_KEY} - SUScheduledCheckInterval - 86400 - SUAllowsAutomaticUpdates - - - CFBundleURLTypes - - - CFBundleURLName - ${BUNDLE_ID} - CFBundleURLSchemes - - howler - - - - - -PLIST +bash "$ROOT/scripts/info-plist.sh" "$APP_NAME" "$BUNDLE_ID" > "$APP/Contents/Info.plist" if [[ -n "$COMMIT" ]]; then for key in SUFeedURL SUPublicEDKey SUScheduledCheckInterval SUAllowsAutomaticUpdates CFBundleURLTypes; do plutil -remove "$key" "$APP/Contents/Info.plist" diff --git a/scripts/info-plist.sh b/scripts/info-plist.sh new file mode 100644 index 0000000..8b16b21 --- /dev/null +++ b/scripts/info-plist.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +source "$ROOT/app.config" +APP_NAME="${1:-$APP_NAME}" +BUNDLE_ID="${2:-$BUNDLE_ID}" + +cat < + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + ${APP_NAME} + CFBundleExecutable + ${APP_NAME} + CFBundleIconFile + AppIcon + CFBundleIdentifier + ${BUNDLE_ID} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${APP_NAME} + CFBundlePackageType + APPL + CFBundleShortVersionString + ${VERSION} + CFBundleVersion + ${BUILD_NUMBER} + LSApplicationCategoryType + public.app-category.productivity + LSMinimumSystemVersion + ${MIN_MACOS} + LSUIElement + + NSHighResolutionCapable + + NSPrincipalClass + NSApplication + SUFeedURL + ${SPARKLE_FEED_URL} + SUPublicEDKey + ${SPARKLE_PUBLIC_KEY} + SUScheduledCheckInterval + 86400 + SUAllowsAutomaticUpdates + + + CFBundleURLTypes + + + CFBundleURLName + ${BUNDLE_ID} + CFBundleURLSchemes + + howler + + + + + +PLIST