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

address review (codex): sync album/track membership + validate track audioFilename

[._.]/ Adam Eivy7f5b70a25770
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
index 6e61e0132c..12199e328b 100644
--- a/client/src/components/music/TracksManager.jsx
+++ b/client/src/components/music/TracksManager.jsx
@@ -19,7 +19,7 @@ import { formatTimecode } from '../../utils/formatters';
import ArtistPicker from './ArtistPicker';
import {
listTracks, createTrack, updateTrack, deleteTrack,
- uploadTrackAudio, attachTrackAudio, clearTrackAudio, listMusicLibrary,
+ uploadTrackAudio, attachTrackAudio, clearTrackAudio, listMusicLibrary, listAlbums,
TRACK_TITLE_MAX, TRACK_LYRICS_MAX, TRACK_PROMPT_MAX,
} from '../../services/api';
@@ -28,11 +28,12 @@ const AUDIO_MAX_BYTES = 50 * 1024 * 1024;
const AUDIO_SRC = (filename) => `/data/music/${encodeURIComponent(filename)}`;
const emptyForm = () => ({
- title: '', artistId: '', artist: '', lyrics: '', prompt: '', audioFilename: '',
+ title: '', albumId: '', artistId: '', artist: '', lyrics: '', prompt: '', audioFilename: '',
});
const formFromTrack = (t) => ({
title: t.title || '',
+ albumId: t.albumId || '',
artistId: t.artistId || '',
artist: t.artist || '',
lyrics: t.lyrics || '',
@@ -60,12 +61,18 @@ export default function TracksManager() {
const [uploading, setUploading] = useState(false);
const [libraryOpen, setLibraryOpen] = useState(false);
const [library, setLibrary] = useState([]);
+ const [albums, setAlbums] = useState([]);
const fileInputRef = useRef(null);
useEffect(() => {
- listTracks()
- .then((list) => setTracks(Array.isArray(list) ? list : []))
- .catch((err) => toast.error(err.message || 'Failed to load tracks'))
+ Promise.all([
+ listTracks().catch((err) => { toast.error(err.message || 'Failed to load tracks'); return []; }),
+ listAlbums({ silent: true }).catch(() => []),
+ ])
+ .then(([trackList, albumList]) => {
+ setTracks(Array.isArray(trackList) ? trackList : []);
+ setAlbums(Array.isArray(albumList) ? albumList : []);
+ })
.finally(() => setLoading(false));
}, []);
@@ -244,6 +251,22 @@ export default function TracksManager() {
onChange={(artistId, artist) => setForm((f) => ({ ...f, artistId, artist }))}
/>
</Field>
+ <Field label="Album" hint="Optional — none means a standalone single. Saving syncs the album's tracklist.">
+ <select
+ id="track-album"
+ value={form.albumId}
+ onChange={(e) => setForm((f) => ({ ...f, albumId: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
+ >
+ <option value="">— Single (no album) —</option>
+ {albums.map((a) => (
+ <option key={a.id} value={a.id}>{a.title}</option>
+ ))}
+ {form.albumId && !albums.some((a) => a.id === form.albumId) ? (
+ <option value={form.albumId}>Linked album (unavailable)</option>
+ ) : null}
+ </select>
+ </Field>
<Field label="Prompt" hint="Text/style prompt for generation (used by the upcoming on-device generators).">
<textarea
value={form.prompt}
diff --git a/server/routes/albums.js b/server/routes/albums.js
index 1bced12b46..38cf09c35d 100644
--- a/server/routes/albums.js
+++ b/server/routes/albums.js
@@ -16,6 +16,7 @@ import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import * as albums from '../services/albums/index.js';
+import * as tracks from '../services/tracks/index.js';
const router = Router();
@@ -51,13 +52,44 @@ const patchSchema = z.object({
trackIds: trackIdsField.optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
+// Membership single-source-of-truth reconcile. The album's `trackIds` carry the
+// ORDER; each track's `albumId` is the membership pointer the Tracks API reports.
+// After an album write, stamp `albumId` on its member tracks and clear it on any
+// track that used to belong to this album but was dropped — so the two views
+// never disagree (a track removed from the album stops reporting that albumId,
+// and an added track starts). Best-effort per track: a missing/deleted track id
+// in `trackIds` is simply skipped (updateTrack 404s are swallowed). Runs after
+// the album persists so a rejected album write doesn't mutate track membership.
+async function reconcileAlbumMembership(album) {
+ const desired = new Set(album.trackIds || []);
+ const all = await tracks.listTracks().catch(() => []);
+ const ops = [];
+ // Clear albumId on tracks that point here but are no longer listed.
+ for (const t of all) {
+ if (t.albumId === album.id && !desired.has(t.id)) {
+ ops.push(tracks.updateTrack(t.id, { albumId: '' }).catch(() => {}));
+ }
+ }
+ // Stamp albumId on listed tracks that don't already point here.
+ const byId = new Map(all.map((t) => [t.id, t]));
+ for (const id of desired) {
+ const t = byId.get(id);
+ if (t && t.albumId !== album.id) {
+ ops.push(tracks.updateTrack(id, { albumId: album.id }).catch(() => {}));
+ }
+ }
+ await Promise.all(ops);
+}
+
router.get('/', asyncHandler(async (_req, res) => {
res.json(await albums.listAlbums());
}));
router.post('/', asyncHandler(async (req, res) => {
const body = validateRequest(createSchema, req.body ?? {});
- res.status(201).json(await albums.createAlbum(body));
+ const album = await albums.createAlbum(body);
+ await reconcileAlbumMembership(album);
+ res.status(201).json(album);
}));
router.get('/:id', asyncHandler(async (req, res) => {
@@ -68,11 +100,18 @@ router.get('/:id', asyncHandler(async (req, res) => {
router.patch('/:id', asyncHandler(async (req, res) => {
const body = validateRequest(patchSchema, req.body ?? {});
- res.json(await albums.updateAlbum(req.params.id, body));
+ const album = await albums.updateAlbum(req.params.id, body);
+ // Only reconcile when the membership list was part of this write.
+ if ('trackIds' in body) await reconcileAlbumMembership(album);
+ res.json(album);
}));
router.delete('/:id', asyncHandler(async (req, res) => {
- res.json(await albums.deleteAlbum(req.params.id));
+ const result = await albums.deleteAlbum(req.params.id);
+ // Orphan the album's tracks (clear their albumId) so they revert to singles
+ // rather than pointing at a tombstoned album.
+ await reconcileAlbumMembership({ id: req.params.id, trackIds: [] });
+ res.json(result);
}));
export default router;
diff --git a/server/routes/albums.test.js b/server/routes/albums.test.js
index d9285a6abf..bcee7a665d 100644
--- a/server/routes/albums.test.js
+++ b/server/routes/albums.test.js
@@ -16,12 +16,18 @@ vi.mock('../services/albums/index.js', () => ({
ALBUM_ID_RE: /^album-/,
listAlbums: vi.fn(async () => [{ id: 'album-1', title: 'Debut' }]),
getAlbum: vi.fn(),
- createAlbum: vi.fn(async (input) => ({ id: 'album-new', ...input })),
- updateAlbum: vi.fn(async (id, patch) => ({ id, ...patch })),
+ createAlbum: vi.fn(async (input) => ({ id: 'album-new', trackIds: [], ...input })),
+ updateAlbum: vi.fn(async (id, patch) => ({ id, trackIds: [], ...patch })),
deleteAlbum: vi.fn(async (id) => ({ id })),
}));
+vi.mock('../services/tracks/index.js', () => ({
+ listTracks: vi.fn(async () => []),
+ updateTrack: vi.fn(async (id, patch) => ({ id, ...patch })),
+}));
+
import * as albums from '../services/albums/index.js';
+import * as tracks from '../services/tracks/index.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import albumsRoutes from './albums.js';
@@ -82,4 +88,30 @@ describe('albums routes', () => {
expect(r.status).toBe(200);
expect(r.body).toEqual({ id: 'album-1' });
});
+
+ it('PATCH /:id with trackIds reconciles track.albumId (stamp added, clear removed)', async () => {
+ // The album will list track-1 + track-2; track-3 used to belong here and
+ // must be cleared, track-1 already points here (no-op), track-2 is added.
+ tracks.listTracks.mockResolvedValueOnce([
+ { id: 'track-1', albumId: 'album-1' },
+ { id: 'track-2', albumId: '' },
+ { id: 'track-3', albumId: 'album-1' },
+ ]);
+ const r = await request(app).patch('/api/albums/album-1').send({ trackIds: ['track-1', 'track-2'] });
+ expect(r.status).toBe(200);
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-3', { albumId: '' });
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-2', { albumId: 'album-1' });
+ expect(tracks.updateTrack).not.toHaveBeenCalledWith('track-1', expect.anything());
+ });
+
+ it('PATCH /:id WITHOUT trackIds does not reconcile membership', async () => {
+ await request(app).patch('/api/albums/album-1').send({ genre: 'jazz' });
+ expect(tracks.listTracks).not.toHaveBeenCalled();
+ });
+
+ it('DELETE /:id orphans the album\'s tracks (clears their albumId)', async () => {
+ tracks.listTracks.mockResolvedValueOnce([{ id: 'track-9', albumId: 'album-1' }]);
+ await request(app).delete('/api/albums/album-1');
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-9', { albumId: '' });
+ });
});
diff --git a/server/routes/tracks.js b/server/routes/tracks.js
index 7e53024222..16b7b4085b 100644
--- a/server/routes/tracks.js
+++ b/server/routes/tracks.js
@@ -24,6 +24,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { uploadSingle } from '../lib/multipart.js';
import * as tracks from '../services/tracks/index.js';
+import * as albums from '../services/albums/index.js';
import {
listMusicLibrary, importUploadedTrack, statMusicTrack,
isSupportedMusicUpload, assertSafeMusicFilename, MUSIC_UPLOAD_MAX_BYTES,
@@ -39,7 +40,19 @@ const lyricsField = z.string().trim().max(tracks.LYRICS_MAX);
const promptField = z.string().trim().max(tracks.PROMPT_MAX);
const engineField = z.string().trim().max(tracks.ENGINE_MAX);
const modelIdField = z.string().trim().max(tracks.MODEL_ID_MAX);
-const audioFilenameField = z.string().trim().max(tracks.AUDIO_FILENAME_MAX);
+// On the generic save path, `audioFilename` must be a bare, safe music-library
+// basename — same guard `/audio/attach` enforces — so a direct POST/PATCH can't
+// persist a path-ish (`../x.mp3`) or wrong-extension pointer that the player
+// would later render. '' is allowed (clears the pointer). Existence is NOT
+// checked here (a create may set the name before the file lands); the dedicated
+// attach route verifies the file is in the library.
+const audioFilenameField = z.string().trim().max(tracks.AUDIO_FILENAME_MAX).refine(
+ (v) => {
+ if (v === '') return true;
+ try { assertSafeMusicFilename(v); return true; } catch { return false; }
+ },
+ { message: 'audioFilename must be a bare music-library filename (mp3/wav/m4a/ogg/flac), no path separators' },
+);
const durationField = z.number().int().min(tracks.DURATION_MIN_SEC).max(tracks.DURATION_MAX_SEC).nullable();
const createSchema = z.object({
@@ -94,6 +107,29 @@ async function requireTrack(id) {
return track;
}
+// Membership reconcile, track→album direction (the inverse of the album route's
+// reconcileAlbumMembership). When a track's `albumId` changes, append it to the
+// new album's ordered `trackIds` (if absent) and drop it from the previous
+// album's list — so `track.albumId` (the membership truth) and `album.trackIds`
+// (the order) never disagree. Calls the album SERVICE directly (not the album
+// ROUTE) so this can't re-enter the album route's track-side reconcile and loop.
+// Best-effort: a missing/deleted album id is skipped.
+async function reconcileTrackAlbum(trackId, prevAlbumId, nextAlbumId) {
+ if (prevAlbumId === nextAlbumId) return;
+ if (prevAlbumId) {
+ const prev = await albums.getAlbum(prevAlbumId).catch(() => null);
+ if (prev && (prev.trackIds || []).includes(trackId)) {
+ await albums.updateAlbum(prevAlbumId, { trackIds: prev.trackIds.filter((id) => id !== trackId) }).catch(() => {});
+ }
+ }
+ if (nextAlbumId) {
+ const next = await albums.getAlbum(nextAlbumId).catch(() => null);
+ if (next && !(next.trackIds || []).includes(trackId)) {
+ await albums.updateAlbum(nextAlbumId, { trackIds: [...(next.trackIds || []), trackId] }).catch(() => {});
+ }
+ }
+}
+
router.get('/', asyncHandler(async (_req, res) => {
res.json(await tracks.listTracks());
}));
@@ -107,7 +143,9 @@ router.get('/library', asyncHandler(async (_req, res) => {
router.post('/', asyncHandler(async (req, res) => {
const body = validateRequest(createSchema, req.body ?? {});
- res.status(201).json(await tracks.createTrack(body));
+ const track = await tracks.createTrack(body);
+ if (track.albumId) await reconcileTrackAlbum(track.id, '', track.albumId);
+ res.status(201).json(track);
}));
router.get('/:id', asyncHandler(async (req, res) => {
@@ -116,11 +154,19 @@ router.get('/:id', asyncHandler(async (req, res) => {
router.patch('/:id', asyncHandler(async (req, res) => {
const body = validateRequest(patchSchema, req.body ?? {});
- res.json(await tracks.updateTrack(req.params.id, body));
+ const prev = await requireTrack(req.params.id);
+ const track = await tracks.updateTrack(req.params.id, body);
+ if ('albumId' in body) await reconcileTrackAlbum(track.id, prev.albumId, track.albumId);
+ res.json(track);
}));
router.delete('/:id', asyncHandler(async (req, res) => {
- res.json(await tracks.deleteTrack(req.params.id));
+ const prev = await tracks.getTrack(req.params.id).catch(() => null);
+ const result = await tracks.deleteTrack(req.params.id);
+ // Drop the deleted track from its album's ordered list so the album doesn't
+ // render a dangling (missing) entry.
+ if (prev?.albumId) await reconcileTrackAlbum(req.params.id, prev.albumId, '');
+ res.json(result);
}));
// Upload an audio file into the shared library and attach it to this track.
diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.js
index 4608ff01bc..dad755912e 100644
--- a/server/routes/tracks.test.js
+++ b/server/routes/tracks.test.js
@@ -35,7 +35,13 @@ vi.mock('../services/pipeline/musicLibrary.js', () => ({
}));
import * as tracks from '../services/tracks/index.js';
+vi.mock('../services/albums/index.js', () => ({
+ getAlbum: vi.fn(async () => null),
+ updateAlbum: vi.fn(async (id, patch) => ({ id, ...patch })),
+}));
+
import * as musicLibrary from '../services/pipeline/musicLibrary.js';
+import * as albums from '../services/albums/index.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import tracksRoutes from './tracks.js';
@@ -71,6 +77,37 @@ describe('tracks routes', () => {
expect(r.body.id).toBe('track-new');
});
+ it('POST / rejects a path-ish audioFilename (same guard as /audio/attach)', async () => {
+ const r = await request(app).post('/api/tracks').send({ title: 'Intro', audioFilename: '../escape.mp3' });
+ expect(r.status).toBe(400);
+ expect(tracks.createTrack).not.toHaveBeenCalled();
+ });
+
+ it('POST / accepts an empty audioFilename (clears the pointer)', async () => {
+ const r = await request(app).post('/api/tracks').send({ title: 'Intro', audioFilename: '' });
+ expect(r.status).toBe(201);
+ });
+
+ it('POST / with albumId appends the track to the album tracklist', async () => {
+ albums.getAlbum.mockResolvedValueOnce({ id: 'album-1', trackIds: ['track-0'] });
+ tracks.createTrack.mockResolvedValueOnce({ id: 'track-new', title: 'Intro', albumId: 'album-1' });
+ const r = await request(app).post('/api/tracks').send({ title: 'Intro', albumId: 'album-1' });
+ expect(r.status).toBe(201);
+ expect(albums.updateAlbum).toHaveBeenCalledWith('album-1', { trackIds: ['track-0', 'track-new'] });
+ });
+
+ it('PATCH /:id moving albums drops from the old tracklist and appends to the new', async () => {
+ tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Intro', albumId: 'album-old' });
+ tracks.updateTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Intro', albumId: 'album-new' });
+ albums.getAlbum.mockImplementation(async (id) => (
+ id === 'album-old' ? { id, trackIds: ['track-1'] } : { id, trackIds: [] }
+ ));
+ const r = await request(app).patch('/api/tracks/track-1').send({ albumId: 'album-new' });
+ expect(r.status).toBe(200);
+ expect(albums.updateAlbum).toHaveBeenCalledWith('album-old', { trackIds: [] });
+ expect(albums.updateAlbum).toHaveBeenCalledWith('album-new', { trackIds: ['track-1'] });
+ });
+
it('POST / rejects a missing title', async () => {
expect((await request(app).post('/api/tracks').send({ engine: 'x' })).status).toBe(400);
expect(tracks.createTrack).not.toHaveBeenCalled();