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

feat: add a progress bar to ChiptunePanel's preview loop (#3394)

[._.]/ Adam Eivy66d0840076e8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0774a3783a..151b5b5d87 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,7 @@
## Changed
+- **The chiptune preview loop now shows where it is.** `ChiptunePanel`'s Play/Stop row gained a thin progress bar and elapsed/total timecode for the 15–30s loop, driven by a requestAnimationFrame clock that reads the player's transport position and paints straight into the DOM (no per-frame React render). `createChiptunePlayer` exposes `position()` + `loopSec()` for it — the length of the schedule actually sounding, so a mid-preview regeneration can't re-scale the bar against a loop nobody is hearing yet.
- **"Does this process own the agent?" is now one named predicate.** Ownership is split across `activeAgents` and `runnerAgents` by spawn mode, and which map an agent lands in isn't guessable from its `executionMode` — a `runner-tui` agent is driven locally and registers in `activeAgents` even though the runner owns its process and lists it. That implicit protocol was open-coded at two call sites, one of which had it wrong (above). `isAgentOwnedLocally` in `agentState.js` now owns the invariant, and `syncRunnerAgents` + `cleanupOrphanedAgents` both call it.
- `handleAgentCompletion` bails when the persisted record is already terminal — the same check its post-restart branch has always had — so any double-completion path is a no-op rather than a clobbering re-finalize.
- `agentLifecycle.js` imported `getAgent` aliased as `getAgentRecord`, shadowing the real transcript-free reader that was split out in #3368 for exactly this purpose. Both call sites read only `.status`/`.metadata`, but the alias made them hydrate the record: reading and line-splitting a completed run's whole `output.txt` (megabytes on a long TUI run) and potentially rewriting `metadata.json` via `repairCodexTaskSummary`. Now imports the real `getAgentRecord`, read once and shared.
diff --git a/client/src/components/music/ChiptunePanel.jsx b/client/src/components/music/ChiptunePanel.jsx
index f47ad94271..b4c283fe23 100644
--- a/client/src/components/music/ChiptunePanel.jsx
+++ b/client/src/components/music/ChiptunePanel.jsx
@@ -18,6 +18,7 @@ import useProviderModels from '../../hooks/useProviderModels';
import useMounted from '../../hooks/useMounted';
import ProviderModelSelector from '../ProviderModelSelector';
import { buildChiptuneSchedule, createChiptunePlayer } from '../../lib/chiptunePlayback.js';
+import { formatTimecode } from '../../utils/formatters';
import {
generateTrackChiptune, renderTrackChiptune, publishTrackChiptune,
getApps, getSettings, updateSettings,
@@ -67,6 +68,33 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix }) {
// Stop playback when the selected track changes or the panel unmounts.
useEffect(() => () => { playerRef.current?.stop(); setPlaying(false); }, [track?.id]);
+ // Preview playhead — painted straight into the DOM by the rAF loop below, so
+ // the bar tracks at frame rate without re-rendering the panel 60x a second.
+ const progressRef = useRef(null);
+ const elapsedRef = useRef(null);
+
+ // rAF clock, mirroring PianoRoll's: animate while playing, paint one idle
+ // frame otherwise. Cancelled on stop (the effect re-runs) and on unmount.
+ useEffect(() => {
+ const paint = (fraction, sec) => {
+ if (progressRef.current) progressRef.current.style.transform = `scaleX(${fraction})`;
+ if (elapsedRef.current) elapsedRef.current.textContent = formatTimecode(sec);
+ };
+ if (!playing) { paint(0, 0); return undefined; }
+ let raf = 0;
+ const loop = () => {
+ const player = playerRef.current;
+ const loopSec = player.loopSec();
+ // position() is monotonic across loop passes and NEGATIVE during the
+ // transport's lead-in — clamp, then modulo onto the current pass.
+ const within = loopSec > 0 ? Math.max(0, player.position()) % loopSec : 0;
+ paint(loopSec > 0 ? within / loopSec : 0, within);
+ raf = requestAnimationFrame(loop);
+ };
+ raf = requestAnimationFrame(loop);
+ return () => cancelAnimationFrame(raf);
+ }, [playing]);
+
// Reseed the prompt + publish slug from the newly-selected track.
useEffect(() => {
setPrompt(track?.chiptunePrompt || '');
@@ -128,6 +156,7 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix }) {
patterns: Object.keys(score.patterns || {}).length,
order: (score.order || []).join(' '),
seconds: Math.round(totalSec * 10) / 10,
+ totalSec,
};
}, [score]);
@@ -312,6 +341,23 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix }) {
</button>
</div>
+ {/* Preview position. The bar is decorative (aria-hidden) — the
+ timecode beside it carries the same information as text. */}
+ <div className="flex items-center gap-2">
+ <div className="flex-1 h-1.5 rounded-full bg-port-border overflow-hidden" aria-hidden="true">
+ <div
+ ref={progressRef}
+ data-testid="chiptune-progress-bar"
+ className="h-full w-full origin-left bg-port-accent"
+ style={{ transform: 'scaleX(0)' }}
+ />
+ </div>
+ <span className="text-[11px] font-mono text-gray-500 tabular-nums whitespace-nowrap">
+ <span ref={elapsedRef} data-testid="chiptune-progress-time">0:00.00</span>
+ {' / '}{formatTimecode(summary.totalSec)}
+ </span>
+ </div>
+
{publishOpen ? (
<div className="space-y-2 border border-port-border rounded-lg p-2 bg-port-bg">
{apps.length === 0 ? (
diff --git a/client/src/components/music/ChiptunePanel.test.jsx b/client/src/components/music/ChiptunePanel.test.jsx
index e94c133b7b..c9dd56ddf7 100644
--- a/client/src/components/music/ChiptunePanel.test.jsx
+++ b/client/src/components/music/ChiptunePanel.test.jsx
@@ -1,8 +1,24 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import ChiptunePanel from './ChiptunePanel';
import * as api from '../../services/api';
+// The panel drives the real chiptune player, which needs WebAudio (absent in
+// jsdom). Stub only the PLAYER — the pure schedule build stays real, since the
+// summary line and the loop-length readout are derived from it — with a
+// hand-driven transport so the preview playhead is assertable.
+const audio = vi.hoisted(() => ({ playing: false, position: 0, loopSec: 0 }));
+vi.mock('../../lib/chiptunePlayback.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ createChiptunePlayer: () => ({
+ play: async () => { audio.playing = true; },
+ stop: () => { audio.playing = false; },
+ isPlaying: () => audio.playing,
+ position: () => audio.position,
+ loopSec: () => audio.loopSec,
+ }),
+}));
+
vi.mock('../../services/api', () => ({
generateTrackChiptune: vi.fn(),
renderTrackChiptune: vi.fn(),
@@ -44,6 +60,9 @@ const pending = () => new Promise(() => {});
describe('ChiptunePanel', () => {
beforeEach(() => {
vi.clearAllMocks();
+ audio.playing = false;
+ audio.position = 0;
+ audio.loopSec = 0;
api.getSettings.mockResolvedValue({ music: {} });
api.getApps.mockResolvedValue([GAME_APP]);
api.updateSettings.mockResolvedValue({});
@@ -128,4 +147,82 @@ describe('ChiptunePanel', () => {
);
});
});
+
+ // The preview playhead is painted by a rAF loop straight into the DOM (no
+ // per-frame setState) — stub requestAnimationFrame to a manual queue so each
+ // frame() runs exactly one frame and the assertions read the painted nodes.
+ describe('preview progress bar', () => {
+ let rafQueue;
+ let cancelSpy;
+ const frame = () => {
+ const q = rafQueue;
+ rafQueue = [];
+ act(() => { q.forEach((cb) => cb()); });
+ };
+
+ beforeEach(() => {
+ rafQueue = [];
+ cancelSpy = vi.fn();
+ vi.stubGlobal('requestAnimationFrame', (cb) => { rafQueue.push(cb); return rafQueue.length; });
+ vi.stubGlobal('cancelAnimationFrame', cancelSpy);
+ });
+ afterEach(() => { vi.unstubAllGlobals(); });
+
+ const startPreview = async () => {
+ const result = render(<ChiptunePanel track={TRACK} onTrackUpdate={vi.fn()} />);
+ const playBtn = await screen.findByRole('button', { name: /preview loop/i });
+ await act(async () => { fireEvent.click(playBtn); });
+ await screen.findByRole('button', { name: /^stop$/i });
+ return result;
+ };
+
+ it('tracks the playhead across a loop pass and wraps on the next one', async () => {
+ audio.loopSec = 20;
+ await startPreview();
+ const bar = screen.getByTestId('chiptune-progress-bar');
+
+ audio.position = 5;
+ frame();
+ expect(bar.style.transform).toBe('scaleX(0.25)');
+ expect(screen.getByTestId('chiptune-progress-time')).toHaveTextContent('0:05.00');
+
+ // Second pass: position() keeps climbing (the player re-bases its cursor
+ // rather than restarting), so the bar must wrap, not run off the end.
+ audio.position = 25;
+ frame();
+ expect(bar.style.transform).toBe('scaleX(0.25)');
+ expect(screen.getByTestId('chiptune-progress-time')).toHaveTextContent('0:05.00');
+ });
+
+ it('clamps the transport lead-in (negative position) to the start of the bar', async () => {
+ audio.loopSec = 20;
+ await startPreview();
+
+ audio.position = -0.08;
+ frame();
+ expect(screen.getByTestId('chiptune-progress-bar').style.transform).toBe('scaleX(0)');
+ });
+
+ it('cancels the frame loop and resets the bar on stop', async () => {
+ audio.loopSec = 20;
+ await startPreview();
+ audio.position = 10;
+ frame();
+ expect(screen.getByTestId('chiptune-progress-bar').style.transform).toBe('scaleX(0.5)');
+
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /^stop$/i })); });
+ expect(cancelSpy).toHaveBeenCalled();
+ expect(screen.getByTestId('chiptune-progress-bar').style.transform).toBe('scaleX(0)');
+ expect(screen.getByTestId('chiptune-progress-time')).toHaveTextContent('0:00.00');
+ });
+
+ it('cancels the frame loop on unmount while playing', async () => {
+ audio.loopSec = 20;
+ const { unmount } = await startPreview();
+ frame();
+ cancelSpy.mockClear();
+ unmount();
+ expect(cancelSpy).toHaveBeenCalled();
+ });
+ });
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d4fc9a2ae4..890e320614 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -123,7 +123,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
| `chordShapes.js` | Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). `getChordVoicing(name, instrument)` → guitar `{ frets: [6 × (-1/0/n)], baseFret, bass }`, ukulele (4-string GCEA, exact lowest-position search), or piano `{ notes: ['A','C','E'], bass }` with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by `baseFret` (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry `bass` separately. `parseChordName(name)`, `splitJoinedChords('Am-Am7')`, `toVoicingInstrument(songInstrument)`, `VOICING_INSTRUMENTS`. Reuses `tabNotation.js`'s `CHORD_TOKEN_RE`/`NOTE_TO_PC`/`spellPitchClass` (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws. |
| `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. |
-| `chiptunePlayback.js` | Looping WebAudio preview for LLM-generated chiptune scores (#2911) — `buildChiptuneSchedule(score)` (pure pattern/order → absolute-time flatten, MIRRORS `server/lib/chiptuneScore.js` timing semantics), `parseChiptunePitch("C5")` → MIDI, and `createChiptunePlayer(getScore, { onLoop })` — a seamless-loop player over `createLookaheadTransport` (pulse-duty via PeriodicWave, triangle bass, noise-buffer/sine-sweep drums). No React — `ChiptunePanel` drives it. |
+| `chiptunePlayback.js` | Looping WebAudio preview for LLM-generated chiptune scores (#2911) — `buildChiptuneSchedule(score)` (pure pattern/order → absolute-time flatten, MIRRORS `server/lib/chiptuneScore.js` timing semantics), `parseChiptunePitch("C5")` → MIDI, and `createChiptunePlayer(getScore, { onLoop })` — a seamless-loop player over `createLookaheadTransport` (pulse-duty via PeriodicWave, triangle bass, noise-buffer/sine-sweep drums), exposing `position()` (monotonic across loop passes) + `loopSec()` for playhead UIs. No React — `ChiptunePanel` drives it. |
| `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |
| `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
diff --git a/client/src/lib/chiptunePlayback.js b/client/src/lib/chiptunePlayback.js
index 8da568d8e3..653423045f 100644
--- a/client/src/lib/chiptunePlayback.js
+++ b/client/src/lib/chiptunePlayback.js
@@ -165,7 +165,10 @@ function scheduleChipVoice(c, ev, startAt, destination, waveCache) {
*
* @param {() => object|null} getScore — returns the current score (or null)
* @param {{ onLoop?: (loopCount:number) => void }} [callbacks]
- * @returns {{ play, stop, isPlaying }}
+ * @returns {{ play, stop, isPlaying, position, loopSec }} — `position()` is the
+ * elapsed preview time in seconds, MONOTONIC across loop passes (the cursor
+ * re-bases rather than restarting), and `loopSec()` the exact length of one
+ * pass, so a UI renders the per-pass playhead as `position() % loopSec()`.
*/
export function createChiptunePlayer(getScore, { onLoop } = {}) {
let schedule = null;
@@ -213,5 +216,15 @@ export function createChiptunePlayer(getScore, { onLoop } = {}) {
},
});
- return { play: transport.play, stop: transport.stop, isPlaying: transport.isPlaying };
+ return {
+ play: transport.play,
+ stop: transport.stop,
+ isPlaying: transport.isPlaying,
+ position: transport.position,
+ // The length of the schedule that is actually SOUNDING (built at play()),
+ // not of the caller's current score — a regeneration mid-preview must not
+ // re-scale a playhead against a loop nobody is hearing yet. 0 before the
+ // first play.
+ loopSec: () => (schedule ? schedule.totalSec : 0),
+ };
}