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 FluidVoice 1.6.10-beta.8 (build 27) (#1039)
ALTIC26b09c9faeff
diff --git a/.github/pr-assets/beta8-meeting-language-dark.png b/.github/pr-assets/beta8-meeting-language-dark.pngnew file mode 100644index 00000000..bd43f349Binary files /dev/null and b/.github/pr-assets/beta8-meeting-language-dark.png differdiff --git a/.github/pr-assets/beta8-meeting-language-light.png b/.github/pr-assets/beta8-meeting-language-light.pngnew file mode 100644index 00000000..9b377ac2Binary files /dev/null and b/.github/pr-assets/beta8-meeting-language-light.png differdiff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojindex 9d186c55..17f1a9b4 100644--- a/Fluid.xcodeproj/project.pbxproj+++ b/Fluid.xcodeproj/project.pbxproj@@ -44,6 +44,7 @@C1A000000000000000000002 /* MeetingResultSidecarTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000001 /* MeetingResultSidecarTests.swift */; };C2A000000000000000000002 /* MeetingAnalysisManifestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2A000000000000000000001 /* MeetingAnalysisManifestTests.swift */; };FEA4AB111222333444555502 /* MeetingSpeakerVoiceMatcherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEA4AB111222333444555501 /* MeetingSpeakerVoiceMatcherTests.swift */; };+ D9B100000000000000000002 /* VoiceModelDeletionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9B100000000000000000001 /* VoiceModelDeletionTests.swift */; };C2B100000000000000000002 /* MeetingTranscriptAssemblerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2B100000000000000000001 /* MeetingTranscriptAssemblerTests.swift */; };C2B200000000000000000002 /* MeetingCanonicalPipelineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2B200000000000000000001 /* MeetingCanonicalPipelineTests.swift */; };E3A000000000000000000002 /* MeetingParakeetNemotronBackendTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3A000000000000000000001 /* MeetingParakeetNemotronBackendTests.swift */; };@@ -176,6 +177,7 @@C1A000000000000000000001 /* MeetingResultSidecarTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingResultSidecarTests.swift; sourceTree = "<group>"; };C2A000000000000000000001 /* MeetingAnalysisManifestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingAnalysisManifestTests.swift; sourceTree = "<group>"; };FEA4AB111222333444555501 /* MeetingSpeakerVoiceMatcherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingSpeakerVoiceMatcherTests.swift; sourceTree = "<group>"; };+ D9B100000000000000000001 /* VoiceModelDeletionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceModelDeletionTests.swift; sourceTree = "<group>"; };C2B100000000000000000001 /* MeetingTranscriptAssemblerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingTranscriptAssemblerTests.swift; sourceTree = "<group>"; };C2B200000000000000000001 /* MeetingCanonicalPipelineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingCanonicalPipelineTests.swift; sourceTree = "<group>"; };E3A000000000000000000001 /* MeetingParakeetNemotronBackendTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingParakeetNemotronBackendTests.swift; sourceTree = "<group>"; };@@ -389,6 +391,7 @@AB492EFF712C42EE91601003 /* MeetingSummaryDownloadTests.swift */,AB492EFF712C42EE91601001 /* MeetingSummaryInputTests.swift */,C2B100000000000000000001 /* MeetingTranscriptAssemblerTests.swift */,+ D9B100000000000000000001 /* VoiceModelDeletionTests.swift */,C2B200000000000000000001 /* MeetingCanonicalPipelineTests.swift */,E3A000000000000000000001 /* MeetingParakeetNemotronBackendTests.swift */,E3A000000000000000000011 /* MeetingTextOverlapEchoVerdictProviderTests.swift */,@@ -744,6 +747,7 @@AB492EFF712C42EE91601004 /* MeetingSummaryDownloadTests.swift in Sources */,AB492EFF712C42EE91601002 /* MeetingSummaryInputTests.swift in Sources */,C2B100000000000000000002 /* MeetingTranscriptAssemblerTests.swift in Sources */,+ D9B100000000000000000002 /* VoiceModelDeletionTests.swift in Sources */,C2B200000000000000000002 /* MeetingCanonicalPipelineTests.swift in Sources */,E3A000000000000000000002 /* MeetingParakeetNemotronBackendTests.swift in Sources */,E3A000000000000000000012 /* MeetingTextOverlapEchoVerdictProviderTests.swift in Sources */,@@ -968,7 +972,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 26;+ CURRENT_PROJECT_VERSION = 27;DEVELOPMENT_TEAM = V4J43B279J;ENABLE_APP_SANDBOX = NO;ENABLE_CODE_COVERAGE = NO;@@ -996,7 +1000,7 @@"@executable_path/../Frameworks",);MACOSX_DEPLOYMENT_TARGET = 15.0;- MARKETING_VERSION = "1.6.10-beta.7";+ MARKETING_VERSION = "1.6.10-beta.8";PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app.debug;PRODUCT_NAME = "FluidVoice Debug";PROVISIONING_PROFILE_SPECIFIER = "";@@ -1023,7 +1027,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 26;+ CURRENT_PROJECT_VERSION = 27;DEVELOPMENT_TEAM = V4J43B279J;ENABLE_APP_SANDBOX = NO;ENABLE_CODE_COVERAGE = NO;@@ -1051,7 +1055,7 @@"@executable_path/../Frameworks",);MACOSX_DEPLOYMENT_TARGET = 15.0;- MARKETING_VERSION = "1.6.10-beta.7";+ MARKETING_VERSION = "1.6.10-beta.8";PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app;PRODUCT_NAME = FluidVoice;PROVISIONING_PROFILE_SPECIFIER = "";@@ -1321,8 +1325,8 @@isa = XCRemoteSwiftPackageReference;repositoryURL = "https://github.com/altic-dev/DynamicNotchKit.git";requirement = {- branch = main;- kind = branch;+ revision = 50dc8565469cc80bbbe3c0d5dd902585a2d67986;+ kind = revision;};};7C5AF1492F15041600DE21B0 /* XCRemoteSwiftPackageReference "mediaremote-adapter" */ = {diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 9c24d800..9121c9bb 100644--- a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -15,8 +15,7 @@"kind" : "remoteSourceControl","location" : "https://github.com/altic-dev/DynamicNotchKit.git","state" : {- "branch" : "main",- "revision" : "708f31da5319436c64059ee7ae566953407063d7"+ "revision" : "50dc8565469cc80bbbe3c0d5dd902585a2d67986"}},{diff --git a/Info.plist b/Info.plistindex d1a1298a..72c3855a 100644--- a/Info.plist+++ b/Info.plist@@ -13,9 +13,9 @@<key>CFBundleIdentifier</key><string>$(PRODUCT_BUNDLE_IDENTIFIER)</string><key>CFBundleVersion</key>- <string>26</string>+ <string>27</string><key>CFBundleShortVersionString</key>- <string>1.6.10-beta.7</string>+ <string>1.6.10-beta.8</string><key>LSMinimumSystemVersion</key><string>$(MACOSX_DEPLOYMENT_TARGET)</string><key>LSApplicationCategoryType</key>diff --git a/Package.resolved b/Package.resolvedindex e3c778d1..ba9dc633 100644--- a/Package.resolved+++ b/Package.resolved@@ -14,8 +14,7 @@"kind" : "remoteSourceControl","location" : "https://github.com/altic-dev/DynamicNotchKit.git","state" : {- "branch" : "main",- "revision" : "708f31da5319436c64059ee7ae566953407063d7"+ "revision" : "50dc8565469cc80bbbe3c0d5dd902585a2d67986"}},{diff --git a/Package.swift b/Package.swiftindex f81dc17a..024ed1e5 100644--- a/Package.swift+++ b/Package.swift@@ -13,7 +13,7 @@ let package = Package(.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/mxcl/PromiseKit", from: "6.0.0"),- .package(url: "https://github.com/altic-dev/DynamicNotchKit.git", branch: "main"),+ .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"),.package(url: "https://github.com/zepdb/zeppelin-embed.git", exact: "0.4.1"),],diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 76b26df8..98857c52 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -1370,22 +1370,28 @@ struct ContentView: View {.padding(.top, self.theme.metrics.spacing.sm).padding(.bottom, self.theme.metrics.spacing.sm)- if self.isAppSearchActive {- AppSearchResultsView(- service: self.appSearch,- cursor: self.$appSearchCursor,- expanded: self.$appSearchExpanded,- open: self.open(searchHit:)- )- } else {- self.appSidebarSections+ Group {+ if self.isAppSearchActive {+ AppSearchResultsView(+ service: self.appSearch,+ cursor: self.$appSearchCursor,+ expanded: self.$appSearchExpanded,+ open: self.open(searchHit:)+ )+ } else {+ self.appSidebarSections+ }}- }- .safeAreaInset(edge: .bottom, spacing: 0) {+ .frame(maxHeight: .infinity)+ .clipped()++ // Reserve real layout space for the footer. A safe-area inset can let+ // the native sidebar list draw its last rows beneath these controls.VStack(spacing: 0) {self.helpEntryButtonself.settingsEntryButton}+ .fixedSize(horizontal: false, vertical: true)}.onChange(of: self.appSearch.groups) {self.appSearchCursor = nildiff --git a/Sources/Fluid/Persistence/VoiceEngineLanguageCatalog.swift b/Sources/Fluid/Persistence/VoiceEngineLanguageCatalog.swiftindex 7d13f4b7..d94f8316 100644--- a/Sources/Fluid/Persistence/VoiceEngineLanguageCatalog.swift+++ b/Sources/Fluid/Persistence/VoiceEngineLanguageCatalog.swift@@ -223,7 +223,7 @@ enum VoiceEngineLanguageCatalog {"ar",]- private static let parakeetV3LanguageIDs: Set<String> = [+ nonisolated static let parakeetV3LanguageIDs: Set<String> = ["bg","hr","cs",diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex 58c1b623..076622d9 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -999,6 +999,11 @@ final class ASRService: ObservableObject {private var modelDownloadAnalyticsStates: [UUID: ModelDownloadAnalyticsState] = [:]private var modelExistenceCheckID: UUID?+ @Published private(set) var deletingModelID: String?+ #if DEBUG+ var modelProvidersForTesting: [SettingsStore.SpeechModel: TranscriptionProvider] = [:]+ #endif+var hasActiveModelPreparation: Bool {self.ensureReadyTask != nil}@@ -1093,6 +1098,9 @@ final class ASRService: ObservableObject {/// Uses the new SettingsStore.selectedSpeechModel instead of old TranscriptionProviderOption.private var transcriptionProvider: TranscriptionProvider {let model = SettingsStore.shared.selectedSpeechModel+ #if DEBUG+ if let injected = self.modelProvidersForTesting[model] { return injected }+ #endifswitch model {case .appleSpeechAnalyzer:@@ -1224,6 +1232,9 @@ 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 {+ #if DEBUG+ if let injected = self.modelProvidersForTesting[model] { return injected }+ #endifswitch model {case .appleSpeechAnalyzer:if #available(macOS 26.0, *) {@@ -1265,7 +1276,7 @@ final class ASRService: ObservableObject {if self.isMeetingASRPreparationClaimed {throw MeetingASRPreparationError.preparationInProgress}- guard self.modelDownloadTask == nil, self.ensureReadyTask == nil else {+ guard self.deletingModelID == nil, self.modelDownloadTask == nil, self.ensureReadyTask == nil else {throw NSError(domain: "ASRService",code: -2001,@@ -2638,9 +2649,10 @@ final class ASRService: ObservableObject {@discardableResultfunc start(forDictionaryTraining: Bool = false,+ requiresPronunciation: Bool = true,onCaptureStarted: (@MainActor () -> Void)? = nil) async -> AudioCaptureStartOutcome {- guard !forDictionaryTraining || DictionaryMatcherExperiment.sharedFeaturesEnabled else { return .failed }+ guard !forDictionaryTraining || !requiresPronunciation || DictionaryMatcherExperiment.sharedFeaturesEnabled else { return .failed }DebugLogger.shared.info("🎤 START() called - beginning recording session", source: "ASRService")guard self.micStatus == .authorized else {@@ -2673,8 +2685,9 @@ final class ASRService: ObservableObject {self.audioCaptureStartGeneration &+= 1let startGeneration = self.audioCaptureStartGenerationself.isStarting = true- self.isPronunciationTrainingStart = forDictionaryTraining- self.pronunciationTrainingStartGeneration = forDictionaryTraining ? DictionaryMatcherExperiment.generation : nil+ // Spelling-only training owns the same isolated capture, without requiring voice matching.+ self.isPronunciationTrainingStart = forDictionaryTraining && requiresPronunciation+ self.pronunciationTrainingStartGeneration = self.isPronunciationTrainingStart ? DictionaryMatcherExperiment.generation : nildefer {self.pronunciationTrainingStartGeneration = nilself.isPronunciationTrainingStart = false@@ -4018,7 +4031,7 @@ final class ASRService: ObservableObject {try await self.retireDictationASRResourcesForMeeting(lease: lease)},makeProvider: { configuration in- // Fixed Parakeet TDT v2 English policy; never reads selectedSpeechModel.+ // Language selects the pinned Parakeet v2/v3 model; never reads selectedSpeechModel.try FluidAudioProvider(meetingConfiguration: configuration)},prepareProvider: { provider, _, progress in@@ -6259,7 +6272,7 @@ final class ASRService: ObservableObject {)defer { self.meetingModelResidency.endOperation(admission) }try self.requireStreamingProviderAvailable()- guard self.modelDownloadTask == nil else {+ guard self.deletingModelID == nil, self.modelDownloadTask == nil else {throw NSError(domain: "ASRService",code: -2001,@@ -6307,7 +6320,7 @@ final class ASRService: ObservableObject {}}- guard SettingsStore.shared.selectedSpeechModel == model else {+ guard self.deletingModelID == nil, SettingsStore.shared.selectedSpeechModel == model else {throw CancellationError()}@@ -6739,36 +6752,57 @@ final class ASRService: ObservableObject {// MARK: - Cache managementfunc clearModelCache() async throws {- try self.requireStreamingProviderAvailable()- let activityLease = try self.acquireExclusiveActivity(.modelMaintenance)- defer { self.releaseExclusiveActivity(activityLease) }- DebugLogger.shared.debug("Clearing model cache via transcription provider", source: "ASRService")- self.streamingWorkState.invalidateProvider()- self.isAsrReady = false- await self.transcriptionExecutor.cancelAndAwaitPending()- try await self.transcriptionProvider.clearCache()- self.modelsExistOnDisk = false+ try await self.clearModelCache(for: SettingsStore.shared.selectedSpeechModel)}- func clearModelCache(for model: SettingsStore.SpeechModel) async throws {+ func clearModelCache(for requestedModel: SettingsStore.SpeechModel) async throws {+ // The legacy Streaming320 name shares Streaming's files and active provider.+ let model = requestedModel == .nemotronStreaming320 ? .nemotronStreaming : requestedModeltry self.requireStreamingProviderAvailable()+ guard self.deletingModelID == nil, !self.hasActiveModelDownload, !self.hasActiveModelPreparation,+ !self.isMeetingASRPreparationClaimed+ else {+ throw NSError(domain: "ASRService", code: -2001, userInfo: [+ NSLocalizedDescriptionKey: "Another model operation is already in progress. Try deleting again when it finishes.",+ ])+ }+ guard !model.usesAppleLogo, model != .qwen3Asr else {+ throw NSError(domain: "ASRService", code: -2003, userInfo: [+ NSLocalizedDescriptionKey: "This model cannot be deleted from FluidVoice.",+ ])+ }let activityLease = try self.acquireExclusiveActivity(.modelMaintenance)- defer { self.releaseExclusiveActivity(activityLease) }+ self.deletingModelID = model.id+ let isActive = SettingsStore.shared.selectedSpeechModel == model+ defer {+ self.deletingModelID = nil+ self.releaseExclusiveActivity(activityLease)+ }DebugLogger.shared.debug("Clearing model cache for \(model.displayName)", source: "ASRService")- if SettingsStore.shared.selectedSpeechModel == model {+ let provider = isActive ? self.transcriptionProvider : self.cachedDeletionProvider(for: model)+ if isActive {self.streamingWorkState.invalidateProvider()self.isAsrReady = false+ self.providerResetPending = trueawait self.transcriptionExecutor.cancelAndAwaitPending()}- let provider = self.getProvider(for: model)+ try Task.checkCancellation()+ guard !isActive || SettingsStore.shared.selectedSpeechModel == model else { throw CancellationError() }try await provider.clearCache()-if model.requiresExternalArtifacts {SettingsStore.shared.setExternalCoreMLArtifactsDirectory(nil, for: model)}+ if isActive { self.modelsExistOnDisk = false }+ }- guard SettingsStore.shared.selectedSpeechModel == model else { return }- self.providerResetPending = true+ private func cachedDeletionProvider(for model: SettingsStore.SpeechModel) -> TranscriptionProvider {+ // Nemotron keeps providers for both modes; retire the target's existing instance.+ if model == .nemotronOffline || model == .nemotronStreaming || model == .nemotronStreaming320,+ let cached = self.nemotronProviders[model.nemotronProviderMode]+ {+ return cached+ }+ return self.getProvider(for: model)}// MARK: - Timer-based Streaming Transcription (No VAD)diff --git a/Sources/Fluid/Services/AppServices+MeetingMenuBar.swift b/Sources/Fluid/Services/AppServices+MeetingMenuBar.swiftindex 14dad18e..83cda5cc 100644--- a/Sources/Fluid/Services/AppServices+MeetingMenuBar.swift+++ b/Sources/Fluid/Services/AppServices+MeetingMenuBar.swift@@ -57,9 +57,11 @@ extension AppServices {return MeetingCaptureConfiguration(mode: mode,title: MeetingTranscriptionSetupDraft.defaultTitle(mode: mode, applicationDisplayName: application?.displayName),+ languageCode: defaults.languageCode ?? "en",platform: application.map { MeetingPlatformProfile(identifier: $0.bundleIdentifier, displayName: $0.displayName) },application: application,- microphone: microphone+ microphone: microphone,+ timestampDefaultTitle: true)}}diff --git a/Sources/Fluid/Services/DictionaryTrainingEndpointMonitor.swift b/Sources/Fluid/Services/DictionaryTrainingEndpointMonitor.swiftindex 21f4684b..1bc4e5ca 100644--- a/Sources/Fluid/Services/DictionaryTrainingEndpointMonitor.swift+++ b/Sources/Fluid/Services/DictionaryTrainingEndpointMonitor.swift@@ -25,14 +25,15 @@ final class DictionaryTrainingEndpointMonitor {private let detector = DictionaryTrainingEndpointDetector()private var task: Task<Void, Never>?+ private var deadlineTask: Task<Void, Never>?- private init() {}+ init() {}func meetingResidencyParticipant() -> MeetingModelParticipant {MeetingModelParticipant(owner: "dictionary-vad",snapshot: {- let generation = DictionaryMatcherExperiment.generation+ let generation = "dictionary-recording"guard let resident = await self.detector.residencySnapshot() else { return nil }return MeetingResidentModel(id: resident.id, configuration: generation)},@@ -50,12 +51,12 @@ final class DictionaryTrainingEndpointMonitor {)}- /// Eligibility must survive the actual load. Disabling and re-enabling changes the- /// generation, so neither an old snapshot nor a late model completion can revive it.+ /// Keep model restoration bounded to the caller's resource configuration.+ /// Speech-end detection serves spelling capture regardless of pronunciation settings.static func prepareIfCurrent(expectedGeneration: String,- isEnabled: () -> Bool = { DictionaryMatcherExperiment.sharedFeaturesEnabled },- generation: () -> String = { DictionaryMatcherExperiment.generation },+ isEnabled: () -> Bool = { true },+ generation: () -> String = { "dictionary-recording" },prepare: () async throws -> Void,unload: () async -> Void) async throws -> Bool {@@ -69,11 +70,9 @@ final class DictionaryTrainingEndpointMonitor {}func prepare() async {- guard DictionaryMatcherExperiment.sharedFeaturesEnabled else { return }- let generation = DictionaryMatcherExperiment.generationdo {try await self.detector.prepare()- guard DictionaryMatcherExperiment.sharedFeaturesEnabled, generation == DictionaryMatcherExperiment.generation, !Task.isCancelled else { return }+ guard !Task.isCancelled else { return }DebugLogger.shared.debug("Dictionary training endpoint detector ready",source: "DictionaryTrainingEndpointMonitor"@@ -90,34 +89,47 @@ final class DictionaryTrainingEndpointMonitor {asr: ASRService,onSpeechEnded: @escaping @MainActor () -> Void) {- self.stop()- guard DictionaryMatcherExperiment.sharedFeaturesEnabled else { return }- let detector = self.detector- let generation = DictionaryMatcherExperiment.generationguard let captureToken = asr.dictionaryCaptureToken else { return }+ self.start(+ isCurrent: { [weak asr] in asr?.isRunning == true && asr?.dictionaryCaptureToken == captureToken },+ audioGeneration: { [weak asr] in asr?.dictionaryTrainingAudioGeneration ?? 0 },+ readChunk: { [weak asr] offset in+ asr?.dictionaryTrainingAudioChunk(at: offset, count: DictionaryTrainingEndpointDetector.chunkSize) ?? []+ },+ onSpeechEnded: onSpeechEnded+ )+ }- self.task = Task { @MainActor [weak asr] in+ /// The same loop is replayable with recorded PCM; microphone ownership stays with ASRService.+ func start(+ isCurrent: @escaping @MainActor () -> Bool,+ audioGeneration: @escaping @MainActor () -> Int,+ readChunk: @escaping @MainActor (Int) -> [Float],+ maximumDuration: Duration = .seconds(15),+ onSpeechEnded: @escaping @MainActor () -> Void+ ) {+ self.stop()+ let detector = self.detector+ // Bound capture even if model preparation fails or never produces an endpoint.+ self.deadlineTask = Task { @MainActor [weak self] in+ do { try await Task.sleep(for: maximumDuration) } catch { return }+ guard !Task.isCancelled, isCurrent() else { return }+ self?.task?.cancel()+ onSpeechEnded()+ }+ self.task = Task { @MainActor [weak self] indo {- guard DictionaryMatcherExperiment.sharedFeaturesEnabled, generation == DictionaryMatcherExperiment.generation, !Task.isCancelled, let asr,- asr.dictionaryCaptureToken == captureToken,- let detectorSession = try await detector.beginSession()- else {- return- }+ guard !Task.isCancelled, isCurrent() else { return }+ guard let detectorSession = try await detector.beginSession() else { return }defer {Task { await detector.endSession(detectorSession) }}- var cursor = DictionaryTrainingAudioCursor(generation: asr.dictionaryTrainingAudioGeneration)+ var cursor = DictionaryTrainingAudioCursor(generation: audioGeneration())while !Task.isCancelled {- guard DictionaryMatcherExperiment.sharedFeaturesEnabled, generation == DictionaryMatcherExperiment.generation, asr.isRunning,- asr.dictionaryCaptureToken == captureToken else { return }- cursor.synchronize(generation: asr.dictionaryTrainingAudioGeneration)-- let chunk = asr.dictionaryTrainingAudioChunk(- at: cursor.sampleOffset,- count: DictionaryTrainingEndpointDetector.chunkSize- )+ guard isCurrent() else { return }+ cursor.synchronize(generation: audioGeneration())+ let chunk = readChunk(cursor.sampleOffset)guard !chunk.isEmpty else {try await Task.sleep(nanoseconds: 40_000_000)continue@@ -130,9 +142,7 @@ final class DictionaryTrainingEndpointMonitor {) else {continue}- guard DictionaryMatcherExperiment.sharedFeaturesEnabled, generation == DictionaryMatcherExperiment.generation, !Task.isCancelled,- asr.isRunning,- asr.dictionaryCaptureToken == captureToken+ guard !Task.isCancelled, isCurrent()else {return}@@ -148,6 +158,7 @@ final class DictionaryTrainingEndpointMonitor {"Dictionary training speech ended; stopping sample",source: "DictionaryTrainingEndpointMonitor")+ self?.deadlineTask?.cancel()onSpeechEnded()return}@@ -164,6 +175,8 @@ final class DictionaryTrainingEndpointMonitor {}func stop() {+ self.deadlineTask?.cancel()+ self.deadlineTask = nilself.task?.cancel()self.task = nil}diff --git a/Sources/Fluid/Services/ExternalCoreMLTranscriptionProvider.swift b/Sources/Fluid/Services/ExternalCoreMLTranscriptionProvider.swiftindex ec7a8b80..9e3b3cf6 100644--- a/Sources/Fluid/Services/ExternalCoreMLTranscriptionProvider.swift+++ b/Sources/Fluid/Services/ExternalCoreMLTranscriptionProvider.swift@@ -179,47 +179,27 @@ final class ExternalCoreMLTranscriptionProvider: TranscriptionProvider {}func clearCache() async throws {- let model = self.modelOverride ?? SettingsStore.shared.selectedSpeechModel- guard let spec = model.externalCoreMLSpec,- let directory = Self.artifactsDirectory(for: model, spec: spec)- else {- self.isReady = false- self.cohereManager = nil- return- }-- let compiledDirectory = CohereTranscribeAsrModels.compiledArtifactsDirectory(for: directory)-- if FileManager.default.fileExists(atPath: compiledDirectory.path) {- DebugLogger.shared.info(- "ExternalCoreML: clearing compiled cache at \(compiledDirectory.path)",- source: "ExternalCoreML"- )- try FileManager.default.removeItem(at: compiledDirectory)- }-- if FileManager.default.fileExists(atPath: directory.path), spec.isAppManagedArtifactsDirectory(directory) {- DebugLogger.shared.info(- "ExternalCoreML: removing downloaded artifacts at \(directory.path)",- source: "ExternalCoreML"- )- try FileManager.default.removeItem(at: directory)- } else if FileManager.default.fileExists(atPath: directory.path) {- DebugLogger.shared.warning(- "ExternalCoreML: skipping deletion for non-managed artifacts directory at \(directory.path)",- source: "ExternalCoreML"- )- }-self.isReady = falseself.cohereManager = nilself.loadedManifest = nilself.coherePromptTemplate = []self.cohereLanguageTokenIDs = [:]- DebugLogger.shared.info(- "ExternalCoreML: provider reset after cache clear",- source: "ExternalCoreML"- )+ let model = self.modelOverride ?? SettingsStore.shared.selectedSpeechModel+ guard let spec = model.externalCoreMLSpec,+ let directory = Self.artifactsDirectory(for: model, spec: spec)+ else { return }+ let compiledDirectory = CohereTranscribeAsrModels.compiledArtifactsDirectory(for: directory)+ let isManaged = spec.isAppManagedArtifactsDirectory(directory)+ try await Task.detached(priority: .userInitiated) {+ let manager = FileManager.default+ if manager.fileExists(atPath: compiledDirectory.path) {+ try manager.removeItem(at: compiledDirectory)+ }+ if isManaged, manager.fileExists(atPath: directory.path) {+ try manager.removeItem(at: directory)+ }+ }.value+ DebugLogger.shared.info("ExternalCoreML: cleared app-managed cache for \(model.displayName)", source: "ExternalCoreML")}private func ensureArtifactsPresent(diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swiftindex 0fe41d3d..b3dc9be0 100644--- a/Sources/Fluid/Services/FluidAudioProvider.swift+++ b/Sources/Fluid/Services/FluidAudioProvider.swift@@ -8,8 +8,8 @@ nonisolated enum MeetingProviderOptionsError: Error, Equatable {}/// Immutable provider options for the opt-in meeting post-processing path. Only the fixed-/// Parakeet TDT v2 English policy is supported; `resolve` rejects anything else instead of-/// silently coercing it (e.g. labelling a v3 model "v2" or dropping a requested feature).+/// Parakeet TDT v2 handles English; v3 handles its supported multilingual languages.+/// Unsupported model/language combinations and enhancement features are rejected.nonisolated struct MeetingProviderOptions: Equatable, Sendable {let model: SettingsStore.SpeechModellet vocabularyBoostingEnabled: Bool@@ -20,11 +20,14 @@ nonisolated struct MeetingProviderOptions: Equatable, Sendable {static func resolve(_ configuration: MeetingFinalProcessingConfiguration) throws -> MeetingProviderOptions {- let model = SettingsStore.SpeechModel(rawValue: configuration.asrModel)- guard model == .parakeetTDTv2 else {+ guard let model = SettingsStore.SpeechModel(rawValue: configuration.asrModel),+ model == .parakeetTDTv2 || model == .parakeetTDT+ else {throw MeetingProviderOptionsError.unsupportedASRModel(configuration.asrModel)}- guard configuration.languageCode == MeetingFinalProcessingConfiguration.defaultLanguageCode else {+ guard VoiceEngineLanguageCatalog.parakeetV3LanguageIDs.contains(configuration.languageCode),+ model != .parakeetTDTv2 || configuration.languageCode == "en"+ else {throw MeetingProviderOptionsError.unsupportedLanguageCode(configuration.languageCode)}guard !configuration.vocabularyBoostingEnabled else {@@ -40,7 +43,7 @@ nonisolated struct MeetingProviderOptions: Equatable, Sendable {throw MeetingProviderOptionsError.unsupportedFeature("experimentalUnifiedFinal")}return MeetingProviderOptions(- model: .parakeetTDTv2,+ model: model,vocabularyBoostingEnabled: false,pronunciationMatchingEnabled: false,customDictionaryRewritingEnabled: false,@@ -596,7 +599,7 @@ final class FluidAudioProvider: TranscriptionProvider {}func transcribeDictionaryTraining(_ samples: [Float], capturePronunciation: Bool) async throws -> ASRTranscriptionResult {- guard DictionaryMatcherExperiment.sharedFeaturesEnabled else { throw CancellationError() }+ let pronunciationGeneration = DictionaryMatcherExperiment.generationguard let manager = self.streamingAsrManager else {throw NSError(domain: "FluidAudioProvider",@@ -610,8 +613,9 @@ final class FluidAudioProvider: TranscriptionProvider {let result = try await manager.transcribe(samples, source: AudioSource.microphone)let features = await manager.consumePronunciationEncoderFeatures()await manager.setPronunciationCustomizationEnabled(false)- guard DictionaryMatcherExperiment.sharedFeaturesEnabled else { throw CancellationError() }- var capture = shouldCapture ? self.makeEnrollment(result: result, features: features, samples: samples) : nil+ let captureIsCurrent = shouldCapture && DictionaryMatcherExperiment.sharedFeaturesEnabled+ && DictionaryMatcherExperiment.generation == pronunciationGeneration+ var capture = captureIsCurrent ? self.makeEnrollment(result: result, features: features, samples: samples) : nilif capture != nil, DictionaryPronunciationExperiment.enabled,let range = DictionaryPronunciationExperiment.trimmedRange(samples){@@ -619,6 +623,9 @@ final class FluidAudioProvider: TranscriptionProvider {capture?.edgeEmbedding = embedding.valuescapture?.edgeFrameCount = embedding.sourceFrameCount}+ if !DictionaryMatcherExperiment.sharedFeaturesEnabled || DictionaryMatcherExperiment.generation != pronunciationGeneration {+ capture = nil+ }return ASRTranscriptionResult(text: result.text, confidence: result.confidence, pronunciationEnrollment: capture)} catch {_ = await manager.consumePronunciationEncoderFeatures()@@ -1466,51 +1473,34 @@ final class FluidAudioProvider: TranscriptionProvider {}func clearCache() async throws {+ let selectedModel = self.modelOverride ?? SettingsStore.shared.selectedSpeechModelself.automaticPronunciationProfiles = []self.didLoadAutomaticPronunciationProfiles = falseself.recordingGeneration = UUID()self.resetIncrementalSession()- let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()- let selectedModel = self.modelOverride ?? SettingsStore.shared.selectedSpeechModel- DebugLogger.shared.info(- "FluidAudioProvider: clearCache called for \(selectedModel.displayName)",- source: "FluidAudioProvider"- )-- let start = Date()- if selectedModel == .parakeetTDTv2 {- // Clear v2 cache only- let v2CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v2-coreml")- if FileManager.default.fileExists(atPath: v2CacheDir.path) {- try FileManager.default.removeItem(at: v2CacheDir)- DebugLogger.shared.info("FluidAudioProvider: Deleted Parakeet v2 cache", source: "FluidAudioProvider")- }- } else {- // Clear v3 cache only (default)- let v3CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")- if FileManager.default.fileExists(atPath: v3CacheDir.path) {- try FileManager.default.removeItem(at: v3CacheDir)- DebugLogger.shared.info("FluidAudioProvider: Deleted Parakeet v3 cache", source: "FluidAudioProvider")- }- }-- DebugLogger.shared.debug(- "FluidAudioProvider: clearCache completed in \(String(format: "%.3f", Date().timeIntervalSince(start)))s",- source: "FluidAudioProvider"- )-+ self.temporalWarmRequest = nil+ let warmTask = self.temporalWarmTask+ warmTask?.cancel()+ await warmTask?.valueself.isReady = falseself.streamingAsrManager = nilself.finalAsrManager = nilself.temporalModels = nil- self.temporalWarmTask?.cancel()- self.temporalWarmRequest = nilself.pronunciationProfilesToWarm = []self.edgeReferenceCache.removeAll()self.temporalReferenceCache.removeAll()self.isWordBoostingActive = falseself.boostedVocabularyTermsCount = 0self.boostedTermLookup = []++ let version: AsrModelVersion = selectedModel == .parakeetTDTv2 ? .v2 : .v3+ let directory = AsrModels.defaultCacheDirectory(for: version)+ try await Task.detached(priority: .userInitiated) {+ if FileManager.default.fileExists(atPath: directory.path) {+ try FileManager.default.removeItem(at: directory)+ }+ }.value+ DebugLogger.shared.info("FluidAudioProvider: Deleted cache for \(selectedModel.displayName)", source: "FluidAudioProvider")}/// Provides direct access to the underlying AsrManager for advanced use casesdiff --git a/Sources/Fluid/Services/LLMClient.swift b/Sources/Fluid/Services/LLMClient.swiftindex d3ed8ee6..6e516f64 100644--- a/Sources/Fluid/Services/LLMClient.swift+++ b/Sources/Fluid/Services/LLMClient.swift@@ -296,7 +296,7 @@ final nonisolated class LLMClient: @unchecked Sendable {if baseURL.contains("/chat/completions") {return baseURL.replacingOccurrences(of: "/chat/completions", with: "/responses")}- return Self.appendingPath("responses", to: baseURL)+ return self.appendingPath("responses", to: baseURL)}if baseURL.contains("/chat/completions") ||@@ -305,7 +305,7 @@ final nonisolated class LLMClient: @unchecked Sendable {{return baseURL}- return Self.appendingPath("chat/completions", to: baseURL)+ return self.appendingPath("chat/completions", to: baseURL)}static func shouldUseResponsesAPI(baseURL: String, model: String) -> Bool {diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingNemotronModelLocator.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingNemotronModelLocator.swiftindex ba73bbe5..4208614f 100644--- a/Sources/Fluid/Services/Meeting/Backend/MeetingNemotronModelLocator.swift+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingNemotronModelLocator.swift@@ -126,8 +126,28 @@ nonisolated struct MeetingNemotronModelLocator: MeetingNemotronModelLocating {}throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packageNotDirectory")}- guard url.resolvingSymlinksInPath().standardizedFileURL == url else {- throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packagePathContainsSymlink")+ // URL resolution also restores on-disk capitalization on case-insensitive volumes.+ // A home path such as /Users/Gabriel may legitimately resolve to /Users/gabriel.+ // Allow only case changes in real directory entries, not links whose targets happen+ // to differ only by case. Preserve Foundation's handling of system aliases like /var.+ let resolved = url.resolvingSymlinksInPath().standardizedFileURL+ if resolved != url {+ let components = url.pathComponents+ let resolvedComponents = resolved.pathComponents+ guard components.count == resolvedComponents.count else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packagePathContainsSymlink")+ }+ var prefix = URL(fileURLWithPath: "/", isDirectory: true)+ for (component, resolvedComponent) in zip(components.dropFirst(), resolvedComponents.dropFirst()) {+ prefix.appendPathComponent(component, isDirectory: true)+ guard component != resolvedComponent else { continue }+ let attributes = try manager.attributesOfItem(atPath: prefix.path)+ guard component.caseInsensitiveCompare(resolvedComponent) == .orderedSame,+ attributes[.type] as? FileAttributeType == .typeDirectory+ else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packagePathContainsSymlink")+ }+ }}var totalByteCount: Int64 = 0diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swiftindex 0bf3fd82..b8954267 100644--- a/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift@@ -1,7 +1,7 @@import Foundation// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the local composite backend.-// Parakeet TDT v2 produces word-timed ASR; Nemotron-3 produces per-epoch speaker activity. The+// Parakeet TDT v2/v3 produce word-timed ASR; Nemotron-3 produces per-epoch speaker activity. The// backend owns orchestration — per-epoch materialization, unit construction, slot assignment and// exactly-tiling coverage receipts — while the host-injected runtime owns the two model// capabilities. It never touches the filesystem outside the frozen request's session directory,@@ -13,16 +13,16 @@ import Foundationfinal class MeetingParakeetNemotronBackend: MeetingTranscriptionBackend {static let descriptor = MeetingBackendDescriptor(id: .parakeetNemotron,- version: "4",+ version: "5",execution: .local,- supportedLanguageCodes: ["en"],+ supportedLanguageCodes: VoiceEngineLanguageCatalog.parakeetV3LanguageIDs,supportedTrackKinds: Set(MeetingAudioTrackKind.allCases),supportedFinalPrecisions: [.word, .utterance],resultContract: .canonicalEvidence,knownLimits: ["Nemotron-3 has 8 speaker slots per analysis epoch; a ninth voice is not reliably announced or separated.","Speaker slots are epoch-scoped; conservative local voice matching can reconnect identities across epochs of the same track.",- "English only; the fixed Parakeet TDT v2 meeting policy rejects other requested options.",+ "Parakeet TDT v2 handles English; v3 handles the supported European languages.","When ASR returns text without usable word timings, one utterance covering the epoch is emitted instead of fabricated words.","Local Nemotron model must be installed before planning. Voice matching downloads its local embedding model on first use.",],@@ -55,7 +55,10 @@ final class MeetingParakeetNemotronBackend: MeetingTranscriptionBackend {languageCode: request.session.languageCode)}- // The fixed meeting Parakeet v2 policy rejects unsupported requested options explicitly+ guard request.configuration.languageCode == request.session.languageCode else {+ throw MeetingProviderOptionsError.unsupportedLanguageCode(request.configuration.languageCode)+ }+ // The pinned meeting provider policy rejects unsupported requested options explicitly// (plan §5): no coercion of another model or feature into this backend._ = try MeetingProviderOptions.resolve(request.configuration)// Model readiness is a precondition of planning; execute performs no downloads.diff --git a/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTranscriptionCoordinator.swift b/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTranscriptionCoordinator.swiftindex 64bd402b..dfb2f07d 100644--- a/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTranscriptionCoordinator.swift+++ b/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTranscriptionCoordinator.swift@@ -61,7 +61,11 @@ final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable)}- func start(mode: MeetingCaptureMode) {+ func start(mode: MeetingCaptureMode, languageCode: String = "en") {+ guard languageCode == "en" else {+ self.publish { $0.settingAvailability(.unavailable(reason: "Live captions support English only. Your transcript will be generated after recording.")) }+ return+ }#if arch(arm64)guard Self.isMemorySufficient(physicalMemory: ProcessInfo.processInfo.physicalMemory) else {self.diag(@@ -89,15 +93,19 @@ final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable#endif}- /// The capture-tee entry point. Copies the sample immediately, then hands it to the matching+ /// The capture-tee entry point. Copies PCM only for an active engine, then hands it to the/// track's bounded queue — never retains the `CMSampleBuffer` beyond this call.func offer(kind: MeetingAudioTrackKind, sampleBuffer: CMSampleBuffer) {#if arch(arm64)+ let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)+ guard pts.isNumeric else { return }+ // Keep the shared capture clock even when this track has no caption engine.+ self.originBox.establish(pts)+ guard self.stateLock.withLock({ kind == .microphone ? self.microphoneEngine != nil : self.applicationEngine != nil }) else { return }guard let sample = MeetingLiveSampleCopy.copy(sampleBuffer) else {self.diag("[live/tee] sample copy FAILED kind=\(kind)")return}- self.originBox.establish(sample.pts)let engine: MeetingLiveTrackEngine? = self.stateLock.withLock { () -> MeetingLiveTrackEngine? inlet count = (self.offerCounts[kind] ?? 0) + 1self.offerCounts[kind] = countdiff --git a/Sources/Fluid/Services/Meeting/MeetingModels.swift b/Sources/Fluid/Services/Meeting/MeetingModels.swiftindex ca05f90b..2ac38ba5 100644--- a/Sources/Fluid/Services/Meeting/MeetingModels.swift+++ b/Sources/Fluid/Services/Meeting/MeetingModels.swift@@ -140,6 +140,7 @@ nonisolated struct MeetingRecordingDefaults: Codable, Equatable, Sendable {var microphoneCaptureDeviceID: String?var microphoneCoreAudioUID: String?var microphoneRole: MeetingMicrophoneRole+ var languageCode: String? = nilstatic let unconfigured = Self(isConfigured: false,@@ -270,6 +271,7 @@ nonisolated struct MeetingCaptureConfiguration: Codable, Equatable, Sendable {var application: MeetingApplicationIdentity?var microphone: MeetingMicrophoneIdentityvar chunkDuration: TimeInterval+ var timestampDefaultTitle: Bool? = nilinit(mode: MeetingCaptureMode,@@ -278,7 +280,8 @@ nonisolated struct MeetingCaptureConfiguration: Codable, Equatable, Sendable {platform: MeetingPlatformProfile? = nil,application: MeetingApplicationIdentity? = nil,microphone: MeetingMicrophoneIdentity,- chunkDuration: TimeInterval = Self.defaultChunkDuration+ chunkDuration: TimeInterval = Self.defaultChunkDuration,+ timestampDefaultTitle: Bool = false) {self.mode = modeself.title = title@@ -287,10 +290,11 @@ nonisolated struct MeetingCaptureConfiguration: Codable, Equatable, Sendable {self.application = applicationself.microphone = microphoneself.chunkDuration = max(60, chunkDuration)+ self.timestampDefaultTitle = timestampDefaultTitle}func validate() throws {- guard self.languageCode == "en" else {+ guard VoiceEngineLanguageCatalog.parakeetV3LanguageIDs.contains(self.languageCode) else {throw MeetingModelValidationError.unsupportedLanguage}guard !self.microphone.captureDeviceID.isEmpty else {@@ -773,6 +777,8 @@ nonisolated struct MeetingTranscriptSegment: Codable, Identifiable, Equatable, Svar sourceTrackID: MeetingAudioTrackIDvar speakerID: SessionSpeakerID?var text: String+ /// The initial ASR wording is retained when a user corrects this turn.+ var originalText: String? = nilvar revision: Intvar status: MeetingTranscriptStatusvar overlap: MeetingTranscriptOverlap@@ -863,6 +869,8 @@ nonisolated struct MeetingSession: Codable, Identifiable, Equatable, Sendable {var schemaVersion: Intvar id: MeetingSessionIDvar title: String+ /// Present only for automatically named recordings; cleared when the user renames one.+ var defaultTitleBase: String? = nilvar languageCode: Stringvar mode: MeetingCaptureModevar platform: MeetingPlatformProfile?@@ -907,7 +915,10 @@ nonisolated struct MeetingSession: Codable, Identifiable, Equatable, Sendable {) {self.schemaVersion = Self.currentSchemaVersionself.id = id- self.title = configuration.title+ self.defaultTitleBase = configuration.timestampDefaultTitle == true ? configuration.title : nil+ self.title = self.defaultTitleBase.map {+ "\($0) · \(startedAt.formatted(.dateTime.year().month(.abbreviated).day().hour().minute()))"+ } ?? configuration.titleself.languageCode = configuration.languageCodeself.mode = configuration.modeself.platform = configuration.platform@@ -1037,7 +1048,7 @@ nonisolated struct MeetingSession: Codable, Identifiable, Equatable, Sendable {else {throw MeetingModelValidationError.unsupportedSchema(self.schemaVersion)}- guard self.languageCode == "en" else {+ guard VoiceEngineLanguageCatalog.parakeetV3LanguageIDs.contains(self.languageCode) else {throw MeetingModelValidationError.unsupportedLanguage}guard !self.selectedMicrophone.captureDeviceID.isEmpty else {@@ -1182,6 +1193,8 @@ nonisolated enum MeetingDomainError: LocalizedError, Equatable {case cannotMergeSpeakerWithItselfcase cannotMergeSpeakerscase emptyMeetingTitle+ case emptyTranscriptText+ case staleTranscriptEditvar errorDescription: String? {switch self {@@ -1199,6 +1212,10 @@ nonisolated enum MeetingDomainError: LocalizedError, Equatable {return "A speaker can't be merged into itself."case .cannotMergeSpeakers:return "These speakers can't be merged."+ case .emptyTranscriptText:+ return "Transcript text cannot be empty."+ case .staleTranscriptEdit:+ return "This paragraph changed while you were editing. Reopen it and try again."case .emptyMeetingTitle:return "Meeting title cannot be empty."}@@ -1232,7 +1249,7 @@ nonisolated enum MeetingModelValidationError: LocalizedError, Equatable {case let .unsupportedSchema(version):return "Unsupported meeting schema version \(version)."case .unsupportedLanguage:- return "Meeting transcription currently supports English only."+ return "Choose a supported meeting language from Recording settings."case .missingMicrophone:return "A microphone must be selected."case .missingOnlineApplication:diff --git a/Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swift b/Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swiftindex 13e97465..fded7aa1 100644--- a/Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swift+++ b/Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swift@@ -37,7 +37,7 @@ nonisolated struct MeetingFinalProcessingConfiguration: Equatable, Sendable {let pipelineVersion: Intinit(- asrModel: String = Self.defaultASRModel,+ asrModel: String? = nil,languageCode: String = Self.defaultLanguageCode,vocabularyBoostingEnabled: Bool = false,pronunciationMatchingEnabled: Bool = false,@@ -46,7 +46,7 @@ nonisolated struct MeetingFinalProcessingConfiguration: Equatable, Sendable {diarizationFingerprint: String = MeetingProcessingCheckpoint.currentDiarizationFingerprint,pipelineVersion: Int = Self.defaultPipelineVersion) {- self.asrModel = asrModel+ self.asrModel = asrModel ?? (languageCode == Self.defaultLanguageCode ? Self.defaultASRModel : "parakeet-tdt")self.languageCode = languageCodeself.vocabularyBoostingEnabled = vocabularyBoostingEnabledself.pronunciationMatchingEnabled = pronunciationMatchingEnableddiff --git a/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift b/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swiftindex ff57e821..4a28623b 100644--- a/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift+++ b/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift@@ -1328,7 +1328,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {private let asrServiceProvider: @MainActor () -> ASRServiceprivate let serializationGate: MeetingProcessingSerializationGateprivate let backendRegistry: MeetingTranscriptionBackendRegistry- private let backendIDProvider: @MainActor () -> MeetingBackendID+ private let backendIDProvider: @MainActor (String) -> MeetingBackendID/// Canonical path only: observes chunk files for the analysis manifest. `nil` uses the real/// filesystem observer; tests inject fixture observations instead of writing audio.private let chunkObserver: (any MeetingChunkAudioObserving)?@@ -1380,14 +1380,18 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {// otherwise the user preference. An unknown selection is rejected in `process`, never// quietly replaced.if let backendID {- self.backendIDProvider = { backendID }+ self.backendIDProvider = { _ in backendID }} else if let backendIDProvider {- self.backendIDProvider = backendIDProvider+ self.backendIDProvider = { _ in backendIDProvider() }} else if let backendRegistry {let registryDefault = backendRegistry.defaultBackendID- self.backendIDProvider = { registryDefault }+ self.backendIDProvider = { _ in registryDefault }} else {- self.backendIDProvider = { SettingsStore.shared.meetingTranscriptionBackendID }+ self.backendIDProvider = { languageCode in+ let saved = SettingsStore.shared.meetingTranscriptionBackendID+ // Preserve English rollback settings; non-English recordings need the current backend.+ return saved == .legacyCompatibility && languageCode != "en" ? .productionDefault : saved+ }}}@@ -1396,7 +1400,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {sessionDirectory: URL,progress: @escaping @MainActor (MeetingProcessingStage) -> Void) async throws -> MeetingProcessingResult {- guard session.languageCode == "en" else {+ guard VoiceEngineLanguageCatalog.parakeetV3LanguageIDs.contains(session.languageCode) else {throw MeetingProcessingError.unsupportedLanguage}guard session.audioTracks.contains(where: { !$0.chunks.isEmpty }) else {@@ -1406,7 +1410,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {// The selection is read exactly once, here, and every later decision in this attempt uses// the local copy. Re-reading the preference after an await could split one attempt across// two backends — planning under one, failing the legacy callback against another.- let backendID = self.backendIDProvider()+ let backendID = self.backendIDProvider(session.languageCode)DebugLogger.shared.info("Meeting final processing selected backend=\(backendID.rawValue)",source: "MeetingProcessingPipeline"@@ -3155,7 +3159,7 @@ nonisolated enum MeetingProcessingError: LocalizedError {var errorDescription: String? {switch self {case .unsupportedLanguage:- return "Meeting transcription currently supports English only."+ return "Choose a supported meeting language from Recording settings."case .noRecoverableAudio:return "No finalized meeting audio is available to transcribe."case .dictationActive:diff --git a/Sources/Fluid/Services/Meeting/MeetingSegmentPlayback.swift b/Sources/Fluid/Services/Meeting/MeetingSegmentPlayback.swiftnew file mode 100644index 00000000..16cd34d6--- /dev/null+++ b/Sources/Fluid/Services/Meeting/MeetingSegmentPlayback.swift@@ -0,0 +1,267 @@+import AVFoundation+import Combine+import Foundation++/// Only the expanded player observes the clock; transcript rows do not redraw every tick.+@MainActor+final class MeetingPlaybackProgress: ObservableObject {+ @Published var elapsed: Double = 0+ @Published var duration: Double = 0+ @Published var isPlaying = false+}++/// One player for the visible transcript. Never changes capture, speaker or persisted state.+@MainActor+final class MeetingSegmentPlayback: ObservableObject {+ @Published private(set) var activeSegmentID: MeetingTranscriptSegmentID?+ @Published private(set) var isLoading = false+ @Published private(set) var errorMessage: String?+ let progress = MeetingPlaybackProgress()+ private var timeObserver: Any?+ private var isSeeking = false+ private var seekRevision = 0+ private var player: AVPlayer?+ private var loadTask: Task<Void, Never>?+ private var endObserver: NSObjectProtocol?+ private var failureObserver: NSObjectProtocol?+ private var statusObserver: NSKeyValueObservation?+ private var requestID = UUID()++ func toggle(sessionID: MeetingSessionID, segmentID: MeetingTranscriptSegmentID) {+ let wasActive = self.activeSegmentID == segmentID+ if wasActive {+ self.togglePause()+ return+ }+ self.stop()+ self.activeSegmentID = segmentID+ self.isLoading = true+ let requestID = self.requestID+ self.loadTask = Task { [weak self] in+ do {+ guard let session = try await MeetingSessionStore.shared.load(id: sessionID),+ let directory = try await MeetingSessionStore.shared.existingSessionDirectory(for: sessionID),+ let segment = session.transcriptSegments.first(where: { $0.id == segmentID })+ else { throw MeetingSegmentPlaybackError.unavailable }+ let composition = try await Self.composition(session: session, segment: segment, directory: directory)+ try Task.checkCancellation()+ guard let self, self.requestID == requestID else { return }+ defer { self.loadTask = nil }+ let item = AVPlayerItem(asset: composition)+ let player = AVPlayer(playerItem: item)+ self.player = player+ self.progress.duration = composition.duration.seconds+ self.isLoading = false+ self.timeObserver = player.addPeriodicTimeObserver(+ forInterval: CMTime(seconds: 0.2, preferredTimescale: 600), queue: .main+ ) { [weak self] time in+ Task { @MainActor [weak self] in+ guard let self, self.requestID == requestID, !self.isSeeking, time.seconds.isFinite else { return }+ self.progress.elapsed = min(max(0, time.seconds), self.progress.duration)+ }+ }+ self.endObserver = NotificationCenter.default.addObserver(+ forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main+ ) { [weak self] _ in+ Task { @MainActor [weak self] in+ guard let self, self.requestID == requestID else { return }+ guard !self.isSeeking else { return }+ self.player?.pause()+ self.progress.isPlaying = false+ self.progress.elapsed = self.progress.duration+ }+ }+ self.failureObserver = NotificationCenter.default.addObserver(+ forName: .AVPlayerItemFailedToPlayToEndTime, object: item, queue: .main+ ) { [weak self] _ in+ Task { @MainActor [weak self] in+ guard let self, self.requestID == requestID else { return }+ self.stop()+ self.errorMessage = "This audio chunk could not be played."+ }+ }+ self.statusObserver = item.observe(\.status, options: [.initial, .new]) { [weak self] item, _ in+ guard item.status == .failed else { return }+ Task { @MainActor [weak self] in+ guard let self, self.requestID == requestID else { return }+ self.stop()+ self.errorMessage = "This audio chunk could not be played."+ }+ }+ self.progress.isPlaying = true+ player.play()+ } catch {+ guard let self, !Task.isCancelled, self.requestID == requestID else { return }+ self.stop()+ self.errorMessage = "This audio chunk is unavailable. Its recording may have been deleted or its timing could not be verified."+ }+ }+ }++ func togglePause() {+ guard let player, !self.isLoading else { return }+ if self.progress.isPlaying {+ player.pause()+ self.progress.isPlaying = false+ } else {+ self.progress.isPlaying = true+ if self.progress.elapsed >= self.progress.duration - 0.05 {+ self.seek(to: 0)+ } else if !self.isSeeking {+ player.play()+ }+ }+ }++ func seek(to seconds: Double) {+ guard let player, seconds.isFinite, self.progress.duration > 0 else { return }+ self.seekRevision += 1+ let revision = self.seekRevision+ let requestID = self.requestID+ let position = min(max(0, seconds), self.progress.duration)+ self.isSeeking = true+ self.progress.elapsed = position+ player.pause()+ player.seek(to: CMTime(seconds: position, preferredTimescale: 48_000), toleranceBefore: .zero, toleranceAfter: .zero) { [weak self] finished in+ Task { @MainActor [weak self] in+ guard let self, self.requestID == requestID, self.seekRevision == revision else { return }+ self.isSeeking = false+ if finished, self.progress.isPlaying, position < self.progress.duration {+ self.player?.play()+ } else if position >= self.progress.duration || !finished {+ self.progress.isPlaying = false+ }+ }+ }+ }++ func skip(by seconds: Double) {+ self.seek(to: self.progress.elapsed + seconds)+ }++ func stop() {+ self.requestID = UUID()+ self.errorMessage = nil+ self.loadTask?.cancel()+ self.loadTask = nil+ self.player?.pause()+ if let timeObserver { self.player?.removeTimeObserver(timeObserver) }+ self.timeObserver = nil+ self.isSeeking = false+ self.seekRevision += 1+ self.progress.isPlaying = false+ self.progress.elapsed = 0+ self.progress.duration = 0+ self.statusObserver = nil+ if let endObserver { NotificationCenter.default.removeObserver(endObserver) }+ self.endObserver = nil+ if let failureObserver { NotificationCenter.default.removeObserver(failureObserver) }+ self.failureObserver = nil+ self.player?.replaceCurrentItem(with: nil)+ self.player = nil+ self.activeSegmentID = nil+ self.isLoading = false+ }++ private nonisolated static func composition(+ session: MeetingSession, segment: MeetingTranscriptSegment, directory: URL+ ) async throws -> AVMutableComposition {+ // Sidecar verification and path resolution are disk work, outside the main actor.+ let plan = try await Task.detached(priority: .userInitiated) {+ try MeetingSegmentPlaybackPlan.slices(session: session, segment: segment, directory: directory)+ }.value+ try Task.checkCancellation()+ let composition = AVMutableComposition()+ guard let output = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)+ else { throw MeetingSegmentPlaybackError.unavailable }+ var cursor = CMTime.zero+ for slice in plan {+ try Task.checkCancellation()+ let asset = AVURLAsset(url: slice.url)+ let deadline = Task {+ do { try await Task.sleep(for: .seconds(15)) } catch { return }+ asset.cancelLoading()+ }+ defer { deadline.cancel() }+ let tracks = try await withTaskCancellationHandler {+ try await asset.loadTracks(withMediaType: .audio)+ } onCancel: { asset.cancelLoading() }+ guard let track = tracks.first else { throw MeetingSegmentPlaybackError.unavailable }+ let range = CMTimeRange(+ start: CMTime(seconds: slice.start, preferredTimescale: 48_000),+ duration: CMTime(seconds: slice.end - slice.start, preferredTimescale: 48_000)+ )+ try output.insertTimeRange(range, of: track, at: cursor)+ cursor = CMTimeAdd(cursor, range.duration)+ }+ return composition+ }+}++nonisolated enum MeetingSegmentPlaybackError: Error {+ case unavailable+}++nonisolated enum MeetingSegmentPlaybackPlan {+ struct Slice: Equatable {+ let url: URL+ let start: Double+ let end: Double+ }++ static func slices(session: MeetingSession, segment: MeetingTranscriptSegment, directory: URL) throws -> [Slice] {+ guard session.retention.audioDeletedAt == nil,+ segment.start.seconds.isFinite, segment.end.seconds.isFinite,+ segment.end > segment.start+ else { throw MeetingSegmentPlaybackError.unavailable }+ if let reference = session.resultSidecarReference {+ guard session.transcriptTimeDomain == .meetingRelative,+ let attempt = session.processingAttempts.last(where: {+ MeetingResultSidecarStore.fileName(for: $0.id) == reference.fileName+ }), let backendID = attempt.backendID+ else { throw MeetingSegmentPlaybackError.unavailable }+ let sidecar = try MeetingResultSidecarStore(sessionDirectory: directory).read(+ expectedAttemptID: attempt.id, expectedBackendID: MeetingBackendID(rawValue: backendID), reference: reference+ )+ return try self.slices(segment: segment, spans: sidecar.analysisManifest.allSpans, directory: directory)+ }+ // Legacy transcripts use chunk-relative offsets. Refuse drift-corrected legacy audio+ // without a verified span mapping rather than silently playing the wrong words.+ guard let track = session.audioTracks.first(where: { $0.id == segment.sourceTrackID }),+ track.clockDrift == nil,+ track.captureEras?.contains(where: { $0.clockDrift != nil }) != true+ else { throw MeetingSegmentPlaybackError.unavailable }+ let origin = MeetingAnalysisManifest.presentationOrigin(of: session)+ var slices: [Slice] = []+ for chunk in track.chunks.sorted(by: { $0.presentationStart < $1.presentationStart }) {+ let offset = chunk.presentationStart.seconds - origin+ let start = max(segment.start.seconds, offset)+ let end = min(segment.end.seconds, chunk.presentationEnd.seconds - origin)+ guard end > start, let path = MeetingAudioPresentation.relativePlaybackPath(for: chunk) else { continue }+ let url = try MeetingChunkPathConfinement.containedURL(sessionDirectory: directory, relativePath: path)+ slices.append(Slice(url: url, start: start - offset, end: end - offset))+ }+ guard !slices.isEmpty else { throw MeetingSegmentPlaybackError.unavailable }+ return slices+ }++ static func slices(segment: MeetingTranscriptSegment, spans: [MeetingAnalysisSpan], directory: URL) throws -> [Slice] {+ var slices: [Slice] = []+ for span in spans.filter({ $0.trackID == segment.sourceTrackID }).sorted(by: { $0.presentationInterval.start < $1.presentationInterval.start }) {+ let start = max(segment.start.seconds, span.presentationInterval.start)+ let end = min(segment.end.seconds, span.presentationInterval.end)+ guard end > start else { continue }+ let rate = span.presentationMapping.rateRatio+ guard rate.isFinite, rate > 0 else { throw MeetingSegmentPlaybackError.unavailable }+ let sourceStart = span.sourceLocalInterval.start + (start - span.presentationInterval.start) / rate+ let sourceEnd = min(span.sourceLocalInterval.end, span.sourceLocalInterval.start + (end - span.presentationInterval.start) / rate)+ guard sourceStart.isFinite, sourceEnd.isFinite, sourceStart >= 0, sourceEnd > sourceStart else {+ throw MeetingSegmentPlaybackError.unavailable+ }+ let url = try MeetingChunkPathConfinement.containedURL(sessionDirectory: directory, relativePath: span.chunk.relativeFilePath)+ slices.append(Slice(url: url, start: sourceStart, end: sourceEnd))+ }+ guard !slices.isEmpty else { throw MeetingSegmentPlaybackError.unavailable }+ return slices+ }+}diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swiftindex 3d6ef98b..e81cb98b 100644--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift@@ -164,6 +164,7 @@ final class MeetingSessionCoordinator: ObservableObject {private var retentionTimerTask: Task<Void, Never>?private enum TranscriptCorrection {+ case editText(segmentID: MeetingTranscriptSegmentID, previousText: String, previousOriginalText: String?, previousRevision: Int)case rename(speakerID: SessionSpeakerID, previousName: String)case reassign(segmentID: MeetingTranscriptSegmentID,@@ -322,8 +323,10 @@ final class MeetingSessionCoordinator: ObservableObject {return MeetingCaptureConfiguration(mode: mode,title: title,+ languageCode: SettingsStore.shared.meetingRecordingDefaults.languageCode ?? "en",application: application,- microphone: microphone+ microphone: microphone,+ timestampDefaultTitle: true)}@@ -445,7 +448,7 @@ final class MeetingSessionCoordinator: ObservableObject {}self.liveTranscriptionCoordinator = liveTranscriptionCoordinatorself.liveTranscript = .empty- liveTranscriptionCoordinator.start(mode: configuration.mode)+ liveTranscriptionCoordinator.start(mode: configuration.mode, languageCode: configuration.languageCode)do {try await self.store.create(session)@@ -869,6 +872,31 @@ final class MeetingSessionCoordinator: ObservableObject {if self.latestCompletedSession?.id == session.id { self.latestCompletedSession = session }}+ @discardableResult+ func editTranscriptText(sessionID: MeetingSessionID, segmentID: MeetingTranscriptSegmentID, text: String, expectedRevision: Int) async throws -> MeetingSession {+ try await self.performCorrection(sessionID: sessionID) { session in+ guard let index = session.transcriptSegments.firstIndex(where: { $0.id == segmentID }) else {+ throw MeetingDomainError.segmentNotFound+ }+ let previous = session.transcriptSegments[index]+ guard previous.revision == expectedRevision else { throw MeetingDomainError.staleTranscriptEdit }+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else { throw MeetingDomainError.emptyTranscriptText }+ let inverse = TranscriptCorrection.editText(+ segmentID: segmentID,+ previousText: previous.text,+ previousOriginalText: previous.originalText,+ previousRevision: previous.revision+ )+ guard trimmed != previous.text else { return inverse }+ session.transcriptSegments[index].originalText = previous.originalText ?? previous.text+ session.transcriptSegments[index].text = trimmed+ session.transcriptSegments[index].revision += 1+ session.updatedAt = Date()+ return inverse+ }+ }+@discardableResultfunc renameSpeaker(sessionID: MeetingSessionID, speakerID: SessionSpeakerID, to displayName: String) async throws -> MeetingSession {try await self.performCorrection(sessionID: sessionID) { session in@@ -1012,6 +1040,7 @@ final class MeetingSessionCoordinator: ObservableObject {guard target.title != trimmed else { return target }target.title = trimmed+ target.defaultTitleBase = niltarget.updatedAt = Date()try await self.store.save(target)@@ -1182,6 +1211,12 @@ final class MeetingSessionCoordinator: ObservableObject {/// False when the inverse's target no longer exists; caller must not save or re-push.private static func applyInverse(_ correction: TranscriptCorrection, to session: inout MeetingSession) -> Bool {switch correction {+ case let .editText(segmentID, previousText, previousOriginalText, previousRevision):+ guard let index = session.transcriptSegments.firstIndex(where: { $0.id == segmentID }) else { return false }+ session.transcriptSegments[index].text = previousText+ session.transcriptSegments[index].originalText = previousOriginalText+ session.transcriptSegments[index].revision = previousRevision+ return truecase let .rename(speakerID, previousName):guard let index = session.speakers.firstIndex(where: { $0.id == speakerID }) else { return false }session.speakers[index].displayName = previousNamediff --git a/Sources/Fluid/Services/NemotronProvider.swift b/Sources/Fluid/Services/NemotronProvider.swiftindex 185e8280..86f6f09b 100644--- a/Sources/Fluid/Services/NemotronProvider.swift+++ b/Sources/Fluid/Services/NemotronProvider.swift@@ -331,15 +331,17 @@ final class NemotronProvider: TranscriptionProvider {if let manager = self.manager {await self.stopComponentProfilingIfNeeded(on: manager)}- if let dir = self.cacheDirectory {- if FileManager.default.fileExists(atPath: dir.path) {- try FileManager.default.removeItem(at: dir)- }- }self.manager = nilself.isReady = falseself.streamedSampleCount = 0self.activeLanguageCode = nil+ if let directory = self.cacheDirectory {+ try await Task.detached(priority: .userInitiated) {+ if FileManager.default.fileExists(atPath: directory.path) {+ try FileManager.default.removeItem(at: directory)+ }+ }.value+ }}private func transcribeBatched(_ samples: [Float]) async throws -> ASRTranscriptionResult {diff --git a/Sources/Fluid/Services/ParakeetRealtimeProvider.swift b/Sources/Fluid/Services/ParakeetRealtimeProvider.swiftindex b3e7afc2..b784a327 100644--- a/Sources/Fluid/Services/ParakeetRealtimeProvider.swift+++ b/Sources/Fluid/Services/ParakeetRealtimeProvider.swift@@ -156,13 +156,15 @@ final class ParakeetRealtimeProvider: TranscriptionProvider {}func clearCache() async throws {- let cacheRoot = Self.cacheRootDirectory()- if FileManager.default.fileExists(atPath: cacheRoot.path) {- try FileManager.default.removeItem(at: cacheRoot)- }self.isReady = falseself.streamedSampleCount = 0self.engine = nil+ let cacheRoot = Self.cacheRootDirectory()+ try await Task.detached(priority: .userInitiated) {+ if FileManager.default.fileExists(atPath: cacheRoot.path) {+ try FileManager.default.removeItem(at: cacheRoot)+ }+ }.value}private func requireEngine() throws -> StreamingEouAsrManager {diff --git a/Sources/Fluid/Services/SimpleUpdater.swift b/Sources/Fluid/Services/SimpleUpdater.swiftindex e010fd7e..1f2ccdf2 100644--- a/Sources/Fluid/Services/SimpleUpdater.swift+++ b/Sources/Fluid/Services/SimpleUpdater.swift@@ -125,7 +125,7 @@ final class SimpleUpdater {}static let shared = SimpleUpdater()- private init() {}+ init() {}private let fileManager = FileManager.defaultprivate let maxRollbackBackups = 3@@ -469,7 +469,7 @@ final class SimpleUpdater {// MARK: - Helpers- private func showUpdateInstallStatus(version: String) {+ func showUpdateInstallStatus(version: String) {guard self.updateStatusWindow == nil else { return }let panel = NSPanel(@@ -479,6 +479,7 @@ final class SimpleUpdater {defer: false)panel.title = "Installing FluidVoice \(version)"+ panel.isReleasedWhenClosed = falsepanel.level = .floatingpanel.isOpaque = falsepanel.backgroundColor = .clear@@ -528,6 +529,11 @@ final class SimpleUpdater {private func resetUpdateOperation() {self.updateOperationGate.finish()+ self.dismissUpdateInstallStatus()+ }++ func dismissUpdateInstallStatus() {+ self.updateStatusWindow?.orderOut(nil)self.updateStatusWindow?.close()self.updateStatusWindow = nil}@@ -890,6 +896,11 @@ final class SimpleUpdater {finalAppURL = installedAppURL}+ // 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 launchingDispatchQueue.main.async {DebugLogger.shared.info("SimpleUpdater: Attempting to relaunch app at: \(finalAppURL.path)", source: "SimpleUpdater")@@ -919,7 +930,7 @@ final class SimpleUpdater {DebugLogger.shared.info("SimpleUpdater: Successfully relaunched app, terminating old instance", source: "SimpleUpdater")// Give the new instance time to fully start before terminatingDispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {- NSApp.terminate(nil)+ UpdateTerminationScheduler.requestTermination()}}}diff --git a/Sources/Fluid/Services/UpdateTerminationScheduler.swift b/Sources/Fluid/Services/UpdateTerminationScheduler.swiftnew file mode 100644index 00000000..11e6f920--- /dev/null+++ b/Sources/Fluid/Services/UpdateTerminationScheduler.swift@@ -0,0 +1,16 @@+import AppKit++@MainActor+enum UpdateTerminationScheduler {+ static func requestTermination() {+ // AppKit may synchronously pump its termination run loop for .terminateLater.+ // Calling terminate from a main-queue block keeps that serial queue occupied,+ // preventing applicationShouldTerminate's MainActor history-save task from running.+ // A run-loop callback leaves the main dispatch queue available for that task.+ RunLoop.main.perform {+ MainActor.assumeIsolated {+ NSApp.terminate(nil)+ }+ }+ }+}diff --git a/Sources/Fluid/Services/WhisperProvider.swift b/Sources/Fluid/Services/WhisperProvider.swiftindex f15b0651..b8274fd4 100644--- a/Sources/Fluid/Services/WhisperProvider.swift+++ b/Sources/Fluid/Services/WhisperProvider.swift@@ -341,21 +341,19 @@ final class WhisperProvider: TranscriptionProvider {func clearCache() async throws {self.unloadModel()-- if FileManager.default.fileExists(atPath: self.modelURL.path) {- try FileManager.default.removeItem(at: self.modelURL)- }- if let legacyModelURL, FileManager.default.fileExists(atPath: legacyModelURL.path) {- try FileManager.default.removeItem(at: legacyModelURL)- }- self.removeLegacyModelIfNeeded()-- if FileManager.default.fileExists(atPath: self.modelDirectory.path) {- let contents = try FileManager.default.contentsOfDirectory(atPath: self.modelDirectory.path)- if contents.isEmpty {- try FileManager.default.removeItem(at: self.modelDirectory)+ let files = [self.modelURL, self.legacyModelURL].compactMap { $0 }+ let directory = self.modelDirectory+ try await Task.detached(priority: .userInitiated) {+ let manager = FileManager.default+ for file in files where manager.fileExists(atPath: file.path) {+ try manager.removeItem(at: file)}- }+ if manager.fileExists(atPath: directory.path),+ try manager.contentsOfDirectory(atPath: directory.path).isEmpty+ {+ try manager.removeItem(at: directory)+ }+ }.value}private func downloadModel(progressHandler: ((Double) -> Void)?) async throws {diff --git a/Sources/Fluid/Theme/Components/FluidDropdown.swift b/Sources/Fluid/Theme/Components/FluidDropdown.swiftindex f7a42325..60d3efea 100644--- a/Sources/Fluid/Theme/Components/FluidDropdown.swift+++ b/Sources/Fluid/Theme/Components/FluidDropdown.swift@@ -59,31 +59,12 @@ private struct FluidDropdownControlStyle: ViewModifier {var appearance: FluidDropdownAppearance = .standardvar tone: Color?- @Environment(\.theme) private var theme-- @ViewBuilder func body(content: Content) -> some View {- if self.fillsWidth {- content- .menuStyle(.button)- .buttonStyle(FluidDropdownButtonStyle(fillsWidth: true, appearance: self.appearance, tone: self.tone))- .menuIndicator(.hidden)- .labelsHidden()- } else {- content- .menuStyle(.borderlessButton)- .buttonStyle(.plain)- .menuIndicator(.hidden)- .labelsHidden()- .font(self.appearance == .inline ? self.theme.typography.statement : self.theme.typography.bodySmall)- .foregroundStyle(self.tone ?? self.theme.palette.primaryText)- .padding(.leading, self.appearance == .inline ? 8 : 12)- .padding(.trailing, self.appearance == .inline ? 24 : 30)- .padding(.vertical, self.appearance == .inline ? 8 : 9)- .fluidDropdownSurface(appearance: self.appearance)- .overlay(alignment: .trailing) {- FluidDropdownChevron().padding(.trailing, self.appearance == .inline ? 8 : 12).allowsHitTesting(false)- }- }+ func body(content: Content) -> some View {+ content+ .menuStyle(.button)+ .buttonStyle(FluidDropdownButtonStyle(fillsWidth: self.fillsWidth, appearance: self.appearance, tone: self.tone))+ .menuIndicator(.hidden)+ .labelsHidden()}}@@ -113,8 +94,8 @@ private struct FluidDropdownButtonStyle: ButtonStyle {extension View {/// Apply outside a native menu/picker, rather than inside its label:/// macOS may flatten label styling when building the native control.- /// Full-width selectors use a Menu containing an inline Picker. Native- /// menu Pickers and borderless menus ignore custom ButtonStyle hit geometry.+ /// Use FluidDropdownPicker for selections. Native menu Pickers and+ /// borderless menus ignore custom ButtonStyle hit geometry.func fluidDropdownStyle(fillsWidth: Bool = false, appearance: FluidDropdownAppearance = .standard, tone: Color? = nil) -> some View {modifier(FluidDropdownControlStyle(fillsWidth: fillsWidth, appearance: appearance, tone: tone))}@@ -136,3 +117,30 @@ struct FluidDropdown<Content: View>: View {.frame(width: self.width)}}++/// Native menu pickers ignore custom button hit geometry. Keep the native+/// selection/checkmark behavior inside a Menu whose entire label is clickable.+struct FluidDropdownPicker<Selection: Hashable, Options: View>: View {+ let title: String+ let selectedTitle: String+ @Binding var selection: Selection+ @ViewBuilder let options: () -> Options++ init(_ title: String, selectedTitle: String, selection: Binding<Selection>, @ViewBuilder content: @escaping () -> Options) {+ self.title = title+ self.selectedTitle = selectedTitle+ self._selection = selection+ self.options = content+ }++ var body: some View {+ Menu {+ Picker(self.title, selection: self.$selection, content: self.options)+ .pickerStyle(.inline)+ } label: {+ Text(self.selectedTitle)+ }+ .accessibilityLabel(self.title.isEmpty ? self.selectedTitle : self.title)+ .accessibilityValue(self.selectedTitle)+ }+}diff --git a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swiftindex bd0d28d2..971d5280 100644--- a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift+++ b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift@@ -389,7 +389,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {guard PrivateAIIntegrationService.isModelInstalled(currentModel) else {self.updateConnectionStatus(.failed, for: providerID)- self.setConnectionError("\(currentModel.displayName) is not installed.", for: providerID)+ self.setConnectionError(PrivateAIModelLoadState.missingModelMessage, for: providerID)return false}@@ -823,7 +823,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {return}- if !isLocal && apiKey.isEmpty {+ if !isLocal, apiKey.isEmpty {await MainActor.run {self.updateConnectionStatus(.failed, for: providerID)self.setConnectionError("API key is required for \(providerName). Enter your API key above.", for: providerID)@@ -856,7 +856,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)let fullURL: String- if isAnthropic && !usesResponsesAPI {+ if isAnthropic, !usesResponsesAPI {// Anthropic uses /messages endpoint, not /chat/completionsif endpoint.contains("/messages") {fullURL = endpointdiff --git a/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift b/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swiftindex ad2860f4..bcc4289b 100644--- a/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift+++ b/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift@@ -121,9 +121,10 @@ struct FluidIntelligenceLiveSection<Management: View>: View {private func cardControls(_ model: PrivateAIRegisteredModel) -> some View {let files = self.snapshots[model.id]let selected = model.id == self.controller.privateAISelectedModelID+ let needsDownload = self.controller.privateAILoadState.needsDownload(model.id)// Active = dictation will use this model. Whether it is in memory right now is shown// separately, because the idle unloader frees it and the next dictation reloads it.- let active = selected && self.isVerified && self.controller.routesDictationThroughPrivateAI+ let active = !needsDownload && files?.installed == true && selected && self.isVerified && self.controller.routesDictationThroughPrivateAIlet inMemory = self.controller.privateAILoadState.isLoaded(model.id)let realUpdate = files?.installed == true && self.controller.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailablereturn VStack(alignment: .leading, spacing: 8) {@@ -133,6 +134,11 @@ struct FluidIntelligenceLiveSection<Management: View>: View {.font(self.theme.typography.caption).lineLimit(2)} else if self.controller.privateAILoadState.isLoading(model.id) {Text("Preparing model…").font(self.theme.typography.caption)+ } else if needsDownload {+ Text("Model files are missing. Download again to repair.")+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)+ .fixedSize(horizontal: false, vertical: true)} else if let failure = self.controller.privateAILoadState.failureMessage(for: model.id) {Text(failure).font(self.theme.typography.caption).foregroundStyle(.red).lineLimit(2).help(failure)} else if active {@@ -152,14 +158,14 @@ struct FluidIntelligenceLiveSection<Management: View>: View {Button {guard let files else { return }self.controller.previewModel(model.id)- self.controller.usePreviewModel(isInstalled: files.installed, onReady: {})+ self.controller.usePreviewModel(isInstalled: files.installed && !needsDownload, onReady: {})} label: {- Text(files?.installed == false ? "Download" : "Activate")+ Text(needsDownload ? "Download again" : files?.installed == false ? "Download" : "Activate").font(self.theme.typography.bodyStrong).frame(minWidth: 76, minHeight: 24)}.fluidGlassAction(prominent: true)- .disabled(self.controller.isBusy || files == nil || (files?.installed == false && !model.canDownload))+ .disabled(self.controller.isBusy || files == nil || ((needsDownload || files?.installed == false) && !model.canDownload))if files?.installed == false, let bytes = model.artifact.byteCount, bytes > 0 {Text(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)).font(self.theme.typography.caption)@@ -184,7 +190,7 @@ struct FluidIntelligenceLiveSection<Management: View>: View {self.showsVerificationResult = true})}- .disabled(!selected || files?.installed != true || self.controller.isBusy)+ .disabled(!selected || files?.installed != true || needsDownload || self.controller.isBusy)Button("Deactivate model") {self.controller.deactivateSelectedModel()}diff --git a/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift b/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swiftindex 963a9cba..edb3f634 100644--- a/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift+++ b/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift@@ -2,12 +2,28 @@ import AppKitimport Combineenum PrivateAIModelLoadState: Equatable {+ static let missingModelMessage = "Model file is not installed."+case idle+ case downloadRequired(modelID: String)case downloading(modelID: String, progress: PrivateAIModelDownloadProgress?)case loading(modelID: String)case loaded(modelID: String, latencyMilliseconds: Int?)case failed(modelID: String, message: String)+ func needsDownload(_ modelID: String) -> Bool {+ if case let .downloadRequired(id) = self { return id == modelID }+ return false+ }++ static func failure(modelID: String, message: String) -> Self {+ // Verification crosses the provider bridge as text. Match only its known missing-file errors.+ if message.hasPrefix("Missing local model: ") || message == self.missingModelMessage {+ return .downloadRequired(modelID: modelID)+ }+ return .failed(modelID: modelID, message: message)+ }+func isLoading(_ modelID: String) -> Bool {if case .loading(modelID) = self { return true }return false@@ -203,14 +219,11 @@ final class PrivateAISettingsController: ObservableObject {let message = self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID).isEmpty? "Model downloaded, but verification failed.": self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID)- self.privateAILoadState = .failed(modelID: model.id, message: message)+ self.recordFailure(modelID: model.id, message: message)}} catch {guard self.privateAISelectedModelID == model.id else { return }- self.privateAILoadState = .failed(- modelID: model.id,- message: Self.errorMessage(for: error)- )+ self.recordFailure(modelID: model.id, message: Self.errorMessage(for: error))}self.viewModel.refreshProviderItems()}@@ -294,8 +307,9 @@ final class PrivateAISettingsController: ObservableObject {let message = self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID).isEmpty? "Model verification failed.": self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID)- self.privateAILoadState = .failed(modelID: model.id, message: message)- onCompletion?(message)+ self.recordFailure(modelID: model.id, message: message)+ onCompletion?(self.privateAILoadState.needsDownload(model.id)+ ? "Model files are missing. Download again to repair." : message)}self.viewModel.refreshProviderItems()}@@ -321,6 +335,7 @@ final class PrivateAISettingsController: ObservableObject {func refreshPrivateAILoadState() {guard !self.session.isBusy else { return }if case .failed = self.privateAILoadState { return }+ if case .downloadRequired = self.privateAILoadState { return }let revision = self.session.revisionTask { @MainActor inlet loaded = await PrivateAIIntegrationService.shared.loadedModelState()@@ -338,7 +353,7 @@ final class PrivateAISettingsController: ObservableObject {guard let operation = self.beginOperation(for: model.id) else { return }guard PrivateAIIntegrationService.isModelInstalled(model) else {self.session.finish(operation)- self.privateAILoadState = .failed(modelID: model.id, message: "Model file is not installed.")+ self.recordFailure(modelID: model.id, message: PrivateAIModelLoadState.missingModelMessage)return}@@ -357,17 +372,11 @@ final class PrivateAISettingsController: ObservableObject {case .ready:self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)default:- self.privateAILoadState = .failed(- modelID: model.id,- message: status.message ?? "Model did not report ready."- )+ self.recordFailure(modelID: model.id, message: status.message ?? "Model did not report ready.")}} catch {guard self.privateAISelectedModelID == model.id else { return }- self.privateAILoadState = .failed(- modelID: model.id,- message: Self.errorMessage(for: error)- )+ self.recordFailure(modelID: model.id, message: Self.errorMessage(for: error))}self.viewModel.refreshProviderItems()}@@ -413,6 +422,14 @@ final class PrivateAISettingsController: ObservableObject {}}+ private func recordFailure(modelID: String, message: String) {+ DebugLogger.shared.error("Model operation failed model=\(modelID): \(message)", source: "AISettingsView")+ self.privateAILoadState = .failure(modelID: modelID, message: message)+ if self.privateAILoadState.needsDownload(modelID) {+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)+ }+ }+private static func errorMessage(for error: Error) -> String {if let localizedError = error as? LocalizedError,let description = localizedError.errorDescriptiondiff --git a/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift b/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swiftindex 7fc740c3..8beef037 100644--- a/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift+++ b/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift@@ -12,6 +12,8 @@ final class VoiceEngineSettingsViewModel: ObservableObject {var areSpeechModelActionsBlocked: Bool {self.asr.isRunning+ || self.asr.deletingModelID != nil+ || self.asr.activeExclusiveActivity != nil|| self.downloadingModel != nil|| self.asr.hasActiveModelDownload|| self.asr.hasActiveModelPreparation@@ -28,8 +30,6 @@ final class VoiceEngineSettingsViewModel: ObservableObject {@Published var selectedSpeechProvider: SettingsStore.SpeechModel.Provider@Published var previewSpeechModel: SettingsStore.SpeechModel@Published var showAdvancedSpeechInfo: Bool = false- @Published var suppressSpeechProviderSync: Bool = false- @Published var skipNextSpeechModelSync: Bool = falsevar downloadingModel: SettingsStore.SpeechModel? {guard let modelID = self.asr.downloadingModelId else { return nil }@@ -68,11 +68,6 @@ final class VoiceEngineSettingsViewModel: ObservableObject {}func handleSelectedSpeechModelChange(_ newValue: SettingsStore.SpeechModel) {- if self.skipNextSpeechModelSync {- self.skipNextSpeechModelSync = false- return- }- guard !self.suppressSpeechProviderSync else { return }self.previewSpeechModel = newValueself.setSelectedSpeechProvider(newValue.provider)}@@ -168,32 +163,8 @@ final class VoiceEngineSettingsViewModel: ObservableObject {func deleteSpeechModel(_ model: SettingsStore.SpeechModel) {guard !self.areSpeechModelActionsBlocked else { return }- let previousActive = self.settings.selectedSpeechModel-Task {- let shouldRestore = previousActive != model- await MainActor.run {- if shouldRestore {- self.suppressSpeechProviderSync = true- }- self.settings.selectedSpeechModel = model- self.asr.resetTranscriptionProvider()- }-- defer {- Task { @MainActor in- guard shouldRestore else { return }- self.skipNextSpeechModelSync = true- self.settings.selectedSpeechModel = previousActive- self.asr.resetTranscriptionProvider()- if self.previewSpeechModel == model {- self.previewSpeechModel = model- }- self.suppressSpeechProviderSync = false- }- }-- await self.deleteModels()+ await self.deleteModels(model)}}@@ -240,17 +211,18 @@ final class VoiceEngineSettingsViewModel: ObservableObject {}}- func deleteModels() async {+ func deleteModels(_ model: SettingsStore.SpeechModel? = nil) async {+ let target = model ?? self.settings.selectedSpeechModeldo {- try await self.asr.clearModelCache()- let model = self.settings.selectedSpeechModel- if model.requiresExternalArtifacts {- self.settings.setExternalCoreMLArtifactsDirectory(nil, for: model)- self.asr.resetTranscriptionProvider()- }+ try await self.asr.clearModelCache(for: target)} catch {- DebugLogger.shared.error("Failed to delete models: \(error)", source: "AISettingsView")+ DebugLogger.shared.error("Failed to delete model \(target.displayName): \(error)", source: "AISettingsView")+ self.asr.errorTitle = "Model Deletion Failed"+ self.asr.errorMessage = error.localizedDescription+ self.asr.showError = true}+ // Inactive-model deletion must refresh its card without switching the active model.+ self.objectWillChange.send()}func setSelectedSpeechProvider(_ provider: SettingsStore.SpeechModel.Provider) {diff --git a/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift b/Sources/Fluid/UI/AISettingsView+AIConfiguration.swiftindex 2aa612b7..b5f3400f 100644--- a/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift+++ b/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift@@ -673,7 +673,7 @@ extension AIEnhancementSettingsView {private var privateAIRuntimeSection: some View {let model = self.privateAIController.selectedPrivateAIModellet status = self.privateAIModelStatus(for: model)- let isInstalled = PrivateAIIntegrationService.isModelInstalled(model)+ let isInstalled = !self.privateAIController.privateAILoadState.needsDownload(model.id) && PrivateAIIntegrationService.isModelInstalled(model)let isDownloading = self.privateAIController.privateAILoadState.isDownloading(model.id)let downloadProgress = self.privateAIController.privateAILoadState.downloadProgress(for: model.id)let isLoading = self.privateAIController.privateAILoadState.isLoading(model.id)@@ -841,12 +841,11 @@ extension AIEnhancementSettingsView {}private func privateAIBackendPicker(isBusy: Bool) -> some View {- Picker("", selection: self.privateAIBackendBinding) {+ FluidDropdownPicker("Backend", selectedTitle: self.privateAIBackendBinding.wrappedValue.displayName, selection: self.privateAIBackendBinding) {ForEach(self.privateAISelectableBackendPreferences) { preference inText(preference.displayName).tag(preference)}}- .pickerStyle(.menu).fluidDropdownStyle().labelsHidden().disabled(isBusy)@@ -1030,6 +1029,13 @@ extension AIEnhancementSettingsView {)}+ if self.privateAIController.privateAILoadState.needsDownload(model.id) {+ return PrivateAIProviderModelStatus(+ detail: "Model files are missing. Download again to repair.",+ color: self.theme.palette.secondaryText+ )+ }+if let message = self.privateAIController.privateAILoadState.failureMessage(for: model.id) {return PrivateAIProviderModelStatus(detail: message,@@ -1447,7 +1453,7 @@ extension AIEnhancementSettingsView {: primaryPromptSelection == .default && item.id == self.settings.selectedProviderIDlet fluidModel = self.privateAIController.selectedPrivateAIModellet fluidStatus = self.privateAIModelStatus(for: fluidModel)- let isFluidInstalled = PrivateAIIntegrationService.isModelInstalled(fluidModel)+ let isFluidInstalled = !self.privateAIController.privateAILoadState.needsDownload(fluidModel.id) && PrivateAIIntegrationService.isModelInstalled(fluidModel)let isFluidDownloading = self.privateAIController.privateAILoadState.isDownloading(fluidModel.id)let fluidDownloadProgress = self.privateAIController.privateAILoadState.downloadProgress(for: fluidModel.id)let isFluidLoading = self.privateAIController.privateAILoadState.isLoading(fluidModel.id)@@ -2391,39 +2397,42 @@ extension AIEnhancementSettingsView {.foregroundStyle(.secondary).frame(width: 70, alignment: .trailing)- Picker("", selection: Binding(- get: {- if self.viewModel.editingReasoningParamName == "reasoning_effort" {- return "reasoning_effort"- } else if self.viewModel.editingReasoningParamName == "enable_thinking" {- return "enable_thinking"- } else {- return "custom"- }- },- set: { newValue in- if newValue == "custom" {- if self.viewModel.editingReasoningParamName == "reasoning_effort" ||- self.viewModel.editingReasoningParamName == "enable_thinking"- {- self.viewModel.editingReasoningParamName = ""+ FluidDropdownPicker(+ "Reasoning parameter",+ selectedTitle: ["reasoning_effort", "enable_thinking"].contains(self.viewModel.editingReasoningParamName) ? self.viewModel.editingReasoningParamName : "Custom...",+ selection: Binding(+ get: {+ if self.viewModel.editingReasoningParamName == "reasoning_effort" {+ return "reasoning_effort"+ } else if self.viewModel.editingReasoningParamName == "enable_thinking" {+ return "enable_thinking"+ } else {+ return "custom"}- } else {- self.viewModel.editingReasoningParamName = newValue- // Set sensible default value when switching- if newValue == "reasoning_effort", !["none", "minimal", "low", "medium", "high"].contains(self.viewModel.editingReasoningParamValue) {- self.viewModel.editingReasoningParamValue = "low"- } else if newValue == "enable_thinking", !["true", "false"].contains(self.viewModel.editingReasoningParamValue) {- self.viewModel.editingReasoningParamValue = "true"+ },+ set: { newValue in+ if newValue == "custom" {+ if self.viewModel.editingReasoningParamName == "reasoning_effort" ||+ self.viewModel.editingReasoningParamName == "enable_thinking"+ {+ self.viewModel.editingReasoningParamName = ""+ }+ } else {+ self.viewModel.editingReasoningParamName = newValue+ // Set sensible default value when switching+ if newValue == "reasoning_effort", !["none", "minimal", "low", "medium", "high"].contains(self.viewModel.editingReasoningParamValue) {+ self.viewModel.editingReasoningParamValue = "low"+ } else if newValue == "enable_thinking", !["true", "false"].contains(self.viewModel.editingReasoningParamValue) {+ self.viewModel.editingReasoningParamValue = "true"+ }}}- }- )) {+ )+ ) {Text("reasoning_effort").tag("reasoning_effort")Text("enable_thinking").tag("enable_thinking")Text("Custom...").tag("custom")}- .pickerStyle(.menu).fluidDropdownStyle().labelsHidden().frame(width: 140)@@ -2453,23 +2462,29 @@ extension AIEnhancementSettingsView {.frame(width: 70, alignment: .trailing)if self.viewModel.editingReasoningParamName == "reasoning_effort" {- Picker("", selection: self.$viewModel.editingReasoningParamValue) {+ FluidDropdownPicker(+ "Reasoning value",+ selectedTitle: self.viewModel.editingReasoningParamValue,+ selection: self.$viewModel.editingReasoningParamValue+ ) {Text("none").tag("none")Text("minimal").tag("minimal")Text("low").tag("low")Text("medium").tag("medium")Text("high").tag("high")}- .pickerStyle(.menu).fluidDropdownStyle().labelsHidden().frame(width: 100)} else if self.viewModel.editingReasoningParamName == "enable_thinking" {- Picker("", selection: self.$viewModel.editingReasoningParamValue) {+ FluidDropdownPicker(+ "Reasoning value",+ selectedTitle: self.viewModel.editingReasoningParamValue,+ selection: self.$viewModel.editingReasoningParamValue+ ) {Text("true").tag("true")Text("false").tag("false")}- .pickerStyle(.menu).fluidDropdownStyle().labelsHidden().frame(width: 100)diff --git a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swiftindex 6d7f9155..d49390d0 100644--- a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift+++ b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift@@ -1364,12 +1364,15 @@ extension AIEnhancementSettingsView {.font(.fluidSystem(.caption)).foregroundStyle(.secondary)- Picker("", selection: self.editModeProviderBinding) {+ FluidDropdownPicker(+ "Provider",+ selectedTitle: verified.first(where: { $0.id == self.editModeProviderBinding.wrappedValue })?.name ?? "Choose provider",+ selection: self.editModeProviderBinding+ ) {ForEach(verified) { provider inText(provider.name).tag(provider.id)}}- .pickerStyle(.menu).fluidDropdownStyle().labelsHidden().frame(width: AISettingsLayout.promptInlinePickerWidth)diff --git a/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift b/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swiftindex 9542f69c..c28aca14 100644--- a/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift+++ b/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift@@ -291,7 +291,15 @@ extension VoiceEngineSettingsView {.frame(maxWidth: .infinity, alignment: .leading)// Action area: Show progress if THIS model is being downloaded- if self.viewModel.downloadingModel == model {+ if self.viewModel.asr.deletingModelID == model.id {+ HStack(spacing: 8) {+ ProgressView().controlSize(.mini)+ Text("Deleting…")+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.voiceEngineSecondaryText)+ }+ .accessibilityLabel("Deleting \(model.humanReadableName)")+ } else if self.viewModel.downloadingModel == model {// This specific model is currently being downloadedHStack(spacing: 8) {VStack(alignment: .trailing, spacing: 4) {@@ -494,7 +502,6 @@ extension VoiceEngineSettingsView {}} label: { Label(self.settings.selectedCohereLanguage.displayName, systemImage: "globe") }.fluidDropdownStyle()- .buttonStyle(.plain)} else if model == .nemotronOffline || model == .nemotronStreaming || model == .nemotronStreaming320 {self.nemotronLanguagePickerButton}diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swiftindex 97cef1b6..c702a473 100644--- a/Sources/Fluid/UI/CustomDictionaryView.swift+++ b/Sources/Fluid/UI/CustomDictionaryView.swift@@ -111,7 +111,7 @@ struct CustomDictionaryView: View {return true}guard !self.trainingStopRequestedDuringStart, !self.isTrainingProcessing else { return false }- return self.isTrainingRecording || (self.pronunciationEnabled && (self.canRecordTrainingSample || self.canRetryTrainingAfterMaximum))+ return self.isTrainingRecording || (self.canRecordTrainingSample || self.canRetryTrainingAfterMaximum)}private var trainingRecorderIsStop: Bool {@@ -125,20 +125,24 @@ struct CustomDictionaryView: View {return self.canRetryTrainingAfterMaximum ? "Try Again" : "Start"}+ private var trainingProgress: DictionaryTrainingProgress {+ DictionaryTrainingProgress(+ spellingCount: self.trainingSampleCount,+ pronunciationCount: self.trainingPronunciationEnrollments.count,+ pronunciationEnabled: self.activePronunciationMatching+ )+ }+private var trainingFinalOutputIsReady: Bool {- if self.activePronunciationMatching {- return self.trainingPronunciationEnrollments.count >= CustomDictionaryTrainingMerge.readyCoveredCount- }- return self.trainingSampleCount >= CustomDictionaryTrainingMerge.readyCoveredCount+ self.trainingProgress.spellingReady}private var trainingAlreadyCorrectWithoutReplacement: Bool {- if self.activePronunciationMatching { return false }- return self.trainingVariants.isEmpty &&- self.trainingOutputIsCovered &&- !self.lastTrainingOutput.isEmpty &&- self.lastTrainingOutput.caseInsensitiveCompare(self.normalizedTrainingReplacement) == .orderedSame &&- self.consecutiveCoveredCaptures >= CustomDictionaryTrainingMerge.readyCoveredCount+ !self.trainingProgress.pronunciationReady && self.trainingProgress.spellingAlreadyCorrect(+ variants: self.trainingVariants,+ lastOutput: self.lastTrainingOutput,+ target: self.normalizedTrainingReplacement+ )}private var trainingReadinessProgress: Int {@@ -153,10 +157,7 @@ struct CustomDictionaryView: View {}private var trainingOutputIsCovered: Bool {- if self.activePronunciationMatching {- return !self.trainingPronunciationEnrollments.isEmpty- }- return self.lastTrainingOutputIsCovered+ self.lastTrainingOutputIsCovered || (self.activePronunciationMatching && !self.trainingPronunciationEnrollments.isEmpty)}private var trainingFinalOutputText: String {@@ -165,7 +166,7 @@ struct CustomDictionaryView: View {}private var canRecordTrainingSample: Bool {- self.pronunciationEnabled && !self.normalizedTrainingReplacement.isEmpty &&+ !self.normalizedTrainingReplacement.isEmpty &&!self.isTrainingProcessing &&!self.asr.isRunning &&self.trainingSampleCount < CustomDictionaryTrainingMerge.maxSamples@@ -183,7 +184,7 @@ struct CustomDictionaryView: View {private var canAddTrainedReplacement: Bool {!self.normalizedTrainingReplacement.isEmpty &&- (!self.trainingVariants.isEmpty || !self.trainingPronunciationEnrollments.isEmpty) &&+ (!self.trainingVariants.isEmpty || self.trainingProgress.pronunciationReady) &&!self.isTrainingRecording &&!self.isTrainingProcessing &&self.trainingFinalOutputIsReady@@ -358,19 +359,12 @@ struct CustomDictionaryView: View {}.onChange(of: self.pronunciationEnabled) { _, enabled inguard !enabled else { return }- self.isAutomaticTrainingEnabled = false- DictionaryTrainingEndpointMonitor.shared.stop()self.trainingPronunciationEnrollments = []- self.trainingSaveID = nil- self.isTrainingProcessing = false- if self.isTrainingRecording {- Task {- if self.isTrainingStarting {- await self.asr.cancelPendingPronunciationTrainingStart()- } else {- await self.stopTrainingSample()- }- }+ if self.trainingSaveID != nil {+ self.trainingSaveID = nil+ self.isTrainingProcessing = false+ self.trainingHasError = true+ self.trainingStatusMessage = "Pronunciation learning was turned off. Try saving your spelling corrections again."}}.onDisappear {@@ -579,7 +573,7 @@ struct CustomDictionaryView: View {DictionaryWordWizard(word: self.$trainingReplacement,step: self.wizardStep,- count: self.activePronunciationMatching ? self.trainingPronunciationEnrollments.count : self.trainingSampleCount,+ count: self.trainingSampleCount,heard: self.lastTrainingOutput,variants: self.trainingVariants,busy: self.isTrainingRecording || self.isTrainingProcessing || self.isTrainingStarting,@@ -591,7 +585,7 @@ struct CustomDictionaryView: View {alreadyCorrect: self.trainingAlreadyCorrectWithoutReplacement,savedWord: self.wizardSavedWord,onContinue: {- let captures = self.activePronunciationMatching ? self.trainingPronunciationEnrollments.count : self.trainingSampleCount+ let captures = self.trainingSampleCountself.wizardStep = captures >= 3 ? .review : .recording},onRecord: {@@ -628,7 +622,9 @@ struct CustomDictionaryView: View {self.wizardStep = .recording},automaticCaptureActive: self.isAutomaticTrainingEnabled,- audioLevels: self.asr.audioLevelPublisher+ audioLevels: self.asr.audioLevelPublisher,+ pronunciationNotice: self.trainingProgress.pronunciationNotice,+ pronunciationIncomplete: self.activePronunciationMatching && !self.trainingProgress.pronunciationReady).onChange(of: self.trainingReplacement) { oldValue, newValue inself.handleTrainingReplacementChange(oldValue: oldValue, newValue: newValue)@@ -2233,7 +2229,7 @@ struct CustomDictionaryView: View {}private func startTrainingSample() async {- guard self.pronunciationEnabled, self.isAutomaticTrainingEnabled, self.canRecordTrainingSample else {+ guard self.isAutomaticTrainingEnabled, self.canRecordTrainingSample else {self.isAutomaticTrainingEnabled = falsereturn}@@ -2244,7 +2240,7 @@ struct CustomDictionaryView: View {self.isTrainingStarting = trueself.isTrainingRecording = true- await self.asr.start(forDictionaryTraining: true)+ await self.asr.start(forDictionaryTraining: true, requiresPronunciation: false)self.isTrainingStarting = falseif !self.asr.isRunning {self.isTrainingRecording = false@@ -2297,8 +2293,6 @@ struct CustomDictionaryView: View {let pronunciationGeneration = DictionaryMatcherExperiment.generationlet transcript = await self.asr.stop(forDictionaryTraining: true, captureDictionaryPronunciation: self.activePronunciationMatching)self.isTrainingProcessing = false- guard self.pronunciationEnabled,- DictionaryMatcherExperiment.generation == pronunciationGeneration else { return }guard !CustomDictionaryTrainingMerge.isOversizedResponse(transcript, intendedReplacement: self.normalizedTrainingReplacement) else {self.isAutomaticTrainingEnabled = falseself.trainingHasError = true@@ -2306,6 +2300,7 @@ struct CustomDictionaryView: View {return}if self.activePronunciationMatching,+ DictionaryMatcherExperiment.generation == pronunciationGeneration,CustomDictionaryTrainingMerge.normalizedTrigger(transcript) != nil,let enrollment = self.asr.lastDictionaryTrainingResult?.pronunciationEnrollment{@@ -2347,13 +2342,6 @@ struct CustomDictionaryView: View {}private func addTrainingVariant(from transcript: String) {- if self.activePronunciationMatching,- self.asr.lastDictionaryTrainingResult?.pronunciationEnrollment == nil- {- self.trainingHasError = true- self.trainingStatusMessage = "Couldn't capture a voice profile. Try again with one clear word."- return- }guard let detected = CustomDictionaryTrainingMerge.normalizedTrigger(transcript) else {self.lastTrainingOutput = ""self.lastTrainingOutputIsCovered = false@@ -2429,10 +2417,10 @@ struct CustomDictionaryView: View {}let replacementText = self.normalizedTrainingReplacementlet enrollments = self.trainingPronunciationEnrollments- let savePronunciation = self.activePronunciationMatching+ let savePronunciation = self.trainingProgress.pronunciationReadylet pronunciationGeneration = DictionaryMatcherExperiment.generationlet filtered = await VoiceTrainingAliasFilter.filter(self.trainingVariants)- guard self.trainingSaveID == saveID, !Task.isCancelled, self.pronunciationEnabled else { return }+ guard self.trainingSaveID == saveID, !Task.isCancelled else { return }DebugLogger.shared.info("VOICE_TRAINING_ALIAS_FILTER accepted=\(filtered.accepted.count) rejected=\(filtered.rejected.count) available=\(filtered.lookupAvailable)",source: "CustomDictionary"@@ -2470,7 +2458,7 @@ struct CustomDictionaryView: View {})} catch {- guard self.trainingSaveID == saveID, !Task.isCancelled, self.pronunciationEnabled else { return }+ guard self.trainingSaveID == saveID, !Task.isCancelled else { return }self.trainingHasError = trueself.trainingStatusMessage = SettingsStore.shared.customDictionaryEntries == originalEntries? "Couldn't save the voice profile. Try again."@@ -2482,7 +2470,7 @@ struct CustomDictionaryView: View {return}}- guard self.trainingSaveID == saveID, !Task.isCancelled, self.pronunciationEnabled else { return }+ guard self.trainingSaveID == saveID, !Task.isCancelled else { return }// Profile persistence suspends this view. Never publish a snapshot over a newer// manual edit, import, or deletion; keep the recordings available for a retry.guard SettingsStore.shared.customDictionaryEntries == originalEntries else {@@ -3209,6 +3197,35 @@ enum PronunciationProfileEditPolicy {}}+/// Spelling examples are useful even when voice enrollment is missing or incomplete.+struct DictionaryTrainingProgress {+ let spellingCount: Int+ let pronunciationCount: Int+ let pronunciationEnabled: Bool++ var spellingReady: Bool { self.spellingCount >= CustomDictionaryTrainingMerge.readyCoveredCount }+ var pronunciationReady: Bool {+ self.pronunciationEnabled && self.pronunciationCount >= CustomDictionaryTrainingMerge.readyCoveredCount+ }++ func spellingAlreadyCorrect(variants: [String], lastOutput: String, target: String) -> Bool {+ self.spellingReady && variants.isEmpty && !lastOutput.isEmpty+ && lastOutput.caseInsensitiveCompare(target) == .orderedSame+ }++ var pronunciationNotice: String? {+ guard self.pronunciationEnabled else { return nil }+ let count = min(self.pronunciationCount, CustomDictionaryTrainingMerge.readyCoveredCount)+ if self.spellingReady, !self.pronunciationReady {+ if self.spellingCount >= CustomDictionaryTrainingMerge.maxSamples {+ return "Spelling examples are ready. Pronunciation needs more voice examples. Save spelling corrections only, or redo recordings to try voice learning again."+ }+ return "Spelling examples are ready. Pronunciation has \(count) of 3 voice examples. Record more to finish voice learning, or save spelling corrections only."+ }+ return "Pronunciation: \(count) of 3 voice examples"+ }+}+enum CustomDictionaryTrainingMerge {static let recommendedSamples = 5static let maxSamples = 20diff --git a/Sources/Fluid/UI/DictionaryMatchDiagnosticsView.swift b/Sources/Fluid/UI/DictionaryMatchDiagnosticsView.swiftindex 540fe593..db23650f 100644--- a/Sources/Fluid/UI/DictionaryMatchDiagnosticsView.swift+++ b/Sources/Fluid/UI/DictionaryMatchDiagnosticsView.swift@@ -100,7 +100,11 @@ struct DictionaryMatchDiagnosticsView: View {Text("Load an older recording into the textbox.").font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)- Picker("Recording", selection: self.$historyID) {+ FluidDropdownPicker(+ "Recording",+ selectedTitle: self.history.first(where: { $0.id == self.historyID }).map { "\($0.timestamp.formatted(date: .omitted, time: .shortened)) · \(String(($0.clipboardText ?? $0.rawText).prefix(60)))" } ?? "Choose a recording",+ selection: self.$historyID+ ) {Text("Choose a recording").tag(UUID?.none)ForEach(self.history) { entry inText("\(entry.timestamp.formatted(date: .omitted, time: .shortened)) · \(String((entry.clipboardText ?? entry.rawText).prefix(60)))")diff --git a/Sources/Fluid/UI/DictionaryWordWizard.swift b/Sources/Fluid/UI/DictionaryWordWizard.swiftindex 3b143113..c57f3139 100644--- a/Sources/Fluid/UI/DictionaryWordWizard.swift+++ b/Sources/Fluid/UI/DictionaryWordWizard.swift@@ -38,6 +38,8 @@ struct DictionaryWordWizard: View {var onRedo: () -> Void = {}var automaticCaptureActive = falsevar audioLevels: AnyPublisher<CGFloat, Never> = Empty().eraseToAnyPublisher()+ var pronunciationNotice: String?+ var pronunciationIncomplete = false@Environment(\.theme) private var theme@Environment(\.accessibilityReduceMotion) private var reduceMotion@@ -161,7 +163,7 @@ struct DictionaryWordWizard: View {private var captureStage: some View {VStack(spacing: self.theme.metrics.spacing.lg) {- Text(self.step == .review ? "Your word is ready" : "Let’s hear your word")+ Text(self.step == .review ? (self.pronunciationIncomplete ? "Your spellings are ready" : "Your word is ready") : "Let’s hear your word").font(self.theme.typography.body).foregroundStyle(self.theme.palette.accent)Text("“\(self.word)”")@@ -301,6 +303,13 @@ struct DictionaryWordWizard: View {self.stableInstruction("We’ll stop automatically and let you know when to speak again.", review: "Add it now, or record another example.").font(self.theme.typography.body).foregroundStyle(self.theme.palette.secondaryText)+ if let pronunciationNotice {+ Text(pronunciationNotice)+ .font(self.theme.typography.body)+ .foregroundStyle(self.theme.palette.secondaryText)+ .multilineTextAlignment(.center)+ .frame(maxWidth: .infinity)+ }ZStack(alignment: .top) {if self.step == .review {self.captureRecordActions.hidden().accessibilityHidden(true)@@ -372,7 +381,7 @@ struct DictionaryWordWizard: View {Button(action: self.onSave) {ZStack {Text("Add “\(self.word)” to dictionary").hidden().accessibilityHidden(true)- Text(self.busy ? "Saving…" : "Add “\(self.word)” to dictionary")+ Text(self.busy ? "Saving…" : (self.pronunciationIncomplete ? "Save spelling corrections" : "Add “\(self.word)” to dictionary"))}}.buttonStyle(FluidRecordInvitationStyle(inviting: self.step == .review && !self.busy, recording: false, fillsWidth: true))@@ -382,7 +391,7 @@ struct DictionaryWordWizard: View {Button("Record more", action: self.onRecord).buttonStyle(FluidRecordInvitationStyle(inviting: false, recording: false, prominent: false, fillsWidth: true)).disabled(self.busy)- Text("Optional · Recommended for tricky words")+ Text(self.pronunciationIncomplete ? "Needed to finish pronunciation learning" : "Optional · Recommended for tricky words").font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText).frame(maxWidth: 190)diff --git a/Sources/Fluid/UI/FileTranscriptionView.swift b/Sources/Fluid/UI/FileTranscriptionView.swiftindex 3a4a6b50..613c8405 100644--- a/Sources/Fluid/UI/FileTranscriptionView.swift+++ b/Sources/Fluid/UI/FileTranscriptionView.swift@@ -317,13 +317,16 @@ struct FileTranscriptionView: View {Spacer()- Picker("Number of speakers", selection: self.$settings.fileTranscriptionExpectedSpeakerCount) {+ FluidDropdownPicker(+ "Number of speakers",+ selectedTitle: self.settings.fileTranscriptionExpectedSpeakerCount == 0 ? "Auto" : String(self.settings.fileTranscriptionExpectedSpeakerCount),+ selection: self.$settings.fileTranscriptionExpectedSpeakerCount+ ) {Text("Auto").tag(0)ForEach(2...8, id: \.self) { count inText("\(count)").tag(count)}}- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 110).disabled(self.transcriptionService.isTranscribing)diff --git a/Sources/Fluid/UI/MeetingRecordingSettingsSheet.swift b/Sources/Fluid/UI/MeetingRecordingSettingsSheet.swiftindex e6f1cd1d..21677974 100644--- a/Sources/Fluid/UI/MeetingRecordingSettingsSheet.swift+++ b/Sources/Fluid/UI/MeetingRecordingSettingsSheet.swift@@ -18,7 +18,7 @@ enum MeetingSettingsSection: String, CaseIterable, Identifiable {var guidance: String {switch self {- case .recording: "Choose your audio sources. Transcripts are currently in English."+ case .recording: "Choose your audio sources and transcript language."case .automation: "Choose when to see a recording prompt and how long to keep audio."case .integrations: "Connect your meeting notes to the AI assistants you already use."}@@ -81,6 +81,7 @@ struct MeetingRecordingSettingsSheet: View {}private var canSave: Bool {+ guard VoiceEngineLanguageCatalog.parakeetV3LanguageIDs.contains(self.draft.languageCode) else { return false }guard self.microphones.contains(where: { $0.id == self.draft.selectedMicrophoneID }) else { return false }return self.draft.mode == .inRoom|| self.draft.usesAutomaticApplication@@ -276,6 +277,26 @@ struct MeetingRecordingSettingsSheet: View {.accessibilityLabel("Refresh audio sources")}+ FluidManagementGroup(title: "Transcript language") {+ MeetingAdaptiveSetupRow(+ title: "Language",+ detail: "Final transcripts support 25 languages. Live captions are English-only."+ ) {+ Menu {+ Picker("Meeting language", selection: self.$draft.languageCode) {+ ForEach(VoiceEngineLanguageCatalog.allLanguages(availableModels: [.parakeetTDT])) { language in+ Text(language.displayName).tag(language.id)+ }+ }+ .pickerStyle(.inline)+ } label: {+ Text(VoiceEngineLanguageCatalog.language(id: self.draft.languageCode, availableModels: [.parakeetTDT])?.displayName ?? "Choose language…")+ }+ .fluidDropdownStyle(fillsWidth: true)+ .accessibilityLabel("Meeting transcript language")+ }+ }+MeetingModelSettingsSection(onModelImported: self.onModelImported)if self.readiness.showMicrophoneSettingsAction || self.readiness.showScreenRecordingSettingsAction {diff --git a/Sources/Fluid/UI/MeetingSegmentAudioPlayer.swift b/Sources/Fluid/UI/MeetingSegmentAudioPlayer.swiftnew file mode 100644index 00000000..55c1a47e--- /dev/null+++ b/Sources/Fluid/UI/MeetingSegmentAudioPlayer.swift@@ -0,0 +1,89 @@+import SwiftUI++/// A compact transport aligned with the transcript row's trailing audio action.+struct MeetingSegmentAudioPlayer: View {+ let playback: MeetingSegmentPlayback+ let isLoading: Bool+ @ObservedObject private var progress: MeetingPlaybackProgress+ @Environment(\.theme) private var theme+ @State private var isScrubbing = false+ @State private var scrubPosition: Double = 0++ init(playback: MeetingSegmentPlayback, isLoading: Bool) {+ self.playback = playback+ self.isLoading = isLoading+ self.progress = playback.progress+ }++ var body: some View {+ VStack(spacing: self.theme.metrics.spacing.sm) {+ HStack(spacing: self.theme.metrics.spacing.sm) {+ FluidGlassControlGroup {+ HStack(spacing: self.theme.metrics.spacing.sm) {+ self.action("Back 5 seconds", symbol: "gobackward.5") { self.playback.skip(by: -5) }+ Button(action: self.playback.togglePause) {+ Group {+ if self.isLoading {+ ProgressView().controlSize(.mini)+ } else {+ Image(systemName: self.progress.isPlaying ? "pause.fill" : "play.fill")+ }+ }+ .frame(width: 16, height: 16)+ }+ .fluidGlassAction(circular: true)+ .disabled(self.isLoading)+ .accessibilityLabel(self.progress.isPlaying ? "Pause audio chunk" : "Play audio chunk")+ self.action("Forward 5 seconds", symbol: "goforward.5") { self.playback.skip(by: 5) }+ }+ }+ Spacer(minLength: self.theme.metrics.spacing.sm)+ Text(self.isLoading ? "Loading…" : "\(Self.time(self.isScrubbing ? self.scrubPosition : self.progress.elapsed)) / \(Self.time(self.progress.duration))")+ .font(self.theme.typography.codeCaption)+ .foregroundStyle(self.theme.palette.secondaryText)+ .monospacedDigit()+ .fixedSize()+ .accessibilityLabel("Playback time")+ }+ Slider(+ value: Binding(+ get: { self.isScrubbing ? self.scrubPosition : self.progress.elapsed },+ set: { value in+ self.scrubPosition = value+ // Keyboard and accessibility changes do not always begin a drag.+ if !self.isScrubbing { self.playback.seek(to: value) }+ }+ ),+ in: 0...max(self.progress.duration, 0.01),+ onEditingChanged: { editing in+ if editing {+ self.scrubPosition = self.progress.elapsed+ self.isScrubbing = true+ } else {+ self.isScrubbing = false+ self.playback.seek(to: self.scrubPosition)+ }+ }+ )+ .tint(self.theme.palette.accent)+ .disabled(self.isLoading || self.progress.duration <= 0)+ .accessibilityLabel("Audio chunk position")+ .accessibilityValue(Self.time(self.isScrubbing ? self.scrubPosition : self.progress.elapsed))+ }+ .padding(.vertical, self.theme.metrics.spacing.sm)+ .frame(maxWidth: .infinity)+ }++ private func action(_ title: String, symbol: String, action: @escaping () -> Void) -> some View {+ Button(action: action) { Image(systemName: symbol) }+ .fluidGlassAction(circular: true)+ .disabled(self.isLoading)+ .help(title)+ .accessibilityLabel(title)+ }++ private static func time(_ seconds: Double) -> String {+ let value = Int(max(0, seconds.isFinite ? seconds : 0))+ return String(format: "%d:%02d", value / 60, value % 60)+ }+}diff --git a/Sources/Fluid/UI/MeetingSessionCanvases.swift b/Sources/Fluid/UI/MeetingSessionCanvases.swiftindex f7243c82..611cbf80 100644--- a/Sources/Fluid/UI/MeetingSessionCanvases.swift+++ b/Sources/Fluid/UI/MeetingSessionCanvases.swift@@ -344,9 +344,11 @@ struct MeetingResultCanvas: View {let isQuiescent: Boollet canUndo: Bool@State private var showsProbableEchoes = false+ @StateObject private var playback = MeetingSegmentPlayback()let onCopyTranscript: (MeetingSession, Bool) -> Voidlet onExportTranscript: (MeetingSession, MeetingTranscriptExportFormat, Bool) -> Voidlet onReassignSegment: (MeetingTranscriptSegmentID, SessionSpeakerID) -> Void+ var onEditTranscriptSegment: (MeetingTranscriptSegmentID, String, Int) async -> String? = { _, _, _ in "Transcript editing is unavailable." }let onNameUnknownSegment: (MeetingTranscriptSegmentID, String) -> Voidlet onRenameSpeaker: (SessionSpeakerID, String) -> Voidlet onMergeSpeakers: (SessionSpeakerID, SessionSpeakerID) -> Void@@ -358,6 +360,7 @@ struct MeetingResultCanvas: View {var summaryASRService: ASRService? = nil@Environment(\.theme) private var theme+ @State private var pendingEditedSegment: MeetingTranscriptSegment?@State private var pendingRenameSpeaker: MeetingSessionSpeaker?@State private var pendingRenameText = ""@State private var pendingNameUnknownSegmentID: MeetingTranscriptSegmentID?@@ -449,6 +452,11 @@ struct MeetingResultCanvas: View {}}+ if let errorMessage = self.playback.errorMessage {+ Label(errorMessage, systemImage: "exclamationmark.triangle")+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.warning)+ }if visibleSegments.isEmpty {VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {Text("No transcript text")@@ -481,10 +489,15 @@ struct MeetingResultCanvas: View {}},isLocalUser: row.isLocal,- showsSpeakerLabel: row.showsLabel,reassignTargets: activeSpeakers.filter { $0.id != row.segment.speakerID },isQuiescent: self.isQuiescent,- onReassign: { speakerID in self.onReassignSegment(row.segment.id, speakerID) }+ onReassign: { speakerID in self.onReassignSegment(row.segment.id, speakerID) },+ canPlayAudio: self.session.retention.audioDeletedAt == nil && self.session.hasFinalizedAudio && self.isQuiescent,+ isAudioExpanded: self.playback.activeSegmentID == row.segment.id,+ playback: self.playback,+ isLoadingAudio: self.playback.activeSegmentID == row.segment.id && self.playback.isLoading,+ onPlayAudio: { self.playback.toggle(sessionID: self.session.id, segmentID: row.segment.id) },+ onEditText: { if self.isQuiescent { self.pendingEditedSegment = row.segment } })}}@@ -496,6 +509,23 @@ struct MeetingResultCanvas: View {.frame(maxWidth: .infinity, alignment: .center)}.id(self.session.id)+ .sheet(item: self.$pendingEditedSegment) { segment in+ MeetingTranscriptTextEditor(+ text: segment.text,+ onSave: { text in+ let error = await self.onEditTranscriptSegment(segment.id, text, segment.revision)+ if error == nil { self.pendingEditedSegment = nil }+ return error+ },+ onCancel: { self.pendingEditedSegment = nil }+ )+ }+ .onDisappear { self.playback.stop() }+ .onChange(of: self.session.id) { _, _ in self.playback.stop() }+ .onChange(of: self.session.retention.audioDeletedAt) { _, _ in self.playback.stop() }+ .onChange(of: self.isQuiescent) { _, value in if !value { self.playback.stop() } }+ .onChange(of: self.documentSection) { _, _ in self.playback.stop() }+ .onChange(of: self.showsProbableEchoes) { _, _ in self.playback.stop() }.task(id: self.copyRevision) {guard self.copied else { return }do { try await Task.sleep(for: .seconds(2)) } catch { return }@@ -1021,10 +1051,15 @@ private struct MeetingTranscriptSegmentRow: View {let speakerTint: Color?let onRenameSpeakerTapped: (() -> Void)?let isLocalUser: Bool- let showsSpeakerLabel: Boollet reassignTargets: [MeetingSessionSpeaker]let isQuiescent: Boollet onReassign: (SessionSpeakerID) -> Void+ let canPlayAudio: Bool+ let isAudioExpanded: Bool+ let playback: MeetingSegmentPlayback+ let isLoadingAudio: Bool+ let onPlayAudio: () -> Void+ let onEditText: () -> Void@Environment(\.theme) private var theme@@ -1034,18 +1069,43 @@ private struct MeetingTranscriptSegmentRow: View {.font(self.theme.typography.codeCaption).foregroundStyle(self.theme.palette.secondaryText).frame(width: 58, alignment: .leading)- .padding(.top, 2)+ .frame(height: 28)VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {- if self.showsSpeakerLabel { self.speakerLabel }+ HStack(spacing: self.theme.metrics.spacing.sm) {+ self.speakerLabel+ Spacer(minLength: self.theme.metrics.spacing.md)+ Button("Edit", systemImage: "pencil", action: self.onEditText)+ .fluidGlassAction()+ .disabled(!self.isQuiescent)+ .help("Edit text, or double-click this paragraph")+ Button {+ if self.isAudioExpanded { self.playback.stop() } else { self.onPlayAudio() }+ } label: {+ Label(self.isAudioExpanded ? "Close" : "Audio", systemImage: self.isAudioExpanded ? "xmark" : "play.fill")+ .frame(minWidth: 54)+ }+ .fluidGlassAction()+ .disabled(!self.canPlayAudio && !self.isAudioExpanded)+ .help(self.isAudioExpanded ? "Close audio player" : (self.canPlayAudio ? "Play this speaker chunk" : "Audio unavailable"))+ .accessibilityLabel(self.isAudioExpanded ? "Close audio player" : "Play audio chunk for \(self.speakerName)")+ }+ .frame(minHeight: 28)Text(self.segment.text).font(self.theme.typography.body).foregroundStyle(self.theme.palette.primaryText).lineSpacing(5).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)+ .simultaneousGesture(TapGesture(count: 2).onEnded { if self.isQuiescent { self.onEditText() } })+ .accessibilityAction(named: Text("Edit text")) { if self.isQuiescent { self.onEditText() } }if self.segment.isEcho {Text("Probable echo").font(self.theme.typography.caption).foregroundStyle(.secondary)}+ if self.isAudioExpanded {+ MeetingSegmentAudioPlayer(playback: self.playback, isLoading: self.isLoadingAudio)+ .frame(maxWidth: 360)+ .frame(maxWidth: .infinity, alignment: .trailing)+ }}}.opacity(self.segment.isEcho ? 0.6 : 1)@@ -1059,7 +1119,7 @@ private struct MeetingTranscriptSegmentRow: View {}.disabled(!self.isQuiescent || self.reassignTargets.isEmpty)}- .accessibilityElement(children: .combine)+ .accessibilityElement(children: .contain).accessibilityLabel("\(MeetingTranscriptExporter.timestampText(self.segment.start.seconds)), \(self.speakerName), \(self.segment.text)")@@ -1100,3 +1160,67 @@ private struct MeetingTranscriptSegmentRow: View {return self.speakerTint ?? self.theme.palette.tertiaryText}}++struct MeetingTranscriptTextEditor: View {+ let onSave: (String) async -> String?+ let onCancel: () -> Void+ @Environment(\.theme) private var theme+ @State private var text: String+ @State private var isSaving = false+ @State private var errorMessage: String?++ init(text: String, onSave: @escaping (String) async -> String?, onCancel: @escaping () -> Void) {+ self._text = State(initialValue: text)+ self.onSave = onSave+ self.onCancel = onCancel+ }++ var body: some View {+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {+ Text("Edit transcript")+ .font(self.theme.typography.title)+ .accessibilityAddTraits(.isHeader)+ Text("Correct this paragraph. Its timestamps, speaker, and recording stay the same.")+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.theme.palette.secondaryText)+ TextEditor(text: self.$text)+ .font(self.theme.typography.body)+ .scrollContentBackground(.hidden)+ .padding(self.theme.metrics.spacing.sm)+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))+ .frame(minHeight: 200)+ .disabled(self.isSaving)+ .accessibilityLabel("Transcript text")+ if let errorMessage {+ Text(errorMessage)+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.warning)+ }+ FluidGlassControlGroup {+ HStack {+ Button("Cancel", action: self.onCancel)+ .meetingGlassAction()+ .keyboardShortcut(.cancelAction)+ .disabled(self.isSaving)+ Spacer()+ Button(self.isSaving ? "Saving…" : "Save") {+ guard !self.isSaving else { return }+ self.isSaving = true+ Task { @MainActor in+ self.errorMessage = await self.onSave(self.text)+ self.isSaving = false+ }+ }+ .meetingGlassAction(prominent: true)+ .keyboardShortcut(.defaultAction)+ .disabled(self.isSaving || self.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ }+ .padding(self.theme.metrics.spacing.xl)+ .frame(width: 560)+ .frame(minHeight: 400)+ .background(self.theme.palette.windowBackground)+ .interactiveDismissDisabled(self.isSaving)+ }+}diff --git a/Sources/Fluid/UI/MeetingSummaryView.swift b/Sources/Fluid/UI/MeetingSummaryView.swiftindex eca2c4ca..04760824 100644--- a/Sources/Fluid/UI/MeetingSummaryView.swift+++ b/Sources/Fluid/UI/MeetingSummaryView.swift@@ -1,4 +1,3 @@-import AppKitimport SwiftUIstruct MeetingSummaryView: View {@@ -6,135 +5,19 @@ struct MeetingSummaryView: View {var asrService: ASRService? = nilvar isQuiescent = true@Environment(\.theme) private var theme- @StateObject private var controller = MeetingSummaryController()- @State private var confirmDeletion = false- @State private var kind = MeetingSummaryKind.executive-- private var refreshID: String {- "\(self.session?.id.uuidString ?? "home")-\(self.session?.updatedAt.timeIntervalSince1970 ?? 0)-\(self.kind.rawValue)"- }-- private var hint: String {- if self.session == nil, self.controller.installed {- return "Open a completed meeting to summarize its transcript."- }- return "Summaries, decisions, and action items, generated on your Mac."- }var body: some View {- VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {- VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {- Text("Your meeting, summed up.")- .font(.system(.title3, design: .serif).weight(.medium))- .foregroundStyle(self.theme.palette.primaryText)- .accessibilityAddTraits(.isHeader)- Text(self.controller.model == nil ? "Meeting summaries require a build with Fluid Intelligence." : self.hint)- .font(self.theme.typography.bodySmall)- .foregroundStyle(self.theme.palette.secondaryText)- }- if self.controller.model != nil {- HStack(spacing: self.theme.metrics.spacing.sm) {- if self.controller.installed {- Picker("Summary type", selection: self.$kind) {- ForEach(MeetingSummaryKind.allCases) { kind in Text(kind.title).tag(kind) }- }- .labelsHidden()- .pickerStyle(.menu)- .fluidDropdownStyle()- .fixedSize()- .disabled(self.controller.busy)- }- self.actions- }- if self.controller.downloading {- Text(PrivateAIModelDownloadProgressText.detailText(for: self.controller.progress))- .font(self.theme.typography.caption)- .foregroundStyle(self.theme.palette.secondaryText)- }- if let error = self.controller.error {- Text(error).font(self.theme.typography.bodySmall).foregroundStyle(self.theme.palette.warning)- .textSelection(.enabled)- }- if !self.controller.output.isEmpty {- CommandMarkdownContent(text: self.controller.output)- }- }- Label("On-device · English · Frees its memory when done", systemImage: "lock")- .font(self.theme.typography.caption)- .foregroundStyle(self.theme.palette.tertiaryText)+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {+ Text("Meeting summaries — coming soon")+ .font(self.theme.typography.bodyStrong)+ .foregroundStyle(self.theme.palette.primaryText)+ .accessibilityAddTraits(.isHeader)+ Text("Temporarily disabled due to summary inaccuracies.")+ .font(self.theme.typography.body)+ .foregroundStyle(self.theme.palette.secondaryText)+ .fixedSize(horizontal: false, vertical: true)}- .fixedSize(horizontal: false, vertical: true)- .frame(maxWidth: 620, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, self.theme.metrics.spacing.md)- .task(id: self.refreshID) { await self.controller.refresh(session: self.session, kind: self.kind) }- .onDisappear { self.controller.cancel() }- .alert("Delete summary model?", isPresented: self.$confirmDeletion) {- Button("Cancel", role: .cancel) {}- Button("Delete", role: .destructive) {- if let asrService { self.controller.deleteModel(asr: asrService) }- }- } message: {- Text("Remove the 1.45 GB download from this Mac. Your meetings and saved summaries stay. You can download it again anytime.")- }- }-- private var actions: some View {- FluidGlassControlGroup {- HStack(spacing: self.theme.metrics.spacing.sm) {- if self.controller.checking {- ProgressView().controlSize(.small)- } else if self.controller.downloading {- Button {} label: {- VStack(spacing: 4) {- Text(PrivateAIModelDownloadProgressText.buttonTitle(for: self.controller.progress))- ProgressView(value: self.controller.progress?.fractionCompleted)- .progressViewStyle(.linear)- .frame(width: 160)- .controlSize(.mini)- }- }- .fluidGlassAction()- .disabled(true)- Button("Cancel") { self.controller.cancel() }.fluidGlassAction()- } else if self.controller.deleting {- ProgressView().controlSize(.small)- Text("Deleting download…").font(self.theme.typography.bodySmall)- } else if !self.controller.installed {- Button("Download · 1.45 GB", systemImage: "arrow.down.circle") { self.controller.download() }- .fluidGlassAction(prominent: true)- .disabled(!self.isQuiescent)- } else if self.controller.generating {- ProgressView().controlSize(.small)- Text("Summarizing…").font(self.theme.typography.bodySmall)- Button("Cancel") { self.controller.cancel() }.fluidGlassAction()- } else {- Button("Summarize", systemImage: "sparkles") {- if let session, let asrService {- self.controller.summarize(session: session, kind: self.kind, asr: asrService)- }- }- .fluidGlassAction(prominent: true)- .disabled(self.session?.transcriptSegments.isEmpty != false || self.asrService == nil || !self.isQuiescent)- }- Menu {- Button("Delete model", systemImage: "trash", role: .destructive) {- self.confirmDeletion = true- }- .disabled(!self.controller.installed || self.controller.busy || self.controller.checking || !self.isQuiescent || self.asrService == nil)- } label: { Image(systemName: "ellipsis") }- .menuIndicator(.hidden)- .fluidGlassAction(circular: true)- .accessibilityLabel("Meeting summary actions")- .disabled(self.controller.busy)- if !self.controller.output.isEmpty {- Button("Copy", systemImage: "doc.on.doc") {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(self.controller.output, forType: .string)- }- .fluidGlassAction()- }- }- }}}diff --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swiftindex 8f72bd0e..decc9549 100644--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift@@ -31,6 +31,7 @@ struct MeetingTranscriptionSetupDraft: Equatable {var usesAutomaticApplication = truevar selectedMicrophoneID: String?/// Once true, the default title stops following the selected application/mode.+ var languageCode: Stringvar titleWasEdited = falsevar autoDetectEnabled: Boolvar browserDetectionEnabled: Bool@@ -39,6 +40,7 @@ struct MeetingTranscriptionSetupDraft: Equatable {let defaults = settings.meetingRecordingDefaultsself.autoDetectEnabled = settings.meetingAutoDetectEnabledself.browserDetectionEnabled = settings.meetingAutoDetectBrowserEnabled+ self.languageCode = defaults.languageCode ?? "en"self.mode = defaults.modeself.title = Self.defaultTitle(mode: defaults.mode, applicationDisplayName: nil)self.selectedApplicationID = nil@@ -163,7 +165,8 @@ struct MeetingTranscriptionView: View {@State private var pendingDeleteSessionID: MeetingSessionID?@State private var pendingDeleteAudioSessionID: MeetingSessionID?@State private var draftMeetingAudioRetentionPolicy = SettingsStore.shared.meetingAudioRetentionPolicy- @AppStorage("MeetingHistoryInspectorVisible") private var isMeetingHistoryVisible = true+ // Reopen history on each visit; narrow-window selection must not hide it permanently.+ @State private var isMeetingHistoryVisible = trueinit(coordinator: MeetingSessionCoordinator,@@ -201,6 +204,7 @@ struct MeetingTranscriptionView: View {onCopyTranscript: self.copyTranscript,onExportTranscript: self.exportTranscript,onReassignSegment: self.reassignSegment,+ onEditTranscriptSegment: self.editTranscriptSegment,onNameUnknownSegment: self.nameUnknownSegment,onRenameSpeaker: self.renameSpeaker,onMergeSpeakers: self.mergeSpeakers,@@ -712,11 +716,13 @@ struct MeetingTranscriptionView: View {return MeetingCaptureConfiguration(mode: application == nil ? .inRoom : .onlineCall,title: title,+ languageCode: self.setupDraft.languageCode,platform: application.map {MeetingPlatformProfile(identifier: $0.bundleIdentifier, displayName: $0.displayName)},application: application,- microphone: microphone+ microphone: microphone,+ timestampDefaultTitle: !self.setupDraft.titleWasEdited)}@@ -796,6 +802,16 @@ struct MeetingTranscriptionView: View {}}+ private func editTranscriptSegment(sessionID: MeetingSessionID, segmentID: MeetingTranscriptSegmentID, text: String, revision: Int) async -> String? {+ do {+ _ = try await self.coordinator.editTranscriptText(sessionID: sessionID, segmentID: segmentID, text: text, expectedRevision: revision)+ await self.loadMeetingHistory()+ return nil+ } catch {+ return error.localizedDescription+ }+ }+private func assignSpeakers(sessionID: MeetingSessionID, names: [SessionSpeakerID: String]) async -> String? {self.actionErrorMessage = nilvar errorMessage: String?@@ -906,10 +922,12 @@ struct MeetingTranscriptionView: View {}return MeetingCaptureConfiguration(mode: session.mode,- title: session.title,+ title: session.defaultTitleBase ?? session.title,+ languageCode: session.languageCode,platform: session.platform,application: application,- microphone: microphone+ microphone: microphone,+ timestampDefaultTitle: session.defaultTitleBase != nil)}@@ -1138,7 +1156,8 @@ struct MeetingTranscriptionView: View {applicationDisplayName: previousDefaults.applicationDisplayName,microphoneCaptureDeviceID: microphone.identity.captureDeviceID,microphoneCoreAudioUID: microphone.identity.coreAudioUID,- microphoneRole: .unknown+ microphoneRole: .unknown,+ languageCode: self.setupDraft.languageCode)let previousRetentionPolicy = settings.meetingAudioRetentionPolicy@@ -1282,6 +1301,7 @@ struct MeetingTranscriptionCanvas: View {let onCopyTranscript: (MeetingSession, Bool) -> Voidlet onExportTranscript: (MeetingSession, MeetingTranscriptExportFormat, Bool) -> Voidlet onReassignSegment: (MeetingSessionID, MeetingTranscriptSegmentID, SessionSpeakerID) -> Void+ var onEditTranscriptSegment: (MeetingSessionID, MeetingTranscriptSegmentID, String, Int) async -> String? = { _, _, _, _ in "Transcript editing is unavailable." }let onNameUnknownSegment: (MeetingSessionID, MeetingTranscriptSegmentID, String) -> Voidlet onRenameSpeaker: (MeetingSessionID, SessionSpeakerID, String) -> Voidlet onMergeSpeakers: (MeetingSessionID, SessionSpeakerID, SessionSpeakerID) -> Void@@ -1342,9 +1362,7 @@ struct MeetingTranscriptionCanvas: View {recentSession: recentSession,onStart: self.onStart,onRepairSetup: self.onRepairSetup,- onEditSetup: self.onEditSetup ?? self.onRepairSetup,- summaryASRService: self.summaryASRService,- isQuiescent: self.isQuiescent+ onEditSetup: self.onEditSetup ?? self.onRepairSetup)case let .recording(session, trackHealth, liveTranscript):MeetingRecordingCanvas(@@ -1384,6 +1402,9 @@ struct MeetingTranscriptionCanvas: View {onReassignSegment: { segmentID, speakerID inself.onReassignSegment(session.id, segmentID, speakerID)},+ onEditTranscriptSegment: { segmentID, text, revision in+ await self.onEditTranscriptSegment(session.id, segmentID, text, revision)+ },onNameUnknownSegment: { segmentID, name inself.onNameUnknownSegment(session.id, segmentID, name)},@@ -1954,8 +1975,6 @@ private struct MeetingSetupCanvas: View {let onStart: () -> Voidlet onRepairSetup: () -> Voidlet onEditSetup: () -> Void- var summaryASRService: ASRService? = nil- var isQuiescent = true@Environment(\.theme) private var theme@State private var documentSection = MeetingDocumentSection.transcript@@ -2025,7 +2044,7 @@ private struct MeetingSetupCanvas: View {MeetingDocumentTabs(selection: self.$documentSection, primaryTitle: "Meeting home", primaryIcon: "house", isEnabled: !self.isStarting)if self.documentSection == .summary {- MeetingSummaryView(asrService: self.summaryASRService, isQuiescent: self.isQuiescent)+ MeetingSummaryView()} else {self.recordingSetup}diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swiftindex 2aeca601..99c76a43 100644--- a/Sources/Fluid/UI/SettingsView.swift+++ b/Sources/Fluid/UI/SettingsView.swift@@ -331,7 +331,7 @@ struct SettingsView: View {Spacer()- Picker("", selection: Binding(+ FluidDropdownPicker("Transcription sound", selectedTitle: SettingsStore.shared.transcriptionStartSound.displayName, selection: Binding(get: { SettingsStore.shared.transcriptionStartSound },set: { newValue inSettingsStore.shared.transcriptionStartSound = newValue@@ -342,7 +342,6 @@ struct SettingsView: View {Text(option.displayName).tag(option)}}- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 170, alignment: .trailing)}@@ -807,12 +806,11 @@ struct SettingsView: View {}.frame(maxWidth: .infinity, alignment: .leading)- Picker("", selection: self.$hotkeyMode) {+ FluidDropdownPicker("Activation mode", selectedTitle: self.hotkeyMode.displayName, selection: self.$hotkeyMode) {ForEach(HotkeyActivationMode.allCases) { mode inText(mode.displayName).tag(mode)}}- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 170, alignment: .trailing)}@@ -846,7 +844,7 @@ struct SettingsView: View {}.frame(maxWidth: .infinity, alignment: .leading)- Picker("", selection: Binding(+ FluidDropdownPicker("Text insertion", selectedTitle: SettingsStore.shared.textInsertionMode.displayName, selection: Binding(get: { SettingsStore.shared.textInsertionMode },set: { SettingsStore.shared.textInsertionMode = $0 })) {@@ -854,7 +852,6 @@ struct SettingsView: View {Text(mode.displayName).tag(mode)}}- .pickerStyle(.menu).fluidDropdownStyle().fixedSize(horizontal: true, vertical: false).frame(minWidth: 170, alignment: .trailing)@@ -1203,7 +1200,11 @@ struct SettingsView: View {.font(self.theme.typography.bodyStrong).foregroundStyle(self.settingsTitleText)Spacer()- Picker("", selection: self.$selectedOutputUID) {+ FluidDropdownPicker(+ "Output device",+ selectedTitle: self.outputDevices.first(where: { $0.uid == self.selectedOutputUID }).map { $0.name == self.cachedDefaultOutputName ? "\($0.name) (System Default)" : $0.name } ?? "Loading...",+ selection: self.$selectedOutputUID+ ) {// Handle empty state gracefullyif self.outputDevices.isEmpty {Text("Loading...").tag("")@@ -1215,7 +1216,6 @@ struct SettingsView: View {}}}- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 240).disabled(self.asr.isRunning) // Disable device changes during recording@@ -1291,21 +1291,23 @@ struct SettingsView: View {Spacer()if self.settings.overlayPosition == .bottom {- Picker("", selection: self.$settings.overlaySize) {+ FluidDropdownPicker("Overlay size", selectedTitle: self.settings.overlaySize.displayName, selection: self.$settings.overlaySize) {ForEach(SettingsStore.OverlaySize.allCases, id: \.self) { size inText(size.displayName).tag(size)}}- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 170, alignment: .trailing)} else {- Picker("", selection: self.$settings.notchPresentationMode) {+ FluidDropdownPicker(+ "Notch presentation",+ selectedTitle: self.settings.notchPresentationMode.displayName,+ selection: self.$settings.notchPresentationMode+ ) {ForEach(SettingsStore.NotchPresentationMode.allCases, id: \.self) { mode inText(mode.displayName).tag(mode)}}- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 170, alignment: .trailing)}@@ -1405,12 +1407,11 @@ struct SettingsView: View {Spacer()- Picker("", selection: self.$settings.overlayPosition) {+ FluidDropdownPicker("Overlay position", selectedTitle: self.settings.overlayPosition.displayName, selection: self.$settings.overlayPosition) {ForEach(SettingsStore.OverlayPosition.allCases, id: \.self) { position inText(position.displayName).tag(position)}}- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 170, alignment: .trailing)}@@ -3009,7 +3010,7 @@ private extension SettingsView {Spacer()- Picker("", selection: Binding(+ FluidDropdownPicker("Send key", selectedTitle: self.settings.spokenSendKey.displayName, selection: Binding(get: { self.settings.spokenSendKey },set: { self.settings.spokenSendKey = $0 })) {@@ -3017,7 +3018,6 @@ private extension SettingsView {Text(key.displayName).tag(key)}}- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 170, alignment: .trailing).accessibilityLabel("Spoken Send command")@@ -3075,12 +3075,15 @@ private struct DictionarySuggestionsSettingsRow: View {}.frame(maxWidth: .infinity, alignment: .leading)- Picker("Ask after", selection: self.$settings.automaticDictionarySuggestionFrequency) {+ FluidDropdownPicker(+ "Ask after",+ selectedTitle: self.settings.automaticDictionarySuggestionFrequency.displayName,+ selection: self.$settings.automaticDictionarySuggestionFrequency+ ) {ForEach(SettingsStore.AutomaticDictionarySuggestionFrequency.allCases) { frequency inText(frequency.displayName).tag(frequency)}}- .pickerStyle(.menu).fluidDropdownStyle().fixedSize()}diff --git a/Sources/Fluid/UI/WelcomeView.swift b/Sources/Fluid/UI/WelcomeView.swiftindex 1fbe9644..0c706714 100644--- a/Sources/Fluid/UI/WelcomeView.swift+++ b/Sources/Fluid/UI/WelcomeView.swift@@ -2461,8 +2461,9 @@ private struct OnboardingMicrophoneSetupPanel: View {.font(.fluidSystem(size: 12, weight: .semibold)).foregroundStyle(Color.orange.opacity(0.9))} else {- Picker(+ FluidDropdownPicker("Input microphone",+ selectedTitle: self.devices.first(where: { $0.uid == self.selectedUID })?.name ?? "Choose microphone",selection: Binding(get: { self.selectedUID },set: self.onSelect@@ -2473,7 +2474,6 @@ private struct OnboardingMicrophoneSetupPanel: View {}}.labelsHidden()- .pickerStyle(.menu).fluidDropdownStyle().frame(width: 248).tint(.white)diff --git a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swiftindex f2c91c12..a3e0e938 100644--- a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift+++ b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift@@ -336,17 +336,37 @@ final class MicrophoneChangeOverlayController {let hideGeneration = self.generationself.dismissTask?.cancel()self.dismissTask = nil- guard let panel, panel.isVisible else { return }+ guard let panel else { return }+ guard panel.isVisible else {+ self.releasePanel()+ return+ }self.animate(duration: 0.1) {panel.animator().alphaValue = 0} completion: { [weak self] inMainActor.assumeIsolated {- guard let self, self.generation == hideGeneration else { return }- self.panel?.orderOut(nil)- self.panel?.alphaValue = 1- DictionaryCorrectionOverlayController.shared.transientOverlayLayoutDidChange()+ self?.finishHide(generation: hideGeneration)}}+ // AppKit can reach alpha=0 without delivering the animation completion+ // (notably for an inactive nonactivating panel). Bound the hosted timeline.+ Task { @MainActor [weak self] in+ try? await Task.sleep(for: .milliseconds(200))+ self?.finishHide(generation: hideGeneration)+ }+ }++ private func finishHide(generation: UInt64) {+ guard self.generation == generation, self.panel != nil else { return }+ self.releasePanel()+ DictionaryCorrectionOverlayController.shared.transientOverlayLayoutDidChange()+ }++ private func releasePanel() {+ self.panel?.orderOut(nil)+ self.panel?.contentView = nil+ self.hostingView = nil+ self.panel = nil}func topEdge(on screen: NSScreen) -> CGFloat? {diff --git a/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swiftindex bb3fb711..2cdc9776 100644--- a/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift+++ b/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift@@ -875,6 +875,56 @@ final class AudioRouteRecoveryIntegrationTests: XCTestCase {super.tearDown()}+ @MainActor+ func testSpellingTrainingStartsWithPronunciationOffAndKeepsSettings() async throws {+ UserDefaults.standard.set(false, forKey: "DictionarySharedFeatureMatcherEnabled")+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in+ await fixture.service.stopWithoutTranscription()+ fixture.service.micStatus = .authorized+ let outcome = await fixture.service.start(forDictionaryTraining: true, requiresPronunciation: false)+ XCTAssertEqual(outcome, .started)+ XCTAssertTrue(fixture.service.isRunning)+ XCTAssertFalse(DictionaryMatcherExperiment.sharedFeaturesEnabled)+ fixture.assertSettingsPreserved()+ await fixture.service.stopWithoutTranscription()+ }+ }++ @MainActor+ func testPronunciationOnlyTrainingStillRejectsDisabledSwitch() async throws {+ UserDefaults.standard.set(false, forKey: "DictionarySharedFeatureMatcherEnabled")+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in+ await fixture.service.stopWithoutTranscription()+ fixture.service.micStatus = .authorized+ let outcome = await fixture.service.start(forDictionaryTraining: true)+ XCTAssertEqual(outcome, .failed)+ XCTAssertFalse(fixture.service.isRunning)+ XCTAssertFalse(fixture.service.isStarting)+ fixture.assertSettingsPreserved()+ }+ }++ @MainActor+ func testSpellingTrainingSurvivesPronunciationSwitchDuringStartup() async throws {+ try await withASRRecoveryFixture(queryDelay: 0.2) { fixture in+ await fixture.service.stopWithoutTranscription()+ fixture.service.micStatus = .authorized+ let starting = Task { await fixture.service.start(forDictionaryTraining: true, requiresPronunciation: false) }+ for _ in 0..<200 {+ if fixture.service.isStarting { break }+ try await Task.sleep(nanoseconds: 1_000_000)+ }+ XCTAssertTrue(fixture.service.isStarting)+ DictionaryMatcherExperiment.setEnabled(false)+ await fixture.service.cancelPendingPronunciationTrainingStart()+ let outcome = await starting.value+ XCTAssertEqual(outcome, .started)+ XCTAssertTrue(fixture.service.isRunning)+ fixture.assertSettingsPreserved()+ await fixture.service.stopWithoutTranscription()+ }+ }+@MainActorfunc testStartupTriesNewMicrophoneMissingFromDeviceCache() async throws {try await withASRRecoveryFixture(queryDelay: 0) { fixture indiff --git a/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift b/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swiftindex cc7e7f2d..76e84987 100644--- a/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift+++ b/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift@@ -23,7 +23,183 @@ final class CustomDictionaryManualEntryTests: XCTestCase {super.tearDown()}+ func testIncompletePronunciationNoticeRendersWithoutRecordingOrSaving() async throws {+ var actions = 0+ for width in [420.0, 760.0] {+ for scheme in [ColorScheme.light, .dark] {+ let progress = DictionaryTrainingProgress(spellingCount: 3, pronunciationCount: 1, pronunciationEnabled: true)+ let view = DictionaryWordWizard(+ word: .constant("Palermo"),+ step: .review,+ count: 3,+ heard: "pal ermo",+ variants: ["pal ermo"],+ busy: false,+ recording: false,+ processing: false,+ starting: false,+ error: nil,+ voiceSupported: true,+ alreadyCorrect: false,+ savedWord: "",+ onContinue: { actions += 1 },+ onRecord: { actions += 1 },+ onSave: { actions += 1 },+ onBack: { actions += 1 },+ onNewWord: { actions += 1 },+ onManual: { actions += 1 },+ onPracticeMore: { actions += 1 },+ pronunciationNotice: progress.pronunciationNotice,+ pronunciationIncomplete: true+ )+ .padding(20).frame(width: width)+ .background(scheme == .dark ? Color(white: 0.12) : Color(white: 0.96))+ .appTheme(.adaptive(accent: FluidBrandColors.blue, colorScheme: scheme))+ .environment(\.colorScheme, scheme)+ let host = NSHostingView(rootView: view)+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: 1050), styleMask: [.titled], backing: .buffered, defer: false)+ window.contentView = host+ window.appearance = NSAppearance(named: scheme == .dark ? .darkAqua : .aqua)+ window.orderFrontRegardless()+ try await Task.sleep(for: .milliseconds(150))+ host.layoutSubtreeIfNeeded()+ 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: [:]))+ try png.write(to: URL(fileURLWithPath: "/tmp/dictionary-wizard-review-\(Int(width))-\(scheme).png"))+ window.orderOut(nil)+ }+ }+ XCTAssertEqual(actions, 0)+ }++ func testSpellingAndPronunciationReadinessAreIndependent() {+ for spellingCount in 0...4 {+ for pronunciationCount in 0...3 {+ for enabled in [false, true] {+ let progress = DictionaryTrainingProgress(+ spellingCount: spellingCount, pronunciationCount: pronunciationCount, pronunciationEnabled: enabled+ )+ XCTAssertEqual(progress.spellingReady, spellingCount >= 3)+ XCTAssertEqual(progress.pronunciationReady, enabled && pronunciationCount >= 3)+ XCTAssertEqual(progress.pronunciationNotice == nil, !enabled)+ if enabled, spellingCount >= 3, pronunciationCount < 3 {+ XCTAssertTrue(progress.pronunciationNotice?.contains("save spelling corrections only") == true)+ }+ }+ }+ }+ }++ func testAlreadyCorrectSpellingsCanFinishAfterAnEmptyAttempt() {+ // Empty attempts reset the consecutive streak, but do not erase successful examples.+ let progress = DictionaryTrainingProgress(spellingCount: 3, pronunciationCount: 1, pronunciationEnabled: true)+ XCTAssertTrue(progress.spellingAlreadyCorrect(variants: [], lastOutput: "palermo", target: "Palermo"))+ XCTAssertFalse(progress.pronunciationReady)+ XCTAssertFalse(progress.spellingAlreadyCorrect(variants: ["pal ermo"], lastOutput: "palermo", target: "Palermo"))+ XCTAssertFalse(progress.spellingAlreadyCorrect(variants: [], lastOutput: "", target: "Palermo"))+ XCTAssertFalse(progress.spellingAlreadyCorrect(variants: [], lastOutput: "different", target: "Palermo"))+ let incomplete = DictionaryTrainingProgress(spellingCount: 2, pronunciationCount: 0, pronunciationEnabled: false)+ XCTAssertFalse(incomplete.spellingAlreadyCorrect(variants: [], lastOutput: "palermo", target: "Palermo"))+ }++ func testIncompletePronunciationAtLimitOffersABoundedRecovery() {+ let progress = DictionaryTrainingProgress(spellingCount: 20, pronunciationCount: 2, pronunciationEnabled: true)+ XCTAssertTrue(progress.spellingReady)+ XCTAssertFalse(progress.pronunciationReady)+ XCTAssertTrue(progress.pronunciationNotice?.contains("redo recordings") == true)+ }++ func testSpeechMonitorDeadlineStopsSilenceOnceAndCancelsOldDeadline() async {+ let monitor = DictionaryTrainingEndpointMonitor()+ let stale = expectation(description: "Old deadline cannot stop new capture")+ stale.isInverted = true+ let stopped = expectation(description: "Silence reaches bounded stop")+ monitor.start(isCurrent: { true }, audioGeneration: { 0 }, readChunk: { _ in [] }, maximumDuration: .milliseconds(20)) {+ stale.fulfill()+ }+ monitor.start(isCurrent: { true }, audioGeneration: { 0 }, readChunk: { _ in [] }, maximumDuration: .milliseconds(80)) {+ stopped.fulfill()+ }+ await fulfillment(of: [stopped, stale], timeout: 0.3)+ monitor.stop()+ }+#if arch(arm64)+ func testAutomaticSpeechEndWorksWithPronunciationOffAndAcrossToggles() async throws {+ let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent()+ .appendingPathComponent("Resources/dictation_fixture.wav")+ let samples = try AudioConverter().resampleAudioFile(path: fixture.path) + [Float](repeating: 0, count: 32_000)+ for toggleDuringCapture in [false, true] {+ DictionaryMatcherExperiment.setEnabled(toggleDuringCapture)+ let monitor = DictionaryTrainingEndpointMonitor()+ let stopped = expectation(description: "Speech ends independently of pronunciation")+ var callbacks = 0+ monitor.start(+ isCurrent: { true },+ audioGeneration: { 0 },+ readChunk: { offset in+ if toggleDuringCapture, offset > 0 {+ DictionaryMatcherExperiment.setEnabled(false)+ }+ let end = offset + DictionaryTrainingEndpointDetector.chunkSize+ return end <= samples.count ? Array(samples[offset..<end]) : []+ },+ onSpeechEnded: { callbacks += 1; stopped.fulfill() }+ )+ await fulfillment(of: [stopped], timeout: 10)+ monitor.stop()+ XCTAssertEqual(callbacks, 1)+ XCTAssertFalse(DictionaryMatcherExperiment.sharedFeaturesEnabled)+ }+ }++ func testCancelledSpeechMonitorCannotStopReplacementCapture() async throws {+ let monitor = DictionaryTrainingEndpointMonitor()+ var current = true+ let read = expectation(description: "Old capture read")+ let staleCallback = expectation(description: "No callback for stale capture")+ staleCallback.isInverted = true+ monitor.start(+ isCurrent: { current },+ audioGeneration: { 0 },+ readChunk: { _ in+ current = false+ read.fulfill()+ return [Float](repeating: 0, count: DictionaryTrainingEndpointDetector.chunkSize)+ },+ onSpeechEnded: { staleCallback.fulfill() }+ )+ await fulfillment(of: [read], timeout: 10)+ monitor.stop()+ await fulfillment(of: [staleCallback], timeout: 0.2)+ }+ #endif++ #if arch(arm64)+ func testTrainingTranscribesSpellingsAcrossPronunciationToggle() async throws {+ let provider = FluidAudioProvider(modelOverride: .parakeetTDTv2, configureWordBoosting: false)+ try await provider.prepare()+ let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent()+ .appendingPathComponent("Resources/dictation_fixture.wav")+ let samples = try AudioConverter().resampleAudioFile(path: fixture.path)+ for enabled in [false, true, false] {+ DictionaryMatcherExperiment.setEnabled(enabled)+ let result = try await provider.transcribeDictionaryTraining(samples, capturePronunciation: enabled)+ XCTAssertFalse(result.text.isEmpty, "Spelling transcription must work with either toggle value")+ if enabled {+ XCTAssertNotNil(result.pronunciationEnrollment, "On must capture pronunciation alongside spellings")+ } else {+ XCTAssertNil(result.pronunciationEnrollment)+ }+ let entries = CustomDictionaryTrainingMerge.mergedEntries(+ current: [], replacement: "Correct spelling", triggers: [result.text], savePronunciation: false+ )+ XCTAssertEqual(entries.first?.replacement, "Correct spelling")+ XCTAssertEqual(entries.first?.triggers, try [XCTUnwrap(CustomDictionaryTrainingMerge.normalizedTrigger(result.text))])+ }+ }+func testLegacyEdgePreparationOnlyUsesReadyCachedReferences() {let ids = (0..<3).map { _ in UUID() }let enrollments = ids.map { id in@@ -47,7 +223,9 @@ final class CustomDictionaryManualEntryTests: XCTestCase {let frames = [DictionaryMatchFrames(hiddenSize: 2, values: [1, 0])]let entryBytes = 2 * MemoryLayout<Float>.sizevar cache = FluidAudioProvider.TemporalReferenceCache(byteLimit: 9 * entryBytes)- for index in 0..<9 { XCTAssertTrue(cache.insert(frames, for: String(index))) }+ for index in 0..<9 {+ XCTAssertTrue(cache.insert(frames, for: String(index)))+ }XCTAssertEqual(cache.byteCount, 9 * entryBytes)XCTAssertEqual(cache["0"], frames, "Adding a ninth word must preserve earlier references")XCTAssertFalse(cache.insert(frames, for: "overflow"))diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swiftindex 34d1d8be..6980a0e6 100644--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift@@ -3221,6 +3221,32 @@ final class AudioBudgetMeasurementGateTests: XCTestCase {@MainActorfinal class SimpleUpdaterTests: XCTestCase {+ func testInstallStatusClosesWithoutTerminatingTheOldApp() throws {+ let updater = SimpleUpdater()+ let version = "status-test-\(UUID().uuidString)"+ updater.showUpdateInstallStatus(version: version)+ defer { updater.dismissUpdateInstallStatus() }+ let window = try XCTUnwrap(NSApplication.shared.windows.first {+ $0.title == "Installing FluidVoice \(version)"+ })+ XCTAssertTrue(window.isVisible)++ // The updater closes its window after the file swap, before asking AppKit to+ // relaunch/quit. The old process intentionally stays alive throughout this test.+ updater.dismissUpdateInstallStatus()+ XCTAssertFalse(window.isVisible)+ updater.dismissUpdateInstallStatus()+ XCTAssertFalse(window.isVisible)++ updater.showUpdateInstallStatus(version: version)+ let replacement = try XCTUnwrap(NSApplication.shared.windows.first {+ $0.title == "Installing FluidVoice \(version)" && $0.isVisible+ })+ XCTAssertFalse(replacement === window)+ updater.dismissUpdateInstallStatus()+ XCTAssertFalse(replacement.isVisible)+ }+func testUpdateOperationGateAllowsOnlyOneActiveInstall() {var gate = UpdateOperationGate()@@ -4195,10 +4221,9 @@ extension DictationE2ETests {let disabled = try await provider.transcribeFinal(pcm)XCTAssertEqual(disabled.text, baseline.text, "Off must preserve ordinary recognition despite saved profiles")XCTAssertNil(disabled.dictionaryLearningAlignment, "Off must not retain pronunciation learning alignment")- do {- _ = try await provider.transcribeDictionaryTraining(pcm, capturePronunciation: true)- XCTFail("Off must reject voice enrollment")- } catch is CancellationError {}+ let spellingOnly = try await provider.transcribeDictionaryTraining(pcm, capturePronunciation: true)+ XCTAssertFalse(spellingOnly.text.isEmpty, "Off must still transcribe spelling examples")+ XCTAssertNil(spellingOnly.pronunciationEnrollment, "Off must reject voice enrollment")for key in keys {UserDefaults.standard.set(false, forKey: key)}diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swiftindex 9ebd8093..a3ca8efb 100644--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift@@ -410,7 +410,11 @@ final class HotkeyShortcutTests: XCTestCase {NotchContentState.shared.updateTranscription(String(repeating: "multiline preview text ", count: 30))controller.refreshSizeForContent()- try await Task.sleep(nanoseconds: 120_000_000)+ // SwiftUI layout can finish after 120 ms on a busy host; await the actual resize.+ let resizeDeadline = Date().addingTimeInterval(2)+ while let size = controller.windowSizeForTests, size.height <= emptySize.height, Date() < resizeDeadline {+ try await Task.sleep(for: .milliseconds(10))+ }let expandedSize = try XCTUnwrap(controller.windowSizeForTests)XCTAssertGreaterThan(expandedSize.height, emptySize.height)diff --git a/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swiftindex 4a16e84c..af8f2b52 100644--- a/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift@@ -344,7 +344,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {_ = try await harness.owner.prepare(lease: lease,attemptID: UUID(),- configuration: MeetingFinalProcessingConfiguration(languageCode: "de")+ configuration: MeetingFinalProcessingConfiguration(asrModel: "parakeet-tdt-v2", languageCode: "de"))XCTFail("Expected unsupported policy rejection")} catch let error as MeetingProviderOptionsError {diff --git a/Tests/FluidDictationIntegrationTests/MeetingLiveTranscriptionTests.swift b/Tests/FluidDictationIntegrationTests/MeetingLiveTranscriptionTests.swiftindex 324f068b..343c5968 100644--- a/Tests/FluidDictationIntegrationTests/MeetingLiveTranscriptionTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingLiveTranscriptionTests.swift@@ -317,6 +317,17 @@ final class MeetingLiveEchoFilterTests: XCTestCase {}final class MeetingLiveMemoryGateTests: XCTestCase {+ func testNonEnglishRecordingDoesNotStartEnglishCaptionEngines() {+ let notice = expectation(description: "Final transcript available after recording")+ let coordinator = MeetingLiveTranscriptionCoordinator { snapshot in+ XCTAssertEqual(snapshot.availability, .unavailable(reason: "Live captions support English only. Your transcript will be generated after recording."))+ XCTAssertTrue(snapshot.utterances.isEmpty)+ notice.fulfill()+ }+ coordinator.start(mode: .onlineCall, languageCode: "de")+ wait(for: [notice], timeout: 1)+ }+func testBelowThresholdDisablesLive() {let oneGigabyte: UInt64 = 1 * 1024 * 1024 * 1024XCTAssertFalse(MeetingLiveTranscriptionCoordinator.isMemorySufficient(physicalMemory: oneGigabyte))diff --git a/Tests/FluidDictationIntegrationTests/MeetingNemotronModelLocatorTests.swift b/Tests/FluidDictationIntegrationTests/MeetingNemotronModelLocatorTests.swiftindex 7ec6b6b6..e25c7714 100644--- a/Tests/FluidDictationIntegrationTests/MeetingNemotronModelLocatorTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingNemotronModelLocatorTests.swift@@ -90,6 +90,35 @@ final class MeetingNemotronModelLocatorTests: XCTestCase {return package}+ func testHomeDirectoryCapitalizationDoesNotLookLikeASymlink() throws {+ let root = try self.makeTempDirectory()+ let home = root.appendingPathComponent("gabriel/Library/Application Support/FluidVoice/MeetingModels")+ let package = try self.makeFakePackage(at: home)+ let alternate = root.appendingPathComponent("Gabriel/Library/Application Support/FluidVoice/MeetingModels")+ .appendingPathComponent(package.lastPathComponent, isDirectory: true)+ guard FileManager.default.fileExists(atPath: alternate.path) else {+ throw XCTSkip("Capitalization aliases require a case-insensitive volume")+ }+ XCTAssertNotEqual(alternate, alternate.resolvingSymlinksInPath().standardizedFileURL)+ let locator = MeetingNemotronModelLocator(injectedURL: alternate)+ let artifact = try locator.locate()+ XCTAssertEqual(artifact.fileCount, 3)+ XCTAssertEqual(try locator.recheck(artifact), artifact)+ XCTAssertEqual(artifact.manifestSHA256, try MeetingNemotronModelLocator(injectedURL: package).locate().manifestSHA256)+ }++ func testSymlinkedParentRemainsRejected() throws {+ let root = try self.makeTempDirectory()+ let real = root.appendingPathComponent("real")+ let package = try self.makeFakePackage(at: real)+ let link = root.appendingPathComponent("linked")+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: real)+ let alternate = link.appendingPathComponent(package.lastPathComponent, isDirectory: true)+ XCTAssertThrowsError(try MeetingNemotronModelLocator(injectedURL: alternate).locate()) {+ XCTAssertEqual($0 as? MeetingNemotronModelReadinessError, .invalidModelPackage(reason: "packagePathContainsSymlink"))+ }+ }+func testInjectedURLValidatesStructureAndRechecks() throws {let root = try self.makeTempDirectory()let package = try self.makeFakePackage(at: root)diff --git a/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift b/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swiftindex e9a85caf..26b546fb 100644--- a/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift@@ -285,7 +285,7 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {XCTAssertEqual(backend.descriptor.resultContract, .canonicalEvidence)XCTAssertEqual(backend.descriptor.supportedFinalPrecisions, [.word, .utterance])XCTAssertEqual(backend.descriptor.supportedTrackKinds, Set(MeetingAudioTrackKind.allCases))- XCTAssertEqual(backend.descriptor.supportedLanguageCodes, ["en"])+ XCTAssertEqual(backend.descriptor.supportedLanguageCodes, VoiceEngineLanguageCatalog.parakeetV3LanguageIDs)XCTAssertEqual(backend.descriptor.execution, .local)XCTAssertEqual(backend.descriptor.analysisSampleRate, 16_000)@@ -512,16 +512,16 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {)}- let german = self.makeSession(+ let unsupported = self.makeSession(mode: .inRoom,tracks: [self.makeMicTrack(chunks: [self.makeChunk(sequence: 0, start: 0, end: 1)], eraStart: 0)],- languageCode: "de"+ languageCode: "zh")let backend = self.makeBackend(runtime: FakeRuntime())- XCTAssertThrowsError(try backend.plan(self.makeRequest(session: german, directory: directory))) {+ XCTAssertThrowsError(try backend.plan(self.makeRequest(session: unsupported, directory: directory))) {XCTAssertEqual($0 as? MeetingBackendError,- .unsupportedLanguage(backend: .parakeetNemotron, languageCode: "de")+ .unsupportedLanguage(backend: .parakeetNemotron, languageCode: "zh"))}@@ -550,6 +550,32 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {XCTAssertEqual(Set(plan.chunkIDsByTrackID.keys), [fixture.micTrack.id, fixture.appTrack.id])}+ func testMultilingualPlanAndExecutionKeepV3LanguageAndWordEvidence() async throws {+ let fixture = self.makeTwoEpochFixture()+ var session = fixture.session+ session.languageCode = "de"+ let runtime = FakeRuntime()+ let backend = self.makeBackend(runtime: runtime)+ let configuration = MeetingFinalProcessingConfiguration(languageCode: "de")+ let request = self.makeRequest(session: session, directory: try self.makeTempSessionDirectory(), configuration: configuration)+ let plan = try backend.plan(request)+ let manifest = try self.makeManifest(plan: plan, observations: fixture.observations)+ runtime.asrSession.responses = [+ .init(text: "Guten", words: [.init(text: "Guten", start: 0.2, end: 0.4)]),+ .init(text: "Morgen", words: [.init(text: "Morgen", start: 0.2, end: 0.4)]),+ .init(text: "Hallo", words: [.init(text: "Hallo", start: 0.2, end: 0.4)]),+ ]+ let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ guard case let .canonicalEvidence(bundle) = outcome else { return XCTFail("Expected canonical evidence") }+ XCTAssertEqual(runtime.asrConfigurations, [configuration])+ XCTAssertEqual(configuration.asrModel, "parakeet-tdt")+ XCTAssertEqual(bundle.evidence.units.map(\.text), ["Guten", "Morgen", "Hallo"])+ XCTAssertTrue(bundle.coverageReceipts.allSatisfy { $0.status == .processed })+ XCTAssertEqual(runtime.diarizationScopeCount, 1)+ XCTAssertEqual(session.languageCode, "de")+ XCTAssertThrowsError(try backend.plan(self.makeRequest(session: session, directory: request.sessionDirectory)))+ }+func testExecuteRechecksTheExactArtifactFrozenDuringPlan() async throws {let fixture = self.makeTwoEpochFixture()let locator = StubModelLocator()diff --git a/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift b/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swiftindex 527cbc12..35f23b91 100644--- a/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift@@ -1,4 +1,8 @@+import AppKit+import AVFoundation@testable import FluidVoice_Debug+import Foundation+import SwiftUIimport XCTestfinal class MeetingProviderOptionsTests: XCTestCase {@@ -20,7 +24,6 @@ final class MeetingProviderOptionsTests: XCTestCase {func testResolveRejectsUnsupportedModelsWithoutRelabeling() {let unsupportedModels = [- "parakeet-tdt", // raw value of the v3 multilingual model"parakeet-tdt-v3","parakeet-tdt-v99","whisper-tiny",@@ -37,8 +40,8 @@ final class MeetingProviderOptionsTests: XCTestCase {}}- func testResolveRejectsNonEnglishLanguageCode() {- let configuration = MeetingFinalProcessingConfiguration(languageCode: "de")+ func testResolveRejectsNonEnglishLanguageCodeForV2() {+ let configuration = MeetingFinalProcessingConfiguration(asrModel: "parakeet-tdt-v2", languageCode: "de")XCTAssertThrowsError(try MeetingProviderOptions.resolve(configuration)) { error inXCTAssertEqual(error as? MeetingProviderOptionsError,@@ -47,6 +50,52 @@ final class MeetingProviderOptionsTests: XCTestCase {}}+ func testSupportedLanguagesResolveToPinnedModelsWithoutEnhancements() throws {+ for language in VoiceEngineLanguageCatalog.parakeetV3LanguageIDs {+ let configuration = MeetingFinalProcessingConfiguration(languageCode: language)+ let options = try MeetingProviderOptions.resolve(configuration)+ XCTAssertEqual(options.model, language == "en" ? .parakeetTDTv2 : .parakeetTDT)+ XCTAssertFalse(options.vocabularyBoostingEnabled)+ XCTAssertFalse(options.pronunciationMatchingEnabled)+ XCTAssertFalse(options.customDictionaryRewritingEnabled)+ XCTAssertFalse(options.experimentalUnifiedFinalEnabled)+ let capture = MeetingCaptureConfiguration(+ mode: .inRoom,+ title: "Multilingual meeting",+ languageCode: language,+ microphone: .init(captureDeviceID: "fixture", displayName: "Fixture")+ )+ try capture.validate()+ let session = MeetingSession(configuration: capture, timebase: .init(startedHostTime: 1, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil))+ try session.validateForPersistence()+ let restored = try JSONDecoder().decode(MeetingSession.self, from: JSONEncoder().encode(session))+ XCTAssertEqual(restored.languageCode, language)+ }+ XCTAssertThrowsError(try MeetingProviderOptions.resolve(MeetingFinalProcessingConfiguration(languageCode: "zh")))+ }++ func testV3PinsProviderAndChangesResumeFingerprint() throws {+ let configuration = MeetingFinalProcessingConfiguration(languageCode: "de")+ let provider = try FluidAudioProvider(meetingConfiguration: configuration)+ #if arch(arm64)+ XCTAssertEqual(provider.modelOverride, .parakeetTDT)+ #endif+ XCTAssertNotEqual(configuration.identityFingerprint, MeetingFinalProcessingConfiguration().identityFingerprint)+ }++ func testLegacyDefaultsDecodeWithoutLanguageAndNewDefaultsPersistIt() throws {+ let encoder = JSONEncoder()+ let original = MeetingRecordingDefaults.unconfigured+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: encoder.encode(original)) as? [String: Any])+ json.removeValue(forKey: "languageCode")+ let legacy = try JSONDecoder().decode(MeetingRecordingDefaults.self, from: JSONSerialization.data(withJSONObject: json))+ XCTAssertNil(legacy.languageCode)+ XCTAssertEqual(legacy.mode, original.mode)+ var configured = original+ configured.languageCode = "de"+ XCTAssertEqual(try JSONDecoder().decode(MeetingRecordingDefaults.self, from: encoder.encode(configured)).languageCode, "de")+ }+func testResolveRejectsEveryEnhancementFlag() {let cases: [(MeetingFinalProcessingConfiguration, String)] = [(MeetingFinalProcessingConfiguration(vocabularyBoostingEnabled: true), "vocabularyBoosting"),@@ -84,6 +133,64 @@ final class MeetingProviderOptionsTests: XCTestCase {}}+ @MainActor+ func testOptInMeetingLanguageSettingsSnapshot() throws {+ guard let directory = ProcessInfo.processInfo.environment["FLUIDVOICE_MEETING_SETTINGS_SNAPSHOT"] else {+ throw XCTSkip("Set FLUIDVOICE_MEETING_SETTINGS_SNAPSHOT for a settings visual check")+ }+ var draft = MeetingTranscriptionSetupDraft()+ draft.languageCode = "de"+ let view = MeetingRecordingSettingsSheet(+ draft: .constant(draft),+ retentionPolicy: .constant(SettingsStore.shared.meetingAudioRetentionPolicy),+ applications: [],+ microphones: [],+ readiness: .checking,+ isFirstSetup: false,+ onRefreshSources: {},+ onOpenMicrophoneSettings: {},+ onOpenScreenRecordingSettings: {},+ onOpenVoiceEngine: {},+ onCancel: {},+ onSave: {}+ )+ for (name, scheme) in [("light", ColorScheme.light), ("dark", ColorScheme.dark)] {+ let host = NSHostingView(rootView: view.appTheme(.adaptive(accent: FluidBrandColors.blue, colorScheme: scheme)).environment(\.colorScheme, scheme))+ host.frame = NSRect(x: 0, y: 0, width: 820, height: 720)+ host.layoutSubtreeIfNeeded()+ 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: [:]))+ try png.write(to: URL(fileURLWithPath: directory).appendingPathComponent("meeting-language-\(name).png"))+ }+ }++ #if arch(arm64)+ @MainActor+ func testOptInGermanV3AudioProducesOriginalLanguageAndWordTimings() async throws {+ guard let path = ProcessInfo.processInfo.environment["FLUIDVOICE_MEETING_GERMAN_FIXTURE"] else {+ 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.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)))+ let selected = SettingsStore.shared.selectedSpeechModel+ let provider = try FluidAudioProvider(meetingConfiguration: .init(languageCode: "de"))+ try await provider.prepare(progressHandler: nil)+ let output = try await provider.transcribeWithWordTimings(samples)+ print("Meeting v3 German smoke: \(output.result.text); words=\(output.words.count)")+ 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 })+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selected)+ }+ #endif+#if arch(arm64)func testLegacyConstructorsKeepDynamicModelResolution() {XCTAssertNil(FluidAudioProvider().modelOverride)diff --git a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swiftindex 90414360..005eb640 100644--- a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift@@ -405,7 +405,7 @@ final class MeetingRecoveryTests: XCTestCase {}let started = await recorder.events.contains("store.save.start")XCTAssertTrue(started, "The first snapshot must be in flight before the burst")- for index in 1..<1_000 {+ for index in 1..<1000 {session.events.append(MeetingSessionEvent(id: UUID(), occurredAt: Date(), kind: .writerFailure, trackID: nil, detail: "Failure \(index)"))queue.enqueue(session)}@@ -416,7 +416,7 @@ final class MeetingRecoveryTests: XCTestCase {await secondFlush.valuelet savedCounts = await store.savedEventCounts- XCTAssertEqual(savedCounts, [1, 1_000], "Slow storage must not save or retain every intermediate snapshot")+ XCTAssertEqual(savedCounts, [1, 1000], "Slow storage must not save or retain every intermediate snapshot")let persisted = try await store.load(id: session.id)XCTAssertEqual(persisted?.events.map(\.id), session.events.map(\.id))XCTAssertEqual(persisted?.events.last?.detail, session.events.last?.detail)@@ -2690,6 +2690,140 @@ final class MeetingRecoveryTests: XCTestCase {// MARK: - Transcript corrections: persistence, undo, gating+ func testTranscriptTextEditPersistsExportsAndUndoesWithoutChangingRecording() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)+ var (session, _, _, segmentID) = self.makeCorrectionSession(state: .completed)+ var other = session.transcriptSegments[0]+ other.id = UUID()+ session.transcriptSegments.append(other)+ try await store.create(session)+ let baseline = try await store.load(id: session.id)+ session = try XCTUnwrap(baseline)+ let coordinator = MeetingSessionCoordinator(+ store: store, capture: StubCaptureController(), processing: StubProcessingController(), audioArbiter: StubArbiter()+ )+ let original = session.transcriptSegments[0]+ let edited = try await coordinator.editTranscriptText(+ sessionID: session.id, segmentID: segmentID, text: " Corrected words ", expectedRevision: original.revision+ )+ var expected = session+ expected.transcriptSegments[0].text = "Corrected words"+ expected.transcriptSegments[0].originalText = original.text+ expected.transcriptSegments[0].revision += 1+ expected.updatedAt = edited.updatedAt+ XCTAssertEqual(edited, expected, "Only this paragraph's text, correction metadata and update time change")+ let loaded = try await store.load(id: session.id)+ let reloaded = try XCTUnwrap(loaded)+ XCTAssertEqual(reloaded.updatedAt.timeIntervalSince1970, floor(edited.updatedAt.timeIntervalSince1970), accuracy: 0.001)+ expected.updatedAt = reloaded.updatedAt // Existing ISO-8601 persistence has second precision.+ XCTAssertEqual(reloaded, expected)+ XCTAssertTrue(MeetingTranscriptExporter.text(for: reloaded).contains("Corrected words"))+ let exportedJSON = try XCTUnwrap(String(data: MeetingTranscriptExporter.json(for: reloaded), encoding: .utf8))+ XCTAssertTrue(exportedJSON.contains("Corrected words"))+ XCTAssertNil(coordinator.activeSession, "Editing history must not start or adopt a recording")++ let editedAgain = try await coordinator.editTranscriptText(+ sessionID: session.id, segmentID: segmentID, text: "Second correction", expectedRevision: original.revision + 1+ )+ XCTAssertEqual(editedAgain.transcriptSegments[0].originalText, original.text)+ let undoSecond = try await coordinator.undoTranscriptCorrection(sessionID: session.id)+ XCTAssertEqual(undoSecond.transcriptSegments, edited.transcriptSegments)+ let undone = try await coordinator.undoTranscriptCorrection(sessionID: session.id)+ XCTAssertEqual(undone.transcriptSegments, session.transcriptSegments)+ XCTAssertEqual(undone.audioTracks, session.audioTracks)+ XCTAssertFalse(coordinator.canUndoCorrection(sessionID: session.id))+ }++ func testTranscriptTextEditRejectsBlankStaleAndIgnoresNoOp() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)+ var (session, _, _, segmentID) = self.makeCorrectionSession(state: .completed)+ try await store.create(session)+ let baseline = try await store.load(id: session.id)+ session = try XCTUnwrap(baseline)+ let coordinator = MeetingSessionCoordinator(+ store: store, capture: StubCaptureController(), processing: StubProcessingController(), audioArbiter: StubArbiter()+ )+ let original = session.transcriptSegments[0]+ for (text, revision, expectedError) in [+ (" \n ", original.revision, MeetingDomainError.emptyTranscriptText),+ ("New text", original.revision - 1, MeetingDomainError.staleTranscriptEdit),+ ] {+ do {+ _ = try await coordinator.editTranscriptText(sessionID: session.id, segmentID: segmentID, text: text, expectedRevision: revision)+ XCTFail("Invalid correction must fail")+ } catch let error as MeetingDomainError {+ XCTAssertEqual(error, expectedError)+ }+ }+ _ = try await coordinator.editTranscriptText(+ sessionID: session.id, segmentID: segmentID, text: " \(original.text) ", expectedRevision: original.revision+ )+ let reloaded = try await store.load(id: session.id)+ XCTAssertEqual(reloaded, session)+ XCTAssertFalse(coordinator.canUndoCorrection(sessionID: session.id))+ }++ func testTranscriptTextFailedSaveKeepsOriginalAndAllowsRetry() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)+ var (session, _, _, segmentID) = self.makeCorrectionSession(state: .completed)+ try await store.create(session)+ let baseline = try await store.load(id: session.id)+ session = try XCTUnwrap(baseline)+ let gated = GatedThrowingSaveStore(inner: store, recorder: EventRecorder())+ await gated.throwOnNextSave()+ let coordinator = MeetingSessionCoordinator(+ store: gated, capture: StubCaptureController(), processing: StubProcessingController(), audioArbiter: StubArbiter()+ )+ do {+ _ = try await coordinator.editTranscriptText(sessionID: session.id, segmentID: segmentID, text: "Corrected", expectedRevision: 1)+ XCTFail("Save failure must propagate")+ } catch {}+ let reloaded = try await store.load(id: session.id)+ XCTAssertEqual(reloaded, session)+ XCTAssertFalse(coordinator.canUndoCorrection(sessionID: session.id))+ let retried = try await coordinator.editTranscriptText(sessionID: session.id, segmentID: segmentID, text: "Corrected", expectedRevision: 1)+ XCTAssertEqual(retried.transcriptSegments[0].text, "Corrected")+ XCTAssertTrue(coordinator.canUndoCorrection(sessionID: session.id))+ }++ func testTranscriptEditorRendersWithoutInvokingSaveOrCancel() throws {+ guard let path = ProcessInfo.processInfo.environment["FLUIDVOICE_MEETING_EDIT_SNAPSHOT"] else {+ throw XCTSkip("Opt-in transcript editor visual check")+ }+ let output = URL(fileURLWithPath: path, isDirectory: true)+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ var actions = 0+ for scheme in [ColorScheme.light, .dark] {+ let view = MeetingTranscriptTextEditor(+ text: "Today we reviewed the project timeline. Our next meeting is on Friday.",+ onSave: { _ in actions += 1; return nil },+ onCancel: { actions += 1 }+ )+ .appTheme(.adaptive(accent: FluidBrandColors.blue, colorScheme: scheme))+ .environment(\.colorScheme, scheme)+ let host = NSHostingView(rootView: view)+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 560, height: 440), styleMask: [.borderless], backing: .buffered, defer: false)+ window.appearance = NSAppearance(named: scheme == .dark ? .darkAqua : .aqua)+ host.appearance = window.appearance+ window.contentView = host+ window.makeKeyAndOrderFront(nil)+ RunLoop.current.run(until: Date().addingTimeInterval(0.2))+ defer { window.orderOut(nil) }+ host.layoutSubtreeIfNeeded()+ host.displayIfNeeded()+ let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: bitmap)+ try XCTUnwrap(bitmap.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("editor-\(scheme).png"))+ }+ XCTAssertEqual(actions, 0)+ }+func testEachCorrectionOpOnHistorySessionPersists() async throws {let dir = self.makeTempDirectory()defer { try? FileManager.default.removeItem(at: dir) }@@ -2903,6 +3037,12 @@ final class MeetingRecoveryTests: XCTestCase {}}+ do {+ _ = try await coordinator.editTranscriptText(sessionID: session.id, segmentID: session.transcriptSegments[0].id, text: "Correction", expectedRevision: 1)+ XCTFail("Text edit must fail while processing")+ } catch let error as MeetingCoordinatorError {+ guard case .activityInProgress = error else { return XCTFail("Expected activityInProgress, got \(error)") }+ }processing.openGate()_ = try await retryTask.value}@@ -4425,6 +4565,42 @@ final class MeetingRecoveryTests: XCTestCase {XCTAssertEqual(MeetingTranscriptionSetupDraft.defaultTitle(mode: .onlineCall, applicationDisplayName: nil), "Meeting")}+ func testAutomaticMeetingTitleUsesRecordingStartAndPreservesCustomNames() throws {+ let timebase = MeetingTimebaseMetadata(startedHostTime: 1, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil)+ let startedAt = Date(timeIntervalSince1970: 1_800_000_000)+ let configuration = MeetingCaptureConfiguration(+ mode: .inRoom,+ title: "Meeting",+ microphone: .init(captureDeviceID: "fixture", displayName: "Fixture"),+ timestampDefaultTitle: true+ )+ let first = MeetingSession(configuration: configuration, startedAt: startedAt, timebase: timebase)+ let later = MeetingSession(configuration: configuration, startedAt: startedAt.addingTimeInterval(3600), timebase: timebase)+ XCTAssertTrue(first.title.hasPrefix("Meeting · "))+ XCTAssertNotEqual(first.title, later.title)+ XCTAssertEqual(first.defaultTitleBase, "Meeting")+ XCTAssertEqual(first.startedAt, startedAt)+ XCTAssertEqual(first.selectedMicrophone, configuration.microphone)+ var custom = configuration+ custom.title = "Weekly planning"+ custom.timestampDefaultTitle = false+ let named = MeetingSession(configuration: custom, startedAt: startedAt, timebase: timebase)+ XCTAssertEqual(named.title, "Weekly planning")+ XCTAssertNil(named.defaultTitleBase)+ let restored = try JSONDecoder().decode(MeetingSession.self, from: JSONEncoder().encode(first))+ XCTAssertEqual(restored.title, first.title)+ XCTAssertEqual(restored.defaultTitleBase, "Meeting")+ }++ func testOldMeetingWithoutAutomaticTitleMetadataKeepsItsTitle() throws {+ let (session, _, _, _) = self.makeCorrectionSession(state: .completed)+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(session)) as? [String: Any])+ json.removeValue(forKey: "defaultTitleBase")+ let restored = try JSONDecoder().decode(MeetingSession.self, from: JSONSerialization.data(withJSONObject: json))+ XCTAssertEqual(restored.title, session.title)+ XCTAssertNil(restored.defaultTitleBase)+ }+// MARK: - Rename sessionfunc testRenameSessionRejectsEmptyOrWhitespaceTitle() async throws {@@ -4454,7 +4630,8 @@ final class MeetingRecoveryTests: XCTestCase {let dir = self.makeTempDirectory()defer { try? FileManager.default.removeItem(at: dir) }let store = MeetingSessionStore(rootDirectory: dir)- let (session, _, _, _) = self.makeCorrectionSession(state: .completed)+ var (session, _, _, _) = self.makeCorrectionSession(state: .completed)+ session.defaultTitleBase = "Meeting"try await store.create(session)let coordinator = MeetingSessionCoordinator(@@ -4463,9 +4640,11 @@ final class MeetingRecoveryTests: XCTestCase {let renamed = try await coordinator.renameSession(sessionID: session.id, to: " Weekly Sync ")XCTAssertEqual(renamed.title, "Weekly Sync")+ XCTAssertNil(renamed.defaultTitleBase)let reloaded = try await store.load(id: session.id)XCTAssertEqual(reloaded?.title, "Weekly Sync")+ XCTAssertNil(reloaded?.defaultTitleBase)// A title rename must not consume the transcript-correction undo stack.XCTAssertFalse(coordinator.canUndoCorrection(sessionID: session.id))}@@ -4563,7 +4742,9 @@ private final class StubCaptureController: MeetingCaptureControlling, @unchecked) async throws -> MeetingCaptureStartResult {self.startCount += 1self.eventHandler = eventHandler- for event in self.startupEvents { eventHandler(event) }+ for event in self.startupEvents {+ eventHandler(event)+ }await self.onStart?()if let startError { throw startError }return self.startResultdiff --git a/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swiftindex d4ac9165..7d98199b 100644--- a/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift@@ -520,6 +520,80 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {XCTAssertEqual(self.dispositions(result)[unit.id]?.disposition, .emitted)}+ @MainActor+ func testPlaybackResetClearsCompletedFailureAndRejectsStaleLoads() async throws {+ let playback = MeetingSegmentPlayback()+ playback.toggle(sessionID: UUID(), segmentID: UUID())+ let deadline = Date().addingTimeInterval(2)+ while playback.isLoading, Date() < deadline {+ try await Task.sleep(for: .milliseconds(1))+ }+ XCTAssertNotNil(playback.errorMessage, "A completed load failure must still be visible")+ playback.stop()+ XCTAssertNil(playback.errorMessage, "Changing meetings clears the old warning")+ playback.toggle(sessionID: UUID(), segmentID: UUID())+ playback.stop()+ try await Task.sleep(for: .milliseconds(100))+ XCTAssertNil(playback.errorMessage)+ XCTAssertNil(playback.activeSegmentID)+ XCTAssertFalse(playback.isLoading)+ XCTAssertFalse(playback.progress.isPlaying)+ XCTAssertEqual(playback.progress.elapsed, 0)+ XCTAssertEqual(playback.progress.duration, 0)+ }++ @MainActor+ func testPlaybackCancellationCannotRestartOrReportStaleFailure() async throws {+ let playback = MeetingSegmentPlayback()+ playback.toggle(sessionID: UUID(), segmentID: UUID())+ playback.toggle(sessionID: UUID(), segmentID: UUID())+ playback.stop()+ try await Task.sleep(for: .milliseconds(100))+ XCTAssertNil(playback.activeSegmentID)+ XCTAssertFalse(playback.isLoading)+ XCTAssertNil(playback.errorMessage)+ }++ @MainActor+ func testStoppedPlaybackReleasesOwner() async throws {+ weak var releasedPlayback: MeetingSegmentPlayback?+ do {+ let playback = MeetingSegmentPlayback()+ releasedPlayback = playback+ playback.toggle(sessionID: UUID(), segmentID: UUID())+ playback.stop()+ }+ try await Task.sleep(for: .milliseconds(100))+ XCTAssertNil(releasedPlayback)+ }++ func testPlaybackInvertsDriftAndDoesNotChangeTranscript() throws {+ let drift = MeetingClockDriftRecord(cumulativeAbsorbedSeconds: 0.006, elapsedValidHostSeconds: 100, eligible: true)+ let (plan, manifest, span) = try self.onlineMicFixture(drift: drift)+ let unit = self.unit(id: "playback", span: span, analysisStart: 1, analysisEnd: 2)+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["playback": .notEcho]+ ))+ let segment = try XCTUnwrap(result.segments.first)+ let original = segment+ let slices = try MeetingSegmentPlaybackPlan.slices(segment: segment, spans: manifest.allSpans, directory: FileManager.default.temporaryDirectory)+ XCTAssertEqual(slices.count, 1)+ XCTAssertEqual(try XCTUnwrap(slices.first).start, 1, accuracy: 0.001)+ XCTAssertEqual(try XCTUnwrap(slices.first).end, 2, accuracy: 0.001)+ XCTAssertEqual(segment, original)+ var otherTrack = segment+ otherTrack.sourceTrackID = UUID()+ XCTAssertThrowsError(try MeetingSegmentPlaybackPlan.slices(segment: otherTrack, spans: manifest.allSpans, directory: FileManager.default.temporaryDirectory))+ var outside = segment+ outside.start = self.mediaTime(1000)+ outside.end = self.mediaTime(1001)+ XCTAssertThrowsError(try MeetingSegmentPlaybackPlan.slices(segment: outside, spans: manifest.allSpans, directory: FileManager.default.temporaryDirectory))+ }+func testCrossSpanUnitMapsOnceAcrossChunkBoundary() throws {let first = self.chunk(sequence: 0, start: 100, end: 105)let second = self.chunk(sequence: 1, start: 105, end: 110)@@ -551,6 +625,12 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {echoVerdicts: ["u-0": .notEcho]))let segment = try XCTUnwrap(result.segments.first)+ let slices = try MeetingSegmentPlaybackPlan.slices(segment: segment, spans: manifest.allSpans, directory: FileManager.default.temporaryDirectory)+ XCTAssertEqual(slices.count, 2)+ XCTAssertEqual(slices[0].start, 4.5, accuracy: 0.001)+ XCTAssertEqual(slices[0].end, 5, accuracy: 0.001)+ XCTAssertEqual(slices[1].start, 0, accuracy: 0.001)+ XCTAssertEqual(slices[1].end, 0.5, accuracy: 0.001)// Start maps through the first span's transform, end through the last's — once each.let expectedStart = spans[0].presentationMapping.presentationTime(forAnalysisTime: 4.5)let expectedEnd = spans[1].presentationMapping.presentationTime(forAnalysisTime: 5.5)diff --git a/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swiftindex f70bbc8e..f2c650f8 100644--- a/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift@@ -640,11 +640,11 @@ final class MeetingTranscriptionBackendTests: XCTestCase {do {_ = try await self.makePipeline(registry: registry(), backendID: nil).process(- session: self.makeSession(languageCode: "fr"),+ session: self.makeSession(languageCode: "zh"),sessionDirectory: FileManager.default.temporaryDirectory,progress: { _ in })- XCTFail("Non-English sessions must still be rejected")+ XCTFail("Unsupported languages must still be rejected")} catch {guard case MeetingProcessingError.unsupportedLanguage = error else {return XCTFail("Expected unsupportedLanguage, got \(error)")@@ -667,6 +667,63 @@ final class MeetingTranscriptionBackendTests: XCTestCase {XCTAssertEqual(factoryCallCount, 0, "preflight failures must not construct a backend")}+ func testSavedLegacyBackendUsesProductionForFrenchWithoutChangingPreference() async {+ let settings = SettingsStore.shared+ let previous = settings.meetingTranscriptionBackendID+ defer { settings.meetingTranscriptionBackendID = previous }+ settings.meetingTranscriptionBackendID = .legacyCompatibility+ let marker = CocoaError(.userCancelled)+ var productionPreparations = 0+ let pipeline = MeetingProcessingPipeline(+ asrServiceProvider: { XCTFail("Routing must happen before ASR loading"); return ASRService() },+ managesModelResidency: false,+ prepareDiarizationModel: { productionPreparations += 1; throw marker }+ )+ do {+ _ = try await pipeline.process(+ session: self.makeSession(languageCode: "fr"),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("Expected the production preparation marker")+ } catch {+ XCTAssertEqual(error as? CocoaError, marker)+ }+ XCTAssertEqual(productionPreparations, 1)+ XCTAssertEqual(settings.meetingTranscriptionBackendID, .legacyCompatibility)+ }++ func testExplicitLegacyAndUnknownSavedBackendsDoNotSilentlyFallBack() async {+ let settings = SettingsStore.shared+ let previous = settings.meetingTranscriptionBackendID+ defer { settings.meetingTranscriptionBackendID = previous }+ let unknown = MeetingBackendID(rawValue: "unknown-saved-backend")+ for pinned in [true, false] {+ settings.meetingTranscriptionBackendID = pinned ? .legacyCompatibility : unknown+ let pipeline = MeetingProcessingPipeline(+ asrServiceProvider: { XCTFail("Rejected selections must not load models"); return ASRService() },+ managesModelResidency: false,+ backendID: pinned ? .legacyCompatibility : nil,+ prepareDiarizationModel: { XCTFail("Explicit/unknown selections must not use production") }+ )+ do {+ _ = try await pipeline.process(+ session: self.makeSession(languageCode: "fr"),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("The incompatible selection must be rejected")+ } catch {+ XCTAssertEqual(+ error as? MeetingBackendError,+ pinned+ ? .unsupportedLanguage(backend: .legacyCompatibility, languageCode: "fr")+ : .unknownBackend(unknown)+ )+ }+ }+ }+/// Every chunk reports unreadable, so a manifest builds to explicit gaps without fixture audio.private struct UnreadableFixtureObserver: MeetingChunkAudioObserving {func observe(diff --git a/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift b/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swiftindex ab6b6c16..1817d00a 100644--- a/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift+++ b/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift@@ -1435,6 +1435,8 @@ final class MeetingSessionModelTests: XCTestCase {XCTAssertNoThrow(try configuration.validate())configuration.languageCode = "fr"+ XCTAssertNoThrow(try configuration.validate())+ configuration.languageCode = "zh"self.assertConfigurationValidationError(.unsupportedLanguage, configuration: configuration)configuration = MeetingModelFixture.makeOnlineConfiguration()@@ -1769,8 +1771,8 @@ final class MeetingSessionModelTests: XCTestCase {private func micTurn(_ cluster: UUID, _ start: Double, _ end: Double,overlapsRemote: Bool = true, echoScored: Bool = true, isEcho: Bool = false- // Mirror the test fixture fields in one named return value.- // swiftlint:disable:next large_tuple+ // Mirror the test fixture fields in one named return value.+ // swiftlint:disable:next large_tuple) -> (clusterID: UUID, start: Double, end: Double, overlapsRemote: Bool, echoScored: Bool, isEcho: Bool) {(cluster, start, end, overlapsRemote, echoScored, isEcho)}diff --git a/Tests/FluidDictationIntegrationTests/VoiceModelDeletionTests.swift b/Tests/FluidDictationIntegrationTests/VoiceModelDeletionTests.swiftnew file mode 100644index 00000000..406b9b85--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/VoiceModelDeletionTests.swift@@ -0,0 +1,244 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++@MainActor+private final class DeletionFixtureProvider: TranscriptionProvider {+ let name = "Deletion fixture"+ let isAvailable = true+ var isReady = true+ var clearCalls = 0+ var prepareCalls = 0+ var clear: (() async throws -> Void)?+ var prepareBody: (() async throws -> Void)?++ func prepare(progressHandler: ((ModelPreparationProgress) -> Void)?) async throws {+ self.prepareCalls += 1+ try await self.prepareBody?()+ }++ func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult {+ ASRTranscriptionResult(text: "", confidence: 0)+ }++ func clearCache() async throws {+ self.clearCalls += 1+ try await self.clear?()+ self.isReady = false+ }+}++@MainActor+final class VoiceModelDeletionTests: XCTestCase {+ func testLegacyNemotronDeletionUsesCanonicalProviderAndInvalidatesOnlyActiveModel() async throws {+ let settings = SettingsStore.shared+ let previous = settings.selectedSpeechModel+ defer { settings.selectedSpeechModel = previous }+ for selected: SettingsStore.SpeechModel in [.nemotronStreaming, .whisperBase] {+ settings.selectedSpeechModel = selected+ let isActive = selected == .nemotronStreaming+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let streamingFile = directory.appendingPathComponent("streaming")+ let offlineFile = directory.appendingPathComponent("offline")+ try Data([1]).write(to: streamingFile)+ try Data([2]).write(to: offlineFile)+ let asr = ASRService()+ let canonical = DeletionFixtureProvider()+ let alias = DeletionFixtureProvider()+ let unrelated = DeletionFixtureProvider()+ asr.modelProvidersForTesting[.nemotronStreaming] = canonical+ asr.modelProvidersForTesting[.nemotronStreaming320] = alias+ asr.modelProvidersForTesting[.whisperBase] = unrelated+ asr.isAsrReady = true+ canonical.clear = {+ XCTAssertEqual(asr.deletingModelID, SettingsStore.SpeechModel.nemotronStreaming.id)+ XCTAssertEqual(asr.activeExclusiveActivity, .modelMaintenance)+ XCTAssertEqual(asr.isAsrReady, !isActive, "Invalidate the active model before deleting its files")+ try FileManager.default.removeItem(at: streamingFile)+ }+ try await asr.clearModelCache(for: .nemotronStreaming320)+ // Active deletion starts the existing asynchronous provider reset.+ let resetDeadline = Date().addingTimeInterval(2)+ while asr.activeExclusiveActivity != nil, Date() < resetDeadline {+ try await Task.sleep(nanoseconds: 1_000_000)+ }+ XCTAssertEqual(canonical.clearCalls, 1)+ XCTAssertFalse(canonical.isReady)+ XCTAssertEqual(alias.clearCalls, 0)+ XCTAssertEqual(unrelated.clearCalls, 0)+ XCTAssertTrue(unrelated.isReady)+ XCTAssertEqual(asr.isAsrReady, !isActive)+ XCTAssertEqual(settings.selectedSpeechModel, selected)+ XCTAssertFalse(FileManager.default.fileExists(atPath: streamingFile.path))+ XCTAssertEqual(try Data(contentsOf: offlineFile), Data([2]))+ XCTAssertNil(asr.deletingModelID)+ XCTAssertNil(asr.activeExclusiveActivity)+ canonical.clear = nil+ }+ }++ func testInactiveDeletionRemovesOnlyTargetAndKeepsSelection() async throws {+ let settings = SettingsStore.shared+ let previous = settings.selectedSpeechModel+ defer { settings.selectedSpeechModel = previous }+ settings.selectedSpeechModel = .whisperBase+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let target = try directory.appendingPathComponent(XCTUnwrap(SettingsStore.SpeechModel.whisperTiny.whisperModelFile))+ let sibling = try directory.appendingPathComponent(XCTUnwrap(SettingsStore.SpeechModel.whisperBase.whisperModelFile))+ let targetLegacy = directory.appendingPathComponent("ggml-tiny.bin")+ let siblingLegacy = directory.appendingPathComponent("ggml-base.bin")+ try Data([3]).write(to: targetLegacy)+ try Data([4]).write(to: siblingLegacy)+ try Data([1]).write(to: target)+ try Data([2]).write(to: sibling)+ let active = DeletionFixtureProvider()+ let asr = ASRService()+ asr.isAsrReady = true+ asr.modelProvidersForTesting[.whisperBase] = active+ asr.modelProvidersForTesting[.whisperTiny] = WhisperProvider(modelDirectory: directory, modelOverride: .whisperTiny)+ try await asr.clearModelCache(for: .whisperTiny)+ XCTAssertFalse(FileManager.default.fileExists(atPath: target.path))+ XCTAssertFalse(FileManager.default.fileExists(atPath: targetLegacy.path))+ XCTAssertEqual(try Data(contentsOf: siblingLegacy), Data([4]))+ XCTAssertEqual(try Data(contentsOf: sibling), Data([2]))+ XCTAssertEqual(settings.selectedSpeechModel, .whisperBase)+ XCTAssertTrue(asr.isAsrReady)+ XCTAssertTrue(active.isReady)+ XCTAssertEqual(active.clearCalls, 0)+ XCTAssertNil(asr.deletingModelID)+ XCTAssertNil(asr.activeExclusiveActivity)+ // Repeated deletion is safe and does not remove the sibling.+ try await asr.clearModelCache(for: .whisperTiny)+ XCTAssertEqual(try Data(contentsOf: sibling), Data([2]))+ }++ func testActiveDeletionUsesCurrentProviderAndBlocksCompetingWork() async throws {+ let settings = SettingsStore.shared+ let previous = settings.selectedSpeechModel+ defer { settings.selectedSpeechModel = previous }+ settings.selectedSpeechModel = .whisperBase+ let asr = ASRService()+ let provider = DeletionFixtureProvider()+ asr.modelProvidersForTesting[.whisperBase] = provider+ asr.isAsrReady = true+ provider.clear = {+ XCTAssertEqual(asr.deletingModelID, SettingsStore.SpeechModel.whisperBase.id)+ XCTAssertEqual(asr.activeExclusiveActivity, .modelMaintenance)+ XCTAssertFalse(asr.isAsrReady)+ do {+ try await asr.downloadModel(.whisperTiny, progressHandler: nil)+ XCTFail("Download must not start during deletion")+ } catch {}+ do {+ try await asr.ensureAsrReady()+ XCTFail("Preparation must not start during deletion")+ } catch {}+ do {+ try await asr.clearModelCache(for: .whisperTiny)+ XCTFail("A second deletion must not start")+ } catch {}+ XCTAssertFalse(asr.hasActiveModelDownload)+ XCTAssertFalse(asr.hasActiveModelPreparation)+ }+ try await asr.clearModelCache()+ XCTAssertEqual(provider.clearCalls, 1)+ XCTAssertFalse(provider.isReady)+ XCTAssertEqual(provider.prepareCalls, 0)+ XCTAssertFalse(asr.isAsrReady)+ XCTAssertEqual(settings.selectedSpeechModel, .whisperBase)+ XCTAssertNil(asr.deletingModelID)+ provider.clear = nil+ }++ func testFailureAndBusyActivityDoNotChangeSelectionOrLeaveDeletionBlocked() async throws {+ let asr = ASRService()+ let provider = DeletionFixtureProvider()+ let selected = SettingsStore.shared.selectedSpeechModel+ asr.modelProvidersForTesting[.whisperTiny] = provider+ let lease = try asr.acquireExclusiveActivity(.dictation)+ do {+ try await asr.clearModelCache(for: .whisperTiny)+ XCTFail("Deletion must not interrupt dictation")+ } catch {}+ XCTAssertEqual(provider.clearCalls, 0)+ XCTAssertEqual(asr.activeExclusiveActivity, .dictation)+ asr.releaseExclusiveActivity(lease)+ provider.clear = { throw CocoaError(.fileWriteNoPermission) }+ do {+ try await asr.clearModelCache(for: .whisperTiny)+ XCTFail("Deletion failures must reach the caller")+ } catch {+ XCTAssertEqual((error as NSError).code, CocoaError.fileWriteNoPermission.rawValue)+ }+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel, selected)+ XCTAssertNil(asr.deletingModelID)+ provider.clear = nil+ try await asr.clearModelCache(for: .whisperTiny)+ XCTAssertEqual(provider.clearCalls, 2)+ }++ func testDownloadInProgressRejectsDeletionWithoutCancellingDownload() async throws {+ let asr = ASRService()+ let provider = DeletionFixtureProvider()+ asr.modelProvidersForTesting[.whisperTiny] = provider+ provider.prepareBody = {+ XCTAssertTrue(asr.hasActiveModelDownload)+ do {+ try await asr.clearModelCache(for: .whisperTiny)+ XCTFail("Deletion must not remove a downloading model")+ } catch {}+ XCTAssertTrue(asr.hasActiveModelDownload)+ XCTAssertFalse(asr.isCancellingModelDownload)+ XCTAssertNil(asr.deletingModelID)+ }+ try await asr.downloadModel(.whisperTiny, progressHandler: nil)+ XCTAssertEqual(provider.prepareCalls, 1)+ XCTAssertEqual(provider.clearCalls, 0)+ XCTAssertFalse(asr.hasActiveModelDownload)+ provider.prepareBody = nil+ }++ func testPreparationInProgressRejectsDeletion() 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)+ do {+ try await asr.clearModelCache(for: .whisperTiny)+ XCTFail("Deletion must not interrupt model preparation")+ } catch {}+ XCTAssertTrue(asr.hasActiveModelPreparation)+ XCTAssertFalse(asr.isCancellingModelPreparation)+ throw CocoaError(.fileReadUnknown)+ }+ do { try await asr.ensureAsrReady() } catch {}+ XCTAssertEqual(provider.prepareCalls, 1)+ XCTAssertEqual(provider.clearCalls, 0)+ XCTAssertFalse(asr.hasActiveModelPreparation)+ provider.prepareBody = nil+ }++ func testCancelledDeletionDoesNotTouchFilesOrLeaveBusyState() async throws {+ let asr = ASRService()+ let provider = DeletionFixtureProvider()+ asr.modelProvidersForTesting[.whisperTiny] = provider+ let task = Task { try await asr.clearModelCache(for: .whisperTiny) }+ task.cancel()+ do {+ try await task.value+ XCTFail("A cancelled request must not delete anything")+ } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") }+ XCTAssertEqual(provider.clearCalls, 0)+ XCTAssertNil(asr.deletingModelID)+ XCTAssertNil(asr.activeExclusiveActivity)+ }+}diff --git a/Tests/PrivateAISettingsControllerDoubles.swift b/Tests/PrivateAISettingsControllerDoubles.swiftindex cdda2473..b66c7daa 100644--- a/Tests/PrivateAISettingsControllerDoubles.swift+++ b/Tests/PrivateAISettingsControllerDoubles.swift@@ -68,8 +68,11 @@ final class AIEnhancementSettingsViewModel {var verificationCount = 0var resetCount = 0var verified = true+ var verificationMessage = "test failure"var smartSelectionCount = 0var smartSelected = false+ var routesDictationThroughPrivateAI: Bool { self.smartSelected }+ func turnOffPrivateAIDictationSlots() { self.smartSelected = false }func selectPrivateAIPromptIfAvailable() {guard self.verified else { return }self.smartSelectionCount += 1@@ -78,7 +81,7 @@ final class AIEnhancementSettingsViewModel {func providerKey(for id: String) -> String { id }func refreshProviderItems() {}- func connectionErrorMessage(for id: String) -> String { "test failure" }+ func connectionErrorMessage(for id: String) -> String { self.verificationMessage }func resetVerification(for id: String) { self.resetCount += 1 }func updateConnectionStatus(_ status: ConnectionStatus, for id: String) {}func verifyPrivateAIProvider(model: PrivateAIRegisteredModel) async -> Bool {@@ -97,6 +100,7 @@ struct DebugLogger {final class PrivateAIIntegrationService {struct LoadedModelState { var state: PrivateAIStatus.State; var modelID: String }static let shared = PrivateAIIntegrationService()+ static let runtimeDidChangeNotification = Notification.Name("TestPrivateAIRuntimeDidChange")static var configuredModelID = "mini"static let selectedModelDefaultsKey = "test-selection"static let localModelPathDefaultsKey = "test-path"@@ -310,5 +314,42 @@ enum PrivateAIControllerChecks {controller.usePreviewModel(isInstalled: true) {}await self.eventually { !controller.isBusy }check(vm.smartSelected && vm.smartSelectionCount == 2, "Another explicit activation switches Basic back to Smart")+ vm.verified = false+ vm.verificationMessage = "Missing local model: model.safetensors."+ let resetsBeforeMissing = vm.resetCount+ let downloadsBeforeMissing = PrivateAIIntegrationService.downloads+ let removalsBeforeMissing = PrivateAIIntegrationService.removals+ controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { reportedError = $0 })+ await self.eventually { !controller.isBusy }+ check(controller.privateAILoadState.needsDownload("mini"), "Missing weights becomes a recoverable download state")+ check(!controller.privateAILoadState.needsDownload("pico"), "Recovery belongs only to the affected model")+ check(controller.privateAILoadState.failureMessage(for: "mini") == nil, "Missing files do not display a raw failure")+ check(reportedError == "Model files are missing. Download again to repair.", "Explicit verification explains recovery")+ check(vm.resetCount == resetsBeforeMissing + 1, "Missing files clear stale verification")+ check(PrivateAIIntegrationService.downloads == downloadsBeforeMissing, "Recovery never silently starts a download")+ check(PrivateAIIntegrationService.removals == removalsBeforeMissing, "Recovery never deletes model files")+ vm.verificationMessage = PrivateAIModelLoadState.missingModelMessage+ controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { reportedError = $0 })+ await self.eventually { !controller.isBusy }+ check(controller.privateAILoadState.needsDownload("mini"), "Missing installation during Verify uses the same recovery as Load")+ check(reportedError == "Model files are missing. Download again to repair.", "Missing installation explains recovery")+ check(vm.resetCount == resetsBeforeMissing + 2, "Missing installation clears stale verification")+ check(+ PrivateAIIntegrationService.downloads == downloadsBeforeMissing && PrivateAIIntegrationService.removals == removalsBeforeMissing,+ "Verification recovery does not download or remove files"+ )+ controller.refreshPrivateAILoadState()+ check(controller.privateAILoadState.needsDownload("mini"), "Passive refresh retains recovery state")+ vm.verified = true+ controller.usePreviewModel(isInstalled: false) {}+ await self.eventually { !controller.isBusy }+ check(controller.privateAILoadState.isLoaded("mini"), "Explicit repair verifies and clears recovery state")+ check(PrivateAIIntegrationService.downloads == downloadsBeforeMissing + 1, "Repair uses the existing download path once")+ for message in ["Network connection lost", "Not enough disk space", "Model checksum mismatch", "Failed to load local model: model.safetensors."] {+ check(+ PrivateAIModelLoadState.failure(modelID: "mini", message: message).failureMessage(for: "mini") == message,+ "Non-missing failures retain their actual diagnostic"+ )+ }}}diff --git a/Tests/UpdaterTerminationBoundaryTests.swift b/Tests/UpdaterTerminationBoundaryTests.swiftnew file mode 100644index 00000000..31142e9e--- /dev/null+++ b/Tests/UpdaterTerminationBoundaryTests.swift@@ -0,0 +1,49 @@+import AppKit++private func record(_ message: String) {+ FileHandle.standardOutput.write(Data((message + "\n").utf8))+}++@MainActor+private final class TerminationDelegate: NSObject, NSApplicationDelegate {+ func applicationDidFinishLaunching(_ notification: Notification) {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {+ if CommandLine.arguments.contains("--original") {+ NSApp.terminate(nil)+ } else {+ UpdateTerminationScheduler.requestTermination()+ }+ }+ }++ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {+ record("termination-requested")+ // Match the real delegate's asynchronous history-save path. Even an immediately+ // ready save cannot execute while terminate occupies the main dispatch queue.+ Task { @MainActor in+ await Task.yield()+ record("history-save-completed")+ sender.reply(toApplicationShouldTerminate: true)+ }+ return .terminateLater+ }++ func applicationWillTerminate(_ notification: Notification) {+ record("termination-completed")+ }+}++@main+private enum UpdaterTerminationBoundaryTests {+ @MainActor+ static func main() {+ let application = NSApplication.shared+ let delegate = TerminationDelegate()+ application.delegate = delegate+ DispatchQueue.global().asyncAfter(deadline: .now() + 5) {+ record("termination-stuck")+ exit(2)+ }+ withExtendedLifetime(delegate) { application.run() }+ }+}diff --git a/scripts/test_updater_termination.sh b/scripts/test_updater_termination.shnew file mode 100644index 00000000..e81bf87f--- /dev/null+++ b/scripts/test_updater_termination.sh@@ -0,0 +1,26 @@+#!/bin/sh+set -eu+cd "$(dirname "$0")/.."+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"+if [ ! -d "$task_developer_dir/Platforms/MacOSX.platform" ]; then+ echo "Select a full Xcode with DEVELOPER_DIR before running these tests." >&2+ exit 1+fi+export DEVELOPER_DIR="$task_developer_dir"+task_test_dir=$(mktemp -d /tmp/fluidvoice-updater-tests.XXXXXX)+trap 'rm -rf "$task_test_dir"' EXIT+xcrun swiftc -swift-version 6 -parse-as-library \+ Sources/Fluid/Services/UpdateTerminationScheduler.swift \+ Tests/UpdaterTerminationBoundaryTests.swift \+ -o "$task_test_dir/termination-tests"+task_original_status=0+"$task_test_dir/termination-tests" --original > "$task_test_dir/original.log" || task_original_status=$?+cat "$task_test_dir/original.log"+test "$task_original_status" -eq 2+grep -q '^termination-stuck$' "$task_test_dir/original.log"+for task_run in 1 2 3; do+ "$task_test_dir/termination-tests" > "$task_test_dir/fixed.log"+ grep -q '^history-save-completed$' "$task_test_dir/fixed.log"+ grep -q '^termination-completed$' "$task_test_dir/fixed.log"+ echo "PASS: fixed termination run $task_run saved history and exited"+done