Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

feat(meeting): session-addressable recovery actions + processing resume (M2 slices 2-3)

Shreeraman A Kb49719756dcb
diff --git a/Sources/Fluid/Services/Meeting/MeetingModels.swift b/Sources/Fluid/Services/Meeting/MeetingModels.swift
index 214eeda1..41a4f7f7 100644
--- a/Sources/Fluid/Services/Meeting/MeetingModels.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingModels.swift
@@ -586,6 +586,15 @@ nonisolated struct MeetingSession: Codable, Identifiable, Equatable, Sendable {
}
}
+extension MeetingSession {
+ /// Shared retry/recovery predicate: ended, with at least one finalized non-empty chunk.
+ var hasRetryableAudio: Bool {
+ self.endedAt != nil && self.audioTracks.contains { track in
+ track.chunks.contains { $0.finalizationState == .finalized && $0.byteCount > 0 }
+ }
+ }
+}
+
nonisolated enum MeetingDomainError: LocalizedError, Equatable {
case emptySpeakerName
case speakerNotFound
@@ -673,4 +682,67 @@ nonisolated struct MeetingProcessingResult: Sendable {
var speakers: [MeetingSessionSpeaker]
var segments: [MeetingTranscriptSegment]
var attempt: MeetingProcessingAttempt
+ var skippedChunkIDs: [MeetingAudioChunkID] = []
+}
+
+/// Resume point written after the application-audio pass so a retry can skip re-diarizing and
+/// re-transcribing that track. `trackFingerprints` cover every track's finalized, byteCount>0
+/// chunks (origin depends on all chunks), but deliberately NOT `embeddingIndexByTrack`: only the
+/// microphone pass reads `embeddingIndexByTrack[.microphone]`, so a resumed run keeps the
+/// embeddings already stored on `MeetingSessionSpeaker` instead of rebuilding that index.
+nonisolated struct MeetingProcessingCheckpoint: Codable, Equatable, Sendable {
+ static let currentVersion = 1
+
+ nonisolated struct ChunkFingerprint: Codable, Equatable, Sendable {
+ var id: MeetingAudioChunkID
+ var byteCount: Int64
+ var sha256: String
+ }
+
+ nonisolated struct SpeechInterval: Codable, Equatable, Sendable {
+ var start: TimeInterval
+ var end: TimeInterval
+ }
+
+ var version: Int
+ var sessionID: MeetingSessionID
+ var pipelineVersion: Int
+ var asrProvider: String
+ var asrModel: String
+ var languageCode: String
+ var completedTrackID: MeetingAudioTrackID
+ var trackFingerprints: [MeetingAudioTrackID: [ChunkFingerprint]]
+ var speakers: [MeetingSessionSpeaker]
+ var segments: [MeetingTranscriptSegment]
+ var remoteSpeech: [SpeechInterval]
+ var speakerIDByKey: [String: SessionSpeakerID]
+ var nextRemoteSpeaker: Int
+ var nextMicrophoneSpeaker: Int
+
+ static func fingerprints(for tracks: [MeetingAudioTrack]) -> [MeetingAudioTrackID: [ChunkFingerprint]] {
+ Dictionary(uniqueKeysWithValues: tracks.map { track in
+ (track.id, track.chunks
+ .filter { $0.finalizationState == .finalized && $0.byteCount > 0 }
+ .map { ChunkFingerprint(id: $0.id, byteCount: $0.byteCount, sha256: $0.sha256) })
+ })
+ }
+
+ func isValid(
+ session: MeetingSession,
+ pipelineVersion: Int,
+ provider: String,
+ model: String,
+ language: String,
+ completedTrackID: MeetingAudioTrackID,
+ expectedFingerprints: [MeetingAudioTrackID: [ChunkFingerprint]]
+ ) -> Bool {
+ self.version == Self.currentVersion
+ && self.sessionID == session.id
+ && self.pipelineVersion == pipelineVersion
+ && self.asrProvider == provider
+ && self.asrModel == model
+ && self.languageCode == language
+ && self.completedTrackID == completedTrackID
+ && self.trackFingerprints == expectedFingerprints
+ }
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift b/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift
index e4d96877..65dbde80 100644
--- a/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift
@@ -434,6 +434,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
.min() ?? 0
var accumulator = Accumulator()
var remoteSpeech: [TimelineInterval] = []
+ let expectedFingerprints = MeetingProcessingCheckpoint.fingerprints(for: session.audioTracks)
let context = ProcessingContext(
origin: origin,
@@ -443,28 +444,92 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
asrService: asrService,
languagePin: languagePin
)
+
+ var applicationSkippedChunkIDs: [MeetingAudioChunkID] = []
+ var resumedFromCheckpoint = false
if let applicationTrack = session.audioTracks.first(where: { $0.kind == .applicationAudio }) {
- try await self.processApplicationTrack(
- applicationTrack,
- context: context,
- accumulator: &accumulator,
- remoteSpeech: &remoteSpeech
- )
- attempt.lastCompletedTrackID = applicationTrack.id
+ if let checkpoint = Self.loadCheckpoint(sessionDirectory: sessionDirectory),
+ checkpoint.isValid(
+ session: session,
+ pipelineVersion: Self.pipelineVersion,
+ provider: provider.name,
+ model: selectedModel.rawValue,
+ language: languagePin.languageCode,
+ completedTrackID: applicationTrack.id,
+ expectedFingerprints: expectedFingerprints
+ )
+ {
+ accumulator.speakers = checkpoint.speakers
+ accumulator.segments = checkpoint.segments
+ accumulator.speakerIDByKey = checkpoint.speakerIDByKey
+ accumulator.nextRemoteSpeaker = checkpoint.nextRemoteSpeaker
+ accumulator.nextMicrophoneSpeaker = checkpoint.nextMicrophoneSpeaker
+ remoteSpeech = checkpoint.remoteSpeech.map { TimelineInterval(start: $0.start, end: $0.end) }
+ attempt.lastCompletedTrackID = checkpoint.completedTrackID
+ resumedFromCheckpoint = true
+ DebugLogger.shared.log(
+ "Meeting processing resuming from checkpoint after application track",
+ source: "MeetingProcessingPipeline"
+ )
+ } else {
+ Self.deleteCheckpoint(sessionDirectory: sessionDirectory)
+ }
+
+ if !resumedFromCheckpoint {
+ try await self.processApplicationTrack(
+ applicationTrack,
+ context: context,
+ accumulator: &accumulator,
+ remoteSpeech: &remoteSpeech,
+ skippedChunkIDs: &applicationSkippedChunkIDs
+ )
+ attempt.lastCompletedTrackID = applicationTrack.id
+ if applicationSkippedChunkIDs.isEmpty {
+ Self.writeCheckpoint(
+ MeetingProcessingCheckpoint(
+ version: MeetingProcessingCheckpoint.currentVersion,
+ sessionID: session.id,
+ pipelineVersion: Self.pipelineVersion,
+ asrProvider: provider.name,
+ asrModel: selectedModel.rawValue,
+ languageCode: languagePin.languageCode,
+ completedTrackID: applicationTrack.id,
+ trackFingerprints: expectedFingerprints,
+ speakers: accumulator.speakers,
+ segments: accumulator.segments,
+ remoteSpeech: remoteSpeech.map { MeetingProcessingCheckpoint.SpeechInterval(start: $0.start, end: $0.end) },
+ speakerIDByKey: accumulator.speakerIDByKey,
+ nextRemoteSpeaker: accumulator.nextRemoteSpeaker,
+ nextMicrophoneSpeaker: accumulator.nextMicrophoneSpeaker
+ ),
+ sessionDirectory: sessionDirectory
+ )
+ }
+ }
}
progress(.transcribing)
+ var microphoneSkippedChunkIDs: [MeetingAudioChunkID] = []
if let microphoneTrack = session.audioTracks.first(where: { $0.kind == .microphone }) {
try await self.processMicrophoneTrack(
microphoneTrack,
session: session,
context: context,
remoteSpeech: remoteSpeech,
- accumulator: &accumulator
+ accumulator: &accumulator,
+ skippedChunkIDs: &microphoneSkippedChunkIDs
)
attempt.lastCompletedTrackID = microphoneTrack.id
}
+ let skippedChunkIDs = applicationSkippedChunkIDs + microphoneSkippedChunkIDs
+ let totalFinalizedChunkCount = session.audioTracks.reduce(0) {
+ $0 + $1.chunks.filter { $0.finalizationState == .finalized }.count
+ }
+ guard skippedChunkIDs.count < totalFinalizedChunkCount else {
+ throw MeetingProcessingError.noRecoverableAudio
+ }
+
progress(.finalizing)
accumulator.segments.sort {
if $0.start == $1.start { return $0.sourceTrackID.uuidString < $1.sourceTrackID.uuidString }
@@ -477,124 +542,199 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
return MeetingProcessingResult(
speakers: accumulator.speakers,
segments: accumulator.segments,
- attempt: attempt
+ attempt: attempt,
+ skippedChunkIDs: skippedChunkIDs
)
}
+ private static let checkpointEncoder: JSONEncoder = {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ return encoder
+ }()
+
+ private static let checkpointDecoder: JSONDecoder = {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ return decoder
+ }()
+
+ private static func checkpointURL(sessionDirectory: URL) -> URL {
+ sessionDirectory.appendingPathComponent("checkpoint.json", isDirectory: false)
+ }
+
+ private static func loadCheckpoint(sessionDirectory: URL) -> MeetingProcessingCheckpoint? {
+ guard let data = try? Data(contentsOf: Self.checkpointURL(sessionDirectory: sessionDirectory)) else { return nil }
+ return try? Self.checkpointDecoder.decode(MeetingProcessingCheckpoint.self, from: data)
+ }
+
+ private static func writeCheckpoint(_ checkpoint: MeetingProcessingCheckpoint, sessionDirectory: URL) {
+ let url = Self.checkpointURL(sessionDirectory: sessionDirectory)
+ do {
+ let data = try Self.checkpointEncoder.encode(checkpoint)
+ try data.write(to: url, options: .atomic)
+ try FileManager.default.setAttributes(
+ [.posixPermissions: NSNumber(value: Int16(0o600))],
+ ofItemAtPath: url.path
+ )
+ } catch {
+ DebugLogger.shared.warning("Meeting checkpoint write failed: \(error)", source: "MeetingProcessingPipeline")
+ }
+ }
+
+ private static func deleteCheckpoint(sessionDirectory: URL) {
+ try? FileManager.default.removeItem(at: Self.checkpointURL(sessionDirectory: sessionDirectory))
+ }
+
private func processApplicationTrack(
_ track: MeetingAudioTrack,
context: ProcessingContext,
accumulator: inout Accumulator,
- remoteSpeech: inout [TimelineInterval]
+ remoteSpeech: inout [TimelineInterval],
+ skippedChunkIDs: inout [MeetingAudioChunkID]
) async throws {
let diarizer = SpeakerDiarizationService()
for chunk in track.chunks where chunk.finalizationState == .finalized {
- let url = chunk.fileURL(relativeTo: context.sessionDirectory)
- let chunkOffset = chunk.presentationStart.seconds - context.origin
- if SpeakerDiarizationService.isSupported {
- do {
- let diarization = try await diarizer.diarizeWithProfiles(fileURL: url)
- let turns = diarization.turns
- if !turns.isEmpty {
- remoteSpeech.append(contentsOf: turns.map { turn in
- TimelineInterval(
- start: chunkOffset + turn.startSeconds,
- end: chunkOffset + turn.endSeconds
- )
- })
- var transcribedTurns: [(Int, SpeakerDiarizationService.SpeakerTurn, String)] = []
- for (index, turn) in turns.enumerated() {
- let text = try await self.transcribeTurn(
- turn,
- fileURL: url,
- provider: context.provider,
- languageCode: context.languageCode,
- asrService: context.asrService,
- languagePin: context.languagePin
- )
- guard !text.isEmpty else { throw LabeledPassError.emptyTurn }
- transcribedTurns.append((index, turn, text))
- }
- var speakerIDByLabel: [String: SessionSpeakerID] = [:]
- var usedSpeakerIDs = Set<SessionSpeakerID>()
- for (_, turn, _) in transcribedTurns where speakerIDByLabel[turn.speakerLabel] == nil {
- let resolved = accumulator.resolveCluster(
- trackKind: .applicationAudio,
- newClusterKey: "remote:\(chunk.id.uuidString):\(turn.speakerLabel)",
- profile: diarization.profilesByLabel[turn.speakerLabel],
- excluding: usedSpeakerIDs
- )
- let displayName: String
- if resolved.matchedExisting {
- displayName = "Speaker"
- } else {
- displayName = "Speaker \(accumulator.nextRemoteSpeaker)"
- accumulator.nextRemoteSpeaker += 1
- }
- accumulator.addResolvedSpeaker(
- id: resolved.speakerID,
- key: "remote-cluster:\(resolved.speakerID.uuidString)",
- displayName: displayName,
- clusterID: turn.speakerLabel,
- trackKind: .applicationAudio,
- isLocalUser: false
- )
- speakerIDByLabel[turn.speakerLabel] = resolved.speakerID
- usedSpeakerIDs.insert(resolved.speakerID)
- }
- for (index, turn, text) in transcribedTurns {
- let absoluteStart = chunkOffset + turn.startSeconds
- let absoluteEnd = chunkOffset + turn.endSeconds
- guard let speakerID = speakerIDByLabel[turn.speakerLabel] else { continue }
- accumulator.segments.append(Self.segment(
- key: "remote:\(chunk.id.uuidString):\(index)",
- trackID: track.id,
- speakerID: speakerID,
- start: absoluteStart,
- end: absoluteEnd,
- text: text,
- overlap: .none
- ))
+ // Snapshot so a mid-chunk partial mutation (e.g. some turns transcribed before an
+ // unreadable read) never leaks into the accumulated result for a skipped chunk.
+ let accumulatorSnapshot = accumulator
+ let remoteSpeechSnapshot = remoteSpeech
+ do {
+ try await self.processApplicationChunk(
+ chunk,
+ track: track,
+ diarizer: diarizer,
+ context: context,
+ accumulator: &accumulator,
+ remoteSpeech: &remoteSpeech
+ )
+ } catch {
+ if error is CancellationError { throw error }
+ guard case MeetingProcessingError.audioUnreadable = error else { throw error }
+ accumulator = accumulatorSnapshot
+ remoteSpeech = remoteSpeechSnapshot
+ skippedChunkIDs.append(chunk.id)
+ }
+ }
+ }
+
+ private func processApplicationChunk(
+ _ chunk: MeetingAudioChunk,
+ track: MeetingAudioTrack,
+ diarizer: SpeakerDiarizationService,
+ context: ProcessingContext,
+ accumulator: inout Accumulator,
+ remoteSpeech: inout [TimelineInterval]
+ ) async throws {
+ let url = chunk.fileURL(relativeTo: context.sessionDirectory)
+ let chunkOffset = chunk.presentationStart.seconds - context.origin
+ // Preflight readability once, provider-independent, so a garbage file is skipped
+ // uniformly instead of only surfacing via a post-transcription duration read.
+ let chunkDuration = try await Task.detached(priority: .userInitiated) {
+ try Self.audioDuration(url)
+ }.value
+ if SpeakerDiarizationService.isSupported {
+ do {
+ let diarization = try await diarizer.diarizeWithProfiles(fileURL: url)
+ let turns = diarization.turns
+ if !turns.isEmpty {
+ remoteSpeech.append(contentsOf: turns.map { turn in
+ TimelineInterval(
+ start: chunkOffset + turn.startSeconds,
+ end: chunkOffset + turn.endSeconds
+ )
+ })
+ var transcribedTurns: [(Int, SpeakerDiarizationService.SpeakerTurn, String)] = []
+ for (index, turn) in turns.enumerated() {
+ let text = try await self.transcribeTurn(
+ turn,
+ fileURL: url,
+ provider: context.provider,
+ languageCode: context.languageCode,
+ asrService: context.asrService,
+ languagePin: context.languagePin
+ )
+ guard !text.isEmpty else { throw LabeledPassError.emptyTurn }
+ transcribedTurns.append((index, turn, text))
+ }
+ var speakerIDByLabel: [String: SessionSpeakerID] = [:]
+ var usedSpeakerIDs = Set<SessionSpeakerID>()
+ for (_, turn, _) in transcribedTurns where speakerIDByLabel[turn.speakerLabel] == nil {
+ let resolved = accumulator.resolveCluster(
+ trackKind: .applicationAudio,
+ newClusterKey: "remote:\(chunk.id.uuidString):\(turn.speakerLabel)",
+ profile: diarization.profilesByLabel[turn.speakerLabel],
+ excluding: usedSpeakerIDs
+ )
+ let displayName: String
+ if resolved.matchedExisting {
+ displayName = "Speaker"
+ } else {
+ displayName = "Speaker \(accumulator.nextRemoteSpeaker)"
+ accumulator.nextRemoteSpeaker += 1
}
- continue
+ accumulator.addResolvedSpeaker(
+ id: resolved.speakerID,
+ key: "remote-cluster:\(resolved.speakerID.uuidString)",
+ displayName: displayName,
+ clusterID: turn.speakerLabel,
+ trackKind: .applicationAudio,
+ isLocalUser: false
+ )
+ speakerIDByLabel[turn.speakerLabel] = resolved.speakerID
+ usedSpeakerIDs.insert(resolved.speakerID)
}
- } catch {
- DebugLogger.shared.warning(
- "Meeting remote diarization failed; preserving an unlabeled track transcript",
- source: "MeetingProcessingPipeline"
- )
+ for (index, turn, text) in transcribedTurns {
+ let absoluteStart = chunkOffset + turn.startSeconds
+ let absoluteEnd = chunkOffset + turn.endSeconds
+ guard let speakerID = speakerIDByLabel[turn.speakerLabel] else { continue }
+ accumulator.segments.append(Self.segment(
+ key: "remote:\(chunk.id.uuidString):\(index)",
+ trackID: track.id,
+ speakerID: speakerID,
+ start: absoluteStart,
+ end: absoluteEnd,
+ text: text,
+ overlap: .none
+ ))
+ }
+ return
}
- }
- if let fallback = try await self.transcribeWholeChunk(
- url,
- provider: context.provider,
- languageCode: context.languageCode,
- asrService: context.asrService,
- languagePin: context.languagePin
- ) {
- let duration = try await Task.detached(priority: .userInitiated) {
- try Self.audioDuration(url)
- }.value
- let key = "meeting-audio"
- let speakerID = accumulator.speaker(
- key: key,
- displayName: "Meeting audio",
- trackKind: .applicationAudio,
- isLocalUser: false,
- clusterID: nil
+ } catch {
+ if error is CancellationError { throw error }
+ if case MeetingProcessingError.audioUnreadable = error { throw error }
+ DebugLogger.shared.warning(
+ "Meeting remote diarization failed; preserving an unlabeled track transcript",
+ source: "MeetingProcessingPipeline"
)
- remoteSpeech.append(TimelineInterval(start: chunkOffset, end: chunkOffset + duration))
- accumulator.segments.append(Self.segment(
- key: "remote-fallback:\(chunk.id.uuidString)",
- trackID: track.id,
- speakerID: speakerID,
- start: chunkOffset,
- end: chunkOffset + duration,
- text: fallback,
- overlap: .none
- ))
}
}
+ if let fallback = try await self.transcribeWholeChunk(
+ url,
+ provider: context.provider,
+ languageCode: context.languageCode,
+ asrService: context.asrService,
+ languagePin: context.languagePin
+ ) {
+ let key = "meeting-audio"
+ let speakerID = accumulator.speaker(
+ key: key,
+ displayName: "Meeting audio",
+ trackKind: .applicationAudio,
+ isLocalUser: false,
+ clusterID: nil
+ )
+ remoteSpeech.append(TimelineInterval(start: chunkOffset, end: chunkOffset + chunkDuration))
+ accumulator.segments.append(Self.segment(
+ key: "remote-fallback:\(chunk.id.uuidString)",
+ trackID: track.id,
+ speakerID: speakerID,
+ start: chunkOffset,
+ end: chunkOffset + chunkDuration,
+ text: fallback,
+ overlap: .none
+ ))
+ }
}
private func processMicrophoneTrack(
@@ -602,103 +742,157 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
session: MeetingSession,
context: ProcessingContext,
remoteSpeech: [TimelineInterval],
- accumulator: inout Accumulator
+ accumulator: inout Accumulator,
+ skippedChunkIDs: inout [MeetingAudioChunkID]
) async throws {
let diarizer = SpeakerDiarizationService()
var stagedTurns: [StagedMicrophoneTurn] = []
var cleanDurationByCluster: [SessionSpeakerID: TimeInterval] = [:]
for chunk in track.chunks where chunk.finalizationState == .finalized {
- let url = chunk.fileURL(relativeTo: context.sessionDirectory)
- let chunkOffset = chunk.presentationStart.seconds - context.origin
- if SpeakerDiarizationService.isSupported {
- do {
- let diarization = try await diarizer.diarizeWithProfiles(fileURL: url)
- let turns = diarization.turns
- if !turns.isEmpty {
- var transcribedTurns: [(Int, SpeakerDiarizationService.SpeakerTurn, String)] = []
- for (index, turn) in turns.enumerated() {
- let text = try await self.transcribeTurn(
- turn,
- fileURL: url,
- provider: context.provider,
- languageCode: context.languageCode,
- asrService: context.asrService,
- languagePin: context.languagePin
- )
- guard !text.isEmpty else { throw LabeledPassError.emptyTurn }
- transcribedTurns.append((index, turn, text))
- }
- var clusterIDByLabel: [String: SessionSpeakerID] = [:]
- var usedClusterIDs = Set<SessionSpeakerID>()
- for (_, turn, _) in transcribedTurns where clusterIDByLabel[turn.speakerLabel] == nil {
- let resolved = accumulator.resolveCluster(
- trackKind: .microphone,
- newClusterKey: "microphone:\(chunk.id.uuidString):\(turn.speakerLabel)",
- profile: diarization.profilesByLabel[turn.speakerLabel],
- excluding: usedClusterIDs
- )
- clusterIDByLabel[turn.speakerLabel] = resolved.speakerID
- usedClusterIDs.insert(resolved.speakerID)
+ let accumulatorSnapshot = accumulator
+ let stagedTurnsSnapshot = stagedTurns
+ let cleanDurationByClusterSnapshot = cleanDurationByCluster
+ do {
+ try await self.processMicrophoneChunk(
+ chunk,
+ track: track,
+ diarizer: diarizer,
+ context: context,
+ remoteSpeech: remoteSpeech,
+ accumulator: &accumulator,
+ stagedTurns: &stagedTurns,
+ cleanDurationByCluster: &cleanDurationByCluster
+ )
+ } catch {
+ if error is CancellationError { throw error }
+ guard case MeetingProcessingError.audioUnreadable = error else { throw error }
+ accumulator = accumulatorSnapshot
+ stagedTurns = stagedTurnsSnapshot
+ cleanDurationByCluster = cleanDurationByClusterSnapshot
+ skippedChunkIDs.append(chunk.id)
+ }
+ }
+
+ self.finishMicrophoneTrack(
+ track,
+ session: session,
+ stagedTurns: stagedTurns,
+ cleanDurationByCluster: cleanDurationByCluster,
+ accumulator: &accumulator
+ )
+ }
+
+ private func processMicrophoneChunk(
+ _ chunk: MeetingAudioChunk,
+ track: MeetingAudioTrack,
+ diarizer: SpeakerDiarizationService,
+ context: ProcessingContext,
+ remoteSpeech: [TimelineInterval],
+ accumulator: inout Accumulator,
+ stagedTurns: inout [StagedMicrophoneTurn],
+ cleanDurationByCluster: inout [SessionSpeakerID: TimeInterval]
+ ) async throws {
+ let url = chunk.fileURL(relativeTo: context.sessionDirectory)
+ let chunkOffset = chunk.presentationStart.seconds - context.origin
+ let chunkDuration = try await Task.detached(priority: .userInitiated) {
+ try Self.audioDuration(url)
+ }.value
+ if SpeakerDiarizationService.isSupported {
+ do {
+ let diarization = try await diarizer.diarizeWithProfiles(fileURL: url)
+ let turns = diarization.turns
+ if !turns.isEmpty {
+ var transcribedTurns: [(Int, SpeakerDiarizationService.SpeakerTurn, String)] = []
+ for (index, turn) in turns.enumerated() {
+ let text = try await self.transcribeTurn(
+ turn,
+ fileURL: url,
+ provider: context.provider,
+ languageCode: context.languageCode,
+ asrService: context.asrService,
+ languagePin: context.languagePin
+ )
+ guard !text.isEmpty else { throw LabeledPassError.emptyTurn }
+ transcribedTurns.append((index, turn, text))
+ }
+ var clusterIDByLabel: [String: SessionSpeakerID] = [:]
+ var usedClusterIDs = Set<SessionSpeakerID>()
+ for (_, turn, _) in transcribedTurns where clusterIDByLabel[turn.speakerLabel] == nil {
+ let resolved = accumulator.resolveCluster(
+ trackKind: .microphone,
+ newClusterKey: "microphone:\(chunk.id.uuidString):\(turn.speakerLabel)",
+ profile: diarization.profilesByLabel[turn.speakerLabel],
+ excluding: usedClusterIDs
+ )
+ clusterIDByLabel[turn.speakerLabel] = resolved.speakerID
+ usedClusterIDs.insert(resolved.speakerID)
+ }
+ for (index, turn, text) in transcribedTurns {
+ let start = chunkOffset + turn.startSeconds
+ let end = chunkOffset + turn.endSeconds
+ let overlapsRemote = remoteSpeech.contains {
+ min(end, $0.end) - max(start, $0.start) > 0.15
}
- for (index, turn, text) in transcribedTurns {
- let start = chunkOffset + turn.startSeconds
- let end = chunkOffset + turn.endSeconds
- let overlapsRemote = remoteSpeech.contains {
- min(end, $0.end) - max(start, $0.start) > 0.15
- }
- guard let clusterID = clusterIDByLabel[turn.speakerLabel] else { continue }
- stagedTurns.append(StagedMicrophoneTurn(
- chunkID: chunk.id,
- index: index,
- clusterID: clusterID,
- clusterLabel: turn.speakerLabel,
- start: start,
- end: end,
- text: text,
- overlapsRemote: overlapsRemote
- ))
- if !overlapsRemote {
- cleanDurationByCluster[clusterID, default: 0] += max(0, end - start)
- }
+ guard let clusterID = clusterIDByLabel[turn.speakerLabel] else { continue }
+ stagedTurns.append(StagedMicrophoneTurn(
+ chunkID: chunk.id,
+ index: index,
+ clusterID: clusterID,
+ clusterLabel: turn.speakerLabel,
+ start: start,
+ end: end,
+ text: text,
+ overlapsRemote: overlapsRemote
+ ))
+ if !overlapsRemote {
+ cleanDurationByCluster[clusterID, default: 0] += max(0, end - start)
}
- continue
}
- } catch {
- DebugLogger.shared.warning(
- "Meeting microphone speech detection failed; preserving an unlabeled track transcript",
- source: "MeetingProcessingPipeline"
- )
+ return
}
- }
- if let fallback = try await self.transcribeWholeChunk(
- url,
- provider: context.provider,
- languageCode: context.languageCode,
- asrService: context.asrService,
- languagePin: context.languagePin
- ) {
- let duration = try await Task.detached(priority: .userInitiated) {
- try Self.audioDuration(url)
- }.value
- let speakerID = accumulator.speaker(
- key: "microphone-unknown",
- displayName: "Microphone / Unknown",
- trackKind: .microphone,
- isLocalUser: false,
- clusterID: nil
+ } catch {
+ if error is CancellationError { throw error }
+ if case MeetingProcessingError.audioUnreadable = error { throw error }
+ DebugLogger.shared.warning(
+ "Meeting microphone speech detection failed; preserving an unlabeled track transcript",
+ source: "MeetingProcessingPipeline"
)
- accumulator.segments.append(Self.segment(
- key: "microphone-fallback:\(chunk.id.uuidString)",
- trackID: track.id,
- speakerID: speakerID,
- start: chunkOffset,
- end: chunkOffset + duration,
- text: fallback,
- overlap: .ambiguous
- ))
}
}
+ if let fallback = try await self.transcribeWholeChunk(
+ url,
+ provider: context.provider,
+ languageCode: context.languageCode,
+ asrService: context.asrService,
+ languagePin: context.languagePin
+ ) {
+ let duration = chunkDuration
+ let speakerID = accumulator.speaker(
+ key: "microphone-unknown",
+ displayName: "Microphone / Unknown",
+ trackKind: .microphone,
+ isLocalUser: false,
+ clusterID: nil
+ )
+ accumulator.segments.append(Self.segment(
+ key: "microphone-fallback:\(chunk.id.uuidString)",
+ trackID: track.id,
+ speakerID: speakerID,
+ start: chunkOffset,
+ end: chunkOffset + duration,
+ text: fallback,
+ overlap: .ambiguous
+ ))
+ }
+ }
+ private func finishMicrophoneTrack(
+ _ track: MeetingAudioTrack,
+ session: MeetingSession,
+ stagedTurns: [StagedMicrophoneTurn],
+ cleanDurationByCluster: [SessionSpeakerID: TimeInterval],
+ accumulator: inout Accumulator
+ ) {
if session.mode == .inRoom {
for turn in stagedTurns {
let isNewSpeaker = !accumulator.speakers.contains { $0.id == turn.clusterID }
@@ -847,12 +1041,18 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
)
}
- private nonisolated static func readSamples(
+ /// Internal (not private) so tests can exercise unreadable-file classification directly.
+ nonisolated static func readSamples(
fileURL: URL,
startSeconds: TimeInterval,
endSeconds: TimeInterval?
) throws -> [Float] {
- let audioFile = try AVAudioFile(forReading: fileURL)
+ let audioFile: AVAudioFile
+ do {
+ audioFile = try AVAudioFile(forReading: fileURL)
+ } catch {
+ throw MeetingProcessingError.audioUnreadable
+ }
let sampleRate = audioFile.processingFormat.sampleRate
guard sampleRate > 0 else { throw MeetingProcessingError.audioUnreadable }
let fileDuration = Double(audioFile.length) / sampleRate
@@ -867,12 +1067,21 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
)
else { return [] }
audioFile.framePosition = startFrame
- try audioFile.read(into: buffer, frameCount: frameCount)
+ do {
+ try audioFile.read(into: buffer, frameCount: frameCount)
+ } catch {
+ throw MeetingProcessingError.audioUnreadable
+ }
return try AudioBufferConverter.monoSamples(from: buffer, targetSampleRate: 16_000)
}
private nonisolated static func audioDuration(_ url: URL) throws -> TimeInterval {
- let file = try AVAudioFile(forReading: url)
+ let file: AVAudioFile
+ do {
+ file = try AVAudioFile(forReading: url)
+ } catch {
+ throw MeetingProcessingError.audioUnreadable
+ }
guard file.processingFormat.sampleRate > 0 else { throw MeetingProcessingError.audioUnreadable }
return Double(file.length) / file.processingFormat.sampleRate
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
index 26c521e3..345dc0ea 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
@@ -85,8 +85,11 @@ final class MeetingSessionCoordinator: ObservableObject {
private var stopTask: Task<MeetingSession, Error>?
private var interruptionTask: Task<Void, Never>?
private var terminationTask: Task<Void, Never>?
+ private var retryTask: Task<MeetingSession, Error>?
private var persistenceTail: Task<Void, Never>?
+ private var persistenceGeneration = 0
private var restoreTask: Task<Void, Never>?
+ private var isDeleting = false
init(
store: any MeetingSessionStoring,
@@ -120,6 +123,25 @@ final class MeetingSessionCoordinator: ObservableObject {
return false
}
+ /// True when no capture/stop/interruption/termination/retry activity is in flight and the
+ /// session isn't mid-transition — safe for the UI to offer delete/retry/record-again actions.
+ var isQuiescent: Bool {
+ guard self.stopTask == nil,
+ self.interruptionTask == nil,
+ self.terminationTask == nil,
+ self.retryTask == nil,
+ !self.isRecording,
+ !self.isProcessing,
+ !self.isDeleting
+ else { return false }
+ switch self.state {
+ case .preparing, .stopping:
+ return false
+ default:
+ return true
+ }
+ }
+
var elapsedTime: TimeInterval {
guard let session = self.activeSession else { return 0 }
return max(0, (session.endedAt ?? Date()).timeIntervalSince(session.startedAt))
@@ -171,7 +193,8 @@ final class MeetingSessionCoordinator: ObservableObject {
guard self.activeSession == nil,
self.stopTask == nil,
self.interruptionTask == nil,
- self.terminationTask == nil
+ self.terminationTask == nil,
+ self.retryTask == nil
else {
throw MeetingCoordinatorError.recordingAlreadyActive
}
@@ -291,14 +314,90 @@ final class MeetingSessionCoordinator: ObservableObject {
@discardableResult
func 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,
+ guard let activeSession else { throw MeetingCoordinatorError.noRecoverableAudio }
+ return try await self.retryProcessing(sessionID: activeSession.id)
+ }
+
+ @discardableResult
+ func retryProcessing(sessionID: MeetingSessionID) async throws -> MeetingSession {
+ guard self.retryTask == nil else { throw MeetingCoordinatorError.activityInProgress }
+ let task = Task { @MainActor [weak self] () throws -> MeetingSession in
+ guard let self else { throw MeetingCoordinatorError.noActiveMeeting }
+ return try await self.performRetryProcessing(sessionID: sessionID)
+ }
+ self.retryTask = task
+ do {
+ let session = try await task.value
+ self.retryTask = nil
+ return session
+ } catch {
+ self.retryTask = nil
+ throw error
+ }
+ }
+
+ private func performRetryProcessing(sessionID: MeetingSessionID) async throws -> MeetingSession {
+ await self.ensureRestored()
+ guard self.stopTask == nil,
+ self.interruptionTask == nil,
+ self.terminationTask == nil,
+ !self.isProcessing,
+ !self.isRecording,
+ !self.isDeleting
+ else { throw MeetingCoordinatorError.activityInProgress }
+
+ if self.activeSession?.id == sessionID {
+ guard let session = self.activeSession, session.hasRetryableAudio else {
+ throw MeetingCoordinatorError.noRecoverableAudio
+ }
+ return try await self.beginProcessingRetry(session)
+ }
+
+ if let offer = self.activeSession {
+ guard offer.state == .interrupted || offer.state == .failed else {
+ throw MeetingCoordinatorError.activityInProgress
+ }
+ }
+
+ guard let session = try await self.store.load(id: sessionID) else {
+ throw MeetingCoordinatorError.noActiveMeeting
+ }
+ // Re-validate: another operation may have started while we awaited the load above.
+ guard self.stopTask == nil,
self.interruptionTask == nil,
self.terminationTask == nil,
- session.endedAt != nil,
- session.audioTracks.contains(where: { !$0.chunks.isEmpty })
- else { throw MeetingCoordinatorError.noRecoverableAudio }
+ !self.isProcessing,
+ !self.isRecording,
+ !self.isDeleting
+ else { throw MeetingCoordinatorError.activityInProgress }
+ guard session.hasRetryableAudio else { throw MeetingCoordinatorError.noRecoverableAudio }
+
+ // Acquire before displacing/adopting so a throw here never strands activeSession mid-transition.
+ if self.activityLease == nil {
+ self.activityLease = try self.audioArbiter.acquireMeetingCapture()
+ }
+
+ // Target is valid — only now displace the passive recovery offer it replaces.
+ if var offer = self.activeSession {
+ guard offer.state == .interrupted || offer.state == .failed else {
+ throw MeetingCoordinatorError.activityInProgress
+ }
+ offer.recoveryResolvedAt = Date()
+ offer.updatedAt = Date()
+ try? await self.store.save(offer)
+ guard self.terminationTask == nil else { throw MeetingCoordinatorError.activityInProgress }
+ self.activeSession = nil
+ self.trackHealth = [:]
+ self.state = .idle
+ }
+
+ self.activeSession = session
+ self.trackHealth = Dictionary(uniqueKeysWithValues: session.audioTracks.map { ($0.kind, $0.health) })
+ return try await self.beginProcessingRetry(session)
+ }
+
+ private func beginProcessingRetry(_ inputSession: MeetingSession) async throws -> MeetingSession {
+ var session = inputSession
if self.activityLease == nil {
self.activityLease = try self.audioArbiter.acquireMeetingCapture()
}
@@ -318,6 +417,98 @@ final class MeetingSessionCoordinator: ObservableObject {
return try await self.process(session, generation: generation)
}
+ func deleteSession(id: MeetingSessionID) async throws {
+ await self.ensureRestored()
+ guard self.isQuiescent else { throw MeetingCoordinatorError.activityInProgress }
+ self.isDeleting = true
+ defer { self.isDeleting = false }
+ await self.flushQueuedPersistence()
+ // Re-check: the flush await gives a racing operation a window to start.
+ guard self.stopTask == nil,
+ self.interruptionTask == nil,
+ self.terminationTask == nil,
+ self.retryTask == nil
+ else { throw MeetingCoordinatorError.activityInProgress }
+ try await self.store.delete(id: id)
+ if self.activeSession?.id == id {
+ self.activeSession = nil
+ self.trackHealth = [:]
+ self.state = .idle
+ }
+ if self.latestCompletedSession?.id == id {
+ self.latestCompletedSession = nil
+ if self.state == .completed(id) {
+ self.state = .idle
+ }
+ }
+ }
+
+ @discardableResult
+ func recordAgain(
+ from sourceID: MeetingSessionID,
+ configuration: MeetingCaptureConfiguration
+ ) async throws -> MeetingSession {
+ await self.ensureRestored()
+ guard self.stopTask == nil,
+ self.interruptionTask == nil,
+ self.terminationTask == nil,
+ self.retryTask == nil,
+ !self.isProcessing,
+ !self.isRecording,
+ !self.isDeleting
+ else { throw MeetingCoordinatorError.activityInProgress }
+ if let snapshot = self.activeSession, snapshot.id == sourceID {
+ guard snapshot.state == .interrupted || snapshot.state == .failed else {
+ throw MeetingCoordinatorError.activityInProgress
+ }
+ return try await self.recordAgainFromActiveOffer(snapshot, configuration: configuration)
+ }
+ return try await self.recordAgainFromHistory(sourceID: sourceID, configuration: configuration)
+ }
+
+ private func recordAgainFromActiveOffer(
+ _ snapshot: MeetingSession,
+ configuration: MeetingCaptureConfiguration
+ ) async throws -> MeetingSession {
+ self.activeSession = nil
+ self.trackHealth = [:]
+ self.state = .idle
+ do {
+ let newSession = try await self.startRecording(configuration: configuration)
+ var resolved = snapshot
+ resolved.recoveryResolvedAt = Date()
+ resolved.updatedAt = Date()
+ try? await self.store.save(resolved)
+ return newSession
+ } catch {
+ if self.activeSession == nil {
+ self.activeSession = snapshot
+ self.trackHealth = Dictionary(uniqueKeysWithValues: snapshot.audioTracks.map { ($0.kind, $0.health) })
+ self.state = snapshot.state == .interrupted
+ ? .interrupted(snapshot.id)
+ : .failed(snapshot.id, snapshot.failures.last ?? Self.failure(from: error, domain: .capture, recoverable: true))
+ }
+ throw error
+ }
+ }
+
+ private func recordAgainFromHistory(
+ sourceID: MeetingSessionID,
+ configuration: MeetingCaptureConfiguration
+ ) async throws -> MeetingSession {
+ let newSession = try await self.startRecording(configuration: configuration)
+ if var source = try? await self.store.load(id: sourceID) {
+ source.recoveryResolvedAt = Date()
+ source.updatedAt = Date()
+ do {
+ try await self.store.save(source)
+ } catch {
+ DebugLogger.shared.log("recordAgain: could not stamp recoveryResolvedAt for \(sourceID): \(error)")
+ }
+ }
+ return newSession
+ }
+
func renameSpeaker(id: SessionSpeakerID, to displayName: String) async throws {
guard var session = self.currentSession else { throw MeetingCoordinatorError.noActiveMeeting }
try session.renameSpeaker(id: id, to: displayName)
@@ -334,7 +525,9 @@ final class MeetingSessionCoordinator: ObservableObject {
!self.isProcessing,
self.stopTask == nil,
self.interruptionTask == nil,
- self.terminationTask == nil
+ self.terminationTask == nil,
+ self.retryTask == nil,
+ !self.isDeleting
else {
throw MeetingCoordinatorError.activityInProgress
}
@@ -470,6 +663,7 @@ final class MeetingSessionCoordinator: ObservableObject {
self.operationGeneration = nil
self.stopTask?.cancel()
self.interruptionTask?.cancel()
+ self.retryTask?.cancel()
guard var session = self.activeSession else {
await self.flushQueuedPersistence()
@@ -514,7 +708,18 @@ final class MeetingSessionCoordinator: ObservableObject {
}
session.updatedAt = Date()
await self.flushQueuedPersistence()
- try? await self.store.save(session)
+ do {
+ try await self.store.save(session)
+ } catch MeetingSessionStoreError.sessionDeleted {
+ // Deleted mid-shutdown: don't resurrect it as an interrupted offer.
+ self.activeSession = nil
+ self.trackHealth = [:]
+ self.state = .idle
+ self.releaseActivityLease()
+ return
+ } catch {
+ // Preserve today's behavior: reinstall as interrupted despite the save failure.
+ }
self.activeSession = session
self.state = .interrupted(session.id)
self.releaseActivityLease()
@@ -575,10 +780,28 @@ final class MeetingSessionCoordinator: ObservableObject {
} else {
session.processingAttempts.append(result.attempt)
}
+ if !result.skippedChunkIDs.isEmpty {
+ session.events.append(MeetingSessionEvent(
+ id: UUID(),
+ occurredAt: Date(),
+ kind: .writerFailure,
+ trackID: nil,
+ detail: "\(result.skippedChunkIDs.count) audio chunk(s) could not be read and were skipped."
+ ))
+ let skipped = Set(result.skippedChunkIDs)
+ for trackIndex in session.audioTracks.indices {
+ for chunkIndex in session.audioTracks[trackIndex].chunks.indices
+ where skipped.contains(session.audioTracks[trackIndex].chunks[chunkIndex].id)
+ {
+ session.audioTracks[trackIndex].chunks[chunkIndex].finalizationState = .failed
+ }
+ }
+ }
session.state = .completed
session.updatedAt = Date()
await self.flushQueuedPersistence()
try await self.store.save(session)
+ self.removeCheckpoint(sessionDirectory: sessionDirectory)
self.activeSession = nil
self.latestCompletedSession = session
self.state = .completed(session.id)
@@ -789,6 +1012,7 @@ final class MeetingSessionCoordinator: ObservableObject {
}
private func enqueuePersistence(_ session: MeetingSession) {
+ self.persistenceGeneration += 1
let previous = self.persistenceTail
let store = self.store
self.persistenceTail = Task {
@@ -798,8 +1022,14 @@ final class MeetingSessionCoordinator: ObservableObject {
}
private func flushQueuedPersistence() async {
- _ = await self.persistenceTail?.value
- self.persistenceTail = nil
+ while let tail = self.persistenceTail {
+ let generation = self.persistenceGeneration
+ _ = await tail.value
+ if self.persistenceGeneration == generation {
+ self.persistenceTail = nil
+ return
+ }
+ }
}
private func releaseActivityLease() {
@@ -808,6 +1038,21 @@ final class MeetingSessionCoordinator: ObservableObject {
self.activityLease = nil
}
+ /// Only called after the completed session save succeeds; on failure the checkpoint stays so a
+ /// retry can resume from it.
+ private func removeCheckpoint(sessionDirectory: URL) {
+ let url = sessionDirectory.appendingPathComponent("checkpoint.json", isDirectory: false)
+ guard FileManager.default.fileExists(atPath: url.path) else { return }
+ do {
+ try FileManager.default.removeItem(at: url)
+ } catch {
+ DebugLogger.shared.warning(
+ "Failed to remove meeting checkpoint after completion: \(error)",
+ source: "MeetingSessionCoordinator"
+ )
+ }
+ }
+
private static func makeTimebase() -> MeetingTimebaseMetadata {
var info = mach_timebase_info_data_t()
mach_timebase_info(&info)
diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift b/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift
index a1eb5e1c..895f9126 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift
@@ -7,6 +7,8 @@ nonisolated protocol MeetingSessionStoring: Sendable {
func loadAll() async throws -> [MeetingSession]
func loadRecoverable() async throws -> [MeetingSession]
func sessionDirectory(for id: MeetingSessionID) async throws -> URL
+ func existingSessionDirectory(for id: MeetingSessionID) async throws -> URL?
+ func delete(id: MeetingSessionID) async throws
}
private final nonisolated class MeetingSessionFileSystem: @unchecked Sendable {
@@ -32,6 +34,7 @@ actor MeetingSessionStore: MeetingSessionStoring {
private let rootDirectory: URL
private let encoder: JSONEncoder
private let decoder: JSONDecoder
+ private var tombstonedIDs: Set<MeetingSessionID> = []
init(rootDirectory: URL? = nil, fileManager: FileManager = .default) {
self.fileSystem = MeetingSessionFileSystem(manager: fileManager)
@@ -59,6 +62,9 @@ actor MeetingSessionStore: MeetingSessionStoring {
}
func create(_ session: MeetingSession) throws {
+ guard !self.tombstonedIDs.contains(session.id) else {
+ throw MeetingSessionStoreError.sessionDeleted
+ }
try session.validateForPersistence()
try self.prepareRootDirectory()
let directory = self.sessionDirectoryURL(for: session.id)
@@ -72,6 +78,9 @@ actor MeetingSessionStore: MeetingSessionStoring {
}
func save(_ session: MeetingSession) throws {
+ guard !self.tombstonedIDs.contains(session.id) else {
+ throw MeetingSessionStoreError.sessionDeleted
+ }
try session.validateForPersistence()
try self.prepareRootDirectory()
let directory = self.sessionDirectoryURL(for: session.id)
@@ -84,6 +93,7 @@ actor MeetingSessionStore: MeetingSessionStoring {
}
func load(id: MeetingSessionID) throws -> MeetingSession? {
+ guard !self.tombstonedIDs.contains(id) else { return nil }
let url = self.sessionManifestURL(for: id)
guard self.fileSystem.manager.fileExists(atPath: url.path) else { return nil }
let session = try self.decodeSession(at: url)
@@ -138,6 +148,9 @@ actor MeetingSessionStore: MeetingSessionStoring {
}
func sessionDirectory(for id: MeetingSessionID) throws -> URL {
+ guard !self.tombstonedIDs.contains(id) else {
+ throw MeetingSessionStoreError.sessionDeleted
+ }
try self.prepareRootDirectory()
let directory = self.sessionDirectoryURL(for: id)
if !self.fileSystem.manager.fileExists(atPath: directory.path) {
@@ -147,6 +160,20 @@ actor MeetingSessionStore: MeetingSessionStoring {
return directory
}
+ func existingSessionDirectory(for id: MeetingSessionID) throws -> URL? {
+ let directory = self.sessionDirectoryURL(for: id)
+ return self.fileSystem.manager.fileExists(atPath: directory.path) ? directory : nil
+ }
+
+ func delete(id: MeetingSessionID) throws {
+ self.tombstonedIDs.insert(id)
+ let directory = self.sessionDirectoryURL(for: id)
+ if self.fileSystem.manager.fileExists(atPath: directory.path) {
+ try self.fileSystem.manager.removeItem(at: directory)
+ }
+ try self.removeFromIndex(id)
+ }
+
private func writeSession(_ session: MeetingSession) throws {
let data = try self.encoder.encode(session)
try self.atomicPrivateWrite(data, to: self.sessionManifestURL(for: session.id))
@@ -281,6 +308,21 @@ actor MeetingSessionStore: MeetingSessionStoring {
)
}
+ private func removeFromIndex(_ id: MeetingSessionID) throws {
+ var index = (try? self.readIndex()) ?? SessionIndex(
+ schemaVersion: SessionIndex.currentSchemaVersion,
+ sessionIDs: [],
+ updatedAt: Date()
+ )
+ index.sessionIDs.removeAll { $0 == id }
+ index.updatedAt = Date()
+ let data = try self.encoder.encode(index)
+ try self.atomicPrivateWrite(
+ data,
+ to: self.rootDirectory.appendingPathComponent("index.json", isDirectory: false)
+ )
+ }
+
private func discoverSessionIDs() throws -> [MeetingSessionID] {
let urls = try self.fileSystem.manager.contentsOfDirectory(
at: self.rootDirectory,
@@ -308,6 +350,7 @@ actor MeetingSessionStore: MeetingSessionStoring {
enum MeetingSessionStoreError: LocalizedError {
case sessionAlreadyExists
case unsupportedSchema(Int)
+ case sessionDeleted
var errorDescription: String? {
switch self {
@@ -315,6 +358,8 @@ enum MeetingSessionStoreError: LocalizedError {
return "A meeting session with this identifier already exists."
case let .unsupportedSchema(version):
return "This meeting was created with unsupported schema version \(version)."
+ case .sessionDeleted:
+ return "This meeting has been deleted."
}
}
}
diff --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swift
index 0896335c..7ad7a008 100644
--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift
+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift
@@ -104,6 +104,7 @@ struct MeetingTranscriptionView: View {
@State private var meetingHistory: [MeetingSession] = []
@State private var selectedHistorySessionID: MeetingSessionID?
@State private var meetingHistoryError: String?
+ @State private var pendingDeleteSessionID: MeetingSessionID?
@AppStorage("MeetingHistoryInspectorVisible") private var isMeetingHistoryVisible = true
init(
@@ -152,8 +153,9 @@ struct MeetingTranscriptionView: View {
onRefreshSources: self.refreshSourcesFromUserAction,
onStart: self.startRecording,
onStop: self.stopAndTranscribe,
- onRetry: self.retryProcessing,
+ onRetrySession: { self.retryProcessingSession(id: $0.id) },
onRevealAudio: self.revealCapturedAudio,
+ onRecordAgain: self.recordAgain,
onCopyTranscript: self.copyTranscript,
onOpenMeetingSettings: self.openMeetingSettings,
isRetrying: self.isRetrying
@@ -165,7 +167,12 @@ struct MeetingTranscriptionView: View {
sessions: self.meetingHistory,
selectedSessionID: self.$selectedHistorySessionID,
errorMessage: self.meetingHistoryError,
- onRefresh: { Task { await self.loadMeetingHistory() } }
+ isQuiescent: self.coordinator.isQuiescent,
+ onRefresh: { Task { await self.loadMeetingHistory() } },
+ onRetry: { self.retryProcessingSession(id: $0) },
+ onRevealAudio: self.revealCapturedAudio,
+ onExportAudio: self.exportAudio,
+ onDeleteRequest: { self.pendingDeleteSessionID = $0 }
)
.frame(width: 290)
.transition(.move(edge: .trailing).combined(with: .opacity))
@@ -218,11 +225,36 @@ struct MeetingTranscriptionView: View {
)
.interactiveDismissDisabled(!SettingsStore.shared.meetingRecordingDefaults.isConfigured)
}
+ .alert(
+ "Delete Meeting?",
+ isPresented: Binding(
+ get: { self.pendingDeleteSessionID != nil },
+ set: { if !$0 { self.pendingDeleteSessionID = nil } }
+ )
+ ) {
+ Button("Cancel", role: .cancel) { self.pendingDeleteSessionID = nil }
+ Button("Delete", role: .destructive) {
+ if let id = self.pendingDeleteSessionID { self.deleteSession(id: id) }
+ }
+ } message: {
+ Text("The recording and transcript will be permanently deleted from this Mac.")
+ }
}
private var canvasState: MeetingTranscriptionCanvasState {
if let selectedHistorySession, self.canBrowseMeetingHistory {
- return .result(selectedHistorySession)
+ switch selectedHistorySession.state {
+ case .failed:
+ let message = selectedHistorySession.failures.last?.message ?? "This meeting failed."
+ return .failed(session: selectedHistorySession, message: message)
+ case .interrupted:
+ let message = selectedHistorySession.endedAt != nil && !selectedHistorySession.processingAttempts.isEmpty
+ ? "Transcription was interrupted. Captured audio is ready to retry."
+ : "Recording was interrupted. Captured audio has been preserved on this Mac."
+ return .failed(session: selectedHistorySession, message: message)
+ default:
+ return .result(selectedHistorySession)
+ }
}
switch self.coordinator.state {
@@ -505,24 +537,98 @@ struct MeetingTranscriptionView: View {
}
}
- private func retryProcessing() {
+ private func retryProcessingSession(id: MeetingSessionID) {
guard !self.isRetrying else { return }
self.isRetrying = true
self.actionErrorMessage = nil
+ self.selectedHistorySessionID = nil
Task {
defer { self.isRetrying = false }
do {
- _ = try await self.coordinator.retryProcessing()
+ _ = try await self.coordinator.retryProcessing(sessionID: id)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func deleteSession(id: MeetingSessionID) {
+ self.pendingDeleteSessionID = nil
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ try await self.coordinator.deleteSession(id: id)
+ if self.selectedHistorySessionID == id { self.selectedHistorySessionID = nil }
} catch {
self.actionErrorMessage = error.localizedDescription
}
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func recordAgain(_ session: MeetingSession) {
+ guard let configuration = self.recordAgainConfiguration(from: session) else { return }
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.recordAgain(from: session.id, configuration: configuration)
+ self.selectedHistorySessionID = nil
+ self.setupDraft.title = MeetingTranscriptionSetupDraft.defaultTitle()
+ await self.loadMeetingHistory()
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ }
+ }
+
+ private func recordAgainConfiguration(from session: MeetingSession) -> MeetingCaptureConfiguration? {
+ guard let microphone = self.resolvedMicrophone(for: session) else {
+ self.actionErrorMessage = "microphone unavailable"
+ return nil
+ }
+ var application: MeetingApplicationIdentity?
+ if session.mode == .onlineCall {
+ guard let bundleIdentifier = session.capturedApplication?.bundleIdentifier,
+ let resolved = self.applications.first(where: { $0.identity.bundleIdentifier == bundleIdentifier })
+ else {
+ self.actionErrorMessage = "app not running"
+ return nil
+ }
+ application = resolved.identity
+ }
+ return MeetingCaptureConfiguration(
+ mode: session.mode,
+ title: session.title,
+ platform: session.platform,
+ application: application,
+ microphone: microphone
+ )
+ }
+
+ private func resolvedMicrophone(for session: MeetingSession) -> MeetingMicrophoneIdentity? {
+ if let coreAudioUID = session.selectedMicrophone.coreAudioUID,
+ let match = self.microphones.first(where: { $0.identity.coreAudioUID == coreAudioUID })
+ {
+ var identity = match.identity
+ identity.role = session.selectedMicrophone.role
+ return identity
+ }
+ guard let match = self.microphones.first(where: { $0.identity.captureDeviceID == session.selectedMicrophone.captureDeviceID }) else {
+ return nil
}
+ var identity = match.identity
+ identity.role = session.selectedMicrophone.role
+ return identity
}
private func revealCapturedAudio(_ session: MeetingSession) {
Task {
do {
- let directory = try await MeetingSessionStore.shared.sessionDirectory(for: session.id)
+ guard let directory = try await MeetingSessionStore.shared.existingSessionDirectory(for: session.id) else {
+ self.actionErrorMessage = "Captured audio could not be revealed: recording no longer on disk."
+ return
+ }
let firstAudioURL = session.audioTracks
.flatMap(\.chunks)
.first(where: { $0.finalizationState == .finalized })?
@@ -534,6 +640,80 @@ struct MeetingTranscriptionView: View {
}
}
+ private func exportAudio(_ session: MeetingSession) {
+ let panel = NSOpenPanel()
+ panel.canChooseDirectories = true
+ panel.canChooseFiles = false
+ panel.canCreateDirectories = true
+ panel.prompt = "Choose"
+ guard panel.runModal() == .OK, let destinationFolder = panel.url else { return }
+
+ Task {
+ do {
+ guard let sourceDirectory = try await MeetingSessionStore.shared.existingSessionDirectory(for: session.id) else {
+ self.actionErrorMessage = "Export failed: recording no longer on disk."
+ return
+ }
+ try Self.stageExport(of: session, from: sourceDirectory, into: destinationFolder)
+ } catch {
+ self.actionErrorMessage = "Export failed: \(error.localizedDescription)"
+ }
+ }
+ }
+
+ private static func stageExport(
+ of session: MeetingSession,
+ from sourceDirectory: URL,
+ into destinationFolder: URL
+ ) throws {
+ let fileManager = FileManager.default
+ let baseName = Self.sanitizedExportName(session.title)
+ let name = Self.uniqueExportName(baseName, in: destinationFolder, fileManager: fileManager)
+ let stagingDirectory = destinationFolder.appendingPathComponent(".\(name).\(UUID().uuidString).export-tmp", isDirectory: true)
+ try fileManager.createDirectory(at: stagingDirectory, withIntermediateDirectories: true)
+
+ do {
+ for track in session.audioTracks {
+ for chunk in track.chunks where chunk.finalizationState == .finalized && chunk.byteCount > 0 {
+ let sourceURL = chunk.fileURL(relativeTo: sourceDirectory)
+ let ext = sourceURL.pathExtension.isEmpty ? "m4a" : sourceURL.pathExtension
+ let fileName = "\(track.kind.rawValue)-\(String(format: "%03d", chunk.sequence)).\(ext)"
+ try fileManager.copyItem(
+ at: sourceURL,
+ to: stagingDirectory.appendingPathComponent(fileName, isDirectory: false)
+ )
+ }
+ }
+ var destinationName = name
+ do {
+ try fileManager.moveItem(at: stagingDirectory, to: destinationFolder.appendingPathComponent(destinationName, isDirectory: true))
+ } catch CocoaError.fileWriteFileExists {
+ // Destination appeared between the uniqueness check and the move; retry once with a fresh name.
+ destinationName = Self.uniqueExportName(baseName, in: destinationFolder, fileManager: fileManager)
+ try fileManager.moveItem(at: stagingDirectory, to: destinationFolder.appendingPathComponent(destinationName, isDirectory: true))
+ }
+ } catch {
+ try? fileManager.removeItem(at: stagingDirectory)
+ throw error
+ }
+ }
+
+ private static func sanitizedExportName(_ title: String) -> String {
+ let allowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 _.-")
+ let sanitized = String(title.unicodeScalars.map { allowed.contains($0) ? Character($0) : "-" }.prefix(80))
+ return sanitized.isEmpty ? "Meeting" : sanitized
+ }
+
+ private static func uniqueExportName(_ baseName: String, in folder: URL, fileManager: FileManager) -> String {
+ var candidate = baseName
+ var suffix = 2
+ while fileManager.fileExists(atPath: folder.appendingPathComponent(candidate).path) {
+ candidate = "\(baseName) \(suffix)"
+ suffix += 1
+ }
+ return candidate
+ }
+
private func startNewMeeting() {
do {
try self.coordinator.resetForNewMeeting()
@@ -689,8 +869,9 @@ struct MeetingTranscriptionCanvas: View {
let onRefreshSources: () -> Void
let onStart: () -> Void
let onStop: () -> Void
- let onRetry: () -> Void
+ let onRetrySession: (MeetingSession) -> Void
let onRevealAudio: (MeetingSession) -> Void
+ let onRecordAgain: (MeetingSession) -> Void
let onCopyTranscript: (MeetingSession) -> Void
let onOpenMeetingSettings: () -> Void
let isRetrying: Bool
@@ -740,8 +921,9 @@ struct MeetingTranscriptionCanvas: View {
session: session,
message: self.errorMessage ?? message,
isRetrying: self.isRetrying,
- onRetry: self.onRetry,
- onRevealAudio: self.onRevealAudio
+ onRetrySession: self.onRetrySession,
+ onRevealAudio: self.onRevealAudio,
+ onRecordAgain: self.onRecordAgain
)
}
}
@@ -863,7 +1045,12 @@ private struct MeetingHistoryInspector: View {
let sessions: [MeetingSession]
@Binding var selectedSessionID: MeetingSessionID?
let errorMessage: String?
+ let isQuiescent: Bool
let onRefresh: () -> Void
+ let onRetry: (MeetingSessionID) -> Void
+ let onRevealAudio: (MeetingSession) -> Void
+ let onExportAudio: (MeetingSession) -> Void
+ let onDeleteRequest: (MeetingSessionID) -> Void
@Environment(\.theme) private var theme
@State private var searchText = ""
@@ -924,6 +1111,26 @@ private struct MeetingHistoryInspector: View {
ForEach(self.filteredSessions) { session in
MeetingHistoryRow(session: session)
.tag(session.id)
+ .contextMenu {
+ if session.hasRetryableAudio, session.state == .failed || session.state == .interrupted {
+ Button("Retry Transcription", systemImage: "arrow.clockwise") {
+ self.onRetry(session.id)
+ }
+ .disabled(!self.isQuiescent)
+ }
+ Button("Reveal Audio", systemImage: "folder") {
+ self.onRevealAudio(session)
+ }
+ Button("Export Audio…", systemImage: "square.and.arrow.up") {
+ self.onExportAudio(session)
+ }
+ .disabled(!Self.hasFinalizedAudio(session))
+ Divider()
+ Button("Delete Meeting…", systemImage: "trash", role: .destructive) {
+ self.onDeleteRequest(session.id)
+ }
+ .disabled(!self.isQuiescent)
+ }
}
}
.listStyle(.sidebar)
@@ -932,6 +1139,10 @@ private struct MeetingHistoryInspector: View {
}
.background(self.theme.palette.sidebarBackground)
}
+
+ private static func hasFinalizedAudio(_ session: MeetingSession) -> Bool {
+ session.audioTracks.flatMap(\.chunks).contains { $0.finalizationState == .finalized && $0.byteCount > 0 }
+ }
}
private struct MeetingHistoryRow: View {
@@ -1797,16 +2008,14 @@ private struct MeetingFailureCanvas: View {
let session: MeetingSession?
let message: String
let isRetrying: Bool
- let onRetry: () -> Void
+ let onRetrySession: (MeetingSession) -> Void
let onRevealAudio: (MeetingSession) -> Void
+ let onRecordAgain: (MeetingSession) -> Void
@Environment(\.theme) private var theme
private var hasRecoverableAudio: Bool {
- guard let session, session.endedAt != nil else { return false }
- return session.audioTracks
- .flatMap(\.chunks)
- .contains(where: { $0.finalizationState == .finalized && $0.byteCount > 0 })
+ self.session?.hasRetryableAudio == true
}
private var title: String {
@@ -1846,7 +2055,7 @@ private struct MeetingFailureCanvas: View {
if let session, self.hasRecoverableAudio {
Button("Reveal Audio", systemImage: "folder", action: { self.onRevealAudio(session) })
.fluidButton(.compact, size: .medium)
- Button(action: self.onRetry) {
+ Button(action: { self.onRetrySession(session) }) {
if self.isRetrying {
HStack(spacing: self.theme.metrics.spacing.sm) {
ProgressView().controlSize(.small)
@@ -1859,6 +2068,12 @@ private struct MeetingFailureCanvas: View {
.fluidButton(.accent, size: .medium)
.disabled(self.isRetrying)
}
+ if let session {
+ Button("Record Again", systemImage: "arrow.counterclockwise.circle") {
+ self.onRecordAgain(session)
+ }
+ .fluidButton(.compact, size: .medium)
+ }
}
}
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
index 295c877f..d4702eec 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
@@ -440,6 +440,702 @@ final class MeetingRecoveryTests: XCTestCase {
return XCTFail("Expected .failed after sessionDirectory throw, got \(coordinator.state)")
}
}
+
+ // MARK: - Test 9: store delete removes directory + index, idempotent, resurrection-proof
+
+ func testStoreDeleteRemovesSessionIdempotently() 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 sessionDirectory = try await store.sessionDirectory(for: session.id)
+ XCTAssertTrue(FileManager.default.fileExists(atPath: sessionDirectory.path))
+
+ try await store.delete(id: session.id)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: sessionDirectory.path))
+
+ try await store.delete(id: session.id) // idempotent
+
+ do {
+ try await store.save(session)
+ XCTFail("Expected save after delete to throw")
+ } catch {}
+
+ do {
+ _ = try await store.sessionDirectory(for: session.id)
+ XCTFail("Expected sessionDirectory after delete to throw")
+ } catch {}
+
+ let all = try await store.loadAll()
+ XCTAssertFalse(all.contains(where: { $0.id == session.id }))
+ }
+
+ // MARK: - Test 10: retry-by-id on a non-active history session
+
+ func testRetryByIDOnNonActiveHistorySessionCompletes() 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 coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ XCTAssertEqual(coordinator.activeSession?.id, session.id)
+ try coordinator.resetForNewMeeting()
+
+ for _ in 0..<40 {
+ if let persisted = try await store.load(id: session.id), persisted.recoveryResolvedAt != nil { break }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ XCTAssertNil(coordinator.activeSession)
+
+ let result = try await coordinator.retryProcessing(sessionID: session.id)
+ XCTAssertEqual(result.state, .completed)
+ XCTAssertEqual(coordinator.latestCompletedSession?.id, session.id)
+ XCTAssertEqual(coordinator.state, .completed(session.id))
+ XCTAssertNil(coordinator.activeSession)
+ }
+
+ // MARK: - Test 11: retry-by-id displaces a passive recovery offer
+
+ func testRetryByIDDisplacesPassiveOffer() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+
+ let now = Date()
+ let older = self.makeSession(
+ state: .interrupted,
+ startedAt: now.addingTimeInterval(-600),
+ endedAt: now.addingTimeInterval(-590),
+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
+ )
+ let newer = self.makeSession(
+ state: .interrupted,
+ startedAt: now.addingTimeInterval(-60),
+ endedAt: now.addingTimeInterval(-50),
+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
+ )
+ try await store.create(older)
+ try await store.create(newer)
+
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ XCTAssertEqual(coordinator.activeSession?.id, newer.id)
+
+ let result = try await coordinator.retryProcessing(sessionID: older.id)
+ XCTAssertEqual(result.id, older.id)
+ XCTAssertEqual(result.state, .completed)
+ XCTAssertEqual(coordinator.latestCompletedSession?.id, older.id)
+
+ let persistedOffer = try await store.load(id: newer.id)
+ XCTAssertNotNil(persistedOffer?.recoveryResolvedAt)
+ }
+
+ // MARK: - Test 12: retry-by-id refused while recording, and while another retry is in-flight
+
+ func testRetryByIDRefusedWhileRecordingAndWhileRetryInFlight() async throws {
+ let recordingDir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: recordingDir) }
+ let recordingStore = MeetingSessionStore(rootDirectory: recordingDir)
+ let capture = StubCaptureController()
+ capture.startResult = MeetingCaptureStartResult(tracks: [self.makeMicrophoneTrack(chunks: [])], firstPresentationTime: nil)
+ let recordingCoordinator = MeetingSessionCoordinator(
+ store: recordingStore,
+ capture: capture,
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ let recordingSession = try await recordingCoordinator.startRecording(configuration: self.makeConfiguration())
+ do {
+ _ = try await recordingCoordinator.retryProcessing(sessionID: recordingSession.id)
+ XCTFail("Expected retryProcessing to throw while recording")
+ } catch let error as MeetingCoordinatorError {
+ guard case .activityInProgress = error else {
+ return XCTFail("Expected .activityInProgress, got \(error)")
+ }
+ }
+
+ let retryDir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: retryDir) }
+ let retryStore = MeetingSessionStore(rootDirectory: retryDir)
+ let session = self.makeSession(
+ state: .interrupted,
+ endedAt: Date(),
+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
+ )
+ try await retryStore.create(session)
+ let gatedProcessing = GatedProcessingController()
+ let retryCoordinator = MeetingSessionCoordinator(
+ store: retryStore,
+ capture: StubCaptureController(),
+ processing: gatedProcessing,
+ audioArbiter: StubArbiter()
+ )
+ await retryCoordinator.ensureRestored()
+ let retryTask = Task { try await retryCoordinator.retryProcessing(sessionID: session.id) }
+
+ for _ in 0..<40 {
+ if case .processing = retryCoordinator.state { break }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ guard case .processing = retryCoordinator.state else {
+ return XCTFail("First retry did not reach .processing")
+ }
+
+ do {
+ _ = try await retryCoordinator.retryProcessing(sessionID: session.id)
+ XCTFail("Expected second retryProcessing to throw while first is in-flight")
+ } catch let error as MeetingCoordinatorError {
+ guard case .activityInProgress = error else {
+ return XCTFail("Expected .activityInProgress, got \(error)")
+ }
+ }
+
+ gatedProcessing.openGate()
+ let finalSession = try await retryTask.value
+ XCTAssertEqual(finalSession.state, .completed)
+ }
+
+ // MARK: - Test 13: deleteSession on the active recovery offer
+
+ func testDeleteSessionOnActiveRecoveryOffer() 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 coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ XCTAssertEqual(coordinator.activeSession?.id, session.id)
+
+ let sessionDirectory = try await store.sessionDirectory(for: session.id)
+ try await coordinator.deleteSession(id: session.id)
+
+ XCTAssertNil(coordinator.activeSession)
+ XCTAssertEqual(coordinator.state, .idle)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: sessionDirectory.path))
+ }
+
+ // MARK: - Test 14: deleteSession refused mid-processing
+
+ func testDeleteSessionRefusedMidProcessing() 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 gatedProcessing = GatedProcessingController()
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: gatedProcessing,
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ 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 {
+ return XCTFail("retryProcessing did not reach .processing")
+ }
+
+ do {
+ try await coordinator.deleteSession(id: session.id)
+ XCTFail("Expected deleteSession to throw while processing")
+ } catch let error as MeetingCoordinatorError {
+ guard case .activityInProgress = error else {
+ return XCTFail("Expected .activityInProgress, got \(error)")
+ }
+ }
+
+ gatedProcessing.openGate()
+ _ = try await retryTask.value
+ }
+
+ // MARK: - Test 15: delete-resurrection guard
+
+ func testStoreDeleteResurrectionGuard() 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)
+
+ try await store.delete(id: session.id)
+
+ do {
+ try await store.save(session)
+ XCTFail("Expected save after delete to throw")
+ } catch {}
+
+ let sessionDirectory = try await store.existingSessionDirectory(for: session.id)
+ XCTAssertNil(sessionDirectory)
+ }
+
+ // MARK: - Test 16: recordAgain from a passive offer
+
+ func testRecordAgainFromPassiveOfferSucceeds() 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 capture = StubCaptureController()
+ capture.startResult = MeetingCaptureStartResult(tracks: [self.makeMicrophoneTrack(chunks: [])], firstPresentationTime: nil)
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: capture,
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ XCTAssertEqual(coordinator.activeSession?.id, session.id)
+
+ let newSession = try await coordinator.recordAgain(
+ from: session.id,
+ configuration: self.makeConfiguration(title: "Again")
+ )
+ XCTAssertNotEqual(newSession.id, session.id)
+ XCTAssertEqual(coordinator.activeSession?.id, newSession.id)
+ guard case .recording = coordinator.state else {
+ return XCTFail("Expected .recording after recordAgain, got \(coordinator.state)")
+ }
+
+ var persistedOld: MeetingSession?
+ for _ in 0..<40 {
+ persistedOld = try await store.load(id: session.id)
+ if persistedOld?.recoveryResolvedAt != nil { break }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ XCTAssertNotNil(persistedOld?.recoveryResolvedAt)
+ }
+
+ func testRecordAgainFromPassiveOfferRestoresOnCaptureFailure() 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 capture = StubCaptureController()
+ capture.startError = MeetingCaptureError.applicationNotSelected
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: capture,
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ XCTAssertEqual(coordinator.activeSession?.id, session.id)
+
+ do {
+ _ = try await coordinator.recordAgain(from: session.id, configuration: self.makeConfiguration(title: "Again"))
+ XCTFail("Expected recordAgain to throw when capture start fails")
+ } catch {}
+
+ XCTAssertEqual(coordinator.activeSession?.id, session.id)
+ XCTAssertEqual(coordinator.activeSession?.state, .interrupted)
+ XCTAssertEqual(coordinator.state, .interrupted(session.id))
+
+ let persistedOld = try await store.load(id: session.id)
+ XCTAssertNil(persistedOld?.recoveryResolvedAt)
+ }
+
+ // MARK: - Slice 3: checkpoint fixtures
+
+ private func makeCheckpoint(
+ sessionID: MeetingSessionID = UUID(),
+ completedTrackID: MeetingAudioTrackID = UUID(),
+ trackFingerprints: [MeetingAudioTrackID: [MeetingProcessingCheckpoint.ChunkFingerprint]] = [:]
+ ) -> MeetingProcessingCheckpoint {
+ MeetingProcessingCheckpoint(
+ version: MeetingProcessingCheckpoint.currentVersion,
+ sessionID: sessionID,
+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,
+ asrProvider: "apple",
+ asrModel: "base",
+ languageCode: "en",
+ completedTrackID: completedTrackID,
+ trackFingerprints: trackFingerprints,
+ speakers: [],
+ segments: [],
+ remoteSpeech: [MeetingProcessingCheckpoint.SpeechInterval(start: 0, end: 1.5)],
+ speakerIDByKey: ["remote-cluster:x": UUID()],
+ nextRemoteSpeaker: 2,
+ nextMicrophoneSpeaker: 1
+ )
+ }
+
+ // MARK: - Slice 3, test 1: checkpoint round-trip
+
+ func testCheckpointRoundTripEncodesAndDecodesEqual() throws {
+ let checkpoint = self.makeCheckpoint(trackFingerprints: [
+ UUID(): [MeetingProcessingCheckpoint.ChunkFingerprint(id: UUID(), byteCount: 100, sha256: "abc")],
+ ])
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ let data = try encoder.encode(checkpoint)
+ let decoded = try decoder.decode(MeetingProcessingCheckpoint.self, from: data)
+ XCTAssertEqual(decoded, checkpoint)
+ }
+
+ // MARK: - Slice 3, test 2: checkpoint validity matrix
+
+ func testCheckpointValidityMatrix() throws {
+ let session = self.makeSession(state: .interrupted, endedAt: Date())
+ let trackID = UUID()
+ let fingerprint = MeetingProcessingCheckpoint.ChunkFingerprint(id: UUID(), byteCount: 128, sha256: "abc123")
+ let fingerprints: [MeetingAudioTrackID: [MeetingProcessingCheckpoint.ChunkFingerprint]] = [trackID: [fingerprint]]
+ let checkpoint = self.makeCheckpoint(sessionID: session.id, completedTrackID: trackID, trackFingerprints: fingerprints)
+
+ func isValid(
+ pipelineVersion: Int = MeetingProcessingPipeline.pipelineVersion,
+ provider: String = "apple",
+ model: String = "base",
+ language: String = "en",
+ completedTrackID: MeetingAudioTrackID = trackID,
+ expectedFingerprints: [MeetingAudioTrackID: [MeetingProcessingCheckpoint.ChunkFingerprint]] = fingerprints,
+ session: MeetingSession = session
+ ) -> Bool {
+ checkpoint.isValid(
+ session: session,
+ pipelineVersion: pipelineVersion,
+ provider: provider,
+ model: model,
+ language: language,
+ completedTrackID: completedTrackID,
+ expectedFingerprints: expectedFingerprints
+ )
+ }
+
+ XCTAssertTrue(isValid())
+ XCTAssertFalse(isValid(pipelineVersion: MeetingProcessingPipeline.pipelineVersion + 1))
+ XCTAssertFalse(isValid(provider: "other"))
+ XCTAssertFalse(isValid(model: "other"))
+ XCTAssertFalse(isValid(language: "fr"))
+ XCTAssertFalse(isValid(completedTrackID: UUID()))
+ var otherSession = session
+ otherSession.id = UUID()
+ XCTAssertFalse(isValid(session: otherSession))
+
+ var mutatedByteCount = fingerprints
+ mutatedByteCount[trackID]?[0].byteCount = 999
+ XCTAssertFalse(isValid(expectedFingerprints: mutatedByteCount))
+
+ var mutatedSha = fingerprints
+ mutatedSha[trackID]?[0].sha256 = "different"
+ XCTAssertFalse(isValid(expectedFingerprints: mutatedSha))
+
+ var extraChunk = fingerprints
+ extraChunk[trackID]?.append(MeetingProcessingCheckpoint.ChunkFingerprint(id: UUID(), byteCount: 1, sha256: "x"))
+ XCTAssertFalse(isValid(expectedFingerprints: extraChunk))
+
+ XCTAssertFalse(isValid(expectedFingerprints: [trackID: []]))
+
+ var versionMismatch = checkpoint
+ versionMismatch.version = MeetingProcessingCheckpoint.currentVersion + 1
+ XCTAssertFalse(versionMismatch.isValid(
+ session: session,
+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,
+ provider: "apple",
+ model: "base",
+ language: "en",
+ completedTrackID: trackID,
+ expectedFingerprints: fingerprints
+ ))
+ }
+
+ // MARK: - Slice 3, test 3: coordinator deletes checkpoint after success
+
+ func testCoordinatorDeletesCheckpointAfterProcessingSuccess() 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 sessionDirectory = try await store.sessionDirectory(for: session.id)
+ let checkpointURL = sessionDirectory.appendingPathComponent("checkpoint.json", isDirectory: false)
+ try Data("{}".utf8).write(to: checkpointURL)
+ XCTAssertTrue(FileManager.default.fileExists(atPath: checkpointURL.path))
+
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ let result = try await coordinator.retryProcessing()
+
+ XCTAssertEqual(result.state, .completed)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: checkpointURL.path))
+ }
+
+ // MARK: - Slice 3, test 4: checkpoint survives a failed retry
+
+ func testCheckpointSurvivesProcessingFailure() 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 sessionDirectory = try await store.sessionDirectory(for: session.id)
+ let checkpointURL = sessionDirectory.appendingPathComponent("checkpoint.json", isDirectory: false)
+ try Data("{}".utf8).write(to: checkpointURL)
+
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: ThrowingProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ do {
+ _ = try await coordinator.retryProcessing()
+ XCTFail("Expected retryProcessing to throw")
+ } catch {}
+
+ XCTAssertTrue(FileManager.default.fileExists(atPath: checkpointURL.path))
+ }
+
+ // MARK: - Slice 3, test 5: skipped-chunk event and chunk failure marking
+
+ func testSkippedChunksProduceEventAndMarkChunksFailed() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let chunk = self.makeFinalizedChunk(sequence: 0, path: "tracks/microphone/chunk_0.caf")
+ // A second finalized chunk keeps the skip count below the total, so the
+ // success+skip combination this test asserts is actually realizable.
+ let survivingChunk = self.makeFinalizedChunk(sequence: 1, path: "tracks/microphone/chunk_1.caf")
+ let session = self.makeSession(
+ state: .interrupted,
+ endedAt: Date(),
+ audioTracks: [self.makeMicrophoneTrack(chunks: [chunk, survivingChunk])]
+ )
+ try await store.create(session)
+
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: SkippedChunkProcessingController(skippedChunkIDs: [chunk.id]),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ let result = try await coordinator.retryProcessing()
+
+ XCTAssertEqual(result.state, .completed)
+ XCTAssertTrue(result.events.contains {
+ $0.detail == "1 audio chunk(s) could not be read and were skipped."
+ })
+ let persistedChunk = result.audioTracks.first?.chunks.first(where: { $0.id == chunk.id })
+ XCTAssertEqual(persistedChunk?.finalizationState, .failed)
+ let persistedSurvivor = result.audioTracks.first?.chunks.first(where: { $0.id == survivingChunk.id })
+ XCTAssertEqual(persistedSurvivor?.finalizationState, .finalized)
+
+ let reloaded = try await store.load(id: session.id)
+ let reloadedChunk = reloaded?.audioTracks.first?.chunks.first(where: { $0.id == chunk.id })
+ XCTAssertEqual(reloadedChunk?.finalizationState, .failed)
+ }
+
+ // MARK: - Slice 3, test 6: unreadable-chunk classification
+
+ // MARK: - Regression: arbiter failure during history retry must not strand activeSession
+
+ func testRetryByIDArbiterFailureDoesNotStrandActiveSession() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+
+ let now = Date()
+ let older = self.makeSession(
+ state: .interrupted,
+ startedAt: now.addingTimeInterval(-600),
+ endedAt: now.addingTimeInterval(-590),
+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
+ )
+ let newer = self.makeSession(
+ state: .interrupted,
+ startedAt: now.addingTimeInterval(-60),
+ endedAt: now.addingTimeInterval(-50),
+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
+ )
+ try await store.create(older)
+ try await store.create(newer)
+
+ let arbiter = ThrowOnceArbiter()
+ let coordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: StubCaptureController(),
+ processing: StubProcessingController(),
+ audioArbiter: arbiter
+ )
+ await coordinator.ensureRestored()
+ XCTAssertEqual(coordinator.activeSession?.id, newer.id)
+
+ do {
+ _ = try await coordinator.retryProcessing(sessionID: older.id)
+ XCTFail("Expected retryProcessing to throw when the arbiter refuses the lease")
+ } catch {}
+
+ // Not wedged: the passive offer was never displaced/adopted, so state and activeSession
+ // stay consistent with each other instead of activeSession != nil with state == .idle.
+ XCTAssertEqual(coordinator.activeSession?.id, newer.id)
+ XCTAssertEqual(coordinator.state, .interrupted(newer.id))
+
+ // A subsequent recording is not permanently blocked by a stranded activeSession.
+ try coordinator.resetForNewMeeting()
+ for _ in 0..<40 {
+ if let persisted = try await store.load(id: newer.id), persisted.recoveryResolvedAt != nil { break }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ // `older` was never resolved (the failed retry targeted it but never adopted it); clear
+ // it too so a fresh coordinator's restore scan has nothing left to re-offer.
+ try await store.delete(id: older.id)
+ let capture = StubCaptureController()
+ capture.startResult = MeetingCaptureStartResult(tracks: [self.makeMicrophoneTrack(chunks: [])], firstPresentationTime: nil)
+ let workingCoordinator = MeetingSessionCoordinator(
+ store: store,
+ capture: capture,
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ let started = try await workingCoordinator.startRecording(configuration: self.makeConfiguration(title: "Recovered"))
+ guard case .recording = workingCoordinator.state else {
+ return XCTFail("Expected .recording, got \(workingCoordinator.state)")
+ }
+ XCTAssertEqual(workingCoordinator.activeSession?.id, started.id)
+ }
+
+ // MARK: - Regression: deleteSession re-checks quiescence after the persistence flush
+
+ func testDeleteSessionBlocksRetryUntilComplete() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let realStore = MeetingSessionStore(rootDirectory: dir)
+ let session = self.makeSession(
+ state: .interrupted,
+ endedAt: Date(),
+ audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
+ )
+ try await realStore.create(session)
+
+ let recorder = EventRecorder()
+ let gatedStore = GatedDeleteStore(inner: realStore, recorder: recorder)
+ let coordinator = MeetingSessionCoordinator(
+ store: gatedStore,
+ capture: StubCaptureController(),
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ await coordinator.ensureRestored()
+ XCTAssertEqual(coordinator.activeSession?.id, session.id)
+
+ let deleteTask = Task { try await coordinator.deleteSession(id: session.id) }
+
+ for _ in 0..<40 {
+ if await recorder.events.contains("store.delete.start") { break }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ let eventsSoFar = await recorder.events
+ XCTAssertTrue(eventsSoFar.contains("store.delete.start"))
+
+ do {
+ _ = try await coordinator.retryProcessing(sessionID: session.id)
+ XCTFail("Expected retryProcessing to throw while deleteSession is mid-flight")
+ } catch let error as MeetingCoordinatorError {
+ guard case .activityInProgress = error else {
+ return XCTFail("Expected .activityInProgress, got \(error)")
+ }
+ }
+
+ await gatedStore.openGate()
+ try await deleteTask.value
+
+ XCTAssertNil(coordinator.activeSession)
+ let reloaded = try? await realStore.load(id: session.id)
+ XCTAssertNil(reloaded)
+ }
+
+ func testReadSamplesThrowsAudioUnreadableForGarbageFile() throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let url = dir.appendingPathComponent("garbage.m4a", isDirectory: false)
+ try Data((0..<256).map { _ in UInt8.random(in: 0...255) }).write(to: url)
+
+ XCTAssertThrowsError(
+ try MeetingProcessingPipeline.readSamples(fileURL: url, startSeconds: 0, endSeconds: nil)
+ ) { error in
+ guard case MeetingProcessingError.audioUnreadable = error else {
+ XCTFail("Expected .audioUnreadable, got \(error)")
+ return
+ }
+ }
+ }
}
// MARK: - Test doubles
@@ -459,6 +1155,10 @@ private final class ThrowingDirectoryStore: MeetingSessionStoring, @unchecked Se
if self.throwOnSessionDirectory { throw CocoaError(.fileWriteNoPermission) }
return try await self.wrapped.sessionDirectory(for: id)
}
+ func existingSessionDirectory(for id: MeetingSessionID) async throws -> URL? {
+ try await self.wrapped.existingSessionDirectory(for: id)
+ }
+ func delete(id: MeetingSessionID) async throws { try await self.wrapped.delete(id: id) }
}
private actor EventRecorder {
@@ -468,6 +1168,7 @@ private actor EventRecorder {
private final class StubCaptureController: MeetingCaptureControlling, @unchecked Sendable {
var startResult = MeetingCaptureStartResult(tracks: [], firstPresentationTime: nil)
+ var startError: Error?
var onStart: (@Sendable () async -> Void)?
func start(
@@ -477,6 +1178,7 @@ private final class StubCaptureController: MeetingCaptureControlling, @unchecked
eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void
) async throws -> MeetingCaptureStartResult {
await self.onStart?()
+ if let startError { throw startError }
return self.startResult
}
@@ -513,6 +1215,52 @@ private final class StubProcessingController: MeetingProcessingControlling {
}
}
+private struct ProcessingFailure: Error {}
+
+@MainActor
+private final class ThrowingProcessingController: MeetingProcessingControlling {
+ func process(
+ session: MeetingSession,
+ sessionDirectory: URL,
+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void
+ ) async throws -> MeetingProcessingResult {
+ throw ProcessingFailure()
+ }
+}
+
+@MainActor
+private final class SkippedChunkProcessingController: MeetingProcessingControlling {
+ private let skippedChunkIDs: [MeetingAudioChunkID]
+
+ init(skippedChunkIDs: [MeetingAudioChunkID]) {
+ self.skippedChunkIDs = skippedChunkIDs
+ }
+
+ 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
+ ),
+ skippedChunkIDs: self.skippedChunkIDs
+ )
+ }
+}
+
/// Blocks `process(...)` until `openGate()` is called, so tests can inspect mid-flight state.
@MainActor
private final class GatedProcessingController: MeetingProcessingControlling {
@@ -560,6 +1308,57 @@ private final class StubArbiter: MeetingAudioActivityArbitrating {
func release(_ lease: MeetingAudioActivityLease) {}
}
+/// Throws on the first `acquireMeetingCapture()` call, then succeeds on every subsequent call.
+@MainActor
+private final class ThrowOnceArbiter: MeetingAudioActivityArbitrating {
+ private var hasThrown = false
+ func acquireMeetingCapture() throws -> MeetingAudioActivityLease {
+ guard self.hasThrown else {
+ self.hasThrown = true
+ throw MeetingCoordinatorError.dictationActive
+ }
+ return MeetingAudioActivityLease(id: UUID())
+ }
+ func release(_ lease: MeetingAudioActivityLease) {}
+}
+
+/// Wraps a real `MeetingSessionStore`, suspending `delete(id:)` until `openGate()` is called —
+/// used to hold `deleteSession` mid-flight so a racing retry can be observed.
+private actor GatedDeleteStore: 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 loadRecoverable() async throws -> [MeetingSession] { try await self.inner.loadRecoverable() }
+ func sessionDirectory(for id: MeetingSessionID) async throws -> URL { try await self.inner.sessionDirectory(for: id) }
+ func existingSessionDirectory(for id: MeetingSessionID) async throws -> URL? {
+ try await self.inner.existingSessionDirectory(for: id)
+ }
+ func delete(id: MeetingSessionID) async throws {
+ await self.recorder.record("store.delete.start")
+ if !self.isOpen {
+ await withCheckedContinuation { self.continuation = $0 }
+ }
+ try await self.inner.delete(id: id)
+ }
+}
+
/// Wraps a real `MeetingSessionStore`, suspending `loadRecoverable()` until `openGate()` is
/// called — used to prove `startRecording` waits for the launch restore barrier.
private actor GatedRecoverableStore: MeetingSessionStoring {
@@ -584,6 +1383,10 @@ private actor GatedRecoverableStore: MeetingSessionStoring {
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 existingSessionDirectory(for id: MeetingSessionID) async throws -> URL? {
+ try await self.inner.existingSessionDirectory(for: id)
+ }
+ func delete(id: MeetingSessionID) async throws { try await self.inner.delete(id: id) }
func loadRecoverable() async throws -> [MeetingSession] {
await self.recorder.record("restore.loadRecoverable.start")
diff --git a/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift b/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift
index 4a15d0a1..a254e685 100644
--- a/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift
+++ b/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift
@@ -1358,12 +1358,16 @@ private actor FakeMeetingSessionStore: MeetingSessionStoring {
private var rejectedSaveStates: [MeetingSessionState] = []
private var createCallCount = 0
private var failingSaveState: MeetingSessionState?
+ private var tombstonedIDs: Set<MeetingSessionID> = []
init(failingSaveState: MeetingSessionState?) {
self.failingSaveState = failingSaveState
}
func create(_ session: MeetingSession) throws {
+ guard !self.tombstonedIDs.contains(session.id) else {
+ throw MeetingSessionStoreError.sessionDeleted
+ }
try session.validateForPersistence()
self.createCallCount += 1
self.sessions[session.id] = session
@@ -1371,6 +1375,9 @@ private actor FakeMeetingSessionStore: MeetingSessionStoring {
}
func save(_ session: MeetingSession) throws {
+ guard !self.tombstonedIDs.contains(session.id) else {
+ throw MeetingSessionStoreError.sessionDeleted
+ }
try session.validateForPersistence()
if self.failingSaveState == session.state {
self.failingSaveState = nil
@@ -1381,6 +1388,11 @@ private actor FakeMeetingSessionStore: MeetingSessionStoring {
self.persistedStates.append(session.state)
}
+ func delete(id: MeetingSessionID) throws {
+ self.tombstonedIDs.insert(id)
+ self.sessions.removeValue(forKey: id)
+ }
+
func load(id: MeetingSessionID) -> MeetingSession? {
self.sessions[id]
}
@@ -1419,6 +1431,10 @@ private actor FakeMeetingSessionStore: MeetingSessionStoring {
.appendingPathComponent(id.uuidString, isDirectory: true)
}
+ func existingSessionDirectory(for id: MeetingSessionID) -> URL? {
+ self.sessions[id] != nil ? self.sessionDirectory(for: id) : nil
+ }
+
func snapshot() -> Snapshot {
Snapshot(
sessions: self.sessions,