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
@@ -85,6 +85,28 @@ public struct LyrebirdScratchView: View {
}
public var body: some View {
HStack(spacing: 0) {
mainColumn
Divider()
consolePanel
.frame(width: consoleWidth)
}
.frame(minWidth: scratchMinWidth + consoleWidth, minHeight: scratchMinHeight)
.onAppear {
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
// Idempotent — safe if `onAppear` fires again.
model.session.prewarm()
}
.onReceive(engineRefresh) { _ in
engineTick &+= 1
// Settle a `.queued` readiness badge once its swap has fired.
model.refreshQueuedState()
}
}
/// The editor column: engine controls, editor, status, engine panel.
private var mainColumn: some View {
VStack(spacing: 0) {
engineBar
if let hint: String = model.snippetMemoryHint {
@@ -101,27 +123,50 @@ public struct LyrebirdScratchView: View {
wrapsLines: model.wrapsLines,
requestCompletions: { line, character in
await model.completionItems(line: line, character: character)
}
},
onSelectionChanged: { selected in model.updateSelection(selected) }
)
.frame(minHeight: editorMinHeight)
Divider()
statusBar
if !model.diagnostics.isEmpty {
Divider()
diagnosticsList
Divider()
enginePanel
}
}
/// Always-open right-side console: report messages, errors, and run notices,
/// oldest first, auto-scrolled to the newest.
private var consolePanel: some View {
VStack(spacing: 0) {
HStack {
Text("Console")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer()
Button("Clear") { model.clearConsole() }
.buttonStyle(.plain)
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
.disabled(model.consoleEntries.isEmpty)
}
.padding(.horizontal, statusHPad)
.padding(.vertical, statusVPad)
Divider()
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 2) {
ForEach(model.consoleEntries) { entry in
ConsoleRow(entry: entry)
}
Color.clear.frame(height: 1).id(consoleBottomID)
}
.padding(diagnosticListPadding)
.frame(maxWidth: .infinity, alignment: .leading)
}
.onChange(of: model.consoleEntries.count) { _, _ in
proxy.scrollTo(consoleBottomID, anchor: .bottom)
}
}
}
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
.onAppear {
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
// Idempotent — safe if `onAppear` fires again.
model.session.prewarm()
}
.onReceive(engineRefresh) { _ in
engineTick &+= 1
// Settle a `.queued` readiness badge once its swap has fired.
model.refreshQueuedState()
}
}
@@ -180,6 +225,73 @@ public struct LyrebirdScratchView: View {
.background(Color.orange.opacity(0.12))
}
/// Bottom engine panel: a live output oscilloscope plus a compact status
/// readout (sample rate, CPU average/peak meters, node counts). Refreshed on
/// the editor heartbeat via `.id(engineTick)`.
private var enginePanel: some View {
VStack(alignment: .leading, spacing: 6) {
// The scope keeps a stable identity so its 30 Hz `.task` poll loop
// is NOT cancelled/restarted by the `.id(engineTick)` heartbeat —
// that only wraps the status text below.
if let scope: ScopeCapture = model.session.scope {
ScratchScopeView(capture: scope)
.frame(height: scopeHeight)
}
engineStatusRow
.id(engineTick)
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
}
/// Heartbeat-refreshed engine readout: rate/channels, CPU meters, node counts.
private var engineStatusRow: some View {
let engine: SynthesisEngine = model.session.engine
return VStack(alignment: .leading, spacing: 6) {
HStack {
Text("Engine")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer()
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch")
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
}
cpuMeter(label: "CPU avg", value: engine.averageCPU)
cpuMeter(label: "CPU peak", value: engine.peakCPU)
Text("synths \(engine.synthesizerCount) · groups \(engine.groupCount) · snippets \(model.loadedSnippetCount)")
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
}
}
/// One labelled CPU meter bar. `value` is a fraction of one block period
/// (`[0, 1]`); the fill greens/oranges/reds as it approaches overrun.
private func cpuMeter(label: String, value: Double) -> some View {
let clamped: CGFloat = CGFloat(min(max(value, 0), 1))
let fill: Color = value > cpuMeterCriticalThreshold
? .red
: (value > cpuMeterWarningThreshold ? .orange : .green)
return HStack(spacing: 6) {
Text(label)
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
.frame(width: cpuLabelWidth, alignment: .leading)
GeometryReader { geo in
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 2).fill(Color.secondary.opacity(0.15))
RoundedRectangle(cornerRadius: 2).fill(fill)
.frame(width: geo.size.width * clamped)
}
}
.frame(height: meterHeight)
Text(formatCPU(value))
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
.frame(width: cpuValueWidth, alignment: .trailing)
}
}
private func formatCPU(_ value: Double) -> String {
String(format: "%.0f%%", value * 100)
}
@@ -190,6 +302,14 @@ public struct LyrebirdScratchView: View {
}
}
/// Evaluate just the current selection, additively. No-op when nothing is
/// selected.
public func runSelection() {
Task { @MainActor in
_ = await model.runSelection()
}
}
public func presentOpenPanel() {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.swiftSource]
@@ -322,18 +442,6 @@ public struct LyrebirdScratchView: View {
}
}
private var diagnosticsList: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
DiagnosticRow(diagnostic: diag)
}
}
.padding(diagnosticListPadding)
}
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
}
// Layout constants — all in points. Kept private; tuned to match
// LyrebirdEngineStatusView's visual density.
private let scratchMinWidth: CGFloat = 520
@@ -350,26 +458,38 @@ public struct LyrebirdScratchView: View {
private let diagnosticsMaxHeight: CGFloat = 200
private let engineDotSize: CGFloat = 8
private let reevalBadgeSpacing: CGFloat = 4
private let scopeHeight: CGFloat = 88
private let meterHeight: CGFloat = 6
private let consoleWidth: CGFloat = 300
private let consoleBottomID: String = "scratch.console.bottom"
private let cpuLabelWidth: CGFloat = 58
private let cpuValueWidth: CGFloat = 40
/// CPU-meter fill turns orange above this fraction of one block period, red
/// above ``cpuMeterCriticalThreshold``.
private let cpuMeterWarningThreshold: Double = 0.5
private let cpuMeterCriticalThreshold: Double = 0.8
}
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
/// message in a compact monospaced row.
private struct DiagnosticRow: View {
private struct ConsoleRow: View {
let diagnostic: Diagnostic
let entry: ScratchConsoleEntry
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
Text(locationString)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
.frame(minWidth: locationColumnWidth, alignment: .leading)
Text(diagnostic.severity.rawValue)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(color(for: diagnostic.severity))
.frame(minWidth: severityColumnWidth, alignment: .leading)
Text(diagnostic.message)
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(glyph)
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(color)
.frame(width: 14, alignment: .leading)
if let location: String = entry.location {
Text(location)
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
}
Text(entry.text)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(entry.kind == .error ? Color.primary : color)
.textSelection(.enabled)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
@@ -377,58 +497,88 @@ private struct DiagnosticRow: View {
}
}
private var locationString: String {
if let line: Int = diagnostic.line {
return "\(line):\(diagnostic.column)"
/// Leading glyph per kind: an X for errors, an arrow for messages, a dot for
/// info notices.
private var glyph: String {
switch entry.kind {
case .error: return "✗"
case .message: return "›"
case .info: return "·"
}
// No user-body line. A swiftc preamble hit carries a real (1-based)
// rawLine; a graph-DSL file-scope error carries rawLine 0 (there is no
// harness/preamble at all), so label the two cases distinctly.
return diagnostic.rawLine >= 1
? "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
: "(file)"
}
private func color(for severity: DiagnosticSeverity) -> Color {
switch severity {
private var color: Color {
switch entry.kind {
case .error: return .red
case .warning: return .orange
case .note: return .secondary
case .message: return .cyan
case .info: return .secondary
}
}
private let rowGutter: CGFloat = 8
private let locationColumnWidth: CGFloat = 80
private let severityColumnWidth: CGFloat = 56
}
/// `NSTextView` subclass that fixes member-completion behavior.
///
/// The default `rangeForUserCompletion` scans back over the whole dotted
/// expression, so completing a member right after a `.` (e.g. `context.` →
/// `engine`) would *replace* the receiver (`context`) with the chosen member
/// instead of inserting after the dot. When the character before the insertion
/// point is a `.`, this override returns an empty range at the caret, so the
/// completion is a pure insertion and `context.engine` is produced.
/// UTF-16 code unit for `.` (the member-access operator that triggers and
/// shapes completion).
private let dotCharacterCode: unichar = 46
/// expression, so a candidate would *replace* the receiver rather than the
/// partial word being typed. Completing a member after `context.` → `engine`
/// would replace `context`; accepting an argument label after `OscSin.Audio(`
/// → `freq:` would replace `OscSin.Audio`. The correct replace range is just
/// the run of identifier characters immediately before the caret (empty after
/// any boundary — `.`, `(`, `,`, whitespace), so the candidate inserts there.
/// Whether `selection` is a bare insertion point sitting immediately after a
/// `.` in `text` — the member-completion trigger condition.
private func caretFollowsDot(in text: NSString, selection: NSRange) -> Bool {
guard selection.length == 0, selection.location > 0, selection.location <= text.length
else { return false }
return text.character(at: selection.location - 1) == dotCharacterCode
/// Whether `c` (a UTF-16 code unit) is a Swift identifier character —
/// ASCII letter, digit, or underscore. Sufficient for completion-range
/// scanning; identifiers with non-ASCII scalars are not a concern here.
private func isIdentifierCodeUnit(_ c: unichar) -> Bool {
let underscore: unichar = 95
let zero: unichar = 48, nine: unichar = 57
let upperA: unichar = 65, upperZ: unichar = 90
let lowerA: unichar = 97, lowerZ: unichar = 122
return c == underscore
|| (c >= zero && c <= nine)
|| (c >= upperA && c <= upperZ)
|| (c >= lowerA && c <= lowerZ)
}
final class ScratchTextView: NSTextView {
/// Invoked when the user asks for completion (the standard completion key —
/// Esc / F5). Set by `makeNSView`, right after `configure`; runs the async fetch and then
/// shows the completion window. Completion is manual only.
var onManualComplete: (() -> Void)?
override var rangeForUserCompletion: NSRange {
let sel: NSRange = selectedRange()
if caretFollowsDot(in: string as NSString, selection: sel) {
return NSRange(location: sel.location, length: 0)
// Never replace across an actual selection — defer to the default.
guard sel.length == 0, sel.location <= (string as NSString).length else {
return super.rangeForUserCompletion
}
return super.rangeForUserCompletion
let ns: NSString = string as NSString
var start: Int = sel.location
while start > 0 && isIdentifierCodeUnit(ns.character(at: start - 1)) {
start -= 1
}
return NSRange(location: start, length: sel.location - start)
}
/// Intercept the built-in `complete:` command (bound to Esc / F5) so the
/// candidates are fetched asynchronously first, then shown. Without this,
/// pressing Esc would call the delegate with an empty (never-fetched) list.
/// Everything else falls through to the normal editor commands.
override func doCommand(by selector: Selector) {
if selector == #selector(NSStandardKeyBindingResponding.complete(_:)) {
onManualComplete?()
return
}
super.doCommand(by: selector)
}
/// Esc is delivered as `cancelOperation:` (not `complete:`) by the default
/// key bindings, so it never reaches `doCommand(by:)`'s `complete:` arm —
/// only F5 does. Route it here too so Esc invokes completion as documented.
/// The completion window, once open, consumes Esc itself to dismiss, so this
/// only fires when the window is closed.
override func cancelOperation(_ sender: Any?) {
onManualComplete?()
}
}
@@ -444,6 +594,9 @@ private struct ScratchEditor: NSViewRepresentable {
/// Async source of code-completion candidates for a zero-based user-space
/// (line, UTF-16 character). Supplied by the view from the model.
let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem]
/// Called with the current selected substring whenever the selection
/// changes (empty when nothing is selected). Drives "Run Selection".
let onSelectionChanged: @MainActor (String) -> Void
@MainActor
final class Coordinator: NSObject, NSTextViewDelegate {
@@ -455,17 +608,67 @@ private struct ScratchEditor: NSViewRepresentable {
/// applies its results if it is still the newest (so a slow older request
/// can't clobber a fresher one that landed first).
private var _completionGeneration: Int = 0
/// Pending debounced re-highlight; cancelled and rescheduled on each edit
/// so a burst of keystrokes re-tokenizes the buffer once, not per key.
private var _highlightWork: DispatchWorkItem?
/// Last selection substring pushed to the model, so an unchanged selection
/// (the common case while typing — caret moves, selection stays empty)
/// doesn't republish `@Published` state and re-render the whole view.
private var _lastSelectionPushed: String = ""
/// Last `wrapsLines` value applied, so `updateNSView` can skip re-applying
/// wrap/paragraph settings on a pure text republish (every keystroke).
var lastWraps: Bool?
/// Idle delay before re-highlighting after an edit. Short enough to feel
/// instant once typing pauses; long enough to coalesce a fast burst.
private static let highlightDebounce: TimeInterval = 0.045
init(_ parent: ScratchEditor) { self.parent = parent }
func textDidChange(_ notification: Notification) {
guard let tv: NSTextView = notification.object as? NSTextView else { return }
parent.text = tv.string
parent.applyHighlight(to: tv)
// Auto-trigger member completion right after a `.` is typed.
if caretFollowsDot(in: tv.string as NSString, selection: tv.selectedRange()) {
triggerCompletion(tv)
scheduleHighlight(tv)
// Completion is manual (Esc), never auto-triggered on `.`: an
// unrequested popup ambushes typing and the built-in completion
// window is awkward to dismiss mid-edit.
}
/// Coalesce full-buffer re-highlighting: cancel any pending pass and run
/// one shortly after the edits stop. Newly typed characters render in the
/// base color immediately (via `typingAttributes`); syntax colors catch
/// up a beat later, avoiding an O(n) tokenize on every keystroke.
private func scheduleHighlight(_ tv: NSTextView) {
_highlightWork?.cancel()
let work: DispatchWorkItem = DispatchWorkItem { [weak self, weak tv] in
guard let self: Coordinator = self, let tv: NSTextView = tv else { return }
self.parent.applyHighlight(to: tv)
}
_highlightWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + Coordinator.highlightDebounce, execute: work)
}
/// Push the current selected substring up to the model so "Run Selection"
/// knows what (if anything) is selected — but only when it actually
/// changed, to avoid a per-caret-move `@Published` republish.
func textViewDidChangeSelection(_ notification: Notification) {
guard let tv: NSTextView = notification.object as? NSTextView else { return }
let sel: NSRange = tv.selectedRange()
let selected: String
if sel.length > 0, sel.location + sel.length <= (tv.string as NSString).length {
selected = (tv.string as NSString).substring(with: sel)
} else {
selected = ""
}
guard selected != _lastSelectionPushed else { return }
_lastSelectionPushed = selected
// Defer the @Published mutation: a programmatic text change (via
// `updateNSView` → `replaceText`) can clamp the selection and re-post
// this notification from inside a SwiftUI update pass. Scheduling on
// the next main-actor tick keeps that off the render pass ("Publishing
// changes from within view updates is not allowed").
let notify: @MainActor (String) -> Void = parent.onSelectionChanged
Task { @MainActor in notify(selected) }
}
/// The text view calls this synchronously from `complete(_:)`; return the
@@ -525,6 +728,12 @@ private struct ScratchEditor: NSViewRepresentable {
scroll.documentView = tv
configure(tv, in: scroll, with: context.coordinator)
// Manual completion (Esc): fetch candidates, then show the window.
let coordinator: Coordinator = context.coordinator
tv.onManualComplete = { [weak coordinator, weak tv] in
guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return }
coordinator.triggerCompletion(tv)
}
return scroll
}
@@ -533,14 +742,23 @@ private struct ScratchEditor: NSViewRepresentable {
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
if fontChanged {
tv.font = font
}
let wrapChanged: Bool = context.coordinator.lastWraps != wrapsLines
context.coordinator.lastWraps = wrapsLines
let textChanged: Bool = tv.string != text
// Fast path: a pure text republish (the per-keystroke case) needs no work
// here — the `NSTextView` already holds the text (it's the editor of
// record), highlighting is debounced in the Coordinator, and font/wrap
// are unchanged. Skip the paragraph-style measure + attribute churn.
guard textChanged || fontChanged || wrapChanged else { return }
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
if fontChanged { tv.font = font }
tv.defaultParagraphStyle = paragraphStyle
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
applyWrap(to: tv, in: scroll)
if tv.string != text {
if textChanged {
// External change (load, reset, mode switch) — replace + re-highlight.
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
} else if fontChanged {
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)