Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more
fix: show live model download progress
altic-dev49e151023371
diff --git a/Package.resolved b/Package.resolvedindex f5f21e17..5874459a 100644--- a/Package.resolved+++ b/Package.resolved@@ -24,7 +24,7 @@"location" : "https://github.com/altic-dev/FluidAudio.git","state" : {"branch" : "B/cohere-coreml-asr",- "revision" : "72625bbccf9f6c797a540a1f1cb66a4cb60753eb"+ "revision" : "6af79253328cd174f4200c5790eca664012ca45c"}},{diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swiftindex a7922f3f..bad538fe 100644--- a/Sources/Fluid/Networking/ModelDownloader.swift+++ b/Sources/Fluid/Networking/ModelDownloader.swift@@ -282,19 +282,14 @@ final class HuggingFaceModelDownloader {private func downloadFile(relativePath: String, to destination: URL, perFileProgress: ((Double) -> Void)? = nil) async throws {let fileURL = self.baseResolveURL.appendingPathComponent(relativePath)- let delegate = DownloadProgressDelegate { totalBytesWritten, totalBytesExpected in- guard totalBytesExpected > 0 else { return }- perFileProgress?(min(1.0, Double(totalBytesWritten) / Double(totalBytesExpected)))- }- let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)- defer { session.finishTasksAndInvalidate() }-var temporaryURL: URL?do {- let result = try await withTaskCancellationHandler {- try await session.download(from: fileURL)- } onCancel: {- session.invalidateAndCancel()+ let result = try await ProgressiveFileDownloader.download(+ from: fileURL,+ configuration: .default+ ) { totalBytesWritten, totalBytesExpected in+ guard totalBytesExpected > 0 else { return }+ perFileProgress?(min(1.0, Double(totalBytesWritten) / Double(totalBytesExpected)))}temporaryURL = result.0let response = result.1@@ -319,7 +314,6 @@ final class HuggingFaceModelDownloader {if let temporaryURL {try? FileManager.default.removeItem(at: temporaryURL)}- session.invalidateAndCancel()if Task.isCancelled || Self.isCancellationError(error) {throw CancellationError()}@@ -564,23 +558,6 @@ final class HuggingFaceModelDownloader {])}- private final class DownloadProgressDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {- private let onProgress: (Int64, Int64) -> Void-- init(onProgress: @escaping (Int64, Int64) -> Void) {- self.onProgress = onProgress- }-- func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {- // The async URLSession API owns completion; this delegate only reports bytes.- }-- func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {- guard totalBytesExpectedToWrite > 0 else { return }- self.onProgress(totalBytesWritten, totalBytesExpectedToWrite)- }- }-private func headExpectedLength(relativePath: String) async throws -> Int64 {try Task.checkCancellation()let fileURL = self.baseResolveURL.appendingPathComponent(relativePath)@@ -638,6 +615,137 @@ final class HuggingFaceModelDownloader {}}+/// Uses URLSession's delegate API directly so large-file byte progress is delivered+/// continuously. The async download convenience only surfaced file completion here.+final nonisolated class ProgressiveFileDownloader: @unchecked Sendable {+ private final class TaskHolder: @unchecked Sendable {+ private let lock = NSLock()+ private var task: URLSessionDownloadTask?+ private var isCancelled = false++ func setTask(_ task: URLSessionDownloadTask) {+ self.lock.withLock {+ if self.isCancelled {+ task.cancel()+ } else {+ self.task = task+ }+ }+ }++ func cancel() {+ self.lock.withLock {+ self.isCancelled = true+ self.task?.cancel()+ }+ }+ }++ private final class Delegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {+ typealias Completion = @Sendable (Result<(URL, URLResponse), Error>) -> Void++ private let onProgress: @Sendable (Int64, Int64) -> Void+ private let lock = NSLock()+ private var completion: Completion?+ private var downloadResult: Result<(URL, URLResponse), Error>?+ weak var session: URLSession?++ init(+ onProgress: @escaping @Sendable (Int64, Int64) -> Void,+ completion: @escaping Completion+ ) {+ self.onProgress = onProgress+ self.completion = completion+ }++ func urlSession(+ _ session: URLSession,+ downloadTask: URLSessionDownloadTask,+ didWriteData bytesWritten: Int64,+ totalBytesWritten: Int64,+ totalBytesExpectedToWrite: Int64+ ) {+ self.onProgress(totalBytesWritten, totalBytesExpectedToWrite)+ }++ func urlSession(+ _ session: URLSession,+ downloadTask: URLSessionDownloadTask,+ didFinishDownloadingTo location: URL+ ) {+ guard let response = downloadTask.response else {+ self.storeResult(.failure(URLError(.badServerResponse)))+ return+ }++ do {+ let retainedURL = FileManager.default.temporaryDirectory+ .appendingPathComponent("FluidVoiceDownload-\(UUID().uuidString)")+ try FileManager.default.copyItem(at: location, to: retainedURL)+ self.storeResult(.success((retainedURL, response)))+ } catch {+ self.storeResult(.failure(error))+ }+ }++ func urlSession(+ _ session: URLSession,+ task: URLSessionTask,+ didCompleteWithError error: Error?+ ) {+ if let error {+ self.finish(.failure(error))+ } else {+ let result = self.lock.withLock { self.downloadResult }+ self.finish(result ?? .failure(URLError(.badServerResponse)))+ }+ self.session?.finishTasksAndInvalidate()+ }++ private func storeResult(_ result: Result<(URL, URLResponse), Error>) {+ self.lock.withLock {+ self.downloadResult = result+ }+ }++ private func finish(_ result: Result<(URL, URLResponse), Error>) {+ let completion = self.lock.withLock { () -> Completion? in+ defer { self.completion = nil }+ return self.completion+ }+ completion?(result)+ }+ }++ static func download(+ from url: URL,+ configuration: URLSessionConfiguration,+ onProgress: @escaping @Sendable (Int64, Int64) -> Void+ ) async throws -> (URL, URLResponse) {+ let taskHolder = TaskHolder()+ return try await withTaskCancellationHandler {+ try await withCheckedThrowingContinuation { continuation in+ let delegate = Delegate(+ onProgress: onProgress,+ completion: { continuation.resume(with: $0) }+ )+ let session = URLSession(+ configuration: configuration,+ delegate: delegate,+ delegateQueue: nil+ )+ delegate.session = session++ let task = session.downloadTask(with: url)+ taskHolder.setTask(task)+ task.resume()+ }+ } onCancel: {+ taskHolder.cancel()+ }+ }+}+#if arch(arm64)extension HuggingFaceModelDownloader {/// Load ASR models directly from disk using unified v3 model namesdiff --git a/Sources/Fluid/Services/TranscriptionProvider.swift b/Sources/Fluid/Services/TranscriptionProvider.swiftindex b8cf47e8..78903834 100644--- a/Sources/Fluid/Services/TranscriptionProvider.swift+++ b/Sources/Fluid/Services/TranscriptionProvider.swift@@ -1,13 +1,13 @@import Foundation-enum ModelPreparationPhase: Sendable, Equatable {+nonisolated enum ModelPreparationPhase: Sendable, Equatable {case preparingDownloadcase downloadingcase optimizingcase loading}-struct ModelPreparationProgress: Sendable, Equatable {+nonisolated struct ModelPreparationProgress: Sendable, Equatable {let phase: ModelPreparationPhaselet fractionCompleted: Double?@@ -27,15 +27,78 @@ struct ModelPreparationProgress: Sendable, Equatable {/// Bridges provider callbacks into dependencies whose progress handlers are `@Sendable`./// The callback is immutable; callers remain responsible for hopping to their UI actor.-final class ModelPreparationProgressRelay: @unchecked Sendable {+final nonisolated class ModelPreparationProgressRelay: @unchecked Sendable {+ private static let minimumDeliveryInterval: TimeInterval = 0.1+private let handler: ((ModelPreparationProgress) -> Void)?+ private let lock = NSLock()+ private var lastPhase: ModelPreparationPhase?+ private var lastDeliveredPercentage: Int?+ private var lastDeliveryTime: TimeInterval = 0+ private var pendingProgress: ModelPreparationProgress?+ private var deliveryScheduled = falseinit(_ handler: ((ModelPreparationProgress) -> Void)?) {self.handler = handler}func report(_ progress: ModelPreparationProgress) {- self.handler?(progress)+ let now = ProcessInfo.processInfo.systemUptime+ let delivery = self.lock.withLock { () -> (immediate: Bool, delay: TimeInterval?) in+ if progress.phase != self.lastPhase {+ self.lastPhase = progress.phase+ self.pendingProgress = nil+ self.lastDeliveredPercentage = nil+ self.lastDeliveryTime = now+ return (true, nil)+ }++ guard progress.phase == .downloading else { return (false, nil) }++ let percentage = Int((progress.fractionCompleted ?? 0) * 100)+ guard percentage != self.lastDeliveredPercentage else { return (false, nil) }++ let elapsed = now - self.lastDeliveryTime+ if elapsed >= Self.minimumDeliveryInterval {+ self.pendingProgress = nil+ self.lastDeliveredPercentage = percentage+ self.lastDeliveryTime = now+ return (true, nil)+ }++ self.pendingProgress = progress+ guard !self.deliveryScheduled else { return (false, nil) }+ self.deliveryScheduled = true+ return (false, Self.minimumDeliveryInterval - elapsed)+ }++ if delivery.immediate {+ self.handler?(progress)+ } else if let delay = delivery.delay {+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + delay) { [weak self] in+ self?.flushPendingProgress()+ }+ }+ }++ private func flushPendingProgress() {+ let progress = self.lock.withLock { () -> ModelPreparationProgress? in+ self.deliveryScheduled = false+ guard let progress = self.pendingProgress,+ progress.phase == self.lastPhase+ else {+ self.pendingProgress = nil+ return nil+ }++ self.pendingProgress = nil+ self.lastDeliveredPercentage = Int((progress.fractionCompleted ?? 0) * 100)+ self.lastDeliveryTime = ProcessInfo.processInfo.systemUptime+ return progress+ }+ if let progress {+ self.handler?(progress)+ }}}diff --git a/Sources/Fluid/Services/WhisperProvider.swift b/Sources/Fluid/Services/WhisperProvider.swiftindex 7a2c1547..c2e47a1a 100644--- a/Sources/Fluid/Services/WhisperProvider.swift+++ b/Sources/Fluid/Services/WhisperProvider.swift@@ -407,16 +407,15 @@ final class WhisperProvider: TranscriptionProvider {}private func downloadFile(from url: URL, to destination: URL, progressHandler: ((Double) -> Void)?) async throws {- let delegate = DownloadProgressDelegate(onProgress: progressHandler)- let session = URLSession(configuration: self.urlSession.configuration, delegate: delegate, delegateQueue: nil)- defer { session.finishTasksAndInvalidate() }-var temporaryURL: URL?do {- let (downloadedURL, response) = try await withTaskCancellationHandler {- try await session.download(from: url)- } onCancel: {- session.invalidateAndCancel()+ let (downloadedURL, response) = try await ProgressiveFileDownloader.download(+ from: url,+ configuration: self.urlSession.configuration+ ) { totalBytesWritten, totalBytesExpectedToWrite in+ guard totalBytesExpectedToWrite > 0 else { return }+ let pct = min(0.999, Double(totalBytesWritten) / Double(totalBytesExpectedToWrite))+ progressHandler?(pct)}temporaryURL = downloadedURLtry Task.checkCancellation()@@ -470,7 +469,6 @@ final class WhisperProvider: TranscriptionProvider {if let temporaryURL {try? FileManager.default.removeItem(at: temporaryURL)}- session.invalidateAndCancel()let nsError = error as NSErrorif Task.isCancelled|| error is CancellationError@@ -483,28 +481,4 @@ final class WhisperProvider: TranscriptionProvider {try Task.checkCancellation()progressHandler?(1.0)}-- private final class DownloadProgressDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {- private let onProgress: ((Double) -> Void)?-- init(onProgress: ((Double) -> Void)?) {- self.onProgress = onProgress- }-- func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {- // The async URLSession API owns completion; this delegate only reports bytes.- }-- func urlSession(- _ session: URLSession,- downloadTask: URLSessionDownloadTask,- didWriteData bytesWritten: Int64,- totalBytesWritten: Int64,- totalBytesExpectedToWrite: Int64- ) {- guard totalBytesExpectedToWrite > 0 else { return }- let pct = min(0.999, Double(totalBytesWritten) / Double(totalBytesExpectedToWrite))- self.onProgress?(pct)- }- }}