Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/App/AppEnvironment.swift3// Description: Dependency container of the app: server, API client, auth, cache, stores. Built once at launch and injected through the SwiftUI environment.4import SwiftUI5import Network6import SPChatCore78/// What the process was asked to do at launch. Overrides exist for development and automated tests only:9/// a non-production server must be a loopback address, and a session can be injected only in DEBUG builds.10struct LaunchOptions {11 var server: ServerConfiguration = .production12 var dataDirectory: URL?13 var injectedSessionCookie: String?14 var inMemory = false15 var isUITest = false16 var isHostedTest = false17 /// Hosted tests only: let the sync coordinator run on the scripted transport.18 var forceSync = false19 /// DEBUG only: text sent automatically in a new conversation at launch (visual checks without synthetic input).20 var autoSend: String?21 /// DEBUG only: conversation opened at launch.22 var autoOpen: String?23 /// DEBUG only: launch states for visual checks (see Scripts/run-dev.sh).24 var debug: [String: String] = [:]2526 static func current(arguments: [String] = ProcessInfo.processInfo.arguments, environment: [String: String] = ProcessInfo.processInfo.environment) -> LaunchOptions {27 var o = LaunchOptions()28 func value(_ flag: String) -> String? { arguments.firstIndex(of: flag).flatMap { arguments.indices.contains($0 + 1) ? arguments[$0 + 1] : nil } }29 #if DEBUG30 if let s = value("-SPChatServer") ?? environment["SPCHAT_SERVER"], let url = URL(string: s), let cfg = ServerConfiguration(url: url), cfg.host == "localhost" || cfg.host == "127.0.0.1" { o.server = cfg }31 o.injectedSessionCookie = environment["SPCHAT_SESSION_COOKIE"]32 o.isUITest = arguments.contains("-SPChatUITest")33 o.autoSend = value("-SPChatAutoSend"); o.autoOpen = value("-SPChatOpen")34 for key in ["Model", "Draft", "Section", "Panel", "Settings", "Appearance", "ExplorerModel", "Window", "Arena", "Lens"] { if let v = value("-SPChat" + key) { o.debug[key] = v } }35 for flag in ["Web", "Palette", "ShowModelPicker"] where arguments.contains("-SPChat" + flag) { o.debug[flag] = "1" }36 #endif37 if let d = value("-SPChatDataDir") { o.dataDirectory = URL(fileURLWithPath: (d as NSString).expandingTildeInPath, isDirectory: true) }38 o.inMemory = arguments.contains("-SPChatInMemory")39 // hosting unit tests: the app process must not open the production UI, the Keychain or the network on its own40 if environment["XCTestConfigurationFilePath"] != nil, !o.isUITest { o.isHostedTest = true; o.inMemory = true }41 return o42 }43}4445/// Network reachability (NWPathMonitor). Used to explain failures and to wait before reconnecting — never to block a request.46@Observable final class Connectivity {47 private(set) var isOnline = true48 @ObservationIgnored private let monitor = NWPathMonitor()49 @ObservationIgnored nonisolated private let flag = OnlineFlag()5051 init() {52 let flag = flag53 monitor.pathUpdateHandler = { [weak self] path in54 let online = path.status == .satisfied55 flag.set(online)56 Task { @MainActor in self?.isOnline = online }57 }58 monitor.start(queue: DispatchQueue(label: "ai.spboucher.spchat.connectivity"))59 }60 deinit { monitor.cancel() }61 /// Thread-safe snapshot for the streaming engine.62 nonisolated var probe: @Sendable () -> Bool { let flag = flag; return { flag.value } }63}6465nonisolated final class OnlineFlag: @unchecked Sendable {66 private let lock = NSLock(); private var online = true67 init() {}68 func set(_ v: Bool) { lock.withLock { online = v } }69 var value: Bool { lock.withLock { online } }70}7172@Observable final class AppEnvironment {73 let options: LaunchOptions74 let server: ServerConfiguration75 let api: APIClient76 let auth: AuthService77 let cache: CacheStore?78 let engine: GenerationEngine79 let preferences: Preferences80 let connectivity: Connectivity81 let toasts = ToastCenter()82 let session: SessionStore83 let conversations: ConversationStore84 let catalog: CatalogStore85 let files: AttachmentService86 /// Drafts typed while the server was unreachable (kept locally, pushed when back online).87 let outbox: DraftOutbox88 /// Sync feed: keeps every store in step with the web and iOS apps.89 let sync: SyncCoordinator90 @ObservationIgnored private var chats: [String: ChatViewModel] = [:]91 @ObservationIgnored var started = false92 let notifications = CompletionNotifier()93 /// Text handed to the next "new conversation" composer (deep link, quick chat, prompt library). Never sent automatically.94 var pendingComposerText: String?95 /// Files handed to the next conversation composer (dropped on the Dock icon, « Ouvrir avec »).96 var pendingFiles: [URL] = []97 /// Tab the Settings window shows (palette, menus).98 var settingsTab: SettingsTab = .general99 /// Conversation that windows should bring to front (deep link, notification, search result).100 var navigationRequest: NavigationRequest?101102 struct NavigationRequest: Equatable { let id = UUID(); let conversationId: String; var messageId: String? }103104 /// `transport` and `authenticator` are replaced in tests; production uses URLSession and AuthenticationServices.105 init(options: LaunchOptions = .current(), transport: HTTPTransport? = nil, authenticator: PasskeyAuthenticator? = nil) {106 self.options = options107 server = options.server108 let serviceName = Bundle.main.bundleIdentifier ?? "ai.spboucher.spchat"109 let secrets: SecretStore = options.inMemory || options.isUITest ? InMemorySecretStore() : KeychainStore(service: serviceName)110 let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0"111 let os = ProcessInfo.processInfo.operatingSystemVersion112 api = APIClient(server: server, transport: transport ?? URLSessionTransport(), secrets: secrets, userAgent: "SPChat/\(version) (Macintosh; Mac OS X \(os.majorVersion).\(os.minorVersion)) native")113 if let cookie = options.injectedSessionCookie { api.cookies.ingest(setCookie: cookie + "; Path=/; Max-Age=86400") }114 auth = AuthService(api: api, authenticator: authenticator ?? SystemPasskeyAuthenticator())115116 let base = options.dataDirectory ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("SPChat", isDirectory: true)117 let dbURL: URL? = options.inMemory ? nil : base.appendingPathComponent("cache-\(server.host).sqlite")118 cache = try? CacheStore(url: dbURL)119 // transient runs (tests, -SPChatInMemory) get their own throw-away preferences domain120 let transientSuite = "ai.spboucher.spchat.transient.\(UUID().uuidString)"121 preferences = Preferences(defaults: options.isUITest || options.inMemory ? (UserDefaults(suiteName: transientSuite) ?? .standard) : .standard)122 if options.isUITest || options.inMemory { UserDefaults.standard.removePersistentDomain(forName: transientSuite) }123 connectivity = Connectivity()124 engine = GenerationEngine(api: api, isOnline: connectivity.probe)125 session = SessionStore(api: api, auth: auth, cache: cache)126 conversations = ConversationStore(api: api, cache: cache, preferences: preferences)127 catalog = CatalogStore(api: api, cache: cache)128 files = AttachmentService(api: api, cacheDirectory: base.appendingPathComponent("files", isDirectory: true))129 outbox = DraftOutbox(cache: cache)130 sync = SyncCoordinator(client: SyncClient(api: api, isOnline: connectivity.probe), preferences: preferences)131 session.onSignedOut = { [weak self] in self?.resetAfterSignOut() }132 sync.attach(self)133 }134135 /// One view model per conversation, shared by every window showing it. `draftKey` identifies an unsaved new conversation.136 func chat(conversationId: String?, draftKey: String) -> ChatViewModel {137 let key = conversationId ?? "draft:" + draftKey138 if let vm = chats[key] { return vm }139 let vm = ChatViewModel(conversationId: conversationId, env: self)140 chats[key] = vm141 return vm142 }143 /// A draft became a real conversation: it is now reachable under its id.144 func adopt(_ vm: ChatViewModel, draftKey: String, conversationId: String) { chats[conversationId] = vm; chats["draft:" + draftKey] = nil }145 func forget(conversationId: String) { chats[conversationId]?.stop(notifyServer: false); chats[conversationId] = nil }146 func existingChat(_ conversationId: String) -> ChatViewModel? { chats[conversationId] }147 /// Every conversation view model currently alive (open in a window, or streaming).148 var liveChats: [ChatViewModel] { Array(Set(chats.values.map(ObjectIdentifier.init)).compactMap { id in chats.values.first { ObjectIdentifier($0) == id } }) }149 var streamingConversationIds: Set<String> { Set(chats.values.filter(\.isStreaming).compactMap(\.conversationId)) }150151 private func resetAfterSignOut() {152 for vm in chats.values { vm.stop(notifyServer: false) }153 chats.removeAll(); conversations.reset(); catalog.reset(); files.purge(); sync.stop(resetCursor: true)154 }155156 /// Tells the owner an answer is ready when the app is in the background (only if enabled in Settings).157 func notifyCompletion(of chat: ChatViewModel, message: Message) {158 guard preferences.notifyOnCompletion, !NSApp.isActive, let id = chat.conversationId else { return }159 notifications.post(title: chat.title, body: String(message.visibleText.prefix(180)), conversationId: id)160 }161162 func open(conversationId: String, messageId: String? = nil) { navigationRequest = NavigationRequest(conversationId: conversationId, messageId: messageId) }163}164