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

chore(server): Civitai/Z-Image follow-ups — RUNNER_FAMILIES, deepMerge, assertSafeFilename, listLoras rename, mediaModels drift, CLI defaultModel (#222)

[._.]/ Adam Eivy3ed0396f632b
diff --git a/DONE.md b/DONE.md
index 08137c81ce..dbc31c2e13 100644
--- a/DONE.md
+++ b/DONE.md
@@ -6,6 +6,13 @@ Archive of completed work. For active roadmap, see [PLAN.md](./PLAN.md). For pro
## 2026-05-12
+- **Civitai / Z-Image follow-ups — six post-merge cleanups** — Six items off the "Civitai LoRA / Z-Image-Turbo follow-ups" backlog in one pass.
+ - **`RUNNER_FAMILIES` constants module** — New `server/lib/runners.js` exports `RUNNER_FAMILIES = { MFLUX, FLUX2, Z_IMAGE, ERNIE }` (frozen) plus typed predicates; `client/src/lib/runnerFamilies.js` mirrors it (Vite fs.allow doesn't cross the server boundary). All bare-string usages in `server/lib/civitai.js` (`baseModelToRunner`, `RUNNER_TO_BASE_MODELS`), `server/lib/mediaModels.js` (`isFlux2`/`isZImage`/`isErnie`, flux2 upgrade path), `client/src/pages/ImageGen.jsx` (current runner gate), `client/src/lib/imageGenResolutions.js` (compatibility keys), `client/src/components/imageGen/ImageGenControls.jsx` (isFlux2 gate), and the `RUNNER_LABEL`/`RUNNER_BADGE_CLASS`/`RUNNER_LABELS_SHORT` maps + section list in `client/src/pages/Loras.jsx` now reference the canonical ids. Shape-invariant + mirror-sync tests in `server/lib/runners.test.js`.
+ - **`listLoras` exports collision fix** — `server/services/imageGen/local.js#listLoras` renamed to `listLoraFilenames` so the minimal `{ filename, name }` shape can't be confused with `server/services/loras.js#listLoras` (rich Civitai-aware shape). Route + test mock updated.
+ - **Generic `deepMerge` utility** — New `server/lib/objects.js#deepMerge` adopts the cleanest existing implementation (from `voice/config.js`). Three call sites collapsed: `services/voice/config.js`, `services/meatspacePost.js`, and `routes/loras.js#POST /auth/civitai`. Documents array-replacement + null-as-value semantics + missing-base tolerance; 10 unit tests cover override, null, missing-base (null/undefined/non-object), mutation guard, and the patch-not-an-object early return.
+ - **`assertSafeFilename` helper** — New shared `server/lib/fileUtils.js#assertSafeFilename(filename, { extensions, subject, requiredMessage })` consolidates `services/loras.js#assertSafeLoraFilename` (`.safetensors`) and `services/imageGen/local.js#assertGalleryFilename` (`.png`). Rejects path separators, null bytes, exact `.`/`..`, and non-allowlisted extensions; case-insensitive extension match; enforces each extension starts with `.` (programmer-error otherwise); throws a 400 ServerError with code `VALIDATION_ERROR`. `requiredMessage` lets wrappers preserve their historical missing-input phrase. 13 unit tests in `fileUtils.test.js`.
+ - **`mediaModels.js` drift warning** — `loadMediaModels()` now logs a loud `⚠️ media-models drift` warning at boot for any id present in BOTH `_shippedDefaults` AND `DEFAULT_REGISTRY` but missing from the user's live list. Catches the 2026-05-09 silent-drift class. No auto-recover — surfaces the bug, lets a human decide. Warning is honest that intentional deletions are indistinguishable from drift and will keep firing each boot. Covers `image` plus `video.macos` and `video.windows`. 4 new tests.
+ - **CLI `defaultModel` for all CLI providers** — `services/runner.js#buildCliArgs` now appends `--model <id>` to claude-code (after `-p -`; claude-code parses flags positionally) and `-m <id>` to gemini-cli, gated on the provider's stored `args` not already containing `--model`/`-m` (both space- and `=`-joined forms; rejects dangling/empty flag forms). Codex behavior unchanged. New `hasModelFlag`/`extractBakedModel`/`stripBrokenModelFlags` helpers exported for reuse. Stage runner / message evaluator / media prompt refiner / world builder refiner per-call model overrides now actually take effect for all three CLIs instead of silently no-op'ing for claude-code and gemini-cli; refiners report the args-baked model id (not defaultModel) when a model is pinned in args. 15+ new tests + 2 regression tests; surfaced from Copilot review on PR #217 and #222.
- **Extract `scripts/_runner_common.py`** — Pulled the byte-for-byte-duplicated `pick_device` / `make_generator` / `apply_memory_optimizations` / `write_sidecar` / `make_stepwise_callback` / `_emit_user_error` / `_repo_from_hf_error` / HF cause-chain walker (~200 LOC) out of `scripts/flux2_macos.py` + `scripts/z_image_turbo.py` into a shared module. `make_stepwise_callback` now takes an optional `unpack_latents` callable so the flux2 packed-transformer-latent path stays runner-specific while the rest of the decode is shared. `install_hf_error_handler` is a `@decorator` over `main()` that owns the gated/notfound/401 dispatch — `if __name__ == "__main__": main()` collapses to one line in both runners. Mirrors the `lora_utils.py` extraction pattern. Server tests 4012/4012 green; both runners' `--help` resolves cleanly.
## 2026-05-10
diff --git a/PLAN.md b/PLAN.md
index b1b98bebca..7d3fc69b77 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -55,13 +55,10 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud
These were flagged by the post-merge code review pass on the Z-Image + Civitai LoRA work but deliberately deferred to keep the original PR scoped.
-- [ ] **Detect `_shippedDefaults` ↔ `image[]` drift in mediaModels.js.** A real-install case (2026-05-09) hit a state where `_shippedDefaults.image.list` recorded all default ids but the user's `image[]` array was missing several of them — possibly from a partial editor save or a write race. The deletion-survives-upgrade contract then permanently skipped re-adding those built-ins on every restart. Add a boot-time check in `loadMediaModels()`: for any id present in `_shippedDefaults.image.list` AND `DEFAULT_REGISTRY.image` but missing from the user's `image[]`, log a clear warning (`⚠️ media-models drift: built-in <id> was shipped but is missing from image[] — restore it manually or delete _shippedDefaults.image to re-bootstrap`). Don't auto-recover (would defeat real deletions), just make the drift loud. Same pattern applies to video.
-
-- [ ] **`RUNNER_FAMILIES` constants module** — runner ids `'mflux' | 'flux2' | 'z-image'` are bare strings in `server/lib/civitai.js`, `server/lib/mediaModels.js`, `client/src/pages/ImageGen.jsx`, and the `RUNNER_LABEL` / `RUNNER_BADGE_CLASS` maps in `client/src/pages/Loras.jsx`. Export `RUNNER_FAMILIES = { MFLUX, FLUX2, Z_IMAGE }` from `server/lib/runners.js` (mirror to a small client constant) so a typo can't silently break the LoRA picker's compat filter. `isFlux2()` / `isZImage()` already wrap the server-side comparisons; this is mostly client + civitai.js cleanup.
-- [ ] **Two `listLoras` exports collision** — `server/services/imageGen/local.js#listLoras` returns minimal `{ filename, name }` (powers `/api/image-gen/loras`); `server/services/loras.js#listLoras` returns the rich Civitai-aware shape (powers `/api/loras`). Same name, two modules, two shapes — a future caller importing the wrong one gets `undefined` for `civitai` / `runnerFamily`. Rename the legacy one to `listLoraFilenames` (or have it project from the new list) to make the distinction explicit.
-- [ ] **Generic `deepMerge` utility** — three call sites now do hand-rolled deep-merge: `server/services/voice/config.js`, `server/services/meatspacePost.js`, and the new `server/routes/loras.js#POST /auth/civitai`. Promote the cleanest impl (voice/config.js) into `server/lib/objects.js` and consolidate. Then loras.js, voice config, and meatspacePost all consume one helper — and `updateSettings()`-via-shallow-merge stops being a footgun for any future settings sub-object.
+_All items in this section have shipped — see DONE.md → 2026-05-12 for the
+"Civitai / Z-Image follow-ups — six post-merge cleanups" entry and the
+`scripts/_runner_common.py` extraction entry._
- [ ] **Project-wide `<Modal>` component** — every modal in the app (`Flux2InstallModal`, `EditAppModal`, `MemoryEditModal`, `ResumeAgentModal`, `MediaLightbox`, `LayoutEditor`, `KeyboardHelp`, `RapidReader`, `DeployPanel`'s confirm, the new `CivitaiAuthModal` in `Loras.jsx`) rolls its own `fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4` backdrop + click-outside + close-button + ESC handler. Extract `client/src/components/ui/Modal.jsx` with backdrop + dialog props and a slot for the body, then convert all call sites. ~300 LOC of duplicated chrome across the codebase.
-- [ ] **`assertSafeFilename(filename, { extensions })` in `fileUtils.js`** — `server/services/loras.js#assertSafeLoraFilename` (`.safetensors` whitelist) and `server/services/imageGen/local.js#assertGalleryFilename` (`.png` whitelist) are the same validation pattern with different extensions. One small helper in `fileUtils.js` consolidates both call sites.
- [ ] **Extract shared `runPromptThroughProvider` runner-wrapper** — four near-identical "create run → branch on provider.type → executeCliRun/executeApiRun → accumulate text → reject on error" implementations now exist: `server/services/mediaPromptRefiner.js#runRefinePrompt`, `server/services/messageEvaluator.js#runPrompt`, `server/lib/stageRunner.js#awaitRunnerCall`, `server/services/worldBuilderExpand.js#callLLM`. Promote into `server/lib/promptRunner.js` returning `{ text, runId }`, then collapse the four sites. Failure-handling drift is already visible (some reject on `success === false`, some only on `error`) — the unified version should pick the stricter discriminator. Surfaced from the Refine Prompt /simplify pass.
@@ -69,8 +66,6 @@ These were flagged by the post-merge code review pass on the Z-Image + Civitai L
- [ ] **Extend `normalize.js` to expose render-config fields** — `client/src/components/media/PromptRefineModal.jsx#getRenderConfig` reaches into `item.raw?.{cfgScale,loraFilenames,loraScales,steps (video),guidanceScale,seed,tiling,disableAudio}` because `normalizeImage`/`normalizeVideo` don't surface those fields. Either lift the snake_case/camelCase fallback chain into normalize.js so the modal reads from `item.*` only, or add `getRenderConfigForItem(item)` co-located with normalize so the sidecar field-naming knowledge lives in one file. Surfaced from the Refine Prompt /simplify pass.
-- [ ] **Extend `runner.js#buildCliArgs` to honor `defaultModel` for all CLI providers** — today only `codex` translates `provider.defaultModel` into a `--model` flag; `claude-code` and `gemini-cli` ignore it entirely, so the stageRunner / messageEvaluator / mediaPromptRefiner pattern of cloning the provider with an overridden `defaultModel` is silently a no-op for non-Codex CLIs. The user picks a model in the UI and the request runs against whatever model is baked into `provider.args` instead. Fix: append `--model <model>` to claude-code (after `-p -` is fine; claude-code parses flags positionally) and `-m <model>` to gemini-cli, gated on `!provider.args.includes('--model')` so existing user configs with model baked in don't get a duplicate flag. Test: each CLI's `--help` to confirm flag conventions, then verify Refine Prompt picks the modal-selected model for all three. Surfaced from Copilot review on PR #217.
-
### Better Audit follow-ups
- [ ] **[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test-specific hack in prod boot path).
diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsx
index 31fcfa4889..20a42aec72 100644
--- a/client/src/components/imageGen/ImageGenControls.jsx
+++ b/client/src/components/imageGen/ImageGenControls.jsx
@@ -11,6 +11,7 @@
import { Dice5 } from 'lucide-react';
import { filterResolutions } from '../../lib/imageGenResolutions';
import { randomSeed } from '../../lib/genUtils';
+import { RUNNER_FAMILIES } from '../../lib/runnerFamilies';
const QUANTIZE_OPTIONS = [
{ value: '3', label: '3-bit' },
@@ -42,7 +43,7 @@ export default function ImageGenControls({
const isCodex = mode === 'codex';
const currentModel = models.find((m) => m.id === modelId);
- const isFlux2 = currentModel?.runner === 'flux2';
+ const isFlux2 = currentModel?.runner === RUNNER_FAMILIES.FLUX2;
// Filter by backend; a stale w/h (e.g. Flux 2 → Flux 1 with 1536 still set)
// falls through to the (custom) <option> below so the value stays visible
diff --git a/client/src/lib/imageGenResolutions.js b/client/src/lib/imageGenResolutions.js
index dc318033a5..cbdc136056 100644
--- a/client/src/lib/imageGenResolutions.js
+++ b/client/src/lib/imageGenResolutions.js
@@ -6,19 +6,24 @@
// ones reflect real model constraints, not just style — Z-Image-Turbo and
// ERNIE were trained at 1024² and degrade past ~1280, and gpt-image-2's
// native sizes are 1024² / 1024×1536 / 1536×1024.
+import { RUNNER_FAMILIES } from './runnerFamilies';
+
+// `flux1` and `external` aren't members of RUNNER_FAMILIES — they're synthetic
+// compatibility-only keys ('flux1' = mflux/diffusers fallback when no `runner`
+// field is set; 'external' = Codex/API providers). Keep them as bare strings.
export const RESOLUTIONS = [
{ label: '512×512', w: 512, h: 512 },
{ label: '768×512', w: 768, h: 512 },
{ label: '512×768', w: 512, h: 768 },
{ label: '768×768', w: 768, h: 768 },
{ label: '1024×1024', w: 1024, h: 1024 },
- { label: '832×1216 (Flux portrait)', w: 832, h: 1216, compatible: ['flux1', 'flux2', 'external'] },
- { label: '1216×832 (Flux landscape)', w: 1216, h: 832, compatible: ['flux1', 'flux2', 'external'] },
+ { label: '832×1216 (Flux portrait)', w: 832, h: 1216, compatible: ['flux1', RUNNER_FAMILIES.FLUX2, 'external'] },
+ { label: '1216×832 (Flux landscape)', w: 1216, h: 832, compatible: ['flux1', RUNNER_FAMILIES.FLUX2, 'external'] },
{ label: '1024×576 (16:9)', w: 1024, h: 576 },
{ label: '576×1024 (9:16)', w: 576, h: 1024 },
- { label: '1536×1536 (hi-res square)', w: 1536, h: 1536, compatible: ['codex', 'flux2'] },
- { label: '1024×1536 (hi-res portrait)', w: 1024, h: 1536, compatible: ['codex', 'flux2'] },
- { label: '1536×1024 (hi-res landscape)', w: 1536, h: 1024, compatible: ['codex', 'flux2'] },
+ { label: '1536×1536 (hi-res square)', w: 1536, h: 1536, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
+ { label: '1024×1536 (hi-res portrait)', w: 1024, h: 1536, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
+ { label: '1536×1024 (hi-res landscape)', w: 1536, h: 1024, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
];
// Flux 1 (mflux/diffusers, `dev` / `schnell`) has no `runner` field — it's
@@ -26,7 +31,11 @@ export const RESOLUTIONS = [
export const compatibilityKey = (mode, runner) => {
if (mode === 'codex') return 'codex';
if (mode === 'external') return 'external';
- if (runner === 'flux2' || runner === 'z-image' || runner === 'ernie') return runner;
+ if (runner === RUNNER_FAMILIES.FLUX2
+ || runner === RUNNER_FAMILIES.Z_IMAGE
+ || runner === RUNNER_FAMILIES.ERNIE) {
+ return runner;
+ }
return 'flux1';
};
diff --git a/client/src/lib/runnerFamilies.js b/client/src/lib/runnerFamilies.js
new file mode 100644
index 0000000000..103b24637d
--- /dev/null
+++ b/client/src/lib/runnerFamilies.js
@@ -0,0 +1,11 @@
+// Mirror of server/lib/runners.js — keep byte-for-byte in sync.
+// Vite's fs.allow doesn't cross the server/ boundary, so the client carries
+// its own copy of the canonical runner-family ids. The shape-invariant test
+// in server/lib/runners.test.js is the contract.
+
+export const RUNNER_FAMILIES = Object.freeze({
+ MFLUX: 'mflux',
+ FLUX2: 'flux2',
+ Z_IMAGE: 'z-image',
+ ERNIE: 'ernie',
+});
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 87f519027c..c283abf749 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -18,6 +18,7 @@ import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
import StylePresetPicker from '../components/media/StylePresetPicker';
import BackendChipStrip from '../components/media/BackendChipStrip';
import { normalizeImage } from '../components/media/normalize';
+import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';
import Flux2TokenBanner from '../components/imageGen/Flux2TokenBanner';
import ImageGenControls from '../components/imageGen/ImageGenControls';
@@ -382,13 +383,13 @@ export default function ImageGen() {
}, [settingsOpen, reloadBackends]);
const currentModel = models.find((m) => m.id === modelId);
- const isFlux2Model = currentModel?.runner === 'flux2';
+ const isFlux2Model = currentModel?.runner === RUNNER_FAMILIES.FLUX2;
// mflux is the default runner for entries with no explicit `runner` field.
// Used to filter the LoRA picker so users only see compatible weights for
// the selected model. LoRAs with `runnerFamily === null` (legacy / unknown
// base) are shown too with a warning indicator — the runner may still
// accept them, or surface a clear error.
- const currentRunnerFamily = currentModel?.runner || 'mflux';
+ const currentRunnerFamily = currentModel?.runner || RUNNER_FAMILIES.MFLUX;
const compatibleLoras = availableLoras.filter((l) => !l.runnerFamily || l.runnerFamily === currentRunnerFamily);
const refreshFlux2Status = useCallback((signal) => {
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index 9ba25e3306..494299e653 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -12,6 +12,7 @@ import { Link } from 'react-router-dom';
import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2 } from 'lucide-react';
import toast from '../components/ui/Toast';
import { formatBytes } from '../utils/formatters';
+import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
import {
listLorasFull,
installLoraFromCivitai,
@@ -23,16 +24,16 @@ import {
} from '../services/api';
const RUNNER_LABEL = {
- mflux: 'Flux 1',
- flux2: 'Flux 2',
- 'z-image': 'Z-Image',
- ernie: 'ERNIE',
+ [RUNNER_FAMILIES.MFLUX]: 'Flux 1',
+ [RUNNER_FAMILIES.FLUX2]: 'Flux 2',
+ [RUNNER_FAMILIES.Z_IMAGE]: 'Z-Image',
+ [RUNNER_FAMILIES.ERNIE]: 'ERNIE',
};
const RUNNER_BADGE_CLASS = {
- mflux: 'bg-port-accent/20 text-port-accent border-port-accent/30',
- flux2: 'bg-purple-600/20 text-purple-300 border-purple-500/30',
- 'z-image': 'bg-emerald-600/20 text-emerald-300 border-emerald-500/30',
- ernie: 'bg-amber-600/20 text-amber-300 border-amber-500/30',
+ [RUNNER_FAMILIES.MFLUX]: 'bg-port-accent/20 text-port-accent border-port-accent/30',
+ [RUNNER_FAMILIES.FLUX2]: 'bg-purple-600/20 text-purple-300 border-purple-500/30',
+ [RUNNER_FAMILIES.Z_IMAGE]: 'bg-emerald-600/20 text-emerald-300 border-emerald-500/30',
+ [RUNNER_FAMILIES.ERNIE]: 'bg-amber-600/20 text-amber-300 border-amber-500/30',
};
export default function Loras() {
@@ -234,10 +235,10 @@ function SuggestionsPanel({ suggestions, loading, installedFilenames, installing
// 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: 'mflux', label: 'Top for Flux 1', cards: runners.mflux || [], hint: 'Most-downloaded LoRAs trained against Flux.1 D / Flux.1 S.', alwaysShow: true },
- { key: 'flux2', label: 'Top for Flux 2', cards: runners.flux2 || [], hint: 'Most-downloaded LoRAs trained against Flux.2 Klein 4B / 9B.', alwaysShow: true },
- { key: 'z-image', label: 'Top for Z-Image', cards: runners['z-image'] || [], hint: 'Most-downloaded LoRAs trained against Z-Image / Z-Image-Turbo.', alwaysShow: true },
- { key: 'ernie', label: 'Top for ERNIE', cards: runners.ernie || [], hint: 'Most-downloaded LoRAs trained against ERNIE-Image.', alwaysShow: true },
+ { 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 },
];
return (
<div className="space-y-4">
@@ -305,7 +306,12 @@ function SuggestionsSection({ label, hint, cards, alwaysShow = false, installedF
);
}
-const RUNNER_LABELS_SHORT = { mflux: 'Flux 1', flux2: 'Flux 2', 'z-image': 'Z-Image', ernie: 'ERNIE' };
+const RUNNER_LABELS_SHORT = {
+ [RUNNER_FAMILIES.MFLUX]: 'Flux 1',
+ [RUNNER_FAMILIES.FLUX2]: 'Flux 2',
+ [RUNNER_FAMILIES.Z_IMAGE]: 'Z-Image',
+ [RUNNER_FAMILIES.ERNIE]: 'ERNIE',
+};
function SuggestionCard({ card, installedFilenames, installingSuggestionKey, onInstall }) {
const installs = card.curated && card.installs && Object.keys(card.installs).length > 0 ? card.installs : null;
diff --git a/server/lib/civitai.js b/server/lib/civitai.js
index d9fc43c97e..42064382f5 100644
--- a/server/lib/civitai.js
+++ b/server/lib/civitai.js
@@ -16,6 +16,7 @@
*/
import { ServerError } from './errorHandler.js';
+import { RUNNER_FAMILIES } from './runners.js';
const CIVITAI_API = 'https://civitai.com/api/v1';
const CIVITAI_HOSTS = new Set(['civitai.com', 'civitai.red', 'civitai.green', 'www.civitai.com']);
@@ -29,10 +30,10 @@ export const baseModelToRunner = (baseModel) => {
const b = baseModel.trim().toLowerCase();
if (!b) return null;
// Match Flux.1 *, Flux 1 *, FLUX.1 D, FLUX.1 S
- if (b.startsWith('flux.1') || b.startsWith('flux 1') || b === 'flux1') return 'mflux';
- if (b.startsWith('flux.2') || b.startsWith('flux 2') || b === 'flux2') return 'flux2';
- if (b.startsWith('z-image') || b.startsWith('zimage') || b.startsWith('z image')) return 'z-image';
- if (b.startsWith('ernie-image') || b.startsWith('ernie image') || b.startsWith('ernieimage') || b === 'ernie') return 'ernie';
+ if (b.startsWith('flux.1') || b.startsWith('flux 1') || b === 'flux1') return RUNNER_FAMILIES.MFLUX;
+ if (b.startsWith('flux.2') || b.startsWith('flux 2') || b === 'flux2') return RUNNER_FAMILIES.FLUX2;
+ if (b.startsWith('z-image') || b.startsWith('zimage') || b.startsWith('z image')) return RUNNER_FAMILIES.Z_IMAGE;
+ if (b.startsWith('ernie-image') || b.startsWith('ernie image') || b.startsWith('ernieimage') || b === 'ernie') return RUNNER_FAMILIES.ERNIE;
// SDXL / SD1.5 / Pony / Illustrious / etc. — none currently supported by
// any PortOS runner. Surfacing them in the UI as "incompatible" is more
// useful than hiding them entirely.
@@ -305,10 +306,10 @@ export const buildSidecar = ({ model, version, file, filename }) => {
// LoRAs (e.g. model 1155749). Civitai is inconsistent about hyphens and
// per-variant naming, so each runner family lists every accepted alias.
const RUNNER_TO_BASE_MODELS = {
- mflux: ['Flux.1 D', 'Flux.1 S'],
- flux2: ['Flux.2 Klein 4B', 'Flux.2 Klein 9B'],
- 'z-image': ['ZImageBase', 'ZImageTurbo'],
- ernie: ['Ernie'],
+ [RUNNER_FAMILIES.MFLUX]: ['Flux.1 D', 'Flux.1 S'],
+ [RUNNER_FAMILIES.FLUX2]: ['Flux.2 Klein 4B', 'Flux.2 Klein 9B'],
+ [RUNNER_FAMILIES.Z_IMAGE]: ['ZImageBase', 'ZImageTurbo'],
+ [RUNNER_FAMILIES.ERNIE]: ['Ernie'],
};
// Search Civitai for LoRA-family models targeting the given runner family.
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index eec8223245..d45e51d329 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -9,9 +9,10 @@ import { existsSync } from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { randomUUID } from 'crypto';
-import { join, dirname } from 'path';
+import { join, dirname, basename } from 'path';
import { fileURLToPath } from 'url';
import { homedir } from 'os';
+import { ServerError } from './errorHandler.js';
const execFileAsync = promisify(execFile);
const IS_WIN = process.platform === 'win32';
@@ -518,6 +519,74 @@ export function formatBytes(bytes) {
return (bytes / Math.pow(1024, i)).toFixed(i > 1 ? 1 : 0) + ' ' + units[i];
}
+/**
+ * Validate a user-supplied filename is a safe basename with one of the
+ * allowed extensions — refuses path-traversal, null bytes, separators, and
+ * exact `.` / `..`. Throws a 400 ServerError with code VALIDATION_ERROR
+ * so calling routes don't have to repeat the check.
+ *
+ * Consolidates the two near-identical assertions that used to live in
+ * `services/loras.js#assertSafeLoraFilename` (`.safetensors` only) and
+ * `services/imageGen/local.js#assertGalleryFilename` (`.png` only).
+ *
+ * Substring `..` is intentionally allowed (e.g. `foo..bar.png` is fine);
+ * only the exact-string traversal cases are rejected. Path separators (`/`
+ * and `\`) are rejected on every platform — the same input gets posted
+ * from Windows clients too.
+ *
+ * @param {string} filename
+ * @param {{ extensions: string[], subject?: string, requiredMessage?: string }} opts
+ * - `extensions`: list of allowed extensions including the leading dot
+ * (`['.png']`, `['.safetensors']`, etc.). Case-insensitive match. Each
+ * entry MUST be a non-empty string starting with `.` — otherwise a bare
+ * suffix like `'png'` would also match `'not-an-imagepng'` and weaken
+ * the validation, so we treat that as a programmer error and throw.
+ * - `subject`: optional noun for the error message ("LoRA filename" →
+ * "Invalid LoRA filename"). Defaults to "filename".
+ * - `requiredMessage`: optional exact message used when `filename` is
+ * missing/empty — preserves backward-compat for wrappers that used to
+ * throw a specific phrase. The gallery wrapper passes `'Invalid filename'`
+ * (its pre-refactor implementation threw that for every failure, including
+ * missing-input); the LoRA wrapper passes `'Filename required'` to match
+ * its historical wording. When omitted, the message is derived from
+ * `subject` (e.g. `'Filename required'` / `'LoRA filename required'`).
+ */
+export function assertSafeFilename(filename, { extensions, subject = 'filename', requiredMessage } = {}) {
+ if (!Array.isArray(extensions) || extensions.length === 0) {
+ throw new Error('assertSafeFilename: extensions allowlist is required');
+ }
+ for (const ext of extensions) {
+ if (typeof ext !== 'string' || ext.length < 2 || !ext.startsWith('.')) {
+ throw new Error(`assertSafeFilename: each extension must be a non-empty string starting with "." (got ${JSON.stringify(ext)})`);
+ }
+ }
+ const subjectText = subject || 'filename';
+ if (!filename || typeof filename !== 'string') {
+ const Subject = `${subjectText[0].toUpperCase()}${subjectText.slice(1)}`;
+ const message = typeof requiredMessage === 'string' && requiredMessage.length > 0
+ ? requiredMessage
+ : `${Subject} required`;
+ throw new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ // Null bytes terminate C strings — some POSIX syscalls treat the prefix
+ // as a separate path. Reject up front so it can't reach the FS layer.
+ if (filename.includes('\0')) {
+ throw new ServerError(`Invalid ${subjectText}`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const isExactTraversal = filename === '.' || filename === '..';
+ const hasSeparator = filename.includes('/') || filename.includes('\\');
+ const isPureBasename = basename(filename) === filename;
+ // Leading dot is fine for normal hidden files, but combined with the no-
+ // separator rule it's already covered above for `.`/`..`. We keep the
+ // basename equality check so e.g. `subdir\foo.png` (which has a `\` and
+ // also has basename `foo.png`) is still rejected by hasSeparator.
+ const lower = filename.toLowerCase();
+ const extOk = extensions.some((ext) => lower.endsWith(String(ext).toLowerCase()));
+ if (!extOk || hasSeparator || isExactTraversal || !isPureBasename) {
+ throw new ServerError(`Invalid ${subjectText}`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+}
+
// Size in bytes of every file under `path`. Shells out to `du -sk` (or
// PowerShell on Windows) — orders of magnitude faster than walking with
// node's recursive readdir on large trees (hundreds of GB / 200k+ files).
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 50ac239c17..f4e61f849c 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -3,6 +3,7 @@ import { writeFile, rm, mkdir } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
import {
+ assertSafeFilename,
isValidJSON,
safeJSONParse,
safeJSONLParse,
@@ -331,4 +332,99 @@ describe('fileUtils', () => {
expect(formatDuration(50 * 60 * 60000)).toBe('2d 2h');
});
});
+
+ describe('assertSafeFilename', () => {
+ it('accepts a safe basename with an allowlisted extension', () => {
+ expect(() => assertSafeFilename('foo.png', { extensions: ['.png'] })).not.toThrow();
+ expect(() => assertSafeFilename('lora-cool.safetensors', { extensions: ['.safetensors'] })).not.toThrow();
+ });
+
+ it('matches extensions case-insensitively', () => {
+ expect(() => assertSafeFilename('FOO.PNG', { extensions: ['.png'] })).not.toThrow();
+ expect(() => assertSafeFilename('cool.SafeTensors', { extensions: ['.safetensors'] })).not.toThrow();
+ });
+
+ it('allows substring `..` in the middle of a name', () => {
+ expect(() => assertSafeFilename('my..render.png', { extensions: ['.png'] })).not.toThrow();
+ });
+
+ it('rejects path separators', () => {
+ expect(() => assertSafeFilename('sub/foo.png', { extensions: ['.png'] })).toThrow(/Invalid filename/);
+ expect(() => assertSafeFilename('sub\\foo.png', { extensions: ['.png'] })).toThrow(/Invalid filename/);
+ });
+
+ it('rejects exact-traversal `.` and `..`', () => {
+ expect(() => assertSafeFilename('.', { extensions: ['.png'] })).toThrow(/Invalid filename/);
+ expect(() => assertSafeFilename('..', { extensions: ['.png'] })).toThrow(/Invalid filename/);
+ });
+
+ it('rejects null bytes', () => {
+ expect(() => assertSafeFilename('foo\0.png', { extensions: ['.png'] })).toThrow(/Invalid filename/);
+ });
+
+ it('rejects empty or non-string inputs', () => {
+ expect(() => assertSafeFilename('', { extensions: ['.png'] })).toThrow(/Filename required/);
+ expect(() => assertSafeFilename(undefined, { extensions: ['.png'] })).toThrow(/Filename required/);
+ expect(() => assertSafeFilename(null, { extensions: ['.png'] })).toThrow(/Filename required/);
+ });
+
+ it('rejects unrecognized extensions', () => {
+ expect(() => assertSafeFilename('foo.jpg', { extensions: ['.png'] })).toThrow(/Invalid filename/);
+ expect(() => assertSafeFilename('foo.exe', { extensions: ['.png', '.gif'] })).toThrow(/Invalid filename/);
+ });
+
+ it('uses subject in error messages', () => {
+ expect(() => assertSafeFilename('', { extensions: ['.safetensors'], subject: 'LoRA filename' }))
+ .toThrow(/LoRA filename required/);
+ expect(() => assertSafeFilename('foo.jpg', { extensions: ['.safetensors'], subject: 'LoRA filename' }))
+ .toThrow(/Invalid LoRA filename/);
+ });
+
+ it('throws on missing extensions option (programmer error, not user)', () => {
+ expect(() => assertSafeFilename('foo.png', {})).toThrow(/extensions allowlist is required/);
+ expect(() => assertSafeFilename('foo.png', { extensions: [] })).toThrow(/extensions allowlist is required/);
+ });
+
+ it('throws on extensions that do not start with a dot (programmer error)', () => {
+ // Bare suffix like 'png' would also match 'not-an-imagepng' if we didn't
+ // enforce the leading-dot rule — that's a serious validation hole.
+ expect(() => assertSafeFilename('foo.png', { extensions: ['png'] }))
+ .toThrow(/each extension must be a non-empty string starting with/);
+ expect(() => assertSafeFilename('foo.png', { extensions: ['.png', 'jpg'] }))
+ .toThrow(/each extension must be a non-empty string starting with/);
+ expect(() => assertSafeFilename('foo.png', { extensions: [''] }))
+ .toThrow(/each extension must be a non-empty string starting with/);
+ expect(() => assertSafeFilename('foo.png', { extensions: ['.'] }))
+ .toThrow(/each extension must be a non-empty string starting with/);
+ expect(() => assertSafeFilename('foo.png', { extensions: [123] }))
+ .toThrow(/each extension must be a non-empty string starting with/);
+ });
+
+ it('honors requiredMessage override for the missing-input case only', () => {
+ // Backward-compat path: wrappers that used to throw a fixed phrase
+ // (e.g. "Filename required" / "Invalid filename") can preserve that
+ // message without affecting the invalid-input message.
+ expect(() => assertSafeFilename('', {
+ extensions: ['.safetensors'],
+ subject: 'LoRA filename',
+ requiredMessage: 'Filename required',
+ })).toThrow(/^Filename required$/);
+ // Invalid path still uses the subject-derived message.
+ expect(() => assertSafeFilename('foo.jpg', {
+ extensions: ['.safetensors'],
+ subject: 'LoRA filename',
+ requiredMessage: 'Filename required',
+ })).toThrow(/^Invalid LoRA filename$/);
+ });
+
+ it('attaches 400 status + VALIDATION_ERROR code on the thrown ServerError', () => {
+ try {
+ assertSafeFilename('bad/path.png', { extensions: ['.png'] });
+ throw new Error('Expected assertion to throw');
+ } catch (err) {
+ expect(err.status).toBe(400);
+ expect(err.code).toBe('VALIDATION_ERROR');
+ }
+ });
+ });
});
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index 5ca4a93cae..9c769196b4 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -19,6 +19,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import { join, dirname } from 'path';
import { PATHS } from './fileUtils.js';
+import { RUNNER_FAMILIES } from './runners.js';
// fileUtils.ensureDir is async/Promise-returning; this module needs a
// synchronous version because `loadMediaModels()` is called at import-time
// from videoGen/imageGen modules, which can't await before exporting.
@@ -187,7 +188,7 @@ const arrayOrDefault = (v, fallback) => (Array.isArray(v) ? v : fallback);
// flux2 model but is missing the runner discriminator. User overrides for
// other fields (custom name, steps, repo) are preserved.
const FLUX2_DEFAULTS_BY_ID = Object.fromEntries(
- DEFAULT_REGISTRY.image.filter((m) => m.runner === 'flux2').map((m) => [m.id, m])
+ DEFAULT_REGISTRY.image.filter((m) => m.runner === RUNNER_FAMILIES.FLUX2).map((m) => [m.id, m])
);
const upgradeImageEntries = (list) => {
@@ -203,7 +204,7 @@ const upgradeImageEntries = (list) => {
// to clear). Any other broken value the user added is intentional and
// preserved.
const { broken, ...rest } = entry;
- const merged = { ...seed, ...rest, runner: 'flux2' };
+ const merged = { ...seed, ...rest, runner: RUNNER_FAMILIES.FLUX2 };
if (broken !== undefined && broken !== 'macos') merged.broken = broken;
return merged;
});
@@ -236,9 +237,9 @@ const backfillCfgDisabled = (list) => {
});
};
-export const isFlux2 = (model) => model?.runner === 'flux2';
-export const isZImage = (model) => model?.runner === 'z-image';
-export const isErnie = (model) => model?.runner === 'ernie';
+export const isFlux2 = (model) => model?.runner === RUNNER_FAMILIES.FLUX2;
+export const isZImage = (model) => model?.runner === RUNNER_FAMILIES.Z_IMAGE;
+export const isErnie = (model) => model?.runner === RUNNER_FAMILIES.ERNIE;
export const isCfgDisabled = (model) => model?.cfgDisabled === true;
// Append models that are genuinely new in this release (not in
@@ -393,6 +394,44 @@ const normalizeRegistry = (parsed) => {
};
};
+// Detect drift between `_shippedDefaults` and the user's live list. We
+// previously hit a real install (2026-05-09) where `_shippedDefaults.image.list`
+// claimed all default ids had been shipped but the user's `image[]` array was
+// missing several of them — most likely from a partial editor save or a
+// concurrent-write race. The deletion-survives-upgrade contract then
+// permanently skipped re-adding those built-ins on every restart. We DON'T
+// auto-recover (that would defeat real deletions), but we make the drift
+// loud at boot so a user / sysadmin can act on it.
+//
+// IMPORTANT: this state is structurally indistinguishable from an INTENTIONAL
+// deletion — `appendNewlyShippedEntries` skips re-adding ids that are in
+// shippedIds but not userList for exactly that reason. There is no "silence
+// without re-adding" path today: removing an id from `_shippedDefaults`
+// flips it back to "genuinely new built-in" and normalizeRegistry will
+// re-append it on next boot. So if the absence is intentional, this log
+// fires every restart — users can either live with it, or accept the
+// re-add and delete the entry again from the UI. We surface it anyway
+// because the silent-skipping behaviour was the original bug.
+//
+// `kind` is either 'image' (single list at `_shippedDefaults.image.list`)
+// or 'video' (per-platform arrays at `_shippedDefaults.video.macos` /
+// `_shippedDefaults.video.windows`).
+const warnDrift = (kind, platform, shippedIds, defaultIds, presentIds) => {
+ const shippedSet = new Set(shippedIds || []);
+ const defaultSet = new Set(defaultIds || []);
+ const presentSet = new Set(presentIds || []);
+ for (const id of shippedSet) {
+ if (!defaultSet.has(id)) continue; // not a current built-in; ignore
+ if (presentSet.has(id)) continue; // present — no drift
+ // shippedIds for image lives at `_shippedDefaults.image.list`; for video
+ // it's `_shippedDefaults.video.{macos,windows}` directly. Surface the
+ // accurate key so a copy-paste from the warning lands in the right place.
+ const where = platform ? `${kind}.${platform}` : kind;
+ const shippedKey = platform ? `_shippedDefaults.${kind}.${platform}` : `_shippedDefaults.${kind}.list`;
+ console.log(`⚠️ media-models drift: built-in "${id}" was shipped but is missing from ${where}[] — if the deletion is intentional this warning will repeat each boot (no silence-without-restore path exists); to restore, either re-add the entry manually or delete ${shippedKey} entirely to re-bootstrap`);
+ }
+};
+
export const loadMediaModels = () => {
if (cached) return cached;
seedIfMissing();
@@ -409,6 +448,44 @@ export const loadMediaModels = () => {
} catch (err) {
console.log(`⚠️ Failed to load ${REGISTRY_FILE} (${err.message}) — using built-in defaults`);
}
+ // Drift check runs on the RAW parsed file (pre-normalize), because
+ // normalizeRegistry uses _shippedDefaults to decide which built-ins to
+ // re-add and which to skip. We want to surface the mismatch as it exists
+ // on disk, not the post-merge view. Skip when no parsed file at all (the
+ // catch above already logged) or when _shippedDefaults isn't populated yet
+ // (bootstrap path — no drift is possible).
+ if (readOk && isPlainObject(parsed?._shippedDefaults)) {
+ const sd = parsed._shippedDefaults;
+ if (isPlainObject(sd.image) && Array.isArray(parsed.image)) {
+ warnDrift(
+ 'image',
+ null,
+ Array.isArray(sd.image.list) ? sd.image.list : [],
+ DEFAULT_REGISTRY.image.map((m) => m.id),
+ parsed.image.map((m) => m?.id).filter((id) => typeof id === 'string'),
+ );
+ }
+ if (isPlainObject(sd.video) && isPlainObject(parsed.video)) {
+ if (Array.isArray(sd.video.macos) && Array.isArray(parsed.video.macos)) {
+ warnDrift(
+ 'video',
+ 'macos',
+ sd.video.macos,
+ DEFAULT_REGISTRY.video.macos.map((m) => m.id),
+ parsed.video.macos.map((m) => m?.id).filter((id) => typeof id === 'string'),
+ );
+ }
+ if (Array.isArray(sd.video.windows) && Array.isArray(parsed.video.windows)) {
+ warnDrift(
+ 'video',
+ 'windows',
+ sd.video.windows,
+ DEFAULT_REGISTRY.video.windows.map((m) => m.id),
+ parsed.video.windows.map((m) => m?.id).filter((id) => typeof id === 'string'),
+ );
+ }
+ }
+ }
cached = normalizeRegistry(parsed);
// Persist _shippedDefaults back to disk whenever it was absent or gained new
// ids (bootstrap run or a new built-in model shipped in this release). This
diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.js
index a7b611f088..02f35011e1 100644
--- a/server/lib/mediaModels.test.js
+++ b/server/lib/mediaModels.test.js
@@ -501,4 +501,129 @@ describe('mediaModels registry', () => {
expect(reg._shippedDefaults.video.macos).toContain('ltx23_dgrauet_q8');
logSpy.mockRestore();
});
+
+ // _shippedDefaults ↔ image[] drift — surfaced as a loud warning at boot.
+ // The deletion-survives-upgrade contract means any built-in in
+ // `_shippedDefaults` AND in DEFAULT_REGISTRY but missing from the user's
+ // image[] will never be re-added on its own. The drift was real (a
+ // 2026-05-09 install hit it after a partial editor save / write race).
+
+ it('drift warning fires when a shipped built-in is missing from image[]', async () => {
+ // _shippedDefaults claims z-image-turbo-bf16 was shipped, but the user's
+ // image[] array doesn't have it (and it IS a current DEFAULT_REGISTRY
+ // entry, so this is true drift — not a legitimate deletion).
+ writeFileSync(registryFile, JSON.stringify({
+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },
+ image: [
+ { id: 'dev', name: 'Flux 1 Dev' },
+ // 'z-image-turbo-bf16' deliberately missing
+ ],
+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],
+ selectedTextEncoder: 't',
+ _shippedDefaults: {
+ video: { macos: [], windows: [] },
+ image: { list: ['dev', 'z-image-turbo-bf16'] },
+ },
+ }));
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { loadMediaModels } = await import('./mediaModels.js');
+ loadMediaModels();
+ const driftCalls = logSpy.mock.calls
+ .map((args) => args.join(' '))
+ .filter((line) => line.includes('media-models drift'));
+ expect(driftCalls.length).toBeGreaterThan(0);
+ expect(driftCalls.some((c) => c.includes('z-image-turbo-bf16'))).toBe(true);
+ logSpy.mockRestore();
+ });
+
+ it('drift warning does NOT fire for an id no longer in DEFAULT_REGISTRY', async () => {
+ // _shippedDefaults includes a legacy id (e.g. an old experimental model
+ // that we removed from DEFAULT_REGISTRY) — that's not drift, it's normal
+ // upgrade churn. The warning must skip it.
+ writeFileSync(registryFile, JSON.stringify({
+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },
+ image: [{ id: 'dev', name: 'Flux 1 Dev' }],
+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],
+ selectedTextEncoder: 't',
+ _shippedDefaults: {
+ video: { macos: [], windows: [] },
+ image: { list: ['dev', 'ancient-removed-model'] },
+ },
+ }));
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { loadMediaModels } = await import('./mediaModels.js');
+ loadMediaModels();
+ const driftCalls = logSpy.mock.calls
+ .map((args) => args.join(' '))
+ .filter((line) => line.includes('media-models drift'));
+ expect(driftCalls.some((c) => c.includes('ancient-removed-model'))).toBe(false);
+ logSpy.mockRestore();
+ });
+
+ it('drift warning fires for video.macos as well as image', async () => {
+ const platformKey = process.platform === 'win32' ? 'windows' : 'macos';
+ const otherKey = process.platform === 'win32' ? 'macos' : 'windows';
+ // _shippedDefaults claims ltx23_dgrauet_q4 was shipped (and it IS still
+ // in DEFAULT_REGISTRY.video.macos), but the user's macos list doesn't
+ // have it.
+ const driftedId = 'ltx23_dgrauet_q4';
+ const userPlatformList = platformKey === 'macos' ? [
+ { id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'mlx_video', steps: 30, guidance: 3.0 },
+ // ltx23_dgrauet_q4 deliberately absent (drift)
+ ] : [
+ { id: 'ltx_video', name: 'LTX', runtime: 'mlx_video', steps: 25, guidance: 3.0 },
+ ];
+ writeFileSync(registryFile, JSON.stringify({
+ video: {
+ [platformKey]: userPlatformList,
+ [otherKey]: [],
+ defaultMacos: 'ltx2_unified',
+ defaultWindows: 'ltx_video',
+ },
+ image: [],
+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],
+ selectedTextEncoder: 't',
+ _shippedDefaults: {
+ video: {
+ macos: platformKey === 'macos' ? ['ltx2_unified', driftedId] : [],
+ windows: platformKey === 'windows' ? ['ltx_video'] : [],
+ },
+ image: { list: [] },
+ },
+ }));
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { loadMediaModels } = await import('./mediaModels.js');
+ loadMediaModels();
+ const driftCalls = logSpy.mock.calls
+ .map((args) => args.join(' '))
+ .filter((line) => line.includes('media-models drift'));
+ // Only assert on macos to avoid platform divergence in CI — the macos
+ // built-in list is the populated one for both test runs.
+ if (platformKey === 'macos') {
+ expect(driftCalls.some((c) => c.includes(driftedId) && c.includes('video.macos'))).toBe(true);
+ }
+ logSpy.mockRestore();
+ });
+
+ it('does NOT auto-recover the drifted entry (warn loud, but trust the registry on disk)', async () => {
+ // Same setup as the first drift test — confirm that the warning does
+ // NOT cause normalizeRegistry to silently re-add the missing built-in.
+ // Auto-recovery would defeat real deletions.
+ writeFileSync(registryFile, JSON.stringify({
+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },
+ image: [{ id: 'dev', name: 'Flux 1 Dev' }],
+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],
+ selectedTextEncoder: 't',
+ _shippedDefaults: {
+ video: { macos: [], windows: [] },
+ image: { list: ['dev', 'z-image-turbo-bf16'] },
+ },
+ }));
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { loadMediaModels, getImageModels } = await import('./mediaModels.js');
+ loadMediaModels();
+ const ids = getImageModels().map((m) => m.id);
+ expect(ids).not.toContain('z-image-turbo-bf16');
+ logSpy.mockRestore();
+ });
});
diff --git a/server/lib/objects.js b/server/lib/objects.js
new file mode 100644
index 0000000000..88469cec36
--- /dev/null
+++ b/server/lib/objects.js
@@ -0,0 +1,36 @@
+/**
+ * Object utilities.
+ *
+ * `deepMerge` is the project's shared deep-merge — promoted from
+ * `services/voice/config.js` after the same pattern was reinvented in
+ * `services/meatspacePost.js` and `routes/loras.js#POST /auth/civitai`.
+ *
+ * Semantics (matches the original voice/config.js implementation):
+ * - Both base[k] and patch[k] are plain objects → recurse.
+ * - Arrays are REPLACED, not merged (Object.entries iterates patch's keys
+ * so the entire array under each key is replaced; this matches every
+ * existing call site's expectation that arrays are leaf values).
+ * - Primitives, null, and any non-plain-object value at patch[k] overwrite
+ * base[k] verbatim.
+ * - When patch itself is not a plain object, returns patch directly
+ * (preserving the "patch is the new value" intent), unless patch is
+ * undefined — then returns base unchanged so callers can pass an
+ * optional patch without losing the defaults.
+ * - When `base` is null/undefined/non-object, it's treated as an empty
+ * object — `deepMerge(undefined, { a: 1 })` returns `{ a: 1 }`. This
+ * matches the function's own `base?.[k]` recursion guard, which already
+ * assumes a missing base is fine.
+ *
+ * Does NOT mutate `base`.
+ */
+
+const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+
+export const deepMerge = (base, patch) => {
+ if (!isPlainObject(patch)) return patch === undefined ? base : patch;
+ const out = { ...(isPlainObject(base) ? base : {}) };
+ for (const [k, v] of Object.entries(patch)) {
+ out[k] = isPlainObject(base?.[k]) && isPlainObject(v) ? deepMerge(base[k], v) : v;
+ }
+ return out;
+};
diff --git a/server/lib/objects.test.js b/server/lib/objects.test.js
new file mode 100644
index 0000000000..64be7fb366
--- /dev/null
+++ b/server/lib/objects.test.js
@@ -0,0 +1,65 @@
+import { describe, it, expect } from 'vitest';
+import { deepMerge } from './objects.js';
+
+describe('deepMerge', () => {
+ it('merges nested objects recursively', () => {
+ const base = { a: { b: 1, c: 2 }, d: 3 };
+ const patch = { a: { c: 20, e: 30 } };
+ expect(deepMerge(base, patch)).toEqual({ a: { b: 1, c: 20, e: 30 }, d: 3 });
+ });
+
+ it('overrides primitives at the patch key', () => {
+ expect(deepMerge({ a: 1 }, { a: 2 })).toEqual({ a: 2 });
+ expect(deepMerge({ a: 'old' }, { a: 'new' })).toEqual({ a: 'new' });
+ expect(deepMerge({ a: true }, { a: false })).toEqual({ a: false });
+ });
+
+ it('replaces arrays rather than merging them (canonical contract)', () => {
+ expect(deepMerge({ items: [1, 2, 3] }, { items: [9] })).toEqual({ items: [9] });
+ expect(deepMerge({ a: { items: [1, 2] } }, { a: { items: [] } })).toEqual({ a: { items: [] } });
+ });
+
+ it('treats null as a value override, not as object-to-recurse', () => {
+ expect(deepMerge({ a: { b: 1 } }, { a: null })).toEqual({ a: null });
+ expect(deepMerge({ a: null }, { a: { b: 2 } })).toEqual({ a: { b: 2 } });
+ });
+
+ it('preserves base keys not mentioned in patch', () => {
+ expect(deepMerge({ a: 1, b: 2 }, { b: 20 })).toEqual({ a: 1, b: 20 });
+ });
+
+ it('returns base unchanged when patch is undefined', () => {
+ const base = { a: 1 };
+ expect(deepMerge(base, undefined)).toBe(base);
+ });
+
+ it('returns patch directly when patch is not a plain object (number, string, array)', () => {
+ expect(deepMerge({ a: 1 }, 42)).toBe(42);
+ expect(deepMerge({ a: 1 }, 'replace')).toBe('replace');
+ const arr = [1, 2];
+ expect(deepMerge({ a: 1 }, arr)).toBe(arr);
+ });
+
+ it('does not mutate the base object', () => {
+ const base = { a: { b: 1 } };
+ const snapshot = JSON.parse(JSON.stringify(base));
+ deepMerge(base, { a: { c: 2 } });
+ expect(base).toEqual(snapshot);
+ });
+
+ it('handles missing base keys cleanly when patch has nested objects', () => {
+ // base.a doesn't exist; patch.a is an object — should land verbatim
+ expect(deepMerge({}, { a: { b: 1 } })).toEqual({ a: { b: 1 } });
+ });
+
+ it('treats a missing/null/non-object base as an empty object', () => {
+ // `base?.[k]` recursion guard already tolerated missing bases — formalize
+ // it for the top-level so callers can pass `deepMerge(saved ?? null, patch)`
+ // without a TypeError when saved was never written.
+ expect(deepMerge(undefined, { a: 1 })).toEqual({ a: 1 });
+ expect(deepMerge(null, { a: 1, b: { c: 2 } })).toEqual({ a: 1, b: { c: 2 } });
+ expect(deepMerge(42, { a: 1 })).toEqual({ a: 1 });
+ expect(deepMerge('string', { a: 1 })).toEqual({ a: 1 });
+ expect(deepMerge([1, 2], { a: 1 })).toEqual({ a: 1 });
+ });
+});
diff --git a/server/lib/runners.js b/server/lib/runners.js
new file mode 100644
index 0000000000..f86afb57a2
--- /dev/null
+++ b/server/lib/runners.js
@@ -0,0 +1,33 @@
+/**
+ * Image-runner family constants — single source of truth for the runner ids
+ * (`'mflux' | 'flux2' | 'z-image' | 'ernie'`) that distinguish which Python
+ * runner backs an image-gen model entry.
+ *
+ * Bare-string runner ids previously sprawled across `server/lib/civitai.js`,
+ * `server/lib/mediaModels.js`, `client/src/pages/ImageGen.jsx`, and the
+ * `RUNNER_LABEL` / `RUNNER_BADGE_CLASS` maps in `client/src/pages/Loras.jsx`.
+ * A typo in any one of those sites silently broke the LoRA picker's compat
+ * filter, since `runnerFamily === 'zimage'` (wrong) just doesn't match
+ * `runner === 'z-image'` (right). Importing from this module locks the
+ * canonical strings in place.
+ *
+ * The client mirrors this list at `client/src/lib/runnerFamilies.js` —
+ * Vite's fs.allow doesn't cross the server/ boundary, so we keep the two
+ * files manually in sync (same convention as `scenePrompt.js`).
+ */
+
+export const RUNNER_FAMILIES = Object.freeze({
+ MFLUX: 'mflux',
+ FLUX2: 'flux2',
+ Z_IMAGE: 'z-image',
+ ERNIE: 'ernie',
+});
+
+// Convenience predicate helpers — match the semantics of the existing
+// `isFlux2()` / `isZImage()` / `isErnie()` exports in `mediaModels.js`
+// (which still exist for back-compat with their many call sites). New code
+// can import either; same result.
+export const isMflux = (model) => model?.runner === RUNNER_FAMILIES.MFLUX;
+export const isFlux2 = (model) => model?.runner === RUNNER_FAMILIES.FLUX2;
+export const isZImage = (model) => model?.runner === RUNNER_FAMILIES.Z_IMAGE;
+export const isErnie = (model) => model?.runner === RUNNER_FAMILIES.ERNIE;
diff --git a/server/lib/runners.test.js b/server/lib/runners.test.js
new file mode 100644
index 0000000000..36e4a34314
--- /dev/null
+++ b/server/lib/runners.test.js
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+import { RUNNER_FAMILIES, isMflux, isFlux2, isZImage, isErnie } from './runners.js';
+
+const __dirname_self = dirname(fileURLToPath(import.meta.url));
+const CLIENT_MIRROR_PATH = join(__dirname_self, '..', '..', 'client', 'src', 'lib', 'runnerFamilies.js');
+
+describe('RUNNER_FAMILIES', () => {
+ it('exports the four canonical runner ids', () => {
+ expect(RUNNER_FAMILIES.MFLUX).toBe('mflux');
+ expect(RUNNER_FAMILIES.FLUX2).toBe('flux2');
+ expect(RUNNER_FAMILIES.Z_IMAGE).toBe('z-image');
+ expect(RUNNER_FAMILIES.ERNIE).toBe('ernie');
+ });
+
+ it('is frozen so callers can\'t mutate the canonical strings at runtime', () => {
+ expect(Object.isFrozen(RUNNER_FAMILIES)).toBe(true);
+ });
+
+ it('client mirror at client/src/lib/runnerFamilies.js carries the same ids', () => {
+ // The mirror is plain JS (not importable from a Vitest server suite —
+ // Vite's fs.allow doesn't cross), so we string-grep the file. Any
+ // change to a canonical id has to be reflected in both places, or this
+ // test fails.
+ const text = readFileSync(CLIENT_MIRROR_PATH, 'utf-8');
+ expect(text).toMatch(/MFLUX:\s*'mflux'/);
+ expect(text).toMatch(/FLUX2:\s*'flux2'/);
+ expect(text).toMatch(/Z_IMAGE:\s*'z-image'/);
+ expect(text).toMatch(/ERNIE:\s*'ernie'/);
+ });
+
+ it('predicate helpers match on the canonical runner ids', () => {
+ expect(isMflux({ runner: 'mflux' })).toBe(true);
+ expect(isFlux2({ runner: 'flux2' })).toBe(true);
+ expect(isZImage({ runner: 'z-image' })).toBe(true);
+ expect(isErnie({ runner: 'ernie' })).toBe(true);
+ expect(isFlux2({ runner: 'mflux' })).toBe(false);
+ expect(isFlux2(null)).toBe(false);
+ expect(isFlux2(undefined)).toBe(false);
+ });
+});
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 0f3639c605..9a94bf09d7 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -246,7 +246,7 @@ router.get('/models', (_req, res) => {
});
router.get('/loras', asyncHandler(async (_req, res) => {
- res.json(await local.listLoras());
+ res.json(await local.listLoraFilenames());
}));
router.get('/gallery', asyncHandler(async (_req, res) => {
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 635f9333c8..e18fd537bc 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -12,7 +12,7 @@ vi.mock('../services/imageGen/index.js', () => ({
IMAGE_GEN_MODES: ['external', 'local', 'codex'],
local: {
listImageModels: vi.fn(() => []),
- listLoras: vi.fn(async () => []),
+ listLoraFilenames: vi.fn(async () => []),
listGallery: vi.fn(async () => []),
deleteImage: vi.fn(async () => ({ ok: true })),
},
diff --git a/server/routes/loras.js b/server/routes/loras.js
index 02194d50b7..68f81d65f3 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -10,6 +10,7 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../lib/errorHandler.js';
+import { deepMerge } from '../lib/objects.js';
import { validateRequest } from '../lib/validation.js';
import {
deleteLora,
@@ -55,10 +56,10 @@ router.get('/auth/civitai', asyncHandler(async (_req, res) => {
const authPostSchema = z.object({ apiKey: z.string().min(1).max(256) });
router.post('/auth/civitai', asyncHandler(async (req, res) => {
const { apiKey } = validateRequest(authPostSchema, req.body);
- // Manual deep-merge so future civitai sub-fields don't get clobbered by
- // updateSettings' shallow-merge contract.
+ // Shared deepMerge so future civitai sub-fields don't get clobbered by
+ // updateSettings' shallow-merge contract (see lib/objects.js).
const current = await getSettings();
- await saveSettings({ ...current, civitai: { ...(current.civitai || {}), apiKey: apiKey.trim() } });
+ await saveSettings(deepMerge(current, { civitai: { apiKey: apiKey.trim() } }));
res.json({ hasKey: true, source: 'settings' });
}));
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 2625c0aabd..0613945f81 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -18,7 +18,7 @@ import { existsSync, watch as fsWatch } from 'fs';
import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
-import { ensureDir, PATHS, safeJSONParse } from '../../lib/fileUtils.js';
+import { assertSafeFilename, ensureDir, PATHS, safeJSONParse } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
@@ -512,14 +512,18 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
}
// Validate a gallery filename: PNG-only, basename only, no path separators.
-// `.endsWith('.png')` already rejects `.` and `..` so substring-`..` matching
-// would over-reject legitimate names like `my..render.png`. Throws a 400 so
-// callers don't have to repeat the check.
+// Delegates to the shared `assertSafeFilename` helper in fileUtils.js.
+// Substring `..` is allowed (e.g. `my..render.png` is fine) because the
+// helper only rejects the exact-string traversal cases.
+// `requiredMessage` preserves the original "Invalid filename" wording for
+// the missing-input case so existing client error-message expectations
+// (and the previously-shipped error-middleware contract) don't shift.
export function assertGalleryFilename(filename) {
- if (!filename || !filename.endsWith('.png')
- || filename.includes('/') || filename.includes('\\')) {
- throw new ServerError('Invalid filename', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ assertSafeFilename(filename, {
+ extensions: ['.png'],
+ subject: 'filename',
+ requiredMessage: 'Invalid filename',
+ });
}
// Returns `{ path, metadata }`. `path` is the resolved sidecar location, or
@@ -574,7 +578,13 @@ export async function setImageHidden(filename, hidden) {
// Returns just `{ filename, name }` — clients send `filename` back in the
// generate payload's `loraFilenames` and the server resolves it against
// PATHS.loras. Avoids leaking absolute server paths into the API surface.
-export async function listLoras() {
+//
+// Distinct from `services/loras.js#listLoras` which returns the rich
+// Civitai-aware shape (civitai, runnerFamily, triggerWords, etc.) for the
+// `/api/loras` manager UI. The two used to share the name `listLoras`;
+// rename here makes the shape distinction explicit so a future caller
+// can't import the wrong one and silently lose `civitai`/`runnerFamily`.
+export async function listLoraFilenames() {
await ensureDir(PATHS.loras);
const files = await readdir(PATHS.loras).catch(() => []);
return files.filter((f) => f.endsWith('.safetensors')).map((f) => ({
diff --git a/server/services/loras.js b/server/services/loras.js
index 0de413e766..5424fe0186 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -25,7 +25,7 @@ import { Readable } from 'stream';
import { pipeline } from 'stream/promises';
import { basename, join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
-import { PATHS } from '../lib/fileUtils.js';
+import { assertSafeFilename, PATHS } from '../lib/fileUtils.js';
import {
applyDownloadToken,
baseModelToRunner,
@@ -65,20 +65,19 @@ export const readSidecar = async (filename) => {
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
};
-// Validate a basename so it can't escape PATHS.loras. We require the input
-// equals its own basename (no path separators, no parent traversal) and ends
-// in `.safetensors`. Substring `..` is allowed because slugifyForFilename can
-// produce names like `foo..bar` from non-ASCII input.
+// Validate a basename so it can't escape PATHS.loras. Delegates to the
+// shared `assertSafeFilename` helper in fileUtils.js (which also handles
+// gallery .png assertions). Substring `..` is allowed because
+// slugifyForFilename can produce names like `foo..bar` from non-ASCII input.
+// `requiredMessage` preserves the historical "Filename required" wording
+// (instead of the subject-derived "LoRA filename required") so any client
+// or test that pattern-matches on the missing-input message keeps working.
export const assertSafeLoraFilename = (filename) => {
- if (!filename || typeof filename !== 'string') {
- throw new ServerError('Filename required', { status: 400, code: 'VALIDATION_ERROR' });
- }
- const isExactTraversal = filename === '.' || filename === '..';
- const hasSeparator = filename.includes('/') || filename.includes('\\');
- const isPureBasename = basename(filename) === filename;
- if (!filename.endsWith('.safetensors') || hasSeparator || isExactTraversal || !isPureBasename) {
- throw new ServerError('Invalid LoRA filename', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ assertSafeFilename(filename, {
+ extensions: ['.safetensors'],
+ subject: 'LoRA filename',
+ requiredMessage: 'Filename required',
+ });
};
// LoRAs without sidecars get a minimal "legacy" entry with sensible defaults
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 9621058dcf..b27b01293b 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -9,6 +9,7 @@ import { writeFile } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { deepMerge } from '../lib/objects.js';
import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';
const MEATSPACE_DIR = PATHS.meatspace;
@@ -351,19 +352,3 @@ function computeSessionScore(tasks) {
return Math.round(totalScore / valid.length);
}
-// =============================================================================
-// UTILITY
-// =============================================================================
-
-function deepMerge(target, source) {
- const result = { ...target };
- for (const key of Object.keys(source)) {
- if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key]) &&
- target[key] && typeof target[key] === 'object' && !Array.isArray(target[key])) {
- result[key] = deepMerge(target[key], source[key]);
- } else {
- result[key] = source[key];
- }
- }
- return result;
-}
diff --git a/server/services/mediaPromptRefiner.js b/server/services/mediaPromptRefiner.js
index d86fd592ce..899270ccae 100644
--- a/server/services/mediaPromptRefiner.js
+++ b/server/services/mediaPromptRefiner.js
@@ -1,6 +1,6 @@
import { ServerError } from '../lib/errorHandler.js';
import { getProviderById } from './providers.js';
-import { createRun, executeApiRun, executeCliRun } from './runner.js';
+import { createRun, executeApiRun, executeCliRun, hasModelFlag, extractBakedModel } from './runner.js';
const MAX_PROMPT_LEN = 8000;
const MAX_REASON_LEN = 1200;
@@ -134,14 +134,12 @@ async function runRefinePrompt(provider, model, prompt) {
}
};
if (provider.type === 'cli') {
- // `runner.js#buildCliArgs` only translates `provider.defaultModel` into
- // a `--model` flag for `codex` today; `claude-code` and `gemini-cli`
- // ignore it and run with whatever model is baked into provider.args.
- // Override defaultModel only when it'll actually take effect — otherwise
- // we'd lie to the caller about which model ran. (PLAN.md tracks the
- // shared-infra fix to extend buildCliArgs to all CLI providers.)
- const canOverrideModel = provider.id === 'codex';
- const providerForCli = canOverrideModel && model && model !== provider.defaultModel
+ // `runner.js#buildCliArgs` honors `provider.defaultModel` for every
+ // supported CLI provider (codex / claude-code / gemini-cli) — it
+ // injects `--model` / `-m` whenever the user hasn't already baked a
+ // model flag into provider.args. So cloning with an overridden
+ // defaultModel is safe for all CLI types.
+ const providerForCli = model && model !== provider.defaultModel
? { ...provider, defaultModel: model }
: provider;
executeCliRun(runId, providerForCli, prompt, process.cwd(), onData, onComplete, provider.timeout ?? 300000).catch(reject);
@@ -175,18 +173,20 @@ export async function refineMediaPrompt({
);
}
- // Resolve the model that'll actually run. For API + Codex CLI, the runner
- // honors the per-call `model` override. For other CLI providers (claude-code,
- // gemini-cli), `runner.js#buildCliArgs` ignores per-call model and runs
- // whatever's baked into provider.args / provider.defaultModel — so reporting
- // the user-requested model in the response/run-record would lie about which
- // model produced the output. Fall back through defaultModel → models[0] for
- // those providers so the returned `model` reflects reality. (PLAN.md tracks
- // extending buildCliArgs to honor per-call model for all CLI providers.)
- const honorsModelOverride = provider.type === 'api' || provider.id === 'codex';
+ // Resolve the model that'll actually run. API providers honor the per-call
+ // `model` override directly; for CLI providers, `runner.js#buildCliArgs`
+ // injects `--model`/`-m` from `provider.defaultModel` for every supported
+ // CLI (codex / claude-code / gemini-cli) UNLESS the user has already baked
+ // a model flag into provider.args. In the "baked flag" case the override
+ // is silently dropped and the model from args wins — so we surface that
+ // exact id (extracted from args) on the run record instead of guessing
+ // from defaultModel, which can diverge.
+ const cliHasBakedModelFlag = provider.type === 'cli' && hasModelFlag(provider.args);
+ const honorsModelOverride = provider.type === 'api' || (provider.type === 'cli' && !cliHasBakedModelFlag);
+ const bakedModel = cliHasBakedModelFlag ? extractBakedModel(provider.args) : null;
const selectedModel = honorsModelOverride
? (model || provider.defaultModel || provider.models?.[0] || '')
- : (provider.defaultModel || provider.models?.[0] || '');
+ : (bakedModel || provider.defaultModel || provider.models?.[0] || '');
if (!selectedModel && provider.type === 'api') {
throw new ServerError('Model is required for prompt refinement', { status: 400, code: 'MODEL_REQUIRED' });
}
diff --git a/server/services/mediaPromptRefiner.test.js b/server/services/mediaPromptRefiner.test.js
index 4e50132a8b..4ea5089bef 100644
--- a/server/services/mediaPromptRefiner.test.js
+++ b/server/services/mediaPromptRefiner.test.js
@@ -4,11 +4,21 @@ vi.mock('./providers.js', () => ({
getProviderById: vi.fn(),
}));
-vi.mock('./runner.js', () => ({
- createRun: vi.fn().mockResolvedValue({ runId: 'test-run' }),
- executeApiRun: vi.fn(),
- executeCliRun: vi.fn(),
-}));
+// Partial mock: stub the side-effectful run-execution surface (createRun /
+// executeApiRun / executeCliRun) but defer to the REAL helper exports for
+// hasModelFlag / extractBakedModel so the tests always exercise the
+// canonical parsing logic. If those helpers ever change semantics
+// (e.g. start rejecting --model with no value), the refiner tests pick
+// up the new behavior automatically.
+vi.mock('./runner.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ createRun: vi.fn().mockResolvedValue({ runId: 'test-run' }),
+ executeApiRun: vi.fn(),
+ executeCliRun: vi.fn(),
+ };
+});
const providers = await import('./providers.js');
const runner = await import('./runner.js');
@@ -173,11 +183,11 @@ ${JSON.stringify({ prompt: 'painted owl portrait', negativePrompt: 'blurry', rat
})).rejects.toMatchObject({ code: 'PROVIDER_DISABLED', status: 400 });
});
- it('ignores per-call model override for non-Codex CLIs since the runner cannot apply it', async () => {
- // runner.js#buildCliArgs only translates defaultModel into a --model flag
- // for codex. For claude-code / gemini-cli the per-call override would be
- // silently dropped, so the response model must reflect what'll actually
- // run (the provider's configured default), not the user's selection.
+ it('honors per-call model override for claude-code / gemini-cli when args do not pin a model', async () => {
+ // runner.js#buildCliArgs now injects --model/-m from provider.defaultModel
+ // for every CLI provider (codex / claude-code / gemini-cli), so cloning
+ // the provider with the user-selected model is safe and the response
+ // accurately reports what'll actually run.
providers.getProviderById.mockResolvedValue({
id: 'claude-code',
type: 'cli',
@@ -193,10 +203,61 @@ ${JSON.stringify({ prompt: 'painted owl portrait', negativePrompt: 'blurry', rat
prompt: 'p',
feedback: 'f',
providerId: 'claude-code',
- model: 'user-selected-model-the-runner-will-ignore',
+ model: 'user-selected-sonnet',
+ });
+
+ expect(result.model).toBe('user-selected-sonnet');
+ });
+
+ it('reports the args-baked model (not defaultModel) when a CLI provider pins a model in args', async () => {
+ // When the user has hard-coded `--model X` (or `-m X`) into provider.args,
+ // buildCliArgs skips injection and the saved arg wins — the per-call
+ // override is silently dropped. To match reality, the response should
+ // report the model extracted from args, NOT defaultModel (which might
+ // diverge from what the CLI will actually run with).
+ providers.getProviderById.mockResolvedValue({
+ id: 'claude-code',
+ type: 'cli',
+ enabled: true,
+ defaultModel: 'claude-stale-default',
+ args: ['--model', 'baked-in-from-args'],
+ });
+ mockRunnerSuccess(runner.executeCliRun, JSON.stringify({
+ prompt: 'x', negativePrompt: '', rationale: '', changes: [],
+ }));
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'p',
+ feedback: 'f',
+ providerId: 'claude-code',
+ model: 'user-selection-runner-will-drop',
+ });
+
+ expect(result.model).toBe('baked-in-from-args');
+ });
+
+ it('extracts the args-baked model from joined-form (--model=X) flags too', async () => {
+ providers.getProviderById.mockResolvedValue({
+ id: 'gemini-cli',
+ type: 'cli',
+ enabled: true,
+ defaultModel: 'gemini-stale-default',
+ args: ['-m=gemini-from-joined-arg'],
+ });
+ mockRunnerSuccess(runner.executeCliRun, JSON.stringify({
+ prompt: 'x', negativePrompt: '', rationale: '', changes: [],
+ }));
+
+ const result = await refineMediaPrompt({
+ kind: 'image',
+ prompt: 'p',
+ feedback: 'f',
+ providerId: 'gemini-cli',
+ model: 'user-selection-dropped',
});
- expect(result.model).toBe('claude-baked-in');
+ expect(result.model).toBe('gemini-from-joined-arg');
});
it('falls back to provider.models[0] when defaultModel is absent (API provider)', async () => {
diff --git a/server/services/runner.js b/server/services/runner.js
index 48e11040c9..667fee48e5 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -25,17 +25,32 @@ export async function createRun(options) {
/**
* Build CLI args based on provider type.
- * Each CLI provider has different conventions for stdin input and model selection.
+ * Each CLI provider has different conventions for stdin input and model
+ * selection. `provider.defaultModel` is honored for all three (codex /
+ * claude-code / gemini-cli) so a per-call clone with an overridden
+ * defaultModel (e.g. modal-selected "thinking" tier in Refine Prompt)
+ * actually picks the modal-selected model instead of falling back to
+ * whatever's baked into `provider.args`.
+ *
+ * Model-flag injection is GATED on `provider.args` not already containing
+ * a model flag — users who hard-coded e.g. `--model gemini-2.5-pro` in
+ * their saved provider config keep that override and don't get a
+ * duplicate flag from us.
*/
-function buildCliArgs(provider) {
+export function buildCliArgs(provider) {
const providerId = provider?.id || '';
+ // Sanitize: drop any broken/dangling `--model` / `-m` tokens before
+ // appending. hasModelFlag treats those as "not a real pin" so the
+ // injection path fires — but if we kept the bogus token in baseArgs the
+ // CLI would still see two `--model` occurrences and reject the argv.
+ const baseArgs = stripBrokenModelFlags(Array.isArray(provider?.args) ? provider.args : []);
const effectiveDefaultModel = providerId === 'codex' && provider.defaultModel === 'codex-configured-default'
? null
: provider.defaultModel;
// Codex CLI: `codex exec -` reads prompt from stdin, --model for model
if (providerId === 'codex') {
- const args = [...(provider.args || []), 'exec'];
+ const args = [...baseArgs, 'exec'];
if (effectiveDefaultModel) {
args.push('--model', effectiveDefaultModel);
}
@@ -43,13 +58,107 @@ function buildCliArgs(provider) {
return args;
}
- // Gemini CLI: prompt is piped via stdin directly
+ // Gemini CLI: prompt is piped via stdin directly. `-m <model>` is gemini-
+ // cli's documented short flag for model selection (long form: `--model`).
+ // Skip injection when the user's saved args already pin a model (either
+ // form) so we don't duplicate the flag.
if (providerId === 'gemini-cli') {
- return [...(provider.args || [])];
+ const args = [...baseArgs];
+ if (effectiveDefaultModel && !hasModelFlag(baseArgs)) {
+ args.push('-m', effectiveDefaultModel);
+ }
+ return args;
+ }
+
+ // Default (Claude Code CLI): `-p -` means "read prompt from stdin".
+ // `--model <id>` is claude-code's model flag; it parses flags
+ // positionally so appending after `-p -` is fine. Same gate as gemini-
+ // cli — respect user-baked model flags.
+ const args = [...baseArgs, '-p', '-'];
+ if (effectiveDefaultModel && !hasModelFlag(baseArgs)) {
+ args.push('--model', effectiveDefaultModel);
+ }
+ return args;
+}
+
+// Strip dangling/empty `--model` / `-m` tokens (no value follows, or the
+// joined form has an empty value). Those would survive into the spawned
+// argv unchanged and cause the CLI to reject the invocation — see the
+// comment on hasModelFlag for the full reasoning. Pinned-with-value tokens
+// are preserved untouched so user-baked model selections still win.
+function stripBrokenModelFlags(args) {
+ if (!Array.isArray(args) || args.length === 0) return [];
+ const out = [];
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (typeof a === 'string' && (a === '--model=' || a === '-m=')) {
+ continue; // empty joined form
+ }
+ if (a === '--model' || a === '-m') {
+ const next = args[i + 1];
+ const hasValue = typeof next === 'string' && next.length > 0 && !next.startsWith('-');
+ if (!hasValue) continue; // dangling separated form
+ }
+ out.push(a);
}
+ return out;
+}
+
+// Detects whether the provider's stored argv already pins a model with a
+// usable value. We check both flag forms (`--model` / `-m`) and both styles
+// (separated `--model x` and joined `--model=x`). gemini-cli is the only
+// one that uses `-m` short form; checking it on claude-code too is harmless
+// (claude-code doesn't define a `-m` short flag).
+//
+// A separated flag with no value following (`['--model']` at end of argv,
+// or `['--model', '--other']`) is treated as NOT a baked-in pin — the CLI
+// would reject the argv at runtime anyway, and pretending it's a pin would
+// also make refiners report `null` (from extractBakedModel) and skip
+// injecting our own model. Better to leave injection on and let
+// buildCliArgs fix the broken argv by appending a valid `--model X`.
+export function hasModelFlag(args) {
+ if (!Array.isArray(args)) return false;
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (typeof a !== 'string') continue;
+ if (a.startsWith('--model=') && a.length > '--model='.length) return true;
+ if (a.startsWith('-m=') && a.length > '-m='.length) return true;
+ if (a === '--model' || a === '-m') {
+ const next = args[i + 1];
+ if (typeof next === 'string' && next.length > 0 && !next.startsWith('-')) return true;
+ }
+ }
+ return false;
+}
- // Default (Claude Code CLI): -p - means "read prompt from stdin"
- return [...(provider.args || []), '-p', '-'];
+/**
+ * Extract the pinned model id from provider.args when a model flag is baked
+ * in. Supports separated form (`--model X` / `-m X`) and joined form
+ * (`--model=X` / `-m=X`). Returns null when no model flag is present or the
+ * separated form has no value following the flag.
+ *
+ * Used by refiners (mediaPromptRefiner, worldBuilderRefine) so the model
+ * reported back to the caller / persisted on the run record matches what
+ * the CLI will actually run when the user has hard-coded a model in args.
+ */
+export function extractBakedModel(args) {
+ if (!Array.isArray(args)) return null;
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (typeof a !== 'string') continue;
+ if (a === '--model' || a === '-m') {
+ const next = args[i + 1];
+ // Match hasModelFlag exactly: a value that starts with '-' is the next
+ // flag, not the model id. Without this guard, `['--model', '--other']`
+ // would extract `'--other'` even though hasModelFlag said "no baked
+ // model" — the two would disagree and refiners could mis-report.
+ if (typeof next === 'string' && next.length > 0 && !next.startsWith('-')) return next;
+ return null;
+ }
+ if (a.startsWith('--model=')) return a.slice('--model='.length) || null;
+ if (a.startsWith('-m=')) return a.slice('-m='.length) || null;
+ }
+ return null;
}
/**
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index b83a046720..ca6847ff55 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -17,7 +17,7 @@ vi.mock('fs/promises', () => ({
const { spawn } = await import('child_process');
const runner = await import('./runner.js');
-const { setAIToolkit, executeCliRun } = runner;
+const { setAIToolkit, executeCliRun, buildCliArgs, hasModelFlag, extractBakedModel } = runner;
// Minimal toolkit stub that satisfies executeCliRun's expectations
function fakeToolkit() {
@@ -97,3 +97,199 @@ describe('executeCliRun — Codex sentinel suppression', () => {
expect(capturedArgs[modelIdx + 1]).toBe('o4-mini');
});
});
+
+describe('buildCliArgs — claude-code defaultModel honoring', () => {
+ it('appends --model <id> after `-p -` for claude-code', () => {
+ const provider = { id: 'claude-code', command: 'claude', args: [], defaultModel: 'claude-opus-4-7' };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['-p', '-', '--model', 'claude-opus-4-7']);
+ });
+
+ it('omits --model when defaultModel is unset', () => {
+ const provider = { id: 'claude-code', command: 'claude', args: [], defaultModel: null };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['-p', '-']);
+ });
+
+ it('respects a user-baked --model in provider.args and does NOT duplicate', () => {
+ const provider = {
+ id: 'claude-code',
+ command: 'claude',
+ args: ['--model', 'claude-sonnet-4-5'],
+ defaultModel: 'claude-opus-4-7',
+ };
+ const args = buildCliArgs(provider);
+ // baked model wins, no extra trailing flag
+ expect(args).toEqual(['--model', 'claude-sonnet-4-5', '-p', '-']);
+ expect(args.filter((a) => a === '--model').length).toBe(1);
+ });
+
+ it('respects a user-baked --model=value joined form', () => {
+ const provider = {
+ id: 'claude-code',
+ command: 'claude',
+ args: ['--model=claude-sonnet-4-5'],
+ defaultModel: 'claude-opus-4-7',
+ };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['--model=claude-sonnet-4-5', '-p', '-']);
+ });
+});
+
+describe('buildCliArgs — gemini-cli defaultModel honoring', () => {
+ it('appends -m <id> for gemini-cli', () => {
+ const provider = { id: 'gemini-cli', command: 'gemini', args: [], defaultModel: 'gemini-2.5-pro' };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['-m', 'gemini-2.5-pro']);
+ });
+
+ it('omits -m when defaultModel is unset', () => {
+ const provider = { id: 'gemini-cli', command: 'gemini', args: [], defaultModel: null };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual([]);
+ });
+
+ it('respects a user-baked -m in provider.args', () => {
+ const provider = {
+ id: 'gemini-cli',
+ command: 'gemini',
+ args: ['-m', 'gemini-2.0-flash'],
+ defaultModel: 'gemini-2.5-pro',
+ };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['-m', 'gemini-2.0-flash']);
+ expect(args.filter((a) => a === '-m').length).toBe(1);
+ });
+
+ it('respects a user-baked --model in provider.args (long-form)', () => {
+ const provider = {
+ id: 'gemini-cli',
+ command: 'gemini',
+ args: ['--model', 'gemini-2.0-flash'],
+ defaultModel: 'gemini-2.5-pro',
+ };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['--model', 'gemini-2.0-flash']);
+ });
+});
+
+describe('buildCliArgs — codex (regression coverage for the existing logic)', () => {
+ it('omits --model when defaultModel is the sentinel', () => {
+ const provider = { id: 'codex', command: 'codex', args: [], defaultModel: 'codex-configured-default' };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['exec', '-']);
+ });
+
+ it('appends --model when a real model is given', () => {
+ const provider = { id: 'codex', command: 'codex', args: [], defaultModel: 'o4-mini' };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['exec', '--model', 'o4-mini', '-']);
+ });
+});
+
+describe('buildCliArgs — strips dangling --model from baseArgs before injecting', () => {
+ it('drops a bare --model at end of args (claude-code) and appends the valid one', () => {
+ const provider = { id: 'claude-code', command: 'claude', args: ['--model'], defaultModel: 'sonnet-3.7' };
+ const args = buildCliArgs(provider);
+ // Bare --model would survive into argv and conflict with our injected
+ // --model sonnet-3.7. The sanitizer drops it so only the valid pair remains.
+ expect(args).toEqual(['-p', '-', '--model', 'sonnet-3.7']);
+ });
+
+ it('drops a --model followed by another flag (gemini-cli) and appends the valid one', () => {
+ const provider = { id: 'gemini-cli', command: 'gemini', args: ['-m', '--other'], defaultModel: 'gemini-flash' };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['--other', '-m', 'gemini-flash']);
+ });
+
+ it('drops an empty joined model flag (--model=) and appends the valid one', () => {
+ const provider = { id: 'claude-code', command: 'claude', args: ['--model='], defaultModel: 'sonnet-3.7' };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['-p', '-', '--model', 'sonnet-3.7']);
+ });
+
+ it('drops dangling --model on codex too (regression)', () => {
+ const provider = { id: 'codex', command: 'codex', args: ['--model'], defaultModel: 'o4-mini' };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['exec', '--model', 'o4-mini', '-']);
+ });
+
+ it('preserves a properly-pinned --model and does NOT inject our own', () => {
+ const provider = { id: 'claude-code', command: 'claude', args: ['--model', 'baked-in'], defaultModel: 'would-be-ignored' };
+ const args = buildCliArgs(provider);
+ expect(args).toEqual(['--model', 'baked-in', '-p', '-']);
+ });
+});
+
+describe('hasModelFlag', () => {
+ it('detects separated long form (--model X)', () => {
+ expect(hasModelFlag(['--model', 'foo'])).toBe(true);
+ });
+ it('detects separated short form (-m X)', () => {
+ expect(hasModelFlag(['-m', 'foo'])).toBe(true);
+ });
+ it('detects joined long form (--model=X)', () => {
+ expect(hasModelFlag(['--model=foo'])).toBe(true);
+ });
+ it('detects joined short form (-m=X)', () => {
+ expect(hasModelFlag(['-m=foo'])).toBe(true);
+ });
+ it('returns false when no model flag is present', () => {
+ expect(hasModelFlag(['--other', 'foo'])).toBe(false);
+ expect(hasModelFlag([])).toBe(false);
+ });
+ it('returns false for non-array input', () => {
+ expect(hasModelFlag(null)).toBe(false);
+ expect(hasModelFlag(undefined)).toBe(false);
+ expect(hasModelFlag('--model foo')).toBe(false);
+ });
+ it('returns false for a separated flag at end of argv (no value follows)', () => {
+ expect(hasModelFlag(['--model'])).toBe(false);
+ expect(hasModelFlag(['-m'])).toBe(false);
+ expect(hasModelFlag(['--other', '--model'])).toBe(false);
+ });
+ it('returns false when the value following looks like another flag', () => {
+ expect(hasModelFlag(['--model', '--other'])).toBe(false);
+ expect(hasModelFlag(['-m', '-x'])).toBe(false);
+ });
+ it('returns false for an empty joined value (--model= / -m=)', () => {
+ expect(hasModelFlag(['--model='])).toBe(false);
+ expect(hasModelFlag(['-m='])).toBe(false);
+ });
+});
+
+describe('extractBakedModel', () => {
+ it('extracts from separated long form', () => {
+ expect(extractBakedModel(['--model', 'sonnet-3.7'])).toBe('sonnet-3.7');
+ });
+ it('extracts from separated short form', () => {
+ expect(extractBakedModel(['-m', 'gemini-2.5-pro'])).toBe('gemini-2.5-pro');
+ });
+ it('extracts from joined long form', () => {
+ expect(extractBakedModel(['--model=opus-4.7'])).toBe('opus-4.7');
+ });
+ it('extracts from joined short form', () => {
+ expect(extractBakedModel(['-m=gemini-flash'])).toBe('gemini-flash');
+ });
+ it('returns null when separated form has no value following the flag', () => {
+ expect(extractBakedModel(['--model'])).toBe(null);
+ });
+ it('returns null when the value following looks like another flag (matches hasModelFlag)', () => {
+ // Without this guard, extractBakedModel would extract '--other' as the
+ // model id while hasModelFlag returned false, leaving the two functions
+ // out of sync. Both must agree on what counts as a real pin.
+ expect(extractBakedModel(['--model', '--other'])).toBe(null);
+ expect(extractBakedModel(['-m', '-x'])).toBe(null);
+ });
+ it('returns null when no model flag is present', () => {
+ expect(extractBakedModel(['--other', 'foo'])).toBe(null);
+ expect(extractBakedModel([])).toBe(null);
+ });
+ it('returns null for non-array input', () => {
+ expect(extractBakedModel(null)).toBe(null);
+ expect(extractBakedModel(undefined)).toBe(null);
+ });
+ it('returns the FIRST baked flag when more than one is present', () => {
+ expect(extractBakedModel(['--model', 'first', '-m', 'second'])).toBe('first');
+ });
+});
diff --git a/server/services/voice/config.js b/server/services/voice/config.js
index c1f6393565..5f9333b820 100644
--- a/server/services/voice/config.js
+++ b/server/services/voice/config.js
@@ -5,6 +5,7 @@
import { homedir } from 'os';
import { join } from 'path';
import { getSettings, updateSettings } from '../settings.js';
+import { deepMerge } from '../../lib/objects.js';
const VOICE_HOME = join(homedir(), '.portos', 'voice');
@@ -79,17 +80,6 @@ export const VOICE_DEFAULTS = Object.freeze({
vad: { endOfSpeechMs: 700, minUtteranceMs: 250 },
});
-const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
-
-const deepMerge = (base, patch) => {
- if (!isObj(patch)) return patch === undefined ? base : patch;
- const out = { ...base };
- for (const [k, v] of Object.entries(patch)) {
- out[k] = isObj(base[k]) && isObj(v) ? deepMerge(base[k], v) : v;
- }
- return out;
-};
-
export const expandPath = (p) => {
if (typeof p !== 'string') return p;
if (p.startsWith('~/')) return join(homedir(), p.slice(2));
diff --git a/server/services/worldBuilderRefine.js b/server/services/worldBuilderRefine.js
index 4c3e5dbaf4..833bf1a31a 100644
--- a/server/services/worldBuilderRefine.js
+++ b/server/services/worldBuilderRefine.js
@@ -13,7 +13,7 @@
import { ServerError } from '../lib/errorHandler.js';
import { getActiveProvider, getProviderById } from './providers.js';
-import { createRun, executeApiRun, executeCliRun } from './runner.js';
+import { createRun, executeApiRun, executeCliRun, hasModelFlag, extractBakedModel } from './runner.js';
import {
PROMPT_FRAGMENT_MAX,
STARTER_PROMPT_MAX,
@@ -147,10 +147,11 @@ async function runRefine(provider, model, prompt) {
}
};
if (provider.type === 'cli') {
- // Mirror the media refiner: only Codex's `buildCliArgs` honors a per-call
- // model override today, so don't lie about which model ran for the others.
- const canOverrideModel = provider.id === 'codex';
- const providerForCli = canOverrideModel && model && model !== provider.defaultModel
+ // Mirror the media refiner: `buildCliArgs` now honors a per-call model
+ // override (via `provider.defaultModel`) for codex / claude-code /
+ // gemini-cli. Clone the provider with the overridden defaultModel
+ // whenever the caller picked something other than the saved default.
+ const providerForCli = model && model !== provider.defaultModel
? { ...provider, defaultModel: model }
: provider;
executeCliRun(runId, providerForCli, prompt, process.cwd(), onData, onComplete, provider.timeout ?? 300000).catch(reject);
@@ -198,10 +199,17 @@ export async function refineWorldPrompts({
);
}
- const honorsModelOverride = provider.type === 'api' || provider.id === 'codex';
+ // API providers honor per-call `model` directly; CLI providers do too via
+ // buildCliArgs (which injects --model/-m from provider.defaultModel),
+ // unless the user has hard-coded a model flag into provider.args — in
+ // that case the saved arg wins and we surface the model id parsed out of
+ // args so the response/run record matches what'll actually run.
+ const cliHasBakedModelFlag = provider.type === 'cli' && hasModelFlag(provider.args);
+ const honorsModelOverride = provider.type === 'api' || (provider.type === 'cli' && !cliHasBakedModelFlag);
+ const bakedModel = cliHasBakedModelFlag ? extractBakedModel(provider.args) : null;
const selectedModel = honorsModelOverride
? (model || provider.defaultModel || provider.models?.[0] || '')
- : (provider.defaultModel || provider.models?.[0] || '');
+ : (bakedModel || provider.defaultModel || provider.models?.[0] || '');
if (!selectedModel && provider.type === 'api') {
throw new ServerError('Model is required for world refinement', { status: 400, code: 'MODEL_REQUIRED' });
}