Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

test([issue-2109]): make sticky/hold pitch-tracker tests deterministic with fake timers

Adam Eivyb4524340cbf8
diff --git a/client/src/lib/pitchDetect.test.js b/client/src/lib/pitchDetect.test.js
index e80ed9511f..604f4d51ec 100644
--- a/client/src/lib/pitchDetect.test.js
+++ b/client/src/lib/pitchDetect.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
detectFrequency,
frequencyToNote,
@@ -210,55 +210,60 @@ describe('createPitchTracker', () => {
});
});
-describe('createPitchTracker — hysteresis, hold, and sticky label', () => {
- // Frame fillers for a scripted analyser: each produces a specific signal so we
- // can drive clarity and pitch frame-by-frame. With the emit throttle OFF (the
- // default), the tracker emits exactly one update per tick and consumes exactly
- // one filler per tick — so `updates[k]` corresponds to `fillers[k]`, giving a
- // deterministic sequence regardless of wall-clock timing.
- const fillSine = (hz, amplitude = 0.5) => (out) => {
- for (let i = 0; i < out.length; i++) out[i] = amplitude * Math.sin((2 * Math.PI * hz * i) / SAMPLE_RATE);
- };
- const fillSilence = () => (out) => out.fill(0);
- // A sine buried in seeded noise — clarity ≈ 0.81 at noiseAmp 0.3 (measured):
- // above holdClarity (0.6) but below acquireClarity (0.9), i.e. a "hold-band"
- // frame. Deterministic (fixed seed) so it never flakes.
- const fillMix = (hz, noiseAmp = 0.3, seed = 999) => (out) => {
- let s = seed >>> 0;
- for (let i = 0; i < out.length; i++) {
- s = (1664525 * s + 1013904223) >>> 0;
- out[i] = 0.5 * Math.sin((2 * Math.PI * hz * i) / SAMPLE_RATE) + ((s / 0xffffffff) * 2 - 1) * noiseAmp;
- }
- };
+// Frame fillers for a scripted analyser: each produces a specific signal so we
+// can drive clarity and pitch frame-by-frame.
+const fillSine = (hz, amplitude = 0.5) => (out) => {
+ for (let i = 0; i < out.length; i++) out[i] = amplitude * Math.sin((2 * Math.PI * hz * i) / SAMPLE_RATE);
+};
+const fillSilence = () => (out) => out.fill(0);
+// A sine buried in seeded noise — clarity ≈ 0.81 at noiseAmp 0.3 (measured):
+// above holdClarity (0.6) but below acquireClarity (0.9), i.e. a "hold-band"
+// frame. Deterministic (fixed seed) so it never flakes.
+const fillMix = (hz, noiseAmp = 0.3, seed = 999) => (out) => {
+ let s = seed >>> 0;
+ for (let i = 0; i < out.length; i++) {
+ s = (1664525 * s + 1013904223) >>> 0;
+ out[i] = 0.5 * Math.sin((2 * Math.PI * hz * i) / SAMPLE_RATE) + ((s / 0xffffffff) * 2 - 1) * noiseAmp;
+ }
+};
- // Analyser that plays a scripted list of frame fillers in order, repeating the
- // LAST one once the script is exhausted (so the loop keeps running in a stable
- // terminal state while we wait for enough ticks to fire).
- const scriptedAnalyser = (fillers, { fftSize = 4096 } = {}) => {
- let i = 0;
- return {
- fftSize,
- context: { sampleRate: SAMPLE_RATE },
- getFloatTimeDomainData: (out) => {
- fillers[Math.min(i, fillers.length - 1)](out);
- i += 1;
- },
- };
+// Analyser that plays a scripted list of frame fillers in order, repeating the
+// LAST one once the script is exhausted (so the loop keeps running in a stable
+// terminal state).
+const scriptedAnalyser = (fillers, { fftSize = 4096 } = {}) => {
+ let i = 0;
+ return {
+ fftSize,
+ context: { sampleRate: SAMPLE_RATE },
+ getFloatTimeDomainData: (out) => {
+ fillers[Math.min(i, fillers.length - 1)](out);
+ i += 1;
+ },
};
+};
- // Concert frequencies used below.
- const A4 = 440;
- const AS4 = 440 * Math.pow(2, 1 / 12); // A♯4, a clean semitone up
- const A4_PLUS_55 = 440 * Math.pow(2, 55 / 1200); // +55¢ of A4 (inside the sticky band)
+// Concert frequencies used below.
+const A4 = 440;
+const AS4 = 440 * Math.pow(2, 1 / 12); // A♯4, a clean semitone up
+const centsOfA4 = (c) => 440 * Math.pow(2, c / 1200); // A4 detuned by `c` cents
- const runScript = async (fillers, opts, ms = 90) => {
+describe('createPitchTracker — hysteresis, hold, and sticky label', () => {
+ // Fake timers make the loop deterministic: with `intervalMs: 1` and the emit
+ // throttle OFF, advancing N ms fires exactly N ticks, each consuming one filler
+ // and emitting one update — so `updates[k]` is `fillers[k]`, with no dependence
+ // on wall-clock speed (the flake a real-timer wait would introduce on slow CI).
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ // Drive exactly `frames` ticks and return the emitted updates.
+ const runFrames = async (fillers, opts, frames) => {
const updates = [];
const tracker = createPitchTracker(scriptedAnalyser(fillers), {
intervalMs: 1,
onUpdate: (u) => updates.push(u),
...opts,
});
- await new Promise((r) => setTimeout(r, ms));
+ await vi.advanceTimersByTimeAsync(frames);
tracker.stop();
return updates;
};
@@ -266,27 +271,27 @@ describe('createPitchTracker — hysteresis, hold, and sticky label', () => {
it('a single interleaved unclear frame is HELD, not nulled — the smoother survives it', async () => {
// Acquire + settle on A4 (6 clear frames), one dropout frame, then A4 again.
const script = [...Array(6).fill(fillSine(A4)), fillSilence(), ...Array(6).fill(fillSine(A4))];
- const updates = await runScript(script, { releaseFrames: 3 });
+ const updates = await runFrames(script, { releaseFrames: 3 }, 13);
// The display never blanked: every frame kept a note.
expect(updates.every((u) => u.note !== null)).toBe(true);
- // The dropout frame was emitted as a HELD reading on the same note.
- const held = updates.filter((u) => u.held);
- expect(held.length).toBeGreaterThanOrEqual(1);
- expect(held.every((u) => u.note?.letter === 'A' && u.note?.octave === 4)).toBe(true);
+ // The dropout frame (index 6) was emitted as a HELD reading on the same note.
+ expect(updates[6]).toMatchObject({ held: true });
+ expect(updates[6].note).toMatchObject({ letter: 'A', octave: 4 });
});
it('hold-band frames update an acquired pitch but never acquire from silence', async () => {
// From silence: a run of hold-band frames (clarity ~0.81 < acquire 0.9) must
// NOT acquire — the readout stays blank.
- const fromSilence = await runScript(Array(12).fill(fillMix(A4)), {});
- expect(fromSilence.length).toBeGreaterThan(0);
+ const fromSilence = await runFrames(Array(12).fill(fillMix(A4)), {}, 12);
+ expect(fromSilence.length).toBe(12);
expect(fromSilence.every((u) => u.note === null)).toBe(true);
// Once acquired on clear frames, a hold-band frame keeps updating (it is
// clear-enough to HOLD, so it is emitted live — not as a held/coasting frame).
- const afterAcquire = await runScript(
+ const afterAcquire = await runFrames(
[...Array(6).fill(fillSine(A4)), ...Array(6).fill(fillMix(A4))],
{},
+ 12,
);
const holdBandLive = afterAcquire.filter(
(u) => u.note?.letter === 'A' && !u.held && u.clarity >= 0.6 && u.clarity < 0.9,
@@ -297,10 +302,10 @@ describe('createPitchTracker — hysteresis, hold, and sticky label', () => {
it('emits nulls only after the release window of consecutive unclear frames', async () => {
const RELEASE = 4;
const script = [...Array(6).fill(fillSine(A4)), ...Array(20).fill(fillSilence())];
- const updates = await runScript(script, { releaseFrames: RELEASE });
+ const updates = await runFrames(script, { releaseFrames: RELEASE }, 15);
const firstNull = updates.findIndex((u) => u.note === null);
- // A null eventually arrives, but only after acquisition + the release window.
- expect(firstNull).toBeGreaterThanOrEqual(6 + RELEASE);
+ // A null arrives only after acquisition (6 frames) + the release window (4).
+ expect(firstNull).toBe(6 + RELEASE);
// The RELEASE frames just before the first null are all HELD on A4…
const window = updates.slice(firstNull - RELEASE, firstNull);
expect(window.length).toBe(RELEASE);
@@ -311,39 +316,52 @@ describe('createPitchTracker — hysteresis, hold, and sticky label', () => {
});
it('keeps one sticky label while the pitch wanders ±55¢, reporting cents past ±50', async () => {
- // Settle on A4, then sustain +55¢ — inside the ±60¢ sticky band, so the label
- // must stay A4 while cents (relative to the held note) climb past +50.
- const script = [...Array(6).fill(fillSine(A4)), ...Array(12).fill(fillSine(A4_PLUS_55))];
- const updates = await runScript(script, {});
+ // Isolate the sticky band from EMA ramp lag (medianWindow 1 + emaAlpha 1 make
+ // the smoothed pitch equal the detected pitch each frame). Acquire on A4, then
+ // wander through ±55¢ — all inside the ±60¢ band, so the label stays A4 while
+ // cents (relative to the held note) pass the ±50 semitone edge.
+ const script = [
+ fillSine(A4), fillSine(A4),
+ fillSine(centsOfA4(55)), fillSine(centsOfA4(-55)),
+ fillSine(centsOfA4(52)), fillSine(centsOfA4(-50)),
+ fillSine(centsOfA4(48)), fillSine(centsOfA4(55)),
+ ];
+ const updates = await runFrames(script, { medianWindow: 1, emaAlpha: 1 }, 8);
const voiced = updates.filter((u) => u.note !== null);
- expect(voiced.length).toBeGreaterThan(0);
+ expect(voiced.length).toBe(8);
expect(voiced.every((u) => u.note.letter === 'A' && u.note.accidental === '' && u.note.octave === 4)).toBe(true);
// Cents are relative to the HELD note, so they exceed the ±50 semitone edge.
expect(voiced.some((u) => u.cents > 50)).toBe(true);
});
it('switches the label within a few frames on a clean semitone step', async () => {
- // Settle on A4, then step cleanly up to A♯4 (+100¢) — well past the sticky
- // band, so the label re-derives.
- const ACQUIRE = 6;
- const script = [...Array(ACQUIRE).fill(fillSine(A4)), ...Array(20).fill(fillSine(AS4))];
- const updates = await runScript(script, {}, 120);
+ // A clean +100¢ step blows past the ±60¢ band and re-derives — it must NOT be
+ // trapped by stickiness. With ramp lag removed (medianWindow 1 + emaAlpha 1)
+ // the step lands in one frame; the release smoothing is exercised separately.
+ const ACQUIRE = 2;
+ const script = [...Array(ACQUIRE).fill(fillSine(A4)), ...Array(4).fill(fillSine(AS4))];
+ const updates = await runFrames(script, { medianWindow: 1, emaAlpha: 1 }, 6);
// The final voiced reading is A♯4.
const voiced = updates.filter((u) => u.note !== null);
- const last = voiced[voiced.length - 1];
- expect(last.note).toMatchObject({ letter: 'A', accidental: '#', octave: 4 });
+ expect(voiced[voiced.length - 1].note).toMatchObject({ letter: 'A', accidental: '#', octave: 4 });
// …and it switched promptly — within a few frames of the step, not stuck on A4.
const firstSharp = updates.findIndex((u) => u.note?.accidental === '#');
expect(firstSharp).toBeGreaterThanOrEqual(ACQUIRE);
- expect(firstSharp - ACQUIRE).toBeLessThanOrEqual(12);
+ expect(firstSharp - ACQUIRE).toBeLessThanOrEqual(3);
+ });
+});
+
+describe('createPitchTracker — emit throttle', () => {
+ const steady = () => ({
+ fftSize: 4096,
+ context: { sampleRate: SAMPLE_RATE },
+ getFloatTimeDomainData: (out) => { for (let i = 0; i < out.length; i++) out[i] = 0.5 * Math.sin((2 * Math.PI * A4 * i) / SAMPLE_RATE); },
});
it('throttles emits to ~updateHz for a steady tone (vs every frame unthrottled)', async () => {
- const steady = () => ({
- fftSize: 4096,
- context: { sampleRate: SAMPLE_RATE },
- getFloatTimeDomainData: (out) => { for (let i = 0; i < out.length; i++) out[i] = 0.5 * Math.sin((2 * Math.PI * A4 * i) / SAMPLE_RATE); },
- });
+ // Real timers here: the throttle keys on wall-clock time (performance.now), so
+ // this asserts a robust inequality (throttled ≪ unthrottled) rather than an
+ // exact count.
const unthrottled = [];
const throttled = [];
const t1 = createPitchTracker(steady(), { intervalMs: 1, onUpdate: (u) => unthrottled.push(u) });
@@ -352,7 +370,7 @@ describe('createPitchTracker — hysteresis, hold, and sticky label', () => {
t1.stop();
t2.stop();
// A steady note has no material change after acquisition, so the throttle caps
- // the ~12Hz stream far below the per-frame (~1kHz here) unthrottled stream.
+ // the ~12Hz stream far below the per-frame unthrottled stream.
expect(throttled.length).toBeGreaterThanOrEqual(1);
expect(unthrottled.length).toBeGreaterThan(throttled.length);
expect(throttled.length).toBeLessThanOrEqual(6);