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: resolve six DevSecOps audit findings

[._.]/ Adam Eivy35df8155d24d
diff --git a/client/src/components/Drawer.jsx b/client/src/components/Drawer.jsx
index 9d5d83bb58..17974b8006 100644
--- a/client/src/components/Drawer.jsx
+++ b/client/src/components/Drawer.jsx
@@ -107,7 +107,7 @@ export default function Drawer({
role="dialog"
aria-modal="true"
aria-label={title}
- className={`fixed inset-y-0 right-0 z-50 w-full ${resolvedWidth} bg-port-card border-l border-port-border shadow-2xl flex flex-col`}
+ className={`fixed inset-y-0 right-0 z-50 w-full max-w-full ${resolvedWidth} bg-port-card border-l border-port-border shadow-2xl flex flex-col`}
>
<header className="flex items-center justify-between px-4 py-3 border-b border-port-border">
<div className="min-w-0 pr-2">
diff --git a/client/src/components/wiki/tabs/BrowseTab.jsx b/client/src/components/wiki/tabs/BrowseTab.jsx
index 671a4001c0..a30ba2d321 100644
--- a/client/src/components/wiki/tabs/BrowseTab.jsx
+++ b/client/src/components/wiki/tabs/BrowseTab.jsx
@@ -11,6 +11,7 @@ import { WIKI_CATEGORIES } from '../constants.jsx';
import BrailleSpinner from '../../BrailleSpinner';
import OfflineNotesNotice from '../../OfflineNotesNotice.jsx';
import { useNoteSave } from '../../../hooks/useNoteSave.js';
+import useMounted from '../../../hooks/useMounted';
import ForceSaveNoteRow from '../../ForceSaveNoteRow.jsx';
const WIKI_FOLDERS = WIKI_CATEGORIES.map(c => ({ key: c.folder, label: c.label, icon: c.icon, color: c.textClass }));
@@ -19,10 +20,12 @@ const RAW_FOLDERS = [{ key: 'raw', label: 'Raw Sources', icon: FolderOpen, color
export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefresh }) {
const [searchParams, setSearchParams] = useSearchParams();
const noteParam = searchParams.get('note');
- const [selectedNote, setSelectedNote] = useState(null);
+ const [loadedNote, setSelectedNote] = useState(null);
+ const selectedNote = loadedNote?.path === noteParam ? loadedNote : null;
const [noteContent, setNoteContent] = useState('');
const [editing, setEditing] = useState(false);
const [loadingNote, setLoadingNote] = useState(false);
+ const [noteUnavailable, setNoteUnavailable] = useState(false);
const [expandedFolders, setExpandedFolders] = useState(new Set(['wiki/sources', 'wiki/entities', 'wiki/concepts']));
const [activeSection, setActiveSection] = useState('wiki');
const [tags, setTags] = useState([]);
@@ -31,6 +34,8 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
const [showTags, setShowTags] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(null);
const editorRef = useRef(null);
+ const mountedRef = useMounted();
+ const noteSequence = useRef(0);
// Owns the write plus the iCloud force-save escape hatch (#3717).
const { saving, save, forceOffered, dismissForce } = useNoteSave({
@@ -49,33 +54,40 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
}, options);
};
- // Handle deep-link from the URL.
+ // URL identity owns the read. Loading/error state must not re-trigger it, or
+ // a missing note retries forever. Cleanup also invalidates pending saves.
useEffect(() => {
- if (noteParam && !loadingNote) {
- // URLSearchParams already decodes the serialized query value. Keeping
- // the returned path intact also preserves literal percent signs in note paths.
- const notePath = noteParam;
- if (selectedNote?.path !== notePath) handleSelectNote(notePath);
- }
- }, [noteParam, selectedNote?.path, loadingNote]);
-
- const handleSelectNote = async (notePath) => {
- updateNoteParam(notePath);
- setLoadingNote(true);
+ const sequence = ++noteSequence.current;
+ setSelectedNote(null);
+ setNoteContent('');
setEditing(false);
- const data = await api.getNote(vaultId, notePath).catch(() => null);
- if (data && !data.error) {
- setSelectedNote(data);
- setNoteContent(data.content);
+ setConfirmDelete(null);
+ setNoteUnavailable(false);
+ setLoadingNote(!!noteParam);
+ if (noteParam) {
+ api.getNote(vaultId, noteParam).catch(() => null).then(data => {
+ if (!mountedRef.current || sequence !== noteSequence.current) return;
+ if (data && !data.error) {
+ setSelectedNote(data);
+ setNoteContent(data.content);
+ } else {
+ setNoteUnavailable(true);
+ }
+ setLoadingNote(false);
+ });
}
- setLoadingNote(false);
- };
+ return () => { ++noteSequence.current; };
+ }, [vaultId, noteParam, mountedRef]);
+
+ const handleSelectNote = (notePath) => updateNoteParam(notePath);
// `force` is ONLY ever passed by <ForceSaveNoteRow>'s confirm (#3717) — never
// by the Save button or ⌘S.
const handleSaveNote = async (options) => {
+ if (!selectedNote) return;
+ const sequence = noteSequence.current;
const data = await save(options);
- if (!data) return;
+ if (!data || !mountedRef.current || sequence !== noteSequence.current) return;
setSelectedNote(data);
setEditing(false);
toast.success('Note saved');
@@ -83,7 +95,10 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
};
const handleDeleteNote = async (notePath) => {
- await api.deleteNote(vaultId, notePath).catch(() => null);
+ if (selectedNote?.path !== notePath) return;
+ const sequence = noteSequence.current;
+ const deleted = await api.deleteNote(vaultId, notePath).then(() => true).catch(() => false);
+ if (!deleted || !mountedRef.current || sequence !== noteSequence.current) return;
toast.success('Note deleted');
setConfirmDelete(null);
if (selectedNote?.path === notePath) setSelectedNote(null);
@@ -93,6 +108,7 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
const loadTags = async () => {
const data = await api.getNotesVaultTags(vaultId).catch(() => null);
+ if (!mountedRef.current) return;
if (data?.tags) setTags(data.tags);
setSkippedTagNotes(data?.skippedUnavailable || 0);
};
@@ -127,7 +143,7 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
// header never clips it.
<div className="grid grid-cols-1 md:grid-cols-[320px_1fr] grid-rows-1 h-full min-h-0 overflow-hidden">
{/* Left panel — tree/list. Hidden on mobile while a note is open. */}
- <div className={`border-r border-port-border flex-col min-h-0 overflow-hidden ${selectedNote || loadingNote ? 'hidden md:flex' : 'flex'}`}>
+ <div className={`border-r border-port-border flex-col min-h-0 overflow-hidden ${noteParam ? 'hidden md:flex' : 'flex'}`}>
{/* Section toggle */}
<div className="p-3 border-b border-port-border flex items-center gap-2">
<button
@@ -226,11 +242,18 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
</div>
{/* Right panel: note viewer. Hidden on mobile until a note is opened. */}
- <div className={`flex-col min-w-0 min-h-0 overflow-hidden ${selectedNote || loadingNote ? 'flex' : 'hidden md:flex'}`}>
+ <div className={`flex-col min-w-0 min-h-0 overflow-hidden ${noteParam ? 'flex' : 'hidden md:flex'}`}>
{loadingNote ? (
<div className="flex items-center justify-center h-full">
<BrailleSpinner text="Loading" />
</div>
+ ) : noteUnavailable ? (
+ <div className="flex flex-col items-center justify-center h-full gap-3 p-4 text-gray-500">
+ <p className="text-sm">Page unavailable in this vault</p>
+ <button type="button" onClick={() => updateNoteParam(null, { replace: true })} className="text-sm text-port-accent hover:underline">
+ Back to list
+ </button>
+ </div>
) : selectedNote ? (
<>
{/* Note header */}
diff --git a/client/src/pages/Wiki.jsx b/client/src/pages/Wiki.jsx
index dd307e15d4..23383eed91 100644
--- a/client/src/pages/Wiki.jsx
+++ b/client/src/pages/Wiki.jsx
@@ -1,10 +1,11 @@
-import { useState, useEffect, useCallback, useMemo } from 'react';
+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router';
import * as api from '../services/api';
import { BookOpen, Search, Network, FileText, BarChart3, Activity } from 'lucide-react';
import PageSkeleton from '../components/ui/PageSkeleton';
import PageHeader from '../components/PageHeader';
import TabPills from '../components/ui/TabPills';
+import useMounted from '../hooks/useMounted';
import WikiOverviewTab from '../components/wiki/tabs/OverviewTab';
import WikiBrowseTab from '../components/wiki/tabs/BrowseTab';
@@ -38,7 +39,9 @@ export default function Wiki() {
const [vaults, setVaults] = useState([]);
const [loading, setLoading] = useState(true);
- const [notes, setNotes] = useState([]);
+ const [noteSnapshot, setNoteSnapshot] = useState(null);
+ const mountedRef = useMounted();
+ const scanSequence = useRef(0);
const loadVaults = useCallback(async () => {
const data = await api.getNotesVaults().catch(() => []);
@@ -54,6 +57,12 @@ export default function Wiki() {
);
const selectedVaultId = selectedVault?.id || null;
const vaultNotFound = !loading && vaults.length > 0 && !!vaultParam && !selectedVault;
+ // Each visit owns its data, including A -> B -> A while an old A scan is
+ // still running. Do not show the previous vault's list during the new scan.
+ const vaultScopeRef = useRef(null);
+ if (vaultScopeRef.current?.id !== selectedVaultId) vaultScopeRef.current = { id: selectedVaultId };
+ const vaultScope = vaultScopeRef.current;
+ const notes = useMemo(() => noteSnapshot?.scope === vaultScope ? noteSnapshot.notes : [], [noteSnapshot, vaultScope]);
// Selection handler writes the id to the URL; the tab route param is untouched.
const selectVault = useCallback((id) => {
@@ -73,12 +82,13 @@ export default function Wiki() {
}, [setSearchParams]);
const loadNotes = useCallback(async () => {
- if (!selectedVaultId) return;
- const data = await api.scanNotesVault(selectedVaultId, { limit: 1000 }).catch(() => null);
- if (data) {
- setNotes(data.notes);
+ if (!vaultScope.id || !mountedRef.current || vaultScopeRef.current !== vaultScope) return;
+ const sequence = ++scanSequence.current;
+ const data = await api.scanNotesVault(vaultScope.id, { limit: 1000 }).catch(() => null);
+ if (data && mountedRef.current && vaultScopeRef.current === vaultScope && scanSequence.current === sequence) {
+ setNoteSnapshot({ scope: vaultScope, notes: data.notes });
}
- }, [selectedVaultId]);
+ }, [vaultScope, mountedRef]);
useEffect(() => {
loadVaults();
@@ -164,7 +174,7 @@ export default function Wiki() {
case 'overview':
return <WikiOverviewTab vaultId={selectedVaultId} stats={stats} notes={wikiNotes} allNotes={notes} onRefresh={handleRefresh} />;
case 'browse':
- return <WikiBrowseTab vaultId={selectedVaultId} notes={wikiNotes} rawNotes={rawNotes} allNotes={notes} onRefresh={handleRefresh} />;
+ return <WikiBrowseTab key={selectedVaultId} vaultId={selectedVaultId} notes={wikiNotes} rawNotes={rawNotes} allNotes={notes} onRefresh={handleRefresh} />;
case 'search':
return <WikiSearchTab vaultId={selectedVaultId} onRefresh={handleRefresh} />;
case 'graph':
diff --git a/client/src/pages/Wiki.test.jsx b/client/src/pages/Wiki.test.jsx
index 461eb363ae..ab5c5af111 100644
--- a/client/src/pages/Wiki.test.jsx
+++ b/client/src/pages/Wiki.test.jsx
@@ -1,23 +1,26 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor, fireEvent } from '@testing-library/react';
+import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
import { MemoryRouter, Routes, Route, Navigate, useLocation } from 'react-router';
vi.mock('../services/api', () => ({
getNotesVaults: vi.fn(),
scanNotesVault: vi.fn(),
+ getNote: vi.fn(),
+ updateNote: vi.fn(),
+ deleteNote: vi.fn(),
}));
-// Stub the tab bodies — this suite only exercises vault selection + URL wiring.
+// Keep Browse real: vault selection must be tested through its editor and
+// mutation boundary, not only through the parent route's vaultId prop.
vi.mock('../components/wiki/tabs/OverviewTab', () => ({
default: ({ vaultId }) => <div data-testid="overview">overview:{vaultId || 'none'}</div>,
}));
-vi.mock('../components/wiki/tabs/BrowseTab', () => ({ default: () => <div>browse</div> }));
vi.mock('../components/wiki/tabs/SearchTab', () => ({ default: () => <div>search</div> }));
vi.mock('../components/wiki/tabs/GraphTab', () => ({ default: () => <div>graph</div> }));
vi.mock('../components/wiki/tabs/LogTab', () => ({ default: () => <div>log</div> }));
import Wiki, { TABS } from './Wiki';
-import { getNotesVaults, scanNotesVault } from '../services/api';
+import { getNotesVaults, scanNotesVault, getNote, updateNote, deleteNote } from '../services/api';
import { expectPageNavTabs } from '../test/pageNavTabAssertions.js';
describe('Wiki TABS ↔ nav manifest', () => {
@@ -51,7 +54,7 @@ const renderWiki = (initialEntry) =>
);
beforeEach(() => {
- vi.clearAllMocks();
+ vi.resetAllMocks();
getNotesVaults.mockResolvedValue([
{ id: 'vault-a', name: 'Vault A' },
{ id: 'vault-b', name: 'Vault B' },
@@ -59,6 +62,124 @@ beforeEach(() => {
scanNotesVault.mockResolvedValue({ notes: [] });
});
+const noteA = {
+ path: 'wiki/index.md', name: 'Example A', folder: 'wiki', content: 'Example A body',
+ size: 14, modifiedAt: '2026-01-01T00:00:00Z',
+};
+const noteB = { ...noteA, name: 'Example B', content: 'Example B body' };
+const deferred = () => {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+};
+
+describe('Wiki vault editor isolation', () => {
+ beforeEach(() => {
+ scanNotesVault.mockImplementation(async id => ({ notes: [id === 'vault-a' ? noteA : noteB] }));
+ getNote.mockImplementation(async id => id === 'vault-a' ? noteA : noteB);
+ updateNote.mockImplementation(async (id, path, content) => ({ ...(id === 'vault-a' ? noteA : noteB), path, content }));
+ deleteNote.mockResolvedValue(null);
+ });
+
+ const switchToB = () => fireEvent.change(screen.getByRole('combobox', { name: 'Vault' }), { target: { value: 'vault-b' } });
+ const openA = () => renderWiki('/wiki/browse?vault=vault-a&note=wiki%2Findex.md');
+
+ it('loads the destination note before editing or deleting a shared path in another vault', async () => {
+ openA();
+ await screen.findByText(noteA.content);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'Note content' }), { target: { value: 'Example A draft' } });
+
+ switchToB();
+ await screen.findByText(noteB.content);
+ expect(screen.queryByRole('textbox', { name: 'Note content' })).not.toBeInTheDocument();
+ expect(screen.getByTestId('location')).toHaveTextContent('/wiki/browse?vault=vault-b&note=wiki%2Findex.md');
+ expect(getNote).toHaveBeenCalledWith('vault-b', noteB.path);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ expect(screen.getByRole('textbox', { name: 'Note content' })).toHaveValue(noteB.content);
+ fireEvent.change(screen.getByRole('textbox', { name: 'Note content' }), { target: { value: 'Example B edited' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await screen.findByText('Example B edited');
+ expect(updateNote.mock.calls).toEqual([['vault-b', noteB.path, 'Example B edited', { force: false }]]);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Delete note' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
+ await waitFor(() => expect(deleteNote).toHaveBeenCalledWith('vault-b', noteB.path));
+ await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/wiki/browse?vault=vault-b'));
+ });
+
+ it('ignores a previous vault scan and note read that finish after the destination has loaded', async () => {
+ const scanA = deferred();
+ const readA = deferred();
+ scanNotesVault.mockImplementation(id => id === 'vault-a' ? scanA.promise : Promise.resolve({ notes: [noteB] }));
+ getNote.mockImplementation(id => id === 'vault-a' ? readA.promise : Promise.resolve(noteB));
+ openA();
+ await waitFor(() => expect(getNote).toHaveBeenCalledWith('vault-a', noteA.path));
+
+ switchToB();
+ await screen.findByText(noteB.content);
+ await act(async () => {
+ scanA.resolve({ notes: [noteA] });
+ readA.resolve(noteA);
+ });
+ expect(screen.getByText(noteB.content)).toBeInTheDocument();
+ expect(screen.queryByText(noteA.name)).not.toBeInTheDocument();
+ expect(screen.queryByText(noteA.content)).not.toBeInTheDocument();
+ });
+
+ it('keeps a destination draft intact when a previous vault save completes', async () => {
+ const saveA = deferred();
+ updateNote.mockReturnValue(saveA.promise);
+ openA();
+ await screen.findByText(noteA.content);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(updateNote).toHaveBeenCalledWith('vault-a', noteA.path, noteA.content, { force: false }));
+
+ switchToB();
+ await screen.findByText(noteB.content);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'Note content' }), { target: { value: 'Example B draft' } });
+ await act(async () => { saveA.resolve({ ...noteA, content: 'Example A saved' }); });
+ expect(screen.getByRole('textbox', { name: 'Note content' })).toHaveValue('Example B draft');
+ expect(scanNotesVault.mock.calls.filter(([id]) => id === 'vault-a')).toHaveLength(1);
+ expect(screen.getByTestId('location')).toHaveTextContent('/wiki/browse?vault=vault-b&note=wiki%2Findex.md');
+ });
+
+ it('keeps the URL-selected page when an earlier note read in the same vault finishes late', async () => {
+ const readA = deferred();
+ const second = { ...noteA, path: 'wiki/second.md', name: 'Second page', content: 'Second page body' };
+ scanNotesVault.mockResolvedValue({ notes: [noteA, second] });
+ getNote.mockImplementation((_id, path) => path === noteA.path ? readA.promise : Promise.resolve(second));
+ openA();
+ fireEvent.click(await screen.findByRole('button', { name: second.name }));
+ await screen.findByText(second.content);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Example second-note draft' } });
+ await act(async () => { readA.resolve(noteA); });
+ expect(screen.getByRole('textbox')).toHaveValue('Example second-note draft');
+ expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
+ expect(screen.queryByText(noteA.content)).not.toBeInTheDocument();
+ expect(screen.getByTestId('location')).toHaveTextContent('note=wiki%2Fsecond.md');
+ });
+
+ it('shows an unavailable destination note without retaining the previous editor or repeatedly fetching', async () => {
+ getNote.mockImplementation(id => id === 'vault-a' ? Promise.resolve(noteA) : Promise.reject(new Error('Note not found')));
+ openA();
+ await screen.findByText(noteA.content);
+ switchToB();
+ await screen.findByText('Page unavailable in this vault');
+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Delete note' })).not.toBeInTheDocument();
+ await act(async () => {});
+ expect(getNote.mock.calls.filter(([id]) => id === 'vault-b')).toHaveLength(1);
+ fireEvent.click(screen.getByRole('button', { name: 'Back to list' }));
+ expect(screen.getByText('Select a page to view')).toBeInTheDocument();
+ expect(screen.getByTestId('location')).toHaveTextContent('/wiki/browse?vault=vault-b');
+ });
+});
+
describe('Wiki vault URL wiring', () => {
it('defaults to the first vault when no ?vault= param is present', async () => {
renderWiki('/wiki/overview');
diff --git a/server/routes/tracks.js b/server/routes/tracks.js
index 810d4d1d63..ac801488f4 100644
--- a/server/routes/tracks.js
+++ b/server/routes/tracks.js
@@ -33,7 +33,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, isPaginationRequested, paginateArray } 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 { createTrackWithAlbum, updateTrackWithAlbum, removeTrackFromAlbum } from '../services/trackAlbumMembership.js';
import {
listMusicLibrary, importUploadedTrack, statMusicTrack,
isSupportedMusicUpload, assertSafeMusicFilename, MUSIC_UPLOAD_MAX_BYTES,
@@ -159,29 +159,6 @@ async function attachAudioAsRender(trackId, filename) {
});
}
-// 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(() => {});
- }
- }
-}
-
// Backward-compatible by default: returns the full tracks array. When a client
// passes `limit`/`offset`, the response becomes the bounded
// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.
@@ -218,8 +195,7 @@ router.post('/import/:jobId/cancel', (req, res) => {
router.post('/', asyncHandler(async (req, res) => {
const body = validateRequest(createSchema, req.body ?? {});
- const track = await tracks.createTrack(body);
- if (track.albumId) await reconcileTrackAlbum(track.id, '', track.albumId);
+ const { track } = await createTrackWithAlbum(body);
res.status(201).json(track);
}));
@@ -230,8 +206,7 @@ router.get('/:id', asyncHandler(async (req, res) => {
router.patch('/:id', asyncHandler(async (req, res) => {
const body = validateRequest(patchSchema, req.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);
+ const track = await updateTrackWithAlbum(prev, body);
res.json(track);
}));
@@ -240,7 +215,7 @@ router.delete('/:id', asyncHandler(async (req, res) => {
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, '');
+ if (prev?.albumId) await removeTrackFromAlbum(req.params.id, prev.albumId);
res.json(result);
}));
diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.js
index e9b8c92172..68eb5027d6 100644
--- a/server/routes/tracks.test.js
+++ b/server/routes/tracks.test.js
@@ -63,6 +63,7 @@ vi.mock('../services/trackYoutubeImport.js', () => ({
import * as musicLibrary from '../services/pipeline/musicLibrary.js';
import * as albums from '../services/albums/index.js';
+import { TRACK_IDS_MAX } from '../services/albums/logic.js';
import * as ytImport from '../services/trackYoutubeImport.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import tracksRoutes from './tracks.js';
@@ -200,6 +201,31 @@ describe('tracks routes', () => {
expect(albums.updateAlbum).toHaveBeenCalledWith('album-new', { trackIds: ['track-1'] });
});
+ // The capacity/existence contract itself is covered at the service boundary
+ // (services/trackAlbumMembership.test.js). These two pin the ROUTE wiring:
+ // a regression that reinstates the old best-effort reconcile would persist
+ // the track and answer 2xx instead of surfacing the refusal.
+ it('POST / refuses a create into a full album without persisting the track', async () => {
+ albums.getAlbum.mockResolvedValueOnce({ id: 'album-full', trackIds: Array.from({ length: TRACK_IDS_MAX }, (_, i) => `track-${i}`) });
+ const r = await request(app).post('/api/tracks').send({ title: 'Intro', albumId: 'album-full' });
+ expect(r.status).toBe(409);
+ expect(r.body.code).toBe('ALBUM_FULL');
+ expect(tracks.createTrack).not.toHaveBeenCalled();
+ expect(albums.updateAlbum).not.toHaveBeenCalled();
+ });
+
+ it('PATCH /:id refuses a move into an album that no longer exists', async () => {
+ tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Intro', albumId: 'album-old' });
+ // An earlier case left a mockImplementation on getAlbum; clearAllMocks keeps
+ // implementations, so state the missing destination explicitly.
+ albums.getAlbum.mockResolvedValueOnce(null);
+ const r = await request(app).patch('/api/tracks/track-1').send({ albumId: 'album-missing' });
+ expect(r.status).toBe(404);
+ expect(r.body.code).toBe('ALBUM_NOT_FOUND');
+ expect(tracks.updateTrack).not.toHaveBeenCalled();
+ expect(albums.updateAlbum).not.toHaveBeenCalled();
+ });
+
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();
diff --git a/server/services/authGate.js b/server/services/authGate.js
index 3561c0ed4f..17eb64167b 100644
--- a/server/services/authGate.js
+++ b/server/services/authGate.js
@@ -73,7 +73,10 @@ export const authGate = async (req, res, next) => {
}));
return;
}
- const path = req.path;
+ // Express mounts match case-insensitively. Use the same casing for every
+ // authorization check, including public exceptions, without rewriting the
+ // request URL: downstream record IDs and asset filenames may be case-sensitive.
+ const path = req.path.toLowerCase();
if (isPublicPath(path)) return next();
// Per-API public exemptions. When the user has marked an API exposed +
// passwordless in Settings (`apiAccess.<id>`), re-open ONLY its declared
diff --git a/server/services/authGate.test.js b/server/services/authGate.test.js
index 6e6be39b5e..4d4cb22f4a 100644
--- a/server/services/authGate.test.js
+++ b/server/services/authGate.test.js
@@ -1,8 +1,10 @@
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
import { readFileSync, writeFileSync, rmSync } from 'fs';
import { join } from 'path';
import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
import { bindSettingsFile } from '../lib/settingsTestUtil.js';
+import { request } from '../lib/testHelper.js';
const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-authgate-' });
@@ -399,6 +401,126 @@ describe('authGate per-API public registry (apiAccess)', () => {
});
});
+describe('authGate Express path matching', () => {
+ // Real HTTP requests through ordinary Express mounts reproduce the routing
+ // mismatch a direct middleware call cannot see. Auth uses this suite's temp
+ // storage; fixture handlers avoid booting services or touching application data.
+ const buildApp = async () => {
+ const { authGate } = await import('./authGate.js');
+ const { default: authRoutes } = await import('../routes/auth.js');
+ const app = express();
+ const mutations = [];
+ const recordMutation = (req, res) => {
+ mutations.push(req.body);
+ res.json({ auth: req.portosAuthContext });
+ };
+ app.use(authGate);
+ app.use(express.json());
+ app.use('/api/auth', authRoutes);
+
+ const api = express.Router();
+ api.get('/records/:id', (req, res) => res.json({ id: req.params.id, auth: req.portosAuthContext }));
+ api.post('/records', recordMutation);
+ app.use('/api/example', api);
+ app.use('/data/images', (req, res) => res.type('text/plain').send(req.path));
+
+ const sdapi = express.Router();
+ sdapi.get('/sd-models', (_req, res) => res.json([]));
+ sdapi.post('/txt2img', recordMutation);
+ app.use('/sdapi/v1', sdapi);
+
+ const voice = express.Router();
+ voice.post('/public/synthesize', recordMutation);
+ voice.put('/config', recordMutation);
+ voice.post('/publicity', recordMutation);
+ app.use('/api/voice', voice);
+ app.get('/api/system/health', (_req, res) => res.json({ status: 'ok' }));
+ app.get('/assets/App.js', (_req, res) => res.type('text/javascript').send('// Example bundle'));
+ return { app, mutations };
+ };
+
+ it('blocks protected reads and mutations regardless of prefix casing', async () => {
+ const auth = await import('./auth.js');
+ await auth.setPassword({ newPassword: 'correct-horse' });
+ const { app, mutations } = await buildApp();
+
+ for (const path of [
+ '/api/example/records/ExampleRecord', '/aPi/example/records/ExampleRecord',
+ '/data/images/ExampleAsset.txt', '/DaTa/images/ExampleAsset.txt',
+ '/sdapi/v1/sd-models', '/SdApI/v1/sd-models',
+ ]) {
+ const response = await request(app).get(path);
+ expect(response.status, path).toBe(401);
+ if (path.toLowerCase().startsWith('/data/')) expect(response.text).toBe('Unauthorized');
+ else expect(response.body.code).toBe('AUTH_REQUIRED');
+ }
+ for (const path of ['/API/example/records', '/SDAPI/v1/txt2img']) {
+ const response = await request(app).post(path).send({ name: 'Example Record' });
+ expect(response.status, path).toBe(401);
+ }
+ expect(mutations).toEqual([]);
+ });
+
+ it('authenticates mixed-case routes without changing record IDs or asset paths', async () => {
+ const auth = await import('./auth.js');
+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });
+ const { app, mutations } = await buildApp();
+ const record = await request(app).get('/API/example/records/CaseSensitiveID')
+ .set('Cookie', `portos_auth=${token}`);
+ expect(record.status).toBe(200);
+ expect(record.body).toEqual({ id: 'CaseSensitiveID', auth: { enabled: true, authenticated: true, method: 'session' } });
+
+ const asset = await request(app).get('/DaTa/images/ExampleAsset.txt')
+ .set('Authorization', `Bearer ${token}`);
+ expect(asset.status).toBe(200);
+ expect(asset.text).toBe('/ExampleAsset.txt');
+
+ const rendered = await request(app).post('/SDAPI/v1/txt2img')
+ .set('Authorization', `Basic ${Buffer.from(':correct-horse').toString('base64')}`)
+ .send({ prompt: 'Example scene' });
+ expect(rendered.status).toBe(200);
+ expect(rendered.body.auth).toEqual({ enabled: true, authenticated: true, method: 'basic' });
+ expect(mutations).toEqual([{ prompt: 'Example scene' }]);
+ });
+
+ it('preserves public auth routes and keeps opt-in API exemptions within their prefixes', async () => {
+ const auth = await import('./auth.js');
+ await auth.setPassword({ newPassword: 'correct-horse' });
+ const { app, mutations } = await buildApp();
+ const status = await request(app).get('/API/Auth/STATUS');
+ expect(status.status).toBe(200);
+ expect(status.body).toEqual({ enabled: true });
+ const login = await request(app).post('/API/Auth/LOGIN').send({ password: 'correct-horse' });
+ expect(login.status).toBe(200);
+ expect(login.headers['set-cookie']).toMatch(/portos_auth=/);
+ const health = await request(app).get('/API/SYSTEM/HEALTH');
+ expect(health.status).toBe(200);
+ expect(health.body).toEqual({ status: 'ok' });
+ expect((await request(app).get('/assets/App.js')).status).toBe(200);
+
+ await writeApiAccess({ voice: { exposed: true, requireAuth: false }, sdapi: { exposed: true, requireAuth: false } });
+ expect((await request(app).post('/API/VOICE/PUBLIC/synthesize').send({ text: 'Example speech' })).status).toBe(200);
+ expect((await request(app).post('/SDAPI/v1/txt2img').send({ prompt: 'Example scene' })).status).toBe(200);
+ expect((await request(app).put('/API/VOICE/config').send({ example: true })).status).toBe(401);
+ expect((await request(app).post('/API/VOICE/publicity').send({ example: true })).status).toBe(401);
+ expect(mutations).toEqual([{ text: 'Example speech' }, { prompt: 'Example scene' }]);
+
+ await writeApiAccess({ voice: { exposed: true, requireAuth: true }, sdapi: { exposed: false, requireAuth: false } });
+ expect((await request(app).post('/API/VOICE/PUBLIC/synthesize').send({ text: 'Example speech' })).status).toBe(401);
+ expect((await request(app).post('/SDAPI/v1/txt2img').send({ prompt: 'Example scene' })).status).toBe(401);
+ expect(mutations).toHaveLength(2);
+ });
+
+ it('keeps the default auth-off behavior on mixed-case routes', async () => {
+ await writeApiAccess({ voice: { exposed: false, requireAuth: true } });
+ const { app } = await buildApp();
+ const record = await request(app).get('/API/example/records/ExampleRecord');
+ expect(record.status).toBe(200);
+ expect(record.body.auth).toEqual({ enabled: false, authenticated: false, method: null });
+ expect((await request(app).post('/API/VOICE/PUBLIC/synthesize').send({ text: 'Example speech' })).status).toBe(200);
+ });
+});
+
describe('authGate HTTP Basic auth (peer federation)', () => {
const basicHeader = (password, username = '') =>
`Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
diff --git a/server/services/musicStudioHook.js b/server/services/musicStudioHook.js
index 742318aa0c..bfdf36578a 100644
--- a/server/services/musicStudioHook.js
+++ b/server/services/musicStudioHook.js
@@ -6,7 +6,7 @@ import { renderFederatedMediaAudioPrompt } from '../lib/federatedMediaWire.js';
import { createMediaJobImageHook } from './mediaJobImageHook.js';
import { updateJobResult } from './mediaJobQueue/index.js';
import * as tracks from './tracks/index.js';
-import * as albums from './albums/index.js';
+import { createTrackWithAlbum } from './trackAlbumMembership.js';
const hook = createMediaJobImageHook({
label: 'Music Studio',
@@ -70,23 +70,18 @@ const hook = createMediaJobImageHook({
// a standalone render has no prior record, so retain its authored lyrics.
const shouldPersistLyrics = lyricsEnabled && lyricsProvided && (instrumentalOnly !== true || !trackId);
if (shouldPersistLyrics) meta.lyrics = authoredLyrics;
- const track = trackId
- ? await tracks.updateTrack(trackId, meta)
- : await tracks.createTrack({
+ const { track, albumAssignmentError } = trackId
+ ? { track: await tracks.updateTrack(trackId, meta) }
+ : await createTrackWithAlbum({
title: title || authoredPrompt.slice(0, 60),
artistId,
artist,
albumId,
...(shouldPersistLyrics ? { lyrics: authoredLyrics } : {}),
...meta,
- });
- if (!trackId && track?.albumId) {
- const album = await albums.getAlbum(track.albumId).catch(() => null);
- if (album && !(album.trackIds || []).includes(track.id)) {
- await albums.updateAlbum(track.albumId, { trackIds: [...(album.trackIds || []), track.id] }).catch(() => {});
- }
- }
- await updateJobResult(job.id, { trackId: track.id });
+ }, { preserveUnassigned: true });
+ await updateJobResult(job.id, { trackId: track.id, ...(albumAssignmentError ? { albumAssignmentError } : {}) });
+ if (albumAssignmentError) console.warn(`⚠️ Music Studio saved completed audio as a single: ${albumAssignmentError.message}`);
return track;
},
onAttached: ({ trackId, filename }, track) => {
diff --git a/server/services/musicStudioHook.test.js b/server/services/musicStudioHook.test.js
index 8c895e76ad..564e58c3da 100644
--- a/server/services/musicStudioHook.test.js
+++ b/server/services/musicStudioHook.test.js
@@ -1,4 +1,6 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { buildAlbumRecord, TRACK_IDS_MAX } from './albums/logic.js';
+import { buildTrackRecord, makeRender } from './tracks/logic.js';
const queue = vi.hoisted(() => {
const listeners = new Set();
return {
@@ -26,8 +28,8 @@ describe('music studio completion hook', () => {
trackStore.getTrack.mockReset();
trackStore.buildRenderAppend.mockReset().mockReturnValue({ renders: [{ id: 'render-1' }] });
trackStore.updateTrack.mockReset().mockResolvedValue({ id: 'track-1' });
- trackStore.createTrack.mockReset().mockResolvedValue({ id: 'track-new', albumId: 'album-1' });
- albumStore.getAlbum.mockReset().mockResolvedValue({ trackIds: [] });
+ trackStore.createTrack.mockReset().mockImplementation(async (input) => ({ id: 'track-new', ...input }));
+ albumStore.getAlbum.mockReset().mockResolvedValue({ id: 'album-1', trackIds: [] });
albumStore.updateAlbum.mockReset().mockResolvedValue({});
initMusicStudioHook();
});
@@ -130,6 +132,36 @@ describe('music studio completion hook', () => {
expect(trackStore.updateTrack).not.toHaveBeenCalledWith('deleted-track', expect.anything());
});
+ it.each(['full', 'missing'])('preserves completed audio as an unassigned track when the album is %s', async (state) => {
+ const now = '2026-01-01T00:00:00.000Z';
+ const album = state === 'full' ? buildAlbumRecord({
+ title: 'Example Album', trackIds: Array.from({ length: TRACK_IDS_MAX }, (_, i) => `track-example-${i}`),
+ }, { id: 'album-1', now }) : null;
+ albumStore.getAlbum.mockResolvedValue(album);
+ let storedTrack;
+ trackStore.createTrack.mockImplementation(async (input) => {
+ storedTrack = buildTrackRecord(input, { id: 'track-new', now });
+ return storedTrack;
+ });
+ trackStore.buildRenderAppend.mockImplementation((_track, input) => ({
+ renders: [makeRender(input, { id: 'render-new', now })],
+ }));
+ queue.events.emit('completed', {
+ id: 'job-preserved', kind: 'audio', queuedAt: now,
+ params: { prompt: 'Example prompt', musicStudio: { trackId: null, title: 'Example Track', albumId: 'album-1' } },
+ result: { filename: 'completed.wav', durationSec: 8, engine: 'musicgen', modelId: 'example-model' },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(storedTrack).toMatchObject({ id: 'track-new', albumId: '', audioFilename: 'completed.wav' });
+ expect(storedTrack.renders).toEqual([expect.objectContaining({ audioFilename: 'completed.wav' })]);
+ expect(albumStore.updateAlbum).not.toHaveBeenCalled();
+ expect(queue.updateJobResult).toHaveBeenCalledWith('job-preserved', {
+ trackId: 'track-new',
+ albumAssignmentError: { code: state === 'full' ? 'ALBUM_FULL' : 'ALBUM_NOT_FOUND', message: expect.any(String) },
+ });
+ });
+
it('files the privacy-safe profile prompt instead of the rollback-safe empty prompt', async () => {
trackStore.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });
queue.events.emit('completed', {
diff --git a/server/services/sharing/watcher.js b/server/services/sharing/watcher.js
index 2f93b6e718..be8ca5ba64 100644
--- a/server/services/sharing/watcher.js
+++ b/server/services/sharing/watcher.js
@@ -15,7 +15,7 @@
*/
import { watch } from 'chokidar';
-import { join, basename } from 'path';
+import { join, basename, sep } from 'path';
import { processManifest, processBacklog, handleUnshare, sharingEvents } from './importer.js';
import { getBucket, listBuckets, ensureBucketLayout } from './buckets.js';
import { isManifestPruning, pruneBucketManifests } from './manifest.js';
@@ -40,14 +40,20 @@ function queueBacklog(bucketId) {
if (!slot) {
const running = runScan().finally(() => {
const live = backlogQueues.get(bucketId);
- if (live && live.running === running) backlogQueues.delete(bucketId);
+ if (live?.running === running && !live.queued) backlogQueues.delete(bucketId);
});
backlogQueues.set(bucketId, { running, queued: null });
return running;
}
- const queued = slot.running.then(runScan).finally(() => {
+ const queued = slot.running.then(() => {
+ // Promote the follow-up before scanning. Events arriving during it need
+ // another trailing scan, since their manifest may already have been read.
+ slot.running = queued;
+ slot.queued = null;
+ return runScan();
+ }).finally(() => {
const live = backlogQueues.get(bucketId);
- if (live && live.queued === queued) backlogQueues.delete(bucketId);
+ if (live?.running === queued && !live.queued) backlogQueues.delete(bucketId);
});
slot.queued = queued;
return queued;
@@ -74,7 +80,7 @@ export async function attachWatcher(bucketId) {
// A path under assets/ or records/ is bundle-side sync we should retry on,
// not a manifest to process. Manifests live in manifests/ (always *.json).
- const isBundleSync = (p) => p.includes(`${assetsDir}/`) || p.includes(`${recordsDir}/`);
+ const isBundleSync = (p) => p.startsWith(`${assetsDir}${sep}`) || p.startsWith(`${recordsDir}${sep}`);
// try/catch around async event handlers — see AGENTS.md "PTY/child-process
// /setTimeout/setInterval callbacks" rule (chokidar events fire outside the
@@ -105,7 +111,7 @@ export async function attachWatcher(bucketId) {
w.on('unlink', async (path) => {
// Only manifest deletions are unshare signals. Record/asset unlinks are
// expected during cloud-sync churn and not actionable here.
- if (!path.includes(`${manifestsDir}/`)) return;
+ if (!path.startsWith(`${manifestsDir}${sep}`)) return;
const file = basename(path);
if (!file.endsWith('.json')) return;
// Our own pruner moves stale manifests into `<bucket>/.archive/manifests/`;
@@ -167,10 +173,3 @@ export async function shutdownAllWatchers() {
export function listAttachedWatchers() {
return [...watchers.keys()];
}
-
-/**
- * Exported for unit testing only — exposes the coalescing queue so the
- * flood-then-assert pattern can be tested without a real chokidar watcher.
- * @internal
- */
-export { queueBacklog as __queueBacklogForTests, backlogQueues as __backlogQueuesForTests };
diff --git a/server/services/sharing/watcher.test.js b/server/services/sharing/watcher.test.js
index e5d3571727..6f5eb54262 100644
--- a/server/services/sharing/watcher.test.js
+++ b/server/services/sharing/watcher.test.js
@@ -1,163 +1,141 @@
-/**
- * Tests for queueBacklog coalescing in server/services/sharing/watcher.js
- *
- * The coalescing contract: a flood of concurrent queueBacklog(bucketId) calls
- * must collapse to at most one in-flight scan + one queued follow-up. When the
- * in-flight finishes, the queued run executes. All calls that arrive while a
- * scan is running share the same queued Promise, so processBacklog is never
- * called more than twice regardless of flood size.
- *
- * Testing strategy: mock importer.processBacklog with a controlled promise so
- * we can pause and resume the in-flight scan and count calls precisely.
- */
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'node:events';
+import { posix, win32 } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-// Mock chokidar so attaching a watcher doesn't require real fs events.
-vi.mock('chokidar', () => ({
- watch: vi.fn(() => ({
- on: vi.fn().mockReturnThis(),
- close: vi.fn().mockResolvedValue(undefined),
- })),
-}));
-
-// Mock all the collaborators watcher.js pulls in.
+vi.mock('chokidar', () => ({ watch: vi.fn() }));
vi.mock('./importer.js', () => ({
- processManifest: vi.fn().mockResolvedValue(undefined),
- processBacklog: vi.fn(),
- handleUnshare: vi.fn().mockResolvedValue(undefined),
- sharingEvents: { emit: vi.fn(), on: vi.fn() },
+ processManifest: vi.fn(), processBacklog: vi.fn(), handleUnshare: vi.fn(),
+ sharingEvents: { emit: vi.fn() },
}));
-
vi.mock('./buckets.js', () => ({
- getBucket: vi.fn(),
- listBuckets: vi.fn().mockResolvedValue([]),
+ getBucket: vi.fn(), listBuckets: vi.fn().mockResolvedValue([]),
ensureBucketLayout: vi.fn().mockResolvedValue(undefined),
}));
+vi.mock('./manifest.js', () => ({ isManifestPruning: vi.fn(), pruneBucketManifests: vi.fn() }));
+vi.mock('../instances.js', () => ({ getInstanceId: vi.fn() }));
-vi.mock('./manifest.js', () => ({
- isManifestPruning: vi.fn().mockReturnValue(false),
- pruneBucketManifests: vi.fn().mockResolvedValue(undefined),
-}));
-
-vi.mock('../instances.js', () => ({
- getInstanceId: vi.fn().mockResolvedValue('test-instance'),
- getPeers: vi.fn().mockResolvedValue([]),
-}));
-
-import { processBacklog } from './importer.js';
-import {
- __queueBacklogForTests as queueBacklog,
- __backlogQueuesForTests as backlogQueues,
-} from './watcher.js';
+import { watch } from 'chokidar';
+import { processBacklog, processManifest, handleUnshare } from './importer.js';
+import { getBucket } from './buckets.js';
+import { isManifestPruning } from './manifest.js';
-// Helper: create a deferred Promise so we can control when processBacklog resolves.
+let shutdown;
function deferred() {
- let resolve, reject;
- const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
- return { promise, resolve, reject };
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+}
+// Deliver a real attached listener's event and expose its completion to the test.
+const deliver = (watcher, event, path) => Promise.all(watcher.listeners(event).map(listener => listener(path)));
+
+async function attach(paths = posix, root = '/example/bucket') {
+ vi.doMock('path', () => ({ join: paths.join, basename: paths.basename, sep: paths.sep }));
+ getBucket.mockImplementation(async id => ({ id, name: 'Example bucket', path: root }));
+ const module = await import('./watcher.js');
+ shutdown = module.shutdownAllWatchers;
+ return { watcher: await module.attachWatcher('bucket-example'), attachWatcher: module.attachWatcher, root, paths };
}
-describe('watcher — queueBacklog coalescing', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- // Clear any residual queue state from other tests.
- backlogQueues.clear();
- });
-
- afterEach(() => {
- backlogQueues.clear();
- });
-
- it('calls processBacklog once when there is no in-flight scan', async () => {
- processBacklog.mockResolvedValue(undefined);
-
- await queueBacklog('bucket-1');
-
- expect(processBacklog).toHaveBeenCalledTimes(1);
- expect(processBacklog).toHaveBeenCalledWith('bucket-1');
- // Queue slot is cleaned up after the run.
- expect(backlogQueues.has('bucket-1')).toBe(false);
- });
-
- it('coalesces a flood of calls to at most two processBacklog invocations', async () => {
- // First scan is in-flight — hold it with a deferred.
- const d = deferred();
- processBacklog.mockReturnValueOnce(d.promise).mockResolvedValue(undefined);
-
- // Fire the first call (in-flight).
- const p1 = queueBacklog('bucket-flood');
- // Fire many more calls while the first scan is still running.
- const p2 = queueBacklog('bucket-flood');
- const p3 = queueBacklog('bucket-flood');
- const p4 = queueBacklog('bucket-flood');
- const p5 = queueBacklog('bucket-flood');
-
- // While in-flight, processBacklog should have been called exactly once.
- expect(processBacklog).toHaveBeenCalledTimes(1);
-
- // Release the first scan.
- d.resolve();
- await Promise.all([p1, p2, p3, p4, p5]);
+beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ watch.mockImplementation(() => Object.assign(new EventEmitter(), { close: vi.fn().mockResolvedValue(undefined) }));
+ processBacklog.mockReset().mockResolvedValue(undefined);
+ processManifest.mockReset().mockResolvedValue(undefined);
+ handleUnshare.mockReset().mockResolvedValue(undefined);
+ isManifestPruning.mockReset().mockReturnValue(false);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+afterEach(async () => {
+ await shutdown?.();
+ shutdown = null;
+ vi.doUnmock('path');
+ vi.restoreAllMocks();
+});
- // After the in-flight scan completes, exactly one queued follow-up should
- // have fired — total calls is 2 (in-flight + one queued).
+describe.each([
+ ['POSIX', posix, '/example/bucket'],
+ ['Windows', win32, 'C:\\example\\bucket'],
+])('share-bucket watcher on %s', (_label, paths, root) => {
+ it('retries late assets and records, while dispatching only manifests for import and unshare', async () => {
+ const { watcher } = await attach(paths, root);
+ const asset = paths.join(root, 'assets', 'blobs', 'example-blob');
+ const record = paths.join(root, 'records', 'universes', 'example.json');
+ const manifest = paths.join(root, 'manifests', 'example-manifest.json');
+ await deliver(watcher, 'add', asset);
+ await deliver(watcher, 'change', record);
expect(processBacklog).toHaveBeenCalledTimes(2);
- // Queue is fully drained.
- expect(backlogQueues.has('bucket-flood')).toBe(false);
- });
-
- it('all queued calls receive the same Promise (coalescing, not duplication)', async () => {
- const d = deferred();
- processBacklog.mockReturnValueOnce(d.promise).mockResolvedValue(undefined);
-
- // Start first in-flight call.
- queueBacklog('bucket-coalesce');
- // All subsequent calls while in-flight must return the SAME Promise.
- const q1 = queueBacklog('bucket-coalesce');
- const q2 = queueBacklog('bucket-coalesce');
- const q3 = queueBacklog('bucket-coalesce');
-
- // q1, q2, q3 are the queued promises — they must be the same reference.
- expect(q1).toBe(q2);
- expect(q2).toBe(q3);
-
- d.resolve();
- await Promise.all([q1, q2, q3]);
- });
-
- it('uses separate queue slots for different bucket ids', async () => {
- processBacklog.mockResolvedValue(undefined);
-
- await Promise.all([
- queueBacklog('bucket-A'),
- queueBacklog('bucket-B'),
+ expect(processManifest).not.toHaveBeenCalled();
+ await deliver(watcher, 'add', manifest);
+ await deliver(watcher, 'change', manifest);
+ expect(processManifest.mock.calls).toEqual([
+ ['bucket-example', 'example-manifest.json'], ['bucket-example', 'example-manifest.json'],
]);
-
- // Each bucket is handled independently.
- expect(processBacklog).toHaveBeenCalledWith('bucket-A');
- expect(processBacklog).toHaveBeenCalledWith('bucket-B');
- // Both queue slots are cleaned up.
- expect(backlogQueues.has('bucket-A')).toBe(false);
- expect(backlogQueues.has('bucket-B')).toBe(false);
+ await deliver(watcher, 'unlink', asset);
+ await deliver(watcher, 'unlink', record);
+ await deliver(watcher, 'unlink', paths.join(root, 'manifests-old', 'example.json'));
+ expect(handleUnshare).not.toHaveBeenCalled();
+ await deliver(watcher, 'unlink', manifest);
+ expect(handleUnshare).toHaveBeenCalledExactlyOnceWith('bucket-example', 'example-manifest.json');
+ isManifestPruning.mockReturnValue(true);
+ await deliver(watcher, 'unlink', manifest);
+ expect(handleUnshare).toHaveBeenCalledTimes(1);
});
+});
- it('continues to accept new scans after the queue drains', async () => {
- processBacklog.mockResolvedValue(undefined);
-
- await queueBacklog('bucket-seq');
+describe('share-bucket watcher backlog lifecycle', () => {
+ it('coalesces each burst without overlapping or losing events during a follow-up scan', async () => {
+ const { watcher, paths, root } = await attach();
+ const first = deferred();
+ const second = deferred();
+ const secondStarted = deferred();
+ let active = 0;
+ let peak = 0;
+ const scan = async pending => {
+ active++;
+ peak = Math.max(peak, active);
+ await pending;
+ active--;
+ };
+ processBacklog
+ .mockImplementationOnce(() => scan(first.promise))
+ .mockImplementationOnce(() => { secondStarted.resolve(); return scan(second.promise); })
+ .mockImplementation(() => scan(Promise.resolve()));
+ const event = () => deliver(watcher, 'add', paths.join(root, 'assets', 'blobs', 'example-blob'));
+ const initial = event();
+ const burst = [event(), event(), event()];
expect(processBacklog).toHaveBeenCalledTimes(1);
- expect(backlogQueues.has('bucket-seq')).toBe(false);
-
- // A second call after draining should start a fresh in-flight scan.
- await queueBacklog('bucket-seq');
- expect(processBacklog).toHaveBeenCalledTimes(2);
+ first.resolve();
+ await secondStarted.promise;
+ const late = event();
+ const scansWhileFollowupRuns = processBacklog.mock.calls.length;
+ second.resolve();
+ await Promise.all([initial, ...burst, late]);
+ expect(scansWhileFollowupRuns).toBe(2);
+ expect(peak).toBe(1);
+ expect(processBacklog).toHaveBeenCalledTimes(3);
+ await event();
+ expect(processBacklog).toHaveBeenCalledTimes(4);
});
- it('swallows processBacklog errors without unhandled rejection', async () => {
- processBacklog.mockRejectedValue(new Error('scan failed'));
-
- // Should not throw — errors are caught inside queueBacklog.
- await expect(queueBacklog('bucket-err')).resolves.toBeUndefined();
- expect(backlogQueues.has('bucket-err')).toBe(false);
+ it('recovers from a failed scan and lets a different bucket make progress', async () => {
+ const { watcher, attachWatcher, paths, root } = await attach();
+ const other = await attachWatcher('bucket-other');
+ const blocked = deferred();
+ processBacklog
+ .mockImplementationOnce(() => blocked.promise.then(() => { throw new Error('Example scan failure'); }))
+ .mockResolvedValue(undefined);
+ const path = paths.join(root, 'records', 'example.json');
+ const pending = deliver(watcher, 'change', path);
+ const trailing = deliver(watcher, 'change', path);
+ await deliver(other, 'change', path);
+ expect(processBacklog.mock.calls.map(([id]) => id)).toEqual(['bucket-example', 'bucket-other']);
+ blocked.resolve();
+ await Promise.all([pending, trailing]);
+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Example scan failure'));
+ expect(processBacklog.mock.calls.map(([id]) => id)).toEqual(['bucket-example', 'bucket-other', 'bucket-example']);
+ await deliver(watcher, 'change', path);
+ expect(processBacklog).toHaveBeenCalledTimes(4);
});
});
diff --git a/server/services/trackAlbumMembership.js b/server/services/trackAlbumMembership.js
new file mode 100644
index 0000000000..1d174b282a
--- /dev/null
+++ b/server/services/trackAlbumMembership.js
@@ -0,0 +1,57 @@
+/**
+ * Track-to-album mutations shared by HTTP saves and Music Studio completion.
+ * Validate the destination before writing either side: the album sanitizer's
+ * read/sync cap intentionally truncates overflow rather than rejecting it.
+ */
+import { ServerError } from '../lib/errorHandler.js';
+import { TRACK_IDS_MAX } from './albums/logic.js';
+import * as albums from './albums/index.js';
+import * as tracks from './tracks/index.js';
+
+async function destinationAlbum(albumId, trackId) {
+ if (!albumId) return null;
+ const album = await albums.getAlbum(albumId);
+ if (!album) throw new ServerError('Album not found', { status: 404, code: 'ALBUM_NOT_FOUND' });
+ const ids = album.trackIds || [];
+ if (!ids.includes(trackId) && ids.length >= TRACK_IDS_MAX) {
+ throw new ServerError(`Album already has ${TRACK_IDS_MAX} tracks. Remove a track before adding another.`, {
+ status: 409, code: 'ALBUM_FULL',
+ });
+ }
+ return album;
+}
+
+async function appendTrackToAlbum(trackId, album) {
+ if (!album || (album.trackIds || []).includes(trackId)) return;
+ await albums.updateAlbum(album.id, { trackIds: [...(album.trackIds || []), trackId] });
+}
+
+export async function removeTrackFromAlbum(trackId, albumId) {
+ if (!albumId) return;
+ const album = await albums.getAlbum(albumId);
+ if (album?.trackIds?.includes(trackId)) {
+ await albums.updateAlbum(albumId, { trackIds: album.trackIds.filter((id) => id !== trackId) });
+ }
+}
+
+/** Completed audio may survive an unavailable destination as a single. */
+export async function createTrackWithAlbum(input, { preserveUnassigned = false } = {}) {
+ let albumAssignmentError = null;
+ const album = await destinationAlbum(input.albumId).catch((err) => {
+ if (!preserveUnassigned || !['ALBUM_FULL', 'ALBUM_NOT_FOUND'].includes(err.code)) throw err;
+ albumAssignmentError = { code: err.code, message: err.message };
+ return null;
+ });
+ const track = await tracks.createTrack({ ...input, albumId: album?.id || '' });
+ await appendTrackToAlbum(track.id, album);
+ return { track, albumAssignmentError };
+}
+
+export async function updateTrackWithAlbum(current, patch) {
+ if (!('albumId' in patch)) return tracks.updateTrack(current.id, patch);
+ const album = await destinationAlbum(patch.albumId, current.id);
+ const track = await tracks.updateTrack(current.id, patch);
+ await appendTrackToAlbum(track.id, album);
+ if (current.albumId !== track.albumId) await removeTrackFromAlbum(track.id, current.albumId);
+ return track;
+}
diff --git a/server/services/trackAlbumMembership.test.js b/server/services/trackAlbumMembership.test.js
new file mode 100644
index 0000000000..3012d11182
--- /dev/null
+++ b/server/services/trackAlbumMembership.test.js
@@ -0,0 +1,125 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { buildAlbumRecord, TRACK_IDS_MAX } from './albums/logic.js';
+import { buildTrackRecord } from './tracks/logic.js';
+
+const records = vi.hoisted(() => ({ albums: new Map(), tracks: new Map() }));
+
+// Exercise the real stored shapes: returning a patch verbatim would hide the
+// album sanitizer silently dropping the appended 201st track while the caller
+// still reports success.
+vi.mock('./albums/index.js', async () => {
+ const { applyAlbumPatch } = await import('./albums/logic.js');
+ return {
+ getAlbum: async (id) => records.albums.get(id) || null,
+ updateAlbum: async (id, patch) => {
+ const next = applyAlbumPatch(records.albums.get(id), patch);
+ records.albums.set(id, next);
+ return next;
+ },
+ };
+});
+vi.mock('./tracks/index.js', async () => {
+ const logic = await import('./tracks/logic.js');
+ return {
+ ...logic,
+ getTrack: async (id) => records.tracks.get(id) || null,
+ createTrack: async (input) => {
+ const next = logic.buildTrackRecord(input, { id: 'track-new', now: '2026-01-01T00:00:00.000Z' });
+ records.tracks.set(next.id, next);
+ return next;
+ },
+ updateTrack: async (id, patch) => {
+ const next = logic.applyTrackPatch(records.tracks.get(id), patch);
+ records.tracks.set(id, next);
+ return next;
+ },
+ };
+});
+
+import { createTrackWithAlbum, updateTrackWithAlbum, removeTrackFromAlbum } from './trackAlbumMembership.js';
+
+const now = '2026-01-01T00:00:00.000Z';
+
+function seedAlbum(id, count) {
+ const album = buildAlbumRecord({
+ title: 'Example Album', trackIds: Array.from({ length: count }, (_, i) => `track-example-${i}`),
+ }, { id, now });
+ records.albums.set(id, album);
+ return album;
+}
+
+function seedAssignedTrack() {
+ const track = buildTrackRecord({ title: 'Example Track', albumId: 'album-old' }, { id: 'track-existing', now });
+ const album = buildAlbumRecord({ title: 'Previous Album', trackIds: [track.id] }, { id: track.albumId, now });
+ records.tracks.set(track.id, track);
+ records.albums.set(album.id, album);
+ return { track, album };
+}
+
+describe('track album membership through the stored record contract', () => {
+ beforeEach(() => {
+ records.albums.clear();
+ records.tracks.clear();
+ });
+
+ it('rejects a create into a full album before persisting a track', async () => {
+ const album = seedAlbum('album-full', TRACK_IDS_MAX);
+ await expect(createTrackWithAlbum({ title: 'New Track', albumId: album.id }))
+ .rejects.toMatchObject({ status: 409, code: 'ALBUM_FULL' });
+ expect(records.tracks.size).toBe(0);
+ expect(records.albums.get(album.id)).toEqual(album);
+ });
+
+ it('preserves the prior track and both albums when moving into a full album', async () => {
+ const { track, album: prior } = seedAssignedTrack();
+ const full = seedAlbum('album-full', TRACK_IDS_MAX);
+ await expect(updateTrackWithAlbum(track, { title: 'Changed', albumId: full.id }))
+ .rejects.toMatchObject({ status: 409, code: 'ALBUM_FULL' });
+ expect(records.tracks.get(track.id)).toEqual(track);
+ expect(records.albums.get(prior.id)).toEqual(prior);
+ expect(records.albums.get(full.id)).toEqual(full);
+ });
+
+ it('fills the last slot and accepts re-selecting that member in the full album', async () => {
+ const album = seedAlbum('album-last-slot', TRACK_IDS_MAX - 1);
+ const { track } = await createTrackWithAlbum({ title: 'Last Track', albumId: album.id });
+ expect(track.albumId).toBe(album.id);
+ const reselected = await updateTrackWithAlbum(track, { albumId: album.id });
+ expect(reselected.albumId).toBe(album.id);
+ expect(records.albums.get(album.id).trackIds).toEqual([...album.trackIds, track.id]);
+ });
+
+ it('rejects a missing destination without removing existing membership', async () => {
+ const { track, album } = seedAssignedTrack();
+ await expect(updateTrackWithAlbum(track, { albumId: 'album-missing' }))
+ .rejects.toMatchObject({ status: 404, code: 'ALBUM_NOT_FOUND' });
+ expect(records.tracks.get(track.id)).toEqual(track);
+ expect(records.albums.get(album.id)).toEqual(album);
+ });
+
+ it('moves a track between albums, appending to the destination and dropping the source', async () => {
+ const { track, album: prior } = seedAssignedTrack();
+ const next = seedAlbum('album-next', 2);
+ const moved = await updateTrackWithAlbum(track, { albumId: next.id });
+ expect(moved.albumId).toBe(next.id);
+ expect(records.albums.get(next.id).trackIds).toEqual([...next.trackIds, track.id]);
+ expect(records.albums.get(prior.id).trackIds).toEqual([]);
+ });
+
+ it('keeps completed audio as a single when its destination album is unavailable', async () => {
+ const { track, albumAssignmentError } = await createTrackWithAlbum(
+ { title: 'Rendered Track', albumId: 'album-missing' },
+ { preserveUnassigned: true },
+ );
+ expect(track.albumId).toBe('');
+ expect(albumAssignmentError).toEqual({ code: 'ALBUM_NOT_FOUND', message: 'Album not found' });
+ expect(records.tracks.get(track.id)).toEqual(track);
+ });
+
+ it('removes a track from its album and ignores an album that no longer exists', async () => {
+ const { track, album } = seedAssignedTrack();
+ await removeTrackFromAlbum(track.id, album.id);
+ expect(records.albums.get(album.id).trackIds).toEqual([]);
+ await expect(removeTrackFromAlbum(track.id, 'album-missing')).resolves.toBeUndefined();
+ });
+});