From bf67e68994e777f441705883b82d9358ae6b65d6 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:50:21 -0800 Subject: [PATCH 01/25] chore: untangler phase 0 triage and baseline Co-Authored-By: Claude Opus 5.5 --- .untangler/RUNNING.md | 52 +++++++++++++++++++++++++++++ .untangler/STATE.md | 28 ++++++++++++++++ .untangler/audit.json | 6 ++++ .untangler/deferred.md | 4 +++ .untangler/state.json | 75 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 165 insertions(+) create mode 100644 .untangler/RUNNING.md create mode 100644 .untangler/STATE.md create mode 100644 .untangler/audit.json create mode 100644 .untangler/deferred.md create mode 100644 .untangler/state.json diff --git a/.untangler/RUNNING.md b/.untangler/RUNNING.md new file mode 100644 index 0000000..a7b02c1 --- /dev/null +++ b/.untangler/RUNNING.md @@ -0,0 +1,52 @@ +# How to run this app + +feedBack desktop (Rock Band edition): Electron main process (TypeScript), a vanilla-JS +renderer, a native C++/JUCE audio engine loaded as a Node addon, a sandboxed VST host, and +the bundled feedBack core (Python server + web UI) under `resources/slopsmith`. + +Windows only for this engagement. + +## Setup + +- Node deps: `npm install` (runs `electron-builder install-app-deps`). +- Native engine: `npm run build:audio` (CMake + MSVC, see WINDOWS_BUILD_REQUIREMENTS.md). + Output: `build/Release/slopsmith_audio.node`. Already built on this machine; reuse it. +- Bundled core + plugins: `scripts/bundle-slopsmith.sh` with `SLOPSMITH_DIR` pointing at a + clone of `mattromano/feedBack@custom` (see `clone_slopsmith` in `scripts/build-common.sh`). +- `resources/python` and `resources/bin` are already bundled on this machine; reuse them. + +## Run (the way the user tests: local packaged build, NOT `npm start`) + +```bash +npm run build:ts && npx electron-builder --win --dir +release/win-unpacked/feedback.exe +``` + +Verified: `release/win-unpacked/feedback.exe` exists and ran this session (ASIO4ALL @256). + +After any local build, restore `amps/`, `pedals/`, `racks/` into +`release/win-unpacked/resources/slopsmith/plugins/rig_builder/vst/` from +`%LOCALAPPDATA%\Temp\slopsmith\plugins\rig_builder\vst` (song tones store absolute paths +there). Close the dev/local copy before running the installed app: they share settings and +port 18000. + +`npm start` / `npm run dev` also work (dev mode) but the user reported wrong guitar settings +in dev mode; prefer the packaged build for any check the user will hear. + +## Test + +Only targeted, source-reading tests on this machine. NEVER the full `npm test`. + +Safe baseline set (24 files, 155 tests, all passing at baseline, < 1 s): + +```bash +node --test $(ls tests/*.test.js | grep -v -E "chain-mutation-storm|contract-check|live-pitch|ml-note-detection|multi-source|napi-arg-fuzz|config-bootstrap|config-reset") +``` + +Do NOT run locally (they load the native engine, grab ASIO devices and lag the PC): +chain-mutation-storm, contract-check, live-pitch, ml-note-detection, multi-source, +napi-arg-fuzz. The user's notes also exclude config-bootstrap and config-reset (they turn +out to use temp dirs only, but keep them out per the user's rule). Leave those to CI. + +C++ unit suites (`tests/engine_units`, `tests/onset_lag`, `tests/chordscorer`, ...) build +with CMake; run individual test executables only, Debug builds, with a timeout. diff --git a/.untangler/STATE.md b/.untangler/STATE.md new file mode 100644 index 0000000..00d1212 --- /dev/null +++ b/.untangler/STATE.md @@ -0,0 +1,28 @@ +# Codebase Untangler - State + +**Started**: 2026-11-07T20:48:45.568531+00:00 +**Current phase**: 1 (Audit) +**Branch**: refactor/untangle-2026-11-07 +**Stack**: electron, typescript, vanilla-js-renderer, cpp-juce-node-addon, vst-sandbox, python-bundled-core + +## Phase progress + +- [x] Phase 0: Triage (done) +- [~] Phase 1: Audit (in_progress) +- [ ] Phase 2: Safety Net (pending) +- [ ] Phase 3: Refactor (pending) +- [ ] Phase 4: Hardening (pending) +- [ ] Phase 5: Handover (pending) + +## Baseline + +- Total LOC: 53008 +- File count: 408 +- Tests: 155 (155 passing, 0 failing) + +## Overrides used + +(none) + +--- +*Auto-generated from state.json.* diff --git a/.untangler/audit.json b/.untangler/audit.json new file mode 100644 index 0000000..1752288 --- /dev/null +++ b/.untangler/audit.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "issues": [], + "top_5": [], + "deferred": [] +} \ No newline at end of file diff --git a/.untangler/deferred.md b/.untangler/deferred.md new file mode 100644 index 0000000..8a3ac55 --- /dev/null +++ b/.untangler/deferred.md @@ -0,0 +1,4 @@ +# Deferred Items + +Problems noticed during refactor but deliberately not fixed now. + diff --git a/.untangler/state.json b/.untangler/state.json new file mode 100644 index 0000000..915be85 --- /dev/null +++ b/.untangler/state.json @@ -0,0 +1,75 @@ +{ + "schema_version": 1, + "started_at": "2026-11-07T20:48:45.568531+00:00", + "current_phase": 1, + "phases": { + "0": { + "name": "Triage", + "status": "done", + "gates": {}, + "started_at": "2026-11-07T20:48:45.568531+00:00", + "completed_at": "2026-11-07T20:50:20.953556+00:00" + }, + "1": { + "name": "Audit", + "status": "in_progress", + "gates": {}, + "started_at": "2026-11-07T20:50:20.953556+00:00" + }, + "2": { + "name": "Safety Net", + "status": "pending", + "gates": {} + }, + "3": { + "name": "Refactor", + "status": "pending", + "gates": {} + }, + "4": { + "name": "Hardening", + "status": "pending", + "gates": {} + }, + "5": { + "name": "Handover", + "status": "pending", + "gates": {} + } + }, + "baseline": { + "git_tag": "pre-refactor-baseline", + "branch": "refactor/untangle-2026-11-07", + "total_loc": 53008, + "file_count": 408, + "test_count": 155, + "tests_passing": 155, + "tests_failing": 0, + "code_file_count": 203, + "dependency_count": { + "dependencies": 3, + "devDependencies": 5 + }, + "test_note": "Baseline run: 24 files (155 pass, 0 fail), incl. config-bootstrap + config-reset (temp dirs only). Going forward the safe set is 22 files (RUNNING.md); 6 engine-loading files left to CI" + }, + "stack": [ + "electron", + "typescript", + "vanilla-js-renderer", + "cpp-juce-node-addon", + "vst-sandbox", + "python-bundled-core" + ], + "top_5_signed_off_at": null, + "overrides": [], + "stack_reference_note": "No matching stack file; read node-express.md as the closest (Node process) and applied its general patterns", + "last_test_run": { + "timestamp": "2026-11-07T20:50:11.101125+00:00", + "passing": true, + "passing_count": 155, + "failing_count": 0 + }, + "user_ack": { + "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" + } +} \ No newline at end of file From 79a57438689bc19ff72593826bc1063eae05cbcf Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:00:24 -0800 Subject: [PATCH 02/25] docs: untangler phase 1 audit (33 issues, Top 5 pending sign-off) Co-Authored-By: Claude Opus 5.5 --- .untangler/audit.json | 533 +++++++++++++++++++++++++++++++++++++++++- .untangler/state.json | 3 +- REFACTOR_AUDIT.md | 229 ++++++++++++++++++ 3 files changed, 761 insertions(+), 4 deletions(-) create mode 100644 REFACTOR_AUDIT.md diff --git a/.untangler/audit.json b/.untangler/audit.json index 1752288..4ca56a7 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -1,6 +1,533 @@ { "schema_version": 1, - "issues": [], - "top_5": [], - "deferred": [] + "baseline_commit": "e610887", + "issues": [ + { + "id": "I-001", + "title": "Engine tests run nowhere; npm test mixes fast and engine-loading tests", + "severity": "critical", + "category": "risk", + "files": [ + "package.json:13", + ".github/workflows/ci.yml:39-48", + "tests/CMakeLists.txt:15-18" + ], + "description": "CI runs no JS or C++ unit tests; the 6 engine-loading JS tests cannot run on the owner machine.", + "status": "pending", + "refactor_plan": "Move engine tests to tests/engine/, add test:fast/test:engine (test=fast), run fast in ci.yml and engine + ctest unit suites in addon-ci.yml.", + "commits": [] + }, + { + "id": "I-002", + "title": "Desktop config store lives in soundfont-manager and a corrupt file wipes all prefs", + "severity": "critical", + "category": "boundary", + "files": [ + "src/main/soundfont-manager.ts:32-79", + "src/main/main.ts:126,514-523", + "src/main/pane-hosts.ts:28", + "src/main/python.ts:12" + ], + "description": "Parse failure returns {} and the next write drops every setting; the module also causes a require cycle.", + "status": "pending", + "refactor_plan": "Extract desktop-config.ts (re-export for one release); on parse failure keep a .corrupt backup and do not overwrite blindly; add a test.", + "commits": [] + }, + { + "id": "I-003", + "title": "Renderer tone switchers duplicated and drifted; two song-load pipelines race on the chain", + "severity": "high", + "category": "duplication", + "files": [ + "src/renderer/screen.js:2301-2340,2682-2797,3308-3324", + "src/renderer/screen.js:4755-4893,4970-4995,5029-5157", + "src/renderer/screen.js:4445-4464,3227-3233" + ], + "description": "IIFE2 copies of the bypass/MIDI switchers lack tonePresetNameMap and normalizeTimelineToneData; the IIFE2 preload is not serialized by _applyToneMappingsLock.", + "status": "pending", + "refactor_plan": "Add vm tests, export one switcher factory + chain-job lock from IIFE1, call from IIFE2; verify on the packaged build.", + "commits": [] + }, + { + "id": "I-004", + "title": "~40 copies of fail-soft addon-call boilerplate; ~15 native calls unguarded", + "severity": "high", + "category": "duplication", + "files": [ + "src/main/audio-bridge.ts:505-1205", + "src/main/audio-bridge.ts:602-612,728,1010,1031,1035,1040-1056,1212,1240,1273-1298" + ], + "description": "Same typeof-guard/try/warn/default pattern copied ~40 times; inconsistent guarding lets native throws reject into the renderer.", + "status": "pending", + "refactor_plan": "callAddon(name, fallback, ...args) + PITCH_NONE, one handler group per commit; keep literal ipcMain.handle lines, defaults and warn text.", + "commits": [] + }, + { + "id": "I-005", + "title": "No lockfile: every build resolves deps fresh (Electron ABI drift)", + "severity": "high", + "category": "dependency", + "files": [ + ".gitignore:52", + ".github/workflows/ci.yml:39", + ".github/workflows/addon-ci.yml:177", + "scripts/build-common.sh:296", + "package.json:148-152" + ], + "description": "package-lock.json is gitignored; CI and local builds can get different Electron/TypeScript.", + "status": "deferred", + "refactor_plan": "Track package-lock.json, switch CI to npm ci, wire or drop .build-config.json versions.electron.", + "commits": [] + }, + { + "id": "I-006", + "title": "Bundling skips failed plugin clones and desktop-plugin copies silently", + "severity": "critical", + "category": "risk", + "files": [ + "scripts/build-common.sh:211-215,233", + "scripts/bundle-slopsmith.sh:185" + ], + "description": "git clone 2>/dev/null || echo skipped; a green release can ship without a plugin.", + "status": "pending", + "refactor_plan": "Show stderr; fail when cloned != total unless ALLOW_MISSING_PLUGINS=1; fail loudly on the desktop plugin copy.", + "commits": [] + }, + { + "id": "I-007", + "title": "restartPython races: no serialization, unawaited, port can drift", + "severity": "high", + "category": "risk", + "files": [ + "src/main/python.ts:943-947,699,848-849", + "src/main/main.ts:1325-1342" + ], + "description": "Two quick restarts spawn two backends; renderer stays on :18000 while the server moves to :18001; Windows grandchildren survive.", + "status": "deferred", + "refactor_plan": "Serialize through one in-flight promise that awaits the old child close before spawning.", + "commits": [] + }, + { + "id": "I-008", + "title": "localStorage schemas (tone mappings, presets, signal chain) parsed and written by hand", + "severity": "high", + "category": "duplication", + "files": [ + "src/renderer/screen.js:2545,4812,4910,2981,2999,3011", + "src/renderer/screen.js:1988,2654", + "src/renderer/screen.js:1191,1269,2406,2426,2446,2602,2723,4879" + ], + "description": "Raw JSON.parse/setItem bypass the defensive reader; quota errors can throw mid-handler. User data.", + "status": "deferred", + "refactor_plan": "window._aeStore accessors with round-trip tests first.", + "commits": [] + }, + { + "id": "I-009", + "title": "JSON config files read/written 4 ways; audio settings write is not atomic", + "severity": "medium", + "category": "duplication", + "files": [ + "src/main/soundfont-manager.ts:73-79", + "src/main/audio-bridge.ts:209-221", + "src/main/vst-crash-guard.ts:86", + "src/main/python.ts:435-441" + ], + "description": "A crash mid-write can lose device settings.", + "status": "deferred", + "refactor_plan": "src/main/json-file.ts readJson/writeJsonAtomic.", + "commits": [] + }, + { + "id": "I-010", + "title": "Resource/config path resolution computed independently in several modules", + "severity": "medium", + "category": "duplication", + "files": [ + "src/main/main.ts:301-305", + "src/main/audio-bridge.ts:232-236,308-310", + "src/main/python.ts:107-129,410-421,542,582-586,636-657", + "src/main/config-paths.ts:223-225" + ], + "description": "getConfigDir uses process.env.HOME (unset on Windows) and mkdirs on read.", + "status": "deferred", + "refactor_plan": "src/main/app-paths.ts; the HOME change needs user confirmation.", + "commits": [] + }, + { + "id": "I-011", + "title": "~125 IPC channel names are bare strings; ipc-channels.ts covers ~19", + "severity": "medium", + "category": "boundary", + "files": [ + "src/main/ipc-channels.ts", + "src/main/preload.ts:301-570", + "src/main/preload.ts:47", + "src/main/update-manager.ts:89", + "src/main/main.ts:1371" + ], + "description": "Channels and the UpdateChannel type are defined in several places.", + "status": "deferred", + "refactor_plan": "Constants only after tests/contracts/extract.js handles them.", + "commits": [] + }, + { + "id": "I-012", + "title": "Duplex vs split output callbacks repeat the mix tail", + "severity": "medium", + "category": "duplication", + "files": [ + "src/audio/AudioEngine.cpp:1113-1182", + "src/audio/AudioEngine.cpp:1337-1411" + ], + "description": "~60 lines copied; heard-clock-wiring.test.js pins exact occurrence counts.", + "status": "deferred", + "refactor_plan": "Extract pure noexcept backingRms/meterPeak first; leave stamping and locks in place.", + "commits": [] + }, + { + "id": "I-013", + "title": "N-API int parsing bypasses NapiHelpers (~25 raw Int32Value)", + "severity": "medium", + "category": "duplication", + "files": [ + "src/audio/addon/DetectionBindings.cpp:27-35,188,299-609", + "src/audio/addon/DeviceBindings.cpp:321-842", + "src/audio/addon/ControlBindings.cpp:46", + "src/audio/addon/ChainOps.cpp:682,743,806" + ], + "description": "NaN coerced to 0; As() without IsString.", + "status": "deferred", + "refactor_plan": "Convert one file at a time to argInt/argSlotId.", + "commits": [] + }, + { + "id": "I-014", + "title": "Ring consume and seqlock patterns open-coded 3x each", + "severity": "medium", + "category": "duplication", + "files": [ + "src/audio/AudioEngine.cpp:1250-1333,1444-1473", + "src/audio/engine/StreamSink.cpp:87-104", + "src/audio/SourceChain.cpp:235-241", + "src/audio/engine/RendererBus.h:229-317" + ], + "description": "Timing-critical code duplicated.", + "status": "deferred", + "refactor_plan": "PackedStereoRing::consume and SeqlockStamp with unit tests; deferred until timing is re-verified.", + "commits": [] + }, + { + "id": "I-015", + "title": "Legacy vs per-source binding marshalling duplicated; 5 near-identical AsyncWorkers", + "severity": "medium", + "category": "duplication", + "files": [ + "src/audio/addon/DetectionBindings.cpp:119-147,245-449", + "src/audio/addon/DeviceBindings.cpp:631-860,893-934", + "src/audio/addon/ChainOps.cpp:103-148,419,636-819" + ], + "description": "DeviceBindings.cpp holds non-device bindings.", + "status": "deferred", + "refactor_plan": "toJs helpers; NAM/IR via queueChainSlotMutation.", + "commits": [] + }, + { + "id": "I-016", + "title": "CI signing, vpk pack and vpk version copied across 3 workflows", + "severity": "medium", + "category": "duplication", + "files": [ + ".github/workflows/build.yml:95-132,289,325-459", + ".github/workflows/nightly.yml:114-317", + ".github/workflows/rc.yml:86-110", + "package.json:145" + ], + "description": "Already drifting (--noPortable, macos-14 vs 15).", + "status": "deferred", + "refactor_plan": "Composite actions; read the vpk version from package.json.", + "commits": [] + }, + { + "id": "I-017", + "title": "Bundling split across three dispatchers; SLOPSMITH_DIR discovery copied", + "severity": "medium", + "category": "duplication", + "files": [ + "scripts/bundle.sh:14-22", + "scripts/build-windows.sh:124-130", + "scripts/bundle-slopsmith.sh:19-27", + "package.json:14,26" + ], + "description": "npm run dist:win and CI take different paths.", + "status": "deferred", + "refactor_plan": "resolve_slopsmith_dir helper; dist:* calls build-release.sh; move the copier to scripts/copy-static.js.", + "commits": [] + }, + { + "id": "I-018", + "title": "~37 window._ae* globals form the cross-IIFE bus; _toneSwitcher written from 18 places", + "severity": "medium", + "category": "boundary", + "files": [ + "src/renderer/screen.js:2471-4392", + "src/renderer/screen.js:4743-5135" + ], + "description": "The class of bug behind issue #12.", + "status": "deferred", + "refactor_plan": "hookState.tone with set/get; keep window aliases.", + "commits": [] + }, + { + "id": "I-019", + "title": "Device-settings validation duplicated across the IPC boundary", + "severity": "low", + "category": "boundary", + "files": [ + "src/renderer/screen.js:155-192", + "src/main/audio-bridge.ts:55-96" + ], + "description": "Main already normalizes on read and write.", + "status": "deferred", + "refactor_plan": "Keep the renderer copy only for the one-time migration.", + "commits": [] + }, + { + "id": "I-020", + "title": "DeviceSetup and bindings reach into engine internals", + "severity": "medium", + "category": "boundary", + "files": [ + "src/audio/AudioEngine.cpp:568-570,588", + "src/audio/AudioEngine.h:32-34,413" + ], + "description": "6 references passed to applySplit; raw SourceChain*; 3 unused manager getters.", + "status": "deferred", + "refactor_plan": "Delete the unused getters; later a SplitOutputPort struct.", + "commits": [] + }, + { + "id": "I-021", + "title": "Test-only loopback lives in production audio callbacks", + "severity": "medium", + "category": "boundary", + "files": [ + "src/audio/AudioEngine.h:542-548", + "src/audio/AudioEngine.cpp:851-862,1089-1103,1184-1194" + ], + "description": "Env-gated but evaluated every duplex block.", + "status": "deferred", + "refactor_plan": "engine/TestLoopback.h hooks, compiled out unless SLOPSMITH_TEST_HOOKS.", + "commits": [] + }, + { + "id": "I-022", + "title": "C++ test targets compiled into every release addon build", + "severity": "low", + "category": "boundary", + "files": [ + "CMakeLists.txt:61-64", + "tests/CMakeLists.txt:72" + ], + "description": "SLOPSMITH_BUILD_TESTS defaults ON; the tests never run.", + "status": "deferred", + "refactor_plan": "OFF in release builds, ON in the CI engine lane.", + "commits": [] + }, + { + "id": "I-023", + "title": "Dead code batch (IPC, renderer, addon exports, engine methods, repo leftovers)", + "severity": "low", + "category": "dead_code", + "files": [ + "src/main/plugin-manager.ts:218-221", + "src/renderer/screen.js:28,110-112,2791,3409", + "src/audio/NodeAddon.cpp:344,361", + "src/audio/AudioEngine.h:13-23", + "src/audio/addon/Bindings.h:116-117", + "tests/spike/", + "scripts/dev/renderer-bus-spike.js" + ], + "description": "See REFACTOR_AUDIT.md section 7; keep diagnostics used from DevTools and getLatencyBreakdown.", + "status": "deferred", + "refactor_plan": "One commit per area after a fresh grep including tests/.", + "commits": [] + }, + { + "id": "I-024", + "title": "Windows bundled binaries are unpinned 'latest' with no checksum", + "severity": "medium", + "category": "dependency", + "files": [ + "scripts/build-windows.sh:108,184,224", + "scripts/bundle-binaries.sh:139" + ], + "description": "macOS is pinned in .build-config.json.", + "status": "deferred", + "refactor_plan": "Pinned URL + sha256 for Windows ffmpeg/vgmstream.", + "commits": [] + }, + { + "id": "I-025", + "title": "package.json version frozen at 0.3.0 while tags are v0.4.17", + "severity": "high", + "category": "dependency", + "files": [ + "package.json:3,39", + "src/main/update-manager.ts:173", + "src/main/main.ts:1197", + "scripts/release-rockband.sh:15-33" + ], + "description": "app.getVersion, the Linux updater and the migration stamp report 0.3.0.", + "status": "deferred", + "refactor_plan": "npm version --no-git-tag-version from the tag in the build step.", + "commits": [] + }, + { + "id": "I-026", + "title": "Bundle strips rig_builder/vst while song tones store absolute paths; local builds differ from CI", + "severity": "critical", + "category": "risk", + "files": [ + "scripts/bundle-slopsmith.sh:176" + ], + "description": "Song tones break after a CI release; local builds hide it.", + "status": "deferred", + "refactor_plan": "Explicit BUNDLE_RIG_VST flag here; the root fix belongs in the rig_builder plugin repo.", + "commits": [] + }, + { + "id": "I-027", + "title": "Renderer-supplied paths reach the filesystem unchecked; plugins:remove has no confirm", + "severity": "high", + "category": "risk", + "files": [ + "src/main/audio-bridge.ts:1219-1225,1375", + "src/main/plugin-manager.ts:156-173" + ], + "description": "Plugin scripts can reach these channels.", + "status": "deferred", + "refactor_plan": "Restrict savePluginList to userData; native confirm on plugins:remove.", + "commits": [] + }, + { + "id": "I-028", + "title": "Audio-thread hazards (fprintf, call_once/sigaction, alloc+mutex on crash, sandbox wait)", + "severity": "critical", + "category": "risk", + "files": [ + "src/audio/AudioEngine.cpp:1033,1040,1240", + "src/audio/SignalChain.cpp:122-170,260-285", + "src/audio/Sandbox/SandboxedProcessor.cpp:503-524" + ], + "description": "Flag only; do not refactor inside the callbacks this cycle.", + "status": "deferred", + "refactor_plan": "Out of scope this cycle.", + "commits": [] + }, + { + "id": "I-029", + "title": "songBusPullScratch sized only by the input-side about-to-start", + "severity": "medium", + "category": "risk", + "files": [ + "src/audio/AudioEngine.cpp:846,945-948,1430" + ], + "description": "Song audio silently dropped on an output-only start.", + "status": "deferred", + "refactor_plan": "Size it in audioOutputAboutToStart too.", + "commits": [] + }, + { + "id": "I-030", + "title": "Linux AppImage self-update never checks size/hash before rename", + "severity": "medium", + "category": "risk", + "files": [ + "src/main/update-manager.ts:261-339" + ], + "description": "A truncated download replaces the running binary.", + "status": "deferred", + "refactor_plan": "Compare received vs content-length before renameSync.", + "commits": [] + }, + { + "id": "I-031", + "title": "Renderer meter/latency setIntervals leak on re-evaluation", + "severity": "low", + "category": "risk", + "files": [ + "src/renderer/screen.js:1582-1588,1642" + ], + "description": "Pollers stack per re-evaluation.", + "status": "deferred", + "refactor_plan": "Keep handles in hookState and clear on start.", + "commits": [] + }, + { + "id": "I-032", + "title": "Global error handlers drop stacks; IPC registered inside createWindow", + "severity": "low", + "category": "risk", + "files": [ + "src/main/main.ts:262-268,565,582,667" + ], + "description": "Hard to debug; second-handler throw on re-create.", + "status": "deferred", + "refactor_plan": "Log err.stack; move the handlers to the startup block.", + "commits": [] + }, + { + "id": "I-033", + "title": "upterm SSH session opens on every failed build while secrets are loaded", + "severity": "medium", + "category": "risk", + "files": [ + ".github/workflows/build.yml:178-182", + ".github/workflows/nightly.yml:150", + ".github/workflows/rc.yml" + ], + "description": "Remote shell on a job holding signing secrets.", + "status": "deferred", + "refactor_plan": "Gate behind a workflow_dispatch debug input.", + "commits": [] + } + ], + "top_5": [ + "I-001", + "I-002", + "I-006", + "I-004", + "I-003" + ], + "deferred": [ + "I-005", + "I-007", + "I-008", + "I-009", + "I-010", + "I-011", + "I-012", + "I-013", + "I-014", + "I-015", + "I-016", + "I-017", + "I-018", + "I-019", + "I-020", + "I-021", + "I-022", + "I-023", + "I-024", + "I-025", + "I-026", + "I-027", + "I-028", + "I-029", + "I-030", + "I-031", + "I-032", + "I-033" + ] } \ No newline at end of file diff --git a/.untangler/state.json b/.untangler/state.json index 915be85..96668c7 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -71,5 +71,6 @@ }, "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" - } + }, + "next_action": "Phase 1: user to sign off on the Top 5 (I-001, I-002, I-006, I-004, I-003) or swap items; then record top_5_signed_off_at and run check_gate.py 1" } \ No newline at end of file diff --git a/REFACTOR_AUDIT.md b/REFACTOR_AUDIT.md new file mode 100644 index 0000000..f111799 --- /dev/null +++ b/REFACTOR_AUDIT.md @@ -0,0 +1,229 @@ +# Refactor Audit - feedBack desktop (Rock Band edition) + +**Date**: 2026-11-07 +**Auditor**: Claude Code (codebase-untangler skill), four read-only reviewers + spot checks +**Baseline commit**: e610887 (tag `pre-refactor-baseline`, branch `refactor/untangle-2026-11-07`) +**Stack**: Electron 35 + TypeScript main process, vanilla-JS renderer plugin, C++/JUCE native +audio engine (N-API addon), sandboxed VST host, bundled Python core + +The structured version of this audit is `.untangler/audit.json` (source of truth). Issue IDs +match. Every finding cites file:line at the baseline commit. + +## 1. App Summary + +A desktop rhythm game for real guitar (Rocksmith-style) plus Rock Band band play. Electron +hosts the bundled feedBack core (a Python server on port 18000 and its web UI). This repo adds +the desktop shell: window/pane management, auto-update (Velopack; AppImage on Linux), the +native low-latency audio engine (ASIO/WASAPI, amp/NAM/IR/VST chain, pitch and note detection, +song/renderer buses), a crash-isolated VST host, and the `audio_engine` renderer plugin +(`src/renderer/screen.js`) that drives the engine from the UI. Windows is the target that +matters; Mac/Linux build in CI. + +## 2. Entry Points + +| Type | Path / Trigger | Handler | Notes | +|------|----------------|---------|-------| +| App start | `electron .` / `feedback.exe` | `src/main/main.ts` | Bootstrap order is load-bearing (main.ts:72-107) | +| IPC (~145 channels) | `window.feedBackDesktop.*` | `src/main/preload.ts` -> `audio-bridge.ts`, `main.ts`, `plugin-manager.ts`, `pane-hosts.ts`, `update-manager.ts` | Only ~19 channels in `ipc-channels.ts` | +| Native addon | `build/Release/slopsmith_audio.node` | `src/audio/NodeAddon.cpp` (112 exports) | Contract: `tests/contracts/addon-exports.json` | +| Renderer plugin | core loads `plugin.json` -> `screen.js` | `src/renderer/screen.js` (3 IIFEs) | Single classic script; bundled by `scripts/bundle-slopsmith.sh:181-186` | +| Child process | Python core | `src/main/python.ts:463-769` | Port 18000, restart via `restartPython` | +| Child process | VST host | `src/vst-host/main.cpp` | Sandboxed plugin processing | +| Release | `scripts/release-rockband.sh X.Y.Z` | `.github/workflows/build.yml` | Tags only; CI builds + Velopack packs | + +## 3. Module Map + +| Path | LOC (approx) | Purpose | Concerns mixed? | +|------|-----|---------|-----------------| +| `src/main` | ~9,000 | Electron main process | Yes - main.ts (9 concerns), audio-bridge.ts (10), python.ts (5) | +| `src/renderer` | ~5,900 | audio_engine UI plugin | Yes - one 4,460-line closure with ~15 features | +| `src/audio` | ~18,000 | Native engine + N-API bindings | Partly - AudioEngine.cpp god-object; earlier extractions are clean | +| `src/vst-host` | ~2,000 | Sandboxed VST host process | Small duplication with VSTScan.cpp | +| `scripts` | ~2,500 | Build/bundle/release shell | Bundling split across 3 dispatchers | +| `.github/workflows` | ~1,500 | CI + releases | Signing/pack steps copied across 3 workflows | +| `tests` | ~6,000 | 30 JS test files + C++ suites | Fast and engine-loading tests mixed in one glob | + +Totals: 408 tracked files, 203 code files, ~53,000 code lines (JUCE is a submodule, excluded). + +## 4. Hotspots + +### Large files (>500 LOC) +- `src/renderer/screen.js` - 5,377 lines (30 commits; #1 by size and churn) +- `src/vst-host/main.cpp` - 1,959 +- `src/main/main.ts` - 1,539 +- `src/audio/AudioEngine.cpp` - 1,535 +- `src/main/audio-bridge.ts` - 1,467 +- `src/audio/addon/ChainOps.cpp` - 1,053 +- `src/audio/addon/DeviceBindings.cpp` - 968 +- `src/main/python.ts` - 949 +- `src/audio/SignalChain.cpp` - 876 +- `src/main/update-manager.ts` - 821 + +### High-churn +- `screen.js` 29, `AudioEngine.h` 28, `AudioEngine.cpp`/`NodeAddon.cpp`/`preload.ts`/`main.ts` 23 each, + `scripts/build-common.sh` 22, `audio-bridge.ts` 17. + +Combined LOC+churn top 5: screen.js, AudioEngine.cpp, main.ts, audio-bridge.ts, preload.ts. + +## 5. Duplication Catalogue + +| ID | What | Locations | Canonical home | +|----|------|-----------|----------------| +| I-004 | Fail-soft addon-call boilerplate (~40 copies), inconsistent guarding | `audio-bridge.ts:505-1205`; unguarded at 602-612, 728, 1010, 1031, 1035, 1040-1056, 1212, 1240, 1273-1298 | `callAddon(name, fallback, ...args)` in audio-bridge | +| I-003 | Bypass preload + MIDI tone switchers implemented twice, already drifted | IIFE1 `screen.js:2301-2340, 2682-2797, 3308-3324`; IIFE2 `4970-4995, 5029-5157` | One factory exported from IIFE1 | +| I-008 | localStorage schemas parsed/written by hand | `slopsmith-tone-mappings` 2545, 4812, 4910 (+ setItem 2981, 2999, 3011); `slopsmith-chain-presets` 1988, 2654; `slopsmith-signal-chain` 9 sites | `window._aeStore` accessors | +| I-009 | JSON config files read/written 4 ways, one non-atomic | `soundfont-manager.ts:73-79` (atomic), `audio-bridge.ts:209-221` (not atomic), `vst-crash-guard.ts:86`, `python.ts:435-441` | `src/main/json-file.ts` | +| I-010 | Resource/config path resolution computed independently | `main.ts:301-305`, `audio-bridge.ts:232-236, 308-310`, `python.ts:107-129, 373, 397, 410-421, 542, 582-586, 636-657` | `src/main/app-paths.ts` | +| I-011 | ~125 IPC channel names as bare strings in 2 files each | `audio-bridge.ts`, `main.ts`, `preload.ts:301-570`; `UpdateChannel` type x3 | `ipc-channels.ts` (after extractor update) | +| I-012 | Duplex vs split output callback mix tail (~60 lines) | `AudioEngine.cpp:1113-1182` vs `1337-1411` | pure `noexcept` helpers first | +| I-013 | N-API int parsing bypasses NapiHelpers (~25 raw `Int32Value`) | `DetectionBindings.cpp`, `DeviceBindings.cpp`, `ControlBindings.cpp:46`, `ChainOps.cpp:806` | `addon/NapiHelpers.h` `argInt`/`argSlotId` | +| I-014 | Ring consume / seqlock patterns open-coded 3x each | `AudioEngine.cpp:1250-1333, 1444-1473`, `StreamSink.cpp:87-104`, `SourceChain.cpp:235-241`, `RendererBus.h:229-317` | `PackedStereoRing::consume`, `SeqlockStamp` | +| I-015 | Legacy vs per-source binding marshalling; 5 near-identical AsyncWorkers | `DetectionBindings.cpp:119-147, 245-449` vs `DeviceBindings.cpp:631-860`; `ChainOps.cpp:419, 636-819` | `toJs(...)` helpers; `queueChainSlotMutation` | +| I-016 | CI signing / vpk pack / vpk version copied across workflows | `build.yml:95-132, 325-459`, `nightly.yml:114-317`, `rc.yml:86-110`; vpk version x3 | composite actions | +| I-017 | Bundling logic split across three dispatchers; SLOPSMITH_DIR discovery copied | `bundle.sh:14-22`, `build-windows.sh`, `build-macos.sh`, `package.json:26`, `bundle-slopsmith.sh:19-27`, `build-windows.sh:124-130` | `resolve_slopsmith_dir` + one dispatcher | + +## 6. Boundary Violations + +- **I-002** The app-wide desktop config store lives in `soundfont-manager.ts:32-79` and is + imported by `main.ts:126`, `pane-hosts.ts:28`, `python.ts:12`, which creates a require + cycle (soundfont-manager imports `restartPython`, line 15). +- **I-018** `window._toneSwitcher` is written from 18 places across both renderer IIFEs, and + ~37 `window._ae*` globals act as the cross-IIFE bus (the class of bug behind issue #12). +- **I-019** Device-settings validation is duplicated across the IPC boundary + (`screen.js:155-192` vs `audio-bridge.ts:55-96`). +- **I-020** DeviceSetup and the bindings reach into engine internals: 6 references passed to + `applySplit` (`AudioEngine.cpp:568-570, 588`), raw `SourceChain*` handed out + (`AudioEngine.h:413`), and 3 manager getters with no callers (`AudioEngine.h:32-34`). +- **I-021** Test-only loopback lives in production audio callbacks + (`AudioEngine.h:542-548`, `AudioEngine.cpp:851-862, 1089-1103, 1184-1194`). +- **I-022** C++ test targets are compiled into every release addon build + (`CMakeLists.txt:61-64`, `SLOPSMITH_BUILD_TESTS` defaults ON), but the tests are never run. + +## 7. Dead Code Candidates + +Each was verified by grep over `src/` and `tests/`. Check again before deleting. + +- `plugins:restart` IPC (`plugin-manager.ts:218-221`): no preload binding, so unreachable. +- Renderer: `meterAnimFrame` (screen.js:28), `ToneSwitcher.teardown` (2791), + `_aeLinearGainToDb`/`_aeDbToLinearGain`/`_aeFormatGainDbLabel` (110-112), + `_aeInjectSongTonePicker` (3409), `#ae-tone-automation` (settings.html:62). +- Preload audio methods with no JS caller: `setOutputDeviceType`, `getDeviceMetrics`, + `getBackingLevel`, `setStreamBusGain`, `getRendererBusMetrics`, `getSongBusMetrics`, + `isStreamOutputActive`, `getStreamUnderflowCount`, `getStreamOverflowCount`, + `setSourceMonitorMute`, `moveProcessor`, `isBackingPlaying`. Some of these are diagnostics + used from DevTools this session (`getSongBusMetrics`), so keep them. +- Addon exports with no caller: `getMonitorMuteState`, `setInputDeviceType` (NodeAddon.cpp:344, 361); + `getLatencyBreakdown` (362) looks planned, so keep it. +- AudioEngine methods with no caller: `activeExtraInputCount`, `getCurrentDeviceType`, + `getOutputGain`, `getStreamOutputDeviceName`, single-type `probeDeviceOptions`, + `setAudioDevice`, `setInputDeviceType`, `sanitizeStreamGain`, `InputDeviceSlot`; unused + includes in AudioEngine.h:13-23; stale decls in `addon/Bindings.h:116-117`. +- Repo: `tests/spike/` (self-described throwaway), orphaned `tests/chordscorer` and + `tests/mlnotedetector` (not in `tests/CMakeLists.txt`), `scripts/dev/renderer-bus-spike.js`, + `scripts/VST_TRACE_README.md`, two unreferenced docs, the `bundle.sh:28` IR step (copies a + gitignored dir), and the `rc.yml` trigger on `release/**`. + +Tracked as **I-023** (one batch, after Top 5). + +## 8. Dependency Issues + +### Unused +- None found. `lottie-web` is only copied into dist and could be a devDependency. + +### Redundant / drift +- **I-005** `package-lock.json` is gitignored (`.gitignore:52`). CI and the build scripts run + `npm install` with caret ranges (electron `^35.0.0`), so the addon is built against + whatever Electron 35.x resolves that day. `.build-config.json` has an `electron` version + that nothing reads. +- **I-024** Windows ffmpeg/vgmstream/get-pip are unpinned "latest" with no checksum + (`build-windows.sh:108, 184, 224`, `bundle-binaries.sh:139`). macOS is pinned. + +### Version concerns +- **I-025** `package.json:3` is frozen at 0.3.0 while tags are at v0.4.17, so + `app.getVersion()`, the Linux updater (`update-manager.ts:173`), the migration stamp + (`main.ts:1197`) and Linux artifact names all report 0.3.0. +- Electron 35 is past its support window. Upgrade separately (out of scope). + +## 9. Risk Register + +| ID | File | Concern | Risk if changed / left | +|----|------|---------|------------------------| +| I-002 | `soundfont-manager.ts:65-79` | A corrupt desktop config is read as `{}` and the next write (every quit, `main.ts:514-523`) drops all prefs | User loses window, LAN, pane and soundfont settings | +| I-006 | `scripts/build-common.sh:211-215` | A failed plugin clone is skipped silently (`2>/dev/null`); a green release can ship without rig_builder/five_fret/rockherosmith | Features vanish for users on auto-update | +| I-026 | `scripts/bundle-slopsmith.sh:176` | Strips `rig_builder/vst`, but song tones store absolute VST paths into it, and local builds don't match CI | Song tones break after a CI release (plugin-side fix needed too) | +| I-003 | `screen.js:4755-4893` vs `4445-4464` | Two song-load pipelines rebuild the native chain; only one holds `_applyToneMappingsLock` | Overlapping clear+load = wrong or empty tone at song start | +| I-007 | `python.ts:943-947`, `main.ts:1325-1342` | `restartPython` races (no serialization, unawaited); port can drift to 18001; Windows grandchildren survive | Renderer talks to a dead port; orphaned Python | +| I-027 | `audio-bridge.ts:1219-1225, 1375`, `plugin-manager.ts:156-173` | Renderer-supplied paths reach the filesystem unchecked; `plugins:remove` is a recursive rm with no confirm | Plugin scripts can write/delete files | +| I-028 | `AudioEngine.cpp:1033,1040,1240`, `SignalChain.cpp:122-170, 260-285`, `SandboxedProcessor.cpp:508-523` | Audio-thread hazards: fprintf, call_once+sigaction on first plugin call, alloc+mutex on plugin crash, up to 4x block wait on the sandbox | Dropouts. Flag only; do not refactor inside the callbacks | +| I-029 | `AudioEngine.cpp:945-948` | `songBusPullScratch` is sized only by the input-side about-to-start | Song audio silently dropped on an output-only start | +| I-030 | `update-manager.ts:261-339` | Linux AppImage self-update never checks size/hash before renaming over the running binary | Truncated download bricks the app (Linux only) | +| I-031 | `screen.js:1582-1588, 1642` | Meter/latency `setInterval`s not kept in `hookState`; re-evaluation stacks pollers | Extra IPC load grows per re-eval | +| I-032 | `main.ts:262-268, 565, 582, 667` | Global handlers log message only (no stack); IPC registered inside `createWindow` | Hard-to-debug failures; "second handler" throw on re-create | +| I-033 | `build.yml:178-182` (+ nightly, rc) | upterm SSH opens on every failed build while signing secrets are loaded | Remote shell on a job holding secrets | + +## 10. Test Coverage + +- **JS (30 files):** 24 source-only files run locally (155 pass, 0 fail at baseline). 6 load + the native engine (`chain-mutation-storm`, `contract-check`, `live-pitch`, + `ml-note-detection`, `multi-source`, `napi-arg-fuzz`). +- **CI runs none of them** (**I-001**): `ci.yml:39-48` runs install, typecheck and audit only. + `ctest` runs only the sandbox suites (`sandbox.yml`). `tests/engine_units`, + `audio_sanitize`, `live_pitch`, `onset_lag` never run in CI, and the engine JS tests can't + run on the owner's machine (they grab ASIO and lag the PC). So the engine-level tests run + nowhere. +- **`npm test` mixes both kinds** (`package.json:13`), so the only safe local command is a + long `grep -v` line. +- Renderer tests are all source-reading (extract a function into `vm`, or match literal + substrings). Nothing exercises init, presets, the tone panel, the IIFE2 preload or the race. +- No tests: main.ts (incl. navigation security predicates), python.ts, update-manager.ts, + soundfont-manager/desktop config, plugin-manager validators, pane-hosts, vst-crash-guard; + both C++ output callbacks, DeviceSetup apply*, ExtraInputs, StreamSink, BackingPlayer, + SignalChain, ChainOps workers. +- **Refactor constraint:** many tests match exact source text (`tests/contracts/extract.js:23-29` + regex over `ipcMain.handle('...'`, `renderer-iife-scope`, `renderer-capability-migration` + ~45 substrings, `heard-clock-wiring` exact-count checks). Every Top 5 change has to update + the affected test in the same commit and keep the contract snapshots identical. + +## 11. TOP 5 PRIORITIES + +In order. These are what Phase 3 fixes. Each one is behaviour-preserving apart from the noted +safety fixes. + +1. **[I-001] Split the test suite and run it in CI.** Move the 6 engine-loading tests to + `tests/engine/`, add `test:fast` / `test:engine` scripts (`test` = fast), and run fast in + `ci.yml` plus engine + C++ unit suites in `addon-ci.yml`. This is the safety net for + everything else, and it makes the safe local command one word. Blocks 2-5. +2. **[I-002] Move the desktop config out of soundfont-manager and stop a corrupt file from + wiping it.** Extract `desktop-config.ts` (re-exported from soundfont-manager for one + release), which also breaks the require cycle. On a parse failure, keep a `.corrupt` + backup and don't overwrite blindly. Critical: user settings. +3. **[I-006] Make bundling fail loudly.** A plugin clone that fails stops the build (unless + `ALLOW_MISSING_PLUGINS=1`), and stderr is no longer hidden. The same goes for the + desktop-plugin copy (`bundle-slopsmith.sh:185`). Critical: releases. +4. **[I-004] One fail-soft helper for addon calls in audio-bridge.** Add + `callAddon(name, fallback, ...args)` and `PITCH_NONE`, applied one handler group at a + time with the literal `ipcMain.handle('...'` lines kept. This removes ~300 lines and fixes + the ~15 unguarded native calls that can reject into the renderer. Defaults and warn text + must stay identical. +5. **[I-003] One tone-switcher and one chain lock in the renderer.** Export a single + bypass/MIDI switcher factory from IIFE1, call it from IIFE2 (removing the drifted copy and + restoring `tonePresetNameMap` + `normalizeTimelineToneData` there), and route the IIFE2 + song-load preload through `_applyToneMappingsLock`. Needs new vm tests first, plus a check + on the local packaged build, since it touches what you hear at song start. + +Issues 6+ are deferred to a later pass. Next in line: I-005 (lockfile + `npm ci`), I-007 +(restartPython race), I-008 (localStorage store), I-025 (version number), I-027 (path +validation). + +## 12. Out of Scope + +- Framework upgrades (Electron 35 -> current) +- Real-time audio-thread rework (I-028 is flag-only) +- Any change to latency/timing behaviour (just retuned and measured) +- rig_builder absolute-path fix (belongs in the plugin repo; I-026 tracks the desktop side) +- Performance optimisation, new features, visual/UX changes +- Splitting `screen.js` into multiple files (needs a bundle concat step first; later cycle) + +## 13. Sign-off + +User confirmed Top 5 on: __________ (timestamp recorded in state.json) From d5794016f6a240f2232343ee34ea076a7f123394 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:27:24 -0800 Subject: [PATCH 03/25] docs: untangler I-001 scoped to fast tests in the existing CI check Co-Authored-By: Claude Opus 5.5 --- .untangler/audit.json | 2 +- REFACTOR_AUDIT.md | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.untangler/audit.json b/.untangler/audit.json index 4ca56a7..1c65f02 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -14,7 +14,7 @@ ], "description": "CI runs no JS or C++ unit tests; the 6 engine-loading JS tests cannot run on the owner machine.", "status": "pending", - "refactor_plan": "Move engine tests to tests/engine/, add test:fast/test:engine (test=fast), run fast in ci.yml and engine + ctest unit suites in addon-ci.yml.", + "refactor_plan": "Move engine tests to tests/engine/, add test:fast/test:engine (test=fast), add one npm run test:fast step to the existing ci.yml check job. User scope 2026-11-07: no new CI jobs, no engine lane, nothing added to build.yml/release builds.", "commits": [] }, { diff --git a/REFACTOR_AUDIT.md b/REFACTOR_AUDIT.md index f111799..3acb297 100644 --- a/REFACTOR_AUDIT.md +++ b/REFACTOR_AUDIT.md @@ -189,9 +189,11 @@ Tracked as **I-023** (one batch, after Top 5). In order. These are what Phase 3 fixes. Each one is behaviour-preserving apart from the noted safety fixes. -1. **[I-001] Split the test suite and run it in CI.** Move the 6 engine-loading tests to - `tests/engine/`, add `test:fast` / `test:engine` scripts (`test` = fast), and run fast in - `ci.yml` plus engine + C++ unit suites in `addon-ci.yml`. This is the safety net for +1. **[I-001] Split the test suite; run only the fast tests in CI.** Move the 6 engine-loading + tests to `tests/engine/`, add `test:fast` / `test:engine` scripts (`test` = fast), and add + one `npm run test:fast` step to the existing `ci.yml` check job (Ubuntu, after typecheck; + the suite takes under a second). Scope set by the user on 2026-11-07: no new CI jobs, no + engine lane, nothing added to the release build (`build.yml`). This is the safety net for everything else, and it makes the safe local command one word. Blocks 2-5. 2. **[I-002] Move the desktop config out of soundfont-manager and stop a corrupt file from wiping it.** Extract `desktop-config.ts` (re-exported from soundfont-manager for one From 4ed8da5e499bd4629731c2ef7986b7aef8deed9a Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:33:34 -0800 Subject: [PATCH 04/25] chore: untangler Top 5 signed off, enter phase 2 Co-Authored-By: Claude Opus 5.5 --- .untangler/STATE.md | 6 +++--- .untangler/state.json | 16 +++++++++------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/.untangler/STATE.md b/.untangler/STATE.md index 00d1212..9475825 100644 --- a/.untangler/STATE.md +++ b/.untangler/STATE.md @@ -1,15 +1,15 @@ # Codebase Untangler - State **Started**: 2026-11-07T20:48:45.568531+00:00 -**Current phase**: 1 (Audit) +**Current phase**: 2 (Safety Net) **Branch**: refactor/untangle-2026-11-07 **Stack**: electron, typescript, vanilla-js-renderer, cpp-juce-node-addon, vst-sandbox, python-bundled-core ## Phase progress - [x] Phase 0: Triage (done) -- [~] Phase 1: Audit (in_progress) -- [ ] Phase 2: Safety Net (pending) +- [x] Phase 1: Audit (done) +- [~] Phase 2: Safety Net (in_progress) - [ ] Phase 3: Refactor (pending) - [ ] Phase 4: Hardening (pending) - [ ] Phase 5: Handover (pending) diff --git a/.untangler/state.json b/.untangler/state.json index 96668c7..786161c 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -1,7 +1,7 @@ { "schema_version": 1, "started_at": "2026-11-07T20:48:45.568531+00:00", - "current_phase": 1, + "current_phase": 2, "phases": { "0": { "name": "Triage", @@ -12,14 +12,16 @@ }, "1": { "name": "Audit", - "status": "in_progress", + "status": "done", "gates": {}, - "started_at": "2026-11-07T20:50:20.953556+00:00" + "started_at": "2026-11-07T20:50:20.953556+00:00", + "completed_at": "2026-11-09T14:33:34.237429+00:00" }, "2": { "name": "Safety Net", - "status": "pending", - "gates": {} + "status": "in_progress", + "gates": {}, + "started_at": "2026-11-09T14:33:34.238429+00:00" }, "3": { "name": "Refactor", @@ -60,7 +62,7 @@ "vst-sandbox", "python-bundled-core" ], - "top_5_signed_off_at": null, + "top_5_signed_off_at": "2026-11-09T14:33:29Z", "overrides": [], "stack_reference_note": "No matching stack file; read node-express.md as the closest (Node process) and applied its general patterns", "last_test_run": { @@ -72,5 +74,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 1: user to sign off on the Top 5 (I-001, I-002, I-006, I-004, I-003) or swap items; then record top_5_signed_off_at and run check_gate.py 1" + "next_action": "Phase 2: plan + build a verified safety net for each Top 5 item (I-001, I-002, I-006, I-004, I-003), source-reading tests only; prove one fails when broken" } \ No newline at end of file From d332dc536cee70672c422481d765aebc5c2fbfac Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:42:33 -0800 Subject: [PATCH 05/25] test: untangler phase 2 safety nets for the Top 5 Snapshot of every audio:* handler's fallbacks (I-004), desktop config read/write (I-002), plugin clone harness (I-006), tone switcher parity across both IIFEs (I-003), and a test-file inventory (I-001). Each guarded spot was broken on purpose and the matching test failed. Co-Authored-By: Claude Opus 5.5 --- .untangler/RUNNING.md | 2 +- .untangler/audit.json | 57 +- .untangler/state.json | 2 +- tests/_load-ts-stubbed.js | 50 + tests/audio-bridge-fallbacks.test.js | 127 + tests/build-plugin-clone.test.js | 79 + tests/desktop-config.test.js | 76 + .../audio-bridge-fallbacks.snapshot.json | 2054 +++++++++++++++++ tests/test-inventory.test.js | 59 + tests/tone-switcher-parity.test.js | 174 ++ 10 files changed, 2672 insertions(+), 8 deletions(-) create mode 100644 tests/_load-ts-stubbed.js create mode 100644 tests/audio-bridge-fallbacks.test.js create mode 100644 tests/build-plugin-clone.test.js create mode 100644 tests/desktop-config.test.js create mode 100644 tests/fixtures/audio-bridge-fallbacks.snapshot.json create mode 100644 tests/test-inventory.test.js create mode 100644 tests/tone-switcher-parity.test.js diff --git a/.untangler/RUNNING.md b/.untangler/RUNNING.md index a7b02c1..011faba 100644 --- a/.untangler/RUNNING.md +++ b/.untangler/RUNNING.md @@ -37,7 +37,7 @@ in dev mode; prefer the packaged build for any check the user will hear. Only targeted, source-reading tests on this machine. NEVER the full `npm test`. -Safe baseline set (24 files, 155 tests, all passing at baseline, < 1 s): +Safe set (27 files, 162 tests incl. the Phase 2 safety nets, all passing, ~1.5 s): ```bash node --test $(ls tests/*.test.js | grep -v -E "chain-mutation-storm|contract-check|live-pitch|ml-note-detection|multi-source|napi-arg-fuzz|config-bootstrap|config-reset") diff --git a/.untangler/audit.json b/.untangler/audit.json index 1c65f02..5f474f0 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -15,7 +15,14 @@ "description": "CI runs no JS or C++ unit tests; the 6 engine-loading JS tests cannot run on the owner machine.", "status": "pending", "refactor_plan": "Move engine tests to tests/engine/, add test:fast/test:engine (test=fast), add one npm run test:fast step to the existing ci.yml check job. User scope 2026-11-07: no new CI jobs, no engine lane, nothing added to build.yml/release builds.", - "commits": [] + "commits": [], + "safety_net": { + "type": "unit_test", + "location": "tests/test-inventory.test.js", + "status": "verified", + "broken_then_fixed": false, + "covers": "Pins all 35 node:test files (none dropped/duplicated by the move to tests/engine/) and that only the 6 engine files load the native addon." + } }, { "id": "I-002", @@ -31,7 +38,15 @@ "description": "Parse failure returns {} and the next write drops every setting; the module also causes a require cycle.", "status": "pending", "refactor_plan": "Extract desktop-config.ts (re-export for one release); on parse failure keep a .corrupt backup and do not overwrite blindly; add a test.", - "commits": [] + "commits": [], + "safety_net": { + "type": "unit_test", + "location": "tests/desktop-config.test.js", + "status": "verified", + "broken_then_fixed": true, + "covers": "Missing file -> {}, pretty atomic write (no .tmp left), shallow merge keeps unknown keys, corrupt file -> {} then next set writes, import sites in main/pane-hosts/python.", + "proof": "Dropping the 2-space indent in setDesktopConfig failed the test; reverted." + } }, { "id": "I-003", @@ -46,7 +61,21 @@ "description": "IIFE2 copies of the bypass/MIDI switchers lack tonePresetNameMap and normalizeTimelineToneData; the IIFE2 preload is not serialized by _applyToneMappingsLock.", "status": "pending", "refactor_plan": "Add vm tests, export one switcher factory + chain-job lock from IIFE1, call from IIFE2; verify on the packaged build.", - "commits": [] + "commits": [], + "safety_net": { + "type": "unit_test", + "location": "tests/tone-switcher-parity.test.js", + "status": "verified", + "broken_then_fixed": true, + "covers": "IIFE1 ToneSwitcher preload+switch engine calls pinned; IIFE2 bypass switcher must issue identical calls; all 3 MIDI switcher copies must send identical program changes. Records the tonePresetNameMap drift.", + "proof": "Flipping bypassed:false to true in the IIFE2 switcher failed the parity test; reverted.", + "manual_checks": [ + "Packaged build: song with tone changes, auto-switch on -> tones switch at the right points, chain panel shows the right preset names", + "Packaged build: MIDI PC song -> program changes reach the VST, chain is not wiped", + "Packaged build: song with a whole-song tone lock -> locked preset holds through tone changes", + "Packaged build: start one song then quickly another -> chain ends up with the second song's presets only (preload race)" + ] + } }, { "id": "I-004", @@ -60,7 +89,15 @@ "description": "Same typeof-guard/try/warn/default pattern copied ~40 times; inconsistent guarding lets native throws reject into the renderer.", "status": "pending", "refactor_plan": "callAddon(name, fallback, ...args) + PITCH_NONE, one handler group per commit; keep literal ipcMain.handle lines, defaults and warn text.", - "commits": [] + "commits": [], + "safety_net": { + "type": "snapshot", + "location": "tests/audio-bridge-fallbacks.test.js + tests/fixtures/audio-bridge-fallbacks.snapshot.json", + "status": "verified", + "broken_then_fixed": true, + "covers": "All 111 audio:* IPC handlers called with addon missing / every export throwing / every export returning; return values, throws/rejections and warn/error text snapshotted.", + "proof": "Changing addSource's no-addon default (-1 -> -2) and the detectNotes warning text each failed the test; reverted. Snapshot shows 55 handlers that throw when the addon throws (unguarded) - guarding them is a behaviour change to decide explicitly in Phase 3." + } }, { "id": "I-005", @@ -91,7 +128,15 @@ "description": "git clone 2>/dev/null || echo skipped; a green release can ship without a plugin.", "status": "pending", "refactor_plan": "Show stderr; fail when cloned != total unless ALLOW_MISSING_PLUGINS=1; fail loudly on the desktop plugin copy.", - "commits": [] + "commits": [], + "safety_net": { + "type": "integration_test", + "location": "tests/build-plugin-clone.test.js", + "status": "verified", + "broken_then_fixed": true, + "covers": "Runs real clone_slopsmith() in bash (set -euo pipefail) with git stubbed: pins the 38 plugin dirs, the skipped/Cloned N of M report on a failed plugin clone (exit 0 today, I-006 flips it), and that a failed core clone aborts.", + "proof": "Deleting the scorecard entry and renaming five_fret to five-fret both failed the test; reverted. Note: the repo->dirname fallback rule is dead code (every entry has an explicit dirname), so breaking it is not detected." + } }, { "id": "I-007", @@ -530,4 +575,4 @@ "I-032", "I-033" ] -} \ No newline at end of file +} diff --git a/.untangler/state.json b/.untangler/state.json index 786161c..86b3a1b 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -74,5 +74,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 2: plan + build a verified safety net for each Top 5 item (I-001, I-002, I-006, I-004, I-003), source-reading tests only; prove one fails when broken" + "next_action": "Phase 2 gate passed 11/11; user to acknowledge the safety nets (incl. I-003 manual packaged-build checklist), then advance 2 and start Phase 3 with I-001" } \ No newline at end of file diff --git a/tests/_load-ts-stubbed.js b/tests/_load-ts-stubbed.js new file mode 100644 index 0000000..0058630 --- /dev/null +++ b/tests/_load-ts-stubbed.js @@ -0,0 +1,50 @@ +// Shared helper: transpile a main-process TypeScript module and load it with a +// controlled require(), so electron, sibling modules and the native addon can +// be replaced by stubs. Sibling './x' imports that are not stubbed are loaded +// the same way (transpiled from src). Nothing here starts electron or the +// native audio engine. +const fs = require('node:fs'); +const path = require('node:path'); +const ts = require('typescript'); + +const ROOT = path.join(__dirname, '..'); + +// stubs: { [requestId]: exports } where requestId is exactly what the module +// passes to require ('electron', './python', ...). resolveExtra(id) may return +// a value for ids not in stubs (return undefined to fall through); used for +// computed paths such as the native addon. +function loadTsStubbed(relPath, stubs = {}, resolveExtra = () => undefined, cache = new Map()) { + const file = path.join(ROOT, relPath); + if (cache.has(file)) return cache.get(file).exports; + const source = fs.readFileSync(file, 'utf8'); + const compiled = ts.transpileModule(source, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2022, + esModuleInterop: true, + }, + fileName: file, + }).outputText; + const mod = { exports: {} }; + cache.set(file, mod); + const dir = path.dirname(file); + const req = (id) => { + if (Object.prototype.hasOwnProperty.call(stubs, id)) return stubs[id]; + const extra = resolveExtra(id); + if (extra !== undefined) return extra; + if (id.startsWith('.')) { + const tsFile = path.join(dir, id + '.ts'); + if (fs.existsSync(tsFile)) { + return loadTsStubbed(path.relative(ROOT, tsFile), stubs, resolveExtra, cache); + } + } + return require(id); + }; + // eslint-disable-next-line no-new-func + new Function('exports', 'require', 'module', '__filename', '__dirname', compiled)( + mod.exports, req, mod, file, dir, + ); + return mod.exports; +} + +module.exports = { loadTsStubbed, ROOT }; diff --git a/tests/audio-bridge-fallbacks.test.js b/tests/audio-bridge-fallbacks.test.js new file mode 100644 index 0000000..2f247a2 --- /dev/null +++ b/tests/audio-bridge-fallbacks.test.js @@ -0,0 +1,127 @@ +// Untangler safety net for I-004 (callAddon helper in audio-bridge.ts). +// +// Registers every audio:* IPC handler against a stubbed electron and a fake +// native addon, calls each one, and compares what it returns (and what it +// logs) with a committed snapshot. Three addon states are covered: +// missing - the .node file cannot be loaded (audio === null) +// throws - init() works, every other export throws +// returns - every export returns a tagged value +// Folding the ~40 copies of "if (!audio) return X; try {...} catch {warn}" +// into one helper must leave this snapshot byte-identical. +// +// Regenerate (only when a behaviour change is intended): +// UPDATE_SNAPSHOT=1 node --test tests/audio-bridge-fallbacks.test.js +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { loadTsStubbed, ROOT } = require('./_load-ts-stubbed'); + +const SNAPSHOT = path.join(__dirname, 'fixtures', 'audio-bridge-fallbacks.snapshot.json'); +// Fixed argument list handed to every handler after the event. +const ARGS = [0, 'x', 0]; + +function fakeAddon(mode) { + return new Proxy({}, { + get(_t, name) { + if (typeof name !== 'string' || name === 'then') return undefined; + if (name === 'init') return () => undefined; + if (mode === 'throws') return () => { throw new Error(`boom:${name}`); }; + return (...a) => `ret:${name}:${a.length}`; + }, + has() { return true; }, + }); +} + +function settle(value) { + if (!value || typeof value.then !== 'function') return Promise.resolve({ ret: value }); + return Promise.race([ + value.then((ret) => ({ ret }), (e) => ({ rejected: String(e && e.message) })), + new Promise((r) => setTimeout(() => r({ pending: true }), 100)), + ]); +} + +function normalize(value, tmp) { + const s = JSON.stringify(value === undefined ? null : value, (_k, v) => { + if (v === undefined) return ''; + if (typeof v === 'number' && !Number.isFinite(v)) return `<${v}>`; + if (typeof v === 'function') return ''; + return v; + }); + return JSON.parse( + s.split(tmp.replace(/\\/g, '\\\\')).join('') + .split(tmp).join('') + .split(ROOT.replace(/\\/g, '\\\\')).join('') + .split(ROOT).join(''), + ); +} + +async function runScenario(mode) { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), `untangler-i004-${mode}-`)); + const handlers = new Map(); + const reg = (kind) => (channel, fn) => handlers.set(channel, { kind, fn }); + const electron = { + ipcMain: { handle: reg('handle'), on: reg('on') }, + app: { getPath: () => tmp, isPackaged: false }, + }; + const stubs = { + electron, + './debug-log': { isDebugEnabled: () => false, getDebugLogPath: () => path.join(tmp, 'debug.log') }, + './vst-crash-guard': { + initVstCrashGuard: () => [], + armSentinel() {}, disarmSentinel() {}, armEditorSentinel() {}, + getSentinelPath: () => path.join(tmp, 'sentinel'), + }, + }; + const addon = mode === 'missing' ? null : fakeAddon(mode); + const resolveExtra = (id) => { + if (!id.endsWith('slopsmith_audio.node')) return undefined; + if (!addon) throw new Error('not found'); + return addon; + }; + + const logs = []; + const orig = { log: console.log, warn: console.warn, error: console.error }; + console.log = () => {}; + console.warn = (...a) => logs.push(['warn', a.map(String).join(' ')]); + console.error = (...a) => logs.push(['error', a.map(String).join(' ')]); + const out = {}; + try { + const bridge = loadTsStubbed('src/main/audio-bridge.ts', stubs, resolveExtra); + bridge.initAudioBridge(); + logs.length = 0; + for (const channel of [...handlers.keys()].sort()) { + const { kind, fn } = handlers.get(channel); + let result; + try { + result = await settle(fn({ sender: { send() {} } }, ...ARGS)); + } catch (e) { + result = { threw: String(e && e.message) }; + } + out[channel] = normalize({ kind, ...result, logs: logs.splice(0) }, tmp); + } + } finally { + Object.assign(console, orig); + fs.rmSync(tmp, { recursive: true, force: true }); + } + return out; +} + +test('audio-bridge handler fallbacks match the snapshot', async () => { + const actual = {}; + for (const mode of ['missing', 'throws', 'returns']) actual[mode] = await runScenario(mode); + + if (process.env.UPDATE_SNAPSHOT === '1' || !fs.existsSync(SNAPSHOT)) { + fs.mkdirSync(path.dirname(SNAPSHOT), { recursive: true }); + fs.writeFileSync(SNAPSHOT, JSON.stringify(actual, null, 2) + '\n'); + } + const expected = JSON.parse(fs.readFileSync(SNAPSHOT, 'utf8')); + assert.equal(Object.keys(actual.missing).length, 111, 'handler count changed'); + for (const mode of Object.keys(expected)) { + for (const channel of Object.keys(expected[mode])) { + assert.deepEqual(actual[mode][channel], expected[mode][channel], `${mode} ${channel}`); + } + assert.deepEqual(Object.keys(actual[mode]), Object.keys(expected[mode]), `${mode} channel set`); + } +}); diff --git a/tests/build-plugin-clone.test.js b/tests/build-plugin-clone.test.js new file mode 100644 index 0000000..55b40ce --- /dev/null +++ b/tests/build-plugin-clone.test.js @@ -0,0 +1,79 @@ +// Untangler safety net for I-006 (a failed plugin clone must fail the build). +// +// Runs the real clone_slopsmith() from scripts/build-common.sh in bash under +// `set -euo pipefail` (as the build does), with `git` replaced by a shell +// function that only creates directories. No network, nothing outside a temp +// dir. Pins the plugin list and the repo -> directory-name mapping, and the +// current (lenient) failure behaviour that I-006 is meant to change. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const SRC = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'build-common.sh'), 'utf8'); +const FN = SRC.match(/^clone_slopsmith\(\) \{[\s\S]*?^\}$/m)[0]; + +const EXPECTED_DIRS = [ + // Snapshot of every bundled plugin directory as of the untangler baseline. + // Adding/removing a plugin is a deliberate edit to this list. + 'autotune', 'bongocat', 'camera_director', 'drums', 'editor', 'five_fret', + 'flappy_bend', 'fretboard', 'guitar_theory', 'invert_highway', 'jumpingtab', 'loose_folder', + 'lyrics_karaoke', 'metronome', 'midi', 'multiplayer', 'musicxml_import', 'nam_tone', + 'notedetect', 'piano', 'practice', 'rig_builder', 'rockherosmith', 'scorecard', + 'sectionmap', 'song_preview', 'splitscreen', 'staffview', 'stem_splitter', 'stems', + 'stepmode', 'strum_fighter', 'studio', 'tabview', 'themes', 'transpose_chords', + 'tutorials', 'virtuoso', +]; + +function run(failPattern = '') { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'untangler-i006-')); + const harness = ` +set -euo pipefail +git() { + local dest="\${@: -1}" url="\${@: -2:1}" + if [[ -n "$FAIL" && "$url" == *"$FAIL"* ]]; then return 128; fi + mkdir -p "$dest/plugins" +} +${FN} +unset SLOPSMITH_DIR +clone_slopsmith "$TMPC/clone" +echo "DIRS:$(cd "$TMPC/clone/plugins" && ls -1 | tr '\\n' ' ')" +`; + const r = spawnSync('bash', ['-c', harness], { + env: { ...process.env, FAIL: failPattern, TMPC: tmp.replace(/\\/g, '/'), GH_CLONE_TOKEN: '' }, + encoding: 'utf8', + timeout: 30000, + }); + fs.rmSync(tmp, { recursive: true, force: true }); + const dirs = ((r.stdout.match(/^DIRS:(.*)$/m) || [])[1] || '').trim().split(/\s+/).filter(Boolean).sort(); + return { status: r.status, out: r.stdout, err: r.stderr, dirs }; +} + +test('all clones succeed: every plugin lands in its expected directory', () => { + const r = run(); + assert.equal(r.status, 0, r.err); + const m = r.out.match(/Cloned (\d+) of (\d+) plugins/); + assert.ok(m, r.out); + assert.equal(m[1], m[2]); + assert.equal(r.dirs.length, Number(m[2])); + assert.deepEqual(r.dirs, EXPECTED_DIRS); + for (const d of r.dirs) assert.match(d, /^[a-z0-9_]+$/, `plugin dir "${d}" is not a valid module name`); +}); + +test('a failed plugin clone is reported (current behaviour: build continues)', () => { + const r = run('feedBack-plugin-scorecard'); + assert.match(r.out, /skipped mattromano\/feedBack-plugin-scorecard/); + assert.match(r.out, /Cloned (\d+) of (\d+) plugins/); + const [, got, total] = r.out.match(/Cloned (\d+) of (\d+) plugins/); + assert.equal(Number(got), Number(total) - 1); + assert.ok(!r.dirs.includes('scorecard')); + // I-006 flips this to a non-zero exit unless ALLOW_MISSING_PLUGINS=1. + assert.equal(r.status, 0); +}); + +test('a failed core clone stops the build', () => { + const r = run('mattromano/feedBack.git'); + assert.notEqual(r.status, 0); +}); diff --git a/tests/desktop-config.test.js b/tests/desktop-config.test.js new file mode 100644 index 0000000..df8a1f9 --- /dev/null +++ b/tests/desktop-config.test.js @@ -0,0 +1,76 @@ +// Untangler safety net for I-002 (extract desktop-config.ts out of +// soundfont-manager.ts). Pins how /slopsmith-desktop.json is read and +// written, through the module every caller imports today. Electron and +// python.ts are stubbed; nothing is spawned. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { loadTsStubbed } = require('./_load-ts-stubbed'); + +function load() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'untangler-i002-')); + const stubs = { + electron: { + app: { getPath: () => dir, isPackaged: false }, + ipcMain: { handle() {}, on() {} }, + BrowserWindow: { getAllWindows: () => [] }, + }, + './python': { restartPython: async () => {} }, + }; + const mod = loadTsStubbed('src/main/soundfont-manager.ts', stubs); + const file = path.join(dir, 'slopsmith-desktop.json'); + return { mod, dir, file, done: () => fs.rmSync(dir, { recursive: true, force: true }) }; +} + +test('missing config file reads as {}', () => { + const t = load(); + try { + assert.deepEqual(t.mod.getDesktopConfig(), {}); + } finally { t.done(); } +}); + +test('set writes pretty JSON atomically and get reads it back', () => { + const t = load(); + try { + t.mod.setDesktopConfig({ lanAccess: true }); + assert.equal(fs.readFileSync(t.file, 'utf8'), JSON.stringify({ lanAccess: true }, null, 2)); + assert.equal(fs.existsSync(t.file + '.tmp'), false, 'tmp file left behind'); + assert.deepEqual(t.mod.getDesktopConfig(), { lanAccess: true }); + } finally { t.done(); } +}); + +test('set merges shallowly and keeps keys it does not know about', () => { + const t = load(); + try { + fs.writeFileSync(t.file, JSON.stringify({ futureKey: 1, paneWindows: { a: { alwaysOnTop: true } } })); + t.mod.setDesktopConfig({ startFullscreen: true }); + t.mod.setDesktopConfig({ paneWindows: { b: { alwaysOnTop: false } } }); + assert.deepEqual(t.mod.getDesktopConfig(), { + futureKey: 1, + startFullscreen: true, + paneWindows: { b: { alwaysOnTop: false } }, // shallow: replaces, not deep-merged + }); + } finally { t.done(); } +}); + +test('corrupt config reads as {} and the next set still writes the patch', () => { + const t = load(); + try { + fs.writeFileSync(t.file, '{ not json'); + assert.deepEqual(t.mod.getDesktopConfig(), {}); + t.mod.setDesktopConfig({ lanAccess: false }); + assert.deepEqual(t.mod.getDesktopConfig(), { lanAccess: false }); + // I-002 will additionally keep the corrupt bytes as a .corrupt backup; + // that assertion is added with the change itself. + } finally { t.done(); } +}); + +test('callers keep importing the config API from one place', () => { + // Pins the import sites the extraction must move together. + const src = (f) => fs.readFileSync(path.join(__dirname, '..', 'src', 'main', f), 'utf8'); + for (const f of ['main.ts', 'pane-hosts.ts', 'python.ts']) { + assert.match(src(f), /import \{[^}]*getDesktopConfig[^}]*\} from '\.\/(soundfont-manager|desktop-config)'/, f); + } +}); diff --git a/tests/fixtures/audio-bridge-fallbacks.snapshot.json b/tests/fixtures/audio-bridge-fallbacks.snapshot.json new file mode 100644 index 0000000..5dae9de --- /dev/null +++ b/tests/fixtures/audio-bridge-fallbacks.snapshot.json @@ -0,0 +1,2054 @@ +{ + "missing": { + "audio-effects:activateSegment": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:inspectRoute": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "0" + } + }, + "logs": [] + }, + "audio-effects:loadChainPlan": { + "kind": "handle", + "ret": { + "outcome": "unavailable", + "status": "unavailable", + "reason": "Native audio engine is unavailable" + }, + "logs": [] + }, + "audio-effects:releaseRoute": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setRouteGain": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setStageBypass": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setStageParameter": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio:addSource": { + "kind": "handle", + "ret": -1, + "logs": [] + }, + "audio:bindInputDevice": { + "kind": "handle", + "ret": "unsupported", + "logs": [] + }, + "audio:clearChain": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:clearStreamOutput": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:closePluginEditor": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:detectNotes": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:getBackingDuration": { + "kind": "handle", + "ret": 0, + "logs": [] + }, + "audio:getBackingLevel": { + "kind": "handle", + "ret": 0, + "logs": [] + }, + "audio:getBackingPosition": { + "kind": "handle", + "ret": 0, + "logs": [] + }, + "audio:getBufferSizes": { + "kind": "handle", + "ret": [], + "logs": [] + }, + "audio:getChainState": { + "kind": "handle", + "ret": [], + "logs": [] + }, + "audio:getCurrentDevice": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:getDeviceMetrics": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:getDeviceTypes": { + "kind": "handle", + "ret": [], + "logs": [] + }, + "audio:getKnownPlugins": { + "kind": "handle", + "ret": [], + "logs": [] + }, + "audio:getLevels": { + "kind": "handle", + "ret": { + "inputLevel": 0, + "outputLevel": 0, + "inputPeak": 0, + "outputPeak": 0 + }, + "logs": [] + }, + "audio:getLivePitch": { + "kind": "handle", + "ret": { + "supported": false, + "cents": 0, + "windowMs": 0, + "ratio": 1, + "latencyMs": 0 + }, + "logs": [] + }, + "audio:getNoteVerdicts": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:getParameters": { + "kind": "handle", + "ret": [], + "logs": [] + }, + "audio:getPitchDetection": { + "kind": "handle", + "ret": { + "frequency": -1, + "confidence": 0, + "midiNote": -1, + "cents": 0, + "noteName": "" + }, + "logs": [] + }, + "audio:getRawAudioFrame": { + "kind": "handle", + "ret": {}, + "logs": [] + }, + "audio:getRawPitch": { + "kind": "handle", + "ret": { + "frequency": -1, + "confidence": 0, + "midiNote": -1, + "cents": 0, + "noteName": "" + }, + "logs": [] + }, + "audio:getRendererBusMetrics": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:getSampleRate": { + "kind": "handle", + "ret": 48000, + "logs": [] + }, + "audio:getSampleRates": { + "kind": "handle", + "ret": [], + "logs": [] + }, + "audio:getSongBusClock": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:getSongBusMetrics": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:getSourceLevels": { + "kind": "handle", + "ret": { + "inputLevel": 0, + "outputLevel": 0, + "inputPeak": 0, + "outputPeak": 0 + }, + "logs": [] + }, + "audio:getSourceNoteVerdicts": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:getSourcePitchDetection": { + "kind": "handle", + "ret": { + "frequency": -1, + "confidence": 0, + "midiNote": -1, + "cents": 0, + "noteName": "" + }, + "logs": [] + }, + "audio:getSourceRawAudioFrame": { + "kind": "handle", + "ret": {}, + "logs": [] + }, + "audio:getSourceRawPitch": { + "kind": "handle", + "ret": { + "frequency": -1, + "confidence": 0, + "midiNote": -1, + "cents": 0, + "noteName": "" + }, + "logs": [] + }, + "audio:getStreamOverflowCount": { + "kind": "handle", + "ret": 0, + "logs": [] + }, + "audio:getStreamSinkLevel": { + "kind": "handle", + "ret": 0, + "logs": [] + }, + "audio:getStreamUnderflowCount": { + "kind": "handle", + "ret": 0, + "logs": [] + }, + "audio:isAudioRunning": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:isAvailable": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:isBackingPlaying": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:isMlNoteDetection": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:isMonitorMuted": { + "kind": "handle", + "ret": true, + "logs": [] + }, + "audio:isStreamOutputActive": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:listInputDevices": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:listSources": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:loadBackingTrack": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:loadDeviceSettings": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:loadIR": { + "kind": "handle", + "ret": -1, + "logs": [] + }, + "audio:loadNAMModel": { + "kind": "handle", + "ret": -1, + "logs": [] + }, + "audio:loadPluginList": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:loadPreset": { + "kind": "handle", + "ret": { + "success": false, + "error": "No audio" + }, + "logs": [] + }, + "audio:loadVST": { + "kind": "handle", + "ret": -1, + "logs": [] + }, + "audio:moveProcessor": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:openPluginEditor": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:probeDeviceOptions": { + "kind": "handle", + "ret": { + "type": "", + "inputType": "", + "outputType": "", + "input": "x", + "output": "", + "inputChannels": [], + "outputChannels": [], + "sampleRates": [], + "bufferSizes": [], + "compatible": false, + "error": "Native audio addon not available" + }, + "logs": [] + }, + "audio:pushRendererAudio": { + "kind": "on", + "ret": "", + "logs": [] + }, + "audio:pushSongAudio": { + "kind": "on", + "ret": "", + "logs": [] + }, + "audio:removeProcessor": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:removeSource": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:replaceIR": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:resetPeaks": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:saveDeviceSettings": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:savePluginList": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:savePreset": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:scanPlugins": { + "kind": "handle", + "ret": [], + "logs": [] + }, + "audio:scoreChord": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:scoreSourceChord": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:seekBacking": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:sendMidiToSlot": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setBackingSpeed": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setBranch": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setBranchSrc": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setBypass": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setChart": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:setDevice": { + "kind": "handle", + "ret": { + "ok": false, + "error": "Native audio addon not available", + "duplex": true + }, + "logs": [] + }, + "audio:setDeviceType": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setGain": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setInputChannel": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setLivePitch": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setMonitorKill": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setMonitorMute": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setMonitorMuteSuppressed": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setMultiBypass": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setNoiseGate": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setNoteDetectionEnabled": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setOutputDeviceType": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setPan": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setParameter": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setPostGain": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setRendererBus": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSlotState": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setSongBus": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSourceChart": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:setSourceInputChannel": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSourceMonitorMute": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSourceVerifierOffset": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setStreamBus": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setStreamBusGain": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setStreamOutputDevice": { + "kind": "handle", + "ret": "unsupported", + "logs": [] + }, + "audio:setTonePolish": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:startAudio": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:startBacking": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:stopAudio": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:stopBacking": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:unbindInputDevice": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "debug:isEnabled": { + "kind": "handle", + "ret": false, + "logs": [] + } + }, + "throws": { + "audio-effects:activateSegment": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:inspectRoute": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "0" + } + }, + "logs": [] + }, + "audio-effects:loadChainPlan": { + "kind": "handle", + "ret": { + "outcome": "failed", + "status": "failed", + "reason": "Audio-effects chain plan validation failed", + "payload": { + "errors": [ + "Missing audio-effects chain plan" + ] + } + }, + "logs": [] + }, + "audio-effects:releaseRoute": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setRouteGain": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setStageBypass": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setStageParameter": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio:addSource": { + "kind": "handle", + "ret": -1, + "logs": [ + [ + "warn", + "[audio] addSource failed: boom:addSource" + ] + ] + }, + "audio:bindInputDevice": { + "kind": "handle", + "ret": "invalid deviceKey", + "logs": [] + }, + "audio:clearChain": { + "kind": "handle", + "rejected": "boom:clearChain", + "logs": [] + }, + "audio:clearStreamOutput": { + "kind": "handle", + "threw": "boom:clearStreamOutput", + "logs": [] + }, + "audio:closePluginEditor": { + "kind": "handle", + "threw": "boom:closePluginEditor", + "logs": [] + }, + "audio:detectNotes": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] detectNotes failed: boom:detectNotes" + ] + ] + }, + "audio:getBackingDuration": { + "kind": "handle", + "threw": "boom:getBackingDuration", + "logs": [] + }, + "audio:getBackingLevel": { + "kind": "handle", + "threw": "boom:getBackingLevel", + "logs": [] + }, + "audio:getBackingPosition": { + "kind": "handle", + "threw": "boom:getBackingPosition", + "logs": [] + }, + "audio:getBufferSizes": { + "kind": "handle", + "threw": "boom:getBufferSizes", + "logs": [] + }, + "audio:getChainState": { + "kind": "handle", + "threw": "boom:getChainState", + "logs": [] + }, + "audio:getCurrentDevice": { + "kind": "handle", + "threw": "boom:getCurrentDevice", + "logs": [] + }, + "audio:getDeviceMetrics": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] getDeviceMetrics failed: boom:getDeviceMetrics" + ] + ] + }, + "audio:getDeviceTypes": { + "kind": "handle", + "threw": "boom:getDeviceTypes", + "logs": [] + }, + "audio:getKnownPlugins": { + "kind": "handle", + "threw": "boom:getKnownPlugins", + "logs": [] + }, + "audio:getLevels": { + "kind": "handle", + "threw": "boom:getLevels", + "logs": [] + }, + "audio:getLivePitch": { + "kind": "handle", + "ret": { + "supported": false, + "cents": 0, + "windowMs": 0, + "ratio": 1, + "latencyMs": 0 + }, + "logs": [ + [ + "warn", + "[audio] getLivePitch failed: boom:getLivePitch" + ] + ] + }, + "audio:getNoteVerdicts": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] getNoteVerdicts failed: boom:getNoteVerdicts" + ] + ] + }, + "audio:getParameters": { + "kind": "handle", + "threw": "boom:getParameters", + "logs": [] + }, + "audio:getPitchDetection": { + "kind": "handle", + "threw": "boom:getPitchDetection", + "logs": [] + }, + "audio:getRawAudioFrame": { + "kind": "handle", + "ret": {}, + "logs": [] + }, + "audio:getRawPitch": { + "kind": "handle", + "ret": { + "frequency": -1, + "confidence": 0, + "midiNote": -1, + "cents": 0, + "noteName": "" + }, + "logs": [] + }, + "audio:getRendererBusMetrics": { + "kind": "handle", + "threw": "boom:getRendererBusMetrics", + "logs": [] + }, + "audio:getSampleRate": { + "kind": "handle", + "ret": 48000, + "logs": [] + }, + "audio:getSampleRates": { + "kind": "handle", + "threw": "boom:getSampleRates", + "logs": [] + }, + "audio:getSongBusClock": { + "kind": "handle", + "threw": "boom:getSongBusClock", + "logs": [] + }, + "audio:getSongBusMetrics": { + "kind": "handle", + "threw": "boom:getSongBusMetrics", + "logs": [] + }, + "audio:getSourceLevels": { + "kind": "handle", + "ret": { + "inputLevel": 0, + "outputLevel": 0, + "inputPeak": 0, + "outputPeak": 0 + }, + "logs": [ + [ + "warn", + "[audio] getSourceLevels failed: boom:getSourceLevels" + ] + ] + }, + "audio:getSourceNoteVerdicts": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] getSourceNoteVerdicts failed: boom:getSourceNoteVerdicts" + ] + ] + }, + "audio:getSourcePitchDetection": { + "kind": "handle", + "ret": { + "frequency": -1, + "confidence": 0, + "midiNote": -1, + "cents": 0, + "noteName": "" + }, + "logs": [ + [ + "warn", + "[audio] getSourcePitchDetection failed: boom:getSourcePitchDetection" + ] + ] + }, + "audio:getSourceRawAudioFrame": { + "kind": "handle", + "ret": {}, + "logs": [ + [ + "warn", + "[audio] getSourceRawAudioFrame failed: boom:getSourceRawAudioFrame" + ] + ] + }, + "audio:getSourceRawPitch": { + "kind": "handle", + "ret": { + "frequency": -1, + "confidence": 0, + "midiNote": -1, + "cents": 0, + "noteName": "" + }, + "logs": [ + [ + "warn", + "[audio] getSourceRawPitch failed: boom:getSourceRawPitchDetection" + ] + ] + }, + "audio:getStreamOverflowCount": { + "kind": "handle", + "threw": "boom:getStreamOverflowCount", + "logs": [] + }, + "audio:getStreamSinkLevel": { + "kind": "handle", + "threw": "boom:getStreamSinkLevel", + "logs": [] + }, + "audio:getStreamUnderflowCount": { + "kind": "handle", + "threw": "boom:getStreamUnderflowCount", + "logs": [] + }, + "audio:isAudioRunning": { + "kind": "handle", + "threw": "boom:isAudioRunning", + "logs": [] + }, + "audio:isAvailable": { + "kind": "handle", + "ret": true, + "logs": [] + }, + "audio:isBackingPlaying": { + "kind": "handle", + "threw": "boom:isBackingPlaying", + "logs": [] + }, + "audio:isMlNoteDetection": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:isMonitorMuted": { + "kind": "handle", + "threw": "boom:isMonitorMuted", + "logs": [] + }, + "audio:isStreamOutputActive": { + "kind": "handle", + "threw": "boom:isStreamOutputActive", + "logs": [] + }, + "audio:listInputDevices": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] listInputDevices failed: boom:listInputDevices" + ] + ] + }, + "audio:listSources": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] listSources failed: boom:listSources" + ] + ] + }, + "audio:loadBackingTrack": { + "kind": "handle", + "threw": "boom:loadBackingTrack", + "logs": [] + }, + "audio:loadDeviceSettings": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:loadIR": { + "kind": "handle", + "rejected": "boom:loadIR", + "logs": [] + }, + "audio:loadNAMModel": { + "kind": "handle", + "rejected": "boom:loadNAMModel", + "logs": [] + }, + "audio:loadPluginList": { + "kind": "handle", + "threw": "boom:loadPluginList", + "logs": [] + }, + "audio:loadPreset": { + "kind": "handle", + "rejected": "boom:loadPreset", + "logs": [] + }, + "audio:loadVST": { + "kind": "handle", + "rejected": "boom:loadVST", + "logs": [] + }, + "audio:moveProcessor": { + "kind": "handle", + "rejected": "boom:moveProcessor", + "logs": [] + }, + "audio:openPluginEditor": { + "kind": "handle", + "threw": "boom:getChainState", + "logs": [] + }, + "audio:probeDeviceOptions": { + "kind": "handle", + "ret": { + "type": "", + "inputType": "", + "outputType": "", + "input": "x", + "output": "", + "inputChannels": [], + "outputChannels": [], + "sampleRates": [], + "bufferSizes": [], + "compatible": false, + "error": "boom:probeDeviceOptions" + }, + "logs": [ + [ + "warn", + "[audio] probeDeviceOptions threw: boom:probeDeviceOptions" + ] + ] + }, + "audio:pushRendererAudio": { + "kind": "on", + "ret": "", + "logs": [] + }, + "audio:pushSongAudio": { + "kind": "on", + "ret": "", + "logs": [] + }, + "audio:removeProcessor": { + "kind": "handle", + "rejected": "boom:removeProcessor", + "logs": [] + }, + "audio:removeSource": { + "kind": "handle", + "ret": false, + "logs": [ + [ + "warn", + "[audio] removeSource failed: boom:removeSource" + ] + ] + }, + "audio:replaceIR": { + "kind": "handle", + "rejected": "boom:replaceIR", + "logs": [] + }, + "audio:resetPeaks": { + "kind": "handle", + "threw": "boom:resetPeaks", + "logs": [] + }, + "audio:saveDeviceSettings": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:savePluginList": { + "kind": "handle", + "threw": "boom:savePluginList", + "logs": [] + }, + "audio:savePreset": { + "kind": "handle", + "threw": "boom:savePreset", + "logs": [] + }, + "audio:scanPlugins": { + "kind": "handle", + "rejected": "boom:scanPlugins", + "logs": [] + }, + "audio:scoreChord": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] scoreChord failed: boom:scoreChord" + ] + ] + }, + "audio:scoreSourceChord": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] scoreSourceChord failed: boom:scoreSourceChord" + ] + ] + }, + "audio:seekBacking": { + "kind": "handle", + "threw": "boom:seekBacking", + "logs": [] + }, + "audio:sendMidiToSlot": { + "kind": "handle", + "threw": "boom:sendMidiToSlot", + "logs": [] + }, + "audio:setBackingSpeed": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setBranch": { + "kind": "handle", + "threw": "boom:setBranch", + "logs": [] + }, + "audio:setBranchSrc": { + "kind": "handle", + "threw": "boom:setBranchSrc", + "logs": [] + }, + "audio:setBypass": { + "kind": "handle", + "threw": "boom:setBypass", + "logs": [] + }, + "audio:setChart": { + "kind": "handle", + "ret": null, + "logs": [ + [ + "warn", + "[audio] setChart failed: boom:setChart" + ] + ] + }, + "audio:setDevice": { + "kind": "handle", + "ret": { + "ok": false, + "error": "boom:setDevice", + "duplex": true + }, + "logs": [ + [ + "warn", + "[audio] setDevice threw: boom:setDevice" + ] + ] + }, + "audio:setDeviceType": { + "kind": "handle", + "threw": "boom:setDeviceType", + "logs": [] + }, + "audio:setGain": { + "kind": "handle", + "threw": "boom:setGain", + "logs": [] + }, + "audio:setInputChannel": { + "kind": "handle", + "threw": "boom:setInputChannel", + "logs": [] + }, + "audio:setLivePitch": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setMonitorKill": { + "kind": "handle", + "threw": "boom:setMonitorKill", + "logs": [] + }, + "audio:setMonitorMute": { + "kind": "handle", + "threw": "boom:setMonitorMute", + "logs": [] + }, + "audio:setMonitorMuteSuppressed": { + "kind": "handle", + "threw": "boom:setMonitorMuteSuppressed", + "logs": [] + }, + "audio:setMultiBypass": { + "kind": "handle", + "threw": "boom:setMultiBypass", + "logs": [] + }, + "audio:setNoiseGate": { + "kind": "handle", + "threw": "boom:setNoiseGate", + "logs": [] + }, + "audio:setNoteDetectionEnabled": { + "kind": "handle", + "ret": "", + "logs": [ + [ + "warn", + "[audio] setNoteDetectionEnabled failed: boom:setNoteDetectionEnabled" + ] + ] + }, + "audio:setOutputDeviceType": { + "kind": "handle", + "ret": false, + "logs": [ + [ + "warn", + "[audio] setOutputDeviceType failed: boom:setOutputDeviceType" + ] + ] + }, + "audio:setPan": { + "kind": "handle", + "threw": "boom:setPan", + "logs": [] + }, + "audio:setParameter": { + "kind": "handle", + "threw": "boom:setParameter", + "logs": [] + }, + "audio:setPostGain": { + "kind": "handle", + "threw": "boom:setPostGain", + "logs": [] + }, + "audio:setRendererBus": { + "kind": "handle", + "threw": "boom:setRendererBus", + "logs": [] + }, + "audio:setSlotState": { + "kind": "handle", + "ret": false, + "logs": [ + [ + "warn", + "[audio-bridge] setSlotState threw: Error: boom:setSlotState" + ] + ] + }, + "audio:setSongBus": { + "kind": "handle", + "threw": "boom:setSongBus", + "logs": [] + }, + "audio:setSourceChart": { + "kind": "handle", + "ret": false, + "logs": [ + [ + "warn", + "[audio] setSourceChart failed: boom:setSourceChart" + ] + ] + }, + "audio:setSourceInputChannel": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSourceMonitorMute": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSourceVerifierOffset": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setStreamBus": { + "kind": "handle", + "threw": "boom:setStreamBus", + "logs": [] + }, + "audio:setStreamBusGain": { + "kind": "handle", + "threw": "boom:setStreamBusGain", + "logs": [] + }, + "audio:setStreamOutputDevice": { + "kind": "handle", + "ret": "invalid arguments", + "logs": [] + }, + "audio:setTonePolish": { + "kind": "handle", + "threw": "boom:setTonePolish", + "logs": [] + }, + "audio:startAudio": { + "kind": "handle", + "threw": "boom:startAudio", + "logs": [] + }, + "audio:startBacking": { + "kind": "handle", + "threw": "boom:startBacking", + "logs": [] + }, + "audio:stopAudio": { + "kind": "handle", + "threw": "boom:stopAudio", + "logs": [] + }, + "audio:stopBacking": { + "kind": "handle", + "threw": "boom:stopBacking", + "logs": [] + }, + "audio:unbindInputDevice": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "debug:isEnabled": { + "kind": "handle", + "ret": false, + "logs": [] + } + }, + "returns": { + "audio-effects:activateSegment": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:inspectRoute": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "0" + } + }, + "logs": [] + }, + "audio-effects:loadChainPlan": { + "kind": "handle", + "ret": { + "outcome": "failed", + "status": "failed", + "reason": "Audio-effects chain plan validation failed", + "payload": { + "errors": [ + "Missing audio-effects chain plan" + ] + } + }, + "logs": [] + }, + "audio-effects:releaseRoute": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setRouteGain": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setStageBypass": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio-effects:setStageParameter": { + "kind": "handle", + "ret": { + "outcome": "no-target", + "status": "no-target", + "reason": "No audio-effects route has been loaded", + "payload": { + "routeKey": "desktop-main" + } + }, + "logs": [] + }, + "audio:addSource": { + "kind": "handle", + "ret": "ret:addSource:2", + "logs": [] + }, + "audio:bindInputDevice": { + "kind": "handle", + "ret": "invalid deviceKey", + "logs": [] + }, + "audio:clearChain": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:clearStreamOutput": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:closePluginEditor": { + "kind": "handle", + "ret": "ret:closePluginEditor:1", + "logs": [] + }, + "audio:detectNotes": { + "kind": "handle", + "ret": "ret:detectNotes:0", + "logs": [] + }, + "audio:getBackingDuration": { + "kind": "handle", + "ret": "ret:getBackingDuration:0", + "logs": [] + }, + "audio:getBackingLevel": { + "kind": "handle", + "ret": "ret:getBackingLevel:0", + "logs": [] + }, + "audio:getBackingPosition": { + "kind": "handle", + "ret": "ret:getBackingPosition:0", + "logs": [] + }, + "audio:getBufferSizes": { + "kind": "handle", + "ret": "ret:getBufferSizes:0", + "logs": [] + }, + "audio:getChainState": { + "kind": "handle", + "ret": "ret:getChainState:0", + "logs": [] + }, + "audio:getCurrentDevice": { + "kind": "handle", + "ret": "ret:getCurrentDevice:0", + "logs": [] + }, + "audio:getDeviceMetrics": { + "kind": "handle", + "ret": "ret:getDeviceMetrics:0", + "logs": [] + }, + "audio:getDeviceTypes": { + "kind": "handle", + "threw": "result.map is not a function", + "logs": [] + }, + "audio:getKnownPlugins": { + "kind": "handle", + "ret": "ret:getKnownPlugins:0", + "logs": [] + }, + "audio:getLevels": { + "kind": "handle", + "ret": "ret:getLevels:0", + "logs": [] + }, + "audio:getLivePitch": { + "kind": "handle", + "ret": "ret:getLivePitch:0", + "logs": [] + }, + "audio:getNoteVerdicts": { + "kind": "handle", + "ret": "ret:getNoteVerdicts:0", + "logs": [] + }, + "audio:getParameters": { + "kind": "handle", + "ret": "ret:getParameters:1", + "logs": [] + }, + "audio:getPitchDetection": { + "kind": "handle", + "ret": "ret:getPitchDetection:0", + "logs": [] + }, + "audio:getRawAudioFrame": { + "kind": "handle", + "ret": "ret:getRawAudioFrame:1", + "logs": [] + }, + "audio:getRawPitch": { + "kind": "handle", + "ret": "ret:getRawPitchDetection:0", + "logs": [] + }, + "audio:getRendererBusMetrics": { + "kind": "handle", + "ret": "ret:getRendererBusMetrics:0", + "logs": [] + }, + "audio:getSampleRate": { + "kind": "handle", + "ret": 48000, + "logs": [] + }, + "audio:getSampleRates": { + "kind": "handle", + "ret": "ret:getSampleRates:0", + "logs": [] + }, + "audio:getSongBusClock": { + "kind": "handle", + "ret": "ret:getSongBusClock:0", + "logs": [] + }, + "audio:getSongBusMetrics": { + "kind": "handle", + "ret": "ret:getSongBusMetrics:0", + "logs": [] + }, + "audio:getSourceLevels": { + "kind": "handle", + "ret": "ret:getSourceLevels:1", + "logs": [] + }, + "audio:getSourceNoteVerdicts": { + "kind": "handle", + "ret": "ret:getSourceNoteVerdicts:1", + "logs": [] + }, + "audio:getSourcePitchDetection": { + "kind": "handle", + "ret": "ret:getSourcePitchDetection:1", + "logs": [] + }, + "audio:getSourceRawAudioFrame": { + "kind": "handle", + "ret": "ret:getSourceRawAudioFrame:2", + "logs": [] + }, + "audio:getSourceRawPitch": { + "kind": "handle", + "ret": "ret:getSourceRawPitchDetection:1", + "logs": [] + }, + "audio:getStreamOverflowCount": { + "kind": "handle", + "ret": "ret:getStreamOverflowCount:0", + "logs": [] + }, + "audio:getStreamSinkLevel": { + "kind": "handle", + "ret": "ret:getStreamSinkLevel:0", + "logs": [] + }, + "audio:getStreamUnderflowCount": { + "kind": "handle", + "ret": "ret:getStreamUnderflowCount:0", + "logs": [] + }, + "audio:isAudioRunning": { + "kind": "handle", + "ret": "ret:isAudioRunning:0", + "logs": [] + }, + "audio:isAvailable": { + "kind": "handle", + "ret": true, + "logs": [] + }, + "audio:isBackingPlaying": { + "kind": "handle", + "ret": "ret:isBackingPlaying:0", + "logs": [] + }, + "audio:isMlNoteDetection": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:isMonitorMuted": { + "kind": "handle", + "ret": "ret:isMonitorMuted:0", + "logs": [] + }, + "audio:isStreamOutputActive": { + "kind": "handle", + "ret": "ret:isStreamOutputActive:0", + "logs": [] + }, + "audio:listInputDevices": { + "kind": "handle", + "ret": "ret:listInputDevices:0", + "logs": [] + }, + "audio:listSources": { + "kind": "handle", + "ret": "ret:listSources:0", + "logs": [] + }, + "audio:loadBackingTrack": { + "kind": "handle", + "ret": "ret:loadBackingTrack:1", + "logs": [] + }, + "audio:loadDeviceSettings": { + "kind": "handle", + "ret": null, + "logs": [] + }, + "audio:loadIR": { + "kind": "handle", + "ret": "ret:loadIR:1", + "logs": [] + }, + "audio:loadNAMModel": { + "kind": "handle", + "ret": "ret:loadNAMModel:1", + "logs": [] + }, + "audio:loadPluginList": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:loadPreset": { + "kind": "handle", + "ret": "ret:loadPreset:1", + "logs": [] + }, + "audio:loadVST": { + "kind": "handle", + "ret": "ret:loadVST:1", + "logs": [] + }, + "audio:moveProcessor": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:openPluginEditor": { + "kind": "handle", + "threw": "((intermediate value) ?? []).find is not a function", + "logs": [] + }, + "audio:probeDeviceOptions": { + "kind": "handle", + "ret": { + "type": "", + "inputType": "", + "outputType": "", + "input": "x", + "output": "", + "inputChannels": [], + "outputChannels": [], + "sampleRates": [], + "bufferSizes": [], + "compatible": false, + "error": "" + }, + "logs": [] + }, + "audio:pushRendererAudio": { + "kind": "on", + "ret": "", + "logs": [] + }, + "audio:pushSongAudio": { + "kind": "on", + "ret": "", + "logs": [] + }, + "audio:removeProcessor": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:removeSource": { + "kind": "handle", + "ret": "ret:removeSource:1", + "logs": [] + }, + "audio:replaceIR": { + "kind": "handle", + "ret": "ret:replaceIR:3", + "logs": [] + }, + "audio:resetPeaks": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:saveDeviceSettings": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:savePluginList": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:savePreset": { + "kind": "handle", + "ret": "ret:savePreset:0", + "logs": [] + }, + "audio:scanPlugins": { + "kind": "handle", + "ret": "ret:scanPlugins:1", + "logs": [] + }, + "audio:scoreChord": { + "kind": "handle", + "ret": "ret:scoreChord:1", + "logs": [] + }, + "audio:scoreSourceChord": { + "kind": "handle", + "ret": "ret:scoreSourceChord:2", + "logs": [] + }, + "audio:seekBacking": { + "kind": "handle", + "ret": "ret:seekBacking:1", + "logs": [] + }, + "audio:sendMidiToSlot": { + "kind": "handle", + "ret": "ret:sendMidiToSlot:5", + "logs": [] + }, + "audio:setBackingSpeed": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setBranch": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setBranchSrc": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setBypass": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setChart": { + "kind": "handle", + "ret": "ret:setChart:1", + "logs": [] + }, + "audio:setDevice": { + "kind": "handle", + "ret": { + "ok": false, + "error": "Native audio device call returned an unsupported result", + "duplex": true, + "sampleRate": 0, + "inputBlockSize": 0, + "outputBlockSize": 0 + }, + "logs": [] + }, + "audio:setDeviceType": { + "kind": "handle", + "ret": "ret:setDeviceType:1", + "logs": [] + }, + "audio:setGain": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setInputChannel": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setLivePitch": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "audio:setMonitorKill": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setMonitorMute": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setMonitorMuteSuppressed": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setMultiBypass": { + "kind": "handle", + "ret": "ret:setMultiBypass:1", + "logs": [] + }, + "audio:setNoiseGate": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setNoteDetectionEnabled": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setOutputDeviceType": { + "kind": "handle", + "ret": "ret:setOutputDeviceType:1", + "logs": [] + }, + "audio:setPan": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setParameter": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setPostGain": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setRendererBus": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSlotState": { + "kind": "handle", + "ret": true, + "logs": [] + }, + "audio:setSongBus": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSourceChart": { + "kind": "handle", + "ret": "ret:setSourceChart:2", + "logs": [] + }, + "audio:setSourceInputChannel": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSourceMonitorMute": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setSourceVerifierOffset": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setStreamBus": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setStreamBusGain": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:setStreamOutputDevice": { + "kind": "handle", + "ret": "invalid arguments", + "logs": [] + }, + "audio:setTonePolish": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:startAudio": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:startBacking": { + "kind": "handle", + "ret": "ret:startBacking:0", + "logs": [] + }, + "audio:stopAudio": { + "kind": "handle", + "ret": "", + "logs": [] + }, + "audio:stopBacking": { + "kind": "handle", + "ret": "ret:stopBacking:0", + "logs": [] + }, + "audio:unbindInputDevice": { + "kind": "handle", + "ret": false, + "logs": [] + }, + "debug:isEnabled": { + "kind": "handle", + "ret": false, + "logs": [] + } + } +} diff --git a/tests/test-inventory.test.js b/tests/test-inventory.test.js new file mode 100644 index 0000000..6649fce --- /dev/null +++ b/tests/test-inventory.test.js @@ -0,0 +1,59 @@ +// Untangler safety net for I-001 (split the suite into a fast lane and an +// engine lane). Pins the full set of node:test files so the move into +// tests/engine/ cannot silently drop one, and checks that every test outside +// the engine set stays engine-free (never loads build/Release/*.node), which is +// what makes the fast lane safe to run on any machine and in CI. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const TESTS = __dirname; + +// Tests that load the native engine (directly or via tests/contracts/extract.js). +const ENGINE = [ + 'chain-mutation-storm', 'contract-check', 'live-pitch', + 'ml-note-detection', 'multi-source', 'napi-arg-fuzz', +]; + +// Every node:test file at the untangler baseline plus the Phase 2 safety nets. +const ALL = [ + 'audio-bridge-fallbacks', 'audio-chain-persistence', 'audio-effects-executor', + 'build-plugin-clone', 'chain-mutation-storm', 'config-bootstrap', + 'config-migrations', 'config-paths', 'config-reset', 'contract-check', + 'desktop-config', 'device-setup-lifecycle', 'engine-no-default-mic', + 'guitar-input-channel-default', 'heard-clock-wiring', 'input-source-selection-sync', + 'juce-exclusive-type-name', 'library-path-config', 'linux-update-decision', + 'live-pitch', 'live-retune-follow-song', 'ml-note-detection', + 'monitor-mute-suppression', 'multi-source', 'napi-arg-fuzz', + 'preset-swap-mute', 'renderer-capability-migration', 'renderer-iife-scope', + 'song-tone-lock', 'startup-missing-input', 'test-inventory', + 'tone-automation-base-tone', 'tone-load-no-stall', 'tone-switcher-parity', + 'window-bounds', +]; + +function listTests(dir, rel = '') { + const out = []; + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + if (e.isDirectory()) { + if (e.name === 'fixtures' || e.name === 'node_modules') continue; + out.push(...listTests(path.join(dir, e.name), path.join(rel, e.name))); + } else if (e.name.endsWith('.test.js')) { + out.push({ name: e.name.replace(/\.test\.js$/, ''), file: path.join(dir, e.name) }); + } + } + return out; +} + +const found = listTests(TESTS); + +test('no node:test file was added, dropped or duplicated', () => { + const names = found.map((t) => t.name).sort(); + assert.deepEqual(names, [...ALL].sort()); +}); + +test('only the engine set loads the native addon', () => { + const loads = (src) => /'Release'/.test(src) || /require\(['"]\.\/contracts\/extract(\.js)?['"]\)/.test(src); + const actual = found.filter((t) => t.name !== 'test-inventory' && loads(fs.readFileSync(t.file, 'utf8'))).map((t) => t.name).sort(); + assert.deepEqual(actual, [...ENGINE].sort()); +}); diff --git a/tests/tone-switcher-parity.test.js b/tests/tone-switcher-parity.test.js new file mode 100644 index 0000000..0b26f36 --- /dev/null +++ b/tests/tone-switcher-parity.test.js @@ -0,0 +1,174 @@ +// Untangler safety net for I-003 (one tone-switcher factory shared by both +// screen.js IIFEs). +// +// Today the bypass switcher exists twice (IIFE 1's ToneSwitcher class and an +// object literal in IIFE 2's song preload) and the MIDI program-change +// switcher three times. These tests run every copy against the same scripted +// tone sequence with a fake audio API and require identical engine calls, so +// collapsing them into one factory cannot change what reaches the engine. +// The preload race (IIFE 2 not serialised by _applyToneMappingsLock) is not +// unit-testable here; it is covered by the packaged-build checklist in +// .untangler/audit.json (I-003 safety_net.manual_checks). +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const SRC = fs.readFileSync(path.join(__dirname, '..', 'src', 'renderer', 'screen.js'), 'utf8').replace(/\r\n/g, '\n'); + +function braceBlock(src, openIdx) { + let i = openIdx + 1, depth = 1; + while (i < src.length && depth > 0) { if (src[i] === '{') depth++; else if (src[i] === '}') depth--; i++; } + return src.slice(openIdx, i); +} +function extractDecl(src, head) { + const start = src.indexOf(head); + assert.ok(start !== -1, `${head} not found`); + const open = head.startsWith('class ') ? src.indexOf('{', start) : src.indexOf('{', src.indexOf(')', start)); + return src.slice(start, open) + braceBlock(src, open); +} +// The object literal assigned to window._toneSwitcher at the first assignment +// after `anchor`. +function switcherLiteral(anchor) { + const a = SRC.indexOf(anchor); + assert.ok(a !== -1, `anchor not found: ${anchor}`); + const assign = SRC.indexOf('window._toneSwitcher = {', a); + assert.ok(assign !== -1 && assign - a < 2000, `no switcher literal near: ${anchor}`); + return braceBlock(SRC, SRC.indexOf('{', assign)); +} + +// ── Shared fixture ────────────────────────────────────────────────────────── +const PRESETS = { + CleanP: { + items: [{ type: 'NAM', path: 'a.nam' }, { type: 'VST', path: 'v.vst3' }], + nativePreset: JSON.stringify({ chain: [{ type: 1, path: 'a.nam' }, { type: 0, path: 'v.vst3', state: 'S1' }] }), + }, + LeadP: { + items: [{ type: 'VST', path: 'w.vst3' }], + nativePreset: JSON.stringify({ chain: [{ type: 0, path: 'w.vst3', state: 'S2' }] }), + }, +}; +const MAPPINGS = { Clean: 'CleanP', Lead: 'LeadP' }; +const TONE_CHANGES = [{ name: 'Lead', time: 10 }, { name: 'Clean', time: 20 }]; +const TONE_BASE = 'Clean'; +const SEQUENCE = ['Lead', 'Lead', 'Nope', 'Clean']; + +function fakeApi(log) { + let next = 1; + const rec = (name, ret) => (...a) => { log.push([name, ...a]); return typeof ret === 'function' ? ret() : ret; }; + return { + clearChain: rec('clearChain', undefined), + loadNAMModel: rec('loadNAMModel', () => next++), + loadIR: rec('loadIR', () => next++), + loadVST: rec('loadVST', () => next++), + setSlotState: rec('setSlotState', true), + setMultiBypass: rec('setMultiBypass', undefined), + sendMidiToSlot: rec('sendMidiToSlot', undefined), + }; +} +const quiet = { log() {}, warn() {}, error() {} }; +// Values built inside the vm realm have foreign prototypes; compare as plain data. +const plain = (v) => JSON.parse(JSON.stringify(v)); + +// ── Bypass switcher ───────────────────────────────────────────────────────── +test('IIFE 1 ToneSwitcher: preload and switch call the engine as pinned', async () => { + const log = []; + const ctx = { + console: quiet, + localStorage: { setItem() {} }, + api: fakeApi(log), + getPresets: () => PRESETS, + resolveTonePresetName: (m, n) => m[n] || m.$default, + aeIsRigBuilderStage: () => false, + applyPresetGainLevels: (p) => log.push(['gain', p === PRESETS.CleanP ? 'CleanP' : 'LeadP']), + applyPresetNoiseGate: () => log.push(['gate']), + applyPresetTonePolish: () => log.push(['polish']), + refreshChain: async () => log.push(['refreshChain']), + chainContainer: null, + $: () => null, + }; + vm.runInNewContext([ + extractDecl(SRC, 'function getPresetItems('), + extractDecl(SRC, 'function getToneChangeTime('), + extractDecl(SRC, 'async function loadPresetItemsWithState('), + extractDecl(SRC, 'class ToneSwitcher'), + 'this.ToneSwitcher = ToneSwitcher;', + ].join('\n'), ctx); + + const sw = new ctx.ToneSwitcher(); + await sw.preloadForSong(TONE_CHANGES, TONE_BASE, MAPPINGS); + assert.deepEqual(plain(log.splice(0)), [ + ['clearChain'], + ['loadNAMModel', 'a.nam'], + ['loadVST', 'v.vst3'], + ['setSlotState', 2, 'S1'], + ['loadVST', 'w.vst3'], + ['setSlotState', 3, 'S2'], + ['setMultiBypass', [{ slotId: 3, bypassed: true }]], + ['gain', 'CleanP'], ['gate'], ['polish'], + ['refreshChain'], + ]); + assert.deepEqual(plain(sw.toneSlotMap), { Clean: [1, 2], Lead: [3] }); + assert.deepEqual(plain(sw.tonePresetNameMap), { Clean: 'CleanP', Lead: 'LeadP' }); + assert.equal(sw.activeTone, 'Clean'); + + for (const t of SEQUENCE) sw.switchToTone(t); + assert.deepEqual(plain(log), BYPASS_SWITCH_CALLS); +}); + +const BYPASS_SWITCH_CALLS = [ + ['setMultiBypass', [{ slotId: 1, bypassed: true }, { slotId: 2, bypassed: true }, { slotId: 3, bypassed: false }]], + ['gain', 'LeadP'], ['gate'], ['polish'], + ['setMultiBypass', [{ slotId: 3, bypassed: true }, { slotId: 1, bypassed: false }, { slotId: 2, bypassed: false }]], + ['gain', 'CleanP'], ['gate'], ['polish'], +]; + +test('IIFE 2 bypass switcher switches exactly like IIFE 1', () => { + const log = []; + const ctx = { + console: quiet, + api: fakeApi(log), + effectiveBase: 'Clean', + toneSlotMap: { Clean: [1, 2], Lead: [3] }, + tonePresetMap: { Clean: PRESETS.CleanP, Lead: PRESETS.LeadP }, + applyPresetGainLevels: (_api, p) => log.push(['gain', p === PRESETS.CleanP ? 'CleanP' : 'LeadP']), + applyPresetNoiseGate: () => log.push(['gate']), + applyPresetTonePolish: () => log.push(['polish']), + }; + vm.runInNewContext(`this.sw = ${switcherLiteral('const initialPreset = tonePresetMap[effectiveBase];')};`, ctx); + for (const t of SEQUENCE) ctx.sw.switchToTone(t); + assert.deepEqual(plain(log), BYPASS_SWITCH_CALLS); + // Known drift (I-003): this copy has no tonePresetNameMap, so the chain + // panel's preset-name lookup misses for bypass songs loaded via IIFE 2. + assert.equal(ctx.sw.tonePresetNameMap, undefined); +}); + +// ── MIDI program-change switcher (three copies) ───────────────────────────── +const MIDI = { mode: 'midi', vstSlotId: 7, channel: 2, mappings: { Clean: 1, Lead: 5 } }; +const MIDI_COPIES = { + 'IIFE 1 song load': 'const midiMappings = midiConfig.mappings || {};\n toneSwitcher = null;', + 'IIFE 1 Save MIDI Mapping': 'const _midiCh = chInput ? parseInt(chInput.value) : 1;', + 'IIFE 2 song preload': '// MIDI PC mode — send program changes to a single VST', +}; + +for (const [label, anchor] of Object.entries(MIDI_COPIES)) { + test(`MIDI switcher (${label}) sends the same program changes`, () => { + const log = []; + const api = fakeApi(log); + const ctx = { + console: quiet, + window: { feedBackDesktop: { audio: api } }, + api, midiConfig: MIDI, midiMappings: MIDI.mappings, + _liveApi: api, _midiMappings: MIDI.mappings, _midiVstSlot: MIDI.vstSlotId, _midiCh: MIDI.channel, + }; + vm.runInNewContext(`this.sw = ${switcherLiteral(anchor)};`, ctx); + assert.equal(ctx.sw.midiMode, true); + for (const t of ['Clean', 'Clean', 'Nope', 'Lead', 'Lead']) ctx.sw.switchToTone(t); + assert.deepEqual(log, [ + ['sendMidiToSlot', 7, 0, 2, 1], + ['sendMidiToSlot', 7, 0, 2, 5], + ]); + assert.equal(ctx.sw.activeTone, 'Lead'); + }); +} From 0543bcf1c818208c4dd32a19d0db763d0cb8402c Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:42:42 -0800 Subject: [PATCH 06/25] test: clone harness tolerates CRLF checkouts of build-common.sh Co-Authored-By: Claude Opus 5.5 --- tests/build-plugin-clone.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/build-plugin-clone.test.js b/tests/build-plugin-clone.test.js index 55b40ce..f35d1e9 100644 --- a/tests/build-plugin-clone.test.js +++ b/tests/build-plugin-clone.test.js @@ -12,7 +12,7 @@ const os = require('node:os'); const path = require('node:path'); const { spawnSync } = require('node:child_process'); -const SRC = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'build-common.sh'), 'utf8'); +const SRC = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'build-common.sh'), 'utf8').replace(/\r\n/g, '\n'); const FN = SRC.match(/^clone_slopsmith\(\) \{[\s\S]*?^\}$/m)[0]; const EXPECTED_DIRS = [ From f155640294e914efd652040de2cd8c3f26af61ac Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:48:43 -0800 Subject: [PATCH 07/25] refactor(tests): move the six engine-loading tests into tests/engine Only paths change (one more '..', contracts/ import). test-inventory now checks the two lanes. Co-Authored-By: Claude Opus 5.5 --- .untangler/STATE.md | 6 +++--- .untangler/state.json | 12 +++++++----- tests/{ => engine}/chain-mutation-storm.test.js | 4 ++-- tests/{ => engine}/contract-check.test.js | 4 ++-- tests/{ => engine}/live-pitch.test.js | 2 +- tests/{ => engine}/ml-note-detection.test.js | 6 +++--- tests/{ => engine}/multi-source.test.js | 2 +- tests/{ => engine}/napi-arg-fuzz.test.js | 2 +- tests/test-inventory.test.js | 12 +++++++++++- 9 files changed, 31 insertions(+), 19 deletions(-) rename tests/{ => engine}/chain-mutation-storm.test.js (95%) rename tests/{ => engine}/contract-check.test.js (89%) rename tests/{ => engine}/live-pitch.test.js (99%) rename tests/{ => engine}/ml-note-detection.test.js (96%) rename tests/{ => engine}/multi-source.test.js (98%) rename tests/{ => engine}/napi-arg-fuzz.test.js (98%) diff --git a/.untangler/STATE.md b/.untangler/STATE.md index 9475825..53bbe4e 100644 --- a/.untangler/STATE.md +++ b/.untangler/STATE.md @@ -1,7 +1,7 @@ # Codebase Untangler - State **Started**: 2026-11-07T20:48:45.568531+00:00 -**Current phase**: 2 (Safety Net) +**Current phase**: 3 (Refactor) **Branch**: refactor/untangle-2026-11-07 **Stack**: electron, typescript, vanilla-js-renderer, cpp-juce-node-addon, vst-sandbox, python-bundled-core @@ -9,8 +9,8 @@ - [x] Phase 0: Triage (done) - [x] Phase 1: Audit (done) -- [~] Phase 2: Safety Net (in_progress) -- [ ] Phase 3: Refactor (pending) +- [x] Phase 2: Safety Net (done) +- [~] Phase 3: Refactor (in_progress) - [ ] Phase 4: Hardening (pending) - [ ] Phase 5: Handover (pending) diff --git a/.untangler/state.json b/.untangler/state.json index 86b3a1b..8ee402b 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -1,7 +1,7 @@ { "schema_version": 1, "started_at": "2026-11-07T20:48:45.568531+00:00", - "current_phase": 2, + "current_phase": 3, "phases": { "0": { "name": "Triage", @@ -19,14 +19,16 @@ }, "2": { "name": "Safety Net", - "status": "in_progress", + "status": "done", "gates": {}, - "started_at": "2026-11-09T14:33:34.238429+00:00" + "started_at": "2026-11-09T14:33:34.238429+00:00", + "completed_at": "2026-11-09T14:47:39.483445+00:00" }, "3": { "name": "Refactor", - "status": "pending", - "gates": {} + "status": "in_progress", + "gates": {}, + "started_at": "2026-11-09T14:47:39.483445+00:00" }, "4": { "name": "Hardening", diff --git a/tests/chain-mutation-storm.test.js b/tests/engine/chain-mutation-storm.test.js similarity index 95% rename from tests/chain-mutation-storm.test.js rename to tests/engine/chain-mutation-storm.test.js index e6301c7..beac328 100644 --- a/tests/chain-mutation-storm.test.js +++ b/tests/engine/chain-mutation-storm.test.js @@ -8,7 +8,7 @@ // EXPECTED-FAIL / QUARANTINED: needs the built addon, drives a known race // repeatedly (a single clean run proves nothing for a race), and initializes // JUCE in-process. Run explicitly with: -// CHAIN_STORM=1 node --test tests/chain-mutation-storm.test.js +// CHAIN_STORM=1 node --test tests/engine/chain-mutation-storm.test.js 'use strict'; const test = require('node:test'); @@ -17,7 +17,7 @@ const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); -const ADDON = path.join(__dirname, '..', 'build', 'Release', 'slopsmith_audio.node'); +const ADDON = path.join(__dirname, '..', '..', 'build', 'Release', 'slopsmith_audio.node'); const ENABLED = process.env.CHAIN_STORM === '1'; const ITERATIONS = 50; diff --git a/tests/contract-check.test.js b/tests/engine/contract-check.test.js similarity index 89% rename from tests/contract-check.test.js rename to tests/engine/contract-check.test.js index aed2f44..66c001a 100644 --- a/tests/contract-check.test.js +++ b/tests/engine/contract-check.test.js @@ -10,10 +10,10 @@ const assert = require('node:assert'); const fs = require('fs'); const path = require('path'); -const { extractAddonExports, extractIpcChannels, extractPreloadApi } = require('./contracts/extract.js'); +const { extractAddonExports, extractIpcChannels, extractPreloadApi } = require('../contracts/extract.js'); function loadSnapshot(name) { - return JSON.parse(fs.readFileSync(path.join(__dirname, 'contracts', name), 'utf8')); + return JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'contracts', name), 'utf8')); } test('addon export table matches snapshot', (t) => { diff --git a/tests/live-pitch.test.js b/tests/engine/live-pitch.test.js similarity index 99% rename from tests/live-pitch.test.js rename to tests/engine/live-pitch.test.js index f0d3419..f9c42b9 100644 --- a/tests/live-pitch.test.js +++ b/tests/engine/live-pitch.test.js @@ -15,7 +15,7 @@ const path = require('node:path'); const vm = require('node:vm'); const ts = require('typescript'); -const ROOT = path.join(__dirname, '..'); +const ROOT = path.join(__dirname, '..', '..'); const BRIDGE_SRC = fs.readFileSync(path.join(ROOT, 'src', 'main', 'audio-bridge.ts'), 'utf8'); // Source text of one `ipcMain.handle('', …);` registration. diff --git a/tests/ml-note-detection.test.js b/tests/engine/ml-note-detection.test.js similarity index 96% rename from tests/ml-note-detection.test.js rename to tests/engine/ml-note-detection.test.js index 641c62f..7622bd9 100644 --- a/tests/ml-note-detection.test.js +++ b/tests/engine/ml-note-detection.test.js @@ -5,7 +5,7 @@ // the ML path, that getPitchDetection()/scoreChord() keep their shapes, and // that a bad model path fails soft to the YIN fallback (Constitution VII). // -// Run: node --test tests/ml-note-detection.test.js +// Run: node --test tests/engine/ml-note-detection.test.js // Skips cleanly when the addon hasn't been built yet (npm run build:audio). // // WAV→MIDI detection accuracy is covered separately by the Phase 0 spike @@ -16,8 +16,8 @@ const assert = require('node:assert/strict'); const path = require('node:path'); const fs = require('node:fs'); -const ADDON = path.join(__dirname, '..', 'build', 'Release', 'slopsmith_audio.node'); -const MODEL = path.join(__dirname, '..', 'resources', 'models', 'basic_pitch.onnx'); +const ADDON = path.join(__dirname, '..', '..', 'build', 'Release', 'slopsmith_audio.node'); +const MODEL = path.join(__dirname, '..', '..', 'resources', 'models', 'basic_pitch.onnx'); let audio = null; try { diff --git a/tests/multi-source.test.js b/tests/engine/multi-source.test.js similarity index 98% rename from tests/multi-source.test.js rename to tests/engine/multi-source.test.js index 8ffe413..ca7e23f 100644 --- a/tests/multi-source.test.js +++ b/tests/engine/multi-source.test.js @@ -9,7 +9,7 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const path = require('node:path'); -const ADDON = path.join(__dirname, '..', 'build', 'Release', 'slopsmith_audio.node'); +const ADDON = path.join(__dirname, '..', '..', 'build', 'Release', 'slopsmith_audio.node'); let audio; try { diff --git a/tests/napi-arg-fuzz.test.js b/tests/engine/napi-arg-fuzz.test.js similarity index 98% rename from tests/napi-arg-fuzz.test.js rename to tests/engine/napi-arg-fuzz.test.js index 3ac9f40..8c259b6 100644 --- a/tests/napi-arg-fuzz.test.js +++ b/tests/engine/napi-arg-fuzz.test.js @@ -12,7 +12,7 @@ const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); -const ADDON = path.join(__dirname, '..', 'build', 'Release', 'slopsmith_audio.node'); +const ADDON = path.join(__dirname, '..', '..', 'build', 'Release', 'slopsmith_audio.node'); const HAVE_ADDON = fs.existsSync(ADDON); function writeImpulseWav(file) { diff --git a/tests/test-inventory.test.js b/tests/test-inventory.test.js index 6649fce..6d429e5 100644 --- a/tests/test-inventory.test.js +++ b/tests/test-inventory.test.js @@ -52,8 +52,18 @@ test('no node:test file was added, dropped or duplicated', () => { assert.deepEqual(names, [...ALL].sort()); }); +const loads = (src) => /'Release'/.test(src) || /require\(['"](\.\.?)\/contracts\/extract(\.js)?['"]\)/.test(src); + test('only the engine set loads the native addon', () => { - const loads = (src) => /'Release'/.test(src) || /require\(['"]\.\/contracts\/extract(\.js)?['"]\)/.test(src); const actual = found.filter((t) => t.name !== 'test-inventory' && loads(fs.readFileSync(t.file, 'utf8'))).map((t) => t.name).sort(); assert.deepEqual(actual, [...ENGINE].sort()); }); + +test('engine tests live in tests/engine/, everything else is in the fast lane', () => { + // npm run test:fast runs tests/*.test.js; npm run test:engine runs tests/engine/*.test.js. + const engineDir = path.join(TESTS, 'engine'); + const inEngine = found.filter((t) => path.dirname(t.file) === engineDir).map((t) => t.name).sort(); + const inFast = found.filter((t) => path.dirname(t.file) === TESTS).map((t) => t.name); + assert.deepEqual(inEngine, [...ENGINE].sort()); + assert.equal(inEngine.length + inFast.length, ALL.length, 'a test file sits outside both lanes'); +}); From 1d2d250350de39d131da4c2b3f66bdb1d4072863 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:49:26 -0800 Subject: [PATCH 08/25] ci: run the fast test lane in the existing check job npm test now means the fast lane; test:engine runs tests/engine/ on demand. No new jobs, nothing added to build or release workflows. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 +++++ package.json | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d8fdf4..05691a5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,11 @@ jobs: - name: TypeScript type check run: npm run typecheck + # Fast lane only (source-reading tests, ~2 s). The engine-loading tests in + # tests/engine/ need a built native addon and are run locally on demand. + - name: Fast tests + run: npm run test:fast + - name: npm audit run: npm audit --audit-level=high continue-on-error: true diff --git a/package.json b/package.json index 8b72277..896ea07 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,9 @@ "main": "dist/main/main.js", "scripts": { "typecheck": "tsc --noEmit", - "test": "node --test \"tests/*.test.js\"", + "test": "npm run test:fast", + "test:fast": "node --test \"tests/*.test.js\"", + "test:engine": "node --test \"tests/engine/*.test.js\"", "build:ts": "tsc && node -e \"const fs=require('fs'),path=require('path');fs.copyFileSync('src/main/splash.html','dist/main/splash.html');fs.copyFileSync('src/main/spinner.json','dist/main/spinner.json');fs.copyFileSync('node_modules/lottie-web/build/player/lottie.min.js','dist/main/lottie.min.js');const dst='dist/main/images';if(fs.existsSync(dst))fs.rmSync(dst,{recursive:true});fs.mkdirSync(dst,{recursive:true});fs.readdirSync('src/main/images',{withFileTypes:true}).filter(d=>d.isFile()&&d.name.endsWith('.webp')).forEach(d=>fs.copyFileSync(path.join('src/main/images',d.name),path.join(dst,d.name)));fs.copyFileSync('resources/icons/icon.ico','dist/main/tray.ico');fs.copyFileSync('resources/icons/32x32.png','dist/main/tray.png')\"", "build:audio": "bash scripts/build-audio.sh Release", "build:audio:debug": "bash scripts/build-audio.sh Debug", From 5ebc3e3c6a7046dc8e337768c8f146b547d777ab Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:49:26 -0800 Subject: [PATCH 09/25] chore: untangler I-001 done Co-Authored-By: Claude Opus 5.5 --- .untangler/audit.json | 7 +++++-- .untangler/deferred.md | 2 ++ .untangler/state.json | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.untangler/audit.json b/.untangler/audit.json index 5f474f0..457d0c4 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -13,9 +13,12 @@ "tests/CMakeLists.txt:15-18" ], "description": "CI runs no JS or C++ unit tests; the 6 engine-loading JS tests cannot run on the owner machine.", - "status": "pending", + "status": "done", "refactor_plan": "Move engine tests to tests/engine/, add test:fast/test:engine (test=fast), add one npm run test:fast step to the existing ci.yml check job. User scope 2026-11-07: no new CI jobs, no engine lane, nothing added to build.yml/release builds.", - "commits": [], + "commits": [ + "f155640", + "1d2d250" + ], "safety_net": { "type": "unit_test", "location": "tests/test-inventory.test.js", diff --git a/.untangler/deferred.md b/.untangler/deferred.md index 8a3ac55..6aa507d 100644 --- a/.untangler/deferred.md +++ b/.untangler/deferred.md @@ -2,3 +2,5 @@ Problems noticed during refactor but deliberately not fixed now. +- (found in Phase 2, I-006) build-common.sh's repo->dirname fallback (strip `feedback-plugin-`, `-`→`_`) never runs: every plugin entry has an explicit `:dirname`, and the strip is case-sensitive while repos are `feedBack-plugin-*`. Remove or fix later. +- (found in Phase 2, I-004) 55 audio:* handlers throw instead of returning a fallback when the addon call throws. Guarding them is a behaviour change; decide explicitly, not as part of the callAddon refactor. diff --git a/.untangler/state.json b/.untangler/state.json index 8ee402b..a8fe46c 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -76,5 +76,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 2 gate passed 11/11; user to acknowledge the safety nets (incl. I-003 manual packaged-build checklist), then advance 2 and start Phase 3 with I-001" + "next_action": "Phase 3: I-001 done (f155640, 1d2d250). Next: I-002 extract desktop-config.ts from soundfont-manager.ts, keep a .corrupt backup on parse errors" } \ No newline at end of file From 34c14bc45bc7027748c20b3236b2bb1d125aab49 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:50:26 -0800 Subject: [PATCH 10/25] refactor(main): move desktop config read/write into desktop-config.ts Code moved unchanged; main, pane-hosts and python import it from there, soundfont-manager re-exports SoundfontQuality. Co-Authored-By: Claude Opus 5.5 --- src/main/desktop-config.ts | 61 +++++++++++++++++++++++++++++++++++ src/main/main.ts | 3 +- src/main/pane-hosts.ts | 2 +- src/main/python.ts | 3 +- src/main/soundfont-manager.ts | 57 +++----------------------------- tests/desktop-config.test.js | 7 ++-- 6 files changed, 73 insertions(+), 60 deletions(-) create mode 100644 src/main/desktop-config.ts diff --git a/src/main/desktop-config.ts b/src/main/desktop-config.ts new file mode 100644 index 0000000..2f69c09 --- /dev/null +++ b/src/main/desktop-config.ts @@ -0,0 +1,61 @@ +// Desktop config — the main process's own settings file, +// /slopsmith-desktop.json (soundfont quality, LAN access, window +// geometry, fullscreen, pane pop-out windows). Read by main.ts, pane-hosts.ts, +// python.ts and soundfont-manager.ts. Moved out of soundfont-manager.ts +// unchanged (untangler I-002). + +import { app } from 'electron'; +import * as fs from 'fs'; +import * as path from 'path'; +import type { SavedWindowBounds } from './window-bounds'; + +export type SoundfontQuality = 'default' | 'high'; + +export interface DesktopConfig { + soundfontQuality?: SoundfontQuality; + // When true, the Python backend binds 0.0.0.0 (LAN-reachable) instead of + // 127.0.0.1, so other devices on the network can reach the library / sync + // room. Opt-in (default loopback) — see python.ts and issue #441. + lanAccess?: boolean; + // Last main-window geometry, restored (after sanitization against the + // current display layout) on next launch — see window-bounds.ts. + windowBounds?: SavedWindowBounds; + // When true, the main window launches in fullscreen and the System-settings + // toggle that drives it is shown. Opt-in (default off) — this deliberately + // reverses createWindow()'s historical "never launch fullscreen" default, + // but only for users who ask for it. Persisted here (not renderer + // localStorage) because the main process must read it at window creation, + // before the renderer exists. + startFullscreen?: boolean; + // Per-pane pop-out window geometry, keyed by pane id, plus its always-on-top + // flag. Sanitized against the display layout on restore, exactly like + // windowBounds — see pane-hosts.ts. Lives in the desktop config rather than + // the renderer's localStorage because localStorage is shared with the pane + // windows themselves (same origin), and a second writer there would race. + paneWindows?: Record; +} + +export interface SavedPaneWindow { + bounds?: SavedWindowBounds; + alwaysOnTop?: boolean; +} + +function configPath(): string { + return path.join(app.getPath('userData'), 'slopsmith-desktop.json'); +} + +export function getDesktopConfig(): DesktopConfig { + try { + return JSON.parse(fs.readFileSync(configPath(), 'utf-8')) as DesktopConfig; + } catch { + return {}; + } +} + +export function setDesktopConfig(patch: Partial): void { + const current = getDesktopConfig(); + const next = { ...current, ...patch }; + const tmp = configPath() + '.tmp'; + fs.writeFileSync(tmp, JSON.stringify(next, null, 2)); + fs.renameSync(tmp, configPath()); +} diff --git a/src/main/main.ts b/src/main/main.ts index 2ebbd8e..57a60f5 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -123,7 +123,8 @@ import { import { initAudioBridge, shutdownAudio } from './audio-bridge'; import { initDebugLogging, isDebugEnabled } from './debug-log'; import { initPluginManager } from './plugin-manager'; -import { initSoundfontManager, getDesktopConfig, setDesktopConfig } from './soundfont-manager'; +import { initSoundfontManager } from './soundfont-manager'; +import { getDesktopConfig, setDesktopConfig } from './desktop-config'; import * as updateManager from './update-manager'; import type { UpdateChannel } from './update-manager'; import { installAppMenu } from './app-menu'; diff --git a/src/main/pane-hosts.ts b/src/main/pane-hosts.ts index 05a5191..3b924fd 100644 --- a/src/main/pane-hosts.ts +++ b/src/main/pane-hosts.ts @@ -25,7 +25,7 @@ import { BrowserWindow, ipcMain, screen } from 'electron'; import { IPC_PANE_SYNC } from './ipc-channels'; import { sanitizeWindowBounds, type WindowSizing } from './window-bounds'; -import { getDesktopConfig, setDesktopConfig, type SavedPaneWindow } from './soundfont-manager'; +import { getDesktopConfig, setDesktopConfig, type SavedPaneWindow } from './desktop-config'; import { setTrayPanes, type TrayPane } from './pane-tray'; // The renderer names the frame `fbpane-`. Keep in sync with diff --git a/src/main/python.ts b/src/main/python.ts index 3733afa..6315160 100644 --- a/src/main/python.ts +++ b/src/main/python.ts @@ -9,7 +9,8 @@ import { app } from 'electron'; import * as http from 'http'; import * as net from 'net'; import * as os from 'os'; -import { getActiveSoundfontPath, getDesktopConfig } from './soundfont-manager'; +import { getActiveSoundfontPath } from './soundfont-manager'; +import { getDesktopConfig } from './desktop-config'; import { isDebugEnabled } from './debug-log'; import { applyLibraryPathToPythonEnvironment, diff --git a/src/main/soundfont-manager.ts b/src/main/soundfont-manager.ts index 345b67f..5098b19 100644 --- a/src/main/soundfont-manager.ts +++ b/src/main/soundfont-manager.ts @@ -13,7 +13,9 @@ import * as https from 'https'; import * as path from 'path'; import * as crypto from 'crypto'; import { restartPython } from './python'; -import type { SavedWindowBounds } from './window-bounds'; +import { getDesktopConfig, setDesktopConfig, type SoundfontQuality } from './desktop-config'; + +export type { SoundfontQuality } from './desktop-config'; // ── Source of truth for the high-quality soundfont ────────────────────────── // Public mirror of FluidR3_GM.sf2 on the feedback-soundfonts repo. When a new @@ -25,58 +27,7 @@ const SOUNDFONT_URL = const SOUNDFONT_SHA256 = '74594e8f4250680adf590507a306655a299935343583256f3b722c48a1bc1cb0'; const SOUNDFONT_EXPECTED_SIZE_MB = 142; -// ── Config + path helpers ─────────────────────────────────────────────────── - -export type SoundfontQuality = 'default' | 'high'; - -interface DesktopConfig { - soundfontQuality?: SoundfontQuality; - // When true, the Python backend binds 0.0.0.0 (LAN-reachable) instead of - // 127.0.0.1, so other devices on the network can reach the library / sync - // room. Opt-in (default loopback) — see python.ts and issue #441. - lanAccess?: boolean; - // Last main-window geometry, restored (after sanitization against the - // current display layout) on next launch — see window-bounds.ts. - windowBounds?: SavedWindowBounds; - // When true, the main window launches in fullscreen and the System-settings - // toggle that drives it is shown. Opt-in (default off) — this deliberately - // reverses createWindow()'s historical "never launch fullscreen" default, - // but only for users who ask for it. Persisted here (not renderer - // localStorage) because the main process must read it at window creation, - // before the renderer exists. - startFullscreen?: boolean; - // Per-pane pop-out window geometry, keyed by pane id, plus its always-on-top - // flag. Sanitized against the display layout on restore, exactly like - // windowBounds — see pane-hosts.ts. Lives in the desktop config rather than - // the renderer's localStorage because localStorage is shared with the pane - // windows themselves (same origin), and a second writer there would race. - paneWindows?: Record; -} - -export interface SavedPaneWindow { - bounds?: SavedWindowBounds; - alwaysOnTop?: boolean; -} - -function configPath(): string { - return path.join(app.getPath('userData'), 'slopsmith-desktop.json'); -} - -export function getDesktopConfig(): DesktopConfig { - try { - return JSON.parse(fs.readFileSync(configPath(), 'utf-8')) as DesktopConfig; - } catch { - return {}; - } -} - -export function setDesktopConfig(patch: Partial): void { - const current = getDesktopConfig(); - const next = { ...current, ...patch }; - const tmp = configPath() + '.tmp'; - fs.writeFileSync(tmp, JSON.stringify(next, null, 2)); - fs.renameSync(tmp, configPath()); -} +// ── Path helpers (config lives in desktop-config.ts) ──────────────────────── function soundfontsDir(): string { const dir = path.join(app.getPath('userData'), 'soundfonts'); diff --git a/tests/desktop-config.test.js b/tests/desktop-config.test.js index df8a1f9..21a0a40 100644 --- a/tests/desktop-config.test.js +++ b/tests/desktop-config.test.js @@ -1,7 +1,6 @@ -// Untangler safety net for I-002 (extract desktop-config.ts out of +// Untangler safety net for I-002 (desktop-config.ts, extracted from // soundfont-manager.ts). Pins how /slopsmith-desktop.json is read and -// written, through the module every caller imports today. Electron and -// python.ts are stubbed; nothing is spawned. +// written. Electron is stubbed; nothing is spawned. const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); @@ -19,7 +18,7 @@ function load() { }, './python': { restartPython: async () => {} }, }; - const mod = loadTsStubbed('src/main/soundfont-manager.ts', stubs); + const mod = loadTsStubbed('src/main/desktop-config.ts', stubs); const file = path.join(dir, 'slopsmith-desktop.json'); return { mod, dir, file, done: () => fs.rmSync(dir, { recursive: true, force: true }) }; } From ec7489905dc92a2402de672492b1bd76fbfe5268 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:51:02 -0800 Subject: [PATCH 11/25] fix(main): keep a .corrupt copy instead of overwriting an unreadable desktop config Reads still treat a bad file as {}; the next write now saves the old bytes as slopsmith-desktop.json.corrupt first, so window bounds, LAN access and pane settings can be recovered. Co-Authored-By: Claude Opus 5.5 --- src/main/desktop-config.ts | 22 ++++++++++++++++++++++ tests/desktop-config.test.js | 13 +++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/main/desktop-config.ts b/src/main/desktop-config.ts index 2f69c09..91d08e3 100644 --- a/src/main/desktop-config.ts +++ b/src/main/desktop-config.ts @@ -52,7 +52,29 @@ export function getDesktopConfig(): DesktopConfig { } } +// An unreadable config would otherwise be replaced by just the next patch, +// silently dropping every other setting (window bounds, LAN access, ...). +// Keep the bad bytes next to it as slopsmith-desktop.json.corrupt so they can +// be recovered by hand. Reads still treat it as {} exactly as before. +function backupIfCorrupt(file: string): void { + let raw: string; + try { + raw = fs.readFileSync(file, 'utf-8'); + } catch { + return; // missing or unreadable: nothing to keep + } + try { + JSON.parse(raw); + } catch { + try { + fs.writeFileSync(file + '.corrupt', raw); + console.warn(`[desktop-config] ${file} was not valid JSON; kept a copy as ${file}.corrupt`); + } catch { /* best effort */ } + } +} + export function setDesktopConfig(patch: Partial): void { + backupIfCorrupt(configPath()); const current = getDesktopConfig(); const next = { ...current, ...patch }; const tmp = configPath() + '.tmp'; diff --git a/tests/desktop-config.test.js b/tests/desktop-config.test.js index 21a0a40..2d526ab 100644 --- a/tests/desktop-config.test.js +++ b/tests/desktop-config.test.js @@ -61,8 +61,17 @@ test('corrupt config reads as {} and the next set still writes the patch', () => assert.deepEqual(t.mod.getDesktopConfig(), {}); t.mod.setDesktopConfig({ lanAccess: false }); assert.deepEqual(t.mod.getDesktopConfig(), { lanAccess: false }); - // I-002 will additionally keep the corrupt bytes as a .corrupt backup; - // that assertion is added with the change itself. + // The bad bytes are kept next to it instead of being lost. + assert.equal(fs.readFileSync(t.file + '.corrupt', 'utf8'), '{ not json'); + } finally { t.done(); } +}); + +test('a healthy or missing config never leaves a .corrupt file', () => { + const t = load(); + try { + t.mod.setDesktopConfig({ lanAccess: true }); + t.mod.setDesktopConfig({ lanAccess: false }); + assert.equal(fs.existsSync(t.file + '.corrupt'), false); } finally { t.done(); } }); From f2ca43f5efe7f6b05681efdfe3fad8908a94c7a1 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:51:02 -0800 Subject: [PATCH 12/25] chore: untangler I-002 done Co-Authored-By: Claude Opus 5.5 --- .untangler/audit.json | 7 +++++-- .untangler/deferred.md | 1 + .untangler/state.json | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.untangler/audit.json b/.untangler/audit.json index 457d0c4..0a45eb8 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -39,9 +39,12 @@ "src/main/python.ts:12" ], "description": "Parse failure returns {} and the next write drops every setting; the module also causes a require cycle.", - "status": "pending", + "status": "done", "refactor_plan": "Extract desktop-config.ts (re-export for one release); on parse failure keep a .corrupt backup and do not overwrite blindly; add a test.", - "commits": [], + "commits": [ + "34c14bc", + "ec74899" + ], "safety_net": { "type": "unit_test", "location": "tests/desktop-config.test.js", diff --git a/.untangler/deferred.md b/.untangler/deferred.md index 6aa507d..725247a 100644 --- a/.untangler/deferred.md +++ b/.untangler/deferred.md @@ -4,3 +4,4 @@ Problems noticed during refactor but deliberately not fixed now. - (found in Phase 2, I-006) build-common.sh's repo->dirname fallback (strip `feedback-plugin-`, `-`→`_`) never runs: every plugin entry has an explicit `:dirname`, and the strip is case-sensitive while repos are `feedBack-plugin-*`. Remove or fix later. - (found in Phase 2, I-004) 55 audio:* handlers throw instead of returning a fallback when the addon call throws. Guarding them is a behaviour change; decide explicitly, not as part of the callAddon refactor. +- (found in Phase 3, I-002) The python.ts <-> soundfont-manager.ts require cycle is still there: python.ts needs getActiveSoundfontPath and soundfont-manager needs restartPython. Moving the config out did not break it (the audit over-claimed). Harmless today (both uses are inside functions). diff --git a/.untangler/state.json b/.untangler/state.json index a8fe46c..cf77334 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -76,5 +76,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 3: I-001 done (f155640, 1d2d250). Next: I-002 extract desktop-config.ts from soundfont-manager.ts, keep a .corrupt backup on parse errors" + "next_action": "Phase 3: I-001 and I-002 done. Next: I-006 fail the build when a plugin clone fails (ALLOW_MISSING_PLUGINS=1 escape), same for the bundle-slopsmith.sh desktop plugin copy" } \ No newline at end of file From d6625c5ad1859633b3056a4bdb580eb8519baaac Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:53:12 -0800 Subject: [PATCH 13/25] fix(build): fail the build when a bundled plugin is missing clone_slopsmith now returns non-zero when any plugin clone fails (ALLOW_MISSING_PLUGINS=1 keeps the old behaviour), and the desktop plugin copy no longer swallows errors; only the optional .html is skipped when absent. All 38 plugin repos/branches checked reachable. Co-Authored-By: Claude Opus 5.5 --- scripts/BUILD_SCRIPTS.md | 1 + scripts/build-common.sh | 12 ++++++++++++ scripts/bundle-slopsmith.sh | 7 ++++++- tests/build-plugin-clone.test.js | 22 ++++++++++++++-------- 4 files changed, 33 insertions(+), 9 deletions(-) diff --git a/scripts/BUILD_SCRIPTS.md b/scripts/BUILD_SCRIPTS.md index 26003b0..5d2f682 100644 --- a/scripts/BUILD_SCRIPTS.md +++ b/scripts/BUILD_SCRIPTS.md @@ -71,6 +71,7 @@ Unified build system for Slopsmith Desktop supporting Linux (via Docker), macOS, - Validates environment (Node.js, Python, .NET) - Runs npm install, builds C++ engine, bundles resources - Calls platform-specific functions for: dependency installation, Python bundling, binary bundling + - Clones the core and every bundled plugin; if any plugin fails to clone the build stops. Set `ALLOW_MISSING_PLUGINS=1` to build without the missing ones (local or fork builds that cannot reach every plugin repo) ## Platform-Specific Scripts diff --git a/scripts/build-common.sh b/scripts/build-common.sh index 570d52d..a637949 100644 --- a/scripts/build-common.sh +++ b/scripts/build-common.sh @@ -231,6 +231,18 @@ clone_slopsmith() { export SLOPSMITH_DIR="$clone_dir" echo "Cloned ${cloned} of ${total} plugins" + # A missing plugin used to ship silently (the app just lacked it). Fail + # instead; ALLOW_MISSING_PLUGINS=1 keeps the old lenient behaviour for + # local/fork builds that cannot reach every plugin repo. + if (( cloned < total )); then + if [[ "${ALLOW_MISSING_PLUGINS:-0}" == "1" ]]; then + echo "WARNING: $((total - cloned)) plugin(s) missing; continuing (ALLOW_MISSING_PLUGINS=1)" >&2 + else + echo "ERROR: $((total - cloned)) plugin(s) failed to clone (see 'skipped' above). Set ALLOW_MISSING_PLUGINS=1 to build without them." >&2 + cd - >/dev/null + return 1 + fi + fi cd - >/dev/null } diff --git a/scripts/bundle-slopsmith.sh b/scripts/bundle-slopsmith.sh index e6c8976..36e12a9 100755 --- a/scripts/bundle-slopsmith.sh +++ b/scripts/bundle-slopsmith.sh @@ -182,7 +182,12 @@ for dp in "$PROJECT_DIR/src/renderer" "$PROJECT_DIR/src/renderer/plugin-manager" if [ -f "$dp/plugin.json" ]; then pname=$(python3 -c "import json, sys; print(json.load(open(sys.argv[1]))['id'])" "$dp/plugin.json") mkdir -p "$BUNDLE_DIR/plugins/$pname" - cp "$dp"/*.html "$dp"/*.js "$dp"/plugin.json "$BUNDLE_DIR/plugins/$pname/" 2>/dev/null || true + # plugin.json and the scripts are required; a page is optional + # (live-retune has none). A failed copy now fails the bundle. + cp "$dp"/plugin.json "$dp"/*.js "$BUNDLE_DIR/plugins/$pname/" + for f in "$dp"/*.html; do + if [ -e "$f" ]; then cp "$f" "$BUNDLE_DIR/plugins/$pname/"; fi + done fi done diff --git a/tests/build-plugin-clone.test.js b/tests/build-plugin-clone.test.js index f35d1e9..97e896c 100644 --- a/tests/build-plugin-clone.test.js +++ b/tests/build-plugin-clone.test.js @@ -3,8 +3,8 @@ // Runs the real clone_slopsmith() from scripts/build-common.sh in bash under // `set -euo pipefail` (as the build does), with `git` replaced by a shell // function that only creates directories. No network, nothing outside a temp -// dir. Pins the plugin list and the repo -> directory-name mapping, and the -// current (lenient) failure behaviour that I-006 is meant to change. +// dir. Pins the plugin list and the repo -> directory-name mapping, and that a +// failed plugin clone fails the build unless ALLOW_MISSING_PLUGINS=1. const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); @@ -27,7 +27,7 @@ const EXPECTED_DIRS = [ 'tutorials', 'virtuoso', ]; -function run(failPattern = '') { +function run(failPattern = '', extraEnv = {}) { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'untangler-i006-')); const harness = ` set -euo pipefail @@ -42,7 +42,7 @@ clone_slopsmith "$TMPC/clone" echo "DIRS:$(cd "$TMPC/clone/plugins" && ls -1 | tr '\\n' ' ')" `; const r = spawnSync('bash', ['-c', harness], { - env: { ...process.env, FAIL: failPattern, TMPC: tmp.replace(/\\/g, '/'), GH_CLONE_TOKEN: '' }, + env: { ...process.env, FAIL: failPattern, TMPC: tmp.replace(/\\/g, '/'), GH_CLONE_TOKEN: '', ALLOW_MISSING_PLUGINS: '', ...extraEnv }, encoding: 'utf8', timeout: 30000, }); @@ -62,15 +62,21 @@ test('all clones succeed: every plugin lands in its expected directory', () => { for (const d of r.dirs) assert.match(d, /^[a-z0-9_]+$/, `plugin dir "${d}" is not a valid module name`); }); -test('a failed plugin clone is reported (current behaviour: build continues)', () => { +test('a failed plugin clone is reported and fails the build', () => { const r = run('feedBack-plugin-scorecard'); assert.match(r.out, /skipped mattromano\/feedBack-plugin-scorecard/); - assert.match(r.out, /Cloned (\d+) of (\d+) plugins/); const [, got, total] = r.out.match(/Cloned (\d+) of (\d+) plugins/); assert.equal(Number(got), Number(total) - 1); + assert.match(r.err, /1 plugin\(s\) failed to clone/); + assert.notEqual(r.status, 0); +}); + +test('ALLOW_MISSING_PLUGINS=1 keeps building without the missing plugin', () => { + const r = run('feedBack-plugin-scorecard', { ALLOW_MISSING_PLUGINS: '1' }); + assert.equal(r.status, 0, r.err); + assert.match(r.err, /1 plugin\(s\) missing; continuing/); + assert.equal(r.dirs.length, EXPECTED_DIRS.length - 1); assert.ok(!r.dirs.includes('scorecard')); - // I-006 flips this to a non-zero exit unless ALLOW_MISSING_PLUGINS=1. - assert.equal(r.status, 0); }); test('a failed core clone stops the build', () => { From 23b79c11f97261e9d10369d61dc0d0b8acec457f Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:53:13 -0800 Subject: [PATCH 14/25] chore: untangler I-006 done Co-Authored-By: Claude Opus 5.5 --- .untangler/audit.json | 6 ++++-- .untangler/state.json | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.untangler/audit.json b/.untangler/audit.json index 0a45eb8..a6c2719 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -132,9 +132,11 @@ "scripts/bundle-slopsmith.sh:185" ], "description": "git clone 2>/dev/null || echo skipped; a green release can ship without a plugin.", - "status": "pending", + "status": "done", "refactor_plan": "Show stderr; fail when cloned != total unless ALLOW_MISSING_PLUGINS=1; fail loudly on the desktop plugin copy.", - "commits": [], + "commits": [ + "d6625c5" + ], "safety_net": { "type": "integration_test", "location": "tests/build-plugin-clone.test.js", diff --git a/.untangler/state.json b/.untangler/state.json index cf77334..9488aea 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -76,5 +76,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 3: I-001 and I-002 done. Next: I-006 fail the build when a plugin clone fails (ALLOW_MISSING_PLUGINS=1 escape), same for the bundle-slopsmith.sh desktop plugin copy" + "next_action": "Phase 3: I-001, I-002, I-006 done. Next: I-004 callAddon helper in audio-bridge.ts (snapshot must stay identical), then I-003 tone switcher factory (needs packaged-build listening check)" } \ No newline at end of file From caab1dae930d1df76b6ee093273c73601cf32e69 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:54:48 -0800 Subject: [PATCH 15/25] refactor(audio): fold seven exact-copy guarded addon calls into callAddon() setOutputDeviceType, getDeviceMetrics, scoreChord, setChart, listInputDevices, listSources and detectNotes now share one guard / try / warn / fallback helper. Handler snapshot unchanged; IPC contract snapshot unchanged. Handlers that validate arguments, swallow errors silently or have no try are left as they are. Co-Authored-By: Claude Opus 5.5 --- src/main/audio-bridge.ts | 67 ++++++++++++---------------------------- 1 file changed, 20 insertions(+), 47 deletions(-) diff --git a/src/main/audio-bridge.ts b/src/main/audio-bridge.ts index abb70c4..0ed4b00 100644 --- a/src/main/audio-bridge.ts +++ b/src/main/audio-bridge.ts @@ -14,6 +14,19 @@ type AudioModule = Record any>; let audio: AudioModule | null = null; +// Guarded call into the native addon: the fallback when the addon is missing +// or lacks the export, otherwise the call, with a throw logged as +// "[audio] failed: " and answered with the fallback. Used by +// handlers whose whole body is exactly that (untangler I-004). +function callAddon(name: string, fallback: T, ...args: unknown[]): T { + if (!audio || typeof audio[name] !== 'function') return fallback; + try { return audio[name](...args); } + catch (e: unknown) { + console.warn(`[audio] ${name} failed: ${e instanceof Error ? e.message : String(e)}`); + return fallback; + } +} + type AudioDeviceSettings = { type: string; // legacy alias = inputType when only type was stored inputType?: string; @@ -505,12 +518,7 @@ export function initAudioBridge(): void { }); ipcMain.handle('audio:setOutputDeviceType', (_event, typeName: string) => { - if (!audio || typeof audio.setOutputDeviceType !== 'function') return false; - try { return audio.setOutputDeviceType(typeName); } - catch (e: any) { - console.warn(`[audio] setOutputDeviceType failed: ${e?.message ?? e}`); - return false; - } + return callAddon('setOutputDeviceType', false, typeName); }); ipcMain.handle('audio:setDevice', (_event, ...args: any[]) => { @@ -571,12 +579,7 @@ export function initAudioBridge(): void { }); ipcMain.handle('audio:getDeviceMetrics', () => { - if (!audio || typeof audio.getDeviceMetrics !== 'function') return null; - try { return audio.getDeviceMetrics(); } - catch (e: any) { - console.warn(`[audio] getDeviceMetrics failed: ${e?.message ?? e}`); - return null; - } + return callAddon('getDeviceMetrics', null); }); ipcMain.handle('audio:loadDeviceSettings', () => readAudioSettings()); @@ -834,13 +837,7 @@ export function initAudioBridge(): void { // above does — a downlevel addon (pre-ChordScorer build) should // return null so the renderer can fall back to skipping chord // scoring instead of throwing on every call. - if (!audio || typeof audio.scoreChord !== 'function') return null; - try { - return audio.scoreChord(ctx); - } catch (e: unknown) { - console.warn(`[audio] scoreChord failed: ${e instanceof Error ? e.message : String(e)}`); - return null; - } + return callAddon('scoreChord', null, ctx); }); // Push the song's note chart into the engine for continuous, background @@ -850,13 +847,7 @@ export function initAudioBridge(): void { // Returns null on a downlevel addon (pre-NoteVerifier) so the renderer // feature-detects and keeps the old matchNotes path. ipcMain.handle('audio:setChart', (_event, chart: unknown) => { - if (!audio || typeof audio.setChart !== 'function') return null; - try { - return audio.setChart(chart); - } catch (e: unknown) { - console.warn(`[audio] setChart failed: ${e instanceof Error ? e.message : String(e)}`); - return null; - } + return callAddon('setChart', null, chart); }); // Drain the verdicts the NoteVerifier thread has finalized since the last @@ -915,13 +906,7 @@ export function initAudioBridge(): void { // listInputDevices() -> [{ typeName, name }] | null. Capture devices available // to bind as additional engine inputs. ipcMain.handle('audio:listInputDevices', () => { - if (!audio || typeof audio.listInputDevices !== 'function') return null; - try { - return audio.listInputDevices(); - } catch (e: unknown) { - console.warn(`[audio] listInputDevices failed: ${e instanceof Error ? e.message : String(e)}`); - return null; - } + return callAddon('listInputDevices', null); }); // bindInputDevice(deviceKey, deviceName) -> "" on success or an error string @@ -1067,13 +1052,7 @@ export function initAudioBridge(): void { }); ipcMain.handle('audio:listSources', () => { - if (!audio || typeof audio.listSources !== 'function') return null; - try { - return audio.listSources(); - } catch (e: unknown) { - console.warn(`[audio] listSources failed: ${e instanceof Error ? e.message : String(e)}`); - return null; - } + return callAddon('listSources', null); }); ipcMain.handle('audio:setSourceInputChannel', (_event, id: unknown, channel: unknown) => { @@ -1196,13 +1175,7 @@ export function initAudioBridge(): void { // support, or no model loaded) so the renderer feature-detects and falls // back to the getPitchDetection / scoreChord path. ipcMain.handle('audio:detectNotes', () => { - if (!audio || typeof audio.detectNotes !== 'function') return null; - try { - return audio.detectNotes(); - } catch (e: unknown) { - console.warn(`[audio] detectNotes failed: ${e instanceof Error ? e.message : String(e)}`); - return null; - } + return callAddon('detectNotes', null); }); // ── VST Scanning ─────────────────────────────────────────────────────── From 29240d9f0003c522e764d0566b56edc74b60b0f7 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:54:49 -0800 Subject: [PATCH 16/25] chore: untangler I-004 done Co-Authored-By: Claude Opus 5.5 --- .untangler/audit.json | 9 ++++++--- .untangler/deferred.md | 1 + .untangler/state.json | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/.untangler/audit.json b/.untangler/audit.json index a6c2719..baf4473 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -93,9 +93,11 @@ "src/main/audio-bridge.ts:602-612,728,1010,1031,1035,1040-1056,1212,1240,1273-1298" ], "description": "Same typeof-guard/try/warn/default pattern copied ~40 times; inconsistent guarding lets native throws reject into the renderer.", - "status": "pending", + "status": "done", "refactor_plan": "callAddon(name, fallback, ...args) + PITCH_NONE, one handler group per commit; keep literal ipcMain.handle lines, defaults and warn text.", - "commits": [], + "commits": [ + "caab1da" + ], "safety_net": { "type": "snapshot", "location": "tests/audio-bridge-fallbacks.test.js + tests/fixtures/audio-bridge-fallbacks.snapshot.json", @@ -103,7 +105,8 @@ "broken_then_fixed": true, "covers": "All 111 audio:* IPC handlers called with addon missing / every export throwing / every export returning; return values, throws/rejections and warn/error text snapshotted.", "proof": "Changing addSource's no-addon default (-1 -> -2) and the detectNotes warning text each failed the test; reverted. Snapshot shows 55 handlers that throw when the addon throws (unguarded) - guarding them is a behaviour change to decide explicitly in Phase 3." - } + }, + "outcome": "Only 7 handlers were exact copies of guard/try/warn/fallback; those now use callAddon(). The audit's ~40 figure counted sites with argument validation, silent catches or no try at all; converting those would change behaviour (see deferred.md)." }, { "id": "I-005", diff --git a/.untangler/deferred.md b/.untangler/deferred.md index 725247a..9c3b4a7 100644 --- a/.untangler/deferred.md +++ b/.untangler/deferred.md @@ -5,3 +5,4 @@ Problems noticed during refactor but deliberately not fixed now. - (found in Phase 2, I-006) build-common.sh's repo->dirname fallback (strip `feedback-plugin-`, `-`→`_`) never runs: every plugin entry has an explicit `:dirname`, and the strip is case-sensitive while repos are `feedBack-plugin-*`. Remove or fix later. - (found in Phase 2, I-004) 55 audio:* handlers throw instead of returning a fallback when the addon call throws. Guarding them is a behaviour change; decide explicitly, not as part of the callAddon refactor. - (found in Phase 3, I-002) The python.ts <-> soundfont-manager.ts require cycle is still there: python.ts needs getActiveSoundfontPath and soundfont-manager needs restartPython. Moving the config out did not break it (the audit over-claimed). Harmless today (both uses are inside functions). +- (Phase 3, I-004) ~27 other guarded addon sites in audio-bridge.ts were NOT folded into callAddon(): they validate args between the guard and the call (guard order decides which fallback you get), catch silently, or have no try (the bare getters like getSongBusClock, getStreamSinkLevel). Each would be a small behaviour change; take them one at a time if wanted. setLivePitch/getLivePitch must stay self-contained (tests/engine/live-pitch.test.js extracts them verbatim). diff --git a/.untangler/state.json b/.untangler/state.json index 9488aea..adb3cef 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -76,5 +76,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 3: I-001, I-002, I-006 done. Next: I-004 callAddon helper in audio-bridge.ts (snapshot must stay identical), then I-003 tone switcher factory (needs packaged-build listening check)" + "next_action": "Phase 3: I-001, I-002, I-006, I-004 done. Next: I-003 tone switcher factory shared by both screen.js IIFEs + route IIFE2 preload through the chain lock; needs the packaged-build listening checklist" } \ No newline at end of file From 36ffd5a2b838e514a7db7795f8c3af7cdddae739 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:21:17 -0800 Subject: [PATCH 17/25] refactor(renderer): one tone-switch implementation for both IIFEs; serialise the song preload - bypassSwitchToTone / makeMidiToneSwitcher in IIFE 1 replace the two bypass and three MIDI switcher copies (IIFE 2 uses the window exports). - IIFE 2's bypass switcher now carries tonePresetNameMap like IIFE 1's, so the chain panel's preset-name lookup works for those songs too. - IIFE 2's song preload runs under the same chain lock as tone-mapping applies (window._aeWithToneChainLock), re-checking the song generation after the wait, so two rebuilds no longer clear/load the chain at once. Co-Authored-By: Claude Opus 5.5 --- src/renderer/screen.js | 175 +++++++++++++++-------------- tests/tone-switcher-parity.test.js | 96 ++++++++++++---- 2 files changed, 169 insertions(+), 102 deletions(-) diff --git a/src/renderer/screen.js b/src/renderer/screen.js index a52359b..4596cf5 100644 --- a/src/renderer/screen.js +++ b/src/renderer/screen.js @@ -2679,6 +2679,50 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; let midiAmpSongTonesUnavailable = false; const midiAmpSongTonesPending = new Map(); + // ── Shared tone-switch steps (untangler I-003) ───────────────────────── + // Both IIFEs install tone switchers on window._toneSwitcher. These are the + // one copy of the switching logic; IIFE 2 reaches them through the window + // exports below (the IIFEs do not share scope). + + /** Bypass-mode switch: bypass the active tone's slots, un-bypass + * `toneName`'s, then apply its preset levels. No-op for the current tone + * or a tone with no preloaded slots. */ + function bypassSwitchToTone(sw, toneName, setMultiBypass, applyPreset) { + if (toneName === sw.activeTone) return; + if (!sw.toneSlotMap[toneName]) return; + const changes = []; + if (sw.activeTone && sw.toneSlotMap[sw.activeTone]) { + for (const id of sw.toneSlotMap[sw.activeTone]) changes.push({ slotId: id, bypassed: true }); + } + for (const id of sw.toneSlotMap[toneName]) changes.push({ slotId: id, bypassed: false }); + if (changes.length > 0) setMultiBypass(changes); + sw.activeTone = toneName; + const newPreset = sw.tonePresetMap?.[toneName]; + if (newPreset) applyPreset(newPreset); + console.log('[tone-switcher] Switched to:', toneName); + } + + /** MIDI program-change switcher: one VST slot, a program per tone name. + * getApi is read on every switch; channel is passed through as given. */ + function makeMidiToneSwitcher({ getApi, slotId, channel, mappings }) { + return { + activeTone: null, + midiMode: true, + switchToTone(name) { + if (name === this.activeTone) return; + const program = mappings[name]; + const midiApi = getApi(); + if (program !== undefined && midiApi?.sendMidiToSlot) { + midiApi.sendMidiToSlot(slotId, 0, channel, program); + console.log('[tone-switcher] MIDI PC:', name, '-> program', program); + } + this.activeTone = name; + } + }; + } + window._aeBypassSwitchToTone = bypassSwitchToTone; + window._aeMakeMidiToneSwitcher = makeMidiToneSwitcher; + class ToneSwitcher { constructor() { this.toneSlotMap = {}; // { toneName: [slotId, ...] } @@ -2764,28 +2808,11 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; } switchToTone(toneName) { - if (toneName === this.activeTone) return; - if (!this.toneSlotMap[toneName]) return; - - const changes = []; - // Bypass old tone - if (this.activeTone && this.toneSlotMap[this.activeTone]) { - for (const id of this.toneSlotMap[this.activeTone]) - changes.push({ slotId: id, bypassed: true }); - } - // Unbypass new tone - for (const id of this.toneSlotMap[toneName]) - changes.push({ slotId: id, bypassed: false }); - - if (changes.length > 0) api.setMultiBypass(changes); - this.activeTone = toneName; - const newPreset = this.tonePresetMap[toneName]; - if (newPreset) { - applyPresetGainLevels(newPreset); - applyPresetNoiseGate(newPreset); - applyPresetTonePolish(newPreset); - } - console.log('[tone-switcher] Switched to:', toneName); + bypassSwitchToTone(this, toneName, (changes) => api.setMultiBypass(changes), (preset) => { + applyPresetGainLevels(preset); + applyPresetNoiseGate(preset); + applyPresetTonePolish(preset); + }); } async teardown() { @@ -3225,13 +3252,20 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; } let _applyToneMappingsLock = Promise.resolve(); - function applyToneMappingsNow(songKey, options = {}) { + // Serialises every song chain rebuild: tone-mapping applies here and IIFE 2's + // song preload (through window._aeWithToneChainLock), so two rebuilds never + // clear/load the chain at the same time (untangler I-003). + function withToneChainLock(job) { const next = _applyToneMappingsLock .catch(() => {}) - .then(() => _applyToneMappingsImpl(songKey, options)); + .then(job); _applyToneMappingsLock = next.catch(() => {}); return next; } + window._aeWithToneChainLock = withToneChainLock; + function applyToneMappingsNow(songKey, options = {}) { + return withToneChainLock(() => _applyToneMappingsImpl(songKey, options)); + } async function _applyToneMappingsImpl(songKey, options = {}) { const forceBypass = !!options.forceBypass; @@ -3308,18 +3342,12 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; if (midiConfig?.mode === 'midi' && midiConfig.vstSlotId >= 0) { const midiMappings = midiConfig.mappings || {}; toneSwitcher = null; - window._toneSwitcher = { - activeTone: null, - midiMode: true, - switchToTone(name) { - if (name === this.activeTone) return; - const program = midiMappings[name]; - if (program !== undefined && api?.sendMidiToSlot) { - api.sendMidiToSlot(midiConfig.vstSlotId, 0, midiConfig.channel || 1, program); - } - this.activeTone = name; - } - }; + window._toneSwitcher = makeMidiToneSwitcher({ + getApi: () => api, + slotId: midiConfig.vstSlotId, + channel: midiConfig.channel || 1, + mappings: midiMappings, + }); if (activeNow) window._toneSwitcher.switchToTone(activeNow); return; } @@ -3899,19 +3927,12 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; const _midiMappings = mappingsObj; const _midiVstSlot = vstSelect ? parseInt(vstSelect.value) : -1; const _midiCh = chInput ? parseInt(chInput.value) : 1; - window._toneSwitcher = { - activeTone: null, - midiMode: true, - switchToTone(name) { - if (name === this.activeTone) return; - const program = _midiMappings[name]; - if (program !== undefined && _liveApi?.sendMidiToSlot) { - _liveApi.sendMidiToSlot(_midiVstSlot, 0, _midiCh, program); - console.log('[tone-switcher] MIDI PC:', name, '-> program', program); - } - this.activeTone = name; - } - }; + window._toneSwitcher = makeMidiToneSwitcher({ + getApi: () => _liveApi, + slotId: _midiVstSlot, + channel: _midiCh, + mappings: _midiMappings, + }); console.log('[tone-switcher] Saved & activated MIDI config:', mappingsObj); midiSaveBtn.textContent = 'Saved!'; setTimeout(() => { midiSaveBtn.textContent = 'Save MIDI Mapping'; }, 1500); @@ -4777,7 +4798,12 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; }, 500); // Start tone monitoring and preload presets after WebSocket delivers tone data - setTimeout(async () => { + setTimeout(() => { + if (hookState.toneAutoLoadGeneration !== generation) return; + // Queue behind any tone-mapping apply already rebuilding the chain + // (and make later ones wait for this) -- see withToneChainLock. + const preload = async () => { + // A newer song may have started while this waited for the lock. if (hookState.toneAutoLoadGeneration !== generation) return; let shouldResolveChainRebuildGuard = false; try { @@ -4970,22 +4996,12 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; if (midiConfig?.mode === 'midi' && midiConfig.vstSlotId >= 0) { // MIDI PC mode — send program changes to a single VST const midiMappings = midiConfig.mappings || {}; - window._toneSwitcher = { - activeTone: null, - midiMode: true, - switchToTone(name) { - console.log('[tone-switcher] switchToTone called:', name, 'current:', this.activeTone, 'midiMode:', this.midiMode); - if (name === this.activeTone) return; - const program = midiMappings[name]; - const _api = window.feedBackDesktop?.audio; - console.log('[tone-switcher] program:', program, 'api:', !!_api, 'sendMidi:', !!_api?.sendMidiToSlot, 'slotId:', midiConfig.vstSlotId); - if (program !== undefined && _api?.sendMidiToSlot) { - _api.sendMidiToSlot(midiConfig.vstSlotId, 0, midiConfig.channel || 1, program); - console.log('[tone-switcher] MIDI PC SENT:', name, '-> program', program); - } - this.activeTone = name; - } - }; + window._toneSwitcher = window._aeMakeMidiToneSwitcher({ + getApi: () => window.feedBackDesktop?.audio, + slotId: midiConfig.vstSlotId, + channel: midiConfig.channel || 1, + mappings: midiMappings, + }); // Send initial PC for base tone const _apiInit = window.feedBackDesktop?.audio; if (midiMappings[toneBase] !== undefined && _apiInit?.sendMidiToSlot) { @@ -5060,6 +5076,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; window._toneSwitcher = null; const toneSlotMap = {}; const tonePresetMap = {}; + const tonePresetNameMap = {}; const lookupBypass = (name) => (window._aeResolveTonePresetName ? window._aeResolveTonePresetName(mappings, name) @@ -5120,6 +5137,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; } toneSlotMap[toneName] = slotIds; tonePresetMap[toneName] = preset; + tonePresetNameMap[toneName] = presetName; if (toneName !== effectiveBase && slotIds.length > 0) { await api.setMultiBypass(slotIds.map(id => ({ slotId: id, bypassed: true }))); } @@ -5136,23 +5154,13 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; activeTone: effectiveBase, toneSlotMap, tonePresetMap, + tonePresetNameMap, switchToTone(name) { - if (name === this.activeTone) return; - if (!this.toneSlotMap[name]) return; - const bypassList = []; - if (this.activeTone && this.toneSlotMap[this.activeTone]) { - for (const id of this.toneSlotMap[this.activeTone]) bypassList.push({ slotId: id, bypassed: true }); - } - for (const id of this.toneSlotMap[name]) bypassList.push({ slotId: id, bypassed: false }); - if (bypassList.length > 0) api.setMultiBypass(bypassList); - this.activeTone = name; - const newPreset = this.tonePresetMap?.[name]; - if (newPreset) { - applyPresetGainLevels(api, newPreset); - applyPresetNoiseGate(api, newPreset); - applyPresetTonePolish(api, newPreset); - } - console.log('[tone-switcher] Switched to:', name); + window._aeBypassSwitchToTone(this, name, (changes) => api.setMultiBypass(changes), (preset) => { + applyPresetGainLevels(api, preset); + applyPresetNoiseGate(api, preset); + applyPresetTonePolish(api, preset); + }); } }; _preloadedToneCacheKey = getTonePreloadCacheKey(); @@ -5167,6 +5175,9 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; // show an empty-chain monitor warning. if (shouldResolveChainRebuildGuard) await resolveChainRebuildGuard(); } + }; + const lock = window._aeWithToneChainLock; + void (typeof lock === 'function' ? lock(preload) : preload()); }, 800); }, }; diff --git a/tests/tone-switcher-parity.test.js b/tests/tone-switcher-parity.test.js index 0b26f36..a868a68 100644 --- a/tests/tone-switcher-parity.test.js +++ b/tests/tone-switcher-parity.test.js @@ -1,13 +1,12 @@ -// Untangler safety net for I-003 (one tone-switcher factory shared by both -// screen.js IIFEs). +// Untangler safety net for I-003 (one tone-switch implementation shared by +// both screen.js IIFEs). // -// Today the bypass switcher exists twice (IIFE 1's ToneSwitcher class and an -// object literal in IIFE 2's song preload) and the MIDI program-change -// switcher three times. These tests run every copy against the same scripted -// tone sequence with a fake audio API and require identical engine calls, so -// collapsing them into one factory cannot change what reaches the engine. -// The preload race (IIFE 2 not serialised by _applyToneMappingsLock) is not -// unit-testable here; it is covered by the packaged-build checklist in +// Bypass switchers are installed in two places (IIFE 1's ToneSwitcher class and +// IIFE 2's song preload) and MIDI program-change switchers in three. Each +// install site is run against the same scripted tone sequence with a fake +// audio API and must make identical engine calls. The chain lock that +// serialises IIFE 2's preload with tone-mapping applies is tested directly; +// the real-app timing is covered by the packaged-build checklist in // .untangler/audit.json (I-003 safety_net.manual_checks). const test = require('node:test'); const assert = require('node:assert/strict'); @@ -28,15 +27,28 @@ function extractDecl(src, head) { const open = head.startsWith('class ') ? src.indexOf('{', start) : src.indexOf('{', src.indexOf(')', start)); return src.slice(start, open) + braceBlock(src, open); } -// The object literal assigned to window._toneSwitcher at the first assignment -// after `anchor`. -function switcherLiteral(anchor) { +function parenBlock(src, openIdx) { + let i = openIdx + 1, depth = 1; + while (i < src.length && depth > 0) { if (src[i] === '(') depth++; else if (src[i] === ')') depth--; i++; } + return src.slice(openIdx, i); +} +// The expression (object literal or call) assigned to window._toneSwitcher at +// the first assignment after `anchor`. +function switcherExpr(anchor) { const a = SRC.indexOf(anchor); assert.ok(a !== -1, `anchor not found: ${anchor}`); - const assign = SRC.indexOf('window._toneSwitcher = {', a); - assert.ok(assign !== -1 && assign - a < 2000, `no switcher literal near: ${anchor}`); - return braceBlock(SRC, SRC.indexOf('{', assign)); + const marker = 'window._toneSwitcher = '; + const assign = SRC.indexOf(marker, a); + assert.ok(assign !== -1 && assign - a < 2000, `no switcher install near: ${anchor}`); + const at = assign + marker.length; + if (SRC[at] === '{') return braceBlock(SRC, at); + const open = SRC.indexOf('(', at); + return SRC.slice(at, open) + parenBlock(SRC, open); } +const SHARED = [ + extractDecl(SRC, 'function bypassSwitchToTone('), + extractDecl(SRC, 'function makeMidiToneSwitcher('), +].join('\n'); // ── Shared fixture ────────────────────────────────────────────────────────── const PRESETS = { @@ -92,6 +104,7 @@ test('IIFE 1 ToneSwitcher: preload and switch call the engine as pinned', async extractDecl(SRC, 'function getPresetItems('), extractDecl(SRC, 'function getToneChangeTime('), extractDecl(SRC, 'async function loadPresetItemsWithState('), + SHARED, extractDecl(SRC, 'class ToneSwitcher'), 'this.ToneSwitcher = ToneSwitcher;', ].join('\n'), ctx); @@ -128,20 +141,24 @@ test('IIFE 2 bypass switcher switches exactly like IIFE 1', () => { const log = []; const ctx = { console: quiet, + window: {}, api: fakeApi(log), effectiveBase: 'Clean', toneSlotMap: { Clean: [1, 2], Lead: [3] }, tonePresetMap: { Clean: PRESETS.CleanP, Lead: PRESETS.LeadP }, + tonePresetNameMap: { Clean: 'CleanP', Lead: 'LeadP' }, applyPresetGainLevels: (_api, p) => log.push(['gain', p === PRESETS.CleanP ? 'CleanP' : 'LeadP']), applyPresetNoiseGate: () => log.push(['gate']), applyPresetTonePolish: () => log.push(['polish']), }; - vm.runInNewContext(`this.sw = ${switcherLiteral('const initialPreset = tonePresetMap[effectiveBase];')};`, ctx); + vm.runInNewContext(`${SHARED} +window._aeBypassSwitchToTone = bypassSwitchToTone; +this.sw = ${switcherExpr('const initialPreset = tonePresetMap[effectiveBase];')};`, ctx); for (const t of SEQUENCE) ctx.sw.switchToTone(t); assert.deepEqual(plain(log), BYPASS_SWITCH_CALLS); - // Known drift (I-003): this copy has no tonePresetNameMap, so the chain - // panel's preset-name lookup misses for bypass songs loaded via IIFE 2. - assert.equal(ctx.sw.tonePresetNameMap, undefined); + // Fixed drift: the chain panel's preset-name lookup now works for bypass + // songs loaded via IIFE 2 too. + assert.deepEqual(plain(ctx.sw.tonePresetNameMap), { Clean: 'CleanP', Lead: 'LeadP' }); }); // ── MIDI program-change switcher (three copies) ───────────────────────────── @@ -162,7 +179,9 @@ for (const [label, anchor] of Object.entries(MIDI_COPIES)) { api, midiConfig: MIDI, midiMappings: MIDI.mappings, _liveApi: api, _midiMappings: MIDI.mappings, _midiVstSlot: MIDI.vstSlotId, _midiCh: MIDI.channel, }; - vm.runInNewContext(`this.sw = ${switcherLiteral(anchor)};`, ctx); + vm.runInNewContext(`${SHARED} +window._aeMakeMidiToneSwitcher = makeMidiToneSwitcher; +this.sw = ${switcherExpr(anchor)};`, ctx); assert.equal(ctx.sw.midiMode, true); for (const t of ['Clean', 'Clean', 'Nope', 'Lead', 'Lead']) ctx.sw.switchToTone(t); assert.deepEqual(log, [ @@ -172,3 +191,40 @@ for (const [label, anchor] of Object.entries(MIDI_COPIES)) { assert.equal(ctx.sw.activeTone, 'Lead'); }); } + +// ── Chain lock shared by tone-mapping applies and IIFE 2's preload ───────── +test('withToneChainLock runs jobs one at a time, in order, past failures', async () => { + const ctx = { window: {}, Promise }; + vm.runInNewContext(`let _applyToneMappingsLock = Promise.resolve(); +${extractDecl(SRC, 'function withToneChainLock(')} +this.lock = withToneChainLock;`, ctx); + const order = []; + let running = 0; + const job = (name, fail) => async () => { + running++; + assert.equal(running, 1, `${name} overlapped another job`); + order.push(`${name}:start`); + await new Promise((r) => setTimeout(r, 5)); + order.push(`${name}:end`); + running--; + if (fail) throw new Error(name); + }; + const a = ctx.lock(job('a')); + const b = ctx.lock(job('b', true)); + const c = ctx.lock(job('c')); + await a; + await assert.rejects(b, /b/); + await c; + assert.deepEqual(order, ['a:start', 'a:end', 'b:start', 'b:end', 'c:start', 'c:end']); +}); + +test('tone-mapping applies and the IIFE 2 song preload share that lock', () => { + assert.match(SRC, /function applyToneMappingsNow\(songKey, options = \{\}\) \{\n\s*return withToneChainLock\(/); + assert.match(SRC, /window\._aeWithToneChainLock = withToneChainLock;/); + const preloadAt = SRC.indexOf('const preload = async () => {'); + assert.ok(preloadAt !== -1, 'IIFE 2 preload not found'); + const tail = SRC.slice(preloadAt, SRC.indexOf('}, 800);', preloadAt)); + assert.match(tail, /const lock = window\._aeWithToneChainLock;\n\s*void \(typeof lock === 'function' \? lock\(preload\) : preload\(\)\);\s*$/); + // After waiting for the lock, a newer song must win. + assert.match(tail, /^const preload = async \(\) => \{\n(?:\s*\/\/.*\n)*\s*if \(hookState\.toneAutoLoadGeneration !== generation\) return;/); +}); From 844691832004f6653a3673cc51cc432ad2711aed Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:22:37 -0800 Subject: [PATCH 18/25] chore: untangler I-003 done pending listening check Co-Authored-By: Claude Opus 5.5 --- .untangler/audit.json | 9 ++++++--- .untangler/state.json | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.untangler/audit.json b/.untangler/audit.json index baf4473..ebebe13 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -65,9 +65,11 @@ "src/renderer/screen.js:4445-4464,3227-3233" ], "description": "IIFE2 copies of the bypass/MIDI switchers lack tonePresetNameMap and normalizeTimelineToneData; the IIFE2 preload is not serialized by _applyToneMappingsLock.", - "status": "pending", + "status": "done", "refactor_plan": "Add vm tests, export one switcher factory + chain-job lock from IIFE1, call from IIFE2; verify on the packaged build.", - "commits": [], + "commits": [ + "36ffd5a" + ], "safety_net": { "type": "unit_test", "location": "tests/tone-switcher-parity.test.js", @@ -81,7 +83,8 @@ "Packaged build: song with a whole-song tone lock -> locked preset holds through tone changes", "Packaged build: start one song then quickly another -> chain ends up with the second song's presets only (preload race)" ] - } + }, + "outcome": "Shared bypassSwitchToTone/makeMidiToneSwitcher (2 bypass + 3 MIDI copies folded), IIFE2 switcher gains tonePresetNameMap, IIFE2 song preload runs under window._aeWithToneChainLock. Unit tests green; packaged-build listening checklist (safety_net.manual_checks) pending with the user." }, { "id": "I-004", diff --git a/.untangler/state.json b/.untangler/state.json index adb3cef..3342e74 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -76,5 +76,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 3: I-001, I-002, I-006, I-004 done. Next: I-003 tone switcher factory shared by both screen.js IIFEs + route IIFE2 preload through the chain lock; needs the packaged-build listening checklist" + "next_action": "Phase 3: all Top 5 done in code. User to run the I-003 listening checklist on release/win-unpacked/feedback.exe (built from 36ffd5a), then check_gate.py 3 and advance to Phase 4" } \ No newline at end of file From 7fc6d2143ddcde1fe5267ddbbcae3975cc8f7dd4 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:07:02 -0800 Subject: [PATCH 19/25] chore: untangler I-003 checked in the packaged app Co-Authored-By: Claude Opus 5.5 --- .untangler/audit.json | 11 ++++++++++- .untangler/deferred.md | 2 ++ .untangler/state.json | 2 +- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/.untangler/audit.json b/.untangler/audit.json index ebebe13..5f59dfc 100644 --- a/.untangler/audit.json +++ b/.untangler/audit.json @@ -82,7 +82,16 @@ "Packaged build: MIDI PC song -> program changes reach the VST, chain is not wiped", "Packaged build: song with a whole-song tone lock -> locked preset holds through tone changes", "Packaged build: start one song then quickly another -> chain ends up with the second song's presets only (preload race)" - ] + ], + "automated_app_checks": { + "date": "2026-11-09", + "build": "release/win-unpacked from 36ffd5a, driven over CDP", + "tone_changes": "PASS (Helena, manual bypass: Twin/Mesa slots swap at 26.6/72.8/74.7 s; tonePresetNameMap present)", + "midi": "Program changes correct (clean->2, lead->5, back->2); chain wiped on song load - same on the previous code (A/B), pre-existing, deferred", + "tone_lock": "PASS (Main Lead held through tone changes)", + "quick_switch": "PASS 25/25 manual bypass, 25/25 Tone Automation (gaps 300-1600 ms, Helena -> Dead!)", + "not_covered": "How it sounds; whether the VST actually changes patch on MIDI" + } }, "outcome": "Shared bypassSwitchToTone/makeMidiToneSwitcher (2 bypass + 3 MIDI copies folded), IIFE2 switcher gains tonePresetNameMap, IIFE2 song preload runs under window._aeWithToneChainLock. Unit tests green; packaged-build listening checklist (safety_net.manual_checks) pending with the user." }, diff --git a/.untangler/deferred.md b/.untangler/deferred.md index 9c3b4a7..c598ce6 100644 --- a/.untangler/deferred.md +++ b/.untangler/deferred.md @@ -6,3 +6,5 @@ Problems noticed during refactor but deliberately not fixed now. - (found in Phase 2, I-004) 55 audio:* handlers throw instead of returning a fallback when the addon call throws. Guarding them is a behaviour change; decide explicitly, not as part of the callAddon refactor. - (found in Phase 3, I-002) The python.ts <-> soundfont-manager.ts require cycle is still there: python.ts needs getActiveSoundfontPath and soundfont-manager needs restartPython. Moving the config out did not break it (the audit over-claimed). Harmless today (both uses are inside functions). - (Phase 3, I-004) ~27 other guarded addon sites in audio-bridge.ts were NOT folded into callAddon(): they validate args between the guard and the call (guard order decides which fallback you get), catch silently, or have no try (the bare getters like getSongBusClock, getStreamSinkLevel). Each would be a small behaviour change; take them one at a time if wanted. setLivePitch/getLivePitch must stay self-contained (tests/engine/live-pitch.test.js extracts them verbatim). +- (Phase 3, I-003 app check) MIDI PC mode: loading a song wipes the chain, so the VST the program changes target is gone (getChainState() == [] after load). Same on the pre-I-003 code (A/B on the packaged build), so pre-existing. Likely the 400 ms _aeClearChainForNewSong path not exempting MIDI mode. +- (Phase 3, I-003 app check) One song load rebuilds the chain up to three times (IIFE 2 preload + IIFE 1 song:ready reapplies at 600/1500 ms); a locked song logged "[tone-lock] whole song" 3-4 times. Now serialised, but redundant clear/load work (and VST editor windows closing) per song. diff --git a/.untangler/state.json b/.untangler/state.json index 3342e74..547f69b 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -76,5 +76,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 3: all Top 5 done in code. User to run the I-003 listening checklist on release/win-unpacked/feedback.exe (built from 36ffd5a), then check_gate.py 3 and advance to Phase 4" + "next_action": "Phase 3 done in code and app-checked over CDP (I-003 checks pass; MIDI chain wipe is pre-existing, deferred). User to confirm, then advance 3 and start Phase 4 (hardening)" } \ No newline at end of file From 081929342171743b8623758460ba645be76b5d82 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:11:44 -0800 Subject: [PATCH 20/25] chore: untangler phase 4 guard rails ARCHITECTURE.md (layout + 8 rules), tests/boundaries.test.js enforcing them in the fast lane (CI), a pre-commit guard script with npm run hooks:install, CLAUDE.md conventions, CONTRIBUTING.md. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE.md | 79 ++++++++++++++++++++++++++++++++ CLAUDE.md | 68 ++++++++++++++++++++++++++++ CONTRIBUTING.md | 30 +++++++++++++ package.json | 1 + scripts/hooks/pre-commit | 20 +++++++++ scripts/install-hooks.js | 12 +++++ src/main/config-paths.ts | 2 +- tests/boundaries.test.js | 87 ++++++++++++++++++++++++++++++++++++ tests/test-inventory.test.js | 2 +- 9 files changed, 299 insertions(+), 2 deletions(-) create mode 100644 ARCHITECTURE.md create mode 100644 CLAUDE.md create mode 100644 CONTRIBUTING.md create mode 100644 scripts/hooks/pre-commit create mode 100644 scripts/install-hooks.js create mode 100644 tests/boundaries.test.js diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..6e62f94 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,79 @@ +# Architecture + +fee[dB]ack desktop is the Electron shell around the bundled feedBack core (a Python server +on port 18000 plus its web UI). It adds: + +- window and pane management +- auto-update +- a native low-latency audio engine +- a crash-isolated VST host +- the `audio_engine` renderer plugin that drives the engine from the UI + +Windows is the platform that matters; macOS and Linux build in CI. + +``` + renderer (core web UI + plugins) main process (Node/Electron) native + ┌──────────────────────────────┐ IPC ┌──────────────────────────────┐ N-API ┌──────────────────┐ + │ src/renderer/screen.js │ ─────► │ preload.ts (window.feedBack │ ────► │ slopsmith_audio │ + │ IIFE 1: chain, presets, │ │ Desktop.*) │ │ .node (src/audio)│ + │ tone switching │ │ audio-bridge.ts (audio:*) │ └────────┬─────────┘ + │ IIFE 2: song lifecycle, │ │ main.ts, pane-hosts.ts, │ │ spawn + │ preload, monitor │ │ plugin-manager.ts, update- │ ┌────────▼─────────┐ + │ IIFE 3: chain button owner │ │ manager.ts, python.ts ... │ │ VST host process │ + └──────────────────────────────┘ └──────────────┬───────────────┘ │ (src/vst-host) │ + │ spawn └──────────────────┘ + ┌────────▼────────┐ + │ Python core │ resources/slopsmith, :18000 + └─────────────────┘ +``` + +## Module layout + +| Path | Owns | +|------|------| +| `src/main/main.ts` | App bootstrap (order is load-bearing), windows, app-level IPC | +| `src/main/preload.ts` | The only renderer-facing API (`window.feedBackDesktop`) | +| `src/main/audio-bridge.ts` | Every `audio:*` IPC handler; the only main-process file that loads the native addon | +| `src/main/desktop-config.ts` | `/slopsmith-desktop.json`: the only reader and writer | +| `src/main/soundfont-manager.ts` | Soundfont quality and download | +| `src/main/python.ts` | Spawning and restarting the Python core | +| `src/main/config-*.ts` | Config paths, bootstrap, migrations, reset | +| `src/main/pane-hosts.ts`, `pane-tray.ts` | Pop-out pane windows | +| `src/renderer/screen.js` | The `audio_engine` plugin, one classic script made of 3 IIFEs | +| `src/audio` | Native engine (JUCE): device I/O, processing chain, detection, buses | +| `src/vst-host` | Sandboxed VST host process | +| `scripts/` | Build, bundle and release shell scripts (`build-common.sh` is the shared core) | +| `tests/*.test.js` | Fast lane: source-reading and stubbed tests, run in CI (`npm run test:fast`) | +| `tests/engine/*.test.js` | Engine lane: loads the built addon, run by hand (`npm run test:engine`) | +| `tests/contracts/` | Snapshots of the addon exports, IPC channels and preload API | + +## Rules + +These are enforced by `tests/boundaries.test.js` and `tests/test-inventory.test.js`, which +run in CI and in the pre-commit hook. + +1. **Native addon:** only `audio-bridge.ts` loads `slopsmith_audio.node` in the main + process. Everything else goes through its IPC handlers. +2. **Desktop config:** only `desktop-config.ts` reads or writes `slopsmith-desktop.json`. + Callers import `getDesktopConfig` / `setDesktopConfig` from it. `config-paths.ts` may + list the file name for reset. +3. **No Node in the renderer:** `src/renderer` never uses `require` or imports `electron`; + it talks to the main process only through `window.feedBackDesktop`. The main process + never imports renderer code. +4. **Cross-IIFE calls:** the IIFEs in `screen.js` don't share scope. One IIFE calls into + another only through a `window._ae*` export, never a bare function name (see + `renderer-iife-scope.test.js`). +5. **One tone-switch implementation:** every `window._toneSwitcher` that switches tones by + bypass or MIDI uses `bypassSwitchToTone` / `makeMidiToneSwitcher` (exported as + `window._aeBypassSwitchToTone` / `window._aeMakeMidiToneSwitcher`). No new inline copies. +6. **One chain lock:** anything that rebuilds the chain for a song runs under + `withToneChainLock` (`window._aeWithToneChainLock` from IIFE 2). +7. **Guarded addon calls:** a handler whose whole body is "addon missing → fallback; call; + on throw warn `[audio] failed: …` and return the fallback" uses + `callAddon(name, fallback, ...args)` instead of a new copy. +8. **Test lanes:** fast-lane tests never load the native addon. Engine tests live in + `tests/engine/`. + +## Known debt + +See `.untangler/deferred.md` and `REFACTOR_AUDIT.md`. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..c72da7b --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,68 @@ +# feedBack desktop + +Electron shell around the bundled feedBack core, with a native JUCE audio engine. See +`ARCHITECTURE.md` for the layout and `.untangler/RUNNING.md` for how to build, run and test. + +## Codebase Conventions (do not break these) + +This repo went through a structural cleanup (`.untangler/`, `REFACTOR_AUDIT.md`). Changes +must keep to these rules. If a task can't, stop and ask the user before going on. + +### Architecture + +The rules are in `ARCHITECTURE.md`. `tests/boundaries.test.js` enforces them in CI and in +the pre-commit hook. In short: + +- Only `src/main/audio-bridge.ts` loads the native addon. +- Only `src/main/desktop-config.ts` reads or writes `slopsmith-desktop.json`. +- The renderer reaches the main process only through `window.feedBackDesktop`. +- The three IIFEs in `src/renderer/screen.js` call each other only through `window._ae*` + exports, never bare names. +- Tone switchers use `bypassSwitchToTone` / `makeMidiToneSwitcher`. +- Song chain rebuilds run under `withToneChainLock`. +- New "guard, call, warn, fallback" addon handlers use `callAddon()`. + +### Before adding code + +- Search for an existing implementation first. Extend the canonical one; don't add another + copy. +- Many tests match exact source text, for example: + - `tests/contracts/extract.js` relies on literal `ipcMain.handle('…'` lines. + - `tests/engine/live-pitch.test.js` extracts `audio:setLivePitch` / `audio:getLivePitch` + verbatim. + + When you change such code, update the matching test in the same commit. +- The contract snapshots (`tests/contracts/*.json`) are the public surface: the addon + exports, IPC channels and preload API. Change them only on purpose. + +### Tests + +- Run only the fast, source-reading tests locally (the list is in `.untangler/RUNNING.md`). + Never run `npm run test:engine` or anything that loads the native addon unless the user + asks. It grabs the audio device and lags the machine. +- New logic needs a test. A bug fix needs a test that would have caught the bug. +- Never disable or loosen a failing test to get green. +- `tests/fixtures/audio-bridge-fallbacks.snapshot.json` pins every `audio:*` handler's + fallbacks. Regenerate it (`UPDATE_SNAPSHOT=1`) only for an intended behaviour change, and + say so in the commit. + +### Commits + +- Keep refactors and features in separate commits; one logical change each, small diffs. +- Never push, merge or release without the user's explicit go-ahead. +- Check user-facing changes on the local packaged build + (`npm run build:ts && npx electron-builder --win --dir`), not `npm start`. + +### When tempted to rewrite + +Don't. Refactor in small steps (the `codebase-untangler` skill) and log side issues in +`.untangler/deferred.md` instead of fixing them on the way. + +### Patterns that caused the last cleanup + +- Copy-pasting a handler or switcher and editing one line. There were 3 MIDI switchers and + 2 bypass switchers. +- Two code paths rebuilding the same state with no shared lock. +- Catching errors and silently carrying on: missing plugins used to ship unnoticed. +- App-wide state living in an unrelated module (the desktop config sat in + `soundfont-manager.ts`). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..30ac938 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,30 @@ +# Contributing + +## Setup + +```bash +npm install +npm run hooks:install # pre-commit guard: boundary rules + safety-net tests, ~2 s +``` + +Building the native engine and bundling the core are covered in `WINDOWS_BUILD_REQUIREMENTS.md` +and `scripts/BUILD_SCRIPTS.md`. + +## Tests + +| Command | What runs | Where | +|---------|-----------|-------| +| `npm test` / `npm run test:fast` | `tests/*.test.js`: source-reading and stubbed tests, no native engine | CI (`ci.yml` check job) and locally | +| `npm run test:engine` | `tests/engine/*.test.js`: load the built `slopsmith_audio.node` | Locally, on demand (they open audio devices) | + +## Conventions + +Read `ARCHITECTURE.md` (module layout and rules). `tests/boundaries.test.js` enforces the +rules. In short: + +- One logical change per commit. Keep refactors and features in separate commits. +- Reuse the canonical helper instead of copying code (`callAddon`, the tone-switch helpers, + `desktop-config.ts`). +- Bug fixes come with a test that would have caught the bug. +- A bundled plugin that fails to clone now fails the build. Set `ALLOW_MISSING_PLUGINS=1` + only for local or fork builds. diff --git a/package.json b/package.json index 896ea07..e9add50 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "test": "npm run test:fast", "test:fast": "node --test \"tests/*.test.js\"", "test:engine": "node --test \"tests/engine/*.test.js\"", + "hooks:install": "node scripts/install-hooks.js", "build:ts": "tsc && node -e \"const fs=require('fs'),path=require('path');fs.copyFileSync('src/main/splash.html','dist/main/splash.html');fs.copyFileSync('src/main/spinner.json','dist/main/spinner.json');fs.copyFileSync('node_modules/lottie-web/build/player/lottie.min.js','dist/main/lottie.min.js');const dst='dist/main/images';if(fs.existsSync(dst))fs.rmSync(dst,{recursive:true});fs.mkdirSync(dst,{recursive:true});fs.readdirSync('src/main/images',{withFileTypes:true}).filter(d=>d.isFile()&&d.name.endsWith('.webp')).forEach(d=>fs.copyFileSync(path.join('src/main/images',d.name),path.join(dst,d.name)));fs.copyFileSync('resources/icons/icon.ico','dist/main/tray.ico');fs.copyFileSync('resources/icons/32x32.png','dist/main/tray.png')\"", "build:audio": "bash scripts/build-audio.sh Release", "build:audio:debug": "bash scripts/build-audio.sh Debug", diff --git a/scripts/hooks/pre-commit b/scripts/hooks/pre-commit new file mode 100644 index 0000000..671bf3d --- /dev/null +++ b/scripts/hooks/pre-commit @@ -0,0 +1,20 @@ +#!/bin/sh +# Pre-commit guard (installed by `npm run hooks:install`). Runs the architecture +# boundary rules and the untangler safety nets: source-reading tests only, no +# native engine, a couple of seconds. Skip once with `git commit --no-verify`. +cd "$(git rev-parse --show-toplevel)" || exit 1 +log="${TMPDIR:-/tmp}/feedback-precommit.log" +node --test \ + tests/boundaries.test.js \ + tests/test-inventory.test.js \ + tests/renderer-iife-scope.test.js \ + tests/tone-switcher-parity.test.js \ + tests/audio-bridge-fallbacks.test.js \ + tests/desktop-config.test.js \ + tests/build-plugin-clone.test.js > "$log" 2>&1 +status=$? +if [ $status -ne 0 ]; then + grep -E "^not ok|AssertionError|Error:" "$log" | head -20 + echo "pre-commit: guard tests failed (full log: $log)" >&2 +fi +exit $status diff --git a/scripts/install-hooks.js b/scripts/install-hooks.js new file mode 100644 index 0000000..1cf419d --- /dev/null +++ b/scripts/install-hooks.js @@ -0,0 +1,12 @@ +// Installs scripts/hooks/pre-commit into this checkout's git hooks directory +// (works in worktrees). Run once per clone: npm run hooks:install +const fs = require('node:fs'); +const path = require('node:path'); +const { execSync } = require('node:child_process'); + +const hooksDir = execSync('git rev-parse --git-path hooks').toString().trim(); +fs.mkdirSync(hooksDir, { recursive: true }); +const dest = path.join(hooksDir, 'pre-commit'); +fs.copyFileSync(path.join(__dirname, 'hooks', 'pre-commit'), dest); +fs.chmodSync(dest, 0o755); +console.log(`installed ${dest}`); diff --git a/src/main/config-paths.ts b/src/main/config-paths.ts index dfa7f2a..7663631 100644 --- a/src/main/config-paths.ts +++ b/src/main/config-paths.ts @@ -94,7 +94,7 @@ export function enumerateConfigPaths(env: ConfigPathEnv): ConfigPathCategories { const c = env.configDir; const appSettingsAndCaches = [ - // Desktop prefs (soundfont quality, LAN access) — soundfont-manager.ts + // Desktop prefs (soundfont quality, LAN access, windows) — desktop-config.ts path.join(u, 'slopsmith-desktop.json'), // Audio device settings — audio-bridge.ts path.join(u, 'slopsmith-audio-settings.json'), diff --git a/tests/boundaries.test.js b/tests/boundaries.test.js new file mode 100644 index 0000000..35c506e --- /dev/null +++ b/tests/boundaries.test.js @@ -0,0 +1,87 @@ +// Architecture boundary rules from ARCHITECTURE.md. Source-reading only, so it +// runs in the fast lane, in CI and in the pre-commit hook. A failure here means +// a change crossed a boundary the untangler refactor set up; fix the change +// (or update ARCHITECTURE.md and this test together, deliberately). +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const ROOT = path.join(__dirname, '..'); +const read = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8').replace(/\r\n/g, '\n'); +const filesIn = (dir, ext) => fs.readdirSync(path.join(ROOT, dir), { recursive: true }) + .map(String).filter((f) => f.endsWith(ext)).map((f) => path.join(dir, f).replace(/\\/g, '/')); +// Code without // line comments and /* */ blocks (good enough for these checks). +const code = (src) => src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:'"`\\])\/\/.*$/gm, '$1'); + +const MAIN = filesIn('src/main', '.ts'); +const RENDERER = filesIn('src/renderer', '.js'); + +function braceBlock(src, openIdx) { + let i = openIdx + 1, depth = 1; + while (i < src.length && depth > 0) { if (src[i] === '{') depth++; else if (src[i] === '}') depth--; i++; } + return src.slice(openIdx, i); +} + +test('rule 1: only audio-bridge.ts loads the native addon', () => { + const offenders = MAIN.filter((f) => /slopsmith_audio\.node/.test(code(read(f))) && f !== 'src/main/audio-bridge.ts'); + assert.deepEqual(offenders, []); +}); + +test('rule 2: only desktop-config.ts owns slopsmith-desktop.json', () => { + const allowed = new Set(['src/main/desktop-config.ts', 'src/main/config-paths.ts']); + const offenders = MAIN.filter((f) => /slopsmith-desktop\.json/.test(code(read(f))) && !allowed.has(f)); + assert.deepEqual(offenders, []); + for (const f of MAIN) { + const m = code(read(f)).match(/import\s*\{[^}]*\b(get|set)DesktopConfig\b[^}]*\}\s*from\s*'([^']+)'/g) || []; + for (const imp of m) assert.match(imp, /from '\.\/desktop-config'$/, `${f}: ${imp}`); + } +}); + +test('rule 3: no Node/electron in the renderer, no renderer code in main', () => { + for (const f of RENDERER) { + const c = code(read(f)); + assert.doesNotMatch(c, /\brequire\s*\(/, `${f} uses require()`); + assert.doesNotMatch(c, /from\s+['"]electron['"]/, `${f} imports electron`); + } + for (const f of MAIN) { + assert.doesNotMatch(code(read(f)), /from\s+['"][^'"]*renderer\//, `${f} imports renderer code`); + } +}); + +test('rule 5: tone switchers use the shared switch helpers', () => { + const src = code(read('src/renderer/screen.js')); + const marker = 'window._toneSwitcher = {'; + let at = src.indexOf(marker), checked = 0; + while (at !== -1) { + const block = braceBlock(src, at + marker.length - 1); + const line = src.slice(0, at).split('\n').length; + // Passing api.setMultiBypass to the shared helper is fine; calling the + // engine directly from a switcher is the copy this rule forbids. + const ownBypass = /setMultiBypass\(/.test(block) && !/_aeBypassSwitchToTone\(this,/.test(block); + assert.ok(!ownBypass && !/sendMidiToSlot\(/.test(block), + `screen.js:~${line} installs a switcher with its own bypass/MIDI logic; use window._aeBypassSwitchToTone / window._aeMakeMidiToneSwitcher`); + checked++; + at = src.indexOf(marker, at + 1); + } + assert.ok(checked > 0); + const cls = src.slice(src.indexOf('class ToneSwitcher')); + const sw = cls.slice(cls.indexOf('switchToTone(toneName) {')); + assert.match(sw.slice(0, 200), /bypassSwitchToTone\(this,/, 'ToneSwitcher.switchToTone must delegate to bypassSwitchToTone'); +}); + +test('rule 6: song chain rebuilds share one lock', () => { + const src = read('src/renderer/screen.js'); + assert.match(src, /function applyToneMappingsNow\(songKey, options = \{\}\) \{\n\s*return withToneChainLock\(/); + assert.equal((src.match(/_applyToneMappingsLock = /g) || []).length, 2, 'the lock is declared once and only advanced inside withToneChainLock'); +}); + +test('rule 7: no new hand-written copies of the callAddon pattern', () => { + const src = read('src/main/audio-bridge.ts'); + const WARN = "console\\.warn\\(`\\[audio\\] (?\\w+) failed: \\$\\{(?:e\\?\\.message \\?\\? e|e instanceof Error \\? e\\.message : String\\(e\\))\\}`\\);"; + const one = new RegExp("if \\(!audio \\|\\| typeof audio\\.(?\\w+) !== 'function'\\) return (?[^;\\n]+);\\n\\s*try \\{ return audio\\.\\k\\([^()\\n]*\\); \\}\\n\\s*catch \\(e(?:: any|: unknown)?\\) \\{\\n\\s*" + WARN + "\\n\\s*return \\k;", 'g'); + const multi = new RegExp("if \\(!audio \\|\\| typeof audio\\.(?\\w+) !== 'function'\\) return (?[^;\\n]+);\\n\\s*try \\{\\n\\s*return audio\\.\\k\\([^()\\n]*\\);\\n\\s*\\} catch \\(e(?:: any|: unknown)?\\) \\{\\n\\s*" + WARN + "\\n\\s*return \\k;", 'g'); + const hits = [...src.matchAll(one), ...src.matchAll(multi)].map((m) => m.groups.n) + .filter((n) => n !== 'setLivePitch' && n !== 'getLivePitch'); + assert.deepEqual(hits, [], 'use callAddon(name, fallback, ...args) for these'); +}); diff --git a/tests/test-inventory.test.js b/tests/test-inventory.test.js index 6d429e5..8c64fe1 100644 --- a/tests/test-inventory.test.js +++ b/tests/test-inventory.test.js @@ -18,7 +18,7 @@ const ENGINE = [ // Every node:test file at the untangler baseline plus the Phase 2 safety nets. const ALL = [ - 'audio-bridge-fallbacks', 'audio-chain-persistence', 'audio-effects-executor', + 'audio-bridge-fallbacks', 'audio-chain-persistence', 'audio-effects-executor', 'boundaries', 'build-plugin-clone', 'chain-mutation-storm', 'config-bootstrap', 'config-migrations', 'config-paths', 'config-reset', 'contract-check', 'desktop-config', 'device-setup-lifecycle', 'engine-no-default-mic', From 2c5d1f4fd3b0c756afa7f219c796716f474f852c Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:11:45 -0800 Subject: [PATCH 21/25] chore: untangler phase 4 state Co-Authored-By: Claude Opus 5.5 --- .untangler/STATE.md | 6 +++--- .untangler/state.json | 14 ++++++++------ 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.untangler/STATE.md b/.untangler/STATE.md index 53bbe4e..9418119 100644 --- a/.untangler/STATE.md +++ b/.untangler/STATE.md @@ -1,7 +1,7 @@ # Codebase Untangler - State **Started**: 2026-11-07T20:48:45.568531+00:00 -**Current phase**: 3 (Refactor) +**Current phase**: 4 (Hardening) **Branch**: refactor/untangle-2026-11-07 **Stack**: electron, typescript, vanilla-js-renderer, cpp-juce-node-addon, vst-sandbox, python-bundled-core @@ -10,8 +10,8 @@ - [x] Phase 0: Triage (done) - [x] Phase 1: Audit (done) - [x] Phase 2: Safety Net (done) -- [~] Phase 3: Refactor (in_progress) -- [ ] Phase 4: Hardening (pending) +- [x] Phase 3: Refactor (done) +- [~] Phase 4: Hardening (in_progress) - [ ] Phase 5: Handover (pending) ## Baseline diff --git a/.untangler/state.json b/.untangler/state.json index 547f69b..c788fe6 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -1,7 +1,7 @@ { "schema_version": 1, "started_at": "2026-11-07T20:48:45.568531+00:00", - "current_phase": 3, + "current_phase": 4, "phases": { "0": { "name": "Triage", @@ -26,14 +26,16 @@ }, "3": { "name": "Refactor", - "status": "in_progress", + "status": "done", "gates": {}, - "started_at": "2026-11-09T14:47:39.483445+00:00" + "started_at": "2026-11-09T14:47:39.483445+00:00", + "completed_at": "2026-11-09T16:08:29.044296+00:00" }, "4": { "name": "Hardening", - "status": "pending", - "gates": {} + "status": "in_progress", + "gates": {}, + "started_at": "2026-11-09T16:08:29.044296+00:00" }, "5": { "name": "Handover", @@ -76,5 +78,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 3 done in code and app-checked over CDP (I-003 checks pass; MIDI chain wipe is pre-existing, deferred). User to confirm, then advance 3 and start Phase 4 (hardening)" + "next_action": "Phase 4: gate 2/4. User runs npm run hooks:install (clears the hook check). Lint check: boundaries are enforced by tests/boundaries.test.js instead of ESLint (no new deps); needs the override phrase or an ESLint setup. Then Phase 5 handover" } \ No newline at end of file From 51289a8b5b97f0b50690a2c81bf0aa958897f083 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:11:55 -0800 Subject: [PATCH 22/25] chore: keep the pre-commit hook script LF on Windows checkouts Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8993860 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Shell scripts run under sh/bash must keep LF line endings on Windows checkouts. +scripts/hooks/pre-commit text eol=lf From 4755b173baed4ccec6871f47d497a48114e52a51 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:15:02 -0800 Subject: [PATCH 23/25] docs: untangler handover Co-Authored-By: Claude Opus 5.5 --- .untangler/HANDOVER.md | 76 ++++++++++++++++++++++++++++++++++++++++++ .untangler/STATE.md | 9 ++--- .untangler/state.json | 29 ++++++++++++---- 3 files changed, 103 insertions(+), 11 deletions(-) create mode 100644 .untangler/HANDOVER.md diff --git a/.untangler/HANDOVER.md b/.untangler/HANDOVER.md new file mode 100644 index 0000000..c3a9e4a --- /dev/null +++ b/.untangler/HANDOVER.md @@ -0,0 +1,76 @@ +# Untangler handover: feedBack desktop + +Branch `refactor/untangle-2026-11-07`, from tag `pre-refactor-baseline` to +`refactor-complete-2026-11-09`. Nothing is pushed or merged. The branch sits on top of the +unpushed latency work (`e610887`, fix/heard-clocks), so it carries those commits too. + +## What was audited + +The whole repo: Electron main, the `screen.js` renderer plugin, the native engine, the VST +host, build scripts and CI. 33 issues are in `REFACTOR_AUDIT.md` and `.untangler/audit.json`. +You signed off a Top 5. + +## What was fixed (Top 5) + +| Issue | Change | Commits | +|-------|--------|---------| +| I-001 Test lanes | Engine-loading tests moved to `tests/engine/`. `npm test` = fast lane; `npm run test:engine` on demand. One ~2 s "Fast tests" step in the existing CI check job; no new jobs, nothing in build/release. | `f155640`, `1d2d250` | +| I-002 Desktop config | Read/write moved unchanged into `desktop-config.ts`. An unreadable `slopsmith-desktop.json` is now kept as `.corrupt` instead of being silently replaced. | `34c14bc`, `ec74899` | +| I-006 Missing plugins | A failed plugin clone fails the build (`ALLOW_MISSING_PLUGINS=1` to opt out). The desktop-plugin copy no longer hides errors. All 38 plugin repos checked reachable. | `d6625c5` | +| I-004 Guarded addon calls | `callAddon()` replaces the 7 handlers that were exact copies. The audit's "~40" overcounted; the rest differ in ways that matter. | `caab1da` | +| I-003 Tone switching | One bypass-switch step and one MIDI-switcher factory shared by both IIFEs. IIFE 2 switchers gain the preset-name map. IIFE 2's song preload runs under the same chain lock as tone-mapping applies. | `36ffd5a` | + +### How it was verified + +- **Safety-net tests first.** Each Top 5 item got its own test, written before the change: + - an `audio:*` handler snapshot (111 handlers, 3 addon states) + - a desktop-config behaviour test + - a bash harness that runs the real clone function + - tone-switch parity across every install site + - a test-file inventory + + Each one was broken on purpose to prove it catches regressions. +- **173 fast tests** and the typecheck pass after every change. +- **I-003 in the packaged app**, driven over CDP: + - Tone changes: switch correctly. + - Tone lock: holds. + - Quick song switches: 25/25 in manual mode and 25/25 with Tone Automation. + - MIDI program changes: correct. + - Not checked by ear: how it sounds, and whether a VST actually changes patch on MIDI. + +## Guard rails now in place + +- `ARCHITECTURE.md`: module layout and 8 rules. +- `tests/boundaries.test.js`: enforces the rules in the CI fast lane. +- `scripts/hooks/pre-commit`: about 2 s, boundary rules plus safety nets. **Install once with + `npm run hooks:install`** (the automated install was blocked). +- `CLAUDE.md`: "Codebase Conventions" for future AI-assisted work. +- `CONTRIBUTING.md`: setup and test commands. + +## Overrides + +Phase 4, recorded in `.untangler/overrides.log`: + +- **ESLint config:** replaced by `tests/boundaries.test.js`, so no new dependencies or CI + time. +- **Pre-commit install:** pending your `npm run hooks:install`. + +## Deferred + +The full list is in `.untangler/deferred.md` and `audit.json`. The next three by priority: + +1. **MIDI PC mode wipes the chain on song load.** The VST that program changes target is + gone after load. The same happens on the pre-refactor code. The likely cause is the + 400 ms clear-chain-for-new-song step not exempting MIDI mode. +2. **One song load rebuilds the chain up to 3 times.** The rebuilds are the IIFE 2 preload + plus the IIFE 1 reapplies at 600 and 1500 ms. They're serialised now, but the work is + redundant and closes open VST editor windows each time. +3. **I-005: no lockfile.** CI uses `npm install`, so builds aren't reproducible. Commit a + `package-lock.json` and switch to `npm ci`. I-007, the `restartPython` race, is next + after that. + +## Recommended cadence + +About 30 minutes a week on `deferred.md`, one item per small commit. Keep +`npm run test:fast` and the pre-commit guard green. When a pattern starts repeating, add a +rule to `ARCHITECTURE.md` and `tests/boundaries.test.js` together. diff --git a/.untangler/STATE.md b/.untangler/STATE.md index 9418119..21ac9b1 100644 --- a/.untangler/STATE.md +++ b/.untangler/STATE.md @@ -1,7 +1,7 @@ # Codebase Untangler - State **Started**: 2026-11-07T20:48:45.568531+00:00 -**Current phase**: 4 (Hardening) +**Current phase**: 5 (Handover) **Branch**: refactor/untangle-2026-11-07 **Stack**: electron, typescript, vanilla-js-renderer, cpp-juce-node-addon, vst-sandbox, python-bundled-core @@ -11,8 +11,8 @@ - [x] Phase 1: Audit (done) - [x] Phase 2: Safety Net (done) - [x] Phase 3: Refactor (done) -- [~] Phase 4: Hardening (in_progress) -- [ ] Phase 5: Handover (pending) +- [x] Phase 4: Hardening (done) +- [~] Phase 5: Handover (in_progress) ## Baseline @@ -22,7 +22,8 @@ ## Overrides used -(none) +- 2026-11-09T16:14:35.080914+00:00 Phase 4: Lint config present - User override 2026-11-09: boundary rules enforced by tests/boundaries.test.js in the CI fast lane instead of ESLint (no new deps / CI runtime) +- 2026-11-09T16:14:35.160636+00:00 Phase 4: Pre-commit hooks configured - User override 2026-11-09: hook script committed (scripts/hooks/pre-commit); installing into .git/hooks was blocked by the permission check - user to run npm run hooks:install --- *Auto-generated from state.json.* diff --git a/.untangler/state.json b/.untangler/state.json index c788fe6..5a334ed 100644 --- a/.untangler/state.json +++ b/.untangler/state.json @@ -1,7 +1,7 @@ { "schema_version": 1, "started_at": "2026-11-07T20:48:45.568531+00:00", - "current_phase": 4, + "current_phase": 5, "phases": { "0": { "name": "Triage", @@ -33,14 +33,16 @@ }, "4": { "name": "Hardening", - "status": "in_progress", + "status": "done", "gates": {}, - "started_at": "2026-11-09T16:08:29.044296+00:00" + "started_at": "2026-11-09T16:08:29.044296+00:00", + "completed_at": "2026-11-09T16:14:35.232063+00:00" }, "5": { "name": "Handover", - "status": "pending", - "gates": {} + "status": "in_progress", + "gates": {}, + "started_at": "2026-11-09T16:14:35.232063+00:00" } }, "baseline": { @@ -67,7 +69,20 @@ "python-bundled-core" ], "top_5_signed_off_at": "2026-11-09T14:33:29Z", - "overrides": [], + "overrides": [ + { + "timestamp": "2026-11-09T16:14:35.080914+00:00", + "phase": "4", + "gate": "Lint config present", + "reason": "User override 2026-11-09: boundary rules enforced by tests/boundaries.test.js in the CI fast lane instead of ESLint (no new deps / CI runtime)" + }, + { + "timestamp": "2026-11-09T16:14:35.160636+00:00", + "phase": "4", + "gate": "Pre-commit hooks configured", + "reason": "User override 2026-11-09: hook script committed (scripts/hooks/pre-commit); installing into .git/hooks was blocked by the permission check - user to run npm run hooks:install" + } + ], "stack_reference_note": "No matching stack file; read node-express.md as the closest (Node process) and applied its general patterns", "last_test_run": { "timestamp": "2026-11-07T20:50:11.101125+00:00", @@ -78,5 +93,5 @@ "user_ack": { "audit_duration": "2026-11-07: user asked to audit and set up (scope confirmed)" }, - "next_action": "Phase 4: gate 2/4. User runs npm run hooks:install (clears the hook check). Lint check: boundaries are enforced by tests/boundaries.test.js instead of ESLint (no new deps); needs the override phrase or an ESLint setup. Then Phase 5 handover" + "next_action": "Phase 5: handover written and tagged refactor-complete-2026-11-09 (local). User to read HANDOVER.md and confirm completion; branch left unmerged/unpushed for the user" } \ No newline at end of file From 60218a70e3443596f36c9b5ce1ba214f32d71178 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:18:12 -0800 Subject: [PATCH 24/25] fix(renderer): keep the chain on song load in MIDI program-change mode songShouldRebuildChain() said yes whenever the song's bypass mappings resolved, even with a valid MIDI PC config for the song. Playback then takes the MIDI path (program changes to an existing VST, no rebuild), so the song-start clear deleted that VST and nothing put it back. A valid MIDI PC config now keeps the chain; Tone Automation still takes precedence. Checked in the packaged app: the VST stays through load and tone changes, program changes reach it; bypass mode still rebuilds. Co-Authored-By: Claude Opus 5.5 --- src/renderer/screen.js | 7 ++++ tests/midi-chain-preserve.test.js | 64 +++++++++++++++++++++++++++++++ tests/test-inventory.test.js | 2 +- 3 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 tests/midi-chain-preserve.test.js diff --git a/src/renderer/screen.js b/src/renderer/screen.js index 4596cf5..2f1e85d 100644 --- a/src/renderer/screen.js +++ b/src/renderer/screen.js @@ -2544,6 +2544,13 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; } const raw = JSON.parse(localStorage.getItem('slopsmith-tone-mappings') || '{}') || {}; const key = window._aeGetCurrentSongKey ? window._aeGetCurrentSongKey() : ''; + // A valid MIDI PC config for this song wins over bypass mappings + // at playback (both preload paths check it first), and it only + // sends program changes to a VST already in the chain. Clearing + // here would delete that VST and nothing would rebuild it — so + // keep the chain, even if bypass mappings also resolve. + const midi = raw.midiPC && raw.midiPC[key]; + if (midi && midi.mode === 'midi' && Number(midi.vstSlotId) >= 0) return false; // Global / per-song bypass mappings: rebuild only when the // mapping resolves to a loadable preset. Evaluate the MERGED // mapping that playback actually consumes — getToneMappings() diff --git a/tests/midi-chain-preserve.test.js b/tests/midi-chain-preserve.test.js new file mode 100644 index 0000000..7a5f53d --- /dev/null +++ b/tests/midi-chain-preserve.test.js @@ -0,0 +1,64 @@ +// MIDI program-change mode must keep the chain on song load. +// +// In MIDI PC mode the song only sends program changes to a VST already in the +// chain. Song start asks songShouldRebuildChain() whether to clear the chain +// first; it used to say yes whenever the song's merged bypass mappings named a +// real preset, even though MIDI mode never uses them. The clear removed the +// VST the program changes go to (seen in the packaged app: getChainState() +// == [] after loading a MIDI-mode song). Regression test for that. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const SRC = fs.readFileSync(path.join(__dirname, '..', 'src', 'renderer', 'screen.js'), 'utf8').replace(/\r\n/g, '\n'); + +function extractFunction(src, name) { + const start = src.indexOf(`function ${name}(`); + assert.ok(start !== -1, `function ${name} not found`); + let i = src.indexOf('{', src.indexOf(')', start)) + 1, depth = 1; + while (i < src.length && depth > 0) { if (src[i] === '{') depth++; else if (src[i] === '}') depth--; i++; } + return src.slice(start, i); +} + +const KEY = 'settings-v1-song'; +const PRESETS = { Clean: { nativePreset: '{}' }, Lead: { nativePreset: '{}' } }; + +function decide({ mappings = {}, midiPC = {}, ta = null }) { + const store = { 'slopsmith-tone-mappings': JSON.stringify({ global: {}, songs: { [KEY]: mappings }, midiPC }) }; + const ctx = { + JSON, Object, String, Number, + localStorage: { getItem: (k) => store[k] ?? null }, + getPresets: () => PRESETS, + window: { + _aeGetCurrentSongKey: () => KEY, + _aeToneAutomation: ta ? { isEnabled: () => true, getConfig: () => ({ targets: ta }) } : undefined, + }, + }; + vm.runInNewContext(`${extractFunction(SRC, 'songShouldRebuildChain')}; this.r = songShouldRebuildChain();`, ctx); + return ctx.r; +} + +const MIDI = { [KEY]: { mode: 'midi', vstSlotId: 40, channel: 1, mappings: { clean: 2, lead: 5 } } }; + +test('bypass mappings alone still rebuild the chain', () => { + assert.equal(decide({ mappings: { clean: 'Clean', lead: 'Lead' } }), true); +}); + +test('MIDI PC mode keeps the chain even when bypass mappings exist', () => { + assert.equal(decide({ mappings: { clean: 'Clean', lead: 'Lead' }, midiPC: MIDI }), false); +}); + +test('MIDI PC mode with no mappings keeps the chain', () => { + assert.equal(decide({ midiPC: MIDI }), false); +}); + +test('an invalid MIDI entry (no slot) does not block a bypass rebuild', () => { + const bad = { [KEY]: { mode: 'midi', vstSlotId: -1, mappings: {} } }; + assert.equal(decide({ mappings: { clean: 'Clean' }, midiPC: bad }), true); +}); + +test('Tone Automation still wins over MIDI mode (it rebuilds the chain itself)', () => { + assert.equal(decide({ midiPC: MIDI, ta: { idle: 'Clean' } }), true); +}); diff --git a/tests/test-inventory.test.js b/tests/test-inventory.test.js index 8c64fe1..7a1ea6d 100644 --- a/tests/test-inventory.test.js +++ b/tests/test-inventory.test.js @@ -24,7 +24,7 @@ const ALL = [ 'desktop-config', 'device-setup-lifecycle', 'engine-no-default-mic', 'guitar-input-channel-default', 'heard-clock-wiring', 'input-source-selection-sync', 'juce-exclusive-type-name', 'library-path-config', 'linux-update-decision', - 'live-pitch', 'live-retune-follow-song', 'ml-note-detection', + 'live-pitch', 'live-retune-follow-song', 'midi-chain-preserve', 'ml-note-detection', 'monitor-mute-suppression', 'multi-source', 'napi-arg-fuzz', 'preset-swap-mute', 'renderer-capability-migration', 'renderer-iife-scope', 'song-tone-lock', 'startup-missing-input', 'test-inventory', From 55ae3af222a2c3142c8790be2688c099a53322e3 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:18:12 -0800 Subject: [PATCH 25/25] docs: untangler deferred MIDI chain wipe fixed Co-Authored-By: Claude Opus 5.5 --- .untangler/HANDOVER.md | 4 +--- .untangler/deferred.md | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.untangler/HANDOVER.md b/.untangler/HANDOVER.md index c3a9e4a..996932b 100644 --- a/.untangler/HANDOVER.md +++ b/.untangler/HANDOVER.md @@ -59,9 +59,7 @@ Phase 4, recorded in `.untangler/overrides.log`: The full list is in `.untangler/deferred.md` and `audit.json`. The next three by priority: -1. **MIDI PC mode wipes the chain on song load.** The VST that program changes target is - gone after load. The same happens on the pre-refactor code. The likely cause is the - 400 ms clear-chain-for-new-song step not exempting MIDI mode. +1. ~~MIDI PC mode wipes the chain on song load~~: **fixed after handover in `60218a7`**. A valid MIDI PC config now keeps the chain on song start; checked in the packaged app. 2. **One song load rebuilds the chain up to 3 times.** The rebuilds are the IIFE 2 preload plus the IIFE 1 reapplies at 600 and 1500 ms. They're serialised now, but the work is redundant and closes open VST editor windows each time. diff --git a/.untangler/deferred.md b/.untangler/deferred.md index c598ce6..ed998be 100644 --- a/.untangler/deferred.md +++ b/.untangler/deferred.md @@ -6,5 +6,5 @@ Problems noticed during refactor but deliberately not fixed now. - (found in Phase 2, I-004) 55 audio:* handlers throw instead of returning a fallback when the addon call throws. Guarding them is a behaviour change; decide explicitly, not as part of the callAddon refactor. - (found in Phase 3, I-002) The python.ts <-> soundfont-manager.ts require cycle is still there: python.ts needs getActiveSoundfontPath and soundfont-manager needs restartPython. Moving the config out did not break it (the audit over-claimed). Harmless today (both uses are inside functions). - (Phase 3, I-004) ~27 other guarded addon sites in audio-bridge.ts were NOT folded into callAddon(): they validate args between the guard and the call (guard order decides which fallback you get), catch silently, or have no try (the bare getters like getSongBusClock, getStreamSinkLevel). Each would be a small behaviour change; take them one at a time if wanted. setLivePitch/getLivePitch must stay self-contained (tests/engine/live-pitch.test.js extracts them verbatim). -- (Phase 3, I-003 app check) MIDI PC mode: loading a song wipes the chain, so the VST the program changes target is gone (getChainState() == [] after load). Same on the pre-I-003 code (A/B on the packaged build), so pre-existing. Likely the 400 ms _aeClearChainForNewSong path not exempting MIDI mode. +- FIXED in 60218a7: (Phase 3, I-003 app check) MIDI PC mode: loading a song wipes the chain, so the VST the program changes target is gone (getChainState() == [] after load). Same on the pre-I-003 code (A/B on the packaged build), so pre-existing. Likely the 400 ms _aeClearChainForNewSong path not exempting MIDI mode. - (Phase 3, I-003 app check) One song load rebuilds the chain up to three times (IIFE 2 preload + IIFE 1 song:ready reapplies at 600/1500 ms); a locked song logged "[tone-lock] whole song" 3-4 times. Now serialised, but redundant clear/load work (and VST editor windows closing) per song.