Skip to content

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

fix(meetings): stop delayed live startup and quiet diagnostics

altic-dev930fa25ffcb6
diff --git a/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTrackEngine.swift b/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTrackEngine.swift
index 700f70a7..8fc65a89 100644
--- a/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTrackEngine.swift
+++ b/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTrackEngine.swift
@@ -72,6 +72,8 @@ actor MeetingLiveTrackEngine {
private var diagnosticResetUptime: Double?
private let targetFormat = AVAudioFormat(
commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false
+ // Fixed Float32 PCM format with positive sample rate and channels is valid by construction.
+ // swiftlint:disable:next force_unwrapping
)!
private var converter: AVAudioConverter?
@@ -87,6 +89,9 @@ actor MeetingLiveTrackEngine {
private var drainTask: Task<Void, Never>?
private var loadTask: Task<Void, Never>?
private var isModelReady = false
+ // Each engine belongs to one meeting. Stop is terminal, including suspended startup.
+ private var hasStarted = false
+ private var isStopped = false
private var diagSamplesConsumed = 0
private var diagSecondsConsumed: Double = 0
@@ -98,8 +103,9 @@ actor MeetingLiveTrackEngine {
private var diagLabel: String { self.kind == .microphone ? "MIC" : "APP" }
- private func diag(_ message: String) {
- DebugLogger.shared.info("[live/\(self.diagLabel)] \(message)", source: "MeetingLive")
+ private func diag(_ message: @autoclosure () -> String) {
+ guard self.diagnosticsEnabled else { return }
+ DebugLogger.shared.info("[live/\(self.diagLabel)] \(message())", source: "MeetingLive")
}
private var onPartial: PartialHandler?
@@ -130,6 +136,7 @@ actor MeetingLiveTrackEngine {
onDegraded: @escaping DegradedHandler,
onReady: @escaping ReadyHandler
) {
+ guard !self.isStopped else { return }
self.onPartial = onPartial
self.onUtterance = onUtterance
self.onDegraded = onDegraded
@@ -137,11 +144,13 @@ actor MeetingLiveTrackEngine {
}
func start() async {
- guard self.drainTask == nil else { return }
+ guard !self.hasStarted, !self.isStopped else { return }
+ self.hasStarted = true
let manager = self.manager
let kind = self.kind
// Wired synchronously before load/drain start so no decode result can race ahead of it.
await self.installCallbacks()
+ guard !self.isStopped else { return }
self.loadTask = Task { [weak self] in
guard let self else { return }
do {
@@ -164,6 +173,11 @@ actor MeetingLiveTrackEngine {
}
func stop() async {
+ self.isStopped = true
+ self.onPartial = nil
+ self.onUtterance = nil
+ self.onReady = nil
+ self.onDegraded = nil
self.loadTask?.cancel()
self.drainTask?.cancel()
await self.loadTask?.value
@@ -207,20 +221,22 @@ actor MeetingLiveTrackEngine {
try await self.manager.appendAudio(silence)
try await self.manager.processBufferedAudio()
} catch {
- self.diag("warmup failed (continuing): \(error)")
+ DebugLogger.shared.warning("Live captions warmup failed (continuing): \(error)", source: "MeetingLive")
}
await self.resetRecognizer()
self.diag(String(format: "warmup complete in %.2fs", self.uptime() - started))
}
private func markReady() {
+ guard !self.isStopped else { return }
self.isModelReady = true
self.diag("model ready")
self.onReady?(self.kind)
}
private func markLoadFailed(kind: MeetingAudioTrackKind, error: Error) {
- self.diag("model load FAILED: \(error)")
+ guard !self.isStopped else { return }
+ DebugLogger.shared.warning("Live captions model load failed: \(error)", source: "MeetingLive")
self.onDegraded?(kind, "Live captions could not load: \(error.localizedDescription)")
}
@@ -275,7 +291,7 @@ actor MeetingLiveTrackEngine {
await self.rotateLongUtteranceIfNeeded()
} catch {
if self.diagnosticsEnabled { self.diagnosticSnapshot.appendOrProcessErrors += 1 }
- self.diag("appendAudio/process error: \(error)")
+ DebugLogger.shared.warning("Live captions audio processing failed: \(error)", source: "MeetingLive")
self.onDegraded?(self.kind, "Live captions hit an error and resynced.")
await self.resetUtterance()
}
@@ -302,13 +318,15 @@ actor MeetingLiveTrackEngine {
self.lastPartialText = ""
self.lastPartialUptime = nil
await self.resetRecognizer()
- guard !text.isEmpty else { return }
+ guard !self.isStopped, !text.isEmpty else { return }
self.lastUtteranceEndPTS = end
self.diagUtterances += 1
self.diag(String(
format: "forced EOU (%@) span=[%.2f–%.2f] chars=%d",
hitCeiling ? "open>\(Int(Self.maxOpenUtteranceSeconds))s" : String(format: "quiet %.1fs", quietSeconds ?? 0),
- start.seconds, end.seconds, text.count
+ start.seconds,
+ end.seconds,
+ text.count
))
self.onUtterance?(self.kind, turnID, text, start, end)
}
@@ -316,6 +334,7 @@ actor MeetingLiveTrackEngine {
/// Once every 5s of wall clock: proves audio is still reaching the recognizer, and how long the
/// current utterance has been open without an endpoint.
private func logFlowIfDue() {
+ guard self.diagnosticsEnabled else { return }
let now = self.uptime()
guard now - self.diagLastFlowLog >= 5 else { return }
self.diagLastFlowLog = now
@@ -325,14 +344,20 @@ actor MeetingLiveTrackEngine {
let sinceEou = self.diagLastEouUptime.map { now - $0 }
self.diag(String(
format: "flow chunks=%d audio=%.1fs openUtterance=%.1fs partials=%d utterances=%d drops=%d sinceEOU=%@",
- self.diagSamplesConsumed, self.diagSecondsConsumed, openFor,
- self.diagPartials, self.diagUtterances, self.diagDrops,
+ self.diagSamplesConsumed,
+ self.diagSecondsConsumed,
+ openFor,
+ self.diagPartials,
+ self.diagUtterances,
+ self.diagDrops,
sinceEou.map { String(format: "%.1fs", $0) } ?? "never"
))
if self.diagnosticsEnabled {
let snapshot = self.diagnosticSnapshot
// Wrapper counters only: no audio, transcript, names, or identity evidence.
// Actor-local logging is not an independent hung-executor watchdog.
+ // Keep the complete diagnostic output string intact.
+ // swiftlint:disable:next line_length
self.diag("p0 converted=\(snapshot.convertedBuffers) conversionFailures=\(snapshot.conversionFailures) append=\(snapshot.appendCompletions)/\(snapshot.appendStarts) process=\(snapshot.processCompletions)/\(snapshot.processStarts) errors=\(snapshot.appendOrProcessErrors) partialCallbacks=\(snapshot.partialCallbacks) eouCallbacks=\(snapshot.eouCallbacks) resetReturns=\(snapshot.recognizerResetReturned)/\(snapshot.resetInvocations) resetOrdinal=\(snapshot.wrapperGeneration) maxProcessSeconds=\(snapshot.maxProcessSeconds)")
}
}
@@ -341,6 +366,7 @@ actor MeetingLiveTrackEngine {
/// first audio buffer — marks where this utterance actually begins. Anchoring on audio instead
/// swallowed every second of preceding silence into the utterance's span.
private func handlePartial(_ text: String) {
+ guard !self.isStopped else { return }
if self.diagnosticsEnabled {
self.diagnosticSnapshot.partialCallbacks += 1
if self.diagnosticSnapshot.firstPartialAfterResetSeconds == nil,
@@ -363,12 +389,13 @@ actor MeetingLiveTrackEngine {
let end = self.lastConsumedPTS ?? start
self.diagPartials += 1
if self.diagPartials % 10 == 1 {
- self.diag("partial #\(self.diagPartials) chars=\(text.count) tail=…\(String(text.suffix(60)))")
+ self.diag("partial #\(self.diagPartials) chars=\(text.count)")
}
self.onPartial?(self.kind, turnID, text, start, end)
}
private func handleEOU(_ text: String) async {
+ guard !self.isStopped else { return }
if self.diagnosticsEnabled { self.diagnosticSnapshot.eouCallbacks += 1 }
let start = self.utteranceStartPTS
let end = self.lastConsumedPTS ?? start
@@ -382,7 +409,7 @@ actor MeetingLiveTrackEngine {
self.lastPartialUptime = nil
await self.resetRecognizer()
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else { return }
+ guard !self.isStopped, !trimmed.isEmpty else { return }
guard let start, let end, let turnID else {
self.diag("EOU fired but no start PTS — dropped (chars=\(text.count))")
return
@@ -390,10 +417,13 @@ actor MeetingLiveTrackEngine {
self.lastUtteranceEndPTS = end
self.diagUtterances += 1
self.diag(String(
- format: "EOU #%d span=[%.2f–%.2f] (%.1fs) sinceLastEOU=%@ text=%@",
- self.diagUtterances, start.seconds, end.seconds, end.seconds - start.seconds,
+ format: "EOU #%d span=[%.2f–%.2f] (%.1fs) sinceLastEOU=%@ chars=%d",
+ self.diagUtterances,
+ start.seconds,
+ end.seconds,
+ end.seconds - start.seconds,
gap.map { String(format: "%.1fs", $0) } ?? "first",
- trimmed
+ trimmed.count
))
self.onUtterance?(self.kind, turnID, trimmed, start, end)
}
diff --git a/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTranscriptionCoordinator.swift b/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTranscriptionCoordinator.swift
index f49f74c5..398a840e 100644
--- a/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTranscriptionCoordinator.swift
+++ b/Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTranscriptionCoordinator.swift
@@ -11,14 +11,27 @@ import Foundation
final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable {
/// Two `StreamingEouAsrManager` instances measured at ~470MB RSS each. Below this, skip live
/// entirely rather than risk contending with the recording or the later batch model.
- static let minimumPhysicalMemoryBytes: UInt64 = 8 * 1_024 * 1_024 * 1_024
+ static let minimumPhysicalMemoryBytes: UInt64 = 8 * 1024 * 1024 * 1024
static let echoWindowSeconds: TimeInterval = 20
static func isMemorySufficient(physicalMemory: UInt64) -> Bool {
- physicalMemory >= Self.minimumPhysicalMemoryBytes
+ physicalMemory >= self.minimumPhysicalMemoryBytes
}
private let stateLock = NSLock()
+ private let diagnosticsEnabled: Bool = {
+ #if DEBUG
+ ProcessInfo.processInfo.environment["FLUIDVOICE_MEETING_LIVE_DIAGNOSTICS"] == "1"
+ #else
+ false
+ #endif
+ }()
+
+ private func diag(_ message: @autoclosure () -> String) {
+ guard self.diagnosticsEnabled else { return }
+ DebugLogger.shared.info(message(), source: "MeetingLive")
+ }
+
private var snapshot: MeetingLiveTranscriptSnapshot = .empty
private var recentThemUtterances: [MeetingLiveUtterance] = []
private var offerCounts: [MeetingAudioTrackKind: Int] = [:]
@@ -43,26 +56,23 @@ final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable
func setMicrophoneCaptureMethod(_ method: MeetingAudioTrackCaptureMethod?) {
self.stateLock.withLock { self.microphoneCaptureMethod = method }
- DebugLogger.shared.info(
- "[live/ECHO] setter-armed captureMethod=\(method.map(String.init(describing:)) ?? "nil")",
- source: "MeetingLive"
+ self.diag(
+ "[live/ECHO] setter-armed captureMethod=\(method.map(String.init(describing:)) ?? "nil")"
)
}
func start(mode: MeetingCaptureMode) {
#if arch(arm64)
guard Self.isMemorySufficient(physicalMemory: ProcessInfo.processInfo.physicalMemory) else {
- DebugLogger.shared.info(
- "Live meeting transcription skipped: below memory threshold.",
- source: "MeetingLiveTranscriptionCoordinator"
+ self.diag(
+ "Live meeting transcription skipped: below memory threshold."
)
self.publish { $0.settingAvailability(.unavailable(reason: "Not enough memory available for live captions.")) }
return
}
- DebugLogger.shared.info(
- "[live] starting engines mode=\(mode) physicalMemory=\(ProcessInfo.processInfo.physicalMemory / 1_073_741_824)GB",
- source: "MeetingLive"
+ self.diag(
+ "[live] starting engines mode=\(mode) physicalMemory=\(ProcessInfo.processInfo.physicalMemory / 1_073_741_824)GB"
)
let microphone = MeetingLiveTrackEngine(kind: .microphone)
self.stateLock.withLock { self.microphoneEngine = microphone }
@@ -84,7 +94,7 @@ final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable
func offer(kind: MeetingAudioTrackKind, sampleBuffer: CMSampleBuffer) {
#if arch(arm64)
guard let sample = MeetingLiveSampleCopy.copy(sampleBuffer) else {
- DebugLogger.shared.info("[live/tee] sample copy FAILED kind=\(kind)", source: "MeetingLive")
+ self.diag("[live/tee] sample copy FAILED kind=\(kind)")
return
}
self.originBox.establish(sample.pts)
@@ -92,14 +102,13 @@ final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable
let count = (self.offerCounts[kind] ?? 0) + 1
self.offerCounts[kind] = count
if count == 1 {
- DebugLogger.shared.info(
- "[live/tee] first sample kind=\(kind) pts=\(String(format: "%.3f", sample.pts.seconds)) sr=\(sample.buffer.format.sampleRate) ch=\(sample.buffer.format.channelCount)",
- source: "MeetingLive"
+ self.diag(
+ "[live/tee] first sample kind=\(kind) pts=\(String(format: "%.3f", sample.pts.seconds)) sr=\(sample.buffer.format.sampleRate) ch=\(sample.buffer.format.channelCount)"
)
}
let engine = kind == .microphone ? self.microphoneEngine : self.applicationEngine
if engine == nil, count == 1 {
- DebugLogger.shared.info("[live/tee] no engine for kind=\(kind) — samples discarded", source: "MeetingLive")
+ self.diag("[live/tee] no engine for kind=\(kind) — samples discarded")
}
return engine
}
@@ -118,13 +127,12 @@ final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable
}
return (self.microphoneEngine, self.applicationEngine)
}
- DebugLogger.shared.info(
- "[live] stopping engines offers=\(self.offerCounts.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: " "))",
- source: "MeetingLive"
+ self.diag(
+ "[live] stopping engines offers=\(self.stateLock.withLock { self.offerCounts.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: " ") })"
)
await microphone?.stop()
await application?.stop()
- DebugLogger.shared.info("[live] engines stopped, models released", source: "MeetingLive")
+ self.diag("[live] engines stopped, models released")
#endif
}
@@ -167,29 +175,16 @@ final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable
let updated: MeetingLiveTranscriptSnapshot = self.stateLock.withLock {
if speaker == .you {
- if self.microphoneCaptureMethod == .voiceProcessing {
- DebugLogger.shared.info(
- "[live/ECHO] skipped (voiceProcessing) mic utterance [\(String(format: "%.2f", startSeconds))] text=\(text)",
- source: "MeetingLive"
- )
- } else {
+ if self.microphoneCaptureMethod != .voiceProcessing {
let recentThem = MeetingLiveEchoFilter.recentThemText(
from: self.recentThemUtterances,
before: startSeconds,
windowSeconds: Self.echoWindowSeconds
)
if MeetingLiveEchoFilter.shouldSuppress(micText: text, recentThemText: recentThem) {
- DebugLogger.shared.info(
- "[live/ECHO] SUPPRESSED mic utterance [\(String(format: "%.2f", startSeconds))] text=\(text)",
- source: "MeetingLive"
- )
self.snapshot = self.snapshot.settingPartial(nil, for: .you).markingFinalized(id)
return self.snapshot
}
- DebugLogger.shared.info(
- "[live/ECHO] kept mic utterance [\(String(format: "%.2f", startSeconds))] text=\(text)",
- source: "MeetingLive"
- )
}
} else {
let record = MeetingLiveUtterance(id: id, speaker: .them, text: text, start: startSeconds, end: endSeconds)
@@ -204,7 +199,7 @@ final nonisolated class MeetingLiveTranscriptionCoordinator: @unchecked Sendable
}
private func handleDegraded(kind: MeetingAudioTrackKind, reason: String) {
- DebugLogger.shared.info("[live] DEGRADED kind=\(kind) reason=\(reason)", source: "MeetingLive")
+ DebugLogger.shared.warning("Live captions degraded: \(reason)", source: "MeetingLive")
self.publish { $0.settingAvailability(.degraded(reason: reason)) }
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingLiveTranscriptionTests.swift b/Tests/FluidDictationIntegrationTests/MeetingLiveTranscriptionTests.swift
index c8047a1e..94b17502 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingLiveTranscriptionTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingLiveTranscriptionTests.swift
@@ -1,5 +1,6 @@
-@testable import FluidVoice_Debug
+import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -9,8 +10,8 @@ final class MeetingModelPreparationQueueTests: XCTestCase {
var active = 0
var maximum = 0
var completed = 0
- func enter() { active += 1; maximum = max(maximum, active) }
- func leave() { active -= 1; completed += 1 }
+ func enter() { self.active += 1; self.maximum = max(self.maximum, self.active) }
+ func leave() { self.active -= 1; self.completed += 1 }
}
func testConcurrentPreparationsNeverOverlap() async throws {
@@ -231,7 +232,9 @@ final class MeetingLiveBoundedQueueTests: XCTestCase {
func testSaturationDropsTheOldestElement() {
let queue = MeetingLiveBoundedQueue<Int>(capacity: 3)
- for value in 0..<3 { _ = queue.enqueue(value) }
+ for value in 0..<3 {
+ _ = queue.enqueue(value)
+ }
let dropped = queue.enqueue(3)
XCTAssertTrue(dropped)
// 0 was the oldest; it must be gone, newest (3) must be present.
@@ -247,7 +250,9 @@ final class MeetingLiveBoundedQueueTests: XCTestCase {
func testHeavySaturationNeverGrowsPastCapacity() {
let queue = MeetingLiveBoundedQueue<Int>(capacity: 4)
- for value in 0..<1000 { _ = queue.enqueue(value) }
+ for value in 0..<1000 {
+ _ = queue.enqueue(value)
+ }
let drained = queue.drainAll()
XCTAssertEqual(drained.count, 4)
XCTAssertEqual(drained, [996, 997, 998, 999])
@@ -258,9 +263,11 @@ final class MeetingLiveEchoFilterTests: XCTestCase {
func testMicUtteranceMatchingRecentThemTextIsSuppressed() {
let them = [
MeetingLiveUtterance(
- id: UUID(), speaker: .them,
+ id: UUID(),
+ speaker: .them,
text: "let's push the release to next Tuesday afternoon",
- start: 10, end: 14
+ start: 10,
+ end: 14
),
]
let recent = MeetingLiveEchoFilter.recentThemText(from: them, before: 15, windowSeconds: 20)
@@ -295,7 +302,7 @@ final class MeetingLiveEchoFilterTests: XCTestCase {
final class MeetingLiveMemoryGateTests: XCTestCase {
func testBelowThresholdDisablesLive() {
- let oneGigabyte: UInt64 = 1 * 1_024 * 1_024 * 1_024
+ let oneGigabyte: UInt64 = 1 * 1024 * 1024 * 1024
XCTAssertFalse(MeetingLiveTranscriptionCoordinator.isMemorySufficient(physicalMemory: oneGigabyte))
}
@@ -303,7 +310,7 @@ final class MeetingLiveMemoryGateTests: XCTestCase {
XCTAssertTrue(MeetingLiveTranscriptionCoordinator.isMemorySufficient(
physicalMemory: MeetingLiveTranscriptionCoordinator.minimumPhysicalMemoryBytes
))
- XCTAssertTrue(MeetingLiveTranscriptionCoordinator.isMemorySufficient(physicalMemory: 64 * 1_024 * 1_024 * 1_024))
+ XCTAssertTrue(MeetingLiveTranscriptionCoordinator.isMemorySufficient(physicalMemory: 64 * 1024 * 1024 * 1024))
}
}
@@ -319,8 +326,12 @@ final class MeetingLiveProvisionalContainmentTests: XCTestCase {
let speakerID = UUID()
session.speakers = [
MeetingSessionSpeaker(
- id: speakerID, displayName: "Speaker 1", diarizationClusterID: nil,
- trackKind: .microphone, isLocalUser: true, identityCandidates: []
+ id: speakerID,
+ displayName: "Speaker 1",
+ diarizationClusterID: nil,
+ trackKind: .microphone,
+ isLocalUser: true,
+ identityCandidates: []
),
]
session.transcriptSegments = [
@@ -370,3 +381,117 @@ final class MeetingOverlayVisibilityTests: XCTestCase {
))))
}
}
+
+#if arch(arm64)
+@MainActor
+final class MeetingLiveStartupCancellationTests: XCTestCase {
+ private actor SuspendedRecognizer: MeetingLiveRecognizer {
+ let didBeginInstalling: @Sendable () -> Void
+ let didPrepare: @Sendable () -> Void
+ private var continuation: CheckedContinuation<Void, Never>?
+ private var eouCallback: (@Sendable (String) -> Void)?
+ private var partialCallback: (@Sendable (String) -> Void)?
+ private(set) var installationCount = 0
+
+ init(didBeginInstalling: @escaping @Sendable () -> Void, didPrepare: @escaping @Sendable () -> Void) {
+ self.didBeginInstalling = didBeginInstalling
+ self.didPrepare = didPrepare
+ }
+
+ func setEouCallback(_ callback: @escaping @Sendable (String) -> Void) async {
+ self.eouCallback = callback
+ self.installationCount += 1
+ await withCheckedContinuation { continuation in
+ self.continuation = continuation
+ self.didBeginInstalling()
+ }
+ }
+
+ func setPartialTranscriptCallback(_ callback: @escaping @Sendable (String) -> Void) async {
+ self.partialCallback = callback
+ }
+
+ func resumeInstallation() {
+ self.continuation?.resume()
+ self.continuation = nil
+ }
+
+ func emitStaleCallbacks() {
+ self.partialCallback?("late partial")
+ self.eouCallback?("late final")
+ }
+
+ func prepareModels() async throws { self.didPrepare() }
+ func appendAudio(_ buffer: AVAudioPCMBuffer) async throws {}
+ func processBufferedAudio() async throws {}
+ func reset() async {}
+ }
+
+ func testStopDuringCallbackInstallationCannotLaunchModelsOrPublish() async {
+ let installing = expectation(description: "callback installation suspended")
+ let noPrepare = expectation(description: "stopped engine must not load models")
+ noPrepare.isInverted = true
+ let noPublish = expectation(description: "stopped engine must not publish")
+ noPublish.isInverted = true
+ let recognizer = SuspendedRecognizer(
+ didBeginInstalling: { installing.fulfill() },
+ didPrepare: { noPrepare.fulfill() }
+ )
+ let engine = MeetingLiveTrackEngine(kind: .microphone, recognizer: recognizer)
+ await engine.configure(
+ onPartial: { _, _, _, _, _ in noPublish.fulfill() },
+ onUtterance: { _, _, _, _, _ in noPublish.fulfill() },
+ onDegraded: { _, _ in noPublish.fulfill() },
+ onReady: { _ in noPublish.fulfill() }
+ )
+ let starting = Task { await engine.start() }
+ await fulfillment(of: [installing], timeout: 2)
+ await engine.stop()
+ await recognizer.resumeInstallation()
+ await starting.value
+ await recognizer.emitStaleCallbacks()
+ await engine.start() // A delayed coordinator launch cannot restart a stopped engine either.
+ await fulfillment(of: [noPrepare, noPublish], timeout: 0.1)
+ let installationCount = await recognizer.installationCount
+ XCTAssertEqual(installationCount, 1)
+ await engine.stop()
+ }
+
+ func testUninterruptedStartupStillLoadsAndBecomesReady() async {
+ let installing = expectation(description: "installing callbacks")
+ let prepared = expectation(description: "models prepared")
+ let ready = expectation(description: "captions ready")
+ let recognizer = SuspendedRecognizer(
+ didBeginInstalling: { installing.fulfill() },
+ didPrepare: { prepared.fulfill() }
+ )
+ let engine = MeetingLiveTrackEngine(kind: .microphone, recognizer: recognizer)
+ await engine.configure(
+ onPartial: { _, _, _, _, _ in },
+ onUtterance: { _, _, _, _, _ in },
+ onDegraded: { _, _ in XCTFail("Unexpected degradation") },
+ onReady: { _ in ready.fulfill() }
+ )
+ let starting = Task { await engine.start() }
+ await fulfillment(of: [installing], timeout: 2)
+ await recognizer.resumeInstallation()
+ await starting.value
+ await fulfillment(of: [prepared, ready], timeout: 2)
+ await engine.stop()
+ }
+
+ func testStopBeforeLaunchPreventsCallbackInstallation() async {
+ let noInstall = expectation(description: "stopped engine must not install callbacks")
+ noInstall.isInverted = true
+ let recognizer = SuspendedRecognizer(didBeginInstalling: { noInstall.fulfill() }, didPrepare: {})
+ let engine = MeetingLiveTrackEngine(kind: .microphone, recognizer: recognizer)
+ await engine.stop()
+ let starting = Task { await engine.start() }
+ await fulfillment(of: [noInstall], timeout: 0.1)
+ // Unblock a regression so a failed assertion cannot leak a suspended task.
+ await recognizer.resumeInstallation()
+ await starting.value
+ await engine.stop()
+ }
+}
+#endif