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: preserve gallery browsing during background refreshes (#7040)
[._.]/ Adam Eivydab63d87959b
diff --git a/client/src/hooks/useRecentImageGallery.js b/client/src/hooks/useRecentImageGallery.jsindex 30e1ecf192..2bd0341967 100644--- a/client/src/hooks/useRecentImageGallery.js+++ b/client/src/hooks/useRecentImageGallery.js@@ -4,7 +4,7 @@ import { listImageGalleryPage } from '../services/api';const HIDDEN_PAGE_SIZE = 60;/** Recent-five gallery, lazy hidden pages, and a bounded deep-link lookup. */-export function useRecentImageGallery({ favoritesOnly, showHidden, previewParam, annotationRevision = '' }) {+export function useRecentImageGallery({ favoritesOnly, showHidden, previewParam, annotationRevision = '', annotationPending = false }) {const [gallery, setGallery] = useState([]);const [total, setTotal] = useState(0);const [hiddenTotal, setHiddenTotal] = useState(0);@@ -14,13 +14,18 @@ export function useRecentImageGallery({ favoritesOnly, showHidden, previewParam,const [error, setError] = useState(false);const [hiddenError, setHiddenError] = useState(false);const [revision, setRevision] = useState(0);+ const [hiddenRevision, setHiddenRevision] = useState(0);+ const waitingForAnnotations = favoritesOnly && annotationPending;+ const refreshRecent = useCallback(() => setRevision(n => n + 1), []);const [previewImage, setPreviewImage] = useState(null);const refreshGallery = useCallback(() => {setHiddenOffset(0);+ setHiddenRevision(n => n + 1);setRevision(n => n + 1);}, []);useEffect(() => {+ if (waitingForAnnotations) return;let cancelled = false;setError(false);listImageGalleryPage({ limit: 5, hidden: false, starred: favoritesOnly, summary: true }, { silent: true })@@ -32,7 +37,7 @@ export function useRecentImageGallery({ favoritesOnly, showHidden, previewParam,}).catch(() => { if (!cancelled) setError(true); });return () => { cancelled = true; };- }, [favoritesOnly, revision, annotationRevision]);+ }, [favoritesOnly, revision, annotationRevision, waitingForAnnotations]);// Scope changes start hidden browsing at the beginning; keep the offset tied// to that scope rather than issuing a stale offset before an effect resets it.@@ -51,6 +56,7 @@ export function useRecentImageGallery({ favoritesOnly, showHidden, previewParam,setHiddenLoading(false);return;}+ if (waitingForAnnotations) return;if (hiddenOffset === 0) {setGallery(previous => previous.filter(item => !item.hidden));setNextHiddenOffset(null);@@ -74,24 +80,25 @@ export function useRecentImageGallery({ favoritesOnly, showHidden, previewParam,.catch(() => { if (!cancelled) setHiddenError(true); }).finally(() => { if (!cancelled) setHiddenLoading(false); });return () => { cancelled = true; };- }, [showHidden, favoritesOnly, hiddenOffset, revision, annotationRevision]);+ }, [showHidden, favoritesOnly, hiddenOffset, hiddenRevision, annotationRevision, waitingForAnnotations]);+ const filename = previewParam?.startsWith('image:') ? previewParam.slice(6) : previewParam;+ const cachedPreview = gallery.find(item => item.filename === filename);useEffect(() => {setPreviewImage(null);- if (!previewParam) return;+ if (!filename || cachedPreview) return;let cancelled = false;- const filename = previewParam.startsWith('image:') ? previewParam.slice(6) : previewParam;listImageGalleryPage({ limit: 1, filename }, { silent: true }).then(page => { if (!cancelled) setPreviewImage(page.items[0] || null); }).catch(() => {});return () => { cancelled = true; };- }, [previewParam, revision]);+ }, [filename, cachedPreview, revision]);const loadMoreHidden = () => {if (!hiddenLoading && nextHiddenOffset !== null) setHiddenOffset(nextHiddenOffset);};return {- gallery, setGallery, total, hiddenTotal, refreshGallery, previewImage,+ gallery, setGallery, total, hiddenTotal, refreshGallery, refreshRecent, previewImage: cachedPreview || previewImage,hiddenLoading, hiddenError, error, loadMoreHidden, hasMoreHidden: nextHiddenOffset !== null,};}diff --git a/client/src/hooks/useRecentImageGallery.test.jsx b/client/src/hooks/useRecentImageGallery.test.jsxindex ee50818336..0dc3f150f5 100644--- a/client/src/hooks/useRecentImageGallery.test.jsx+++ b/client/src/hooks/useRecentImageGallery.test.jsx@@ -32,9 +32,21 @@ describe('recent gallery request lifecycle', () => {expect(listImageGalleryPage).toHaveBeenLastCalledWith({ limit: 60, offset: 60, hidden: true, starred: false }, { silent: true });expect(result.current.hasMoreHidden).toBe(false);+ const beforeCompletion = listImageGalleryPage.mock.calls.length;+ act(() => result.current.refreshRecent());+ await waitFor(() => expect(listImageGalleryPage).toHaveBeenCalledTimes(beforeCompletion + 1));+ expect(result.current.gallery).toHaveLength(67);+ expect(listImageGalleryPage).toHaveBeenLastCalledWith(+ { limit: 5, hidden: false, starred: false, summary: true }, { silent: true });act(() => result.current.refreshGallery());await waitFor(() => expect(result.current.gallery).toHaveLength(65));expect(listImageGalleryPage.mock.calls.every(([params]) => params.limit <= 60)).toBe(true);+ rerender(initial);+ await waitFor(() => expect(result.current.gallery).toHaveLength(5));+ const beforePreview = listImageGalleryPage.mock.calls.length;+ rerender({ ...initial, previewParam: 'image:v0.png' });+ expect(result.current.previewImage?.filename).toBe('v0.png');+ expect(listImageGalleryPage).toHaveBeenCalledTimes(beforePreview);});it('rejects stale filter responses, retries failed requests and resolves an older preview without downloading the gallery', async () => {@@ -58,4 +70,34 @@ describe('recent gallery request lifecycle', () => {await waitFor(() => expect(result.current.previewImage?.filename).toBe('old-hidden.png'));expect(listImageGalleryPage).toHaveBeenLastCalledWith({ limit: 1, filename: 'old-hidden.png' }, { silent: true });});++ it('retries hidden errors, deduplicates overlapping pages, and restarts the scope only after favorite saves settle', async () => {+ const first = images('hidden', 60, true);+ listImageGalleryPage.mockImplementation(async ({ limit, offset = 0, hidden, starred }) => ({+ items: !hidden ? images('visible', 5) : starred ? images('favorite', 1, true)+ : offset ? [first[59], { filename: 'last.png', hidden: true }] : first,+ total: hidden ? (starred ? 1 : 62) : 2000, hiddenTotal: 62, limit, offset,+ }));+ const { result, rerender } = renderHook(props => useRecentImageGallery(props), { initialProps: { ...initial, showHidden: true } });+ await waitFor(() => expect(result.current.gallery).toHaveLength(65));+ listImageGalleryPage.mockRejectedValueOnce(new Error('offline'));+ act(() => result.current.loadMoreHidden());+ await waitFor(() => expect(result.current.hiddenError).toBe(true));+ act(() => result.current.refreshGallery());+ await waitFor(() => expect(result.current.hiddenLoading).toBe(false));+ expect(result.current.hiddenError).toBe(false);+ act(() => result.current.loadMoreHidden());+ await waitFor(() => expect(result.current.gallery).toHaveLength(66));+ expect(result.current.gallery.filter(item => item.filename === first[59].filename)).toHaveLength(1);+ const beforeSave = listImageGalleryPage.mock.calls.length;+ rerender({ ...initial, showHidden: true, favoritesOnly: true, annotationRevision: 'image:favorite0.png', annotationPending: true });+ expect(listImageGalleryPage).toHaveBeenCalledTimes(beforeSave);+ rerender({ ...initial, showHidden: true, favoritesOnly: true, annotationRevision: 'image:favorite0.png', annotationPending: false });+ await waitFor(() => expect(result.current.gallery).toHaveLength(6));+ expect(listImageGalleryPage).toHaveBeenCalledTimes(beforeSave + 2);+ expect(listImageGalleryPage).toHaveBeenLastCalledWith(+ { limit: 60, offset: 0, hidden: true, starred: true }, { silent: true });+ expect(result.current.hasMoreHidden).toBe(false);+ });+});diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 8d417533ef..6be1c4c8d5 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -139,23 +139,29 @@ export default function ImageGen() {const [showHidden, setShowHidden] = useState(false);const [favoritesOnly, setFavoritesOnly] = useState(false);const { annotations, updateAnnotation: saveAnnotation, getCardProps } = useMediaAnnotations();+ const [annotationSaves, setAnnotationSaves] = useState(0);+ const annotationsRef = useRef(annotations);+ annotationsRef.current = annotations;const annotationRevision = useMemo(() => favoritesOnly? Object.keys(annotations).filter(key => annotations[key]?.starred).sort().join('\n') : '',[annotations, favoritesOnly]);const {- gallery, setGallery, total: galleryTotal, hiddenTotal, refreshGallery, previewImage,+ gallery, setGallery, total: galleryTotal, hiddenTotal, refreshGallery, refreshRecent, previewImage,hiddenLoading, hiddenError, error: galleryError, loadMoreHidden, hasMoreHidden,} = useRecentImageGallery({- favoritesOnly, showHidden, previewParam: searchParams.get('preview'), annotationRevision,+ favoritesOnly, showHidden, previewParam: searchParams.get('preview'), annotationRevision, annotationPending: annotationSaves > 0,});const updateAnnotation = useCallback(async (...args) => {- const result = await saveAnnotation(...args);- if (favoritesOnly) refreshGallery();- return result;+ setAnnotationSaves(count => count + 1);+ return saveAnnotation(...args).finally(() => {+ setAnnotationSaves(count => count - 1);+ if (favoritesOnly) refreshGallery();+ });}, [saveAnnotation, refreshGallery, favoritesOnly]);const toggleGalleryStar = useCallback(item => {- updateAnnotation(item.key, { starred: !annotations[item.key]?.starred });- }, [annotations, updateAnnotation]);+ if (!item?.key) return;+ updateAnnotation(item.key, { starred: !annotationsRef.current[item.key]?.starred });+ }, [updateAnnotation]);// FLUX.2 readiness — drives the gating banner. Lazy-fetched on the first// selection of a flux2 model so we don't make an extra request when the// user is only using mflux/external/codex.@@ -348,7 +354,7 @@ export default function ImageGen() {});}, []);- useMediaCompletionRefresh({ onImageCompleted: refreshGallery });+ useMediaCompletionRefresh({ onImageCompleted: refreshRecent });// SynthID-defeat regen (issue #912) is hardware-gated on a local FLUX// runner — only surface the lightbox action when the backend is installed.@@ -876,12 +882,12 @@ export default function ImageGen() {// Only refresh gallery on a busy-count drop — that's the signal a// queued job just completed. Otherwise polling re-fetches the gallery// every 4s for nothing.- if (stillBusy < lastBusyRef.current) refreshGallery();+ if (stillBusy < lastBusyRef.current) refreshRecent();lastBusyRef.current = stillBusy;// No-op guard: same value setState would still trigger a render, so// explicitly skip when nothing changed.setPendingQueued((prev) => (prev === next ? prev : next));- }, [generating, refreshGallery]);+ }, [generating, refreshRecent]);useAutoRefetch(pollQueue, 4000, { enabled: queueActive, pollOnly: true });// The HF-gated-repo "token" issue only applies to actual FLUX.2 models —@@ -1028,7 +1034,7 @@ export default function ImageGen() {// Queue N renders without taking over the active SSE/preview. Used when the// user submits while one is already rendering — they get to keep watching// the in-flight render, and the new payloads land in mediaJobQueue (server- // FIFO). When the active render finishes, refreshGallery() pulls all+ // FIFO). When the active render finishes, refreshRecent() pulls the newest// completed images so the queued ones become visible as they land.// Async-mode only; external is synchronous so submitting N would block N×.const queueAdditional = async (count = 1) => {@@ -1109,7 +1115,7 @@ export default function ImageGen() {setResult({ ...data, prompt: payload.prompt, negativePrompt: payload.negativePrompt, width: clampedW, height: clampedH, steps: payload.steps, cfgScale });}toast.success('Image generated');- refreshGallery();+ refreshRecent();} catch (err) {setError(err.message || 'Image generation failed');// Typed kind from a USER_ERROR: line lets the UI render guidance@@ -1761,7 +1767,7 @@ export default function ImageGen() {</div></div>{visibleGallery.length === 0 ? (- <div className="text-xs text-gray-500 py-3">No favorited images yet.</div>+ <div className="text-xs text-gray-500 py-3">{favoritesOnly ? 'No favorited images yet.' : 'No recent images.'}</div>) : (<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">{visibleGalleryItems.slice(0, 5).map((item) => (diff --git a/client/src/pages/ImageGen.probeGating.test.jsx b/client/src/pages/ImageGen.probeGating.test.jsxindex 6d699880f0..2583b2bdc6 100644--- a/client/src/pages/ImageGen.probeGating.test.jsx+++ b/client/src/pages/ImageGen.probeGating.test.jsx@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router';-import { listImageGalleryPage } from '../services/api';+import { listImageGalleryPage, deleteImage } from '../services/api';const MODEL = { id: 'dev', name: 'FLUX.1 Dev', runner: 'mflux', steps: 20, guidance: 3.5 };@@ -73,7 +73,6 @@ vi.mock('../hooks/useMediaAnnotations', () => ({useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),}));vi.mock('../hooks/useAutoRefetch', () => ({ useAutoRefetch: vi.fn() }));-vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));vi.mock('../components/ui/Toast', () => ({default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),}));@@ -82,9 +81,14 @@ vi.mock('../components/media/PromptFromMedia', () => ({ default: () => <button tvi.mock('../components/media/UniverseStylePicker', () => ({ default: () => null }));vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));vi.mock('../components/media/MediaCard', () => ({- default: ({ item, onToggleHidden }) => <button type="button" onClick={() => onToggleHidden(item)}>{item.filename}</button>,+ default: ({ item, onToggleHidden, onDelete }) => <div>+ <button type="button" onClick={() => onToggleHidden(item)}>{item.filename}</button>+ <button type="button" aria-label={`Delete ${item.filename}`} onClick={() => onDelete(item)}>Delete</button>+ </div>,+}));+vi.mock('../components/media/MediaPreview', () => ({+ default: ({ preview }) => preview ? <div role="dialog" aria-label={`Preview ${preview.filename}`} /> : 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 }));@@ -97,10 +101,10 @@ vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));const { default: ImageGen } = await import('./ImageGen.jsx');-const mount = async () => {+const mount = async (path = '/media/image') => {await act(async () => {render(- <MemoryRouter initialEntries={['/media/image']}>+ <MemoryRouter initialEntries={[path]}><ImageGen /></MemoryRouter>,);@@ -109,6 +113,7 @@ const mount = async () => {describe('ImageGen backend-probe gating', () => {beforeEach(() => {+ deleteImage.mockReset().mockResolvedValue({});listImageGalleryPage.mockReset().mockResolvedValue({ items: [], total: 0, hiddenTotal: 0 });state.generateImage.mockReset().mockResolvedValue({ jobId: 'job-1' });state.statusPromise = new Promise((resolve) => { state.resolveStatus = resolve; });@@ -137,6 +142,20 @@ describe('ImageGen backend-probe gating', () => {{ limit: 5, hidden: false, starred: true, summary: true }, { silent: true });});+ it('opens an older hidden deep link independently of the recent strip and retains a card when deletion fails', async () => {+ listImageGalleryPage.mockImplementation(async ({ filename }) => filename+ ? { items: [{ filename, hidden: true }], total: 1 }+ : { items: [{ filename: 'recent.png' }], total: 1, hiddenTotal: 1 });+ await mount('/media/image?preview=image:older.png');+ expect(await screen.findByRole('dialog', { name: 'Preview older.png' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Show hidden/ })).toBeInTheDocument();+ expect(listImageGalleryPage).toHaveBeenCalledWith({ limit: 1, filename: 'older.png' }, { silent: true });+ deleteImage.mockRejectedValueOnce(new Error('cannot delete'));+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Delete recent.png' })));+ expect(screen.getByRole('button', { name: 'recent.png' })).toBeInTheDocument();+ expect(screen.getByText('Recent renders (1 of 1)')).toBeInTheDocument();+ });+// The probe decides which backend can RUN, not what the user may TYPE. While// it is in flight the whole above-the-fold form must stay usable.it('leaves the prompt fields editable while the status probe is still in flight', async () => {diff --git a/docs/IMAGE_GALLERY.md b/docs/IMAGE_GALLERY.mdindex e21cfecf29..9f914a7d65 100644--- a/docs/IMAGE_GALLERY.md+++ b/docs/IMAGE_GALLERY.md@@ -31,7 +31,12 @@ The LoRA import dialog and Image Gen use this page contract. Image Gen requestshidden matches of the same search/favorite scope independently of the page's`hidden` filter. Expanding hidden images loads 60 at a time. `starred=true`filters against the local author's stars before LIMIT (a peer's star alone does-not qualify). `filename=<exact filename>&limit=1` resolves an older deep-linked+not qualify). Favorites consult the authoritative annotation map; that metadata+read remains proportional to the number of annotations, while image rows and+payloads stay bounded. Background render completions refresh only the recent+window and totals, preserving loaded hidden pages. Explicit gallery mutations+and retries restart hidden paging because they can shift offsets.+`filename=<exact filename>&limit=1` resolves an older deep-linkedpreview without fetching intervening pages.Media History and the other legacy consumers have not yet migrated. Their global scopes, favorites,