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: recover accepted Code Animation output after history failures (#10661)

Adam Eivy6c30314ad4e2
diff --git a/client/src/components/codeAnimation/ProductionAcceptance.jsx b/client/src/components/codeAnimation/ProductionAcceptance.jsx
index 6042f593ce..2a016cf1fd 100644
--- a/client/src/components/codeAnimation/ProductionAcceptance.jsx
+++ b/client/src/components/codeAnimation/ProductionAcceptance.jsx
@@ -21,7 +21,7 @@ export default function ProductionAcceptance({ projectId, disabled, onProject, o
});
const data = resource.data;
if (!data) return resource.error ? <p role="alert" className="text-xs text-port-error">{resource.error.message}</p> : null;
- const { accepted, runs } = data;
+ const { accepted, runs, acceptanceProjection } = data;
const chosen = (params.get('compare') || '').split(',').filter(Boolean);
const selected = chosen.map(id => runs.find(run => run.runId === id)).filter(Boolean);
const toggle = runId => {
@@ -31,7 +31,14 @@ export default function ProductionAcceptance({ projectId, disabled, onProject, o
setParams(next, { replace: true });
};
const promote = runId => act(async () => {
- onProject(await acceptCodeAnimationOutput(projectId, runId, { silent: true }));
+ const project = await acceptCodeAnimationOutput(projectId, runId, { silent: true });
+ onProject(project);
+ resource.updateData(previous => ({
+ ...previous,
+ accepted: { ...project.acceptedOutput, fresh: true, stale: [] },
+ acceptanceProjection: project.acceptanceProjection,
+ runs: previous.runs.map(run => ({ ...run, accepted: run.runId === project.acceptedOutput.runId })),
+ }));
await resource.refetch();
});
return <section className="space-y-3 rounded border border-port-border p-3" aria-label="Production acceptance">
@@ -43,12 +50,17 @@ export default function ProductionAcceptance({ projectId, disabled, onProject, o
<p>Earlier passing evidence is stale. The accepted video still plays, but it is no longer verified.</p>
{accepted.stale.map(item => <p key={item.dimension}>{item.reason}</p>)}
</div>}
+ {acceptanceProjection?.status === 'pending' && <div role="status" className="space-y-2 rounded border border-port-warning p-2 text-xs text-port-warning">
+ <p>Acceptance saved. Media History synchronization is pending; your accepted video is still available. Repair Media History storage, then retry synchronization or reopen this view.</p>
+ <button type="button" className={buttonClass} disabled={disabled || busy || resource.loading} onClick={() => act(() => resource.refetch())}>Retry Media History sync</button>
+ </div>}
+ {resource.error && <p role="alert" className="text-xs text-port-error">{resource.error.message}</p>}
<EvidenceGrid evidence={accepted.evidence} />
<div className="flex flex-wrap gap-2">
<button type="button" className={buttonClass} disabled={disabled || busy} onClick={() => onDownloadSource(accepted.revisionId)}>Download source bundle</button>
<a className={`${buttonClass} inline-block`} href={accepted.path} download>Download accepted MP4</a>
</div>
- <p className="text-xs text-gray-400">This video is in Media History as <code>{accepted.videoId}</code>; Music Video Studio and Creative Director can use it without a song or episode project.</p>
+ {acceptanceProjection?.status !== 'pending' && <p className="text-xs text-gray-400">This video is in Media History as <code>{accepted.videoId}</code>; Music Video Studio and Creative Director can use it without a song or episode project.</p>}
</div> : <p className="text-xs text-gray-400">No output has been accepted. Accept a passing run below; failed runs never replace an accepted output.</p>}
<h3 className="text-sm font-semibold">Runs to compare</h3>
{runs.length === 0 && <p className="text-xs text-gray-400">Run production stages to produce evidence.</p>}
diff --git a/client/src/components/codeAnimation/ProductionAcceptance.test.jsx b/client/src/components/codeAnimation/ProductionAcceptance.test.jsx
index 7b26e28adf..7c01bc8a63 100644
--- a/client/src/components/codeAnimation/ProductionAcceptance.test.jsx
+++ b/client/src/components/codeAnimation/ProductionAcceptance.test.jsx
@@ -40,7 +40,7 @@ describe('Production acceptance', () => {
const user = userEvent.setup();
const low = run('cccccccc-3', { settings: { requested: { providerId: 'example', model: 'example-model', effort: 'low' }, effective: { providerId: 'example', model: 'example-model', effort: 'low' }, renderer: null }, spend: { repairs: 5, tokens: 900, renderMs: 4000, elapsedMs: 9000, diskBytes: 2048 } });
api.getCodeAnimationAcceptance.mockResolvedValue({ accepted: null, runs: [run('dddddddd-4'), low] });
- api.acceptCodeAnimationOutput.mockResolvedValue({ id: 'p1' });
+ api.acceptCodeAnimationOutput.mockResolvedValue({ id: 'p1', acceptedOutput: { ...frozen, runId: 'cccccccc-3' } });
renderIt();
await user.click(await screen.findByLabelText(/Run dddddddd/));
await user.click(screen.getByLabelText(/Run cccccccc/));
@@ -55,4 +55,25 @@ describe('Production acceptance', () => {
await user.click(screen.getByRole('button', { name: /Accept output of run cccccccc/ }));
expect(api.acceptCodeAnimationOutput).toHaveBeenCalledWith('p1', 'cccccccc-3', { silent: true });
});
+ it('applies committed acceptance immediately and keeps playback plus a sync retry when the refresh fails', async () => {
+ const user = userEvent.setup();
+ const onProject = vi.fn();
+ api.getCodeAnimationAcceptance.mockResolvedValueOnce({ accepted: null, runs: [run(frozen.runId)] })
+ .mockRejectedValueOnce(new Error('Synthetic read failure'));
+ const project = { id: 'p1', acceptedOutput: frozen, acceptanceProjection: { decisionId: 'decision-1', status: 'pending' } };
+ api.acceptCodeAnimationOutput.mockResolvedValue(project);
+ renderIt({ onProject });
+ await user.click(await screen.findByRole('button', { name: /Accept output of run/ }));
+ expect(onProject).toHaveBeenCalledWith(project);
+ expect(await screen.findByLabelText('Accepted final video')).toHaveAttribute('src', frozen.path);
+ expect(screen.getByRole('status')).toHaveTextContent('Acceptance saved. Media History synchronization is pending');
+ expect(await screen.findByRole('alert')).toHaveTextContent('Synthetic read failure');
+ expect(screen.queryByText(/This video is in Media History/)).not.toBeInTheDocument();
+ api.getCodeAnimationAcceptance.mockResolvedValue({ accepted: frozen, runs: [run(frozen.runId, { accepted: true })], acceptanceProjection: { decisionId: 'decision-1', status: 'synced' } });
+ await user.click(screen.getByRole('button', { name: 'Retry Media History sync' }));
+ expect(await screen.findByText(/This video is in Media History/)).toBeInTheDocument();
+ expect(screen.queryByRole('status')).not.toBeInTheDocument();
+ expect(api.acceptCodeAnimationOutput).toHaveBeenCalledTimes(1);
+ });
+
});
diff --git a/server/services/codeAnimation/acceptance.db.test.js b/server/services/codeAnimation/acceptance.db.test.js
index cf1324a24b..07300142d3 100644
--- a/server/services/codeAnimation/acceptance.db.test.js
+++ b/server/services/codeAnimation/acceptance.db.test.js
@@ -1,12 +1,19 @@
/** Public acceptance routes: frozen promotion, stale detection, failed-run isolation and downstream discovery. */
-import { afterAll, describe, expect, it, vi } from 'vitest';
+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
import { chmod, mkdir, readFile, writeFile } from 'fs/promises';
import { createHash, randomUUID } from 'crypto';
import { join } from 'path';
import { lazyTempDataRoot, makePathsProxy, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';
vi.mock('../../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('animation-acceptance-') }));
-vi.mock('../../lib/fileUtils.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('animation-acceptance-') }));
+const historyFault = vi.hoisted(() => ({ beforeSave: null }));
+vi.mock('../../lib/fileUtils.js', async original => {
+ const actual = makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('animation-acceptance-') });
+ return { ...actual, atomicWrite: async (path, ...args) => {
+ if (path.endsWith('video-history.json')) await historyFault.beforeSave?.();
+ return actual.atomicWrite(path, ...args);
+ } };
+});
vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));
import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
import { requireDbOrSkip } from '../../lib/dbTestGate.js';
@@ -17,6 +24,10 @@ import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';
import { emitCodeAnimationChanged } from '../socket.js';
import { loadHistory, saveHistory } from '../videoGen/history.js';
import routes from '../../routes/codeAnimation.js';
+import * as store from './projectStore.js';
+import { acceptProductionOutput } from './acceptance.js';
+
+afterEach(() => { historyFault.beforeSave = null; vi.restoreAllMocks(); });
const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));
const ready = requireDbOrSkip('codeAnimation/acceptance.db.test', health.connected, health.error);
@@ -94,6 +105,85 @@ describe.skipIf(!ready)('Production acceptance', () => {
expect(assets).toMatchObject({ videoId: run.videoId, sourceHash: p.revision.sourceHash, packageUrl: `/api/code-animation/projects/${p.id}/revisions/${p.revision.id}/package` });
});
+ it.each(['read', 'save'])('returns committed acceptance on history %s failure and recovers from durable intent on the next read', async failure => {
+ const p = await project();
+ const old = await finishedRun(p);
+ await post(`/projects/${p.id}/accepted-output`, { runId: old.runId });
+ const imported = await post(`/projects/${p.id}/import`, createCodeAnimationPackage(manifest, [{ path: 'index.html', content: '<html><canvas>New source</canvas></html>' }]));
+ const next = await finishedRun({ id: p.id, revision: imported.body.revision });
+ const history = await loadHistory();
+ if (failure === 'read') await writeFile(join(PATHS.data, 'video-history.json'), '{broken');
+ else historyFault.beforeSave = () => { throw new Error('Synthetic ENOSPC'); };
+ vi.mocked(emitCodeAnimationChanged).mockClear();
+
+ const result = await post(`/projects/${p.id}/accepted-output`, { runId: next.runId });
+ expect(result).toMatchObject({ status: 200, body: {
+ acceptedOutput: { runId: next.runId }, acceptanceProjection: { status: 'pending' },
+ acceptedRevisionId: imported.body.revision.id, candidateRevisionId: null,
+ } });
+ expect(emitCodeAnimationChanged).toHaveBeenCalledWith(p.id);
+ const durable = await store.getProjectRecord(p.id);
+ expect(durable.acceptanceProjection).toEqual(result.body.acceptanceProjection);
+ const unavailable = (await get(`/projects/${p.id}/acceptance`)).body;
+ expect(unavailable).toMatchObject({ acceptanceProjection: { status: 'pending' }, accepted: { runId: next.runId, fresh: true, path: `/data/videos/${next.filename}` } });
+
+ historyFault.beforeSave = null;
+ await saveHistory(history);
+ // A fresh service instance has no in-memory queue/intent from the request,
+ // as after restart. Only the persisted project tells it what to recover.
+ const restarted = await import('./acceptance.js?recovery');
+ const recovered = failure === 'read'
+ ? await restarted.getProductionAcceptance(p.id)
+ : (await restarted.listAcceptedAssets({ limit: 50, offset: 0 })).items.find(item => item.projectId === p.id);
+ expect(recovered.acceptanceProjection).toMatchObject({ status: 'synced', decisionId: durable.acceptanceProjection.decisionId });
+ const after = await store.getProjectRecord(p.id);
+ expect(after.acceptedOutput).toEqual(durable.acceptedOutput);
+ expect(after.acceptedRevisionId).toBe(durable.acceptedRevisionId);
+ expect(after.candidateRevisionId).toBe(durable.candidateRevisionId);
+ expect((await loadHistory()).filter(entry => entry.codeAnimation?.acceptance?.projectId === p.id).map(entry => entry.id)).toEqual([next.videoId]);
+ await get(`/projects/${p.id}/acceptance`);
+ expect((await store.getProjectRecord(p.id)).acceptedOutput).toEqual(durable.acceptedOutput);
+ });
+
+ it('replays a history write after acknowledgement failure without changing the frozen decision', async () => {
+ const p = await project();
+ const run = await finishedRun(p);
+ vi.spyOn(store, 'acknowledgeAcceptanceProjection').mockRejectedValueOnce(new Error('Synthetic DB interruption'));
+ const result = await post(`/projects/${p.id}/accepted-output`, { runId: run.runId });
+ expect(result.body.acceptanceProjection.status).toBe('pending');
+ const projected = await loadHistory();
+ expect(projected.find(entry => entry.id === run.videoId).codeAnimation.acceptance.runId).toBe(run.runId);
+ expect((await get(`/projects/${p.id}/acceptance`)).body.acceptanceProjection.status).toBe('synced');
+ expect(await loadHistory()).toEqual(projected);
+ expect((await store.getProjectRecord(p.id)).acceptedOutput).toEqual(result.body.acceptedOutput);
+ });
+
+ it('serializes overlapping promotions and never acknowledges a newer decision with an older receipt', async () => {
+ const p = await project();
+ const first = await finishedRun(p);
+ const second = await finishedRun(p);
+ const entered = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ historyFault.beforeSave = async () => { entered.resolve(); await release.promise; };
+ const olderRequest = acceptProductionOutput(p.id, first.runId);
+ await entered.promise;
+ const older = await store.getProjectRecord(p.id);
+ const newerRequest = acceptProductionOutput(p.id, second.runId);
+ expect((await store.getProjectRecord(p.id)).acceptedOutput.runId).toBe(first.runId);
+ historyFault.beforeSave = () => { throw new Error('Synthetic ENOSPC'); };
+ release.resolve();
+ await olderRequest;
+ const newer = await newerRequest;
+ expect(newer).toMatchObject({ acceptedOutput: { runId: second.runId }, acceptanceProjection: { status: 'pending' } });
+ expect(newer.acceptanceProjection.decisionId).not.toBe(older.acceptanceProjection.decisionId);
+ await store.acknowledgeAcceptanceProjection(p.id, older.acceptanceProjection.decisionId);
+ expect((await store.getProjectRecord(p.id)).acceptanceProjection).toEqual(newer.acceptanceProjection);
+ historyFault.beforeSave = null;
+ await get('/accepted-assets');
+ expect((await loadHistory()).filter(entry => entry.codeAnimation?.acceptance?.projectId === p.id).map(entry => entry.id)).toEqual([second.videoId]);
+ expect((await store.getProjectRecord(p.id)).acceptedOutput).toEqual(newer.acceptedOutput);
+ });
+
it('refuses a failing run and keeps the accepted playback when a later candidate fails', async () => {
const p = await project();
const good = await finishedRun(p);
diff --git a/server/services/codeAnimation/acceptance.js b/server/services/codeAnimation/acceptance.js
index 62583b6e02..5533974b43 100644
--- a/server/services/codeAnimation/acceptance.js
+++ b/server/services/codeAnimation/acceptance.js
@@ -8,6 +8,7 @@ import { createHash } from 'crypto';
import { createReadStream } from 'fs';
import { join } from 'path';
import { acceptanceFreshness, acceptanceProblem, freezeAcceptance, summarizeRunForComparison } from '../../lib/codeAnimationAcceptance.js';
+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS } from '../../lib/paths.js';
import { emitCodeAnimationChanged } from '../socket.js';
@@ -19,6 +20,8 @@ import { STAGE_RUN_KIND } from './stages.js';
const RECENT_RUNS = 30;
const UNREADABLE = 'unreadable';
+// Serialize promotion and recovery through the entire DB → history → acknowledgement cycle.
+const queueAcceptance = createKeyCachedQueue();
const hashVideo = filename => new Promise(resolve => {
const digest = createHash('sha256');
@@ -42,62 +45,90 @@ async function currentHashes(projectId, frozen, run) {
}
export async function acceptProductionOutput(projectId, runId) {
- const project = await getProductionProject(projectId);
- const run = await store.getRunRecord(projectId, runId);
- if (!run || run.data.kind !== STAGE_RUN_KIND) throw new ServerError('Run not found', { status: 404, code: 'NOT_FOUND' });
- const problem = acceptanceProblem(run);
- if (problem) throw new ServerError(problem, { status: 409, code: 'CODE_ANIMATION_OUTPUT_NOT_ACCEPTABLE' });
- const renderHash = await hashVideo(run.data.output.filename);
- const measured = run.data.output.audioEvidence?.videoHash;
- if (renderHash === UNREADABLE || (measured && measured !== renderHash)) {
- throw new ServerError('The rendered video is missing or changed since the run measured it', { status: 409, code: 'CODE_ANIMATION_RENDER_CHANGED' });
- }
- const frozen = freezeAcceptance({ run, project, renderHash });
- const current = await currentHashes(projectId, frozen, run);
- const freshness = acceptanceFreshness(frozen, current);
- if (!freshness.fresh) {
- throw new ServerError(`The run's source or audio changed since it was measured: ${freshness.stale.map(item => item.reason).join(' ')}`, { status: 409, code: 'CODE_ANIMATION_EVIDENCE_STALE' });
- }
- const saved = await store.setAcceptedOutput(projectId, frozen);
- // Media History carries the accepted marker so Music Video Studio and Creative
- // Director can pick the short by its ordinary history id, with no song or episode project.
- await mutateVideoHistory(history => {
+ return queueAcceptance(projectId, async () => {
+ const project = await getProductionProject(projectId);
+ const run = await store.getRunRecord(projectId, runId);
+ if (!run || run.data.kind !== STAGE_RUN_KIND) throw new ServerError('Run not found', { status: 404, code: 'NOT_FOUND' });
+ const problem = acceptanceProblem(run);
+ if (problem) throw new ServerError(problem, { status: 409, code: 'CODE_ANIMATION_OUTPUT_NOT_ACCEPTABLE' });
+ const renderHash = await hashVideo(run.data.output.filename);
+ const measured = run.data.output.audioEvidence?.videoHash;
+ if (renderHash === UNREADABLE || (measured && measured !== renderHash)) {
+ throw new ServerError('The rendered video is missing or changed since the run measured it', { status: 409, code: 'CODE_ANIMATION_RENDER_CHANGED' });
+ }
+ const frozen = freezeAcceptance({ run, project, renderHash });
+ const current = await currentHashes(projectId, frozen, run);
+ const freshness = acceptanceFreshness(frozen, current);
+ if (!freshness.fresh) {
+ throw new ServerError(`The run's source or audio changed since it was measured: ${freshness.stale.map(item => item.reason).join(' ')}`, { status: 409, code: 'CODE_ANIMATION_EVIDENCE_STALE' });
+ }
+ const saved = await store.setAcceptedOutput(projectId, frozen);
+ const result = await reconcileProjection(saved, false);
+ // The acceptance is committed even when its history projection is pending.
+ emitCodeAnimationChanged(projectId);
+ return result;
+ });
+}
+
+/** Called under the project queue; the DB record is the only recovery intent. */
+async function reconcileProjection(project, notify = true) {
+ if (project.acceptanceProjection?.status !== 'pending') return project;
+ const frozen = project.acceptedOutput;
+ const projected = await mutateVideoHistory(history => {
+ if (!history.some(entry => entry?.id === frozen.videoId)) {
+ throw new Error('Accepted video is missing from Media History');
+ }
for (const entry of history) {
- if (entry?.codeAnimation?.acceptance?.projectId === projectId && entry.id !== frozen.videoId) delete entry.codeAnimation.acceptance;
+ if (entry?.codeAnimation?.acceptance?.projectId === project.id && entry.id !== frozen.videoId) delete entry.codeAnimation.acceptance;
if (entry?.id === frozen.videoId) {
entry.codeAnimation = { ...(entry.codeAnimation || {}), revisionId: frozen.revisionId, sourceHash: frozen.sourceHash,
- acceptance: { projectId, runId, sourceHash: frozen.sourceHash, audioHash: frozen.audioHash, renderHash, acceptedAt: frozen.acceptedAt } };
+ acceptance: { projectId: project.id, runId: frozen.runId, sourceHash: frozen.sourceHash,
+ audioHash: frozen.audioHash, renderHash: frozen.renderHash, acceptedAt: frozen.acceptedAt } };
}
}
return history;
- });
- emitCodeAnimationChanged(projectId);
- return saved;
+ }).then(() => store.acknowledgeAcceptanceProjection(project.id, project.acceptanceProjection.decisionId))
+ .catch(() => {
+ // Keep the durable intent for the next acceptance/discovery read, including
+ // an acknowledgement failure after a successful history write.
+ console.warn('⚠️ Code Animation acceptance committed; Media History synchronization remains pending');
+ return project;
+ });
+ if (notify && projected.acceptanceProjection?.status === 'synced') emitCodeAnimationChanged(project.id);
+ return projected;
}
/** The accepted output with live freshness, plus recent runs summarized for side-by-side comparison. */
export async function getProductionAcceptance(projectId) {
- const project = await getProductionProject(projectId);
- const { items } = await store.pageProjectHistory(projectId, { limit: RECENT_RUNS, offset: 0 });
- const runs = items.filter(item => item.data?.kind === STAGE_RUN_KIND);
- const frozen = project.acceptedOutput ?? null;
- let accepted = null;
- if (frozen) {
- const source = runs.find(run => run.id === frozen.runId) ?? await store.getRunRecord(projectId, frozen.runId);
- accepted = { ...frozen, ...acceptanceFreshness(frozen, await currentHashes(projectId, frozen, source)) };
- }
- return { accepted, runs: runs.map(run => summarizeRunForComparison(run, frozen?.runId ?? null)) };
+ return queueAcceptance(projectId, async () => {
+ const project = await reconcileProjection(await getProductionProject(projectId));
+ const { items } = await store.pageProjectHistory(projectId, { limit: RECENT_RUNS, offset: 0 });
+ const runs = items.filter(item => item.data?.kind === STAGE_RUN_KIND);
+ const frozen = project.acceptedOutput ?? null;
+ let accepted = null;
+ if (frozen) {
+ const source = runs.find(run => run.id === frozen.runId) ?? await store.getRunRecord(projectId, frozen.runId);
+ accepted = { ...frozen, ...acceptanceFreshness(frozen, await currentHashes(projectId, frozen, source)) };
+ }
+ return { accepted, acceptanceProjection: project.acceptanceProjection ?? null, runs: runs.map(run => summarizeRunForComparison(run, frozen?.runId ?? null)) };
+ });
}
/** Accepted shorts as downstream tools consume them: a Media History id and a source package, nothing else required. */
export async function listAcceptedAssets(page) {
const { items, nextCursor } = await store.pageAcceptedOutputs(page);
return {
- items: items.map(({ id, title, accepted }) => ({
- projectId: id, title, videoId: accepted.videoId, filename: accepted.filename, path: accepted.path, format: accepted.format,
- sourceHash: accepted.sourceHash, audioHash: accepted.audioHash, renderHash: accepted.renderHash, acceptedAt: accepted.acceptedAt,
- packageUrl: `/api/code-animation/projects/${id}/revisions/${accepted.revisionId}/package`,
- })),
+ items: await Promise.all(items.map(({ id }) => queueAcceptance(id, async () => {
+ // Re-read inside the queue: a newer promotion may have superseded the page.
+ const project = await reconcileProjection(await getProductionProject(id));
+ const accepted = project.acceptedOutput;
+ return {
+ projectId: id, title: project.title, videoId: accepted.videoId, filename: accepted.filename, path: accepted.path, format: accepted.format,
+ sourceHash: accepted.sourceHash, audioHash: accepted.audioHash, renderHash: accepted.renderHash, acceptedAt: accepted.acceptedAt,
+ acceptanceProjection: project.acceptanceProjection ?? null,
+ packageUrl: `/api/code-animation/projects/${id}/revisions/${accepted.revisionId}/package`,
+ };
+ }))),
nextCursor,
};
}
diff --git a/server/services/codeAnimation/projectStore.js b/server/services/codeAnimation/projectStore.js
index ef1c673dc5..17e366f83a 100644
--- a/server/services/codeAnimation/projectStore.js
+++ b/server/services/codeAnimation/projectStore.js
@@ -1,4 +1,5 @@
/** PostgreSQL owns projects, source revision lineage and import-run records. */
+import { randomUUID } from 'crypto';
import { query, withTransaction } from '../../lib/db.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -195,14 +196,24 @@ export async function setAcceptedOutput(projectId, accepted) {
const { rows } = await client.query(`SELECT ${columns} FROM code_animation_projects WHERE id = $1 FOR UPDATE`, [projectId]);
if (!rows[0]) throw missing();
const promoteSource = rows[0].candidateRevisionId === accepted.revisionId;
- const result = await client.query(`UPDATE code_animation_projects SET data = data || jsonb_build_object('acceptedOutput', $2::jsonb),
+ const result = await client.query(`UPDATE code_animation_projects SET data = data || jsonb_build_object('acceptedOutput', $2::jsonb, 'acceptanceProjection', $5::jsonb),
accepted_revision_id = CASE WHEN $4 THEN $3 ELSE accepted_revision_id END,
candidate_revision_id = CASE WHEN $4 THEN NULL ELSE candidate_revision_id END, updated_at = NOW()
- WHERE id = $1 RETURNING ${columns}`, [projectId, JSON.stringify(accepted), accepted.revisionId, promoteSource]);
+ WHERE id = $1 RETURNING ${columns}`, [projectId, JSON.stringify(accepted), accepted.revisionId, promoteSource,
+ JSON.stringify({ decisionId: randomUUID(), status: 'pending' })]);
return present(result.rows[0]);
});
}
+/** A history write only acknowledges the exact decision it projected. */
+export async function acknowledgeAcceptanceProjection(projectId, decisionId) {
+ const { rows } = await query(`UPDATE code_animation_projects
+ SET data = jsonb_set(data, '{acceptanceProjection,status}', '"synced"'::jsonb)
+ WHERE id = $1 AND data->'acceptanceProjection'->>'decisionId' = $2
+ RETURNING ${columns}`, [projectId, decisionId]);
+ return present(rows[0]) || getProjectRecord(projectId);
+}
+
export async function pageAcceptedOutputs({ limit, offset }) {
const { rows } = await query(`SELECT id, title, data->'acceptedOutput' AS accepted FROM code_animation_projects
WHERE data ? 'acceptedOutput' ORDER BY data->'acceptedOutput'->>'acceptedAt' DESC, id DESC LIMIT $1 OFFSET $2`, [limit + 1, offset]);