8519cabe42
Additive conveniences to the macOS-only Live Scratch editor. No changes to existing public API. - Run Selection (⌘E): evaluate just the highlighted text, additively. - Graceful slot release: context.release(slot:) / free(slot:). - Engine panel: live oscilloscope (ScopeCapture) + CPU avg/peak + counts. - Reset Session / Restart to Reclaim Memory. - Always-open console panel (report messages + errors with line:col). - Faster typing: debounced highlight, updateNSView fast-path, publish guards. - Manual code completion (Esc / F5), no auto-trigger on `.`; completion replaces the partial word, not the receiver expression. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
319 lines
13 KiB
Swift
319 lines
13 KiB
Swift
// LyrebirdScratchModelTests.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
#if os(macOS)
|
|
import Testing
|
|
import Foundation
|
|
import LyrebirdSynth
|
|
@testable import LyrebirdLiveCompile
|
|
@testable import LyrebirdLiveCompileUI
|
|
|
|
@Suite("LyrebirdScratchModel")
|
|
@MainActor
|
|
struct LyrebirdScratchModelTests {
|
|
|
|
/// NRT engine — `start()` is never called. Matches the LiveSession test
|
|
/// fixture so we exercise the same compile + dlopen + entry path.
|
|
private func makeSession() -> LiveSession {
|
|
let engine: SynthesisEngine = SynthesisEngine(
|
|
blockSize: 64,
|
|
controlBlockSize: 16,
|
|
sampleRate: 48_000,
|
|
numOutputChannels: 2,
|
|
numInputChannels: 0,
|
|
numAudioBuses: 16,
|
|
numControlBuses: 16,
|
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
|
driver: OfflineDriver()
|
|
)
|
|
return LiveSession(engine: engine)
|
|
}
|
|
|
|
@Test
|
|
func defaultPlaceholderMentionsBothShortcuts() {
|
|
let placeholder: String = LyrebirdScratchModel.defaultPlaceholder
|
|
#expect(placeholder.contains("⌘↩"))
|
|
#expect(placeholder.contains("⌘⇧↩"))
|
|
#expect(placeholder.contains("context"))
|
|
}
|
|
|
|
@Test
|
|
func initSeedsTextAndZeroTrackedSynths() {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// hi")
|
|
#expect(model.text == "// hi")
|
|
#expect(model.trackedSynthCount == 0)
|
|
#expect(model.diagnostics.isEmpty)
|
|
#expect(model.statusMessage.isEmpty)
|
|
#expect(model.isCompiling == false)
|
|
#expect(model.documentURL == nil)
|
|
}
|
|
|
|
@Test
|
|
func runValidSnippetClearsDiagnosticsAndReportsReplaced() async {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
|
session: session,
|
|
initialText: "context.reportMessage(\"hello\")"
|
|
)
|
|
let ok: Bool = await model.run(additive: false)
|
|
#expect(ok)
|
|
#expect(model.diagnostics.isEmpty)
|
|
#expect(model.statusMessage.contains("replaced"))
|
|
#expect(model.statusMessage.contains("Tracked synths: 0"))
|
|
// The report message is drained from the session into the console.
|
|
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello" })
|
|
#expect(session.lastSnippetMessage == nil) // drained
|
|
#expect(model.isCompiling == false)
|
|
}
|
|
|
|
@Test
|
|
func runInvalidSnippetSurfacesUserCoordinateDiagnostics() async throws {
|
|
let session: LiveSession = makeSession()
|
|
// `let x: Int = "nope"` — guaranteed type-check error on the first row
|
|
// of the user body. The diagnostic parser maps the wrapped-source line
|
|
// back to user line 1.
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
|
session: session,
|
|
initialText: "let x: Int = \"nope\"\n"
|
|
)
|
|
let ok: Bool = await model.run(additive: false)
|
|
#expect(ok == false)
|
|
#expect(model.diagnostics.isEmpty == false)
|
|
let first: Diagnostic = try #require(model.diagnostics.first)
|
|
#expect(first.severity == .error)
|
|
#expect(first.line == 1)
|
|
#expect(model.statusMessage.contains("Compile failed"))
|
|
#expect(model.isCompiling == false)
|
|
}
|
|
|
|
@Test
|
|
func clearTrackedZerosCountAndUpdatesStatus() async {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "")
|
|
await model.run(additive: false)
|
|
model.clearTracked()
|
|
#expect(model.trackedSynthCount == 0)
|
|
#expect(model.statusMessage == "Cleared all synths (tracked + slots).")
|
|
}
|
|
|
|
@Test
|
|
func concurrentRunsCollapseToOneCompile() async {
|
|
// Both `async let` tasks invoke `model.run(...)`, but the model is
|
|
// `@MainActor`-isolated so they cannot truly overlap. The first call
|
|
// sets `isCompiling = true` synchronously before its first `await`;
|
|
// when main resumes on the second call's body, the `isCompiling`
|
|
// guard sees the flag set and returns `false`. Deterministic with no
|
|
// wall-clock dependency.
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
|
session: session,
|
|
initialText: "context.reportMessage(\"x\")"
|
|
)
|
|
async let first: Bool = model.run(additive: false)
|
|
async let second: Bool = model.run(additive: false)
|
|
let results: [Bool] = await [first, second]
|
|
let successes: Int = results.filter { $0 }.count
|
|
let rejections: Int = results.filter { !$0 }.count
|
|
#expect(successes == 1)
|
|
#expect(rejections == 1)
|
|
#expect(model.isCompiling == false)
|
|
}
|
|
|
|
@Test
|
|
func saveRoundTripsTextAndSetsDocumentURL() throws {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "let a = 1\n")
|
|
let url: URL = FileManager.default
|
|
.temporaryDirectory
|
|
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
try model.save(to: url)
|
|
#expect(model.documentURL == url)
|
|
#expect(model.statusMessage.contains("Saved"))
|
|
let onDisk: String = try String(contentsOf: url, encoding: .utf8)
|
|
#expect(onDisk == "let a = 1\n")
|
|
}
|
|
|
|
@Test
|
|
func loadReplacesTextAndSetsDocumentURL() throws {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// stale\n")
|
|
let url: URL = FileManager.default
|
|
.temporaryDirectory
|
|
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
try "let b = 2\n".write(to: url, atomically: true, encoding: .utf8)
|
|
try model.load(from: url)
|
|
#expect(model.text == "let b = 2\n")
|
|
#expect(model.documentURL == url)
|
|
#expect(model.statusMessage.contains("Loaded"))
|
|
#expect(model.diagnostics.isEmpty)
|
|
}
|
|
|
|
@Test
|
|
func loadFromMissingURLThrowsAndPreservesText() {
|
|
let session: LiveSession = makeSession()
|
|
let original: String = "// keep me\n"
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: original)
|
|
let url: URL = FileManager.default
|
|
.temporaryDirectory
|
|
.appendingPathComponent("does_not_exist_\(UUID().uuidString).swift")
|
|
#expect(throws: (any Error).self) {
|
|
try model.load(from: url)
|
|
}
|
|
#expect(model.text == original)
|
|
#expect(model.documentURL == nil)
|
|
}
|
|
|
|
// MARK: - Re-eval readiness signal
|
|
|
|
@Test
|
|
func blankInitialTextIsEmptyState() {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: " \n\t")
|
|
#expect(model.reevalState == .empty)
|
|
#expect(model.reevalState.canEvaluate == false)
|
|
}
|
|
|
|
@Test
|
|
func nonBlankInitialTextIsDirtyState() {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// hi")
|
|
#expect(model.reevalState == .dirty)
|
|
#expect(model.reevalState.canEvaluate == true)
|
|
}
|
|
|
|
@Test
|
|
func editingBlankToContentGoesDirty() {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "")
|
|
#expect(model.reevalState == .empty)
|
|
model.text = "context.reportMessage(\"x\")"
|
|
#expect(model.reevalState == .dirty)
|
|
}
|
|
|
|
// A successful run drives the buffer `.dirty` → `.compiling` → `.clean`.
|
|
// (`LiveSession.discoverSPMModuleMaps` makes the snippet compile under a
|
|
// bare `swift test`, so a valid snippet reliably succeeds here.)
|
|
@Test
|
|
func runSettlesToCleanOnSuccess() async {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
|
session: session,
|
|
initialText: "context.reportMessage(\"x\")"
|
|
)
|
|
#expect(model.reevalState == .dirty)
|
|
let ok: Bool = await model.run(additive: false)
|
|
#expect(ok)
|
|
#expect(model.reevalState == .clean)
|
|
}
|
|
|
|
@Test
|
|
func editingAfterCleanReturnsToDirty() async {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
|
session: session,
|
|
initialText: "context.reportMessage(\"x\")"
|
|
)
|
|
let ok: Bool = await model.run(additive: false)
|
|
#expect(ok)
|
|
#expect(model.reevalState == .clean)
|
|
model.text = "context.reportMessage(\"y\")"
|
|
#expect(model.reevalState == .dirty)
|
|
}
|
|
|
|
@Test
|
|
func failedRunEntersFailedWithDiagnosticCount() async {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
|
session: session,
|
|
initialText: "let x: Int = \"nope\"\n"
|
|
)
|
|
await model.run(additive: false)
|
|
#expect(model.reevalState == .failed(diagnosticCount: model.diagnostics.count))
|
|
#expect(model.diagnostics.isEmpty == false)
|
|
}
|
|
|
|
@Test
|
|
func clearTrackedDropsBaselineToDirty() async {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
|
session: session,
|
|
initialText: "context.reportMessage(\"x\")"
|
|
)
|
|
let ok: Bool = await model.run(additive: false)
|
|
#expect(ok)
|
|
#expect(model.reevalState == .clean)
|
|
model.clearTracked()
|
|
// Nothing the buffer produced is still playing → a re-run is meaningful.
|
|
#expect(model.reevalState == .dirty)
|
|
}
|
|
|
|
@Test
|
|
func quantizedRunEntersQueuedThenSettles() async throws {
|
|
let session: LiveSession = makeSession()
|
|
session.swapClock = LyrebirdClock(engine: session.engine, bpm: 120)
|
|
session.swapQuantize = .nextBeat
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
|
session: session,
|
|
initialText: "context.play(slot: \"bass\") { OscSin.Audio(freq: 110, mul: 0.1) }"
|
|
)
|
|
let ok: Bool = await model.run(additive: false)
|
|
#expect(ok)
|
|
// Compiled + scheduled: queued until beat 1 (offline clock sits at 0).
|
|
if case .queued(let beat) = model.reevalState {
|
|
#expect(beat == 1.0)
|
|
} else {
|
|
Issue.record("expected .queued, got \(model.reevalState)")
|
|
}
|
|
// Still pending → refresh is a no-op.
|
|
model.refreshQueuedState()
|
|
if case .queued = model.reevalState {} else {
|
|
Issue.record("expected still .queued")
|
|
}
|
|
// Once the swap is no longer pending (here: clock dropped), it settles
|
|
// to .clean since the buffer is unchanged.
|
|
session.swapClock = nil
|
|
model.refreshQueuedState()
|
|
#expect(model.reevalState == .clean)
|
|
}
|
|
|
|
@Test
|
|
func clearTrackedFullResetAlsoClearsSlots() throws {
|
|
let session: LiveSession = makeSession()
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// x")
|
|
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
|
try session.engine.add(slotted)
|
|
session.assignSlot("bass", synth: slotted)
|
|
#expect(session.slotCount == 1)
|
|
// The model's "Clear Synths" is a full reset — tracked + slots.
|
|
model.clearTracked()
|
|
#expect(session.slotCount == 0)
|
|
}
|
|
|
|
@Test
|
|
func loadEntersDirtyEvenIfContentMatchesPriorRun() async throws {
|
|
let session: LiveSession = makeSession()
|
|
let source: String = "context.reportMessage(\"x\")"
|
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: source)
|
|
let ok: Bool = await model.run(additive: false)
|
|
#expect(ok)
|
|
#expect(model.reevalState == .clean)
|
|
// Load the *same* source from disk: the run baseline is dropped, so it
|
|
// reads as dirty rather than clean.
|
|
let url: URL = FileManager.default
|
|
.temporaryDirectory
|
|
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
try source.write(to: url, atomically: true, encoding: .utf8)
|
|
try model.load(from: url)
|
|
#expect(model.reevalState == .dirty)
|
|
}
|
|
}
|
|
|
|
#endif
|