import Foundation import OSLog /// The on-device decision models Seer can run. enum LocalModel: String, CaseIterable, Identifiable, Sendable { case d1_2B = "d1-2B" case d1_3B = "d1-3B" var id: String { rawValue } /// The model the engine runs: the user's choice in Settings. static var selected: LocalModel { LocalModel(rawValue: UserDefaults.standard.string(forKey: "localModel") ?? "") ?? .d1_2B } /// Name with the Liquid AI model family it is built on. var label: String { switch self { case .d1_2B: "d1-2B (LFM3)" case .d1_3B: "d1-3B (LFM2.5)" } } var sizeLabel: String { switch self { case .d1_2B: "1.1 GB" case .d1_3B: "1.7 GB" } } /// What to expect from it, shown next to the choice. var caveat: String { switch self { case .d1_2B: "Smaller, and Liquid AI reports it decides better than d1-3B. But it reads the whole prompt in both directions, so nothing can be reused: every question re-reads the entire screen, about 3 to 5 seconds each on an M4 (a typical 3-question step takes 10 to 15 s, whether or not the screen changed)." case .d1_3B: "Larger download and reportedly less accurate than d1-2B. It reads left to right, so Seer keeps what it already read: a step on a new screen takes about 6 s on an M4, but questions about a screen it has already read take only about a second." } } var fileName: String { "\(rawValue)-Q4_K_M.gguf" } var remote: URL { URL(string: "https://huggingface.co/LiquidAI/\(rawValue)-GGUF/resolve/main/\(fileName)")! } /// Size of the published file, for progress when the server doesn't report one. var expectedBytes: Int64 { switch self { case .d1_2B: 1_099_629_888 case .d1_3B: 1_674_456_672 } } } /// Downloads and tracks the weights (Q4_K_M) of the local decision models. @MainActor final class LocalModelStore: ObservableObject { static let shared = LocalModelStore() enum State: Equatable { case missing case downloading(Double) case ready case failed(String) } @Published private(set) var states: [LocalModel: State] nonisolated static var directory: URL { FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] .appendingPathComponent("Seer/Models", isDirectory: true) } nonisolated static func modelURL(for model: LocalModel) -> URL { directory.appendingPathComponent(model.fileName) } nonisolated static func isDownloaded(_ model: LocalModel) -> Bool { FileManager.default.fileExists(atPath: modelURL(for: model).path) } private var downloaders: [LocalModel: ModelDownloader] = [:] private init() { states = Dictionary(uniqueKeysWithValues: LocalModel.allCases.map { ($0, Self.isDownloaded($0) ? .ready : .missing) }) } func state(of model: LocalModel) -> State { states[model] ?? .missing } func download(_ model: LocalModel) { guard downloaders[model] == nil, state(of: model) != .ready else { return } states[model] = .downloading(0) do { try FileManager.default.createDirectory(at: Self.directory, withIntermediateDirectories: true) } catch { states[model] = .failed(error.localizedDescription) return } let downloader = ModelDownloader( destination: Self.modelURL(for: model), expectedBytes: model.expectedBytes, onProgress: { [weak self] fraction in Task { @MainActor in if case .downloading = self?.state(of: model) { self?.states[model] = .downloading(fraction) } } }, onComplete: { [weak self] result in Task { @MainActor in self?.finish(model, result) } }) downloaders[model] = downloader downloader.start(url: model.remote) } func cancelDownload(_ model: LocalModel) { downloaders[model]?.cancel() downloaders[model] = nil states[model] = Self.isDownloaded(model) ? .ready : .missing } func delete(_ model: LocalModel) { downloaders[model]?.cancel() downloaders[model] = nil try? FileManager.default.removeItem(at: Self.modelURL(for: model)) states[model] = .missing Task { await LocalDecisionEngine.shared.unload() } } private func finish(_ model: LocalModel, _ result: Result) { // A cancelled download has already reset the state. guard downloaders[model] != nil else { return } downloaders[model] = nil switch result { case .success: Logger.api.info("Local decision model \(model.rawValue, privacy: .public) downloaded") states[model] = .ready case .failure(let error): Logger.api.error("Local decision model \(model.rawValue, privacy: .public) download failed: \(error.localizedDescription, privacy: .public)") states[model] = .failed(error.localizedDescription) } } } /// One download task with progress; the finished file is moved into place before the delegate returns. private final class ModelDownloader: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { private let destination: URL private let expectedBytes: Int64 private let onProgress: @Sendable (Double) -> Void private let onComplete: @Sendable (Result) -> Void private var session: URLSession? private var task: URLSessionDownloadTask? private var finished = false private var lastReported = 0.0 struct DownloadError: LocalizedError { let errorDescription: String? } init(destination: URL, expectedBytes: Int64, onProgress: @escaping @Sendable (Double) -> Void, onComplete: @escaping @Sendable (Result) -> Void) { self.destination = destination self.expectedBytes = expectedBytes self.onProgress = onProgress self.onComplete = onComplete } func start(url: URL) { let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) self.session = session task = session.downloadTask(with: url) task?.resume() } func cancel() { task?.cancel() session?.invalidateAndCancel() } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let total = totalBytesExpectedToWrite > 0 ? totalBytesExpectedToWrite : expectedBytes let fraction = min(1, Double(totalBytesWritten) / Double(total)) guard fraction - lastReported >= 0.005 || fraction >= 1 else { return } lastReported = fraction onProgress(fraction) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { finished = true let status = (downloadTask.response as? HTTPURLResponse)?.statusCode ?? 0 guard status == 200 else { onComplete(.failure(DownloadError(errorDescription: "Download failed (HTTP \(status))"))) return } do { try? FileManager.default.removeItem(at: destination) try FileManager.default.moveItem(at: location, to: destination) onComplete(.success(())) } catch { onComplete(.failure(error)) } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { defer { session.finishTasksAndInvalidate() } guard !finished, let error else { return } finished = true onComplete(.failure(error)) } }