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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: validate Video source attachments and expose repair actions (#6547)
[._.]/ Adam Eivy45da08b20317
diff --git a/client/src/components/creative-director/VideoArtifactsTab.jsx b/client/src/components/creative-director/VideoArtifactsTab.jsxindex 9851d74bbb..1a0b53448d 100644--- a/client/src/components/creative-director/VideoArtifactsTab.jsx+++ b/client/src/components/creative-director/VideoArtifactsTab.jsx@@ -1,4 +1,6 @@import { Link } from 'react-router';+import { useEffect, useState } from 'react';+import { getCreativeDirectorSources } from '../../services/apiCreativeDirector.js';import { formatTimecode } from '../../utils/formatters.js';import { PLAN_STEP_STATUS_META, stepResultLink } from '../../lib/creativeDirectorPlan.js';@@ -7,11 +9,38 @@ export default function VideoArtifactsTab({ project, basePath }) {const artifact = treatment?.artifact;const projectPath = `${basePath}/${encodeURIComponent(project.id)}`;const scenes = new Map((treatment?.scenes || []).map(scene => [scene.sceneId, scene]));+ const [sourceState, setSourceState] = useState(null);+ const [sourceError, setSourceError] = useState(false);+ const [check, setCheck] = useState(0);+ useEffect(() => {+ let current = true;+ setSourceState(null);+ setSourceError(false);+ getCreativeDirectorSources(project.id, { silent: true }).then(result => {+ if (current) setSourceState(result);+ }).catch(() => { if (current) setSourceError(true); });+ return () => { current = false; };+ }, [project.id, project.updatedAt, check]);+ const repairPath = `${projectPath}/overview?draft=1&videoDraftTab=sources`;return (<div className="max-w-4xl space-y-4"><h2 className="text-lg font-medium">Production artifacts</h2><p className="text-sm text-port-text-muted">Saved planning artifacts. Production remains blocked until revision approvals and dispatch controls are available.</p>+ <section aria-label="Source availability" className="bg-port-card border border-port-border rounded p-4 space-y-2 text-sm">+ <h3 className="font-medium">Source availability</h3>+ {sourceError ? <p role="alert">Unable to check sources. Availability is unknown; no references were changed.</p>+ : !sourceState ? <p role="status">Checking sources…</p>+ : <>+ <p>Current draft: {sourceState.draft.filter(source => !source.available).length} missing sources. Saved revisions are unchanged by this check.</p>+ <ul>{sourceState.draft.filter(source => !source.available).map(source => <li key={source.referenceId} className="text-port-warning break-words">Missing {source.kind}: {source.id}</li>)}</ul>+ </>}+ <div className="flex flex-wrap gap-3">+ <button disabled={!sourceState && !sourceError} onClick={() => setCheck(value => value + 1)} className="text-port-accent disabled:opacity-50">Check again</button>+ {project.status === 'draft' && <Link className="text-port-accent hover:underline" to={repairPath}>Edit source attachments</Link>}+ </div>+ <p className="text-port-text-muted">Remove or replace missing sources in the draft, then save a revised treatment to repair saved references. Music references identify tracks; voice references identify local voice profiles.</p>+ </section>{!artifact ? (<p className="text-sm text-port-text-muted">No compiled artifact yet. A saved Video treatment with a script and shots totaling the exact target will appear here.@@ -52,16 +81,21 @@ export default function VideoArtifactsTab({ project, basePath }) {</section><section aria-labelledby="video-artifact-references" className="space-y-2"><h3 id="video-artifact-references" className="font-medium">Saved references ({artifact.references.length})</h3>- <p className="text-sm text-port-text-muted">References belong to this artifact revision. Source availability has not been checked.</p>+ <p className="text-sm text-port-text-muted">References belong to this artifact revision. Availability is checked against this install and does not certify that source content matches its recorded revision.</p>{!artifact.references.length && <p className="text-sm">No attached sources in this revision.</p>}<ul className="space-y-2">{artifact.references.map(reference => {+ const available = sourceState?.artifact.find(source => source.referenceId === reference.referenceId)?.available;const sourcePath = reference.kind === 'universe' ? `/universes/${encodeURIComponent(reference.id)}`: reference.kind === 'series' ? `/pipeline/series/${encodeURIComponent(reference.id)}` : null;return <li key={reference.referenceId} className="bg-port-card border border-port-border rounded p-3 text-sm space-y-1 break-words"><p>{reference.kind}: {reference.id}</p><p className="text-xs text-port-text-muted">Reference ID: {reference.referenceId}</p><p>Source revision: {reference.revision || 'Not recorded'}</p>+ <p className={available === false ? 'text-port-warning' : 'text-port-text-muted'}>+ {available === true ? 'Source available'+ : available === false ? 'Source missing — repair the draft and save a revised treatment' : 'Source availability unknown'}+ </p>{sourcePath && <Link className="text-port-accent hover:underline" to={sourcePath}>Open {reference.kind}</Link>}</li>;})}diff --git a/client/src/pages/CreativeDirectorDetail.test.jsx b/client/src/pages/CreativeDirectorDetail.test.jsxindex cca95b000a..2ae04c773f 100644--- a/client/src/pages/CreativeDirectorDetail.test.jsx+++ b/client/src/pages/CreativeDirectorDetail.test.jsx@@ -5,6 +5,7 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router';vi.mock('../services/apiCreativeDirector.js', () => ({getCreativeDirectorProject: vi.fn(),+ getCreativeDirectorSources: vi.fn(async () => ({ draft: [], artifact: [] })),deleteCreativeDirectorProject: vi.fn(),startCreativeDirectorProject: vi.fn(),pauseCreativeDirectorProject: vi.fn(),@@ -163,4 +164,20 @@ describe('Video saved artifacts', () => {expect(screen.getByRole('link', { name: 'Review the brief' })).toHaveAttribute('href', '/video/cd-example/overview');expect(screen.getByText('No tool plan saved.')).toBeInTheDocument();});++ it('reports missing sources, links to repair, and retries failed checks without altering saved revisions', async () => {+ const user = userEvent.setup();+ cdApi.getCreativeDirectorSources.mockRejectedValueOnce(new Error('Unavailable'));+ renderVideo();+ expect(await screen.findByRole('alert')).toHaveTextContent('Availability is unknown');+ cdApi.getCreativeDirectorSources.mockResolvedValueOnce({+ draft: [{ referenceId: 'universe:example-universe', kind: 'universe', id: 'example-universe', available: false }],+ artifact: [{ referenceId: 'universe:example-universe', kind: 'universe', id: 'example-universe', available: false }],+ });+ await user.click(screen.getByRole('button', { name: 'Check again' }));+ expect(await screen.findByText('Missing universe: example-universe')).toBeInTheDocument();+ expect(screen.getByText('Source revision: rev-4')).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'Edit source attachments' })).toHaveAttribute('href', '/video/cd-example/overview?draft=1&videoDraftTab=sources');+ expect(cdApi.startCreativeDirectorProject).not.toHaveBeenCalled();+ });});diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.jsindex 320e518204..fca8ce5850 100644--- a/client/src/services/apiCreativeDirector.js+++ b/client/src/services/apiCreativeDirector.js@@ -2,6 +2,7 @@ import { request } from './apiCore.js';import { fetchByIds } from './apiBatch.js';export const listCreativeDirectorProjects = (options = {}) => request('/creative-director', options);+export const getCreativeDirectorSources = (id, options = {}) => request(`/creative-director/${encodeURIComponent(id)}/sources`, options);// Pass `{ slim: true }` to receive only the fields a polling consumer needs// (status / per-scene status / finalVideoId / failureReason / updatedAt) —// drops the `runs[]` history and the full treatment text. Usefuldiff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex 38e2e6652a..c1564357cc 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -128,6 +128,14 @@ router.get('/:id', asyncHandler(async (req, res) => {res.json(req.query.slim === '1' ? slimProject(p) : p);}));+router.get('/:id/sources', asyncHandler(async (req, res) => {+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ if (project.workspace !== 'video') throw new ServerError('Source checks require a Video project', { status: 400, code: 'INVALID_STATE' });+ const { getVideoSourceStatus } = await import('../services/creativeDirector/videoSources.js');+ res.json(await getVideoSourceStatus(project));+}));+router.post('/', asyncHandler(async (req, res) => {const data = validateRequest(creativeDirectorProjectCreateSchema, req.body);const project = await createProject(data);diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex a597ab48b7..703adbb372 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -2,6 +2,14 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';+vi.mock('../services/universeBuilder/crud.js', () => ({ getUniverse: vi.fn(async () => ({ id: 'example-universe', name: 'Example universe' })) }));+vi.mock('../services/pipeline/series.js', () => ({ getSeries: vi.fn(async () => ({ id: 'example-series' })) }));+vi.mock('../services/catalogDB/ingredients.js', () => ({ getIngredient: vi.fn(async () => ({ id: 'example-catalog' })) }));+vi.mock('../services/tracks/index.js', () => ({ getTrack: vi.fn(async () => ({ id: 'example-music' })) }));+vi.mock('../services/voice/profiles.js', () => ({ getVoiceProfile: vi.fn(async () => ({ id: 'example-voice', inference: { checkpointPath: '/fake/private/voice' } })) }));+import { getUniverse } from '../services/universeBuilder/crud.js';+import { getSeries } from '../services/pipeline/series.js';+vi.mock('../services/creativeDirector/local.js', () => ({listProjects: vi.fn(async () => [{ id: 'cd-1', name: 'A' }]),getProjectsByIds: vi.fn(async () => []),@@ -80,6 +88,36 @@ describe('creativeDirector routes', () => {});describe('Video drafts', () => {+ it('checks draft and saved sources without exporting source records or rewriting revisions', async () => {+ const sources = ['universe', 'series', 'catalog', 'music', 'voice'].map(kind => ({ kind, id: `example-${kind}`, revision: 'recorded-revision' }));+ const project = { id: 'cd-video', workspace: 'video', videoDraft: { sources }, treatment: { artifact: { references: sources.map(source => ({ ...source, referenceId: `${source.kind}:${source.id}`, revision: 'older-revision' })) } } };+ cdService.getProject.mockResolvedValueOnce(project);+ const res = await request(app).get('/api/creative-director/cd-video/sources');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({+ draft: sources.map(source => ({ ...source, referenceId: `${source.kind}:${source.id}`, available: true })),+ artifact: sources.map(source => ({ ...source, referenceId: `${source.kind}:${source.id}`, revision: 'older-revision', available: true })),+ });+ expect(getUniverse).toHaveBeenCalledTimes(1);+ expect(cdService.updateProject).not.toHaveBeenCalled();+ expect(project.treatment.artifact.references[0].revision).toBe('older-revision');+ });++ it('reports deleted sources but treats failed lookups as unknown instead of missing', async () => {+ const project = { workspace: 'video', videoDraft: { sources: [{ kind: 'series', id: 'example-series' }] } };+ cdService.getProject.mockResolvedValue(project);+ getSeries.mockRejectedValueOnce(Object.assign(new Error('Missing series'), { code: 'PIPELINE_SERIES_NOT_FOUND' }));+ const missing = await request(app).get('/api/creative-director/cd-video/sources');+ expect(missing.status).toBe(200);+ expect(missing.body.draft[0].available).toBe(false);+ getSeries.mockRejectedValueOnce(new Error('Store unavailable'));+ const failed = await request(app).get('/api/creative-director/cd-video/sources');+ expect(failed.status).toBe(500);+ expect(failed.body.draft).toBeUndefined();+ cdService.getProject.mockResolvedValueOnce(null);+ expect((await request(app).get('/api/creative-director/missing/sources')).status).toBe(404);+ });+const draft = {name: 'Example short', workspace: 'video', modelId: '',aspectRatio: '16:9', quality: 'draft', targetDurationSeconds: 60,diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsindex 1bcec68ae0..13530a95b6 100644--- a/server/services/creativeDirector/local.js+++ b/server/services/creativeDirector/local.js@@ -133,6 +133,8 @@ export async function deleteProject(id) {}export async function setTreatment(id, treatmentInput) {+ const { assertVideoSourcesAvailable } = await import('./videoSources.js');+ await assertVideoSourcesAvailable(await getProject(id));const next = await (await selectBackend()).setTreatment(id, treatmentInput);emitRecordUpdated('creativeDirectorProject', id);// Scene reference frames (#1867): the user opts into first-pass gen at@@ -151,6 +153,8 @@ export async function setTreatment(id, treatmentInput) {}export async function setPlan(id, planInput) {+ const { assertVideoSourcesAvailable } = await import('./videoSources.js');+ await assertVideoSourcesAvailable(await getProject(id));const next = await (await selectBackend()).setPlan(id, planInput);emitRecordUpdated('creativeDirectorProject', id);return next;diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.jsindex 4f124aae1d..55fa6ee173 100644--- a/server/services/creativeDirector/local.test.js+++ b/server/services/creativeDirector/local.test.js@@ -32,7 +32,10 @@ vi.mock('./firstPassGen.js', () => ({enqueueFirstPassSceneFrames: vi.fn(async () => ({ mode: 'local', enqueued: [], skipped: [] })),}));-const { setTreatment, recordRun, updateRun, trimRuns, getProjectsByIds } = await import('./local.js');+vi.mock('../catalogDB/ingredients.js', () => ({ getIngredient: vi.fn() }));+import { getIngredient } from '../catalogDB/ingredients.js';++const { setTreatment, setPlan, recordRun, updateRun, trimRuns, getProjectsByIds } = await import('./local.js');import * as firstPassGen from './firstPassGen.js';const VALID_TREATMENT = {@@ -57,6 +60,25 @@ beforeEach(() => {});describe('setTreatment — first-pass scene frames (#1867/#1938)', () => {+ it('blocks both Video artifact writers on missing sources, then saves after source repair', async () => {+ const project = { id: 'cd-video', workspace: 'video', status: 'draft', name: 'Example', targetDurationSeconds: 120, aspectRatio: '16:9', videoDraft: { sources: [{ kind: 'catalog', id: 'example-catalog', revision: 'revision-1' }] } };+ mockReadJSONFile.mockResolvedValue([project]);+ getIngredient.mockResolvedValue(null);+ const treatment = { ...VALID_TREATMENT, script: 'A cat finds a hat.', scenes: Array.from({ length: 12 }, (_, order) => ({ ...VALID_TREATMENT.scenes[0], sceneId: `scene-${order}`, order, durationSeconds: 10 })) };+ const plan = { steps: [{ stepId: 'lookup', toolName: 'catalog_searchIngredients', args: { query: 'Example' } }] };+ await expect(setTreatment(project.id, treatment)).rejects.toMatchObject({ code: 'VIDEO_SOURCE_MISSING', status: 409 });+ await expect(setPlan(project.id, plan)).rejects.toMatchObject({ code: 'VIDEO_SOURCE_MISSING', status: 409 });+ getIngredient.mockRejectedValueOnce(new Error('Store unavailable'));+ await expect(setTreatment(project.id, treatment)).rejects.toThrow('Store unavailable');+ expect(mockAtomicWrite).not.toHaveBeenCalled();+ getIngredient.mockResolvedValue({ id: 'example-catalog', updatedAt: 'newer-source-revision' });+ const saved = await setTreatment(project.id, treatment);+ expect(saved.treatment.artifact.references).toEqual([{ kind: 'catalog', id: 'example-catalog', referenceId: 'catalog:example-catalog', revision: 'revision-1' }]);+ expect(saved.status).toBe('draft');+ await expect(setPlan(project.id, plan)).resolves.toMatchObject({ status: 'draft' });+ expect(firstPassGen.enqueueFirstPassSceneFrames).not.toHaveBeenCalled();+ });+it('seeds first-pass scene frames when the project opted into generateFirstPass', async () => {mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', generateFirstPass: true, name: 'Test' }]);const result = await setTreatment('cd-1', VALID_TREATMENT);diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex e9480213e9..0e7785284b 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -511,7 +511,9 @@ export function applyPlan(project, planInput) {};});const replanRounds = project.plan ? (project.plan.replanRounds || 0) + 1 : 0;- const nextStatus = (project.status === 'paused' || project.status === 'failed')+ // Like treatment saves, an inert Video plan must remain editable so missing+ // attachments can be repaired. Saving a plan is not production approval.+ const nextStatus = (project.workspace === 'video' || project.status === 'paused' || project.status === 'failed')? project.status: 'rendering';return {diff --git a/server/services/creativeDirector/videoSources.js b/server/services/creativeDirector/videoSources.jsnew file mode 100644index 0000000000..459180d24d--- /dev/null+++ b/server/services/creativeDirector/videoSources.js@@ -0,0 +1,53 @@+/** Read-only, machine-local availability checks for Video draft/artifact sources. */+import { creativeDirectorVideoDraftSchema } from '../../lib/creativeDirectorValidation.js';+import { ServerError } from '../../lib/errorHandler.js';++const sourceSchema = creativeDirectorVideoDraftSchema.shape.sources.unwrap().element;++// Load only the requested store. Voice means a local voice-profile ID, music a+// Music track ID. Never return source records, local paths, or voice bindings.+const readers = {+ universe: async (id) => (await import('../universeBuilder/crud.js')).getUniverse(id),+ series: async (id) => (await import('../pipeline/series.js')).getSeries(id),+ catalog: async (id) => (await import('../catalogDB/ingredients.js')).getIngredient(id),+ music: async (id) => (await import('../tracks/index.js')).getTrack(id),+ voice: async (id) => (await import('../voice/profiles.js')).getVoiceProfile(id),+};++async function sourceAvailable(source) {+ const record = await readers[source.kind](source.id).catch(error => {+ // These stores deliberately use different not-found contracts. An outage+ // must propagate: it is not evidence that a source was deleted.+ if (error.code === 'NOT_FOUND' || error.code === 'PIPELINE_SERIES_NOT_FOUND') return null;+ throw error;+ });+ return Boolean(record && !record.deleted);+}++/** Checks both snapshots while retaining each snapshot's declared revision. */+export async function getVideoSourceStatus(project) {+ const availability = new Map();+ const check = async (references) => Promise.all(references.map(reference => {+ const source = sourceSchema.parse({ kind: reference.kind, id: reference.id, revision: reference.revision });+ const referenceId = `${source.kind}:${source.id}`;+ if (!availability.has(referenceId)) availability.set(referenceId, sourceAvailable(source));+ return availability.get(referenceId).then(available => ({ ...source, referenceId, available }));+ }));+ const [draft, artifact] = await Promise.all([+ check(project.videoDraft?.sources || []),+ check(project.treatment?.artifact?.references || []),+ ]);+ return { draft, artifact };+}++/** All public treatment/plan writers share this guard; draft edits stay repairable. */+export async function assertVideoSourcesAvailable(project) {+ if (project?.workspace !== 'video') return;+ const { draft } = await getVideoSourceStatus({ ...project, treatment: null });+ const missing = draft.filter(source => !source.available);+ if (missing.length) {+ throw new ServerError(`Video sources are missing: ${missing.map(source => source.referenceId).join(', ')}. Open Edit draft > Sources to remove or replace them, then save a revised treatment.`, {+ status: 409, code: 'VIDEO_SOURCE_MISSING',+ });+ }+}