Skip to content

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

Prepare beta 8: Fluid Speech models and reliability fixes (#1063)

ALTIC18bb4c635fd6
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index cb60fb62..07c9ba7b 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -94,6 +94,12 @@ jobs:
- name: Run release highlights regressions
run: sh Tests/run_release_highlights_tests.sh
+ - name: Run settings backup concurrency regressions
+ run: python3 Tests/run_settings_backup_concurrency_tests.py
+
+ - name: Run meeting backup refresh regressions
+ run: python3 Tests/run_meeting_backup_refresh_tests.py
+
# Tiny Whisper GGUF output is nondeterministic on hosted macOS runners.
# Keep this E2E assertion in the suite for local validation, but skip it in CI.
- name: Build and test (excluding flaky Tiny Whisper E2E)
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index cff8e548..c13ecd61 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -7,6 +7,18 @@
objects = {
/* Begin PBXBuildFile section */
+ D63B0F8456B440F1A123B987 /* PronunciationModelRevisionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFA73C8D5E7647C4AB125DEE /* PronunciationModelRevisionTests.swift */; };
+ 5D4A9F54826FD6BB32CE13F8 /* SpeechModelInstallationSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D47EF42AC1B641A705AC302 /* SpeechModelInstallationSnapshotTests.swift */; };
+ B51B7EE5BA8CE09BC09A47DB /* ProgressiveFileDownloaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70362FCD2F941BFB800AD8E8 /* ProgressiveFileDownloaderTests.swift */; };
+ 9F12D6C37B0166B549AECB61 /* ParakeetCompactModelDemoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16DE344948E4DBF0E1739769 /* ParakeetCompactModelDemoTests.swift */; };
+ 209C92C604F912C74A733D21 /* ParakeetCompactModelSmokeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9A7E0C9B501E87114F7A88 /* ParakeetCompactModelSmokeTests.swift */; };
+ 67F6BBBA604C996A20BEE7AC /* ParakeetArchiveDownloaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3398800F76A93226E76A5C9 /* ParakeetArchiveDownloaderTests.swift */; };
+ EA91B858DDC9E68655DCA343 /* ParakeetSpeechModelCatalogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BF00D40A027DC3970C2D0AE /* ParakeetSpeechModelCatalogTests.swift */; };
+ 24AFD1DFC6BFC9DB5BC6329B /* UpdateRollbackBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91C92FF93D3D21E0FD4D93EE /* UpdateRollbackBackupTests.swift */; };
+ 563881F82B15C86EDB50E198 /* UpdateInstallationPipelineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F12B5FA911AD928DAFD058FB /* UpdateInstallationPipelineTests.swift */; };
+ 7EAA9E7C4E4155A44F9CC415 /* UpdateAppReplacementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E4FCA0BC854678A142D944F /* UpdateAppReplacementTests.swift */; };
+ 6AE26D3BB678D13615C41376 /* UpdateBundleValidatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93E63CD61E6BD954698A8E63 /* UpdateBundleValidatorTests.swift */; };
+ 75454216C2DD7BBBB1D76D42 /* SettingsBackupRoundTripTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4263717D7203AAA6B63D9330 /* SettingsBackupRoundTripTests.swift */; };
FEA4AB111222333444555504 /* MeetingModelResidencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEA4AB111222333444555503 /* MeetingModelResidencyTests.swift */; };
AB492EFF712C42EE91601004 /* MeetingSummaryDownloadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB492EFF712C42EE91601003 /* MeetingSummaryDownloadTests.swift */; };
AB492EFF712C42EE91601002 /* MeetingSummaryInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB492EFF712C42EE91601001 /* MeetingSummaryInputTests.swift */; };
@@ -114,6 +126,8 @@
A5B000000000000000000018 /* MediaRemoteAdapter in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 7C5AF14A2F15041600DE21B0 /* MediaRemoteAdapter */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
A5B000000000000000000023 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7CDB0A2C2F3C4D5600FB7CAD /* XCTest.framework */; };
D1C7A7100000000000000002 /* UpdatePromptIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1C7A7100000000000000001 /* UpdatePromptIntegrationTests.swift */; };
+ C093F64545C6FDD2D79BF559 /* ParakeetArchiveInstallerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F06B51CF3F45AF989D0CA7F /* ParakeetArchiveInstallerTests.swift */; };
+ 640AB09C7781553DF72D1156 /* CompactSpeechModelArchiveTransportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01DEEE85A263FAED9ED5DEF8 /* CompactSpeechModelArchiveTransportTests.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -159,6 +173,18 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
+ AFA73C8D5E7647C4AB125DEE /* PronunciationModelRevisionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PronunciationModelRevisionTests.swift; sourceTree = "<group>"; };
+ 7D47EF42AC1B641A705AC302 /* SpeechModelInstallationSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpeechModelInstallationSnapshotTests.swift; sourceTree = "<group>"; };
+ 70362FCD2F941BFB800AD8E8 /* ProgressiveFileDownloaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProgressiveFileDownloaderTests.swift; sourceTree = "<group>"; };
+ 16DE344948E4DBF0E1739769 /* ParakeetCompactModelDemoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParakeetCompactModelDemoTests.swift; sourceTree = "<group>"; };
+ BC9A7E0C9B501E87114F7A88 /* ParakeetCompactModelSmokeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParakeetCompactModelSmokeTests.swift; sourceTree = "<group>"; };
+ E3398800F76A93226E76A5C9 /* ParakeetArchiveDownloaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParakeetArchiveDownloaderTests.swift; sourceTree = "<group>"; };
+ 6BF00D40A027DC3970C2D0AE /* ParakeetSpeechModelCatalogTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParakeetSpeechModelCatalogTests.swift; sourceTree = "<group>"; };
+ 91C92FF93D3D21E0FD4D93EE /* UpdateRollbackBackupTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateRollbackBackupTests.swift; sourceTree = "<group>"; };
+ F12B5FA911AD928DAFD058FB /* UpdateInstallationPipelineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateInstallationPipelineTests.swift; sourceTree = "<group>"; };
+ 8E4FCA0BC854678A142D944F /* UpdateAppReplacementTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateAppReplacementTests.swift; sourceTree = "<group>"; };
+ 93E63CD61E6BD954698A8E63 /* UpdateBundleValidatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateBundleValidatorTests.swift; sourceTree = "<group>"; };
+ 4263717D7203AAA6B63D9330 /* SettingsBackupRoundTripTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsBackupRoundTripTests.swift; sourceTree = "<group>"; };
FEA4AB111222333444555503 /* MeetingModelResidencyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingModelResidencyTests.swift; sourceTree = "<group>"; };
AB492EFF712C42EE91601003 /* MeetingSummaryDownloadTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingSummaryDownloadTests.swift; sourceTree = "<group>"; };
AB492EFF712C42EE91601001 /* MeetingSummaryInputTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingSummaryInputTests.swift; sourceTree = "<group>"; };
@@ -255,6 +281,8 @@
A5B00000000000000000000F /* placeholder.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = placeholder.json; sourceTree = "<group>"; };
A5B00000000000000000001D /* FluidASRBaselineTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = FluidASRBaselineTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
D1C7A7100000000000000001 /* UpdatePromptIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdatePromptIntegrationTests.swift; sourceTree = "<group>"; };
+ 5F06B51CF3F45AF989D0CA7F /* ParakeetArchiveInstallerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParakeetArchiveInstallerTests.swift; sourceTree = "<group>"; };
+ 01DEEE85A263FAED9ED5DEF8 /* CompactSpeechModelArchiveTransportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompactSpeechModelArchiveTransportTests.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
@@ -367,6 +395,20 @@
7CDB0A262F3C4D5600FB7CAD /* Helpers */,
7CDB0A272F3C4D5600FB7CAD /* Resources */,
D1C7A7100000000000000001 /* UpdatePromptIntegrationTests.swift */,
+ 4263717D7203AAA6B63D9330 /* SettingsBackupRoundTripTests.swift */,
+ 91C92FF93D3D21E0FD4D93EE /* UpdateRollbackBackupTests.swift */,
+ F12B5FA911AD928DAFD058FB /* UpdateInstallationPipelineTests.swift */,
+ 8E4FCA0BC854678A142D944F /* UpdateAppReplacementTests.swift */,
+ 93E63CD61E6BD954698A8E63 /* UpdateBundleValidatorTests.swift */,
+ 7D47EF42AC1B641A705AC302 /* SpeechModelInstallationSnapshotTests.swift */,
+ 70362FCD2F941BFB800AD8E8 /* ProgressiveFileDownloaderTests.swift */,
+ AFA73C8D5E7647C4AB125DEE /* PronunciationModelRevisionTests.swift */,
+ 16DE344948E4DBF0E1739769 /* ParakeetCompactModelDemoTests.swift */,
+ BC9A7E0C9B501E87114F7A88 /* ParakeetCompactModelSmokeTests.swift */,
+ E3398800F76A93226E76A5C9 /* ParakeetArchiveDownloaderTests.swift */,
+ 01DEEE85A263FAED9ED5DEF8 /* CompactSpeechModelArchiveTransportTests.swift */,
+ 5F06B51CF3F45AF989D0CA7F /* ParakeetArchiveInstallerTests.swift */,
+ 6BF00D40A027DC3970C2D0AE /* ParakeetSpeechModelCatalogTests.swift */,
7CDB0A292F3C4D5600FB7CAD /* DictationE2ETests.swift */,
CD1C7A0000000000000000B1 /* CustomDictionaryManualEntryTests.swift */,
7C91B0022F42AA0100C0DEF0 /* HotkeyShortcutTests.swift */,
@@ -723,6 +765,20 @@
files = (
7CDB0A2E2F3C4D5600FB7CAD /* AudioFixtureLoader.swift in Sources */,
D1C7A7100000000000000002 /* UpdatePromptIntegrationTests.swift in Sources */,
+ 75454216C2DD7BBBB1D76D42 /* SettingsBackupRoundTripTests.swift in Sources */,
+ 24AFD1DFC6BFC9DB5BC6329B /* UpdateRollbackBackupTests.swift in Sources */,
+ 563881F82B15C86EDB50E198 /* UpdateInstallationPipelineTests.swift in Sources */,
+ 7EAA9E7C4E4155A44F9CC415 /* UpdateAppReplacementTests.swift in Sources */,
+ 6AE26D3BB678D13615C41376 /* UpdateBundleValidatorTests.swift in Sources */,
+ 5D4A9F54826FD6BB32CE13F8 /* SpeechModelInstallationSnapshotTests.swift in Sources */,
+ B51B7EE5BA8CE09BC09A47DB /* ProgressiveFileDownloaderTests.swift in Sources */,
+ D63B0F8456B440F1A123B987 /* PronunciationModelRevisionTests.swift in Sources */,
+ 9F12D6C37B0166B549AECB61 /* ParakeetCompactModelDemoTests.swift in Sources */,
+ 209C92C604F912C74A733D21 /* ParakeetCompactModelSmokeTests.swift in Sources */,
+ 67F6BBBA604C996A20BEE7AC /* ParakeetArchiveDownloaderTests.swift in Sources */,
+ 640AB09C7781553DF72D1156 /* CompactSpeechModelArchiveTransportTests.swift in Sources */,
+ C093F64545C6FDD2D79BF559 /* ParakeetArchiveInstallerTests.swift in Sources */,
+ EA91B858DDC9E68655DCA343 /* ParakeetSpeechModelCatalogTests.swift in Sources */,
7CDB0A2D2F3C4D5600FB7CAD /* DictationE2ETests.swift in Sources */,
B52000000000000000000002 /* PrivateAIDictationTokenBudgetTests.swift in Sources */,
CD1C7A0000000000000000B2 /* CustomDictionaryManualEntryTests.swift in Sources */,
@@ -1320,7 +1376,7 @@
repositoryURL = "https://github.com/altic-dev/FluidAudio.git";
requirement = {
kind = revision;
- revision = 09c23cce76126920b3ff6710cdb154bdf9c126b8;
+ revision = eb1e6628998e47022799d305b52c2680d3576801;
};
};
diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index 9121c9bb..ea0494b1 100644
--- a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -32,7 +32,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/altic-dev/FluidAudio.git",
"state" : {
- "revision" : "09c23cce76126920b3ff6710cdb154bdf9c126b8"
+ "revision" : "eb1e6628998e47022799d305b52c2680d3576801"
}
},
{
diff --git a/Package.resolved b/Package.resolved
index ba9dc633..0894533a 100644
--- a/Package.resolved
+++ b/Package.resolved
@@ -31,7 +31,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/altic-dev/FluidAudio.git",
"state" : {
- "revision" : "09c23cce76126920b3ff6710cdb154bdf9c126b8"
+ "revision" : "eb1e6628998e47022799d305b52c2680d3576801"
}
},
{
diff --git a/Package.swift b/Package.swift
index 024ed1e5..f519e403 100644
--- a/Package.swift
+++ b/Package.swift
@@ -11,7 +11,7 @@ let package = Package(
dependencies: [
.package(path: "Vendor/WebRTCAudioProcessing"),
.package(url: "https://github.com/mxcl/AppUpdater.git", from: "1.0.0"),
- .package(url: "https://github.com/altic-dev/FluidAudio.git", revision: "09c23cce76126920b3ff6710cdb154bdf9c126b8"),
+ .package(url: "https://github.com/altic-dev/FluidAudio.git", revision: "eb1e6628998e47022799d305b52c2680d3576801"),
.package(url: "https://github.com/mxcl/PromiseKit", from: "6.0.0"),
.package(url: "https://github.com/altic-dev/DynamicNotchKit.git", revision: "50dc8565469cc80bbbe3c0d5dd902585a2d67986"),
.package(url: "https://github.com/altic-dev/transcribe-cpp-swift.git", exact: "0.1.2"),
@@ -37,6 +37,9 @@ let package = Package(
.product(name: "TranscribeCpp", package: "transcribe-cpp-swift"),
.product(name: "ZeppelinEmbed", package: "zeppelin-embed"),
],
+ resources: [
+ .copy("Resources/speech-model-check.pcm"),
+ ],
linkerSettings: [
.linkedLibrary("sqlite3"),
]
diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swift
index 884c9ead..68e608b9 100644
--- a/Sources/Fluid/AppDelegate.swift
+++ b/Sources/Fluid/AppDelegate.swift
@@ -80,6 +80,12 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
_ = FileLogger.shared
TypingService.startKeyboardLayoutTracking()
_ = TranscriptionHistoryStore.shared
+ #if arch(arm64)
+ Task {
+ await CompactSpeechModelReleaseCatalog.shared.refreshIfNeeded()
+ SpeechModelInstallationSnapshot.shared.refresh()
+ }
+ #endif
#if DEBUG
MeetingDetectorFeasibilityProbe.startIfRequested()
#endif
@@ -107,7 +113,6 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
SettingsStore.shared.bootstrapOnboardingState(isTrueFirstOpen: isTrueFirstOpen)
AnalyticsService.shared.bootstrap()
- SearchIndexCoordinator.shared.start()
// Check for updates automatically if enabled (initial check on launch)
self.checkForUpdatesAutomatically()
@@ -178,7 +183,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
private func closeZeppelinForTermination() {
var didClose = false
Task {
- await FluidZeppelinRoot.shared.closeAll()
+ AppSearchService.shared.stop()
+ await SearchIndexCoordinator.shared.stop()
+ await FluidZeppelinRoot.shared.shutdown()
didClose = true
}
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 533b6df3..6380a96d 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -263,7 +263,10 @@ struct ContentView: View {
/// This maintains backward compatibility with the existing code while
/// removing the duplicate service instances that cause startup crashes.
private var asr: ASRService {
- self.appServices.asr
+ #if DEBUG
+ if let fixture = self.dictationModeSwitchASRForTesting { return fixture }
+ #endif
+ return self.appServices.asr
}
private var audioObserver: AudioHardwareObserver {
@@ -406,7 +409,55 @@ struct ContentView: View {
@State private var columnVisibility: NavigationSplitViewVisibility = .all
@State private var toolbarTrailingInset: CGFloat = 80
+ #if DEBUG
+ private var dictationModeSwitchASRForTesting: ASRService?
+ private var dictationModeSwitchOnReadyForTesting: ((ContentView) -> Void)?
+
+ /// Install real SwiftUI state while avoiding the app page's startup/hardware observers.
+ static func dictationModeSwitchFixture(
+ asr: ASRService,
+ hasActiveMode: Bool = true,
+ onReady: @escaping (ContentView) -> Void
+ ) -> ContentView {
+ let commandFixture = CommandModeService()
+ var view = ContentView()
+ view._commandModeService = StateObject(wrappedValue: commandFixture)
+ view.dictationModeSwitchASRForTesting = asr
+ view.dictationModeSwitchOnReadyForTesting = onReady
+ view._activeRecordingMode = State(initialValue: hasActiveMode ? .edit : .none)
+ view._isRecordingForRewrite = State(initialValue: hasActiveMode)
+ return view
+ }
+
+ func beginDictationModeSwitchForTesting(selection: SettingsStore.DictationPromptSelection? = nil) -> Task<Void, Never>? {
+ if let selection { return self.beginDictationRecording(for: selection, mode: .promptMode) }
+ return self.beginDictationRecording(for: .primary, mode: .dictate)
+ }
+
+ func blockDictationModeSwitchForTesting(savingCancellation: Bool = false, processing: Bool = false) {
+ self.isSavingCancelledRecording = savingCancellation
+ self.processingDictationLifecycleID = processing ? self.overlayLifecycleID : nil
+ }
+
+ var dictationModeSwitchStateForTesting: (mode: String, slot: SettingsStore.DictationShortcutSlot?, generation: UInt64) {
+ (self.activeRecordingMode.rawValue, self.activeDictationShortcutSlot, self.overlayLifecycleID)
+ }
+ #endif
+
+ @ViewBuilder
var body: some View {
+ #if DEBUG
+ if let onReady = self.dictationModeSwitchOnReadyForTesting {
+ Color.clear.onAppear { onReady(self) }
+ } else {
+ self.appBody
+ }
+ #else
+ self.appBody
+ #endif
+ }
+
+ private var appBody: some View {
let layout = AnyView(
Group {
if self.settings.shouldShowOnboarding {
@@ -1490,7 +1541,7 @@ struct ContentView: View {
private func open(searchHit hit: AppSearchHit) {
switch hit.target {
case let .history(id):
- TranscriptionHistoryStore.shared.selectedEntryID = id
+ TranscriptionHistoryStore.shared.selectEntryFromSearch(id: id)
self.navigateToApp(.history)
case let .transcript(id):
FileTranscriptionHistoryStore.shared.selectedEntryID = id
@@ -1997,11 +2048,9 @@ struct ContentView: View {
if self.settings.shouldShowOnboarding {
return .minimum(width: window.onboardingMinWidth, height: window.onboardingMinHeight)
}
- return FluidWindowSizing(
- minWidth: window.mainMinWidth,
- minHeight: window.mainMinHeight,
- maximumSize: NSSize(width: 1440, height: 1000)
- )
+ // Let SwiftUI and the screen choose the upper size; a hard cap can
+ // fight the hosting view's content bounds while switching pages.
+ return .minimum(width: window.mainMinWidth, height: window.mainMinHeight)
}
@ViewBuilder
@@ -5308,17 +5357,29 @@ extension ContentView {
}
}
+ private var canSwitchActiveDictationCaptureMode: Bool {
+ self.activeRecordingMode != .none && self.asr.canSwitchOwnedDictationCaptureMode
+ }
+
+ private func canBeginDictationRecording() -> Bool {
+ guard !self.isSavingCancelledRecording, self.processingDictationLifecycleID == nil else { return false }
+ if self.canSwitchActiveDictationCaptureMode { return true }
+ guard !self.presentExclusiveActivityBlockIfNeeded() else { return false }
+ return !self.asr.isRunningOrStarting && !self.asr.isDictionaryTrainingCaptureActive
+ }
+
private func beginDictationRecording(
for slot: SettingsStore.DictationShortcutSlot,
mode: ActiveRecordingMode,
startMethod: AnalyticsOnboardingTryoutStartMethod = .hotkey
) -> Task<Void, Never>? {
- guard !self.isSavingCancelledRecording, self.processingDictationLifecycleID == nil else { return nil }
- guard !self.presentExclusiveActivityBlockIfNeeded() else { return nil }
+ guard self.canBeginDictationRecording() else { return nil }
+ let switchesOwnedCapture = self.canSwitchActiveDictationCaptureMode
+ let previousMode = self.activeRecordingMode
DebugLogger.shared.debug("Begin dictation recording for slot \(slot.rawValue)", source: "ContentView")
DebugLogger.shared.debug("CLOSE_DETAIL nextStartRequested uptime=\(ProcessInfo.processInfo.systemUptime)", source: "StopTiming")
self.appBench("begin_recording slot=\(slot.rawValue) mode=\(mode.rawValue)")
- if self.isOnboardingVoicePlaygroundStepActive {
+ if !switchesOwnedCapture, self.isOnboardingVoicePlaygroundStepActive {
self.asr.finalText = ""
self.settings.onboardingPlaygroundValidated = false
self.settings.onboardingPlaygroundSkipped = false
@@ -5329,6 +5390,17 @@ extension ContentView {
self.setActiveRecordingMode(mode)
self.rewriteModeService.clearState()
+ if switchesOwnedCapture {
+ if self.asr.showError, self.asr.errorTitle == "Dictation Unavailable",
+ self.asr.errorMessage == "Wait for the active dictation to finish."
+ { self.asr.showError = false }
+ self.menuBarManager.setOverlayMode(.dictation)
+ DebugLogger.shared.info(
+ "Dictation capture mode switched from=\(previousMode.rawValue) to=\(mode.rawValue) slot=\(slot.rawValue)",
+ source: "ContentView"
+ )
+ return nil
+ }
guard !self.asr.isRunningOrStarting else {
self.appBench("asr_start_skipped reason=already_running_or_starting")
return nil
@@ -5383,6 +5455,7 @@ extension ContentView {
}
private func beginDictationRecording(for selection: SettingsStore.DictationPromptSelection, mode: ActiveRecordingMode) -> Task<Void, Never>? {
+ guard self.canBeginDictationRecording() else { return nil }
let settings = SettingsStore.shared
settings.setDictationPromptSelection(selection, for: .secondary)
return self.beginDictationRecording(for: .secondary, mode: mode)
diff --git a/Sources/Fluid/Networking/CompactSpeechModelArchiveTransport.swift b/Sources/Fluid/Networking/CompactSpeechModelArchiveTransport.swift
new file mode 100644
index 00000000..ab2740d8
--- /dev/null
+++ b/Sources/Fluid/Networking/CompactSpeechModelArchiveTransport.swift
@@ -0,0 +1,342 @@
+import Darwin
+import Foundation
+
+/// One resumable archive per compact model. All IO and the advisory claim run off main.
+nonisolated enum CompactSpeechModelArchiveTransport {
+ typealias Progress = @Sendable (Int64, Int64) -> Void
+ typealias ChunkTransport = @Sendable (URLRequest, Int64, @escaping @Sendable (Int64) -> Void) async throws -> (URL, URLResponse)
+ static let rangeBytes: Int64 = 16 * 1024 * 1024
+
+ enum Failure: LocalizedError, Equatable {
+ case invalidDescriptor, invalidRange, alreadyDownloading
+ case unsafePartial(URL)
+
+ var errorDescription: String? {
+ switch self {
+ case .invalidDescriptor: "This compact voice model has no valid pinned download."
+ case let .unsafePartial(url): "Voice model download files are unsafe at \(url.path). Remove that file or folder and try again."
+ case .invalidRange: "The model server returned an invalid download range. Please try again."
+ case .alreadyDownloading: "This voice model is already downloading in another app process. Please try again when it finishes."
+ }
+ }
+ }
+
+ static func download(
+ descriptor: ParakeetSpeechModelCatalog.Descriptor,
+ in modelsDirectory: URL,
+ progress: @escaping Progress,
+ transport: ChunkTransport? = nil,
+ chunkBytes: Int64 = rangeBytes
+ ) async throws -> (URL, URLResponse) {
+ let task = Task.detached(priority: .utility) {
+ try await self.assemble(descriptor: descriptor, in: modelsDirectory, progress: progress, transport: transport, chunkBytes: chunkBytes)
+ }
+ return try await withTaskCancellationHandler {
+ do { return try await task.value } catch {
+ if Task.isCancelled || error is CancellationError { throw CancellationError() }
+ throw error
+ }
+ } onCancel: { task.cancel() }
+ }
+
+ private static func assemble(
+ descriptor: ParakeetSpeechModelCatalog.Descriptor,
+ in modelsDirectory: URL,
+ progress: @escaping Progress,
+ transport: ChunkTransport?,
+ chunkBytes: Int64
+ ) async throws -> (URL, URLResponse) {
+ try Task.checkCancellation()
+ guard descriptor.variant == .mini || descriptor.variant == .pico,
+ descriptor.folderName == ParakeetSpeechModelCatalog.descriptor(for: descriptor.variant).folderName,
+ modelsDirectory.isFileURL,
+ let url = descriptor.archiveURL, url.scheme == "https", url.host == SpeechModelFeed.host,
+ url.port == nil, url.user == nil, url.password == nil,
+ let hash = descriptor.archiveSHA256, self.validHash(hash),
+ descriptor.expectedDownloadBytes > 0, descriptor.expectedDownloadBytes <= 1_000_000_000,
+ chunkBytes > 0, chunkBytes <= self.rangeBytes
+ else { throw Failure.invalidDescriptor }
+ try self.requireDirectory(modelsDirectory)
+ let retainedRoot = modelsDirectory.appendingPathComponent(".compact-downloads", isDirectory: true)
+ try self.createOwnedDirectory(retainedRoot)
+ let directory = retainedRoot.appendingPathComponent(descriptor.folderName, isDirectory: true)
+ try self.createOwnedDirectory(directory)
+ let claim = try Claim(directory.appendingPathComponent("claim.lock"))
+ defer { claim.close() }
+ try self.removeAbandonedReadyArchives(in: directory)
+ let marker = directory.appendingPathComponent("release.sha256")
+ let partial = directory.appendingPathComponent("archive.partial")
+ var completed = try self.preparePartial(partial, marker: marker, hash: hash, total: descriptor.expectedDownloadBytes, chunkBytes: chunkBytes)
+ let transfer: ChunkTransport = transport ?? { request, maximumBytes, progress in
+ try await ChunkLoader.download(request: request, maximumBytes: maximumBytes, progress: progress)
+ }
+ progress(completed, descriptor.expectedDownloadBytes)
+ while completed < descriptor.expectedDownloadBytes {
+ try Task.checkCancellation()
+ let start = completed
+ let end = min(start + chunkBytes, descriptor.expectedDownloadBytes) - 1
+ var request = URLRequest(url: url)
+ request.timeoutInterval = 60
+ request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
+ request.setValue("bytes=\(start)-\(end)", forHTTPHeaderField: "Range")
+ request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
+ var downloaded: URL?
+ do {
+ let (chunk, response) = try await transfer(request, end - start + 1) { bytes in
+ progress(start + max(0, min(bytes, end - start + 1)), descriptor.expectedDownloadBytes)
+ }
+ downloaded = chunk
+ try Task.checkCancellation()
+ guard let response = response as? HTTPURLResponse,
+ response.statusCode == 206, response.url == url,
+ response.value(forHTTPHeaderField: "Content-Range") == "bytes \(start)-\(end)/\(descriptor.expectedDownloadBytes)",
+ response.value(forHTTPHeaderField: "Content-Encoding").map({ $0.lowercased() == "identity" }) ?? true,
+ try self.fileSize(chunk) == end - start + 1
+ else { throw Failure.invalidRange }
+ try self.append(chunk: chunk, to: partial, offset: start)
+ try Task.checkCancellation()
+ completed = end + 1
+ try FileManager.default.removeItem(at: chunk)
+ downloaded = nil
+ progress(completed, descriptor.expectedDownloadBytes)
+ } catch {
+ // Join transport cancellation before touching its file. Only complete ranges survive.
+ if let downloaded { try? FileManager.default.removeItem(at: downloaded) }
+ try self.truncate(partial, to: completed)
+ throw error
+ }
+ }
+ try Task.checkCancellation()
+ // Transfer unique ownership while still holding the claim, so another process
+ // cannot resume or replace a completed file the installer is about to consume.
+ let ready = directory.appendingPathComponent("ready-\(getpid())-\(UUID().uuidString).tar")
+ try FileManager.default.moveItem(at: partial, to: ready)
+ // This 200 represents an assembled file, not an HTTP range response. The outer
+ // installer still verifies its whole size/SHA before any extraction/publication.
+ guard let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["Content-Length": String(descriptor.expectedDownloadBytes)]) else {
+ try? FileManager.default.removeItem(at: ready)
+ throw Failure.invalidRange
+ }
+ return (ready, response)
+ }
+
+ /// A completed handoff may outlive an app exit before the installer consumes it.
+ /// Bound recovery work and never remove another live process's owned handoff.
+ private static func removeAbandonedReadyArchives(in directory: URL) throws {
+ guard let files = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: nil, options: [.skipsSubdirectoryDescendants]) else {
+ throw Failure.unsafePartial(directory)
+ }
+ var inspected = 0
+ for case let file as URL in files {
+ try Task.checkCancellation()
+ inspected += 1
+ guard inspected <= 128 else { break }
+ let name = file.lastPathComponent
+ guard name.hasPrefix("ready-"), name.hasSuffix(".tar") else { continue }
+ let identity = name.dropFirst("ready-".count).dropLast(".tar".count)
+ let parts = identity.split(separator: "-", maxSplits: 1)
+ guard parts.count == 2,
+ let owner = Int32(parts[0]), owner > 0, String(owner) == parts[0],
+ let uuid = UUID(uuidString: String(parts[1])), uuid.uuidString == parts[1],
+ kill(owner, 0) == -1, errno == ESRCH,
+ (try? self.optionalFileSize(file)) != nil
+ else { continue }
+ try FileManager.default.removeItem(at: file)
+ }
+ }
+
+ private static func preparePartial(_ partial: URL, marker: URL, hash: String, total: Int64, chunkBytes: Int64) throws -> Int64 {
+ let manager = FileManager.default
+ let markerSize = try self.optionalFileSize(marker)
+ let partialSize = try self.optionalFileSize(partial)
+ var sameRelease = false
+ if markerSize == 64 {
+ let file = try self.openRegular(marker, flags: O_RDONLY)
+ defer { try? file.close() }
+ let bytes = try file.read(upToCount: 65) ?? Data()
+ if let oldHash = String(data: bytes, encoding: .utf8), self.validHash(oldHash) { sameRelease = oldHash == hash }
+ }
+ if !sameRelease {
+ if partialSize != nil { try manager.removeItem(at: partial) }
+ if markerSize != nil { try manager.removeItem(at: marker) }
+ try Data(hash.utf8).write(to: marker, options: .withoutOverwriting)
+ }
+ var size = sameRelease ? (partialSize ?? 0) : 0
+ if size > total {
+ // A crash/corrupted regular partial must have a bounded Retry recovery.
+ // The claim and no-link checks restrict repair to this model's owned file.
+ try self.truncate(partial, to: 0)
+ size = 0
+ }
+ if try self.optionalFileSize(partial) == nil {
+ guard manager.createFile(atPath: partial.path, contents: nil, attributes: [.posixPermissions: 0o600]) else { throw Failure.unsafePartial(partial) }
+ }
+ let boundary = size == total ? size : (size / chunkBytes) * chunkBytes
+ if boundary != size { try self.truncate(partial, to: boundary) }
+ return boundary
+ }
+
+ private static func append(chunk: URL, to partial: URL, offset: Int64) throws {
+ guard try self.fileSize(partial) == offset else { throw Failure.unsafePartial(partial) }
+ let input = try self.openRegular(chunk, flags: O_RDONLY)
+ defer { try? input.close() }
+ let output = try self.openRegular(partial, flags: O_WRONLY)
+ defer { try? output.close() }
+ try output.seek(toOffset: UInt64(offset))
+ while let bytes = try input.read(upToCount: 1_048_576), !bytes.isEmpty {
+ try Task.checkCancellation()
+ try output.write(contentsOf: bytes)
+ }
+ try output.synchronize()
+ }
+
+ private static func truncate(_ partial: URL, to offset: Int64) throws {
+ let file = try self.openRegular(partial, flags: O_WRONLY)
+ defer { try? file.close() }
+ try file.truncate(atOffset: UInt64(offset))
+ try file.synchronize()
+ }
+
+ private static func openRegular(_ url: URL, flags: Int32) throws -> FileHandle {
+ let descriptor = Darwin.open(url.path, flags | O_NOFOLLOW | O_CLOEXEC)
+ guard descriptor >= 0 else { throw Failure.unsafePartial(url) }
+ var attributes = stat()
+ guard fstat(descriptor, &attributes) == 0, attributes.st_mode & S_IFMT == S_IFREG, attributes.st_nlink == 1 else {
+ Darwin.close(descriptor)
+ throw Failure.unsafePartial(url)
+ }
+ return FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
+ }
+
+ private static func fileSize(_ url: URL) throws -> Int64 {
+ guard let size = try self.optionalFileSize(url) else { throw Failure.unsafePartial(url) }
+ return size
+ }
+
+ private static func optionalFileSize(_ url: URL) throws -> Int64? {
+ var attributes = stat()
+ if lstat(url.path, &attributes) != 0 {
+ if errno == ENOENT { return nil }
+ throw Failure.unsafePartial(url)
+ }
+ guard attributes.st_mode & S_IFMT == S_IFREG, attributes.st_nlink == 1, attributes.st_size >= 0 else { throw Failure.unsafePartial(url) }
+ return attributes.st_size
+ }
+
+ private static func requireDirectory(_ url: URL) throws {
+ var attributes = stat()
+ guard lstat(url.path, &attributes) == 0, attributes.st_mode & S_IFMT == S_IFDIR else { throw Failure.unsafePartial(url) }
+ }
+
+ private static func createOwnedDirectory(_ url: URL) throws {
+ if mkdir(url.path, 0o700) != 0, errno != EEXIST { throw Failure.unsafePartial(url) }
+ try self.requireDirectory(url)
+ }
+
+ private static func validHash(_ hash: String) -> Bool {
+ hash.utf8.count == 64 && hash.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) }
+ }
+
+ private final class Claim {
+ private let descriptor: Int32
+
+ init(_ url: URL) throws {
+ let descriptor = Darwin.open(url.path, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, 0o600)
+ guard descriptor >= 0 else { throw Failure.unsafePartial(url) }
+ var attributes = stat()
+ guard fstat(descriptor, &attributes) == 0, attributes.st_mode & S_IFMT == S_IFREG, attributes.st_nlink == 1 else {
+ Darwin.close(descriptor)
+ throw Failure.unsafePartial(url)
+ }
+ guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {
+ Darwin.close(descriptor)
+ throw Failure.alreadyDownloading
+ }
+ self.descriptor = descriptor
+ }
+
+ func close() { flock(self.descriptor, LOCK_UN); Darwin.close(self.descriptor) }
+ }
+
+ /// Completion joins URLSession's didComplete callback; cancellation never races deletion.
+ private final class ChunkLoader: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
+ private let maximumBytes: Int64
+ private let progress: @Sendable (Int64) -> Void
+ private let lock = NSLock()
+ private var continuation: CheckedContinuation<(URL, URLResponse), Error>?
+ private var task: URLSessionDownloadTask?
+ private var session: URLSession?
+ private var result: Result<(URL, URLResponse), Error>?
+ private var canceled = false
+ private var exceededLimit = false
+
+ init(maximumBytes: Int64, progress: @escaping @Sendable (Int64) -> Void) {
+ self.maximumBytes = maximumBytes
+ self.progress = progress
+ }
+
+ static func download(request: URLRequest, maximumBytes: Int64, progress: @escaping @Sendable (Int64) -> Void) async throws -> (URL, URLResponse) {
+ let loader = ChunkLoader(maximumBytes: maximumBytes, progress: progress)
+ return try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { loader.start(request, continuation: $0) }
+ } onCancel: { loader.cancel() }
+ }
+
+ private func start(_ request: URLRequest, continuation: CheckedContinuation<(URL, URLResponse), Error>) {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = 60
+ configuration.timeoutIntervalForResource = 600
+ let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
+ let task = session.downloadTask(with: request)
+ let canceled = self.lock.withLock {
+ self.continuation = continuation
+ self.session = session
+ self.task = task
+ return self.canceled
+ }
+ task.resume()
+ if canceled { task.cancel() }
+ }
+
+ private func cancel() {
+ let task = self.lock.withLock { self.canceled = true; return self.task }
+ task?.cancel()
+ }
+
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
+ completionHandler(nil)
+ }
+
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
+ guard totalBytesWritten <= self.maximumBytes, totalBytesExpectedToWrite <= self.maximumBytes else {
+ self.lock.withLock { self.exceededLimit = true }
+ downloadTask.cancel()
+ return
+ }
+ self.progress(totalBytesWritten)
+ }
+
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
+ let result: Result<(URL, URLResponse), Error>
+ do {
+ guard let response = downloadTask.response, try CompactSpeechModelArchiveTransport.fileSize(location) <= self.maximumBytes else { throw Failure.invalidRange }
+ result = try .success((ProgressiveFileDownloader.retainDownloadedFile(at: location), response))
+ } catch { result = .failure(error) }
+ self.lock.withLock { self.result = result }
+ }
+
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+ let (continuation, result, exceededLimit) = self.lock.withLock {
+ defer { self.continuation = nil; self.result = nil; self.task = nil; self.session = nil }
+ return (self.continuation, self.result, self.exceededLimit)
+ }
+ session.finishTasksAndInvalidate()
+ if let error {
+ if case let .success((url, _)) = result { try? FileManager.default.removeItem(at: url) }
+ continuation?.resume(throwing: exceededLimit ? URLError(.dataLengthExceedsMaximum) : error)
+ } else {
+ continuation?.resume(with: result ?? .failure(Failure.invalidRange))
+ }
+ }
+ }
+}
diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swift
index f06ea13b..be80880c 100644
--- a/Sources/Fluid/Networking/ModelDownloader.swift
+++ b/Sources/Fluid/Networking/ModelDownloader.swift
@@ -14,7 +14,7 @@ final class HuggingFaceModelDownloader {
let size: Int64?
}
- struct ModelItem {
+ nonisolated struct ModelItem: Sendable {
let path: String
let isDirectory: Bool
}
@@ -324,7 +324,7 @@ final class HuggingFaceModelDownloader {
}
}
- static func artifactsAreComplete(root: URL, items: [ModelItem]) -> Bool {
+ nonisolated static func artifactsAreComplete(root: URL, items: [ModelItem]) -> Bool {
items.allSatisfy { item in
Self.artifactIsComplete(
at: root.appendingPathComponent(item.path, isDirectory: item.isDirectory),
@@ -333,7 +333,7 @@ final class HuggingFaceModelDownloader {
}
}
- static func artifactIsComplete(at url: URL, isDirectory: Bool) -> Bool {
+ nonisolated static func artifactIsComplete(at url: URL, isDirectory: Bool) -> Bool {
guard isDirectory else { return self.fileHasContents(at: url) }
if url.pathExtension == "mlpackage" {
@@ -386,7 +386,7 @@ final class HuggingFaceModelDownloader {
return false
}
- private static func fileHasContents(at url: URL) -> Bool {
+ private nonisolated static func fileHasContents(at url: URL) -> Bool {
guard
let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
let type = attributes[.type] as? FileAttributeType,
@@ -464,7 +464,7 @@ final class HuggingFaceModelDownloader {
/// only 512 bytes are read). There is no `URLResponse` for a cached file, so only the
/// content is inspected, not a `Content-Type`. Returns `false` (treat as valid) on any
/// read error, so an unreadable file is never deleted on uncertainty.
- static func cachedFileIsMarkup(at fileURL: URL) -> Bool {
+ nonisolated static func cachedFileIsMarkup(at fileURL: URL) -> Bool {
guard let handle = try? FileHandle(forReadingFrom: fileURL) else {
return false
}
@@ -531,7 +531,7 @@ final class HuggingFaceModelDownloader {
/// catches `<!doctype`, `<html`, `<head>`, `<body>`, `<script>`, `<meta>`, comments
/// (`<!-- -->`) and XML / `<?xml` declarations, not just the two prefixes we used to
/// match. See issue #353.
- static func looksLikeHTML(_ data: Data) -> Bool {
+ nonisolated static func looksLikeHTML(_ data: Data) -> Bool {
var bytes = [UInt8](data.prefix(512))
if bytes.starts(with: [0xef, 0xbb, 0xbf]) {
bytes.removeFirst(3)
@@ -644,19 +644,23 @@ final nonisolated class ProgressiveFileDownloader: @unchecked Sendable {
}
}
- private final class Delegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
+ final class Delegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
typealias Completion = @Sendable (Result<(URL, URLResponse), Error>) -> Void
private let onProgress: @Sendable (Int64, Int64) -> Void
+ private let maximumBytes: Int64?
private let lock = NSLock()
private var completion: Completion?
private var downloadResult: Result<(URL, URLResponse), Error>?
+ private var exceededByteLimit = false
weak var session: URLSession?
init(
+ maximumBytes: Int64?,
onProgress: @escaping @Sendable (Int64, Int64) -> Void,
completion: @escaping Completion
) {
+ self.maximumBytes = maximumBytes
self.onProgress = onProgress
self.completion = completion
}
@@ -668,6 +672,11 @@ final nonisolated class ProgressiveFileDownloader: @unchecked Sendable {
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64
) {
+ if let maximumBytes, totalBytesWritten > maximumBytes || totalBytesExpectedToWrite > maximumBytes {
+ self.lock.withLock { self.exceededByteLimit = true }
+ downloadTask.cancel()
+ return
+ }
self.onProgress(totalBytesWritten, totalBytesExpectedToWrite)
}
@@ -681,11 +690,26 @@ final nonisolated class ProgressiveFileDownloader: @unchecked Sendable {
return
}
+ self.retainDownload(at: location, response: response)
+ }
+
+ @discardableResult
+ func retainDownload(at location: URL, response: URLResponse) -> URL? {
do {
+ if let maximumBytes {
+ let attributes = try FileManager.default.attributesOfItem(atPath: location.path)
+ guard let size = attributes[.size] as? NSNumber, size.int64Value <= maximumBytes else {
+ self.lock.withLock { self.exceededByteLimit = true }
+ self.storeResult(.failure(URLError(.dataLengthExceedsMaximum)))
+ return nil
+ }
+ }
let retainedURL = try ProgressiveFileDownloader.retainDownloadedFile(at: location)
self.storeResult(.success((retainedURL, response)))
+ return retainedURL
} catch {
self.storeResult(.failure(error))
+ return nil
}
}
@@ -695,7 +719,14 @@ final nonisolated class ProgressiveFileDownloader: @unchecked Sendable {
didCompleteWithError error: Error?
) {
if let error {
- self.finish(.failure(error))
+ let retainedFile = self.lock.withLock { () -> URL? in
+ defer { self.downloadResult = nil }
+ if case let .success((url, _)) = self.downloadResult { return url }
+ return nil
+ }
+ if let retainedFile { try? FileManager.default.removeItem(at: retainedFile) }
+ let exceedsLimit = self.lock.withLock { self.exceededByteLimit }
+ self.finish(.failure(exceedsLimit ? URLError(.dataLengthExceedsMaximum) : error))
} else {
let result = self.lock.withLock { self.downloadResult }
self.finish(result ?? .failure(URLError(.badServerResponse)))
@@ -731,12 +762,14 @@ final nonisolated class ProgressiveFileDownloader: @unchecked Sendable {
static func download(
from url: URL,
configuration: URLSessionConfiguration,
+ maximumBytes: Int64? = nil,
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(
+ maximumBytes: maximumBytes,
onProgress: onProgress,
completion: { continuation.resume(with: $0) }
)
diff --git a/Sources/Fluid/Networking/ParakeetArchiveDownloader.swift b/Sources/Fluid/Networking/ParakeetArchiveDownloader.swift
new file mode 100644
index 00000000..cbd7278a
--- /dev/null
+++ b/Sources/Fluid/Networking/ParakeetArchiveDownloader.swift
@@ -0,0 +1,308 @@
+import Darwin
+import Foundation
+
+/// Installs only the descriptor's hash-pinned archive, without changing model selection.
+nonisolated enum ParakeetArchiveDownloader {
+ typealias Transport = @Sendable (URL, @escaping @Sendable (Int64, Int64) -> Void) async throws -> (URL, URLResponse)
+ typealias RevisionWriter = @Sendable (URL, ParakeetSpeechModelCatalog.Descriptor) throws -> Void
+ typealias CapacityReader = @Sendable (URL) throws -> Int64
+ typealias StageValidator = @Sendable (URL) async throws -> Void
+ private static let publicationLock = NSLock()
+
+ private struct InstallationIO: Sendable {
+ let transport: Transport?
+ let capacityReader: CapacityReader?
+ let revisionWriter: RevisionWriter
+ }
+
+ private struct InstalledIdentity: Equatable {
+ let device: UInt64
+ let inode: UInt64
+ let revision: String
+ }
+
+ enum DownloadError: LocalizedError {
+ case invalidDescriptor, invalidResponse, checksumMismatch, invalidArchive, incompleteModel, targetExists
+ case cleanupFailed(URL)
+ case targetChanged
+ case capacityUnavailable
+ case insufficientSpace(required: Int64, available: Int64)
+ case replacementCleanupFailed(installed: URL, retainedOld: URL)
+ case updateFailedWithCleanup(reason: String, installed: URL, temporaryFiles: URL)
+
+ var errorDescription: String? {
+ switch self {
+ case .invalidDescriptor: return "This voice model has no valid pinned download."
+ case .invalidResponse: return "The model server did not return the expected archive. Please try again."
+ case .checksumMismatch: return "The downloaded voice model failed verification. Please try again."
+ case .invalidArchive: return "The voice model archive contains invalid or unsafe files."
+ case .incompleteModel: return "The voice model archive is incomplete."
+ case .targetExists: return "A different or incomplete voice model is already cached. Delete this model in Voice Engine settings, then download it again."
+ case let .cleanupFailed(url): return "Voice model temporary files could not be removed: \(url.path)"
+ case .capacityUnavailable: return "Available disk space could not be checked. Your installed model was kept. Please try again."
+ case .insufficientSpace: return "There is not enough free disk space to safely update this voice model. Free some space and try again. Your installed model was kept."
+ case .targetChanged: return "The installed voice model changed during this update. Its files were preserved. Please try again."
+ case let .replacementCleanupFailed(installed, retainedOld): return "The updated voice model is installed at \(installed.path), but its old files could not be removed: \(retainedOld.path)"
+ case let .updateFailedWithCleanup(reason, installed, temporaryFiles):
+ return "The voice model update failed: \(reason). "
+ + "This update did not replace the installed model at \(installed.path). "
+ + "Temporary files could not be removed: \(temporaryFiles.path)"
+ }
+ }
+ }
+
+ static func ensurePresent(
+ descriptor: ParakeetSpeechModelCatalog.Descriptor,
+ in modelsDirectory: URL,
+ progressHandler: @escaping @Sendable (ModelPreparationProgress) -> Void = { _ in },
+ replaceExisting: Bool = false,
+ stageValidator: StageValidator? = nil,
+ transport: Transport? = nil,
+ capacityReader: CapacityReader? = nil,
+ revisionWriter: @escaping RevisionWriter = { directory, descriptor in try descriptor.writeInstallationRevision(at: directory) }
+ ) async throws -> URL {
+ let task = Task.detached(priority: .utility) {
+ try await self.install(
+ descriptor: descriptor,
+ modelsDirectory: modelsDirectory,
+ progressHandler: progressHandler,
+ replaceExisting: replaceExisting,
+ stageValidator: stageValidator,
+ io: InstallationIO(transport: transport, capacityReader: capacityReader, revisionWriter: revisionWriter)
+ )
+ }
+ return try await withTaskCancellationHandler {
+ try await task.value
+ } onCancel: {
+ task.cancel()
+ }
+ }
+
+ static func isCleanupFailure(_ error: Error) -> Bool {
+ guard let failure = error as? DownloadError else { return false }
+ if case .cleanupFailed = failure { return true }
+ if case .replacementCleanupFailed = failure { return true }
+ if case .updateFailedWithCleanup = failure { return true }
+ return false
+ }
+
+ private static func install(
+ descriptor: ParakeetSpeechModelCatalog.Descriptor,
+ modelsDirectory: URL,
+ progressHandler: @escaping @Sendable (ModelPreparationProgress) -> Void,
+ replaceExisting: Bool,
+ stageValidator: StageValidator?,
+ io: InstallationIO
+ ) async throws -> URL {
+ let transport = io.transport
+ let capacityReader = io.capacityReader
+ let revisionWriter = io.revisionWriter
+ try Task.checkCancellation()
+ guard self.isComponent(descriptor.folderName), self.isComponent(descriptor.vocabularyFile),
+ !descriptor.requiredModelNames.isEmpty,
+ descriptor.requiredModelNames.allSatisfy(self.isComponent),
+ Set(descriptor.requiredModelNames).count == descriptor.requiredModelNames.count,
+ modelsDirectory.isFileURL
+ else { throw DownloadError.invalidDescriptor }
+ let manager = FileManager.default
+ let target = descriptor.cacheDirectory(in: modelsDirectory)
+ if self.pathExists(modelsDirectory) { try self.requireDirectory(modelsDirectory) }
+ if self.artifactsAreComplete(at: target, descriptor: descriptor) {
+ progressHandler(.loading)
+ return target
+ }
+ guard let archiveURL = descriptor.archiveURL, archiveURL.scheme == "https", archiveURL.host != nil,
+ let checksum = descriptor.archiveSHA256,
+ checksum.count == 64, checksum.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }),
+ descriptor.expectedDownloadBytes > 0, descriptor.expectedDownloadBytes <= 1_073_741_824
+ else { throw DownloadError.invalidDescriptor }
+ try manager.createDirectory(at: modelsDirectory, withIntermediateDirectories: true)
+ try self.requireDirectory(modelsDirectory)
+ let original: InstalledIdentity?
+ if self.pathExists(target) {
+ guard replaceExisting else { throw DownloadError.targetExists }
+ original = try self.installedIdentity(at: target, descriptor: descriptor)
+ } else {
+ original = nil
+ }
+ // The old model already consumes disk space; reserve both the tar and its unpacked copy.
+ // Runs inside this detached installer, before transport or private staging is created.
+ let headroom: Int64 = 32 * 1024 * 1024
+ let required = descriptor.expectedDownloadBytes * 2 + headroom
+ let available: Int64
+ do {
+ available = try (capacityReader ?? self.availableCapacity)(modelsDirectory)
+ } catch {
+ try Task.checkCancellation()
+ throw DownloadError.capacityUnavailable
+ }
+ guard available >= 0 else { throw DownloadError.capacityUnavailable }
+ guard available >= required else { throw DownloadError.insufficientSpace(required: required, available: available) }
+ try Task.checkCancellation()
+ let stage = modelsDirectory.appendingPathComponent(".\(descriptor.folderName)-\(UUID().uuidString).staging", isDirectory: true)
+ try manager.createDirectory(at: stage, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
+ var retainedDownload: URL?
+ do {
+ progressHandler(.preparingDownload)
+ let transfer: Transport = transport ?? { _, progress in
+ try await CompactSpeechModelArchiveTransport.download(descriptor: descriptor, in: modelsDirectory, progress: progress)
+ }
+ let (downloaded, response) = try await transfer(archiveURL) { bytes, _ in
+ let bounded = max(0, min(bytes, descriptor.expectedDownloadBytes))
+ progressHandler(.downloading(Double(bounded) / Double(descriptor.expectedDownloadBytes)))
+ }
+ retainedDownload = downloaded
+ try Task.checkCancellation()
+ guard let response = response as? HTTPURLResponse, response.statusCode == 200,
+ response.url?.scheme == "https",
+ try self.regularFileSize(downloaded) == descriptor.expectedDownloadBytes
+ else { throw DownloadError.invalidResponse }
+ let archive = stage.appendingPathComponent("archive.tar")
+ try manager.moveItem(at: downloaded, to: archive)
+ retainedDownload = nil
+ guard try self.sha256(archive) == checksum else { throw DownloadError.checksumMismatch }
+ progressHandler(.optimizing)
+ let extraction = stage.appendingPathComponent("extracted", isDirectory: true)
+ let extracted = try ParakeetArchiveInstaller.unpack(
+ archive: archive,
+ folderName: descriptor.folderName,
+ staging: extraction,
+ manifestSHA256: descriptor.manifestSHA256
+ )
+ guard self.contentsAreComplete(at: extracted, descriptor: descriptor) else { throw DownloadError.incompleteModel }
+ try Task.checkCancellation()
+ try revisionWriter(extracted, descriptor)
+ try Task.checkCancellation()
+ guard self.artifactsAreComplete(at: extracted, descriptor: descriptor) else { throw DownloadError.incompleteModel }
+ if let stageValidator { try await stageValidator(extracted) }
+ try Task.checkCancellation()
+ guard self.artifactsAreComplete(at: extracted, descriptor: descriptor) else { throw DownloadError.incompleteModel }
+ // Serialize only publication, not transfers or Core ML validation. Identity
+ // and revision checks reject a competing completed update in this process.
+ try self.publicationLock.withLock {
+ try Task.checkCancellation()
+ try self.requireDirectory(modelsDirectory)
+ if let original {
+ guard try self.installedIdentity(at: target, descriptor: descriptor) == original else { throw DownloadError.targetChanged }
+ }
+ let result = extracted.withUnsafeFileSystemRepresentation { source in
+ target.withUnsafeFileSystemRepresentation { destination in
+ renameatx_np(AT_FDCWD, source, AT_FDCWD, destination, UInt32(original == nil ? RENAME_EXCL : RENAME_SWAP))
+ }
+ }
+ guard result == 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
+ }
+ } catch {
+ let originalError = error
+ var failedTemporaryURL: URL?
+ if let retainedDownload {
+ do { try manager.removeItem(at: retainedDownload) } catch { failedTemporaryURL = retainedDownload }
+ }
+ do { try manager.removeItem(at: stage) } catch { failedTemporaryURL = stage }
+ if let failedTemporaryURL {
+ if original != nil {
+ throw DownloadError.updateFailedWithCleanup(reason: originalError.localizedDescription, installed: target, temporaryFiles: failedTemporaryURL)
+ }
+ throw DownloadError.cleanupFailed(failedTemporaryURL)
+ }
+ throw originalError
+ }
+ do { try manager.removeItem(at: stage) } catch {
+ if original != nil { throw DownloadError.replacementCleanupFailed(installed: target, retainedOld: stage) }
+ throw DownloadError.cleanupFailed(stage)
+ }
+ progressHandler(.loading)
+ return target
+ }
+
+ private static func availableCapacity(at directory: URL) throws -> Int64 {
+ if let capacity = try? directory.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage,
+ capacity >= 0 { return capacity }
+ let attributes = try FileManager.default.attributesOfFileSystem(forPath: directory.path)
+ guard let bytes = attributes[.systemFreeSize] as? NSNumber, bytes.int64Value >= 0 else {
+ throw DownloadError.capacityUnavailable
+ }
+ return bytes.int64Value
+ }
+
+ private static func installedIdentity(at directory: URL, descriptor: ParakeetSpeechModelCatalog.Descriptor) throws -> InstalledIdentity {
+ guard let revision = descriptor.installedArchiveSHA256(at: directory),
+ self.contentsAreComplete(at: directory, descriptor: descriptor),
+ let attributes = try? FileManager.default.attributesOfItem(atPath: directory.path),
+ let device = attributes[.systemNumber] as? NSNumber,
+ let inode = attributes[.systemFileNumber] as? NSNumber
+ else {
+ try Task.checkCancellation()
+ throw DownloadError.targetChanged
+ }
+ return InstalledIdentity(device: device.uint64Value, inode: inode.uint64Value, revision: revision)
+ }
+
+ /// Mirrors compiled-artifact readiness while rejecting links anywhere in the tree.
+ static func artifactsAreComplete(at directory: URL, descriptor: ParakeetSpeechModelCatalog.Descriptor) -> Bool {
+ guard descriptor.installationRevisionMatches(at: directory),
+ self.contentsAreComplete(at: directory, descriptor: descriptor)
+ else { return false }
+ if let manifestSHA256 = descriptor.manifestSHA256 {
+ return descriptor.installedManifestSHA256(at: directory) == manifestSHA256
+ }
+ return true
+ }
+
+ private static func contentsAreComplete(at directory: URL, descriptor: ParakeetSpeechModelCatalog.Descriptor) -> Bool {
+ do {
+ try Task.checkCancellation()
+ try self.requireDirectory(directory)
+ let manager = FileManager.default
+ var enumerationFailed = false
+ guard let enumerator = manager.enumerator(at: directory, includingPropertiesForKeys: nil, options: [], errorHandler: { _, _ in
+ enumerationFailed = true
+ return false
+ }) else { return false }
+ var count = 0
+ for case let url as URL in enumerator {
+ try Task.checkCancellation()
+ count += 1
+ guard count <= 50_000 else { return false }
+ let type = try manager.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType
+ guard type == .typeDirectory || type == .typeRegular else { return false }
+ }
+ guard !enumerationFailed else { return false }
+ guard try self.regularFileSize(directory.appendingPathComponent(descriptor.vocabularyFile)) > 0 else { return false }
+ for name in descriptor.requiredModelNames {
+ let model = directory.appendingPathComponent(name, isDirectory: true)
+ try self.requireDirectory(model)
+ for file in ["coremldata.bin", "metadata.json", "weights/weight.bin"] {
+ guard try self.regularFileSize(model.appendingPathComponent(file)) > 0 else { return false }
+ }
+ }
+ return true
+ } catch { return false }
+ }
+
+ private static func isComponent(_ name: String) -> Bool {
+ !name.isEmpty && name != "." && name != ".." && !name.contains("/") && !name.contains("\0")
+ }
+
+ private static func pathExists(_ url: URL) -> Bool {
+ (try? FileManager.default.attributesOfItem(atPath: url.path)) != nil
+ }
+
+ private static func requireDirectory(_ url: URL) throws {
+ guard try FileManager.default.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType == .typeDirectory else {
+ throw DownloadError.invalidArchive
+ }
+ }
+
+ private static func regularFileSize(_ url: URL) throws -> Int64 {
+ let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
+ guard attributes[.type] as? FileAttributeType == .typeRegular, let size = attributes[.size] as? NSNumber else {
+ throw DownloadError.invalidArchive
+ }
+ return size.int64Value
+ }
+
+ private static func sha256(_ url: URL) throws -> String {
+ try ParakeetArchiveInstaller.sha256(of: url)
+ }
+}
diff --git a/Sources/Fluid/Networking/ParakeetArchiveInstaller.swift b/Sources/Fluid/Networking/ParakeetArchiveInstaller.swift
new file mode 100644
index 00000000..7287c13f
--- /dev/null
+++ b/Sources/Fluid/Networking/ParakeetArchiveInstaller.swift
@@ -0,0 +1,326 @@
+import CryptoKit
+import Foundation
+
+/// Canonical iPhone/publisher archive checks, with bounded Mac staging and cancellation checks.
+/// Mac publication remains in ParakeetArchiveDownloader so a validated update uses an atomic swap.
+nonisolated enum ParakeetArchiveInstaller {
+ private static let maximumManifestBytes: Int64 = 1_048_576
+ private static let maximumFiles = 50_000
+ private static let maximumPayloadBytes: Int64 = 1_073_741_824
+
+ private struct Manifest: Decodable {
+ struct File: Decodable {
+ let path: String
+ let size: Int64
+ let sha256: String
+ }
+
+ let folderName: String
+ let totalSize: Int64
+ let files: [File]
+ }
+
+ enum InstallError: LocalizedError, Equatable {
+ case invalidStaging
+ case missingFolder
+ case manifestMismatch
+ case fileMismatch(String)
+ case unlistedFile(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .invalidStaging: "The model staging folder is not safe to use."
+ case .missingFolder: "The downloaded model is incomplete."
+ case .manifestMismatch: "The downloaded model is not the expected release."
+ case let .fileMismatch(path): "The downloaded model failed verification (\(path))."
+ case let .unlistedFile(path): "The downloaded model holds an unexpected file (\(path))."
+ }
+ }
+ }
+
+ /// Unpacks into `staging` and returns the model folder. With a manifest hash, every file is proven against it.
+ static func unpack(archive: URL, folderName: String, staging: URL, manifestSHA256: String?) throws -> URL {
+ try Task.checkCancellation()
+ let fileManager = FileManager.default
+ guard staging.isFileURL, self.isComponent(folderName),
+ (try? fileManager.attributesOfItem(atPath: staging.path)) == nil,
+ try fileManager.attributesOfItem(atPath: staging.deletingLastPathComponent().path)[.type]
+ as? FileAttributeType == .typeDirectory
+ else { throw InstallError.invalidStaging }
+ // Only a new, private staging folder may be unpacked. Never remove a caller's existing cache.
+ try fileManager.createDirectory(at: staging, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
+ try TarExtractor.extract(archive: archive, to: staging)
+
+ let extracted = staging.appendingPathComponent(folderName, isDirectory: true)
+ guard (try? fileManager.attributesOfItem(atPath: extracted.path)[.type] as? FileAttributeType) == .typeDirectory,
+ try fileManager.contentsOfDirectory(atPath: staging.path) == [folderName]
+ else { throw InstallError.missingFolder }
+ if let manifestSHA256 {
+ try self.verify(folder: extracted, folderName: folderName, manifestSHA256: manifestSHA256)
+ }
+ return extracted
+ }
+
+ static func verify(folder: URL, folderName: String, manifestSHA256: String) throws {
+ try Task.checkCancellation()
+ let manager = FileManager.default
+ guard self.isComponent(folderName), self.isSHA256(manifestSHA256),
+ (try? manager.attributesOfItem(atPath: folder.path)[.type] as? FileAttributeType) == .typeDirectory
+ else { throw InstallError.manifestMismatch }
+ let manifestURL = folder.appendingPathComponent("manifest.json")
+ guard let attributes = try? manager.attributesOfItem(atPath: manifestURL.path),
+ attributes[.type] as? FileAttributeType == .typeRegular,
+ let size = attributes[.size] as? NSNumber,
+ size.int64Value > 0, size.int64Value <= maximumManifestBytes,
+ try sha256(of: manifestURL) == manifestSHA256,
+ let manifest = try? JSONDecoder().decode(Manifest.self, from: Data(contentsOf: manifestURL)),
+ manifest.folderName == folderName,
+ manifest.files.count <= maximumFiles,
+ manifest.totalSize >= 0, manifest.totalSize <= maximumPayloadBytes
+ else { throw InstallError.manifestMismatch }
+
+ var total: Int64 = 0
+ for file in manifest.files {
+ try Task.checkCancellation()
+ guard file.size >= 0, file.size <= self.maximumPayloadBytes - total else { throw InstallError.manifestMismatch }
+ total += file.size
+ }
+ guard total == manifest.totalSize else { throw InstallError.manifestMismatch }
+
+ // Check the complete tree before any payload hash; standalone verification must not follow cache links.
+ // Relative filenames avoid Foundation's /var versus /private/var URL aliases.
+ // Never resolve child links: inspect their actual type before reading any payload.
+ var enumerationFailed = false
+ guard let enumerator = manager.enumerator(
+ at: folder,
+ includingPropertiesForKeys: nil,
+ options: .producesRelativePathURLs,
+ errorHandler: { _, _ in enumerationFailed = true; return false }
+ ) else { throw InstallError.manifestMismatch }
+ var regularFiles: [String] = []
+ var count = 0
+ for case let url as URL in enumerator {
+ let relativePath = url.relativePath
+ try Task.checkCancellation()
+ count += 1
+ guard count <= self.maximumFiles else { throw InstallError.manifestMismatch }
+ let type = try manager.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType
+ guard type == .typeRegular || type == .typeDirectory else { throw InstallError.fileMismatch(url.lastPathComponent) }
+ if type == .typeRegular { regularFiles.append(relativePath) }
+ }
+
+ guard !enumerationFailed else { throw InstallError.manifestMismatch }
+
+ var listed = Set<String>()
+ for file in manifest.files {
+ try Task.checkCancellation()
+ let components = file.path.split(separator: "/", omittingEmptySubsequences: false)
+ guard !components.isEmpty, components.allSatisfy({ self.isComponent(String($0)) }),
+ self.isSHA256(file.sha256), listed.insert(file.path).inserted
+ else { throw InstallError.fileMismatch(file.path) }
+ let url = folder.appendingPathComponent(file.path, isDirectory: false)
+ let attributes = try? manager.attributesOfItem(atPath: url.path)
+ guard attributes?[.type] as? FileAttributeType == .typeRegular,
+ (attributes?[.size] as? NSNumber)?.int64Value == file.size,
+ try self.sha256(of: url) == file.sha256
+ else { throw InstallError.fileMismatch(file.path) }
+ }
+ for path in regularFiles {
+ guard path == "manifest.json" || listed.contains(path) else { throw InstallError.unlistedFile(path) }
+ }
+ }
+
+ private static func isComponent(_ name: String) -> Bool {
+ !name.isEmpty && name != "." && name != ".." && !name.contains("/") && !name.contains("\0")
+ }
+
+ private static func isSHA256(_ value: String) -> Bool {
+ value.count == 64 && value.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) }
+ }
+
+ static func previousURL(for target: URL) -> URL {
+ target.deletingLastPathComponent()
+ .appendingPathComponent(".\(target.lastPathComponent)-previous", isDirectory: true)
+ }
+
+ /// Puts `extracted` at `target`. With `keepPrevious` the model already there is parked, not deleted,
+ /// until the new one has proven itself.
+ static func swap(extracted: URL, target: URL, keepPrevious: Bool) throws {
+ let fileManager = FileManager.default
+ let previous = self.previousURL(for: target)
+ let hadModel = fileManager.fileExists(atPath: target.path)
+ if hadModel {
+ if keepPrevious {
+ if fileManager.fileExists(atPath: previous.path) {
+ try fileManager.removeItem(at: previous)
+ }
+ try fileManager.moveItem(at: target, to: previous)
+ } else {
+ try fileManager.removeItem(at: target)
+ }
+ }
+ do {
+ try fileManager.moveItem(at: extracted, to: target)
+ } catch {
+ if hadModel, keepPrevious {
+ try? fileManager.moveItem(at: previous, to: target)
+ }
+ throw error
+ }
+ }
+
+ static func hasPrevious(for target: URL) -> Bool {
+ FileManager.default.fileExists(atPath: self.previousURL(for: target).path)
+ }
+
+ /// Throws away the model at `target` and puts the parked one back.
+ static func restorePrevious(for target: URL) throws {
+ let fileManager = FileManager.default
+ let previous = self.previousURL(for: target)
+ guard fileManager.fileExists(atPath: previous.path) else { return }
+ if fileManager.fileExists(atPath: target.path) {
+ try fileManager.removeItem(at: target)
+ }
+ try fileManager.moveItem(at: previous, to: target)
+ }
+
+ static func discardPrevious(for target: URL) {
+ try? FileManager.default.removeItem(at: self.previousURL(for: target))
+ }
+
+ static func sha256(of file: URL) throws -> String {
+ let handle = try FileHandle(forReadingFrom: file)
+ defer { try? handle.close() }
+ var hasher = SHA256()
+ while true {
+ try Task.checkCancellation()
+ guard let data = try handle.read(upToCount: 1_048_576), !data.isEmpty else { break }
+ hasher.update(data: data)
+ }
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ }
+}
+
+nonisolated enum TarExtractor {
+ static func extract(archive: URL, to destination: URL) throws {
+ let manager = FileManager.default
+ guard (try? manager.attributesOfItem(atPath: destination.path)[.type] as? FileAttributeType) == .typeDirectory,
+ try manager.contentsOfDirectory(atPath: destination.path).isEmpty,
+ let archiveAttributes = try? manager.attributesOfItem(atPath: archive.path),
+ archiveAttributes[.type] as? FileAttributeType == .typeRegular,
+ let archiveBytes = archiveAttributes[.size] as? NSNumber,
+ archiveBytes.int64Value >= 512, archiveBytes.int64Value <= 1_073_741_824
+ else { throw Error.truncatedArchive }
+ let input = try FileHandle(forReadingFrom: archive)
+ defer { try? input.close() }
+
+ var entryCount = 0
+ while true {
+ try Task.checkCancellation()
+ guard let headerData = try input.read(upToCount: 512), headerData.count == 512 else {
+ throw Error.truncatedArchive
+ }
+ let header = [UInt8](headerData)
+ if header.allSatisfy({ $0 == 0 }) {
+ return
+ }
+
+ entryCount += 1
+ guard entryCount <= 50_000,
+ try self.octal(in: header, range: 148..<156) == header.enumerated().reduce(Int64(0), {
+ $0 + Int64((148..<156).contains($1.offset) ? 32 : $1.element)
+ })
+ else { throw Error.unsupportedEntry }
+ let name = try string(in: header, range: 0..<100)
+ let prefix = try string(in: header, range: 345..<500)
+ let relativePath = prefix.isEmpty ? name : "\(prefix)/\(name)"
+ let output = try safeOutputURL(relativePath: relativePath, destination: destination)
+ let size = try octal(in: header, range: 124..<136)
+ let type = header[156]
+ let offset = try input.offset()
+ let padding = (512 - (size % 512)) % 512
+ guard size >= 0, offset <= archiveBytes.uint64Value,
+ UInt64(size) <= archiveBytes.uint64Value - offset,
+ UInt64(padding) <= archiveBytes.uint64Value - offset - UInt64(size)
+ else { throw Error.truncatedArchive }
+
+ switch type {
+ case 0, 48:
+ guard (try? manager.attributesOfItem(atPath: output.path)) == nil else { throw Error.unsupportedEntry }
+ try FileManager.default.createDirectory(
+ at: output.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ guard FileManager.default.createFile(atPath: output.path, contents: nil, attributes: [.posixPermissions: 0o600]) else {
+ throw Error.cannotCreateFile
+ }
+ let file = try FileHandle(forWritingTo: output)
+ defer { try? file.close() }
+ var remaining = size
+ while remaining > 0 {
+ try Task.checkCancellation()
+ let count = Int(min(remaining, 1_048_576))
+ guard let data = try input.read(upToCount: count), data.count == count else {
+ throw Error.truncatedArchive
+ }
+ try file.write(contentsOf: data)
+ remaining -= Int64(count)
+ }
+ case 53:
+ guard size == 0 else { throw Error.unsupportedEntry }
+ try FileManager.default.createDirectory(
+ at: output,
+ withIntermediateDirectories: true
+ )
+ case 103, 120:
+ // BSD tar emits global/per-file PAX metadata records. Their
+ // payload is metadata only; paths remain available in the
+ // following ustar header for these model archives.
+ let offset = try input.offset()
+ try input.seek(toOffset: offset + UInt64(size))
+ default:
+ throw Error.unsupportedEntry
+ }
+
+ try input.seek(toOffset: offset + UInt64(size + padding))
+ }
+ }
+
+ private static func safeOutputURL(relativePath: String, destination: URL) throws -> URL {
+ guard !relativePath.isEmpty, !relativePath.hasPrefix("/") else {
+ throw Error.unsafePath
+ }
+ let components = relativePath.split(separator: "/", omittingEmptySubsequences: true)
+ guard !components.isEmpty,
+ components.allSatisfy({ $0 != "." && $0 != ".." && !$0.contains("\0") })
+ else {
+ throw Error.unsafePath
+ }
+ return components.reduce(destination) { output, component in
+ output.appendingPathComponent(String(component), isDirectory: false)
+ }
+ }
+
+ private static func string(in bytes: [UInt8], range: Range<Int>) throws -> String {
+ guard let value = String(bytes: bytes[range].prefix { $0 != 0 }, encoding: .utf8) else { throw Error.unsafePath }
+ return value
+ }
+
+ private static func octal(in bytes: [UInt8], range: Range<Int>) throws -> Int64 {
+ let raw = try string(in: bytes, range: range).trimmingCharacters(in: .whitespaces)
+ guard raw.isEmpty || raw.allSatisfy({ ("0"..."7").contains(String($0)) }),
+ let value = Int64(raw.isEmpty ? "0" : raw, radix: 8)
+ else {
+ throw Error.invalidSize
+ }
+ return value
+ }
+
+ private enum Error: Swift.Error {
+ case cannotCreateFile
+ case invalidSize
+ case truncatedArchive
+ case unsafePath
+ case unsupportedEntry
+ }
+}
diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swift
index 7b6a6cf0..a36c30dd 100644
--- a/Sources/Fluid/Persistence/BackupService.swift
+++ b/Sources/Fluid/Persistence/BackupService.swift
@@ -139,6 +139,12 @@ struct SettingsBackupPayload: Codable, Equatable {
let defaultEditPromptOverride: String?
let fileTranscriptionSpeakerLabelsEnabled: Bool?
let fileTranscriptionExpectedSpeakerCount: Int?
+ // Additive fields: absence in an older backup preserves current preferences.
+ var meetingRecordingDefaults: MeetingRecordingDefaults? = nil
+ var privateAIIdleUnload: SettingsStore.PrivateAIIdleUnload? = nil
+ // A present empty map clears prompt overrides; an absent map preserves them.
+ // swiftlint:disable:next discouraged_optional_collection
+ var dictationPromptConfigurations: [String: SettingsStore.DictationPromptConfiguration]? = nil
}
struct AppBackupDocument: Codable, Equatable {
@@ -157,6 +163,7 @@ struct AppBackupDocument: Codable, Equatable {
enum BackupServiceError: LocalizedError {
case unsupportedSchemaVersion(BackupFileVersion)
case invalidJSON
+ case operationInProgress
var errorDescription: String? {
switch self {
@@ -164,6 +171,8 @@ enum BackupServiceError: LocalizedError {
return "This backup uses an unsupported schema version (\(version.major).\(version.minor))."
case .invalidJSON:
return "The selected backup file is not a valid FluidVoice backup."
+ case .operationInProgress:
+ return "A backup import or export is already running. Wait for it to finish, then try again."
}
}
}
@@ -172,11 +181,23 @@ enum BackupServiceError: LocalizedError {
final class BackupService {
static let shared = BackupService()
+ private var operationInProgress = false
+
private init() {}
+ private func beginOperation() throws {
+ guard !self.operationInProgress else { throw BackupServiceError.operationInProgress }
+ self.operationInProgress = true
+ }
+
func makeBackupDocument() async throws -> AppBackupDocument {
+ try self.beginOperation()
+ defer { self.operationInProgress = false }
+ try Task.checkCancellation()
try await TranscriptionHistoryStore.shared.waitUntilLoaded()
+ try Task.checkCancellation()
let pronunciationProfiles = await PronunciationDictionaryStore.shared.allProfiles()
+ try Task.checkCancellation()
return AppBackupDocument(
schemaVersion: .current,
appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "Unknown",
@@ -213,20 +234,41 @@ final class BackupService {
}
func restore(_ document: AppBackupDocument) async throws {
+ try self.beginOperation()
+ defer { self.operationInProgress = false }
+ try Task.checkCancellation()
try self.validate(document)
+ let asr = AppServices.shared.asr
+ let activityLease = try asr.beginSettingsBackupRestore()
+ defer { asr.releaseExclusiveActivity(activityLease) }
// A legacy backup represents the complete state from before voice
// profiles existed. Restoring it must therefore clear newer profiles
// instead of leaving them attached to restored dictionary entry IDs.
try await PronunciationDictionaryStore.shared.replaceAllProfiles(
document.pronunciationProfiles ?? []
)
+ // Profile replacement is a synchronous actor write once admitted. Finish
+ // the matching settings/History commit even if cancellation arrives during
+ // its actor hop; stopping here would leave a partially restored document.
+ let previousIdleUnload = SettingsStore.shared.privateAIIdleUnload
SettingsStore.shared.restore(
from: document.settings,
promptProfiles: document.promptProfiles,
appPromptBindings: document.appPromptBindings
)
+ // Commit settings, History and synchronous observers together before
+ // yielding to another actor, keeping the settings/History snapshot consistent.
TranscriptionHistoryStore.shared.restore(from: document.transcriptionHistory)
+ // Arm model retirement before admission reopens, including imports whose
+ // unchanged idle preference has no further actor hop. UI notification
+ // delivery must never decide whether the next capture uses stale state.
+ asr.handleSettingsBackupDidRestore()
NotificationCenter.default.post(name: .settingsBackupDidRestore, object: nil)
+ if let idleUnload = document.settings.privateAIIdleUnload, idleUnload != previousIdleUnload {
+ // Match the preference UI's targeted rescheduling; do not use the
+ // general restore notification to change model timers.
+ await PrivateAIIntegrationService.idleUnloader.settingsChanged()
+ }
}
func suggestedFilename(for date: Date = Date()) -> String {
diff --git a/Sources/Fluid/Persistence/Search/SearchIndex.swift b/Sources/Fluid/Persistence/Search/SearchIndex.swift
index 81292c57..9307d115 100644
--- a/Sources/Fluid/Persistence/Search/SearchIndex.swift
+++ b/Sources/Fluid/Persistence/Search/SearchIndex.swift
@@ -4,13 +4,13 @@ import ZeppelinEmbed
/// The full-text index behind the sidebar search: one record-only Zeppelin
/// namespace per `SearchIndexKind`.
///
-/// This is a derived copy. The stores in `UserDefaults` remain the source of truth,
+/// This is a derived copy. The app's history stores remain the source of truth,
/// so a namespace that is missing, reset, or from another build is simply rebuilt
/// from its store.
///
/// The one write operation is `reconcile`: compare what the store has with what the
/// namespace has, delete the rest, upsert the difference. It is idempotent, so the
-/// same call is the launch backfill, the write-through after a change, the cleanup
+/// same call is the first-search backfill, the write-through after a change, the cleanup
/// after a store evicts rows past its cap, and the recovery after a reset. An
/// interrupted run leaves nothing to undo; the next run finishes it.
actor SearchIndex {
@@ -27,9 +27,11 @@ actor SearchIndex {
}
private let root: FluidZeppelinRoot
+ private let maintenanceActiveRowLimit: UInt64?
- init(root: FluidZeppelinRoot = .shared) {
+ init(root: FluidZeppelinRoot = .shared, maintenanceActiveRowLimit: UInt64? = 256) {
self.root = root
+ self.maintenanceActiveRowLimit = maintenanceActiveRowLimit
}
/// No attributes: there is no filtered lexical query, and grouping is by
@@ -82,6 +84,9 @@ actor SearchIndex {
_ = try await store.upsert(pending.map(Self.document))
report.upserted = pending.count
}
+ // Finish the document scan before sealing: its cursor belongs to the old
+ // generation. Also migrate unchanged indexes left entirely in the WAL.
+ await self.sealLargeActiveIndex(store, kind: kind)
if report != ReconcileReport() {
await DebugLogger.shared.info(
"Search index \(kind.rawValue): +\(report.upserted) -\(report.deleted)",
@@ -91,6 +96,19 @@ actor SearchIndex {
return report
}
+ private func sealLargeActiveIndex(_ store: ZeppelinStore, kind: SearchIndexKind) async {
+ guard let limit = self.maintenanceActiveRowLimit else { return }
+ do {
+ let stats = try await store.stats()
+ guard stats.activeRowCount >= limit, stats.activeRowCount > 0 else { return }
+ _ = try await store.seal()
+ } catch {
+ // This is a derived index. Failed maintenance must not turn a
+ // successful update into missing results; retry on the next update.
+ DebugLogger.shared.warning("Search index \(kind.rawValue) maintenance deferred: \(error)", source: "SearchIndex")
+ }
+ }
+
private static func document(_ record: SearchIndexRecord) -> IngestDocument {
IngestDocument(
id: DocumentID(uuid: record.id),
diff --git a/Sources/Fluid/Persistence/Search/SearchIndexCoordinator.swift b/Sources/Fluid/Persistence/Search/SearchIndexCoordinator.swift
index 7dd4c32f..cd37e2f3 100644
--- a/Sources/Fluid/Persistence/Search/SearchIndexCoordinator.swift
+++ b/Sources/Fluid/Persistence/Search/SearchIndexCoordinator.swift
@@ -1,68 +1,391 @@
import Combine
import Foundation
-/// Keeps `SearchIndex` equal to the three stores it mirrors.
-///
-/// Each store publishes its whole array on every change and replays its current
-/// snapshot on subscription. History waits until its asynchronous load succeeds,
-/// so an incomplete snapshot cannot erase the index. One subscription per store
-/// covers the launch backfill and every later change with the same code path.
-/// The debounce folds a burst of saves into one reconcile, and reconciles for
-/// one kind run in order so two cannot interleave.
+/// Mirrors authoritative store snapshots only once search is requested.
+/// Each kind retains at most one running snapshot and one replaceable successor.
@MainActor
final class SearchIndexCoordinator {
static let shared = SearchIndexCoordinator()
+ enum Snapshot {
+ case history([TranscriptionHistoryEntry])
+ case transcripts([FileTranscriptionEntry])
+ case chats([ChatSession])
+
+ var kind: SearchIndexKind {
+ switch self {
+ case .history: .history
+ case .transcripts: .transcripts
+ case .chats: .chats
+ }
+ }
+ }
+
+ enum PreparationError: LocalizedError {
+ case timedOut
+
+ var errorDescription: String? {
+ "Search is taking longer than expected. Please try again."
+ }
+ }
+
+ private struct PendingSnapshot {
+ let generation: UInt64
+ let snapshot: Snapshot
+ }
+
+ private struct Waiter {
+ let id: UUID
+ let generation: UInt64
+ let continuation: CheckedContinuation<Void, Error>
+ let timeout: Task<Void, Never>
+ }
+
+ private final class State {
+ var generation: UInt64 = 0
+ var completedGeneration: UInt64 = 0
+ var latest: PendingSnapshot?
+ var worker: Task<Void, Never>?
+ var debounce: Task<Void, Never>?
+ var waiters: [Waiter] = []
+ var seeded = false
+ var failure: (generation: UInt64, error: Error)?
+ var needsRefresh = false
+ var suppressedGeneration: UInt64 = 0
+ }
+
+ /// Chat metadata stays on the main actor; only immutable text fields cross it.
+ private nonisolated struct ChatFields: Sendable {
+ let id: UUID
+ let revision: UInt64
+ let timestamp: Date
+ let parts: [String]
+
+ var record: SearchIndexRecord {
+ SearchIndexRecord(
+ id: self.id,
+ revision: self.revision,
+ timestamp: self.timestamp,
+ text: SearchIndexRecord.joined(self.parts)
+ )
+ }
+ }
+
private var cancellables: Set<AnyCancellable> = []
- private var pending: [SearchIndexKind: Task<Void, Never>] = [:]
- private var seeded: Set<SearchIndexKind> = []
- private let index: SearchIndex
-
- init(index: SearchIndex = .shared) {
- self.index = index
- }
-
- func start(historyStore: TranscriptionHistoryStore = .shared) {
- guard self.cancellables.isEmpty else { return }
- // Results join the index against `TranscriptionHistoryStore.entries`, which is
- // empty until the load finishes. A query typed before then finds nothing to
- // join, and an index already equal to the loaded history reconciles to no
- // change, so the first snapshot has to refresh on its own.
- self.mirror(
- .history,
- historyStore.loadedEntriesPublisher.map { $0.map(\.searchRecord) },
- refreshOnFirstSnapshot: true
+ private var states: [SearchIndexKind: State] = [:]
+ private var stopped = false
+ private var preparing = 0
+ private var historyWaiters: [Waiter] = []
+ private var historyLoad: Task<Void, Never>?
+ private let preparationTimeout: Duration
+ private let reconcile: @Sendable (SearchIndexKind, [SearchIndexRecord]) async throws -> SearchIndex.ReconcileReport
+ private let refresh: @MainActor () -> Void
+
+ init(
+ index: SearchIndex = .shared,
+ reconcile: (@Sendable (SearchIndexKind, [SearchIndexRecord]) async throws -> SearchIndex.ReconcileReport)? = nil,
+ refresh: @escaping @MainActor () -> Void = { AppSearchService.shared.refresh() },
+ preparationTimeout: Duration = .seconds(20)
+ ) {
+ self.reconcile = reconcile ?? { kind, records in
+ try await index.reconcile(kind, with: records)
+ }
+ self.refresh = refresh
+ self.preparationTimeout = preparationTimeout
+ }
+
+ /// Explicit callers retain write-through behavior. Production calls this lazily.
+ func start(historyStore: TranscriptionHistoryStore? = nil) {
+ guard !self.stopped, self.cancellables.isEmpty else { return }
+ let historyStore = historyStore ?? .shared
+ // This publisher never treats an incomplete or failed load as empty history.
+ historyStore.loadedEntriesPublisher
+ .sink { [weak self] in self?.submit(.history($0)) }
+ .store(in: &self.cancellables)
+ FileTranscriptionHistoryStore.shared.$entries
+ .sink { [weak self] in self?.submit(.transcripts($0)) }
+ .store(in: &self.cancellables)
+ ChatHistoryStore.shared.$sessions
+ .sink { [weak self] in self?.submit(.chats($0)) }
+ .store(in: &self.cancellables)
+ }
+
+ /// The first query waits for complete history and its latest captured index state.
+ /// Later edits cannot extend this barrier indefinitely: targets are fixed here.
+ func prepareForSearch(historyStore: TranscriptionHistoryStore? = nil) async throws {
+ guard !self.stopped else { throw CancellationError() }
+ let historyStore = historyStore ?? .shared
+ let deadline = ContinuousClock.now.advanced(by: self.preparationTimeout)
+ var targets: [SearchIndexKind: UInt64] = [:]
+ self.preparing += 1
+ defer {
+ self.preparing -= 1
+ if self.preparing == 0 {
+ let missedChange = self.states.contains { kind, state in
+ state.suppressedGeneration > (targets[kind] ?? state.generation)
+ }
+ for state in self.states.values {
+ state.suppressedGeneration = 0
+ }
+ if missedChange, !self.stopped { self.refresh() }
+ }
+ }
+ self.start(historyStore: historyStore)
+ try await self.waitForHistory(historyStore, until: deadline)
+ try Task.checkCancellation()
+ targets = self.states.mapValues(\.generation)
+ try await self.waitUntilCurrent(targets: targets, deadline: deadline)
+ }
+
+ /// Retains raw values, so a burst never constructs text for discarded snapshots.
+ func submit(_ snapshot: Snapshot) {
+ guard !self.stopped else { return }
+ let kind = snapshot.kind
+ let state = self.state(for: kind)
+ state.generation &+= 1
+ state.latest = PendingSnapshot(generation: state.generation, snapshot: snapshot)
+ state.debounce?.cancel()
+ state.debounce = Task { [weak self] in
+ do { try await Task.sleep(for: .milliseconds(250)) } catch { return }
+ guard !Task.isCancelled, let self, !self.stopped else { return }
+ state.debounce = nil
+ self.startWorker(kind, state: state)
+ }
+ }
+
+ /// Flushes the debounce without building records on the caller's actor.
+ func flush() {
+ guard !self.stopped else { return }
+ for (kind, state) in self.states {
+ state.debounce?.cancel()
+ state.debounce = nil
+ self.startWorker(kind, state: state)
+ }
+ }
+
+ /// A bounded barrier for snapshots already received; subsequent edits coalesce.
+ func waitUntilCurrent() async throws {
+ guard !self.stopped else { throw CancellationError() }
+ let targets = self.states.mapValues(\.generation)
+ try await self.waitUntilCurrent(
+ targets: targets,
+ deadline: ContinuousClock.now.advanced(by: self.preparationTimeout)
)
- self.mirror(.transcripts, FileTranscriptionHistoryStore.shared.$entries.map { $0.map(\.searchRecord) })
- self.mirror(.chats, ChatHistoryStore.shared.$sessions.map { $0.compactMap(\.searchRecord) })
- }
-
- private func mirror<P: Publisher>(
- _ kind: SearchIndexKind,
- _ records: P,
- refreshOnFirstSnapshot: Bool = false
- ) where P.Output == [SearchIndexRecord], P.Failure == Never {
- records
- .debounce(for: .milliseconds(250), scheduler: DispatchQueue.main)
- .sink { [weak self] records in
- guard let self else { return }
- let isFirstSnapshot = self.seeded.insert(kind).inserted
- let previous = self.pending[kind]
- self.pending[kind] = Task { [index] in
- await previous?.value
+ }
+
+ private func waitUntilCurrent(targets: [SearchIndexKind: UInt64], deadline: ContinuousClock.Instant) async throws {
+ self.flush()
+ for (kind, generation) in targets {
+ try Task.checkCancellation()
+ try await self.wait(for: generation, kind: kind, deadline: deadline)
+ }
+ }
+
+ /// Once stopped, this instance cannot reopen namespaces or refresh search again.
+ func stop() async {
+ self.stopped = true
+ self.cancellables.removeAll()
+ self.historyLoad?.cancel()
+ self.historyLoad = nil
+ for waiter in self.historyWaiters {
+ waiter.timeout.cancel()
+ waiter.continuation.resume(throwing: CancellationError())
+ }
+ self.historyWaiters.removeAll()
+ let workers = self.states.values.compactMap(\.worker)
+ for state in self.states.values {
+ state.debounce?.cancel()
+ state.debounce = nil
+ state.latest = nil
+ self.finishWaiters(state, through: .max, result: .failure(CancellationError()))
+ }
+ for worker in workers {
+ await worker.value
+ }
+ }
+
+ private func state(for kind: SearchIndexKind) -> State {
+ if let state = self.states[kind] { return state }
+ let state = State()
+ self.states[kind] = state
+ return state
+ }
+
+ private func startWorker(_ kind: SearchIndexKind, state: State) {
+ guard !self.stopped, state.worker == nil, state.latest != nil else { return }
+ state.worker = Task { [weak self] in
+ guard let self else { return }
+ while !self.stopped, state.debounce == nil, let pending = state.latest {
+ state.latest = nil
+ state.debounce?.cancel()
+ state.debounce = nil
+ let records = await self.records(for: pending.snapshot)
+ guard !self.stopped else { break }
+ do {
+ let report = try await self.reconcile(kind, records)
+ let first = !state.seeded
+ state.seeded = true
+ state.completedGeneration = pending.generation
+ state.failure = nil
+ self.finishWaiters(state, through: pending.generation, result: .success(()))
+ state.needsRefresh = state.needsRefresh || report != SearchIndex.ReconcileReport() || (kind == .history && first)
+ } catch {
+ state.failure = (state.generation, error)
+ self.finishWaiters(state, through: state.generation, result: .failure(error))
+ DebugLogger.shared.error(
+ "Search index \(kind.rawValue) reconcile failed: \(error)",
+ source: "SearchIndex"
+ )
+ // Preserve only the latest raw snapshot for a later retry. Never
+ // spin on a failed index or let older input replace newer input.
+ if state.latest == nil, !self.stopped { state.latest = pending }
+ break
+ }
+ }
+ state.worker = nil
+ if state.latest == nil {
+ let shouldRefresh = state.needsRefresh
+ state.needsRefresh = false
+ if shouldRefresh, !self.stopped {
+ if self.preparing == 0 {
+ self.refresh()
+ } else {
+ state.suppressedGeneration = state.completedGeneration
+ }
+ }
+ }
+ }
+ }
+
+ private func records(for snapshot: Snapshot) async -> [SearchIndexRecord] {
+ switch snapshot {
+ case let .history(entries):
+ return await Task.detached(priority: .utility) {
+ autoreleasepool { entries.map(\.searchRecord) }
+ }.value
+ case let .transcripts(entries):
+ return await Task.detached(priority: .utility) {
+ autoreleasepool { entries.map(\.searchRecord) }
+ }.value
+ case let .chats(sessions):
+ let fields = sessions.compactMap { session -> ChatFields? in
+ guard !session.isArchived, let id = UUID(uuidString: session.id) else { return nil }
+ var parts = [session.title]
+ for message in session.messages {
+ parts.append(message.content)
+ if let command = message.toolCall?.command { parts.append(command) }
+ }
+ return ChatFields(
+ id: id,
+ revision: session.searchRevision ?? UInt64(max(1, session.updatedAt.timeIntervalSince1970 * 1000)),
+ timestamp: session.updatedAt,
+ parts: parts
+ )
+ }
+ return await Task.detached(priority: .utility) {
+ autoreleasepool { fields.map(\.record) }
+ }.value
+ }
+ }
+
+ private func wait(for generation: UInt64, kind: SearchIndexKind, deadline: ContinuousClock.Instant) async throws {
+ guard !self.stopped else { throw CancellationError() }
+ let state = self.state(for: kind)
+ guard state.completedGeneration < generation else { return }
+ if state.worker == nil, let failure = state.failure, failure.generation >= generation {
+ throw failure.error
+ }
+ let id = UUID()
+ try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
+ if Task.isCancelled || self.stopped {
+ continuation.resume(throwing: CancellationError())
+ } else {
+ state.waiters.append(Waiter(
+ id: id,
+ generation: generation,
+ continuation: continuation,
+ timeout: self.timeout(id: id, kind: kind, deadline: deadline)
+ ))
+ }
+ }
+ } onCancel: {
+ Task { @MainActor [weak self] in
+ guard let self, let state = self.states[kind],
+ let position = state.waiters.firstIndex(where: { $0.id == id }) else { return }
+ let waiter = state.waiters.remove(at: position)
+ waiter.timeout.cancel()
+ waiter.continuation.resume(throwing: CancellationError())
+ }
+ }
+ }
+
+ private func finishWaiters(_ state: State, through generation: UInt64, result: Result<Void, Error>) {
+ let ready = state.waiters.filter { $0.generation <= generation }
+ state.waiters.removeAll { $0.generation <= generation }
+ for waiter in ready {
+ waiter.timeout.cancel()
+ waiter.continuation.resume(with: result)
+ }
+ }
+
+ private func waitForHistory(_ store: TranscriptionHistoryStore, until deadline: ContinuousClock.Instant) async throws {
+ guard !self.stopped else { throw CancellationError() }
+ let id = UUID()
+ try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
+ guard !Task.isCancelled, !self.stopped else {
+ continuation.resume(throwing: CancellationError())
+ return
+ }
+ self.historyWaiters.append(Waiter(
+ id: id,
+ generation: 0,
+ continuation: continuation,
+ timeout: self.timeout(id: id, kind: nil, deadline: deadline)
+ ))
+ guard self.historyLoad == nil else { return }
+ self.historyLoad = Task { [weak self] in
+ let result: Result<Void, Error>
do {
- let report = try await index.reconcile(kind, with: records)
- if report != SearchIndex.ReconcileReport() || (refreshOnFirstSnapshot && isFirstSnapshot) {
- AppSearchService.shared.refresh()
- }
+ try await store.waitUntilLoaded()
+ result = .success(())
} catch {
- DebugLogger.shared.error(
- "Search index \(kind.rawValue) reconcile failed: \(error)",
- source: "SearchIndex"
- )
+ result = .failure(error)
+ }
+ guard let self else { return }
+ self.historyLoad = nil
+ let waiters = self.historyWaiters
+ self.historyWaiters.removeAll()
+ for waiter in waiters {
+ waiter.timeout.cancel()
+ waiter.continuation.resume(with: result)
}
}
}
- .store(in: &self.cancellables)
+ } onCancel: {
+ Task { @MainActor [weak self] in self?.removeWaiter(id: id, kind: nil, error: CancellationError()) }
+ }
+ }
+
+ private func timeout(id: UUID, kind: SearchIndexKind?, deadline: ContinuousClock.Instant) -> Task<Void, Never> {
+ Task { [weak self] in
+ do { try await Task.sleep(until: deadline, clock: .continuous) } catch { return }
+ guard !Task.isCancelled else { return }
+ self?.removeWaiter(id: id, kind: kind, error: PreparationError.timedOut)
+ }
+ }
+
+ private func removeWaiter(id: UUID, kind: SearchIndexKind?, error: Error) {
+ let waiter: Waiter
+ if let kind {
+ guard let state = self.states[kind], let position = state.waiters.firstIndex(where: { $0.id == id }) else { return }
+ waiter = state.waiters.remove(at: position)
+ } else {
+ guard let position = self.historyWaiters.firstIndex(where: { $0.id == id }) else { return }
+ waiter = self.historyWaiters.remove(at: position)
+ }
+ waiter.timeout.cancel()
+ waiter.continuation.resume(throwing: error)
}
}
diff --git a/Sources/Fluid/Persistence/Search/SearchIndexRecord.swift b/Sources/Fluid/Persistence/Search/SearchIndexRecord.swift
index 3208594e..dd4bbb42 100644
--- a/Sources/Fluid/Persistence/Search/SearchIndexRecord.swift
+++ b/Sources/Fluid/Persistence/Search/SearchIndexRecord.swift
@@ -45,7 +45,7 @@ extension TranscriptionHistoryEntry {
///
/// An entry is immutable, so its revision only moves when a restore replaces the
/// id with different text; everything else stays at the revision it was indexed at.
- var searchRecord: SearchIndexRecord {
+ nonisolated var searchRecord: SearchIndexRecord {
SearchIndexRecord(
id: self.id,
revision: self.searchRevision ?? 1,
@@ -60,7 +60,7 @@ extension FileTranscriptionEntry {
/// joined together, so indexing both would count every word twice.
///
/// Renaming advances the persisted revision without changing the recording date.
- var searchRecord: SearchIndexRecord {
+ nonisolated var searchRecord: SearchIndexRecord {
SearchIndexRecord(
id: self.id,
revision: self.searchRevision ?? 1,
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index d9d9f132..580edd9f 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -1691,7 +1691,7 @@ final class SettingsStore: ObservableObject {
}
/// How long the local model may sit unused before its memory is released.
- enum PrivateAIIdleUnload: Int, CaseIterable, Identifiable {
+ enum PrivateAIIdleUnload: Int, Codable, CaseIterable, Identifiable {
case never = 0
case tenMinutes = 10
case thirtyMinutes = 30
@@ -3681,7 +3681,10 @@ final class SettingsStore: ObservableObject {
defaultDictationPromptOverride: self.defaultDictationPromptOverride,
defaultEditPromptOverride: self.defaultEditPromptOverride,
fileTranscriptionSpeakerLabelsEnabled: self.fileTranscriptionSpeakerLabelsEnabled,
- fileTranscriptionExpectedSpeakerCount: self.fileTranscriptionExpectedSpeakerCount
+ fileTranscriptionExpectedSpeakerCount: self.fileTranscriptionExpectedSpeakerCount,
+ meetingRecordingDefaults: self.meetingRecordingDefaults,
+ privateAIIdleUnload: self.privateAIIdleUnload,
+ dictationPromptConfigurations: self.dictationPromptConfigurations
)
}
@@ -3710,6 +3713,9 @@ final class SettingsStore: ObservableObject {
if let privateAIContextTokenLimit = payload.privateAIContextTokenLimit {
self.privateAIContextTokenLimit = privateAIContextTokenLimit
}
+ if let privateAIIdleUnload = payload.privateAIIdleUnload {
+ self.privateAIIdleUnload = privateAIIdleUnload
+ }
self.selectedSpeechModel = payload.selectedSpeechModel
if let selectedWhisperLanguageCode = payload.selectedWhisperLanguageCode {
self.selectedWhisperLanguageCode = Self.whisperLanguageCode(fromBackupValue: selectedWhisperLanguageCode)
@@ -3726,6 +3732,9 @@ final class SettingsStore: ObservableObject {
self.meetingTranscriptionBackendID = payload.meetingTranscriptionBackendID.map {
MeetingBackendID(rawValue: $0)
} ?? .productionDefault
+ if let meetingRecordingDefaults = payload.meetingRecordingDefaults {
+ self.meetingRecordingDefaults = meetingRecordingDefaults
+ }
self.primaryDictationShortcuts = payload.primaryDictationShortcuts ?? [payload.hotkeyShortcut]
self.promptModeHotkeyShortcut = payload.promptModeHotkeyShortcut
self.promptModeShortcutEnabled = payload.promptModeShortcutEnabled
@@ -3888,6 +3897,9 @@ final class SettingsStore: ObservableObject {
self.customDictionaryEntries = payload.customDictionaryEntries
self.dictationPromptProfiles = promptProfiles
+ if let configurations = payload.dictationPromptConfigurations {
+ self.dictationPromptConfigurations = configurations
+ }
self.appPromptBindings = appPromptBindings
self.selectedDictationPromptID = payload.selectedDictationPromptID
self.isDictationPromptOff = payload.dictationPromptOff ?? self.isDictationPromptOff
@@ -3906,6 +3918,11 @@ final class SettingsStore: ObservableObject {
self.promptModeSelectedPromptID = payload.promptModeSelectedPromptID
self.isSecondaryDictationPromptOff = payload.secondaryDictationPromptOff ?? false
self.normalizePromptSelectionsIfNeeded()
+ // Validate imported mappings only after profile migration/normalization.
+ // Legacy backups do not own the newer map, so leave it intact when absent.
+ if payload.dictationPromptConfigurations != nil {
+ self.normalizeDictationPromptConfigurationsIfNeeded()
+ }
self.purgeRetiredAppleIntelligenceState()
}
@@ -5050,6 +5067,8 @@ final class SettingsStore: ObservableObject {
case parakeetTDT = "parakeet-tdt"
case parakeetTDTv2 = "parakeet-tdt-v2"
+ case fluidParakeetMini = "fluid-parakeet-mini"
+ case fluidParakeetPico = "fluid-parakeet-pico"
case parakeetRealtime = "parakeet-realtime"
case qwen3Asr = "qwen3-asr"
case cohereTranscribeSixBit = "cohere-transcribe-6bit"
@@ -5071,6 +5090,16 @@ final class SettingsStore: ObservableObject {
case whisperLargeTurbo = "whisper-large-turbo"
case whisperLarge = "whisper-large"
+ var parakeetDescriptor: ParakeetSpeechModelCatalog.Descriptor? {
+ ParakeetSpeechModelCatalog.descriptor(forModelID: self.rawValue)
+ }
+
+ /// Relative product ratings for display and sorting, not benchmark accuracy.
+ var hasPerformanceRatings: Bool {
+ guard let descriptor = self.parakeetDescriptor else { return true }
+ return descriptor.performanceRatings != nil
+ }
+
var id: String {
rawValue
}
@@ -5079,8 +5108,7 @@ final class SettingsStore: ObservableObject {
var displayName: String {
switch self {
- case .parakeetTDT: return "Parakeet TDT v3 (Multilingual)"
- case .parakeetTDTv2: return "Parakeet TDT v2 (English Only)"
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.displayName ?? self.rawValue
case .parakeetRealtime: return "Parakeet Flash (Beta)"
case .qwen3Asr: return "Qwen3 ASR (Beta)"
case .cohereTranscribeSixBit: return "Cohere Transcribe"
@@ -5100,9 +5128,7 @@ final class SettingsStore: ObservableObject {
var languageSupport: String {
switch self {
- case .parakeetTDT:
- return "25 Languages"
- case .parakeetTDTv2: return "English Only (Higher Accuracy)"
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.languageSupport ?? "English Only"
case .parakeetRealtime: return "English Only (Live Streaming)"
case .qwen3Asr: return "30 Languages"
case .cohereTranscribeSixBit: return "14 Languages (Select Manually)"
@@ -5116,8 +5142,7 @@ final class SettingsStore: ObservableObject {
var downloadSize: String {
switch self {
- case .parakeetTDT: return "~460.9 MiB"
- case .parakeetTDTv2: return "~442.9 MiB"
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.downloadSize ?? ""
case .parakeetRealtime: return "~428.4 MiB"
case .qwen3Asr: return "~2.0 GiB"
case .cohereTranscribeSixBit: return "~1.54 GiB"
@@ -5137,8 +5162,7 @@ final class SettingsStore: ObservableObject {
var expectedDownloadBytes: Int64 {
switch self {
- case .parakeetTDT: return 483_288_717
- case .parakeetTDTv2: return 464_421_712
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.expectedDownloadBytes ?? 0
case .parakeetRealtime: return 449_190_189
case .qwen3Asr: return 2000 * 1024 * 1024
case .cohereTranscribeSixBit: return 1_650_748_785
@@ -5156,14 +5180,14 @@ final class SettingsStore: ObservableObject {
var requiresAppleSilicon: Bool {
switch self {
- case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .qwen3Asr, .cohereTranscribeSixBit, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320: return true
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico, .parakeetRealtime, .qwen3Asr, .cohereTranscribeSixBit, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320: return true
default: return false
}
}
var isWhisperModel: Bool {
switch self {
- case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .qwen3Asr, .cohereTranscribeSixBit, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320, .appleSpeech,
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico, .parakeetRealtime, .qwen3Asr, .cohereTranscribeSixBit, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320, .appleSpeech,
.appleSpeechAnalyzer: return false
default: return true
}
@@ -5229,7 +5253,7 @@ final class SettingsStore: ObservableObject {
/// Requires macOS 15 or later.
var requiresMacOS15: Bool {
switch self {
- case .qwen3Asr, .cohereTranscribeSixBit: return true
+ case .fluidParakeetMini, .fluidParakeetPico, .qwen3Asr, .cohereTranscribeSixBit: return true
default: return false
}
}
@@ -5279,8 +5303,7 @@ final class SettingsStore: ObservableObject {
/// Human-readable marketing name for the card UI
var humanReadableName: String {
switch self {
- case .parakeetTDT: return "Blazing Fast - Multilingual"
- case .parakeetTDTv2: return "Blazing Fast - English"
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.humanReadableName ?? self.rawValue
case .parakeetRealtime: return "Flash Dictation"
case .qwen3Asr: return "Qwen3 - Multilingual"
case .cohereTranscribeSixBit: return "Cohere - High Accuracy"
@@ -5301,13 +5324,8 @@ final class SettingsStore: ObservableObject {
/// One-line description for the card UI
var cardDescription: String {
switch self {
- case .parakeetTDT:
- return "Fast multilingual transcription. Supports Bulgarian, Croatian, Czech, Danish, " +
- "Dutch, English, Estonian, Finnish, French, German, Greek, Hungarian, Italian, " +
- "Latvian, Lithuanian, Maltese, Polish, Portuguese, Romanian, Russian, Slovak, " +
- "Slovenian, Spanish, Swedish, and Ukrainian."
- case .parakeetTDTv2:
- return "Optimized for English accuracy and fastest transcription."
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico:
+ return self.parakeetDescriptor?.cardDescription ?? ""
case .parakeetRealtime:
return "English-only streaming local dictation with low-latency partial text and end-of-utterance detection."
case .qwen3Asr:
@@ -5342,7 +5360,7 @@ final class SettingsStore: ObservableObject {
/// Minimum recommended RAM in GB for this model to run safely
var requiredMemoryGB: Double {
switch self {
- case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico, .parakeetRealtime:
return 4.0
case .qwen3Asr:
return 8.0
@@ -5386,8 +5404,7 @@ final class SettingsStore: ObservableObject {
/// Speed rating (1-5, higher is faster)
var speedRating: Int {
switch self {
- case .parakeetTDT: return 5
- case .parakeetTDTv2: return 5
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.performanceRatings?.speedRating ?? 0
case .parakeetRealtime: return 5
case .qwen3Asr: return 3
case .cohereTranscribeSixBit: return 3
@@ -5407,8 +5424,7 @@ final class SettingsStore: ObservableObject {
/// Accuracy rating (1-5, higher is more accurate)
var accuracyRating: Int {
switch self {
- case .parakeetTDT: return 5
- case .parakeetTDTv2: return 5
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.performanceRatings?.accuracyRating ?? 0
case .parakeetRealtime: return 4
case .qwen3Asr: return 4
case .cohereTranscribeSixBit: return 5
@@ -5428,8 +5444,7 @@ final class SettingsStore: ObservableObject {
/// Exact speed percentage (0.0 - 1.0) for the liquid bars
var speedPercent: Double {
switch self {
- case .parakeetTDT: return 1.0
- case .parakeetTDTv2: return 1.0
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.performanceRatings?.speedPercent ?? 0
case .parakeetRealtime: return 1.0
case .qwen3Asr: return 0.45
case .cohereTranscribeSixBit: return 0.85
@@ -5449,8 +5464,7 @@ final class SettingsStore: ObservableObject {
/// Exact accuracy percentage (0.0 - 1.0) for the liquid bars
var accuracyPercent: Double {
switch self {
- case .parakeetTDT: return 0.92
- case .parakeetTDTv2: return 0.96
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico: return self.parakeetDescriptor?.performanceRatings?.accuracyPercent ?? 0
case .parakeetRealtime: return 0.75
case .qwen3Asr: return 0.90
case .cohereTranscribeSixBit: return 0.98
@@ -5472,6 +5486,7 @@ final class SettingsStore: ObservableObject {
switch self {
case .parakeetTDT: return "FluidVoice Pick"
case .parakeetTDTv2: return "FluidVoice Pick"
+ case .fluidParakeetMini, .fluidParakeetPico: return "New"
case .parakeetRealtime: return "Beta"
case .qwen3Asr: return "Beta"
case .cohereTranscribeSixBit: return "New"
@@ -5484,7 +5499,7 @@ final class SettingsStore: ObservableObject {
/// Optimization level for Apple Silicon (for display)
var appleSiliconOptimized: Bool {
switch self {
- case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .qwen3Asr, .cohereTranscribeSixBit, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320, .appleSpeechAnalyzer:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico, .parakeetRealtime, .qwen3Asr, .cohereTranscribeSixBit, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320, .appleSpeechAnalyzer:
return true
default:
return false
@@ -5505,7 +5520,7 @@ final class SettingsStore: ObservableObject {
var supportsPronunciationMatching: Bool {
#if arch(arm64)
switch self {
- case .parakeetTDT, .parakeetTDTv2:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico:
return true
default:
return false
@@ -5557,7 +5572,7 @@ final class SettingsStore: ObservableObject {
/// Which provider this model belongs to
var provider: Provider {
switch self {
- case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico, .parakeetRealtime, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320:
return .nvidia
case .appleSpeech, .appleSpeechAnalyzer:
return .apple
@@ -5580,15 +5595,10 @@ final class SettingsStore: ObservableObject {
switch self {
case .appleSpeech, .appleSpeechAnalyzer:
return true
- case .parakeetTDT:
- #if canImport(FluidAudio)
- return Self.parakeetModelsExist(version: .v3)
- #else
- return false
- #endif
- case .parakeetTDTv2:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico:
#if canImport(FluidAudio)
- return Self.parakeetModelsExist(version: .v2)
+ guard let descriptor = self.parakeetDescriptor else { return false }
+ return Self.parakeetModelsExist(descriptor: descriptor)
#else
return false
#endif
@@ -5649,22 +5659,10 @@ final class SettingsStore: ObservableObject {
}
#if canImport(FluidAudio)
- private static func parakeetModelsExist(version: AsrModelVersion) -> Bool {
- let directory = AsrModels.defaultCacheDirectory(for: version)
- let vocabulary = directory.appendingPathComponent(ModelNames.ASR.vocabularyFile)
- guard
- AsrModels.modelsExist(at: directory, version: version),
- HuggingFaceModelDownloader.artifactIsComplete(at: vocabulary, isDirectory: false)
- else {
- return false
- }
-
- return AsrModels.requiredModelNames.allSatisfy { modelName in
- HuggingFaceModelDownloader.artifactIsComplete(
- at: directory.appendingPathComponent(modelName, isDirectory: true),
- isDirectory: true
- )
- }
+ private static func parakeetModelsExist(descriptor: ParakeetSpeechModelCatalog.Descriptor) -> Bool {
+ let modelsDirectory = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
+ let directory = descriptor.cacheDirectory(in: modelsDirectory)
+ return descriptor.artifactsAreComplete(at: directory)
}
private static func parakeetRealtimeModelsExist() -> Bool {
@@ -5686,6 +5684,8 @@ final class SettingsStore: ObservableObject {
/// Brand/provider name for the model (NVIDIA, Apple, OpenAI)
var brandName: String {
switch self {
+ case .fluidParakeetMini, .fluidParakeetPico:
+ return "FluidVoice"
case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320:
return "NVIDIA"
case .qwen3Asr:
@@ -5710,6 +5710,8 @@ final class SettingsStore: ObservableObject {
/// Brand color for the provider badge
var brandColorHex: String {
switch self {
+ case .fluidParakeetMini, .fluidParakeetPico:
+ return "#1A75FF" // FluidBrandColors.blue
case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320:
return "#76B900"
case .qwen3Asr:
@@ -6167,7 +6169,7 @@ extension SettingsStore.SpeechModel {
switch self {
case .parakeetTDT:
return "BG, HR, CS, DA, NL, EN, ET, FI, FR, DE, EL, HU, IT, LV, LT, MT, PL, PT, RO, SK, SL, ES, SV, RU, UK"
- case .parakeetRealtime:
+ case .fluidParakeetMini, .fluidParakeetPico, .parakeetRealtime:
return "EN"
case .cohereTranscribeSixBit:
return "AR, DE, EL, EN, ES, FR, IT, JA, KO, NL, PL, PT, VI, ZH"
@@ -6186,6 +6188,8 @@ extension SettingsStore.SpeechModel {
return """
Bulgarian, Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, German, Greek, Hungarian, Italian, Latvian, Lithuanian, Maltese, Polish, Portuguese, Romanian, Slovak, Slovenian, Spanish, Swedish, Russian, and Ukrainian
"""
+ case .fluidParakeetMini, .fluidParakeetPico:
+ return "English"
case .cohereTranscribeSixBit:
return "Arabic, German, Greek, English, Spanish, French, Italian, Japanese, Korean, Dutch, Polish, Portuguese, Vietnamese, and Mandarin Chinese"
case .nemotronOffline, .nemotronStreaming, .nemotronStreaming320:
@@ -6342,6 +6346,13 @@ extension SettingsStore {
}
}
+ /// Read only the persisted choice; callers can resolve the fallback off the main thread.
+ func storedExternalCoreMLArtifactsPath(for model: SpeechModel) -> String? {
+ let paths = self.defaults.dictionary(forKey: Keys.externalCoreMLArtifactsDirectories) as? [String: String] ?? [:]
+ guard let path = paths[model.rawValue], !path.isEmpty else { return nil }
+ return path
+ }
+
func externalCoreMLArtifactsDirectory(for model: SpeechModel) -> URL? {
guard let spec = model.externalCoreMLSpec else { return nil }
let paths = self.defaults.dictionary(forKey: Keys.externalCoreMLArtifactsDirectories) as? [String: String] ?? [:]
diff --git a/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift b/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
index 0598e151..9223fca6 100644
--- a/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
+++ b/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
@@ -239,6 +239,12 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable, Sendable {
}
}
+/// One pending sidebar reveal. Repeated clicks replace it; it is never persisted.
+nonisolated struct HistorySearchSelectionRequest: Equatable {
+ let token = UUID()
+ let entryID: UUID
+}
+
// MARK: - Transcription History Store
@MainActor
@@ -265,6 +271,18 @@ final class TranscriptionHistoryStore: ObservableObject {
}
@Published var selectedEntryID: UUID?
+ @Published private(set) var searchSelectionRequest: HistorySearchSelectionRequest?
+
+ func selectEntryFromSearch(id: UUID) {
+ self.selectedEntryID = id
+ self.searchSelectionRequest = HistorySearchSelectionRequest(entryID: id)
+ }
+
+ func consumeSearchSelectionRequest(_ request: HistorySearchSelectionRequest) {
+ guard self.searchSelectionRequest == request else { return }
+ self.searchSelectionRequest = nil
+ }
+
/// Last completed snapshot while a coalesced background refresh is pending.
/// Rendering must never scan history or schedule work.
@Published private(set) var todaySummary = TodaySummary(words: 0, transcriptions: 0)
@@ -458,7 +476,7 @@ final class TranscriptionHistoryStore: ObservableObject {
func restore(from payload: [TranscriptionHistoryEntry]) {
self.audioSaveGeneration &+= 1
self.invalidateAutomaticAudioBudgetMeasurement()
- let indexed = Dictionary(self.entries.map { ($0.id, $0.searchRecord.revision) }) { first, _ in first }
+ let indexed = Dictionary(self.entries.map { ($0.id, $0.searchRevision ?? 1) }) { first, _ in first }
self.entries = payload
.map { entry in
var entry = entry
@@ -644,6 +662,12 @@ final class TranscriptionHistoryStore: ObservableObject {
)
}
+ /// Search retries may reload unavailable history, but must never rewrite it.
+ func retryLoadingIfNeeded() {
+ guard !self.hasLoaded else { return }
+ self.retryPersistence()
+ }
+
func retryPersistence() {
guard !self.isLoading else { return }
guard self.hasLoaded else {
diff --git a/Sources/Fluid/Persistence/VoiceEngineLanguageCatalog.swift b/Sources/Fluid/Persistence/VoiceEngineLanguageCatalog.swift
index d94f8316..374e4d82 100644
--- a/Sources/Fluid/Persistence/VoiceEngineLanguageCatalog.swift
+++ b/Sources/Fluid/Persistence/VoiceEngineLanguageCatalog.swift
@@ -48,7 +48,7 @@ struct VoiceEngineLanguageRoute: Identifiable, Equatable {
var badgeText: String? {
switch self.model {
- case .parakeetTDT, .parakeetTDTv2:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico:
return "Optimized for FluidVoice"
default:
return nil
@@ -150,6 +150,11 @@ enum VoiceEngineLanguageCatalog {
routes.append(Self.route(language, .parakeetTDT, .automatic))
}
+ if language.id == "en" {
+ routes.append(Self.route(language, .fluidParakeetMini, .automatic))
+ routes.append(Self.route(language, .fluidParakeetPico, .automatic))
+ }
+
if let cohereLanguage = Self.cohereLanguage(for: language.id) {
routes.append(Self.route(language, .cohereTranscribeSixBit, .cohere(cohereLanguage)))
}
@@ -223,33 +228,7 @@ enum VoiceEngineLanguageCatalog {
"ar",
]
- nonisolated static let parakeetV3LanguageIDs: Set<String> = [
- "bg",
- "hr",
- "cs",
- "da",
- "nl",
- "en",
- "et",
- "fi",
- "fr",
- "de",
- "el",
- "hu",
- "it",
- "lv",
- "lt",
- "mt",
- "pl",
- "pt",
- "ro",
- "sk",
- "sl",
- "es",
- "sv",
- "ru",
- "uk",
- ]
+ nonisolated static let parakeetV3LanguageIDs = Set(ParakeetSpeechModelCatalog.v3.supportedLanguageCodes)
private static let cohereLanguageMap: [String: SettingsStore.CohereLanguage] = [
"ar": .arabic,
diff --git a/Sources/Fluid/Persistence/Zeppelin/FluidZeppelinRoot.swift b/Sources/Fluid/Persistence/Zeppelin/FluidZeppelinRoot.swift
index 1aebc143..9510eba5 100644
--- a/Sources/Fluid/Persistence/Zeppelin/FluidZeppelinRoot.swift
+++ b/Sources/Fluid/Persistence/Zeppelin/FluidZeppelinRoot.swift
@@ -16,6 +16,7 @@ actor FluidZeppelinRoot {
private let root: URL
private var namespaces: [String: Task<ZeppelinStore, Error>] = [:]
+ private var stopped = false
init(root: URL? = nil) {
self.root = root ?? FileManager.default
@@ -28,6 +29,7 @@ actor FluidZeppelinRoot {
/// A second open of the same directory fails on its writer lock, so the open is
/// cached as a task: concurrent first callers share one open instead of racing.
func namespace(_ name: String, spec: NamespaceSpec) async throws -> ZeppelinStore {
+ guard !self.stopped else { throw CancellationError() }
if let open = self.namespaces[name] {
return try await open.value
}
@@ -55,8 +57,8 @@ actor FluidZeppelinRoot {
}
}
- /// Closes every open namespace so their logs are checkpointed rather than
- /// replayed on the next launch. Called from `applicationWillTerminate`.
+ /// Closes cached handles. This is reusable; app termination uses `shutdown`.
+ /// SearchIndex seals large active indexes before closure to avoid WAL replay.
func closeAll() async {
for (name, open) in self.namespaces {
do {
@@ -70,4 +72,10 @@ actor FluidZeppelinRoot {
}
self.namespaces.removeAll()
}
+
+ /// App termination permanently rejects new opens before draining old ones.
+ func shutdown() async {
+ self.stopped = true
+ await self.closeAll()
+ }
}
diff --git a/Sources/Fluid/Resources/speech-model-check.pcm b/Sources/Fluid/Resources/speech-model-check.pcm
new file mode 100644
index 00000000..5a92558e
Binary files /dev/null and b/Sources/Fluid/Resources/speech-model-check.pcm differ
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 6c1c6457..24dcaab6 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -364,6 +364,7 @@ enum ASRExclusiveActivity: String, Equatable {
case localAPI
case meeting
case modelMaintenance
+ case settingsRestore
var displayName: String {
switch self {
@@ -377,6 +378,8 @@ enum ASRExclusiveActivity: String, Equatable {
return "meeting transcription"
case .modelMaintenance:
return "voice model maintenance"
+ case .settingsRestore:
+ return "settings import"
}
}
}
@@ -388,11 +391,14 @@ struct ASRActivityLease: Equatable {
enum ASRActivityError: LocalizedError {
case activityInProgress(ASRExclusiveActivity)
+ case settingsRestoreUnavailable
var errorDescription: String? {
switch self {
case let .activityInProgress(activity):
return "Wait for the active \(activity.displayName) to finish."
+ case .settingsRestoreUnavailable:
+ return "Finish the current recording, transcription, microphone preview, or voice model operation, then import the backup again."
}
}
}
@@ -652,6 +658,15 @@ final class ASRService: ObservableObject {
self.isRunning || self.isStarting
}
+ /// Change only the output mode of our existing capture, never another activity's audio.
+ var canSwitchOwnedDictationCaptureMode: Bool {
+ guard let lease = self.dictationActivityLease else { return false }
+ return lease.activity == .dictation && self.activeActivityLease == lease
+ && self.isRunning && !self.isStarting && !self.isStoppingFinalTranscription
+ && !self.isTerminating && !self.isDictionaryTrainingCaptureActive
+ && !self.recordingBufferHandoffGate.isActive && !self.recordingBufferHandoffGate.isRecovering
+ }
+
func acquireExclusiveActivity(_ activity: ASRExclusiveActivity) throws -> ASRActivityLease {
guard let activeActivityLease = self.activeActivityLease else {
DictionaryAudioLearningService.shared.cancelForRecording()
@@ -663,6 +678,23 @@ final class ASRService: ObservableObject {
throw ASRActivityError.activityInProgress(activeActivityLease.activity)
}
+ /// Reject before any backup writes, then reserve admission across its actor hop.
+ /// Keep the whole import together instead of changing the current capture's settings.
+ func beginSettingsBackupRestore() throws -> ASRActivityLease {
+ try Task.checkCancellation()
+ guard !self.isTerminating, self.activeActivityLease == nil,
+ !self.isRunning, !self.isStarting, !self.isStoppingFinalTranscription,
+ !self.recordingBufferHandoffGate.isRecovering,
+ !self.isMicrophonePreviewRequested, !self.isMicrophonePreviewActive,
+ !self.hasActiveModelDownload, !self.hasActiveModelPreparation,
+ self.deletingModelID == nil, self.providerResetDrain == nil,
+ !self.isCancellingModelPreparation, !self.isCancellingModelDownload,
+ !self.meetingModelResidency.isExclusive,
+ self.isAsrReady || (!self.isDownloadingModel && !self.isLoadingModel)
+ else { throw ASRActivityError.settingsRestoreUnavailable }
+ return try self.acquireExclusiveActivity(.settingsRestore)
+ }
+
func releaseExclusiveActivity(_ lease: ASRActivityLease) {
guard self.activeActivityLease == lease else { return }
if self.isMeetingASRClaimBlocking(lease: lease) {
@@ -853,7 +885,6 @@ final class ASRService: ObservableObject {
private var lastBoostHitTerm: String?
private var hasPendingParakeetVocabularyReload: Bool = false
private var vocabularyChangeObserver: NSObjectProtocol?
- private var settingsBackupRestoreObserver: NSObjectProtocol?
private var clamshellStateChangeObserver: NSObjectProtocol?
private var inputDeviceAvailabilityChangeObserver: NSObjectProtocol?
@@ -934,6 +965,24 @@ final class ASRService: ObservableObject {
)
}
+ func configureDictationModeSwitchForTesting(
+ ownedLease: ASRActivityLease?,
+ starting: Bool = false,
+ finalizing: Bool = false,
+ dictionaryTraining: Bool = false
+ ) {
+ self.dictationActivityLease = ownedLease
+ self.isStarting = starting
+ self.isStoppingFinalTranscription = finalizing
+ self.isDictionaryTrainingCaptureActive = dictionaryTraining
+ }
+
+ func beginDictationBufferDrainForTesting(recovering: Bool = false) -> (() -> Void)? {
+ guard let token = self.recordingBufferHandoffGate.begin() else { return nil }
+ if recovering { self.recordingBufferHandoffGate.markTimedOut(token) }
+ return { self.recordingBufferHandoffGate.complete(token) }
+ }
+
func finishAudioRouteRecoveryTest() async {
await self.cancelAudioRouteRecoveryAndWait()
self.isRunning = false
@@ -1002,6 +1051,11 @@ final class ASRService: ObservableObject {
@Published private(set) var deletingModelID: String?
#if DEBUG
var modelProvidersForTesting: [SettingsStore.SpeechModel: TranscriptionProvider] = [:]
+
+ func prepareProviderRecoveryForTesting(_ provider: TranscriptionProvider, modelsAlreadyCached: Bool) async throws {
+ try await self.prepareProviderWithRecovery(provider: provider, modelsAlreadyCached: modelsAlreadyCached, progressHandler: { _ in })
+ }
+
#endif
var hasActiveModelPreparation: Bool {
@@ -1112,7 +1166,7 @@ final class ASRService: ObservableObject {
}
case .appleSpeech:
return self.getAppleSpeechProvider()
- case .parakeetTDT, .parakeetTDTv2:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico:
return self.getFluidAudioProvider()
case .parakeetRealtime:
return self.getParakeetRealtimeProvider()
@@ -1231,7 +1285,7 @@ final class ASRService: ObservableObject {
/// Gets a provider for a specific model (without changing the active selection)
/// Used for downloading models without switching the active model.
- private func getProvider(for model: SettingsStore.SpeechModel) -> TranscriptionProvider {
+ private func getProvider(for model: SettingsStore.SpeechModel, updateWeights: Bool = false) -> TranscriptionProvider {
#if DEBUG
if let injected = self.modelProvidersForTesting[model] { return injected }
#endif
@@ -1244,9 +1298,9 @@ final class ASRService: ObservableObject {
}
case .appleSpeech:
return AppleSpeechProvider()
- case .parakeetTDT, .parakeetTDTv2:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico:
// Create a new provider configured for the specific model
- return FluidAudioProvider(modelOverride: model, configureWordBoosting: false)
+ return FluidAudioProvider(modelOverride: model, configureWordBoosting: false, updateCompactWeights: updateWeights)
case .parakeetRealtime:
return ParakeetRealtimeProvider()
case .cohereTranscribeSixBit:
@@ -1269,8 +1323,31 @@ final class ASRService: ObservableObject {
func downloadModel(
_ model: SettingsStore.SpeechModel,
source: AnalyticsModelDownloadSource = .settings,
+ updateWeights: Bool = false,
progressHandler: ((Double) -> Void)?
) async throws {
+ try Task.checkCancellation()
+ let updateLease: ASRActivityLease?
+ if updateWeights {
+ guard model == .fluidParakeetMini || model == .fluidParakeetPico else {
+ throw NSError(domain: "ASRService", code: -2003, userInfo: [NSLocalizedDescriptionKey: "Only Mini and Pico support weight updates."])
+ }
+ guard !self.isTerminating, !self.isRunning, !self.isStarting, !self.isStoppingFinalTranscription,
+ !self.recordingBufferHandoffGate.isActive, !self.recordingBufferHandoffGate.isRecovering,
+ !self.isMicrophonePreviewRequested, !self.isMicrophonePreviewActive, !self.isDictionaryTrainingCaptureActive,
+ self.providerResetDrain == nil, !self.isCancellingModelPreparation, !self.isCancellingModelDownload,
+ !self.meetingModelResidency.isExclusive
+ else {
+ throw ASRActivityError.activityInProgress(self.activeExclusiveActivity ?? .modelMaintenance)
+ }
+ updateLease = try self.acquireExclusiveActivity(.modelMaintenance)
+ } else {
+ updateLease = nil
+ }
+ defer { if let updateLease { self.releaseExclusiveActivity(updateLease) } }
+ guard self.activeExclusiveActivity != .settingsRestore else {
+ throw ASRActivityError.activityInProgress(.settingsRestore)
+ }
let admission = try self.meetingModelResidency.beginOperation(owner: "speech", modelID: model.id)
defer { self.meetingModelResidency.endOperation(admission) }
if self.isMeetingASRPreparationClaimed {
@@ -1285,7 +1362,7 @@ final class ASRService: ObservableObject {
}
let operationID = UUID()
- let provider = self.getProvider(for: model)
+ let provider = self.getProvider(for: model, updateWeights: updateWeights)
self.modelDownloadOperationID = operationID
self.downloadingModelId = model.id
self.downloadProgress = nil
@@ -1314,11 +1391,12 @@ final class ASRService: ObservableObject {
)
}
})
- try Task.checkCancellation()
+ if !updateWeights { try Task.checkCancellation() }
DebugLogger.shared.info("Model download completed: \(model.displayName)", source: "ASRService")
} catch {
+ if ParakeetArchiveDownloader.isCleanupFailure(error) { throw error }
let wasCancelled = Task.isCancelled || Self.isModelPreparationCancellation(error)
- if wasCancelled,
+ if wasCancelled, !updateWeights,
provider.shouldClearCacheAfterCancellation,
provider.modelsExistOnDisk() == false
{
@@ -1340,6 +1418,7 @@ final class ASRService: ObservableObject {
self.downloadProgress = nil
self.modelPreparationPhase = nil
self.isCancellingModelDownload = false
+ SpeechModelInstallationSnapshot.shared.refresh()
}
}
@@ -1349,11 +1428,22 @@ final class ASRService: ObservableObject {
} onCancel: {
task.cancel()
}
+ if updateWeights, SettingsStore.shared.selectedSpeechModel == model {
+ // Release the update lease only after progress and operation cleanup;
+ // the normal deferred reset then retires the old active checkpoint.
+ self.providerResetPending = true
+ }
self.finishModelDownloadAnalytics(operationID: operationID, outcome: .succeeded)
} catch is CancellationError {
self.finishModelDownloadAnalytics(operationID: operationID, outcome: .cancelled)
throw CancellationError()
} catch {
+ if updateWeights, SettingsStore.shared.selectedSpeechModel == model,
+ let failure = error as? ParakeetArchiveDownloader.DownloadError,
+ case .replacementCleanupFailed = failure
+ {
+ self.providerResetPending = true
+ }
self.finishModelDownloadAnalytics(operationID: operationID, outcome: .failed)
throw error
}
@@ -1402,10 +1492,16 @@ final class ASRService: ObservableObject {
}
let resetDrainID = UUID()
let executor = self.transcriptionExecutor
- let resetDrainTask = Task { await executor.cancelAndAwaitPending() }
+ let resetDrainTask = Task { @MainActor [weak self] in
+ await executor.cancelAndAwaitPending()
+ // A completed handle must not leave future imports permanently busy.
+ if self?.providerResetDrain?.id == resetDrainID {
+ self?.providerResetDrain = nil
+ }
+ }
self.providerResetDrain = (resetDrainID, resetDrainTask)
- // Keep the task handle until its provider has stopped and cancellation cleanup has
- // completed. The next ensureAsrReady call waits for it before touching the same cache.
+ // ensureAsrReady joins this executor drain. The retiring preparation task
+ // separately remains retained until its provider cancellation cleanup finishes.
self.ensureReadyProviderKey = nil
self.ensureReadyOperationID = nil
self.lastBoostHitTerm = nil
@@ -2168,19 +2264,6 @@ final class ASRService: ObservableObject {
self?.handleParakeetVocabularyDidChange()
}
}
- self.settingsBackupRestoreObserver = NotificationCenter.default.addObserver(
- forName: .settingsBackupDidRestore,
- object: nil,
- queue: .main
- ) { [weak self] _ in
- Task { @MainActor [weak self] in
- self?.scheduleAudioRouteRecovery(
- reason: "settings backup restored",
- requiresIdlePrewarm: true,
- reconcilesInputSelection: true
- )
- }
- }
self.clamshellStateChangeObserver = NotificationCenter.default.addObserver(
forName: .clamshellStateDidChange,
object: nil,
@@ -2210,9 +2293,6 @@ final class ASRService: ObservableObject {
if let observer = self.engineConfigurationChangeObserver {
NotificationCenter.default.removeObserver(observer)
}
- if let observer = self.settingsBackupRestoreObserver {
- NotificationCenter.default.removeObserver(observer)
- }
if let observer = self.clamshellStateChangeObserver {
NotificationCenter.default.removeObserver(observer)
}
@@ -2248,6 +2328,20 @@ final class ASRService: ObservableObject {
)
}
+ @MainActor
+ func handleSettingsBackupDidRestore() {
+ // BackupService calls this synchronously while settingsRestore holds admission.
+ // Its release consumes the pending reset before a new capture can enter.
+ // Downloaded model files remain intact.
+ self.resetTranscriptionProvider()
+ SpeechModelInstallationSnapshot.shared.refresh()
+ self.scheduleAudioRouteRecovery(
+ reason: "settings backup restored",
+ requiresIdlePrewarm: true,
+ reconcilesInputSelection: true
+ )
+ }
+
@MainActor
private func handleParakeetVocabularyDidChange() {
let model = SettingsStore.shared.selectedSpeechModel
@@ -2412,6 +2506,8 @@ final class ASRService: ObservableObject {
} else {
exists = self.getAppleSpeechProvider().modelsExistOnDisk()
}
+ } else if model == .fluidParakeetMini || model == .fluidParakeetPico {
+ exists = (try? await self.modelArtifactsExist(provider: self.transcriptionProvider)) ?? false
} else {
exists = model.isInstalled
}
@@ -2457,6 +2553,7 @@ final class ASRService: ObservableObject {
self.isRunning == false,
self.isStarting == false,
self.activeExclusiveActivity != .meeting,
+ self.activeExclusiveActivity != .settingsRestore,
self.isTerminating == false
else { return }
@@ -2475,6 +2572,7 @@ final class ASRService: ObservableObject {
self.isRunning == false,
self.isStarting == false,
self.activeExclusiveActivity != .meeting,
+ self.activeExclusiveActivity != .settingsRestore,
self.isTerminating == false,
Task.isCancelled == false
else {
@@ -2494,6 +2592,7 @@ final class ASRService: ObservableObject {
self.isRunning == false,
self.isStarting == false,
self.activeExclusiveActivity != .meeting,
+ self.activeExclusiveActivity != .settingsRestore,
self.isTerminating == false,
Task.isCancelled == false
else {
@@ -2520,6 +2619,7 @@ final class ASRService: ObservableObject {
self.isRunning == false,
self.isStarting == false,
self.activeExclusiveActivity != .meeting,
+ self.activeExclusiveActivity != .settingsRestore,
self.isTerminating == false
else { throw CancellationError() }
_ = try await self.directAudioLifecycleController.start(
@@ -2532,6 +2632,7 @@ final class ASRService: ObservableObject {
self.isRunning == false,
self.isStarting == false,
self.activeExclusiveActivity != .meeting,
+ self.activeExclusiveActivity != .settingsRestore,
self.isTerminating == false
else { throw CancellationError() }
self.activeAudioCaptureBackend = .directCoreAudio
@@ -3971,7 +4072,8 @@ final class ASRService: ObservableObject {
guard let self, !self.isTerminating,
SettingsStore.shared.selectedSpeechModel.id == model.id else { return }
// Never download a missing model just to restore residency.
- guard self.transcriptionProvider.modelsExistOnDisk() else { return }
+ guard try await self.modelArtifactsExist(provider: self.transcriptionProvider),
+ !self.isTerminating, SettingsStore.shared.selectedSpeechModel.id == model.id else { return }
try await self.ensureAsrReady()
if SettingsStore.shared.selectedSpeechModel.id != model.id,
let lease = self.activeActivityLease
@@ -6262,6 +6364,9 @@ final class ASRService: ObservableObject {
progressHandler: ((Double) -> Void)? = nil
) async throws {
try Task.checkCancellation()
+ guard self.activeExclusiveActivity != .settingsRestore else {
+ throw ASRActivityError.activityInProgress(.settingsRestore)
+ }
let admission = try self.meetingModelResidency.beginOperation(
owner: "speech", modelID: SettingsStore.shared.selectedSpeechModel.id
)
@@ -6315,6 +6420,9 @@ final class ASRService: ObservableObject {
}
}
+ guard self.activeExclusiveActivity != .settingsRestore else {
+ throw ASRActivityError.activityInProgress(.settingsRestore)
+ }
guard self.deletingModelID == nil, SettingsStore.shared.selectedSpeechModel == model else {
throw CancellationError()
}
@@ -6356,6 +6464,15 @@ final class ASRService: ObservableObject {
}
}
+ private func modelArtifactsExist(provider: TranscriptionProvider) async throws -> Bool {
+ #if arch(arm64)
+ if let compactProvider = provider as? FluidAudioProvider {
+ return try await compactProvider.refreshModelsExistOnDiskAsync()
+ }
+ #endif
+ return provider.modelsExistOnDisk()
+ }
+
private func performEnsureAsrReady(
provider: TranscriptionProvider,
operationID: UUID,
@@ -6376,13 +6493,17 @@ final class ASRService: ObservableObject {
return
}
+ defer { SpeechModelInstallationSnapshot.shared.refresh() }
+
// If the flag is set but provider isn't ready (e.g., provider switch without reset), re-init.
if self.isAsrReady, !provider.isReady {
DebugLogger.shared.debug("ASR marked ready but provider not ready; re-initializing", source: "ASRService")
}
self.isAsrReady = false
- let modelsAlreadyCached = provider.modelsExistOnDisk()
+ let modelsAlreadyCached = try await self.modelArtifactsExist(provider: provider)
+ try Task.checkCancellation()
+ guard self.ensureReadyOperationID == operationID else { throw CancellationError() }
let totalStartTime = Date()
do {
@@ -6515,7 +6636,7 @@ final class ASRService: ObservableObject {
}
throw CancellationError()
} catch {
- if Task.isCancelled || Self.isModelPreparationCancellation(error) {
+ if !ParakeetArchiveDownloader.isCleanupFailure(error), Task.isCancelled || Self.isModelPreparationCancellation(error) {
self.finishModelDownloadAnalytics(operationID: operationID, outcome: .cancelled)
if provider.shouldClearCacheAfterCancellation,
provider.modelsExistOnDisk() == false
@@ -6652,9 +6773,17 @@ final class ASRService: ObservableObject {
)
return
} catch {
+ // Staging cleanup failure must not delete a successfully published cache
+ // or hide its repair path when cancellation was also requested.
+ if ParakeetArchiveDownloader.isCleanupFailure(error) { throw error }
if Task.isCancelled || Self.isModelPreparationCancellation(error) {
throw CancellationError()
}
+ if let compact = provider as? FluidAudioProvider, compact.preservesInstalledCompactWeights {
+ // Repairing by deletion could silently upgrade an installed older
+ // checkpoint. Explicit Update/Delete owns that choice instead.
+ throw error
+ }
firstError = error
DebugLogger.shared.error("ASRService: First prepare attempt for \(provider.name) failed after \(String(format: "%.2f", Date().timeIntervalSince(start)))s", source: "ASRService")
DebugLogger.shared.warning(
@@ -6692,6 +6821,7 @@ final class ASRService: ObservableObject {
do {
try await provider.prepare(progressHandler: progressHandler)
} catch {
+ if ParakeetArchiveDownloader.isCleanupFailure(error) { throw error }
if Task.isCancelled || Self.isModelPreparationCancellation(error) {
throw CancellationError()
}
@@ -6771,6 +6901,7 @@ final class ASRService: ObservableObject {
let isActive = SettingsStore.shared.selectedSpeechModel == model
defer {
self.deletingModelID = nil
+ SpeechModelInstallationSnapshot.shared.refresh()
self.releaseExclusiveActivity(activityLease)
}
DebugLogger.shared.debug("Clearing model cache for \(model.displayName)", source: "ASRService")
diff --git a/Sources/Fluid/Services/AppSearch/AppSearchService.swift b/Sources/Fluid/Services/AppSearch/AppSearchService.swift
index 8f3dec56..9e64466d 100644
--- a/Sources/Fluid/Services/AppSearch/AppSearchService.swift
+++ b/Sources/Fluid/Services/AppSearch/AppSearchService.swift
@@ -60,7 +60,12 @@ nonisolated struct AppSearchGroup: Identifiable, Equatable, Sendable {
/// next to one from another, so hits are never merged across kinds.
@MainActor
final class AppSearchService: ObservableObject {
- static let shared = AppSearchService()
+ static let shared = AppSearchService(
+ prepareIndex: { try await SearchIndexCoordinator.shared.prepareForSearch() },
+ retryPreparation: {
+ TranscriptionHistoryStore.shared.retryLoadingIfNeeded()
+ }
+ )
/// Hits fetched per indexed kind. The UI shows a few and offers the rest.
static let limit = 50
@@ -75,14 +80,48 @@ final class AppSearchService: ObservableObject {
}
@Published private(set) var groups: [AppSearchGroup] = []
+ @Published private(set) var isSearching = false
+ @Published private(set) var searchError: String?
private let index: SearchIndex
+ private let prepareIndex: @MainActor () async throws -> Void
+ private let retryPreparation: @MainActor () -> Void
+ private let performSearch: (@MainActor (String) async -> [AppSearchGroup])?
+ private let readVocabulary: @Sendable () async throws -> [ParakeetVocabularyStore.VocabularyConfig.Term]
private var task: Task<Void, Never>?
private var token: ZeppelinCancellationToken?
+ private var tokenID: UUID?
private var chatAvailabilitySubscription: AnyCancellable?
-
- init(index: SearchIndex = .shared) {
+ private var vocabularySubscription: AnyCancellable?
+ private var vocabularyTerms: [ParakeetVocabularyStore.VocabularyConfig.Term] = []
+ private var hasVocabularySnapshot = false
+ private var vocabularyGeneration: UInt64 = 0
+ private var stopped = false
+
+ init(
+ index: SearchIndex = .shared,
+ prepareIndex: @escaping @MainActor () async throws -> Void = {},
+ retryPreparation: @escaping @MainActor () -> Void = {},
+ performSearch: (@MainActor (String) async -> [AppSearchGroup])? = nil,
+ readVocabulary: @escaping @Sendable () async throws -> [ParakeetVocabularyStore.VocabularyConfig.Term] = {
+ try await ParakeetVocabularyStore.readSearchTerms()
+ },
+ notificationCenter: NotificationCenter = .default
+ ) {
self.index = index
+ self.prepareIndex = prepareIndex
+ self.retryPreparation = retryPreparation
+ self.performSearch = performSearch
+ self.readVocabulary = readVocabulary
+ self.vocabularySubscription = notificationCenter.publisher(for: .parakeetVocabularyDidChange)
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] _ in
+ guard let self else { return }
+ self.vocabularyGeneration &+= 1
+ self.vocabularyTerms = []
+ self.hasVocabularySnapshot = false
+ self.refresh()
+ }
self.chatAvailabilitySubscription = ChatHistoryStore.shared.$sessions
.map { Set($0.filter { !$0.isArchived }.map(\.id)) }
.removeDuplicates()
@@ -100,18 +139,43 @@ final class AppSearchService: ObservableObject {
self.schedule()
}
+ /// Explicit retries may reload failed history. Ordinary keystrokes never do.
+ func retry() {
+ guard !self.stopped else { return }
+ self.retryPreparation()
+ self.schedule()
+ }
+
+ func stop() {
+ self.stopped = true
+ self.task?.cancel()
+ self.task = nil
+ if let token = self.token { Task { try? await token.cancel() } }
+ self.token = nil
+ self.tokenID = nil
+ self.groups = []
+ self.isSearching = false
+ self.searchError = nil
+ }
+
private func schedule() {
+ guard !self.stopped else { return }
self.task?.cancel()
if let token = self.token {
self.token = nil
+ self.tokenID = nil
Task { try? await token.cancel() }
}
let query = self.query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !query.isEmpty else {
self.groups = []
+ self.isSearching = false
+ self.searchError = nil
return
}
self.groups = []
+ self.isSearching = true
+ self.searchError = nil
self.task = Task { [weak self] in
try? await Task.sleep(for: Self.debounce)
guard !Task.isCancelled, let self else { return }
@@ -121,12 +185,39 @@ final class AppSearchService: ObservableObject {
guard !Task.isCancelled else { return }
let availableIDs = Set(ChatHistoryStore.shared.sessions.filter { !$0.isArchived }.map(\.id))
self.groups = Self.removingUnavailableChats(from: groups, availableIDs: availableIDs)
+ self.isSearching = false
}
}
func search(_ query: String) async -> [AppSearchGroup] {
+ guard !self.stopped, !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }
+ do {
+ try await self.prepareIndex()
+ try Task.checkCancellation()
+ } catch {
+ if !Task.isCancelled, self.query.trimmingCharacters(in: .whitespacesAndNewlines) == query {
+ self.searchError = error is SearchIndexCoordinator.PreparationError
+ ? "Search is still getting ready. Try again shortly."
+ : "Search is unavailable right now. Try again."
+ }
+ return []
+ }
+ guard !self.stopped else { return [] }
+ if let performSearch = self.performSearch { return await performSearch(query) }
let token = try? await ZeppelinCancellationToken.create()
+ guard !Task.isCancelled, !self.stopped else {
+ if let token { try? await token.cancel() }
+ return []
+ }
+ let tokenID = UUID()
self.token = token
+ self.tokenID = tokenID
+ defer {
+ if self.tokenID == tokenID {
+ self.token = nil
+ self.tokenID = nil
+ }
+ }
async let history = self.hits(.history, query, token)
async let transcripts = self.hits(.transcripts, query, token)
@@ -136,10 +227,12 @@ final class AppSearchService: ObservableObject {
self.transcriptGroup(transcripts, query),
self.chatGroup(chats, query),
]
+ guard !Task.isCancelled else { return [] }
+ let vocabulary = await self.vocabularyGroup(query)
let inMemory = [
self.dictionaryGroup(query),
self.promptGroup(query),
- self.vocabularyGroup(query),
+ vocabulary,
self.punctuationGroup(query),
self.settingsGroup(query),
]
@@ -191,7 +284,8 @@ final class AppSearchService: ObservableObject {
}
private func historyGroup(_ hits: [SearchIndex.Hit], _ query: String) -> AppSearchGroup {
- let rows = Dictionary(TranscriptionHistoryStore.shared.entries.map { ($0.id, $0) }) { first, _ in first }
+ let wanted = Set(hits.map(\.id))
+ let rows = Dictionary(TranscriptionHistoryStore.shared.entries.lazy.filter { wanted.contains($0.id) }.map { ($0.id, $0) }) { first, _ in first }
return AppSearchGroup(kind: .history, hits: Self.ranked(hits, rows: rows, date: \.timestamp) { entry in
AppSearchHit(
kind: .history,
@@ -204,7 +298,8 @@ final class AppSearchService: ObservableObject {
}
private func transcriptGroup(_ hits: [SearchIndex.Hit], _ query: String) -> AppSearchGroup {
- let rows = Dictionary(FileTranscriptionHistoryStore.shared.entries.map { ($0.id, $0) }) { first, _ in first }
+ let wanted = Set(hits.map(\.id))
+ let rows = Dictionary(FileTranscriptionHistoryStore.shared.entries.lazy.filter { wanted.contains($0.id) }.map { ($0.id, $0) }) { first, _ in first }
return AppSearchGroup(kind: .transcripts, hits: Self.ranked(hits, rows: rows, date: \.timestamp) { entry in
AppSearchHit(
kind: .transcripts,
@@ -217,9 +312,10 @@ final class AppSearchService: ObservableObject {
}
private func chatGroup(_ hits: [SearchIndex.Hit], _ query: String) -> AppSearchGroup {
+ let wanted = Set(hits.map(\.id))
let rows = Dictionary(
ChatHistoryStore.shared.sessions.compactMap { session -> (UUID, ChatSession)? in
- guard !session.isArchived, let id = UUID(uuidString: session.id) else { return nil }
+ guard !session.isArchived, let id = UUID(uuidString: session.id), wanted.contains(id) else { return nil }
return (id, session)
}
) { first, _ in first }
@@ -275,8 +371,23 @@ final class AppSearchService: ObservableObject {
return AppSearchGroup(kind: .prompts, hits: hits)
}
- private func vocabularyGroup(_ query: String) -> AppSearchGroup {
- let terms = (try? ParakeetVocabularyStore.shared.loadUserBoostTerms()) ?? []
+ private func vocabularyGroup(_ query: String) async -> AppSearchGroup {
+ let generation = self.vocabularyGeneration
+ let terms: [ParakeetVocabularyStore.VocabularyConfig.Term]
+ if self.hasVocabularySnapshot {
+ terms = self.vocabularyTerms
+ } else {
+ do {
+ terms = try await self.readVocabulary()
+ if generation == self.vocabularyGeneration {
+ self.vocabularyTerms = terms
+ self.hasVocabularySnapshot = true
+ }
+ } catch {
+ // A transient read failure must remain retryable on the next query.
+ terms = []
+ }
+ }
let hits = terms
.filter { Self.matches(query, [$0.text] + $0.aliases) }
.map { term in
diff --git a/Sources/Fluid/Services/CompactSpeechModelReleaseCatalog.swift b/Sources/Fluid/Services/CompactSpeechModelReleaseCatalog.swift
new file mode 100644
index 00000000..4d9db43f
--- /dev/null
+++ b/Sources/Fluid/Services/CompactSpeechModelReleaseCatalog.swift
@@ -0,0 +1,467 @@
+import Combine
+import Darwin
+import Foundation
+
+/// UI/provider lookup reads immutable metadata; all feed and state IO happens off main.
+@MainActor
+final class CompactSpeechModelReleaseCatalog: ObservableObject {
+ typealias Descriptor = ParakeetSpeechModelCatalog.Descriptor
+ typealias Variant = ParakeetSpeechModelCatalog.Variant
+ typealias Fetcher = @Sendable () async throws -> Data
+
+ nonisolated struct Snapshot: Equatable, Sendable {
+ let revision: UInt64
+ let sequence: Int
+ let descriptors: [Variant: Descriptor]
+ let rejectedManifestHashes: Set<String>
+ }
+
+ private nonisolated struct StoredState: Codable, Sendable {
+ let lastCheck: Date?
+ let lastCheckSucceeded: Bool
+ let rejectedManifestHashes: [String]
+ }
+
+ private nonisolated struct FeedCommit: Sendable {
+ let payload: SpeechModelFeed.Payload
+ let acceptedIncoming: Bool
+ }
+
+ private nonisolated enum CacheError: Error { case busy, invalidLock }
+
+ static let shared = CompactSpeechModelReleaseCatalog()
+ nonisolated static let manifestURL = CompactSpeechModelReleaseCatalog.fixedURL("https://models.fluidvoice.app/feed/v1/speech-models.json")
+ nonisolated static let stagingURL = CompactSpeechModelReleaseCatalog.fixedURL("https://models.fluidvoice.app/feed/v1/speech-models-staging.json")
+ nonisolated static let publicKeys = [
+ "etCg9rPWJ81mB3XdJfKs2Y6QeuJjIIqCYfbYy40LRY4=",
+ "Lf4aPkJzkEbu7nUj2Oh+ltoCePbPGXQMEMh+KfqtJvw=",
+ ]
+ nonisolated static let maximumManifestBytes = SpeechModelFeed.maximumEnvelopeBytes
+ nonisolated static let supportedFormat = 1
+ private nonisolated static let maximumRejectedReleases = 64
+ @Published private(set) var snapshot = Snapshot(
+ revision: 0,
+ sequence: 0,
+ descriptors: [.mini: ParakeetSpeechModelCatalog.mini, .pico: ParakeetSpeechModelCatalog.pico],
+ rejectedManifestHashes: []
+ )
+ var revision: UInt64 { self.snapshot.revision }
+
+ private let keys: [String]
+ private let cacheURL: URL?
+ private let stateURL: URL?
+ private let fetch: Fetcher
+ private let build: Int
+ private let refreshInterval: TimeInterval
+ private let retryInterval: TimeInterval
+ private let now: @Sendable () -> Date
+ private let staging: Bool
+ private var loadedCache = false
+ private var loadTask: Task<Void, Never>?
+ private var lastCheck: Date?
+ private var lastCheckSucceeded = false
+ private var rejectedOrder: [String] = []
+ private var refreshTask: Task<Void, Never>?
+ private var stateWriteTask: Task<Void, Never>?
+ private var pendingState: StoredState?
+
+ init(
+ publicKeys: [String] = CompactSpeechModelReleaseCatalog.publicKeys,
+ cacheURL: URL? = CompactSpeechModelReleaseCatalog.defaultCacheURL(),
+ build: Int = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String).flatMap(Int.init) ?? 0,
+ refreshInterval: TimeInterval = 24 * 60 * 60,
+ retryInterval: TimeInterval = 60 * 60,
+ now: @escaping @Sendable () -> Date = { Date() },
+ fetch: Fetcher? = nil
+ ) {
+ self.keys = publicKeys
+ self.cacheURL = cacheURL
+ self.stateURL = cacheURL?.appendingPathExtension("state")
+ self.build = build
+ self.refreshInterval = refreshInterval
+ self.retryInterval = retryInterval
+ self.now = now
+ self.staging = Self.usesStaging
+ self.fetch = fetch ?? { try await Self.fetchManifest() }
+ }
+
+ func descriptor(for model: SettingsStore.SpeechModel) -> Descriptor? {
+ switch model {
+ case .fluidParakeetMini: self.descriptor(for: .mini)
+ case .fluidParakeetPico: self.descriptor(for: .pico)
+ default: nil
+ }
+ }
+
+ func descriptor(for variant: Variant) -> Descriptor {
+ self.snapshot.descriptors[variant] ?? ParakeetSpeechModelCatalog.descriptor(for: variant)
+ }
+
+ /// Event-driven checks join one worker. A failure never removes the last good feed.
+ func refreshIfNeeded(force: Bool = false) async {
+ if let refreshTask { await refreshTask.value; return }
+ let task = Task { [weak self] in
+ guard let self else { return }
+ await self.loadCacheIfNeeded()
+ let date = self.now()
+ let interval = self.lastCheckSucceeded ? self.refreshInterval : self.retryInterval
+ if !force, !self.staging, let lastCheck = self.lastCheck {
+ let elapsed = date.timeIntervalSince(lastCheck)
+ if elapsed >= 0, elapsed < interval {
+ if self.pendingState != nil { await self.persistState() }
+ self.refreshTask = nil
+ return
+ }
+ }
+ self.lastCheck = date
+ do {
+ let data = try await self.fetch()
+ try Task.checkCancellation()
+ if let cacheURL = self.cacheURL {
+ let commit = try await Self.commitFeed(data, at: cacheURL, publicKeys: self.keys, lastSequence: self.snapshot.sequence)
+ self.apply(commit.payload)
+ self.lastCheckSucceeded = commit.acceptedIncoming
+ } else {
+ let payload = try await Self.verify(data, publicKeys: self.keys, lastSequence: self.snapshot.sequence)
+ self.apply(payload)
+ self.lastCheckSucceeded = true
+ }
+ } catch {
+ self.lastCheckSucceeded = false
+ }
+ await self.persistState()
+ self.refreshTask = nil
+ }
+ self.refreshTask = task
+ await task.value
+ }
+
+ /// Only a staged model's load/sentence proof failure rejects a release; cancellation does not.
+ func reject(manifestSHA256: String) async {
+ guard Self.validHash(manifestSHA256) else { return }
+ await self.loadCacheIfNeeded()
+ if self.snapshot.rejectedManifestHashes.contains(manifestSHA256) {
+ if self.pendingState != nil { await self.persistState() }
+ return
+ }
+ self.rejectedOrder.append(manifestSHA256)
+ if self.rejectedOrder.count > Self.maximumRejectedReleases {
+ self.rejectedOrder.removeFirst(self.rejectedOrder.count - Self.maximumRejectedReleases)
+ }
+ self.snapshot = Snapshot(
+ revision: self.snapshot.revision &+ 1,
+ sequence: self.snapshot.sequence,
+ descriptors: self.snapshot.descriptors,
+ rejectedManifestHashes: Set(self.rejectedOrder)
+ )
+ await self.persistState()
+ }
+
+ private func loadCacheIfNeeded() async {
+ if let loadTask { await loadTask.value; return }
+ guard !self.loadedCache else { return }
+ let task = Task { [weak self] in
+ guard let self else { return }
+ if let stateURL = self.stateURL,
+ let bytes = await Self.readBoundedData(at: stateURL),
+ let state = await Self.decodeState(bytes)
+ {
+ self.lastCheck = state.lastCheck
+ self.lastCheckSucceeded = state.lastCheckSucceeded
+ self.rejectedOrder = state.rejectedManifestHashes
+ self.snapshot = Snapshot(
+ revision: self.snapshot.revision &+ 1,
+ sequence: self.snapshot.sequence,
+ descriptors: self.snapshot.descriptors,
+ rejectedManifestHashes: Set(self.rejectedOrder)
+ )
+ }
+ if let cacheURL = self.cacheURL,
+ let bytes = await Self.readBoundedData(at: cacheURL),
+ let payload = try? await Self.verify(bytes, publicKeys: self.keys, lastSequence: 0)
+ {
+ self.apply(payload)
+ } else if self.lastCheckSucceeded {
+ // Missing/corrupt last-good metadata cannot suppress a recovery fetch for a day.
+ self.lastCheck = nil
+ self.lastCheckSucceeded = false
+ }
+ self.loadedCache = true
+ self.loadTask = nil
+ }
+ self.loadTask = task
+ await task.value
+ }
+
+ private func apply(_ payload: SpeechModelFeed.Payload) {
+ let descriptors = Self.descriptors(in: payload, build: self.build)
+ guard self.snapshot.sequence != payload.sequence || descriptors != self.snapshot.descriptors else { return }
+ self.snapshot = Snapshot(
+ revision: self.snapshot.revision &+ 1,
+ sequence: payload.sequence,
+ descriptors: descriptors,
+ rejectedManifestHashes: self.snapshot.rejectedManifestHashes
+ )
+ }
+
+ nonisolated static func descriptors(in payload: SpeechModelFeed.Payload, build: Int) -> [Variant: Descriptor] {
+ var result: [Variant: Descriptor] = [:]
+ for variant in [Variant.mini, .pico] {
+ let builtIn = ParakeetSpeechModelCatalog.descriptor(for: variant)
+ if let entry = SpeechModelFeed.entry(in: payload, model: variant.rawValue, platform: "macos", build: build, supportedFormat: self.supportedFormat) {
+ result[variant] = builtIn.replacingArchive(url: entry.url, sha256: entry.sha256, byteCount: entry.bytes, manifestSHA256: entry.manifestSHA256)
+ } else {
+ result[variant] = builtIn
+ }
+ }
+ return result
+ }
+
+ private func persistState() async {
+ guard let stateURL = self.stateURL else { return }
+ self.pendingState = StoredState(
+ lastCheck: self.lastCheck,
+ lastCheckSucceeded: self.lastCheckSucceeded,
+ rejectedManifestHashes: self.rejectedOrder
+ )
+ if let stateWriteTask { await stateWriteTask.value; return }
+ let task = Task { [weak self] in
+ guard let self else { return }
+ while let state = self.pendingState {
+ self.pendingState = nil
+ if let stored = await Self.writeState(state, at: stateURL) {
+ // A competing process may have remembered another failed release.
+ let merged = Self.mergedRejections(stored.rejectedManifestHashes, self.rejectedOrder)
+ self.rejectedOrder = merged
+ if Set(merged) != self.snapshot.rejectedManifestHashes {
+ self.snapshot = Snapshot(
+ revision: self.snapshot.revision &+ 1,
+ sequence: self.snapshot.sequence,
+ descriptors: self.snapshot.descriptors,
+ rejectedManifestHashes: Set(merged)
+ )
+ }
+ } else {
+ // Keep one latest state for the next event; never spin on a busy/broken volume.
+ if self.pendingState == nil { self.pendingState = state }
+ break
+ }
+ }
+ self.stateWriteTask = nil
+ }
+ self.stateWriteTask = task
+ await task.value
+ }
+
+ private nonisolated static var usesStaging: Bool {
+ #if DEBUG
+ ProcessInfo.processInfo.arguments.contains("--fv-model-feed=staging")
+ #else
+ false
+ #endif
+ }
+
+ private nonisolated static func defaultCacheURL() -> URL? {
+ #if DEBUG
+ let isDebug = true
+ #else
+ let isDebug = false
+ #endif
+ let folder = self.cacheFolderName(bundleIdentifier: Bundle.main.bundleIdentifier, isDebug: isDebug)
+ return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?
+ .appendingPathComponent(folder, isDirectory: true)
+ .appendingPathComponent(self.usesStaging ? "speech-model-feed-staging.json" : "speech-model-feed.json")
+ }
+
+ nonisolated static func cacheFolderName(bundleIdentifier: String?, isDebug: Bool) -> String {
+ guard isDebug else { return "FluidVoice" }
+ let identifier = bundleIdentifier ?? "debug"
+ let valid = !identifier.isEmpty && identifier != "." && identifier != ".."
+ && identifier.utf8.allSatisfy { (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 46 }
+ return "FluidVoice/\(valid ? identifier : "debug")"
+ }
+
+ private nonisolated static func fixedURL(_ value: String) -> URL {
+ guard let url = URL(string: value) else { preconditionFailure("Invalid speech model feed URL") }
+ return url
+ }
+
+ private nonisolated static func validHash(_ value: String) -> Bool {
+ value.utf8.count == 64 && value.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) }
+ }
+
+ @concurrent private static func verify(_ data: Data, publicKeys: [String], lastSequence: Int) async throws -> SpeechModelFeed.Payload {
+ try SpeechModelFeed.verified(envelope: data, publicKeys: publicKeys, lastSequence: lastSequence)
+ }
+
+ private final nonisolated class NoRedirects: NSObject, URLSessionTaskDelegate {
+ nonisolated func urlSession(
+ _ session: URLSession,
+ task: URLSessionTask,
+ willPerformHTTPRedirection response: HTTPURLResponse,
+ newRequest request: URLRequest,
+ completionHandler: @escaping (URLRequest?) -> Void
+ ) {
+ completionHandler(nil)
+ }
+ }
+
+ @concurrent private static func fetchManifest() async throws -> Data {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = 10
+ configuration.timeoutIntervalForResource = 10
+ let session = URLSession(configuration: configuration)
+ defer { session.invalidateAndCancel() }
+ var request = URLRequest(url: self.usesStaging ? self.stagingURL : self.manifestURL)
+ request.timeoutInterval = 10
+ request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
+ let (bytes, response) = try await session.bytes(for: request, delegate: NoRedirects())
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200,
+ http.expectedContentLength <= Int64(self.maximumManifestBytes)
+ else { throw URLError(.badServerResponse) }
+ var data = Data()
+ for try await byte in bytes {
+ try Task.checkCancellation()
+ guard data.count < self.maximumManifestBytes else { throw SpeechModelFeed.Rejection.tooLarge }
+ data.append(byte)
+ }
+ return data
+ }
+
+ @concurrent private static func readBoundedData(at url: URL) async -> Data? {
+ self.readData(at: url)
+ }
+
+ private nonisolated static func readData(at url: URL) -> Data? {
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
+ attributes[.type] as? FileAttributeType == .typeRegular,
+ let size = (attributes[.size] as? NSNumber)?.intValue, size > 0, size <= self.maximumManifestBytes,
+ let input = try? FileHandle(forReadingFrom: url)
+ else { return nil }
+ defer { try? input.close() }
+ guard let data = try? input.read(upToCount: self.maximumManifestBytes + 1), data.count <= self.maximumManifestBytes else { return nil }
+ return data
+ }
+
+ @concurrent private static func decodeState(_ data: Data) async -> StoredState? {
+ self.validatedState(data)
+ }
+
+ private nonisolated static func validatedState(_ data: Data) -> StoredState? {
+ guard let state = try? JSONDecoder().decode(StoredState.self, from: data),
+ state.rejectedManifestHashes.count <= self.maximumRejectedReleases,
+ state.rejectedManifestHashes.allSatisfy(self.validHash),
+ Set(state.rejectedManifestHashes).count == state.rejectedManifestHashes.count
+ else { return nil }
+ return state
+ }
+
+ private nonisolated static func writeData(_ data: Data, at url: URL) throws {
+ guard data.count <= self.maximumManifestBytes else { throw SpeechModelFeed.Rejection.tooLarge }
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try data.write(to: url, options: .atomic)
+ }
+
+ /// No network work is performed while locked. Contention exits immediately for a later retry.
+ private nonisolated static func withCacheLock<T>(at cacheURL: URL, operation: () throws -> T) throws -> T {
+ try Task.checkCancellation()
+ try FileManager.default.createDirectory(at: cacheURL.deletingLastPathComponent(), withIntermediateDirectories: true)
+ let lockURL = cacheURL.appendingPathExtension("lock")
+ let descriptor = open(lockURL.path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, 0o600)
+ guard descriptor >= 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
+ defer { Darwin.close(descriptor) }
+ var attributes = stat()
+ guard fstat(descriptor, &attributes) == 0, attributes.st_mode & S_IFMT == S_IFREG else { throw CacheError.invalidLock }
+ guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { throw CacheError.busy }
+ defer { flock(descriptor, LOCK_UN) }
+ try Task.checkCancellation()
+ return try operation()
+ }
+
+ @concurrent private static func commitFeed(_ data: Data, at url: URL, publicKeys: [String], lastSequence: Int) async throws -> FeedCommit {
+ try self.withCacheLock(at: url) {
+ let stored = self.readData(at: url).flatMap { try? SpeechModelFeed.verified(envelope: $0, publicKeys: publicKeys, lastSequence: 0) }
+ let payload = try SpeechModelFeed.verified(envelope: data, publicKeys: publicKeys, lastSequence: 0)
+ let floor = max(lastSequence, stored?.sequence ?? 0)
+ if payload.sequence < floor {
+ guard let stored, stored.sequence >= lastSequence else { throw SpeechModelFeed.Rejection.staleSequence }
+ return FeedCommit(payload: stored, acceptedIncoming: false)
+ }
+ try Task.checkCancellation()
+ try self.writeData(data, at: url)
+ return FeedCommit(payload: payload, acceptedIncoming: true)
+ }
+ }
+
+ private nonisolated static func mergedRejections(_ stored: [String], _ incoming: [String]) -> [String] {
+ var result: [String] = []
+ for hash in stored + incoming {
+ result.removeAll { $0 == hash }
+ result.append(hash)
+ }
+ return Array(result.suffix(self.maximumRejectedReleases))
+ }
+
+ @concurrent private static func writeState(_ state: StoredState, at url: URL) async -> StoredState? {
+ for attempt in 0..<3 {
+ do {
+ return try self.mergeState(state, at: url)
+ } catch CacheError.busy {
+ guard attempt < 2, !Task.isCancelled else { return nil }
+ do { try await Task.sleep(for: .milliseconds(20)) } catch { return nil }
+ } catch {
+ return nil
+ }
+ }
+ return nil
+ }
+
+ private nonisolated static func mergeState(_ state: StoredState, at url: URL) throws -> StoredState {
+ try self.withCacheLock(at: url.deletingPathExtension()) {
+ let stored = self.readData(at: url).flatMap(self.validatedState)
+ let freshness: StoredState
+ if let storedDate = stored?.lastCheck,
+ state.lastCheck == nil || storedDate > (state.lastCheck ?? .distantPast)
+ {
+ freshness = stored ?? state
+ } else {
+ freshness = state
+ }
+ let succeeded = stored?.lastCheck == state.lastCheck
+ ? state.lastCheckSucceeded && (stored?.lastCheckSucceeded ?? true)
+ : freshness.lastCheckSucceeded
+ let merged = StoredState(
+ lastCheck: freshness.lastCheck,
+ lastCheckSucceeded: succeeded,
+ rejectedManifestHashes: self.mergedRejections(stored?.rejectedManifestHashes ?? [], state.rejectedManifestHashes)
+ )
+ try Task.checkCancellation()
+ try self.writeData(JSONEncoder().encode(merged), at: url)
+ return merged
+ }
+ }
+}
+
+extension ParakeetSpeechModelCatalog.Descriptor {
+ nonisolated func replacingArchive(url: URL?, sha256: String?, byteCount: Int64? = nil, manifestSHA256: String? = nil) -> Self {
+ let bytes = byteCount ?? self.expectedDownloadBytes
+ return Self(
+ modelID: self.modelID,
+ variant: self.variant,
+ folderName: self.folderName,
+ expectedDownloadBytes: bytes,
+ archiveURL: url,
+ archiveSHA256: sha256,
+ requiredModelNames: self.requiredModelNames,
+ vocabularyFile: self.vocabularyFile,
+ displayName: self.displayName,
+ humanReadableName: self.humanReadableName,
+ languageSupport: self.languageSupport,
+ supportedLanguageCodes: self.supportedLanguageCodes,
+ downloadSize: String(format: "~%.1f MiB", Double(bytes) / 1_048_576),
+ cardDescription: self.cardDescription,
+ performanceRatings: self.performanceRatings,
+ manifestSHA256: manifestSHA256
+ )
+ }
+}
diff --git a/Sources/Fluid/Services/DictionaryAudioLearningService.swift b/Sources/Fluid/Services/DictionaryAudioLearningService.swift
index 34445481..50a66392 100644
--- a/Sources/Fluid/Services/DictionaryAudioLearningService.swift
+++ b/Sources/Fluid/Services/DictionaryAudioLearningService.swift
@@ -150,20 +150,31 @@ actor OriginalAudioEmbeddingExtractor {
@concurrent static func extract(_ evidence: DictionaryLearningAudioEvidence) async throws -> PronunciationEnrollmentCapture {
try Task.checkCancellation()
#if arch(arm64)
- let version: AsrModelVersion
- switch evidence.modelKey {
- case "parakeet-v2": version = .v2
- case "parakeet-v3": version = .v3
- default: throw PronunciationDictionaryStoreError.inconsistentEnrollment
+ guard let descriptor = ParakeetSpeechModelCatalog.descriptor(forInstalledPronunciationModelKey: evidence.modelKey) else {
+ if ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey(evidence.modelKey) {
+ throw PronunciationDictionaryStoreError.outdatedModelRevision
+ }
+ throw PronunciationDictionaryStoreError.inconsistentEnrollment
+ }
+ let version = descriptor.asrModelVersion
+ let directory = AsrModels.defaultCacheDirectory(for: version)
+ guard descriptor.installationRevisionMatches(at: directory),
+ descriptor.variant == .v2 || descriptor.variant == .v3 || descriptor.installedArchiveSHA256(at: directory) == descriptor.archiveSHA256
+ else {
+ throw PronunciationDictionaryStoreError.outdatedModelRevision
}
let models = try await AsrModels.loadLocalOnly(
- from: AsrModels.defaultCacheDirectory(for: version),
+ from: directory,
version: version
)
try Task.checkCancellation()
+ guard descriptor.installationRevisionMatches(at: directory) else {
+ throw PronunciationDictionaryStoreError.outdatedModelRevision
+ }
+ try Task.checkCancellation()
let manager = AsrManager(config: ASRConfig(
tdtConfig: TdtConfig(blankId: version.blankId),
- encoderHiddenSize: 1024
+ encoderHiddenSize: version.encoderHiddenSize
))
do {
try await manager.initialize(models: models)
diff --git a/Sources/Fluid/Services/DictionaryMatchPlayground.swift b/Sources/Fluid/Services/DictionaryMatchPlayground.swift
index 7c92e410..ceb7cdca 100644
--- a/Sources/Fluid/Services/DictionaryMatchPlayground.swift
+++ b/Sources/Fluid/Services/DictionaryMatchPlayground.swift
@@ -70,6 +70,26 @@ actor DictionaryMatchPlayground {
static let shared = DictionaryMatchPlayground()
private var running = false
+ /// Resolve before loading a model: an older checkpoint's vectors remain saved
+ /// but cannot be replayed through a different encoder with the same dimensions.
+ nonisolated static func targetProfile(
+ from profiles: [PronunciationDictionaryProfile],
+ target: String,
+ compatibleModelKeys: Set<String> = Set(ParakeetSpeechModelCatalog.descriptors.map(\.pronunciationModelKey))
+ ) throws -> PronunciationDictionaryProfile {
+ let matching = profiles.filter { $0.label.caseInsensitiveCompare(target) == .orderedSame }
+ if let current = matching.first(where: {
+ compatibleModelKeys.contains($0.modelKey)
+ && ParakeetSpeechModelCatalog.descriptor(forInstalledPronunciationModelKey: $0.modelKey) != nil
+ }) {
+ return current
+ }
+ if matching.contains(where: { ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey($0.modelKey) }) {
+ throw PronunciationDictionaryStoreError.outdatedModelRevision
+ }
+ throw DictionaryMatchPlaygroundError.unavailable("No saved Parakeet pronunciation recordings for “\(target)”. Train this word by voice first.")
+ }
+
func analyze(recordingID: UUID, audioURL: URL, savedTranscript: String, target: String) async throws -> DictionaryMatchReport {
let file = try AVAudioFile(forReading: audioURL)
let duration = Double(file.length) / file.processingFormat.sampleRate
@@ -99,11 +119,14 @@ actor DictionaryMatchPlayground {
let duration = Double(samples.count) / 16_000
#if arch(arm64)
let allProfiles = await PronunciationDictionaryStore.shared.allProfiles()
- guard let targetProfile = allProfiles.first(where: {
- $0.label.caseInsensitiveCompare(target) == .orderedSame && ["parakeet-v2", "parakeet-v3"].contains($0.modelKey)
- }) else {
- throw DictionaryMatchPlaygroundError.unavailable("No saved Parakeet pronunciation recordings for “\(target)”. Train this word by voice first.")
+ var compatibleModelKeys: Set<String> = ["parakeet-v2", "parakeet-v3"]
+ for descriptor in [ParakeetSpeechModelCatalog.mini, ParakeetSpeechModelCatalog.pico] {
+ let directory = AsrModels.defaultCacheDirectory(for: descriptor.asrModelVersion)
+ if let hash = descriptor.installedArchiveSHA256(at: directory) {
+ compatibleModelKeys.insert(descriptor.modelID + ":sha256:" + hash)
+ }
}
+ let targetProfile = try Self.targetProfile(from: allProfiles, target: target, compatibleModelKeys: compatibleModelKeys)
let matching = allProfiles.filter { $0.modelKey == targetProfile.modelKey }.sorted {
let lhsTarget = $0.dictionaryEntryID == targetProfile.dictionaryEntryID
let rhsTarget = $1.dictionaryEntryID == targetProfile.dictionaryEntryID
@@ -112,8 +135,21 @@ actor DictionaryMatchPlayground {
}
let profiles = Array(matching.prefix(64))
try Task.checkCancellation()
- let version: AsrModelVersion = targetProfile.modelKey == "parakeet-v2" ? .v2 : .v3
- let models = try await AsrModels.loadLocalOnly(from: AsrModels.defaultCacheDirectory(for: version), version: version)
+ guard let descriptor = ParakeetSpeechModelCatalog.descriptor(forInstalledPronunciationModelKey: targetProfile.modelKey) else {
+ throw DictionaryMatchPlaygroundError.unavailable("This pronunciation model is unavailable.")
+ }
+ let version = descriptor.asrModelVersion
+ let directory = AsrModels.defaultCacheDirectory(for: version)
+ guard descriptor.installationRevisionMatches(at: directory),
+ descriptor.variant == .v2 || descriptor.variant == .v3 || descriptor.installedArchiveSHA256(at: directory) == descriptor.archiveSHA256
+ else {
+ throw PronunciationDictionaryStoreError.outdatedModelRevision
+ }
+ let models = try await AsrModels.loadLocalOnly(from: directory, version: version)
+ try Task.checkCancellation()
+ guard descriptor.installationRevisionMatches(at: directory) else {
+ throw PronunciationDictionaryStoreError.outdatedModelRevision
+ }
let manager = AsrManager(config: ASRConfig(tdtConfig: TdtConfig(blankId: version.blankId), encoderHiddenSize: version.encoderHiddenSize))
do {
try await manager.initialize(models: models)
@@ -148,7 +184,7 @@ actor DictionaryMatchPlayground {
samples: [Float], manager: AsrManager, profiles: [PronunciationDictionaryProfile],
targetProfile: PronunciationDictionaryProfile, context: ReplayContext
) async throws -> DictionaryMatchReport {
- let references = DictionaryPronunciationReferences.make(profiles: profiles)
+ let references = DictionaryPronunciationReferences.make(profiles: profiles, compatibleModelKey: targetProfile.modelKey)
let vectors = references.map(\.embedding)
var rows = references.map { reference in
DictionaryMatchReport.Candidate(
diff --git a/Sources/Fluid/Services/DictionaryNegativeExamples.swift b/Sources/Fluid/Services/DictionaryNegativeExamples.swift
index a254c59e..6f84b335 100644
--- a/Sources/Fluid/Services/DictionaryNegativeExamples.swift
+++ b/Sources/Fluid/Services/DictionaryNegativeExamples.swift
@@ -94,7 +94,10 @@ actor DictionaryNegativeExampleStore {
}
func frames(entryID: UUID, profileKey: String, modelKey: String) -> [DictionaryMatchFrames] {
- ((try? self.read()) ?? []).filter { $0.entryID == entryID && $0.profileKey == profileKey && $0.modelKey == modelKey }.map(\.frames)
+ guard ParakeetSpeechModelCatalog.descriptor(forInstalledPronunciationModelKey: modelKey) != nil
+ || !ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey(modelKey)
+ else { return [] }
+ return ((try? self.read()) ?? []).filter { $0.entryID == entryID && $0.profileKey == profileKey && $0.modelKey == modelKey }.map(\.frames)
}
func save(_ correction: DictionaryNegativeCorrection, expectedRevision: UUID) throws {
diff --git a/Sources/Fluid/Services/DictionaryPronunciationReferences.swift b/Sources/Fluid/Services/DictionaryPronunciationReferences.swift
index 3dabeff6..c92395c9 100644
--- a/Sources/Fluid/Services/DictionaryPronunciationReferences.swift
+++ b/Sources/Fluid/Services/DictionaryPronunciationReferences.swift
@@ -9,8 +9,13 @@ enum DictionaryPronunciationReferences {
let embedding: PronunciationEmbedding
}
- static func make(profiles: [PronunciationDictionaryProfile], hiddenSize: Int? = nil) -> [Reference] {
+ static func make(profiles: [PronunciationDictionaryProfile], hiddenSize: Int? = nil, compatibleModelKey: String? = nil) -> [Reference] {
profiles.flatMap { profile -> [Reference] in
+ let compatible = compatibleModelKey.map {
+ profile.modelKey == $0 && ParakeetSpeechModelCatalog.descriptor(forInstalledPronunciationModelKey: $0) != nil
+ } ?? !ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey(profile.modelKey)
+ guard compatible, profile.enrollments.allSatisfy({ $0.modelKey == profile.modelKey })
+ else { return [] }
guard hiddenSize == nil || profile.hiddenSize == hiddenSize else { return [] }
if let calibration = profile.edgeCalibration {
let frames = profile.enrollments.compactMap(\.edgeFrameCount)
diff --git a/Sources/Fluid/Services/DictionaryTemporalEncoder.swift b/Sources/Fluid/Services/DictionaryTemporalEncoder.swift
index 71b0e341..8c4c8a5b 100644
--- a/Sources/Fluid/Services/DictionaryTemporalEncoder.swift
+++ b/Sources/Fluid/Services/DictionaryTemporalEncoder.swift
@@ -6,7 +6,7 @@ import Foundation
/// Uses the provider's already-loaded models; never downloads or starts an ASR decoder.
nonisolated enum DictionaryTemporalEncoder {
@concurrent static func encode(_ input: [Float], models: AsrModels) async throws -> DictionaryMatchFrames {
- guard !input.isEmpty, input.count <= 240_000, input.allSatisfy(\.isFinite), let encoder = models.encoder else {
+ guard !input.isEmpty, input.count <= 240_000, input.allSatisfy(\.isFinite) else {
throw PronunciationDictionaryStoreError.inconsistentEnrollment
}
try Task.checkCancellation()
@@ -25,29 +25,30 @@ nonisolated enum DictionaryTemporalEncoder {
let pre = try await models.preprocessor.prediction(from: provider, options: AsrModels.optimizedPredictionOptions())
try Task.checkCancellation()
var fields: [String: MLFeatureValue] = [:]
- for key in encoder.modelDescription.inputDescriptionsByName.keys {
+ for key in models.encoderInputFeatureNames {
fields[key] = pre.featureValue(for: key) ?? provider.featureValue(for: key)
}
- let output = try await encoder.prediction(from: MLDictionaryFeatureProvider(dictionary: fields), options: AsrModels.optimizedPredictionOptions())
+ let output = try await models.predictEncoder(from: MLDictionaryFeatureProvider(dictionary: fields), options: AsrModels.optimizedPredictionOptions())
try Task.checkCancellation()
guard let array = output.featureValue(for: "encoder")?.multiArrayValue,
let encodedLength = output.featureValue(for: "encoder_length")?.multiArrayValue,
array.dataType == .float32, array.shape.count == 3 else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
let shape = array.shape.map(\.intValue), strides = array.strides.map(\.intValue)
- let hiddenAxis = shape[1] == 1024 ? 1 : 2, timeAxis = hiddenAxis == 1 ? 2 : 1
- guard shape[hiddenAxis] == 1024 else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ let hiddenSize = models.version.encoderHiddenSize
+ let hiddenAxis = shape[1] == hiddenSize ? 1 : 2, timeAxis = hiddenAxis == 1 ? 2 : 1
+ guard shape[hiddenAxis] == hiddenSize else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
let end = min(input.count, max(1, Int((Double(input.count) / 1280).rounded()) * 1280))
let count = min(encodedLength[0].intValue, min(shape[timeAxis], (end + 1279) / 1280))
guard (1...192).contains(count) else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
let data = array.dataPointer.bindMemory(to: Float.self, capacity: array.count)
var values: [Float] = []
- values.reserveCapacity(count * 1024)
+ values.reserveCapacity(count * hiddenSize)
for frame in 0..<count {
- for d in 0..<1024 {
+ for d in 0..<hiddenSize {
values.append(data[frame * strides[timeAxis] + d * strides[hiddenAxis]])
}
}
- let frames = DictionaryMatchFrames(hiddenSize: 1024, values: values)
+ let frames = DictionaryMatchFrames(hiddenSize: hiddenSize, values: values)
guard frames.isValid else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
return frames
}
diff --git a/Sources/Fluid/Services/ExternalCoreMLModelRegistry.swift b/Sources/Fluid/Services/ExternalCoreMLModelRegistry.swift
index e2a1cbe1..38e1c8f4 100644
--- a/Sources/Fluid/Services/ExternalCoreMLModelRegistry.swift
+++ b/Sources/Fluid/Services/ExternalCoreMLModelRegistry.swift
@@ -2,11 +2,11 @@ import CoreML
import FluidAudio
import Foundation
-enum ExternalCoreMLASRBackend {
+nonisolated enum ExternalCoreMLASRBackend: Sendable {
case cohereTranscribe
}
-struct ExternalCoreMLManifestIdentity: Decodable {
+nonisolated struct ExternalCoreMLManifestIdentity: Decodable, Sendable {
let modelID: String
let sampleRate: Int
let maxAudioSamples: Int
@@ -22,7 +22,7 @@ struct ExternalCoreMLManifestIdentity: Decodable {
}
}
-enum ExternalCoreMLArtifactsValidationError: LocalizedError {
+nonisolated enum ExternalCoreMLArtifactsValidationError: LocalizedError {
case missingEntries([String])
case manifestMissing(URL)
case manifestUnreadable(URL, Error)
@@ -57,7 +57,7 @@ enum ExternalCoreMLArtifactsValidationError: LocalizedError {
}
}
-struct ExternalCoreMLASRModelSpec {
+nonisolated struct ExternalCoreMLASRModelSpec: Sendable {
private static let bundleStampFileName = ".fluid_artifact_bundle_version"
let backend: ExternalCoreMLASRBackend
@@ -244,7 +244,7 @@ extension SettingsStore.SpeechModel {
var supportsCustomVocabulary: Bool {
switch self {
- case .parakeetTDT, .parakeetTDTv2:
+ case .parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico:
return true
default:
return false
diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swift
index b3dc9be0..39eb8965 100644
--- a/Sources/Fluid/Services/FluidAudioProvider.swift
+++ b/Sources/Fluid/Services/FluidAudioProvider.swift
@@ -1,5 +1,118 @@
import Foundation
+/// A bounded recording and fixed verdict shared by the staged installer and its tests.
+/// This runs only for newly downloaded compact weights, never for a healthy installed copy.
+nonisolated enum CompactSpeechModelRuntimeCheck {
+ static let words = ["quick", "brown", "fox", "jumps", "over", "lazy", "dog", "near", "quiet"]
+ static let maximumSamples = 240_000
+
+ enum Failure: LocalizedError, Equatable {
+ case missingRecording
+ case invalidRecording
+ case incorrectTranscript
+ case timedOut
+
+ var errorDescription: String? {
+ switch self {
+ case .missingRecording, .invalidRecording:
+ "The app's voice model verification recording is unavailable. Your previous model was kept."
+ case .incorrectTranscript:
+ "The updated voice model failed its test sentence. Your previous model was kept."
+ case .timedOut:
+ "The updated voice model took too long to verify. Your previous model was kept."
+ }
+ }
+ }
+
+ static var recordingURL: URL? {
+ #if SWIFT_PACKAGE
+ Bundle.module.url(forResource: "speech-model-check", withExtension: "pcm")
+ #else
+ Bundle(for: FluidAudioProvider.self).url(forResource: "speech-model-check", withExtension: "pcm")
+ #endif
+ }
+
+ static func samples() throws -> [Float] {
+ guard let url = self.recordingURL else { throw Failure.missingRecording }
+ let file = try FileHandle(forReadingFrom: url)
+ defer { try? file.close() }
+ // A damaged resource cannot allocate an unbounded audio buffer.
+ let data = try file.read(upToCount: self.maximumSamples * 2 + 1) ?? Data()
+ return try self.decode(data)
+ }
+
+ static func decode(_ data: Data) throws -> [Float] {
+ guard data.count >= 32_000, data.count <= self.maximumSamples * 2,
+ data.count.isMultiple(of: 2)
+ else { throw Failure.invalidRecording }
+ // Byte decoding also works for unaligned Data slices; no Int16 pointer assumptions.
+ return data.withUnsafeBytes { bytes in
+ stride(from: 0, to: bytes.count, by: 2).map { offset in
+ let bits = UInt16(bytes[offset]) | (UInt16(bytes[offset + 1]) << 8)
+ return Float(Int16(bitPattern: bits)) / 32_768
+ }
+ }
+ }
+
+ static func accepts(_ text: String) -> Bool {
+ let heard = Set(text.lowercased().split(whereSeparator: { !$0.isLetter }).map(String.init))
+ return self.words.filter(heard.contains).count * 2 >= self.words.count
+ }
+
+ /// Requests cancellation at the deadline, then joins the work before returning.
+ /// Core ML's in-flight native prediction is cooperative, not forcibly preemptible.
+ static func withDeadline(
+ _ timeout: Duration = .seconds(240),
+ operation: @escaping @Sendable () async throws -> Void
+ ) async throws {
+ try Task.checkCancellation()
+ try await withThrowingTaskGroup(of: Void.self) { group in
+ group.addTask { try await operation() }
+ group.addTask {
+ try await Task.sleep(for: timeout)
+ throw Failure.timedOut
+ }
+ defer { group.cancelAll() }
+ _ = try await group.next()
+ }
+ try Task.checkCancellation()
+ }
+
+ #if arch(arm64)
+ /// Validate unpublished files. A missing app resource is not evidence that a release is bad.
+ static func validateStagedWeights(
+ at directory: URL,
+ descriptor: ParakeetSpeechModelCatalog.Descriptor
+ ) async throws {
+ let samples = try self.samples()
+ do {
+ try await self.withDeadline {
+ let stagedModels = try await AsrModels.loadLocalOnly(from: directory, version: descriptor.asrModelVersion)
+ let manager = AsrManager(config: ASRConfig.default)
+ do {
+ try await manager.initialize(models: stagedModels)
+ try Task.checkCancellation()
+ // An isolated manager never receives custom vocabulary or dictionary boosting.
+ let result = try await manager.transcribe(samples, source: .microphone)
+ try Task.checkCancellation()
+ guard self.accepts(result.text) else { throw Failure.incorrectTranscript }
+ await manager.cleanup()
+ } catch {
+ await manager.cleanup()
+ throw error
+ }
+ }
+ } catch {
+ if Task.isCancelled || error is CancellationError { throw CancellationError() }
+ if let manifestSHA256 = descriptor.manifestSHA256 {
+ await CompactSpeechModelReleaseCatalog.shared.reject(manifestSHA256: manifestSHA256)
+ }
+ throw error
+ }
+ }
+ #endif
+}
+
/// Rejection of a meeting ASR configuration outside the fixed supported policy.
nonisolated enum MeetingProviderOptionsError: Error, Equatable {
case unsupportedASRModel(String)
@@ -153,6 +266,10 @@ final class FluidAudioProvider: TranscriptionProvider {
private(set) var boostedVocabularyTermsCount: Int = 0
private var boostedTermLookup: [String] = []
private var pronunciationModelKey = ""
+ #if DEBUG
+ var modelCacheRootForTesting: URL?
+ var pronunciationModelKeyForTesting: String { self.pronunciationModelKey }
+ #endif
private var edgeReferenceCache: [UUID: PronunciationEmbedding] = [:]
private var incrementalSharedFeatures = false
private var incrementalSharedEvidence: [Int: [(Range<Int>, DictionaryAcousticEvidence)]] = [:]
@@ -166,6 +283,7 @@ final class FluidAudioProvider: TranscriptionProvider {
/// Used for downloading specific models without changing the active selection.
let modelOverride: SettingsStore.SpeechModel?
private let configureWordBoosting: Bool
+ private let updateCompactWeights: Bool
/// Opt-in pinned meeting options. When nil (legacy dictation), enhancement switches and
/// the custom dictionary are still read live from `SettingsStore` at each call site.
private let meetingOptions: MeetingProviderOptions?
@@ -177,11 +295,13 @@ final class FluidAudioProvider: TranscriptionProvider {
init(
modelOverride: SettingsStore.SpeechModel? = nil,
configureWordBoosting: Bool = true,
+ updateCompactWeights: Bool = false,
enhancementOptions: FluidAudioProviderEnhancementOptions? = nil,
pronunciationStore: PronunciationDictionaryStore = .shared
) {
self.modelOverride = modelOverride
self.configureWordBoosting = configureWordBoosting
+ self.updateCompactWeights = updateCompactWeights
self.meetingOptions = nil
self.enhancementOptions = enhancementOptions
self.pronunciationStore = pronunciationStore
@@ -195,6 +315,7 @@ final class FluidAudioProvider: TranscriptionProvider {
let options = try MeetingProviderOptions.resolve(configuration)
self.modelOverride = options.model
self.configureWordBoosting = false
+ self.updateCompactWeights = false
self.meetingOptions = options
self.enhancementOptions = nil
self.pronunciationStore = .shared
@@ -206,6 +327,12 @@ final class FluidAudioProvider: TranscriptionProvider {
?? SettingsStore.shared.experimentalParakeetUnifiedFinalEnabled
}
+ private var resolvedSpeechModel: SettingsStore.SpeechModel {
+ let selected = self.modelOverride ?? SettingsStore.shared.selectedSpeechModel
+ // Preserve the established fallback for old Qwen selections.
+ return selected == .qwen3Asr ? .parakeetTDT : selected
+ }
+
private var explicitPronunciationMatchingEnabled: Bool {
self.meetingOptions?.pronunciationMatchingEnabled
?? self.enhancementOptions?.pronunciationMatchingEnabled
@@ -295,27 +422,77 @@ final class FluidAudioProvider: TranscriptionProvider {
try Task.checkCancellation()
guard self.isReady == false else { return }
- let selectedModel = self.modelOverride ?? SettingsStore.shared.selectedSpeechModel
- let asrModelVersion: AsrModelVersion = selectedModel == .parakeetTDTv2 ? .v2 : .v3
- let modelVersion = selectedModel == .parakeetTDTv2 ? "v2" : "v3"
- self.pronunciationModelKey = "parakeet-\(modelVersion)"
+ let selectedModel = self.resolvedSpeechModel
+ if self.updateCompactWeights { await CompactSpeechModelReleaseCatalog.shared.refreshIfNeeded() }
+ try Task.checkCancellation()
+ guard var descriptor = CompactSpeechModelReleaseCatalog.shared.descriptor(for: selectedModel)
+ ?? selectedModel.parakeetDescriptor
+ else {
+ throw NSError(domain: "FluidAudioProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Choose a supported Parakeet model."])
+ }
+ let asrModelVersion = descriptor.asrModelVersion
+ let modelVersion = descriptor.variant.rawValue
+ #if DEBUG
+ let cacheDirectory = self.modelCacheRootForTesting ?? AsrModels.defaultCacheDirectory().deletingLastPathComponent()
+ #else
let cacheDirectory = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
- let modelCacheDirectory = AsrModels.defaultCacheDirectory(for: asrModelVersion)
+ #endif
+ let modelCacheDirectory = descriptor.cacheDirectory(in: cacheDirectory)
DebugLogger.shared.info(
"FluidAudioProvider: Starting model preparation for \(selectedModel.displayName) [version=\(modelVersion)]",
source: "FluidAudioProvider"
)
DebugLogger.shared.debug("FluidAudioProvider: target cache directory=\(cacheDirectory.path)", source: "FluidAudioProvider")
- try Task.checkCancellation()
- if FileManager.default.fileExists(atPath: modelCacheDirectory.path), !self.modelsExistOnDisk() {
- DebugLogger.shared.warning(
- "FluidAudioProvider: removing incomplete \(modelVersion) cache before download",
- source: "FluidAudioProvider"
- )
- try FileManager.default.removeItem(at: modelCacheDirectory)
- }
let progressRelay = ModelPreparationProgressRelay(progressHandler)
progressRelay.report(.preparingDownload)
+ if self.updateCompactWeights {
+ guard descriptor.variant == .mini || descriptor.variant == .pico else {
+ throw NSError(domain: "FluidAudioProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Only Mini and Pico support weight updates."])
+ }
+ let release = descriptor
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: descriptor,
+ in: cacheDirectory,
+ progressHandler: { progressRelay.report($0) },
+ replaceExisting: true,
+ stageValidator: { directory in
+ progressRelay.report(.loading)
+ try await CompactSpeechModelRuntimeCheck.validateStagedWeights(at: directory, descriptor: release)
+ }
+ )
+ // Publication is the commit point. A later cancellation cannot turn a
+ // completed replacement into a failure or remove its validated files.
+ return
+ }
+ let inspectionDescriptor = descriptor
+ let inspection = Task.detached(priority: .userInitiated) { () throws -> String? in
+ try Task.checkCancellation()
+ if let installedHash = inspectionDescriptor.installedArchiveSHA256(at: modelCacheDirectory) {
+ return installedHash
+ }
+ try Task.checkCancellation()
+ if FileManager.default.fileExists(atPath: modelCacheDirectory.path),
+ !inspectionDescriptor.artifactsAreComplete(at: modelCacheDirectory)
+ {
+ try FileManager.default.removeItem(at: modelCacheDirectory)
+ }
+ return nil
+ }
+ let installedHash = try await withTaskCancellationHandler {
+ try await inspection.value
+ } onCancel: {
+ inspection.cancel()
+ }
+ try Task.checkCancellation()
+ if installedHash == nil, descriptor.variant == .mini || descriptor.variant == .pico {
+ // Keep an installed checkpoint usable without a network wait. Only a
+ // first download needs the bounded signed-catalog freshness check.
+ await CompactSpeechModelReleaseCatalog.shared.refreshIfNeeded()
+ try Task.checkCancellation()
+ descriptor = CompactSpeechModelReleaseCatalog.shared.descriptor(for: selectedModel) ?? descriptor
+ }
+ self.pronunciationModelKey = installedHash.map { descriptor.modelID + ":sha256:" + $0 }
+ ?? descriptor.pronunciationModelKey
let fluidAudioProgressHandler: DownloadUtils.ProgressHandler = { progress in
switch progress.phase {
case .listing:
@@ -333,11 +510,38 @@ final class FluidAudioProvider: TranscriptionProvider {
// Download and load models
let models: AsrModels
do {
- models = try await AsrModels.downloadAndLoad(
- version: asrModelVersion,
- progressHandler: fluidAudioProgressHandler
- )
+ if descriptor.archiveURL != nil {
+ if installedHash == nil {
+ let release = descriptor
+ let validator: ParakeetArchiveDownloader.StageValidator?
+ if release.variant == .mini || release.variant == .pico {
+ validator = { directory in
+ progressRelay.report(.loading)
+ try await CompactSpeechModelRuntimeCheck.validateStagedWeights(at: directory, descriptor: release)
+ }
+ } else {
+ validator = nil
+ }
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: release,
+ in: cacheDirectory,
+ progressHandler: { progressRelay.report($0) },
+ stageValidator: validator
+ )
+ }
+ try Task.checkCancellation()
+ progressRelay.report(.loading)
+ models = try await AsrModels.loadLocalOnly(from: modelCacheDirectory, version: asrModelVersion)
+ } else {
+ models = try await AsrModels.downloadAndLoad(
+ version: asrModelVersion,
+ progressHandler: fluidAudioProgressHandler
+ )
+ }
} catch {
+ // A canceled transfer can still leave files that require user cleanup.
+ // Keep that repair path visible instead of reporting an ordinary cancel.
+ if ParakeetArchiveDownloader.isCleanupFailure(error) { throw error }
let nsError = error as NSError
if Task.isCancelled
|| error is CancellationError
@@ -369,7 +573,7 @@ final class FluidAudioProvider: TranscriptionProvider {
// Shares the same underlying MLModel objects (reference types) so memory overhead
// is only the decoder state (~100KB).
let finalManager: AsrManager
- if self.configureWordBoosting {
+ if self.configureWordBoosting, selectedModel.supportsCustomVocabulary {
do {
if let vocabBundle = try await ParakeetVocabularyStore.shared.loadTokenizedVocabularyBundle() {
DebugLogger.shared.debug(
@@ -870,7 +1074,7 @@ final class FluidAudioProvider: TranscriptionProvider {
let generation = self.recordingGeneration
let profiles = Self.preparedEdgeProfiles(await self.pronunciationProfiles(), cache: self.edgeReferenceCache)
try self.requireCurrentRecording(generation)
- let references = DictionaryPronunciationReferences.make(profiles: profiles)
+ let references = DictionaryPronunciationReferences.make(profiles: profiles, compatibleModelKey: self.pronunciationModelKey)
let useSharedFeatures = DictionaryMatcherExperiment.sharedFeaturesEnabled
let pronunciationGeneration = DictionaryMatcherExperiment.generation
let refiner: PronunciationChunkRefiner?
@@ -1005,7 +1209,7 @@ final class FluidAudioProvider: TranscriptionProvider {
textMayBeCorrected
)
}
- let references = DictionaryPronunciationReferences.make(profiles: profiles, hiddenSize: features.hiddenSize)
+ let references = DictionaryPronunciationReferences.make(profiles: profiles, hiddenSize: features.hiddenSize, compatibleModelKey: self.pronunciationModelKey)
let matches = PronunciationEmbeddingMatcher.allMatches(
prototypes: references.map(\.embedding),
in: features,
@@ -1227,6 +1431,9 @@ final class FluidAudioProvider: TranscriptionProvider {
private func temporalReferences(_ profile: PronunciationDictionaryProfile, key: String, models: AsrModels) async throws -> [DictionaryMatchFrames] {
guard DictionaryMatcherExperiment.sharedFeaturesEnabled else { return [] }
+ guard profile.modelKey == self.pronunciationModelKey,
+ profile.enrollments.allSatisfy({ $0.modelKey == profile.modelKey })
+ else { throw PronunciationDictionaryStoreError.outdatedModelRevision }
if let cached = self.temporalReferenceCache[key] { return cached }
guard profile.enrollments.count >= 3 else { return [] }
// Reserve a worst-case three-reference slot before encoding. Stable admission avoids
@@ -1463,8 +1670,10 @@ final class FluidAudioProvider: TranscriptionProvider {
}
func modelsExistOnDisk() -> Bool {
- let selectedModel = self.modelOverride ?? SettingsStore.shared.selectedSpeechModel
+ let selectedModel = self.resolvedSpeechModel
switch selectedModel {
+ case .fluidParakeetMini, .fluidParakeetPico:
+ return SpeechModelInstallationSnapshot.shared.isInstalled(modelID: selectedModel.id)
case .parakeetTDT, .parakeetTDTv2:
return selectedModel.isInstalled
default:
@@ -1472,8 +1681,32 @@ final class FluidAudioProvider: TranscriptionProvider {
}
}
+ /// Preparation uses a fresh off-main check; synchronous consumers only read
+ /// the event-refreshed installation snapshot for hosted compact models.
+ func refreshModelsExistOnDiskAsync() async throws -> Bool {
+ let model = self.resolvedSpeechModel
+ guard let descriptor = model.parakeetDescriptor, descriptor.archiveURL != nil else {
+ return self.modelsExistOnDisk()
+ }
+ let installed = try await SpeechModelInstallationSnapshot.scan([
+ .init(modelID: model.id, kind: .parakeet(descriptor)),
+ ])
+ try Task.checkCancellation()
+ return installed.contains(model.id)
+ }
+
+ var preservesInstalledCompactWeights: Bool {
+ self.resolvedSpeechModel == .fluidParakeetMini || self.resolvedSpeechModel == .fluidParakeetPico
+ }
+
+ var shouldClearCacheAfterCancellation: Bool {
+ // Hosted downloads own their unpublished temporary files. A later load
+ // cancellation must retain the verified, atomically published model.
+ self.resolvedSpeechModel.parakeetDescriptor?.archiveURL == nil
+ }
+
func clearCache() async throws {
- let selectedModel = self.modelOverride ?? SettingsStore.shared.selectedSpeechModel
+ let selectedModel = self.resolvedSpeechModel
self.automaticPronunciationProfiles = []
self.didLoadAutomaticPronunciationProfiles = false
self.recordingGeneration = UUID()
@@ -1493,8 +1726,15 @@ final class FluidAudioProvider: TranscriptionProvider {
self.boostedVocabularyTermsCount = 0
self.boostedTermLookup = []
- let version: AsrModelVersion = selectedModel == .parakeetTDTv2 ? .v2 : .v3
- let directory = AsrModels.defaultCacheDirectory(for: version)
+ guard let descriptor = selectedModel.parakeetDescriptor else {
+ throw NSError(domain: "FluidAudioProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Choose a supported Parakeet model."])
+ }
+ #if DEBUG
+ let directory = self.modelCacheRootForTesting.map { descriptor.cacheDirectory(in: $0) }
+ ?? AsrModels.defaultCacheDirectory(for: descriptor.asrModelVersion)
+ #else
+ let directory = AsrModels.defaultCacheDirectory(for: descriptor.asrModelVersion)
+ #endif
try await Task.detached(priority: .userInitiated) {
if FileManager.default.fileExists(atPath: directory.path) {
try FileManager.default.removeItem(at: directory)
@@ -1565,9 +1805,12 @@ final class FluidAudioProvider: TranscriptionProvider {
private(set) var isWordBoostingActive: Bool = false
private(set) var boostedVocabularyTermsCount: Int = 0
+ var preservesInstalledCompactWeights: Bool { false }
+
init(
modelOverride: SettingsStore.SpeechModel? = nil,
configureWordBoosting: Bool = true,
+ updateCompactWeights: Bool = false,
enhancementOptions: FluidAudioProviderEnhancementOptions? = nil
) {
// Intel stub - parameters ignored
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index 5cece606..7a1a7965 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -306,6 +306,7 @@ final class GlobalHotkeyManager: NSObject {
private var isRewriteRecordingProvider: (() -> Bool)?
private var isShortcutCaptureActiveProvider: (() -> Bool)?
private var shortcutCaptureHandler: ((NSEvent) -> NSEvent?)?
+ private let isSessionLockedProvider: () -> Bool
private var cancelCallback: (() -> CancelHandlingResult)?
private var pasteLastTranscriptionCallback: (() -> Void)?
private var hotkeyMode: HotkeyActivationMode = SettingsStore.shared.hotkeyMode
@@ -540,7 +541,8 @@ final class GlobalHotkeyManager: NSObject {
isCommandRecordingProvider: (() -> Bool)? = nil,
isRewriteRecordingProvider: (() -> Bool)? = nil,
isShortcutCaptureActiveProvider: (() -> Bool)? = nil,
- shortcutCaptureHandler: ((NSEvent) -> NSEvent?)? = nil
+ shortcutCaptureHandler: ((NSEvent) -> NSEvent?)? = nil,
+ isSessionLockedProvider: @escaping () -> Bool = { GlobalHotkeyManager.currentSessionIsLocked() }
) {
self.asrService = asrService
self.primaryShortcuts = primaryShortcuts
@@ -564,6 +566,7 @@ final class GlobalHotkeyManager: NSObject {
self.isRewriteRecordingProvider = isRewriteRecordingProvider
self.isShortcutCaptureActiveProvider = isShortcutCaptureActiveProvider
self.shortcutCaptureHandler = shortcutCaptureHandler
+ self.isSessionLockedProvider = isSessionLockedProvider
super.init()
self.initializeWithDelay()
@@ -2352,7 +2355,7 @@ final class GlobalHotkeyManager: NSObject {
}
private func canTriggerRecordingAction(_ label: String) -> Bool {
- guard !Self.currentSessionIsLocked() else {
+ guard !self.isSessionLockedProvider() else {
DebugLogger.shared.info("Ignoring \(label) - screen is locked", source: "GlobalHotkeyManager")
return false
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift b/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift
index d3400371..b76cb091 100644
--- a/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift
@@ -108,6 +108,8 @@ final class MeetingAutoDetector {
private let clock: any MeetingClockProviding
private let isNativeDetectionEnabled: () -> Bool
private let isBrowserDetectionEnabled: () -> Bool
+ private let rejectionLogger: (String) -> Void
+ private var lastLoggedRejectionByPID: [Int32: String] = [:]
private var records: [Int32: CandidateRecord] = [:] {
didSet { self.publishAutomaticTarget() }
@@ -139,7 +141,8 @@ final class MeetingAutoDetector {
activityGate: any DetectionActivityGate,
clock: any MeetingClockProviding,
isNativeDetectionEnabled: @escaping () -> Bool,
- isBrowserDetectionEnabled: @escaping () -> Bool
+ isBrowserDetectionEnabled: @escaping () -> Bool,
+ rejectionLogger: @escaping (String) -> Void = { DebugLogger.shared.log($0, source: "MeetingAutoDetector") }
) {
self.workspaceEvents = workspaceEvents
self.micActivity = micActivity
@@ -150,6 +153,7 @@ final class MeetingAutoDetector {
self.clock = clock
self.isNativeDetectionEnabled = isNativeDetectionEnabled
self.isBrowserDetectionEnabled = isBrowserDetectionEnabled
+ self.rejectionLogger = rejectionLogger
}
// MARK: - Lifecycle
@@ -186,6 +190,7 @@ final class MeetingAutoDetector {
self.titleEnrichmentInFlight.removeAll()
self.titleEnrichmentGeneration.removeAll()
self.removeTransientDisarmObservers()
+ self.lastLoggedRejectionByPID.removeAll()
}
private func pollTick(runGeneration: UInt64) async {
@@ -252,6 +257,7 @@ final class MeetingAutoDetector {
DebugLogger.shared.log("app-activated bundle=\(event.bundleIdentifier)", source: "MeetingAutoDetector")
case .terminated:
self.records[event.processID] = nil
+ self.lastLoggedRejectionByPID[event.processID] = nil
self.lastBrowserPollAt[event.processID] = nil
self.titleEnrichmentInFlight.remove(event.processID)
self.titleEnrichmentGeneration[event.processID] = nil
@@ -526,36 +532,36 @@ final class MeetingAutoDetector {
return // a transient HAL failure is not an inactive edge, but cannot confirm anew
}
guard now.timeIntervalSince(audioEvidenceAt) <= Self.confirmDeadlineSeconds else {
- self.logConfirmRejected("deadline", bundleIdentifier: record.bundleIdentifier)
+ self.logConfirmRejected("deadline", record: record)
return
}
guard abs(windowEvidenceAt.timeIntervalSince(audioEvidenceAt)) <= Self.coincidenceWindowSeconds else {
- self.logConfirmRejected("coincidence", bundleIdentifier: record.bundleIdentifier)
+ self.logConfirmRejected("coincidence", record: record)
return
}
let frontmostPasses = audioEvidenceSource == .process ? record.lastFrontmostAt != nil : self.isFrontmostNearEdge(record, edge: audioEvidenceAt)
guard frontmostPasses else {
- self.logConfirmRejected("frontmost", bundleIdentifier: record.bundleIdentifier)
+ self.logConfirmRejected("frontmost", record: record)
return
}
let readiness = self.activityGate.preflightState()
guard readiness != .busy else {
- self.logConfirmRejected("busy", bundleIdentifier: record.bundleIdentifier)
+ self.logConfirmRejected("busy", record: record)
return
}
let episodeKey = "pid:\(pid)|\(evidenceKey)"
if var existingEpisode = self.episodesByKey[episodeKey] {
if !existingEpisode.duplicateEpisodeRejectionLogged {
- self.logConfirmRejected("duplicate-episode", bundleIdentifier: record.bundleIdentifier)
+ self.logConfirmRejected("duplicate-episode", record: record)
existingEpisode.duplicateEpisodeRejectionLogged = true
self.episodesByKey[episodeKey] = existingEpisode
}
return
}
guard (self.dismissedBundleUntil[record.bundleIdentifier].map { $0 > now }) != true else {
- self.logConfirmRejected("bundle-suppressed", bundleIdentifier: record.bundleIdentifier)
+ self.logConfirmRejected("bundle-suppressed", record: record)
return
}
@@ -569,6 +575,7 @@ final class MeetingAutoDetector {
confirmedAt: now
)
self.episodesByKey[episodeKey] = episode
+ self.lastLoggedRejectionByPID[pid] = nil
DebugLogger.shared.log("preflight-state=\(Self.readinessToken(readiness)) bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
guard readiness != .busy else {
@@ -587,8 +594,12 @@ final class MeetingAutoDetector {
))
}
- private func logConfirmRejected(_ reason: String, bundleIdentifier: String) {
- DebugLogger.shared.log("confirm-rejected reason=\(reason) bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
+ private func logConfirmRejected(_ reason: String, record: CandidateRecord) {
+ // Diagnostics follow reason changes; prompt admission still runs on every event.
+ // These slots share the candidate lifetime and never mutate source-selection state.
+ guard self.lastLoggedRejectionByPID[record.pid] != reason else { return }
+ self.lastLoggedRejectionByPID[record.pid] = reason
+ self.rejectionLogger("confirm-rejected reason=\(reason) bundle=\(record.bundleIdentifier)")
}
private static func readinessToken(_ state: DetectionPreflightState) -> String {
@@ -760,6 +771,7 @@ final class MeetingAutoDetector {
episode.consumed ? nil : episode.id
}
self.records = [:]
+ self.lastLoggedRejectionByPID.removeAll()
self.titleEnrichmentInFlight.removeAll()
self.titleEnrichmentGeneration.removeAll()
self.lastMicReleaseAt = nil
diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
index e81cb98b..95c7243f 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
@@ -144,7 +144,10 @@ final class MeetingSessionCoordinator: ObservableObject {
willSet { if (newValue == nil) != (self.stopTask == nil) { self.objectWillChange.send() } }
}
- private var interruptionTask: Task<Void, Never>?
+ private var interruptionTask: Task<Void, Never>? {
+ willSet { if (newValue == nil) != (self.interruptionTask == nil) { self.objectWillChange.send() } }
+ }
+
private var terminationTask: Task<Void, Never>?
private var retryTask: Task<MeetingSession, Error>? {
willSet { if (newValue == nil) != (self.retryTask == nil) { self.objectWillChange.send() } }
@@ -190,6 +193,7 @@ final class MeetingSessionCoordinator: ObservableObject {
private var correctionUndoStacks: [MeetingSessionID: [TranscriptCorrection]] = [:]
private let validateRecordingModels: @MainActor () async throws -> Void
+ private let processingLogger: @MainActor (String) -> Void
private static let correctionUndoStackCap = 50
init(
@@ -198,7 +202,8 @@ final class MeetingSessionCoordinator: ObservableObject {
processing: any MeetingProcessingControlling,
audioArbiter: any MeetingAudioActivityArbitrating,
preferredMicrophoneUID: @escaping @MainActor () -> String? = { nil },
- validateRecordingModels: @escaping @MainActor () async throws -> Void = {}
+ validateRecordingModels: @escaping @MainActor () async throws -> Void = {},
+ processingLogger: @escaping @MainActor (String) -> Void = { DebugLogger.shared.info($0, source: "MeetingSessionCoordinator") }
) {
self.store = store
self.persistence = MeetingSessionPersistenceQueue(store: store)
@@ -207,6 +212,7 @@ final class MeetingSessionCoordinator: ObservableObject {
self.audioArbiter = audioArbiter
self.preferredMicrophoneUID = preferredMicrophoneUID
self.validateRecordingModels = validateRecordingModels
+ self.processingLogger = processingLogger
}
var currentSession: MeetingSession? {
@@ -1548,6 +1554,22 @@ final class MeetingSessionCoordinator: ObservableObject {
}
private func process(_ inputSession: MeetingSession, generation: UUID) async throws -> MeetingSession {
+ let diagnosticStarted = ContinuousClock.now
+ var diagnosticStage = MeetingProcessingStage.pending
+ var diagnosticOutcome = "failed"
+ var diagnosticFailure: MeetingSessionFailure?
+ defer {
+ let elapsed = diagnosticStarted.duration(to: .now).components
+ let elapsedMs = elapsed.seconds * 1000 + elapsed.attoseconds / 1_000_000_000_000_000
+ var line = "Meeting processing outcome=\(diagnosticOutcome) session=\(inputSession.id) stage=\(diagnosticStage.rawValue) elapsedMs=\(elapsedMs)"
+ if let failure = diagnosticFailure {
+ // One bounded line; never add meeting titles, transcripts or audio contents.
+ let detail = String(failure.message.prefix(512)).replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: "\r", with: " ")
+ let code = String(failure.code.prefix(128)).replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: "\r", with: " ")
+ line += " errorCode=\(code) detail=\(detail)"
+ }
+ self.processingLogger(line)
+ }
#if DEBUG
AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingCoordinator, queueRole: .mainControl, phase: .processing)
var diagnosticsProcessingSucceeded = false
@@ -1568,6 +1590,8 @@ final class MeetingSessionCoordinator: ObservableObject {
session: session,
sessionDirectory: sessionDirectory
) { [weak self] stage in
+ guard self?.operationGeneration == generation else { return }
+ diagnosticStage = stage
self?.updateProcessingStage(stage, generation: generation)
}
guard self.operationGeneration == generation,
@@ -1664,6 +1688,8 @@ final class MeetingSessionCoordinator: ObservableObject {
self.state = .completed(session.id)
self.operationGeneration = nil
await self.releaseActivityLease()
+ diagnosticOutcome = "completed"
+ diagnosticStage = .completed
// afterTranscription policy deletes here; sweep failures are logged, never affect this result.
Task { @MainActor [weak self] in await self?.sweepExpiredAudio() }
#if DEBUG
@@ -1671,7 +1697,9 @@ final class MeetingSessionCoordinator: ObservableObject {
#endif
return session
} catch {
+ if error is CancellationError { diagnosticOutcome = "cancelled" }
guard self.operationGeneration == generation else {
+ diagnosticOutcome = "superseded"
throw error
}
if error is CancellationError {
@@ -1693,6 +1721,7 @@ final class MeetingSessionCoordinator: ObservableObject {
throw error
}
let failure = Self.failure(from: error, domain: .processing, recoverable: true)
+ diagnosticFailure = failure
// A failed completed-session save must not durably publish a sidecar or overwrite the
// last saved transcript under `.failed`. The verified new sidecar remains unreferenced
// for retry/journal reconciliation.
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index ce3b4a12..edf18ed3 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -1544,9 +1544,10 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
}
private func ensureUsableMainWindow(_ window: NSWindow) {
+ guard !window.styleMask.contains(.fullScreen) else { return }
// If the window is too small (e.g., height collapsed), reset to the default frame.
let minSize = self.mainWindowMinimumSize
- window.minSize = minSize
+ if window.minSize != minSize { window.minSize = minSize }
let frame = window.frame
if frame.height < minSize.height || frame.width < minSize.width {
diff --git a/Sources/Fluid/Services/NemotronProvider.swift b/Sources/Fluid/Services/NemotronProvider.swift
index 86f6f09b..7c7ab75e 100644
--- a/Sources/Fluid/Services/NemotronProvider.swift
+++ b/Sources/Fluid/Services/NemotronProvider.swift
@@ -38,7 +38,7 @@ final class NemotronProvider: TranscriptionProvider {
private let repositoryOwner = "BarathwajAnandan"
private let repositoryRevision = "main"
- static let requiredFiles = [
+ nonisolated static let requiredFiles = [
"metadata.json",
"preprocessor.mlpackage",
"encoder.mlpackage",
@@ -79,7 +79,7 @@ final class NemotronProvider: TranscriptionProvider {
return Self.artifactsAreComplete(at: dir)
}
- static func artifactsAreComplete(at directory: URL) -> Bool {
+ nonisolated static func artifactsAreComplete(at directory: URL) -> Bool {
guard HuggingFaceModelDownloader.artifactsAreComplete(
root: directory,
items: self.requiredFiles.map {
diff --git a/Sources/Fluid/Services/ParakeetSpeechModelBackend.swift b/Sources/Fluid/Services/ParakeetSpeechModelBackend.swift
new file mode 100644
index 00000000..8b7691b5
--- /dev/null
+++ b/Sources/Fluid/Services/ParakeetSpeechModelBackend.swift
@@ -0,0 +1,17 @@
+#if arch(arm64)
+import FluidAudio
+import Foundation
+
+/// Converts immutable app metadata to the library contract without consulting settings.
+nonisolated extension ParakeetSpeechModelCatalog.Descriptor {
+ var asrModelVersion: AsrModelVersion {
+ switch self.variant {
+ case .v2: .v2
+ case .v3: .v3
+ case .mini: .fluidParakeetMini
+ case .pico: .fluidParakeetPico
+ }
+ }
+}
+
+#endif
diff --git a/Sources/Fluid/Services/ParakeetSpeechModelCatalog.swift b/Sources/Fluid/Services/ParakeetSpeechModelCatalog.swift
new file mode 100644
index 00000000..52a4ae90
--- /dev/null
+++ b/Sources/Fluid/Services/ParakeetSpeechModelCatalog.swift
@@ -0,0 +1,312 @@
+import CryptoKit
+import Foundation
+
+/// Immutable metadata shared by model selection, cache ownership and ASR routing.
+/// Resolving a descriptor performs no hardware, network or filesystem queries.
+nonisolated enum ParakeetSpeechModelCatalog {
+ enum Variant: String, CaseIterable, Sendable {
+ case v2, v3, mini, pico
+ }
+
+ struct PerformanceRatings: Equatable, Sendable {
+ let speedRating: Int
+ let accuracyRating: Int
+ let speedPercent: Double
+ let accuracyPercent: Double
+ }
+
+ struct Descriptor: Equatable, Sendable {
+ enum InstallationRevisionError: Error { case invalidChecksum }
+ let modelID: String
+ let variant: Variant
+ let folderName: String
+ let expectedDownloadBytes: Int64
+ let archiveURL: URL?
+ let archiveSHA256: String?
+ let requiredModelNames: [String]
+ let vocabularyFile: String
+ let displayName: String
+ let humanReadableName: String
+ let languageSupport: String
+ let supportedLanguageCodes: [String]
+ let downloadSize: String
+ let cardDescription: String
+ let performanceRatings: PerformanceRatings?
+ var manifestSHA256: String? = nil
+
+ var isEnglishOnly: Bool { self.supportedLanguageCodes == ["en"] }
+
+ var attribution: String {
+ switch self.variant {
+ case .v2, .v3: "NVIDIA Parakeet"
+ case .mini, .pico: "NVIDIA Parakeet · Moondream Parakeet Ultra"
+ }
+ }
+
+ var creditLine: String {
+ switch self.variant {
+ case .v2, .v3: "Built on NVIDIA Parakeet."
+ case .mini, .pico: "Made by FluidVoice, built on NVIDIA Parakeet and Moondream’s Parakeet Ultra."
+ }
+ }
+
+ /// Encoder vectors are compatible only with the checkpoint that produced them.
+ /// Legacy v2/v3 keep their established persisted keys byte for byte.
+ var pronunciationModelKey: String {
+ switch self.variant {
+ case .v2: "parakeet-v2"
+ case .v3: "parakeet-v3"
+ case .mini, .pico: "\(self.modelID):sha256:\(self.archiveSHA256 ?? "unavailable")"
+ }
+ }
+
+ /// The caller supplies its existing cache root; appending a folder does no IO.
+ func cacheDirectory(in modelsDirectory: URL) -> URL {
+ modelsDirectory.appendingPathComponent(self.folderName, isDirectory: true)
+ }
+
+ /// Explicit filesystem validation for download/preparation work. This is
+ /// separate from descriptor lookup; callers should run it off the main actor.
+ func artifactsAreComplete(at directory: URL) -> Bool {
+ guard self.installationRevisionMatches(at: directory) else { return false }
+ guard HuggingFaceModelDownloader.artifactIsComplete(
+ at: directory.appendingPathComponent(self.vocabularyFile), isDirectory: false
+ ) else { return false }
+ return self.requiredModelNames.allSatisfy { name in
+ HuggingFaceModelDownloader.artifactIsComplete(
+ at: directory.appendingPathComponent(name, isDirectory: true), isDirectory: true
+ )
+ }
+ }
+
+ /// Compact model folders are stable across releases; their exact installed
+ /// archive revision must match before an existing cache may skip download.
+ func installationRevisionMatches(at directory: URL) -> Bool {
+ guard self.variant == .mini || self.variant == .pico else { return true }
+ guard let hash = self.archiveSHA256, hash.count == 64,
+ hash.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) })
+ else { return false }
+ let marker = directory.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName)
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: marker.path),
+ attributes[.type] as? FileAttributeType == .typeRegular,
+ (attributes[.size] as? NSNumber)?.intValue == 64,
+ let input = try? FileHandle(forReadingFrom: marker)
+ else { return false }
+ defer { try? input.close() }
+ return (try? input.read(upToCount: 65)) == Data(hash.utf8)
+ }
+
+ /// Explicit background-only disk inspection. Older compact checkpoints remain
+ /// usable, but must not be mistaken for the currently advertised download.
+ func installedArchiveSHA256(at directory: URL) -> String? {
+ guard self.variant == .mini || self.variant == .pico,
+ let rootAttributes = try? FileManager.default.attributesOfItem(atPath: directory.path),
+ rootAttributes[.type] as? FileAttributeType == .typeDirectory
+ else { return nil }
+ let marker = directory.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName)
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: marker.path),
+ attributes[.type] as? FileAttributeType == .typeRegular,
+ (attributes[.size] as? NSNumber)?.intValue == 64,
+ let input = try? FileHandle(forReadingFrom: marker)
+ else { return nil }
+ defer { try? input.close() }
+ guard let bytes = try? input.read(upToCount: 65), bytes.count == 64,
+ bytes.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }),
+ let hash = String(data: bytes, encoding: .utf8),
+ HuggingFaceModelDownloader.artifactIsComplete(at: directory.appendingPathComponent(self.vocabularyFile), isDirectory: false),
+ self.requiredModelNames.allSatisfy({ name in
+ HuggingFaceModelDownloader.artifactIsComplete(at: directory.appendingPathComponent(name, isDirectory: true), isDirectory: true)
+ })
+ else { return nil }
+ var enumerationFailed = false
+ guard let enumerator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: nil, options: [], errorHandler: { _, _ in
+ enumerationFailed = true
+ return false
+ }) else { return nil }
+ var count = 0
+ for case let item as URL in enumerator {
+ if Task.isCancelled { return nil }
+ count += 1
+ guard count <= 50_000,
+ let type = (try? FileManager.default.attributesOfItem(atPath: item.path))?[.type] as? FileAttributeType,
+ type == .typeRegular || type == .typeDirectory
+ else { return nil }
+ }
+ return enumerationFailed ? nil : hash
+ }
+
+ /// Small bounded identity read for installation snapshots, never UI rendering.
+ /// Existing archive markers remain the pronunciation identity across migration.
+ func installedManifestSHA256(at directory: URL) -> String? {
+ guard self.variant == .mini || self.variant == .pico,
+ (try? FileManager.default.attributesOfItem(atPath: directory.path))?[.type] as? FileAttributeType == .typeDirectory
+ else { return nil }
+ let file = directory.appendingPathComponent("manifest.json")
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: file.path),
+ attributes[.type] as? FileAttributeType == .typeRegular,
+ let size = (attributes[.size] as? NSNumber)?.intValue,
+ size > 0, size <= 1_048_576,
+ let input = try? FileHandle(forReadingFrom: file)
+ else { return nil }
+ defer { try? input.close() }
+ guard let data = try? input.read(upToCount: 1_048_577), data.count == size else { return nil }
+ return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+ }
+
+ /// Only the downloader calls this on its validated, unpublished stage.
+ /// Exclusive creation rejects any marker supplied by the archive itself.
+ func writeInstallationRevision(at directory: URL) throws {
+ guard self.variant == .mini || self.variant == .pico else { return }
+ guard let hash = self.archiveSHA256, hash.count == 64,
+ hash.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) })
+ else { throw InstallationRevisionError.invalidChecksum }
+ try Data(hash.utf8).write(
+ to: directory.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName),
+ options: .withoutOverwriting
+ )
+ }
+ }
+
+ static let installationRevisionFileName = ".fluidvoice-archive-sha256"
+ static let standardModelNames = ["Preprocessor.mlmodelc", "Encoder.mlmodelc", "Decoder.mlmodelc", "JointDecision.mlmodelc"]
+ static let splitModelNames = [
+ "Preprocessor.mlmodelc", "Encoder-1.mlmodelc", "Encoder-2.mlmodelc",
+ "Encoder-3.mlmodelc", "Encoder-4.mlmodelc", "Decoder.mlmodelc", "JointDecision.mlmodelc",
+ ]
+
+ static let v2 = Descriptor(
+ modelID: "parakeet-tdt-v2",
+ variant: .v2,
+ folderName: "parakeet-tdt-0.6b-v2-coreml",
+ expectedDownloadBytes: 464_421_712,
+ archiveURL: nil,
+ archiveSHA256: nil,
+ requiredModelNames: ParakeetSpeechModelCatalog.standardModelNames,
+ vocabularyFile: "parakeet_vocab.json",
+ displayName: "Parakeet TDT v2 (English Only)",
+ humanReadableName: "Blazing Fast - English",
+ languageSupport: "English Only (Higher Accuracy)",
+ supportedLanguageCodes: ["en"],
+ downloadSize: "~442.9 MiB",
+ cardDescription: "Optimized for English accuracy and fastest transcription.",
+ performanceRatings: .init(speedRating: 5, accuracyRating: 5, speedPercent: 0.99, accuracyPercent: 0.96)
+ )
+ static let v3 = Descriptor(
+ modelID: "parakeet-tdt",
+ variant: .v3,
+ folderName: "parakeet-tdt-0.6b-v3-coreml",
+ expectedDownloadBytes: 483_288_717,
+ archiveURL: nil,
+ archiveSHA256: nil,
+ requiredModelNames: ParakeetSpeechModelCatalog.standardModelNames,
+ vocabularyFile: "parakeet_vocab.json",
+ displayName: "Parakeet TDT v3 (Multilingual)",
+ humanReadableName: "Blazing Fast - Multilingual",
+ languageSupport: "25 Languages",
+ supportedLanguageCodes: [
+ "bg", "hr", "cs", "da", "nl", "en", "et", "fi", "fr", "de", "el", "hu", "it",
+ "lv", "lt", "mt", "pl", "pt", "ro", "sk", "sl", "es", "sv", "ru", "uk",
+ ],
+ downloadSize: "~460.9 MiB",
+ cardDescription: "Fast multilingual transcription. Supports Bulgarian, Croatian, Czech, Danish, " +
+ "Dutch, English, Estonian, Finnish, French, German, Greek, Hungarian, Italian, " +
+ "Latvian, Lithuanian, Maltese, Polish, Portuguese, Romanian, Russian, Slovak, " +
+ "Slovenian, Spanish, Swedish, and Ukrainian.",
+ performanceRatings: .init(speedRating: 5, accuracyRating: 5, speedPercent: 0.99, accuracyPercent: 0.92)
+ )
+ static let mini = Descriptor(
+ modelID: "fluid-parakeet-mini",
+ variant: .mini,
+ folderName: "fluid-parakeet-mini-coreml",
+ expectedDownloadBytes: 254_136_320,
+ archiveURL: URL(string: "https://models.fluidvoice.app/parakeet/fluid-mini/1.1.1/fluid-parakeet-mini-coreml.tar"),
+ archiveSHA256: "7f811554cc670ded812937502f928ae6aad946bbf6e4c2eecd6fcffbe76f4d16",
+ requiredModelNames: ParakeetSpeechModelCatalog.splitModelNames,
+ vocabularyFile: "parakeet_vocab.json",
+ displayName: "Fluid Speech Mini",
+ humanReadableName: "Fluid Speech Mini",
+ languageSupport: "English Only",
+ supportedLanguageCodes: ["en"],
+ downloadSize: "~242.4 MiB",
+ cardDescription: "Clear dictation in noisy places, at half the size of Blazing Fast. Runs on your Mac.",
+ performanceRatings: .init(speedRating: 5, accuracyRating: 5, speedPercent: 0.99, accuracyPercent: 0.95),
+ manifestSHA256: "32193c4cec7f5daf92fd617c424e7a157ea8dfcfa832a0db2cfcfa5cb9b674b8"
+ )
+ static let pico = Descriptor(
+ modelID: "fluid-parakeet-pico",
+ variant: .pico,
+ folderName: "fluid-parakeet-pico-coreml",
+ expectedDownloadBytes: 161_208_320,
+ archiveURL: URL(string: "https://models.fluidvoice.app/parakeet/fluid-pico/1.1.1/fluid-parakeet-pico-coreml.tar"),
+ archiveSHA256: "542f74f639438bf37ff134a7a75daddb50d301deb87696994e11ff272df21512",
+ requiredModelNames: ParakeetSpeechModelCatalog.splitModelNames,
+ vocabularyFile: "parakeet_vocab.json",
+ displayName: "Fluid Speech Pico",
+ humanReadableName: "Fluid Speech Pico",
+ languageSupport: "English Only",
+ supportedLanguageCodes: ["en"],
+ downloadSize: "~153.7 MiB",
+ cardDescription: "Our smallest model. Light enough for older Macs, and still clear in noisy places.",
+ performanceRatings: .init(speedRating: 5, accuracyRating: 5, speedPercent: 1.0, accuracyPercent: 0.91),
+ manifestSHA256: "a87ee649edc18aca6d30f251e75237f48c995448b865ffee35ab343ed3e66121"
+ )
+
+ static let descriptors = [ParakeetSpeechModelCatalog.v2, ParakeetSpeechModelCatalog.v3, ParakeetSpeechModelCatalog.mini, ParakeetSpeechModelCatalog.pico]
+
+ static func descriptor(forModelID modelID: String) -> Descriptor? {
+ self.descriptors.first { $0.modelID == modelID }
+ }
+
+ static func descriptor(forPronunciationModelKey modelKey: String) -> Descriptor? {
+ self.descriptors.first { $0.pronunciationModelKey == modelKey }
+ }
+
+ /// A candidate for loading an existing checkpoint, never a download instruction.
+ /// Callers must verify its hash against the installed marker before loadLocalOnly.
+ static func descriptor(forInstalledPronunciationModelKey modelKey: String) -> Descriptor? {
+ if modelKey == self.v2.pronunciationModelKey { return self.v2 }
+ if modelKey == self.v3.pronunciationModelKey { return self.v3 }
+ for source in [self.mini, self.pico] {
+ let prefix = source.modelID + ":sha256:"
+ guard modelKey.hasPrefix(prefix) else { continue }
+ let hash = String(modelKey.dropFirst(prefix.count))
+ guard hash.utf8.count == 64,
+ hash.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) })
+ else { return nil }
+ return Descriptor(
+ modelID: source.modelID,
+ variant: source.variant,
+ folderName: source.folderName,
+ expectedDownloadBytes: source.expectedDownloadBytes,
+ archiveURL: nil,
+ archiveSHA256: hash,
+ requiredModelNames: source.requiredModelNames,
+ vocabularyFile: source.vocabularyFile,
+ displayName: source.displayName,
+ humanReadableName: source.humanReadableName,
+ languageSupport: source.languageSupport,
+ supportedLanguageCodes: source.supportedLanguageCodes,
+ downloadSize: source.downloadSize,
+ cardDescription: source.cardDescription,
+ performanceRatings: source.performanceRatings
+ )
+ }
+ return nil
+ }
+
+ static func isOutdatedCompactPronunciationModelKey(_ modelKey: String) -> Bool {
+ [self.mini, self.pico].contains { descriptor in
+ (modelKey == descriptor.modelID || modelKey.hasPrefix(descriptor.modelID + ":sha256:"))
+ && modelKey != descriptor.pronunciationModelKey
+ }
+ }
+
+ static func descriptor(for variant: Variant) -> Descriptor {
+ switch variant {
+ case .v2: self.v2
+ case .v3: self.v3
+ case .mini: self.mini
+ case .pico: self.pico
+ }
+ }
+}
diff --git a/Sources/Fluid/Services/ParakeetVocabularyStore.swift b/Sources/Fluid/Services/ParakeetVocabularyStore.swift
index a45b490b..2e9082a5 100644
--- a/Sources/Fluid/Services/ParakeetVocabularyStore.swift
+++ b/Sources/Fluid/Services/ParakeetVocabularyStore.swift
@@ -8,8 +8,8 @@ import FluidAudio
final class ParakeetVocabularyStore {
static let shared = ParakeetVocabularyStore()
- struct VocabularyConfig: Codable, Sendable {
- struct Term: Codable, Hashable, Sendable {
+ nonisolated struct VocabularyConfig: Codable, Sendable {
+ nonisolated struct Term: Codable, Hashable, Sendable {
let text: String
let weight: Float?
let aliases: [String]
@@ -74,7 +74,7 @@ final class ParakeetVocabularyStore {
}
}
- private enum Defaults {
+ private nonisolated enum Defaults {
// Balanced defaults to reduce over-biasing while still improving rare terms.
static let alpha: Float = 2.8
static let minCtcScore: Float = -2.2
@@ -148,6 +148,19 @@ final class ParakeetVocabularyStore {
return Self.normalizeUserTerms(parsed.terms, maxTerms: Defaults.maxTerms)
}
+ /// Search reads a bounded snapshot without creating files or blocking the UI.
+ @concurrent nonisolated static func readSearchTerms() async throws -> [VocabularyConfig.Term] {
+ guard let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { return [] }
+ let url = base.appendingPathComponent("FluidVoice/parakeet_custom_vocabulary.json")
+ guard FileManager.default.fileExists(atPath: url.path) else { return [] }
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ let limit = 2 * 1024 * 1024
+ guard let data = try handle.read(upToCount: limit + 1), data.count <= limit else { return [] }
+ let parsed = try JSONDecoder().decode(VocabularyConfig.self, from: data)
+ return Self.normalizeUserTerms(parsed.terms, maxTerms: Defaults.maxTerms)
+ }
+
/// Saves user-managed boost terms while keeping tuning backend-controlled.
func saveUserBoostTerms(_ terms: [VocabularyConfig.Term]) throws {
let normalizedTerms = Self.normalizeUserTerms(terms, maxTerms: Defaults.maxTerms)
@@ -256,7 +269,7 @@ final class ParakeetVocabularyStore {
}
}
- private static func normalizeUserTerms(_ terms: [VocabularyConfig.Term], maxTerms: Int) -> [VocabularyConfig.Term] {
+ private nonisolated static func normalizeUserTerms(_ terms: [VocabularyConfig.Term], maxTerms: Int) -> [VocabularyConfig.Term] {
var seen: Set<String> = []
var normalized: [VocabularyConfig.Term] = []
normalized.reserveCapacity(min(terms.count, maxTerms))
diff --git a/Sources/Fluid/Services/PronunciationDictionaryStore.swift b/Sources/Fluid/Services/PronunciationDictionaryStore.swift
index f9c53845..a7e0e458 100644
--- a/Sources/Fluid/Services/PronunciationDictionaryStore.swift
+++ b/Sources/Fluid/Services/PronunciationDictionaryStore.swift
@@ -45,6 +45,7 @@ struct PronunciationDictionaryProfile: Codable, Equatable, Identifiable, Sendabl
enum PronunciationDictionaryStoreError: LocalizedError, Equatable {
case inconsistentEnrollment
case staleEvidence
+ case outdatedModelRevision
var errorDescription: String? {
switch self {
@@ -52,6 +53,8 @@ enum PronunciationDictionaryStoreError: LocalizedError, Equatable {
"The dictionary entry changed before audio learning finished."
case .inconsistentEnrollment:
"Pronunciation samples must use the same model and embedding size."
+ case .outdatedModelRevision:
+ "These pronunciation recordings use an older voice model. Retrain this word by voice. Your custom words and text corrections remain saved."
}
}
}
diff --git a/Sources/Fluid/Services/SimpleUpdater.swift b/Sources/Fluid/Services/SimpleUpdater.swift
index 89c16d2c..1a5d5e5e 100644
--- a/Sources/Fluid/Services/SimpleUpdater.swift
+++ b/Sources/Fluid/Services/SimpleUpdater.swift
@@ -15,6 +15,8 @@ enum SimpleUpdateError: Error, LocalizedError {
case unzipFailed
case notAnAppBundle
case codesignMismatch
+ case backupFailed
+ case installedAppChanged
case rollbackUnavailable
case rollbackRestoreFailed
@@ -31,6 +33,8 @@ enum SimpleUpdateError: Error, LocalizedError {
case .unzipFailed: return "Failed to extract the update archive."
case .notAnAppBundle: return "Extracted content does not contain an app bundle."
case .codesignMismatch: return "Downloaded app’s code signature does not match current app."
+ case .backupFailed: return "The current app could not be backed up. Nothing was replaced."
+ case .installedAppChanged: return "The installed app changed. Restart FluidVoice before trying the update again."
case .rollbackUnavailable: return "No rollback backup is available."
case .rollbackRestoreFailed: return "Failed to restore a previous version."
}
@@ -214,12 +218,12 @@ final class SimpleUpdater: ObservableObject {
throw SimpleUpdateError.rollbackUnavailable
}
- self.createRollbackBackup(beforeRollback: true)
-
do {
- try self.performSwapAndRelaunch(
+ try await self.performSwapAndRelaunch(
installedAppURL: Bundle.main.bundleURL,
- downloadedAppURL: rollbackBundleURL
+ downloadedAppURL: rollbackBundleURL,
+ expectedVersion: nil,
+ isRollback: true
)
DebugLogger.shared.info(
"SimpleUpdater: Rolled back to \(rollbackBundleURL.lastPathComponent)",
@@ -291,7 +295,7 @@ final class SimpleUpdater: ObservableObject {
// Allowed Apple Developer Team IDs for code-sign validation
// Restrict update transitions to FluidVoice's approved signing teams.
- private let allowedTeamIDs: Set<String> = [
+ private nonisolated static let allowedTeamIDs: Set<String> = [
"V4J43B279J",
"537RRRT57V",
]
@@ -646,6 +650,9 @@ final class SimpleUpdater: ObservableObject {
appropriateFor: Bundle.main.bundleURL,
create: true
)
+ defer {
+ Task.detached(priority: .utility) { try? FileManager.default.removeItem(at: tempDir) }
+ }
let downloadURL = tempDir.appendingPathComponent(asset.browser_download_url.lastPathComponent)
do {
@@ -667,52 +674,12 @@ final class SimpleUpdater: ObservableObject {
throw SimpleUpdateError.notAnAppBundle
}
- // Validate code signing identity matches (skip in DEBUG for easier local testing)
- #if DEBUG
- // In Debug builds the local app is typically signed with a development cert, while
- // releases are signed with Developer ID. Skip strict check to enable testing.
- _ = currentBundle // keep reference used in Release path
- #else
- let curID = try await codeSigningIdentity(for: currentBundle.bundleURL)
- let newID = try await codeSigningIdentity(for: extractedBundleURL)
-
- func teamID(from identity: String) -> String? {
- // Handle TeamIdentifier= format first
- if identity.hasPrefix("TeamIdentifier=") {
- return String(identity.dropFirst("TeamIdentifier=".count))
- }
-
- // Handle Authority= format (extract team ID from parentheses)
- guard let l = identity.lastIndex(of: "("), let r = identity.lastIndex(of: ")"), l < r else { return nil }
- let inside = identity[identity.index(after: l)..<r]
- return String(inside)
- }
-
- // Allow update if:
- // - full identity matches OR
- // - Team IDs match OR
- // - both current and new Team IDs are in the allowedTeamIDs set
- // This enables dev→prod updates across your two known Team IDs.
- let sameIdentity = curID == newID
- let curTeam = teamID(from: curID)
- let newTeam = teamID(from: newID)
- let sameTeam = (curTeam != nil && curTeam == newTeam)
- let bothAllowed: Bool = {
- guard let ct = curTeam, let nt = newTeam else { return false }
- return self.allowedTeamIDs.contains(ct) && self.allowedTeamIDs.contains(nt)
- }()
-
- guard sameIdentity || sameTeam || bothAllowed else {
- DebugLogger.shared.error("SimpleUpdater: Code-sign mismatch. Current=\(curID) New=\(newID)", source: "SimpleUpdater")
- DebugLogger.shared.error("SimpleUpdater: Current Team=\(curTeam ?? "none") New Team=\(newTeam ?? "none")", source: "SimpleUpdater")
- throw SimpleUpdateError.codesignMismatch
- }
- #endif
-
- self.createRollbackBackup(beforeRollback: false)
-
- // Replace and relaunch
- try self.performSwapAndRelaunch(installedAppURL: currentBundle.bundleURL, downloadedAppURL: extractedBundleURL)
+ try await self.performSwapAndRelaunch(
+ installedAppURL: currentBundle.bundleURL,
+ downloadedAppURL: extractedBundleURL,
+ expectedVersion: rawVersion,
+ isRollback: false
+ )
shouldKeepOperationActive = true
}
@@ -913,64 +880,39 @@ final class SimpleUpdater: ObservableObject {
.replacingOccurrences(of: " ", with: "_")
}
- private func createRollbackBackup(beforeRollback: Bool) {
- let currentAppVersion = self.currentAppVersion
- let appURL = Bundle.main.bundleURL
- let backupRoot = self.rollbackRootDirectory()
-
- do {
- try self.fileManager.createDirectory(
- at: backupRoot,
- withIntermediateDirectories: true
- )
- } catch {
- DebugLogger.shared.warning("SimpleUpdater: Failed to create rollback backup folder: \(error.localizedDescription)", source: "SimpleUpdater")
- return
- }
-
- let timestamp = Int(Date().timeIntervalSince1970)
- let safeVersion = self.sanitizeVersion(currentAppVersion)
- let backupName = beforeRollback
- ? "\(self.installedAppName)-\(safeVersion)-rollback-\(timestamp).app"
- : "\(self.installedAppName)-\(safeVersion)-\(timestamp).app"
- let backupURL = backupRoot.appendingPathComponent(backupName)
-
- do {
- try self.fileManager.copyItem(at: appURL, to: backupURL)
- try? self.fileManager.setAttributes(
- [.modificationDate: Date()],
- ofItemAtPath: backupURL.path
- )
- self.pruneRollbackBackups()
- DebugLogger.shared.info(
- "SimpleUpdater: Created rollback backup at \(backupURL.path)",
- source: "SimpleUpdater"
- )
- } catch {
- DebugLogger.shared.warning(
- "SimpleUpdater: Failed to create rollback backup: \(error.localizedDescription)",
- source: "SimpleUpdater"
- )
- }
- }
-
- private func pruneRollbackBackups() {
- let backups = self.availableRollbackBackups()
- guard backups.count > self.maxRollbackBackups else { return }
-
- for oldBackup in backups.dropFirst(self.maxRollbackBackups) {
- do {
- try self.fileManager.removeItem(at: oldBackup)
- } catch {
- DebugLogger.shared.warning(
- "SimpleUpdater: Failed to remove old rollback backup \(oldBackup.lastPathComponent): \(error.localizedDescription)",
- source: "SimpleUpdater"
- )
+ private func pruneRollbackBackups(preserving protectedURLs: Set<URL>) async {
+ let root = self.rollbackRootDirectory()
+ let limit = self.maxRollbackBackups
+ let warnings = await Task.detached(priority: .utility) {
+ let manager = FileManager.default
+ guard let urls = try? manager.contentsOfDirectory(
+ at: root,
+ includingPropertiesForKeys: [.contentModificationDateKey],
+ options: [.skipsHiddenFiles]
+ ) else { return [String]() }
+ let backups = Self.sortedRollbackBackups(urls.filter { $0.pathExtension == "app" }) {
+ (try? $0.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
+ }
+ var retained = Set(backups.filter { protectedURLs.contains($0) })
+ for backup in backups where retained.count < limit {
+ retained.insert(backup)
+ }
+ var failures = [String]()
+ for backup in backups where !retained.contains(backup) {
+ do {
+ try manager.removeItem(at: backup)
+ } catch {
+ failures.append(error.localizedDescription)
+ }
}
+ return failures
+ }.value
+ for warning in warnings {
+ DebugLogger.shared.warning("SimpleUpdater: Rollback cleanup failed: \(warning)", source: "SimpleUpdater")
}
}
- static func sortedRollbackBackups(
+ nonisolated static func sortedRollbackBackups(
_ urls: [URL],
modificationDate: (URL) -> Date?
) -> [URL] {
@@ -993,7 +935,7 @@ final class SimpleUpdater: ObservableObject {
return version != currentVersion
}
- private static func rollbackBackupCreationDate(
+ private nonisolated static func rollbackBackupCreationDate(
from url: URL,
fallbackModificationDate: Date?
) -> Date? {
@@ -1004,7 +946,7 @@ final class SimpleUpdater: ObservableObject {
return fallbackModificationDate
}
- private static func rollbackBackupTimestamp(from url: URL) -> TimeInterval? {
+ private nonisolated static func rollbackBackupTimestamp(from url: URL) -> TimeInterval? {
let name = url.deletingPathExtension().lastPathComponent
guard let suffix = name.split(separator: "-").last,
let timestamp = TimeInterval(suffix)
@@ -1090,110 +1032,184 @@ final class SimpleUpdater: ObservableObject {
}
}
- private func codeSigningIdentity(for bundleURL: URL) async throws -> String {
- let proc = Process()
- proc.launchPath = "/usr/bin/codesign"
- proc.arguments = ["-dvvv", bundleURL.path]
- let pipe = Pipe()
- proc.standardError = pipe
-
- return try await withCheckedThrowingContinuation { cont in
- proc.terminationHandler = { _ in
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- let s = String(data: data, encoding: .utf8) ?? ""
+ nonisolated struct PreparedInstallation: Sendable {
+ let replacement: UpdateAppReplacement
+ let backupURL: URL
+ }
- // First try to get TeamIdentifier (most reliable)
- if let teamLine = s.split(separator: "\n").first(where: { $0.hasPrefix("TeamIdentifier=") }) {
- cont.resume(returning: String(teamLine))
- } else {
- // Fallback to Authority line
- let line = s.split(separator: "\n").first(where: { $0.hasPrefix("Authority=") })
- cont.resume(returning: line.map(String.init) ?? "")
+ /// Runs under the replacement's process-shared lock on a background task.
+ nonisolated static func prepareValidatedInstallation(
+ installedAppURL: URL,
+ downloadedAppURL: URL,
+ installedExpectation: UpdateBundleValidator.Expectation,
+ expectedVersion: String?,
+ backupURL: URL,
+ isRollback: Bool
+ ) throws -> PreparedInstallation {
+ let teams = Self.allowedTeamIDs
+ guard isRollback || expectedVersion != nil, installedExpectation.version != nil, installedExpectation.build != nil
+ else { throw UpdateBundleValidator.ValidationError.invalidExpectation }
+ try Task.checkCancellation()
+ let replacement = try UpdateAppReplacement.prepare(
+ installedAppURL: installedAppURL,
+ replacementAppURL: downloadedAppURL,
+ validateInstalledApp: { url in
+ do {
+ _ = try UpdateBundleValidator.validate(
+ at: url,
+ expectation: installedExpectation,
+ policy: .installedApp(allowedTeamIDs: teams)
+ )
+ } catch UpdateBundleValidator.ValidationError.versionMismatch {
+ throw SimpleUpdateError.installedAppChanged
+ } catch UpdateBundleValidator.ValidationError.buildMismatch {
+ throw SimpleUpdateError.installedAppChanged
}
}
- do { try proc.run() } catch { cont.resume(throwing: error) }
- }
- }
-
- private func performSwapAndRelaunch(installedAppURL: URL, downloadedAppURL: URL) throws {
- // Handle app name changes: if the downloaded app has a different name,
- // we need to replace the old app and use the new name
- let installedAppName = installedAppURL.lastPathComponent
- let downloadedAppName = downloadedAppURL.lastPathComponent
-
- DebugLogger.shared.info("SimpleUpdater: Installing app - Current: \(installedAppName), New: \(downloadedAppName)", source: "SimpleUpdater")
-
- let finalAppURL: URL
- if installedAppName != downloadedAppName {
- // App name changed - use the new name
- finalAppURL = installedAppURL.deletingLastPathComponent().appendingPathComponent(downloadedAppName)
- DebugLogger.shared.info("SimpleUpdater: App name changed, installing to: \(finalAppURL.path)", source: "SimpleUpdater")
-
- // Safety check: ensure we don't overwrite an existing app with the new name
- if FileManager.default.fileExists(atPath: finalAppURL.path) {
- DebugLogger.shared.info("SimpleUpdater: Removing existing app at new location: \(finalAppURL.path)", source: "SimpleUpdater")
- try FileManager.default.removeItem(at: finalAppURL)
+ )
+ var backupCreated = false
+ do {
+ try Task.checkCancellation()
+ _ = try UpdateBundleValidator.validate(
+ at: replacement.stagedAppURL,
+ expectation: .init(bundleIdentifier: installedExpectation.bundleIdentifier, version: expectedVersion),
+ policy: isRollback ? .installedApp(allowedTeamIDs: teams) : .developerID(allowedTeamIDs: teams)
+ )
+ do {
+ try UpdateRollbackBackup.create(installedAppURL: installedAppURL, backupURL: backupURL) { url in
+ _ = try UpdateBundleValidator.validate(
+ at: url,
+ expectation: installedExpectation,
+ policy: .installedApp(allowedTeamIDs: teams)
+ )
+ }
+ backupCreated = true
+ } catch let failure as UpdateRollbackBackup.Failure where failure.retainedDirectoryURL != nil {
+ throw failure
+ } catch {
+ throw SimpleUpdateError.backupFailed
}
-
- // Remove old app if it exists
- if FileManager.default.fileExists(atPath: installedAppURL.path) {
- DebugLogger.shared.info("SimpleUpdater: Removing old app: \(installedAppURL.path)", source: "SimpleUpdater")
- try FileManager.default.removeItem(at: installedAppURL)
+ try Task.checkCancellation()
+ try replacement.commit()
+ return PreparedInstallation(replacement: replacement, backupURL: backupURL)
+ } catch {
+ let originalError = error
+ // A failed atomic exchange leaves the installed app untouched. The owned
+ // duplicate backup is unnecessary until the exchange succeeds.
+ var backupCleanupFailure: Error?
+ if backupCreated {
+ do {
+ try FileManager.default.removeItem(at: backupURL)
+ } catch {
+ backupCleanupFailure = UpdateAppReplacement.Failure(
+ operation: .cleanup, recoveryDirectoryURL: backupURL, underlyingError: error
+ )
+ }
}
-
- // Move new app to Applications with new name
- try FileManager.default.moveItem(at: downloadedAppURL, to: finalAppURL)
- DebugLogger.shared.info("SimpleUpdater: Successfully installed new app at: \(finalAppURL.path)", source: "SimpleUpdater")
- } else {
- // Same name - normal replacement
- DebugLogger.shared.info("SimpleUpdater: Same app name, performing normal replacement", source: "SimpleUpdater")
- if FileManager.default.fileExists(atPath: installedAppURL.path) {
- try FileManager.default.removeItem(at: installedAppURL)
+ do {
+ try replacement.discardPrepared()
+ } catch {
+ throw error
}
- try FileManager.default.moveItem(at: downloadedAppURL, to: installedAppURL)
- finalAppURL = installedAppURL
+ if let backupCleanupFailure { throw backupCleanupFailure }
+ throw originalError
+ }
+ }
+
+ private func performSwapAndRelaunch(
+ installedAppURL: URL,
+ downloadedAppURL: URL,
+ expectedVersion: String?,
+ isRollback: Bool
+ ) async throws {
+ guard let identifier = Bundle.main.bundleIdentifier,
+ let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
+ else { throw SimpleUpdateError.notAnAppBundle }
+ let version = self.currentAppVersion
+ let name = self.installedAppName
+ let safeVersion = self.sanitizeVersion(version)
+ let suffix = "\(isRollback ? "rollback-" : "")\(UUID().uuidString)-\(Int(Date().timeIntervalSince1970))"
+ let backupURL = self.rollbackRootDirectory().appendingPathComponent("\(name)-\(safeVersion)-\(suffix).app")
+ let preparation = Task.detached(priority: .utility) {
+ try Self.prepareValidatedInstallation(
+ installedAppURL: installedAppURL,
+ downloadedAppURL: downloadedAppURL,
+ installedExpectation: .init(bundleIdentifier: identifier, version: version, build: build),
+ expectedVersion: expectedVersion,
+ backupURL: backupURL,
+ isRollback: isRollback
+ )
+ }
+ let installation = try await withTaskCancellationHandler {
+ try await preparation.value
+ } onCancel: {
+ preparation.cancel()
}
self.availableUpdateVersion = nil
self.availableChannelRevision = nil
-
- // Installation is finished. Do not leave the floating progress window owned by
- // the old process until it exits: quitting may be delayed or cancelled by AppKit.
- // Keep the operation gate active so that old process cannot start another install.
self.dismissUpdateInstallStatus()
-
- // Use modern NSWorkspace API for more reliable app launching
- DispatchQueue.main.async {
- DebugLogger.shared.info("SimpleUpdater: Attempting to relaunch app at: \(finalAppURL.path)", source: "SimpleUpdater")
-
- // Verify the app exists before trying to launch
- guard FileManager.default.fileExists(atPath: finalAppURL.path) else {
- DebugLogger.shared.error("SimpleUpdater: ERROR - App not found at expected location: \(finalAppURL.path)", source: "SimpleUpdater")
- self.resetUpdateOperation()
- // Don't terminate if we can't find the new app
- return
- }
-
- let configuration = NSWorkspace.OpenConfiguration()
- configuration.createsNewApplicationInstance = true
-
- NSWorkspace.shared.openApplication(at: finalAppURL, configuration: configuration) { _, error in
- if let error = error {
- DebugLogger.shared.error("SimpleUpdater: Failed to relaunch app: \(error)", source: "SimpleUpdater")
- DebugLogger.shared.error("SimpleUpdater: App location: \(finalAppURL.path)", source: "SimpleUpdater")
- Task { @MainActor in
- self.resetUpdateOperation()
- }
- // Don't terminate if relaunch failed - let user manually restart
+ let configuration = NSWorkspace.OpenConfiguration()
+ configuration.createsNewApplicationInstance = true
+ NSWorkspace.shared.openApplication(at: installedAppURL, configuration: configuration) { application, error in
+ Task { @MainActor in
+ guard error == nil, let application else {
+ await self.recoverFailedRelaunch(installation, error: error)
return
}
-
- DebugLogger.shared.info("SimpleUpdater: Successfully relaunched app, terminating old instance", source: "SimpleUpdater")
- // Give the new instance time to fully start before terminating
- DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
- UpdateTerminationScheduler.requestTermination()
+ // Keep the outgoing app and shared lock through the existing startup
+ // grace period; a newly launched process must not start another swap.
+ try? await Task.sleep(for: .seconds(2))
+ guard !application.isTerminated else {
+ await self.recoverFailedRelaunch(installation, error: nil)
+ return
+ }
+ // Keep the shared lock while pruning so another process cannot
+ // create a backup that this operation mistakes for an old one.
+ var protected: Set<URL> = [installation.backupURL]
+ if isRollback { protected.insert(downloadedAppURL) }
+ await self.pruneRollbackBackups(preserving: protected)
+ guard !application.isTerminated else {
+ await self.recoverFailedRelaunch(installation, error: nil)
+ return
+ }
+ let cleanupWarning = await Task.detached(priority: .utility) {
+ do {
+ try installation.replacement.finalize()
+ return String?.none
+ } catch {
+ return error.localizedDescription
+ }
+ }.value
+ if let cleanupWarning {
+ DebugLogger.shared.warning("SimpleUpdater: Update completed; cleanup failed: \(cleanupWarning)", source: "SimpleUpdater")
}
+ UpdateTerminationScheduler.requestTermination()
+ }
+ }
+ }
+
+ private func recoverFailedRelaunch(_ installation: PreparedInstallation, error: Error?) async {
+ let recoveryWarning = await Task.detached(priority: .utility) {
+ do {
+ try installation.replacement.recover()
+ return String?.none
+ } catch {
+ return error.localizedDescription
}
+ }.value
+ self.resetUpdateOperation()
+ if let error {
+ DebugLogger.shared.error("SimpleUpdater: Relaunch failed: \(error.localizedDescription)", source: "SimpleUpdater")
+ }
+ if let recoveryWarning {
+ DebugLogger.shared.error("SimpleUpdater: Recovery failed; saved app at \(installation.backupURL.path): \(recoveryWarning)", source: "SimpleUpdater")
}
+ self.showUpdateCheckResult(
+ title: "Update Failed",
+ message: recoveryWarning == nil
+ ? "The new app could not start. Your previous version has been restored. Please try again."
+ : "The app could not restart. Your previous version is saved at \(installation.backupURL.path)."
+ )
}
}
diff --git a/Sources/Fluid/Services/SpeechModelFeed.swift b/Sources/Fluid/Services/SpeechModelFeed.swift
new file mode 100644
index 00000000..7943b0c8
--- /dev/null
+++ b/Sources/Fluid/Services/SpeechModelFeed.swift
@@ -0,0 +1,103 @@
+import CryptoKit
+import Foundation
+
+/// The signed list of current speech model releases. Rules and format: docs/MODEL_UPDATE_FEED.md.
+/// Foundation and CryptoKit only: Tools/model-release compiles this file to check a feed before it is published.
+nonisolated enum SpeechModelFeed {
+ struct Entry: Codable, Equatable, Sendable {
+ let release: String
+ let url: URL
+ let bytes: Int64
+ let sha256: String
+ let manifestSHA256: String
+ let format: Int
+ let minBuild: Int
+ }
+
+ struct Payload: Codable, Equatable, Sendable {
+ let schema: Int
+ let sequence: Int
+ let models: [String: [String: [Entry]]]
+ }
+
+ enum Rejection: String, Error, Equatable {
+ case tooLarge
+ case notAnEnvelope
+ case badSignature
+ case unreadablePayload
+ case unknownSchema
+ case staleSequence
+ case badEntry
+ }
+
+ static let schema = 1
+ static let maximumEnvelopeBytes = 64 * 1024
+ static let host = "models.fluidvoice.app"
+ static let pathPrefix = "/parakeet/"
+ static let byteRange: ClosedRange<Int64> = 20_000_000...1_000_000_000
+
+ private struct Envelope: Decodable {
+ let payload: String
+ let signature: String
+ }
+
+ /// The payload when the envelope is signed by one of `publicKeys` and every field of every entry is valid.
+ static func verified(envelope: Data, publicKeys: [String], lastSequence: Int) throws -> Payload {
+ guard envelope.count <= self.maximumEnvelopeBytes else { throw Rejection.tooLarge }
+ guard let decoded = try? JSONDecoder().decode(Envelope.self, from: envelope),
+ let payloadBytes = Data(base64Encoded: decoded.payload),
+ let signature = Data(base64Encoded: decoded.signature)
+ else { throw Rejection.notAnEnvelope }
+
+ let signed = publicKeys.contains { key in
+ guard let raw = Data(base64Encoded: key),
+ let publicKey = try? Curve25519.Signing.PublicKey(rawRepresentation: raw)
+ else { return false }
+ return publicKey.isValidSignature(signature, for: payloadBytes)
+ }
+ guard signed else { throw Rejection.badSignature }
+
+ guard let payload = try? JSONDecoder().decode(Payload.self, from: payloadBytes) else {
+ throw Rejection.unreadablePayload
+ }
+ guard payload.schema == self.schema else { throw Rejection.unknownSchema }
+ guard payload.sequence >= 1, payload.sequence >= lastSequence else { throw Rejection.staleSequence }
+ let entries = payload.models.values.flatMap { $0.values.flatMap { $0 } }
+ guard entries.allSatisfy(self.isValid) else { throw Rejection.badEntry }
+ return payload
+ }
+
+ /// Lists are newest first; the first release this build can run wins.
+ static func entry(
+ in payload: Payload,
+ model: String,
+ platform: String,
+ build: Int,
+ supportedFormat: Int
+ ) -> Entry? {
+ payload.models[model]?[platform]?.first { $0.format <= supportedFormat && $0.minBuild <= build }
+ }
+
+ static func isValid(_ entry: Entry) -> Bool {
+ let releaseCharacters = CharacterSet(charactersIn: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-")
+ guard !entry.release.isEmpty, entry.release.count <= 32,
+ entry.release.unicodeScalars.allSatisfy(releaseCharacters.contains)
+ else { return false }
+
+ let url = entry.url
+ let pathComponents = url.path.split(separator: "/", omittingEmptySubsequences: false).dropFirst()
+ guard url.scheme == "https", url.host == self.host, url.port == nil, url.user == nil, url.password == nil,
+ url.query == nil, url.fragment == nil,
+ url.path.hasPrefix(self.pathPrefix), url.path.hasSuffix(".tar"),
+ pathComponents.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." })
+ else { return false }
+
+ return self.isSHA256(entry.sha256) && self.isSHA256(entry.manifestSHA256)
+ && self.byteRange.contains(entry.bytes)
+ && entry.format >= 1 && entry.minBuild >= 1
+ }
+
+ private static func isSHA256(_ value: String) -> Bool {
+ value.utf8.count == 64 && value.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) }
+ }
+}
diff --git a/Sources/Fluid/Services/SpeechModelInstallationSnapshot.swift b/Sources/Fluid/Services/SpeechModelInstallationSnapshot.swift
new file mode 100644
index 00000000..9732abca
--- /dev/null
+++ b/Sources/Fluid/Services/SpeechModelInstallationSnapshot.swift
@@ -0,0 +1,259 @@
+import Combine
+import Foundation
+#if canImport(FluidAudio)
+import FluidAudio
+#endif
+
+/// UI reads immutable IDs. Only an event-triggered worker inspects downloaded files.
+@MainActor
+final class SpeechModelInstallationSnapshot: ObservableObject {
+ static let shared = SpeechModelInstallationSnapshot()
+
+ nonisolated enum State: Equatable, Sendable {
+ case checking, ready, failed
+ }
+
+ nonisolated struct Probe: Sendable {
+ nonisolated enum Kind: Sendable {
+ case builtIn
+ case parakeet(ParakeetSpeechModelCatalog.Descriptor)
+ case realtime(folder: String, requiredModels: [String])
+ case cohere(ExternalCoreMLASRModelSpec, storedPath: String?)
+ case nemotron(folder: String)
+ case whisper(file: String, expectedBytes: Int64)
+ case unavailable
+ }
+
+ let modelID: String
+ let kind: Kind
+ var rejectedManifestHashes: Set<String> = []
+ }
+
+ nonisolated struct ScanResult: Equatable, Sendable {
+ let installedIDs: Set<String>
+ let updateAvailableIDs: Set<String>
+ let installedArchiveHashes: [String: String]
+ let installedManifestHashes: [String: String]
+
+ init(installedIDs: Set<String>, updateAvailableIDs: Set<String> = [], installedArchiveHashes: [String: String] = [:], installedManifestHashes: [String: String] = [:]) {
+ self.installedIDs = installedIDs
+ self.updateAvailableIDs = updateAvailableIDs
+ self.installedArchiveHashes = installedArchiveHashes
+ self.installedManifestHashes = installedManifestHashes
+ }
+ }
+
+ nonisolated struct Value: Equatable, Sendable {
+ let state: State
+ let result: ScanResult
+ let latestDescriptors: [String: ParakeetSpeechModelCatalog.Descriptor]
+ }
+
+ typealias Scanner = @Sendable ([Probe]) async throws -> Set<String>
+ typealias ResultScanner = @Sendable ([Probe]) async throws -> ScanResult
+ @Published private(set) var value = Value(state: .checking, result: ScanResult(installedIDs: []), latestDescriptors: [:])
+ var installedIDs: Set<String> { self.value.result.installedIDs }
+ var updateAvailableIDs: Set<String> { self.value.result.updateAvailableIDs }
+ var installedArchiveHashes: [String: String] { self.value.result.installedArchiveHashes }
+ var installedManifestHashes: [String: String] { self.value.result.installedManifestHashes }
+ var latestDescriptors: [String: ParakeetSpeechModelCatalog.Descriptor] { self.value.latestDescriptors }
+ var state: State { self.value.state }
+ var isChecking: Bool { self.state == .checking }
+ var canUseModelActions: Bool { self.state == .ready }
+
+ private let capture: @MainActor () -> [Probe]
+ private let scanner: ResultScanner
+ private let timeoutNanoseconds: UInt64
+ private var generation: UInt64 = 0
+ private var pending: (generation: UInt64, probes: [Probe])?
+ private var worker: Task<Void, Never>?
+ private var deadline: Task<Void, Never>?
+ private var deadlineID: UUID?
+
+ init(
+ timeoutNanoseconds: UInt64 = 5_000_000_000,
+ capture: @escaping @MainActor () -> [Probe] = SpeechModelInstallationSnapshot.captureProbes,
+ scanner: Scanner? = nil,
+ resultScanner: @escaping ResultScanner = { try await SpeechModelInstallationSnapshot.scanResult($0) }
+ ) {
+ self.timeoutNanoseconds = timeoutNanoseconds
+ self.capture = capture
+ if let scanner {
+ self.scanner = { try ScanResult(installedIDs: await scanner($0)) }
+ } else {
+ self.scanner = resultScanner
+ }
+ }
+
+ func isInstalled(modelID: String) -> Bool { self.installedIDs.contains(modelID) }
+ func isUpdateAvailable(modelID: String) -> Bool { self.updateAvailableIDs.contains(modelID) }
+
+ /// A display/profile key lookup only; it never starts download or reads disk.
+ func installedDescriptor(for model: SettingsStore.SpeechModel) -> ParakeetSpeechModelCatalog.Descriptor? {
+ guard let descriptor = self.latestDescriptors[model.id], let hash = self.installedArchiveHashes[model.id] else { return nil }
+ return descriptor.replacingArchive(url: nil, sha256: hash, manifestSHA256: self.installedManifestHashes[model.id])
+ }
+
+ /// Keep at most one worker and one latest request. Byte-progress callbacks never call this.
+ func refresh() {
+ self.generation &+= 1
+ self.pending = (self.generation, self.capture())
+ self.value = Value(state: .checking, result: self.value.result, latestDescriptors: self.value.latestDescriptors)
+ if self.deadline == nil {
+ let id = UUID()
+ self.deadlineID = id
+ self.deadline = Task { [weak self, timeoutNanoseconds] in
+ do { try await Task.sleep(nanoseconds: timeoutNanoseconds) } catch { return }
+ guard !Task.isCancelled, let self, self.deadlineID == id, self.state == .checking else { return }
+ self.cancel()
+ }
+ }
+ self.startWorkerIfNeeded()
+ }
+
+ /// A slow/unavailable volume has a visible bounded exit. A canceled worker must
+ /// actually drain before a replacement starts, even when filesystem IO cannot cancel.
+ func cancel() {
+ self.generation &+= 1
+ self.pending = nil
+ self.worker?.cancel()
+ self.deadline?.cancel()
+ self.deadline = nil
+ self.deadlineID = nil
+ self.value = Value(state: .failed, result: ScanResult(installedIDs: []), latestDescriptors: self.value.latestDescriptors)
+ }
+
+ private func startWorkerIfNeeded() {
+ guard self.worker == nil, self.pending != nil else { return }
+ self.worker = Task { [weak self] in
+ guard let self else { return }
+ while !Task.isCancelled, let request = self.pending {
+ self.pending = nil
+ do {
+ let installed = try await self.scanner(request.probes)
+ guard !Task.isCancelled, request.generation == self.generation else { continue }
+ let descriptors = Dictionary(request.probes.compactMap { probe -> (String, ParakeetSpeechModelCatalog.Descriptor)? in
+ guard case let .parakeet(descriptor) = probe.kind else { return nil }
+ return (probe.modelID, descriptor)
+ }, uniquingKeysWith: { _, latest in latest })
+ self.value = Value(state: .ready, result: installed, latestDescriptors: descriptors)
+ self.finishDeadline()
+ } catch {
+ guard !Task.isCancelled, request.generation == self.generation else { continue }
+ self.value = Value(state: .failed, result: ScanResult(installedIDs: []), latestDescriptors: self.value.latestDescriptors)
+ self.finishDeadline()
+ }
+ }
+ self.worker = nil
+ self.startWorkerIfNeeded()
+ }
+ }
+
+ private func finishDeadline() {
+ self.deadline?.cancel()
+ self.deadline = nil
+ self.deadlineID = nil
+ }
+
+ private static func captureProbes() -> [Probe] {
+ let releases = CompactSpeechModelReleaseCatalog.shared
+ return SettingsStore.SpeechModel.availableModels.map { model in
+ let kind: Probe.Kind
+ if let descriptor = CompactSpeechModelReleaseCatalog.shared.descriptor(for: model) ?? model.parakeetDescriptor {
+ kind = .parakeet(descriptor)
+ } else if let spec = model.externalCoreMLSpec {
+ kind = .cohere(spec, storedPath: SettingsStore.shared.storedExternalCoreMLArtifactsPath(for: model))
+ } else if let file = model.whisperModelFile {
+ kind = .whisper(file: file, expectedBytes: model.expectedDownloadBytes)
+ } else {
+ switch model {
+ case .appleSpeech, .appleSpeechAnalyzer:
+ kind = .builtIn
+ case .parakeetRealtime:
+ #if canImport(FluidAudio)
+ kind = .realtime(folder: Repo.parakeetEou160.folderName, requiredModels: Array(ModelNames.ParakeetEOU.requiredModels).sorted())
+ #else
+ kind = .unavailable
+ #endif
+ case .nemotronOffline:
+ kind = .nemotron(folder: "nemotron-3.5-asr-offline-6bit-CoreML")
+ case .nemotronStreaming, .nemotronStreaming320:
+ kind = .nemotron(folder: "nemotron-3.5-asr-streaming320-int8-CoreML")
+ default:
+ kind = .unavailable
+ }
+ }
+ return Probe(modelID: model.id, kind: kind, rejectedManifestHashes: releases.descriptor(for: model) == nil ? [] : releases.snapshot.rejectedManifestHashes)
+ }
+ }
+
+ @concurrent static func scan(_ probes: [Probe], cachesDirectory: URL? = nil, modelsDirectory: URL? = nil) async throws -> Set<String> {
+ try await self.scanResult(probes, cachesDirectory: cachesDirectory, modelsDirectory: modelsDirectory).installedIDs
+ }
+
+ @concurrent static func scanResult(_ probes: [Probe], cachesDirectory: URL? = nil, modelsDirectory: URL? = nil) async throws -> ScanResult {
+ var installed: Set<String> = []
+ var updates: Set<String> = []
+ var hashes: [String: String] = [:]
+ var manifests: [String: String] = [:]
+ let fm = FileManager.default
+ let caches = cachesDirectory ?? fm.urls(for: .cachesDirectory, in: .userDomainMask).first
+ let models = modelsDirectory ?? fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?
+ .appendingPathComponent("FluidAudio/Models", isDirectory: true)
+ for probe in probes {
+ try Task.checkCancellation()
+ let exists: Bool
+ switch probe.kind {
+ case .builtIn:
+ exists = true
+ case let .parakeet(descriptor):
+ if descriptor.variant == .mini || descriptor.variant == .pico {
+ let hash = models.flatMap { descriptor.installedArchiveSHA256(at: descriptor.cacheDirectory(in: $0)) }
+ exists = hash != nil
+ if let hash {
+ hashes[probe.modelID] = hash
+ let manifest = models.flatMap { descriptor.installedManifestSHA256(at: descriptor.cacheDirectory(in: $0)) }
+ if let manifest { manifests[probe.modelID] = manifest }
+ let differs: Bool
+ if let latest = descriptor.manifestSHA256, let manifest {
+ differs = latest != manifest
+ } else {
+ // Legacy complete caches with the same tar need no redundant download.
+ differs = hash != descriptor.archiveSHA256
+ }
+ let rejected = descriptor.manifestSHA256.map { probe.rejectedManifestHashes.contains($0) } ?? false
+ if differs, !rejected { updates.insert(probe.modelID) }
+ }
+ } else {
+ exists = models.map { descriptor.artifactsAreComplete(at: descriptor.cacheDirectory(in: $0)) } ?? false
+ }
+ case let .realtime(folder, requiredModels):
+ let directory = models?.appendingPathComponent("parakeet-eou-streaming", isDirectory: true)
+ .appendingPathComponent(folder, isDirectory: true)
+ exists = directory.map { root in
+ requiredModels.allSatisfy {
+ HuggingFaceModelDownloader.artifactIsComplete(at: root.appendingPathComponent($0), isDirectory: $0.hasSuffix(".mlmodelc"))
+ }
+ } ?? false
+ case let .cohere(spec, storedPath):
+ let directory = storedPath.map { URL(fileURLWithPath: $0, isDirectory: true) } ?? spec.defaultCacheDirectory
+ exists = directory.map { spec.validatesInstalledArtifacts(at: $0) } ?? false
+ case let .nemotron(folder):
+ #if arch(arm64)
+ exists = caches.map { NemotronProvider.artifactsAreComplete(at: $0.appendingPathComponent(folder, isDirectory: true)) } ?? false
+ #else
+ exists = false
+ #endif
+ case let .whisper(file, expectedBytes):
+ let url = caches?.appendingPathComponent("WhisperModels", isDirectory: true).appendingPathComponent(file)
+ let attributes = url.flatMap { try? fm.attributesOfItem(atPath: $0.path) }
+ exists = expectedBytes > 0 && (attributes?[.size] as? NSNumber)?.int64Value == expectedBytes
+ case .unavailable:
+ exists = false
+ }
+ if exists { installed.insert(probe.modelID) }
+ }
+ try Task.checkCancellation()
+ return ScanResult(installedIDs: installed, updateAvailableIDs: updates, installedArchiveHashes: hashes, installedManifestHashes: manifests)
+ }
+}
diff --git a/Sources/Fluid/Services/UpdateAppReplacement.swift b/Sources/Fluid/Services/UpdateAppReplacement.swift
new file mode 100644
index 00000000..c8fdc7e8
--- /dev/null
+++ b/Sources/Fluid/Services/UpdateAppReplacement.swift
@@ -0,0 +1,285 @@
+import Darwin
+import Foundation
+
+/// Copies the incoming bundle, then exchanges it atomically with the installed bundle.
+/// The caller validates `stagedAppURL` and saves its durable rollback backup before commit.
+/// All methods perform disk IO and must run outside the main actor.
+final nonisolated class UpdateAppReplacement: @unchecked Sendable {
+ nonisolated struct Operations: Sendable {
+ var createDirectory: @Sendable (URL) throws -> Void
+ var copyBundle: @Sendable (URL, URL) throws -> Void
+ var exchangeBundles: @Sendable (URL, URL) throws -> Void
+ var removeDirectory: @Sendable (URL) throws -> Void
+
+ static let live = Operations(
+ createDirectory: { url in
+ try FileManager.default.createDirectory(
+ at: url,
+ withIntermediateDirectories: false,
+ attributes: [.posixPermissions: 0o700]
+ )
+ },
+ copyBundle: { source, destination in
+ try FileManager.default.copyItem(at: source, to: destination)
+ },
+ exchangeBundles: { installed, staged in
+ let result = installed.withUnsafeFileSystemRepresentation { installedPath in
+ staged.withUnsafeFileSystemRepresentation { stagedPath in
+ renameatx_np(AT_FDCWD, installedPath, AT_FDCWD, stagedPath, UInt32(RENAME_SWAP))
+ }
+ }
+ guard result == 0 else {
+ throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno))
+ }
+ },
+ removeDirectory: { url in
+ do {
+ try FileManager.default.removeItem(at: url)
+ } catch let error as CocoaError where error.code == .fileNoSuchFile {
+ // Cleanup is idempotent after a completed prior attempt.
+ }
+ }
+ )
+ }
+
+ nonisolated enum Operation: String, Sendable {
+ case preparation, commit, recovery, cleanup
+ }
+
+ nonisolated struct Failure: LocalizedError {
+ let operation: Operation
+ let recoveryDirectoryURL: URL?
+ let underlyingError: Error
+
+ var errorDescription: String? {
+ let recovery = self.recoveryDirectoryURL.map { " Recovery files: \($0.path)." } ?? ""
+ return "App replacement \(self.operation.rawValue) failed: \(self.underlyingError.localizedDescription).\(recovery)"
+ }
+ }
+
+ private enum State {
+ case prepared, committed, restored, discarded, finalized
+ }
+
+ let installedAppURL: URL
+ let stagedAppURL: URL
+ let stagingDirectoryURL: URL
+ /// After commit this contains the outgoing bundle, until recovery or finalization.
+ var recoveryAppURL: URL { self.stagedAppURL }
+ private let operations: Operations
+ private var processLock: ProcessLock?
+ private let installedIdentity: BundleIdentity
+ private var stagedIdentity: BundleIdentity?
+ private let lock = NSLock()
+ private var state = State.prepared
+
+ private init(installedAppURL: URL, stagingDirectoryURL: URL, operations: Operations, processLock: ProcessLock, installedIdentity: BundleIdentity) {
+ self.installedAppURL = installedAppURL
+ self.stagingDirectoryURL = stagingDirectoryURL
+ self.stagedAppURL = stagingDirectoryURL.appendingPathComponent(installedAppURL.lastPathComponent, isDirectory: true)
+ self.operations = operations
+ self.processLock = processLock
+ self.installedIdentity = installedIdentity
+ }
+
+ static func prepare(
+ installedAppURL: URL,
+ replacementAppURL: URL,
+ validateInstalledApp: (@Sendable (URL) throws -> Void)? = nil,
+ operations: Operations = .live
+ ) throws -> UpdateAppReplacement {
+ try self.requireRealBundleDirectory(installedAppURL)
+ try self.requireRealBundleDirectory(replacementAppURL)
+ // A retained recovery/cleanup directory blocks another attempt rather than
+ // accumulating new copies or destroying recovery files from a prior attempt.
+ let directory = installedAppURL.deletingLastPathComponent()
+ .appendingPathComponent(".fluidvoice-update-\(installedAppURL.lastPathComponent).staging", isDirectory: true)
+ let processLock = try ProcessLock(installedAppURL: installedAppURL)
+ let transaction = try UpdateAppReplacement(
+ installedAppURL: installedAppURL,
+ stagingDirectoryURL: directory,
+ operations: operations,
+ processLock: processLock,
+ installedIdentity: BundleIdentity(installedAppURL)
+ )
+ var createdDirectory = false
+ do {
+ // Revalidate under the process-shared lock, including normal attempts.
+ try validateInstalledApp?(installedAppURL)
+ if FileManager.default.fileExists(atPath: directory.path) {
+ try transaction.discardStaleStage(validateInstalledApp: validateInstalledApp)
+ }
+ try operations.createDirectory(directory)
+ createdDirectory = true
+ try transaction.ownershipData.write(to: transaction.ownershipURL, options: .atomic)
+ try operations.copyBundle(replacementAppURL, transaction.stagedAppURL)
+ transaction.stagedIdentity = try BundleIdentity(transaction.stagedAppURL)
+ return transaction
+ } catch {
+ guard createdDirectory else {
+ throw Failure(
+ operation: .preparation,
+ recoveryDirectoryURL: FileManager.default.fileExists(atPath: directory.path) ? directory : nil,
+ underlyingError: error
+ )
+ }
+ do {
+ try operations.removeDirectory(directory)
+ } catch let cleanupError {
+ throw Failure(operation: .cleanup, recoveryDirectoryURL: directory, underlyingError: cleanupError)
+ }
+ throw Failure(operation: .preparation, recoveryDirectoryURL: nil, underlyingError: error)
+ }
+ }
+
+ /// No delete/move fallback: exchange failure leaves the installed bundle in place.
+ func commit() throws {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ guard self.state == .prepared else { throw self.invalidState(.commit) }
+ do {
+ try Self.requireRealBundleDirectory(self.installedAppURL)
+ try Self.requireRealBundleDirectory(self.stagedAppURL)
+ guard try BundleIdentity(self.installedAppURL) == self.installedIdentity,
+ try BundleIdentity(self.stagedAppURL) == self.stagedIdentity
+ else { throw CocoaError(.fileWriteFileExists) }
+ try self.operations.exchangeBundles(self.installedAppURL, self.stagedAppURL)
+ self.state = .committed
+ } catch {
+ throw Failure(operation: .commit, recoveryDirectoryURL: self.stagingDirectoryURL, underlyingError: error)
+ }
+ }
+
+ /// Cancels staging after validation/backup/commit failure without touching the installed app.
+ func discardPrepared() throws {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ guard self.state == .prepared || self.state == .discarded else { throw self.invalidState(.cleanup) }
+ guard self.processLock != nil else { return }
+ self.state = .discarded
+ try self.cleanup()
+ }
+
+ /// Restores the outgoing app after a failed relaunch. A failed exchange retains it for retry.
+ func recover() throws {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ if self.state == .committed {
+ do {
+ guard try BundleIdentity(self.installedAppURL) == self.stagedIdentity,
+ try BundleIdentity(self.stagedAppURL) == self.installedIdentity
+ else { throw CocoaError(.fileWriteFileExists) }
+ try self.operations.exchangeBundles(self.installedAppURL, self.stagedAppURL)
+ self.state = .restored
+ } catch {
+ throw Failure(operation: .recovery, recoveryDirectoryURL: self.stagingDirectoryURL, underlyingError: error)
+ }
+ } else if self.state != .restored {
+ throw self.invalidState(.recovery)
+ }
+ guard self.processLock != nil else { return }
+ try self.cleanup()
+ }
+
+ /// Call only after successful relaunch, with a durable precommit backup already retained.
+ /// Recursive cleanup can partially fail; it must never trigger recovery afterward.
+ func finalize() throws {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ guard self.state == .committed || self.state == .finalized else { throw self.invalidState(.cleanup) }
+ guard self.processLock != nil else { return }
+ self.state = .finalized
+ try self.cleanup()
+ }
+
+ private func cleanup() throws {
+ do {
+ try self.operations.removeDirectory(self.stagingDirectoryURL)
+ self.processLock = nil
+ } catch {
+ throw Failure(operation: .cleanup, recoveryDirectoryURL: self.stagingDirectoryURL, underlyingError: error)
+ }
+ }
+
+ private func invalidState(_ operation: Operation) -> Failure {
+ Failure(
+ operation: operation,
+ recoveryDirectoryURL: self.stagingDirectoryURL,
+ underlyingError: CocoaError(.fileWriteUnknown)
+ )
+ }
+
+ private var ownershipURL: URL { self.stagingDirectoryURL.appendingPathComponent("ownership") }
+ private var ownershipData: Data {
+ Data("FluidVoiceUpdateStage-v1\n\(self.installedAppURL.standardizedFileURL.path)\n".utf8)
+ }
+
+ private func discardStaleStage(validateInstalledApp: (@Sendable (URL) throws -> Void)?) throws {
+ let attributes = try FileManager.default.attributesOfItem(atPath: self.stagingDirectoryURL.path)
+ let markerAttributes = try FileManager.default.attributesOfItem(atPath: self.ownershipURL.path)
+ guard validateInstalledApp != nil,
+ attributes[.type] as? FileAttributeType == .typeDirectory,
+ markerAttributes[.type] as? FileAttributeType == .typeRegular,
+ (markerAttributes[.size] as? NSNumber)?.intValue == self.ownershipData.count,
+ try Data(contentsOf: self.ownershipURL) == self.ownershipData
+ else { throw CocoaError(.fileWriteFileExists) }
+ // Installed validation already passed under this lock. Remove this one known
+ // orphan only; no other sibling bundles or recovery paths are enumerated.
+ try self.operations.removeDirectory(self.stagingDirectoryURL)
+ }
+
+ private static func requireRealBundleDirectory(_ url: URL) throws {
+ let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
+ guard url.isFileURL, url.pathExtension == "app", attributes[.type] as? FileAttributeType == .typeDirectory else {
+ throw CocoaError(.fileReadInvalidFileName)
+ }
+ }
+
+ private struct BundleIdentity: Equatable, Sendable {
+ private let device: dev_t
+ private let inode: ino_t
+
+ init(_ url: URL) throws {
+ var status = stat()
+ guard lstat(url.path, &status) == 0,
+ status.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR)
+ else { throw CocoaError(.fileReadInvalidFileName) }
+ self.device = status.st_dev
+ self.inode = status.st_ino
+ }
+ }
+
+ /// The lock file is intentionally retained: unlinking it could let another
+ /// process lock a different inode while this transaction still owns the old one.
+ private final class ProcessLock {
+ private let descriptor: Int32
+
+ init(installedAppURL: URL) throws {
+ let url = installedAppURL.deletingLastPathComponent()
+ .appendingPathComponent(".fluidvoice-update-\(installedAppURL.lastPathComponent).lock")
+ let descriptor = url.withUnsafeFileSystemRepresentation { path in
+ guard let path else { return Int32(-1) }
+ return Darwin.open(path, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, mode_t(0o600))
+ }
+ guard descriptor >= 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
+ var status = stat()
+ guard fstat(descriptor, &status) == 0,
+ status.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG),
+ status.st_uid == geteuid(), status.st_nlink == 1
+ else {
+ Darwin.close(descriptor)
+ throw CocoaError(.fileWriteInvalidFileName)
+ }
+ guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {
+ let error = NSError(domain: NSPOSIXErrorDomain, code: Int(errno))
+ Darwin.close(descriptor)
+ throw error
+ }
+ self.descriptor = descriptor
+ }
+
+ deinit {
+ Darwin.close(self.descriptor)
+ }
+ }
+}
diff --git a/Sources/Fluid/Services/UpdateBundleValidator.swift b/Sources/Fluid/Services/UpdateBundleValidator.swift
new file mode 100644
index 00000000..f8727d60
--- /dev/null
+++ b/Sources/Fluid/Services/UpdateBundleValidator.swift
@@ -0,0 +1,196 @@
+import Foundation
+import Security
+
+/// Synchronous disk/security work. Call from the updater's background staging pipeline.
+/// The caller must keep the validated bundle unchanged until the filesystem exchange.
+nonisolated enum UpdateBundleValidator {
+ struct Expectation: Sendable {
+ let bundleIdentifier: String
+ /// Exact approved release version. Nil is only for inspecting an installed/rollback bundle.
+ let version: String?
+ /// GitHub tags do not publish build numbers; nil still requires a valid numeric build.
+ let build: String?
+
+ init(bundleIdentifier: String, version: String?, build: String? = nil) {
+ self.bundleIdentifier = bundleIdentifier
+ self.version = version
+ self.build = build
+ }
+ }
+
+ enum SigningPolicy: Sendable {
+ /// Downloaded releases must use this policy, including in Debug builds.
+ case developerID(allowedTeamIDs: Set<String>)
+ /// Only for local development builds and their rollback backups/tests.
+ case appleDevelopment(allowedTeamIDs: Set<String>)
+ /// Installed apps/rollback backups can use either approved signing certificate kind.
+ /// Never use this broader policy for a downloaded release.
+ case installedApp(allowedTeamIDs: Set<String>)
+
+ var allowedTeamIDs: Set<String> {
+ switch self {
+ case let .developerID(teams), let .appleDevelopment(teams), let .installedApp(teams): return teams
+ }
+ }
+
+ var certificateRequirement: String {
+ switch self {
+ case .developerID:
+ return "certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"
+ case .appleDevelopment:
+ return "certificate leaf[field.1.2.840.113635.100.6.1.2] exists"
+ case .installedApp:
+ return "((certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists) or certificate leaf[field.1.2.840.113635.100.6.1.2] exists)"
+ }
+ }
+ }
+
+ struct ValidatedBundle: Equatable, Sendable {
+ let bundleIdentifier: String
+ let version: String
+ let build: String
+ let teamIdentifier: String
+ }
+
+ enum ValidationError: LocalizedError, Equatable {
+ case invalidBundle
+ case invalidExpectation
+ case invalidSignature(OSStatus)
+ case missingSigningMetadata
+ case invalidBundleMetadata
+ case identityMismatch
+ case versionMismatch
+ case buildMismatch
+
+ var errorDescription: String? {
+ switch self {
+ case .invalidBundle: return "The update is not a valid application bundle."
+ case .invalidExpectation: return "The update's expected identity or signing policy is invalid."
+ case .invalidSignature: return "The update's signature or sealed contents could not be verified."
+ case .missingSigningMetadata: return "The update has no trusted signing identity."
+ case .invalidBundleMetadata: return "The update has invalid application metadata."
+ case .identityMismatch: return "The update belongs to a different application."
+ case .versionMismatch: return "The update does not match the selected release version."
+ case .buildMismatch: return "The update does not match the expected build."
+ }
+ }
+ }
+
+ static func validate(
+ at bundleURL: URL,
+ expectation: Expectation,
+ policy: SigningPolicy
+ ) throws -> ValidatedBundle {
+ guard self.validIdentifier(expectation.bundleIdentifier),
+ !policy.allowedTeamIDs.isEmpty,
+ policy.allowedTeamIDs.allSatisfy(self.validTeamIdentifier),
+ expectation.version.map(self.validVersion) ?? true,
+ expectation.build.map(self.validBuild) ?? true
+ else { throw ValidationError.invalidExpectation }
+
+ guard bundleURL.isFileURL, bundleURL.pathExtension.lowercased() == "app",
+ let values = try? bundleURL.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
+ values.isDirectory == true, values.isSymbolicLink != true
+ else { throw ValidationError.invalidBundle }
+
+ // Read the staged file afresh; Bundle caches can retain metadata from an earlier
+ // app at the same URL. Bound the read before passing the bundle to Security.
+ let plist = try self.readInfoPlist(at: bundleURL.appendingPathComponent("Contents/Info.plist"))
+
+ var staticCode: SecStaticCode?
+ let createStatus = SecStaticCodeCreateWithPath(bundleURL as CFURL, [], &staticCode)
+ guard createStatus == errSecSuccess, let staticCode else {
+ throw ValidationError.invalidSignature(createStatus)
+ }
+
+ let teams = policy.allowedTeamIDs.sorted().map { "certificate leaf[subject.OU] = \"\($0)\"" }.joined(separator: " or ")
+ let requirementText = "anchor apple generic and \(policy.certificateRequirement) and (\(teams))"
+ var requirement: SecRequirement?
+ let requirementStatus = SecRequirementCreateWithString(requirementText as CFString, [], &requirement)
+ guard requirementStatus == errSecSuccess, let requirement else {
+ throw ValidationError.invalidSignature(requirementStatus)
+ }
+
+ // No skip-resource/executable flags and no network access. One full check also
+ // verifies nested code and every executable architecture; serialize resource work.
+ let flags = SecCSFlags(rawValue: kSecCSCheckAllArchitectures | kSecCSCheckNestedCode | kSecCSStrictValidate | kSecCSSingleThreaded)
+ let validityStatus = SecStaticCodeCheckValidity(staticCode, flags, requirement)
+ guard validityStatus == errSecSuccess else {
+ throw ValidationError.invalidSignature(validityStatus)
+ }
+
+ var signingInformation: CFDictionary?
+ let informationStatus = SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation), &signingInformation)
+ guard informationStatus == errSecSuccess, let information = signingInformation as? [String: Any],
+ let identifier = information[kSecCodeInfoIdentifier as String] as? String,
+ let team = information[kSecCodeInfoTeamIdentifier as String] as? String,
+ policy.allowedTeamIDs.contains(team),
+ let certificates = information[kSecCodeInfoCertificates as String] as? [SecCertificate], !certificates.isEmpty,
+ let cms = information[kSecCodeInfoCMS as String] as? Data, !cms.isEmpty,
+ let signatureFlags = information[kSecCodeInfoFlags as String] as? NSNumber,
+ signatureFlags.uint32Value & SecCodeSignatureFlags.adhoc.rawValue == 0,
+ let securedPlist = information[kSecCodeInfoPList as String] as? [String: Any]
+ else { throw ValidationError.missingSigningMetadata }
+
+ guard let bundleIdentifier = plist["CFBundleIdentifier"] as? String,
+ let version = plist["CFBundleShortVersionString"] as? String, self.validVersion(version),
+ let build = plist["CFBundleVersion"] as? String, self.validBuild(build),
+ plist["CFBundlePackageType"] as? String == "APPL",
+ let executable = plist["CFBundleExecutable"] as? String,
+ !executable.isEmpty, executable != ".", executable != "..", !executable.contains("/"),
+ securedPlist["CFBundleIdentifier"] as? String == bundleIdentifier,
+ securedPlist["CFBundleShortVersionString"] as? String == version,
+ securedPlist["CFBundleVersion"] as? String == build
+ else { throw ValidationError.invalidBundleMetadata }
+ guard identifier == expectation.bundleIdentifier, bundleIdentifier == expectation.bundleIdentifier else {
+ throw ValidationError.identityMismatch
+ }
+ if let expectedVersion = expectation.version, version != expectedVersion {
+ throw ValidationError.versionMismatch
+ }
+ if let expectedBuild = expectation.build, build != expectedBuild {
+ throw ValidationError.buildMismatch
+ }
+ return ValidatedBundle(bundleIdentifier: bundleIdentifier, version: version, build: build, teamIdentifier: team)
+ }
+
+ private static func readInfoPlist(at url: URL) throws -> [String: Any] {
+ do {
+ let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
+ guard values.isRegularFile == true, values.isSymbolicLink != true else {
+ throw ValidationError.invalidBundleMetadata
+ }
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ let maximumSize = 1024 * 1024
+ guard let data = try handle.read(upToCount: maximumSize + 1), data.count <= maximumSize,
+ let plist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any]
+ else { throw ValidationError.invalidBundleMetadata }
+ return plist
+ } catch {
+ throw ValidationError.invalidBundleMetadata
+ }
+ }
+
+ private static func validIdentifier(_ value: String) -> Bool {
+ !value.isEmpty && value.utf8.count <= 255 && value.utf8.allSatisfy {
+ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 46
+ }
+ }
+
+ private static func validTeamIdentifier(_ value: String) -> Bool {
+ value.utf8.count == 10 && value.utf8.allSatisfy { (65...90).contains($0) || (48...57).contains($0) }
+ }
+
+ private static func validVersion(_ value: String) -> Bool {
+ !value.isEmpty && value.utf8.count <= 128 && value == value.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ private static func validBuild(_ value: String) -> Bool {
+ guard !value.isEmpty, value.utf8.count <= 32 else { return false }
+ let components = value.split(separator: ".", omittingEmptySubsequences: false)
+ return (1...3).contains(components.count) && components.allSatisfy {
+ !$0.isEmpty && $0.utf8.allSatisfy { (48...57).contains($0) }
+ }
+ }
+}
diff --git a/Sources/Fluid/Services/UpdateRollbackBackup.swift b/Sources/Fluid/Services/UpdateRollbackBackup.swift
new file mode 100644
index 00000000..f602283e
--- /dev/null
+++ b/Sources/Fluid/Services/UpdateRollbackBackup.swift
@@ -0,0 +1,94 @@
+import Foundation
+
+/// Called while the app replacement's process-shared lock is held.
+/// Disk and signature work must run outside the main actor.
+nonisolated enum UpdateRollbackBackup {
+ struct Operations: Sendable {
+ var createDirectory: @Sendable (URL) throws -> Void
+ var copyBundle: @Sendable (URL, URL) throws -> Void
+ var publishBundle: @Sendable (URL, URL) throws -> Void
+ var removeDirectory: @Sendable (URL) throws -> Void
+
+ static let live = Operations(
+ createDirectory: { url in
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
+ },
+ copyBundle: { source, destination in try FileManager.default.copyItem(at: source, to: destination) },
+ publishBundle: { source, destination in try FileManager.default.moveItem(at: source, to: destination) },
+ removeDirectory: { url in
+ do {
+ try FileManager.default.removeItem(at: url)
+ } catch let error as CocoaError where error.code == .fileNoSuchFile {}
+ }
+ )
+ }
+
+ struct Failure: LocalizedError {
+ let retainedDirectoryURL: URL?
+ let underlyingError: Error
+
+ var errorDescription: String? {
+ let retained = self.retainedDirectoryURL.map { " Retained backup files: \($0.path)." } ?? ""
+ return "The current app could not be backed up. Nothing was replaced.\(retained) \(self.underlyingError.localizedDescription)"
+ }
+ }
+
+ static func create(
+ installedAppURL: URL,
+ backupURL: URL,
+ validate: @Sendable (URL) throws -> Void,
+ operations: Operations = .live
+ ) throws {
+ let manager = FileManager.default
+ let root = backupURL.deletingLastPathComponent()
+ let directory = root.appendingPathComponent(".fluidvoice-backup-\(installedAppURL.lastPathComponent).staging", isDirectory: true)
+ let marker = directory.appendingPathComponent("ownership")
+ let ownership = Data("FluidVoiceRollbackBackup-v1\n\(installedAppURL.standardizedFileURL.path)\n".utf8)
+ let stagedBundle = directory.appendingPathComponent(installedAppURL.lastPathComponent, isDirectory: true)
+ var createdDirectory = false
+ do {
+ guard installedAppURL.isFileURL, backupURL.isFileURL,
+ installedAppURL.pathExtension == "app", backupURL.pathExtension == "app"
+ else { throw CocoaError(.fileWriteInvalidFileName) }
+ // Recheck before removing any owned crash leftovers. The supplied validator
+ // must enforce the running app's identity, version, build and trusted signature.
+ try validate(installedAppURL)
+ try manager.createDirectory(at: root, withIntermediateDirectories: true)
+ if manager.fileExists(atPath: directory.path) {
+ let attributes = try manager.attributesOfItem(atPath: directory.path)
+ let markerAttributes = try manager.attributesOfItem(atPath: marker.path)
+ guard attributes[.type] as? FileAttributeType == .typeDirectory,
+ markerAttributes[.type] as? FileAttributeType == .typeRegular,
+ (markerAttributes[.size] as? NSNumber)?.intValue == ownership.count,
+ try Data(contentsOf: marker) == ownership
+ else { throw CocoaError(.fileWriteFileExists) }
+ try operations.removeDirectory(directory)
+ }
+ try operations.createDirectory(directory)
+ createdDirectory = true
+ try ownership.write(to: marker, options: .atomic)
+ try operations.copyBundle(installedAppURL, stagedBundle)
+ try validate(stagedBundle)
+ // Same-filesystem publication is exclusive: an existing backup is never replaced.
+ try operations.publishBundle(stagedBundle, backupURL)
+ } catch {
+ let originalError = error
+ if createdDirectory {
+ do {
+ try operations.removeDirectory(directory)
+ } catch {
+ throw Failure(retainedDirectoryURL: directory, underlyingError: error)
+ }
+ }
+ throw Failure(
+ retainedDirectoryURL: manager.fileExists(atPath: directory.path) ? directory : nil,
+ underlyingError: originalError
+ )
+ }
+ do {
+ try operations.removeDirectory(directory)
+ } catch {
+ throw Failure(retainedDirectoryURL: directory, underlyingError: error)
+ }
+ }
+}
diff --git a/Sources/Fluid/Theme/Components/FluidVoiceBrandIcon.swift b/Sources/Fluid/Theme/Components/FluidVoiceBrandIcon.swift
new file mode 100644
index 00000000..58a06e8f
--- /dev/null
+++ b/Sources/Fluid/Theme/Components/FluidVoiceBrandIcon.swift
@@ -0,0 +1,19 @@
+import AppKit
+import SwiftUI
+
+/// Reuse AppKit's cached app icon; no asset lookup or filesystem query in the view.
+struct FluidVoiceBrandIcon: View {
+ private static let appIconImage: NSImage = NSApplication.shared.applicationIconImage
+ ?? NSImage(size: NSSize(width: 32, height: 32))
+
+ let size: CGFloat
+
+ var body: some View {
+ Image(nsImage: Self.appIconImage)
+ .resizable()
+ .interpolation(.high)
+ .aspectRatio(contentMode: .fit)
+ .frame(width: self.size, height: self.size)
+ .accessibilityHidden(true)
+ }
+}
diff --git a/Sources/Fluid/Theme/Components/WindowSizingComponents.swift b/Sources/Fluid/Theme/Components/WindowSizingComponents.swift
index df458b9b..e3fbf453 100644
--- a/Sources/Fluid/Theme/Components/WindowSizingComponents.swift
+++ b/Sources/Fluid/Theme/Components/WindowSizingComponents.swift
@@ -36,16 +36,18 @@ private struct FluidWindowSizingBridge: NSViewRepresentable {
}
}
-private final class FluidWindowSizingNSView: NSView {
+final class FluidWindowSizingNSView: NSView {
var sizing: FluidWindowSizing {
didSet {
- self.applySizing()
+ guard self.sizing != oldValue else { return }
+ self.scheduleSizing()
}
}
private weak var observedWindow: NSWindow?
- private var resizeObserver: NSObjectProtocol?
+ private var windowObservers: [NSObjectProtocol] = []
private var isApplyingSizing = false
+ private var isSizingScheduled = false
init(sizing: FluidWindowSizing) {
self.sizing = sizing
@@ -64,7 +66,7 @@ private final class FluidWindowSizingNSView: NSView {
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
self.observeWindowIfNeeded()
- self.applySizing()
+ self.scheduleSizing()
}
private func observeWindowIfNeeded() {
@@ -74,35 +76,42 @@ private final class FluidWindowSizingNSView: NSView {
self.observedWindow = self.window
guard let window else { return }
- self.resizeObserver = NotificationCenter.default.addObserver(
- forName: NSWindow.didResizeNotification,
- object: window,
- queue: .main
- ) { [weak self] _ in
- self?.applySizing()
+ self.windowObservers = [NSWindow.didResizeNotification, NSWindow.didExitFullScreenNotification].map { name in
+ NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
+ self?.scheduleSizing()
+ }
}
}
private func removeResizeObserver() {
- if let resizeObserver {
- NotificationCenter.default.removeObserver(resizeObserver)
+ for observer in self.windowObservers {
+ NotificationCenter.default.removeObserver(observer)
+ }
+ self.windowObservers.removeAll()
+ }
+
+ private func scheduleSizing() {
+ guard !self.isSizingScheduled else { return }
+ self.isSizingScheduled = true
+ // NSWindow bounds must not change inside SwiftUI's constraint/layout pass.
+ // One deferred application reads the latest sizing and current window.
+ DispatchQueue.main.async { [weak self] in
+ guard let self else { return }
+ self.isSizingScheduled = false
+ self.applySizing()
}
- self.resizeObserver = nil
}
private func applySizing() {
- guard !self.isApplyingSizing, let window else { return }
+ guard !self.isApplyingSizing, let window, !window.styleMask.contains(.fullScreen) else { return }
self.isApplyingSizing = true
defer { self.isApplyingSizing = false }
let minSize = self.sizing.minSize
- window.minSize = minSize
+ if window.minSize != minSize { window.minSize = minSize }
let maximumSize = self.sizing.maximumSize ?? NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
- window.maxSize = maximumSize
-
- // Full-screen geometry belongs to macOS, not the normal-window bounds.
- guard !window.styleMask.contains(.fullScreen) else { return }
+ if window.maxSize != maximumSize { window.maxSize = maximumSize }
let frame = window.frame
let targetWidth = min(max(frame.width, minSize.width), maximumSize.width)
diff --git a/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift b/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift
index 8beef037..4b45a9d2 100644
--- a/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift
+++ b/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift
@@ -7,11 +7,13 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
let settings: SettingsStore
private let appServices: AppServices
private var cancellables = Set<AnyCancellable>()
+ let installations = SpeechModelInstallationSnapshot.shared
var asr: ASRService { self.appServices.asr }
var areSpeechModelActionsBlocked: Bool {
- self.asr.isRunning
+ !self.installations.canUseModelActions
+ || self.asr.isRunning
|| self.asr.deletingModelID != nil
|| self.asr.activeExclusiveActivity != nil
|| self.downloadingModel != nil
@@ -56,14 +58,23 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
}
}
.store(in: &self.cancellables)
+ self.installations.objectWillChange
+ .sink { [weak self] _ in
+ Task { @MainActor in self?.objectWillChange.send() }
+ }
+ .store(in: &self.cancellables)
}
func onAppear() {
self.previewSpeechModel = self.settings.selectedSpeechModel
self.selectedSpeechProvider = self.settings.selectedSpeechModel.provider
+ self.installations.refresh()
Task {
- await self.asr.checkIfModelsExistAsync()
+ let catalog = CompactSpeechModelReleaseCatalog.shared
+ let revision = catalog.revision
+ await catalog.refreshIfNeeded()
+ if catalog.revision != revision { self.installations.refresh() }
}
}
@@ -97,7 +108,7 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
}
if self.installedOnlyFilter {
- models = models.filter { $0.isInstalled }
+ models = models.filter { self.isSpeechModelInstalled($0) }
}
switch self.modelSortOption {
@@ -134,18 +145,22 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
}
}
- func downloadSpeechModel(_ model: SettingsStore.SpeechModel) {
+ func downloadSpeechModel(_ model: SettingsStore.SpeechModel, updateWeights: Bool = false) {
guard !self.areSpeechModelActionsBlocked else { return }
Task { [weak self] in
guard let self else { return }
do {
- try await self.asr.downloadModel(model, progressHandler: nil)
+ try await self.asr.downloadModel(model, updateWeights: updateWeights, progressHandler: nil)
DebugLogger.shared.info("Model download completed: \(model.displayName)", source: "VoiceEngineVM")
} catch is CancellationError {
DebugLogger.shared.info("Model download cancelled: \(model.displayName)", source: "VoiceEngineVM")
} catch {
DebugLogger.shared.error("Failed to download model \(model.displayName): \(error)", source: "VoiceEngineVM")
- self.asr.errorTitle = "Model Download Failed"
+ if let failure = error as? ParakeetArchiveDownloader.DownloadError, case .replacementCleanupFailed = failure {
+ self.asr.errorTitle = "Model Updated"
+ } else {
+ self.asr.errorTitle = updateWeights ? "Model Update Failed" : "Model Download Failed"
+ }
self.asr.errorMessage = error.localizedDescription
self.asr.showError = true
}
@@ -172,6 +187,18 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
self.settings.selectedSpeechModel == model
}
+ func isSpeechModelInstalled(_ model: SettingsStore.SpeechModel) -> Bool {
+ self.installations.isInstalled(modelID: model.id)
+ }
+
+ func isSpeechModelUpdateAvailable(_ model: SettingsStore.SpeechModel) -> Bool {
+ self.installations.updateAvailableIDs.contains(model.id)
+ }
+
+ func speechModelDownloadSize(_ model: SettingsStore.SpeechModel) -> String {
+ self.installations.latestDescriptors[model.id]?.downloadSize ?? model.downloadSize
+ }
+
var modelDescriptionText: String {
let model = self.settings.selectedSpeechModel
switch model {
@@ -183,6 +210,8 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
return "Parakeet TDT v3 uses CoreML and Neural Engine for fastest transcription (25 languages) on Apple Silicon."
case .parakeetTDTv2:
return "Parakeet TDT v2 is an English-only model optimized for accuracy and consistency on Apple Silicon."
+ case .fluidParakeetMini, .fluidParakeetPico:
+ return "\(model.cardDescription) Requires Apple silicon."
case .parakeetRealtime:
return "Parakeet Flash uses FluidAudio's true streaming EOU pipeline for low-latency English dictation. Best when you want words to appear live as you speak."
case .qwen3Asr:
diff --git a/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift b/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
index c28aca14..0e5b3678 100644
--- a/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
+++ b/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
@@ -12,7 +12,7 @@ extension VoiceEngineSettingsView {
var speechRecognitionCard: some View {
let selectedModel = self.settings.selectedSpeechModel
- let activeModel = selectedModel.isInstalled ? selectedModel : nil
+ let activeModel = self.viewModel.isSpeechModelInstalled(selectedModel) ? selectedModel : nil
let hasActiveModel = activeModel != nil
let otherModels = self.viewModel.filteredSpeechModels.filter { model in
guard let activeModel else { return true }
@@ -51,12 +51,12 @@ extension VoiceEngineSettingsView {
Spacer()
Menu {
ForEach(SpeechProviderFilter.allCases) { option in
- Button(option.rawValue) {
+ Button(option.displayName) {
self.viewModel.providerFilter = option
}
}
} label: {
- Text("Filter: \(self.viewModel.providerFilter.rawValue)")
+ Text("Filter: \(self.viewModel.providerFilter.displayName)")
}
.fluidDropdownStyle()
Menu {
@@ -85,9 +85,17 @@ extension VoiceEngineSettingsView {
Text("Active Model")
.font(self.theme.typography.sectionTitle)
.foregroundStyle(self.voiceEngineTitleText)
- Label("No active model yet. Download and activate one below.", systemImage: "arrow.down.circle")
- .font(self.theme.typography.bodySmall)
- .foregroundStyle(self.voiceEngineSecondaryText)
+ Label(
+ self.viewModel.installations.isChecking ? "Checking downloaded models…"
+ : (self.viewModel.installations.state == .failed ? "Couldn't check downloaded models. Try again." : "No active model yet. Download and activate one below."),
+ systemImage: self.viewModel.installations.canUseModelActions ? "arrow.down.circle" : "info.circle"
+ )
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.voiceEngineSecondaryText)
+ if self.viewModel.installations.state == .failed {
+ Button("Retry check") { self.viewModel.installations.refresh() }
+ .fluidGlassAction(quiet: true)
+ }
}
}
@@ -156,10 +164,17 @@ extension VoiceEngineSettingsView {
.font(self.theme.typography.bodySmall)
.foregroundStyle(self.voiceEngineSecondaryText)
.lineLimit(2)
+
+ if let descriptor = model.parakeetDescriptor {
+ Text(descriptor.creditLine)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.voiceEngineSecondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ }
}
HStack(spacing: 8) {
- Label(model.downloadSize, systemImage: "internaldrive")
+ Label(self.viewModel.speechModelDownloadSize(model), systemImage: "internaldrive")
.font(self.theme.typography.bodySmall)
.foregroundStyle(self.voiceEngineSecondaryText)
@@ -213,25 +228,28 @@ extension VoiceEngineSettingsView {
}
.frame(maxWidth: .infinity, alignment: .leading)
- HStack(spacing: 16) {
- LiquidBar(
- fillPercent: model.speedPercent,
- color: .yellow,
- secondaryColor: .orange,
- icon: "bolt.fill",
- label: "Speed"
- )
+ if model.hasPerformanceRatings {
+ HStack(spacing: 16) {
+ LiquidBar(
+ fillPercent: model.speedPercent,
+ color: .yellow,
+ secondaryColor: .orange,
+ icon: "bolt.fill",
+ label: "Speed"
+ )
- LiquidBar(
- fillPercent: model.accuracyPercent,
- color: Color.fluidGreen,
- secondaryColor: .cyan,
- icon: "target",
- label: "Accuracy"
- )
+ LiquidBar(
+ fillPercent: model.accuracyPercent,
+ color: Color.fluidGreen,
+ secondaryColor: .cyan,
+ icon: "target",
+ label: "Accuracy"
+ )
+ }
+ .frame(width: 140, alignment: .center)
+ .help("Relative ratings for comparing models, not measured transcription accuracy.")
+ .animation(.spring(response: 0.5, dampingFraction: 0.7), value: model.id)
}
- .frame(width: 140, alignment: .center)
- .animation(.spring(response: 0.5, dampingFraction: 0.7), value: model.id)
}
}
.padding(.vertical, 6)
@@ -240,7 +258,7 @@ extension VoiceEngineSettingsView {
func speechModelCard(for model: SettingsStore.SpeechModel) -> some View {
let isSelected = self.viewModel.previewSpeechModel == model
let isConfiguredActive = self.viewModel.isActiveSpeechModel(model)
- let isActive = isConfiguredActive && model.isInstalled && self.viewModel.asr.isAsrReady
+ let isActive = isConfiguredActive && self.viewModel.isSpeechModelInstalled(model) && self.viewModel.asr.isAsrReady
return HStack(alignment: .top, spacing: 10) {
Circle()
@@ -263,22 +281,24 @@ extension VoiceEngineSettingsView {
.foregroundStyle(self.voiceEngineSecondaryText)
HStack(spacing: 12) {
- HStack(spacing: 4) {
- Image(systemName: "bolt.fill")
- .font(.fluidSystem(size: 11))
- .foregroundStyle(.yellow)
- Text("Speed \(Int(model.speedPercent * 100))%")
- .font(self.theme.typography.bodyStrong)
- .foregroundStyle(self.voiceEngineSecondaryText)
- }
+ if model.hasPerformanceRatings {
+ HStack(spacing: 4) {
+ Image(systemName: "bolt.fill")
+ .font(.fluidSystem(size: 11))
+ .foregroundStyle(.yellow)
+ Text("Speed \(Int(model.speedPercent * 100))%")
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.voiceEngineSecondaryText)
+ }
- HStack(spacing: 4) {
- Image(systemName: "target")
- .font(.fluidSystem(size: 11))
- .foregroundStyle(Color.fluidGreen)
- Text("Acc \(Int(model.accuracyPercent * 100))%")
- .font(self.theme.typography.bodyStrong)
- .foregroundStyle(self.voiceEngineSecondaryText)
+ HStack(spacing: 4) {
+ Image(systemName: "target")
+ .font(.fluidSystem(size: 11))
+ .foregroundStyle(Color.fluidGreen)
+ Text("Acc \(Int(model.accuracyPercent * 100))%")
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.voiceEngineSecondaryText)
+ }
}
if isSelected && !isActive {
@@ -375,8 +395,29 @@ extension VoiceEngineSettingsView {
.controlSize(.small)
.disabled(self.viewModel.asr.isCancellingModelPreparation)
}
- } else if model.isInstalled {
+ } else if !self.viewModel.installations.canUseModelActions {
+ if self.viewModel.installations.isChecking {
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.mini)
+ Text("Checking downloads…")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.voiceEngineSecondaryText)
+ }
+ } else {
+ Button("Retry check") { self.viewModel.installations.refresh() }
+ .fluidGlassAction(quiet: true)
+ }
+ } else if self.viewModel.isSpeechModelInstalled(model) {
HStack(spacing: 8) {
+ if self.viewModel.isSpeechModelUpdateAvailable(model) {
+ Button("Update") {
+ self.viewModel.downloadSpeechModel(model, updateWeights: true)
+ }
+ .fluidGlassAction(prominent: true, tone: .orange)
+ .disabled(self.viewModel.areSpeechModelActionsBlocked)
+ .accessibilityLabel("Update \(model.humanReadableName)")
+ }
+
if isActive {
self.speechModelLanguagePicker(for: model)
.disabled(self.viewModel.areSpeechModelActionsBlocked)
@@ -391,7 +432,7 @@ extension VoiceEngineSettingsView {
Button("Activate") {
self.viewModel.activateSpeechModel(model)
}
- .fluidGlassAction(quiet: true)
+ .fluidGlassAction(prominent: true)
.disabled(self.viewModel.areSpeechModelActionsBlocked)
}
@@ -626,6 +667,9 @@ extension VoiceEngineSettingsView {
}
private func speechModelSubtitle(for model: SettingsStore.SpeechModel) -> String {
+ if model == .fluidParakeetMini || model == .fluidParakeetPico {
+ return model.languageSupport
+ }
switch model {
case .nemotronStreaming, .nemotronStreaming320:
return "Nemotron Speech 3.5 - Streaming Capable"
@@ -761,7 +805,9 @@ extension VoiceEngineSettingsView {
RoundedRectangle(cornerRadius: 7, style: .continuous)
.fill(bgColor)
- if model.usesAppleLogo {
+ if model.brandName == "FluidVoice" {
+ FluidVoiceBrandIcon(size: 28)
+ } else if model.usesAppleLogo {
Image(systemName: "apple.logo")
.font(.fluidSystem(size: 14, weight: .medium))
.foregroundStyle(.primary)
diff --git a/Sources/Fluid/UI/AISettingsView.swift b/Sources/Fluid/UI/AISettingsView.swift
index 20e85fd8..4c845475 100644
--- a/Sources/Fluid/UI/AISettingsView.swift
+++ b/Sources/Fluid/UI/AISettingsView.swift
@@ -75,6 +75,7 @@ enum SpeechProviderFilter: String, CaseIterable, Identifiable {
case openai = "OpenAI"
var id: String { self.rawValue }
+ var displayName: String { self == .nvidia ? "FluidVoice / NVIDIA" : self.rawValue }
}
enum AISettingsLayout {
diff --git a/Sources/Fluid/UI/AppSearchResultsView.swift b/Sources/Fluid/UI/AppSearchResultsView.swift
index 6f9760d5..fb64cd13 100644
--- a/Sources/Fluid/UI/AppSearchResultsView.swift
+++ b/Sources/Fluid/UI/AppSearchResultsView.swift
@@ -23,7 +23,26 @@ struct AppSearchResultsView: View {
var body: some View {
ScrollViewReader { proxy in
List {
- if self.service.groups.isEmpty {
+ if self.service.isSearching {
+ Text("Searching…")
+ .font(self.theme.typography.sidebarItem)
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, self.theme.metrics.spacing.md)
+ } else if let error = self.service.searchError {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ Text(error)
+ .font(self.theme.typography.sidebarItem)
+ .foregroundStyle(.secondary)
+ .lineLimit(3)
+ .fixedSize(horizontal: false, vertical: true)
+ Button("Retry") { self.service.retry() }
+ .buttonStyle(.plain)
+ .font(self.theme.typography.sidebarItem)
+ .foregroundStyle(self.theme.palette.accent)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, self.theme.metrics.spacing.md)
+ } else if self.service.groups.isEmpty {
Text("No results")
.font(self.theme.typography.sidebarItem)
.foregroundStyle(.secondary)
diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swift
index c702a473..456bd6ec 100644
--- a/Sources/Fluid/UI/CustomDictionaryView.swift
+++ b/Sources/Fluid/UI/CustomDictionaryView.swift
@@ -23,6 +23,10 @@ struct CustomDictionaryView: View {
@Environment(\.theme) private var theme
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@EnvironmentObject private var appServices: AppServices
+ @ObservedObject private var settings = SettingsStore.shared
+ @ObservedObject private var modelInstallations = SpeechModelInstallationSnapshot.shared
+ @State private var pronunciationRevisionNotice: String?
+ @State private var pronunciationRevisionNoticeRefresh: UInt64 = 0
/// A row picked in the sidebar search. Opening it is the reveal; the binding is
/// cleared so the same row can be picked again later.
@@ -269,6 +273,12 @@ struct CustomDictionaryView: View {
HStack(spacing: 0) {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xl) {
+ if let notice = self.pronunciationRevisionNotice {
+ Text(notice)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ }
self.trainReplacementSection
}
.fluidPageContent(width: .reading, alignment: .center)
@@ -312,6 +322,19 @@ struct CustomDictionaryView: View {
.task(id: self.revealTarget) {
self.revealSearchTarget()
}
+ .task(id: self.pronunciationRevisionNoticeRequest) {
+ self.pronunciationRevisionNotice = nil
+ guard !self.formattingOnly,
+ let descriptor = self.modelInstallations.installedDescriptor(for: self.settings.selectedSpeechModel),
+ descriptor.variant == .mini || descriptor.variant == .pico
+ else { return }
+ let entryIDs = Set(self.settings.customDictionaryEntries.map(\.id))
+ let profiles = await PronunciationDictionaryStore.shared.allProfiles()
+ guard !Task.isCancelled,
+ descriptor.pronunciationModelKey == self.modelInstallations.installedDescriptor(for: self.settings.selectedSpeechModel)?.pronunciationModelKey
+ else { return }
+ self.pronunciationRevisionNotice = DictionaryPronunciationRevisionPolicy.notice(profiles: profiles, descriptor: descriptor, entryIDs: entryIDs)
+ }
.overlay {
if let confirmation = self.replacementConfirmation {
ReplacementConfirmationToast(confirmation: confirmation)
@@ -356,6 +379,11 @@ struct CustomDictionaryView: View {
.onReceive(NotificationCenter.default.publisher(for: .parakeetVocabularyDidChange)) { _ in
guard !self.formattingOnly else { return }
self.entries = SettingsStore.shared.customDictionaryEntries
+ self.pronunciationRevisionNoticeRefresh &+= 1
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .settingsBackupDidRestore)) { _ in
+ guard !self.formattingOnly else { return }
+ self.pronunciationRevisionNoticeRefresh &+= 1
}
.onChange(of: self.pronunciationEnabled) { _, enabled in
guard !enabled else { return }
@@ -825,6 +853,10 @@ struct CustomDictionaryView: View {
.fixedSize(horizontal: false, vertical: true)
}
+ private var pronunciationRevisionNoticeRequest: String {
+ "\(self.settings.selectedSpeechModel.rawValue):\(self.modelInstallations.installedArchiveHashes[self.settings.selectedSpeechModel.id] ?? ""): \(self.pronunciationRevisionNoticeRefresh)"
+ }
+
private var trainingRecorderPanel: some View {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
Text("Teach FluidVoice your pronunciation")
@@ -3191,6 +3223,30 @@ enum CustomDictionaryManualEntry {
}
}
+nonisolated enum DictionaryPronunciationRevisionPolicy {
+ /// Pure UI snapshot: no file access, settings writes or background re-encoding.
+ static func notice(
+ profiles: [PronunciationDictionaryProfile],
+ descriptor: ParakeetSpeechModelCatalog.Descriptor,
+ entryIDs: Set<UUID>
+ ) -> String? {
+ guard descriptor.variant == .mini || descriptor.variant == .pico else { return nil }
+ let current = Set(profiles.filter {
+ $0.modelKey == descriptor.pronunciationModelKey && $0.isEligibleForMatching
+ }.map(\.dictionaryEntryID))
+ let outdated = profiles.filter {
+ entryIDs.contains($0.dictionaryEntryID) && !current.contains($0.dictionaryEntryID)
+ && ($0.modelKey == descriptor.modelID || $0.modelKey.hasPrefix(descriptor.modelID + ":sha256:"))
+ && $0.modelKey != descriptor.pronunciationModelKey
+ }
+ let labels = Array(Set(outdated.map(\.label))).sorted()
+ guard !labels.isEmpty else { return nil }
+ let words = labels.prefix(3).joined(separator: ", ")
+ let additional = labels.count > 3 ? " and \(labels.count - 3) more" : ""
+ return "Pronunciation recordings for \(words)\(additional) need retraining for the updated \(descriptor.displayName). Your custom words and text corrections remain saved."
+ }
+}
+
enum PronunciationProfileEditPolicy {
static func shouldDiscardProfile(previousReplacement: String, updatedReplacement: String) -> Bool {
previousReplacement.caseInsensitiveCompare(updatedReplacement) != .orderedSame
diff --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swift
index decc9549..6d25c0e7 100644
--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift
+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift
@@ -146,6 +146,8 @@ struct MeetingTranscriptionView: View {
@State private var setupDraft: MeetingTranscriptionSetupDraft
@State private var setupDraftBeforeEditing: MeetingTranscriptionSetupDraft
+ @State private var pendingBackupSetupRefresh = false
+ @State private var cachedSystemDefaultMicrophoneUID: String?
@State private var isShowingMeetingSettings: Bool
@State private var applications: [MeetingApplicationOption] = []
@State private var microphones: [MeetingMicrophoneOption] = []
@@ -303,6 +305,13 @@ struct MeetingTranscriptionView: View {
Task { await self.refreshSources(requestPermissions: false) }
self.regenerateDefaultTitleIfNeeded()
}
+ .onReceive(NotificationCenter.default.publisher(for: .settingsBackupDidRestore)) { _ in
+ self.pendingBackupSetupRefresh = true
+ self.applyPendingBackupSetupRefresh()
+ }
+ .onChange(of: self.canRefreshSetupAfterBackupRestore) { _, canRefresh in
+ if canRefresh { self.applyPendingBackupSetupRefresh() }
+ }
.onChange(of: self.setupDraft.selectedApplicationID) { _, _ in
self.regenerateDefaultTitleIfNeeded()
}
@@ -575,6 +584,7 @@ struct MeetingTranscriptionView: View {
if AVCaptureDevice.authorizationStatus(for: .audio) == .authorized {
let snapshot = await MeetingCaptureSourceCatalog.microphoneSnapshot()
let identities = snapshot.identities
+ self.cachedSystemDefaultMicrophoneUID = snapshot.defaultCoreAudioUID
self.microphones = identities.map(MeetingMicrophoneOption.init)
self.selectPreferredMicrophone(from: identities, systemDefaultUID: snapshot.defaultCoreAudioUID)
} else {
@@ -1108,6 +1118,41 @@ struct MeetingTranscriptionView: View {
}
}
+ // Restore updates future setup only; a running meeting and an open editing sheet
+ // keep their draft until the existing activity/dismissal events reach a safe point.
+ private var canRefreshSetupAfterBackupRestore: Bool {
+ self.coordinator.isQuiescent && !self.isStarting && !self.isStopping &&
+ !self.isRetrying && !self.isRefreshingSources && !self.isShowingMeetingSettings
+ }
+
+ private func applyPendingBackupSetupRefresh() {
+ guard self.pendingBackupSetupRefresh, self.canRefreshSetupAfterBackupRestore else { return }
+ self.pendingBackupSetupRefresh = false
+ var restoredDraft = MeetingTranscriptionSetupDraft(settings: .shared)
+ if self.setupDraft.titleWasEdited {
+ restoredDraft.title = self.setupDraft.title
+ restoredDraft.titleWasEdited = true
+ }
+ self.setupDraft = restoredDraft
+ self.selectPreferredMicrophone(
+ from: self.microphones.map(\.identity),
+ systemDefaultUID: self.cachedSystemDefaultMicrophoneUID
+ )
+ self.selectPreferredApplication(from: self.applications.map(\.identity))
+ self.regenerateDefaultTitleIfNeeded()
+ self.setupDraftBeforeEditing = self.setupDraft
+ self.draftMeetingAudioRetentionPolicy = SettingsStore.shared.meetingAudioRetentionPolicy
+ }
+
+ private func finishRestoredMeetingSettingsIfPending() -> Bool {
+ guard self.pendingBackupSetupRefresh else { return false }
+ // A backup imported in another window supersedes this older sheet. Closing
+ // it must not write its stale language/mode over the restored preferences.
+ self.isShowingMeetingSettings = false
+ self.applyPendingBackupSetupRefresh()
+ return true
+ }
+
private func openMeetingSettings() {
self.setupDraft.autoDetectEnabled = SettingsStore.shared.meetingAutoDetectEnabled
self.setupDraft.browserDetectionEnabled = SettingsStore.shared.meetingAutoDetectBrowserEnabled
@@ -1127,6 +1172,7 @@ struct MeetingTranscriptionView: View {
}
private func cancelMeetingSettings() {
+ if self.finishRestoredMeetingSettingsIfPending() { return }
self.setupDraft = self.setupDraftBeforeEditing
self.draftMeetingAudioRetentionPolicy = SettingsStore.shared.meetingAudioRetentionPolicy
self.isShowingMeetingSettings = false
@@ -1134,6 +1180,7 @@ struct MeetingTranscriptionView: View {
}
private func saveMeetingSettings() {
+ if self.finishRestoredMeetingSettingsIfPending() { return }
guard let microphone = self.microphones.first(where: { $0.id == self.setupDraft.selectedMicrophoneID }) else {
self.actionErrorMessage = "Choose an available microphone before saving."
return
diff --git a/Sources/Fluid/UI/TranscriptionHistoryView.swift b/Sources/Fluid/UI/TranscriptionHistoryView.swift
index 4bcbc970..2858fd70 100644
--- a/Sources/Fluid/UI/TranscriptionHistoryView.swift
+++ b/Sources/Fluid/UI/TranscriptionHistoryView.swift
@@ -2,6 +2,20 @@ import AppKit
import SwiftUI
import UniformTypeIdentifiers
+/// A hidden existing row can be selected from sidebar search even when the list is empty.
+nonisolated enum HistorySelectionRevealPolicy {
+ static func needsFilterReset(
+ requestedID: UUID?,
+ selectedID: UUID?,
+ allEntries: [TranscriptionHistoryEntry],
+ visibleEntries: [TranscriptionHistoryEntry]
+ ) -> Bool {
+ guard let selectedID, requestedID == selectedID else { return false }
+ return !visibleEntries.contains { $0.id == selectedID }
+ && allEntries.contains { $0.id == selectedID }
+ }
+}
+
struct TranscriptionHistoryView: View {
@ObservedObject private var historyStore = TranscriptionHistoryStore.shared
@ObservedObject private var settings = SettingsStore.shared
@@ -104,7 +118,10 @@ struct TranscriptionHistoryView: View {
.frame(minWidth: 400)
}
}
- .onChange(of: self.filteredEntries.map(\.id), initial: true) { _, visibleIDs in
+ .onChange(of: self.historyStore.searchSelectionRequest) { _, _ in
+ self.revealExternalSelection()
+ }
+ .onChange(of: self.filteredEntries.map(\.id)) { _, visibleIDs in
if let selectedEntryID = self.selectedEntryID, visibleIDs.contains(selectedEntryID) { return }
self.selectedEntryID = visibleIDs.first
}
@@ -119,6 +136,7 @@ struct TranscriptionHistoryView: View {
}
.onAppear {
self.audioAvailabilityRevision = UUID()
+ self.revealExternalSelection()
if self.selectedEntryID == nil {
self.selectedEntryID = self.filteredEntries.first?.id
}
@@ -212,19 +230,28 @@ struct TranscriptionHistoryView: View {
}
}
- /// Scrolls to a row chosen elsewhere (the sidebar search). A local filter that
- /// hides it is cleared first, or the selection would fall back to the first row.
+ /// Parent-level handling also runs when no list exists to observe the selection.
+ private func revealExternalSelection() {
+ guard let request = self.historyStore.searchSelectionRequest else { return }
+ defer { self.historyStore.consumeSearchSelectionRequest(request) }
+ guard HistorySelectionRevealPolicy.needsFilterReset(
+ requestedID: request.entryID,
+ selectedID: self.selectedEntryID,
+ allEntries: self.historyStore.entries,
+ visibleEntries: self.filteredEntries
+ ) else { return }
+ self.searchQuery = ""
+ self.starredOnly = false
+ }
+
+ /// The parent clears a hidden selection's filters; scroll after that view update.
private func reveal(_ id: UUID?, with proxy: ScrollViewProxy) {
guard let id else { return }
if !self.filteredEntries.contains(where: { $0.id == id }) {
- self.searchQuery = ""
- self.starredOnly = false
- DispatchQueue.main.async {
- proxy.scrollTo(id)
- }
- return
+ DispatchQueue.main.async { proxy.scrollTo(id) }
+ } else {
+ proxy.scrollTo(id)
}
- proxy.scrollTo(id)
}
private func entryRow(_ entry: TranscriptionHistoryEntry) -> some View {
diff --git a/Sources/Fluid/UI/WelcomeView.swift b/Sources/Fluid/UI/WelcomeView.swift
index 0c706714..60808aa5 100644
--- a/Sources/Fluid/UI/WelcomeView.swift
+++ b/Sources/Fluid/UI/WelcomeView.swift
@@ -3,6 +3,28 @@ import AVFoundation
import Combine
import SwiftUI
+/// Presentation only: preserve the user's selected model and the language catalog's order.
+enum OnboardingModelRecommendation {
+ static func defaultRoutes(forLanguageID languageID: String, from availableRoutes: [VoiceEngineLanguageRoute]) -> [VoiceEngineLanguageRoute] {
+ guard let first = availableRoutes.first else { return [] }
+ guard languageID == "en" else { return [first] }
+ if let english = availableRoutes.first(where: { $0.model == .parakeetTDTv2 }),
+ let mini = availableRoutes.first(where: { $0.model == .fluidParakeetMini })
+ {
+ return [english, mini]
+ }
+ // Mini has the same architecture gate and a newer OS gate. Keep the
+ // established cards when either preferred model is unavailable.
+ var routes = [first]
+ if let builtIn = availableRoutes.first(where: { $0.model == .appleSpeech || $0.model == .appleSpeechAnalyzer }),
+ builtIn.id != first.id
+ {
+ routes.append(builtIn)
+ }
+ return routes
+ }
+}
+
struct WelcomeView: View {
@EnvironmentObject var appServices: AppServices
@Binding var selectedSidebarItem: SidebarItem?
@@ -38,6 +60,7 @@ struct OnboardingFlowView: View {
}
@ObservedObject private var settings = SettingsStore.shared
+ @ObservedObject private var installations = SpeechModelInstallationSnapshot.shared
@StateObject private var aiSetup = OnboardingAISetupController.live
@Binding var currentStep: Int
@@ -93,6 +116,7 @@ struct OnboardingFlowView: View {
case primary
case secondary
case destructive
+ case update
}
private struct OnboardingPillButtonConfiguration {
@@ -205,36 +229,11 @@ struct OnboardingFlowView: View {
return self.selectedLanguageRoutes.first
}
- private var primaryDisplayedModelRoute: VoiceEngineLanguageRoute? {
- self.selectedLanguageRoutes.first
- }
-
private var defaultDisplayedModelRoutes: [VoiceEngineLanguageRoute] {
- var routes: [VoiceEngineLanguageRoute] = []
- if let primaryDisplayedModelRoute {
- routes.append(primaryDisplayedModelRoute)
- }
- if let builtInRoute = self.defaultBuiltInModelRoute,
- !routes.contains(where: { $0.id == builtInRoute.id })
- {
- routes.append(builtInRoute)
- }
- return routes
- }
-
- private var defaultBuiltInModelRoute: VoiceEngineLanguageRoute? {
- guard self.selectedOnboardingLanguage.id == "en" else {
- return nil
- }
-
- return self.selectedLanguageRoutes.first { route in
- switch route.model {
- case .appleSpeech, .appleSpeechAnalyzer:
- return true
- default:
- return false
- }
- }
+ OnboardingModelRecommendation.defaultRoutes(
+ forLanguageID: self.selectedOnboardingLanguage.id,
+ from: self.selectedLanguageRoutes
+ )
}
private var otherModelRoutes: [VoiceEngineLanguageRoute] {
@@ -275,6 +274,7 @@ struct OnboardingFlowView: View {
}
return self.preparingModelRouteID != nil
|| self.asr.hasActiveModelPreparation
+ || self.asr.hasActiveModelDownload
|| self.asr.isCancellingModelPreparation
|| self.asr.isDownloadingModel
|| (self.asr.isLoadingModel && !self.asr.isAsrReady)
@@ -356,6 +356,13 @@ struct OnboardingFlowView: View {
FluidOnboardingWindowTransparency()
}
.onAppear {
+ self.installations.refresh()
+ Task {
+ let catalog = CompactSpeechModelReleaseCatalog.shared
+ let revision = catalog.revision
+ await catalog.refreshIfNeeded()
+ if catalog.revision != revision { self.installations.refresh() }
+ }
self.isOnboardingFlowVisible = true
self.syncOnboardingSelectionFromSettings()
self.playLandingWelcomeSoundIfNeeded()
@@ -1426,7 +1433,7 @@ struct OnboardingFlowView: View {
}
private func isOnboardingModelBundledOrInstalled(_ model: SettingsStore.SpeechModel) -> Bool {
- model.isInstalled
+ self.installations.isInstalled(modelID: model.id)
}
private func isPreparingOnboardingModel(_ model: SettingsStore.SpeechModel) -> Bool {
@@ -1447,7 +1454,7 @@ struct OnboardingFlowView: View {
}
private func prepareOnboardingRoute(_ route: VoiceEngineLanguageRoute) {
- guard !self.asr.isRunning, !self.isModelPreparationInProgress, self.uninstallingModelRouteID == nil else { return }
+ guard self.installations.canUseModelActions, !self.asr.isRunning, !self.isModelPreparationInProgress, self.uninstallingModelRouteID == nil else { return }
self.modelPreparationTask?.cancel()
self.preparingModelRouteID = route.id
@@ -1479,11 +1486,15 @@ struct OnboardingFlowView: View {
private func cancelOnboardingModelPreparation() {
self.modelPreparationTask?.cancel()
- self.asr.cancelModelPreparation()
+ if self.asr.hasActiveModelDownload {
+ self.asr.cancelModelDownload()
+ } else {
+ self.asr.cancelModelPreparation()
+ }
}
private func uninstallOnboardingRoute(_ route: VoiceEngineLanguageRoute) {
- guard !self.asr.isRunning, !self.isModelPreparationInProgress, self.uninstallingModelRouteID == nil else { return }
+ guard self.installations.canUseModelActions, !self.asr.isRunning, !self.isModelPreparationInProgress, self.uninstallingModelRouteID == nil else { return }
self.uninstallingModelRouteID = route.id
@@ -1509,22 +1520,26 @@ struct OnboardingFlowView: View {
enablesHover: Bool = true
) -> some View {
let model = route.model
+ let isCompactModel = model == .fluidParakeetMini || model == .fluidParakeetPico
let isSelected = self.isOnboardingRouteSelected(route)
let isHovered = enablesHover && self.hoveredModelRouteID == route.id
let isRouteActiveInSettings = self.isRouteSelectedInSettings(route)
let isDownloaded = self.isOnboardingModelBundledOrInstalled(model) || (isRouteActiveInSettings && (self.asr.isAsrReady || self.asr.modelsExistOnDisk))
- let isPreparing = self.preparingModelRouteID == route.id || (isRouteActiveInSettings && (self.asr.isDownloadingModel || (self.asr.isLoadingModel && !self.asr.isAsrReady)))
+ let isPreparing = self.preparingModelRouteID == route.id || self.asr.downloadingModelId == model.id || (isRouteActiveInSettings && (self.asr.isDownloadingModel || (self.asr.isLoadingModel && !self.asr.isAsrReady)))
let isReady = self.isOnboardingRouteReady(route)
let isUninstalling = self.uninstallingModelRouteID == route.id
- let areModelActionsBlocked = self.asr.isRunning || self.uninstallingModelRouteID != nil || self.preparingModelRouteID != nil || isPreparing || self.isModelPreparationInProgress
+ let areModelActionsBlocked = !self.installations.canUseModelActions || self.asr.isRunning || self.uninstallingModelRouteID != nil || self.preparingModelRouteID != nil || isPreparing || self.isModelPreparationInProgress
let isBuiltInAppleModel = model == .appleSpeech || model == .appleSpeechAnalyzer
let shape = RoundedRectangle(cornerRadius: 14, style: .continuous)
let cardFill = isHovered
? Color(red: 0.042, green: 0.052, blue: 0.074)
: Color(red: 0.030, green: 0.038, blue: 0.056)
- return VStack(alignment: .leading, spacing: 10) {
+ return VStack(alignment: .leading, spacing: isCompactModel ? self.theme.metrics.spacing.sm : 10) {
HStack(alignment: .top, spacing: 10) {
+ if model.brandName == "FluidVoice" {
+ FluidVoiceBrandIcon(size: 22)
+ }
Text(self.onboardingModelTitle(for: model))
.font(self.theme.typography.sectionTitle)
.foregroundStyle(.white)
@@ -1546,9 +1561,17 @@ struct OnboardingFlowView: View {
}
.frame(height: 38, alignment: .top)
+ if isCompactModel {
+ Text(model.languageSupport)
+ .font(self.theme.typography.bodySmallStrong)
+ .foregroundStyle(Color.white.opacity(0.62))
+ }
+
self.onboardingModelMetadataRow(badgeText: route.badgeText)
- self.onboardingModelFeaturePanel(for: model)
+ if model.hasPerformanceRatings {
+ self.onboardingModelFeaturePanel(for: model)
+ }
Spacer(minLength: 0)
@@ -1567,7 +1590,7 @@ struct OnboardingFlowView: View {
Spacer()
- Text(model.downloadSize)
+ Text(self.installations.latestDescriptors[model.id]?.downloadSize ?? model.downloadSize)
.font(self.theme.typography.bodySmallStrong)
.foregroundStyle(.white)
.lineLimit(1)
@@ -1581,11 +1604,11 @@ struct OnboardingFlowView: View {
if isPreparing {
self.onboardingModelActionButton(
id: "\(route.id)-cancel",
- title: self.asr.isCancellingModelPreparation ? "Cancelling…" : "Cancel",
+ title: self.asr.isCancellingModelPreparation || self.asr.isCancellingModelDownload ? "Cancelling…" : "Cancel",
systemImage: "xmark",
tone: .secondary,
width: 104,
- isDisabled: self.asr.isCancellingModelPreparation
+ isDisabled: self.asr.isCancellingModelPreparation || self.asr.isCancellingModelDownload
) {
self.cancelOnboardingModelPreparation()
}
@@ -1603,29 +1626,51 @@ struct OnboardingFlowView: View {
) {
self.prepareOnboardingRoute(route)
}
+ } else if !self.installations.canUseModelActions {
+ if self.installations.isChecking {
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.small)
+ Text("Checking downloads…").font(self.theme.typography.bodySmall)
+ }
+ } else {
+ self.onboardingModelActionButton(
+ id: "\(route.id)-retry-check",
+ title: "Retry check",
+ systemImage: "arrow.clockwise",
+ tone: .primary,
+ width: nil,
+ isDisabled: false
+ ) { self.installations.refresh() }
+ }
} else if isDownloaded {
+ let hasUpdate = self.installations.updateAvailableIDs.contains(model.id)
HStack(spacing: 8) {
+ if hasUpdate {
+ self.onboardingModelActionButton(
+ id: "\(route.id)-update",
+ title: "Update",
+ systemImage: "arrow.down.circle",
+ tone: .update,
+ width: 84,
+ isDisabled: areModelActionsBlocked
+ ) { self.updateOnboardingRoute(route) }
+ }
self.onboardingModelActionButton(
id: "\(route.id)-activate",
- title: self.onboardingModelActionButtonTitle(isPreparing: false, isDownloaded: true, isReady: isReady),
+ title: hasUpdate && isReady ? "Active" : self.onboardingModelActionButtonTitle(isPreparing: false, isDownloaded: true, isReady: isReady),
systemImage: isReady ? "checkmark" : "bolt.fill",
- tone: .primary,
- width: 124,
+ tone: hasUpdate ? .secondary : .primary,
+ width: hasUpdate ? 88 : 124,
isDisabled: areModelActionsBlocked || isReady
- ) {
- self.prepareOnboardingRoute(route)
- }
-
+ ) { self.prepareOnboardingRoute(route) }
self.onboardingModelActionButton(
id: "\(route.id)-uninstall",
title: "Delete",
systemImage: "trash",
tone: .destructive,
- width: 124,
+ width: hasUpdate ? 72 : 124,
isDisabled: areModelActionsBlocked
- ) {
- self.uninstallOnboardingRoute(route)
- }
+ ) { self.uninstallOnboardingRoute(route) }
}
} else {
self.onboardingModelActionButton(
@@ -1664,7 +1709,7 @@ struct OnboardingFlowView: View {
}
}
.onTapGesture {
- guard !areModelActionsBlocked else { return }
+ guard !areModelActionsBlocked, !self.isModelPreparationInProgress else { return }
self.selectOnboardingRoute(route)
}
.onHover { isHovered in
@@ -1692,13 +1737,14 @@ struct OnboardingFlowView: View {
)
}
.padding(.vertical, 2)
+ .help("Relative ratings for comparing models, not measured transcription accuracy.")
.accessibilityElement(children: .combine)
.accessibilityLabel("Speed \(Int(model.speedPercent * 100)) percent. Accuracy \(Int(model.accuracyPercent * 100)) percent.")
}
private func onboardingModelPreparationStatus(isUninstalling: Bool) -> some View {
VStack(alignment: .leading, spacing: 7) {
- if self.asr.isCancellingModelPreparation {
+ if self.asr.isCancellingModelPreparation || self.asr.isCancellingModelDownload {
HStack(spacing: 8) {
ProgressView()
.controlSize(.small)
@@ -1708,7 +1754,7 @@ struct OnboardingFlowView: View {
.font(self.theme.typography.captionStrong)
.foregroundStyle(Color.white.opacity(0.62))
}
- } else if self.asr.isDownloadingModel,
+ } else if self.asr.isDownloadingModel || self.asr.hasActiveModelDownload,
self.asr.modelPreparationPhase == .downloading,
let progress = self.asr.downloadProgress
{
@@ -1857,11 +1903,15 @@ struct OnboardingFlowView: View {
onHover: @escaping (Bool) -> Void
) -> some View {
let shape = Capsule()
- let accentColor: Color = configuration.tone == .destructive ? .red : FluidOnboardingLandingColors.blue
- let isFilledTone = configuration.tone == .primary || configuration.tone == .destructive
+ let accentColor: Color = switch configuration.tone {
+ case .destructive: .red
+ case .update: .orange
+ default: FluidOnboardingLandingColors.blue
+ }
+ let isFilledTone = configuration.tone != .secondary
let fillColor: Color = {
switch configuration.tone {
- case .primary, .destructive:
+ case .primary, .destructive, .update:
return accentColor.opacity(configuration.isEnabled ? 1 : 0.34)
case .secondary:
return Color.white.opacity(configuration.isEnabled ? (configuration.isHovered ? 0.11 : 0.07) : 0.045)
@@ -1869,7 +1919,7 @@ struct OnboardingFlowView: View {
}()
let borderColor: Color = {
switch configuration.tone {
- case .primary, .destructive:
+ case .primary, .destructive, .update:
return Color.white.opacity(configuration.isHovered && configuration.isEnabled ? 0.30 : 0)
case .secondary:
return configuration.isHovered && configuration.isEnabled ? FluidOnboardingLandingColors.blue.opacity(0.30) : Color.white.opacity(0.07)
@@ -1879,7 +1929,7 @@ struct OnboardingFlowView: View {
let shadowOpacity: Double = {
guard configuration.isEnabled else { return 0 }
switch configuration.tone {
- case .primary, .destructive:
+ case .primary, .destructive, .update:
return configuration.isHovered ? 0.56 : 0.26
case .secondary:
return configuration.isHovered ? 0.08 : 0
@@ -1934,7 +1984,9 @@ struct OnboardingFlowView: View {
private func onboardingModelTooltip(for route: VoiceEngineLanguageRoute) -> String {
let model = route.model
- return "\(self.onboardingModelSubtitle(for: model)) - \(model.downloadSize)\n\(model.cardDescription)"
+ let downloadSize = self.installations.latestDescriptors[model.id]?.downloadSize ?? model.downloadSize
+ let credit = model.parakeetDescriptor.map { "\n\($0.creditLine)" } ?? ""
+ return "\(self.onboardingModelSubtitle(for: model)) - \(downloadSize)\n\(model.cardDescription)\(credit)"
}
private func onboardingModelTitle(for model: SettingsStore.SpeechModel) -> String {
@@ -1947,6 +1999,8 @@ struct OnboardingFlowView: View {
return "Parakeet v3"
case .parakeetTDTv2:
return "Parakeet v2"
+ case .fluidParakeetMini, .fluidParakeetPico:
+ return model.displayName
case .parakeetRealtime:
return "Parakeet Flash"
case .cohereTranscribeSixBit:
@@ -2212,6 +2266,30 @@ struct OnboardingFlowView: View {
}
private extension OnboardingFlowView {
+ func updateOnboardingRoute(_ route: VoiceEngineLanguageRoute) {
+ guard self.installations.canUseModelActions, !self.asr.isRunning,
+ self.asr.activeExclusiveActivity == nil, !self.isModelPreparationInProgress,
+ self.uninstallingModelRouteID == nil
+ else { return }
+ self.preparingModelRouteID = route.id
+ self.modelPreparationTask = Task { @MainActor in
+ defer { self.preparingModelRouteID = nil; self.modelPreparationTask = nil }
+ do {
+ try await self.asr.downloadModel(route.model, source: .onboarding, updateWeights: true, progressHandler: nil)
+ } catch is CancellationError {
+ // The retained installation remains available.
+ } catch {
+ if let failure = error as? ParakeetArchiveDownloader.DownloadError, case .replacementCleanupFailed = failure {
+ self.asr.errorTitle = "Model Updated"
+ } else {
+ self.asr.errorTitle = "Model Update Failed"
+ }
+ self.asr.errorMessage = error.localizedDescription
+ self.asr.showError = true
+ }
+ }
+ }
+
var aiEnhancementStep: some View {
OnboardingAIEnhancementStepView(
setup: self.aiSetup,
diff --git a/Tests/FluidDictationIntegrationTests/AppSearchServiceTests.swift b/Tests/FluidDictationIntegrationTests/AppSearchServiceTests.swift
index 6b6f392a..0a152fdf 100644
--- a/Tests/FluidDictationIntegrationTests/AppSearchServiceTests.swift
+++ b/Tests/FluidDictationIntegrationTests/AppSearchServiceTests.swift
@@ -1,5 +1,7 @@
+import AppKit
@testable import FluidVoice_Debug
import Foundation
+import SwiftUI
import XCTest
/// The query side of the sidebar search.
@@ -60,7 +62,7 @@ final class AppSearchServiceTests: XCTestCase {
service.query = "launch at startup"
service.query = "accent color"
- try await Task.sleep(for: .milliseconds(600))
+ try await self.waitUntil { !service.isSearching && !service.groups.isEmpty }
let settings = try XCTUnwrap(service.groups.first { $0.kind == .settings })
XCTAssertTrue(settings.hits.contains { $0.target == .settings(.accentColor) })
@@ -77,7 +79,7 @@ final class AppSearchServiceTests: XCTestCase {
let service = AppSearchService(index: SearchIndex(root: FluidZeppelinRoot(root: root)))
service.query = "launch at startup"
- try await Task.sleep(for: .milliseconds(600))
+ try await self.waitUntil { !service.isSearching && !service.groups.isEmpty }
XCTAssertFalse(service.groups.isEmpty)
service.query = "accent color"
@@ -85,6 +87,341 @@ final class AppSearchServiceTests: XCTestCase {
XCTAssertTrue(service.groups.isEmpty)
}
+ private func waitUntil(_ condition: () async -> Bool) async throws {
+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))
+ while !(await condition()), ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ guard await condition() else {
+ XCTFail("A bounded app-search condition did not complete")
+ throw AppSearchPreparationGate.Failure.unavailable
+ }
+ }
+
+ private static func queryGroup(_ query: String) -> [AppSearchGroup] {
+ [AppSearchGroup(kind: .settings, hits: [AppSearchHit(
+ kind: .settings,
+ target: .settings(query == "old" ? .launchAtStartup : .accentColor),
+ title: query,
+ snippet: "",
+ date: nil
+ )])]
+ }
+
+ func testFirstQueryWaitsForPreparationAndShowsPendingState() async throws {
+ let gate = AppSearchPreparationGate()
+ var queried: [String] = []
+ let service = AppSearchService(prepareIndex: { try await gate.wait() }, performSearch: { query in
+ queried.append(query)
+ return Self.queryGroup(query)
+ })
+ service.query = "old"
+ do {
+ try await self.waitUntil { await gate.hasStarted() }
+ XCTAssertTrue(service.isSearching)
+ XCTAssertTrue(service.groups.isEmpty)
+ XCTAssertNil(service.searchError)
+ XCTAssertTrue(queried.isEmpty, "A lexical query cannot run before authoritative snapshots are ready")
+ await gate.release()
+ try await self.waitUntil { !service.isSearching }
+ XCTAssertEqual(queried, ["old"])
+ XCTAssertEqual(service.groups, Self.queryGroup("old"))
+ XCTAssertNil(service.searchError)
+ } catch {
+ service.query = ""
+ await gate.release()
+ throw error
+ }
+ service.query = ""
+ }
+
+ func testFailedPreparationShowsRetryableErrorAndDoesNotRunTheQuery() async throws {
+ let gate = AppSearchPreparationGate()
+ var queried: [String] = []
+ let service = AppSearchService(prepareIndex: { try await gate.wait() }, performSearch: { query in
+ queried.append(query)
+ return Self.queryGroup(query)
+ })
+ service.query = "new"
+ do {
+ try await self.waitUntil { await gate.hasStarted() }
+ await gate.release(failing: true)
+ try await self.waitUntil { !service.isSearching }
+ XCTAssertTrue(service.groups.isEmpty)
+ XCTAssertNotNil(service.searchError)
+ XCTAssertTrue(queried.isEmpty)
+ await gate.release(failing: false)
+ service.refresh()
+ XCTAssertTrue(service.isSearching)
+ XCTAssertNil(service.searchError)
+ try await self.waitUntil { !service.isSearching }
+ XCTAssertEqual(queried, ["new"])
+ XCTAssertEqual(service.groups, Self.queryGroup("new"))
+ XCTAssertNil(service.searchError)
+ } catch {
+ service.query = ""
+ await gate.release()
+ throw error
+ }
+ service.query = ""
+ }
+
+ func testOnlyExplicitRetryReloadsFailedPreparationAndStoppedRetryDoesNothing() async throws {
+ let center = NotificationCenter()
+ var preparationCalls = 0
+ var retryCalls = 0
+ var canPrepare = false
+ var queried: [String] = []
+ let service = AppSearchService(
+ prepareIndex: {
+ preparationCalls += 1
+ if !canPrepare { throw AppSearchPreparationGate.Failure.unavailable }
+ },
+ retryPreparation: {
+ retryCalls += 1
+ canPrepare = true
+ },
+ performSearch: { query in
+ queried.append(query)
+ return Self.queryGroup(query)
+ },
+ notificationCenter: center
+ )
+ defer { service.stop() }
+ service.query = "old"
+ try await self.waitUntil { !service.isSearching }
+ XCTAssertNotNil(service.searchError)
+ service.query = "new"
+ try await self.waitUntil { !service.isSearching }
+ service.refresh()
+ try await self.waitUntil { !service.isSearching }
+ center.post(name: .parakeetVocabularyDidChange, object: nil)
+ await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
+ DispatchQueue.main.async { continuation.resume() }
+ }
+ try await self.waitUntil { !service.isSearching }
+ XCTAssertEqual(preparationCalls, 4)
+ XCTAssertEqual(retryCalls, 0, "Typing, refresh, and cache invalidation must not reload source history")
+ XCTAssertNotNil(service.searchError)
+ XCTAssertTrue(queried.isEmpty)
+
+ service.retry()
+ XCTAssertEqual(retryCalls, 1)
+ XCTAssertTrue(service.isSearching)
+ XCTAssertNil(service.searchError)
+ try await self.waitUntil { !service.isSearching }
+ XCTAssertEqual(service.groups, Self.queryGroup("new"))
+ XCTAssertEqual(queried, ["new"])
+ XCTAssertEqual(preparationCalls, 5)
+ XCTAssertNil(service.searchError)
+
+ service.stop()
+ service.retry()
+ service.query = "after stop"
+ service.refresh()
+ center.post(name: .parakeetVocabularyDidChange, object: nil)
+ try await Task.sleep(for: .milliseconds(120))
+ XCTAssertEqual(retryCalls, 1)
+ XCTAssertEqual(preparationCalls, 5)
+ XCTAssertEqual(queried, ["new"])
+ XCTAssertTrue(service.groups.isEmpty)
+ XCTAssertFalse(service.isSearching)
+ XCTAssertNil(service.searchError)
+ }
+
+ func testOlderInFlightQueryCannotReplaceNewerResultsWhenItCompletesLate() async throws {
+ let gate = AppSearchQueryGate(blockedQueries: ["old"])
+ let service = AppSearchService(performSearch: { query in
+ await gate.run(query)
+ return Self.queryGroup(query)
+ })
+ service.query = "old"
+ do {
+ try await self.waitUntil { await gate.calls().contains("old") }
+ service.query = "new"
+ try await self.waitUntil { !service.isSearching && service.groups == Self.queryGroup("new") }
+ await gate.release("old")
+ try await self.waitUntil { await gate.finished().contains("old") }
+ // The completion is delivered through the real schedule task; give
+ // that main-actor continuation a turn before checking non-effects.
+ await Task.yield()
+ XCTAssertEqual(service.groups, Self.queryGroup("new"))
+ XCTAssertFalse(service.isSearching)
+ XCTAssertNil(service.searchError)
+ } catch {
+ service.query = ""
+ await gate.release("old")
+ throw error
+ }
+ service.query = ""
+ }
+
+ func testClearingQueryWhileSearchIsInFlightCannotRepublishLateResults() async throws {
+ let gate = AppSearchQueryGate(blockedQueries: ["old"])
+ let service = AppSearchService(performSearch: { query in
+ await gate.run(query)
+ return Self.queryGroup(query)
+ })
+ service.query = "old"
+ do {
+ try await self.waitUntil { await gate.calls().contains("old") }
+ service.query = " "
+ XCTAssertTrue(service.groups.isEmpty)
+ XCTAssertFalse(service.isSearching)
+ XCTAssertNil(service.searchError)
+ await gate.release("old")
+ try await self.waitUntil { await gate.finished().contains("old") }
+ await Task.yield()
+ XCTAssertTrue(service.groups.isEmpty)
+ XCTAssertFalse(service.isSearching)
+ XCTAssertNil(service.searchError)
+ } catch {
+ service.query = ""
+ await gate.release("old")
+ throw error
+ }
+ }
+
+ func testStoppingSearchRejectsLateResultsAndAllLaterQueries() async throws {
+ let gate = AppSearchQueryGate(blockedQueries: ["old"])
+ var preparationCalls = 0
+ let service = AppSearchService(prepareIndex: { preparationCalls += 1 }, performSearch: { query in
+ await gate.run(query)
+ return Self.queryGroup(query)
+ })
+ service.query = "old"
+ do {
+ try await self.waitUntil { await gate.calls().contains("old") }
+ XCTAssertEqual(preparationCalls, 1)
+ service.stop()
+ XCTAssertTrue(service.groups.isEmpty)
+ XCTAssertFalse(service.isSearching)
+ XCTAssertNil(service.searchError)
+ await gate.release("old")
+ try await self.waitUntil { await gate.finished().contains("old") }
+ service.query = "new"
+ service.refresh()
+ let direct = await service.search("direct after stop")
+ XCTAssertTrue(direct.isEmpty)
+ // Beyond the real 80 ms debounce, any incorrectly restarted task
+ // would reach the runner and be visible in this gate's call list.
+ try await Task.sleep(for: .milliseconds(120))
+ let calls = await gate.calls()
+ XCTAssertEqual(calls, ["old"])
+ XCTAssertEqual(preparationCalls, 1)
+ XCTAssertTrue(service.groups.isEmpty)
+ XCTAssertFalse(service.isSearching)
+ XCTAssertNil(service.searchError)
+ } catch {
+ service.stop()
+ await gate.release("old")
+ throw error
+ }
+ }
+
+ private func withVocabularyProbe(failingReads: Set<Int> = [], _ body: (AppSearchService, AppSearchVocabularyProbe, NotificationCenter) async throws -> Void) async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("AppSearchVocabularyTests-\(UUID().uuidString)", isDirectory: true)
+ let database = FluidZeppelinRoot(root: directory)
+ let loader = AppSearchVocabularyProbe(failingReads: failingReads)
+ let center = NotificationCenter()
+ let service = AppSearchService(index: SearchIndex(root: database), readVocabulary: { try await loader.read() }, notificationCenter: center)
+ do {
+ try await body(service, loader, center)
+ } catch {
+ service.stop()
+ await loader.releaseAll()
+ await database.closeAll()
+ try? FileManager.default.removeItem(at: directory)
+ throw error
+ }
+ service.stop()
+ await loader.releaseAll()
+ await database.closeAll()
+ try? FileManager.default.removeItem(at: directory)
+ }
+
+ private static func vocabularyTargets(_ groups: [AppSearchGroup]) -> [AppSearchHit.Target] {
+ groups.first { $0.kind == .vocabulary }?.hits.map(\.target) ?? []
+ }
+
+ func testTransientVocabularyReadFailureRetriesThenCachesSuccessfulLoad() async throws {
+ try await self.withVocabularyProbe(failingReads: [0]) { service, loader, _ in
+ let term = ParakeetVocabularyStore.VocabularyConfig.Term(text: "fvsearchvocabfixture alpha", weight: 2, aliases: ["fvsearchaliasfixture"])
+ await loader.setTerms([term])
+ let failed = await service.search("fvsearchvocabfixture")
+ XCTAssertTrue(Self.vocabularyTargets(failed).isEmpty)
+ let retry = await service.search("fvsearchaliasfixture")
+ XCTAssertEqual(Self.vocabularyTargets(retry), [.vocabulary(term.text)])
+ let cached = await service.search("fvsearchvocabfixture")
+ XCTAssertEqual(Self.vocabularyTargets(cached), [.vocabulary(term.text)])
+ let reads = await loader.readCount()
+ XCTAssertEqual(reads, 2, "Only a successful read may become the reusable immutable snapshot")
+ }
+ }
+
+ func testSuccessfulEmptyVocabularyLoadIsCachedUntilAnActualChange() async throws {
+ try await self.withVocabularyProbe { service, loader, _ in
+ let first = await service.search("fvsearchvocabfixture")
+ XCTAssertTrue(Self.vocabularyTargets(first).isEmpty)
+ await loader.setTerms([.init(text: "fvsearchvocabfixture unpublished", weight: 2)])
+ let cached = await service.search("fvsearchvocabfixture")
+ XCTAssertTrue(Self.vocabularyTargets(cached).isEmpty, "Changing the fixture without an event must not trigger disk rereads")
+ let reads = await loader.readCount()
+ XCTAssertEqual(reads, 1)
+ }
+ }
+
+ func testVocabularyChangeInvalidatesOnlyTheSuccessfulSearchSnapshot() async throws {
+ try await self.withVocabularyProbe { service, loader, center in
+ let first = ParakeetVocabularyStore.VocabularyConfig.Term(text: "fvsearchvocabfixture alpha", weight: 2)
+ let updated = ParakeetVocabularyStore.VocabularyConfig.Term(text: "fvsearchvocabfixture beta", weight: 2)
+ await loader.setTerms([first])
+ service.query = "fvsearchvocabfixture"
+ try await self.waitUntil { !service.isSearching && Self.vocabularyTargets(service.groups) == [.vocabulary(first.text)] }
+ await loader.setTerms([updated])
+ // Private center: global vocabulary events also retire ASR models.
+ // This fixture must never notify those unrelated production consumers.
+ center.post(name: .parakeetVocabularyDidChange, object: nil)
+ try await self.waitUntil { !service.isSearching && Self.vocabularyTargets(service.groups) == [.vocabulary(updated.text)] }
+ service.refresh()
+ try await self.waitUntil { !service.isSearching && Self.vocabularyTargets(service.groups) == [.vocabulary(updated.text)] }
+ let reads = await loader.readCount()
+ XCTAssertEqual(reads, 2, "One real change invalidates the snapshot once; later keystrokes reuse it")
+ }
+ }
+
+ func testLateVocabularyLoadCannotReplaceTheSnapshotFromANewerChange() async throws {
+ try await self.withVocabularyProbe { service, loader, center in
+ let first = ParakeetVocabularyStore.VocabularyConfig.Term(text: "fvsearchvocabfixture stale", weight: 2)
+ let updated = ParakeetVocabularyStore.VocabularyConfig.Term(text: "fvsearchvocabfixture latest", weight: 2)
+ await loader.setTerms([first])
+ await loader.gateRead(0)
+ let old = Task { await service.search("fvsearchvocabfixture") }
+ do {
+ try await self.waitUntil { await loader.readCount() == 1 }
+ await loader.setTerms([updated])
+ center.post(name: .parakeetVocabularyDidChange, object: nil)
+ // The event uses receive(on: .main). This FIFO barrier drains
+ // that delivery without a sleep or a global notification.
+ await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
+ DispatchQueue.main.async { continuation.resume() }
+ }
+ let latest = await service.search("fvsearchvocabfixture")
+ XCTAssertEqual(Self.vocabularyTargets(latest), [.vocabulary(updated.text)])
+ await loader.releaseRead(0)
+ _ = await old.value
+ let cached = await service.search("fvsearchvocabfixture")
+ XCTAssertEqual(Self.vocabularyTargets(cached), [.vocabulary(updated.text)], "The older loader result must not poison the newly cached generation")
+ let reads = await loader.readCount()
+ XCTAssertEqual(reads, 2)
+ } catch {
+ await loader.releaseAll()
+ _ = await old.value
+ throw error
+ }
+ }
+ }
+
func testFileTranscriptRevealIgnoresOtherSearchDestinations() {
let id = UUID()
@@ -127,3 +464,187 @@ final class AppSearchServiceTests: XCTestCase {
XCTAssertTrue(AppSearchService.matches("cafe", ["café"]))
}
}
+
+private actor AppSearchPreparationGate {
+ enum Failure: Error { case unavailable }
+ private var started = false
+ private var released = false
+ private var failing = false
+ private var waiters: [CheckedContinuation<Void, Never>] = []
+
+ func hasStarted() -> Bool { self.started }
+
+ func wait() async throws {
+ self.started = true
+ if !self.released { await withCheckedContinuation { self.waiters.append($0) } }
+ if self.failing { throw Failure.unavailable }
+ }
+
+ func release(failing: Bool = false) {
+ self.failing = failing
+ self.released = true
+ let waiters = self.waiters
+ self.waiters.removeAll()
+ for waiter in waiters {
+ waiter.resume()
+ }
+ }
+}
+
+private actor AppSearchQueryGate {
+ private let blockedQueries: Set<String>
+ private var released: Set<String> = []
+ private var entered: [String] = []
+ private var completed: [String] = []
+ private var waiters: [String: CheckedContinuation<Void, Never>] = [:]
+
+ init(blockedQueries: Set<String>) { self.blockedQueries = blockedQueries }
+ func calls() -> [String] { self.entered }
+ func finished() -> [String] { self.completed }
+
+ func run(_ query: String) async {
+ self.entered.append(query)
+ if self.blockedQueries.contains(query), !self.released.contains(query) {
+ await withCheckedContinuation { self.waiters[query] = $0 }
+ }
+ self.completed.append(query)
+ }
+
+ func release(_ query: String) {
+ self.released.insert(query)
+ self.waiters.removeValue(forKey: query)?.resume()
+ }
+}
+
+private actor AppSearchVocabularyProbe {
+ private var terms: [ParakeetVocabularyStore.VocabularyConfig.Term] = []
+ private var reads = 0
+ private let failingReads: Set<Int>
+ private var gatedReads: Set<Int> = []
+ private var waiters: [Int: CheckedContinuation<Void, Never>] = [:]
+
+ init(failingReads: Set<Int> = []) { self.failingReads = failingReads }
+ func setTerms(_ terms: [ParakeetVocabularyStore.VocabularyConfig.Term]) { self.terms = terms }
+ func readCount() -> Int { self.reads }
+ func gateRead(_ number: Int) { self.gatedReads.insert(number) }
+
+ func read() async throws -> [ParakeetVocabularyStore.VocabularyConfig.Term] {
+ let number = self.reads
+ self.reads += 1
+ let snapshot = self.terms
+ if self.gatedReads.contains(number) { await withCheckedContinuation { self.waiters[number] = $0 } }
+ if self.failingReads.contains(number) { throw AppSearchPreparationGate.Failure.unavailable }
+ return snapshot
+ }
+
+ func releaseRead(_ number: Int) { self.waiters.removeValue(forKey: number)?.resume() }
+ func releaseAll() {
+ self.gatedReads.removeAll()
+ let waiters = self.waiters.values
+ self.waiters.removeAll()
+ for waiter in waiters {
+ waiter.resume()
+ }
+ }
+}
+
+extension AppSearchServiceTests {
+ /// App-hosted rendering proof only. No installed-app interaction, preference
+ /// or history writes, model preparation, global events, or microphone use.
+ func testOptInNativeSearchSidebarStatesAtCompactWidth() async throws {
+ guard let path = ProcessInfo.processInfo.environment["FLUIDVOICE_SEARCH_UI_PROOF"], !path.isEmpty else {
+ throw XCTSkip("Supply an external output directory for the native search sidebar proof")
+ }
+ let output = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL.resolvingSymlinksInPath()
+ let repository = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().resolvingSymlinksInPath()
+ guard output.path != repository.path, !output.path.hasPrefix(repository.path + "/") else {
+ XCTFail("Native proof images must be saved outside the repository")
+ throw CocoaError(.fileWriteNoPermission)
+ }
+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
+ let privateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("SearchUIProof-\(UUID().uuidString)", isDirectory: true)
+ let database = FluidZeppelinRoot(root: privateDirectory)
+ let index = SearchIndex(root: database)
+ let center = NotificationCenter()
+ let gate = AppSearchPreparationGate()
+ let loading = AppSearchService(index: index, prepareIndex: { try await gate.wait() }, performSearch: { _ in [] }, notificationCenter: center)
+ let error = AppSearchService(index: index, prepareIndex: { throw AppSearchPreparationGate.Failure.unavailable }, performSearch: { _ in [] }, notificationCenter: center)
+ let empty = AppSearchService(index: index, performSearch: { _ in [] }, notificationCenter: center)
+ let results = AppSearchService(index: index, performSearch: { _ in Self.nativeProofGroups }, notificationCenter: center)
+ let services = [loading, error, empty, results]
+ do {
+ for service in services {
+ service.query = "meeting"
+ }
+ try await self.waitUntil { await gate.hasStarted() }
+ try await self.waitUntil { !error.isSearching && !empty.isSearching && !results.isSearching }
+ XCTAssertTrue(loading.isSearching)
+ XCTAssertNotNil(error.searchError)
+ XCTAssertTrue(empty.groups.isEmpty)
+ XCTAssertEqual(results.groups, Self.nativeProofGroups)
+ let states = [("searching", loading), ("preparation-error", error), ("empty", empty), ("results", results)]
+ for scheme in [ColorScheme.dark, .light] {
+ let appearance = scheme == .dark ? "dark" : "light"
+ for (name, service) in states {
+ try await self.captureNativeSearchProof(service, scheme: scheme, destination: output.appendingPathComponent("search-\(name)-\(appearance).png"))
+ }
+ }
+ } catch {
+ for service in services {
+ service.stop()
+ }
+ await gate.release()
+ await database.closeAll()
+ try? FileManager.default.removeItem(at: privateDirectory)
+ throw error
+ }
+ for service in services {
+ service.stop()
+ }
+ await gate.release()
+ await database.closeAll()
+ try? FileManager.default.removeItem(at: privateDirectory)
+ print("Native search sidebar proof: \(output.path) (app-hosted fixtures, 260px, dark/light)")
+ }
+
+ private static var nativeProofGroups: [AppSearchGroup] {
+ let histories = (1...8).map { number in
+ let id = UUID(uuid: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, UInt8(number)))
+ return AppSearchHit(kind: .history, target: .history(id), title: "Meeting notes \(number)", snippet: "Reviewed the project update and the next steps for the team.", date: nil)
+ }
+ let settings = AppSearchHit(kind: .settings, target: .settings(.accentColor), title: "Accent color", snippet: "Choose the appearance of FluidVoice.", date: nil)
+ return [AppSearchGroup(kind: .history, hits: histories), AppSearchGroup(kind: .settings, hits: [settings])]
+ }
+
+ private func captureNativeSearchProof(_ service: AppSearchService, scheme: ColorScheme, destination: URL) async throws {
+ let size = NSSize(width: 260, height: 520)
+ let theme = AppTheme.adaptive(accent: FluidBrandColors.blue, colorScheme: scheme)
+ let content = AppSearchResultsView(service: service, cursor: .constant(nil), expanded: .constant([]), open: { _ in })
+ .frame(width: size.width, height: size.height)
+ .appTheme(theme)
+ .environment(\.colorScheme, scheme)
+ let host = NSHostingView(rootView: content)
+ host.frame = NSRect(origin: .zero, size: size)
+ let window = NSWindow(contentRect: host.frame, styleMask: [.titled], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.appearance = NSAppearance(named: scheme == .dark ? .darkAqua : .aqua)
+ window.title = "Search sidebar proof"
+ window.contentView = host
+ window.orderFront(nil)
+ defer {
+ window.orderOut(nil)
+ window.contentView = nil
+ window.close()
+ }
+ host.layoutSubtreeIfNeeded()
+ try await Task.sleep(for: .milliseconds(160))
+ host.layoutSubtreeIfNeeded()
+ host.displayIfNeeded()
+ let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
+ host.cacheDisplay(in: host.bounds, to: bitmap)
+ let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ XCTAssertEqual(host.bounds.width, 260)
+ XCTAssertGreaterThan(png.count, 100)
+ try png.write(to: destination)
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/CompactSpeechModelArchiveTransportTests.swift b/Tests/FluidDictationIntegrationTests/CompactSpeechModelArchiveTransportTests.swift
new file mode 100644
index 00000000..a825daa0
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/CompactSpeechModelArchiveTransportTests.swift
@@ -0,0 +1,368 @@
+import CryptoKit
+import Darwin
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+final nonisolated class CompactSpeechModelArchiveTransportTests: XCTestCase {
+ func testRangesAssembleOwnedArchiveAndPreserveSiblings() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let recorder = Recorder()
+ let (ready, response) = try await fixture.download { request, maximum, progress in
+ recorder.add(request.value(forHTTPHeaderField: "Range") ?? "")
+ XCTAssertEqual(request.value(forHTTPHeaderField: "Accept-Encoding"), "identity")
+ XCTAssertLessThanOrEqual(maximum, 4)
+ return try fixture.chunk(request, progress: progress)
+ }
+ defer { try? FileManager.default.removeItem(at: ready) }
+ XCTAssertEqual(recorder.values, ["bytes=0-3", "bytes=4-7", "bytes=8-9"])
+ XCTAssertEqual(try Data(contentsOf: ready), fixture.payload)
+ XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 200)
+ XCTAssertEqual(response.expectedContentLength, 10)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.partial.path))
+ XCTAssertEqual(try String(contentsOf: fixture.marker, encoding: .utf8), fixture.descriptor.archiveSHA256)
+ try fixture.assertSiblings()
+ }
+
+ func testFailureResumesOnlyCompleteRanges() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ do {
+ _ = try await fixture.download { request, _, progress in
+ if request.value(forHTTPHeaderField: "Range") == "bytes=4-7" { throw ProbeFailure.injected }
+ return try fixture.chunk(request, progress: progress)
+ }
+ XCTFail("Expected interrupted transfer")
+ } catch { XCTAssertTrue(error is ProbeFailure) }
+ XCTAssertEqual(try Data(contentsOf: fixture.partial), fixture.payload.prefix(4))
+ let recorder = Recorder()
+ let (ready, _) = try await fixture.download { request, _, progress in
+ recorder.add(request.value(forHTTPHeaderField: "Range") ?? "")
+ return try fixture.chunk(request, progress: progress)
+ }
+ defer { try? FileManager.default.removeItem(at: ready) }
+ XCTAssertEqual(recorder.values, ["bytes=4-7", "bytes=8-9"])
+ XCTAssertEqual(try Data(contentsOf: ready), fixture.payload)
+ try fixture.assertSiblings()
+ }
+
+ func testCancellationJoinsTransportAndPreservesCompletedRange() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let (started, continuation) = AsyncStream<Void>.makeStream()
+ let cleanup = Recorder()
+ let task = Task {
+ try await fixture.download { request, _, progress in
+ if request.value(forHTTPHeaderField: "Range") == "bytes=4-7" {
+ let (chunk, _) = try fixture.chunk(request, progress: progress)
+ continuation.yield(())
+ continuation.finish()
+ do { try await Task.sleep(for: .seconds(60)) } catch {
+ try FileManager.default.removeItem(at: chunk)
+ cleanup.add("joined")
+ throw error
+ }
+ throw ProbeFailure.injected
+ }
+ return try fixture.chunk(request, progress: progress)
+ }
+ }
+ for await _ in started {
+ break
+ }
+ task.cancel()
+ do { _ = try await task.value; XCTFail("Expected cancellation") } catch { XCTAssertTrue(error is CancellationError) }
+ XCTAssertEqual(cleanup.values, ["joined"])
+ XCTAssertEqual(try Data(contentsOf: fixture.partial), fixture.payload.prefix(4))
+ XCTAssertFalse(try FileManager.default.contentsOfDirectory(atPath: fixture.base.path).contains { $0.hasPrefix("chunk-") })
+ try fixture.assertSiblings()
+ }
+
+ func testCanceledReturnedChunkIsDeletedWithoutAppendingIt() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ do {
+ _ = try await fixture.download { request, _, progress in
+ let result = try fixture.chunk(request, progress: progress)
+ withUnsafeCurrentTask { $0?.cancel() }
+ return result
+ }
+ XCTFail("Expected cancellation")
+ } catch { XCTAssertTrue(error is CancellationError) }
+ XCTAssertEqual(try Data(contentsOf: fixture.partial).count, 0)
+ XCTAssertFalse(try FileManager.default.contentsOfDirectory(atPath: fixture.base.path).contains { $0.hasPrefix("chunk-") })
+ try fixture.assertSiblings()
+ }
+
+ func testBadStatusRangeSizeEncodingAndRedirectCannotAdvancePartial() async throws {
+ for defect in Defect.allCases {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ do {
+ _ = try await fixture.download { request, _, progress in try fixture.chunk(request, progress: progress, defect: defect) }
+ XCTFail("Invalid \(defect) must fail")
+ } catch { XCTAssertEqual(error as? CompactSpeechModelArchiveTransport.Failure, .invalidRange) }
+ XCTAssertEqual(try Data(contentsOf: fixture.partial).count, 0)
+ XCTAssertFalse(try FileManager.default.contentsOfDirectory(atPath: fixture.base.path).contains { $0.hasPrefix("chunk-") })
+ try fixture.assertSiblings()
+ }
+ }
+
+ func testNewReleaseDiscardsOnlyItsOwnOldPartial() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ try fixture.seedPartial(fixture.payload.prefix(4), marker: XCTUnwrap(fixture.descriptor.archiveSHA256))
+ let replacement = Data("ABCDEFGHIJ".utf8)
+ let descriptor = fixture.descriptor.replacingArchive(url: fixture.descriptor.archiveURL, sha256: Fixture.sha256(replacement), byteCount: Int64(replacement.count))
+ let recorder = Recorder()
+ let (ready, _) = try await CompactSpeechModelArchiveTransport.download(
+ descriptor: descriptor,
+ in: fixture.models,
+ progress: { _, _ in },
+ transport: { request, _, progress in
+ recorder.add(request.value(forHTTPHeaderField: "Range") ?? "")
+ return try fixture.chunk(request, progress: progress, payload: replacement)
+ },
+ chunkBytes: 4
+ )
+ defer { try? FileManager.default.removeItem(at: ready) }
+ XCTAssertEqual(recorder.values.first, "bytes=0-3")
+ XCTAssertEqual(try Data(contentsOf: ready), replacement)
+ XCTAssertEqual(try String(contentsOf: fixture.marker, encoding: .utf8), descriptor.archiveSHA256)
+ try fixture.assertSiblings()
+ }
+
+ func testMalformedMarkerOversizedAndCrashPartialRecoverOnRetry() async throws {
+ for corruption in 0..<4 {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let hash = try XCTUnwrap(fixture.descriptor.archiveSHA256)
+ let marker = corruption == 0 ? "broken" : corruption == 1 ? String(repeating: "z", count: 64) : hash
+ let bytes = corruption == 2 ? Data(repeating: 0, count: 11) : fixture.payload.prefix(corruption == 3 ? 6 : 4)
+ try fixture.seedPartial(bytes, marker: marker)
+ let recorder = Recorder()
+ let (ready, _) = try await fixture.download { request, _, progress in
+ recorder.add(request.value(forHTTPHeaderField: "Range") ?? "")
+ return try fixture.chunk(request, progress: progress)
+ }
+ defer { try? FileManager.default.removeItem(at: ready) }
+ XCTAssertEqual(recorder.values.first, corruption == 3 ? "bytes=4-7" : "bytes=0-3")
+ XCTAssertEqual(try Data(contentsOf: ready), fixture.payload)
+ try fixture.assertSiblings()
+ }
+ }
+
+ func testSamePartialClaimRejectsConcurrentDownloadWithoutNetwork() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let (started, continuation) = AsyncStream<Void>.makeStream()
+ let first = Task {
+ try await fixture.download { _, _, _ in
+ continuation.yield(())
+ continuation.finish()
+ try await Task.sleep(for: .seconds(60))
+ throw ProbeFailure.injected
+ }
+ }
+ for await _ in started {
+ break
+ }
+ do {
+ _ = try await fixture.download { _, _, _ in XCTFail("A competing claim must fail before network"); throw ProbeFailure.injected }
+ XCTFail("Expected another-process claim failure")
+ } catch { XCTAssertEqual(error as? CompactSpeechModelArchiveTransport.Failure, .alreadyDownloading) }
+ first.cancel()
+ do { _ = try await first.value; XCTFail("Expected cancellation") } catch { XCTAssertTrue(error is CancellationError) }
+ let (ready, _) = try await fixture.download { request, _, progress in try fixture.chunk(request, progress: progress) }
+ defer { try? FileManager.default.removeItem(at: ready) }
+ XCTAssertEqual(try Data(contentsOf: ready), fixture.payload)
+ try fixture.assertSiblings()
+ }
+
+ func testPartialMarkerAndClaimLinksCannotMutateExternalFiles() async throws {
+ for name in ["archive.partial", "release.sha256", "claim.lock"] {
+ for hardLink in [false, true] {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ try fixture.seedPartial(Data(), marker: XCTUnwrap(fixture.descriptor.archiveSHA256))
+ let external = fixture.base.appendingPathComponent("external")
+ let contents = Data(String(repeating: "f", count: 64).utf8)
+ try contents.write(to: external)
+ let link = fixture.partial.deletingLastPathComponent().appendingPathComponent(name)
+ if FileManager.default.fileExists(atPath: link.path) { try FileManager.default.removeItem(at: link) }
+ if hardLink { try FileManager.default.linkItem(at: external, to: link) } else { try FileManager.default.createSymbolicLink(at: link, withDestinationURL: external) }
+ do {
+ _ = try await fixture.download { _, _, _ in XCTFail("Unsafe retained files must fail before network"); throw ProbeFailure.injected }
+ XCTFail("Expected unsafe link rejection")
+ } catch let error as CompactSpeechModelArchiveTransport.Failure {
+ guard case let .unsafePartial(url) = error else { return XCTFail("Expected unsafePartial, got \(error)") }
+ XCTAssertEqual(url, link)
+ XCTAssertTrue(error.localizedDescription.contains(link.path))
+ }
+ XCTAssertEqual(try Data(contentsOf: external), contents)
+ try fixture.assertSiblings()
+ }
+ }
+ }
+
+ func testCompletedArchiveOwnershipPreventsChecksumFailureResume() async throws {
+ try await self.assertChecksumFailureRetry(seedCorruptPrefix: false)
+ }
+
+ func testDamagedAlignedRetainedPrefixCannotSurviveChecksumFailureRetry() async throws {
+ try await self.assertChecksumFailureRetry(seedCorruptPrefix: true)
+ }
+
+ private func assertChecksumFailureRetry(seedCorruptPrefix: Bool) async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let corrupted = Data("XXXXXXXXXX".utf8)
+ if seedCorruptPrefix {
+ try fixture.seedPartial(corrupted.prefix(4), marker: XCTUnwrap(fixture.descriptor.archiveSHA256))
+ }
+ let (ready, _) = try await fixture.download { request, _, progress in
+ try fixture.chunk(request, progress: progress, payload: seedCorruptPrefix ? fixture.payload : corrupted)
+ }
+ XCTAssertNotEqual(try Fixture.sha256(Data(contentsOf: ready)), fixture.descriptor.archiveSHA256)
+ // The outer installer's checksum failure deletes only this uniquely owned complete file.
+ try FileManager.default.removeItem(at: ready)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.partial.path))
+ let recorder = Recorder()
+ let (retry, _) = try await fixture.download { request, _, progress in
+ recorder.add(request.value(forHTTPHeaderField: "Range") ?? "")
+ return try fixture.chunk(request, progress: progress)
+ }
+ defer { try? FileManager.default.removeItem(at: retry) }
+ XCTAssertEqual(recorder.values.first, "bytes=0-3")
+ XCTAssertEqual(try Data(contentsOf: retry), fixture.payload)
+ try fixture.assertSiblings()
+ }
+
+ func testNextAttemptRemovesDeadProcessHandoffAndPreservesActiveAndUnknownFiles() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ try fixture.seedPartial(Data(), marker: XCTUnwrap(fixture.descriptor.archiveSHA256))
+ let directory = fixture.partial.deletingLastPathComponent()
+ let deadOwner = Int32.max
+ XCTAssertEqual(kill(deadOwner, 0), -1)
+ XCTAssertEqual(errno, ESRCH)
+ let abandoned = directory.appendingPathComponent("ready-\(deadOwner)-\(UUID().uuidString).tar")
+ let active = directory.appendingPathComponent("ready-\(getpid())-\(UUID().uuidString).tar")
+ let unknown = directory.appendingPathComponent("ready-\(deadOwner)-not-a-uuid.tar")
+ for file in [abandoned, active, unknown] { try fixture.payload.write(to: file) }
+ let (ready, _) = try await fixture.download { request, _, progress in try fixture.chunk(request, progress: progress) }
+ XCTAssertEqual(ready.deletingLastPathComponent(), directory)
+ XCTAssertTrue(ready.lastPathComponent.hasPrefix("ready-\(getpid())-"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: abandoned.path))
+ XCTAssertEqual(try Data(contentsOf: active), fixture.payload)
+ XCTAssertEqual(try Data(contentsOf: unknown), fixture.payload)
+ XCTAssertEqual(try Data(contentsOf: ready), fixture.payload)
+ try fixture.assertSiblings()
+ }
+
+ func testAbandonedHandoffLinksAndDirectoriesCannotDeleteExternalFiles() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ try fixture.seedPartial(Data(), marker: XCTUnwrap(fixture.descriptor.archiveSHA256))
+ let directory = fixture.partial.deletingLastPathComponent()
+ let external = fixture.base.appendingPathComponent("external-ready")
+ try fixture.payload.write(to: external)
+ let symlink = directory.appendingPathComponent("ready-\(Int32.max)-\(UUID().uuidString).tar")
+ let hardlink = directory.appendingPathComponent("ready-\(Int32.max)-\(UUID().uuidString).tar")
+ let folder = directory.appendingPathComponent("ready-\(Int32.max)-\(UUID().uuidString).tar")
+ try FileManager.default.createSymbolicLink(at: symlink, withDestinationURL: external)
+ try FileManager.default.linkItem(at: external, to: hardlink)
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
+ let (ready, _) = try await fixture.download { request, _, progress in try fixture.chunk(request, progress: progress) }
+ XCTAssertEqual(try Data(contentsOf: ready), fixture.payload)
+ XCTAssertEqual(try Data(contentsOf: external), fixture.payload)
+ for file in [symlink, hardlink, folder] { XCTAssertTrue(FileManager.default.fileExists(atPath: file.path)) }
+ try fixture.assertSiblings()
+ }
+
+ func testAbandonedHandoffCleanupIsBoundedPerAttempt() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ try fixture.seedPartial(Data(), marker: XCTUnwrap(fixture.descriptor.archiveSHA256))
+ let directory = fixture.partial.deletingLastPathComponent()
+ for _ in 0..<160 {
+ let file = directory.appendingPathComponent("ready-\(Int32.max)-\(UUID().uuidString).tar")
+ try fixture.payload.write(to: file)
+ }
+ _ = try await fixture.download { request, _, progress in try fixture.chunk(request, progress: progress) }
+ let remaining = try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.hasPrefix("ready-\(Int32.max)-") }
+ XCTAssertGreaterThanOrEqual(remaining.count, 160 - 128)
+ XCTAssertLessThan(remaining.count, 160)
+ try fixture.assertSiblings()
+ }
+
+ private enum ProbeFailure: Error { case injected }
+ private enum Defect: CaseIterable, Equatable { case status, range, size, encoding, redirect }
+
+ private final class Recorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private var storage: [String] = []
+ var values: [String] { self.lock.withLock { self.storage } }
+ func add(_ value: String) { self.lock.withLock { self.storage.append(value) } }
+ }
+
+ private struct Fixture: Sendable {
+ let base: URL
+ let models: URL
+ let descriptor: ParakeetSpeechModelCatalog.Descriptor
+ let payload = Data("0123456789".utf8)
+ var partial: URL { self.models.appendingPathComponent(".compact-downloads/\(self.descriptor.folderName)/archive.partial") }
+ var marker: URL { self.partial.deletingLastPathComponent().appendingPathComponent("release.sha256") }
+
+ init() throws {
+ self.base = FileManager.default.temporaryDirectory.appendingPathComponent("FVCompactTransport-\(UUID().uuidString)")
+ self.models = self.base.appendingPathComponent("models")
+ try FileManager.default.createDirectory(at: self.models, withIntermediateDirectories: true)
+ let payload = Data("0123456789".utf8)
+ self.descriptor = ParakeetSpeechModelCatalog.mini.replacingArchive(url: ParakeetSpeechModelCatalog.mini.archiveURL, sha256: Self.sha256(payload), byteCount: Int64(payload.count))
+ try Data("installed-old-weights".utf8).write(to: self.models.appendingPathComponent("preserved-installed"))
+ let sibling = self.models.appendingPathComponent(".compact-downloads/\(ParakeetSpeechModelCatalog.pico.folderName)")
+ try FileManager.default.createDirectory(at: sibling, withIntermediateDirectories: true)
+ try Data("other-model-partial".utf8).write(to: sibling.appendingPathComponent("archive.partial"))
+ }
+
+ func cleanup() { try? FileManager.default.removeItem(at: self.base) }
+ func download(_ transport: @escaping CompactSpeechModelArchiveTransport.ChunkTransport) async throws -> (URL, URLResponse) {
+ try await CompactSpeechModelArchiveTransport.download(descriptor: self.descriptor, in: self.models, progress: { _, _ in }, transport: transport, chunkBytes: 4)
+ }
+
+ func chunk(_ request: URLRequest, progress: @Sendable (Int64) -> Void, payload: Data? = nil, defect: Defect? = nil) throws -> (URL, URLResponse) {
+ let payload = payload ?? self.payload
+ let range = try XCTUnwrap(request.value(forHTTPHeaderField: "Range"))
+ let bounds = range.dropFirst("bytes=".count).split(separator: "-")
+ let start = try XCTUnwrap(Int(bounds[0]))
+ let end = try XCTUnwrap(Int(bounds[1]))
+ let file = self.base.appendingPathComponent("chunk-\(UUID().uuidString)")
+ let contents = defect == .size ? Data([0]) : payload.subdata(in: start..<(end + 1))
+ try contents.write(to: file)
+ progress(Int64(contents.count))
+ let url = defect == .redirect ? URL(string: "https://elsewhere.example/archive.tar") : request.url
+ let response = try XCTUnwrap(HTTPURLResponse(url: XCTUnwrap(url), statusCode: defect == .status ? 200 : 206, httpVersion: "HTTP/1.1", headerFields: [
+ "Content-Range": defect == .range ? "bytes 1-4/99" : "bytes \(start)-\(end)/\(payload.count)",
+ "Content-Length": String(contents.count),
+ "Content-Encoding": defect == .encoding ? "gzip" : "identity",
+ ]))
+ return (file, response)
+ }
+
+ func seedPartial(_ data: Data, marker: String) throws {
+ try FileManager.default.createDirectory(at: self.partial.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try data.write(to: self.partial)
+ try Data(marker.utf8).write(to: self.marker)
+ }
+
+ func assertSiblings() throws {
+ XCTAssertEqual(try String(contentsOf: self.models.appendingPathComponent("preserved-installed"), encoding: .utf8), "installed-old-weights")
+ let sibling = self.models.appendingPathComponent(".compact-downloads/\(ParakeetSpeechModelCatalog.pico.folderName)/archive.partial")
+ XCTAssertEqual(try String(contentsOf: sibling, encoding: .utf8), "other-model-partial")
+ }
+
+ static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bad-entry-other-platform.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bad-entry-other-platform.json
new file mode 100644
index 00000000..1e5e5fad
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bad-entry-other-platform.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbCiAgICB7CiAgICAgInJlbGVhc2UiOiAiMS4yLjAiLAogICAgICJ1cmwiOiAiaHR0cHM6Ly9tb2RlbHMuZmx1aWR2b2ljZS5hcHAvcGFyYWtlZXQvZmx1aWQtbWluaS8xLjIuMC9mbHVpZC1wYXJha2VldC1taW5pLWNvcmVtbC50YXIiLAogICAgICJieXRlcyI6IDI1NDEzNjMyMCwKICAgICAic2hhMjU2IjogInNob3J0IiwKICAgICAibWFuaWZlc3RTSEEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgImZvcm1hdCI6IDEsCiAgICAgIm1pbkJ1aWxkIjogMTAKICAgIH0KICAgXQogIH0KIH0KfQ==", "signature": "aq9l9PjeNIgM5AebMp8uJBnt407lavyYLxfb+CxfU0nry+haQ3yTvFcANI+yY/AE0y2Iwyp8APYUg+PrCUAiCA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bad-signature.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bad-signature.json
new file mode 100644
index 00000000..7aeced7e
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bad-signature.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "zxFEaNeNNWXIOLT0Rp1a/T0z7D21WwHaJGpcXw1boPhSI5gm5HtS4Ax195LB0fj+0i+B6T0sb9tUNOLFM+AuCA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-as-text.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-as-text.json
new file mode 100644
index 00000000..4551bd0e
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-as-text.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogIjI1NDEzNjMyMCIsCiAgICAgInNoYTI1NiI6ICJhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAgICAibWFuaWZlc3RTSEEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgImZvcm1hdCI6IDEsCiAgICAgIm1pbkJ1aWxkIjogMTAKICAgIH0KICAgXSwKICAgIm1hY29zIjogW10KICB9LAogICJwaWNvIjogewogICAiaW9zIjogW10sCiAgICJtYWNvcyI6IFtdCiAgfQogfQp9", "signature": "SQUClvFvMGwjJTnwX3Lu9G442YRMxNqB7loemVxeTlWBIb7L1hotJVEv4ad1iC21hwiLYLFsxucDjWbtHhaYAQ=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-fraction.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-fraction.json
new file mode 100644
index 00000000..d8751b28
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-fraction.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLjUsCiAgICAgInNoYTI1NiI6ICJhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAgICAibWFuaWZlc3RTSEEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgImZvcm1hdCI6IDEsCiAgICAgIm1pbkJ1aWxkIjogMTAKICAgIH0KICAgXSwKICAgIm1hY29zIjogW10KICB9LAogICJwaWNvIjogewogICAiaW9zIjogW10sCiAgICJtYWNvcyI6IFtdCiAgfQogfQp9", "signature": "iJeSIoF+v87aNnvfidnJprSSCerPxyd15BgxhRWVQW7tnVaqsqj89ktfoGaQwbmzOHxlJD2wLbQDhnN/DjnAAw=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-negative.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-negative.json
new file mode 100644
index 00000000..9695a20b
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-negative.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogLTI1NDEzNjMyMCwKICAgICAic2hhMjU2IjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLAogICAgICJtYW5pZmVzdFNIQTI1NiI6ICJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwKICAgICAiZm9ybWF0IjogMSwKICAgICAibWluQnVpbGQiOiAxMAogICAgfQogICBdLAogICAibWFjb3MiOiBbXQogIH0sCiAgInBpY28iOiB7CiAgICJpb3MiOiBbXSwKICAgIm1hY29zIjogW10KICB9CiB9Cn0=", "signature": "yBLydz7fMy8F8eJAMdmLuVNCjjw5RS9q3nQBlP06egiQVj44g3KwS0iVvhTV+92GQnu34YS1bqcBrV4ktf8wBw=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-too-large.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-too-large.json
new file mode 100644
index 00000000..7af82ed6
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-too-large.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjAwMDAwMDAwMCwKICAgICAic2hhMjU2IjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLAogICAgICJtYW5pZmVzdFNIQTI1NiI6ICJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwKICAgICAiZm9ybWF0IjogMSwKICAgICAibWluQnVpbGQiOiAxMAogICAgfQogICBdLAogICAibWFjb3MiOiBbXQogIH0sCiAgInBpY28iOiB7CiAgICJpb3MiOiBbXSwKICAgIm1hY29zIjogW10KICB9CiB9Cn0=", "signature": "KZ+OUqlofC7C/5XKXQfjCeNbB71w+LKGU3XNSbtj8EJTtJ7pULiVLXts3oytwEaqpid0Y9o6+ESETBh8l+ONDg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-too-small.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-too-small.json
new file mode 100644
index 00000000..cf0fa7b3
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/bytes-too-small.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMTAwMCwKICAgICAic2hhMjU2IjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLAogICAgICJtYW5pZmVzdFNIQTI1NiI6ICJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwKICAgICAiZm9ybWF0IjogMSwKICAgICAibWluQnVpbGQiOiAxMAogICAgfQogICBdLAogICAibWFjb3MiOiBbXQogIH0sCiAgInBpY28iOiB7CiAgICJpb3MiOiBbXSwKICAgIm1hY29zIjogW10KICB9CiB9Cn0=", "signature": "c41TknN1b7LXjf93NROGvol3iNUL5coK2DeoF94r1Cp9RY15F816h6x0R+LbYF3XLYOJJlyJVB+YZuvaUW0BAg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/expected.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/expected.json
new file mode 100644
index 00000000..6c4c28fa
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/expected.json
@@ -0,0 +1,202 @@
+[
+ {
+ "file": "good.json",
+ "lastSequence": 0,
+ "verdict": "ok"
+ },
+ {
+ "file": "good-same-sequence.json",
+ "lastSequence": 7,
+ "verdict": "ok"
+ },
+ {
+ "file": "good-extra-fields.json",
+ "lastSequence": 0,
+ "verdict": "ok"
+ },
+ {
+ "file": "good-no-models.json",
+ "lastSequence": 0,
+ "verdict": "ok"
+ },
+ {
+ "file": "good-two-releases.json",
+ "lastSequence": 0,
+ "verdict": "ok"
+ },
+ {
+ "file": "not-json.json",
+ "lastSequence": 0,
+ "verdict": "notAnEnvelope"
+ },
+ {
+ "file": "missing-signature.json",
+ "lastSequence": 0,
+ "verdict": "notAnEnvelope"
+ },
+ {
+ "file": "payload-not-base64.json",
+ "lastSequence": 0,
+ "verdict": "notAnEnvelope"
+ },
+ {
+ "file": "oversized.json",
+ "lastSequence": 0,
+ "verdict": "tooLarge"
+ },
+ {
+ "file": "bad-signature.json",
+ "lastSequence": 0,
+ "verdict": "badSignature"
+ },
+ {
+ "file": "unknown-key.json",
+ "lastSequence": 0,
+ "verdict": "badSignature"
+ },
+ {
+ "file": "payload-not-json.json",
+ "lastSequence": 0,
+ "verdict": "unreadablePayload"
+ },
+ {
+ "file": "missing-field.json",
+ "lastSequence": 0,
+ "verdict": "unreadablePayload"
+ },
+ {
+ "file": "bytes-as-text.json",
+ "lastSequence": 0,
+ "verdict": "unreadablePayload"
+ },
+ {
+ "file": "bytes-fraction.json",
+ "lastSequence": 0,
+ "verdict": "unreadablePayload"
+ },
+ {
+ "file": "models-wrong-shape.json",
+ "lastSequence": 0,
+ "verdict": "unreadablePayload"
+ },
+ {
+ "file": "unknown-schema.json",
+ "lastSequence": 0,
+ "verdict": "unknownSchema"
+ },
+ {
+ "file": "sequence-zero.json",
+ "lastSequence": 0,
+ "verdict": "staleSequence"
+ },
+ {
+ "file": "lower-sequence.json",
+ "lastSequence": 8,
+ "verdict": "staleSequence"
+ },
+ {
+ "file": "url-http.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-wrong-host.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-lookalike-host.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-user-info.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-port.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-outside-prefix.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-traversal.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-encoded-traversal.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-not-tar.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "url-query.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "hash-short.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "hash-uppercase.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "hash-not-hex.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "bytes-too-small.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "bytes-too-large.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "bytes-negative.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "format-zero.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "min-build-zero.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "release-empty.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "release-odd-characters.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ },
+ {
+ "file": "bad-entry-other-platform.json",
+ "lastSequence": 0,
+ "verdict": "badEntry"
+ }
+]
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/format-zero.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/format-zero.json
new file mode 100644
index 00000000..8c6a890d
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/format-zero.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAwLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "Lkd72dHgkQfsAd+m1yjMQMX85ZlrH21Ubn/Mjt/B7eGAAguE+28VtDrhI1lcP6i5SzldoPohQCdvUPM31f9KCQ=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-extra-fields.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-extra-fields.json
new file mode 100644
index 00000000..b7861e64
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-extra-fields.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwLAogICAgICJ3ZXIiOiA0LjM3LAogICAgICJub3RlIjogIngiCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0sCiAidXBkYXRlZCI6ICIyMDI2LTEwLTA1Igp9", "signature": "cyblVK+R+1aJf8WsAgb6xurZhbjdmTgQh/oDnlrfxuOfqrjcf8npPWCKjNJY4xgQZqaN8q+VDF/zs/J9jsdiDA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-no-models.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-no-models.json
new file mode 100644
index 00000000..e0461d32
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-no-models.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHt9Cn0=", "signature": "B8BomdL4X7ta70aTnXY4x3IJf+PiJG0LdoEr0+2r2dPwWjzdsPQTt8222cGUuqu2DIaRi9vI/fnmuw/Yb1J2Dg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-same-sequence.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-same-sequence.json
new file mode 100644
index 00000000..91f42ccc
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-same-sequence.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "zxFEaNeNNWXIOLT0Rp1a/T0z7D21WwHaJGpcXw1boPhSI5gm5HtS4Ax195LB0fj+0i+B6T0sb9tUNOLFM+AuCA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-two-releases.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-two-releases.json
new file mode 100644
index 00000000..57db7318
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good-two-releases.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIyLjAuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2Zs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FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good.json
new file mode 100644
index 00000000..91f42ccc
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/good.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "zxFEaNeNNWXIOLT0Rp1a/T0z7D21WwHaJGpcXw1boPhSI5gm5HtS4Ax195LB0fj+0i+B6T0sb9tUNOLFM+AuCA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-not-hex.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-not-hex.json
new file mode 100644
index 00000000..4d7dfe21
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-not-hex.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImdnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2ciLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "WX+FX33It6l6xIV4EVh38238I9lJ8V1Iztz/dS7dl4ynqceCUPWthnmQIaasnZgPVOqCqGCu94vIkjiWbb8XCQ=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-short.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-short.json
new file mode 100644
index 00000000..25f5b76f
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-short.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAgICAibWFuaWZlc3RTSEEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgImZvcm1hdCI6IDEsCiAgICAgIm1pbkJ1aWxkIjogMTAKICAgIH0KICAgXSwKICAgIm1hY29zIjogW10KICB9LAogICJwaWNvIjogewogICAiaW9zIjogW10sCiAgICJtYWNvcyI6IFtdCiAgfQogfQp9", "signature": "+yRxthv8tXNamT/HInVw9V/blTRnvqzT85Zru5SRqYbPVU/eUMBLq5rVhPyy+XhaoKPWVeMBFfk7DjpMnUElAg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-uppercase.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-uppercase.json
new file mode 100644
index 00000000..f27f60e4
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/hash-uppercase.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "lV9DsjrcH24Rw5BijrBI2kjD5umXQs6UtodXncgD8sUwpygAKWBdsU8rDPFhxyzhGp/gYObbYPfABEaoAUs7CQ=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/lower-sequence.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/lower-sequence.json
new file mode 100644
index 00000000..91f42ccc
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/lower-sequence.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "zxFEaNeNNWXIOLT0Rp1a/T0z7D21WwHaJGpcXw1boPhSI5gm5HtS4Ax195LB0fj+0i+B6T0sb9tUNOLFM+AuCA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/min-build-zero.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/min-build-zero.json
new file mode 100644
index 00000000..8de42e1e
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/min-build-zero.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDAKICAgIH0KICAgXSwKICAgIm1hY29zIjogW10KICB9LAogICJwaWNvIjogewogICAiaW9zIjogW10sCiAgICJtYWNvcyI6IFtdCiAgfQogfQp9", "signature": "d00ylzL7gYRli9ltJ9QvzC4DG5rcv94WpbeexOpF4nvqy19TpLh4QheWBsyGi/uFI2WtH5X+/IWWmUU1BnQUBw=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/missing-field.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/missing-field.json
new file mode 100644
index 00000000..266d3f21
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/missing-field.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJtYW5pZmVzdFNIQTI1NiI6ICJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwKICAgICAiZm9ybWF0IjogMSwKICAgICAibWluQnVpbGQiOiAxMAogICAgfQogICBdLAogICAibWFjb3MiOiBbXQogIH0sCiAgInBpY28iOiB7CiAgICJpb3MiOiBbXSwKICAgIm1hY29zIjogW10KICB9CiB9Cn0=", "signature": "LTXEzc8mj2C1IQjxfD0WrXUMwD2OZHnC9SJBb1lscU6/6OabmbFM0JnkniTpNp2HrwWK0SkIYTSU7X5OTERkBA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/missing-signature.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/missing-signature.json
new file mode 100644
index 00000000..0d5082d6
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/missing-signature.json
@@ -0,0 +1 @@
+{"payload": "e30="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/models-wrong-shape.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/models-wrong-shape.json
new file mode 100644
index 00000000..0909aa4e
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/models-wrong-shape.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IFsKICAgewogICAgInJlbGVhc2UiOiAiMS4yLjAiLAogICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAiYnl0ZXMiOiAyNTQxMzYzMjAsCiAgICAic2hhMjU2IjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLAogICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgImZvcm1hdCI6IDEsCiAgICAibWluQnVpbGQiOiAxMAogICB9CiAgXQogfQp9", "signature": "blLS9wgH1UVZCBir2WtFgX9WVsLUaHAWwaDPIU3Ob5YA5zCItE8qzABzfn2HW8yTP16VEk+/Us3mZxFaxBy9BA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/not-json.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/not-json.json
new file mode 100644
index 00000000..36efa5ac
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/not-json.json
@@ -0,0 +1 @@
+<html>503</html>
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/oversized.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/oversized.json
new file mode 100644
index 00000000..32e3bdf1
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/oversized.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW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4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4Igp9", "signature": "o39drwgZqS9P7KPUvxG0kLjGVh49aSwYHEV2hCO9rkX5sW7itZS1gyyyz1Q5cnwfHt6cc/Pvus8IUjYOLVCqCQ=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/payload-not-base64.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/payload-not-base64.json
new file mode 100644
index 00000000..45f4f9e2
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/payload-not-base64.json
@@ -0,0 +1 @@
+{"payload": "***", "signature": "AAAA"}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/payload-not-json.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/payload-not-json.json
new file mode 100644
index 00000000..fbb9b0de
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/payload-not-json.json
@@ -0,0 +1 @@
+{"payload": "bm90IGpzb24=", "signature": "Fg5bSxoGzO5WPQB0F3BODWfCU/IoC5aXrdzH1jTJy265OUgTg6YziMfOfPoyX51SGzJg4WvIukm6SfVI0fvxCw=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/picks.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/picks.json
new file mode 100644
index 00000000..fc11703c
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/picks.json
@@ -0,0 +1,58 @@
+[
+ {
+ "file": "good-two-releases.json",
+ "model": "mini",
+ "platform": "ios",
+ "build": 25,
+ "format": 2,
+ "release": "2.0.0"
+ },
+ {
+ "file": "good-two-releases.json",
+ "model": "mini",
+ "platform": "ios",
+ "build": 25,
+ "format": 1,
+ "release": "1.2.0"
+ },
+ {
+ "file": "good-two-releases.json",
+ "model": "mini",
+ "platform": "ios",
+ "build": 12,
+ "format": 2,
+ "release": "1.2.0"
+ },
+ {
+ "file": "good-two-releases.json",
+ "model": "mini",
+ "platform": "ios",
+ "build": 9,
+ "format": 2,
+ "release": null
+ },
+ {
+ "file": "good-two-releases.json",
+ "model": "mini",
+ "platform": "macos",
+ "build": 25,
+ "format": 2,
+ "release": null
+ },
+ {
+ "file": "good-two-releases.json",
+ "model": "pico",
+ "platform": "ios",
+ "build": 25,
+ "format": 2,
+ "release": null
+ },
+ {
+ "file": "good-two-releases.json",
+ "model": "v3",
+ "platform": "ios",
+ "build": 25,
+ "format": 2,
+ "release": null
+ }
+]
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/release-empty.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/release-empty.json
new file mode 100644
index 00000000..c56b962b
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/release-empty.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIiLAogICAgICJ1cmwiOiAiaHR0cHM6Ly9tb2RlbHMuZmx1aWR2b2ljZS5hcHAvcGFyYWtlZXQvZmx1aWQtbWluaS8xLjIuMC9mbHVpZC1wYXJha2VldC1taW5pLWNvcmVtbC50YXIiLAogICAgICJieXRlcyI6IDI1NDEzNjMyMCwKICAgICAic2hhMjU2IjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLAogICAgICJtYW5pZmVzdFNIQTI1NiI6ICJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwKICAgICAiZm9ybWF0IjogMSwKICAgICAibWluQnVpbGQiOiAxMAogICAgfQogICBdLAogICAibWFjb3MiOiBbXQogIH0sCiAgInBpY28iOiB7CiAgICJpb3MiOiBbXSwKICAgIm1hY29zIjogW10KICB9CiB9Cn0=", "signature": "vLb8bUR0oejnsxHTuD0f9Q86RvJrEe9YCxPlaEztPj5iFXDqDCGWtDOgO/e9vJnM8cESbahdaMlQr4sy5FZDBg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/release-odd-characters.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/release-odd-characters.json
new file mode 100644
index 00000000..225a0c15
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/release-odd-characters.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMC8uLi94IiwKICAgICAidXJsIjogImh0dHBzOi8vbW9kZWxzLmZsdWlkdm9pY2UuYXBwL3BhcmFrZWV0L2ZsdWlkLW1pbmkvMS4yLjAvZmx1aWQtcGFyYWtlZXQtbWluaS1jb3JlbWwudGFyIiwKICAgICAiYnl0ZXMiOiAyNTQxMzYzMjAsCiAgICAgInNoYTI1NiI6ICJhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAgICAibWFuaWZlc3RTSEEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgImZvcm1hdCI6IDEsCiAgICAgIm1pbkJ1aWxkIjogMTAKICAgIH0KICAgXSwKICAgIm1hY29zIjogW10KICB9LAogICJwaWNvIjogewogICAiaW9zIjogW10sCiAgICJtYWNvcyI6IFtdCiAgfQogfQp9", "signature": "uZRQVvSUSi3v+zizNGTTtrDYhm86xwCDtWob3wgN+gPtdA0gzxmxsgpspwEaZ9K70B8bh0GIDECU5wQH3BUuCw=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/sequence-zero.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/sequence-zero.json
new file mode 100644
index 00000000..0ff73fe3
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/sequence-zero.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiAwLAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "DHXJJIKkZtqfX/x1zQeaAKM2qwqaH537uCAYDxn7uqK65EOGoQui+ozTQcc1G3T83qh4cX+ZBJ5uhE09FlORCA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/unknown-key.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/unknown-key.json
new file mode 100644
index 00000000..383d547e
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/unknown-key.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "VDk0YvsKPgqFf5FAVXXcMieYgORw1Pp4suTtjhUpQTBUIQP44HAKRJZuJchwxqEwO8IXT7vQ73JgfKtZ2UaBCQ=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/unknown-schema.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/unknown-schema.json
new file mode 100644
index 00000000..034de84c
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/unknown-schema.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDIsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "jFCV663+mFCakv+jTrNwPx3IFkVsyaN0e9RxMIcxD8/9gryxcxw8a+HnXby3Yub+CMmqYAoiTpauHg+h6IpDAg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-encoded-traversal.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-encoded-traversal.json
new file mode 100644
index 00000000..4dff04a5
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-encoded-traversal.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC8lMmUlMmUvZmVlZC9mbHVpZC1wYXJha2VldC1taW5pLWNvcmVtbC50YXIiLAogICAgICJieXRlcyI6IDI1NDEzNjMyMCwKICAgICAic2hhMjU2IjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLAogICAgICJtYW5pZmVzdFNIQTI1NiI6ICJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwKICAgICAiZm9ybWF0IjogMSwKICAgICAibWluQnVpbGQiOiAxMAogICAgfQogICBdLAogICAibWFjb3MiOiBbXQogIH0sCiAgInBpY28iOiB7CiAgICJpb3MiOiBbXSwKICAgIm1hY29zIjogW10KICB9CiB9Cn0=", "signature": "1YA76donzCtjshTBex8rOsgscvQyQvyGcFyQEwQnTnOqpV7CAKuuaUCgJmwoTRuPaFCYy5tqKgd1lYVe22/vDA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-http.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-http.json
new file mode 100644
index 00000000..3bc9ff91
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-http.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwOi8vbW9kZWxzLmZsdWlkdm9pY2UuYXBwL3BhcmFrZWV0L2ZsdWlkLW1pbmkvMS4yLjAvZmx1aWQtcGFyYWtlZXQtbWluaS1jb3JlbWwudGFyIiwKICAgICAiYnl0ZXMiOiAyNTQxMzYzMjAsCiAgICAgInNoYTI1NiI6ICJhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAgICAibWFuaWZlc3RTSEEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgImZvcm1hdCI6IDEsCiAgICAgIm1pbkJ1aWxkIjogMTAKICAgIH0KICAgXSwKICAgIm1hY29zIjogW10KICB9LAogICJwaWNvIjogewogICAiaW9zIjogW10sCiAgICJtYWNvcyI6IFtdCiAgfQogfQp9", "signature": "2JJ0KZCyJWC+YmC38wDmMgvUXTDb00Yg87i18AcroDSYl3sN6NfSWc3A4R/V8tqhCVevoXVXScl0PUbv5kFWAw=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-lookalike-host.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-lookalike-host.json
new file mode 100644
index 00000000..e1ae9b09
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-lookalike-host.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC5leGFtcGxlLmNvbS9wYXJha2VldC9mbHVpZC1wYXJha2VldC1taW5pLWNvcmVtbC50YXIiLAogICAgICJieXRlcyI6IDI1NDEzNjMyMCwKICAgICAic2hhMjU2IjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLAogICAgICJtYW5pZmVzdFNIQTI1NiI6ICJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwKICAgICAiZm9ybWF0IjogMSwKICAgICAibWluQnVpbGQiOiAxMAogICAgfQogICBdLAogICAibWFjb3MiOiBbXQogIH0sCiAgInBpY28iOiB7CiAgICJpb3MiOiBbXSwKICAgIm1hY29zIjogW10KICB9CiB9Cn0=", "signature": "21odh0opzpKD8nl1EFperxo0PmeJjqv5X76mcqsf8RiYEjKLIGwWurGGkgn4AOEOQ5/xDtEu1vgduLDanHeEDA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-not-tar.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-not-tar.json
new file mode 100644
index 00000000..872d7478
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-not-tar.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1taW5pLzEuMi4wL21vZGVsLnppcCIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "yovjDIsziFLloSNVV5QOImbtSc1eKm//rwPq8dYl0jdsD2VrNROe3+TnAXub8ipFRoAgfmxGCfocPnVvw1rqCA=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-outside-prefix.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-outside-prefix.json
new file mode 100644
index 00000000..02780995
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-outside-prefix.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9mZWVkL3YxL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "0lc8RA3qkxwzYIVmtUhmCz8cXAZ77jo2al5geX4lr36ea99hmDzC7WySVYc2amdx41bQdqIm5ZTFweSsPX2PBQ=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-port.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-port.json
new file mode 100644
index 00000000..9a8800c4
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-port.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcDo4NDQzL3BhcmFrZWV0L2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "4UW8PapP3XaX0UaYROYILSkxlQHTFOAQdiFE98DwMjWBT7hs1r8nrC9qAvezxzjMDfR17OPWFfYWc6LpB0/ZAw=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-query.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-query.json
new file mode 100644
index 00000000..fcc1003a
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-query.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC9mbHVpZC1wYXJha2VldC1taW5pLWNvcmVtbC50YXI/dj0yIiwKICAgICAiYnl0ZXMiOiAyNTQxMzYzMjAsCiAgICAgInNoYTI1NiI6ICJhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAgICAibWFuaWZlc3RTSEEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgImZvcm1hdCI6IDEsCiAgICAgIm1pbkJ1aWxkIjogMTAKICAgIH0KICAgXSwKICAgIm1hY29zIjogW10KICB9LAogICJwaWNvIjogewogICAiaW9zIjogW10sCiAgICJtYWNvcyI6IFtdCiAgfQogfQp9", "signature": "9fwd8cZh4fasADdeEiYbgWCm7a+7uo7a+dZZmhqQzrdfLj4JSkpFhOu98LCrGkvT+E+EB006mB6VtZr6LcIAAg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-traversal.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-traversal.json
new file mode 100644
index 00000000..c782ab6d
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-traversal.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcC9wYXJha2VldC8uLi9mZWVkL2ZsdWlkLXBhcmFrZWV0LW1pbmktY29yZW1sLnRhciIsCiAgICAgImJ5dGVzIjogMjU0MTM2MzIwLAogICAgICJzaGEyNTYiOiAiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsCiAgICAgIm1hbmlmZXN0U0hBMjU2IjogImJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLAogICAgICJmb3JtYXQiOiAxLAogICAgICJtaW5CdWlsZCI6IDEwCiAgICB9CiAgIF0sCiAgICJtYWNvcyI6IFtdCiAgfSwKICAicGljbyI6IHsKICAgImlvcyI6IFtdLAogICAibWFjb3MiOiBbXQogIH0KIH0KfQ==", "signature": "vbR9/9KlEp3IDylymIGN/+B0MAe7Dg3/ZC4Czw99Pae6gbDw/zxsBasZ7Dp8H+rWbGBEvfLAVg6WSFCKAfkcBg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-user-info.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-user-info.json
new file mode 100644
index 00000000..02f47de1
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-user-info.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL21vZGVscy5mbHVpZHZvaWNlLmFwcEBleGFtcGxlLmNvbS9wYXJha2VldC9mbHVpZC1wYXJha2VldC1taW5pLWNvcmVtbC50YXIiLAogICAgICJieXRlcyI6IDI1NDEzNjMyMCwKICAgICAic2hhMjU2IjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLAogICAgICJtYW5pZmVzdFNIQTI1NiI6ICJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwKICAgICAiZm9ybWF0IjogMSwKICAgICAibWluQnVpbGQiOiAxMAogICAgfQogICBdLAogICAibWFjb3MiOiBbXQogIH0sCiAgInBpY28iOiB7CiAgICJpb3MiOiBbXSwKICAgIm1hY29zIjogW10KICB9CiB9Cn0=", "signature": "amcBHcDMUwPJTJxOAcH3Muf1dz7PbVL2b0AAa/aH5qfq8h6dtBqEUcRWU2cJ+j6+YAb8fXGp6vnd8VSFu3VqDg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-wrong-host.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-wrong-host.json
new file mode 100644
index 00000000..e06dc89d
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/feeds/url-wrong-host.json
@@ -0,0 +1 @@
+{"payload": "ewogInNjaGVtYSI6IDEsCiAic2VxdWVuY2UiOiA3LAogIm1vZGVscyI6IHsKICAibWluaSI6IHsKICAgImlvcyI6IFsKICAgIHsKICAgICAicmVsZWFzZSI6ICIxLjIuMCIsCiAgICAgInVybCI6ICJodHRwczovL2V4YW1wbGUuY29tL3BhcmFrZWV0L2ZsdWlkLW1pbmkvMS4yLjAvZmx1aWQtcGFyYWtlZXQtbWluaS1jb3JlbWwudGFyIiwKICAgICAiYnl0ZXMiOiAyNTQxMzYzMjAsCiAgICAgInNoYTI1NiI6ICJhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAgICAibWFuaWZlc3RTSEEyNTYiOiAiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsCiAgICAgImZvcm1hdCI6IDEsCiAgICAgIm1pbkJ1aWxkIjogMTAKICAgIH0KICAgXSwKICAgIm1hY29zIjogW10KICB9LAogICJwaWNvIjogewogICAiaW9zIjogW10sCiAgICJtYWNvcyI6IFtdCiAgfQogfQp9", "signature": "r4XWpuL5r4QFAm7cuVv6JibAtqw/FHhOr53smdMENYB6+STgSwgdkLGNY8PECifi6IvCXm6uqgERL/ufHwXQBg=="}
\ No newline at end of file
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/public_keys.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/public_keys.json
new file mode 100644
index 00000000..efa39d61
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/public_keys.json
@@ -0,0 +1,4 @@
+{
+ "main": "etCg9rPWJ81mB3XdJfKs2Y6QeuJjIIqCYfbYy40LRY4=",
+ "spare": "Lf4aPkJzkEbu7nUj2Oh+ltoCePbPGXQMEMh+KfqtJvw="
+}
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/absolute-path.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/absolute-path.tar
new file mode 100644
index 00000000..e9c7f0c3
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/absolute-path.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/expected.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/expected.json
new file mode 100644
index 00000000..74761e8e
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/expected.json
@@ -0,0 +1,104 @@
+[
+ {
+ "file": "good.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "ok"
+ },
+ {
+ "file": "pax.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "unsafePath"
+ },
+ {
+ "file": "tampered-file.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "fileMismatch"
+ },
+ {
+ "file": "wrong-size-file.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "fileMismatch"
+ },
+ {
+ "file": "missing-file.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "fileMismatch"
+ },
+ {
+ "file": "extra-file.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "unlistedFile"
+ },
+ {
+ "file": "other-manifest.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "manifestMismatch"
+ },
+ {
+ "file": "no-manifest.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "manifestMismatch"
+ },
+ {
+ "file": "wrong-total.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "71481da01d303c2dea7fb7803d48f3d2b62c6ba6cce2f9977401862615cc5894",
+ "verdict": "manifestMismatch"
+ },
+ {
+ "file": "manifest-names-other-folder.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "70ca01241180a231454f461947e8990d0b0762a5dfb37dd6c956df68758e0e32",
+ "verdict": "manifestMismatch"
+ },
+ {
+ "file": "manifest-path-escapes.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "57ff9b64e417f067daf4d5a40456f91089d7a464af27b1face63716cdbf98145",
+ "verdict": "fileMismatch"
+ },
+ {
+ "file": "wrong-folder.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "missingFolder"
+ },
+ {
+ "file": "two-folders.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "missingFolder"
+ },
+ {
+ "file": "traversal.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "unsafePath"
+ },
+ {
+ "file": "absolute-path.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "unsafePath"
+ },
+ {
+ "file": "symlink.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "unsupportedEntry"
+ },
+ {
+ "file": "truncated.tar",
+ "folderName": "tiny-model",
+ "manifestSHA256": "789c99ff3358b6f881cfccf2e3420533d9ede3145384e86a3a52f4225845416f",
+ "verdict": "truncatedArchive"
+ }
+]
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/extra-file.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/extra-file.tar
new file mode 100644
index 00000000..c9d9a88e
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/extra-file.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/good.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/good.tar
new file mode 100644
index 00000000..18bed4a9
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/good.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/manifest-names-other-folder.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/manifest-names-other-folder.tar
new file mode 100644
index 00000000..1a83ded0
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/manifest-names-other-folder.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/manifest-path-escapes.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/manifest-path-escapes.tar
new file mode 100644
index 00000000..958b8493
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/manifest-path-escapes.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/missing-file.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/missing-file.tar
new file mode 100644
index 00000000..8c61950e
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/missing-file.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/no-manifest.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/no-manifest.tar
new file mode 100644
index 00000000..f8c58d53
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/no-manifest.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/other-manifest.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/other-manifest.tar
new file mode 100644
index 00000000..2edff90b
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/other-manifest.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/pax.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/pax.tar
new file mode 100644
index 00000000..94494ce5
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/pax.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/symlink.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/symlink.tar
new file mode 100644
index 00000000..99ea6401
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/symlink.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/tampered-file.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/tampered-file.tar
new file mode 100644
index 00000000..959d3cdc
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/tampered-file.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/traversal.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/traversal.tar
new file mode 100644
index 00000000..42b8bb2a
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/traversal.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/truncated.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/truncated.tar
new file mode 100644
index 00000000..7009347c
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/truncated.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/two-folders.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/two-folders.tar
new file mode 100644
index 00000000..b2f59399
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/two-folders.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-folder.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-folder.tar
new file mode 100644
index 00000000..ee38cf08
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-folder.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-size-file.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-size-file.tar
new file mode 100644
index 00000000..b9c028a8
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-size-file.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-total.tar b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-total.tar
new file mode 100644
index 00000000..1375bbb4
Binary files /dev/null and b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/tars/wrong-total.tar differ
diff --git a/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/test_key.json b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/test_key.json
new file mode 100644
index 00000000..a156189a
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/Fixtures/ModelRelease/test_key.json
@@ -0,0 +1,5 @@
+{
+ "note": "Test key for the fixtures only. It signs nothing real.",
+ "seed": "Oet8Ql8/mQ/BxTkCkk1L+PE5O3ce3OS1mz3QmFl/BOw=",
+ "publicKey": "hrWpkZUM4TP7ElDXPXRvSccJ6eOuZfsvItnbazb6Krs="
+}
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index 0f08c6e9..f3d1f7b6 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -646,7 +646,8 @@ final class HotkeyShortcutTests: XCTestCase {
promptModeCallback: { starts += 1 },
promptSelectionCallback: { _ in starts += 1 },
commandModeCallback: { starts += 1 },
- rewriteModeCallback: { starts += 1 }
+ rewriteModeCallback: { starts += 1 },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(activationMode)
let down = try self.primaryReleaseTestEvent(type: .keyDown)
@@ -856,7 +857,8 @@ final class HotkeyShortcutTests: XCTestCase {
promptModeCallback: { otherStarts += 1 },
promptSelectionCallback: { _ in otherStarts += 1 },
commandModeCallback: { otherStarts += 1 },
- rewriteModeCallback: { otherStarts += 1 }
+ rewriteModeCallback: { otherStarts += 1 },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(.toggle)
_ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: 54, modifiers: .maskCommand))
@@ -1031,7 +1033,8 @@ final class HotkeyShortcutTests: XCTestCase {
promptModeCallback: { starts += 1 },
promptSelectionCallback: { _ in starts += 1 },
commandModeCallback: { starts += 1 },
- rewriteModeCallback: { starts += 1 }
+ rewriteModeCallback: { starts += 1 },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(.toggle)
_ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: 54, modifiers: .maskCommand))
@@ -1095,7 +1098,8 @@ final class HotkeyShortcutTests: XCTestCase {
promptModeCallback: { starts += 1 },
promptSelectionCallback: { _ in starts += 1 },
commandModeCallback: { starts += 1 },
- rewriteModeCallback: { starts += 1 }
+ rewriteModeCallback: { starts += 1 },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(activation)
let down = try self.primaryReleaseTestEvent(type: .keyDown, keyCode: 31, modifiers: [])
@@ -1278,7 +1282,8 @@ final class HotkeyShortcutTests: XCTestCase {
promptModeShortcutEnabled: false,
commandModeShortcutEnabled: false,
rewriteModeShortcutEnabled: false,
- promptSelectionCallback: { selections.append($0) }
+ promptSelectionCallback: { selections.append($0) },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(.toggle)
_ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: 54, modifiers: .maskCommand))
@@ -1330,7 +1335,8 @@ final class HotkeyShortcutTests: XCTestCase {
startRecordingCallback: { starts += 1; asr.isRunning = true },
dictationModeCallback: { starts += 1; asr.isRunning = true },
stopAndProcessCallback: { _ in stops += 1 },
- isDictateRecordingProvider: { isDictate }
+ isDictateRecordingProvider: { isDictate },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(.hold)
_ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: 55, modifiers: .maskCommand))
@@ -1472,7 +1478,8 @@ final class HotkeyShortcutTests: XCTestCase {
startRecordingCallback: { asr.isRunning = true },
dictationModeCallback: { asr.isRunning = true },
stopAndProcessCallback: { _ in stops += 1; asr.isRunning = false },
- isDictateRecordingProvider: { isDictate }
+ isDictateRecordingProvider: { isDictate },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(.hold)
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
@@ -1600,7 +1607,8 @@ final class HotkeyShortcutTests: XCTestCase {
rewriteModeShortcutEnabled: false,
stopAndProcessCallback: { _ in stops += 1; asr.isRunning = false },
promptSelectionCallback: { _ in starts += 1; asr.isRunning = true },
- isPromptModeRecordingProvider: { true }
+ isPromptModeRecordingProvider: { true },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(.hold)
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 2, modifiers: .maskControl))
@@ -1735,7 +1743,8 @@ final class HotkeyShortcutTests: XCTestCase {
promptModeShortcutEnabled: false,
commandModeShortcutEnabled: false,
rewriteModeShortcutEnabled: false,
- promptSelectionCallback: { selections.append($0) }
+ promptSelectionCallback: { selections.append($0) },
+ isSessionLockedProvider: { false }
)
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, modifiers: .maskControl))
manager.updatePromptShortcutAssignments([(selection: .privateAI, shortcut: shortcut)])
@@ -1772,7 +1781,8 @@ final class HotkeyShortcutTests: XCTestCase {
stopAndProcessCallback: { _ in stops += 1; asr.isRunning = false },
promptSelectionCallback: { _ in starts += 1; asr.isRunning = true },
isDictateRecordingProvider: { !style },
- isPromptModeRecordingProvider: { style }
+ isPromptModeRecordingProvider: { style },
+ isSessionLockedProvider: { false }
)
manager.setHotkeyMode(.hold)
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, modifiers: .maskControl))
@@ -1887,7 +1897,7 @@ final class HotkeyShortcutTests: XCTestCase {
asr.isRunning = true
defer { asr.isRunning = false }
var cancellations = 0
- let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {})
+ let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {}, isSessionLocked: { true })
manager.setCancelCallback { cancellations += 1; return .cancelled }
let result = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: []))
XCTAssertNil(result)
@@ -2058,11 +2068,87 @@ final class HotkeyShortcutTests: XCTestCase {
withExtendedLifetime(event) { XCTAssertNotNil(result) }
}
+ @MainActor
+ func testLockedSessionBlocksPrimaryRecordingStarts() async throws {
+ for activationMode in [HotkeyActivationMode.toggle, .hold, .automatic] {
+ var starts = 0
+ let manager = self.makePrimaryReleaseTestManager(asr: ASRService(), onStart: { starts += 1 }, isSessionLocked: { true })
+ manager.setHotkeyMode(activationMode)
+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
+ _ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp))
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(starts, 0, "A locked session must not start primary recording in \(activationMode)")
+ }
+ }
+
+ @MainActor
+ func testLockedSessionBlocksOtherRecordingStarts() async throws {
+ let shortcut = HotkeyShortcut(keyCode: 2, modifierFlags: [.control, .command])
+ for mode in [HotkeyHoldModeType.promptMode, .commandMode, .rewriteMode, .promptAssignment] {
+ var starts = 0
+ let manager = GlobalHotkeyManager(
+ asrService: ASRService(),
+ primaryShortcuts: [],
+ promptModeShortcut: shortcut,
+ commandModeShortcut: shortcut,
+ rewriteModeShortcut: shortcut,
+ promptShortcutAssignments: mode == .promptAssignment ? [(selection: SettingsStore.DictationPromptSelection.default, shortcut: shortcut)] : [],
+ promptModeShortcutEnabled: mode == .promptMode,
+ commandModeShortcutEnabled: mode == .commandMode,
+ rewriteModeShortcutEnabled: mode == .rewriteMode,
+ promptModeCallback: { starts += 1 },
+ promptSelectionCallback: { _ in starts += 1 },
+ commandModeCallback: { starts += 1 },
+ rewriteModeCallback: { starts += 1 },
+ isSessionLockedProvider: { true }
+ )
+ manager.setHotkeyMode(.toggle)
+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
+ _ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp))
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(starts, 0, "A locked session must not start \(mode)")
+ }
+ }
+
+ @MainActor
+ func testLockingSessionStillAllowsOwnedHoldRelease() async throws {
+ let asr = ASRService()
+ defer { asr.isRunning = false }
+ var isLocked = false
+ var starts = 0
+ var stops = 0
+ let manager = self.makePrimaryReleaseTestManager(
+ asr: asr,
+ onStart: { starts += 1; asr.isRunning = true },
+ onStop: { stops += 1; asr.isRunning = false },
+ isSessionLocked: { isLocked }
+ )
+ manager.setHotkeyMode(.hold)
+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(starts, 1)
+ XCTAssertTrue(asr.isRunning)
+ isLocked = true
+ _ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp, modifiers: []))
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(stops, 1, "Locking must not strand a recording owned by the held shortcut")
+ XCTAssertFalse(asr.isRunning)
+ }
+
@MainActor
private func makePrimaryReleaseTestManager(
asr: ASRService,
onStart: @escaping () async -> Void,
- onStop: @escaping () async -> Void = {}
+ onStop: @escaping () async -> Void = {},
+ isSessionLocked: @escaping () -> Bool = { false }
) -> GlobalHotkeyManager {
let manager = GlobalHotkeyManager(
asrService: asr,
@@ -2076,7 +2162,8 @@ final class HotkeyShortcutTests: XCTestCase {
startRecordingCallback: onStart,
dictationModeCallback: onStart,
stopAndProcessCallback: { _ in await onStop() },
- isDictateRecordingProvider: { true }
+ isDictateRecordingProvider: { true },
+ isSessionLockedProvider: isSessionLocked
)
manager.setHotkeyMode(.toggle)
return manager
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
index cdd91866..595fb8b2 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
@@ -109,7 +109,7 @@ private final class DetectorHarness {
set { self.flags.browserEnabled = newValue }
}
- init() {
+ init(rejectionLogger: @escaping (String) -> Void = { _ in }) {
let flags = self.flags
self.detector = MeetingAutoDetector(
workspaceEvents: self.workspace,
@@ -120,7 +120,8 @@ private final class DetectorHarness {
activityGate: self.gate,
clock: self.clock,
isNativeDetectionEnabled: { flags.nativeEnabled },
- isBrowserDetectionEnabled: { flags.browserEnabled }
+ isBrowserDetectionEnabled: { flags.browserEnabled },
+ rejectionLogger: rejectionLogger
)
self.detector.onPromptRequested = { [weak self] request in self?.prompts.append(request) }
self.detector.onStillRecordingNudge = { [weak self] in self?.nudges += 1 }
@@ -795,7 +796,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
let h = DetectorHarness()
let firstEpisode = h.confirmZoom()
XCTAssertNotNil(firstEpisode)
- h.detector.timeoutDismissed(episodeID: try XCTUnwrap(firstEpisode))
+ try h.detector.timeoutDismissed(episodeID: XCTUnwrap(firstEpisode))
// Window disappears; after grace + the 60s release window the episode is evicted.
h.detector.handleWindowSnapshot([], at: h.clock.now())
@@ -960,6 +961,65 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.first?.cta, .record)
}
+ func testRepeatedBusyEvidenceLogsOnceWithoutBlockingLaterPrompt() {
+ var lines: [String] = []
+ let h = DetectorHarness(rejectionLogger: { lines.append($0) })
+ h.gate.isIdle = false
+ h.confirmZoom()
+ let target = h.detector.automaticTarget
+ for _ in 0..<100 {
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ }
+ XCTAssertEqual(lines.filter { $0.contains("reason=busy") }.count, 1)
+ XCTAssertTrue(h.prompts.isEmpty)
+ XCTAssertEqual(h.detector.automaticTarget, target)
+ h.gate.isIdle = true
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ XCTAssertEqual(h.prompts.count, 1)
+ XCTAssertEqual(h.prompts.first?.cta, .record)
+ }
+
+ func testRejectionLoggingResetsOnTerminationStopAndSleep() {
+ var lines: [String] = []
+ let h = DetectorHarness(rejectionLogger: { lines.append($0) })
+ h.gate.isIdle = false
+ h.confirmZoom()
+ h.detector.handleWorkspaceEvent(.init(kind: .terminated, bundleIdentifier: "us.zoom.xos", processID: 100), at: h.clock.now())
+ h.confirmZoom()
+ XCTAssertEqual(lines.filter { $0.contains("reason=busy") }.count, 2)
+ h.detector.stop()
+ h.confirmZoom()
+ XCTAssertEqual(lines.filter { $0.contains("reason=busy") }.count, 3)
+ h.detector.disarmAndClearTransientState()
+ h.confirmZoom()
+ XCTAssertEqual(lines.filter { $0.contains("reason=busy") }.count, 4)
+ XCTAssertTrue(h.prompts.isEmpty)
+ }
+
+ func testRejectionLoggingIsIndependentPerCandidateAndReason() {
+ var lines: [String] = []
+ let h = DetectorHarness(rejectionLogger: { lines.append($0) })
+ h.gate.isIdle = false
+ h.confirmZoom(pid: 100)
+ h.confirmZoom(pid: 200)
+ XCTAssertEqual(lines.filter { $0.contains("reason=busy") }.count, 2)
+ h.advance(31)
+ for _ in 0..<2 {
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 200, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ }
+ XCTAssertEqual(lines.filter { $0.contains("reason=deadline") }.count, 1)
+ XCTAssertTrue(h.prompts.isEmpty)
+ }
+
func testRedactedZoomUsesAXMeetingTitleEvenWhenWorkplaceComesFirst() async {
let h = DetectorHarness()
h.windowProvider.axTitles = ["Zoom Workplace", "Zoom Meeting"]
diff --git a/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift b/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift
index 35f23b91..f967c868 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift
@@ -27,6 +27,8 @@ final class MeetingProviderOptionsTests: XCTestCase {
"parakeet-tdt-v3",
"parakeet-tdt-v99",
"whisper-tiny",
+ "fluid-parakeet-mini",
+ "fluid-parakeet-pico",
"",
]
for asrModel in unsupportedModels {
@@ -172,7 +174,7 @@ final class MeetingProviderOptionsTests: XCTestCase {
throw XCTSkip("Set FLUIDVOICE_MEETING_GERMAN_FIXTURE to a 16 kHz mono German WAV for model verification")
}
let file = try AVAudioFile(forReading: URL(fileURLWithPath: path), commonFormat: .pcmFormatFloat32, interleaved: false)
- XCTAssertEqual(file.processingFormat.sampleRate, 16000)
+ XCTAssertEqual(file.processingFormat.sampleRate, 16_000)
XCTAssertEqual(file.processingFormat.channelCount, 1)
let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length)))
try file.read(into: buffer)
@@ -186,7 +188,7 @@ final class MeetingProviderOptionsTests: XCTestCase {
XCTAssertTrue(output.result.text.lowercased().contains("morgen"))
XCTAssertTrue(output.result.text.lowercased().contains("freitag"))
XCTAssertFalse(output.words.isEmpty)
- XCTAssertTrue(output.words.allSatisfy { $0.start >= 0 && $0.end >= $0.start && $0.end <= Double(samples.count) / 16000 + 0.1 })
+ XCTAssertTrue(output.words.allSatisfy { $0.start >= 0 && $0.end >= $0.start && $0.end <= Double(samples.count) / 16_000 + 0.1 })
XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selected)
}
#endif
diff --git a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
index 005eb640..7d86c9f0 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
@@ -1,6 +1,7 @@
// Existing end-to-end fixture suite is kept together to share its setup and helpers.
// swiftlint:disable file_length
import AppKit
+import Combine
import CoreMedia
@testable import FluidVoice_Debug
import Foundation
@@ -11,6 +12,50 @@ import XCTest
// Existing recovery suite shares setup across crash and corruption scenarios.
// swiftlint:disable:next type_body_length
final class MeetingRecoveryTests: XCTestCase {
+ func testUnexpectedStopPublishesQuiescenceAfterDelayedAudioHandback() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ capture.startResult = MeetingCaptureStartResult(
+ tracks: [self.makeMicrophoneTrack(chunks: [])], firstPresentationTime: nil
+ )
+ let leasing = SuspendedHandbackASRActivityLeasing()
+ defer { leasing.resumeHandback() }
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: capture,
+ processing: StubProcessingController(),
+ audioArbiter: AudioActivityArbiter { leasing }
+ )
+ let session = try await coordinator.startRecording(configuration: self.makeConfiguration())
+ capture.emit(.interrupted(kind: .captureStoppedUnexpectedly, trackID: nil, detail: "Fixture stop"))
+ for _ in 0..<200 {
+ if leasing.handbackStarted { break }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ XCTAssertTrue(leasing.handbackStarted, "Unexpected stop must reach audio handback")
+ XCTAssertEqual(coordinator.state, .interrupted(session.id))
+ XCTAssertFalse(coordinator.isQuiescent, "Retry/settings refresh must wait for handback")
+ await self.drainCaptureEvents()
+ var notifications = 0
+ let subscription = coordinator.objectWillChange.sink { notifications += 1 }
+ defer { subscription.cancel() }
+ leasing.resumeHandback()
+ for _ in 0..<200 {
+ if coordinator.isQuiescent { break }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ XCTAssertTrue(coordinator.isQuiescent)
+ XCTAssertGreaterThan(notifications, 0, "Views must be told when retry/settings refresh becomes safe")
+ XCTAssertEqual(coordinator.state, .interrupted(session.id), "Completion must not restart recording")
+ XCTAssertEqual(capture.startCount, 1)
+ XCTAssertEqual(leasing.handbackCount, 1)
+ let saved = try await store.load(id: session.id)
+ XCTAssertEqual(saved?.state, .interrupted)
+ XCTAssertTrue(saved?.failures.isEmpty == true)
+ }
+
func testVoiceProcessingFallbackDoesNotDegradeHealthyRecording() async throws {
for deliverDuringStart in [false, true] {
let dir = self.makeTempDirectory()
@@ -2468,19 +2513,113 @@ final class MeetingRecoveryTests: XCTestCase {
try Data("{}".utf8).write(to: checkpointURL)
XCTAssertTrue(FileManager.default.fileExists(atPath: checkpointURL.path))
+ var lines: [String] = []
let coordinator = MeetingSessionCoordinator(
store: store,
capture: StubCaptureController(),
processing: StubProcessingController(),
- audioArbiter: StubArbiter()
+ audioArbiter: StubArbiter(),
+ processingLogger: { lines.append($0) }
)
await coordinator.ensureRestored()
let result = try await coordinator.retryProcessing()
+ XCTAssertEqual(lines.count, 1)
+ XCTAssertTrue(lines.first?.contains("outcome=completed") == true)
+ XCTAssertTrue(lines.first?.contains("stage=completed") == true)
+ XCTAssertFalse(lines.first?.contains("errorCode=") == true)
XCTAssertEqual(result.state, .completed)
XCTAssertFalse(FileManager.default.fileExists(atPath: checkpointURL.path))
}
+ func testProcessingDiagnosticsPreserveFailureAndTranscriptAcrossRetries() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ var session = self.makeCorrectionSession(state: .interrupted).session
+ session.title = "Private meeting title"
+ session.transcriptSegments[0].text = "Private transcript content"
+ try await store.create(session)
+ let message = "Missing model\n" + String(repeating: "x", count: 1000)
+ let error = NSError(domain: "MeetingProbe\r", code: 42, userInfo: [NSLocalizedDescriptionKey: message])
+ var lines: [String] = []
+ let arbiter = StubArbiter()
+ let processing = DiagnosticFailingProcessingController(error: error)
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: processing,
+ audioArbiter: arbiter,
+ processingLogger: { lines.append($0) }
+ )
+ await coordinator.ensureRestored()
+ for attempt in 1...2 {
+ do {
+ _ = try await coordinator.retryProcessing(sessionID: session.id)
+ XCTFail("Expected the processing error")
+ } catch {
+ XCTAssertEqual((error as NSError).code, 42)
+ }
+ XCTAssertEqual(lines.count, attempt, "Exactly one terminal diagnostic per attempt")
+ let line = try XCTUnwrap(lines.last)
+ XCTAssertTrue(line.contains("outcome=failed"))
+ XCTAssertTrue(line.contains("stage=transcribing"))
+ XCTAssertTrue(line.contains("errorCode=MeetingProbe .42"))
+ XCTAssertTrue(line.contains("elapsedMs="))
+ XCTAssertLessThan(line.count, 800)
+ XCTAssertFalse(line.contains("\n"))
+ XCTAssertFalse(line.contains("\r"))
+ XCTAssertFalse(line.contains(session.title))
+ XCTAssertFalse(line.contains("Private transcript content"))
+ let saved = try await store.load(id: session.id)
+ let persisted = try XCTUnwrap(saved)
+ XCTAssertEqual(persisted.state, .failed)
+ XCTAssertEqual(persisted.failures.last?.message, message, "Only log details are shortened")
+ XCTAssertEqual(persisted.transcriptSegments, session.transcriptSegments)
+ XCTAssertEqual(persisted.audioTracks, session.audioTracks)
+ XCTAssertEqual(arbiter.releaseCount, attempt)
+ }
+ XCTAssertEqual(arbiter.acquireCount, 2)
+ processing.emitLateProgress(.completed)
+ XCTAssertEqual(lines.count, 2, "Stale progress must not produce a second outcome")
+ XCTAssertEqual(coordinator.activeSession?.state, .failed)
+ XCTAssertEqual(coordinator.activeSession?.transcriptSegments, session.transcriptSegments)
+ }
+
+ func testProcessingCancellationLogsWithoutAddingFailureOrLosingTranscript() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let session = self.makeCorrectionSession(state: .interrupted).session
+ try await store.create(session)
+ var lines: [String] = []
+ let arbiter = StubArbiter()
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: DiagnosticFailingProcessingController(error: CancellationError()),
+ audioArbiter: arbiter,
+ processingLogger: { lines.append($0) }
+ )
+ await coordinator.ensureRestored()
+ do {
+ _ = try await coordinator.retryProcessing(sessionID: session.id)
+ XCTFail("Expected cancellation")
+ } catch {
+ XCTAssertTrue(error is CancellationError)
+ }
+ XCTAssertEqual(lines.count, 1)
+ XCTAssertTrue(lines.first?.contains("outcome=cancelled") == true)
+ XCTAssertFalse(lines.first?.contains("errorCode=") == true)
+ let saved = try await store.load(id: session.id)
+ let persisted = try XCTUnwrap(saved)
+ XCTAssertEqual(persisted.state, .interrupted)
+ XCTAssertTrue(persisted.failures.isEmpty)
+ XCTAssertEqual(persisted.transcriptSegments, session.transcriptSegments)
+ XCTAssertEqual(persisted.audioTracks, session.audioTracks)
+ XCTAssertEqual(arbiter.releaseCount, 1)
+ }
+
// MARK: - Slice 3, test 4: checkpoint survives a failed retry
func testCheckpointSurvivesProcessingFailure() async throws {
@@ -4783,6 +4922,27 @@ private final class StubProcessingController: MeetingProcessingControlling {
}
}
+@MainActor
+private final class DiagnosticFailingProcessingController: MeetingProcessingControlling {
+ private let error: Error
+ private var lastProgress: (@MainActor (MeetingProcessingStage) -> Void)?
+
+ init(error: Error) { self.error = error }
+
+ func emitLateProgress(_ stage: MeetingProcessingStage) { self.lastProgress?(stage) }
+
+ func process(
+ session: MeetingSession,
+ sessionDirectory: URL,
+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void
+ ) async throws -> MeetingProcessingResult {
+ self.lastProgress = progress
+ progress(.identifyingSpeakers)
+ progress(.transcribing)
+ throw self.error
+ }
+}
+
private struct ProcessingFailure: Error {}
@MainActor
@@ -4873,12 +5033,13 @@ private final class GatedProcessingController: MeetingProcessingControlling {
@MainActor
private final class StubArbiter: MeetingAudioActivityArbitrating {
private(set) var acquireCount = 0
+ private(set) var releaseCount = 0
func acquireMeetingCapture() async throws -> MeetingAudioActivityLease {
self.acquireCount += 1
return MeetingAudioActivityLease(id: UUID())
}
- func release(_ lease: MeetingAudioActivityLease) async {}
+ func release(_ lease: MeetingAudioActivityLease) async { self.releaseCount += 1 }
}
/// Records acquire/release calls without touching a real ASRService.
diff --git a/Tests/FluidDictationIntegrationTests/ParakeetArchiveDownloaderTests.swift b/Tests/FluidDictationIntegrationTests/ParakeetArchiveDownloaderTests.swift
new file mode 100644
index 00000000..81c42d34
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/ParakeetArchiveDownloaderTests.swift
@@ -0,0 +1,871 @@
+import CryptoKit
+import Darwin
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+final nonisolated class ParakeetArchiveDownloaderTests: XCTestCase {
+ func testValidTarPublishesCompleteModelWithRealByteProgressAndPreservesSiblings() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let recorder = ProgressRecorder()
+ let result = try await fixture.install(progress: recorder.record)
+ XCTAssertEqual(result, fixture.target)
+ XCTAssertTrue(ParakeetArchiveDownloader.artifactsAreComplete(at: result, descriptor: fixture.descriptor))
+ XCTAssertTrue(fixture.descriptor.artifactsAreComplete(at: result))
+ XCTAssertEqual(try Data(contentsOf: result.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName)), try Data(XCTUnwrap(fixture.descriptor.archiveSHA256).utf8))
+ XCTAssertEqual(recorder.values.filter { $0.phase == .downloading }.compactMap(\.fractionCompleted), [0.5, 1])
+ XCTAssertEqual(recorder.values.last?.phase, .loading)
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testInstalledCompleteCacheSkipsNetwork() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ _ = try await fixture.install()
+ let result = try await ParakeetArchiveDownloader.ensurePresent(descriptor: fixture.descriptor, in: fixture.models, transport: { _, _ in
+ XCTFail("An installed model must not use the network")
+ throw ProbeFailure.injected
+ })
+ XCTAssertEqual(result, fixture.target)
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testNewRevisionRejectsOldCompleteCacheAndPublishesOnlyAfterOwnedRemoval() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ XCTAssertFalse(newer.descriptor.artifactsAreComplete(at: old.target))
+ XCTAssertFalse(ParakeetArchiveDownloader.artifactsAreComplete(at: old.target, descriptor: newer.descriptor))
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(descriptor: newer.descriptor, in: old.models, transport: { _, _ in
+ XCTFail("The downloader must preserve an existing target until its caller admits removal")
+ throw ProbeFailure.injected
+ })
+ XCTFail("An old revision must never be accepted as the new installed model")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case .targetExists = error else { return XCTFail("Expected actionable existing-cache failure") }
+ }
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ // Mirror the provider's admitted removal of this exact stale model folder.
+ // The archive helper itself never removes an existing installed target.
+ try FileManager.default.removeItem(at: old.target)
+ let result = try await ParakeetArchiveDownloader.ensurePresent(descriptor: newer.descriptor, in: old.models, transport: { _, progress in
+ try newer.transport(progress)
+ })
+ XCTAssertEqual(result, old.target)
+ XCTAssertTrue(newer.descriptor.artifactsAreComplete(at: result))
+ XCTAssertFalse(old.descriptor.artifactsAreComplete(at: result))
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testMissingWrongOversizedAndSymlinkRevisionMarkersCannotClaimInstalledCache() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ _ = try await fixture.install()
+ let marker = fixture.target.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName)
+ for contents: Data? in [nil, Data(String(repeating: "0", count: 64).utf8), Data(repeating: 1, count: 65)] {
+ try FileManager.default.removeItem(at: marker)
+ if let contents { try contents.write(to: marker) }
+ XCTAssertFalse(fixture.descriptor.artifactsAreComplete(at: fixture.target))
+ XCTAssertFalse(ParakeetArchiveDownloader.artifactsAreComplete(at: fixture.target, descriptor: fixture.descriptor))
+ if contents == nil { try fixture.descriptor.writeInstallationRevision(at: fixture.target) }
+ }
+ try FileManager.default.removeItem(at: marker)
+ let external = fixture.base.appendingPathComponent("external-revision")
+ try Data(XCTUnwrap(fixture.descriptor.archiveSHA256).utf8).write(to: external)
+ try FileManager.default.createSymbolicLink(at: marker, withDestinationURL: external)
+ XCTAssertFalse(fixture.descriptor.artifactsAreComplete(at: fixture.target))
+ XCTAssertFalse(ParakeetArchiveDownloader.artifactsAreComplete(at: fixture.target, descriptor: fixture.descriptor))
+ XCTAssertTrue(ParakeetSpeechModelCatalog.v2.installationRevisionMatches(at: fixture.base))
+ XCTAssertTrue(ParakeetSpeechModelCatalog.v3.installationRevisionMatches(at: fixture.base))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testExplicitUpdateValidatesUnpublishedStageThenSwapsAndRemovesOldFiles() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ let result = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ stageValidator: { stage in
+ XCTAssertNotEqual(stage, old.target)
+ XCTAssertTrue(newer.descriptor.artifactsAreComplete(at: stage))
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target), "Old weights stay usable during validation")
+ }, transport: { _, progress in try newer.transport(progress) }
+ )
+ XCTAssertEqual(result, old.target)
+ XCTAssertTrue(newer.descriptor.artifactsAreComplete(at: result))
+ XCTAssertFalse(old.descriptor.artifactsAreComplete(at: result))
+ XCTAssertEqual(try String(contentsOf: result.appendingPathComponent("Encoder-1.mlmodelc/weights/weight.bin"), encoding: .utf8), "new trained checkpoint")
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testUpdateValidatorFailureAndCancellationPreserveInstalledOldRevision() async throws {
+ for cancel in [false, true] {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ stageValidator: { _ in
+ if cancel { withUnsafeCurrentTask { $0?.cancel() } } else { throw ProbeFailure.injected }
+ }, transport: { _, progress in try newer.transport(progress) }
+ )
+ XCTFail("Failed or cancelled Core ML validation must not publish")
+ } catch {}
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ XCTAssertEqual(try String(contentsOf: old.target.appendingPathComponent("Encoder-1.mlmodelc/weights/weight.bin"), encoding: .utf8), "fixture")
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+ }
+
+ func testUpdateTransferFailureAndBadChecksumPreserveOldFiles() async throws {
+ for badChecksum in [false, true] {
+ let old = try Fixture()
+ let newer = try Fixture(checksum: badChecksum ? String(repeating: "0", count: 64) : nil, artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ await self.expectFailure {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(descriptor: newer.descriptor, in: old.models, replaceExisting: true, transport: { _, progress in
+ if !badChecksum { throw ProbeFailure.injected }
+ return try newer.transport(progress)
+ })
+ }
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+ }
+
+ func testUpdateCancellationDuringTransferKeepsOldModel() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ let started = Started()
+ let task = Task {
+ try await ParakeetArchiveDownloader.ensurePresent(descriptor: newer.descriptor, in: old.models, replaceExisting: true, transport: { _, _ in
+ await started.signal()
+ try await Task.sleep(for: .seconds(30))
+ throw ProbeFailure.injected
+ })
+ }
+ await started.wait()
+ task.cancel()
+ do { _ = try await task.value; XCTFail("Expected cancellation") } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") }
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ try old.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testUpdateIncompleteArchivePreservesOldModel() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(omitLastArtifact: true, artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ await self.expectFailure {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(descriptor: newer.descriptor, in: old.models, replaceExisting: true, transport: { _, progress in try newer.transport(progress) })
+ }
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testCancellationAtCompletedArchiveHandoffCleansReadyAndKeepsOldModel() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ let directory = old.models.appendingPathComponent(".compact-downloads/\(newer.descriptor.folderName)", isDirectory: true)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let ready = directory.appendingPathComponent("ready-\(getpid())-\(UUID().uuidString).tar")
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ transport: { url, _ in
+ try newer.archive.write(to: ready)
+ let response = try XCTUnwrap(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil))
+ // Cancel after a completed handoff exists, before its URL reaches
+ // the installer's first cancellation check.
+ withUnsafeCurrentTask { $0?.cancel() }
+ return (ready, response)
+ }
+ )
+ XCTFail("Expected cancellation at the completed archive handoff")
+ } catch is CancellationError {} catch { XCTFail("Expected CancellationError, got \(error)") }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: ready.path))
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ XCTAssertEqual(try String(contentsOf: old.target.appendingPathComponent("Encoder-1.mlmodelc/weights/weight.bin"), encoding: .utf8), "fixture")
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testCompetingUpdatesPublishOnceAndRejectStaleOriginalIdentity() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ let gate = UpdateValidationGate()
+ let operation: @Sendable () async throws -> Bool = {
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ stageValidator: { _ in await gate.enter() },
+ transport: { _, progress in try newer.transport(progress) }
+ )
+ return true
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case .targetChanged = error else { throw error }
+ return false
+ }
+ }
+ let first = Task { try await operation() }
+ let second = Task { try await operation() }
+ let deadline = ContinuousClock.now + .seconds(3)
+ while await gate.count < 2, ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ let arrived = await gate.count
+ await gate.releaseAll()
+ XCTAssertEqual(arrived, 2, "Both stages must validate before either publishes")
+ let results = try await [first.value, second.value]
+ XCTAssertEqual(results.filter { $0 }.count, 1)
+ XCTAssertTrue(newer.descriptor.artifactsAreComplete(at: old.target))
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testPostCommitCleanupFailureReportsInstalledNewAndRetainedOldFiles() async throws {
+ guard geteuid() != 0 else { throw XCTSkip("Filesystem permission failure requires a non-root user") }
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ stageValidator: { stage in
+ let ownedStage = stage.deletingLastPathComponent().deletingLastPathComponent()
+ try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: ownedStage.path)
+ }, transport: { _, progress in try newer.transport(progress) }
+ )
+ XCTFail("Cleanup failure must not be returned as success")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case let .replacementCleanupFailed(installed, retainedOld) = error else { return XCTFail("Expected post-commit cleanup failure, got \(error)") }
+ XCTAssertEqual(installed, old.target)
+ XCTAssertTrue(newer.descriptor.artifactsAreComplete(at: installed))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: retainedOld.path), "A post-commit cleanup error names the owned remainder, not a rollback")
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: retainedOld.path)
+ try FileManager.default.removeItem(at: retainedOld)
+ }
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testUpdateCleanupFailureNamesRetainedArchiveWhenStageRemovalSucceeds() async throws {
+ guard geteuid() != 0 else { throw XCTSkip("Filesystem permission failure requires a non-root user") }
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ let directory = newer.base.appendingPathComponent("owned-ready", isDirectory: true)
+ defer {
+ try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path)
+ old.cleanup()
+ newer.cleanup()
+ }
+ _ = try await old.install()
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)
+ let ready = directory.appendingPathComponent("archive.tar")
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ transport: { url, _ in
+ try newer.archive.write(to: ready)
+ try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: directory.path)
+ // Reject this handoff before moving it into staging. Its parent
+ // blocks archive deletion while the independent stage can be removed.
+ return try (ready, XCTUnwrap(HTTPURLResponse(url: url, statusCode: 500, httpVersion: nil, headerFields: nil)))
+ }
+ )
+ XCTFail("Expected an update failure with retained archive cleanup")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case let .updateFailedWithCleanup(_, installed, temporaryFiles) = error else {
+ return XCTFail("Expected failed-update cleanup error, got \(error)")
+ }
+ XCTAssertEqual(installed, old.target)
+ XCTAssertEqual(temporaryFiles, ready)
+ XCTAssertTrue(FileManager.default.fileExists(atPath: temporaryFiles.path))
+ }
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ XCTAssertEqual(try String(contentsOf: old.target.appendingPathComponent("Encoder-1.mlmodelc/weights/weight.bin"), encoding: .utf8), "fixture")
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testUpdateRejectsChangedTargetIdentityEvenWithTheSameRevision() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ stageValidator: { _ in
+ let replacement = old.models.appendingPathComponent("competing-target")
+ try FileManager.default.copyItem(at: old.target, to: replacement)
+ try FileManager.default.removeItem(at: old.target)
+ try FileManager.default.moveItem(at: replacement, to: old.target)
+ }, transport: { _, progress in try newer.transport(progress) }
+ )
+ XCTFail("A replaced directory must not be overwritten")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case .targetChanged = error else { return XCTFail("Expected targetChanged") }
+ }
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ try old.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testUpdateRejectsRevisionChangedDuringValidation() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new trained checkpoint")
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ let competingHash = String(repeating: "a", count: 64)
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ stageValidator: { _ in
+ try Data(competingHash.utf8).write(to: old.target.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName))
+ }, transport: { _, progress in try newer.transport(progress) }
+ )
+ XCTFail("A changed checkpoint must be preserved")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case .targetChanged = error else { return XCTFail("Expected targetChanged") }
+ }
+ XCTAssertEqual(old.descriptor.installedArchiveSHA256(at: old.target), competingHash)
+ try old.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testRevisionWriteFailureCleansStageAndNeverPublishes() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ await self.expectFailure {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: fixture.descriptor,
+ in: fixture.models,
+ transport: { _, progress in try fixture.transport(progress) },
+ revisionWriter: { _, _ in throw CocoaError(.fileWriteNoPermission) }
+ )
+ }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testCancellationAfterRevisionWriteCleansStageWithoutPublishing() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: fixture.descriptor,
+ in: fixture.models,
+ transport: { _, progress in try fixture.transport(progress) },
+ revisionWriter: { directory, descriptor in
+ try descriptor.writeInstallationRevision(at: directory)
+ withUnsafeCurrentTask { $0?.cancel() }
+ }
+ )
+ XCTFail("Expected cancellation before publication")
+ } catch is CancellationError {} catch { XCTFail("Expected CancellationError, got \(error)") }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testArchiveCannotSupplyItsOwnRevisionMarker() async throws {
+ let marker = "fluid-parakeet-mini-coreml/" + ParakeetSpeechModelCatalog.installationRevisionFileName
+ let fixture = try Fixture(extraEntry: Entry(path: marker, data: Data(String(repeating: "0", count: 64).utf8)))
+ defer { fixture.cleanup() }
+ await self.expectFailure { _ = try await fixture.install() }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testWrongHashDoesNotExtractOrPublish() async throws {
+ let fixture = try Fixture(checksum: String(repeating: "0", count: 64))
+ defer { fixture.cleanup() }
+ await self.expectFailure { _ = try await fixture.install() }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testMissingCompiledArtifactDoesNotPublish() async throws {
+ let fixture = try Fixture(omitLastArtifact: true)
+ defer { fixture.cleanup() }
+ await self.expectFailure { _ = try await fixture.install() }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testWrongArchiveRootCannotWriteASibling() async throws {
+ let fixture = try Fixture(rootName: "parakeet-tdt-0.6b-v3-coreml")
+ defer { fixture.cleanup() }
+ await self.expectFailure { _ = try await fixture.install() }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testTraversalAndSymlinkEntriesAreRejected() async throws {
+ for entry in [Entry(path: "../escape", data: Data("bad".utf8)), Entry(path: "fluid-parakeet-mini-coreml/link", type: 50)] {
+ let fixture = try Fixture(extraEntry: entry)
+ defer { fixture.cleanup() }
+ await self.expectFailure { _ = try await fixture.install() }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.base.appendingPathComponent("escape").path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+ }
+
+ func testCancellationDuringTransferCleansOwnedStageAndPreservesSiblings() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let started = Started()
+ let task = Task {
+ try await ParakeetArchiveDownloader.ensurePresent(descriptor: fixture.descriptor, in: fixture.models, transport: { _, _ in
+ await started.signal()
+ try await Task.sleep(for: .seconds(30))
+ throw ProbeFailure.injected
+ })
+ }
+ await started.wait()
+ task.cancel()
+ do {
+ _ = try await task.value
+ XCTFail("Expected transfer cancellation")
+ } catch is CancellationError {} catch { XCTFail("Expected CancellationError, got \(error)") }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testCancellationAfterHashBeforeExtractionNeverExposesPartialTarget() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ do {
+ _ = try await fixture.install(progress: { progress in
+ if progress.phase == .optimizing { withUnsafeCurrentTask { $0?.cancel() } }
+ })
+ XCTFail("Expected install cancellation")
+ } catch is CancellationError {} catch { XCTFail("Expected CancellationError, got \(error)") }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testExistingIncompleteTargetAndCompetingPublishedTargetAreNeverOverwritten() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ try FileManager.default.createDirectory(at: fixture.target, withIntermediateDirectories: false)
+ let marker = fixture.target.appendingPathComponent("keep")
+ try Data("keep".utf8).write(to: marker)
+ await self.expectFailure { _ = try await fixture.install() }
+ XCTAssertEqual(try String(contentsOf: marker, encoding: .utf8), "keep")
+ try FileManager.default.removeItem(at: fixture.target)
+ await self.expectFailure {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(descriptor: fixture.descriptor, in: fixture.models, transport: { _, progress in
+ try FileManager.default.createDirectory(at: fixture.target, withIntermediateDirectories: false)
+ try Data("keep".utf8).write(to: marker)
+ return try fixture.transport(progress)
+ })
+ }
+ XCTAssertEqual(try String(contentsOf: marker, encoding: .utf8), "keep")
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testBadHTTPResponseAndWrongLengthCleanDownloadedFile() async throws {
+ for status in [404, 200] {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ await self.expectFailure {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(descriptor: fixture.descriptor, in: fixture.models, transport: { url, _ in
+ let file = fixture.base.appendingPathComponent("returned-download")
+ try Data("short response".utf8).write(to: file)
+ let response = try XCTUnwrap(HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil))
+ return (file, response)
+ })
+ }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.base.appendingPathComponent("returned-download").path))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+ }
+
+ func testSymlinkCacheRootAndNestedInstalledLinksAreRejected() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let alias = fixture.base.appendingPathComponent("alias")
+ try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: fixture.models)
+ await self.expectFailure { _ = try await ParakeetArchiveDownloader.ensurePresent(descriptor: fixture.descriptor, in: alias, transport: { _, _ in
+ XCTFail("A symlink cache root must not download")
+ throw ProbeFailure.injected
+ }) }
+ _ = try await fixture.install()
+ let link = fixture.target.appendingPathComponent("unexpected-link")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: fixture.models.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml"))
+ XCTAssertFalse(ParakeetArchiveDownloader.artifactsAreComplete(at: fixture.target, descriptor: fixture.descriptor))
+ await self.expectFailure { _ = try await fixture.install() }
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testPinnedManifestIsVerifiedBeforeRevisionWriteAndStageValidation() async throws {
+ let fixture = try Fixture(includeManifest: true)
+ defer { fixture.cleanup() }
+ let calls = ProgressRecorder()
+ let result = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: fixture.descriptor,
+ in: fixture.models,
+ stageValidator: { stage in
+ XCTAssertTrue(fixture.descriptor.artifactsAreComplete(at: stage))
+ calls.record(.loading)
+ },
+ transport: { _, progress in try fixture.transport(progress) },
+ revisionWriter: { stage, descriptor in
+ try ParakeetArchiveInstaller.verify(folder: stage, folderName: descriptor.folderName, manifestSHA256: XCTUnwrap(descriptor.manifestSHA256))
+ calls.record(.optimizing)
+ try descriptor.writeInstallationRevision(at: stage)
+ }
+ )
+ XCTAssertEqual(result, fixture.target)
+ XCTAssertEqual(calls.values.count, 2)
+ XCTAssertEqual(fixture.descriptor.installedManifestSHA256(at: result), fixture.descriptor.manifestSHA256)
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testCachedArchiveMarkerCannotBypassChangedManifestPin() async throws {
+ let fixture = try Fixture(includeManifest: true)
+ defer { fixture.cleanup() }
+ _ = try await fixture.install()
+ var changed = fixture.descriptor
+ changed.manifestSHA256 = String(repeating: "0", count: 64)
+ XCTAssertFalse(ParakeetArchiveDownloader.artifactsAreComplete(at: fixture.target, descriptor: changed))
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: changed,
+ in: fixture.models,
+ replaceExisting: true,
+ transport: { _, progress in try fixture.transport(progress) }
+ )
+ XCTFail("A matching archive marker cannot bypass a mismatched manifest pin")
+ } catch let error as ParakeetArchiveInstaller.InstallError {
+ XCTAssertEqual(error, .manifestMismatch)
+ }
+ XCTAssertTrue(ParakeetArchiveDownloader.artifactsAreComplete(at: fixture.target, descriptor: fixture.descriptor))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testBadPinnedManifestOrPayloadNeverWritesRevisionOrValidatesAndPreservesOldModel() async throws {
+ for tamperPayload in [false, true] {
+ let old = try Fixture()
+ let newer = try Fixture(
+ artifactContents: "new",
+ includeManifest: true,
+ tamperManifestFile: tamperPayload,
+ manifestHashOverride: tamperPayload ? nil : String(repeating: "0", count: 64)
+ )
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ let calls = ProgressRecorder()
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ stageValidator: { _ in calls.record(.loading) },
+ transport: { _, progress in try newer.transport(progress) },
+ revisionWriter: { _, _ in calls.record(.optimizing) }
+ )
+ XCTFail("Expected pinned manifest/payload rejection")
+ } catch let error as ParakeetArchiveInstaller.InstallError {
+ if tamperPayload {
+ guard case .fileMismatch = error else { return XCTFail("Expected payload mismatch, got \(error)") }
+ } else {
+ XCTAssertEqual(error, .manifestMismatch)
+ }
+ }
+ XCTAssertTrue(calls.values.isEmpty)
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ XCTAssertEqual(try String(contentsOf: old.target.appendingPathComponent("Encoder-1.mlmodelc/weights/weight.bin"), encoding: .utf8), "fixture")
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+ }
+
+ func testLowOrUnknownCapacityRefusesBeforeTransferAndKeepsExistingModel() async throws {
+ let old = try Fixture()
+ let newer = try Fixture(artifactContents: "new", includeManifest: true)
+ defer { old.cleanup(); newer.cleanup() }
+ _ = try await old.install()
+ let required = newer.descriptor.expectedDownloadBytes * 2 + 32 * 1024 * 1024
+ for available in [Int64(0), required - 1, -1] {
+ let calls = ProgressRecorder()
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: newer.descriptor,
+ in: old.models,
+ replaceExisting: true,
+ stageValidator: { _ in calls.record(.loading) },
+ transport: { _, progress in calls.record(.preparingDownload); return try newer.transport(progress) },
+ capacityReader: { directory in
+ XCTAssertEqual(directory, old.models)
+ XCTAssertFalse(Thread.isMainThread)
+ return available
+ },
+ revisionWriter: { _, _ in calls.record(.optimizing) }
+ )
+ XCTFail("Expected capacity refusal")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ if available < 0 {
+ guard case .capacityUnavailable = error else { return XCTFail("Expected unknown-capacity error, got \(error)") }
+ } else {
+ guard case let .insufficientSpace(needed, free) = error else { return XCTFail("Expected low-space error, got \(error)") }
+ XCTAssertEqual(needed, required)
+ XCTAssertEqual(free, available)
+ }
+ }
+ XCTAssertTrue(calls.values.isEmpty)
+ XCTAssertTrue(old.descriptor.artifactsAreComplete(at: old.target))
+ XCTAssertEqual(try String(contentsOf: old.target.appendingPathComponent("Encoder-1.mlmodelc/weights/weight.bin"), encoding: .utf8), "fixture")
+ try old.assertPreservedSiblingsAndNoStage()
+ try newer.assertPreservedSiblingsAndNoStage()
+ }
+ }
+
+ func testCapacityReaderFailureHasDefinedErrorAndNeverStartsTransfer() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ do {
+ _ = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: fixture.descriptor,
+ in: fixture.models,
+ transport: { _, _ in XCTFail("Capacity must be checked before network"); throw ProbeFailure.injected },
+ capacityReader: { _ in throw ProbeFailure.injected }
+ )
+ XCTFail("Expected unknown-capacity refusal")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case .capacityUnavailable = error else { return XCTFail("Expected capacity error, got \(error)") }
+ }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.target.path))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ func testExactReservedCapacityAllowsFirstInstallOffMain() async throws {
+ let fixture = try Fixture(includeManifest: true)
+ defer { fixture.cleanup() }
+ let result = try await ParakeetArchiveDownloader.ensurePresent(
+ descriptor: fixture.descriptor,
+ in: fixture.models,
+ transport: { _, progress in try fixture.transport(progress) },
+ capacityReader: { _ in
+ XCTAssertFalse(Thread.isMainThread)
+ return fixture.descriptor.expectedDownloadBytes * 2 + 32 * 1024 * 1024
+ }
+ )
+ XCTAssertTrue(ParakeetArchiveDownloader.artifactsAreComplete(at: result, descriptor: fixture.descriptor))
+ try fixture.assertPreservedSiblingsAndNoStage()
+ }
+
+ private func expectFailure(_ body: () async throws -> Void) async {
+ do { try await body(); XCTFail("Expected archive installation to fail") } catch {}
+ }
+
+ private enum ProbeFailure: Error { case injected }
+
+ private actor Started {
+ private var started = false
+ private var continuation: CheckedContinuation<Void, Never>?
+ func signal() { self.started = true; self.continuation?.resume(); self.continuation = nil }
+ func wait() async {
+ if self.started { return }
+ await withCheckedContinuation { self.continuation = $0 }
+ }
+ }
+
+ private actor UpdateValidationGate {
+ private(set) var count = 0
+ private var continuations: [CheckedContinuation<Void, Never>] = []
+ private var released = false
+ func enter() async {
+ self.count += 1
+ guard !self.released else { return }
+ await withCheckedContinuation { self.continuations.append($0) }
+ }
+
+ func releaseAll() {
+ self.released = true
+ let pending = self.continuations
+ self.continuations = []
+ for continuation in pending {
+ continuation.resume()
+ }
+ }
+ }
+
+ private final class ProgressRecorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private var progress: [ModelPreparationProgress] = []
+ var values: [ModelPreparationProgress] { self.lock.withLock { self.progress } }
+ func record(_ value: ModelPreparationProgress) { self.lock.withLock { self.progress.append(value) } }
+ }
+
+ private struct Entry {
+ let path: String
+ var data = Data()
+ var type: UInt8 = 48
+ }
+
+ private struct Fixture: Sendable {
+ let base: URL
+ let models: URL
+ let descriptor: ParakeetSpeechModelCatalog.Descriptor
+ let archive: Data
+ var target: URL { self.descriptor.cacheDirectory(in: self.models) }
+
+ init(
+ checksum: String? = nil,
+ omitLastArtifact: Bool = false,
+ rootName: String = "fluid-parakeet-mini-coreml",
+ extraEntry: Entry? = nil,
+ artifactContents: String = "fixture",
+ includeManifest: Bool = false,
+ tamperManifestFile: Bool = false,
+ manifestHashOverride: String? = nil
+ ) throws {
+ self.base = FileManager.default.temporaryDirectory.appendingPathComponent("ParakeetArchiveDownloaderTests-" + UUID().uuidString, isDirectory: true)
+ self.models = self.base.appendingPathComponent("Models", isDirectory: true)
+ try FileManager.default.createDirectory(at: self.models, withIntermediateDirectories: true)
+ for name in ["parakeet-tdt-0.6b-v2-coreml", "parakeet-tdt-0.6b-v3-coreml", "fluid-parakeet-pico-coreml", "parakeet-eou-streaming"] {
+ let sibling = self.models.appendingPathComponent(name, isDirectory: true)
+ try FileManager.default.createDirectory(at: sibling, withIntermediateDirectories: false)
+ try Data(name.utf8).write(to: sibling.appendingPathComponent("keep"))
+ }
+ let source = ParakeetSpeechModelCatalog.mini
+ var entries = source.requiredModelNames.flatMap { name in
+ ["coremldata.bin", "metadata.json", "weights/weight.bin"].map {
+ Entry(path: "\(rootName)/\(name)/\($0)", data: Data(artifactContents.utf8))
+ }
+ }
+ if omitLastArtifact { entries.removeLast() }
+ entries.append(Entry(path: "\(rootName)/\(source.vocabularyFile)", data: Data("{}".utf8)))
+ if let extraEntry { entries.append(extraEntry) }
+ var manifestSHA256: String?
+ if includeManifest {
+ let manifest: [String: Any] = [
+ "folderName": rootName,
+ "totalSize": entries.reduce(0) { $0 + $1.data.count },
+ "files": entries.map { entry in
+ [
+ "path": String(entry.path.dropFirst(rootName.count + 1)),
+ "size": entry.data.count,
+ "sha256": SHA256.hash(data: entry.data).map { String(format: "%02x", $0) }.joined(),
+ ] as [String: Any]
+ },
+ ]
+ let data = try JSONSerialization.data(withJSONObject: manifest, options: [.sortedKeys])
+ manifestSHA256 = manifestHashOverride ?? SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+ if tamperManifestFile { entries[0].data = Data("tampered".utf8) }
+ entries.append(Entry(path: "\(rootName)/manifest.json", data: data))
+ }
+ self.archive = Self.tar(entries)
+ self.descriptor = .init(
+ modelID: source.modelID,
+ variant: source.variant,
+ folderName: source.folderName,
+ expectedDownloadBytes: Int64(self.archive.count),
+ archiveURL: source.archiveURL,
+ archiveSHA256: checksum ?? SHA256.hash(data: self.archive).map { String(format: "%02x", $0) }.joined(),
+ requiredModelNames: source.requiredModelNames,
+ vocabularyFile: source.vocabularyFile,
+ displayName: source.displayName,
+ humanReadableName: source.humanReadableName,
+ languageSupport: source.languageSupport,
+ supportedLanguageCodes: source.supportedLanguageCodes,
+ downloadSize: source.downloadSize,
+ cardDescription: source.cardDescription,
+ performanceRatings: source.performanceRatings,
+ manifestSHA256: manifestSHA256
+ )
+ }
+
+ func install(progress: @escaping @Sendable (ModelPreparationProgress) -> Void = { _ in }) async throws -> URL {
+ try await ParakeetArchiveDownloader.ensurePresent(descriptor: self.descriptor, in: self.models, progressHandler: progress, transport: { _, progress in
+ try self.transport(progress)
+ })
+ }
+
+ func transport(_ progress: @Sendable (Int64, Int64) -> Void) throws -> (URL, URLResponse) {
+ let file = self.base.appendingPathComponent("download-" + UUID().uuidString)
+ try self.archive.write(to: file)
+ progress(Int64(self.archive.count / 2), -1)
+ progress(Int64(self.archive.count), Int64(self.archive.count))
+ let url = try XCTUnwrap(self.descriptor.archiveURL)
+ return try (file, XCTUnwrap(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)))
+ }
+
+ func assertPreservedSiblingsAndNoStage(file: StaticString = #filePath, line: UInt = #line) throws {
+ for name in ["parakeet-tdt-0.6b-v2-coreml", "parakeet-tdt-0.6b-v3-coreml", "fluid-parakeet-pico-coreml", "parakeet-eou-streaming"] {
+ XCTAssertEqual(try String(contentsOf: self.models.appendingPathComponent("\(name)/keep"), encoding: .utf8), name, file: file, line: line)
+ }
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: self.models.path).filter { $0.hasSuffix(".staging") }, [], file: file, line: line)
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: self.base.path).filter { $0.hasPrefix("download-") }, [], file: file, line: line)
+ }
+
+ func cleanup() { try? FileManager.default.removeItem(at: self.base) }
+
+ private static func tar(_ entries: [Entry]) -> Data {
+ var archive = Data()
+ for entry in entries {
+ var header = [UInt8](repeating: 0, count: 512)
+ for (offset, byte) in entry.path.utf8.prefix(100).enumerated() {
+ header[offset] = byte
+ }
+ let size = String(format: "%011o", entry.data.count)
+ for (offset, byte) in size.utf8.enumerated() {
+ header[124 + offset] = byte
+ }
+ for offset in 148..<156 {
+ header[offset] = 32
+ }
+ header[156] = entry.type
+ let checksum = String(format: "%06o", header.reduce(0) { $0 + Int($1) })
+ for (offset, byte) in checksum.utf8.enumerated() {
+ header[148 + offset] = byte
+ }
+ header[154] = 0; header[155] = 32
+ archive.append(contentsOf: header)
+ archive.append(entry.data)
+ archive.append(Data(repeating: 0, count: (512 - entry.data.count % 512) % 512))
+ }
+ archive.append(Data(repeating: 0, count: 1024))
+ return archive
+ }
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/ParakeetArchiveInstallerTests.swift b/Tests/FluidDictationIntegrationTests/ParakeetArchiveInstallerTests.swift
new file mode 100644
index 00000000..72c8a698
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/ParakeetArchiveInstallerTests.swift
@@ -0,0 +1,193 @@
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+/// Byte-identical publisher/iPhone archives; Mac must return the same verdict for every case.
+final nonisolated class ParakeetArchiveInstallerTests: XCTestCase {
+ private struct TarCase: Decodable {
+ let file: String
+ let folderName: String
+ let manifestSHA256: String
+ let verdict: String
+ }
+
+ private var fixtures: URL {
+ URL(fileURLWithPath: #filePath).deletingLastPathComponent()
+ .appendingPathComponent("Fixtures/ModelRelease/tars", isDirectory: true)
+ }
+
+ private func cases() throws -> [TarCase] {
+ try JSONDecoder().decode([TarCase].self, from: Data(contentsOf: self.fixtures.appendingPathComponent("expected.json")))
+ }
+
+ private func scratch() throws -> URL {
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("ArchiveInstallerTests-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
+ return url
+ }
+
+ private func unpack(_ tar: TarCase, staging: URL) throws -> URL {
+ try ParakeetArchiveInstaller.unpack(
+ archive: self.fixtures.appendingPathComponent(tar.file),
+ folderName: tar.folderName,
+ staging: staging,
+ manifestSHA256: tar.manifestSHA256
+ )
+ }
+
+ private func verdict(_ error: Error) -> String {
+ String(String(describing: error).prefix { $0 != "(" })
+ }
+
+ func testEveryCanonicalTarGetsThePublisherAndIPhoneVerdict() throws {
+ let base = try scratch()
+ defer { try? FileManager.default.removeItem(at: base) }
+ let entries = try cases()
+ XCTAssertEqual(entries.count, 17)
+ for entry in entries {
+ let result: String
+ do {
+ _ = try self.unpack(entry, staging: base.appendingPathComponent(entry.file, isDirectory: true))
+ result = "ok"
+ } catch { result = self.verdict(error) }
+ XCTAssertEqual(result, entry.verdict, entry.file)
+ }
+ }
+
+ func testVarAndPrivateVarAliasesVerifySameArchiveWithoutChangingFilesOrLinkRules() throws {
+ let base = try self.scratch()
+ defer { try? FileManager.default.removeItem(at: base) }
+ let publicPath = base.path.hasPrefix("/private/var/") ? String(base.path.dropFirst("/private".count)) : base.path
+ guard publicPath.hasPrefix("/var/") else { return XCTFail("Expected macOS temporary folder under /var, got \(base.path)") }
+ // Build both spellings literally; URL standardization can collapse /private/var.
+ let varBase = URL(fileURLWithPath: publicPath, isDirectory: true)
+ let privateBase = URL(fileURLWithPath: "/private" + publicPath, isDirectory: true)
+ XCTAssertTrue(FileManager.default.fileExists(atPath: varBase.path))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: privateBase.path))
+ let good = try XCTUnwrap(self.cases().first { $0.file == "good.tar" })
+ let sibling = privateBase.appendingPathComponent("other-model", isDirectory: true)
+ try FileManager.default.createDirectory(at: sibling, withIntermediateDirectories: false)
+ let siblingWeights = sibling.appendingPathComponent("weights")
+ try Data("keep".utf8).write(to: siblingWeights)
+ let privateFolder = try self.unpack(good, staging: privateBase.appendingPathComponent("staging", isDirectory: true))
+ let varFolder = varBase.appendingPathComponent("staging/\(good.folderName)", isDirectory: true)
+ let manifest = privateFolder.appendingPathComponent("manifest.json")
+ let originalManifest = try Data(contentsOf: manifest)
+ let originalNames = try FileManager.default.subpathsOfDirectory(atPath: privateFolder.path).sorted()
+ let originalFileIdentity = try XCTUnwrap(try FileManager.default.attributesOfItem(atPath: privateFolder.path)[.systemFileNumber] as? NSNumber)
+ for alias in [varFolder, privateFolder] {
+ XCTAssertNoThrow(try ParakeetArchiveInstaller.verify(folder: alias, folderName: good.folderName, manifestSHA256: good.manifestSHA256))
+ XCTAssertEqual(try ParakeetArchiveInstaller.sha256(of: alias.appendingPathComponent("manifest.json")), good.manifestSHA256)
+ XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: alias.path)[.systemFileNumber] as? NSNumber, originalFileIdentity)
+ XCTAssertEqual(try Data(contentsOf: alias.appendingPathComponent("manifest.json")), originalManifest)
+ XCTAssertEqual(try FileManager.default.subpathsOfDirectory(atPath: alias.path).sorted(), originalNames)
+ XCTAssertEqual(try Data(contentsOf: siblingWeights), Data("keep".utf8))
+ }
+ // Canonicalizing an ancestor alias must never permit a symlink as the model root.
+ let rootLink = privateBase.appendingPathComponent("linked-model")
+ try FileManager.default.createSymbolicLink(at: rootLink, withDestinationURL: privateFolder)
+ XCTAssertThrowsError(try ParakeetArchiveInstaller.verify(folder: rootLink, folderName: good.folderName, manifestSHA256: good.manifestSHA256)) {
+ XCTAssertEqual($0 as? ParakeetArchiveInstaller.InstallError, .manifestMismatch)
+ }
+ try FileManager.default.createSymbolicLink(at: privateFolder.appendingPathComponent("linked-weights"), withDestinationURL: siblingWeights)
+ for alias in [varFolder, privateFolder] {
+ XCTAssertThrowsError(try ParakeetArchiveInstaller.verify(folder: alias, folderName: good.folderName, manifestSHA256: good.manifestSHA256)) {
+ XCTAssertEqual($0 as? ParakeetArchiveInstaller.InstallError, .fileMismatch("linked-weights"))
+ }
+ XCTAssertEqual(try Data(contentsOf: alias.appendingPathComponent("manifest.json")), originalManifest)
+ XCTAssertEqual(try Data(contentsOf: siblingWeights), Data("keep".utf8))
+ }
+ }
+
+ func testEveryRejectedTarLeavesExistingWeightsAndSiblingUntouched() throws {
+ let base = try scratch()
+ defer { try? FileManager.default.removeItem(at: base) }
+ let installed = base.appendingPathComponent("installed", isDirectory: true)
+ let sibling = base.appendingPathComponent("other-model", isDirectory: true)
+ for folder in [installed, sibling] {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
+ try Data("keep".utf8).write(to: folder.appendingPathComponent("weights"))
+ }
+ for entry in try self.cases() where entry.verdict != "ok" {
+ XCTAssertThrowsError(try unpack(entry, staging: base.appendingPathComponent(entry.file)))
+ for folder in [installed, sibling] {
+ XCTAssertEqual(try Data(contentsOf: folder.appendingPathComponent("weights")), Data("keep".utf8), entry.file)
+ }
+ }
+ }
+
+ func testPreexistingStagingDirectoryAndSymlinkAreNeverRemoved() throws {
+ let base = try scratch()
+ defer { try? FileManager.default.removeItem(at: base) }
+ let good = try XCTUnwrap(cases().first { $0.file == "good.tar" })
+ let protected = base.appendingPathComponent("protected", isDirectory: true)
+ try FileManager.default.createDirectory(at: protected, withIntermediateDirectories: false)
+ try Data("keep".utf8).write(to: protected.appendingPathComponent("weights"))
+ let link = base.appendingPathComponent("linked-staging")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: protected)
+ for staging in [protected, link] {
+ XCTAssertThrowsError(try self.unpack(good, staging: staging)) {
+ XCTAssertEqual($0 as? ParakeetArchiveInstaller.InstallError, .invalidStaging)
+ }
+ XCTAssertEqual(try Data(contentsOf: protected.appendingPathComponent("weights")), Data("keep".utf8))
+ XCTAssertNotNil(try? FileManager.default.attributesOfItem(atPath: staging.path))
+ }
+ }
+
+ func testStandaloneVerificationRejectsLinksWithoutReadingTheirPayload() throws {
+ let base = try scratch()
+ defer { try? FileManager.default.removeItem(at: base) }
+ let good = try XCTUnwrap(cases().first { $0.file == "good.tar" })
+ let folder = try unpack(good, staging: base.appendingPathComponent("staging"))
+ let external = base.appendingPathComponent("external")
+ try Data("keep".utf8).write(to: external)
+ try FileManager.default.createSymbolicLink(at: folder.appendingPathComponent("linked"), withDestinationURL: external)
+ XCTAssertThrowsError(try ParakeetArchiveInstaller.verify(folder: folder, folderName: good.folderName, manifestSHA256: good.manifestSHA256)) {
+ XCTAssertEqual($0 as? ParakeetArchiveInstaller.InstallError, .fileMismatch("linked"))
+ }
+ XCTAssertEqual(try Data(contentsOf: external), Data("keep".utf8))
+ }
+
+ func testInvalidManifestSizesExitWithoutIntegerOverflow() throws {
+ let base = try scratch()
+ defer { try? FileManager.default.removeItem(at: base) }
+ for size in [-1, Int64.max] as [Int64] {
+ let folder = base.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
+ let manifest: [String: Any] = [
+ "folderName": "tiny-model", "totalSize": 0,
+ "files": [["path": "payload", "size": size, "sha256": String(repeating: "0", count: 64)]],
+ ]
+ let data = try JSONSerialization.data(withJSONObject: manifest)
+ let url = folder.appendingPathComponent("manifest.json")
+ try data.write(to: url)
+ XCTAssertThrowsError(try ParakeetArchiveInstaller.verify(folder: folder, folderName: "tiny-model", manifestSHA256: ParakeetArchiveInstaller.sha256(of: url))) {
+ XCTAssertEqual($0 as? ParakeetArchiveInstaller.InstallError, .manifestMismatch)
+ }
+ }
+ }
+
+ func testOversizedManifestIsRejectedBeforeDecode() throws {
+ let base = try scratch()
+ defer { try? FileManager.default.removeItem(at: base) }
+ let manifest = base.appendingPathComponent("manifest.json")
+ try Data(repeating: 32, count: 1_048_577).write(to: manifest)
+ XCTAssertThrowsError(try ParakeetArchiveInstaller.verify(folder: base, folderName: "tiny-model", manifestSHA256: ParakeetArchiveInstaller.sha256(of: manifest))) {
+ XCTAssertEqual($0 as? ParakeetArchiveInstaller.InstallError, .manifestMismatch)
+ }
+ }
+
+ func testCancelledUnpackDoesNotCreateStaging() async throws {
+ let base = try scratch()
+ defer { try? FileManager.default.removeItem(at: base) }
+ let good = try XCTUnwrap(cases().first { $0.file == "good.tar" })
+ let archive = self.fixtures.appendingPathComponent(good.file)
+ let stage = base.appendingPathComponent("staging")
+ let task = Task.detached {
+ withUnsafeCurrentTask { $0?.cancel() }
+ return try ParakeetArchiveInstaller.unpack(archive: archive, folderName: good.folderName, staging: stage, manifestSHA256: good.manifestSHA256)
+ }
+ do { _ = try await task.value; XCTFail("Expected cancellation") } catch is CancellationError {}
+ XCTAssertFalse(FileManager.default.fileExists(atPath: stage.path))
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/ParakeetCompactModelDemoTests.swift b/Tests/FluidDictationIntegrationTests/ParakeetCompactModelDemoTests.swift
new file mode 100644
index 00000000..646800b3
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/ParakeetCompactModelDemoTests.swift
@@ -0,0 +1,260 @@
+import AppKit
+import AVFoundation
+@testable import FluidVoice_Debug
+import Foundation
+import SwiftUI
+import XCTest
+
+@MainActor
+final class ParakeetCompactModelDemoTests: XCTestCase {
+ func testOptInNativeOnboardingAndSettingsReview() async throws {
+ guard ProcessInfo.processInfo.environment["FLUIDVOICE_COMPACT_MODEL_DEMO"] == "1",
+ let audioPath = ProcessInfo.processInfo.environment["FLUIDVOICE_COMPACT_MODEL_AUDIO"]
+ else { throw XCTSkip("Explicitly enable the native model review with an English test WAV") }
+ let settings = SettingsStore.shared
+ settings.onboardingSelectedLanguageID = "en"
+ let finished = expectation(description: "Native review closed")
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 780), styleMask: [.titled, .resizable], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.title = "Mini and Pico — Model Review"
+ let viewModel = VoiceEngineSettingsViewModel(settings: settings, appServices: .shared)
+ viewModel.providerFilter = .nvidia
+ viewModel.englishOnlyFilter = true
+ let view = CompactModelReviewView(viewModel: viewModel, audioPath: audioPath) {
+ window.orderOut(nil)
+ finished.fulfill()
+ }
+ window.contentView = NSHostingView(rootView: view.appTheme(.dark))
+ window.center()
+ window.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ print("COMPACT_MODEL_DEMO_READY window=\(window.windowNumber)")
+ await fulfillment(of: [finished], timeout: 600)
+ window.contentView = nil
+ window.close()
+ await AppServices.shared.asr.finishAudioRouteRecoveryTest()
+ }
+}
+
+@MainActor
+private struct CompactModelReviewView: View {
+ @ObservedObject var viewModel: VoiceEngineSettingsViewModel
+ let audioPath: String
+ let onClose: () -> Void
+ @State private var page = 0
+ @State private var onboardingStep = 2
+ @State private var shortcutTarget: ShortcutRecordingTarget?
+ @State private var shortcutMessage: String?
+ @State private var transcript = "Choose a downloaded model to transcribe the test recording."
+ @State private var isTranscribing = false
+ private let menuBarManager = MenuBarManager()
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack {
+ Picker("Review", selection: self.$page) {
+ Text("Voice Engine").tag(0)
+ Text("Onboarding").tag(1)
+ Text("Test transcription").tag(2)
+ }
+ .pickerStyle(.segmented)
+ .frame(width: 450)
+ Spacer()
+ Button("Close review", action: self.onClose)
+ .disabled(self.isTranscribing || self.viewModel.areSpeechModelActionsBlocked)
+ }
+ .padding(16)
+ Divider()
+ switch self.page {
+ case 1:
+ OnboardingFlowView(
+ currentStep: self.$onboardingStep,
+ accessibilityEnabled: true,
+ accessibilitySetupInProgress: false,
+ markAISkipped: {},
+ finishOnboarding: {},
+ finishOnboardingAtGettingStarted: {},
+ openAccessibilitySettings: {},
+ restartApp: {},
+ menuBarManager: self.menuBarManager,
+ activeShortcutRecordingTarget: self.$shortcutTarget,
+ shortcutRecordingMessage: self.$shortcutMessage,
+ theme: .dark
+ )
+ .environmentObject(AppServices.shared)
+ case 2:
+ VStack(alignment: .leading, spacing: 20) {
+ Text("English test recording · Microphone stays off")
+ HStack {
+ Button("Test Mini") { self.transcribe(.fluidParakeetMini) }
+ Button("Test Pico") { self.transcribe(.fluidParakeetPico) }
+ }
+ .disabled(self.isTranscribing)
+ if self.isTranscribing { ProgressView("Loading and transcribing…") }
+ Text(self.transcript).textSelection(.enabled)
+ Spacer()
+ }
+ .padding(32)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ default:
+ ScrollView {
+ VoiceEngineSettingsView(viewModel: self.viewModel, settings: .shared, theme: .dark)
+ .padding(20)
+ }
+ }
+ }
+ .preferredColorScheme(.dark)
+ .background(Color(nsColor: .windowBackgroundColor))
+ }
+
+ private func transcribe(_ model: SettingsStore.SpeechModel) {
+ self.isTranscribing = true
+ self.transcript = ""
+ Task { @MainActor in
+ defer { self.isTranscribing = false }
+ do {
+ let samples = try await Self.readAudio(self.audioPath)
+ let provider = FluidAudioProvider(
+ modelOverride: model,
+ configureWordBoosting: false,
+ enhancementOptions: .init(experimentalUnifiedFinalEnabled: false, pronunciationMatchingEnabled: false, customDictionaryEntries: [])
+ )
+ try await provider.prepare()
+ let result = try await provider.transcribe(samples)
+ self.transcript = "\(model.humanReadableName): \(result.text)"
+ } catch {
+ self.transcript = error.localizedDescription
+ }
+ }
+ }
+
+ @concurrent private static func readAudio(_ path: String) async throws -> [Float] {
+ let file = try AVAudioFile(forReading: URL(fileURLWithPath: path), commonFormat: .pcmFormatFloat32, interleaved: false)
+ guard file.processingFormat.sampleRate == 16_000, file.processingFormat.channelCount == 1,
+ let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length))
+ else { throw CocoaError(.fileReadCorruptFile) }
+ try file.read(into: buffer)
+ guard let channel = buffer.floatChannelData?[0] else { throw CocoaError(.fileReadCorruptFile) }
+ return Array(UnsafeBufferPointer(start: channel, count: Int(buffer.frameLength)))
+ }
+}
+
+@MainActor
+final class WindowSizingRegressionTests: XCTestCase {
+ func testRepeatedLayoutAndResizeEventsDoNotRewriteStableBounds() async {
+ let window = SizingRecordingWindow()
+ let view = FluidWindowSizingNSView(sizing: .minimum(width: 800, height: 500))
+ window.contentView = view
+ await self.drainSizing()
+ window.resetWrites()
+ for _ in 0..<100 {
+ view.sizing = .minimum(width: 800, height: 500)
+ NotificationCenter.default.post(name: NSWindow.didResizeNotification, object: window)
+ }
+ XCTAssertEqual(window.boundsWrites, 0, "A SwiftUI update must not synchronously invalidate window constraints")
+ await self.drainSizing()
+ XCTAssertEqual(window.boundsWrites, 0, "Stable bounds must stay untouched after the coalesced update")
+ XCTAssertEqual(window.frameWrites, 0)
+ window.contentView = nil
+ }
+
+ func testRapidSizingChangesApplyOnlyTheLatestBoundsAfterLayout() async {
+ let window = SizingRecordingWindow()
+ let view = FluidWindowSizingNSView(sizing: .minimum(width: 800, height: 500))
+ window.contentView = view
+ await self.drainSizing()
+ window.resetWrites()
+ view.sizing = .minimum(width: 900, height: 550)
+ view.sizing = .minimum(width: 940, height: 700)
+ XCTAssertEqual(window.boundsWrites, 0)
+ await self.drainSizing()
+ XCTAssertEqual(window.minSize, NSSize(width: 940, height: 700))
+ XCTAssertEqual(window.minimumWrites, 1)
+ window.contentView = nil
+ }
+
+ func testFullScreenLayoutDoesNotChangeAnyWindowBoundsOrFrame() async {
+ let window = SizingRecordingWindow()
+ let view = FluidWindowSizingNSView(sizing: .minimum(width: 800, height: 500))
+ window.contentView = view
+ await self.drainSizing()
+ window.isFullScreenForTest = true
+ window.resetWrites()
+ view.sizing = .minimum(width: 940, height: 700)
+ NotificationCenter.default.post(name: NSWindow.didResizeNotification, object: window)
+ await self.drainSizing()
+ XCTAssertEqual(window.boundsWrites, 0, "Full-screen sizing belongs entirely to macOS")
+ XCTAssertEqual(window.frameWrites, 0)
+ window.isFullScreenForTest = false
+ // Exit must restore the pending bounds even without a final resize event.
+ NotificationCenter.default.post(name: NSWindow.didExitFullScreenNotification, object: window)
+ await self.drainSizing()
+ XCTAssertEqual(window.minSize, NSSize(width: 940, height: 700))
+ window.contentView = nil
+ }
+
+ func testQueuedSizingDoesNotWriteToThePreviousWindow() async {
+ let oldWindow = SizingRecordingWindow()
+ let newWindow = SizingRecordingWindow()
+ let view = FluidWindowSizingNSView(sizing: .minimum(width: 800, height: 500))
+ oldWindow.contentView = view
+ await self.drainSizing()
+ oldWindow.resetWrites()
+ view.sizing = .minimum(width: 940, height: 700)
+ oldWindow.contentView = nil
+ newWindow.contentView = view
+ await self.drainSizing()
+ XCTAssertEqual(oldWindow.boundsWrites, 0)
+ XCTAssertEqual(oldWindow.frameWrites, 0)
+ XCTAssertEqual(newWindow.minSize, NSSize(width: 940, height: 700))
+ newWindow.contentView = nil
+ }
+
+ private func drainSizing() async {
+ for _ in 0..<3 {
+ await withCheckedContinuation { continuation in
+ DispatchQueue.main.async { continuation.resume() }
+ }
+ }
+ }
+}
+
+@MainActor
+private final class SizingRecordingWindow: NSWindow {
+ var minimumWrites = 0
+ var maximumWrites = 0
+ var frameWrites = 0
+ var isFullScreenForTest = false
+ var boundsWrites: Int { self.minimumWrites + self.maximumWrites }
+
+ init() {
+ super.init(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 700), styleMask: [.titled, .resizable], backing: .buffered, defer: false)
+ self.isReleasedWhenClosed = false
+ }
+
+ override var minSize: NSSize {
+ get { super.minSize }
+ set { self.minimumWrites += 1; super.minSize = newValue }
+ }
+
+ override var maxSize: NSSize {
+ get { super.maxSize }
+ set { self.maximumWrites += 1; super.maxSize = newValue }
+ }
+
+ override var styleMask: NSWindow.StyleMask {
+ get { self.isFullScreenForTest ? super.styleMask.union(.fullScreen) : super.styleMask }
+ set { super.styleMask = newValue }
+ }
+
+ override func setFrame(_ frameRect: NSRect, display flag: Bool, animate animateFlag: Bool) {
+ self.frameWrites += 1
+ super.setFrame(frameRect, display: flag, animate: animateFlag)
+ }
+
+ func resetWrites() {
+ self.minimumWrites = 0
+ self.maximumWrites = 0
+ self.frameWrites = 0
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/ParakeetCompactModelSmokeTests.swift b/Tests/FluidDictationIntegrationTests/ParakeetCompactModelSmokeTests.swift
new file mode 100644
index 00000000..9ec81092
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/ParakeetCompactModelSmokeTests.swift
@@ -0,0 +1,222 @@
+import AVFoundation
+import CryptoKit
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+#if arch(arm64)
+import FluidAudio
+#endif
+
+@MainActor
+final class ParakeetCompactModelSmokeTests: XCTestCase {
+ func testShippedRuntimeCheckRecordingIsBundledAndUnchanged() throws {
+ let url = try XCTUnwrap(CompactSpeechModelRuntimeCheck.recordingURL)
+ let data = try Data(contentsOf: url)
+ XCTAssertEqual(data.count, 131_162)
+ XCTAssertEqual(
+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(),
+ "961ac4a204b913fb953e1ef9a7d4a54a235f69a3bf0a818a6712968bacdde68d"
+ )
+ let samples = try CompactSpeechModelRuntimeCheck.samples()
+ XCTAssertEqual(samples.count, 65_581)
+ XCTAssertTrue(samples.allSatisfy(\.isFinite))
+ XCTAssertTrue(samples.contains { abs($0) > 0.01 })
+ }
+
+ func testRuntimeCheckRequiresFiveDistinctWholeWords() {
+ XCTAssertTrue(CompactSpeechModelRuntimeCheck.accepts("QUICK, brown fox jumps over."))
+ XCTAssertTrue(CompactSpeechModelRuntimeCheck.accepts("The quick brown fox jumps over the lazy dog near quiet water."))
+ XCTAssertFalse(CompactSpeechModelRuntimeCheck.accepts("quick brown fox jumps"))
+ XCTAssertFalse(CompactSpeechModelRuntimeCheck.accepts("quick quick quick quick quick"))
+ XCTAssertFalse(CompactSpeechModelRuntimeCheck.accepts("quickly brownish foxes jumping overhead"))
+ XCTAssertFalse(CompactSpeechModelRuntimeCheck.accepts(""))
+ }
+
+ func testRuntimeCheckRejectsInvalidAndOversizedPCM() throws {
+ for data in [Data(), Data([0]), Data(repeating: 0, count: 32_001), Data(repeating: 0, count: 480_002)] {
+ XCTAssertThrowsError(try CompactSpeechModelRuntimeCheck.decode(data)) { error in
+ XCTAssertEqual(error as? CompactSpeechModelRuntimeCheck.Failure, .invalidRecording)
+ }
+ }
+ var data = Data(repeating: 0, count: 32_000)
+ data[0] = 0xff
+ data[1] = 0x7f
+ data[2] = 0
+ data[3] = 0x80
+ let samples = try CompactSpeechModelRuntimeCheck.decode(data)
+ XCTAssertEqual(samples.count, 16_000)
+ XCTAssertEqual(samples[0], 32_767.0 / 32_768)
+ XCTAssertEqual(samples[1], -1)
+ }
+
+ func testRuntimeDeadlineJoinsCanceledProofCleanup() async throws {
+ let activity = RuntimeCheckActivity()
+ do {
+ try await CompactSpeechModelRuntimeCheck.withDeadline(.milliseconds(10)) {
+ do {
+ try await Task.sleep(for: .seconds(60))
+ } catch {
+ await activity.finish()
+ throw error
+ }
+ }
+ XCTFail("A blocked proof must time out")
+ } catch {
+ XCTAssertEqual(error as? CompactSpeechModelRuntimeCheck.Failure, .timedOut)
+ }
+ let finished = await activity.finished
+ XCTAssertTrue(finished, "The installer must not delete staged files while proof still uses them")
+ }
+
+ func testCanceledRuntimeProofJoinsCleanupWithoutReportingBadWeights() async throws {
+ let activity = RuntimeCheckActivity()
+ let (started, continuation) = AsyncStream<Void>.makeStream()
+ let task = Task {
+ try await CompactSpeechModelRuntimeCheck.withDeadline(.seconds(60)) {
+ continuation.yield(())
+ continuation.finish()
+ do {
+ try await Task.sleep(for: .seconds(60))
+ } catch {
+ await activity.finish()
+ throw error
+ }
+ }
+ }
+ for await _ in started { break }
+ task.cancel()
+ do {
+ try await task.value
+ XCTFail("Canceled verification must not publish weights")
+ } catch {
+ XCTAssertTrue(error is CancellationError)
+ }
+ let finished = await activity.finished
+ XCTAssertTrue(finished)
+ }
+
+ func testSuccessfulRuntimeProofCancelsDeadline() async throws {
+ let activity = RuntimeCheckActivity()
+ try await CompactSpeechModelRuntimeCheck.withDeadline(.seconds(60)) {
+ await activity.finish()
+ }
+ let finished = await activity.finished
+ XCTAssertTrue(finished)
+ }
+
+ func testHostedOldWeightsStayUsableUntilExplicitValidatedUpdate() async throws {
+ #if arch(arm64)
+ guard ProcessInfo.processInfo.environment["FLUIDVOICE_COMPACT_MODEL_AUDIO"] != nil else {
+ throw XCTSkip("Explicitly enable hosted compact model runtime checks")
+ }
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("FluidVoiceCompactUpdate-\(UUID().uuidString)", isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let selection = SettingsStore.shared.selectedSpeechModel
+ let fixtures: [(SettingsStore.SpeechModel, Int64, String)] = [
+ (.fluidParakeetMini, 254_126_592, "12109f89c80b959847ac80ae963714a00af08f029144c3e4a2a8c1641f528a36"),
+ (.fluidParakeetPico, 161_201_152, "afcdd76d4aba0328c97c858ee5c4c227ab5e23cc6885de5299d009c3671fe5d6"),
+ ]
+ for (model, bytes, oldHash) in fixtures {
+ let latest = try XCTUnwrap(model.parakeetDescriptor)
+ let oldURL = try XCTUnwrap(URL(string: "https://models.fluidvoice.app/parakeet/fluid-\(latest.variant.rawValue)/1.0.0/\(latest.folderName).tar"))
+ let old = latest.replacingArchive(url: oldURL, sha256: oldHash, byteCount: bytes)
+ let directory = try await ParakeetArchiveDownloader.ensurePresent(descriptor: old, in: root)
+ let probe = SpeechModelInstallationSnapshot.Probe(modelID: model.id, kind: .parakeet(latest))
+ let before = try await SpeechModelInstallationSnapshot.scanResult([probe], modelsDirectory: root)
+ XCTAssertEqual(before.installedIDs, [model.id])
+ XCTAssertEqual(before.updateAvailableIDs, [model.id])
+ XCTAssertEqual(before.installedArchiveHashes[model.id], oldHash)
+ do {
+ let provider = FluidAudioProvider(modelOverride: model, configureWordBoosting: false)
+ provider.modelCacheRootForTesting = root
+ try await provider.prepare()
+ XCTAssertTrue(provider.isReady)
+ XCTAssertEqual(provider.pronunciationModelKeyForTesting, old.pronunciationModelKey)
+ XCTAssertEqual(latest.installedArchiveSHA256(at: directory), oldHash)
+ }
+ let updater = FluidAudioProvider(modelOverride: model, configureWordBoosting: false, updateCompactWeights: true)
+ updater.modelCacheRootForTesting = root
+ try await updater.prepare()
+ XCTAssertTrue(latest.artifactsAreComplete(at: directory))
+ let after = try await SpeechModelInstallationSnapshot.scanResult([probe], modelsDirectory: root)
+ XCTAssertEqual(after.installedIDs, [model.id])
+ XCTAssertTrue(after.updateAvailableIDs.isEmpty)
+ XCTAssertEqual(after.installedArchiveHashes[model.id], latest.archiveSHA256)
+ let provider = FluidAudioProvider(modelOverride: model, configureWordBoosting: false)
+ provider.modelCacheRootForTesting = root
+ try await provider.prepare()
+ XCTAssertTrue(provider.isReady)
+ XCTAssertEqual(provider.pronunciationModelKeyForTesting, latest.pronunciationModelKey)
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selection)
+ }
+ #else
+ throw XCTSkip("Compact Parakeet models require Apple silicon")
+ #endif
+ }
+
+ func testHostedCompactModelsDownloadLoadTranscribeAndExtractDictionaryFrames() async throws {
+ #if arch(arm64)
+ guard let audioPath = ProcessInfo.processInfo.environment["FLUIDVOICE_COMPACT_MODEL_AUDIO"] else {
+ throw XCTSkip("Set FLUIDVOICE_COMPACT_MODEL_AUDIO to an English test recording for the hosted model check")
+ }
+ let verificationSamples = try CompactSpeechModelRuntimeCheck.samples()
+ let file = try AVAudioFile(forReading: URL(fileURLWithPath: audioPath), commonFormat: .pcmFormatFloat32, interleaved: false)
+ XCTAssertEqual(file.processingFormat.sampleRate, 16_000)
+ XCTAssertEqual(file.processingFormat.channelCount, 1)
+ let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length)))
+ try file.read(into: buffer)
+ let channel = try XCTUnwrap(buffer.floatChannelData?[0])
+ let samples = Array(UnsafeBufferPointer(start: channel, count: Int(buffer.frameLength)))
+ XCTAssertFalse(samples.isEmpty)
+ XCTAssertLessThanOrEqual(samples.count, 240_000)
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("FluidVoiceCompactModels-\(UUID().uuidString)", isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let selection = SettingsStore.shared.selectedSpeechModel
+ for descriptor in [ParakeetSpeechModelCatalog.mini, ParakeetSpeechModelCatalog.pico] {
+ // Exercise first-download publication through the real provider's staged proof.
+ do {
+ let model: SettingsStore.SpeechModel = descriptor.variant == .mini ? .fluidParakeetMini : .fluidParakeetPico
+ let provider = FluidAudioProvider(modelOverride: model, configureWordBoosting: false)
+ provider.modelCacheRootForTesting = root
+ try await provider.prepare()
+ XCTAssertTrue(provider.isReady)
+ XCTAssertFalse(provider.isWordBoostingActive)
+ }
+ let directory = descriptor.cacheDirectory(in: root)
+ XCTAssertTrue(descriptor.artifactsAreComplete(at: directory))
+ let models = try await AsrModels.loadLocalOnly(from: directory, version: descriptor.asrModelVersion)
+ XCTAssertEqual(models.version, descriptor.asrModelVersion)
+ XCTAssertNotNil(models.splitEncoder)
+ XCTAssertEqual(models.encoderOutputShape.count, 3)
+ let hiddenDimension = try XCTUnwrap(models.encoderOutputShape.dropFirst().first)
+ XCTAssertEqual(hiddenDimension, models.version.encoderHiddenSize)
+ let manager = AsrManager(config: .default)
+ do {
+ try await manager.initialize(models: models)
+ let verification = try await manager.transcribe(verificationSamples, source: .microphone)
+ XCTAssertTrue(CompactSpeechModelRuntimeCheck.accepts(verification.text), "Shipped sentence failed: \(verification.text)")
+ let result = try await manager.transcribe(samples, source: .microphone)
+ XCTAssertGreaterThanOrEqual(result.text.split(separator: " ").count, 3)
+ let embedding = try await manager.pronunciationEmbedding(audioSamples: samples, focalSampleRange: 0..<samples.count)
+ XCTAssertEqual(embedding.values.count, models.version.encoderHiddenSize)
+ XCTAssertTrue(embedding.values.allSatisfy(\.isFinite))
+ let frames = try await DictionaryTemporalEncoder.encode(samples, models: models)
+ XCTAssertTrue(frames.isValid)
+ XCTAssertEqual(frames.hiddenSize, models.version.encoderHiddenSize)
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selection)
+ await manager.cleanup()
+ } catch {
+ await manager.cleanup()
+ throw error
+ }
+ }
+ #else
+ throw XCTSkip("Compact Parakeet models require Apple silicon")
+ #endif
+ }
+}
+
+private actor RuntimeCheckActivity {
+ private(set) var finished = false
+ func finish() { self.finished = true }
+}
diff --git a/Tests/FluidDictationIntegrationTests/ParakeetSpeechModelCatalogTests.swift b/Tests/FluidDictationIntegrationTests/ParakeetSpeechModelCatalogTests.swift
new file mode 100644
index 00000000..39dc6ae6
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/ParakeetSpeechModelCatalogTests.swift
@@ -0,0 +1,308 @@
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+@MainActor
+final class ParakeetSpeechModelCatalogTests: XCTestCase {
+ func testManifestIdentityReadIsBoundedAndRejectsLinksWithoutChangingArchiveMarker() throws {
+ let descriptor = ParakeetSpeechModelCatalog.mini
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let marker = directory.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName)
+ let oldHash = String(repeating: "a", count: 64)
+ try Data(oldHash.utf8).write(to: marker)
+ let manifest = directory.appendingPathComponent("manifest.json")
+ XCTAssertNil(descriptor.installedManifestSHA256(at: directory))
+ try Data("{}".utf8).write(to: manifest)
+ XCTAssertEqual(descriptor.installedManifestSHA256(at: directory), "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a")
+ XCTAssertEqual(try Data(contentsOf: marker), Data(oldHash.utf8))
+ try Data(repeating: 0, count: 1_048_577).write(to: manifest)
+ XCTAssertNil(descriptor.installedManifestSHA256(at: directory))
+ try FileManager.default.removeItem(at: manifest)
+ try FileManager.default.createSymbolicLink(at: manifest, withDestinationURL: marker)
+ XCTAssertNil(descriptor.installedManifestSHA256(at: directory))
+ XCTAssertNil(ParakeetSpeechModelCatalog.v2.installedManifestSHA256(at: directory))
+ XCTAssertEqual(try Data(contentsOf: marker), Data(oldHash.utf8))
+ }
+
+ func testInstalledCompactRevisionCanBeOlderButMustHaveCompleteRegularArtifacts() throws {
+ let descriptor = ParakeetSpeechModelCatalog.mini
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ for model in descriptor.requiredModelNames {
+ let root = directory.appendingPathComponent(model)
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("weights"), withIntermediateDirectories: true)
+ for file in ["coremldata.bin", "metadata.json", "weights/weight.bin"] {
+ try Data("fixture".utf8).write(to: root.appendingPathComponent(file))
+ }
+ }
+ try Data("{}".utf8).write(to: directory.appendingPathComponent(descriptor.vocabularyFile))
+ let oldHash = "12109f89c80b959847ac80ae963714a00af08f029144c3e4a2a8c1641f528a36"
+ let marker = directory.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName)
+ try Data(oldHash.utf8).write(to: marker)
+ XCTAssertEqual(descriptor.installedArchiveSHA256(at: directory), oldHash)
+ XCTAssertFalse(descriptor.artifactsAreComplete(at: directory), "A usable old checkpoint is not the latest installation")
+ let link = directory.appendingPathComponent("unexpected-link")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: marker)
+ XCTAssertNil(descriptor.installedArchiveSHA256(at: directory))
+ try FileManager.default.removeItem(at: link)
+ for invalid in [String(repeating: "g", count: 64), String(repeating: "a", count: 65), ""] {
+ try Data(invalid.utf8).write(to: marker)
+ XCTAssertNil(descriptor.installedArchiveSHA256(at: directory))
+ }
+ try Data(oldHash.utf8).write(to: marker)
+ try FileManager.default.removeItem(at: directory.appendingPathComponent("Encoder-1.mlmodelc/weights/weight.bin"))
+ XCTAssertNil(descriptor.installedArchiveSHA256(at: directory))
+ XCTAssertNil(ParakeetSpeechModelCatalog.v2.installedArchiveSHA256(at: directory))
+ }
+
+ func testInstalledPronunciationDescriptorIsOnlyALocalCandidate() throws {
+ let oldHash = "12109f89c80b959847ac80ae963714a00af08f029144c3e4a2a8c1641f528a36"
+ let key = ParakeetSpeechModelCatalog.mini.modelID + ":sha256:" + oldHash
+ let candidate = try XCTUnwrap(ParakeetSpeechModelCatalog.descriptor(forInstalledPronunciationModelKey: key))
+ XCTAssertEqual(candidate.pronunciationModelKey, key)
+ XCTAssertEqual(candidate.archiveSHA256, oldHash)
+ XCTAssertNil(candidate.archiveURL, "An old checkpoint may never be downloaded from the latest archive URL")
+ XCTAssertEqual(candidate.requiredModelNames, ParakeetSpeechModelCatalog.mini.requiredModelNames)
+ XCTAssertNil(ParakeetSpeechModelCatalog.descriptor(forPronunciationModelKey: key))
+ XCTAssertTrue(ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey(key))
+ for invalid in [ParakeetSpeechModelCatalog.mini.modelID, key + "x", "fluid-parakeet-mini:sha256:" + String(repeating: "G", count: 64)] {
+ XCTAssertNil(ParakeetSpeechModelCatalog.descriptor(forInstalledPronunciationModelKey: invalid))
+ }
+ XCTAssertEqual(ParakeetSpeechModelCatalog.descriptor(forInstalledPronunciationModelKey: "parakeet-v2"), ParakeetSpeechModelCatalog.v2)
+ }
+
+ func testAllOfflineParakeetVariantsHaveIndependentStableCacheAndPronunciationKeys() throws {
+ let descriptors = ParakeetSpeechModelCatalog.descriptors
+ XCTAssertEqual(Set(descriptors.map(\.variant)), Set(ParakeetSpeechModelCatalog.Variant.allCases))
+ XCTAssertEqual(Set(descriptors.map(\.modelID)).count, 4)
+ XCTAssertEqual(Set(descriptors.map(\.folderName)).count, 4)
+ XCTAssertEqual(Set(descriptors.map(\.pronunciationModelKey)).count, 4)
+ let root = URL(fileURLWithPath: "/fixture/FluidAudio/Models", isDirectory: true)
+ for descriptor in descriptors {
+ let model = try XCTUnwrap(SettingsStore.SpeechModel(rawValue: descriptor.modelID))
+ XCTAssertEqual(model.parakeetDescriptor, descriptor)
+ XCTAssertEqual(ParakeetSpeechModelCatalog.descriptor(for: descriptor.variant), descriptor)
+ XCTAssertEqual(descriptor.cacheDirectory(in: root).deletingLastPathComponent(), root)
+ XCTAssertEqual(descriptor.cacheDirectory(in: root).lastPathComponent, descriptor.folderName)
+ XCTAssertEqual(model.expectedDownloadBytes, descriptor.expectedDownloadBytes)
+ XCTAssertEqual(model.displayName, descriptor.displayName)
+ XCTAssertEqual(model.humanReadableName, descriptor.humanReadableName)
+ XCTAssertFalse(model.isWhisperModel)
+ XCTAssertEqual(model.provider, .nvidia)
+ XCTAssertTrue(model.requiresAppleSilicon)
+ XCTAssertEqual(model.requiresMacOS15, model == .fluidParakeetMini || model == .fluidParakeetPico)
+ XCTAssertFalse(model.requiresMacOS26)
+ XCTAssertNil(model.whisperModelFile)
+ XCTAssertNil(model.legacyWhisperModelFile)
+ XCTAssertEqual(try JSONDecoder().decode(SettingsStore.SpeechModel.self, from: JSONEncoder().encode(model)), model)
+ }
+ XCTAssertNil(ParakeetSpeechModelCatalog.descriptor(forModelID: "missing"))
+ XCTAssertNil(SettingsStore.SpeechModel.parakeetRealtime.parakeetDescriptor)
+ XCTAssertNil(SettingsStore.SpeechModel.whisperBase.parakeetDescriptor)
+ }
+
+ func testLegacyV2V3IdentityAndArchitectureDefaultRemainUnchanged() {
+ let v2 = ParakeetSpeechModelCatalog.v2
+ let v3 = ParakeetSpeechModelCatalog.v3
+ XCTAssertEqual(v2.modelID, "parakeet-tdt-v2")
+ XCTAssertEqual(v3.modelID, "parakeet-tdt")
+ XCTAssertEqual(v2.folderName, "parakeet-tdt-0.6b-v2-coreml")
+ XCTAssertEqual(v3.folderName, "parakeet-tdt-0.6b-v3-coreml")
+ XCTAssertEqual(v2.pronunciationModelKey, "parakeet-v2")
+ XCTAssertEqual(v3.pronunciationModelKey, "parakeet-v3")
+ XCTAssertEqual(v2.expectedDownloadBytes, 464_421_712)
+ XCTAssertEqual(v3.expectedDownloadBytes, 483_288_717)
+ XCTAssertEqual(v2.downloadSize, "~442.9 MiB")
+ XCTAssertEqual(v3.downloadSize, "~460.9 MiB")
+ XCTAssertEqual(SettingsStore.SpeechModel.parakeetTDTv2.humanReadableName, "Blazing Fast - English")
+ XCTAssertEqual(SettingsStore.SpeechModel.parakeetTDT.humanReadableName, "Blazing Fast - Multilingual")
+ XCTAssertEqual(SettingsStore.SpeechModel.parakeetTDTv2.accuracyPercent, 0.96)
+ XCTAssertEqual(SettingsStore.SpeechModel.parakeetTDT.accuracyPercent, 0.92)
+ XCTAssertEqual(SettingsStore.SpeechModel.parakeetTDTv2.speedPercent, 0.99)
+ XCTAssertEqual(SettingsStore.SpeechModel.parakeetTDT.speedPercent, 0.99)
+ XCTAssertTrue(SettingsStore.SpeechModel.parakeetTDTv2.hasPerformanceRatings)
+ XCTAssertTrue(SettingsStore.SpeechModel.parakeetTDT.hasPerformanceRatings)
+ for model: SettingsStore.SpeechModel in [.parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .nemotronOffline, .nemotronStreaming] {
+ XCTAssertEqual(model.brandName, "NVIDIA")
+ XCTAssertEqual(model.brandColorHex, "#76B900")
+ XCTAssertEqual(model.provider, .nvidia)
+ }
+ XCTAssertNil(v2.archiveURL)
+ XCTAssertNil(v3.archiveSHA256)
+ XCTAssertEqual(Set(v2.requiredModelNames), Set(["Preprocessor.mlmodelc", "Encoder.mlmodelc", "Decoder.mlmodelc", "JointDecision.mlmodelc"]))
+ XCTAssertEqual(v2.requiredModelNames, v3.requiredModelNames)
+ XCTAssertEqual(v2.supportedLanguageCodes, ["en"])
+ XCTAssertEqual(Set(v3.supportedLanguageCodes), Set([
+ "bg", "hr", "cs", "da", "nl", "en", "et", "fi", "fr", "de", "el", "hu", "it",
+ "lv", "lt", "mt", "pl", "pt", "ro", "sk", "sl", "es", "sv", "ru", "uk",
+ ]))
+ XCTAssertEqual(SettingsStore.SpeechModel.defaultModel, CPUArchitecture.isAppleSilicon ? .parakeetTDT : .whisperBase)
+ }
+
+ func testHostedSmallVariantsUseExactArchivesAndNoInventedPerformanceRatings() throws {
+ let fixtures: [(SettingsStore.SpeechModel, Int64, String, String)] = [
+ (.fluidParakeetMini, 254_136_320, "fluid-mini", "7f811554cc670ded812937502f928ae6aad946bbf6e4c2eecd6fcffbe76f4d16"),
+ (.fluidParakeetPico, 161_208_320, "fluid-pico", "542f74f639438bf37ff134a7a75daddb50d301deb87696994e11ff272df21512"),
+ ]
+ for (model, bytes, path, hash) in fixtures {
+ let descriptor = try XCTUnwrap(model.parakeetDescriptor)
+ XCTAssertEqual(descriptor.expectedDownloadBytes, bytes)
+ XCTAssertEqual(descriptor.archiveSHA256, hash)
+ XCTAssertEqual(descriptor.archiveURL?.absoluteString, "https://models.fluidvoice.app/parakeet/\(path)/1.1.1/\(descriptor.folderName).tar")
+ XCTAssertEqual(descriptor.archiveURL?.scheme, "https")
+ XCTAssertEqual(descriptor.supportedLanguageCodes, ["en"])
+ XCTAssertTrue(descriptor.isEnglishOnly)
+ XCTAssertEqual(model.languageSupport, "English Only")
+ XCTAssertEqual(model.brandName, "FluidVoice")
+ XCTAssertEqual(model.brandColorHex, "#1A75FF")
+ XCTAssertEqual(model.provider, .nvidia, "Product branding must not change the Parakeet backend or family filter")
+ XCTAssertFalse(model.usesAppleLogo)
+ XCTAssertEqual(model.supportedLanguageCodes, "EN")
+ XCTAssertEqual(model.supportedLanguageNames, "English")
+ XCTAssertTrue(model.hasPerformanceRatings)
+ XCTAssertNotNil(descriptor.performanceRatings)
+ XCTAssertEqual(descriptor.attribution, "NVIDIA Parakeet · Moondream Parakeet Ultra")
+ XCTAssertEqual(descriptor.creditLine, "Made by FluidVoice, built on NVIDIA Parakeet and Moondream’s Parakeet Ultra.")
+ XCTAssertEqual(model.accuracyPercent, model == .fluidParakeetMini ? 0.95 : 0.91)
+ XCTAssertEqual(model.speedPercent, model == .fluidParakeetMini ? 0.99 : 1.0)
+ XCTAssertTrue(model.supportsPronunciationMatching, "Real split encoders produce compatible 1024-dimensional embeddings")
+ XCTAssertTrue(model.supportsCustomVocabulary, "Real CTC110m boosting is verified for both variants")
+ XCTAssertEqual(model.streamingPreviewIntervalSeconds, SettingsStore.SpeechModel.parakeetTDTv2.streamingPreviewIntervalSeconds)
+ XCTAssertEqual(model.minimumStreamingPreviewSeconds, SettingsStore.SpeechModel.parakeetTDTv2.minimumStreamingPreviewSeconds)
+ XCTAssertEqual(SettingsStore.SpeechModel.availableModels.contains(model), CPUArchitecture.isAppleSilicon)
+ }
+ XCTAssertEqual(SettingsStore.SpeechModel.fluidParakeetMini.humanReadableName, "Fluid Speech Mini")
+ XCTAssertEqual(SettingsStore.SpeechModel.fluidParakeetPico.humanReadableName, "Fluid Speech Pico")
+ }
+
+ func testSmallVariantsAreOfferedOnlyForEnglishAndDoNotReplaceExistingFirstChoice() {
+ let models: [SettingsStore.SpeechModel] = [.parakeetTDTv2, .parakeetRealtime, .parakeetTDT, .fluidParakeetMini, .fluidParakeetPico]
+ let english = VoiceEngineLanguageCatalog.routes(forLanguageID: "en", availableModels: models)
+ XCTAssertEqual(english.map(\.model), models)
+ XCTAssertEqual(english.first?.model, .parakeetTDTv2)
+ for route in english where route.model == .fluidParakeetMini || route.model == .fluidParakeetPico {
+ XCTAssertEqual(route.binding, .automatic)
+ XCTAssertNotNil(route.badgeText)
+ }
+ for language in VoiceEngineLanguageCatalog.allLanguages(availableModels: models) where language.id != "en" {
+ let routes = VoiceEngineLanguageCatalog.routes(for: language, availableModels: models)
+ XCTAssertFalse(routes.contains { $0.model == .fluidParakeetMini || $0.model == .fluidParakeetPico })
+ XCTAssertEqual(routes.map(\.model), [.parakeetTDT])
+ }
+ XCTAssertEqual(VoiceEngineLanguageCatalog.allLanguages(availableModels: [.fluidParakeetMini, .fluidParakeetPico]).map(\.id), ["en"])
+ XCTAssertTrue(VoiceEngineLanguageCatalog.routes(forLanguageID: "fr", availableModels: [.fluidParakeetMini, .fluidParakeetPico]).isEmpty)
+ XCTAssertTrue(VoiceEngineLanguageCatalog.routes(forLanguageID: "missing", availableModels: models).isEmpty)
+ }
+
+ func testEnglishOnboardingShowsV2AndMiniWithoutChangingSelectionOrAvailableRoutes() {
+ let language = VoiceEngineLanguage(id: "en", displayName: "English", aliases: [], isPopular: true)
+ let models: [SettingsStore.SpeechModel] = [.parakeetTDTv2, .parakeetRealtime, .parakeetTDT, .fluidParakeetMini, .fluidParakeetPico, .appleSpeechAnalyzer, .appleSpeech, .whisperBase]
+ let available = models.map { VoiceEngineLanguageRoute(language: language, model: $0, binding: .automatic) }
+ let selection = SettingsStore.shared.selectedSpeechModel
+ let displayed = OnboardingModelRecommendation.defaultRoutes(forLanguageID: "en", from: available)
+ XCTAssertEqual(displayed.map(\.model), [.parakeetTDTv2, .fluidParakeetMini])
+ XCTAssertEqual(displayed.first, available.first, "The established first recommendation must stay unchanged")
+ let displayedIDs = Set(displayed.map(\.id))
+ let other = available.filter { !displayedIDs.contains($0.id) }
+ XCTAssertEqual(other.map(\.model), [.parakeetRealtime, .parakeetTDT, .fluidParakeetPico, .appleSpeechAnalyzer, .appleSpeech, .whisperBase])
+ XCTAssertEqual(available.map(\.model), models)
+ XCTAssertEqual(Set((displayed + other).map(\.id)), Set(available.map(\.id)))
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selection)
+ XCTAssertEqual(ParakeetSpeechModelCatalog.mini.cardDescription, "Clear dictation in noisy places, at half the size of Blazing Fast. Runs on your Mac.")
+ XCTAssertEqual(ParakeetSpeechModelCatalog.pico.cardDescription, "Our smallest model. Light enough for older Macs, and still clear in noisy places.")
+ }
+
+ func testOnboardingRecommendationsPreserveUnavailableMiniIntelAndNonEnglishFallbacks() {
+ let english = VoiceEngineLanguage(id: "en", displayName: "English", aliases: [], isPopular: true)
+ func routes(_ models: [SettingsStore.SpeechModel]) -> [VoiceEngineLanguageRoute] {
+ models.map { VoiceEngineLanguageRoute(language: english, model: $0, binding: .automatic) }
+ }
+ let oldOS = routes([.parakeetTDTv2, .parakeetTDT, .appleSpeech])
+ XCTAssertEqual(OnboardingModelRecommendation.defaultRoutes(forLanguageID: "en", from: oldOS).map(\.model), [.parakeetTDTv2, .appleSpeech])
+ let intel = routes([.whisperBase, .appleSpeechAnalyzer, .appleSpeech])
+ XCTAssertEqual(OnboardingModelRecommendation.defaultRoutes(forLanguageID: "en", from: intel).map(\.model), [.whisperBase, .appleSpeechAnalyzer])
+ let appleFirst = routes([.appleSpeech, .whisperBase])
+ XCTAssertEqual(OnboardingModelRecommendation.defaultRoutes(forLanguageID: "en", from: appleFirst), [appleFirst[0]], "Do not duplicate the built-in card")
+ let withoutV2 = routes([.parakeetTDT, .fluidParakeetMini, .appleSpeech])
+ XCTAssertEqual(OnboardingModelRecommendation.defaultRoutes(forLanguageID: "en", from: withoutV2).map(\.model), [.parakeetTDT, .appleSpeech])
+ let french = VoiceEngineLanguage(id: "fr", displayName: "French", aliases: [], isPopular: true)
+ let frenchRoutes = [.parakeetTDT, SettingsStore.SpeechModel.appleSpeech].map {
+ VoiceEngineLanguageRoute(language: french, model: $0, binding: .automatic)
+ }
+ XCTAssertEqual(OnboardingModelRecommendation.defaultRoutes(forLanguageID: "fr", from: frenchRoutes), [frenchRoutes[0]])
+ XCTAssertTrue(OnboardingModelRecommendation.defaultRoutes(forLanguageID: "en", from: []).isEmpty)
+ XCTAssertTrue(OnboardingModelRecommendation.defaultRoutes(forLanguageID: "fr", from: []).isEmpty)
+ let onlyMini = routes([.fluidParakeetMini])
+ XCTAssertEqual(OnboardingModelRecommendation.defaultRoutes(forLanguageID: "en", from: onlyMini), onlyMini)
+ }
+
+ func testCatalogReadsPreserveExistingAndNewPersistedSelections() throws {
+ let defaults = UserDefaults.standard
+ let domain = try XCTUnwrap(Bundle.main.bundleIdentifier)
+ let original = defaults.persistentDomain(forName: domain)
+ defer {
+ if let original {
+ defaults.setPersistentDomain(original, forName: domain)
+ } else {
+ defaults.removePersistentDomain(forName: domain)
+ }
+ }
+ let settings = SettingsStore.shared
+ let models: [SettingsStore.SpeechModel] = [.parakeetTDT, .parakeetTDTv2, .fluidParakeetMini, .fluidParakeetPico, .whisperBase]
+ for model in models {
+ // A direct persisted fixture avoids sending model-switch UI events.
+ defaults.set(model.rawValue, forKey: "SelectedSpeechModel")
+ let before = defaults.persistentDomain(forName: domain)
+ _ = model.parakeetDescriptor
+ _ = model.displayName
+ _ = model.expectedDownloadBytes
+ _ = SettingsStore.SpeechModel.availableModels
+ let expected = model.requiresAppleSilicon && !CPUArchitecture.isAppleSilicon ? SettingsStore.SpeechModel.whisperBase : model
+ XCTAssertEqual(settings.selectedSpeechModel, expected)
+ XCTAssertEqual(defaults.string(forKey: "SelectedSpeechModel"), model.rawValue)
+ XCTAssertEqual(defaults.persistentDomain(forName: domain) as NSDictionary?, before as NSDictionary?)
+ }
+ }
+
+ func testSplitCompletenessRequiresEveryEncoderPartAndVocabularyWithoutBorrowingSiblingCache() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let mini = ParakeetSpeechModelCatalog.mini
+ let pico = ParakeetSpeechModelCatalog.pico
+ let miniDirectory = mini.cacheDirectory(in: root)
+ try self.installFixture(mini, at: miniDirectory)
+ XCTAssertTrue(mini.artifactsAreComplete(at: miniDirectory))
+ XCTAssertFalse(pico.artifactsAreComplete(at: pico.cacheDirectory(in: root)))
+ let encoder = miniDirectory.appendingPathComponent("Encoder-3.mlmodelc", isDirectory: true)
+ try FileManager.default.removeItem(at: encoder)
+ XCTAssertFalse(mini.artifactsAreComplete(at: miniDirectory))
+ try self.installCompiledFixture(at: encoder)
+ let vocabulary = miniDirectory.appendingPathComponent(mini.vocabularyFile)
+ try Data().write(to: vocabulary)
+ XCTAssertFalse(mini.artifactsAreComplete(at: miniDirectory))
+ try Data("{}".utf8).write(to: vocabulary)
+ XCTAssertTrue(mini.artifactsAreComplete(at: miniDirectory))
+ let weights = encoder.appendingPathComponent("weights/weight.bin")
+ try Data().write(to: weights)
+ XCTAssertFalse(mini.artifactsAreComplete(at: miniDirectory))
+ }
+
+ private func installFixture(_ descriptor: ParakeetSpeechModelCatalog.Descriptor, at directory: URL) throws {
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ try Data("{}".utf8).write(to: directory.appendingPathComponent(descriptor.vocabularyFile))
+ for name in descriptor.requiredModelNames {
+ try self.installCompiledFixture(at: directory.appendingPathComponent(name, isDirectory: true))
+ }
+ try descriptor.writeInstallationRevision(at: directory)
+ }
+
+ private func installCompiledFixture(at directory: URL) throws {
+ try FileManager.default.createDirectory(at: directory.appendingPathComponent("weights", isDirectory: true), withIntermediateDirectories: true)
+ try Data([1]).write(to: directory.appendingPathComponent("coremldata.bin"))
+ try Data("{}".utf8).write(to: directory.appendingPathComponent("metadata.json"))
+ try Data([1]).write(to: directory.appendingPathComponent("weights/weight.bin"))
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/ProgressiveFileDownloaderTests.swift b/Tests/FluidDictationIntegrationTests/ProgressiveFileDownloaderTests.swift
new file mode 100644
index 00000000..7ccca49d
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/ProgressiveFileDownloaderTests.swift
@@ -0,0 +1,99 @@
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+/// Exercises the real delegate without starting a network task.
+final nonisolated class ProgressiveFileDownloaderTests: XCTestCase {
+ func testOversizedChunkedTransferStopsBeforeReportingMisleadingProgress() throws {
+ try self.assertRejected(written: 11, expected: -1, maximum: 10)
+ }
+
+ func testOversizedDeclaredResponseStopsAtFirstByteCallback() throws {
+ try self.assertRejected(written: 1, expected: 11, maximum: 10)
+ }
+
+ func testExactLimitAndDefaultUnlimitedDownloadsStillReturnTheirFile() throws {
+ for maximum: Int64? in [3, nil] {
+ let fixture = try Fixture(maximumBytes: maximum)
+ defer { fixture.cleanup() }
+ fixture.delegate.urlSession(fixture.session, downloadTask: fixture.task, didWriteData: 3, totalBytesWritten: 3, totalBytesExpectedToWrite: 3)
+ fixture.delegate.retainDownload(at: fixture.source, response: fixture.response)
+ fixture.delegate.urlSession(fixture.session, task: fixture.task, didCompleteWithError: nil)
+ let result = try XCTUnwrap(fixture.recorder.result).get()
+ defer { try? FileManager.default.removeItem(at: result.0) }
+ XCTAssertEqual(try Data(contentsOf: result.0), Data([1, 2, 3]))
+ XCTAssertEqual(fixture.recorder.progress, [3])
+ }
+ }
+
+ func testFinishedOversizedFileIsNeverRetainedEvenWithoutProgressCallback() throws {
+ let fixture = try Fixture(maximumBytes: 2)
+ defer { fixture.cleanup() }
+ fixture.delegate.retainDownload(at: fixture.source, response: fixture.response)
+ fixture.delegate.urlSession(fixture.session, task: fixture.task, didCompleteWithError: nil)
+ self.assertLengthFailure(fixture.recorder.result)
+ XCTAssertTrue(FileManager.default.fileExists(atPath: fixture.source.path))
+ }
+
+ func testCancellationAfterFileCompletionRemovesRetainedDownload() throws {
+ let fixture = try Fixture(maximumBytes: nil)
+ defer { fixture.cleanup() }
+ let retained = try XCTUnwrap(fixture.delegate.retainDownload(at: fixture.source, response: fixture.response))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: retained.path))
+ fixture.delegate.urlSession(fixture.session, task: fixture.task, didCompleteWithError: URLError(.cancelled))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: retained.path))
+ guard case let .failure(error)? = fixture.recorder.result else { return XCTFail("Expected cancellation") }
+ XCTAssertEqual((error as? URLError)?.code, .cancelled)
+ }
+
+ private func assertRejected(written: Int64, expected: Int64, maximum: Int64) throws {
+ let fixture = try Fixture(maximumBytes: maximum)
+ defer { fixture.cleanup() }
+ fixture.delegate.urlSession(fixture.session, downloadTask: fixture.task, didWriteData: written, totalBytesWritten: written, totalBytesExpectedToWrite: expected)
+ fixture.delegate.urlSession(fixture.session, task: fixture.task, didCompleteWithError: URLError(.cancelled))
+ self.assertLengthFailure(fixture.recorder.result)
+ XCTAssertTrue(fixture.recorder.progress.isEmpty)
+ }
+
+ private func assertLengthFailure(_ result: Result<(URL, URLResponse), Error>?, file: StaticString = #filePath, line: UInt = #line) {
+ guard case let .failure(error)? = result else { return XCTFail("Expected oversized transfer rejection", file: file, line: line) }
+ XCTAssertEqual((error as? URLError)?.code, .dataLengthExceedsMaximum, file: file, line: line)
+ }
+
+ private final class Recorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private var storedResult: Result<(URL, URLResponse), Error>?
+ private var storedProgress: [Int64] = []
+ var result: Result<(URL, URLResponse), Error>? { self.lock.withLock { self.storedResult } }
+ var progress: [Int64] { self.lock.withLock { self.storedProgress } }
+ func complete(_ result: Result<(URL, URLResponse), Error>) { self.lock.withLock { self.storedResult = result } }
+ func report(_ bytes: Int64, _: Int64) { self.lock.withLock { self.storedProgress.append(bytes) } }
+ }
+
+ private struct Fixture {
+ let directory: URL
+ let source: URL
+ let session: URLSession
+ let task: URLSessionDownloadTask
+ let response: URLResponse
+ let delegate: ProgressiveFileDownloader.Delegate
+ let recorder: Recorder
+
+ init(maximumBytes: Int64?) throws {
+ self.directory = FileManager.default.temporaryDirectory.appendingPathComponent("ProgressiveFileDownloaderTests-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: self.directory, withIntermediateDirectories: false)
+ self.source = self.directory.appendingPathComponent("transfer")
+ try Data([1, 2, 3]).write(to: self.source)
+ self.recorder = Recorder()
+ self.delegate = ProgressiveFileDownloader.Delegate(maximumBytes: maximumBytes, onProgress: self.recorder.report, completion: self.recorder.complete)
+ self.session = URLSession(configuration: .ephemeral)
+ self.task = try self.session.downloadTask(with: XCTUnwrap(URL(string: "https://fixture.invalid/unused")))
+ self.response = URLResponse(url: self.source, mimeType: nil, expectedContentLength: 3, textEncodingName: nil)
+ }
+
+ func cleanup() {
+ self.session.invalidateAndCancel()
+ try? FileManager.default.removeItem(at: self.directory)
+ }
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/PronunciationModelRevisionTests.swift b/Tests/FluidDictationIntegrationTests/PronunciationModelRevisionTests.swift
new file mode 100644
index 00000000..93a299c3
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/PronunciationModelRevisionTests.swift
@@ -0,0 +1,193 @@
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+@MainActor
+final class PronunciationModelRevisionTests: XCTestCase {
+ func testCurrentCompactKeysIncludeFullPinnedHashAndLegacyKeysStayExact() throws {
+ XCTAssertEqual(ParakeetSpeechModelCatalog.v2.pronunciationModelKey, "parakeet-v2")
+ XCTAssertEqual(ParakeetSpeechModelCatalog.v3.pronunciationModelKey, "parakeet-v3")
+ for descriptor in [ParakeetSpeechModelCatalog.mini, ParakeetSpeechModelCatalog.pico] {
+ let hash = try XCTUnwrap(descriptor.archiveSHA256)
+ XCTAssertEqual(descriptor.pronunciationModelKey, descriptor.modelID + ":sha256:" + hash)
+ XCTAssertEqual(ParakeetSpeechModelCatalog.descriptor(forPronunciationModelKey: descriptor.pronunciationModelKey), descriptor)
+ XCTAssertNil(ParakeetSpeechModelCatalog.descriptor(forPronunciationModelKey: descriptor.modelID))
+ XCTAssertTrue(ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey(descriptor.modelID))
+ let old = descriptor.modelID + ":sha256:" + String(repeating: "0", count: 64)
+ XCTAssertNil(ParakeetSpeechModelCatalog.descriptor(forPronunciationModelKey: old))
+ XCTAssertTrue(ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey(old))
+ XCTAssertFalse(ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey(descriptor.pronunciationModelKey))
+ }
+ XCTAssertEqual(ParakeetSpeechModelCatalog.descriptor(forPronunciationModelKey: "parakeet-v2"), ParakeetSpeechModelCatalog.v2)
+ XCTAssertEqual(ParakeetSpeechModelCatalog.descriptor(forPronunciationModelKey: "parakeet-v3"), ParakeetSpeechModelCatalog.v3)
+ XCTAssertFalse(ParakeetSpeechModelCatalog.isOutdatedCompactPronunciationModelKey("parakeet-v3"))
+ }
+
+ func testRetrainingKeepsOriginalStoredProfileAndTextEntryWithoutReusingOldVectors() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let store = PronunciationDictionaryStore(fileURL: directory.appendingPathComponent("profiles.json"))
+ let descriptor = ParakeetSpeechModelCatalog.mini
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: ["fluid boys"], replacement: "FluidVoice")
+ let originalEntry = entry
+ let old = Self.profile(entryID: entry.id, key: descriptor.modelID)
+ try await store.upsert(dictionaryEntryID: entry.id, label: old.label, modelKey: old.modelKey, enrollments: old.enrollments)
+ let original = await store.allProfiles()
+ let currentBeforeRetraining = await store.profiles(modelKey: descriptor.pronunciationModelKey)
+ XCTAssertTrue(currentBeforeRetraining.isEmpty)
+ #if arch(arm64)
+ XCTAssertTrue(DictionaryPronunciationReferences.make(profiles: original).isEmpty)
+ #endif
+ let current = Self.profile(entryID: entry.id, key: descriptor.pronunciationModelKey)
+ try await store.upsert(dictionaryEntryID: entry.id, label: current.label, modelKey: current.modelKey, enrollments: current.enrollments)
+ let all = await store.allProfiles()
+ let stillSaved = all.filter { $0.modelKey == old.modelKey }
+ XCTAssertEqual(stillSaved, original)
+ XCTAssertEqual(all.count, 2)
+ XCTAssertEqual(entry, originalEntry, "Revision checks must not change basic text corrections")
+ let compatible = await store.profiles(modelKey: descriptor.pronunciationModelKey)
+ XCTAssertEqual(compatible.count, 1)
+ XCTAssertEqual(compatible[0].enrollments.map(\.modelKey), Array(repeating: descriptor.pronunciationModelKey, count: 3))
+ #if arch(arm64)
+ XCTAssertEqual(DictionaryPronunciationReferences.make(profiles: all).count, 3)
+ for key in ["parakeet-v2", "parakeet-v3"] {
+ XCTAssertEqual(DictionaryPronunciationReferences.make(profiles: [Self.profile(entryID: entry.id, key: key)]).count, 3)
+ }
+ #endif
+ }
+
+ func testOldNegativeFramesAreInactiveAndRemainStoredWithoutAReadMutation() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let url = directory.appendingPathComponent("negative.plist")
+ let store = DictionaryNegativeExampleStore(url: url, collectionEnabled: { true })
+ let id = UUID()
+ let oldKey = ParakeetSpeechModelCatalog.mini.modelID
+ let currentKey = ParakeetSpeechModelCatalog.mini.pronunciationModelKey
+ let frames = DictionaryMatchFrames(hiddenSize: 2, values: [1, 0, 1, 0])
+ let evidence = DictionaryAcousticEvidence(id: UUID(), entryID: id, label: "FluidVoice", profileKey: "fixture", modelKey: oldKey, sourceWordRange: 0..<1, frames: frames)
+ let revision = await store.revision()
+ try await store.save(.init(evidence: evidence, correctedText: "different", expiresAt: Date().addingTimeInterval(60)), expectedRevision: revision)
+ let before = try Data(contentsOf: url)
+ let inactive = await store.frames(entryID: id, profileKey: "fixture", modelKey: oldKey)
+ let current = await store.frames(entryID: id, profileKey: "fixture", modelKey: currentKey)
+ XCTAssertTrue(inactive.isEmpty)
+ XCTAssertTrue(current.isEmpty)
+ XCTAssertEqual(try Data(contentsOf: url), before)
+ let saved = try PropertyListDecoder().decode([DictionaryNegativeExampleStore.Example].self, from: before)
+ XCTAssertEqual(saved.count, 1)
+ XCTAssertEqual(saved[0].modelKey, oldKey)
+ for key in [currentKey, "parakeet-v2", "parakeet-v3"] {
+ let currentID = UUID()
+ let currentEvidence = DictionaryAcousticEvidence(id: UUID(), entryID: currentID, label: "Current", profileKey: "current-fixture", modelKey: key, sourceWordRange: 0..<1, frames: frames)
+ try await store.save(.init(evidence: currentEvidence, correctedText: "different", expiresAt: Date().addingTimeInterval(60)), expectedRevision: revision)
+ let compatible = await store.frames(entryID: currentID, profileKey: "current-fixture", modelKey: key)
+ XCTAssertEqual(compatible, [frames], "Current and legacy checkpoints must still use their own negative frames")
+ }
+ let after = try PropertyListDecoder().decode([DictionaryNegativeExampleStore.Example].self, from: Data(contentsOf: url))
+ XCTAssertTrue(after.contains { $0.modelKey == oldKey }, "Reading inactive negatives must not silently erase them")
+ }
+
+ func testNoticeAndReplayAskToRetrainOnlyAffectedActiveWords() throws {
+ let descriptor = ParakeetSpeechModelCatalog.mini
+ let id = UUID()
+ let old = Self.profile(entryID: id, key: descriptor.modelID)
+ let current = Self.profile(entryID: id, key: descriptor.pronunciationModelKey)
+ let notice = DictionaryPronunciationRevisionPolicy.notice(profiles: [old], descriptor: descriptor, entryIDs: [id])
+ XCTAssertTrue(notice?.contains("FluidVoice") == true)
+ XCTAssertTrue(notice?.contains("need retraining") == true)
+ XCTAssertTrue(notice?.contains("text corrections remain saved") == true)
+ XCTAssertNil(DictionaryPronunciationRevisionPolicy.notice(profiles: [old, current], descriptor: descriptor, entryIDs: [id]))
+ XCTAssertNil(DictionaryPronunciationRevisionPolicy.notice(profiles: [old], descriptor: descriptor, entryIDs: []))
+ XCTAssertNil(DictionaryPronunciationRevisionPolicy.notice(profiles: [old], descriptor: ParakeetSpeechModelCatalog.pico, entryIDs: [id]))
+ XCTAssertNil(DictionaryPronunciationRevisionPolicy.notice(profiles: [old], descriptor: ParakeetSpeechModelCatalog.v3, entryIDs: [id]))
+ XCTAssertThrowsError(try DictionaryMatchPlayground.targetProfile(from: [old], target: "fluidvoice")) { error in
+ XCTAssertEqual(error as? PronunciationDictionaryStoreError, .outdatedModelRevision)
+ XCTAssertTrue(error.localizedDescription.contains("Retrain this word"))
+ }
+ XCTAssertEqual(try DictionaryMatchPlayground.targetProfile(from: [old, current], target: "fluidvoice"), current)
+ }
+
+ #if arch(arm64)
+ func testProfileCannotMixEnrollmentVectorsFromDifferentRevisions() {
+ let current = ParakeetSpeechModelCatalog.mini.pronunciationModelKey
+ var profile = Self.profile(entryID: UUID(), key: current)
+ profile.enrollments[0] = PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 6, modelKey: ParakeetSpeechModelCatalog.mini.modelID)
+ XCTAssertTrue(DictionaryPronunciationReferences.make(profiles: [profile]).isEmpty)
+ }
+
+ func testOldOriginalAudioEvidenceIsRejectedBeforeAnyModelLoad() async throws {
+ let evidence = DictionaryLearningAudioEvidence(
+ recordingID: UUID(),
+ modelKey: ParakeetSpeechModelCatalog.mini.modelID,
+ observedText: "fluid boys",
+ sourceWordRange: 0..<1,
+ sourceSampleRange: 0..<1,
+ focalSampleRange: 0..<1,
+ samples: [0.1]
+ )
+ do {
+ _ = try await OriginalAudioEmbeddingExtractor.extract(evidence)
+ XCTFail("Old revision evidence must never load the current encoder")
+ } catch let error as PronunciationDictionaryStoreError {
+ XCTAssertEqual(error, .outdatedModelRevision)
+ }
+ }
+ #endif
+
+ #if arch(arm64)
+ func testLoadedOldCompactRevisionMatchesOnlyItsOwnEnrollmentVectors() {
+ let descriptor = ParakeetSpeechModelCatalog.mini
+ let oldKey = descriptor.modelID + ":sha256:" + String(repeating: "a", count: 64)
+ let old = Self.profile(entryID: UUID(), key: oldKey)
+ let latest = Self.profile(entryID: UUID(), key: descriptor.pronunciationModelKey)
+ XCTAssertTrue(DictionaryPronunciationReferences.make(profiles: [old]).isEmpty)
+ let oldReferences = DictionaryPronunciationReferences.make(profiles: [old, latest], compatibleModelKey: oldKey)
+ XCTAssertEqual(oldReferences.count, 3)
+ XCTAssertTrue(oldReferences.allSatisfy { $0.profile.modelKey == oldKey })
+ let latestReferences = DictionaryPronunciationReferences.make(profiles: [old, latest], compatibleModelKey: descriptor.pronunciationModelKey)
+ XCTAssertEqual(latestReferences.count, 3)
+ XCTAssertTrue(latestReferences.allSatisfy { $0.profile.modelKey == descriptor.pronunciationModelKey })
+ var mixed = old
+ mixed.enrollments[0] = latest.enrollments[0]
+ XCTAssertTrue(DictionaryPronunciationReferences.make(profiles: [mixed], compatibleModelKey: oldKey).isEmpty)
+ let unversioned = Self.profile(entryID: UUID(), key: descriptor.modelID)
+ XCTAssertTrue(DictionaryPronunciationReferences.make(profiles: [unversioned], compatibleModelKey: descriptor.modelID).isEmpty)
+ }
+
+ func testNormalProviderPreparationKeepsCompleteOldWeightsAndTheirActualPronunciationKey() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ for model: SettingsStore.SpeechModel in [.fluidParakeetMini, .fluidParakeetPico] {
+ let descriptor = try XCTUnwrap(model.parakeetDescriptor)
+ let installed = descriptor.cacheDirectory(in: root)
+ try FileManager.default.createDirectory(at: installed, withIntermediateDirectories: true)
+ let oldHash = String(repeating: "a", count: 64)
+ try Data(oldHash.utf8).write(to: installed.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName))
+ try Data("{}".utf8).write(to: installed.appendingPathComponent(descriptor.vocabularyFile))
+ for name in descriptor.requiredModelNames {
+ let folder = installed.appendingPathComponent(name)
+ try FileManager.default.createDirectory(at: folder.appendingPathComponent("weights"), withIntermediateDirectories: true)
+ for file in ["coremldata.bin", "metadata.json", "weights/weight.bin"] {
+ try Data("fixture".utf8).write(to: folder.appendingPathComponent(file))
+ }
+ }
+ XCTAssertEqual(descriptor.installedArchiveSHA256(at: installed), oldHash)
+ let provider = FluidAudioProvider(modelOverride: model, configureWordBoosting: false)
+ provider.modelCacheRootForTesting = root
+ do {
+ try await ASRService().prepareProviderRecoveryForTesting(provider, modelsAlreadyCached: true)
+ XCTFail("Dummy Core ML files must fail locally without deleting old weights for recovery")
+ } catch {}
+ XCTAssertEqual(provider.pronunciationModelKeyForTesting, descriptor.modelID + ":sha256:" + oldHash)
+ XCTAssertEqual(descriptor.installedArchiveSHA256(at: installed), oldHash, "Normal loading must never erase an older complete download")
+ XCTAssertEqual(try Data(contentsOf: installed.appendingPathComponent(descriptor.vocabularyFile)), Data("{}".utf8))
+ }
+ }
+ #endif
+
+ private static func profile(entryID: UUID, key: String) -> PronunciationDictionaryProfile {
+ let captures = Array(repeating: PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 6, modelKey: key), count: 3)
+ return PronunciationDictionaryProfile(dictionaryEntryID: entryID, label: "FluidVoice", modelKey: key, hiddenSize: 2, enrollments: captures)
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/SearchIndexTests.swift b/Tests/FluidDictationIntegrationTests/SearchIndexTests.swift
index b7bff1cb..234a677e 100644
--- a/Tests/FluidDictationIntegrationTests/SearchIndexTests.swift
+++ b/Tests/FluidDictationIntegrationTests/SearchIndexTests.swift
@@ -1,3 +1,5 @@
+import CryptoKit
+import Darwin
@testable import FluidVoice_Debug
import Foundation
import SQLite3
@@ -87,6 +89,208 @@ final class SearchIndexTests: XCTestCase {
XCTAssertEqual(new, [original.id])
}
+ func testLowerAndEqualRevisionsCannotReplaceNewerIndexedText() async throws {
+ let latest = Self.record("latest harbour manuscript", revision: 9)
+ try await self.index.reconcile(.history, with: [latest])
+ for revision: UInt64 in [1, 9] {
+ let stale = SearchIndexRecord(id: latest.id, revision: revision, timestamp: latest.timestamp, text: "obsolete lighthouse manuscript")
+ let report = try await self.index.reconcile(.history, with: [stale])
+ XCTAssertEqual(report, .init(upserted: 0, deleted: 0))
+ let current = try await self.ids(.history, query: "harb")
+ let replaced = try await self.ids(.history, query: "lighth")
+ XCTAssertEqual(current, [latest.id])
+ XCTAssertTrue(replaced.isEmpty)
+ }
+ }
+
+ func testReconcilingOneKindDoesNotDeleteOrReplaceOtherNamespaces() async throws {
+ let history = Self.record("harbour history")
+ let transcript = SearchIndexRecord(id: history.id, revision: 17, timestamp: history.timestamp, text: "lighthouse transcript")
+ let chat = SearchIndexRecord(id: history.id, revision: 30, timestamp: history.timestamp, text: "mountain chat")
+ try await self.index.reconcile(.history, with: [history])
+ try await self.index.reconcile(.transcripts, with: [transcript])
+ try await self.index.reconcile(.chats, with: [chat])
+ let report = try await self.index.reconcile(.history, with: [])
+ XCTAssertEqual(report, .init(upserted: 0, deleted: 1))
+ let historyCount = try await self.count(.history)
+ let transcripts = try await self.ids(.transcripts, query: "lighth")
+ let chats = try await self.ids(.chats, query: "mount")
+ XCTAssertEqual(historyCount, 0)
+ XCTAssertEqual(transcripts, [history.id])
+ XCTAssertEqual(chats, [history.id])
+ }
+
+ func testSealedRecordOnlyNamespaceReopensWithoutBackfillAndKeepsPrefixMatches() async throws {
+ XCTAssertNil(SearchIndex.spec.vectorSpace)
+ XCTAssertTrue(SearchIndex.spec.attributes.isEmpty)
+ let directory = self.root.appendingPathComponent("sealed", isDirectory: true)
+ let records = [Self.record("meeting notes from monday"), Self.record("harbour lights at dusk")]
+ let initialRoot = FluidZeppelinRoot(root: directory)
+ let initial = SearchIndex(root: initialRoot)
+ do {
+ try await initial.reconcile(.history, with: records)
+ let store = try await initial.namespace(.history)
+ _ = try await store.seal()
+ let sealed = try await store.stats()
+ XCTAssertEqual(sealed.activeRowCount, 0, "Record-only rows must leave the active segment when sealed")
+ } catch {
+ await initialRoot.closeAll()
+ throw error
+ }
+ await initialRoot.closeAll()
+
+ // Distinct roots and actor handles exercise the actual reopen path, not
+ // the cached namespace task from the first reconcile.
+ for _ in 0..<3 {
+ let reopenedRoot = FluidZeppelinRoot(root: directory)
+ let reopened = SearchIndex(root: reopenedRoot)
+ do {
+ let report = try await reopened.reconcile(.history, with: records)
+ XCTAssertEqual(report, .init(upserted: 0, deleted: 0))
+ for typed in ["mee", "meetin", "notes mo"] {
+ let hits = try await reopened.query(.history, text: typed, limit: 10)
+ XCTAssertEqual(Set(hits.map(\.id)), [records[0].id])
+ }
+ let store = try await reopened.namespace(.history)
+ let sealed = try await store.stats()
+ XCTAssertEqual(sealed.activeRowCount, 0, "An unchanged reopen must not create a fresh active backfill")
+ } catch {
+ await reopenedRoot.closeAll()
+ throw error
+ }
+ await reopenedRoot.closeAll()
+ }
+ }
+
+ func testReopenedIndexAppliesInsertDeleteAndRestoredRevisionWithoutRevivingOldText() async throws {
+ let directory = self.root.appendingPathComponent("revisions", isDirectory: true)
+ let kept = Self.record("original harbour text", revision: 6)
+ let removed = Self.record("removed lighthouse text", revision: 4)
+ let initialRoot = FluidZeppelinRoot(root: directory)
+ let initial = SearchIndex(root: initialRoot)
+ do {
+ try await initial.reconcile(.history, with: [kept, removed])
+ let store = try await initial.namespace(.history)
+ _ = try await store.seal()
+ } catch {
+ await initialRoot.closeAll()
+ throw error
+ }
+ await initialRoot.closeAll()
+
+ let reopenedRoot = FluidZeppelinRoot(root: directory)
+ let reopened = SearchIndex(root: reopenedRoot)
+ do {
+ let restored = SearchIndexRecord(id: kept.id, revision: 7, timestamp: kept.timestamp, text: "restored mountain text")
+ let inserted = Self.record("new river text")
+ let report = try await reopened.reconcile(.history, with: [restored, inserted])
+ XCTAssertEqual(report, .init(upserted: 2, deleted: 1))
+ let restoredHits = try await reopened.query(.history, text: "mount", limit: 10)
+ let insertedHits = try await reopened.query(.history, text: "riv", limit: 10)
+ let oldHits = try await reopened.query(.history, text: "harbour", limit: 10)
+ let deletedHits = try await reopened.query(.history, text: "lighthouse", limit: 10)
+ XCTAssertEqual(Set(restoredHits.map(\.id)), [kept.id])
+ XCTAssertEqual(Set(insertedHits.map(\.id)), [inserted.id])
+ XCTAssertTrue(oldHits.isEmpty)
+ XCTAssertTrue(deletedHits.isEmpty)
+ } catch {
+ await reopenedRoot.closeAll()
+ throw error
+ }
+ await reopenedRoot.closeAll()
+ }
+
+ func testUnchangedLegacyBackfillSealsOnceAndSmallSubsequentWritesStayActive() async throws {
+ let directory = self.root.appendingPathComponent("maintenance", isDirectory: true)
+ let records = (0..<260).map { Self.record("maintenance harbour entry \($0)") }
+ let legacyRoot = FluidZeppelinRoot(root: directory)
+ let legacy = SearchIndex(root: legacyRoot, maintenanceActiveRowLimit: nil)
+ do {
+ try await legacy.reconcile(.history, with: records)
+ let store = try await legacy.namespace(.history)
+ let stats = try await store.stats()
+ XCTAssertEqual(stats.activeRowCount, 260)
+ } catch {
+ await legacyRoot.closeAll()
+ throw error
+ }
+ await legacyRoot.closeAll()
+
+ let maintainedRoot = FluidZeppelinRoot(root: directory)
+ let maintained = SearchIndex(root: maintainedRoot)
+ do {
+ let backfill = try await maintained.reconcile(.history, with: records)
+ XCTAssertEqual(backfill, .init(upserted: 0, deleted: 0), "Sealing must not relabel unchanged records as new writes")
+ let store = try await maintained.namespace(.history)
+ let first = try await store.stats()
+ XCTAssertEqual(first.activeRowCount, 0)
+ XCTAssertGreaterThan(first.segmentBytes, 0)
+ let repeated = try await maintained.reconcile(.history, with: records)
+ let second = try await store.stats()
+ XCTAssertEqual(repeated, .init(upserted: 0, deleted: 0))
+ XCTAssertEqual(second.segmentBytes, first.segmentBytes, "An unchanged snapshot must not create another segment")
+ XCTAssertEqual(second.activeRowCount, 0)
+
+ let added = Self.record("one additional river entry")
+ let insertion = try await maintained.reconcile(.history, with: records + [added])
+ let smallWrite = try await store.stats()
+ XCTAssertEqual(insertion, .init(upserted: 1, deleted: 0))
+ XCTAssertEqual(smallWrite.activeRowCount, 1, "Do not seal after every dictation")
+ let hits = try await maintained.query(.history, text: "additional riv", limit: 10)
+ XCTAssertEqual(Set(hits.map(\.id)), [added.id])
+ } catch {
+ await maintainedRoot.closeAll()
+ throw error
+ }
+ await maintainedRoot.closeAll()
+ }
+
+ func testFailedSealingPreservesSearchableRecordsAndRetriesOnNextSnapshot() async throws {
+ let directory = self.root.appendingPathComponent("maintenance-failure", isDirectory: true)
+ let namespace = directory.appendingPathComponent(SearchIndexKind.history.rawValue, isDirectory: true)
+ let database = FluidZeppelinRoot(root: directory)
+ let records = (0..<260).map { Self.record("permission harbour entry \($0)") }
+ let legacy = SearchIndex(root: database, maintenanceActiveRowLimit: nil)
+ do {
+ try await legacy.reconcile(.history, with: records)
+ // The live WAL handle stays writable; immutable segment publication
+ // needs a new directory entry and must fail under these permissions.
+ try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: namespace.path)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: namespace.path) }
+ let permissionProbe = namespace.appendingPathComponent("permission-probe")
+ var deniesCreation = false
+ do {
+ try Data([0]).write(to: permissionProbe, options: .withoutOverwriting)
+ } catch {
+ deniesCreation = true
+ }
+ if !deniesCreation {
+ try? FileManager.default.removeItem(at: permissionProbe)
+ throw XCTSkip("The test runner can create files despite private directory permissions")
+ }
+ let maintained = SearchIndex(root: database)
+ let report = try await maintained.reconcile(.history, with: records)
+ XCTAssertEqual(report, .init(upserted: 0, deleted: 0), "Maintenance failure must not fail an otherwise successful reconcile")
+ let store = try await maintained.namespace(.history)
+ let failedStats = try await store.stats()
+ XCTAssertEqual(failedStats.activeRowCount, 260)
+ let hits = try await maintained.query(.history, text: "permission harb", limit: 300)
+ XCTAssertEqual(Set(hits.map(\.id)), Set(records.map(\.id)))
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: namespace.path)
+ let retry = try await maintained.reconcile(.history, with: records)
+ let retriedStats = try await store.stats()
+ XCTAssertEqual(retry, .init(upserted: 0, deleted: 0))
+ XCTAssertEqual(retriedStats.activeRowCount, 0)
+ let restoredHits = try await maintained.query(.history, text: "permission harb", limit: 300)
+ XCTAssertEqual(Set(restoredHits.map(\.id)), Set(records.map(\.id)))
+ } catch {
+ try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: namespace.path)
+ await database.closeAll()
+ throw error
+ }
+ await database.closeAll()
+ }
+
/// A damaged namespace is moved aside by `FluidZeppelinRoot`; the next reconcile
/// then refills the empty one. Nothing is lost because the store still has it.
func testAResetNamespaceIsRefilledByTheNextReconcile() async throws {
@@ -315,7 +519,7 @@ final class SearchIndexCoordinatorTests: XCTestCase {
XCTAssertEqual(afterEdits, [saved.id, deleted.id, stale.id], "Edits after a failed load are still an incomplete snapshot")
try fixture.defaults.set(JSONEncoder().encode([saved, deleted]), forKey: "TranscriptionHistoryEntries")
- history.retryPersistence()
+ history.retryLoadingIfNeeded()
try await history.waitUntilLoaded()
XCTAssertNil(history.persistenceError)
XCTAssertEqual(Set(history.entries.map(\.id)), [saved.id, pending.id])
@@ -339,6 +543,30 @@ final class SearchIndexCoordinatorTests: XCTestCase {
}
}
+ func testSearchRetryNeverRewritesSuccessfullyLoadedHistory() async throws {
+ try await self.withFixture { fixture in
+ let saved = self.entry("saved history must remain untouched")
+ try fixture.defaults.set(JSONEncoder().encode([saved]), forKey: "TranscriptionHistoryEntries")
+ let history = TranscriptionHistoryStore(writer: fixture.writer)
+ try await history.waitUntilLoaded()
+ var connection: OpaquePointer?
+ XCTAssertEqual(sqlite3_open(fixture.historyURL.path, &connection), SQLITE_OK)
+ let database = try XCTUnwrap(connection)
+ defer { sqlite3_close(database) }
+ // retryPersistence's loaded branch deletes every row before rewriting.
+ // Make that unintended operation fail instead of merely comparing IDs.
+ XCTAssertEqual(sqlite3_exec(database, "CREATE TRIGGER reject_history_rewrite BEFORE DELETE ON history BEGIN SELECT RAISE(ABORT, 'unexpected history rewrite'); END", nil, nil, nil), SQLITE_OK)
+ history.retryLoadingIfNeeded()
+ await history.finishPendingWrites()
+ XCTAssertNil(history.persistenceError)
+ let writeError = await fixture.writer.drain()
+ XCTAssertNil(writeError)
+ let rows = try await fixture.writer.load()
+ XCTAssertEqual(rows.map(\.id), [saved.id])
+ XCTAssertEqual(history.entries.map(\.id), [saved.id])
+ }
+ }
+
func testClearingLoadedHistoryDeletesIndexedRecords() async throws {
try await self.withFixture { fixture in
let saved = self.entry("startup saved dictation")
@@ -412,4 +640,731 @@ final class SearchIndexCoordinatorTests: XCTestCase {
try await self.waitForIndexedIDs([saved.id], in: fixture.index)
}
}
+
+ func testFirstSearchPreparationWaitsForLoadedHistoryAndSuppressesSelfRefresh() async throws {
+ try await self.withFixture { fixture in
+ let saved = self.entry("first query authoritative history")
+ try fixture.defaults.set(JSONEncoder().encode([saved]), forKey: "TranscriptionHistoryEntries")
+ let history = TranscriptionHistoryStore(writer: fixture.writer)
+ try await history.waitUntilLoaded()
+ let probe = SearchReconcileProbe(gatedCallCount: 3)
+ var refreshCount = 0
+ let coordinator = SearchIndexCoordinator(
+ index: fixture.index,
+ reconcile: { kind, records in try await probe.reconcile(kind, records: records) },
+ refresh: { refreshCount += 1 }
+ )
+ var prepared = false
+ let preparation = Task { try await coordinator.prepareForSearch(historyStore: history); prepared = true }
+ do {
+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))
+ while await probe.calls().count < 3, ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ let calls = await probe.calls()
+ XCTAssertEqual(calls.count, 3)
+ guard calls.count == 3 else { throw SearchReconcileProbe.Failure.unavailable }
+ let indexedHistory = try XCTUnwrap(calls.first { $0.kind == .history })
+ XCTAssertEqual(indexedHistory.records.map(\.id), [saved.id])
+ XCTAssertEqual(indexedHistory.records.first?.text, saved.searchRecord.text)
+ XCTAssertFalse(prepared, "The first query cannot run against an unfinished history snapshot")
+ XCTAssertEqual(refreshCount, 0)
+ await probe.releaseAll()
+ let completionDeadline = ContinuousClock.now.advanced(by: .seconds(5))
+ while !prepared, ContinuousClock.now < completionDeadline {
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ XCTAssertTrue(prepared)
+ guard prepared else { throw SearchReconcileProbe.Failure.unavailable }
+ try await preparation.value
+ XCTAssertEqual(refreshCount, 0, "Seeding the first search must not cancel and restart its own query")
+ } catch {
+ await probe.releaseAll()
+ await coordinator.stop()
+ _ = await preparation.result
+ throw error
+ }
+ await coordinator.stop()
+ }
+ }
+}
+
+private struct SearchBenchmarkRecord: Decodable {
+ let id: UUID
+ let revision: UInt64
+ let timestampMilliseconds: Int64
+ let text: String
+
+ var record: SearchIndexRecord {
+ SearchIndexRecord(id: self.id, revision: self.revision, timestamp: Date(timeIntervalSince1970: Double(self.timestampMilliseconds) / 1000), text: self.text)
+ }
+}
+
+private actor SearchReconcileProbe {
+ struct Call: Sendable {
+ let kind: SearchIndexKind
+ let records: [SearchIndexRecord]
+ }
+
+ enum Failure: Error { case unavailable }
+
+ private var recorded: [Call] = []
+ private var gates: [Int: CheckedContinuation<Void, Never>] = [:]
+ private var released = false
+ private var active: [SearchIndexKind: Int] = [:]
+ private var peak: [SearchIndexKind: Int] = [:]
+ private let gatedCallCount: Int
+ private let failingCalls: Set<Int>
+
+ init(gatedCallCount: Int = 2, failingCalls: Set<Int> = []) {
+ self.gatedCallCount = gatedCallCount
+ self.failingCalls = failingCalls
+ }
+
+ func reconcile(_ kind: SearchIndexKind, records: [SearchIndexRecord]) async throws -> SearchIndex.ReconcileReport {
+ let number = self.recorded.count
+ self.recorded.append(Call(kind: kind, records: records))
+ self.active[kind, default: 0] += 1
+ self.peak[kind] = max(self.peak[kind, default: 0], self.active[kind, default: 0])
+ defer { self.active[kind, default: 0] -= 1 }
+ if !self.released, number < self.gatedCallCount {
+ await withCheckedContinuation { self.gates[number] = $0 }
+ }
+ if self.failingCalls.contains(number) { throw Failure.unavailable }
+ return .init(upserted: records.count, deleted: 0)
+ }
+
+ func calls() -> [Call] { self.recorded }
+ func maximumConcurrentCalls(_ kind: SearchIndexKind) -> Int { self.peak[kind, default: 0] }
+ func release(_ number: Int) { self.gates.removeValue(forKey: number)?.resume() }
+
+ func releaseAll() {
+ self.released = true
+ let gates = self.gates.values
+ self.gates.removeAll()
+ for gate in gates {
+ gate.resume()
+ }
+ }
+}
+
+@MainActor
+final class SearchIndexCoordinatorSchedulingTests: XCTestCase {
+ private func entry(_ text: String) -> TranscriptionHistoryEntry {
+ TranscriptionHistoryEntry(rawText: text, processedText: text, appName: "Fixture", windowTitle: "Fixture", wasAIProcessed: false)
+ }
+
+ private func withProbe(failingCalls: Set<Int> = [], preparationTimeout: Duration = .seconds(20), _ body: (SearchIndexCoordinator, SearchReconcileProbe, () -> Int) async throws -> Void) async throws {
+ let probe = SearchReconcileProbe(failingCalls: failingCalls)
+ var refreshCount = 0
+ let coordinator = SearchIndexCoordinator(
+ reconcile: { kind, records in
+ try await probe.reconcile(kind, records: records)
+ },
+ refresh: { refreshCount += 1 },
+ preparationTimeout: preparationTimeout
+ )
+ do {
+ try await body(coordinator, probe) { refreshCount }
+ } catch {
+ await probe.releaseAll()
+ await coordinator.stop()
+ throw error
+ }
+ await probe.releaseAll()
+ await coordinator.stop()
+ }
+
+ private func waitForCalls(_ count: Int, in probe: SearchReconcileProbe) async throws {
+ try await self.waitUntil { await probe.calls().count >= count }
+ }
+
+ private func waitUntil(_ condition: () async -> Bool) async throws {
+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))
+ while !(await condition()), ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ guard await condition() else {
+ XCTFail("A bounded search scheduling condition did not complete")
+ throw SearchReconcileProbe.Failure.unavailable
+ }
+ }
+
+ func testRapidSnapshotsKeepOneWorkerAndOnlyTheLatestSuccessor() async throws {
+ try await self.withProbe { coordinator, probe, refreshCount in
+ let first = self.entry("first snapshot")
+ coordinator.submit(.history([first]))
+ coordinator.flush()
+ try await self.waitForCalls(1, in: probe)
+ var latest = first
+ for number in 0..<100 {
+ latest = self.entry("latest snapshot \(number)")
+ coordinator.submit(.history([latest]))
+ coordinator.flush()
+ }
+ let before = await probe.calls()
+ XCTAssertEqual(before.count, 1, "A blocked reconcile must not spawn a task chain")
+ var completed = false
+ var captureStarted = false
+ let barrier = Task { captureStarted = true; try await coordinator.waitUntilCurrent(); completed = true }
+ try await self.waitUntil { captureStarted }
+ await probe.release(0)
+ try await self.waitForCalls(2, in: probe)
+ XCTAssertFalse(completed, "The current snapshot barrier must include the captured latest snapshot")
+ XCTAssertEqual(refreshCount(), 0, "Do not refresh results from an intermediate snapshot")
+ let calls = await probe.calls()
+ XCTAssertEqual(calls.map { $0.records.map(\.id) }, [[first.id], [latest.id]])
+ XCTAssertEqual(calls[1].records.first?.text, latest.searchRecord.text)
+ await probe.release(1)
+ try await self.waitUntil { completed }
+ try await barrier.value
+ try await self.waitUntil { refreshCount() == 1 }
+ let peak = await probe.maximumConcurrentCalls(.history)
+ XCTAssertEqual(peak, 1)
+ }
+ }
+
+ func testCapturedBarrierIsNotExtendedByLaterSnapshots() async throws {
+ try await self.withProbe { coordinator, probe, _ in
+ coordinator.submit(.history([self.entry("captured snapshot")]))
+ coordinator.flush()
+ try await self.waitForCalls(1, in: probe)
+ var completed = false
+ var captureStarted = false
+ let barrier = Task { captureStarted = true; try await coordinator.waitUntilCurrent(); completed = true }
+ // Let the barrier capture generation one before sending generation two.
+ try await self.waitUntil { captureStarted }
+ coordinator.submit(.history([self.entry("later snapshot")]))
+ await probe.release(0)
+ try await self.waitForCalls(2, in: probe)
+ try await self.waitUntil { completed }
+ try await barrier.value
+ await probe.release(1)
+ try await coordinator.waitUntilCurrent()
+ }
+ }
+
+ func testStopDropsQueuedSnapshotsCancelsWaitersAndDrainsCurrentWork() async throws {
+ try await self.withProbe { coordinator, probe, refreshCount in
+ coordinator.submit(.history([self.entry("running snapshot")]))
+ coordinator.flush()
+ try await self.waitForCalls(1, in: probe)
+ coordinator.submit(.history([self.entry("queued snapshot")]))
+ var barrierCancelled = false
+ let barrier = Task {
+ do {
+ try await coordinator.waitUntilCurrent()
+ XCTFail("Stop must cancel the barrier")
+ } catch is CancellationError {
+ barrierCancelled = true
+ } catch {
+ XCTFail("Unexpected barrier failure: \(error)")
+ }
+ }
+ await Task.yield()
+ var stopped = false
+ let stop = Task { await coordinator.stop(); stopped = true }
+ try await self.waitUntil { barrierCancelled }
+ XCTAssertFalse(stopped, "Stop must await the actual in-flight write before closeAll")
+ await probe.release(0)
+ try await self.waitUntil { stopped }
+ await stop.value
+ await barrier.value
+ coordinator.submit(.history([self.entry("after stop")]))
+ coordinator.flush()
+ do {
+ try await coordinator.waitUntilCurrent()
+ XCTFail("A stopped coordinator cannot reopen")
+ } catch is CancellationError {}
+ let calls = await probe.calls()
+ XCTAssertEqual(calls.count, 1)
+ XCTAssertEqual(refreshCount(), 0, "Late work must not refresh search during termination")
+ }
+ }
+
+ func testFailedReconcileFinishesBarrierAndExplicitRetryUsesLatestSnapshot() async throws {
+ try await self.withProbe(failingCalls: [0]) { coordinator, probe, refreshCount in
+ coordinator.submit(.history([self.entry("failed first snapshot")]))
+ coordinator.flush()
+ try await self.waitForCalls(1, in: probe)
+ let latest = self.entry("latest retry snapshot")
+ coordinator.submit(.history([latest]))
+ var failed = false
+ let barrier = Task {
+ do {
+ try await coordinator.waitUntilCurrent()
+ XCTFail("The first reconcile is intentionally unavailable")
+ } catch SearchReconcileProbe.Failure.unavailable {
+ failed = true
+ }
+ }
+ await Task.yield()
+ await probe.release(0)
+ try await self.waitUntil { failed }
+ try await barrier.value
+ XCTAssertEqual(refreshCount(), 0)
+ var retried = false
+ let retry = Task { try await coordinator.waitUntilCurrent(); retried = true }
+ try await self.waitForCalls(2, in: probe)
+ let calls = await probe.calls()
+ XCTAssertEqual(calls[1].records.map(\.id), [latest.id], "Retry cannot replay an older snapshot over newer input")
+ await probe.release(1)
+ try await self.waitUntil { retried }
+ try await retry.value
+ try await self.waitUntil { refreshCount() == 1 }
+ }
+ }
+
+ func testPreparationTimeoutFinishesPromptlyWithoutStartingAnotherWorker() async throws {
+ try await self.withProbe(preparationTimeout: .milliseconds(50)) { coordinator, probe, _ in
+ coordinator.submit(.history([self.entry("temporarily slow snapshot")]))
+ coordinator.flush()
+ try await self.waitForCalls(1, in: probe)
+ let start = ContinuousClock.now
+ do {
+ try await coordinator.waitUntilCurrent()
+ XCTFail("The blocked writer must exceed the injected preparation deadline")
+ } catch SearchIndexCoordinator.PreparationError.timedOut {}
+ XCTAssertLessThan(start.duration(to: .now), .seconds(2))
+ let before = await probe.calls()
+ XCTAssertEqual(before.count, 1, "Timeout must not create another index worker")
+ await probe.release(0)
+ try await coordinator.waitUntilCurrent()
+ let peak = await probe.maximumConcurrentCalls(.history)
+ XCTAssertEqual(peak, 1)
+ }
+ }
+
+ func testCancellingOneBarrierDoesNotCancelTheSharedIndexWorkerOrOtherWaiter() async throws {
+ try await self.withProbe { coordinator, probe, _ in
+ coordinator.submit(.history([self.entry("shared pending snapshot")]))
+ coordinator.flush()
+ try await self.waitForCalls(1, in: probe)
+ var cancelled = false
+ var survivorCompleted = false
+ let first = Task {
+ do {
+ try await coordinator.waitUntilCurrent()
+ XCTFail("This waiter was cancelled")
+ } catch is CancellationError {
+ cancelled = true
+ }
+ }
+ let survivor = Task { try await coordinator.waitUntilCurrent(); survivorCompleted = true }
+ first.cancel()
+ try await self.waitUntil { cancelled }
+ try await first.value
+ XCTAssertFalse(survivorCompleted)
+ await probe.release(0)
+ try await self.waitUntil { survivorCompleted }
+ try await survivor.value
+ let calls = await probe.calls()
+ XCTAssertEqual(calls.count, 1)
+ }
+ }
+}
+
+private struct SearchBenchmarkStats: Codable {
+ let activeRows: UInt64
+ let residentOwnedBytes: UInt64
+ let mappedBytes: UInt64
+ let segmentBytes: UInt64
+ let walBytes: UInt64
+ let physicalFootprint: UInt64?
+
+ init(_ stats: StoreStats) {
+ self.activeRows = stats.activeRowCount
+ self.residentOwnedBytes = stats.residentOwnedBytes
+ self.mappedBytes = stats.mappedBytes
+ self.segmentBytes = stats.segmentBytes
+ self.walBytes = stats.walBytes
+ self.physicalFootprint = stats.physicalFootprint
+ }
+}
+
+private struct SearchBenchmarkReopen: Codable {
+ let queryMilliseconds: Double
+ let reconcileMilliseconds: Double
+ let returnedHits: Int
+ let beforeQueryPhysicalFootprintBytes: UInt64?
+ let afterQueryPhysicalFootprintBytes: UInt64?
+ let afterReconcilePhysicalFootprintBytes: UInt64?
+ let stats: SearchBenchmarkStats
+}
+
+private struct SearchBenchmarkVariant: Codable {
+ let label: String
+ let recordCount: Int
+ let openMilliseconds: Double
+ let reconcileMilliseconds: Double
+ let initialUpserts: Int
+ let initialDeletes: Int
+ let beforeOpenPhysicalFootprintBytes: UInt64?
+ let afterOpenPhysicalFootprintBytes: UInt64?
+ let afterReconcilePhysicalFootprintBytes: UInt64?
+ let before: SearchBenchmarkStats
+ let after: SearchBenchmarkStats
+ let membershipSHA256: String
+ let queryMembershipSHA256: [String: String]
+ let reopens: [SearchBenchmarkReopen]
+}
+
+extension SearchIndexTests {
+ /// Exercises the real coordinator's snapshot construction and index updates,
+ /// using synthetic finished dictations only. No audio, preferences or real stores.
+ @MainActor
+ func testOptInSequentialDictationMemoryGrowth() async throws {
+ guard let path = ProcessInfo.processInfo.environment["FLUIDVOICE_SEARCH_APPEND_MEMORY_REPORT"], !path.isEmpty else {
+ throw XCTSkip("Supply an external JSON report path for the incremental memory simulation")
+ }
+ let database = FluidZeppelinRoot(root: self.root.appendingPathComponent("append-memory", isDirectory: true))
+ let index = SearchIndex(root: database)
+ let coordinator = SearchIndexCoordinator(index: index, refresh: {}, preparationTimeout: .seconds(120))
+ var entries = (0..<12_880).map { number in
+ TranscriptionHistoryEntry(
+ rawText: "not indexed",
+ processedText: "seedhistory item\(number) " + String(repeating: "meeting project update planning notes ", count: 5),
+ appName: "Synthetic fixture",
+ windowTitle: "Search memory simulation",
+ wasAIProcessed: false
+ )
+ }
+ var samples: [SearchAppendMemorySample] = []
+ var timings: [Double] = []
+ var peak: UInt64 = 0
+ var samplerTicks = 0
+ var sampler: Task<Void, Never>?
+ do {
+ coordinator.submit(.history(entries))
+ try await coordinator.waitUntilCurrent()
+ _ = try await index.query(.history, text: "seedhistory", limit: 50)
+ let store = try await index.namespace(.history)
+ try samples.append(await self.appendMemorySample("prepared baseline", added: 0, sourceRows: entries.count, store: store))
+ peak = Self.physicalFootprint() ?? 0
+ sampler = Task {
+ // Bound diagnostic storage/work even if native recovery is slow.
+ while !Task.isCancelled, samplerTicks < 20_000 {
+ peak = max(peak, Self.physicalFootprint() ?? 0)
+ samplerTicks += 1
+ do { try await Task.sleep(for: .milliseconds(10)) } catch { return }
+ }
+ }
+ for added in 1...1024 {
+ entries.append(TranscriptionHistoryEntry(
+ rawText: "not indexed",
+ processedText: "appendmarker update\(added) " + String(repeating: "finished dictation project followup ", count: added % 8 + 1),
+ appName: "Synthetic fixture",
+ windowTitle: "Sequential additions",
+ wasAIProcessed: false
+ ))
+ let started = ContinuousClock.now
+ coordinator.submit(.history(entries))
+ try await coordinator.waitUntilCurrent()
+ timings.append(Self.milliseconds(since: started))
+ if added % 32 == 0 || added == 1 || added == 255 || added == 257 {
+ let hits = try await index.query(.history, text: "appendmarker update\(added)", limit: 50)
+ XCTAssertTrue(hits.contains { $0.id == entries.last?.id })
+ try samples.append(await self.appendMemorySample("sequential", added: added, sourceRows: entries.count, store: store))
+ }
+ if added % 256 == 0 {
+ let stats = try await store.stats()
+ XCTAssertEqual(stats.activeRowCount, 0)
+ print("Search append simulation: \(added) additions indexed and sealed")
+ }
+ }
+ // A rapid event burst must keep only the latest successor snapshot.
+ for added in 1025...1280 {
+ entries.append(TranscriptionHistoryEntry(
+ rawText: "not indexed",
+ processedText: "burstmarker update\(added) " + String(repeating: "rapid finished history update ", count: 6),
+ appName: "Synthetic fixture",
+ windowTitle: "Burst additions",
+ wasAIProcessed: false
+ ))
+ coordinator.submit(.history(entries))
+ }
+ try await coordinator.waitUntilCurrent()
+ try samples.append(await self.appendMemorySample("burst drained", added: 1280, sourceRows: entries.count, store: store))
+ let burstStats = try await store.stats()
+ XCTAssertEqual(burstStats.activeRowCount, 0)
+ // More words require more memory even with the same row-count limit.
+ for added in 1281...1408 {
+ entries.append(TranscriptionHistoryEntry(
+ rawText: "not indexed",
+ processedText: "longmarker update\(added) " + String(repeating: "longer dictation contains discussion of project details and followup actions ", count: 220),
+ appName: "Synthetic fixture",
+ windowTitle: "Long additions",
+ wasAIProcessed: false
+ ))
+ coordinator.submit(.history(entries))
+ try await coordinator.waitUntilCurrent()
+ if added % 32 == 0 {
+ try samples.append(await self.appendMemorySample("long entries", added: added, sourceRows: entries.count, store: store))
+ }
+ }
+ try await Task.sleep(for: .milliseconds(300))
+ try samples.append(await self.appendMemorySample("settled", added: 1408, sourceRows: entries.count, store: store))
+ var actual = Set<UUID>()
+ for try await row in store.documents(fields: []) {
+ actual.insert(row.id.uuid)
+ }
+ XCTAssertEqual(actual, Set(entries.map(\.id)))
+ let latest = try await index.query(.history, text: "longmarker update1408", limit: 50)
+ XCTAssertTrue(latest.contains { $0.id == entries.last?.id })
+ sampler?.cancel()
+ await sampler?.value
+ await coordinator.stop()
+ await database.closeAll()
+ let closed = Self.physicalFootprint()
+ let reopenedRoot = FluidZeppelinRoot(root: self.root.appendingPathComponent("append-memory", isDirectory: true))
+ let reopened = SearchIndex(root: reopenedRoot)
+ let reopenStart = ContinuousClock.now
+ let reopenedHits = try await reopened.query(.history, text: "longmarker update1408", limit: 50)
+ let reopenMilliseconds = Self.milliseconds(since: reopenStart)
+ XCTAssertTrue(reopenedHits.contains { $0.id == entries.last?.id })
+ let reopenedStore = try await reopened.namespace(.history)
+ try samples.append(await self.appendMemorySample("reopened", added: 1408, sourceRows: entries.count, store: reopenedStore))
+ await reopenedRoot.closeAll()
+ let sorted = timings.sorted()
+ let report = SearchAppendMemoryReport(
+ initialRows: 12_880,
+ addedRows: 1408,
+ peakPhysicalFootprintBytes: peak,
+ closedPhysicalFootprintBytes: closed,
+ samplerTicks: samplerTicks,
+ medianUpdateMilliseconds: sorted[sorted.count / 2],
+ p95UpdateMilliseconds: sorted[Int(Double(sorted.count - 1) * 0.95)],
+ reopenMilliseconds: reopenMilliseconds,
+ samples: samples
+ )
+ let output = URL(fileURLWithPath: path)
+ try FileManager.default.createDirectory(at: output.deletingLastPathComponent(), withIntermediateDirectories: true)
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ try encoder.encode(report).write(to: output, options: .withoutOverwriting)
+ print("Search append memory report: \(output.path)")
+ } catch {
+ sampler?.cancel()
+ await sampler?.value
+ await coordinator.stop()
+ await database.closeAll()
+ throw error
+ }
+ }
+
+ private func appendMemorySample(_ phase: String, added: Int, sourceRows: Int, store: ZeppelinStore) async throws -> SearchAppendMemorySample {
+ let stats = try await store.stats()
+ return SearchAppendMemorySample(
+ phase: phase,
+ addedRows: added,
+ sourceRows: sourceRows,
+ processPhysicalFootprintBytes: Self.physicalFootprint(),
+ index: SearchBenchmarkStats(stats),
+ cacheBytes: stats.cacheBytes,
+ queryPoolBytes: stats.queryPoolBytes,
+ openFiles: stats.openFiles
+ )
+ }
+
+ /// Explicitly supplied JSON is an exported private copy, never a production
+ /// store. Both variants modify only unique test roots. Reports omit all text.
+ func testOptInCopiedRealHistoryReopenBenchmark() async throws {
+ let environment = ProcessInfo.processInfo.environment
+ guard let recordsPath = environment["FLUIDVOICE_SEARCH_BENCHMARK_RECORDS"],
+ let outputPath = environment["FLUIDVOICE_SEARCH_BENCHMARK_OUTPUT"]
+ else { throw XCTSkip("Supply private record JSON and a report directory to run the search reopen benchmark") }
+ let input = URL(fileURLWithPath: recordsPath)
+ let attributes = try FileManager.default.attributesOfItem(atPath: input.path)
+ XCTAssertLessThanOrEqual((attributes[.size] as? NSNumber)?.intValue ?? Int.max, 256 * 1024 * 1024)
+ guard (attributes[.size] as? NSNumber)?.intValue ?? Int.max <= 256 * 1024 * 1024 else {
+ throw CocoaError(.fileReadTooLarge)
+ }
+ let records = try JSONDecoder().decode([SearchBenchmarkRecord].self, from: Data(contentsOf: input)).map(\.record)
+ XCTAssertTrue((10_000...20_000).contains(records.count), "Use the real approximately 13k-record corpus")
+ let expectedIDs = Set(records.map(\.id))
+ XCTAssertEqual(expectedIDs.count, records.count)
+ guard (10_000...20_000).contains(records.count), expectedIDs.count == records.count else {
+ throw CocoaError(.coderInvalidValue)
+ }
+ let queries = ["the", "meeting", "mo", "project", "update"]
+ let labels: [String]
+ if let variant = environment["FLUIDVOICE_SEARCH_BENCHMARK_VARIANT"] {
+ guard ["baseline", "optimized"].contains(variant) else { throw CocoaError(.coderInvalidValue) }
+ labels = [variant]
+ } else {
+ labels = ["baseline", "optimized"]
+ }
+ var variants: [SearchBenchmarkVariant] = []
+ try FileManager.default.createDirectory(at: self.root, withIntermediateDirectories: true)
+ for label in labels {
+ let directory = self.root.appendingPathComponent(label, isDirectory: true)
+ if let sourcePath = environment["FLUIDVOICE_SEARCH_BENCHMARK_SOURCE_INDEX"] {
+ // Optional frozen index copy permits unchanged legacy-backfill
+ // timing. The provided source directory is never opened/written.
+ try FileManager.default.copyItem(at: URL(fileURLWithPath: sourcePath, isDirectory: true), to: directory)
+ }
+ let result = try await self.benchmarkVariant(label, directory: directory, records: records, queries: queries)
+ XCTAssertEqual(result.membershipSHA256, Self.membershipHash(expectedIDs))
+ if label == "optimized" { XCTAssertEqual(result.after.activeRows, 0) }
+ if let baseline = variants.first {
+ XCTAssertEqual(result.queryMembershipSHA256, baseline.queryMembershipSHA256, "Sealing must preserve all matching IDs; top-50 score ties may legitimately reorder")
+ XCTAssertEqual(result.initialUpserts, baseline.initialUpserts)
+ XCTAssertEqual(result.initialDeletes, baseline.initialDeletes)
+ }
+ variants.append(result)
+ if label == "optimized", let preparedPath = environment["FLUIDVOICE_SEARCH_BENCHMARK_EXPORT_PREPARED_INDEX"] {
+ // An explicitly requested private fixture for a fresh-process
+ // reopen measurement; never exported by ordinary test runs.
+ let destination = URL(fileURLWithPath: preparedPath, isDirectory: true)
+ try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
+ try FileManager.default.copyItem(at: directory, to: destination)
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: destination.path)
+ }
+ }
+ let output = URL(fileURLWithPath: outputPath, isDirectory: true)
+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let report = output.appendingPathComponent("search-index-benchmark-\(UUID().uuidString).json")
+ try encoder.encode(variants).write(to: report, options: .withoutOverwriting)
+ print("Search index benchmark report: \(report.path)")
+ }
+
+ private func benchmarkVariant(_ label: String, directory: URL, records: [SearchIndexRecord], queries: [String]) async throws -> SearchBenchmarkVariant {
+ let root = FluidZeppelinRoot(root: directory)
+ let index = SearchIndex(root: root, maintenanceActiveRowLimit: label == "baseline" ? nil : 256)
+ let beforeOpenFootprint = Self.physicalFootprint()
+ let start = ContinuousClock.now
+ let store: ZeppelinStore
+ let before: StoreStats
+ let report: SearchIndex.ReconcileReport
+ let openMilliseconds: Double
+ let afterOpenFootprint: UInt64?
+ let reconcileMilliseconds: Double
+ let afterReconcileFootprint: UInt64?
+ let after: StoreStats
+ var membership = Set<UUID>()
+ var queryHashes: [String: String] = [:]
+ do {
+ store = try await index.namespace(.history)
+ openMilliseconds = Self.milliseconds(since: start)
+ afterOpenFootprint = Self.physicalFootprint()
+ before = try await store.stats()
+ let reconcileStart = ContinuousClock.now
+ report = try await index.reconcile(.history, with: records)
+ reconcileMilliseconds = Self.milliseconds(since: reconcileStart)
+ afterReconcileFootprint = Self.physicalFootprint()
+ after = try await store.stats()
+ for try await document in store.documents(fields: []) {
+ membership.insert(document.id.uuid)
+ }
+ // Full membership avoids mistaking a different ordering of equal
+ // BM25 scores at the result limit for a lost document.
+ for query in queries {
+ let hits = try await index.query(.history, text: query, limit: records.count)
+ queryHashes[query] = Self.membershipHash(Set(hits.map(\.id)))
+ }
+ } catch {
+ await root.closeAll()
+ throw error
+ }
+ await root.closeAll()
+ var reopens: [SearchBenchmarkReopen] = []
+ for iteration in 0..<5 {
+ let freshRoot = FluidZeppelinRoot(root: directory)
+ let fresh = SearchIndex(root: freshRoot, maintenanceActiveRowLimit: label == "baseline" ? nil : 256)
+ do {
+ let beforeQueryFootprint = Self.physicalFootprint()
+ let queryStart = ContinuousClock.now
+ // This first query opens the namespace; no cached actor/handle
+ // from a prior iteration can hide startup WAL replay.
+ let hits = try await fresh.query(.history, text: queries[iteration % queries.count], limit: 50)
+ let queryMilliseconds = Self.milliseconds(since: queryStart)
+ let afterQueryFootprint = Self.physicalFootprint()
+ let reconcileStart = ContinuousClock.now
+ let unchanged = try await fresh.reconcile(.history, with: records)
+ let reconcileMilliseconds = Self.milliseconds(since: reconcileStart)
+ let afterReconcileFootprint = Self.physicalFootprint()
+ XCTAssertEqual(unchanged, .init(upserted: 0, deleted: 0))
+ let freshStore = try await fresh.namespace(.history)
+ let stats = try await freshStore.stats()
+ let count = try await freshStore.count().count
+ XCTAssertEqual(count, UInt64(records.count))
+ reopens.append(SearchBenchmarkReopen(
+ queryMilliseconds: queryMilliseconds,
+ reconcileMilliseconds: reconcileMilliseconds,
+ returnedHits: hits.count,
+ beforeQueryPhysicalFootprintBytes: beforeQueryFootprint,
+ afterQueryPhysicalFootprintBytes: afterQueryFootprint,
+ afterReconcilePhysicalFootprintBytes: afterReconcileFootprint,
+ stats: SearchBenchmarkStats(stats)
+ ))
+ } catch {
+ await freshRoot.closeAll()
+ throw error
+ }
+ await freshRoot.closeAll()
+ }
+ return SearchBenchmarkVariant(
+ label: label,
+ recordCount: records.count,
+ openMilliseconds: openMilliseconds,
+ reconcileMilliseconds: reconcileMilliseconds,
+ initialUpserts: report.upserted,
+ initialDeletes: report.deleted,
+ beforeOpenPhysicalFootprintBytes: beforeOpenFootprint,
+ afterOpenPhysicalFootprintBytes: afterOpenFootprint,
+ afterReconcilePhysicalFootprintBytes: afterReconcileFootprint,
+ before: SearchBenchmarkStats(before),
+ after: SearchBenchmarkStats(after),
+ membershipSHA256: Self.membershipHash(membership),
+ queryMembershipSHA256: queryHashes,
+ reopens: reopens
+ )
+ }
+
+ private static func membershipHash(_ ids: Set<UUID>) -> String {
+ let input = ids.map(\.uuidString).sorted().joined(separator: "\n")
+ return SHA256.hash(data: Data(input.utf8)).map { String(format: "%02x", $0) }.joined()
+ }
+
+ private static func milliseconds(since start: ContinuousClock.Instant) -> Double {
+ let components = start.duration(to: .now).components
+ return Double(components.seconds) * 1000 + Double(components.attoseconds) / 1_000_000_000_000_000
+ }
+
+ private static func physicalFootprint() -> UInt64? {
+ var info = task_vm_info_data_t()
+ var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
+ let capacity = Int(count)
+ let result = withUnsafeMutablePointer(to: &info) { pointer in
+ pointer.withMemoryRebound(to: integer_t.self, capacity: capacity) {
+ task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
+ }
+ }
+ return result == KERN_SUCCESS ? info.phys_footprint : nil
+ }
+}
+
+private struct SearchAppendMemorySample: Codable {
+ let phase: String
+ let addedRows: Int
+ let sourceRows: Int
+ let processPhysicalFootprintBytes: UInt64?
+ let index: SearchBenchmarkStats
+ let cacheBytes: UInt64
+ let queryPoolBytes: UInt64
+ let openFiles: UInt64
+}
+
+private struct SearchAppendMemoryReport: Codable {
+ let initialRows: Int
+ let addedRows: Int
+ let peakPhysicalFootprintBytes: UInt64
+ let closedPhysicalFootprintBytes: UInt64?
+ let samplerTicks: Int
+ let medianUpdateMilliseconds: Double
+ let p95UpdateMilliseconds: Double
+ let reopenMilliseconds: Double
+ let samples: [SearchAppendMemorySample]
}
diff --git a/Tests/FluidDictationIntegrationTests/SettingsBackupRoundTripTests.swift b/Tests/FluidDictationIntegrationTests/SettingsBackupRoundTripTests.swift
new file mode 100644
index 00000000..72c0e9e7
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/SettingsBackupRoundTripTests.swift
@@ -0,0 +1,157 @@
+import AppKit
+@testable import FluidVoice_Debug
+import XCTest
+
+@MainActor
+final class SettingsBackupRoundTripTests: XCTestCase {
+ func testModernBackupExportsAndRestoresMeetingIdleAndPromptConfiguration() throws {
+ try self.withSavedDefaults {
+ let settings = SettingsStore.shared
+ let profile = self.profile(id: "backup-dictation")
+ let meeting = self.meetingDefaults()
+ let configurations = self.configurations(profileID: profile.id)
+ settings.dictationPromptProfiles = [profile]
+ settings.meetingRecordingDefaults = meeting
+ settings.privateAIIdleUnload = .oneHour
+ settings.dictationPromptConfigurations = configurations
+ let payload = settings.makeBackupPayload()
+ let encoded = try JSONEncoder().encode(payload)
+ let json = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any])
+ XCTAssertNotNil(json["meetingRecordingDefaults"])
+ XCTAssertEqual(json["privateAIIdleUnload"] as? Int, 60)
+ XCTAssertNotNil(json["dictationPromptConfigurations"])
+
+ settings.meetingRecordingDefaults = .unconfigured
+ settings.privateAIIdleUnload = .never
+ settings.dictationPromptConfigurations = [:]
+ settings.dictationPromptProfiles = []
+ try settings.restore(
+ from: JSONDecoder().decode(SettingsBackupPayload.self, from: encoded),
+ promptProfiles: [profile],
+ appPromptBindings: []
+ )
+ XCTAssertEqual(settings.meetingRecordingDefaults, meeting)
+ XCTAssertEqual(settings.privateAIIdleUnload, .oneHour)
+ XCTAssertEqual(settings.dictationPromptConfigurations, configurations)
+ XCTAssertEqual(settings.dictationPromptShortcutAssignments().count, 3)
+ XCTAssertEqual(settings.selectedProviderID, payload.selectedProviderID)
+ XCTAssertEqual(settings.primaryDictationShortcuts, payload.primaryDictationShortcuts)
+ }
+ }
+
+ func testLegacyAbsentFieldsPreserveCurrentPreferences() throws {
+ try self.withSavedDefaults {
+ let settings = SettingsStore.shared
+ let profile = self.profile(id: "legacy-survivor")
+ settings.dictationPromptProfiles = [profile]
+ let payload = try self.payload(removing: [
+ "meetingRecordingDefaults", "privateAIIdleUnload", "dictationPromptConfigurations",
+ ])
+ let meeting = self.meetingDefaults()
+ let configurations = self.configurations(profileID: profile.id)
+ settings.meetingRecordingDefaults = meeting
+ settings.privateAIIdleUnload = .thirtyMinutes
+ settings.dictationPromptConfigurations = configurations
+ settings.restore(from: payload, promptProfiles: [profile], appPromptBindings: [])
+ XCTAssertEqual(settings.meetingRecordingDefaults, meeting)
+ XCTAssertEqual(settings.privateAIIdleUnload, .thirtyMinutes)
+ XCTAssertEqual(settings.dictationPromptConfigurations, configurations)
+ }
+ }
+
+ func testExplicitEmptyPromptConfigurationsClearPreviousMappings() throws {
+ try self.withSavedDefaults {
+ let settings = SettingsStore.shared
+ settings.dictationPromptConfigurations = [:]
+ let payload = settings.makeBackupPayload()
+ let json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(payload)) as? [String: Any])
+ XCTAssertEqual((json["dictationPromptConfigurations"] as? [String: Any])?.count, 0)
+ settings.dictationPromptConfigurations = self.configurations(profileID: "previous")
+ settings.restore(from: payload, promptProfiles: [], appPromptBindings: [])
+ XCTAssertTrue(settings.dictationPromptConfigurations.isEmpty)
+ XCTAssertTrue(settings.dictationPromptShortcutAssignments().isEmpty)
+ }
+ }
+
+ func testImportedPromptConfigurationsUseRestoredProfilesAndCannotActivateInvalidReferences() throws {
+ try self.withSavedDefaults {
+ let settings = SettingsStore.shared
+ let valid = self.profile(id: "imported")
+ let edit = self.profile(id: "edit-only", mode: .edit)
+ let shortcut = HotkeyShortcut(keyCode: 2, modifierFlags: [.control, .option])
+ let imported: [String: SettingsStore.DictationPromptConfiguration] = [
+ "profile:imported": .init(shortcut: shortcut, providerID: "openai", modelName: "imported-model"),
+ "profile:missing": .init(shortcut: shortcut, providerID: "openai", modelName: "missing-model"),
+ "profile:edit-only": .init(shortcut: shortcut, providerID: "openai", modelName: "edit-model"),
+ "unknown": .init(shortcut: shortcut),
+ "__default__": .init(shortcut: HotkeyShortcut(keyCode: 2, modifierFlags: []), providerID: "openai", modelName: "default-model"),
+ "__privateAI__": .init(shortcut: shortcut, providerID: "apple-intelligence", modelName: "retired-model"),
+ ]
+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(settings.makeBackupPayload())) as? [String: Any])
+ json["dictationPromptConfigurations"] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(imported))
+ let payload = try JSONDecoder().decode(SettingsBackupPayload.self, from: JSONSerialization.data(withJSONObject: json))
+ settings.dictationPromptProfiles = [self.profile(id: "previous")]
+ settings.dictationPromptConfigurations = ["profile:previous": .init(shortcut: shortcut)]
+ settings.restore(from: payload, promptProfiles: [valid, edit], appPromptBindings: [])
+
+ XCTAssertEqual(settings.dictationPromptConfigurations["profile:imported"], imported["profile:imported"])
+ XCTAssertNil(settings.dictationPromptConfigurations["profile:missing"])
+ XCTAssertNil(settings.dictationPromptConfigurations["profile:edit-only"])
+ XCTAssertNil(settings.dictationPromptConfigurations["profile:previous"])
+ XCTAssertNil(settings.dictationPromptConfigurations["unknown"])
+ XCTAssertNil(settings.dictationPromptConfiguration(for: .default).shortcut)
+ XCTAssertEqual(settings.dictationPromptConfiguration(for: .default).modelName, "default-model")
+ XCTAssertEqual(settings.dictationPromptConfigurations["__privateAI__"], .init(shortcut: shortcut))
+ XCTAssertEqual(settings.dictationPromptShortcutAssignments().count, 2)
+ XCTAssertEqual(settings.selectedProviderID, payload.selectedProviderID)
+ XCTAssertEqual(settings.primaryDictationShortcuts, payload.primaryDictationShortcuts)
+ }
+ }
+
+ private func payload(removing keys: [String]) throws -> SettingsBackupPayload {
+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(SettingsStore.shared.makeBackupPayload())) as? [String: Any])
+ for key in keys {
+ json.removeValue(forKey: key)
+ }
+ return try JSONDecoder().decode(SettingsBackupPayload.self, from: JSONSerialization.data(withJSONObject: json))
+ }
+
+ private func profile(id: String, mode: SettingsStore.PromptMode = .dictate) -> SettingsStore.DictationPromptProfile {
+ .init(id: id, name: "Backup fixture", prompt: "Keep these words", mode: mode)
+ }
+
+ private func configurations(profileID: String) -> [String: SettingsStore.DictationPromptConfiguration] {
+ [
+ "__default__": .init(shortcut: HotkeyShortcut(keyCode: 2, modifierFlags: .control), providerID: "openai", modelName: "default-model"),
+ "__privateAI__": .init(shortcut: HotkeyShortcut(keyCode: 3, modifierFlags: .control), providerID: "fluid-fixture", modelName: "private-model"),
+ "profile:\(profileID)": .init(shortcut: HotkeyShortcut(keyCode: 5, modifierFlags: .control), providerID: "custom:fixture", modelName: "profile-model"),
+ ]
+ }
+
+ private func meetingDefaults() -> MeetingRecordingDefaults {
+ .init(
+ isConfigured: true,
+ mode: .inRoom,
+ applicationBundleIdentifier: "fixture.meeting",
+ applicationDisplayName: "Fixture Meeting",
+ microphoneCaptureDeviceID: "fixture-capture",
+ microphoneCoreAudioUID: "fixture-core-audio",
+ microphoneRole: .shared,
+ languageCode: "fr"
+ )
+ }
+
+ private func withSavedDefaults(_ body: () throws -> Void) throws {
+ let defaults = UserDefaults.standard
+ let domain = try XCTUnwrap(Bundle.main.bundleIdentifier)
+ let original = defaults.persistentDomain(forName: domain)
+ defer {
+ if let original {
+ defaults.setPersistentDomain(original, forName: domain)
+ } else {
+ defaults.removePersistentDomain(forName: domain)
+ }
+ }
+ try body()
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/SpeechModelInstallationSnapshotTests.swift b/Tests/FluidDictationIntegrationTests/SpeechModelInstallationSnapshotTests.swift
new file mode 100644
index 00000000..2e0da1f6
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/SpeechModelInstallationSnapshotTests.swift
@@ -0,0 +1,539 @@
+import CryptoKit
+import Darwin
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+@MainActor
+private final class InstallationCapture {
+ var modelID = "first"
+}
+
+private actor InstallationScanGate {
+ private(set) var calls = 0
+ private(set) var observedIDs: [[String]] = []
+ private var continuations: [CheckedContinuation<Set<String>, Error>] = []
+
+ func scan(_ probes: [SpeechModelInstallationSnapshot.Probe]) async throws -> Set<String> {
+ self.calls += 1
+ self.observedIDs.append(probes.map(\.modelID))
+ return try await withCheckedThrowingContinuation { self.continuations.append($0) }
+ }
+
+ func complete(_ result: Result<Set<String>, Error>) {
+ self.continuations.removeFirst().resume(with: result)
+ }
+}
+
+private actor CompactCatalogFetchGate {
+ private(set) var calls = 0
+ private var waiting: [CheckedContinuation<Data, Error>] = []
+
+ func fetch() async throws -> Data {
+ self.calls += 1
+ return try await withCheckedThrowingContinuation { self.waiting.append($0) }
+ }
+
+ func complete(_ result: Result<Data, Error>) {
+ self.waiting.removeFirst().resume(with: result)
+ }
+}
+
+private final nonisolated class CatalogTestClock: @unchecked Sendable {
+ private let lock = NSLock()
+ private var date = Date(timeIntervalSince1970: 1_000_000)
+
+ func now() -> Date { self.lock.withLock { self.date } }
+ func advance(_ seconds: TimeInterval) { self.lock.withLock { self.date.addTimeInterval(seconds) } }
+}
+
+@MainActor
+final class SpeechModelInstallationSnapshotTests: XCTestCase {
+ private func waitUntil(_ condition: @escaping @MainActor () async -> Bool) async throws {
+ let deadline = Date().addingTimeInterval(2)
+ while !(await condition()), Date() < deadline {
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ let completed = await condition()
+ XCTAssertTrue(completed, "Snapshot operation must finish within the test deadline")
+ }
+
+ private struct FeedCase: Decodable {
+ let file: String
+ let lastSequence: Int
+ let verdict: String
+ }
+
+ private struct PickCase: Decodable {
+ let file: String
+ let model: String
+ let platform: String
+ let build: Int
+ let format: Int
+ let release: String?
+ }
+
+ private var fixtures: URL {
+ URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/ModelRelease")
+ }
+
+ private func fixture<T: Decodable>(_ type: T.Type, _ path: String) throws -> T {
+ try JSONDecoder().decode(type, from: Data(contentsOf: self.fixtures.appendingPathComponent(path)))
+ }
+
+ private func fixtureKey() throws -> String {
+ try XCTUnwrap(self.fixture([String: String].self, "test_key.json")["publicKey"])
+ }
+
+ private func releaseModels(release: String = "1.2.0", format: Int = 1, minBuild: Int = 27) -> [String: [String: [[String: Any]]]] {
+ var result: [String: [String: [[String: Any]]]] = [:]
+ for descriptor in [ParakeetSpeechModelCatalog.mini, ParakeetSpeechModelCatalog.pico] {
+ result[descriptor.variant.rawValue] = ["macos": [[
+ "release": release,
+ "url": "https://models.fluidvoice.app/parakeet/fluid-\(descriptor.variant.rawValue)/\(release)/\(descriptor.folderName).tar",
+ "sha256": String(repeating: descriptor.variant == .mini ? "a" : "b", count: 64),
+ "manifestSHA256": String(repeating: descriptor.variant == .mini ? "c" : "d", count: 64),
+ "bytes": descriptor.expectedDownloadBytes,
+ "format": format,
+ "minBuild": minBuild,
+ ]]]
+ }
+ return result
+ }
+
+ private func signedFeed(
+ key: Curve25519.Signing.PrivateKey,
+ sequence: Int,
+ models: [String: [String: [[String: Any]]]]
+ ) throws -> Data {
+ let payload = try JSONSerialization.data(withJSONObject: ["schema": 1, "sequence": sequence, "models": models])
+ return try JSONSerialization.data(withJSONObject: [
+ "payload": payload.base64EncodedString(), "signature": key.signature(for: payload).base64EncodedString(),
+ ])
+ }
+
+ func testEveryCanonicalFeedFixtureGetsTheSameVerdict() throws {
+ let key = try self.fixtureKey()
+ let cases = try self.fixture([FeedCase].self, "feeds/expected.json")
+ XCTAssertEqual(cases.count, 40)
+ for feed in cases {
+ let data = try Data(contentsOf: self.fixtures.appendingPathComponent("feeds/\(feed.file)"))
+ let verdict: String
+ do {
+ _ = try SpeechModelFeed.verified(envelope: data, publicKeys: [key], lastSequence: feed.lastSequence)
+ verdict = "ok"
+ } catch {
+ verdict = (error as? SpeechModelFeed.Rejection)?.rawValue ?? String(describing: error)
+ }
+ XCTAssertEqual(verdict, feed.verdict, feed.file)
+ }
+ }
+
+ func testCanonicalReleasePicksAndProductionKeysMatchIPhone() throws {
+ let key = try self.fixtureKey()
+ let picks = try self.fixture([PickCase].self, "feeds/picks.json")
+ XCTAssertEqual(picks.count, 7)
+ for pick in picks {
+ let data = try Data(contentsOf: self.fixtures.appendingPathComponent("feeds/\(pick.file)"))
+ let payload = try SpeechModelFeed.verified(envelope: data, publicKeys: [key], lastSequence: 0)
+ XCTAssertEqual(SpeechModelFeed.entry(in: payload, model: pick.model, platform: pick.platform, build: pick.build, supportedFormat: pick.format)?.release, pick.release)
+ }
+ let keys = try self.fixture([String: String].self, "public_keys.json")
+ XCTAssertEqual(CompactSpeechModelReleaseCatalog.publicKeys, try [XCTUnwrap(keys["main"]), XCTUnwrap(keys["spare"])])
+ let data = try Data(contentsOf: self.fixtures.appendingPathComponent("feeds/good.json"))
+ XCTAssertThrowsError(try SpeechModelFeed.verified(envelope: data, publicKeys: CompactSpeechModelReleaseCatalog.publicKeys, lastSequence: 0)) {
+ XCTAssertEqual($0 as? SpeechModelFeed.Rejection, .badSignature)
+ }
+ XCTAssertEqual(CompactSpeechModelReleaseCatalog.manifestURL.absoluteString, "https://models.fluidvoice.app/feed/v1/speech-models.json")
+ XCTAssertEqual(CompactSpeechModelReleaseCatalog.maximumManifestBytes, 64 * 1024)
+ }
+
+ func testMacReleaseChangesOnlyTrustedMetadataAndNeverPicksIOS() throws {
+ let key = Curve25519.Signing.PrivateKey()
+ let payload = try SpeechModelFeed.verified(
+ envelope: self.signedFeed(key: key, sequence: 5, models: self.releaseModels()),
+ publicKeys: [key.publicKey.rawRepresentation.base64EncodedString()],
+ lastSequence: 0
+ )
+ let descriptors = CompactSpeechModelReleaseCatalog.descriptors(in: payload, build: 27)
+ for original in [ParakeetSpeechModelCatalog.mini, ParakeetSpeechModelCatalog.pico] {
+ let release = try XCTUnwrap(descriptors[original.variant])
+ XCTAssertNotEqual(release.archiveSHA256, original.archiveSHA256)
+ XCTAssertNotEqual(release.manifestSHA256, original.manifestSHA256)
+ XCTAssertEqual(release.expectedDownloadBytes, original.expectedDownloadBytes)
+ XCTAssertEqual(release.folderName, original.folderName)
+ XCTAssertEqual(release.requiredModelNames, original.requiredModelNames)
+ XCTAssertEqual(release.vocabularyFile, original.vocabularyFile)
+ XCTAssertEqual(release.displayName, original.displayName)
+ XCTAssertEqual(release.cardDescription, original.cardDescription)
+ XCTAssertEqual(release.supportedLanguageCodes, ["en"])
+ }
+ let builtins: [ParakeetSpeechModelCatalog.Variant: ParakeetSpeechModelCatalog.Descriptor] = [.mini: ParakeetSpeechModelCatalog.mini, .pico: ParakeetSpeechModelCatalog.pico]
+ XCTAssertEqual(CompactSpeechModelReleaseCatalog.descriptors(in: payload, build: 26), builtins)
+ let iosOnly: [String: [String: [[String: Any]]]] = [
+ "mini": ["ios": self.releaseModels()["mini"]?["macos"] ?? [], "macos": []],
+ "pico": ["ios": [], "macos": []],
+ ]
+ let incompatible = [self.releaseModels(format: 2), self.releaseModels(minBuild: 28), iosOnly]
+ for models in incompatible {
+ let fallback = try SpeechModelFeed.verified(
+ envelope: self.signedFeed(key: key, sequence: 6, models: models),
+ publicKeys: [key.publicKey.rawRepresentation.base64EncodedString()],
+ lastSequence: 5
+ )
+ XCTAssertEqual(CompactSpeechModelReleaseCatalog.descriptors(in: fallback, build: 27), builtins)
+ }
+ }
+
+ func testCatalogCoalescesAndAcceptsRollbackOnlyUnderNewSequence() async throws {
+ let key = Curve25519.Signing.PrivateKey()
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let cache = directory.appendingPathComponent("feed.json")
+ try self.signedFeed(key: key, sequence: 5, models: self.releaseModels()).write(to: cache)
+ let gate = CompactCatalogFetchGate()
+ let catalog = CompactSpeechModelReleaseCatalog(publicKeys: [key.publicKey.rawRepresentation.base64EncodedString()], cacheURL: cache, build: 27, fetch: { try await gate.fetch() })
+ let first = Task { await catalog.refreshIfNeeded() }
+ try await self.waitUntil { await gate.calls == 1 }
+ let second = Task { await catalog.refreshIfNeeded() }
+ XCTAssertEqual(catalog.snapshot.sequence, 5)
+ let cached = catalog.snapshot
+ try await gate.complete(.success(self.signedFeed(key: key, sequence: 4, models: self.releaseModels(release: "1.3.0"))))
+ await first.value
+ await second.value
+ XCTAssertEqual(catalog.snapshot, cached)
+ await catalog.refreshIfNeeded()
+ let calls = await gate.calls
+ XCTAssertEqual(calls, 1, "Failed checks retry hourly, not on every appearance")
+ let retry = Task { await catalog.refreshIfNeeded(force: true) }
+ try await self.waitUntil { await gate.calls == 2 }
+ try await gate.complete(.success(self.signedFeed(key: key, sequence: 6, models: self.releaseModels(release: "1.0.0"))))
+ await retry.value
+ XCTAssertEqual(catalog.snapshot.sequence, 6)
+ XCTAssertTrue(catalog.descriptor(for: .pico).archiveURL?.path.contains("/1.0.0/") == true, "Intentional rollback is allowed under a higher signed sequence")
+ let retained = try SpeechModelFeed.verified(envelope: Data(contentsOf: cache), publicKeys: [key.publicKey.rawRepresentation.base64EncodedString()], lastSequence: 6)
+ XCTAssertEqual(retained.sequence, 6)
+ XCTAssertEqual(catalog.descriptor(for: .v3), ParakeetSpeechModelCatalog.v3)
+ XCTAssertNil(catalog.descriptor(for: SettingsStore.SpeechModel.appleSpeech))
+ let reopened = CompactSpeechModelReleaseCatalog(
+ publicKeys: [key.publicKey.rawRepresentation.base64EncodedString()],
+ cacheURL: cache,
+ build: 27,
+ fetch: { XCTFail("Persisted successful checks must not refetch before one day"); throw URLError(.timedOut) }
+ )
+ await reopened.refreshIfNeeded()
+ XCTAssertEqual(reopened.snapshot.sequence, 6)
+ XCTAssertEqual(reopened.descriptor(for: .mini), catalog.descriptor(for: .mini))
+ }
+
+ func testRejectionsPersistAreBoundedAndCannotChangeModelSelection() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let cache = directory.appendingPathComponent("feed.json")
+ let catalog = CompactSpeechModelReleaseCatalog(cacheURL: cache, fetch: { throw URLError(.timedOut) })
+ let selection = SettingsStore.shared.selectedSpeechModel
+ let hash = try XCTUnwrap(ParakeetSpeechModelCatalog.mini.manifestSHA256)
+ await catalog.reject(manifestSHA256: hash)
+ let revision = catalog.revision
+ await catalog.reject(manifestSHA256: hash)
+ await catalog.reject(manifestSHA256: "invalid")
+ XCTAssertEqual(catalog.revision, revision)
+ XCTAssertEqual(catalog.snapshot.rejectedManifestHashes, [hash])
+ XCTAssertEqual(catalog.descriptor(for: .mini), ParakeetSpeechModelCatalog.mini)
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selection)
+ let reopened = CompactSpeechModelReleaseCatalog(cacheURL: cache, fetch: { throw URLError(.timedOut) })
+ await reopened.refreshIfNeeded()
+ XCTAssertTrue(reopened.snapshot.rejectedManifestHashes.contains(hash))
+ let bounded = CompactSpeechModelReleaseCatalog(cacheURL: nil, fetch: { throw URLError(.timedOut) })
+ for number in 0..<70 {
+ await bounded.reject(manifestSHA256: String(format: "%064x", number))
+ }
+ XCTAssertEqual(bounded.snapshot.rejectedManifestHashes.count, 64)
+ XCTAssertFalse(bounded.snapshot.rejectedManifestHashes.contains(String(format: "%064x", 0)))
+ XCTAssertTrue(bounded.snapshot.rejectedManifestHashes.contains(String(format: "%064x", 69)))
+ }
+
+ func testCompetingCatalogsPreserveHighestSignedSequenceAndMergeRejections() async throws {
+ let key = Curve25519.Signing.PrivateKey()
+ let keys = [key.publicKey.rawRepresentation.base64EncodedString()]
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let cache = directory.appendingPathComponent("feed.json")
+ try self.signedFeed(key: key, sequence: 1, models: self.releaseModels()).write(to: cache)
+ let earlierGate = CompactCatalogFetchGate()
+ let laterGate = CompactCatalogFetchGate()
+ let earlier = CompactSpeechModelReleaseCatalog(publicKeys: keys, cacheURL: cache, build: 27, fetch: { try await earlierGate.fetch() })
+ let later = CompactSpeechModelReleaseCatalog(publicKeys: keys, cacheURL: cache, build: 27, fetch: { try await laterGate.fetch() })
+ let earlierCheck = Task { await earlier.refreshIfNeeded(force: true) }
+ try await self.waitUntil { await earlierGate.calls == 1 }
+ let laterCheck = Task { await later.refreshIfNeeded(force: true) }
+ try await self.waitUntil { await laterGate.calls == 1 }
+ try await laterGate.complete(.success(self.signedFeed(key: key, sequence: 3, models: self.releaseModels(release: "1.3.0"))))
+ await laterCheck.value
+ try await earlierGate.complete(.success(self.signedFeed(key: key, sequence: 2, models: self.releaseModels(release: "1.2.0"))))
+ await earlierCheck.value
+ XCTAssertEqual(earlier.snapshot.sequence, 3, "The stale writer must adopt the higher on-disk signed feed")
+ XCTAssertEqual(earlier.descriptor(for: .mini), later.descriptor(for: .mini))
+ XCTAssertEqual(try SpeechModelFeed.verified(envelope: Data(contentsOf: cache), publicKeys: keys, lastSequence: 3).sequence, 3)
+ let lock = open(cache.appendingPathExtension("lock").path, O_RDWR)
+ XCTAssertGreaterThanOrEqual(lock, 0)
+ guard lock >= 0 else { return }
+ defer { Darwin.close(lock) }
+ XCTAssertEqual(flock(lock, LOCK_EX | LOCK_NB), 0)
+ let firstHash = String(repeating: "e", count: 64)
+ let secondHash = String(repeating: "f", count: 64)
+ let firstReject = Task { await earlier.reject(manifestSHA256: firstHash) }
+ let secondReject = Task { await later.reject(manifestSHA256: secondHash) }
+ try await self.waitUntil {
+ earlier.snapshot.rejectedManifestHashes.contains(firstHash) && later.snapshot.rejectedManifestHashes.contains(secondHash)
+ }
+ await firstReject.value
+ await secondReject.value
+ XCTAssertEqual(flock(lock, LOCK_UN), 0)
+ // Both bounded busy retries exhausted while the lock was held. The next
+ // duplicate rejection event must flush the one retained pending state.
+ await earlier.reject(manifestSHA256: firstHash)
+ await later.reject(manifestSHA256: secondHash)
+ let reopened = CompactSpeechModelReleaseCatalog(publicKeys: keys, cacheURL: cache, build: 27, fetch: { throw URLError(.timedOut) })
+ await reopened.refreshIfNeeded()
+ XCTAssertEqual(reopened.snapshot.sequence, 3)
+ XCTAssertEqual(reopened.snapshot.rejectedManifestHashes, [firstHash, secondHash], "Overlapping processes must retain both failures after restart")
+ XCTAssertEqual(CompactSpeechModelReleaseCatalog.cacheFolderName(bundleIdentifier: "com.FluidApp.app", isDebug: false), "FluidVoice")
+ XCTAssertEqual(CompactSpeechModelReleaseCatalog.cacheFolderName(bundleIdentifier: "com.FluidApp.app.debug", isDebug: true), "FluidVoice/com.FluidApp.app.debug")
+ }
+
+ func testSuccessfulChecksWaitOneDayAndFailedChecksRetryHourly() async throws {
+ let key = Curve25519.Signing.PrivateKey()
+ let clock = CatalogTestClock()
+ let gate = CompactCatalogFetchGate()
+ let catalog = CompactSpeechModelReleaseCatalog(
+ publicKeys: [key.publicKey.rawRepresentation.base64EncodedString()],
+ cacheURL: nil,
+ build: 27,
+ now: { clock.now() },
+ fetch: { try await gate.fetch() }
+ )
+ let first = Task { await catalog.refreshIfNeeded() }
+ try await self.waitUntil { await gate.calls == 1 }
+ try await gate.complete(.success(self.signedFeed(key: key, sequence: 1, models: self.releaseModels())))
+ await first.value
+ clock.advance(86_399)
+ await catalog.refreshIfNeeded()
+ let beforeDay = await gate.calls
+ XCTAssertEqual(beforeDay, 1)
+ clock.advance(1)
+ let failure = Task { await catalog.refreshIfNeeded() }
+ try await self.waitUntil { await gate.calls == 2 }
+ await gate.complete(.failure(URLError(.timedOut)))
+ await failure.value
+ let lastGood = catalog.snapshot
+ clock.advance(3599)
+ await catalog.refreshIfNeeded()
+ let beforeHour = await gate.calls
+ XCTAssertEqual(beforeHour, 2)
+ clock.advance(1)
+ let retry = Task { await catalog.refreshIfNeeded() }
+ try await self.waitUntil { await gate.calls == 3 }
+ await gate.complete(.failure(URLError(.timedOut)))
+ await retry.value
+ XCTAssertEqual(catalog.snapshot, lastGood)
+ }
+
+ func testOfflineInvalidFeedKeepsBuiltInModelsUsable() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let cache = directory.appendingPathComponent("feed.json")
+ try Data("{\"schema\":1,\"models\":[]}".utf8).write(to: cache)
+ let catalog = CompactSpeechModelReleaseCatalog(cacheURL: cache, fetch: { throw URLError(.timedOut) })
+ await catalog.refreshIfNeeded()
+ XCTAssertEqual(catalog.descriptor(for: .mini), ParakeetSpeechModelCatalog.mini)
+ XCTAssertEqual(catalog.descriptor(for: .pico), ParakeetSpeechModelCatalog.pico)
+ XCTAssertEqual(catalog.snapshot.sequence, 0)
+ }
+
+ func testOldCompleteCompactInstallIsUsableAndHasUpdateWithActualProfileHash() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let descriptor = ParakeetSpeechModelCatalog.mini
+ let directory = descriptor.cacheDirectory(in: root)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ for name in descriptor.requiredModelNames {
+ let artifact = directory.appendingPathComponent(name, isDirectory: true)
+ try FileManager.default.createDirectory(at: artifact, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: artifact.appendingPathComponent("weights", isDirectory: true), withIntermediateDirectories: true)
+ for file in ["coremldata.bin", "metadata.json", "weights/weight.bin"] {
+ try Data([1]).write(to: artifact.appendingPathComponent(file))
+ }
+ }
+ try Data("{}".utf8).write(to: directory.appendingPathComponent(descriptor.vocabularyFile))
+ let oldHash = String(repeating: "c", count: 64)
+ try Data(oldHash.utf8).write(to: directory.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName))
+ let probes = [SpeechModelInstallationSnapshot.Probe(modelID: descriptor.modelID, kind: .parakeet(descriptor))]
+ let snapshot = SpeechModelInstallationSnapshot(capture: { probes }, resultScanner: {
+ try await SpeechModelInstallationSnapshot.scanResult($0, cachesDirectory: root, modelsDirectory: root)
+ })
+ snapshot.refresh()
+ try await self.waitUntil { snapshot.state == .ready }
+ XCTAssertEqual(snapshot.installedIDs, [descriptor.modelID])
+ XCTAssertEqual(snapshot.updateAvailableIDs, [descriptor.modelID])
+ XCTAssertEqual(snapshot.installedArchiveHashes, [descriptor.modelID: oldHash])
+ XCTAssertEqual(snapshot.installedDescriptor(for: .fluidParakeetMini)?.pronunciationModelKey, "\(descriptor.modelID):sha256:\(oldHash)")
+ XCTAssertNil(snapshot.installedDescriptor(for: .appleSpeech))
+ XCTAssertEqual(snapshot.latestDescriptors[descriptor.modelID], descriptor)
+ XCTAssertFalse(descriptor.artifactsAreComplete(at: directory), "Old complete weights cannot count as latest")
+ XCTAssertEqual(
+ try Data(contentsOf: directory.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName)),
+ Data(oldHash.utf8),
+ "Checking cannot replace the installed checkpoint"
+ )
+ try Data((descriptor.archiveSHA256 ?? "").utf8).write(to: directory.appendingPathComponent(ParakeetSpeechModelCatalog.installationRevisionFileName))
+ snapshot.refresh()
+ try await self.waitUntil { snapshot.state == .ready }
+ XCTAssertEqual(snapshot.installedIDs, [descriptor.modelID])
+ XCTAssertTrue(snapshot.updateAvailableIDs.isEmpty)
+
+ let manifestBytes = Data("{\"schema\":1}".utf8)
+ let manifestHash = SHA256.hash(data: manifestBytes).map { String(format: "%02x", $0) }.joined()
+ let manifestFile = directory.appendingPathComponent("manifest.json")
+ try manifestBytes.write(to: manifestFile)
+ let sameManifest = descriptor.replacingArchive(url: descriptor.archiveURL, sha256: oldHash, manifestSHA256: manifestHash)
+ let matching = try await SpeechModelInstallationSnapshot.scanResult(
+ [.init(modelID: descriptor.modelID, kind: .parakeet(sameManifest))], cachesDirectory: root, modelsDirectory: root
+ )
+ XCTAssertEqual(matching.installedManifestHashes, [descriptor.modelID: manifestHash])
+ XCTAssertTrue(matching.updateAvailableIDs.isEmpty, "Manifest identity wins even when archive packaging differs")
+ let newManifest = String(repeating: "d", count: 64)
+ let update = sameManifest.replacingArchive(url: descriptor.archiveURL, sha256: oldHash, manifestSHA256: newManifest)
+ let differing = try await SpeechModelInstallationSnapshot.scanResult(
+ [.init(modelID: descriptor.modelID, kind: .parakeet(update))], cachesDirectory: root, modelsDirectory: root
+ )
+ XCTAssertEqual(differing.updateAvailableIDs, [descriptor.modelID])
+ let rejected = try await SpeechModelInstallationSnapshot.scanResult(
+ [.init(modelID: descriptor.modelID, kind: .parakeet(update), rejectedManifestHashes: [newManifest])], cachesDirectory: root, modelsDirectory: root
+ )
+ XCTAssertEqual(rejected.installedIDs, [descriptor.modelID])
+ XCTAssertTrue(rejected.updateAvailableIDs.isEmpty, "A failed runtime release must not nag the user again")
+ XCTAssertEqual(rejected.installedArchiveHashes, matching.installedArchiveHashes, "Feed identity must not change pronunciation checkpoint identity")
+ XCTAssertEqual(try Data(contentsOf: manifestFile), manifestBytes, "Checking and rejecting cannot change installed files")
+ }
+
+ func testRapidRefreshScansOnlyInitialAndLatestSnapshotAndRejectsOldResult() async throws {
+ let gate = InstallationScanGate()
+ let capture = InstallationCapture()
+ let snapshot = SpeechModelInstallationSnapshot(capture: {
+ [.init(modelID: capture.modelID, kind: .builtIn)]
+ }, scanner: { try await gate.scan($0) })
+ snapshot.refresh()
+ try await self.waitUntil { await gate.calls == 1 }
+ capture.modelID = "middle"
+ snapshot.refresh()
+ capture.modelID = "latest"
+ snapshot.refresh()
+ await gate.complete(.success(["first"]))
+ try await self.waitUntil { await gate.calls == 2 }
+ XCTAssertEqual(snapshot.state, .checking)
+ XCTAssertTrue(snapshot.installedIDs.isEmpty, "An outdated scan must not publish")
+ XCTAssertFalse(snapshot.canUseModelActions)
+ await gate.complete(.success(["latest"]))
+ try await self.waitUntil { snapshot.state == .ready }
+ XCTAssertEqual(snapshot.installedIDs, ["latest"])
+ let observed = await gate.observedIDs
+ XCTAssertEqual(observed, [["first"], ["latest"]])
+ XCTAssertTrue(snapshot.canUseModelActions)
+ }
+
+ func testCancelDrainsOldWorkerBeforeRetryAndNeverPublishesCanceledResult() async throws {
+ let gate = InstallationScanGate()
+ let snapshot = SpeechModelInstallationSnapshot(capture: { [] }, scanner: { try await gate.scan($0) })
+ snapshot.refresh()
+ try await self.waitUntil { await gate.calls == 1 }
+ snapshot.cancel()
+ XCTAssertEqual(snapshot.state, .failed)
+ snapshot.refresh()
+ let beforeDrain = await gate.calls
+ XCTAssertEqual(beforeDrain, 1, "A retry must not start overlapping filesystem work")
+ await gate.complete(.success(["canceled"]))
+ try await self.waitUntil { await gate.calls == 2 }
+ XCTAssertFalse(snapshot.isInstalled(modelID: "canceled"))
+ await gate.complete(.success(["retry"]))
+ try await self.waitUntil { snapshot.state == .ready }
+ XCTAssertEqual(snapshot.installedIDs, ["retry"])
+ }
+
+ func testFailureClearsOldIDsAndAllowsSuccessfulRetry() async throws {
+ let gate = InstallationScanGate()
+ let snapshot = SpeechModelInstallationSnapshot(capture: { [] }, scanner: { try await gate.scan($0) })
+ snapshot.refresh()
+ try await self.waitUntil { await gate.calls == 1 }
+ await gate.complete(.success(["old"]))
+ try await self.waitUntil { snapshot.state == .ready }
+ snapshot.refresh()
+ try await self.waitUntil { await gate.calls == 2 }
+ await gate.complete(.failure(CocoaError(.fileReadNoSuchFile)))
+ try await self.waitUntil { snapshot.state == .failed }
+ XCTAssertTrue(snapshot.installedIDs.isEmpty)
+ XCTAssertFalse(snapshot.canUseModelActions)
+ snapshot.refresh()
+ try await self.waitUntil { await gate.calls == 3 }
+ await gate.complete(.success(["new"]))
+ try await self.waitUntil { snapshot.state == .ready }
+ XCTAssertEqual(snapshot.installedIDs, ["new"])
+ }
+
+ func testStalledIOHasBoundedFailureAndRejectsLateSuccess() async throws {
+ let gate = InstallationScanGate()
+ let snapshot = SpeechModelInstallationSnapshot(timeoutNanoseconds: 20_000_000, capture: { [] }, scanner: { try await gate.scan($0) })
+ snapshot.refresh()
+ try await self.waitUntil { await gate.calls == 1 }
+ try await self.waitUntil { snapshot.state == .failed }
+ XCTAssertTrue(snapshot.installedIDs.isEmpty)
+ XCTAssertFalse(snapshot.canUseModelActions)
+ await gate.complete(.success(["late"]))
+ try await Task.sleep(for: .milliseconds(10))
+ XCTAssertEqual(snapshot.state, .failed)
+ XCTAssertFalse(snapshot.isInstalled(modelID: "late"))
+ }
+
+ func testCompletedDeadlineCannotCancelLaterRefresh() async throws {
+ let gate = InstallationScanGate()
+ let snapshot = SpeechModelInstallationSnapshot(timeoutNanoseconds: 100_000_000, capture: { [] }, scanner: { try await gate.scan($0) })
+ snapshot.refresh()
+ try await self.waitUntil { await gate.calls == 1 }
+ await gate.complete(.success(["one"]))
+ try await self.waitUntil { snapshot.state == .ready }
+ try await Task.sleep(for: .milliseconds(70))
+ snapshot.refresh()
+ try await self.waitUntil { await gate.calls == 2 }
+ try await Task.sleep(for: .milliseconds(40))
+ XCTAssertEqual(snapshot.state, .checking, "The first canceled deadline must not cancel the new request")
+ await gate.complete(.success(["two"]))
+ try await self.waitUntil { snapshot.state == .ready }
+ }
+
+ func testOffMainScannerChecksExactWhisperSizeAndHasNoStatefulSideEffects() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let models = root.appendingPathComponent("WhisperModels", isDirectory: true)
+ try FileManager.default.createDirectory(at: models, withIntermediateDirectories: true)
+ let file = models.appendingPathComponent("fixture.bin")
+ try Data([1, 2, 3]).write(to: file)
+ let selection = SettingsStore.shared.selectedSpeechModel
+ let ids = try await SpeechModelInstallationSnapshot.scan(
+ [
+ .init(modelID: "bundled", kind: .builtIn),
+ .init(modelID: "exact", kind: .whisper(file: "fixture.bin", expectedBytes: 3)),
+ .init(modelID: "wrong-size", kind: .whisper(file: "fixture.bin", expectedBytes: 4)),
+ .init(modelID: "missing", kind: .whisper(file: "missing.bin", expectedBytes: 3)),
+ .init(modelID: "unsupported", kind: .unavailable),
+ ],
+ cachesDirectory: root,
+ modelsDirectory: root
+ )
+ XCTAssertEqual(ids, ["bundled", "exact"])
+ XCTAssertEqual(try Data(contentsOf: file), Data([1, 2, 3]))
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selection)
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/UpdateAppReplacementTests.swift b/Tests/FluidDictationIntegrationTests/UpdateAppReplacementTests.swift
new file mode 100644
index 00000000..a4529361
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/UpdateAppReplacementTests.swift
@@ -0,0 +1,409 @@
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+final class UpdateAppReplacementTests: XCTestCase {
+ func testCommitKeepsInstalledNameSourceAndUnrelatedDestination() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let unrelated = try fixture.bundle("DownloadedName.app", parent: fixture.applications, contents: "unrelated")
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertEqual(try fixture.contents(replacement.stagedAppURL), "new")
+ try replacement.commit()
+ XCTAssertEqual(try fixture.contents(fixture.installed), "new")
+ XCTAssertEqual(replacement.installedAppURL, fixture.installed)
+ XCTAssertEqual(try fixture.contents(replacement.recoveryAppURL), "old")
+ XCTAssertEqual(try fixture.contents(fixture.source), "new")
+ XCTAssertEqual(try fixture.contents(unrelated), "unrelated")
+ try replacement.finalize()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: replacement.stagingDirectoryURL.path))
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ XCTAssertEqual(try fixture.contents(fixture.installed), "new")
+ }
+
+ func testFailedRelaunchRecoveryRestoresOldBundleWithoutConsumingRollbackSource() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.backup)
+ try replacement.commit()
+ try replacement.recover()
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: replacement.stagingDirectoryURL.path))
+ }
+
+ func testPreparationFailureDoesNotChangeInstalledBundle() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ var operations = UpdateAppReplacement.Operations.live
+ operations.copyBundle = { _, destination in
+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false)
+ throw ProbeFailure.injected
+ }
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source, operations: operations))
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertEqual(try fixture.contents(fixture.source), "new")
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: fixture.applications.path).filter { $0.hasSuffix(".staging") }, [])
+ }
+
+ func testCreateFailureCannotDeleteAnUnownedDirectory() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let removals = Counter()
+ var operations = UpdateAppReplacement.Operations.live
+ operations.createDirectory = { _ in throw ProbeFailure.injected }
+ operations.removeDirectory = { _ in _ = removals.next() }
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source, operations: operations))
+ XCTAssertEqual(removals.value, 0)
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+
+ func testExchangeFailurePreservesOldBundleAndPreparedCopyCanBeDiscarded() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ var operations = UpdateAppReplacement.Operations.live
+ operations.exchangeBundles = { _, _ in throw ProbeFailure.injected }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source, operations: operations)
+ XCTAssertThrowsError(try replacement.commit())
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertEqual(try fixture.contents(replacement.stagedAppURL), "new")
+ try replacement.discardPrepared()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: replacement.stagingDirectoryURL.path))
+ }
+
+ func testRecoveryFailureRetainsBothBundlesAndAllowsRetry() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let exchanges = Counter()
+ var operations = UpdateAppReplacement.Operations.live
+ operations.exchangeBundles = { installed, staged in
+ if exchanges.next() == 2 { throw ProbeFailure.injected }
+ try UpdateAppReplacement.Operations.live.exchangeBundles(installed, staged)
+ }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source, operations: operations)
+ try replacement.commit()
+ XCTAssertThrowsError(try replacement.recover()) { error in
+ XCTAssertEqual((error as? UpdateAppReplacement.Failure)?.operation, .recovery)
+ XCTAssertEqual((error as? UpdateAppReplacement.Failure)?.recoveryDirectoryURL, replacement.stagingDirectoryURL)
+ }
+ XCTAssertEqual(try fixture.contents(fixture.installed), "new")
+ XCTAssertEqual(try fixture.contents(replacement.recoveryAppURL), "old")
+ try replacement.recover()
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: replacement.stagingDirectoryURL.path))
+ }
+
+ func testCleanupFailureAfterRecoveryKeepsOldInstalledAndRetriesOnlyCleanup() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let exchanges = Counter()
+ let removals = Counter()
+ var operations = UpdateAppReplacement.Operations.live
+ operations.exchangeBundles = { installed, staged in
+ _ = exchanges.next()
+ try UpdateAppReplacement.Operations.live.exchangeBundles(installed, staged)
+ }
+ operations.removeDirectory = { directory in
+ if removals.next() == 1 { throw ProbeFailure.injected }
+ try UpdateAppReplacement.Operations.live.removeDirectory(directory)
+ }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source, operations: operations)
+ try replacement.commit()
+ XCTAssertThrowsError(try replacement.recover())
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ try replacement.recover()
+ XCTAssertEqual(exchanges.value, 2)
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: replacement.stagingDirectoryURL.path))
+ }
+
+ func testPartialFinalizationFailureKeepsInstalledNewAndDurableOldBackup() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let removals = Counter()
+ var operations = UpdateAppReplacement.Operations.live
+ operations.removeDirectory = { directory in
+ if removals.next() == 1 {
+ try FileManager.default.removeItem(at: directory.appendingPathComponent("FluidVoice.app/marker"))
+ throw ProbeFailure.injected
+ }
+ try UpdateAppReplacement.Operations.live.removeDirectory(directory)
+ }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source, operations: operations)
+ try replacement.commit()
+ XCTAssertThrowsError(try replacement.finalize())
+ XCTAssertEqual(try fixture.contents(fixture.installed), "new")
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ XCTAssertThrowsError(try replacement.recover(), "Partially cleaned old files must never replace the running new app")
+ try replacement.finalize()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: replacement.stagingDirectoryURL.path))
+ }
+
+ func testValidationOrBackupFailureCanDiscardPreparedWithoutChangingEitherBundle() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ try replacement.discardPrepared()
+ try replacement.discardPrepared()
+ XCTAssertThrowsError(try replacement.commit())
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertEqual(try fixture.contents(fixture.source), "new")
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ }
+
+ func testCopyAndCleanupFailureReportsOwnedRecoveryDirectory() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ var operations = UpdateAppReplacement.Operations.live
+ operations.copyBundle = { _, _ in throw ProbeFailure.injected }
+ operations.removeDirectory = { _ in throw ProbeFailure.injected }
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source, operations: operations)) { error in
+ let failure = error as? UpdateAppReplacement.Failure
+ XCTAssertEqual(failure?.operation, .cleanup)
+ XCTAssertEqual(failure?.recoveryDirectoryURL?.deletingLastPathComponent(), fixture.applications)
+ XCTAssertTrue(failure?.recoveryDirectoryURL?.lastPathComponent.hasPrefix(".fluidvoice-update-") == true)
+ }
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+
+ func testRepeatedCommitIsRejectedAndSymlinkInputsAreRejected() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ try replacement.commit()
+ XCTAssertThrowsError(try replacement.commit())
+ XCTAssertEqual(try fixture.contents(fixture.installed), "new")
+ try replacement.recover()
+ let link = fixture.root.appendingPathComponent("Link.app")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: fixture.source)
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: link))
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+
+ func testLiveTransactionLockBlocksConcurrentAttemptWithoutDeletingRecoveryOrAccumulatingCopies() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let first = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ for _ in 0..<3 {
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)) { error in
+ XCTAssertEqual((error as NSError).domain, NSPOSIXErrorDomain)
+ XCTAssertEqual((error as NSError).code, Int(EWOULDBLOCK))
+ }
+ }
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: fixture.applications.path).count, 3)
+ XCTAssertEqual(try fixture.contents(first.stagedAppURL), "new")
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ try first.discardPrepared()
+ let retry = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ try retry.discardPrepared()
+ }
+
+ func testCallerValidationRunsUnderLockEvenWithoutStaleStage() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let validations = Counter()
+ let replacement = try UpdateAppReplacement.prepare(
+ installedAppURL: fixture.installed,
+ replacementAppURL: fixture.source,
+ validateInstalledApp: { _ in
+ _ = validations.next()
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source))
+ }
+ )
+ XCTAssertEqual(validations.value, 1)
+ try replacement.discardPrepared()
+ }
+
+ func testOtherProcessCannotAcquireLockUntilTransactionCompletes() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ let lock = fixture.applications.appendingPathComponent(".fluidvoice-update-FluidVoice.app.lock")
+ func childLockAttempt() throws -> Int32 {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/python3")
+ process.arguments = ["-c", """
+ import fcntl, os, sys
+ target = os.stat(sys.argv[1])
+ for name in os.listdir('/dev/fd'):
+ try:
+ inherited = os.fstat(int(name))
+ except OSError:
+ continue
+ if (inherited.st_dev, inherited.st_ino) == (target.st_dev, target.st_ino):
+ sys.exit(43)
+ with open(sys.argv[1], 'r+') as lock:
+ try:
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ sys.exit(42)
+ """, lock.path]
+ try process.run()
+ process.waitUntilExit()
+ return process.terminationStatus
+ }
+ XCTAssertEqual(try childLockAttempt(), 42)
+ try replacement.discardPrepared()
+ XCTAssertEqual(try childLockAttempt(), 0)
+ }
+
+ func testChangedInstalledDirectoryCannotBeOverwrittenAtCommit() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ let moved = fixture.root.appendingPathComponent("MovedOriginal.app")
+ try FileManager.default.moveItem(at: fixture.installed, to: moved)
+ _ = try fixture.bundle("FluidVoice.app", parent: fixture.applications, contents: "external")
+ XCTAssertThrowsError(try replacement.commit())
+ XCTAssertEqual(try fixture.contents(fixture.installed), "external")
+ XCTAssertEqual(try fixture.contents(moved), "old")
+ try replacement.discardPrepared()
+ }
+
+ func testChangedInstalledDirectoryCannotBeOverwrittenOrDeletedDuringRecovery() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let replacement = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ try replacement.commit()
+ let moved = fixture.root.appendingPathComponent("MovedNew.app")
+ try FileManager.default.moveItem(at: fixture.installed, to: moved)
+ _ = try fixture.bundle("FluidVoice.app", parent: fixture.applications, contents: "external")
+ XCTAssertThrowsError(try replacement.recover())
+ XCTAssertEqual(try fixture.contents(fixture.installed), "external")
+ XCTAssertEqual(try fixture.contents(replacement.recoveryAppURL), "old")
+ XCTAssertEqual(try fixture.contents(moved), "new")
+ }
+
+ func testVerifiedInstalledBundleAllowsOwnedCrashStageCleanupAndRetry() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let directory = try {
+ let abandoned = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ try abandoned.commit()
+ return abandoned.stagingDirectoryURL
+ }()
+ XCTAssertTrue(FileManager.default.fileExists(atPath: directory.path))
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source))
+ XCTAssertEqual(try fixture.contents(directory.appendingPathComponent("FluidVoice.app")), "old")
+ let replacement = try UpdateAppReplacement.prepare(
+ installedAppURL: fixture.installed,
+ replacementAppURL: fixture.source,
+ validateInstalledApp: { url in XCTAssertEqual(try fixture.contents(url), "new") }
+ )
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ XCTAssertEqual(try fixture.contents(fixture.installed), "new")
+ XCTAssertEqual(try fixture.contents(replacement.stagedAppURL), "new")
+ try replacement.discardPrepared()
+ }
+
+ func testRejectedInstalledValidationPreservesOwnedStaleRecovery() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let directory = try {
+ let abandoned = try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source)
+ try abandoned.commit()
+ return abandoned.stagingDirectoryURL
+ }()
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(
+ installedAppURL: fixture.installed,
+ replacementAppURL: fixture.source,
+ validateInstalledApp: { _ in throw ProbeFailure.injected }
+ ))
+ XCTAssertEqual(try fixture.contents(directory.appendingPathComponent("FluidVoice.app")), "old")
+ XCTAssertEqual(try fixture.contents(fixture.installed), "new")
+ }
+
+ func testUnknownStagingDirectoryIsNeverRemoved() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let directory = fixture.applications.appendingPathComponent(".fluidvoice-update-FluidVoice.app.staging")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)
+ try Data("unrelated".utf8).write(to: directory.appendingPathComponent("valuable"))
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(
+ installedAppURL: fixture.installed,
+ replacementAppURL: fixture.source,
+ validateInstalledApp: { _ in }
+ ))
+ XCTAssertEqual(try String(contentsOf: directory.appendingPathComponent("valuable"), encoding: .utf8), "unrelated")
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+
+ func testStagingSymlinkAndLockSymlinkAreNeverFollowedOrRemoved() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let directory = fixture.applications.appendingPathComponent(".fluidvoice-update-FluidVoice.app.staging")
+ try FileManager.default.createSymbolicLink(at: directory, withDestinationURL: fixture.source)
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(
+ installedAppURL: fixture.installed,
+ replacementAppURL: fixture.source,
+ validateInstalledApp: { _ in }
+ ))
+ XCTAssertEqual(try fixture.contents(fixture.source), "new")
+ try FileManager.default.removeItem(at: directory)
+ let lock = fixture.applications.appendingPathComponent(".fluidvoice-update-FluidVoice.app.lock")
+ try FileManager.default.removeItem(at: lock)
+ try FileManager.default.createSymbolicLink(at: lock, withDestinationURL: fixture.source.appendingPathComponent("marker"))
+ XCTAssertThrowsError(try UpdateAppReplacement.prepare(installedAppURL: fixture.installed, replacementAppURL: fixture.source))
+ XCTAssertEqual(try fixture.contents(fixture.source), "new")
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+
+ private enum ProbeFailure: Error { case injected }
+
+ private final class Counter: @unchecked Sendable {
+ private let lock = NSLock()
+ private var count = 0
+ var value: Int {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ return self.count
+ }
+
+ func next() -> Int {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ self.count += 1
+ return self.count
+ }
+ }
+
+ private struct Fixture: Sendable {
+ let root: URL
+ let applications: URL
+ let installed: URL
+ let source: URL
+ let backup: URL
+
+ init() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("fluidvoice-replacement-tests-\(UUID().uuidString)", isDirectory: true)
+ self.root = root
+ self.applications = root.appendingPathComponent("Applications", isDirectory: true)
+ try FileManager.default.createDirectory(at: self.applications, withIntermediateDirectories: true)
+ let downloads = root.appendingPathComponent("Downloads", isDirectory: true)
+ try FileManager.default.createDirectory(at: downloads, withIntermediateDirectories: false)
+ self.installed = self.applications.appendingPathComponent("FluidVoice.app", isDirectory: true)
+ self.source = downloads.appendingPathComponent("DownloadedName.app", isDirectory: true)
+ self.backup = root.appendingPathComponent("Rollback.app", isDirectory: true)
+ for (url, value) in [(self.installed, "old"), (self.source, "new"), (self.backup, "old")] {
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
+ try Data(value.utf8).write(to: url.appendingPathComponent("marker"))
+ }
+ }
+
+ func bundle(_ name: String, parent: URL, contents: String) throws -> URL {
+ let url = parent.appendingPathComponent(name, isDirectory: true)
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
+ try Data(contents.utf8).write(to: url.appendingPathComponent("marker"))
+ return url
+ }
+
+ func contents(_ url: URL) throws -> String {
+ try String(contentsOf: url.appendingPathComponent("marker"), encoding: .utf8)
+ }
+
+ func cleanup() {
+ try? FileManager.default.removeItem(at: self.root)
+ }
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/UpdateBundleValidatorTests.swift b/Tests/FluidDictationIntegrationTests/UpdateBundleValidatorTests.swift
new file mode 100644
index 00000000..a6d650cc
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/UpdateBundleValidatorTests.swift
@@ -0,0 +1,370 @@
+import CryptoKit
+import Darwin
+@testable import FluidVoice_Debug
+import Foundation
+import Security
+import XCTest
+
+final nonisolated class UpdateBundleValidatorTests: XCTestCase {
+ private let identifier = "com.fluidvoice.update-validator.fixture"
+ private let version = "1.6.10-beta.8"
+
+ func testMissingBundleIsRejected() {
+ let missing = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".app")
+ XCTAssertThrowsError(try UpdateBundleValidator.validate(
+ at: missing,
+ expectation: self.expectation,
+ policy: .developerID(allowedTeamIDs: ["V4J43B279J"])
+ )) { XCTAssertEqual($0 as? UpdateBundleValidator.ValidationError, .invalidBundle) }
+ }
+
+ func testUnsignedBundleIsRejected() throws {
+ try self.withFixture(sign: false) { fixture in
+ XCTAssertThrowsError(try self.validate(fixture))
+ }
+ }
+
+ func testDevelopmentFixtureAndInstalledPolicyPreserveExactMetadata() throws {
+ try self.withFixture { fixture in
+ let result = try self.validate(fixture)
+ XCTAssertEqual(result.bundleIdentifier, self.identifier)
+ XCTAssertEqual(result.version, self.version)
+ XCTAssertEqual(result.build, "27")
+ XCTAssertEqual(result.teamIdentifier, fixture.team)
+ XCTAssertEqual(try UpdateBundleValidator.validate(
+ at: fixture.bundle,
+ expectation: self.expectation,
+ policy: .installedApp(allowedTeamIDs: [fixture.team])
+ ), result)
+ }
+ }
+
+ func testDownloadedReleasePolicyRejectsDevelopmentCertificate() throws {
+ try self.withFixture { fixture in
+ XCTAssertThrowsError(try UpdateBundleValidator.validate(
+ at: fixture.bundle,
+ expectation: self.expectation,
+ policy: .developerID(allowedTeamIDs: [fixture.team])
+ ))
+ }
+ }
+
+ func testDeveloperIDReleaseAcceptsApprovedSigningTeams() throws {
+ try self.withFixture(developerID: true) { fixture in
+ let approved: Set<String> = ["V4J43B279J", "537RRRT57V"]
+ let result = try UpdateBundleValidator.validate(
+ at: fixture.bundle,
+ expectation: self.expectation,
+ policy: .developerID(allowedTeamIDs: approved)
+ )
+ XCTAssertTrue(approved.contains(result.teamIdentifier))
+ XCTAssertEqual(result.version, self.version)
+ XCTAssertEqual(result.build, "27")
+ }
+ }
+
+ func testUnapprovedTeamIsRejected() throws {
+ try self.withFixture { fixture in
+ XCTAssertThrowsError(try UpdateBundleValidator.validate(
+ at: fixture.bundle,
+ expectation: self.expectation,
+ policy: .appleDevelopment(allowedTeamIDs: ["0000000000"])
+ ))
+ }
+ }
+
+ func testDifferentApplicationIdentityIsRejected() throws {
+ try self.withFixture(identifier: "com.fluidvoice.some-other-app") { fixture in
+ XCTAssertThrowsError(try self.validate(fixture)) {
+ XCTAssertEqual($0 as? UpdateBundleValidator.ValidationError, .identityMismatch)
+ }
+ }
+ }
+
+ func testDifferentReleaseVersionIsRejectedButRollbackInspectionAllowsIt() throws {
+ try self.withFixture(version: "1.6.10-beta.7") { fixture in
+ XCTAssertThrowsError(try self.validate(fixture)) {
+ XCTAssertEqual($0 as? UpdateBundleValidator.ValidationError, .versionMismatch)
+ }
+ let rollback = try UpdateBundleValidator.validate(
+ at: fixture.bundle,
+ expectation: .init(bundleIdentifier: self.identifier, version: nil),
+ policy: .installedApp(allowedTeamIDs: [fixture.team])
+ )
+ XCTAssertEqual(rollback.version, "1.6.10-beta.7")
+ }
+ }
+
+ func testExpectedBuildMismatchAndMalformedBuildAreRejected() throws {
+ try self.withFixture { fixture in
+ XCTAssertThrowsError(try UpdateBundleValidator.validate(
+ at: fixture.bundle,
+ expectation: .init(bundleIdentifier: self.identifier, version: self.version, build: "28"),
+ policy: .appleDevelopment(allowedTeamIDs: [fixture.team])
+ )) { XCTAssertEqual($0 as? UpdateBundleValidator.ValidationError, .buildMismatch) }
+ }
+ try self.withFixture(build: "not-a-build") { fixture in
+ XCTAssertThrowsError(try self.validate(fixture)) {
+ XCTAssertEqual($0 as? UpdateBundleValidator.ValidationError, .invalidBundleMetadata)
+ }
+ }
+ }
+
+ func testTamperedResourceIsRejectedAlthoughSigningMetadataIsStillReadable() throws {
+ try self.withFixture { fixture in
+ try Data("changed after signing".utf8).write(to: fixture.resource)
+ XCTAssertEqual(try self.signingTeam(at: fixture.bundle), fixture.team)
+ XCTAssertThrowsError(try self.validate(fixture))
+ }
+ }
+
+ func testTamperedNestedResourceIsRejectedAlthoughOuterSignatureStillPasses() throws {
+ try self.withFixture(nested: true) { fixture in
+ XCTAssertNoThrow(try self.validate(fixture))
+ let nested = fixture.bundle.appendingPathComponent("Contents/PlugIns/Nested.app")
+ try Data("changed nested resource".utf8).write(to: nested.appendingPathComponent("Contents/Resources/payload.txt"))
+ var code: SecStaticCode?
+ XCTAssertEqual(SecStaticCodeCreateWithPath(fixture.bundle as CFURL, [], &code), errSecSuccess)
+ let outerCode = try XCTUnwrap(code)
+ let outerOnly = SecCSFlags(rawValue: kSecCSCheckAllArchitectures | kSecCSStrictValidate)
+ XCTAssertEqual(SecStaticCodeCheckValidity(outerCode, outerOnly, nil), errSecSuccess)
+ XCTAssertThrowsError(try self.validate(fixture))
+ }
+ }
+
+ func testTamperedNonNativeArchitectureIsRejected() throws {
+ try self.withFixture { fixture in
+ XCTAssertNoThrow(try self.validate(fixture))
+ let executable = fixture.bundle.appendingPathComponent("Contents/MacOS/Fixture")
+ var bytes = try Data(contentsOf: executable)
+ // /usr/bin/true is a universal binary on the test Mac. Damage only the
+ // other architecture so validating just the native slice would miss it.
+ #if arch(arm64)
+ let otherCPU: UInt32 = 0x01000007
+ #else
+ let otherCPU: UInt32 = 0x0100000c
+ #endif
+ let damaged = try self.textByteOffset(in: bytes, cpu: otherCPU)
+ bytes[damaged] ^= 0x01
+ try bytes.write(to: executable)
+ var code: SecStaticCode?
+ XCTAssertEqual(SecStaticCodeCreateWithPath(fixture.bundle as CFURL, [], &code), errSecSuccess)
+ XCTAssertEqual(try SecStaticCodeCheckValidity(XCTUnwrap(code), SecCSFlags(rawValue: kSecCSStrictValidate), nil), errSecSuccess)
+ XCTAssertThrowsError(try self.validate(fixture))
+ }
+ }
+
+ func testTamperedNestedExecutableIsRejected() throws {
+ try self.withFixture(nested: true) { fixture in
+ XCTAssertNoThrow(try self.validate(fixture))
+ let executable = fixture.bundle.appendingPathComponent("Contents/PlugIns/Nested.app/Contents/MacOS/Fixture")
+ var bytes = try Data(contentsOf: executable)
+ let damaged = try self.textByteOffset(in: bytes)
+ bytes[damaged] ^= 0x01
+ try bytes.write(to: executable)
+ var code: SecStaticCode?
+ XCTAssertEqual(SecStaticCodeCreateWithPath(fixture.bundle as CFURL, [], &code), errSecSuccess)
+ XCTAssertEqual(try SecStaticCodeCheckValidity(XCTUnwrap(code), SecCSFlags(rawValue: kSecCSStrictValidate), nil), errSecSuccess)
+ XCTAssertThrowsError(try self.validate(fixture))
+ }
+ }
+
+ func testInvalidExpectationFailsClosed() {
+ XCTAssertThrowsError(try UpdateBundleValidator.validate(
+ at: URL(fileURLWithPath: "/unused.app"),
+ expectation: .init(bundleIdentifier: self.identifier, version: self.version),
+ policy: .developerID(allowedTeamIDs: [])
+ )) { XCTAssertEqual($0 as? UpdateBundleValidator.ValidationError, .invalidExpectation) }
+ }
+
+ private var expectation: UpdateBundleValidator.Expectation {
+ .init(bundleIdentifier: self.identifier, version: self.version, build: "27")
+ }
+
+ private struct Fixture {
+ let bundle: URL
+ let team: String
+ var resource: URL { self.bundle.appendingPathComponent("Contents/Resources/payload.txt") }
+ }
+
+ private func validate(_ fixture: Fixture) throws -> UpdateBundleValidator.ValidatedBundle {
+ try UpdateBundleValidator.validate(at: fixture.bundle, expectation: self.expectation, policy: .appleDevelopment(allowedTeamIDs: [fixture.team]))
+ }
+
+ private func withFixture(
+ identifier: String? = nil,
+ version: String? = nil,
+ build: String = "27",
+ sign: Bool = true,
+ nested: Bool = false,
+ developerID: Bool = false,
+ body: (Fixture) throws -> Void
+ ) throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("UpdateBundleValidatorTests-" + UUID().uuidString, isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let bundle = root.appendingPathComponent("Fixture.app", isDirectory: true)
+ try self.makeBundle(at: bundle, identifier: identifier ?? self.identifier, version: version ?? self.version, build: build)
+ if !sign {
+ // The copied executable retains Apple's signature, but the enclosing
+ // application has never been signed and has no sealed resource envelope.
+ try body(Fixture(bundle: bundle, team: "V4J43B279J"))
+ return
+ }
+ let identity = try self.signingIdentity(developerID: developerID)
+ if nested {
+ let nestedBundle = bundle.appendingPathComponent("Contents/PlugIns/Nested.app", isDirectory: true)
+ try self.makeBundle(at: nestedBundle, identifier: self.identifier + ".nested", version: self.version, build: build)
+ try self.sign(nestedBundle, identity: identity)
+ }
+ try self.sign(bundle, identity: identity)
+ try body(Fixture(bundle: bundle, team: self.signingTeam(at: bundle)))
+ }
+
+ private func makeBundle(at bundle: URL, identifier: String, version: String, build: String) throws {
+ let executableDirectory = bundle.appendingPathComponent("Contents/MacOS", isDirectory: true)
+ let resources = bundle.appendingPathComponent("Contents/Resources", isDirectory: true)
+ try FileManager.default.createDirectory(at: executableDirectory, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executableDirectory.appendingPathComponent("Fixture"))
+ try Data("original resource".utf8).write(to: resources.appendingPathComponent("payload.txt"))
+ let plist = [
+ "CFBundleIdentifier": identifier,
+ "CFBundleShortVersionString": version,
+ "CFBundleVersion": build,
+ "CFBundleExecutable": "Fixture",
+ "CFBundlePackageType": "APPL",
+ ]
+ try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ .write(to: bundle.appendingPathComponent("Contents/Info.plist"))
+ }
+
+ private func signingIdentity(developerID: Bool) throws -> String {
+ let prefix = developerID ? "Developer ID Application:" : "Apple Development:"
+ var result: CFTypeRef?
+ let query: [String: Any] = [kSecClass as String: kSecClassIdentity, kSecReturnRef as String: true, kSecMatchLimit as String: kSecMatchLimitAll]
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
+ guard status == errSecSuccess, let identities = result as? [SecIdentity] else {
+ throw XCTSkip("A \(prefix) signing identity is required for signed bundle fixtures.")
+ }
+ for identity in identities {
+ var certificate: SecCertificate?
+ guard SecIdentityCopyCertificate(identity, &certificate) == errSecSuccess, let certificate,
+ let summary = SecCertificateCopySubjectSummary(certificate) as String?, summary.hasPrefix(prefix)
+ else { continue }
+ var trust: SecTrust?
+ guard let policy = SecPolicyCreateWithProperties(kSecPolicyAppleCodeSigning, nil),
+ SecTrustCreateWithCertificates(certificate, policy, &trust) == errSecSuccess, let trust,
+ SecTrustSetNetworkFetchAllowed(trust, false) == errSecSuccess,
+ SecTrustEvaluateWithError(trust, nil)
+ else { continue }
+ return Insecure.SHA1.hash(data: SecCertificateCopyData(certificate) as Data).map { String(format: "%02x", $0) }.joined()
+ }
+ throw XCTSkip("A valid \(prefix) signing identity is required for signed bundle fixtures.")
+ }
+
+ private func signingTeam(at bundle: URL) throws -> String {
+ var code: SecStaticCode?
+ XCTAssertEqual(SecStaticCodeCreateWithPath(bundle as CFURL, [], &code), errSecSuccess)
+ let staticCode = try XCTUnwrap(code)
+ var result: CFDictionary?
+ XCTAssertEqual(SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation), &result), errSecSuccess)
+ let information = try XCTUnwrap(result as? [String: Any])
+ return try XCTUnwrap(information[kSecCodeInfoTeamIdentifier as String] as? String)
+ }
+
+ private func sign(_ bundle: URL, identity: String) throws {
+ let log = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".codesign.log")
+ XCTAssertTrue(FileManager.default.createFile(atPath: log.path, contents: nil))
+ let output = try FileHandle(forWritingTo: log)
+ defer {
+ try? output.close()
+ try? FileManager.default.removeItem(at: log)
+ }
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")
+ process.arguments = ["--force", "--sign", identity, "--timestamp=none", bundle.path]
+ process.standardOutput = output
+ process.standardError = output
+ try process.run()
+ let deadline = Date().addingTimeInterval(15)
+ while process.isRunning, Date() < deadline {
+ Thread.sleep(forTimeInterval: 0.01)
+ }
+ if process.isRunning {
+ process.terminate()
+ let terminationDeadline = Date().addingTimeInterval(1)
+ while process.isRunning, Date() < terminationDeadline {
+ Thread.sleep(forTimeInterval: 0.01)
+ }
+ if process.isRunning { kill(process.processIdentifier, SIGKILL) }
+ XCTFail("Temporary fixture signing exceeded its bounded timeout.")
+ throw NSError(domain: "UpdateBundleValidatorTests", code: 1)
+ }
+ guard process.terminationStatus == 0 else {
+ let diagnostic = (try? String(contentsOf: log, encoding: .utf8)) ?? "No signing diagnostic"
+ XCTFail("Temporary fixture signing failed: \(diagnostic)")
+ throw NSError(domain: "UpdateBundleValidatorTests", code: Int(process.terminationStatus))
+ }
+ }
+
+ private func bigEndian32(_ data: Data, at offset: Int) -> UInt32 {
+ guard offset >= 0, offset + 4 <= data.count else { return 0 }
+ return data[offset..<offset + 4].reduce(0) { ($0 << 8) | UInt32($1) }
+ }
+
+ /// Mutate sealed executable instructions, never padding inside a signature blob.
+ private func textByteOffset(in data: Data, cpu: UInt32? = nil) throws -> Int {
+ guard self.bigEndian32(data, at: 0) == 0xcafebabe else {
+ throw XCTSkip("The system fixture is not a 32-bit-header universal binary.")
+ }
+ let count = Int(self.bigEndian32(data, at: 4))
+ guard (1...16).contains(count), 8 + count * 20 <= data.count else {
+ throw NSError(domain: "UpdateBundleValidatorTests.MachO", code: 1)
+ }
+ let header = try XCTUnwrap((0..<count).map { 8 + $0 * 20 }.first {
+ cpu == nil || self.bigEndian32(data, at: $0) == cpu
+ })
+ let slice = Int(self.bigEndian32(data, at: header + 8))
+ let sliceSize = Int(self.bigEndian32(data, at: header + 12))
+ guard slice + 32 <= data.count, sliceSize >= 32, slice + sliceSize <= data.count,
+ self.littleEndian32(data, at: slice) == 0xfeedfacf
+ else { throw NSError(domain: "UpdateBundleValidatorTests.MachO", code: 2) }
+ let commands = Int(self.littleEndian32(data, at: slice + 16))
+ let commandsSize = Int(self.littleEndian32(data, at: slice + 20))
+ let commandsEnd = slice + 32 + commandsSize
+ guard (1...128).contains(commands), commandsEnd <= slice + sliceSize else {
+ throw NSError(domain: "UpdateBundleValidatorTests.MachO", code: 3)
+ }
+ var cursor = slice + 32
+ for _ in 0..<commands {
+ guard cursor + 8 <= commandsEnd else { break }
+ let kind = self.littleEndian32(data, at: cursor)
+ let size = Int(self.littleEndian32(data, at: cursor + 4))
+ guard size >= 8, cursor + size <= commandsEnd else { break }
+ if kind == 0x19, size >= 72 {
+ let sections = Int(self.littleEndian32(data, at: cursor + 64))
+ guard sections <= 128, 72 + sections * 80 <= size else { break }
+ for section in 0..<sections {
+ let position = cursor + 72 + section * 80
+ let name = String(bytes: data[position..<position + 16].prefix { $0 != 0 }, encoding: .utf8)
+ if name == "__text" {
+ let offset = Int(self.littleEndian32(data, at: position + 48))
+ let sectionSize = Int(self.littleEndian32(data, at: position + 40))
+ guard sectionSize > 0, offset + sectionSize <= sliceSize,
+ self.littleEndian32(data, at: position + 44) == 0
+ else { break }
+ return slice + offset + sectionSize / 2
+ }
+ }
+ }
+ cursor += size
+ }
+ throw NSError(domain: "UpdateBundleValidatorTests.MachO", code: 4)
+ }
+
+ private func littleEndian32(_ data: Data, at offset: Int) -> UInt32 {
+ guard offset >= 0, offset + 4 <= data.count else { return 0 }
+ return data[offset..<offset + 4].reversed().reduce(0) { ($0 << 8) | UInt32($1) }
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/UpdateInstallationPipelineTests.swift b/Tests/FluidDictationIntegrationTests/UpdateInstallationPipelineTests.swift
new file mode 100644
index 00000000..b6ba7867
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/UpdateInstallationPipelineTests.swift
@@ -0,0 +1,322 @@
+import CryptoKit
+import Darwin
+@testable import FluidVoice_Debug
+import Foundation
+import Security
+import XCTest
+
+final nonisolated class UpdateInstallationPipelineTests: XCTestCase {
+ func testReleaseInstallationHasVerifiedBackupAndCanRecoverWithoutConsumingSource() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let installation = try fixture.prepare()
+ XCTAssertEqual(installation.backupURL, fixture.backup)
+ XCTAssertEqual(try fixture.validated(fixture.installed).version, Fixture.incomingVersion)
+ XCTAssertEqual(try fixture.validated(fixture.backup).version, Fixture.installedVersion)
+ XCTAssertEqual(try fixture.validated(fixture.backup).build, Fixture.installedBuild)
+ XCTAssertEqual(try fixture.payload(fixture.backup), "installed")
+ XCTAssertEqual(try fixture.payload(installation.replacement.recoveryAppURL), "installed")
+ XCTAssertEqual(try fixture.payload(fixture.incoming), "incoming")
+ try installation.replacement.recover()
+ XCTAssertEqual(try fixture.validated(fixture.installed).version, Fixture.installedVersion)
+ XCTAssertEqual(try fixture.payload(fixture.installed), "installed")
+ XCTAssertEqual(try fixture.validated(fixture.incoming).version, Fixture.incomingVersion)
+ XCTAssertEqual(try fixture.validated(fixture.backup).version, Fixture.installedVersion)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: installation.replacement.stagingDirectoryURL.path))
+ }
+
+ func testTamperedCandidateCannotReplaceOriginalOrCreateBackup() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let originalPlist = try Data(contentsOf: fixture.installed.appendingPathComponent("Contents/Info.plist"))
+ try Data("tampered incoming".utf8).write(to: fixture.incoming.appendingPathComponent("Contents/Resources/payload.txt"))
+ XCTAssertThrowsError(try fixture.prepare())
+ XCTAssertEqual(try Data(contentsOf: fixture.installed.appendingPathComponent("Contents/Info.plist")), originalPlist)
+ try fixture.assertOriginalUnchanged()
+ XCTAssertEqual(try fixture.payload(fixture.incoming), "tampered incoming")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ try fixture.assertNoStage()
+ }
+
+ func testInstalledVersionChangedSinceApprovalRejectsPreparation() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ XCTAssertThrowsError(try fixture.prepare(installedVersion: "1.6.10-beta.6")) { error in
+ self.assertInstalledChanged(error)
+ }
+ try fixture.assertOriginalUnchanged()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ try fixture.assertNoStage()
+ }
+
+ func testInstalledBuildChangedSinceApprovalRejectsPreparation() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ XCTAssertThrowsError(try fixture.prepare(installedBuild: "25")) { error in
+ self.assertInstalledChanged(error)
+ }
+ try fixture.assertOriginalUnchanged()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ try fixture.assertNoStage()
+ }
+
+ func testPreexistingBackupDestinationIsPreservedAndOriginalIsUntouched() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ try FileManager.default.createDirectory(at: fixture.backup.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: fixture.incoming, to: fixture.backup)
+ let before = try Data(contentsOf: fixture.backup.appendingPathComponent("Contents/Info.plist"))
+ XCTAssertThrowsError(try fixture.prepare()) { error in
+ guard case .backupFailed? = error as? SimpleUpdateError else { return XCTFail("Expected backup failure: \(error)") }
+ }
+ XCTAssertEqual(try Data(contentsOf: fixture.backup.appendingPathComponent("Contents/Info.plist")), before)
+ XCTAssertEqual(try fixture.validated(fixture.backup).version, Fixture.incomingVersion)
+ XCTAssertEqual(try fixture.payload(fixture.backup), "incoming")
+ try fixture.assertOriginalUnchanged()
+ try fixture.assertNoStage()
+ }
+
+ func testRegularFileAtBackupParentAbortsWithoutReplacingOriginal() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let parent = fixture.backup.deletingLastPathComponent()
+ let marker = Data("unrelated existing file".utf8)
+ try marker.write(to: parent)
+ XCTAssertThrowsError(try fixture.prepare()) { error in
+ guard case .backupFailed? = error as? SimpleUpdateError else { return XCTFail("Expected backup failure: \(error)") }
+ }
+ XCTAssertEqual(try Data(contentsOf: parent), marker)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ try fixture.assertOriginalUnchanged()
+ try fixture.assertNoStage()
+ }
+
+ func testDevelopmentCandidateIsRejectedAsReleaseButAcceptedAsRollbackAndRetained() throws {
+ let fixture = try Fixture(incomingDeveloperID: false, candidateVersion: "1.6.10-beta.6")
+ defer { fixture.cleanup() }
+ XCTAssertThrowsError(try fixture.prepare(expectedVersion: fixture.candidateVersion)) { error in
+ guard case .invalidSignature? = error as? UpdateBundleValidator.ValidationError else {
+ return XCTFail("Expected the release policy to reject a development certificate: \(error)")
+ }
+ }
+ try fixture.assertOriginalUnchanged()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ try fixture.assertNoStage()
+
+ let installation = try fixture.prepare(expectedVersion: nil, isRollback: true)
+ XCTAssertEqual(try fixture.validated(fixture.installed).version, fixture.candidateVersion)
+ XCTAssertEqual(try fixture.validated(fixture.incoming).version, fixture.candidateVersion)
+ XCTAssertEqual(try fixture.validated(fixture.backup).version, Fixture.installedVersion)
+ try installation.replacement.finalize()
+ XCTAssertEqual(try fixture.validated(fixture.incoming).version, fixture.candidateVersion)
+ XCTAssertEqual(try fixture.validated(fixture.backup).version, Fixture.installedVersion)
+ try fixture.assertNoStage()
+ }
+
+ func testReleaseWithoutApprovedVersionIsRejectedBeforeAnyStagingOrBackup() throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ XCTAssertThrowsError(try fixture.prepare(expectedVersion: nil)) { error in
+ XCTAssertEqual(error as? UpdateBundleValidator.ValidationError, .invalidExpectation)
+ }
+ try fixture.assertOriginalUnchanged()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ try fixture.assertNoStage()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.lockURL.path))
+ }
+
+ func testCancelledTaskBeforePreparationDoesNotTouchOriginalStageOrBackup() async throws {
+ let fixture = try Fixture()
+ defer { fixture.cleanup() }
+ let gate = StartGate()
+ let operation = Task.detached {
+ await gate.wait()
+ return try fixture.prepare()
+ }
+ operation.cancel()
+ await gate.open()
+ do {
+ let installation = try await operation.value
+ try installation.replacement.recover()
+ XCTFail("Cancellation must reject preparation before exchange.")
+ } catch is CancellationError {
+ // This is the real production Task.checkCancellation exit.
+ }
+ try fixture.assertOriginalUnchanged()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ try fixture.assertNoStage()
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.lockURL.path))
+ }
+
+ private func assertInstalledChanged(_ error: Error) {
+ guard let failure = error as? UpdateAppReplacement.Failure else { return XCTFail("Expected preparation wrapper: \(error)") }
+ XCTAssertEqual(failure.operation, .preparation)
+ guard case .installedAppChanged? = failure.underlyingError as? SimpleUpdateError else {
+ return XCTFail("Expected installed app changed rejection: \(failure.underlyingError)")
+ }
+ }
+
+ private actor StartGate {
+ private var opened = false
+ private var continuation: CheckedContinuation<Void, Never>?
+
+ func wait() async {
+ guard !self.opened else { return }
+ await withCheckedContinuation { self.continuation = $0 }
+ }
+
+ func open() {
+ self.opened = true
+ self.continuation?.resume()
+ self.continuation = nil
+ }
+ }
+
+ private struct Fixture: Sendable {
+ static let identifier = "com.fluidvoice.update-pipeline.fixture"
+ static let installedVersion = "1.6.10-beta.7"
+ static let installedBuild = "26"
+ static let incomingVersion = "1.6.10-beta.8"
+ static let approvedTeams: Set<String> = ["V4J43B279J", "537RRRT57V"]
+
+ let root: URL
+ let installed: URL
+ let incoming: URL
+ let backup: URL
+ let candidateVersion: String
+ var lockURL: URL { self.installed.deletingLastPathComponent().appendingPathComponent(".fluidvoice-update-\(self.installed.lastPathComponent).lock") }
+
+ init(incomingDeveloperID: Bool = true, candidateVersion: String = Self.incomingVersion) throws {
+ self.root = FileManager.default.temporaryDirectory.appendingPathComponent("UpdateInstallationPipelineTests-" + UUID().uuidString, isDirectory: true)
+ self.installed = self.root.appendingPathComponent("Applications/Fixture.app")
+ self.incoming = self.root.appendingPathComponent("Downloads/Incoming.app")
+ self.backup = self.root.appendingPathComponent("Backups/Previous.app")
+ self.candidateVersion = candidateVersion
+ do {
+ try self.makeBundle(at: self.installed, version: Self.installedVersion, build: Self.installedBuild, payload: "installed", developerID: false)
+ try self.makeBundle(at: self.incoming, version: candidateVersion, build: "27", payload: "incoming", developerID: incomingDeveloperID)
+ } catch {
+ self.cleanup()
+ throw error
+ }
+ }
+
+ func cleanup() { try? FileManager.default.removeItem(at: self.root) }
+
+ func prepare(
+ installedVersion: String = Self.installedVersion,
+ installedBuild: String = Self.installedBuild,
+ expectedVersion: String? = Self.incomingVersion,
+ isRollback: Bool = false
+ ) throws -> SimpleUpdater.PreparedInstallation {
+ try SimpleUpdater.prepareValidatedInstallation(
+ installedAppURL: self.installed,
+ downloadedAppURL: self.incoming,
+ installedExpectation: .init(bundleIdentifier: Self.identifier, version: installedVersion, build: installedBuild),
+ expectedVersion: expectedVersion,
+ backupURL: self.backup,
+ isRollback: isRollback
+ )
+ }
+
+ func validated(_ bundle: URL) throws -> UpdateBundleValidator.ValidatedBundle {
+ try UpdateBundleValidator.validate(
+ at: bundle,
+ expectation: .init(bundleIdentifier: Self.identifier, version: nil),
+ policy: .installedApp(allowedTeamIDs: Self.approvedTeams)
+ )
+ }
+
+ func payload(_ bundle: URL) throws -> String {
+ try String(contentsOf: bundle.appendingPathComponent("Contents/Resources/payload.txt"), encoding: .utf8)
+ }
+
+ func assertOriginalUnchanged() throws {
+ let original = try self.validated(self.installed)
+ XCTAssertEqual(original.version, Self.installedVersion)
+ XCTAssertEqual(original.build, Self.installedBuild)
+ XCTAssertEqual(try self.payload(self.installed), "installed")
+ }
+
+ func assertNoStage() throws {
+ let contents = try FileManager.default.contentsOfDirectory(atPath: self.installed.deletingLastPathComponent().path)
+ XCTAssertFalse(contents.contains { $0.hasSuffix(".staging") })
+ }
+
+ private func makeBundle(at bundle: URL, version: String, build: String, payload: String, developerID: Bool) throws {
+ let executableDirectory = bundle.appendingPathComponent("Contents/MacOS", isDirectory: true)
+ let resources = bundle.appendingPathComponent("Contents/Resources", isDirectory: true)
+ try FileManager.default.createDirectory(at: executableDirectory, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executableDirectory.appendingPathComponent("Fixture"))
+ try Data(payload.utf8).write(to: resources.appendingPathComponent("payload.txt"))
+ let plist = [
+ "CFBundleIdentifier": Self.identifier,
+ "CFBundleShortVersionString": version,
+ "CFBundleVersion": build,
+ "CFBundleExecutable": "Fixture",
+ "CFBundlePackageType": "APPL",
+ ]
+ try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ .write(to: bundle.appendingPathComponent("Contents/Info.plist"))
+ try self.sign(bundle, identity: self.signingIdentity(developerID: developerID))
+ _ = try self.validated(bundle)
+ }
+
+ private func signingIdentity(developerID: Bool) throws -> String {
+ let prefix = developerID ? "Developer ID Application:" : "Apple Development:"
+ var result: CFTypeRef?
+ let query: [String: Any] = [kSecClass as String: kSecClassIdentity, kSecReturnRef as String: true, kSecMatchLimit as String: kSecMatchLimitAll]
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
+ guard status == errSecSuccess, let identities = result as? [SecIdentity] else {
+ throw XCTSkip("A \(prefix) signing identity is required for signed pipeline fixtures.")
+ }
+ for identity in identities {
+ var certificate: SecCertificate?
+ guard SecIdentityCopyCertificate(identity, &certificate) == errSecSuccess, let certificate,
+ let summary = SecCertificateCopySubjectSummary(certificate) as String?, summary.hasPrefix(prefix)
+ else { continue }
+ var trust: SecTrust?
+ guard let policy = SecPolicyCreateWithProperties(kSecPolicyAppleCodeSigning, nil),
+ SecTrustCreateWithCertificates(certificate, policy, &trust) == errSecSuccess, let trust,
+ SecTrustSetNetworkFetchAllowed(trust, false) == errSecSuccess,
+ SecTrustEvaluateWithError(trust, nil)
+ else { continue }
+ return Insecure.SHA1.hash(data: SecCertificateCopyData(certificate) as Data).map { String(format: "%02x", $0) }.joined()
+ }
+ throw XCTSkip("A valid \(prefix) signing identity is required for signed pipeline fixtures.")
+ }
+
+ private func sign(_ bundle: URL, identity: String) throws {
+ let log = bundle.deletingLastPathComponent().appendingPathComponent(UUID().uuidString + ".codesign.log")
+ XCTAssertTrue(FileManager.default.createFile(atPath: log.path, contents: nil))
+ let output = try FileHandle(forWritingTo: log)
+ defer { try? output.close() }
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")
+ process.arguments = ["--force", "--sign", identity, "--timestamp=none", bundle.path]
+ process.standardOutput = output
+ process.standardError = output
+ try process.run()
+ let deadline = Date().addingTimeInterval(15)
+ while process.isRunning, Date() < deadline {
+ Thread.sleep(forTimeInterval: 0.01)
+ }
+ if process.isRunning {
+ process.terminate()
+ let terminationDeadline = Date().addingTimeInterval(1)
+ while process.isRunning, Date() < terminationDeadline {
+ Thread.sleep(forTimeInterval: 0.01)
+ }
+ if process.isRunning { kill(process.processIdentifier, SIGKILL) }
+ XCTFail("Temporary fixture signing exceeded its bounded timeout.")
+ throw NSError(domain: "UpdateInstallationPipelineTests", code: 1)
+ }
+ guard process.terminationStatus == 0 else {
+ let diagnostic = (try? String(contentsOf: log, encoding: .utf8)) ?? "No signing diagnostic"
+ XCTFail("Temporary fixture signing failed: \(diagnostic)")
+ throw NSError(domain: "UpdateInstallationPipelineTests", code: Int(process.terminationStatus))
+ }
+ }
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/UpdateRollbackBackupTests.swift b/Tests/FluidDictationIntegrationTests/UpdateRollbackBackupTests.swift
new file mode 100644
index 00000000..f2fc331d
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/UpdateRollbackBackupTests.swift
@@ -0,0 +1,198 @@
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+final nonisolated class UpdateRollbackBackupTests: XCTestCase {
+ func testCopiesVerifiedBundleAndPreservesInstalledSource() throws {
+ try self.withFixture { fixture in
+ try fixture.create()
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ XCTAssertFalse(fixture.stageExists)
+ }
+ }
+
+ func testExistingBackupIsNeverOverwritten() throws {
+ try self.withFixture { fixture in
+ try fixture.makeBundle(at: fixture.backup, contents: "unrelated")
+ XCTAssertThrowsError(try fixture.create())
+ XCTAssertEqual(try fixture.contents(fixture.backup), "unrelated")
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ XCTAssertFalse(fixture.stageExists)
+ }
+ }
+
+ func testPartialCopyFailureCleansStagingWithoutPublishing() throws {
+ try self.withFixture { fixture in
+ var operations = UpdateRollbackBackup.Operations.live
+ operations.copyBundle = { _, destination in
+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false)
+ try Data("partial".utf8).write(to: destination.appendingPathComponent("payload"))
+ throw ProbeFailure.injected
+ }
+ XCTAssertThrowsError(try fixture.create(operations: operations))
+ XCTAssertFalse(fixture.stageExists)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+ }
+
+ func testStagedValidationFailureCleansPartialAndDoesNotPublish() throws {
+ try self.withFixture { fixture in
+ XCTAssertThrowsError(try UpdateRollbackBackup.create(installedAppURL: fixture.installed, backupURL: fixture.backup, validate: { url in
+ if url != fixture.installed { throw ProbeFailure.injected }
+ }))
+ XCTAssertFalse(fixture.stageExists)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+ }
+
+ func testCleanupFailureReportsOneStablePathAndNextAttemptRetriesIt() throws {
+ try self.withFixture { fixture in
+ var operations = UpdateRollbackBackup.Operations.live
+ operations.copyBundle = { _, _ in throw ProbeFailure.injected }
+ operations.removeDirectory = { _ in throw ProbeFailure.injected }
+ for _ in 0..<2 {
+ XCTAssertThrowsError(try fixture.create(operations: operations)) {
+ XCTAssertEqual(($0 as? UpdateRollbackBackup.Failure)?.retainedDirectoryURL, fixture.stage)
+ }
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: fixture.root.path).filter { $0.hasSuffix(".staging") }, [fixture.stage.lastPathComponent])
+ }
+ try fixture.create()
+ XCTAssertFalse(fixture.stageExists)
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ }
+ }
+
+ func testOwnedCrashStageIsDiscardedOnlyAfterInstalledValidation() throws {
+ try self.withFixture { fixture in
+ try fixture.makeOwnedStage()
+ try fixture.makeBundle(at: fixture.stage.appendingPathComponent("partial.app"), contents: "partial")
+ XCTAssertThrowsError(try UpdateRollbackBackup.create(installedAppURL: fixture.installed, backupURL: fixture.backup, validate: { _ in throw ProbeFailure.injected }))
+ XCTAssertTrue(fixture.stageExists)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ try fixture.create()
+ XCTAssertFalse(fixture.stageExists)
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ }
+ }
+
+ func testUnknownStageAndForeignOwnershipArePreserved() throws {
+ try self.withFixture { fixture in
+ try FileManager.default.createDirectory(at: fixture.stage, withIntermediateDirectories: false)
+ let marker = fixture.stage.appendingPathComponent("ownership")
+ XCTAssertThrowsError(try fixture.create())
+ XCTAssertTrue(fixture.stageExists)
+ try Data("belongs to another app".utf8).write(to: marker)
+ XCTAssertThrowsError(try fixture.create())
+ XCTAssertEqual(try String(contentsOf: marker, encoding: .utf8), "belongs to another app")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ }
+ }
+
+ func testSymlinkStageAndSymlinkMarkerCannotDeleteUnrelatedPaths() throws {
+ try self.withFixture { fixture in
+ let unrelated = fixture.root.appendingPathComponent("unrelated", isDirectory: true)
+ try FileManager.default.createDirectory(at: unrelated, withIntermediateDirectories: false)
+ try Data("preserve".utf8).write(to: unrelated.appendingPathComponent("payload"))
+ let unrelatedMarker = unrelated.appendingPathComponent("ownership")
+ try Data("FluidVoiceRollbackBackup-v1\n\(fixture.installed.standardizedFileURL.path)\n".utf8).write(to: unrelatedMarker)
+ try FileManager.default.createSymbolicLink(at: fixture.stage, withDestinationURL: unrelated)
+ XCTAssertThrowsError(try fixture.create())
+ XCTAssertEqual(try fixture.contents(unrelated), "preserve")
+ try FileManager.default.removeItem(at: fixture.stage)
+ try FileManager.default.createDirectory(at: fixture.stage, withIntermediateDirectories: false)
+ try FileManager.default.createSymbolicLink(at: fixture.stage.appendingPathComponent("ownership"), withDestinationURL: unrelatedMarker)
+ XCTAssertThrowsError(try fixture.create())
+ XCTAssertEqual(try fixture.contents(unrelated), "preserve")
+ }
+ }
+
+ func testPublicationFailureCleansStagingAndPreservesSource() throws {
+ try self.withFixture { fixture in
+ var operations = UpdateRollbackBackup.Operations.live
+ operations.publishBundle = { _, _ in throw ProbeFailure.injected }
+ XCTAssertThrowsError(try fixture.create(operations: operations))
+ XCTAssertFalse(fixture.stageExists)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.backup.path))
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+ }
+
+ func testCleanupFailureAfterPublicationRetainsVerifiedBackupAndRetries() throws {
+ try self.withFixture { fixture in
+ var operations = UpdateRollbackBackup.Operations.live
+ operations.removeDirectory = { _ in throw ProbeFailure.injected }
+ XCTAssertThrowsError(try fixture.create(operations: operations)) {
+ XCTAssertEqual(($0 as? UpdateRollbackBackup.Failure)?.retainedDirectoryURL, fixture.stage)
+ }
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ let nextBackup = fixture.root.appendingPathComponent("next.app")
+ try UpdateRollbackBackup.create(installedAppURL: fixture.installed, backupURL: nextBackup, validate: { try fixture.validate($0) })
+ XCTAssertFalse(fixture.stageExists)
+ XCTAssertEqual(try fixture.contents(nextBackup), "old")
+ XCTAssertEqual(try fixture.contents(fixture.backup), "old")
+ }
+ }
+
+ func testCreateFailureCannotDeleteAnUnknownPath() throws {
+ try self.withFixture { fixture in
+ var operations = UpdateRollbackBackup.Operations.live
+ operations.createDirectory = { _ in throw ProbeFailure.injected }
+ operations.removeDirectory = { _ in XCTFail("No owned directory was created") }
+ XCTAssertThrowsError(try fixture.create(operations: operations))
+ XCTAssertFalse(fixture.stageExists)
+ XCTAssertEqual(try fixture.contents(fixture.installed), "old")
+ }
+ }
+
+ private func withFixture(_ body: (Fixture) throws -> Void) throws {
+ let fixture = try Fixture()
+ defer { try? FileManager.default.removeItem(at: fixture.base) }
+ try body(fixture)
+ }
+
+ private enum ProbeFailure: Error { case injected }
+
+ private struct Fixture: Sendable {
+ let base: URL
+ let root: URL
+ let installed: URL
+ let backup: URL
+ var stage: URL { self.root.appendingPathComponent(".fluidvoice-backup-FluidVoice.app.staging", isDirectory: true) }
+ var stageExists: Bool { FileManager.default.fileExists(atPath: self.stage.path) }
+
+ init() throws {
+ self.base = FileManager.default.temporaryDirectory.appendingPathComponent("UpdateRollbackBackupTests-" + UUID().uuidString, isDirectory: true)
+ self.root = self.base.appendingPathComponent("backups", isDirectory: true)
+ self.installed = self.base.appendingPathComponent("FluidVoice.app", isDirectory: true)
+ self.backup = self.root.appendingPathComponent("saved.app", isDirectory: true)
+ try FileManager.default.createDirectory(at: self.root, withIntermediateDirectories: true)
+ try self.makeBundle(at: self.installed, contents: "old")
+ }
+
+ func makeBundle(at url: URL, contents: String) throws {
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
+ try Data(contents.utf8).write(to: url.appendingPathComponent("payload"))
+ }
+
+ func contents(_ url: URL) throws -> String {
+ try String(contentsOf: url.appendingPathComponent("payload"), encoding: .utf8)
+ }
+
+ func validate(_ url: URL) throws {
+ guard try self.contents(url) == "old" else { throw ProbeFailure.injected }
+ }
+
+ func create(operations: UpdateRollbackBackup.Operations = .live) throws {
+ try UpdateRollbackBackup.create(installedAppURL: self.installed, backupURL: self.backup, validate: { try self.validate($0) }, operations: operations)
+ }
+
+ func makeOwnedStage() throws {
+ try FileManager.default.createDirectory(at: self.stage, withIntermediateDirectories: false)
+ try Data("FluidVoiceRollbackBackup-v1\n\(self.installed.standardizedFileURL.path)\n".utf8).write(to: self.stage.appendingPathComponent("ownership"))
+ }
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/VoiceModelDeletionTests.swift b/Tests/FluidDictationIntegrationTests/VoiceModelDeletionTests.swift
index 406b9b85..08f05ac3 100644
--- a/Tests/FluidDictationIntegrationTests/VoiceModelDeletionTests.swift
+++ b/Tests/FluidDictationIntegrationTests/VoiceModelDeletionTests.swift
@@ -1,5 +1,7 @@
+import AppKit
@testable import FluidVoice_Debug
import Foundation
+import SwiftUI
import XCTest
@MainActor
@@ -9,11 +11,14 @@ private final class DeletionFixtureProvider: TranscriptionProvider {
var isReady = true
var clearCalls = 0
var prepareCalls = 0
+ var cachedFilesExist = false
var clear: (() async throws -> Void)?
var prepareBody: (() async throws -> Void)?
+ var preparationProgressHandler: ((ModelPreparationProgress) -> Void)?
func prepare(progressHandler: ((ModelPreparationProgress) -> Void)?) async throws {
self.prepareCalls += 1
+ self.preparationProgressHandler = progressHandler
try await self.prepareBody?()
}
@@ -21,6 +26,8 @@ private final class DeletionFixtureProvider: TranscriptionProvider {
ASRTranscriptionResult(text: "", confidence: 0)
}
+ func modelsExistOnDisk() -> Bool { self.cachedFilesExist }
+
func clearCache() async throws {
self.clearCalls += 1
try await self.clear?()
@@ -30,6 +37,625 @@ private final class DeletionFixtureProvider: TranscriptionProvider {
@MainActor
final class VoiceModelDeletionTests: XCTestCase {
+ private func makeNoHardwareController(for asr: ASRService) -> DirectCoreAudioLifecycleController {
+ DirectCoreAudioLifecycleController(
+ packetHandler: asr.recoveryPacketHandlerForTesting,
+ inputFactory: { _, _ in throw CocoaError(.fileReadUnknown) },
+ fingerprintReader: { _ in throw CocoaError(.fileReadUnknown) },
+ installsHardwareListeners: false,
+ deviceSnapshotReader: { _ in throw CocoaError(.fileReadUnknown) },
+ deviceLivenessReader: { _ in nil },
+ deviceResolver: { _ in throw CocoaError(.fileReadUnknown) },
+ onFormatInvalidated: { _ in }
+ )
+ }
+
+ private func withDictationModeSwitchFixture(
+ asr: ASRService,
+ hasActiveMode: Bool = true,
+ body: (ContentView) async throws -> Void
+ ) async throws {
+ var ready: ContentView?
+ let oldMode = NotchContentState.shared.mode
+ let oldSlot = NotchContentState.shared.activeDictationShortcutSlot
+ let oldPrompt = NotchContentState.shared.isPromptModeActive
+ let oldProfileName = NotchContentState.shared.promptModeOverrideProfileName
+ let oldProfileID = NotchContentState.shared.promptModeOverrideProfileID
+ let oldStopLabel = NotchContentState.shared.stopSnapshotLabel
+ let manager = MenuBarManager()
+ let view = ContentView.dictationModeSwitchFixture(asr: asr, hasActiveMode: hasActiveMode) { ready = $0 }
+ .environmentObject(manager)
+ let host = NSHostingView(rootView: view)
+ host.frame = NSRect(x: 0, y: 0, width: 120, height: 80)
+ let window = NSWindow(contentRect: host.frame, styleMask: [.titled], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = host
+ window.orderFront(nil)
+ defer {
+ window.orderOut(nil)
+ window.contentView = nil
+ window.close()
+ NotchContentState.shared.mode = oldMode
+ NotchContentState.shared.activeDictationShortcutSlot = oldSlot
+ NotchContentState.shared.isPromptModeActive = oldPrompt
+ NotchContentState.shared.promptModeOverrideProfileName = oldProfileName
+ NotchContentState.shared.promptModeOverrideProfileID = oldProfileID
+ NotchContentState.shared.stopSnapshotLabel = oldStopLabel
+ }
+ host.layoutSubtreeIfNeeded()
+ let deadline = ContinuousClock.now + .seconds(3)
+ while ready == nil, ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ manager.setOverlayMode(.edit)
+ try await body(XCTUnwrap(ready, "SwiftUI must install the real ContentView state"))
+ }
+
+ private func replayPrimaryTap(_ manager: GlobalHotkeyManager) throws {
+ for type in [CGEventType.keyDown, .keyUp] {
+ let event = try XCTUnwrap(CGEvent(keyboardEventSource: nil, virtualKey: 2, keyDown: type == .keyDown))
+ event.type = type
+ event.flags = [.maskControl, .maskCommand]
+ _ = manager.handleKeyEvent(type: type, event: event)
+ }
+ }
+
+ private func makeModeSwitchHotkeyManager(
+ asr: ASRService,
+ view: ContentView,
+ onSwitch: @escaping () -> Void,
+ onStop: @escaping () -> Void
+ ) -> GlobalHotkeyManager {
+ let manager = GlobalHotkeyManager(
+ asrService: asr,
+ primaryShortcuts: [HotkeyShortcut(keyCode: 2, modifierFlags: [.control, .command])],
+ promptModeShortcut: HotkeyShortcut(keyCode: 60, modifierFlags: []),
+ commandModeShortcut: nil,
+ rewriteModeShortcut: HotkeyShortcut(keyCode: 58, modifierFlags: []),
+ promptModeShortcutEnabled: false,
+ commandModeShortcutEnabled: false,
+ rewriteModeShortcutEnabled: false,
+ dictationModeCallback: {
+ onSwitch()
+ await view.beginDictationModeSwitchForTesting()?.value
+ },
+ stopAndProcessCallback: { _ in onStop() },
+ isDictateRecordingProvider: { view.dictationModeSwitchStateForTesting.mode == "dictate" },
+ isSessionLockedProvider: { false }
+ )
+ manager.setHotkeyMode(.toggle)
+ return manager
+ }
+
+ func testRewriteToDictateSwitchPreservesCaptureThenNextTapStops() async throws {
+ let settings = SettingsStore.shared
+ let selected = settings.selectedSpeechModel
+ let primary = settings.dictationPromptSelection(for: .primary)
+ let secondary = settings.dictationPromptSelection(for: .secondary)
+ let savesHistory = settings.saveTranscriptionHistory
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[selected] = provider
+ asr.isAsrReady = true
+ asr.finalText = "retained final text"
+ let samples: [Float] = [0.12, -0.24, 0.31]
+ asr.configureAudioRouteRecoveryForTesting(controller: self.makeNoHardwareController(for: asr), devices: [], initialSamples: samples)
+ let lease = try asr.acquireExclusiveActivity(.dictation)
+ asr.configureDictationModeSwitchForTesting(ownedLease: lease)
+ try await self.withDictationModeSwitchFixture(asr: asr) { view in
+ let generation = view.dictationModeSwitchStateForTesting.generation
+ var switches = 0
+ var stops = 0
+ let manager = self.makeModeSwitchHotkeyManager(asr: asr, view: view, onSwitch: { switches += 1 }, onStop: {
+ stops += 1
+ asr.isRunning = false
+ asr.releaseExclusiveActivity(lease)
+ })
+ asr.errorTitle = "Dictation Unavailable"
+ asr.errorMessage = "Wait for the active dictation to finish."
+ asr.showError = true
+ try self.replayPrimaryTap(manager)
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(switches, 1)
+ XCTAssertEqual(stops, 0)
+ XCTAssertEqual(view.dictationModeSwitchStateForTesting.mode, "dictate")
+ XCTAssertEqual(view.dictationModeSwitchStateForTesting.slot, .primary)
+ XCTAssertEqual(view.dictationModeSwitchStateForTesting.generation, generation)
+ XCTAssertEqual(NotchContentState.shared.mode, .dictation)
+ XCTAssertFalse(asr.showError, "Only the stale own-capture block should disappear")
+ XCTAssertTrue(asr.isRunning)
+ XCTAssertTrue(asr.canSwitchOwnedDictationCaptureMode)
+ XCTAssertEqual(asr.activeExclusiveActivity, .dictation)
+ XCTAssertTrue(asr.audioRouteRecoveryStateForTesting.acceptingPCM)
+ XCTAssertEqual(asr.audioRouteRecoveryStateForTesting.samples, samples)
+ XCTAssertTrue((asr.fileTranscriptionProvider as? DeletionFixtureProvider) === provider)
+ XCTAssertTrue(asr.isAsrReady)
+ XCTAssertEqual(asr.finalText, "retained final text")
+ XCTAssertEqual(provider.prepareCalls + provider.clearCalls, 0)
+ XCTAssertEqual(settings.selectedSpeechModel, selected)
+ XCTAssertEqual(settings.dictationPromptSelection(for: .primary), primary)
+ XCTAssertEqual(settings.dictationPromptSelection(for: .secondary), secondary)
+ XCTAssertEqual(settings.saveTranscriptionHistory, savesHistory)
+ try self.replayPrimaryTap(manager)
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(switches, 1, "The next tap must stop, not switch again")
+ XCTAssertEqual(stops, 1)
+ XCTAssertFalse(asr.isRunning)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ }
+ asr.configureDictationModeSwitchForTesting(ownedLease: nil)
+ await asr.finishAudioRouteRecoveryTest()
+ asr.releaseExclusiveActivity(lease)
+ }
+
+ func testRapidRewriteToDictateDoubleTapSwitchesThenStopsOnce() async throws {
+ let asr = ASRService()
+ asr.configureAudioRouteRecoveryForTesting(controller: self.makeNoHardwareController(for: asr), devices: [], initialSamples: [0.5])
+ let lease = try asr.acquireExclusiveActivity(.dictation)
+ asr.configureDictationModeSwitchForTesting(ownedLease: lease)
+ try await self.withDictationModeSwitchFixture(asr: asr) { view in
+ var switches = 0
+ var stops = 0
+ let manager = self.makeModeSwitchHotkeyManager(asr: asr, view: view, onSwitch: { switches += 1 }, onStop: {
+ stops += 1
+ asr.isRunning = false
+ asr.releaseExclusiveActivity(lease)
+ })
+ try self.replayPrimaryTap(manager)
+ try self.replayPrimaryTap(manager)
+ for _ in 0..<30 {
+ await Task.yield()
+ }
+ XCTAssertEqual(switches, 1)
+ XCTAssertEqual(stops, 1)
+ XCTAssertEqual(view.dictationModeSwitchStateForTesting.mode, "dictate")
+ XCTAssertEqual(asr.audioRouteRecoveryStateForTesting.samples, [0.5])
+ }
+ asr.configureDictationModeSwitchForTesting(ownedLease: nil)
+ await asr.finishAudioRouteRecoveryTest()
+ asr.releaseExclusiveActivity(lease)
+ }
+
+ func testDictationModeSwitchRejectsForeignAndUnsettledCaptureWithoutWrites() async throws {
+ let cases: [(String, ASRExclusiveActivity)] = [
+ ("meeting", .meeting), ("file", .fileTranscription), ("API", .localAPI),
+ ("model", .modelMaintenance), ("backup", .settingsRestore),
+ ("unowned", .dictation), ("mismatch", .dictation), ("stale", .dictation),
+ ("starting", .dictation), ("finalizing", .dictation), ("training", .dictation),
+ ("draining", .dictation), ("recovering", .dictation),
+ ("idle UI", .dictation), ("cancel save", .dictation), ("processing", .dictation),
+ ]
+ let settings = SettingsStore.shared
+ let secondary = settings.dictationPromptSelection(for: .secondary)
+ defer { settings.setDictationPromptSelection(secondary, for: .secondary) }
+ let attempted: SettingsStore.DictationPromptSelection = secondary == .privateAI ? .off : .privateAI
+ for (name, activity) in cases {
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[settings.selectedSpeechModel] = provider
+ asr.isAsrReady = true
+ asr.configureAudioRouteRecoveryForTesting(controller: self.makeNoHardwareController(for: asr), devices: [], initialSamples: [0.25])
+ let lease = try asr.acquireExclusiveActivity(activity)
+ let owned = name == "unowned" ? nil : name == "mismatch" ? ASRActivityLease(id: UUID(), activity: .dictation) : lease
+ asr.configureDictationModeSwitchForTesting(ownedLease: owned, starting: name == "starting", finalizing: name == "finalizing", dictionaryTraining: name == "training")
+ if name == "stale" { asr.releaseExclusiveActivity(lease) }
+ let finishDrain = name == "draining" || name == "recovering" ? asr.beginDictationBufferDrainForTesting(recovering: name == "recovering") : nil
+ try await self.withDictationModeSwitchFixture(asr: asr, hasActiveMode: name != "idle UI") { view in
+ view.blockDictationModeSwitchForTesting(savingCancellation: name == "cancel save", processing: name == "processing")
+ let before = view.dictationModeSwitchStateForTesting
+ XCTAssertNil(view.beginDictationModeSwitchForTesting(selection: attempted), name)
+ XCTAssertEqual(view.dictationModeSwitchStateForTesting.mode, before.mode, name)
+ XCTAssertEqual(view.dictationModeSwitchStateForTesting.slot, before.slot, name)
+ XCTAssertEqual(view.dictationModeSwitchStateForTesting.generation, before.generation, name)
+ XCTAssertEqual(NotchContentState.shared.mode, .edit, name)
+ XCTAssertEqual(settings.dictationPromptSelection(for: .secondary), secondary, name)
+ XCTAssertEqual(asr.audioRouteRecoveryStateForTesting.samples, [0.25], name)
+ XCTAssertTrue(asr.audioRouteRecoveryStateForTesting.acceptingPCM, name)
+ XCTAssertTrue((asr.fileTranscriptionProvider as? DeletionFixtureProvider) === provider, name)
+ XCTAssertEqual(provider.prepareCalls + provider.clearCalls, 0, name)
+ }
+ finishDrain?()
+ asr.configureDictationModeSwitchForTesting(ownedLease: nil)
+ await asr.finishAudioRouteRecoveryTest()
+ asr.releaseExclusiveActivity(lease)
+ }
+ }
+
+ func testOwnedDictationModeSwitchPreservesUnrelatedError() async throws {
+ let asr = ASRService()
+ asr.configureAudioRouteRecoveryForTesting(controller: self.makeNoHardwareController(for: asr), devices: [], initialSamples: [0.25])
+ let lease = try asr.acquireExclusiveActivity(.dictation)
+ asr.configureDictationModeSwitchForTesting(ownedLease: lease)
+ asr.errorTitle = "Microphone Unavailable"
+ asr.errorMessage = "Retained microphone error"
+ asr.showError = true
+ try await self.withDictationModeSwitchFixture(asr: asr) { view in
+ XCTAssertNil(view.beginDictationModeSwitchForTesting())
+ XCTAssertEqual(view.dictationModeSwitchStateForTesting.mode, "dictate")
+ XCTAssertTrue(asr.showError)
+ XCTAssertEqual(asr.errorTitle, "Microphone Unavailable")
+ XCTAssertEqual(asr.errorMessage, "Retained microphone error")
+ }
+ asr.configureDictationModeSwitchForTesting(ownedLease: nil)
+ await asr.finishAudioRouteRecoveryTest()
+ asr.releaseExclusiveActivity(lease)
+ }
+
+ func testBusyBackupAdmissionPreservesCapturedPCMProviderAndActivity() async throws {
+ let settings = SettingsStore.shared
+ let previous = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = previous }
+ settings.selectedSpeechModel = .appleSpeech
+ let asr = ASRService()
+ let original = DeletionFixtureProvider()
+ let replacement = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.appleSpeech] = original
+ asr.modelProvidersForTesting[.parakeetTDT] = replacement
+ asr.isAsrReady = true
+ // Never open an input, query Core Audio, or install real hardware listeners.
+ let controller = self.makeNoHardwareController(for: asr)
+ let samples: [Float] = [0.12, -0.24, 0.31]
+ asr.configureAudioRouteRecoveryForTesting(controller: controller, devices: [], initialSamples: samples)
+ let dictation = try asr.acquireExclusiveActivity(.dictation)
+ let before = asr.audioRouteRecoveryStateForTesting
+ XCTAssertThrowsError(try asr.beginSettingsBackupRestore()) { error in
+ guard case ASRActivityError.settingsRestoreUnavailable = error else { return XCTFail("Unexpected admission error: \(error)") }
+ }
+ XCTAssertEqual(settings.selectedSpeechModel, .appleSpeech)
+ XCTAssertTrue((asr.fileTranscriptionProvider as? DeletionFixtureProvider) === original)
+ XCTAssertTrue(asr.isAsrReady)
+ XCTAssertEqual(asr.activeExclusiveActivity, .dictation)
+ let after = asr.audioRouteRecoveryStateForTesting
+ XCTAssertTrue(after.acceptingPCM)
+ XCTAssertEqual(after.samples, samples)
+ XCTAssertEqual(after.pending, before.pending)
+ XCTAssertEqual(after.recovering, before.recovering)
+ XCTAssertEqual(original.prepareCalls + replacement.prepareCalls, 0)
+ XCTAssertEqual(original.clearCalls + replacement.clearCalls, 0)
+ await asr.finishAudioRouteRecoveryTest()
+ asr.releaseExclusiveActivity(dictation)
+ let admitted = try asr.beginSettingsBackupRestore()
+ XCTAssertEqual(asr.activeExclusiveActivity, .settingsRestore)
+ asr.releaseExclusiveActivity(admitted)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ }
+
+ func testBackupReservationRejectsNewTranscriptionModelWorkAndPreview() async throws {
+ let asr = ASRService()
+ let selected = SettingsStore.shared.selectedSpeechModel
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[selected] = provider
+ asr.modelProvidersForTesting[.whisperTiny] = provider
+ let reservation = try asr.beginSettingsBackupRestore()
+ for activity: ASRExclusiveActivity in [.dictation, .fileTranscription, .localAPI, .meeting, .modelMaintenance] {
+ XCTAssertThrowsError(try asr.acquireExclusiveActivity(activity))
+ }
+ do {
+ try await asr.ensureAsrReady()
+ XCTFail("Preparation must not enter while a backup is being applied")
+ } catch let ASRActivityError.activityInProgress(activity) {
+ XCTAssertEqual(activity, .settingsRestore)
+ }
+ do {
+ try await asr.downloadModel(.whisperTiny, progressHandler: nil)
+ XCTFail("Download must not enter while a backup is being applied")
+ } catch let ASRActivityError.activityInProgress(activity) {
+ XCTAssertEqual(activity, .settingsRestore)
+ }
+ do {
+ try await asr.clearModelCache(for: .whisperTiny)
+ XCTFail("Deletion must not enter while a backup is being applied")
+ } catch {}
+ asr.micStatus = .authorized
+ await asr.startMicrophonePreview()
+ XCTAssertFalse(asr.isMicrophonePreviewActive)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ XCTAssertFalse(asr.hasActiveModelPreparation)
+ XCTAssertNil(asr.deletingModelID)
+ XCTAssertEqual(provider.prepareCalls, 0)
+ XCTAssertEqual(provider.clearCalls, 0)
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selected)
+ XCTAssertEqual(asr.activeExclusiveActivity, .settingsRestore)
+ asr.releaseExclusiveActivity(reservation)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ let retry = try asr.beginSettingsBackupRestore()
+ asr.releaseExclusiveActivity(retry)
+ }
+
+ func testSynchronousBackupResetPrecedesQueuedPostImportAdmission() async throws {
+ let settings = SettingsStore.shared
+ let previous = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = previous }
+ settings.selectedSpeechModel = .parakeetTDT
+ let asr = ASRService()
+ asr.configureAudioRouteRecoveryForTesting(
+ controller: self.makeNoHardwareController(for: asr), devices: [], initialSamples: []
+ )
+ await asr.finishAudioRouteRecoveryTest()
+ // Provider construction is metadata-only; no preparation or model load.
+ let retired = try XCTUnwrap(asr.fileTranscriptionProvider as? FluidAudioProvider)
+ asr.isAsrReady = true
+ let reservation = try asr.beginSettingsBackupRestore()
+ settings.selectedSpeechModel = .parakeetTDTv2
+ // Mirrors the unchanged-idle import tail: synchronous invalidation,
+ // UI event/queued caller, then lease release, with no intervening await.
+ asr.handleSettingsBackupDidRestore()
+ XCTAssertTrue(asr.isAsrReady, "The held reservation defers retirement until release")
+ XCTAssertEqual(asr.activeExclusiveActivity, .settingsRestore)
+ let queuedCaller = Task { @MainActor in
+ XCTAssertFalse(asr.isAsrReady, "A queued caller must never see old ready state after import admission releases")
+ XCTAssertFalse((asr.fileTranscriptionProvider as? FluidAudioProvider) === retired, "The old cached provider must be retired before the caller runs")
+ do {
+ let next = try asr.acquireExclusiveActivity(.dictation)
+ asr.releaseExclusiveActivity(next)
+ } catch let ASRActivityError.activityInProgress(activity) {
+ XCTAssertEqual(activity, .modelMaintenance, "The bounded model reset may still own admission")
+ } catch { XCTFail("Unexpected queued admission error: \(error)") }
+ }
+ asr.releaseExclusiveActivity(reservation)
+ XCTAssertFalse(asr.isAsrReady)
+ XCTAssertFalse((asr.fileTranscriptionProvider as? FluidAudioProvider) === retired)
+ // Cache-existence checks use a fake and never prepare/load actual models.
+ let replacement = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.parakeetTDTv2] = replacement
+ await queuedCaller.value
+ await asr.finishAudioRouteRecoveryTest()
+ let deadline = ContinuousClock.now + .seconds(3)
+ while asr.activeExclusiveActivity != nil, ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertEqual(replacement.prepareCalls, 0)
+ XCTAssertEqual(replacement.clearCalls, 0)
+ let retry = try asr.beginSettingsBackupRestore()
+ asr.releaseExclusiveActivity(retry)
+ }
+
+ func testActiveDownloadRejectsBackupWithoutCancellingOrChangingIt() async throws {
+ let asr = ASRService()
+ let selected = SettingsStore.shared.selectedSpeechModel
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.whisperTiny] = provider
+ provider.prepareBody = {
+ XCTAssertTrue(asr.hasActiveModelDownload)
+ XCTAssertThrowsError(try asr.beginSettingsBackupRestore())
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertTrue(asr.hasActiveModelDownload)
+ XCTAssertFalse(asr.isCancellingModelDownload)
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selected)
+ }
+ try await asr.downloadModel(.whisperTiny, progressHandler: nil)
+ XCTAssertEqual(provider.prepareCalls, 1)
+ XCTAssertEqual(provider.clearCalls, 0)
+ provider.prepareBody = nil
+ let retry = try asr.beginSettingsBackupRestore()
+ asr.releaseExclusiveActivity(retry)
+ }
+
+ func testActivePreparationRejectsBackupWithoutCancellingIt() async throws {
+ let settings = SettingsStore.shared
+ let previous = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = previous }
+ settings.selectedSpeechModel = .whisperTiny
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.whisperTiny] = provider
+ provider.prepareBody = {
+ XCTAssertTrue(asr.hasActiveModelPreparation)
+ XCTAssertThrowsError(try asr.beginSettingsBackupRestore())
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertTrue(asr.hasActiveModelPreparation)
+ XCTAssertFalse(asr.isCancellingModelPreparation)
+ throw CocoaError(.fileReadUnknown)
+ }
+ do { try await asr.ensureAsrReady() } catch {}
+ XCTAssertEqual(provider.prepareCalls, 1)
+ XCTAssertEqual(provider.clearCalls, 0)
+ provider.prepareBody = nil
+ let retry = try asr.beginSettingsBackupRestore()
+ asr.releaseExclusiveActivity(retry)
+ }
+
+ func testCompletedProviderResetDoesNotPermanentlyBlockBackupImport() async throws {
+ let settings = SettingsStore.shared
+ let previous = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = previous }
+ settings.selectedSpeechModel = .whisperTiny
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.whisperTiny] = provider
+ asr.resetTranscriptionProvider()
+ XCTAssertThrowsError(try asr.beginSettingsBackupRestore())
+ let deadline = ContinuousClock.now + .seconds(3)
+ while asr.activeExclusiveActivity != nil, ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ XCTAssertNil(asr.activeExclusiveActivity)
+ // Give the independent executor drain its actor turn; no ensureAsrReady
+ // call is allowed to hide a stale completed reset handle in this regression.
+ var reservation: ASRActivityLease?
+ while reservation == nil, ContinuousClock.now < deadline {
+ reservation = try? asr.beginSettingsBackupRestore()
+ if reservation == nil { try await Task.sleep(for: .milliseconds(1)) }
+ }
+ let admitted = try XCTUnwrap(reservation)
+ asr.releaseExclusiveActivity(admitted)
+ XCTAssertEqual(provider.prepareCalls, 0)
+ XCTAssertEqual(provider.clearCalls, 0)
+ XCTAssertEqual(settings.selectedSpeechModel, .whisperTiny)
+ }
+
+ func testCancelledBackupAdmissionNeverAcquiresAnActivity() async throws {
+ let asr = ASRService()
+ let cancelled = Task { () throws -> ASRActivityLease in
+ withUnsafeCurrentTask { $0?.cancel() }
+ return try asr.beginSettingsBackupRestore()
+ }
+ do { _ = try await cancelled.value; XCTFail("Cancelled imports must not reserve activity") } catch is CancellationError {}
+ XCTAssertNil(asr.activeExclusiveActivity)
+ let retry = try asr.beginSettingsBackupRestore()
+ asr.releaseExclusiveActivity(retry)
+ }
+
+ func testCancelledDownloadKeepsCleanupFailureAndDoesNotClearPublishedCache() async throws {
+ let selected = SettingsStore.shared.selectedSpeechModel
+ let retained = FileManager.default.temporaryDirectory.appendingPathComponent("retained-download-stage")
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ provider.cachedFilesExist = true
+ provider.prepareBody = {
+ withUnsafeCurrentTask { $0?.cancel() }
+ throw ParakeetArchiveDownloader.DownloadError.cleanupFailed(retained)
+ }
+ asr.modelProvidersForTesting[.fluidParakeetMini] = provider
+ do {
+ try await asr.downloadModel(.fluidParakeetMini, progressHandler: nil)
+ XCTFail("The retained cleanup path must reach the caller")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case let .cleanupFailed(path) = error else { return XCTFail("Unexpected archive failure") }
+ XCTAssertEqual(path, retained)
+ }
+ XCTAssertEqual(provider.clearCalls, 0)
+ XCTAssertEqual(provider.prepareCalls, 1)
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selected)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ XCTAssertFalse(asr.isCancellingModelDownload)
+ XCTAssertNil(asr.downloadingModelId)
+ }
+
+ func testPreparationCleanupFailureSkipsDestructiveRetryEvenWhenCancelled() async throws {
+ guard SettingsStore.SpeechModel.availableModels.contains(.fluidParakeetMini) else {
+ throw XCTSkip("Compact model preparation requires a supported Mac and macOS version")
+ }
+ let settings = SettingsStore.shared
+ let previous = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = previous }
+ settings.selectedSpeechModel = .fluidParakeetMini
+ let retained = FileManager.default.temporaryDirectory.appendingPathComponent("retained-preparation-stage")
+ for cancelled in [false, true] {
+ for cached in [false, true] {
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ provider.cachedFilesExist = cached
+ provider.prepareBody = {
+ if cancelled { withUnsafeCurrentTask { $0?.cancel() } }
+ throw ParakeetArchiveDownloader.DownloadError.cleanupFailed(retained)
+ }
+ asr.modelProvidersForTesting[.fluidParakeetMini] = provider
+ do {
+ try await asr.ensureAsrReady()
+ XCTFail("The retained cleanup path must reach the caller")
+ } catch let error as ParakeetArchiveDownloader.DownloadError {
+ guard case let .cleanupFailed(path) = error else { return XCTFail("Unexpected archive failure") }
+ XCTAssertEqual(path, retained)
+ }
+ XCTAssertEqual(provider.prepareCalls, 1)
+ XCTAssertEqual(provider.clearCalls, 0, "A staging failure must preserve published model files")
+ XCTAssertFalse(asr.isAsrReady)
+ XCTAssertFalse(asr.hasActiveModelPreparation)
+ XCTAssertFalse(asr.isCancellingModelPreparation)
+ XCTAssertFalse(asr.isDownloadingModel)
+ XCTAssertFalse(asr.isLoadingModel)
+ }
+ }
+ }
+
+ func testRestoredCompactSelectionRetiresReadyModelOnlyAfterActiveWorkFinishes() async throws {
+ let settings = SettingsStore.shared
+ let previous = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = previous }
+ for model: SettingsStore.SpeechModel in [.fluidParakeetMini, .fluidParakeetPico] {
+ settings.selectedSpeechModel = .parakeetTDT
+ let asr = ASRService()
+ let old = DeletionFixtureProvider()
+ let restored = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.parakeetTDT] = old
+ asr.modelProvidersForTesting[model] = restored
+ asr.isAsrReady = true
+ let lease = try asr.acquireExclusiveActivity(.dictation)
+ settings.selectedSpeechModel = model
+ asr.handleSettingsBackupDidRestore()
+ XCTAssertTrue(asr.isAsrReady, "Restoring settings must not interrupt active dictation")
+ XCTAssertEqual(asr.activeExclusiveActivity, .dictation)
+ XCTAssertEqual(old.clearCalls, 0)
+ XCTAssertEqual(restored.prepareCalls, 0)
+ await asr.finishAudioRouteRecoveryTest()
+ asr.releaseExclusiveActivity(lease)
+ XCTAssertFalse(asr.isAsrReady, "The old ready model must be retired before the next dictation")
+ XCTAssertEqual(settings.selectedSpeechModel, model)
+ XCTAssertEqual(old.clearCalls, 0, "Restoring settings must retain downloaded files")
+ let deadline = Date().addingTimeInterval(2)
+ while asr.activeExclusiveActivity != nil, Date() < deadline {
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ XCTAssertNil(asr.activeExclusiveActivity)
+ }
+ }
+
+ func testCompactModelDownloadsKeepActiveSelectionAndRejectCompetingDeletion() async throws {
+ let settings = SettingsStore.shared
+ let previous = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = previous }
+ settings.selectedSpeechModel = .parakeetTDT
+ for model: SettingsStore.SpeechModel in [.fluidParakeetMini, .fluidParakeetPico] {
+ let asr = ASRService()
+ let target = DeletionFixtureProvider()
+ let active = DeletionFixtureProvider()
+ asr.isAsrReady = true
+ asr.modelProvidersForTesting[model] = target
+ asr.modelProvidersForTesting[.parakeetTDT] = active
+ target.prepareBody = {
+ XCTAssertEqual(asr.downloadingModelId, model.id)
+ XCTAssertEqual(settings.selectedSpeechModel, .parakeetTDT)
+ do {
+ try await asr.clearModelCache(for: model)
+ XCTFail("A model being downloaded must not be deleted")
+ } catch {}
+ XCTAssertTrue(asr.hasActiveModelDownload)
+ }
+ try await asr.downloadModel(model, progressHandler: nil)
+ XCTAssertEqual(target.prepareCalls, 1)
+ XCTAssertEqual(active.prepareCalls, 0)
+ XCTAssertEqual(active.clearCalls, 0)
+ XCTAssertTrue(active.isReady)
+ XCTAssertTrue(asr.isAsrReady)
+ XCTAssertEqual(settings.selectedSpeechModel, .parakeetTDT)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ XCTAssertNil(asr.downloadingModelId)
+ target.prepareBody = nil
+ }
+ }
+
+ func testCompactModelFailedAndCancelledDownloadsReleaseAdmission() async throws {
+ let selected = SettingsStore.shared.selectedSpeechModel
+ for model: SettingsStore.SpeechModel in [.fluidParakeetMini, .fluidParakeetPico] {
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[model] = provider
+ for cancelled in [false, true] {
+ provider.prepareBody = {
+ if cancelled { throw CancellationError() }
+ throw URLError(.notConnectedToInternet)
+ }
+ do {
+ try await asr.downloadModel(model, progressHandler: nil)
+ XCTFail("Failure must reach the caller")
+ } catch {}
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selected)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ XCTAssertNil(asr.downloadingModelId)
+ XCTAssertFalse(asr.isCancellingModelDownload)
+ }
+ provider.prepareBody = nil
+ try await asr.downloadModel(model, progressHandler: nil)
+ XCTAssertEqual(provider.prepareCalls, 3)
+ }
+ }
+
func testLegacyNemotronDeletionUsesCanonicalProviderAndInvalidatesOnlyActiveModel() async throws {
let settings = SettingsStore.shared
let previous = settings.selectedSpeechModel
@@ -241,4 +867,217 @@ final class VoiceModelDeletionTests: XCTestCase {
XCTAssertNil(asr.deletingModelID)
XCTAssertNil(asr.activeExclusiveActivity)
}
+
+ func testCompactLoadCancellationRetainsAtomicallyPublishedModelsAndLegacyPolicy() {
+ #if arch(arm64)
+ for model: SettingsStore.SpeechModel in [.fluidParakeetMini, .fluidParakeetPico] {
+ let provider = FluidAudioProvider(modelOverride: model, configureWordBoosting: false)
+ XCTAssertFalse(
+ provider.shouldClearCacheAfterCancellation,
+ "The hosted downloader owns staging cleanup; cancellation during Core ML loading must retain a verified publication"
+ )
+ XCTAssertEqual(provider.modelsExistOnDisk(), SpeechModelInstallationSnapshot.shared.isInstalled(modelID: model.id))
+ }
+ for model: SettingsStore.SpeechModel in [.parakeetTDTv2, .parakeetTDT] {
+ XCTAssertTrue(FluidAudioProvider(modelOverride: model, configureWordBoosting: false).shouldClearCacheAfterCancellation)
+ }
+ #endif
+ }
+
+ func testCompactWeightUpdatesRejectEveryForeignActivityWithoutChangingCaptureOrProvider() async throws {
+ let selected = SettingsStore.shared.selectedSpeechModel
+ for activity: ASRExclusiveActivity in [.dictation, .meeting, .fileTranscription, .localAPI, .settingsRestore, .modelMaintenance] {
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.fluidParakeetMini] = provider
+ asr.isAsrReady = true
+ let lease = try asr.acquireExclusiveActivity(activity)
+ do {
+ try await asr.downloadModel(.fluidParakeetMini, updateWeights: true, progressHandler: nil)
+ XCTFail("Updates must not enter while \(activity) owns admission")
+ } catch {}
+ XCTAssertEqual(asr.activeExclusiveActivity, activity)
+ XCTAssertEqual(provider.prepareCalls + provider.clearCalls, 0)
+ XCTAssertTrue(provider.isReady)
+ XCTAssertTrue(asr.isAsrReady)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selected)
+ asr.releaseExclusiveActivity(lease)
+ }
+ }
+
+ func testCompactWeightUpdatesRejectUnownedCaptureAndPendingDrains() async throws {
+ for state in ["running", "starting", "finalizing", "training", "draining", "recovering"] {
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.fluidParakeetMini] = provider
+ asr.isAsrReady = true
+ asr.isRunning = state == "running"
+ asr.configureDictationModeSwitchForTesting(ownedLease: nil, starting: state == "starting", finalizing: state == "finalizing", dictionaryTraining: state == "training")
+ let finish = state == "draining" || state == "recovering" ? asr.beginDictationBufferDrainForTesting(recovering: state == "recovering") : nil
+ do {
+ try await asr.downloadModel(.fluidParakeetMini, updateWeights: true, progressHandler: nil)
+ XCTFail("Updates must not change \(state) audio")
+ } catch {}
+ XCTAssertEqual(provider.prepareCalls + provider.clearCalls, 0)
+ XCTAssertEqual(asr.isRunning, state == "running")
+ XCTAssertTrue(asr.isAsrReady)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ finish?()
+ asr.isRunning = false
+ asr.configureDictationModeSwitchForTesting(ownedLease: nil)
+ }
+ }
+
+ func testInactiveCompactWeightUpdateReservesAdmissionWithoutChangingActiveSelection() async throws {
+ let settings = SettingsStore.shared
+ let selected = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = selected }
+ settings.selectedSpeechModel = .parakeetTDTv2
+ for model: SettingsStore.SpeechModel in [.fluidParakeetMini, .fluidParakeetPico] {
+ let asr = ASRService()
+ let target = DeletionFixtureProvider()
+ let active = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[model] = target
+ asr.modelProvidersForTesting[.parakeetTDTv2] = active
+ asr.isAsrReady = true
+ target.prepareBody = {
+ XCTAssertEqual(asr.activeExclusiveActivity, .modelMaintenance)
+ XCTAssertTrue(asr.hasActiveModelDownload)
+ XCTAssertThrowsError(try asr.acquireExclusiveActivity(.dictation))
+ XCTAssertThrowsError(try asr.beginSettingsBackupRestore())
+ do { try await asr.clearModelCache(for: model); XCTFail("A weight update must block deletion") } catch {}
+ do { try await asr.downloadModel(.whisperTiny, progressHandler: nil); XCTFail("A weight update must block competing downloads") } catch {}
+ }
+ try await asr.downloadModel(model, updateWeights: true, progressHandler: nil)
+ XCTAssertEqual(target.prepareCalls, 1)
+ XCTAssertEqual(target.clearCalls, 0)
+ XCTAssertEqual(active.prepareCalls + active.clearCalls, 0)
+ XCTAssertTrue(active.isReady)
+ XCTAssertTrue(asr.isAsrReady)
+ XCTAssertEqual(settings.selectedSpeechModel, .parakeetTDTv2)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ XCTAssertNil(asr.downloadingModelId)
+ }
+ }
+
+ func testFailedOrCancelledWeightUpdateKeepsActiveProviderAndNeverClearsPublishedFiles() async throws {
+ let settings = SettingsStore.shared
+ let selected = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = selected }
+ for model: SettingsStore.SpeechModel in [.fluidParakeetMini, .fluidParakeetPico] {
+ settings.selectedSpeechModel = model
+ for cancelled in [false, true] {
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[model] = provider
+ asr.isAsrReady = true
+ provider.prepareBody = {
+ if cancelled { throw CancellationError() }
+ throw URLError(.notConnectedToInternet)
+ }
+ do { try await asr.downloadModel(model, updateWeights: true, progressHandler: nil); XCTFail("Failure must reach the caller") } catch {}
+ XCTAssertEqual(provider.prepareCalls, 1)
+ XCTAssertEqual(provider.clearCalls, 0, "Explicit update failures never delete old files")
+ XCTAssertTrue(provider.isReady)
+ XCTAssertTrue(asr.isAsrReady)
+ XCTAssertTrue((asr.fileTranscriptionProvider as? DeletionFixtureProvider) === provider)
+ XCTAssertEqual(settings.selectedSpeechModel, model)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ XCTAssertFalse(asr.isCancellingModelDownload)
+ let retry = try asr.acquireExclusiveActivity(.dictation)
+ asr.releaseExclusiveActivity(retry)
+ }
+ }
+ }
+
+ func testOnlyCompactModelsAcceptWeightUpdatesAndCancelledAdmissionHasNoWrites() async throws {
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.parakeetTDTv2] = provider
+ asr.modelProvidersForTesting[.fluidParakeetMini] = provider
+ do { try await asr.downloadModel(.parakeetTDTv2, updateWeights: true, progressHandler: nil); XCTFail("Legacy models have no weight-update path") } catch {}
+ let task = Task { try await asr.downloadModel(.fluidParakeetMini, updateWeights: true, progressHandler: nil) }
+ task.cancel()
+ do { try await task.value; XCTFail("Cancelled admission must not begin") } catch is CancellationError {}
+ XCTAssertEqual(provider.prepareCalls + provider.clearCalls, 0)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ }
+
+ func testStaleCancelledWeightUpdateProgressCannotReplaceRetryProgress() async throws {
+ let settings = SettingsStore.shared
+ let selected = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = selected }
+ settings.selectedSpeechModel = .parakeetTDTv2
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.fluidParakeetMini] = provider
+ provider.prepareBody = { throw CancellationError() }
+ do { try await asr.downloadModel(.fluidParakeetMini, updateWeights: true, progressHandler: nil); XCTFail("First update cancels") } catch is CancellationError {}
+ let stale = provider.preparationProgressHandler
+ provider.prepareBody = {
+ stale?(.downloading(0.97))
+ for _ in 0..<4 {
+ await Task.yield()
+ }
+ XCTAssertNil(asr.downloadProgress, "An old operation must not update the new progress")
+ provider.preparationProgressHandler?(.downloading(0.25))
+ for _ in 0..<4 {
+ await Task.yield()
+ }
+ XCTAssertEqual(asr.downloadProgress, 0.25)
+ }
+ try await asr.downloadModel(.fluidParakeetMini, updateWeights: true, progressHandler: nil)
+ XCTAssertNil(asr.downloadProgress)
+ XCTAssertEqual(provider.clearCalls, 0)
+ XCTAssertEqual(settings.selectedSpeechModel, .parakeetTDTv2)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ }
+
+ func testSuccessfulActiveWeightUpdateInvalidatesProviderOnlyAfterPublication() async throws {
+ let settings = SettingsStore.shared
+ let selected = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = selected }
+ settings.selectedSpeechModel = .fluidParakeetMini
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.fluidParakeetMini] = provider
+ asr.isAsrReady = true
+ provider.prepareBody = {
+ XCTAssertTrue(asr.isAsrReady, "Keep the old checkpoint ready until replacement commits")
+ XCTAssertEqual(asr.activeExclusiveActivity, .modelMaintenance)
+ }
+ try await asr.downloadModel(.fluidParakeetMini, updateWeights: true, progressHandler: nil)
+ XCTAssertFalse(asr.isAsrReady, "The next use must load the replacement checkpoint")
+ XCTAssertEqual(settings.selectedSpeechModel, .fluidParakeetMini)
+ XCTAssertEqual(provider.clearCalls, 0)
+ let deadline = ContinuousClock.now + .seconds(2)
+ while asr.activeExclusiveActivity != nil, ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ }
+
+ func testLateCancellationAfterCommittedWeightUpdateDoesNotDeleteItsFiles() async throws {
+ let settings = SettingsStore.shared
+ let selected = settings.selectedSpeechModel
+ defer { settings.selectedSpeechModel = selected }
+ settings.selectedSpeechModel = .parakeetTDTv2
+ let asr = ASRService()
+ let provider = DeletionFixtureProvider()
+ asr.modelProvidersForTesting[.fluidParakeetMini] = provider
+ // The provider returns only after its atomic publication point.
+ provider.prepareBody = { withUnsafeCurrentTask { $0?.cancel() } }
+ try await asr.downloadModel(.fluidParakeetMini, updateWeights: true, progressHandler: nil)
+ XCTAssertEqual(provider.prepareCalls, 1)
+ XCTAssertEqual(provider.clearCalls, 0)
+ XCTAssertEqual(settings.selectedSpeechModel, .parakeetTDTv2)
+ XCTAssertNil(asr.activeExclusiveActivity)
+ XCTAssertFalse(asr.hasActiveModelDownload)
+ }
}
diff --git a/Tests/FluidDictationIntegrationTests/ZeppelinDataLayerTests.swift b/Tests/FluidDictationIntegrationTests/ZeppelinDataLayerTests.swift
index e45948e9..6f4dedd1 100644
--- a/Tests/FluidDictationIntegrationTests/ZeppelinDataLayerTests.swift
+++ b/Tests/FluidDictationIntegrationTests/ZeppelinDataLayerTests.swift
@@ -90,6 +90,69 @@ final class ZeppelinDataLayerTests: XCTestCase {
await database.closeAll()
}
+ func testCloseAllAllowsReopeningWithPersistedRows() async throws {
+ let database = FluidZeppelinRoot(root: self.root)
+ let first = try await database.namespace("first", spec: Self.spec)
+ try await self.seed(first, ids: 1...3)
+ await database.closeAll()
+
+ let reopened = try await database.namespace("first", spec: Self.spec)
+ XCTAssertFalse(first === reopened, "Closing releases the cached handle")
+ let count = try await reopened.count().count
+ XCTAssertEqual(count, 3, "A reusable close must preserve indexed rows")
+ await database.closeAll()
+ }
+
+ func testShutdownRejectsCachedAndNewNamespacesWithoutLosingPersistedRows() async throws {
+ let database = FluidZeppelinRoot(root: self.root)
+ let opened = try await database.namespace("first", spec: Self.spec)
+ try await self.seed(opened, ids: 1...3)
+ await database.shutdown()
+
+ for name in ["first", "new-after-shutdown"] {
+ do {
+ _ = try await database.namespace(name, spec: Self.spec)
+ XCTFail("A terminated root must reject \(name)")
+ } catch {
+ XCTAssertTrue(error is CancellationError, "Shutdown must reject opens explicitly")
+ }
+ }
+ XCTAssertEqual(try self.directories(), ["first"], "A rejected open must not create a directory")
+
+ // A fresh instance, as on the next launch, can open the checkpointed data.
+ let relaunched = FluidZeppelinRoot(root: self.root)
+ let count = try await relaunched.namespace("first", spec: Self.spec).count().count
+ XCTAssertEqual(count, 3, "Shutdown must close handles without deleting rows")
+ await relaunched.closeAll()
+ }
+
+ func testShutdownAfterReusableCloseStillRejectsReopening() async throws {
+ let database = FluidZeppelinRoot(root: self.root)
+ _ = try await database.namespace("first", spec: Self.spec)
+ await database.closeAll()
+ await database.shutdown()
+ await database.closeAll()
+
+ do {
+ _ = try await database.namespace("first", spec: Self.spec)
+ XCTFail("A reusable close after shutdown must not restart the root")
+ } catch {
+ XCTAssertTrue(error is CancellationError)
+ }
+ }
+
+ func testShutdownBeforeOpeningCreatesNoIndexFiles() async throws {
+ let database = FluidZeppelinRoot(root: self.root)
+ await database.shutdown()
+ do {
+ _ = try await database.namespace("first", spec: Self.spec)
+ XCTFail("A never-opened terminated root must reject its first namespace")
+ } catch {
+ XCTAssertTrue(error is CancellationError)
+ }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: self.root.path))
+ }
+
// MARK: - Unreadable namespaces are reset
func testACorruptNamespaceIsResetAndReopenedEmpty() async throws {
diff --git a/Tests/HistoryPersistenceBoundaryTests.swift b/Tests/HistoryPersistenceBoundaryTests.swift
index 09fe0b5b..416f27c3 100644
--- a/Tests/HistoryPersistenceBoundaryTests.swift
+++ b/Tests/HistoryPersistenceBoundaryTests.swift
@@ -238,12 +238,30 @@ final class DebugLogger {
return entry
}
precondition(normalizedRestore == backup, "Backup restore must retain stars and metadata while refreshing search revisions")
+ store.selectEntryFromSearch(id: older.id)
+ guard let firstRequest = store.searchSelectionRequest else {
+ preconditionFailure("Selecting a search result must create a request")
+ }
+ store.selectEntryFromSearch(id: older.id)
+ guard let repeatedRequest = store.searchSelectionRequest else {
+ preconditionFailure("Selecting the same result again must create a request")
+ }
+ precondition(firstRequest != repeatedRequest, "Repeated clicks on the same result must create a fresh bounded request")
+ store.consumeSearchSelectionRequest(firstRequest)
+ precondition(store.searchSelectionRequest == repeatedRequest, "A stale consumer must not clear the latest search request")
+ store.consumeSearchSelectionRequest(repeatedRequest)
+ precondition(store.searchSelectionRequest == nil, "The active consumer clears its request")
+ store.selectedEntryID = older.id
+ store.toggleStar(id: older.id)
+ precondition(store.searchSelectionRequest == nil, "Unstar is a local edit, not a sidebar reveal")
store.deleteEntry(id: older.id)
+ precondition(store.selectedEntryID == newer.id, "Deleting the selected row retains the existing store fallback")
+ precondition(store.searchSelectionRequest == nil, "Delete fallback must not reset History filters")
store.toggleStar(id: older.id)
await store.finishPendingWrites()
let afterDelete = try await writer.load()
precondition(afterDelete == restored.filter { $0.id == newer.id }, "A stale star action must not resurrect a deleted entry")
- print("PASS: star filtering/search, chronology, audio preservation, unstar/restart, backup restore and deletion")
+ print("PASS: star filtering/search, chronology, audio preservation, unstar/restart, backup restore, deletion and bounded explicit search requests")
}
@MainActor static func testTodaySummary(root: URL, defaults: UserDefaults, audio: DictationAudioMetadata) async throws {
diff --git a/Tests/HistoryPresentationTests.swift b/Tests/HistoryPresentationTests.swift
index 12bc3a6b..116c007f 100644
--- a/Tests/HistoryPresentationTests.swift
+++ b/Tests/HistoryPresentationTests.swift
@@ -59,6 +59,35 @@ struct HistoryPresentationTests {
aiTokensPerSecond: 746,
audio: audio
)
+ precondition(HistorySelectionRevealPolicy.needsFilterReset(
+ requestedID: enhanced.id, selectedID: enhanced.id, allEntries: [enhanced], visibleEntries: []
+ ), "An empty Starred or text-filter result must still reveal an existing external selection")
+ precondition(!HistorySelectionRevealPolicy.needsFilterReset(
+ requestedID: enhanced.id, selectedID: enhanced.id, allEntries: [enhanced], visibleEntries: [enhanced]
+ ), "Already visible selections must preserve active filters")
+ precondition(!HistorySelectionRevealPolicy.needsFilterReset(
+ requestedID: enhanced.id, selectedID: nil, allEntries: [enhanced], visibleEntries: []
+ ), "An empty selection must preserve filters")
+ let missingID = UUID()
+ precondition(!HistorySelectionRevealPolicy.needsFilterReset(
+ requestedID: missingID, selectedID: missingID, allEntries: [enhanced], visibleEntries: []
+ ), "Missing or deleted selections must preserve filters")
+ precondition(!HistorySelectionRevealPolicy.needsFilterReset(
+ requestedID: nil, selectedID: enhanced.id, allEntries: [enhanced], visibleEntries: []
+ ), "Local deletion fallback, unstar and restore selection must not clear Starred without a search request")
+ precondition(!HistorySelectionRevealPolicy.needsFilterReset(
+ requestedID: missingID, selectedID: enhanced.id, allEntries: [enhanced], visibleEntries: []
+ ), "An older search request cannot override a newer local selection")
+ let viewSource = try String(contentsOfFile: "Sources/Fluid/UI/TranscriptionHistoryView.swift", encoding: .utf8)
+ let parent = viewSource.components(separatedBy: "private var entryListView:").first ?? ""
+ precondition(parent.contains(".onChange(of: self.historyStore.searchSelectionRequest)"), "External selection must be observed outside the conditionally absent list")
+ precondition(!parent.contains(".onChange(of: self.historyStore.selectedEntryID)"), "Local selection must not become an external reveal event")
+ precondition(parent.contains("self.revealExternalSelection()"), "Parent must use the tested policy")
+ precondition(parent.contains("self.audioAvailabilityRevision = UUID()\n self.revealExternalSelection()"), "Initial appearance must reveal the already-selected row")
+ precondition(!parent.contains("filteredEntries.map(\\.id), initial: true"), "Initial filter fallback must not erase an external selection before appearance")
+ let contentSource = try String(contentsOfFile: "Sources/Fluid/ContentView.swift", encoding: .utf8)
+ precondition(contentSource.contains("TranscriptionHistoryStore.shared.selectEntryFromSearch(id: id)"), "Sidebar navigation must produce the explicit request before opening History")
+ print("PASS: hidden/empty external reveal, visible/nil/deleted/local/stale non-effects and explicit parent/appearance wiring")
let before = enhanced
precondition(enhanced.clipboardText == "final words")
precondition(enhanced == before, "Reading copy text must not mutate an entry")
diff --git a/Tests/run_dictionary_training_save_tests.py b/Tests/run_dictionary_training_save_tests.py
index fb40929f..c5c38d3e 100644
--- a/Tests/run_dictionary_training_save_tests.py
+++ b/Tests/run_dictionary_training_save_tests.py
@@ -19,6 +19,9 @@ os.environ["DEVELOPER_DIR"] = developer_dir
source = (repo / 'Sources/Fluid/UI/CustomDictionaryView.swift').read_text()
method = source[source.index(' private func addTrainedReplacement() async {'):source.index(' private func removeTrainingVariant(')].replace('private func addTrainedReplacement', 'func addTrainedReplacement')
+progress = source[source.index('struct DictionaryTrainingProgress {'):source.index('enum CustomDictionaryTrainingMerge {')]
+readiness = source[source.index(' private var trainingProgress:'):source.index(' private var trainingAlreadyCorrectWithoutReplacement:')]
+can_save = source[source.index(' private var canAddTrainedReplacement:'):source.index(' private var shouldPulseTrainedReplacementButton:')]
merge = source[source.index('enum CustomDictionaryTrainingMerge {'):source.index('private struct ReplacementConfirmation:')]
settings = (repo / 'Sources/Fluid/Persistence/SettingsStore.swift').read_text()
entry_start = settings.rfind('\n', 0, settings.index('struct CustomDictionaryEntry:')) + 1
@@ -36,8 +39,16 @@ enum DictionaryMatcherExperiment {
static var generation = UUID()
}
struct VoiceTrainingAliasFilter {
- struct Result { let accepted: [String]; let rejected: [String] = []; let lookupAvailable = true }
- static func filter(_ values: [String]) async -> Result { Result(accepted: values) }
+ struct Result {
+ let accepted: [String]
+ let rejected: [String] = []
+ let lookupAvailable: Bool
+ init(accepted: [String], lookupAvailable: Bool = true) {
+ self.accepted = accepted; self.lookupAvailable = lookupAvailable
+ }
+ }
+ static var response: Result?
+ static func filter(_ values: [String]) async -> Result { response ?? Result(accepted: values) }
}
final class DebugLogger {
static let shared = DebugLogger()
@@ -56,10 +67,12 @@ actor PronunciationDictionaryStore {
var lateGate: Gate?
var forceFailure = false
var writes: [UUID] = []
+ var calls = 0
func configure(gate: Gate?, lateGate: Gate? = nil, failure: Bool = false) {
- self.gate = gate; self.lateGate = lateGate; forceFailure = failure; writes = []
+ self.gate = gate; self.lateGate = lateGate; forceFailure = failure; writes = []; calls = 0
}
func upsert(dictionaryEntryID: UUID, label: String, modelKey: String, enrollments: [PronunciationEnrollmentCapture], automaticMatchingEnabled: Bool, canPersist: @Sendable () -> Bool) async throws {
+ calls += 1
guard canPersist() else { throw CancellationError() }
if let gate { await gate.pause() }
guard canPersist(), !forceFailure else { throw CancellationError() }
@@ -67,13 +80,17 @@ actor PronunciationDictionaryStore {
if let lateGate { await lateGate.pause() }
}
}
+PROGRESS
MERGE
@MainActor final class SaveHarness {
- var canAddTrainedReplacement = true
+ READINESS
+ CAN_SAVE
+ var trainingSampleCount = 3
+ var isTrainingRecording = false
var isTrainingProcessing = false
var trainingSaveID: UUID?
var normalizedTrainingReplacement = "FluidVoice"
- var trainingPronunciationEnrollments = [PronunciationEnrollmentCapture()]
+ var trainingPronunciationEnrollments = Array(repeating: PronunciationEnrollmentCapture(), count: 3)
var activePronunciationMatching = true
var trainingVariants = ["fluid boys"]
var pronunciationEnabled = true
@@ -102,9 +119,16 @@ func check(_ condition: @autoclosure () -> Bool, _ message: String) {
SettingsStore.shared.customDictionaryEntries = entries
DictionaryMatcherExperiment.sharedFeaturesEnabled = true
DictionaryMatcherExperiment.generation = UUID()
+ VoiceTrainingAliasFilter.response = nil
return SaveHarness()
}
- func waitForGate(_ gate: Gate) async { while !(await gate.entered) { await Task.yield() } }
+ func waitForGate(_ gate: Gate) async throws {
+ let deadline = ContinuousClock.now + .seconds(3)
+ while !(await gate.entered) {
+ check(ContinuousClock.now < deadline, "Save did not reach its expected persistence boundary within 3 seconds")
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ }
// Production save and merge retain existing profile UUID and save new entries under the written UUID.
for existing in [true, false] {
let original = existing ? baseline() : []
@@ -125,7 +149,7 @@ func check(_ condition: @autoclosure () -> Bool, _ message: String) {
let gate = Gate()
await PronunciationDictionaryStore.shared.configure(gate: gate)
let save = Task { await view.addTrainedReplacement() }
- await waitForGate(gate)
+ try await waitForGate(gate)
var latest = original
switch mutation {
case 0: latest.append(Entry(triggers: ["new"], replacement: "New"))
@@ -154,7 +178,7 @@ func check(_ condition: @autoclosure () -> Bool, _ message: String) {
let lateGate = Gate()
await PronunciationDictionaryStore.shared.configure(gate: nil, lateGate: lateGate)
let save = Task { await view.addTrainedReplacement() }
- await waitForGate(lateGate)
+ try await waitForGate(lateGate)
let latest = [original[1]]
SettingsStore.shared.customDictionaryEntries = latest
await lateGate.release(); await save.value
@@ -168,7 +192,7 @@ func check(_ condition: @autoclosure () -> Bool, _ message: String) {
let gate = Gate()
await PronunciationDictionaryStore.shared.configure(gate: gate, failure: true)
let save = Task { await view.addTrainedReplacement() }
- await waitForGate(gate)
+ try await waitForGate(gate)
let newSaveID = UUID()
view.trainingSaveID = newSaveID
view.trainingStatusMessage = "new save"
@@ -199,10 +223,105 @@ func check(_ condition: @autoclosure () -> Bool, _ message: String) {
check(await PronunciationDictionaryStore.shared.writes.isEmpty, "Text-only training must not write profiles")
passes += 1
}
- print("PASS \(passes) dictionary save scenarios using the production save method and merge code")
+ // Three spelling examples may save even when voice enrollment is incomplete.
+ // The actual readiness calculation must keep zero, one and two voice examples
+ // out of profile persistence, even with pronunciation learning enabled.
+ for count in 0..<3 {
+ let original = baseline()
+ let view = reset(original)
+ view.trainingPronunciationEnrollments = Array(repeating: PronunciationEnrollmentCapture(), count: count)
+ await PronunciationDictionaryStore.shared.configure(gate: nil, failure: true)
+ await view.addTrainedReplacement()
+ let calls = await PronunciationDictionaryStore.shared.calls
+ let profiles = await PronunciationDictionaryStore.shared.writes
+ check(view.writes == 1 && view.wizardStep == .saved, "Incomplete voice enrollment must not block spelling-only save")
+ check(calls == 0 && profiles.isEmpty, "Incomplete voice examples must never enter profile persistence")
+ check(SettingsStore.shared.customDictionaryEntries.first?.id == original.first?.id, "Spelling fallback retains the existing entry identity")
+ check(SettingsStore.shared.customDictionaryEntries.last == original.last, "Spelling fallback preserves unrelated rules")
+ check(!view.trainingHasError && !view.isTrainingProcessing && view.trainingSaveID == nil, "Spelling fallback finishes cleanly")
+ passes += 1
+ }
+ // Filtering cannot create a text rule when no safe aliases and no ready voice exist.
+ for available in [true, false] {
+ let original = baseline()
+ let view = reset(original)
+ view.trainingPronunciationEnrollments = []
+ VoiceTrainingAliasFilter.response = .init(accepted: [], lookupAvailable: available)
+ await PronunciationDictionaryStore.shared.configure(gate: nil)
+ await view.addTrainedReplacement()
+ let calls = await PronunciationDictionaryStore.shared.calls
+ check(view.writes == 0 && calls == 0, "Rejected aliases must not write text rules or profiles")
+ check(SettingsStore.shared.customDictionaryEntries == original, "Rejected aliases preserve the dictionary")
+ check(view.trainingHasError && view.wizardStep == .recording, "Rejected or unavailable aliases leave a visible retry")
+ check(view.trainingStatusMessage.contains(available ? "everyday words" : "Couldn't check"), "Alias failure explains its actual cause")
+ check(!view.trainingVariants.isEmpty && !view.isTrainingProcessing && view.trainingSaveID == nil, "Alias failure retains recordings and releases busy state")
+ passes += 1
+ }
+ // Insufficient spellings use the production save gate, even with enough voice examples.
+ do {
+ let original = baseline()
+ let view = reset(original)
+ view.trainingSampleCount = 2
+ await PronunciationDictionaryStore.shared.configure(gate: nil)
+ await view.addTrainedReplacement()
+ let calls = await PronunciationDictionaryStore.shared.calls
+ check(calls == 0 && view.writes == 0 && SettingsStore.shared.customDictionaryEntries == original, "Incomplete spellings must not save")
+ check(!view.isTrainingProcessing && view.trainingSaveID == nil && view.wizardStep == .recording, "Rejected save must not advance the wizard or leave it busy")
+ passes += 1
+ }
+ // A new feature generation while the store is suspended rejects old enrollment.
+ do {
+ let original = baseline()
+ let view = reset(original)
+ let gate = Gate()
+ await PronunciationDictionaryStore.shared.configure(gate: gate)
+ let save = Task { await view.addTrainedReplacement() }
+ try await waitForGate(gate)
+ DictionaryMatcherExperiment.generation = UUID()
+ await gate.release(); await save.value
+ let profiles = await PronunciationDictionaryStore.shared.writes
+ check(profiles.isEmpty && view.writes == 0 && SettingsStore.shared.customDictionaryEntries == original, "Stale pronunciation generation must not persist")
+ check(view.trainingHasError && !view.trainingPronunciationEnrollments.isEmpty, "Generation refusal is retryable and retains captured examples")
+ check(!view.isTrainingProcessing && view.trainingSaveID == nil, "Generation refusal must release busy state")
+ passes += 1
+ }
+ // A completion from an older save must not clear or advance a newer save.
+ do {
+ let original = baseline()
+ let view = reset(original)
+ let lateGate = Gate()
+ await PronunciationDictionaryStore.shared.configure(gate: nil, lateGate: lateGate)
+ let save = Task { await view.addTrainedReplacement() }
+ try await waitForGate(lateGate)
+ let newerID = UUID()
+ view.trainingSaveID = newerID
+ view.trainingStatusMessage = "New save is running"
+ await lateGate.release(); await save.value
+ check(view.writes == 0 && SettingsStore.shared.customDictionaryEntries == original, "Stale success must not publish text rules")
+ check(view.trainingSaveID == newerID && view.isTrainingProcessing, "Stale success must not release the newer save")
+ check(view.trainingStatusMessage == "New save is running" && view.wizardStep == .recording && !view.trainingHasError, "Stale success must preserve newer UI state")
+ passes += 1
+ }
+ // Cancellation after profile completion suppresses dictionary publication and wizard success.
+ // This deliberately does not claim cancellation rolls back an already completed profile write.
+ do {
+ let original = baseline()
+ let view = reset(original)
+ let lateGate = Gate()
+ await PronunciationDictionaryStore.shared.configure(gate: nil, lateGate: lateGate)
+ let save = Task { await view.addTrainedReplacement() }
+ try await waitForGate(lateGate)
+ save.cancel()
+ await lateGate.release(); await save.value
+ check(view.writes == 0 && SettingsStore.shared.customDictionaryEntries == original, "Cancelled save must not publish dictionary changes")
+ check(!view.isTrainingProcessing && view.trainingSaveID == nil && view.wizardStep == .recording && !view.trainingHasError, "Cancelled completion must leave no success, error or busy state")
+ check(!view.trainingPronunciationEnrollments.isEmpty, "Cancelled save retains captures for retry")
+ passes += 1
+ }
+ print("PASS \(passes) dictionary save scenarios using the production save method, readiness and merge code")
}
}
-'''.replace('ENTRY', entry).replace('MERGE', merge).replace('METHOD', method)
+'''.replace('ENTRY', entry).replace('PROGRESS', progress).replace('MERGE', merge).replace('READINESS', readiness).replace('CAN_SAVE', can_save).replace('METHOD', method)
swift = swift.replace('check(await PronunciationDictionaryStore.shared.writes.isEmpty,', 'let textOnlyWrites = await PronunciationDictionaryStore.shared.writes\n check(textOnlyWrites.isEmpty,')
isolation_swift = r'''
import Foundation
@@ -229,12 +348,12 @@ actor SnapshotReader {
with tempfile.TemporaryDirectory(prefix="fluidvoice-dictionary-regression-") as directory:
root = Path(directory)
(root / 'dictionary-proof.swift').write_text(swift)
- subprocess.run(['xcrun', 'swiftc', '-parse-as-library', str(root/'dictionary-proof.swift'), '-o', str(root/'dictionary-proof')], check=True)
- subprocess.run([str(root/'dictionary-proof')], check=True)
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', str(root/'dictionary-proof.swift'), '-o', str(root/'dictionary-proof')], check=True, timeout=60)
+ subprocess.run([str(root/'dictionary-proof')], check=True, timeout=60)
(root / 'dictionary-isolation.swift').write_text(isolation_swift)
subprocess.run([
'xcrun', 'swiftc', '-parse-as-library', '-swift-version', '6',
'-default-isolation', 'MainActor', '-strict-concurrency=complete', '-warnings-as-errors',
str(root/'dictionary-isolation.swift'), '-o', str(root/'dictionary-isolation'),
- ], check=True)
- subprocess.run([str(root/'dictionary-isolation')], check=True)
+ ], check=True, timeout=60)
+ subprocess.run([str(root/'dictionary-isolation')], check=True, timeout=60)
diff --git a/Tests/run_meeting_backup_refresh_tests.py b/Tests/run_meeting_backup_refresh_tests.py
new file mode 100644
index 00000000..e1d0f479
--- /dev/null
+++ b/Tests/run_meeting_backup_refresh_tests.py
@@ -0,0 +1,213 @@
+#!/usr/bin/env python3
+"""Exercise the production meeting backup handlers without hardware or app defaults."""
+import argparse
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[1]
+SOURCE = ROOT / "Sources/Fluid/UI/MeetingTranscriptionView.swift"
+
+
+def declaration(source: str, marker: str) -> str:
+ start = source.index(marker)
+ brace = source.index("{", start)
+ depth = 1
+ end = brace + 1
+ while depth:
+ depth += (source[end] == "{") - (source[end] == "}")
+ end += 1
+ return source[start:end]
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--baseline-ref", help="Optional pre-fix git ref for reproduction checks")
+ args = parser.parse_args()
+ developer_dir = os.environ.get("DEVELOPER_DIR") or subprocess.check_output(
+ ["xcode-select", "-p"], text=True, timeout=10
+ ).strip()
+ if not ("Xcode" in developer_dir and developer_dir.endswith(".app/Contents/Developer")):
+ raise SystemExit("Set DEVELOPER_DIR to a full installed Xcode before running tests.")
+ env = {**os.environ, "DEVELOPER_DIR": developer_dir}
+ source = SOURCE.read_text()
+ baseline = None
+ if args.baseline_ref:
+ baseline = subprocess.check_output(
+ ["git", "show", f"{args.baseline_ref}:Sources/Fluid/UI/MeetingTranscriptionView.swift"],
+ cwd=ROOT, text=True, timeout=10,
+ )
+ assert "settingsBackupDidRestore" not in baseline
+ assert "self.appDetailContent\n" in (ROOT / "Sources/Fluid/ContentView.swift").read_text()
+ assert ".onReceive(NotificationCenter.default.publisher(for: .settingsBackupDidRestore))" in source
+ assert ".onChange(of: self.canRefreshSetupAfterBackupRestore)" in source
+ mode_observer = declaration(source, ".onChange(of: self.setupDraft.mode)")
+ assert "Task { await self.refreshSources(requestPermissions: false) }" in mode_observer
+ for action in ("cancelMeetingSettings", "saveMeetingSettings"):
+ body = declaration(source, f"private func {action}()")
+ assert body.split("{", 1)[1].strip().startswith(
+ "if self.finishRestoredMeetingSettingsIfPending() { return }"
+ ), f"{action} must reject stale sheet writes before validation or source refresh"
+
+ draft = declaration(source, "struct MeetingTranscriptionSetupDraft:")
+ if baseline is not None:
+ assert draft == declaration(baseline, "struct MeetingTranscriptionSetupDraft:")
+ members = "\n".join(declaration(source, marker) for marker in (
+ "private var canRefreshSetupAfterBackupRestore:",
+ "private func applyPendingBackupSetupRefresh()",
+ "private func finishRestoredMeetingSettingsIfPending()",
+ ))
+ swift = r'''
+import Foundation
+
+enum MeetingCaptureMode { case onlineCall, inRoom }
+struct Defaults { var languageCode: String? = "en"; var mode: MeetingCaptureMode = .onlineCall }
+final class SettingsStore {
+ static let shared = SettingsStore()
+ var meetingRecordingDefaults = Defaults()
+ var meetingAutoDetectEnabled = true
+ var meetingAutoDetectBrowserEnabled = true
+ var meetingAudioRetentionPolicy = 7
+}
+struct Identity { let id: String }
+struct Option { let identity: Identity }
+final class Coordinator { var isQuiescent = true; var activeLanguage = "en" }
+''' + draft + r'''
+final class Harness {
+ let coordinator = Coordinator()
+ var setupDraft = MeetingTranscriptionSetupDraft()
+ var setupDraftBeforeEditing = MeetingTranscriptionSetupDraft()
+ var pendingBackupSetupRefresh = false
+ var cachedSystemDefaultMicrophoneUID: String? = "cached-mic"
+ var isStarting = false, isStopping = false, isRetrying = false
+ var isRefreshingSources = false, isShowingMeetingSettings = false
+ var microphones = [Option(identity: Identity(id: "cached-mic"))]
+ var applications = [Option(identity: Identity(id: "cached-app"))]
+ var draftMeetingAudioRetentionPolicy = 7
+ var selectedIdentities = 0
+ var persistedWrites = 0
+ var hardwareQueries = 0
+ func selectPreferredMicrophone(from identities: [Identity], systemDefaultUID: String?) {
+ selectedIdentities += 1
+ setupDraft.selectedMicrophoneID = identities.first(where: { $0.id == systemDefaultUID })?.id
+ }
+ func selectPreferredApplication(from identities: [Identity]) {
+ selectedIdentities += 1
+ setupDraft.selectedApplicationID = identities.first?.id
+ }
+ func regenerateDefaultTitleIfNeeded() {
+ if !setupDraft.titleWasEdited {
+ setupDraft.title = MeetingTranscriptionSetupDraft.defaultTitle(mode: setupDraft.mode, applicationDisplayName: nil)
+ }
+ }
+''' + members + r'''
+ func notifyRestore() { pendingBackupSetupRefresh = true; applyPendingBackupSetupRefresh() }
+ func reachSafePoint() { if canRefreshSetupAfterBackupRestore { applyPendingBackupSetupRefresh() } }
+ func closeSheetSaving() {
+ if finishRestoredMeetingSettingsIfPending() { return }
+ persistedWrites += 1
+ }
+ func closeSheetCancelling() {
+ if finishRestoredMeetingSettingsIfPending() { return }
+ hardwareQueries += 1
+ }
+ func expect(_ ok: Bool, _ message: String) { check(ok, message) }
+}
+var assertions = 0
+func check(_ ok: Bool, _ message: String) {
+ assertions += 1
+ if !ok { fatalError(message) }
+}
+func restored(_ language: String = "fr", _ mode: MeetingCaptureMode = .inRoom) {
+ SettingsStore.shared.meetingRecordingDefaults = Defaults(languageCode: language, mode: mode)
+}
+func fresh() -> Harness {
+ restored("en", .onlineCall)
+ SettingsStore.shared.meetingAutoDetectEnabled = true
+ SettingsStore.shared.meetingAutoDetectBrowserEnabled = true
+ SettingsStore.shared.meetingAudioRetentionPolicy = 7
+ return Harness()
+}
+@main enum Tests {
+ static func main() {
+ // Reproduce pre-fix: real production draft is a value snapshot, not a settings binding.
+ let baseline = fresh()
+ restored()
+ check(baseline.setupDraft.languageCode == "en" && baseline.setupDraft.mode == .onlineCall,
+ "baseline hidden page keeps stale language/mode after defaults import")
+ print("PASS: setup draft is a snapshot; restore notification must refresh it")
+ baseline.notifyRestore()
+ check(baseline.setupDraft.languageCode == "fr" && baseline.setupDraft.mode == .inRoom, "idle restore refreshes language/mode")
+ check(baseline.setupDraftBeforeEditing == baseline.setupDraft, "cancel snapshot follows restored setup")
+ check(baseline.hardwareQueries == 0 && baseline.persistedWrites == 0, "restore handler performs neither synchronous source queries nor persistence")
+ check(baseline.setupDraft.selectedMicrophoneID == "cached-mic" && baseline.setupDraft.selectedApplicationID == "cached-app", "cached identities populate restored setup")
+ check(baseline.coordinator.activeLanguage == "en", "active capture configuration is never rewritten")
+
+ for blocker in 0..<6 {
+ let h = fresh()
+ switch blocker {
+ case 0: h.coordinator.isQuiescent = false
+ case 1: h.isStarting = true
+ case 2: h.isStopping = true
+ case 3: h.isRetrying = true
+ case 4: h.isRefreshingSources = true
+ default: h.isShowingMeetingSettings = true
+ }
+ h.setupDraft.title = "User's meeting"; h.setupDraft.titleWasEdited = true
+ restored(); h.notifyRestore()
+ check(h.pendingBackupSetupRefresh && h.setupDraft.languageCode == "en", "busy/editing restore defers \(blocker)")
+ check(h.selectedIdentities == 0 && h.persistedWrites == 0, "deferral has no effects \(blocker)")
+ restored("de", .onlineCall); h.notifyRestore()
+ check(h.setupDraft.title == "User's meeting", "repeated restore preserves active edited input \(blocker)")
+ h.coordinator.isQuiescent = true; h.isStarting = false; h.isStopping = false
+ h.isRetrying = false; h.isRefreshingSources = false; h.isShowingMeetingSettings = false
+ h.reachSafePoint()
+ check(!h.pendingBackupSetupRefresh && h.setupDraft.languageCode == "de", "success/failure/close uses latest coalesced restore \(blocker)")
+ check(h.setupDraft.title == "User's meeting" && h.setupDraft.titleWasEdited, "custom title survives refresh \(blocker)")
+ let identityCount = h.selectedIdentities
+ h.reachSafePoint()
+ check(h.selectedIdentities == identityCount, "safe-point events do not replay completed restore \(blocker)")
+ }
+ for save in [false, true] {
+ let h = fresh(); h.isShowingMeetingSettings = true
+ restored(); h.notifyRestore()
+ if save { h.closeSheetSaving() } else { h.closeSheetCancelling() }
+ check(!h.isShowingMeetingSettings && h.setupDraft.languageCode == "fr", "sheet close consumes deferred restore")
+ check(h.persistedWrites == 0 && h.hardwareQueries == 0, "stale Save/Cancel cannot overwrite imported preferences or query sources")
+ }
+ let busySheet = fresh(); busySheet.isShowingMeetingSettings = true; busySheet.coordinator.isQuiescent = false
+ restored(); busySheet.notifyRestore(); busySheet.closeSheetSaving()
+ check(busySheet.pendingBackupSetupRefresh && busySheet.setupDraft.languageCode == "en", "closing edited sheet does not change busy capture setup")
+ busySheet.coordinator.isQuiescent = true; busySheet.reachSafePoint()
+ check(busySheet.setupDraft.languageCode == "fr" && busySheet.persistedWrites == 0, "capture failure/completion later applies pending sheet restore without writes")
+
+ let rapid = fresh()
+ restored(); rapid.notifyRestore()
+ restored("de", .onlineCall); rapid.notifyRestore()
+ check(rapid.setupDraft.languageCode == "de" && rapid.setupDraft.mode == .onlineCall, "rapid change-back restore keeps latest values")
+ restored("fr", .inRoom); rapid.notifyRestore(); restored("de", .inRoom); rapid.notifyRestore()
+ check(rapid.setupDraft.languageCode == "de" && !rapid.pendingBackupSetupRefresh, "same-mode repeated restores consume latest language without stale pending state")
+ let legacy = fresh(); SettingsStore.shared.meetingRecordingDefaults.languageCode = nil
+ legacy.notifyRestore()
+ check(legacy.setupDraft.languageCode == "en" && legacy.hardwareQueries == 0, "legacy language defaults to English without source discovery")
+ let missing = fresh(); missing.microphones = []; missing.applications = []
+ restored(); missing.notifyRestore()
+ check(missing.setupDraft.selectedMicrophoneID == nil && missing.setupDraft.selectedApplicationID == nil, "missing cached sources stay unselected")
+ check(missing.hardwareQueries == 0 && !missing.pendingBackupSetupRefresh, "missing sources do not create a permanent pending restore")
+ print("PASS: \(assertions) production-handler assertions")
+ }
+}
+'''
+ with tempfile.TemporaryDirectory(prefix="fluidvoice-meeting-backup-") as directory:
+ directory = Path(directory)
+ swift_file = directory / "Tests.swift"
+ swift_file.write_text(swift)
+ executable = directory / "tests"
+ subprocess.run(["xcrun", "swiftc", "-parse-as-library", str(swift_file), "-o", str(executable)],
+ env=env, check=True, timeout=60)
+ subprocess.run([str(executable)], env=env, check=True, timeout=15)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Tests/run_settings_backup_concurrency_tests.py b/Tests/run_settings_backup_concurrency_tests.py
new file mode 100644
index 00000000..b263ddeb
--- /dev/null
+++ b/Tests/run_settings_backup_concurrency_tests.py
@@ -0,0 +1,562 @@
+#!/usr/bin/env python3
+"""Test source-extracted backup methods with bounded real-actor dependency probes.
+
+No production defaults, disk stores, UI, hardware, or network are used.
+--ref REF --expect-overlap-gap reproduces a historical overlapping snapshot gap.
+Normal execution needs only the current source, including its single-flight gate.
+"""
+
+import argparse
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+
+
+def declaration(source: str, marker: str) -> str:
+ start = source.index(marker)
+ brace = source.index("{", start)
+ depth, end = 1, brace + 1
+ while depth:
+ depth += (source[end] == "{") - (source[end] == "}")
+ end += 1
+ return source[start:end]
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--ref")
+ probes = parser.add_mutually_exclusive_group()
+ probes.add_argument("--expect-overlap-gap", action="store_true")
+ probes.add_argument("--expect-active-work-gap", action="store_true")
+ args = parser.parse_args()
+ repo = Path(__file__).resolve().parent.parent
+ selected = subprocess.check_output(["xcode-select", "-p"], text=True, timeout=10).strip()
+ developer_dir = os.environ.get("DEVELOPER_DIR", selected)
+ if not (Path(developer_dir) / "Platforms/MacOSX.platform").is_dir():
+ raise SystemExit("Set DEVELOPER_DIR to a full installed Xcode before running this test.")
+ environment = dict(os.environ, DEVELOPER_DIR=developer_dir)
+ source_path = "Sources/Fluid/Persistence/BackupService.swift"
+ source = (
+ subprocess.check_output(["git", "show", f"{args.ref}:{source_path}"], cwd=repo, text=True, timeout=10)
+ if args.ref else (repo / source_path).read_text()
+ )
+ members = "\n".join(declaration(source, marker) for marker in (
+ " func makeBackupDocument() async throws -> AppBackupDocument",
+ " func restore(_ document: AppBackupDocument) async throws",
+ " private func validate(_ document: AppBackupDocument)",
+ ))
+ if "private var operationInProgress" in source:
+ # Extract the actual gate storage and admission method, never a mirrored gate.
+ gate_line = next(line for line in source.splitlines() if "private var operationInProgress" in line)
+ members = gate_line + "\n" + declaration(source, " private func beginOperation()") + "\n" + members
+ errors = declaration(source, "enum BackupServiceError:")
+ schema = declaration(source, "struct BackupFileVersion:")
+ asr_source = (repo / "Sources/Fluid/Services/ASRService.swift").read_text()
+ asr_admission = declaration(asr_source, " func beginSettingsBackupRestore()")
+ asr_activity = declaration(asr_source, "enum ASRExclusiveActivity:")
+ asr_error = declaration(asr_source, "enum ASRActivityError:")
+ asr_release = declaration(asr_source, " func releaseExclusiveActivity(")
+ asr_restore = declaration(asr_source, " func handleSettingsBackupDidRestore()")
+ swift = r'''
+import Foundation
+SCHEMA
+ERRORS
+struct Payload: Codable {
+ var owner: String
+ var privateAIIdleUnload: Int?
+ var meetingLanguage: String? = nil
+ var promptConfigurations: [String: String]? = nil
+}
+struct AppBackupDocument {
+ var schemaVersion: BackupFileVersion = .current
+ var appVersion = "fixture"
+ var exportedAt = Date()
+ var settings: Payload
+ var promptProfiles: [String] = []
+ var appPromptBindings: [String] = []
+ var transcriptionHistory: [String] = []
+ var pronunciationProfiles: [String]?
+}
+@MainActor final class SettingsStore {
+ static let shared = SettingsStore()
+ var owner = "original"
+ var privateAIIdleUnload = 30
+ var meetingLanguage = "en"
+ var configurations = ["__default__": "original"]
+ var dictationPromptProfiles: [String] = []
+ var appPromptBindings: [String] = []
+ func makeBackupPayload() -> Payload {
+ .init(owner: owner, privateAIIdleUnload: privateAIIdleUnload,
+ meetingLanguage: meetingLanguage, promptConfigurations: configurations)
+ }
+ func restore(from payload: Payload, promptProfiles: [String], appPromptBindings: [String]) {
+ owner = payload.owner
+ if let idle = payload.privateAIIdleUnload { privateAIIdleUnload = idle }
+ if let language = payload.meetingLanguage { meetingLanguage = language }
+ if let configurations = payload.promptConfigurations { self.configurations = configurations }
+ dictationPromptProfiles = promptProfiles
+ self.appPromptBindings = appPromptBindings
+ }
+}
+actor Gate {
+ var entered = false
+ var continuation: CheckedContinuation<Void, Never>?
+ func pause() async { entered = true; await withCheckedContinuation { continuation = $0 } }
+ func release() { continuation?.resume(); continuation = nil }
+}
+enum ProbeFailure: Error { case storage }
+actor PronunciationDictionaryStore {
+ static let shared = PronunciationDictionaryStore()
+ var profiles = ["original"]
+ var reject = false
+ var exportGate: Gate?
+ var restoreGate: Gate?
+ var snapshots = 0, replacements = 0
+ func setup(reject: Bool = false, exportGate: Gate? = nil, restoreGate: Gate? = nil) {
+ profiles = ["original"]; self.reject = reject
+ self.exportGate = exportGate; self.restoreGate = restoreGate
+ snapshots = 0; replacements = 0
+ }
+ func allProfiles() async -> [String] {
+ snapshots += 1
+ let snapshot = profiles
+ if let gate = exportGate { exportGate = nil; await gate.pause() }
+ return snapshot
+ }
+ func replaceAllProfiles(_ profiles: [String]) async throws {
+ replacements += 1
+ if let gate = restoreGate { restoreGate = nil; await gate.pause() }
+ if reject { throw ProbeFailure.storage }
+ self.profiles = profiles
+ }
+ func ordinaryEdit(_ profiles: [String]) { self.profiles = profiles }
+ func state() -> ([String], Int, Int) { (profiles, snapshots, replacements) }
+}
+@MainActor final class TranscriptionHistoryStore {
+ static let shared = TranscriptionHistoryStore()
+ var history = ["original"]
+ var loaded = true
+ var loadGate: Gate?
+ var loads = 0, writes = 0
+ func waitUntilLoaded() async throws {
+ loads += 1
+ if let gate = loadGate { loadGate = nil; await gate.pause() }
+ if !loaded { throw ProbeFailure.storage }
+ }
+ func makeBackupPayload() -> [String] { history }
+ func restore(from payload: [String]) { writes += 1; history = payload }
+}
+actor IdleDouble {
+ var gate: Gate?
+ var calls = 0
+ var observations: [Int] = []
+ func setup(gate: Gate? = nil) { self.gate = gate; calls = 0; observations = [] }
+ func settingsChanged() async {
+ calls += 1
+ if let gate { self.gate = nil; await gate.pause() }
+ observations.append(await SettingsStore.shared.privateAIIdleUnload)
+ }
+ func state() -> (Int, [Int]) { (calls, observations) }
+}
+enum PrivateAIIntegrationService { static let idleUnloader = IdleDouble() }
+@MainActor final class NotificationCenter {
+ static let `default` = NotificationCenter()
+ var snapshots: [(String, [String])] = []
+ var onPost: (() -> Void)?
+ enum Name { case settingsBackupDidRestore }
+ func post(name: Name, object: Any?) {
+ snapshots.append((SettingsStore.shared.owner, TranscriptionHistoryStore.shared.history))
+ onPost?()
+ }
+}
+ASR_ACTIVITY
+ASR_ERROR
+struct ASRActivityLease: Equatable { let id: UUID; let activity: ASRExclusiveActivity }
+@MainActor final class HandoffProbe { var isRecovering = false }
+@MainActor final class ResidencyProbe { var isExclusive = false }
+@MainActor final class ASRService {
+ var isTerminating = false
+ var activeActivityLease: ASRActivityLease?
+ var activeExclusiveActivity: ASRExclusiveActivity?
+ var isRunning = false, isStarting = false, isStoppingFinalTranscription = false
+ let recordingBufferHandoffGate = HandoffProbe()
+ var isMicrophonePreviewRequested = false, isMicrophonePreviewActive = false
+ var hasActiveModelDownload = false, hasActiveModelPreparation = false
+ var deletingModelID: String?, providerResetDrain: UUID?
+ var isCancellingModelPreparation = false, isCancellingModelDownload = false
+ let meetingModelResidency = ResidencyProbe()
+ var isAsrReady = true, isDownloadingModel = false, isLoadingModel = false
+ var admissions = 0
+ var releases: Int { DictionaryAudioLearningService.shared.activityEnds }
+ var providerResetPending = false
+ var deferredMeetingActivityLeaseRelease: ASRActivityLease?
+ var completedResets = 0, recoveryRequests = 0
+ ASR_ADMISSION
+ func acquireExclusiveActivity(_ activity: ASRExclusiveActivity) throws -> ASRActivityLease {
+ guard activeActivityLease == nil else { throw ASRActivityError.activityInProgress(activeExclusiveActivity!) }
+ let lease = ASRActivityLease(id: UUID(), activity: activity)
+ activeActivityLease = lease; activeExclusiveActivity = activity; admissions += 1; return lease
+ }
+ ASR_RELEASE
+ ASR_RESTORE
+ func isMeetingASRClaimBlocking(lease: ASRActivityLease) -> Bool { false }
+ func resetTranscriptionProvider() {
+ if activeActivityLease != nil { providerResetPending = true; return }
+ isAsrReady = false; completedResets += 1
+ }
+ func scheduleAudioRouteRecovery(reason: String, requiresIdlePrewarm: Bool, reconcilesInputSelection: Bool) {
+ recoveryRequests += 1
+ }
+}
+@MainActor final class DictionaryAudioLearningService {
+ static let shared = DictionaryAudioLearningService()
+ var activityEnds = 0
+ func activityDidEnd() { activityEnds += 1 }
+}
+@MainActor final class SpeechModelInstallationSnapshot {
+ static let shared = SpeechModelInstallationSnapshot()
+ func refresh() {}
+}
+@MainActor final class AppServices {
+ static let shared = AppServices()
+ var asr = ASRService()
+}
+@MainActor final class BackupService {
+MEMBERS
+}
+@MainActor var assertions = 0
+@MainActor func expect(_ condition: Bool, _ message: String) {
+ assertions += 1
+ if !condition { fatalError("FAIL: " + message) }
+}
+@MainActor func busy(_ work: () async throws -> Void) async {
+ do { try await work(); fatalError("Expected busy rejection") }
+ catch BackupServiceError.operationInProgress {
+ expect(BackupServiceError.operationInProgress.localizedDescription.contains("already running"), "busy error tells user to retry")
+ } catch { fatalError("Wrong busy error: \(error)") }
+}
+@MainActor func reset(idleGate: Gate? = nil, exportGate: Gate? = nil, restoreGate: Gate? = nil) async {
+ AppServices.shared.asr = ASRService()
+ DictionaryAudioLearningService.shared.activityEnds = 0
+ SettingsStore.shared.owner = "original"
+ SettingsStore.shared.privateAIIdleUnload = 30
+ SettingsStore.shared.meetingLanguage = "en"
+ SettingsStore.shared.configurations = ["__default__": "original"]
+ SettingsStore.shared.dictationPromptProfiles = []
+ SettingsStore.shared.appPromptBindings = []
+ TranscriptionHistoryStore.shared.history = ["original"]
+ TranscriptionHistoryStore.shared.loaded = true
+ TranscriptionHistoryStore.shared.loads = 0; TranscriptionHistoryStore.shared.writes = 0
+ TranscriptionHistoryStore.shared.loadGate = nil
+ NotificationCenter.default.snapshots = []; NotificationCenter.default.onPost = nil
+ await PronunciationDictionaryStore.shared.setup(exportGate: exportGate, restoreGate: restoreGate)
+ await PrivateAIIntegrationService.idleUnloader.setup(gate: idleGate)
+}
+func awaitGate(_ gate: Gate) async {
+ let deadline = ContinuousClock.now + .seconds(3)
+ while !(await gate.entered) {
+ if ContinuousClock.now > deadline { fatalError("Timed out waiting for actor gate") }
+ try? await Task.sleep(for: .milliseconds(1))
+ }
+}
+@MainActor func document(_ owner: String, idle: Int? = 60) -> AppBackupDocument {
+ .init(settings: .init(owner: owner, privateAIIdleUnload: idle),
+ promptProfiles: [owner], appPromptBindings: [owner],
+ transcriptionHistory: [owner], pronunciationProfiles: [owner])
+}
+@main struct Run {
+ @MainActor static func main() async throws {
+ let service = BackupService()
+ // Export suspended after obtaining old pronunciation; concurrent import used
+ // to make the eventual settings/History snapshot belong to a different backup.
+ let exportGate = Gate()
+ await reset(exportGate: exportGate)
+ let firstExport = Task { try await service.makeBackupDocument() }
+ await awaitGate(exportGate)
+ OVERLAP_ACTION
+ await exportGate.release()
+ let snapshot = try await firstExport.value
+ OVERLAP_ASSERTION
+ CURRENT_TESTS
+ }
+}
+'''.replace("SCHEMA", schema).replace("ERRORS", errors).replace("MEMBERS", members).replace("ASR_ACTIVITY", asr_activity).replace("ASR_ERROR", asr_error).replace("ASR_ADMISSION", asr_admission).replace("ASR_RELEASE", asr_release).replace("ASR_RESTORE", asr_restore)
+
+ if args.expect_active_work_gap:
+ swift = swift[:swift.index("@main struct Run")] + r'''
+@main struct Run {
+ @MainActor static func main() async throws {
+ let service = BackupService()
+ await reset()
+ let asr = AppServices.shared.asr
+ asr.isRunning = true
+ let dictation = try asr.acquireExclusiveActivity(.dictation)
+ try await service.restore(document("changed-during-dictation", idle: nil))
+ let state = await PronunciationDictionaryStore.shared.state()
+ expect(SettingsStore.shared.owner == "changed-during-dictation" && state.0 == ["changed-during-dictation"], "historical restore changes settings/profiles during dictation")
+ expect(TranscriptionHistoryStore.shared.writes == 1 && NotificationCenter.default.snapshots.count == 1, "historical restore publishes history and restore callbacks while recording")
+ expect(asr.activeActivityLease == dictation && asr.isRunning, "the ongoing dictation did not release its lease before the restore")
+ print("REPRODUCED: backup changes settings/profiles/history and posts restore callbacks while dictation still owns its recording lease")
+ }
+}
+'''
+ elif args.expect_overlap_gap:
+ # Historical enum lacks the busy case, so remove the current-only helper.
+ start = swift.index("@MainActor func busy(")
+ end = swift.index("@MainActor func reset(", start)
+ swift = swift[:start] + swift[end:]
+ swift = swift.replace("OVERLAP_ACTION", 'try await service.restore(document("B", idle: nil))')
+ swift = swift.replace("OVERLAP_ASSERTION", r'''
+ expect(snapshot.pronunciationProfiles == ["original"] && snapshot.settings.owner == "B" && snapshot.transcriptionHistory == ["B"], "historical export/import overlap must expose mixed snapshot")
+ print("REPRODUCED: old pronunciation + new settings/History from overlapping export/import")
+''')
+ swift = swift.replace("CURRENT_TESTS", 'print("Historical overlap probe completed")')
+ else:
+ swift = swift.replace("OVERLAP_ACTION", r'''
+ await busy { try await service.restore(document("B", idle: nil)) }
+ await busy { _ = try await service.makeBackupDocument() }
+ let during = await PronunciationDictionaryStore.shared.state()
+ expect(during.2 == 0 && during.1 == 1, "rejected overlap cannot enter profile writer/second snapshot")
+ expect(SettingsStore.shared.owner == "original" && TranscriptionHistoryStore.shared.writes == 0 && NotificationCenter.default.snapshots.isEmpty, "rejected import cannot write or notify")
+''')
+ swift = swift.replace("OVERLAP_ASSERTION", r'''
+ expect(snapshot.pronunciationProfiles == [snapshot.settings.owner] && snapshot.transcriptionHistory == [snapshot.settings.owner], "admitted export remains a consistent snapshot")
+ try await service.restore(document("B", idle: nil))
+ let freshExport = try await service.makeBackupDocument()
+ expect(freshExport.pronunciationProfiles == ["B"] && freshExport.settings.owner == "B", "import and export can retry after owner finishes")
+''')
+ swift = swift.replace("CURRENT_TESTS", r'''
+ // Reject complete imports before any profile/settings/history mutation when
+ // existing capture, processing, preparation, download or cleanup owns the app.
+ for blocker in 0..<21 {
+ await reset()
+ let asr = AppServices.shared.asr
+ switch blocker {
+ case 0: _ = try asr.acquireExclusiveActivity(.dictation)
+ case 1: _ = try asr.acquireExclusiveActivity(.fileTranscription)
+ case 2: _ = try asr.acquireExclusiveActivity(.localAPI)
+ case 3: _ = try asr.acquireExclusiveActivity(.meeting)
+ case 4: _ = try asr.acquireExclusiveActivity(.modelMaintenance)
+ case 5: asr.isRunning = true
+ case 6: asr.isStarting = true
+ case 7: asr.isStoppingFinalTranscription = true
+ case 8: asr.recordingBufferHandoffGate.isRecovering = true
+ case 9: asr.isMicrophonePreviewRequested = true
+ case 10: asr.isMicrophonePreviewActive = true
+ case 11: asr.hasActiveModelDownload = true
+ case 12: asr.hasActiveModelPreparation = true
+ case 13: asr.deletingModelID = "fixture"
+ case 14: asr.providerResetDrain = UUID()
+ case 15: asr.isCancellingModelPreparation = true
+ case 16: asr.meetingModelResidency.isExclusive = true
+ case 17: asr.isAsrReady = false; asr.isLoadingModel = true
+ case 18: asr.isCancellingModelDownload = true
+ case 19: asr.isTerminating = true
+ default: asr.isAsrReady = false; asr.isDownloadingModel = true
+ }
+ let originalLease = asr.activeActivityLease
+ do {
+ try await service.restore(document("busy", idle: nil))
+ fatalError("Active work must reject the import before any writes")
+ } catch ASRActivityError.settingsRestoreUnavailable {
+ expect(ASRActivityError.settingsRestoreUnavailable.localizedDescription.contains("import the backup again"), "busy rejection gives an explicit retry")
+ }
+ let untouched = await PronunciationDictionaryStore.shared.state()
+ expect(untouched.2 == 0 && untouched.0 == ["original"], "busy import must not replace profiles")
+ expect(SettingsStore.shared.owner == "original" && TranscriptionHistoryStore.shared.history == ["original"] && TranscriptionHistoryStore.shared.writes == 0, "busy import must preserve settings/history")
+ expect(NotificationCenter.default.snapshots.isEmpty && asr.activeActivityLease == originalLease, "busy import must not notify or release another activity")
+ // No queued automatic import: a fresh explicit retry is required.
+ AppServices.shared.asr = ASRService()
+ try await service.restore(document("retry", idle: nil))
+ expect(SettingsStore.shared.owner == "retry" && AppServices.shared.asr.activeActivityLease == nil, "busy rejection releases backup gate for explicit retry")
+ }
+
+ // Reverse overlap: an admitted import has not yet replaced profiles.
+ let restoreGate = Gate()
+ await reset(restoreGate: restoreGate)
+ let firstRestore = Task { try await service.restore(document("A")) }
+ await awaitGate(restoreGate)
+ let restoringASR = AppServices.shared.asr
+ expect(restoringASR.activeExclusiveActivity == .settingsRestore, "import reserves ASR before the profile actor hop")
+ for activity: ASRExclusiveActivity in [.dictation, .fileTranscription, .localAPI, .meeting, .modelMaintenance] {
+ do {
+ _ = try restoringASR.acquireExclusiveActivity(activity)
+ fatalError("A new activity must not race into the suspended import")
+ } catch ASRActivityError.activityInProgress(let existing) {
+ expect(existing == .settingsRestore, "competing activity sees the exact import owner")
+ }
+ }
+ await busy { _ = try await service.makeBackupDocument() }
+ await busy { try await service.restore(document("B")) }
+ let beforeReplace = await PronunciationDictionaryStore.shared.state()
+ expect(beforeReplace.2 == 1 && beforeReplace.1 == 0 && TranscriptionHistoryStore.shared.loads == 0, "reverse overlap is rejected before export load or second profile write")
+ await restoreGate.release(); try await firstRestore.value
+ expect(restoringASR.activeActivityLease == nil && restoringASR.admissions == 1 && restoringASR.releases == 1, "successful import releases its exact ASR reservation once")
+ let nextDictation = try restoringASR.acquireExclusiveActivity(.dictation)
+ restoringASR.releaseExclusiveActivity(nextDictation)
+ let afterRestore = try await service.makeBackupDocument()
+ expect(afterRestore.settings.owner == "A" && afterRestore.pronunciationProfiles == ["A"] && afterRestore.transcriptionHistory == ["A"], "admitted restore publishes one complete document")
+
+ // An unchanged idle preference leaves no await after the UI notification.
+ // Observe synchronous reset arming, then queue capture admission before
+ // restore returns; it must never observe the old ready-model state.
+ await reset()
+ let unchangedASR = AppServices.shared.asr
+ var queuedCapture: Task<Void, Never>?
+ NotificationCenter.default.onPost = {
+ expect(unchangedASR.activeExclusiveActivity == .settingsRestore && unchangedASR.providerResetPending, "UI observers run after model retirement is armed while import admission is held")
+ queuedCapture = Task { @MainActor in
+ expect(!unchangedASR.isAsrReady && unchangedASR.completedResets == 1, "queued capture sees retired ready-model state before admission")
+ do {
+ let lease = try unchangedASR.acquireExclusiveActivity(.dictation)
+ unchangedASR.releaseExclusiveActivity(lease)
+ } catch { fatalError("Capture should be retryable after the completed fixture reset") }
+ }
+ }
+ try await service.restore(document("unchanged-idle", idle: 30))
+ await queuedCapture?.value
+ let unchangedIdle = await PrivateAIIntegrationService.idleUnloader.state()
+ expect(unchangedIdle.0 == 0 && unchangedASR.recoveryRequests == 1 && unchangedASR.completedResets == 1, "unchanged idle import arms exactly one reset/recovery without a timer hop")
+ expect(!unchangedASR.providerResetPending && unchangedASR.activeActivityLease == nil, "queued capture leaves no stale reset or import reservation")
+
+ // Retain ownership through timer replies and notification reentrancy.
+ let idleGate = Gate()
+ await reset(idleGate: idleGate)
+ let idleRestore = Task { try await service.restore(document("A")) }
+ await awaitGate(idleGate)
+ await busy { _ = try await service.makeBackupDocument() }
+ await busy { try await service.restore(document("B", idle: nil)) }
+ expect(NotificationCenter.default.snapshots.count == 1 && NotificationCenter.default.snapshots.allSatisfy { $0.1 == [$0.0] }, "synchronous observers see matching settings/history")
+ SettingsStore.shared.privateAIIdleUnload = 0
+ idleRestore.cancel(); await idleGate.release(); try await idleRestore.value
+ let idleState = await PrivateAIIntegrationService.idleUnloader.state()
+ expect(idleState.1 == [0], "timer reads latest user preference after cancellation")
+ try await service.restore(document("retry", idle: nil))
+ expect(SettingsStore.shared.owner == "retry", "cancellation after commit releases busy flag")
+
+ // Cancel a read-only export while actor reply is delayed: no document or write.
+ let cancelledGate = Gate()
+ await reset(exportGate: cancelledGate)
+ let cancelledExport = Task { try await service.makeBackupDocument() }
+ await awaitGate(cancelledGate); cancelledExport.cancel(); await cancelledGate.release()
+ do { _ = try await cancelledExport.value; fatalError("Expected cancellation") } catch is CancellationError {}
+ expect(SettingsStore.shared.owner == "original" && TranscriptionHistoryStore.shared.writes == 0 && NotificationCenter.default.snapshots.isEmpty, "cancelled export has no writes/notifications")
+ _ = try await service.makeBackupDocument()
+ try await service.restore(document("after-export-cancel", idle: nil))
+ expect(SettingsStore.shared.owner == "after-export-cancel", "cancelled export releases gate for both operations")
+
+ // A profile write admitted before cancellation must finish the matching
+ // synchronous commit rather than leave new profiles with old settings.
+ let cancelledRestoreGate = Gate()
+ await reset(restoreGate: cancelledRestoreGate)
+ let cancelledRestore = Task { try await service.restore(document("cancelled", idle: nil)) }
+ await awaitGate(cancelledRestoreGate); cancelledRestore.cancel(); await cancelledRestoreGate.release()
+ try await cancelledRestore.value
+ expect(AppServices.shared.asr.activeActivityLease == nil && AppServices.shared.asr.releases == 1, "cancelled admitted import releases its ASR reservation")
+ let completed = try await service.makeBackupDocument()
+ expect(completed.pronunciationProfiles == ["cancelled"] && completed.settings.owner == "cancelled" && completed.transcriptionHistory == ["cancelled"], "cancellation after profile admission finishes a consistent restore")
+ expect(NotificationCenter.default.snapshots.count == 1, "completed cancelled restore notifies exactly once")
+
+ // Cancellation before admission prevents all dependency work and releases gate.
+ for isRestore in [false, true] {
+ await reset()
+ let task = Task { () throws -> Void in
+ withUnsafeCurrentTask { $0?.cancel() }
+ if isRestore { try await service.restore(document("unstarted")) }
+ else { _ = try await service.makeBackupDocument() }
+ }
+ do { try await task.value; fatalError("Expected early cancellation") } catch is CancellationError {}
+ let untouched = await PronunciationDictionaryStore.shared.state()
+ expect(untouched.1 == 0 && untouched.2 == 0 && TranscriptionHistoryStore.shared.loads == 0, "pre-cancelled operation never touches dependencies")
+ _ = try await service.makeBackupDocument()
+ try await service.restore(document("retry", idle: nil))
+ expect(SettingsStore.shared.owner == "retry", "early cancellation clears admission flag")
+ }
+ // Every failure path releases its hold and preserves non-effects.
+ await reset()
+ await PronunciationDictionaryStore.shared.setup(reject: true)
+ do { try await service.restore(document("failed")); fatalError("Expected store failure") } catch ProbeFailure.storage {}
+ expect(SettingsStore.shared.owner == "original" && TranscriptionHistoryStore.shared.writes == 0 && NotificationCenter.default.snapshots.isEmpty, "profile failure has no settings/history/notification effects")
+ expect(AppServices.shared.asr.activeActivityLease == nil && AppServices.shared.asr.releases == 1, "profile failure releases the exact ASR reservation")
+ await PronunciationDictionaryStore.shared.setup()
+ _ = try await service.makeBackupDocument()
+ try await service.restore(document("retry", idle: nil))
+ expect(SettingsStore.shared.owner == "retry", "profile failure clears gate")
+ await reset()
+ var invalid = document("invalid"); invalid.schemaVersion = .init(major: 99, minor: 0)
+ do { try await service.restore(invalid); fatalError("Expected schema failure") } catch BackupServiceError.unsupportedSchemaVersion {}
+ let rejected = await PronunciationDictionaryStore.shared.state()
+ expect(rejected.2 == 0 && SettingsStore.shared.owner == "original", "schema validation rejects before profile write")
+ _ = try await service.makeBackupDocument()
+ expect(TranscriptionHistoryStore.shared.loads == 1, "schema failure clears gate")
+ await reset(); TranscriptionHistoryStore.shared.loaded = false
+ do { _ = try await service.makeBackupDocument(); fatalError("Expected load failure") } catch ProbeFailure.storage {}
+ let unloaded = await PronunciationDictionaryStore.shared.state()
+ expect(unloaded.1 == 0 && unloaded.2 == 0 && NotificationCenter.default.snapshots.isEmpty, "load failure has no profile or notification effects")
+ TranscriptionHistoryStore.shared.loaded = true
+ try await service.restore(document("retry", idle: nil))
+ expect(SettingsStore.shared.owner == "retry", "load failure clears gate")
+
+ // Export retains admission even before history has loaded; cancellation
+ // is checked after the pre-existing non-cancellable load reply returns.
+ let loadGate = Gate()
+ await reset(); TranscriptionHistoryStore.shared.loadGate = loadGate
+ let loading = Task { try await service.makeBackupDocument() }
+ await awaitGate(loadGate)
+ await busy { try await service.restore(document("blocked")) }
+ await busy { _ = try await service.makeBackupDocument() }
+ loading.cancel(); await loadGate.release()
+ do { _ = try await loading.value; fatalError("Expected load cancellation") } catch is CancellationError {}
+ let noSnapshot = await PronunciationDictionaryStore.shared.state()
+ expect(noSnapshot.1 == 0, "cancelled history wait exits before pronunciation snapshot")
+ _ = try await service.makeBackupDocument()
+
+ for (idle, expectedCalls) in [(nil, 0), (Optional(30), 0), (Optional(60), 1), (Optional(0), 1)] {
+ await reset(); try await service.restore(document("field", idle: idle))
+ let state = await PrivateAIIntegrationService.idleUnloader.state()
+ expect(state.0 == expectedCalls, "only changed present idle values reschedule")
+ expect(SettingsStore.shared.privateAIIdleUnload == (idle ?? 30), "legacy absent idle preserves preference")
+ }
+ await reset()
+ var legacy = document("legacy", idle: nil); legacy.pronunciationProfiles = nil
+ try await service.restore(legacy)
+ let legacyExport = try await service.makeBackupDocument()
+ expect(legacyExport.pronunciationProfiles == [] && legacyExport.settings.owner == "legacy", "legacy import clears newer pronunciation profiles")
+ expect(SettingsStore.shared.meetingLanguage == "en" && SettingsStore.shared.configurations == ["__default__": "original"], "absent additive settings remain unchanged")
+ var modern = document("modern", idle: nil)
+ modern.settings.meetingLanguage = "fr"; modern.settings.promptConfigurations = [:]
+ try await service.restore(modern)
+ expect(SettingsStore.shared.meetingLanguage == "fr" && SettingsStore.shared.configurations.isEmpty, "present empty configuration remains authoritative")
+ await reset()
+ NotificationCenter.default.onPost = { SettingsStore.shared.privateAIIdleUnload = 0 }
+ try await service.restore(document("notice"))
+ let notificationSettings = await PrivateAIIntegrationService.idleUnloader.state()
+ expect(notificationSettings.1 == [0], "timer respects synchronous observer preference changes")
+
+ // Deliberately document the limit: ordinary dictionary/settings edits do
+ // not participate in BackupService admission. This gate cannot serialize them.
+ let manualGate = Gate()
+ await reset(exportGate: manualGate)
+ let manualExport = Task { try await service.makeBackupDocument() }
+ await awaitGate(manualGate)
+ await PronunciationDictionaryStore.shared.ordinaryEdit(["manual"])
+ SettingsStore.shared.owner = "manual"; TranscriptionHistoryStore.shared.history = ["manual"]
+ await manualGate.release()
+ let manualSnapshot = try await manualExport.value
+ expect(manualSnapshot.pronunciationProfiles == ["original"] && manualSnapshot.settings.owner == "manual", "service gate does not falsely serialize ordinary dictionary/settings mutations")
+ expect(AppServices.shared.asr.activeActivityLease == nil, "no completed test leaves import admission held")
+ print("LIMIT: ordinary dictionary/settings edits remain outside backup-operation admission")
+ print("PASS: \(assertions) production-method concurrency assertions")
+''')
+ with tempfile.TemporaryDirectory(prefix="fluidvoice-backup-concurrency-") as directory:
+ swift_path = Path(directory) / "Probe.swift"
+ binary = Path(directory) / "probe"
+ swift_path.write_text(swift)
+ subprocess.run(["xcrun", "swiftc", "-parse-as-library", str(swift_path), "-o", str(binary)],
+ cwd=repo, env=environment, check=True, timeout=60)
+ subprocess.run([str(binary)], env=environment, check=True, timeout=20)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test_history_presentation.sh b/scripts/test_history_presentation.sh
index 2d454184..2b0b58b0 100644
--- a/scripts/test_history_presentation.sh
+++ b/scripts/test_history_presentation.sh
@@ -8,5 +8,6 @@ task_test_dir=$(mktemp -d /tmp/fluidvoice-history-presentation.XXXXXX)
# Compile the real value types without starting the app or accessing user history.
sed '/^\/\/ MARK: - Transcription History Store/,$d' Sources/Fluid/Persistence/TranscriptionHistoryStore.swift > "$task_test_dir/Entry.swift"
sed '/^final nonisolated class DictationAudioHistoryStore/,$d' Sources/Fluid/Persistence/DictationAudioHistoryStore.swift > "$task_test_dir/Audio.swift"
-xcrun swiftc -parse-as-library "$task_test_dir/Entry.swift" "$task_test_dir/Audio.swift" Sources/Fluid/UI/HistoryTextDiff.swift Sources/Fluid/UI/HistoryAudioAvailability.swift Sources/Fluid/UI/ModelDisplayName.swift Tests/HistoryPresentationTests.swift -o "$task_test_dir/tests"
+sed '/^struct TranscriptionHistoryView:/,$d; s/^import AppKit$/import Foundation/; /^import SwiftUI$/d; /^import UniformTypeIdentifiers$/d' Sources/Fluid/UI/TranscriptionHistoryView.swift > "$task_test_dir/Selection.swift"
+xcrun swiftc -parse-as-library "$task_test_dir/Entry.swift" "$task_test_dir/Audio.swift" "$task_test_dir/Selection.swift" Sources/Fluid/UI/HistoryTextDiff.swift Sources/Fluid/UI/HistoryAudioAvailability.swift Sources/Fluid/UI/ModelDisplayName.swift Tests/HistoryPresentationTests.swift -o "$task_test_dir/tests"
"$task_test_dir/tests"