feat(ios): harden native connectivity

This commit is contained in:
Theo Browne committed 2026-08-09 20:52:49 -07:00
1 parent 411ba96443
commit c9679c3ec4
10 files changed
+1314 -44

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
import Foundation
public enum ImageAttachmentError: LocalizedError, Equatable, Sendable {
case empty
case tooLarge(actualBytes: Int, maximumBytes: Int)
case invalidName
case invalidMIMEType
public var errorDescription: String? {
switch self {
case .empty:
"The selected image is empty."
case let .tooLarge(actualBytes, maximumBytes):
"The image is \(actualBytes) bytes. T3 accepts up to \(maximumBytes) bytes."
case .invalidName:
"The image needs a valid file name."
case .invalidMIMEType:
"The selected file is not a supported image."
}
}
}
/// Inline upload shape accepted by `thread.turn.start`.
///
/// There is intentionally no standalone attachment-upload endpoint in the T3
/// contract. New image bytes travel as a base64 data URL on the turn command;
/// the server normalizes them into a persisted `ChatAttachment`.
public struct UploadChatImageAttachment: Codable, Equatable, Sendable {
public static let maximumBytes = 10 * 1024 * 1024
public let type: String
public let name: String
public let mimeType: String
public let sizeBytes: Int
public let dataUrl: String
public init(data: Data, name: String, mimeType: String) throws {
guard !data.isEmpty else { throw ImageAttachmentError.empty }
guard data.count <= Self.maximumBytes else {
throw ImageAttachmentError.tooLarge(
actualBytes: data.count,
maximumBytes: Self.maximumBytes
)
}
let normalizedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedName.isEmpty, normalizedName.count <= 255 else {
throw ImageAttachmentError.invalidName
}
let normalizedMIME = mimeType.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard normalizedMIME.hasPrefix("image/"), normalizedMIME.count <= 100 else {
throw ImageAttachmentError.invalidMIMEType
}
type = "image"
self.name = normalizedName
self.mimeType = normalizedMIME
sizeBytes = data.count
dataUrl = "data:\(normalizedMIME);base64,\(data.base64EncodedString())"
}
var jsonValue: JSONValue {
.object([
"type": .string(type),
"name": .string(name),
"mimeType": .string(mimeType),
"sizeBytes": .number(Double(sizeBytes)),
"dataUrl": .string(dataUrl),
])
}
}
public enum AssetResource: Equatable, Sendable {
case workspaceFile(threadID: String, path: String)
case attachment(id: String)
case projectFavicon(cwd: String)
var jsonValue: JSONValue {
switch self {
case let .workspaceFile(threadID, path):
.object([
"_tag": .string("workspace-file"),
"threadId": .string(threadID),
"path": .string(path),
])
case let .attachment(id):
.object([
"_tag": .string("attachment"),
"attachmentId": .string(id),
])
case let .projectFavicon(cwd):
.object([
"_tag": .string("project-favicon"),
"cwd": .string(cwd),
])
}
}
}
public struct AssetCreateURLResult: Codable, Equatable, Sendable {
public let relativeUrl: String
/// Unix epoch milliseconds from the server contract.
public let expiresAt: Double
}
+102 -4
View File
@@ -7,12 +7,23 @@ public protocol HTTPTransport: Sendable {
public struct URLSessionHTTPTransport: HTTPTransport {
private let session: URLSession
public init(session: URLSession = .shared) {
self.session = session
public init(session: URLSession? = nil) {
if let session {
self.session = session
} else {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = [
"Accept-Encoding": HTTPRequestPolicy.acceptEncoding,
]
self.session = URLSession(configuration: configuration)
}
}
public func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {
let (data, response) = try await session.data(for: request)
// URLSession transparently decodes gzip responses before returning
// their body. Applying the policy here is a final guard for requests
// constructed outside EnvironmentAPI.
let (data, response) = try await session.data(for: HTTPRequestPolicy.prepare(request))
guard let httpResponse = response as? HTTPURLResponse else {
throw HTTPError.invalidResponse
}
@@ -20,6 +31,26 @@ public struct URLSessionHTTPTransport: HTTPTransport {
}
}
/// Shared wire-level defaults for HTTP requests.
///
/// Foundation's URL loading system transparently decompresses gzip response
/// bodies. The explicit offer matters because T3 only compresses JSON when the
/// client advertises support.
public enum HTTPRequestPolicy {
public static let acceptEncoding = "gzip"
public static func prepare(_ request: URLRequest) -> URLRequest {
var prepared = request
if prepared.value(forHTTPHeaderField: "Accept-Encoding") == nil {
prepared.setValue(acceptEncoding, forHTTPHeaderField: "Accept-Encoding")
}
if prepared.value(forHTTPHeaderField: "Accept") == nil {
prepared.setValue("application/json", forHTTPHeaderField: "Accept")
}
return prepared
}
}
public enum HTTPError: LocalizedError, Sendable {
case invalidResponse
case status(Int, message: String, traceID: String?)
@@ -126,6 +157,41 @@ public actor EnvironmentAPI {
)
}
public func clientSessions(for environment: Environment) async throws
-> [AuthClientSession]
{
try await authorized(
environment: environment,
path: "/api/auth/clients",
method: "GET",
as: [AuthClientSession].self
)
}
public func revokeClientSession(
id: String,
environment: Environment
) async throws -> AuthClientSessionRevokeResult {
try await authorized(
environment: environment,
path: "/api/auth/clients/revoke",
method: "POST",
body: JSONEncoder.t3.encode(["sessionId": id]),
as: AuthClientSessionRevokeResult.self
)
}
public func revokeOtherClientSessions(
for environment: Environment
) async throws -> AuthOtherClientSessionsRevokeResult {
try await authorized(
environment: environment,
path: "/api/auth/clients/revoke-others",
method: "POST",
as: AuthOtherClientSessionsRevokeResult.self
)
}
private func authorized<Result: Decodable & Sendable>(
environment: Environment,
path: String,
@@ -150,7 +216,7 @@ public actor EnvironmentAPI {
_ request: URLRequest,
as type: Result.Type
) async throws -> Result {
let (data, response) = try await transport.data(for: request)
let (data, response) = try await transport.data(for: HTTPRequestPolicy.prepare(request))
guard (200..<300).contains(response.statusCode) else {
let body = try? JSONDecoder.t3.decode(ErrorBody.self, from: data)
throw HTTPError.status(
@@ -179,6 +245,38 @@ public struct AuthSessionState: Codable, Equatable, Sendable {
public let expiresAt: String?
}
public struct AuthClientMetadata: Codable, Equatable, Sendable {
public let label: String?
public let ipAddress: String?
public let userAgent: String?
public let deviceType: String
public let os: String?
public let browser: String?
}
public struct AuthClientSession: Codable, Identifiable, Equatable, Sendable {
public var id: String { sessionId }
public let sessionId: String
public let subject: String
public let scopes: [String]
public let method: String
public let client: AuthClientMetadata
public let issuedAt: String
public let expiresAt: String
public let lastConnectedAt: String?
public let connected: Bool
public let current: Bool
}
public struct AuthClientSessionRevokeResult: Codable, Equatable, Sendable {
public let revoked: Bool
}
public struct AuthOtherClientSessionsRevokeResult: Codable, Equatable, Sendable {
public let revokedCount: Int
}
func endpoint(_ baseURL: URL, path: String) -> URL {
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)!
components.path = path
+181
View File
@@ -0,0 +1,181 @@
import Foundation
public struct ConnectionProbeResult: Equatable, Sendable {
public let baseURL: URL
public let descriptor: EnvironmentDescriptor
public let latency: Duration
}
public enum ConnectionProbeError: LocalizedError, Equatable, Sendable {
case invalidURL
case unavailableHost(String)
case timeout(String)
case likelyLocalNetworkDenied(String)
case serverRejected(status: Int, message: String)
case transport(String)
public var errorDescription: String? {
switch self {
case .invalidURL:
"Enter a valid T3 server address."
case let .unavailableHost(host):
"Could not reach \(host). Check that the server is running and both devices are online."
case let .timeout(host):
"\(host) did not respond in time."
case let .likelyLocalNetworkDenied(host):
"Local Network access appears to be off for T3 Code. Allow it in Settings, then retry \(host)."
case let .serverRejected(status, message):
"\(message) (HTTP \(status))"
case let .transport(message):
message
}
}
}
/// Performs the public environment-descriptor request before token exchange.
///
/// iOS does not expose a direct Local Network privacy authorization query. A
/// real connection attempt is the authoritative way to trigger/check access;
/// failures carrying POSIX permission evidence are reported separately from an
/// offline server.
public actor LocalNetworkProbe {
private let transport: any HTTPTransport
public init(transport: any HTTPTransport = URLSessionHTTPTransport()) {
self.transport = transport
}
public func probe(
address rawAddress: String,
timeout: TimeInterval = 5
) async throws -> ConnectionProbeResult {
let fields: PairingInputFields
do {
fields = try PairingURL.parseFields(rawAddress)
} catch {
throw ConnectionProbeError.invalidURL
}
guard let baseURL = URL(string: fields.host),
let host = baseURL.host,
["http", "https"].contains(baseURL.scheme?.lowercased() ?? "")
else {
throw ConnectionProbeError.invalidURL
}
var request = URLRequest(
url: endpoint(baseURL, path: "/.well-known/t3/environment"),
timeoutInterval: max(1, timeout)
)
request.httpMethod = "GET"
let clock = ContinuousClock()
let startedAt = clock.now
do {
let (data, response) = try await transport.data(
for: HTTPRequestPolicy.prepare(request)
)
guard (200..<300).contains(response.statusCode) else {
let body = try? JSONDecoder.t3.decode(JSONValue.self, from: data)
throw ConnectionProbeError.serverRejected(
status: response.statusCode,
message: body?["message"]?.stringValue
?? body?["reason"]?.stringValue
?? "The server rejected the connection probe."
)
}
let descriptor = try JSONDecoder.t3.decode(EnvironmentDescriptor.self, from: data)
return ConnectionProbeResult(
baseURL: baseURL,
descriptor: descriptor,
latency: startedAt.duration(to: clock.now)
)
} catch let error as ConnectionProbeError {
throw error
} catch {
throw Self.classify(error, host: host, isLocal: Self.isLocalHost(host))
}
}
public static func classify(
_ error: any Error,
host: String,
isLocal: Bool
) -> ConnectionProbeError {
let nsError = error as NSError
let urlCode = URLError.Code(rawValue: nsError.code)
if nsError.domain == NSURLErrorDomain {
switch urlCode {
case .timedOut:
return .timeout(host)
case .cannotFindHost, .dnsLookupFailed, .cannotConnectToHost:
if isLocal, hasPermissionDenialEvidence(nsError) {
return .likelyLocalNetworkDenied(host)
}
return .unavailableHost(host)
case .notConnectedToInternet, .networkConnectionLost, .internationalRoamingOff,
.dataNotAllowed:
if isLocal, hasPermissionDenialEvidence(nsError) {
return .likelyLocalNetworkDenied(host)
}
return .unavailableHost(host)
default:
break
}
}
if isLocal, hasPermissionDenialEvidence(nsError) {
return .likelyLocalNetworkDenied(host)
}
return .transport(nsError.localizedDescription)
}
public static func isLocalHost(_ host: String) -> Bool {
let value = host
.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
.lowercased()
if value == "localhost" || value == "::1" || value.hasSuffix(".local") {
return true
}
if value.hasPrefix("10.")
|| value.hasPrefix("127.")
|| value.hasPrefix("192.168.")
|| value.hasPrefix("169.254.")
{
return true
}
let octets = value.split(separator: ".").compactMap { Int($0) }
if octets.count == 4, octets[0] == 172, (16...31).contains(octets[1]) {
return true
}
// IPv6 unique-local and link-local ranges.
return value.hasPrefix("fc")
|| value.hasPrefix("fd")
|| value.hasPrefix("fe8")
|| value.hasPrefix("fe9")
|| value.hasPrefix("fea")
|| value.hasPrefix("feb")
}
private static func hasPermissionDenialEvidence(_ error: NSError) -> Bool {
if error.domain == NSPOSIXErrorDomain, error.code == 1 || error.code == 13 {
return true
}
let description = [
error.localizedDescription,
error.localizedFailureReason,
error.localizedRecoverySuggestion,
String(describing: error.userInfo),
]
.compactMap { $0 }
.joined(separator: " ")
.lowercased()
if description.contains("local network prohibited")
|| description.contains("localnetworkdenied")
|| description.contains("local network denied")
{
return true
}
if let underlying = error.userInfo[NSUnderlyingErrorKey] as? NSError {
return hasPermissionDenialEvidence(underlying)
}
return false
}
}
+7 -1
View File
@@ -22,6 +22,12 @@ public actor PairingService {
"orchestration:operate",
"terminal:operate",
"review:write",
// Startup pairing credentials carry administrative access. Requesting
// these scopes preserves that access for native multi-device
// management; ordinary pairing links remain bounded by the scopes the
// server granted them.
"access:read",
"access:write",
"relay:read",
]
@@ -134,7 +140,7 @@ public actor PairingService {
"application/x-www-form-urlencoded",
forHTTPHeaderField: "Content-Type"
)
let (data, response) = try await transport.data(for: request)
let (data, response) = try await transport.data(for: HTTPRequestPolicy.prepare(request))
guard (200..<300).contains(response.statusCode) else {
let body = try? JSONDecoder.t3.decode(JSONValue.self, from: data)
throw HTTPError.status(
+201 -27
View File
@@ -6,72 +6,232 @@ public struct PairingTarget: Equatable, Sendable {
public let webSocketBaseURL: URL
}
/// Display fields produced from pasted text or a scanned QR payload.
public struct PairingInputFields: Equatable, Sendable {
public let host: String
public let pairingCode: String
public let label: String?
}
public enum PairingURLError: LocalizedError, Equatable {
case emptyInput
case invalidURL
case unsupportedScheme
case missingToken
case missingHost
case emptyQRCode
case invalidQRCode
public var errorDescription: String? {
switch self {
case .emptyInput: "Enter a server address."
case .invalidURL: "Pairing URL is invalid."
case .unsupportedScheme: "Pairing URL uses an unsupported scheme."
case .missingToken: "Pairing URL is missing its token."
case .missingHost: "Pairing URL is missing its environment host."
case .emptyQRCode: "Scanned QR code did not contain a pairing URL."
case .invalidQRCode: "Scanned QR code is not a T3 pairing link."
}
}
}
public enum PairingURL {
private static let supportedSchemes = Set(["http", "https", "ws", "wss"])
/// Resolves a complete pairing link from a clipboard, universal link, or
/// QR scanner. `t3code://pair?pairingUrl=...` wrappers are unwrapped.
public static func resolve(_ rawValue: String) throws -> PairingTarget {
let trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines)
guard var components = URLComponents(string: trimmed), components.url != nil else {
throw PairingURLError.invalidURL
}
guard ["http", "https", "ws", "wss"].contains(components.scheme?.lowercased() ?? "") else {
throw PairingURLError.unsupportedScheme
let extracted = try extractPairingURL(from: rawValue, qrInput: false)
let fields = try parseFields(extracted)
return try directTarget(host: fields.host, credential: requireToken(fields.pairingCode))
}
/// Resolves split form fields. If the host field contains a complete
/// pairing URL, its embedded token wins. This lets pasting a full link into
/// the host field immediately populate both inputs.
public static func resolve(host: String, pairingCode: String) throws -> PairingTarget {
let fields = try parseFields(host)
let embeddedCode = fields.pairingCode.trimmingCharacters(in: .whitespacesAndNewlines)
let code = embeddedCode.isEmpty ? pairingCode : embeddedCode
return try directTarget(host: fields.host, credential: requireToken(code))
}
/// Splits a complete URL or loose `host code` connection string into the
/// two fields shown by onboarding.
public static func parseFields(_ rawValue: String) throws -> PairingInputFields {
let extracted = try extractPairingURL(from: rawValue, qrInput: false)
if let loose = looseHostAndCode(extracted) {
let normalized = try normalizedBaseURL(loose.host)
return PairingInputFields(
host: displayHost(normalized),
pairingCode: loose.code,
label: nil
)
}
guard let components = strictURLComponents(extracted) else {
// Bare hosts are valid form input even before the code is entered.
let normalized = try normalizedBaseURL(extracted)
return PairingInputFields(
host: displayHost(normalized),
pairingCode: "",
label: nil
)
}
try requireSupportedScheme(components.scheme)
let query = components.queryItems ?? []
let fragment = URLComponents(string: "?\(components.fragment ?? "")")?.queryItems ?? []
let fragment = queryItems(fromFragment: components.fragment)
let token = (fragment + query)
.first(where: { $0.name == "token" })?
.first(where: { $0.name.caseInsensitiveCompare("token") == .orderedSame })?
.value?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let label = query
.first(where: { $0.name.caseInsensitiveCompare("label") == .orderedSame })?
.value?
.trimmingCharacters(in: .whitespacesAndNewlines)
if let hosted = query.first(where: { $0.name == "host" })?.value,
!hosted.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return try directTarget(host: hosted, credential: requireToken(token))
if let hosted = query
.first(where: { $0.name.caseInsensitiveCompare("host") == .orderedSame })?
.value?
.trimmingCharacters(in: .whitespacesAndNewlines),
!hosted.isEmpty
{
let normalized = try normalizedBaseURL(hosted)
return PairingInputFields(
host: displayHost(normalized),
pairingCode: token,
label: label?.isEmpty == false ? label : nil
)
}
components.path = "/"
components.query = nil
components.fragment = nil
guard let base = components.url, base.host != nil else { throw PairingURLError.missingHost }
return try target(baseURL: base, credential: requireToken(token))
guard components.host != nil else { throw PairingURLError.missingHost }
let normalized = try normalizedBaseURL(extracted)
return PairingInputFields(
host: displayHost(normalized),
pairingCode: token,
label: label?.isEmpty == false ? label : nil
)
}
public static func resolve(host: String, pairingCode: String) throws -> PairingTarget {
let normalized = host.contains("://") ? host : "https://\(host)"
guard let url = URL(string: normalized), url.host != nil else {
/// Extracts a pairing URL from a QR payload. Native deep links generated
/// by the React Native client are accepted alongside ordinary URLs.
public static func pairingURL(fromQRCode payload: String) throws -> String {
try extractPairingURL(from: payload, qrInput: true)
}
public static func build(host: String, pairingCode: String) throws -> String {
let base = try normalizedBaseURL(host)
var components = URLComponents(url: base, resolvingAgainstBaseURL: false)!
components.path = "/pair"
components.percentEncodedFragment = URLComponents().withQueryItems([
URLQueryItem(name: "token", value: try requireToken(pairingCode)),
]).percentEncodedQuery
guard let value = components.url?.absoluteString else {
throw PairingURLError.invalidURL
}
return try directTarget(host: normalized, credential: requireToken(pairingCode))
return value
}
private static func extractPairingURL(
from rawValue: String,
qrInput: Bool
) throws -> String {
let trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
throw qrInput ? PairingURLError.emptyQRCode : PairingURLError.emptyInput
}
guard let components = URLComponents(string: trimmed),
components.scheme?.lowercased() == "t3code"
else {
return trimmed
}
let wrapped = components.queryItems?
.first(where: { $0.name.caseInsensitiveCompare("pairingUrl") == .orderedSame })?
.value?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !wrapped.isEmpty else {
throw qrInput ? PairingURLError.invalidQRCode : PairingURLError.invalidURL
}
return wrapped
}
private static func looseHostAndCode(_ value: String) -> (host: String, code: String)? {
// URLs legitimately contain percent-encoded or query whitespace, so
// only use this fallback when the last whitespace-delimited token
// looks like a compact pairing code.
let fields = value.split(whereSeparator: \.isWhitespace).map(String.init)
guard fields.count >= 2, let code = fields.last,
code.range(of: #"^[A-Za-z0-9_-]{4,256}$"#, options: .regularExpression) != nil
else {
return nil
}
let host = fields.dropLast().joined(separator: " ")
guard host.contains(".") || host.contains(":") || host.hasPrefix("/") else {
return nil
}
return (host, code)
}
private static func directTarget(host: String, credential: String) throws -> PairingTarget {
let normalized = host.contains("://") ? host : "https://\(host)"
guard var components = URLComponents(string: normalized), let url = components.url else {
try target(baseURL: normalizedBaseURL(host), credential: credential)
}
private static func normalizedBaseURL(_ rawValue: String) throws -> URL {
let trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { throw PairingURLError.emptyInput }
let withoutLeadingSlashes = trimmed.replacingOccurrences(
of: #"^/+"#,
with: "",
options: .regularExpression
)
let normalized: String
if withoutLeadingSlashes.range(
of: #"^[A-Za-z][A-Za-z0-9+.-]*://"#,
options: .regularExpression
) != nil {
normalized = withoutLeadingSlashes
} else {
normalized = "https://\(withoutLeadingSlashes)"
}
guard var components = URLComponents(string: normalized),
components.url != nil
else {
throw PairingURLError.invalidURL
}
guard ["http", "https", "ws", "wss"].contains(components.scheme?.lowercased() ?? "") else {
throw PairingURLError.unsupportedScheme
}
try requireSupportedScheme(components.scheme)
guard components.host != nil else { throw PairingURLError.missingHost }
components.path = "/"
components.query = nil
components.fragment = nil
guard let base = components.url, url.host != nil else { throw PairingURLError.missingHost }
return try target(baseURL: base, credential: credential)
guard let base = components.url else { throw PairingURLError.invalidURL }
return base
}
private static func strictURLComponents(_ value: String) -> URLComponents? {
guard value.range(
of: #"^[A-Za-z][A-Za-z0-9+.-]*://"#,
options: .regularExpression
) != nil else {
return nil
}
return URLComponents(string: value)
}
private static func queryItems(fromFragment fragment: String?) -> [URLQueryItem] {
guard let fragment, !fragment.isEmpty else { return [] }
var components = URLComponents()
components.percentEncodedQuery = fragment
return components.queryItems ?? []
}
private static func displayHost(_ url: URL) -> String {
var value = url.absoluteString
if value.hasSuffix("/") { value.removeLast() }
return value
}
private static func target(baseURL: URL, credential: String) throws -> PairingTarget {
@@ -100,9 +260,23 @@ public enum PairingURL {
)
}
private static func requireSupportedScheme(_ scheme: String?) throws {
guard supportedSchemes.contains(scheme?.lowercased() ?? "") else {
throw PairingURLError.unsupportedScheme
}
}
private static func requireToken(_ token: String?) throws -> String {
let trimmed = token?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !trimmed.isEmpty else { throw PairingURLError.missingToken }
return trimmed
}
}
private extension URLComponents {
func withQueryItems(_ items: [URLQueryItem]) -> URLComponents {
var copy = self
copy.queryItems = items
return copy
}
}
@@ -0,0 +1,136 @@
import Foundation
public struct ServerProviderAuthSnapshot: Codable, Equatable, Sendable {
public let status: String
public let type: String?
public let label: String?
public let email: String?
}
public struct ServerProviderOptionChoice: Codable, Identifiable, Equatable, Sendable {
public let id: String
public let label: String
public let description: String?
public let isDefault: Bool?
}
public struct ServerSelectOptionDescriptor: Codable, Identifiable, Equatable, Sendable {
public let id: String
public let label: String
public let description: String?
public let options: [ServerProviderOptionChoice]
public let currentValue: String?
public let promptInjectedValues: [String]?
}
public struct ServerBooleanOptionDescriptor: Codable, Identifiable, Equatable, Sendable {
public let id: String
public let label: String
public let description: String?
public let currentValue: Bool?
}
public enum ServerProviderOptionDescriptor: Codable, Equatable, Sendable {
case select(ServerSelectOptionDescriptor)
case boolean(ServerBooleanOptionDescriptor)
private enum CodingKeys: String, CodingKey { case type }
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch try container.decode(String.self, forKey: .type) {
case "select":
self = .select(try ServerSelectOptionDescriptor(from: decoder))
case "boolean":
self = .boolean(try ServerBooleanOptionDescriptor(from: decoder))
case let type:
throw DecodingError.dataCorruptedError(
forKey: .type,
in: container,
debugDescription: "Unknown provider option type \(type)"
)
}
}
public func encode(to encoder: any Encoder) throws {
switch self {
case let .select(value):
try value.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode("select", forKey: .type)
case let .boolean(value):
try value.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode("boolean", forKey: .type)
}
}
}
public struct ServerModelCapabilities: Codable, Equatable, Sendable {
public let optionDescriptors: [ServerProviderOptionDescriptor]?
}
public struct ServerProviderModelSnapshot: Codable, Identifiable, Equatable, Sendable {
public var id: String { slug }
public let slug: String
public let name: String
public let shortName: String?
public let subProvider: String?
public let isCustom: Bool
public let isDefault: Bool?
public let capabilities: ServerModelCapabilities?
}
public struct ServerProviderSnapshot: Codable, Identifiable, Equatable, Sendable {
public var id: String { instanceId }
public let instanceId: String
public let driver: String
public let displayName: String?
public let accentColor: String?
public let badgeLabel: String?
public let showInteractionModeToggle: Bool?
public let requiresNewThreadForModelChange: Bool?
public let enabled: Bool
public let installed: Bool
public let version: String?
public let status: String
public let auth: ServerProviderAuthSnapshot
public let checkedAt: String
public let message: String?
public let availability: String?
public let unavailableReason: String?
public let models: [ServerProviderModelSnapshot]
}
/// Narrow decode view of the much larger `ServerConfig` RPC result.
public struct ServerConfigSnapshot: Codable, Equatable, Sendable {
public let providers: [ServerProviderSnapshot]
}
public enum ServerConfigStreamEvent: Decodable, Sendable {
case snapshot(ServerConfigSnapshot)
case providerStatuses([ServerProviderSnapshot])
case unrelated(type: String)
private enum CodingKeys: String, CodingKey { case type, config, payload }
private struct ProviderPayload: Decodable { let providers: [ServerProviderSnapshot] }
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
switch type {
case "snapshot":
self = .snapshot(
try container.decode(ServerConfigSnapshot.self, forKey: .config)
)
case "providerStatuses":
self = .providerStatuses(
try container.decode(ProviderPayload.self, forKey: .payload).providers
)
default:
self = .unrelated(type: type)
}
}
}
+107 -8
View File
@@ -52,6 +52,40 @@ public actor T3Client {
try await api.threadSnapshot(id: id, environment: environment)
}
public func serverConfig() async throws -> ServerConfigSnapshot {
try await rpc.request(
RPCMethod.serverGetConfig.rawValue,
as: ServerConfigSnapshot.self
)
}
public func serverConfigEvents() async
-> AsyncThrowingStream<ServerConfigStreamEvent, Error>
{
await rpc.subscribe(
RPCMethod.subscribeServerConfig.rawValue,
as: ServerConfigStreamEvent.self
)
}
public func clientSessions() async throws -> [AuthClientSession] {
try await api.clientSessions(for: environment)
}
public func authSession() async throws -> AuthSessionState {
try await api.session(for: environment)
}
@discardableResult
public func revokeClientSession(id: String) async throws -> Bool {
try await api.revokeClientSession(id: id, environment: environment).revoked
}
@discardableResult
public func revokeOtherClientSessions() async throws -> Int {
try await api.revokeOtherClientSessions(for: environment).revokedCount
}
/// HTTP live-sync fallback. Each iteration is an independent request, so a
/// transient network loss naturally reconnects without replaying commands.
public func pollShell(
@@ -119,14 +153,18 @@ public actor T3Client {
threadID: String,
text: String,
runtimeMode: RuntimeMode,
interactionMode: InteractionMode = .default
interactionMode: InteractionMode = .default,
model: ModelSelection? = nil,
attachments: [UploadChatImageAttachment] = []
) async throws -> DispatchResult {
try await dispatch(
OrchestrationCommands.sendTurn(
try OrchestrationCommands.sendTurn(
threadID: threadID,
text: text,
runtimeMode: runtimeMode,
interactionMode: interactionMode
interactionMode: interactionMode,
model: model,
attachments: attachments
)
)
}
@@ -156,6 +194,37 @@ public actor T3Client {
)
}
/// Atomically creates a thread and starts its first turn. This is the
/// server-supported path for message-first thread creation.
@discardableResult
public func createThreadAndSend(
threadID: String = UUID().uuidString,
projectID: String,
title: String,
text: String,
model: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: InteractionMode = .default,
branch: String? = nil,
worktreePath: String? = nil,
attachments: [UploadChatImageAttachment] = []
) async throws -> DispatchResult {
try await dispatch(
try OrchestrationCommands.createThreadAndSend(
threadID: threadID,
projectID: projectID,
title: title,
text: text,
model: model,
runtimeMode: runtimeMode,
interactionMode: interactionMode,
branch: branch,
worktreePath: worktreePath,
attachments: attachments
)
)
}
@discardableResult
public func createProject(
projectID: String = UUID().uuidString,
@@ -328,6 +397,27 @@ public actor T3Client {
)
}
/// Issues a short-lived authenticated URL for a persisted attachment,
/// workspace preview, or project favicon.
public func createAssetURL(resource: AssetResource) async throws -> AssetCreateURLResult {
try await rpc.request(
RPCMethod.assetsCreateURL.rawValue,
payload: .object(["resource": resource.jsonValue]),
as: AssetCreateURLResult.self
)
}
public func resolvedAssetURL(resource: AssetResource) async throws -> URL {
let result = try await createAssetURL(resource: resource)
guard let url = URL(
string: result.relativeUrl,
relativeTo: environment.httpBaseURL
)?.absoluteURL else {
throw RPCError.protocolViolation("The server returned an invalid asset URL.")
}
return url
}
// MARK: VCS and source control
public func refreshVCSStatus(cwd: String) async throws -> VCSStatus {
@@ -859,6 +949,8 @@ public enum RPCMethod: String, Sendable {
case projectsReadFile = "projects.readFile"
case projectsWriteFile = "projects.writeFile"
case filesystemBrowse = "filesystem.browse"
case assetsCreateURL = "assets.createUrl"
case subscribeServerConfig
case subscribeVCSStatus = "subscribeVcsStatus"
case vcsPull = "vcs.pull"
case vcsRefreshStatus = "vcs.refreshStatus"
@@ -943,11 +1035,13 @@ public enum OrchestrationCommands {
text: String,
runtimeMode: RuntimeMode,
interactionMode: InteractionMode = .default,
model: ModelSelection? = nil,
attachments: [UploadChatImageAttachment] = [],
commandID: String = UUID().uuidString,
messageID: String = UUID().uuidString,
createdAt: String = now()
) -> JSONValue {
.object([
) throws -> JSONValue {
var command: [String: JSONValue] = [
"type": .string("thread.turn.start"),
"commandId": .string(commandID),
"threadId": .string(threadID),
@@ -955,12 +1049,16 @@ public enum OrchestrationCommands {
"messageId": .string(messageID),
"role": .string("user"),
"text": .string(text),
"attachments": .array([]),
"attachments": .array(attachments.map(\.jsonValue)),
]),
"runtimeMode": .string(runtimeMode.rawValue),
"interactionMode": .string(interactionMode.rawValue),
"createdAt": .string(createdAt),
])
]
if let model {
command["modelSelection"] = try .encode(model)
}
return .object(command)
}
public static func createThreadAndSend(
@@ -973,6 +1071,7 @@ public enum OrchestrationCommands {
interactionMode: InteractionMode = .default,
branch: String? = nil,
worktreePath: String? = nil,
attachments: [UploadChatImageAttachment] = [],
commandID: String = UUID().uuidString,
messageID: String = UUID().uuidString,
createdAt: String = now()
@@ -996,7 +1095,7 @@ public enum OrchestrationCommands {
"messageId": .string(messageID),
"role": .string("user"),
"text": .string(text),
"attachments": .array([]),
"attachments": .array(attachments.map(\.jsonValue)),
]),
"runtimeMode": .string(runtimeMode.rawValue),
"interactionMode": .string(interactionMode.rawValue),
+35 -4
View File
@@ -10,15 +10,46 @@ public protocol WebSocketConnecting: Sendable {
func connect(to url: URL) async throws -> any WebSocketConnection
}
public enum WebSocketHandshakeRequest {
public static let perMessageDeflateOffer = "permessage-deflate; client_max_window_bits"
/// URLSessionWebSocketTask accepts a URLRequest for its opening handshake.
/// It does not expose the 101 response headers or negotiated extensions,
/// so callers can know that compression was offered, not prove that a
/// particular connection accepted it.
public static func make(
url: URL,
offersPerMessageDeflate: Bool = true
) -> URLRequest {
var request = URLRequest(url: url)
if offersPerMessageDeflate {
request.setValue(
perMessageDeflateOffer,
forHTTPHeaderField: "Sec-WebSocket-Extensions"
)
}
return request
}
}
public struct URLSessionWebSocketConnector: WebSocketConnecting {
private let session: URLSession
private let offersPerMessageDeflate: Bool
public init(session: URLSession = .shared) {
public init(
session: URLSession = .shared,
offersPerMessageDeflate: Bool = true
) {
self.session = session
self.offersPerMessageDeflate = offersPerMessageDeflate
}
public func connect(to url: URL) async throws -> any WebSocketConnection {
let connection = URLSessionWebSocketConnection(session: session, url: url)
let request = WebSocketHandshakeRequest.make(
url: url,
offersPerMessageDeflate: offersPerMessageDeflate
)
let connection = URLSessionWebSocketConnection(session: session, request: request)
await connection.open()
return connection
}
@@ -27,8 +58,8 @@ public struct URLSessionWebSocketConnector: WebSocketConnecting {
private actor URLSessionWebSocketConnection: WebSocketConnection {
private let task: URLSessionWebSocketTask
init(session: URLSession, url: URL) {
task = session.webSocketTask(with: url)
init(session: URLSession, request: URLRequest) {
task = session.webSocketTask(with: request)
}
func open() {
@@ -0,0 +1,250 @@
import XCTest
@testable import T3Code
@MainActor
final class NativeContractExpansionTests: XCTestCase {
func testAdministrativeClientSessionContractsAndRequests() async throws {
let environment = Environment(
id: "environment-1",
label: "Studio",
httpBaseURL: URL(string: "https://studio.example")!,
webSocketBaseURL: URL(string: "wss://studio.example")!
)
let credentials = InMemoryCredentialStore(credentials: [
environment.id: EnvironmentCredential(
accessToken: "bearer",
scopes: ["access:read", "access:write"]
),
])
let transport = AccessHTTPTransport()
let api = EnvironmentAPI(transport: transport, credentials: credentials)
let sessions = try await api.clientSessions(for: environment)
let revoked = try await api.revokeClientSession(
id: "session-2",
environment: environment
)
let others = try await api.revokeOtherClientSessions(for: environment)
XCTAssertEqual(sessions.first?.client.label, "Big O")
XCTAssertEqual(sessions.first?.client.deviceType, "mobile")
XCTAssertFalse(sessions.first?.current ?? true)
XCTAssertTrue(revoked.revoked)
XCTAssertEqual(others.revokedCount, 2)
let requests = await transport.requests
XCTAssertEqual(requests.map { $0.url?.path }, [
"/api/auth/clients",
"/api/auth/clients/revoke",
"/api/auth/clients/revoke-others",
])
XCTAssertTrue(requests.allSatisfy {
$0.value(forHTTPHeaderField: "Authorization") == "Bearer bearer"
})
XCTAssertTrue(requests.allSatisfy {
$0.value(forHTTPHeaderField: "Accept-Encoding") == "gzip"
})
let revokeBody = try JSONDecoder.t3.decode(
[String: String].self,
from: try XCTUnwrap(requests[1].httpBody)
)
XCTAssertEqual(revokeBody, ["sessionId": "session-2"])
}
func testImageAttachmentBuildsExactTurnUploadShape() throws {
let image = try UploadChatImageAttachment(
data: Data([0x89, 0x50, 0x4e, 0x47]),
name: "screenshot.png",
mimeType: "image/png"
)
let command = try OrchestrationCommands.sendTurn(
threadID: "thread-1",
text: "What is in this image?",
runtimeMode: .fullAccess,
model: ModelSelection(instanceId: "codex", model: "gpt-5.6-sol"),
attachments: [image],
commandID: "command-1",
messageID: "message-1",
createdAt: "2026-07-30T12:00:00.000Z"
)
guard case let .array(attachments)? = command["message"]?["attachments"] else {
return XCTFail("Expected an attachment array")
}
let attachment = try XCTUnwrap(attachments.first)
XCTAssertEqual(attachment["type"]?.stringValue, "image")
XCTAssertEqual(attachment["name"]?.stringValue, "screenshot.png")
XCTAssertEqual(attachment["mimeType"]?.stringValue, "image/png")
guard case let .number(sizeBytes)? = attachment["sizeBytes"] else {
return XCTFail("Expected numeric attachment size")
}
XCTAssertEqual(sizeBytes, 4)
XCTAssertEqual(
attachment["dataUrl"]?.stringValue,
"data:image/png;base64,iVBORw=="
)
XCTAssertEqual(command["modelSelection"]?["instanceId"]?.stringValue, "codex")
}
func testImageAttachmentRejectsOversizedInput() {
XCTAssertThrowsError(
try UploadChatImageAttachment(
data: Data(count: UploadChatImageAttachment.maximumBytes + 1),
name: "huge.png",
mimeType: "image/png"
)
) { error in
guard case ImageAttachmentError.tooLarge = error else {
return XCTFail("Expected size validation, got \(error)")
}
}
}
func testAssetContractUsesExactTagsAndResultFields() throws {
XCTAssertEqual(RPCMethod.assetsCreateURL.rawValue, "assets.createUrl")
XCTAssertEqual(
AssetResource.attachment(id: "attachment-1").jsonValue["_tag"]?.stringValue,
"attachment"
)
XCTAssertEqual(
AssetResource.workspaceFile(
threadID: "thread-1",
path: "screenshots/app.png"
).jsonValue["threadId"]?.stringValue,
"thread-1"
)
let result = try JSONDecoder.t3.decode(
AssetCreateURLResult.self,
from: Data(
"""
{
"relativeUrl": "/api/assets/signed/image.png",
"expiresAt": 1785466800000
}
""".utf8
)
)
XCTAssertEqual(result.relativeUrl, "/api/assets/signed/image.png")
XCTAssertEqual(result.expiresAt, 1_785_466_800_000)
}
func testServerConfigDecodesFullModelPickerCatalogue() throws {
let config = try JSONDecoder.t3.decode(
ServerConfigSnapshot.self,
from: Data(
"""
{
"providers": [{
"instanceId": "codex-work",
"driver": "codex",
"displayName": "Codex",
"accentColor": "#10a37f",
"badgeLabel": "OpenAI",
"showInteractionModeToggle": true,
"requiresNewThreadForModelChange": false,
"enabled": true,
"installed": true,
"version": "1.2.3",
"status": "ready",
"auth": {
"status": "authenticated",
"type": "chatgpt",
"label": "ChatGPT",
"email": "[email protected]"
},
"checkedAt": "2026-07-30T12:00:00.000Z",
"availability": "available",
"models": [{
"slug": "gpt-5.6-sol",
"name": "GPT-5.6 Sol",
"shortName": "Sol",
"isCustom": false,
"isDefault": true,
"capabilities": {
"optionDescriptors": [{
"id": "effort",
"type": "select",
"label": "Reasoning",
"description": "How hard the model thinks.",
"options": [{
"id": "high",
"label": "High",
"isDefault": true
}],
"currentValue": "high"
}, {
"id": "fastMode",
"type": "boolean",
"label": "Fast mode",
"currentValue": true
}]
}
}]
}]
}
""".utf8
)
)
let provider = try XCTUnwrap(config.providers.first)
XCTAssertEqual(provider.instanceId, "codex-work")
XCTAssertEqual(provider.auth.status, "authenticated")
let model = try XCTUnwrap(provider.models.first)
XCTAssertEqual(model.slug, "gpt-5.6-sol")
let descriptors = try XCTUnwrap(model.capabilities?.optionDescriptors)
guard case let .select(effort) = descriptors[0],
case let .boolean(fastMode) = descriptors[1]
else {
return XCTFail("Expected typed select and boolean descriptors")
}
XCTAssertEqual(effort.options.first?.label, "High")
XCTAssertEqual(effort.currentValue, "high")
XCTAssertEqual(fastMode.currentValue, true)
}
}
private actor AccessHTTPTransport: HTTPTransport {
private(set) var requests: [URLRequest] = []
func data(for request: URLRequest) -> (Data, HTTPURLResponse) {
requests.append(request)
let body: String
switch request.url?.path {
case "/api/auth/clients":
body = """
[{
"sessionId": "session-2",
"subject": "paired-client",
"scopes": ["orchestration:read"],
"method": "bearer-access-token",
"client": {
"label": "Big O",
"ipAddress": "192.168.1.10",
"deviceType": "mobile",
"os": "iOS"
},
"issuedAt": "2026-07-30T12:00:00.000Z",
"expiresAt": "2026-08-30T12:00:00.000Z",
"lastConnectedAt": "2026-07-30T12:05:00.000Z",
"connected": true,
"current": false
}]
"""
case "/api/auth/clients/revoke":
body = #"{"revoked":true}"#
case "/api/auth/clients/revoke-others":
body = #"{"revokedCount":2}"#
default:
body = "{}"
}
return (
Data(body.utf8),
HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: "HTTP/1.1",
headerFields: ["Content-Type": "application/json"]
)!
)
}
}
@@ -0,0 +1,193 @@
import XCTest
@testable import T3Code
@MainActor
final class TransportReliabilityTests: XCTestCase {
func testHTTPPolicyOffersGzipWithoutOverwritingCallerPreference() {
var request = URLRequest(url: URL(string: "https://studio.example/api")!)
let prepared = HTTPRequestPolicy.prepare(request)
XCTAssertEqual(prepared.value(forHTTPHeaderField: "Accept-Encoding"), "gzip")
XCTAssertEqual(prepared.value(forHTTPHeaderField: "Accept"), "application/json")
request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
XCTAssertEqual(
HTTPRequestPolicy.prepare(request).value(forHTTPHeaderField: "Accept-Encoding"),
"identity"
)
}
func testEnvironmentAPIDecodesURLSessionDecompressedGzipResponse() async throws {
let transport = RecordingHTTPTransport { request in
let body = """
{
"environmentId": "environment-1",
"label": "Studio",
"platform": {"os": "darwin", "arch": "arm64"},
"serverVersion": "1.0.0",
"capabilities": {"repositoryIdentity": true}
}
"""
return (
Data(body.utf8),
transportResponse(
request,
headers: [
"Content-Type": "application/json",
// URLSession retains this response header while
// returning the already decompressed body.
"Content-Encoding": "gzip",
]
)
)
}
let api = EnvironmentAPI(
transport: transport,
credentials: InMemoryCredentialStore()
)
let descriptor = try await api.descriptor(
at: URL(string: "https://studio.example")!
)
XCTAssertEqual(descriptor.environmentId, "environment-1")
let requests = await transport.requests
let request = try XCTUnwrap(requests.first)
XCTAssertEqual(request.value(forHTTPHeaderField: "Accept-Encoding"), "gzip")
}
func testWebSocketHandshakeOffersPerMessageDeflate() {
let url = URL(string: "wss://studio.example/ws?wsTicket=secret")!
let compressed = WebSocketHandshakeRequest.make(url: url)
XCTAssertEqual(
compressed.value(forHTTPHeaderField: "Sec-WebSocket-Extensions"),
"permessage-deflate; client_max_window_bits"
)
XCTAssertNil(
WebSocketHandshakeRequest.make(
url: url,
offersPerMessageDeflate: false
).value(forHTTPHeaderField: "Sec-WebSocket-Extensions")
)
}
/// Set `T3_SWIFT_WS_DEFLATE_ECHO_URL` to a WebSocket endpoint that rejects
/// non-deflate handshakes and echoes binary frames. This is intentionally
/// opt-in because XCTest does not own a Node process. A successful round
/// trip proves URLSession accepted the server's compressed frame.
func testLivePerMessageDeflateRoundTripWhenConfigured() async throws {
guard let value = ProcessInfo.processInfo.environment[
"T3_SWIFT_WS_DEFLATE_ECHO_URL"
], let url = URL(string: value) else {
throw XCTSkip("Set T3_SWIFT_WS_DEFLATE_ECHO_URL for live compression proof.")
}
let connection = try await URLSessionWebSocketConnector().connect(to: url)
defer { Task { await connection.close() } }
let payload = Data(repeating: 0x54, count: 64 * 1024)
try await connection.send(payload)
let echoed = try await connection.receive()
XCTAssertEqual(echoed, payload)
}
func testPairingInputParsesClipboardQRHostedAndLooseFormats() throws {
let direct = try PairingURL.parseFields(
" https://studio.example:3773/pair#token=N735%4BQXJ "
)
XCTAssertEqual(direct.host, "https://studio.example:3773")
XCTAssertEqual(direct.pairingCode, "N735KQXJ")
let hosted = try PairingURL.parseFields(
"https://app.t3.codes/pair?host=http%3A%2F%2F192.168.1.7%3A18773"
+ "&label=Big%20O#token=PAIRING"
)
XCTAssertEqual(hosted.host, "http://192.168.1.7:18773")
XCTAssertEqual(hosted.pairingCode, "PAIRING")
XCTAssertEqual(hosted.label, "Big O")
let loose = try PairingURL.parseFields("192.168.1.7:18773 N735KQXJ5SJW")
XCTAssertEqual(loose.host, "https://192.168.1.7:18773")
XCTAssertEqual(loose.pairingCode, "N735KQXJ5SJW")
let wrapped = try PairingURL.pairingURL(
fromQRCode: "t3code://pair?pairingUrl=https%3A%2F%2Fstudio.example"
+ "%2Fpair%23token%3DQR-CODE"
)
XCTAssertEqual(wrapped, "https://studio.example/pair#token=QR-CODE")
XCTAssertEqual(try PairingURL.parseFields(wrapped).pairingCode, "QR-CODE")
}
func testSplitPairingFieldsAcceptCompleteURLInHostField() throws {
let target = try PairingURL.resolve(
host: "http://192.168.1.7:18773/pair#token=FROM-URL",
pairingCode: ""
)
XCTAssertEqual(target.credential, "FROM-URL")
XCTAssertEqual(target.httpBaseURL.absoluteString, "http://192.168.1.7:18773/")
XCTAssertEqual(target.webSocketBaseURL.absoluteString, "ws://192.168.1.7:18773/")
}
func testLocalNetworkProbeClassificationDistinguishesFailureModes() {
XCTAssertTrue(LocalNetworkProbe.isLocalHost("192.168.20.4"))
XCTAssertTrue(LocalNetworkProbe.isLocalHost("studio.local"))
XCTAssertFalse(LocalNetworkProbe.isLocalHost("app.t3.codes"))
let denied = NSError(
domain: NSURLErrorDomain,
code: URLError.notConnectedToInternet.rawValue,
userInfo: [
NSUnderlyingErrorKey: NSError(
domain: NSPOSIXErrorDomain,
code: 13
),
]
)
XCTAssertEqual(
LocalNetworkProbe.classify(denied, host: "192.168.20.4", isLocal: true),
.likelyLocalNetworkDenied("192.168.20.4")
)
XCTAssertEqual(
LocalNetworkProbe.classify(
URLError(.timedOut),
host: "studio.local",
isLocal: true
),
.timeout("studio.local")
)
XCTAssertEqual(
LocalNetworkProbe.classify(
URLError(.cannotConnectToHost),
host: "studio.local",
isLocal: true
),
.unavailableHost("studio.local")
)
}
}
private func transportResponse(
_ request: URLRequest,
status: Int = 200,
headers: [String: String] = ["Content-Type": "application/json"]
) -> HTTPURLResponse {
HTTPURLResponse(
url: request.url!,
statusCode: status,
httpVersion: "HTTP/1.1",
headerFields: headers
)!
}
private actor RecordingHTTPTransport: HTTPTransport {
typealias Handler = @Sendable (URLRequest) throws -> (Data, HTTPURLResponse)
private(set) var requests: [URLRequest] = []
private let handler: Handler
init(handler: @escaping Handler) {
self.handler = handler
}
func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) {
requests.append(request)
return try handler(request)
}
}