Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: address release review findings
[._.]/ Adam Eivy62f84483e645
diff --git a/client/src/components/cos/AgentJobProviderFields.jsx b/client/src/components/cos/AgentJobProviderFields.jsxindex dd31100c3c..368887c298 100644--- a/client/src/components/cos/AgentJobProviderFields.jsx+++ b/client/src/components/cos/AgentJobProviderFields.jsx@@ -1,6 +1,22 @@-import { effortAwareModelOptions, filterRunnableProviders, resolveEffectiveProvider } from '../../utils/providers.js';+import {+ AGENT_HARNESS_PROVIDER_TYPES,+ effortAwareModelOptions,+ filterRunnableProviders,+ resolveEffectiveProvider,+} from '../../utils/providers.js';import ProviderModelSelector from '../ProviderModelSelector.jsx';+/**+ * Whether an agent job's saved provider choice resolves to a file-writing+ * CLI/TUI harness at save time. HTTP API providers can generate text, but they+ * cannot perform the filesystem work an agent job promises to do.+ */+export const hasRunnableAgentProvider = (providers, providerId, activeProviderId) => {+ const selectableProviders = filterRunnableProviders(providers, providerId);+ const { provider } = resolveEffectiveProvider(selectableProviders, providerId, activeProviderId);+ return AGENT_HARNESS_PROVIDER_TYPES.includes(provider?.type);+};+/*** Shared provider/model/effort controls for persisted CoS agent jobs.*@@ -30,6 +46,9 @@ export default function AgentJobProviderFields({const effectiveProviderId = usingActive ? (activeProviderId || undefined) : undefined;const patchWithActiveProvider = (patch) =>data.providerId || !activeProviderId ? patch : { providerId: activeProviderId, ...patch };+ const canInheritActiveProvider = AGENT_HARNESS_PROVIDER_TYPES.includes(+ selectableProviders.find(provider => provider.id === activeProviderId)?.type+ );return (<div>@@ -45,11 +64,16 @@ export default function AgentJobProviderFields({effort={data.effort || ''}onEffortChange={effort => onChange(patchWithActiveProvider({ effort }))}compact- emptyProviderOption="Default (active provider)"+ emptyProviderOption={canInheritActiveProvider ? 'Default (active provider)' : 'Select a CLI/TUI provider'}emptyModelOption="Default model"alwaysShowModelhighlightToolUse/>+ {!data.providerId && !canInheritActiveProvider && (+ <p role="alert" className="mt-1 text-xs text-port-warning">+ Select a CLI/TUI provider before saving this agent job.+ </p>+ )}</div>);}diff --git a/client/src/components/cos/AgentJobProviderFields.test.jsx b/client/src/components/cos/AgentJobProviderFields.test.jsxindex 24bf1d0ad1..50ca561151 100644--- a/client/src/components/cos/AgentJobProviderFields.test.jsx+++ b/client/src/components/cos/AgentJobProviderFields.test.jsx@@ -122,4 +122,28 @@ describe('AgentJobProviderFields', () => {expect(screen.queryByRole('option', { name: 'claude-sonnet' })).not.toBeInTheDocument();});++ it('requires an explicit coding provider when the active provider is an API', async () => {+ const apiProvider = {+ id: 'ollama',+ name: 'Ollama API',+ type: 'api',+ enabled: true,+ defaultModel: 'qwen3.6:35b',+ models: ['qwen3.6:35b']+ };++ render(+ <AgentJobProviderFields+ data={{ providerId: '', model: '', effort: '' }}+ providers={[apiProvider, ...PROVIDERS]}+ activeProviderId="ollama"+ onChange={vi.fn()}+ />+ );+ await act(async () => {});++ expect(screen.getByRole('option', { name: 'Select a CLI/TUI provider' })).toBeInTheDocument();+ expect(screen.getByRole('alert')).toHaveTextContent('Select a CLI/TUI provider before saving');+ });});diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsxindex 6f5e14621a..9c001a26d7 100644--- a/client/src/components/cos/tabs/JobsTab.jsx+++ b/client/src/components/cos/tabs/JobsTab.jsx@@ -5,7 +5,7 @@ import * as api from '../../../services/api';import { timeAgo, timeUntil, formatDateTime, formatDateNumeric } from '../../../utils/formatters';import { DEFAULT_CRON, describeCron, describeRecurrence, parseCronToRecurrence, buildCronFromRecurrence, JOB_INTERVAL_OPTIONS as INTERVAL_OPTIONS } from '../../../utils/cronHelpers';import CronSchedulePicker from '../../CronSchedulePicker';-import AgentJobProviderFields from '../AgentJobProviderFields';+import AgentJobProviderFields, { hasRunnableAgentProvider } from '../AgentJobProviderFields';import { filterRunnableProviders } from '../../../utils/providers';import InlineConfirmRow from '../../ui/InlineConfirmRow';import FormField from '../../ui/FormField';@@ -269,6 +269,12 @@ function JobCard({ job, apps, providers, activeProviderId, timezone, onToggle, o};const handleSave = async () => {+ const providerResolutionKnown = Boolean(editData.providerId || activeProviderId || providers.length);+ if (isAgentJobType(editData.type) && providerResolutionKnown+ && !hasRunnableAgentProvider(providers, editData.providerId, activeProviderId)) {+ toast.error('Select a CLI/TUI provider before saving an agent job');+ return;+ }const payload = normalizeJobPayload(editData);const result = await api.updateCosJob(job.id, payload, { silent: true }).catch(err => {toast.error(err.message);@@ -644,6 +650,12 @@ export default function JobsTab() {toast.error('Prompt template is required for AI jobs');return;}+ const providerResolutionKnown = Boolean(newJob.providerId || activeProviderId || providers.length);+ if (isAgentJobType(newJob.type) && providerResolutionKnown+ && !hasRunnableAgentProvider(providers, newJob.providerId, activeProviderId)) {+ toast.error('Select a CLI/TUI provider before saving an agent job');+ return;+ }if (newJob.scheduleMode === 'cron' && !newJob.cronSchedule && (!newJob.cronExpression?.trim() || newJob.cronExpression.trim().split(/\s+/).length !== 5)) {toast.error('A valid recurrence or 5-field cron expression is required for cron scheduling');return;diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex c64df1c4f1..815b7ed595 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -153,6 +153,9 @@ app.post('/spawn-tui', async (req, res) => {args = [],workspacePath,envVars = {},+ // Non-secret provider identity used to retain that provider's ambient auth+ // allowlist when the runner builds the child environment.+ providerAuth = null,cols = 80,rows = 24,doneSentinelPath = null,@@ -180,7 +183,7 @@ app.post('/spawn-tui', async (req, res) => {}const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;- const childEnv = buildCliChildEnv({ before: envVars, cwd });+ const childEnv = buildCliChildEnv({ before: envVars, provider: providerAuth, cwd });// node-pty reports a missing executable as an immediate exit with no data.// Check the exact child PATH first so the caller gets a usable configuration// error instead of a generic startup-failure after a blank PTY transcript.@@ -344,6 +347,9 @@ app.post('/spawn', async (req, res) => {workspacePath,model,envVars = {},+ // Non-secret provider identity used to retain that provider's ambient auth+ // allowlist when the runner builds the child environment.+ providerAuth = null,// New: CLI-agnostic parameterscliCommand,cliArgs,@@ -403,7 +409,7 @@ app.post('/spawn', async (req, res) => {// The pin is the path #3193 was reported through: the log line above named the// app's workspace correctly while every OpenCode agent still ran in the PortOS// folder. No `guard` — this separate process has never carried the pm2 shim.- const childEnv = buildCliChildEnv({ before: envVars, cwd });+ const childEnv = buildCliChildEnv({ before: envVars, provider: providerAuth, cwd });// Resolve a bare npm-installed CLI (opencode/codex/claude/… — a .cmd/.bat// shim on Windows) to its real path and wrap a shim as `cmd.exe /c <path>` sodiff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex c6732b7627..34e2ba2962 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -100,7 +100,7 @@ describe('cos-runner durable TUI ownership (#3202)', () => {expect(RUNNER_SRC).toMatch(/import\s*\{[^}]*\bcommandExists\b[^}]*\}\s*from\s*'\.\.\/lib\/commandExists\.js';/);- const childEnvIdx = RUNNER_SRC.indexOf('const childEnv = buildCliChildEnv({ before: envVars, cwd });');+ const childEnvIdx = RUNNER_SRC.indexOf('const childEnv = buildCliChildEnv({ before: envVars, provider: providerAuth, cwd });');const resolveIdx = RUNNER_SRC.indexOf('const executable = findCommandOnPath(command, { env: childEnv, cwd });');const prepareProbeIdx = RUNNER_SRC.indexOf("const versionProbe = prepareCliSpawn(executable, ['--version'], childEnv);");const probeIdx = RUNNER_SRC.indexOf('const runnable = await commandExists(versionProbe.command, versionProbe.args, {');diff --git a/server/lib/cliChildEnv.test.js b/server/lib/cliChildEnv.test.jsindex 47a46006f5..2901526a73 100644--- a/server/lib/cliChildEnv.test.js+++ b/server/lib/cliChildEnv.test.js@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';import { posixPath } from './testHelper.js';import { buildCliChildEnv, composeProviderEnv } from './cliChildEnv.js';+import { cliProviderAuthDescriptor } from './processEnv.js';import { AGENT_GUARD_BIN } from './agentGuard/index.js';import { collectServerSources, readServerSource } from './testHelper.js';import { readFileSync } from 'node:fs';@@ -343,6 +344,17 @@ describe('buildCliChildEnv — per-call-site composition', () => {});});+ it('retains ambient auth for the selected provider when the runner supplies its descriptor', () => {+ const provider = { id: 'codex', command: 'codex', envVars: { OPENAI_API_KEY: 'not serialized' } };+ const env = buildCliChildEnv({+ baseEnv: { PATH: '/usr/bin', OPENAI_API_KEY: 'ambient-key' },+ provider: cliProviderAuthDescriptor(provider),+ cwd: '/workspace',+ });++ expect(env.OPENAI_API_KEY).toBe('ambient-key');+ });+it('askService.js: no cwd means no PWD is invented', () => {const env = buildCliChildEnv({ baseEnv: { PATH: '/usr/bin' }, provider: { envVars: {} }, model: 'opus' });expect(env.PWD).toBeUndefined();diff --git a/server/lib/processEnv.js b/server/lib/processEnv.jsindex aee90df3a3..47050b87f1 100644--- a/server/lib/processEnv.js+++ b/server/lib/processEnv.js@@ -67,6 +67,23 @@ const CLI_PROVIDER_AUTH_RULES = Object.freeze({const LOCAL_PROVIDER_MARKERS = ['ollamaBacked', 'mtplxBacked', 'llamaBacked', 'vllmBacked', 'sglangBacked'];+/**+ * Build the non-secret provider metadata needed to classify ambient CLI auth+ * in another process. Provider envVars are deliberately excluded: those may+ * contain credentials and are already carried separately when explicitly+ * configured.+ */+export function cliProviderAuthDescriptor(provider) {+ if (!provider || typeof provider !== 'object') return null;+ const descriptor = {};+ if (typeof provider.id === 'string' && provider.id) descriptor.id = provider.id;+ if (typeof provider.command === 'string' && provider.command) descriptor.command = provider.command;+ for (const marker of LOCAL_PROVIDER_MARKERS) {+ if (provider[marker] === true) descriptor[marker] = true;+ }+ return Object.keys(descriptor).length ? descriptor : null;+}+function cliProviderAuthRule(provider) {const command = typeof provider?.command === 'string'? provider.command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '')diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 370b809871..ad9304ae81 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -524,7 +524,11 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {const { pythonPath: py, selectedModel } = resolveLocalImageModel(settings, params);const queued = enqueueJob({kind: 'image',- params: { pythonPath: py, ...params },+ params: {+ ...params,+ pythonPath: py,+ ...(selectedModel?.id ? { modelId: selectedModel.id } : {}),+ },});// selectedModel reflects the actual fallback chain resolveLocalImageModel// applied (caller modelId → 'dev' → allModels[0]) rather than just thediff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex a358c20b26..c56066b6b4 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -311,7 +311,7 @@ describe('Image Gen Routes', () => {expect(response.body.path).toBe('/data/images/queued-job-001.png');expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({kind: 'image',- params: expect.objectContaining({ prompt: 'a fox in a forest', pythonPath: '/usr/bin/python3' }),+ params: expect.objectContaining({ prompt: 'a fox in a forest', pythonPath: '/usr/bin/python3', modelId: 'dev' }),}));// Synchronous generateImage MUST NOT be called in local mode — the// queue takes ownership of the job lifecycle.diff --git a/server/routes/meatspacePostRoutes.drill.test.js b/server/routes/meatspacePostRoutes.drill.test.jsindex 6645266eff..7690da8ec5 100644--- a/server/routes/meatspacePostRoutes.drill.test.js+++ b/server/routes/meatspacePostRoutes.drill.test.js@@ -25,6 +25,10 @@ vi.mock('../services/meatspacePostMemory.js', () => ({generateMemoryDrill: vi.fn(),}));+vi.mock('../services/meatspacePostRhetoric.js', () => ({+ evaluateRhetoricAttempt: vi.fn(),+}));+vi.mock('../services/meatspacePost.js', () => ({resolveDrillConfig: vi.fn(),generateDrill: vi.fn(),@@ -37,6 +41,7 @@ vi.mock('../services/meatspacePost.js', () => ({import { getCachedDrill, triggerReplenish } from '../services/meatspacePostDrillCache.js';import { generateLlmDrill } from '../services/meatspacePostLlm.js';import { generateMemoryDrill } from '../services/meatspacePostMemory.js';+import { evaluateRhetoricAttempt } from '../services/meatspacePostRhetoric.js';import { resolveDrillConfig, generateDrill, getPostReviewReps, getPostConfig } from '../services/meatspacePost.js';import { errorMiddleware } from '../lib/errorHandler.js';import meatspacePostRoutes from './meatspacePostRoutes.js';@@ -264,3 +269,40 @@ describe('GET /api/meatspace/post/review/reps', () => {expect(getPostReviewReps).toHaveBeenCalledWith(expect.any(Date), 5);});});++describe('POST /api/meatspace/post/rhetoric/evaluate', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ });++ const payload = {+ attemptId: 'attempt-1',+ mode: 'meter',+ prompt: 'State the claim clearly.',+ response: 'The claim is clear.',+ };++ it('rejects evaluation while the saved evaluator consent is disabled', async () => {+ getPostConfig.mockResolvedValue({ rhetoricEvaluator: { enabled: false } });++ const r = await request(app).post('/api/meatspace/post/rhetoric/evaluate').send(payload);++ expect(r.status).toBe(409);+ expect(r.body.code).toBe('POST_RHETORIC_EVALUATOR_DISABLED');+ expect(evaluateRhetoricAttempt).not.toHaveBeenCalled();+ });++ it('evaluates only after the saved evaluator consent is enabled', async () => {+ const result = { score: 0.9, feedback: 'Strong.' };+ getPostConfig.mockResolvedValue({ rhetoricEvaluator: { enabled: true } });+ evaluateRhetoricAttempt.mockResolvedValue(result);++ const r = await request(app).post('/api/meatspace/post/rhetoric/evaluate').send(payload);++ expect(r.status).toBe(200);+ expect(r.body).toEqual(result);+ expect(evaluateRhetoricAttempt).toHaveBeenCalledWith(payload);+ });+});diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex df129cc064..76fe9a265a 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -286,6 +286,13 @@ router.post('/post/score-llm', asyncHandler(async (req, res) => {*/router.post('/post/rhetoric/evaluate', asyncHandler(async (req, res) => {const data = validateRequest(postRhetoricEvaluationRequestSchema, req.body);+ const config = await postService.getPostConfig();+ if (config?.rhetoricEvaluator?.enabled !== true) {+ throw new ServerError(+ 'Rhetoric evaluator is disabled — enable it in the POST configuration before evaluating an attempt',+ { status: 409, code: 'POST_RHETORIC_EVALUATOR_DISABLED' },+ );+ }const result = await evaluateRhetoricAttempt(data);res.json(result);}));diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 492682469b..5364c728eb 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -58,6 +58,7 @@ import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken }import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';import { prClaimWasVerified } from '../lib/prDisposition.js';import { composeProviderEnv } from '../lib/cliChildEnv.js';+import { cliProviderAuthDescriptor } from '../lib/processEnv.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';@@ -881,6 +882,7 @@ export async function spawnViaRunner(agentId, task, opts) {prompt,workspacePath,model,+ providerAuth: cliProviderAuthDescriptor(provider),// A DELTA, not a full env — the cos-runner bases it on its own process.env// and does the PWD pin / CLAUDECODE strip. composeProviderEnv owns the layer// order: forgeTokenEnv before provider.envVars so an explicit providerdiff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 2f77d12150..079b328a31 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -68,6 +68,7 @@ import {import { injectTuiModelAndEffort } from '../lib/providerVendors.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { composeProviderEnv } from '../lib/cliChildEnv.js';+import { cliProviderAuthDescriptor } from '../lib/processEnv.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';import { shellHasLiveChild } from '../lib/shellLivenessProbe.js';@@ -126,6 +127,7 @@ export async function createAgentTuiSession({args: tuiConfig.args,workspacePath: cwd,envVars: env,+ providerAuth: cliProviderAuthDescriptor(provider),doneSentinelPath,onData,onExit,diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 0f2278c82c..6af742b869 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -411,6 +411,7 @@ export async function spawnAgentViaRunner(options) {workspacePath,model,envVars,+ providerAuth,// New: CLI-agnostic parameterscliCommand,cliArgs,@@ -425,6 +426,7 @@ export async function spawnAgentViaRunner(options) {workspacePath,model,envVars,+ providerAuth,cliCommand,cliArgs,claudePathdiff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.jsindex 564c2f66d4..61e3bd4a48 100644--- a/server/services/cosRunnerClient.test.js+++ b/server/services/cosRunnerClient.test.js@@ -257,6 +257,17 @@ describe('cosRunnerClient', () => {expect(callBody.cliArgs).toEqual(['--model', 'opus']);});+ it('should pass the non-secret provider auth descriptor to the runner', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { agentId: 'a1' }));+ await spawnAgentViaRunner({+ agentId: 'a1',+ providerAuth: { id: 'codex', command: 'codex' },+ });++ const callBody = JSON.parse(fetchWithTimeout.mock.calls[0][1].body);+ expect(callBody.providerAuth).toEqual({ id: 'codex', command: 'codex' });+ });+it('surfaces a non-JSON error body instead of crashing on "Unexpected token <"', async () => {// Simulates the runner returning an HTML 500 page (e.g. PM2 restarting it// mid-request) rather than JSON. Parsing it as JSON used to throw.diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsindex 67136712b6..6032db7302 100644--- a/server/services/eventScheduler.js+++ b/server/services/eventScheduler.js@@ -330,6 +330,15 @@ function parseRecurrenceToNextRun(rule, from = new Date(), timezone = 'UTC', unt}const boundary = new Date(from)boundary.setFullYear(boundary.getFullYear() + 2)+ // The two-year search horizon is relative to `from`, but a persisted anchor+ // may intentionally begin farther in the future. Extend the horizon through+ // that anchor so a valid recurrence is not rejected merely because its first+ // occurrence lies beyond the runtime look-ahead window.+ if (parsedAnchor) {+ const anchorBoundary = new Date(Date.UTC(parsedAnchor.year, parsedAnchor.month - 1, parsedAnchor.day))+ anchorBoundary.setUTCFullYear(anchorBoundary.getUTCFullYear() + 2)+ if (anchorBoundary > boundary) boundary.setTime(anchorBoundary.getTime())+ }const maxDate = until instanceof Date && until < boundary ? until : boundaryreturn findNextRecurrenceCandidate(normalized, anchor, from, timezone, maxDate)}diff --git a/server/services/eventScheduler.test.js b/server/services/eventScheduler.test.jsindex 37765db2ba..9566ed082b 100644--- a/server/services/eventScheduler.test.js+++ b/server/services/eventScheduler.test.js@@ -181,6 +181,13 @@ describe('parseRecurrenceToNextRun', () => {expect(next.toISOString()).toBe('2025-01-01T00:00:00.000Z');});+ it('accepts a valid future anchor beyond the runtime two-year horizon', () => {+ const next = parseRecurrenceToNextRun({+ frequency: 'monthly-date', interval: 12, dayOfMonth: 1, time: '00:00', anchorDate: '2027-01-01',+ }, new Date('2024-01-02T00:00:00.000Z'));+ expect(next.toISOString()).toBe('2027-01-01T00:00:00.000Z');+ });+it('validates both rich recurrence rules and custom cron rules', () => {expect(isValidRecurrence({ frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2024-01-01' })).toBe(true);expect(isValidRecurrence({ frequency: 'custom', cron: '*/15 * * * *' })).toBe(true);diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.jsindex 78ebdc295c..c9c5867884 100644--- a/server/services/imageGen/prepareParams.js+++ b/server/services/imageGen/prepareParams.js@@ -70,6 +70,23 @@ const RECORD_PIN_SOURCES = Object.freeze([// so the route never silently relabels (e.g. HEIC) bytes as ".png".const MIME_TO_EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '.webp' };+/**+ * Select the model a local render will actually use. An omitted model keeps+ * the historical `dev` preference only when that model can run on this host;+ * otherwise it falls through to the first compatible catalog entry.+ *+ * @param {string|null|undefined} modelId+ * @param {object[]} [allModels]+ * @returns {object|undefined}+ */+export function selectLocalImageModel(modelId, allModels = getImageModels()) {+ const requestedModel = allModels.find((model) => model.id === modelId);+ return requestedModel || [+ allModels.find((model) => model.id === 'dev'),+ ...allModels,+ ].filter(Boolean).find((model) => isHardwareCompatible(model.hardwareCompatibility)) || allModels[0];+}+/*** @param {object} opts* @param {object} opts.data - validated + coerced body from Zod (mutated in place)@@ -193,9 +210,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields// downstream — that would orphan files on disk and produce metadata sidecars// that lie about how the render was conditioned.if (referenceUploads.length && mode === IMAGE_GEN_MODE.LOCAL) {- const candidate = getImageModels().find((m) => m.id === data.modelId)- ?? getImageModels().find((m) => m.id === 'dev')- ?? getImageModels()[0];+ const candidate = selectLocalImageModel(data.modelId);if (!isFlux2(candidate)) {cleanupReqFilesTemp();throw new ServerError(@@ -330,15 +345,11 @@ export function resolveLocalImageModel(settings, params) {{ status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' },);}- const requestedModel = allModels.find((m) => m.id === params.modelId);// An explicit pin must fail clearly when the host cannot run it. For an// omitted pin, prefer the historical `dev` default only when it is actually// compatible, then choose the first known-compatible model. This keeps a// Windows/Linux install from silently queueing the Apple-only default.- const selectedModel = requestedModel || [- allModels.find((m) => m.id === 'dev'),- ...allModels,- ].filter(Boolean).find((model) => isHardwareCompatible(model.hardwareCompatibility)) || allModels[0];+ const selectedModel = selectLocalImageModel(params.modelId, allModels);if (selectedModel && !isHardwareCompatible(selectedModel.hardwareCompatibility)) {throw new ServerError(`Image model "${selectedModel.id}" is unavailable on this machine: ${selectedModel.hardwareCompatibility.reasons.join(' · ')}`,diff --git a/server/services/imageGen/prepareParams.test.js b/server/services/imageGen/prepareParams.test.jsindex 144b7150f8..131d7b21f5 100644--- a/server/services/imageGen/prepareParams.test.js+++ b/server/services/imageGen/prepareParams.test.js@@ -20,11 +20,29 @@ vi.mock('../musicVideo/projects.js', () => ({ getProject: (...a) => getProject(.const getUniverseRenderPin = vi.fn(async () => null);vi.mock('../universeBuilder/crud.js', () => ({ getUniverseRenderPin: (...a) => getUniverseRenderPin(...a) }));-const { prepareGenerateParams } = await import('./prepareParams.js');+const { prepareGenerateParams, selectLocalImageModel } = await import('./prepareParams.js');const CODEX_ON = { codex: { enabled: true, codexPath: '/bin/codex' } };const run = (data) => prepareGenerateParams({ data, files: undefined, referenceImageFields: [] });+describe('selectLocalImageModel', () => {+ it('keeps an explicit model pin', () => {+ const models = [+ { id: 'dev', hardwareCompatibility: { state: 'unavailable' } },+ { id: 'custom', hardwareCompatibility: { state: 'available' } },+ ];+ expect(selectLocalImageModel('custom', models).id).toBe('custom');+ });++ it('falls back from an unavailable dev default to a compatible model', () => {+ const models = [+ { id: 'dev', hardwareCompatibility: { state: 'unavailable' } },+ { id: 'custom', hardwareCompatibility: { state: 'available' } },+ ];+ expect(selectLocalImageModel(undefined, models).id).toBe('custom');+ });+});+beforeEach(() => {vi.clearAllMocks();getSettings.mockResolvedValue({});