// LiveSessionTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation import LyrebirdSynth @testable import LyrebirdLiveCompile #if os(macOS) @MainActor @Suite("LiveSession") struct LiveSessionTests { /// NRT engine — `start()` is not called. We never pull audio. The session /// holds a reference; the snippet reads `engine.sampleRate` via `context`. private func makeEngine() -> SynthesisEngine { SynthesisEngine( blockSize: 64, controlBlockSize: 16, sampleRate: 48_000, numOutputChannels: 2, numInputChannels: 0, numAudioBuses: 16, numControlBuses: 16, eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, driver: OfflineDriver() ) } @Test func buildDirDiscoveryFindsLyrebirdDylib() throws { let buildDir: URL = try #require(LiveSession.currentBuildDir()) let dylib: URL = buildDir.appendingPathComponent("libLyrebirdDynamic.dylib") #expect(FileManager.default.fileExists(atPath: dylib.path)) } @Test func snippetReadsEngineSampleRateViaContext() throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) try session.compileAndRun("context.reportSampleRate(context.engine.sampleRate)") #expect(session.reportedSampleRate == 48_000) } @Test func snippetReportMessageRoundTripsThroughSession() throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) try session.compileAndRun("context.reportMessage(\"hello from snippet\")") #expect(session.lastSnippetMessage == "hello from snippet") } @Test func reEvaluationClearsLastMessageStateThenReruns() throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) try session.compileAndRun("context.reportMessage(\"first\")") #expect(session.lastSnippetMessage == "first") try session.compileAndRun("context.reportMessage(\"second\")") #expect(session.lastSnippetMessage == "second") } @Test func asyncCompileAndRunRoundTripsMessage() async throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) _ = try await session.compileAndRunAsync( "context.reportMessage(\"async hello\")" ) #expect(session.lastSnippetMessage == "async hello") } /// Runtime guard: a snippet driven through `compileAndRunAsync` that calls /// `context.play(_:)` actually adds and tracks a synth. `context.play` → `engine.add` is /// `@MainActor`; `compileAndRunAsync` resumes the snippet entry on the main /// actor (not the nonisolated executor it suspends on), so this exercises that hop. @Test func asyncCompileAndRunPlaysAndTracksSynth() async throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) #expect(session.trackedSynthCount == 0) let body: String = """ final class SineSynth: SynthesizerBase { override func build() { output(bus: 0, source: OscSin.Audio(freq: 440, mul: 0.1)) } } _ = context.play(SineSynth()) """ _ = try await session.compileAndRunAsync(body) #expect(session.trackedSynthCount == 1) } /// Bare-graph `context.play { … }` — no `SynthesizerBase` subclass — adds /// and tracks a synth, exercising the `ClosureSynthesizer` forwarder. @Test func closurePlayAddsAndTracksBareGraph() async throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) #expect(session.trackedSynthCount == 0) _ = try await session.compileAndRunAsync( "context.play { OscSin.Audio(freq: 440, mul: 0.1) }" ) #expect(session.trackedSynthCount == 1) } // MARK: - Named slots @Test func assignSlotReplacesInPlaceKeepingOneVoice() throws { let session: LiveSession = LiveSession(engine: makeEngine()) let first: ClosureSynthesizer = ClosureSynthesizer { 0.1 } try session.engine.add(first) session.assignSlot("bass", synth: first) #expect(session.slotCount == 1) #expect(session.slotNames == ["bass"]) // Re-assigning the same name replaces the voice — count stays 1. let second: ClosureSynthesizer = ClosureSynthesizer { 0.2 } try session.engine.add(second) session.assignSlot("bass", synth: second) #expect(session.slotCount == 1) // Slots are separate from the anonymous tracked list. #expect(session.trackedSynthCount == 0) } @Test func clearSlotRemovesNamedSlotOnly() throws { let session: LiveSession = LiveSession(engine: makeEngine()) let a: ClosureSynthesizer = ClosureSynthesizer { 0.1 } let b: ClosureSynthesizer = ClosureSynthesizer { 0.2 } try session.engine.add(a); session.assignSlot("a", synth: a) try session.engine.add(b); session.assignSlot("b", synth: b) #expect(session.slotCount == 2) #expect(session.clearSlot("a") == true) #expect(session.slotCount == 1) #expect(session.slotNames == ["b"]) // Clearing an empty slot is a no-op. #expect(session.clearSlot("missing") == false) #expect(session.slotCount == 1) } @Test func clearSlotsRemovesAllSlots() throws { let session: LiveSession = LiveSession(engine: makeEngine()) let a: ClosureSynthesizer = ClosureSynthesizer { 0.1 } let b: ClosureSynthesizer = ClosureSynthesizer { 0.2 } try session.engine.add(a); session.assignSlot("a", synth: a) try session.engine.add(b); session.assignSlot("b", synth: b) #expect(session.slotCount == 2) session.clearSlots() #expect(session.slotCount == 0) } @Test func clearTrackedLeavesSlotsIntact() throws { // Slots must survive a non-additive re-evaluation (that is the whole // point) — `clearTracked()` clears only the anonymous list. let session: LiveSession = LiveSession(engine: makeEngine()) let anon: ClosureSynthesizer = ClosureSynthesizer { 0.1 } let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 } try session.engine.add(anon); session.track(anon) try session.engine.add(slotted); session.assignSlot("bass", synth: slotted) #expect(session.trackedSynthCount == 1) #expect(session.slotCount == 1) session.clearTracked() #expect(session.trackedSynthCount == 0) #expect(session.slotCount == 1) } // MARK: - Swap quantization @Test func quantizedSwapSchedulesAndReportsPendingBeat() throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) session.swapClock = LyrebirdClock(engine: engine, bpm: 120) session.swapQuantize = .nextBeat try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 }) #expect(session.slotCount == 1) // Offline clock sits at beat 0, so the swap targets beat 1 and is pending. #expect(session.pendingSwapBeat == 1.0) } @Test func immediateSwapReportsNoPendingBeat() throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) // No clock set → immediate regardless of the quantize mode. session.swapQuantize = .nextBeat try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 }) #expect(session.slotCount == 1) #expect(session.pendingSwapBeat == nil) } /// A running engine: two quantized swaps of the same slot must leave exactly /// one voice in the node tree once the scheduled events have fired. @Test func quantizedSwapReplaceEndsWithOneVoiceInTree() throws { let engine: SynthesisEngine = makeEngine() try engine.start() let session: LiveSession = LiveSession(engine: engine) session.swapClock = LyrebirdClock(engine: engine, bpm: 120) session.swapQuantize = .nextBeat try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 }) try session.swapSlot("bass", synth: ClosureSynthesizer { 0.2 }) #expect(session.slotCount == 1) // Beat 1 @ 120 bpm / 48 kHz = 24000 samples; 64-sample blocks. for _: Int in 0..<500 { engine.processBlock(inputSamples: []) } #expect(engine.synthesizerCount == 1) } /// Regression: clearing a slot *before* its scheduled quantized add fires /// must not orphan the pending voice. The removal is scheduled no earlier /// than the add, so the add and remove cancel out — the tree ends empty. @Test func clearSlotsBeforeScheduledSwapFiresLeavesNoOrphan() throws { let engine: SynthesisEngine = makeEngine() try engine.start() let session: LiveSession = LiveSession(engine: engine) session.swapClock = LyrebirdClock(engine: engine, bpm: 120) session.swapQuantize = .nextBeat try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 }) session.clearSlots() #expect(session.slotCount == 0) for _: Int in 0..<500 { engine.processBlock(inputSamples: []) } #expect(engine.synthesizerCount == 0) } /// End-to-end through the real swiftc pipeline: `context.play(slot:) { }` /// installs one voice, and a non-additive re-run of the same slot replaces /// it in place (still one voice) — the slot survives the non-additive clear. @Test func closureSlotPlayReplacesAcrossReevaluations() async throws { let session: LiveSession = LiveSession(engine: makeEngine()) _ = try await session.compileAndRunAsync( "context.play(slot: \"bass\") { OscSin.Audio(freq: 110, mul: 0.1) }" ) #expect(session.slotCount == 1) #expect(session.trackedSynthCount == 0) _ = try await session.compileAndRunAsync( "context.play(slot: \"bass\") { OscSin.Audio(freq: 220, mul: 0.1) }" ) #expect(session.slotCount == 1) } @Test func asyncCompileFailureSurfacesDiagnosticsThroughSnippetCompileFailed() async { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) do { _ = try await session.compileAndRunAsync("let x: Int = \"nope\"\n") Issue.record("expected snippetCompileFailed") } catch let LiveSessionError.snippetCompileFailed(diags, _) { #expect(diags.isEmpty == false) #expect(diags.contains(where: { $0.severity == .error })) } catch { Issue.record("unexpected error: \(error)") } } @Test func additiveReEvaluationDoesNotClearTrackedSynths() throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) // No synths added in either run; just verify the additive branch executes // without nuking session state. try session.compileAndRun("context.reportMessage(\"a\")", additive: false) try session.compileAndRun("context.reportMessage(\"b\")", additive: true) #expect(session.lastSnippetMessage == "b") #expect(session.trackedSynthCount == 0) } @Test func discoverSPMModuleMapsMatchesTopLevelBuildDirMapsAndDedups() throws { // Fixture mirroring the `swift build` layout: a C target's generated map // sits at `/.build/module.modulemap`, while a Swift // target's map is one level deeper (`.build/include/module.modulemap`) // and must NOT be picked up. let fm: FileManager = FileManager.default let root: URL = fm.temporaryDirectory .appendingPathComponent("spm-maps-\(UUID().uuidString)", isDirectory: true) defer { try? fm.removeItem(at: root) } let cTargetMap: URL = root .appendingPathComponent("LyrebirdC.build", isDirectory: true) .appendingPathComponent("module.modulemap") let swiftTargetMap: URL = root .appendingPathComponent("LyrebirdSynth.build", isDirectory: true) .appendingPathComponent("include", isDirectory: true) .appendingPathComponent("module.modulemap") let nonBuildMap: URL = root .appendingPathComponent("Modules", isDirectory: true) .appendingPathComponent("module.modulemap") for url: URL in [cTargetMap, swiftTargetMap, nonBuildMap] { try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) try "module X {}".write(to: url, atomically: true, encoding: .utf8) } // Pass the same path twice to exercise dedup. let found: [URL] = LiveSession.discoverSPMModuleMaps(in: [root, root]) #expect(found.count == 1) // Suffix match, not full-path equality: the temp dir resolves through // the `/var` → `/private/var` symlink, so `contentsOfDirectory` returns // a differently-prefixed but equivalent path. #expect(found.first?.path.hasSuffix("LyrebirdC.build/module.modulemap") == true) } // MARK: - Session reset + snippet accounting @Test func resetAllClearsTrackedAndSlots() throws { let session: LiveSession = LiveSession(engine: makeEngine()) let anon: ClosureSynthesizer = ClosureSynthesizer { 0.1 } let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 } try session.engine.add(anon); session.track(anon) try session.engine.add(slotted); session.assignSlot("bass", synth: slotted) #expect(session.trackedSynthCount == 1) #expect(session.slotCount == 1) session.resetAll() #expect(session.trackedSynthCount == 0) #expect(session.slotCount == 0) } @Test func resetAllClearsPendingSwap() throws { let engine: SynthesisEngine = makeEngine() let session: LiveSession = LiveSession(engine: engine) session.swapClock = LyrebirdClock(engine: engine, bpm: 120) session.swapQuantize = .nextBeat try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 }) #expect(session.pendingSwapBeat == 1.0) session.resetAll() #expect(session.pendingSwapBeat == nil) #expect(session.slotCount == 0) } @Test func loadedSnippetCountGrowsPerCompile() async throws { let session: LiveSession = LiveSession(engine: makeEngine()) #expect(session.loadedSnippetCount == 0) _ = try await session.compileAndRunAsync("context.reportMessage(\"a\")") #expect(session.loadedSnippetCount == 1) _ = try await session.compileAndRunAsync("context.reportMessage(\"b\")") #expect(session.loadedSnippetCount == 2) } // MARK: - Module-cache prewarm @Test func prewarmCompletesAndSetsFlag() async { let session: LiveSession = LiveSession(engine: makeEngine()) #expect(session.isPrewarmed == false) // Await the detached prewarm task (a real `swiftc -typecheck` that warms // swiftc's default module cache — cold ~2–3 s the first time). await session.prewarm().value #expect(session.isPrewarmed == true) } @Test func prewarmIsIdempotentAfterCompletion() async { let session: LiveSession = LiveSession(engine: makeEngine()) await session.prewarm().value #expect(session.isPrewarmed == true) // A second call is a no-op (already warmed) and returns immediately. await session.prewarm().value #expect(session.isPrewarmed == true) } @Test func swiftcArgsIncludeImportLibrarySearchAndRpathFlags() { let buildDir: URL = URL(fileURLWithPath: "/tmp/fake-build") let session: LiveSession = LiveSession( engine: makeEngine(), importPaths: [buildDir], librarySearchPaths: [buildDir], libraries: ["Lyrebird"], rpaths: [buildDir] ) // Indirectly verify makeSwiftcArgs via attempting a compile that will // fail with the fake paths but expose the flags through the stderr. do { _ = try session.compileAndRun("// empty body") Issue.record("expected compile failure with fake build dir") } catch let LiveSessionError.snippetCompileFailed(_, underlying) { guard case .compileFailed(_, let stderr) = underlying else { Issue.record("expected compileFailed underlying, got \(underlying)") return } // swiftc rejects with "no such module 'Lyrebird'" — that's the proof // the -I /tmp/fake-build flag was passed and searched. #expect(stderr.contains("Lyrebird") || stderr.contains("module")) } catch { Issue.record("expected snippetCompileFailed, got \(error)") } } } #endif