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
refactor(server): factor model resolution into resolveEffectiveModel — args-baked CLI models now win over defaultModel (#225)
[._.]/ Adam Eivya14fc4485473
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e8f52819d5..0c2adc30bb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -65,6 +65,8 @@## Fixed+- **Effective-model resolution for args-baked CLI providers.** Four callers (`stageRunner.runStagedLLM`, `worldBuilderExpand.expandWorldTemplate`, `worldBuilderRefine.refineWorldPrompts`, and `promptRunner.runPromptThroughProvider` itself) fell through to `provider.defaultModel || provider.models[0]` on the non-honoring CLI branch — but the actual model that runs for a CLI provider with a baked `--model`/`-m` flag in `provider.args` is the args-pinned id, which can diverge from `defaultModel`. Result: the run record, the pre-call log line, and the returned `llm.model` field could all lie when args win. Factored `mediaPromptRefiner`'s existing baked-model resolution into a shared `resolveEffectiveModel(provider, callerModel)` in `server/lib/promptRunner.js`, exported alongside `providerHonorsModelOverride`. It consults `hasModelFlag` + `extractBakedModel` from `services/runner.js` for the args-baked CLI case and returns the args-pinned id; otherwise it follows the existing override→defaultModel→models[0] chain. Replaced the inline logic at all five sites (`mediaPromptRefiner` was already on this pattern; the four above adopt it). `mediaPromptRefiner` and `worldBuilderRefine` no longer need to import `hasModelFlag` / `extractBakedModel` directly. Regression test in `promptRunner.test.js` pins that the run record + returned model reflect the baked id (not `provider.defaultModel`) when `extractBakedModel` resolves.+- **Creative Director evaluator prompt — backfill `imageStrength` block on existing installs.** `data.sample/prompts/stages/cd-evaluate.md` gained a `{{#scene.hasImageStrength}}` / `{{^scene.hasImageStrength}}` block in the scene-context section (so the evaluator can see the current i2v strength) and a sentence in the retry-branch instructions documenting the `imageStrength` knob it can adjust on rewrite. New installs picked it up automatically (fresh `data/` clones from `data.sample/`), but existing installs were stuck with the old template because `setup-data.js` only seeds files that don't yet exist — three regression tests in `creativeDirectorPrompts.test.js` flagged the drift on every test run. New one-shot migration `data/migrations/002-cd-evaluate-image-strength.js` surgically patches both pieces in when the surrounding anchor text matches the pre-update template (so a hand-edited prompt is left alone with a `⚠️` notice). Idempotent — re-runs are a no-op.- **Media chips/search now show LoRAs for snake_case-only sidecars.** `normalizeImage` / `normalizeVideo` were building `loraNames` from only the camelCase `loraFilenames` / `loraPaths` shapes, so a sidecar written by the Python pipeline (`lora_filenames` / `lora_paths`) showed no LoRA chips on the card and didn't surface in LoRA-name search — even though the requeue path through `getRenderConfigForItem` resolved them correctly via `pickLoraFilenames`. Both normalizers now reuse `pickLoraFilenames` so chips, search, and requeue agree across all four field shapes (`loraFilenames` / `lora_filenames` / `loraPaths` / `lora_paths`). Three new tests in `normalize.test.js` pin the snake_case coverage for both image and video. Picked up from PR #223 Copilot review.diff --git a/PLAN.md b/PLAN.mdindex 85205d7b16..588e3dbbb0 100644--- a/PLAN.md+++ b/PLAN.md@@ -52,6 +52,7 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud- [ ] **Extract `CollectionPickerShell` from `AddToCollectionMenu` + `BulkTargetPicker`** — both files (`client/src/components/media/AddToCollectionMenu.jsx`, `client/src/components/media/BulkTargetPicker.jsx`) own a near-identical portal popover: same `MENU_WIDTH/GAP/VIEWPORT_PADDING/SEARCH_THRESHOLD` constants, line-for-line identical reposition math, identical click-away + Esc + rAF-scroll effects, identical "new collection" footer form. The only differences are local to the list row (membership-toggle w/ check vs single-pick) and the create-success path (add-after-create vs pick-after-create). Extract `<CollectionPickerShell anchorRef, title, busy, onClose, renderRow, onCreate>` that owns positioning/portal/search/create-form; each picker becomes a ~40-line `renderRow` function. Two files isn't a fire; a third would force this. While extracting, also accept a `collections` prop (optional, falls back to internal fetch) so `MediaCollectionDetail` can pass its already-fetched list and avoid the per-mount `listMediaCollections` round-trip when the user toggles Move/Copy. Surfaced from the bulk-actions /simplify pass.- [ ] **Server-side bulk endpoint for collection items** — `MediaCollectionDetail`'s bulk Move/Copy/Remove currently makes N sequential HTTP calls (server has no per-collection lock, so parallel writes would lose updates on the JSON read-modify-write). At ~30ms localhost RTT, 20 items ≈ 600ms; 50 items ≈ 1.5s (move = 2 × that). The user's stated use case is "select all" on a world-builder collection that could legitimately have 50+ items. Add `POST /api/media/collections/:id/items/bulk` taking `{ add: [{kind,ref}], remove: [key] }` and doing one read-modify-write per collection. Halves wall-clock for Move (single source-side commit instead of N), dodges the race window entirely. Surfaced from the bulk-actions /simplify pass.- [ ] **Drop legacy `description` fallback in `sanitizeCharacter`** — `server/lib/storyBible.js:130` carries an inline `TODO(item-4): drop the description fallback once pipeline characters extract natively.` Item 4 (shared bible-extraction service) shipped 2026-05-10 — extraction now writes the canonical `physicalDescription` field directly. Plan: write a one-shot migration that rewrites every `series.characters[].description` → `physicalDescription` in `data/pipeline-series.json` (idempotent: skip entries that already have `physicalDescription`), drop the `|| raw.description` fallback at `storyBible.js:137`, and remove the TODO comment. Audit `data.sample/` + tests for any remaining `description` reads before merging.+- [ ] **Migrate `worldBuilderRefine.runRefine` onto `runPromptThroughProvider`** — `server/services/worldBuilderRefine.js:131-162` still hand-rolls the createRun → branch-on-type → executeApiRun/executeCliRun → accumulate-text → reject-on-error pattern that the parent unification (PR #221) collapsed for the other four LLM-runner sites. The effective-model resolution was unified in this PR, but the full runner-wrapper migration was deferred to keep scope tight. Replace the inline `runRefine` with a single `runPromptThroughProvider({ provider, model, prompt, source: 'world-builder-refine' })` call (mirroring `worldBuilderExpand.js`). Drop the local `createRun`/`executeApiRun`/`executeCliRun` imports. ~30 LOC dedup. Surfaced from /do:review on the resolveEffectiveModel PR.### Civitai LoRA / Z-Image-Turbo follow-ups (from /simplify pass)diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.jsindex 116867567d..7a2550678b 100644--- a/server/lib/promptRunner.js+++ b/server/lib/promptRunner.js@@ -26,7 +26,7 @@* stay honest about what the runner actually executed.*/-import { createRun, executeApiRun, executeCliRun, hasModelFlag } from '../services/runner.js';+import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag } from '../services/runner.js';const DEFAULT_TIMEOUT_MS = 300000;const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));@@ -47,6 +47,35 @@ export const providerHonorsModelOverride = (provider) => (|| (provider?.type === 'cli' && !hasModelFlag(provider?.args)));+/**+ * Resolve the model id that will ACTUALLY execute against the provider,+ * for accurate logging + run-record persistence.+ *+ * Decision table:+ * - Provider honors per-call override (API or CLI w/o baked args flag)+ * → callerModel || provider.defaultModel || provider.models[0]+ * - CLI with a baked --model/-m in provider.args (runner.js will+ * suppress its own injection and let the args-pinned model win)+ * → extractBakedModel(args) || provider.defaultModel || models[0]+ *+ * Returns null when no fallback resolves (so logs read "(default)" instead+ * of an inaccurate value).+ *+ * @param {object} provider+ * @param {string} [callerModel] — the per-call model the caller asked for+ * @returns {string|null}+ */+export function resolveEffectiveModel(provider, callerModel) {+ if (providerHonorsModelOverride(provider)) {+ return callerModel || provider?.defaultModel || provider?.models?.[0] || null;+ }+ // Non-honoring CLI path: args-baked model id wins over defaultModel.+ const baked = provider?.type === 'cli' && hasModelFlag(provider?.args)+ ? extractBakedModel(provider.args)+ : null;+ return baked || provider?.defaultModel || provider?.models?.[0] || null;+}+/*** Run a prompt through a provider and resolve with the streamed text +* run id. Rejects (via the strictest discriminator) on any runner-@@ -93,11 +122,10 @@ export async function runPromptThroughProvider({ provider, prompt, source, model}// Resolve the model that'll actually run BEFORE creating the run record- // so the record reflects reality. For providers that don't honor the- // override, fall back to provider.defaultModel / models[0].- const effectiveModel = providerHonorsModelOverride(provider)- ? (model || provider.defaultModel || provider.models?.[0] || null)- : (provider.defaultModel || provider.models?.[0] || null);+ // so the record reflects reality. resolveEffectiveModel handles both+ // the override-honored fallback chain AND the args-baked-CLI case+ // (extract the args-pinned model id rather than logging defaultModel).+ const effectiveModel = resolveEffectiveModel(provider, model);// Some call sites (stageRunner) create the run themselves so they can// log the runId before the LLM call starts. When provided, reuse it.diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.jsindex 7141ca9d5f..7330b2ad5e 100644--- a/server/lib/promptRunner.test.js+++ b/server/lib/promptRunner.test.js@@ -5,6 +5,7 @@ vi.mock('../services/runner.js', () => ({executeApiRun: vi.fn(),executeCliRun: vi.fn(),hasModelFlag: vi.fn(() => false),+ extractBakedModel: vi.fn(() => null),}));const runner = await import('../services/runner.js');@@ -155,6 +156,42 @@ describe('promptRunner — happy paths', () => {expect(out.text).toBe('ran with defaultModel=fallback');});++ it('returns the args-baked model id (not defaultModel) when extractBakedModel succeeds', async () => {+ // Regression: previously the non-honoring CLI branch fell through to+ // provider.defaultModel, so a baked args model id would never reach+ // the run record / return value. Now resolveEffectiveModel extracts+ // the args-pinned id directly.+ runner.hasModelFlag.mockReturnValue(true);+ runner.extractBakedModel.mockReturnValue('baked-in');+ runner.executeCliRun.mockImplementation(async (id, providerArg, _p, _cwd, onData, onComplete, _t) => {+ onData(`ran with defaultModel=${providerArg.defaultModel}`);+ onComplete({ success: true });+ });++ const out = await runPromptThroughProvider({+ provider: { id: 'claude-code', type: 'cli', defaultModel: 'fallback', timeout: 5000, args: ['--model', 'baked-in'] },+ prompt: 'p',+ source: 't',+ model: 'user-picked-this',+ });++ // effectiveModel = baked-in (not defaultModel='fallback'). Clone+ // fires because baked-in !== defaultModel; the CLI receives the+ // cloned provider whose defaultModel === baked-in.+ expect(out.model).toBe('baked-in');+ expect(out.text).toBe('ran with defaultModel=baked-in');+ // Run-record side of the bugfix: createRun must persist the+ // args-baked model id so the recorded run reflects what actually+ // executed (not the caller's silently-dropped override or the+ // provider.defaultModel fallback).+ expect(runner.createRun).toHaveBeenCalledWith({+ providerId: 'claude-code',+ model: 'baked-in',+ prompt: 'p',+ source: 't',+ });+ });});describe('promptRunner — strictest-discriminator rejection', () => {diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.jsindex 9c5c3954cb..75b4b820b7 100644--- a/server/lib/stageRunner.js+++ b/server/lib/stageRunner.js@@ -16,7 +16,7 @@import { ServerError } from './errorHandler.js';import { findBalancedBlocks, tryParseWithRepair } from './jsonExtract.js';-import { providerHonorsModelOverride, runPromptThroughProvider } from './promptRunner.js';+import { resolveEffectiveModel, runPromptThroughProvider } from './promptRunner.js';import { stripCodeFences } from './aiProvider.js';import { getActiveProvider, getProviderById } from '../services/providers.js';import { buildPrompt, getStage } from '../services/promptService.js';@@ -183,17 +183,12 @@ export async function runStagedLLM(stageName, variables, options = {}) {const provider = await resolveProviderForStage(stage, options);const prompt = await buildPrompt(stageName, variables);const resolvedModel = resolveModel(provider, options.modelOverride || stage?.model);- // Non-codex CLI providers ignore per-call model overrides at the- // runner.js#buildCliArgs layer, so recording the resolved model in- // createRun would lie about what actually ran. Drop the override at- // the record + log boundary for those providers — promptRunner does- // the same internally. PLAN.md tracks extending buildCliArgs to honor- // per-call model for all CLI providers; once that lands the gate goes- // away (and the gemini-cli fast-model fallback can be reintroduced- // here, since today it would be silently dropped anyway).- const effectiveModel = providerHonorsModelOverride(provider)- ? resolvedModel- : (provider.defaultModel || provider.models?.[0] || null);+ // resolveEffectiveModel gates the override per provider type and, for+ // CLI providers with a baked --model/-m flag in args, extracts the+ // args-pinned model id so the run record + log line reflect what+ // truly executes (rather than guessing from defaultModel, which can+ // diverge from the args-baked value).+ const effectiveModel = resolveEffectiveModel(provider, resolvedModel);const { runId } = await createRun({providerId: provider.id,diff --git a/server/services/mediaPromptRefiner.js b/server/services/mediaPromptRefiner.jsindex b132d400d1..567674fd64 100644--- a/server/services/mediaPromptRefiner.js+++ b/server/services/mediaPromptRefiner.js@@ -1,8 +1,7 @@import { ServerError } from '../lib/errorHandler.js';import { findBalancedBlocks, tryParseWithRepair } from '../lib/jsonExtract.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { resolveEffectiveModel, runPromptThroughProvider } from '../lib/promptRunner.js';import { getProviderById } from './providers.js';-import { hasModelFlag, extractBakedModel } from './runner.js';const MAX_PROMPT_LEN = 8000;const MAX_REASON_LEN = 1200;@@ -144,20 +143,12 @@ export async function refineMediaPrompt({);}- // 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] || '')- : (bakedModel || provider.defaultModel || provider.models?.[0] || '');+ // Resolve the model that'll actually run via the shared helper so the+ // early MODEL_REQUIRED guard + the response's `model` field match what+ // promptRunner resolves internally. resolveEffectiveModel handles both+ // the API/CLI override gate and the args-baked-CLI case (extracts the+ // args-pinned model id instead of guessing from defaultModel).+ const selectedModel = resolveEffectiveModel(provider, model) || '';if (!selectedModel && provider.type === 'api') {throw new ServerError('Model is required for prompt refinement', { status: 400, code: 'MODEL_REQUIRED' });}diff --git a/server/services/worldBuilderExpand.js b/server/services/worldBuilderExpand.jsindex f394792ead..2ab950097e 100644--- a/server/services/worldBuilderExpand.js+++ b/server/services/worldBuilderExpand.js@@ -25,7 +25,7 @@ import {} from './worldBuilder.js';import { ServerError } from '../lib/errorHandler.js';import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';-import { providerHonorsModelOverride, runPromptThroughProvider } from '../lib/promptRunner.js';+import { resolveEffectiveModel, runPromptThroughProvider } from '../lib/promptRunner.js';const LABEL_MAX = 80;@@ -170,12 +170,12 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;if (!provider) provider = await getActiveProvider();if (!provider) throw new Error('No AI provider available for world expansion');- // Mirror the gate that promptRunner applies internally so the log line- // and the returned `llm.model` field reflect what'll actually execute.- // Non-codex CLI providers ignore the per-call model.- const selectedModel = providerHonorsModelOverride(provider)- ? (model || provider.defaultModel || provider.models?.[0])- : (provider.defaultModel || provider.models?.[0]);+ // resolveEffectiveModel mirrors what promptRunner resolves internally+ // so the log line below + the returned `llm.model` field reflect what+ // actually executed. For CLI providers with a baked --model/-m flag+ // in args it returns the args-pinned id (not provider.defaultModel,+ // which can diverge).+ const selectedModel = resolveEffectiveModel(provider, model);const fullPrompt = EXPANSION_PROMPT.replace('{starterPrompt}', starterPrompt.trim());console.log(`🌍 World Builder expanding via ${provider.name}/${selectedModel || 'default'}`);diff --git a/server/services/worldBuilderRefine.js b/server/services/worldBuilderRefine.jsindex 833bf1a31a..89598cf8a8 100644--- a/server/services/worldBuilderRefine.js+++ b/server/services/worldBuilderRefine.js@@ -13,7 +13,8 @@import { ServerError } from '../lib/errorHandler.js';import { getActiveProvider, getProviderById } from './providers.js';-import { createRun, executeApiRun, executeCliRun, hasModelFlag, extractBakedModel } from './runner.js';+import { createRun, executeApiRun, executeCliRun } from './runner.js';+import { resolveEffectiveModel } from '../lib/promptRunner.js';import {PROMPT_FRAGMENT_MAX,STARTER_PROMPT_MAX,@@ -199,17 +200,11 @@ export async function refineWorldPrompts({);}- // 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] || '')- : (bakedModel || provider.defaultModel || provider.models?.[0] || '');+ // Resolve the model id that will ACTUALLY execute so the response /+ // run record / log line match the args-pinned id when a CLI provider's+ // args have a baked --model/-m flag. Shared helper documents the+ // decision table.+ const selectedModel = resolveEffectiveModel(provider, model) || '';if (!selectedModel && provider.type === 'api') {throw new ServerError('Model is required for world refinement', { status: 400, code: 'MODEL_REQUIRED' });}