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: hide/unhide media cards + Flux image-to-image
Adam Eivyb2c9fd7721b5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 92ee5653e8..543bedb125 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,10 @@## Added+- **Image Gen + Video Gen — hide/unhide media cards.** Each generated image/video now has an Eye/EyeOff toggle in its action row that moves the card into a per-page "hidden" section. Cards in the hidden section show as "Unhide" instead of "Hide". A collapsible "Show hidden (N) ▸" / "Hide hidden (N) ▾" toggle below the recent-renders grid reveals the hidden cards on demand. Server: `POST /api/image-gen/:filename/visibility` mutates the per-image sidecar JSON; `POST /api/video-gen/history/:id/visibility` mutates the matching record in `data/video-history.json`. Client: optimistic state update with rollback on server failure. The `hidden` flag flows through the existing normalizers so any future MediaCard consumer (e.g. Media History, gallery search) can opt into the same UI just by passing `onToggleHidden`. Files: `server/routes/imageGen.js`, `server/routes/videoGen.js`, `server/services/imageGen/local.js`, `server/services/videoGen/local.js`, `client/src/services/apiImageVideo.js`, `client/src/components/media/{MediaCard.jsx,normalize.js}`, `client/src/pages/{ImageGen.jsx,VideoGen.jsx}`.++- **Flux image-to-image (i2i) on the Image Gen page.** When Local mode is selected, a new "Init image" section under the model/seed grid lets the user upload a source image (PNG/JPG/WebP, ≤20MB) or pre-fill from a gallery basename via `?initImageFile=foo.png`. A strength slider (0.0 closer-to-source ... 1.0 freer-remix, default 0.4) controls how much of the source survives the diffusion. Server: `mflux-generate` is now invoked with `--image-path <path>` and `--image-strength <0..1>` when an init image is set; the path is realpath-validated against `PATHS.images` (defense-in-depth in both the route and the service). The route gained an `optionalUpload('initImage', ...)` middleware (also exported from `server/lib/multipart.js` for reuse) that no-ops on JSON bodies, so the existing JSON callers (SDAPI bridge, avatar route, the Imagine page's old payload) keep working unchanged. The dispatcher silently drops the i2i fields for External/Codex modes (which don't support i2i) so a misrouted payload still produces a useful txt2img result. The init image filename + strength are persisted to the metadata sidecar so a remix or audit can recover them. Client now exports a shared `buildFormData(fields)` helper used by both `generateVideo` and the new i2i upload branch in `ImageGen.jsx`. Files: `server/lib/multipart.js`, `server/routes/imageGen.js`, `server/services/imageGen/{index.js,local.js}`, `client/src/services/apiImageVideo.js`, `client/src/pages/ImageGen.jsx`.+- **`/brain/links` — per-repo malware/risk scan button.** New "Scan" action (ShieldCheck icon) sits next to Open / Pull on every cloned-status GitHub repo. Clicking it queues a CoS user task that runs `/do:scan` against the clone's `localPath` — the bundled slashdo command is a hardened read-only audit (no scanned code is executed, no fetched URLs are followed, hostile-until-proven-safe). The agent writes its full markdown report to `~/.claude/scans/<basename>-<date>.md` and the user is told to track progress in CoS Tasks. Backed by a new `POST /api/brain/links/:id/scan` endpoint that loads the bundled slashdo body via `loadSlashdoCommand('scan')` and bakes the repo path into the task context as `SCAN_DIR`. Pre-flight checks reject non-cloned links, missing `localPath`, vanished folders, and duplicate in-flight scans for the same repo. Files: `server/routes/brain.js`, `client/src/services/apiBrain.js`, `client/src/components/brain/tabs/LinksTab.jsx`. The slashdo submodule is also bumped from `a38ee04` to `50011ef` (picks up `do:pr-better` and the v2.12.0 release).## Changeddiff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsxindex 4b6225446e..7a8f5049a5 100644--- a/client/src/components/media/MediaCard.jsx+++ b/client/src/components/media/MediaCard.jsx@@ -1,4 +1,4 @@-import { Trash2, Download, Film, Image as ImageIcon, Sparkles } from 'lucide-react';+import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff } from 'lucide-react';// Single card used everywhere a generated image/video appears in a grid:// the Image Gen page's recent gallery, the Video Gen page's recent renders,@@ -13,6 +13,7 @@ export default function MediaCard({onSendToVideo,onContinue,onDelete,+ onToggleHidden,selectionLabel = null, // e.g. "1", "2" — shown as the stitch order badgeselected = false,disabled = false,@@ -99,6 +100,16 @@ export default function MediaCard({><Download className="w-3 h-3" /></a>+ {onToggleHidden && (+ <button+ type="button"+ onClick={() => onToggleHidden(item)}+ className="px-1.5 py-1 bg-port-border hover:bg-port-border/70 text-white text-[10px] rounded flex items-center justify-center"+ title={item.hidden ? 'Unhide (move out of hidden section)' : 'Hide (move to hidden section)'}+ >+ {item.hidden ? <EyeOff className="w-3 h-3" /> : <Eye className="w-3 h-3" />}+ </button>+ )}{onDelete && (<buttontype="button"diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.jsindex 7fede8e568..e55a38b9cb 100644--- a/client/src/components/media/normalize.js+++ b/client/src/components/media/normalize.js@@ -17,6 +17,7 @@ export function normalizeImage(i) {quantize: i.quantize,seed: i.seed,createdAt: i.createdAt,+ hidden: !!i.hidden,raw: i,};}@@ -37,6 +38,7 @@ export function normalizeVideo(v) {fps: v.fps,stitchedFrom: v.stitchedFrom,createdAt: v.createdAt,+ hidden: !!v.hidden,raw: v,};}diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 400a5d0895..dfa867e0f7 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -8,7 +8,7 @@* "Enable Codex Imagegen" toggle in Settings; otherwise its chip is hidden.*/-import { useState, useEffect, useCallback, useRef } from 'react';+import { useState, useEffect, useCallback, useRef, useMemo } from 'react';import { useNavigate, useSearchParams, Link } from 'react-router-dom';import Drawer from '../components/Drawer';import { ImageGenTab } from '../components/settings/ImageGenTab';@@ -24,7 +24,8 @@ import BrailleSpinner from '../components/BrailleSpinner';import { useImageGenProgress } from '../hooks/useImageGenProgress';import {getImageGenStatus, generateImage, listImageModels, listLoras, listImageGallery,- cancelImageGen, deleteImage, getActiveImageJob, getSettings,+ cancelImageGen, deleteImage, setImageHidden, getActiveImageJob, getSettings,+ buildFormData,} from '../services/api';import { randomSeed, safeParseJSON } from '../lib/genUtils';@@ -54,6 +55,7 @@ export default function ImageGen() {const [availableLoras, setAvailableLoras] = useState([]);const [gallery, setGallery] = useState([]);const [preview, setPreview] = useState(null);+ const [showHidden, setShowHidden] = useState(false);const [selectedMode, setSelectedMode] = useState(null);const [availableBackends, setAvailableBackends] = useState([]);@@ -70,6 +72,12 @@ export default function ImageGen() {const [seed, setSeed] = useState('');const [selectedLoras, setSelectedLoras] = useState([]);+ // i2i (Flux, local mflux only). source='upload' carries `file`; source='gallery'+ // carries `name` (basename from URL param). Coupled lifetime — always replace+ // the whole object so previewUrl can never out-live its file/name.+ const [initImage, setInitImage] = useState({ source: null, file: null, name: null, previewUrl: null });+ const [initImageStrength, setInitImageStrength] = useState(0.4);+const [generating, setGenerating] = useState(false);const [statusMsg, setStatusMsg] = useState('');const [localProgress, setLocalProgress] = useState(null); // local mode SSE-driven 0..1@@ -187,6 +195,32 @@ export default function ImageGen() {refreshStatus(effectiveMode);}, [effectiveMode, refreshStatus]);+ // ?initImageFile=foo.png pre-fills from a gallery basename — supports a+ // future "Send to Image (i2i)" gallery action.+ useEffect(() => {+ const fromUrl = searchParams.get('initImageFile');+ if (fromUrl && initImage.source == null) {+ setInitImage({ source: 'gallery', file: null, name: fromUrl, previewUrl: `/data/images/${fromUrl}` });+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [searchParams]);++ const handlePickInitImage = (e) => {+ const file = e.target.files?.[0];+ if (!file) return;+ if (initImage.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(initImage.previewUrl);+ setInitImage({ source: 'upload', file, name: file.name, previewUrl: URL.createObjectURL(file) });+ };+ const handleClearInitImage = () => {+ if (initImage.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(initImage.previewUrl);+ setInitImage({ source: null, file: null, name: null, previewUrl: null });+ };+ // Object URL cleanup on unmount.+ useEffect(() => () => {+ if (initImage.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(initImage.previewUrl);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+// When the user closes the Settings drawer, settings may have changed// (e.g. they enabled Codex or configured a new external URL). Reload so// the chip strip matches the new state without a page refresh.@@ -201,6 +235,10 @@ export default function ImageGen() {const currentModel = models.find((m) => m.id === modelId);const matchedResolution = RESOLUTIONS.find((r) => r.w === width && r.h === height);const resolutionLabel = matchedResolution?.label || `${width}×${height}`;+ const { visibleGallery, hiddenGallery } = useMemo(() => ({+ visibleGallery: gallery.filter((img) => !img.hidden),+ hiddenGallery: gallery.filter((img) => img.hidden),+ }), [gallery]);const handleResolutionChange = (e) => {const r = RESOLUTIONS.find((r) => r.label === e.target.value);@@ -233,7 +271,26 @@ export default function ImageGen() {loraScales: selectedLoras.map((l) => l.scale),mode: 'local',};- const data = await generateImage(payload);+ // i2i (local Flux): switch to multipart so the init image travels with+ // the prompt payload. The route's optional-multipart middleware accepts+ // both shapes against the same endpoint.+ const hasInitImage = isLocalMode && initImage.source != null;+ let data;+ if (hasInitImage) {+ const fd = buildFormData({+ ...payload,+ ...(initImage.source === 'upload' ? { initImage: initImage.file } : { initImageFile: initImage.name }),+ initImageStrength,+ });+ const res = await fetch('/api/image-gen/generate', { method: 'POST', body: fd });+ if (!res.ok) {+ const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));+ throw new Error(body.error || `HTTP ${res.status}`);+ }+ data = await res.json();+ } else {+ data = await generateImage(payload);+ }return new Promise((resolve, reject) => {const jobId = data.jobId || data.generationId;@@ -334,6 +391,17 @@ export default function ImageGen() {setGallery((g) => g.filter((img) => img.filename !== filename));};+ const handleToggleHidden = async (img) => {+ const nextHidden = !img.hidden;+ setGallery((g) => g.map((x) => (x.filename === img.filename ? { ...x, hidden: nextHidden } : x)));+ const result = await setImageHidden(img.filename, nextHidden).catch((err) => {+ toast.error(err.message || 'Failed to update visibility');+ setGallery((g) => g.map((x) => (x.filename === img.filename ? { ...x, hidden: !nextHidden } : x)));+ return null;+ });+ if (result) toast.success(nextHidden ? 'Image hidden' : 'Image unhidden');+ };+const sendToVideo = (img) => {if (!img?.filename) return;const params = new URLSearchParams({ sourceImageFile: img.filename });@@ -616,6 +684,55 @@ export default function ImageGen() {</div>)}+ {isLocalMode && (+ <div>+ <label className="block text-sm font-medium text-gray-300 mb-2">+ Init image <span className="text-xs text-gray-500 font-normal">(image-to-image — Flux only)</span>+ </label>+ {initImage.previewUrl ? (+ <div className="flex items-start gap-3">+ <div className="relative">+ <img+ src={initImage.previewUrl}+ alt="Init"+ className="w-24 h-24 object-cover rounded-lg border border-port-border bg-port-bg"+ />+ <button+ type="button"+ onClick={handleClearInitImage}+ disabled={generating}+ className="absolute -top-2 -right-2 w-6 h-6 rounded-full bg-port-card border border-port-border text-gray-300 hover:text-white hover:bg-port-error/40 flex items-center justify-center disabled:opacity-50"+ title="Remove init image"+ >+ <X className="w-3 h-3" />+ </button>+ </div>+ <div className="flex-1 space-y-2">+ <div className="text-xs text-gray-400 truncate" title={initImage.name}>+ {initImage.name}+ </div>+ <label className="block text-xs text-gray-400">+ Strength ({initImageStrength.toFixed(2)}) — lower = closer to source, higher = freer remix+ </label>+ <input+ type="range" min={0} max={1} step={0.05}+ value={initImageStrength}+ disabled={generating}+ onChange={(e) => setInitImageStrength(Number(e.target.value))}+ className="w-full accent-port-accent"+ />+ </div>+ </div>+ ) : (+ <label className="flex items-center justify-center gap-2 w-full px-3 py-3 border border-dashed border-port-border rounded-lg text-xs text-gray-400 hover:text-white hover:border-port-accent cursor-pointer transition-colors">+ <ImageIcon className="w-4 h-4" />+ Upload an image to remix (PNG, JPG, WebP, ≤20MB)+ <input type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={handlePickInitImage} disabled={generating} />+ </label>+ )}+ </div>+ )}+<div className="flex items-center gap-2 pt-2">{generating ? (<button@@ -695,16 +812,16 @@ export default function ImageGen() {</div></form>- {gallery.length > 0 && (+ {visibleGallery.length > 0 && (<div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3"><div className="flex items-center justify-between">- <h2 className="text-sm font-medium text-gray-300">Recent renders ({Math.min(gallery.length, 6)} of {gallery.length})</h2>- {gallery.length > 6 && (+ <h2 className="text-sm font-medium text-gray-300">Recent renders ({Math.min(visibleGallery.length, 6)} of {visibleGallery.length})</h2>+ {visibleGallery.length > 6 && (<Link to="/media/history" className="text-xs text-port-accent hover:underline">View all →</Link>)}</div><div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">- {gallery.slice(0, 6).map((img) => {+ {visibleGallery.slice(0, 6).map((img) => {const item = normalizeImage(img);return (<MediaCard@@ -714,6 +831,7 @@ export default function ImageGen() {onRemix={() => handleRemix(img)}onSendToVideo={() => sendToVideo(img)}onDelete={() => handleDelete(img.filename)}+ onToggleHidden={() => handleToggleHidden(item)}/>);})}@@ -721,6 +839,37 @@ export default function ImageGen() {</div>)}+ {hiddenGallery.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">+ <button+ type="button"+ onClick={() => setShowHidden((s) => !s)}+ className="flex items-center justify-between w-full text-sm font-medium text-gray-300 hover:text-white"+ >+ <span>{showHidden ? 'Hide' : 'Show'} hidden ({hiddenGallery.length})</span>+ <span className="text-xs text-gray-500">{showHidden ? '▾' : '▸'}</span>+ </button>+ {showHidden && (+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">+ {hiddenGallery.map((img) => {+ const item = normalizeImage(img);+ return (+ <MediaCard+ key={item.key}+ item={item}+ onPreview={() => setPreview(img)}+ onRemix={() => handleRemix(img)}+ onSendToVideo={() => sendToVideo(img)}+ onDelete={() => handleDelete(img.filename)}+ onToggleHidden={() => handleToggleHidden(item)}+ />+ );+ })}+ </div>+ )}+ </div>+ )}+<MediaLightboxitem={preview ? normalizeImage(preview) : null}onClose={() => setPreview(null)}diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex c8e4b405d3..4e7db4343b 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -7,7 +7,7 @@* straight into video.*/-import { useState, useEffect, useRef, useCallback } from 'react';+import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { useSearchParams, useNavigate, Link } from 'react-router-dom';import Drawer from '../components/Drawer';import { ImageGenTab } from '../components/settings/ImageGenTab';@@ -22,7 +22,7 @@ import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';import {getVideoGenStatus, generateVideo, cancelVideoGen,- listVideoHistory, deleteVideoHistoryItem, extractLastFrame,+ listVideoHistory, deleteVideoHistoryItem, setVideoHidden, extractLastFrame,} from '../services/api';import { randomSeed, safeParseJSON } from '../lib/genUtils';@@ -88,6 +88,7 @@ export default function VideoGen() {}, [incomingNegativePrompt]);const [history, setHistory] = useState([]);const [preview, setPreview] = useState(null);+ const [showHidden, setShowHidden] = useState(false);const navigate = useNavigate();const refreshHistory = useCallback(() => {@@ -95,10 +96,25 @@ export default function VideoGen() {}, []);useEffect(() => { refreshHistory(); }, [refreshHistory]);+ const { visibleHistory, hiddenHistory } = useMemo(() => ({+ visibleHistory: history.filter((v) => !v.hidden),+ hiddenHistory: history.filter((v) => v.hidden),+ }), [history]);+const handleDeleteHistory = async (item) => {await deleteVideoHistoryItem(item.id).catch((err) => toast.error(err.message || 'Delete failed'));setHistory((h) => h.filter((v) => v.id !== item.id));};+ const handleToggleHistoryHidden = async (item) => {+ const nextHidden = !item.hidden;+ setHistory((h) => h.map((v) => (v.id === item.id ? { ...v, hidden: nextHidden } : v)));+ const result = await setVideoHidden(item.id, nextHidden).catch((err) => {+ toast.error(err.message || 'Failed to update visibility');+ setHistory((h) => h.map((v) => (v.id === item.id ? { ...v, hidden: !nextHidden } : v)));+ return null;+ });+ if (result) toast.success(nextHidden ? 'Video hidden' : 'Video unhidden');+ };const handleContinueHistory = async (item) => {try {const { filename } = await extractLastFrame(item.id);@@ -520,16 +536,16 @@ export default function VideoGen() {</div></form>- {history.length > 0 && (+ {visibleHistory.length > 0 && (<div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3"><div className="flex items-center justify-between">- <h2 className="text-sm font-medium text-gray-300">Recent renders ({Math.min(history.length, 6)} of {history.length})</h2>- {history.length > 6 && (+ <h2 className="text-sm font-medium text-gray-300">Recent renders ({Math.min(visibleHistory.length, 6)} of {visibleHistory.length})</h2>+ {visibleHistory.length > 6 && (<Link to="/media/history" className="text-xs text-port-accent hover:underline">View all →</Link>)}</div><div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">- {history.slice(0, 6).map((v) => {+ {visibleHistory.slice(0, 6).map((v) => {const item = normalizeVideo(v);return (<MediaCard@@ -538,6 +554,7 @@ export default function VideoGen() {onPreview={() => setPreview(item)}onContinue={() => handleContinueHistory(v)}onDelete={() => handleDeleteHistory(v)}+ onToggleHidden={() => handleToggleHistoryHidden(v)}/>);})}@@ -545,6 +562,36 @@ export default function VideoGen() {</div>)}+ {hiddenHistory.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">+ <button+ type="button"+ onClick={() => setShowHidden((s) => !s)}+ className="flex items-center justify-between w-full text-sm font-medium text-gray-300 hover:text-white"+ >+ <span>{showHidden ? 'Hide' : 'Show'} hidden ({hiddenHistory.length})</span>+ <span className="text-xs text-gray-500">{showHidden ? '▾' : '▸'}</span>+ </button>+ {showHidden && (+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">+ {hiddenHistory.map((v) => {+ const item = normalizeVideo(v);+ return (+ <MediaCard+ key={item.key}+ item={item}+ onPreview={() => setPreview(item)}+ onContinue={() => handleContinueHistory(v)}+ onDelete={() => handleDeleteHistory(v)}+ onToggleHidden={() => handleToggleHistoryHidden(v)}+ />+ );+ })}+ </div>+ )}+ </div>+ )}+<MediaLightboxitem={preview}onClose={() => setPreview(null)}diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex bb4c4dcbbb..4ce06c0e87 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -9,6 +9,10 @@ export const listImageGallery = () => request('/image-gen/gallery');export const getActiveImageJob = () => request('/image-gen/active');export const cancelImageGen = () => request('/image-gen/cancel', { method: 'POST' });export const deleteImage = (filename) => request(`/image-gen/${encodeURIComponent(filename)}`, { method: 'DELETE' });+export const setImageHidden = (filename, hidden) => request(`/image-gen/${encodeURIComponent(filename)}/visibility`, {+ method: 'POST',+ body: JSON.stringify({ hidden }),+});// Video genexport const getVideoGenStatus = () => request('/video-gen/status');@@ -16,24 +20,36 @@ export const listVideoModels = () => request('/video-gen/models');export const cancelVideoGen = () => request('/video-gen/cancel', { method: 'POST' });export const listVideoHistory = () => request('/video-gen/history');export const deleteVideoHistoryItem = (id) => request(`/video-gen/history/${encodeURIComponent(id)}`, { method: 'DELETE' });+export const setVideoHidden = (id, hidden) => request(`/video-gen/history/${encodeURIComponent(id)}/visibility`, {+ method: 'POST',+ body: JSON.stringify({ hidden }),+});export const extractLastFrame = (id) => request(`/video-gen/last-frame/${encodeURIComponent(id)}`, { method: 'POST' });export const stitchVideos = (videoIds) => request('/video-gen/stitch', {method: 'POST',body: JSON.stringify({ videoIds }),});-// generateVideo always sends multipart/form-data via FormData. Bypass the-// JSON-only request() helper because the server route expects multipart for-// the optional sourceImage upload (and uniform multipart parsing for both-// upload and no-upload paths is simpler than branching on Content-Type).-export async function generateVideo(fields) {+// Build a FormData payload, skipping null/undefined/empty fields. Arrays are+// appended one element per key (Express's multer parses repeated keys into+// req.body[key] = [...]). Blobs (File objects, etc.) pass through unchanged.+export function buildFormData(fields) {const fd = new FormData();for (const [k, v] of Object.entries(fields)) {if (v == null || v === '') continue;if (v instanceof Blob) fd.append(k, v);+ else if (Array.isArray(v)) v.forEach((item) => fd.append(k, String(item)));else fd.append(k, String(v));}- const res = await fetch('/api/video-gen', { method: 'POST', body: fd });+ return fd;+}++// generateVideo always sends multipart/form-data via FormData. Bypass the+// JSON-only request() helper because the server route expects multipart for+// the optional sourceImage upload (and uniform multipart parsing for both+// upload and no-upload paths is simpler than branching on Content-Type).+export async function generateVideo(fields) {+ const res = await fetch('/api/video-gen', { method: 'POST', body: buildFormData(fields) });if (!res.ok) {const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));const err = new Error(body.error || `HTTP ${res.status}`);diff --git a/server/lib/multipart.js b/server/lib/multipart.jsindex 046a002edf..ef1ca5ff3e 100644--- a/server/lib/multipart.js+++ b/server/lib/multipart.js@@ -39,6 +39,18 @@ export function uploadSingle(fieldName, { limits = {}, fileFilter } = {}) {};}+// Wrap uploadSingle so the parser only kicks in for multipart bodies — JSON+// callers fall through untouched. Useful when an existing JSON endpoint adds+// optional file-upload support without breaking back-compat.+export function optionalUpload(fieldName, opts) {+ const uploader = uploadSingle(fieldName, opts);+ return (req, res, next) => {+ const ct = req.headers['content-type'] || '';+ if (!ct.startsWith('multipart/form-data')) return next();+ return uploader(req, res, next);+ };+}+function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next) {const PART_DELIM = Buffer.from('\r\n--' + boundary);const FIRST_DELIM = Buffer.from('--' + boundary);diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex fe4271c6fa..b427f04dc7 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -11,16 +11,20 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler } from '../lib/errorHandler.js';+import { existsSync } from 'fs';+import { copyFile, unlink } from 'fs/promises';+import { randomUUID } from 'crypto';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';+import { optionalUpload } from '../lib/multipart.js';import * as imageGen from '../services/imageGen/index.js';import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';import {REQUIRED_PACKAGES, detectPython, checkPackages, installPackages,isExternallyManaged, createVenv, isAllowedPython, pipNameFor,} from '../lib/pythonSetup.js';-import { PATHS } from '../lib/fileUtils.js';-import { join } from 'node:path';+import { PATHS, ensureDir } from '../lib/fileUtils.js';+import { join, basename, resolve as resolvePath, sep as PATH_SEP, extname } from 'node:path';const router = Router();@@ -45,8 +49,31 @@ const generateSchema = z.object({loraFilenames: z.array(z.string().max(256).regex(/^[^/\\]+$/, 'lora filename must not contain path separators')).max(8).optional(),loraPaths: z.array(z.string().max(512)).max(8).optional(),loraScales: z.array(z.number().min(0).max(2)).max(8).optional(),+ // i2i: pick an existing gallery image (basename) as the init image. If+ // initImage was uploaded via multipart, this is ignored in favor of the+ // upload. Strength: 0.0 = ignore source, 1.0 = max influence.+ initImageFile: z.string().max(256).regex(/^[^/\\]+\.(png|jpg|jpeg|webp)$/i, 'init image must be a basename ending in png/jpg/jpeg/webp').optional(),+ initImageStrength: z.number().min(0).max(1).optional(),});+// JSON callers (SDAPI bridge, avatar route, the Imagine page's old payload+// shape) skip the parser entirely; FormData callers get req.file + string+// req.body that coerceFormFields() converts before Zod validation.+const initImageUpload = optionalUpload('initImage', {+ limits: { fileSize: 20 * 1024 * 1024 },+ fileFilter: (_req, file, cb) => cb(null, file.mimetype.startsWith('image/')),+});++// Numerics arrive as strings from FormData — coerce before Zod validation.+function coerceFormFields(body) {+ const numericFields = ['width', 'height', 'steps', 'cfgScale', 'guidance', 'seed', 'initImageStrength'];+ for (const f of numericFields) {+ if (typeof body[f] === 'string' && body[f] !== '') body[f] = Number(body[f]);+ }+ if (typeof body.quantize === 'string' && /^\d+$/.test(body.quantize)) body.quantize = Number(body.quantize);+ return body;+}+const avatarSchema = z.object({name: z.string().max(100).optional(),characterClass: z.string().max(100).optional(),@@ -69,9 +96,37 @@ router.get('/active', asyncHandler(async (_req, res) => {res.json({ activeJob: await imageGen.getActiveJob() });}));-router.post('/generate', asyncHandler(async (req, res) => {- const data = validateRequest(generateSchema, req.body);- res.json(await imageGen.generateImage(data));+router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {+ const data = validateRequest(generateSchema, coerceFormFields(req.body));+ // Resolve init image source: uploaded file > gallery filename. The local+ // service double-checks that the path stays under PATHS.images.+ let initImagePath = null;+ let uploadedInitTempPath = null;+ if (req.file) {+ await ensureDir(PATHS.images);+ const safeExt = (extname(req.file.originalname || '') || '.png').toLowerCase();+ const ext = ['.png', '.jpg', '.jpeg', '.webp'].includes(safeExt) ? safeExt : '.png';+ const initFilename = `init-${randomUUID()}${ext}`;+ initImagePath = join(PATHS.images, initFilename);+ await copyFile(req.file.path, initImagePath);+ uploadedInitTempPath = req.file.path;+ } else if (data.initImageFile) {+ const candidate = join(PATHS.images, basename(data.initImageFile));+ const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;+ const resolved = resolvePath(candidate);+ if (!resolved.startsWith(imagesRoot) || !existsSync(resolved)) {+ throw new ServerError('Init image not found in gallery', { status: 400, code: 'INIT_IMAGE_NOT_FOUND' });+ }+ initImagePath = resolved;+ }+ // Strip the route-only `initImageFile` field — providers expect `initImagePath`.+ delete data.initImageFile;+ if (initImagePath) data.initImagePath = initImagePath;++ const result = await imageGen.generateImage(data);+ // Multer's tmp upload is no longer needed once we've copied it into PATHS.images.+ if (uploadedInitTempPath) await unlink(uploadedInitTempPath).catch(() => {});+ res.json(result);}));router.post('/avatar', asyncHandler(async (req, res) => {@@ -108,6 +163,10 @@ router.delete('/:filename', asyncHandler(async (req, res) => {res.json(await local.deleteImage(req.params.filename));}));+router.post('/:filename/visibility', asyncHandler(async (req, res) => {+ res.json(await local.setImageHidden(req.params.filename, !!req.body?.hidden));+}));+// --- Local-mode setup automation ---router.get('/setup/python', asyncHandler(async (_req, res) => {diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 04f80a9261..02ee855f6a 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -23,6 +23,7 @@ import {cancel,loadHistory,deleteHistoryItem,+ setHistoryItemHidden,extractLastFrame,stitchVideos,} from '../services/videoGen/local.js';@@ -149,6 +150,10 @@ router.delete('/history/:id', asyncHandler(async (req, res) => {res.json(await deleteHistoryItem(req.params.id));}));+router.post('/history/:id/visibility', asyncHandler(async (req, res) => {+ res.json(await setHistoryItemHidden(req.params.id, !!req.body?.hidden));+}));+router.post('/last-frame/:id', asyncHandler(async (req, res) => {res.json(await extractLastFrame(req.params.id));}));diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex 1584218c8c..fff661a148 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -61,6 +61,13 @@ export async function generateImage(params) {}// Strip the dispatcher-only `mode` field — providers don't expect it.delete normalized.mode;+ // i2i is only supported by the local mflux backend. If the caller passed an+ // init image for external/codex, drop it silently rather than failing the+ // whole render — the prompt still produces a useful txt2img result.+ if (mode !== 'local' && (normalized.initImagePath || normalized.initImageStrength != null)) {+ delete normalized.initImagePath;+ delete normalized.initImageStrength;+ }if (mode === 'codex') {const c = codexCfg(s);if (!c.enabled) {diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex af3ac77408..5482430296 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -70,7 +70,7 @@ export const cancel = () => {return true;};-const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths, loraScales, stepwiseDir }) => {+const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths, loraScales, stepwiseDir, initImagePath, initImageStrength }) => {if (IS_WIN) {const scriptPath = join(PATHS.root, 'scripts', 'imagine_win.py');return {@@ -80,6 +80,8 @@ const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height,...(negativePrompt ? ['--negative-prompt', negativePrompt] : []),...(loraPaths.length ? ['--lora-paths', ...loraPaths] : []),...(loraScales.length ? ['--lora-scales', ...loraScales.map(String)] : []),+ ...(initImagePath ? ['--image-path', initImagePath] : []),+ ...(initImagePath && initImageStrength != null ? ['--image-strength', String(initImageStrength)] : []),],};}@@ -90,6 +92,8 @@ const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height,if (negativePrompt) args.push('--negative-prompt', negativePrompt);if (loraPaths.length) args.push('--lora-paths', ...loraPaths);if (loraScales.length) args.push('--lora-scales', ...loraScales.map(String));+ if (initImagePath) args.push('--image-path', initImagePath);+ if (initImagePath && initImageStrength != null) args.push('--image-strength', String(initImageStrength));// mflux writes one PNG per step here as it diffuses; we watch the dir and// stream the latest frame back to the client as `currentImage` for the// live-preview area.@@ -97,7 +101,7 @@ const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height,return { bin, args };};-export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [] }) {+export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null }) {if (!pythonPath) throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });// Enforce the single-activeProcess invariant the rest of this module relies@@ -136,7 +140,21 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m// what the new client API uses for remix. Keep `loraPaths` populated too// so older code paths reading the sidecar don't break.const validLoraFilenames = validLoras.map((p) => basename(p));- const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, createdAt: new Date().toISOString() };+ // i2i: validate the init image path stays under PATHS.images so a malicious+ // payload (or a stale absolute path from an old sidecar) can't make mflux+ // read arbitrary files. If the caller passes a basename, the route layer+ // already resolved it to PATHS.images/<basename>; this is a defense-in-depth+ // check here too.+ let validInitImagePath = null;+ if (initImagePath && typeof initImagePath === 'string') {+ const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;+ const resolved = resolvePath(initImagePath);+ if (resolved.startsWith(imagesRoot) && existsSync(resolved)) validInitImagePath = resolved;+ }+ const validInitImageStrength = validInitImagePath && initImageStrength != null+ ? Math.max(0, Math.min(1, Number(initImageStrength)))+ : null;+ const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, createdAt: new Date().toISOString() };const job = { ...meta, clients: [], status: 'running' };jobs.set(jobId, job);@@ -144,7 +162,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m// per inference step here; we watch and stream the latest as `currentImage`.const stepwiseDir = await mkdtemp(join(tmpdir(), 'portos-stepwise-'));- const { bin, args } = buildArgs({ pythonPath, modelId, prompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir });+ const { bin, args } = buildArgs({ pythonPath, modelId, prompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir, initImagePath: validInitImagePath, initImageStrength: validInitImageStrength });console.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps}`);imageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });@@ -313,6 +331,20 @@ export async function deleteImage(filename) {return { ok: true };}+export async function setImageHidden(filename, hidden) {+ if (!filename.endsWith('.png') || filename.includes('/') || filename.includes('\\') || filename.includes('..')) {+ throw new ServerError('Invalid filename', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const portosSidecar = join(PATHS.images, filename.replace('.png', '.metadata.json'));+ const altSidecar = join(PATHS.images, `${filename}.metadata.json`);+ const sidecarPath = existsSync(portosSidecar) ? portosSidecar : (existsSync(altSidecar) ? altSidecar : portosSidecar);+ const raw = await readFile(sidecarPath, 'utf-8').catch(() => null);+ const meta = raw ? safeJSONParse(raw, {}) : {};+ meta.hidden = !!hidden;+ await writeFile(sidecarPath, JSON.stringify(meta, null, 2));+ return { ok: true, hidden: meta.hidden };+}+// Returns just `{ filename, name }` — clients send `filename` back in the// generate payload's `loraFilenames` and the server resolves it against// PATHS.loras. Avoids leaking absolute server paths into the API surface.diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 5aed7b7374..a279aaae7f 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -409,6 +409,15 @@ export async function stitchVideos(videoIds) {return stitchedMeta;}+export async function setHistoryItemHidden(id, hidden) {+ const history = await loadHistory();+ const item = history.find((h) => h.id === id);+ if (!item) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });+ item.hidden = !!hidden;+ await saveHistory(history);+ return { ok: true, hidden: item.hidden };+}+export async function deleteHistoryItem(id) {const history = await loadHistory();const item = history.find((h) => h.id === id);