// ONE model store per phone, shared by every Cotton app: the App Group // container `group.com.cottondb.shared`, so a model is downloaded once, by // whichever app asks first, and every other app finds it ready. // // /VoiceModels// the files, as the catalogue names them // /VoiceModels//.ready written last, after every sha256 matched // /VoiceModels//.downloading the app downloading it, and when it began // // Downloads run on a BACKGROUND URLSession, so they go on while the app is // away and resume after a failure (the resume data is kept beside the files); // each file's sha256 is checked before it is moved into place, and a file that // does not match is deleted and the model marked failed. Whether a download // may use mobile data is the person's setting (`voice.settings`), read from // the core and applied as the session's cellular rule. // // Every change of a model's state is told to the core (`voice.model`), which // joins it with the catalogue for `voice.models`. import CottonKit import CryptoKit import Foundation import Observation import os @MainActor @Observable public final class VoiceModelStore { nonisolated public static let appGroup = "group.com.cottondb.shared" /// What this phone holds, by model id. public private(set) var states: [String: VoiceModelState] = [:] public private(set) var bytesDone: [String: Int64] = [:] /// The catalogue as the core last answered it (`voice.models`). public private(set) var catalogue: [String: VoiceModelEntry] = [:] /// The voice-activity model a segmented live engine needs: the catalogue's `vad`. public private(set) var vadModel: String? public let root: URL /// False when the App Group container could not be opened (an app whose /// profile lacks the group): models then live in this app alone. public let shared: Bool private var core: (any CottonCalling)? private let downloader: VoiceDownloader private static let log = Logger(subsystem: "com.cottondb.voice", category: "models") /// The one store of this process. public static let current = VoiceModelStore() init(root: URL? = nil) { if let root { self.root = root shared = false } else if let group = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Self.appGroup) { self.root = group.appendingPathComponent("VoiceModels", isDirectory: true) shared = true } else { let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] self.root = support.appendingPathComponent("VoiceModels", isDirectory: true) shared = false } try? FileManager.default.createDirectory(at: self.root, withIntermediateDirectories: true) downloader = VoiceDownloader(root: self.root) downloader.onProgress = { [weak self] model, done in Task { @MainActor in self?.progress(model, done) } } downloader.onFinished = { [weak self] model, failure in Task { @MainActor in await self?.finished(model, failure: failure) } } } /// Hand the store its core: it reads the catalogue and tells the core what /// this phone holds. public func attach(_ core: any CottonCalling) async { self.core = core await refresh() } /// Read the catalogue again (`voice.models`) and look at the disk. public func refresh() async { if let core, let answer = try? await core.call(CottonMethod.voiceModels, as: VoiceModelsAnswer.self) { for entry in answer.models { catalogue[entry.model] = entry } vadModel = answer.vad ?? vadModel } for model in catalogue.keys { states[model] = diskState(model) } } /// Learn entries from outside the core (the plan's downloads, a debug catalogue). public func learn(_ entries: [VoiceModelEntry]) { for entry in entries { catalogue[entry.model] = entry; states[entry.model] = diskState(entry.model) } } nonisolated public func folder(_ model: String) -> URL { root.appendingPathComponent(model, isDirectory: true) } /// The model, ready to load; throws `modelMissing` when it is not here. public func ready(_ model: String) async throws -> VoiceModelEntry { if catalogue[model] == nil { await refresh() } guard let entry = readyNow(model) else { throw VoiceFailure.modelMissing(model) } return entry } /// The model's entry when every file is here and checked: the files as /// they were fetched (the marker), how to run it as the catalogue says. public func readyNow(_ model: String) -> VoiceModelEntry? { guard diskState(model) == .ready, let entry = readMarker(model) else { return nil } return catalogue[model].map(entry.taught(by:)) ?? entry } /// A held model that can hear `language` live when the platform's /// recogniser cannot: one made for live first, then one for both passes, /// then a second-pass model (run on voice-activity segments). public func heldStandIn(for language: String?) -> VoiceModelEntry? { let code = language.flatMap { Locale.Language(identifier: $0).languageCode?.identifier } ?? "en" let names = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? [] let held = names.compactMap { readyNow($0) } .filter { $0.role != "vad" && ($0.languages.contains(code) || $0.languages.contains("*")) } for role in ["live", "both", "second"] { if let found = held.filter({ $0.role == role }).sorted(by: { $0.model < $1.model }).first { return found } } return nil } /// Take a model whose files are already on this device elsewhere (Cotton /// Dev's proof models): its files are linked into the store's folder and /// it is marked ready, exactly as a finished download is. public func adopt(_ entry: VoiceModelEntry, from source: URL) { let into = folder(entry.model) try? FileManager.default.createDirectory(at: into, withIntermediateDirectories: true) for file in entry.files { let link = into.appendingPathComponent(file.name) try? FileManager.default.removeItem(at: link) try? FileManager.default.createSymbolicLink(at: link, withDestinationURL: source.appendingPathComponent(file.name).resolvingSymlinksInPath()) } writeMarker(entry) states[entry.model] = .ready } // MARK: Downloading /// Fetch a model the plan asked for: every file the plan's downloads /// list for it (one entry per file; `url`'s last part is the file's name). public func download(_ model: String, files offers: [VoiceDownload], mobileData: String) async { let known = catalogue[model]?.files ?? [] let files = offers.filter { $0.model == model }.map { offer in VoiceModelFile(name: offer.file, url: offer.url, bytes: offer.bytes, sha256: offer.sha256, part: known.first { $0.name == offer.file }?.part ?? "") } guard !files.isEmpty else { return } var entry = catalogue[model] ?? VoiceModelEntry(model: model, kind: "") entry.files = files catalogue[model] = entry rule = mobileData await fetch(model, asked: true) } /// The plan's mobile-data rule, as last given. private var rule: String? /// Fetch a catalogue model by id. `asked`: the person tapped for it. public func fetch(_ model: String, asked: Bool) async { guard let entry = catalogue[model], !entry.files.isEmpty else { return } guard diskState(model) != .ready else { return } let cellular = await mobileDataAllowed(asked: asked) states[model] = .downloading bytesDone[model] = 0 await tell(model, .downloading) downloader.fetch(entry, cellular: cellular) } private func mobileDataAllowed(asked: Bool) async -> Bool { if let rule { return VoiceSettings(mobileData: rule).mobileDataAllowed(asked: asked) } guard let core, let settings = try? await core.call(CottonMethod.voiceSettings, as: VoiceSettings.self) else { return false } return settings.mobileDataAllowed(asked: asked) } private func progress(_ model: String, _ done: Int64) { bytesDone[model] = done } private func finished(_ model: String, failure: String?) async { if let failure { Self.log.error("model \(model, privacy: .public) failed: \(failure, privacy: .public)") states[model] = .failed await tell(model, .failed) return } if let entry = catalogue[model] { writeMarker(entry) } states[model] = .ready await tell(model, .ready) } private func tell(_ model: String, _ state: VoiceModelState) async { guard let core else { return } let change = VoiceModelChange( model: model, state: state, path: state == .ready ? folder(model).path : nil, bytesDone: bytesDone[model]) _ = try? await core.callJSON(CottonMethod.voiceModel, change) } /// The background session's events, handed over by the app delegate. public static func handleBackgroundEvents(identifier: String, completion: @escaping () -> Void) -> Bool { guard identifier == VoiceDownloader.sessionIdentifier else { return false } // iOS hands it over on the main thread and wants it called there. nonisolated(unsafe) let completion = completion current.downloader.backgroundCompletion = { completion() } return true } // MARK: The disk func diskState(_ model: String) -> VoiceModelState { let folder = folder(model) if FileManager.default.fileExists(atPath: folder.appendingPathComponent(".ready").path) { return .ready } if downloader.isFetching(model) { return .downloading } if let marker = VoiceFiles.read(folder.appendingPathComponent(".downloading"), atMost: VoiceFiles.markerBytes), let since = Double(String(decoding: marker, as: UTF8.self).split(separator: " ").last ?? ""), Date().timeIntervalSince1970 - since < 600 { // Another Cotton app is fetching it now. return .downloading } return .absent } private func writeMarker(_ entry: VoiceModelEntry) { let marker = VoiceReadyMarker(model: entry.model, family: entry.family, kind: entry.kind, role: entry.role, languages: entry.languages, files: entry.files, options: entry.options, level: entry.level) if let data = try? JSONEncoder().encode(marker) { try? data.write(to: folder(entry.model).appendingPathComponent(".ready"), options: .atomic) } try? FileManager.default.removeItem(at: folder(entry.model).appendingPathComponent(".downloading")) } private func readMarker(_ model: String) -> VoiceModelEntry? { guard let data = VoiceFiles.read(folder(model).appendingPathComponent(".ready"), atMost: VoiceFiles.markerBytes), let marker = try? JSONDecoder().decode(VoiceReadyMarker.self, from: data) else { return nil } return VoiceModelEntry(model: marker.model, family: marker.family, kind: marker.kind, role: marker.role, languages: marker.languages, files: marker.files, state: .ready, options: marker.options ?? [:], level: marker.level) } /// Remove a model (Settings' voice models). public func remove(_ model: String) async { try? FileManager.default.removeItem(at: folder(model)) states[model] = .absent await tell(model, .absent) } } /// The store's own small files, read with a ceiling: a marker or a resume /// record that has grown past it is not one this store wrote, and is treated /// as absent rather than read whole. enum VoiceFiles { /// A `.ready` marker lists a model's few files; `.downloading` is a stamp. static let markerBytes = 64 * 1024 /// URLSession's resume record: a small property list naming the partial file. static let resumeBytes = 1024 * 1024 static func read(_ url: URL, atMost limit: Int) -> Data? { guard let handle = try? FileHandle(forReadingFrom: url) else { return nil } defer { try? handle.close() } guard let data = try? handle.read(upToCount: limit + 1), data.count <= limit else { return nil } return data } } struct VoiceReadyMarker: Codable { var model: String var family: String var kind: String var role: String var languages: [String] var files: [VoiceModelFile] var options: [String: String]? var level: VoiceLevelling? } /// The background session: one download task per file, sha256 checked, /// resumable. final class VoiceDownloader: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { static var sessionIdentifier: String { "com.cottondb.voice.models." + (Bundle.main.bundleIdentifier ?? "app") } private let root: URL private let lock = NSLock() /// Per model: its entry, the files still to come, bytes done per file. private var jobs: [String: Job] = [:] var onProgress: ((String, Int64) -> Void)? var onFinished: ((String, String?) -> Void)? var backgroundCompletion: (@Sendable () -> Void)? private struct Job { var entry: VoiceModelEntry var waiting: Set var done: [String: Int64] = [:] var failure: String? } private lazy var session: URLSession = makeSession(cellular: false) private var cellular = false init(root: URL) { self.root = root super.init() } private func makeSession(cellular: Bool) -> URLSession { let config = URLSessionConfiguration.background(withIdentifier: Self.sessionIdentifier) config.sharedContainerIdentifier = VoiceModelStore.appGroup config.allowsCellularAccess = cellular config.allowsExpensiveNetworkAccess = cellular config.isDiscretionary = false config.sessionSendsLaunchEvents = true return URLSession(configuration: config, delegate: self, delegateQueue: nil) } func isFetching(_ model: String) -> Bool { lock.lock() defer { lock.unlock() } return jobs[model] != nil } func fetch(_ entry: VoiceModelEntry, cellular: Bool) { lock.lock() if jobs[entry.model] != nil { lock.unlock(); return } if cellular != self.cellular { // The cellular rule is the session's: a new rule is a new session // once nothing is in flight on the old one. if jobs.isEmpty { session.finishTasksAndInvalidate() self.cellular = cellular session = makeSession(cellular: cellular) } } let folder = root.appendingPathComponent(entry.model, isDirectory: true) try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) let stamp = "\(Bundle.main.bundleIdentifier ?? "app") \(Date().timeIntervalSince1970)" try? Data(stamp.utf8).write(to: folder.appendingPathComponent(".downloading")) // Files already here and matching are not fetched again. let missing = entry.files.filter { file in let at = folder.appendingPathComponent(file.name) guard FileManager.default.fileExists(atPath: at.path) else { return true } return !(file.sha256.isEmpty || (try? Self.sha256(of: at)) == file.sha256.lowercased()) } jobs[entry.model] = Job(entry: entry, waiting: Set(missing.map(\.name))) lock.unlock() if missing.isEmpty { finish(entry.model) return } for file in missing { guard let url = URL(string: file.url), !file.url.isEmpty else { fail(entry.model, "url_missing:\(file.name)") return } let resume = folder.appendingPathComponent(".resume-\(file.name)") let task: URLSessionDownloadTask if let data = VoiceFiles.read(resume, atMost: VoiceFiles.resumeBytes) { task = session.downloadTask(withResumeData: data) try? FileManager.default.removeItem(at: resume) } else { task = session.downloadTask(with: url) } task.taskDescription = "\(entry.model)\n\(file.name)" task.countOfBytesClientExpectsToReceive = file.bytes > 0 ? file.bytes : NSURLSessionTransferSizeUnknown task.resume() } } private func names(_ task: URLSessionTask) -> (model: String, file: String)? { guard let parts = task.taskDescription?.split(separator: "\n", maxSplits: 1), parts.count == 2 else { return nil } return (String(parts[0]), String(parts[1])) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData _: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite _: Int64) { guard let (model, file) = names(downloadTask) else { return } lock.lock() jobs[model]?.done[file] = totalBytesWritten let total = jobs[model]?.done.values.reduce(0, +) ?? 0 lock.unlock() onProgress?(model, total) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let (model, name) = names(downloadTask) else { return } lock.lock() let entry = jobs[model]?.entry lock.unlock() guard let entry, let file = entry.files.first(where: { $0.name == name }) else { return } let target = root.appendingPathComponent(model, isDirectory: true).appendingPathComponent(name) if let status = (downloadTask.response as? HTTPURLResponse)?.statusCode, !(200 ..< 300).contains(status) { fail(model, "\(name): HTTP \(status)") return } // The check happens HERE, before the file is moved into place: the // system deletes `location` when this returns. if !file.sha256.isEmpty { guard let digest = try? Self.sha256(of: location), digest == file.sha256.lowercased() else { fail(model, "sha256_mismatch:\(name)") return } } try? FileManager.default.removeItem(at: target) do { try FileManager.default.moveItem(at: location, to: target) } catch { fail(model, "\(name): \(error.localizedDescription)") return } lock.lock() jobs[model]?.waiting.remove(name) let left = jobs[model]?.waiting.count ?? 0 lock.unlock() if left == 0 { finish(model) } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) { guard let error, let (model, name) = names(task) else { return } // Keep what came, for the next try. if let data = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data { let resume = root.appendingPathComponent(model, isDirectory: true).appendingPathComponent(".resume-\(name)") try? data.write(to: resume) } fail(model, "\(name): \(error.localizedDescription)") } func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { let completion = backgroundCompletion backgroundCompletion = nil DispatchQueue.main.async { completion?() } } private func finish(_ model: String) { lock.lock() jobs[model] = nil lock.unlock() onFinished?(model, nil) } private func fail(_ model: String, _ why: String) { lock.lock() let already = jobs[model] == nil jobs[model] = nil lock.unlock() try? FileManager.default.removeItem(at: root.appendingPathComponent(model).appendingPathComponent(".downloading")) if !already { onFinished?(model, why) } } /// The file's sha256, hex, read in pieces (models are hundreds of MB). static func sha256(of url: URL) throws -> String { let handle = try FileHandle(forReadingFrom: url) defer { try? handle.close() } var hash = SHA256() while let data = try handle.read(upToCount: 4 << 20), !data.isEmpty { hash.update(data: data) } return hash.finalize().map { String(format: "%02x", $0) }.joined() } }