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
let the default local render model be configured in Settings instead of settings.json
[._.]/ Adam Eivy9825381629d5
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex e2d9553de0..814343484e 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -21,10 +21,10 @@ import { isLoopbackHost } from '../../lib/loopbackHost.js';import { PORTS } from '../../lib/ports.js';import {getSettings, updateSettings, getImageGenStatus, generateImage,- registerTool, updateTool, getToolsList,+ registerTool, updateTool, getToolsList, listImageModels,saveHfToken, clearHfToken,} from '../../services/api';-import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';+import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, LOCAL_IMAGEGEN_DEFAULT_MODEL, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';import { resolveCleanersFromConfig } from '../../lib/imageCleaners';import { useMediaJobSse } from '../../hooks/useMediaJobSse';import { useAgyModels } from '../../hooks/useAgyModels';@@ -114,8 +114,26 @@ export function ImageGenTab() {// reactor.inc fast-h3 API key (#6214) — same usability-gate shape as fal above.const [reactorApiKey, setReactorApiKey] = useState('');const videoGenSliceRef = useRef({});+ // Same round-trip guard as videoGenSliceRef, for the same reason: the PUT+ // replaces `imageGen` wholesale, and `imageGen.local` carries hand-edit-only+ // keys this tab never renders — steps / guidance / quantize, read by+ // fableLoom/production.js. Rebuilding the slice from the rendered fields+ // alone silently wiped them on every Media save.+ const localSliceRef = useRef({});const [sdapiUrl, setSdapiUrl] = useState('');const [pythonPath, setPythonPath] = useState('');+ // Install-wide default local image model (`settings.imageGen.local.modelId`).+ // '' = no pin, which the server resolves to LOCAL_IMAGEGEN_DEFAULT_MODEL.+ // Every SERVER-side local-render caller reads this key (deckRender, sprite+ // references, the pipeline visual stages, character sheets, FableLoom, and+ // now selectLocalImageModel itself); until now it was only reachable by+ // hand-editing settings.json. Client-side defaults in lib/pipelineImageDefaults+ // and lib/wrImageDefaults still hardcode their own model and do not consult it.+ const [localModelId, setLocalModelId] = useState('');+ // Catalog for the picker, probed once the Local tab is mounted. `null` until+ // the fetch resolves (vs `[]` for "fetched and genuinely empty") so the+ // select can say "loading" rather than silently offering nothing.+ const [localModels, setLocalModels] = useState(null);const [exposeA1111, setExposeA1111] = useState(false);// Codex CLI provider config — gated by `codexEnabled` so users without// a paid Codex plan that includes image_gen can hide the option entirely.@@ -176,7 +194,7 @@ export function ImageGenTab() {// Snapshot of saved values so we can show the "dirty" stateconst [saved, setSaved] = useState({- mode: IMAGE_GEN_MODE.EXTERNAL, sdapiUrl: '', pythonPath: '', exposeA1111: false,+ mode: IMAGE_GEN_MODE.EXTERNAL, sdapiUrl: '', pythonPath: '', localModelId: '', exposeA1111: false,codexEnabled: false, codexPath: '', codexModel: '', codexEffort: '', codexParallelLimit: 1,grokEnabled: false, grokPath: '', grokAspectRatio: '',agyEnabled: false, agyPath: '', agyModel: '',@@ -264,6 +282,7 @@ export function ImageGenTab() {const m = ig.mode || IMAGE_GEN_MODE.EXTERNAL;const url = normalizeUrl(ig.external?.sdapiUrl || ig.sdapiUrl);const py = ig.local?.pythonPath || '';+ const localModel = ig.local?.modelId || '';const expose = ig.expose?.a1111 === true;const cx = ig.codex || {};const cxEnabled = cx.enabled === true;@@ -298,9 +317,11 @@ export function ImageGenTab() {setVideoGenDisplaySleep(vgDisplaySleep);setFalApiKey(vgFalApiKey);setReactorApiKey(vgReactorApiKey);+ localSliceRef.current = (ig.local && typeof ig.local === 'object') ? ig.local : {};videoGenSliceRef.current = vg;setSdapiUrl(url);setPythonPath(py);+ setLocalModelId(localModel);setExposeA1111(expose);setCodexEnabled(cxEnabled);setCodexPath(cxPath);@@ -317,7 +338,7 @@ export function ImageGenTab() {setCleanC2PAByMode(c2);setDenoiseByMode(dn);setSaved({- mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose,+ mode: m, sdapiUrl: url, pythonPath: py, localModelId: localModel, exposeA1111: expose,codexEnabled: cxEnabled, codexPath: cxPath, codexModel: cxModel, codexEffort: cxEffort,codexParallelLimit: cxParallel,grokEnabled: gkEnabled, grokPath: gkPath, grokAspectRatio: gkRatio,@@ -338,6 +359,31 @@ export function ImageGenTab() {.finally(() => setLoading(false));}, []);+ // Local model catalog — fetched once the Local tab has been opened, on the+ // same "don't probe a tab nobody looked at" rule as the Agy list below.+ // Hardware-incompatible entries are filtered out by `listImageModels`: a+ // default that this machine's runner refuses is a render error waiting to+ // happen, and `checkLocalConnection` already reports it as unavailable.+ useEffect(() => {+ if (!localMounted) return;+ let alive = true;+ listImageModels()+ .then((list) => { if (alive) setLocalModels(Array.isArray(list) ? list : []); })+ .catch(() => { if (alive) setLocalModels([]); });+ return () => { alive = false; };+ }, [localMounted]);++ // A pin the live catalog no longer lists (model rotated out, or this machine+ // stopped being compatible) still has to render as the selected option —+ // otherwise the select paints blank, reads as "install default", and a save+ // would silently drop a pin the server is still honouring.+ const pinIsOrphaned = localModelId && localModels !== null && !localModels.some((m) => m.id === localModelId);+ const localModelOptions = pinIsOrphaned+ ? [{ id: localModelId, name: `${localModelId} (unavailable on this machine)` }, ...localModels]+ : localModels ?? [];+ const localDefaultLabel = localModels?.find((m) => m.id === LOCAL_IMAGEGEN_DEFAULT_MODEL)?.name+ || LOCAL_IMAGEGEN_DEFAULT_MODEL;+// Probe only while the Agy tab is actually open — the list spawns `agy models`// server-side, so an unopened tab must not pay for a child process.const {@@ -395,6 +441,7 @@ export function ImageGenTab() {const isDirty = mode !== saved.mode|| normalizeUrl(sdapiUrl) !== saved.sdapiUrl|| pythonPath !== saved.pythonPath+ || localModelId !== saved.localModelId|| exposeA1111 !== saved.exposeA1111|| codexEnabled !== saved.codexEnabled|| codexPath !== saved.codexPath@@ -438,7 +485,17 @@ export function ImageGenTab() {imageGen: {mode,external: { sdapiUrl: url, cleanC2PA: cleanC2PAByMode.external, denoise: denoiseByMode.external },- local: { pythonPath: pythonPath || undefined, cleanC2PA: cleanC2PAByMode.local, denoise: denoiseByMode.local },+ local: {+ ...localSliceRef.current,+ pythonPath: pythonPath || undefined,+ // `undefined` drops the key so an un-pinned install keeps resolving+ // through LOCAL_IMAGEGEN_DEFAULT_MODEL rather than persisting a ''+ // that every `|| LOCAL_IMAGEGEN_DEFAULT_MODEL` read would have to+ // keep coercing.+ modelId: localModelId || undefined,+ cleanC2PA: cleanC2PAByMode.local,+ denoise: denoiseByMode.local,+ },codex: {enabled: codexEnabled, codexPath: cxPath, model: cxModel, effort: cxEffort, parallelLimit: cxParallel,cleanC2PA: cleanC2PAByMode.codex, denoise: denoiseByMode.codex,@@ -481,7 +538,7 @@ export function ImageGenTab() {// after a successful save (state has " codex " but `saved` was// updated with the trimmed "codex").setSaved({- mode, sdapiUrl: url || '', pythonPath, exposeA1111,+ mode, sdapiUrl: url || '', pythonPath, localModelId, exposeA1111,codexEnabled, codexPath: cxPath || '', codexModel: cxModel || '', codexEffort: cxEffort || '',codexParallelLimit: cxParallel,grokEnabled, grokPath: gkPath || '', grokAspectRatio: gkRatio || '',@@ -497,6 +554,7 @@ export function ImageGenTab() {// dirty check compares like against like after a save.setRenderDefaults(patch.renderDefaults);videoGenSliceRef.current = patch.videoGen;+ localSliceRef.current = patch.imageGen.local;if (cxParallel !== codexParallelLimit) {setCodexParallelLimit(cxParallel);setParallelLimitDraft(String(cxParallel));@@ -931,6 +989,40 @@ export function ImageGenTab() {and are surfaced in <a href="/models/media" className="text-port-accent hover:underline">Models → Media</a>.</p><LocalSetupPanel pythonPath={pythonPath} onPythonPathChange={setPythonPath} />+ <FormField+ label="Default model"+ labelClassName="block text-xs font-medium text-gray-400 mb-1"+ >+ <select+ value={localModelId}+ onChange={(e) => setLocalModelId(e.target.value)}+ disabled={localModels === null}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ <option value="">+ {localModels === null ? 'Loading models…' : `Install default (${localDefaultLabel})`}+ </option>+ {localModelOptions.map((m) => <option key={m.id} value={m.id}>{m.name || m.id}</option>)}+ </select>+ </FormField>+ {/* Deliberately does NOT point at the Defaults tab: its per-surface+ model pin is gated on supportsCloudModelOverride and hidden for+ Local, and renderDefaults[target].imageModel only ever reaches+ resolveCloudProviderConfig — so for local renders it is inert.+ What actually outranks this pin is a per-record/per-render model+ choice, which is what the sentence names. */}+ <p className="text-xs text-gray-500">+ Used by every local render that doesn't choose its own model — the Image Gen+ form, deck cards, sprite references, pipeline visuals, character sheets and+ FableLoom. A model picked on one of those surfaces still wins for that render.+ Weights download on first use; check what's already cached in{' '}+ <a href="/models/media" className="text-port-accent hover:underline">Models → Media</a>.+ </p>+ {localModels?.length === 0 && (+ <p role="status" className="text-xs text-port-warning">+ No local image models are compatible with this machine.+ </p>+ )}<CleanersTogglescleanC2PA={cleanC2PAByMode.local}denoise={denoiseByMode.local}diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsxindex 3aff9c7c20..43e1550382 100644--- a/client/src/components/settings/ImageGenTab.test.jsx+++ b/client/src/components/settings/ImageGenTab.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';import { MemoryRouter } from 'react-router';vi.mock('../../services/api', () => ({@@ -13,6 +13,7 @@ vi.mock('../../services/api', () => ({saveHfToken: vi.fn(),clearHfToken: vi.fn(),listAgyImageModels: vi.fn(),+ listImageModels: vi.fn(),}));vi.mock('../../hooks/useHfTokenStatus', () => ({useHfTokenStatus: vi.fn(),@@ -32,7 +33,7 @@ vi.mock('../../hooks/useMediaJobSse', () => ({}));import {- getSettings, getToolsList, updateSettings, listAgyImageModels, getImageGenStatus, generateImage,+ getSettings, getToolsList, updateSettings, listAgyImageModels, listImageModels, getImageGenStatus, generateImage,} from '../../services/api';import { useHfTokenStatus } from '../../hooks/useHfTokenStatus';import { ImageGenTab, MEDIA_TABS } from './ImageGenTab';@@ -63,6 +64,10 @@ beforeEach(() => {useHfTokenStatus.mockReturnValue({ present: false, source: 'none', refresh: vi.fn() });updateSettings.mockResolvedValue({});listAgyImageModels.mockResolvedValue({ models: ['gemini-image', 'custom/image-v2'], error: null });+ listImageModels.mockResolvedValue([+ { id: 'dev', name: 'FLUX.1 Dev' },+ { id: 'flux2-klein-4b', name: 'FLUX.2 Klein' },+ ]);});describe('ImageGenTab grouped tabs', () => {@@ -96,6 +101,8 @@ describe('ImageGenTab grouped tabs', () => {await renderTab();fireEvent.click(screen.getByRole('tab', { name: /^Local/i }));expect(screen.getByTestId('local-setup-panel')).toBeTruthy();+ // The tab's lazy model-catalog probe resolves after the click.+ await act(async () => {});});it('keeps LocalSetupPanel mounted (hidden) after leaving the Local tab so an in-flight install stream is not torn down', async () => {@@ -103,6 +110,7 @@ describe('ImageGenTab grouped tabs', () => {// Not mounted until first visited (avoids a cold python-env probe).expect(screen.queryByTestId('local-setup-panel')).toBeNull();fireEvent.click(screen.getByRole('tab', { name: /^Local/i }));+ await act(async () => {});const panel = screen.getByTestId('local-setup-panel');// Switch away — the panel must stay in the DOM (its install EventSource// survives), just visually hidden, rather than unmounting.@@ -227,6 +235,90 @@ describe('ImageGenTab grouped tabs', () => {expect(patch.imageGen).toHaveProperty('expose');});+ it('pins the install-wide default local model and saves it under imageGen.local.modelId', async () => {+ await renderTab(['/media/image?mediaTab=local']);+ await act(async () => {});+ const select = screen.getByLabelText('Default model');+ // Nothing pinned in settings — blank names what the server actually+ // resolves to, not an empty option the user has to guess at.+ expect(select.value).toBe('');+ expect(screen.getByRole('option', { name: 'Install default (FLUX.1 Dev)' })).toBeTruthy();++ fireEvent.change(select, { target: { value: 'flux2-klein-4b' } });+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());+ expect(updateSettings.mock.calls[0][0].imageGen.local.modelId).toBe('flux2-klein-4b');+ });++ it('drops modelId from the save body when the pin is cleared, so the server default resolves again', async () => {+ getSettings.mockResolvedValue({+ imageGen: {+ mode: 'local',+ external: { sdapiUrl: '' },+ local: { pythonPath: '/usr/bin/python3', modelId: 'flux2-klein-4b' },+ codex: { enabled: false },+ expose: { a1111: false },+ },+ });+ await renderTab(['/media/image?mediaTab=local']);+ await act(async () => {});+ const select = screen.getByLabelText('Default model');+ expect(select.value).toBe('flux2-klein-4b');++ fireEvent.change(select, { target: { value: '' } });+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());+ // Absent, not '' — every consumer reads `local.modelId || DEFAULT`, and a+ // persisted empty string is a value they would all have to keep coercing.+ expect(JSON.parse(JSON.stringify(updateSettings.mock.calls[0][0])).imageGen.local)+ .not.toHaveProperty('modelId');+ });++ it('keeps a pin the catalog no longer lists selectable rather than silently dropping it', async () => {+ getSettings.mockResolvedValue({+ imageGen: {+ mode: 'local',+ external: { sdapiUrl: '' },+ local: { pythonPath: '/usr/bin/python3', modelId: 'retired-model' },+ codex: { enabled: false },+ expose: { a1111: false },+ },+ });+ await renderTab(['/media/image?mediaTab=local']);+ await act(async () => {});+ // A select whose value matches no option paints blank and reads as+ // "install default" — while the server is still honouring the pin.+ expect(screen.getByLabelText('Default model').value).toBe('retired-model');+ expect(screen.getByRole('option', { name: /retired-model \(unavailable on this machine\)/ })).toBeTruthy();+ });++ it('the imageGen.local save body round-trips sibling keys the tab does not edit', async () => {+ // Same wholesale-slice-replace hazard the videoGen case below pins:+ // imageGen.local carries hand-edit-only render knobs this tab never+ // renders (steps / guidance / quantize, read by fableLoom/production.js).+ // Rebuilding the slice from the rendered fields alone wipes them on every+ // Media save. The server can't see this — it validates whatever arrives.+ getSettings.mockResolvedValue({+ imageGen: {+ mode: 'local',+ external: { sdapiUrl: '' },+ local: { pythonPath: '/usr/bin/python3', steps: 28, guidance: 4.5, quantize: '4' },+ codex: { enabled: false },+ expose: { a1111: false },+ },+ });+ await renderTab(['/media/image?mediaTab=local']);+ await act(async () => {});++ fireEvent.change(screen.getByLabelText('Default model'), { target: { value: 'flux2-klein-4b' } });+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());+ const local = updateSettings.mock.calls[0][0].imageGen.local;+ expect(local).toMatchObject({ steps: 28, guidance: 4.5, quantize: '4' });+ expect(local.modelId).toBe('flux2-klein-4b');+ expect(local.pythonPath).toBe('/usr/bin/python3');+ });+it('the videoGen save body round-trips sibling keys the tab does not edit (#3231 Phase 4)', async () => {// The settings PUT replaces top-level slices wholesale, so if this wire// body ever drops the loaded slice's sibling keys, a Defaults-tab savediff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.jsindex db2be51ee4..7ba1113b2e 100644--- a/client/src/lib/imageGenModes.js+++ b/client/src/lib/imageGenModes.js@@ -50,6 +50,7 @@ import {CODEX_IMAGEGEN_DEFAULT_MODEL,GROK_ASPECT_RATIOS,I2I_CAPABLE_MODES,+ LOCAL_IMAGEGEN_DEFAULT_MODEL,MODEL_OVERRIDE_CAPABLE_MODES,cloudPromptRequired,maxInputImages,@@ -75,6 +76,10 @@ export {// pickers filter through and what `pickI2iMode` walks.I2I_CAPABLE_MODES,IMAGE_GEN_MODE,+ // The local model a blank `imageGen.local.modelId` resolves to, so the+ // Settings Local tab can name the install default instead of showing a blank+ // select whose meaning the user has to guess.+ LOCAL_IMAGEGEN_DEFAULT_MODEL,// Cloud CLIs that accept a per-render model override. Use// `supportsCloudModelOverride` at branch sites rather than a hand-rolled// `mode === CODEX || mode === AGY` disjunction.diff --git a/client/src/pages/ImageGen.defaultLocalModel.test.jsx b/client/src/pages/ImageGen.defaultLocalModel.test.jsxnew file mode 100644index 0000000000..ca543d7a93--- /dev/null+++ b/client/src/pages/ImageGen.defaultLocalModel.test.jsx@@ -0,0 +1,130 @@+/**+ * The Image Gen form seeds its model picker from the install-wide default+ * (`settings.imageGen.local.modelId`, set on Settings → Media → Local) rather+ * than from whatever the catalog happens to list first. Every other local+ * render surface already honoured that pin; this page did not, so one install+ * rendered a different model depending on which screen you started from.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import { getSettings } from '../services/api';++const DEV = { id: 'dev', name: 'FLUX.1 Dev', runner: 'mflux', steps: 20, guidance: 3.5 };+// Deliberately NOT first in the catalog — the regression this suite pins is the+// page opening on models[0] and ignoring the saved pin.+const KLEIN = { id: 'flux2-klein-4b', name: 'FLUX.2 Klein', runner: 'flux2', steps: 20, guidance: 3.5 };++vi.mock('../services/api', () => ({+ getInstances: vi.fn(async () => ({ peers: [] })),+ getImageGenStatus: vi.fn(async () => ({ connected: true, mode: 'local', readiness: 'ready' })),+ generateImage: vi.fn(async () => ({})),+ generateImageMultipart: vi.fn(async () => ({})),+ listImageModels: vi.fn(async () => [DEV, KLEIN]),+ listLorasFull: vi.fn(async () => []),+ listImageGalleryPage: vi.fn(async () => ({ items: [], total: 0, hiddenTotal: 0 })),+ cancelImageGen: vi.fn(async () => ({})),+ deleteImage: vi.fn(async () => ({})),+ setImageHidden: vi.fn(async () => ({})),+ cleanGalleryImage: vi.fn(async () => ({})),+ getActiveImageJob: vi.fn(async () => ({ activeJob: null })),+ getSettings: vi.fn(async () => ({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } })),+ buildFormData: vi.fn(() => new FormData()),+ listMediaJobs: vi.fn(async () => ({ jobs: [] })),+ regenerateGalleryImage: vi.fn(async () => ({})),+ getRegenAvailability: vi.fn(async () => ({ available: false })),+ removeImageWatermark: vi.fn(async () => ({})),+ getFlux2Status: vi.fn(async () => ({ installed: true, ready: true })),+}));++vi.mock('../hooks/useImageGenProgress', () => ({+ useImageGenProgress: () => ({ progress: null, begin: vi.fn(), end: vi.fn(), resume: vi.fn() }),+}));+vi.mock('../hooks/useMediaJobSse', () => ({+ useMediaJobSse: () => ({ attach: vi.fn(), eventSourceRef: { current: null } }),+}));+vi.mock('../hooks/useModelDownloadStatus', () => ({+ useModelDownloadStatus: () => ({+ getStatus: () => ({ cached: true }), start: vi.fn(), cancel: vi.fn(), repair: vi.fn(), refresh: vi.fn(),+ downloading: false, repairing: false, progress: null, lastError: null, activeModelId: null, extra: {}, loading: false, statusError: null,+ }),+}));+vi.mock('../hooks/useHfTokenStatus', () => ({ useHfTokenStatus: () => ({ present: true, refresh: vi.fn() }) }));+vi.mock('../hooks/useAgyModels', () => ({ useAgyModels: () => ({ models: [], error: null }) }));+vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: vi.fn() }));+vi.mock('../hooks/useMediaAnnotations', () => ({+ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),+}));+vi.mock('../hooks/useAutoRefetch', () => ({ useAutoRefetch: vi.fn() }));+vi.mock('../components/ui/Toast', () => ({+ default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),+}));+vi.mock('../components/media/PromptEnhancer', () => ({ default: () => null }));+vi.mock('../components/media/PromptFromMedia', () => ({ default: () => null }));+vi.mock('../components/media/UniverseStylePicker', () => ({ default: () => null }));+vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));+vi.mock('../components/media/MediaCard', () => ({ default: () => null }));+vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));+vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));+vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));+vi.mock('../components/Drawer', () => ({ default: () => null }));+vi.mock('../components/settings/ImageGenTab', () => ({ ImageGenTab: () => null }));+vi.mock('../components/imageGen/Flux2InstallModal', () => ({ default: () => null }));+vi.mock('../components/imageGen/GalleryImagePicker', () => ({ default: () => null }));+vi.mock('../components/imageGen/InitImagePicker', () => ({ default: () => null }));+vi.mock('../components/imageGen/ReferenceImagePicker', () => ({ default: () => null }));+vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));++const { default: ImageGen } = await import('./ImageGen.jsx');++const mount = async (path = '/media/image') => {+ await act(async () => {+ render(+ <MemoryRouter initialEntries={[path]}>+ <ImageGen />+ </MemoryRouter>,+ );+ });+};+++const settingsWith = (local) => ({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3', ...local } } });+const modelSelect = () => screen.getByLabelText('Model');++describe('ImageGen default local model', () => {+ beforeEach(() => {+ window.matchMedia = vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }));+ });++ it('opens on the model pinned in settings, not the first catalog entry', async () => {+ getSettings.mockResolvedValue(settingsWith({ modelId: 'flux2-klein-4b' }));+ await mount();+ await waitFor(() => expect(modelSelect().value).toBe('flux2-klein-4b'));+ });++ it('falls back to the first catalog entry when nothing is pinned', async () => {+ getSettings.mockResolvedValue(settingsWith({}));+ await mount();+ await waitFor(() => expect(modelSelect().value).toBe('dev'));+ });++ it('falls back to the first catalog entry when the pin no longer resolves', async () => {+ // A retired/incompatible pin must not leave the select empty — the form+ // would then submit a blank modelId the local runner cannot dispatch.+ getSettings.mockResolvedValue(settingsWith({ modelId: 'retired-model' }));+ await mount();+ await waitFor(() => expect(modelSelect().value).toBe('dev'));+ });++ it('still settles on a model when the settings fetch fails', async () => {+ getSettings.mockRejectedValue(new Error('offline'));+ await mount();+ await waitFor(() => expect(modelSelect().value).toBe('dev'));+ });++ it('lets a ?modelId= deep link win over the pin', async () => {+ getSettings.mockResolvedValue(settingsWith({ modelId: 'flux2-klein-4b' }));+ await mount('/media/image?modelId=dev');+ await waitFor(() => expect(modelSelect().value).toBe('dev'));+ });+});diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex d477787462..947fbd90cd 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -198,6 +198,11 @@ export default function ImageGen() {// AGY_IMAGEGEN_DEFAULT_MODEL — #3231).const [agyModel, setAgyModel] = useState('');const [savedAgyModel, setSavedAgyModel] = useState('');+ // The install-wide default local model (Settings → Media → Local). `null`+ // until settings resolve — distinct from '' ("loaded, no pin"), because the+ // first-paint model pick below has to wait for the answer rather than race+ // the catalog fetch and land on whatever happens to be first.+ const [savedLocalModelId, setSavedLocalModelId] = useState(null);// i2i (Flux, local mflux only). source='upload' carries `file`; source='gallery'// carries `name` (basename from URL param). Coupled lifetime — always replace@@ -403,12 +408,17 @@ export default function ImageGen() {// Shown as the "Settings default (…)" option label on the per-render Agy// model select, so the user can see what blank actually resolves to.setSavedAgyModel(s?.imageGen?.agy?.model || '');+ setSavedLocalModelId(s?.imageGen?.local?.modelId || '');setSavedCleanC2PAByMode(c2);setSavedDenoiseByMode(dn);setSelectedMode(next);setCleanC2PA(c2[next] === true);setDenoise(dn[next] === true);- }).catch(() => {});+ }).catch(() => {+ // Settings unreachable — settle the pin to "none" so the model seed+ // below still resolves instead of waiting forever on a failed fetch.+ setSavedLocalModelId('');+ });}, [refreshRegenAvailability]);// Switch the active backend AND re-seed the cleaner checkboxes from the@@ -424,10 +434,7 @@ export default function ImageGen() {}, [savedCleanC2PAByMode, savedDenoiseByMode]);useEffect(() => {- listImageModels().then((m) => {- setModels(m);- if (m.length && !modelId) setModelId(m[0].id);- }).catch(() => {});+ listImageModels().then(setModels).catch(() => {});// Use the richer /api/loras surface so the picker can show trigger// words + recommended scale + Civitai-derived runnerFamily.listLorasFull().then(setAvailableLoras).catch(() => {});@@ -470,6 +477,17 @@ export default function ImageGen() {return () => eventSourceRef.current?.close();}, []);+ // Seed the model picker from the install-wide default (Settings → Media →+ // Local), falling back to the first catalog entry when nothing is pinned or+ // the pin no longer resolves. Runs once BOTH async answers are in — seeding+ // from whichever resolved first is what made the page ignore the pin. A form+ // already carrying a model (deep link, restored active job, a user pick) is+ // never overwritten.+ useEffect(() => {+ if (modelId || savedLocalModelId === null || !models.length) return;+ setModelId(models.some((m) => m.id === savedLocalModelId) ? savedLocalModelId : models[0].id);+ }, [models, savedLocalModelId, modelId]);+// Re-probe status whenever the effective backend changes — flipping the// chip from Local to Codex shouldn't leave the badge / notConnected// gating reflecting the previous backend.diff --git a/server/lib/imageGenCapabilities.js b/server/lib/imageGenCapabilities.jsindex ce27bde424..c9a275b0d3 100644--- a/server/lib/imageGenCapabilities.js+++ b/server/lib/imageGenCapabilities.js@@ -97,6 +97,13 @@ export const CODEX_IMAGEGEN_DEFAULT_EFFORT = 'low';// install with no catalog falls back to.export const AGY_IMAGEGEN_DEFAULT_MODEL = 'gemini-3.8-flash-low';+// The local runner's fallback model id when neither the request nor+// settings.imageGen.local.modelId names one (local.js's parameter default).+// Lives here rather than in `services/imageGen/modes.js` because the Settings+// Local tab labels its "install default" option with whichever model a blank+// pin actually resolves to — the same reason the Codex/Agy pins moved down.+export const LOCAL_IMAGEGEN_DEFAULT_MODEL = 'dev';+// The image model behind agy's generate_image tool — fixed server-side by// Antigravity and NOT selectable by PortOS. Re-probed 2026-07-30 against agy// 1.1.8 and still closed; the decisive evidence is now the tool's own schema,diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.jsindex 51e3ec59cc..0a63fbf3ec 100644--- a/server/services/imageGen/modes.js+++ b/server/services/imageGen/modes.js@@ -26,6 +26,7 @@ import {CODEX_IMAGEGEN_DEFAULT_EFFORT,CODEX_IMAGEGEN_DEFAULT_MODEL,EDIT_INCAPABLE_IMAGE_MODES,+ LOCAL_IMAGEGEN_DEFAULT_MODEL,isEditCapableMode,} from '../../lib/imageGenCapabilities.js';@@ -45,6 +46,9 @@ export {CODEX_IMAGEGEN_DEFAULT_EFFORT,CODEX_IMAGEGEN_DEFAULT_MODEL,EDIT_INCAPABLE_IMAGE_MODES,+ // The local runner's fallback model id. Re-exported so provenance writers+ // (sprite candidate sidecars, #2896) keep their service-local import path.+ LOCAL_IMAGEGEN_DEFAULT_MODEL,isEditCapableMode,};@@ -167,12 +171,6 @@ export function nearestAspectRatio(width, height, ratios) {/** `nearestAspectRatio` bound to agy's alphabet. */export const nearestAgyAspectRatio = (width, height) => nearestAspectRatio(width, height, AGY_ASPECT_RATIOS);-// The local runner's fallback model id when neither the request nor-// settings.imageGen.local.modelId names one (local.js's parameter default).-// Exported so provenance writers (sprite candidate sidecars, #2896) can-// record the model that actually ran without hardcoding a second copy.-export const LOCAL_IMAGEGEN_DEFAULT_MODEL = 'dev';-/*** Resolve the queue-capable image mode for a render request: the per-request* override (honored only when that backend is enabled/available), else thediff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.jsindex 053ac68e65..e5f5aec137 100644--- a/server/services/imageGen/prepareParams.js+++ b/server/services/imageGen/prepareParams.js@@ -28,7 +28,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, resolveGalleryImage, copyFileGuarded, unlinkGuarded } from '../../lib/fileUtils.js';import { getSettings } from '../settings.js';import { IMAGE_GEN_MODE, resolveImageCleaners } from './index.js';-import { editIncapableModeError, isEditCapableMode, modeLabel } from './modes.js';+import { LOCAL_IMAGEGEN_DEFAULT_MODEL, editIncapableModeError, isEditCapableMode, modeLabel } from './modes.js';import {cloudPromptRequired, maxInputImages, resolveCloudProviderConfig, resolveRenderTargetConfig,} from './cloudProviderConfig.js';@@ -70,18 +70,27 @@ const RECORD_PIN_SOURCES = Object.freeze([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.+ * Select the model a local render will actually use. An omitted model prefers+ * the install-wide pin (`settings.imageGen.local.modelId`, set on Settings →+ * Media → Local), then the historical `dev` default — each only when it can+ * actually run on this host; otherwise it falls through to the first+ * compatible catalog entry.+ *+ * `pinnedId` is a PREFERENCE, not a request: a stale or incompatible pin is+ * skipped rather than rejected, because the user who saved it is not the+ * caller of this render and has no way to see a 400 from it. A caller's own+ * `modelId` keeps its existing exact-match-or-throw handling upstream.** @param {string|null|undefined} modelId* @param {object[]} [allModels]+ * @param {string|null} [pinnedId] - settings.imageGen.local.modelId* @returns {object|undefined}*/-export function selectLocalImageModel(modelId, allModels = getImageModels()) {+export function selectLocalImageModel(modelId, allModels = getImageModels(), pinnedId = null) {const requestedModel = allModels.find((model) => model.id === modelId);return requestedModel || [- allModels.find((model) => model.id === 'dev'),+ allModels.find((model) => model.id === pinnedId),+ allModels.find((model) => model.id === LOCAL_IMAGEGEN_DEFAULT_MODEL),...allModels,].filter(Boolean).find((model) => isHardwareCompatible(model.hardwareCompatibility)) || allModels[0];}@@ -349,7 +358,8 @@ export async function prepareGenerateParams({ data, files, referenceImageFields* called from the route right before it enqueues a local job.** Resolves the effective model via the same fallback chain the local worker- * uses (`params.modelId` → compatible `'dev'` → the first compatible model)+ * uses (`params.modelId` → the install pin → compatible `'dev'` → the first+ * compatible model)* and validates it can actually run: an edit-only model (e.g. Qwen-Image-Edit)* requires a source image, and any model that isn't FLUX.2 or diffusers-run* needs a configured pythonPath. Throws the identical `ServerError`s (same@@ -379,7 +389,7 @@ export function resolveLocalImageModel(settings, params) {// 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 = selectLocalImageModel(params.modelId, allModels);+ const selectedModel = selectLocalImageModel(params.modelId, allModels, settings.imageGen?.local?.modelId || null);if (selectedModel && !isHardwareCompatible(selectedModel.hardwareCompatibility)) {throw new ServerError(hardwareUnavailableReason(`Image model "${selectedModel.id}"`, selectedModel.hardwareCompatibility),diff --git a/server/services/imageGen/prepareParams.test.js b/server/services/imageGen/prepareParams.test.jsindex 131d7b21f5..f4da1331ff 100644--- a/server/services/imageGen/prepareParams.test.js+++ b/server/services/imageGen/prepareParams.test.js@@ -41,6 +41,36 @@ describe('selectLocalImageModel', () => {];expect(selectLocalImageModel(undefined, models).id).toBe('custom');});++ // The install-wide pin (settings.imageGen.local.modelId, Settings → Media →+ // Local). Without this rung the setting is a control that silently does+ // nothing for any render whose body omits modelId.+ it('prefers the install pin over the dev default when the caller omits a model', () => {+ const models = [+ { id: 'dev', hardwareCompatibility: { state: 'available' } },+ { id: 'klein', hardwareCompatibility: { state: 'available' } },+ ];+ expect(selectLocalImageModel(undefined, models, 'klein').id).toBe('klein');+ });++ it('lets the caller\'s own model outrank the install pin', () => {+ const models = [+ { id: 'dev', hardwareCompatibility: { state: 'available' } },+ { id: 'klein', hardwareCompatibility: { state: 'available' } },+ ];+ expect(selectLocalImageModel('dev', models, 'klein').id).toBe('dev');+ });++ it('skips an install pin this host cannot run rather than rejecting the render', () => {+ // The user who saved the pin is not the caller of this render, so a stale+ // or incompatible pin must degrade, never 400.+ const models = [+ { id: 'dev', hardwareCompatibility: { state: 'available' } },+ { id: 'klein', hardwareCompatibility: { state: 'unavailable' } },+ ];+ expect(selectLocalImageModel(undefined, models, 'klein').id).toBe('dev');+ expect(selectLocalImageModel(undefined, models, 'retired-model').id).toBe('dev');+ });});beforeEach(() => {