Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/App/AppEnvironment.swift4// Description: Dependency container: builds the services once and injects them into the SwiftUI environment.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation11import Observation12import SwiftUI13import UserNotifications1415/// Navigation state shared by the iPhone stack and the iPad split view.16@MainActor17@Observable18final class AppRouter {19 enum Sheet: String, Identifiable { case settings, search, prompts, commandCenter, explorer, arena, constellation, projects, research, images; var id: String { rawValue } }20 /// The session on screen (a conversation, or a new draft).21 var current: ChatSession?22 var sheet: Sheet?23 /// Text handed over by a deep link, a shortcut or a drop, waiting to be placed in the composer.24 var pendingComposerText: String?25 /// Asks the composer to take keyboard focus (⌘N, "new conversation").26 var focusComposerToken = 027 /// A contextual panel to open on the conversation on screen (`timeline`, `branches`, `context`, `lens`, `models`): set by the command center and deep links.28 var pendingPanel: String?29 /// Prompt handed to the Arena when it is opened from a conversation or the command center.30 var arenaSeed: ArenaSeed?31 /// Models preselected for the next Arena (from the Explorer's comparison).32 var arenaModelIds: [String] = []33 /// Bumped per entity by the sync feed (`prompt`, `provider`, `memory`…): open screens reload when their tick changes.34 private(set) var syncTicks: [String: Int] = [:]35 func tick(_ entity: String) -> Int { syncTicks[entity, default: 0] }36 func bump(_ entity: String) { syncTicks[entity, default: 0] += 1 }37}3839struct ArenaSeed: Equatable, Sendable { var prompt: String = ""; var conversationId: String?; var projectId: String? }4041@MainActor42@Observable43final class AppEnvironment {44 let configuration: AppConfiguration45 let http: HTTPClient46 let api: ChatAPI47 let store: LocalStore48 let auth: AuthStore49 let network: NetworkMonitor50 let preferences: Preferences51 let catalog: ModelCatalog52 let conversations: ConversationListStore53 let appLock: AppLock54 let router = AppRouter()55 let files: AttachmentCache56 let haptics: Haptics57 let speech: SpeechPlayer58 let settings: AccountSettings59 let prompts: PromptStore60 let sync: SyncEngine6162 @ObservationIgnored private var sessions: [String: ChatSession] = [:]63 @ObservationIgnored private var recency: [String] = []64 @ObservationIgnored private var isFlushingOutbox = false65 /// Number of messages waiting in the outbox (badge in the list).66 private(set) var outboxCount = 06768 init(configuration: AppConfiguration, tokens: SessionTokenStore? = nil, storeDirectory: URL? = AppEnvironment.defaultStoreDirectory, defaults: UserDefaults = .standard, protocolClasses: [AnyClass]? = nil) {69 self.configuration = configuration70 let tokens = tokens ?? KeychainSessionTokenStore(origin: configuration.origin)71 http = HTTPClient(configuration: configuration, tokens: tokens, protocolClasses: protocolClasses)72 api = ChatAPI(http: http)73 // a cache that cannot be opened must never prevent the app from working online74 store = (try? LocalStore(directory: storeDirectory)) ?? (try! LocalStore(directory: nil))75 network = NetworkMonitor()76 preferences = Preferences(defaults: defaults)77 appLock = AppLock(defaults: defaults)78 catalog = ModelCatalog(api: api, store: store)79 conversations = ConversationListStore(api: api, store: store)80 files = AttachmentCache(api: api, directory: storeDirectory?.appendingPathComponent("files", isDirectory: true))81 haptics = Haptics(preferences: preferences)82 speech = SpeechPlayer(api: api)83 settings = AccountSettings(api: api, store: store)84 prompts = PromptStore(api: api, store: store)85 sync = SyncEngine(api: api, store: store, waitUntilOnline: { [network] in await network.waitUntilOnline() })86 auth = AuthStore(http: http, api: api, passkeys: PasskeyService(http: http, relyingParty: configuration.relyingParty), hasStoredSession: tokens.load() != nil)87 auth.onSignedOut = { [weak self] in await self?.wipeLocalData() }88 auth.onSignedIn = { [weak self] in self?.appLock.enableByDefaultAfterSignIn(); await self?.didSignIn() }89 conversations.onDeleted = { [weak self] id in self?.forgetSession(id) }90 sync.onPlan = { [weak self] plan in await self?.apply(plan) }91 }9293 static var defaultStoreDirectory: URL? {94 FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("SPChat", isDirectory: true)95 }9697 /// One-time wiring after launch.98 func start() async {99 let flag = network.offlineFlag100 await http.setOfflineProbe { flag.withLock { $0 } }101 await auth.installHandlers()102 if auth.phase == .signedIn { await didSignIn() }103 }104105 private func didSignIn() async {106 await catalog.loadCached()107 await settings.loadCached()108 if router.current == nil { router.current = newSession() }109 async let a: Void = conversations.refresh()110 async let b: Void = catalog.refresh()111 async let c: Void = settings.refresh()112 async let d: Void = prompts.refresh()113 _ = await (a, b, c, d)114 await flushOutbox()115 startSync()116 }117118 /// Options of the next message: the device's choices, the model resolved against the catalogue, the tool subset.119 var sendOptions: SendOptions {120 var o = preferences.sendOptions(tools: settings.tools)121 o.modelId = catalog.effectiveModelId(preferred: preferences.modelId)122 return o123 }124125 /// Selects a model for the next messages (manual routing, no preset).126 func select(model id: String) {127 preferences.routingMode = .manual; preferences.presetId = nil; preferences.modelId = id128 // an effort the new model does not list would be reported as ignored on every answer: drop it now129 if let e = preferences.effort, let levels = catalog.model(id)?.effortLevels, !levels.isEmpty, !levels.contains(e.rawValue) { preferences.effort = nil }130 }131132 // MARK: sessions133134 private var dependencies: ChatSessionDependencies {135 ChatSessionDependencies(136 api: api, store: store,137 isOnline: { [network] in network.isOnline },138 waitUntilOnline: { [network] in await network.waitUntilOnline() },139 conversationsChanged: { [weak self] in await self?.conversations.refresh(); await self?.refreshOutboxCount() },140 sessionAdopted: { [weak self] session, id in self?.sessions[id] = session; self?.touch(id) },141 turnFinished: { [weak self] conversationId, title, message in self?.turnFinished(conversationId: conversationId, title: title, message: message) })142 }143144 /// The session of a conversation (one instance per conversation, so a stream keeps running while the user browses).145 func session(for conversationId: String) -> ChatSession {146 if let s = sessions[conversationId] { touch(conversationId); return s }147 let s = ChatSession(conversationId: conversationId, dependencies: dependencies)148 sessions[conversationId] = s; touch(conversationId)149 return s150 }151152 func newSession(projectId: String? = nil) -> ChatSession { ChatSession(conversationId: nil, projectId: projectId, dependencies: dependencies) }153154 func open(_ conversationId: String) { router.current = session(for: conversationId) }155 func startNewConversation(projectId: String? = nil, text: String? = nil) {156 let s = newSession(projectId: projectId)157 if let text, !text.isEmpty { s.composerText = text }158 router.current = s159 router.focusComposerToken += 1160 }161162 private func touch(_ id: String) {163 recency.removeAll { $0 == id }; recency.append(id)164 // idle sessions beyond the most recent 12 are released (their data stays in the cache)165 while recency.count > 12, let victim = recency.first(where: { sessions[$0]?.isBusy != true && router.current?.conversationId != $0 }) {166 recency.removeAll { $0 == victim }; sessions[victim]?.detach(); sessions[victim] = nil167 }168 }169170 private func forgetSession(_ id: String) {171 sessions[id]?.detach(); sessions[id] = nil; recency.removeAll { $0 == id }172 if router.current?.conversationId == id { router.current = newSession() }173 }174175 // MARK: sync176177 /// Foreground / reconnection: refresh the list and the open conversation, then post what waited offline.178 func synchronize() async {179 guard auth.phase == .signedIn else { return }180 // the pull says what changed while the app was away; without a cursor (or without an answer) refresh the essentials181 let plan = await sync.pull()182 if plan == nil || sync.cursor == nil || plan?.isEmpty == true {183 await conversations.refresh()184 await router.current?.resume()185 }186 if catalog.models.isEmpty { await catalog.refresh() }187 await router.current?.pushUnsentDraft()188 await flushOutbox()189 startSync()190 }191192 /// The live feed runs only while the app is active and signed in.193 func startSync() { if auth.phase == .signedIn, UIApplication.shared.applicationState != .background { sync.start() } }194 func stopSync() { sync.stop() }195196 /// Re-reads what a batch of sync events says has changed. Stores keep their own "apply after the server" rules.197 func apply(_ plan: SyncPlan) async {198 guard auth.phase == .signedIn else { return }199 for id in plan.deletedConversations { conversations.removeLocally(id); forgetSession(id) }200 if plan.conversationList { await conversations.refresh() }201 if plan.openConversation || plan.everything, let current = router.current, current.conversationId != nil, !current.isBusy {202 // another device wrote in the conversation on screen (or this one just finished: the reload is then a no-op)203 if plan.everything || plan.conversations.isEmpty || plan.conversations.contains(current.conversationId ?? "") { await current.load() }204 }205 for scope in plan.drafts { await router.current?.draftChangedOnServer(scope: scope) }206 if plan.models { await catalog.refreshModels() }207 if plan.catalogData { await catalog.refreshPresetsAndProjects() }208 if plan.settings { await settings.refresh() }209 if plan.prompts { await prompts.refresh(); router.bump("prompt") }210 if plan.providers { router.bump("provider") }211 if plan.memory { router.bump("memory") }212 }213214 func refreshOutboxCount() async { outboxCount = await store.outbox().count }215216 /// Posts the messages written offline, oldest first, one conversation at a time. Each keeps its idempotency key:217 /// a message that did reach the server before the connection dropped is recognised and not duplicated.218 func flushOutbox() async {219 await refreshOutboxCount()220 guard preferences.autoSendOutbox, network.isOnline, auth.phase == .signedIn, !isFlushingOutbox else { return }221 isFlushingOutbox = true; defer { isFlushingOutbox = false }222 for item in await store.outbox() {223 guard network.isOnline, auth.phase == .signedIn else { break }224 let session: ChatSession225 if let id = item.conversationId { session = self.session(for: id) }226 else if let current = router.current, current.conversationId == nil, current.pending.contains(where: { $0.id == item.id }) { session = current }227 else { session = newSession(projectId: item.projectId) }228 guard !session.isBusy else { continue }229 session.sendQueued(item)230 // wait for this turn before the next one: answers must follow the order the messages were written in231 while session.isBusy { try? await Task.sleep(for: .milliseconds(250)) }232 }233 await refreshOutboxCount()234 }235236 private func turnFinished(conversationId: String?, title: String, message: ChatMessage?) {237 guard let message else { return }238 catalog.markUsed(message.modelId)239 switch message.status {240 case .complete: haptics.success()241 case .error, .incomplete: haptics.warning()242 default: break243 }244 guard preferences.notifyWhenAnswerReady, UIApplication.shared.applicationState != .active, let conversationId else { return }245 let content = UNMutableNotificationContent()246 content.title = title247 content.body = message.status == .complete ? String(message.text.prefix(180)) : String(localized: "La réponse s’est arrêtée avant la fin.")248 content.userInfo = ["conversationId": conversationId]249 content.sound = .default250 UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "answer-\(conversationId)", content: content, trigger: nil))251 }252253 // MARK: deep links254255 /// `spchat://c/<id>`, `spchat://new?text=…`, and universal links `https://chat.spboucher.ai/c/<id>`.256 func handle(url: URL) {257 guard auth.phase == .signedIn else { return }258 let parts: [String]259 if url.scheme == AppConfiguration.urlScheme { parts = ([url.host()].compactMap { $0 } + url.pathComponents.filter { $0 != "/" }) }260 else if url.host() == configuration.baseURL.host() { parts = url.pathComponents.filter { $0 != "/" } }261 else { return }262 let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems263 switch parts.first {264 case "c":265 if parts.count > 1, parts[1].range(of: #"^conv_[a-z0-9]{1,40}$"#, options: .regularExpression) != nil {266 open(parts[1])267 if let panel = query?.first(where: { $0.name == "panel" })?.value, ["timeline", "branches", "context", "lens", "models"].contains(panel) { router.pendingPanel = panel }268 }269 case "new", nil: startNewConversation(text: query?.first { $0.name == "text" }?.value.map { String($0.prefix(20_000)) })270 case "search": router.sheet = .search271 case "settings": router.sheet = .settings272 case "arena": router.arenaSeed = ArenaSeed(prompt: query?.first { $0.name == "text" }?.value ?? ""); router.sheet = .arena273 case "explorer", "models": router.sheet = .explorer274 case "constellation": router.sheet = .constellation275 case "command": router.sheet = .commandCenter276 case "projects": router.sheet = .projects277 case "research": router.sheet = .research278 case "images": router.sheet = .images279 case "prompts": router.sheet = .prompts280 default: break281 }282 }283284 // MARK: wipe285286 /// Sign-out or revoked session: nothing of the account stays on the device — database rows (overwritten, then287 /// vacuumed), downloaded files, in-memory sessions, account-scoped preferences, pending notifications.288 func wipeLocalData() async {289 for s in sessions.values { s.detach() }290 sessions.removeAll(); recency.removeAll()291 router.current?.detach(); router.current = nil; router.sheet = nil; router.pendingComposerText = nil292 conversations.reset(); catalog.reset(); speech.stop(); settings.reset(); prompts.reset()293 await sync.reset()294 await store.wipe()295 await files.wipe()296 preferences.resetAccountScoped()297 appLock.reset()298 outboxCount = 0299 UNUserNotificationCenter.current().removeAllDeliveredNotifications()300 UNUserNotificationCenter.current().removeAllPendingNotificationRequests()301 }302}303