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

fix: schedule CyberCity music on the audio clock instead of two drifting intervals (#3396)

[._.]/ Adam Eivy6e37406ad688
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9a8ba2e2ed..18c8665696 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,7 @@
## Fixed
+- **[issue-3396] CyberCity's ambient music no longer drifts under main-thread load.** The chord changes (every 2400ms) and the 16th-note arp plucks (every 150ms) rode two independent `setInterval`s that each read `ctx.currentTime` at fire time — so under load both drifted against the audio clock *and* against each other, the failure mode the sibling synth players adopted the shared lookahead scheduler to avoid. Both now come off one 16th-note step counter (16 steps per chord, so the arp is phase-locked to the chord changes by construction) and every event is written to the audio clock at an absolute grid time, `gridOrigin + step × 0.15s`, which cannot accumulate drift. The timing constants come from `SYNTH_TIMING` in `lib/lookaheadTransport.js` so the feel stays shared; the transport body itself is deliberately not reused, because it reads its clock from the shared `lib/audioContext.js` singleton while `cityAudioEngine` is a documented holdout that owns (and closes) its own `AudioContext` — scheduling this graph against a clock it doesn't run on would be worse than the drift. A backgrounded tab now re-anchors to the grid on return instead of dumping every missed step into one burst. Generative behavior (chord walk, mood sets, energy-driven arp gain) and the stop-ramp contract are unchanged.
- **[issue-3400] Rendering two storyboard scenes at once no longer loses one of the jobs.** `enqueueStoryboardSceneVideo`, `enqueueStoryboardShotStartFrame`, and `refineStoryboardScenePrompt` each read `stages.storyboards.scenes` up front, then wrote the whole pre-read array back through `updateStage`. That write *is* serialized, but the array it shallow-merges was built outside the lock — so two enqueues for different scenes that both read before either wrote would revert each other's freshly-stamped `sceneVideoJobId` / `startFrameJobId`, and the losing render would run to completion with nothing left pointing at it. All three now patch a single scene through `updateStageWithLatest`, so the read-modify-write of `scenes` happens inside the write region and only the targeted index is replaced. A scene that disappeared between the caller's read and the write now 404s instead of resurrecting itself.
- **[issue-3407] Stacker News sync works again.** Stacker News renamed its territory listing route from `/recent` to `/new`, so every browser-transport sync was refused with "landed on a different page than the one requested" — the redirect guard correctly caught the rename. Syncs now request the new route directly; the guard stays strict.
- **A completed TUI agent could be recorded as failed by a duplicate finalize.** `cleanupOrphanedAgents` runs every 15 minutes and calls `syncRunnerAgents`, which only checked `runnerAgents` for "already tracked" — but a runner-backed TUI agent is owned by the live `spawnTuiAgent` closure, which registers in `activeAgents` and never in `runnerAgents`. Any TUI run outliving one health-check tick was therefore hoisted into `runnerAgents` mid-flight, so the `agent:completed` event the runner emits when the TUI spawner's own `finish()` kills the session slipped past the `if (!agent) return` guard and ran a *second* `finalizeAgent`. That overwrote a sentinel-signalled success with `success: false, exitCode: 143` plus a bogus `startup-failure` analysis (computed from an output buffer that path can't read — a TUI writes `output.txt` under the dated run dir, not `AGENTS_DIR/<id>`), which in turn flipped the agent card to Failed and requeued the already-finished task as `pending`. Observed on a 55-minute release-check run that had already published v2.37.0 and merged all three of its PRs.
diff --git a/client/src/components/city/audio/citySynthMusic.js b/client/src/components/city/audio/citySynthMusic.js
index 118e748521..044eb6059b 100644
--- a/client/src/components/city/audio/citySynthMusic.js
+++ b/client/src/components/city/audio/citySynthMusic.js
@@ -1,12 +1,45 @@
-// Procedural ambient synthwave using Web Audio oscillators
+// Procedural ambient synthwave using Web Audio oscillators.
+//
+// Scheduling follows the "two clocks" pattern the sibling synth players use (see
+// lib/metronome.js:3-6 and lib/lookaheadTransport.js): a coarse setInterval
+// *lookahead* timer wakes every LOOKAHEAD_MS and hands every note event falling
+// inside the next SCHEDULE_AHEAD window to the AudioContext clock at an ABSOLUTE
+// time. Previously the chord changes (2400ms) and arp plucks (150ms) rode two
+// independent setIntervals that read ctx.currentTime at fire time, so both
+// drifted under main-thread load and drifted apart from each other.
+//
+// It does NOT reuse createLookaheadTransport, deliberately: that transport reads
+// its clock from the shared lib/audioContext.js singleton with no injection
+// point, while cityAudioEngine is a documented holdout that owns its own
+// AudioContext (and close()s it on unmount). Driving this graph from the shared
+// context's currentTime would mean scheduling against a clock the graph doesn't
+// run on. The transport also models a finite piece (total length, pause/seek/
+// position, per-note node teardown) — none of which an endless drone built from
+// long-lived oscillators has. What IS shared is the timing feel: SYNTH_TIMING.
import { getAudioContext, getMusicGain } from './cityAudioEngine';
import { CHORD_SETS } from '../../../utils/citySoundscape';
+import { SYNTH_TIMING } from '../../../lib/lookaheadTransport';
+
+const { LOOKAHEAD_MS, SCHEDULE_AHEAD } = SYNTH_TIMING;
+
+// The note grid: one 16th note every ARP_SEC (150ms at 100BPM), with a chord
+// change every CHORD_STEPS sixteenths (2.4s = 4 beats). Deriving both from ONE
+// step counter is what keeps the arp phase-locked to the chords — the previous
+// pair of independent timers could only stay aligned by luck.
+const ARP_SEC = 0.15;
+const CHORD_STEPS = 16;
let isPlaying = false;
let oscillators = [];
-let intervals = [];
let nodesCleanup = [];
+// Lookahead scheduler state. `gridOrigin` is the ctx time of step 0; every event
+// time is gridOrigin + step * ARP_SEC, so the grid can never accumulate drift.
+let schedulerTimer = null;
+let gridOrigin = 0;
+let nextStep = 1;
+let currentChordIdx = 0;
+
// Default chord progression (Am -> Em -> F -> C). The soundscape layer (roadmap 3.4) can swap
// this for the darker `tense` set via setSoundscape(); we keep a mutable pointer so the running
// chord interval reads whatever's current without re-scheduling.
@@ -26,6 +59,10 @@ let liveBassGain = null;
let livePadGain = null;
let liveArpGain = null;
+// Oscillators the scheduler retunes each step. Null while stopped.
+let liveBassOsc = null;
+let liveArpOsc = null;
+
// Arp note patterns (scale degrees relative to chord root)
const ARP_PATTERN = [0, 2, 4, 7, 12, 7, 4, 2];
@@ -48,6 +85,59 @@ export const setSoundscape = (params) => {
}
};
+// Advance to the next chord and glide the bass + pad onto it AT `when`. Reads
+// `activeChords` live so a soundscape mood-swap (bright↔tense) takes effect on
+// the next chord; the walk is incremental (not derived from the step index) so
+// swapping to a set of a different length can't jump the progression.
+const scheduleChordChange = (when) => {
+ const chords = activeChords;
+ currentChordIdx = (currentChordIdx + 1) % chords.length;
+ const chord = chords[currentChordIdx];
+ liveBassOsc.frequency.setTargetAtTime(chord[0], when, 0.3);
+ livePadOscs.forEach((osc, i) => {
+ osc.frequency.setTargetAtTime(chord[i] * 2, when, 0.3);
+ });
+};
+
+// One arp 16th note AT `when`. The pluck peaks at `liveArpPeak`, which the
+// soundscape raises with system energy (more active agents → a louder lead).
+const scheduleArpPluck = (step, when) => {
+ const chords = activeChords;
+ const chord = chords[currentChordIdx % chords.length];
+ const rootFreq = chord[0] * 4; // two octaves up
+ const semitone = ARP_PATTERN[(step - 1) % ARP_PATTERN.length];
+ const freq = rootFreq * Math.pow(2, semitone / 12);
+
+ liveArpOsc.frequency.setTargetAtTime(freq, when, 0.01);
+ // Short percussive envelope
+ liveArpGain.gain.setTargetAtTime(liveArpPeak, when, 0.005);
+ liveArpGain.gain.setTargetAtTime(0.0, when + 0.06, 0.04);
+};
+
+// One lookahead tick: schedule every step due inside the next SCHEDULE_AHEAD
+// window. Chord-first at a shared step so the pluck landing on the downbeat
+// already sounds the new chord.
+const scheduleWindow = () => {
+ const ctx = getAudioContext();
+ if (!isPlaying || !ctx) return;
+
+ // A backgrounded tab throttles this timer to once a second or worse. Without
+ // this, catching up would schedule every missed step at a time already in the
+ // past — Web Audio clamps those to "now", firing them as one burst. Re-anchor
+ // to whole steps instead, which keeps the grid phase (and so the arp/chord
+ // lock) while dropping the steps nobody was there to hear.
+ const behind = ctx.currentTime - (gridOrigin + nextStep * ARP_SEC);
+ if (behind > ARP_SEC) nextStep += Math.floor(behind / ARP_SEC);
+
+ const horizon = ctx.currentTime + SCHEDULE_AHEAD;
+ while (gridOrigin + nextStep * ARP_SEC < horizon) {
+ const when = gridOrigin + nextStep * ARP_SEC;
+ if (nextStep % CHORD_STEPS === 0) scheduleChordChange(when);
+ scheduleArpPluck(nextStep, when);
+ nextStep += 1;
+ }
+};
+
const createReverb = (ctx) => {
const convolver = ctx.createConvolver();
const rate = ctx.sampleRate;
@@ -91,7 +181,6 @@ export const startMusic = () => {
bassFilter.connect(output);
bassFilter.connect(reverb);
- let currentChordIdx = 0;
const bassOsc = ctx.createOscillator();
bassOsc.type = 'sawtooth';
bassOsc.frequency.value = activeChords[0][0];
@@ -151,49 +240,25 @@ export const startMusic = () => {
arpOsc.start();
oscillators.push(arpOsc);
- let arpStep = 0;
- // Chord change every 2.4s (4 beats at 100BPM). Reads `activeChords` live so a soundscape
- // mood-swap (bright↔tense) takes effect on the next chord without re-scheduling the interval.
- const chordInterval = setInterval(() => {
- if (!isPlaying) return;
- const chords = activeChords;
- currentChordIdx = (currentChordIdx + 1) % chords.length;
- const chord = chords[currentChordIdx];
- const now = ctx.currentTime;
- bassOsc.frequency.setTargetAtTime(chord[0], now, 0.3);
- padOscs.forEach((osc, i) => {
- osc.frequency.setTargetAtTime(chord[i] * 2, now, 0.3);
- });
- }, 2400);
- intervals.push(chordInterval);
-
- // Arp sixteenth notes at 100BPM = 150ms per step. The pluck peaks at `liveArpPeak`, which the
- // soundscape raises with system energy (more active agents → a louder, livelier lead).
- const arpInterval = setInterval(() => {
- if (!isPlaying) return;
- const chord = activeChords[currentChordIdx % activeChords.length];
- const rootFreq = chord[0] * 4; // two octaves up
- const semitone = ARP_PATTERN[arpStep % ARP_PATTERN.length];
- const freq = rootFreq * Math.pow(2, semitone / 12);
- const now = ctx.currentTime;
-
- arpOsc.frequency.setTargetAtTime(freq, now, 0.01);
- // Short percussive envelope
- arpGain.gain.setTargetAtTime(liveArpPeak, now, 0.005);
- arpGain.gain.setTargetAtTime(0.0, now + 0.06, 0.04);
-
- arpStep++;
- }, 150);
- intervals.push(arpInterval);
-
- // Expose the modulatable nodes so setSoundscape() can ramp them in real time.
+ // Expose the modulatable nodes so setSoundscape() and the scheduler can reach them.
liveBassFilter = bassFilter;
livePadOscs = padOscs;
liveBassGain = bassGain;
livePadGain = padGain;
liveArpGain = arpGain;
+ liveBassOsc = bassOsc;
+ liveArpOsc = arpOsc;
nodesCleanup.push(reverb, reverbGain, delay, delayFeedback, bassFilter, bassGain, padGain, arpFilter, arpGain);
+
+ // Anchor the note grid to the audio clock and start the lookahead timer. Chord
+ // index 0 is already sounding from the oscillator frequencies above, so the
+ // grid starts at step 1 — the first chord CHANGE lands on step CHORD_STEPS.
+ gridOrigin = ctx.currentTime;
+ nextStep = 1;
+ currentChordIdx = 0;
+ scheduleWindow();
+ schedulerTimer = setInterval(scheduleWindow, LOOKAHEAD_MS);
};
// Fade time constant for the pre-stop ramp (setTargetAtTime never truly reaches
@@ -215,6 +280,12 @@ const STOP_SETTLE = 0.08;
export const stopMusic = () => {
if (!isPlaying) return 0;
isPlaying = false;
+ // Stop the lookahead timer before the ramps below, so no further note events
+ // get scheduled onto a graph that is already fading out.
+ if (schedulerTimer != null) {
+ clearInterval(schedulerTimer);
+ schedulerTimer = null;
+ }
const ctx = getAudioContext();
const now = ctx ? ctx.currentTime : 0;
@@ -233,8 +304,6 @@ export const stopMusic = () => {
});
oscillators = [];
- intervals.forEach(clearInterval);
- intervals = [];
nodesCleanup = [];
// Drop references to the now-stopping nodes so a stray setSoundscape() can't ramp a
// dead graph. The next startMusic() re-captures fresh ones.
@@ -243,6 +312,8 @@ export const stopMusic = () => {
liveBassGain = null;
livePadGain = null;
liveArpGain = null;
+ liveBassOsc = null;
+ liveArpOsc = null;
// Disconnect after the ramp/stop settles instead of instantly — an immediate
// disconnect() would cut the fade above short, defeating the point of it.
diff --git a/client/src/components/city/audio/citySynthMusic.test.js b/client/src/components/city/audio/citySynthMusic.test.js
index 79bfa6abfc..71be0baf2f 100644
--- a/client/src/components/city/audio/citySynthMusic.test.js
+++ b/client/src/components/city/audio/citySynthMusic.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { CHORD_SETS } from '../../../utils/citySoundscape';
+import { SYNTH_TIMING } from '../../../lib/lookaheadTransport';
// Minimal fake Web Audio graph for citySynthMusic.js. The module pulls its
// context/output gain from cityAudioEngine's getAudioContext()/getMusicGain()
@@ -74,6 +76,46 @@ const makeFakeContext = () => {
// STOP_SETTLE = 0.08 (delay before the hard oscillator stop).
const STOP_RAMP_TC = 0.02;
const STOP_SETTLE = 0.08;
+// The note grid, likewise pinned from the source: one 16th every ARP_SEC, with
+// a chord change every CHORD_STEPS of them.
+const ARP_SEC = 0.15;
+const CHORD_STEPS = 16;
+const { LOOKAHEAD_MS } = SYNTH_TIMING;
+
+// The bass is the only sawtooth oscillator and the arp the only gain that
+// starts at 0 — identify both by that rather than by creation order, so
+// re-ordering the graph build can't silently point these assertions at the
+// wrong node.
+const bassOsc = () => fakeCtx.oscillators.find(o => o.type === 'sawtooth');
+const arpGain = () => fakeCtx.gains.find(g => g.gain.value === 0);
+
+// Drive both clocks forward together the way a browser does: every lookahead
+// tick also advances the audio clock. Scheduling asserts are meaningless if the
+// audio clock stands still while the timer fires.
+const runAudio = (seconds) => {
+ const ticks = Math.round((seconds * 1000) / LOOKAHEAD_MS);
+ for (let i = 0; i < ticks; i += 1) {
+ fakeCtx.now += LOOKAHEAD_MS / 1000;
+ vi.advanceTimersByTime(LOOKAHEAD_MS);
+ }
+};
+
+// Same, but with the timer firing at irregular points on the audio clock —
+// main-thread jank. This is the condition the old scheduling drifted under: a
+// note written at "whatever currentTime is right now" lands off the grid, while
+// a note written at an absolute grid time does not. The multipliers average
+// 1.0, so the two clocks stay in sync across each cycle and only the sampling
+// points jitter.
+const runAudioJanky = (seconds) => {
+ const jitter = [0.9, 1.6, 0.4, 1.3, 0.8];
+ let elapsed = 0;
+ for (let i = 0; elapsed < seconds; i += 1) {
+ const delta = (LOOKAHEAD_MS / 1000) * jitter[i % jitter.length];
+ fakeCtx.now += delta;
+ elapsed += delta;
+ vi.advanceTimersByTime(LOOKAHEAD_MS);
+ }
+};
let fakeCtx;
let fakeOutput;
@@ -176,6 +218,72 @@ describe('citySynthMusic', () => {
expect(fakeCtx.oscillators.length).toBe(firstOscCount * 2);
});
+ describe('lookahead scheduling (#3396)', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('schedules arp notes at absolute future times on the 16th grid, despite jank', () => {
+ synth.startMusic(); // gridOrigin = 0
+ runAudioJanky(0.5);
+
+ // Every pluck is a (peak, when) pair; the peak ramps are the note onsets.
+ const onsets = arpGain().gain.values
+ .filter(e => e.v !== 0)
+ .map(e => e.when);
+ expect(onsets.length).toBeGreaterThan(0);
+ // Exactly on the grid — n * ARP_SEC, never "whatever currentTime was".
+ onsets.forEach((when, i) => {
+ expect(when).toBeCloseTo((i + 1) * ARP_SEC, 10);
+ });
+ // And scheduled ahead of the clock, not at it.
+ expect(Math.max(...onsets)).toBeGreaterThan(fakeCtx.now);
+ });
+
+ it('changes chord exactly on the CHORD_STEPS boundary, phase-locked to the arp', () => {
+ synth.startMusic();
+ runAudioJanky(2.6); // just past step 16 (2.4s)
+
+ const chordChanges = bassOsc().frequency.values;
+ expect(chordChanges).toHaveLength(1);
+ expect(chordChanges[0].when).toBeCloseTo(CHORD_STEPS * ARP_SEC, 10);
+ // Walked to the next chord of the active (bright) set, not re-derived.
+ expect(chordChanges[0].v).toBe(CHORD_SETS.bright[1][0]);
+
+ // An arp pluck lands on that same instant — the two grids share one counter.
+ const onsets = arpGain().gain.values.filter(e => e.v !== 0).map(e => e.when);
+ expect(onsets.some(w => Math.abs(w - CHORD_STEPS * ARP_SEC) < 1e-9)).toBe(true);
+ });
+
+ it('stops scheduling once stopMusic clears the lookahead timer', () => {
+ synth.startMusic();
+ runAudio(0.5);
+ const scheduled = arpGain().gain.values.length;
+ expect(scheduled).toBeGreaterThan(0);
+
+ synth.stopMusic();
+ const afterStop = arpGain().gain.values.length; // includes the stop ramp
+ runAudio(2.0);
+ expect(arpGain().gain.values).toHaveLength(afterStop);
+ });
+
+ it('re-anchors instead of bursting after the tab is backgrounded', () => {
+ synth.startMusic();
+ runAudio(0.5);
+ const before = arpGain().gain.values.length;
+
+ // A throttled tab: 30s of audio clock passes with no timer tick.
+ fakeCtx.now += 30;
+ vi.advanceTimersByTime(LOOKAHEAD_MS);
+
+ // One window's worth of notes (a couple), not the ~200 missed steps.
+ const scheduledInBurst = arpGain().gain.values.length - before;
+ expect(scheduledInBurst).toBeLessThan(10);
+ // Still on the original grid phase, so the arp/chord lock survives.
+ const last = arpGain().gain.values.filter(e => e.v !== 0).at(-1).when;
+ expect(last / ARP_SEC).toBeCloseTo(Math.round(last / ARP_SEC), 6);
+ });
+ });
+
it('double-stop is safe: no throw and no double-schedule', () => {
synth.startMusic();
fakeCtx.now = 3;