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
feat: Creative Director first-pass portrait gen from auto-cast (#1818)
[._.]/ Adam Eivy109bb33c2507
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9976a8d72c..db13efc0ec 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,7 @@## Added- **Creative Director auto-compose** — the Overview tab's Auto-cast control now has a `+ treatment` toggle (shown only before a treatment exists): with it on, once the director seeds the cast from the catalog it autonomously writes a first-pass treatment + scene plan grounded in that cast, instead of stopping at cast seeding. Director-first — the autonomous treatment is a starting point you keep editing on the same board, and it never clobbers an existing treatment. (#1817)+- **Creative Director first-pass portraits** — the Overview tab's Auto-cast control gains a `+ portraits` toggle: with it on, once the director seeds the cast from the catalog it queues an on-model portrait render for each newly-cast member that has no portrait yet, so the cast "arrives on-model" without hand-rendering each ingredient. Reuses the existing media-job queue and the durable catalog image-attach hook (the render lands as the ingredient's portrait even if you've navigated away), is strictly optional and idempotent (members that already have a portrait are skipped), and seeds only the queue-backed image-gen modes (local / codex) — external SD-API and a disabled codex are skipped gracefully rather than failing the auto-cast. (#1818)- Shell page now has a **Fullscreen** button that promotes the terminal to a full-viewport overlay (above the sidebar), hiding the stacked header/tabs/quick-commands toolbars so the TUI gets the whole screen — a major mobile usability win where those toolbars previously ate most of the display. Fullscreen keeps a compact, horizontally-scrollable control bar (Exit, Ctrl+C, Paste, arrow/Enter keys) so you can still drive a TUI by thumb, and the Ctrl+C/Paste labels now collapse on small screens to save width.- OpenCode Ollama **TUI** provider for CoS tasks. The TUI completion workflow is now provider-aware: a slashdo-free TUI (OpenCode, which doesn't load Claude Code `/do:*` slash commands) gets a plain `git` + forge-CLI commit → push → open-PR-for-review → `.agent-done` sentinel handoff instead of `/do:pr` / `/do:push`, so an OpenCode TUI agent can actually complete an automated task. The manual path opens the PR/MR (GitHub `gh` or GitLab `glab`) for review without auto-merging. Ships `opencode-ollama-tui` to existing installs via migration 152. (#1814)diff --git a/client/src/components/creative-director/OverviewTab.jsx b/client/src/components/creative-director/OverviewTab.jsxindex 04b03fd292..b7429ae51e 100644--- a/client/src/components/creative-director/OverviewTab.jsx+++ b/client/src/components/creative-director/OverviewTab.jsx@@ -12,6 +12,11 @@ export default function OverviewTab({ project, onProjectUpdate }) {// the treatment agent so the director writes a first-pass treatment + scene// plan. Director-first — off by default so the user opts into the autonomy.const [composeAfter, setComposeAfter] = useState(false);+ // First-pass gen (#1818): when checked, auto-cast also enqueues a catalog+ // portrait render for each newly-cast member lacking one, so the cast arrives+ // on-model. Off by default — opt into the autonomy. Independent of compose:+ // portraits are useful with or without an auto-written treatment.+ const [generateFirstPass, setGenerateFirstPass] = useState(false);// Track the project id this tab is currently mounted for. If the user// toggles audio and navigates to a different CD project before the PATCH// resolves, the late `.then()` would otherwise call onProjectUpdate on@@ -36,6 +41,8 @@ export default function OverviewTab({ project, onProjectUpdate }) {setAutoCasting(false);// The compose toggle is a per-project intent — don't carry it across a switch.setComposeAfter(false);+ // First-pass toggle is per-project intent too — reset on switch.+ setGenerateFirstPass(false);}, [project.id]);useEffect(() => {if (!savingRef.current) {@@ -78,11 +85,19 @@ export default function OverviewTab({ project, onProjectUpdate }) {// guards this too, but gating here keeps the toast honest. Omit the flag// entirely in the default case so the request body stays minimal.const wantCompose = composeAfter && !project.treatment;- applyCreativeDirectorAutoCast(requestProjectId, wantCompose ? { compose: true } : {}, { silent: true })+ applyCreativeDirectorAutoCast(+ requestProjectId,+ {+ ...(wantCompose ? { compose: true } : {}),+ ...(generateFirstPass ? { generateFirstPass: true } : {}),+ },+ { silent: true },+ ).then((result) => {if (projectIdRef.current !== requestProjectId) return;const added = result?.added?.length || 0;const composing = Boolean(result?.composing);+ const firstPassQueued = result?.firstPass?.enqueued?.length || 0;// When the director starts composing, optimistically flip the status to// 'planning' as well — the detail page disables polling for 'draft'// projects, so without this the treatment + runs the agent produces stay@@ -91,10 +106,15 @@ export default function OverviewTab({ project, onProjectUpdate }) {cast: result?.project?.cast || [],...(composing ? { status: 'planning' } : {}),});+ // Suffix the portrait-gen count onto whichever success toast fires, so a+ // user who opted into first-pass gen sees it kicked off in one place.+ const portraitSuffix = firstPassQueued > 0+ ? ` — rendering ${firstPassQueued} first-pass portrait${firstPassQueued === 1 ? '' : 's'}`+ : '';if (composing) {- toast.success(`Auto-cast added ${added} ingredient${added === 1 ? '' : 's'} — director is composing the treatment…`);+ toast.success(`Auto-cast added ${added} ingredient${added === 1 ? '' : 's'} — director is composing the treatment…${portraitSuffix}`);} else if (added > 0) {- toast.success(`Auto-cast added ${added} ingredient${added === 1 ? '' : 's'}`);+ toast.success(`Auto-cast added ${added} ingredient${added === 1 ? '' : 's'}${portraitSuffix}`);} else {toast.info('Auto-cast found no new catalog matches for this brief');}@@ -185,6 +205,24 @@ export default function OverviewTab({ project, onProjectUpdate }) {<span>+ treatment</span></label>)}+ {/* First-pass gen (#1818): render an on-model portrait for each+ newly-cast member lacking one. Independent of the treatment+ toggle, so it's always offered alongside auto-cast. */}+ <label+ htmlFor="cd-first-pass"+ className="flex items-center gap-1 text-xs text-port-text-muted cursor-pointer"+ title="After seeding the cast, queue a catalog portrait render for each new member that has no portrait yet"+ >+ <input+ id="cd-first-pass"+ type="checkbox"+ checked={generateFirstPass}+ onChange={(e) => setGenerateFirstPass(e.target.checked)}+ disabled={autoCasting}+ className="accent-port-accent"+ />+ <span>+ portraits</span>+ </label><buttontype="button"onClick={handleAutoCast}diff --git a/client/src/components/creative-director/OverviewTab.test.jsx b/client/src/components/creative-director/OverviewTab.test.jsxindex 8bac30e0bb..b203ae320b 100644--- a/client/src/components/creative-director/OverviewTab.test.jsx+++ b/client/src/components/creative-director/OverviewTab.test.jsx@@ -140,3 +140,56 @@ describe('OverviewTab auto-compose (#1817)', () => {expect(onProjectUpdate).toHaveBeenCalledWith(expect.not.objectContaining({ status: expect.anything() }));});});++describe('OverviewTab first-pass gen (#1818)', () => {+ it('offers the +portraits toggle even when the project already has a treatment', () => {+ const { unmount } = renderTab(baseProject);+ expect(screen.getByLabelText(/\+ portraits/i)).toBeTruthy();+ unmount();+ // Independent of the +treatment toggle — still offered with a treatment present.+ renderTab({ ...baseProject, treatment: { scenes: [] } });+ expect(screen.getByLabelText(/\+ portraits/i)).toBeTruthy();+ });++ it('passes generateFirstPass:true when the toggle is checked', async () => {+ applyCreativeDirectorAutoCast.mockResolvedValue({ project: { id: 'cd-1', cast: [] }, added: [], suggestions: [] });+ renderTab(baseProject);+ fireEvent.click(screen.getByLabelText(/\+ portraits/i));+ fireEvent.click(screen.getByRole('button', { name: /^Auto-cast$/i }));+ await waitFor(() => expect(applyCreativeDirectorAutoCast).toHaveBeenCalledWith('cd-1', { generateFirstPass: true }, { silent: true }));+ });++ it('combines compose + generateFirstPass when both toggles are checked', async () => {+ applyCreativeDirectorAutoCast.mockResolvedValue({ project: { id: 'cd-1', cast: [] }, added: [], suggestions: [] });+ renderTab(baseProject);+ fireEvent.click(screen.getByLabelText(/\+ treatment/i));+ fireEvent.click(screen.getByLabelText(/\+ portraits/i));+ fireEvent.click(screen.getByRole('button', { name: /^Auto-cast$/i }));+ await waitFor(() => expect(applyCreativeDirectorAutoCast).toHaveBeenCalledWith('cd-1', { compose: true, generateFirstPass: true }, { silent: true }));+ });++ it('suffixes the portrait count onto the success toast', async () => {+ applyCreativeDirectorAutoCast.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1', name: 'The Spire' }] },+ added: [{ ingredientId: 'p1', name: 'The Spire' }],+ suggestions: [],+ firstPass: { mode: 'local', enqueued: [{ ingredientId: 'p1', jobId: 'j1' }], skipped: [] },+ });+ renderTab(baseProject);+ fireEvent.click(screen.getByLabelText(/\+ portraits/i));+ fireEvent.click(screen.getByRole('button', { name: /^Auto-cast$/i }));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/rendering 1 first-pass portrait/i)));+ });++ it('omits the flag and portrait suffix when the toggle is unchecked', async () => {+ applyCreativeDirectorAutoCast.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1', name: 'The Spire' }] },+ added: [{ ingredientId: 'p1', name: 'The Spire' }],+ suggestions: [],+ });+ renderTab(baseProject);+ fireEvent.click(screen.getByRole('button', { name: /^Auto-cast$/i }));+ await waitFor(() => expect(applyCreativeDirectorAutoCast).toHaveBeenCalledWith('cd-1', {}, { silent: true }));+ expect(toast.success).toHaveBeenCalledWith(expect.not.stringMatching(/first-pass portrait/i));+ });+});diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.jsindex 906abbf511..36f8e90910 100644--- a/client/src/services/apiCreativeDirector.js+++ b/client/src/services/apiCreativeDirector.js@@ -45,7 +45,10 @@ export const suggestCreativeDirectorAutoCast = (brief, { types, limit } = {}, op// `compose: true` (#1817) tells the director to autonomously write a treatment +// scene plan grounded in the freshly-seeded cast — the response carries// `composing: true` when the server actually kicked the agent off.-export const applyCreativeDirectorAutoCast = (id, { brief, types, limit, compose } = {}, options = {}) =>+// `generateFirstPass: true` (#1818) additionally enqueues a catalog portrait+// render for each newly-cast member lacking one — the response carries a+// `firstPass: { mode, enqueued, skipped }` summary when it ran.+export const applyCreativeDirectorAutoCast = (id, { brief, types, limit, compose, generateFirstPass } = {}, options = {}) =>request(`/creative-director/${encodeURIComponent(id)}/auto-cast`, {method: 'POST',body: JSON.stringify({@@ -53,6 +56,7 @@ export const applyCreativeDirectorAutoCast = (id, { brief, types, limit, compose...(types ? { types } : {}),...(limit ? { limit } : {}),...(compose ? { compose: true } : {}),+ ...(generateFirstPass ? { generateFirstPass: true } : {}),}),...options,});diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex 8edc8e3c66..f39ef27dba 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -101,6 +101,11 @@ export const creativeDirectorAutoCastApplySchema = z.object({// grounded in the auto-cast cast. The route only honors it when the project has// a non-empty cast and no treatment yet (never clobbers an existing one).compose: z.boolean().optional(),+ // First-pass gen (#1818): when true, enqueue a catalog portrait render for each+ // newly auto-cast member that lacks a portrait so the cast "arrives on-model".+ // Reuses the durable media-job → catalog attach hook (#1359); strictly optional+ // and only seeds queue-backed image-gen modes (local / codex).+ generateFirstPass: z.boolean().optional(),});// Update is restricted to a few editable fields. modelId / aspectRatio /diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex b98be0c9fb..4c19008b79 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -28,6 +28,7 @@ import {updateScene,} from '../services/creativeDirector/local.js';import { suggestCastForBrief, applyAutoCastToProject, toSuggestionView } from '../services/creativeDirector/autoCast.js';+import { enqueueFirstPassPortraits } from '../services/creativeDirector/firstPassGen.js';import { startCreativeDirectorProject } from '../services/creativeDirector/completionHook.js';import { createSmokeTestProject } from '../services/creativeDirector/smokeTest.js';@@ -106,7 +107,7 @@ router.delete('/:id', asyncHandler(async (req, res) => {// treatment as they land. The response carries `composing` so the UI can tell// the user the director took over.router.post('/:id/auto-cast', asyncHandler(async (req, res) => {- const { brief, types, limit, compose } = validateRequest(creativeDirectorAutoCastApplySchema, req.body);+ const { brief, types, limit, compose, generateFirstPass } = validateRequest(creativeDirectorAutoCastApplySchema, req.body);const result = await applyAutoCastToProject(req.params.id, { brief, types, limit });const project = result.project;const cast = project?.cast;@@ -120,7 +121,20 @@ router.post('/:id/auto-cast', asyncHandler(async (req, res) => {if (composing) {startCreativeDirectorProject(req.params.id).catch((e) => console.log(`⚠️ CD auto-compose failed: ${e.message}`));}- res.json({ ...result, composing });+ // First-pass gen (#1818): when opted in, kick off a catalog portrait render+ // for each member auto-cast just added that has no portrait yet. The renders+ // are enqueued onto the media-job queue and land via the durable catalog+ // attach hook (#1359) — we await only the (fast) enqueue so the response can+ // report how many were queued; the renders themselves run in the background.+ let firstPass = null;+ if (generateFirstPass && Array.isArray(result.added) && result.added.length > 0) {+ firstPass = await enqueueFirstPassPortraits(result.added)+ .catch((e) => {+ console.log(`⚠️ CD first-pass portraits failed: ${e.message}`);+ return null;+ });+ }+ res.json({ ...result, composing, ...(firstPass ? { firstPass } : {}) });}));// Agent-callable: write the treatment doc.diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex 25c2af136f..1346e92cfa 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -25,9 +25,16 @@ vi.mock('../services/creativeDirector/autoCast.js', () => ({toSuggestionView: (hit) => ({ ingredientId: hit.ingredient.id, name: hit.ingredient.name, type: hit.ingredient.type, score: hit.rrfScore, searchMethod: hit.searchMethod }),}));+// Mock first-pass gen (#1818) so the route test doesn't pull the real+// mediaJobQueue/catalogDB graph; the route's job is to gate + dispatch.+vi.mock('../services/creativeDirector/firstPassGen.js', () => ({+ enqueueFirstPassPortraits: vi.fn(async () => ({ mode: 'local', enqueued: [], skipped: [] })),+}));+import * as cdService from '../services/creativeDirector/local.js';import * as autoCast from '../services/creativeDirector/autoCast.js';import * as hook from '../services/creativeDirector/completionHook.js';+import * as firstPass from '../services/creativeDirector/firstPassGen.js';import creativeDirectorRoutes from './creativeDirector.js';describe('creativeDirector routes', () => {@@ -350,4 +357,55 @@ describe('creativeDirector routes', () => {expect(hook.startCreativeDirectorProject).not.toHaveBeenCalled();});});++ describe('POST /:id/auto-cast — first-pass gen (#1818)', () => {+ it('enqueues first-pass portraits for the added members and returns the summary', async () => {+ autoCast.applyAutoCastToProject.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],+ });+ firstPass.enqueueFirstPassPortraits.mockResolvedValue({+ mode: 'local', enqueued: [{ ingredientId: 'p1', jobId: 'job-1' }], skipped: [],+ });+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPass: true });+ expect(r.status).toBe(200);+ expect(firstPass.enqueueFirstPassPortraits).toHaveBeenCalledWith([{ ingredientId: 'p1' }]);+ expect(r.body.firstPass).toEqual({ mode: 'local', enqueued: [{ ingredientId: 'p1', jobId: 'job-1' }], skipped: [] });+ });++ it('does not enqueue when generateFirstPass 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({});+ expect(r.status).toBe(200);+ expect(firstPass.enqueueFirstPassPortraits).not.toHaveBeenCalled();+ expect(r.body.firstPass).toBeUndefined();+ });++ it('does not enqueue when nothing was added', async () => {+ autoCast.applyAutoCastToProject.mockResolvedValue({ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [], suggestions: [] });+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPass: true });+ expect(r.status).toBe(200);+ expect(firstPass.enqueueFirstPassPortraits).not.toHaveBeenCalled();+ expect(r.body.firstPass).toBeUndefined();+ });++ it('composes and generates first-pass portraits together', async () => {+ autoCast.applyAutoCastToProject.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],+ });+ firstPass.enqueueFirstPassPortraits.mockResolvedValue({ mode: 'local', enqueued: [{ ingredientId: 'p1', jobId: 'j' }], skipped: [] });+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ compose: true, generateFirstPass: true });+ expect(r.status).toBe(200);+ expect(r.body.composing).toBe(true);+ expect(hook.startCreativeDirectorProject).toHaveBeenCalledWith('cd-1');+ expect(firstPass.enqueueFirstPassPortraits).toHaveBeenCalledWith([{ ingredientId: 'p1' }]);+ });++ it('400s on a non-boolean generateFirstPass', async () => {+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPass: 'yes' });+ expect(r.status).toBe(400);+ expect(autoCast.applyAutoCastToProject).not.toHaveBeenCalled();+ });+ });});diff --git a/server/services/creativeDirector/firstPassGen.js b/server/services/creativeDirector/firstPassGen.jsnew file mode 100644index 0000000000..0dcfa6d3b1--- /dev/null+++ b/server/services/creativeDirector/firstPassGen.js@@ -0,0 +1,154 @@+/**+ * Creative Director — first-pass asset generation (#1818).+ *+ * Follow-up to the Auto-cast MVP (#1810) and auto-compose (#1817). When the+ * autonomous path seeds a project's cast from the catalog, an opt-in+ * "generate first-pass assets" step kicks off a catalog portrait render for+ * each freshly-cast member that has no portrait yet — so the cast "arrives+ * on-model" without the user hand-rendering each ingredient.+ *+ * Reuse, not a new pipeline (the issue's explicit constraint). Each render is+ * an ordinary image-gen job enqueued onto the SAME mediaJobQueue with the same+ * `catalogAttach` tag the manual portrait path uses (#1359), so the durable+ * server-side `catalogImageAttachHook` files the finished render onto the+ * ingredient as its portrait — even with no client mounted. We add no attach+ * logic here; we only enqueue and tag.+ *+ * Director-first + strictly optional: only the queue-backed modes (local /+ * codex) are seeded — they route through the durable attach hook. If image-gen+ * is configured for external SD-API, codex is disabled, etc., first-pass gen+ * skips gracefully (recorded in the returned summary) rather than failing the+ * auto-cast request. Autonomy seeds what it can; the director takes over.+ */++import { enqueueJob } from '../mediaJobQueue/index.js';+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 { payloadSnippet, getActiveCatalogType } from '../../lib/catalogTypes.js';++// Keep the derived portrait prompt bounded — enough descriptive text to render+// on-model, not the whole payload. Mirrors the cast-summary budget order of+// magnitude (catalogSeed's CAST_SUMMARY_CHARS = 200) but a touch wider since+// this is the actual render prompt, not a list snippet.+const PORTRAIT_PROMPT_CHARS = 400;++/**+ * Pure: derive an image-gen prompt for a catalog ingredient's first-pass+ * portrait. The name anchors the subject; the payload snippet (characters fall+ * back to `physicalDescription`, others to `description` — the same fallback+ * chain the cast summary uses via `snippetFallbackKeys`) supplies the visual+ * detail. Returns '' when the ingredient carries no usable name/description, so+ * the caller can skip it rather than queue a contentless render.+ */+export function buildPortraitPrompt(ingredient) {+ if (!ingredient || typeof ingredient !== 'object') return '';+ const name = typeof ingredient.name === 'string' ? ingredient.name.trim() : '';+ const detail = payloadSnippet(ingredient.payload, ingredient.type, PORTRAIT_PROMPT_CHARS, getActiveCatalogType);+ if (name && detail) return `${name} — ${detail}`;+ return name || detail || '';+}++/**+ * Resolve the queue-backed image-gen mode + the per-job base params, or a+ * not-ready marker when first-pass gen can't run as a background batch+ * (external mode, codex disabled). Reads settings the same way the imageGen+ * route + universeBuilderRender do, so the cleanC2PA / denoise cleaners apply+ * to first-pass renders exactly like a manual portrait render.+ */+async function resolveQueueModeParams() {+ const settings = await getSettings();+ const mode = settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;+ if (mode === IMAGE_GEN_MODE.CODEX) {+ const c = settings.imageGen?.codex || {};+ if (!c.enabled) return { mode, ready: false, reason: 'codex-disabled' };+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);+ return {+ mode,+ ready: true,+ jobParams: { mode: IMAGE_GEN_MODE.CODEX, codexPath: c.codexPath, model: c.model, cleanC2PA, denoise },+ };+ }+ if (mode === IMAGE_GEN_MODE.LOCAL) {+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);+ // modelId omitted → the worker falls through to its default ('dev') model,+ // matching the manual portrait path which also passes no modelId. pythonPath+ // may be null (FLUX.2 carries its own venv); the worker surfaces a missing+ // python over SSE rather than us hard-failing the whole auto-cast request.+ return {+ mode,+ ready: true,+ jobParams: { pythonPath: settings.imageGen?.local?.pythonPath || null, cleanC2PA, denoise },+ };+ }+ // external (or an unknown mode) — synchronous SD-API isn't suited for a+ // fire-and-forget background batch and doesn't route through the durable+ // attach hook, so first-pass gen sits this one out.+ return { mode, ready: false, reason: 'mode-unsupported' };+}++/**+ * Already has a live portrait? First-pass gen never clobbers an on-model+ * portrait — it only fills the gap for cast members that have none, so re-running+ * auto-cast with the toggle on is idempotent.+ */+async function ingredientHasPortrait(ingredientId) {+ const media = await listMediaForIngredient(ingredientId);+ return media.some((m) => m.kind === 'portrait');+}++/**+ * Enqueue first-pass portrait renders for the given cast members lacking a+ * portrait. `members` is the cast-view array (each carries `ingredientId`) —+ * typically the `added` set auto-cast just appended.+ *+ * Returns `{ mode, enqueued: [{ ingredientId, jobId }], skipped: [{ ingredientId, reason }], reason? }`.+ * Best-effort and self-contained: a single ingredient being gone / promptless is+ * recorded in `skipped`, never thrown — this runs as a side-effect of auto-cast,+ * so it must not fail the seeding it follows.+ */+export async function enqueueFirstPassPortraits(members = []) {+ const list = Array.isArray(members) ? members.filter((m) => m && m.ingredientId) : [];+ if (list.length === 0) return { mode: null, enqueued: [], skipped: [] };++ const resolved = await resolveQueueModeParams();+ if (!resolved.ready) {+ return { mode: resolved.mode, enqueued: [], skipped: [], reason: resolved.reason };+ }++ const enqueued = [];+ const skipped = [];+ for (const member of list) {+ const { ingredientId } = member;+ const ingredient = await getIngredient(ingredientId);+ if (!ingredient) {+ skipped.push({ ingredientId, reason: 'gone' });+ continue;+ }+ if (await ingredientHasPortrait(ingredientId)) {+ skipped.push({ ingredientId, reason: 'has-portrait' });+ continue;+ }+ const prompt = buildPortraitPrompt(ingredient);+ if (!prompt) {+ skipped.push({ ingredientId, reason: 'no-prompt' });+ continue;+ }+ const queued = enqueueJob({+ kind: 'image',+ params: {+ ...resolved.jobParams,+ prompt,+ // Tag the job so the durable catalogImageAttachHook (#1359) files the+ // finished render as this ingredient's portrait — no mounted client+ // required. Explicit `kind: 'portrait'` since this is a deliberate+ // first-pass portrait, not an ad-hoc reference render.+ catalogAttach: { ingredientId, kind: 'portrait' },+ },+ });+ enqueued.push({ ingredientId, jobId: queued.jobId });+ }+ console.log(`🎨 CD first-pass portraits: ${enqueued.length} queued, ${skipped.length} skipped (${resolved.mode})`);+ return { mode: resolved.mode, enqueued, skipped };+}diff --git a/server/services/creativeDirector/firstPassGen.test.js b/server/services/creativeDirector/firstPassGen.test.jsnew file mode 100644index 0000000000..1d91721ffb--- /dev/null+++ b/server/services/creativeDirector/firstPassGen.test.js@@ -0,0 +1,143 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the I/O boundaries; keep catalogTypes real (pure snippet transform) so+// buildPortraitPrompt exercises the actual physicalDescription fallback chain.+vi.mock('../mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(),+}));+vi.mock('../settings.js', () => ({+ getSettings: vi.fn(),+}));+vi.mock('../imageGen/index.js', () => ({+ resolveImageCleaners: vi.fn(() => ({ cleanC2PA: true, denoise: false })),+}));+vi.mock('../catalogDB.js', () => ({+ getIngredient: vi.fn(),+ listMediaForIngredient: vi.fn(),+}));++import { buildPortraitPrompt, enqueueFirstPassPortraits } from './firstPassGen.js';+import { enqueueJob } from '../mediaJobQueue/index.js';+import { getSettings } from '../settings.js';+import { getIngredient, listMediaForIngredient } from '../catalogDB.js';++let jobSeq = 0;++beforeEach(() => {+ vi.clearAllMocks();+ jobSeq = 0;+ enqueueJob.mockImplementation(() => ({ jobId: `job-${++jobSeq}`, position: 1, status: 'queued' }));+ // Default: local mode configured, ingredients have no portrait.+ getSettings.mockResolvedValue({ imageGen: { mode: 'local', local: { pythonPath: '/py' } } });+ listMediaForIngredient.mockResolvedValue([]);+});++describe('buildPortraitPrompt', () => {+ it('joins name + the physicalDescription snippet for a character', () => {+ const prompt = buildPortraitPrompt({+ id: 'c1', type: 'character', name: 'Vale',+ payload: { physicalDescription: 'a tall noir detective in a trench coat', description: 'ignored' },+ });+ expect(prompt).toBe('Vale — a tall noir detective in a trench coat');+ });++ it('falls back to description for non-character types', () => {+ const prompt = buildPortraitPrompt({+ id: 'p1', type: 'place', name: 'The Pier', payload: { description: 'a fog-soaked dock at night' },+ });+ expect(prompt).toBe('The Pier — a fog-soaked dock at night');+ });++ it('uses the name alone when there is no descriptive payload', () => {+ expect(buildPortraitPrompt({ id: 'x', type: 'object', name: 'Brass Key', payload: {} })).toBe('Brass Key');+ });++ it('returns "" for a null / nameless+descriptionless ingredient', () => {+ expect(buildPortraitPrompt(null)).toBe('');+ expect(buildPortraitPrompt({ id: 'x', type: 'object', name: ' ', payload: {} })).toBe('');+ });+});++describe('enqueueFirstPassPortraits', () => {+ it('enqueues a portrait-tagged job per member lacking a portrait', async () => {+ getIngredient.mockImplementation(async (id) => ({+ id, type: 'character', name: `Name-${id}`, payload: { physicalDescription: `desc ${id}` },+ }));+ const out = await enqueueFirstPassPortraits([{ ingredientId: 'a' }, { ingredientId: 'b' }]);+ expect(out.mode).toBe('local');+ expect(out.enqueued).toEqual([+ { ingredientId: 'a', jobId: 'job-1' },+ { ingredientId: 'b', jobId: 'job-2' },+ ]);+ expect(out.skipped).toEqual([]);+ // Each job carries the catalogAttach tag the durable hook keys off, with an+ // explicit portrait kind and the local pythonPath/cleaners folded in.+ const firstJob = enqueueJob.mock.calls[0][0];+ expect(firstJob.kind).toBe('image');+ expect(firstJob.params.catalogAttach).toEqual({ ingredientId: 'a', kind: 'portrait' });+ expect(firstJob.params.prompt).toBe('Name-a — desc a');+ expect(firstJob.params.pythonPath).toBe('/py');+ expect(firstJob.params.cleanC2PA).toBe(true);+ });++ it('skips a member that already has a portrait (idempotent re-run)', async () => {+ getIngredient.mockImplementation(async (id) => ({ id, type: 'character', name: id, payload: { physicalDescription: 'd' } }));+ listMediaForIngredient.mockImplementation(async (id) =>+ id === 'a' ? [{ kind: 'portrait', mediaKey: 'a.png' }] : []);+ const out = await enqueueFirstPassPortraits([{ ingredientId: 'a' }, { ingredientId: 'b' }]);+ expect(out.enqueued).toEqual([{ ingredientId: 'b', jobId: 'job-1' }]);+ expect(out.skipped).toEqual([{ ingredientId: 'a', reason: 'has-portrait' }]);+ expect(enqueueJob).toHaveBeenCalledTimes(1);+ });++ it('skips a gone ingredient and one with no usable prompt', async () => {+ getIngredient.mockImplementation(async (id) => {+ if (id === 'gone') return null;+ if (id === 'blank') return { id, type: 'object', name: ' ', payload: {} };+ return { id, type: 'character', name: id, payload: { physicalDescription: 'd' } };+ });+ const out = await enqueueFirstPassPortraits([{ ingredientId: 'gone' }, { ingredientId: 'blank' }, { ingredientId: 'ok' }]);+ expect(out.enqueued).toEqual([{ ingredientId: 'ok', jobId: 'job-1' }]);+ expect(out.skipped).toEqual([+ { ingredientId: 'gone', reason: 'gone' },+ { ingredientId: 'blank', reason: 'no-prompt' },+ ]);+ });++ it('enqueues codex-mode jobs only when codex is enabled', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'codex', codex: { enabled: true, codexPath: '/cx', model: 'gpt-image' } } });+ getIngredient.mockResolvedValue({ id: 'a', type: 'character', name: 'A', payload: { physicalDescription: 'd' } });+ const out = await enqueueFirstPassPortraits([{ ingredientId: 'a' }]);+ expect(out.mode).toBe('codex');+ expect(out.enqueued).toHaveLength(1);+ expect(enqueueJob.mock.calls[0][0].params.mode).toBe('codex');+ expect(enqueueJob.mock.calls[0][0].params.codexPath).toBe('/cx');+ });++ it('skips gracefully when codex is the mode but disabled', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'codex', codex: { enabled: false } } });+ const out = await enqueueFirstPassPortraits([{ ingredientId: 'a' }]);+ expect(out).toEqual({ mode: 'codex', enqueued: [], skipped: [], reason: 'codex-disabled' });+ expect(enqueueJob).not.toHaveBeenCalled();+ expect(getIngredient).not.toHaveBeenCalled();+ });++ it('skips gracefully for external mode (not queue-backed)', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });+ const out = await enqueueFirstPassPortraits([{ ingredientId: 'a' }]);+ expect(out).toEqual({ mode: 'external', enqueued: [], skipped: [], reason: 'mode-unsupported' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('returns an empty summary for no members (never reads settings)', async () => {+ const out = await enqueueFirstPassPortraits([]);+ expect(out).toEqual({ mode: null, enqueued: [], skipped: [] });+ expect(getSettings).not.toHaveBeenCalled();+ });++ it('ignores members without an ingredientId', async () => {+ getIngredient.mockResolvedValue({ id: 'a', type: 'character', name: 'A', payload: { physicalDescription: 'd' } });+ const out = await enqueueFirstPassPortraits([{ foo: 'bar' }, null, { ingredientId: 'a' }]);+ expect(out.enqueued).toEqual([{ ingredientId: 'a', jobId: 'job-1' }]);+ });+});