From c1d3d2429424352fe4f64f760c143f9c770e3b81 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:14:04 +0530 Subject: [PATCH 01/10] Split transcription finish and cancellation --- Aural/CustomVocabularyDemoView.swift | 23 +-- Aural/CustomVocabularyDemoViewModel.swift | 37 ++--- Aural/TranscriptionManager.swift | 23 +-- Aural/TranscriptionView.swift | 17 +- Aural/TranscriptionViewComponents.swift | 20 ++- README.md | 26 ++- Sources/AuralKit/SpeechSession+Audio.swift | 11 +- ...ession+CustomVocabularyConfiguration.swift | 3 +- Sources/AuralKit/SpeechSession+File.swift | 16 +- .../SpeechSession+NativeCaptureInput.swift | 5 +- .../SpeechSession+NativeFileInput.swift | 10 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 150 +++++++++++------- .../SpeechSession+ScreenCapture.swift | 14 +- .../AuralKit/SpeechSession+Transcriber.swift | 26 ++- Sources/AuralKit/SpeechSession.swift | 38 +++-- Tests/AuralKitTests/AuralKitTests.swift | 7 +- .../CustomVocabularyOwnershipTests.swift | 2 +- Tests/AuralKitTests/FileProgressTests.swift | 4 +- .../ScreenCaptureTransitionTests.swift | 62 +++++++- .../ScreenCaptureUpdateTests.swift | 8 +- .../AuralKitTests/SessionLifecycleTests.swift | 28 +++- 21 files changed, 324 insertions(+), 206 deletions(-) diff --git a/Aural/CustomVocabularyDemoView.swift b/Aural/CustomVocabularyDemoView.swift index 71a7eba..3d42f1a 100644 --- a/Aural/CustomVocabularyDemoView.swift +++ b/Aural/CustomVocabularyDemoView.swift @@ -30,12 +30,13 @@ struct CustomVocabularyDemoView: View { TranscriptionControlsView( status: viewModel.status, error: viewModel.errorMessage, - showStopButton: showStopButton, buttonColor: buttonColor, buttonIcon: buttonIcon, statusMessage: statusMessage, onPrimaryAction: handlePrimaryAction, - onStopAction: handleStopAction + onFinishAction: { model.finishTranscription() }, + onCancelAction: { model.cancelTranscription() }, + isPreparing: model.isCompiling ) .padding(.horizontal) } @@ -256,15 +257,6 @@ private extension CustomVocabularyDemoView { } } - var showStopButton: Bool { - switch model.status { - case .idle, .stopping: - return false - case .preparing, .transcribing, .paused: - return true - } - } - var statusMessage: String { switch model.status { case .idle: @@ -274,9 +266,9 @@ private extension CustomVocabularyDemoView { case .transcribing: return "Listening..." case .paused: - return "Paused — tap to resume or stop" + return "Paused" case .stopping: - return "Stopping..." + return "Ending session..." } } @@ -285,7 +277,7 @@ private extension CustomVocabularyDemoView { case .idle: model.startTranscription() case .preparing: - model.stopTranscription() + model.cancelTranscription() case .transcribing: model.pauseTranscription() case .paused: @@ -295,7 +287,4 @@ private extension CustomVocabularyDemoView { } } - func handleStopAction() { - model.stopTranscription() - } } diff --git a/Aural/CustomVocabularyDemoViewModel.swift b/Aural/CustomVocabularyDemoViewModel.swift index 05e9ba2..ed54c5c 100644 --- a/Aural/CustomVocabularyDemoViewModel.swift +++ b/Aural/CustomVocabularyDemoViewModel.swift @@ -57,10 +57,9 @@ final class CustomVocabularyDemoViewModel { // MARK: - Intent Handlers func startTranscription() { - guard status != .transcribing, status != .preparing else { return } + guard status == .idle, transcriptionTask == nil else { return } resetTranscriptionState() - cancelExistingTasks() transcriptionTask = Task { @MainActor in do { @@ -68,7 +67,8 @@ final class CustomVocabularyDemoViewModel { monitorDownloadProgress() try await processTranscriptionStream(stream) } catch is CancellationError { - // expected when stopped + partialText = "" + currentTimeRange = "" } catch { errorMessage = error.localizedDescription isCompiling = false @@ -78,17 +78,15 @@ final class CustomVocabularyDemoViewModel { } } - func stopTranscription() { - progressTask?.cancel() - progressTask = nil - resetProgressObservation(clearFraction: true) - transcriptionTask?.cancel() - transcriptionTask = nil + func finishTranscription() { + Task { await session.finishTranscribing() } + } - Task { @MainActor in - await session.stopTranscribing() - partialText = "" - currentTimeRange = "" + func cancelTranscription() { + if session.status == .idle { + transcriptionTask?.cancel() + } else { + Task { await session.cancelTranscribing() } } } @@ -111,7 +109,7 @@ final class CustomVocabularyDemoViewModel { func handleToggleChange(_ isEnabled: Bool) { isCustomVocabularyEnabled = isEnabled if !isEnabled, status == .transcribing || status == .preparing { - stopTranscription() + cancelTranscription() } } @@ -124,7 +122,7 @@ final class CustomVocabularyDemoViewModel { } func teardown() { - stopTranscription() + cancelTranscription() statusTask?.cancel() statusTask = nil } @@ -153,10 +151,6 @@ final class CustomVocabularyDemoViewModel { isCompiling || status == .preparing || status == .transcribing } - var isStopDisabled: Bool { - status == .idle || status == .stopping - } - // MARK: - Private helpers private func bindStatusStream() { @@ -287,11 +281,6 @@ extension CustomVocabularyDemoViewModel { compilationDuration = nil } - private func cancelExistingTasks() { - transcriptionTask?.cancel() - progressTask?.cancel() - } - private func prepareTranscriptionStream() async throws -> AsyncThrowingStream { let startTime = Date() diff --git a/Aural/TranscriptionManager.swift b/Aural/TranscriptionManager.swift index ed48a85..cefabeb 100644 --- a/Aural/TranscriptionManager.swift +++ b/Aural/TranscriptionManager.swift @@ -14,7 +14,7 @@ class TranscriptionManager { var selectedPreset: DemoTranscriberPreset = .manual { didSet { if oldValue != selectedPreset, status != .idle { - stopTranscription() + cancelTranscription() } } } @@ -122,12 +122,14 @@ class TranscriptionManager { return String(format: "%d:%02d.%02d", minutes, remainingSeconds, milliseconds) } - func stopTranscription() { - guard status != .idle, status != .stopping else { return } - Task { @MainActor in - await self.speechSession?.stopTranscribing() - } - stopAuxiliaryTasks() + func finishTranscription() { + guard let speechSession else { return } + Task { await speechSession.finishTranscribing() } + } + + func cancelTranscription() { + guard let speechSession else { return } + Task { await speechSession.cancelTranscribing() } } func pauseTranscription() { @@ -154,7 +156,7 @@ class TranscriptionManager { case .idle: startTranscription() case .preparing: - stopTranscription() + cancelTranscription() case .transcribing: pauseTranscription() case .paused: @@ -183,10 +185,11 @@ class TranscriptionManager { } private func finishSession() { - if !currentTranscript.isEmpty { + let transcript = String(finalizedText.characters) + if !transcript.isEmpty { let record = TranscriptionRecord( id: UUID(), - text: currentTranscript, + text: transcript, locale: selectedLocale, timestamp: Date(), alternatives: [], diff --git a/Aural/TranscriptionView.swift b/Aural/TranscriptionView.swift index 07d3431..e8dc9f5 100644 --- a/Aural/TranscriptionView.swift +++ b/Aural/TranscriptionView.swift @@ -36,12 +36,12 @@ struct TranscriptionView: View { TranscriptionControlsView( status: manager.status, error: manager.error, - showStopButton: showStopButton, buttonColor: buttonColor, buttonIcon: buttonIcon, statusMessage: statusMessage, onPrimaryAction: { manager.primaryAction() }, - onStopAction: { manager.stopTranscription() }, + onFinishAction: { manager.finishTranscription() }, + onCancelAction: { manager.cancelTranscription() }, animationScale: animationScale ) .padding(.horizontal) @@ -166,15 +166,6 @@ struct TranscriptionView: View { } } - private var showStopButton: Bool { - switch manager.status { - case .idle, .stopping: - return false - case .preparing, .transcribing, .paused: - return true - } - } - private var statusMessage: String { switch manager.status { case .idle: @@ -184,9 +175,9 @@ struct TranscriptionView: View { case .transcribing: return "Listening..." case .paused: - return "Paused — tap to resume or stop" + return "Paused" case .stopping: - return "Stopping..." + return "Ending session..." } } } diff --git a/Aural/TranscriptionViewComponents.swift b/Aural/TranscriptionViewComponents.swift index 46b7d8d..8c30bbf 100644 --- a/Aural/TranscriptionViewComponents.swift +++ b/Aural/TranscriptionViewComponents.swift @@ -120,12 +120,13 @@ struct TranscriptionTextView: View { struct TranscriptionControlsView: View { let status: SpeechSession.Status let error: String? - let showStopButton: Bool let buttonColor: Color let buttonIcon: String let statusMessage: String let onPrimaryAction: () -> Void - let onStopAction: () -> Void + let onFinishAction: () -> Void + let onCancelAction: () -> Void + var isPreparing = false var animationScale: CGFloat = 1.0 var body: some View { @@ -153,12 +154,17 @@ struct TranscriptionControlsView: View { } .buttonStyle(.glass) .buttonBorderShape(.circle) - .disabled(error != nil || status == .stopping) + .disabled(error != nil || status == .stopping || isPreparing) - if showStopButton { - Button("Stop", action: onStopAction) - .buttonStyle(.borderedProminent) - .tint(.gray) + if status != .idle || isPreparing { + HStack { + if status == .transcribing || status == .paused { + Button("Finish", action: onFinishAction) + .buttonStyle(.borderedProminent) + } + Button("Cancel", action: onCancelAction) + .buttonStyle(.bordered) + } } Text(statusMessage) diff --git a/README.md b/README.md index 37cae08..485fb78 100644 --- a/README.md +++ b/README.md @@ -80,9 +80,9 @@ let streamTask = Task { } } -// Later, when you want to stop capturing audio +// Later, when you want to finish capturing audio Task { - await session.stopTranscribing() + await session.finishTranscribing() await streamTask.value } ``` @@ -140,13 +140,24 @@ let streamTask = Task { } } -// Stop when needed +// Finish capture and wait for the final results Task { - await session.stopTranscribing() + await session.finishTranscribing() await streamTask.value } ``` +### Migrating from AuralKit 2.x + +Replace `stopTranscribing()` with `finishTranscribing()` when saving a live transcript. Keep +reading the result stream until it ends and use `isFinal` to decide what to save. Finish waits +for an active file transcription to reach the end of the file. If setup is still in progress, +Finish closes the stream without starting capture. + +Use `cancelTranscribing()` to abandon a run. The stream ends with `CancellationError`, including +when using the one-shot file API. The stream may still contain results already yielded before +cancellation. Clear any displayed partial text and handle cancellation separately from errors. + ## Demo App Check out the included **Aural** demo app to see AuralKit in action! The demo showcases: @@ -453,8 +464,11 @@ public final class SpeechSession { /// Start transcribing - returns stream of SpeechTranscriber.Result public func startTranscribing() -> AsyncThrowingStream - /// Stop transcribing - public func stopTranscribing() async + /// End live capture and drain final results + public func finishTranscribing() async + + /// Abort transcription with CancellationError + public func cancelTranscribing() async } ``` diff --git a/Sources/AuralKit/SpeechSession+Audio.swift b/Sources/AuralKit/SpeechSession+Audio.swift index ef7396f..f9e5766 100644 --- a/Sources/AuralKit/SpeechSession+Audio.swift +++ b/Sources/AuralKit/SpeechSession+Audio.swift @@ -230,11 +230,9 @@ extension SpeechSession { return } + guard status == .paused else { return } do { - try await setupAudioSession() - // The session can be stopped and restarted while the audio session is being - // reconfigured; a stale interruption must not resume or tear down the newer stream. - guard generation == sessionGeneration else { return } + try setupAudioSession() try startAudioStreaming() setStatus(.transcribing) if Self.shouldLog(.notice) { @@ -255,10 +253,7 @@ extension SpeechSession { /// to a session that has already been stopped cannot mark a newer session `.stopping` or /// finish its stream. private func finishInterruptedSession(error: Error?, generation: Int) async { - guard generation == sessionGeneration else { return } - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) + await endTranscription(error: error, generation: generation) } #elseif os(macOS) func handleEngineConfigurationChange() async { diff --git a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift index 4513902..2c6149f 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift @@ -106,7 +106,8 @@ extension SpeechSession { } let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in + newContinuation.onTermination = { [weak self] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self] in await self?.handleStreamTermination(generation: generation) } diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 788925d..d680649 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -74,7 +74,8 @@ public extension SpeechSession { } let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in + newContinuation.onTermination = { [weak self] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self] in await self?.handleStreamTermination(generation: generation) } @@ -125,6 +126,7 @@ public extension SpeechSession { } let finalResults = try await stream.reduce(into: [SpeechTranscriber.Result](), accumulator) + try Task.checkCancellation() return finalResults } } @@ -282,7 +284,7 @@ private extension SpeechSession { if #available(iOS 27.0, macOS 27.0, *), progressHandler == nil, await shouldUseNativeAssetInputProvider { - return try await feedAudioFileWithNativeAnalyzer(payload.file, progressHandler: progressHandler) + return try await feedAudioFileWithNativeAnalyzer(payload.file, generation: generation) } #endif @@ -319,7 +321,7 @@ private extension SpeechSession { let sendableBuffer = SendablePCMBuffer(buffer: bufferCopy) - try await self.processAudioBuffer(sendableBuffer) + try await processAudioBuffer(sendableBuffer, generation: generation) processedFrames += AVAudioFramePosition(buffer.frameLength) @@ -331,7 +333,7 @@ private extension SpeechSession { guard !Task.isCancelled else { return false } - try await self.finishAnalyzerInput() + try await finishFileInput(generation: generation) return !Task.isCancelled && processedFrames >= totalFrames } @@ -348,6 +350,12 @@ private extension SpeechSession { } extension SpeechSession { + func finishFileInput(generation: Int) async throws { + try Task.checkCancellation() + guard generation == sessionGeneration else { throw CancellationError() } + try await finishAnalyzerInput() + } + func reportFileProgress( _ progress: Double, handler: @Sendable (Double) -> Void, diff --git a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift index 76d063d..aa27fd6 100644 --- a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift @@ -83,10 +83,11 @@ extension SpeechSession { defer { withExtendedLifetime(vocabularyArtifacts) {} } do { let lastAudioTime = try await analyzer.analyzeSequence(analyzerInputs) + try Task.checkCancellation() if let lastAudioTime { try await analyzer.finalizeAndFinish(through: lastAudioTime) } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() + await analyzer.cancelAndFinishNow() } } catch is CancellationError { // Cancellation is expected during explicit cleanup. @@ -133,7 +134,7 @@ extension SpeechSession { func finishFromNativeCaptureAnalysis(_ error: Error, generation: Int) async { guard generation == sessionGeneration else { return } nativeCaptureAnalysisTask = nil - await finishFromRecognizerTask(error: error, generation: generation) + await endTranscription(error: error, generation: generation) } } #endif diff --git a/Sources/AuralKit/SpeechSession+NativeFileInput.swift b/Sources/AuralKit/SpeechSession+NativeFileInput.swift index a412ba2..dbc0eeb 100644 --- a/Sources/AuralKit/SpeechSession+NativeFileInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeFileInput.swift @@ -15,24 +15,28 @@ extension SpeechSession { nonisolated func feedAudioFileWithNativeAnalyzer( _ file: AVAudioFile, - progressHandler _: (@Sendable (Double) -> Void)? + generation: Int ) async throws -> Bool { guard !Task.isCancelled else { return false } - guard let analyzer = await MainActor.run(body: { analyzer }) else { + guard let analyzer = await MainActor.run(body: { generation == sessionGeneration ? analyzer : nil }) else { throw SpeechSessionError.recognitionStreamSetupFailed } try await prepareAnalyzerForStartIfNeeded(in: file.processingFormat) + try Task.checkCancellation() await MainActor.run { + guard !Task.isCancelled, generation == sessionGeneration else { return } startSpeechDetectorMonitoringIfNeeded() } + try Task.checkCancellation() let lastAudioTime = try await analyzer.analyzeSequence(from: file) + try Task.checkCancellation() if let lastAudioTime { try await analyzer.finalizeAndFinish(through: lastAudioTime) } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() + await analyzer.cancelAndFinishNow() } return !Task.isCancelled diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 97c0395..17d3246 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -86,10 +86,7 @@ extension SpeechSession { /// Runs only when the terminating stream is still the current one; stale handlers /// (from streams that were already replaced or finished) are ignored. func handleStreamTermination(generation: Int) async { - guard generation == sessionGeneration else { return } - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: nil, generation: generation) + await endTranscription(error: CancellationError(), generation: generation) } var isPausableStreamingMode: Bool { @@ -108,7 +105,7 @@ extension SpeechSession { try Task.checkCancellation() try await ensurePermissions() try Task.checkCancellation() - try await setupAudioSession() + try setupAudioSession() try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider @@ -161,7 +158,7 @@ extension SpeechSession { try Task.checkCancellation() try await ensurePermissions() try Task.checkCancellation() - try await setupAudioSession() + try setupAudioSession() try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider @@ -205,63 +202,98 @@ extension SpeechSession { } func finishFailedPipelineSetup(_ error: Error, generation: Int) async { - guard generation == sessionGeneration else { return } + guard generation == sessionGeneration, terminationTask == nil else { return } pipelineTask = nil - if error is CancellationError { - await finishCancelledPipelineSetup(generation: generation) - } else { - await finishWithStartupError(error, generation: generation) - } + await finishWithStartupError(error, generation: generation) } - /// Unwind a pipeline whose setup task was cancelled by `cleanup` (stop or stream termination). - /// - /// The canceller already ran `cleanup`, but this task may have created additional state - /// (transcriber, analyzer, audio taps) after that cleanup finished, so run it once more. - /// `finishStream` is a no-op when the canceller already finished the stream, and both steps - /// are skipped when a newer stream generation owns the session state. - func finishCancelledPipelineSetup(generation: Int) async { - guard generation == sessionGeneration else { return } - if Self.shouldLog(.debug) { - Self.logger.debug("Pipeline setup cancelled; unwinding") - } - await cleanup(cancelRecognizer: true, generation: generation) - guard generation == sessionGeneration else { return } - await finishStream(error: nil, generation: generation) + func finishWithStartupError(_ error: Error, generation: Int) async { + guard generation == sessionGeneration, terminationTask == nil else { return } + await endTranscription(error: Task.isCancelled ? CancellationError() : error, generation: generation) } - func finishWithStartupError(_ error: Error, generation: Int) async { + func finishFromRecognizerTask(error: Error?, generation: Int) async { + await endTranscription(error: error, generation: generation, cancelRecognizer: error != nil) + } + + func finishTranscribing(generation: Int, sourceEnded: Bool = false) async { guard generation == sessionGeneration else { return } - // A cancelled setup task means another teardown already owns the stream; unwind - // quietly instead of surfacing a spurious error to a stream that was stopped on purpose. - if Task.isCancelled { - await finishCancelledPipelineSetup(generation: generation) + if let terminationTask { + await terminationTask.value return } - if Self.shouldLog(.error) { - Self.logger.error("Finishing due to startup error: \(error.localizedDescription, privacy: .public)") + if let finishTask { + await finishTask.value + return + } + guard let recognizerTask, sourceEnded || status != .preparing else { + await endTranscription(error: nil, generation: generation) + return } + if streamingMode == .filePlayback { + await recognizerTask.value + return + } + prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) + let task = Task { + await finishLiveTranscription(results: recognizerTask, generation: generation) + } + finishTask = task + await task.value } - func finishFromRecognizerTask(error: Error?, generation: Int) async { + private func finishLiveTranscription(results: Task, generation: Int) async { guard generation == sessionGeneration else { return } - if let error { - if Self.shouldLog(.error) { - Self.logger.error( - "Finishing from recognizer with error: \(error.localizedDescription, privacy: .public)" - ) - } + if let terminationTask { + await terminationTask.value + return + } + guard continuation != nil else { return } + stopAudioStreaming() + if let nativeCaptureAnalysisTask { + // The provider's sequence reaches EOF when its audio data output is deallocated. + nativeCaptureSession = nil + await nativeCaptureAnalysisTask.value } else { - if Self.shouldLog(.notice) { - Self.logger.notice("Finishing from recognizer without error") + await stopScreenCaptureStreamingIfNeeded() + guard generation == sessionGeneration else { return } + if let terminationTask { + await terminationTask.value + return } + guard continuation != nil else { return } + do { + try await finishAnalyzerInput() + } catch { + await endTranscription(error: error, generation: generation) + return + } + } + + await results.value + } + + func endTranscription(error: Error?, generation: Int, cancelRecognizer: Bool = true) async { + guard generation == sessionGeneration else { return } + if let terminationTask { + await terminationTask.value + return + } + guard continuation != nil || pipelineTask != nil || status != .idle || streamingMode != .inactive else { + return } prepareForStop() - await cleanup(cancelRecognizer: false, generation: generation) - await finishStream(error: error, generation: generation) + pipelineTask?.cancel() + let task = Task { + await cleanup(cancelRecognizer: cancelRecognizer, generation: generation) + guard generation == sessionGeneration else { return } + finishTask = nil + terminationTask = nil + finishStream(error: error, generation: generation) + } + terminationTask = task + await task.value } /// Tear down the active pipeline. @@ -305,8 +337,8 @@ extension SpeechSession { shouldResumeAfterInterruption = false #endif let detached = detachTranscriberState() + await cleanUpDetachedTranscriberState(detached, cancelAnalyzer: cancelRecognizer) await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached) guard generation == sessionGeneration else { return } await modelManager.releaseLocales() @@ -322,7 +354,7 @@ extension SpeechSession { /// /// Generation-guarded so a teardown belonging to an older stream can never finish (or /// error out) the stream of a session that has since started. - func finishStream(error: Error?, generation: Int) async { + func finishStream(error: Error?, generation: Int) { guard generation == sessionGeneration else { return } guard let continuation else { return } self.continuation = nil @@ -361,18 +393,16 @@ extension SpeechSession { // MARK: - Helper Methods - func setupAudioSession() async throws { + func setupAudioSession() throws { #if os(iOS) - try await MainActor.run { - let audioSession = AVAudioSession.sharedInstance() - try audioSession.setCategory( - audioConfig.category, - mode: audioConfig.mode, - options: audioConfig.options - ) - try audioSession.setActive(true) - isAudioSessionActive = true - } + let audioSession = AVAudioSession.sharedInstance() + try audioSession.setCategory( + audioConfig.category, + mode: audioConfig.mode, + options: audioConfig.options + ) + try audioSession.setActive(true) + isAudioSessionActive = true #endif #if os(iOS) || os(macOS) publishCurrentAudioInputInfo() @@ -441,6 +471,7 @@ extension SpeechSession { do { for try await result in results { + guard generation == sessionGeneration, terminationTask == nil else { return } streamContinuation.yield(result) } if Self.shouldLog(.notice) { @@ -451,6 +482,7 @@ extension SpeechSession { if Self.shouldLog(.debug) { Self.logger.debug("\(label, privacy: .public) cancelled") } + await self.finishFromRecognizerTask(error: CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error( diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index fec4157..af041d8 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -38,9 +38,7 @@ extension SpeechSession { } catch { let canFinish = status == .paused || (captureFailure != nil && status == .stopping) guard generation == sessionGeneration, canFinish, streamingMode == .screenCapture else { throw error } - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) + await endTranscription(error: error, generation: generation) throw error } if let terminalFailure { throw terminalFailure } @@ -89,7 +87,8 @@ public extension SpeechSession { } let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in + newContinuation.onTermination = { [weak self] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self] in await self?.handleStreamTermination(generation: generation) } @@ -152,6 +151,7 @@ extension SpeechSession { ) try await setUpScreenCaptureStreaming(options: options, generation: generation) try Task.checkCancellation() + guard status == .preparing else { return } streamingMode = .screenCapture setStatus(.transcribing) @@ -181,7 +181,11 @@ extension SpeechSession { useNativeConversion: inputProviderPreference == .automatic, onTermination: { [weak self] error in Task { @MainActor [weak self] in - await self?.finishFromRecognizerTask(error: error, generation: generation) + if let error { + await self?.endTranscription(error: error, generation: generation) + } else { + await self?.finishTranscribing(generation: generation, sourceEnded: true) + } } } ) diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index 460ddcf..a2de988 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -212,6 +212,7 @@ extension SpeechSession { guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: modules) else { throw SpeechSessionError.invalidAudioDataType } + try Task.checkCancellation() analyzerFormat = format if Self.shouldLog(.debug) { @@ -231,8 +232,10 @@ extension SpeechSession { } try await prepareAnalyzerForStartIfNeeded(in: format) + try Task.checkCancellation() try await analyzer.start(inputSequence: inputSequence) + try Task.checkCancellation() if Self.shouldLog(.info) { Self.logger.info("Analyzer started") } @@ -240,7 +243,9 @@ extension SpeechSession { startSpeechDetectorMonitoringIfNeeded() } - func processAudioBuffer(_ buffer: SendablePCMBuffer) async throws { + func processAudioBuffer(_ buffer: SendablePCMBuffer, generation: Int) async throws { + try Task.checkCancellation() + guard generation == sessionGeneration else { throw CancellationError() } guard let inputBuilder, let analyzerFormat else { throw SpeechSessionError.invalidAudioDataType } @@ -249,6 +254,7 @@ extension SpeechSession { from: buffer, analyzerFormat: analyzerFormat ) + try Task.checkCancellation() inputBuilder.yield(input) } @@ -257,7 +263,7 @@ extension SpeechSession { try await analyzer?.finalizeAndFinishThroughEndOfInput() } - /// State captured by `detachTranscriberState()` for asynchronous finalization. + /// State captured by `detachTranscriberState()` for asynchronous cleanup. struct DetachedTranscriberState { let inputBuilder: AsyncStream.Continuation? let analyzer: SpeechAnalyzer? @@ -293,21 +299,9 @@ extension SpeechSession { return detached } - /// Finish the detached analyzer input and finalize the detached analyzer. - /// - /// Operates only on the captured references, never on live session state, so it is safe to - /// run even after a newer session has started. - func finalizeDetachedTranscriberState(_ detached: DetachedTranscriberState) async { + func cleanUpDetachedTranscriberState(_ detached: DetachedTranscriberState, cancelAnalyzer: Bool) async { defer { withExtendedLifetime(detached.vocabularyArtifacts) {} } detached.inputBuilder?.finish() - do { - try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() - } catch { - // Finalization failed, but we still need to clean up resources - // Log for debugging but don't propagate since stop() is best-effort cleanup - } - if Self.shouldLog(.debug) { - Self.logger.debug("Transcriber cleanup complete") - } + if cancelAnalyzer { await detached.analyzer?.cancelAndFinishNow() } } } diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 8c3008d..dc537d5 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -28,8 +28,7 @@ import Speech /// } /// ``` /// -/// Call `stopTranscribing()` to end capture and unwind the stream. The same instance may be reused -/// for subsequent transcription sessions. +/// Use `finishTranscribing()` to receive final results or `cancelTranscribing()` to abandon the run. @MainActor public final class SpeechSession { @@ -100,6 +99,8 @@ public final class SpeechSession { var continuation: TranscriptionContinuation? var recognizerTask: Task? var pipelineTask: Task? + var finishTask: Task? + var terminationTask: Task? var fileIngestionTask: Task? var streamingMode: StreamingMode = .inactive /// Incremented for every accepted start so stale termination handlers can be ignored. @@ -267,7 +268,7 @@ public final class SpeechSession { /// /// The returned `AsyncThrowingStream` yields `SpeechTranscriber.Result` chunks containing both text and /// timing metadata (`.audioTimeRange`), as well as whether the result is final or volatile (partial). - /// Consume the stream with `for try await` and call `stopTranscribing()` to finish early. + /// Consume the stream with `for try await` and call `finishTranscribing()` to finish capture. /// /// - Parameter contextualStrings: Optional dictionary mapping contextual strings tags /// to arrays of contextual words that help improve transcription accuracy. For example, @@ -305,7 +306,8 @@ public final class SpeechSession { } let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in + newContinuation.onTermination = { [weak self] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self] in await self?.handleStreamTermination(generation: generation) } @@ -345,18 +347,23 @@ public final class SpeechSession { public func startTranscribing( contextualStrings: [String] ) -> AsyncThrowingStream { - return startTranscribing(contextualStrings: [.general: contextualStrings]) + startTranscribing(contextualStrings: [.general: contextualStrings]) } - /// Stop capturing audio and finish the current transcription stream. + /// End live capture and deliver final results for audio already queued for analysis. /// - /// Safe to call even if `startTranscribing()` has not been invoked or the stream has already - /// completed; the method simply waits for cleanup and returns. - public func stopTranscribing() async { - let generation = sessionGeneration - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: nil, generation: generation) + /// Keep consuming the result stream until it completes. For an active file transcription, this + /// waits for the file to finish naturally. During preparation, it closes the stream without + /// starting capture. The result stream reports any finalization error. + public func finishTranscribing() async { + await finishTranscribing(generation: sessionGeneration) + } + + /// Abort the current run without finalizing pending audio. + /// + /// The result stream ends with `CancellationError`. Results already yielded may still be read. + public func cancelTranscribing() async { + await endTranscription(error: CancellationError(), generation: sessionGeneration) } /// Pause capture without tearing down the analyzer pipeline. @@ -385,11 +392,8 @@ public final class SpeechSession { try startAudioStreaming() setStatus(.transcribing) } catch { - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) + await endTranscription(error: error, generation: generation) throw error } } - } diff --git a/Tests/AuralKitTests/AuralKitTests.swift b/Tests/AuralKitTests/AuralKitTests.swift index 2b1d8ff..b52533f 100644 --- a/Tests/AuralKitTests/AuralKitTests.swift +++ b/Tests/AuralKitTests/AuralKitTests.swift @@ -36,11 +36,12 @@ struct SpeechSessionStateTests { #expect(session.analyzerConfiguration == configuration) } - @Test("Stop transcribing without session is a no-op") + @Test("Finish and Cancel without a session are no-ops") @MainActor - func stopTranscribingWithoutSessionIsNoOp() async { + func endingTranscriptionWithoutSessionIsNoOp() async { let session = SpeechSession() - await session.stopTranscribing() + await session.finishTranscribing() + await session.cancelTranscribing() #expect(await session.modelDownloadProgress == nil) #expect(session.status == .idle) } diff --git a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift index 6efec35..0315234 100644 --- a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift +++ b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift @@ -126,7 +126,7 @@ struct CustomVocabularyOwnershipTests { try await owner!.configureCustomVocabulary(nil) owner = nil try assertFiles(in: directory) - await SpeechSession().finalizeDetachedTranscriberState(try #require(detached)) + await SpeechSession().cleanUpDetachedTranscriberState(try #require(detached), cancelAnalyzer: true) try assertFiles(in: directory) detached = nil #expect(!FileManager.default.fileExists(atPath: directory.path)) diff --git a/Tests/AuralKitTests/FileProgressTests.swift b/Tests/AuralKitTests/FileProgressTests.swift index 0a86f0e..04721db 100644 --- a/Tests/AuralKitTests/FileProgressTests.swift +++ b/Tests/AuralKitTests/FileProgressTests.swift @@ -22,7 +22,7 @@ struct FileProgressTests { case "stopping": session.prepareForStop() case "stopped": - await session.stopTranscribing() + await session.cancelTranscribing() case "replacement": _ = session.beginStreamGeneration() default: @@ -41,6 +41,6 @@ struct FileProgressTests { var received: [Double] = [] for await value in progress { received.append(value) } #expect(received == [0.25]) - await session.stopTranscribing() + await session.cancelTranscribing() } } diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index fbc9d7f..bbeee88 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -34,7 +34,7 @@ final class CaptureSessionFixture { func close(_ fixture: CaptureFixture) async { fixture.releaseAll() - await session.stopTranscribing() + await session.cancelTranscribing() } } @@ -91,6 +91,62 @@ struct ScreenCaptureTransitionTests { } } + @Test("Finish drains screen input unless Cancel supersedes it", arguments: [false, true]) + @MainActor + func finishDrainsScreenSource(cancel: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + let (inputs, inputBuilder) = AsyncStream.makeStream() + runtime.session.inputBuilder = inputBuilder + let (results, resultContinuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(resultContinuation) + let generation = runtime.session.sessionGeneration + let resultsTask = Task { + for await _ in inputs {} + await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) + } + defer { resultsTask.cancel() } + runtime.session.recognizerTask = resultsTask + let finish = fixture.track(Task { await runtime.session.finishTranscribing() }) + try await stopEntered.wait() + #expect(runtime.session.status == .stopping) + let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) + let pcm = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 1)) + pcm.frameLength = 1 + let input = AnalyzerInput(buffer: pcm) + if case .terminated = inputBuilder.yield(input) { + Issue.record("The input stream closed before the screen source stopped") + } + if cancel { + let cancelTask = fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.session.inputBuilder == nil } + switch inputBuilder.yield(input) { + case .terminated: break + default: Issue.record("Cancel left the input stream open") + } + stopRelease.open() + await cancelTask.value + await #expect(throws: CancellationError.self) { + for try await _ in results {} + } + } else { + stopRelease.open() + var iterator = results.makeAsyncIterator() + let result = try await iterator.next() + #expect(result == nil) + } + await finish.value + #expect(runtime.session.status == .idle) + } + } + @Test("Concurrent public stops join a replacement start and its compensating stop") @MainActor func stopDuringReplacementStart() async throws { @@ -108,13 +164,13 @@ struct ScreenCaptureTransitionTests { try await entered.wait() var firstReturned = false, secondReturned = false let first = fixture.track(Task { - await runtime.session.stopTranscribing(); firstReturned = true + await runtime.session.cancelTranscribing(); firstReturned = true }) try await runtime.dismissed.wait() let secondEntered = fixture.gate() let second = fixture.track(Task { secondEntered.open() - await runtime.session.stopTranscribing(); secondReturned = true + await runtime.session.cancelTranscribing(); secondReturned = true }) try await secondEntered.wait() #expect(!firstReturned && !secondReturned) diff --git a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift index d65ef4d..92ba0f4 100644 --- a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift @@ -26,7 +26,7 @@ struct ScreenCaptureUpdateTests { }) try await started.wait() if stopFirst { - fixture.track(Task { await runtime.session.stopTranscribing() }) + fixture.track(Task { await runtime.session.cancelTranscribing() }) } await fixture.track(Task { @MainActor in if stopFirst { #expect(runtime.session.status == .stopping) } @@ -126,7 +126,11 @@ struct ScreenCaptureUpdateTests { try await updating.wait() #expect(stream.capturing && stream.starts == 1 && stream.stops == 0) let control = fixture.track(Task { - if stop { await runtime.session.stopTranscribing() } else { await runtime.session.pauseTranscribing() } + if stop { + await runtime.session.cancelTranscribing() + } else { + await runtime.session.pauseTranscribing() + } }) try await waitForCaptureState { runtime.owner.desiredState == (stop ? .stopped : .paused) } let later = fixture.track(runtime.provider.updateStream(stream) { updates += 1 }) diff --git a/Tests/AuralKitTests/SessionLifecycleTests.swift b/Tests/AuralKitTests/SessionLifecycleTests.swift index bc50a4f..fbce288 100644 --- a/Tests/AuralKitTests/SessionLifecycleTests.swift +++ b/Tests/AuralKitTests/SessionLifecycleTests.swift @@ -113,12 +113,12 @@ struct SpeechSessionLifecycleTests { let (_, continuation) = AsyncThrowingStream.makeStream() session.continuation = .speech(continuation) - await session.finishStream(error: SpeechSessionError.invalidAudioDataType, generation: staleGeneration) + session.finishStream(error: SpeechSessionError.invalidAudioDataType, generation: staleGeneration) #expect(session.continuation != nil) // The current generation still owns the stream and can finish it. - await session.finishStream(error: nil, generation: session.sessionGeneration) + session.finishStream(error: nil, generation: session.sessionGeneration) #expect(session.continuation == nil) } @@ -138,10 +138,32 @@ struct SpeechSessionLifecycleTests { ) #expect(session.pipelineTask == successor) - await session.stopTranscribing() + await session.cancelTranscribing() await successor.value } + @Test("Finish closes a preparing stream and Cancel reports cancellation", arguments: [false, true]) + @MainActor + func endPreparingTranscription(cancel: Bool) async throws { + let session = SpeechSession() + let stream = session.startTranscribing() + + if cancel { + await session.cancelTranscribing() + await #expect(throws: CancellationError.self) { + for try await _ in stream {} + } + } else { + await session.finishTranscribing() + var iterator = stream.makeAsyncIterator() + let result = try await iterator.next() + #expect(result == nil) + } + + #expect(session.status == .idle) + #expect(session.continuation == nil) + } + /// Pausing is only meaningful for live capture; during file transcription it must be /// refused (previously, resuming a "paused" file session started the microphone). @Test("Pause is refused during file transcription") From 635d21dd6fcb2a917a8b29b029c8cf8fc6c07579 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:16:14 +0530 Subject: [PATCH 02/10] Use analyzer compatible PCM in lifecycle test --- .../ScreenCaptureTransitionTests.swift | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index bbeee88..bfa6b10 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -117,10 +117,7 @@ struct ScreenCaptureTransitionTests { let finish = fixture.track(Task { await runtime.session.finishTranscribing() }) try await stopEntered.wait() #expect(runtime.session.status == .stopping) - let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) - let pcm = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 1)) - pcm.frameLength = 1 - let input = AnalyzerInput(buffer: pcm) + let input = try makeAnalyzerInput() if case .terminated = inputBuilder.yield(input) { Issue.record("The input stream closed before the screen source stopped") } @@ -147,6 +144,16 @@ struct ScreenCaptureTransitionTests { } } + private func makeAnalyzerInput() throws -> AnalyzerInput { + let format = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let pcm = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 160)) + pcm.frameLength = 160 + pcm.int16ChannelData?.pointee.initialize(repeating: 0, count: 160) + return AnalyzerInput(buffer: pcm) + } + @Test("Concurrent public stops join a replacement start and its compensating stop") @MainActor func stopDuringReplacementStart() async throws { From 731ef5b97e50192452739ab1c714fdd0e5140062 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:18:25 +0530 Subject: [PATCH 03/10] Admit screen stop before awaiting terminal cleanup --- Sources/AuralKit/SpeechSession+Pipeline.swift | 23 ++++++++++++++----- .../SpeechSession+ScreenCapture.swift | 15 ++++++------ 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 17d3246..0d36a8e 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -236,14 +236,19 @@ extension SpeechSession { } prepareForStop() + let screenStop = beginStoppingScreenCapture() let task = Task { - await finishLiveTranscription(results: recognizerTask, generation: generation) + await finishLiveTranscription(results: recognizerTask, screenStop: screenStop, generation: generation) } finishTask = task await task.value } - private func finishLiveTranscription(results: Task, generation: Int) async { + private func finishLiveTranscription( + results: Task, + screenStop: Task?, + generation: Int + ) async { guard generation == sessionGeneration else { return } if let terminationTask { await terminationTask.value @@ -256,7 +261,7 @@ extension SpeechSession { nativeCaptureSession = nil await nativeCaptureAnalysisTask.value } else { - await stopScreenCaptureStreamingIfNeeded() + await screenStop?.value guard generation == sessionGeneration else { return } if let terminationTask { await terminationTask.value @@ -285,8 +290,9 @@ extension SpeechSession { } prepareForStop() pipelineTask?.cancel() + let screenStop = beginStoppingScreenCapture() let task = Task { - await cleanup(cancelRecognizer: cancelRecognizer, generation: generation) + await cleanup(cancelRecognizer: cancelRecognizer, screenStop: screenStop, generation: generation) guard generation == sessionGeneration else { return } finishTask = nil terminationTask = nil @@ -303,7 +309,11 @@ extension SpeechSession { /// slow finalization steps then operate on the detached references. Steps that touch shared /// state after a suspension re-check `generation` so a stale teardown cannot damage a newer /// session. - func cleanup(cancelRecognizer: Bool, generation: Int) async { + func cleanup( + cancelRecognizer: Bool, + screenStop: Task? = nil, + generation: Int + ) async { guard generation == sessionGeneration else { return } if Self.shouldLog(.debug) { Self.logger.debug("Cleanup started (cancelRecognizer: \(cancelRecognizer, privacy: .public))") @@ -338,7 +348,8 @@ extension SpeechSession { #endif let detached = detachTranscriberState() await cleanUpDetachedTranscriberState(detached, cancelAnalyzer: cancelRecognizer) - await stopScreenCaptureStreamingIfNeeded() + await screenStop?.value + if screenCaptureStopTask?.generation == generation { screenCaptureStopTask = nil } guard generation == sessionGeneration else { return } await modelManager.releaseLocales() diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index af041d8..5e3ccab 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -205,20 +205,18 @@ extension SpeechSession { setStatus(.paused) } - func stopScreenCaptureStreamingIfNeeded() async { + func beginStoppingScreenCapture() -> Task? { let generation = sessionGeneration if let pending = screenCaptureStopTask, pending.generation == generation { - await pending.task.value - return + return pending.task } let detachedProvider = screenCaptureInputProvider screenCaptureInputProvider = nil - guard #available(iOS 27.0, macOS 14.0, *) else { return } - guard let provider = detachedProvider as? ScreenCaptureAudioInputProvider else { return } + guard #available(iOS 27.0, macOS 14.0, *) else { return nil } + guard let provider = detachedProvider as? ScreenCaptureAudioInputProvider else { return nil } let task = provider.stop() screenCaptureStopTask = (generation, task) - await task.value - if screenCaptureStopTask?.generation == generation { screenCaptureStopTask = nil } + return task } } @@ -521,8 +519,9 @@ public extension SpeechSession { extension SpeechSession { func pauseScreenCaptureStreamingIfNeeded(generation: Int) async {} - func stopScreenCaptureStreamingIfNeeded() async { + func beginStoppingScreenCapture() -> Task? { screenCaptureInputProvider = nil + return nil } } #endif From 17aa09e93aa71adf3e6d415b78579c7d74e36b3d Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:19:29 +0530 Subject: [PATCH 04/10] Keep cancellation observable until result stream completes --- Sources/AuralKit/SpeechSession+Pipeline.swift | 12 +++++-- Sources/AuralKit/SpeechSession.swift | 3 +- .../ScreenCaptureTransitionTests.swift | 33 +++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 0d36a8e..a110000 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -279,8 +279,14 @@ extension SpeechSession { await results.value } - func endTranscription(error: Error?, generation: Int, cancelRecognizer: Bool = true) async { + func endTranscription( + error: Error?, + generation: Int, + cancelRecognizer: Bool = true, + requestedByCaller: Bool = false + ) async { guard generation == sessionGeneration else { return } + if requestedByCaller, continuation != nil { cancellationRequested = true } if let terminationTask { await terminationTask.value return @@ -294,9 +300,11 @@ extension SpeechSession { let task = Task { await cleanup(cancelRecognizer: cancelRecognizer, screenStop: screenStop, generation: generation) guard generation == sessionGeneration else { return } + let terminalError = cancellationRequested ? CancellationError() : error + cancellationRequested = false finishTask = nil terminationTask = nil - finishStream(error: error, generation: generation) + finishStream(error: terminalError, generation: generation) } terminationTask = task await task.value diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index dc537d5..4310d2f 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -101,6 +101,7 @@ public final class SpeechSession { var pipelineTask: Task? var finishTask: Task? var terminationTask: Task? + var cancellationRequested = false var fileIngestionTask: Task? var streamingMode: StreamingMode = .inactive /// Incremented for every accepted start so stale termination handlers can be ignored. @@ -363,7 +364,7 @@ public final class SpeechSession { /// /// The result stream ends with `CancellationError`. Results already yielded may still be read. public func cancelTranscribing() async { - await endTranscription(error: CancellationError(), generation: sessionGeneration) + await endTranscription(error: CancellationError(), generation: sessionGeneration, requestedByCaller: true) } /// Pause capture without tearing down the analyzer pipeline. diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index bfa6b10..5e838a0 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -144,6 +144,39 @@ struct ScreenCaptureTransitionTests { } } + @Test("Cancel wins while the successful screen completion still owns cleanup") + @MainActor + func cancelDuringTerminalScreenCleanup() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + let generation = runtime.session.sessionGeneration + let completed = fixture.track(Task { + await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) + }) + try await stopEntered.wait() + let cancel = fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.session.cancellationRequested } + stopRelease.open() + await cancel.value + await completed.value + + await #expect(throws: CancellationError.self) { + for try await _ in results {} + } + #expect(source.stops == 1) + #expect(runtime.session.status == .idle) + } + } + private func makeAnalyzerInput() throws -> AnalyzerInput { let format = try #require(AVAudioFormat( commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true From 4943f0ffa6dc11ceeb9b9f9ce259f7b652287124 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:26:46 +0530 Subject: [PATCH 05/10] Close empty analysis and surface finish failures --- Aural/TranscriptionManager.swift | 13 +- README.md | 2 + Sources/AuralKit/SpeechSession+Audio.swift | 3 +- Sources/AuralKit/SpeechSession+File.swift | 4 +- .../SpeechSession+NativeCaptureInput.swift | 2 +- .../SpeechSession+NativeFileInput.swift | 2 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 28 ++-- .../SpeechSession+ScreenCapture.swift | 7 +- .../AuralKit/SpeechSession+Transcriber.swift | 16 ++- Sources/AuralKit/SpeechSession.swift | 14 +- .../ScreenCaptureFinishTests.swift | 127 ++++++++++++++++++ .../ScreenCaptureTransitionTests.swift | 96 ------------- .../AuralKitTests/SessionLifecycleTests.swift | 24 ++++ 13 files changed, 206 insertions(+), 132 deletions(-) create mode 100644 Tests/AuralKitTests/ScreenCaptureFinishTests.swift diff --git a/Aural/TranscriptionManager.swift b/Aural/TranscriptionManager.swift index cefabeb..18bed85 100644 --- a/Aural/TranscriptionManager.swift +++ b/Aural/TranscriptionManager.swift @@ -14,7 +14,7 @@ class TranscriptionManager { var selectedPreset: DemoTranscriberPreset = .manual { didSet { if oldValue != selectedPreset, status != .idle { - cancelTranscription() + finishTranscription() } } } @@ -66,7 +66,8 @@ class TranscriptionManager { currentTimeRange = "" isSpeechDetected = true - let session = SpeechSession(locale: selectedLocale, preset: selectedPreset.preset) + let sessionLocale = selectedLocale + let session = SpeechSession(locale: sessionLocale, preset: selectedPreset.preset) speechSession = session observeStatus(from: session) observeAudioInput(from: session) @@ -77,12 +78,12 @@ class TranscriptionManager { for try await result in session.startTranscribing() { self.handleTranscriptionResult(result) } - self.finishSession() + self.finishSession(locale: sessionLocale) } catch is CancellationError { self.cleanupSession() } catch { self.error = error.localizedDescription - self.finishSession() + self.finishSession(locale: sessionLocale) } } } @@ -184,13 +185,13 @@ class TranscriptionManager { transcriptionHistory.removeAll { $0.id == record.id } } - private func finishSession() { + private func finishSession(locale: Locale) { let transcript = String(finalizedText.characters) if !transcript.isEmpty { let record = TranscriptionRecord( id: UUID(), text: transcript, - locale: selectedLocale, + locale: locale, timestamp: Date(), alternatives: [], timeRange: currentTimeRange diff --git a/README.md b/README.md index 485fb78..b80466a 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ This project would not have been possible without Apple's excellent sample code. ## Quick Start +The examples below use the AuralKit 3.0 API. See the [latest release](https://github.com/rryam/AuralKit/releases/latest) for documentation matching the published package. + ```swift import AuralKit diff --git a/Sources/AuralKit/SpeechSession+Audio.swift b/Sources/AuralKit/SpeechSession+Audio.swift index f9e5766..1dc0c7b 100644 --- a/Sources/AuralKit/SpeechSession+Audio.swift +++ b/Sources/AuralKit/SpeechSession+Audio.swift @@ -218,7 +218,7 @@ extension SpeechSession { } private func handleInterruptionEnded(options: AVAudioSession.InterruptionOptions) async { - guard shouldResumeAfterInterruption else { return } + guard shouldResumeAfterInterruption, status == .paused else { return } shouldResumeAfterInterruption = false let generation = sessionGeneration @@ -230,7 +230,6 @@ extension SpeechSession { return } - guard status == .paused else { return } do { try setupAudioSession() try startAudioStreaming() diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index d680649..de6aac2 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -353,7 +353,9 @@ extension SpeechSession { func finishFileInput(generation: Int) async throws { try Task.checkCancellation() guard generation == sessionGeneration else { throw CancellationError() } - try await finishAnalyzerInput() + if try await !finishAnalyzerInput() { + await finishWithoutInput(generation: generation) + } } func reportFileProgress( diff --git a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift index aa27fd6..0f28e52 100644 --- a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift @@ -87,7 +87,7 @@ extension SpeechSession { if let lastAudioTime { try await analyzer.finalizeAndFinish(through: lastAudioTime) } else { - await analyzer.cancelAndFinishNow() + await self?.finishWithoutInput(generation: generation) } } catch is CancellationError { // Cancellation is expected during explicit cleanup. diff --git a/Sources/AuralKit/SpeechSession+NativeFileInput.swift b/Sources/AuralKit/SpeechSession+NativeFileInput.swift index dbc0eeb..a8d5c60 100644 --- a/Sources/AuralKit/SpeechSession+NativeFileInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeFileInput.swift @@ -36,7 +36,7 @@ extension SpeechSession { if let lastAudioTime { try await analyzer.finalizeAndFinish(through: lastAudioTime) } else { - await analyzer.cancelAndFinishNow() + await finishWithoutInput(generation: generation) } return !Task.isCancelled diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index a110000..302ea72 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -216,6 +216,10 @@ extension SpeechSession { await endTranscription(error: error, generation: generation, cancelRecognizer: error != nil) } + func finishWithoutInput(generation: Int) async { + await endTranscription(error: nil, generation: generation) + } + func finishTranscribing(generation: Int, sourceEnded: Bool = false) async { guard generation == sessionGeneration else { return } if let terminationTask { @@ -246,7 +250,7 @@ extension SpeechSession { private func finishLiveTranscription( results: Task, - screenStop: Task?, + screenStop: Task?, generation: Int ) async { guard generation == sessionGeneration else { return } @@ -261,15 +265,17 @@ extension SpeechSession { nativeCaptureSession = nil await nativeCaptureAnalysisTask.value } else { - await screenStop?.value - guard generation == sessionGeneration else { return } - if let terminationTask { - await terminationTask.value - return - } - guard continuation != nil else { return } do { - try await finishAnalyzerInput() + try await screenStop?.value + guard generation == sessionGeneration else { return } + if let terminationTask { + await terminationTask.value + return + } + guard continuation != nil else { return } + if try await !finishAnalyzerInput() { + await finishWithoutInput(generation: generation) + } } catch { await endTranscription(error: error, generation: generation) return @@ -319,7 +325,7 @@ extension SpeechSession { /// session. func cleanup( cancelRecognizer: Bool, - screenStop: Task? = nil, + screenStop: Task? = nil, generation: Int ) async { guard generation == sessionGeneration else { return } @@ -356,7 +362,7 @@ extension SpeechSession { #endif let detached = detachTranscriberState() await cleanUpDetachedTranscriberState(detached, cancelAnalyzer: cancelRecognizer) - await screenStop?.value + _ = await screenStop?.result if screenCaptureStopTask?.generation == generation { screenCaptureStopTask = nil } guard generation == sessionGeneration else { return } diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 5e3ccab..aa19507 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -205,7 +205,7 @@ extension SpeechSession { setStatus(.paused) } - func beginStoppingScreenCapture() -> Task? { + func beginStoppingScreenCapture() -> Task? { let generation = sessionGeneration if let pending = screenCaptureStopTask, pending.generation == generation { return pending.task @@ -347,7 +347,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } @MainActor - func stop() -> Task { + func stop() -> Task { stopped = true let operation = transitions.stop() dismissPicker(self) @@ -357,6 +357,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD try await operation.value } catch { audio.discard() + throw error } } } @@ -519,7 +520,7 @@ public extension SpeechSession { extension SpeechSession { func pauseScreenCaptureStreamingIfNeeded(generation: Int) async {} - func beginStoppingScreenCapture() -> Task? { + func beginStoppingScreenCapture() -> Task? { screenCaptureInputProvider = nil return nil } diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index a2de988..22723d9 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -1,5 +1,6 @@ import Foundation import AVFoundation +import CoreMedia import Speech // SpeechDetector gained native SpeechModule and Sendable conformances in Xcode 26.2. @@ -234,8 +235,9 @@ extension SpeechSession { try await prepareAnalyzerForStartIfNeeded(in: format) try Task.checkCancellation() - try await analyzer.start(inputSequence: inputSequence) - try Task.checkCancellation() + analyzerInputTask = Task { + try await analyzer.analyzeSequence(inputSequence) + } if Self.shouldLog(.info) { Self.logger.info("Analyzer started") } @@ -258,9 +260,13 @@ extension SpeechSession { inputBuilder.yield(input) } - func finishAnalyzerInput() async throws { + func finishAnalyzerInput() async throws -> Bool { inputBuilder?.finish() - try await analyzer?.finalizeAndFinishThroughEndOfInput() + guard let analyzer, let analyzerInputTask else { return true } + guard let endTime = try await analyzerInputTask.value else { return false } + try Task.checkCancellation() + try await analyzer.finalizeAndFinish(through: endTime) + return true } /// State captured by `detachTranscriberState()` for asynchronous cleanup. @@ -279,6 +285,8 @@ extension SpeechSession { if Self.shouldLog(.debug) { Self.logger.debug("Stopping transcriber and cleaning up") } + analyzerInputTask?.cancel() + analyzerInputTask = nil let detached = DetachedTranscriberState( inputBuilder: inputBuilder, analyzer: analyzer, vocabularyArtifacts: activeCustomVocabularyArtifacts diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 4310d2f..a02d504 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -1,5 +1,6 @@ import Foundation import AVFoundation +import CoreMedia import Speech // MARK: - SpeechSession @@ -66,6 +67,7 @@ public final class SpeechSession { var dictationTranscriber: DictationTranscriber? var speechDetector: SpeechDetector? var analyzer: SpeechAnalyzer? + var analyzerInputTask: Task? var activeModules: [any SpeechModule]? var inputSequence: AsyncStream? var inputBuilder: AsyncStream.Continuation? @@ -73,7 +75,7 @@ public final class SpeechSession { var nativeCaptureSession: AVCaptureSession? var nativeCaptureAnalysisTask: Task? var screenCaptureInputProvider: AnyObject? - var screenCaptureStopTask: (generation: Int, task: Task)? + var screenCaptureStopTask: (generation: Int, task: Task)? var voiceActivationConfiguration: VoiceActivationConfiguration? var customVocabularyDescriptor: CustomVocabulary? var customVocabularyConfiguration: SFSpeechLanguageModel.Configuration? @@ -353,16 +355,14 @@ public final class SpeechSession { /// End live capture and deliver final results for audio already queued for analysis. /// - /// Keep consuming the result stream until it completes. For an active file transcription, this - /// waits for the file to finish naturally. During preparation, it closes the stream without - /// starting capture. The result stream reports any finalization error. + /// Keep consuming the stream for final results and errors. Finish waits for active file + /// transcription to reach EOF and closes a preparing session without starting capture. public func finishTranscribing() async { await finishTranscribing(generation: sessionGeneration) } - /// Abort the current run without finalizing pending audio. - /// - /// The result stream ends with `CancellationError`. Results already yielded may still be read. + /// Abort without finalizing pending audio. The result stream ends with `CancellationError`. + /// Results already yielded may still be read. public func cancelTranscribing() async { await endTranscription(error: CancellationError(), generation: sessionGeneration, requestedByCaller: true) } diff --git a/Tests/AuralKitTests/ScreenCaptureFinishTests.swift b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift new file mode 100644 index 0000000..cfb8a31 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift @@ -0,0 +1,127 @@ +#if canImport(ScreenCaptureKit) +import AVFoundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Finishing screen transcription") +struct ScreenCaptureFinishTests { + @Test("Finish drains screen input unless Cancel supersedes it", arguments: [false, true]) + @MainActor + func finishDrainsScreenSource(cancel: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + let (inputs, inputBuilder) = AsyncStream.makeStream() + runtime.session.inputBuilder = inputBuilder + let (results, resultContinuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(resultContinuation) + let generation = runtime.session.sessionGeneration + let resultsTask = Task { + for await _ in inputs {} + await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) + } + defer { resultsTask.cancel() } + runtime.session.recognizerTask = resultsTask + let finish = fixture.track(Task { await runtime.session.finishTranscribing() }) + try await stopEntered.wait() + #expect(runtime.session.status == .stopping) + let input = try makeAnalyzerInput() + if case .terminated = inputBuilder.yield(input) { + Issue.record("The input stream closed before the screen source stopped") + } + if cancel { + let cancelTask = fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.session.inputBuilder == nil } + switch inputBuilder.yield(input) { + case .terminated: break + default: Issue.record("Cancel left the input stream open") + } + stopRelease.open() + await cancelTask.value + await #expect(throws: CancellationError.self) { + for try await _ in results {} + } + } else { + stopRelease.open() + var iterator = results.makeAsyncIterator() + let result = try await iterator.next() + #expect(result == nil) + } + await finish.value + #expect(runtime.session.status == .idle) + } + } + + @Test("Finish reports a native screen stop failure") + @MainActor + func finishReportsScreenStopFailure() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + source.stopError = CaptureFixtureError.startFailed + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + runtime.session.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + + await runtime.session.finishTranscribing() + + await #expect(throws: CaptureFixtureError.self) { + for try await _ in results {} + } + #expect(runtime.session.status == .idle) + } + } + + @Test("Cancel wins while the successful screen completion still owns cleanup") + @MainActor + func cancelDuringTerminalScreenCleanup() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + let generation = runtime.session.sessionGeneration + let completed = fixture.track(Task { + await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) + }) + try await stopEntered.wait() + let cancel = fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.session.cancellationRequested } + stopRelease.open() + await cancel.value + await completed.value + + await #expect(throws: CancellationError.self) { + for try await _ in results {} + } + #expect(source.stops == 1) + #expect(runtime.session.status == .idle) + } + } + + private func makeAnalyzerInput() throws -> AnalyzerInput { + let format = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let pcm = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 160)) + pcm.frameLength = 160 + pcm.int16ChannelData?.pointee.initialize(repeating: 0, count: 160) + return AnalyzerInput(buffer: pcm) + } +} +#endif diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index 5e838a0..314c5a3 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -91,102 +91,6 @@ struct ScreenCaptureTransitionTests { } } - @Test("Finish drains screen input unless Cancel supersedes it", arguments: [false, true]) - @MainActor - func finishDrainsScreenSource(cancel: Bool) async throws { - guard #available(iOS 27.0, macOS 26.0, *) else { return } - try await withCaptureFixture { fixture in - let runtime = try CaptureSessionFixture(fixture) - let source = ControlledCaptureStream() - await fixture.track(runtime.provider.selectStream { source }).value - - let stopEntered = fixture.gate(), stopRelease = fixture.gate() - source.stopEntered = stopEntered - source.stopRelease = stopRelease - let (inputs, inputBuilder) = AsyncStream.makeStream() - runtime.session.inputBuilder = inputBuilder - let (results, resultContinuation) = AsyncThrowingStream.makeStream() - runtime.session.continuation = .speech(resultContinuation) - let generation = runtime.session.sessionGeneration - let resultsTask = Task { - for await _ in inputs {} - await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) - } - defer { resultsTask.cancel() } - runtime.session.recognizerTask = resultsTask - let finish = fixture.track(Task { await runtime.session.finishTranscribing() }) - try await stopEntered.wait() - #expect(runtime.session.status == .stopping) - let input = try makeAnalyzerInput() - if case .terminated = inputBuilder.yield(input) { - Issue.record("The input stream closed before the screen source stopped") - } - if cancel { - let cancelTask = fixture.track(Task { await runtime.session.cancelTranscribing() }) - try await waitForCaptureState { runtime.session.inputBuilder == nil } - switch inputBuilder.yield(input) { - case .terminated: break - default: Issue.record("Cancel left the input stream open") - } - stopRelease.open() - await cancelTask.value - await #expect(throws: CancellationError.self) { - for try await _ in results {} - } - } else { - stopRelease.open() - var iterator = results.makeAsyncIterator() - let result = try await iterator.next() - #expect(result == nil) - } - await finish.value - #expect(runtime.session.status == .idle) - } - } - - @Test("Cancel wins while the successful screen completion still owns cleanup") - @MainActor - func cancelDuringTerminalScreenCleanup() async throws { - guard #available(iOS 27.0, macOS 26.0, *) else { return } - try await withCaptureFixture { fixture in - let runtime = try CaptureSessionFixture(fixture) - let source = ControlledCaptureStream() - await fixture.track(runtime.provider.selectStream { source }).value - let stopEntered = fixture.gate(), stopRelease = fixture.gate() - source.stopEntered = stopEntered - source.stopRelease = stopRelease - - let (results, continuation) = AsyncThrowingStream.makeStream() - runtime.session.continuation = .speech(continuation) - let generation = runtime.session.sessionGeneration - let completed = fixture.track(Task { - await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) - }) - try await stopEntered.wait() - let cancel = fixture.track(Task { await runtime.session.cancelTranscribing() }) - try await waitForCaptureState { runtime.session.cancellationRequested } - stopRelease.open() - await cancel.value - await completed.value - - await #expect(throws: CancellationError.self) { - for try await _ in results {} - } - #expect(source.stops == 1) - #expect(runtime.session.status == .idle) - } - } - - private func makeAnalyzerInput() throws -> AnalyzerInput { - let format = try #require(AVAudioFormat( - commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true - )) - let pcm = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 160)) - pcm.frameLength = 160 - pcm.int16ChannelData?.pointee.initialize(repeating: 0, count: 160) - return AnalyzerInput(buffer: pcm) - } - @Test("Concurrent public stops join a replacement start and its compensating stop") @MainActor func stopDuringReplacementStart() async throws { diff --git a/Tests/AuralKitTests/SessionLifecycleTests.swift b/Tests/AuralKitTests/SessionLifecycleTests.swift index fbce288..5751711 100644 --- a/Tests/AuralKitTests/SessionLifecycleTests.swift +++ b/Tests/AuralKitTests/SessionLifecycleTests.swift @@ -164,6 +164,30 @@ struct SpeechSessionLifecycleTests { #expect(session.continuation == nil) } + @Test("Finish closes a live result stream with no analyzer input") + @MainActor + func finishEmptyLiveTranscription() async throws { + let session = SpeechSession() + let (inputs, inputBuilder) = AsyncStream.makeStream() + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + let analyzer = SpeechAnalyzer(modules: []) + session.inputBuilder = inputBuilder + session.analyzer = analyzer + session.analyzerInputTask = Task { try await analyzer.analyzeSequence(inputs) } + session.continuation = .speech(resultBuilder) + session.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + session.streamingMode = .liveMicrophone + session.setStatus(.transcribing) + + try await awaitResult(timeout: 3) { + async let finish: Void = session.finishTranscribing() + for try await _ in results { Issue.record("Expected no results") } + await finish + } + #expect(session.status == .idle) + #expect(session.recognizerTask == nil) + } + /// Pausing is only meaningful for live capture; during file transcription it must be /// refused (previously, resuming a "paused" file session started the microphone). @Test("Pause is refused during file transcription") From fc141556b9ea78ece3c1bfd654e44273e8444eed Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:31:29 +0530 Subject: [PATCH 06/10] Use final result times in transcript history --- Aural/TranscriptionManager.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Aural/TranscriptionManager.swift b/Aural/TranscriptionManager.swift index 18bed85..d269138 100644 --- a/Aural/TranscriptionManager.swift +++ b/Aural/TranscriptionManager.swift @@ -188,13 +188,19 @@ class TranscriptionManager { private func finishSession(locale: Locale) { let transcript = String(finalizedText.characters) if !transcript.isEmpty { + let ranges = finalizedText.runs.compactMap(\.audioTimeRange) + let timeRange = if let first = ranges.first, let last = ranges.last { + "\(formatTime(first.start)) - \(formatTime(last.end))" + } else { + "" + } let record = TranscriptionRecord( id: UUID(), text: transcript, locale: locale, timestamp: Date(), alternatives: [], - timeRange: currentTimeRange + timeRange: timeRange ) transcriptionHistory.insert(record, at: 0) } From b84c3364f21781eaf3cc1f6d22fb0609784a1f05 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:34:01 +0530 Subject: [PATCH 07/10] Report a screen audio drain failure through Finish --- Sources/AuralKit/SpeechSession+ScreenCapture.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 1bff22e..381af1e 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -364,6 +364,9 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD try await operation.value } catch { audio.discard() + if let drainFailure = error as? ScreenCaptureDrainFailure { + throw SpeechSessionError.screenCaptureFailed(drainFailure.underlyingError) + } throw error } } From 1fc75dab14b951d0618ae519ece10ccf00b506e9 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:45:48 +0530 Subject: [PATCH 08/10] Preserve terminal capture and analyzer failures --- .../AuralKit/ScreenCaptureTransitions.swift | 20 ++++++++-- .../AuralKit/SpeechSession+Transcriber.swift | 18 ++++++++- .../ScreenCaptureFinishTests.swift | 40 +++++++++++++++++++ .../AuralKitTests/SessionLifecycleTests.swift | 24 +++++++++++ 4 files changed, 98 insertions(+), 4 deletions(-) diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index de1b6ab..268fbfd 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -34,6 +34,8 @@ final class ScreenCaptureTransitions { private var tail: Task? private var terminalFailure: TerminalFailure? private var drainFailure: ScreenCaptureDrainFailure? + private var explicitStopPending = false + private var explicitStopFailure: Error? // Synchronous admission returns the owned handle before any capture call can suspend. func replace(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) -> Task { @@ -83,6 +85,9 @@ final class ScreenCaptureTransitions { guard stream === expectedStream else { return false } terminatedStream = ObjectIdentifier(expectedStream) isRunning = false + if explicitStopPending, streamRevision == revision, let error { + explicitStopFailure = explicitStopFailure ?? error + } guard isCurrent(expectedStream) else { return false } if let error { terminalFailure = TerminalFailure(control: controlRevision, error: error, operation: tail) } controlRevision = UUID() @@ -140,10 +145,19 @@ final class ScreenCaptureTransitions { func stop() -> Task { controlRevision = UUID() desiredState = .stopped + explicitStopPending = true return enqueue { - defer { self.stream = nil } - try await self.stopCurrent() - if let drainFailure = self.drainFailure { throw drainFailure } + defer { + self.stream = nil + self.explicitStopPending = false + self.explicitStopFailure = nil + } + do { + try await self.stopCurrent() + } catch { + throw self.explicitStopFailure ?? error + } + if let error = self.explicitStopFailure ?? self.drainFailure { throw error } } } diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index 22723d9..81eb1d5 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -235,7 +235,7 @@ extension SpeechSession { try await prepareAnalyzerForStartIfNeeded(in: format) try Task.checkCancellation() - analyzerInputTask = Task { + startAnalyzingInput(generation: sessionGeneration) { try await analyzer.analyzeSequence(inputSequence) } if Self.shouldLog(.info) { @@ -245,6 +245,22 @@ extension SpeechSession { startSpeechDetectorMonitoringIfNeeded() } + func startAnalyzingInput( + generation: Int, + analyze: @escaping @MainActor () async throws -> CMTime? + ) { + analyzerInputTask = Task { [weak self] in + do { + return try await analyze() + } catch { + if !Task.isCancelled { + await self?.endTranscription(error: error, generation: generation) + } + throw error + } + } + } + func processAudioBuffer(_ buffer: SendablePCMBuffer, generation: Int) async throws { try Task.checkCancellation() guard generation == sessionGeneration else { throw CancellationError() } diff --git a/Tests/AuralKitTests/ScreenCaptureFinishTests.swift b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift index cfb8a31..2d39739 100644 --- a/Tests/AuralKitTests/ScreenCaptureFinishTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift @@ -81,6 +81,46 @@ struct ScreenCaptureFinishTests { } } + @Test("A delegate failure during native stop reaches Finish unless Cancel wins", arguments: [false, true]) + @MainActor + func delegateErrorDuringFinish(cancel: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + source.stopError = CaptureFixtureError.deadline + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + runtime.session.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + + let finish = fixture.track(Task { await runtime.session.finishTranscribing() }) + try await stopEntered.wait() + runtime.provider.streamDidStop(source, error: CaptureFixtureError.startFailed) + if cancel { + fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.session.cancellationRequested } + } + stopRelease.open() + await finish.value + + do { + for try await _ in results {} + Issue.record("Expected terminal failure") + } catch is CancellationError { + #expect(cancel) + } catch SpeechSessionError.screenCaptureFailed(let underlyingError) { + #expect(!cancel) + #expect(underlyingError as? CaptureFixtureError == .startFailed) + } + #expect(source.stops == 1) + #expect(runtime.session.status == .idle) + } + } + @Test("Cancel wins while the successful screen completion still owns cleanup") @MainActor func cancelDuringTerminalScreenCleanup() async throws { diff --git a/Tests/AuralKitTests/SessionLifecycleTests.swift b/Tests/AuralKitTests/SessionLifecycleTests.swift index 5751711..b30fe30 100644 --- a/Tests/AuralKitTests/SessionLifecycleTests.swift +++ b/Tests/AuralKitTests/SessionLifecycleTests.swift @@ -188,6 +188,30 @@ struct SpeechSessionLifecycleTests { #expect(session.recognizerTask == nil) } + @Test("Input analysis failure closes results before Finish is called") + @MainActor + func inputAnalysisFailureClosesResults() async throws { + let session = SpeechSession() + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + session.continuation = .speech(resultBuilder) + session.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + session.streamingMode = .liveMicrophone + session.setStatus(.transcribing) + + session.startAnalyzingInput(generation: session.sessionGeneration) { + throw SpeechSessionError.invalidAudioDataType + } + + do { + try await awaitResult(timeout: 3) { + for try await _ in results { Issue.record("Expected no results") } + } + Issue.record("Expected input analysis to fail") + } catch SpeechSessionError.invalidAudioDataType {} + #expect(session.status == .idle) + #expect(session.recognizerTask == nil) + } + /// Pausing is only meaningful for live capture; during file transcription it must be /// refused (previously, resuming a "paused" file session started the microphone). @Test("Pause is refused during file transcription") From 67fcb497cf1f88d64af1b73d79feb11e9e8820dc Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:49:15 +0530 Subject: [PATCH 09/10] Retire picker setup when its source finishes --- README.md | 4 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 5 ++ .../ScreenCaptureFinishTests.swift | 50 +++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b80466a..a722c59 100644 --- a/README.md +++ b/README.md @@ -98,11 +98,11 @@ Add AuralKit to your project through Xcode: 2. Enter: `https://github.com/rryam/AuralKit` 3. Click Add Package -Or add it to your `Package.swift`: +Once 3.0 is published, select 3.0.0 in Xcode or add this dependency to your `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/rryam/AuralKit", from: "2.1.1") + .package(url: "https://github.com/rryam/AuralKit", from: "3.0.0") ] ``` diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 302ea72..e6b772e 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -204,6 +204,7 @@ extension SpeechSession { func finishFailedPipelineSetup(_ error: Error, generation: Int) async { guard generation == sessionGeneration, terminationTask == nil else { return } pipelineTask = nil + guard finishTask == nil || !Task.isCancelled else { return } await finishWithStartupError(error, generation: generation) } @@ -239,6 +240,10 @@ extension SpeechSession { return } + if status == .preparing { + // Picker teardown can resume its pending selection with a cancellation error. + pipelineTask?.cancel() + } prepareForStop() let screenStop = beginStoppingScreenCapture() let task = Task { diff --git a/Tests/AuralKitTests/ScreenCaptureFinishTests.swift b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift index 2d39739..f5b0ff9 100644 --- a/Tests/AuralKitTests/ScreenCaptureFinishTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift @@ -154,6 +154,56 @@ struct ScreenCaptureFinishTests { } } + @Test("A source ending during picker setup finishes without a selection cancellation error") + @MainActor + func sourceEndedDuringSetup() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + runtime.session.streamingMode = .inactive + runtime.session.setStatus(.preparing) + let generation = runtime.session.sessionGeneration + let (inputs, inputBuilder) = AsyncStream.makeStream() + runtime.session.inputBuilder = inputBuilder + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(resultBuilder) + runtime.session.recognizerTask = fixture.track(Task { + for await _ in inputs {} + await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) + }) + + let pickerError = fixture.gate(), reported = fixture.gate() + runtime.session.pipelineTask = fixture.track(Task { + await fixtureWaitForPickerError(pickerError) + await runtime.session.finishFailedPipelineSetup( + SpeechSessionError.screenCaptureSelectionCancelled, generation: generation + ) + reported.open() + }) + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + let finish = fixture.track(Task { + await runtime.session.finishTranscribing(generation: generation, sourceEnded: true) + }) + try await stopEntered.wait() + pickerError.open() + try await reported.wait() + stopRelease.open() + await finish.value + + var iterator = results.makeAsyncIterator() + #expect(try await iterator.next() == nil) + } + } + + @MainActor + private func fixtureWaitForPickerError(_ gate: CaptureGate) async { + await Task { try? await gate.wait() }.value + } + private func makeAnalyzerInput() throws -> AnalyzerInput { let format = try #require(AVAudioFormat( commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true From dd19eae7e673093942c6590b900f6154ac6c2b14 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 18:48:10 +0530 Subject: [PATCH 10/10] Preserve screen stop errors at delegate ingress --- .../SpeechSession+ScreenCapture.swift | 70 +++++++++++++++++-- .../ScreenCaptureFinishTests.swift | 20 ++++++ 2 files changed, 83 insertions(+), 7 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 381af1e..012fcac 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -3,6 +3,7 @@ import CoreMedia import Foundation import OSLog import Speech +import Synchronization // swiftlint:disable file_length @@ -220,20 +221,66 @@ extension SpeechSession { } } +// ScreenCaptureKit can call its delegate before the asynchronous stop returns while the +// delegate's main-actor work is still queued. Keep the ingress error until stop observes it. +final class ScreenCaptureStopErrors: Sendable { + private struct State { + var streamID: ObjectIdentifier? + var error: Error? + } + + private let state = Mutex(State()) + + func start(_ streamID: ObjectIdentifier) { + state.withLock { $0 = State(streamID: streamID) } + } + + func record(_ error: Error, for streamID: ObjectIdentifier) { + state.withLock { + guard $0.streamID == streamID, $0.error == nil else { return } + $0.error = error + } + } + + @MainActor + func stop(_ streamID: ObjectIdentifier, nativeStop: () async throws -> Void) async throws { + let nativeError: Error? + do { + try await nativeStop() + nativeError = nil + } catch { + nativeError = error + } + let delegateError = state.withLock { + guard $0.streamID == streamID else { return nil as Error? } + let error = $0.error + if error != nil || nativeError == nil { $0 = State() } + return error + } + if let delegateError { + throw SpeechSessionError.screenCaptureFailed(delegateError) + } + if let nativeError { throw nativeError } + } +} + @available(iOS 27.0, macOS 14.0, *) @MainActor private final class NativeScreenCaptureStream: ScreenCaptureStream { let stream: SCStream private let audio: ScreenCaptureAudioProcessor + private let stopErrors: ScreenCaptureStopErrors - init(stream: SCStream, audio: ScreenCaptureAudioProcessor) { + init(stream: SCStream, audio: ScreenCaptureAudioProcessor, stopErrors: ScreenCaptureStopErrors) { self.stream = stream self.audio = audio + self.stopErrors = stopErrors } func startCapture() async throws { defer { logCaptureState(after: "startCapture") } let id = ObjectIdentifier(stream) + stopErrors.start(id) audio.start(id) do { try await stream.startCapture() @@ -245,8 +292,9 @@ private final class NativeScreenCaptureStream: ScreenCaptureStream { func stopCapture() async throws { defer { logCaptureState(after: "stopCapture") } - try await stream.stopCapture() - if let error = audio.drain(ObjectIdentifier(stream)) { + let id = ObjectIdentifier(stream) + try await stopErrors.stop(id) { try await stream.stopCapture() } + if let error = audio.drain(id) { throw ScreenCaptureDrainFailure(underlyingError: error) } } @@ -277,6 +325,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD private let targetFormat: AVAudioFormat private let onTermination: @Sendable (Error?) -> Task private let audio: ScreenCaptureAudioProcessor + private let stopErrors = ScreenCaptureStopErrors() @MainActor private let transitions: ScreenCaptureTransitions @MainActor private var terminalCleanupTask: Task? @@ -399,7 +448,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD configuration.height = 2 let capture = SCStream(filter: selectedFilter, configuration: configuration, delegate: self) try capture.addStreamOutput(self, type: .audio, sampleHandlerQueue: audio.queue) - return NativeScreenCaptureStream(stream: capture, audio: audio) + return NativeScreenCaptureStream(stream: capture, audio: audio, stopErrors: stopErrors) } } } @@ -421,6 +470,9 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } func stream(_ stream: SCStream, didStopWithError error: any Error) { + if !Self.isUserStop(error) { + stopErrors.record(error, for: ObjectIdentifier(stream)) + } Task { @MainActor [weak self] in guard let self, let current = self.transitions.stream as? NativeScreenCaptureStream, current.stream === stream else { return } @@ -493,9 +545,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD @MainActor func streamDidStop(_ stream: any ScreenCaptureStream, error: Error) { - let nativeError = error as NSError - let userStopped = nativeError.domain == SCStreamError.errorDomain - && nativeError.code == SCStreamError.Code.userStopped.rawValue + let userStopped = Self.isUserStop(error) var failure: Error? = userStopped ? nil : SpeechSessionError.screenCaptureFailed(error) if let nativeStream = stream as? NativeScreenCaptureStream { let id = ObjectIdentifier(nativeStream.stream) @@ -510,6 +560,12 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD stopped = true terminalCleanupTask = onTermination(failure) } + + private static func isUserStop(_ error: Error) -> Bool { + let nativeError = error as NSError + return nativeError.domain == SCStreamError.errorDomain + && nativeError.code == SCStreamError.Code.userStopped.rawValue + } } #else public extension SpeechSession { diff --git a/Tests/AuralKitTests/ScreenCaptureFinishTests.swift b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift index f5b0ff9..f670bc9 100644 --- a/Tests/AuralKitTests/ScreenCaptureFinishTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift @@ -1,5 +1,6 @@ #if canImport(ScreenCaptureKit) import AVFoundation +import Foundation import Speech import Testing @testable import AuralKit @@ -204,6 +205,25 @@ struct ScreenCaptureFinishTests { await Task { try? await gate.wait() }.value } + @Test("Native stop sees delegate ingress before its main actor hop", arguments: [false, true]) + @MainActor + func nativeStopSeesDelegateIngress(nativeThrows: Bool) async throws { + let active = NSObject(), stale = NSObject() + let activeID = ObjectIdentifier(active) + let errors = ScreenCaptureStopErrors() + errors.start(activeID) + errors.record(CaptureFixtureError.deadline, for: ObjectIdentifier(stale)) + do { + try await errors.stop(activeID) { + errors.record(CaptureFixtureError.startFailed, for: activeID) + if nativeThrows { throw CaptureFixtureError.deadline } + } + Issue.record("Expected the delegate failure") + } catch SpeechSessionError.screenCaptureFailed(let underlyingError) { + #expect(underlyingError as? CaptureFixtureError == .startFailed) + } + } + private func makeAnalyzerInput() throws -> AnalyzerInput { let format = try #require(AVAudioFormat( commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true