// RoutineContextOnMainTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import Synchronization import Testing @testable @_spi(LyrebirdExtensions) import LyrebirdSynth /// `LyrebirdRoutineContext.onMain` — construct `@MainActor` synthesizers from inside a /// `@Sendable` routine/task body, instead of pre-allocating them outside and capturing. /// /// The suite is intentionally **not** `@MainActor`: `LyrebirdTask.run` blocks the calling /// thread, and the body's `ctx.add` / `ctx.onMain` hops need a free main thread to service /// them. Running the test off-main takes `waitUntilComplete()`'s plain-poll branch and leaves /// the main queue available — matching the existing `LyrebirdTask` suites. @Suite("RoutineContext.onMain") struct RoutineContextOnMainTests { /// Bounded wait for main-dispatched `build()` calls: 100 × 10 ms = 1 s ceiling. private let pollAttempts: Int = 100 private let pollIntervalSeconds: Double = 0.01 /// Counts `build()` calls so a test can prove a dynamically-constructed synth /// actually reached the engine. /// /// The counter is an `Atomic` because `build()` runs on the main thread (inside the /// `engine.add` that `ctx.add` dispatches) while the test reads it from the test thread — /// a plain `var` would be a data race even though the values would usually agree. final class CountingSynth: SynthesizerBase { // `nonisolated` is legal here (immutable `let` of a Sendable type) — it would be // rejected on a mutable stored property. Needed so the off-main test body can read it. nonisolated static let buildCount: Atomic = Atomic(0) let value: Double init(value: Double) { self.value = value super.init() } override func build() { CountingSynth.buildCount.wrappingAdd(1, ordering: .releasing) addOutputGenerator(Out.Audio(bus: 0, source: value)) } } @Test func onMainReturnsValueBuiltOnMainThread() { let engine: SynthesisEngine = makeTestEngine() let bodyWasOffMain: Ref = Ref(false) let workRanOnMain: Ref = Ref(false) LyrebirdTask.run(engine: engine) { ctx in // Establish the body is off-main first, so the assertion below proves a real // hop occurred rather than passing vacuously via the bridge's inline branch. bodyWasOffMain.value = !Thread.isMainThread workRanOnMain.value = ctx.onMain { Thread.isMainThread } } #expect(bodyWasOffMain.value) #expect(workRanOnMain.value) } @Test func onMainConstructsSynthesizerInsideBody() { let engine: SynthesisEngine = makeTestEngine() let expected: Int = 3 CountingSynth.buildCount.store(0, ordering: .releasing) // The body decides how many synths to make — impossible with pre-allocation. LyrebirdTask.run(engine: engine) { ctx in for i: Int in 0.. = Ref(false) struct ProbeError: Error {} LyrebirdTask.run(engine: engine) { ctx in do { let _: Int = try ctx.onMain { throw ProbeError() } } catch is ProbeError { caught.value = true } } #expect(caught.value) } @Test func onMainReturnsNonSendableReferenceType() { let engine: SynthesisEngine = makeTestEngine() let value: Ref = Ref(0) // `SynthesizerBase` subclasses are not Sendable — the box must carry one back anyway. LyrebirdTask.run(engine: engine) { ctx in let s: CountingSynth = ctx.onMain { CountingSynth(value: 7.0) } value.value = s.value } #expect(value.value == 7.0) } } /// Minimal reference box so a `@Sendable` task body can report a result back to the test. /// `@unchecked Sendable`: the body writes `value`, the test reads it only after /// `LyrebirdTask.run` has joined the body thread — no concurrent access. private final class Ref: @unchecked Sendable { var value: T init(_ value: T) { self.value = value } }