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

Creative Director: evaluate rendered scenes on a local vision model, not Opus

[._.]/ Adam Eivye861788b0c7b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 836961c2dc..b69617ec71 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -85,3 +85,5 @@
- **A wrong local-model default now self-corrects instead of failing the run.** When an Ollama or LM Studio provider is pointed at a model that isn't actually installed (a stale or mis-typed `defaultModel`, or a model you've since deleted), an API call against it returned a dead-end "model not found" — the user had to notice, open settings, and pick a real model by hand. The shared `callProviderAISimple` path now catches that error, lists the backend's actually-installed models, picks the best fit (the editorial recommender's family/size ranking, skipping embedding-only weights), repoints the provider's `defaultModel` (and any tier slot pointing at a missing model), tells the user via a low-priority notification + activity log, and retries the call once — so the run succeeds and the bad config is fixed going forward. Remote/API and CLI providers are left untouched, since their installed models can't be enumerated. (`server/services/localModelHealing.js`, `server/lib/aiProvider.js`)
- **[issue-2192] OpenCode TUI prompt paste no longer gets silently swallowed during slow startup.** When pasting a task prompt into a non-Claude TUI (OpenCode, Codex, Gemini), the paste could be sent while the TUI was still initializing — the prompt never appeared in the input buffer and the agent sat idle for 185s before being reaped as a false success. The TUI paste-commit path now verifies the pasted text actually rendered in the buffer (extracting a unique prefix from the prompt and checking for it after the paste-marker or fallback timeout). If verification fails, the paste is retried with exponential backoff (800ms, 1.6s, 3.2s); after 3 attempts the agent is finalized as a startup failure with a clear `paste-not-rendered` reason instead of a misleading `idle-complete` success. Claude TUIs already had positive input-ready detection and are unaffected. (`server/lib/tuiHandshake.js`, `server/services/agentTuiSpawning.js`)
+
+- **Creative Director now evaluates rendered scenes on a local vision model instead of Opus.** Judging each freshly-rendered scene ("does it match the style spec and deliver the intent?") used to spawn a full Chief-of-Staff coding agent that landed on the active provider's *heavy* model — Opus for a Claude provider — purely to look at a couple of thumbnails and record a verdict. That decision now runs server-side through PortOS's vision-API path: it attaches the sampled frames to a **local, vision-capable model** (Ollama/LM Studio VLM) and parses a structured accept/retry/fail verdict, applying the exact same scene transitions (accept → add the clip to the collection; miss with retries left → re-render with a refined prompt; miss when exhausted → drop the scene). Pick the model under **Settings → AI Assignments → "Scene evaluation model"**; leave it blank to auto-select an installed local vision model. Installs with no local vision model configured transparently fall back to the original coding-agent path, so nothing breaks — but if you have a VLM installed, scene evaluation is now local and free. (`server/services/creativeDirector/sceneEvaluator.js`)
diff --git a/server/lib/creativeDirectorPrompts.js b/server/lib/creativeDirectorPrompts.js
index 1931f2dcbe..a62d049b8d 100644
--- a/server/lib/creativeDirectorPrompts.js
+++ b/server/lib/creativeDirectorPrompts.js
@@ -146,3 +146,71 @@ export async function buildEvaluatePrompt(project, scene) {
const view = buildEvaluateView(project, scene);
return buildPrompt('cd-evaluate', view);
}
+
+// Max render attempts before a scene is given up on. Mirrors the "max 3" the
+// cd-evaluate agent template enforces — the server-side vision evaluator must
+// make the same accept/retry/fail decision the agent would.
+export const CD_MAX_SCENE_RETRIES = 3;
+
+/**
+ * Structured-JSON evaluation prompt for the SERVER-SIDE vision path.
+ *
+ * Unlike `cd-evaluate` (a CLI agent that Reads frame files off disk with its
+ * vision tool and then issues an HTTP PATCH), this prompt drives a direct
+ * vision-model API call: the sampled frames are attached to the request as
+ * image blocks by the runner, and the model must return ONLY a JSON verdict
+ * that `applySceneVerdict` maps to the exact same scene transitions the agent's
+ * PATCH would (accept → collection add; miss+retries-left → re-render with a
+ * refined prompt; miss+exhausted → fail). Kept in code (not a UI-editable stage
+ * template) because the output contract must stay machine-parseable.
+ *
+ * @param {object} project
+ * @param {object} scene
+ * @param {number} frameCount — how many frames are attached to the call
+ * @returns {string}
+ */
+export function buildEvaluateVisionPrompt(project, scene, frameCount) {
+ const total = project.treatment?.scenes?.length;
+ const positionLabel = total ? `${(scene.order ?? 0) + 1}/${total}` : `${(scene.order ?? 0) + 1}/?`;
+ const styleSpec = (project.styleSpec || '').trim()
+ || '(none — judge against a coherent visual language derived from the project name + scene intent)';
+ const retryCount = scene.retryCount || 0;
+ const retriesLeft = retryCount < CD_MAX_SCENE_RETRIES;
+ const strategy = scene.useContinuationFromPrior
+ ? 'continued from the prior scene\'s last frame'
+ : (scene.sourceImageFile ? 'seeded from a source image (image-to-video)' : 'text-to-video');
+ const frameLine = frameCount > 1
+ ? `You are shown ${frameCount} frames sampled across the scene's timeline, in order (first = start, last = end).`
+ : 'You are shown a single representative frame from the scene.';
+
+ return `You are the creative director for the video project "${project.name}". Evaluate a freshly-rendered scene and decide whether it works.
+
+${frameLine}
+
+## Scene
+- Position: ${positionLabel}
+- Intent: ${scene.intent || '(unspecified)'}
+- Render strategy: ${strategy}
+- Attempt: ${retryCount + 1} of ${CD_MAX_SCENE_RETRIES + 1} (${retriesLeft ? 'a retry is still available' : 'this is the final attempt — no retries left'})
+
+## Style spec (apply to every scene)
+${styleSpec}
+
+## Judge on three dimensions
+1. Style adherence — does it match the style spec across the whole sequence, not just the first frame?
+2. Continuity — does it flow from the project's established tone, color, and characters? (If this is scene 1, just check it stands on its own.)
+3. Scene intent — does it actually depict "${scene.intent || 'the intended action'}" by the END of the clip? Intent that arrives late still counts as delivered — accept it. Perfect is the enemy of done: accept anything good enough.
+
+## Output — return ONLY this JSON object, no markdown, no prose, no code fences
+{
+ "accepted": <boolean>, // true if the render is good enough to keep
+ "score": <number 0.0-1.0>, // overall quality
+ "notes": "<one short sentence: why accepted, or what to fix>"${retriesLeft ? `,
+ "refinedPrompt": "<ONLY when accepted is false: a revised render prompt that fixes the problem; omit when accepted>",
+ "imageStrength": <OPTIONAL number 0.0-1.0 for image-to-video scenes only — lower to let the prompt express more, raise to hug the seed image; omit to leave unchanged>` : ''}
+}
+
+${retriesLeft
+ ? 'If the render misses the mark, set accepted=false and provide a refinedPrompt so the scene can be re-rendered.'
+ : 'Retries are exhausted. Set accepted=true only if the render is acceptable; otherwise accepted=false and the scene will be dropped.'}`;
+}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index beb79cfb0a..d443ba80f6 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -372,6 +372,14 @@ export const featureProviderConfigSchema = z.object({
model: z.preprocess(emptyToUndefined, z.string().optional()),
});
+// Creative Director settings slice. `evaluation` pins the vision provider/model
+// used to judge each rendered scene server-side (blank = auto-pick a local
+// vision model, else fall back to the coding agent). Reuses the shared
+// feature-provider shape so an empty-string picker value normalizes to unset.
+export const creativeDirectorSettingsSchema = z.object({
+ evaluation: featureProviderConfigSchema.partial().optional(),
+});
+
/**
* Validate data against a schema
* Returns { success: true, data } or { success: false, errors }
diff --git a/server/routes/settings.js b/server/routes/settings.js
index 95ad3524cc..9dbb008897 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -10,7 +10,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -133,6 +133,11 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.codeReview !== undefined) {
validateRequest(codeReviewSettingsSchema.partial(), req.body.codeReview);
}
+ // Creative Director scene-evaluation provider/model pin — validate the slice
+ // when present so a malformed picker save can't write a bad provider config.
+ if (req.body?.creativeDirector !== undefined) {
+ validateRequest(creativeDirectorSettingsSchema.partial(), req.body.creativeDirector);
+ }
// Home location ({ lat, lon }) read by the weather_now voice tool. The schema
// already makes both fields optional + nullable (clearing falls back to the
// tool default), and the refine enforces both-or-neither — so validate the
diff --git a/server/services/aiAssignments.js b/server/services/aiAssignments.js
index 1222f98c41..2c98190932 100644
--- a/server/services/aiAssignments.js
+++ b/server/services/aiAssignments.js
@@ -157,6 +157,18 @@ const addSettingsEntries = async (entries) => {
}));
}
+ entries.push(makeEntry({
+ id: 'settings.creativeDirector.evaluation',
+ area: 'Creative Director',
+ label: 'Scene evaluation model',
+ source: 'settings.creativeDirector.evaluation',
+ providerId: settings.creativeDirector?.evaluation?.providerId || null,
+ model: settings.creativeDirector?.evaluation?.model || null,
+ providerTypes: apiProviderTypes,
+ notes: 'Vision model that judges each rendered scene. Blank = auto-pick an installed local (Ollama / LM Studio) vision model; if none is available it falls back to the coding agent (Opus).',
+ link: '/creative-director',
+ }));
+
entries.push(makeEntry({
id: 'settings.voice.llm',
area: 'Voice',
@@ -476,6 +488,11 @@ export async function updateAiAssignment(id, { providerId, model } = {}) {
return getAiAssignments();
}
+ if (id === 'settings.creativeDirector.evaluation') {
+ await patchSettingsPath('creativeDirector.evaluation', { providerId: nextProviderId, model: nextModel });
+ return getAiAssignments();
+ }
+
if (id === 'settings.voice.llm') {
await updateVoiceConfig({ llm: { provider: nextProviderId || '', model: nextModel || '' } });
return getAiAssignments();
diff --git a/server/services/aiAssignments.test.js b/server/services/aiAssignments.test.js
index af74c04d56..01497eb2f0 100644
--- a/server/services/aiAssignments.test.js
+++ b/server/services/aiAssignments.test.js
@@ -109,6 +109,7 @@ describe('getAiAssignments', () => {
expect(ids).toContain('provider.active');
expect(ids).toContain('settings.embeddings');
expect(ids).toContain('settings.voice.vision');
+ expect(ids).toContain('settings.creativeDirector.evaluation');
expect(ids).toContain('cos.task.morning-brief');
});
});
@@ -129,6 +130,11 @@ describe('updateAiAssignment routing', () => {
expect(mocks.updateSettings).toHaveBeenCalledWith({ autofixer: { providerId: 'claude', model: 'opus' } });
});
+ it('settings.creativeDirector.evaluation writes the vision provider/model under creativeDirector', async () => {
+ await updateAiAssignment('settings.creativeDirector.evaluation', { providerId: 'ollama', model: 'qwen2.5-vl' });
+ expect(mocks.updateSettings).toHaveBeenCalledWith({ creativeDirector: { evaluation: { providerId: 'ollama', model: 'qwen2.5-vl' } } });
+ });
+
it('cos.task.<existing> updates the schedule interval', async () => {
await updateAiAssignment('cos.task.morning-brief', { providerId: 'claude', model: 'opus' });
expect(mocks.updateTaskInterval).toHaveBeenCalledWith('morning-brief', { providerId: 'claude', model: 'opus' });
diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.js
index 0ffadff7d8..3da4010335 100644
--- a/server/services/creativeDirector/completionHook.js
+++ b/server/services/creativeDirector/completionHook.js
@@ -25,7 +25,8 @@
import { existsSync } from 'fs';
import { join } from 'path';
import { getProject, updateProject, updateScene, updateRun, recordRun } from './local.js';
-import { enqueueTreatmentTask, enqueueEvaluateTask } from './agentBridge.js';
+import { enqueueTreatmentTask } from './agentBridge.js';
+import { dispatchSceneEvaluation } from './sceneEvaluator.js';
import { runSceneRender } from './sceneRunner.js';
import { runStitch } from './stitchRunner.js';
import { sampleEvaluationFrames } from '../videoGen/local.js';
@@ -279,7 +280,7 @@ export async function advanceAfterSceneSettled(projectId) {
console.log(`▶️ CD resume: re-firing evaluator for orphaned 'evaluating' scene ${orphanedEvaluating.sceneId} on project ${project.id} (renderedJobId preserved from pre-pause render).`);
const sceneRefreshed = recheck?.treatment?.scenes?.find((s) => s.sceneId === orphanedEvaluating.sceneId);
if (recheck && sceneRefreshed) {
- await enqueueEvaluateTask(recheck, { ...sceneRefreshed, evaluationFrames: frames });
+ await dispatchSceneEvaluation(recheck, { ...sceneRefreshed, evaluationFrames: frames });
}
return;
} finally {
diff --git a/server/services/creativeDirector/sceneEvaluator.js b/server/services/creativeDirector/sceneEvaluator.js
new file mode 100644
index 0000000000..188866d182
--- /dev/null
+++ b/server/services/creativeDirector/sceneEvaluator.js
@@ -0,0 +1,298 @@
+/**
+ * Creative Director — server-side scene evaluator (local-vision path).
+ *
+ * The `evaluate` step judges a freshly-rendered scene against the style spec +
+ * scene intent. Historically this spawned a full CoS coding agent that landed
+ * on the active provider's HEAVY model (Opus for Claude) purely to Read a
+ * couple of thumbnails and PATCH a verdict — vastly overpowered for a bounded
+ * "look at 1-3 frames, score 3 dimensions, accept/retry/fail" decision.
+ *
+ * This module runs that same decision server-side through PortOS's existing
+ * vision-API path (`runPromptThroughProvider({ screenshots })`), preferring a
+ * LOCAL vision-capable model (Ollama/LM Studio VLM). A CoS *agent* task can't
+ * use a local vision model at all — `agentProviderResolution.js` rejects
+ * `type:'api'` providers (no file-writing harness) and a claude-on-Ollama CLI
+ * coding model isn't vision-capable — so the only way to evaluate on a local
+ * vision model is this direct API call.
+ *
+ * `dispatchSceneEvaluation` is the single entry point the orchestrator calls.
+ * When no vision-capable API provider is configured/available (or the vision
+ * call fails), it falls back to the original Opus-agent path
+ * (`enqueueEvaluateTask`), so installs without a local vision model keep
+ * working exactly as before.
+ */
+
+import { existsSync } from 'fs';
+import { z } from 'zod';
+
+import { PATHS } from '../../lib/fileUtils.js';
+import { safeUnder } from '../../lib/ffmpeg.js';
+import { extractJson } from '../../lib/jsonExtract.js';
+import { runPromptThroughProvider, assertVisionRunUsedImages } from '../../lib/promptRunner.js';
+import { buildEvaluateVisionPrompt, CD_MAX_SCENE_RETRIES } from '../../lib/creativeDirectorPrompts.js';
+import { getSettings } from '../settings.js';
+import { getProviderById } from '../providers.js';
+import { listVisionModels } from '../localLlm.js';
+import { addItem } from '../mediaCollections.js';
+import { updateScene, recordRun } from './local.js';
+import { enqueueEvaluateTask } from './agentBridge.js';
+
+// Cap frames per call — the runner base64-inlines every frame into one request
+// body, so a large batch balloons the prompt and a local VLM's context window.
+// 5 samples across the timeline is plenty to judge a short clip.
+const MAX_EVAL_FRAMES = 5;
+// Local VLMs on modest hardware can be slow to first token; give them room.
+const VISION_EVAL_TIMEOUT_MS = 180000;
+// Structured JSON verdict, so the reply can't truncate mid-object.
+const VISION_EVAL_MAX_TOKENS = 600;
+
+// Local backends served by an aiToolkit `api`-type provider. Auto-resolution
+// only picks from these — the whole point is a LOCAL vision model. An explicit
+// assignment (below) may still point at any configured API vision provider.
+const LOCAL_VISION_BACKENDS = new Set(['ollama', 'lmstudio']);
+
+// Only `accepted` is load-bearing — everything else is advisory. Coerce loose
+// numbers/strings, and `.catch(undefined)` so an out-of-range or unparseable
+// optional field just drops out instead of rejecting the whole verdict (which
+// would needlessly fall the scene back to the Opus agent). A model that emits
+// `"score": 85` meaning 85% shouldn't nuke an otherwise-usable accept/reject.
+const verdictSchema = z.object({
+ accepted: z.boolean(),
+ score: z.coerce.number().min(0).max(1).optional().catch(undefined),
+ notes: z.coerce.string().max(2000).optional().catch(undefined),
+ refinedPrompt: z.coerce.string().max(8000).optional().catch(undefined),
+ imageStrength: z.coerce.number().min(0).max(1).optional().catch(undefined),
+});
+
+/**
+ * Parse a vision model's reply into a validated verdict. Uses the shared
+ * `extractJson` (code-fence stripping, balanced-block walking, trailing-comma
+ * repair) to tolerate chatter around the object, preferring the block that
+ * actually carries a boolean `accepted`. Throws when no usable verdict is
+ * present so the caller falls back to the agent path.
+ *
+ * Pure — exported for tests.
+ */
+export function parseVisionVerdict(text) {
+ const { value } = extractJson(String(text || ''), {
+ shapePredicate: (v) => v && typeof v === 'object' && typeof v.accepted === 'boolean',
+ });
+ if (value === undefined) throw new Error('no JSON verdict in vision reply');
+ return verdictSchema.parse(value);
+}
+
+/**
+ * Resolve which API provider + model should run the vision evaluation.
+ *
+ * Order:
+ * 1. Explicit assignment — `settings.creativeDirector.evaluation.providerId`
+ * (set via AI Assignments). Honored as long as it's an enabled API
+ * provider; the assigned `model` (if any) is used verbatim.
+ * 2. Auto — the first installed local (Ollama/LM Studio) vision-capable model.
+ *
+ * @returns {Promise<{ provider: object, model: string|undefined }|null>} null
+ * when nothing suitable is configured (caller falls back to the agent).
+ */
+export async function resolveVisionEvalTarget() {
+ // An API provider is usable only if it exists and is enabled — vision runs
+ // through the api-only chat path, so a CLI/TUI provider can't serve it.
+ const usableApiProvider = async (id) => {
+ const p = await getProviderById(id).catch(() => null);
+ return p && p.type === 'api' && p.enabled !== false ? p : null;
+ };
+
+ const settings = await getSettings().catch(() => ({}));
+ const assigned = settings?.creativeDirector?.evaluation || {};
+
+ if (assigned.providerId) {
+ const provider = await usableApiProvider(assigned.providerId);
+ if (provider) return { provider, model: assigned.model || undefined };
+ // A stale/invalid pin shouldn't silently downgrade to Opus — fall through
+ // to auto-resolution so a healthy local VLM is still preferred.
+ }
+
+ const visionModels = await listVisionModels().catch(() => []);
+ const local = visionModels.find((m) => LOCAL_VISION_BACKENDS.has(m.backend));
+ if (local) {
+ const provider = await usableApiProvider(local.providerId);
+ if (provider) return { provider, model: local.id };
+ }
+ return null;
+}
+
+/**
+ * Collect the on-disk frame paths for a scene's evaluation. Prefers the
+ * multi-frame timeline samples; falls back to the single `{jobId}.jpg`
+ * thumbnail. Only returns files that actually exist (frames can be deleted with
+ * the underlying video while a project is paused).
+ */
+function collectFramePaths(scene) {
+ // safeUnder basenames + rejects `..`/slashes so a tampered scene.renderedJobId
+ // or evaluationFrames entry can't traverse outside the thumbnails dir.
+ const frames = Array.isArray(scene.evaluationFrames) ? scene.evaluationFrames : [];
+ const paths = frames
+ .map((f) => safeUnder(PATHS.videoThumbnails, f))
+ .filter((p) => p && existsSync(p))
+ .slice(0, MAX_EVAL_FRAMES);
+ if (paths.length) return paths;
+ if (scene.renderedJobId) {
+ const single = safeUnder(PATHS.videoThumbnails, `${scene.renderedJobId}.jpg`);
+ if (single && existsSync(single)) return [single];
+ }
+ return [];
+}
+
+/**
+ * Evaluate a scene with a vision model. Resolves the provider, attaches the
+ * sampled frames, and parses a structured verdict.
+ *
+ * @returns {Promise<
+ * | { ok: true, verdict: object, llm: { provider: string, model: string|null } }
+ * | { ok: false, fallbackToAgent: true, reason: string }
+ * >}
+ */
+export async function evaluateSceneWithVision(project, scene) {
+ const target = await resolveVisionEvalTarget();
+ if (!target) {
+ return { ok: false, fallbackToAgent: true, reason: 'no vision-capable API provider configured' };
+ }
+
+ const frames = collectFramePaths(scene);
+ if (frames.length === 0) {
+ // No image on disk — the vision API path has nothing to send. The agent's
+ // template has the same prerequisite, but let it handle the edge case.
+ return { ok: false, fallbackToAgent: true, reason: 'no evaluation frames on disk' };
+ }
+
+ const prompt = buildEvaluateVisionPrompt(project, scene, frames.length);
+ const result = await runPromptThroughProvider({
+ provider: target.provider,
+ model: target.model,
+ prompt,
+ source: 'cd-scene-evaluate',
+ screenshots: frames,
+ timeout: VISION_EVAL_TIMEOUT_MS,
+ maxTokens: VISION_EVAL_MAX_TOKENS,
+ });
+
+ // Guard against a silent fallback to a non-API provider (which would drop the
+ // images and hallucinate a verdict from the prompt text alone).
+ const ran = assertVisionRunUsedImages(result, target.provider);
+ const verdict = parseVisionVerdict(result.text);
+ return {
+ ok: true,
+ verdict,
+ llm: { provider: ran.id || target.provider.id, model: result.model || target.model || null },
+ };
+}
+
+// advanceAfterSceneSettled is dynamically imported to avoid a static import
+// cycle (completionHook → sceneEvaluator → completionHook).
+const loadAdvance = () => import('./completionHook.js').then((m) => m.advanceAfterSceneSettled);
+
+/**
+ * Apply a parsed verdict to a scene, driving the exact same transitions the
+ * agent's PATCH + orchestrator would:
+ * - accepted → status 'accepted' + add the rendered video to the
+ * project collection, then advance.
+ * - miss, retries left → status 'pending' + refined prompt + retryCount++
+ * (+ optional imageStrength), then advance (re-render).
+ * - miss, exhausted → status 'failed', then advance.
+ *
+ * `score`/`imageStrength` are already validated to [0,1]-or-undefined by
+ * `verdictSchema`, so no re-clamping is needed here.
+ */
+export async function applySceneVerdict(project, scene, verdict, llm = null) {
+ const evaluation = {
+ accepted: !!verdict.accepted,
+ score: verdict.score,
+ notes: verdict.notes || '',
+ sampledAt: new Date().toISOString(),
+ };
+ const retryCount = scene.retryCount || 0;
+
+ // Best-effort run record so the Runs tab shows a local-model evaluation
+ // instead of a silent gap where an agent run used to be.
+ await recordRun(project.id, {
+ kind: 'evaluate',
+ sceneId: scene.sceneId || null,
+ status: 'completed',
+ completedAt: evaluation.sampledAt,
+ via: 'vision',
+ provider: llm?.provider || null,
+ model: llm?.model || null,
+ }).catch((err) => console.log(`⚠️ CD vision recordRun failed: ${err.message}`));
+
+ const advanceAfterSceneSettled = await loadAdvance();
+
+ if (verdict.accepted) {
+ await updateScene(project.id, scene.sceneId, { status: 'accepted', evaluation });
+ if (project.collectionId && scene.renderedJobId) {
+ await addItem(project.collectionId, { kind: 'video', ref: scene.renderedJobId })
+ .catch((err) => {
+ // Idempotent — a re-evaluation of an already-collected scene is fine.
+ if (!/already in collection/i.test(err.message)) {
+ console.log(`⚠️ CD collection add failed for ${scene.renderedJobId}: ${err.message}`);
+ }
+ });
+ }
+ console.log(`✅ CD scene ${scene.sceneId} accepted by vision (${llm?.provider || 'local'}/${llm?.model || '?'})`);
+ return advanceAfterSceneSettled(project.id);
+ }
+
+ if (retryCount < CD_MAX_SCENE_RETRIES) {
+ const patch = { status: 'pending', retryCount: retryCount + 1, evaluation };
+ if (verdict.refinedPrompt && verdict.refinedPrompt.trim()) patch.prompt = verdict.refinedPrompt.trim();
+ if (verdict.imageStrength !== undefined) patch.imageStrength = verdict.imageStrength;
+ await updateScene(project.id, scene.sceneId, patch);
+ console.log(`🔁 CD scene ${scene.sceneId} rejected by vision — retry ${patch.retryCount}/${CD_MAX_SCENE_RETRIES}`);
+ return advanceAfterSceneSettled(project.id);
+ }
+
+ await updateScene(project.id, scene.sceneId, { status: 'failed', evaluation });
+ console.log(`⛔ CD scene ${scene.sceneId} failed by vision — retries exhausted`);
+ return advanceAfterSceneSettled(project.id);
+}
+
+/**
+ * Single entry point the orchestrator calls to settle a rendered scene. Tries
+ * the local-vision path; on no-provider or ANY failure falls back to the
+ * Opus-agent path. Never throws — it runs outside the Express request lifecycle
+ * (job-completion hook / orchestrator), where an uncaught throw would crash the
+ * process.
+ */
+export async function dispatchSceneEvaluation(project, scene) {
+ let result;
+ try {
+ result = await evaluateSceneWithVision(project, scene);
+ } catch (err) {
+ console.log(`⚠️ CD vision eval errored for scene ${scene.sceneId} — falling back to agent: ${err.message}`);
+ result = { ok: false, fallbackToAgent: true, reason: err.message };
+ }
+
+ if (result.ok) {
+ try {
+ await applySceneVerdict(project, scene, result.verdict, result.llm);
+ return { via: 'vision', verdict: result.verdict, llm: result.llm };
+ } catch (err) {
+ // Verdict came back but persisting/advancing threw. Don't re-run on the
+ // agent — that could double-apply the verdict (and re-add to the
+ // collection). Best-effort mark the scene failed so the orchestrator can
+ // recover, and never throw (this runs outside the request lifecycle).
+ console.error(`❌ CD applySceneVerdict failed for scene ${scene.sceneId}: ${err.message}`);
+ await updateScene(project.id, scene.sceneId, {
+ status: 'failed',
+ evaluation: {
+ accepted: false,
+ notes: `Vision verdict could not be applied: ${err.message}`,
+ sampledAt: new Date().toISOString(),
+ },
+ }).catch((e) => console.log(`⚠️ CD verdict-failure mark for ${scene.sceneId} failed: ${e.message}`));
+ const advanceAfterSceneSettled = await loadAdvance();
+ return advanceAfterSceneSettled(project.id).catch(() => {});
+ }
+ }
+
+ console.log(`🎬 CD scene ${scene.sceneId} evaluation via agent (${result.reason})`);
+ return enqueueEvaluateTask(project, scene);
+}
diff --git a/server/services/creativeDirector/sceneEvaluator.test.js b/server/services/creativeDirector/sceneEvaluator.test.js
new file mode 100644
index 0000000000..ca79ed1e1c
--- /dev/null
+++ b/server/services/creativeDirector/sceneEvaluator.test.js
@@ -0,0 +1,256 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+/**
+ * Tests for the server-side (local-vision) scene evaluator.
+ *
+ * Covers: verdict parsing (tolerant of fences/chatter), provider resolution
+ * (explicit pin → auto local pick → none), the vision-call happy path + the
+ * fall-back-to-agent contract, and applySceneVerdict's three transitions
+ * (accept + collection add / retry with refined prompt / fail when exhausted).
+ */
+
+const mocks = vi.hoisted(() => ({
+ runPromptThroughProvider: vi.fn(),
+ assertVisionRunUsedImages: vi.fn((r, p) => r?.provider || p),
+ getSettings: vi.fn(),
+ getProviderById: vi.fn(),
+ listVisionModels: vi.fn(),
+ addItem: vi.fn(),
+ updateScene: vi.fn(),
+ recordRun: vi.fn(),
+ enqueueEvaluateTask: vi.fn(),
+ advanceAfterSceneSettled: vi.fn(),
+ existsSync: vi.fn(() => true),
+}));
+
+vi.mock('fs', () => ({ existsSync: mocks.existsSync }));
+vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { videoThumbnails: '/data/video-thumbnails' } }));
+vi.mock('../../lib/aiProvider.js', () => ({ stripCodeFences: (s) => String(s).replace(/```[a-z]*\n?/gi, '').replace(/```/g, '') }));
+vi.mock('../../lib/promptRunner.js', () => ({
+ runPromptThroughProvider: mocks.runPromptThroughProvider,
+ assertVisionRunUsedImages: mocks.assertVisionRunUsedImages,
+}));
+vi.mock('../settings.js', () => ({ getSettings: mocks.getSettings }));
+vi.mock('../providers.js', () => ({ getProviderById: mocks.getProviderById }));
+vi.mock('../localLlm.js', () => ({ listVisionModels: mocks.listVisionModels }));
+vi.mock('../mediaCollections.js', () => ({ addItem: mocks.addItem }));
+vi.mock('./local.js', () => ({
+ updateScene: mocks.updateScene,
+ recordRun: mocks.recordRun,
+}));
+vi.mock('./agentBridge.js', () => ({ enqueueEvaluateTask: mocks.enqueueEvaluateTask }));
+vi.mock('./completionHook.js', () => ({ advanceAfterSceneSettled: mocks.advanceAfterSceneSettled }));
+
+const {
+ parseVisionVerdict,
+ resolveVisionEvalTarget,
+ evaluateSceneWithVision,
+ applySceneVerdict,
+ dispatchSceneEvaluation,
+} = await import('./sceneEvaluator.js');
+
+const OLLAMA = { id: 'ollama', type: 'api', enabled: true };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.existsSync.mockReturnValue(true);
+ mocks.getSettings.mockResolvedValue({});
+ mocks.listVisionModels.mockResolvedValue([]);
+ mocks.getProviderById.mockResolvedValue(null);
+ mocks.updateScene.mockResolvedValue({});
+ mocks.recordRun.mockResolvedValue({});
+ mocks.addItem.mockResolvedValue({});
+ mocks.advanceAfterSceneSettled.mockResolvedValue(undefined);
+ mocks.assertVisionRunUsedImages.mockImplementation((r, p) => r?.provider || p);
+});
+
+describe('parseVisionVerdict', () => {
+ it('parses a bare JSON object', () => {
+ const v = parseVisionVerdict('{"accepted": true, "score": 0.8, "notes": "great"}');
+ expect(v).toEqual({ accepted: true, score: 0.8, notes: 'great' });
+ });
+
+ it('tolerates code fences and surrounding prose', () => {
+ const text = 'Here is my verdict:\n```json\n{"accepted": false, "score": 0.3, "notes": "off-style", "refinedPrompt": "add fog"}\n```\nHope that helps.';
+ const v = parseVisionVerdict(text);
+ expect(v.accepted).toBe(false);
+ expect(v.refinedPrompt).toBe('add fog');
+ });
+
+ it('coerces loose numeric strings and requires accepted', () => {
+ const v = parseVisionVerdict('{"accepted": true, "score": "0.9"}');
+ expect(v.score).toBe(0.9);
+ });
+
+ it('drops an out-of-range score instead of failing the whole verdict', () => {
+ const v = parseVisionVerdict('{"accepted": true, "score": 85, "notes": "great"}');
+ expect(v.accepted).toBe(true);
+ expect(v.score).toBeUndefined();
+ expect(v.notes).toBe('great');
+ });
+
+ it('throws when there is no JSON object', () => {
+ expect(() => parseVisionVerdict('the render looks fine to me')).toThrow();
+ });
+
+ it('throws when accepted is missing', () => {
+ expect(() => parseVisionVerdict('{"score": 0.5}')).toThrow();
+ });
+});
+
+describe('resolveVisionEvalTarget', () => {
+ it('honors an explicit API-provider assignment', async () => {
+ mocks.getSettings.mockResolvedValue({ creativeDirector: { evaluation: { providerId: 'lmstudio', model: 'llava' } } });
+ mocks.getProviderById.mockResolvedValue({ id: 'lmstudio', type: 'api', enabled: true });
+ const target = await resolveVisionEvalTarget();
+ expect(target).toEqual({ provider: { id: 'lmstudio', type: 'api', enabled: true }, model: 'llava' });
+ expect(mocks.listVisionModels).not.toHaveBeenCalled();
+ });
+
+ it('falls through to auto when the pinned provider is not an API provider', async () => {
+ mocks.getSettings.mockResolvedValue({ creativeDirector: { evaluation: { providerId: 'claude' } } });
+ mocks.getProviderById.mockImplementation(async (id) => {
+ if (id === 'claude') return { id: 'claude', type: 'cli', enabled: true };
+ if (id === 'ollama') return OLLAMA;
+ return null;
+ });
+ mocks.listVisionModels.mockResolvedValue([{ providerId: 'ollama', backend: 'ollama', id: 'qwen2.5-vl', vision: true }]);
+ const target = await resolveVisionEvalTarget();
+ expect(target).toEqual({ provider: OLLAMA, model: 'qwen2.5-vl' });
+ });
+
+ it('auto-picks the first local vision model, skipping CLI-backed entries', async () => {
+ mocks.listVisionModels.mockResolvedValue([
+ { providerId: 'claude-code', backend: 'cli', id: 'claude-opus-4-8', vision: true },
+ { providerId: 'ollama', backend: 'ollama', id: 'llama3.2-vision', vision: true },
+ ]);
+ mocks.getProviderById.mockImplementation(async (id) => (id === 'ollama' ? OLLAMA : null));
+ const target = await resolveVisionEvalTarget();
+ expect(target).toEqual({ provider: OLLAMA, model: 'llama3.2-vision' });
+ });
+
+ it('returns null when no vision-capable API provider exists', async () => {
+ mocks.listVisionModels.mockResolvedValue([{ providerId: 'claude-code', backend: 'cli', id: 'opus', vision: true }]);
+ const target = await resolveVisionEvalTarget();
+ expect(target).toBeNull();
+ });
+});
+
+describe('evaluateSceneWithVision', () => {
+ const project = { id: 'p1', name: 'Demo', styleSpec: 'neon noir' };
+ const scene = { sceneId: 's1', order: 0, intent: 'hero enters', renderedJobId: 'job-1', evaluationFrames: ['job-1-f1.jpg', 'job-1-f2.jpg'], retryCount: 0 };
+
+ beforeEach(() => {
+ mocks.listVisionModels.mockResolvedValue([{ providerId: 'ollama', backend: 'ollama', id: 'qwen2.5-vl', vision: true }]);
+ mocks.getProviderById.mockImplementation(async (id) => (id === 'ollama' ? OLLAMA : null));
+ });
+
+ it('resolves a verdict from the vision model and reports the model that ran', async () => {
+ mocks.runPromptThroughProvider.mockResolvedValue({
+ text: '{"accepted": true, "score": 0.85, "notes": "on-style"}',
+ model: 'qwen2.5-vl',
+ provider: OLLAMA,
+ });
+ const res = await evaluateSceneWithVision(project, scene);
+ expect(res.ok).toBe(true);
+ expect(res.verdict.accepted).toBe(true);
+ expect(res.llm).toEqual({ provider: 'ollama', model: 'qwen2.5-vl' });
+ // Frames passed as absolute paths under the thumbnails dir.
+ const call = mocks.runPromptThroughProvider.mock.calls[0][0];
+ expect(call.screenshots).toEqual(['/data/video-thumbnails/job-1-f1.jpg', '/data/video-thumbnails/job-1-f2.jpg']);
+ expect(call.source).toBe('cd-scene-evaluate');
+ });
+
+ it('falls back to the agent when no vision provider is configured', async () => {
+ mocks.listVisionModels.mockResolvedValue([]);
+ const res = await evaluateSceneWithVision(project, scene);
+ expect(res).toMatchObject({ ok: false, fallbackToAgent: true });
+ expect(mocks.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the agent when no frames exist on disk', async () => {
+ mocks.existsSync.mockReturnValue(false);
+ const res = await evaluateSceneWithVision(project, scene);
+ expect(res).toMatchObject({ ok: false, fallbackToAgent: true });
+ expect(mocks.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('uses the single-thumbnail fallback when no sampled frames are present', async () => {
+ mocks.runPromptThroughProvider.mockResolvedValue({ text: '{"accepted": true}', model: 'qwen2.5-vl', provider: OLLAMA });
+ await evaluateSceneWithVision(project, { ...scene, evaluationFrames: [] });
+ const call = mocks.runPromptThroughProvider.mock.calls[0][0];
+ expect(call.screenshots).toEqual(['/data/video-thumbnails/job-1.jpg']);
+ });
+});
+
+describe('applySceneVerdict', () => {
+ const project = { id: 'p1', name: 'Demo', collectionId: 'col-1' };
+ const scene = { sceneId: 's1', order: 0, renderedJobId: 'job-1', retryCount: 0 };
+ const llm = { provider: 'ollama', model: 'qwen2.5-vl' };
+
+ it('accept → marks accepted, adds video to the collection, and advances', async () => {
+ await applySceneVerdict(project, scene, { accepted: true, score: 0.9, notes: 'good' }, llm);
+ expect(mocks.updateScene).toHaveBeenCalledWith('p1', 's1', expect.objectContaining({ status: 'accepted' }));
+ expect(mocks.addItem).toHaveBeenCalledWith('col-1', { kind: 'video', ref: 'job-1' });
+ expect(mocks.advanceAfterSceneSettled).toHaveBeenCalledWith('p1');
+ });
+
+ it('accept → an already-in-collection error is swallowed (idempotent)', async () => {
+ mocks.addItem.mockRejectedValue(new Error('Item already in collection: video:job-1'));
+ await expect(applySceneVerdict(project, scene, { accepted: true }, llm)).resolves.not.toThrow();
+ expect(mocks.advanceAfterSceneSettled).toHaveBeenCalledWith('p1');
+ });
+
+ it('miss with retries left → pending + refined prompt + bumped retryCount, no collection add', async () => {
+ await applySceneVerdict(project, { ...scene, retryCount: 1 }, { accepted: false, notes: 'fix', refinedPrompt: 'more fog', imageStrength: 0.6 }, llm);
+ expect(mocks.updateScene).toHaveBeenCalledWith('p1', 's1', expect.objectContaining({
+ status: 'pending',
+ retryCount: 2,
+ prompt: 'more fog',
+ imageStrength: 0.6,
+ }));
+ expect(mocks.addItem).not.toHaveBeenCalled();
+ expect(mocks.advanceAfterSceneSettled).toHaveBeenCalledWith('p1');
+ });
+
+ it('miss with retries exhausted → failed', async () => {
+ await applySceneVerdict(project, { ...scene, retryCount: 3 }, { accepted: false, notes: 'still bad' }, llm);
+ expect(mocks.updateScene).toHaveBeenCalledWith('p1', 's1', expect.objectContaining({ status: 'failed' }));
+ expect(mocks.advanceAfterSceneSettled).toHaveBeenCalledWith('p1');
+ });
+
+ it('skips the collection add when the project has no collectionId', async () => {
+ await applySceneVerdict({ id: 'p1' }, scene, { accepted: true }, llm);
+ expect(mocks.addItem).not.toHaveBeenCalled();
+ });
+});
+
+describe('dispatchSceneEvaluation', () => {
+ const project = { id: 'p1', name: 'Demo', collectionId: 'col-1' };
+ const scene = { sceneId: 's1', order: 0, renderedJobId: 'job-1', evaluationFrames: ['job-1-f1.jpg'], retryCount: 0 };
+
+ it('applies the verdict via the vision path when a provider resolves', async () => {
+ mocks.listVisionModels.mockResolvedValue([{ providerId: 'ollama', backend: 'ollama', id: 'qwen2.5-vl', vision: true }]);
+ mocks.getProviderById.mockImplementation(async (id) => (id === 'ollama' ? OLLAMA : null));
+ mocks.runPromptThroughProvider.mockResolvedValue({ text: '{"accepted": true, "score": 0.9}', model: 'qwen2.5-vl', provider: OLLAMA });
+ const res = await dispatchSceneEvaluation(project, scene);
+ expect(res.via).toBe('vision');
+ expect(mocks.updateScene).toHaveBeenCalledWith('p1', 's1', expect.objectContaining({ status: 'accepted' }));
+ expect(mocks.enqueueEvaluateTask).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the agent when the vision path is unavailable', async () => {
+ mocks.listVisionModels.mockResolvedValue([]);
+ await dispatchSceneEvaluation(project, scene);
+ expect(mocks.enqueueEvaluateTask).toHaveBeenCalledWith(project, scene);
+ expect(mocks.updateScene).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the agent when the vision call throws', async () => {
+ mocks.listVisionModels.mockResolvedValue([{ providerId: 'ollama', backend: 'ollama', id: 'qwen2.5-vl', vision: true }]);
+ mocks.getProviderById.mockImplementation(async (id) => (id === 'ollama' ? OLLAMA : null));
+ mocks.runPromptThroughProvider.mockRejectedValue(new Error('connection refused'));
+ await dispatchSceneEvaluation(project, scene);
+ expect(mocks.enqueueEvaluateTask).toHaveBeenCalledWith(project, scene);
+ });
+});
diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.js
index e4a6e9f4b4..55e0ceb446 100644
--- a/server/services/creativeDirector/sceneRunner.js
+++ b/server/services/creativeDirector/sceneRunner.js
@@ -32,13 +32,15 @@ import { join } from 'path';
import { PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';
import { verifyVideoPlayable } from '../../lib/ffmpeg.js';
import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';
+import { CD_MAX_SCENE_RETRIES } from '../../lib/creativeDirectorPrompts.js';
import { extractLastFrame, sampleEvaluationFrames } from '../videoGen/local.js';
import { enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { updateScene, updateProject, getProject } from './local.js';
-import { enqueueEvaluateTask } from './agentBridge.js';
+import { dispatchSceneEvaluation } from './sceneEvaluator.js';
-const MAX_SCENE_RETRIES = 3;
+// Max render+eval attempts per scene (shared with the evaluator so render-retry
+// and eval-retry caps can't silently diverge — both bump the same scene.retryCount).
// Default image strength when an i2v continuation scene has no explicit
// per-scene `imageStrength`. Anchors the next clip to the prior last-frame
@@ -59,7 +61,7 @@ export function resolveImageStrength({ explicit, isContinuation }) {
* the evaluate task or schedule a retry.
*/
export async function runSceneRender(project, scene) {
- console.log(`🎞️ CD scene render starting: ${project.id} / ${scene.sceneId} (order ${scene.order}, attempt ${(scene.retryCount || 0) + 1}/${MAX_SCENE_RETRIES + 1})`);
+ console.log(`🎞️ CD scene render starting: ${project.id} / ${scene.sceneId} (order ${scene.order}, attempt ${(scene.retryCount || 0) + 1}/${CD_MAX_SCENE_RETRIES + 1})`);
await updateScene(project.id, scene.sceneId, {
status: 'rendering',
@@ -70,7 +72,7 @@ export async function runSceneRender(project, scene) {
const pythonPath = settings.imageGen?.local?.pythonPath || null;
// Fail fast when local video gen isn't configured. Without this guard the
// job would be enqueued, fail inside `generateVideo`, retry up to
- // MAX_SCENE_RETRIES, and pollute the persisted queue with N doomed entries
+ // CD_MAX_SCENE_RETRIES, and pollute the persisted queue with N doomed entries
// — none of which can ever succeed without operator intervention. Mark
// the scene failed and let advanceAfterSceneSettled flag the project so
// the user can configure pythonPath and Resume from the UI.
@@ -211,7 +213,7 @@ export async function runSceneRender(project, scene) {
cleanup();
// Treat user-initiated cancel as a terminal stop for this scene — do
// NOT route through handleRenderFailed (which would retry up to
- // MAX_SCENE_RETRIES); the user explicitly stopped this. Mark the scene
+ // CD_MAX_SCENE_RETRIES); the user explicitly stopped this. Mark the scene
// failed and let the completionHook flag the project so the user can
// resume from the UI.
await handleRenderCanceled(project.id, scene.sceneId);
@@ -246,7 +248,7 @@ async function handleRenderCompleted(projectId, sceneId, jobId, opts = {}) {
// regression this fixture is supposed to catch.
//
// Bypass handleRenderFailed: that function retries up to
- // MAX_SCENE_RETRIES, and a broken last-frame extraction will fail the
+ // CD_MAX_SCENE_RETRIES, and a broken last-frame extraction will fail the
// same way every retry — burning three more full renders before
// surfacing the regression. Mark terminal directly and let the
// completion hook decide what to do next.
@@ -362,7 +364,10 @@ async function handleRenderCompleted(projectId, sceneId, jobId, opts = {}) {
console.log(`⏸️ CD project ${projectId} is ${postUpdate.status} — paused during updateScene; renderedJobId persisted on scene ${sceneId}, deferring evaluator to resume.`);
return;
}
- await enqueueEvaluateTask(fresh, { ...scene, renderedJobId: jobId, status: 'evaluating', evaluationFrames });
+ // Settle the render: evaluate on a local vision model server-side when one is
+ // configured, otherwise fall back to the Opus CoS agent. dispatchSceneEvaluation
+ // never throws (runs outside the request lifecycle).
+ await dispatchSceneEvaluation(fresh, { ...scene, renderedJobId: jobId, status: 'evaluating', evaluationFrames });
}
async function handleRenderCanceled(projectId, sceneId) {
@@ -385,8 +390,8 @@ async function handleRenderFailed(projectId, sceneId, errorMsg) {
const scene = fresh.treatment?.scenes?.find((s) => s.sceneId === sceneId);
if (!scene) return;
const nextRetry = (scene.retryCount || 0) + 1;
- if (nextRetry <= MAX_SCENE_RETRIES) {
- console.log(`🔁 CD scene ${sceneId} render failed (${errorMsg}) — retry ${nextRetry}/${MAX_SCENE_RETRIES}`);
+ if (nextRetry <= CD_MAX_SCENE_RETRIES) {
+ console.log(`🔁 CD scene ${sceneId} render failed (${errorMsg}) — retry ${nextRetry}/${CD_MAX_SCENE_RETRIES}`);
await updateScene(projectId, sceneId, { status: 'pending', retryCount: nextRetry });
const updated = { ...scene, retryCount: nextRetry };
await runSceneRender(fresh, updated);