Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: reverse-engineer image and video prompts from gallery media
[._.]/ Adam Eivyb6bfe7735f5a
diff --git a/.changelog/next/added-agent-59e8502b.md b/.changelog/next/added-agent-59e8502b.mdnew file mode 100644index 0000000000..0b4d3f96c6--- /dev/null+++ b/.changelog/next/added-agent-59e8502b.md@@ -0,0 +1 @@+- Media Gen can reverse-engineer image and video prompts from a gallery still, clip, or upload using any vision-capable provider.diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex 475a1ab17b..2b04a4b88a 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -1,9 +1,10 @@import { useEffect, useRef, useState } from 'react';import {X, Copy, Sparkles, Film, Image as ImageIcon, Download, Eraser, Wand2,- ChevronLeft, ChevronRight, Maximize2, Minimize2, Star, Box,+ ChevronLeft, ChevronRight, Maximize2, Minimize2, Star, Box, ScanEye,} from 'lucide-react';import PromptRefineModal from './PromptRefineModal';+import { PromptFromMediaModal } from './PromptFromMedia';import AddToCollectionMenu from './AddToCollectionMenu';import PinToMoodBoardMenu from './PinToMoodBoardMenu';import MediaImage from '../MediaImage';@@ -108,6 +109,7 @@ export default function MediaLightbox({}) {const [fullScreen, setFullScreen] = useState(false);const [refineOpen, setRefineOpen] = useState(false);+ const [promptFromOpen, setPromptFromOpen] = useState(false);useScrollLock(!!item);// Read callbacks + frequently-changing values from refs so the keydown// listener and the note-save debounce don't tear down on every parent@@ -150,6 +152,7 @@ export default function MediaLightbox({const cb = refs.current;if (e.key === 'Escape') {if (refineOpen) { setRefineOpen(false); return; }+ if (promptFromOpen) { setPromptFromOpen(false); return; }if (fullScreen) { setFullScreen(false); return; }cb.onClose();return;@@ -179,10 +182,10 @@ export default function MediaLightbox({};window.addEventListener('keydown', onKey);return () => window.removeEventListener('keydown', onKey);- }, [item, hasPrevious, hasNext, fullScreen, refineOpen]);+ }, [item, hasPrevious, hasNext, fullScreen, refineOpen, promptFromOpen]);// Reset refine modal when the previewed item changes.- useEffect(() => { setRefineOpen(false); }, [item?.key]);+ useEffect(() => { setRefineOpen(false); setPromptFromOpen(false); }, [item?.key]);const { onTouchStart, onTouchEnd } = useSwipeNav({ onPrevious, onNext, hasPrevious, hasNext });@@ -356,6 +359,7 @@ export default function MediaLightbox({regenBounds={regenBounds}copy={copy}onRefine={() => setRefineOpen(true)}+ onPromptFrom={() => setPromptFromOpen(true)}annotation={annotation}onAnnotationChange={onAnnotationChange}variantGroup={variantGroup}@@ -364,6 +368,7 @@ export default function MediaLightbox({)}</div><PromptRefineModal item={item} open={refineOpen} onClose={() => setRefineOpen(false)} />+ <PromptFromMediaModal item={item} open={promptFromOpen} onClose={() => setPromptFromOpen(false)} /></div>);}@@ -396,7 +401,7 @@ function PeerNotes({ others }) {function SettingsPane({item, meta, isVideo,onClose, onRemix, onSendToImage, onSendToVideo, onSendTo3d, onContinue, onClean, onRegenerate, onRemoveWatermark, regenAvailable, regenBounds,- copy, onRefine,+ copy, onRefine, onPromptFrom,annotation, onAnnotationChange,variantGroup, onSelectVariant,}) {@@ -642,6 +647,16 @@ function SettingsPane({<Sparkles className="w-3.5 h-3.5" /> Refine Prompt</button>)}+ {onPromptFrom && (+ <button+ type="button"+ onClick={onPromptFrom}+ title="Ask a vision model to write the image and/or video prompt that would recreate this"+ 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"+ >+ <ScanEye className="w-3.5 h-3.5" /> Prompt from this+ </button>+ )}{onRemix && (<buttontype="button"diff --git a/client/src/components/media/MediaLightbox.test.jsx b/client/src/components/media/MediaLightbox.test.jsxindex 864ff76070..4ad77a100b 100644--- a/client/src/components/media/MediaLightbox.test.jsx+++ b/client/src/components/media/MediaLightbox.test.jsx@@ -8,6 +8,7 @@ import MediaLightbox from './MediaLightbox';// on MediaLightbox's own <video> markup and off the network.vi.mock('./AddToCollectionMenu', () => ({ default: () => null }));vi.mock('./PromptRefineModal', () => ({ default: () => null }));+vi.mock('./PromptFromMedia', () => ({ default: () => null, PromptFromMediaModal: () => null }));const videoItem = {kind: 'video',diff --git a/client/src/components/media/PromptFromMedia.jsx b/client/src/components/media/PromptFromMedia.jsxnew file mode 100644index 0000000000..d028ea5db0--- /dev/null+++ b/client/src/components/media/PromptFromMedia.jsx@@ -0,0 +1,427 @@+import { useCallback, useEffect, useId, useState } from 'react';+import { useNavigate } from 'react-router';+import { ScanEye, ChevronDown, ChevronUp, Image as ImageIcon, Film, X, Copy } from 'lucide-react';+import ProviderModelSelector from '../ProviderModelSelector';+import useProviderModels from '../../hooks/useProviderModels';+import useVisionModelIds from '../../hooks/useVisionModelIds';+import GalleryImagePicker from '../imageGen/GalleryImagePicker';+import GalleryVideoPicker from '../videoGen/GalleryVideoPicker';+import Modal from '../ui/Modal';+import { FormField } from '../ui/FormField';+import { promptFromMedia } from '../../services/apiMediaJobs';+import { isVisionCapableCliProvider, visionLocalModelFilter } from '../../utils/providers';+import { copyToClipboard } from '../../lib/clipboard';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';++const LS_KEY_PROVIDER = 'portos_prompt_from_media_provider';+const LS_KEY_MODEL = 'portos_prompt_from_media_model';+const LS_KEY_EFFORT = 'portos_prompt_from_media_effort';++const visionProviderFilter = (p) => p.enabled && (p.type === 'api' || isVisionCapableCliProvider(p));++function sourceFromItem(item) {+ if (!item) return null;+ if (item.kind === 'upload') {+ return { sourceKind: 'upload', filename: item.filename, previewUrl: item.previewUrl || null, label: item.label || item.filename };+ }+ if (item.kind === 'video') {+ return { sourceKind: 'video', videoId: item.id, filename: item.filename, previewUrl: item.previewUrl || null, label: item.prompt || item.filename };+ }+ return { sourceKind: 'image', filename: item.filename, previewUrl: item.previewUrl || `/data/images/${item.filename}`, label: item.prompt || item.filename };+}++function SourceThumb({ source }) {+ if (!source) return null;+ if (source.previewUrl) {+ return <img src={source.previewUrl} alt="" className="w-16 h-16 rounded object-cover bg-port-bg" />;+ }+ return (+ <div className="w-16 h-16 rounded bg-port-bg border border-port-border flex items-center justify-center text-gray-500">+ {source.sourceKind === 'image' ? <ImageIcon className="w-6 h-6" /> : <Film className="w-6 h-6" />}+ </div>+ );+}++/**+ * Pick a gallery still/clip (or upload one), choose a vision-capable+ * provider/model/effort, and reverse-engineer the image and/or video prompt+ * that would recreate something like it.+ *+ * `kindDefault` seeds the target checkboxes (`image` / `video` / `both`).+ * When `setPrompt` is passed (Image Gen / Video Gen), Apply fills the host+ * form. Otherwise the result offers "Open in Image Gen / Video Gen".+ */+export default function PromptFromMedia({+ kindDefault = 'both',+ setPrompt,+ setNegativePrompt,+ applyKind,+ initialSource = null,+ disabled = false,+ alwaysOpen = false,+}) {+ const navigate = useNavigate();+ const idPrefix = useId();+ const [isOpen, setIsOpen] = useState(!!initialSource || alwaysOpen);+ const [source, setSource] = useState(() => sourceFromItem(initialSource));+ const [imagePickerOpen, setImagePickerOpen] = useState(false);+ const [videoPickerOpen, setVideoPickerOpen] = useState(false);+ const [wantImage, setWantImage] = useState(kindDefault !== 'video');+ const [wantVideo, setWantVideo] = useState(kindDefault !== 'image');+ const [effort, setEffort] = useState(() => {+ try { return localStorage.getItem(LS_KEY_EFFORT) || ''; } catch { return ''; }+ });+ const [running, setRunning] = useState(false);+ const [result, setResult] = useState(null);+ const { idsByProvider: visionIds } = useVisionModelIds(isOpen);+ const modelFilter = useCallback(+ (id, provider) => visionLocalModelFilter(id, provider, visionIds),+ [visionIds],+ );++ const {+ providers,+ selectedProviderId,+ selectedModel,+ availableModels,+ setSelectedProviderId,+ setSelectedModel,+ loading: providersLoading,+ } = useProviderModels({+ filter: visionProviderFilter,+ silent: true,+ withEffort: true,+ modelFilter,+ });++ useEffect(() => {+ if (providersLoading || !providers.length) return;+ try {+ const savedProvider = localStorage.getItem(LS_KEY_PROVIDER);+ const savedModel = localStorage.getItem(LS_KEY_MODEL);+ if (savedProvider && providers.some((p) => p.id === savedProvider)) {+ setSelectedProviderId(savedProvider);+ if (savedModel) setSelectedModel(savedModel);+ }+ } catch { /* ignore */ }+ }, [providers, providersLoading, setSelectedProviderId, setSelectedModel]);++ useEffect(() => {+ if (!initialSource) return;+ setSource(sourceFromItem(initialSource));+ setResult(null);+ }, [initialSource]);++ const persistProvider = (id) => {+ try {+ if (id) localStorage.setItem(LS_KEY_PROVIDER, id);+ else localStorage.removeItem(LS_KEY_PROVIDER);+ localStorage.removeItem(LS_KEY_MODEL);+ localStorage.removeItem(LS_KEY_EFFORT);+ } catch { /* ignore */ }+ };++ const handleProviderChange = (id) => {+ setSelectedProviderId(id);+ setEffort('');+ persistProvider(id);+ };++ const handleModelChange = (model) => {+ setSelectedModel(model);+ try {+ if (selectedProviderId) localStorage.setItem(LS_KEY_PROVIDER, selectedProviderId);+ if (model) localStorage.setItem(LS_KEY_MODEL, model);+ else localStorage.removeItem(LS_KEY_MODEL);+ } catch { /* ignore */ }+ };++ const handleEffortChange = (val) => {+ setEffort(val);+ try {+ if (val) localStorage.setItem(LS_KEY_EFFORT, val);+ else localStorage.removeItem(LS_KEY_EFFORT);+ } catch { /* ignore */ }+ };++ const targets = [+ ...(wantImage ? ['image'] : []),+ ...(wantVideo ? ['video'] : []),+ ];+ const canRun = !!source && targets.length > 0 && !!selectedProviderId && !running && !disabled;++ const handleGenerate = async () => {+ if (!canRun) {+ if (!source) toast.error('Pick an image or video first');+ else if (!targets.length) toast.error('Choose at least one of image or video prompt');+ else if (!selectedProviderId) toast.error('Select a vision-capable AI provider');+ return;+ }+ setRunning(true);+ setResult(null);+ const payload = {+ sourceKind: source.sourceKind,+ filename: source.filename,+ videoId: source.videoId,+ targets,+ providerId: selectedProviderId,+ model: selectedModel || undefined,+ effort: effort || undefined,+ };+ const data = await promptFromMedia(payload).catch(() => null);+ setRunning(false);+ if (!data) return;+ setResult(data);+ toast.success('Prompts ready');+ };++ const apply = (kind) => {+ if (!result) return;+ const prompt = kind === 'video' ? result.videoPrompt : result.imagePrompt;+ const negative = kind === 'video' ? result.videoNegativePrompt : result.imageNegativePrompt;+ if (!prompt) return;+ if (setPrompt && applyKind === kind) {+ setPrompt(prompt);+ if (setNegativePrompt && negative != null) setNegativePrompt(negative);+ toast.success(`${kind === 'video' ? 'Video' : 'Image'} prompt applied`);+ return;+ }+ const params = new URLSearchParams();+ params.set('prompt', prompt);+ if (negative) params.set('negativePrompt', negative);+ navigate(`/media/${kind}?${params.toString()}`);+ };++ const copyField = (text, label) => {+ if (text) copyToClipboard(text, `${label} copied`);+ };++ return (+ <div className="space-y-2 my-1">+ {!alwaysOpen && (+ <div className="flex items-center justify-between gap-2">+ <button+ type="button"+ onClick={() => setIsOpen((prev) => !prev)}+ disabled={disabled || running}+ className="inline-flex items-center gap-1.5 text-xs text-port-accent hover:text-port-accent/80 font-medium transition-colors disabled:opacity-50 min-h-[36px] px-1"+ aria-expanded={isOpen}+ aria-label="Toggle prompt from media"+ >+ <ScanEye className="w-3.5 h-3.5" />+ <span>Prompt from media</span>+ {isOpen ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}+ </button>+ </div>+ )}++ {isOpen && (+ <div className="p-3 bg-port-bg/70 border border-port-border rounded-lg space-y-3">+ <div className="flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={() => setImagePickerOpen(true)}+ disabled={disabled || running}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-port-border text-xs text-gray-200 hover:border-port-accent hover:text-white disabled:opacity-50 min-h-[36px]"+ >+ <ImageIcon className="w-3.5 h-3.5" /> Pick image+ </button>+ <button+ type="button"+ onClick={() => setVideoPickerOpen(true)}+ disabled={disabled || running}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-port-border text-xs text-gray-200 hover:border-port-accent hover:text-white disabled:opacity-50 min-h-[36px]"+ >+ <Film className="w-3.5 h-3.5" /> Pick video+ </button>+ </div>++ {source && (+ <div className="flex items-center gap-3">+ <SourceThumb source={source} />+ <div className="min-w-0 flex-1">+ <div className="text-xs text-gray-300 truncate">{source.label || source.filename || source.videoId}</div>+ <div className="text-[10px] uppercase tracking-wide text-gray-500">+ {source.sourceKind === 'video' ? 'Gallery video' : source.sourceKind === 'upload' ? 'Upload' : 'Gallery image'}+ </div>+ </div>+ <button+ type="button"+ onClick={() => { setSource(null); setResult(null); }}+ className="p-1.5 text-gray-400 hover:text-white min-h-[36px] min-w-[36px] flex items-center justify-center"+ aria-label="Clear selected media"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>+ )}++ <div className="flex flex-wrap gap-4">+ <label htmlFor={`${idPrefix}-want-image`} className="inline-flex items-center gap-2 text-xs text-gray-300 min-h-[36px]">+ <input+ id={`${idPrefix}-want-image`}+ type="checkbox"+ checked={wantImage}+ onChange={(e) => setWantImage(e.target.checked)}+ disabled={disabled || running}+ className="accent-port-accent"+ />+ Image prompt+ </label>+ <label htmlFor={`${idPrefix}-want-video`} className="inline-flex items-center gap-2 text-xs text-gray-300 min-h-[36px]">+ <input+ id={`${idPrefix}-want-video`}+ type="checkbox"+ checked={wantVideo}+ onChange={(e) => setWantVideo(e.target.checked)}+ disabled={disabled || running}+ className="accent-port-accent"+ />+ Video prompt+ </label>+ </div>++ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={handleProviderChange}+ onModelChange={handleModelChange}+ effort={effort}+ onEffortChange={handleEffortChange}+ disabled={disabled || running || providersLoading}+ layout="stacked"+ />++ {providers.length === 0 && !providersLoading && (+ <p className="text-xs text-port-warning">No vision-capable providers are enabled. Add an API VLM or a Claude/Codex CLI in Settings → Providers.</p>+ )}++ <div className="flex justify-end">+ <button+ type="button"+ onClick={handleGenerate}+ disabled={!canRun}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80 transition-colors disabled:opacity-50 min-h-[36px]"+ >+ {running ? <><BrailleSpinner /><span>Reading media…</span></> : <><ScanEye className="w-3.5 h-3.5" /><span>Create prompt</span></>}+ </button>+ </div>++ {result && (+ <div className="space-y-3 pt-1">+ {result.rationale && (+ <p className="text-xs text-gray-300 bg-port-bg border border-port-border rounded-lg p-2">{result.rationale}</p>+ )}+ {result.imagePrompt != null && (+ <PromptResultField+ label="Image prompt"+ value={result.imagePrompt}+ negative={result.imageNegativePrompt}+ onCopy={() => copyField(result.imagePrompt, 'Image prompt')}+ onApply={() => apply('image')}+ applyLabel={setPrompt && applyKind === 'image' ? 'Use as prompt' : 'Open in Image Gen'}+ />+ )}+ {result.videoPrompt != null && (+ <PromptResultField+ label="Video prompt"+ value={result.videoPrompt}+ negative={result.videoNegativePrompt}+ onCopy={() => copyField(result.videoPrompt, 'Video prompt')}+ onApply={() => apply('video')}+ applyLabel={setPrompt && applyKind === 'video' ? 'Use as prompt' : 'Open in Video Gen'}+ />+ )}+ </div>+ )}+ </div>+ )}++ <GalleryImagePicker+ open={imagePickerOpen}+ onClose={() => setImagePickerOpen(false)}+ allowUpload+ onSelect={(item) => { setSource(sourceFromItem(item)); setResult(null); }}+ />+ <GalleryVideoPicker+ open={videoPickerOpen}+ onClose={() => setVideoPickerOpen(false)}+ allowUpload+ onSelect={(item) => { setSource(sourceFromItem(item)); setResult(null); }}+ />+ </div>+ );+}++function PromptResultField({ label, value, negative, onCopy, onApply, applyLabel }) {+ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[11px] uppercase tracking-wide text-gray-500">{label}</span>+ <div className="flex items-center gap-1">+ <button type="button" onClick={onCopy} className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50" aria-label={`Copy ${label}`}>+ <Copy className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={onApply}+ className="px-2 py-1 rounded text-[11px] bg-port-accent/80 text-white hover:opacity-90 min-h-[32px]"+ >+ {applyLabel}+ </button>+ </div>+ </div>+ <textarea+ readOnly+ value={value}+ rows={4}+ className="w-full bg-port-bg border border-port-border rounded-lg p-2 text-xs text-white resize-y"+ />+ {negative ? (+ <FormField label="Negative" labelClassName="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">+ <textarea readOnly value={negative} rows={2} className="w-full bg-port-bg border border-port-border rounded-lg p-2 text-xs text-gray-300 resize-y" />+ </FormField>+ ) : null}+ </div>+ );+}++export function PromptFromMediaModal({ item, open, onClose }) {+ if (!open || !item) return null;+ return (+ <Modal+ open={open}+ onClose={onClose}+ size="xl"+ zIndexClassName="z-[70]"+ backdropClassName="bg-black/80"+ ariaLabelledBy="prompt-from-media-title"+ panelClassName="max-h-[90vh] overflow-hidden bg-port-card border border-port-border rounded-xl shadow-2xl flex flex-col"+ >+ <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">+ <ScanEye className="w-4 h-4 text-port-accent shrink-0" />+ <h2 id="prompt-from-media-title" className="text-sm font-semibold text-white">Prompt from this</h2>+ </div>+ <button+ type="button"+ onClick={onClose}+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50 min-h-[44px] min-w-[44px] flex items-center justify-center"+ aria-label="Close"+ >+ <X className="w-4 h-4" />+ </button>+ </header>+ <div className="flex-1 overflow-y-auto p-4">+ <PromptFromMedia+ kindDefault="both"+ initialSource={item}+ alwaysOpen+ />+ </div>+ </Modal>+ );+}diff --git a/client/src/components/media/PromptFromMedia.test.jsx b/client/src/components/media/PromptFromMedia.test.jsxnew file mode 100644index 0000000000..9acc983705--- /dev/null+++ b/client/src/components/media/PromptFromMedia.test.jsx@@ -0,0 +1,112 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import PromptFromMedia from './PromptFromMedia';+import * as api from '../../services/apiMediaJobs';++vi.mock('../../hooks/useProviderModels', () => ({+ default: vi.fn(() => ({+ providers: [+ { id: 'openai', name: 'OpenAI', type: 'api', enabled: true, defaultModel: 'gpt-4o' },+ ],+ selectedProviderId: 'openai',+ selectedModel: 'gpt-4o',+ availableModels: ['gpt-4o'],+ setSelectedProviderId: vi.fn(),+ setSelectedModel: vi.fn(),+ loading: false,+ })),+}));++vi.mock('../../hooks/useVisionModelIds', () => ({+ default: () => ({ idsByProvider: null, loaded: true }),+}));++vi.mock('../../services/apiMediaJobs', () => ({+ promptFromMedia: vi.fn(),+}));++vi.mock('../imageGen/GalleryImagePicker', () => ({ default: () => null }));+vi.mock('../videoGen/GalleryVideoPicker', () => ({ default: () => null }));++const INITIAL = {+ kind: 'image',+ filename: 'still.png',+ previewUrl: '/data/images/still.png',+ prompt: 'a reference still',+};++function renderPanel(props = {}) {+ return render(+ <MemoryRouter>+ <PromptFromMedia+ kindDefault="image"+ applyKind="image"+ initialSource={INITIAL}+ setPrompt={vi.fn()}+ setNegativePrompt={vi.fn()}+ {...props}+ />+ </MemoryRouter>,+ );+}++describe('PromptFromMedia', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('sends the selected still to a vision provider and applies the image prompt', async () => {+ const setPrompt = vi.fn();+ const setNegativePrompt = vi.fn();+ vi.mocked(api.promptFromMedia).mockResolvedValue({+ imagePrompt: 'moonlit painted wizard',+ imageNegativePrompt: 'blurry',+ rationale: 'Painted moonlight look.',+ });++ renderPanel({ setPrompt, setNegativePrompt });++ fireEvent.click(screen.getByRole('button', { name: /create prompt/i }));++ await waitFor(() => {+ expect(api.promptFromMedia).toHaveBeenCalledWith({+ sourceKind: 'image',+ filename: 'still.png',+ videoId: undefined,+ targets: ['image'],+ providerId: 'openai',+ model: 'gpt-4o',+ effort: undefined,+ });+ });++ fireEvent.click(screen.getByRole('button', { name: /use as prompt/i }));+ expect(setPrompt).toHaveBeenCalledWith('moonlit painted wizard');+ expect(setNegativePrompt).toHaveBeenCalledWith('blurry');+ });++ it('can request both image and video prompts from a gallery clip', async () => {+ vi.mocked(api.promptFromMedia).mockResolvedValue({+ imagePrompt: 'a still of the clip',+ videoPrompt: 'the camera dollies past the subject',+ });++ renderPanel({+ kindDefault: 'both',+ applyKind: undefined,+ initialSource: { kind: 'video', id: 'vid-1', filename: 'vid-1.mp4', previewUrl: '/data/video-thumbnails/t.jpg' },+ });++ fireEvent.click(screen.getByRole('button', { name: /create prompt/i }));++ await waitFor(() => {+ expect(api.promptFromMedia).toHaveBeenCalledWith(expect.objectContaining({+ sourceKind: 'video',+ videoId: 'vid-1',+ targets: ['image', 'video'],+ }));+ });+ expect(screen.getByText('the camera dollies past the subject')).toBeInTheDocument();+ });+});diff --git a/client/src/components/videoGen/GalleryVideoPicker.jsx b/client/src/components/videoGen/GalleryVideoPicker.jsxnew file mode 100644index 0000000000..f8d5e6c44b--- /dev/null+++ b/client/src/components/videoGen/GalleryVideoPicker.jsx@@ -0,0 +1,164 @@+// Visual picker over video history — the video counterpart of GalleryImagePicker.+// Opens as a modal, fetches GET /api/video-gen/history on open, lets the user+// search (same haystack as MediaHistory) and click a thumbnail. With+// `allowUpload`, a header Upload button saves the file via POST /api/uploads+// and selects it as `{ kind: 'upload', filename }` so the reverse-prompt+// endpoint can sample frames from PATHS.uploads.++import { useEffect, useMemo, useState } from 'react';+import { Search, X, RefreshCw, Upload } from 'lucide-react';+import Modal from '../ui/Modal';+import FilePickerButton from '../ui/FilePickerButton';+import MediaCard from '../media/MediaCard';+import { normalizeVideo } from '../media/normalize';+import { listVideoHistory } from '../../services/apiImageVideo';+import { uploadFile } from '../../services/apiMedia';+import { readFileAsBase64, JSON_UPLOAD_MAX_FILE_SIZE } from '../../utils/fileUpload';+import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';+import { formatBytes } from '../../utils/formatters';+import toast from '../ui/Toast';++const VIDEO_ACCEPT = 'video/mp4,video/webm,video/quicktime,video/x-m4v,.mp4,.webm,.mov,.m4v';++export default function GalleryVideoPicker({ open, onClose, onSelect, allowUpload = false }) {+ const [items, setItems] = useState([]);+ const [loading, setLoading] = useState(false);+ const [uploading, setUploading] = useState(false);+ const [query, setQuery] = useState('');++ useEffect(() => {+ if (!open) { setQuery(''); return undefined; }+ let cancelled = false;+ setLoading(true);+ listVideoHistory()+ .then((videos) => {+ if (cancelled) return;+ const normalized = (Array.isArray(videos) ? videos : [])+ .map(normalizeVideo)+ .filter((it) => !it.hidden);+ setItems(normalized);+ })+ .catch(() => { if (!cancelled) setItems([]); })+ .finally(() => { if (!cancelled) setLoading(false); });+ return () => { cancelled = true; };+ }, [open]);++ const haystacks = useMemo(() => items.map(buildMediaHaystack), [items]);+ const tokens = useMemo(() => tokenizeQuery(query), [query]);+ const filtered = useMemo(() => {+ if (!tokens.length) return items;+ return items.filter((item, idx) => matchHaystack(haystacks[idx], tokens));+ }, [items, haystacks, tokens]);++ const handleUpload = async (event) => {+ const file = event.target.files?.[0];+ if (!file) return;+ if (file.size > JSON_UPLOAD_MAX_FILE_SIZE) {+ toast.error(`Video is too large (${formatBytes(file.size)}). Max ${formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)}.`);+ return;+ }+ setUploading(true);+ const base64 = await readFileAsBase64(file).catch(() => null);+ if (!base64) { setUploading(false); toast.error(`Failed to read ${file.name}`); return; }+ const saved = await uploadFile(base64, file.name, { silent: true }).catch((err) => {+ toast.error(err?.message || 'Upload failed');+ return null;+ });+ setUploading(false);+ if (!saved?.filename) return;+ onSelect?.({+ kind: 'upload',+ filename: saved.filename,+ label: file.name,+ previewUrl: null,+ });+ onClose?.();+ };++ return (+ <Modal+ open={open}+ onClose={onClose}+ size="3xl"+ usePortal+ panelClassName="bg-port-card border border-port-border rounded-xl max-h-[85vh] flex flex-col"+ ariaLabel="Pick a video from your gallery"+ >+ <div className="p-3 border-b border-port-border space-y-2">+ <div className="flex items-center justify-between gap-3">+ <h2 className="text-sm font-medium text-white shrink-0">Pick a video</h2>+ <div className="flex items-center gap-2 shrink-0">+ {allowUpload && (+ <FilePickerButton+ accept={VIDEO_ACCEPT}+ onChange={handleUpload}+ disabled={uploading}+ title="Upload a video from your device"+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-300 hover:border-port-accent hover:text-white"+ >+ {uploading+ ? <><RefreshCw className="h-3.5 w-3.5 animate-spin" /> Uploading…</>+ : <><Upload className="h-3.5 w-3.5" /> Upload</>}+ </FilePickerButton>+ )}+ <button+ type="button"+ onClick={onClose}+ className="shrink-0 p-1.5 text-gray-400 hover:text-white rounded min-h-[44px] min-w-[44px] flex items-center justify-center"+ aria-label="Close"+ >+ <X className="w-4 h-4" />+ </button>+ </div>+ </div>+ <div className="relative">+ <label htmlFor="video-picker-search" className="sr-only">Search videos</label>+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500" />+ <input+ id="video-picker-search"+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search prompt, model, seed…"+ className="w-full pl-7 pr-7 py-1.5 text-xs bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"+ autoFocus+ />+ {query && (+ <button+ type="button"+ onClick={() => setQuery('')}+ className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"+ aria-label="Clear search"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ </div>++ <div className="flex-1 overflow-y-auto p-3">+ {loading ? (+ <div className="flex items-center justify-center gap-2 text-xs text-gray-400 py-10">+ <RefreshCw className="w-4 h-4 animate-spin" /> Loading videos…+ </div>+ ) : filtered.length === 0 ? (+ <div className="text-xs text-gray-500 py-10 text-center">+ {items.length === 0 ? 'No videos in your gallery yet.' : 'No videos match your search.'}+ </div>+ ) : (+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">+ {filtered.map((item) => (+ <MediaCard+ key={item.key}+ item={item}+ hideActions+ showCollectionMenu={false}+ onClick={() => { onSelect?.(item); onClose?.(); }}+ />+ ))}+ </div>+ )}+ </div>+ </Modal>+ );+}diff --git a/client/src/components/videoGen/GalleryVideoPicker.test.jsx b/client/src/components/videoGen/GalleryVideoPicker.test.jsxnew file mode 100644index 0000000000..f421c868fe--- /dev/null+++ b/client/src/components/videoGen/GalleryVideoPicker.test.jsx@@ -0,0 +1,50 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import GalleryVideoPicker from './GalleryVideoPicker';++const listVideoHistory = vi.fn();+vi.mock('../../services/apiImageVideo', () => ({+ listVideoHistory: (...args) => listVideoHistory(...args),+}));++vi.mock('../../services/apiMedia', () => ({+ uploadFile: vi.fn(),+}));++vi.mock('../../utils/fileUpload', () => ({+ readFileAsBase64: vi.fn().mockResolvedValue('ZmFrZQ=='),+ JSON_UPLOAD_MAX_FILE_SIZE: 41 * 1024 * 1024,+}));++vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));++const HISTORY = [+ { id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', filename: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa.mp4', prompt: 'a neon chase', hidden: false },+ { id: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', filename: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb.mp4', prompt: 'a quiet forest walk', hidden: false },+];++describe('GalleryVideoPicker', () => {+ beforeEach(() => {+ listVideoHistory.mockReset();+ listVideoHistory.mockResolvedValue(HISTORY);+ });++ it('does not fetch when closed', () => {+ render(<GalleryVideoPicker open={false} onClose={vi.fn()} onSelect={vi.fn()} />);+ expect(listVideoHistory).not.toHaveBeenCalled();+ });++ it('lists videos on open and selects one', async () => {+ const onSelect = vi.fn();+ const onClose = vi.fn();+ render(<GalleryVideoPicker open onClose={onClose} onSelect={onSelect} />);+ await waitFor(() => expect(screen.getByText('a neon chase')).toBeInTheDocument());+ const tile = screen.getByText('a neon chase').closest('.bg-port-card').querySelector('button');+ fireEvent.click(tile);+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',+ }));+ expect(onClose).toHaveBeenCalled();+ });+});diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex ec0f6eabf3..4bbb4b5939 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -17,6 +17,7 @@ import MediaPreview from '../components/media/MediaPreview';import FavoritesFilterChip from '../components/media/FavoritesFilterChip';import StylePresetPicker from '../components/media/StylePresetPicker';import PromptEnhancer from '../components/media/PromptEnhancer';+import PromptFromMedia from '../components/media/PromptFromMedia';import BackendChipStrip from '../components/media/BackendChipStrip';import { normalizeImage } from '../components/media/normalize';import { RUNNER_FAMILIES, loraCompatKey } from '../lib/runnerFamilies';@@ -1226,6 +1227,13 @@ export default function ImageGen() {renderConfig={{ stylePreset: stylePreset?.id, mode: effectiveMode }}disabled={statusLoading}/>+ <PromptFromMedia+ kindDefault="both"+ applyKind="image"+ setPrompt={setPrompt}+ setNegativePrompt={setNegativePrompt}+ disabled={statusLoading}+ />{flux2Issue === 'venv' && (<div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex aaa446ad08..5620c59d06 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -57,6 +57,7 @@ import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';import MediaPreview from '../components/media/MediaPreview';import StylePresetPicker from '../components/media/StylePresetPicker';import PromptEnhancer from '../components/media/PromptEnhancer';+import PromptFromMedia from '../components/media/PromptFromMedia';import { normalizeVideo } from '../components/media/normalize';import {Film, Sparkles, Settings as SettingsIcon, RefreshCw, AlertTriangle,@@ -932,6 +933,13 @@ export default function VideoGen() {renderConfig={{ stylePreset: stylePreset?.id, mode, model: modelId }}disabled={generating}/>+ <PromptFromMedia+ kindDefault="both"+ applyKind="video"+ setPrompt={setPrompt}+ setNegativePrompt={setNegativePrompt}+ disabled={generating}+ />{mode === 'fflf' && keyframesSupported && (<KeyframePaneldiff --git a/client/src/pages/VideoGen.terms.test.jsx b/client/src/pages/VideoGen.terms.test.jsxindex d464765abd..1947412a87 100644--- a/client/src/pages/VideoGen.terms.test.jsx+++ b/client/src/pages/VideoGen.terms.test.jsx@@ -80,8 +80,11 @@ vi.mock('../services/api', () => ({// provider list from a mount effect. Unmocked it throws out of a passive// effect — the tests still pass, but the unhandled rejection fails the run.getProviders: vi.fn(async () => ({ providers: [] })),+ getVisionModels: vi.fn(async () => ({ models: [] })),}));+vi.mock('../components/media/PromptFromMedia', () => ({ default: () => null }));+vi.mock('../hooks/useModelDownloadStatus', () => ({TEXT_ENCODER_DOWNLOAD_ID: '__text_encoder__',useModelDownloadStatus: () => ({diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 6c6d043331..5ffa124311 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -95,7 +95,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiImageVideo.js` | Image-gen local backend extras (gallery, models, LoRAs, cancel, delete). || `apiLoraTraining.js` | Character LoRA training — datasets (CRUD, upload, generate, slice, caption), training runs (start/list/cancel/delete + status), character→LoRA link lookup. || `apiMedia.js` | Screenshots + media assets. Also owns the multi-file upload orchestration — `processScreenshotUploads` / `processAttachmentUploads` and their single-file variants (`uploadScreenshotFile` / `uploadAttachmentFile`) — moved from `utils/fileUpload.js` since they perform network I/O, not pure transforms. `utils/fileUpload.js` keeps only the pure helpers/constants and no longer re-exports these. |-| `apiMediaJobs.js` | Media generation job tracking. |+| `apiMediaJobs.js` | Media generation job tracking + `refineMediaPrompt` / `promptFromMedia` (vision reverse-prompt). || `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). || `apiGames.js` | Game studio records, managed-app binding, reusable sprite/music bindings, deterministic asset-bundle compilation/integrity preflight, and AI feedback history. |diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.jsindex a4814c78c4..d2bb6b1885 100644--- a/client/src/services/apiMediaJobs.js+++ b/client/src/services/apiMediaJobs.js@@ -44,3 +44,12 @@ export const refineMediaPrompt = (data) => request('/media-jobs/refine-prompt',method: 'POST',body: JSON.stringify(data),});++// Reverse-engineer an image-gen and/or video-gen prompt from a gallery still,+// gallery clip, or generic upload. `data` is `{ sourceKind, filename?, videoId?,+// targets, providerId, model?, effort? }`.+export const promptFromMedia = (data, options) => request('/media-jobs/prompt-from-media', {+ method: 'POST',+ body: JSON.stringify(data),+ ...options,+});diff --git a/client/src/utils/providers.js b/client/src/utils/providers.jsindex e2e3ecb578..7bc3dee6ae 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -451,6 +451,19 @@ export const isVisionModel = (id) =>// Mirror of VISION_RE in server/lib/localModelHeuristics.js — keep in lockstep./(?:^|[-_/:])vision(?:[-_/:.]|$)|(?:^|[-_/:])vl(?:\d|[-_/:.]|$)|qwen[\d.]*-?vl|(?:^|[-_/:])gemma-?[34]|llava|bakllava|moondream|minicpm-?v|pixtral|smolvlm|internvl|cogvlm|glm-?4v|phi-?3\.5?-vision|phi-?4-multimodal|got-ocr|idefics|fuyu|paligemma|kosmos|nanollava/i.test(id);+/**+ * Whether a CLI-type provider can read an image file (its CLI accepts a+ * vision attachment). Mirror of `isVisionCapableCliProvider` in+ * server/lib/localModelHeuristics.js — keyed on command basename so a+ * renamed/path-configured Claude or Codex still qualifies. API providers+ * return false here; use `visionLocalModelFilter` for their model lists.+ * @param {{type?:string, command?:string}|null|undefined} provider+ * @returns {boolean}+ */+export const isVisionCapableCliProvider = (provider) =>+ provider?.type === 'cli'+ && (commandBasename(provider.command) === 'codex' || commandBasename(provider.command) === 'claude');+/*** Tool-use (function-calling) capable model detector — mirror of `isToolUseModel`* in server/lib/localModelHeuristics.js (and the TOOL_USE_RE inlined indiff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex 619424c4e3..c53d8f8d6b 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -12,6 +12,7 @@ import {filterGenerationModels,isEmbeddingModel,isVisionModel,+ isVisionCapableCliProvider,visionLocalModelFilter,isToolUseModel,localToolUseHint,@@ -592,6 +593,21 @@ describe('isVisionModel (mirror of server localModelHeuristics)', () => {});});+describe('isVisionCapableCliProvider', () => {+ it('accepts Claude and Codex CLIs, including a path-configured command', () => {+ expect(isVisionCapableCliProvider({ type: 'cli', command: 'codex' })).toBe(true);+ expect(isVisionCapableCliProvider({ type: 'cli', command: 'claude' })).toBe(true);+ expect(isVisionCapableCliProvider({ type: 'cli', command: '/opt/homebrew/bin/claude' })).toBe(true);+ });++ it('rejects API providers and non-vision CLIs', () => {+ expect(isVisionCapableCliProvider({ type: 'api', command: 'codex' })).toBe(false);+ expect(isVisionCapableCliProvider({ type: 'cli', command: 'agy' })).toBe(false);+ expect(isVisionCapableCliProvider({ type: 'tui', command: 'claude' })).toBe(false);+ expect(isVisionCapableCliProvider(null)).toBe(false);+ });+});+describe('isToolUseModel (mirror of server localModelHeuristics)', () => {it('flags known tool-use-capable model ids', () => {for (const id of [diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.jsindex 6e19bcc97d..51c12be049 100644--- a/server/routes/mediaJobs.js+++ b/server/routes/mediaJobs.js@@ -11,6 +11,7 @@ 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';+import { promptFromMedia } from '../services/mediaPromptFromMedia.js';import { CODEX_EFFORT_LEVELS } from '../lib/providerModels.js';const router = Router();@@ -66,6 +67,32 @@ const refinePromptSchema = z.object({.optional(),});+const optionalTrimmed = z.string().max(256).optional().transform((s) => {+ const v = (s ?? '').trim();+ return v.length > 0 ? v : undefined;+});++const promptFromMediaSchema = z.object({+ sourceKind: z.enum(['image', 'video', 'upload']),+ filename: z.string().trim().min(1).max(256).optional(),+ videoId: z.string().trim().min(1).max(64).optional(),+ targets: z.array(z.enum(['image', 'video'])).min(1).max(2)+ .refine((arr) => new Set(arr).size === arr.length, { message: 'targets must be unique' }),+ providerId: z.string().trim().min(1).max(128),+ model: optionalTrimmed,+ effort: z.string().max(64).optional().transform((s) => {+ const v = (s ?? '').trim();+ return v.length > 0 ? v : undefined;+ }),+}).superRefine((data, ctx) => {+ if (data.sourceKind === 'video' && !data.videoId) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'videoId is required for a gallery video', path: ['videoId'] });+ }+ if ((data.sourceKind === 'image' || data.sourceKind === 'upload') && !data.filename) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'filename is required', path: ['filename'] });+ }+});+// 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@@ -148,6 +175,11 @@ router.post('/refine-prompt', asyncHandler(async (req, res) => {res.json(await refineMediaPrompt(data));}));+router.post('/prompt-from-media', asyncHandler(async (req, res) => {+ const data = validateRequest(promptFromMediaSchema, req.body);+ res.json(await promptFromMedia(data));+}));+router.get('/:id', asyncHandler(async (req, res) => {const job = getJob(req.params.id);if (!job) {diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.jsindex 2da9170f8c..843b7e6145 100644--- a/server/routes/mediaJobs.test.js+++ b/server/routes/mediaJobs.test.js@@ -73,6 +73,15 @@ describe('mediaJobs routes', () => {expect(r.body.params.uploadedTempPath).toBeUndefined();});+ it('POST /prompt-from-media 400s when the image source has no filename', async () => {+ const r = await request(makeApp()).post('/api/media-jobs/prompt-from-media').send({+ sourceKind: 'image',+ targets: ['image'],+ providerId: 'openai',+ });+ expect(r.status).toBe(400);+ });+it('POST /:id/retry 404s for unknown id', async () => {const r = await request(makeApp()).post('/api/media-jobs/nope/retry').send({});expect(r.status).toBe(404);diff --git a/server/services/mediaPromptFromMedia.js b/server/services/mediaPromptFromMedia.jsnew file mode 100644index 0000000000..f66a2da2fc--- /dev/null+++ b/server/services/mediaPromptFromMedia.js@@ -0,0 +1,328 @@+/**+ * Reverse-engineer an image-gen and/or video-gen prompt from a still or clip.+ *+ * One vision call, any vision-capable provider:+ * - API (Ollama VLM, LM Studio, OpenAI-compatible) → runPromptThroughProvider+ * with screenshots + effort+ * - Vision CLI (codex / claude) → describeImagesFromPaths with the same+ * files + effort+ *+ * Source resolution:+ * - gallery image → PATHS.images basename+ * - gallery video → ffmpeg-sampled frames under PATHS.video-thumbnails+ * - generic upload → PATHS.uploads (image as-is, video sampled the same way)+ */++import { existsSync } from 'fs';+import { extname, join } from 'path';+import { randomUUID } from 'crypto';++import { ServerError } from '../lib/errorHandler.js';+import { extractJson } from '../lib/jsonExtract.js';+import { PATHS, resolveGalleryImage } from '../lib/fileUtils.js';+import { extractEvaluationFrames, safeUnder } from '../lib/ffmpeg.js';+import { isVisionCapableCliProvider } from '../lib/localModelHeuristics.js';+import {+ assertVisionRunUsedImages,+ resolveEffectiveModel,+ runPromptThroughProvider,+} from '../lib/promptRunner.js';+import { getProviderById } from './providers.js';+import { loadHistory } from './videoGen/history.js';+import { describeImagesFromPaths } from './visionCli.js';++const MAX_PROMPT_LEN = 8000;+const MAX_REASON_LEN = 1200;+const MAX_FRAMES = 5;+const VISION_TIMEOUT_MS = 180000;+const VIDEO_ID_RE = /^[a-f0-9-]{36}$/i;+const IMAGE_EXT_RE = /\.(png|jpe?g|gif|webp)$/i;+const VIDEO_EXT_RE = /\.(mp4|webm|mov|m4v|mkv)$/i;++const trimString = (value, max = MAX_PROMPT_LEN) =>+ typeof value === 'string' ? value.trim().slice(0, max) : '';++const isPlaceholderPrompt = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(s);++export const PROMPT_FROM_MEDIA_TARGETS = Object.freeze(['image', 'video']);++/**+ * Build the vision prompt. `targets` decides which JSON fields the model+ * must fill; `mediaKind` + `frameCount` tell it whether it's looking at a+ * still or a chronological frame set.+ */+export function buildPromptFromMediaPrompt({ targets, mediaKind, frameCount }) {+ const wantImage = targets.includes('image');+ const wantVideo = targets.includes('video');+ const lookingAt = mediaKind === 'video'+ ? (frameCount > 1+ ? `${frameCount} frames sampled in chronological order from a short video`+ : 'a representative frame from a short video')+ : 'a still image';++ const fields = [];+ if (wantImage) {+ fields.push(+ ' "imagePrompt": "<full ready-to-render image-generation prompt>",',+ ' "imageNegativePrompt": "<what an image model should avoid, or empty string>",',+ );+ }+ if (wantVideo) {+ fields.push(+ ' "videoPrompt": "<full ready-to-render video-generation prompt, including motion>",',+ ' "videoNegativePrompt": "<what a video model should avoid, or empty string>",',+ );+ }+ fields.push(' "rationale": "<one concise sentence about the look and, if video, the motion>"');++ const rules = [+ '- Output ONLY valid JSON. Replace every <…> with real content; do NOT emit the literal angle-bracket text.',+ '- Each prompt field must be the COMPLETE ready-to-render text, paragraph-style — not a summary, not a caption of the file, not a list of changes.',+ '- Describe what is actually visible: subject, setting, materials, lighting, color, composition, camera, mood, style.',+ '- Do not invent brands, logos, or named characters that are not visible.',+ ];+ if (wantImage) {+ rules.push('- imagePrompt: a still-image prompt (composition, lighting, textures, lens/look). No motion language.');+ }+ if (wantVideo) {+ rules.push('- videoPrompt: a moving-image prompt. Include subject action, camera move, pacing, and how light or atmosphere changes across the clip.');+ if (mediaKind === 'video' && frameCount > 1) {+ rules.push('- The frames are chronological. Infer motion from what changes between them; do not describe each frame separately.');+ }+ }++ return `You are a senior prompt engineer for generative image and video models.++You are looking at ${lookingAt}. Write the prompt(s) that would make a generator produce something like this — not a caption of the file, the actual render prompt.++Return ONLY valid JSON in this schema:+{+${fields.join('\n')}+}++Rules:+${rules.join('\n')}`;+}++/**+ * Parse the model's JSON into the requested prompt fields. Walks balanced+ * blocks so a CLI banner / schema echo does not win over the real object.+ */+export function parsePromptFromMediaJson(raw, targets) {+ const wantImage = targets.includes('image');+ const wantVideo = targets.includes('video');+ const { value, lastError } = extractJson(String(raw || ''), {+ shapePredicate: (v) => {+ if (!v || typeof v !== 'object') return false;+ if (wantImage && (typeof v.imagePrompt !== 'string' || isPlaceholderPrompt(v.imagePrompt))) return false;+ if (wantVideo && (typeof v.videoPrompt !== 'string' || isPlaceholderPrompt(v.videoPrompt))) return false;+ return (wantImage ? trimString(v.imagePrompt) : true) && (wantVideo ? trimString(v.videoPrompt) : true);+ },+ });+ if (!value) {+ throw new Error(lastError?.message || 'Invalid JSON in AI response');+ }++ const imagePrompt = wantImage ? trimString(value.imagePrompt) : '';+ const videoPrompt = wantVideo ? trimString(value.videoPrompt) : '';+ if (wantImage && (isPlaceholderPrompt(value.imagePrompt) || !imagePrompt)) {+ throw new Error('LLM returned an empty image prompt');+ }+ if (wantVideo && (isPlaceholderPrompt(value.videoPrompt) || !videoPrompt)) {+ throw new Error('LLM returned an empty video prompt');+ }++ return {+ ...(wantImage ? {+ imagePrompt,+ imageNegativePrompt: trimString(value.imageNegativePrompt),+ } : {}),+ ...(wantVideo ? {+ videoPrompt,+ videoNegativePrompt: trimString(value.videoNegativePrompt),+ } : {}),+ rationale: trimString(value.rationale, MAX_REASON_LEN),+ };+}++function assertVisionProvider(provider) {+ 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' },+ );+ }+ if (provider.type === 'api') return 'api';+ if (isVisionCapableCliProvider(provider)) return 'cli';+ throw new ServerError(+ `Provider "${provider.name || provider.id}" cannot read images. Pick a vision-capable API model (Ollama/LM Studio VLM, gpt-4o, grok, …) or a vision CLI (Claude Code, Codex).`,+ { status: 400, code: 'NOT_VISION_CAPABLE' },+ );+}++async function resolveImagePath(filename) {+ const imagePath = resolveGalleryImage(filename);+ if (!imagePath) {+ throw new ServerError(`Gallery image not found: ${filename}`, {+ status: 400,+ code: 'GALLERY_IMAGE_NOT_FOUND',+ });+ }+ return { mediaKind: 'image', screenshots: [imagePath] };+}++async function sampleVideoFrames(videoPath, extractId) {+ const names = await extractEvaluationFrames(videoPath, extractId, MAX_FRAMES);+ const screenshots = names+ .map((name) => join(PATHS.videoThumbnails, name))+ .filter((p) => existsSync(p));+ if (!screenshots.length) {+ throw new ServerError(+ 'Could not extract frames from this video (is ffmpeg installed?)',+ { status: 502, code: 'VIDEO_FRAMES_FAILED' },+ );+ }+ return { mediaKind: 'video', screenshots };+}++async function resolveVideoSource(videoId) {+ if (!VIDEO_ID_RE.test(videoId)) {+ throw new ServerError('Invalid video id', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const history = await loadHistory();+ const item = (Array.isArray(history) ? history : []).find((h) => h.id === videoId);+ if (!item) {+ throw new ServerError('Video not found', { status: 404, code: 'NOT_FOUND' });+ }+ const videoPath = safeUnder(PATHS.videos, item.filename);+ if (!videoPath || !existsSync(videoPath)) {+ throw new ServerError('Video file not found on disk', { status: 404, code: 'NOT_FOUND' });+ }+ return sampleVideoFrames(videoPath, `pfm-${videoId}`);+}++async function resolveUploadSource(filename) {+ const uploadPath = safeUnder(PATHS.uploads, filename);+ if (!uploadPath || !existsSync(uploadPath)) {+ throw new ServerError(`Upload not found: ${filename}`, {+ status: 400,+ code: 'UPLOAD_NOT_FOUND',+ });+ }+ if (IMAGE_EXT_RE.test(filename)) {+ return { mediaKind: 'image', screenshots: [uploadPath] };+ }+ if (VIDEO_EXT_RE.test(filename)) {+ return sampleVideoFrames(uploadPath, `pfm-up-${randomUUID()}`);+ }+ throw new ServerError(+ `Unsupported upload type "${extname(filename) || filename}" — use an image or video`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+}++async function resolvePromptFromMediaSource({ sourceKind, filename, videoId }) {+ if (sourceKind === 'image') return resolveImagePath(filename);+ if (sourceKind === 'video') return resolveVideoSource(videoId);+ if (sourceKind === 'upload') return resolveUploadSource(filename);+ throw new ServerError(`Unsupported sourceKind "${sourceKind}"`, {+ status: 400,+ code: 'VALIDATION_ERROR',+ });+}++async function runVision({ provider, kind, model, effort, prompt, screenshots }) {+ const timeout = provider.timeout || VISION_TIMEOUT_MS;+ if (kind === 'cli') {+ const result = await describeImagesFromPaths({+ provider,+ imagePaths: screenshots,+ prompt,+ model,+ effort,+ timeout,+ });+ return { text: result.text, model, ranProvider: provider };+ }++ const result = await runPromptThroughProvider({+ provider,+ prompt,+ source: 'media-prompt-from-media',+ model,+ effort,+ screenshots,+ timeout,+ }).catch((err) => {+ throw new ServerError(err?.message || 'Vision prompt failed', {+ status: 502,+ code: 'PROMPT_FROM_MEDIA_FAILED',+ });+ });+ const ranProvider = assertVisionRunUsedImages(result, provider);+ return { text: result.text, model: result.model || model, ranProvider };+}++export async function promptFromMedia({+ sourceKind,+ filename,+ videoId,+ targets,+ providerId,+ model,+ effort,+}) {+ const wanted = [...new Set((Array.isArray(targets) ? targets : []).filter((t) => PROMPT_FROM_MEDIA_TARGETS.includes(t)))];+ if (!wanted.length) {+ throw new ServerError('Select at least one of image or video prompt', {+ status: 400,+ code: 'VALIDATION_ERROR',+ });+ }++ const provider = await getProviderById(providerId);+ const kind = assertVisionProvider(provider);+ const selectedModel = resolveEffectiveModel(provider, model) || '';+ if (!selectedModel && provider.type === 'api') {+ throw new ServerError('Model is required', { status: 400, code: 'MODEL_REQUIRED' });+ }++ const { mediaKind, screenshots } = await resolvePromptFromMediaSource({+ sourceKind, filename, videoId,+ });++ const llmPrompt = buildPromptFromMediaPrompt({+ targets: wanted,+ mediaKind,+ frameCount: screenshots.length,+ });++ const { text, model: ranModel, ranProvider } = await runVision({+ provider,+ kind,+ model: selectedModel || undefined,+ effort,+ prompt: llmPrompt,+ screenshots,+ });++ let parsed;+ try {+ parsed = parsePromptFromMediaJson(text || '', wanted);+ } catch (e) {+ console.warn(`⚠️ media-prompt-from-media [${provider.id}/${selectedModel || 'default'}] parse failed: ${e.message} (response size: ${(text || '').length} chars)`);+ throw new ServerError(e.message, { status: 502, code: 'PROMPT_FROM_MEDIA_BAD_JSON' });+ }++ return {+ ...parsed,+ mediaKind,+ frameCount: screenshots.length,+ targets: wanted,+ providerId: ranProvider.id || provider.id,+ model: ranModel || selectedModel,+ };+}diff --git a/server/services/mediaPromptFromMedia.test.js b/server/services/mediaPromptFromMedia.test.jsnew file mode 100644index 0000000000..dfbc89f473--- /dev/null+++ b/server/services/mediaPromptFromMedia.test.js@@ -0,0 +1,221 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('./providers.js', () => ({+ getProviderById: vi.fn(),+}));++vi.mock('../lib/promptRunner.js', () => ({+ resolveEffectiveModel: vi.fn((_provider, model) => model || 'default-model'),+ runPromptThroughProvider: vi.fn(),+ assertVisionRunUsedImages: vi.fn((_result, provider) => provider),+}));++vi.mock('./visionCli.js', () => ({+ describeImagesFromPaths: vi.fn(),+}));++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ resolveGalleryImage: vi.fn(),+ PATHS: {+ ...actual.PATHS,+ images: '/mock/images',+ videos: '/mock/videos',+ uploads: '/mock/uploads',+ videoThumbnails: '/mock/video-thumbnails',+ },+ };+});++vi.mock('../lib/ffmpeg.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ extractEvaluationFrames: vi.fn(),+ safeUnder: vi.fn((root, name) => (name && !String(name).includes('..') ? `${root}/${name}` : null)),+ };+});++vi.mock('./videoGen/history.js', () => ({+ loadHistory: vi.fn(),+}));++vi.mock('fs', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ existsSync: vi.fn(() => true),+ };+});++const providers = await import('./providers.js');+const promptRunner = await import('../lib/promptRunner.js');+const visionCli = await import('./visionCli.js');+const fileUtils = await import('../lib/fileUtils.js');+const ffmpeg = await import('../lib/ffmpeg.js');+const history = await import('./videoGen/history.js');+const {+ buildPromptFromMediaPrompt,+ parsePromptFromMediaJson,+ promptFromMedia,+} = await import('./mediaPromptFromMedia.js');++const API_PROVIDER = {+ id: 'openai',+ name: 'OpenAI',+ type: 'api',+ enabled: true,+ defaultModel: 'gpt-4o',+};++const CLI_PROVIDER = {+ id: 'codex',+ name: 'Codex',+ type: 'cli',+ command: 'codex',+ enabled: true,+ defaultModel: 'gpt-5',+};++const JSON_BOTH = JSON.stringify({+ imagePrompt: 'a painted wizard in moonlight',+ imageNegativePrompt: 'blurry',+ videoPrompt: 'the wizard turns as the camera dollies in',+ videoNegativePrompt: 'jitter',+ rationale: 'Moonlit painted look with a slow push-in.',+});++beforeEach(() => {+ vi.clearAllMocks();+ fileUtils.resolveGalleryImage.mockReturnValue('/mock/images/still.png');+ ffmpeg.extractEvaluationFrames.mockResolvedValue(['pfm-vid-f1.jpg', 'pfm-vid-f2.jpg']);+ history.loadHistory.mockResolvedValue([+ { id: '11111111-1111-4111-8111-111111111111', filename: 'clip.mp4' },+ ]);+});++describe('buildPromptFromMediaPrompt', () => {+ it('asks only for image fields when that is the target', () => {+ const prompt = buildPromptFromMediaPrompt({ targets: ['image'], mediaKind: 'image', frameCount: 1 });+ expect(prompt).toContain('imagePrompt');+ expect(prompt).not.toContain('videoPrompt');+ expect(prompt).toContain('still image');+ expect(prompt).toContain('No motion language');+ });++ it('asks for motion language and names the frame count for a video', () => {+ const prompt = buildPromptFromMediaPrompt({ targets: ['video'], mediaKind: 'video', frameCount: 5 });+ expect(prompt).toContain('videoPrompt');+ expect(prompt).not.toContain('imagePrompt');+ expect(prompt).toContain('5 frames');+ expect(prompt).toContain('chronological');+ });+});++describe('parsePromptFromMediaJson', () => {+ it('extracts both prompts and skips a placeholder echo', () => {+ const raw = `here you go\n${JSON_BOTH}`;+ const parsed = parsePromptFromMediaJson(raw, ['image', 'video']);+ expect(parsed.imagePrompt).toBe('a painted wizard in moonlight');+ expect(parsed.videoPrompt).toContain('dollies');+ expect(parsed.rationale).toMatch(/Moonlit/);+ });++ it('rejects a schema-placeholder image prompt', () => {+ expect(() => parsePromptFromMediaJson(JSON.stringify({+ imagePrompt: '<full ready-to-render image-generation prompt>',+ }), ['image'])).toThrow(/Invalid JSON|empty/i);+ });+});++describe('promptFromMedia', () => {+ it('sends a gallery still through the API vision runner with effort', async () => {+ providers.getProviderById.mockResolvedValue(API_PROVIDER);+ promptRunner.runPromptThroughProvider.mockResolvedValue({+ text: JSON_BOTH,+ model: 'gpt-4o',+ provider: API_PROVIDER,+ });++ const result = await promptFromMedia({+ sourceKind: 'image',+ filename: 'still.png',+ targets: ['image', 'video'],+ providerId: 'openai',+ model: 'gpt-4o',+ effort: 'high',+ });++ expect(fileUtils.resolveGalleryImage).toHaveBeenCalledWith('still.png');+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({+ provider: API_PROVIDER,+ model: 'gpt-4o',+ effort: 'high',+ screenshots: ['/mock/images/still.png'],+ source: 'media-prompt-from-media',+ }));+ expect(result.imagePrompt).toContain('wizard');+ expect(result.videoPrompt).toContain('dollies');+ expect(result.mediaKind).toBe('image');+ expect(result.providerId).toBe('openai');+ });++ it('samples gallery-video frames and uses the CLI vision path for Codex', async () => {+ providers.getProviderById.mockResolvedValue(CLI_PROVIDER);+ visionCli.describeImagesFromPaths.mockResolvedValue({ text: JSON_BOTH });++ const result = await promptFromMedia({+ sourceKind: 'video',+ videoId: '11111111-1111-4111-8111-111111111111',+ targets: ['video'],+ providerId: 'codex',+ model: 'gpt-5',+ effort: 'medium',+ });++ expect(ffmpeg.extractEvaluationFrames).toHaveBeenCalled();+ expect(visionCli.describeImagesFromPaths).toHaveBeenCalledWith(expect.objectContaining({+ provider: CLI_PROVIDER,+ model: 'gpt-5',+ effort: 'medium',+ imagePaths: [+ '/mock/video-thumbnails/pfm-vid-f1.jpg',+ '/mock/video-thumbnails/pfm-vid-f2.jpg',+ ],+ }));+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();+ expect(result.videoPrompt).toContain('dollies');+ expect(result.imagePrompt).toBeUndefined();+ expect(result.mediaKind).toBe('video');+ expect(result.frameCount).toBe(2);+ });++ it('rejects a text-only CLI that cannot see images', async () => {+ providers.getProviderById.mockResolvedValue({+ id: 'opencode',+ name: 'OpenCode',+ type: 'cli',+ command: 'opencode',+ enabled: true,+ });++ await expect(promptFromMedia({+ sourceKind: 'image',+ filename: 'still.png',+ targets: ['image'],+ providerId: 'opencode',+ })).rejects.toMatchObject({ code: 'NOT_VISION_CAPABLE', status: 400 });+ });++ it('404s a missing provider instead of silently swapping', async () => {+ providers.getProviderById.mockResolvedValue(null);+ await expect(promptFromMedia({+ sourceKind: 'image',+ filename: 'still.png',+ targets: ['image'],+ providerId: 'missing',+ })).rejects.toMatchObject({ code: 'PROVIDER_NOT_FOUND', status: 404 });+ });+});diff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex 65850d8c15..251d2c3433 100644--- a/server/services/visionCli.js+++ b/server/services/visionCli.js@@ -24,11 +24,12 @@*/import { spawn } from 'child_process';-import { writeFile, rm, mkdtemp } from 'fs/promises';+import { writeFile, rm, mkdtemp, copyFile } from 'fs/promises';+import { existsSync } from 'fs';import { tmpdir } from 'os';-import { join } from 'path';+import { extname, join } from 'path';import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';-import { resolveCliModel, isCodexProvider, buildCodexStartupArgs } from '../lib/providerModels.js';+import { resolveCliModel, isCodexProvider, buildCodexStartupArgs, buildEffortArgs } from '../lib/providerModels.js';import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';@@ -57,13 +58,24 @@ export function decodeImageDataUrl(dataUrl) {/*** Build the spawn invocation (command, argv, stdin, cwd) for a vision CLI call.- * `imageDir` is the temp dir holding `IMAGE_BASENAME`. Pure — exported so the+ * `imageDir` is the temp dir holding the image file(s). Pure — exported so the* per-provider attachment convention is unit-testable without spawning.*+ * `opts.imageNames` defaults to `[IMAGE_BASENAME]` (the single-file caption+ * path). A multi-frame call passes `vision-1.jpg`, `vision-2.jpg`, … and the+ * prompt text names them in chronological order.+ *+ * `opts.effort` is a per-call reasoning-effort override (same contract as+ * `runPromptThroughProvider`). Codex gets `-c model_reasoning_effort=…`;+ * Claude/other stdin CLIs inherit it through `buildCliArgs`.+ ** @returns {{ command: string, args: string[], stdin: string|null, cwd: string }}*/-export function buildCliVisionInvocation(provider, model, imageDir, prompt) {- const imagePath = join(imageDir, IMAGE_BASENAME);+export function buildCliVisionInvocation(provider, model, imageDir, prompt, opts = {}) {+ const imageNames = Array.isArray(opts.imageNames) && opts.imageNames.length+ ? opts.imageNames+ : [IMAGE_BASENAME];+ const effort = opts.effort || provider?.effort || null;if (isCodexProvider(provider)) {const baseArgs = Array.isArray(provider.args) ? provider.args : [];const hasExec = baseArgs.includes('exec');@@ -72,6 +84,7 @@ export function buildCliVisionInvocation(provider, model, imageDir, prompt) {// sentinel verbatim makes `codex exec` try a non-existent model. Same// resolution buildCliArgs applies on the normal CLI run path.const codexModel = resolveCliModel(model);+ const imageFlags = imageNames.flatMap((name) => ['-i', join(imageDir, name)]);const args = [...(hasExec ? baseArgs : [...baseArgs, 'exec']),'--skip-git-repo-check',@@ -80,7 +93,8 @@ export function buildCliVisionInvocation(provider, model, imageDir, prompt) {// or an unattended `brew upgrade` would blow the caption call. No-op when// the user pinned the key in provider.args....buildCodexStartupArgs(baseArgs),- '-i', imagePath,+ ...imageFlags,+ ...buildEffortArgs(effort, provider, baseArgs, model),...(codexModel ? ['-m', String(codexModel)] : []),prompt,];@@ -88,10 +102,13 @@ export function buildCliVisionInvocation(provider, model, imageDir, prompt) {}// Claude Code (and any other stdin CLI): buildCliArgs gives the `-p -`- // stdin convention + `--model`; the image rides in the spawn cwd so the CLI- // can open it by basename with its file tools.- const args = buildCliArgs({ ...provider, defaultModel: model });- const stdin = `${prompt}\n\nThe image to analyze is the file "${IMAGE_BASENAME}" in the current directory.`;+ // stdin convention + `--model` + optional `--effort`; the image(s) ride in+ // the spawn cwd so the CLI can open them by basename with its file tools.+ const args = buildCliArgs({ ...provider, defaultModel: model, effort });+ const listed = imageNames.map((n) => `"${n}"`).join(', ');+ const stdin = imageNames.length === 1+ ? `${prompt}\n\nThe image to analyze is the file ${listed} in the current directory.`+ : `${prompt}\n\nThe images to analyze are the files ${listed} in the current directory, in chronological order.`;return { command: provider.command, args, stdin, cwd: imageDir };}@@ -104,12 +121,13 @@ export function buildCliVisionInvocation(provider, model, imageDir, prompt) {* @param {string} opts.dataUrl — base64 image data URL* @param {string} opts.prompt — what to ask about the image* @param {string} [opts.model] — model override (defaults to provider.defaultModel)+ * @param {string} [opts.effort] — reasoning-effort override for capable CLIs* @param {number} [opts.timeout]* @param {Function} [opts.spawnImpl] — child_process.spawn replacement (tests)* @returns {Promise<{ text:string, finishReason:null, usage:null, reasoning:string }>}*/export async function describeImageViaCli({- provider, dataUrl, prompt, model, timeout = CLI_VISION_TIMEOUT_MS, spawnImpl = spawn,+ provider, dataUrl, prompt, model, effort, timeout = CLI_VISION_TIMEOUT_MS, spawnImpl = spawn,}) {const visionModel = model || provider?.defaultModel || null;const bytes = decodeImageDataUrl(dataUrl);@@ -121,94 +139,155 @@ export async function describeImageViaCli({let cleanupPromptFile = () => {};try {await writeFile(join(dir, IMAGE_BASENAME), bytes);- const { command, args, stdin, cwd } = buildCliVisionInvocation(provider, visionModel, dir, prompt);- // Deliver the prompt per provider convention: antigravity as the --print- // VALUE (agy doesn't read stdin); grok's --prompt-file /dev/stdin via stdin- // (POSIX) / temp file (Windows); every other provider via stdin.- const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup } = prepareCliPrompt(command, args, stdin);- cleanupPromptFile = cleanup;-- // Shared composition (provider.envVars + OpenCode models map + PWD pin +- // CLAUDECODE strip) — see buildCliChildEnv. The PWD pin is load-bearing- // here: the non-codex branch above tells the CLI the image is "in the- // current directory", and the vision provider is user-configurable — so on- // OpenCode (which resolves its project root from PWD) a stale value both- // hides vision-input.png and turns the CLI loose in the PortOS checkout.- // Routing through the shared builder also brings the OpenCode declared-models- // map here for the first time, so the `--model` buildCliVisionInvocation- // injects isn't rejected by an Ollama-backed OpenCode provider (the #2190- // fix, previously applied only at the runner/agent sites). No `guard` —- // vision is a one-shot describe, not an agent.- const childEnv = buildCliChildEnv({ provider, model: visionModel, cwd });-- // npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap- // (cmd.exe /c) instead of enabling a shell. This matters even more here- // than at other call sites: the codex branch of buildCliVisionInvocation- // puts the free-text `prompt` directly into `args` (see above), and- // shell:true + an args array does NOT escape arguments (DEP0190) — any- // prompt containing a space would silently mis-split into extra shell- // tokens, corrupting or shell-injecting the invocation. The cmd.exe- // wrapper instead relies on Node's own correct non-shell argv escaping,- // which DOES preserve spaces within each arg as a single token. Resolved- // against `childEnv` so a provider-configured PATH override is honored.- // See resolveWindowsExecutable/prepareWindowsSafeSpawn in- // server/lib/bufferedSpawn.js.- const resolvedCommand = resolveWindowsExecutable(command, undefined, childEnv) || command;- const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, deliveredArgs);-- const text = await new Promise((resolve, reject) => {- const child = spawnImpl(spawnCommand, spawnArgs, {- cwd,- env: childEnv,- windowsHide: true,- stdio: ['pipe', 'pipe', 'pipe'],- });- let out = '';- let err = '';- let killTimer = null;- // On timeout, SIGTERM the child AND reject now — don't wait on `close`. A- // wedged CLI that ignores SIGTERM would otherwise never emit `close`, so- // the promise would hang forever and the temp dir (cleaned in `finally`)- // would leak. Escalate to SIGKILL on a short grace timer.- const timer = timeout > 0 ? setTimeout(() => {- if (!child.killed) killProcessTree(child);- killTimer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 5000);- killTimer?.unref?.();- reject(new Error(`${command} vision call timed out after ${timeout}ms`));- }, timeout) : null;- timer?.unref?.();- const clearTimers = () => { if (timer) clearTimeout(timer); if (killTimer) clearTimeout(killTimer); };-- child.on('error', (e) => { clearTimers(); reject(new Error(`Failed to spawn ${command}: ${e.message}`)); });- child.stdout?.on('data', (d) => { out += d.toString(); });- child.stderr?.on('data', (d) => { err += d.toString(); });- child.on('close', (code) => {- clearTimers();- // `codex exec` prints the whole session transcript (banner, echoed- // prompt, tool sections, `tokens used` footer) to stdout — carve out- // the assistant reply so captioning doesn't persist the transcript as- // the caption. Newer Codex emits the final reply AFTER the `tokens used`- // footer (extractCodexAssistantTail), older versions before it- // (extractCodexAssistant); try tail first, then the legacy extractor,- // both no-ops for non-codex output (tail → null, legacy → input).- if (code === 0) return resolve((extractCodexAssistantTail(out) ?? extractCodexAssistant(out)).trim());- const tail = err.trim().split('\n').slice(-4).join('\n');- reject(new Error(`${command} vision call exited ${code}${tail ? `: ${tail}` : ''}`));- });-- // When grok is delivered via a Windows temp file the prompt is already on- // disk (writePromptToStdin=false) — just close stdin.- if (writePromptToStdin && stdin != null) {- child.stdin?.write(stdin);- child.stdin?.end();- } else {- child.stdin?.end();- }+ const invocation = buildCliVisionInvocation(provider, visionModel, dir, prompt, { effort });+ const text = await runCliVisionSpawn({+ provider, model: visionModel, invocation, timeout, spawnImpl,+ setCleanup: (fn) => { cleanupPromptFile = fn; },});+ return { text, finishReason: null, usage: null, reasoning: '' };+ } finally {+ cleanupPromptFile();+ await rm(dir, { recursive: true, force: true }).catch(() => {});+ }+}++/**+ * Same spawn + diagnostic shape as {@link describeImageViaCli}, but the+ * images are already on disk (gallery stills, extracted video frames).+ * Copies them into a fresh temp dir as `vision-1.ext`… so concurrent calls+ * can't collide, then attaches every file the way the CLI expects.+ *+ * @param {object} opts+ * @param {object} opts.provider+ * @param {string[]} opts.imagePaths — absolute paths the caller already validated+ * @param {string} opts.prompt+ * @param {string} [opts.model]+ * @param {string} [opts.effort]+ * @param {number} [opts.timeout]+ * @param {Function} [opts.spawnImpl]+ * @returns {Promise<{ text:string, finishReason:null, usage:null, reasoning:string }>}+ */+export async function describeImagesFromPaths({+ provider, imagePaths, prompt, model, effort, timeout = CLI_VISION_TIMEOUT_MS, spawnImpl = spawn,+}) {+ const paths = (Array.isArray(imagePaths) ? imagePaths : []).filter((p) => typeof p === 'string' && p);+ if (!paths.length) throw new Error('At least one image path is required');+ for (const p of paths) {+ if (!existsSync(p)) throw new Error(`Vision image not found: ${p}`);+ }+ const visionModel = model || provider?.defaultModel || null;+ const dir = await mkdtemp(join(tmpdir(), 'portos-vision-'));+ let cleanupPromptFile = () => {};+ try {+ const imageNames = [];+ for (let i = 0; i < paths.length; i += 1) {+ const ext = extname(paths[i]) || '.jpg';+ const name = `vision-${i + 1}${ext}`;+ await copyFile(paths[i], join(dir, name));+ imageNames.push(name);+ }+ const invocation = buildCliVisionInvocation(+ provider, visionModel, dir, prompt, { imageNames, effort },+ );+ const text = await runCliVisionSpawn({+ provider, model: visionModel, invocation, timeout, spawnImpl,+ setCleanup: (fn) => { cleanupPromptFile = fn; },+ });return { text, finishReason: null, usage: null, reasoning: '' };} finally {cleanupPromptFile();await rm(dir, { recursive: true, force: true }).catch(() => {});}}++// Shared spawn for the two public CLI-vision entry points. `setCleanup` receives+// the prompt-file cleanup from prepareCliPrompt (Grok-on-Windows temp file).+async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnImpl, setCleanup }) {+ const { command, args, stdin, cwd } = invocation;+ // Deliver the prompt per provider convention: antigravity as the --print+ // VALUE (agy doesn't read stdin); grok's --prompt-file /dev/stdin via stdin+ // (POSIX) / temp file (Windows); every other provider via stdin.+ const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup } = prepareCliPrompt(command, args, stdin);+ setCleanup?.(cleanup);++ // Shared composition (provider.envVars + OpenCode models map + PWD pin ++ // CLAUDECODE strip) — see buildCliChildEnv. The PWD pin is load-bearing+ // here: the non-codex branch above tells the CLI the image is "in the+ // current directory", and the vision provider is user-configurable — so on+ // OpenCode (which resolves its project root from PWD) a stale value both+ // hides vision-input.png and turns the CLI loose in the PortOS checkout.+ // Routing through the shared builder also brings the OpenCode declared-models+ // map here for the first time, so the `--model` buildCliVisionInvocation+ // injects isn't rejected by an Ollama-backed OpenCode provider (the #2190+ // fix, previously applied only at the runner/agent sites). No `guard` —+ // vision is a one-shot describe, not an agent.+ const childEnv = buildCliChildEnv({ provider, model, cwd });++ // npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap+ // (cmd.exe /c) instead of enabling a shell. This matters even more here+ // than at other call sites: the codex branch of buildCliVisionInvocation+ // puts the free-text `prompt` directly into `args` (see above), and+ // shell:true + an args array does NOT escape arguments (DEP0190) — any+ // prompt containing a space would silently mis-split into extra shell+ // tokens, corrupting or shell-injecting the invocation. The cmd.exe+ // wrapper instead relies on Node's own correct non-shell argv escaping,+ // which DOES preserve spaces within each arg as a single token. Resolved+ // against `childEnv` so a provider-configured PATH override is honored.+ // See resolveWindowsExecutable/prepareWindowsSafeSpawn in+ // server/lib/bufferedSpawn.js.+ const resolvedCommand = resolveWindowsExecutable(command, undefined, childEnv) || command;+ const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, deliveredArgs);++ const text = await new Promise((resolve, reject) => {+ const child = spawnImpl(spawnCommand, spawnArgs, {+ cwd,+ env: childEnv,+ windowsHide: true,+ stdio: ['pipe', 'pipe', 'pipe'],+ });+ let out = '';+ let err = '';+ let killTimer = null;+ // On timeout, SIGTERM the child AND reject now — don't wait on `close`. A+ // wedged CLI that ignores SIGTERM would otherwise never emit `close`, so+ // the promise would hang forever and the temp dir (cleaned in `finally`)+ // would leak. Escalate to SIGKILL on a short grace timer.+ const timer = timeout > 0 ? setTimeout(() => {+ if (!child.killed) killProcessTree(child);+ killTimer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 5000);+ killTimer?.unref?.();+ reject(new Error(`${command} vision call timed out after ${timeout}ms`));+ }, timeout) : null;+ timer?.unref?.();+ const clearTimers = () => { if (timer) clearTimeout(timer); if (killTimer) clearTimeout(killTimer); };++ child.on('error', (e) => { clearTimers(); reject(new Error(`Failed to spawn ${command}: ${e.message}`)); });+ child.stdout?.on('data', (d) => { out += d.toString(); });+ child.stderr?.on('data', (d) => { err += d.toString(); });+ child.on('close', (code) => {+ clearTimers();+ // `codex exec` prints the whole session transcript (banner, echoed+ // prompt, tool sections, `tokens used` footer) to stdout — carve out+ // the assistant reply so captioning doesn't persist the transcript as+ // the caption. Newer Codex emits the final reply AFTER the `tokens used`+ // footer (extractCodexAssistantTail), older versions before it+ // (extractCodexAssistant); try tail first, then the legacy extractor,+ // both no-ops for non-codex output (tail → null, legacy → input).+ if (code === 0) return resolve((extractCodexAssistantTail(out) ?? extractCodexAssistant(out)).trim());+ const tail = err.trim().split('\n').slice(-4).join('\n');+ reject(new Error(`${command} vision call exited ${code}${tail ? `: ${tail}` : ''}`));+ });++ // When grok is delivered via a Windows temp file the prompt is already on+ // disk (writePromptToStdin=false) — just close stdin.+ if (writePromptToStdin && stdin != null) {+ child.stdin?.write(stdin);+ child.stdin?.end();+ } else {+ child.stdin?.end();+ }+ });++ return text;+}diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.jsindex 2b5ee0336c..e60afe829f 100644--- a/server/services/visionCli.test.js+++ b/server/services/visionCli.test.js@@ -80,6 +80,35 @@ describe('buildCliVisionInvocation', () => {expect(inv.stdin).toContain('vision-input.png');expect(posixPath(inv.cwd)).toBe('/tmp/y');});++ it('attaches every named frame and injects effort for a multi-image Codex call', () => {+ const inv = buildCliVisionInvocation(+ { id: 'codex', command: 'codex', args: [] },+ 'gpt-5',+ '/tmp/x',+ 'describe motion',+ { imageNames: ['vision-1.jpg', 'vision-2.jpg'], effort: 'high' },+ );+ const paths = inv.args.map((a) => posixPath(a));+ expect(paths.filter((a) => a === '-i')).toHaveLength(2);+ expect(paths).toContain('/tmp/x/vision-1.jpg');+ expect(paths).toContain('/tmp/x/vision-2.jpg');+ expect(inv.args).toEqual(expect.arrayContaining(['-c', 'model_reasoning_effort=high']));+ });++ it('lists every frame in the Claude stdin prompt and passes effort through buildCliArgs', () => {+ const inv = buildCliVisionInvocation(+ { id: 'claude-code', command: 'claude', args: [] },+ 'claude-opus-4-8',+ '/tmp/y',+ 'describe motion',+ { imageNames: ['vision-1.jpg', 'vision-2.jpg'], effort: 'high' },+ );+ expect(inv.stdin).toContain('vision-1.jpg');+ expect(inv.stdin).toContain('vision-2.jpg');+ expect(inv.stdin).toMatch(/chronological/i);+ expect(inv.args).toEqual(expect.arrayContaining(['--effort', 'high']));+ });});// A minimal child-process double: an EventEmitter with stdin/stdout/stderr.