From 145d0af484445e0d62ddb878a47d85c9c99cba5b Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 11:16:41 -0500 Subject: [PATCH 01/70] Cancel and join actual tasks in timeout fixtures --- Tests/AuralKitTests/AuralKitTests.swift | 46 +++------ Tests/AuralKitTests/TestTimeoutHelpers.swift | 37 ++++++- .../TestTimeoutHelpersTests.swift | 99 +++++++++++++++++++ 3 files changed, 151 insertions(+), 31 deletions(-) create mode 100644 Tests/AuralKitTests/TestTimeoutHelpersTests.swift diff --git a/Tests/AuralKitTests/AuralKitTests.swift b/Tests/AuralKitTests/AuralKitTests.swift index 07a9833..809d648 100644 --- a/Tests/AuralKitTests/AuralKitTests.swift +++ b/Tests/AuralKitTests/AuralKitTests.swift @@ -91,21 +91,14 @@ struct SpeechSessionStateTests { let nextB = Task { await probeB.next() } - defer { - nextA.cancel() - nextB.cancel() - } - - session.setStatus(.preparing) + try await withOwnedTasks([nextA, nextB]) { + session.setStatus(.preparing) - let valueA = try await awaitResult { - await nextA.value - } - let valueB = try await awaitResult { - await nextB.value + let valueA = try await awaitResult(task: nextA) + let valueB = try await awaitResult(task: nextB) + #expect(valueA == .some(.preparing)) + #expect(valueB == .some(.preparing)) } - #expect(valueA == .some(.preparing)) - #expect(valueB == .some(.preparing)) } } @@ -162,24 +155,17 @@ struct SpeechSessionAudioInputStreamTests { let valueB = Task { await probeB.next() } - defer { - valueA.cancel() - valueB.cancel() - } - - await Task.yield() - session.broadcastAudioInputInfo(nil) - - let firstA = try await awaitResult { - await valueA.value - } - let firstB = try await awaitResult { - await valueB.value + try await withOwnedTasks([valueA, valueB]) { + await Task.yield() + session.broadcastAudioInputInfo(nil) + + let firstA = try await awaitResult(task: valueA) + let firstB = try await awaitResult(task: valueB) + let flattenedA = firstA?.flatMap { $0 } + let flattenedB = firstB?.flatMap { $0 } + #expect(flattenedA == nil) + #expect(flattenedB == nil) } - let flattenedA = firstA?.flatMap { $0 } - let flattenedB = firstB?.flatMap { $0 } - #expect(flattenedA == nil) - #expect(flattenedB == nil) } } diff --git a/Tests/AuralKitTests/TestTimeoutHelpers.swift b/Tests/AuralKitTests/TestTimeoutHelpers.swift index 4d3c1f9..d43c3cf 100644 --- a/Tests/AuralKitTests/TestTimeoutHelpers.swift +++ b/Tests/AuralKitTests/TestTimeoutHelpers.swift @@ -40,11 +40,46 @@ func awaitResult( throw TestTimeoutError.timedOut(seconds: seconds) } + defer { group.cancelAll() } guard let value = try await group.next() else { fatalError("Timeout helper started without any tasks") } - group.cancelAll() return value } } + +// Cancellation must reach the actual task, not just the child awaiting its value. +// The task must cooperate with cancellation; this helper still joins its completion. +@MainActor +func awaitResult( + timeout seconds: TimeInterval = 1.0, + task: Task +) async throws -> T { + try await awaitResult(timeout: seconds) { + try await withTaskCancellationHandler { + let value = await task.value + try Task.checkCancellation() + return value + } onCancel: { + task.cancel() + } + } +} + +@MainActor +func withOwnedTasks( + _ tasks: [Task], + operation: @MainActor () async throws -> Result +) async rethrows -> Result { + do { + let result = try await operation() + for task in tasks { task.cancel() } + for task in tasks { _ = await task.value } + return result + } catch { + for task in tasks { task.cancel() } + for task in tasks { _ = await task.value } + throw error + } +} diff --git a/Tests/AuralKitTests/TestTimeoutHelpersTests.swift b/Tests/AuralKitTests/TestTimeoutHelpersTests.swift new file mode 100644 index 0000000..1b2b163 --- /dev/null +++ b/Tests/AuralKitTests/TestTimeoutHelpersTests.swift @@ -0,0 +1,99 @@ +import Foundation +import Testing + +@Suite("Timeout task ownership") +@MainActor +struct TestTimeoutHelpersTests { + enum Exit: Sendable, CaseIterable { case timeout, cancelledBeforeWait, cancelledDuringWait } + enum FixtureError: Error { case expected } + + @Test("Timeout and cancellation join stream consumers and producers", arguments: Exit.allCases) + func streamTasksAreJoined(exit: Exit) async throws { + let values = AsyncStream.makeStream() + let producerGate = AsyncStream.makeStream() + let ready = AsyncStream.makeStream() + let state = CompletionState() + let producer = Task { @MainActor in + defer { + state.producerFinished = true + values.continuation.finish() + } + ready.continuation.yield(()) + var iterator = producerGate.stream.makeAsyncIterator() + _ = await iterator.next() + return nil + } + let consumer = Task { @MainActor in + defer { state.consumerFinished = true } + ready.continuation.yield(()) + var iterator = values.stream.makeAsyncIterator() + return await iterator.next() + } + try await withOwnedTasks([producer, consumer]) { + // Both tasks have entered their real stream waits before the race begins. + let probe = AsyncStreamProbe(ready.stream) + _ = try await awaitResult { await probe.next() } + _ = try await awaitResult { await probe.next() } + let entered = AsyncStream.makeStream() + let waiter = Task { @MainActor in + entered.continuation.yield(()) + return try await awaitResult(timeout: 0.02, task: consumer) + } + if exit == .cancelledBeforeWait { + // No actor suspension since task creation: cancellation predates entry. + waiter.cancel() + } else if exit == .cancelledDuringWait { + var iterator = entered.stream.makeAsyncIterator() + _ = await iterator.next() + waiter.cancel() + } + do { + _ = try await waiter.value + Issue.record("Expected timeout or cancellation") + } catch is TestTimeoutError { + #expect(exit == .timeout) + } catch is CancellationError { + #expect(exit != .timeout) + } + #expect(state.consumerFinished) + } + #expect(state.producerFinished) + #expect(state.consumerFinished) + producerGate.continuation.finish() + ready.continuation.finish() + } + + @Test("Values and operation errors propagate") + func valuesAndErrors() async throws { + let value = try await awaitResult { 42 } + #expect(value == 42) + let taskValue = try await awaitResult(task: Task { 43 }) + #expect(taskValue == 43) + do { + let _: Int = try await awaitResult { throw FixtureError.expected } + Issue.record("Expected operation error") + } catch FixtureError.expected { } + } + + @Test("Throwing fixture scope cancels and joins its task") + func throwingScopeJoins() async { + let stream = AsyncStream.makeStream() + let state = CompletionState() + let task = Task { @MainActor in + defer { state.consumerFinished = true } + var iterator = stream.stream.makeAsyncIterator() + return await iterator.next() + } + do { + try await withOwnedTasks([task]) { throw FixtureError.expected } + } catch { } + #expect(state.consumerFinished) + stream.continuation.finish() + } +} + +@MainActor +private final class CompletionState { + var producerFinished = false + var consumerFinished = false +} From 177d2084ec11344998f6c7062d0a1b80371a4a6b Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 11:20:40 -0500 Subject: [PATCH 02/70] Own custom vocabulary files per compilation and native consumer --- .../SpeechSession+CustomVocabulary.swift | 60 ++++-- ...ession+CustomVocabularyConfiguration.swift | 48 ++--- .../SpeechSession+NativeCaptureInput.swift | 5 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 13 +- .../AuralKit/SpeechSession+Transcriber.swift | 13 +- Sources/AuralKit/SpeechSession.swift | 3 + Tests/AuralKitTests/AuralKitTests.swift | 3 +- .../CustomVocabularyOwnershipTests.swift | 192 ++++++++++++++++++ 8 files changed, 284 insertions(+), 53 deletions(-) create mode 100644 Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift diff --git a/Sources/AuralKit/SpeechSession+CustomVocabulary.swift b/Sources/AuralKit/SpeechSession+CustomVocabulary.swift index b80a798..4ce9d62 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabulary.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabulary.swift @@ -146,6 +146,22 @@ struct CustomVocabularyCompilation: Sendable { let configuration: SFSpeechLanguageModel.Configuration let cacheKey: String let outputDirectory: URL + let artifacts: CustomVocabularyArtifacts +} + +/// Retained by the configuration and every in-flight native consumer. +final class CustomVocabularyArtifacts: Sendable { + let directory: URL + + init(directory: URL) { self.directory = directory } + + deinit { + do { + try FileManager.default.removeItem(at: directory) + } catch { + logCustomVocabularyError("Failed to retire vocabulary directory.", path: directory.path, error: error) + } + } } protocol CustomVocabularyCompiling: Sendable { @@ -161,22 +177,40 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send let assetURL: URL } - private let fileManager: FileManager + typealias PrepareModel = @Sendable ( + SpeechSession.CustomVocabulary, URL, SFSpeechLanguageModel.Configuration + ) async throws -> Void - init(fileManager: FileManager = .default) { + private let fileManager: FileManager + private let prepareModel: PrepareModel + + init( + fileManager: FileManager = .default, + prepareModel: @escaping PrepareModel = { descriptor, assetURL, configuration in + try await descriptor.makeModelData().export(to: assetURL) + try Task.checkCancellation() + try await SFSpeechLanguageModel.prepareCustomLanguageModel(for: assetURL, configuration: configuration) + } + ) { self.fileManager = fileManager + self.prepareModel = prepareModel } func compile(descriptor: SpeechSession.CustomVocabulary) async throws -> CustomVocabularyCompilation { + try Task.checkCancellation() let cacheKey = try descriptor.stableCacheKey() let paths = try preparePaths(for: cacheKey) + let artifacts = CustomVocabularyArtifacts(directory: paths.outputDirectory) + defer { withExtendedLifetime(artifacts) {} } let configuration = makeConfiguration(for: descriptor, paths: paths) try await exportModelData(descriptor, with: paths, configuration: configuration) + try Task.checkCancellation() return CustomVocabularyCompilation( configuration: configuration, cacheKey: cacheKey, - outputDirectory: paths.outputDirectory + outputDirectory: paths.outputDirectory, + artifacts: artifacts ) } @@ -188,7 +222,7 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send let outputDirectory = baseDirectory .appendingPathComponent("com.auralkit.vocabulary", isDirectory: true) - .appendingPathComponent(cacheKey, isDirectory: true) + .appendingPathComponent("\(cacheKey)-\(UUID().uuidString)", isDirectory: true) if !fileManager.fileExists(atPath: outputDirectory.path) { try fileManager.createDirectory(at: outputDirectory, withIntermediateDirectories: true) @@ -198,11 +232,7 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send let vocabularyURL = outputDirectory.appendingPathComponent("vocabulary.bin") // Use UUID to ensure unique temp file per compilation invocation, preventing races let uniqueID = UUID().uuidString - let assetURL = fileManager.temporaryDirectory - .appendingPathComponent("auralkit-custom-vocabulary-\(uniqueID).bin") - - // Clean up any existing temp file before creating new one - try? fileManager.removeItem(at: assetURL) + let assetURL = outputDirectory.appendingPathComponent("source-\(uniqueID).bin") return CompilationPaths( outputDirectory: outputDirectory, @@ -235,8 +265,6 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send with paths: CompilationPaths, configuration: SFSpeechLanguageModel.Configuration ) async throws { - let modelData = descriptor.makeModelData() - defer { // Best-effort cleanup of temp asset file do { @@ -254,14 +282,8 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send } do { - // Offload heavy I/O work to background to avoid blocking main actor - try await Task.detached(priority: .userInitiated) { - try await modelData.export(to: paths.assetURL) - try await SFSpeechLanguageModel.prepareCustomLanguageModel( - for: paths.assetURL, - configuration: configuration - ) - }.value + // The session already runs the compiler in a detached task and joins it. + try await prepareModel(descriptor, paths.assetURL, configuration) } catch { throw SpeechSessionError.customVocabularyCompilationFailed(error) } diff --git a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift index 78d7997..4d269de 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift @@ -13,7 +13,7 @@ extension SpeechSession { /// - Throws: A `SpeechSessionError` when the session is active, the descriptor locale mismatches, or /// compilation fails. public func configureCustomVocabulary(_ vocabulary: CustomVocabulary?) async throws { - if streamingMode != .inactive { + if streamingMode != .inactive || continuation != nil || pipelineTask != nil || recognizerTask != nil { throw SpeechSessionError.customVocabularyRequiresIdleSession } @@ -35,6 +35,10 @@ extension SpeechSession { throw SpeechSessionError.customVocabularyCompilationFailed(error) } + let requestID = UUID() + customVocabularyRequestID = requestID + try Task.checkCancellation() + if cacheKey == customVocabularyCacheKey, customVocabularyConfiguration != nil { customVocabularyDescriptor = vocabulary @@ -44,27 +48,26 @@ extension SpeechSession { // Offload compilation to background task to avoid blocking main actor UI // Capture compiler before detached task to avoid cross-actor access let compiler = customVocabularyCompiler - let compilation = try await Task.detached(priority: .userInitiated) { + let task = Task.detached(priority: .userInitiated) { try await compiler.compile(descriptor: vocabulary) - }.value - - if let previousDirectory = customVocabularyOutputDirectory, - previousDirectory != compilation.outputDirectory { - do { - try FileManager.default.removeItem(at: previousDirectory) - } catch { - logCustomVocabularyError( - "Failed to delete previous vocabulary directory.", - path: previousDirectory.path, - error: error - ) - } + } + let compilation = try await withTaskCancellationHandler { + try await task.value + } onCancel: { + task.cancel() + } + // Rejected results release their private artifacts after the compiler has joined. + try Task.checkCancellation() + guard customVocabularyRequestID == requestID else { throw CancellationError() } + guard streamingMode == .inactive, continuation == nil, pipelineTask == nil, recognizerTask == nil else { + throw SpeechSessionError.customVocabularyRequiresIdleSession } customVocabularyDescriptor = vocabulary customVocabularyConfiguration = compilation.configuration customVocabularyCacheKey = compilation.cacheKey customVocabularyOutputDirectory = compilation.outputDirectory + customVocabularyArtifacts = compilation.artifacts } /// Start a dictation-backed transcription stream that leverages the currently configured custom vocabulary. @@ -120,18 +123,9 @@ extension SpeechSession { } func clearCustomVocabularyArtifacts(removeDescriptor: Bool) { - if let directory = customVocabularyOutputDirectory { - // Best-effort cleanup of vocabulary directory - do { - try FileManager.default.removeItem(at: directory) - } catch { - logCustomVocabularyError( - "Failed to delete vocabulary directory during cleanup.", - path: directory.path, - error: error - ) - } - } + customVocabularyRequestID = nil + // Dropping the session's owner cannot delete files retained by native consumers. + customVocabularyArtifacts = nil customVocabularyConfiguration = nil customVocabularyCacheKey = nil diff --git a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift index 858f92d..76d063d 100644 --- a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift @@ -61,6 +61,8 @@ extension SpeechSession { guard let modules = activeModules, let analyzer else { throw SpeechSessionError.recognitionStreamSetupFailed } + let vocabularyArtifacts = activeCustomVocabularyArtifacts + defer { withExtendedLifetime(vocabularyArtifacts) {} } guard let captureDevice = AVCaptureDevice.default(for: .audio) else { throw SpeechSessionError.recognitionStreamSetupFailed } @@ -77,7 +79,8 @@ extension SpeechSession { try Task.checkCancellation() let analyzerInputs = provider.analyzerInputs - nativeCaptureAnalysisTask = Task { [weak self, analyzer, analyzerInputs] in + nativeCaptureAnalysisTask = Task { [weak self, analyzer, analyzerInputs, vocabularyArtifacts] in + defer { withExtendedLifetime(vocabularyArtifacts) {} } do { let lastAudioTime = try await analyzer.analyzeSequence(analyzerInputs) if let lastAudioTime { diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 9025f0c..b3838f2 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -156,6 +156,8 @@ extension SpeechSession { contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, generation: Int ) async { + let vocabularyArtifacts = customVocabularyArtifacts + defer { withExtendedLifetime(vocabularyArtifacts) {} } do { if Self.shouldLog(.notice) { Self.logger.notice("Starting dictation pipeline setup") @@ -178,6 +180,7 @@ extension SpeechSession { recognizerTask = createDictationRecognizerTask( transcriber: transcriber, + vocabularyArtifacts: vocabularyArtifacts, streamContinuation: streamContinuation, generation: generation ) @@ -406,26 +409,30 @@ extension SpeechSession { private func createDictationRecognizerTask( transcriber: DictationTranscriber, + vocabularyArtifacts: CustomVocabularyArtifacts?, streamContinuation: AsyncThrowingStream.Continuation, generation: Int ) -> Task { createRecognizerTask( label: "Dictation recognizer task", + vocabularyArtifacts: vocabularyArtifacts, results: transcriber.results, streamContinuation: streamContinuation, generation: generation ) } - private func createRecognizerTask( + func createRecognizerTask( label: String, + vocabularyArtifacts: CustomVocabularyArtifacts? = nil, results: Sequence, streamContinuation: AsyncThrowingStream.Continuation, generation: Int ) -> Task where Sequence: Sendable, Sequence.Element: Sendable { - Task { [weak self] in - guard let self else { return } + Task { [self, vocabularyArtifacts] in + // Retain the session before the first turn so EOF can still retire the analyzer. + defer { withExtendedLifetime(vocabularyArtifacts) {} } do { for try await result in results { diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index e2d5f2e..3db1ac6 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -38,6 +38,8 @@ extension SpeechSession { contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, startAnalyzerImmediately: Bool = true ) async throws -> DictationTranscriber { + let artifacts = customVocabularyArtifacts + defer { withExtendedLifetime(artifacts) {} } if Self.shouldLog(.notice) { Self.logger.notice("Setting up dictation transcriber") } @@ -74,7 +76,7 @@ extension SpeechSession { return transcriber } - private func createDictationTranscriber() throws -> DictationTranscriber { + func createDictationTranscriber() throws -> DictationTranscriber { let basePreset = DictationTranscriber.Preset.progressiveShortDictation var contentHints = basePreset.contentHints var reportingOptions = basePreset.reportingOptions @@ -85,6 +87,7 @@ extension SpeechSession { reportingOptions.insert(.frequentFinalization) } + activeCustomVocabularyArtifacts = customVocabularyArtifacts dictationTranscriber = DictationTranscriber( locale: locale, contentHints: contentHints, @@ -243,6 +246,7 @@ extension SpeechSession { struct DetachedTranscriberState { let inputBuilder: AsyncStream.Continuation? let analyzer: SpeechAnalyzer? + let vocabularyArtifacts: CustomVocabularyArtifacts? } /// Synchronously clear all transcriber-related session state and return the pieces that @@ -254,7 +258,11 @@ extension SpeechSession { if Self.shouldLog(.debug) { Self.logger.debug("Stopping transcriber and cleaning up") } - let detached = DetachedTranscriberState(inputBuilder: inputBuilder, analyzer: analyzer) + let detached = DetachedTranscriberState( + inputBuilder: inputBuilder, analyzer: analyzer, + vocabularyArtifacts: activeCustomVocabularyArtifacts + ) + activeCustomVocabularyArtifacts = nil tearDownSpeechDetectorStream() speechDetector = nil @@ -275,6 +283,7 @@ extension SpeechSession { /// 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 { + defer { withExtendedLifetime(detached.vocabularyArtifacts) {} } detached.inputBuilder?.finish() do { try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 03c211c..85a289a 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -79,6 +79,9 @@ public final class SpeechSession { var customVocabularyConfiguration: SFSpeechLanguageModel.Configuration? var customVocabularyCacheKey: String? var customVocabularyOutputDirectory: URL? + var customVocabularyArtifacts: CustomVocabularyArtifacts? + var activeCustomVocabularyArtifacts: CustomVocabularyArtifacts? + var customVocabularyRequestID: UUID? var activeResultKind: TranscriptionResultKind? // MARK: - Public Observables diff --git a/Tests/AuralKitTests/AuralKitTests.swift b/Tests/AuralKitTests/AuralKitTests.swift index 07a9833..1de3e00 100644 --- a/Tests/AuralKitTests/AuralKitTests.swift +++ b/Tests/AuralKitTests/AuralKitTests.swift @@ -342,7 +342,8 @@ actor MockCustomVocabularyCompiler: CustomVocabularyCompiling { return CustomVocabularyCompilation( configuration: configuration, cacheKey: cacheKey, - outputDirectory: outputDirectory + outputDirectory: outputDirectory, + artifacts: CustomVocabularyArtifacts(directory: outputDirectory) ) } diff --git a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift new file mode 100644 index 0000000..baf5374 --- /dev/null +++ b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift @@ -0,0 +1,192 @@ +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Custom vocabulary artifact ownership") +@MainActor +struct CustomVocabularyOwnershipTests { + private func descriptor(_ version: String = "1") -> SpeechSession.CustomVocabulary { + .init(locale: Locale(identifier: "en_US"), identifier: "ownership-test", version: version, weight: 0.4) + } + + private func session(_ preparation: VocabularyPreparation) -> SpeechSession { + let session = SpeechSession(locale: Locale(identifier: "en_US")) + session.customVocabularyCompiler = CustomVocabularyCompiler { descriptor, asset, configuration in + try await preparation.prepare(descriptor, asset: asset, configuration: configuration) + } + return session + } + + @Test("Equal descriptors have private production outputs and independent retirement") + func twoSessionsRetireIndependently() async throws { + let preparation = VocabularyPreparation() + var first: SpeechSession? = session(preparation) + var second: SpeechSession? = session(preparation) + defer { first = nil; second = nil } + weak var weakFirst = first + weak var weakSecond = second + try await first!.configureCustomVocabulary(descriptor()) + try await second!.configureCustomVocabulary(descriptor()) + let firstDirectory = try #require(first?.customVocabularyOutputDirectory) + let secondDirectory = try #require(second?.customVocabularyOutputDirectory) + #expect(firstDirectory != secondDirectory) + #expect(first?.customVocabularyCacheKey == second?.customVocabularyCacheKey) + #expect(second?.customVocabularyConfiguration?.weight?.doubleValue == 0.4) + try await second!.configureCustomVocabulary(descriptor()) + #expect(second?.customVocabularyOutputDirectory == secondDirectory) + #expect(await preparation.count == 2) + + try await first!.configureCustomVocabulary(nil) + #expect(!FileManager.default.fileExists(atPath: firstDirectory.path)) + try assertFiles(in: secondDirectory) + try await first!.configureCustomVocabulary(descriptor()) + let retired = try #require(first?.customVocabularyOutputDirectory) + try await first!.configureCustomVocabulary(descriptor("replacement")) + let replacement = try #require(first?.customVocabularyOutputDirectory) + #expect(!FileManager.default.fileExists(atPath: retired.path)) + try assertFiles(in: secondDirectory) + first = nil + #expect(weakFirst == nil) + #expect(!FileManager.default.fileExists(atPath: replacement.path)) + try assertFiles(in: secondDirectory) + second = nil + #expect(weakSecond == nil) + #expect(!FileManager.default.fileExists(atPath: secondDirectory.path)) + } + + enum Rejection: Sendable, CaseIterable { case clear, replacement, cancellation } + + @Test("Pending compilation cannot publish after clear, replacement or cancellation", arguments: Rejection.allCases) + func rejectedCompilationRetires(rejection: Rejection) async throws { + let preparation = VocabularyPreparation() + let session = session(preparation) + let request = Task { @MainActor in + try await session.configureCustomVocabulary(descriptor("blocked")) + } + do { + // The collaborator signals only after production paths/configuration and real files exist. + var ready = preparation.ready.stream.makeAsyncIterator() + let rejectedDirectory = try #require(await ready.next()) + switch rejection { + case .clear: try await session.configureCustomVocabulary(nil) + case .replacement: try await session.configureCustomVocabulary(descriptor("replacement")) + case .cancellation: request.cancel() + } + preparation.release.continuation.yield(()) + // Always join the actual request before any throwing assertion or fixture exit. + let result = await request.result + do { + try result.get() + Issue.record("Expected rejection") + } catch is CancellationError { } + #expect(!FileManager.default.fileExists(atPath: rejectedDirectory.path)) + if rejection == .replacement { + let retained = try #require(session.customVocabularyOutputDirectory) + try assertFiles(in: retained) + #expect(session.customVocabularyDescriptor?.version == "replacement") + try await session.configureCustomVocabulary(nil) + #expect(!FileManager.default.fileExists(atPath: retained.path)) + } else { + #expect(session.customVocabularyConfiguration == nil) + } + } catch { + request.cancel() + preparation.release.continuation.finish() + _ = await request.result + throw error + } + } + + @Test("Failed preparation removes partial production output") + func failedCompilationRetires() async throws { + let preparation = VocabularyPreparation() + let session = session(preparation) + do { + try await session.configureCustomVocabulary(descriptor("failure")) + Issue.record("Expected preparation error") + } catch SpeechSessionError.customVocabularyCompilationFailed { } + let failed = try #require(await preparation.directories.first) + #expect(!FileManager.default.fileExists(atPath: failed.path)) + #expect(session.customVocabularyConfiguration == nil) + } + + @Test("Detached transcriber state retains files after session retirement") + func detachedStateRetainsArtifacts() async throws { + let preparation = VocabularyPreparation() + var owner: SpeechSession? = session(preparation) + defer { owner = nil } + try await owner!.configureCustomVocabulary(descriptor()) + let directory = try #require(owner?.customVocabularyOutputDirectory) + // Constructs the real customized module; no asset install or analyzer start. + _ = try owner!.createDictationTranscriber() + var detached: SpeechSession.DetachedTranscriberState? = owner!.detachTranscriberState() + try await owner!.configureCustomVocabulary(nil) + owner = nil + try assertFiles(in: directory) + await SpeechSession().finalizeDetachedTranscriberState(try #require(detached)) + try assertFiles(in: directory) + detached = nil + #expect(!FileManager.default.fileExists(atPath: directory.path)) + } + + @Test("Queued result consumer retains artifacts through terminal cleanup") + func resultConsumerRetainsArtifacts() async throws { + let preparation = VocabularyPreparation() + var owner: SpeechSession? = session(preparation) + defer { owner = nil } + weak var weakOwner = owner + try await owner!.configureCustomVocabulary(descriptor()) + let directory = try #require(owner?.customVocabularyOutputDirectory) + let results = AsyncStream.makeStream() + let output = AsyncThrowingStream.makeStream() + let reader = owner!.createRecognizerTask( + label: "Ownership fixture", + vocabularyArtifacts: owner?.customVocabularyArtifacts, + results: results.stream, + streamContinuation: output.continuation, + generation: owner!.sessionGeneration + ) + // Drop the session's ownership before the queued reader's first actor turn. + owner!.clearCustomVocabularyArtifacts(removeDescriptor: true) + owner = nil + #expect(weakOwner != nil) + #expect(FileManager.default.fileExists(atPath: directory.path)) + results.continuation.finish() + await reader.value + #expect(weakOwner == nil) + #expect(!FileManager.default.fileExists(atPath: directory.path)) + } + + private func assertFiles(in directory: URL) throws { + #expect(try Data(contentsOf: directory.appendingPathComponent("languageModel.bin")) == Data("model".utf8)) + #expect(try Data(contentsOf: directory.appendingPathComponent("vocabulary.bin")) == Data("vocabulary".utf8)) + } +} + +/// Substitutes only Apple export/preparation, keeping production allocation and configuration. +private actor VocabularyPreparation { + enum Failure: Error { case expected } + nonisolated let ready = AsyncStream.makeStream() + nonisolated let release = AsyncStream.makeStream() + private(set) var directories: [URL] = [] + var count: Int { directories.count } + + func prepare( + _ descriptor: SpeechSession.CustomVocabulary, + asset: URL, + configuration: SFSpeechLanguageModel.Configuration + ) async throws { + let directory = configuration.languageModel.deletingLastPathComponent() + directories.append(directory) + try Data("source".utf8).write(to: asset) + try Data("model".utf8).write(to: configuration.languageModel) + try Data("vocabulary".utf8).write(to: #require(configuration.vocabulary)) + if descriptor.version == "failure" { throw Failure.expected } + if descriptor.version == "blocked" { + ready.continuation.yield(directory) + var iterator = release.stream.makeAsyncIterator() + _ = await iterator.next() + } + } +} From dfe875c32decfd056f4d1080aeea53816e43f882 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 11:36:53 -0500 Subject: [PATCH 03/70] Keep speech asset reservations leased across model managers --- Sources/AuralKit/ModelManager.swift | 162 ++++-- .../AuralKit/SpeechAssetReservations.swift | 181 +++++++ .../SpeechAssetReservationTests.swift | 475 ++++++++++++++++++ 3 files changed, 769 insertions(+), 49 deletions(-) create mode 100644 Sources/AuralKit/SpeechAssetReservations.swift create mode 100644 Tests/AuralKitTests/SpeechAssetReservationTests.swift diff --git a/Sources/AuralKit/ModelManager.swift b/Sources/AuralKit/ModelManager.swift index 70041b9..c7ea488 100644 --- a/Sources/AuralKit/ModelManager.swift +++ b/Sources/AuralKit/ModelManager.swift @@ -10,8 +10,20 @@ actor ModelManager { private(set) var currentDownloadProgress: Progress? - // Track locales reserved by this ModelManager instance to avoid releasing others' reservations - private var reservedLocales: Set = [] + private let reservations: SpeechAssetReservations + private let assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? + private var leases: Set = [] + private var preparations = 0 + private var preparationWaiters: [CheckedContinuation] = [] + private var cleanupTask: Task? + + init( + reservations: SpeechAssetReservations = .shared, + assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? = nil + ) { + self.reservations = reservations + self.assetDownloader = assetDownloader + } /// Ensure the speech model for the given locale is available func ensureModel(module: any LocaleDependentSpeechModule, locale: Locale) async throws { @@ -35,7 +47,9 @@ actor ModelManager { return } - try await downloadAssetsIfNeeded(for: [module]) + try await prepareAssets(for: [module]) { manager in + try await manager.downloadAssetsIfNeeded(for: [module]) + } } private func ensureLocaleAssets( @@ -44,19 +58,19 @@ actor ModelManager { supportedLocales: @escaping @Sendable () async -> [Locale], installedLocales: @escaping @Sendable () async -> [Locale] ) async throws { - guard await localeMatches(provider: supportedLocales, locale: locale) else { - throw SpeechSessionError.unsupportedLocale(locale) - } - - if await localeMatches(provider: installedLocales, locale: locale) { - logger.notice("Locale \(locale.identifier(.bcp47)) already installed") - currentDownloadProgress = nil - } else { - logger.info("Ensuring model download for locale \(locale.identifier(.bcp47))") - try await downloadAssetsIfNeeded(for: [module]) - } - - try await reserveLocaleIfNeeded(locale) + try await prepareAssets(for: [module], validate: { manager in + guard await manager.localeMatches(provider: supportedLocales, locale: locale) else { + throw SpeechSessionError.unsupportedLocale(locale) + } + }, install: { manager in + if await manager.localeMatches(provider: installedLocales, locale: locale) { + manager.logger.notice("Locale \(locale.identifier(.bcp47)) already installed") + manager.currentDownloadProgress = nil + } else { + manager.logger.info("Ensuring model download for locale \(locale.identifier(.bcp47))") + try await manager.downloadAssetsIfNeeded(for: [module]) + } + }) } private func localeMatches( @@ -68,32 +82,21 @@ actor ModelManager { return locales.contains { $0.identifier(.bcp47) == target } } - private func reserveLocaleIfNeeded(_ locale: Locale) async throws { - let existingReservations = await AssetInventory.reservedLocales - let target = locale.identifier(.bcp47) - if existingReservations.contains(where: { $0.identifier(.bcp47) == target }) { - logger.debug("Locale \(target) already reserved") - // Don't track it - it was reserved by another session - return - } - - do { - try await AssetInventory.reserve(locale: locale) - logger.info("Reserved locale \(target)") - reservedLocales.insert(target) - } catch { - logger.error("Failed to reserve locale \(target): \(error.localizedDescription, privacy: .public)") - throw SpeechSessionError.modelReservationFailed(locale, error) - } - } - func ensureAssets(for modules: [any SpeechModule]) async throws { guard !modules.isEmpty else { return } - try await downloadAssetsIfNeeded(for: modules) + try await prepareAssets(for: modules) { manager in + try await manager.downloadAssetsIfNeeded(for: modules) + } } private func downloadAssetsIfNeeded(for modules: [any SpeechModule]) async throws { + try requirePreparation() + if let assetDownloader { + try await assetDownloader(modules) + return + } if let downloader = try await AssetInventory.assetInstallationRequest(supporting: modules) { + try requirePreparation() currentDownloadProgress = downloader.progress logger.info("Starting asset download for \(modules.count) module(s)") do { @@ -119,21 +122,82 @@ actor ModelManager { } } - /// Release reserved locales so other clients can access them - /// Only releases locales that were reserved by this ModelManager instance + /// Close preparation admission and join it before returning locale leases. + /// A late native acquisition/download must not outlive its manager cleanup. func releaseLocales() async { - let allReserved = await AssetInventory.reservedLocales - // Only release locales tracked by this instance - var releasedCount = 0 - for locale in allReserved { - let target = locale.identifier(.bcp47) - if reservedLocales.contains(target) { - await AssetInventory.release(reservedLocale: locale) - reservedLocales.remove(target) - releasedCount += 1 + await beginReleasingLocales().value + } + + /// Close admission synchronously on this actor; concurrent releases join one drain. + /// Only ModelManager preparation is joined here, never its calling pipeline task: + /// a failed setup may itself call releaseLocales after ensureModel has unwound. + func beginReleasingLocales() -> Task { + if let cleanupTask { return cleanupTask } + let cleanup = Task { + if self.preparations != 0 { + await withCheckedContinuation { self.preparationWaiters.append($0) } } + let pending = self.leases + self.leases.removeAll() + for lease in pending { + await self.reservations.release(lease) + } + self.currentDownloadProgress = nil + self.cleanupTask = nil + self.logger.debug("Released \(pending.count) session locale lease(s)") } - currentDownloadProgress = nil - logger.debug("Released \(releasedCount) reserved locale(s)") + cleanupTask = cleanup + return cleanup + } + + private func prepareAssets( + for modules: [any SpeechModule], + validate: @Sendable (isolated ModelManager) async throws -> Void = { _ in }, + install: @Sendable (isolated ModelManager) async throws -> Void + ) async throws { + try requirePreparation() + preparations += 1 + defer { preparationFinished() } + var acquired: [SpeechAssetReservations.Lease] = [] + do { + try await validate(self) + try requirePreparation() + // These are module-defined asset locales, not guessed equivalents + // of the user's preferred transcription language. + let locales = modules.compactMap { $0 as? any LocaleDependentSpeechModule } + .flatMap { $0.selectedLocales } + var requested = Set() + for locale in locales where requested.insert(locale.identifier(.bcp47)).inserted { + do { + acquired.append(try await reservations.acquire(locale)) + } catch is CancellationError { + throw CancellationError() + } catch { + throw SpeechSessionError.modelReservationFailed(locale, error) + } + try requirePreparation() + } + try await install(self) + try requirePreparation() + leases.formUnion(acquired) + } catch { + for lease in acquired { + await reservations.release(lease) + } + throw error + } + } + + private func requirePreparation() throws { + try Task.checkCancellation() + guard cleanupTask == nil else { throw CancellationError() } + } + + private func preparationFinished() { + preparations -= 1 + guard preparations == 0 else { return } + let waiters = preparationWaiters + preparationWaiters.removeAll() + for waiter in waiters { waiter.resume() } } } diff --git a/Sources/AuralKit/SpeechAssetReservations.swift b/Sources/AuralKit/SpeechAssetReservations.swift new file mode 100644 index 0000000..4da4a62 --- /dev/null +++ b/Sources/AuralKit/SpeechAssetReservations.swift @@ -0,0 +1,181 @@ +import Foundation +import Speech + +/// Coordinates reservation mutations made through AuralKit's shared instance. +/// Its native inventory calls are serialized across suspension points, not merely +/// isolated to an actor. Unrelated AssetInventory clients are outside this queue. +/// Existing reservations are borrowed, never reclaimed. +actor SpeechAssetReservations { + struct Inventory: Sendable { + var locales: @Sendable () async -> [Locale] + var reserve: @Sendable (Locale) async throws -> Bool + var release: @Sendable (Locale) async -> Bool + + static let live = Inventory( + locales: { await AssetInventory.reservedLocales }, + reserve: { try await AssetInventory.reserve(locale: $0) }, + release: { await AssetInventory.release(reservedLocale: $0) } + ) + } + + struct Lease: Hashable, Sendable { + fileprivate let id: UUID + } + + enum ReservationError: Error { + case ambiguousInventoryChange + } + + private struct Reservation { + let locale: Locale + var holders: Set = [] + } + + private struct Alias { + let protectedKeys: Set + var holders: Set = [] + } + + private struct Holding { + let alias: String + let protectedKeys: Set + } + + static let shared = SpeechAssetReservations() + + private let inventory: Inventory + private var reservations: [String: Reservation] = [:] + private var aliases: [String: Alias] = [:] + private var holdings: [UUID: Holding] = [:] + private var tail: Task? + private var queuedOperations = 0 + + init(inventory: Inventory = .live) { + self.inventory = inventory + } + + func acquire(_ locale: Locale) async throws -> Lease { + try Task.checkCancellation() + let previous = tail + queuedOperations += 1 + let operation = Task { + await previous?.value + return try await self.acquireSerially(locale) + } + tail = Task { + _ = await operation.result + self.operationFinished() + } + let lease = try await operation.value + do { + try Task.checkCancellation() + return lease + } catch { + // A shared native reserve can finish after its caller is canceled. + // Do not abandon the successful acquisition at that boundary. + await release(lease) + throw error + } + } + + func release(_ lease: Lease) async { + let previous = tail + queuedOperations += 1 + let operation = Task { + await previous?.value + await self.releaseSerially(lease) + } + tail = Task { + await operation.value + self.operationFinished() + } + await operation.value + } + + private func operationFinished() { + queuedOperations -= 1 + if queuedOperations == 0 { + // Completed tasks must not become a retained operation history. + tail = nil + } + } + + private func acquireSerially(_ locale: Locale) async throws -> Lease { + let alias = Self.key(locale) + if let known = aliases[alias] { + return admit(alias: alias, protecting: known.protectedKeys) + } + if reservations[alias] != nil { + return admit(alias: alias, protecting: [alias]) + } + + let before = Self.index(await inventory.locales()) + if before[alias] != nil { + // Preserve an exact external reservation without mutating it. + return admit(alias: alias, protecting: []) + } + let created = try await inventory.reserve(locale) + let after = Self.index(await inventory.locales()) + let protectedKeys: Set + if created { + let added = Set(after.keys).subtracting(before.keys) + // The API returns a Bool, not the canonical asset locale. Only one + // unambiguous new native identity establishes ownership. Preserve + // unknown reservations if another inventory client changed it. + guard added.count == 1, let key = added.first, let actual = after[key] else { + throw ReservationError.ambiguousInventoryChange + } + if reservations[key] == nil { + reservations[key] = Reservation(locale: actual) + } + protectedKeys = [key] + } else if after[alias] != nil { + // An exact native identity can be borrowed without protecting + // unrelated reservations that this coordinator happens to own. + protectedKeys = reservations[alias] == nil ? [] : [alias] + } else { + guard !after.isEmpty else { throw ReservationError.ambiguousInventoryChange } + // Native inventory can report a variant of the requested locale. + // Do not guess language/region equivalence. An unknown borrowed + // alias protects only currently owned candidates until it ends. + protectedKeys = Set(reservations.keys).intersection(after.keys) + } + return admit(alias: alias, protecting: protectedKeys) + } + + private func admit(alias: String, protecting keys: Set) -> Lease { + let lease = Lease(id: UUID()) + var entry = aliases[alias] ?? Alias(protectedKeys: keys) + entry.holders.insert(lease.id) + aliases[alias] = entry + holdings[lease.id] = Holding(alias: alias, protectedKeys: keys) + for key in keys { + reservations[key]?.holders.insert(lease.id) + } + return lease + } + + private func releaseSerially(_ lease: Lease) async { + guard let holding = holdings.removeValue(forKey: lease.id) else { return } + aliases[holding.alias]?.holders.remove(lease.id) + if aliases[holding.alias]?.holders.isEmpty == true { + aliases.removeValue(forKey: holding.alias) + } + for key in holding.protectedKeys { + reservations[key]?.holders.remove(lease.id) + } + for key in holding.protectedKeys { + guard let reservation = reservations[key], reservation.holders.isEmpty else { continue } + reservations.removeValue(forKey: key) + _ = await inventory.release(reservation.locale) + } + } + + private static func key(_ locale: Locale) -> String { + locale.identifier(.bcp47) + } + + private static func index(_ locales: [Locale]) -> [String: Locale] { + Dictionary(locales.map { (key($0), $0) }, uniquingKeysWith: { first, _ in first }) + } +} diff --git a/Tests/AuralKitTests/SpeechAssetReservationTests.swift b/Tests/AuralKitTests/SpeechAssetReservationTests.swift new file mode 100644 index 0000000..b412e5f --- /dev/null +++ b/Tests/AuralKitTests/SpeechAssetReservationTests.swift @@ -0,0 +1,475 @@ +import Foundation +import AVFoundation +import Speech +import Testing +@testable import AuralKit + +private actor AssetGate { + private var entered = false + private var arrivals: [CheckedContinuation] = [] + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + + func wait() async { + entered = true + let pending = arrivals + arrivals.removeAll() + for arrival in pending { arrival.resume() } + guard !isOpen else { return } + await withCheckedContinuation { waiters.append($0) } + } + + func waitForEntry() async { + guard !entered else { return } + await withCheckedContinuation { arrivals.append($0) } + } + + func open() { + isOpen = true + let pending = waiters + waiters.removeAll() + for waiter in pending { waiter.resume() } + } +} + +private actor AssetInventoryProbe { + struct Snapshot: Sendable { + let locales: Set + let reserves: [String] + let releases: [String] + } + + private var stored: [String: Locale] + private let variants: [String: Locale] + private var reserveCalls: [String] = [] + private var releaseCalls: [String] = [] + private var reserveGate: AssetGate? + private var releaseGate: AssetGate? + private var extraLocales: [Locale] = [] + + init(initial: [Locale] = [], variants: [String: Locale] = [:]) { + stored = Dictionary(initial.map { ($0.identifier(.bcp47), $0) }, + uniquingKeysWith: { first, _ in first }) + self.variants = variants + } + + nonisolated var client: SpeechAssetReservations.Inventory { + .init(locales: { await self.locales() }, + reserve: { await self.reserve($0) }, + release: { await self.release($0) }) + } + + var snapshot: Snapshot { + Snapshot(locales: Set(stored.keys), reserves: reserveCalls, releases: releaseCalls) + } + + func holdReserve(at gate: AssetGate) { reserveGate = gate } + func holdRelease(at gate: AssetGate) { releaseGate = gate } + func addDuringNextReserve(_ locales: [Locale]) { extraLocales = locales } + private func locales() -> [Locale] { Array(stored.values) } + + private func reserve(_ locale: Locale) async -> Bool { + let requested = locale.identifier(.bcp47) + reserveCalls.append(requested) + await reserveGate?.wait() + let actual = variants[requested] ?? locale + let key = actual.identifier(.bcp47) + guard stored[key] == nil else { return false } + stored[key] = actual + for extra in extraLocales { stored[extra.identifier(.bcp47)] = extra } + extraLocales.removeAll() + return true + } + + private func release(_ locale: Locale) async -> Bool { + let key = locale.identifier(.bcp47) + releaseCalls.append(key) + await releaseGate?.wait() + return stored.removeValue(forKey: key) != nil + } +} + +@MainActor +private final class AssetReservationFixture { + let inventory: AssetInventoryProbe + let reservations: SpeechAssetReservations + private var gates: [AssetGate] = [] + private var acquisitions: [Task] = [] + private var work: [Task] = [] + private var releases: [Task] = [] + private var managers: [ModelManager] = [] + + init(initial: [Locale] = [], variants: [String: Locale] = [:]) { + let inventory = AssetInventoryProbe(initial: initial, variants: variants) + self.inventory = inventory + reservations = SpeechAssetReservations(inventory: inventory.client) + } + + func gate() -> AssetGate { + let gate = AssetGate() + gates.append(gate) + return gate + } + + func acquire(_ locale: Locale) -> Task { + let task = Task { try await reservations.acquire(locale) } + acquisitions.append(task) + return task + } + + func start(_ operation: @escaping @MainActor () async throws -> Void) -> Task { + let task = Task { try await operation() } + work.append(task) + return task + } + + func release(_ lease: SpeechAssetReservations.Lease) -> Task { + let task = Task { await reservations.release(lease) } + releases.append(task) + return task + } + + func manager( + download: @escaping @Sendable ([any SpeechModule]) async throws -> Void + ) -> ModelManager { + let manager = ModelManager(reservations: reservations, assetDownloader: download) + managers.append(manager) + return manager + } + + func release(_ manager: ModelManager) async -> Task { + let task = await manager.beginReleasingLocales() + releases.append(task) + return task + } + + func cleanup() async { + for task in acquisitions { task.cancel() } + for task in work { task.cancel() } + for gate in gates { await gate.open() } + for task in work { _ = await task.result } + for manager in managers { await manager.releaseLocales() } + for task in acquisitions { + if case .success(let lease) = await task.result { await reservations.release(lease) } + } + for task in releases { await task.value } + } + + enum ProbeError: Error { case download } +} + +/// Only module metadata is needed by ModelManager. No native provider is invoked. +private final class ReservationModule: LocaleDependentSpeechModule { + struct Result: SpeechModuleResult, Sendable { + let range = CMTimeRange.zero + let resultsFinalizationTime = CMTime.zero + } + + let selectedLocales: [Locale] + init(locales: [Locale]) { selectedLocales = locales } + + static var supportedLocales: [Locale] { get async { [] } } + static func supportedLocale(equivalentTo locale: Locale) async -> Locale? { nil } + var availableCompatibleAudioFormats: [AVAudioFormat] { get async { [] } } + var results: AsyncThrowingStream { + AsyncThrowingStream { $0.finish() } + } +} + +@Suite("Speech asset reservations") +struct SpeechAssetReservationTests { + @Test("concurrent sessions share acquisition and only the final owner releases") + @MainActor + func concurrentOwners() async throws { + try await withFixture { fixture in + let gate = fixture.gate() + await fixture.inventory.holdReserve(at: gate) + let first = fixture.acquire(Locale(identifier: "en-US")) + await gate.waitForEntry() + let second = fixture.acquire(Locale(identifier: "en-US")) + await gate.open() + let firstLease = try await first.value + let secondLease = try await second.value + await fixture.reservations.release(firstLease) + var state = await fixture.inventory.snapshot + #expect(state.reserves == ["en-US"]) + #expect(state.releases.isEmpty) + await fixture.reservations.release(secondLease) + state = await fixture.inventory.snapshot + #expect(state.releases == ["en-US"]) + #expect(state.locales.isEmpty) + } + } + + @Test("managers retain module-selected locales until the last holder releases") + @MainActor + func managerHolders() async throws { + try await withFixture { fixture in + let module = ReservationModule(locales: [Locale(identifier: "ja-JP")]) + let first = fixture.manager { _ in } + let second = fixture.manager { _ in } + // The explicit locale is not a substitute for module-selected asset identity. + try await first.ensureModel(module: module, locale: Locale(identifier: "en-US")) + try await second.ensureAssets(for: [module]) + await first.releaseLocales() + await first.releaseLocales() + var state = await fixture.inventory.snapshot + #expect(state.reserves == ["ja-JP"]) + #expect(state.releases.isEmpty) + await second.releaseLocales() + state = await fixture.inventory.snapshot + #expect(state.releases == ["ja-JP"]) + #expect(state.locales.isEmpty) + } + } + + @Test("release uses the observed native locale variant") + @MainActor + func canonicalVariant() async throws { + try await withFixture(variants: ["en-AU": Locale(identifier: "en-US")]) { fixture in + let lease = try await fixture.acquire(Locale(identifier: "en-AU")).value + let canonical = try await fixture.acquire(Locale(identifier: "en-US")).value + let alias = try await fixture.acquire(Locale(identifier: "en-AU")).value + await fixture.reservations.release(lease) + await fixture.reservations.release(canonical) + #expect(await fixture.inventory.snapshot.releases.isEmpty) + await fixture.reservations.release(alias) + let state = await fixture.inventory.snapshot + #expect(state.reserves == ["en-AU"]) + #expect(state.releases == ["en-US"]) + #expect(state.locales.isEmpty) + } + } + + @Test("preexisting variant reservations remain borrowed") + @MainActor + func preexistingReservation() async throws { + try await withFixture(initial: [Locale(identifier: "en-US")], + variants: ["en-AU": Locale(identifier: "en-US")]) { fixture in + let lease = try await fixture.acquire(Locale(identifier: "en-AU")).value + await fixture.reservations.release(lease) + let state = await fixture.inventory.snapshot + #expect(state.releases.isEmpty) + #expect(state.locales == ["en-US"]) + } + } + + @Test("an externally reserved exact locale survives manager cleanup") + @MainActor + func externalManagerReservation() async throws { + try await withFixture(initial: [Locale(identifier: "en-US")]) { fixture in + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let manager = fixture.manager { _ in } + try await manager.ensureAssets(for: [module]) + await manager.releaseLocales() + let state = await fixture.inventory.snapshot + #expect(state.reserves.isEmpty) + #expect(state.releases.isEmpty) + #expect(state.locales == ["en-US"]) + } + } + + @Test("a borrowed alias conservatively protects all current owned candidates") + @MainActor + func multipleAliasCandidates() async throws { + try await withFixture(variants: ["en-AU": Locale(identifier: "en-US")]) { fixture in + let english = try await fixture.acquire(Locale(identifier: "en-US")).value + let japanese = try await fixture.acquire(Locale(identifier: "ja-JP")).value + let alias = try await fixture.acquire(Locale(identifier: "en-AU")).value + await fixture.reservations.release(english) + await fixture.reservations.release(japanese) + #expect(await fixture.inventory.snapshot.releases.isEmpty) + await fixture.reservations.release(alias) + let state = await fixture.inventory.snapshot + #expect(Set(state.releases) == ["en-US", "ja-JP"]) + #expect(state.locales.isEmpty) + } + } + + @Test("unknown borrowed aliases protect current candidates, not future unrelated assets") + @MainActor + func ambiguousBorrower() async throws { + try await withFixture(variants: ["en-AU": Locale(identifier: "en-US")]) { fixture in + let owner = try await fixture.acquire(Locale(identifier: "en-US")).value + let borrower = try await fixture.acquire(Locale(identifier: "en-AU")).value + let later = try await fixture.acquire(Locale(identifier: "ja-JP")).value + await fixture.reservations.release(owner) + var state = await fixture.inventory.snapshot + #expect(state.releases.isEmpty) + await fixture.reservations.release(later) + state = await fixture.inventory.snapshot + #expect(state.releases == ["ja-JP"]) + await fixture.reservations.release(borrower) + state = await fixture.inventory.snapshot + #expect(state.releases == ["ja-JP", "en-US"]) + } + } + + @Test("ambiguous native mutations are not claimed or broadly released") + @MainActor + func ambiguousInventoryMutation() async throws { + try await withFixture { fixture in + await fixture.inventory.addDuringNextReserve([Locale(identifier: "fr-FR")]) + let operation = fixture.acquire(Locale(identifier: "en-US")) + if case .success = await operation.result { Issue.record("Ambiguous inventory was accepted") } + let state = await fixture.inventory.snapshot + #expect(state.releases.isEmpty) + #expect(state.locales == ["en-US", "fr-FR"]) + } + } + + @Test("reacquisition during release waits and establishes a fresh reservation") + @MainActor + func reacquisitionDuringRelease() async throws { + try await withFixture { fixture in + let lease = try await fixture.acquire(Locale(identifier: "en-US")).value + let gate = fixture.gate() + await fixture.inventory.holdRelease(at: gate) + let release = fixture.release(lease) + await gate.waitForEntry() + let next = fixture.acquire(Locale(identifier: "en-US")) + await gate.open() + await release.value + let nextLease = try await next.value + var state = await fixture.inventory.snapshot + #expect(state.reserves == ["en-US", "en-US"]) + #expect(state.locales == ["en-US"]) + await fixture.reservations.release(nextLease) + state = await fixture.inventory.snapshot + #expect(state.releases == ["en-US", "en-US"]) + } + } + + @Test("manager download failure returns its explicitly acquired locale") + @MainActor + func downloadFailure() async throws { + try await withFixture { fixture in + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let manager = fixture.manager { _ in throw AssetReservationFixture.ProbeError.download } + let operation = fixture.start { + do { + try await manager.ensureAssets(for: [module]) + } catch { + await manager.releaseLocales() + throw error + } + } + if case .success = await operation.result { Issue.record("Download failure was ignored") } + let state = await fixture.inventory.snapshot + #expect(!state.reserves.isEmpty) + #expect(state.releases.count == state.reserves.count) + #expect(state.locales.isEmpty) + } + } + + @Test("canceling manager acquisition cannot abandon a late native reservation") + @MainActor + func canceledAcquisition() async throws { + try await withFixture { fixture in + let gate = fixture.gate() + await fixture.inventory.holdReserve(at: gate) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let manager = fixture.manager { _ in Issue.record("Canceled acquisition started a download") } + let operation = fixture.start { try await manager.ensureAssets(for: [module]) } + await gate.waitForEntry() + operation.cancel() + await gate.open() + if case .success = await operation.result { Issue.record("Canceled acquisition succeeded") } + let state = await fixture.inventory.snapshot + #expect(state.releases.count == 1) + #expect(state.locales.isEmpty) + } + } + + @Test("cancellation after acquisition returns the lease when preparation unwinds") + @MainActor + func canceledPreparation() async throws { + try await withFixture { fixture in + let gate = fixture.gate() + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let manager = fixture.manager { _ in await gate.wait() } + let operation = fixture.start { try await manager.ensureAssets(for: [module]) } + await gate.waitForEntry() + operation.cancel() + #expect(await fixture.inventory.snapshot.releases.isEmpty) + await gate.open() + switch await operation.result { + case .failure(is CancellationError): break + default: Issue.record("Canceled preparation did not throw CancellationError") + } + let state = await fixture.inventory.snapshot + #expect(state.releases == ["en-US"]) + #expect(state.locales.isEmpty) + } + } + + @Test("manager cleanup drains pending acquisitions before returning") + @MainActor + func cleanupDuringAcquisition() async throws { + try await withFixture { fixture in + let gate = fixture.gate() + await fixture.inventory.holdReserve(at: gate) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let manager = fixture.manager { _ in Issue.record("Retired preparation started a download") } + let operation = fixture.start { try await manager.ensureAssets(for: [module]) } + await gate.waitForEntry() + let cleanup = await fixture.release(manager) + let repeated = await fixture.release(manager) + await gate.open() + if case .success = await operation.result { Issue.record("Retired acquisition succeeded") } + await repeated.value + await cleanup.value + let state = await fixture.inventory.snapshot + #expect(state.releases.count == 1) + #expect(state.locales.isEmpty) + } + } + + @Test("manager cleanup retains reservations until an active download returns") + @MainActor + func cleanupDuringDownload() async throws { + try await withFixture { fixture in + let gate = fixture.gate() + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let manager = fixture.manager { _ in await gate.wait() } + let operation = fixture.start { try await manager.ensureAssets(for: [module]) } + await gate.waitForEntry() + let cleanup = await fixture.release(manager) + let repeated = await fixture.release(manager) + let peer = fixture.manager { _ in } + try await peer.ensureAssets(for: [module]) + // Admission stays closed while cleanup is joining preparation. + let rejected = fixture.start { try await manager.ensureAssets(for: [module]) } + if case .success = await rejected.result { Issue.record("Cleanup admitted new preparation") } + var state = await fixture.inventory.snapshot + #expect(state.releases.isEmpty) + await gate.open() + if case .success = await operation.result { Issue.record("Retired download was admitted") } + await cleanup.value + await repeated.value + state = await fixture.inventory.snapshot + #expect(state.releases.isEmpty) + // A retired holder's repeated cleanup cannot return a peer's lease. + await manager.releaseLocales() + await peer.releaseLocales() + state = await fixture.inventory.snapshot + #expect(state.releases.count == 1) + #expect(state.locales.isEmpty) + } + } + + @MainActor + private func withFixture( + initial: [Locale] = [], variants: [String: Locale] = [:], + operation: @MainActor (AssetReservationFixture) async throws -> Void + ) async throws { + let fixture = AssetReservationFixture(initial: initial, variants: variants) + do { + try await operation(fixture) + } catch { + await fixture.cleanup() + throw error + } + await fixture.cleanup() + } +} From 2d4d5b61a6d021270d63c0c217a1d250322915d6 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 11:42:32 -0500 Subject: [PATCH 04/70] Bound file frame reads before narrowing to UInt32 --- Sources/AuralKit/AudioFileReadSize.swift | 7 ++++ Sources/AuralKit/SpeechSession+File.swift | 6 ++- .../FileTranscriptionReadSizeTests.swift | 38 +++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 Sources/AuralKit/AudioFileReadSize.swift create mode 100644 Tests/AuralKitTests/FileTranscriptionReadSizeTests.swift diff --git a/Sources/AuralKit/AudioFileReadSize.swift b/Sources/AuralKit/AudioFileReadSize.swift new file mode 100644 index 0000000..f806218 --- /dev/null +++ b/Sources/AuralKit/AudioFileReadSize.swift @@ -0,0 +1,7 @@ +/// Bounds the signed 64-bit file remainder before narrowing to a per-read count. +/// Even a file longer than UInt32.max frames needs only one buffer per read. +enum AudioFileReadSize { + static func next(remaining: Int64, capacity: UInt32) -> UInt32 { + UInt32(min(max(remaining, 0), Int64(capacity))) + } +} diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 56ebbcb..d3bb0ef 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -300,8 +300,10 @@ private extension SpeechSession { while processedFrames < totalFrames { if Task.isCancelled { break } - let framesRemaining = AVAudioFrameCount(totalFrames - processedFrames) - let framesToRead = min(frameCapacity, framesRemaining) + let framesToRead = AudioFileReadSize.next( + remaining: totalFrames - processedFrames, + capacity: buffer.frameCapacity + ) buffer.frameLength = framesToRead diff --git a/Tests/AuralKitTests/FileTranscriptionReadSizeTests.swift b/Tests/AuralKitTests/FileTranscriptionReadSizeTests.swift new file mode 100644 index 0000000..5284bb4 --- /dev/null +++ b/Tests/AuralKitTests/FileTranscriptionReadSizeTests.swift @@ -0,0 +1,38 @@ +import Testing +@testable import AuralKit + +@Suite("File transcription read sizes") +struct FileTranscriptionReadSizeTests { + @Test("large file remainders fit a single buffer", arguments: [ + Int64(UInt32.max), Int64(UInt32.max) + 1, Int64.max + ]) + func largeRemainders(_ remaining: Int64) { + #expect(AudioFileReadSize.next(remaining: remaining, capacity: 4_096) == 4_096) + } + + @Test("ordinary remainders include the final short read", arguments: [ + (Int64(0), UInt32(0)), + (1, 1), + (17, 17), + (4_095, 4_095), + (4_096, 4_096), + (4_097, 4_096) + ]) + func ordinaryRemainders(remaining: Int64, expected: UInt32) { + #expect(AudioFileReadSize.next(remaining: remaining, capacity: 4_096) == expected) + } + + @Test("the actual buffer capacity limits the read", arguments: [ + UInt32(0), 1, 17, 4_096, UInt32.max + ]) + func capacityBoundaries(_ capacity: UInt32) { + #expect(AudioFileReadSize.next(remaining: Int64.max, capacity: capacity) == capacity) + #expect(AudioFileReadSize.next(remaining: 0, capacity: capacity) == 0) + #expect(AudioFileReadSize.next(remaining: 1, capacity: capacity) == min(1, capacity)) + } + + @Test("nonpositive remainders produce no read", arguments: [Int64.min, -1, 0]) + func nonpositiveRemainders(_ remaining: Int64) { + #expect(AudioFileReadSize.next(remaining: remaining, capacity: UInt32.max) == 0) + } +} From c2ffc3dbfc60f6a535519f6ab5b2cf8f51342620 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:00:42 -0500 Subject: [PATCH 05/70] Serialize screen capture transitions and join admitted shutdown work --- .../AuralKit/ScreenCaptureTransitions.swift | 91 ++++++++ .../SpeechSession+ScreenCapture.swift | 136 +++++++---- Sources/AuralKit/SpeechSession.swift | 9 + .../ScreenCaptureTransitionTests.swift | 220 ++++++++++++++++++ 4 files changed, 407 insertions(+), 49 deletions(-) create mode 100644 Sources/AuralKit/ScreenCaptureTransitions.swift create mode 100644 Tests/AuralKitTests/ScreenCaptureTransitionTests.swift diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift new file mode 100644 index 0000000..8022314 --- /dev/null +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -0,0 +1,91 @@ +import Foundation + +/// The narrow boundary around actual capture calls, shared by SCStream and controlled fixtures. +@available(iOS 26.0, macOS 14.0, *) +@MainActor +protocol ScreenCaptureStream: AnyObject { + func startCapture() async throws + func stopCapture() async throws +} + +/// Serializes capture side effects across suspension. Admission changes intent immediately; +/// only internal operations are joined, never a public caller that may await session cleanup. +@available(iOS 26.0, macOS 14.0, *) +@MainActor +final class ScreenCaptureTransitions { + enum DesiredState { case running, paused, stopped } + private(set) var desiredState = DesiredState.running + private(set) var stream: (any ScreenCaptureStream)? + private(set) var isRunning = false + private var revision = UUID() + private var tail: Task? + + // Synchronous admission returns the owned handle before any capture call can suspend. + func replace(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) -> Task { + guard desiredState != .stopped else { return Task { throw CancellationError() } } + let admitted = UUID() + revision = admitted + return enqueue { + do { + guard self.desiredState != .stopped, self.revision == admitted else { return } + try await self.stopCurrent() + guard self.desiredState != .stopped, self.revision == admitted else { return } + self.stream = try makeStream() + try await self.startCurrent(revision: admitted) + } catch { + // A stale picker operation must not report failure against its successor. + guard self.desiredState != .stopped, self.revision == admitted else { return } + throw error + } + } + } + + func pause() -> Task { + guard desiredState != .stopped else { return enqueue {} } + desiredState = .paused + return enqueue { try await self.stopCurrent() } + } + + func resume() -> Task { + guard desiredState != .stopped else { return enqueue { throw CancellationError() } } + desiredState = .running + let admitted = revision + return enqueue { try await self.startCurrent(revision: admitted) } + } + + func stop() -> Task { + desiredState = .stopped + return enqueue { + try await self.stopCurrent() + self.stream = nil + } + } + + private func enqueue(_ body: @escaping @MainActor () async throws -> Void) -> Task { + let previous = tail + let operation = Task { @MainActor in + // Failure must not bypass the join or prevent a later terminal stop. + _ = try? await previous?.value + try await body() + } + tail = operation + return operation + } + + private func stopCurrent() async throws { + guard isRunning, let stream else { return } + try await stream.stopCapture() + isRunning = false + } + + private func startCurrent(revision admitted: UUID) async throws { + guard desiredState == .running, revision == admitted, !isRunning, let stream else { return } + try await stream.startCapture() + // Nothing else can perform capture calls until this operation exits. Intent can + // still change during start; compensate before allowing a queued operation to run. + isRunning = true + if desiredState != .running || revision != admitted { + try await stopCurrent() + } + } +} diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index e6432fc..24b2cb6 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -180,8 +180,27 @@ extension SpeechSession { } } +/// Keeps ScreenCaptureKit calls on the same tested transition boundary. @available(iOS 27.0, macOS 14.0, *) -private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamDelegate, +@MainActor +private final class NativeScreenCaptureStream: ScreenCaptureStream { + let stream: SCStream + let willStop: @MainActor (SCStream) -> Void + + init(stream: SCStream, willStop: @escaping @MainActor (SCStream) -> Void) { + self.stream = stream + self.willStop = willStop + } + + func startCapture() async throws { try await stream.startCapture() } + func stopCapture() async throws { + willStop(stream) + try await stream.stopCapture() + } +} + +@available(iOS 27.0, macOS 14.0, *) +final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamDelegate, SCContentSharingPickerObserver, @unchecked Sendable { private let options: SpeechSession.ScreenCaptureTranscriptionOptions @@ -192,26 +211,40 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S // Only touched on `sampleQueue`, which serializes access. private let bufferConverter = BufferConverter() - private var stream: SCStream? + @MainActor private let transitions: ScreenCaptureTransitions + private let dismissPicker: @MainActor (any SCContentSharingPickerObserver) -> Void private var selectionContinuation: CheckedContinuation? - private var isRunning = false + private var stopped = false + @MainActor private var captureTasks: [UUID: Task] = [:] + @MainActor private var pickerUpdateID: UUID? private var intentionallyStoppingStreams = Set() + @MainActor init( options: SpeechSession.ScreenCaptureTranscriptionOptions, targetFormat: AVAudioFormat, inputContinuation: AsyncStream.Continuation, - onFailure: @escaping @Sendable (Error) -> Void + onFailure: @escaping @Sendable (Error) -> Void, + transitions: ScreenCaptureTransitions = ScreenCaptureTransitions(), + dismissPicker: @escaping @MainActor (any SCContentSharingPickerObserver) -> Void = { observer in + let picker = SCContentSharingPicker.shared + picker.isActive = false + picker.remove(observer) + } ) { self.options = options self.targetFormat = targetFormat self.inputContinuation = inputContinuation self.onFailure = onFailure + self.transitions = transitions + self.dismissPicker = dismissPicker super.init() } @MainActor func start() async throws { + try Task.checkCancellation() + guard !stopped else { throw CancellationError() } let picker = SCContentSharingPicker.shared let configuration = SCContentSharingPickerConfiguration() picker.configuration = configuration @@ -219,46 +252,41 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S picker.add(self) picker.isActive = true + // Cleanup stops this provider before finalizing detached analyzer state. + // stop() resumes pending selection and joins admitted picker updates. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in selectionContinuation = continuation picker.present() } + try Task.checkCancellation() } @MainActor func pause() async { - guard isRunning, let stream else { return } - markStreamForIntentionalStop(stream) - try? await stream.stopCapture() - isRunning = false + _ = try? await transitions.pause().value } @MainActor func resume() async throws { - guard !isRunning, let stream else { - throw SpeechSessionError.recognitionStreamSetupFailed - } - try await stream.startCapture() - isRunning = true + guard !stopped else { throw CancellationError() } + try await transitions.resume().value } @MainActor func stop() async { - let picker = SCContentSharingPicker.shared - picker.isActive = false - picker.remove(self) + stopped = true + dismissPicker(self) if let selectionContinuation { selectionContinuation.resume(throwing: SpeechSessionError.screenCaptureSelectionCancelled) self.selectionContinuation = nil } - if isRunning, let stream { - markStreamForIntentionalStop(stream) - try? await stream.stopCapture() - } - stream = nil - isRunning = false + // Joins internal start/resume/pause/replacement operations, including a late + // start's compensating stop, before cleanup can finalize detached analyzer/model owners. + _ = try? await transitions.stop().value + let tasks = Array(captureTasks.values) + for task in tasks { await task.value } } func contentSharingPicker( @@ -267,14 +295,26 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S for stream: SCStream? ) { nonisolated(unsafe) let selectedFilter = filter + nonisolated(unsafe) let updatedStream = stream Task { @MainActor [weak self] in - guard let self else { return } - do { - try await beginCapture(with: selectedFilter) - resumeSelection() - } catch { - if !resumeSelection(throwing: error) { - onFailure(SpeechSessionError.screenCaptureFailed(error)) + guard let self, !self.stopped else { return } + if let updatedStream { + guard (self.transitions.stream as? NativeScreenCaptureStream)?.stream === updatedStream else { return } + } + let id = UUID() + self.pickerUpdateID = id + self.captureTasks[id] = Task { @MainActor in + defer { self.captureTasks[id] = nil } + guard !self.stopped, self.pickerUpdateID == id else { return } + do { + try await self.beginCapture(with: selectedFilter) + guard !self.stopped, self.pickerUpdateID == id else { return } + self.resumeSelection() + } catch { + guard !self.stopped, self.pickerUpdateID == id else { return } + if !self.resumeSelection(throwing: error) { + self.onFailure(SpeechSessionError.screenCaptureFailed(error)) + } } } } @@ -298,8 +338,8 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S func stream(_ stream: SCStream, didStopWithError error: any Error) { Task { @MainActor [weak self] in - guard let self, !self.consumeIntentionalStop(for: stream) else { return } - self.isRunning = false + guard let self, !self.consumeIntentionalStop(for: stream), + !self.stopped, (self.transitions.stream as? NativeScreenCaptureStream)?.stream === stream else { return } self.onFailure(SpeechSessionError.screenCaptureFailed(error)) } } @@ -329,25 +369,23 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S @MainActor private func beginCapture(with filter: SCContentFilter) async throws { - if isRunning, let stream { - markStreamForIntentionalStop(stream) - try await stream.stopCapture() - isRunning = false + guard !stopped else { throw CancellationError() } + let operation = transitions.replace { [self] in + let streamConfiguration = SCStreamConfiguration() + streamConfiguration.capturesAudio = true + streamConfiguration.sampleRate = Int(targetFormat.sampleRate) + streamConfiguration.channelCount = Int(targetFormat.channelCount) + streamConfiguration.excludesCurrentProcessAudio = options.excludesCurrentProcessAudio + streamConfiguration.width = 2 + streamConfiguration.height = 2 + + let captureStream = SCStream(filter: filter, configuration: streamConfiguration, delegate: self) + try captureStream.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) + return NativeScreenCaptureStream(stream: captureStream) { [weak self] stream in + self?.markStreamForIntentionalStop(stream) + } } - - let streamConfiguration = SCStreamConfiguration() - streamConfiguration.capturesAudio = true - streamConfiguration.sampleRate = Int(targetFormat.sampleRate) - streamConfiguration.channelCount = Int(targetFormat.channelCount) - streamConfiguration.excludesCurrentProcessAudio = options.excludesCurrentProcessAudio - streamConfiguration.width = 2 - streamConfiguration.height = 2 - - let captureStream = SCStream(filter: filter, configuration: streamConfiguration, delegate: self) - try captureStream.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) - self.stream = captureStream - try await captureStream.startCapture() - isRunning = true + try await operation.value } @discardableResult diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 03c211c..b45a812 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -360,11 +360,15 @@ public final class SpeechSession { /// screen capture). Calls during file transcription or in any other state are ignored. public func pauseTranscribing() async { guard status == .transcribing, isPausableStreamingMode else { return } + let generation = sessionGeneration if streamingMode == .screenCapture { await pauseScreenCaptureStreamingIfNeeded() } else { stopAudioStreaming() } + // A paused capture call can finish after stop has published idle, even in the + // same generation; it must not publish paused over that terminal status. + guard generation == sessionGeneration, status == .transcribing, isPausableStreamingMode else { return } setStatus(.paused) } @@ -380,8 +384,13 @@ public final class SpeechSession { } else { try startAudioStreaming() } + // A late start may have compensated for stop while this caller was suspended. + // Generation alone is insufficient until a successor actually begins. + guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { return } setStatus(.transcribing) } catch { + // A late failure belongs to the detached provider, not a successor session. + guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { throw error } prepareForStop() await cleanup(cancelRecognizer: true, generation: generation) await finishStream(error: error, generation: generation) diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift new file mode 100644 index 0000000..4accf52 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -0,0 +1,220 @@ +import AVFoundation +import Speech +import Testing +@testable import AuralKit + +/// Cancellation-independent latches: a cancelled operation still owns its OS call +/// until the fixture explicitly releases it. No readiness depends on scheduling delays. +@MainActor +private final class CaptureGate { + private var opened = false + private var waiters: [CheckedContinuation] = [] + + func wait() async { + if opened { return } + await withCheckedContinuation { waiters.append($0) } + } + + func open() { + opened = true + let pending = waiters + waiters.removeAll() + for waiter in pending { waiter.resume() } + } +} + +@available(iOS 26.0, macOS 26.0, *) +@MainActor +private final class ControlledCaptureStream: ScreenCaptureStream { + var starts = 0 + var stops = 0 + var capturing = false + var startEntered: CaptureGate? + var startRelease: CaptureGate? + var stopEntered: CaptureGate? + var stopRelease: CaptureGate? + + func startCapture() async throws { + starts += 1 + startEntered?.open() + await startRelease?.wait() + capturing = true + } + + func stopCapture() async throws { + stops += 1 + stopEntered?.open() + await stopRelease?.wait() + capturing = false + } +} + +@Suite("Screen capture transitions") +struct ScreenCaptureTransitionTests { + @Test("A picker replacement stopped across pause never starts the new stream") + @MainActor + func replacementHonorsAdmittedPause() async { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let owner = ScreenCaptureTransitions() + let old = ControlledCaptureStream() + let replacement = ControlledCaptureStream() + let entered = CaptureGate() + let release = CaptureGate() + defer { release.open(); entered.open() } + _ = try? await owner.replace { old }.value + old.stopEntered = entered + old.stopRelease = release + let update = owner.replace { replacement } + await entered.wait() + let pause = owner.pause() + #expect(owner.desiredState == .paused) + release.open() + _ = try? await update.value + _ = try? await pause.value + #expect(owner.stream === replacement) + #expect(!owner.isRunning) + #expect(!old.capturing) + #expect(replacement.starts == 0) + // A later explicit resume starts the selected stream, not the old one. + _ = try? await owner.resume().value + #expect(replacement.starts == 1) + #expect(old.starts == 1) + _ = try? await owner.stop().value + } + + @Test("Overlapping picker replacements cannot install an obsolete stream after stop") + @MainActor + func replacementIdentityAcrossStop() async { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let owner = ScreenCaptureTransitions() + let old = ControlledCaptureStream() + let obsolete = ControlledCaptureStream() + let current = ControlledCaptureStream() + let entered = CaptureGate() + let release = CaptureGate() + defer { release.open(); entered.open() } + _ = try? await owner.replace { old }.value + old.stopEntered = entered + old.stopRelease = release + var obsoleteCreated = false + let first = owner.replace { obsoleteCreated = true; return obsolete } + await entered.wait() + let second = owner.replace { current } + release.open() + _ = try? await first.value + _ = try? await second.value + #expect(!obsoleteCreated) + #expect(obsolete.starts == 0) + #expect(owner.stream === current) + #expect(current.capturing) + #expect(old.stops == 1) + _ = try? await owner.stop().value + } + + @Test("A superseded start compensates before its successor can start") + @MainActor + func replacementIdentityAcrossStart() async { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let owner = ScreenCaptureTransitions() + let obsolete = ControlledCaptureStream() + let current = ControlledCaptureStream() + let startEntered = CaptureGate() + let startRelease = CaptureGate() + let stopEntered = CaptureGate() + let stopRelease = CaptureGate() + defer { + startRelease.open(); stopRelease.open() + startEntered.open(); stopEntered.open() + } + obsolete.startEntered = startEntered + obsolete.startRelease = startRelease + obsolete.stopEntered = stopEntered + obsolete.stopRelease = stopRelease + let first = owner.replace { obsolete } + await startEntered.wait() + let second = owner.replace { current } + startRelease.open() + await stopEntered.wait() + #expect(current.starts == 0) + #expect(owner.stream === obsolete) + stopRelease.open() + _ = try? await first.value + _ = try? await second.value + #expect(!obsolete.capturing) + #expect(obsolete.stops == 1) + #expect(owner.stream === current) + #expect(current.starts == 1) + #expect(owner.isRunning) + _ = try? await owner.stop().value + } +} + +#if canImport(ScreenCaptureKit) +import ScreenCaptureKit + +extension ScreenCaptureTransitionTests { + @Test("Detached provider shutdown joins late resume and compensating stop") + @MainActor + func shutdownJoinsLateProviderResume() async { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + let owner = ScreenCaptureTransitions() + let stream = ControlledCaptureStream() + _ = try? await owner.replace { stream }.value + _ = try? await owner.pause().value + let startEntered = CaptureGate() + let startRelease = CaptureGate() + let stopEntered = CaptureGate() + let stopRelease = CaptureGate() + let dismissed = CaptureGate() + defer { + startRelease.open(); stopRelease.open() + startEntered.open(); stopEntered.open(); dismissed.open() + } + stream.startEntered = startEntered + stream.startRelease = startRelease + stream.stopEntered = stopEntered + stream.stopRelease = stopRelease + let (_, continuation) = AsyncStream.makeStream() + defer { continuation.finish() } + // Actual provider and actual detached cleanup interface. Only OS capture calls + // and picker dismissal vary; no analyzer setup or public session state setters. + let provider = ScreenCaptureAudioInputProvider( + options: .init(), + targetFormat: AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)!, + inputContinuation: continuation, + onFailure: { _ in Issue.record("Unexpected provider failure") }, + transitions: owner, + dismissPicker: { _ in dismissed.open() } + ) + let session = SpeechSession() + session.screenCaptureInputProvider = provider + let resume = Task { @MainActor in try? await provider.resume() } + await startEntered.wait() + var terminalReturned = false + let stop = Task { @MainActor in + await session.stopScreenCaptureStreamingIfNeeded() + terminalReturned = true + } + await dismissed.wait() + #expect(owner.desiredState == .stopped) + #expect(session.screenCaptureInputProvider == nil) + #expect(!terminalReturned) + startRelease.open() + await stopEntered.wait() + #expect(!terminalReturned) + #expect(stream.capturing) + stopRelease.open() + await stop.value + _ = await resume.value + #expect(terminalReturned) + #expect(!stream.capturing) + #expect(stream.starts == 2) + #expect(stream.stops == 2) + #expect(owner.stream == nil) + // Public stopTranscribing -> cleanup -> stopScreenCaptureStreamingIfNeeded + // awaits this boundary before finalizeDetachedTranscriberState/releaseLocales. + // Public resumeTranscribing is deliberately outside the joined operation chain: + // its error path can await cleanup itself. Full public setup needs native analysis. + } +} +#endif From 95e00b2cbd9cabbc28539a52b5e4f529a57e65b7 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:09:16 -0500 Subject: [PATCH 06/70] Join file transcription tasks through terminal cleanup --- Sources/AuralKit/SpeechSession+File.swift | 101 ++++----- .../SpeechSession+FileLifecycle.swift | 114 ++++++++++ Sources/AuralKit/SpeechSession+Pipeline.swift | 9 +- Sources/AuralKit/SpeechSession.swift | 8 +- .../FileTranscriptionJoinTests.swift | 211 ++++++++++++++++++ 5 files changed, 384 insertions(+), 59 deletions(-) create mode 100644 Sources/AuralKit/SpeechSession+FileLifecycle.swift create mode 100644 Tests/AuralKitTests/FileTranscriptionJoinTests.swift diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 56ebbcb..0393798 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -83,14 +83,31 @@ public extension SpeechSession { setStatus(.preparing) continuation = .speech(newContinuation) - pipelineTask = Task { @MainActor [weak self] in + let run = FileTranscriptionRun( + finalize: { [self] in + prepareForStop() + streamingMode = .inactive + activeResultKind = nil + let detached = detachTranscriberState() + detached.inputBuilder?.finish() + try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() + }, + complete: { [self] error in + await modelManager.releaseLocales() + setStatus(.idle) + fileTranscription = nil + await finishStream(error: error, generation: generation) + } + ) + fileTranscription = run + run.startSetup { [weak self] in guard let self else { return } - await self.startFilePipeline( + try await self.startFilePipeline( + run: run, with: newContinuation, audioFileURL: audioFile, options: options, - progressHandler: progressHandler, - generation: generation + progressHandler: progressHandler ) } @@ -133,52 +150,28 @@ public extension SpeechSession { private extension SpeechSession { func startFilePipeline( + run: FileTranscriptionRun, with streamContinuation: AsyncThrowingStream.Continuation, audioFileURL: URL, options: FileTranscriptionOptions, - progressHandler: (@Sendable (Double) -> Void)?, - generation: Int - ) async { - do { - try Task.checkCancellation() - let validation = try validateAudioFile(at: audioFileURL, options: options) - try await ensureSpeechRecognitionAuthorization(context: "for file transcription") - try Task.checkCancellation() - let shouldUseNativeAnalyzer = shouldUseNativeFileAnalyzer(progressHandler: progressHandler) - try await setUpFilePipeline( - with: streamContinuation, - contextualStrings: options.contextualStrings, - startAnalyzerImmediately: !shouldUseNativeAnalyzer, - generation: generation - ) - try Task.checkCancellation() - let handler = progressHandler - fileIngestionTask = Task { [weak self] in - guard let self else { return } - - do { - let completed = try await self.feedAudioFile(validation, progressHandler: handler) - - if completed, let handler { - await MainActor.run { - handler(1.0) - } - } - } catch is CancellationError { - // Swallow cancellation triggered by cleanup. - } catch { - await self.finishWithStartupError(error, generation: generation) - } - } - } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) - } catch { - if Self.shouldLog(.error) { - Self.logger.error("File transcription pipeline failed: \(error.localizedDescription, privacy: .public)") - } - pipelineTask = nil - await finishWithStartupError(error, generation: generation) + progressHandler: (@Sendable (Double) -> Void)? + ) async throws { + try Task.checkCancellation() + let validation = try validateAudioFile(at: audioFileURL, options: options) + try await ensureSpeechRecognitionAuthorization(context: "for file transcription") + try Task.checkCancellation() + let shouldUseNativeAnalyzer = shouldUseNativeFileAnalyzer(progressHandler: progressHandler) + try await setUpFilePipeline( + run: run, + with: streamContinuation, + contextualStrings: options.contextualStrings, + startAnalyzerImmediately: !shouldUseNativeAnalyzer + ) + try Task.checkCancellation() + run.startIngestion { [self] in + let completed = try await feedAudioFile(validation, progressHandler: progressHandler) + if completed { progressHandler?(1.0) } + return completed } } @@ -246,10 +239,10 @@ private extension SpeechSession { } func setUpFilePipeline( + run: FileTranscriptionRun, with streamContinuation: AsyncThrowingStream.Continuation, contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]?, - startAnalyzerImmediately: Bool, - generation: Int + startAnalyzerImmediately: Bool ) async throws { if Self.shouldLog(.notice) { Self.logger.notice("Starting file transcription pipeline") @@ -262,11 +255,9 @@ private extension SpeechSession { try Task.checkCancellation() activeResultKind = .speech - recognizerTask = createSpeechRecognizerTask( - transcriber: transcriber, - streamContinuation: streamContinuation, - generation: generation - ) + run.startResults(transcriber.results) { result in + streamContinuation.yield(result) + } streamingMode = .filePlayback setStatus(.transcribing) @@ -335,6 +326,8 @@ private extension SpeechSession { guard !Task.isCancelled else { return false } + guard processedFrames >= totalFrames else { return false } + try await self.finishAnalyzerInput() return !Task.isCancelled && processedFrames >= totalFrames diff --git a/Sources/AuralKit/SpeechSession+FileLifecycle.swift b/Sources/AuralKit/SpeechSession+FileLifecycle.swift new file mode 100644 index 0000000..34d116a --- /dev/null +++ b/Sources/AuralKit/SpeechSession+FileLifecycle.swift @@ -0,0 +1,114 @@ +import Foundation + +/// Owns the actual tasks for one file stream. Producers request retirement and +/// return; only the separate terminal task joins them, so none can join itself. +@MainActor +final class FileTranscriptionRun { + private var setupTask: Task? + private var ingestionTask: Task? + private var resultTask: Task? + private(set) var terminalTask: Task? + private var stoppingInput = false + private var terminalError: Error? + private let finalize: @MainActor () async throws -> Void + private let complete: @MainActor (Error?) async -> Void + + init( + finalize: @escaping @MainActor () async throws -> Void, + complete: @escaping @MainActor (Error?) async -> Void + ) { + self.finalize = finalize + self.complete = complete + } + + func startSetup(_ operation: @escaping @MainActor () async throws -> Void) { + precondition(setupTask == nil) + setupTask = Task { + do { + try Task.checkCancellation() + try await operation() + } catch { + requestRetirement(error: error) + } + } + } + + func startIngestion(_ operation: @escaping @MainActor () async throws -> Bool) { + precondition(ingestionTask == nil) + ingestionTask = Task { + do { + try Task.checkCancellation() + let completed = try await operation() + try Task.checkCancellation() + guard completed else { + throw SpeechSessionError.audioFileReadFailed(CocoaError( + .fileReadUnknown, + userInfo: [NSLocalizedDescriptionKey: "Audio input ended before all declared frames were read."] + )) + } + } catch { + requestRetirement(error: error) + } + } + // Setup can install a child after stop has already latched retirement. + if stoppingInput { ingestionTask?.cancel() } + } + + func startResults( + _ results: Sequence, + yield: @escaping @MainActor (Sequence.Element) -> Void + ) where Sequence: Sendable, Sequence.Element: Sendable { + precondition(resultTask == nil) + resultTask = Task { + do { + for try await result in results { + yield(result) + } + try Task.checkCancellation() + requestRetirement(cancelInput: false) + } catch { + requestRetirement(error: error) + } + } + } + + /// Latch synchronously before any suspension. Concurrent callers receive + /// the same work, including callers arriving during finalization/drain. + @discardableResult + func requestRetirement(error: Error? = nil, cancelInput: Bool = true) -> Task { + if let terminalTask { + if !stoppingInput, cancelInput { + terminalError = error + stoppingInput = true + setupTask?.cancel() + ingestionTask?.cancel() + } + return terminalTask + } + terminalError = error + stoppingInput = cancelInput + if cancelInput { + setupTask?.cancel() + ingestionTask?.cancel() + } + let terminal = Task { + await setupTask?.value + if stoppingInput { ingestionTask?.cancel() } + await ingestionTask?.value + // Keep results alive while finalization publishes its last chunks. + do { + try await finalize() + } catch { + if terminalError == nil { terminalError = error } + resultTask?.cancel() + } + await resultTask?.value + await complete(terminalError) + setupTask = nil + ingestionTask = nil + resultTask = nil + } + terminalTask = terminal + return terminal + } +} diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 9025f0c..4e53543 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -87,6 +87,11 @@ extension SpeechSession { /// (from streams that were already replaced or finished) are ignored. func handleStreamTermination(generation: Int) async { guard generation == sessionGeneration else { return } + if let fileTranscription { + prepareForStop() + await fileTranscription.requestRetirement().value + return + } prepareForStop() await cleanup(cancelRecognizer: true, generation: generation) await finishStream(error: nil, generation: generation) @@ -277,10 +282,6 @@ extension SpeechSession { let task = recognizerTask recognizerTask = nil - let ingestionTask = fileIngestionTask - fileIngestionTask = nil - ingestionTask?.cancel() - if cancelRecognizer { if Self.shouldLog(.debug) { Self.logger.debug("Cancelling recognizer task") diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 03c211c..d4098b8 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -96,7 +96,7 @@ public final class SpeechSession { var continuation: TranscriptionContinuation? var recognizerTask: Task? var pipelineTask: Task? - var fileIngestionTask: Task? + var fileTranscription: FileTranscriptionRun? var streamingMode: StreamingMode = .inactive /// Incremented for every accepted start so stale termination handlers can be ignored. var sessionGeneration: Int = 0 @@ -347,7 +347,13 @@ public final class SpeechSession { /// /// Safe to call even if `startTranscribing()` has not been invoked or the stream has already /// completed; the method simply waits for cleanup and returns. + /// For file transcription, return also joins setup, ingestion and result reading. public func stopTranscribing() async { + if let fileTranscription { + prepareForStop() + await fileTranscription.requestRetirement().value + return + } let generation = sessionGeneration prepareForStop() await cleanup(cancelRecognizer: true, generation: generation) diff --git a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift new file mode 100644 index 0000000..fb05da6 --- /dev/null +++ b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift @@ -0,0 +1,211 @@ +import Foundation +import Testing +@testable import AuralKit + +/// Deliberately ignores cancellation so a join must await the actual operation. +@MainActor +private final class FileJoinGate { + private var opened = false + private var waiters: [CheckedContinuation] = [] + + func wait() async { + if opened { return } + await withCheckedContinuation { waiters.append($0) } + } + + func open() { + opened = true + let pending = waiters + waiters.removeAll() + for waiter in pending { waiter.resume() } + } +} + +@Suite("Joined file retirement") +@MainActor +struct FileTranscriptionJoinTests { + /// Every test body is nonthrowing. Always release gates, close the sequence, + /// and join the owner, even when an expectation records a failure. + private func withRun( + failFinalization: Bool = false, + _ body: (FileTranscriptionRun, [FileJoinGate], AsyncThrowingStream, + AsyncThrowingStream.Continuation, FileJoinRecord) async -> Void + ) async { + let gates = (0..<6).map { _ in FileJoinGate() } + let record = FileJoinRecord() + let (stream, continuation) = AsyncThrowingStream.makeStream() + let run = FileTranscriptionRun(finalize: { + record.events.append("finalize") + gates[3].open() + await gates[4].wait() + if failFinalization { throw CocoaError(.fileReadUnknown) } + continuation.yield(42) + continuation.finish() + }, complete: { error in + record.error = error + record.events.append("complete") + }) + await body(run, gates, stream, continuation, record) + for gate in gates { gate.open() } + continuation.finish() + await run.requestRetirement().value + } + + @Test("Stop joins suspended setup and a late-installed reader") + func stopDuringSetup() async { + await withRun { run, gates, stream, _, record in + run.startSetup { + gates[0].open() + await gates[1].wait() + run.startResults(stream) { record.values.append($0) } + run.startIngestion { record.events.append("unexpected input"); return true } + record.events.append("setup exited") + } + await gates[0].wait() + let terminal = run.requestRetirement() + gates[1].open() + await gates[3].wait() + #expect(record.events == ["setup exited", "finalize"]) + gates[4].open() + await terminal.value + #expect(record.values == [42]) + #expect(record.events.last == "complete") + } + } + + @Test("Stop joins input before finalization and concurrent callers share completion") + func stopDuringInput() async { + await withRun { run, gates, stream, _, record in + run.startSetup { + run.startResults(stream) { record.values.append($0) } + run.startIngestion { + gates[0].open() + await gates[1].wait() + record.events.append("input exited") + return true + } + } + await gates[0].wait() + let first = Task { await run.requestRetirement().value; record.events.append("stop one") } + let second = Task { await run.requestRetirement().value; record.events.append("stop two") } + // Latch before releasing the input; the two Tasks join that same owner. + let terminal = run.requestRetirement() + gates[1].open() + await gates[3].wait() + #expect(record.events == ["input exited", "finalize"]) + gates[4].open() + await terminal.value + await first.value + await second.value + #expect(record.events.filter { $0 == "finalize" }.count == 1) + #expect(Array(record.events.prefix(3)) == ["input exited", "finalize", "complete"]) + #expect(Set(record.events.suffix(2)) == Set(["stop one", "stop two"])) + #expect(record.error == nil) + } + } + + @Test("Finalizer-generated results drain before completion") + func finalResultDrain() async { + await withRun { run, gates, stream, _, record in + run.startSetup { + run.startResults(stream) { record.values.append($0); record.events.append("result") } + run.startIngestion { gates[0].open(); return true } + } + await gates[0].wait() + let terminal = run.requestRetirement() + await gates[3].wait() + #expect(record.values.isEmpty) + #expect(!record.events.contains("complete")) + gates[4].open() + await terminal.value + #expect(record.values == [42]) + #expect(record.events.suffix(2) == ["result", "complete"]) + } + } + + @Test("Natural reader completion joins ingestion without cancelling it") + func naturalCompletion() async { + await withRun { run, gates, stream, continuation, record in + run.startSetup { + run.startResults(stream) { record.values.append($0) } + run.startIngestion { + gates[0].open() + await gates[1].wait() + #expect(!Task.isCancelled) + record.events.append("input exited") + return true + } + } + await gates[0].wait() + continuation.finish() + gates[1].open() + await gates[3].wait() + gates[4].open() + await run.terminalTask?.value + #expect(record.events == ["input exited", "finalize", "complete"]) + #expect(record.error == nil) + } + } + + @Test("Finalizer failure cancels and joins a waiting reader") + func finalizationFailure() async { + await withRun(failFinalization: true) { run, gates, stream, _, record in + run.startSetup { + run.startResults(stream) { record.values.append($0) } + gates[0].open() + } + await gates[0].wait() + let terminal = run.requestRetirement() + await gates[3].wait() + gates[4].open() + await terminal.value + #expect(record.error is CocoaError) + #expect(record.events.last == "complete") + } + } + + @Test("Independent result cancellation settles the stream") + func readerCancellation() async { + await withRun { run, gates, stream, continuation, record in + run.startSetup { + run.startResults(stream) { record.values.append($0) } + gates[0].open() + } + await gates[0].wait() + continuation.finish(throwing: CancellationError()) + await gates[3].wait() + gates[4].open() + // Finalization was reached by the reader's request, without public stop. + await run.terminalTask?.value + #expect(record.error is CancellationError) + } + } + + @Test("Incomplete input and independent input cancellation are failures", arguments: [false, true]) + func incompleteInput(cancelled: Bool) async { + await withRun { run, gates, stream, _, record in + run.startSetup { + run.startResults(stream) { record.values.append($0) } + run.startIngestion { + if cancelled { throw CancellationError() } + return false + } + } + await gates[3].wait() + gates[4].open() + await run.terminalTask?.value + if cancelled { + #expect(record.error is CancellationError) + } else { + #expect(record.error is SpeechSessionError) + } + } + } +} + +@MainActor +private final class FileJoinRecord { + var events: [String] = [] + var values: [Int] = [] + var error: Error? +} From 2c809b0e4dd361d03ef0ff8583b376aa5ea7d7b3 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:12:51 -0500 Subject: [PATCH 07/70] Preserve the Apple speech sample copyright and permission notice --- LICENSE-Apple-SpeechExample.txt | 8 ++++++++ README.md | 2 ++ 2 files changed, 10 insertions(+) create mode 100644 LICENSE-Apple-SpeechExample.txt diff --git a/LICENSE-Apple-SpeechExample.txt b/LICENSE-Apple-SpeechExample.txt new file mode 100644 index 0000000..de2de43 --- /dev/null +++ b/LICENSE-Apple-SpeechExample.txt @@ -0,0 +1,8 @@ +Copyright © 2025 Apple Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/README.md b/README.md index cd6302c..69f75e0 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription This project would not have been possible without Apple's excellent sample code. The implementation is heavily inspired by [Bringing advanced speech-to-text capabilities to your app](https://developer.apple.com/documentation/Speech/bringing-advanced-speech-to-text-capabilities-to-your-app), which shows how to add live speech-to-text transcription with `SpeechAnalyzer`. +`BufferConverter` adapts the sample's `Helpers/BufferConversion.swift`. Apple's original notice is retained in [LICENSE-Apple-SpeechExample.txt](LICENSE-Apple-SpeechExample.txt), from the [published sample download](https://docs-assets.developer.apple.com/published/e40c20fc5641/BringingAdvancedSpeechToTextCapabilitiesToYourApp.zip). AuralKit adds concurrency annotations, package-specific errors and input-format invalidation; the converter is not an unchanged copy. + ## Quick Start ```swift From 0c9729c60819b5185e11ddb820f45543a4d37eb4 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:18:12 -0500 Subject: [PATCH 08/70] Join concurrent screen cleanup and fence superseded resume outcomes --- .../AuralKit/ScreenCapturePipelineHooks.swift | 20 + .../AuralKit/ScreenCaptureTransitions.swift | 32 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 28 +- .../SpeechSession+ScreenCapture.swift | 225 ++++---- Sources/AuralKit/SpeechSession.swift | 9 +- .../ScreenCaptureTransitionTests.swift | 492 ++++++++++++------ 6 files changed, 545 insertions(+), 261 deletions(-) create mode 100644 Sources/AuralKit/ScreenCapturePipelineHooks.swift diff --git a/Sources/AuralKit/ScreenCapturePipelineHooks.swift b/Sources/AuralKit/ScreenCapturePipelineHooks.swift new file mode 100644 index 0000000..75ed7d6 --- /dev/null +++ b/Sources/AuralKit/ScreenCapturePipelineHooks.swift @@ -0,0 +1,20 @@ +import AVFoundation +import Speech + +/// Instance-local native boundaries. Production keeps native authorization and analysis; +/// controlled collaborators can drive the same public setup and teardown orchestration. +@available(iOS 26.0, macOS 14.0, *) +struct ScreenCapturePreparedAnalysis { + let format: AVAudioFormat + let inputs: AsyncStream.Continuation + let finalize: @MainActor () async -> Void +} + +@available(iOS 26.0, macOS 14.0, *) +struct ScreenCapturePipelineHooks { + let authorize: @MainActor () async throws -> Void + let prepareAnalysis: @MainActor () async throws -> ScreenCapturePreparedAnalysis + let makeProvider: @MainActor ( + AVAudioFormat, AsyncStream.Continuation, @escaping @Sendable (Error) -> Void + ) -> any ScreenCaptureInput +} diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index 8022314..3c1cef6 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -8,6 +8,15 @@ protocol ScreenCaptureStream: AnyObject { func stopCapture() async throws } +/// Carries admission through async returns. The public caller checks ownership at +/// the instant it publishes status or propagates a failure into session teardown. +@available(iOS 26.0, macOS 14.0, *) +@MainActor +struct ScreenCaptureResumeOutcome { + let isCurrent: @MainActor () -> Bool + let error: Error? +} + /// Serializes capture side effects across suspension. Admission changes intent immediately; /// only internal operations are joined, never a public caller that may await session cleanup. @available(iOS 26.0, macOS 14.0, *) @@ -46,11 +55,26 @@ final class ScreenCaptureTransitions { return enqueue { try await self.stopCurrent() } } - func resume() -> Task { - guard desiredState != .stopped else { return enqueue { throw CancellationError() } } - desiredState = .running + func resume() -> Task { + desiredState = desiredState == .stopped ? .stopped : .running let admitted = revision - return enqueue { try await self.startCurrent(revision: admitted) } + let previous = tail + let operation = Task { @MainActor in + _ = try? await previous?.value + let error: Error? + do { + try await self.startCurrent(revision: admitted) + error = nil + } catch let failure { + error = failure + } + return ScreenCaptureResumeOutcome( + isCurrent: { self.desiredState == .running && self.revision == admitted }, + error: error + ) + } + tail = Task { _ = await operation.value } + return operation } func stop() -> Task { diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 9025f0c..5225b1d 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -258,12 +258,27 @@ extension SpeechSession { /// Tear down the active pipeline. /// - /// All session state is detached synchronously up front so that concurrent teardowns (or a - /// new session starting once the stream finishes) never observe partially-cleared state; the - /// 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. + /// One internal terminal task owns detachment, capture shutdown, analyzer + /// finalization and locale release. Concurrent callers join that same task even + /// after the provider and analyzer have been detached. Generation checks keep + /// an obsolete terminal task from touching a successor's shared state. func cleanup(cancelRecognizer: Bool, generation: Int) async { + guard generation == sessionGeneration else { return } + if let terminal = cleanupTask, terminal.generation == generation { + await terminal.task.value + return + } + // Own only internal teardown. Neither a public caller nor setup producer is + // joined here: either may be suspended awaiting this very terminal task. + let terminal = Task { @MainActor in + await self.performCleanup(cancelRecognizer: cancelRecognizer, generation: generation) + if self.cleanupTask?.generation == generation { self.cleanupTask = nil } + } + cleanupTask = (generation, terminal) + await terminal.value + } + + private func performCleanup(cancelRecognizer: Bool, generation: Int) async { guard generation == sessionGeneration else { return } if Self.shouldLog(.debug) { Self.logger.debug("Cleanup started (cancelRecognizer: \(cancelRecognizer, privacy: .public))") @@ -296,9 +311,12 @@ extension SpeechSession { #if os(iOS) shouldResumeAfterInterruption = false #endif + let analysisFinalizer = screenCaptureAnalysisFinalizer + screenCaptureAnalysisFinalizer = nil let detached = detachTranscriberState() await stopScreenCaptureStreamingIfNeeded() await finalizeDetachedTranscriberState(detached) + await analysisFinalizer?() guard generation == sessionGeneration else { return } await modelManager.releaseLocales() diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 24b2cb6..f2e9914 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -5,6 +5,49 @@ import Speech // swiftlint:disable file_length +/// Internal capture lifetime boundary; production uses ScreenCaptureKit below. +@available(iOS 26.0, macOS 14.0, *) +protocol ScreenCaptureInput: AnyObject { + @MainActor func start() async throws + @MainActor func pause() async + @MainActor func resume() async throws + @MainActor func resumeOutcome() async -> ScreenCaptureResumeOutcome + @MainActor func stop() async +} + +@available(iOS 26.0, macOS 14.0, *) +extension ScreenCaptureInput { + @MainActor + func resumeOutcome() async -> ScreenCaptureResumeOutcome { + do { + try await resume() + return ScreenCaptureResumeOutcome(isCurrent: { true }, error: nil) + } catch { + return ScreenCaptureResumeOutcome(isCurrent: { true }, error: error) + } + } +} + +@available(iOS 26.0, macOS 14.0, *) +extension SpeechSession { + func pauseScreenCaptureStreamingIfNeeded() async { + await screenCaptureInputProvider?.pause() + } + + func resumeScreenCaptureStreamingIfNeeded() async throws -> ScreenCaptureResumeOutcome { + guard let provider = screenCaptureInputProvider else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + return await provider.resumeOutcome() + } + + func stopScreenCaptureStreamingIfNeeded() async { + let provider = screenCaptureInputProvider + screenCaptureInputProvider = nil + await provider?.stop() + } +} + #if canImport(ScreenCaptureKit) @preconcurrency import ScreenCaptureKit @@ -100,15 +143,25 @@ extension SpeechSession { } try Task.checkCancellation() - try await ensureSpeechRecognitionAuthorization(context: "for screen capture transcription") - try Task.checkCancellation() - let transcriber = try await setUpSpeechTranscriber(contextualStrings: contextualStrings) + if let hooks = screenCapturePipelineHooks { + try await hooks.authorize() + try Task.checkCancellation() + let prepared = try await hooks.prepareAnalysis() + analyzerFormat = prepared.format + inputBuilder = prepared.inputs + screenCaptureAnalysisFinalizer = prepared.finalize + } else { + try await ensureSpeechRecognitionAuthorization(context: "for screen capture transcription") + try Task.checkCancellation() + let transcriber = try await setUpSpeechTranscriber(contextualStrings: contextualStrings) + try Task.checkCancellation() + recognizerTask = createSpeechRecognizerTask( + transcriber: transcriber, + streamContinuation: streamContinuation, + generation: generation + ) + } try Task.checkCancellation() - recognizerTask = createSpeechRecognizerTask( - transcriber: transcriber, - streamContinuation: streamContinuation, - generation: generation - ) try await setUpScreenCaptureStreaming(options: options, generation: generation) try Task.checkCancellation() @@ -135,48 +188,22 @@ extension SpeechSession { throw SpeechSessionError.invalidAudioDataType } - let provider = ScreenCaptureAudioInputProvider( - options: options, - targetFormat: analyzerFormat, - inputContinuation: inputBuilder, - onFailure: { [weak self] error in - Task { @MainActor [weak self] in - await self?.finishFromRecognizerTask(error: error, generation: generation) - } + let onFailure: @Sendable (Error) -> Void = { [weak self] error in + Task { @MainActor [weak self] in + await self?.finishFromRecognizerTask(error: error, generation: generation) } - ) - screenCaptureInputProvider = provider - try await provider.start() - } -} - -@MainActor -extension SpeechSession { - func pauseScreenCaptureStreamingIfNeeded() async { - guard #available(iOS 27.0, macOS 14.0, *) else { return } - guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { return } - await provider.pause() - } - - func resumeScreenCaptureStreamingIfNeeded() async throws { - guard #available(iOS 27.0, macOS 14.0, *) else { - throw SpeechSessionError.screenCaptureUnavailable } - guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { - throw SpeechSessionError.recognitionStreamSetupFailed + let provider: any ScreenCaptureInput + if let makeProvider = screenCapturePipelineHooks?.makeProvider { + provider = makeProvider(analyzerFormat, inputBuilder, onFailure) + } else { + provider = ScreenCaptureAudioInputProvider( + options: options, targetFormat: analyzerFormat, + inputContinuation: inputBuilder, onFailure: onFailure + ) } - try await provider.resume() - } - - func stopScreenCaptureStreamingIfNeeded() async { - // Detach synchronously so concurrent teardowns or a subsequent session never observe - // a provider that is already being stopped. - let detachedProvider = screenCaptureInputProvider - screenCaptureInputProvider = nil - - guard #available(iOS 27.0, macOS 14.0, *) else { return } - guard let provider = detachedProvider as? ScreenCaptureAudioInputProvider else { return } - await provider.stop() + screenCaptureInputProvider = provider + try await provider.start() } } @@ -200,7 +227,7 @@ private final class NativeScreenCaptureStream: ScreenCaptureStream { } @available(iOS 27.0, macOS 14.0, *) -final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamDelegate, +final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStreamOutput, SCStreamDelegate, SCContentSharingPickerObserver, @unchecked Sendable { private let options: SpeechSession.ScreenCaptureTranscriptionOptions @@ -212,6 +239,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD private let bufferConverter = BufferConverter() @MainActor private let transitions: ScreenCaptureTransitions + private let presentPicker: @MainActor (ScreenCaptureAudioInputProvider) -> Void private let dismissPicker: @MainActor (any SCContentSharingPickerObserver) -> Void private var selectionContinuation: CheckedContinuation? private var stopped = false @@ -226,6 +254,15 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD inputContinuation: AsyncStream.Continuation, onFailure: @escaping @Sendable (Error) -> Void, transitions: ScreenCaptureTransitions = ScreenCaptureTransitions(), + presentPicker: @escaping @MainActor (ScreenCaptureAudioInputProvider) -> Void = { provider in + let picker = SCContentSharingPicker.shared + let configuration = SCContentSharingPickerConfiguration() + picker.configuration = configuration + picker.defaultConfiguration = configuration + picker.add(provider) + picker.isActive = true + picker.present() + }, dismissPicker: @escaping @MainActor (any SCContentSharingPickerObserver) -> Void = { observer in let picker = SCContentSharingPicker.shared picker.isActive = false @@ -237,6 +274,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD self.inputContinuation = inputContinuation self.onFailure = onFailure self.transitions = transitions + self.presentPicker = presentPicker self.dismissPicker = dismissPicker super.init() } @@ -245,18 +283,11 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD func start() async throws { try Task.checkCancellation() guard !stopped else { throw CancellationError() } - let picker = SCContentSharingPicker.shared - let configuration = SCContentSharingPickerConfiguration() - picker.configuration = configuration - picker.defaultConfiguration = configuration - picker.add(self) - picker.isActive = true - // Cleanup stops this provider before finalizing detached analyzer state. // stop() resumes pending selection and joins admitted picker updates. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in selectionContinuation = continuation - picker.present() + presentPicker(self) } try Task.checkCancellation() } @@ -269,7 +300,14 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD @MainActor func resume() async throws { guard !stopped else { throw CancellationError() } - try await transitions.resume().value + let outcome = await resumeOutcome() + guard outcome.isCurrent() else { return } + if let error = outcome.error { throw error } + } + + @MainActor + func resumeOutcome() async -> ScreenCaptureResumeOutcome { + await transitions.resume().value } @MainActor @@ -301,20 +339,19 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD if let updatedStream { guard (self.transitions.stream as? NativeScreenCaptureStream)?.stream === updatedStream else { return } } - let id = UUID() - self.pickerUpdateID = id - self.captureTasks[id] = Task { @MainActor in - defer { self.captureTasks[id] = nil } - guard !self.stopped, self.pickerUpdateID == id else { return } - do { - try await self.beginCapture(with: selectedFilter) - guard !self.stopped, self.pickerUpdateID == id else { return } - self.resumeSelection() - } catch { - guard !self.stopped, self.pickerUpdateID == id else { return } - if !self.resumeSelection(throwing: error) { - self.onFailure(SpeechSessionError.screenCaptureFailed(error)) - } + self.selectStream { [self] in + let streamConfiguration = SCStreamConfiguration() + streamConfiguration.capturesAudio = true + streamConfiguration.sampleRate = Int(targetFormat.sampleRate) + streamConfiguration.channelCount = Int(targetFormat.channelCount) + streamConfiguration.excludesCurrentProcessAudio = options.excludesCurrentProcessAudio + streamConfiguration.width = 2 + streamConfiguration.height = 2 + + let captureStream = SCStream(filter: selectedFilter, configuration: streamConfiguration, delegate: self) + try captureStream.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) + return NativeScreenCaptureStream(stream: captureStream) { [weak self] stream in + self?.markStreamForIntentionalStop(stream) } } } @@ -367,25 +404,27 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } } + /// Common admission for the native picker callback and controlled capture collaborators. @MainActor - private func beginCapture(with filter: SCContentFilter) async throws { - guard !stopped else { throw CancellationError() } - let operation = transitions.replace { [self] in - let streamConfiguration = SCStreamConfiguration() - streamConfiguration.capturesAudio = true - streamConfiguration.sampleRate = Int(targetFormat.sampleRate) - streamConfiguration.channelCount = Int(targetFormat.channelCount) - streamConfiguration.excludesCurrentProcessAudio = options.excludesCurrentProcessAudio - streamConfiguration.width = 2 - streamConfiguration.height = 2 - - let captureStream = SCStream(filter: filter, configuration: streamConfiguration, delegate: self) - try captureStream.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) - return NativeScreenCaptureStream(stream: captureStream) { [weak self] stream in - self?.markStreamForIntentionalStop(stream) + func selectStream(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) { + guard !stopped else { return } + let operation = transitions.replace(makeStream: makeStream) + let id = UUID() + self.pickerUpdateID = id + self.captureTasks[id] = Task { @MainActor in + defer { self.captureTasks[id] = nil } + guard !self.stopped, self.pickerUpdateID == id else { return } + do { + try await operation.value + guard !self.stopped, self.pickerUpdateID == id else { return } + self.resumeSelection() + } catch { + guard !self.stopped, self.pickerUpdateID == id else { return } + if !self.resumeSelection(throwing: error) { + self.onFailure(SpeechSessionError.screenCaptureFailed(error)) + } } } - try await operation.value } @discardableResult @@ -453,16 +492,4 @@ public extension SpeechSession { } } -@MainActor -extension SpeechSession { - func pauseScreenCaptureStreamingIfNeeded() async {} - - func resumeScreenCaptureStreamingIfNeeded() async throws { - throw SpeechSessionError.screenCaptureUnavailable - } - - func stopScreenCaptureStreamingIfNeeded() async { - screenCaptureInputProvider = nil - } -} #endif diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index b45a812..16097b9 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -73,7 +73,9 @@ public final class SpeechSession { var analyzerFormat: AVAudioFormat? var nativeCaptureSession: AVCaptureSession? var nativeCaptureAnalysisTask: Task? - var screenCaptureInputProvider: AnyObject? + var screenCapturePipelineHooks: ScreenCapturePipelineHooks? + var screenCaptureAnalysisFinalizer: (@MainActor () async -> Void)? + var screenCaptureInputProvider: (any ScreenCaptureInput)? var voiceActivationConfiguration: VoiceActivationConfiguration? var customVocabularyDescriptor: CustomVocabulary? var customVocabularyConfiguration: SFSpeechLanguageModel.Configuration? @@ -95,6 +97,7 @@ public final class SpeechSession { // Stream state management var continuation: TranscriptionContinuation? var recognizerTask: Task? + var cleanupTask: (generation: Int, task: Task)? var pipelineTask: Task? var fileIngestionTask: Task? var streamingMode: StreamingMode = .inactive @@ -380,7 +383,9 @@ public final class SpeechSession { let generation = sessionGeneration do { if streamingMode == .screenCapture { - try await resumeScreenCaptureStreamingIfNeeded() + let outcome = try await resumeScreenCaptureStreamingIfNeeded() + guard outcome.isCurrent() else { return } + if let error = outcome.error { throw error } } else { try startAudioStreaming() } diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index 4accf52..95afcba 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -3,26 +3,84 @@ import Speech import Testing @testable import AuralKit -/// Cancellation-independent latches: a cancelled operation still owns its OS call -/// until the fixture explicitly releases it. No readiness depends on scheduling delays. +private enum CaptureFixtureError: Error { case deadline, startFailed } + +/// Each waiter owns its deadline and can be removed by cancellation. No timeout +/// task group can be stranded joining a checked continuation that ignores cancel. @MainActor private final class CaptureGate { private var opened = false - private var waiters: [CheckedContinuation] = [] + private var waiters: [UUID: CheckedContinuation] = [:] + var waiterCount: Int { waiters.count } - func wait() async { + func wait(timeoutNanoseconds: UInt64 = 3_000_000_000) async throws { + try Task.checkCancellation() if opened { return } - await withCheckedContinuation { waiters.append($0) } + let id = UUID() + let deadline = Task { @MainActor in + do { try await Task.sleep(nanoseconds: timeoutNanoseconds) } catch { return } + self.remove(id, error: CaptureFixtureError.deadline) + } + defer { deadline.cancel() } + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + if Task.isCancelled { continuation.resume(throwing: CancellationError()) } + else { waiters[id] = continuation } + } + } onCancel: { + Task { @MainActor in self.remove(id, error: CancellationError()) } + } + } + + private func remove(_ id: UUID, error: Error) { + waiters.removeValue(forKey: id)?.resume(throwing: error) } func open() { opened = true - let pending = waiters + let pending = waiters.values waiters.removeAll() for waiter in pending { waiter.resume() } } } +/// Async cleanup opens all gates before joining every task admitted by the test, +/// including on a failed readiness wait. Errors remain visible to the test body. +@MainActor +private final class CaptureFixture { + private var gates: [CaptureGate] = [] + private var joins: [Task] = [] + private var cancellations: [() -> Void] = [] + func gate() -> CaptureGate { + let gate = CaptureGate() + gates.append(gate) + return gate + } + func track(_ task: Task) -> Task { + cancellations.append { task.cancel() } + joins.append(Task { _ = await task.result }) + return task + } + func releaseAll() { gates.forEach { $0.open() } } + func cleanUp() async { + releaseAll() + cancellations.forEach { $0() } + for join in joins { await join.value } + } +} + +@MainActor +private func withCaptureFixture(_ body: (CaptureFixture) async throws -> Void) async throws { + let fixture = CaptureFixture() + do { + try await body(fixture) + await fixture.cleanUp() + } catch { + await fixture.cleanUp() + throw error + } +} + @available(iOS 26.0, macOS 26.0, *) @MainActor private final class ControlledCaptureStream: ScreenCaptureStream { @@ -33,188 +91,320 @@ private final class ControlledCaptureStream: ScreenCaptureStream { var startRelease: CaptureGate? var stopEntered: CaptureGate? var stopRelease: CaptureGate? + var startError: Error? func startCapture() async throws { starts += 1 startEntered?.open() - await startRelease?.wait() + try await startRelease?.wait() + if let startError { throw startError } capturing = true } - func stopCapture() async throws { stops += 1 stopEntered?.open() - await stopRelease?.wait() + try await stopRelease?.wait() capturing = false } } @Suite("Screen capture transitions") struct ScreenCaptureTransitionTests { + @Test("Cancellation removes a readiness waiter") + @MainActor + func readinessCancellation() async throws { + try await withCaptureFixture { fixture in + let gate = fixture.gate() + let entered = fixture.gate() + let wait = fixture.track(Task { @MainActor in + entered.open() + try await gate.wait() + }) + try await entered.wait() + wait.cancel() + do { try await wait.value; Issue.record("Cancelled wait returned successfully") } + catch is CancellationError {} // Expected, including cancellation before registration. + #expect(gate.waiterCount == 0) + } + } + + @Test("A missing readiness signal expires and removes its waiter") + @MainActor + func readinessDeadline() async throws { + try await withCaptureFixture { fixture in + let gate = fixture.gate() + do { + try await gate.wait(timeoutNanoseconds: 1_000_000) + Issue.record("Unopened gate returned successfully") + } catch CaptureFixtureError.deadline {} + #expect(gate.waiterCount == 0) + } + } + @Test("A picker replacement stopped across pause never starts the new stream") @MainActor - func replacementHonorsAdmittedPause() async { + func replacementHonorsAdmittedPause() async throws { guard #available(iOS 26.0, macOS 26.0, *) else { return } - let owner = ScreenCaptureTransitions() - let old = ControlledCaptureStream() - let replacement = ControlledCaptureStream() - let entered = CaptureGate() - let release = CaptureGate() - defer { release.open(); entered.open() } - _ = try? await owner.replace { old }.value - old.stopEntered = entered - old.stopRelease = release - let update = owner.replace { replacement } - await entered.wait() - let pause = owner.pause() - #expect(owner.desiredState == .paused) - release.open() - _ = try? await update.value - _ = try? await pause.value - #expect(owner.stream === replacement) - #expect(!owner.isRunning) - #expect(!old.capturing) - #expect(replacement.starts == 0) - // A later explicit resume starts the selected stream, not the old one. - _ = try? await owner.resume().value - #expect(replacement.starts == 1) - #expect(old.starts == 1) - _ = try? await owner.stop().value - } - - @Test("Overlapping picker replacements cannot install an obsolete stream after stop") + try await withCaptureFixture { fixture in + let owner = ScreenCaptureTransitions() + let old = ControlledCaptureStream() + let replacement = ControlledCaptureStream() + let entered = fixture.gate(), release = fixture.gate() + try await fixture.track(owner.replace { old }).value + old.stopEntered = entered; old.stopRelease = release + let update = fixture.track(owner.replace { replacement }) + try await entered.wait() + let pause = fixture.track(owner.pause()) + #expect(owner.desiredState == .paused) + release.open() + try await update.value + try await pause.value + #expect(owner.stream === replacement) + #expect(!owner.isRunning) + #expect(!old.capturing) + #expect(replacement.starts == 0) + let resumed = await fixture.track(owner.resume()).value + #expect(resumed.isCurrent()) + #expect(resumed.error == nil) + #expect(replacement.starts == 1) + #expect(old.starts == 1) + try await fixture.track(owner.stop()).value + } + } + + @Test("Stop admitted during old shutdown prevents either replacement from starting") @MainActor - func replacementIdentityAcrossStop() async { + func replacementIdentityAcrossStop() async throws { guard #available(iOS 26.0, macOS 26.0, *) else { return } - let owner = ScreenCaptureTransitions() - let old = ControlledCaptureStream() - let obsolete = ControlledCaptureStream() - let current = ControlledCaptureStream() - let entered = CaptureGate() - let release = CaptureGate() - defer { release.open(); entered.open() } - _ = try? await owner.replace { old }.value - old.stopEntered = entered - old.stopRelease = release - var obsoleteCreated = false - let first = owner.replace { obsoleteCreated = true; return obsolete } - await entered.wait() - let second = owner.replace { current } - release.open() - _ = try? await first.value - _ = try? await second.value - #expect(!obsoleteCreated) - #expect(obsolete.starts == 0) - #expect(owner.stream === current) - #expect(current.capturing) - #expect(old.stops == 1) - _ = try? await owner.stop().value + try await withCaptureFixture { fixture in + let owner = ScreenCaptureTransitions() + let old = ControlledCaptureStream(), obsolete = ControlledCaptureStream(), current = ControlledCaptureStream() + let entered = fixture.gate(), release = fixture.gate() + try await fixture.track(owner.replace { old }).value + old.stopEntered = entered; old.stopRelease = release + let first = fixture.track(owner.replace { obsolete }) + try await entered.wait() + let second = fixture.track(owner.replace { current }) + let stop = fixture.track(owner.stop()) + #expect(obsolete.starts == 0 && current.starts == 0) + release.open() + try await first.value + try await second.value + try await stop.value + #expect(owner.stream == nil) + #expect(!old.capturing) + #expect(obsolete.starts == 0 && current.starts == 0) + } } @Test("A superseded start compensates before its successor can start") @MainActor - func replacementIdentityAcrossStart() async { + func replacementIdentityAcrossStart() async throws { guard #available(iOS 26.0, macOS 26.0, *) else { return } - let owner = ScreenCaptureTransitions() - let obsolete = ControlledCaptureStream() - let current = ControlledCaptureStream() - let startEntered = CaptureGate() - let startRelease = CaptureGate() - let stopEntered = CaptureGate() - let stopRelease = CaptureGate() - defer { - startRelease.open(); stopRelease.open() - startEntered.open(); stopEntered.open() + try await withCaptureFixture { fixture in + let owner = ScreenCaptureTransitions() + let obsolete = ControlledCaptureStream(), current = ControlledCaptureStream() + let startEntered = fixture.gate(), startRelease = fixture.gate() + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + obsolete.startEntered = startEntered; obsolete.startRelease = startRelease + obsolete.stopEntered = stopEntered; obsolete.stopRelease = stopRelease + let first = fixture.track(owner.replace { obsolete }) + try await startEntered.wait() + let second = fixture.track(owner.replace { current }) + startRelease.open() + try await stopEntered.wait() + #expect(current.starts == 0) + #expect(owner.stream === obsolete) + stopRelease.open() + try await first.value + try await second.value + #expect(!obsolete.capturing) + #expect(obsolete.stops == 1) + #expect(owner.stream === current) + #expect(current.starts == 1) + try await fixture.track(owner.stop()).value } - obsolete.startEntered = startEntered - obsolete.startRelease = startRelease - obsolete.stopEntered = stopEntered - obsolete.stopRelease = stopRelease - let first = owner.replace { obsolete } - await startEntered.wait() - let second = owner.replace { current } - startRelease.open() - await stopEntered.wait() - #expect(current.starts == 0) - #expect(owner.stream === obsolete) - stopRelease.open() - _ = try? await first.value - _ = try? await second.value - #expect(!obsolete.capturing) - #expect(obsolete.stops == 1) - #expect(owner.stream === current) - #expect(current.starts == 1) - #expect(owner.isRunning) - _ = try? await owner.stop().value } } #if canImport(ScreenCaptureKit) import ScreenCaptureKit +/// Replaces only authorization, native analyzer preparation/finalization and picker +/// presentation. Public setup, provider, picker admission, transitions and stop are real. +@available(iOS 27.0, macOS 26.0, *) +@MainActor +private final class PublicCaptureFixture { + let session = SpeechSession() + let owner = ScreenCaptureTransitions() + let stream = ControlledCaptureStream() + var provider: ScreenCaptureAudioInputProvider? + let presented: CaptureGate + let dismissed: CaptureGate + let finalized: CaptureGate + let finalizeRelease: CaptureGate + let terminal: CaptureGate + var consumerFinished = false + var consumerError: Error? + + init(_ fixture: CaptureFixture) { + presented = fixture.gate(); dismissed = fixture.gate() + finalized = fixture.gate(); finalizeRelease = fixture.gate(); terminal = fixture.gate() + session.screenCapturePipelineHooks = ScreenCapturePipelineHooks( + authorize: {}, + prepareAnalysis: { [self] in + let (_, inputs) = AsyncStream.makeStream() + return ScreenCapturePreparedAnalysis( + format: AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)!, + inputs: inputs, + finalize: { [self] in + finalized.open() + // A native call may ignore the cancelling caller until explicitly released. + let join = fixture.track(Task { @MainActor in try await finalizeRelease.wait() }) + do { try await join.value } catch { Issue.record("Finalization gate failed: \(error)") } + } + ) + }, + makeProvider: { [self] format, inputs, failure in + let provider = ScreenCaptureAudioInputProvider( + options: .init(), targetFormat: format, inputContinuation: inputs, + onFailure: failure, transitions: owner, + presentPicker: { [self] _ in presented.open() }, + dismissPicker: { [self] _ in dismissed.open() } + ) + self.provider = provider + return provider + } + ) + } + + func start(_ fixture: CaptureFixture, select: Bool = true) async throws { + let results = session.startTranscribingScreenCapture() + fixture.track(Task { @MainActor in + do { for try await _ in results {} } catch { consumerError = error } + consumerFinished = true + terminal.open() + }) + try await presented.wait() + if select { + provider?.selectStream { [self] in stream } + // Public pause waits until setup has published transcribing. Readiness is + // observed from the existing status stream, never a state setter or a delay. + let ready = fixture.gate() + let statuses = session.statusStream + fixture.track(Task { @MainActor in + for await status in statuses { + if status == .transcribing { ready.open(); return } + } + }) + try await ready.wait() + } + } + + func close(_ fixture: CaptureFixture) async { + fixture.releaseAll() + await fixture.track(Task { await session.stopTranscribing() }).value + session.screenCapturePipelineHooks = nil + } +} + extension ScreenCaptureTransitionTests { - @Test("Detached provider shutdown joins late resume and compensating stop") + @Test("Public stop joins pending setup or resume and concurrent stop through finalization", arguments: [false, true]) @MainActor - func shutdownJoinsLateProviderResume() async { + func publicStopJoinsSetupUnwindAndConcurrentStop(afterPause: Bool) async throws { guard #available(iOS 27.0, macOS 26.0, *) else { return } - let owner = ScreenCaptureTransitions() - let stream = ControlledCaptureStream() - _ = try? await owner.replace { stream }.value - _ = try? await owner.pause().value - let startEntered = CaptureGate() - let startRelease = CaptureGate() - let stopEntered = CaptureGate() - let stopRelease = CaptureGate() - let dismissed = CaptureGate() - defer { - startRelease.open(); stopRelease.open() - startEntered.open(); stopEntered.open(); dismissed.open() + try await withCaptureFixture { fixture in + let runtime = PublicCaptureFixture(fixture) + do { + // Pending initial selection wakes the real setup catch on stop. The + // second case enters public resume after a real public start and pause. + try await runtime.start(fixture, select: afterPause) + if afterPause { await runtime.session.pauseTranscribing() } + let entered = fixture.gate(), release = fixture.gate() + runtime.stream.startEntered = entered; runtime.stream.startRelease = release + var resume: Task? + if afterPause { + resume = fixture.track(Task { try await runtime.session.resumeTranscribing() }) + } else { + runtime.provider?.selectStream { runtime.stream } + } + try await entered.wait() + var firstReturned = false, secondReturned = false + let first = fixture.track(Task { @MainActor in + await runtime.session.stopTranscribing(); firstReturned = true + }) + try await runtime.dismissed.wait() + let secondEntered = fixture.gate() + let second = fixture.track(Task { @MainActor in + secondEntered.open() + await runtime.session.stopTranscribing(); secondReturned = true + }) + try await secondEntered.wait() + #expect(!firstReturned && !secondReturned) + #expect(!runtime.consumerFinished) + #expect(runtime.session.status != .idle) + release.open() + try await runtime.finalized.wait() + #expect(!runtime.stream.capturing) + #expect(!firstReturned && !secondReturned) + #expect(!runtime.consumerFinished) + runtime.finalizeRelease.open() + await first.value; await second.value + try await resume?.value + try await runtime.terminal.wait() + #expect(firstReturned && secondReturned) + #expect(runtime.session.status == .idle) + #expect(runtime.consumerError == nil) + } catch { + await runtime.close(fixture) + throw error + } + await runtime.close(fixture) } - stream.startEntered = startEntered - stream.startRelease = startRelease - stream.stopEntered = stopEntered - stream.stopRelease = stopRelease - let (_, continuation) = AsyncStream.makeStream() - defer { continuation.finish() } - // Actual provider and actual detached cleanup interface. Only OS capture calls - // and picker dismissal vary; no analyzer setup or public session state setters. - let provider = ScreenCaptureAudioInputProvider( - options: .init(), - targetFormat: AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)!, - inputContinuation: continuation, - onFailure: { _ in Issue.record("Unexpected provider failure") }, - transitions: owner, - dismissPicker: { _ in dismissed.open() } - ) - let session = SpeechSession() - session.screenCaptureInputProvider = provider - let resume = Task { @MainActor in try? await provider.resume() } - await startEntered.wait() - var terminalReturned = false - let stop = Task { @MainActor in - await session.stopScreenCaptureStreamingIfNeeded() - terminalReturned = true + } + + @Test("Late failing public resume cannot retire a newer picker admission") + @MainActor + func supersededPublicResumeFailure() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = PublicCaptureFixture(fixture) + do { + try await runtime.start(fixture) + await runtime.session.pauseTranscribing() + #expect(runtime.session.status == .paused) + let entered = fixture.gate(), release = fixture.gate() + runtime.stream.startEntered = entered; runtime.stream.startRelease = release + runtime.stream.startError = CaptureFixtureError.startFailed + let resume = fixture.track(Task { try await runtime.session.resumeTranscribing() }) + try await entered.wait() + let successor = ControlledCaptureStream() + let successorStarted = fixture.gate() + successor.startEntered = successorStarted + runtime.provider?.selectStream { successor } + release.open() + try await resume.value + try await successorStarted.wait() + #expect(!runtime.consumerFinished) + #expect(runtime.session.status == .paused) + #expect(runtime.owner.stream === successor) + // Explicitly resume the current selection, then fail that current start. + try await runtime.session.resumeTranscribing() + await runtime.session.pauseTranscribing() + successor.startError = CaptureFixtureError.startFailed + runtime.finalizeRelease.open() + do { + try await runtime.session.resumeTranscribing() + Issue.record("Current resume failure was lost") + } catch CaptureFixtureError.startFailed {} // Original error must propagate. + try await runtime.terminal.wait() + #expect(runtime.consumerError is CaptureFixtureError) + } catch { + await runtime.close(fixture) + throw error + } + await runtime.close(fixture) } - await dismissed.wait() - #expect(owner.desiredState == .stopped) - #expect(session.screenCaptureInputProvider == nil) - #expect(!terminalReturned) - startRelease.open() - await stopEntered.wait() - #expect(!terminalReturned) - #expect(stream.capturing) - stopRelease.open() - await stop.value - _ = await resume.value - #expect(terminalReturned) - #expect(!stream.capturing) - #expect(stream.starts == 2) - #expect(stream.stops == 2) - #expect(owner.stream == nil) - // Public stopTranscribing -> cleanup -> stopScreenCaptureStreamingIfNeeded - // awaits this boundary before finalizeDetachedTranscriberState/releaseLocales. - // Public resumeTranscribing is deliberately outside the joined operation chain: - // its error path can await cleanup itself. Full public setup needs native analysis. } } #endif From fdd8d0755d605b46517f2d528faf003d31e26d8c Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:19:17 -0500 Subject: [PATCH 09/70] Preserve file retirement errors and finalize normal input once --- Sources/AuralKit/SpeechSession+File.swift | 15 +- .../SpeechSession+FileLifecycle.swift | 61 ++-- .../SpeechSession+NativeFileInput.swift | 13 +- .../FileTranscriptionJoinTests.swift | 278 +++++++++++++++--- 4 files changed, 302 insertions(+), 65 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 0393798..4285006 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -84,13 +84,15 @@ public extension SpeechSession { continuation = .speech(newContinuation) let run = FileTranscriptionRun( - finalize: { [self] in + finalize: { [self] inputFinalizationStarted in prepareForStop() streamingMode = .inactive activeResultKind = nil let detached = detachTranscriberState() detached.inputBuilder?.finish() - try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() + if !inputFinalizationStarted { + try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() + } }, complete: { [self] error in await modelManager.releaseLocales() @@ -328,11 +330,18 @@ private extension SpeechSession { guard processedFrames >= totalFrames else { return false } - try await self.finishAnalyzerInput() + try await finishFileInput() return !Task.isCancelled && processedFrames >= totalFrames } + func finishFileInput() async throws { + guard let run = fileTranscription else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + try await run.finishInput { try await self.finishAnalyzerInput() } + } + func shouldUseNativeFileAnalyzer(progressHandler: (@Sendable (Double) -> Void)?) -> Bool { #if swift(>=6.4) if #available(iOS 27.0, macOS 27.0, *) { diff --git a/Sources/AuralKit/SpeechSession+FileLifecycle.swift b/Sources/AuralKit/SpeechSession+FileLifecycle.swift index 34d116a..a19fc96 100644 --- a/Sources/AuralKit/SpeechSession+FileLifecycle.swift +++ b/Sources/AuralKit/SpeechSession+FileLifecycle.swift @@ -10,11 +10,12 @@ final class FileTranscriptionRun { private(set) var terminalTask: Task? private var stoppingInput = false private var terminalError: Error? - private let finalize: @MainActor () async throws -> Void + private var inputFinalizationStarted = false + private let finalize: @MainActor (Bool) async throws -> Void private let complete: @MainActor (Error?) async -> Void init( - finalize: @escaping @MainActor () async throws -> Void, + finalize: @escaping @MainActor (Bool) async throws -> Void, complete: @escaping @MainActor (Error?) async -> Void ) { self.finalize = finalize @@ -28,7 +29,7 @@ final class FileTranscriptionRun { try Task.checkCancellation() try await operation() } catch { - requestRetirement(error: error) + requestRetirement(error: error, ownerCancelled: Task.isCancelled) } } } @@ -47,7 +48,7 @@ final class FileTranscriptionRun { )) } } catch { - requestRetirement(error: error) + requestRetirement(error: error, ownerCancelled: Task.isCancelled) } } // Setup can install a child after stop has already latched retirement. @@ -67,39 +68,59 @@ final class FileTranscriptionRun { try Task.checkCancellation() requestRetirement(cancelInput: false) } catch { - requestRetirement(error: error) + requestRetirement(error: error, ownerCancelled: Task.isCancelled) } } } + /// Called at the actual normal-feed finalization boundary, before suspension. + /// Even a failed attempt must not be repeated by terminal cleanup. + func finishInput(_ operation: @MainActor () async throws -> Void) async throws { + precondition(!inputFinalizationStarted) + inputFinalizationStarted = true + do { + try await operation() + } catch { + record(error, ownerCancelled: Task.isCancelled) + // A failed normal finalization cannot promise result EOF either. + resultTask?.cancel() + throw error + } + } + + private func record(_ error: Error?, ownerCancelled: Bool) { + guard let error else { return } + if error is CancellationError { + if !ownerCancelled, terminalError == nil { terminalError = error } + } else if terminalError == nil || terminalError is CancellationError { + terminalError = error + } + } + /// Latch synchronously before any suspension. Concurrent callers receive /// the same work, including callers arriving during finalization/drain. @discardableResult - func requestRetirement(error: Error? = nil, cancelInput: Bool = true) -> Task { - if let terminalTask { - if !stoppingInput, cancelInput { - terminalError = error - stoppingInput = true - setupTask?.cancel() - ingestionTask?.cancel() - } - return terminalTask - } - terminalError = error - stoppingInput = cancelInput - if cancelInput { + func requestRetirement( + error: Error? = nil, cancelInput: Bool = true, ownerCancelled: Bool = false + ) -> Task { + // Error priority is independent of the latch used to cancel producers. + // A real failure supersedes cancellation, but never an earlier real failure. + record(error, ownerCancelled: ownerCancelled) + if cancelInput, !stoppingInput { + stoppingInput = true setupTask?.cancel() ingestionTask?.cancel() } + if let terminalTask { return terminalTask } let terminal = Task { await setupTask?.value if stoppingInput { ingestionTask?.cancel() } await ingestionTask?.value // Keep results alive while finalization publishes its last chunks. do { - try await finalize() + try await finalize(inputFinalizationStarted) } catch { - if terminalError == nil { terminalError = error } + record(error, ownerCancelled: false) resultTask?.cancel() } await resultTask?.value diff --git a/Sources/AuralKit/SpeechSession+NativeFileInput.swift b/Sources/AuralKit/SpeechSession+NativeFileInput.swift index a412ba2..d059ea4 100644 --- a/Sources/AuralKit/SpeechSession+NativeFileInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeFileInput.swift @@ -29,10 +29,15 @@ extension SpeechSession { } let lastAudioTime = try await analyzer.analyzeSequence(from: file) - if let lastAudioTime { - try await analyzer.finalizeAndFinish(through: lastAudioTime) - } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() + guard let run = await fileTranscription else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + try await run.finishInput { + if let lastAudioTime { + try await analyzer.finalizeAndFinish(through: lastAudioTime) + } else { + try await analyzer.finalizeAndFinishThroughEndOfInput() + } } return !Task.isCancelled diff --git a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift index fb05da6..b595d38 100644 --- a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift @@ -2,53 +2,100 @@ import Foundation import Testing @testable import AuralKit -/// Deliberately ignores cancellation so a join must await the actual operation. +/// Harness waits cooperate; simulated native operations explicitly opt out. @MainActor private final class FileJoinGate { private var opened = false - private var waiters: [CheckedContinuation] = [] + private var waiters: [UUID: CheckedContinuation] = [:] + private var operationWaiters: [CheckedContinuation] = [] - func wait() async { + var pendingControlWaits: Int { waiters.count } + + func wait() async throws { + try Task.checkCancellation() + if opened { return } + let id = UUID() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + waiters[id] = continuation + } + } onCancel: { + Task { @MainActor in + self.waiters.removeValue(forKey: id)?.resume(throwing: CancellationError()) + } + } + } + + func waitIgnoringCancellation() async { if opened { return } - await withCheckedContinuation { waiters.append($0) } + await withCheckedContinuation { operationWaiters.append($0) } } func open() { opened = true - let pending = waiters + let pending = Array(waiters.values) waiters.removeAll() for waiter in pending { waiter.resume() } + let operations = operationWaiters + operationWaiters.removeAll() + for waiter in operations { waiter.resume() } } } @Suite("Joined file retirement") @MainActor struct FileTranscriptionJoinTests { - /// Every test body is nonthrowing. Always release gates, close the sequence, - /// and join the owner, even when an expectation records a failure. + /// The watchdog is independent of the body and its readiness waits. Cleanup + /// releases even cancellation-insensitive simulated native operations first. + @discardableResult private func withRun( failFinalization: Bool = false, - _ body: (FileTranscriptionRun, [FileJoinGate], AsyncThrowingStream, - AsyncThrowingStream.Continuation, FileJoinRecord) async -> Void - ) async { + timeout: Duration = .seconds(5), + expectTimeout: Bool = false, + _ body: @escaping @MainActor (FileTranscriptionRun, [FileJoinGate], AsyncThrowingStream, + AsyncThrowingStream.Continuation, FileJoinRecord) async throws -> Void + ) async -> FileJoinRecord { let gates = (0..<6).map { _ in FileJoinGate() } + let finished = FileJoinGate() let record = FileJoinRecord() let (stream, continuation) = AsyncThrowingStream.makeStream() - let run = FileTranscriptionRun(finalize: { - record.events.append("finalize") + let run = FileTranscriptionRun(finalize: { alreadyFinalized in + record.events.append("detach") gates[3].open() - await gates[4].wait() - if failFinalization { throw CocoaError(.fileReadUnknown) } - continuation.yield(42) - continuation.finish() + if !alreadyFinalized { + record.events.append("finalize") + await gates[4].waitIgnoringCancellation() + if failFinalization { throw CocoaError(.fileReadUnknown) } + continuation.yield(42) + continuation.finish() + } }, complete: { error in record.error = error record.events.append("complete") }) - await body(run, gates, stream, continuation, record) + let work = Task { + do { try await body(run, gates, stream, continuation, record) } + catch is CancellationError { } + catch { Issue.record("Unexpected harness error: \(error)") } + finished.open() + } + let watchdog = Task { + do { try await Task.sleep(for: timeout) } catch { return } + record.timedOut = true + finished.open() + } + try? await finished.wait() + watchdog.cancel() + work.cancel() for gate in gates { gate.open() } continuation.finish() await run.requestRetirement().value + await work.value + await watchdog.value + #expect(record.timedOut == expectTimeout) + #expect(gates.allSatisfy { $0.pendingControlWaits == 0 }) + #expect(record.events.contains("complete")) + return record } @Test("Stop joins suspended setup and a late-installed reader") @@ -56,16 +103,16 @@ struct FileTranscriptionJoinTests { await withRun { run, gates, stream, _, record in run.startSetup { gates[0].open() - await gates[1].wait() + await gates[1].waitIgnoringCancellation() run.startResults(stream) { record.values.append($0) } run.startIngestion { record.events.append("unexpected input"); return true } record.events.append("setup exited") } - await gates[0].wait() + try await gates[0].wait() let terminal = run.requestRetirement() gates[1].open() - await gates[3].wait() - #expect(record.events == ["setup exited", "finalize"]) + try await gates[3].wait() + #expect(record.events == ["setup exited", "detach", "finalize"]) gates[4].open() await terminal.value #expect(record.values == [42]) @@ -80,25 +127,25 @@ struct FileTranscriptionJoinTests { run.startResults(stream) { record.values.append($0) } run.startIngestion { gates[0].open() - await gates[1].wait() + await gates[1].waitIgnoringCancellation() record.events.append("input exited") return true } } - await gates[0].wait() + try await gates[0].wait() let first = Task { await run.requestRetirement().value; record.events.append("stop one") } let second = Task { await run.requestRetirement().value; record.events.append("stop two") } // Latch before releasing the input; the two Tasks join that same owner. let terminal = run.requestRetirement() gates[1].open() - await gates[3].wait() - #expect(record.events == ["input exited", "finalize"]) + try await gates[3].wait() + #expect(record.events == ["input exited", "detach", "finalize"]) gates[4].open() await terminal.value await first.value await second.value #expect(record.events.filter { $0 == "finalize" }.count == 1) - #expect(Array(record.events.prefix(3)) == ["input exited", "finalize", "complete"]) + #expect(Array(record.events.prefix(4)) == ["input exited", "detach", "finalize", "complete"]) #expect(Set(record.events.suffix(2)) == Set(["stop one", "stop two"])) #expect(record.error == nil) } @@ -111,9 +158,9 @@ struct FileTranscriptionJoinTests { run.startResults(stream) { record.values.append($0); record.events.append("result") } run.startIngestion { gates[0].open(); return true } } - await gates[0].wait() + try await gates[0].wait() let terminal = run.requestRetirement() - await gates[3].wait() + try await gates[3].wait() #expect(record.values.isEmpty) #expect(!record.events.contains("complete")) gates[4].open() @@ -130,35 +177,45 @@ struct FileTranscriptionJoinTests { run.startResults(stream) { record.values.append($0) } run.startIngestion { gates[0].open() - await gates[1].wait() + await gates[1].waitIgnoringCancellation() #expect(!Task.isCancelled) record.events.append("input exited") return true } } - await gates[0].wait() + try await gates[0].wait() continuation.finish() gates[1].open() - await gates[3].wait() + try await gates[3].wait() gates[4].open() await run.terminalTask?.value - #expect(record.events == ["input exited", "finalize", "complete"]) + #expect(record.events == ["input exited", "detach", "finalize", "complete"]) #expect(record.error == nil) } } @Test("Finalizer failure cancels and joins a waiting reader") func finalizationFailure() async { - await withRun(failFinalization: true) { run, gates, stream, _, record in + await withRun(failFinalization: true) { run, gates, stream, continuation, record in + continuation.onTermination = { termination in + let cancelled: Bool + if case .cancelled = termination { cancelled = true } else { cancelled = false } + Task { @MainActor in + record.readerWasCancelled = cancelled + gates[2].open() + } + } run.startSetup { run.startResults(stream) { record.values.append($0) } gates[0].open() } - await gates[0].wait() + try await gates[0].wait() let terminal = run.requestRetirement() - await gates[3].wait() + try await gates[3].wait() gates[4].open() await terminal.value + try await gates[2].wait() + #expect(record.readerWasCancelled) #expect(record.error is CocoaError) #expect(record.events.last == "complete") } @@ -171,9 +228,9 @@ struct FileTranscriptionJoinTests { run.startResults(stream) { record.values.append($0) } gates[0].open() } - await gates[0].wait() + try await gates[0].wait() continuation.finish(throwing: CancellationError()) - await gates[3].wait() + try await gates[3].wait() gates[4].open() // Finalization was reached by the reader's request, without public stop. await run.terminalTask?.value @@ -181,6 +238,144 @@ struct FileTranscriptionJoinTests { } } + @Test("Stop preserves a later genuine producer failure", arguments: ["reader", "input", "setup"]) + func realErrorAfterStop(producer: String) async { + await withRun { run, gates, stream, continuation, record in + run.startSetup { + run.startResults(stream) { record.values.append($0) } + if producer == "setup" { + gates[0].open() + await gates[1].waitIgnoringCancellation() + throw FileJoinFailure.first + } + run.startIngestion { + gates[0].open() + await gates[1].waitIgnoringCancellation() + if producer == "input" { throw FileJoinFailure.first } + return true + } + } + try await gates[0].wait() + let terminal = run.requestRetirement() + if producer == "reader" { continuation.finish(throwing: FileJoinFailure.first) } + gates[1].open() + try await gates[3].wait() + gates[4].open() + await terminal.value + #expect(record.error as? FileJoinFailure == .first) + } + } + + @Test("Meaningful error priority survives later cleanup cancellation", arguments: [false, true]) + func errorPriority(initialCancellation: Bool) async { + await withRun { run, gates, stream, continuation, record in + run.startSetup { + run.startResults(stream) { record.values.append($0) } + run.startIngestion { + gates[0].open() + await gates[1].waitIgnoringCancellation() + throw CancellationError() + } + } + try await gates[0].wait() + let initial: Error = initialCancellation ? CancellationError() : FileJoinFailure.first + let terminal = run.requestRetirement(error: initial) + continuation.finish(throwing: FileJoinFailure.second) + gates[1].open() + try await gates[3].wait() + gates[4].open() + await terminal.value + #expect(record.error as? FileJoinFailure == (initialCancellation ? .second : .first)) + } + } + + @Test("Normal input finalization is attempted once and its results drain", + arguments: [false, true], [false, true]) + func normalFinalization(fails: Bool, stopDuringFinalization: Bool) async { + await withRun { run, gates, stream, continuation, record in + run.startSetup { + run.startResults(stream) { record.values.append($0); record.events.append("result") } + run.startIngestion { + try await run.finishInput { + record.events.append("normal finalize") + gates[0].open() + await gates[1].waitIgnoringCancellation() + if fails { throw FileJoinFailure.first } + continuation.yield(7) + continuation.finish() + } + return true + } + } + try await gates[0].wait() + if stopDuringFinalization { run.requestRetirement() } + // A successful reader EOF requests retirement; a failed finalization + // requests it from ingestion. Neither route may retry the operation. + gates[1].open() + try await gates[3].wait() + await run.terminalTask?.value + #expect(record.events.filter { $0 == "normal finalize" }.count == 1) + #expect(!record.events.contains("finalize")) + #expect(record.events.last == "complete") + if fails { + #expect(record.error as? FileJoinFailure == .first) + } else { + #expect(record.error == nil) + #expect(record.values == [7]) + if let result = record.events.firstIndex(of: "result"), + let complete = record.events.firstIndex(of: "complete") { + #expect(result < complete) + } else { Issue.record("Missing result or completion") } + } + } + } + + @Test("Watchdog releases stalled body/readiness and joins native operations", arguments: [false, true]) + func watchdogCleanup(stallOnTerminal: Bool) async { + let record = await withRun(timeout: .seconds(1), expectTimeout: true) { run, gates, stream, _, record in + run.startSetup { + run.startResults(stream) { record.values.append($0) } + run.startIngestion { + gates[0].open() + await gates[1].waitIgnoringCancellation() + record.events.append("released input") + return true + } + } + try await gates[0].wait() + // Intentionally never signalled by a producer. The watchdog must + // cancel this wait, release input/finalization, close and join. + if stallOnTerminal { + await run.requestRetirement().value + } else { + try await gates[5].wait() + } + } + #expect(record.events.contains("released input")) + #expect(record.events.last == "complete") + #expect(record.error == nil) + } + + @Test("Cancelling a harness wait removes its continuation") + func cancelledControlWait() async { + await withRun { _, gates, _, _, _ in + let waiter = Task { + gates[0].open() + try await gates[1].wait() + } + try await gates[0].wait() + #expect(gates[1].pendingControlWaits == 1) + waiter.cancel() + do { + try await waiter.value + Issue.record("Cancelled control wait returned successfully") + } catch { + #expect(error is CancellationError) + } + #expect(gates[1].pendingControlWaits == 0) + } + } + @Test("Incomplete input and independent input cancellation are failures", arguments: [false, true]) func incompleteInput(cancelled: Bool) async { await withRun { run, gates, stream, _, record in @@ -191,7 +386,7 @@ struct FileTranscriptionJoinTests { return false } } - await gates[3].wait() + try await gates[3].wait() gates[4].open() await run.terminalTask?.value if cancelled { @@ -208,4 +403,11 @@ private final class FileJoinRecord { var events: [String] = [] var values: [Int] = [] var error: Error? + var timedOut = false + var readerWasCancelled = false +} + +private enum FileJoinFailure: Error { + case first + case second } From 4a2b50ae3dd30b22ae20bc9f66e96e5308d162f0 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:43:47 -0500 Subject: [PATCH 10/70] Fence speech detector readers by monitor identity --- .../SpeechSession+VoiceActivation.swift | 38 ++- Sources/AuralKit/SpeechSession.swift | 1 + .../SpeechDetectorLifecycleTests.swift | 235 ++++++++++++++++++ 3 files changed, 261 insertions(+), 13 deletions(-) create mode 100644 Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift diff --git a/Sources/AuralKit/SpeechSession+VoiceActivation.swift b/Sources/AuralKit/SpeechSession+VoiceActivation.swift index cc93f31..bf8875d 100644 --- a/Sources/AuralKit/SpeechSession+VoiceActivation.swift +++ b/Sources/AuralKit/SpeechSession+VoiceActivation.swift @@ -28,6 +28,7 @@ extension SpeechSession { } func tearDownSpeechDetectorStream() { + speechDetectorMonitorID = nil speechDetectorResultsTask?.cancel() speechDetectorResultsTask = nil speechDetectorResultsContinuation?.finish() @@ -42,29 +43,39 @@ extension SpeechSession { func startSpeechDetectorMonitoring() { guard let detector = speechDetector else { return } + monitorSpeechDetectorResults(detector.results, speechDetected: { $0.speechDetected }) { [weak self] result in + self?.handleSpeechDetectorResult(result) + } + } + + /// Native detector results and controlled sequences share the same owning reader. + /// Cancellation alone does not revoke a suspended reader's callback authority. + func monitorSpeechDetectorResults( + _ results: Sequence, + speechDetected: @escaping @Sendable (Sequence.Element) -> Bool, + onResult: @escaping @MainActor @Sendable (Sequence.Element) -> Void + ) where Sequence: Sendable, Sequence.Element: Sendable { speechDetectorResultsTask?.cancel() + let monitorID = UUID() + speechDetectorMonitorID = monitorID if Self.shouldLog(.debug) { Self.logger.debug("Starting speech detector monitoring") } - speechDetectorResultsTask = Task { [weak self] in + speechDetectorResultsTask = Task { @MainActor [weak self] in guard let self else { return } do { - for try await result in detector.results { - await MainActor.run { - self.handleSpeechDetectorResult(result) - } + for try await result in results { + guard self.speechDetectorMonitorID == monitorID else { return } + self.isSpeechDetected = speechDetected(result) + onResult(result) } } catch { let finalError = (error as? CancellationError) != nil ? nil : error - await MainActor.run { - self.handleSpeechDetectorStreamCompletion(error: finalError) - } + self.handleSpeechDetectorStreamCompletion(error: finalError, monitorID: monitorID) return } - await MainActor.run { - self.handleSpeechDetectorStreamCompletion(error: nil) - } + self.handleSpeechDetectorStreamCompletion(error: nil, monitorID: monitorID) if Self.shouldLog(.notice) { Self.logger.notice("Speech detector monitoring completed") } @@ -77,7 +88,6 @@ extension SpeechSession { } func handleSpeechDetectorResult(_ result: SpeechDetector.Result) { - isSpeechDetected = result.speechDetected speechDetectorResultsContinuation?.yield(result) if Self.shouldLog(.debug) { Self.logger.debug( @@ -86,7 +96,9 @@ extension SpeechSession { } } - func handleSpeechDetectorStreamCompletion(error: Error?) { + func handleSpeechDetectorStreamCompletion(error: Error?, monitorID: UUID) { + guard speechDetectorMonitorID == monitorID else { return } + speechDetectorMonitorID = nil defer { speechDetectorResultsTask = nil } if let continuation = speechDetectorResultsContinuation { diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 03c211c..7ef95bd 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -107,6 +107,7 @@ public final class SpeechSession { // Voice activation state var speechDetectorResultsContinuation: AsyncStream.Continuation? var speechDetectorResultsTask: Task? + var speechDetectorMonitorID: UUID? // MARK: - Init diff --git a/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift new file mode 100644 index 0000000..43523bb --- /dev/null +++ b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift @@ -0,0 +1,235 @@ +import Foundation +import Testing +@testable import AuralKit + +@Suite("Speech detector monitor identity") +struct SpeechDetectorLifecycleTests { + @Test("public disable and reconfigure rejects a late predecessor result") + @MainActor + func staleResultAfterReconfiguration() async throws { + try await withFixture { fixture in + let source = HeldDetectorSource() + fixture.sources.append(source) + fixture.session.configureVoiceActivation(reportResults: true) + let old = try fixture.monitor(HeldDetectorResults(source: source)) + try await fixture.waitUntil { await source.isWaiting } + fixture.session.disableVoiceActivation() + fixture.session.configureVoiceActivation(reportResults: true) + let (results, continuation) = fixture.results() + _ = try fixture.monitor(results) + let currentID = try #require(fixture.session.speechDetectorMonitorID) + continuation.yield(true) + try await fixture.waitUntil { fixture.values == [true] } + await source.send(false) + await source.finish() + #expect(old.isCancelled) + await old.value + #expect(fixture.values == [true]) + #expect(fixture.session.isSpeechDetected) + #expect(fixture.session.speechDetectorMonitorID == currentID) + #expect(fixture.session.speechDetectorResultsTask != nil) + #expect(fixture.session.speechDetectorResultsStream != nil) + } + } + + @Test("predecessor completion cannot finish a reconfigured monitor", arguments: [false, true]) + @MainActor + func staleCompletionAfterReconfiguration(failed: Bool) async throws { + try await withFixture { fixture in + fixture.session.configureVoiceActivation(reportResults: true) + let source = HeldDetectorSource() + fixture.sources.append(source) + let old = try fixture.monitor(HeldDetectorResults(source: source)) + try await fixture.waitUntil { await source.isWaiting } + fixture.session.disableVoiceActivation() + fixture.session.configureVoiceActivation(reportResults: true) + let (results, input) = fixture.results() + _ = try fixture.monitor(results) + let currentID = try #require(fixture.session.speechDetectorMonitorID) + input.yield(false) + try await fixture.waitUntil { fixture.values == [false] } + if failed { await source.fail() } + else { await source.finish() } + #expect(old.isCancelled) + await old.value + #expect(!fixture.session.isSpeechDetected) + #expect(fixture.session.speechDetectorMonitorID == currentID) + #expect(fixture.session.speechDetectorResultsTask != nil) + #expect(fixture.session.speechDetectorResultsContinuation != nil) + #expect(fixture.session.speechDetectorResultsStream != nil) + } + } + + @Test("cooperative cancellation of a replaced reader cannot clear its successor") + @MainActor + func cancelledPredecessorCompletion() async throws { + try await withFixture { fixture in + fixture.session.configureVoiceActivation(reportResults: true) + let (oldResults, oldInput) = fixture.results() + let old = try fixture.monitor(oldResults) + oldInput.yield(true) + try await fixture.waitUntil { fixture.values == [true] } + let (results, input) = fixture.results() + _ = try fixture.monitor(results) + let currentID = try #require(fixture.session.speechDetectorMonitorID) + await old.value + #expect(old.isCancelled) + #expect(fixture.session.speechDetectorMonitorID == currentID) + #expect(fixture.session.speechDetectorResultsTask != nil) + #expect(fixture.session.speechDetectorResultsStream != nil) + input.yield(false) + try await fixture.waitUntil { fixture.values == [true, false] } + #expect(!fixture.session.isSpeechDetected) + } + } + + @Test("disable revokes a reader even without a replacement") + @MainActor + func staleResultAfterDisable() async throws { + try await withFixture { fixture in + let source = HeldDetectorSource() + fixture.sources.append(source) + fixture.session.configureVoiceActivation(reportResults: true) + let old = try fixture.monitor(HeldDetectorResults(source: source)) + try await fixture.waitUntil { await source.isWaiting } + fixture.session.disableVoiceActivation() + await source.send(false) + await source.finish() + await old.value + #expect(old.isCancelled) + #expect(fixture.values.isEmpty) + #expect(fixture.session.isSpeechDetected) + #expect(fixture.session.speechDetectorMonitorID == nil) + #expect(fixture.session.speechDetectorResultsTask == nil) + #expect(fixture.session.speechDetectorResultsStream == nil) + } + } + + @Test("current results and normal or failed completion retain their behavior", arguments: [false, true]) + @MainActor + func currentMonitorCompletion(failed: Bool) async throws { + try await withFixture { fixture in + fixture.session.configureVoiceActivation(reportResults: true) + let (results, input) = fixture.results() + let task = try fixture.monitor(results) + input.yield(false) + try await fixture.waitUntil { fixture.values == [false] } + #expect(!fixture.session.isSpeechDetected) + if failed { input.finish(throwing: DetectorTestError.failed) } + else { input.finish() } + await task.value + #expect(fixture.session.isSpeechDetected) + #expect(fixture.session.speechDetectorMonitorID == nil) + #expect(fixture.session.speechDetectorResultsTask == nil) + #expect(fixture.session.speechDetectorResultsContinuation == nil) + #expect(fixture.session.speechDetectorResultsStream == nil) + } + } + + @MainActor + private func withFixture(_ operation: @MainActor (DetectorFixture) async throws -> Void) async throws { + let fixture = DetectorFixture() + do { try await operation(fixture) } + catch { await fixture.cleanup(); throw error } + await fixture.cleanup() + } +} + +private enum DetectorTestError: Error { + case failed +} + +/// Holds a suspended next() across cancellation to exercise a late value or +/// completion. This models the AsyncSequence contract, not Apple implementation timing. +private actor HeldDetectorSource { + private var continuation: CheckedContinuation? + private var finished = false + private(set) var isWaiting = false + + func next() async throws -> Bool? { + guard !finished else { return nil } + isWaiting = true + return try await withCheckedThrowingContinuation { continuation = $0 } + } + + func send(_ value: Bool) { + isWaiting = false + continuation?.resume(returning: value) + continuation = nil + } + + func fail() { + finished = true + isWaiting = false + continuation?.resume(throwing: DetectorTestError.failed) + continuation = nil + } + + func finish() { + finished = true + isWaiting = false + continuation?.resume(returning: nil) + continuation = nil + } +} + +private struct HeldDetectorResults: AsyncSequence, Sendable { + typealias Element = Bool + let source: HeldDetectorSource + + func makeAsyncIterator() -> AsyncIterator { + AsyncIterator(source: source) + } + + struct AsyncIterator: AsyncIteratorProtocol { + let source: HeldDetectorSource + + mutating func next() async throws -> Bool? { + try await source.next() + } + } +} + +@MainActor +private final class DetectorFixture { + let session = SpeechSession() + var values: [Bool] = [] + var sources: [HeldDetectorSource] = [] + private var tasks: [Task] = [] + private var inputs: [AsyncThrowingStream.Continuation] = [] + + func results() -> ( + AsyncThrowingStream, + AsyncThrowingStream.Continuation + ) { + let (results, input) = AsyncThrowingStream.makeStream() + inputs.append(input) + return (results, input) + } + + func monitor(_ results: Sequence) throws -> Task + where Sequence: Sendable, Sequence.Element == Bool { + session.monitorSpeechDetectorResults(results, speechDetected: { $0 }) { [unowned self] detected in + values.append(detected) + } + let task = try #require(session.speechDetectorResultsTask) + tasks.append(task) + return task + } + + func waitUntil(_ predicate: @MainActor () async -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) + while !(await predicate()) { + guard ContinuousClock.now < deadline else { throw TestTimeoutError.timedOut(seconds: 2) } + await Task.yield() + } + } + + func cleanup() async { + session.disableVoiceActivation() + for source in sources { await source.finish() } + inputs.forEach { $0.finish() } + tasks.forEach { $0.cancel() } + for task in tasks { await task.value } + } +} From 21d50dd3cdabcb7d8fb17ec3cee58bbbe47fa6ec Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:52:48 -0500 Subject: [PATCH 11/70] Disambiguate screen readiness gates and organize bounded fixtures --- .../SpeechSession+ScreenCapture.swift | 3 +- Sources/AuralKit/SpeechSession+State.swift | 46 +++++++ Sources/AuralKit/SpeechSession.swift | 46 ------- .../ScreenCaptureTestFixtures.swift | 111 ++++++++++++++++ .../ScreenCaptureTransitionTests.swift | 124 ++---------------- 5 files changed, 172 insertions(+), 158 deletions(-) create mode 100644 Tests/AuralKitTests/ScreenCaptureTestFixtures.swift diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index f2e9914..1493d96 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -376,7 +376,8 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr func stream(_ stream: SCStream, didStopWithError error: any Error) { Task { @MainActor [weak self] in guard let self, !self.consumeIntentionalStop(for: stream), - !self.stopped, (self.transitions.stream as? NativeScreenCaptureStream)?.stream === stream else { return } + !self.stopped, + (self.transitions.stream as? NativeScreenCaptureStream)?.stream === stream else { return } self.onFailure(SpeechSessionError.screenCaptureFailed(error)) } } diff --git a/Sources/AuralKit/SpeechSession+State.swift b/Sources/AuralKit/SpeechSession+State.swift index ca4d8cb..407f376 100644 --- a/Sources/AuralKit/SpeechSession+State.swift +++ b/Sources/AuralKit/SpeechSession+State.swift @@ -39,4 +39,50 @@ extension SpeechSession { } statusContinuations.removeAll() } + + /// Pause capture without tearing down the analyzer pipeline. + /// + /// Safe to call only when the session is actively transcribing live audio (microphone or + /// screen capture). Calls during file transcription or in any other state are ignored. + public func pauseTranscribing() async { + guard status == .transcribing, isPausableStreamingMode else { return } + let generation = sessionGeneration + if streamingMode == .screenCapture { + await pauseScreenCaptureStreamingIfNeeded() + } else { + stopAudioStreaming() + } + // A paused capture call can finish after stop has published idle, even in the + // same generation; it must not publish paused over that terminal status. + guard generation == sessionGeneration, status == .transcribing, isPausableStreamingMode else { return } + setStatus(.paused) + } + + /// Resume a paused capture session. + /// + /// - Throws: `SpeechSessionError` if audio streaming cannot restart. + public func resumeTranscribing() async throws { + guard status == .paused, isPausableStreamingMode else { return } + let generation = sessionGeneration + do { + if streamingMode == .screenCapture { + let outcome = try await resumeScreenCaptureStreamingIfNeeded() + guard outcome.isCurrent() else { return } + if let error = outcome.error { throw error } + } else { + try startAudioStreaming() + } + // A late start may have compensated for stop while this caller was suspended. + // Generation alone is insufficient until a successor actually begins. + guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { return } + setStatus(.transcribing) + } catch { + // A late failure belongs to the detached provider, not a successor session. + guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { throw error } + prepareForStop() + await cleanup(cancelRecognizer: true, generation: generation) + await finishStream(error: error, generation: generation) + throw error + } + } } diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 16097b9..6153254 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -357,50 +357,4 @@ public final class SpeechSession { await finishStream(error: nil, generation: generation) } - /// Pause capture without tearing down the analyzer pipeline. - /// - /// Safe to call only when the session is actively transcribing live audio (microphone or - /// screen capture). Calls during file transcription or in any other state are ignored. - public func pauseTranscribing() async { - guard status == .transcribing, isPausableStreamingMode else { return } - let generation = sessionGeneration - if streamingMode == .screenCapture { - await pauseScreenCaptureStreamingIfNeeded() - } else { - stopAudioStreaming() - } - // A paused capture call can finish after stop has published idle, even in the - // same generation; it must not publish paused over that terminal status. - guard generation == sessionGeneration, status == .transcribing, isPausableStreamingMode else { return } - setStatus(.paused) - } - - /// Resume a paused capture session. - /// - /// - Throws: `SpeechSessionError` if audio streaming cannot restart. - public func resumeTranscribing() async throws { - guard status == .paused, isPausableStreamingMode else { return } - let generation = sessionGeneration - do { - if streamingMode == .screenCapture { - let outcome = try await resumeScreenCaptureStreamingIfNeeded() - guard outcome.isCurrent() else { return } - if let error = outcome.error { throw error } - } else { - try startAudioStreaming() - } - // A late start may have compensated for stop while this caller was suspended. - // Generation alone is insufficient until a successor actually begins. - guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { return } - setStatus(.transcribing) - } catch { - // A late failure belongs to the detached provider, not a successor session. - guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { throw error } - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) - throw error - } - } - } diff --git a/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift new file mode 100644 index 0000000..56f9c12 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift @@ -0,0 +1,111 @@ +import Foundation +@testable import AuralKit + +enum CaptureFixtureError: Error { case deadline, startFailed } + +/// Each waiter owns its deadline and can be removed by cancellation. No timeout +/// task group can be stranded joining a checked continuation that ignores cancel. +@MainActor +final class CaptureGate { + private var opened = false + private var waiters: [UUID: CheckedContinuation] = [:] + var waiterCount: Int { waiters.count } + + func wait(timeoutNanoseconds: UInt64 = 3_000_000_000) async throws { + try Task.checkCancellation() + if opened { return } + let id = UUID() + let deadline = Task { @MainActor in + do { try await Task.sleep(nanoseconds: timeoutNanoseconds) } catch { return } + self.remove(id, error: CaptureFixtureError.deadline) + } + defer { deadline.cancel() } + try await withTaskCancellationHandler { () async throws -> Void in + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + if Task.isCancelled { + continuation.resume(throwing: CancellationError()) + } else { + waiters[id] = continuation + } + } + } onCancel: { + Task { @MainActor in self.remove(id, error: CancellationError()) } + } + } + + private func remove(_ id: UUID, error: Error) { + waiters.removeValue(forKey: id)?.resume(throwing: error) + } + + func open() { + opened = true + let pending = waiters.values + waiters.removeAll() + for waiter in pending { waiter.resume() } + } +} + +/// Async cleanup opens all gates before joining every task admitted by the test, +/// including on a failed readiness wait. Errors remain visible to the test body. +@MainActor +final class CaptureFixture { + private var gates: [CaptureGate] = [] + private var joins: [Task] = [] + private var cancellations: [() -> Void] = [] + func gate() -> CaptureGate { + let gate = CaptureGate() + gates.append(gate) + return gate + } + @discardableResult + func track(_ task: Task) -> Task { + cancellations.append { task.cancel() } + joins.append(Task { _ = await task.result }) + return task + } + func releaseAll() { gates.forEach { $0.open() } } + func cleanUp() async { + releaseAll() + cancellations.forEach { $0() } + for join in joins { await join.value } + } +} + +@MainActor +func withCaptureFixture(_ body: (CaptureFixture) async throws -> Void) async throws { + let fixture = CaptureFixture() + do { + try await body(fixture) + await fixture.cleanUp() + } catch { + await fixture.cleanUp() + throw error + } +} + +@available(iOS 26.0, macOS 26.0, *) +@MainActor +final class ControlledCaptureStream: ScreenCaptureStream { + var starts = 0 + var stops = 0 + var capturing = false + var startEntered: CaptureGate? + var startRelease: CaptureGate? + var stopEntered: CaptureGate? + var stopRelease: CaptureGate? + var startError: Error? + + func startCapture() async throws { + starts += 1 + startEntered?.open() + try await startRelease?.wait() + if let startError { throw startError } + capturing = true + } + func stopCapture() async throws { + stops += 1 + stopEntered?.open() + try await stopRelease?.wait() + capturing = false + } +} diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index 95afcba..9371a69 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -3,111 +3,6 @@ import Speech import Testing @testable import AuralKit -private enum CaptureFixtureError: Error { case deadline, startFailed } - -/// Each waiter owns its deadline and can be removed by cancellation. No timeout -/// task group can be stranded joining a checked continuation that ignores cancel. -@MainActor -private final class CaptureGate { - private var opened = false - private var waiters: [UUID: CheckedContinuation] = [:] - var waiterCount: Int { waiters.count } - - func wait(timeoutNanoseconds: UInt64 = 3_000_000_000) async throws { - try Task.checkCancellation() - if opened { return } - let id = UUID() - let deadline = Task { @MainActor in - do { try await Task.sleep(nanoseconds: timeoutNanoseconds) } catch { return } - self.remove(id, error: CaptureFixtureError.deadline) - } - defer { deadline.cancel() } - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - if Task.isCancelled { continuation.resume(throwing: CancellationError()) } - else { waiters[id] = continuation } - } - } onCancel: { - Task { @MainActor in self.remove(id, error: CancellationError()) } - } - } - - private func remove(_ id: UUID, error: Error) { - waiters.removeValue(forKey: id)?.resume(throwing: error) - } - - func open() { - opened = true - let pending = waiters.values - waiters.removeAll() - for waiter in pending { waiter.resume() } - } -} - -/// Async cleanup opens all gates before joining every task admitted by the test, -/// including on a failed readiness wait. Errors remain visible to the test body. -@MainActor -private final class CaptureFixture { - private var gates: [CaptureGate] = [] - private var joins: [Task] = [] - private var cancellations: [() -> Void] = [] - func gate() -> CaptureGate { - let gate = CaptureGate() - gates.append(gate) - return gate - } - func track(_ task: Task) -> Task { - cancellations.append { task.cancel() } - joins.append(Task { _ = await task.result }) - return task - } - func releaseAll() { gates.forEach { $0.open() } } - func cleanUp() async { - releaseAll() - cancellations.forEach { $0() } - for join in joins { await join.value } - } -} - -@MainActor -private func withCaptureFixture(_ body: (CaptureFixture) async throws -> Void) async throws { - let fixture = CaptureFixture() - do { - try await body(fixture) - await fixture.cleanUp() - } catch { - await fixture.cleanUp() - throw error - } -} - -@available(iOS 26.0, macOS 26.0, *) -@MainActor -private final class ControlledCaptureStream: ScreenCaptureStream { - var starts = 0 - var stops = 0 - var capturing = false - var startEntered: CaptureGate? - var startRelease: CaptureGate? - var stopEntered: CaptureGate? - var stopRelease: CaptureGate? - var startError: Error? - - func startCapture() async throws { - starts += 1 - startEntered?.open() - try await startRelease?.wait() - if let startError { throw startError } - capturing = true - } - func stopCapture() async throws { - stops += 1 - stopEntered?.open() - try await stopRelease?.wait() - capturing = false - } -} - @Suite("Screen capture transitions") struct ScreenCaptureTransitionTests { @Test("Cancellation removes a readiness waiter") @@ -122,8 +17,10 @@ struct ScreenCaptureTransitionTests { }) try await entered.wait() wait.cancel() - do { try await wait.value; Issue.record("Cancelled wait returned successfully") } - catch is CancellationError {} // Expected, including cancellation before registration. + do { + try await wait.value + Issue.record("Cancelled wait returned successfully") + } catch is CancellationError {} // Expected, including cancellation before registration. #expect(gate.waiterCount == 0) } } @@ -178,7 +75,8 @@ struct ScreenCaptureTransitionTests { guard #available(iOS 26.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in let owner = ScreenCaptureTransitions() - let old = ControlledCaptureStream(), obsolete = ControlledCaptureStream(), current = ControlledCaptureStream() + let old = ControlledCaptureStream() + let obsolete = ControlledCaptureStream(), current = ControlledCaptureStream() let entered = fixture.gate(), release = fixture.gate() try await fixture.track(owner.replace { old }).value old.stopEntered = entered; old.stopRelease = release @@ -293,8 +191,9 @@ private final class PublicCaptureFixture { let ready = fixture.gate() let statuses = session.statusStream fixture.track(Task { @MainActor in - for await status in statuses { - if status == .transcribing { ready.open(); return } + for await status in statuses where status == .transcribing { + ready.open() + return } }) try await ready.wait() @@ -309,7 +208,10 @@ private final class PublicCaptureFixture { } extension ScreenCaptureTransitionTests { - @Test("Public stop joins pending setup or resume and concurrent stop through finalization", arguments: [false, true]) + @Test( + "Public stop joins pending setup or resume and concurrent stop through finalization", + arguments: [false, true] + ) @MainActor func publicStopJoinsSetupUnwindAndConcurrentStop(afterPause: Bool) async throws { guard #available(iOS 27.0, macOS 26.0, *) else { return } From 03aa1caab358143555124b84da55bb506cc8b364 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:52:48 -0500 Subject: [PATCH 12/70] Separate joined file fixtures and bound suite bodies --- .../FileTranscriptionJoinTestFixtures.swift | 50 +++++++++++++++ .../FileTranscriptionJoinTests.swift | 61 +++---------------- 2 files changed, 59 insertions(+), 52 deletions(-) create mode 100644 Tests/AuralKitTests/FileTranscriptionJoinTestFixtures.swift diff --git a/Tests/AuralKitTests/FileTranscriptionJoinTestFixtures.swift b/Tests/AuralKitTests/FileTranscriptionJoinTestFixtures.swift new file mode 100644 index 0000000..a609a56 --- /dev/null +++ b/Tests/AuralKitTests/FileTranscriptionJoinTestFixtures.swift @@ -0,0 +1,50 @@ +import Foundation + +/// Harness waits cooperate; simulated native operations explicitly opt out. +@MainActor +final class FileJoinGate { + private var opened = false + private var waiters: [UUID: CheckedContinuation] = [:] + private var operationWaiters: [CheckedContinuation] = [] + + var pendingControlWaits: Int { waiters.count } + + func wait() async throws { + try Task.checkCancellation() + if opened { return } + let id = UUID() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + waiters[id] = continuation + } + } onCancel: { + Task { @MainActor in + self.waiters.removeValue(forKey: id)?.resume(throwing: CancellationError()) + } + } + } + + func waitIgnoringCancellation() async { + if opened { return } + await withCheckedContinuation { operationWaiters.append($0) } + } + + func open() { + opened = true + let pending = Array(waiters.values) + waiters.removeAll() + for waiter in pending { waiter.resume() } + let operations = operationWaiters + operationWaiters.removeAll() + for waiter in operations { waiter.resume() } + } +} + +@MainActor +final class FileJoinRecord { + var events: [String] = [] + var values: [Int] = [] + var error: Error? + var timedOut = false + var readerWasCancelled = false +} diff --git a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift index b595d38..00ec80e 100644 --- a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift @@ -2,46 +2,6 @@ import Foundation import Testing @testable import AuralKit -/// Harness waits cooperate; simulated native operations explicitly opt out. -@MainActor -private final class FileJoinGate { - private var opened = false - private var waiters: [UUID: CheckedContinuation] = [:] - private var operationWaiters: [CheckedContinuation] = [] - - var pendingControlWaits: Int { waiters.count } - - func wait() async throws { - try Task.checkCancellation() - if opened { return } - let id = UUID() - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - waiters[id] = continuation - } - } onCancel: { - Task { @MainActor in - self.waiters.removeValue(forKey: id)?.resume(throwing: CancellationError()) - } - } - } - - func waitIgnoringCancellation() async { - if opened { return } - await withCheckedContinuation { operationWaiters.append($0) } - } - - func open() { - opened = true - let pending = Array(waiters.values) - waiters.removeAll() - for waiter in pending { waiter.resume() } - let operations = operationWaiters - operationWaiters.removeAll() - for waiter in operations { waiter.resume() } - } -} - @Suite("Joined file retirement") @MainActor struct FileTranscriptionJoinTests { @@ -74,9 +34,12 @@ struct FileTranscriptionJoinTests { record.events.append("complete") }) let work = Task { - do { try await body(run, gates, stream, continuation, record) } - catch is CancellationError { } - catch { Issue.record("Unexpected harness error: \(error)") } + do { + try await body(run, gates, stream, continuation, record) + } catch is CancellationError { + } catch { + Issue.record("Unexpected harness error: \(error)") + } finished.open() } let watchdog = Task { @@ -150,7 +113,10 @@ struct FileTranscriptionJoinTests { #expect(record.error == nil) } } +} +@MainActor +extension FileTranscriptionJoinTests { @Test("Finalizer-generated results drain before completion") func finalResultDrain() async { await withRun { run, gates, stream, _, record in @@ -398,15 +364,6 @@ struct FileTranscriptionJoinTests { } } -@MainActor -private final class FileJoinRecord { - var events: [String] = [] - var values: [Int] = [] - var error: Error? - var timedOut = false - var readerWasCancelled = false -} - private enum FileJoinFailure: Error { case first case second From d6fb5789a6ce96d8cb882364c54bd3b7b5ec9f85 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:52:48 -0500 Subject: [PATCH 13/70] Separate reservation probes and bound suite bodies --- .../SpeechAssetReservationTestFixtures.swift | 87 +++++++++++++++++++ .../SpeechAssetReservationTests.swift | 87 +------------------ 2 files changed, 89 insertions(+), 85 deletions(-) create mode 100644 Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift diff --git a/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift b/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift new file mode 100644 index 0000000..a6faee9 --- /dev/null +++ b/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift @@ -0,0 +1,87 @@ +import Foundation +@testable import AuralKit + +actor AssetGate { + private var entered = false + private var arrivals: [CheckedContinuation] = [] + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + + func wait() async { + entered = true + let pending = arrivals + arrivals.removeAll() + for arrival in pending { arrival.resume() } + guard !isOpen else { return } + await withCheckedContinuation { waiters.append($0) } + } + + func waitForEntry() async { + guard !entered else { return } + await withCheckedContinuation { arrivals.append($0) } + } + + func open() { + isOpen = true + let pending = waiters + waiters.removeAll() + for waiter in pending { waiter.resume() } + } +} + +actor AssetInventoryProbe { + struct Snapshot: Sendable { + let locales: Set + let reserves: [String] + let releases: [String] + } + + private var stored: [String: Locale] + private let variants: [String: Locale] + private var reserveCalls: [String] = [] + private var releaseCalls: [String] = [] + private var reserveGate: AssetGate? + private var releaseGate: AssetGate? + private var extraLocales: [Locale] = [] + + init(initial: [Locale] = [], variants: [String: Locale] = [:]) { + stored = Dictionary(initial.map { ($0.identifier(.bcp47), $0) }, + uniquingKeysWith: { first, _ in first }) + self.variants = variants + } + + nonisolated var client: SpeechAssetReservations.Inventory { + .init(locales: { await self.locales() }, + reserve: { await self.reserve($0) }, + release: { await self.release($0) }) + } + + var snapshot: Snapshot { + Snapshot(locales: Set(stored.keys), reserves: reserveCalls, releases: releaseCalls) + } + + func holdReserve(at gate: AssetGate) { reserveGate = gate } + func holdRelease(at gate: AssetGate) { releaseGate = gate } + func addDuringNextReserve(_ locales: [Locale]) { extraLocales = locales } + private func locales() -> [Locale] { Array(stored.values) } + + private func reserve(_ locale: Locale) async -> Bool { + let requested = locale.identifier(.bcp47) + reserveCalls.append(requested) + await reserveGate?.wait() + let actual = variants[requested] ?? locale + let key = actual.identifier(.bcp47) + guard stored[key] == nil else { return false } + stored[key] = actual + for extra in extraLocales { stored[extra.identifier(.bcp47)] = extra } + extraLocales.removeAll() + return true + } + + private func release(_ locale: Locale) async -> Bool { + let key = locale.identifier(.bcp47) + releaseCalls.append(key) + await releaseGate?.wait() + return stored.removeValue(forKey: key) != nil + } +} diff --git a/Tests/AuralKitTests/SpeechAssetReservationTests.swift b/Tests/AuralKitTests/SpeechAssetReservationTests.swift index b412e5f..45eb1f0 100644 --- a/Tests/AuralKitTests/SpeechAssetReservationTests.swift +++ b/Tests/AuralKitTests/SpeechAssetReservationTests.swift @@ -4,91 +4,6 @@ import Speech import Testing @testable import AuralKit -private actor AssetGate { - private var entered = false - private var arrivals: [CheckedContinuation] = [] - private var isOpen = false - private var waiters: [CheckedContinuation] = [] - - func wait() async { - entered = true - let pending = arrivals - arrivals.removeAll() - for arrival in pending { arrival.resume() } - guard !isOpen else { return } - await withCheckedContinuation { waiters.append($0) } - } - - func waitForEntry() async { - guard !entered else { return } - await withCheckedContinuation { arrivals.append($0) } - } - - func open() { - isOpen = true - let pending = waiters - waiters.removeAll() - for waiter in pending { waiter.resume() } - } -} - -private actor AssetInventoryProbe { - struct Snapshot: Sendable { - let locales: Set - let reserves: [String] - let releases: [String] - } - - private var stored: [String: Locale] - private let variants: [String: Locale] - private var reserveCalls: [String] = [] - private var releaseCalls: [String] = [] - private var reserveGate: AssetGate? - private var releaseGate: AssetGate? - private var extraLocales: [Locale] = [] - - init(initial: [Locale] = [], variants: [String: Locale] = [:]) { - stored = Dictionary(initial.map { ($0.identifier(.bcp47), $0) }, - uniquingKeysWith: { first, _ in first }) - self.variants = variants - } - - nonisolated var client: SpeechAssetReservations.Inventory { - .init(locales: { await self.locales() }, - reserve: { await self.reserve($0) }, - release: { await self.release($0) }) - } - - var snapshot: Snapshot { - Snapshot(locales: Set(stored.keys), reserves: reserveCalls, releases: releaseCalls) - } - - func holdReserve(at gate: AssetGate) { reserveGate = gate } - func holdRelease(at gate: AssetGate) { releaseGate = gate } - func addDuringNextReserve(_ locales: [Locale]) { extraLocales = locales } - private func locales() -> [Locale] { Array(stored.values) } - - private func reserve(_ locale: Locale) async -> Bool { - let requested = locale.identifier(.bcp47) - reserveCalls.append(requested) - await reserveGate?.wait() - let actual = variants[requested] ?? locale - let key = actual.identifier(.bcp47) - guard stored[key] == nil else { return false } - stored[key] = actual - for extra in extraLocales { stored[extra.identifier(.bcp47)] = extra } - extraLocales.removeAll() - return true - } - - private func release(_ locale: Locale) async -> Bool { - let key = locale.identifier(.bcp47) - releaseCalls.append(key) - await releaseGate?.wait() - return stored.removeValue(forKey: key) != nil - } -} - @MainActor private final class AssetReservationFixture { let inventory: AssetInventoryProbe @@ -222,7 +137,9 @@ struct SpeechAssetReservationTests { #expect(state.locales.isEmpty) } } +} +extension SpeechAssetReservationTests { @Test("release uses the observed native locale variant") @MainActor func canonicalVariant() async throws { From 9a526fe93262b528570f01b846ea18d6b23875a8 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 12:57:42 -0500 Subject: [PATCH 14/70] Fence live analyzer setup writes and failure publication --- .../SpeechSession+NativeCaptureInput.swift | 4 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 51 ++++-- .../SpeechSession+ScreenCapture.swift | 14 +- .../AuralKit/SpeechSession+Transcriber.swift | 33 +++- .../LiveSetupAdmissionTests.swift | 170 ++++++++++++++++++ 5 files changed, 235 insertions(+), 37 deletions(-) create mode 100644 Tests/AuralKitTests/LiveSetupAdmissionTests.swift diff --git a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift index 858f92d..45b1a19 100644 --- a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift @@ -70,11 +70,11 @@ extension SpeechSession { compatibleWith: modules, priority: analyzerConfiguration.priority ) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) nativeCaptureSession = provider.captureSession try await prepareAnalyzerForStartIfNeeded(in: nil) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) let analyzerInputs = provider.analyzerInputs nativeCaptureAnalysisTask = Task { [weak self, analyzer, analyzerInputs] in diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 9025f0c..ea7fb6a 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -105,18 +105,18 @@ extension SpeechSession { if Self.shouldLog(.notice) { Self.logger.notice("Starting pipeline setup") } - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try await ensurePermissions() - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try await setupAudioSession() - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider let transcriber = try await setUpSpeechTranscriber( contextualStrings: contextualStrings, startAnalyzerImmediately: !shouldUseNativeCapture ) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) if Self.shouldLog(.info) { Self.logger.info("Transcriber prepared with modules") } @@ -128,10 +128,10 @@ extension SpeechSession { ) if !(try await setUpNativeCaptureStreamingIfAvailable(generation: generation)) { - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try startAudioStreaming() } - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) streamingMode = .liveMicrophone setStatus(.transcribing) @@ -140,14 +140,12 @@ extension SpeechSession { Self.logger.info("Pipeline started (mode: live microphone)") } } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) + await finishFailedPipelineSetup(CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error("Pipeline setup failed: \(error.localizedDescription, privacy: .public)") } - pipelineTask = nil - await finishWithStartupError(error, generation: generation) + await finishFailedPipelineSetup(error, generation: generation) } } @@ -160,18 +158,18 @@ extension SpeechSession { if Self.shouldLog(.notice) { Self.logger.notice("Starting dictation pipeline setup") } - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try await ensurePermissions() - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try await setupAudioSession() - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider let transcriber = try await setUpDictationTranscriber( contextualStrings: contextualStrings, startAnalyzerImmediately: !shouldUseNativeCapture ) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) if Self.shouldLog(.info) { Self.logger.info("Dictation transcriber prepared with modules") } @@ -183,10 +181,10 @@ extension SpeechSession { ) if !(try await setUpNativeCaptureStreamingIfAvailable(generation: generation)) { - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try startAudioStreaming() } - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) streamingMode = .liveMicrophone setStatus(.transcribing) @@ -195,13 +193,28 @@ extension SpeechSession { Self.logger.info("Dictation pipeline started (mode: live microphone)") } } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) + await finishFailedPipelineSetup(CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error("Dictation pipeline setup failed: \(error.localizedDescription, privacy: .public)") } - pipelineTask = nil + await finishFailedPipelineSetup(error, generation: generation) + } + } + + /// A nonthrowing native await may return after stop or replacement. + func checkSetupAdmission(generation: Int) throws { + try Task.checkCancellation() + guard generation == sessionGeneration else { throw CancellationError() } + } + + /// Check ownership before dropping the setup handle, not only inside terminal cleanup. + func finishFailedPipelineSetup(_ error: Error, generation: Int) async { + guard generation == sessionGeneration else { return } + pipelineTask = nil + if error is CancellationError { + await finishCancelledPipelineSetup(generation: generation) + } else { await finishWithStartupError(error, generation: generation) } } diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index e6432fc..2be7a00 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -99,18 +99,18 @@ extension SpeechSession { Self.logger.notice("Starting screen capture pipeline setup") } - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try await ensureSpeechRecognitionAuthorization(context: "for screen capture transcription") - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) let transcriber = try await setUpSpeechTranscriber(contextualStrings: contextualStrings) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) recognizerTask = createSpeechRecognizerTask( transcriber: transcriber, streamContinuation: streamContinuation, generation: generation ) try await setUpScreenCaptureStreaming(options: options, generation: generation) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) streamingMode = .screenCapture setStatus(.transcribing) @@ -119,14 +119,12 @@ extension SpeechSession { Self.logger.info("Pipeline started (mode: screen capture)") } } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) + await finishFailedPipelineSetup(CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error("Screen capture pipeline failed: \(error.localizedDescription, privacy: .public)") } - pipelineTask = nil - await finishWithStartupError(error, generation: generation) + await finishFailedPipelineSetup(error, generation: generation) } } diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index e2d5f2e..f9757e7 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -21,14 +21,15 @@ extension SpeechSession { Self.logger.notice("Setting up transcriber") } + let generation = sessionGeneration let transcriber = try createSpeechTranscriber() let modules = configureModules(transcriber: transcriber) try await ensureModels(modules: modules) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try await configureAnalyzerContext(contextualStrings: contextualStrings) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) if startAnalyzerImmediately { - try await startAnalyzer(modules: modules) + try await startAnalyzer(modules: modules, generation: generation) } return transcriber @@ -42,14 +43,15 @@ extension SpeechSession { Self.logger.notice("Setting up dictation transcriber") } + let generation = sessionGeneration let transcriber = try createDictationTranscriber() let modules = configureModules(transcriber: transcriber) try await ensureModels(modules: modules) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) try await configureAnalyzerContext(contextualStrings: contextualStrings) - try Task.checkCancellation() + try checkSetupAdmission(generation: generation) if startAnalyzerImmediately { - try await startAnalyzer(modules: modules) + try await startAnalyzer(modules: modules, generation: generation) } return transcriber @@ -190,8 +192,21 @@ extension SpeechSession { } } - private func startAnalyzer(modules: [any SpeechModule]) async throws { - guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: modules) else { + /// The optional collaborator replaces only native format selection; admission and all + /// session writes remain here, including when selection ignores task cancellation. + func startAnalyzer( + modules: [any SpeechModule], + generation: Int, + selectFormat: (@MainActor ([any SpeechModule]) async -> AVAudioFormat?)? = nil + ) async throws { + let selectedFormat: AVAudioFormat? + if let selectFormat { + selectedFormat = await selectFormat(modules) + } else { + selectedFormat = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: modules) + } + try checkSetupAdmission(generation: generation) + guard let format = selectedFormat else { throw SpeechSessionError.invalidAudioDataType } analyzerFormat = format @@ -213,8 +228,10 @@ extension SpeechSession { } try await prepareAnalyzerForStartIfNeeded(in: format) + try checkSetupAdmission(generation: generation) try await analyzer.start(inputSequence: inputSequence) + try checkSetupAdmission(generation: generation) if Self.shouldLog(.info) { Self.logger.info("Analyzer started") } diff --git a/Tests/AuralKitTests/LiveSetupAdmissionTests.swift b/Tests/AuralKitTests/LiveSetupAdmissionTests.swift new file mode 100644 index 0000000..641aa6c --- /dev/null +++ b/Tests/AuralKitTests/LiveSetupAdmissionTests.swift @@ -0,0 +1,170 @@ +import Foundation +import Dispatch +import AVFoundation +import Testing +@testable import AuralKit + +@Suite("Live setup admission") +@MainActor +struct LiveSetupAdmissionTests { + @Test("Cancelled format selection cannot repopulate stopped state", arguments: [false, true]) + func stoppedSelection(returnsNil: Bool) async throws { + try await withSelection(returnsNil: returnsNil) { session, gate, task in + try await gate.waitUntilEntered() + task.cancel() + await session.stopTranscribing() + gate.release() + let error = await task.value + #expect(error is CancellationError) + #expect(session.analyzerFormat == nil) + #expect(session.inputSequence == nil) + #expect(session.inputBuilder == nil) + } + } + + @Test("Replaced format selection and its catch cannot publish into a successor", + arguments: [false, true]) + func replacedSelection(returnsNil: Bool) async throws { + try await withSelection(returnsNil: returnsNil) { session, gate, task in + let oldGeneration = session.sessionGeneration + try await gate.waitUntilEntered() + await session.stopTranscribing() + // This is the same generation admission used by public starts. Leave the old + // task uncancelled to exercise generation rejection independently of cancellation. + _ = session.beginStreamGeneration() + gate.release() + let error = await task.value + #expect(error is CancellationError) + #expect(session.analyzerFormat == nil) + #expect(session.inputSequence == nil) + #expect(session.inputBuilder == nil) + + // Public start installs the actual successor setup handle. Cancel synchronously + // before it can enter permissions/models; no native setup is faked or invoked. + let staleError = try #require(error) + let stream = session.startTranscribing() + // No throwing assertion may leave this task unjoined. + let successor = session.pipelineTask + successor?.cancel() + await session.finishFailedPipelineSetup(staleError, generation: oldGeneration) + #expect(session.pipelineTask != nil) + #expect(session.continuation != nil) + await session.finishFailedPipelineSetup( + SpeechSessionError.invalidAudioDataType, generation: oldGeneration + ) + #expect(session.pipelineTask != nil) + #expect(session.continuation != nil) + await session.stopTranscribing() + await successor?.value + withExtendedLifetime(stream) {} + } + } + + @Test("Current selection reaches the owning format and stream writes", + arguments: [false, true]) + func currentSelection(returnsNil: Bool) async throws { + try await withSelection(returnsNil: returnsNil) { session, gate, task in + try await gate.waitUntilEntered() + gate.release() + let error = await task.value + // No analyzer/model is installed in this helper-level fixture. A valid format + // reaches the real writes, then fails the existing missing-analyzer guard. + #expect(error is SpeechSessionError) + #expect((session.analyzerFormat == nil) == returnsNil) + #expect((session.inputSequence == nil) == returnsNil) + #expect((session.inputBuilder == nil) == returnsNil) + } + } + + private func withSelection( + returnsNil: Bool, + body: (SpeechSession, FormatGate, Task) async throws -> Void + ) async throws { + let session = SpeechSession() + let gate = FormatGate() + let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) + let generation = session.beginStreamGeneration() + let task = Task { @MainActor in + do { + try await session.startAnalyzer(modules: [], generation: generation) { _ in + await gate.select(returnsNil ? nil : format) + } + return nil + } catch { + return error + } + } + do { + try await body(session, gate, task) + } catch { + gate.release() + task.cancel() + _ = await task.value + await session.stopTranscribing() + throw error + } + gate.release() + task.cancel() + _ = await task.value + await session.stopTranscribing() + } +} + +/// A deliberately cancellation-ignoring native format lookup. Entry is event-driven; +/// release is persistent, including when fixture cleanup precedes selection entry. +@MainActor +private final class FormatGate { + private let entered: AsyncStream + private let entry: AsyncStream.Continuation + private var releaseContinuation: CheckedContinuation? + private var released = false + + init() { + (entered, entry) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + } + + func select(_ format: AVAudioFormat?) async -> AVAudioFormat? { + entry.yield(()) + entry.finish() + if !released { + await withCheckedContinuation { releaseContinuation = $0 } + } + return format + } + + func release() { + released = true + releaseContinuation?.resume() + releaseContinuation = nil + entry.finish() + } + + func waitUntilEntered() async throws { + let events = entered + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + var iterator = events.makeAsyncIterator() + guard await iterator.next() != nil else { throw CancellationError() } + try Task.checkCancellation() + } + group.addTask { + // Deadline only; entry events, never elapsed time, sequence the test. + let (ticks, tick) = AsyncStream.makeStream() + let timer = DispatchSource.makeTimerSource(queue: .global()) + timer.schedule(deadline: .now() + 2) + timer.setEventHandler { + tick.yield(()) + tick.finish() + } + timer.resume() + defer { timer.cancel() } + var iterator = ticks.makeAsyncIterator() + _ = await iterator.next() + try Task.checkCancellation() + throw TestTimeoutError.timedOut(seconds: 2) + } + defer { group.cancelAll() } + _ = try await group.next() + } + } +} From 91891690534bc5ceec7e30e2554ffed1ddb134ca Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Fri, 6 Nov 2026 13:31:07 -0500 Subject: [PATCH 15/70] Fix detector closure and statement formatting --- .../SpeechSession+VoiceActivation.swift | 10 +++++++--- .../SpeechDetectorLifecycleTests.swift | 19 ++++++++++--------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+VoiceActivation.swift b/Sources/AuralKit/SpeechSession+VoiceActivation.swift index bf8875d..5b34dc2 100644 --- a/Sources/AuralKit/SpeechSession+VoiceActivation.swift +++ b/Sources/AuralKit/SpeechSession+VoiceActivation.swift @@ -43,9 +43,13 @@ extension SpeechSession { func startSpeechDetectorMonitoring() { guard let detector = speechDetector else { return } - monitorSpeechDetectorResults(detector.results, speechDetected: { $0.speechDetected }) { [weak self] result in - self?.handleSpeechDetectorResult(result) - } + monitorSpeechDetectorResults( + detector.results, + speechDetected: { $0.speechDetected }, + onResult: { [weak self] result in + self?.handleSpeechDetectorResult(result) + } + ) } /// Native detector results and controlled sequences share the same owning reader. diff --git a/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift index 43523bb..aa07ed1 100644 --- a/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift +++ b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift @@ -48,8 +48,7 @@ struct SpeechDetectorLifecycleTests { let currentID = try #require(fixture.session.speechDetectorMonitorID) input.yield(false) try await fixture.waitUntil { fixture.values == [false] } - if failed { await source.fail() } - else { await source.finish() } + if failed { await source.fail() } else { await source.finish() } #expect(old.isCancelled) await old.value #expect(!fixture.session.isSpeechDetected) @@ -115,8 +114,7 @@ struct SpeechDetectorLifecycleTests { input.yield(false) try await fixture.waitUntil { fixture.values == [false] } #expect(!fixture.session.isSpeechDetected) - if failed { input.finish(throwing: DetectorTestError.failed) } - else { input.finish() } + if failed { input.finish(throwing: DetectorTestError.failed) } else { input.finish() } await task.value #expect(fixture.session.isSpeechDetected) #expect(fixture.session.speechDetectorMonitorID == nil) @@ -129,8 +127,7 @@ struct SpeechDetectorLifecycleTests { @MainActor private func withFixture(_ operation: @MainActor (DetectorFixture) async throws -> Void) async throws { let fixture = DetectorFixture() - do { try await operation(fixture) } - catch { await fixture.cleanup(); throw error } + do { try await operation(fixture) } catch { await fixture.cleanup(); throw error } await fixture.cleanup() } } @@ -209,9 +206,13 @@ private final class DetectorFixture { func monitor(_ results: Sequence) throws -> Task where Sequence: Sendable, Sequence.Element == Bool { - session.monitorSpeechDetectorResults(results, speechDetected: { $0 }) { [unowned self] detected in - values.append(detected) - } + session.monitorSpeechDetectorResults( + results, + speechDetected: { $0 }, + onResult: { [unowned self] detected in + values.append(detected) + } + ) let task = try #require(session.speechDetectorResultsTask) tasks.append(task) return task From 8baf0339dd7cf57d4e4ddabfc4cf011bcd7bddd9 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 00:58:11 +0530 Subject: [PATCH 16/70] Simplify stream timeout tests to await iterators directly --- Tests/AuralKitTests/AuralKitTests.swift | 49 ++++----- Tests/AuralKitTests/TestTimeoutHelpers.swift | 37 +------ .../TestTimeoutHelpersTests.swift | 99 ------------------- 3 files changed, 20 insertions(+), 165 deletions(-) delete mode 100644 Tests/AuralKitTests/TestTimeoutHelpersTests.swift diff --git a/Tests/AuralKitTests/AuralKitTests.swift b/Tests/AuralKitTests/AuralKitTests.swift index 809d648..52e862b 100644 --- a/Tests/AuralKitTests/AuralKitTests.swift +++ b/Tests/AuralKitTests/AuralKitTests.swift @@ -85,20 +85,11 @@ struct SpeechSessionStateTests { #expect(firstA == .some(.idle)) #expect(firstB == .some(.idle)) - let nextA = Task { - await probeA.next() - } - let nextB = Task { - await probeB.next() - } - try await withOwnedTasks([nextA, nextB]) { - session.setStatus(.preparing) - - let valueA = try await awaitResult(task: nextA) - let valueB = try await awaitResult(task: nextB) - #expect(valueA == .some(.preparing)) - #expect(valueB == .some(.preparing)) - } + session.setStatus(.preparing) + let valueA = try await awaitResult { await probeA.next() } + let valueB = try await awaitResult { await probeB.next() } + #expect(valueA == .some(.preparing)) + #expect(valueB == .some(.preparing)) } } @@ -149,23 +140,21 @@ struct SpeechSessionAudioInputStreamTests { let probeA = AsyncStreamProbe(session.audioInputConfigurationStream) let probeB = AsyncStreamProbe(session.audioInputConfigurationStream) - let valueA = Task { - await probeA.next() - } - let valueB = Task { - await probeB.next() - } - try await withOwnedTasks([valueA, valueB]) { - await Task.yield() - session.broadcastAudioInputInfo(nil) - - let firstA = try await awaitResult(task: valueA) - let firstB = try await awaitResult(task: valueB) - let flattenedA = firstA?.flatMap { $0 } - let flattenedB = firstB?.flatMap { $0 } - #expect(flattenedA == nil) - #expect(flattenedB == nil) + try await awaitResult { + while session.audioInputContinuations.count < 2 { + try Task.checkCancellation() + await Task.yield() + } } + session.broadcastAudioInputInfo(nil) + let firstA = try await awaitResult { await probeA.next() } + let firstB = try await awaitResult { await probeB.next() } + #expect(firstA != nil) + #expect(firstB != nil) + let flattenedA = firstA?.flatMap { $0 } + let flattenedB = firstB?.flatMap { $0 } + #expect(flattenedA == nil) + #expect(flattenedB == nil) } } diff --git a/Tests/AuralKitTests/TestTimeoutHelpers.swift b/Tests/AuralKitTests/TestTimeoutHelpers.swift index d43c3cf..4d3c1f9 100644 --- a/Tests/AuralKitTests/TestTimeoutHelpers.swift +++ b/Tests/AuralKitTests/TestTimeoutHelpers.swift @@ -40,46 +40,11 @@ func awaitResult( throw TestTimeoutError.timedOut(seconds: seconds) } - defer { group.cancelAll() } guard let value = try await group.next() else { fatalError("Timeout helper started without any tasks") } + group.cancelAll() return value } } - -// Cancellation must reach the actual task, not just the child awaiting its value. -// The task must cooperate with cancellation; this helper still joins its completion. -@MainActor -func awaitResult( - timeout seconds: TimeInterval = 1.0, - task: Task -) async throws -> T { - try await awaitResult(timeout: seconds) { - try await withTaskCancellationHandler { - let value = await task.value - try Task.checkCancellation() - return value - } onCancel: { - task.cancel() - } - } -} - -@MainActor -func withOwnedTasks( - _ tasks: [Task], - operation: @MainActor () async throws -> Result -) async rethrows -> Result { - do { - let result = try await operation() - for task in tasks { task.cancel() } - for task in tasks { _ = await task.value } - return result - } catch { - for task in tasks { task.cancel() } - for task in tasks { _ = await task.value } - throw error - } -} diff --git a/Tests/AuralKitTests/TestTimeoutHelpersTests.swift b/Tests/AuralKitTests/TestTimeoutHelpersTests.swift deleted file mode 100644 index 1b2b163..0000000 --- a/Tests/AuralKitTests/TestTimeoutHelpersTests.swift +++ /dev/null @@ -1,99 +0,0 @@ -import Foundation -import Testing - -@Suite("Timeout task ownership") -@MainActor -struct TestTimeoutHelpersTests { - enum Exit: Sendable, CaseIterable { case timeout, cancelledBeforeWait, cancelledDuringWait } - enum FixtureError: Error { case expected } - - @Test("Timeout and cancellation join stream consumers and producers", arguments: Exit.allCases) - func streamTasksAreJoined(exit: Exit) async throws { - let values = AsyncStream.makeStream() - let producerGate = AsyncStream.makeStream() - let ready = AsyncStream.makeStream() - let state = CompletionState() - let producer = Task { @MainActor in - defer { - state.producerFinished = true - values.continuation.finish() - } - ready.continuation.yield(()) - var iterator = producerGate.stream.makeAsyncIterator() - _ = await iterator.next() - return nil - } - let consumer = Task { @MainActor in - defer { state.consumerFinished = true } - ready.continuation.yield(()) - var iterator = values.stream.makeAsyncIterator() - return await iterator.next() - } - try await withOwnedTasks([producer, consumer]) { - // Both tasks have entered their real stream waits before the race begins. - let probe = AsyncStreamProbe(ready.stream) - _ = try await awaitResult { await probe.next() } - _ = try await awaitResult { await probe.next() } - let entered = AsyncStream.makeStream() - let waiter = Task { @MainActor in - entered.continuation.yield(()) - return try await awaitResult(timeout: 0.02, task: consumer) - } - if exit == .cancelledBeforeWait { - // No actor suspension since task creation: cancellation predates entry. - waiter.cancel() - } else if exit == .cancelledDuringWait { - var iterator = entered.stream.makeAsyncIterator() - _ = await iterator.next() - waiter.cancel() - } - do { - _ = try await waiter.value - Issue.record("Expected timeout or cancellation") - } catch is TestTimeoutError { - #expect(exit == .timeout) - } catch is CancellationError { - #expect(exit != .timeout) - } - #expect(state.consumerFinished) - } - #expect(state.producerFinished) - #expect(state.consumerFinished) - producerGate.continuation.finish() - ready.continuation.finish() - } - - @Test("Values and operation errors propagate") - func valuesAndErrors() async throws { - let value = try await awaitResult { 42 } - #expect(value == 42) - let taskValue = try await awaitResult(task: Task { 43 }) - #expect(taskValue == 43) - do { - let _: Int = try await awaitResult { throw FixtureError.expected } - Issue.record("Expected operation error") - } catch FixtureError.expected { } - } - - @Test("Throwing fixture scope cancels and joins its task") - func throwingScopeJoins() async { - let stream = AsyncStream.makeStream() - let state = CompletionState() - let task = Task { @MainActor in - defer { state.consumerFinished = true } - var iterator = stream.stream.makeAsyncIterator() - return await iterator.next() - } - do { - try await withOwnedTasks([task]) { throw FixtureError.expected } - } catch { } - #expect(state.consumerFinished) - stream.continuation.finish() - } -} - -@MainActor -private final class CompletionState { - var producerFinished = false - var consumerFinished = false -} From e589f5b95084492b26f88ea8afc576d3e7cc9d12 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 00:58:55 +0530 Subject: [PATCH 17/70] Keep file read bounds at the read site --- Sources/AuralKit/AudioFileReadSize.swift | 7 ---- Sources/AuralKit/SpeechSession+File.swift | 5 +-- .../FileTranscriptionReadSizeTests.swift | 38 ------------------- 3 files changed, 1 insertion(+), 49 deletions(-) delete mode 100644 Sources/AuralKit/AudioFileReadSize.swift delete mode 100644 Tests/AuralKitTests/FileTranscriptionReadSizeTests.swift diff --git a/Sources/AuralKit/AudioFileReadSize.swift b/Sources/AuralKit/AudioFileReadSize.swift deleted file mode 100644 index f806218..0000000 --- a/Sources/AuralKit/AudioFileReadSize.swift +++ /dev/null @@ -1,7 +0,0 @@ -/// Bounds the signed 64-bit file remainder before narrowing to a per-read count. -/// Even a file longer than UInt32.max frames needs only one buffer per read. -enum AudioFileReadSize { - static func next(remaining: Int64, capacity: UInt32) -> UInt32 { - UInt32(min(max(remaining, 0), Int64(capacity))) - } -} diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index d3bb0ef..a765af7 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -300,10 +300,7 @@ private extension SpeechSession { while processedFrames < totalFrames { if Task.isCancelled { break } - let framesToRead = AudioFileReadSize.next( - remaining: totalFrames - processedFrames, - capacity: buffer.frameCapacity - ) + let framesToRead = AVAudioFrameCount(min(Int64(frameCapacity), totalFrames - processedFrames)) buffer.frameLength = framesToRead diff --git a/Tests/AuralKitTests/FileTranscriptionReadSizeTests.swift b/Tests/AuralKitTests/FileTranscriptionReadSizeTests.swift deleted file mode 100644 index 5284bb4..0000000 --- a/Tests/AuralKitTests/FileTranscriptionReadSizeTests.swift +++ /dev/null @@ -1,38 +0,0 @@ -import Testing -@testable import AuralKit - -@Suite("File transcription read sizes") -struct FileTranscriptionReadSizeTests { - @Test("large file remainders fit a single buffer", arguments: [ - Int64(UInt32.max), Int64(UInt32.max) + 1, Int64.max - ]) - func largeRemainders(_ remaining: Int64) { - #expect(AudioFileReadSize.next(remaining: remaining, capacity: 4_096) == 4_096) - } - - @Test("ordinary remainders include the final short read", arguments: [ - (Int64(0), UInt32(0)), - (1, 1), - (17, 17), - (4_095, 4_095), - (4_096, 4_096), - (4_097, 4_096) - ]) - func ordinaryRemainders(remaining: Int64, expected: UInt32) { - #expect(AudioFileReadSize.next(remaining: remaining, capacity: 4_096) == expected) - } - - @Test("the actual buffer capacity limits the read", arguments: [ - UInt32(0), 1, 17, 4_096, UInt32.max - ]) - func capacityBoundaries(_ capacity: UInt32) { - #expect(AudioFileReadSize.next(remaining: Int64.max, capacity: capacity) == capacity) - #expect(AudioFileReadSize.next(remaining: 0, capacity: capacity) == 0) - #expect(AudioFileReadSize.next(remaining: 1, capacity: capacity) == min(1, capacity)) - } - - @Test("nonpositive remainders produce no read", arguments: [Int64.min, -1, 0]) - func nonpositiveRemainders(_ remaining: Int64) { - #expect(AudioFileReadSize.next(remaining: remaining, capacity: UInt32.max) == 0) - } -} From d0bd68ee56875bfd2b4dbc2727b167901cdf62a6 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 00:59:02 +0530 Subject: [PATCH 18/70] test: reproduce vocabulary cancellation and temporary storage regressions --- Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift index baf5374..3ad945f 100644 --- a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift +++ b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift @@ -30,6 +30,7 @@ struct CustomVocabularyOwnershipTests { try await second!.configureCustomVocabulary(descriptor()) let firstDirectory = try #require(first?.customVocabularyOutputDirectory) let secondDirectory = try #require(second?.customVocabularyOutputDirectory) + #expect(firstDirectory.path.hasPrefix(FileManager.default.temporaryDirectory.path)) #expect(firstDirectory != secondDirectory) #expect(first?.customVocabularyCacheKey == second?.customVocabularyCacheKey) #expect(second?.customVocabularyConfiguration?.weight?.doubleValue == 0.4) @@ -187,6 +188,7 @@ private actor VocabularyPreparation { ready.continuation.yield(directory) var iterator = release.stream.makeAsyncIterator() _ = await iterator.next() + try Task.checkCancellation() } } } From 857a0c7f9040c0215feaa890fa13a25903c4e8a6 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 00:59:45 +0530 Subject: [PATCH 19/70] Limit stale setup failure cleanup to its owning generation --- Sources/AuralKit/SpeechSession+File.swift | 6 +- .../SpeechSession+NativeCaptureInput.swift | 4 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 31 ++-- .../SpeechSession+ScreenCapture.swift | 8 +- .../AuralKit/SpeechSession+Transcriber.swift | 33 +--- .../LiveSetupAdmissionTests.swift | 170 ------------------ .../AuralKitTests/SessionLifecycleTests.swift | 20 +++ 7 files changed, 48 insertions(+), 224 deletions(-) delete mode 100644 Tests/AuralKitTests/LiveSetupAdmissionTests.swift diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 56ebbcb..a5b16e9 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -171,14 +171,12 @@ private extension SpeechSession { } } } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) + await finishFailedPipelineSetup(CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error("File transcription pipeline failed: \(error.localizedDescription, privacy: .public)") } - pipelineTask = nil - await finishWithStartupError(error, generation: generation) + await finishFailedPipelineSetup(error, generation: generation) } } diff --git a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift index 45b1a19..858f92d 100644 --- a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift @@ -70,11 +70,11 @@ extension SpeechSession { compatibleWith: modules, priority: analyzerConfiguration.priority ) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() nativeCaptureSession = provider.captureSession try await prepareAnalyzerForStartIfNeeded(in: nil) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() let analyzerInputs = provider.analyzerInputs nativeCaptureAnalysisTask = Task { [weak self, analyzer, analyzerInputs] in diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index ea7fb6a..da7089e 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -105,18 +105,18 @@ extension SpeechSession { if Self.shouldLog(.notice) { Self.logger.notice("Starting pipeline setup") } - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try await ensurePermissions() - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try await setupAudioSession() - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider let transcriber = try await setUpSpeechTranscriber( contextualStrings: contextualStrings, startAnalyzerImmediately: !shouldUseNativeCapture ) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() if Self.shouldLog(.info) { Self.logger.info("Transcriber prepared with modules") } @@ -128,10 +128,10 @@ extension SpeechSession { ) if !(try await setUpNativeCaptureStreamingIfAvailable(generation: generation)) { - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try startAudioStreaming() } - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() streamingMode = .liveMicrophone setStatus(.transcribing) @@ -158,18 +158,18 @@ extension SpeechSession { if Self.shouldLog(.notice) { Self.logger.notice("Starting dictation pipeline setup") } - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try await ensurePermissions() - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try await setupAudioSession() - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider let transcriber = try await setUpDictationTranscriber( contextualStrings: contextualStrings, startAnalyzerImmediately: !shouldUseNativeCapture ) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() if Self.shouldLog(.info) { Self.logger.info("Dictation transcriber prepared with modules") } @@ -181,10 +181,10 @@ extension SpeechSession { ) if !(try await setUpNativeCaptureStreamingIfAvailable(generation: generation)) { - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try startAudioStreaming() } - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() streamingMode = .liveMicrophone setStatus(.transcribing) @@ -202,13 +202,6 @@ extension SpeechSession { } } - /// A nonthrowing native await may return after stop or replacement. - func checkSetupAdmission(generation: Int) throws { - try Task.checkCancellation() - guard generation == sessionGeneration else { throw CancellationError() } - } - - /// Check ownership before dropping the setup handle, not only inside terminal cleanup. func finishFailedPipelineSetup(_ error: Error, generation: Int) async { guard generation == sessionGeneration else { return } pipelineTask = nil diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 2be7a00..6d426f1 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -99,18 +99,18 @@ extension SpeechSession { Self.logger.notice("Starting screen capture pipeline setup") } - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try await ensureSpeechRecognitionAuthorization(context: "for screen capture transcription") - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() let transcriber = try await setUpSpeechTranscriber(contextualStrings: contextualStrings) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() recognizerTask = createSpeechRecognizerTask( transcriber: transcriber, streamContinuation: streamContinuation, generation: generation ) try await setUpScreenCaptureStreaming(options: options, generation: generation) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() streamingMode = .screenCapture setStatus(.transcribing) diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index f9757e7..e2d5f2e 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -21,15 +21,14 @@ extension SpeechSession { Self.logger.notice("Setting up transcriber") } - let generation = sessionGeneration let transcriber = try createSpeechTranscriber() let modules = configureModules(transcriber: transcriber) try await ensureModels(modules: modules) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try await configureAnalyzerContext(contextualStrings: contextualStrings) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() if startAnalyzerImmediately { - try await startAnalyzer(modules: modules, generation: generation) + try await startAnalyzer(modules: modules) } return transcriber @@ -43,15 +42,14 @@ extension SpeechSession { Self.logger.notice("Setting up dictation transcriber") } - let generation = sessionGeneration let transcriber = try createDictationTranscriber() let modules = configureModules(transcriber: transcriber) try await ensureModels(modules: modules) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() try await configureAnalyzerContext(contextualStrings: contextualStrings) - try checkSetupAdmission(generation: generation) + try Task.checkCancellation() if startAnalyzerImmediately { - try await startAnalyzer(modules: modules, generation: generation) + try await startAnalyzer(modules: modules) } return transcriber @@ -192,21 +190,8 @@ extension SpeechSession { } } - /// The optional collaborator replaces only native format selection; admission and all - /// session writes remain here, including when selection ignores task cancellation. - func startAnalyzer( - modules: [any SpeechModule], - generation: Int, - selectFormat: (@MainActor ([any SpeechModule]) async -> AVAudioFormat?)? = nil - ) async throws { - let selectedFormat: AVAudioFormat? - if let selectFormat { - selectedFormat = await selectFormat(modules) - } else { - selectedFormat = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: modules) - } - try checkSetupAdmission(generation: generation) - guard let format = selectedFormat else { + private func startAnalyzer(modules: [any SpeechModule]) async throws { + guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: modules) else { throw SpeechSessionError.invalidAudioDataType } analyzerFormat = format @@ -228,10 +213,8 @@ extension SpeechSession { } try await prepareAnalyzerForStartIfNeeded(in: format) - try checkSetupAdmission(generation: generation) try await analyzer.start(inputSequence: inputSequence) - try checkSetupAdmission(generation: generation) if Self.shouldLog(.info) { Self.logger.info("Analyzer started") } diff --git a/Tests/AuralKitTests/LiveSetupAdmissionTests.swift b/Tests/AuralKitTests/LiveSetupAdmissionTests.swift deleted file mode 100644 index 641aa6c..0000000 --- a/Tests/AuralKitTests/LiveSetupAdmissionTests.swift +++ /dev/null @@ -1,170 +0,0 @@ -import Foundation -import Dispatch -import AVFoundation -import Testing -@testable import AuralKit - -@Suite("Live setup admission") -@MainActor -struct LiveSetupAdmissionTests { - @Test("Cancelled format selection cannot repopulate stopped state", arguments: [false, true]) - func stoppedSelection(returnsNil: Bool) async throws { - try await withSelection(returnsNil: returnsNil) { session, gate, task in - try await gate.waitUntilEntered() - task.cancel() - await session.stopTranscribing() - gate.release() - let error = await task.value - #expect(error is CancellationError) - #expect(session.analyzerFormat == nil) - #expect(session.inputSequence == nil) - #expect(session.inputBuilder == nil) - } - } - - @Test("Replaced format selection and its catch cannot publish into a successor", - arguments: [false, true]) - func replacedSelection(returnsNil: Bool) async throws { - try await withSelection(returnsNil: returnsNil) { session, gate, task in - let oldGeneration = session.sessionGeneration - try await gate.waitUntilEntered() - await session.stopTranscribing() - // This is the same generation admission used by public starts. Leave the old - // task uncancelled to exercise generation rejection independently of cancellation. - _ = session.beginStreamGeneration() - gate.release() - let error = await task.value - #expect(error is CancellationError) - #expect(session.analyzerFormat == nil) - #expect(session.inputSequence == nil) - #expect(session.inputBuilder == nil) - - // Public start installs the actual successor setup handle. Cancel synchronously - // before it can enter permissions/models; no native setup is faked or invoked. - let staleError = try #require(error) - let stream = session.startTranscribing() - // No throwing assertion may leave this task unjoined. - let successor = session.pipelineTask - successor?.cancel() - await session.finishFailedPipelineSetup(staleError, generation: oldGeneration) - #expect(session.pipelineTask != nil) - #expect(session.continuation != nil) - await session.finishFailedPipelineSetup( - SpeechSessionError.invalidAudioDataType, generation: oldGeneration - ) - #expect(session.pipelineTask != nil) - #expect(session.continuation != nil) - await session.stopTranscribing() - await successor?.value - withExtendedLifetime(stream) {} - } - } - - @Test("Current selection reaches the owning format and stream writes", - arguments: [false, true]) - func currentSelection(returnsNil: Bool) async throws { - try await withSelection(returnsNil: returnsNil) { session, gate, task in - try await gate.waitUntilEntered() - gate.release() - let error = await task.value - // No analyzer/model is installed in this helper-level fixture. A valid format - // reaches the real writes, then fails the existing missing-analyzer guard. - #expect(error is SpeechSessionError) - #expect((session.analyzerFormat == nil) == returnsNil) - #expect((session.inputSequence == nil) == returnsNil) - #expect((session.inputBuilder == nil) == returnsNil) - } - } - - private func withSelection( - returnsNil: Bool, - body: (SpeechSession, FormatGate, Task) async throws -> Void - ) async throws { - let session = SpeechSession() - let gate = FormatGate() - let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) - let generation = session.beginStreamGeneration() - let task = Task { @MainActor in - do { - try await session.startAnalyzer(modules: [], generation: generation) { _ in - await gate.select(returnsNil ? nil : format) - } - return nil - } catch { - return error - } - } - do { - try await body(session, gate, task) - } catch { - gate.release() - task.cancel() - _ = await task.value - await session.stopTranscribing() - throw error - } - gate.release() - task.cancel() - _ = await task.value - await session.stopTranscribing() - } -} - -/// A deliberately cancellation-ignoring native format lookup. Entry is event-driven; -/// release is persistent, including when fixture cleanup precedes selection entry. -@MainActor -private final class FormatGate { - private let entered: AsyncStream - private let entry: AsyncStream.Continuation - private var releaseContinuation: CheckedContinuation? - private var released = false - - init() { - (entered, entry) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) - } - - func select(_ format: AVAudioFormat?) async -> AVAudioFormat? { - entry.yield(()) - entry.finish() - if !released { - await withCheckedContinuation { releaseContinuation = $0 } - } - return format - } - - func release() { - released = true - releaseContinuation?.resume() - releaseContinuation = nil - entry.finish() - } - - func waitUntilEntered() async throws { - let events = entered - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - var iterator = events.makeAsyncIterator() - guard await iterator.next() != nil else { throw CancellationError() } - try Task.checkCancellation() - } - group.addTask { - // Deadline only; entry events, never elapsed time, sequence the test. - let (ticks, tick) = AsyncStream.makeStream() - let timer = DispatchSource.makeTimerSource(queue: .global()) - timer.schedule(deadline: .now() + 2) - timer.setEventHandler { - tick.yield(()) - tick.finish() - } - timer.resume() - defer { timer.cancel() } - var iterator = ticks.makeAsyncIterator() - _ = await iterator.next() - try Task.checkCancellation() - throw TestTimeoutError.timedOut(seconds: 2) - } - defer { group.cancelAll() } - _ = try await group.next() - } - } -} diff --git a/Tests/AuralKitTests/SessionLifecycleTests.swift b/Tests/AuralKitTests/SessionLifecycleTests.swift index 7532d07..bc50a4f 100644 --- a/Tests/AuralKitTests/SessionLifecycleTests.swift +++ b/Tests/AuralKitTests/SessionLifecycleTests.swift @@ -122,6 +122,26 @@ struct SpeechSessionLifecycleTests { #expect(session.continuation == nil) } + @Test("Stale setup failures preserve the successor setup task") + @MainActor + func staleSetupFailurePreservesSuccessorTask() async { + let session = SpeechSession() + let staleGeneration = session.beginStreamGeneration() + _ = session.beginStreamGeneration() + let successor = Task {} + session.pipelineTask = successor + + await session.finishFailedPipelineSetup(CancellationError(), generation: staleGeneration) + #expect(session.pipelineTask == successor) + await session.finishFailedPipelineSetup( + SpeechSessionError.invalidAudioDataType, generation: staleGeneration + ) + #expect(session.pipelineTask == successor) + + await session.stopTranscribing() + await successor.value + } + /// 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 beffc3f6b869778b38e60f4cabf23895f723a1f4 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:00:20 +0530 Subject: [PATCH 20/70] fix: keep vocabulary artifacts temporary and preserve cancellation --- .../SpeechSession+CustomVocabulary.swift | 18 ++++++------------ ...Session+CustomVocabularyConfiguration.swift | 4 ++++ 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+CustomVocabulary.swift b/Sources/AuralKit/SpeechSession+CustomVocabulary.swift index 4ce9d62..a543a29 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabulary.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabulary.swift @@ -215,24 +215,15 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send } private func preparePaths(for cacheKey: String) throws -> CompilationPaths { - let baseDirectories = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask) - guard let baseDirectory = baseDirectories.first else { - throw SpeechSessionError.customVocabularyPreparationFailed - } - - let outputDirectory = baseDirectory + let outputDirectory = fileManager.temporaryDirectory .appendingPathComponent("com.auralkit.vocabulary", isDirectory: true) .appendingPathComponent("\(cacheKey)-\(UUID().uuidString)", isDirectory: true) - if !fileManager.fileExists(atPath: outputDirectory.path) { - try fileManager.createDirectory(at: outputDirectory, withIntermediateDirectories: true) - } + try fileManager.createDirectory(at: outputDirectory, withIntermediateDirectories: true) let languageModelURL = outputDirectory.appendingPathComponent("languageModel.bin") let vocabularyURL = outputDirectory.appendingPathComponent("vocabulary.bin") - // Use UUID to ensure unique temp file per compilation invocation, preventing races - let uniqueID = UUID().uuidString - let assetURL = outputDirectory.appendingPathComponent("source-\(uniqueID).bin") + let assetURL = outputDirectory.appendingPathComponent("source.bin") return CompilationPaths( outputDirectory: outputDirectory, @@ -284,7 +275,10 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send do { // The session already runs the compiler in a detached task and joins it. try await prepareModel(descriptor, paths.assetURL, configuration) + } catch is CancellationError { + throw CancellationError() } catch { + try Task.checkCancellation() throw SpeechSessionError.customVocabularyCompilationFailed(error) } } diff --git a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift index 4d269de..f749abd 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift @@ -8,6 +8,10 @@ extension SpeechSession { /// Configure the session's custom vocabulary, compiling assets as needed. /// + /// Compiled files are temporary and remain available while the session or a native consumer uses them. + /// Cancelling compilation waits for preparation to finish, then throws `CancellationError` + /// without replacing the current configuration. Superseded compilation results are discarded. + /// /// - Parameter vocabulary: The vocabulary descriptor to activate, or `nil` to clear the current /// configuration. /// - Throws: A `SpeechSessionError` when the session is active, the descriptor locale mismatches, or From e9d836181d3fafbb18c31abc40d6be6aba65a441 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:00:47 +0530 Subject: [PATCH 21/70] Reproduce paused status after a superseded screen resume --- Tests/AuralKitTests/ScreenCaptureTransitionTests.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index 9371a69..59e1a3d 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -288,11 +288,11 @@ extension ScreenCaptureTransitionTests { try await resume.value try await successorStarted.wait() #expect(!runtime.consumerFinished) - #expect(runtime.session.status == .paused) + #expect(runtime.session.status == .transcribing) #expect(runtime.owner.stream === successor) - // Explicitly resume the current selection, then fail that current start. - try await runtime.session.resumeTranscribing() + #expect(successor.capturing) await runtime.session.pauseTranscribing() + #expect(!successor.capturing) successor.startError = CaptureFixtureError.startFailed runtime.finalizeRelease.open() do { From 58d57fafa032f888bd75b0f1c50632f7a53af2e9 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:01:25 +0530 Subject: [PATCH 22/70] Limit file progress delivery to the active session --- Sources/AuralKit/SpeechSession+File.swift | 131 ++++--- .../SpeechSession+FileLifecycle.swift | 135 ------- .../SpeechSession+NativeFileInput.swift | 13 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 9 +- Sources/AuralKit/SpeechSession.swift | 8 +- Tests/AuralKitTests/FileProgressTests.swift | 46 +++ .../FileTranscriptionJoinTestFixtures.swift | 50 --- .../FileTranscriptionJoinTests.swift | 370 ------------------ 8 files changed, 125 insertions(+), 637 deletions(-) delete mode 100644 Sources/AuralKit/SpeechSession+FileLifecycle.swift create mode 100644 Tests/AuralKitTests/FileProgressTests.swift delete mode 100644 Tests/AuralKitTests/FileTranscriptionJoinTestFixtures.swift delete mode 100644 Tests/AuralKitTests/FileTranscriptionJoinTests.swift diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 4285006..9002ddb 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -83,33 +83,14 @@ public extension SpeechSession { setStatus(.preparing) continuation = .speech(newContinuation) - let run = FileTranscriptionRun( - finalize: { [self] inputFinalizationStarted in - prepareForStop() - streamingMode = .inactive - activeResultKind = nil - let detached = detachTranscriberState() - detached.inputBuilder?.finish() - if !inputFinalizationStarted { - try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() - } - }, - complete: { [self] error in - await modelManager.releaseLocales() - setStatus(.idle) - fileTranscription = nil - await finishStream(error: error, generation: generation) - } - ) - fileTranscription = run - run.startSetup { [weak self] in + pipelineTask = Task { @MainActor [weak self] in guard let self else { return } - try await self.startFilePipeline( - run: run, + await self.startFilePipeline( with: newContinuation, audioFileURL: audioFile, options: options, - progressHandler: progressHandler + progressHandler: progressHandler, + generation: generation ) } @@ -152,28 +133,52 @@ public extension SpeechSession { private extension SpeechSession { func startFilePipeline( - run: FileTranscriptionRun, with streamContinuation: AsyncThrowingStream.Continuation, audioFileURL: URL, options: FileTranscriptionOptions, - progressHandler: (@Sendable (Double) -> Void)? - ) async throws { - try Task.checkCancellation() - let validation = try validateAudioFile(at: audioFileURL, options: options) - try await ensureSpeechRecognitionAuthorization(context: "for file transcription") - try Task.checkCancellation() - let shouldUseNativeAnalyzer = shouldUseNativeFileAnalyzer(progressHandler: progressHandler) - try await setUpFilePipeline( - run: run, - with: streamContinuation, - contextualStrings: options.contextualStrings, - startAnalyzerImmediately: !shouldUseNativeAnalyzer - ) - try Task.checkCancellation() - run.startIngestion { [self] in - let completed = try await feedAudioFile(validation, progressHandler: progressHandler) - if completed { progressHandler?(1.0) } - return completed + progressHandler: (@Sendable (Double) -> Void)?, + generation: Int + ) async { + do { + try Task.checkCancellation() + let validation = try validateAudioFile(at: audioFileURL, options: options) + try await ensureSpeechRecognitionAuthorization(context: "for file transcription") + try Task.checkCancellation() + let shouldUseNativeAnalyzer = shouldUseNativeFileAnalyzer(progressHandler: progressHandler) + try await setUpFilePipeline( + with: streamContinuation, + contextualStrings: options.contextualStrings, + startAnalyzerImmediately: !shouldUseNativeAnalyzer, + generation: generation + ) + try Task.checkCancellation() + let handler = progressHandler + fileIngestionTask = Task { [weak self] in + guard let self else { return } + + do { + let completed = try await self.feedAudioFile( + validation, progressHandler: handler, generation: generation + ) + + if completed, let handler { + self.reportFileProgress(1.0, handler: handler, generation: generation) + } + } catch is CancellationError { + // Swallow cancellation triggered by cleanup. + } catch { + await self.finishWithStartupError(error, generation: generation) + } + } + } catch is CancellationError { + pipelineTask = nil + await finishCancelledPipelineSetup(generation: generation) + } catch { + if Self.shouldLog(.error) { + Self.logger.error("File transcription pipeline failed: \(error.localizedDescription, privacy: .public)") + } + pipelineTask = nil + await finishWithStartupError(error, generation: generation) } } @@ -241,10 +246,10 @@ private extension SpeechSession { } func setUpFilePipeline( - run: FileTranscriptionRun, with streamContinuation: AsyncThrowingStream.Continuation, contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]?, - startAnalyzerImmediately: Bool + startAnalyzerImmediately: Bool, + generation: Int ) async throws { if Self.shouldLog(.notice) { Self.logger.notice("Starting file transcription pipeline") @@ -257,9 +262,11 @@ private extension SpeechSession { try Task.checkCancellation() activeResultKind = .speech - run.startResults(transcriber.results) { result in - streamContinuation.yield(result) - } + recognizerTask = createSpeechRecognizerTask( + transcriber: transcriber, + streamContinuation: streamContinuation, + generation: generation + ) streamingMode = .filePlayback setStatus(.transcribing) @@ -270,7 +277,8 @@ private extension SpeechSession { nonisolated func feedAudioFile( _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), - progressHandler: (@Sendable (Double) -> Void)? + progressHandler: (@Sendable (Double) -> Void)?, + generation: Int ) async throws -> Bool { #if swift(>=6.4) if #available(iOS 27.0, macOS 27.0, *), @@ -320,28 +328,17 @@ private extension SpeechSession { if let progressHandler, totalFrames > 0 { let progress = min(1.0, max(0.0, Double(processedFrames) / Double(totalFrames))) - await MainActor.run { - progressHandler(progress) - } + await reportFileProgress(progress, handler: progressHandler, generation: generation) } } guard !Task.isCancelled else { return false } - guard processedFrames >= totalFrames else { return false } - - try await finishFileInput() + try await self.finishAnalyzerInput() return !Task.isCancelled && processedFrames >= totalFrames } - func finishFileInput() async throws { - guard let run = fileTranscription else { - throw SpeechSessionError.recognitionStreamSetupFailed - } - try await run.finishInput { try await self.finishAnalyzerInput() } - } - func shouldUseNativeFileAnalyzer(progressHandler: (@Sendable (Double) -> Void)?) -> Bool { #if swift(>=6.4) if #available(iOS 27.0, macOS 27.0, *) { @@ -352,3 +349,15 @@ private extension SpeechSession { } } + +extension SpeechSession { + func reportFileProgress( + _ progress: Double, + handler: @Sendable (Double) -> Void, + generation: Int + ) { + guard !Task.isCancelled, generation == sessionGeneration, + streamingMode == .filePlayback, status == .transcribing else { return } + handler(progress) + } +} diff --git a/Sources/AuralKit/SpeechSession+FileLifecycle.swift b/Sources/AuralKit/SpeechSession+FileLifecycle.swift deleted file mode 100644 index a19fc96..0000000 --- a/Sources/AuralKit/SpeechSession+FileLifecycle.swift +++ /dev/null @@ -1,135 +0,0 @@ -import Foundation - -/// Owns the actual tasks for one file stream. Producers request retirement and -/// return; only the separate terminal task joins them, so none can join itself. -@MainActor -final class FileTranscriptionRun { - private var setupTask: Task? - private var ingestionTask: Task? - private var resultTask: Task? - private(set) var terminalTask: Task? - private var stoppingInput = false - private var terminalError: Error? - private var inputFinalizationStarted = false - private let finalize: @MainActor (Bool) async throws -> Void - private let complete: @MainActor (Error?) async -> Void - - init( - finalize: @escaping @MainActor (Bool) async throws -> Void, - complete: @escaping @MainActor (Error?) async -> Void - ) { - self.finalize = finalize - self.complete = complete - } - - func startSetup(_ operation: @escaping @MainActor () async throws -> Void) { - precondition(setupTask == nil) - setupTask = Task { - do { - try Task.checkCancellation() - try await operation() - } catch { - requestRetirement(error: error, ownerCancelled: Task.isCancelled) - } - } - } - - func startIngestion(_ operation: @escaping @MainActor () async throws -> Bool) { - precondition(ingestionTask == nil) - ingestionTask = Task { - do { - try Task.checkCancellation() - let completed = try await operation() - try Task.checkCancellation() - guard completed else { - throw SpeechSessionError.audioFileReadFailed(CocoaError( - .fileReadUnknown, - userInfo: [NSLocalizedDescriptionKey: "Audio input ended before all declared frames were read."] - )) - } - } catch { - requestRetirement(error: error, ownerCancelled: Task.isCancelled) - } - } - // Setup can install a child after stop has already latched retirement. - if stoppingInput { ingestionTask?.cancel() } - } - - func startResults( - _ results: Sequence, - yield: @escaping @MainActor (Sequence.Element) -> Void - ) where Sequence: Sendable, Sequence.Element: Sendable { - precondition(resultTask == nil) - resultTask = Task { - do { - for try await result in results { - yield(result) - } - try Task.checkCancellation() - requestRetirement(cancelInput: false) - } catch { - requestRetirement(error: error, ownerCancelled: Task.isCancelled) - } - } - } - - /// Called at the actual normal-feed finalization boundary, before suspension. - /// Even a failed attempt must not be repeated by terminal cleanup. - func finishInput(_ operation: @MainActor () async throws -> Void) async throws { - precondition(!inputFinalizationStarted) - inputFinalizationStarted = true - do { - try await operation() - } catch { - record(error, ownerCancelled: Task.isCancelled) - // A failed normal finalization cannot promise result EOF either. - resultTask?.cancel() - throw error - } - } - - private func record(_ error: Error?, ownerCancelled: Bool) { - guard let error else { return } - if error is CancellationError { - if !ownerCancelled, terminalError == nil { terminalError = error } - } else if terminalError == nil || terminalError is CancellationError { - terminalError = error - } - } - - /// Latch synchronously before any suspension. Concurrent callers receive - /// the same work, including callers arriving during finalization/drain. - @discardableResult - func requestRetirement( - error: Error? = nil, cancelInput: Bool = true, ownerCancelled: Bool = false - ) -> Task { - // Error priority is independent of the latch used to cancel producers. - // A real failure supersedes cancellation, but never an earlier real failure. - record(error, ownerCancelled: ownerCancelled) - if cancelInput, !stoppingInput { - stoppingInput = true - setupTask?.cancel() - ingestionTask?.cancel() - } - if let terminalTask { return terminalTask } - let terminal = Task { - await setupTask?.value - if stoppingInput { ingestionTask?.cancel() } - await ingestionTask?.value - // Keep results alive while finalization publishes its last chunks. - do { - try await finalize(inputFinalizationStarted) - } catch { - record(error, ownerCancelled: false) - resultTask?.cancel() - } - await resultTask?.value - await complete(terminalError) - setupTask = nil - ingestionTask = nil - resultTask = nil - } - terminalTask = terminal - return terminal - } -} diff --git a/Sources/AuralKit/SpeechSession+NativeFileInput.swift b/Sources/AuralKit/SpeechSession+NativeFileInput.swift index d059ea4..a412ba2 100644 --- a/Sources/AuralKit/SpeechSession+NativeFileInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeFileInput.swift @@ -29,15 +29,10 @@ extension SpeechSession { } let lastAudioTime = try await analyzer.analyzeSequence(from: file) - guard let run = await fileTranscription else { - throw SpeechSessionError.recognitionStreamSetupFailed - } - try await run.finishInput { - if let lastAudioTime { - try await analyzer.finalizeAndFinish(through: lastAudioTime) - } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() - } + if let lastAudioTime { + try await analyzer.finalizeAndFinish(through: lastAudioTime) + } else { + try await analyzer.finalizeAndFinishThroughEndOfInput() } return !Task.isCancelled diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 4e53543..9025f0c 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -87,11 +87,6 @@ extension SpeechSession { /// (from streams that were already replaced or finished) are ignored. func handleStreamTermination(generation: Int) async { guard generation == sessionGeneration else { return } - if let fileTranscription { - prepareForStop() - await fileTranscription.requestRetirement().value - return - } prepareForStop() await cleanup(cancelRecognizer: true, generation: generation) await finishStream(error: nil, generation: generation) @@ -282,6 +277,10 @@ extension SpeechSession { let task = recognizerTask recognizerTask = nil + let ingestionTask = fileIngestionTask + fileIngestionTask = nil + ingestionTask?.cancel() + if cancelRecognizer { if Self.shouldLog(.debug) { Self.logger.debug("Cancelling recognizer task") diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index d4098b8..03c211c 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -96,7 +96,7 @@ public final class SpeechSession { var continuation: TranscriptionContinuation? var recognizerTask: Task? var pipelineTask: Task? - var fileTranscription: FileTranscriptionRun? + var fileIngestionTask: Task? var streamingMode: StreamingMode = .inactive /// Incremented for every accepted start so stale termination handlers can be ignored. var sessionGeneration: Int = 0 @@ -347,13 +347,7 @@ public final class SpeechSession { /// /// Safe to call even if `startTranscribing()` has not been invoked or the stream has already /// completed; the method simply waits for cleanup and returns. - /// For file transcription, return also joins setup, ingestion and result reading. public func stopTranscribing() async { - if let fileTranscription { - prepareForStop() - await fileTranscription.requestRetirement().value - return - } let generation = sessionGeneration prepareForStop() await cleanup(cancelRecognizer: true, generation: generation) diff --git a/Tests/AuralKitTests/FileProgressTests.swift b/Tests/AuralKitTests/FileProgressTests.swift new file mode 100644 index 0000000..0a86f0e --- /dev/null +++ b/Tests/AuralKitTests/FileProgressTests.swift @@ -0,0 +1,46 @@ +import Speech +import Testing +@testable import AuralKit + +@Suite("File transcription progress") +struct FileProgressTests { + @Test("Progress stops with its file session", arguments: ["stopping", "stopped", "replacement", "cancelled"]) + @MainActor + func progressStopsWithItsFileSession(termination: String) async { + let session = SpeechSession() + let generation = session.beginStreamGeneration() + let (_, continuation) = AsyncThrowingStream.makeStream() + session.continuation = .speech(continuation) + session.streamingMode = .filePlayback + session.setStatus(.transcribing) + + let (progress, progressContinuation) = AsyncStream.makeStream() + let handler: @Sendable (Double) -> Void = { progressContinuation.yield($0) } + session.reportFileProgress(0.25, handler: handler, generation: generation) + + switch termination { + case "stopping": + session.prepareForStop() + case "stopped": + await session.stopTranscribing() + case "replacement": + _ = session.beginStreamGeneration() + default: + break + } + + let delivery = Task { + if termination == "cancelled" { + withUnsafeCurrentTask { $0?.cancel() } + } + session.reportFileProgress(0.5, handler: handler, generation: generation) + session.reportFileProgress(1.0, handler: handler, generation: generation) + } + await delivery.value + progressContinuation.finish() + var received: [Double] = [] + for await value in progress { received.append(value) } + #expect(received == [0.25]) + await session.stopTranscribing() + } +} diff --git a/Tests/AuralKitTests/FileTranscriptionJoinTestFixtures.swift b/Tests/AuralKitTests/FileTranscriptionJoinTestFixtures.swift deleted file mode 100644 index a609a56..0000000 --- a/Tests/AuralKitTests/FileTranscriptionJoinTestFixtures.swift +++ /dev/null @@ -1,50 +0,0 @@ -import Foundation - -/// Harness waits cooperate; simulated native operations explicitly opt out. -@MainActor -final class FileJoinGate { - private var opened = false - private var waiters: [UUID: CheckedContinuation] = [:] - private var operationWaiters: [CheckedContinuation] = [] - - var pendingControlWaits: Int { waiters.count } - - func wait() async throws { - try Task.checkCancellation() - if opened { return } - let id = UUID() - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - waiters[id] = continuation - } - } onCancel: { - Task { @MainActor in - self.waiters.removeValue(forKey: id)?.resume(throwing: CancellationError()) - } - } - } - - func waitIgnoringCancellation() async { - if opened { return } - await withCheckedContinuation { operationWaiters.append($0) } - } - - func open() { - opened = true - let pending = Array(waiters.values) - waiters.removeAll() - for waiter in pending { waiter.resume() } - let operations = operationWaiters - operationWaiters.removeAll() - for waiter in operations { waiter.resume() } - } -} - -@MainActor -final class FileJoinRecord { - var events: [String] = [] - var values: [Int] = [] - var error: Error? - var timedOut = false - var readerWasCancelled = false -} diff --git a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift deleted file mode 100644 index 00ec80e..0000000 --- a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift +++ /dev/null @@ -1,370 +0,0 @@ -import Foundation -import Testing -@testable import AuralKit - -@Suite("Joined file retirement") -@MainActor -struct FileTranscriptionJoinTests { - /// The watchdog is independent of the body and its readiness waits. Cleanup - /// releases even cancellation-insensitive simulated native operations first. - @discardableResult - private func withRun( - failFinalization: Bool = false, - timeout: Duration = .seconds(5), - expectTimeout: Bool = false, - _ body: @escaping @MainActor (FileTranscriptionRun, [FileJoinGate], AsyncThrowingStream, - AsyncThrowingStream.Continuation, FileJoinRecord) async throws -> Void - ) async -> FileJoinRecord { - let gates = (0..<6).map { _ in FileJoinGate() } - let finished = FileJoinGate() - let record = FileJoinRecord() - let (stream, continuation) = AsyncThrowingStream.makeStream() - let run = FileTranscriptionRun(finalize: { alreadyFinalized in - record.events.append("detach") - gates[3].open() - if !alreadyFinalized { - record.events.append("finalize") - await gates[4].waitIgnoringCancellation() - if failFinalization { throw CocoaError(.fileReadUnknown) } - continuation.yield(42) - continuation.finish() - } - }, complete: { error in - record.error = error - record.events.append("complete") - }) - let work = Task { - do { - try await body(run, gates, stream, continuation, record) - } catch is CancellationError { - } catch { - Issue.record("Unexpected harness error: \(error)") - } - finished.open() - } - let watchdog = Task { - do { try await Task.sleep(for: timeout) } catch { return } - record.timedOut = true - finished.open() - } - try? await finished.wait() - watchdog.cancel() - work.cancel() - for gate in gates { gate.open() } - continuation.finish() - await run.requestRetirement().value - await work.value - await watchdog.value - #expect(record.timedOut == expectTimeout) - #expect(gates.allSatisfy { $0.pendingControlWaits == 0 }) - #expect(record.events.contains("complete")) - return record - } - - @Test("Stop joins suspended setup and a late-installed reader") - func stopDuringSetup() async { - await withRun { run, gates, stream, _, record in - run.startSetup { - gates[0].open() - await gates[1].waitIgnoringCancellation() - run.startResults(stream) { record.values.append($0) } - run.startIngestion { record.events.append("unexpected input"); return true } - record.events.append("setup exited") - } - try await gates[0].wait() - let terminal = run.requestRetirement() - gates[1].open() - try await gates[3].wait() - #expect(record.events == ["setup exited", "detach", "finalize"]) - gates[4].open() - await terminal.value - #expect(record.values == [42]) - #expect(record.events.last == "complete") - } - } - - @Test("Stop joins input before finalization and concurrent callers share completion") - func stopDuringInput() async { - await withRun { run, gates, stream, _, record in - run.startSetup { - run.startResults(stream) { record.values.append($0) } - run.startIngestion { - gates[0].open() - await gates[1].waitIgnoringCancellation() - record.events.append("input exited") - return true - } - } - try await gates[0].wait() - let first = Task { await run.requestRetirement().value; record.events.append("stop one") } - let second = Task { await run.requestRetirement().value; record.events.append("stop two") } - // Latch before releasing the input; the two Tasks join that same owner. - let terminal = run.requestRetirement() - gates[1].open() - try await gates[3].wait() - #expect(record.events == ["input exited", "detach", "finalize"]) - gates[4].open() - await terminal.value - await first.value - await second.value - #expect(record.events.filter { $0 == "finalize" }.count == 1) - #expect(Array(record.events.prefix(4)) == ["input exited", "detach", "finalize", "complete"]) - #expect(Set(record.events.suffix(2)) == Set(["stop one", "stop two"])) - #expect(record.error == nil) - } - } -} - -@MainActor -extension FileTranscriptionJoinTests { - @Test("Finalizer-generated results drain before completion") - func finalResultDrain() async { - await withRun { run, gates, stream, _, record in - run.startSetup { - run.startResults(stream) { record.values.append($0); record.events.append("result") } - run.startIngestion { gates[0].open(); return true } - } - try await gates[0].wait() - let terminal = run.requestRetirement() - try await gates[3].wait() - #expect(record.values.isEmpty) - #expect(!record.events.contains("complete")) - gates[4].open() - await terminal.value - #expect(record.values == [42]) - #expect(record.events.suffix(2) == ["result", "complete"]) - } - } - - @Test("Natural reader completion joins ingestion without cancelling it") - func naturalCompletion() async { - await withRun { run, gates, stream, continuation, record in - run.startSetup { - run.startResults(stream) { record.values.append($0) } - run.startIngestion { - gates[0].open() - await gates[1].waitIgnoringCancellation() - #expect(!Task.isCancelled) - record.events.append("input exited") - return true - } - } - try await gates[0].wait() - continuation.finish() - gates[1].open() - try await gates[3].wait() - gates[4].open() - await run.terminalTask?.value - #expect(record.events == ["input exited", "detach", "finalize", "complete"]) - #expect(record.error == nil) - } - } - - @Test("Finalizer failure cancels and joins a waiting reader") - func finalizationFailure() async { - await withRun(failFinalization: true) { run, gates, stream, continuation, record in - continuation.onTermination = { termination in - let cancelled: Bool - if case .cancelled = termination { cancelled = true } else { cancelled = false } - Task { @MainActor in - record.readerWasCancelled = cancelled - gates[2].open() - } - } - run.startSetup { - run.startResults(stream) { record.values.append($0) } - gates[0].open() - } - try await gates[0].wait() - let terminal = run.requestRetirement() - try await gates[3].wait() - gates[4].open() - await terminal.value - try await gates[2].wait() - #expect(record.readerWasCancelled) - #expect(record.error is CocoaError) - #expect(record.events.last == "complete") - } - } - - @Test("Independent result cancellation settles the stream") - func readerCancellation() async { - await withRun { run, gates, stream, continuation, record in - run.startSetup { - run.startResults(stream) { record.values.append($0) } - gates[0].open() - } - try await gates[0].wait() - continuation.finish(throwing: CancellationError()) - try await gates[3].wait() - gates[4].open() - // Finalization was reached by the reader's request, without public stop. - await run.terminalTask?.value - #expect(record.error is CancellationError) - } - } - - @Test("Stop preserves a later genuine producer failure", arguments: ["reader", "input", "setup"]) - func realErrorAfterStop(producer: String) async { - await withRun { run, gates, stream, continuation, record in - run.startSetup { - run.startResults(stream) { record.values.append($0) } - if producer == "setup" { - gates[0].open() - await gates[1].waitIgnoringCancellation() - throw FileJoinFailure.first - } - run.startIngestion { - gates[0].open() - await gates[1].waitIgnoringCancellation() - if producer == "input" { throw FileJoinFailure.first } - return true - } - } - try await gates[0].wait() - let terminal = run.requestRetirement() - if producer == "reader" { continuation.finish(throwing: FileJoinFailure.first) } - gates[1].open() - try await gates[3].wait() - gates[4].open() - await terminal.value - #expect(record.error as? FileJoinFailure == .first) - } - } - - @Test("Meaningful error priority survives later cleanup cancellation", arguments: [false, true]) - func errorPriority(initialCancellation: Bool) async { - await withRun { run, gates, stream, continuation, record in - run.startSetup { - run.startResults(stream) { record.values.append($0) } - run.startIngestion { - gates[0].open() - await gates[1].waitIgnoringCancellation() - throw CancellationError() - } - } - try await gates[0].wait() - let initial: Error = initialCancellation ? CancellationError() : FileJoinFailure.first - let terminal = run.requestRetirement(error: initial) - continuation.finish(throwing: FileJoinFailure.second) - gates[1].open() - try await gates[3].wait() - gates[4].open() - await terminal.value - #expect(record.error as? FileJoinFailure == (initialCancellation ? .second : .first)) - } - } - - @Test("Normal input finalization is attempted once and its results drain", - arguments: [false, true], [false, true]) - func normalFinalization(fails: Bool, stopDuringFinalization: Bool) async { - await withRun { run, gates, stream, continuation, record in - run.startSetup { - run.startResults(stream) { record.values.append($0); record.events.append("result") } - run.startIngestion { - try await run.finishInput { - record.events.append("normal finalize") - gates[0].open() - await gates[1].waitIgnoringCancellation() - if fails { throw FileJoinFailure.first } - continuation.yield(7) - continuation.finish() - } - return true - } - } - try await gates[0].wait() - if stopDuringFinalization { run.requestRetirement() } - // A successful reader EOF requests retirement; a failed finalization - // requests it from ingestion. Neither route may retry the operation. - gates[1].open() - try await gates[3].wait() - await run.terminalTask?.value - #expect(record.events.filter { $0 == "normal finalize" }.count == 1) - #expect(!record.events.contains("finalize")) - #expect(record.events.last == "complete") - if fails { - #expect(record.error as? FileJoinFailure == .first) - } else { - #expect(record.error == nil) - #expect(record.values == [7]) - if let result = record.events.firstIndex(of: "result"), - let complete = record.events.firstIndex(of: "complete") { - #expect(result < complete) - } else { Issue.record("Missing result or completion") } - } - } - } - - @Test("Watchdog releases stalled body/readiness and joins native operations", arguments: [false, true]) - func watchdogCleanup(stallOnTerminal: Bool) async { - let record = await withRun(timeout: .seconds(1), expectTimeout: true) { run, gates, stream, _, record in - run.startSetup { - run.startResults(stream) { record.values.append($0) } - run.startIngestion { - gates[0].open() - await gates[1].waitIgnoringCancellation() - record.events.append("released input") - return true - } - } - try await gates[0].wait() - // Intentionally never signalled by a producer. The watchdog must - // cancel this wait, release input/finalization, close and join. - if stallOnTerminal { - await run.requestRetirement().value - } else { - try await gates[5].wait() - } - } - #expect(record.events.contains("released input")) - #expect(record.events.last == "complete") - #expect(record.error == nil) - } - - @Test("Cancelling a harness wait removes its continuation") - func cancelledControlWait() async { - await withRun { _, gates, _, _, _ in - let waiter = Task { - gates[0].open() - try await gates[1].wait() - } - try await gates[0].wait() - #expect(gates[1].pendingControlWaits == 1) - waiter.cancel() - do { - try await waiter.value - Issue.record("Cancelled control wait returned successfully") - } catch { - #expect(error is CancellationError) - } - #expect(gates[1].pendingControlWaits == 0) - } - } - - @Test("Incomplete input and independent input cancellation are failures", arguments: [false, true]) - func incompleteInput(cancelled: Bool) async { - await withRun { run, gates, stream, _, record in - run.startSetup { - run.startResults(stream) { record.values.append($0) } - run.startIngestion { - if cancelled { throw CancellationError() } - return false - } - } - try await gates[3].wait() - gates[4].open() - await run.terminalTask?.value - if cancelled { - #expect(record.error is CancellationError) - } else { - #expect(record.error is SpeechSessionError) - } - } - } -} - -private enum FileJoinFailure: Error { - case first - case second -} From cdb6a9953cac0a0a7606ef71883b51330c0cccdb Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:01:52 +0530 Subject: [PATCH 23/70] Keep detector ownership fence in native reader --- .../SpeechSession+VoiceActivation.swift | 24 +- .../SpeechDetectorLifecycleTests.swift | 278 ++++-------------- 2 files changed, 62 insertions(+), 240 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+VoiceActivation.swift b/Sources/AuralKit/SpeechSession+VoiceActivation.swift index 5b34dc2..ee1f117 100644 --- a/Sources/AuralKit/SpeechSession+VoiceActivation.swift +++ b/Sources/AuralKit/SpeechSession+VoiceActivation.swift @@ -43,35 +43,18 @@ extension SpeechSession { func startSpeechDetectorMonitoring() { guard let detector = speechDetector else { return } - monitorSpeechDetectorResults( - detector.results, - speechDetected: { $0.speechDetected }, - onResult: { [weak self] result in - self?.handleSpeechDetectorResult(result) - } - ) - } - - /// Native detector results and controlled sequences share the same owning reader. - /// Cancellation alone does not revoke a suspended reader's callback authority. - func monitorSpeechDetectorResults( - _ results: Sequence, - speechDetected: @escaping @Sendable (Sequence.Element) -> Bool, - onResult: @escaping @MainActor @Sendable (Sequence.Element) -> Void - ) where Sequence: Sendable, Sequence.Element: Sendable { - speechDetectorResultsTask?.cancel() let monitorID = UUID() speechDetectorMonitorID = monitorID + speechDetectorResultsTask?.cancel() if Self.shouldLog(.debug) { Self.logger.debug("Starting speech detector monitoring") } speechDetectorResultsTask = Task { @MainActor [weak self] in guard let self else { return } do { - for try await result in results { + for try await result in detector.results { guard self.speechDetectorMonitorID == monitorID else { return } - self.isSpeechDetected = speechDetected(result) - onResult(result) + self.handleSpeechDetectorResult(result) } } catch { let finalError = (error as? CancellationError) != nil ? nil : error @@ -92,6 +75,7 @@ extension SpeechSession { } func handleSpeechDetectorResult(_ result: SpeechDetector.Result) { + isSpeechDetected = result.speechDetected speechDetectorResultsContinuation?.yield(result) if Self.shouldLog(.debug) { Self.logger.debug( diff --git a/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift index aa07ed1..f7fbd09 100644 --- a/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift +++ b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift @@ -1,236 +1,74 @@ import Foundation +import Speech import Testing @testable import AuralKit @Suite("Speech detector monitor identity") +@MainActor struct SpeechDetectorLifecycleTests { - @Test("public disable and reconfigure rejects a late predecessor result") - @MainActor - func staleResultAfterReconfiguration() async throws { - try await withFixture { fixture in - let source = HeldDetectorSource() - fixture.sources.append(source) - fixture.session.configureVoiceActivation(reportResults: true) - let old = try fixture.monitor(HeldDetectorResults(source: source)) - try await fixture.waitUntil { await source.isWaiting } - fixture.session.disableVoiceActivation() - fixture.session.configureVoiceActivation(reportResults: true) - let (results, continuation) = fixture.results() - _ = try fixture.monitor(results) - let currentID = try #require(fixture.session.speechDetectorMonitorID) - continuation.yield(true) - try await fixture.waitUntil { fixture.values == [true] } - await source.send(false) - await source.finish() - #expect(old.isCancelled) - await old.value - #expect(fixture.values == [true]) - #expect(fixture.session.isSpeechDetected) - #expect(fixture.session.speechDetectorMonitorID == currentID) - #expect(fixture.session.speechDetectorResultsTask != nil) - #expect(fixture.session.speechDetectorResultsStream != nil) - } - } - - @Test("predecessor completion cannot finish a reconfigured monitor", arguments: [false, true]) - @MainActor - func staleCompletionAfterReconfiguration(failed: Bool) async throws { - try await withFixture { fixture in - fixture.session.configureVoiceActivation(reportResults: true) - let source = HeldDetectorSource() - fixture.sources.append(source) - let old = try fixture.monitor(HeldDetectorResults(source: source)) - try await fixture.waitUntil { await source.isWaiting } - fixture.session.disableVoiceActivation() - fixture.session.configureVoiceActivation(reportResults: true) - let (results, input) = fixture.results() - _ = try fixture.monitor(results) - let currentID = try #require(fixture.session.speechDetectorMonitorID) - input.yield(false) - try await fixture.waitUntil { fixture.values == [false] } - if failed { await source.fail() } else { await source.finish() } - #expect(old.isCancelled) - await old.value - #expect(!fixture.session.isSpeechDetected) - #expect(fixture.session.speechDetectorMonitorID == currentID) - #expect(fixture.session.speechDetectorResultsTask != nil) - #expect(fixture.session.speechDetectorResultsContinuation != nil) - #expect(fixture.session.speechDetectorResultsStream != nil) - } - } - - @Test("cooperative cancellation of a replaced reader cannot clear its successor") - @MainActor - func cancelledPredecessorCompletion() async throws { - try await withFixture { fixture in - fixture.session.configureVoiceActivation(reportResults: true) - let (oldResults, oldInput) = fixture.results() - let old = try fixture.monitor(oldResults) - oldInput.yield(true) - try await fixture.waitUntil { fixture.values == [true] } - let (results, input) = fixture.results() - _ = try fixture.monitor(results) - let currentID = try #require(fixture.session.speechDetectorMonitorID) - await old.value - #expect(old.isCancelled) - #expect(fixture.session.speechDetectorMonitorID == currentID) - #expect(fixture.session.speechDetectorResultsTask != nil) - #expect(fixture.session.speechDetectorResultsStream != nil) - input.yield(false) - try await fixture.waitUntil { fixture.values == [true, false] } - #expect(!fixture.session.isSpeechDetected) - } - } + @Test("only the current monitor may complete the detector stream", arguments: [false, true]) + func replacementRejectsStaleCompletion(failed: Bool) throws { + let session = makeSessionWithMonitor() + defer { session.disableVoiceActivation() } + let oldID = try #require(session.speechDetectorMonitorID) + let oldTask = try #require(session.speechDetectorResultsTask) + + session.startSpeechDetectorMonitoring() + let currentID = try #require(session.speechDetectorMonitorID) + let currentTask = try #require(session.speechDetectorResultsTask) + session.isSpeechDetected = false + let error: Error? = failed ? DetectorTestError.failed : nil + session.handleSpeechDetectorStreamCompletion(error: error, monitorID: oldID) + + #expect(oldTask.isCancelled) + #expect(!currentTask.isCancelled) + #expect(currentID != oldID) + #expect(session.speechDetectorMonitorID == currentID) + #expect(session.speechDetectorResultsTask != nil) + #expect(session.speechDetectorResultsContinuation != nil) + #expect(session.speechDetectorResultsStream != nil) + #expect(!session.isSpeechDetected) + + session.handleSpeechDetectorStreamCompletion(error: error, monitorID: currentID) + #expect(session.speechDetectorMonitorID == nil) + #expect(session.speechDetectorResultsTask == nil) + #expect(session.speechDetectorResultsContinuation == nil) + #expect(session.speechDetectorResultsStream == nil) + #expect(session.isSpeechDetected) + currentTask.cancel() + } + + @Test("disable revokes a monitor before reporting is reconfigured") + func disableRejectsStaleCompletion() throws { + let session = makeSessionWithMonitor() + defer { session.disableVoiceActivation() } + let oldID = try #require(session.speechDetectorMonitorID) + let oldTask = try #require(session.speechDetectorResultsTask) + session.disableVoiceActivation() + session.configureVoiceActivation(reportResults: true) - @Test("disable revokes a reader even without a replacement") - @MainActor - func staleResultAfterDisable() async throws { - try await withFixture { fixture in - let source = HeldDetectorSource() - fixture.sources.append(source) - fixture.session.configureVoiceActivation(reportResults: true) - let old = try fixture.monitor(HeldDetectorResults(source: source)) - try await fixture.waitUntil { await source.isWaiting } - fixture.session.disableVoiceActivation() - await source.send(false) - await source.finish() - await old.value - #expect(old.isCancelled) - #expect(fixture.values.isEmpty) - #expect(fixture.session.isSpeechDetected) - #expect(fixture.session.speechDetectorMonitorID == nil) - #expect(fixture.session.speechDetectorResultsTask == nil) - #expect(fixture.session.speechDetectorResultsStream == nil) - } - } + session.handleSpeechDetectorStreamCompletion(error: nil, monitorID: oldID) - @Test("current results and normal or failed completion retain their behavior", arguments: [false, true]) - @MainActor - func currentMonitorCompletion(failed: Bool) async throws { - try await withFixture { fixture in - fixture.session.configureVoiceActivation(reportResults: true) - let (results, input) = fixture.results() - let task = try fixture.monitor(results) - input.yield(false) - try await fixture.waitUntil { fixture.values == [false] } - #expect(!fixture.session.isSpeechDetected) - if failed { input.finish(throwing: DetectorTestError.failed) } else { input.finish() } - await task.value - #expect(fixture.session.isSpeechDetected) - #expect(fixture.session.speechDetectorMonitorID == nil) - #expect(fixture.session.speechDetectorResultsTask == nil) - #expect(fixture.session.speechDetectorResultsContinuation == nil) - #expect(fixture.session.speechDetectorResultsStream == nil) - } + #expect(oldTask.isCancelled) + #expect(session.speechDetectorMonitorID == nil) + #expect(session.speechDetectorResultsTask == nil) + #expect(session.speechDetectorResultsContinuation != nil) + #expect(session.speechDetectorResultsStream != nil) + #expect(session.isSpeechDetected) } - @MainActor - private func withFixture(_ operation: @MainActor (DetectorFixture) async throws -> Void) async throws { - let fixture = DetectorFixture() - do { try await operation(fixture) } catch { await fixture.cleanup(); throw error } - await fixture.cleanup() + private func makeSessionWithMonitor() -> SpeechSession { + let session = SpeechSession() + session.configureVoiceActivation(reportResults: true) + session.speechDetector = SpeechDetector( + detectionOptions: .init(sensitivityLevel: .medium), + reportResults: true + ) + session.startSpeechDetectorMonitoring() + return session } } private enum DetectorTestError: Error { case failed } - -/// Holds a suspended next() across cancellation to exercise a late value or -/// completion. This models the AsyncSequence contract, not Apple implementation timing. -private actor HeldDetectorSource { - private var continuation: CheckedContinuation? - private var finished = false - private(set) var isWaiting = false - - func next() async throws -> Bool? { - guard !finished else { return nil } - isWaiting = true - return try await withCheckedThrowingContinuation { continuation = $0 } - } - - func send(_ value: Bool) { - isWaiting = false - continuation?.resume(returning: value) - continuation = nil - } - - func fail() { - finished = true - isWaiting = false - continuation?.resume(throwing: DetectorTestError.failed) - continuation = nil - } - - func finish() { - finished = true - isWaiting = false - continuation?.resume(returning: nil) - continuation = nil - } -} - -private struct HeldDetectorResults: AsyncSequence, Sendable { - typealias Element = Bool - let source: HeldDetectorSource - - func makeAsyncIterator() -> AsyncIterator { - AsyncIterator(source: source) - } - - struct AsyncIterator: AsyncIteratorProtocol { - let source: HeldDetectorSource - - mutating func next() async throws -> Bool? { - try await source.next() - } - } -} - -@MainActor -private final class DetectorFixture { - let session = SpeechSession() - var values: [Bool] = [] - var sources: [HeldDetectorSource] = [] - private var tasks: [Task] = [] - private var inputs: [AsyncThrowingStream.Continuation] = [] - - func results() -> ( - AsyncThrowingStream, - AsyncThrowingStream.Continuation - ) { - let (results, input) = AsyncThrowingStream.makeStream() - inputs.append(input) - return (results, input) - } - - func monitor(_ results: Sequence) throws -> Task - where Sequence: Sendable, Sequence.Element == Bool { - session.monitorSpeechDetectorResults( - results, - speechDetected: { $0 }, - onResult: { [unowned self] detected in - values.append(detected) - } - ) - let task = try #require(session.speechDetectorResultsTask) - tasks.append(task) - return task - } - - func waitUntil(_ predicate: @MainActor () async -> Bool) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(2)) - while !(await predicate()) { - guard ContinuousClock.now < deadline else { throw TestTimeoutError.timedOut(seconds: 2) } - await Task.yield() - } - } - - func cleanup() async { - session.disableVoiceActivation() - for source in sources { await source.finish() } - inputs.forEach { $0.finish() } - tasks.forEach { $0.cancel() } - for task in tasks { await task.value } - } -} From 34f26d9e3ed4948f00398516ebd5ac5ad15a8749 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:06:36 +0530 Subject: [PATCH 24/70] Limit screen capture repair to serialized native transitions --- .../AuralKit/ScreenCapturePipelineHooks.swift | 20 - .../AuralKit/ScreenCaptureTransitions.swift | 23 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 28 +- .../SpeechSession+ScreenCapture.swift | 232 +++++----- Sources/AuralKit/SpeechSession+State.swift | 46 -- Sources/AuralKit/SpeechSession.swift | 46 +- .../ScreenCaptureTestFixtures.swift | 58 +-- .../ScreenCaptureTransitionTests.swift | 401 ++++++------------ 8 files changed, 320 insertions(+), 534 deletions(-) delete mode 100644 Sources/AuralKit/ScreenCapturePipelineHooks.swift diff --git a/Sources/AuralKit/ScreenCapturePipelineHooks.swift b/Sources/AuralKit/ScreenCapturePipelineHooks.swift deleted file mode 100644 index 75ed7d6..0000000 --- a/Sources/AuralKit/ScreenCapturePipelineHooks.swift +++ /dev/null @@ -1,20 +0,0 @@ -import AVFoundation -import Speech - -/// Instance-local native boundaries. Production keeps native authorization and analysis; -/// controlled collaborators can drive the same public setup and teardown orchestration. -@available(iOS 26.0, macOS 14.0, *) -struct ScreenCapturePreparedAnalysis { - let format: AVAudioFormat - let inputs: AsyncStream.Continuation - let finalize: @MainActor () async -> Void -} - -@available(iOS 26.0, macOS 14.0, *) -struct ScreenCapturePipelineHooks { - let authorize: @MainActor () async throws -> Void - let prepareAnalysis: @MainActor () async throws -> ScreenCapturePreparedAnalysis - let makeProvider: @MainActor ( - AVAudioFormat, AsyncStream.Continuation, @escaping @Sendable (Error) -> Void - ) -> any ScreenCaptureInput -} diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index 3c1cef6..aa91637 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -1,6 +1,5 @@ import Foundation -/// The narrow boundary around actual capture calls, shared by SCStream and controlled fixtures. @available(iOS 26.0, macOS 14.0, *) @MainActor protocol ScreenCaptureStream: AnyObject { @@ -8,13 +7,10 @@ protocol ScreenCaptureStream: AnyObject { func stopCapture() async throws } -/// Carries admission through async returns. The public caller checks ownership at -/// the instant it publishes status or propagates a failure into session teardown. @available(iOS 26.0, macOS 14.0, *) @MainActor struct ScreenCaptureResumeOutcome { - let isCurrent: @MainActor () -> Bool - let error: Error? + let resolve: @MainActor () throws -> Bool } /// Serializes capture side effects across suspension. Admission changes intent immediately; @@ -27,6 +23,7 @@ final class ScreenCaptureTransitions { private(set) var stream: (any ScreenCaptureStream)? private(set) var isRunning = false private var revision = UUID() + private var controlRevision = UUID() private var tail: Task? // Synchronous admission returns the owned handle before any capture call can suspend. @@ -51,11 +48,14 @@ final class ScreenCaptureTransitions { func pause() -> Task { guard desiredState != .stopped else { return enqueue {} } + controlRevision = UUID() desiredState = .paused return enqueue { try await self.stopCurrent() } } func resume() -> Task { + let control = UUID() + controlRevision = control desiredState = desiredState == .stopped ? .stopped : .running let admitted = revision let previous = tail @@ -68,20 +68,23 @@ final class ScreenCaptureTransitions { } catch let failure { error = failure } - return ScreenCaptureResumeOutcome( - isCurrent: { self.desiredState == .running && self.revision == admitted }, - error: error - ) + return ScreenCaptureResumeOutcome { + guard self.desiredState == .running, self.controlRevision == control else { return false } + // A new selection inherits run intent, but not the old selection's failure. + if self.revision == admitted, let error { throw error } + return true + } } tail = Task { _ = await operation.value } return operation } func stop() -> Task { + controlRevision = UUID() desiredState = .stopped return enqueue { + defer { self.stream = nil } try await self.stopCurrent() - self.stream = nil } } diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 5225b1d..9025f0c 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -258,27 +258,12 @@ extension SpeechSession { /// Tear down the active pipeline. /// - /// One internal terminal task owns detachment, capture shutdown, analyzer - /// finalization and locale release. Concurrent callers join that same task even - /// after the provider and analyzer have been detached. Generation checks keep - /// an obsolete terminal task from touching a successor's shared state. + /// All session state is detached synchronously up front so that concurrent teardowns (or a + /// new session starting once the stream finishes) never observe partially-cleared state; the + /// 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 { - guard generation == sessionGeneration else { return } - if let terminal = cleanupTask, terminal.generation == generation { - await terminal.task.value - return - } - // Own only internal teardown. Neither a public caller nor setup producer is - // joined here: either may be suspended awaiting this very terminal task. - let terminal = Task { @MainActor in - await self.performCleanup(cancelRecognizer: cancelRecognizer, generation: generation) - if self.cleanupTask?.generation == generation { self.cleanupTask = nil } - } - cleanupTask = (generation, terminal) - await terminal.value - } - - private func performCleanup(cancelRecognizer: Bool, generation: Int) async { guard generation == sessionGeneration else { return } if Self.shouldLog(.debug) { Self.logger.debug("Cleanup started (cancelRecognizer: \(cancelRecognizer, privacy: .public))") @@ -311,12 +296,9 @@ extension SpeechSession { #if os(iOS) shouldResumeAfterInterruption = false #endif - let analysisFinalizer = screenCaptureAnalysisFinalizer - screenCaptureAnalysisFinalizer = nil let detached = detachTranscriberState() await stopScreenCaptureStreamingIfNeeded() await finalizeDetachedTranscriberState(detached) - await analysisFinalizer?() guard generation == sessionGeneration else { return } await modelManager.releaseLocales() diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 1493d96..317af02 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -5,49 +5,6 @@ import Speech // swiftlint:disable file_length -/// Internal capture lifetime boundary; production uses ScreenCaptureKit below. -@available(iOS 26.0, macOS 14.0, *) -protocol ScreenCaptureInput: AnyObject { - @MainActor func start() async throws - @MainActor func pause() async - @MainActor func resume() async throws - @MainActor func resumeOutcome() async -> ScreenCaptureResumeOutcome - @MainActor func stop() async -} - -@available(iOS 26.0, macOS 14.0, *) -extension ScreenCaptureInput { - @MainActor - func resumeOutcome() async -> ScreenCaptureResumeOutcome { - do { - try await resume() - return ScreenCaptureResumeOutcome(isCurrent: { true }, error: nil) - } catch { - return ScreenCaptureResumeOutcome(isCurrent: { true }, error: error) - } - } -} - -@available(iOS 26.0, macOS 14.0, *) -extension SpeechSession { - func pauseScreenCaptureStreamingIfNeeded() async { - await screenCaptureInputProvider?.pause() - } - - func resumeScreenCaptureStreamingIfNeeded() async throws -> ScreenCaptureResumeOutcome { - guard let provider = screenCaptureInputProvider else { - throw SpeechSessionError.recognitionStreamSetupFailed - } - return await provider.resumeOutcome() - } - - func stopScreenCaptureStreamingIfNeeded() async { - let provider = screenCaptureInputProvider - screenCaptureInputProvider = nil - await provider?.stop() - } -} - #if canImport(ScreenCaptureKit) @preconcurrency import ScreenCaptureKit @@ -143,25 +100,15 @@ extension SpeechSession { } try Task.checkCancellation() - if let hooks = screenCapturePipelineHooks { - try await hooks.authorize() - try Task.checkCancellation() - let prepared = try await hooks.prepareAnalysis() - analyzerFormat = prepared.format - inputBuilder = prepared.inputs - screenCaptureAnalysisFinalizer = prepared.finalize - } else { - try await ensureSpeechRecognitionAuthorization(context: "for screen capture transcription") - try Task.checkCancellation() - let transcriber = try await setUpSpeechTranscriber(contextualStrings: contextualStrings) - try Task.checkCancellation() - recognizerTask = createSpeechRecognizerTask( - transcriber: transcriber, - streamContinuation: streamContinuation, - generation: generation - ) - } + try await ensureSpeechRecognitionAuthorization(context: "for screen capture transcription") + try Task.checkCancellation() + let transcriber = try await setUpSpeechTranscriber(contextualStrings: contextualStrings) try Task.checkCancellation() + recognizerTask = createSpeechRecognizerTask( + transcriber: transcriber, + streamContinuation: streamContinuation, + generation: generation + ) try await setUpScreenCaptureStreaming(options: options, generation: generation) try Task.checkCancellation() @@ -188,26 +135,56 @@ extension SpeechSession { throw SpeechSessionError.invalidAudioDataType } - let onFailure: @Sendable (Error) -> Void = { [weak self] error in - Task { @MainActor [weak self] in - await self?.finishFromRecognizerTask(error: error, generation: generation) + let provider = ScreenCaptureAudioInputProvider( + options: options, + targetFormat: analyzerFormat, + inputContinuation: inputBuilder, + onFailure: { [weak self] error in + Task { @MainActor [weak self] in + await self?.finishFromRecognizerTask(error: error, generation: generation) + } } - } - let provider: any ScreenCaptureInput - if let makeProvider = screenCapturePipelineHooks?.makeProvider { - provider = makeProvider(analyzerFormat, inputBuilder, onFailure) - } else { - provider = ScreenCaptureAudioInputProvider( - options: options, targetFormat: analyzerFormat, - inputContinuation: inputBuilder, onFailure: onFailure - ) - } + ) screenCaptureInputProvider = provider try await provider.start() } } -/// Keeps ScreenCaptureKit calls on the same tested transition boundary. +@MainActor +extension SpeechSession { + func pauseScreenCaptureStreamingIfNeeded() async -> Bool { + guard #available(iOS 27.0, macOS 14.0, *) else { return false } + guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { return false } + return await provider.pause() + } + + func resumeScreenCaptureStreamingIfNeeded() async throws -> ScreenCaptureResumeOutcome { + guard #available(iOS 27.0, macOS 14.0, *) else { + throw SpeechSessionError.screenCaptureUnavailable + } + guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + return await provider.resume() + } + + func stopScreenCaptureStreamingIfNeeded() async { + let generation = sessionGeneration + if let pending = screenCaptureStopTask, pending.generation == generation { + await pending.task.value + return + } + let detachedProvider = screenCaptureInputProvider + screenCaptureInputProvider = nil + guard #available(iOS 27.0, macOS 14.0, *) else { return } + guard let provider = detachedProvider as? ScreenCaptureAudioInputProvider else { return } + let task = Task { await provider.stop() } + screenCaptureStopTask = (generation, task) + await task.value + if screenCaptureStopTask?.generation == generation { screenCaptureStopTask = nil } + } +} + @available(iOS 27.0, macOS 14.0, *) @MainActor private final class NativeScreenCaptureStream: ScreenCaptureStream { @@ -227,7 +204,7 @@ private final class NativeScreenCaptureStream: ScreenCaptureStream { } @available(iOS 27.0, macOS 14.0, *) -final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStreamOutput, SCStreamDelegate, +final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamDelegate, SCContentSharingPickerObserver, @unchecked Sendable { private let options: SpeechSession.ScreenCaptureTranscriptionOptions @@ -239,12 +216,10 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr private let bufferConverter = BufferConverter() @MainActor private let transitions: ScreenCaptureTransitions - private let presentPicker: @MainActor (ScreenCaptureAudioInputProvider) -> Void private let dismissPicker: @MainActor (any SCContentSharingPickerObserver) -> Void private var selectionContinuation: CheckedContinuation? private var stopped = false - @MainActor private var captureTasks: [UUID: Task] = [:] - @MainActor private var pickerUpdateID: UUID? + private var pickerUpdateID: UUID? private var intentionallyStoppingStreams = Set() @MainActor @@ -254,15 +229,6 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr inputContinuation: AsyncStream.Continuation, onFailure: @escaping @Sendable (Error) -> Void, transitions: ScreenCaptureTransitions = ScreenCaptureTransitions(), - presentPicker: @escaping @MainActor (ScreenCaptureAudioInputProvider) -> Void = { provider in - let picker = SCContentSharingPicker.shared - let configuration = SCContentSharingPickerConfiguration() - picker.configuration = configuration - picker.defaultConfiguration = configuration - picker.add(provider) - picker.isActive = true - picker.present() - }, dismissPicker: @escaping @MainActor (any SCContentSharingPickerObserver) -> Void = { observer in let picker = SCContentSharingPicker.shared picker.isActive = false @@ -274,7 +240,6 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr self.inputContinuation = inputContinuation self.onFailure = onFailure self.transitions = transitions - self.presentPicker = presentPicker self.dismissPicker = dismissPicker super.init() } @@ -283,30 +248,32 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr func start() async throws { try Task.checkCancellation() guard !stopped else { throw CancellationError() } - // Cleanup stops this provider before finalizing detached analyzer state. - // stop() resumes pending selection and joins admitted picker updates. + let picker = SCContentSharingPicker.shared + let configuration = SCContentSharingPickerConfiguration() + picker.configuration = configuration + picker.defaultConfiguration = configuration + picker.add(self) + picker.isActive = true + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in selectionContinuation = continuation - presentPicker(self) + picker.present() } try Task.checkCancellation() } @MainActor - func pause() async { - _ = try? await transitions.pause().value - } - - @MainActor - func resume() async throws { - guard !stopped else { throw CancellationError() } - let outcome = await resumeOutcome() - guard outcome.isCurrent() else { return } - if let error = outcome.error { throw error } + func pause() async -> Bool { + do { + try await transitions.pause().value + return true + } catch { + return false + } } @MainActor - func resumeOutcome() async -> ScreenCaptureResumeOutcome { + func resume() async -> ScreenCaptureResumeOutcome { await transitions.resume().value } @@ -314,17 +281,8 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr func stop() async { stopped = true dismissPicker(self) - - if let selectionContinuation { - selectionContinuation.resume(throwing: SpeechSessionError.screenCaptureSelectionCancelled) - self.selectionContinuation = nil - } - - // Joins internal start/resume/pause/replacement operations, including a late - // start's compensating stop, before cleanup can finalize detached analyzer/model owners. + resumeSelection(throwing: SpeechSessionError.screenCaptureSelectionCancelled) _ = try? await transitions.stop().value - let tasks = Array(captureTasks.values) - for task in tasks { await task.value } } func contentSharingPicker( @@ -340,17 +298,16 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr guard (self.transitions.stream as? NativeScreenCaptureStream)?.stream === updatedStream else { return } } self.selectStream { [self] in - let streamConfiguration = SCStreamConfiguration() - streamConfiguration.capturesAudio = true - streamConfiguration.sampleRate = Int(targetFormat.sampleRate) - streamConfiguration.channelCount = Int(targetFormat.channelCount) - streamConfiguration.excludesCurrentProcessAudio = options.excludesCurrentProcessAudio - streamConfiguration.width = 2 - streamConfiguration.height = 2 - - let captureStream = SCStream(filter: selectedFilter, configuration: streamConfiguration, delegate: self) - try captureStream.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) - return NativeScreenCaptureStream(stream: captureStream) { [weak self] stream in + let configuration = SCStreamConfiguration() + configuration.capturesAudio = true + configuration.sampleRate = Int(targetFormat.sampleRate) + configuration.channelCount = Int(targetFormat.channelCount) + configuration.excludesCurrentProcessAudio = options.excludesCurrentProcessAudio + configuration.width = 2 + configuration.height = 2 + let capture = SCStream(filter: selectedFilter, configuration: configuration, delegate: self) + try capture.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) + return NativeScreenCaptureStream(stream: capture) { [weak self] stream in self?.markStreamForIntentionalStop(stream) } } @@ -375,8 +332,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr func stream(_ stream: SCStream, didStopWithError error: any Error) { Task { @MainActor [weak self] in - guard let self, !self.consumeIntentionalStop(for: stream), - !self.stopped, + guard let self, !self.stopped, !self.consumeIntentionalStop(for: stream), (self.transitions.stream as? NativeScreenCaptureStream)?.stream === stream else { return } self.onFailure(SpeechSessionError.screenCaptureFailed(error)) } @@ -405,16 +361,14 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr } } - /// Common admission for the native picker callback and controlled capture collaborators. + @discardableResult @MainActor - func selectStream(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) { - guard !stopped else { return } + func selectStream(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) -> Task { + guard !stopped else { return Task {} } let operation = transitions.replace(makeStream: makeStream) let id = UUID() - self.pickerUpdateID = id - self.captureTasks[id] = Task { @MainActor in - defer { self.captureTasks[id] = nil } - guard !self.stopped, self.pickerUpdateID == id else { return } + pickerUpdateID = id + return Task { @MainActor in do { try await operation.value guard !self.stopped, self.pickerUpdateID == id else { return } @@ -493,4 +447,16 @@ public extension SpeechSession { } } +@MainActor +extension SpeechSession { + func pauseScreenCaptureStreamingIfNeeded() async -> Bool { false } + + func resumeScreenCaptureStreamingIfNeeded() async throws -> ScreenCaptureResumeOutcome { + throw SpeechSessionError.screenCaptureUnavailable + } + + func stopScreenCaptureStreamingIfNeeded() async { + screenCaptureInputProvider = nil + } +} #endif diff --git a/Sources/AuralKit/SpeechSession+State.swift b/Sources/AuralKit/SpeechSession+State.swift index 407f376..ca4d8cb 100644 --- a/Sources/AuralKit/SpeechSession+State.swift +++ b/Sources/AuralKit/SpeechSession+State.swift @@ -39,50 +39,4 @@ extension SpeechSession { } statusContinuations.removeAll() } - - /// Pause capture without tearing down the analyzer pipeline. - /// - /// Safe to call only when the session is actively transcribing live audio (microphone or - /// screen capture). Calls during file transcription or in any other state are ignored. - public func pauseTranscribing() async { - guard status == .transcribing, isPausableStreamingMode else { return } - let generation = sessionGeneration - if streamingMode == .screenCapture { - await pauseScreenCaptureStreamingIfNeeded() - } else { - stopAudioStreaming() - } - // A paused capture call can finish after stop has published idle, even in the - // same generation; it must not publish paused over that terminal status. - guard generation == sessionGeneration, status == .transcribing, isPausableStreamingMode else { return } - setStatus(.paused) - } - - /// Resume a paused capture session. - /// - /// - Throws: `SpeechSessionError` if audio streaming cannot restart. - public func resumeTranscribing() async throws { - guard status == .paused, isPausableStreamingMode else { return } - let generation = sessionGeneration - do { - if streamingMode == .screenCapture { - let outcome = try await resumeScreenCaptureStreamingIfNeeded() - guard outcome.isCurrent() else { return } - if let error = outcome.error { throw error } - } else { - try startAudioStreaming() - } - // A late start may have compensated for stop while this caller was suspended. - // Generation alone is insufficient until a successor actually begins. - guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { return } - setStatus(.transcribing) - } catch { - // A late failure belongs to the detached provider, not a successor session. - guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { throw error } - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) - throw error - } - } } diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 6153254..6c9ee00 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -73,9 +73,8 @@ public final class SpeechSession { var analyzerFormat: AVAudioFormat? var nativeCaptureSession: AVCaptureSession? var nativeCaptureAnalysisTask: Task? - var screenCapturePipelineHooks: ScreenCapturePipelineHooks? - var screenCaptureAnalysisFinalizer: (@MainActor () async -> Void)? - var screenCaptureInputProvider: (any ScreenCaptureInput)? + var screenCaptureInputProvider: AnyObject? + var screenCaptureStopTask: (generation: Int, task: Task)? var voiceActivationConfiguration: VoiceActivationConfiguration? var customVocabularyDescriptor: CustomVocabulary? var customVocabularyConfiguration: SFSpeechLanguageModel.Configuration? @@ -97,7 +96,6 @@ public final class SpeechSession { // Stream state management var continuation: TranscriptionContinuation? var recognizerTask: Task? - var cleanupTask: (generation: Int, task: Task)? var pipelineTask: Task? var fileIngestionTask: Task? var streamingMode: StreamingMode = .inactive @@ -357,4 +355,44 @@ public final class SpeechSession { await finishStream(error: nil, generation: generation) } + /// Pause capture without tearing down the analyzer pipeline. + /// + /// Safe to call only when the session is actively transcribing live audio (microphone or + /// screen capture). Calls during file transcription or in any other state are ignored. + public func pauseTranscribing() async { + guard status == .transcribing, isPausableStreamingMode else { return } + let generation = sessionGeneration + if streamingMode == .screenCapture { + guard await pauseScreenCaptureStreamingIfNeeded() else { return } + } else { + stopAudioStreaming() + } + guard generation == sessionGeneration, status == .transcribing, isPausableStreamingMode else { return } + setStatus(.paused) + } + + /// Resume a paused capture session. + /// + /// - Throws: `SpeechSessionError` if audio streaming cannot restart. + public func resumeTranscribing() async throws { + guard status == .paused, isPausableStreamingMode else { return } + let generation = sessionGeneration + do { + if streamingMode == .screenCapture { + let outcome = try await resumeScreenCaptureStreamingIfNeeded() + guard try outcome.resolve() else { return } + } else { + try startAudioStreaming() + } + guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { return } + setStatus(.transcribing) + } catch { + guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { throw error } + prepareForStop() + await cleanup(cancelRecognizer: true, generation: generation) + await finishStream(error: error, generation: generation) + throw error + } + } + } diff --git a/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift index 56f9c12..7241228 100644 --- a/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift +++ b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift @@ -3,50 +3,24 @@ import Foundation enum CaptureFixtureError: Error { case deadline, startFailed } -/// Each waiter owns its deadline and can be removed by cancellation. No timeout -/// task group can be stranded joining a checked continuation that ignores cancel. @MainActor final class CaptureGate { - private var opened = false - private var waiters: [UUID: CheckedContinuation] = [:] - var waiterCount: Int { waiters.count } + private let stream: AsyncStream + private let continuation: AsyncStream.Continuation - func wait(timeoutNanoseconds: UInt64 = 3_000_000_000) async throws { - try Task.checkCancellation() - if opened { return } - let id = UUID() - let deadline = Task { @MainActor in - do { try await Task.sleep(nanoseconds: timeoutNanoseconds) } catch { return } - self.remove(id, error: CaptureFixtureError.deadline) - } - defer { deadline.cancel() } - try await withTaskCancellationHandler { () async throws -> Void in - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - if Task.isCancelled { - continuation.resume(throwing: CancellationError()) - } else { - waiters[id] = continuation - } - } - } onCancel: { - Task { @MainActor in self.remove(id, error: CancellationError()) } - } - } + init() { (stream, continuation) = AsyncStream.makeStream() } - private func remove(_ id: UUID, error: Error) { - waiters.removeValue(forKey: id)?.resume(throwing: error) + func wait() async throws { + try await awaitResult(timeout: 3) { + for await _ in self.stream {} + try Task.checkCancellation() + } } - func open() { - opened = true - let pending = waiters.values - waiters.removeAll() - for waiter in pending { waiter.resume() } - } + func open() { continuation.finish() } } -/// Async cleanup opens all gates before joining every task admitted by the test, -/// including on a failed readiness wait. Errors remain visible to the test body. +// Release suspended capture calls before joining tasks, including when an assertion fails. @MainActor final class CaptureFixture { private var gates: [CaptureGate] = [] @@ -94,6 +68,7 @@ final class ControlledCaptureStream: ScreenCaptureStream { var stopEntered: CaptureGate? var stopRelease: CaptureGate? var startError: Error? + var stopError: Error? func startCapture() async throws { starts += 1 @@ -106,6 +81,17 @@ final class ControlledCaptureStream: ScreenCaptureStream { stops += 1 stopEntered?.open() try await stopRelease?.wait() + if let stopError { throw stopError } capturing = false } } + +@MainActor +func waitForCaptureState(_ predicate: () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while !predicate() { + guard ContinuousClock.now < deadline else { throw CaptureFixtureError.deadline } + try Task.checkCancellation() + await Task.yield() + } +} diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index 59e1a3d..362bafb 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -1,310 +1,187 @@ +#if canImport(ScreenCaptureKit) import AVFoundation import Speech import Testing @testable import AuralKit +@available(iOS 27.0, macOS 26.0, *) +@MainActor +private final class CaptureSessionFixture { + let session = SpeechSession() + let owner = ScreenCaptureTransitions() + let provider: ScreenCaptureAudioInputProvider + let dismissed: CaptureGate + + init(_ fixture: CaptureFixture) throws { + dismissed = fixture.gate() + let (_, inputs) = AsyncStream.makeStream() + let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) + provider = ScreenCaptureAudioInputProvider( + options: .init(), targetFormat: format, inputContinuation: inputs, + onFailure: { error in Issue.record(error) }, transitions: owner, + dismissPicker: { [dismissed] _ in dismissed.open() } + ) + session.screenCaptureInputProvider = provider + session.streamingMode = .screenCapture + session.setStatus(.transcribing) + } + + func close(_ fixture: CaptureFixture) async { + fixture.releaseAll() + await session.stopTranscribing() + } +} + @Suite("Screen capture transitions") struct ScreenCaptureTransitionTests { - @Test("Cancellation removes a readiness waiter") + @Test("Replacing a pending picker start stops it before starting its successor") @MainActor - func readinessCancellation() async throws { + func replacementDuringStart() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in - let gate = fixture.gate() - let entered = fixture.gate() - let wait = fixture.track(Task { @MainActor in - entered.open() - try await gate.wait() - }) + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), successor = ControlledCaptureStream() + let entered = fixture.gate(), release = fixture.gate() + let stopping = fixture.gate(), stopped = fixture.gate() + old.startEntered = entered; old.startRelease = release + old.stopEntered = stopping; old.stopRelease = stopped + let first = fixture.track(runtime.provider.selectStream { old }) try await entered.wait() - wait.cancel() - do { - try await wait.value - Issue.record("Cancelled wait returned successfully") - } catch is CancellationError {} // Expected, including cancellation before registration. - #expect(gate.waiterCount == 0) - } - } - - @Test("A missing readiness signal expires and removes its waiter") - @MainActor - func readinessDeadline() async throws { - try await withCaptureFixture { fixture in - let gate = fixture.gate() - do { - try await gate.wait(timeoutNanoseconds: 1_000_000) - Issue.record("Unopened gate returned successfully") - } catch CaptureFixtureError.deadline {} - #expect(gate.waiterCount == 0) + let second = fixture.track(runtime.provider.selectStream { successor }) + release.open() + try await stopping.wait() + #expect(old.capturing && successor.starts == 0) + stopped.open() + await first.value; await second.value + #expect(!old.capturing && old.stops == 1) + #expect(successor.capturing && successor.starts == 1) + await runtime.close(fixture) } } - @Test("A picker replacement stopped across pause never starts the new stream") + @Test("Public pause during replacement prevents queued selections from starting") @MainActor - func replacementHonorsAdmittedPause() async throws { - guard #available(iOS 26.0, macOS 26.0, *) else { return } + func pauseDuringReplacement() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in - let owner = ScreenCaptureTransitions() - let old = ControlledCaptureStream() - let replacement = ControlledCaptureStream() + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), replacement = ControlledCaptureStream() + let latest = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { old }).value let entered = fixture.gate(), release = fixture.gate() - try await fixture.track(owner.replace { old }).value old.stopEntered = entered; old.stopRelease = release - let update = fixture.track(owner.replace { replacement }) + let first = fixture.track(runtime.provider.selectStream { replacement }) try await entered.wait() - let pause = fixture.track(owner.pause()) - #expect(owner.desiredState == .paused) + let pause = fixture.track(Task { await runtime.session.pauseTranscribing() }) + try await waitForCaptureState { runtime.owner.desiredState == .paused } + let second = fixture.track(runtime.provider.selectStream { latest }) release.open() - try await update.value - try await pause.value - #expect(owner.stream === replacement) - #expect(!owner.isRunning) - #expect(!old.capturing) - #expect(replacement.starts == 0) - let resumed = await fixture.track(owner.resume()).value - #expect(resumed.isCurrent()) - #expect(resumed.error == nil) - #expect(replacement.starts == 1) - #expect(old.starts == 1) - try await fixture.track(owner.stop()).value + await first.value; await second.value; await pause.value + #expect(runtime.session.status == .paused) + #expect(!old.capturing && replacement.starts == 0 && latest.starts == 0) + try await runtime.session.resumeTranscribing() + #expect(latest.capturing && runtime.session.status == .transcribing) + await runtime.close(fixture) } } - @Test("Stop admitted during old shutdown prevents either replacement from starting") + @Test("Concurrent public stops join a replacement start and its compensating stop") @MainActor - func replacementIdentityAcrossStop() async throws { - guard #available(iOS 26.0, macOS 26.0, *) else { return } + func stopDuringReplacementStart() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in - let owner = ScreenCaptureTransitions() - let old = ControlledCaptureStream() - let obsolete = ControlledCaptureStream(), current = ControlledCaptureStream() + let runtime = try CaptureSessionFixture(fixture) + let previous = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { previous }).value + let stream = ControlledCaptureStream() let entered = fixture.gate(), release = fixture.gate() - try await fixture.track(owner.replace { old }).value - old.stopEntered = entered; old.stopRelease = release - let first = fixture.track(owner.replace { obsolete }) + let stopping = fixture.gate(), stopped = fixture.gate() + stream.startEntered = entered; stream.startRelease = release + stream.stopEntered = stopping; stream.stopRelease = stopped + let selection = fixture.track(runtime.provider.selectStream { stream }) try await entered.wait() - let second = fixture.track(owner.replace { current }) - let stop = fixture.track(owner.stop()) - #expect(obsolete.starts == 0 && current.starts == 0) + var firstReturned = false, secondReturned = false + let first = fixture.track(Task { + await runtime.session.stopTranscribing(); firstReturned = true + }) + try await runtime.dismissed.wait() + let secondEntered = fixture.gate() + let second = fixture.track(Task { + secondEntered.open() + await runtime.session.stopTranscribing(); secondReturned = true + }) + try await secondEntered.wait() + #expect(!firstReturned && !secondReturned) release.open() - try await first.value - try await second.value - try await stop.value - #expect(owner.stream == nil) - #expect(!old.capturing) - #expect(obsolete.starts == 0 && current.starts == 0) + try await stopping.wait() + #expect(!firstReturned && !secondReturned) + #expect(runtime.session.status == .stopping) + stopped.open() + await first.value; await second.value; await selection.value + #expect(firstReturned && secondReturned) + #expect(!previous.capturing && !stream.capturing && runtime.owner.stream == nil) + #expect(runtime.session.status == .idle) } } - @Test("A superseded start compensates before its successor can start") + @Test("Superseded public resume publishes running and allows pause", arguments: [false, true]) @MainActor - func replacementIdentityAcrossStart() async throws { - guard #available(iOS 26.0, macOS 26.0, *) else { return } + func supersededPublicResumeFailure(fails: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in - let owner = ScreenCaptureTransitions() - let obsolete = ControlledCaptureStream(), current = ControlledCaptureStream() - let startEntered = fixture.gate(), startRelease = fixture.gate() - let stopEntered = fixture.gate(), stopRelease = fixture.gate() - obsolete.startEntered = startEntered; obsolete.startRelease = startRelease - obsolete.stopEntered = stopEntered; obsolete.stopRelease = stopRelease - let first = fixture.track(owner.replace { obsolete }) - try await startEntered.wait() - let second = fixture.track(owner.replace { current }) - startRelease.open() - try await stopEntered.wait() - #expect(current.starts == 0) - #expect(owner.stream === obsolete) - stopRelease.open() - try await first.value - try await second.value - #expect(!obsolete.capturing) - #expect(obsolete.stops == 1) - #expect(owner.stream === current) - #expect(current.starts == 1) - try await fixture.track(owner.stop()).value - } - } -} - -#if canImport(ScreenCaptureKit) -import ScreenCaptureKit - -/// Replaces only authorization, native analyzer preparation/finalization and picker -/// presentation. Public setup, provider, picker admission, transitions and stop are real. -@available(iOS 27.0, macOS 26.0, *) -@MainActor -private final class PublicCaptureFixture { - let session = SpeechSession() - let owner = ScreenCaptureTransitions() - let stream = ControlledCaptureStream() - var provider: ScreenCaptureAudioInputProvider? - let presented: CaptureGate - let dismissed: CaptureGate - let finalized: CaptureGate - let finalizeRelease: CaptureGate - let terminal: CaptureGate - var consumerFinished = false - var consumerError: Error? - - init(_ fixture: CaptureFixture) { - presented = fixture.gate(); dismissed = fixture.gate() - finalized = fixture.gate(); finalizeRelease = fixture.gate(); terminal = fixture.gate() - session.screenCapturePipelineHooks = ScreenCapturePipelineHooks( - authorize: {}, - prepareAnalysis: { [self] in - let (_, inputs) = AsyncStream.makeStream() - return ScreenCapturePreparedAnalysis( - format: AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)!, - inputs: inputs, - finalize: { [self] in - finalized.open() - // A native call may ignore the cancelling caller until explicitly released. - let join = fixture.track(Task { @MainActor in try await finalizeRelease.wait() }) - do { try await join.value } catch { Issue.record("Finalization gate failed: \(error)") } - } - ) - }, - makeProvider: { [self] format, inputs, failure in - let provider = ScreenCaptureAudioInputProvider( - options: .init(), targetFormat: format, inputContinuation: inputs, - onFailure: failure, transitions: owner, - presentPicker: { [self] _ in presented.open() }, - dismissPicker: { [self] _ in dismissed.open() } - ) - self.provider = provider - return provider - } - ) - } - - func start(_ fixture: CaptureFixture, select: Bool = true) async throws { - let results = session.startTranscribingScreenCapture() - fixture.track(Task { @MainActor in - do { for try await _ in results {} } catch { consumerError = error } - consumerFinished = true - terminal.open() - }) - try await presented.wait() - if select { - provider?.selectStream { [self] in stream } - // Public pause waits until setup has published transcribing. Readiness is - // observed from the existing status stream, never a state setter or a delay. - let ready = fixture.gate() - let statuses = session.statusStream - fixture.track(Task { @MainActor in - for await status in statuses where status == .transcribing { - ready.open() - return - } - }) - try await ready.wait() + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), successor = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { old }).value + await runtime.session.pauseTranscribing() + let entered = fixture.gate(), release = fixture.gate() + old.startEntered = entered; old.startRelease = release + old.startError = fails ? CaptureFixtureError.startFailed : nil + let resume = fixture.track(Task { try await runtime.session.resumeTranscribing() }) + try await entered.wait() + let replacement = fixture.track(runtime.provider.selectStream { successor }) + release.open() + try await resume.value + await replacement.value + #expect(runtime.session.status == .transcribing && successor.capturing) + #expect(!old.capturing) + await runtime.session.pauseTranscribing() + #expect(runtime.session.status == .paused && !successor.capturing) + #expect(successor.stops == 1) + await runtime.close(fixture) } } - func close(_ fixture: CaptureFixture) async { - fixture.releaseAll() - await fixture.track(Task { await session.stopTranscribing() }).value - session.screenCapturePipelineHooks = nil - } -} - -extension ScreenCaptureTransitionTests { - @Test( - "Public stop joins pending setup or resume and concurrent stop through finalization", - arguments: [false, true] - ) + @Test("Current resume failure still propagates and tears down") @MainActor - func publicStopJoinsSetupUnwindAndConcurrentStop(afterPause: Bool) async throws { + func currentResumeFailure() async throws { guard #available(iOS 27.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in - let runtime = PublicCaptureFixture(fixture) - do { - // Pending initial selection wakes the real setup catch on stop. The - // second case enters public resume after a real public start and pause. - try await runtime.start(fixture, select: afterPause) - if afterPause { await runtime.session.pauseTranscribing() } - let entered = fixture.gate(), release = fixture.gate() - runtime.stream.startEntered = entered; runtime.stream.startRelease = release - var resume: Task? - if afterPause { - resume = fixture.track(Task { try await runtime.session.resumeTranscribing() }) - } else { - runtime.provider?.selectStream { runtime.stream } - } - try await entered.wait() - var firstReturned = false, secondReturned = false - let first = fixture.track(Task { @MainActor in - await runtime.session.stopTranscribing(); firstReturned = true - }) - try await runtime.dismissed.wait() - let secondEntered = fixture.gate() - let second = fixture.track(Task { @MainActor in - secondEntered.open() - await runtime.session.stopTranscribing(); secondReturned = true - }) - try await secondEntered.wait() - #expect(!firstReturned && !secondReturned) - #expect(!runtime.consumerFinished) - #expect(runtime.session.status != .idle) - release.open() - try await runtime.finalized.wait() - #expect(!runtime.stream.capturing) - #expect(!firstReturned && !secondReturned) - #expect(!runtime.consumerFinished) - runtime.finalizeRelease.open() - await first.value; await second.value - try await resume?.value - try await runtime.terminal.wait() - #expect(firstReturned && secondReturned) - #expect(runtime.session.status == .idle) - #expect(runtime.consumerError == nil) - } catch { - await runtime.close(fixture) - throw error + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { stream }).value + await runtime.session.pauseTranscribing() + stream.startError = CaptureFixtureError.startFailed + await #expect(throws: CaptureFixtureError.self) { + try await runtime.session.resumeTranscribing() } - await runtime.close(fixture) + #expect(runtime.session.status == .idle && !stream.capturing) } } - @Test("Late failing public resume cannot retire a newer picker admission") + @Test("A failed native pause keeps the public status transcribing") @MainActor - func supersededPublicResumeFailure() async throws { + func failedPause() async throws { guard #available(iOS 27.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in - let runtime = PublicCaptureFixture(fixture) - do { - try await runtime.start(fixture) - await runtime.session.pauseTranscribing() - #expect(runtime.session.status == .paused) - let entered = fixture.gate(), release = fixture.gate() - runtime.stream.startEntered = entered; runtime.stream.startRelease = release - runtime.stream.startError = CaptureFixtureError.startFailed - let resume = fixture.track(Task { try await runtime.session.resumeTranscribing() }) - try await entered.wait() - let successor = ControlledCaptureStream() - let successorStarted = fixture.gate() - successor.startEntered = successorStarted - runtime.provider?.selectStream { successor } - release.open() - try await resume.value - try await successorStarted.wait() - #expect(!runtime.consumerFinished) - #expect(runtime.session.status == .transcribing) - #expect(runtime.owner.stream === successor) - #expect(successor.capturing) - await runtime.session.pauseTranscribing() - #expect(!successor.capturing) - successor.startError = CaptureFixtureError.startFailed - runtime.finalizeRelease.open() - do { - try await runtime.session.resumeTranscribing() - Issue.record("Current resume failure was lost") - } catch CaptureFixtureError.startFailed {} // Original error must propagate. - try await runtime.terminal.wait() - #expect(runtime.consumerError is CaptureFixtureError) - } catch { - await runtime.close(fixture) - throw error - } + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { stream }).value + stream.stopError = CaptureFixtureError.startFailed + await runtime.session.pauseTranscribing() + #expect(runtime.session.status == .transcribing && stream.capturing) + stream.stopError = nil + await runtime.session.pauseTranscribing() + #expect(runtime.session.status == .paused && !stream.capturing) await runtime.close(fixture) } } From 2d128fb3f9dd6bf2a94a27afc981b59b284dcd21 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:08:57 +0530 Subject: [PATCH 25/70] Cover pending successor starts and failed pause replacement --- .../ScreenCaptureTransitionTests.swift | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index 362bafb..ef783dc 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -136,10 +136,18 @@ struct ScreenCaptureTransitionTests { let entered = fixture.gate(), release = fixture.gate() old.startEntered = entered; old.startRelease = release old.startError = fails ? CaptureFixtureError.startFailed : nil - let resume = fixture.track(Task { try await runtime.session.resumeTranscribing() }) + var resumeReturned = false + let resume = fixture.track(Task { + try await runtime.session.resumeTranscribing(); resumeReturned = true + }) try await entered.wait() + let successorEntered = fixture.gate(), successorRelease = fixture.gate() + successor.startEntered = successorEntered; successor.startRelease = successorRelease let replacement = fixture.track(runtime.provider.selectStream { successor }) release.open() + try await successorEntered.wait() + #expect(!resumeReturned && runtime.session.status == .paused) + successorRelease.open() try await resume.value await replacement.value #expect(runtime.session.status == .transcribing && successor.capturing) @@ -168,9 +176,9 @@ struct ScreenCaptureTransitionTests { } } - @Test("A failed native pause keeps the public status transcribing") + @Test("A failed native pause keeps the public status transcribing", arguments: [false, true]) @MainActor - func failedPause() async throws { + func failedPause(replaceAfterFailure: Bool) async throws { guard #available(iOS 27.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in let runtime = try CaptureSessionFixture(fixture) @@ -180,8 +188,13 @@ struct ScreenCaptureTransitionTests { await runtime.session.pauseTranscribing() #expect(runtime.session.status == .transcribing && stream.capturing) stream.stopError = nil + let active = replaceAfterFailure ? ControlledCaptureStream() : stream + if replaceAfterFailure { + await fixture.track(runtime.provider.selectStream { active }).value + #expect(active.capturing && runtime.session.status == .transcribing) + } await runtime.session.pauseTranscribing() - #expect(runtime.session.status == .paused && !stream.capturing) + #expect(runtime.session.status == .paused && !active.capturing && !stream.capturing) await runtime.close(fixture) } } From 5c0cc0085db405e67f1a54b11f1639ba4c4f8946 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:09:36 +0530 Subject: [PATCH 26/70] Wait for replacement starts and restore intent after failed pause --- .../AuralKit/ScreenCaptureTransitions.swift | 50 ++++++++++++------- 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index aa91637..4f6deb1 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -48,9 +48,17 @@ final class ScreenCaptureTransitions { func pause() -> Task { guard desiredState != .stopped else { return enqueue {} } - controlRevision = UUID() + let control = UUID() + controlRevision = control desiredState = .paused - return enqueue { try await self.stopCurrent() } + return enqueue { + do { + try await self.stopCurrent() + } catch { + if self.controlRevision == control { self.desiredState = .running } + throw error + } + } } func resume() -> Task { @@ -58,25 +66,29 @@ final class ScreenCaptureTransitions { controlRevision = control desiredState = desiredState == .stopped ? .stopped : .running let admitted = revision - let previous = tail - let operation = Task { @MainActor in - _ = try? await previous?.value - let error: Error? - do { - try await self.startCurrent(revision: admitted) - error = nil - } catch let failure { - error = failure - } - return ScreenCaptureResumeOutcome { - guard self.desiredState == .running, self.controlRevision == control else { return false } - // A new selection inherits run intent, but not the old selection's failure. - if self.revision == admitted, let error { throw error } - return true + let operation = enqueue { try await self.startCurrent(revision: admitted) } + // This observer is never the operation tail: following a replacement cannot join itself. + return Task { @MainActor in + var selection = admitted + var pending = operation + while true { + let result = await pending.result + guard self.desiredState == .running, self.controlRevision == control else { + return ScreenCaptureResumeOutcome { false } + } + if self.revision != selection, let successor = self.tail { + selection = self.revision + pending = successor + continue + } + let settled = selection + return ScreenCaptureResumeOutcome { + guard self.desiredState == .running, self.controlRevision == control else { return false } + if self.revision == settled { try result.get() } + return true + } } } - tail = Task { _ = await operation.value } - return operation } func stop() -> Task { From 3a48262d29e9a949e4727907c6bf80e21cc973c5 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:13:30 +0530 Subject: [PATCH 27/70] Publish resume status atomically with capture ownership --- .../AuralKit/ScreenCaptureTransitions.swift | 22 +++++-------------- .../SpeechSession+ScreenCapture.swift | 22 ++++++++++++++----- Sources/AuralKit/SpeechSession.swift | 12 +++++----- 3 files changed, 30 insertions(+), 26 deletions(-) diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index 4f6deb1..1522241 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -7,12 +7,6 @@ protocol ScreenCaptureStream: AnyObject { func stopCapture() async throws } -@available(iOS 26.0, macOS 14.0, *) -@MainActor -struct ScreenCaptureResumeOutcome { - let resolve: @MainActor () throws -> Bool -} - /// Serializes capture side effects across suspension. Admission changes intent immediately; /// only internal operations are joined, never a public caller that may await session cleanup. @available(iOS 26.0, macOS 14.0, *) @@ -61,7 +55,9 @@ final class ScreenCaptureTransitions { } } - func resume() -> Task { + func resume( + onCompletion: @escaping @MainActor (Result) -> Void + ) -> Task { let control = UUID() controlRevision = control desiredState = desiredState == .stopped ? .stopped : .running @@ -73,20 +69,14 @@ final class ScreenCaptureTransitions { var pending = operation while true { let result = await pending.result - guard self.desiredState == .running, self.controlRevision == control else { - return ScreenCaptureResumeOutcome { false } - } + guard self.desiredState == .running, self.controlRevision == control else { return } if self.revision != selection, let successor = self.tail { selection = self.revision pending = successor continue } - let settled = selection - return ScreenCaptureResumeOutcome { - guard self.desiredState == .running, self.controlRevision == control else { return false } - if self.revision == settled { try result.get() } - return true - } + onCompletion(result) + return } } } diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 317af02..478f651 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -158,14 +158,26 @@ extension SpeechSession { return await provider.pause() } - func resumeScreenCaptureStreamingIfNeeded() async throws -> ScreenCaptureResumeOutcome { + func resumeScreenCaptureStreamingIfNeeded(generation: Int) async throws -> Error? { guard #available(iOS 27.0, macOS 14.0, *) else { throw SpeechSessionError.screenCaptureUnavailable } guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { throw SpeechSessionError.recognitionStreamSetupFailed } - return await provider.resume() + var failure: Error? + await provider.resume { result in + guard generation == self.sessionGeneration, + self.status == .paused, self.streamingMode == .screenCapture else { return } + switch result { + case .success: + self.setStatus(.transcribing) + case .failure(let error): + failure = error + self.prepareForStop() + } + } + return failure } func stopScreenCaptureStreamingIfNeeded() async { @@ -273,8 +285,8 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } @MainActor - func resume() async -> ScreenCaptureResumeOutcome { - await transitions.resume().value + func resume(onCompletion: @escaping @MainActor (Result) -> Void) async { + await transitions.resume(onCompletion: onCompletion).value } @MainActor @@ -451,7 +463,7 @@ public extension SpeechSession { extension SpeechSession { func pauseScreenCaptureStreamingIfNeeded() async -> Bool { false } - func resumeScreenCaptureStreamingIfNeeded() async throws -> ScreenCaptureResumeOutcome { + func resumeScreenCaptureStreamingIfNeeded(generation: Int) async throws -> Error? { throw SpeechSessionError.screenCaptureUnavailable } diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 6c9ee00..dbcc135 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -377,17 +377,19 @@ public final class SpeechSession { public func resumeTranscribing() async throws { guard status == .paused, isPausableStreamingMode else { return } let generation = sessionGeneration + var captureFailure: Error? do { if streamingMode == .screenCapture { - let outcome = try await resumeScreenCaptureStreamingIfNeeded() - guard try outcome.resolve() else { return } - } else { - try startAudioStreaming() + captureFailure = try await resumeScreenCaptureStreamingIfNeeded(generation: generation) + if let captureFailure { throw captureFailure } + return } + try startAudioStreaming() guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { return } setStatus(.transcribing) } catch { - guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { throw error } + let canFinish = status == .paused || (captureFailure != nil && status == .stopping) + guard generation == sessionGeneration, canFinish, isPausableStreamingMode else { throw error } prepareForStop() await cleanup(cancelRecognizer: true, generation: generation) await finishStream(error: error, generation: generation) From a724fa3b0e7b47182bf4166ee1a43127852ae9e6 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:14:25 +0530 Subject: [PATCH 28/70] Retire model preparation without waiting for downloads --- Sources/AuralKit/ModelManager.swift | 106 ++-- .../AuralKit/SpeechAssetReservations.swift | 88 ++- .../SpeechAssetReservationTestFixtures.swift | 30 +- .../SpeechAssetReservationTests.swift | 513 +++++------------- 4 files changed, 232 insertions(+), 505 deletions(-) diff --git a/Sources/AuralKit/ModelManager.swift b/Sources/AuralKit/ModelManager.swift index c7ea488..93c2b4a 100644 --- a/Sources/AuralKit/ModelManager.swift +++ b/Sources/AuralKit/ModelManager.swift @@ -13,9 +13,7 @@ actor ModelManager { private let reservations: SpeechAssetReservations private let assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? private var leases: Set = [] - private var preparations = 0 - private var preparationWaiters: [CheckedContinuation] = [] - private var cleanupTask: Task? + private var generation = 0 init( reservations: SpeechAssetReservations = .shared, @@ -47,8 +45,8 @@ actor ModelManager { return } - try await prepareAssets(for: [module]) { manager in - try await manager.downloadAssetsIfNeeded(for: [module]) + try await prepareAssets(for: [module]) { manager, generation in + try await manager.downloadAssetsIfNeeded(for: [module], generation: generation) } } @@ -58,19 +56,19 @@ actor ModelManager { supportedLocales: @escaping @Sendable () async -> [Locale], installedLocales: @escaping @Sendable () async -> [Locale] ) async throws { - try await prepareAssets(for: [module], validate: { manager in + try await prepareAssets(for: [module]) { manager, generation in guard await manager.localeMatches(provider: supportedLocales, locale: locale) else { throw SpeechSessionError.unsupportedLocale(locale) } - }, install: { manager in if await manager.localeMatches(provider: installedLocales, locale: locale) { manager.logger.notice("Locale \(locale.identifier(.bcp47)) already installed") + try manager.requireCurrent(generation) manager.currentDownloadProgress = nil } else { manager.logger.info("Ensuring model download for locale \(locale.identifier(.bcp47))") - try await manager.downloadAssetsIfNeeded(for: [module]) + try await manager.downloadAssetsIfNeeded(for: [module], generation: generation) } - }) + } } private func localeMatches( @@ -84,27 +82,28 @@ actor ModelManager { func ensureAssets(for modules: [any SpeechModule]) async throws { guard !modules.isEmpty else { return } - try await prepareAssets(for: modules) { manager in - try await manager.downloadAssetsIfNeeded(for: modules) + try await prepareAssets(for: modules) { manager, generation in + try await manager.downloadAssetsIfNeeded(for: modules, generation: generation) } } - private func downloadAssetsIfNeeded(for modules: [any SpeechModule]) async throws { - try requirePreparation() + private func downloadAssetsIfNeeded(for modules: [any SpeechModule], generation: Int) async throws { + try requireCurrent(generation) if let assetDownloader { try await assetDownloader(modules) return } - if let downloader = try await AssetInventory.assetInstallationRequest(supporting: modules) { - try requirePreparation() + let request = try await reservations.withInventoryAccess { + try await AssetInventory.assetInstallationRequest(supporting: modules) + } + if let downloader = request { + try requireCurrent(generation) currentDownloadProgress = downloader.progress logger.info("Starting asset download for \(modules.count) module(s)") do { try await downloader.downloadAndInstall() - currentDownloadProgress = nil - logger.notice("Asset download completed successfully") } catch { - currentDownloadProgress = nil + if self.generation == generation { currentDownloadProgress = nil } logger.error("Asset download failed: \(error.localizedDescription, privacy: .public)") // Check for network connectivity errors @@ -116,54 +115,37 @@ actor ModelManager { throw SpeechSessionError.modelDownloadFailed(nsError) } + try requireCurrent(generation) + currentDownloadProgress = nil + logger.notice("Asset download completed successfully") } else { + try requireCurrent(generation) currentDownloadProgress = nil logger.debug("No asset download required for modules") } } - /// Close preparation admission and join it before returning locale leases. - /// A late native acquisition/download must not outlive its manager cleanup. + /// Retire pending preparation without waiting for a native download to finish. func releaseLocales() async { - await beginReleasingLocales().value - } - - /// Close admission synchronously on this actor; concurrent releases join one drain. - /// Only ModelManager preparation is joined here, never its calling pipeline task: - /// a failed setup may itself call releaseLocales after ensureModel has unwound. - func beginReleasingLocales() -> Task { - if let cleanupTask { return cleanupTask } - let cleanup = Task { - if self.preparations != 0 { - await withCheckedContinuation { self.preparationWaiters.append($0) } - } - let pending = self.leases - self.leases.removeAll() - for lease in pending { - await self.reservations.release(lease) - } - self.currentDownloadProgress = nil - self.cleanupTask = nil - self.logger.debug("Released \(pending.count) session locale lease(s)") - } - cleanupTask = cleanup - return cleanup + generation &+= 1 + let pending = leases + leases.removeAll() + currentDownloadProgress = nil + for lease in pending { await reservations.release(lease) } } private func prepareAssets( for modules: [any SpeechModule], - validate: @Sendable (isolated ModelManager) async throws -> Void = { _ in }, - install: @Sendable (isolated ModelManager) async throws -> Void + install: @Sendable (isolated ModelManager, Int) async throws -> Void ) async throws { - try requirePreparation() - preparations += 1 - defer { preparationFinished() } + let generation = self.generation + try requireCurrent(generation) + // Preserve first-install behavior: downloading may create native reservations. + // Those reservations remain borrowed; only explicit acquisitions are owned here. + try await install(self, generation) + try requireCurrent(generation) var acquired: [SpeechAssetReservations.Lease] = [] do { - try await validate(self) - try requirePreparation() - // These are module-defined asset locales, not guessed equivalents - // of the user's preferred transcription language. let locales = modules.compactMap { $0 as? any LocaleDependentSpeechModule } .flatMap { $0.selectedLocales } var requested = Set() @@ -175,29 +157,17 @@ actor ModelManager { } catch { throw SpeechSessionError.modelReservationFailed(locale, error) } - try requirePreparation() + try requireCurrent(generation) } - try await install(self) - try requirePreparation() leases.formUnion(acquired) } catch { - for lease in acquired { - await reservations.release(lease) - } + for lease in acquired { await reservations.release(lease) } throw error } } - private func requirePreparation() throws { + private func requireCurrent(_ generation: Int) throws { try Task.checkCancellation() - guard cleanupTask == nil else { throw CancellationError() } - } - - private func preparationFinished() { - preparations -= 1 - guard preparations == 0 else { return } - let waiters = preparationWaiters - preparationWaiters.removeAll() - for waiter in waiters { waiter.resume() } + guard self.generation == generation else { throw CancellationError() } } } diff --git a/Sources/AuralKit/SpeechAssetReservations.swift b/Sources/AuralKit/SpeechAssetReservations.swift index 4da4a62..059fdad 100644 --- a/Sources/AuralKit/SpeechAssetReservations.swift +++ b/Sources/AuralKit/SpeechAssetReservations.swift @@ -19,34 +19,20 @@ actor SpeechAssetReservations { } struct Lease: Hashable, Sendable { - fileprivate let id: UUID + fileprivate let id = UUID() + fileprivate let alias: String + fileprivate let protectedKeys: Set } enum ReservationError: Error { case ambiguousInventoryChange } - private struct Reservation { - let locale: Locale - var holders: Set = [] - } - - private struct Alias { - let protectedKeys: Set - var holders: Set = [] - } - - private struct Holding { - let alias: String - let protectedKeys: Set - } - static let shared = SpeechAssetReservations() private let inventory: Inventory - private var reservations: [String: Reservation] = [:] - private var aliases: [String: Alias] = [:] - private var holdings: [UUID: Holding] = [:] + private var reservations: [String: Locale] = [:] + private var leases: Set = [] private var tail: Task? private var queuedOperations = 0 @@ -56,17 +42,7 @@ actor SpeechAssetReservations { func acquire(_ locale: Locale) async throws -> Lease { try Task.checkCancellation() - let previous = tail - queuedOperations += 1 - let operation = Task { - await previous?.value - return try await self.acquireSerially(locale) - } - tail = Task { - _ = await operation.result - self.operationFinished() - } - let lease = try await operation.value + let lease = try await enqueue { try await self.acquireSerially(locale) }.value do { try Task.checkCancellation() return lease @@ -79,17 +55,31 @@ actor SpeechAssetReservations { } func release(_ lease: Lease) async { + _ = await enqueue { await self.releaseSerially(lease) }.result + } + + /// Installation requests also reserve locales; their creation shares this queue. + /// The subsequent download must run outside it. + func withInventoryAccess( + _ operation: @escaping @Sendable () async throws -> Value + ) async throws -> Value { + try await enqueue(operation).value + } + + private func enqueue( + _ operation: @escaping @Sendable () async throws -> Value + ) -> Task { let previous = tail queuedOperations += 1 - let operation = Task { + let task = Task { await previous?.value - await self.releaseSerially(lease) + return try await operation() } tail = Task { - await operation.value + _ = await task.result self.operationFinished() } - await operation.value + return task } private func operationFinished() { @@ -102,7 +92,7 @@ actor SpeechAssetReservations { private func acquireSerially(_ locale: Locale) async throws -> Lease { let alias = Self.key(locale) - if let known = aliases[alias] { + if let known = leases.first(where: { $0.alias == alias }) { return admit(alias: alias, protecting: known.protectedKeys) } if reservations[alias] != nil { @@ -126,7 +116,7 @@ actor SpeechAssetReservations { throw ReservationError.ambiguousInventoryChange } if reservations[key] == nil { - reservations[key] = Reservation(locale: actual) + reservations[key] = actual } protectedKeys = [key] } else if after[alias] != nil { @@ -144,30 +134,16 @@ actor SpeechAssetReservations { } private func admit(alias: String, protecting keys: Set) -> Lease { - let lease = Lease(id: UUID()) - var entry = aliases[alias] ?? Alias(protectedKeys: keys) - entry.holders.insert(lease.id) - aliases[alias] = entry - holdings[lease.id] = Holding(alias: alias, protectedKeys: keys) - for key in keys { - reservations[key]?.holders.insert(lease.id) - } + let lease = Lease(alias: alias, protectedKeys: keys) + leases.insert(lease) return lease } private func releaseSerially(_ lease: Lease) async { - guard let holding = holdings.removeValue(forKey: lease.id) else { return } - aliases[holding.alias]?.holders.remove(lease.id) - if aliases[holding.alias]?.holders.isEmpty == true { - aliases.removeValue(forKey: holding.alias) - } - for key in holding.protectedKeys { - reservations[key]?.holders.remove(lease.id) - } - for key in holding.protectedKeys { - guard let reservation = reservations[key], reservation.holders.isEmpty else { continue } - reservations.removeValue(forKey: key) - _ = await inventory.release(reservation.locale) + guard leases.remove(lease) != nil else { return } + for key in lease.protectedKeys where !leases.contains(where: { $0.protectedKeys.contains(key) }) { + guard let locale = reservations.removeValue(forKey: key) else { continue } + _ = await inventory.release(locale) } } diff --git a/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift b/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift index a6faee9..7d5d48b 100644 --- a/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift +++ b/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift @@ -1,4 +1,6 @@ import Foundation +import AVFoundation +import Speech @testable import AuralKit actor AssetGate { @@ -16,11 +18,18 @@ actor AssetGate { await withCheckedContinuation { waiters.append($0) } } + func waitOnce() async { + guard !entered else { return } + await wait() + } + func waitForEntry() async { guard !entered else { return } await withCheckedContinuation { arrivals.append($0) } } + var hasOpened: Bool { isOpen } + func open() { isOpen = true let pending = waiters @@ -42,7 +51,6 @@ actor AssetInventoryProbe { private var releaseCalls: [String] = [] private var reserveGate: AssetGate? private var releaseGate: AssetGate? - private var extraLocales: [Locale] = [] init(initial: [Locale] = [], variants: [String: Locale] = [:]) { stored = Dictionary(initial.map { ($0.identifier(.bcp47), $0) }, @@ -62,7 +70,6 @@ actor AssetInventoryProbe { func holdReserve(at gate: AssetGate) { reserveGate = gate } func holdRelease(at gate: AssetGate) { releaseGate = gate } - func addDuringNextReserve(_ locales: [Locale]) { extraLocales = locales } private func locales() -> [Locale] { Array(stored.values) } private func reserve(_ locale: Locale) async -> Bool { @@ -73,8 +80,6 @@ actor AssetInventoryProbe { let key = actual.identifier(.bcp47) guard stored[key] == nil else { return false } stored[key] = actual - for extra in extraLocales { stored[extra.identifier(.bcp47)] = extra } - extraLocales.removeAll() return true } @@ -85,3 +90,20 @@ actor AssetInventoryProbe { return stored.removeValue(forKey: key) != nil } } + +final class ReservationModule: LocaleDependentSpeechModule { + struct Result: SpeechModuleResult, Sendable { + let range = CMTimeRange.zero + let resultsFinalizationTime = CMTime.zero + } + + let selectedLocales: [Locale] + init(locales: [Locale]) { selectedLocales = locales } + + static var supportedLocales: [Locale] { get async { [] } } + static func supportedLocale(equivalentTo locale: Locale) async -> Locale? { nil } + var availableCompatibleAudioFormats: [AVAudioFormat] { get async { [] } } + var results: AsyncThrowingStream { + AsyncThrowingStream { $0.finish() } + } +} diff --git a/Tests/AuralKitTests/SpeechAssetReservationTests.swift b/Tests/AuralKitTests/SpeechAssetReservationTests.swift index 45eb1f0..ef3fa9c 100644 --- a/Tests/AuralKitTests/SpeechAssetReservationTests.swift +++ b/Tests/AuralKitTests/SpeechAssetReservationTests.swift @@ -1,392 +1,151 @@ import Foundation -import AVFoundation -import Speech import Testing @testable import AuralKit -@MainActor -private final class AssetReservationFixture { - let inventory: AssetInventoryProbe - let reservations: SpeechAssetReservations - private var gates: [AssetGate] = [] - private var acquisitions: [Task] = [] - private var work: [Task] = [] - private var releases: [Task] = [] - private var managers: [ModelManager] = [] - - init(initial: [Locale] = [], variants: [String: Locale] = [:]) { - let inventory = AssetInventoryProbe(initial: initial, variants: variants) - self.inventory = inventory - reservations = SpeechAssetReservations(inventory: inventory.client) - } - - func gate() -> AssetGate { - let gate = AssetGate() - gates.append(gate) - return gate - } - - func acquire(_ locale: Locale) -> Task { - let task = Task { try await reservations.acquire(locale) } - acquisitions.append(task) - return task - } - - func start(_ operation: @escaping @MainActor () async throws -> Void) -> Task { - let task = Task { try await operation() } - work.append(task) - return task - } - - func release(_ lease: SpeechAssetReservations.Lease) -> Task { - let task = Task { await reservations.release(lease) } - releases.append(task) - return task - } - - func manager( - download: @escaping @Sendable ([any SpeechModule]) async throws -> Void - ) -> ModelManager { - let manager = ModelManager(reservations: reservations, assetDownloader: download) - managers.append(manager) - return manager - } - - func release(_ manager: ModelManager) async -> Task { - let task = await manager.beginReleasingLocales() - releases.append(task) - return task - } - - func cleanup() async { - for task in acquisitions { task.cancel() } - for task in work { task.cancel() } - for gate in gates { await gate.open() } - for task in work { _ = await task.result } - for manager in managers { await manager.releaseLocales() } - for task in acquisitions { - if case .success(let lease) = await task.result { await reservations.release(lease) } - } - for task in releases { await task.value } - } - - enum ProbeError: Error { case download } -} - -/// Only module metadata is needed by ModelManager. No native provider is invoked. -private final class ReservationModule: LocaleDependentSpeechModule { - struct Result: SpeechModuleResult, Sendable { - let range = CMTimeRange.zero - let resultsFinalizationTime = CMTime.zero - } - - let selectedLocales: [Locale] - init(locales: [Locale]) { selectedLocales = locales } - - static var supportedLocales: [Locale] { get async { [] } } - static func supportedLocale(equivalentTo locale: Locale) async -> Locale? { nil } - var availableCompatibleAudioFormats: [AVAudioFormat] { get async { [] } } - var results: AsyncThrowingStream { - AsyncThrowingStream { $0.finish() } - } -} - @Suite("Speech asset reservations") struct SpeechAssetReservationTests { - @Test("concurrent sessions share acquisition and only the final owner releases") - @MainActor - func concurrentOwners() async throws { - try await withFixture { fixture in - let gate = fixture.gate() - await fixture.inventory.holdReserve(at: gate) - let first = fixture.acquire(Locale(identifier: "en-US")) - await gate.waitForEntry() - let second = fixture.acquire(Locale(identifier: "en-US")) + @Test("overlapping managers retain the locale until the final owner stops") + func overlappingManagers() async throws { + let inventory = AssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let first = ModelManager(reservations: reservations, assetDownloader: { _ in }) + let second = ModelManager(reservations: reservations, assetDownloader: { _ in }) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + try await first.ensureAssets(for: [module]) + try await second.ensureAssets(for: [module]) + await first.releaseLocales() + #expect(await inventory.snapshot.releases.isEmpty) + await second.releaseLocales() + await second.releaseLocales() + let state = await inventory.snapshot + #expect(state.reserves == ["en-US"]) + #expect(state.releases == ["en-US"]) + #expect(state.locales.isEmpty) + } + + @Test("cleanup returns before a noncooperative download and rejects its late completion") + func cleanupDuringDownload() async throws { + let inventory = AssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let gate = AssetGate() + let manager = ModelManager(reservations: reservations, assetDownloader: { _ in await gate.waitOnce() }) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let old = Task { try await manager.ensureAssets(for: [module]) } + await gate.waitForEntry() + #expect(await inventory.snapshot.reserves.isEmpty) + let rescue = Task { + try? await Task.sleep(for: .seconds(1)) await gate.open() - let firstLease = try await first.value - let secondLease = try await second.value - await fixture.reservations.release(firstLease) - var state = await fixture.inventory.snapshot - #expect(state.reserves == ["en-US"]) - #expect(state.releases.isEmpty) - await fixture.reservations.release(secondLease) - state = await fixture.inventory.snapshot - #expect(state.releases == ["en-US"]) - #expect(state.locales.isEmpty) - } - } - - @Test("managers retain module-selected locales until the last holder releases") - @MainActor - func managerHolders() async throws { - try await withFixture { fixture in - let module = ReservationModule(locales: [Locale(identifier: "ja-JP")]) - let first = fixture.manager { _ in } - let second = fixture.manager { _ in } - // The explicit locale is not a substitute for module-selected asset identity. - try await first.ensureModel(module: module, locale: Locale(identifier: "en-US")) - try await second.ensureAssets(for: [module]) - await first.releaseLocales() - await first.releaseLocales() - var state = await fixture.inventory.snapshot - #expect(state.reserves == ["ja-JP"]) - #expect(state.releases.isEmpty) - await second.releaseLocales() - state = await fixture.inventory.snapshot - #expect(state.releases == ["ja-JP"]) - #expect(state.locales.isEmpty) } - } -} - -extension SpeechAssetReservationTests { - @Test("release uses the observed native locale variant") - @MainActor + await manager.releaseLocales() + #expect(await !gate.hasOpened, "Cleanup waited for the noncooperative download") + try await manager.ensureAssets(for: [module]) + await gate.open() + rescue.cancel() + await rescue.value + if case .success = await old.result { Issue.record("Retired download acquired a lease") } + #expect(await inventory.snapshot.releases.isEmpty) + await manager.releaseLocales() + let state = await inventory.snapshot + #expect(state.reserves == ["en-US"]) + #expect(state.releases == ["en-US"]) + #expect(state.locales.isEmpty) + } + + @Test("a canceled late acquisition cannot release its successor's reservation") + func cleanupDuringAcquisition() async throws { + let inventory = AssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let gate = AssetGate() + await inventory.holdReserve(at: gate) + let manager = ModelManager(reservations: reservations, assetDownloader: { _ in }) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let old = Task { try await manager.ensureAssets(for: [module]) } + await gate.waitForEntry() + old.cancel() + await manager.releaseLocales() + let successor = Task { try await manager.ensureAssets(for: [module]) } + await gate.open() + if case .success = await old.result { Issue.record("Canceled acquisition succeeded") } + try await successor.value + #expect(await inventory.snapshot.locales == ["en-US"]) + await manager.releaseLocales() + let state = await inventory.snapshot + #expect(state.releases.count == state.reserves.count) + #expect(state.locales.isEmpty) + } + + @Test("borrowed external reservations survive cleanup", arguments: ["en-US", "en-AU"]) + func borrowedReservation(alias: String) async throws { + let inventory = AssetInventoryProbe(initial: [Locale(identifier: "en-US")], + variants: ["en-AU": Locale(identifier: "en-US")]) + let reservations = SpeechAssetReservations(inventory: inventory.client) + let manager = ModelManager(reservations: reservations, assetDownloader: { _ in }) + try await manager.ensureAssets(for: [ReservationModule(locales: [Locale(identifier: alias)])]) + await manager.releaseLocales() + #expect(await inventory.snapshot.releases.isEmpty) + #expect(await inventory.snapshot.locales == ["en-US"]) + } + + @Test("variant holders protect the observed native reservation") func canonicalVariant() async throws { - try await withFixture(variants: ["en-AU": Locale(identifier: "en-US")]) { fixture in - let lease = try await fixture.acquire(Locale(identifier: "en-AU")).value - let canonical = try await fixture.acquire(Locale(identifier: "en-US")).value - let alias = try await fixture.acquire(Locale(identifier: "en-AU")).value - await fixture.reservations.release(lease) - await fixture.reservations.release(canonical) - #expect(await fixture.inventory.snapshot.releases.isEmpty) - await fixture.reservations.release(alias) - let state = await fixture.inventory.snapshot - #expect(state.reserves == ["en-AU"]) - #expect(state.releases == ["en-US"]) - #expect(state.locales.isEmpty) - } - } - - @Test("preexisting variant reservations remain borrowed") - @MainActor - func preexistingReservation() async throws { - try await withFixture(initial: [Locale(identifier: "en-US")], - variants: ["en-AU": Locale(identifier: "en-US")]) { fixture in - let lease = try await fixture.acquire(Locale(identifier: "en-AU")).value - await fixture.reservations.release(lease) - let state = await fixture.inventory.snapshot - #expect(state.releases.isEmpty) - #expect(state.locales == ["en-US"]) - } - } - - @Test("an externally reserved exact locale survives manager cleanup") - @MainActor - func externalManagerReservation() async throws { - try await withFixture(initial: [Locale(identifier: "en-US")]) { fixture in - let module = ReservationModule(locales: [Locale(identifier: "en-US")]) - let manager = fixture.manager { _ in } - try await manager.ensureAssets(for: [module]) - await manager.releaseLocales() - let state = await fixture.inventory.snapshot - #expect(state.reserves.isEmpty) - #expect(state.releases.isEmpty) - #expect(state.locales == ["en-US"]) - } - } - - @Test("a borrowed alias conservatively protects all current owned candidates") - @MainActor - func multipleAliasCandidates() async throws { - try await withFixture(variants: ["en-AU": Locale(identifier: "en-US")]) { fixture in - let english = try await fixture.acquire(Locale(identifier: "en-US")).value - let japanese = try await fixture.acquire(Locale(identifier: "ja-JP")).value - let alias = try await fixture.acquire(Locale(identifier: "en-AU")).value - await fixture.reservations.release(english) - await fixture.reservations.release(japanese) - #expect(await fixture.inventory.snapshot.releases.isEmpty) - await fixture.reservations.release(alias) - let state = await fixture.inventory.snapshot - #expect(Set(state.releases) == ["en-US", "ja-JP"]) - #expect(state.locales.isEmpty) - } - } - - @Test("unknown borrowed aliases protect current candidates, not future unrelated assets") - @MainActor - func ambiguousBorrower() async throws { - try await withFixture(variants: ["en-AU": Locale(identifier: "en-US")]) { fixture in - let owner = try await fixture.acquire(Locale(identifier: "en-US")).value - let borrower = try await fixture.acquire(Locale(identifier: "en-AU")).value - let later = try await fixture.acquire(Locale(identifier: "ja-JP")).value - await fixture.reservations.release(owner) - var state = await fixture.inventory.snapshot - #expect(state.releases.isEmpty) - await fixture.reservations.release(later) - state = await fixture.inventory.snapshot - #expect(state.releases == ["ja-JP"]) - await fixture.reservations.release(borrower) - state = await fixture.inventory.snapshot - #expect(state.releases == ["ja-JP", "en-US"]) - } - } - - @Test("ambiguous native mutations are not claimed or broadly released") - @MainActor - func ambiguousInventoryMutation() async throws { - try await withFixture { fixture in - await fixture.inventory.addDuringNextReserve([Locale(identifier: "fr-FR")]) - let operation = fixture.acquire(Locale(identifier: "en-US")) - if case .success = await operation.result { Issue.record("Ambiguous inventory was accepted") } - let state = await fixture.inventory.snapshot - #expect(state.releases.isEmpty) - #expect(state.locales == ["en-US", "fr-FR"]) - } - } - - @Test("reacquisition during release waits and establishes a fresh reservation") - @MainActor - func reacquisitionDuringRelease() async throws { - try await withFixture { fixture in - let lease = try await fixture.acquire(Locale(identifier: "en-US")).value - let gate = fixture.gate() - await fixture.inventory.holdRelease(at: gate) - let release = fixture.release(lease) - await gate.waitForEntry() - let next = fixture.acquire(Locale(identifier: "en-US")) - await gate.open() - await release.value - let nextLease = try await next.value - var state = await fixture.inventory.snapshot - #expect(state.reserves == ["en-US", "en-US"]) - #expect(state.locales == ["en-US"]) - await fixture.reservations.release(nextLease) - state = await fixture.inventory.snapshot - #expect(state.releases == ["en-US", "en-US"]) - } - } - - @Test("manager download failure returns its explicitly acquired locale") - @MainActor - func downloadFailure() async throws { - try await withFixture { fixture in - let module = ReservationModule(locales: [Locale(identifier: "en-US")]) - let manager = fixture.manager { _ in throw AssetReservationFixture.ProbeError.download } - let operation = fixture.start { - do { - try await manager.ensureAssets(for: [module]) - } catch { - await manager.releaseLocales() - throw error - } - } - if case .success = await operation.result { Issue.record("Download failure was ignored") } - let state = await fixture.inventory.snapshot - #expect(!state.reserves.isEmpty) - #expect(state.releases.count == state.reserves.count) - #expect(state.locales.isEmpty) - } - } - - @Test("canceling manager acquisition cannot abandon a late native reservation") - @MainActor - func canceledAcquisition() async throws { - try await withFixture { fixture in - let gate = fixture.gate() - await fixture.inventory.holdReserve(at: gate) - let module = ReservationModule(locales: [Locale(identifier: "en-US")]) - let manager = fixture.manager { _ in Issue.record("Canceled acquisition started a download") } - let operation = fixture.start { try await manager.ensureAssets(for: [module]) } - await gate.waitForEntry() - operation.cancel() - await gate.open() - if case .success = await operation.result { Issue.record("Canceled acquisition succeeded") } - let state = await fixture.inventory.snapshot - #expect(state.releases.count == 1) - #expect(state.locales.isEmpty) - } - } - - @Test("cancellation after acquisition returns the lease when preparation unwinds") - @MainActor - func canceledPreparation() async throws { - try await withFixture { fixture in - let gate = fixture.gate() - let module = ReservationModule(locales: [Locale(identifier: "en-US")]) - let manager = fixture.manager { _ in await gate.wait() } - let operation = fixture.start { try await manager.ensureAssets(for: [module]) } - await gate.waitForEntry() - operation.cancel() - #expect(await fixture.inventory.snapshot.releases.isEmpty) - await gate.open() - switch await operation.result { - case .failure(is CancellationError): break - default: Issue.record("Canceled preparation did not throw CancellationError") + let inventory = AssetInventoryProbe(variants: ["en-AU": Locale(identifier: "en-US"), + "en-GB": Locale(identifier: "en-US")]) + let reservations = SpeechAssetReservations(inventory: inventory.client) + let owner = try await reservations.acquire(Locale(identifier: "en-AU")) + let borrower = try await reservations.acquire(Locale(identifier: "en-GB")) + let canonical = try await reservations.acquire(Locale(identifier: "en-US")) + await reservations.release(owner) + await reservations.release(canonical) + #expect(await inventory.snapshot.releases.isEmpty) + await reservations.release(borrower) + #expect(await inventory.snapshot.locales.isEmpty) + } + + @Test("implicit installation reservations cannot invalidate an explicit acquisition") + func concurrentInstallationRequest() async throws { + let inventory = AssetInventoryProbe() + let native = inventory.client + let gate = AssetGate() + let reservations = SpeechAssetReservations(inventory: .init( + locales: native.locales, + reserve: { locale in + let created = try await native.reserve(locale) + await gate.wait() + return created + }, release: native.release + )) + let owner = Task { try await reservations.acquire(Locale(identifier: "en-US")) } + await gate.waitForEntry() + let installation = Task { + try await reservations.withInventoryAccess { + _ = try await native.reserve(Locale(identifier: "fr-FR")) } - let state = await fixture.inventory.snapshot - #expect(state.releases == ["en-US"]) - #expect(state.locales.isEmpty) - } - } - - @Test("manager cleanup drains pending acquisitions before returning") - @MainActor - func cleanupDuringAcquisition() async throws { - try await withFixture { fixture in - let gate = fixture.gate() - await fixture.inventory.holdReserve(at: gate) - let module = ReservationModule(locales: [Locale(identifier: "en-US")]) - let manager = fixture.manager { _ in Issue.record("Retired preparation started a download") } - let operation = fixture.start { try await manager.ensureAssets(for: [module]) } - await gate.waitForEntry() - let cleanup = await fixture.release(manager) - let repeated = await fixture.release(manager) - await gate.open() - if case .success = await operation.result { Issue.record("Retired acquisition succeeded") } - await repeated.value - await cleanup.value - let state = await fixture.inventory.snapshot - #expect(state.releases.count == 1) - #expect(state.locales.isEmpty) - } - } - - @Test("manager cleanup retains reservations until an active download returns") - @MainActor - func cleanupDuringDownload() async throws { - try await withFixture { fixture in - let gate = fixture.gate() - let module = ReservationModule(locales: [Locale(identifier: "en-US")]) - let manager = fixture.manager { _ in await gate.wait() } - let operation = fixture.start { try await manager.ensureAssets(for: [module]) } - await gate.waitForEntry() - let cleanup = await fixture.release(manager) - let repeated = await fixture.release(manager) - let peer = fixture.manager { _ in } - try await peer.ensureAssets(for: [module]) - // Admission stays closed while cleanup is joining preparation. - let rejected = fixture.start { try await manager.ensureAssets(for: [module]) } - if case .success = await rejected.result { Issue.record("Cleanup admitted new preparation") } - var state = await fixture.inventory.snapshot - #expect(state.releases.isEmpty) - await gate.open() - if case .success = await operation.result { Issue.record("Retired download was admitted") } - await cleanup.value - await repeated.value - state = await fixture.inventory.snapshot - #expect(state.releases.isEmpty) - // A retired holder's repeated cleanup cannot return a peer's lease. - await manager.releaseLocales() - await peer.releaseLocales() - state = await fixture.inventory.snapshot - #expect(state.releases.count == 1) - #expect(state.locales.isEmpty) } + await gate.open() + let lease = try await owner.value + try await installation.value + await reservations.release(lease) + #expect(await inventory.snapshot.releases == ["en-US"]) + #expect(await inventory.snapshot.locales == ["fr-FR"]) } - @MainActor - private func withFixture( - initial: [Locale] = [], variants: [String: Locale] = [:], - operation: @MainActor (AssetReservationFixture) async throws -> Void - ) async throws { - let fixture = AssetReservationFixture(initial: initial, variants: variants) - do { - try await operation(fixture) - } catch { - await fixture.cleanup() - throw error - } - await fixture.cleanup() + @Test("reacquisition waits for a pending native release") + func reacquisitionDuringRelease() async throws { + let inventory = AssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let lease = try await reservations.acquire(Locale(identifier: "en-US")) + let gate = AssetGate() + await inventory.holdRelease(at: gate) + let release = Task { await reservations.release(lease) } + await gate.waitForEntry() + let next = Task { try await reservations.acquire(Locale(identifier: "en-US")) } + await gate.open() + await release.value + let nextLease = try await next.value + #expect(await inventory.snapshot.locales == ["en-US"]) + await reservations.release(nextLease) + #expect(await inventory.snapshot.reserves == ["en-US", "en-US"]) + #expect(await inventory.snapshot.releases == ["en-US", "en-US"]) } } From a0c0480eff6631c8083c5e977c4da64acc6b3a50 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:14:36 +0530 Subject: [PATCH 29/70] test: reproduce vocabulary admission and purged-file reuse failures --- .../CustomVocabularyOwnershipTests.swift | 11 +-- .../CustomVocabularyRecoveryTests.swift | 83 +++++++++++++++++++ 2 files changed, 89 insertions(+), 5 deletions(-) create mode 100644 Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift diff --git a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift index 3ad945f..6efec35 100644 --- a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift +++ b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift @@ -6,11 +6,11 @@ import Testing @Suite("Custom vocabulary artifact ownership") @MainActor struct CustomVocabularyOwnershipTests { - private func descriptor(_ version: String = "1") -> SpeechSession.CustomVocabulary { + func descriptor(_ version: String = "1") -> SpeechSession.CustomVocabulary { .init(locale: Locale(identifier: "en_US"), identifier: "ownership-test", version: version, weight: 0.4) } - private func session(_ preparation: VocabularyPreparation) -> SpeechSession { + func session(_ preparation: VocabularyPreparation) -> SpeechSession { let session = SpeechSession(locale: Locale(identifier: "en_US")) session.customVocabularyCompiler = CustomVocabularyCompiler { descriptor, asset, configuration in try await preparation.prepare(descriptor, asset: asset, configuration: configuration) @@ -63,6 +63,7 @@ struct CustomVocabularyOwnershipTests { let preparation = VocabularyPreparation() let session = session(preparation) let request = Task { @MainActor in + defer { preparation.ready.continuation.finish() } try await session.configureCustomVocabulary(descriptor("blocked")) } do { @@ -120,7 +121,7 @@ struct CustomVocabularyOwnershipTests { try await owner!.configureCustomVocabulary(descriptor()) let directory = try #require(owner?.customVocabularyOutputDirectory) // Constructs the real customized module; no asset install or analyzer start. - _ = try owner!.createDictationTranscriber() + _ = try await owner!.createDictationTranscriber() var detached: SpeechSession.DetachedTranscriberState? = owner!.detachTranscriberState() try await owner!.configureCustomVocabulary(nil) owner = nil @@ -159,14 +160,14 @@ struct CustomVocabularyOwnershipTests { #expect(!FileManager.default.fileExists(atPath: directory.path)) } - private func assertFiles(in directory: URL) throws { + func assertFiles(in directory: URL) throws { #expect(try Data(contentsOf: directory.appendingPathComponent("languageModel.bin")) == Data("model".utf8)) #expect(try Data(contentsOf: directory.appendingPathComponent("vocabulary.bin")) == Data("vocabulary".utf8)) } } /// Substitutes only Apple export/preparation, keeping production allocation and configuration. -private actor VocabularyPreparation { +actor VocabularyPreparation { enum Failure: Error { case expected } nonisolated let ready = AsyncStream.makeStream() nonisolated let release = AsyncStream.makeStream() diff --git a/Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift b/Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift new file mode 100644 index 0000000..3450de6 --- /dev/null +++ b/Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift @@ -0,0 +1,83 @@ +import Foundation +import Testing +@testable import AuralKit + +extension CustomVocabularyOwnershipTests { + @Test("Already-cancelled configuration leaves the pending request intact") + func cancelledRequestDoesNotSupersede() async throws { + let preparation = VocabularyPreparation() + let session = session(preparation) + let pending = Task { @MainActor in + defer { preparation.ready.continuation.finish() } + try await session.configureCustomVocabulary(descriptor("blocked")) + } + var ready = preparation.ready.stream.makeAsyncIterator() + #expect(await ready.next() != nil) + let cancelled = Task { @MainActor in + try await session.configureCustomVocabulary(descriptor("replacement")) + } + cancelled.cancel() + let cancelledResult = await cancelled.result + preparation.release.continuation.finish() + let pendingResult = await pending.result + do { + try cancelledResult.get() + Issue.record("Expected cancellation") + } catch is CancellationError { } + try pendingResult.get() + #expect(session.customVocabularyDescriptor?.version == "blocked") + } + + @Test("Caller cancellation takes precedence over a joined compiler failure") + func cancellationAfterCompilerFailure() async throws { + let session = SpeechSession(locale: Locale(identifier: "en_US")) + let compiler = CancellingVocabularyCompiler() + session.customVocabularyCompiler = compiler + let start = AsyncStream.makeStream() + let request = Task { @MainActor in + for await _ in start.stream { break } + try await session.configureCustomVocabulary(descriptor()) + } + await compiler.cancelOnFailure(request) + start.continuation.finish() + do { + try await request.value + Issue.record("Expected cancellation") + } catch is CancellationError { } + #expect(session.customVocabularyConfiguration == nil) + } + + enum Reuse: Sendable, CaseIterable { case configure, dictation } + + @Test("Purged files are rebuilt before configuration reuse or dictation", arguments: Reuse.allCases) + func purgedFilesAreRebuilt(reuse: Reuse) async throws { + let preparation = VocabularyPreparation() + let session = session(preparation) + try await session.configureCustomVocabulary(descriptor()) + let purged = try #require(session.customVocabularyOutputDirectory) + try FileManager.default.removeItem(at: purged.appendingPathComponent("vocabulary.bin")) + switch reuse { + case .configure: + try await session.configureCustomVocabulary(descriptor()) + case .dictation: + _ = try await session.createDictationTranscriber() + } + let rebuilt = try #require(session.customVocabularyOutputDirectory) + #expect(await preparation.count == 2) + #expect(rebuilt != purged) + #expect(!FileManager.default.fileExists(atPath: purged.path)) + try assertFiles(in: rebuilt) + } +} + +private actor CancellingVocabularyCompiler: CustomVocabularyCompiling { + private var request: Task? + + func cancelOnFailure(_ request: Task) { self.request = request } + + func compile(descriptor: SpeechSession.CustomVocabulary) async throws -> CustomVocabularyCompilation { + request?.cancel() + request = nil + throw VocabularyPreparation.Failure.expected + } +} From 59ec8f233e9ab0f21dbc444731e322e3ba00570c Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:16:54 +0530 Subject: [PATCH 30/70] fix: rebuild purged vocabulary before dictation and fence cancellation --- ...ession+CustomVocabularyConfiguration.swift | 36 +++++++++++++------ Sources/AuralKit/SpeechSession+Pipeline.swift | 9 +++-- .../AuralKit/SpeechSession+Transcriber.swift | 31 +++++++++++----- Tests/AuralKitTests/AuralKitTests.swift | 2 ++ 4 files changed, 55 insertions(+), 23 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift index f749abd..4513902 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift @@ -8,7 +8,7 @@ extension SpeechSession { /// Configure the session's custom vocabulary, compiling assets as needed. /// - /// Compiled files are temporary and remain available while the session or a native consumer uses them. + /// Compiled files are temporary and are rebuilt before reuse if the system purges them. /// Cancelling compilation waits for preparation to finish, then throws `CancellationError` /// without replacing the current configuration. Superseded compilation results are discarded. /// @@ -17,6 +17,7 @@ extension SpeechSession { /// - Throws: A `SpeechSessionError` when the session is active, the descriptor locale mismatches, or /// compilation fails. public func configureCustomVocabulary(_ vocabulary: CustomVocabulary?) async throws { + try Task.checkCancellation() if streamingMode != .inactive || continuation != nil || pipelineTask != nil || recognizerTask != nil { throw SpeechSessionError.customVocabularyRequiresIdleSession } @@ -39,35 +40,50 @@ extension SpeechSession { throw SpeechSessionError.customVocabularyCompilationFailed(error) } + try Task.checkCancellation() let requestID = UUID() customVocabularyRequestID = requestID - try Task.checkCancellation() if cacheKey == customVocabularyCacheKey, - customVocabularyConfiguration != nil { + customVocabularyFilesExist { customVocabularyDescriptor = vocabulary return } + let compilation = try await compileCustomVocabulary(vocabulary) + try Task.checkCancellation() + guard customVocabularyRequestID == requestID else { throw CancellationError() } + guard streamingMode == .inactive, continuation == nil, pipelineTask == nil, recognizerTask == nil else { + throw SpeechSessionError.customVocabularyRequiresIdleSession + } + applyCustomVocabularyCompilation(compilation, descriptor: vocabulary) + } + + var customVocabularyFilesExist: Bool { + guard let configuration = customVocabularyConfiguration else { return false } + let paths = [configuration.languageModel, configuration.vocabulary].compactMap { $0 } + return paths.allSatisfy { FileManager.default.isReadableFile(atPath: $0.path) } + } + + func compileCustomVocabulary(_ vocabulary: CustomVocabulary) async throws -> CustomVocabularyCompilation { // Offload compilation to background task to avoid blocking main actor UI // Capture compiler before detached task to avoid cross-actor access let compiler = customVocabularyCompiler let task = Task.detached(priority: .userInitiated) { try await compiler.compile(descriptor: vocabulary) } - let compilation = try await withTaskCancellationHandler { - try await task.value + let result = await withTaskCancellationHandler { + await task.result } onCancel: { task.cancel() } // Rejected results release their private artifacts after the compiler has joined. try Task.checkCancellation() - guard customVocabularyRequestID == requestID else { throw CancellationError() } - guard streamingMode == .inactive, continuation == nil, pipelineTask == nil, recognizerTask == nil else { - throw SpeechSessionError.customVocabularyRequiresIdleSession - } + return try result.get() + } - customVocabularyDescriptor = vocabulary + func applyCustomVocabularyCompilation(_ compilation: CustomVocabularyCompilation, descriptor: CustomVocabulary) { + customVocabularyDescriptor = descriptor customVocabularyConfiguration = compilation.configuration customVocabularyCacheKey = compilation.cacheKey customVocabularyOutputDirectory = compilation.outputDirectory diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index b3838f2..2bd421f 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -156,8 +156,6 @@ extension SpeechSession { contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, generation: Int ) async { - let vocabularyArtifacts = customVocabularyArtifacts - defer { withExtendedLifetime(vocabularyArtifacts) {} } do { if Self.shouldLog(.notice) { Self.logger.notice("Starting dictation pipeline setup") @@ -169,18 +167,19 @@ extension SpeechSession { try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider - let transcriber = try await setUpDictationTranscriber( + let prepared = try await setUpDictationTranscriber( contextualStrings: contextualStrings, startAnalyzerImmediately: !shouldUseNativeCapture ) + defer { withExtendedLifetime(prepared.artifacts) {} } try Task.checkCancellation() if Self.shouldLog(.info) { Self.logger.info("Dictation transcriber prepared with modules") } recognizerTask = createDictationRecognizerTask( - transcriber: transcriber, - vocabularyArtifacts: vocabularyArtifacts, + transcriber: prepared.transcriber, + vocabularyArtifacts: prepared.artifacts, streamContinuation: streamContinuation, generation: generation ) diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index 3db1ac6..460ddcf 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -13,6 +13,8 @@ extension SpeechSession { // MARK: - Transcriber Setup and Cleanup + typealias PreparedDictation = (transcriber: DictationTranscriber, artifacts: CustomVocabularyArtifacts?) + func setUpSpeechTranscriber( contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, startAnalyzerImmediately: Bool = true @@ -37,15 +39,17 @@ extension SpeechSession { func setUpDictationTranscriber( contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, startAnalyzerImmediately: Bool = true - ) async throws -> DictationTranscriber { - let artifacts = customVocabularyArtifacts - defer { withExtendedLifetime(artifacts) {} } + ) async throws -> PreparedDictation { if Self.shouldLog(.notice) { Self.logger.notice("Setting up dictation transcriber") } - let transcriber = try createDictationTranscriber() - let modules = configureModules(transcriber: transcriber) + let generation = sessionGeneration + let prepared = try await createDictationTranscriber() + defer { withExtendedLifetime(prepared.artifacts) {} } + try Task.checkCancellation() + guard generation == sessionGeneration else { throw CancellationError() } + let modules = configureModules(transcriber: prepared.transcriber) try await ensureModels(modules: modules) try Task.checkCancellation() try await configureAnalyzerContext(contextualStrings: contextualStrings) @@ -54,7 +58,7 @@ extension SpeechSession { try await startAnalyzer(modules: modules) } - return transcriber + return prepared } private func createSpeechTranscriber() throws -> SpeechTranscriber { @@ -76,7 +80,18 @@ extension SpeechSession { return transcriber } - func createDictationTranscriber() throws -> DictationTranscriber { + func createDictationTranscriber() async throws -> PreparedDictation { + if let descriptor = customVocabularyDescriptor, !customVocabularyFilesExist { + let generation = sessionGeneration + let requestID = customVocabularyRequestID + let compilation = try await compileCustomVocabulary(descriptor) + try Task.checkCancellation() + guard generation == sessionGeneration, requestID == customVocabularyRequestID else { + throw CancellationError() + } + applyCustomVocabularyCompilation(compilation, descriptor: descriptor) + } + try Task.checkCancellation() let basePreset = DictationTranscriber.Preset.progressiveShortDictation var contentHints = basePreset.contentHints var reportingOptions = basePreset.reportingOptions @@ -100,7 +115,7 @@ extension SpeechSession { throw SpeechSessionError.recognitionStreamSetupFailed } - return dictationTranscriber + return (dictationTranscriber, activeCustomVocabularyArtifacts) } @discardableResult diff --git a/Tests/AuralKitTests/AuralKitTests.swift b/Tests/AuralKitTests/AuralKitTests.swift index 1de3e00..7129d82 100644 --- a/Tests/AuralKitTests/AuralKitTests.swift +++ b/Tests/AuralKitTests/AuralKitTests.swift @@ -338,6 +338,8 @@ actor MockCustomVocabularyCompiler: CustomVocabularyCompiling { languageModel: outputDirectory.appendingPathComponent("languageModel.bin"), vocabulary: outputDirectory.appendingPathComponent("vocabulary.bin") ) + try Data().write(to: configuration.languageModel) + try Data().write(to: outputDirectory.appendingPathComponent("vocabulary.bin")) return CustomVocabularyCompilation( configuration: configuration, From d60d22bf40435f5c6011b8505e54af2d868111b0 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:17:50 +0530 Subject: [PATCH 31/70] Keep screen control handling in the screen capture extension --- .../SpeechSession+ScreenCapture.swift | 78 +++++++++++-------- Sources/AuralKit/SpeechSession.swift | 19 ++--- 2 files changed, 52 insertions(+), 45 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 478f651..a95b4df 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -5,6 +5,45 @@ import Speech // swiftlint:disable file_length +@MainActor +extension SpeechSession { + func resumeScreenCaptureStreamingIfNeeded(generation: Int) async throws { + guard generation == sessionGeneration, status == .paused, streamingMode == .screenCapture else { return } + var captureFailure: Error? + do { +#if canImport(ScreenCaptureKit) + guard #available(iOS 27.0, macOS 14.0, *) else { + throw SpeechSessionError.screenCaptureUnavailable + } + guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + await provider.resume { result in + guard generation == self.sessionGeneration, + self.status == .paused, self.streamingMode == .screenCapture else { return } + switch result { + case .success: + self.setStatus(.transcribing) + case .failure(let error): + captureFailure = error + self.prepareForStop() + } + } + if let captureFailure { throw captureFailure } +#else + throw SpeechSessionError.screenCaptureUnavailable +#endif + } 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) + throw error + } + } +} + #if canImport(ScreenCaptureKit) @preconcurrency import ScreenCaptureKit @@ -152,32 +191,13 @@ extension SpeechSession { @MainActor extension SpeechSession { - func pauseScreenCaptureStreamingIfNeeded() async -> Bool { - guard #available(iOS 27.0, macOS 14.0, *) else { return false } - guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { return false } - return await provider.pause() - } - - func resumeScreenCaptureStreamingIfNeeded(generation: Int) async throws -> Error? { - guard #available(iOS 27.0, macOS 14.0, *) else { - throw SpeechSessionError.screenCaptureUnavailable - } - guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { - throw SpeechSessionError.recognitionStreamSetupFailed - } - var failure: Error? - await provider.resume { result in - guard generation == self.sessionGeneration, - self.status == .paused, self.streamingMode == .screenCapture else { return } - switch result { - case .success: - self.setStatus(.transcribing) - case .failure(let error): - failure = error - self.prepareForStop() - } - } - return failure + func pauseScreenCaptureStreamingIfNeeded(generation: Int) async { + guard generation == sessionGeneration else { return } + guard #available(iOS 27.0, macOS 14.0, *) else { return } + guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { return } + guard await provider.pause(), generation == sessionGeneration, + status == .transcribing, streamingMode == .screenCapture else { return } + setStatus(.paused) } func stopScreenCaptureStreamingIfNeeded() async { @@ -461,11 +481,7 @@ public extension SpeechSession { @MainActor extension SpeechSession { - func pauseScreenCaptureStreamingIfNeeded() async -> Bool { false } - - func resumeScreenCaptureStreamingIfNeeded(generation: Int) async throws -> Error? { - throw SpeechSessionError.screenCaptureUnavailable - } + func pauseScreenCaptureStreamingIfNeeded(generation: Int) async {} func stopScreenCaptureStreamingIfNeeded() async { screenCaptureInputProvider = nil diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index dbcc135..c81983a 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -361,13 +361,10 @@ public final class SpeechSession { /// screen capture). Calls during file transcription or in any other state are ignored. public func pauseTranscribing() async { guard status == .transcribing, isPausableStreamingMode else { return } - let generation = sessionGeneration if streamingMode == .screenCapture { - guard await pauseScreenCaptureStreamingIfNeeded() else { return } - } else { - stopAudioStreaming() + return await pauseScreenCaptureStreamingIfNeeded(generation: sessionGeneration) } - guard generation == sessionGeneration, status == .transcribing, isPausableStreamingMode else { return } + stopAudioStreaming() setStatus(.paused) } @@ -377,19 +374,13 @@ public final class SpeechSession { public func resumeTranscribing() async throws { guard status == .paused, isPausableStreamingMode else { return } let generation = sessionGeneration - var captureFailure: Error? + if streamingMode == .screenCapture { + return try await resumeScreenCaptureStreamingIfNeeded(generation: generation) + } do { - if streamingMode == .screenCapture { - captureFailure = try await resumeScreenCaptureStreamingIfNeeded(generation: generation) - if let captureFailure { throw captureFailure } - return - } try startAudioStreaming() - guard generation == sessionGeneration, status == .paused, isPausableStreamingMode else { return } setStatus(.transcribing) } catch { - let canFinish = status == .paused || (captureFailure != nil && status == .stopping) - guard generation == sessionGeneration, canFinish, isPausableStreamingMode else { throw error } prepareForStop() await cleanup(cancelRecognizer: true, generation: generation) await finishStream(error: error, generation: generation) From da83140a0346d0220759fb13c5b81764a3d935f8 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 01:27:34 +0530 Subject: [PATCH 32/70] Reject canceled and retired queued asset requests --- Sources/AuralKit/ModelManager.swift | 16 +++++++-- .../AuralKit/SpeechAssetReservations.swift | 13 ++++++-- .../SpeechAssetReservationTests.swift | 33 +++++++++++++++++++ 3 files changed, 58 insertions(+), 4 deletions(-) diff --git a/Sources/AuralKit/ModelManager.swift b/Sources/AuralKit/ModelManager.swift index 93c2b4a..4f29f20 100644 --- a/Sources/AuralKit/ModelManager.swift +++ b/Sources/AuralKit/ModelManager.swift @@ -12,15 +12,20 @@ actor ModelManager { private let reservations: SpeechAssetReservations private let assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? + private let installationRequest: @Sendable ([any SpeechModule]) async throws -> AssetInstallationRequest? private var leases: Set = [] private var generation = 0 init( reservations: SpeechAssetReservations = .shared, - assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? = nil + assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? = nil, + installationRequest: @escaping @Sendable ([any SpeechModule]) async throws -> AssetInstallationRequest? = { + try await AssetInventory.assetInstallationRequest(supporting: $0) + } ) { self.reservations = reservations self.assetDownloader = assetDownloader + self.installationRequest = installationRequest } /// Ensure the speech model for the given locale is available @@ -94,7 +99,7 @@ actor ModelManager { return } let request = try await reservations.withInventoryAccess { - try await AssetInventory.assetInstallationRequest(supporting: modules) + try await self.requestInstallation(for: modules, generation: generation) } if let downloader = request { try requireCurrent(generation) @@ -125,6 +130,13 @@ actor ModelManager { } } + private func requestInstallation( + for modules: [any SpeechModule], generation: Int + ) async throws -> AssetInstallationRequest? { + try requireCurrent(generation) + return try await installationRequest(modules) + } + /// Retire pending preparation without waiting for a native download to finish. func releaseLocales() async { generation &+= 1 diff --git a/Sources/AuralKit/SpeechAssetReservations.swift b/Sources/AuralKit/SpeechAssetReservations.swift index 059fdad..16a8b3e 100644 --- a/Sources/AuralKit/SpeechAssetReservations.swift +++ b/Sources/AuralKit/SpeechAssetReservations.swift @@ -34,7 +34,7 @@ actor SpeechAssetReservations { private var reservations: [String: Locale] = [:] private var leases: Set = [] private var tail: Task? - private var queuedOperations = 0 + private(set) var queuedOperations = 0 init(inventory: Inventory = .live) { self.inventory = inventory @@ -63,7 +63,16 @@ actor SpeechAssetReservations { func withInventoryAccess( _ operation: @escaping @Sendable () async throws -> Value ) async throws -> Value { - try await enqueue(operation).value + try Task.checkCancellation() + let task = enqueue { + try Task.checkCancellation() + return try await operation() + } + return try await withTaskCancellationHandler { + try await task.value + } onCancel: { + task.cancel() + } } private func enqueue( diff --git a/Tests/AuralKitTests/SpeechAssetReservationTests.swift b/Tests/AuralKitTests/SpeechAssetReservationTests.swift index ef3fa9c..d402b1a 100644 --- a/Tests/AuralKitTests/SpeechAssetReservationTests.swift +++ b/Tests/AuralKitTests/SpeechAssetReservationTests.swift @@ -102,6 +102,39 @@ struct SpeechAssetReservationTests { #expect(await inventory.snapshot.locales.isEmpty) } + @Test("canceled or retired installation work cannot reserve a locale", arguments: [true, false]) + func canceledQueuedInstallation(cancel: Bool) async throws { + let inventory = AssetInventoryProbe() + let native = inventory.client + let reservations = SpeechAssetReservations(inventory: native) + let blockerGate = AssetGate() + let blocker = Task { + try await reservations.withInventoryAccess { await blockerGate.wait() } + } + await blockerGate.waitForEntry() + let manager = ModelManager(reservations: reservations, installationRequest: { _ in + _ = try await native.reserve(Locale(identifier: "en-US")) + return nil + }) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let preparation = Task { try await manager.ensureAssets(for: [module]) } + let deadline = ContinuousClock.now + .seconds(1) + while await reservations.queuedOperations < 2, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(1)) + } + #expect(await reservations.queuedOperations == 2) + if cancel { preparation.cancel() } else { await manager.releaseLocales() } + await blockerGate.open() + try await blocker.value + if case .success = await preparation.result { Issue.record("Retired preparation succeeded") } + await manager.releaseLocales() + #expect(await inventory.snapshot.locales.isEmpty) + let successor = ModelManager(reservations: reservations, assetDownloader: { _ in }) + try await successor.ensureAssets(for: [module]) + await successor.releaseLocales() + #expect(await inventory.snapshot.locales.isEmpty) + } + @Test("implicit installation reservations cannot invalidate an explicit acquisition") func concurrentInstallationRequest() async throws { let inventory = AssetInventoryProbe() From d32cf24da0ae36400bc9c42155585bb9cc268f7c Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 14:53:32 +0530 Subject: [PATCH 33/70] Move AuralKit CI to GitHub Actions --- .github/workflows/ci.yml | 37 +++++++++++++++++++++++++++++++++++++ Agents.md | 2 +- README.md | 2 +- codemagic.yaml | 40 ---------------------------------------- 4 files changed, 39 insertions(+), 42 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 codemagic.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..eb70981 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build-and-test: + name: Build and test + runs-on: xcode-27 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Show toolchain + run: | + xcodebuild -version + swift --version + - name: Lint Swift + run: | + brew install swiftlint + swiftlint lint --strict + - name: Build and test Swift package + run: | + swift build + swift test + - name: Build macOS demo + run: xcodebuild -project Aural.xcodeproj -scheme Aural -destination 'platform=macOS' CODE_SIGNING_ALLOWED=NO build + - name: Build iOS Simulator demo + run: xcodebuild -project Aural.xcodeproj -scheme Aural -destination 'generic/platform=iOS Simulator' CODE_SIGNING_ALLOWED=NO build diff --git a/Agents.md b/Agents.md index 8f1be50..5634d6f 100644 --- a/Agents.md +++ b/Agents.md @@ -145,6 +145,6 @@ Before opening a PR (or completing an automated change): - Minimal transcription example lives in `Aural/TranscriptionView.swift`. - Advanced transcription UI lives in `Aural/AdvancedTranscriptionView.swift`. - Error cases and localized descriptions are centralized in `Sources/AuralKit/SpeechSessionError.swift`. -- CI uses Codemagic (`codemagic.yaml`); green builds are required before merging. +- CI uses GitHub Actions (`.github/workflows/ci.yml`). The Build and test job must pass before merging. Happy transcribing! diff --git a/README.md b/README.md index 69f75e0..4359c19 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Swift Package Manager](https://img.shields.io/badge/SPM-compatible-brightgreen.svg)](https://swift.org/package-manager) [![GitHub release](https://img.shields.io/github/release/rryam/AuralKit.svg)](https://github.com/rryam/AuralKit/releases) -[![Codemagic build status](https://api.codemagic.io/apps/6858c0b3eab03a007ef8b1f6/auralkit/status_badge.svg)](https://codemagic.io/app/6858c0b3eab03a007ef8b1f6/auralkit/latest_build) +[![CI](https://github.com/rryam/AuralKit/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/rryam/AuralKit/actions/workflows/ci.yml) AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription using iOS 26's `SpeechTranscriber` and `SpeechAnalyzer` APIs while handling microphone capture, buffer conversion, model downloads, and cancellation on your behalf. diff --git a/codemagic.yaml b/codemagic.yaml deleted file mode 100644 index 3a752db..0000000 --- a/codemagic.yaml +++ /dev/null @@ -1,40 +0,0 @@ -definitions: - triggering: - push: &events - events: - - push - - pull_request - -workflows: - auralkit: - name: AuralKit Workflow - environment: - xcode: edge - vars: - XCODE_SCHEME: "AuralKit" - APP_ID: "AuralKit" - when: - changeset: - includes: - - "Sources" - - "Tests" - - "Aural" - - "Package.swift" - triggering: - <<: *events - scripts: - - name: Download Metal Toolchain - script: | - xcodebuild -downloadComponent MetalToolchain - - name: Install SwiftLint - script: | - brew install swiftlint - - name: Run SwiftLint - script: | - swiftlint --strict - - name: Build Swift Package - script: | - swift build - - name: Build Aural App - script: | - xcodebuild -scheme Aural -configuration Debug -destination "platform=iOS Simulator,name=iPhone 17 Pro" build From c3490d20be5e83acd8f1f7b24d09a747a6f44c2e Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 15:19:24 +0530 Subject: [PATCH 34/70] Update existing capture filters and preserve terminal stream errors --- .../AuralKit/ScreenCaptureTransitions.swift | 38 ++++- .../SpeechSession+ScreenCapture.swift | 74 +++++---- .../ScreenCaptureTestFixtures.swift | 5 +- .../ScreenCaptureTransitionTests.swift | 9 +- .../ScreenCaptureUpdateTests.swift | 153 ++++++++++++++++++ 5 files changed, 245 insertions(+), 34 deletions(-) create mode 100644 Tests/AuralKitTests/ScreenCaptureUpdateTests.swift diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index 1522241..54c72a1 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -17,6 +17,8 @@ final class ScreenCaptureTransitions { private(set) var stream: (any ScreenCaptureStream)? private(set) var isRunning = false private var revision = UUID() + private var streamRevision: UUID? + private var terminatedStream: ObjectIdentifier? private var controlRevision = UUID() private var tail: Task? @@ -31,6 +33,8 @@ final class ScreenCaptureTransitions { try await self.stopCurrent() guard self.desiredState != .stopped, self.revision == admitted else { return } self.stream = try makeStream() + self.streamRevision = admitted + self.terminatedStream = nil try await self.startCurrent(revision: admitted) } catch { // A stale picker operation must not report failure against its successor. @@ -40,6 +44,33 @@ final class ScreenCaptureTransitions { } } + func update( + _ expectedStream: any ScreenCaptureStream, + operation: @escaping @MainActor () async throws -> Void + ) -> Task { + let admitted = revision + return enqueue { + guard self.desiredState != .stopped, self.revision == admitted, + self.stream === expectedStream else { return } + do { + try await operation() + } catch { + guard self.desiredState != .stopped, self.revision == admitted else { return } + throw error + } + } + } + + func didStop(_ expectedStream: any ScreenCaptureStream) -> Bool { + guard stream === expectedStream else { return false } + terminatedStream = ObjectIdentifier(expectedStream) + isRunning = false + guard desiredState != .stopped, streamRevision == revision else { return false } + controlRevision = UUID() + desiredState = .stopped + return true + } + func pause() -> Task { guard desiredState != .stopped else { return enqueue {} } let control = UUID() @@ -103,13 +134,18 @@ final class ScreenCaptureTransitions { private func stopCurrent() async throws { guard isRunning, let stream else { return } - try await stream.stopCapture() + do { + try await stream.stopCapture() + } catch { + guard terminatedStream == ObjectIdentifier(stream) else { throw error } + } isRunning = false } private func startCurrent(revision admitted: UUID) async throws { guard desiredState == .running, revision == admitted, !isRunning, let stream else { return } try await stream.startCapture() + guard terminatedStream != ObjectIdentifier(stream) else { return } // Nothing else can perform capture calls until this operation exits. Intent can // still change during start; compensate before allowing a queued operation to run. isRunning = true diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index a95b4df..79b508c 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -178,7 +178,7 @@ extension SpeechSession { options: options, targetFormat: analyzerFormat, inputContinuation: inputBuilder, - onFailure: { [weak self] error in + onTermination: { [weak self] error in Task { @MainActor [weak self] in await self?.finishFromRecognizerTask(error: error, generation: generation) } @@ -221,16 +221,13 @@ extension SpeechSession { @MainActor private final class NativeScreenCaptureStream: ScreenCaptureStream { let stream: SCStream - let willStop: @MainActor (SCStream) -> Void - init(stream: SCStream, willStop: @escaping @MainActor (SCStream) -> Void) { + init(stream: SCStream) { self.stream = stream - self.willStop = willStop } func startCapture() async throws { try await stream.startCapture() } func stopCapture() async throws { - willStop(stream) try await stream.stopCapture() } } @@ -242,7 +239,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD private let options: SpeechSession.ScreenCaptureTranscriptionOptions private let targetFormat: AVAudioFormat private let inputContinuation: AsyncStream.Continuation - private let onFailure: @Sendable (Error) -> Void + private let onTermination: @Sendable (Error?) -> Void private let sampleQueue = DispatchQueue(label: "com.auralkit.screencapture.audio", qos: .userInitiated) // Only touched on `sampleQueue`, which serializes access. private let bufferConverter = BufferConverter() @@ -252,14 +249,13 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD private var selectionContinuation: CheckedContinuation? private var stopped = false private var pickerUpdateID: UUID? - private var intentionallyStoppingStreams = Set() @MainActor init( options: SpeechSession.ScreenCaptureTranscriptionOptions, targetFormat: AVAudioFormat, inputContinuation: AsyncStream.Continuation, - onFailure: @escaping @Sendable (Error) -> Void, + onTermination: @escaping @Sendable (Error?) -> Void, transitions: ScreenCaptureTransitions = ScreenCaptureTransitions(), dismissPicker: @escaping @MainActor (any SCContentSharingPickerObserver) -> Void = { observer in let picker = SCContentSharingPicker.shared @@ -270,7 +266,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD self.options = options self.targetFormat = targetFormat self.inputContinuation = inputContinuation - self.onFailure = onFailure + self.onTermination = onTermination self.transitions = transitions self.dismissPicker = dismissPicker super.init() @@ -298,7 +294,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD func pause() async -> Bool { do { try await transitions.pause().value - return true + return transitions.desiredState == .paused } catch { return false } @@ -327,7 +323,12 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD Task { @MainActor [weak self] in guard let self, !self.stopped else { return } if let updatedStream { - guard (self.transitions.stream as? NativeScreenCaptureStream)?.stream === updatedStream else { return } + guard let current = self.transitions.stream as? NativeScreenCaptureStream, + current.stream === updatedStream else { return } +#if os(macOS) || targetEnvironment(macCatalyst) + self.updateStream(current) { try await updatedStream.updateContentFilter(selectedFilter) } + return +#endif } self.selectStream { [self] in let configuration = SCStreamConfiguration() @@ -339,9 +340,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: sampleQueue) - return NativeScreenCaptureStream(stream: capture) { [weak self] stream in - self?.markStreamForIntentionalStop(stream) - } + return NativeScreenCaptureStream(stream: capture) } } } @@ -357,16 +356,16 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD guard let self else { return } let wrappedError = SpeechSessionError.screenCaptureFailed(error) if !self.resumeSelection(throwing: wrappedError) { - self.onFailure(wrappedError) + self.onTermination(wrappedError) } } } func stream(_ stream: SCStream, didStopWithError error: any Error) { Task { @MainActor [weak self] in - guard let self, !self.stopped, !self.consumeIntentionalStop(for: stream), - (self.transitions.stream as? NativeScreenCaptureStream)?.stream === stream else { return } - self.onFailure(SpeechSessionError.screenCaptureFailed(error)) + guard let self, let current = self.transitions.stream as? NativeScreenCaptureStream, + current.stream === stream else { return } + self.streamDidStop(current, error: error) } } @@ -382,14 +381,14 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD ) else { return } guard let bufferCopy = sourceBuffer.copy() as? AVAudioPCMBuffer else { - onFailure(SpeechSessionError.conversionBufferCreationFailed) + onTermination(SpeechSessionError.conversionBufferCreationFailed) return } processAudioBuffer(bufferCopy) } } catch { - onFailure(SpeechSessionError.screenCaptureFailed(error)) + onTermination(SpeechSessionError.screenCaptureFailed(error)) } } @@ -397,7 +396,21 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD @MainActor func selectStream(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) -> Task { guard !stopped else { return Task {} } - let operation = transitions.replace(makeStream: makeStream) + return observeSelection(transitions.replace(makeStream: makeStream)) + } + + @discardableResult + @MainActor + func updateStream( + _ stream: any ScreenCaptureStream, + operation: @escaping @MainActor () async throws -> Void + ) -> Task { + guard !stopped else { return Task {} } + return observeSelection(transitions.update(stream, operation: operation)) + } + + @MainActor + private func observeSelection(_ operation: Task) -> Task { let id = UUID() pickerUpdateID = id return Task { @MainActor in @@ -408,7 +421,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } catch { guard !self.stopped, self.pickerUpdateID == id else { return } if !self.resumeSelection(throwing: error) { - self.onFailure(SpeechSessionError.screenCaptureFailed(error)) + self.onTermination(SpeechSessionError.screenCaptureFailed(error)) } } } @@ -445,18 +458,19 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD let converted = try bufferConverter.convertBuffer(buffer, to: targetFormat) inputContinuation.yield(AnalyzerInput(buffer: converted)) } catch { - onFailure(error) + onTermination(error) } } @MainActor - private func markStreamForIntentionalStop(_ stream: SCStream) { - intentionallyStoppingStreams.insert(ObjectIdentifier(stream)) - } - - @MainActor - private func consumeIntentionalStop(for stream: SCStream) -> Bool { - intentionallyStoppingStreams.remove(ObjectIdentifier(stream)) != nil + func streamDidStop(_ stream: any ScreenCaptureStream, error: Error) { + let isCurrent = transitions.didStop(stream) + guard !stopped, isCurrent else { return } + stopped = true + let nativeError = error as NSError + let userStopped = nativeError.domain == SCStreamError.errorDomain + && nativeError.code == SCStreamError.Code.userStopped.rawValue + onTermination(userStopped ? nil : SpeechSessionError.screenCaptureFailed(error)) } } #else diff --git a/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift index 7241228..1c1e489 100644 --- a/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift +++ b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift @@ -63,24 +63,27 @@ final class ControlledCaptureStream: ScreenCaptureStream { var starts = 0 var stops = 0 var capturing = false + var terminated = false var startEntered: CaptureGate? var startRelease: CaptureGate? var stopEntered: CaptureGate? var stopRelease: CaptureGate? var startError: Error? var stopError: Error? + var onStop: (@MainActor () -> Void)? func startCapture() async throws { starts += 1 startEntered?.open() try await startRelease?.wait() if let startError { throw startError } - capturing = true + capturing = !terminated } func stopCapture() async throws { stops += 1 stopEntered?.open() try await stopRelease?.wait() + onStop?() if let stopError { throw stopError } capturing = false } diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index ef783dc..cb575c2 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -6,7 +6,7 @@ import Testing @available(iOS 27.0, macOS 26.0, *) @MainActor -private final class CaptureSessionFixture { +final class CaptureSessionFixture { let session = SpeechSession() let owner = ScreenCaptureTransitions() let provider: ScreenCaptureAudioInputProvider @@ -16,9 +16,14 @@ private final class CaptureSessionFixture { dismissed = fixture.gate() let (_, inputs) = AsyncStream.makeStream() let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) + let generation = session.sessionGeneration provider = ScreenCaptureAudioInputProvider( options: .init(), targetFormat: format, inputContinuation: inputs, - onFailure: { error in Issue.record(error) }, transitions: owner, + onTermination: { [session] error in + Task { @MainActor in + await session.finishFromRecognizerTask(error: error, generation: generation) + } + }, transitions: owner, dismissPicker: { [dismissed] _ in dismissed.open() } ) session.screenCaptureInputProvider = provider diff --git a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift new file mode 100644 index 0000000..361f0b6 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift @@ -0,0 +1,153 @@ +#if canImport(ScreenCaptureKit) +import ScreenCaptureKit +import Speech +import Testing +@testable import AuralKit + +@Suite("Screen capture updates and termination") +struct ScreenCaptureUpdateTests { + @Test("Repeated filter updates retain the selected stream", arguments: [false, true]) + @MainActor + func repeatedUpdates(paused: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { stream }).value + if paused { await runtime.session.pauseTranscribing() } + var filters: [Int] = [] + for filter in [1, 2] { + await fixture.track(runtime.provider.updateStream(stream) { filters.append(filter) }).value + } + #expect(filters == [1, 2] && runtime.owner.stream === stream) + #expect(stream.starts == 1 && stream.stops == (paused ? 1 : 0)) + #expect(stream.capturing == !paused) + #expect(runtime.session.status == (paused ? .paused : .transcribing)) + if paused { try await runtime.session.resumeTranscribing() } + let successor = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { successor }).value + await fixture.track(runtime.provider.updateStream(stream) { filters.append(3) }).value + runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) + #expect(filters == [1, 2] && successor.capturing) + #expect(runtime.session.status == .transcribing) + await runtime.close(fixture) + } + } + + @Test("Filter updates serialize with pending start and pause or stop", arguments: [false, true]) + @MainActor + func updateDuringStart(stop: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + let started = fixture.gate(), startRelease = fixture.gate() + let updating = fixture.gate(), updateRelease = fixture.gate() + stream.startEntered = started; stream.startRelease = startRelease + let selection = fixture.track(runtime.provider.selectStream { stream }) + try await started.wait() + var updates = 0 + let update = fixture.track(runtime.provider.updateStream(stream) { + updates += 1; updating.open(); try await updateRelease.wait() + }) + startRelease.open() + 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() } + }) + try await waitForCaptureState { runtime.owner.desiredState == (stop ? .stopped : .paused) } + let later = fixture.track(runtime.provider.updateStream(stream) { updates += 1 }) + updateRelease.open() + await selection.value; await update.value; await control.value; await later.value + #expect(updates == (stop ? 1 : 2)) + #expect(!stream.capturing && stream.stops == 1) + #expect(runtime.session.status == (stop ? .idle : .paused)) + await runtime.close(fixture) + } + } + + @Test("An obsolete filter failure does not terminate its replacement") + @MainActor + func supersededUpdateFailure() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), successor = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { old }).value + let updating = fixture.gate(), release = fixture.gate() + let update = fixture.track(runtime.provider.updateStream(old) { + updating.open(); try await release.wait(); throw CaptureFixtureError.startFailed + }) + try await updating.wait() + let replacement = fixture.track(runtime.provider.selectStream { successor }) + runtime.provider.streamDidStop(old, error: CaptureFixtureError.startFailed) + old.terminated = true; old.capturing = false + release.open() + await update.value; await replacement.value + #expect(successor.capturing && runtime.session.status == .transcribing) + await runtime.close(fixture) + } + } + + @Test("Terminal delegate errors survive a failed pause", arguments: [false, true]) + @MainActor + func failedPauseWithTerminalEvent(duringStop: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + await fixture.track(runtime.provider.selectStream { stream }).value + stream.stopError = CaptureFixtureError.startFailed + let terminate: @MainActor @Sendable () -> Void = { + stream.terminated = true; stream.capturing = false + runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) + } + if duringStop { stream.onStop = terminate } + await runtime.session.pauseTranscribing() + if !duringStop { + #expect(runtime.session.status == .transcribing && stream.capturing) + terminate() + } + await #expect(throws: SpeechSessionError.self) { + try await awaitResult(timeout: 3) { for try await _ in results {} } + } + #expect(runtime.session.status == .idle && !runtime.owner.isRunning) + #expect(stream.stops == 1) + } + } + + @Test("A terminal event during start cannot resurrect capture", arguments: [false, true]) + @MainActor + func terminalEventDuringStart(userStopped: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + let started = fixture.gate(), release = fixture.gate() + stream.startEntered = started; stream.startRelease = release + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + let selection = fixture.track(runtime.provider.selectStream { stream }) + try await started.wait() + stream.terminated = true + let error: Error = userStopped + ? NSError(domain: SCStreamError.errorDomain, code: SCStreamError.Code.userStopped.rawValue) + : CaptureFixtureError.startFailed + runtime.provider.streamDidStop(stream, error: error) + release.open() + await selection.value + do { + try await awaitResult(timeout: 3) { for try await _ in results {} } + #expect(userStopped) + } catch is SpeechSessionError { + #expect(!userStopped) + } + #expect(runtime.session.status == .idle && !runtime.owner.isRunning) + #expect(!stream.capturing && stream.stops == 0) + } + } +} +#endif From c4286dfca4d65abe958f37e5861e374a247bb2c1 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 15:21:51 +0530 Subject: [PATCH 35/70] Reproduce filter updates suppressing capture startup failures --- .../ScreenCaptureUpdateTests.swift | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift index 361f0b6..5476197 100644 --- a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift @@ -6,6 +6,32 @@ import Testing @Suite("Screen capture updates and termination") struct ScreenCaptureUpdateTests { + @Test("Filter updates cannot hide a pending start failure", arguments: [false, true]) + @MainActor + func updateDuringFailedStart(staleUpdate: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), pending = ControlledCaptureStream() + if staleUpdate { await fixture.track(runtime.provider.selectStream { old }).value } + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + let started = fixture.gate(), release = fixture.gate() + pending.startEntered = started; pending.startRelease = release + pending.startError = CaptureFixtureError.startFailed + let selection = fixture.track(runtime.provider.selectStream { pending }) + try await started.wait() + let update = fixture.track(runtime.provider.updateStream(staleUpdate ? old : pending) {}) + release.open() + await selection.value; await update.value + await #expect(throws: SpeechSessionError.self) { + try await awaitResult(timeout: 1) { for try await _ in results {} } + } + #expect(runtime.session.status == .idle && !pending.capturing) + await runtime.close(fixture) + } + } + @Test("Repeated filter updates retain the selected stream", arguments: [false, true]) @MainActor func repeatedUpdates(paused: Bool) async throws { From 56875fe73948bb86afdae4a503bfee24dc822426 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 15:22:34 +0530 Subject: [PATCH 36/70] Separate filter updates from capture startup ownership --- Sources/AuralKit/ScreenCaptureTransitions.swift | 6 +++++- .../AuralKit/SpeechSession+ScreenCapture.swift | 15 +++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index 54c72a1..65fca66 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -61,11 +61,15 @@ final class ScreenCaptureTransitions { } } + func isCurrent(_ expectedStream: any ScreenCaptureStream) -> Bool { + desiredState != .stopped && stream === expectedStream && streamRevision == revision + } + func didStop(_ expectedStream: any ScreenCaptureStream) -> Bool { guard stream === expectedStream else { return false } terminatedStream = ObjectIdentifier(expectedStream) isRunning = false - guard desiredState != .stopped, streamRevision == revision else { return false } + guard isCurrent(expectedStream) else { return false } controlRevision = UUID() desiredState = .stopped return true diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 79b508c..2d7341d 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -249,6 +249,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD private var selectionContinuation: CheckedContinuation? private var stopped = false private var pickerUpdateID: UUID? + private var filterUpdateID: UUID? @MainActor init( @@ -405,8 +406,18 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD _ stream: any ScreenCaptureStream, operation: @escaping @MainActor () async throws -> Void ) -> Task { - guard !stopped else { return Task {} } - return observeSelection(transitions.update(stream, operation: operation)) + guard !stopped, transitions.isCurrent(stream) else { return Task {} } + let update = transitions.update(stream, operation: operation) + let id = UUID() + filterUpdateID = id + return Task { @MainActor in + do { + try await update.value + } catch { + guard !self.stopped, self.filterUpdateID == id, self.transitions.isCurrent(stream) else { return } + self.onTermination(SpeechSessionError.screenCaptureFailed(error)) + } + } } @MainActor From 9798d77975742365721e8dc150e9a0e2a72a8666 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 15:36:35 +0530 Subject: [PATCH 37/70] Reproduce terminal errors lost by pending screen resume --- .../ScreenCaptureUpdateTests.swift | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift index 5476197..0115534 100644 --- a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift @@ -6,6 +6,37 @@ import Testing @Suite("Screen capture updates and termination") struct ScreenCaptureUpdateTests { + @Test("Terminal errors reach a pending resume unless explicit stop won", arguments: [false, true]) + @MainActor + func terminalErrorDuringResume(stopFirst: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { stream }).value + await runtime.session.pauseTranscribing() + let started = fixture.gate(), release = fixture.gate() + stream.startEntered = started; stream.startRelease = release + let resume = fixture.track(Task { try await runtime.session.resumeTranscribing() }) + try await started.wait() + if stopFirst { + fixture.track(Task { await runtime.session.stopTranscribing() }) + try await runtime.dismissed.wait() + } + stream.terminated = true + runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) + try await runtime.dismissed.wait() + release.open() + try await waitForCaptureState { runtime.session.status == .idle } + if stopFirst { + try await resume.value + } else { + await #expect(throws: SpeechSessionError.self) { try await resume.value } + } + #expect(!runtime.owner.isRunning && stream.stops == 1) + } + } + @Test("Filter updates cannot hide a pending start failure", arguments: [false, true]) @MainActor func updateDuringFailedStart(staleUpdate: Bool) async throws { From 592e24639605cc78214f642d548ba634ca9b20d7 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 15:37:18 +0530 Subject: [PATCH 38/70] Preserve terminal errors for the interrupted screen resume --- .../AuralKit/ScreenCaptureTransitions.swift | 20 +++++++++++++++---- .../SpeechSession+ScreenCapture.swift | 15 ++++++++------ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index 65fca66..1e0f080 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -12,6 +12,12 @@ protocol ScreenCaptureStream: AnyObject { @available(iOS 26.0, macOS 14.0, *) @MainActor final class ScreenCaptureTransitions { + private struct TerminalFailure { + let control: UUID + let error: Error + let operation: Task? + } + enum DesiredState { case running, paused, stopped } private(set) var desiredState = DesiredState.running private(set) var stream: (any ScreenCaptureStream)? @@ -21,6 +27,7 @@ final class ScreenCaptureTransitions { private var terminatedStream: ObjectIdentifier? private var controlRevision = UUID() private var tail: Task? + private var terminalFailure: TerminalFailure? // Synchronous admission returns the owned handle before any capture call can suspend. func replace(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) -> Task { @@ -65,11 +72,12 @@ final class ScreenCaptureTransitions { desiredState != .stopped && stream === expectedStream && streamRevision == revision } - func didStop(_ expectedStream: any ScreenCaptureStream) -> Bool { + func didStop(_ expectedStream: any ScreenCaptureStream, error: Error?) -> Bool { guard stream === expectedStream else { return false } terminatedStream = ObjectIdentifier(expectedStream) isRunning = false guard isCurrent(expectedStream) else { return false } + if let error { terminalFailure = TerminalFailure(control: controlRevision, error: error, operation: tail) } controlRevision = UUID() desiredState = .stopped return true @@ -92,7 +100,7 @@ final class ScreenCaptureTransitions { func resume( onCompletion: @escaping @MainActor (Result) -> Void - ) -> Task { + ) -> Task { let control = UUID() controlRevision = control desiredState = desiredState == .stopped ? .stopped : .running @@ -104,14 +112,18 @@ final class ScreenCaptureTransitions { var pending = operation while true { let result = await pending.result - guard self.desiredState == .running, self.controlRevision == control else { return } + if let terminal = self.terminalFailure, terminal.control == control { + _ = await terminal.operation?.result + return terminal.error + } + guard self.desiredState == .running, self.controlRevision == control else { return nil } if self.revision != selection, let successor = self.tail { selection = self.revision pending = successor continue } onCompletion(result) - return + return nil } } } diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 2d7341d..d0a2d86 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -10,6 +10,7 @@ extension SpeechSession { func resumeScreenCaptureStreamingIfNeeded(generation: Int) async throws { guard generation == sessionGeneration, status == .paused, streamingMode == .screenCapture else { return } var captureFailure: Error? + var terminalFailure: Error? do { #if canImport(ScreenCaptureKit) guard #available(iOS 27.0, macOS 14.0, *) else { @@ -18,7 +19,7 @@ extension SpeechSession { guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { throw SpeechSessionError.recognitionStreamSetupFailed } - await provider.resume { result in + terminalFailure = await provider.resume { result in guard generation == self.sessionGeneration, self.status == .paused, self.streamingMode == .screenCapture else { return } switch result { @@ -41,6 +42,7 @@ extension SpeechSession { await finishStream(error: error, generation: generation) throw error } + if let terminalFailure { throw terminalFailure } } } @@ -302,7 +304,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } @MainActor - func resume(onCompletion: @escaping @MainActor (Result) -> Void) async { + func resume(onCompletion: @escaping @MainActor (Result) -> Void) async -> Error? { await transitions.resume(onCompletion: onCompletion).value } @@ -475,13 +477,14 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD @MainActor func streamDidStop(_ stream: any ScreenCaptureStream, error: Error) { - let isCurrent = transitions.didStop(stream) - guard !stopped, isCurrent else { return } - stopped = true let nativeError = error as NSError let userStopped = nativeError.domain == SCStreamError.errorDomain && nativeError.code == SCStreamError.Code.userStopped.rawValue - onTermination(userStopped ? nil : SpeechSessionError.screenCaptureFailed(error)) + let failure: Error? = userStopped ? nil : SpeechSessionError.screenCaptureFailed(error) + let isCurrent = transitions.didStop(stream, error: failure) + guard !stopped, isCurrent else { return } + stopped = true + onTermination(failure) } } #else From f31d9c01e424331e7cecc172a9811d42fcee897f Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 15:42:49 +0530 Subject: [PATCH 39/70] Admit screen capture stop before awaiting cleanup --- Sources/AuralKit/SpeechSession+ScreenCapture.swift | 7 ++++--- Tests/AuralKitTests/ScreenCaptureUpdateTests.swift | 8 +++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index d0a2d86..82eda52 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -212,7 +212,7 @@ extension SpeechSession { screenCaptureInputProvider = nil guard #available(iOS 27.0, macOS 14.0, *) else { return } guard let provider = detachedProvider as? ScreenCaptureAudioInputProvider else { return } - let task = Task { await provider.stop() } + let task = provider.stop() screenCaptureStopTask = (generation, task) await task.value if screenCaptureStopTask?.generation == generation { screenCaptureStopTask = nil } @@ -309,11 +309,12 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } @MainActor - func stop() async { + func stop() -> Task { stopped = true + let operation = transitions.stop() dismissPicker(self) resumeSelection(throwing: SpeechSessionError.screenCaptureSelectionCancelled) - _ = try? await transitions.stop().value + return Task { _ = try? await operation.value } } func contentSharingPicker( diff --git a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift index 0115534..b59aa2e 100644 --- a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift @@ -21,10 +21,12 @@ struct ScreenCaptureUpdateTests { try await started.wait() if stopFirst { fixture.track(Task { await runtime.session.stopTranscribing() }) - try await runtime.dismissed.wait() } - stream.terminated = true - runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) + await fixture.track(Task { @MainActor in + if stopFirst { #expect(runtime.session.status == .stopping) } + stream.terminated = true + runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) + }).value try await runtime.dismissed.wait() release.open() try await waitForCaptureState { runtime.session.status == .idle } From 24f8284611b4bc31b75cde6ba44dc66279976502 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 15:53:11 +0530 Subject: [PATCH 40/70] Reproduce resume returning before terminal capture cleanup --- .../ScreenCaptureTransitionTests.swift | 3 ++- .../ScreenCaptureUpdateTests.swift | 21 +++++++++++++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index cb575c2..fbc9d7f 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -12,7 +12,7 @@ final class CaptureSessionFixture { let provider: ScreenCaptureAudioInputProvider let dismissed: CaptureGate - init(_ fixture: CaptureFixture) throws { + init(_ fixture: CaptureFixture, terminationRelease: CaptureGate? = nil) throws { dismissed = fixture.gate() let (_, inputs) = AsyncStream.makeStream() let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) @@ -21,6 +21,7 @@ final class CaptureSessionFixture { options: .init(), targetFormat: format, inputContinuation: inputs, onTermination: { [session] error in Task { @MainActor in + try? await terminationRelease?.wait() await session.finishFromRecognizerTask(error: error, generation: generation) } }, transitions: owner, diff --git a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift index b59aa2e..d65ef4d 100644 --- a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift @@ -11,13 +11,19 @@ struct ScreenCaptureUpdateTests { func terminalErrorDuringResume(stopFirst: Bool) async throws { guard #available(iOS 27.0, macOS 26.0, *) else { return } try await withCaptureFixture { fixture in - let runtime = try CaptureSessionFixture(fixture) + let teardown = fixture.gate(), resumed = fixture.gate() + let runtime = try CaptureSessionFixture(fixture, terminationRelease: teardown) + let (_, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) let stream = ControlledCaptureStream() await fixture.track(runtime.provider.selectStream { stream }).value await runtime.session.pauseTranscribing() let started = fixture.gate(), release = fixture.gate() stream.startEntered = started; stream.startRelease = release - let resume = fixture.track(Task { try await runtime.session.resumeTranscribing() }) + let resume = fixture.track(Task { + defer { resumed.open() } + try await runtime.session.resumeTranscribing() + }) try await started.wait() if stopFirst { fixture.track(Task { await runtime.session.stopTranscribing() }) @@ -27,13 +33,20 @@ struct ScreenCaptureUpdateTests { stream.terminated = true runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) }).value - try await runtime.dismissed.wait() release.open() - try await waitForCaptureState { runtime.session.status == .idle } + if !stopFirst { + await #expect(throws: TestTimeoutError.self) { + try await awaitResult(timeout: 0.05) { try await resumed.wait() } + } + #expect(runtime.session.continuation != nil) + } + teardown.open() if stopFirst { try await resume.value + try await waitForCaptureState { runtime.session.status == .idle } } else { await #expect(throws: SpeechSessionError.self) { try await resume.value } + #expect(runtime.session.status == .idle && runtime.session.continuation == nil) } #expect(!runtime.owner.isRunning && stream.stops == 1) } From bb3bb01b7ef8a2a5c7e82a71cce321c1d3882d99 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 15:53:30 +0530 Subject: [PATCH 41/70] Await terminal screen capture cleanup before resume throws --- .../SpeechSession+ScreenCapture.swift | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 82eda52..84024d2 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -241,12 +241,13 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD private let options: SpeechSession.ScreenCaptureTranscriptionOptions private let targetFormat: AVAudioFormat private let inputContinuation: AsyncStream.Continuation - private let onTermination: @Sendable (Error?) -> Void + private let onTermination: @Sendable (Error?) -> Task private let sampleQueue = DispatchQueue(label: "com.auralkit.screencapture.audio", qos: .userInitiated) // Only touched on `sampleQueue`, which serializes access. private let bufferConverter = BufferConverter() @MainActor private let transitions: ScreenCaptureTransitions + @MainActor private var terminalCleanupTask: Task? private let dismissPicker: @MainActor (any SCContentSharingPickerObserver) -> Void private var selectionContinuation: CheckedContinuation? private var stopped = false @@ -258,7 +259,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD options: SpeechSession.ScreenCaptureTranscriptionOptions, targetFormat: AVAudioFormat, inputContinuation: AsyncStream.Continuation, - onTermination: @escaping @Sendable (Error?) -> Void, + onTermination: @escaping @Sendable (Error?) -> Task, transitions: ScreenCaptureTransitions = ScreenCaptureTransitions(), dismissPicker: @escaping @MainActor (any SCContentSharingPickerObserver) -> Void = { observer in let picker = SCContentSharingPicker.shared @@ -305,7 +306,9 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD @MainActor func resume(onCompletion: @escaping @MainActor (Result) -> Void) async -> Error? { - await transitions.resume(onCompletion: onCompletion).value + let failure = await transitions.resume(onCompletion: onCompletion).value + if failure != nil { await terminalCleanupTask?.value } + return failure } @MainActor @@ -360,7 +363,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD guard let self else { return } let wrappedError = SpeechSessionError.screenCaptureFailed(error) if !self.resumeSelection(throwing: wrappedError) { - self.onTermination(wrappedError) + _ = self.onTermination(wrappedError) } } } @@ -385,14 +388,14 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD ) else { return } guard let bufferCopy = sourceBuffer.copy() as? AVAudioPCMBuffer else { - onTermination(SpeechSessionError.conversionBufferCreationFailed) + _ = onTermination(SpeechSessionError.conversionBufferCreationFailed) return } processAudioBuffer(bufferCopy) } } catch { - onTermination(SpeechSessionError.screenCaptureFailed(error)) + _ = onTermination(SpeechSessionError.screenCaptureFailed(error)) } } @@ -418,7 +421,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD try await update.value } catch { guard !self.stopped, self.filterUpdateID == id, self.transitions.isCurrent(stream) else { return } - self.onTermination(SpeechSessionError.screenCaptureFailed(error)) + _ = self.onTermination(SpeechSessionError.screenCaptureFailed(error)) } } } @@ -435,7 +438,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } catch { guard !self.stopped, self.pickerUpdateID == id else { return } if !self.resumeSelection(throwing: error) { - self.onTermination(SpeechSessionError.screenCaptureFailed(error)) + _ = self.onTermination(SpeechSessionError.screenCaptureFailed(error)) } } } @@ -472,7 +475,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD let converted = try bufferConverter.convertBuffer(buffer, to: targetFormat) inputContinuation.yield(AnalyzerInput(buffer: converted)) } catch { - onTermination(error) + _ = onTermination(error) } } @@ -485,7 +488,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD let isCurrent = transitions.didStop(stream, error: failure) guard !stopped, isCurrent else { return } stopped = true - onTermination(failure) + terminalCleanupTask = onTermination(failure) } } #else From 82071ace78d2511960d0cc711d45ea974f02b746 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:03:50 +0530 Subject: [PATCH 42/70] Log native ScreenCaptureKit activity on OS 27 --- README.md | 2 ++ .../SpeechSession+ScreenCapture.swift | 27 +++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4359c19..37cae08 100644 --- a/README.md +++ b/README.md @@ -305,6 +305,8 @@ let stream = session.startTranscribingScreenCapture( Screen capture transcription still returns normal `SpeechTranscriber.Result` values. AuralKit handles the ScreenCaptureKit stream, converts audio `CMSampleBuffer`s into analyzer-compatible buffers, and feeds the existing SpeechAnalyzer pipeline. +On OS 27 and later, set `SpeechSession.logging = .debug` to see the native stream's `SCStream.isCapturing` state after capture starts, stops, or updates its content filter. The property reports screen capture activity. Audio delivery can be checked independently by looking at transcription results. + ### Error Handling AuralKit surfaces detailed `SpeechSessionError` values so you can present actionable messaging: diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 9852a37..2c5d625 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -1,6 +1,7 @@ import AVFoundation import CoreMedia import Foundation +import OSLog import Speech // swiftlint:disable file_length @@ -226,10 +227,32 @@ private final class NativeScreenCaptureStream: ScreenCaptureStream { self.stream = stream } - func startCapture() async throws { try await stream.startCapture() } + func startCapture() async throws { + defer { logCaptureState(after: "startCapture") } + try await stream.startCapture() + } + func stopCapture() async throws { + defer { logCaptureState(after: "stopCapture") } try await stream.stopCapture() } + +#if os(macOS) || targetEnvironment(macCatalyst) + func updateContentFilter(_ filter: SCContentFilter) async throws { + defer { logCaptureState(after: "updateContentFilter") } + try await stream.updateContentFilter(filter) + } +#endif + + private func logCaptureState(after operation: String) { +#if compiler(>=6.4) + guard #available(iOS 27.0, macOS 27.0, macCatalyst 27.0, *), + SpeechSession.shouldLog(.debug) else { return } + SpeechSession.logger.debug( + "SCStream.isCapturing after \(operation, privacy: .public): \(self.stream.isCapturing, privacy: .public)" + ) +#endif + } } @available(iOS 27.0, macOS 14.0, *) @@ -331,7 +354,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD guard let current = self.transitions.stream as? NativeScreenCaptureStream, current.stream === updatedStream else { return } #if os(macOS) || targetEnvironment(macCatalyst) - self.updateStream(current) { try await updatedStream.updateContentFilter(selectedFilter) } + self.updateStream(current) { try await current.updateContentFilter(selectedFilter) } return #endif } From 0403ecb269cb29be1b84c10c53d02938209f588d Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:08:04 +0530 Subject: [PATCH 43/70] Fix first-use speech authorization callback isolation --- Sources/AuralKit/SpeechSession+Pipeline.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 97c0395..f41c9db 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -52,7 +52,7 @@ extension SpeechSession { Self.logger.notice("Requesting speech recognition permission\(suffix)") } let granted = await withCheckedContinuation { continuation in - SFSpeechRecognizer.requestAuthorization { status in + SFSpeechRecognizer.requestAuthorization { @Sendable status in continuation.resume(returning: status == .authorized) } } From fca3fb394c91f1c050dae9e2f311c1bbd254a0f7 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:11:25 +0530 Subject: [PATCH 44/70] Transcribe a selected audio track in local media --- README.md | 24 +++++ Sources/AuralKit/SpeechSession+File.swift | 95 +++++++++------- .../AuralKit/SpeechSession+MediaFile.swift | 101 ++++++++++++++++++ .../FileTranscriptionTests.swift | 22 ++++ 4 files changed, 202 insertions(+), 40 deletions(-) create mode 100644 Sources/AuralKit/SpeechSession+MediaFile.swift diff --git a/README.md b/README.md index 4359c19..24f6e90 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription - Async streams for lifecycle status, audio inputs, and transcription results - Device capability helper to inspect available transcribers and locales - Xcode 27-ready file transcription path that can use Speech's native analyzer file input when built with Swift 6.4+ +- Transcription from a selected audio track in a local movie or other media file on iOS and macOS 27+ - Xcode 27-ready live capture and analyzer preheating configuration with Xcode 26 fallbacks - ScreenCaptureKit-backed transcription for selected content audio on iOS 27+ and macOS 14+ - SwiftUI-friendly API that mirrors Apple's sample project design @@ -35,6 +36,7 @@ AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription - [Usage](#usage) - [Simple Transcription](#simple-transcription) - [Partial Results](#partial-results) + - [Media File Audio](#media-file-audio) - [Screen Capture Audio](#screen-capture-audio) - [Session Observability](#session-observability) - [Monitoring Model Downloads](#monitoring-model-downloads) @@ -276,6 +278,28 @@ struct ContentView: View { The `TranscriptionManager` in the demo app adds language selection, history tracking, and export. +### Media File Audio + +With Swift 6.4 and iOS or macOS 27+, pass a local media file to `streamTranscription(fromMediaFile:audioTrackID:options:)`. The default is the first audio track. Use `AVURLAsset` to find a particular audio track, then pass its `trackID`. + +```swift +import AVFoundation +import AuralKit + +let asset = AVURLAsset(url: movieURL) +let tracks = try await asset.loadTracks(withMediaType: .audio) + +if let commentary = tracks.dropFirst().first { + let session = SpeechSession() + let results = session.streamTranscription(fromMediaFile: movieURL, audioTrackID: commentary.trackID) + for try await result in results where result.isFinal { + print(result.text) + } +} +``` + +The file must be in an allowed directory, as with audio file transcription. `FileTranscriptionOptions.maxDuration` applies to the selected audio track. The app needs `NSSpeechRecognitionUsageDescription` for the Speech permission prompt. + ### Screen Capture Audio On OS versions where ScreenCaptureKit can stream selected content audio, AuralKit can transcribe audio chosen with the system picker: diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 788925d..b009894 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -66,35 +66,15 @@ public extension SpeechSession { options: FileTranscriptionOptions = .init(), progressHandler: (@Sendable (Double) -> Void)? = nil ) -> AsyncThrowingStream { - let (stream, newContinuation) = AsyncThrowingStream.makeStream() - - guard continuation == nil, recognizerTask == nil, streamingMode == .inactive else { - newContinuation.finish(throwing: SpeechSessionError.recognitionStreamSetupFailed) - return stream - } - - let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in - Task { @MainActor [weak self] in - await self?.handleStreamTermination(generation: generation) - } - } - - setStatus(.preparing) - continuation = .speech(newContinuation) - - pipelineTask = Task { @MainActor [weak self] in - guard let self else { return } - await self.startFilePipeline( - with: newContinuation, + startFileTranscription { session, continuation, generation in + await session.startFilePipeline( + with: continuation, audioFileURL: audioFile, options: options, progressHandler: progressHandler, generation: generation ) } - - return stream } /// Convenience wrapper that collects final results from file transcription. @@ -152,22 +132,12 @@ private extension SpeechSession { generation: generation ) try Task.checkCancellation() - let handler = progressHandler - fileIngestionTask = Task { [weak self] in - guard let self else { return } - - do { - let completed = try await self.feedAudioFile( - validation, progressHandler: handler, generation: generation - ) - - if completed, let handler { - self.reportFileProgress(1.0, handler: handler, generation: generation) - } - } catch is CancellationError { - // Swallow cancellation triggered by cleanup. - } catch { - await self.finishWithStartupError(error, generation: generation) + startFileIngestion(generation: generation) { session in + let completed = try await session.feedAudioFile( + validation, progressHandler: progressHandler, generation: generation + ) + if completed, let progressHandler { + session.reportFileProgress(1.0, handler: progressHandler, generation: generation) } } } catch is CancellationError { @@ -213,7 +183,9 @@ private extension SpeechSession { return (audioFile, totalFrames) } +} +extension SpeechSession { func sanitizeAudioFileURL( _ url: URL, allowedDirectories: [URL] @@ -272,7 +244,9 @@ private extension SpeechSession { Self.logger.info("File transcription pipeline active (mode: file playback)") } } +} +private extension SpeechSession { nonisolated func feedAudioFile( _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), progressHandler: (@Sendable (Double) -> Void)?, @@ -344,10 +318,51 @@ private extension SpeechSession { #endif return false } - } extension SpeechSession { + typealias FileResultContinuation = AsyncThrowingStream.Continuation + + func startFileTranscription( + _ setup: @escaping @MainActor (SpeechSession, FileResultContinuation, Int) async -> Void + ) -> AsyncThrowingStream { + let (stream, newContinuation) = AsyncThrowingStream.makeStream() + guard continuation == nil, recognizerTask == nil, streamingMode == .inactive else { + newContinuation.finish(throwing: SpeechSessionError.recognitionStreamSetupFailed) + return stream + } + + let generation = beginStreamGeneration() + newContinuation.onTermination = { [weak self] _ in + Task { @MainActor [weak self] in + await self?.handleStreamTermination(generation: generation) + } + } + setStatus(.preparing) + continuation = .speech(newContinuation) + pipelineTask = Task { @MainActor [weak self] in + guard let self else { return } + await setup(self, newContinuation, generation) + } + return stream + } + + func startFileIngestion( + generation: Int, + _ ingest: @escaping @MainActor (SpeechSession) async throws -> Void + ) { + fileIngestionTask = Task { [weak self] in + guard let self else { return } + do { + try await ingest(self) + } catch is CancellationError { + // Cleanup cancelled the ingestion task. + } catch { + await finishWithStartupError(error, generation: generation) + } + } + } + func reportFileProgress( _ progress: Double, handler: @Sendable (Double) -> Void, diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift new file mode 100644 index 0000000..f71353c --- /dev/null +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -0,0 +1,101 @@ +#if swift(>=6.4) +import AVFoundation +import CoreMedia +import Foundation +import Speech + +@available(iOS 27.0, macOS 27.0, *) +public extension SpeechSession { + /// Stream transcription results from one audio track of a local media file, such as a movie. + /// + /// - Parameters: + /// - mediaFile: A local file URL in one of `options.allowedDirectories`. + /// - audioTrackID: An ID from the file's audio tracks. Pass `nil` to use its first audio track. + /// - options: Contextual strings, allowed directories, and the maximum selected track duration. + /// - Returns: An async throwing stream of transcription results on the media timeline. + func streamTranscription( + fromMediaFile mediaFile: URL, + audioTrackID: CMPersistentTrackID? = nil, + options: FileTranscriptionOptions = .init() + ) -> AsyncThrowingStream { + startFileTranscription { session, continuation, generation in + await session.startMediaFilePipeline( + mediaFile, audioTrackID: audioTrackID, options: options, + continuation: continuation, generation: generation + ) + } + } +} + +@available(iOS 27.0, macOS 27.0, *) +private extension SpeechSession { + func startMediaFilePipeline( + _ mediaFile: URL, + audioTrackID: CMPersistentTrackID?, + options: FileTranscriptionOptions, + continuation: FileResultContinuation, + generation: Int + ) async { + do { + try Task.checkCancellation() + let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) + let asset = AVURLAsset(url: url) + let track = try await loadAudioTrack(from: asset, id: audioTrackID, maxDuration: options.maxDuration) + try Task.checkCancellation() + try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") + try Task.checkCancellation() + try await setUpFilePipeline( + with: continuation, + contextualStrings: options.contextualStrings, + startAnalyzerImmediately: false, + generation: generation + ) + try Task.checkCancellation() + guard let analyzer, let activeModules else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: activeModules) else { + throw SpeechSessionError.invalidAudioDataType + } + try Task.checkCancellation() + let provider = AssetInputSequenceProvider(asset: asset, track: track, analyzerFormat: format) + let inputs = provider.analyzerInputs + startFileIngestion(generation: generation) { session in + try await session.prepareAnalyzerForStartIfNeeded(in: format) + try Task.checkCancellation() + session.startSpeechDetectorMonitoringIfNeeded() + + let endTime = try await analyzer.analyzeSequence(inputs) + try Task.checkCancellation() + if let endTime { + try await analyzer.finalizeAndFinish(through: endTime) + } else { + try await analyzer.finalizeAndFinishThroughEndOfInput() + } + } + } catch { + await finishFailedPipelineSetup(error, generation: generation) + } + } + + func loadAudioTrack( + from asset: AVAsset, + id: CMPersistentTrackID?, + maxDuration: TimeInterval? + ) async throws -> AVAssetTrack { + let tracks = try await asset.loadTracks(withMediaType: .audio) + guard let track = tracks.first(where: { id == nil || $0.trackID == id }) else { + let reason = id.map { "Audio track ID \($0) was not found" } ?? "the media file has no audio tracks" + throw SpeechSessionError.audioFileUnsupportedFormat(reason) + } + let duration = try await track.load(.timeRange).duration.seconds + guard duration.isFinite, duration > 0 else { + throw SpeechSessionError.audioFileUnsupportedFormat("the audio track has no finite, positive duration") + } + if let maxDuration, duration > maxDuration { + throw SpeechSessionError.audioFileTooLong(maximum: maxDuration, actual: duration) + } + return track + } +} +#endif diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 68fd118..2bf24ea 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -30,6 +30,28 @@ struct FileTranscriptionTests { } } +#if swift(>=6.4) + @available(iOS 27.0, macOS 27.0, *) + @Test("Media transcription rejects an unknown audio track without falling back") + @MainActor + func mediaTranscriptionRejectsUnknownTrack() async throws { + let url = try createSilenceAudioFile(duration: 2.0) + defer { try? FileManager.default.removeItem(at: url) } + let asset = AVURLAsset(url: url) + let tracks = try await asset.loadTracks(withMediaType: .audio) + let track = try #require(tracks.first) + let session = SpeechSession() + + let stream = session.streamTranscription(fromMediaFile: url, audioTrackID: track.trackID + 1) + do { + for try await _ in stream { } + Issue.record("Expected the unknown track to be rejected") + } catch SpeechSessionError.audioFileUnsupportedFormat(let reason) { + #expect(reason.contains("\(track.trackID + 1)")) + } + } +#endif + private func createSilenceAudioFile(duration: TimeInterval, sampleRate: Double = 44_100) throws -> URL { let tempURL = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString) From 8c538678145a2a0e043a956a1beacd83fee1bfa2 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:16:13 +0530 Subject: [PATCH 45/70] Validate media references and duration before transcription --- README.md | 2 +- .../AuralKit/SpeechSession+MediaFile.swift | 26 ++++++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 24f6e90..ac6582d 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,7 @@ if let commentary = tracks.dropFirst().first { } ``` -The file must be in an allowed directory, as with audio file transcription. `FileTranscriptionOptions.maxDuration` applies to the selected audio track. The app needs `NSSpeechRecognitionUsageDescription` for the Speech permission prompt. +Use the default `.automatic` input provider. The file must be in an allowed directory and contain its audio. `FileTranscriptionOptions.maxDuration` applies to the selected track’s duration on the media timeline. The app needs `NSSpeechRecognitionUsageDescription` for the Speech permission prompt. ### Screen Capture Audio diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index f71353c..256fbeb 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -13,6 +13,8 @@ public extension SpeechSession { /// - audioTrackID: An ID from the file's audio tracks. Pass `nil` to use its first audio track. /// - options: Contextual strings, allowed directories, and the maximum selected track duration. /// - Returns: An async throwing stream of transcription results on the media timeline. + /// + /// The audio must be stored inside the media file and the session must use `.automatic` input. func streamTranscription( fromMediaFile mediaFile: URL, audioTrackID: CMPersistentTrackID? = nil, @@ -38,8 +40,17 @@ private extension SpeechSession { ) async { do { try Task.checkCancellation() + guard inputProviderPreference == .automatic else { + throw SpeechSessionError.audioFileUnsupportedFormat(NSLocalizedString( + "media transcription requires the automatic input provider", + comment: "Media files cannot use the legacy audio input pipeline" + )) + } let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) - let asset = AVURLAsset(url: url) + let asset = AVURLAsset(url: url, options: [ + AVURLAssetReferenceRestrictionsKey: AVAssetReferenceRestrictions.forbidAll.rawValue, + AVURLAssetPreferPreciseDurationAndTimingKey: options.maxDuration != nil + ]) let track = try await loadAudioTrack(from: asset, id: audioTrackID, maxDuration: options.maxDuration) try Task.checkCancellation() try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") @@ -85,12 +96,21 @@ private extension SpeechSession { ) async throws -> AVAssetTrack { let tracks = try await asset.loadTracks(withMediaType: .audio) guard let track = tracks.first(where: { id == nil || $0.trackID == id }) else { - let reason = id.map { "Audio track ID \($0) was not found" } ?? "the media file has no audio tracks" + let reason = if let id { + String.localizedStringWithFormat(NSLocalizedString( + "audio track ID %d was not found", comment: "The requested audio track is missing" + ), id) + } else { + NSLocalizedString("the media file has no audio tracks", comment: "The media asset has no audio track") + } throw SpeechSessionError.audioFileUnsupportedFormat(reason) } let duration = try await track.load(.timeRange).duration.seconds guard duration.isFinite, duration > 0 else { - throw SpeechSessionError.audioFileUnsupportedFormat("the audio track has no finite, positive duration") + throw SpeechSessionError.audioFileUnsupportedFormat(NSLocalizedString( + "the audio track has no finite, positive duration", + comment: "The media audio track has no usable duration" + )) } if let maxDuration, duration > maxDuration { throw SpeechSessionError.audioFileTooLong(maximum: maxDuration, actual: duration) From 49e05e51ed91fafcb22c54e6c32bd4615b422e98 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:13:27 +0530 Subject: [PATCH 46/70] Use the Sendable microphone tap on OS 27 --- Sources/AuralKit/SpeechSession+Audio.swift | 66 ++++++++++++++-------- 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+Audio.swift b/Sources/AuralKit/SpeechSession+Audio.swift index ef7396f..1842411 100644 --- a/Sources/AuralKit/SpeechSession+Audio.swift +++ b/Sources/AuralKit/SpeechSession+Audio.swift @@ -28,22 +28,7 @@ extension SpeechSession { throw SpeechSessionError.invalidAudioDataType } - audioEngine.inputNode.removeTap(onBus: 0) - - let inputFormat = audioEngine.inputNode.outputFormat(forBus: 0) - - if Self.shouldLog(.debug) { - Self.logger.debug( - "Installing audio tap with buffer size \(Self.microphoneTapBufferSize, privacy: .public) frames" - ) - } - - audioEngine.inputNode.installTap( - onBus: 0, - bufferSize: Self.microphoneTapBufferSize, - format: inputFormat, - block: makeAudioTapHandler(inputBuilder: inputBuilder, analyzerFormat: analyzerFormat) - ) + try installMicrophoneTap(inputBuilder: inputBuilder, analyzerFormat: analyzerFormat) audioEngine.prepare() try audioEngine.start() @@ -53,6 +38,42 @@ extension SpeechSession { } } + private func installMicrophoneTap( + inputBuilder: AsyncStream.Continuation, + analyzerFormat: AVAudioFormat + ) throws { + let inputNode = audioEngine.inputNode + inputNode.removeTap(onBus: 0) + let inputFormat = inputNode.outputFormat(forBus: 0) + +#if swift(>=6.4) + if #available(iOS 27.0, macOS 27.0, *) { + guard inputFormat.sampleRate > 0, inputFormat.channelCount > 0 else { + throw SpeechSessionError.invalidAudioDataType + } + + // Use the smallest supported tap duration of 100 ms. + let bufferSize = AVAudioFrameCount((inputFormat.sampleRate / 10).rounded(.up)) + let processBuffer = makeAudioTapHandler( + inputBuilder: inputBuilder, + analyzerFormat: analyzerFormat, + ownsTapBuffer: true + ) + try inputNode.installAudioTap(onBus: 0, bufferSize: bufferSize, format: inputFormat) { buffer, _ in + guard buffer.frameLength > 0 else { return } + processBuffer(AVAudioPCMBuffer(copying: buffer)) + } + return + } +#endif + + let processBuffer = makeAudioTapHandler(inputBuilder: inputBuilder, analyzerFormat: analyzerFormat) + let tap: @Sendable (AVAudioPCMBuffer, AVAudioTime) -> Void = { buffer, _ in + processBuffer(buffer) + } + inputNode.installTap(onBus: 0, bufferSize: Self.microphoneTapBufferSize, format: inputFormat, block: tap) + } + func stopAudioStreaming() { guard isAudioStreaming else { return } @@ -116,7 +137,7 @@ extension SpeechSession { #endif } - /// Build a tap block that converts and forwards buffers synchronously on the tap thread. + /// Convert and forward buffers synchronously on the tap thread. /// /// Converting inline (rather than hopping through per-buffer tasks) guarantees analyzer /// input arrives in capture order and keeps working across cleanup: yields into a finished @@ -124,15 +145,16 @@ extension SpeechSession { /// device change (which reinstalls the tap with a new format) never reuses a stale converter. private func makeAudioTapHandler( inputBuilder: AsyncStream.Continuation, - analyzerFormat: AVAudioFormat - ) -> AVAudioNodeTapBlock { + analyzerFormat: AVAudioFormat, + ownsTapBuffer: Bool = false + ) -> @Sendable (AVAudioPCMBuffer) -> Void { let converter = BufferConverter() - return { buffer, _ in + return { buffer in do { let converted = try converter.convertBuffer(buffer, to: analyzerFormat) let input: AVAudioPCMBuffer - if converted === buffer { - // Passthrough: the engine reuses the tap buffer, so hand the analyzer a copy. + if converted === buffer, !ownsTapBuffer { + // The older tap reuses its buffer, so give the analyzer a copy. guard let bufferCopy = buffer.copy() as? AVAudioPCMBuffer else { Task { @MainActor in if Self.shouldLog(.error) { From 05cff64e6b58c949aeb11462201b2999f837e859 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:09:51 +0530 Subject: [PATCH 47/70] Use native Speech input for screen audio on OS 27 --- .../ScreenCaptureAudioProcessor.swift | 188 ++++++++++++++++++ .../SpeechSession+ScreenCapture.swift | 91 ++++----- .../ScreenCaptureAudioTests.swift | 89 +++++++++ 3 files changed, 313 insertions(+), 55 deletions(-) create mode 100644 Sources/AuralKit/ScreenCaptureAudioProcessor.swift create mode 100644 Tests/AuralKitTests/ScreenCaptureAudioTests.swift diff --git a/Sources/AuralKit/ScreenCaptureAudioProcessor.swift b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift new file mode 100644 index 0000000..6579191 --- /dev/null +++ b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift @@ -0,0 +1,188 @@ +import AVFoundation +import CoreMedia +import Foundation +import Speech + +/// Serializes audio conversion and admits callbacks only from the currently running stream. +final class ScreenCaptureAudioProcessor: @unchecked Sendable { + let queue = DispatchQueue(label: "com.auralkit.screencapture.audio", qos: .userInitiated) + private let conversion: any ScreenCaptureAudioConversion + private let input: AsyncStream.Continuation + private let onError: @Sendable (Error) -> Void + // Accessed only on queue, including during start and stop. + private var activeStream: ObjectIdentifier? + + init( + targetFormat: AVAudioFormat, + useNativeConversion: Bool, + input: AsyncStream.Continuation, + onError: @escaping @Sendable (Error) -> Void + ) { +#if compiler(>=6.4) + if #available(iOS 27.0, macOS 27.0, *), useNativeConversion { + conversion = NativeScreenCaptureAudioConversion(targetFormat: targetFormat) + } else { + conversion = LegacyScreenCaptureAudioConversion(targetFormat: targetFormat) + } +#else + conversion = LegacyScreenCaptureAudioConversion(targetFormat: targetFormat) +#endif + self.input = input + self.onError = onError + } + + func start(_ stream: ObjectIdentifier) { + queue.sync { activeStream = stream } + } + + func stop(_ stream: ObjectIdentifier, drain: Bool = true) { + queue.sync { + guard activeStream == stream else { return } + endCapture(drain: drain) + } + } + + func discard() { + queue.sync { endCapture(drain: false) } + } + + private func endCapture(drain: Bool) { + activeStream = nil + guard drain else { + conversion.discard() + return + } + do { + try yield(conversion.flush()) + } catch { + onError(error) + } + } + + func receive(_ sample: CMSampleBuffer, from stream: ObjectIdentifier) { + dispatchPrecondition(condition: .onQueue(queue)) + guard activeStream == stream, sample.isValid, sample.numSamples > 0, + sample.dataReadiness == .ready, + let description = sample.formatDescription?.audioStreamBasicDescription, + description.mFormatID == kAudioFormatLinearPCM else { return } + var sourceDescription = description + guard let format = AVAudioFormat(streamDescription: &sourceDescription) else { return } + do { + try yield(conversion.convert(sample, format: format)) + } catch { + endCapture(drain: false) + onError(error) + } + } + + private func yield(_ inputs: [AnalyzerInput]) { + for buffer in inputs { input.yield(buffer) } + } +} + +private protocol ScreenCaptureAudioConversion { + func convert(_ sample: CMSampleBuffer, format: AVAudioFormat) throws -> [AnalyzerInput] + func flush() throws -> [AnalyzerInput] + func discard() +} + +private func copyPCMBuffer(_ sample: CMSampleBuffer, format: AVAudioFormat) throws -> AVAudioPCMBuffer { + let frameCount = AVAudioFrameCount(sample.numSamples) + guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount) else { + throw SpeechSessionError.conversionBufferCreationFailed + } + buffer.frameLength = frameCount + try sample.copyPCMData(fromRange: 0.. [AnalyzerInput] { + let source = try copyPCMBuffer(sample, format: format) + let converted = try converter.convertBuffer(source, to: targetFormat) + return [AnalyzerInput(buffer: converted)] + } + + func flush() -> [AnalyzerInput] { [] } + func discard() {} +} + +#if compiler(>=6.4) +@available(iOS 27.0, macOS 27.0, *) +private final class NativeScreenCaptureAudioConversion: ScreenCaptureAudioConversion { + private let targetFormat: AVAudioFormat + private var converter: AnalyzerInputConverter? + private var converterSourceFormat: AVAudioFormat? + private var nextFrame: AVAudioFramePosition = 0 + + init(targetFormat: AVAudioFormat) { + self.targetFormat = targetFormat + } + + func convert(_ sample: CMSampleBuffer, format: AVAudioFormat) throws -> [AnalyzerInput] { + var inputs: [AnalyzerInput] = [] + if format == targetFormat, sample.dataBuffer != nil { + inputs = try flush() + // Keep the existing contiguous transcript clock across pauses and source changes. + // Copy the timing metadata while retaining the original audio data. + let rate = CMTimeScale(targetFormat.sampleRate) + let timing = CMSampleTimingInfo( + duration: CMTime(value: 1, timescale: rate), + presentationTimeStamp: CMTime(value: nextFrame, timescale: rate), + decodeTimeStamp: .invalid + ) + let frameCount = AVAudioFramePosition(sample.numSamples) + // The copied sample buffer and its retained data remain read-only after handoff. + nonisolated(unsafe) let retimed = try CMSampleBuffer(copying: sample, withNewTiming: [timing]) + let input = AnalyzerInput(buffer: CMReadySampleBuffer(unsafeWithDataBuffer: retimed)) + nextFrame += frameCount + inputs.append(input) + return inputs + } + + let source = try copyPCMBuffer(sample, format: format) + if converterSourceFormat != format { + inputs = try flush() + } + let time: AVAudioTime? + let activeConverter: AnalyzerInputConverter + if let converter { + activeConverter = converter + time = nil + } else { + activeConverter = AnalyzerInputConverter(analyzerFormat: targetFormat) + converter = activeConverter + converterSourceFormat = format + time = AVAudioTime(sampleTime: nextFrame, atRate: targetFormat.sampleRate) + } + let converted = try activeConverter.convert(source, at: time) + advanceClock(with: converted) + inputs += converted + return inputs + } + + func flush() throws -> [AnalyzerInput] { + guard let converter else { return [] } + discard() + let remaining = try converter.flush() + advanceClock(with: remaining) + return remaining + } + + func discard() { + converter = nil + converterSourceFormat = nil + } + + private func advanceClock(with inputs: [AnalyzerInput]) { + for input in inputs { + nextFrame += input.bufferDuration.convertScale( + CMTimeScale(targetFormat.sampleRate), method: .roundHalfAwayFromZero + ).value + } + } +} +#endif diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 2c5d625..fec4157 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -68,9 +68,8 @@ public extension SpeechSession { /// Start transcribing audio from content selected with ScreenCaptureKit's system picker. /// /// Screen capture transcription is available on platforms where ScreenCaptureKit can stream - /// audio as `CMSampleBuffer` values. AuralKit configures the stream for audio capture, converts - /// incoming audio samples into analyzer-compatible `AVAudioPCMBuffer`s, and emits normal - /// `SpeechTranscriber.Result` values. + /// audio as `CMSampleBuffer` values. AuralKit supplies analyzer-compatible audio to Speech + /// and emits normal `SpeechTranscriber.Result` values. /// /// Apps using this API must include `NSScreenCaptureUsageDescription` in their Info.plist. /// @@ -179,6 +178,7 @@ extension SpeechSession { options: options, targetFormat: analyzerFormat, inputContinuation: inputBuilder, + useNativeConversion: inputProviderPreference == .automatic, onTermination: { [weak self] error in Task { @MainActor [weak self] in await self?.finishFromRecognizerTask(error: error, generation: generation) @@ -222,19 +222,29 @@ extension SpeechSession { @MainActor private final class NativeScreenCaptureStream: ScreenCaptureStream { let stream: SCStream + private let audio: ScreenCaptureAudioProcessor - init(stream: SCStream) { + init(stream: SCStream, audio: ScreenCaptureAudioProcessor) { self.stream = stream + self.audio = audio } func startCapture() async throws { defer { logCaptureState(after: "startCapture") } - try await stream.startCapture() + let id = ObjectIdentifier(stream) + audio.start(id) + do { + try await stream.startCapture() + } catch { + audio.stop(id, drain: false) + throw error + } } func stopCapture() async throws { defer { logCaptureState(after: "stopCapture") } try await stream.stopCapture() + audio.stop(ObjectIdentifier(stream)) } #if os(macOS) || targetEnvironment(macCatalyst) @@ -261,11 +271,8 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD private let options: SpeechSession.ScreenCaptureTranscriptionOptions private let targetFormat: AVAudioFormat - private let inputContinuation: AsyncStream.Continuation private let onTermination: @Sendable (Error?) -> Task - private let sampleQueue = DispatchQueue(label: "com.auralkit.screencapture.audio", qos: .userInitiated) - // Only touched on `sampleQueue`, which serializes access. - private let bufferConverter = BufferConverter() + private let audio: ScreenCaptureAudioProcessor @MainActor private let transitions: ScreenCaptureTransitions @MainActor private var terminalCleanupTask: Task? @@ -280,6 +287,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD options: SpeechSession.ScreenCaptureTranscriptionOptions, targetFormat: AVAudioFormat, inputContinuation: AsyncStream.Continuation, + useNativeConversion: Bool = true, onTermination: @escaping @Sendable (Error?) -> Task, transitions: ScreenCaptureTransitions = ScreenCaptureTransitions(), dismissPicker: @escaping @MainActor (any SCContentSharingPickerObserver) -> Void = { observer in @@ -290,8 +298,12 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD ) { self.options = options self.targetFormat = targetFormat - self.inputContinuation = inputContinuation self.onTermination = onTermination + self.audio = ScreenCaptureAudioProcessor( + targetFormat: targetFormat, useNativeConversion: useNativeConversion, input: inputContinuation + ) { error in + _ = onTermination(error) + } self.transitions = transitions self.dismissPicker = dismissPicker super.init() @@ -338,7 +350,13 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD let operation = transitions.stop() dismissPicker(self) resumeSelection(throwing: SpeechSessionError.screenCaptureSelectionCancelled) - return Task { _ = try? await operation.value } + return Task { + do { + try await operation.value + } catch { + audio.discard() + } + } } func contentSharingPicker( @@ -367,8 +385,8 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD configuration.width = 2 configuration.height = 2 let capture = SCStream(filter: selectedFilter, configuration: configuration, delegate: self) - try capture.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) - return NativeScreenCaptureStream(stream: capture) + try capture.addStreamOutput(self, type: .audio, sampleHandlerQueue: audio.queue) + return NativeScreenCaptureStream(stream: capture, audio: audio) } } } @@ -398,26 +416,8 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of type: SCStreamOutputType) { - guard type == .audio, sampleBuffer.isValid, sampleBuffer.numSamples > 0 else { return } - guard let sourceFormat = makeSourceFormat(from: sampleBuffer) else { return } - - do { - try sampleBuffer.withAudioBufferList { audioBufferList, _ in - guard let sourceBuffer = AVAudioPCMBuffer( - pcmFormat: sourceFormat, - bufferListNoCopy: audioBufferList.unsafePointer - ) else { return } - - guard let bufferCopy = sourceBuffer.copy() as? AVAudioPCMBuffer else { - _ = onTermination(SpeechSessionError.conversionBufferCreationFailed) - return - } - - processAudioBuffer(bufferCopy) - } - } catch { - _ = onTermination(SpeechSessionError.screenCaptureFailed(error)) - } + guard type == .audio else { return } + audio.receive(sampleBuffer, from: ObjectIdentifier(stream)) } @discardableResult @@ -478,34 +478,15 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD return true } - private func makeSourceFormat(from sampleBuffer: CMSampleBuffer) -> AVAudioFormat? { - guard let formatDescription = sampleBuffer.formatDescription, - var sourceDescription = formatDescription.audioStreamBasicDescription else { - return nil - } - - return AVAudioFormat(streamDescription: &sourceDescription) - } - - /// Convert and forward a captured buffer synchronously on `sampleQueue`. - /// - /// Inline conversion preserves capture order for the analyzer; the caller passes an - /// already-copied buffer, so a passthrough conversion is safe to forward directly. - private func processAudioBuffer(_ buffer: AVAudioPCMBuffer) { - do { - let converted = try bufferConverter.convertBuffer(buffer, to: targetFormat) - inputContinuation.yield(AnalyzerInput(buffer: converted)) - } catch { - _ = onTermination(error) - } - } - @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 failure: Error? = userStopped ? nil : SpeechSessionError.screenCaptureFailed(error) + if let nativeStream = stream as? NativeScreenCaptureStream { + audio.stop(ObjectIdentifier(nativeStream.stream), drain: userStopped) + } let isCurrent = transitions.didStop(stream, error: failure) guard !stopped, isCurrent else { return } stopped = true diff --git a/Tests/AuralKitTests/ScreenCaptureAudioTests.swift b/Tests/AuralKitTests/ScreenCaptureAudioTests.swift new file mode 100644 index 0000000..a8f5b47 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureAudioTests.swift @@ -0,0 +1,89 @@ +#if compiler(>=6.4) +import AVFoundation +import CoreMedia +import Speech +import Testing +@testable import AuralKit + +struct ScreenCaptureAudioTests { + @Test(arguments: [true, false]) + func conversionKeepsOneTimelineAcrossCaptureStreams(drain: Bool) async throws { + guard #available(iOS 27.0, macOS 27.0, *) else { return } + let target = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let source = try #require(AVAudioFormat( + commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 2, interleaved: true + )) + let (inputs, continuation) = AsyncStream.makeStream() + let processor = ScreenCaptureAudioProcessor( + targetFormat: target, useNativeConversion: true, input: continuation + ) { + Issue.record("Screen audio failed: \($0)") + } + let firstStream = NSObject() + let secondStream = NSObject() + let first = ObjectIdentifier(firstStream) + let second = ObjectIdentifier(secondStream) + let convertible = try makeSample(format: source, frames: 3072, timestamp: 123) + let compatible = try makeSample(format: target, frames: 160, timestamp: 1) + + processor.start(first) + processor.queue.sync { processor.receive(convertible, from: first) } + processor.stop(first, drain: drain) + // Restart the same native stream, as when resuming from pause. + processor.queue.sync { processor.receive(compatible, from: first) } + processor.start(first) + processor.queue.sync { processor.receive(compatible, from: first) } + processor.stop(first) + processor.start(second) + processor.queue.sync { + processor.receive(compatible, from: first) + processor.receive(compatible, from: second) + } + processor.stop(second) + processor.queue.sync { processor.receive(compatible, from: second) } + continuation.finish() + + var nextTime = CMTime.zero + var durations: [CMTime] = [] + for await input in inputs { + #expect(input.bufferFormat == target) + #expect(input.bufferStartTime == nextTime) + nextTime = CMTimeAdd(nextTime, input.bufferDuration) + durations.append(input.bufferDuration) + } + let directDuration = CMTime(value: 160, timescale: 16_000) + #expect(durations.suffix(2).elementsEqual([directDuration, directDuration])) + if drain { + #expect(nextTime == CMTime(value: 1344, timescale: 16_000)) + } else { + #expect(nextTime < CMTime(value: 1344, timescale: 16_000)) + } + withExtendedLifetime((firstStream, secondStream)) {} + } + + private func makeSample(format: AVAudioFormat, frames: Int, timestamp: Int64) throws -> CMSampleBuffer { + let byteCount = frames * Int(format.streamDescription.pointee.mBytesPerFrame) + var data: CMBlockBuffer? + let status = CMBlockBufferCreateWithMemoryBlock( + allocator: kCFAllocatorDefault, memoryBlock: nil, blockLength: byteCount, + blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0, + dataLength: byteCount, flags: kCMBlockBufferAssureMemoryNowFlag, blockBufferOut: &data + ) + #expect(status == noErr) + let block = try #require(data) + #expect(CMBlockBufferFillDataBytes(with: 0, blockBuffer: block, offsetIntoDestination: 0, dataLength: byteCount) + == noErr) + return try CMSampleBuffer( + dataBuffer: block, formatDescription: format.formatDescription, numSamples: frames, + sampleTimings: [CMSampleTimingInfo( + duration: CMTime(value: 1, timescale: CMTimeScale(format.sampleRate)), + presentationTimeStamp: CMTime(value: timestamp, timescale: 1), + decodeTimeStamp: .invalid + )], + sampleSizes: [Int(format.streamDescription.pointee.mBytesPerFrame)] + ) + } +} +#endif From 0bdda6829a452f26c01f6e2a69268982fac0abfb Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:18:20 +0530 Subject: [PATCH 48/70] Omit precise timing option without a media duration limit --- Sources/AuralKit/SpeechSession+MediaFile.swift | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 256fbeb..479ff38 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -47,10 +47,7 @@ private extension SpeechSession { )) } let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) - let asset = AVURLAsset(url: url, options: [ - AVURLAssetReferenceRestrictionsKey: AVAssetReferenceRestrictions.forbidAll.rawValue, - AVURLAssetPreferPreciseDurationAndTimingKey: options.maxDuration != nil - ]) + let asset = Self.makeMediaAsset(url: url, needsPreciseDuration: options.maxDuration != nil) let track = try await loadAudioTrack(from: asset, id: audioTrackID, maxDuration: options.maxDuration) try Task.checkCancellation() try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") @@ -89,6 +86,16 @@ private extension SpeechSession { } } + static func makeMediaAsset(url: URL, needsPreciseDuration: Bool) -> AVURLAsset { + var options: [String: Any] = [ + AVURLAssetReferenceRestrictionsKey: AVAssetReferenceRestrictions.forbidAll.rawValue + ] + if needsPreciseDuration { + options[AVURLAssetPreferPreciseDurationAndTimingKey] = true + } + return AVURLAsset(url: url, options: options) + } + func loadAudioTrack( from asset: AVAsset, id: CMPersistentTrackID?, From 1582336609a1e8065b9df90470bc46cc79811173 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:23:58 +0530 Subject: [PATCH 49/70] Close media analysis when no audio samples arrive --- Sources/AuralKit/SpeechSession+MediaFile.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 479ff38..66e5c45 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -78,7 +78,13 @@ private extension SpeechSession { if let endTime { try await analyzer.finalizeAndFinish(through: endTime) } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() + // With no input samples, Speech may leave the module's results stream open. + await analyzer.cancelAndFinishNow() + try Task.checkCancellation() + guard generation == session.sessionGeneration else { return } + session.prepareForStop() + await session.cleanup(cancelRecognizer: true, generation: generation) + await session.finishStream(error: nil, generation: generation) } } } catch { From a92179b937647ad3780e6072478be91ea91b39bf Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:26:46 +0530 Subject: [PATCH 50/70] Preserve screen capture errors when copying PCM --- Sources/AuralKit/ScreenCaptureAudioProcessor.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/AuralKit/ScreenCaptureAudioProcessor.swift b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift index 6579191..789bc61 100644 --- a/Sources/AuralKit/ScreenCaptureAudioProcessor.swift +++ b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift @@ -92,7 +92,11 @@ private func copyPCMBuffer(_ sample: CMSampleBuffer, format: AVAudioFormat) thro throw SpeechSessionError.conversionBufferCreationFailed } buffer.frameLength = frameCount - try sample.copyPCMData(fromRange: 0.. Date: Fri, 13 Nov 2026 17:27:06 +0530 Subject: [PATCH 51/70] Cancel file analyzer teardown before input starts --- .../AuralKit/SpeechSession+MediaFile.swift | 3 --- Sources/AuralKit/SpeechSession+Pipeline.swift | 2 +- .../AuralKit/SpeechSession+Transcriber.swift | 10 +++++++++- .../FileTranscriptionTests.swift | 19 +++++++++++++++++++ 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 66e5c45..1f33208 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -79,9 +79,6 @@ private extension SpeechSession { try await analyzer.finalizeAndFinish(through: endTime) } else { // With no input samples, Speech may leave the module's results stream open. - await analyzer.cancelAndFinishNow() - try Task.checkCancellation() - guard generation == session.sessionGeneration else { return } session.prepareForStop() await session.cleanup(cancelRecognizer: true, generation: generation) await session.finishStream(error: nil, generation: generation) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 97c0395..5aeabf8 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -306,7 +306,7 @@ extension SpeechSession { #endif let detached = detachTranscriberState() await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached) + await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelRecognizer) guard generation == sessionGeneration else { return } await modelManager.releaseLocales() diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index 460ddcf..057c112 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -297,9 +297,17 @@ extension SpeechSession { /// /// 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 finalizeDetachedTranscriberState( + _ detached: DetachedTranscriberState, + cancelAnalysis: Bool = false + ) async { defer { withExtendedLifetime(detached.vocabularyArtifacts) {} } detached.inputBuilder?.finish() + if cancelAnalysis { + // Finalizing waits for EOF, which may never arrive if setup was cancelled. + await detached.analyzer?.cancelAndFinishNow() + return + } do { try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() } catch { diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 2bf24ea..6ff123f 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -1,5 +1,6 @@ import Testing import AVFoundation +import Speech @testable import AuralKit @Suite("File transcription") @@ -31,6 +32,24 @@ struct FileTranscriptionTests { } #if swift(>=6.4) + @Test("Stopping a file analyzer before it receives input closes the session") + @MainActor + func stopBeforeAnalyzerInputClosesSession() async throws { + let session = SpeechSession() + let (results, continuation) = AsyncThrowingStream.makeStream() + session.analyzer = SpeechAnalyzer(modules: []) + session.continuation = .speech(continuation) + session.streamingMode = .filePlayback + session.setStatus(.preparing) + + try await awaitResult(timeout: 3) { await session.stopTranscribing() } + + var iterator = results.makeAsyncIterator() + let nextResult = try await iterator.next() + #expect(nextResult == nil) + #expect(session.status == .idle) + } + @available(iOS 27.0, macOS 27.0, *) @Test("Media transcription rejects an unknown audio track without falling back") @MainActor From c1d3d2429424352fe4f64f760c143f9c770e3b81 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:14:04 +0530 Subject: [PATCH 52/70] 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 53/70] 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 54/70] 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 55/70] 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 56/70] 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 57/70] 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 938cf9d812ba26d424d7363dff06a6ac5792ad01 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:32:29 +0530 Subject: [PATCH 58/70] Unblock the analyzer if the stop regression test times out --- Tests/AuralKitTests/FileTranscriptionTests.swift | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 6ff123f..d8d4741 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -37,12 +37,24 @@ struct FileTranscriptionTests { func stopBeforeAnalyzerInputClosesSession() async throws { let session = SpeechSession() let (results, continuation) = AsyncThrowingStream.makeStream() - session.analyzer = SpeechAnalyzer(modules: []) + let analyzer = SpeechAnalyzer(modules: []) + session.analyzer = analyzer session.continuation = .speech(continuation) session.streamingMode = .filePlayback session.setStatus(.preparing) - try await awaitResult(timeout: 3) { await session.stopTranscribing() } + let watchdog = Task { + do { + try await Task.sleep(for: .seconds(3)) + Issue.record("Stopping an analyzer with no input did not return") + await analyzer.cancelAndFinishNow() + } catch is CancellationError { + // Stop completed before the deadline. + } + } + await session.stopTranscribing() + watchdog.cancel() + try await watchdog.value var iterator = results.makeAsyncIterator() let nextResult = try await iterator.next() From 4761dc98cd6254536da510d3c7d85678de64418f Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:33:26 +0530 Subject: [PATCH 59/70] Report a single outcome when screen audio drains --- .../ScreenCaptureAudioProcessor.swift | 32 +++++++++---------- .../AuralKit/ScreenCaptureTransitions.swift | 17 +++++++++- .../SpeechSession+ScreenCapture.swift | 20 +++++++++--- .../ScreenCaptureAudioTests.swift | 20 ++++++------ 4 files changed, 57 insertions(+), 32 deletions(-) diff --git a/Sources/AuralKit/ScreenCaptureAudioProcessor.swift b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift index 789bc61..8d8c45c 100644 --- a/Sources/AuralKit/ScreenCaptureAudioProcessor.swift +++ b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift @@ -35,27 +35,24 @@ final class ScreenCaptureAudioProcessor: @unchecked Sendable { queue.sync { activeStream = stream } } - func stop(_ stream: ObjectIdentifier, drain: Bool = true) { + func drain(_ stream: ObjectIdentifier) -> Error? { queue.sync { - guard activeStream == stream else { return } - endCapture(drain: drain) + guard activeStream == stream else { return nil } + activeStream = nil + do { + try yield(conversion.flush()) + return nil + } catch { + return error + } } } - func discard() { - queue.sync { endCapture(drain: false) } - } - - private func endCapture(drain: Bool) { - activeStream = nil - guard drain else { + func discard(_ stream: ObjectIdentifier? = nil) { + queue.sync { + guard stream == nil || activeStream == stream else { return } + activeStream = nil conversion.discard() - return - } - do { - try yield(conversion.flush()) - } catch { - onError(error) } } @@ -70,7 +67,8 @@ final class ScreenCaptureAudioProcessor: @unchecked Sendable { do { try yield(conversion.convert(sample, format: format)) } catch { - endCapture(drain: false) + activeStream = nil + conversion.discard() onError(error) } } diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index 1e0f080..de1b6ab 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -7,6 +7,11 @@ protocol ScreenCaptureStream: AnyObject { func stopCapture() async throws } +// A failure after the native stream has already stopped must not leave it marked running. +struct ScreenCaptureDrainFailure: Error { + let underlyingError: Error +} + /// Serializes capture side effects across suspension. Admission changes intent immediately; /// only internal operations are joined, never a public caller that may await session cleanup. @available(iOS 26.0, macOS 14.0, *) @@ -28,6 +33,7 @@ final class ScreenCaptureTransitions { private var controlRevision = UUID() private var tail: Task? private var terminalFailure: TerminalFailure? + private var drainFailure: ScreenCaptureDrainFailure? // Synchronous admission returns the owned handle before any capture call can suspend. func replace(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) -> Task { @@ -40,6 +46,7 @@ final class ScreenCaptureTransitions { try await self.stopCurrent() guard self.desiredState != .stopped, self.revision == admitted else { return } self.stream = try makeStream() + self.drainFailure = nil self.streamRevision = admitted self.terminatedStream = nil try await self.startCurrent(revision: admitted) @@ -92,7 +99,9 @@ final class ScreenCaptureTransitions { do { try await self.stopCurrent() } catch { - if self.controlRevision == control { self.desiredState = .running } + if self.controlRevision == control, !(error is ScreenCaptureDrainFailure) { + self.desiredState = .running + } throw error } } @@ -134,6 +143,7 @@ final class ScreenCaptureTransitions { return enqueue { defer { self.stream = nil } try await self.stopCurrent() + if let drainFailure = self.drainFailure { throw drainFailure } } } @@ -152,6 +162,10 @@ final class ScreenCaptureTransitions { guard isRunning, let stream else { return } do { try await stream.stopCapture() + } catch let error as ScreenCaptureDrainFailure { + isRunning = false + drainFailure = error + throw error } catch { guard terminatedStream == ObjectIdentifier(stream) else { throw error } } @@ -161,6 +175,7 @@ final class ScreenCaptureTransitions { private func startCurrent(revision admitted: UUID) async throws { guard desiredState == .running, revision == admitted, !isRunning, let stream else { return } try await stream.startCapture() + drainFailure = nil guard terminatedStream != ObjectIdentifier(stream) else { return } // Nothing else can perform capture calls until this operation exits. Intent can // still change during start; compensate before allowing a queued operation to run. diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index fec4157..2982bc9 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -236,7 +236,7 @@ private final class NativeScreenCaptureStream: ScreenCaptureStream { do { try await stream.startCapture() } catch { - audio.stop(id, drain: false) + audio.discard(id) throw error } } @@ -244,7 +244,9 @@ private final class NativeScreenCaptureStream: ScreenCaptureStream { func stopCapture() async throws { defer { logCaptureState(after: "stopCapture") } try await stream.stopCapture() - audio.stop(ObjectIdentifier(stream)) + if let error = audio.drain(ObjectIdentifier(stream)) { + throw ScreenCaptureDrainFailure(underlyingError: error) + } } #if os(macOS) || targetEnvironment(macCatalyst) @@ -332,6 +334,11 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD do { try await transitions.pause().value return transitions.desiredState == .paused + } catch let error as ScreenCaptureDrainFailure { + if !stopped { + _ = onTermination(SpeechSessionError.screenCaptureFailed(error.underlyingError)) + } + return false } catch { return false } @@ -483,9 +490,14 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD let nativeError = error as NSError let userStopped = nativeError.domain == SCStreamError.errorDomain && nativeError.code == SCStreamError.Code.userStopped.rawValue - let failure: Error? = userStopped ? nil : SpeechSessionError.screenCaptureFailed(error) + var failure: Error? = userStopped ? nil : SpeechSessionError.screenCaptureFailed(error) if let nativeStream = stream as? NativeScreenCaptureStream { - audio.stop(ObjectIdentifier(nativeStream.stream), drain: userStopped) + let id = ObjectIdentifier(nativeStream.stream) + if userStopped { + failure = audio.drain(id) + } else { + audio.discard(id) + } } let isCurrent = transitions.didStop(stream, error: failure) guard !stopped, isCurrent else { return } diff --git a/Tests/AuralKitTests/ScreenCaptureAudioTests.swift b/Tests/AuralKitTests/ScreenCaptureAudioTests.swift index a8f5b47..23bcf75 100644 --- a/Tests/AuralKitTests/ScreenCaptureAudioTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureAudioTests.swift @@ -21,8 +21,7 @@ struct ScreenCaptureAudioTests { ) { Issue.record("Screen audio failed: \($0)") } - let firstStream = NSObject() - let secondStream = NSObject() + let firstStream = NSObject(), secondStream = NSObject() let first = ObjectIdentifier(firstStream) let second = ObjectIdentifier(secondStream) let convertible = try makeSample(format: source, frames: 3072, timestamp: 123) @@ -30,18 +29,22 @@ struct ScreenCaptureAudioTests { processor.start(first) processor.queue.sync { processor.receive(convertible, from: first) } - processor.stop(first, drain: drain) + if drain { + #expect(processor.drain(first) == nil) + } else { + processor.discard(first) + } // Restart the same native stream, as when resuming from pause. processor.queue.sync { processor.receive(compatible, from: first) } processor.start(first) processor.queue.sync { processor.receive(compatible, from: first) } - processor.stop(first) + #expect(processor.drain(first) == nil) processor.start(second) processor.queue.sync { processor.receive(compatible, from: first) processor.receive(compatible, from: second) } - processor.stop(second) + #expect(processor.drain(second) == nil) processor.queue.sync { processor.receive(compatible, from: second) } continuation.finish() @@ -55,11 +58,8 @@ struct ScreenCaptureAudioTests { } let directDuration = CMTime(value: 160, timescale: 16_000) #expect(durations.suffix(2).elementsEqual([directDuration, directDuration])) - if drain { - #expect(nextTime == CMTime(value: 1344, timescale: 16_000)) - } else { - #expect(nextTime < CMTime(value: 1344, timescale: 16_000)) - } + let drainedEnd = CMTime(value: 1344, timescale: 16_000) + #expect(drain ? nextTime == drainedEnd : nextTime < drainedEnd) withExtendedLifetime((firstStream, secondStream)) {} } From 6b7309aa90d131befda6778f3c4fc5df442b11d7 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:34:00 +0530 Subject: [PATCH 60/70] Cover screen audio drain failure while pausing --- .../ScreenCaptureTransitionTests.swift | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index fbc9d7f..e7ac85a 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -182,6 +182,32 @@ struct ScreenCaptureTransitionTests { } } + @Test("A terminal stop receives a drain failure from an in-flight pause") + @MainActor + func stopReceivesDrainFailureFromPause() async throws { + try await withCaptureFixture { fixture in + let transitions = ScreenCaptureTransitions() + let stream = ControlledCaptureStream() + try await transitions.replace { stream }.value + let entered = fixture.gate(), release = fixture.gate() + stream.stopEntered = entered + stream.stopRelease = release + stream.onStop = { stream.capturing = false } + stream.stopError = ScreenCaptureDrainFailure(underlyingError: CaptureFixtureError.startFailed) + + let pause = fixture.track(transitions.pause()) + try await entered.wait() + let stop = fixture.track(transitions.stop()) + release.open() + + let pauseError = await pause.result + let stopError = await stop.result + #expect(throws: ScreenCaptureDrainFailure.self) { try pauseError.get() } + #expect(throws: ScreenCaptureDrainFailure.self) { try stopError.get() } + #expect(!stream.capturing && stream.stops == 1 && transitions.stream == nil) + } + } + @Test("A failed native pause keeps the public status transcribing", arguments: [false, true]) @MainActor func failedPause(replaceAfterFailure: Bool) async throws { From b84c3364f21781eaf3cc1f6d22fb0609784a1f05 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:34:01 +0530 Subject: [PATCH 61/70] 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 878e5fd38b34d4312c24f1fdf1c912616d7b1a3c Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:38:41 +0530 Subject: [PATCH 62/70] Preserve file ingestion errors when cancelling the recognizer --- Sources/AuralKit/SpeechSession+Pipeline.swift | 3 ++ .../FileTranscriptionTests.swift | 30 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 5aeabf8..102501c 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -441,8 +441,10 @@ extension SpeechSession { do { for try await result in results { + try Task.checkCancellation() streamContinuation.yield(result) } + try Task.checkCancellation() if Self.shouldLog(.notice) { Self.logger.notice("\(label, privacy: .public) completed without error") } @@ -452,6 +454,7 @@ extension SpeechSession { Self.logger.debug("\(label, privacy: .public) cancelled") } } catch { + guard !Task.isCancelled else { return } if Self.shouldLog(.error) { Self.logger.error( "\(label, privacy: .public) failed: \(error.localizedDescription, privacy: .public)" diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index d8d4741..73ccac9 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -62,6 +62,36 @@ struct FileTranscriptionTests { #expect(session.status == .idle) } + @Test("A cancelled recognizer cannot hide a file read error") + @MainActor + func fileReadErrorSurvivesRecognizerCancellation() async throws { + let session = SpeechSession() + let output = AsyncThrowingStream.makeStream() + let results = AsyncStream.makeStream() + let generation = session.beginStreamGeneration() + session.continuation = .speech(output.continuation) + session.streamingMode = .filePlayback + session.setStatus(.transcribing) + let recognizer = session.createRecognizerTask( + label: "File recognizer", results: results.stream, + streamContinuation: output.continuation, generation: generation + ) + session.recognizerTask = recognizer + session.startFileIngestion(generation: generation) { _ in + throw SpeechSessionError.audioFileReadFailed(nil) + } + let ingestion = try #require(session.fileIngestionTask) + + await recognizer.value + await ingestion.value + var iterator = output.stream.makeAsyncIterator() + do { + _ = try await iterator.next() + Issue.record("Expected the file read error to reach the transcription stream") + } catch SpeechSessionError.audioFileReadFailed { } + #expect(session.status == .idle) + } + @available(iOS 27.0, macOS 27.0, *) @Test("Media transcription rejects an unknown audio track without falling back") @MainActor From c69aba53d2d73a247f83f0172f417e42c85d630e Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:40:25 +0530 Subject: [PATCH 63/70] Exercise the native Speech recognizer in the file error regression --- Tests/AuralKitTests/FileTranscriptionTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 73ccac9..d1f0cc2 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -67,14 +67,14 @@ struct FileTranscriptionTests { func fileReadErrorSurvivesRecognizerCancellation() async throws { let session = SpeechSession() let output = AsyncThrowingStream.makeStream() - let results = AsyncStream.makeStream() + let transcriber = SpeechTranscriber(locale: Locale(identifier: "en-US"), preset: .transcription) + session.analyzer = SpeechAnalyzer(modules: [transcriber]) let generation = session.beginStreamGeneration() session.continuation = .speech(output.continuation) session.streamingMode = .filePlayback session.setStatus(.transcribing) - let recognizer = session.createRecognizerTask( - label: "File recognizer", results: results.stream, - streamContinuation: output.continuation, generation: generation + let recognizer = session.createSpeechRecognizerTask( + transcriber: transcriber, streamContinuation: output.continuation, generation: generation ) session.recognizerTask = recognizer session.startFileIngestion(generation: generation) { _ in From 1fc75dab14b951d0618ae519ece10ccf00b506e9 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:45:48 +0530 Subject: [PATCH 64/70] 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 149545c5af2ff42015843c21cbf9106d7ce04a90 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:46:02 +0530 Subject: [PATCH 65/70] Limit immediate teardown to media playback --- Sources/AuralKit/SpeechSession+File.swift | 5 +++- .../AuralKit/SpeechSession+MediaFile.swift | 24 +++++++++++++++---- Sources/AuralKit/SpeechSession+Pipeline.swift | 3 ++- Sources/AuralKit/SpeechSession+Types.swift | 1 + .../FileTranscriptionTests.swift | 6 ++--- 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index b009894..8e63ce9 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -219,6 +219,7 @@ extension SpeechSession { with streamContinuation: AsyncThrowingStream.Continuation, contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]?, startAnalyzerImmediately: Bool, + mode: StreamingMode = .filePlayback, generation: Int ) async throws { if Self.shouldLog(.notice) { @@ -238,7 +239,7 @@ extension SpeechSession { generation: generation ) - streamingMode = .filePlayback + streamingMode = mode setStatus(.transcribing) if Self.shouldLog(.info) { Self.logger.info("File transcription pipeline active (mode: file playback)") @@ -324,6 +325,7 @@ extension SpeechSession { typealias FileResultContinuation = AsyncThrowingStream.Continuation func startFileTranscription( + mode: StreamingMode = .filePlayback, _ setup: @escaping @MainActor (SpeechSession, FileResultContinuation, Int) async -> Void ) -> AsyncThrowingStream { let (stream, newContinuation) = AsyncThrowingStream.makeStream() @@ -338,6 +340,7 @@ extension SpeechSession { await self?.handleStreamTermination(generation: generation) } } + if mode == .mediaPlayback { streamingMode = mode } setStatus(.preparing) continuation = .speech(newContinuation) pipelineTask = Task { @MainActor [weak self] in diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 1f33208..56903fb 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -20,7 +20,7 @@ public extension SpeechSession { audioTrackID: CMPersistentTrackID? = nil, options: FileTranscriptionOptions = .init() ) -> AsyncThrowingStream { - startFileTranscription { session, continuation, generation in + startFileTranscription(mode: .mediaPlayback) { session, continuation, generation in await session.startMediaFilePipeline( mediaFile, audioTrackID: audioTrackID, options: options, continuation: continuation, generation: generation @@ -41,10 +41,7 @@ private extension SpeechSession { do { try Task.checkCancellation() guard inputProviderPreference == .automatic else { - throw SpeechSessionError.audioFileUnsupportedFormat(NSLocalizedString( - "media transcription requires the automatic input provider", - comment: "Media files cannot use the legacy audio input pipeline" - )) + throw MediaTranscriptionConfigurationError() } let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) let asset = Self.makeMediaAsset(url: url, needsPreciseDuration: options.maxDuration != nil) @@ -56,6 +53,7 @@ private extension SpeechSession { with: continuation, contextualStrings: options.contextualStrings, startAnalyzerImmediately: false, + mode: .mediaPlayback, generation: generation ) try Task.checkCancellation() @@ -128,4 +126,20 @@ private extension SpeechSession { return track } } + +private struct MediaTranscriptionConfigurationError: LocalizedError { + var errorDescription: String? { + NSLocalizedString( + "Media transcription requires the automatic input provider.", + comment: "Media files cannot use the legacy audio input pipeline" + ) + } + + var recoverySuggestion: String? { + NSLocalizedString( + "Create a SpeechSession with inputProviderPreference set to .automatic.", + comment: "How to enable media transcription" + ) + } +} #endif diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 102501c..76bf5f4 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -296,6 +296,7 @@ extension SpeechSession { task?.cancel() } + let cancelMediaAnalysis = cancelRecognizer && streamingMode == .mediaPlayback streamingMode = .inactive activeResultKind = nil stopAudioStreaming() @@ -306,7 +307,7 @@ extension SpeechSession { #endif let detached = detachTranscriberState() await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelRecognizer) + await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelMediaAnalysis) guard generation == sessionGeneration else { return } await modelManager.releaseLocales() diff --git a/Sources/AuralKit/SpeechSession+Types.swift b/Sources/AuralKit/SpeechSession+Types.swift index a874707..6576642 100644 --- a/Sources/AuralKit/SpeechSession+Types.swift +++ b/Sources/AuralKit/SpeechSession+Types.swift @@ -18,6 +18,7 @@ extension SpeechSession { case inactive case liveMicrophone case filePlayback + case mediaPlayback case screenCapture } diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index d1f0cc2..b50701a 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -32,7 +32,7 @@ struct FileTranscriptionTests { } #if swift(>=6.4) - @Test("Stopping a file analyzer before it receives input closes the session") + @Test("Stopping a media analyzer before it receives input closes the session") @MainActor func stopBeforeAnalyzerInputClosesSession() async throws { let session = SpeechSession() @@ -40,7 +40,7 @@ struct FileTranscriptionTests { let analyzer = SpeechAnalyzer(modules: []) session.analyzer = analyzer session.continuation = .speech(continuation) - session.streamingMode = .filePlayback + session.streamingMode = .mediaPlayback session.setStatus(.preparing) let watchdog = Task { @@ -71,7 +71,7 @@ struct FileTranscriptionTests { session.analyzer = SpeechAnalyzer(modules: [transcriber]) let generation = session.beginStreamGeneration() session.continuation = .speech(output.continuation) - session.streamingMode = .filePlayback + session.streamingMode = .mediaPlayback session.setStatus(.transcribing) let recognizer = session.createSpeechRecognizerTask( transcriber: transcriber, streamContinuation: output.continuation, generation: generation From 67fcb497cf1f88d64af1b73d79feb11e9e8820dc Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:49:15 +0530 Subject: [PATCH 66/70] 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 ec08f031786ee4aa2d0e45c828a1837ccb9b7de5 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 17:51:07 +0530 Subject: [PATCH 67/70] Forward recognizer results already queued at stop --- Sources/AuralKit/SpeechSession+Pipeline.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 76bf5f4..8487114 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -442,7 +442,6 @@ extension SpeechSession { do { for try await result in results { - try Task.checkCancellation() streamContinuation.yield(result) } try Task.checkCancellation() From 960b58c0258e28629a4e8b75ada368d4de425a87 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 18:47:47 +0530 Subject: [PATCH 68/70] Normalize screen capture drain failures --- Sources/AuralKit/SpeechSession+ScreenCapture.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 2982bc9..87afc9a 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -465,8 +465,10 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD self.resumeSelection() } catch { guard !self.stopped, self.pickerUpdateID == id else { return } - if !self.resumeSelection(throwing: error) { - _ = self.onTermination(SpeechSessionError.screenCaptureFailed(error)) + let drainFailure = error as? ScreenCaptureDrainFailure + let selectionError = drainFailure.map { SpeechSessionError.screenCaptureFailed($0.underlyingError) } + if !self.resumeSelection(throwing: selectionError ?? error) { + _ = self.onTermination(selectionError ?? SpeechSessionError.screenCaptureFailed(error)) } } } @@ -494,7 +496,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD if let nativeStream = stream as? NativeScreenCaptureStream { let id = ObjectIdentifier(nativeStream.stream) if userStopped { - failure = audio.drain(id) + failure = audio.drain(id).map { SpeechSessionError.screenCaptureFailed($0) } } else { audio.discard(id) } From dd19eae7e673093942c6590b900f6154ac6c2b14 Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Fri, 13 Nov 2026 18:48:10 +0530 Subject: [PATCH 69/70] 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 From 6d07b5db96510deb0fb3eb437940aec742967a08 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Mon, 16 Nov 2026 19:07:02 -0500 Subject: [PATCH 70/70] Preserve file transcription failures until ingestion settles --- Sources/AuralKit/SpeechSession+File.swift | 16 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 11 ++ Sources/AuralKit/SpeechSession.swift | 2 +- .../FileIngestionSettlementTests.swift | 177 ++++++++++++++++++ 4 files changed, 202 insertions(+), 4 deletions(-) create mode 100644 Tests/AuralKitTests/FileIngestionSettlementTests.swift diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index b4ffb1a..a8e62e5 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -248,7 +248,7 @@ extension SpeechSession { } } -private extension SpeechSession { +extension SpeechSession { nonisolated func feedAudioFile( _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), progressHandler: (@Sendable (Double) -> Void)?, @@ -286,7 +286,7 @@ private extension SpeechSession { } if buffer.frameLength == 0 { - break + throw SpeechSessionError.audioFileReadFailed(CocoaError(.fileReadCorruptFile)) } guard let bufferCopy = buffer.copy() as? AVAudioPCMBuffer else { @@ -312,6 +312,9 @@ private extension SpeechSession { return !Task.isCancelled && processedFrames >= totalFrames } +} + +private extension SpeechSession { func shouldUseNativeFileAnalyzer(progressHandler: (@Sendable (Double) -> Void)?) -> Bool { #if swift(>=6.4) if #available(iOS 27.0, macOS 27.0, *) { @@ -360,8 +363,15 @@ extension SpeechSession { guard let self else { return } do { try await ingest(self) + try Task.checkCancellation() + guard generation == sessionGeneration, continuation != nil else { return } + fileIngestionCompleted = true + if fileResultsCompleted { + await endTranscription(error: nil, generation: generation, cancelRecognizer: false) + } } catch is CancellationError { - // Cleanup cancelled the ingestion task. + // Only an existing terminal owner may suppress child cancellation. + await finishWithStartupError(CancellationError(), generation: generation) } catch { await finishWithStartupError(error, generation: generation) } diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 7ed51f9..f77fe75 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -78,6 +78,8 @@ extension SpeechSession { /// session moved on to another stream) cannot tear down state it no longer owns. func beginStreamGeneration() -> Int { sessionGeneration &+= 1 + fileIngestionCompleted = false + fileResultsCompleted = false return sessionGeneration } @@ -214,6 +216,11 @@ extension SpeechSession { } func finishFromRecognizerTask(error: Error?, generation: Int) async { + guard generation == sessionGeneration else { return } + if error == nil, streamingMode == .filePlayback || streamingMode == .mediaPlayback { + fileResultsCompleted = true + guard fileIngestionCompleted else { return } + } await endTranscription(error: error, generation: generation, cancelRecognizer: error != nil) } @@ -236,6 +243,9 @@ extension SpeechSession { return } if streamingMode == .filePlayback || streamingMode == .mediaPlayback { + await pipelineTask?.value + guard generation == sessionGeneration else { return } + await fileIngestionTask?.value await recognizerTask.value return } @@ -504,6 +514,7 @@ extension SpeechSession { guard generation == sessionGeneration, terminationTask == nil else { return } streamContinuation.yield(result) } + try Task.checkCancellation() if Self.shouldLog(.notice) { Self.logger.notice("\(label, privacy: .public) completed without error") } diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index a02d504..51eec39 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -97,7 +97,6 @@ public final class SpeechSession { /// Reflects the speech detector's most recent state; defaults to `true` when monitoring is inactive. public internal(set) var isSpeechDetected: Bool = true - // Stream state management var continuation: TranscriptionContinuation? var recognizerTask: Task? var pipelineTask: Task? @@ -105,6 +104,7 @@ public final class SpeechSession { var terminationTask: Task? var cancellationRequested = false var fileIngestionTask: Task? + var fileIngestionCompleted = false, fileResultsCompleted = false var streamingMode: StreamingMode = .inactive /// Incremented for every accepted start so stale termination handlers can be ignored. var sessionGeneration: Int = 0 diff --git a/Tests/AuralKitTests/FileIngestionSettlementTests.swift b/Tests/AuralKitTests/FileIngestionSettlementTests.swift new file mode 100644 index 0000000..892a45f --- /dev/null +++ b/Tests/AuralKitTests/FileIngestionSettlementTests.swift @@ -0,0 +1,177 @@ +import AVFoundation +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("File ingestion settlement") +@MainActor +struct FileIngestionSettlementTests { + @Test("Independent ingestion cancellation settles the public stream", arguments: [false, true]) + func independentCancellation(throwsCancellation: Bool) async throws { + try await withSession { runtime, fixture in + runtime.session.startFileIngestion(generation: runtime.generation) { _ in + if throwsCancellation { throw CancellationError() } + withUnsafeCurrentTask { $0?.cancel() } + } + let input = fixture.track(try #require(runtime.session.fileIngestionTask)) + await #expect(throws: CancellationError.self) { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + } + await input.value + #expect(runtime.session.status == .idle) + #expect(runtime.session.continuation == nil) + } + } + + @Test("Result EOF preserves a later input or finalization error", arguments: [false, true]) + func resultEOFDoesNotAdmitPrematureSuccess(finalization: Bool) async throws { + try await withSession { runtime, fixture in + let release = fixture.gate() + let results = AsyncThrowingStream.makeStream() + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + let reader = fixture.track(runtime.session.createRecognizerTask( + label: "File result fixture", results: results.stream, + streamContinuation: forwarded.continuation, generation: runtime.generation + )) + runtime.session.recognizerTask = reader + if finalization { + runtime.session.analyzer = SpeechAnalyzer(modules: []) + runtime.session.analyzerInputTask = Task { + try await release.wait() + throw SpeechSessionError.invalidAudioDataType + } + } + runtime.session.startFileIngestion(generation: runtime.generation) { session in + if finalization { + try await session.finishFileInput(generation: runtime.generation) + } else { + try await release.wait() + throw SpeechSessionError.audioFileReadFailed(nil) + } + } + let input = fixture.track(try #require(runtime.session.fileIngestionTask)) + results.continuation.finish() + await reader.value + #expect(runtime.session.continuation != nil) + release.open() + await input.value + do { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + Issue.record("Expected the producer failure") + } catch SpeechSessionError.invalidAudioDataType { + #expect(finalization) + } catch SpeechSessionError.audioFileReadFailed { + #expect(!finalization) + } + #expect(runtime.session.status == .idle) + } + } + + @Test("A result iterator that cancels itself before EOF fails the public stream") + func selfCancelledResultEOF() async throws { + try await withSession { runtime, fixture in + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + runtime.session.startFileIngestion(generation: runtime.generation) { _ in } + let reader = fixture.track(runtime.session.createRecognizerTask( + label: "Self-cancelled results", results: SelfCancelledResults(), + streamContinuation: forwarded.continuation, generation: runtime.generation + )) + runtime.session.recognizerTask = reader + await #expect(throws: CancellationError.self) { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + } + await reader.value + #expect(runtime.session.status == .idle) + } + } + + @Test("A physical short read fails before closing analyzer input") + func physicalShortRead() async throws { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("Aural-short-read-\(UUID().uuidString).caf") + defer { try? FileManager.default.removeItem(at: url) } + let format = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 160)) + buffer.frameLength = 160 + buffer.int16ChannelData?.pointee.initialize(repeating: 0, count: 160) + try autoreleasepool { + let writer = try AVAudioFile( + forWriting: url, settings: format.settings, commonFormat: .pcmFormatInt16, interleaved: true + ) + try writer.write(from: buffer) + } + try await withSession { runtime, _ in + let file = try AVAudioFile(forReading: url, commonFormat: .pcmFormatInt16, interleaved: true) + let declaredFrames = file.length + 1 + let input = AsyncStream.makeStream() + defer { input.continuation.finish() } + runtime.session.inputBuilder = input.continuation + runtime.session.analyzerFormat = format + do { + _ = try await runtime.session.feedAudioFile( + (file: file, totalFrames: declaredFrames), progressHandler: { _ in }, + generation: runtime.generation + ) + Issue.record("Expected audioFileReadFailed for premature physical EOF") + } catch SpeechSessionError.audioFileReadFailed { } + if case .terminated = input.continuation.yield(AnalyzerInput(buffer: buffer)) { + Issue.record("Physical input closed before its read failure was admitted") + } + } + } + + @MainActor + private struct Runtime { + let session: SpeechSession + let results: AsyncThrowingStream + let generation: Int + + init() { + let session = SpeechSession() + let output = AsyncThrowingStream.makeStream() + self.session = session + results = output.stream + generation = session.beginStreamGeneration() + session.continuation = .speech(output.continuation) + session.streamingMode = .filePlayback + session.setStatus(.transcribing) + } + } + + private func withSession(_ body: (Runtime, CaptureFixture) async throws -> Void) async throws { + try await withCaptureFixture { fixture in + let runtime = Runtime() + do { + try await body(runtime, fixture) + } catch { + fixture.releaseAll() + await runtime.session.cancelTranscribing() + throw error + } + fixture.releaseAll() + await runtime.session.cancelTranscribing() + } + } +} + +private struct SelfCancelledResults: AsyncSequence, Sendable { + typealias Element = Int + struct AsyncIterator: AsyncIteratorProtocol { + mutating func next() async -> Int? { + withUnsafeCurrentTask { $0?.cancel() } + return nil + } + } + func makeAsyncIterator() -> AsyncIterator { AsyncIterator() } +}