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
feat(meeting): launch-time crash recovery (M2 slice 1)
Shreeraman A K6fa6b62d2ede
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojindex 9bcccdbb..b1e3b9a2 100644--- a/Fluid.xcodeproj/project.pbxproj+++ b/Fluid.xcodeproj/project.pbxproj@@ -28,6 +28,7 @@D1A600000000000000000202 /* SpeakerTurnMergingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000201 /* SpeakerTurnMergingTests.swift */; };F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1BD00000000000000000001 /* StripThinkingTagsTests.swift */; };D1A600000000000000000204 /* MeetingWindowSelectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */; };+ D1A600000000000000000206 /* MeetingRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000205 /* MeetingRecoveryTests.swift */; };C0DE63600000000000000002 /* AudioEngineRetirementDrainTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */; };DA7100020000000000000002 /* DirectAudioReliabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */; };DA7200020000000000000002 /* AudioHardwareRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */; };@@ -80,6 +81,7 @@D1A600000000000000000201 /* SpeakerTurnMergingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpeakerTurnMergingTests.swift; sourceTree = "<group>"; };F1BD00000000000000000001 /* StripThinkingTagsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StripThinkingTagsTests.swift; sourceTree = "<group>"; };D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingWindowSelectorTests.swift; sourceTree = "<group>"; };+ D1A600000000000000000205 /* MeetingRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingRecoveryTests.swift; sourceTree = "<group>"; };C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioEngineRetirementDrainTests.swift; sourceTree = "<group>"; };DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectAudioReliabilityTests.swift; sourceTree = "<group>"; };DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioHardwareRecoveryTests.swift; sourceTree = "<group>"; };@@ -180,6 +182,7 @@D1A600000000000000000201 /* SpeakerTurnMergingTests.swift */,F1BD00000000000000000001 /* StripThinkingTagsTests.swift */,D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */,+ D1A600000000000000000205 /* MeetingRecoveryTests.swift */,C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */,DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */,DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */,@@ -365,6 +368,7 @@D1A600000000000000000202 /* SpeakerTurnMergingTests.swift in Sources */,F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */,D1A600000000000000000204 /* MeetingWindowSelectorTests.swift in Sources */,+ D1A600000000000000000206 /* MeetingRecoveryTests.swift in Sources */,C0DE63600000000000000002 /* AudioEngineRetirementDrainTests.swift in Sources */,DA7100020000000000000002 /* DirectAudioReliabilityTests.swift in Sources */,DA7200020000000000000002 /* AudioHardwareRecoveryTests.swift in Sources */,diff --git a/Sources/Fluid/Services/AppServices.swift b/Sources/Fluid/Services/AppServices.swiftindex 5a4ec25e..d06d3f1d 100644--- a/Sources/Fluid/Services/AppServices.swift+++ b/Sources/Fluid/Services/AppServices.swift@@ -121,7 +121,7 @@ final class AppServices: ObservableObject {self._meetingSessionCoordinator = coordinatorself.setupMeetingCoordinatorForwarding()Task { @MainActor [weak coordinator] in- await coordinator?.restoreRecoverableSessionIfNeeded()+ await coordinator?.ensureRestored()}return coordinator}diff --git a/Sources/Fluid/Services/Meeting/MeetingModels.swift b/Sources/Fluid/Services/Meeting/MeetingModels.swiftindex 732e4fa3..214eeda1 100644--- a/Sources/Fluid/Services/Meeting/MeetingModels.swift+++ b/Sources/Fluid/Services/Meeting/MeetingModels.swift@@ -408,6 +408,9 @@ nonisolated struct MeetingSession: Codable, Identifiable, Equatable, Sendable {var retention: MeetingRetentionStatevar processingAttempts: [MeetingProcessingAttempt]var updatedAt: Date+ /// Set when the user dismisses a recoverable session so it is not re-offered on next launch.+ /// Optional so pre-M2 persisted manifests still decode.+ var recoveryResolvedAt: Date? = nilinit(id: MeetingSessionID = UUID(),diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swiftindex 0d49fe23..26c521e3 100644--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift@@ -86,6 +86,7 @@ final class MeetingSessionCoordinator: ObservableObject {private var interruptionTask: Task<Void, Never>?private var terminationTask: Task<Void, Never>?private var persistenceTail: Task<Void, Never>?+ private var restoreTask: Task<Void, Never>?init(store: any MeetingSessionStoring,@@ -165,6 +166,7 @@ final class MeetingSessionCoordinator: ObservableObject {@discardableResultfunc startRecording(configuration: MeetingCaptureConfiguration) async throws -> MeetingSession {+ await self.ensureRestored()try configuration.validate()guard self.activeSession == nil,self.stopTask == nil,@@ -289,6 +291,8 @@ final class MeetingSessionCoordinator: ObservableObject {@discardableResultfunc retryProcessing() async throws -> MeetingSession {+ if case .processing = self.state { throw MeetingCoordinatorError.activityInProgress }+ guard self.stopTask == nil else { throw MeetingCoordinatorError.activityInProgress }guard var session = self.activeSession,self.interruptionTask == nil,self.terminationTask == nil,@@ -301,6 +305,12 @@ final class MeetingSessionCoordinator: ObservableObject {let generation = UUID()self.operationGeneration = generationsession.state = .processing+ self.state = .processing(session.id, .pending)+ // Close out zombie attempts left behind by a previous crash before starting a fresh one.+ let closedAt = Date()+ for index in session.processingAttempts.indices where session.processingAttempts[index].completedAt == nil {+ session.processingAttempts[index].completedAt = closedAt+ }session.processingAttempts.append(Self.pendingProcessingAttempt())session.updatedAt = Date()self.activeSession = session@@ -328,69 +338,116 @@ final class MeetingSessionCoordinator: ObservableObject {else {throw MeetingCoordinatorError.activityInProgress}+ if var session = self.activeSession,+ session.state == .interrupted || session.state == .failed+ {+ session.recoveryResolvedAt = Date()+ session.updatedAt = Date()+ self.enqueuePersistence(session)+ }self.activeSession = nilself.trackHealth = [:]self.state = .idle}- func restoreRecoverableSessionIfNeeded() async {- guard self.activeSession == nil else { return }- guard var session = try? await self.store.loadRecoverable().first else { return }- let expectedKinds: Set<MeetingAudioTrackKind> = session.mode == .onlineCall- ? [.applicationAudio, .microphone]- : [.microphone]- guard Set(session.audioTracks.map(\.kind)) == expectedKinds else {- let failure = Self.failure(- from: MeetingCoordinatorError.noRecoverableAudio,- domain: .persistence,- recoverable: false- )- session.state = .failed- session.failures.append(failure)- session.updatedAt = Date()- try? await self.store.save(session)- self.activeSession = session- self.state = .failed(session.id, failure)+ func ensureRestored() async {+ if let restoreTask {+ await restoreTask.valuereturn}+ let task = Task { @MainActor [weak self] in+ guard let self else { return }+ await self.restoreRecoverableSessionIfNeeded()+ }+ self.restoreTask = task+ await task.value+ }- if session.state == .failed,- Self.hasRecoverableAudio(session),- let failure = session.failures.last,- failure.recoverable- {- self.activeSession = session- self.trackHealth = Dictionary(uniqueKeysWithValues: session.audioTracks.map { ($0.kind, $0.health) })- self.state = .failed(session.id, failure)+ private func restoreRecoverableSessionIfNeeded() async {+ guard self.activeSession == nil else { return }+ let recoverable: [MeetingSession]+ do {+ recoverable = try await self.store.loadRecoverable()+ } catch {+ DebugLogger.shared.log("Meeting recovery scan failed; will retry next ensureRestored: \(error)")+ self.restoreTask = nilreturn}-- let previousState = session.state- session.state = .interrupted- if session.endedAt == nil {- session.endedAt = session.audioTracks- .compactMap(\.health.lastSampleAt)- .max() ?? session.updatedAt+ guard !recoverable.isEmpty else { return }++ var viable: [MeetingSession] = []+ for session in recoverable {+ let expectedKinds: Set<MeetingAudioTrackKind> = session.mode == .onlineCall+ ? [.applicationAudio, .microphone]+ : [.microphone]+ let hasExpectedTracks = Set(session.audioTracks.map(\.kind)) == expectedKinds+ if hasExpectedTracks, Self.hasFinalizedAudio(session) {+ viable.append(session)+ continue+ }+ // Non-viable sessions never occupy the active slot; a session already marked+ // .failed keeps its existing failure history instead of gaining a new one.+ if session.state == .failed {+ // Non-viable and already failed: nothing to offer now or later — resolve it+ // so it stops being rescanned. Audio stays on disk, reachable from history.+ if session.recoveryResolvedAt == nil {+ var resolved = session+ resolved.recoveryResolvedAt = Date()+ resolved.updatedAt = Date()+ try? await self.store.save(resolved)+ }+ continue+ }+ var failedSession = session+ failedSession.state = .failed+ if Self.hasFinalizedAudio(session), failedSession.endedAt == nil {+ let backfilled = session.audioTracks+ .compactMap(\.health.lastSampleAt)+ .max() ?? session.updatedAt+ failedSession.endedAt = max(backfilled, session.startedAt)+ }+ let failure = Self.nonViableRecoveryFailure(for: session)+ if failedSession.failures.last?.code != failure.code {+ failedSession.failures.append(failure)+ }+ failedSession.updatedAt = Date()+ do { try await self.store.save(failedSession) } catch {+ DebugLogger.shared.log("Failed to persist non-viable recovery classification for \(session.id): \(error)")+ }}- session.events.append(MeetingSessionEvent(- id: UUID(),- occurredAt: Date(),- kind: .captureStoppedUnexpectedly,- trackID: nil,- detail: previousState == .processing- ? "FluidVoice restarted before transcription completed."- : "FluidVoice restarted before capture finalized."- ))- if session.audioTracks.contains(where: { track in- track.chunks.contains { $0.finalizationState == .finalized }- }), !session.processingAttempts.contains(where: { $0.completedAt == nil }) {- session.processingAttempts.append(Self.pendingProcessingAttempt())+ guard !viable.isEmpty else { return }++ let active = viable.sorted { lhs, rhs in+ lhs.startedAt != rhs.startedAt+ ? lhs.startedAt < rhs.startedAt+ : lhs.id.uuidString < rhs.id.uuidString+ }.last!++ for session in viable {+ guard session.id == active.id else {+ guard session.state != .interrupted, session.state != .failed else { continue }+ let updated = Self.markRecoverableInterrupted(session)+ do { try await self.store.save(updated) } catch {+ DebugLogger.shared.log("Failed to persist deferred recovery for \(session.id): \(error)")+ }+ continue+ }+ if session.state == .failed,+ let failure = session.failures.last,+ failure.recoverable+ {+ // Preserve today's behavior: a failed-but-recoverable session is re-offered as-is.+ self.activeSession = session+ self.trackHealth = Dictionary(uniqueKeysWithValues: session.audioTracks.map { ($0.kind, $0.health) })+ self.state = .failed(session.id, failure)+ } else {+ let updated = Self.markRecoverableInterrupted(session)+ try? await self.store.save(updated)+ self.activeSession = updated+ self.trackHealth = Dictionary(uniqueKeysWithValues: updated.audioTracks.map { ($0.kind, $0.health) })+ self.state = .interrupted(updated.id)+ }}- session.updatedAt = Date()- try? await self.store.save(session)- self.activeSession = session- self.trackHealth = Dictionary(uniqueKeysWithValues: session.audioTracks.map { ($0.kind, $0.health) })- self.state = .interrupted(session.id)}func shutdownForTermination() async {@@ -407,6 +464,7 @@ final class MeetingSessionCoordinator: ObservableObject {}private func performShutdownForTermination() async {+ await self.restoreTask?.valueself.captureGeneration = nilself.degradeReason = nilself.operationGeneration = nil@@ -414,6 +472,7 @@ final class MeetingSessionCoordinator: ObservableObject {self.interruptionTask?.cancel()guard var session = self.activeSession else {+ await self.flushQueuedPersistence()await self.capture.shutdownForTermination()self.releaseActivityLease()return@@ -450,9 +509,7 @@ final class MeetingSessionCoordinator: ObservableObject {: "Transcription paused at app termination and will resume next launch."))}- if session.audioTracks.contains(where: { track in- track.chunks.contains { $0.finalizationState == .finalized }- }), !session.processingAttempts.contains(where: { $0.completedAt == nil }) {+ if Self.shouldQueuePendingAttempt(for: session) {session.processingAttempts.append(Self.pendingProcessingAttempt())}session.updatedAt = Date()@@ -497,8 +554,8 @@ final class MeetingSessionCoordinator: ObservableObject {private func process(_ inputSession: MeetingSession, generation: UUID) async throws -> MeetingSession {var session = inputSession- let sessionDirectory = try await self.store.sessionDirectory(for: session.id)do {+ let sessionDirectory = try await self.store.sessionDirectory(for: session.id)let result = try await self.processing.process(session: session,sessionDirectory: sessionDirectory@@ -680,9 +737,7 @@ final class MeetingSessionCoordinator: ObservableObject {guard self.terminationTask == nil, !Task.isCancelled else { return }session.state = .interrupted- if session.audioTracks.contains(where: { track in- track.chunks.contains { $0.finalizationState == .finalized }- }), !session.processingAttempts.contains(where: { $0.completedAt == nil }) {+ if Self.shouldQueuePendingAttempt(for: session) {session.processingAttempts.append(Self.pendingProcessingAttempt())}session.updatedAt = Date()@@ -721,9 +776,7 @@ final class MeetingSessionCoordinator: ObservableObject {detail: error.localizedDescription))session.state = .interrupted- if session.audioTracks.contains(where: { track in- track.chunks.contains { $0.finalizationState == .finalized }- }), !session.processingAttempts.contains(where: { $0.completedAt == nil }) {+ if Self.shouldQueuePendingAttempt(for: session) {session.processingAttempts.append(Self.pendingProcessingAttempt())}session.updatedAt = Date()@@ -797,6 +850,62 @@ final class MeetingSessionCoordinator: ObservableObject {}}+ private static func shouldQueuePendingAttempt(for session: MeetingSession) -> Bool {+ Self.hasFinalizedAudio(session)+ && !session.processingAttempts.contains(where: { $0.completedAt == nil })+ }++ private static func nonViableRecoveryFailure(for session: MeetingSession) -> MeetingSessionFailure {+ let hasAudio = Self.hasFinalizedAudio(session)+ let message: String+ if session.audioTracks.isEmpty {+ message = "Recording never started — no audio was captured."+ } else if hasAudio {+ message = "Some tracks are missing, but captured audio was preserved."+ } else {+ message = "No finalized audio survived."+ }+ return Self.failure(+ from: MeetingCoordinatorError.noRecoverableAudio,+ domain: .persistence,+ recoverable: hasAudio,+ message: message+ )+ }++ private static func markRecoverableInterrupted(_ inputSession: MeetingSession) -> MeetingSession {+ var session = inputSession+ let previousState = session.state+ session.state = .interrupted+ if session.endedAt == nil {+ session.endedAt = session.audioTracks+ .compactMap(\.health.lastSampleAt)+ .max() ?? session.updatedAt+ }+ if previousState != .interrupted {+ session.events.append(MeetingSessionEvent(+ id: UUID(),+ occurredAt: Date(),+ kind: .captureStoppedUnexpectedly,+ trackID: nil,+ detail: previousState == .processing+ ? "FluidVoice restarted before transcription completed."+ : "FluidVoice restarted before capture finalized."+ ))+ }+ if Self.shouldQueuePendingAttempt(for: session) {+ session.processingAttempts.append(Self.pendingProcessingAttempt())+ }+ session.updatedAt = Date()+ return session+ }++ private static func hasFinalizedAudio(_ session: MeetingSession) -> Bool {+ session.audioTracks.contains { track in+ track.chunks.contains { $0.finalizationState == .finalized && $0.byteCount > 0 }+ }+ }+private static func hasRecoverableAudio(_ session: MeetingSession) -> Bool {session.endedAt != nil && session.audioTracks.contains { track intrack.chunks.contains {@@ -812,7 +921,8 @@ final class MeetingSessionCoordinator: ObservableObject {private static func failure(from error: Error,domain: MeetingFailureDomain,- recoverable: Bool+ recoverable: Bool,+ message: String? = nil) -> MeetingSessionFailure {let nsError = error as NSErrorreturn MeetingSessionFailure(@@ -820,7 +930,7 @@ final class MeetingSessionCoordinator: ObservableObject {occurredAt: Date(),domain: domain,code: "\(nsError.domain).\(nsError.code)",- message: error.localizedDescription,+ message: message ?? error.localizedDescription,recoverable: recoverable)}diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift b/Sources/Fluid/Services/Meeting/MeetingSessionStore.swiftindex daeea5bf..a1eb5e1c 100644--- a/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift+++ b/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift@@ -103,14 +103,23 @@ actor MeetingSessionStore: MeetingSessionStoring {var sessions: [MeetingSession] = []sessions.reserveCapacity(allIDs.count)for id in allIDs {- guard let session = try? self.load(id: id) else { continue }- sessions.append(session)+ do {+ if let session = try self.load(id: id) {+ sessions.append(session)+ }+ } catch {+ DebugLogger.shared.error(+ "Failed to load meeting session \(id): \(error.localizedDescription)",+ source: "MeetingSessionStore"+ )+ }}return sessions.sorted { $0.startedAt > $1.startedAt }}func loadRecoverable() throws -> [MeetingSession] {try self.loadAll().filter {+ guard $0.recoveryResolvedAt == nil else { return false }switch $0.state {case .preparing, .recording, .recordingDegraded, .stopping, .processing, .interrupted:return truediff --git a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swiftnew file mode 100644index 00000000..295c877f--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift@@ -0,0 +1,595 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++@MainActor+final class MeetingRecoveryTests: XCTestCase {+ // MARK: - Fixtures++ private func makeTempDirectory() -> URL {+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent("MeetingRecoveryTests-\(UUID().uuidString)", isDirectory: true)+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ return dir+ }++ private func makeConfiguration(title: String = "Test") -> MeetingCaptureConfiguration {+ MeetingCaptureConfiguration(+ mode: .inRoom,+ title: title,+ microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic-1", displayName: "Mic")+ )+ }++ private func makeTimebase() -> MeetingTimebaseMetadata {+ MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil)+ }++ private func makeFinalizedChunk(+ sequence: Int = 0,+ path: String = "tracks/microphone/chunk_0.caf"+ ) -> MeetingAudioChunk {+ MeetingAudioChunk(+ id: UUID(),+ sequence: sequence,+ relativeFilePath: path,+ presentationStart: MeetingMediaTime(value: 0, timescale: 1000),+ presentationEnd: MeetingMediaTime(value: 1000, timescale: 1000),+ discontinuities: [],+ sha256: "abc123",+ byteCount: 128,+ finalizationState: .finalized+ )+ }++ private func makeMicrophoneTrack(chunks: [MeetingAudioChunk]) -> MeetingAudioTrack {+ MeetingAudioTrack(+ id: UUID(),+ kind: .microphone,+ sourceIdentifier: "mic-1",+ sourceDisplayName: "Mic",+ format: nil,+ timebase: self.makeTimebase(),+ health: .waiting,+ chunks: chunks+ )+ }++ private func makeSession(+ state: MeetingSessionState,+ startedAt: Date = Date(timeIntervalSinceNow: -3600),+ endedAt: Date? = nil,+ audioTracks: [MeetingAudioTrack] = [],+ failures: [MeetingSessionFailure] = [],+ processingAttempts: [MeetingProcessingAttempt] = [],+ recoveryResolvedAt: Date? = nil+ ) -> MeetingSession {+ var session = MeetingSession(configuration: self.makeConfiguration(), startedAt: startedAt, timebase: self.makeTimebase())+ session.state = state+ session.endedAt = endedAt+ session.audioTracks = audioTracks+ session.failures = failures+ session.processingAttempts = processingAttempts+ session.recoveryResolvedAt = recoveryResolvedAt+ session.updatedAt = startedAt+ return session+ }++ // MARK: - Test 1: loadRecoverable classification++ func testLoadRecoverableClassification() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)++ let track = self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])++ let recording = self.makeSession(state: .recording, audioTracks: [track])+ let stopping = self.makeSession(state: .stopping, audioTracks: [track])+ let processing = self.makeSession(state: .processing, endedAt: Date(), audioTracks: [track])+ let interrupted = self.makeSession(state: .interrupted, endedAt: Date(), audioTracks: [track])+ let completed = self.makeSession(state: .completed, endedAt: Date(), audioTracks: [track])+ let recoverableFailed = self.makeSession(+ state: .failed,+ endedAt: Date(),+ audioTracks: [track],+ failures: [MeetingSessionFailure(id: UUID(), occurredAt: Date(), domain: .capture, code: "x", message: "m", recoverable: true)]+ )+ let unrecoverableFailed = self.makeSession(+ state: .failed,+ endedAt: Date(),+ audioTracks: [track],+ failures: [MeetingSessionFailure(id: UUID(), occurredAt: Date(), domain: .persistence, code: "x", message: "m", recoverable: false)]+ )+ let dismissedInterrupted = self.makeSession(+ state: .interrupted,+ endedAt: Date(),+ audioTracks: [track],+ recoveryResolvedAt: Date()+ )++ for session in [recording, stopping, processing, interrupted, completed, recoverableFailed, unrecoverableFailed, dismissedInterrupted] {+ do { try await store.create(session) } catch {+ XCTFail("create failed for state \(session.state): \(error)")+ throw error+ }+ }++ let recoverable = try await store.loadRecoverable()+ let ids = Set(recoverable.map(\.id))++ XCTAssertTrue(ids.contains(recording.id))+ XCTAssertTrue(ids.contains(stopping.id))+ XCTAssertTrue(ids.contains(processing.id))+ XCTAssertTrue(ids.contains(interrupted.id))+ XCTAssertTrue(ids.contains(recoverableFailed.id))+ XCTAssertFalse(ids.contains(completed.id))+ XCTAssertFalse(ids.contains(unrecoverableFailed.id))+ XCTAssertFalse(ids.contains(dismissedInterrupted.id))+ }++ // MARK: - Test 2: multi-session restore++ func testMultiSessionRestoreSelectsNewestViableAndDefersOthers() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)++ let now = Date()+ let track = self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])++ let older = self.makeSession(+ state: .interrupted,+ startedAt: now.addingTimeInterval(-600),+ endedAt: now.addingTimeInterval(-590),+ audioTracks: [track]+ )+ let newer = self.makeSession(+ state: .recording,+ startedAt: now.addingTimeInterval(-60),+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]+ )+ let emptyPreparing = self.makeSession(state: .preparing, startedAt: now.addingTimeInterval(-30))++ for session in [older, newer, emptyPreparing] {+ try await store.create(session)+ }++ let coordinator = MeetingSessionCoordinator(+ store: store,+ capture: StubCaptureController(),+ processing: StubProcessingController(),+ audioArbiter: StubArbiter()+ )+ await coordinator.ensureRestored()++ XCTAssertEqual(coordinator.activeSession?.id, newer.id)+ XCTAssertEqual(coordinator.state, .interrupted(newer.id))++ let persistedOlder = try await store.load(id: older.id)+ XCTAssertEqual(persistedOlder?.state, .interrupted)+ XCTAssertTrue(persistedOlder?.processingAttempts.isEmpty == true)+ XCTAssertEqual(persistedOlder?.events.count, older.events.count)++ let persistedPreparing = try await store.load(id: emptyPreparing.id)+ XCTAssertEqual(persistedPreparing?.state, .failed)+ XCTAssertEqual(persistedPreparing?.failures.last?.recoverable, false)+ XCTAssertEqual(persistedPreparing?.audioTracks.isEmpty, true)++ // Idempotent within the same launch: a second ensureRestored is a no-op.+ await coordinator.ensureRestored()+ XCTAssertEqual(coordinator.activeSession?.id, newer.id)++ // Dismiss the active recovery and simulate the next launch with a fresh coordinator.+ try coordinator.resetForNewMeeting()+ for _ in 0..<100 {+ if let persisted = try await store.load(id: newer.id), persisted.recoveryResolvedAt != nil { break }+ try await Task.sleep(nanoseconds: 5_000_000)+ }+ let coordinator2 = MeetingSessionCoordinator(+ store: store,+ capture: StubCaptureController(),+ processing: StubProcessingController(),+ audioArbiter: StubArbiter()+ )+ await coordinator2.ensureRestored()+ XCTAssertEqual(coordinator2.activeSession?.id, older.id)+ XCTAssertEqual(coordinator2.state, .interrupted(older.id))+ }++ // MARK: - Test 3: dismissal persists recoveryResolvedAt++ func testDismissalPersistsRecoveryResolvedAt() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)++ let track = self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])+ let session = self.makeSession(state: .interrupted, endedAt: Date(), audioTracks: [track])+ try await store.create(session)++ let coordinator = MeetingSessionCoordinator(+ store: store,+ capture: StubCaptureController(),+ processing: StubProcessingController(),+ audioArbiter: StubArbiter()+ )+ await coordinator.ensureRestored()+ XCTAssertEqual(coordinator.activeSession?.id, session.id)++ try coordinator.resetForNewMeeting()++ var persisted: MeetingSession?+ for _ in 0..<40 {+ persisted = try await store.load(id: session.id)+ if persisted?.recoveryResolvedAt != nil { break }+ try await Task.sleep(nanoseconds: 5_000_000)+ }+ XCTAssertNotNil(persisted?.recoveryResolvedAt)++ let coordinator2 = MeetingSessionCoordinator(+ store: store,+ capture: StubCaptureController(),+ processing: StubProcessingController(),+ audioArbiter: StubArbiter()+ )+ await coordinator2.ensureRestored()+ XCTAssertNil(coordinator2.activeSession)+ XCTAssertEqual(coordinator2.state, .idle)+ }++ // MARK: - Test 4: retry hygiene++ func testRetryProcessingClosesStaleAttemptAndRejectsWhileProcessing() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)++ let track = self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])+ let staleAttempt = MeetingProcessingAttempt(+ id: UUID(),+ startedAt: Date().addingTimeInterval(-120),+ completedAt: nil,+ stage: .transcribing,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: nil,+ asrModel: nil,+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )+ let session = self.makeSession(+ state: .interrupted,+ endedAt: Date(),+ audioTracks: [track],+ processingAttempts: [staleAttempt]+ )+ try await store.create(session)++ let processing = GatedProcessingController()+ let coordinator = MeetingSessionCoordinator(+ store: store,+ capture: StubCaptureController(),+ processing: processing,+ audioArbiter: StubArbiter()+ )+ await coordinator.ensureRestored()+ XCTAssertEqual(coordinator.activeSession?.processingAttempts.count, 1)++ let retryTask = Task { try await coordinator.retryProcessing() }++ for _ in 0..<40 {+ if case .processing = coordinator.state { break }+ try await Task.sleep(nanoseconds: 5_000_000)+ }+ guard case .processing = coordinator.state else {+ XCTFail("retryProcessing did not reach .processing state")+ return+ }++ let midFlightAttempts = coordinator.activeSession?.processingAttempts ?? []+ XCTAssertEqual(midFlightAttempts.count, 2)+ XCTAssertEqual(midFlightAttempts.filter { $0.completedAt == nil }.count, 1)+ XCTAssertNotNil(midFlightAttempts.first(where: { $0.id == staleAttempt.id })?.completedAt)++ do {+ _ = try await coordinator.retryProcessing()+ XCTFail("Expected retryProcessing to throw while already processing")+ } catch let error as MeetingCoordinatorError {+ guard case .activityInProgress = error else {+ XCTFail("Expected .activityInProgress, got \(error)")+ return+ }+ }++ processing.openGate()+ let finalSession = try await retryTask.value+ XCTAssertEqual(finalSession.state, .completed)+ XCTAssertEqual(finalSession.processingAttempts.count, 2)+ XCTAssertTrue(finalSession.processingAttempts.allSatisfy { $0.completedAt != nil })+ }++ // MARK: - Test 5: launch race++ func testStartRecordingAwaitsRestoreBeforeCapturing() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let realStore = MeetingSessionStore(rootDirectory: dir)+ let recorder = EventRecorder()+ let gatedStore = GatedRecoverableStore(inner: realStore, recorder: recorder)++ let capture = StubCaptureController()+ capture.startResult = MeetingCaptureStartResult(tracks: [self.makeMicrophoneTrack(chunks: [])], firstPresentationTime: nil)+ capture.onStart = { await recorder.record("capture.start") }++ let coordinator = MeetingSessionCoordinator(+ store: gatedStore,+ capture: capture,+ processing: StubProcessingController(),+ audioArbiter: StubArbiter()+ )++ let startTask = Task { try await coordinator.startRecording(configuration: self.makeConfiguration(title: "Race")) }++ for _ in 0..<40 {+ if await recorder.events.contains("restore.loadRecoverable.start") { break }+ try await Task.sleep(nanoseconds: 5_000_000)+ }+ let eventsBeforeGate = await recorder.events+ XCTAssertTrue(eventsBeforeGate.contains("restore.loadRecoverable.start"))+ XCTAssertFalse(eventsBeforeGate.contains("capture.start"))++ await gatedStore.openGate()+ _ = try await startTask.value++ let finalEvents = await recorder.events+ guard let restoreIndex = finalEvents.firstIndex(of: "restore.loadRecoverable.start"),+ let captureIndex = finalEvents.firstIndex(of: "capture.start")+ else {+ XCTFail("Expected both restore and capture events to be recorded")+ return+ }+ XCTAssertLessThan(restoreIndex, captureIndex)+ }++ // MARK: - Test 6: salvage current behavior pin++ func testMissingChunkFileIsRetainedAsFailedNotDropped() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)++ let chunk = self.makeFinalizedChunk(path: "tracks/microphone/missing.caf")+ let track = self.makeMicrophoneTrack(chunks: [chunk])+ let session = self.makeSession(state: .interrupted, endedAt: Date(), audioTracks: [track])+ try await store.create(session)++ let sessionDirectory = try await store.sessionDirectory(for: session.id)+ let trackManifestDirectory = sessionDirectory+ .appendingPathComponent("tracks", isDirectory: true)+ .appendingPathComponent("microphone", isDirectory: true)+ try FileManager.default.createDirectory(at: trackManifestDirectory, withIntermediateDirectories: true)+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ try encoder.encode(track).write(to: trackManifestDirectory.appendingPathComponent("track.json", isDirectory: false))+ // Deliberately do not write the chunk's audio file, to simulate a missing chunk on disk.++ let loaded = try await store.load(id: session.id)+ let loadedChunk = loaded?.audioTracks.first(where: { $0.kind == .microphone })?.chunks.first++ XCTAssertNotNil(loadedChunk, "A manifest chunk whose file is missing must be retained, not dropped")+ XCTAssertEqual(loadedChunk?.id, chunk.id)+ XCTAssertEqual(loadedChunk?.finalizationState, .failed)+ XCTAssertEqual(loadedChunk?.byteCount, 0)+ XCTAssertEqual(loadedChunk?.sha256, "")+ }++ // MARK: - Test 7: pre-slice JSON without recoveryResolvedAt decodes++ func testPreSliceSessionJSONWithoutResolvedAtDecodes() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = MeetingSessionStore(rootDirectory: dir)+ let session = self.makeSession(+ state: .interrupted,+ endedAt: Date(),+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]+ )+ try await store.create(session)++ let url = dir.appendingPathComponent(session.id.uuidString).appendingPathComponent("session.json")+ var json = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [String: Any]+ json.removeValue(forKey: "recoveryResolvedAt")+ try JSONSerialization.data(withJSONObject: json).write(to: url)++ let reloaded = try await store.load(id: session.id)+ XCTAssertNotNil(reloaded)+ XCTAssertNil(reloaded?.recoveryResolvedAt)+ let recoverable = try await store.loadRecoverable()+ XCTAssertTrue(recoverable.contains(where: { $0.id == session.id }))+ }++ // MARK: - Test 8: retry failure before the pipeline leaves a recoverable state++ func testRetryFailureLeavesRecoverableStateAndReleasesGuards() async throws {+ let dir = self.makeTempDirectory()+ defer { try? FileManager.default.removeItem(at: dir) }+ let store = ThrowingDirectoryStore(wrapping: MeetingSessionStore(rootDirectory: dir))+ let session = self.makeSession(+ state: .interrupted,+ endedAt: Date(),+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]+ )+ try await store.create(session)++ let coordinator = MeetingSessionCoordinator(+ store: store,+ capture: StubCaptureController(),+ processing: StubProcessingController(),+ audioArbiter: StubArbiter()+ )+ await coordinator.ensureRestored()+ XCTAssertNotNil(coordinator.activeSession)++ do {+ _ = try await coordinator.retryProcessing()+ XCTFail("Expected retryProcessing to throw")+ } catch {}++ guard case .failed = coordinator.state else {+ return XCTFail("Expected .failed after sessionDirectory throw, got \(coordinator.state)")+ }+ }+}++// MARK: - Test doubles++private final class ThrowingDirectoryStore: MeetingSessionStoring, @unchecked Sendable {+ private let wrapped: MeetingSessionStore+ var throwOnSessionDirectory = true++ init(wrapping wrapped: MeetingSessionStore) { self.wrapped = wrapped }++ func create(_ session: MeetingSession) async throws { try await self.wrapped.create(session) }+ func save(_ session: MeetingSession) async throws { try await self.wrapped.save(session) }+ func load(id: MeetingSessionID) async throws -> MeetingSession? { try await self.wrapped.load(id: id) }+ func loadAll() async throws -> [MeetingSession] { try await self.wrapped.loadAll() }+ func loadRecoverable() async throws -> [MeetingSession] { try await self.wrapped.loadRecoverable() }+ func sessionDirectory(for id: MeetingSessionID) async throws -> URL {+ if self.throwOnSessionDirectory { throw CocoaError(.fileWriteNoPermission) }+ return try await self.wrapped.sessionDirectory(for: id)+ }+}++private actor EventRecorder {+ private(set) var events: [String] = []+ func record(_ event: String) { self.events.append(event) }+}++private final class StubCaptureController: MeetingCaptureControlling, @unchecked Sendable {+ var startResult = MeetingCaptureStartResult(tracks: [], firstPresentationTime: nil)+ var onStart: (@Sendable () async -> Void)?++ func start(+ session: MeetingSession,+ configuration: MeetingCaptureConfiguration,+ sessionDirectory: URL,+ eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void+ ) async throws -> MeetingCaptureStartResult {+ await self.onStart?()+ return self.startResult+ }++ func stop(sessionID: MeetingSessionID) async throws -> MeetingCaptureStopResult {+ MeetingCaptureStopResult(tracks: [], stoppedAt: Date())+ }++ func shutdownForTermination() async {}+}++@MainActor+private final class StubProcessingController: MeetingProcessingControlling {+ func process(+ session: MeetingSession,+ sessionDirectory: URL,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingProcessingResult {+ MeetingProcessingResult(+ speakers: [],+ segments: [],+ attempt: MeetingProcessingAttempt(+ id: UUID(),+ startedAt: Date(),+ completedAt: Date(),+ stage: .completed,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: nil,+ asrModel: nil,+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )+ )+ }+}++/// Blocks `process(...)` until `openGate()` is called, so tests can inspect mid-flight state.+@MainActor+private final class GatedProcessingController: MeetingProcessingControlling {+ private var isOpen = false+ private var continuation: CheckedContinuation<Void, Never>?++ func openGate() {+ self.isOpen = true+ self.continuation?.resume()+ self.continuation = nil+ }++ func process(+ session: MeetingSession,+ sessionDirectory: URL,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingProcessingResult {+ // Mirrors the real pipeline's convention of reusing the still-open attempt's id.+ let attemptID = session.processingAttempts.last(where: { $0.completedAt == nil })?.id ?? UUID()+ if !self.isOpen {+ await withCheckedContinuation { self.continuation = $0 }+ }+ return MeetingProcessingResult(+ speakers: [],+ segments: [],+ attempt: MeetingProcessingAttempt(+ id: attemptID,+ startedAt: Date(),+ completedAt: Date(),+ stage: .completed,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: nil,+ asrModel: nil,+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )+ )+ }+}++@MainActor+private final class StubArbiter: MeetingAudioActivityArbitrating {+ func acquireMeetingCapture() throws -> MeetingAudioActivityLease { MeetingAudioActivityLease(id: UUID()) }+ func release(_ lease: MeetingAudioActivityLease) {}+}++/// Wraps a real `MeetingSessionStore`, suspending `loadRecoverable()` until `openGate()` is+/// called — used to prove `startRecording` waits for the launch restore barrier.+private actor GatedRecoverableStore: MeetingSessionStoring {+ private let inner: MeetingSessionStore+ private let recorder: EventRecorder+ private var isOpen = false+ private var continuation: CheckedContinuation<Void, Never>?++ init(inner: MeetingSessionStore, recorder: EventRecorder) {+ self.inner = inner+ self.recorder = recorder+ }++ func openGate() {+ self.isOpen = true+ self.continuation?.resume()+ self.continuation = nil+ }++ func create(_ session: MeetingSession) async throws { try await self.inner.create(session) }+ func save(_ session: MeetingSession) async throws { try await self.inner.save(session) }+ func load(id: MeetingSessionID) async throws -> MeetingSession? { try await self.inner.load(id: id) }+ func loadAll() async throws -> [MeetingSession] { try await self.inner.loadAll() }+ func sessionDirectory(for id: MeetingSessionID) async throws -> URL { try await self.inner.sessionDirectory(for: id) }++ func loadRecoverable() async throws -> [MeetingSession] {+ await self.recorder.record("restore.loadRecoverable.start")+ if !self.isOpen {+ await withCheckedContinuation { self.continuation = $0 }+ }+ return try await self.inner.loadRecoverable()+ }+}diff --git a/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift b/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swiftindex 2da71d60..4a15d0a1 100644--- a/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift+++ b/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift@@ -1215,7 +1215,7 @@ final class MeetingSessionCoordinatorTests: XCTestCase {audioArbiter: FakeMeetingAudioActivityArbiter())- await coordinator.restoreRecoverableSessionIfNeeded()+ await coordinator.ensureRestored()XCTAssertEqual(coordinator.activeSession?.id, failedSession.id)XCTAssertEqual(coordinator.activeSession?.state, .failed)@@ -1391,6 +1391,7 @@ private actor FakeMeetingSessionStore: MeetingSessionStoring {func loadRecoverable() -> [MeetingSession] {self.sessions.values.filter {+ guard $0.recoveryResolvedAt == nil else { return false }switch $0.state {case .preparing, .recording, .recordingDegraded, .stopping, .processing, .interrupted:return true