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

refactor([issue-1938]): CD first-pass scene-frame cleanup (deferred from #1867)

Adam Eivye6a0ee2caf5a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ebd81e97df..6957d428c8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -159,6 +159,8 @@
## Internal
+- **[issue-1938] Creative Director first-pass scene-frame cleanup (deferred from #1867).** Three low-risk tidy-ups with no user-visible behavior change: **(1)** the "look up `ASPECT_PRESETS[aspectRatio]`, degrade gracefully if unrecognized" pattern — inlined a third time in `firstPassGen.js#enqueueFirstPassSceneFrames` on top of the two copies in `creativeDirectorPrompts.js` — is now a single exported `resolveAspectDimensions(aspectRatio, fallback)` helper in `creativeDirectorPresets.js` that all three call sites share (the `fallback` stays caller-owned so prompt views keep their printable `{width:0,height:0}` and first-pass gen keeps its `{}` → worker-default box). **(2)** First-pass scene-frame seeding now fires from `setTreatment` itself (the domain write in `creativeDirector/local.js`) rather than only the `/:id/treatment` PATCH route, so the `generateFirstPass` opt-in is honored on every treatment path (route, `episodeVideo`, `liveDirector`) instead of silently no-op'ing if a future caller lands a treatment another way; the route-level assertions moved to `local.test.js`. **(3)** The auto-cast route's `generateFirstPass` opt-in is threaded into `applyAutoCastToProject`'s options so the flag persists in the SAME read-modify-write as the cast merge — collapsing what was two sequential full project writes (each with its own peer-sync push) into one on the opt-in path. (`server/lib/creativeDirectorPresets.js`, `server/lib/creativeDirectorPrompts.js`, `server/services/creativeDirector/{firstPassGen,local,autoCast}.js`, `server/routes/creativeDirector.js`)
+
- **[issue-2256] Removed the dead cos-runner `/run` devtools endpoint (latent Windows ENOENT bug).** The CoS runner's `POST /run` devtools path spawned a bare command under `shell:false` with the prompt passed as an argv — the same Windows `spawn ENOENT` bug the CoS agent path had (#2243), but no code called it: the live "Run Prompt" flow goes through `server/services/runner.js` (already fixed), and `executeCliRunViaRunner` + the `/runs`, `/runs/:id/output`, `/runs/:id/active`, `/runs/:id/stop` sibling endpoints and their client wrappers (`getActiveRunsFromRunner`, `isRunActiveInRunner`, `getRunOutputFromRunner`, `stopRunViaRunner`) were referenced only by their own tests. Rather than refactor dead code to be Windows-safe (a prompt-via-stdin rewrite to dodge the ~8191-char `cmd.exe /c` command-line limit), the whole devtools-run cluster is removed — the endpoint, its in-memory `activeRuns` map + `ensureRunsDir` helper, the `run:data`/`run:complete`/`run:error` socket forwarders, and the now-orphaned client functions and their tests. The main server and cos-runner sidecar ship in one repo and deploy together, so there's no cross-install compatibility concern. (`server/cos-runner/index.js`, `server/services/cosRunnerClient.js`, `server/services/cosRunnerClient.test.js`)
- **[issue-2249] The `issue-reconcile` zombie-scan is now forge-aware — it heals stranded issues on GitLab (`glab`) as well as GitHub (`gh`).** The v1 deterministic scan resolved the repo via `getOriginInfo().isGithub` and queried `gh` only, so enabling `issue-reconcile` on a GitLab-tracked app was a silent no-op. `server/services/issueReconcile.js` now resolves the forge from the app's git `origin` host inside `reconcile()` (github.* → GitHub, gitlab.* → GitLab, anything else → skip/park) and delegates to a per-forge state gatherer. Both gatherers normalize into ONE common issue shape (`{ number, title, url, labels, assignees }`) + change shape (`{ number, headRefName, body, url }`), so the pure classifier (`classifyIssue`), the boundary-safe ref matchers, and the `zombieSignature` convergence guard stay shared and unit-testable with zero forge branching — GitLab maps `iid`→number, MR `source_branch`→head ref (carries `claim/issue-<iid>`), MR `description`→body (carries `Refs #<iid>`). It remains a SINGLE task type (not three): the coordinator prompt is shared and simply gets the resolved forge + the matching `gh`/`glab` command table injected via `{zombieIssues}` (prompt bumped to v2, v1 preserved in `PREVIOUS_DEFAULT_PROMPTS` per the cross-install upgrade contract). A cwd-aware `glab` exec helper was added at `server/services/gitlab.js` (mirrors `execGh`). The JIRA sibling — a status-based "In Review with remaining scope" analog healed through the PortOS JIRA API rather than a forge CLI — is deferred to a follow-up (`Refs #2249`). (`server/services/issueReconcile.js`, `server/services/gitlab.js`, `server/services/cosTaskGenerator.js`, `server/services/taskPromptDefaults/`)
diff --git a/server/lib/creativeDirectorPresets.js b/server/lib/creativeDirectorPresets.js
index d1383bc13d..0661b6a4c8 100644
--- a/server/lib/creativeDirectorPresets.js
+++ b/server/lib/creativeDirectorPresets.js
@@ -18,6 +18,22 @@ export const ASPECT_PRESETS = Object.freeze({
'1:1-small': { width: 384, height: 384 }, // Legacy alias — pre-removal smoke-test fixture
});
+/**
+ * Look up an aspectRatio's {width,height}, degrading gracefully when the ratio
+ * is unrecognized (best-effort callers — prompt views, first-pass seed frames —
+ * must not throw on a stale/unknown ratio the way the render path does).
+ *
+ * The `fallback` is caller-owned because the two consumers want different
+ * degraded shapes: prompt views want `{ width: 0, height: 0 }` (a printable
+ * literal), while first-pass gen wants `{}` so `width`/`height` come through
+ * `undefined` and the image worker applies its own default box instead. Pass
+ * `presetToRenderParams` (which throws on an unknown ratio) when a hard failure
+ * is the correct behavior. See #1938.
+ */
+export function resolveAspectDimensions(aspectRatio, fallback = { width: 0, height: 0 }) {
+ return ASPECT_PRESETS[aspectRatio] || fallback;
+}
+
// `steps` and `guidance` are mlx_video knobs. `fps` is the render frame
// rate. Higher quality = more denoising steps + slightly higher guidance,
// trading wall-clock time for fidelity.
diff --git a/server/lib/creativeDirectorPresets.test.js b/server/lib/creativeDirectorPresets.test.js
index 2d75060096..21bfeb3a04 100644
--- a/server/lib/creativeDirectorPresets.test.js
+++ b/server/lib/creativeDirectorPresets.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { presetToRenderParams, ASPECT_PRESETS, QUALITY_PRESETS, ASPECT_RATIOS } from './creativeDirectorPresets.js';
+import { presetToRenderParams, ASPECT_PRESETS, QUALITY_PRESETS, ASPECT_RATIOS, resolveAspectDimensions } from './creativeDirectorPresets.js';
describe('presetToRenderParams', () => {
it('returns valid params for all current aspect ratios', () => {
@@ -33,3 +33,21 @@ describe('presetToRenderParams', () => {
expect(params.numFrames).toBe(8);
});
});
+
+describe('resolveAspectDimensions (#1938)', () => {
+ it('returns the preset dims for a known ratio', () => {
+ expect(resolveAspectDimensions('16:9')).toEqual({ width: 768, height: 432 });
+ });
+
+ it('degrades to the default { width: 0, height: 0 } for an unknown ratio', () => {
+ expect(resolveAspectDimensions('bogus')).toEqual({ width: 0, height: 0 });
+ expect(resolveAspectDimensions(undefined)).toEqual({ width: 0, height: 0 });
+ });
+
+ it('honors a caller-supplied fallback (first-pass gen passes {} so the worker default applies)', () => {
+ const dims = resolveAspectDimensions('bogus', {});
+ expect(dims).toEqual({});
+ expect(dims.width).toBeUndefined();
+ expect(dims.height).toBeUndefined();
+ });
+});
diff --git a/server/lib/creativeDirectorPrompts.js b/server/lib/creativeDirectorPrompts.js
index 9977f797ed..72004cb2cb 100644
--- a/server/lib/creativeDirectorPrompts.js
+++ b/server/lib/creativeDirectorPrompts.js
@@ -20,7 +20,7 @@
*/
import {
- ASPECT_PRESETS,
+ resolveAspectDimensions,
QUALITY_PRESETS,
presetToRenderParams,
} from './creativeDirectorPresets.js';
@@ -52,7 +52,7 @@ function buildProjectView(project) {
}
function buildTreatmentView(project) {
- const aspect = ASPECT_PRESETS[project.aspectRatio] || { width: 0, height: 0 };
+ const aspect = resolveAspectDimensions(project.aspectRatio);
const quality = QUALITY_PRESETS[project.quality] || { steps: 0, guidance: 0, fps: 0 };
// The example block in the JSON output contract shows a literal value
// for `sourceImageFile` — either a quoted filename or `null`. Precompute
@@ -125,7 +125,7 @@ function frameTimelineLabel(i, total) {
}
function buildEvaluateView(project, scene) {
- const aspect = ASPECT_PRESETS[project.aspectRatio] || { width: 0, height: 0 };
+ const aspect = resolveAspectDimensions(project.aspectRatio);
const quality = QUALITY_PRESETS[project.quality] || { steps: 0, guidance: 0, fps: 0 };
const renderParams = presetToRenderParams({
aspectRatio: project.aspectRatio,
diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.js
index f1f8f2de40..d93106e2e9 100644
--- a/server/routes/creativeDirector.js
+++ b/server/routes/creativeDirector.js
@@ -30,7 +30,7 @@ import {
updateScene,
} from '../services/creativeDirector/local.js';
import { suggestCastForBrief, applyAutoCastToProject, toSuggestionView } from '../services/creativeDirector/autoCast.js';
-import { enqueueFirstPassPortraits, enqueueFirstPassSceneFrames } from '../services/creativeDirector/firstPassGen.js';
+import { enqueueFirstPassPortraits } from '../services/creativeDirector/firstPassGen.js';
import { enqueueFirstPassMusicBed } from '../services/creativeDirector/firstPassMusicGen.js';
import { startCreativeDirectorProject } from '../services/creativeDirector/completionHook.js';
import { createSmokeTestProject } from '../services/creativeDirector/smokeTest.js';
@@ -111,7 +111,19 @@ router.delete('/:id', asyncHandler(async (req, res) => {
// the user the director took over.
router.post('/:id/auto-cast', asyncHandler(async (req, res) => {
const { brief, types, limit, compose, generateFirstPass, generateFirstPassMusicBed } = validateRequest(creativeDirectorAutoCastApplySchema, req.body);
- const result = await applyAutoCastToProject(req.params.id, { brief, types, limit });
+ // Scene reference frames (#1867) depend on a treatment existing, which may
+ // land well after THIS request — either because `compose` kicks it off
+ // asynchronously below, or because the user opted into `generateFirstPass`
+ // without `compose` and only starts the project later via a separate
+ // `/:id/start` call (the OverviewTab toggles are independent, per its own
+ // "Independent of the treatment toggle" copy). Persist the user's opt-in on
+ // the project record — NOT gated on `composing` — so the `/:id/treatment`
+ // handler (the only place the agent's scene plan actually lands) can find it
+ // regardless of which path triggered composition. Folded into the auto-cast
+ // write itself (#1938) so this is one read-modify-write, not two; because it
+ // resolves before the compose kickoff below, there's no ordering ambiguity
+ // between this write and a same-request compose's first read.
+ const result = await applyAutoCastToProject(req.params.id, { brief, types, limit, generateFirstPass });
const project = result.project;
const cast = project?.cast;
// `advanceAfterSceneSettled` (what startCreativeDirectorProject calls) bails
@@ -121,22 +133,6 @@ router.post('/:id/auto-cast', asyncHandler(async (req, res) => {
// treatment path — so we simply skip those statuses.
const composable = project && project.status !== 'paused' && project.status !== 'failed';
const composing = Boolean(compose) && composable && Array.isArray(cast) && cast.length > 0 && !project.treatment;
- // Scene reference frames (#1867) depend on a treatment existing, which may
- // land well after THIS request — either because `compose` kicks it off
- // asynchronously below, or because the user opted into `generateFirstPass`
- // without `compose` and only starts the project later via a separate
- // `/:id/start` call (the OverviewTab toggles are independent, per its own
- // "Independent of the treatment toggle" copy). Persist the user's opt-in on
- // the project record unconditionally — NOT gated on `composing` — so the
- // `/:id/treatment` handler (the only place the agent's scene plan actually
- // lands) can find it regardless of which path triggered composition.
- // Awaited (rather than fired alongside startCreativeDirectorProject) so
- // there is no ordering ambiguity between this write and a same-request
- // compose's first read.
- if (generateFirstPass) {
- await updateProject(req.params.id, { generateFirstPass: true })
- .catch((e) => console.log(`⚠️ CD persist generateFirstPass flag failed: ${e.message}`));
- }
if (composing) {
startCreativeDirectorProject(req.params.id).catch((e) => console.log(`⚠️ CD auto-compose failed: ${e.message}`));
}
@@ -179,17 +175,11 @@ router.post('/:id/auto-cast', asyncHandler(async (req, res) => {
// Agent-callable: write the treatment doc.
router.patch('/:id/treatment', asyncHandler(async (req, res) => {
const treatment = validateRequest(creativeDirectorTreatmentSchema, req.body);
+ // Scene reference frames (#1867): seeding a first reference frame per scene
+ // when the project opted into first-pass gen now fires from `setTreatment`
+ // itself (#1938) — the domain write — so every treatment path honors the
+ // opt-in, not just this route.
const updated = await setTreatment(req.params.id, treatment);
- // Scene reference frames (#1867): the user opted into first-pass gen back
- // at auto-cast time (persisted as `generateFirstPass` on the project since
- // the treatment lands asynchronously, possibly much later). Now that a
- // scene plan exists, seed a first reference frame per scene the same way
- // first-pass portraits are seeded — fire-and-forget like auto-compose
- // above; the response shouldn't block on render-queue work.
- if (updated?.generateFirstPass) {
- enqueueFirstPassSceneFrames(updated)
- .catch((e) => console.log(`⚠️ CD first-pass scene frames failed: ${e.message}`));
- }
res.json(updated);
}));
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index 5c15da0f0c..6421989be4 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -176,20 +176,9 @@ describe('creativeDirector routes', () => {
expect(r.status).toBe(200);
expect(cdService.setTreatment).toHaveBeenCalled();
});
-
- it('seeds first-pass scene frames when the project opted in (#1867)', async () => {
- cdService.setTreatment.mockResolvedValue({ id: 'cd-1', generateFirstPass: true, treatment: { scenes: [] } });
- const r = await request(app).patch('/api/creative-director/cd-1/treatment').send(treatmentBody);
- expect(r.status).toBe(200);
- expect(firstPass.enqueueFirstPassSceneFrames).toHaveBeenCalledWith({ id: 'cd-1', generateFirstPass: true, treatment: { scenes: [] } });
- });
-
- it('does not seed first-pass scene frames when the project never opted in', async () => {
- cdService.setTreatment.mockResolvedValue({ id: 'cd-1', treatment: { scenes: [] } });
- const r = await request(app).patch('/api/creative-director/cd-1/treatment').send(treatmentBody);
- expect(r.status).toBe(200);
- expect(firstPass.enqueueFirstPassSceneFrames).not.toHaveBeenCalled();
- });
+ // First-pass scene-frame seeding now fires from `setTreatment` itself
+ // (the domain write, #1938) rather than this route, so its behavior is
+ // asserted in services/creativeDirector/local.test.js.
});
describe('POST /:id/start', () => {
@@ -382,32 +371,37 @@ describe('creativeDirector routes', () => {
expect(hook.startCreativeDirectorProject).not.toHaveBeenCalled();
});
- it('persists generateFirstPass on the project when composing with the flag set (#1867)', async () => {
+ // The opt-in flag is now threaded into applyAutoCastToProject's options
+ // (#1938) so the cast merge + flag persist in a single write, rather than
+ // the route issuing a second updateProject. The route's job here is to
+ // forward the flag; the actual persist is asserted in autoCast.test.js.
+ it('forwards generateFirstPass to auto-cast when composing with the flag set (#1867)', async () => {
autoCast.applyAutoCastToProject.mockResolvedValue({
project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],
});
const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ compose: true, generateFirstPass: true });
expect(r.status).toBe(200);
- expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { generateFirstPass: true });
+ expect(autoCast.applyAutoCastToProject).toHaveBeenCalledWith('cd-1', expect.objectContaining({ generateFirstPass: true }));
+ expect(cdService.updateProject).not.toHaveBeenCalledWith('cd-1', { generateFirstPass: true });
});
- it('persists generateFirstPass even when not composing this request (#1867) — the toggles are independent, and the project may only be started later via /:id/start', async () => {
+ it('forwards generateFirstPass even when not composing this request (#1867) — the toggles are independent, and the project may only be started later via /:id/start', async () => {
autoCast.applyAutoCastToProject.mockResolvedValue({
project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],
});
const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPass: true });
expect(r.status).toBe(200);
- expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { generateFirstPass: true });
+ expect(autoCast.applyAutoCastToProject).toHaveBeenCalledWith('cd-1', expect.objectContaining({ generateFirstPass: true }));
expect(hook.startCreativeDirectorProject).not.toHaveBeenCalled();
});
- it('does not persist generateFirstPass when the flag is omitted', async () => {
+ it('does not forward a truthy generateFirstPass when the flag is omitted', async () => {
autoCast.applyAutoCastToProject.mockResolvedValue({
project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],
});
const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ compose: true });
expect(r.status).toBe(200);
- expect(cdService.updateProject).not.toHaveBeenCalledWith('cd-1', { generateFirstPass: true });
+ expect(autoCast.applyAutoCastToProject).toHaveBeenCalledWith('cd-1', expect.objectContaining({ generateFirstPass: undefined }));
});
});
diff --git a/server/services/creativeDirector/autoCast.js b/server/services/creativeDirector/autoCast.js
index 654677d49a..b60b369a09 100644
--- a/server/services/creativeDirector/autoCast.js
+++ b/server/services/creativeDirector/autoCast.js
@@ -108,7 +108,7 @@ export async function suggestCastForBrief({ brief, types = DEFAULT_CASTABLE_TYPE
* project, the members actually added, and the full ranked suggestions (so the UI
* can show what was considered, including already-cast matches).
*/
-export async function applyAutoCastToProject(projectId, { brief, types, limit } = {}) {
+export async function applyAutoCastToProject(projectId, { brief, types, limit, generateFirstPass } = {}) {
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
@@ -134,12 +134,25 @@ export async function applyAutoCastToProject(projectId, { brief, types, limit }
.slice(0, capacity);
if (freshIngredients.length === 0) {
+ // Nothing new to merge, but the caller may still have opted into first-pass
+ // scene frames (#1867) — persist that flag on its own so the treatment
+ // handler can find it later. Folded in here (#1938) so the route never has
+ // to issue a second full read-modify-write + peer-sync push of its own.
+ if (generateFirstPass) {
+ const updated = await updateProject(projectId, { generateFirstPass: true });
+ return { project: updated, added: [], suggestions };
+ }
return { project, added: [], suggestions };
}
const newMembers = buildCastFromIngredients(freshIngredients);
const mergedCast = [...existingCast, ...newMembers];
- const updated = await updateProject(projectId, { cast: mergedCast });
+ // Fold the opt-in flag into the same write as the cast merge (#1938) so the
+ // opt-in path is a single read-modify-write + one peer-sync push, not two.
+ const updated = await updateProject(projectId, {
+ cast: mergedCast,
+ ...(generateFirstPass ? { generateFirstPass: true } : {}),
+ });
// Best-effort ref-link (the cast is already persisted) — mirrors createProject.
await linkIngredientsToCreativeDirector(projectId, freshIngredients)
diff --git a/server/services/creativeDirector/autoCast.test.js b/server/services/creativeDirector/autoCast.test.js
index 4a8e11470e..dba72d58fd 100644
--- a/server/services/creativeDirector/autoCast.test.js
+++ b/server/services/creativeDirector/autoCast.test.js
@@ -181,4 +181,58 @@ describe('applyAutoCastToProject', () => {
expect(result.added).toHaveLength(1);
expect(updateProject.mock.calls[0][1].cast).toHaveLength(50);
});
+
+ // #1938: the generateFirstPass opt-in is folded into the auto-cast write so
+ // the route no longer issues a second full read-modify-write for the flag.
+ it('folds generateFirstPass into the same write as the cast merge', async () => {
+ getProject.mockResolvedValue({ id: 'p1', name: 'Neon Run', styleSpec: 'rain noir', cast: [] });
+ mockSearch([hit('p1', 'place', 'The Spire')]);
+ updateProject.mockImplementation(async (_id, patch) => ({ id: 'p1', ...patch }));
+
+ const result = await applyAutoCastToProject('p1', { generateFirstPass: true });
+ expect(result.added.map((m) => m.ingredientId)).toEqual(['p1']);
+ // single write carries both the cast and the flag
+ expect(updateProject).toHaveBeenCalledTimes(1);
+ expect(updateProject.mock.calls[0][1]).toMatchObject({ generateFirstPass: true });
+ expect(updateProject.mock.calls[0][1].cast).toHaveLength(1);
+ expect(result.project.generateFirstPass).toBe(true);
+ });
+
+ it('does not add a generateFirstPass key to the merge write when the flag is off', async () => {
+ getProject.mockResolvedValue({ id: 'p1', name: 'Neon Run', styleSpec: 'rain noir', cast: [] });
+ mockSearch([hit('p1', 'place', 'The Spire')]);
+ updateProject.mockImplementation(async (_id, patch) => ({ id: 'p1', ...patch }));
+
+ await applyAutoCastToProject('p1', {});
+ expect(updateProject).toHaveBeenCalledTimes(1);
+ expect(updateProject.mock.calls[0][1]).not.toHaveProperty('generateFirstPass');
+ });
+
+ it('persists generateFirstPass alone when there are no fresh members to add', async () => {
+ getProject.mockResolvedValue({
+ id: 'p1', name: 'Neon Run', styleSpec: 'rain noir',
+ cast: [{ ingredientId: 'c1', name: 'Mara', type: 'character', role: 'cast' }],
+ });
+ mockSearch([hit('c1', 'character', 'Mara')]); // already cast → nothing fresh
+ updateProject.mockImplementation(async (_id, patch) => ({ id: 'p1', ...patch }));
+
+ const result = await applyAutoCastToProject('p1', { generateFirstPass: true });
+ expect(result.added).toEqual([]);
+ // still a single flag-only write — no cast churn, no double write
+ expect(updateProject).toHaveBeenCalledTimes(1);
+ expect(updateProject).toHaveBeenCalledWith('p1', { generateFirstPass: true });
+ expect(linkIngredientsToCreativeDirector).not.toHaveBeenCalled();
+ expect(result.project.generateFirstPass).toBe(true);
+ });
+
+ it('does not write at all when nothing is fresh and the flag is off', async () => {
+ getProject.mockResolvedValue({
+ id: 'p1', name: 'Neon Run', styleSpec: 'rain noir',
+ cast: [{ ingredientId: 'c1', name: 'Mara', type: 'character', role: 'cast' }],
+ });
+ mockSearch([hit('c1', 'character', 'Mara')]);
+ const result = await applyAutoCastToProject('p1', {});
+ expect(result.added).toEqual([]);
+ expect(updateProject).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/creativeDirector/firstPassGen.js b/server/services/creativeDirector/firstPassGen.js
index 565fb33244..1b975dc3ba 100644
--- a/server/services/creativeDirector/firstPassGen.js
+++ b/server/services/creativeDirector/firstPassGen.js
@@ -33,7 +33,7 @@ import { getSettings } from '../settings.js';
import { resolveImageCleaners } from '../imageGen/index.js';
import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
import { getIngredient, listMediaForIngredient } from '../catalogDB.js';
-import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';
+import { resolveAspectDimensions } from '../../lib/creativeDirectorPresets.js';
import { payloadSnippet, getActiveCatalogType } from '../../lib/catalogTypes.js';
// Keep the derived portrait prompt bounded — enough descriptive text to render
@@ -231,7 +231,7 @@ export async function enqueueFirstPassSceneFrames(project) {
// the worker's own default (undefined → 1024x1024) for an unrecognized
// aspectRatio rather than throwing, matching this function's best-effort
// contract.
- const { width, height } = ASPECT_PRESETS[project.aspectRatio] || {};
+ const { width, height } = resolveAspectDimensions(project.aspectRatio, {});
const enqueued = [];
const skipped = [];
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index f57e5714ed..978e80b7b0 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -26,6 +26,7 @@ import { checkHealth, ensureSchema } from '../../lib/db.js';
import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
import { resolveIngredientsByIds, linkIngredientsToCreativeDirector } from '../catalogDB.js';
import { buildCastFromIngredients } from './catalogSeed.js';
+import { enqueueFirstPassSceneFrames } from './firstPassGen.js';
export { trimRuns, startingImageFilename } from './projectsLogic.js';
@@ -139,6 +140,18 @@ export async function deleteProject(id) {
export async function setTreatment(id, treatmentInput) {
const next = await (await selectBackend()).setTreatment(id, treatmentInput);
emitRecordUpdated('creativeDirectorProject', id);
+ // Scene reference frames (#1867): the user opts into first-pass gen at
+ // auto-cast time (persisted as `generateFirstPass` on the project since the
+ // treatment lands asynchronously, possibly much later). Now that a scene plan
+ // exists, seed a first reference frame per scene. Fire-and-forget — no caller
+ // should block on render-queue work. Fires here, on the domain write, rather
+ // than in one route handler (#1938) so every setTreatment path (the agent
+ // `/:id/treatment` PATCH, episodeVideo, liveDirector) honors the opt-in
+ // instead of the flag silently no-op'ing for treatments that land another way.
+ if (next?.generateFirstPass) {
+ enqueueFirstPassSceneFrames(next)
+ .catch((e) => console.log(`⚠️ CD first-pass scene frames failed: ${e.message}`));
+ }
return next;
}
diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.js
index 6da498df13..de6706e6ae 100644
--- a/server/services/creativeDirector/local.test.js
+++ b/server/services/creativeDirector/local.test.js
@@ -26,7 +26,14 @@ vi.mock('../catalogDB.js', () => ({
cdRefRoleForType: (type) => type,
}));
+// setTreatment fires first-pass scene-frame seeding (#1938) — mock it so this
+// dispatcher test doesn't pull the real mediaJobQueue/imageGen graph.
+vi.mock('./firstPassGen.js', () => ({
+ enqueueFirstPassSceneFrames: vi.fn(async () => ({ mode: 'local', enqueued: [], skipped: [] })),
+}));
+
const { setTreatment, recordRun, updateRun, trimRuns } = await import('./local.js');
+import * as firstPassGen from './firstPassGen.js';
const VALID_TREATMENT = {
logline: 'A cat finds a hat.',
@@ -46,6 +53,24 @@ beforeEach(() => {
mockReadJSONFile.mockReset();
mockAtomicWrite.mockReset().mockResolvedValue(undefined);
mockEnsureDir.mockReset().mockResolvedValue(undefined);
+ firstPassGen.enqueueFirstPassSceneFrames.mockClear();
+});
+
+describe('setTreatment — first-pass scene frames (#1867/#1938)', () => {
+ 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);
+ // Fires on the domain write itself (not the route) so every setTreatment
+ // caller honors the opt-in. Called with the freshly-persisted project.
+ expect(firstPassGen.enqueueFirstPassSceneFrames).toHaveBeenCalledWith(result);
+ expect(result.generateFirstPass).toBe(true);
+ });
+
+ it('does not seed first-pass scene frames when the project never opted in', async () => {
+ mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', name: 'Test' }]);
+ await setTreatment('cd-1', VALID_TREATMENT);
+ expect(firstPassGen.enqueueFirstPassSceneFrames).not.toHaveBeenCalled();
+ });
});
describe('setTreatment — status preservation', () => {