Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

require a vision-capable model for LoRA captioning, with a picker and gallery import

[._.]/ Adam Eivy03efc719193f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4da4847937..1f886d5e9a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,8 @@
## Changed
+- **LoRA captioning now guarantees a vision model, lets you pick it, and can pull from your gallery** — Auto-captioning a training dataset used to silently send images to whatever model the local backend defaulted to; a text-only model would fail every image with a cryptic `Model does not support images` 400. The captioner now resolves (and validates) a **vision-capable** model up front: it auto-picks the first installed vision model across Ollama + LM Studio, and fails the whole run with one actionable message if none is installed — instead of N per-image errors. A new **caption-model picker** on the dataset workbench lists your installed vision models (each tagged with its backend) and persists the choice to `settings.loraTraining`, so "Caption all" and per-image re-caption both use it; "Auto" defers to the auto-pick. Vision capability is detected from explicit backend metadata when available (LM Studio's `type: 'vlm'`, Ollama's `vision` capability) and an id heuristic otherwise (`isVisionModel`, mirrored client-side). And a new **"From gallery"** button imports images you've already generated/saved straight into the dataset (multi-select, copied independently so deleting the gallery original won't strand the dataset). (`server/lib/localModelHeuristics.js`, `server/services/loraDatasetCaption.js`, `server/services/loraDatasets.js`, `server/services/localLlm.js`, `client/src/components/loraTraining/CaptionModelPicker.jsx`, `client/src/components/loraTraining/ImportGalleryDialog.jsx`)
+
- **[issue-1214] Staged upload images no longer pile up on disk** — init and reference images you upload for edit/image-to-image renders are now cleaned up automatically once they're a week old and no longer used by any saved image, so repeated edit-from-upload renders stop quietly growing your data folder.
## Fixed
diff --git a/client/src/components/loraTraining/CaptionModelPicker.jsx b/client/src/components/loraTraining/CaptionModelPicker.jsx
new file mode 100644
index 0000000000..976ec02c77
--- /dev/null
+++ b/client/src/components/loraTraining/CaptionModelPicker.jsx
@@ -0,0 +1,108 @@
+/**
+ * Caption-model picker for the LoRA dataset workbench.
+ *
+ * Lists vision-capable installed local models (both Ollama + LM Studio, each
+ * tagged with the provider that serves it) and lets the user pick which one
+ * auto-captioning uses. The choice persists to `settings.loraTraining`
+ * (captionProviderId/captionModel) so it sticks across runs and machines, and
+ * is lifted to the parent via `onChange` so caption runs pass the explicit
+ * provider+model. "Auto" defers to the server's vision-model auto-pick.
+ */
+
+import { useEffect, useRef, useState } from 'react';
+import { Loader2, AlertTriangle } from 'lucide-react';
+import toast from '../ui/Toast';
+import { getVisionModels, getSettings, updateSettings } from '../../services/api';
+
+const AUTO = '__auto__';
+const keyFor = (m) => `${m.providerId}::${m.id}`;
+
+export default function CaptionModelPicker({ onChange }) {
+ const [models, setModels] = useState(null); // null = loading; [] = none installed
+ const [value, setValue] = useState(AUTO);
+ const [saving, setSaving] = useState(false);
+ // Preserve the rest of settings.loraTraining (training `defaults`) on save —
+ // updateSettings merges shallowly at the top level, so writing just the
+ // caption fields would clobber the sibling slice.
+ const loraTrainingRef = useRef({});
+
+ useEffect(() => {
+ let alive = true;
+ Promise.all([
+ getVisionModels({ silent: true }).catch(() => ({ models: [] })),
+ getSettings({ silent: true }).catch(() => ({})),
+ ]).then(([vm, settings]) => {
+ if (!alive) return;
+ const list = vm?.models || [];
+ setModels(list);
+ loraTrainingRef.current = settings?.loraTraining || {};
+ const savedModel = settings?.loraTraining?.captionModel || null;
+ const savedProvider = settings?.loraTraining?.captionProviderId || null;
+ if (savedModel) {
+ const match = list.find((m) => m.id === savedModel
+ && (!savedProvider || m.providerId === savedProvider));
+ const sel = match || { id: savedModel, providerId: savedProvider || 'lmstudio' };
+ setValue(keyFor(sel));
+ onChange?.({ providerId: sel.providerId, model: sel.id });
+ } else {
+ setValue(AUTO);
+ onChange?.({ providerId: null, model: null });
+ }
+ });
+ return () => { alive = false; };
+ // onChange is a stable setter from the parent; intentionally run once.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const handleChange = async (next) => {
+ setValue(next);
+ const picked = next === AUTO ? null : (models || []).find((m) => keyFor(m) === next) || null;
+ onChange?.(picked ? { providerId: picked.providerId, model: picked.id } : { providerId: null, model: null });
+ setSaving(true);
+ const nextLoraTraining = {
+ ...loraTrainingRef.current,
+ captionProviderId: picked ? picked.providerId : null,
+ captionModel: picked ? picked.id : null,
+ };
+ try {
+ await updateSettings({ loraTraining: nextLoraTraining });
+ loraTrainingRef.current = nextLoraTraining;
+ } catch {
+ toast.error('Could not save caption-model preference');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ if (models === null) {
+ return (
+ <span className="text-xs text-gray-500 flex items-center gap-1">
+ <Loader2 className="w-3 h-3 animate-spin" /> vision models…
+ </span>
+ );
+ }
+
+ return (
+ <div className="flex items-center gap-1.5">
+ <label htmlFor="lt-caption-model" className="text-xs text-gray-500">Caption model</label>
+ <select
+ id="lt-caption-model"
+ value={value}
+ onChange={(e) => handleChange(e.target.value)}
+ disabled={saving}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white max-w-[16rem] disabled:opacity-50"
+ >
+ <option value={AUTO}>Auto (first vision model)</option>
+ {models.map((m) => (
+ <option key={keyFor(m)} value={keyFor(m)}>{m.name} · {m.backend}</option>
+ ))}
+ </select>
+ {saving && <Loader2 className="w-3 h-3 animate-spin text-gray-400" />}
+ {!models.length && (
+ <span className="text-[11px] text-port-warning flex items-center gap-1" title="Install a vision model (e.g. Qwen2.5-VL, LLaVA) from Settings → Local LLM">
+ <AlertTriangle className="w-3 h-3" /> none installed
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/loraTraining/DatasetImageGrid.jsx b/client/src/components/loraTraining/DatasetImageGrid.jsx
index 1dc67b2e3e..d527789a50 100644
--- a/client/src/components/loraTraining/DatasetImageGrid.jsx
+++ b/client/src/components/loraTraining/DatasetImageGrid.jsx
@@ -17,9 +17,10 @@ const SOURCE_BADGE = {
generated: { label: 'generated', cls: 'bg-port-accent/20 text-port-accent' },
upload: { label: 'upload', cls: 'bg-emerald-600/20 text-emerald-300' },
'refsheet-slice': { label: 'sheet crop', cls: 'bg-purple-600/20 text-purple-300' },
+ gallery: { label: 'gallery', cls: 'bg-sky-600/20 text-sky-300' },
};
-export default function DatasetImageGrid({ dataset, onImagesChange, onCaptionRunStarted }) {
+export default function DatasetImageGrid({ dataset, onImagesChange, onCaptionRunStarted, captionModel = null }) {
const [drafts, setDrafts] = useState({});
const [savingId, setSavingId] = useState(null);
const [confirmingId, setConfirmingId] = useState(null);
@@ -53,7 +54,12 @@ export default function DatasetImageGrid({ dataset, onImagesChange, onCaptionRun
const recaption = async (img) => {
setRecaptioningId(img.id);
try {
- const run = await startLoraCaptionRun(dataset.id, { imageIds: [img.id], overwrite: true });
+ const run = await startLoraCaptionRun(dataset.id, {
+ imageIds: [img.id],
+ overwrite: true,
+ ...(captionModel?.providerId ? { providerId: captionModel.providerId } : {}),
+ ...(captionModel?.model ? { model: captionModel.model } : {}),
+ });
onCaptionRunStarted?.(run);
toast.success('Re-captioning image…');
} finally {
diff --git a/client/src/components/loraTraining/ImportGalleryDialog.jsx b/client/src/components/loraTraining/ImportGalleryDialog.jsx
new file mode 100644
index 0000000000..dd2e98fcb8
--- /dev/null
+++ b/client/src/components/loraTraining/ImportGalleryDialog.jsx
@@ -0,0 +1,170 @@
+/**
+ * Import-from-gallery dialog for the LoRA dataset workbench.
+ *
+ * Multi-select picker over the local image gallery (GET /api/image-gen/gallery)
+ * — the "choose images already in the system" path alongside upload/generate/
+ * slice. Reuses the same normalize + search helpers as GalleryImagePicker, but
+ * accumulates a selection and imports them all in one POST. The server copies
+ * each into the dataset (independent of the gallery original).
+ */
+
+import { useEffect, useMemo, useState } from 'react';
+import { Search, X, RefreshCw, Loader2, Check } from 'lucide-react';
+import Modal from '../ui/Modal';
+import MediaCard from '../media/MediaCard';
+import toast from '../ui/Toast';
+import { normalizeImage } from '../media/normalize';
+import { listImageGallery, importLoraDatasetGalleryImages } from '../../services/api';
+import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';
+
+const MAX_IMPORT = 50;
+
+export default function ImportGalleryDialog({ dataset, onClose, onImported }) {
+ const [items, setItems] = useState([]);
+ const [loading, setLoading] = useState(false);
+ const [query, setQuery] = useState('');
+ const [selected, setSelected] = useState([]); // ordered list of filenames
+ const [importing, setImporting] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ listImageGallery()
+ .then((images) => {
+ if (cancelled) return;
+ const normalized = (Array.isArray(images) ? images : [])
+ .map(normalizeImage)
+ .filter((it) => !it.hidden && it.filename);
+ setItems(normalized);
+ })
+ .catch(() => { if (!cancelled) setItems([]); })
+ .finally(() => { if (!cancelled) setLoading(false); });
+ return () => { cancelled = true; };
+ }, []);
+
+ const haystacks = useMemo(() => items.map(buildMediaHaystack), [items]);
+ const tokens = useMemo(() => tokenizeQuery(query), [query]);
+ const filtered = useMemo(
+ () => (tokens.length === 0 ? items : items.filter((_, idx) => matchHaystack(haystacks[idx], tokens))),
+ [items, haystacks, tokens],
+ );
+
+ const toggle = (filename) => {
+ setSelected((prev) => {
+ if (prev.includes(filename)) return prev.filter((f) => f !== filename);
+ if (prev.length >= MAX_IMPORT) {
+ toast.error(`Import up to ${MAX_IMPORT} at a time`);
+ return prev;
+ }
+ return [...prev, filename];
+ });
+ };
+
+ const doImport = async () => {
+ if (!selected.length) return;
+ setImporting(true);
+ try {
+ const { images } = await importLoraDatasetGalleryImages(dataset.id, selected);
+ toast.success(`Imported ${images.length} image${images.length === 1 ? '' : 's'} — caption them next`);
+ onImported?.(images);
+ } finally {
+ setImporting(false);
+ }
+ };
+
+ return (
+ <Modal
+ open
+ onClose={onClose}
+ size="3xl"
+ panelClassName="bg-port-card border border-port-border rounded-xl max-h-[85vh] flex flex-col"
+ ariaLabel="Import images from your gallery"
+ >
+ <div className="flex items-center justify-between gap-3 p-3 border-b border-port-border">
+ <h2 className="text-sm font-medium text-white shrink-0">Import from gallery</h2>
+ <div className="relative flex-1 max-w-md">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500" />
+ <input
+ type="text"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search prompt, model, seed, LoRA…"
+ 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>
+ <button
+ type="button"
+ onClick={onClose}
+ className="shrink-0 p-1.5 text-gray-400 hover:text-white rounded"
+ aria-label="Close"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </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 gallery…
+ </div>
+ ) : filtered.length === 0 ? (
+ <div className="text-xs text-gray-500 py-10 text-center">
+ {items.length === 0 ? 'No images in your gallery yet.' : 'No images 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) => {
+ const idx = selected.indexOf(item.filename);
+ return (
+ <MediaCard
+ key={item.key}
+ item={item}
+ hideActions
+ showCollectionMenu={false}
+ selected={idx !== -1}
+ selectionLabel={idx !== -1 ? String(idx + 1) : null}
+ onClick={() => toggle(item.filename)}
+ />
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center justify-between gap-3 p-3 border-t border-port-border">
+ <span className="text-xs text-gray-400">
+ {selected.length ? `${selected.length} selected` : 'Click images to select'}
+ </span>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={onClose}
+ className="px-3 py-2 text-sm text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={doImport}
+ disabled={!selected.length || importing}
+ className="px-3 py-2 text-sm rounded bg-port-accent text-white disabled:opacity-50 flex items-center gap-2"
+ >
+ {importing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
+ Import {selected.length || ''}
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index 650a2e18c7..85ad05d04e 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -10,7 +10,7 @@
import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import { useParams, Link } from 'react-router-dom';
import {
- ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, AlertTriangle,
+ ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, AlertTriangle, Images,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal';
@@ -18,6 +18,8 @@ import { useSseProgress } from '../hooks/useSseProgress';
import DatasetImageGrid from '../components/loraTraining/DatasetImageGrid';
import GenerateBatchDialog from '../components/loraTraining/GenerateBatchDialog';
import TrainingPanel from '../components/loraTraining/TrainingPanel';
+import CaptionModelPicker from '../components/loraTraining/CaptionModelPicker';
+import ImportGalleryDialog from '../components/loraTraining/ImportGalleryDialog';
import {
getLoraDataset,
patchLoraDataset,
@@ -134,8 +136,13 @@ export default function LoraDatasetDetail() {
const [uploading, setUploading] = useState(false);
const [showGenerate, setShowGenerate] = useState(false);
const [showSlice, setShowSlice] = useState(false);
+ const [showImport, setShowImport] = useState(false);
const [captionRun, setCaptionRun] = useState(null);
const [captionStarting, setCaptionStarting] = useState(false);
+ // Chosen caption model { providerId, model } — null fields mean "let the
+ // server auto-pick a vision model". Lifted from CaptionModelPicker so caption
+ // runs pass the explicit selection.
+ const [captionModel, setCaptionModel] = useState({ providerId: null, model: null });
const fileInputRef = useRef(null);
const refresh = useCallback(() => getLoraDataset(datasetId)
@@ -213,10 +220,21 @@ export default function LoraDatasetDetail() {
}
};
+ // Stable so CaptionModelPicker's run-once effect doesn't re-fire.
+ const onCaptionModelChange = useCallback((sel) => setCaptionModel(sel), []);
+
+ // Strip null provider/model so an "Auto" selection sends an empty body and
+ // the server resolves a vision model itself.
+ const captionOptions = (extra = {}) => ({
+ ...extra,
+ ...(captionModel.providerId ? { providerId: captionModel.providerId } : {}),
+ ...(captionModel.model ? { model: captionModel.model } : {}),
+ });
+
const captionAll = async () => {
setCaptionStarting(true);
try {
- const run = await startLoraCaptionRun(datasetId, { overwrite: false });
+ const run = await startLoraCaptionRun(datasetId, captionOptions({ overwrite: false }));
setCaptionRun(run);
} finally {
setCaptionStarting(false);
@@ -300,6 +318,13 @@ export default function LoraDatasetDetail() {
>
{uploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />} Upload
</button>
+ <button
+ type="button"
+ onClick={() => setShowImport(true)}
+ className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2"
+ >
+ <Images className="w-4 h-4" /> From gallery
+ </button>
<input
ref={fileInputRef}
type="file"
@@ -328,6 +353,7 @@ export default function LoraDatasetDetail() {
? `Captioning ${captionSse.latest?.done ?? 0}/${captionSse.latest?.total ?? '…'}`
: 'Caption all'}
</button>
+ <CaptionModelPicker onChange={onCaptionModelChange} />
</div>
<div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-4 items-start">
@@ -335,6 +361,7 @@ export default function LoraDatasetDetail() {
dataset={dataset}
onImagesChange={onImagesChange}
onCaptionRunStarted={setCaptionRun}
+ captionModel={captionModel}
/>
<TrainingPanel
dataset={dataset}
@@ -360,6 +387,17 @@ export default function LoraDatasetDetail() {
onSliced={() => { setShowSlice(false); refresh(); }}
/>
)}
+ {showImport && (
+ <ImportGalleryDialog
+ dataset={dataset}
+ onClose={() => setShowImport(false)}
+ onImported={(images) => {
+ setShowImport(false);
+ if (images?.length) onImagesChange((prev) => [...prev, ...images]);
+ refresh();
+ }}
+ />
+ )}
</div>
);
}
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index f9a2f8fbd7..ea0fe8d15a 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -4,6 +4,10 @@ import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
// Installed models per backend come back inside getLocalLlmStatus().
export const getLocalLlmStatus = (options) => request('/local-llm/status', options);
+// Vision-capable installed models across both backends, each tagged with the
+// provider id that serves it. Powers the LoRA caption-model picker.
+export const getVisionModels = (options) => request('/local-llm/vision-models', options);
+
export const getLocalLlmCatalog = (backend, q = '') =>
request(`/local-llm/catalog?backend=${encodeURIComponent(backend)}${q ? `&q=${encodeURIComponent(q)}` : ''}`);
diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.js
index a0d98e60d2..e6df504750 100644
--- a/client/src/services/apiLoraTraining.js
+++ b/client/src/services/apiLoraTraining.js
@@ -38,6 +38,12 @@ export const uploadLoraDatasetImages = (id, files) => {
return request(`/lora-datasets/${id}/images`, { method: 'POST', body: form });
};
+// Import existing gallery images (basenames) into the dataset.
+export const importLoraDatasetGalleryImages = (id, filenames) =>
+ request(`/lora-datasets/${id}/import-gallery`, {
+ method: 'POST', body: JSON.stringify({ filenames }),
+ });
+
export const generateLoraDatasetImages = (id, options = {}) =>
request(`/lora-datasets/${id}/generate`, { method: 'POST', body: JSON.stringify(options) });
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index fd46396005..47751cab53 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -43,6 +43,21 @@ export const isEmbeddingModel = (id) =>
typeof id === 'string' && id.length > 0 &&
/(?:^|[-_/:])(?:embed|embedding|bge|nomic|mxbai|gte|e5|snowflake-arctic-embed)(?:[-_/:]|$)|text-embedding/i.test(id);
+/**
+ * Vision-capable (multimodal) model detector — mirror of `isVisionModel` in
+ * server/lib/localModelHeuristics.js (id-regex branch only). Keep the regex in
+ * lockstep with the server. Used to flag/select vision models in the LoRA
+ * caption picker. The server prefers explicit backend capability metadata
+ * (`vision: true` on the model card); use that field when you have it and fall
+ * back to this for bare id strings.
+ * @param {string} id
+ * @returns {boolean}
+ */
+export const isVisionModel = (id) =>
+ typeof id === 'string' && id.length > 0 &&
+ // Mirror of VISION_RE in server/lib/localModelHeuristics.js — keep in lockstep.
+ /(?:^|[-_/:])vision(?:[-_/:.]|$)|(?:^|[-_/:])vl(?:\d|[-_/:.]|$)|llava|bakllava|moondream|minicpm-?v|pixtral|gemma-?3|smolvlm|internvl|cogvlm|glm-?4v|phi-?3\.5?-vision|phi-?4-multimodal|got-ocr|idefics|fuyu|paligemma|kosmos|nanollava/i.test(id);
+
/**
* Selectable models for a generation/chat picker: drops internal sentinels AND
* embedding-only models. Use anywhere the user picks a model that will run a
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 07d575a284..efa017ef40 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -6,6 +6,7 @@ import {
filterSelectableModels,
filterGenerationModels,
isEmbeddingModel,
+ isVisionModel,
localBackendForProvider,
mergeModelLists,
modelOptionLabel,
@@ -198,6 +199,24 @@ describe('isEmbeddingModel / filterGenerationModels', () => {
});
});
+describe('isVisionModel (mirror of server localModelHeuristics)', () => {
+ it('flags known vision model ids', () => {
+ for (const id of [
+ 'qwen2.5-vl:7b', 'llava:latest', 'moondream:latest', 'minicpm-v:8b',
+ 'llama3.2-vision:11b', 'pixtral-12b', 'gemma3:4b', 'internvl2:8b', 'glm-4v:9b',
+ ]) {
+ expect(isVisionModel(id), id).toBe(true);
+ }
+ });
+
+ it('does not flag text-only models or non-strings', () => {
+ for (const id of ['llama3.1:8b', 'qwen2.5:7b', 'gpt-oss:20b', '']) {
+ expect(isVisionModel(id), id).toBe(false);
+ }
+ expect(isVisionModel(null)).toBe(false);
+ });
+});
+
describe('localBackendForProvider', () => {
it('detects Ollama by endpoint or name', () => {
expect(localBackendForProvider({ endpoint: 'http://localhost:11434/v1' })).toBe('ollama');
diff --git a/server/lib/README.md b/server/lib/README.md
index aedb95e928..66bc91c62b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -179,7 +179,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `civitai.js` | Civitai URL parsing + API client. |
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection). |
-| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel` in `client/src/utils/providers.js`. |
+| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
diff --git a/server/lib/localModelHeuristics.js b/server/lib/localModelHeuristics.js
index 6b78b2de2b..e2e37bef7c 100644
--- a/server/lib/localModelHeuristics.js
+++ b/server/lib/localModelHeuristics.js
@@ -9,8 +9,9 @@
* generation/fallback run — the cause of the nomic-embed-text fallback bug)
* - localLlm.getStatus (recommend a best-fit editorial model)
*
- * The client mirrors `isEmbeddingModel` in client/src/utils/providers.js — keep
- * the two regexes in lockstep (the aiToolkit/lib dirs can't be imported there).
+ * The client mirrors `isEmbeddingModel` + `isVisionModel` in
+ * client/src/utils/providers.js — keep the regexes in lockstep (the
+ * aiToolkit/lib dirs can't be imported there).
*/
// Embedding-only models — never valid for chat/generation. The bge/nomic/e5/gte
@@ -35,6 +36,47 @@ export function isGenerationModel(id) {
return typeof id === 'string' && id.length > 0 && !isEmbeddingModel(id);
}
+// Vision / multimodal (VLM) model id markers. These are the families that
+// accept image content blocks on an OpenAI-compatible /chat/completions call.
+// Two groups:
+// - Short/ambiguous tokens (`vision`, `vl`) must be token-bounded so they
+// don't match mid-word (`vl` is the Qwen-VL/InternVL suffix). `vl` requires
+// a leading boundary and a trailing boundary-or-digit (`internvl2`).
+// - Distinctive family names are matched as plain substrings — they're
+// unique enough that an interior version digit (`internvl2`, `glm-4v`)
+// shouldn't defeat the match.
+const VISION_RE = new RegExp([
+ '(?:^|[-_/:])vision(?:[-_/:.]|$)',
+ '(?:^|[-_/:])vl(?:\\d|[-_/:.]|$)',
+ 'llava', 'bakllava', 'moondream', 'minicpm-?v', 'pixtral', 'gemma-?3',
+ 'smolvlm', 'internvl', 'cogvlm', 'glm-?4v', 'phi-?3\\.5?-vision',
+ 'phi-?4-multimodal', 'got-ocr', 'idefics', 'fuyu', 'paligemma',
+ 'kosmos', 'nanollava',
+].join('|'), 'i');
+
+/**
+ * Detect a vision-capable (multimodal) model from its id and/or backend
+ * capability metadata. Prefers explicit metadata when present — LM Studio's
+ * native `/api/v0/models` tags vision models with `type: 'vlm'`, and Ollama's
+ * `/api/show` reports a `vision` capability — and falls back to the id regex
+ * for backends that don't tag (or stored provider model lists that are just
+ * strings).
+ *
+ * @param {string|{id?:string,name?:string,type?:string,capabilities?:string[]}} model
+ * @returns {boolean}
+ */
+export function isVisionModel(model) {
+ if (!model) return false;
+ if (typeof model === 'string') return VISION_RE.test(model);
+ if (typeof model !== 'object') return false;
+ // Explicit metadata wins over the name heuristic.
+ if (model.type && String(model.type).toLowerCase() === 'vlm') return true;
+ if (Array.isArray(model.capabilities)
+ && model.capabilities.some((c) => String(c).toLowerCase() === 'vision')) return true;
+ const id = model.id || model.name || '';
+ return typeof id === 'string' && VISION_RE.test(id);
+}
+
// Families ranked for EDITORIAL FIX GENERATION, best-first. This task needs
// tight instruction-following and clean, constrained output (rewrite a passage,
// emit only the rewrite) — NOT chatty long-form generation. So instruction-tuned
diff --git a/server/lib/localModelHeuristics.test.js b/server/lib/localModelHeuristics.test.js
index 7741fbc9cf..0db0ad476b 100644
--- a/server/lib/localModelHeuristics.test.js
+++ b/server/lib/localModelHeuristics.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { isEmbeddingModel, isGenerationModel, recommendEditorialModel } from './localModelHeuristics.js';
+import { isEmbeddingModel, isGenerationModel, isVisionModel, recommendEditorialModel } from './localModelHeuristics.js';
describe('localModelHeuristics', () => {
describe('isEmbeddingModel', () => {
@@ -42,6 +42,53 @@ describe('localModelHeuristics', () => {
});
});
+ describe('isVisionModel', () => {
+ it('flags known vision/multimodal model ids', () => {
+ for (const id of [
+ 'qwen2.5-vl:7b',
+ 'llava:latest',
+ 'bakllava',
+ 'moondream:latest',
+ 'minicpm-v:8b',
+ 'llama3.2-vision:11b',
+ 'pixtral-12b',
+ 'gemma3:4b',
+ 'internvl2:8b',
+ 'glm-4v:9b',
+ 'paligemma',
+ ]) {
+ expect(isVisionModel(id), id).toBe(true);
+ }
+ });
+
+ it('does not flag text-only models', () => {
+ for (const id of [
+ 'llama3.1:8b',
+ 'qwen2.5:7b',
+ 'gpt-oss:20b',
+ 'mistral-small:latest',
+ 'nomic-embed-text:latest',
+ ]) {
+ expect(isVisionModel(id), id).toBe(false);
+ }
+ });
+
+ it('prefers explicit backend capability metadata over the id heuristic', () => {
+ // LM Studio tags vision models type: 'vlm' even when the id is opaque.
+ expect(isVisionModel({ id: 'some-opaque-id', type: 'vlm' })).toBe(true);
+ expect(isVisionModel({ id: 'x', capabilities: ['vision'] })).toBe(true);
+ // A text model card with no vision markers stays false.
+ expect(isVisionModel({ id: 'llama3.1:8b', type: 'llm' })).toBe(false);
+ });
+
+ it('handles non-values', () => {
+ expect(isVisionModel(null)).toBe(false);
+ expect(isVisionModel(undefined)).toBe(false);
+ expect(isVisionModel('')).toBe(false);
+ expect(isVisionModel(42)).toBe(false);
+ });
+ });
+
describe('recommendEditorialModel', () => {
it('prefers a large general instruct model over a small one', () => {
const rec = recommendEditorialModel([
diff --git a/server/lib/loraDataset.js b/server/lib/loraDataset.js
index 1c5d23618c..644cc01060 100644
--- a/server/lib/loraDataset.js
+++ b/server/lib/loraDataset.js
@@ -18,7 +18,7 @@ export const LORA_DATASET_SCHEMA_VERSION = 1;
// ~10 images a character LoRA badly overfits the few poses it has seen.
export const MIN_TRAINING_IMAGES = 10;
-export const DATASET_IMAGE_SOURCES = Object.freeze(['generated', 'upload', 'refsheet-slice']);
+export const DATASET_IMAGE_SOURCES = Object.freeze(['generated', 'upload', 'refsheet-slice', 'gallery']);
export const DATASET_IMAGE_STATUSES = Object.freeze(['rendering', 'ready', 'failed']);
export const DATASET_STATUSES = Object.freeze(['draft', 'training', 'trained']);
export const CAPTION_SOURCES = Object.freeze(['vision', 'manual']);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 8f2e475103..d25e84c95a 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -839,7 +839,9 @@ const loraTrainingParamsSchema = z.object({
// provider pick + training parameter defaults. Code-level defaults live in
// `services/loraTraining/runtimes.js` so an absent slice needs no migration.
export const loraTrainingConfigSchema = z.object({
- captionProviderId: z.string().max(128).optional(),
+ // Both nullable — the caption-model picker clears them to null on "Auto"
+ // (defer to the server's vision-model auto-pick).
+ captionProviderId: z.string().max(128).nullable().optional(),
captionModel: z.string().max(256).nullable().optional(),
defaults: loraTrainingParamsSchema.optional(),
});
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 533ec2fa3a..3b6eceb97c 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -26,7 +26,7 @@ import {
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import { searchHuggingFaceModels } from '../services/huggingFaceCatalog.js'
import {
- getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer
+ getStatus, listModels, listVisionModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer
} from '../services/localLlm.js'
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'
import { abortSignalFromResponse } from '../lib/requestAbort.js'
@@ -45,6 +45,13 @@ router.get('/status', asyncHandler(async (req, res) => {
res.json(await getStatus())
}))
+// GET /api/local-llm/vision-models — vision-capable installed models across
+// both backends, tagged with the provider id that serves them. Powers the
+// LoRA caption-model picker.
+router.get('/vision-models', asyncHandler(async (_req, res) => {
+ res.json({ models: await listVisionModels() })
+}))
+
// GET /api/local-llm/catalog?backend=ollama&q=llama — curated install picker
router.get('/catalog', asyncHandler(async (req, res) => {
const { backend, q } = req.query
diff --git a/server/routes/loraDatasets.js b/server/routes/loraDatasets.js
index 025cb00fdf..17f45d32c1 100644
--- a/server/routes/loraDatasets.js
+++ b/server/routes/loraDatasets.js
@@ -19,6 +19,7 @@ import {
deleteDataset,
deleteImage,
getDataset,
+ importGalleryImages,
listDatasets,
patchDataset,
reconcileRenderingImages,
@@ -96,6 +97,17 @@ router.post('/:id/images', datasetUploads, asyncHandler(async (req, res) => {
res.status(201).json({ images: entries });
}));
+// Import existing gallery images into the dataset by basename. The server
+// re-normalizes each through sharp (gallery PNGs are `<jobId>.png`).
+const importGallerySchema = z.object({
+ filenames: z.array(z.string().max(256).regex(/^[^/\\]+\.png$/i, 'filename must be a gallery PNG basename')).min(1).max(50),
+});
+router.post('/:id/import-gallery', asyncHandler(async (req, res) => {
+ const { filenames } = validateRequest(importGallerySchema, req.body);
+ const images = await importGalleryImages(req.params.id, { filenames });
+ res.status(201).json({ images });
+}));
+
const generateSchema = z.object({
count: z.number().int().min(1).max(40).default(12),
views: z.array(z.string().max(120)).max(12).optional(),
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index bbdde584dd..97ca7ecc59 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -31,7 +31,7 @@ import { Readable } from 'stream'
import { PATHS, atomicWrite } from '../lib/fileUtils.js'
import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'
import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
-import { recommendEditorialModel } from '../lib/localModelHeuristics.js'
+import { recommendEditorialModel, isVisionModel } from '../lib/localModelHeuristics.js'
import * as ollamaManager from './ollamaManager.js'
import * as lmStudioManager from './lmStudioManager.js'
import { getProviderById, updateProvider } from './providers.js'
@@ -551,13 +551,19 @@ function normalizeModels(backend, models) {
return models.map((m) => ({
id: m.id, name: m.name, size: m.size ?? null,
params: m.params || null, quantization: m.quantization || null, family: m.family || null,
- contextLength: m.contextLength ?? null
+ contextLength: m.contextLength ?? null,
+ // Ollama's /api/tags doesn't tag vision capability, so this is the id
+ // heuristic only (no explicit metadata to prefer).
+ vision: isVisionModel(m.id)
}))
}
return models.map((m) => ({
id: m.id, name: m.id, size: null,
params: null, quantization: m.quantization || null, family: m.arch || null,
- contextLength: m.maxContextLength ?? null
+ contextLength: m.maxContextLength ?? null,
+ // LM Studio's native model list tags vision models `type: 'vlm'` — prefer
+ // that over the id regex.
+ vision: isVisionModel(m)
}))
}
@@ -626,6 +632,26 @@ export async function getStatus() {
}
}
+/**
+ * Vision-capable installed models across both local backends, tagged with the
+ * aiToolkit provider id (`ollama` / `lmstudio`) that serves them. Powers the
+ * caption-model picker and the captioner's auto-resolution of a default vision
+ * model. Each entry: `{ providerId, backend, id, name, vision: true }`.
+ */
+export async function listVisionModels() {
+ // Cache-first for both backends (the model-list caches are busted on
+ // install/delete, so they stay accurate) — the picker doesn't need a forced
+ // round-trip on every dataset-page load.
+ const [ollama, lmstudio] = await Promise.all([
+ listModels('ollama').catch(() => []),
+ listModels('lmstudio').catch(() => [])
+ ])
+ const tag = (backend, models) => models
+ .filter((m) => m.vision)
+ .map((m) => ({ providerId: PROVIDER_ID[backend], backend, id: m.id, name: m.name || m.id, vision: true }))
+ return [...tag('ollama', ollama), ...tag('lmstudio', lmstudio)]
+}
+
// ---- install / delete --------------------------------------------------------
/**
diff --git a/server/services/loraDatasetCaption.js b/server/services/loraDatasetCaption.js
index 7cde27d44f..757e280e9d 100644
--- a/server/services/loraDatasetCaption.js
+++ b/server/services/loraDatasetCaption.js
@@ -9,8 +9,12 @@
* subscribes via `GET /api/lora-datasets/:id/caption-runs/:runId/events`
* and refetches the dataset on the terminal frame.
*
- * Provider resolution: request override → `settings.loraTraining.captionProviderId`
- * → 'lmstudio' (the default local vision backend).
+ * Provider/model resolution: request override → `settings.loraTraining.*`
+ * → a vision-capable installed model auto-picked across the local backends.
+ * A vision model is *required* — captioning sends image content blocks, so a
+ * text-only model would 400 per image with a cryptic "Model does not support
+ * images". We resolve (and validate) a vision model up front and fail the whole
+ * run with one actionable error instead.
*/
import { readFile } from 'fs/promises';
@@ -21,6 +25,8 @@ import { prefixCaption } from '../lib/loraDataset.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';
import { describeImageDataUrl } from './visionTest.js';
import { getSettings } from './settings.js';
+import { listVisionModels } from './localLlm.js';
+import { isVisionModel } from '../lib/localModelHeuristics.js';
import { getDataset, updateDataset, datasetImagePath } from './loraDatasets.js';
export const CAPTION_PROMPT = [
@@ -39,6 +45,60 @@ const captionRuns = new Map();
export const attachCaptionSseClient = (runId, res) => attachSse(captionRuns, runId, res);
+/**
+ * Resolve which provider+model the run captions with, requiring a
+ * vision-capable model. Precedence:
+ * 1. Explicit request override (providerId/model from the UI picker).
+ * 2. Saved `settings.loraTraining.captionProviderId/captionModel`.
+ * 3. Auto-pick the first vision-capable installed local model.
+ *
+ * An explicit non-vision model is rejected (the caller asked for it, so warn
+ * loudly rather than silently swap). When nothing is configured and no vision
+ * model is installed, throws a 409 with an actionable message — the run never
+ * starts, so the user doesn't get N cryptic per-image 400s.
+ *
+ * `listVision` is injectable for tests; defaults to the localLlm scan.
+ */
+export async function resolveCaptionModel({
+ providerId = null, model = null, settings = null, listVision = listVisionModels,
+} = {}) {
+ const explicitProvider = providerId || settings?.loraTraining?.captionProviderId || null;
+ const explicitModel = model || settings?.loraTraining?.captionModel || null;
+
+ if (explicitModel) {
+ // Heuristic-first: the common path (re-caption / caption-all with a picked
+ // model) passes a model the id regex already recognizes, so skip the
+ // two-backend vision scan entirely. Only scan when the id is opaque — then
+ // trust backend metadata (LM Studio `type:'vlm'`) before rejecting.
+ if (!isVisionModel(explicitModel)) {
+ const visionModels = await listVision().catch(() => []);
+ const known = visionModels.some((m) => m.id === explicitModel
+ && (!explicitProvider || m.providerId === explicitProvider));
+ if (!known) {
+ throw new ServerError(
+ `Caption model "${explicitModel}" is not vision-capable — pick a vision model (e.g. a Qwen-VL, LLaVA, or Llama 3.2 Vision build).`,
+ { status: 409, code: 'LORA_CAPTION_NOT_VISION' },
+ );
+ }
+ }
+ return { providerId: explicitProvider || 'lmstudio', model: explicitModel };
+ }
+
+ // No explicit model — scan and auto-pick a vision model (preferring the
+ // chosen provider when one was set).
+ const visionModels = await listVision().catch(() => []);
+ const pick = (explicitProvider
+ ? visionModels.find((m) => m.providerId === explicitProvider)
+ : null) || visionModels[0];
+ if (!pick) {
+ throw new ServerError(
+ 'No vision-capable model is installed for captioning. Install one (e.g. Qwen2.5-VL, LLaVA, or Llama 3.2 Vision) from Settings → Local LLM, then pick it on the dataset.',
+ { status: 409, code: 'LORA_CAPTION_NO_VISION_MODEL' },
+ );
+ }
+ return { providerId: pick.providerId, model: pick.id };
+}
+
const emit = (runId, payload) => {
const run = captionRuns.get(runId);
if (run) broadcastSse(run, payload);
@@ -68,12 +128,16 @@ export async function startCaptionRun(datasetId, {
}
const settings = await getSettings();
- const resolvedProvider = providerId || settings?.loraTraining?.captionProviderId || 'lmstudio';
- const resolvedModel = model || settings?.loraTraining?.captionModel || undefined;
+ // Resolve (and validate) a vision-capable model BEFORE creating the run, so a
+ // missing/non-vision model fails the request synchronously with one clear
+ // error instead of N per-image 400s inside the detached loop.
+ const { providerId: resolvedProvider, model: resolvedModel } = await resolveCaptionModel({
+ providerId, model, settings,
+ });
const runId = uuidv4();
captionRuns.set(runId, { clients: [], lastPayload: null });
- console.log(`🏷️ Caption run ${shortId(runId)} — dataset=${shortId(datasetId)} images=${targets.length} provider=${resolvedProvider}`);
+ console.log(`🏷️ Caption run ${shortId(runId)} — dataset=${shortId(datasetId)} images=${targets.length} provider=${resolvedProvider} model=${resolvedModel}`);
// Detached loop — runs outside the request lifecycle, so each iteration
// wraps its fallible work in try/catch (the async-boundary exception to
diff --git a/server/services/loraDatasets.js b/server/services/loraDatasets.js
index 2d476b8884..445ff4465c 100644
--- a/server/services/loraDatasets.js
+++ b/server/services/loraDatasets.js
@@ -14,9 +14,11 @@
*/
import { copyFile, unlink } from 'fs/promises';
+import { existsSync } from 'fs';
import { join, basename } from 'path';
import sharp from 'sharp';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { assertGalleryFilename } from './imageGen/local.js';
import { createCollectionStore } from '../lib/collectionStore.js';
import {
LORA_DATASET_SCHEMA_VERSION,
@@ -187,6 +189,23 @@ export async function deleteDataset(id) {
return { ok: true, id };
}
+/** Canonical dataset-image entry. One source of truth for the shape so every
+ * image source (upload / gallery import / generation) stamps identical fields. */
+const makeImageEntry = ({ imageId, file, source, info, sourceJobId = null }) => ({
+ id: imageId,
+ file,
+ caption: '',
+ captionSource: null,
+ captionedAt: null,
+ source,
+ sourceJobId,
+ variation: null,
+ status: 'ready',
+ width: info?.width || null,
+ height: info?.height || null,
+ createdAt: nowIso(),
+});
+
/**
* Normalize an uploaded image to PNG inside the dataset's images dir and
* append its entry. `tmpPath` is the multipart parser's staged temp file —
@@ -211,28 +230,52 @@ export async function addUploadedImage(id, { tmpPath, originalname = '' }) {
);
});
await cleanup();
- const width = info.width || null;
- const height = info.height || null;
- const entry = {
- id: imageId,
- file,
- caption: '',
- captionSource: null,
- captionedAt: null,
- source: 'upload',
- sourceJobId: null,
- variation: null,
- status: 'ready',
- width,
- height,
- createdAt: nowIso(),
- };
+ const entry = makeImageEntry({ imageId, file, source: 'upload', info });
await updateDataset(id, (current) => ({ ...current, images: [...current.images, entry] }));
- console.log(`📥 Dataset ${id} ← upload ${file} (${width}×${height})`);
+ console.log(`📥 Dataset ${id} ← upload ${file} (${entry.width}×${entry.height})`);
return entry;
}
+/**
+ * Import existing gallery images (by basename, e.g. `<jobId>.png`) into a
+ * dataset. Each is normalized through sharp into the dataset's images dir —
+ * same gate as a fresh upload — so a gallery PNG with odd metadata can't smuggle
+ * anything in, and the dataset owns an independent copy (deleting the gallery
+ * image later won't strand the dataset). Each call appends a fresh copy (no
+ * dedup — same as uploading the same file twice). Returns the appended entries.
+ */
+export async function importGalleryImages(id, { filenames = [] } = {}) {
+ await requireDataset(id);
+ if (!Array.isArray(filenames) || !filenames.length) {
+ throw new ServerError('No gallery filenames provided', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ await ensureDir(datasetImagesDir(id));
+ // sharp transcodes are independent CPU/disk work — run them concurrently
+ // (single-user trust model; the per-id write queue still serializes the one
+ // dataset mutation below). A single failure rejects the whole import.
+ const entries = await Promise.all(filenames.map(async (filename) => {
+ // Reuse the gallery's own path-traversal/extension guard.
+ assertGalleryFilename(filename);
+ const sourcePath = join(PATHS.images, basename(filename));
+ if (!existsSync(sourcePath)) {
+ throw new ServerError(`Gallery image not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
+ }
+ const imageId = uuidv4();
+ const file = `${imageId}.png`;
+ const info = await sharp(sourcePath).rotate().png().toFile(datasetImagePath(id, file)).catch((err) => {
+ throw new ServerError(
+ `"${filename}" is not a decodable image: ${err?.message || err}`,
+ { status: 422, code: 'INVALID_IMAGE' },
+ );
+ });
+ return makeImageEntry({ imageId, file, source: 'gallery', info });
+ }));
+ await updateDataset(id, (current) => ({ ...current, images: [...current.images, ...entries] }));
+ console.log(`🖼️ Dataset ${id} ← imported ${entries.length} gallery image(s)`);
+ return entries;
+}
+
export async function updateImageCaption(id, imageId, caption) {
const next = await updateDataset(id, (current) => {
if (!current.images.some((img) => img.id === imageId)) {
diff --git a/server/services/loraDatasets.test.js b/server/services/loraDatasets.test.js
index fe3dd45b78..a19ffdb671 100644
--- a/server/services/loraDatasets.test.js
+++ b/server/services/loraDatasets.test.js
@@ -32,6 +32,7 @@ const {
deleteImage,
datasetImagePath,
getDataset,
+ importGalleryImages,
listDatasets,
patchDataset,
reconcileRenderingImages,
@@ -224,6 +225,48 @@ describe('reconcileRenderingImages', () => {
});
});
+describe('importGalleryImages', () => {
+ const seedGallery = async (...filenames) => {
+ mkdirSync(join(TEST_DATA_ROOT, 'images'), { recursive: true });
+ for (const f of filenames) await makePng(join(TEST_DATA_ROOT, 'images', f));
+ };
+
+ it('imports gallery images as independent copies tagged source=gallery', async () => {
+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });
+ await seedGallery('aaaa.png', 'bbbb.png');
+ const images = await importGalleryImages(dataset.id, { filenames: ['aaaa.png', 'bbbb.png'] });
+ expect(images).toHaveLength(2);
+ for (const img of images) {
+ expect(img.source).toBe('gallery');
+ expect(img.status).toBe('ready');
+ expect(img.width).toBe(64);
+ expect(existsSync(datasetImagePath(dataset.id, img.file))).toBe(true);
+ }
+ // The copy is independent — the dataset image is NOT the gallery file.
+ expect(images[0].file).not.toBe('aaaa.png');
+ const after = await getDataset(dataset.id);
+ expect(after.images).toHaveLength(2);
+ });
+
+ it('404s when a gallery file is missing', async () => {
+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });
+ await expect(importGalleryImages(dataset.id, { filenames: ['ghost.png'] }))
+ .rejects.toMatchObject({ status: 404 });
+ });
+
+ it('rejects path-traversal filenames before touching disk', async () => {
+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });
+ await expect(importGalleryImages(dataset.id, { filenames: ['../../etc/passwd.png'] }))
+ .rejects.toBeTruthy();
+ });
+
+ it('400s on an empty filename list', async () => {
+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });
+ await expect(importGalleryImages(dataset.id, { filenames: [] }))
+ .rejects.toMatchObject({ status: 400 });
+ });
+});
+
describe('deleteDataset', () => {
it('removes the record and its images dir', async () => {
const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });