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
fix(loras,image-gen): address Copilot review feedback across PR #213
Adam Eivyeb5b033287bd
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex fb72b0320c..f3a4c3556c 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -44,7 +44,9 @@ const DEFAULT_NEGATIVE = 'blurry, low quality, distorted, deformed, ugly, waterm// often phrases, so we don't tokenize). Returns the updated prompt or the// original if every trigger is already in.const appendTriggerWords = (prompt, words) => {- const list = (Array.isArray(words) ? words : []).filter((w) => typeof w === 'string' && w.trim());+ const list = (Array.isArray(words) ? words : [])+ .filter((w) => typeof w === 'string' && w.trim())+ .map((w) => w.trim());if (!list.length) return prompt;const haystack = String(prompt || '').toLowerCase();const fresh = list.filter((w) => !haystack.includes(w.toLowerCase()));@@ -1053,7 +1055,7 @@ export default function ImageGen() {</div></form>- <MediaJobsQueue kind="image" compact />+ <MediaJobsQueue kind="image" />{visibleGallery.length > 0 && (<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2">diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsxindex 964cb4976c..b985c69447 100644--- a/client/src/pages/Loras.jsx+++ b/client/src/pages/Loras.jsx@@ -85,11 +85,8 @@ export default function Loras() {await installLoraFromCivitai({ url, silent: true }).then((sidecar) => {toast.success(`Installed ${sidecar.name}`);- setLoras((prev) => [- { ...sidecar, sizeBytes: sidecar.file?.sizeKB ? sidecar.file.sizeKB * 1024 : null },- ...prev.filter((l) => l.filename !== sidecar.filename),- ]);setInstallUrl('');+ refresh();}).catch((err) => {// Early-access content is gated by Civitai membership, not by API@@ -320,7 +317,7 @@ function SuggestionCard({ card, installedFilenames, installingSuggestionKey, onI? card.runnerFamilies: (card.runnerFamily ? [card.runnerFamily] : []));const isInstalled = (versionId) => versionId != null- && [...installedFilenames].some((f) => f.includes(`-v${versionId}.safetensors`));+ && [...installedFilenames].some((f) => f.endsWith(`-v${versionId}.safetensors`));const isInstalling = (versionId) => installingSuggestionKey === `${card.modelId}-${versionId}`;return (<div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 47f33f6e09..0d41e0b696 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -1264,7 +1264,7 @@ export default function VideoGen() {)}/>- <MediaJobsQueue kind="video" compact />+ <MediaJobsQueue kind="video" />{visibleHistory.length > 0 && (<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2">diff --git a/scripts/lora_utils.py b/scripts/lora_utils.pyindex e0c9891cd3..a4342de359 100644--- a/scripts/lora_utils.py+++ b/scripts/lora_utils.py@@ -23,27 +23,28 @@ def apply_loras(pipe, lora_paths, lora_scales) -> None:file=sys.stderr,)return- adapter_names = []+ # Track (adapter_name, scale) together so a failed load at index i doesn't+ # shift the scale of every subsequent successfully-loaded LoRA.+ loaded = []for i, path in enumerate(lora_paths):adapter = f"lora_{i}"print(f"🎚️ loading LoRA: {Path(path).name} (adapter={adapter})", file=sys.stderr, flush=True)try:pipe.load_lora_weights(path, adapter_name=adapter)- adapter_names.append(adapter)+ raw = lora_scales[i] if i < len(lora_scales) else "1.0"+ try:+ scale = float(raw)+ except (TypeError, ValueError):+ scale = 1.0+ loaded.append((adapter, scale))except Exception as err:print(f"⚠️ LoRA load failed for {Path(path).name}: {type(err).__name__}: {err}",file=sys.stderr,)- if not adapter_names:+ if not loaded:return- scales = []- for i, _ in enumerate(adapter_names):- raw = lora_scales[i] if i < len(lora_scales) else "1.0"- try:- scales.append(float(raw))- except (TypeError, ValueError):- scales.append(1.0)+ adapter_names, scales = zip(*loaded)if hasattr(pipe, "set_adapters"):try:pipe.set_adapters(adapter_names, adapter_weights=scales)diff --git a/server/lib/civitai.js b/server/lib/civitai.jsindex a00a18aa19..80502dd0d1 100644--- a/server/lib/civitai.js+++ b/server/lib/civitai.js@@ -256,13 +256,22 @@ export const detectEarlyAccess = (version) => {// `<filename>.metadata.json`. Decoupled from fetchCivitaiModel so callers can// build it from a known model+version pair without a second API hit (the// install path already has both in hand).+// Maximum characters to persist for model description. Civitai descriptions+// can be several KB of markdown/HTML — truncating keeps sidecars lean without+// losing the first-glance summary text that the manager UI shows.+const DESCRIPTION_MAX_CHARS = 2000;+export const buildSidecar = ({ model, version, file, filename }) => {const previewImage = pickPreviewImage(version);const baseModel = version?.baseModel || null;+ const rawDesc = typeof model?.description === 'string' ? model.description : '';+ const description = rawDesc.length > DESCRIPTION_MAX_CHARS+ ? rawDesc.slice(0, DESCRIPTION_MAX_CHARS)+ : rawDesc;return {filename,name: model?.name || filename,- description: model?.description || '',+ description,civitai: {modelId: model?.id ?? null,versionId: version?.id ?? null,diff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.jsindex 7b5ff768cf..d3ca3907f1 100644--- a/server/lib/civitai.test.js+++ b/server/lib/civitai.test.js@@ -308,6 +308,35 @@ describe('buildSidecar', () => {expect(sc.triggerWords).toEqual([]);expect(sc.previewImageUrl).toBe(null);});+ it('truncates description to 2000 chars when the model description is long', () => {+ const longDesc = 'x'.repeat(5000);+ const sc = buildSidecar({+ model: { id: 1, name: 'Verbose', description: longDesc },+ version: { id: 2, baseModel: 'Flux.1 D' },+ file: {},+ filename: 'lora-verbose-v2.safetensors',+ });+ expect(sc.description.length).toBe(2000);+ expect(sc.description).toBe(longDesc.slice(0, 2000));+ });+ it('preserves description as-is when it is within the 2000-char limit', () => {+ const sc = buildSidecar({+ model: { id: 1, name: 'Short', description: 'A brief description.' },+ version: { id: 2, baseModel: 'Flux.1 D' },+ file: {},+ filename: 'lora-short-v2.safetensors',+ });+ expect(sc.description).toBe('A brief description.');+ });+ it('defaults description to empty string when absent or non-string', () => {+ const sc = buildSidecar({+ model: { id: 1, name: 'No Desc' },+ version: { id: 2, baseModel: 'Flux.1 D' },+ file: {},+ filename: 'lora-nodesc-v2.safetensors',+ });+ expect(sc.description).toBe('');+ });it('rejects NaN as a recommended scale (Number.isFinite guard)', () => {// `typeof NaN === 'number'` would silently pass, persisting NaN into// the sidecar; downstream multiplies by NaN producing black images.diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 4847fdb8bc..88882e1454 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -266,9 +266,6 @@ const appendNewlyShippedEntries = (userList, defaultList, shippedIds) => {}return { entries: result, newlyShipped };};-// Back-compat alias — kept so any external imports of the old name keep working.-const appendNewlyShippedVideoEntries = appendNewlyShippedEntries;-// Existing installs predate the `runtime` field on video entries — fill it// with 'mlx_video' (the legacy default) for known-legacy ids so the// dispatch in videoGen/local.js routes them through `python -mdiff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex f822519d45..9b1ebce30f 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -22,7 +22,7 @@ import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { getSettings, saveSettings } from '../services/settings.js';import { getHfToken, HF_TOKEN_REGEX } from '../lib/hfToken.js';-import { getImageModels, isFlux2 } from '../lib/mediaModels.js';+import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';import {REQUIRED_PACKAGES, detectPython, checkPackages, installPackages,isExternallyManaged, createVenv, isAllowedPython, pipNameFor,@@ -213,7 +213,7 @@ router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {const selectedModel = allModels.find((m) => m.id === data.modelId)?? allModels.find((m) => m.id === 'dev')?? allModels[0];- if (selectedModel && !isFlux2(selectedModel) && !py) {+ if (selectedModel && !isFlux2(selectedModel) && !isZImage(selectedModel) && !isErnie(selectedModel) && !py) {throw new ServerError('Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',{ status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex bda8059618..635f9333c8 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -215,6 +215,33 @@ describe('Image Gen Routes', () => {expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();});+ // z-image and ernie use the FLUX.2 venv — they must NOT require pythonPath.+ it('local mode with z-image model and missing pythonPath still enqueues (exempted)', async () => {+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local' } }); // no pythonPath+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'mock-image-job', position: 1, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a fox in a forest', modelId: 'z-image-turbo-bf16' });++ expect(response.status).toBe(200);+ expect(response.body.status).toBe('queued');+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalled();+ });++ it('local mode with ernie model and missing pythonPath still enqueues (exempted)', async () => {+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local' } }); // no pythonPath+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'mock-image-job', position: 1, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a wizard tower', modelId: 'ernie-image' });++ expect(response.status).toBe(200);+ expect(response.body.status).toBe('queued');+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalled();+ });+// Codex mode now goes through the mediaJobQueue (codex lane), so a// burst of writers-room storyboard renders queues against itself// instead of failing the second-and-onwards calls with 409diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.jsindex d753e48dfd..d89d2a1d84 100644--- a/server/routes/worldBuilder.js+++ b/server/routes/worldBuilder.js@@ -21,7 +21,7 @@ import { expandWorldTemplate } from '../services/worldBuilderExpand.js';import { enqueueJob } from '../services/mediaJobQueue/index.js';import { getSettings } from '../services/settings.js';import { createCollection, NAME_MAX_LENGTH as COLLECTION_NAME_MAX } from '../services/mediaCollections.js';-import { getImageModels, isFlux2 } from '../lib/mediaModels.js';+import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';const router = Router();@@ -183,7 +183,7 @@ router.post('/:id/render', asyncHandler(async (req, res) => {const selectedModel = allModels.find((m) => m.id === body.modelId)?? allModels.find((m) => m.id === 'dev')?? allModels[0];- if (selectedModel && !isFlux2(selectedModel) && !py) {+ if (selectedModel && !isFlux2(selectedModel) && !isZImage(selectedModel) && !isErnie(selectedModel) && !py) {throw new ServerError('Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',{ status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },diff --git a/server/routes/worldBuilder.test.js b/server/routes/worldBuilder.test.jsindex c7667e14d0..6eba136af4 100644--- a/server/routes/worldBuilder.test.js+++ b/server/routes/worldBuilder.test.js@@ -54,6 +54,8 @@ vi.mock('../services/mediaCollections.js', () => ({vi.mock('../lib/mediaModels.js', () => ({getImageModels: () => [{ id: 'dev', label: 'mflux dev' }],isFlux2: () => false,+ isZImage: () => false,+ isErnie: () => false,}));const worldBuilderRoutes = (await import('./worldBuilder.js')).default;diff --git a/server/services/civitaiSuggestions.js b/server/services/civitaiSuggestions.jsindex 874a5196a2..04df41740a 100644--- a/server/services/civitaiSuggestions.js+++ b/server/services/civitaiSuggestions.js@@ -148,7 +148,12 @@ const getCurated = async ({ fetchImpl, force = false }) => {return items;};-const fetchSuggestionsFor = async (runnerFamily, { fetchImpl, limit, force = false } = {}) => {+// Always fetch at MAX_SUGGESTIONS so any sub-slice request is served from+// the same cache entry without a re-fetch. The caller slices to its own+// `limit` after this returns.+const MAX_SUGGESTIONS = 24;++const fetchSuggestionsFor = async (runnerFamily, { fetchImpl, force = false } = {}) => {const cached = cache.get(runnerFamily);if (!force && cached && now() - cached.fetchedAt < TTL_MS) return cached.items;const apiKey = await resolveCivitaiKey();@@ -156,7 +161,7 @@ const fetchSuggestionsFor = async (runnerFamily, { fetchImpl, limit, force = fal// configured key gets cleaner ranking and avoids anonymous rate limits.const items = await searchCivitaiLoras({runnerFamily,- limit,+ limit: MAX_SUGGESTIONS,apiKey,fetchImpl,});@@ -174,12 +179,12 @@ export const getSuggestions = async ({ fetchImpl, limit = 4, force = false } = {const [curated, runnerEntries] = await Promise.all([getCurated({ fetchImpl, force }),Promise.all(RUNNER_FAMILIES.map(async (family) => {- const cards = await fetchSuggestionsFor(family, { fetchImpl, limit, force })+ const cards = await fetchSuggestionsFor(family, { fetchImpl, force }).catch((err) => {console.log(`⚠️ Civitai suggestion fetch failed for ${family}: ${err?.message || err}`);return cache.get(family)?.items || [];});- return [family, cards];+ return [family, cards.slice(0, limit)];})),]);return {diff --git a/server/services/civitaiSuggestions.test.js b/server/services/civitaiSuggestions.test.jsindex f8ee3d85fc..5c47204d81 100644--- a/server/services/civitaiSuggestions.test.js+++ b/server/services/civitaiSuggestions.test.js@@ -86,6 +86,56 @@ describe('getSuggestions', () => {expect(calls).toBe(callsAfterFirst);});+ it('first call with small limit does not starve a later larger-limit call (always fetches at max)', async () => {+ const makeItems = (count) =>+ Array.from({ length: count }, (_, i) => buildModel(200 + i, `Lora-${i}`, 'Flux.1 D'));++ let fetchCalls = 0;+ const fetchImpl = async (url) => {+ const m = url.match(/api\/v1\/models\/(\d+)$/);+ if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Curated`, 'Flux.1 D') };+ fetchCalls += 1;+ return { ok: true, status: 200, json: async () => ({ items: makeItems(24) }) };+ };++ // First call uses limit=4 — cache is populated at MAX (24 entries).+ const first = await svc.getSuggestions({ fetchImpl, limit: 4 });+ expect(first.runners.mflux.length).toBe(4);++ // Second call asks for limit=20 — must come from the same cache entry (no re-fetch).+ const callsAfterFirst = fetchCalls;+ const second = await svc.getSuggestions({ fetchImpl, limit: 20 });+ expect(fetchCalls).toBe(callsAfterFirst); // cache hit — no new HTTP+ expect(second.runners.mflux.length).toBe(20);+ });++ it('cache hit at limit < cached size returns the requested slice without re-fetching', async () => {+ // Build 24 distinct models so we can confirm slicing works end-to-end.+ const makeItems = (count) =>+ Array.from({ length: count }, (_, i) => buildModel(100 + i, `Lora-${i}`, 'Flux.1 D'));++ let fetchCalls = 0;+ const fetchImpl = async (url) => {+ const m = url.match(/api\/v1\/models\/(\d+)$/);+ if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Curated`, 'Flux.1 D') };+ fetchCalls += 1;+ return { ok: true, status: 200, json: async () => ({ items: makeItems(24) }) };+ };++ // First call: limit=24 — populates cache with 24 cards.+ const first = await svc.getSuggestions({ fetchImpl, limit: 24 });+ const fetchCallsAfterFirst = fetchCalls;+ expect(first.runners.mflux.length).toBe(24);++ // Second call: limit=8 — should hit the cache and return 8, not re-fetch.+ const second = await svc.getSuggestions({ fetchImpl, limit: 8 });+ expect(fetchCalls).toBe(fetchCallsAfterFirst); // no additional HTTP calls+ expect(second.runners.mflux.length).toBe(8);+ // The 8 returned entries should be the first 8 from the original 24.+ expect(second.runners.mflux[0].modelId).toBe(first.runners.mflux[0].modelId);+ expect(second.runners.mflux[7].modelId).toBe(first.runners.mflux[7].modelId);+ });+it('force=true busts the cache', async () => {let calls = 0;const fetchImpl = async (url) => {diff --git a/server/services/loras.js b/server/services/loras.jsindex e09840528a..e9f01e76c1 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -16,7 +16,7 @@*/import { existsSync } from 'fs';-import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'fs/promises';+import { link, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'fs/promises';import { createWriteStream } from 'fs';import { randomBytes } from 'crypto';import { Readable } from 'stream';@@ -83,6 +83,11 @@ export const assertSafeLoraFilename = (filename) => {// so the manager UI can still render LoRAs the user dropped in pre-Civitai.export const listLoras = async () => {if (!existsSync(PATHS.loras)) return [];+ const lorasStat = await stat(PATHS.loras).catch(() => null);+ if (!lorasStat || !lorasStat.isDirectory()) {+ console.log(`⚠️ PATHS.loras exists but is not a directory: ${PATHS.loras}`);+ return [];+ }const files = await readdir(PATHS.loras);const safetensors = files.filter((f) => f.endsWith('.safetensors'));const out = await Promise.all(safetensors.map(async (filename) => {@@ -131,7 +136,16 @@ export const getLora = async (filename) => {throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });}const list = await listLoras();- return list.find((l) => l.filename === filename) || null;+ const lora = list.find((l) => l.filename === filename);+ if (!lora) {+ // File exists on disk but listLoras filtered it out — most likely because+ // it's not a regular .safetensors file (directory, symlink, etc.).+ throw new ServerError(+ `LoRA "${filename}" exists but is not a valid regular .safetensors file`,+ { status: 404, code: 'NOT_FOUND' },+ );+ }+ return lora;};export const deleteLora = async (filename) => {@@ -140,6 +154,13 @@ export const deleteLora = async (filename) => {if (!existsSync(filePath)) {throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });}+ const s = await stat(filePath).catch(() => null);+ if (!s || !s.isFile()) {+ throw new ServerError(+ `Cannot delete "${filename}": not a regular file`,+ { status: 400, code: 'INVALID_LORA_FILE' },+ );+ }await rm(filePath, { force: true });await rm(sidecarPath(filename), { force: true });console.log(`🗑️ Deleted LoRA: ${filename}`);@@ -189,7 +210,7 @@ const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} ,// already set; surface both possibilities instead.const message = hasApiKey? `Civitai rejected the download (${res.status}) even with your saved API key. The LoRA is likely in early-access (Civitai supporters only) or your key has expired/been revoked.`- : `Civitai download rejected (${res.status}) — this LoRA may require an API key. Set CIVITAI_API_KEY in Settings and retry.`;+ : `Civitai download rejected (${res.status}) — this LoRA may require an API key. Configure a Civitai API key in PortOS Settings (or set the CIVITAI_API_KEY env var) and retry.`;throw new ServerError(message, { status: res.status, code: 'CIVITAI_AUTH' });}throw new ServerError(`Civitai download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'CIVITAI_DOWNLOAD_FAILED' });@@ -206,8 +227,26 @@ const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} ,await rm(tmpPath, { force: true }).catch(() => {});throw err;});- // rename can also fail (cross-device, locked dest, AV scan, low disk) —- // wrap separately so the .partial doesn't leak in any failure mode.+ // Atomic no-clobber finalize: `link` is POSIX-atomic and fails with EEXIST+ // when destPath already exists (concurrent install that snuck past our+ // pre-check). On success we unlink the tmp; on EEXIST we clean up and+ // throw CIVITAI_ALREADY_INSTALLED. For other link errors (cross-device+ // EXDEV, read-only fs, etc.) fall back to rename, which is the only+ // portable option on those platforms.+ const linkErr = await link(tmpPath, destPath).catch((e) => e);+ if (!linkErr) {+ await unlink(tmpPath).catch(() => {});+ return;+ }+ if (linkErr.code === 'EEXIST') {+ await rm(tmpPath, { force: true }).catch(() => {});+ const basename_ = destPath.split('/').pop();+ throw new ServerError(+ `Already installed: ${basename_}. Delete it first or pick a different version.`,+ { status: 409, code: 'CIVITAI_ALREADY_INSTALLED' },+ );+ }+ // EXDEV or similar — fall back to rename (best-effort, not atomic).await rename(tmpPath, destPath).catch(async (err) => {await rm(tmpPath, { force: true }).catch(() => {});throw err;diff --git a/server/services/loras.test.js b/server/services/loras.test.jsindex 72dab589cf..a0b9ce1323 100644--- a/server/services/loras.test.js+++ b/server/services/loras.test.js@@ -69,6 +69,14 @@ describe('listLoras', () => {expect(legacy.recommendedScale).toBe(1.0);});+ it('returns [] when PATHS.loras is a file, not a directory', async () => {+ const fs = await import('fs/promises');+ // Write a plain file at the loras path — stat will show isDirectory()=false.+ await fs.mkdir(tmpRoot, { recursive: true });+ await fs.writeFile(tmpLoras, 'not-a-directory');+ expect(await lorasService.listLoras()).toEqual([]);+ });+it('survives an unparseable sidecar', async () => {const fs = await import('fs/promises');await fs.mkdir(tmpLoras, { recursive: true });@@ -138,6 +146,36 @@ describe('deleteLora', () => {it('404s for missing files', async () => {await expect(lorasService.deleteLora('lora-missing.safetensors')).rejects.toThrow(/not found/);});+ it('400s with INVALID_LORA_FILE when path is a directory, not a regular file', async () => {+ const fs = await import('fs/promises');+ // Create a directory whose name ends in .safetensors — exotic but possible.+ await fs.mkdir(join(tmpLoras, 'lora-dir.safetensors'), { recursive: true });+ const err = await lorasService.deleteLora('lora-dir.safetensors').catch((e) => e);+ expect(err.status).toBe(400);+ expect(err.code).toBe('INVALID_LORA_FILE');+ });+});++describe('getLora', () => {+ it('404s when file does not exist', async () => {+ await expect(lorasService.getLora('lora-missing.safetensors')).rejects.toThrow(/not found/i);+ });+ it('404s when file exists but is not a regular .safetensors file (e.g. directory)', async () => {+ const fs = await import('fs/promises');+ // listLoras filters out non-file entries, so getLora must surface a 404+ // rather than returning null.+ await fs.mkdir(join(tmpLoras, 'lora-dir.safetensors'), { recursive: true });+ const err = await lorasService.getLora('lora-dir.safetensors').catch((e) => e);+ expect(err.status).toBe(404);+ expect(err.code).toBe('NOT_FOUND');+ });+ it('returns a full lora entry when the file is valid', async () => {+ const fs = await import('fs/promises');+ await fs.mkdir(tmpLoras, { recursive: true });+ await fs.writeFile(join(tmpLoras, 'lora-x.safetensors'), 'w');+ const lora = await lorasService.getLora('lora-x.safetensors');+ expect(lora.filename).toBe('lora-x.safetensors');+ });});describe('patchLoraSidecar', () => {@@ -245,13 +283,59 @@ describe('installFromCivitai', () => {).rejects.toThrow(/Already installed/);});- it('surfaces a friendly auth error when download is gated', async () => {+ it('surfaces a friendly auth error when download is gated (no key)', async () => {const fetchImpl = async (url) => {if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };return { ok: false, status: 401, statusText: 'Unauthorized' };};await expect(lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }),- ).rejects.toThrow(/may require an API key/);+ ).rejects.toThrow(/Configure a Civitai API key in PortOS Settings/);+ });++ it('surfaces a different auth error message when a key was provided but download still fails', async () => {+ const fetchImpl = async (url) => {+ if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };+ return { ok: false, status: 403, statusText: 'Forbidden' };+ };+ // Provide apiKey inline so hasApiKey=true+ await expect(+ lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698', apiKey: 'my-key' }, { fetchImpl }),+ ).rejects.toThrow(/even with your saved API key/);+ });++ it('atomic no-clobber: CIVITAI_ALREADY_INSTALLED when concurrent install wins the link race', async () => {+ // Simulate a concurrent install winning by pre-creating the dest file+ // AFTER the existsSync precheck passes but BEFORE link() runs. We do this+ // by planting the dest file before the download — since our fetchImpl+ // creates it synchronously (no real I/O delay) and the precheck is in+ // installFromCivitai (before mkdir+download), we plant it inside the+ // download body stream start to mimic the timing. The simplest way: make+ // the download fetchImpl write the dest file first before returning.+ const fs = await import('fs/promises');+ await fs.mkdir(tmpLoras, { recursive: true });+ const destFilename = 'lora-realstagram-v7.safetensors';++ const fetchImpl = async (url) => {+ if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };+ if (url.startsWith('https://civitai.com/api/download/models/7')) {+ // Plant the dest file to simulate a concurrent install winning before+ // our link() call — this is what makes link() return EEXIST.+ await fs.writeFile(join(tmpLoras, destFilename), 'other-install-won');+ const stream = new ReadableStream({+ start(c) { c.enqueue(new Uint8Array(Buffer.from('race-loser'))); c.close(); },+ });+ return { ok: true, status: 200, body: stream };+ }+ throw new Error(`unexpected fetch: ${url}`);+ };++ const err = await lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }).catch((e) => e);+ expect(err.code).toBe('CIVITAI_ALREADY_INSTALLED');+ // The original file written by the "winning" install must be preserved.+ expect(existsSync(join(tmpLoras, destFilename))).toBe(true);+ // The tmp .partial file must be cleaned up.+ const tmpFiles = await fs.readdir(tmpLoras);+ expect(tmpFiles.some((f) => f.endsWith('.partial'))).toBe(false);});});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 004234d51a..5eca571015 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -447,9 +447,9 @@ async function runJob(job) {let watchdogTimer;function terminate(state, apply) {if (job.status !== 'running') return;- // setInterval now (was setTimeout) — clearInterval is the right call.- // clearTimeout would silently no-op on an interval handle and the- // watchdog would keep ticking after the job terminated.+ // setInterval now (was setTimeout) — using clearInterval to match the new+ // API. (Node accepts either clearTimeout or clearInterval on the same+ // Timeout handle, so this is purely stylistic.)clearInterval(watchdogTimer);emitter.off?.('activity', onActivity);emitter.off?.('progress', onActivity);