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: restore images through Image Gen remix path (#8077)
[._.]/ Adam Eivy1c258396844a
diff --git a/client/src/components/providers/ProviderServicesTab.jsx b/client/src/components/providers/ProviderServicesTab.jsxindex dda1f130c8..a1cb938517 100644--- a/client/src/components/providers/ProviderServicesTab.jsx+++ b/client/src/components/providers/ProviderServicesTab.jsx@@ -62,9 +62,16 @@ function ServiceCard({if (open) ref.current?.scrollIntoView?.({ block: 'nearest' });}, [open]);// Re-seeded only when the row's revision moves, so a poll that changed- // nothing cannot wipe a half-typed edit.+ // nothing cannot wipe a half-typed edit. The initial state already matches+ // the loaded service; skip the redundant mount reset so a fast first edit+ // cannot be overwritten by the passive effect.const [draft, setDraft] = useState(() => draftFrom(service));- useEffect(() => { setDraft(draftFrom(service)); }, [service.id, service.revision]); // eslint-disable-line react-hooks/exhaustive-deps+ const draftVersionRef = useRef({ id: service.id, revision: service.revision });+ useEffect(() => {+ if (draftVersionRef.current.id === service.id && draftVersionRef.current.revision === service.revision) return;+ draftVersionRef.current = { id: service.id, revision: service.revision };+ setDraft(draftFrom(service));+ }, [service.id, service.revision]); // eslint-disable-line react-hooks/exhaustive-depsconst [confirmingDelete, setConfirmingDelete] = useState(false);const set = (key) => (e) => setDraft((prev) => ({ ...prev, [key]: e.target.value }));const setTransport = (protocol) => (e) => setDraft((prev) => ({ ...prev, transports: { ...prev.transports, [protocol]: e.target.value } }));diff --git a/client/src/components/ui/CollapsibleListItem.jsx b/client/src/components/ui/CollapsibleListItem.jsxindex 43fd57edba..4d658d3077 100644--- a/client/src/components/ui/CollapsibleListItem.jsx+++ b/client/src/components/ui/CollapsibleListItem.jsx@@ -6,6 +6,7 @@ import usePrefersReducedMotion from '../../hooks/usePrefersReducedMotion';*/export default function CollapsibleListItem({ removing, onExited, children, spacing = '0.5rem' }) {const elementRef = useRef(null);+ const hadFocusRef = useRef(false);const exitRef = useRef(onExited);exitRef.current = onExited;const reducedMotion = usePrefersReducedMotion();@@ -13,7 +14,9 @@ export default function CollapsibleListItem({ removing, onExited, children, spacuseEffect(() => {if (!removing) return undefined;const element = elementRef.current;- if (element.contains(document.activeElement)) {+ const shouldRestoreFocus = element.contains(document.activeElement) || hadFocusRef.current;+ hadFocusRef.current = false;+ if (shouldRestoreFocus) {const siblings = [...element.parentElement.children];const destination = siblings.slice(siblings.indexOf(element) + 1).find(sibling => !sibling.inert)|| siblings.reverse().find(sibling => sibling !== element && !sibling.inert)@@ -26,7 +29,17 @@ export default function CollapsibleListItem({ removing, onExited, children, spac}, [removing, reducedMotion]);return (- <div ref={elementRef} tabIndex={-1} inert={removing || undefined}+ <div+ ref={elementRef}+ tabIndex={-1}+ inert={removing || undefined}+ onFocusCapture={() => { hadFocusRef.current = true; }}+ onBlurCapture={event => {+ if (event.relatedTarget && event.relatedTarget !== document.body+ && !event.currentTarget.contains(event.relatedTarget)) {+ hadFocusRef.current = false;+ }+ }}className="grid transition-[grid-template-rows,opacity] duration-200 ease-out motion-reduce:transition-none"style={{ gridTemplateRows: removing ? '0fr' : '1fr', opacity: removing ? 0 : 1 }}><div className="min-h-0 overflow-hidden">diff --git a/client/src/hooks/useMediaPreviewActions.js b/client/src/hooks/useMediaPreviewActions.jsindex 364f3f2d52..4530a0d0c5 100644--- a/client/src/hooks/useMediaPreviewActions.js+++ b/client/src/hooks/useMediaPreviewActions.js@@ -78,16 +78,11 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})// fps, tiling, etc.). Video remix lands the user in 'text' mode with all// params filled; they can switch to image/extend mode and pick a source.//- // Videos hand over the RECORD ID (`?remix=<id>`), not a render-settings- // bundle (#6290). A field-by-field URL is a second restore implementation- // that has to be extended every time a render field is added, and it fell- // behind the in-page one: `textEncoderId`, `speedProfileId`, `draftDecode`- // and the LoRA arrays were all missing here, so remixing the same clip from- // Media History silently returned those controls to stock while remixing it- // from the Video Gen gallery restored them. The id lets /media/video resolve- // the record from its own history load and reuse `applyRemix` — the single- // restore implementation. The field bundle below stays for records with no- // id (and keeps previously-issued links working), but is not extended.+ // Saved videos hand over the record id, and saved images hand over the+ // filename, rather than maintaining a second field-by-field restore path.+ // The destination resolves the record and reuses its in-page restore logic.+ // Filename-less images and id-less videos keep their legacy bundles for+ // compatibility; those bundles are not extended.const handleRemix = useCallback((item) => {if (!item) return;if (item.kind === 'video') {@@ -119,8 +114,11 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})navigate(`/media/video?${params}`);return;}+ if (item.filename) {+ navigate('/media/image?remix=' + encodeURIComponent(item.filename));+ return;+ }const params = buildImageGenParams(item);- if (item.filename) params.set('remix', item.filename);navigate(`/media/image?${params}`);}, [navigate]);diff --git a/client/src/hooks/useMediaPreviewActions.test.jsx b/client/src/hooks/useMediaPreviewActions.test.jsxindex 13917db643..f81a961f1e 100644--- a/client/src/hooks/useMediaPreviewActions.test.jsx+++ b/client/src/hooks/useMediaPreviewActions.test.jsx@@ -22,6 +22,57 @@ const parseNav = () => {describe('useMediaPreviewActions.handleRemix', () => {beforeEach(() => navigate.mockReset());+ it('sends a saved image back to /media/image by filename only', () => {+ const { result } = renderHook(() => useMediaPreviewActions());+ result.current.handleRemix({+ kind: 'image',+ filename: 'example image.png',+ prompt: 'a paper kite above a garden',+ negativePrompt: 'blurry',+ modelId: 'flux2',+ width: 1024,+ height: 768,+ seed: 42,+ steps: 12,+ guidance: 3,+ quantize: '8',+ loraFilenames: ['example-lora.safetensors'],+ loraScales: [0.7],+ });+ const { path, params } = parseNav();+ expect(path).toBe('/media/image');+ expect(params.get('remix')).toBe('example image.png');+ expect([...params.keys()]).toEqual(['remix']);+ });++ it('keeps the legacy settings bundle for a filename-less image', () => {+ const { result } = renderHook(() => useMediaPreviewActions());+ result.current.handleRemix({+ kind: 'image',+ prompt: 'a paper kite above a garden',+ negativePrompt: 'blurry',+ modelId: 'flux2',+ width: 1024,+ height: 768,+ seed: 42,+ steps: 12,+ guidance: 3,+ quantize: '8',+ });+ const { path, params } = parseNav();+ expect(path).toBe('/media/image');+ expect(params.get('remix')).toBeNull();+ expect(params.get('prompt')).toBe('a paper kite above a garden');+ expect(params.get('negativePrompt')).toBe('blurry');+ expect(params.get('modelId')).toBe('flux2');+ expect(params.get('width')).toBe('1024');+ expect(params.get('height')).toBe('768');+ expect(params.get('seed')).toBe('42');+ expect(params.get('steps')).toBe('12');+ expect(params.get('guidance')).toBe('3');+ expect(params.get('quantize')).toBe('8');+ });+// #6290: a saved video hands over its RECORD ID, not a render-settings// bundle. The bundle was a second restore implementation that had to be// extended for every new render field and wasn't — it silently dropped thediff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 0b836f265d..e2f77d41e8 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -63,7 +63,7 @@ import {getImageGenStatus, generateImage, generateImageMultipart, listImageModels, listLorasFull,cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,buildFormData, listMediaJobs, regenerateGalleryImage, getRegenAvailability, removeImageWatermark,- getFlux2Status,+ getFlux2Status, getGalleryImages,} from '../services/api';// Positional slots preserve uploads across model switches. Qwen 2.1 takes up@@ -71,6 +71,8 @@ import {// referenceSlotsFor reserves room for the init image where the cap is shared.const REFERENCE_SLOT_COUNT = 10;const EMPTY_REF_SLOT = { file: null, previewUrl: null, strength: 1.0 };+const IMAGE_GEN_RESTORE_PARAM_KEYS = ['prompt', 'negativePrompt', 'modelId', 'width', 'height', 'seed', 'steps', 'guidance', 'quantize'];+const IMAGE_GEN_HANDOFF_PARAM_KEYS = ['remix', ...IMAGE_GEN_RESTORE_PARAM_KEYS, 'initImageFile'];// Revoke an object URL only when it's a blob: URL we created — gallery `/data/...`// previews must never be revoked.@@ -125,13 +127,21 @@ const CONNECTED_MODE_LABELS = {export default function ImageGen() {const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();+ const remixHandoffFilename = searchParams.get('remix');const settingsOpen = searchParams.get('settings') === '1';const openSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.set('settings', '1'); return n; });const closeSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.delete('settings'); return n; });const [status, setStatus] = useState(null);const [statusLoading, setStatusLoading] = useState(true);const [models, setModels] = useState([]);+ const [modelsLoaded, setModelsLoaded] = useState(false);+ const [modelsLoadFailed, setModelsLoadFailed] = useState(false);const [availableLoras, setAvailableLoras] = useState([]);+ const [lorasLoaded, setLorasLoaded] = useState(false);+ const [lorasLoadFailed, setLorasLoadFailed] = useState(false);+ const [remixHandoff, setRemixHandoff] = useState(null);+ const remixLookupSequenceRef = useRef(0);+ const remixHandoffPending = remixHandoff?.status === 'loading' || remixHandoff?.status === 'restoring';// `preview` is URL-driven via `usePreviewRoute(previewItems)` — declared// after `previewItems` below so the resolver can match against it.const [showHidden, setShowHidden] = useState(false);@@ -432,10 +442,24 @@ export default function ImageGen() {}, [savedCleanC2PAByMode, savedDenoiseByMode]);useEffect(() => {- listImageModels().then(setModels).catch(() => {});+ listImageModels().then((loadedModels) => {+ setModels(loadedModels);+ setModelsLoadFailed(false);+ setModelsLoaded(true);+ }).catch(() => {+ setModelsLoadFailed(true);+ setModelsLoaded(true);+ });// Use the richer /api/loras surface so the picker can show trigger// words + recommended scale + Civitai-derived runnerFamily.- listLorasFull().then(setAvailableLoras).catch(() => {});+ listLorasFull().then((loadedLoras) => {+ setAvailableLoras(loadedLoras);+ setLorasLoadFailed(false);+ setLorasLoaded(true);+ }).catch(() => {+ setLorasLoadFailed(true);+ setLorasLoaded(true);+ });reloadBackends();// Resume an in-flight job so the user can navigate away mid-render and// come back to the same prompt + settings + live preview frame.@@ -534,12 +558,11 @@ export default function ImageGen() {// Inbound params from Media History / Send-to-i2i (?prompt=…&modelId=…&seed=…// and/or ?initImageFile=…). Populate form state once on mount, then strip ALL// consumed params in a SINGLE setSearchParams so a hot-reload/back-nav doesn't- // re-clobber later edits — and so the init-image strip and the remix-keys strip- // can't race as two competing updates (which left initImageFile in the URL).+ // re-clobber later edits — and so the settings and init-image keys can't race+ // as two competing updates (which left initImageFile in the URL).useEffect(() => {- const remixKeys = ['prompt', 'negativePrompt', 'modelId', 'width', 'height', 'seed', 'steps', 'guidance', 'quantize'];const initFile = searchParams.get('initImageFile');- const present = remixKeys.filter((k) => searchParams.get(k) != null);+ const present = IMAGE_GEN_RESTORE_PARAM_KEYS.filter((k) => searchParams.get(k) != null);if (!initFile && present.length === 0) return;const get = (k) => searchParams.get(k);if (get('prompt')) {@@ -563,10 +586,14 @@ export default function ImageGen() {setInitImage({ source: 'gallery', file: null, name: initFile, previewUrl: `/data/images/${initFile}` });wantI2iModeRef.current = true;}+ // Older Remix links carry both this field bundle and the filename. Keep+ // the bundle as a fallback, then let the filename restore replace it once+ // the record and its supporting catalogs have loaded. One URL update+ // consumes both handoffs after that lookup settles.+ if (searchParams.get('remix')) return;setSearchParams((prev) => {const n = new URLSearchParams(prev);- remixKeys.forEach((k) => n.delete(k));- n.delete('initImageFile');+ IMAGE_GEN_HANDOFF_PARAM_KEYS.forEach((key) => n.delete(key));return n;}, { replace: true });}, []);@@ -1074,6 +1101,7 @@ export default function ImageGen() {const handleGenerate = async (e) => {e?.preventDefault?.();+ if (remixHandoffPending) return;// Empty prompt is allowed (e.g. i2i / unconditional generation). The disabled// submit button blocks clicks, but an Enter keypress in a number input still// fires onSubmit — gate here too so an edit-only model without a source image@@ -1297,6 +1325,102 @@ export default function ImageGen() {window.scrollTo({ top: 0, behavior: 'smooth' });}, [availableLoras, models]);+ const consumeRemixHandoff = useCallback(() => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ IMAGE_GEN_HANDOFF_PARAM_KEYS.forEach((key) => next.delete(key));+ return next;+ }, { replace: true });+ }, [setSearchParams]);++ const lookupRemixHandoff = useCallback((filename) => {+ const sequence = ++remixLookupSequenceRef.current;+ setRemixHandoff({ filename, status: 'loading' });+ getGalleryImages([filename], { silent: true }).then((items) => {+ if (sequence !== remixLookupSequenceRef.current) return;+ const record = items?.[0];+ setRemixHandoff(record+ ? { filename, status: 'restoring', record }+ : { filename, status: 'missing' });+ }).catch(() => {+ if (sequence === remixLookupSequenceRef.current) {+ setRemixHandoff({ filename, status: 'error' });+ }+ });+ }, []);++ useEffect(() => {+ if (!remixHandoffFilename) return;+ lookupRemixHandoff(remixHandoffFilename);+ return () => { remixLookupSequenceRef.current += 1; };+ }, [remixHandoffFilename, lookupRemixHandoff]);++ // Keep the old prompt/settings and Send-to-i2i handoffs intact, but wait for+ // this record path before consuming their URL keys when a legacy Remix bundle+ // is also present.+ useEffect(() => {+ if (!remixHandoff) return;+ if (remixHandoff.status === 'missing' || remixHandoff.status === 'error') {+ consumeRemixHandoff();+ return;+ }+ if (remixHandoff.status !== 'restoring') return;+ if (modelsLoadFailed || lorasLoadFailed) {+ setRemixHandoff({ ...remixHandoff, status: 'error', failure: 'catalog' });+ consumeRemixHandoff();+ return;+ }+ if (!modelsLoaded || !lorasLoaded) return;+ handleRemix(remixHandoff.record);+ setRemixHandoff(null);+ consumeRemixHandoff();+ }, [remixHandoff, modelsLoaded, lorasLoaded, modelsLoadFailed, lorasLoadFailed, handleRemix, consumeRemixHandoff]);++ useEffect(() => {+ if (remixHandoffFilename) return;+ // If a user replaces the URL while a lookup is pending, don't leave the+ // Generate action blocked by a request that no longer owns the page.+ setRemixHandoff((current) => (+ current?.status === 'loading' || current?.status === 'restoring' ? null : current+ ));+ }, [remixHandoffFilename]);++ const retryRemixHandoff = useCallback(() => {+ const filename = remixHandoff?.filename;+ if (!filename) return;+ if (remixHandoff.failure === 'catalog') {+ if (modelsLoadFailed) {+ setModelsLoaded(false);+ setModelsLoadFailed(false);+ listImageModels().then((loadedModels) => {+ setModels(loadedModels);+ setModelsLoaded(true);+ }).catch(() => {+ setModelsLoadFailed(true);+ setModelsLoaded(true);+ });+ }+ if (lorasLoadFailed) {+ setLorasLoaded(false);+ setLorasLoadFailed(false);+ listLorasFull().then((loadedLoras) => {+ setAvailableLoras(loadedLoras);+ setLorasLoaded(true);+ }).catch(() => {+ setLorasLoadFailed(true);+ setLorasLoaded(true);+ });+ }+ }+ lookupRemixHandoff(filename);+ }, [remixHandoff, modelsLoadFailed, lorasLoadFailed, lookupRemixHandoff]);++ const dismissRemixHandoff = useCallback(() => {+ remixLookupSequenceRef.current += 1;+ setRemixHandoff(null);+ consumeRemixHandoff();+ }, [consumeRemixHandoff]);+// The i2i init image only applies on an i2i-capable backend (local or codex).// Switch to one now if installed; otherwise flag the deferred effect to retry// once availableBackends resolves. Called by the in-page send-to-i2i handler;@@ -1409,6 +1533,44 @@ export default function ImageGen() {</div></div>+ {remixHandoffPending && (+ <p role="status" className="rounded-lg border border-port-border bg-port-card px-3 py-2 text-xs text-gray-400">+ Restoring this image’s settings — Generate is paused until they are ready.+ </p>+ )}+ {remixHandoff && (remixHandoff.status === 'error' || remixHandoff.status === 'missing') && (+ <div+ role="status"+ className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2"+ >+ <div>+ {remixHandoff.failure === 'catalog'+ ? 'Couldn’t load the model or LoRA catalog, so this image’s settings were not restored.'+ : remixHandoff.status === 'error'+ ? 'Couldn’t load this image’s render settings.'+ : 'That image is no longer in the gallery, so its render settings could not be restored.'}+ {' '}Retry the lookup or dismiss this notice.+ </div>+ <div className="flex items-center gap-2 self-start sm:self-auto">+ <button+ type="button"+ onClick={retryRemixHandoff}+ className="whitespace-nowrap inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80"+ >+ <RefreshCw className="w-3.5 h-3.5" />+ Retry+ </button>+ <button+ type="button"+ onClick={dismissRemixHandoff}+ className="text-gray-400 hover:text-gray-200 text-xs"+ >+ Dismiss+ </button>+ </div>+ </div>+ )}+<form onSubmit={handleGenerate} className="grid min-w-0 max-w-full grid-cols-1 gap-4 lg:grid-cols-[3fr_2fr]"><div className="min-w-0 bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3"><FormField label="Prompt" labelClassName="block text-xs font-medium text-gray-400 mb-1">@@ -1430,12 +1592,14 @@ export default function ImageGen() {// The probe decides WHICH backend can run, not what the user may// type — so it gates submit and backend selection only. Every form// control stays live while the status pill is still checking.- disabled={remoteTargetActive+ disabled={remixHandoffPending || (remoteTargetActive? remoteBlocked !== null- : (localBackendPending || notConnected || editImageMissing || cloudNeedsPrompt)}- title={localBackendPending- ? 'Checking the image backend…'- : remoteBlocked || (editImageMissing ? 'This image-edit model needs a source image — open Options and upload one first' : cloudNeedsPrompt ? cloudPromptHint : undefined)}+ : (localBackendPending || notConnected || editImageMissing || cloudNeedsPrompt))}+ title={remixHandoffPending+ ? 'Restoring this image’s settings…'+ : localBackendPending+ ? 'Checking the image backend…'+ : remoteBlocked || (editImageMissing ? 'This image-edit model needs a source image — open Options and upload one first' : cloudNeedsPrompt ? cloudPromptHint : undefined)}className="flex min-h-[44px] items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white hover:bg-port-accent/80 disabled:cursor-not-allowed disabled:opacity-50"><Sparkles className="w-4 h-4" /> {generating ? 'Queue' : 'Generate'}diff --git a/client/src/pages/ImageGen.remix.test.jsx b/client/src/pages/ImageGen.remix.test.jsxnew file mode 100644index 0000000000..5771b658a1--- /dev/null+++ b/client/src/pages/ImageGen.remix.test.jsx@@ -0,0 +1,134 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, screen, waitFor } from '@testing-library/react';++import {+ imageGenModel,+ loadImageGenPage,+ renderImageGenPage,+ resetImageGenMockState,+ state,+} from '../test/imageGenPageMocks.jsx';++const MODEL = imageGenModel('installed-image', { name: 'Example Image Model' });+const LORA = { filename: 'example-style.safetensors', name: 'Example Style' };+const RECORD = {+ filename: 'example-render.png',+ prompt: 'a paper kite above a garden',+ negative_prompt: 'blurry edges',+ modelId: MODEL.id,+ width: 1024,+ height: 768,+ seed: 42,+ steps: 12,+ guidance: 3.5,+ quantize: '6',+ loraFilenames: [LORA.filename],+ loraScales: [0.7],+};++await loadImageGenPage();++describe('ImageGen cross-page Remix handoff', () => {+ beforeEach(() => {+ resetImageGenMockState();+ state.models = [MODEL];+ state.availableLoras = [LORA];+ state.getGalleryImages.mockResolvedValue([RECORD]);+ window.matchMedia = vi.fn(() => ({+ matches: true,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }));+ });++ it('restores the same image settings from a filename handoff as in-page Remix', async () => {+ await renderImageGenPage('/media/image?remix=' + encodeURIComponent(RECORD.filename));++ await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));+ expect(state.getGalleryImages).toHaveBeenCalledWith([RECORD.filename], { silent: true });+ expect(screen.getByLabelText('Negative Prompt')).toHaveValue(RECORD.negative_prompt);+ expect(screen.getByLabelText('Model')).toHaveValue(MODEL.id);+ expect(screen.getByLabelText('Seed')).toHaveValue(RECORD.seed);+ expect(screen.getByLabelText(/Steps/)).toHaveValue(RECORD.steps);+ expect(screen.getByLabelText(/Guidance/)).toHaveValue(RECORD.guidance);+ expect(screen.getByLabelText('Quantize (bits)')).toHaveValue(RECORD.quantize);+ expect(state.resolutionFieldProps).toMatchObject({ width: RECORD.width, height: RECORD.height });+ expect(state.loraPickerProps.selected).toEqual([+ { filename: LORA.filename, name: LORA.name, scale: RECORD.loraScales[0] },+ ]);+ await waitFor(() => expect(state.locationSearch).not.toContain('remix'));+ });++ it('waits for the model and LoRA catalogs before restoring the form', async () => {+ let settleModels;+ let settleLoras;+ state.listImageModels.mockReturnValue(new Promise((resolve) => { settleModels = resolve; }));+ state.listLorasFull.mockReturnValue(new Promise((resolve) => { settleLoras = resolve; }));+ await renderImageGenPage('/media/image?remix=' + encodeURIComponent(RECORD.filename));++ await screen.findByText(/Restoring this image’s settings/);+ expect(screen.getByLabelText('Prompt')).not.toHaveValue(RECORD.prompt);+ expect(screen.getByRole('button', { name: /Generate/ })).toBeDisabled();++ await act(async () => {+ settleModels([MODEL]);+ settleLoras([LORA]);+ });++ await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));+ expect(state.loraPickerProps.selected).toEqual([+ { filename: LORA.filename, name: LORA.name, scale: RECORD.loraScales[0] },+ ]);+ });++ it('does not select a model that is no longer installed', async () => {+ state.getGalleryImages.mockResolvedValue([{ ...RECORD, modelId: 'retired-model' }]);+ await renderImageGenPage('/media/image?remix=' + encodeURIComponent(RECORD.filename));++ await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));+ expect(screen.getByLabelText('Model')).toHaveValue(MODEL.id);+ });++ it('keeps the legacy prompt and size URL handoff working', async () => {+ await renderImageGenPage('/media/image?prompt=legacy%20prompt&width=704&height=1280');++ await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue('legacy prompt'));+ expect(state.resolutionFieldProps).toMatchObject({ width: 704, height: 1280 });+ await waitFor(() => expect(state.locationSearch).toBe(''));+ expect(state.getGalleryImages).not.toHaveBeenCalled();+ });++ it('keeps the legacy Send-to-i2i init image handoff working', async () => {+ await renderImageGenPage('/media/image?initImageFile=example-source.png');++ await waitFor(() => expect(state.initImagePickerProps?.initImage).toMatchObject({+ source: 'gallery',+ name: 'example-source.png',+ previewUrl: '/data/images/example-source.png',+ }));+ await waitFor(() => expect(state.locationSearch).toBe(''));+ expect(state.getGalleryImages).not.toHaveBeenCalled();+ });++ it('shows a retryable notice for a missing image and removes the handoff URL', async () => {+ state.getGalleryImages.mockResolvedValueOnce([]).mockResolvedValueOnce([RECORD]);+ await renderImageGenPage('/media/image?remix=' + encodeURIComponent(RECORD.filename));++ await screen.findByText(/no longer in the gallery/);+ await waitFor(() => expect(state.locationSearch).not.toContain('remix'));++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));+ expect(state.getGalleryImages).toHaveBeenCalledTimes(2);+ });++ it('shows a dismissible notice when the lookup fails and removes the handoff URL', async () => {+ state.getGalleryImages.mockRejectedValueOnce(new Error('offline'));+ await renderImageGenPage('/media/image?remix=' + encodeURIComponent(RECORD.filename));++ await screen.findByText(/load this image’s render settings/);+ await waitFor(() => expect(state.locationSearch).not.toContain('remix'));+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ await waitFor(() => expect(screen.queryByText(/load this image’s render settings/)).toBeNull());+ });+});diff --git a/client/src/test/imageGenPageMocks.jsx b/client/src/test/imageGenPageMocks.jsxindex d7f9390b41..0bc811d9a7 100644--- a/client/src/test/imageGenPageMocks.jsx+++ b/client/src/test/imageGenPageMocks.jsx@@ -28,7 +28,7 @@import { StrictMode } from 'react';import { act, render } from '@testing-library/react';-import { MemoryRouter } from 'react-router';+import { MemoryRouter, useLocation } from 'react-router';import { vi } from 'vitest';/** Local model as the catalog reports it; `.defaultLocalModel` pins its regressions against this shape. */@@ -94,6 +94,12 @@ const defaultStatus = async () => ({export const state = {/** Catalog `listImageModels` resolves to; reassign for a different model list. */models: [imageGenModel('dev', { name: 'FLUX.1 Dev' })],+ listImageModels: vi.fn(async () => state.models),+ getGalleryImages: vi.fn(async () => []),+ locationSearch: '',+ initImagePickerProps: null,+ loraPickerProps: null,+ resolutionFieldProps: null,/** `GET /api/instances` peers — a media-provider peer makes the target picker appear. */peers: [],/** `getImageGenStatus`; a spy so a suite can hold the probe open or vary the payload. */@@ -140,6 +146,12 @@ export const state = {/** Restore every documented default, including fresh spies. Call it first in `beforeEach`. */export function resetImageGenMockState() {state.models = [imageGenModel('dev', { name: 'FLUX.1 Dev' })];+ state.listImageModels.mockReset().mockImplementation(async () => state.models);+ state.getGalleryImages.mockReset().mockResolvedValue([]);+ state.locationSearch = '';+ state.initImagePickerProps = null;+ state.loraPickerProps = null;+ state.resolutionFieldProps = null;state.peers = [];state.getImageGenStatus.mockReset().mockImplementation(defaultStatus);state.generateImage.mockReset().mockResolvedValue({ jobId: 'job-1' });@@ -167,7 +179,8 @@ vi.mock('../services/api', () => ({getImageGenStatus: (...args) => state.getImageGenStatus(...args),generateImage: (...args) => state.generateImage(...args),generateImageMultipart: vi.fn(async () => ({})),- listImageModels: vi.fn(async () => state.models),+ listImageModels: (...args) => state.listImageModels(...args),+ getGalleryImages: (...args) => state.getGalleryImages(...args),listLorasFull: (...args) => state.listLorasFull(...args),listImageGalleryPage: (...args) => state.listImageGalleryPage(...args),cancelImageGen: vi.fn(async () => ({})),@@ -235,6 +248,7 @@ vi.mock('../components/media/UniverseStylePicker', () => ({// the gallery card and preview) while every other suite keeps them null.vi.mock('../components/imageGen/InitImagePicker', () => ({default: (props) => {+ state.initImagePickerProps = props;const Factory = state.initImagePickerFactory;return Factory ? <Factory {...props} /> : null;},@@ -270,10 +284,20 @@ vi.mock('../components/media/MediaPreview', () => ({vi.mock('../components/Drawer', () => ({ default: () => null }));vi.mock('../components/settings/ImageGenTab', () => ({ ImageGenTab: () => null }));vi.mock('../components/imageGen/Flux2InstallModal', () => ({ default: () => null }));-vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));+vi.mock('../components/imageGen/LoraPicker', () => ({+ default: (props) => {+ state.loraPickerProps = props;+ return null;+ },+}));vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));-vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));+vi.mock('../components/media/ResolutionField', () => ({+ default: (props) => {+ state.resolutionFieldProps = props;+ return null;+ },+}));let ImageGen = null;@@ -295,9 +319,17 @@ export async function loadImageGenPage() {*/export async function renderImageGenPage(path = '/media/image', { strict = false } = {}) {if (!ImageGen) throw new Error('await loadImageGenPage() at module scope before rendering');+ function LocationProbe() {+ const location = useLocation();+ state.locationSearch = location.search;+ return null;+ }const tree = (<MemoryRouter initialEntries={[path]}>- <ImageGen />+ <>+ <LocationProbe />+ <ImageGen />+ </></MemoryRouter>);let view;