From 1f0ec6184d15dfef29b772665a1ae1515f3d6b64 Mon Sep 17 00:00:00 2001 From: weishu Date: Mon, 17 Aug 2026 15:20:03 +0800 Subject: [PATCH] feat(ios): HapiClient API transport + auth (A-M1b) APIClient (final class, Sendable) with typed endpoints for the M2/M3 REST surface behind an HTTPPerforming seam; actor AuthManager with single-flight JWT refresh (POST /api/auth), proactive refresh 10 min before exp, terminal authFailed state, and 401 -> refresh -> retry-once wiring per docs/api/client-contract/auth.md; Keychain credential store (per-hub records under run.hapi.companion) with CredentialStoring seam + in-memory double; HubRegistry (ordered hubs + active hub in injectable UserDefaults, origin normalization); payload-only JWT decoding; APIError {status, code, body} parsing per errors.md; minimal multipart builder for M4c dictation; 256 MB URLCache session for generated images. Request/response wire models (SendMessageRequest, PermissionApproveRequest, SpawnRequest/SpawnResponse, MessagesQuery, envelopes, RPC-wrapped shapes) join HapiProtocol/Models mirroring shared/src/apiTypes.ts. swift-testing coverage: JWT decode (padding/garbage/hostile exp), auth single-flight (8 concurrent callers -> one exchange), 401 retry-once and terminal paths, APIError body parsing, endpoint request construction byte-checks (cursor queries, deliveryMode body, answers formats, explicit null model reset) via a recording performer, hub URL normalization, multipart bytes. --- .../Sources/HapiClient/APIClient.swift | 221 ++++++++++ .../Sources/HapiClient/Auth/AuthManager.swift | 234 ++++++++++ .../Sources/HapiClient/Auth/HubRegistry.swift | 129 ++++++ .../HapiKit/Sources/HapiClient/Auth/JWT.swift | 76 ++++ .../HapiClient/Auth/KeychainStore.swift | 137 ++++++ .../HapiClient/Endpoints/HubEndpoints.swift | 47 ++ .../Endpoints/MachineEndpoints.swift | 66 +++ .../HapiClient/Endpoints/MediaEndpoints.swift | 55 +++ .../Endpoints/MessageEndpoints.swift | 103 +++++ .../Endpoints/PermissionEndpoints.swift | 35 ++ .../Endpoints/SessionConfigEndpoints.swift | 150 +++++++ .../Endpoints/SessionEndpoints.swift | 146 ++++++ .../Sources/HapiClient/HTTPPerforming.swift | 68 +++ .../HapiClient/HapiClientVersion.swift | 8 +- .../Sources/HapiClient/MultipartEncoder.swift | 65 +++ .../Sources/HapiClient/RequestBuilding.swift | 52 +++ .../HapiProtocol/Models/ApiRequests.swift | 306 +++++++++++++ .../HapiProtocol/Models/ApiResponses.swift | 415 ++++++++++++++++++ .../HapiClientTests/APIClientTests.swift | 136 ++++++ .../HapiClientTests/AuthManagerTests.swift | 144 ++++++ .../CredentialStoreTests.swift | 63 +++ .../EndpointRequestTests.swift | 139 ++++++ .../HapiClientTests/HubRegistryTests.swift | 90 ++++ .../Tests/HapiClientTests/JWTTests.swift | 62 +++ .../MultipartEncoderTests.swift | 60 +++ .../Tests/HapiClientTests/TestSupport.swift | 127 ++++++ ios/README.md | 25 +- 27 files changed, 3153 insertions(+), 6 deletions(-) create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/APIClient.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Auth/AuthManager.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Auth/HubRegistry.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Auth/JWT.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Auth/KeychainStore.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Endpoints/HubEndpoints.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MediaEndpoints.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MessageEndpoints.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PermissionEndpoints.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionConfigEndpoints.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/HTTPPerforming.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/MultipartEncoder.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/RequestBuilding.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiRequests.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/APIClientTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/AuthManagerTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/CredentialStoreTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/HubRegistryTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/JWTTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/MultipartEncoderTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/TestSupport.swift diff --git a/ios/Packages/HapiKit/Sources/HapiClient/APIClient.swift b/ios/Packages/HapiKit/Sources/HapiClient/APIClient.swift new file mode 100644 index 00000000..55c789e8 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/APIClient.swift @@ -0,0 +1,221 @@ +import Foundation +import HapiProtocol + +/// HTTP method of a hub request. +public enum HTTPMethod: String, Sendable { + case get = "GET" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" +} + +/// A non-2xx hub response. +/// +/// Error bodies are JSON `{error, code?}` (`docs/api/client-contract/errors.md`). +/// `code` carries the stable machine discriminator when present; per the web +/// reference (`parseErrorCode`), a string `error` is used as a pseudo-code +/// fallback — acceptable for logging, not for logic. `body` keeps the raw +/// text for detail views. +public struct APIError: Error, Equatable, Sendable { + public let status: Int + public let code: String? + public let body: String? + + public init(status: Int, code: String? = nil, body: String? = nil) { + self.status = status + self.code = code + self.body = body + } + + /// Parses a `{error, code?}` body. Non-JSON bodies yield `code == nil`. + public init(status: Int, responseBody: Data) { + self.status = status + self.body = responseBody.isEmpty ? nil : String(data: responseBody, encoding: .utf8) + var parsedCode: String? + if let value = try? HapiJSON.decoder.decode(JSONValue.self, from: responseBody), + case .object(let object) = value { + if case .string(let code)? = object["code"] { + parsedCode = code + } else if case .string(let error)? = object["error"] { + parsedCode = error + } + } + self.code = parsedCode + } +} + +extension APIError: LocalizedError { + public var errorDescription: String? { + var description = "HTTP \(status)" + if let code { + description += " (\(code))" + } + return description + } +} + +/// Typed REST client for one hub. +/// +/// Stateless by design: the JWT lives in ``AuthManager`` (which single-flights +/// refreshes), so this class is a `Sendable` bundle of immutable wiring and +/// requests may run concurrently. Endpoint methods live in extensions under +/// `Endpoints/`; feature packages (git/files, scratchlist, voice, usage) +/// add theirs the same way. +/// +/// Every authenticated request sends `Authorization: Bearer `; on a 401 +/// it asks the auth manager for a refreshed token and retries exactly once — +/// a second 401 marks authentication failed (re-pair needed) and surfaces an +/// ``APIError``. +public final class APIClient: Sendable { + /// Origin of the active hub (from ``HubRegistry``). + public let baseURL: URL + public let authManager: AuthManager + private let performer: any HTTPPerforming + + public init( + baseURL: URL, + authManager: AuthManager, + performer: any HTTPPerforming = URLSessionHTTPPerformer.shared + ) { + self.baseURL = baseURL + self.authManager = authManager + self.performer = performer + } + + // MARK: - Typed request surface + + /// GET-style JSON request without a body. + public func request( + _ method: HTTPMethod, + _ path: String, + query: [URLQueryItem] = [], + authenticated: Bool = true + ) async throws -> T { + let (data, _) = try await send(method, path: path, query: query, authenticated: authenticated) + return try HapiJSON.decoder.decode(T.self, from: data) + } + + /// JSON request with a JSON body. + public func request( + _ method: HTTPMethod, + _ path: String, + query: [URLQueryItem] = [], + body: Body, + authenticated: Bool = true + ) async throws -> T { + let bodyData = try HapiJSON.encoder.encode(body) + let (data, _) = try await send( + method, + path: path, + query: query, + bodyData: bodyData, + authenticated: authenticated + ) + return try HapiJSON.decoder.decode(T.self, from: data) + } + + /// JSON request with a pre-encoded body (multipart, etc.). + public func request( + _ method: HTTPMethod, + _ path: String, + query: [URLQueryItem] = [], + rawBody: Data, + contentType: String + ) async throws -> T { + let (data, _) = try await send( + method, + path: path, + query: query, + bodyData: rawBody, + contentType: contentType + ) + return try HapiJSON.decoder.decode(T.self, from: data) + } + + /// Request whose response body is ignored (`{ok: true}` endpoints). + public func requestVoid( + _ method: HTTPMethod, + _ path: String, + query: [URLQueryItem] = [] + ) async throws { + _ = try await send(method, path: path, query: query) + } + + /// Body-carrying request whose response body is ignored. + public func requestVoid( + _ method: HTTPMethod, + _ path: String, + query: [URLQueryItem] = [], + body: Body + ) async throws { + let bodyData = try HapiJSON.encoder.encode(body) + _ = try await send(method, path: path, query: query, bodyData: bodyData) + } + + /// Raw-bytes GET (generated images, scratchlist attachments). Responses + /// flow through the session's `URLCache`, so the hub's + /// `ETag`/`immutable` headers make repeats free. + public func requestBytes( + _ path: String, + query: [URLQueryItem] = [] + ) async throws -> (data: Data, response: HTTPURLResponse) { + try await send(.get, path: path, query: query) + } + + // MARK: - Core + + /// One authenticated exchange with the 401 → refresh → retry-once rule + /// (`docs/api/client-contract/auth.md`). Throws ``APIError`` for non-2xx + /// statuses and propagates ``AuthError`` when re-auth is impossible. + func send( + _ method: HTTPMethod, + path: String, + query: [URLQueryItem] = [], + bodyData: Data? = nil, + contentType: String? = "application/json", + authenticated: Bool = true + ) async throws -> (Data, HTTPURLResponse) { + let url = try HubRequestURL.make(baseURL: baseURL, path: path, query: query) + var request = URLRequest(url: url) + request.httpMethod = method.rawValue + if let bodyData { + request.httpBody = bodyData + if let contentType { + request.setValue(contentType, forHTTPHeaderField: "Content-Type") + } + } + + guard authenticated else { + let (data, response) = try await performer.perform(request) + try Self.validate(status: response.statusCode, data: data) + return (data, response) + } + + let token = try await authManager.validToken() + request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + var (data, response) = try await performer.perform(request) + + if response.statusCode == 401 { + // Routine JWT expiry: silently re-exchange the stored access + // token and retry exactly once. + let refreshed = try await authManager.refreshAfterUnauthorized(failedToken: token) + request.setValue("Bearer \(refreshed)", forHTTPHeaderField: "Authorization") + (data, response) = try await performer.perform(request) + if response.statusCode == 401 { + // A fresh JWT was refused — the credentials are dead. + await authManager.markAuthenticationFailed() + throw APIError(status: 401, responseBody: data) + } + } + + try Self.validate(status: response.statusCode, data: data) + return (data, response) + } + + private static func validate(status: Int, data: Data) throws { + guard (200..<300).contains(status) else { + throw APIError(status: status, responseBody: data) + } + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/AuthManager.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/AuthManager.swift new file mode 100644 index 00000000..109414da --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/AuthManager.swift @@ -0,0 +1,234 @@ +import Foundation +import HapiProtocol + +/// Authentication failures surfaced by ``AuthManager``. +public enum AuthError: Error, Equatable, Sendable { + /// No stored credentials for this hub — never paired, or unpaired. + case notPaired + /// Terminal: the hub rejected the stored access token (`POST /api/auth` + /// answered 401) or refused a freshly issued JWT. Only re-pairing + /// recovers from this state. + case reauthenticationRequired + /// `POST /api/auth` answered an unexpected status. Recoverable — the + /// next call retries (throttled). + case refreshFailed(status: Int) +} + +/// Owns the JWT for one hub and keeps it valid. +/// +/// Contract (`docs/api/client-contract/auth.md`): +/// - JWTs expire after 4 h, so 401s are routine: re-exchange the stored +/// access token via `POST /api/auth {accessToken}` and let the caller +/// retry exactly once. +/// - Refreshes are **single-flight**: concurrent callers share one in-flight +/// exchange instead of racing N of them. +/// - Refresh is proactive when `exp` is within ``proactiveRefreshWindow``, +/// so long-lived work (SSE reconnects) rarely sees a stale token. +/// - A 401 from `/api/auth` itself is terminal (`authFailed`): the access +/// token was rotated or revoked, and the UI must offer re-pairing. +/// +/// The HTTP performer and clock are injectable for tests. +public actor AuthManager { + /// Refresh proactively when the token expires within 10 minutes. + public static let proactiveRefreshWindow: TimeInterval = 10 * 60 + /// Minimum spacing between *failed* proactive attempts, so a dead hub + /// does not cause a refresh storm while the current token still works. + public static let failedRefreshThrottle: TimeInterval = 15 + + /// Origin of the hub this manager authenticates against. + public let baseURL: URL + /// Normalized origin used as the ``CredentialStoring`` key. + public let storageKey: String + + private let credentialStore: any CredentialStoring + private let performer: any HTTPPerforming + private let now: @Sendable () -> Date + + private var jwt: String? + private var claims: JWTClaims? + private var didLoadPersistedJWT = false + private var refreshTask: Task? + private var authFailed = false + private var lastFailedRefreshAt: Date? + + public init( + baseURL: URL, + credentialStore: any CredentialStoring, + performer: any HTTPPerforming = URLSessionHTTPPerformer.shared, + now: @escaping @Sendable () -> Date = { Date() } + ) { + self.baseURL = baseURL + self.storageKey = HubURLNormalization.normalize(baseURL.absoluteString) ?? baseURL.absoluteString + self.credentialStore = credentialStore + self.performer = performer + self.now = now + } + + /// `true` once the hub has terminally rejected the credentials + /// ("re-pair needed"). Cleared by ``reset()``. + public var isAuthenticationFailed: Bool { + authFailed + } + + /// Claims of the current JWT (drives `ns == "default"` owner gating). + public var currentClaims: JWTClaims? { + claims + } + + /// Returns a JWT expected to be accepted by the hub: the cached one when + /// it is comfortably fresh, otherwise the result of a (single-flight) + /// refresh. A failed *proactive* refresh falls back to the cached token, + /// which is still temporally valid. + public func validToken() async throws -> String { + if authFailed { + throw AuthError.reauthenticationRequired + } + loadPersistedJWTIfNeeded() + guard let current = jwt else { + return try await singleFlightRefresh() + } + let reference = now() + if isExpired(at: reference) { + return try await singleFlightRefresh() + } + guard needsProactiveRefresh(at: reference) else { + return current + } + if let lastFailed = lastFailedRefreshAt, + reference.timeIntervalSince(lastFailed) < Self.failedRefreshThrottle { + return current + } + do { + return try await singleFlightRefresh() + } catch AuthError.reauthenticationRequired { + throw AuthError.reauthenticationRequired + } catch { + // Best effort: the current token has not expired yet. + return current + } + } + + /// Called by ``APIClient`` after a request 401'd with `failedToken`. + /// If another flight already rotated the JWT, returns it without a new + /// exchange; otherwise refreshes (single-flight). + public func refreshAfterUnauthorized(failedToken: String?) async throws -> String { + if authFailed { + throw AuthError.reauthenticationRequired + } + loadPersistedJWTIfNeeded() + if let current = jwt, current != failedToken { + return current + } + return try await singleFlightRefresh() + } + + /// Enters the terminal failed state. ``APIClient`` calls this when a + /// request still 401s right after a successful refresh. + public func markAuthenticationFailed() { + authFailed = true + } + + /// Clears all cached state (including the terminal flag). Call after the + /// pairing flow stored new credentials for this hub. + public func reset() { + authFailed = false + jwt = nil + claims = nil + didLoadPersistedJWT = false + refreshTask = nil + lastFailedRefreshAt = nil + } + + // MARK: - Internals + + private func loadPersistedJWTIfNeeded() { + guard !didLoadPersistedJWT else { return } + didLoadPersistedJWT = true + guard jwt == nil, + let stored = try? credentialStore.credentials(forHub: storageKey), + let persisted = stored.jwt, + !persisted.isEmpty else { return } + jwt = persisted + claims = JWT.claims(from: persisted) + } + + private func isExpired(at reference: Date) -> Bool { + guard let expiresAt = claims?.expiresAt else { return false } + return expiresAt <= reference + } + + private func needsProactiveRefresh(at reference: Date) -> Bool { + guard let expiresAt = claims?.expiresAt else { return false } + return expiresAt.timeIntervalSince(reference) < Self.proactiveRefreshWindow + } + + /// Shares one in-flight exchange among concurrent callers. + private func singleFlightRefresh() async throws -> String { + if let inFlight = refreshTask { + return try await inFlight.value + } + let task = Task { + try await self.performRefresh() + } + refreshTask = task + defer { + // Only the creator clears the slot, and only if it still holds + // this flight (a later flight must not be discarded). + if refreshTask == task { + refreshTask = nil + } + } + return try await task.value + } + + private func performRefresh() async throws -> String { + let stored = try? credentialStore.credentials(forHub: storageKey) + guard let credentials = stored, !credentials.accessToken.isEmpty else { + throw AuthError.notPaired + } + do { + let request = try makeAuthRequest(accessToken: credentials.accessToken) + let (data, response) = try await performer.perform(request) + switch response.statusCode { + case 200: + let auth = try HapiJSON.decoder.decode(AuthResponse.self, from: data) + adopt(token: auth.token, credentials: credentials) + return auth.token + case 401: + // "Invalid access token" — rotated or revoked. Terminal. + authFailed = true + throw AuthError.reauthenticationRequired + default: + throw AuthError.refreshFailed(status: response.statusCode) + } + } catch { + if !authFailed { + lastFailedRefreshAt = now() + } + throw error + } + } + + private func makeAuthRequest(accessToken: String) throws -> URLRequest { + struct AuthRequestBody: Encodable { + let accessToken: String + } + let url = try HubRequestURL.make(baseURL: baseURL, path: "/api/auth", query: []) + var request = URLRequest(url: url) + request.httpMethod = HTTPMethod.post.rawValue + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try HapiJSON.encoder.encode(AuthRequestBody(accessToken: accessToken)) + return request + } + + private func adopt(token: String, credentials: HubCredentials) { + jwt = token + claims = JWT.claims(from: token) + var updated = credentials + updated.jwt = token + updated.jwtObtainedAt = Int(now().timeIntervalSince1970 * 1000) + // Persisting the JWT is an optimization; failure to write it must + // not fail the refresh. + try? credentialStore.store(updated) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubRegistry.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubRegistry.swift new file mode 100644 index 00000000..c77a2542 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubRegistry.swift @@ -0,0 +1,129 @@ +import Foundation + +/// Canonical form of a hub URL: the lowercased origin, nothing else. +/// +/// Everything credential- or connection-shaped is keyed by this string +/// (Keychain accounts, registry entries, `AuthManager` storage keys), so the +/// same hub typed as `https://Hub.example.com/` and scanned as +/// `https://hub.example.com` collapses to one identity. +public enum HubURLNormalization { + /// `raw` → `scheme://host[:port]`, or `nil` when it is not an absolute + /// http(s) URL. Trims whitespace, lowercases scheme/host, drops any + /// path/query/fragment (including the trailing slash) and default ports. + public static func normalize(_ raw: String) -> String? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, + let components = URLComponents(string: trimmed), + let scheme = components.scheme?.lowercased(), + scheme == "http" || scheme == "https", + var host = components.host?.lowercased(), + !host.isEmpty else { + return nil + } + // URLComponents strips the brackets from IPv6 literals; restore them + // (defensively: only when not already bracketed). + if host.contains(":") && !host.hasPrefix("[") { + host = "[\(host)]" + } + var origin = "\(scheme)://\(host)" + if let port = components.port { + let isDefault = (scheme == "https" && port == 443) || (scheme == "http" && port == 80) + if !isDefault { + origin += ":\(port)" + } + } + return origin + } +} + +/// Ordered set of paired hubs plus the active selection, persisted in +/// `UserDefaults` (URLs only — secrets live in the ``CredentialStoring`` +/// Keychain store). +/// +/// `UserDefaults` is injectable for tests; all URLs are normalized on the way +/// in, so lookups never miss on formatting differences. +public final class HubRegistry: @unchecked Sendable { + public static let hubsDefaultsKey = "run.hapi.hubs" + public static let activeHubDefaultsKey = "run.hapi.activeHub" + + private let defaults: UserDefaults + /// Serializes read-modify-write cycles on the stored array. + private let lock = NSLock() + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + /// Paired hub origins, in pairing order. + public var hubs: [String] { + lock.lock() + defer { lock.unlock() } + return storedHubs() + } + + /// The active hub origin. Falls back to the first paired hub when the + /// stored selection is missing or no longer registered. + public var activeHub: String? { + lock.lock() + defer { lock.unlock() } + let hubs = storedHubs() + if let active = defaults.string(forKey: Self.activeHubDefaultsKey), hubs.contains(active) { + return active + } + return hubs.first + } + + /// Normalizes and registers a hub. Returns the normalized origin, or + /// `nil` when `raw` is not a valid hub URL. The first registered hub + /// becomes active automatically; re-registering is a no-op. + @discardableResult + public func register(_ raw: String) -> String? { + guard let normalized = HubURLNormalization.normalize(raw) else { return nil } + lock.lock() + defer { lock.unlock() } + var hubs = storedHubs() + if !hubs.contains(normalized) { + hubs.append(normalized) + defaults.set(hubs, forKey: Self.hubsDefaultsKey) + } + if defaults.string(forKey: Self.activeHubDefaultsKey) == nil { + defaults.set(normalized, forKey: Self.activeHubDefaultsKey) + } + return normalized + } + + /// Selects the active hub. Returns `false` when the URL is invalid or + /// not registered. + @discardableResult + public func setActiveHub(_ raw: String) -> Bool { + guard let normalized = HubURLNormalization.normalize(raw) else { return false } + lock.lock() + defer { lock.unlock() } + guard storedHubs().contains(normalized) else { return false } + defaults.set(normalized, forKey: Self.activeHubDefaultsKey) + return true + } + + /// Unregisters a hub. When it was active, the first remaining hub (if + /// any) becomes active. Credential cleanup is the caller's job. + public func remove(_ raw: String) { + guard let normalized = HubURLNormalization.normalize(raw) else { return } + lock.lock() + defer { lock.unlock() } + var hubs = storedHubs() + guard let index = hubs.firstIndex(of: normalized) else { return } + hubs.remove(at: index) + defaults.set(hubs, forKey: Self.hubsDefaultsKey) + if defaults.string(forKey: Self.activeHubDefaultsKey) == normalized { + if let next = hubs.first { + defaults.set(next, forKey: Self.activeHubDefaultsKey) + } else { + defaults.removeObject(forKey: Self.activeHubDefaultsKey) + } + } + } + + private func storedHubs() -> [String] { + defaults.stringArray(forKey: Self.hubsDefaultsKey) ?? [] + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/JWT.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/JWT.swift new file mode 100644 index 00000000..5b7592b7 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/JWT.swift @@ -0,0 +1,76 @@ +import Foundation + +/// Decoded payload of a hub JWT. +/// +/// The hub signs `{uid, ns}` plus standard `iat`/`exp` (HS256, 4 h expiry — +/// `docs/api/client-contract/auth.md`). Clients treat the token as opaque for +/// auth purposes but may read the payload for proactive refresh scheduling +/// and namespace gating (`ns == "default"` is the hub owner). +public struct JWTClaims: Equatable, Sendable { + public let uid: Int + /// Namespace the token operates in (`"default"` = hub owner). + public let ns: String + /// Expiry, seconds since the Unix epoch; `nil` when the payload has none. + public let exp: Int? + + public init(uid: Int, ns: String, exp: Int? = nil) { + self.uid = uid + self.ns = ns + self.exp = exp + } + + public var expiresAt: Date? { + exp.map { Date(timeIntervalSince1970: TimeInterval($0)) } + } +} + +/// Payload-only JWT reader. No signature verification — only the hub can +/// verify HS256 tokens, and the client merely schedules around `exp`. +public enum JWT { + /// Decodes the base64url middle segment of `token` into ``JWTClaims``. + /// Returns `nil` for anything that is not a well-formed hub JWT payload + /// (wrong segment count, invalid base64url, non-JSON, missing `uid`/`ns`). + public static func claims(from token: String) -> JWTClaims? { + // `components(separatedBy:)` keeps empty segments, so "a..b" cannot + // shift the payload position the way `split` would. + let segments = token.components(separatedBy: ".") + guard segments.count >= 2 else { return nil } + guard let payload = decodeBase64URLSegment(segments[1]) else { return nil } + + struct RawClaims: Decodable { + let uid: Int + let ns: String + let exp: Double? + } + guard let raw = try? JSONDecoder().decode(RawClaims.self, from: payload) else { return nil } + return JWTClaims(uid: raw.uid, ns: raw.ns, exp: raw.exp.flatMap(safeInt)) + } + + /// base64url → `Data`: translate the URL-safe alphabet and restore the + /// stripped `=` padding. A length of 1 (mod 4) is not valid base64. + static func decodeBase64URLSegment(_ segment: String) -> Data? { + var base64 = segment + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + switch base64.count % 4 { + case 0: + break + case 2: + base64 += "==" + case 3: + base64 += "=" + default: + return nil + } + return Data(base64Encoded: base64) + } + + /// `Int(_:)` traps on out-of-range doubles; a hostile token must not + /// crash the app. + private static func safeInt(_ value: Double) -> Int? { + guard value.isFinite, + value >= -9_000_000_000_000_000_000, + value <= 9_000_000_000_000_000_000 else { return nil } + return Int(value) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/KeychainStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/KeychainStore.swift new file mode 100644 index 00000000..2b2e4cfc --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/KeychainStore.swift @@ -0,0 +1,137 @@ +import Foundation +import Security + +/// The per-hub credential record (`docs/api/client-contract/auth.md`). +/// +/// The access token is the durable secret; the JWT is a 4-hour cache +/// persisted only to save one `/api/auth` round-trip at cold start. +public struct HubCredentials: Codable, Equatable, Sendable { + /// Normalized hub origin (see ``HubURLNormalization``); also the storage key. + public var hubUrl: String + /// Long-lived pairing secret, passed verbatim to `POST /api/auth`. + public var accessToken: String + /// Last issued JWT, if any. + public var jwt: String? + /// When `jwt` was obtained, epoch ms. + public var jwtObtainedAt: Int? + + public init(hubUrl: String, accessToken: String, jwt: String? = nil, jwtObtainedAt: Int? = nil) { + self.hubUrl = hubUrl + self.accessToken = accessToken + self.jwt = jwt + self.jwtObtainedAt = jwtObtainedAt + } +} + +/// Storage seam so `AuthManager` and the pairing flow are testable without +/// touching the real Keychain. +public protocol CredentialStoring: Sendable { + /// Returns the record for a normalized hub origin, or `nil` when unpaired. + func credentials(forHub hubUrl: String) throws -> HubCredentials? + /// Inserts or replaces the record keyed by `credentials.hubUrl`. + func store(_ credentials: HubCredentials) throws + /// Removes the record; deleting a non-existent record is not an error. + func deleteCredentials(forHub hubUrl: String) throws +} + +/// A Keychain operation failed with the given `SecItem` status. +public struct KeychainError: Error, Equatable, Sendable { + public let status: OSStatus + + public init(status: OSStatus) { + self.status = status + } +} + +/// Keychain-backed credential store: one generic-password item per hub under +/// service `run.hapi.companion`, account = normalized hub origin, value = +/// JSON-encoded ``HubCredentials``. +/// +/// Items use `kSecAttrAccessibleAfterFirstUnlock` so a background refresh +/// after reboot (pre-unlock) fails gracefully instead of silently losing +/// credentials, and the data-protection keychain so behavior matches across +/// iOS and macOS (CI). +public struct KeychainCredentialStore: CredentialStoring { + public static let service = "run.hapi.companion" + + public init() {} + + public func credentials(forHub hubUrl: String) throws -> HubCredentials? { + var query = Self.baseQuery(account: hubUrl) + query[kSecReturnData as String] = true + query[kSecMatchLimit as String] = kSecMatchLimitOne + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + switch status { + case errSecSuccess: + guard let data = item as? Data else { + throw KeychainError(status: errSecInternalError) + } + return try JSONDecoder().decode(HubCredentials.self, from: data) + case errSecItemNotFound: + return nil + default: + throw KeychainError(status: status) + } + } + + public func store(_ credentials: HubCredentials) throws { + let data = try JSONEncoder().encode(credentials) + let query = Self.baseQuery(account: credentials.hubUrl) + let update: [String: Any] = [kSecValueData as String: data] + let updateStatus = SecItemUpdate(query as CFDictionary, update as CFDictionary) + if updateStatus == errSecSuccess { return } + guard updateStatus == errSecItemNotFound else { + throw KeychainError(status: updateStatus) + } + var add = query + add[kSecValueData as String] = data + add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock + let addStatus = SecItemAdd(add as CFDictionary, nil) + guard addStatus == errSecSuccess else { + throw KeychainError(status: addStatus) + } + } + + public func deleteCredentials(forHub hubUrl: String) throws { + let status = SecItemDelete(Self.baseQuery(account: hubUrl) as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { + throw KeychainError(status: status) + } + } + + private static func baseQuery(account: String) -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecUseDataProtectionKeychain as String: true, + ] + } +} + +/// Dictionary-backed test double (also handy for previews). +public final class InMemoryCredentialStore: CredentialStoring, @unchecked Sendable { + private let lock = NSLock() + private var records: [String: HubCredentials] = [:] + + public init() {} + + public func credentials(forHub hubUrl: String) throws -> HubCredentials? { + lock.lock() + defer { lock.unlock() } + return records[hubUrl] + } + + public func store(_ credentials: HubCredentials) throws { + lock.lock() + defer { lock.unlock() } + records[credentials.hubUrl] = credentials + } + + public func deleteCredentials(forHub hubUrl: String) throws { + lock.lock() + defer { lock.unlock() } + records[hubUrl] = nil + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/HubEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/HubEndpoints.swift new file mode 100644 index 00000000..bec88c77 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/HubEndpoints.swift @@ -0,0 +1,47 @@ +import Foundation +import HapiProtocol + +/// Hub-level endpoints: health, auth exchange, visibility. +/// +/// Pattern for feature packages adding endpoints later (git/files, +/// scratchlist, voice, usage): one `extension APIClient` per feature, +/// paths composed with `encodePathComponent`, bodies as HapiProtocol +/// request models (or private single-field structs), calls through +/// `request`/`requestVoid`/`requestBytes`. +extension APIClient { + /// `GET /health` (unauthenticated). Capability flags are additive. + public func health() async throws -> HubHealthResponse { + try await request(.get, "/health", authenticated: false) + } + + /// `POST /api/auth` (unauthenticated) — exchanges a pairing access token + /// for a JWT. The pairing flow persists the credentials afterwards; + /// routine refreshes go through ``AuthManager`` instead. + public func authenticate(accessToken: String) async throws -> AuthResponse { + struct AuthRequestBody: Encodable { + let accessToken: String + } + return try await request( + .post, + "/api/auth", + body: AuthRequestBody(accessToken: accessToken), + authenticated: false + ) + } + + /// `POST /api/visibility` — reports foreground/background transitions so + /// the hub can suppress redundant pushes while the app is visible. + /// `subscriptionId` comes from the SSE `connection-changed` handshake; + /// a stale one answers 404. + public func setVisibility(subscriptionId: String, visibility: VisibilityState) async throws { + try await requestVoid( + .post, + "/api/visibility", + body: VisibilityRequest(subscriptionId: subscriptionId, visibility: visibility) + ) + } +} + +/// Empty JSON object body (`{}`) for endpoints whose contract expects one. +struct EmptyRequestBody: Encodable { +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift new file mode 100644 index 00000000..47790ec2 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift @@ -0,0 +1,66 @@ +import Foundation +import HapiProtocol + +/// Machines and spawning (`docs/api/client-contract/rest.md`). +extension APIClient { + /// `GET /api/machines` — online machines in the caller's namespace. + public func listMachines() async throws -> [Machine] { + let response: MachinesResponse = try await request(.get, "/api/machines") + return response.machines + } + + /// `PATCH /api/machines/:id` — rename (≤ 64 chars; empty string clears + /// the custom name back to the hostname). + public func renameMachine(id: String, displayName: String) async throws { + struct RenameMachineRequest: Encodable { + let displayName: String + } + try await requestVoid( + .patch, + "/api/machines/\(encodePathComponent(id))", + body: RenameMachineRequest(displayName: displayName) + ) + } + + /// `POST /api/machines/:id/spawn`. The response is discriminated on + /// `type`, not HTTP status — a failed spawn is still HTTP 200 with + /// `.error`. + public func spawnSession(machineId: String, _ spawn: SpawnRequest) async throws -> SpawnResponse { + try await request( + .post, + "/api/machines/\(encodePathComponent(machineId))/spawn", + body: spawn + ) + } + + /// `POST /api/machines/:id/list-directory` (RPC envelope — check + /// `success`). + public func listMachineDirectory( + machineId: String, + path: String, + includeHidden: Bool = false + ) async throws -> MachineListDirectoryResponse { + struct ListDirectoryRequest: Encodable { + let path: String + let includeHidden: Bool + } + return try await request( + .post, + "/api/machines/\(encodePathComponent(machineId))/list-directory", + body: ListDirectoryRequest(path: path, includeHidden: includeHidden) + ) + } + + /// `POST /api/machines/:id/paths/exists` (≤ 1000 paths). + public func machinePathsExist(machineId: String, paths: [String]) async throws -> [String: Bool] { + struct PathsExistsRequest: Encodable { + let paths: [String] + } + let response: MachinePathsExistsResponse = try await request( + .post, + "/api/machines/\(encodePathComponent(machineId))/paths/exists", + body: PathsExistsRequest(paths: paths) + ) + return response.exists + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MediaEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MediaEndpoints.swift new file mode 100644 index 00000000..b3713750 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MediaEndpoints.swift @@ -0,0 +1,55 @@ +import Foundation +import HapiProtocol + +/// Generated images and message-attachment uploads +/// (`docs/api/client-contract/rest.md`). +extension APIClient { + /// `GET /api/sessions/:id/generated-images/:imageId` — raw bytes. + /// + /// The image id is a content fingerprint doubling as the `ETag`, and the + /// hub sends `Cache-Control: private, max-age=31536000, immutable`, so + /// the configured `URLCache` (see ``URLSessionHTTPPerformer``) serves + /// repeats locally and revalidates with `If-None-Match` transparently. + public func generatedImage( + sessionId: String, + imageId: String + ) async throws -> (data: Data, mimeType: String?) { + let (data, response) = try await requestBytes( + "/api/sessions/\(encodePathComponent(sessionId))/generated-images/\(encodePathComponent(imageId))" + ) + return (data, response.value(forHTTPHeaderField: "Content-Type")) + } + + /// `POST /api/sessions/:id/upload` — JSON + base64, **not** multipart. + /// Decoded size limit 50 MB (413 above). Requires an active session. + /// Pass the returned `path` in the `attachments` metadata of a + /// subsequent send-message. + public func uploadFile( + sessionId: String, + filename: String, + data: Data, + mimeType: String + ) async throws -> UploadFileResponse { + try await request( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/upload", + body: UploadFileRequest( + filename: filename, + content: data.base64EncodedString(), + mimeType: mimeType + ) + ) + } + + /// `POST /api/sessions/:id/upload/delete` — removes a pending upload. + public func deleteUpload(sessionId: String, path: String) async throws -> DeleteUploadResponse { + struct DeleteUploadRequest: Encodable { + let path: String + } + return try await request( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/upload/delete", + body: DeleteUploadRequest(path: path) + ) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MessageEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MessageEndpoints.swift new file mode 100644 index 00000000..4d2f325c --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MessageEndpoints.swift @@ -0,0 +1,103 @@ +import Foundation +import HapiProtocol + +extension MessagesQuery { + /// Query items in the reference client's insertion order + /// (`web/src/api/client.ts` `getMessages`), so request URLs are + /// byte-comparable across clients. + var queryItems: [URLQueryItem] { + var items: [URLQueryItem] = [] + func append(_ name: String, _ value: Int?) { + if let value { + items.append(URLQueryItem(name: name, value: String(value))) + } + } + append("beforeAt", beforeAt) + append("beforeSeq", beforeSeq) + append("afterAt", afterAt) + append("afterSeq", afterSeq) + append("untilAt", untilAt) + append("untilSeq", untilSeq) + append("epoch", epoch) + append("limit", limit) + return items + } +} + +/// Message paging, sending, and queue operations +/// (`docs/api/client-contract/rest.md`, `pagination.md`). +extension APIClient { + /// `GET /api/sessions/:id/messages` with a compound cursor. When the + /// page comes back with `reset: true`, discard the local window — the + /// requested epoch no longer exists. + public func messages(sessionId: String, query: MessagesQuery = .latest()) async throws -> MessagesResponse { + try await request( + .get, + "/api/sessions/\(encodePathComponent(sessionId))/messages", + query: query.queryItems + ) + } + + /// `POST /api/sessions/:id/messages`. Answers `{ok: true}` only — the + /// stored message arrives via SSE (`message-received`), reconciled with + /// the optimistic row through `localId`. + public func sendMessage(sessionId: String, _ message: SendMessageRequest) async throws { + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/messages", + body: message + ) + } + + /// Convenience overload of ``sendMessage(sessionId:_:)``. + public func sendMessage( + sessionId: String, + text: String, + localId: String? = nil, + attachments: [AttachmentMetadata]? = nil, + scheduledAt: Int? = nil, + deliveryMode: MessageDeliveryMode? = nil + ) async throws { + try await sendMessage( + sessionId: sessionId, + SendMessageRequest( + text: text, + localId: localId, + attachments: attachments, + scheduledAt: scheduledAt, + deliveryMode: deliveryMode + ) + ) + } + + /// `DELETE /api/sessions/:id/messages/:messageId` — cancel a queued + /// message. `.invoked` means the cancel came too late. + public func cancelMessage(sessionId: String, messageId: String) async throws -> CancelMessageResponse { + try await request( + .delete, + "/api/sessions/\(encodePathComponent(sessionId))/messages/\(encodePathComponent(messageId))" + ) + } + + /// `POST /api/sessions/:id/messages/:messageId/steer` — promote a queued + /// message to steer delivery. + public func steerMessage(sessionId: String, messageId: String) async throws -> SteerQueuedMessageResponse { + try await request( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/messages/\(encodePathComponent(messageId))/steer" + ) + } + + /// `POST /api/sessions/:id/messages/queued-state` — resync optimistic + /// sends after a reconnect (≤ 1000 localIds). + public func queuedState(sessionId: String, localIds: [String]) async throws -> QueuedStateResponse { + struct QueuedStateRequest: Encodable { + let localIds: [String] + } + return try await request( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/messages/queued-state", + body: QueuedStateRequest(localIds: localIds) + ) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PermissionEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PermissionEndpoints.swift new file mode 100644 index 00000000..7cf86a2f --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PermissionEndpoints.swift @@ -0,0 +1,35 @@ +import Foundation +import HapiProtocol + +/// Permission resolution (`docs/api/client-contract/rest.md`). Pending +/// requests are **not messages** — they live in `session.agentState.requests` +/// and move to `completedRequests` once decided. Both endpoints 404 when the +/// request id is no longer pending and 409 `session_inactive` when the +/// session is inactive. +extension APIClient { + /// `POST /api/sessions/:id/permissions/:requestId/approve`. + public func approvePermission( + sessionId: String, + requestId: String, + _ body: PermissionApproveRequest = PermissionApproveRequest() + ) async throws { + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/permissions/\(encodePathComponent(requestId))/approve", + body: body + ) + } + + /// `POST /api/sessions/:id/permissions/:requestId/deny`. + public func denyPermission( + sessionId: String, + requestId: String, + decision: PermissionDecision? = nil + ) async throws { + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/permissions/\(encodePathComponent(requestId))/deny", + body: PermissionDenyRequest(decision: decision) + ) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionConfigEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionConfigEndpoints.swift new file mode 100644 index 00000000..284147f0 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionConfigEndpoints.swift @@ -0,0 +1,150 @@ +import Foundation +import HapiProtocol + +/// Per-flavor session configuration (`docs/api/client-contract/rest.md`). +/// Wrong-flavor calls answer 400 (hide the control); remote-only controls +/// answer 409 while the session is terminal-controlled. All respond +/// `{ok: true}`. +/// +/// The nullable bodies (`model`, `effort`, `modelReasoningEffort`, +/// `serviceTier`) encode an **explicit JSON null** when the value is absent — +/// "reset to default" — matching the reference client's `JSON.stringify` +/// output; an omitted key would fail the hub's schema. +extension APIClient { + /// `POST /api/sessions/:id/permission-mode`. + public func setPermissionMode(sessionId: String, mode: PermissionMode) async throws { + struct PermissionModeRequest: Encodable { + let mode: PermissionMode + } + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/permission-mode", + body: PermissionModeRequest(mode: mode) + ) + } + + /// `POST /api/sessions/:id/model` (`nil` resets to the default model). + public func setModel(sessionId: String, model: ModelSelection?) async throws { + struct SetModelRequest: Encodable { + let model: ModelSelection? + + enum CodingKeys: String, CodingKey { + case model + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if let model { + try container.encode(model, forKey: .model) + } else { + try container.encodeNil(forKey: .model) + } + } + } + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/model", + body: SetModelRequest(model: model) + ) + } + + /// `POST /api/sessions/:id/effort` — claude, grok, pi. + public func setEffort(sessionId: String, effort: String?) async throws { + struct SetEffortRequest: Encodable { + let effort: String? + + enum CodingKeys: String, CodingKey { + case effort + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if let effort { + try container.encode(effort, forKey: .effort) + } else { + try container.encodeNil(forKey: .effort) + } + } + } + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/effort", + body: SetEffortRequest(effort: effort) + ) + } + + /// `POST /api/sessions/:id/model-reasoning-effort` — codex, opencode + /// (remote-only). + public func setModelReasoningEffort(sessionId: String, modelReasoningEffort: String?) async throws { + struct SetModelReasoningEffortRequest: Encodable { + let modelReasoningEffort: String? + + enum CodingKeys: String, CodingKey { + case modelReasoningEffort + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if let modelReasoningEffort { + try container.encode(modelReasoningEffort, forKey: .modelReasoningEffort) + } else { + try container.encodeNil(forKey: .modelReasoningEffort) + } + } + } + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/model-reasoning-effort", + body: SetModelReasoningEffortRequest(modelReasoningEffort: modelReasoningEffort) + ) + } + + /// `POST /api/sessions/:id/service-tier` — codex (remote-only). + public func setServiceTier(sessionId: String, serviceTier: ServiceTier?) async throws { + struct SetServiceTierRequest: Encodable { + let serviceTier: ServiceTier? + + enum CodingKeys: String, CodingKey { + case serviceTier + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if let serviceTier { + try container.encode(serviceTier, forKey: .serviceTier) + } else { + try container.encodeNil(forKey: .serviceTier) + } + } + } + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/service-tier", + body: SetServiceTierRequest(serviceTier: serviceTier) + ) + } + + /// `POST /api/sessions/:id/collaboration-mode` — codex (remote-only). + public func setCollaborationMode(sessionId: String, mode: CodexCollaborationMode) async throws { + struct CollaborationModeRequest: Encodable { + let mode: CodexCollaborationMode + } + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/collaboration-mode", + body: CollaborationModeRequest(mode: mode) + ) + } + + /// `POST /api/sessions/:id/copilot-agent-mode` — copilot (remote-only). + public func setCopilotAgentMode(sessionId: String, mode: CopilotAgentMode) async throws { + struct CopilotAgentModeRequest: Encodable { + let mode: CopilotAgentMode + } + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/copilot-agent-mode", + body: CopilotAgentModeRequest(mode: mode) + ) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift new file mode 100644 index 00000000..658b584a --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift @@ -0,0 +1,146 @@ +import Foundation +import HapiProtocol + +/// `order` query of `GET /api/sessions`. The default (absent) order is the +/// hub's ranked one (globalPinned → pinned → active → pending requests → +/// recency); `updatedAt` switches to pure recency. +public enum SessionsListOrder: String, Sendable { + case updatedAt +} + +/// Session list, detail, and lifecycle endpoints +/// (`docs/api/client-contract/rest.md`). +extension APIClient { + /// `GET /api/sessions`. + public func listSessions( + limit: Int? = nil, + order: SessionsListOrder? = nil + ) async throws -> [SessionSummary] { + var query: [URLQueryItem] = [] + if let limit { + query.append(URLQueryItem(name: "limit", value: String(limit))) + } + if let order { + query.append(URLQueryItem(name: "order", value: order.rawValue)) + } + let response: SessionsResponse = try await request(.get, "/api/sessions", query: query) + return response.sessions + } + + /// `GET /api/sessions/:id`. + public func session(id: String) async throws -> Session { + let response: SessionResponse = try await request( + .get, + "/api/sessions/\(encodePathComponent(id))" + ) + return response.session + } + + /// `POST /api/sessions/:id/resume`. The returned session id **may differ** + /// from `id` (fresh spawn superseding the old row) — navigate to it and + /// migrate composer drafts. + public func resumeSession(id: String, permissionMode: PermissionMode? = nil) async throws -> String { + struct ResumeSessionRequest: Encodable { + let permissionMode: PermissionMode + } + let path = "/api/sessions/\(encodePathComponent(id))/resume" + let response: ResumeSessionResponse + if let permissionMode { + response = try await request(.post, path, body: ResumeSessionRequest(permissionMode: permissionMode)) + } else { + response = try await request(.post, path) + } + return response.sessionId + } + + /// `POST /api/sessions/:id/reopen`. As with resume, follow the returned + /// session id. Incomplete metadata answers `422 {error, missing[]}`. + public func reopenSession(id: String) async throws -> ReopenSessionResponse { + try await request( + .post, + "/api/sessions/\(encodePathComponent(id))/reopen", + body: EmptyRequestBody() + ) + } + + /// `POST /api/sessions/:id/abort` (active sessions only). + public func abortSession(id: String) async throws { + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(id))/abort", + body: EmptyRequestBody() + ) + } + + /// `POST /api/sessions/:id/switch` — hands a terminal-controlled session + /// over to remote control. + public func switchSession(id: String) async throws { + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(id))/switch", + body: EmptyRequestBody() + ) + } + + /// `POST /api/sessions/:id/archive` (409 for a plain inactive session). + public func archiveSession(id: String) async throws { + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(id))/archive", + body: EmptyRequestBody() + ) + } + + /// `DELETE /api/sessions/:id` (409 while active — archive first). + public func deleteSession(id: String) async throws { + try await requestVoid(.delete, "/api/sessions/\(encodePathComponent(id))") + } + + /// `PATCH /api/sessions/:id` — rename (1–255 chars). + public func renameSession(id: String, name: String) async throws { + struct RenameSessionRequest: Encodable { + let name: String + } + try await requestVoid( + .patch, + "/api/sessions/\(encodePathComponent(id))", + body: RenameSessionRequest(name: name) + ) + } + + /// `PATCH /api/sessions/:id/summary` (1–255 chars). + public func updateSessionSummary(id: String, text: String) async throws { + struct UpdateSummaryRequest: Encodable { + let text: String + } + try await requestVoid( + .patch, + "/api/sessions/\(encodePathComponent(id))/summary", + body: UpdateSummaryRequest(text: text) + ) + } + + /// `PUT /api/sessions/:id/pin`. + public func setSessionPinMode(id: String, mode: SessionPinMode) async throws { + struct PinRequest: Encodable { + let mode: SessionPinMode + } + try await requestVoid( + .put, + "/api/sessions/\(encodePathComponent(id))/pin", + body: PinRequest(mode: mode) + ) + } + + // MARK: - Session catalogs (RPC-wrapped — check `success`) + + /// `GET /api/sessions/:id/slash-commands`. + public func slashCommands(sessionId: String) async throws -> SlashCommandsResponse { + try await request(.get, "/api/sessions/\(encodePathComponent(sessionId))/slash-commands") + } + + /// `GET /api/sessions/:id/skills`. + public func skills(sessionId: String) async throws -> SkillsResponse { + try await request(.get, "/api/sessions/\(encodePathComponent(sessionId))/skills") + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/HTTPPerforming.swift b/ios/Packages/HapiKit/Sources/HapiClient/HTTPPerforming.swift new file mode 100644 index 00000000..0c52cf1e --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/HTTPPerforming.swift @@ -0,0 +1,68 @@ +import Foundation + +/// Seam between the client stack and the actual HTTP transport. +/// +/// `APIClient` and `AuthManager` speak only to this protocol, so tests inject +/// a recording/scripted performer instead of resorting to `URLProtocol` +/// tricks. The production implementation wraps `URLSession`. +public protocol HTTPPerforming: Sendable { + /// Executes one HTTP exchange. Implementations must not throw on non-2xx + /// statuses — status handling (401 refresh, `APIError`) belongs to the + /// caller. Throw only for transport-level failures (`URLError`). + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) +} + +/// Production `HTTPPerforming` backed by `URLSession`. +public struct URLSessionHTTPPerformer: HTTPPerforming { + public let session: URLSession + + public init(session: URLSession) { + self.session = session + } + + /// Shared instance used by default across the client stack, so every + /// consumer benefits from one connection pool and one URL cache. + public static let shared = URLSessionHTTPPerformer(session: makeDefaultSession()) + + /// `URLSession` configured for the hub protocol. + /// + /// The 256 MB disk cache exists chiefly for generated images: the hub + /// serves them with `ETag` + `Cache-Control: private, max-age=31536000, + /// immutable`, so `URLCache` answers repeats locally (and revalidates via + /// `If-None-Match`/304 without the hub's CLI round-trip). Streaming gzip + /// decompression of JSON responses is transparent in `URLSession`. + public static func makeDefaultSession() -> URLSession { + let configuration = URLSessionConfiguration.default + configuration.urlCache = URLCache( + memoryCapacity: 32 * 1024 * 1024, + diskCapacity: 256 * 1024 * 1024, + directory: nil + ) + configuration.requestCachePolicy = .useProtocolCachePolicy + return URLSession(configuration: configuration) + } + + public func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse else { + throw URLError(.badServerResponse) + } + return (data, http) + } +} + +/// JSON coders shared by the whole transport layer so wire behavior is +/// uniform (and request bodies are byte-stable for tests). +public enum HapiJSON { + /// Wire fields are camelCase and dates are epoch-ms integers, so the + /// default strategies are exactly right. + public static let decoder = JSONDecoder() + + /// `sortedKeys` makes encoded bodies deterministic; + /// `withoutEscapingSlashes` keeps embedded paths readable. + public static let encoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return encoder + }() +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/HapiClientVersion.swift b/ios/Packages/HapiKit/Sources/HapiClient/HapiClientVersion.swift index 6368927c..f02cf62d 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/HapiClientVersion.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/HapiClientVersion.swift @@ -1,11 +1,11 @@ import Foundation import HapiProtocol -/// Scaffold marker for the transport layer. +/// Version anchor for the transport layer. /// -/// APIClient, AuthManager (single-flight refresh), and SSEClient arrive in -/// M1b/M1c. Until then this constant proves the target graph and the -/// HapiClient -> HapiProtocol dependency compile and link. +/// As of M1b the target carries `APIClient` + typed endpoints, `AuthManager` +/// (single-flight JWT refresh), the Keychain credential store, `HubRegistry`, +/// and the multipart builder; SSEClient and the stores arrive in M1c+. public enum HapiClientVersion { /// Version of the HapiKit client scaffold. public static let current = "0.1.0" diff --git a/ios/Packages/HapiKit/Sources/HapiClient/MultipartEncoder.swift b/ios/Packages/HapiKit/Sources/HapiClient/MultipartEncoder.swift new file mode 100644 index 00000000..bb483bce --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/MultipartEncoder.swift @@ -0,0 +1,65 @@ +import Foundation + +/// Minimal `multipart/form-data` builder for the one multipart endpoint, +/// `POST /api/voice/transcription` (M4c dictation): text fields plus one +/// file part. +/// +/// The boundary is injectable so tests can compare exact bytes; production +/// callers use the random default. Append order is preserved. +public struct MultipartFormData: Sendable { + public let boundary: String + private var body = Data() + + public init(boundary: String = MultipartFormData.makeBoundary()) { + self.boundary = boundary + } + + public static func makeBoundary() -> String { + "hapi.boundary.\(UUID().uuidString)" + } + + /// Value for the request's `Content-Type` header. + public var contentType: String { + "multipart/form-data; boundary=\(boundary)" + } + + /// Appends a plain text field. + public mutating func appendField(name: String, value: String) { + appendString("--\(boundary)\r\n") + appendString("Content-Disposition: form-data; name=\"\(Self.sanitize(name))\"\r\n\r\n") + appendString(value) + appendString("\r\n") + } + + /// Appends a file part. + public mutating func appendFile(fieldName: String, filename: String, mimeType: String, data: Data) { + appendString("--\(boundary)\r\n") + appendString( + "Content-Disposition: form-data; name=\"\(Self.sanitize(fieldName))\"; " + + "filename=\"\(Self.sanitize(filename))\"\r\n" + ) + appendString("Content-Type: \(mimeType)\r\n\r\n") + body.append(data) + appendString("\r\n") + } + + /// The complete request body, including the closing boundary. The + /// builder stays usable (value semantics) — encoding does not consume it. + public func encodedBody() -> Data { + var encoded = body + encoded.append(Data("--\(boundary)--\r\n".utf8)) + return encoded + } + + private mutating func appendString(_ string: String) { + body.append(Data(string.utf8)) + } + + /// Header values must not smuggle CRLF or unescaped quotes. + private static func sanitize(_ value: String) -> String { + value + .replacingOccurrences(of: "\r", with: "") + .replacingOccurrences(of: "\n", with: "") + .replacingOccurrences(of: "\"", with: "%22") + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/RequestBuilding.swift b/ios/Packages/HapiKit/Sources/HapiClient/RequestBuilding.swift new file mode 100644 index 00000000..d43d7cd5 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/RequestBuilding.swift @@ -0,0 +1,52 @@ +import Foundation + +/// URL assembly shared by `APIClient` and `AuthManager`. +/// +/// Percent-encoding is done by hand with the RFC 3986 unreserved set (the +/// strictest choice) so that path components and query values match what the +/// web client produces via `encodeURIComponent`/`URLSearchParams` — notably +/// `+` is encoded as `%2B`, which `URLComponents.queryItems` would leave +/// literal (and the hub would decode as a space). +enum HubRequestURL { + /// RFC 3986 unreserved characters — everything else is percent-encoded. + static let unreserved = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" + ) + + /// Builds `origin(baseURL) + path + query`. `path` must be an absolute, + /// already-percent-encoded path (compose dynamic segments with + /// ``encodePathComponent(_:)``); any path on `baseURL` itself is replaced, + /// matching the web client's `new URL(path, baseUrl)` for absolute paths. + static func make(baseURL: URL, path: String, query: [URLQueryItem]) throws -> URL { + guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true) else { + throw URLError(.badURL) + } + components.percentEncodedPath = path + components.fragment = nil + components.percentEncodedQuery = query.isEmpty ? nil : encodeQuery(query) + guard let url = components.url else { + throw URLError(.badURL) + } + return url + } + + /// Joins items in the given order as `name=value`, both strictly encoded. + static func encodeQuery(_ items: [URLQueryItem]) -> String { + items.map { item in + let name = encodeComponent(item.name) + guard let value = item.value else { return name } + return "\(name)=\(encodeComponent(value))" + } + .joined(separator: "&") + } + + static func encodeComponent(_ value: String) -> String { + value.addingPercentEncoding(withAllowedCharacters: unreserved) ?? value + } +} + +/// Percent-encodes one path segment (the `encodeURIComponent` equivalent used +/// for `:id`-style params throughout the endpoint layer). +func encodePathComponent(_ value: String) -> String { + HubRequestURL.encodeComponent(value) +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiRequests.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiRequests.swift new file mode 100644 index 00000000..a4142ea2 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiRequests.swift @@ -0,0 +1,306 @@ +import Foundation + +// Request bodies for the REST surface (`docs/api/client-contract/rest.md`). +// Field names mirror the Zod schemas in `shared/src/apiTypes.ts` one-to-one, +// so no CodingKeys are needed anywhere in this file. Single-field bodies +// (`{name}`, `{text}`, ...) stay private to the endpoint layer; only shapes +// that are multi-field or shared across features live here. + +/// How a sent message is delivered while the agent is busy. +/// +/// Mirrors `MessageDeliveryModeSchema` (`shared/src/apiTypes.ts`). +public enum MessageDeliveryMode: String, Codable, Sendable { + case queue + case steer +} + +/// Body of `POST /api/sessions/:id/messages`. +/// +/// Mirrors `SendMessageRequestSchema` (`shared/src/apiTypes.ts`). Server-side +/// refinements (text or attachments required; `scheduledAt` requires +/// `localId`, must be within 7 days, excludes attachments and steer) are not +/// re-validated client-side — the hub answers 400 on violation. +public struct SendMessageRequest: Codable, Equatable, Sendable { + public var text: String + /// Client-generated id for optimistic reconciliation. + public var localId: String? + public var attachments: [AttachmentMetadata]? + /// Future send time (epoch ms). + public var scheduledAt: Int? + public var deliveryMode: MessageDeliveryMode? + + public init( + text: String, + localId: String? = nil, + attachments: [AttachmentMetadata]? = nil, + scheduledAt: Int? = nil, + deliveryMode: MessageDeliveryMode? = nil + ) { + self.text = text + self.localId = localId + self.attachments = attachments + self.scheduledAt = scheduledAt + self.deliveryMode = deliveryMode + } +} + +/// Decision value carried by permission approve/deny bodies. +/// +/// Same wire values as the completed-request record, so the request side +/// reuses that enum (`'approved' | 'approved_for_session' | 'denied' | 'abort'`). +public typealias PermissionDecision = AgentStateCompletedRequest.Decision + +/// Body of `POST /api/sessions/:id/permissions/:requestId/approve`. +/// +/// `answers` has two wire formats depending on the requesting tool — +/// flat `{question: [answers]}` (AskUserQuestion) or nested +/// `{question: {answers: [...]}}` (request_user_input) — and is therefore +/// kept as raw ``JSONValue``. +public struct PermissionApproveRequest: Codable, Equatable, Sendable { + /// Optionally switch permission mode while approving. + public var mode: PermissionMode? + public var allowTools: [String]? + public var decision: PermissionDecision? + public var answers: JSONValue? + + public init( + mode: PermissionMode? = nil, + allowTools: [String]? = nil, + decision: PermissionDecision? = nil, + answers: JSONValue? = nil + ) { + self.mode = mode + self.allowTools = allowTools + self.decision = decision + self.answers = answers + } +} + +/// Body of `POST /api/sessions/:id/permissions/:requestId/deny`. +public struct PermissionDenyRequest: Codable, Equatable, Sendable { + public var decision: PermissionDecision? + + public init(decision: PermissionDecision? = nil) { + self.decision = decision + } +} + +/// The `model` value of `POST /api/sessions/:id/model`: +/// a plain model id or a `{provider, modelId}` catalog reference. +/// (`null` — reset to default — is expressed by the request wrapper, not here.) +public enum ModelSelection: Equatable, Sendable { + case id(String) + case catalogReference(provider: String, modelId: String) +} + +extension ModelSelection: Codable { + private struct CatalogReference: Codable { + let provider: String + let modelId: String + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let id = try? container.decode(String.self) { + self = .id(id) + return + } + if let reference = try? container.decode(CatalogReference.self) { + self = .catalogReference(provider: reference.provider, modelId: reference.modelId) + return + } + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Model selection is neither a string nor {provider, modelId}" + ) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .id(let id): + try container.encode(id) + case .catalogReference(let provider, let modelId): + try container.encode(CatalogReference(provider: provider, modelId: modelId)) + } + } +} + +/// Codex service tier (`POST /api/sessions/:id/service-tier`, spawn request). +public enum ServiceTier: String, Codable, Sendable { + case fast + case standard +} + +/// Pin mode of `PUT /api/sessions/:id/pin`. +public enum SessionPinMode: String, Codable, Sendable { + case none + case project + case global +} + +/// `sessionType` of the spawn request. +public enum SpawnSessionType: String, Codable, Sendable { + case simple + case worktree +} + +/// `startingMode` of the spawn request (`agy` accepts only `remote`). +public enum SpawnStartingMode: String, Codable, Sendable { + case remote + case pty +} + +/// Body of `POST /api/machines/:id/spawn`. +/// +/// Mirrors `SpawnSessionRequestSchema` (`shared/src/apiTypes.ts`). +public struct SpawnRequest: Codable, Equatable, Sendable { + public var directory: String + public var agent: AgentFlavor? + public var model: String? + public var effort: String? + public var modelReasoningEffort: String? + public var yolo: Bool? + public var permissionMode: PermissionMode? + public var sessionType: SpawnSessionType? + public var worktreeName: String? + public var serviceTier: ServiceTier? + public var collaborationMode: CodexCollaborationMode? + public var copilotAgentMode: CopilotAgentMode? + public var startingMode: SpawnStartingMode? + + public init( + directory: String, + agent: AgentFlavor? = nil, + model: String? = nil, + effort: String? = nil, + modelReasoningEffort: String? = nil, + yolo: Bool? = nil, + permissionMode: PermissionMode? = nil, + sessionType: SpawnSessionType? = nil, + worktreeName: String? = nil, + serviceTier: ServiceTier? = nil, + collaborationMode: CodexCollaborationMode? = nil, + copilotAgentMode: CopilotAgentMode? = nil, + startingMode: SpawnStartingMode? = nil + ) { + self.directory = directory + self.agent = agent + self.model = model + self.effort = effort + self.modelReasoningEffort = modelReasoningEffort + self.yolo = yolo + self.permissionMode = permissionMode + self.sessionType = sessionType + self.worktreeName = worktreeName + self.serviceTier = serviceTier + self.collaborationMode = collaborationMode + self.copilotAgentMode = copilotAgentMode + self.startingMode = startingMode + } +} + +/// Compound-cursor query of `GET /api/sessions/:id/messages`. +/// +/// Mirrors `MessagesQuerySchema` (`shared/src/apiTypes.ts`): every cursor is a +/// `(seq, at)` pair that travels together; `epoch` is only meaningful with an +/// `after` cursor; `until` bounds an `after` catch-up. Full semantics in +/// `docs/api/client-contract/pagination.md`. +public struct MessagesQuery: Equatable, Sendable { + /// Page size (1–200, server default 50). + public var limit: Int? + public var beforeSeq: Int? + public var beforeAt: Int? + public var afterSeq: Int? + public var afterAt: Int? + public var untilSeq: Int? + public var untilAt: Int? + public var epoch: Int? + + public init( + limit: Int? = nil, + beforeSeq: Int? = nil, + beforeAt: Int? = nil, + afterSeq: Int? = nil, + afterAt: Int? = nil, + untilSeq: Int? = nil, + untilAt: Int? = nil, + epoch: Int? = nil + ) { + self.limit = limit + self.beforeSeq = beforeSeq + self.beforeAt = beforeAt + self.afterSeq = afterSeq + self.afterAt = afterAt + self.untilSeq = untilSeq + self.untilAt = untilAt + self.epoch = epoch + } + + /// Newest page (no cursor). + public static func latest(limit: Int? = nil) -> MessagesQuery { + MessagesQuery(limit: limit) + } + + /// Page of history strictly older than the `(seq, at)` position. + public static func before(seq: Int, at: Int, limit: Int? = nil) -> MessagesQuery { + MessagesQuery(limit: limit, beforeSeq: seq, beforeAt: at) + } + + /// Catch-up page strictly newer than the `(seq, at)` position. + /// Pass the cached `epoch` so the server can answer `reset: true` when the + /// session history was rewritten. + public static func after( + seq: Int, + at: Int, + epoch: Int? = nil, + untilSeq: Int? = nil, + untilAt: Int? = nil, + limit: Int? = nil + ) -> MessagesQuery { + MessagesQuery( + limit: limit, + afterSeq: seq, + afterAt: at, + untilSeq: untilSeq, + untilAt: untilAt, + epoch: epoch + ) + } +} + +/// Visibility value of `POST /api/visibility`. +public enum VisibilityState: String, Codable, Sendable { + case visible + case hidden +} + +/// Body of `POST /api/visibility`. +/// +/// `subscriptionId` comes from the SSE `connection-changed` handshake and is +/// new on every reconnect; a stale id answers 404. +public struct VisibilityRequest: Codable, Equatable, Sendable { + public var subscriptionId: String + public var visibility: VisibilityState + + public init(subscriptionId: String, visibility: VisibilityState) { + self.subscriptionId = subscriptionId + self.visibility = visibility + } +} + +/// Body of `POST /api/sessions/:id/upload` (JSON + base64, not multipart). +/// +/// Mirrors `UploadFileRequestSchema`; decoded size limit is 50 MB (413 above). +public struct UploadFileRequest: Codable, Equatable, Sendable { + public var filename: String + /// Base64-encoded file content. + public var content: String + public var mimeType: String + + public init(filename: String, content: String, mimeType: String) { + self.filename = filename + self.content = content + self.mimeType = mimeType + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift new file mode 100644 index 00000000..fdd93f8f --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift @@ -0,0 +1,415 @@ +import Foundation + +// Response shapes for the REST surface (`docs/api/client-contract/rest.md`). +// Field names mirror `shared/src/apiTypes.ts` / `shared/src/schemas.ts` +// one-to-one — no CodingKeys anywhere in this file. Discriminated unions +// (`SpawnResponse`, `CancelMessageResponse`, `SteerQueuedMessageResponse`) +// are decode-only: the client never sends them. + +// MARK: - Auth & health + +/// The `user` object of the auth response. +public struct AuthUser: Codable, Equatable, Sendable { + public var id: Int + public var username: String? + public var firstName: String? + public var lastName: String? + + public init(id: Int, username: String? = nil, firstName: String? = nil, lastName: String? = nil) { + self.id = id + self.username = username + self.firstName = firstName + self.lastName = lastName + } +} + +/// Success body of `POST /api/auth`. +public struct AuthResponse: Codable, Equatable, Sendable { + /// The JWT (HS256, `{uid, ns}`, 4 h expiry). + public var token: String + public var user: AuthUser + + public init(token: String, user: AuthUser) { + self.token = token + self.user = user + } +} + +/// Additive capability flags of `GET /health`. Unknown keys are ignored. +public struct HubCapabilities: Codable, Equatable, Sendable { + public var workGraph: Bool? + public var titleSuggestion: Bool? + + public init(workGraph: Bool? = nil, titleSuggestion: Bool? = nil) { + self.workGraph = workGraph + self.titleSuggestion = titleSuggestion + } +} + +/// Body of `GET /health` (unauthenticated). +public struct HubHealthResponse: Codable, Equatable, Sendable { + public var status: String + public var protocolVersion: Int + public var capabilities: HubCapabilities? + + public init(status: String, protocolVersion: Int, capabilities: HubCapabilities? = nil) { + self.status = status + self.protocolVersion = protocolVersion + self.capabilities = capabilities + } +} + +// MARK: - Envelopes + +/// Envelope of `GET /api/sessions`. +public struct SessionsResponse: Codable, Equatable, Sendable { + public var sessions: [SessionSummary] + + public init(sessions: [SessionSummary]) { + self.sessions = sessions + } +} + +/// Envelope of `GET /api/sessions/:id`. +public struct SessionResponse: Codable, Equatable, Sendable { + public var session: Session + + public init(session: Session) { + self.session = session + } +} + +/// Envelope of `GET /api/machines`. +public struct MachinesResponse: Codable, Equatable, Sendable { + public var machines: [Machine] + + public init(machines: [Machine]) { + self.machines = machines + } +} + +// MARK: - Session lifecycle + +/// Body of `POST /api/sessions/:id/resume` — `{type: 'success', sessionId}`. +/// Only `sessionId` is modeled; failures arrive as HTTP errors. +/// +/// The returned id may differ from the one the call was made on (fresh spawn +/// under a new id) — callers must follow it. +public struct ResumeSessionResponse: Codable, Equatable, Sendable { + public var sessionId: String + + public init(sessionId: String) { + self.sessionId = sessionId + } +} + +/// Body of `POST /api/sessions/:id/reopen`. +/// +/// Mirrors `ReopenSessionResponseSchema` (`shared/src/apiTypes.ts`). As with +/// resume, `sessionId` may differ from the id the call was made on. +public struct ReopenSessionResponse: Codable, Equatable, Sendable { + public var ok: Bool + public var sessionId: String + public var resumed: Bool + /// `'acp' | 'stream-json'`; kept open for forward compatibility. + public var cursorSessionProtocol: String? + + public init(ok: Bool, sessionId: String, resumed: Bool, cursorSessionProtocol: String? = nil) { + self.ok = ok + self.sessionId = sessionId + self.resumed = resumed + self.cursorSessionProtocol = cursorSessionProtocol + } +} + +// MARK: - Spawning + +/// Body of `POST /api/machines/:id/spawn`, discriminated on `type` — a failed +/// spawn is still HTTP 200 with `type: 'error'`. +public enum SpawnResponse: Equatable, Sendable { + case success(sessionId: String) + case error(message: String) +} + +extension SpawnResponse: Decodable { + private enum CodingKeys: String, CodingKey { + case type + case sessionId + case message + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let type = try container.decode(String.self, forKey: .type) + switch type { + case "success": + self = .success(sessionId: try container.decode(String.self, forKey: .sessionId)) + case "error": + self = .error(message: try container.decode(String.self, forKey: .message)) + default: + throw DecodingError.dataCorrupted(DecodingError.Context( + codingPath: decoder.codingPath, + debugDescription: "Unknown SpawnResponse type '\(type)'" + )) + } + } +} + +// MARK: - Message queue operations + +/// Body of `DELETE /api/sessions/:id/messages/:messageId`, discriminated on +/// `status`. `invoked` means the cancel arrived too late — the message was +/// already handed to the agent. +public enum CancelMessageResponse: Equatable, Sendable { + case cancelled(localId: String?) + case invoked(message: DecryptedMessage) +} + +extension CancelMessageResponse: Decodable { + private enum CodingKeys: String, CodingKey { + case status + case localId + case message + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let status = try container.decode(String.self, forKey: .status) + switch status { + case "cancelled": + self = .cancelled(localId: try container.decodeIfPresent(String.self, forKey: .localId)) + case "invoked": + self = .invoked(message: try container.decode(DecryptedMessage.self, forKey: .message)) + default: + throw DecodingError.dataCorrupted(DecodingError.Context( + codingPath: decoder.codingPath, + debugDescription: "Unknown CancelMessageResponse status '\(status)'" + )) + } + } +} + +/// Body of `POST /api/sessions/:id/messages/:messageId/steer`, discriminated +/// on `status`. +public enum SteerQueuedMessageResponse: Equatable, Sendable { + case steered(localId: String) + case invoked(message: DecryptedMessage) + case failed(error: String, localId: String?) +} + +extension SteerQueuedMessageResponse: Decodable { + private enum CodingKeys: String, CodingKey { + case status + case localId + case message + case error + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let status = try container.decode(String.self, forKey: .status) + switch status { + case "steered": + self = .steered(localId: try container.decode(String.self, forKey: .localId)) + case "invoked": + self = .invoked(message: try container.decode(DecryptedMessage.self, forKey: .message)) + case "failed": + self = .failed( + error: try container.decode(String.self, forKey: .error), + localId: try container.decodeIfPresent(String.self, forKey: .localId) + ) + default: + throw DecodingError.dataCorrupted(DecodingError.Context( + codingPath: decoder.codingPath, + debugDescription: "Unknown SteerQueuedMessageResponse status '\(status)'" + )) + } + } +} + +/// One invoked entry of the queued-state response. +public struct InvokedLocalMessage: Codable, Equatable, Sendable { + public var localId: String + public var invokedAt: Int + + public init(localId: String, invokedAt: Int) { + self.localId = localId + self.invokedAt = invokedAt + } +} + +/// Body of `POST /api/sessions/:id/messages/queued-state` — resyncs +/// optimistic sends after a reconnect. +public struct QueuedStateResponse: Codable, Equatable, Sendable { + public var queuedLocalIds: [String] + public var invokedLocalMessages: [InvokedLocalMessage] + + public init(queuedLocalIds: [String], invokedLocalMessages: [InvokedLocalMessage]) { + self.queuedLocalIds = queuedLocalIds + self.invokedLocalMessages = invokedLocalMessages + } +} + +// MARK: - Session catalogs (RPC-wrapped) + +/// One slash command of the session catalog. `source` is kept as a raw string +/// (`'builtin' | 'user' | 'plugin' | 'project'` today) so a new source never +/// breaks decoding. +public struct SlashCommand: Codable, Equatable, Sendable { + public var name: String + public var description: String? + public var source: String + public var content: String? + public var pluginName: String? + + public init( + name: String, + description: String? = nil, + source: String, + content: String? = nil, + pluginName: String? = nil + ) { + self.name = name + self.description = description + self.source = source + self.content = content + self.pluginName = pluginName + } +} + +/// Body of `GET /api/sessions/:id/slash-commands` (RPC envelope — check +/// `success`, HTTP 200 alone means nothing). +public struct SlashCommandsResponse: Codable, Equatable, Sendable { + public var success: Bool + public var commands: [SlashCommand]? + public var error: String? + + public init(success: Bool, commands: [SlashCommand]? = nil, error: String? = nil) { + self.success = success + self.commands = commands + self.error = error + } +} + +/// One skill of the session catalog. +public struct SkillSummary: Codable, Equatable, Sendable { + public var name: String + public var description: String? + + public init(name: String, description: String? = nil) { + self.name = name + self.description = description + } +} + +/// Body of `GET /api/sessions/:id/skills` (RPC envelope). +public struct SkillsResponse: Codable, Equatable, Sendable { + public var success: Bool + public var skills: [SkillSummary]? + public var error: String? + + public init(success: Bool, skills: [SkillSummary]? = nil, error: String? = nil) { + self.success = success + self.skills = skills + self.error = error + } +} + +// MARK: - Machine directory browsing + +/// Entry type of a directory listing. +public enum DirectoryEntryType: String, Codable, Sendable { + case file + case directory + case other +} + +/// One entry of `GET /api/sessions/:id/directory`. +public struct DirectoryEntry: Codable, Equatable, Sendable { + public var name: String + public var type: DirectoryEntryType + /// Size in bytes (files only). + public var size: Int? + /// mtime, epoch ms. + public var modified: Int? + + public init(name: String, type: DirectoryEntryType, size: Int? = nil, modified: Int? = nil) { + self.name = name + self.type = type + self.size = size + self.modified = modified + } +} + +/// One entry of `POST /api/machines/:id/list-directory` +/// (`DirectoryEntry & {isGitRepo?}` flattened). +public struct MachineDirectoryEntry: Codable, Equatable, Sendable { + public var name: String + public var type: DirectoryEntryType + public var size: Int? + public var modified: Int? + public var isGitRepo: Bool? + + public init( + name: String, + type: DirectoryEntryType, + size: Int? = nil, + modified: Int? = nil, + isGitRepo: Bool? = nil + ) { + self.name = name + self.type = type + self.size = size + self.modified = modified + self.isGitRepo = isGitRepo + } +} + +/// Body of `POST /api/machines/:id/list-directory` (RPC envelope). +public struct MachineListDirectoryResponse: Codable, Equatable, Sendable { + public var success: Bool + public var entries: [MachineDirectoryEntry]? + public var error: String? + + public init(success: Bool, entries: [MachineDirectoryEntry]? = nil, error: String? = nil) { + self.success = success + self.entries = entries + self.error = error + } +} + +/// Body of `POST /api/machines/:id/paths/exists`. +public struct MachinePathsExistsResponse: Codable, Equatable, Sendable { + public var exists: [String: Bool] + + public init(exists: [String: Bool]) { + self.exists = exists + } +} + +// MARK: - Uploads + +/// Body of `POST /api/sessions/:id/upload` (RPC envelope). `path` feeds the +/// `attachments` metadata of a subsequent send-message. +public struct UploadFileResponse: Codable, Equatable, Sendable { + public var success: Bool + public var path: String? + public var error: String? + + public init(success: Bool, path: String? = nil, error: String? = nil) { + self.success = success + self.path = path + self.error = error + } +} + +/// Body of `POST /api/sessions/:id/upload/delete` (RPC envelope). +public struct DeleteUploadResponse: Codable, Equatable, Sendable { + public var success: Bool + public var error: String? + + public init(success: Bool, error: String? = nil) { + self.success = success + self.error = error + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/APIClientTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/APIClientTests.swift new file mode 100644 index 00000000..7570f4df --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/APIClientTests.swift @@ -0,0 +1,136 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +@Suite("APIClient auth & errors") +struct APIClientTests { + @Test func retriesOnceAfter401WithRefreshedToken() async throws { + let initial = freshJWT() + let harness = try makeHarness(jwt: initial) + let rotated = makeJWT(exp: testEpochSeconds + 5 * 3600) + await harness.performer.enqueue(status: 401, json: "{\"error\":\"Invalid token\"}") + await harness.performer.enqueue(json: authResponseJSON(token: rotated)) + await harness.performer.enqueue(json: "{\"sessions\":[]}") + + let sessions = try await harness.client.listSessions() + #expect(sessions.isEmpty) + + let requests = await harness.performer.requests + try #require(requests.count == 3) + #expect(requests[0].url?.absoluteString == "\(testHubURLString)/api/sessions") + #expect(requests[0].value(forHTTPHeaderField: "Authorization") == "Bearer \(initial)") + #expect(requests[1].url?.absoluteString == "\(testHubURLString)/api/auth") + #expect(requests[1].value(forHTTPHeaderField: "Authorization") == nil) + #expect(requests[2].url?.absoluteString == "\(testHubURLString)/api/sessions") + #expect(requests[2].value(forHTTPHeaderField: "Authorization") == "Bearer \(rotated)") + } + + @Test func secondConsecutive401IsTerminal() async throws { + let harness = try makeHarness(jwt: freshJWT()) + let rotated = makeJWT(exp: testEpochSeconds + 5 * 3600) + await harness.performer.enqueue(status: 401, json: "{\"error\":\"Invalid token\"}") + await harness.performer.enqueue(json: authResponseJSON(token: rotated)) + await harness.performer.enqueue(status: 401, json: "{\"error\":\"Invalid token\"}") + + let error = await capturedError { try await harness.client.listSessions() } + let apiError = error as? APIError + #expect(apiError?.status == 401) + let failed = await harness.auth.isAuthenticationFailed + #expect(failed) + let countAfterFailure = await harness.performer.requests.count + #expect(countAfterFailure == 3) + + // Follow-up calls surface "re-pair needed" without touching the hub. + let followUp = await capturedError { try await harness.client.listSessions() } + #expect(followUp as? AuthError == .reauthenticationRequired) + let countAfterFollowUp = await harness.performer.requests.count + #expect(countAfterFollowUp == 3) + } + + @Test func rejectedAccessTokenSurfacesReauthenticationRequired() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(status: 401, json: "{\"error\":\"Invalid token\"}") + await harness.performer.enqueue(status: 401, json: "{\"error\":\"Invalid access token\"}") + + let error = await capturedError { try await harness.client.listSessions() } + #expect(error as? AuthError == .reauthenticationRequired) + let requestCount = await harness.performer.requests.count + #expect(requestCount == 2) + } + + @Test func parsesErrorBodyWithCode() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue( + status: 409, + json: "{\"error\":\"Session is inactive\",\"code\":\"session_inactive\"}" + ) + let error = await capturedError { try await harness.client.abortSession(id: "s1") } + let apiError = error as? APIError + #expect(apiError?.status == 409) + #expect(apiError?.code == "session_inactive") + #expect(apiError?.body == "{\"error\":\"Session is inactive\",\"code\":\"session_inactive\"}") + } + + @Test func fallsBackToErrorStringAsPseudoCode() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(status: 503, json: "{\"error\":\"Not connected\"}") + let error = await capturedError { try await harness.client.listSessions() } + #expect((error as? APIError)?.code == "Not connected") + } + + @Test func nonJSONBodyYieldsNilCode() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(status: 500, json: "boom") + let error = await capturedError { try await harness.client.listSessions() } + let apiError = error as? APIError + #expect(apiError?.status == 500) + #expect(apiError?.code == nil) + #expect(apiError?.body == "boom") + } + + @Test func healthIsUnauthenticated() async throws { + // Deliberately unpaired: /health must not consult AuthManager. + let harness = try makeHarness(paired: false) + await harness.performer.enqueue(json: "{\"status\":\"ok\",\"protocolVersion\":1}") + let health = try await harness.client.health() + #expect(health.status == "ok") + #expect(health.protocolVersion == 1) + let requests = await harness.performer.requests + try #require(requests.count == 1) + #expect(requests[0].url?.absoluteString == "\(testHubURLString)/health") + #expect(requests[0].value(forHTTPHeaderField: "Authorization") == nil) + } + + @Test func authenticateExchangesAccessToken() async throws { + let harness = try makeHarness(paired: false) + let issued = freshJWT() + await harness.performer.enqueue(json: authResponseJSON(token: issued)) + let response = try await harness.client.authenticate(accessToken: "base:team") + #expect(response.token == issued) + #expect(response.user.id == 1) + let requests = await harness.performer.requests + try #require(requests.count == 1) + #expect(requests[0].url?.absoluteString == "\(testHubURLString)/api/auth") + let body = requests[0].httpBody.flatMap { String(data: $0, encoding: .utf8) } + #expect(body == "{\"accessToken\":\"base:team\"}") + #expect(requests[0].value(forHTTPHeaderField: "Authorization") == nil) + } + + @Test func requestBytesReturnsRawPayload() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue( + json: "not-json-bytes", + headers: ["Content-Type": "image/png"] + ) + let image = try await harness.client.generatedImage(sessionId: "s1", imageId: "img1") + #expect(image.data == Data("not-json-bytes".utf8)) + #expect(image.mimeType == "image/png") + let requests = await harness.performer.requests + try #require(requests.count == 1) + #expect( + requests[0].url?.absoluteString + == "\(testHubURLString)/api/sessions/s1/generated-images/img1" + ) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/AuthManagerTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/AuthManagerTests.swift new file mode 100644 index 00000000..f1739cb2 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/AuthManagerTests.swift @@ -0,0 +1,144 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +@Suite("AuthManager") +struct AuthManagerTests { + @Test func concurrentCallersShareOneRefresh() async throws { + let harness = try makeHarness(jwt: nil) + let issued = freshJWT() + await harness.performer.enqueue(json: authResponseJSON(token: issued)) + await harness.performer.setDelay(nanoseconds: 20_000_000) + + let tokens = try await withThrowingTaskGroup(of: String.self) { group in + for _ in 0..<8 { + group.addTask { try await harness.auth.validToken() } + } + var collected: [String] = [] + for try await token in group { + collected.append(token) + } + return collected + } + + #expect(tokens.count == 8) + #expect(Set(tokens) == [issued]) + let requests = await harness.performer.requests + try #require(requests.count == 1) + #expect(requests[0].url?.absoluteString == "\(testHubURLString)/api/auth") + #expect(requests[0].httpMethod == "POST") + let body = requests[0].httpBody.flatMap { String(data: $0, encoding: .utf8) } + #expect(body == "{\"accessToken\":\"access-token\"}") + } + + @Test func freshTokenIsReturnedWithoutTraffic() async throws { + let stored = freshJWT() + let harness = try makeHarness(jwt: stored) + let token = try await harness.auth.validToken() + #expect(token == stored) + let requestCount = await harness.performer.requests.count + #expect(requestCount == 0) + } + + @Test func refreshesProactivelyWithinTenMinutesOfExpiry() async throws { + let expiring = makeJWT(exp: testEpochSeconds + 5 * 60) + let harness = try makeHarness(jwt: expiring) + let issued = freshJWT() + await harness.performer.enqueue(json: authResponseJSON(token: issued)) + + let token = try await harness.auth.validToken() + #expect(token == issued) + let requestCount = await harness.performer.requests.count + #expect(requestCount == 1) + } + + @Test func failedProactiveRefreshFallsBackAndThrottles() async throws { + let expiring = makeJWT(exp: testEpochSeconds + 5 * 60) + let harness = try makeHarness(jwt: expiring) + await harness.performer.setFallback(status: 503, json: "{\"error\":\"Not connected\"}") + + // First attempt hits the hub, fails, and falls back to the still + // valid token. + let first = try await harness.auth.validToken() + #expect(first == expiring) + let countAfterFirst = await harness.performer.requests.count + #expect(countAfterFirst == 1) + + // Within the 15 s throttle no further attempt is made. + let second = try await harness.auth.validToken() + #expect(second == expiring) + let countAfterSecond = await harness.performer.requests.count + #expect(countAfterSecond == 1) + } + + @Test func expiredTokenIsRefreshed() async throws { + let expired = makeJWT(exp: testEpochSeconds - 10) + let harness = try makeHarness(jwt: expired) + let issued = freshJWT() + await harness.performer.enqueue(json: authResponseJSON(token: issued)) + + let token = try await harness.auth.validToken() + #expect(token == issued) + let requestCount = await harness.performer.requests.count + #expect(requestCount == 1) + } + + @Test func authEndpoint401IsTerminal() async throws { + let harness = try makeHarness(jwt: nil) + await harness.performer.setFallback(status: 401, json: "{\"error\":\"Invalid access token\"}") + + let firstError = await capturedError { try await harness.auth.validToken() } + #expect(firstError as? AuthError == .reauthenticationRequired) + let failed = await harness.auth.isAuthenticationFailed + #expect(failed) + + // Terminal: no further exchange is attempted. + let secondError = await capturedError { try await harness.auth.validToken() } + #expect(secondError as? AuthError == .reauthenticationRequired) + let requestCount = await harness.performer.requests.count + #expect(requestCount == 1) + } + + @Test func missingCredentialsThrowNotPaired() async throws { + let harness = try makeHarness(paired: false) + let error = await capturedError { try await harness.auth.validToken() } + #expect(error as? AuthError == .notPaired) + let requestCount = await harness.performer.requests.count + #expect(requestCount == 0) + // Not terminal: pairing afterwards must be able to proceed. + let failed = await harness.auth.isAuthenticationFailed + #expect(failed == false) + } + + @Test func refreshPersistsJWTNextToAccessToken() async throws { + let harness = try makeHarness(jwt: nil) + let issued = freshJWT() + await harness.performer.enqueue(json: authResponseJSON(token: issued)) + + _ = try await harness.auth.validToken() + let stored = try harness.store.credentials(forHub: testHubURLString) + #expect(stored?.accessToken == "access-token") + #expect(stored?.jwt == issued) + #expect(stored?.jwtObtainedAt == testEpochSeconds * 1000) + } + + @Test func unauthorizedRefreshSkipsExchangeWhenTokenAlreadyRotated() async throws { + let current = freshJWT() + let harness = try makeHarness(jwt: current) + // Prime the in-memory token. + _ = try await harness.auth.validToken() + + let token = try await harness.auth.refreshAfterUnauthorized(failedToken: "some-older-token") + #expect(token == current) + let requestCount = await harness.performer.requests.count + #expect(requestCount == 0) + } + + @Test func claimsExposeNamespaceForOwnerGating() async throws { + let harness = try makeHarness(jwt: freshJWT(ns: "team")) + _ = try await harness.auth.validToken() + let claims = await harness.auth.currentClaims + #expect(claims?.ns == "team") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/CredentialStoreTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/CredentialStoreTests.swift new file mode 100644 index 00000000..00749b70 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/CredentialStoreTests.swift @@ -0,0 +1,63 @@ +import Foundation +import HapiClient +import Testing + +// The Keychain-backed store cannot run on CI (no entitlements/keychain), so +// coverage targets the protocol semantics through the in-memory double the +// rest of the suite relies on. +@Suite("InMemoryCredentialStore") +struct CredentialStoreTests { + @Test func roundTripsPerHubRecords() throws { + let store = InMemoryCredentialStore() + let missing = try store.credentials(forHub: "https://one.test") + #expect(missing == nil) + + let one = HubCredentials( + hubUrl: "https://one.test", + accessToken: "token-one", + jwt: "jwt-one", + jwtObtainedAt: 1_700_000_000_000 + ) + let two = HubCredentials(hubUrl: "https://two.test", accessToken: "token-two") + try store.store(one) + try store.store(two) + + let storedOne = try store.credentials(forHub: "https://one.test") + let storedTwo = try store.credentials(forHub: "https://two.test") + #expect(storedOne == one) + #expect(storedTwo == two) + } + + @Test func storeReplacesExistingRecord() throws { + let store = InMemoryCredentialStore() + try store.store(HubCredentials(hubUrl: "https://one.test", accessToken: "old")) + let updated = HubCredentials(hubUrl: "https://one.test", accessToken: "new", jwt: "j") + try store.store(updated) + let stored = try store.credentials(forHub: "https://one.test") + #expect(stored == updated) + } + + @Test func deleteIsIdempotent() throws { + let store = InMemoryCredentialStore() + try store.store(HubCredentials(hubUrl: "https://one.test", accessToken: "t")) + try store.deleteCredentials(forHub: "https://one.test") + let afterDelete = try store.credentials(forHub: "https://one.test") + #expect(afterDelete == nil) + // Deleting again must not throw. + try store.deleteCredentials(forHub: "https://one.test") + } + + @Test func hubCredentialsSurviveJSONRoundTrip() throws { + // The Keychain store persists the record as JSON; make sure the + // shape round-trips losslessly. + let record = HubCredentials( + hubUrl: "https://hub.test", + accessToken: "base:team", + jwt: makeJWT(), + jwtObtainedAt: 1_700_000_123_456 + ) + let data = try JSONEncoder().encode(record) + let decoded = try JSONDecoder().decode(HubCredentials.self, from: data) + #expect(decoded == record) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift new file mode 100644 index 00000000..885593f1 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift @@ -0,0 +1,139 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +private let emptyPageJSON = """ +{"messages":[],"page":{"direction":"before","limit":200,"epoch":0,"reset":false,\ +"nextBeforeSeq":null,"nextBeforeAt":null,"nextAfterSeq":null,"nextAfterAt":null,\ +"snapshotHeadSeq":null,"snapshotHeadAt":null,"hasMore":false}} +""" + +@Suite("Endpoint request construction") +struct EndpointRequestTests { + private func bodyString(_ request: URLRequest?) -> String? { + request?.httpBody.flatMap { String(data: $0, encoding: .utf8) } + } + + @Test func messagesPageWithBeforeCursor() async throws { + let token = freshJWT() + let harness = try makeHarness(jwt: token) + await harness.performer.enqueue(json: emptyPageJSON) + + let response = try await harness.client.messages( + sessionId: "s 1", + query: .before(seq: 42, at: 170, limit: 200) + ) + #expect(response.messages.isEmpty) + #expect(response.page.direction == .before) + + let request = await harness.performer.requests.first + #expect( + request?.url?.absoluteString + == "\(testHubURLString)/api/sessions/s%201/messages?beforeAt=170&beforeSeq=42&limit=200" + ) + #expect(request?.httpMethod == "GET") + #expect(request?.value(forHTTPHeaderField: "Authorization") == "Bearer \(token)") + } + + @Test func messagesPageWithAfterCursorAndEpoch() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: emptyPageJSON) + + _ = try await harness.client.messages( + sessionId: "abc", + query: .after(seq: 10, at: 99, epoch: 3) + ) + let request = await harness.performer.requests.first + #expect( + request?.url?.absoluteString + == "\(testHubURLString)/api/sessions/abc/messages?afterAt=99&afterSeq=10&epoch=3" + ) + } + + @Test func sendMessageWithDeliveryMode() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: "{\"ok\":true}") + + try await harness.client.sendMessage( + sessionId: "abc", + text: "hi", + localId: "L1", + deliveryMode: .steer + ) + let request = await harness.performer.requests.first + #expect(request?.url?.absoluteString == "\(testHubURLString)/api/sessions/abc/messages") + #expect(request?.httpMethod == "POST") + #expect(request?.value(forHTTPHeaderField: "Content-Type") == "application/json") + #expect(bodyString(request) == "{\"deliveryMode\":\"steer\",\"localId\":\"L1\",\"text\":\"hi\"}") + } + + @Test func approveWithNestedAnswers() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: "{\"ok\":true}") + + try await harness.client.approvePermission( + sessionId: "abc", + requestId: "r/1", + PermissionApproveRequest(answers: ["q1": ["answers": ["a", "b"]]]) + ) + let request = await harness.performer.requests.first + #expect( + request?.url?.absoluteString + == "\(testHubURLString)/api/sessions/abc/permissions/r%2F1/approve" + ) + #expect(bodyString(request) == "{\"answers\":{\"q1\":{\"answers\":[\"a\",\"b\"]}}}") + } + + @Test func approveWithFlatAnswersAndModeSwitch() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: "{\"ok\":true}") + + try await harness.client.approvePermission( + sessionId: "abc", + requestId: "r1", + PermissionApproveRequest(mode: .acceptEdits, answers: ["q1": ["a", "b"]]) + ) + let request = await harness.performer.requests.first + #expect( + bodyString(request) + == "{\"answers\":{\"q1\":[\"a\",\"b\"]},\"mode\":\"acceptEdits\"}" + ) + } + + @Test func setModelEncodesExplicitNull() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: "{\"ok\":true}") + try await harness.client.setModel(sessionId: "abc", model: nil) + let first = await harness.performer.requests.first + #expect(bodyString(first) == "{\"model\":null}") + + await harness.performer.enqueue(json: "{\"ok\":true}") + try await harness.client.setModel( + sessionId: "abc", + model: .catalogReference(provider: "openai", modelId: "gpt-5") + ) + let second = await harness.performer.requests.last + #expect(bodyString(second) == "{\"model\":{\"modelId\":\"gpt-5\",\"provider\":\"openai\"}}") + } + + @Test func spawnDiscriminatesOnType() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: "{\"type\":\"success\",\"sessionId\":\"new-id\"}") + let spawned = try await harness.client.spawnSession( + machineId: "m1", + SpawnRequest(directory: "/work/repo", agent: .claude, sessionType: .worktree, worktreeName: "wt") + ) + #expect(spawned == .success(sessionId: "new-id")) + let request = await harness.performer.requests.first + #expect(request?.url?.absoluteString == "\(testHubURLString)/api/machines/m1/spawn") + #expect( + bodyString(request) + == "{\"agent\":\"claude\",\"directory\":\"/work/repo\",\"sessionType\":\"worktree\",\"worktreeName\":\"wt\"}" + ) + + await harness.performer.enqueue(json: "{\"type\":\"error\",\"message\":\"no runner\"}") + let failed = try await harness.client.spawnSession(machineId: "m1", SpawnRequest(directory: "/x")) + #expect(failed == .error(message: "no runner")) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/HubRegistryTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/HubRegistryTests.swift new file mode 100644 index 00000000..c7b85130 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/HubRegistryTests.swift @@ -0,0 +1,90 @@ +import Foundation +import HapiClient +import Testing + +@Suite("Hub URL normalization") +struct HubURLNormalizationTests { + @Test func normalizesToLowercasedOrigin() { + #expect(HubURLNormalization.normalize(" https://Hub.Example.com/ ") == "https://hub.example.com") + #expect(HubURLNormalization.normalize("https://hub.example.com/some/path?q=1#f") == "https://hub.example.com") + #expect(HubURLNormalization.normalize("HTTP://hub.example.com") == "http://hub.example.com") + } + + @Test func dropsDefaultPortsKeepsCustomOnes() { + #expect(HubURLNormalization.normalize("https://hub.example.com:443/") == "https://hub.example.com") + #expect(HubURLNormalization.normalize("http://hub.example.com:80") == "http://hub.example.com") + #expect(HubURLNormalization.normalize("http://192.168.1.5:8005/") == "http://192.168.1.5:8005") + } + + @Test func keepsIPv6Brackets() { + #expect(HubURLNormalization.normalize("http://[::1]:8005/") == "http://[::1]:8005") + } + + @Test(arguments: ["", " ", "hub.example.com", "ftp://hub.example.com", "hapicompanion://bind"]) + func rejectsNonHTTPInputs(raw: String) { + #expect(HubURLNormalization.normalize(raw) == nil) + } +} + +@Suite("HubRegistry") +struct HubRegistryTests { + private func makeDefaults() throws -> (UserDefaults, String) { + let suiteName = "HubRegistryTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + return (defaults, suiteName) + } + + @Test func registersInOrderAndActivatesFirst() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + let registry = HubRegistry(defaults: defaults) + + #expect(registry.register("https://one.test/") == "https://one.test") + #expect(registry.register("https://two.test") == "https://two.test") + // Re-registering (differently formatted) is a no-op. + #expect(registry.register("https://ONE.test") == "https://one.test") + + #expect(registry.hubs == ["https://one.test", "https://two.test"]) + #expect(registry.activeHub == "https://one.test") + } + + @Test func invalidURLIsRejected() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + let registry = HubRegistry(defaults: defaults) + #expect(registry.register("not a url") == nil) + #expect(registry.hubs.isEmpty) + #expect(registry.activeHub == nil) + } + + @Test func switchesAndValidatesActiveHub() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + let registry = HubRegistry(defaults: defaults) + registry.register("https://one.test") + registry.register("https://two.test") + + #expect(registry.setActiveHub("https://two.test/")) + #expect(registry.activeHub == "https://two.test") + // Unregistered hubs cannot become active. + #expect(registry.setActiveHub("https://three.test") == false) + #expect(registry.activeHub == "https://two.test") + } + + @Test func removalFallsBackToFirstRemainingHub() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + let registry = HubRegistry(defaults: defaults) + registry.register("https://one.test") + registry.register("https://two.test") + registry.setActiveHub("https://two.test") + + registry.remove("https://two.test") + #expect(registry.hubs == ["https://one.test"]) + #expect(registry.activeHub == "https://one.test") + + registry.remove("https://one.test") + #expect(registry.hubs.isEmpty) + #expect(registry.activeHub == nil) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/JWTTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/JWTTests.swift new file mode 100644 index 00000000..34744abb --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/JWTTests.swift @@ -0,0 +1,62 @@ +import Foundation +import HapiClient +import Testing + +@Suite("JWT payload decoding") +struct JWTTests { + @Test func decodesHubShapedPayload() { + let token = makeJWT(uid: 7, ns: "team", exp: 1_800_000_000) + let claims = JWT.claims(from: token) + #expect(claims == JWTClaims(uid: 7, ns: "team", exp: 1_800_000_000)) + #expect(claims?.expiresAt == Date(timeIntervalSince1970: 1_800_000_000)) + } + + @Test func missingExpIsAllowed() { + let claims = JWT.claims(from: makeJWT(uid: 1, ns: "default")) + #expect(claims == JWTClaims(uid: 1, ns: "default", exp: nil)) + #expect(claims?.expiresAt == nil) + } + + /// Payload lengths spanning every base64 padding remainder must all + /// decode (the middle segment arrives with its `=` padding stripped). + @Test(arguments: ["a", "ab", "abc", "abcd", "abcde"]) + func decodesAcrossPaddingLengths(ns: String) { + #expect(JWT.claims(from: makeJWT(ns: ns))?.ns == ns) + } + + /// `???` encodes to a base64 block containing `/`, `>>>` to one + /// containing `+` — both must round-trip through the url-safe alphabet. + @Test(arguments: ["???", ">>>"]) + func decodesURLSafeAlphabet(ns: String) { + #expect(JWT.claims(from: makeJWT(ns: ns))?.ns == ns) + } + + @Test(arguments: [ + "", + "garbage", + "only.one-real-segment", + "a.!!!.c", // invalid base64 characters + "a.b.c", // payload length 1 (mod 4) is not valid base64 + "a..c", // empty payload + ]) + func garbageYieldsNil(token: String) { + #expect(JWT.claims(from: token) == nil) + } + + @Test func nonJSONPayloadYieldsNil() { + let token = "h.\(base64URLEncode(Data("hello".utf8))).s" + #expect(JWT.claims(from: token) == nil) + } + + @Test func payloadWithoutRequiredClaimsYieldsNil() { + let token = "h.\(base64URLEncode(Data("{\"exp\":123}".utf8))).s" + #expect(JWT.claims(from: token) == nil) + } + + /// A hostile out-of-range `exp` must not trap `Int(_:)`. + @Test func absurdExpIsDropped() { + let payload = "{\"uid\":1,\"ns\":\"default\",\"exp\":1e300}" + let token = "h.\(base64URLEncode(Data(payload.utf8))).s" + #expect(JWT.claims(from: token) == JWTClaims(uid: 1, ns: "default", exp: nil)) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/MultipartEncoderTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/MultipartEncoderTests.swift new file mode 100644 index 00000000..e4fb4b44 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/MultipartEncoderTests.swift @@ -0,0 +1,60 @@ +import Foundation +import HapiClient +import Testing + +@Suite("MultipartFormData") +struct MultipartEncoderTests { + @Test func encodesFieldsAndOneFilePart() { + var form = MultipartFormData(boundary: "B") + form.appendField(name: "provider", value: "openai") + form.appendField(name: "mode", value: "standard") + form.appendFile( + fieldName: "file", + filename: "clip.m4a", + mimeType: "audio/mp4", + data: Data([0x01, 0x02]) + ) + + var expected = Data( + ( + "--B\r\n" + + "Content-Disposition: form-data; name=\"provider\"\r\n\r\n" + + "openai\r\n" + + "--B\r\n" + + "Content-Disposition: form-data; name=\"mode\"\r\n\r\n" + + "standard\r\n" + + "--B\r\n" + + "Content-Disposition: form-data; name=\"file\"; filename=\"clip.m4a\"\r\n" + + "Content-Type: audio/mp4\r\n\r\n" + ).utf8 + ) + expected.append(Data([0x01, 0x02])) + expected.append(Data("\r\n--B--\r\n".utf8)) + + #expect(form.contentType == "multipart/form-data; boundary=B") + #expect(form.encodedBody() == expected) + } + + @Test func encodingDoesNotConsumeTheBuilder() { + var form = MultipartFormData(boundary: "B") + form.appendField(name: "a", value: "1") + let first = form.encodedBody() + #expect(form.encodedBody() == first) + } + + @Test func sanitizesQuotesAndCRLFInHeaderValues() { + var form = MultipartFormData(boundary: "B") + form.appendFile( + fieldName: "file", + filename: "we\"ird\r\nname.m4a", + mimeType: "audio/mp4", + data: Data() + ) + let body = String(decoding: form.encodedBody(), as: UTF8.self) + #expect(body.contains("filename=\"we%22irdname.m4a\"")) + } + + @Test func generatedBoundariesAreUnique() { + #expect(MultipartFormData.makeBoundary() != MultipartFormData.makeBoundary()) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/TestSupport.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/TestSupport.swift new file mode 100644 index 00000000..3b02e503 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/TestSupport.swift @@ -0,0 +1,127 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +// MARK: - JWT construction + +func base64URLEncode(_ data: Data) -> String { + data.base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") +} + +/// A well-formed (unsigned) JWT with the hub's payload shape. +func makeJWT(uid: Int = 1, ns: String = "default", exp: Int? = nil) -> String { + var fields = ["\"uid\":\(uid)", "\"ns\":\"\(ns)\""] + if let exp { + fields.append("\"exp\":\(exp)") + } + let payload = "{\(fields.joined(separator: ","))}" + return "eyJhbGciOiJIUzI1NiJ9.\(base64URLEncode(Data(payload.utf8))).c2ln" +} + +// MARK: - Error capture + +/// Runs `body` and returns the error it threw, or `nil` when it succeeded. +func capturedError(_ body: () async throws -> T) async -> (any Error)? { + do { + _ = try await body() + return nil + } catch { + return error + } +} + +// MARK: - Scripted HTTP performer + +/// Records every request and answers from a FIFO of stubbed responses +/// (falling back to a configurable default when the queue is empty). +actor RecordingPerformer: HTTPPerforming { + struct Stub: Sendable { + var status: Int = 200 + var body: Data = Data("{}".utf8) + var headers: [String: String] = [:] + } + + private(set) var requests: [URLRequest] = [] + private var queue: [Stub] = [] + private var fallback = Stub() + private var delayNanoseconds: UInt64 = 0 + + func enqueue(status: Int = 200, json: String = "{}", headers: [String: String] = [:]) { + queue.append(Stub(status: status, body: Data(json.utf8), headers: headers)) + } + + func setFallback(status: Int, json: String) { + fallback = Stub(status: status, body: Data(json.utf8)) + } + + /// Delay before answering — lets concurrent callers pile up on one + /// in-flight exchange. + func setDelay(nanoseconds: UInt64) { + delayNanoseconds = nanoseconds + } + + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + requests.append(request) + if delayNanoseconds > 0 { + try await Task.sleep(nanoseconds: delayNanoseconds) + } + let stub = queue.isEmpty ? fallback : queue.removeFirst() + guard let url = request.url, + let response = HTTPURLResponse( + url: url, + statusCode: stub.status, + httpVersion: "HTTP/1.1", + headerFields: stub.headers + ) else { + throw URLError(.badURL) + } + return (stub.body, response) + } +} + +// MARK: - Wiring + +let testHubURLString = "https://hub.test" +let testEpochSeconds = 1_700_000_000 +let testNow = Date(timeIntervalSince1970: TimeInterval(testEpochSeconds)) + +struct Harness { + let baseURL: URL + let performer: RecordingPerformer + let store: InMemoryCredentialStore + let auth: AuthManager + let client: APIClient +} + +/// Builds the full client stack against a `RecordingPerformer`. +/// `jwt` (when given) is persisted in the credential record, which is how +/// `AuthManager` picks up an initial token. +func makeHarness( + paired: Bool = true, + accessToken: String = "access-token", + jwt: String? = nil, + now: Date = testNow +) throws -> Harness { + let baseURL = try #require(URL(string: testHubURLString)) + let performer = RecordingPerformer() + let store = InMemoryCredentialStore() + if paired { + try store.store(HubCredentials(hubUrl: testHubURLString, accessToken: accessToken, jwt: jwt)) + } + let auth = AuthManager(baseURL: baseURL, credentialStore: store, performer: performer, now: { now }) + let client = APIClient(baseURL: baseURL, authManager: auth, performer: performer) + return Harness(baseURL: baseURL, performer: performer, store: store, auth: auth, client: client) +} + +/// A JWT that will not expire during a test. +func freshJWT(ns: String = "default") -> String { + makeJWT(ns: ns, exp: testEpochSeconds + 4 * 3600) +} + +func authResponseJSON(token: String) -> String { + "{\"token\":\"\(token)\",\"user\":{\"id\":1}}" +} diff --git a/ios/README.md b/ios/README.md index 3a101378..c0aadc24 100644 --- a/ios/README.md +++ b/ios/README.md @@ -47,8 +47,29 @@ ios/ The chat pipeline + message window logic (ported from web/src/chat/**) land in M2, validated against shared/fixtures/**. - HapiClient Transport layer: APIClient, AuthManager (single-flight - refresh), SSEClient, @Observable stores, snapshots. + HapiClient Transport layer. As of M1b: + APIClient typed REST client (Endpoints/*): + Bearer auth, 401 -> refresh -> + retry-once, {error, code} parsing + (APIError), 256 MB URLCache for + generated images. HTTP goes through + the HTTPPerforming seam, so tests + inject a recording performer. + Auth/ JWT payload decoding, AuthManager + (actor; single-flight refresh via + POST /api/auth, proactive refresh + 10 min before exp, terminal + authFailed state), Keychain + credential store (per-hub records + under run.hapi.companion), + HubRegistry (multi-hub + active + hub in UserDefaults). + MultipartEncoder for the voice-transcription + endpoint (M4c). + SSEClient (M1c), @Observable stores and snapshots + (M2) land next; feature endpoints (git/files, + scratchlist, voice, usage) join Endpoints/ with + their feature packages. ``` The app target stays thin; features live in `HapiKit` so they are testable