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: reject HTML-corrupt cached model files at provider preflights, not just the downloader (#353)
postoso1668ee9a8621
diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swiftindex 125fe6ab..8c817e19 100644--- a/Sources/Fluid/Networking/ModelDownloader.swift+++ b/Sources/Fluid/Networking/ModelDownloader.swift@@ -300,6 +300,51 @@ final class HuggingFaceModelDownloader {return Self.looksLikeHTML(prefix)}+ /// Returns `true` if any cached payload under `relativePaths` (each resolved against `root`)+ /// is an HTML/markup document rather than real model data — the cached-*tree* analog of+ /// `cachedFileIsMarkup`, intended for a provider preflight to call before trusting a present+ /// cache and skipping the downloader. The downloader itself already re-validates each file via+ /// `needsDownload`, but a preflight that returns on file-existence alone never reaches it, so a+ /// corrupt-but-present cache would slip through (see #353).+ ///+ /// Each relative path may be a regular file or a directory (e.g. a `.mlpackage` bundle).+ /// Directories are scanned recursively and every regular file inside is byte-sniffed with+ /// `cachedFileIsMarkup`, reusing the single `looksLikeHTML` detector — there is no second+ /// markup heuristic. Conservative on uncertainty, mirroring `cachedFileIsMarkup`: a path that+ /// does not exist, a file that cannot be read, or a directory that cannot be enumerated is+ /// skipped (treated as non-markup), so a valid cache is never reported corrupt. An empty+ /// required directory therefore yields `false` here — its incompleteness is the existence+ /// check's concern, not this markup check's.+ static func cachedPayloadContainsMarkup(root: URL, relativePaths: [String]) -> Bool {+ let fileManager = FileManager.default+ for relativePath in relativePaths {+ let url = root.appendingPathComponent(relativePath)+ var isDirectory: ObjCBool = false+ guard fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory) else {+ continue+ }+ if isDirectory.boolValue {+ guard let enumerator = fileManager.enumerator(+ at: url,+ includingPropertiesForKeys: [.isRegularFileKey],+ options: [.skipsHiddenFiles]+ ) else {+ continue+ }+ for case let fileURL as URL in enumerator {+ let isRegularFile = (try? fileURL.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile ?? false+ guard isRegularFile else { continue }+ if Self.cachedFileIsMarkup(at: fileURL) {+ return true+ }+ }+ } else if Self.cachedFileIsMarkup(at: url) {+ return true+ }+ }+ return false+ }+/// Returns `true` if `data` begins with an HTML / XML markup marker, ignoring a leading/// UTF-8 BOM and ASCII whitespace.///diff --git a/Sources/Fluid/Services/ExternalCoreMLTranscriptionProvider.swift b/Sources/Fluid/Services/ExternalCoreMLTranscriptionProvider.swiftindex 5fc50ba3..5f73603f 100644--- a/Sources/Fluid/Services/ExternalCoreMLTranscriptionProvider.swift+++ b/Sources/Fluid/Services/ExternalCoreMLTranscriptionProvider.swift@@ -230,6 +230,14 @@ final class ExternalCoreMLTranscriptionProvider: TranscriptionProvider {try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)let isManagedDirectory = Self.isAppManagedArtifactsDirectory(directory, spec: spec)+ // `validateArtifacts` proves the required entries exist and the manifest JSON decodes, but+ // it does NOT byte-check the `.mlpackage` binaries — a network proxy can have returned an+ // HTML block page (HTTP 200) in place of one, persisting markup as a model file. Re-sniff+ // the present artifacts so such a payload forces the downloader to run (it then deletes ++ // re-fetches the corrupt files via `needsDownload`) instead of being trusted forever. The+ // outdated-bundle-stamp refresh below is preserved and takes precedence: a stamp-stale+ // managed cache is still fully removed even if it is also markup-corrupt, so the bundle+ // is wholly refreshed rather than only the corrupt files re-fetched. See #353.if spec.validateArtifacts(at: directory) {if isManagedDirectory, self.artifactBundleStampMatches(spec: spec, directory: directory) == false {DebugLogger.shared.warning(@@ -238,6 +246,11 @@ final class ExternalCoreMLTranscriptionProvider: TranscriptionProvider {)try FileManager.default.removeItem(at: directory)try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ } else if Self.cachedArtifactsAreMarkupCorrupt(spec: spec, directory: directory) {+ DebugLogger.shared.warning(+ "ExternalCoreML: cached artifacts for \(directory.lastPathComponent) contain an HTML/markup payload (corrupt); re-downloading",+ source: "ExternalCoreML"+ )} else {DebugLogger.shared.info("ExternalCoreML: artifact validation passed for \(directory.lastPathComponent)",@@ -248,7 +261,8 @@ final class ExternalCoreMLTranscriptionProvider: TranscriptionProvider {}}- if spec.validateArtifacts(at: directory) {+ if spec.validateArtifacts(at: directory),+ !Self.cachedArtifactsAreMarkupCorrupt(spec: spec, directory: directory) {DebugLogger.shared.info("ExternalCoreML: artifact validation passed for \(directory.lastPathComponent)",source: "ExternalCoreML"@@ -307,6 +321,19 @@ final class ExternalCoreMLTranscriptionProvider: TranscriptionProvider {return directory.standardizedFileURL.path == defaultCacheDirectory.standardizedFileURL.path}+ /// `true` if any required cached artifact is an HTML/markup payload instead of model data — a+ /// corrupt cache a markup-blind `validateArtifacts` check would otherwise trust (#353). Reuses+ /// the downloader's shared byte-sniff; conservative on read errors (never flags on uncertainty).+ private static func cachedArtifactsAreMarkupCorrupt(+ spec: ExternalCoreMLASRModelSpec,+ directory: URL+ ) -> Bool {+ HuggingFaceModelDownloader.cachedPayloadContainsMarkup(+ root: directory,+ relativePaths: spec.requiredEntries+ )+ }+private static func makeError(_ description: String) -> NSError {NSError(domain: "ExternalCoreMLTranscriptionProvider",diff --git a/Sources/Fluid/Services/NemotronProvider.swift b/Sources/Fluid/Services/NemotronProvider.swiftindex 6a32dba9..49a9b6d7 100644--- a/Sources/Fluid/Services/NemotronProvider.swift+++ b/Sources/Fluid/Services/NemotronProvider.swift@@ -88,13 +88,27 @@ final class NemotronProvider: TranscriptionProvider {}try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)- if self.modelsExistOnDisk() {+ // A file-existence check alone would trust a corrupt cache: a network proxy can have+ // returned an HTML block page (HTTP 200) in place of a model file, persisting markup as+ // e.g. a `.mlpackage` binary or `tokenizer.model`. Re-sniff the present artifacts so such+ // a payload forces a re-download (the downloader then deletes + re-fetches the bad files+ // via `needsDownload`) instead of being loaded as a model forever. See #353.+ let modelsPresent = self.modelsExistOnDisk()+ let cachedArtifactsCorrupt = modelsPresent+ && HuggingFaceModelDownloader.cachedPayloadContainsMarkup(root: dir, relativePaths: self.requiredFiles)+ if modelsPresent && !cachedArtifactsCorrupt {DebugLogger.shared.info("Nemotron: artifacts present at \(dir.path); skipping download",source: "Nemotron")progressHandler?(0.8)} else {+ if cachedArtifactsCorrupt {+ DebugLogger.shared.warning(+ "Nemotron: cached artifacts at \(dir.path) contain an HTML/markup payload (corrupt); re-downloading",+ source: "Nemotron"+ )+ }DebugLogger.shared.info("Nemotron: artifacts missing; downloading from \(self.repositoryOwner)/\(self.repositoryName)",source: "Nemotron"diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swiftindex 8f001ed6..3f97b50a 100644--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift@@ -634,6 +634,63 @@ final class DictationE2ETests: XCTestCase {XCTAssertFalse(HuggingFaceModelDownloader.cachedFileIsMarkup(at: missingURL))}+ func testCachedPayloadContainsMarkup_detectsCorruptFileInPresentArtifactTree() throws {+ // Guards the #353 provider-PREFLIGHT path: a corrupt HTML payload nested inside a+ // present `.mlpackage` bundle (or a loose required file) must be detected so the preflight+ // re-downloads instead of trusting a file-existence/manifest check, while a valid cached+ // tree must not be flagged, and missing/empty required entries stay conservative.+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("FluidVoice-CachedPayloadTest-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }++ // A realistic `.mlpackage` layout: a JSON manifest plus a nested binary weight payload.+ let packageName = "encoder.mlpackage"+ let weightsDir = root.appendingPathComponent(packageName)+ .appendingPathComponent("Data/com.apple.CoreML/weights", isDirectory: true)+ try FileManager.default.createDirectory(at: weightsDir, withIntermediateDirectories: true)+ let manifestURL = root.appendingPathComponent(packageName).appendingPathComponent("Manifest.json")+ try Data("{\"fileFormatVersion\": \"1.0.0\"}".utf8).write(to: manifestURL)+ let weightURL = weightsDir.appendingPathComponent("weight.bin")+ try Data([0x00, 0x01, 0x02, 0x03, 0x04]).write(to: weightURL)++ // A loose required file (e.g. a tokenizer) with real binary content.+ let tokenizerURL = root.appendingPathComponent("tokenizer.model")+ try Data([0x0A, 0x09, 0x05, 0x00]).write(to: tokenizerURL)++ let entries = [packageName, "tokenizer.model"]++ // An all-valid tree must not be flagged.+ XCTAssertFalse(+ HuggingFaceModelDownloader.cachedPayloadContainsMarkup(root: root, relativePaths: entries)+ )++ // A proxy HTML page persisted as a binary INSIDE the package must be detected.+ try Data("<!DOCTYPE html><html><body>Blocked by proxy</body></html>".utf8).write(to: weightURL)+ XCTAssertTrue(+ HuggingFaceModelDownloader.cachedPayloadContainsMarkup(root: root, relativePaths: entries)+ )++ // Restore the binary; corrupt the loose required file instead — must still be detected.+ try Data([0x00, 0x01, 0x02, 0x03, 0x04]).write(to: weightURL)+ try Data("<html><head></head></html>".utf8).write(to: tokenizerURL)+ XCTAssertTrue(+ HuggingFaceModelDownloader.cachedPayloadContainsMarkup(root: root, relativePaths: entries)+ )++ // Missing entries and an empty required directory are conservative: never flagged corrupt+ // on uncertainty (incompleteness is the existence check's concern, not this one's).+ try Data([0x0A, 0x09, 0x05, 0x00]).write(to: tokenizerURL)+ let emptyPackage = root.appendingPathComponent("empty.mlpackage", isDirectory: true)+ try FileManager.default.createDirectory(at: emptyPackage, withIntermediateDirectories: true)+ XCTAssertFalse(+ HuggingFaceModelDownloader.cachedPayloadContainsMarkup(+ root: root,+ relativePaths: ["empty.mlpackage", "does-not-exist.json"]+ )+ )+ }+private static func modelDirectoryForRun() -> URL {// Use a stable path on CI so GitHub Actions cache can speed up runs.if ProcessInfo.processInfo.environment["GITHUB_ACTIONS"] == "true" ||