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
add per-base-model LoRA keyword search and "Load more" pagination on /media/loras
[._.]/ Adam Eivybf312257d53b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 86cdf77b4e..227633204f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **Search & browse more LoRAs per base model on /media/loras** — Each "Top for …" base-model section (Flux 1, Flux 2, Z-Image, ERNIE, HiDream, Qwen) gains a keyword search box and a "Load more" button. Type a term (e.g. a character or style name) to query Civitai live within that base model so you can find a specific LoRA that targets the model you're using, and click "Load more" to page past the top few into Civitai's deeper results (cursor-paginated). Clearing the search drops back to the cached top ranking. The curated picks section is unchanged.- **Custom scheduled tasks per app** — Each managed app's Automation tab gains a "Custom Tasks" section where you write your own prompt and pick a schedule (interval or cron), and a Chief-of-Staff agent runs it against that app's repo on cadence — just like the built-in task types, but fully your own. Per task you choose priority, autonomy level, and whether the agent works in an isolated worktree and opens a PR (or commits/auto-merges) in the target app. Run-now triggers an immediate pass. Custom tasks also appear (with an app badge) in the Chief of Staff → System Tasks list, where the create/edit form now has an optional app-scope picker so any agent job can be pointed at a specific app or left global.- **Password-protected federated peers** — If one of your PortOS instances sits behind an HTTP Basic auth proxy (Tailscale `serve`, Caddy, nginx), its peers can now reach it: probes were failing with `HTTP 401`. Each peer in the Instances page gains an optional credential — set a username (optional) and password when adding a peer, or click "set credential" on an existing peer. The credential is attached to every outbound hop to that peer (health probes, snapshot sync, per-record push/pull, asset pulls, and the live agent socket relay), so a reachable-but-401 peer now connects. A peer that returns 401/403 is flagged "auth required" in the UI instead of just reading as offline. Credentials are stored locally per peer and are never synced or announced to the peer itself.- **[issue-708] Digital Twin "Voice" tab — spoken vs. written style** — Paste a transcript of yourself speaking and the Digital Twin compares it against how you write (a pasted sample, or your existing twin documents), surfacing where your spoken voice differs from your writing — formality, verbosity, sentence length, directness, filler words — and suggesting a communication profile for voice contexts that you can apply in one click.diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsxindex addabd9b82..8d31aeb867 100644--- a/client/src/pages/Loras.jsx+++ b/client/src/pages/Loras.jsx@@ -9,7 +9,7 @@import { useState, useEffect, useCallback } from 'react';import { Link } from 'react-router-dom';-import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2 } from 'lucide-react';+import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2, Search } from 'lucide-react';import toast from '../components/ui/Toast';import Modal from '../components/ui/Modal';import Banner from '../components/ui/Banner';@@ -23,6 +23,7 @@ import {setCivitaiAuth,clearCivitaiAuth,getCivitaiSuggestions,+ searchCivitaiLoras,} from '../services/api';const RUNNER_LABEL = {@@ -42,6 +43,13 @@ const RUNNER_BADGE_CLASS = {[RUNNER_FAMILIES.QWEN]: 'bg-sky-600/20 text-sky-300 border-sky-500/30',};+// Stable identity for a suggestion's specific model+version — used for React+// keys, install-in-flight tracking, and "Load more" dedup. Curated cards pass+// a family-specific versionId that differs from the card's primary, so the key+// takes the two ids explicitly rather than a whole card.+const suggestionKey = (modelId, versionId) => `${modelId}-${versionId}`;+const cardKey = (card) => suggestionKey(card.modelId, card.versionId);+export default function Loras() {const [loras, setLoras] = useState([]);const [loading, setLoading] = useState(true);@@ -200,7 +208,7 @@ export default function Loras() {// Curated cards pass a family-specific (url, versionId); non-curated// cards omit versionId and we fall back to the card's primary.const vid = versionId ?? card.versionId;- const key = `${card.modelId}-${vid}`;+ const key = suggestionKey(card.modelId, vid);setInstallingSuggestion(key);await performInstall(url || card.installUrl);setInstallingSuggestion(null);@@ -235,15 +243,17 @@ function SuggestionsPanel({ suggestions, loading, installedFilenames, installingconst runners = suggestions?.runners || {};const sections = [{ key: 'curated', label: 'Curated picks', cards: curated, hint: 'Hand-picked LoRAs that work across multiple base models.' },- // The four runner-family sections always render, even when Civitai- // search returns zero — `alwaysShow` lets the user see all four- // headers at a glance instead of silently collapsing the empty ones.- { key: RUNNER_FAMILIES.MFLUX, label: 'Top for Flux 1', cards: runners[RUNNER_FAMILIES.MFLUX] || [], hint: 'Most-downloaded LoRAs trained against Flux.1 D / Flux.1 S.', alwaysShow: true },- { key: RUNNER_FAMILIES.FLUX2, label: 'Top for Flux 2', cards: runners[RUNNER_FAMILIES.FLUX2] || [], hint: 'Most-downloaded LoRAs trained against Flux.2 Klein 4B / 9B.', alwaysShow: true },- { key: RUNNER_FAMILIES.Z_IMAGE, label: 'Top for Z-Image', cards: runners[RUNNER_FAMILIES.Z_IMAGE] || [], hint: 'Most-downloaded LoRAs trained against Z-Image / Z-Image-Turbo.', alwaysShow: true },- { key: RUNNER_FAMILIES.ERNIE, label: 'Top for ERNIE', cards: runners[RUNNER_FAMILIES.ERNIE] || [], hint: 'Most-downloaded LoRAs trained against ERNIE-Image.', alwaysShow: true },- { key: RUNNER_FAMILIES.HIDREAM, label: 'Top for HiDream', cards: runners[RUNNER_FAMILIES.HIDREAM] || [], hint: 'Most-downloaded LoRAs trained against HiDream.', alwaysShow: true },- { key: RUNNER_FAMILIES.QWEN, label: 'Top for Qwen', cards: runners[RUNNER_FAMILIES.QWEN] || [], hint: 'Most-downloaded LoRAs trained against Qwen-Image.', alwaysShow: true },+ // The runner-family sections always render, even when Civitai search+ // returns zero — `alwaysShow` lets the user see every base-model header at+ // a glance instead of silently collapsing the empty ones. `runner` (the+ // family key) marks the section as searchable + paginated; it's tracked+ // separately from `alwaysShow` so the two concerns can't accidentally couple.+ { key: RUNNER_FAMILIES.MFLUX, runner: RUNNER_FAMILIES.MFLUX, label: 'Top for Flux 1', cards: runners[RUNNER_FAMILIES.MFLUX] || [], hint: 'Most-downloaded LoRAs trained against Flux.1 D / Flux.1 S.', alwaysShow: true },+ { key: RUNNER_FAMILIES.FLUX2, runner: RUNNER_FAMILIES.FLUX2, label: 'Top for Flux 2', cards: runners[RUNNER_FAMILIES.FLUX2] || [], hint: 'Most-downloaded LoRAs trained against Flux.2 Klein 4B / 9B.', alwaysShow: true },+ { key: RUNNER_FAMILIES.Z_IMAGE, runner: RUNNER_FAMILIES.Z_IMAGE, label: 'Top for Z-Image', cards: runners[RUNNER_FAMILIES.Z_IMAGE] || [], hint: 'Most-downloaded LoRAs trained against Z-Image / Z-Image-Turbo.', alwaysShow: true },+ { key: RUNNER_FAMILIES.ERNIE, runner: RUNNER_FAMILIES.ERNIE, label: 'Top for ERNIE', cards: runners[RUNNER_FAMILIES.ERNIE] || [], hint: 'Most-downloaded LoRAs trained against ERNIE-Image.', alwaysShow: true },+ { key: RUNNER_FAMILIES.HIDREAM, runner: RUNNER_FAMILIES.HIDREAM, label: 'Top for HiDream', cards: runners[RUNNER_FAMILIES.HIDREAM] || [], hint: 'Most-downloaded LoRAs trained against HiDream.', alwaysShow: true },+ { key: RUNNER_FAMILIES.QWEN, runner: RUNNER_FAMILIES.QWEN, label: 'Top for Qwen', cards: runners[RUNNER_FAMILIES.QWEN] || [], hint: 'Most-downloaded LoRAs trained against Qwen-Image.', alwaysShow: true },];return (<div className="space-y-4">@@ -273,6 +283,10 @@ function SuggestionsPanel({ suggestions, loading, installedFilenames, installinghint={section.hint}cards={section.cards}alwaysShow={section.alwaysShow}+ // Runner-family sections carry a `runner` key → keyword search box ++ // "Load more" pagination; the curated section has none and stays static.+ runner={section.runner || null}+ resetSignal={suggestions?.fetchedAt}installedFilenames={installedFilenames}installingSuggestionKey={installingSuggestionKey}onInstall={onInstall}@@ -282,30 +296,147 @@ function SuggestionsPanel({ suggestions, loading, installedFilenames, installing);}-function SuggestionsSection({ label, hint, cards, alwaysShow = false, installedFilenames, installingSuggestionKey, onInstall }) {- const list = cards || [];- if (list.length === 0 && !alwaysShow) return null;+function SuggestionsSection({ label, hint, cards, alwaysShow = false, runner = null, resetSignal, installedFilenames, installingSuggestionKey, onInstall }) {+ const baseCards = cards || [];+ const searchable = !!runner;++ // Live state for keyword search + "Load more" pagination. `liveCards === null`+ // means we're showing the cached top-N from props; once the user searches or+ // pages, we switch to the live list. `activeQuery` is the last submitted+ // keyword ('' = top ranking); `cursor` is Civitai's next-page token.+ const [query, setQuery] = useState('');+ const [activeQuery, setActiveQuery] = useState('');+ const [liveCards, setLiveCards] = useState(null);+ const [cursor, setCursor] = useState(null);+ const [loading, setLoading] = useState(false);++ // Drop any live search/pagination so the section falls back to the cached+ // top-N. Shared by Clear, the empty-box submit, and the Refresh effect.+ // Stable identity (setters never change) so the effect can depend on it.+ const resetToCached = useCallback(() => {+ setActiveQuery(''); setLiveCards(null); setCursor(null);+ }, []);++ // A global Refresh (new fetchedAt) re-seeds the cached top-N — drop live+ // results so the section doesn't show stale ones under the new header. Also+ // fires once harmlessly on mount (all setters are no-ops at their defaults).+ useEffect(() => { setQuery(''); resetToCached(); }, [resetSignal, resetToCached]);++ const fetchPage = useCallback(async (q, { append, useCursor }) => {+ setLoading(true);+ await searchCivitaiLoras({ runner, query: q, cursor: useCursor, limit: 12 })+ .then((res) => {+ const items = res?.items || [];+ setCursor(res?.nextCursor || null);+ setActiveQuery(q);+ setLiveCards((prev) => {+ if (!append || prev === null) return items;+ // Dedup by modelId-versionId — re-fetched leaders can repeat.+ const seen = new Set(prev.map(cardKey));+ return [...prev, ...items.filter((c) => !seen.has(cardKey(c)))];+ });+ })+ .catch((err) => toast.error(err?.message || 'Civitai search failed'))+ .finally(() => setLoading(false));+ }, [runner]);++ const handleSearch = (e) => {+ e?.preventDefault?.();+ const q = query.trim();+ if (!q) { resetToCached(); return; } // empty box → cached top-N+ fetchPage(q, { append: false, useCursor: null });+ };++ const clearSearch = () => { setQuery(''); resetToCached(); };++ const loadMore = () => {+ if (loading) return;+ // First click from the cached view fetches page 1 live (top ranking or the+ // active query); later clicks page forward with the cursor.+ if (liveCards === null) fetchPage(activeQuery, { append: false, useCursor: null });+ else fetchPage(activeQuery, { append: true, useCursor: cursor });+ };++ const list = liveCards !== null ? liveCards : baseCards;+ // "Load more" is available until we've gone live AND Civitai reports no+ // further cursor. In the cached view we assume more exists (only top-4 shown).+ const canLoadMore = searchable && (liveCards === null || cursor !== null);++ if (list.length === 0 && !alwaysShow && !searchable) return null;return (<div><div className="flex items-baseline gap-3 mb-2"><h3 className="text-sm font-medium text-gray-300">{label}</h3><span className="text-xs text-gray-600">{list.length}</span>+ {activeQuery && (+ <span className="text-xs text-port-accent">results for “{activeQuery}”</span>+ )}</div>{hint && <p className="text-xs text-gray-500 mb-2">{hint}</p>}+ {searchable && (+ <form onSubmit={handleSearch} className="flex gap-2 mb-3">+ <div className="relative flex-1 max-w-md">+ <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-600 pointer-events-none" />+ <input+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={`Search ${RUNNER_LABEL[runner] || runner} LoRAs on Civitai…`}+ className="w-full bg-port-bg border border-port-border rounded pl-8 pr-3 py-1.5 text-xs text-gray-200 placeholder:text-gray-600"+ />+ </div>+ <button+ type="submit"+ disabled={loading}+ className="bg-port-accent/90 text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent disabled:opacity-50"+ >+ {loading ? 'Searching…' : 'Search'}+ </button>+ {activeQuery && (+ <button+ type="button"+ onClick={clearSearch}+ className="px-2 py-1.5 rounded text-xs text-gray-400 hover:text-gray-200 border border-port-border"+ title="Clear search — back to top ranking"+ >+ Clear+ </button>+ )}+ </form>+ )}{list.length === 0 ? (- <p className="text-xs text-gray-600 italic">No LoRAs found on Civitai for this base model yet.</p>+ <p className="text-xs text-gray-600 italic">+ {activeQuery+ ? `No LoRAs match “${activeQuery}” for this base model.`+ : 'No LoRAs found on Civitai for this base model yet.'}+ </p>) : (- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">- {list.map((card) => (- <SuggestionCard- key={`${card.modelId}-${card.versionId}`}- card={card}- installedFilenames={installedFilenames}- installingSuggestionKey={installingSuggestionKey}- onInstall={onInstall}- />- ))}- </div>+ <>+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">+ {list.map((card) => (+ <SuggestionCard+ key={cardKey(card)}+ card={card}+ installedFilenames={installedFilenames}+ installingSuggestionKey={installingSuggestionKey}+ onInstall={onInstall}+ />+ ))}+ </div>+ {canLoadMore && (+ <div className="mt-3 flex justify-center">+ <button+ type="button"+ onClick={loadMore}+ disabled={loading}+ className="text-xs text-gray-300 hover:text-white px-4 py-1.5 rounded border border-port-border hover:border-port-accent/40 disabled:opacity-50 flex items-center gap-1.5"+ >+ {loading ? <RefreshCw size={12} className="animate-spin" /> : <Download size={12} />}+ {loading ? 'Loading…' : 'Load more'}+ </button>+ </div>+ )}+ </>)}</div>);@@ -322,7 +453,7 @@ function SuggestionCard({ card, installedFilenames, installingSuggestionKey, onI: (card.runnerFamily ? [card.runnerFamily] : []));const isInstalled = (versionId) => versionId != null&& [...installedFilenames].some((f) => f.endsWith(`-v${versionId}.safetensors`));- const isInstalling = (versionId) => installingSuggestionKey === `${card.modelId}-${versionId}`;+ const isInstalling = (versionId) => installingSuggestionKey === suggestionKey(card.modelId, versionId);return (<div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">{card.previewImageUrl ? (diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 8917ece067..31973816dc 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -173,6 +173,19 @@ export const installLoraFromCivitai = ({ url, silent = false } = {}) => request(export const getCivitaiSuggestions = ({ force = false } = {}) =>request(`/loras/suggestions${force ? '?force=1' : ''}`);+// Live keyword search + cursor pagination within one runner family. Backs the+// per-category search box and "Load more" button on /media/loras. `query`+// blank pages the plain top-ranking; pass the previous response's `nextCursor`+// to load the next page. Returns `{ runnerFamily, query, items, nextCursor }`.+export const searchCivitaiLoras = ({ runner, query = '', cursor = null, limit } = {}) => {+ const params = new URLSearchParams();+ params.set('runner', runner);+ if (query) params.set('query', query);+ if (cursor) params.set('cursor', cursor);+ if (limit) params.set('limit', String(limit));+ return request(`/loras/search?${params.toString()}`);+};+// Civitai auth — read/save/clear the API key. The key never round-trips back// to the client; the GET only returns `{ hasKey, source }`.export const getCivitaiAuth = () => request('/loras/auth/civitai');diff --git a/server/lib/civitai.js b/server/lib/civitai.jsindex 5c340720c4..724c174b90 100644--- a/server/lib/civitai.js+++ b/server/lib/civitai.js@@ -318,10 +318,12 @@ const RUNNER_TO_BASE_MODELS = {};// Search Civitai for LoRA-family models targeting the given runner family.-// Returns the raw `items` array from `/api/v1/models` (each entry has its-// own `modelVersions[]` etc — let the suggestion service shape them).-// fetchImpl is injectable for tests.-export const searchCivitaiLoras = async ({ runnerFamily, limit = 12, sort = 'Most Downloaded', nsfw = false, apiKey, fetchImpl = fetch } = {}) => {+// Returns `{ items, nextCursor }` — `items` is the raw array from+// `/api/v1/models` (each entry has its own `modelVersions[]` etc — let the+// suggestion service shape them); `nextCursor` is Civitai's cursor token for+// the next page (null when exhausted). Pass `query` to filter by keyword and+// `cursor` to page forward. fetchImpl is injectable for tests.+export const searchCivitaiLoras = async ({ runnerFamily, limit = 12, sort = 'Most Downloaded', nsfw = false, query, cursor, apiKey, fetchImpl = fetch } = {}) => {const baseModels = RUNNER_TO_BASE_MODELS[runnerFamily];if (!baseModels) {throw new ServerError(`Unknown runner family for Civitai search: ${runnerFamily}`, { status: 400, code: 'CIVITAI_BAD_RUNNER' });@@ -334,6 +336,13 @@ export const searchCivitaiLoras = async ({ runnerFamily, limit = 12, sort = 'Mosparams.set('sort', sort);params.set('nsfw', String(!!nsfw));for (const bm of baseModels) params.append('baseModels', bm);+ // `query` is Civitai's keyword search over model name/description. Trim and+ // skip when blank so an empty box falls back to the plain "top" ranking.+ const trimmedQuery = typeof query === 'string' ? query.trim() : '';+ if (trimmedQuery) params.set('query', trimmedQuery);+ // Cursor-based pagination — Civitai returns `metadata.nextCursor`; feed it+ // back here to fetch the next page. Cursor is opaque (string or number).+ if (cursor != null && cursor !== '') params.set('cursor', String(cursor));const url = `${CIVITAI_API}/models?${params.toString()}`;const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildAuthHeaders(apiKey) } });if (!res.ok) {@@ -346,7 +355,10 @@ export const searchCivitaiLoras = async ({ runnerFamily, limit = 12, sort = 'Mosthrow new ServerError(`Civitai search failed: ${res.status}`, { status: 502, code: 'CIVITAI_SEARCH_FAILED' });}const body = await readResponseJson(res);- return Array.isArray(body?.items) ? body.items : [];+ return {+ items: Array.isArray(body?.items) ? body.items : [],+ nextCursor: body?.metadata?.nextCursor ?? null,+ };};// Pull a sample prompt from Civitai's preview image metadata. The `meta`diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 2c830b947c..22315610be 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -801,7 +801,7 @@ export const restoreRequestSchema = z.object({// as "use the default" rather than a bogus id. Both the autofixer (file edits// + pm2) and Google Calendar MCP sync require an agentic CLI provider; the// picker resolution layer (`pickCliProvider`) enforces type 'cli'.-const emptyToUndefined = (v) => (v === '' ? undefined : v);+export const emptyToUndefined = (v) => (v === '' ? undefined : v);export const featureProviderConfigSchema = z.object({providerId: z.preprocess(emptyToUndefined, z.string().optional()),model: z.preprocess(emptyToUndefined, z.string().optional()),diff --git a/server/routes/loras.js b/server/routes/loras.jsindex 28bd93046e..c5de83d461 100644--- a/server/routes/loras.js+++ b/server/routes/loras.js@@ -11,7 +11,7 @@ import { Router } from 'express';import { z } from 'zod';import { asyncHandler } from '../lib/errorHandler.js';import { deepMerge, isPlainObject } from '../lib/objects.js';-import { validateRequest } from '../lib/validation.js';+import { emptyToUndefined, validateRequest } from '../lib/validation.js';import {deleteLora,getLora,@@ -19,8 +19,9 @@ import {listLoras,patchLoraSidecar,} from '../services/loras.js';-import { getSuggestions } from '../services/civitaiSuggestions.js';+import { getSuggestions, searchLorasInFamily } from '../services/civitaiSuggestions.js';import { getSettings, updateSettingsWith } from '../services/settings.js';+import { RUNNER_FAMILIES } from '../lib/runners.js';const router = Router();@@ -38,6 +39,28 @@ router.get('/suggestions', asyncHandler(async (req, res) => {res.json(await getSuggestions({ force, limit }));}));+// Live keyword search + cursor pagination within one runner family. Backs the+// per-category search box and "Load more" button on /media/loras. Uncached —+// results are query/cursor-specific. `query` blank = top ranking for that+// family (so "Load more" with no keyword just pages the leaderboard).+const searchQuerySchema = z.object({+ runner: z.enum(Object.values(RUNNER_FAMILIES)),+ // emptyToUndefined: a blank box (`query=`) is a valid "top ranking" request,+ // not a validation error — coerce '' → undefined before the optional check.+ query: z.preprocess(emptyToUndefined, z.string().max(120).optional()),+ cursor: z.preprocess(emptyToUndefined, z.string().max(512).optional()),+ limit: z.coerce.number().int().min(1).max(50).optional(),+});+router.get('/search', asyncHandler(async (req, res) => {+ const { runner, query, cursor, limit } = validateRequest(searchQuerySchema, req.query);+ res.json(await searchLorasInFamily({+ runnerFamily: runner,+ query: query || '',+ cursor: cursor || null,+ limit: limit || 12,+ }));+}));+// Civitai auth status — returns just whether a key is configured (the key// itself never leaves the server). The 2-segment path keeps it from// colliding with the `/:filename` LoRA endpoints below. `source` lets thediff --git a/server/routes/loras.test.js b/server/routes/loras.test.jsnew file mode 100644index 0000000000..7ba3acf1e1--- /dev/null+++ b/server/routes/loras.test.js@@ -0,0 +1,87 @@+import { describe, it, expect, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Stub the Civitai-backed services — we only verify routing + validation for+// the new /search endpoint here, not the live Civitai call.+vi.mock('../services/loras.js', () => ({+ deleteLora: vi.fn(),+ getLora: vi.fn(),+ installFromCivitai: vi.fn(),+ listLoras: vi.fn(async () => []),+ patchLoraSidecar: vi.fn(),+ resolveCivitaiKey: vi.fn(async () => null),+}));+vi.mock('../services/civitaiSuggestions.js', () => ({+ getSuggestions: vi.fn(async () => ({ curated: [], runners: {}, fetchedAt: 'now' })),+ searchLorasInFamily: vi.fn(async ({ runnerFamily, query, cursor, limit }) => ({+ runnerFamily,+ query: query || '',+ items: [{ modelId: 1, versionId: 10, name: 'Match' }],+ nextCursor: 'NEXT',+ _echo: { cursor, limit },+ })),+}));+vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({})),+ updateSettingsWith: vi.fn(async () => ({})),+}));++const { default: lorasRoutes } = await import('./loras.js');+const { searchLorasInFamily } = await import('../services/civitaiSuggestions.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/loras', lorasRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('GET /api/loras/search', () => {+ it('dispatches a valid runner + keyword + cursor to the service', async () => {+ const res = await request(makeApp())+ .get('/api/loras/search?runner=z-image&query=cyberpunk&cursor=CUR&limit=20');+ expect(res.status).toBe(200);+ expect(res.body.items.length).toBe(1);+ expect(res.body.nextCursor).toBe('NEXT');+ expect(searchLorasInFamily).toHaveBeenCalledWith({+ runnerFamily: 'z-image',+ query: 'cyberpunk',+ cursor: 'CUR',+ limit: 20,+ });+ });++ it('treats a blank keyword as a top-ranking page (no query)', async () => {+ const res = await request(makeApp())+ .get('/api/loras/search?runner=mflux&query=');+ expect(res.status).toBe(200);+ expect(searchLorasInFamily).toHaveBeenCalledWith({+ runnerFamily: 'mflux',+ query: '',+ cursor: null,+ limit: 12,+ });+ });++ it('rejects an unknown runner family with 400', async () => {+ const res = await request(makeApp())+ .get('/api/loras/search?runner=sdxl');+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });++ it('rejects an over-long keyword with 400', async () => {+ const res = await request(makeApp())+ .get(`/api/loras/search?runner=qwen&query=${'x'.repeat(121)}`);+ expect(res.status).toBe(400);+ });++ it('rejects an out-of-range limit (> 50) with 400', async () => {+ const res = await request(makeApp())+ .get('/api/loras/search?runner=qwen&limit=999');+ expect(res.status).toBe(400);+ });+});diff --git a/server/services/civitaiSuggestions.js b/server/services/civitaiSuggestions.jsindex 55581be342..8d12822976 100644--- a/server/services/civitaiSuggestions.js+++ b/server/services/civitaiSuggestions.js@@ -169,7 +169,7 @@ const fetchSuggestionsFor = async (runnerFamily, { fetchImpl, force = false } =const apiKey = await resolveCivitaiKey();// Civitai's API doesn't strictly require auth for SFW LoRA search but a// configured key gets cleaner ranking and avoids anonymous rate limits.- const items = await searchCivitaiLoras({+ const { items } = await searchCivitaiLoras({runnerFamily,limit: MAX_SUGGESTIONS,apiKey,@@ -180,6 +180,31 @@ const fetchSuggestionsFor = async (runnerFamily, { fetchImpl, force = false } =return cards;};+// Live (uncached) search/pagination within one runner family. Backs the+// per-category search box and "Load more" button on /media/loras:+// - `query` filters by keyword (model name/description) — blank = top ranking+// - `cursor` pages forward; pass the previous response's `nextCursor`+// Uncached because results are query-/cursor-specific and short-lived; the+// curated + top-N panel stays on the 1-hour cache. Returns the same card+// shape `buildCard` produces plus Civitai's `nextCursor` for the next page.+export const searchLorasInFamily = async ({ runnerFamily, query = '', cursor = null, limit = 12, fetchImpl } = {}) => {+ const apiKey = await resolveCivitaiKey();+ const { items, nextCursor } = await searchCivitaiLoras({+ runnerFamily,+ limit,+ query,+ cursor,+ apiKey,+ fetchImpl,+ });+ return {+ runnerFamily,+ query: typeof query === 'string' ? query.trim() : '',+ items: items.map(buildCard).filter(Boolean),+ nextCursor: nextCursor || null,+ };+};+// Public API. Returns:// - curated: hand-picked cards (always shown first; multi-runner badged)// - runners: per-family top-N from Civitai's search endpointdiff --git a/server/services/civitaiSuggestions.test.js b/server/services/civitaiSuggestions.test.jsindex 1aa01759a2..5542ab9707 100644--- a/server/services/civitaiSuggestions.test.js+++ b/server/services/civitaiSuggestions.test.js@@ -186,6 +186,63 @@ describe('getSuggestions', () => {expect(card.installs.flux2.installUrl).toMatch(/modelVersionId=100/);});+ it('searchLorasInFamily passes the keyword + cursor through to Civitai and returns nextCursor', async () => {+ let seenUrl = null;+ const fetchImpl = async (url) => {+ seenUrl = url;+ return mockJsonResponse({+ items: [buildModel(7001, 'Cyberpunk City', 'ZImageTurbo')],+ metadata: { nextCursor: 'CURSOR_2' },+ });+ };+ const out = await svc.searchLorasInFamily({+ runnerFamily: 'z-image',+ query: ' cyberpunk ',+ cursor: 'CURSOR_1',+ limit: 12,+ fetchImpl,+ });+ const u = new URL(seenUrl);+ expect(u.searchParams.get('query')).toBe('cyberpunk'); // trimmed+ expect(u.searchParams.get('cursor')).toBe('CURSOR_1');+ expect(u.searchParams.get('limit')).toBe('12');+ expect(u.searchParams.getAll('baseModels')).toContain('ZImageTurbo');+ expect(out.runnerFamily).toBe('z-image');+ expect(out.query).toBe('cyberpunk');+ expect(out.items.length).toBe(1);+ expect(out.items[0].name).toBe('Cyberpunk City');+ expect(out.nextCursor).toBe('CURSOR_2');+ });++ it('searchLorasInFamily omits the query param for a blank keyword (top ranking) and returns null cursor when exhausted', async () => {+ let seenUrl = null;+ const fetchImpl = async (url) => {+ seenUrl = url;+ return mockJsonResponse({ items: [buildModel(7002, 'Top One', 'Flux.1 D')] }); // no metadata+ };+ const out = await svc.searchLorasInFamily({ runnerFamily: 'mflux', query: '', fetchImpl });+ const u = new URL(seenUrl);+ expect(u.searchParams.has('query')).toBe(false);+ expect(u.searchParams.has('cursor')).toBe(false);+ expect(out.query).toBe('');+ expect(out.nextCursor).toBe(null);+ expect(out.items[0].modelId).toBe(7002);+ });++ it('searchLorasInFamily does not touch the cached suggestions (live, uncached)', async () => {+ let searchCalls = 0;+ const fetchImpl = async (url) => {+ const m = url.match(/api\/v1\/models\/(\d+)$/);+ if (m) return mockJsonResponse(buildModel(Number(m[1]), 'Curated', 'Flux.1 D'));+ searchCalls += 1;+ return mockJsonResponse({ items: [buildModel(1, 'X', 'Flux.1 D')] });+ };+ await svc.searchLorasInFamily({ runnerFamily: 'mflux', query: 'a', fetchImpl });+ await svc.searchLorasInFamily({ runnerFamily: 'mflux', query: 'a', fetchImpl });+ // Two live searches → two HTTP calls (no caching).+ expect(searchCalls).toBe(2);+ });+it('curated card derives runnerFamilies from ALL the model versions', async () => {const fetchImpl = async (url) => {const m = url.match(/api\/v1\/models\/(\d+)$/);