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

address review (claude): clean up orphaned import copies, cover resolveCaptionModel

[._.]/ Adam Eivy4d6425729305
diff --git a/client/src/components/loraTraining/ImportGalleryDialog.jsx b/client/src/components/loraTraining/ImportGalleryDialog.jsx
index dd2e98fcb8..786983e2da 100644
--- a/client/src/components/loraTraining/ImportGalleryDialog.jsx
+++ b/client/src/components/loraTraining/ImportGalleryDialog.jsx
@@ -67,6 +67,9 @@ export default function ImportGalleryDialog({ dataset, onClose, onImported }) {
const { images } = await importLoraDatasetGalleryImages(dataset.id, selected);
toast.success(`Imported ${images.length} image${images.length === 1 ? '' : 's'} — caption them next`);
onImported?.(images);
+ } catch {
+ // The api `request` helper already toasted the failure — swallow so the
+ // un-awaited onClick doesn't surface an unhandled promise rejection.
} finally {
setImporting(false);
}
diff --git a/server/services/loraDatasetCaption.js b/server/services/loraDatasetCaption.js
index 757e280e9d..5a1b9f3da7 100644
--- a/server/services/loraDatasetCaption.js
+++ b/server/services/loraDatasetCaption.js
@@ -57,6 +57,14 @@ export const attachCaptionSseClient = (runId, res) => attachSse(captionRuns, run
* 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.
*
+ * Known gap (intentional): the heuristic-first short-circuit accepts a
+ * regex-recognized explicit model WITHOUT confirming it's still installed —
+ * skipping the two-backend scan is the whole point of the fast path. So a saved
+ * `captionModel` that was later uninstalled slips past the up-front 409 and
+ * fails per-image at the API instead (surfaced by the run's terminal error).
+ * Validating every run against the live model list would defeat the fast path;
+ * the picker's own list is the primary defense against a stale selection.
+ *
* `listVision` is injectable for tests; defaults to the localLlm scan.
*/
export async function resolveCaptionModel({
diff --git a/server/services/loraDatasetCaption.test.js b/server/services/loraDatasetCaption.test.js
new file mode 100644
index 0000000000..02fd1d7712
--- /dev/null
+++ b/server/services/loraDatasetCaption.test.js
@@ -0,0 +1,65 @@
+import { describe, it, expect, vi } from 'vitest';
+
+// resolveCaptionModel takes an injectable `listVision`, so the resolution
+// branches are testable without touching the network/DB. The module still
+// pulls in localLlm transitively at import; that's import-only (no calls fire
+// until resolveCaptionModel runs with our stub), so no mocks are needed.
+const { resolveCaptionModel } = await import('./loraDatasetCaption.js');
+
+const VISION = [
+ { providerId: 'lmstudio', backend: 'lmstudio', id: 'qwen2.5-vl-7b', name: 'Qwen2.5-VL 7B', vision: true },
+ { providerId: 'ollama', backend: 'ollama', id: 'opaque-vlm-id', name: 'Opaque VLM', vision: true },
+];
+
+describe('resolveCaptionModel', () => {
+ it('short-circuits an explicit regex-recognized vision model WITHOUT scanning', async () => {
+ const listVision = vi.fn(async () => VISION);
+ const out = await resolveCaptionModel({ providerId: 'ollama', model: 'llava:latest', listVision });
+ expect(out).toEqual({ providerId: 'ollama', model: 'llava:latest' });
+ expect(listVision).not.toHaveBeenCalled(); // heuristic-first fast path
+ });
+
+ it('accepts an explicit opaque id that the live scan confirms is vision-capable', async () => {
+ const listVision = vi.fn(async () => VISION);
+ const out = await resolveCaptionModel({ providerId: 'ollama', model: 'opaque-vlm-id', listVision });
+ expect(out).toEqual({ providerId: 'ollama', model: 'opaque-vlm-id' });
+ expect(listVision).toHaveBeenCalledOnce();
+ });
+
+ it('rejects an explicit non-vision model the scan does not know with a 409', async () => {
+ const listVision = vi.fn(async () => VISION);
+ await expect(resolveCaptionModel({ model: 'llama3.1:8b', listVision }))
+ .rejects.toMatchObject({ status: 409, code: 'LORA_CAPTION_NOT_VISION' });
+ });
+
+ it('reads the explicit model/provider from settings when not passed directly', async () => {
+ const listVision = vi.fn(async () => VISION);
+ const settings = { loraTraining: { captionProviderId: 'lmstudio', captionModel: 'qwen2.5-vl-7b' } };
+ const out = await resolveCaptionModel({ settings, listVision });
+ expect(out).toEqual({ providerId: 'lmstudio', model: 'qwen2.5-vl-7b' });
+ });
+
+ it('auto-picks the first vision model when nothing is configured', async () => {
+ const listVision = vi.fn(async () => VISION);
+ const out = await resolveCaptionModel({ listVision });
+ expect(out).toEqual({ providerId: 'lmstudio', model: 'qwen2.5-vl-7b' });
+ });
+
+ it('auto-pick prefers a model from the chosen provider over the list head', async () => {
+ const listVision = vi.fn(async () => VISION);
+ const out = await resolveCaptionModel({ providerId: 'ollama', listVision });
+ expect(out).toEqual({ providerId: 'ollama', model: 'opaque-vlm-id' });
+ });
+
+ it('throws a 409 when no vision model is installed', async () => {
+ const listVision = vi.fn(async () => []);
+ await expect(resolveCaptionModel({ listVision }))
+ .rejects.toMatchObject({ status: 409, code: 'LORA_CAPTION_NO_VISION_MODEL' });
+ });
+
+ it('treats a failed vision scan as no models installed (409, not a crash)', async () => {
+ const listVision = vi.fn(async () => { throw new Error('backend down'); });
+ await expect(resolveCaptionModel({ listVision }))
+ .rejects.toMatchObject({ status: 409, code: 'LORA_CAPTION_NO_VISION_MODEL' });
+ });
+});
diff --git a/server/services/loraDatasets.js b/server/services/loraDatasets.js
index 445ff4465c..9d69105586 100644
--- a/server/services/loraDatasets.js
+++ b/server/services/loraDatasets.js
@@ -253,7 +253,10 @@ export async function importGalleryImages(id, { filenames = [] } = {}) {
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.
+ // dataset mutation below). A single failure rejects the whole import; track
+ // every file actually written so a partial failure doesn't strand orphaned
+ // PNGs (written but never recorded in the dataset).
+ const written = [];
const entries = await Promise.all(filenames.map(async (filename) => {
// Reuse the gallery's own path-traversal/extension guard.
assertGalleryFilename(filename);
@@ -263,14 +266,20 @@ export async function importGalleryImages(id, { filenames = [] } = {}) {
}
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' },
- );
- });
+ const destPath = datasetImagePath(id, file);
+ const info = await sharp(sourcePath).rotate().png().toFile(destPath)
+ .then((i) => { written.push(destPath); return i; })
+ .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 });
- }));
+ })).catch(async (err) => {
+ await Promise.all(written.map((p) => unlink(p).catch(() => {})));
+ throw err;
+ });
await updateDataset(id, (current) => ({ ...current, images: [...current.images, ...entries] }));
console.log(`🖼️ Dataset ${id} ← imported ${entries.length} gallery image(s)`);
return entries;
diff --git a/server/services/loraDatasets.test.js b/server/services/loraDatasets.test.js
index a19ffdb671..a9900edbd3 100644
--- a/server/services/loraDatasets.test.js
+++ b/server/services/loraDatasets.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
-import { mkdtempSync, rmSync, mkdirSync, existsSync } from 'fs';
+import { mkdtempSync, rmSync, mkdirSync, existsSync, readdirSync } from 'fs';
import { writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -265,6 +265,20 @@ describe('importGalleryImages', () => {
await expect(importGalleryImages(dataset.id, { filenames: [] }))
.rejects.toMatchObject({ status: 400 });
});
+
+ it('cleans up already-written copies when one image in the batch is missing', async () => {
+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });
+ await seedGallery('good1.png', 'good2.png'); // 'missing.png' intentionally absent
+ await expect(importGalleryImages(dataset.id, { filenames: ['good1.png', 'good2.png', 'missing.png'] }))
+ .rejects.toMatchObject({ status: 404 });
+ // The dataset records nothing on a partial failure...
+ const after = await getDataset(dataset.id);
+ expect(after.images).toHaveLength(0);
+ // ...and no orphaned PNGs are left in the dataset's images dir.
+ const imagesDir = join(TEST_DATA_ROOT, 'lora-datasets', dataset.id, 'images');
+ const leftover = existsSync(imagesDir) ? readdirSync(imagesDir) : [];
+ expect(leftover).toEqual([]);
+ });
});
describe('deleteDataset', () => {