Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteCore/AppSession.swift10// Module : ClaudeRemoteCore11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AuthenticationServices89import ClaudeRemoteAPI90import ClaudeRemoteAuth91import ClaudeRemoteModels92import Foundation93import Observation9495/// Everything an app target chooses when it boots the shared core.96public struct AppSessionConfiguration: Sendable {97 public var client: ClientInfo98 public var device: DeviceDescriptor99 /// Debug builds use the `.dev` bundle id suffix: separate Keychain service and push topic.100 public var isDebugBuild: Bool101 /// Override of `profile.baseURL` (dev stack on `http://localhost:8625`, tests).102 public var baseURL: URL?103 /// App Group shared with the widget extension (summary cache). Nil = no cache.104 public var appGroup: String?105 /// Window for the passkey sheet.106 public var passkeyAnchor: @MainActor @Sendable () -> ASPresentationAnchor?107 public var apnsEnvironment: APNsEnvironment108109 // Dependency overrides (tests, previews). Nil = production implementation.110 public var keychain: (any KeychainStoring)?111 public var keychainAccessGroup: String?112 public var deviceKeys: (any DeviceKeyStore)?113 public var passkeys: (any PasskeyAuthenticator)?114 public var localAuth: (any LocalAuthenticating)?115 public var urlSessionConfiguration: URLSessionConfiguration?116 public var webSocketTransport: (any WebSocketTransport)?117 public var sleeper: (any Sleeper)?118 public var network: (any NetworkPathMonitoring)?119 public var notifications: (any UserNotificationPosting)?120 public var summaryCache: SharedSummaryCache?121 /// Suite for non-secret preferences (app lock switch, recent projects).122 public var defaultsSuiteName: String?123124 public init(client: ClientInfo, device: DeviceDescriptor, isDebugBuild: Bool = false, baseURL: URL? = nil, appGroup: String? = nil,125 apnsEnvironment: APNsEnvironment = .production, passkeyAnchor: @escaping @MainActor @Sendable () -> ASPresentationAnchor?) {126 self.client = client127 self.device = device128 self.isDebugBuild = isDebugBuild129 self.baseURL = baseURL130 self.appGroup = appGroup131 self.apnsEnvironment = apnsEnvironment132 self.passkeyAnchor = passkeyAnchor133 }134}135136/// Root object of an app: the auth state machine plus every store, wired to one `APIClient` and137/// one `EventStream`. Create one per product (`AgentProfile.claude` or `.codex`), inject it in the138/// SwiftUI environment, and call `start()` once.139///140/// @State private var session = try! AppSession(profile: .claude, configuration: config)141/// ContentView().environment(session).task { await session.start() }142@MainActor143@Observable144public final class AppSession {145 public nonisolated let profile: AgentProfile146 public nonisolated let client: APIClient147 public nonisolated let auth: AuthService148 public nonisolated let router: DeepLinkRouter149150 /// Server authentication state; drives the root view (sign-in / second factor / app).151 public private(set) var authState: AuthState = .unknown152 /// The route requested by a deep link or a notification, consumed by the UI (`takePendingRoute`).153 public private(set) var pendingRoute: Route?154155 public let events: EventStream156 public let sessions: SessionsStore157 public let projects: ProjectsStore158 public let tasks: TasksStore159 public let cluster: ClusterStore160 public let skillsMCP: SkillsMCPStore161 public let system: SystemStore162 public let notifications: NotificationsStore163 public let settings: SettingsStore164 public let summary: SummaryStore165 public let lock: BiometricLock166 public let notifier: LocalNotifier167 public let push: PushRegistrar168169 /// Live link state (the `/events` stream) and its measured latency.170 public var connection: ConnectionState { events.state }171 public var latencyMs: Int? { events.latencyMs }172 public var isSignedIn: Bool { authState.isSignedIn }173 /// Signed-in user name, when known.174 public var username: String? { if case .signedIn(let info) = authState { info.username } else { nil } }175176 @ObservationIgnored private var fileStores: [String: FilesStore] = [:]177 @ObservationIgnored private var observer: Task<Void, Never>?178 @ObservationIgnored private var started = false179 @ObservationIgnored private var isActive = true180181 /// - Throws: `APIError` (`insecure_url`) when the base URL is not HTTPS (localhost excepted).182 public init(profile: AgentProfile, configuration c: AppSessionConfiguration) throws {183 let profile = c.baseURL.map(profile.with(baseURL:)) ?? profile184 self.profile = profile185 let client = try APIClient(baseURL: profile.baseURL, client: c.client, configuration: c.urlSessionConfiguration ?? .crAPI,186 webSocketTransport: c.webSocketTransport)187 self.client = client188 let keychain = c.keychain ?? SystemKeychain(service: CredentialStore.service(for: profile, debug: c.isDebugBuild), accessGroup: c.keychainAccessGroup)189 let localAuth = c.localAuth ?? SystemLocalAuthenticator()190 auth = AuthService(191 profile: profile, client: client,192 credentials: CredentialStore(keychain: keychain, scope: profile.baseURL.host() ?? "default"),193 deviceKeys: c.deviceKeys ?? KeychainDeviceKeyStore(keychain: keychain),194 passkeys: c.passkeys ?? SystemPasskeyAuthenticator(anchor: c.passkeyAnchor),195 localAuth: localAuth, device: c.device)196 router = DeepLinkRouter(profile: profile)197 let defaults = c.defaultsSuiteName.flatMap(UserDefaults.init(suiteName:)) ?? .standard198 let sleeper = c.sleeper ?? SystemSleeper()199 events = EventStream(client: client, sleeper: sleeper, network: c.network ?? SystemNetworkMonitor())200 sessions = SessionsStore(client: client)201 projects = ProjectsStore(client: client, shortcuts: ProjectShortcuts(defaults: defaults, scope: profile.id.rawValue))202 tasks = TasksStore(client: client, sleeper: sleeper)203 cluster = ClusterStore(client: client)204 skillsMCP = SkillsMCPStore(client: client)205 system = SystemStore(client: client)206 notifications = NotificationsStore(client: client)207 settings = SettingsStore(client: client)208 let cache = c.summaryCache ?? c.appGroup.flatMap { SharedSummaryCache(appGroup: $0, agent: profile.id) }209 summary = SummaryStore(client: client, profile: profile, cache: cache)210 lock = BiometricLock(authenticator: localAuth, defaults: defaults)211 notifier = LocalNotifier(center: c.notifications ?? SystemUserNotifications())212 push = PushRegistrar(client: client, topic: profile.pushTopic(debug: c.isDebugBuild), environment: c.apnsEnvironment)213 wire()214 }215216 private func wire() {217 events.onEvent { [weak self] event in218 guard let self else { return }219 self.sessions.apply(event)220 self.projects.apply(event)221 self.tasks.apply(event)222 self.notifications.apply(event)223 self.summary.apply(event)224 }225 events.onResync { [weak self] in await self?.refreshLiveData() }226 events.onUnauthorized = { [weak self] in await self?.auth.sessionExpiredRemotely() }227 notifications.onArrival = { [weak self] notification in228 guard let self else { return }229 self.notifier.isEnabled = self.settings.settings.notifications.inApp230 Task { await self.notifier.post(notification) }231 }232 }233234 // MARK: Lifecycle235236 /// Restores the stored session and starts following the auth state. Call once at launch.237 public func start() async {238 guard !started else { return }239 started = true240 let updates = await auth.updates()241 observer = Task { [weak self] in242 for await update in updates { await self?.apply(update) }243 }244 await auth.restore()245 await syncAuthState()246 }247248 @ObservationIgnored private var appliedVersion = -1249250 private func syncAuthState() async { await apply(await auth.snapshot) }251252 /// Applies an auth state unless a newer one was already applied (the stream and the253 /// sign-in wrappers both deliver).254 private func apply(_ update: AuthStateUpdate) async {255 guard update.version > appliedVersion else { return }256 appliedVersion = update.version257 let state = update.state258 guard state != authState else { return }259 let wasSignedIn = authState.isSignedIn260 authState = state261 if state.isSignedIn, !wasSignedIn {262 if isActive { events.start() }263 // Initial loads run on their own: a sign-in never waits for them, and a later auth264 // change (revocation during a slow load) is not held back.265 Task { [weak self] in266 await self?.push.registerPendingToken()267 await self?.refreshLiveData()268 await self?.settings.refresh()269 }270 } else if !state.isSignedIn, wasSignedIn {271 clearUserData()272 }273 }274275 private func refreshLiveData() async {276 async let a: Void = sessions.refresh()277 async let b: Void = tasks.refresh()278 async let c: Void = notifications.refresh()279 async let d: Void = summary.refresh()280 async let e: Void = projects.refresh()281 _ = await (a, b, c, d, e)282 }283284 private func clearUserData() {285 events.stop()286 sessions.reset(); projects.reset(); tasks.reset(); cluster.reset(); skillsMCP.reset()287 system.reset(); notifications.reset(); settings.reset(); summary.reset(); push.reset()288 fileStores = [:]289 pendingRoute = nil290 }291292 /// Scene became active: unlock check, reconnect at once, refresh counters.293 public func appDidBecomeActive() {294 isActive = true295 lock.appWillEnterForeground()296 guard isSignedIn else { return }297 events.resume()298 Task { await summary.refresh() }299 }300301 /// Scene went to the background: the event socket is closed (iOS suspends it anyway).302 public func appDidEnterBackground() {303 isActive = false304 lock.appDidEnterBackground()305 events.pause()306 }307308 // MARK: Sign-in (thin wrappers; errors are `APIError`, `PasskeyError`, `AuthFlowError`)309310 /// Runs an auth step, then publishes the resulting state (also when the step threw: a failed311 /// second factor can end the pending sign-in).312 private func step(_ body: () async throws -> Void) async rethrows {313 do {314 try await body()315 } catch {316 await syncAuthState()317 throw error318 }319 await syncAuthState()320 }321322 public func signIn(username: String, password: String, totp: String? = nil) async throws {323 try await step { _ = try await auth.signIn(username: username, password: password, totp: totp) }324 }325 public func submitTOTP(code: String) async throws { try await step { _ = try await auth.submitTOTP(code: code) } }326 public func completeSecondFactorWithPasskey() async throws { try await step { _ = try await auth.completeSecondFactorWithPasskey() } }327 /// Passkey-only sign-in (same passkey as the website).328 public func signInWithPasskey() async throws { try await step { _ = try await auth.signInWithPasskey() } }329 public func cancelSignIn() async { await step { await auth.cancelSignIn() } }330 public func startTOTPEnrollment() async throws -> TotpEnrollStart { try await auth.startTOTPEnrollment() }331 public func finishTOTPEnrollment(code: String) async throws { try await step { _ = try await auth.finishTOTPEnrollment(code: code) } }332 public func registerPasskey(label: String? = nil) async throws { try await step { _ = try await auth.registerPasskey(label: label) } }333334 public func signOut() async { await step { await auth.signOut() } }335336 /// Local wipe: credential, device key, install id, caches and preferences of this product.337 public func wipeLocalData() async {338 await step { await auth.wipeLocalData() }339 lock.isEnabled = false340 }341342 /// Face ID / Touch ID / passcode gate before a destructive action.343 /// - Throws: `LocalAuthError`.344 public func reauthenticate(reason: String) async throws { try await auth.reauthenticate(reason: reason) }345346 // MARK: Per-project files347348 /// The files store of a project (created on first use, kept while signed in).349 public func files(for projectId: String) -> FilesStore {350 if let store = fileStores[projectId] { return store }351 let store = FilesStore(client: client, projectId: projectId)352 fileStores[projectId] = store353 return store354 }355356 // MARK: Deep links357358 /// Handles `clauderemote://…`, `codexremote://…`, universal links and notification links.359 /// Returns the route (also kept in `pendingRoute` until the UI takes it).360 @discardableResult361 public func open(url: URL) -> Route? {362 guard let route = router.route(for: url) else { return nil }363 pendingRoute = route364 return route365 }366367 @discardableResult368 public func open(notificationUserInfo userInfo: [AnyHashable: Any]) -> Route? {369 guard let route = router.route(forNotificationUserInfo: userInfo) else { return nil }370 pendingRoute = route371 return route372 }373374 @discardableResult375 public func open(_ notification: ServerNotification) -> Route? {376 guard let route = notification.link.flatMap(router.route(forWebPath:)) else { return nil }377 pendingRoute = route378 return route379 }380381 /// Returns and clears the pending route (call once signed in and unlocked).382 public func takePendingRoute() -> Route? {383 defer { pendingRoute = nil }384 return pendingRoute385 }386}387