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: keep music takes coherent in backup snapshots (#9980)

[._.]/ Adam Eivyf750c9afcee2
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 3a5e9b6380..3428dd0130 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -5,6 +5,23 @@ PortOS backs up two things together, into a single timestamped snapshot:
1. **Filesystem data** — an rsync mirror of `./data/` (with SHA-256 manifest).
2. **PostgreSQL** — a `pg_dump` logical dump (`portos-db.sql`) written alongside the snapshot.
+### Consistency while assets are changing
+
+The backup service closes a process-local publication boundary before copying
+`data/`, drains music-track take publications already in progress, and keeps
+new take publications waiting through the SQL dump and manifest write. Browser
+code takes, SuperCollider takes, chiptune renders, and painted-waveform renders
+stage encoding outside that boundary, then publish their final audio bytes and
+track row together inside it. Manual and scheduled backups use the same cut.
+
+This is the first slice of [the cross-store consistency work](https://github.com/atomantic/PortOS/issues/9923). Media-job completion, other durable asset
+replacement/deletion paths, and database maintenance are tracked as separate
+children. Until those owners are covered, `status: ok` reports that the file
+copy, manifest, and database dump completed; it does not assert that every
+database asset reference resolves to the captured filesystem bytes. A restore
+operator should verify affected assets before treating a snapshot as a complete
+recovery point.
+
Now that PostgreSQL is a **required** dependency (it owns the creative catalog, memory, and a growing set of app-native records — see [Storage Classification Contract](./STORAGE.md)), **the database dump is part of required system state, not an optional extra.** A snapshot that captured `data/` but failed to capture the DB is incomplete, and PortOS surfaces that explicitly.
The dump includes the machine-local `cos_pending_agent_feedback` reference index and `review_queue_triage` presentation markers. The queue's source records remain in their owning stores; restoring the dump therefore preserves snooze/dismissal decisions without exporting them through federation or duplicating source payloads.
diff --git a/server/lib/README.md b/server/lib/README.md
index c2724dbf51..6895697ead 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -621,6 +621,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
+| `backupSnapshotBoundary.js` | `withBackupAssetPublication(work)` admits a complete durable file-plus-row mutation; `acquireBackupSnapshotCut()` drains admitted work and pauses new publication through backup's file copy, database dump, and manifest. Nested mutation calls reuse their lease. |
| `backupConfig.js` | `resolveBackupConfig(settings.backup)` + `DEFAULT_BACKUP_CRON` — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted `enabled` means enabled, a missing/blank `cronExpression` means midnight (`0 0 * * *`), and `scheduled` additionally requires a `destPath`. Also `resolveRetentionCount(settings.backup)` + `DEFAULT_RETENTION_COUNT`/`MIN_RETENTION_COUNT`/`MAX_RETENTION_COUNT` (#8334): per-source completed-snapshot retention, where an omitted or `null` `retentionCount` means unlimited — a NEW install ships the `30` default on disk via `data.reference/settings.json`, never invented here for an absent value. Read-time resolution only — nothing on disk changes. Shared by `services/backupScheduler.js` (registration + handler eligibility, and the retention count `services/backup.js#runBackup` prunes with) and `routes/settings.js` (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults. |
| `systemIdle.js` | `summarizeSystemActivity(processingSnapshot)` → `{ idle, activeCount, queuedCount, blockers[] }` + `describeActivityBlockers` — the ONE definition of "is this install doing anything", derived from the `/api/system/processing` snapshot. Queued work counts as active. Rendered by the dashboard's Live activity widget and refused on by the unattended auto-updater, so the two can never disagree about a window in which PortOS may restart itself. Every blocker label is generated prose (a count and a noun); no snapshot content is echoed. |
| `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |
diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.js
new file mode 100644
index 0000000000..92cf665e23
--- /dev/null
+++ b/server/lib/backupSnapshotBoundary.js
@@ -0,0 +1,84 @@
+/**
+ * Process-local admission for durable file-plus-row publications during backup.
+ * Callers hold one mutation lease across BOTH stores, not around individual
+ * filesystem or SQL operations. The backup closes admission before rsync and
+ * keeps it closed through the database dump and manifest write.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+const publicationScope = new AsyncLocalStorage();
+const DEFAULT_DRAIN_TIMEOUT_MS = 120_000;
+let admitted = 0;
+let cutRequested = false;
+let cutActive = false;
+let drainWaiters = [];
+let publicationWaiters = [];
+
+function releasePublications() {
+ const waiters = publicationWaiters;
+ publicationWaiters = [];
+ for (const resolve of waiters) resolve();
+}
+
+/** Hold one admission across an entire file-plus-row workflow. Nested calls reuse it. */
+export async function withBackupAssetPublication(work) {
+ if (publicationScope.getStore()?.active) return work();
+ while (cutRequested || cutActive) {
+ await new Promise(resolve => publicationWaiters.push(resolve));
+ }
+ admitted += 1;
+ const lease = { active: true };
+ try {
+ return await publicationScope.run(lease, work);
+ } finally {
+ lease.active = false;
+ admitted -= 1;
+ if (admitted === 0) {
+ const waiters = drainWaiters;
+ drainWaiters = [];
+ for (const resolve of waiters) resolve();
+ }
+ }
+}
+
+/**
+ * Close admission and drain already admitted workflows before copying files.
+ * The returned release function owns only this cut. A timed-out drain reopens
+ * admission and rejects, so runBackup marks its incomplete snapshot failed.
+ */
+export async function acquireBackupSnapshotCut({ timeoutMs = DEFAULT_DRAIN_TIMEOUT_MS } = {}) {
+ if (cutRequested || cutActive) throw new Error('Backup snapshot cut already owned');
+ cutRequested = true;
+ if (admitted > 0) {
+ let timer;
+ let onDrained;
+ try {
+ await Promise.race([
+ new Promise(resolve => {
+ onDrained = resolve;
+ drainWaiters.push(resolve);
+ }),
+ new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error('Timed out draining asset publications for backup')), timeoutMs);
+ timer.unref?.();
+ }),
+ ]);
+ } catch (error) {
+ cutRequested = false;
+ releasePublications();
+ throw error;
+ } finally {
+ clearTimeout(timer);
+ drainWaiters = drainWaiters.filter(resolve => resolve !== onDrained);
+ }
+ }
+ cutActive = true;
+ cutRequested = false;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ cutActive = false;
+ releasePublications();
+ };
+}
diff --git a/server/lib/backupSnapshotBoundary.test.js b/server/lib/backupSnapshotBoundary.test.js
new file mode 100644
index 0000000000..2f739705dc
--- /dev/null
+++ b/server/lib/backupSnapshotBoundary.test.js
@@ -0,0 +1,54 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { acquireBackupSnapshotCut, withBackupAssetPublication } from './backupSnapshotBoundary.js';
+
+const deferred = () => {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+};
+
+afterEach(() => vi.useRealTimers());
+
+describe('backup snapshot publication admission', () => {
+ it('drains a whole admitted workflow and holds a new one through the cut', async () => {
+ const rowWrite = deferred();
+ const first = withBackupAssetPublication(async () => {
+ await withBackupAssetPublication(async () => rowWrite.promise);
+ return 'published';
+ });
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => {
+ cutReady = true;
+ return release;
+ });
+ let secondStarted = false;
+ const second = withBackupAssetPublication(() => { secondStarted = true; });
+ await Promise.resolve();
+ expect(cutReady).toBe(false);
+ expect(secondStarted).toBe(false);
+
+ rowWrite.resolve();
+ expect(await first).toBe('published');
+ const release = await cut;
+ expect(secondStarted).toBe(false);
+ release();
+ await second;
+ expect(secondStarted).toBe(true);
+ });
+
+ it('reopens admission when an admitted workflow cannot drain', async () => {
+ vi.useFakeTimers();
+ const rowWrite = deferred();
+ const first = withBackupAssetPublication(() => rowWrite.promise);
+ const cut = acquireBackupSnapshotCut({ timeoutMs: 100 });
+ const rejected = expect(cut).rejects.toThrow('Timed out draining asset publications');
+ const next = vi.fn();
+ const waiting = withBackupAssetPublication(next);
+ await vi.advanceTimersByTimeAsync(100);
+ await rejected;
+ await waiting;
+ expect(next).toHaveBeenCalledOnce();
+ rowWrite.resolve();
+ await first;
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index cfc2e53f67..bbe62f320d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -606,6 +606,7 @@ export * from './vaultCrypto.js';
// === Model & config ===
export * from './backupConfig.js';
+export * from './backupSnapshotBoundary.js';
export * from './systemIdle.js';
export * from './browserConfig.js';
export * from './buildId.js';
diff --git a/server/services/backup.js b/server/services/backup.js
index 19559c84ef..4019e6709c 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -16,6 +16,7 @@ import { hostname, tmpdir } from 'os';
import { basename, join, resolve, relative, isAbsolute } from 'path';
import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256File } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { acquireBackupSnapshotCut } from '../lib/backupSnapshotBoundary.js';
import { createLineReader } from '../lib/streamLines.js';
import { getEvent } from './eventScheduler.js';
import { POOL_CONFIG, checkHealth, databaseRestoreRecovery, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';
@@ -626,18 +627,25 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
await writeFile(markerPath(snapshotDir), '');
dashboardEvents.emit('backup:changed');
- const excludeFlags = effectiveExcludes.flatMap(p => ['--exclude', p]);
- changedFiles = await runRsync(PATHS.data, dataDestDir, excludeFlags);
- console.log(`💾 Backup rsync complete: ${changedFiles.length} files changed (exit 0)`);
-
- // Dump PostgreSQL alongside the file backup. Result is NO LONGER swallowed —
- // a configured-but-failed dump must degrade the backup and alert the user.
- const pgDumpPath = join(snapshotDir, 'portos-db.sql');
- const pgResult = await dumpPostgres(pgDumpPath);
-
- manifest = await generateManifest(dataDestDir, join(snapshotDir, 'manifest.json'), pgDumpPath, {
- allowMissingDump: pgResult.status === 'skipped' || pgResult.status === 'failed'
- });
+ // Freeze admitted file-plus-row publications across both stores. A writer
+ // that started first drains completely; new writers wait until the dump
+ // and manifest are published. Rendering/provider work is outside admission.
+ const releaseSnapshotCut = await acquireBackupSnapshotCut();
+ let pgResult;
+ try {
+ const excludeFlags = effectiveExcludes.flatMap(p => ['--exclude', p]);
+ changedFiles = await runRsync(PATHS.data, dataDestDir, excludeFlags);
+ console.log(`💾 Backup rsync complete: ${changedFiles.length} files changed (exit 0)`);
+
+ // A configured-but-failed dump degrades the backup and alerts the user.
+ const pgDumpPath = join(snapshotDir, 'portos-db.sql');
+ pgResult = await dumpPostgres(pgDumpPath);
+ manifest = await generateManifest(dataDestDir, join(snapshotDir, 'manifest.json'), pgDumpPath, {
+ allowMissingDump: pgResult.status === 'skipped' || pgResult.status === 'failed'
+ });
+ } finally {
+ releaseSnapshotCut();
+ }
const status = backupStatusForPg(pgResult);
const lastRun = new Date().toISOString();
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 4d350a89c1..2f69054137 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -3252,6 +3252,50 @@ describe('runBackup lifecycle', () => {
]);
});
+ it('keeps a newly admitted music take out of both halves of a snapshot', async () => {
+ const fsp = await actualFs();
+ const { withBackupAssetPublication } = await import('../lib/backupSnapshotBoundary.js');
+ const sourceMusic = joinPath(dataRoot, 'music');
+ await fsp.mkdir(sourceMusic, { recursive: true });
+ await fsp.writeFile(joinPath(sourceMusic, 'old.wav'), 'old audio');
+ let rowFilename = 'old.wav';
+ const rsync = fakeProc();
+ const pg = fakeProc();
+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
+ spawn.mockReturnValueOnce(rsync).mockReturnValueOnce(pg);
+
+ const pending = runBackup(destRoot);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ const snapshotDir = await findSnapshotDir();
+ const capturedMusic = joinPath(snapshotDir, 'data', 'music');
+ await fsp.mkdir(capturedMusic, { recursive: true });
+ await fsp.copyFile(joinPath(sourceMusic, rowFilename), joinPath(capturedMusic, rowFilename));
+
+ let published = false;
+ const newTake = withBackupAssetPublication(async () => {
+ await fsp.writeFile(joinPath(sourceMusic, 'new.wav'), 'new audio');
+ rowFilename = 'new.wav';
+ published = true;
+ });
+ await Promise.resolve();
+ expect(published).toBe(false);
+
+ rsync.emit('close', 0);
+ await waitFor(() => spawn.mock.calls.length === 2, 'pg_dump spawn');
+ const capturedRow = rowFilename;
+ const dumpPath = spawn.mock.calls[1][1][spawn.mock.calls[1][1].indexOf('-f') + 1];
+ await fsp.writeFile(dumpPath, `CREATE TABLE public.tracks (audio_filename text);\nCOPY public.tracks (audio_filename) FROM stdin;\n${capturedRow}\n\\.\n`);
+ pg.emit('close', 0);
+ await pending;
+ await newTake;
+
+ expect(capturedRow).toBe('old.wav');
+ expect(await fsp.readFile(joinPath(capturedMusic, capturedRow), 'utf8')).toBe('old audio');
+ await expect(fsp.access(joinPath(capturedMusic, 'new.wav'))).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(rowFilename).toBe('new.wav');
+ expect(published).toBe(true);
+ });
+
it.each([
['data readdir', 'EIO'],
['data readdir', 'EACCES'],
diff --git a/server/services/chiptune.js b/server/services/chiptune.js
index d738e00001..b3642eb28e 100644
--- a/server/services/chiptune.js
+++ b/server/services/chiptune.js
@@ -15,15 +15,15 @@
*/
import { stat } from 'fs/promises';
-import { randomUUID } from 'crypto';
import { join, resolve, isAbsolute } from 'path';
import { ServerError } from '../lib/errorHandler.js';
-import { PATHS, atomicWrite, isPathInsideDir } from '../lib/fileUtils.js';
+import { atomicWrite, isPathInsideDir } from '../lib/fileUtils.js';
import { writeWavAudioFile } from '../lib/wavAudioFile.js';
import { chiptuneScoreSchema, CHIPTUNE_LIMITS, CHIPTUNE_NOISE_PRESETS, scoreDurationSec } from '../lib/chiptuneScore.js';
import { renderScoreToWav } from '../lib/chiptuneRender.js';
import { resolveProviderAndModel, assertProvider, runPromptThroughProvider } from './promptRunner.js';
import * as tracks from './tracks/index.js';
+import { publishMusicTake } from './musicTakePublication.js';
import { getAppById, PORTOS_APP_ID } from './apps.js';
export const DEFAULT_PUBLISH_SUBDIR = 'game/assets/music';
@@ -126,11 +126,10 @@ const renderScoreToFile = (score, dir, basename) => writeWavAudioFile(renderScor
export async function renderChiptuneTrack({ trackId }) {
const track = await requireTrack(trackId);
const score = requireScore(track);
- const filename = await renderScoreToFile(score, PATHS.music, `music-${randomUUID()}`);
+ const wav = renderScoreToWav(score);
const durationSec = Math.max(1, Math.round(scoreDurationSec(score)));
-
- const updated = await tracks.appendActiveTake(trackId, {
- audioFilename: filename, prompt: track.chiptunePrompt, engine: 'chiptune', durationSec,
+ const { track: updated, filename } = await publishMusicTake({
+ trackId, wav, take: { prompt: track.chiptunePrompt, engine: 'chiptune', durationSec },
});
return { track: updated, filename, durationSec };
}
diff --git a/server/services/musicCode.js b/server/services/musicCode.js
index 783b0f5fec..ae86d394a3 100644
--- a/server/services/musicCode.js
+++ b/server/services/musicCode.js
@@ -17,15 +17,14 @@
* press in the same request (AI Provider Usage Policy: no cold bootstrap).
*/
-import { randomUUID } from 'crypto';
import { ServerError } from '../lib/errorHandler.js';
-import { PATHS } from '../lib/fileUtils.js';
import { trimTo } from '../lib/textUtils.js';
-import { wavDurationMs, writeWavAudioFile } from '../lib/wavAudioFile.js';
+import { wavDurationMs } from '../lib/wavAudioFile.js';
import { readFile } from 'fs/promises';
import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
import * as tracks from './tracks/index.js';
import { readSuperColliderPreview } from './superColliderRender.js';
+import { publishMusicTake } from './musicTakePublication.js';
const CODE_ENGINE = 'code';
// Strudel was the first language; Tone.js the second; SuperCollider is rendered server-side (contained, offline; no browser frame) (client/src/components/music/strudelFrame.js
@@ -166,11 +165,11 @@ export async function saveCodeTakeToTrack({ trackId, wav, prompt, title }) {
const track = await tracks.getTrack(trackId);
if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
- const filename = await writeWavAudioFile(wav, PATHS.music, `music-${randomUUID()}`);
const durationSec = Math.max(1, Math.round(durationMs / 1000));
- const updated = await tracks.appendActiveTake(trackId, {
- audioFilename: filename, prompt: prompt || track.prompt, engine: CODE_ENGINE, durationSec,
- }, title ? { title } : {});
+ const { track: updated, filename } = await publishMusicTake({
+ trackId, wav, take: { prompt: prompt || track.prompt, engine: CODE_ENGINE, durationSec },
+ patch: title ? { title } : {},
+ });
if (!updated) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
console.log(`🎹 Saved code-rendered take (${durationSec}s)`);
return { track: updated, filename, durationSec };
@@ -193,23 +192,25 @@ export async function saveSuperColliderTakeToTrack({ trackId, jobId, prompt, tit
if (!durationMs) throw new ServerError('The preview is not a PCM WAV file', { status: 400, code: 'MUSIC_CODE_TAKE_NOT_WAV' });
const { preview } = found;
- const filename = await writeWavAudioFile(wav, PATHS.music, `music-${randomUUID()}`);
const durationSec = Math.max(1, Math.round(durationMs / 1000));
- const updated = await tracks.appendActiveTake(trackId, {
- audioFilename: filename,
- prompt: prompt || track.prompt,
- engine: CODE_ENGINE,
- durationSec,
- codeProvenance: {
- language: preview.language,
- source: preview.source,
- sourceHash: preview.sourceHash,
- seed: preview.seed,
- runtimeVersion: preview.runtime?.version,
- policyVersion: preview.runtime?.policyVersion,
- settings: preview.settings,
+ const { track: updated, filename } = await publishMusicTake({
+ trackId, wav,
+ take: {
+ prompt: prompt || track.prompt,
+ engine: CODE_ENGINE,
+ durationSec,
+ codeProvenance: {
+ language: preview.language,
+ source: preview.source,
+ sourceHash: preview.sourceHash,
+ seed: preview.seed,
+ runtimeVersion: preview.runtime?.version,
+ policyVersion: preview.runtime?.policyVersion,
+ settings: preview.settings,
+ },
},
- }, title ? { title } : {});
+ patch: title ? { title } : {},
+ });
if (!updated) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
console.log(`🎛️ Saved SuperCollider take (${durationSec}s, seed ${preview.seed})`);
return { track: updated, filename, durationSec };
diff --git a/server/services/musicTakePublication.js b/server/services/musicTakePublication.js
new file mode 100644
index 0000000000..ba23264b0c
--- /dev/null
+++ b/server/services/musicTakePublication.js
@@ -0,0 +1,28 @@
+/** Stage potentially slow audio encoding outside the backup cut, then publish
+ * its final bytes and track row under one admission lease. */
+import { randomUUID } from 'node:crypto';
+import { constants } from 'node:fs';
+import { copyFile, mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
+import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { writeWavAudioFile } from '../lib/wavAudioFile.js';
+import * as tracks from './tracks/index.js';
+
+export async function publishMusicTake({ trackId, wav, take, patch = {} }) {
+ const stageDir = await mkdtemp(join(tmpdir(), 'portos-music-take-'));
+ try {
+ const filename = await writeWavAudioFile(wav, stageDir, `music-${randomUUID()}`);
+ return await withBackupAssetPublication(async () => {
+ await ensureDir(PATHS.music);
+ await copyFile(join(stageDir, filename), join(PATHS.music, filename), constants.COPYFILE_EXCL);
+ const track = Object.keys(patch).length
+ ? await tracks.appendActiveTake(trackId, { ...take, audioFilename: filename }, patch)
+ : await tracks.appendActiveTake(trackId, { ...take, audioFilename: filename });
+ return { track, filename };
+ });
+ } finally {
+ await rm(stageDir, { recursive: true, force: true });
+ }
+}
diff --git a/server/services/musicTakePublication.test.js b/server/services/musicTakePublication.test.js
new file mode 100644
index 0000000000..9dacd10237
--- /dev/null
+++ b/server/services/musicTakePublication.test.js
@@ -0,0 +1,47 @@
+import { afterAll, beforeEach, expect, it, vi } from 'vitest';
+import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const musicDir = await mkdtemp(join(tmpdir(), 'portos-take-publication-test-'));
+
+vi.mock('../lib/fileUtils.js', async importOriginal => ({
+ ...(await importOriginal()),
+ PATHS: { ...(await importOriginal()).PATHS, music: musicDir },
+}));
+vi.mock('../lib/wavAudioFile.js', () => ({
+ writeWavAudioFile: vi.fn(async (wav, dir, base) => {
+ const filename = `${base}.wav`;
+ await writeFile(join(dir, filename), wav);
+ return filename;
+ }),
+}));
+vi.mock('./tracks/index.js', () => ({
+ appendActiveTake: vi.fn(async (id, take) => ({ id, ...take })),
+}));
+
+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+const { writeWavAudioFile } = await import('../lib/wavAudioFile.js');
+const { appendActiveTake } = await import('./tracks/index.js');
+const { publishMusicTake } = await import('./musicTakePublication.js');
+
+afterAll(async () => { await rm(musicDir, { recursive: true, force: true }); });
+beforeEach(() => vi.clearAllMocks());
+
+it('stages encoding outside the cut and publishes bytes with the track row after release', async () => {
+ const release = await acquireBackupSnapshotCut();
+ const pending = publishMusicTake({
+ trackId: 'track-1', wav: Buffer.from('synthetic audio'),
+ take: { engine: 'code', durationSec: 1 },
+ });
+ try {
+ await vi.waitFor(() => expect(writeWavAudioFile).toHaveBeenCalledOnce());
+ expect(await readdir(musicDir)).toEqual([]);
+ expect(appendActiveTake).not.toHaveBeenCalled();
+ } finally {
+ release();
+ }
+ const { track, filename } = await pending;
+ expect(track.audioFilename).toBe(filename);
+ expect(await readFile(join(musicDir, filename), 'utf8')).toBe('synthetic audio');
+});
diff --git a/server/services/musicWaveform.js b/server/services/musicWaveform.js
index d7f0672fd3..cecbf81b11 100644
--- a/server/services/musicWaveform.js
+++ b/server/services/musicWaveform.js
@@ -29,15 +29,12 @@
* Provider Usage Policy — no cold bootstrap).
*/
-import { randomUUID } from 'crypto';
import { mkdtemp, rm } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
-import { PATHS } from '../lib/fileUtils.js';
import { trimTo } from '../lib/textUtils.js';
import { pcmToWavBuffer } from '../lib/chiptuneRender.js';
-import { writeWavAudioFile } from '../lib/wavAudioFile.js';
import { WAVE_SKETCH_SAMPLE_RATE, synthesizeSketchChannels } from '../lib/waveSketch.js';
import {
PAINTED_CANVAS_DECLICK_SEC, PAINTED_CANVAS_LIMITS, PAINTED_CANVAS_MASTER_GAIN, PAINTED_CANVAS_SAMPLE_RATE,
@@ -46,6 +43,7 @@ import {
import { spectrogramPixels } from '../lib/spectrogramImage.js';
import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
import * as tracks from './tracks/index.js';
+import { publishMusicTake } from './musicTakePublication.js';
const WAVEFORM_ENGINE = 'waveform';
const DEFAULT_CANVAS_SEC = 20;
@@ -365,11 +363,12 @@ export async function renderWaveSketchToTrack({ trackId, prompt, title }) {
}
const wav = pcmToWavBuffer(synthesizeSketchChannels(normalized), { sampleRate: WAVE_SKETCH_SAMPLE_RATE });
- const filename = await writeWavAudioFile(wav, PATHS.music, `music-${randomUUID()}`);
const durationSec = Math.max(1, Math.round(normalized.durationSec));
- const updated = await tracks.appendActiveTake(trackId, {
- audioFilename: filename, prompt: prompt || track.waveSketchPrompt || track.prompt, engine: WAVEFORM_ENGINE, durationSec,
- }, title ? { title } : {});
+ const { track: updated, filename } = await publishMusicTake({
+ trackId, wav,
+ take: { prompt: prompt || track.waveSketchPrompt || track.prompt, engine: WAVEFORM_ENGINE, durationSec },
+ patch: title ? { title } : {},
+ });
if (!updated) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
console.log(`🎨 Rendered painted take (${durationSec}s)`);
return { track: updated, filename, durationSec };