v1.4.2 release: live-coding editor — Run Selection, slot release, engine panel, console, manual completion

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>
This commit is contained in:
2026-07-21 11:09:30 -07:00
parent abc64df4d7
commit 8519cabe42
21 changed files with 1578 additions and 145 deletions
@@ -0,0 +1,43 @@
// MessageLogTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@MainActor
@Suite("LiveSession message log")
struct MessageLogTests {
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 accumulatesAndDrains() {
let session: LiveSession = makeSession()
session.appendMessage("a")
session.appendMessage("b")
#expect(session.lastSnippetMessage == "b") // last value, for tests
#expect(session.drainMessages() == ["a", "b"])
// Drained → empty.
#expect(session.lastSnippetMessage == nil)
#expect(session.drainMessages().isEmpty)
}
}
#endif
@@ -0,0 +1,63 @@
// ScopeAttachTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@MainActor
@Suite("LiveSession scope attach")
struct ScopeAttachTests {
private func makeEngine(outChannels: Int = 2) -> SynthesisEngine {
SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: outChannels,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
}
@Test func attachesStereoScopeByDefault() {
let engine: SynthesisEngine = makeEngine(outChannels: 2)
let session: LiveSession = LiveSession(engine: engine)
let scope: ScopeCapture? = session.scope
#expect(scope != nil)
#expect(scope?.buses == [0, 1])
// Installed on the engine so the RT thread writes to it.
#expect(engine.scopeTap === scope)
}
@Test func attachScopeFalseInstallsNothing() {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
#expect(session.scope == nil)
#expect(engine.scopeTap == nil)
}
@Test func monoEngineTapsOneBus() {
let engine: SynthesisEngine = makeEngine(outChannels: 1)
let session: LiveSession = LiveSession(engine: engine)
#expect(session.scope?.buses == [0])
}
@Test func reusesExistingTapRatherThanReplacing() {
let engine: SynthesisEngine = makeEngine()
let existing: ScopeCapture = ScopeCapture(buses: [0], bufferSize: 256)
engine.scopeTap = existing
let session: LiveSession = LiveSession(engine: engine) // attach on, but a tap exists
#expect(session.scope === existing)
#expect(engine.scopeTap === existing)
}
}
#endif
@@ -0,0 +1,94 @@
// SlotReleaseTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@MainActor
@Suite("LiveSession slot release")
struct SlotReleaseTests {
/// A synth whose graceful `release` succeeds (records the call) — stands in
/// for a gated `EnvGen` voice.
private final class GatedSynth: SynthesizerBase, @unchecked Sendable {
var released: Bool = false
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
override func release(engine: SynthesisEngine) throws { released = true }
}
/// A synth with no gate — inherits the default `release` that throws `.noGate`.
private final class GatelessSynth: SynthesizerBase, @unchecked Sendable {
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
}
private func makeStartedSession() throws -> LiveSession {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
let session: LiveSession = LiveSession(engine: engine)
try engine.start()
return session
}
@Test func releaseGatedSlotTriggersReleaseAndDropsHandle() throws {
let session: LiveSession = try makeStartedSession()
let voice: GatedSynth = GatedSynth()
try session.swapSlot("pad", synth: voice)
#expect(session.slotNames.contains("pad"))
let released: Bool = session.releaseSlot("pad")
#expect(released)
#expect(voice.released) // graceful release fired
#expect(session.slotNames.contains("pad") == false) // handle dropped, name free
// Safety net: the released voice moves to the tracked list so it stays
// reclaimable by resetAll() / Clear Synths even if it never self-frees.
#expect(session.trackedSynthCount == 1)
session.resetAll()
#expect(session.trackedSynthCount == 0)
session.engine.stop()
}
@Test func nameIsReusableAfterRelease() throws {
let session: LiveSession = try makeStartedSession()
try session.swapSlot("pad", synth: GatedSynth())
#expect(session.releaseSlot("pad"))
// The name is free again — a fresh voice claims the slot cleanly.
try session.swapSlot("pad", synth: GatedSynth())
#expect(session.slotNames.contains("pad"))
#expect(session.slotCount == 1)
session.engine.stop()
}
@Test func releaseGatelessSlotFailsAndKeepsHandle() throws {
let session: LiveSession = try makeStartedSession()
try session.swapSlot("bass", synth: GatelessSynth())
let released: Bool = session.releaseSlot("bass")
#expect(released == false)
// Not orphaned — still in the slot, still stoppable with a hard clear.
#expect(session.slotNames.contains("bass"))
#expect(session.clearSlot("bass"))
session.engine.stop()
}
@Test func releaseEmptySlotReturnsFalse() throws {
let session: LiveSession = try makeStartedSession()
#expect(session.releaseSlot("nothing-here") == false)
session.engine.stop()
}
}
#endif
@@ -0,0 +1,76 @@
// SnippetScheduledLoopTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
/// Proves the scratch editor runs *functional* Swift — a real `for` loop that
/// schedules a timed sequence — not just single-graph expressions.
@MainActor
@Suite("Snippet scheduled loop")
struct SnippetScheduledLoopTests {
@Test func loopSchedulesTenSelfFreeingTones() throws {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
controlBlockSize: 64,
sampleRate: 44_100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
let session: LiveSession = LiveSession(engine: engine)
try engine.start()
// A `for` loop that schedules ten short sine tones, 0.35 s apart. Each is
// a decaying amplitude envelope (`Line` with `doneAction: .freeNode`)
// times a sine, so it plays ~0.2 s and then frees itself — no manual
// cleanup, no blocking the main thread.
let snippet: String = """
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
440.0, 493.88, 523.25, 587.33, 659.25]
for i in 0..<10 {
let freq: Double = scale[i]
let tone = ClosureSynthesizer {
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
* OscSin.Audio(freq: freq)
}
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
catch { context.reportMessage("schedule failed: \\(error)") }
}
context.reportMessage("scheduled 10 tones")
"""
try session.compileAndRun(snippet)
// The `for` loop and the scheduling calls compiled and ran.
#expect(session.lastSnippetMessage == "scheduled 10 tones")
// Advance ~4.5 s of audio; the scheduled adds fire over time. (Each
// tone's `.freeNode` self-frees via the engine's async auto-free watcher
// in the running app — that background timer doesn't get a turn inside
// this synchronous processBlock loop, so here the tones accumulate; the
// auto-free path itself is covered by `AutoFreeOnDoneTests`.)
let blocks: Int = Int(4.5 * 44_100 / 512)
var peakActive: Int = 0
var producedAudio: Bool = false
for _ in 0..<blocks {
engine.processBlock(inputSamples: [])
peakActive = max(peakActive, engine.synthesizerCount)
if engine.audioBuses[0].contains(where: { $0 != 0 }) { producedAudio = true }
}
#expect(peakActive == 10, "all ten scheduled tones should have entered the tree over time")
#expect(producedAudio, "the scheduled tones should have written audio to the bus")
engine.stop()
}
}
#endif
@@ -64,7 +64,9 @@ struct LyrebirdScratchModelTests {
#expect(model.diagnostics.isEmpty)
#expect(model.statusMessage.contains("replaced"))
#expect(model.statusMessage.contains("Tracked synths: 0"))
#expect(session.lastSnippetMessage == "hello")
// 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)
}
@@ -0,0 +1,76 @@
// ScratchModelConsoleTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel console")
@MainActor
struct ScratchModelConsoleTests {
private func makeModel(text: String) -> LyrebirdScratchModel {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
}
@Test func successfulRunLogsInfo() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(model.consoleEntries.contains { $0.kind == .info })
}
@Test func failedRunLogsErrorEntries() async {
let model: LyrebirdScratchModel = makeModel(text: "NotAGenerator(freq: 1)")
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(model.consoleEntries.contains { $0.kind == .error })
#expect(model.consoleEntries.contains { $0.text.contains("NotAGenerator") })
}
@Test func reportMessagesAppearAsMessages() async {
// A DSL run pushes no messages; drive the log directly to prove the
// message → console wiring (drainMessages → .message entries).
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
model.session.appendMessage("hello from snippet")
_ = await model.run(additive: false)
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello from snippet" })
}
@Test func clearConsoleEmpties() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(!model.consoleEntries.isEmpty)
model.clearConsole()
#expect(model.consoleEntries.isEmpty)
}
@Test func resetSessionClearsConsole() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(!model.consoleEntries.isEmpty)
model.resetSession()
#expect(model.consoleEntries.isEmpty)
}
}
#endif
@@ -0,0 +1,58 @@
// ScratchModelResetTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel resetSession")
@MainActor
struct ScratchModelResetTests {
private func makeModel(text: String) -> LyrebirdScratchModel {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
}
@Test func resetStopsAudioAndClearsDiagnosticsButKeepsBuffer() async {
let source: String = "OscSin(freq: 440) * 0.1"
let model: LyrebirdScratchModel = makeModel(text: source)
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false) // tracked 1
#expect(model.trackedSynthCount == 1)
model.resetSession()
#expect(model.trackedSynthCount == 0) // audio stopped
#expect(model.diagnostics.isEmpty)
// Non-destructive: the user's buffer is preserved.
#expect(model.text == source)
#expect(model.statusMessage.contains("reset"))
}
@Test func resetLeavesAFreshDirtyBaseline() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false) // .clean
model.resetSession()
// The placeholder buffer was never run in this fresh session → .dirty.
#expect(model.reevalState == .dirty)
}
}
#endif
@@ -0,0 +1,104 @@
// ScratchModelRunSelectionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel run selection")
@MainActor
struct ScratchModelRunSelectionTests {
private func makeModel(text: String) -> LyrebirdScratchModel {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
}
@Test func hasSelectionReflectsNonWhitespaceSelection() {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
#expect(model.hasSelection == false)
model.updateSelection("OscSin(freq: 220) * 0.1")
#expect(model.hasSelection)
model.updateSelection(" \n ") // whitespace only
#expect(model.hasSelection == false)
model.updateSelection("")
#expect(model.hasSelection == false)
}
@Test func runSelectionWithNoSelectionIsNoOp() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
let ok: Bool = await model.runSelection()
#expect(ok == false)
#expect(model.trackedSynthCount == 0)
}
@Test func runSelectionAddsToRunningWithoutDisturbingBaseline() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
// Whole-buffer run establishes the baseline → clean, one synth.
_ = await model.run(additive: false)
#expect(model.reevalState == .clean)
#expect(model.trackedSynthCount == 1)
// Run a selected fragment: additive (adds a second synth) and leaves the
// whole-buffer baseline intact (buffer still matches the last whole run).
model.updateSelection("OscSin(freq: 220) * 0.1")
let ok: Bool = await model.runSelection()
#expect(ok)
#expect(model.trackedSynthCount == 2)
#expect(model.reevalState == .clean) // baseline untouched
#expect(model.diagnostics.isEmpty)
}
@Test func selectionRunAddsEvenFromADirtyBuffer() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false) // tracked 1, .clean
// Dirty the buffer (edited since the last whole run).
model.text = "OscSin(freq: 440) * 0.1\n# edited"
#expect(model.reevalState == .dirty)
model.updateSelection("OscSin(freq: 330) * 0.1")
_ = await model.runSelection() // additive → tracked 2
model.updateSelection("OscSin(freq: 110) * 0.1")
_ = await model.runSelection() // additive → tracked 3
#expect(model.trackedSynthCount == 3)
// The selection runs never replaced, and the buffer stays dirty.
#expect(model.reevalState == .dirty)
}
@Test func failedSelectionRunLeavesWholeBufferBadgeUntouched() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false) // .clean
#expect(model.reevalState == .clean)
// A selection with an unknown generator fails to build.
model.updateSelection("NotAGenerator(freq: 1)")
let ok: Bool = await model.runSelection()
#expect(ok == false)
#expect(!model.diagnostics.isEmpty)
// The whole-buffer badge must stay clean — the buffer itself is fine.
#expect(model.reevalState == .clean)
#expect(model.statusMessage.hasPrefix("Selection"))
}
}
#endif
@@ -38,14 +38,49 @@ struct ScratchTextViewTests {
#expect(range == NSRange(location: text.utf16.count, length: 0))
}
/// Mid-identifier (no preceding dot) falls through to the default behavior,
/// which covers the whole partial word so it gets replaced on completion.
@Test func partialIdentifierUsesDefaultWordRange() {
/// Mid-identifier (no preceding dot): the range covers the run of identifier
/// characters before the caret, so the partial word gets replaced.
@Test func partialIdentifierCoversWordRange() {
let tv: ScratchTextView = makeTextView("OscSi", caret: 5)
let range: NSRange = tv.rangeForUserCompletion
// Default range spans the partial word `OscSi` (length 5 from offset 0).
#expect(range == NSRange(location: 0, length: 5))
}
/// Right after an open paren, the range is EMPTY at the caret — an argument
/// label (`freq:`) inserts there instead of replacing the receiver
/// (`OscSin.Audio(` → erases `OscSin.Audio` bug).
@Test func afterOpenParenRangeIsEmptyAtCaret() {
let text: String = "OscSin.Audio("
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
let range: NSRange = tv.rangeForUserCompletion
#expect(range == NSRange(location: text.utf16.count, length: 0))
}
/// After a comma + space (next argument position), the range is empty too.
@Test func afterCommaSpaceRangeIsEmptyAtCaret() {
let text: String = "OscSin.Audio(freq: 440, "
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
let range: NSRange = tv.rangeForUserCompletion
#expect(range == NSRange(location: text.utf16.count, length: 0))
}
/// A partial argument label inside parens replaces just that partial word,
/// not the receiver expression.
@Test func partialArgLabelCoversOnlyThePartial() {
let text: String = "OscSin.Audio(fr"
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
let range: NSRange = tv.rangeForUserCompletion
// `fr` starts at offset 13 (after `OscSin.Audio(`), length 2.
#expect(range == NSRange(location: 13, length: 2))
}
/// Underscore is an identifier character, so a leading-underscore partial is
/// covered whole.
@Test func underscoreIsIdentifierChar() {
let tv: ScratchTextView = makeTextView("_foo", caret: 4)
let range: NSRange = tv.rangeForUserCompletion
#expect(range == NSRange(location: 0, length: 4))
}
}
#endif