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

feat(media): Refine Prompt modal + parallel Codex render lane (#217)

[._.]/ Adam Eivyf51f8e89c20c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7cb1d5d6c9..d06dae0204 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,16 +2,11 @@
## Added
+- **Refine Prompt action in the Media Lightbox.** Open any past image or video render and click *Refine Prompt* to describe what you'd like to change in plain English ("more painterly", "switch to watercolor", "drop the cyberpunk neon"). PortOS hands the original prompt + your feedback to any enabled AI provider — API (OpenAI, Anthropic, LM Studio) or CLI (Codex, Claude Code, Gemini CLI) — and shows the rewritten positive and negative prompts as editable text plus a one-line rationale. Tweak the new prompt if you want, then *Queue Render* to make a new render that inherits the original's model, resolution, LoRAs, seed, and other settings.
- **Pipeline — Arc canvas UI.** PipelineSeries's right-side canvas is now a structural Arc → Season → Episode tree. Top of the canvas shows the series arc card (logline, themes, collapsible summary + protagonist arc, edit-in-place fields). One-click `Generate arc` runs the Phase 3 LLM pass and persists `series.arc` + `series.seasons[]`; `Verify arc` surfaces continuity findings inline with severity badges. Each season expands/collapses, shows `N / target episodes` count, and exposes inline edit (number / title / logline / synopsis / ending hook / status / episode-count target). Episodes render as compact rows with delete, hover-revealed season picker (move between seasons), and direct deep-link into the issue editor. `Generate episodes (LLM)` on an empty season runs the per-season-episodes pass and creates one issue per beat with `seasonId` + `arcPosition` pre-filled; un-grouped issues stay visible in a dedicated bottom panel. Replaces the flat issue-card grid from Phase 1; backed by the schema + endpoints from Phases 2 + 3. Two-click-arm replace guard on arc regeneration and per-season delete. Phase 4 of the Story Arc Planning initiative.
- **Pipeline — LLM-driven series-arc planning.** Three new staged-LLM passes that plan and verify a multi-season series: (1) `POST /api/pipeline/series/:id/arc/generate` proposes the top-level arc — series-level logline, summary, themes, protagonist arc — plus a 2–5 season breakdown with per-season loglines, ending hooks, and episode-count targets, default `model: 'heavy'`. (2) `POST /api/pipeline/series/:id/seasons/:seasonId/episodes/generate` proposes the episode-by-episode breakdown for one season, taking the whole-arc protagonist trajectory and prior seasons' synopses as continuity context. (3) `POST /api/pipeline/series/:id/arc/verify` runs a cross-season continuity pass that surfaces character contradictions, dropped subplots, episode-count/arc-weight mismatch, unresolved finale hooks, arc-role imbalance, and theme drift as actionable `{ severity, location, problem, suggestion }` issues. All three calls accept `{ providerOverride, modelOverride }` and routes 1 + 2 also accept `commit: true` to persist the proposal in one shot (default returns a preview the UI can confirm before writing). Backed by `server/services/pipeline/arcPlanner.js` (~280 LOC) on top of the shared `stageRunner.js` + new stage prompts in `data.sample/prompts/stages/pipeline-arc-{overview,verify}.md` + `pipeline-season-episodes.md`, all three reusing the `_partials/bible-deference.md` block for character/setting consistency. Phase 3 of the Story Arc Planning initiative — no UI yet (Phase 4 builds the arc canvas on top of these endpoints).
- **Pipeline — series-arc + season schema.** Series records gain two new optional fields: `series.arc` (logline, summary, themes, protagonistArc, status) for the overall multi-season story spine, and `series.seasons[]` for the ordered season/volume list. Issues gain optional `seasonId` + `arcPosition` pointers so an issue can be slotted into a specific season at a specific ordinal. Backed by a new `server/lib/storyArc.js` (canonical shapes + sanitizers, sibling to `storyBible.js`) and a new `server/services/pipeline/seasons.js` service that handles delete-with-reassign so removing a season cleanly re-points or un-groups child issues. Routes: `GET / POST /series/:id/seasons`, `PATCH / DELETE /series/:id/seasons/:seasonId`. Pure additive — existing series files round-trip unchanged. Phase 2 of the Story Arc Planning initiative; no UI yet (Phase 4 builds the arc canvas on top of this).
-## Changed
-
-- **Pipeline Series page — two-pane layout.** PipelineSeries (`/pipeline/series/:id`) drops its `max-w-5xl` cap and splits into a sticky left bible sidebar + right card-grid canvas at `lg+`. The bible inputs (name / format / logline / target issue count / premise / style notes / world / characters) live in the sidebar; issues/episodes render as a responsive card grid (1/2/3/4 cols across breakpoints) showing number, status badge, title (line-clamped), and `updated <timeAgo>`. Sidebar collapses to a 48px rail via a panel toggle (state persists in `localStorage` under `portos-pipeline-series-sidebar-collapsed`) so the canvas can use the full viewport when you're deep in episode work. Mobile (< lg) stays single-column with the sidebar reflowing above the canvas. Phase 1 of the Pipeline Story-Arc Planning initiative — pure UI refactor, no schema or API change; subsequent phases evolve the card grid into an Arc → Season → Episode tree.
-
-## Added
-
- **Prompt template partials** — PortOS prompts now support Mustache-style `{{> partial-name }}` includes. Files in `data/prompts/_partials/` get inlined into stage templates at render time (recursive, with cycle detection + loud missing-partial errors). First two partials cover the duplicated bible-deference preamble and the scenes-JSON output contract that were copy-pasted across `writers-room-script.md` and `pipeline-extract-scenes.md`. Both prompts now reference the shared partials — future tweaks to "defer to canonical character names" or "this is the scenes[] JSON shape" land in one place. Step 7 of the Writers Room ↔ Pipeline DRY unification.
- **Writers Room ↔ Pipeline bridge.** A "Promote to pipeline" action on a Writers Room work creates a Pipeline series + first issue in one call, carrying over the active draft prose, all three bibles (characters/settings/objects), and the latest script-analysis scenes as fully-populated storyboards. The two systems record each other's ids so the menu flips to "Open in pipeline" on subsequent visits, and the Pipeline series page surfaces a "Writers Room" badge linking back. Idempotent — re-promoting a linked work returns the existing pair instead of duplicating. Backed by `server/services/writersRoom/promoteToPipeline.js` and `POST /api/writers-room/works/:id/promote-to-pipeline`. Step 6 of the Writers Room ↔ Pipeline DRY unification.
- **Pipeline page** under Create — a series-production workflow that chains a rough idea seed through prose → comic-book script + TV teleplay (parallel) → comic pages + storyboards (image gen) → episode video. Each Series carries a shared bible (logline, premise, characters, optional World Builder ref, style notes) that every issue/episode inherits into its stage prompts so identity stays consistent across the run. The "Auto-run text" button kicks off the LLM chain end-to-end with SSE progress; the visual stages (comic pages, storyboards) hand off to the existing image-gen queue.
@@ -23,6 +18,9 @@
## Changed
+- **MediaCard thumbnails.** Removed the "IMAGE"/"VIDEO" badge overlay from the bottom-right of media cards — the icon and aspect already convey the kind, and the badge added visual noise on grid views.
+- **Pipeline Series page — two-pane layout.** PipelineSeries (`/pipeline/series/:id`) drops its `max-w-5xl` cap and splits into a sticky left bible sidebar + right card-grid canvas at `lg+`. The bible inputs (name / format / logline / target issue count / premise / style notes / world / characters) live in the sidebar; issues/episodes render as a responsive card grid (1/2/3/4 cols across breakpoints) showing number, status badge, title (line-clamped), and `updated <timeAgo>`. Sidebar collapses to a 48px rail via a panel toggle (state persists in `localStorage` under `portos-pipeline-series-sidebar-collapsed`) so the canvas can use the full viewport when you're deep in episode work. Mobile (< lg) stays single-column with the sidebar reflowing above the canvas. Phase 1 of the Pipeline Story-Arc Planning initiative — pure UI refactor, no schema or API change; subsequent phases evolve the card grid into an Arc → Season → Episode tree.
+
- LTX-2.3 video model dropdown now groups the legacy notapalindrome runtimes (`ltx2_unified`, `ltx23_unified`, `ltx23_distilled_q4`) under a `Legacy` `<optgroup>`, with the dgrauet `ltx23_dgrauet_*` runtimes surfaced as the active picks at the top of the list. `defaultMacos` deliberately stays on `ltx23_distilled_q4` because the dgrauet runtime requires an opt-in venv install — fresh installs need a model that works out of the box. Applies to both Video Gen and Creative Director dropdowns. New Video Gen FFLF mode also gets a one-line keyframe-pair guidance hint ("use keyframes that share scene geometry — same camera, same subject; unrelated images produce a visual cut") to prevent the "looks like two stills" complaint.
- Writers Room bible CRUD (characters / settings / objects, one file per work) now collapses onto a single `createBibleStore(...)` factory in `server/lib/storyBible.js` — each domain file shrinks to ~30 LOC of factory configuration. -281 LOC across the three domain files. Pipeline bible routes share the writers-room zod schemas under generic names (`characterBibleCreateSchema`, etc.) instead of the prior `z.record(z.string(), z.any())` loose-record validation; the canonical `sanitizeBibleList` in `storyBible.js` remains the single source-of-truth for shape enforcement on both sides. Steps 2a + 2b of the Writers Room ↔ Pipeline DRY unification.
- Pipeline stage components (`ProseStage`, `TextStagePanel`, `EpisodeVideoStage`) now share a `useAsyncAction(fn)` hook for the common "setLoading(true) → await → catch+toast → setLoading(false)" pattern. `StoryboardsStage` deliberately stays on its existing pattern because its `savingIdx`/`extractingFrom` flags are keyed loading states, not booleans. Step 4c of the Writers Room ↔ Pipeline DRY unification.
@@ -43,3 +41,4 @@
- Pipeline EpisodeVideoStage final-video render no longer breaks when the underlying mp4 is missing — both surfaces (Creative Director SegmentsTab + Pipeline EpisodeVideoStage) now route through a shared `ScenePreview` component with the onError-missing-media fallback + Retry + cache-bust pattern.
- Render Queue UI now lists jobs in execution order (running first, then queue position ascending) instead of mixing a long-running job into the middle of newer queued batches. The route was sorting all jobs by `startedAt || queuedAt` DESC, which slotted an active job below a fresher batch.
- CoS agent dedup race in `spawnAgentForTask` — under sustained scheduler tick load, two parallel `task:ready` emissions for the same task id could both pass the dedup-has-check because `spawningTasks.delete(task.id)` ran BEFORE the agent was queued to the runner. A second spawn would slip through the window and produce a duplicate agent. The delete now lives inside a `try { spawnViaRunner|spawnDirectly } finally { spawningTasks.delete }` block so the guard outlives the spawn call. New behavioral race-repro test in `agentLifecycle.test.js` proves the contract.
+
diff --git a/PLAN.md b/PLAN.md
index 6e655effb3..1da034c317 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -63,6 +63,14 @@ These were flagged by the post-merge code review pass on the Z-Image + Civitai L
- [ ] **Project-wide `<Modal>` component** — every modal in the app (`Flux2InstallModal`, `EditAppModal`, `MemoryEditModal`, `ResumeAgentModal`, `MediaLightbox`, `LayoutEditor`, `KeyboardHelp`, `RapidReader`, `DeployPanel`'s confirm, the new `CivitaiAuthModal` in `Loras.jsx`) rolls its own `fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4` backdrop + click-outside + close-button + ESC handler. Extract `client/src/components/ui/Modal.jsx` with backdrop + dialog props and a slot for the body, then convert all call sites. ~300 LOC of duplicated chrome across the codebase.
- [ ] **`assertSafeFilename(filename, { extensions })` in `fileUtils.js`** — `server/services/loras.js#assertSafeLoraFilename` (`.safetensors` whitelist) and `server/services/imageGen/local.js#assertGalleryFilename` (`.png` whitelist) are the same validation pattern with different extensions. One small helper in `fileUtils.js` consolidates both call sites.
+- [ ] **Extract shared `runPromptThroughProvider` runner-wrapper** — four near-identical "create run → branch on provider.type → executeCliRun/executeApiRun → accumulate text → reject on error" implementations now exist: `server/services/mediaPromptRefiner.js#runRefinePrompt`, `server/services/messageEvaluator.js#runPrompt`, `server/lib/stageRunner.js#awaitRunnerCall`, `server/services/worldBuilderExpand.js#callLLM`. Promote into `server/lib/promptRunner.js` returning `{ text, runId }`, then collapse the four sites. Failure-handling drift is already visible (some reject on `success === false`, some only on `error`) — the unified version should pick the stricter discriminator. Surfaced from the Refine Prompt /simplify pass.
+
+- [ ] **Promote `findBalancedBlocks` + `tryParseWithRepair` to `server/lib/jsonExtract.js`** — `server/services/worldBuilderExpand.js:132-235` (with trailing-comma + Codex `}}]` repair + `[...]` placeholder cleanup), `server/services/mediaPromptRefiner.js#extractRefinementJson` (string-aware brace walker), and `server/lib/stageRunner.js#extractJson` (greedy regex) all solve the same "extract JSON from CLI-banner-prefixed LLM output" problem. The richest implementation is in worldBuilderExpand; lift it out and have all three callers import it (with caller-specific shape predicates). Surfaced from the Refine Prompt /simplify pass.
+
+- [ ] **Extend `normalize.js` to expose render-config fields** — `client/src/components/media/PromptRefineModal.jsx#getRenderConfig` reaches into `item.raw?.{cfgScale,loraFilenames,loraScales,steps (video),guidanceScale,seed,tiling,disableAudio}` because `normalizeImage`/`normalizeVideo` don't surface those fields. Either lift the snake_case/camelCase fallback chain into normalize.js so the modal reads from `item.*` only, or add `getRenderConfigForItem(item)` co-located with normalize so the sidecar field-naming knowledge lives in one file. Surfaced from the Refine Prompt /simplify pass.
+
+- [ ] **Extend `runner.js#buildCliArgs` to honor `defaultModel` for all CLI providers** — today only `codex` translates `provider.defaultModel` into a `--model` flag; `claude-code` and `gemini-cli` ignore it entirely, so the stageRunner / messageEvaluator / mediaPromptRefiner pattern of cloning the provider with an overridden `defaultModel` is silently a no-op for non-Codex CLIs. The user picks a model in the UI and the request runs against whatever model is baked into `provider.args` instead. Fix: append `--model <model>` to claude-code (after `-p -` is fine; claude-code parses flags positionally) and `-m <model>` to gemini-cli, gated on `!provider.args.includes('--model')` so existing user configs with model baked in don't get a duplicate flag. Test: each CLI's `--help` to confirm flag conventions, then verify Refine Prompt picks the modal-selected model for all three. Surfaced from Copilot review on PR #217.
+
### Better Audit follow-ups
- [ ] **[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test-specific hack in prod boot path).
diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsx
index 32bdd696d4..f742ee1a20 100644
--- a/client/src/components/media/MediaCard.jsx
+++ b/client/src/components/media/MediaCard.jsx
@@ -42,9 +42,6 @@ export default function MediaCard({
{isVideo ? <Film className="w-10 h-10" /> : <ImageIcon className="w-10 h-10" />}
</div>
)}
- <span className="absolute bottom-1 right-1 text-[9px] px-1.5 py-0.5 bg-black/70 text-white rounded uppercase tracking-wide">
- {isVideo ? 'Video' : 'Image'}
- </span>
{selectionLabel != null && (
<div className="absolute top-1.5 left-1.5 w-5 h-5 rounded-full bg-port-accent text-white text-[10px] font-bold flex items-center justify-center">
{selectionLabel}
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index c2dda40a2f..bf49a11522 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -4,6 +4,7 @@ import {
ChevronLeft, ChevronRight, Maximize2, Minimize2,
} from 'lucide-react';
import toast from '../ui/Toast';
+import PromptRefineModal from './PromptRefineModal';
// Mirror of CLEAN_LEVELS in server/routes/imageClean.js. If the server adds a
// new level, drop a label here and the pill renders automatically.
@@ -31,6 +32,7 @@ export default function MediaLightbox({
const [cleaning, setCleaning] = useState(null);
const [fullScreen, setFullScreen] = useState(false);
const [drawerOpen, setDrawerOpen] = useState(false);
+ const [refineOpen, setRefineOpen] = useState(false);
const touchStart = useRef({ x: null, y: null });
// Read callbacks from refs so the keydown listener doesn't re-subscribe on
// every parent render (callers pass inline arrows; the lightbox parent re-
@@ -42,6 +44,7 @@ export default function MediaLightbox({
const onKey = (e) => {
const cb = callbacksRef.current;
if (e.key === 'Escape') {
+ if (refineOpen) { setRefineOpen(false); return; }
if (fullScreen && drawerOpen) { setDrawerOpen(false); return; }
if (fullScreen) { setFullScreen(false); return; }
cb.onClose();
@@ -64,11 +67,11 @@ export default function MediaLightbox({
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
- }, [item, hasPrevious, hasNext, fullScreen, drawerOpen]);
+ }, [item, hasPrevious, hasNext, fullScreen, drawerOpen, refineOpen]);
// Reset drawer when item changes (swipe forwards w/ settings open shouldn't
// carry the open state to the next image — feels jumpy).
- useEffect(() => { setDrawerOpen(false); }, [item?.key]);
+ useEffect(() => { setDrawerOpen(false); setRefineOpen(false); }, [item?.key]);
if (!item) return null;
const isVideo = item.kind === 'video';
@@ -209,9 +212,11 @@ export default function MediaLightbox({
cleaning={cleaning}
setCleaning={setCleaning}
copy={copy}
+ onRefine={() => setRefineOpen(true)}
/>
)}
</div>
+ <PromptRefineModal item={item} open={refineOpen} onClose={() => setRefineOpen(false)} />
</div>
);
}
@@ -219,7 +224,7 @@ export default function MediaLightbox({
function SettingsPane({
item, meta, isVideo, fullScreen,
onClose, onPrimaryClose, onRemix, onSendToVideo, onContinue, onClean,
- cleaning, setCleaning, copy,
+ cleaning, setCleaning, copy, onRefine,
}) {
const asideClasses = fullScreen
? 'absolute top-0 right-0 bottom-0 w-full sm:w-96 z-20 bg-port-card border-l border-port-border flex flex-col shadow-2xl'
@@ -301,6 +306,15 @@ function SettingsPane({
</div>
<footer className="flex flex-wrap gap-1.5 p-3 border-t border-port-border">
+ {onRefine && item.prompt && item.prompt !== '(no prompt)' && (
+ <button
+ type="button"
+ onClick={onRefine}
+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-accent/80 text-white hover:opacity-90 rounded"
+ >
+ <Sparkles className="w-3.5 h-3.5" /> Refine Prompt
+ </button>
+ )}
{!isVideo && onRemix && (
<button
type="button"
diff --git a/client/src/components/media/PromptRefineModal.jsx b/client/src/components/media/PromptRefineModal.jsx
new file mode 100644
index 0000000000..398c5ca862
--- /dev/null
+++ b/client/src/components/media/PromptRefineModal.jsx
@@ -0,0 +1,269 @@
+import { useEffect, useState } from 'react';
+import { ListPlus, Sparkles, Wand2, X } from 'lucide-react';
+import ProviderModelSelector from '../ProviderModelSelector';
+import toast from '../ui/Toast';
+import useProviderModels from '../../hooks/useProviderModels';
+import { generateImage, generateVideo, refineMediaPrompt } from '../../services/api';
+
+function getRenderConfig(item) {
+ const raw = item?.raw || {};
+ if (item?.kind === 'image') {
+ return {
+ mode: item.mode || 'local',
+ modelId: item.modelId,
+ width: item.width,
+ height: item.height,
+ steps: item.steps,
+ guidance: item.guidance,
+ cfgScale: raw.cfgScale ?? raw.cfg_scale,
+ seed: item.seed,
+ quantize: item.quantize,
+ loraFilenames: raw.loraFilenames,
+ loraScales: raw.loraScales,
+ };
+ }
+ return {
+ mode: item.mode || 'text',
+ modelId: item.modelId,
+ width: item.width,
+ height: item.height,
+ numFrames: item.numFrames,
+ fps: item.fps,
+ steps: raw.steps,
+ // Nullish coalescing — a deliberate `0` guidanceScale is valid for some
+ // video models and must survive the round-trip back into the queued payload.
+ guidanceScale: raw.guidanceScale ?? raw.guidance,
+ seed: raw.seed,
+ tiling: raw.tiling,
+ disableAudio: raw.disableAudio,
+ };
+}
+
+// Refine→queue forces text-to-video; the source image/last-frame from the
+// original render isn't carried into the modal, so image-to-video can't be
+// reproduced from here without re-uploading.
+function queuePayload(item, refinement) {
+ const base = {
+ ...getRenderConfig(item),
+ prompt: refinement.prompt,
+ negativePrompt: refinement.negativePrompt || undefined,
+ ...(item.kind === 'video' ? { mode: 'text' } : {}),
+ };
+ return Object.fromEntries(Object.entries(base).filter(([, v]) => v != null && v !== ''));
+}
+
+export default function PromptRefineModal({ item, open, onClose }) {
+ const {
+ providers,
+ selectedProviderId,
+ selectedModel,
+ availableModels,
+ setSelectedProviderId,
+ setSelectedModel,
+ loading: providersLoading,
+ } = useProviderModels();
+ const [feedback, setFeedback] = useState('');
+ const [refinedPrompt, setRefinedPrompt] = useState('');
+ const [refinedNegative, setRefinedNegative] = useState('');
+ const [rationale, setRationale] = useState('');
+ const [refining, setRefining] = useState(false);
+ const [queueing, setQueueing] = useState(false);
+
+ useEffect(() => {
+ setFeedback('');
+ setRefinedPrompt('');
+ setRefinedNegative('');
+ setRationale('');
+ }, [open, item?.key]);
+
+ const hasResult = refinedPrompt !== '' || rationale !== '';
+
+ if (!open || !item) return null;
+
+ const originalPrompt = item.prompt || '';
+ const originalNegative = item.negativePrompt || '';
+ const canRefine = feedback.trim() && selectedProviderId && !refining;
+ const canQueue = hasResult && refinedPrompt.trim() && !queueing;
+
+ // refineMediaPrompt + generateImage go through services/apiCore#request(),
+ // which already toasts on non-2xx responses. Don't toast again from the
+ // modal's catch on those paths — that'd produce duplicate notifications.
+ // generateVideo uses raw fetch (multipart, see apiImageVideo.js) and does
+ // NOT auto-toast, so the video catch still needs its own toast.
+ const runRefine = async () => {
+ if (!canRefine) return;
+ setRefining(true);
+ setRefinedPrompt('');
+ setRefinedNegative('');
+ setRationale('');
+ try {
+ const result = await refineMediaPrompt({
+ kind: item.kind,
+ prompt: originalPrompt,
+ negativePrompt: originalNegative,
+ feedback: feedback.trim(),
+ providerId: selectedProviderId,
+ model: selectedModel || undefined,
+ renderConfig: getRenderConfig(item),
+ });
+ setRefinedPrompt(result.prompt || '');
+ setRefinedNegative(result.negativePrompt || '');
+ setRationale(result.rationale || '');
+ } catch {
+ // request() already toasted the server's error message.
+ } finally {
+ setRefining(false);
+ }
+ };
+
+ const queueRender = async () => {
+ if (!canQueue) return;
+ setQueueing(true);
+ try {
+ const payload = queuePayload(item, { prompt: refinedPrompt.trim(), negativePrompt: refinedNegative.trim() });
+ const result = item.kind === 'image'
+ ? await generateImage(payload)
+ : await generateVideo(payload);
+ // external image-gen mode returns synchronously with the filename and
+ // no queue position — the render already completed by the time this
+ // resolves. Local / codex / video return a queued jobId+position.
+ const isAlreadyDone = item.kind === 'image' && result?.mode === 'external';
+ const message = isAlreadyDone
+ ? 'Render complete'
+ : result.position ? `Queued #${result.position}` : 'Render queued';
+ toast.success(message);
+ onClose();
+ } catch (err) {
+ // generateImage routes through request() which already toasts; only
+ // surface a toast for the raw-fetch video path.
+ if (item.kind === 'video') toast.error(err.message || 'Failed to queue render');
+ } finally {
+ setQueueing(false);
+ }
+ };
+
+ return (
+ <div
+ className="fixed inset-0 z-[70] bg-black/80 flex items-center justify-center p-4"
+ // Stop the click before the underlying MediaLightbox backdrop sees it —
+ // both layers wire onClick={onClose} on the backdrop, and without
+ // stopPropagation a single backdrop click would dismiss the refine modal
+ // AND close the lightbox underneath it.
+ onClick={(e) => { e.stopPropagation(); onClose(); }}
+ role="presentation"
+ >
+ <section
+ className="w-full max-w-3xl max-h-[90vh] overflow-hidden bg-port-card border border-port-border rounded-xl shadow-2xl flex flex-col"
+ onClick={(e) => e.stopPropagation()}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="prompt-refine-title"
+ >
+ <header className="flex items-center justify-between gap-3 px-4 py-3 border-b border-port-border">
+ <div className="flex items-center gap-2 min-w-0">
+ <Sparkles className="w-4 h-4 text-port-accent shrink-0" />
+ <h2 id="prompt-refine-title" className="text-sm font-semibold text-white">Refine Prompt</h2>
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"
+ aria-label="Close"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </header>
+
+ <div className="flex-1 overflow-y-auto p-4 space-y-4">
+ <div>
+ <label htmlFor="prompt-refine-feedback" className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">
+ Feedback
+ </label>
+ <textarea
+ id="prompt-refine-feedback"
+ value={feedback}
+ onChange={(e) => setFeedback(e.target.value)}
+ placeholder="What should change about this render?"
+ rows={4}
+ className="w-full bg-port-bg border border-port-border rounded-lg p-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y"
+ />
+ </div>
+
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={selectedProviderId}
+ selectedModel={selectedModel}
+ availableModels={availableModels}
+ onProviderChange={setSelectedProviderId}
+ onModelChange={setSelectedModel}
+ label="LLM Provider"
+ disabled={providersLoading || refining}
+ />
+
+ {providers.length === 0 && !providersLoading && (
+ <p className="text-xs text-port-warning">No enabled providers are configured.</p>
+ )}
+
+ <button
+ type="button"
+ onClick={runRefine}
+ disabled={!canRefine}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90"
+ >
+ <Wand2 className="w-4 h-4" />
+ {refining ? 'Refining...' : (hasResult ? 'Refine Prompt again' : 'Refine Prompt')}
+ </button>
+
+ {hasResult && (
+ <div className="space-y-4">
+ {rationale && (
+ <p className="text-sm text-gray-300 bg-port-bg border border-port-border rounded-lg p-3">
+ {rationale}
+ </p>
+ )}
+
+ <div>
+ <label className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">New prompt</label>
+ <textarea
+ value={refinedPrompt}
+ onChange={(e) => setRefinedPrompt(e.target.value)}
+ rows={6}
+ className="w-full bg-port-bg border border-port-border rounded-lg p-3 text-sm text-white focus:outline-none focus:border-port-accent resize-y"
+ />
+ </div>
+
+ <div>
+ <label className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">New negative prompt</label>
+ <textarea
+ value={refinedNegative}
+ onChange={(e) => setRefinedNegative(e.target.value)}
+ rows={3}
+ className="w-full bg-port-bg border border-port-border rounded-lg p-3 text-sm text-white focus:outline-none focus:border-port-accent resize-y"
+ />
+ </div>
+ </div>
+ )}
+ </div>
+
+ <footer className="flex items-center justify-end gap-2 px-4 py-3 border-t border-port-border">
+ <button
+ type="button"
+ onClick={onClose}
+ className="px-3 py-2 rounded-lg text-sm text-gray-300 hover:text-white hover:bg-port-border/50"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={queueRender}
+ disabled={!canQueue}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-success text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90"
+ >
+ <ListPlus className="w-4 h-4" />
+ {queueing ? 'Queueing...' : 'Queue Render'}
+ </button>
+ </footer>
+ </section>
+ </div>
+ );
+}
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index ef79bb7051..f27cad7744 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -73,11 +73,13 @@ export function normalizeVideo(v) {
previewUrl: v.thumbnail ? `/data/video-thumbnails/${v.thumbnail}` : null,
downloadUrl: `/data/videos/${v.filename}`,
prompt: v.prompt || '(no prompt)',
+ negativePrompt: v.negativePrompt || v.negative_prompt || null,
modelId: v.modelId,
width: v.width,
height: v.height,
numFrames: v.numFrames,
fps: v.fps,
+ mode: v.mode,
stitchedFrom: v.stitchedFrom,
upscaledFrom: v.upscaledFrom,
loraNames,
diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.js
index 422f5e077e..2e5142e9d7 100644
--- a/client/src/services/apiMediaJobs.js
+++ b/client/src/services/apiMediaJobs.js
@@ -34,3 +34,8 @@ export const runMediaJobNow = (id) => request(`/media-jobs/${encodeURIComponent(
// Returns { canceled: <count> }. Running jobs need per-id cancelMediaJob.
export const cancelQueuedMediaJobs = ({ kind } = {}) =>
request(`/media-jobs/cancel-queued${kind ? `?kind=${encodeURIComponent(kind)}` : ''}`, { method: 'POST' });
+
+export const refineMediaPrompt = (data) => request('/media-jobs/refine-prompt', {
+ method: 'POST',
+ body: JSON.stringify(data),
+});
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index d3ef2ecaf3..47ef4d98da 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -10,6 +10,7 @@ import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { listJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
+import { refineMediaPrompt } from '../services/mediaPromptRefiner.js';
const router = Router();
@@ -19,6 +20,47 @@ const listQuerySchema = z.object({
owner: z.string().max(256).optional(),
});
+// renderConfig is inlined into the LLM prompt via JSON.stringify, so an
+// unbounded object would inflate token cost / latency. Cap the serialized
+// payload at 4 KB — that's well above any legitimate render-config (which
+// is typically <500 bytes) but stops a malicious or buggy caller from
+// shipping arbitrarily nested objects through the refiner.
+const RENDER_CONFIG_MAX_BYTES = 4096;
+const refinePromptSchema = z.object({
+ kind: z.enum(JOB_KINDS),
+ // Trim before length check — without trim, " " would slip past min(1)
+ // and arrive at the refiner where it'd be cleaned to an empty string, then
+ // surface as a confusing "LLM returned an empty prompt" error.
+ prompt: z.string().trim().min(1).max(8000),
+ negativePrompt: z.string().trim().max(8000).optional(),
+ feedback: z.string().trim().min(1).max(3000),
+ providerId: z.string().trim().min(1).max(128),
+ // Empty/whitespace model → undefined so the refiner's defaultModel /
+ // models[0] fallback chain kicks in, instead of a whitespace string
+ // bypassing the MODEL_REQUIRED guard and reaching the provider.
+ model: z.string().max(256).optional().transform((s) => {
+ const v = (s ?? '').trim();
+ return v.length > 0 ? v : undefined;
+ }),
+ renderConfig: z.record(z.any())
+ .refine((obj) => {
+ // JSON.stringify throws on BigInt / circular refs. z.record(z.any())
+ // doesn't reject those at parse time, so wrap the size check so a
+ // bad payload surfaces as VALIDATION_ERROR (400), not a 500.
+ // Measure with the same pretty-printed format the refiner inlines
+ // into the LLM prompt (`JSON.stringify(obj, null, 2)`); minified
+ // measurement would under-count, letting an indented blob slip past
+ // the cap and still inflate the prompt.
+ let size;
+ try { size = Buffer.byteLength(JSON.stringify(obj, null, 2), 'utf8'); }
+ catch { return false; }
+ return size <= RENDER_CONFIG_MAX_BYTES;
+ }, {
+ message: `renderConfig must be JSON-serializable and ≤ ${RENDER_CONFIG_MAX_BYTES} bytes`,
+ })
+ .optional(),
+});
+
// Sanitize a job before serialization. The internal job record carries
// worker-only data (the python interpreter path, absolute filesystem paths
// to multipart uploads / source images) that the UI doesn't need and that
@@ -74,6 +116,11 @@ router.get('/', asyncHandler(async (req, res) => {
res.json([...live, ...terminal].map(sanitizeJob));
}));
+router.post('/refine-prompt', asyncHandler(async (req, res) => {
+ const data = validateRequest(refinePromptSchema, req.body);
+ res.json(await refineMediaPrompt(data));
+}));
+
router.get('/:id', asyncHandler(async (req, res) => {
const job = getJob(req.params.id);
if (!job) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/services/mediaPromptRefiner.js b/server/services/mediaPromptRefiner.js
new file mode 100644
index 0000000000..d86fd592ce
--- /dev/null
+++ b/server/services/mediaPromptRefiner.js
@@ -0,0 +1,233 @@
+import { ServerError } from '../lib/errorHandler.js';
+import { getProviderById } from './providers.js';
+import { createRun, executeApiRun, executeCliRun } from './runner.js';
+
+const MAX_PROMPT_LEN = 8000;
+const MAX_REASON_LEN = 1200;
+const MAX_CHANGES = 8;
+
+const trimString = (value, max = MAX_PROMPT_LEN) =>
+ typeof value === 'string' ? value.trim().slice(0, max) : '';
+
+const cleanChanges = (changes) => (
+ Array.isArray(changes)
+ ? changes.map((c) => trimString(c, 240)).filter(Boolean).slice(0, MAX_CHANGES)
+ : []
+);
+
+// The prompt template uses `<...>` markers for every field placeholder. If a
+// JSON block's `prompt` is still wrapped in angle brackets, the model parroted
+// the schema example back instead of producing a real refinement — skip it so
+// Codex's habit of replaying its stdin to stdout doesn't poison the result.
+const isPlaceholderPrompt = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(s);
+
+// Codex CLI prepends a banner like `OpenAI Codex CLI...` and `[workdir, /…]`
+// metadata before the model's JSON output, AND echoes the input prompt to
+// stdout (which contains the schema example {…}). Walk braces with string-
+// awareness, skip any block whose `prompt` is a placeholder, and return the
+// first remaining block that parses as an object with a `prompt` field.
+function extractRefinementJson(raw) {
+ if (typeof raw !== 'string' || !raw.trim()) throw new Error('Empty AI response');
+ let s = raw.trim();
+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (fence) s = fence[1].trim();
+
+ let i = 0;
+ let lastErr;
+ let placeholderSeen = false;
+ while (i < s.length) {
+ const start = s.indexOf('{', i);
+ if (start === -1) break;
+ let depth = 0;
+ let inString = false;
+ let escaped = false;
+ let end = -1;
+ for (let j = start; j < s.length; j++) {
+ const ch = s[j];
+ if (inString) {
+ if (escaped) escaped = false;
+ else if (ch === '\\') escaped = true;
+ else if (ch === '"') inString = false;
+ continue;
+ }
+ if (ch === '"') { inString = true; continue; }
+ if (ch === '{') depth++;
+ else if (ch === '}') {
+ depth--;
+ if (depth === 0) { end = j; break; }
+ }
+ }
+ if (end === -1) break;
+ const block = s.slice(start, end + 1);
+ try {
+ const value = JSON.parse(block);
+ if (value && typeof value === 'object' && typeof value.prompt === 'string') {
+ if (isPlaceholderPrompt(value.prompt)) { placeholderSeen = true; }
+ else return value;
+ }
+ } catch (e) { lastErr = e; }
+ i = end + 1;
+ }
+ if (placeholderSeen) {
+ throw new Error('AI returned the schema placeholder instead of a real refinement — try a stronger model or rerun');
+ }
+ throw new Error(`Invalid JSON in AI response${lastErr ? `: ${lastErr.message}` : ''}`);
+}
+
+export function buildMediaPromptRefinePrompt({ kind, prompt, negativePrompt, feedback, renderConfig = {} }) {
+ const kindLabel = kind === 'video' ? 'video' : 'image';
+ return `You are a senior prompt editor for generative ${kindLabel} renders.
+
+Take the ORIGINAL POSITIVE PROMPT below and produce a NEW POSITIVE PROMPT that fully incorporates the user's feedback. Output the COMPLETE rewritten prompt — not a placeholder, not a summary, not a description of the changes. The "prompt" field MUST contain the full ready-to-render text, paragraph-style, including any preserved details from the original.
+
+Also produce an updated negative prompt and a short rationale.
+
+Return ONLY valid JSON in this schema (replace every <…> with real content; do NOT output the literal angle-bracket text):
+{
+ "prompt": "<the full rewritten positive prompt, ready to send to the renderer>",
+ "negativePrompt": "<the full rewritten negative prompt, or an empty string if none>",
+ "rationale": "<one concise sentence explaining the edit>",
+ "changes": ["<short bullet of what changed>"]
+}
+
+Rules:
+- Do not add new story content, characters, objects, camera moves, aspect ratio text, or brand names unless the user asks for them.
+- Prefer precise visual-direction edits over vague quality boosters.
+- Keep useful existing style constraints unless the user explicitly rejects them.
+- Move things the user dislikes into the negative prompt when that improves control.
+- If the user asks for a different style, make the positive prompt clearly say what to move toward and the negative prompt clearly say what to avoid.
+- The "prompt" field must NEVER equal the schema placeholder text — it must be the actual rewritten render prompt.
+
+ORIGINAL POSITIVE PROMPT:
+${prompt || '(empty)'}
+
+ORIGINAL NEGATIVE PROMPT:
+${negativePrompt || '(empty)'}
+
+RENDER CONFIG (kind=${kind}):
+${JSON.stringify(renderConfig, null, 2)}
+
+USER FEEDBACK:
+${feedback}`;
+}
+
+// CLI providers (codex/claude-code/gemini-cli) need provider-specific arg
+// shapes that the toolkit runner already knows about — going through the
+// runner avoids the "stdin is not a terminal" failure mode that hits when
+// you spawn `codex` directly without the `exec -` invocation.
+async function runRefinePrompt(provider, model, prompt) {
+ const { runId } = await createRun({
+ providerId: provider.id,
+ model,
+ prompt,
+ source: 'media-prompt-refine',
+ });
+
+ let text = '';
+ return await new Promise((resolve, reject) => {
+ const onData = (chunk) => { text += typeof chunk === 'string' ? chunk : (chunk?.text || ''); };
+ const onComplete = (result) => {
+ if (result?.error || result?.success === false) {
+ reject(new ServerError(result?.error || 'Prompt refinement failed', { status: 502, code: 'PROMPT_REFINE_FAILED' }));
+ } else {
+ resolve({ text, runId });
+ }
+ };
+ if (provider.type === 'cli') {
+ // `runner.js#buildCliArgs` only translates `provider.defaultModel` into
+ // a `--model` flag for `codex` today; `claude-code` and `gemini-cli`
+ // ignore it and run with whatever model is baked into provider.args.
+ // Override defaultModel only when it'll actually take effect — otherwise
+ // we'd lie to the caller about which model ran. (PLAN.md tracks the
+ // shared-infra fix to extend buildCliArgs to all CLI providers.)
+ const canOverrideModel = provider.id === 'codex';
+ const providerForCli = canOverrideModel && model && model !== provider.defaultModel
+ ? { ...provider, defaultModel: model }
+ : provider;
+ executeCliRun(runId, providerForCli, prompt, process.cwd(), onData, onComplete, provider.timeout ?? 300000).catch(reject);
+ } else {
+ executeApiRun(runId, provider, model, prompt, process.cwd(), [], onData, onComplete).catch(reject);
+ }
+ });
+}
+
+export async function refineMediaPrompt({
+ kind,
+ prompt,
+ negativePrompt = '',
+ feedback,
+ providerId,
+ model,
+ renderConfig = {},
+}) {
+ // Let real failures (providers.json unreadable, toolkit not initialized)
+ // bubble through the centralized error handler as 5xx. getProviderById
+ // returns null for not-found, which is what 404 PROVIDER_NOT_FOUND is for —
+ // don't swallow other rejections into that 404.
+ const provider = await getProviderById(providerId);
+ if (!provider) {
+ throw new ServerError('Provider not found', { status: 404, code: 'PROVIDER_NOT_FOUND' });
+ }
+ if (provider.enabled === false) {
+ throw new ServerError(
+ `Provider "${provider.name || provider.id}" is disabled — enable it in Settings → Providers first`,
+ { status: 400, code: 'PROVIDER_DISABLED' },
+ );
+ }
+
+ // Resolve the model that'll actually run. For API + Codex CLI, the runner
+ // honors the per-call `model` override. For other CLI providers (claude-code,
+ // gemini-cli), `runner.js#buildCliArgs` ignores per-call model and runs
+ // whatever's baked into provider.args / provider.defaultModel — so reporting
+ // the user-requested model in the response/run-record would lie about which
+ // model produced the output. Fall back through defaultModel → models[0] for
+ // those providers so the returned `model` reflects reality. (PLAN.md tracks
+ // extending buildCliArgs to honor per-call model for all CLI providers.)
+ const honorsModelOverride = provider.type === 'api' || provider.id === 'codex';
+ const selectedModel = honorsModelOverride
+ ? (model || provider.defaultModel || provider.models?.[0] || '')
+ : (provider.defaultModel || provider.models?.[0] || '');
+ if (!selectedModel && provider.type === 'api') {
+ throw new ServerError('Model is required for prompt refinement', { status: 400, code: 'MODEL_REQUIRED' });
+ }
+
+ const llmPrompt = buildMediaPromptRefinePrompt({
+ kind,
+ prompt: trimString(prompt),
+ negativePrompt: trimString(negativePrompt),
+ feedback: trimString(feedback, 3000),
+ renderConfig,
+ });
+
+ const { text, runId } = await runRefinePrompt(provider, selectedModel, llmPrompt);
+
+ let parsed;
+ try {
+ parsed = extractRefinementJson(text || '');
+ } catch (e) {
+ // Log only the response size + error reason, not the raw body. The body
+ // can contain user prompts or other sensitive content; the persisted
+ // run artifact at `data/runs/<runId>/output.txt` already captures the
+ // full response for offline debugging.
+ // Log the runId so operators can locate the full response — the actual
+ // path depends on the runner's configured data dir, so let the Runs UI /
+ // tooling resolve the artifact rather than printing a path that may be
+ // wrong when dataDir isn't the default.
+ console.warn(`⚠️ media-prompt-refine [${provider.id}/${selectedModel || 'default'} runId=${runId}] parse failed: ${e.message} (response size: ${(text || '').length} chars)`);
+ throw new ServerError(e.message, { status: 502, code: 'PROMPT_REFINE_BAD_JSON' });
+ }
+
+ const refinedPrompt = trimString(parsed.prompt);
+ if (!refinedPrompt) {
+ throw new ServerError('LLM returned an empty prompt', { status: 502, code: 'PROMPT_REFINE_EMPTY_PROMPT' });
+ }
+
+ return {
+ prompt: refinedPrompt,
+ negativePrompt: trimString(parsed.negativePrompt),
+ rationale: trimString(parsed.rationale, MAX_REASON_LEN),
+ changes: cleanChanges(parsed.changes),
+ providerId: provider.id,
+ model: selectedModel,
+ };
+}
diff --git a/server/services/mediaPromptRefiner.test.js b/server/services/mediaPromptRefiner.test.js
new file mode 100644
index 0000000000..4e50132a8b
--- /dev/null
+++ b/server/services/mediaPromptRefiner.test.js
@@ -0,0 +1,299 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('./providers.js', () => ({
+ getProviderById: vi.fn(),
+}));
+
+vi.mock('./runner.js', () => ({
+ createRun: vi.fn().mockResolvedValue({ runId: 'test-run' }),
+ executeApiRun: vi.fn(),
+ executeCliRun: vi.fn(),
+}));
+
+const providers = await import('./providers.js');
+const runner = await import('./runner.js');
+const { buildMediaPromptRefinePrompt, refineMediaPrompt } = await import('./mediaPromptRefiner.js');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ runner.createRun.mockResolvedValue({ runId: 'test-run' });
+});
+
+// executeCliRun and executeApiRun have different signatures — onData/onComplete
+// sit at different positions. Find the two trailing function args dynamically.
+function mockRunnerSuccess(target, payload) {
+ target.mockImplementation((...args) => {
+ const fns = args.filter((a) => typeof a === 'function');
+ const [onData, onComplete] = fns;
+ onData(payload);
+ onComplete({ success: true });
+ return Promise.resolve();
+ });
+}
+
+describe('mediaPromptRefiner', () => {
+ it('builds a prompt with the original prompt config and user feedback', () => {
+ const prompt = buildMediaPromptRefinePrompt({
+ kind: 'image',
+ prompt: 'a painted wizard',
+ negativePrompt: 'blurry',
+ feedback: 'less painted',
+ renderConfig: { width: 1024, height: 1024 },
+ });
+
+ expect(prompt).toContain('a painted wizard');
+ expect(prompt).toContain('blurry');
+ expect(prompt).toContain('less painted');
+ expect(prompt).toContain('"width": 1024');
+ });
+
+ it('returns sanitized prompt refinement JSON from an API provider', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'openai',
+ name: 'OpenAI',
+ type: 'api',
+ enabled: true,
+ defaultModel: 'gpt-test',
+ });
+ mockRunnerSuccess(runner.executeApiRun, JSON.stringify({
+ prompt: 'modern animated series still',
+ negativePrompt: 'painterly, ornate',
+ rationale: 'Adjusted toward clean animated styling.',
+ changes: ['Reduced painterly detail', 'Added clean animation direction'],
+ }));
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'ornate painted scene',
+ negativePrompt: '',
+ feedback: 'more modern animated series',
+ providerId: 'openai',
+ });
+
+ expect(runner.executeApiRun).toHaveBeenCalled();
+ expect(runner.executeCliRun).not.toHaveBeenCalled();
+ expect(result).toEqual(expect.objectContaining({
+ prompt: 'modern animated series still',
+ negativePrompt: 'painterly, ornate',
+ providerId: 'openai',
+ model: 'gpt-test',
+ }));
+ });
+
+ it('runs refinement through CLI providers without requiring a model', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'codex',
+ name: 'Codex',
+ type: 'cli',
+ enabled: true,
+ });
+ mockRunnerSuccess(runner.executeCliRun, JSON.stringify({
+ prompt: 'cleaner fox portrait',
+ negativePrompt: '',
+ rationale: '',
+ changes: [],
+ }));
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'a fox',
+ feedback: 'cleaner',
+ providerId: 'codex',
+ });
+
+ expect(runner.executeCliRun).toHaveBeenCalled();
+ expect(runner.executeApiRun).not.toHaveBeenCalled();
+ expect(result.providerId).toBe('codex');
+ expect(result.prompt).toBe('cleaner fox portrait');
+ });
+
+ it('skips Codex bracketed metadata (e.g. [workdir, /…]) and finds the JSON object', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'codex', type: 'cli', enabled: true,
+ });
+ const codexOutput = `OpenAI Codex CLI v2.1.0
+[workdir, /Users/antic/github.com/atomantic/PortOS]
+[model, gpt-5]
+[session, abc-123]
+
+${JSON.stringify({ prompt: 'painted owl portrait', negativePrompt: 'blurry', rationale: 'r', changes: ['c1'] })}
+
+[finished]
+`;
+ mockRunnerSuccess(runner.executeCliRun, codexOutput);
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'an owl',
+ feedback: 'painted style',
+ providerId: 'codex',
+ });
+
+ expect(result.prompt).toBe('painted owl portrait');
+ expect(result.negativePrompt).toBe('blurry');
+ });
+
+ it('lifts JSON out of CLI banner noise (codex)', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'codex', type: 'cli', enabled: true,
+ });
+ mockRunnerSuccess(runner.executeCliRun, `OpenAI Codex CLI v2.1.0\nsession: abc-123\n${JSON.stringify({ prompt: 'sunny fox portrait', negativePrompt: '', rationale: '', changes: [] })}\n--- done ---\n`);
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'a fox',
+ feedback: 'sunnier',
+ providerId: 'codex',
+ });
+
+ expect(result.prompt).toBe('sunny fox portrait');
+ });
+
+ it('requires a model for API providers', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'openai', type: 'api', enabled: true,
+ });
+ await expect(refineMediaPrompt({
+ kind: 'image',
+ prompt: 'x',
+ feedback: 'y',
+ providerId: 'openai',
+ })).rejects.toMatchObject({ code: 'MODEL_REQUIRED', status: 400 });
+ });
+
+ it('rejects disabled providers', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'openai', type: 'api', enabled: false, defaultModel: 'gpt-test',
+ });
+ await expect(refineMediaPrompt({
+ kind: 'image',
+ prompt: 'x',
+ feedback: 'y',
+ providerId: 'openai',
+ })).rejects.toMatchObject({ code: 'PROVIDER_DISABLED', status: 400 });
+ });
+
+ it('ignores per-call model override for non-Codex CLIs since the runner cannot apply it', async () => {
+ // runner.js#buildCliArgs only translates defaultModel into a --model flag
+ // for codex. For claude-code / gemini-cli the per-call override would be
+ // silently dropped, so the response model must reflect what'll actually
+ // run (the provider's configured default), not the user's selection.
+ providers.getProviderById.mockResolvedValue({
+ id: 'claude-code',
+ type: 'cli',
+ enabled: true,
+ defaultModel: 'claude-baked-in',
+ });
+ mockRunnerSuccess(runner.executeCliRun, JSON.stringify({
+ prompt: 'x', negativePrompt: '', rationale: '', changes: [],
+ }));
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'p',
+ feedback: 'f',
+ providerId: 'claude-code',
+ model: 'user-selected-model-the-runner-will-ignore',
+ });
+
+ expect(result.model).toBe('claude-baked-in');
+ });
+
+ it('falls back to provider.models[0] when defaultModel is absent (API provider)', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'openai', type: 'api', enabled: true, models: ['gpt-from-list'],
+ });
+ mockRunnerSuccess(runner.executeApiRun, JSON.stringify({
+ prompt: 'x', negativePrompt: '', rationale: '', changes: [],
+ }));
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'p',
+ feedback: 'f',
+ providerId: 'openai',
+ });
+
+ expect(result.model).toBe('gpt-from-list');
+ });
+
+ it('throws when the provider is unknown', async () => {
+ providers.getProviderById.mockResolvedValue(null);
+ await expect(refineMediaPrompt({
+ kind: 'image',
+ prompt: 'x',
+ feedback: 'y',
+ providerId: 'missing',
+ })).rejects.toMatchObject({ code: 'PROVIDER_NOT_FOUND', status: 404 });
+ });
+
+ it('skips the echoed schema example and returns the real refinement', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'codex', type: 'cli', enabled: true,
+ });
+ // Codex echoes the prompt to stdout (which contains the schema example
+ // {"prompt": "<full rewritten positive prompt>"}) then emits the real result.
+ const echoedSchema = JSON.stringify({
+ prompt: '<the full rewritten positive prompt, ready to send to the renderer>',
+ negativePrompt: '<the full rewritten negative prompt, or an empty string if none>',
+ rationale: '<one concise sentence explaining the edit>',
+ changes: ['<short bullet of what changed>'],
+ });
+ const realResult = JSON.stringify({
+ prompt: 'a calm watercolor portrait of a fox, soft morning light',
+ negativePrompt: 'harsh shadows, oversaturation',
+ rationale: 'Shifted from oil-painted toward watercolor.',
+ changes: ['Changed medium to watercolor', 'Softened lighting'],
+ });
+ mockRunnerSuccess(runner.executeCliRun, `Codex CLI banner\n${echoedSchema}\n\n${realResult}\n`);
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'a fox in oil',
+ feedback: 'watercolor instead',
+ providerId: 'codex',
+ });
+
+ expect(result.prompt).toBe('a calm watercolor portrait of a fox, soft morning light');
+ });
+
+ it('reports a helpful error when the model only returns the schema placeholder', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'codex', type: 'cli', enabled: true,
+ });
+ const onlyPlaceholder = JSON.stringify({
+ prompt: '<the full rewritten positive prompt, ready to send to the renderer>',
+ negativePrompt: '<the full rewritten negative prompt, or an empty string if none>',
+ rationale: 'r',
+ changes: ['c'],
+ });
+ mockRunnerSuccess(runner.executeCliRun, onlyPlaceholder);
+
+ await expect(refineMediaPrompt({
+ kind: 'image',
+ prompt: 'a fox',
+ feedback: 'better',
+ providerId: 'codex',
+ })).rejects.toMatchObject({
+ code: 'PROMPT_REFINE_BAD_JSON',
+ message: expect.stringContaining('schema placeholder'),
+ });
+ });
+
+ it('throws PROMPT_REFINE_FAILED when the runner reports an error', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'openai', type: 'api', enabled: true, defaultModel: 'gpt-test',
+ });
+ runner.executeApiRun.mockImplementation((runId, provider, model, prompt, cwd, ctx, onData, onComplete) => {
+ onComplete({ error: 'upstream down' });
+ return Promise.resolve();
+ });
+
+ await expect(refineMediaPrompt({
+ kind: 'image',
+ prompt: 'x',
+ feedback: 'y',
+ providerId: 'openai',
+ })).rejects.toMatchObject({ code: 'PROMPT_REFINE_FAILED', status: 502 });
+ });
+});