fix(stock): stale searches can't overwrite newer results; scope 404

- A cache-hit search aborts any older in-flight stock_search and clears
  loading; StockPhotoTab only applies the newest request's result
- A bare 404 means 'stock unavailable' only for the stock_search probe;
  on stock_import it is an ordinary error (an explicit invalid/unknown
  action error still disables the tab)

Refs #55

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Opus 5.5 committed 2026-10-07 12:48:18 -07:00
1 parent 4bae531339
commit 822d43cf61
4 files changed
+85 -7

No files matched your search

+35
View File
@@ -89,6 +89,41 @@ describe('useStockPhotos.search', () => {
});
});
describe('useStockPhotos: stale responses and 404 scope (#55 review)', () => {
test('a cache-hit search aborts an older in-flight request and clears loading', async () => {
fetchMock.mockReturnValueOnce(json({ success: true, results: [PHOTO], next_page: null }));
await act(async () => { await api.search('two'); });
const signals: AbortSignal[] = [];
fetchMock.mockImplementation((_u: string, init: any) => {
signals.push(init.signal);
return new Promise(() => { /* never resolves */ });
});
act(() => { void api.search('one'); });
expect(api.loading).toBe(true);
let hit: any;
await act(async () => { hit = await api.search('two'); });
expect(hit.results).toEqual([PHOTO]);
expect(signals).toHaveLength(1);
expect(signals[0].aborted).toBe(true);
expect(api.loading).toBe(false);
});
test('a 404 on stock_import is an ordinary error, not "stock unavailable"', async () => {
fetchMock.mockReturnValue(json({ success: false, error: 'Photo not found' }, 404));
let res: any = 'x';
await act(async () => { res = await api.importPhoto(999); });
expect(res).toBeNull();
expect(api.availability).toBe('unknown');
expect(api.error).toBe('Photo not found');
});
test('an explicit invalid-action error on stock_import still disables the tab', async () => {
fetchMock.mockReturnValue(json({ success: false, error: 'Invalid action. Supported: get_sites, list' }, 400));
await act(async () => { await api.importPhoto(7); });
expect(api.availability).toBe('disabled');
});
});
describe('useStockPhotos.importPhoto', () => {
test('POSTs provider/id/size with the CSRF header and resolves the asset url', async () => {
fetchMock.mockReturnValue(json({ success: true, url: '/api/assets-proxy/?site_id=5&filename=fox.jpg', name: 'fox.jpg', type: 'image/jpeg', credit: PHOTO.credit }));
+15 -6
View File
@@ -55,9 +55,12 @@ function getCfg(): { apiUrl: string; siteId: number; csrfToken: string } | null
}
/** The backend answers `stock_disabled` with no key; an old backend without
* the action answers 404 or an "unknown action" error -- both hide the tab. */
function isDisabledSignal(status: number, data: any): boolean {
if (status === 404) return true;
* the action answers an "unknown/invalid action" error -- both hide the tab.
* A bare 404 only counts for the `stock_search` availability probe
* (`probe`): on stock_import a 404 is an ordinary failure (e.g. a photo id
* that no longer exists) and must not hide the tab. */
function isDisabledSignal(status: number, data: any, probe: boolean): boolean {
if (probe && status === 404) return true;
const err = String(data?.error || '');
return err === 'stock_disabled' || /unknown action|invalid action/i.test(err);
}
@@ -85,7 +88,13 @@ export function useStockPhotos() {
if (!cfg || !query) return null;
const key = `${query}\u0000${page}`;
const hit = cache.current.get(key);
if (hit) { setError(null); return hit; }
if (hit) {
// A cache hit is the newest request: drop any older in-flight search so
// its (stale) response can never land after this one.
if (abortRef.current) { abortRef.current.abort(); abortRef.current = null; setLoading(false); }
setError(null);
return hit;
}
abortRef.current?.abort();
const ctrl = new AbortController();
@@ -97,7 +106,7 @@ export function useStockPhotos() {
const resp = await fetch(url, { headers: { 'X-CSRF-Token': cfg.csrfToken }, signal: ctrl.signal });
let data: any = null;
try { data = await resp.json(); } catch { /* non-JSON body */ }
if (isDisabledSignal(resp.status, data)) { setSharedAvailability('disabled'); return null; }
if (isDisabledSignal(resp.status, data, true)) { setSharedAvailability('disabled'); return null; }
if (!resp.ok || !data?.success || !Array.isArray(data.results)) {
throw new Error(data?.error || `Search failed: ${resp.status}`);
}
@@ -130,7 +139,7 @@ export function useStockPhotos() {
});
let data: any = null;
try { data = await resp.json(); } catch { /* non-JSON body */ }
if (isDisabledSignal(resp.status, data)) { setSharedAvailability('disabled'); return null; }
if (isDisabledSignal(resp.status, data, false)) { setSharedAvailability('disabled'); return null; }
if (!resp.ok || !data?.success || !data.url) throw new Error(data?.error || `Import failed: ${resp.status}`);
return { url: data.url, name: data.name || '', type: data.type || 'image', credit: data.credit };
} catch (e) {
+27
View File
@@ -101,3 +101,30 @@ describe('StockPhotoTab', () => {
expect(q('stock-error')!.textContent).toBe('download failed');
});
});
describe('StockPhotoTab: stale responses (#55 review)', () => {
test('an older search resolving after a newer cache-hit search does not replace or clear the grid', async () => {
mount();
// "fox" -> cached.
await searchAndSelect();
expect(q('stock-thumb-7')).not.toBeNull();
// "cat" stays in flight; resolves (or rejects on abort) only when we say so.
let release!: () => void;
fetchMock.mockImplementationOnce((_u: string, init: any) => new Promise((resolve, reject) => {
init.signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')));
release = () => resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, results: [{ ...PHOTO, id: 99, alt: 'cat' }], next_page: null }) } as Response);
}));
setValueIn('stock-search-input', 'cat');
const form = container.querySelector('form')!;
await act(async () => { form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); });
// Back to "fox" while "cat" is pending: a cache hit (form submit bypasses the disabled button).
setValueIn('stock-search-input', 'fox');
await act(async () => { form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); });
await flush();
release?.();
await flush();
expect(q('stock-thumb-7')).not.toBeNull();
expect(q('stock-thumb-99')).toBeNull();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
+8 -1
View File
@@ -1,4 +1,4 @@
import React, { useState, useCallback } from 'react';
import React, { useState, useCallback, useRef } from 'react';
import { useStockPhotos, StockPhoto, StockCredit } from '../hooks/useStockPhotos';
export interface PickedAsset {
@@ -25,20 +25,27 @@ export const StockPhotoTab: React.FC<Props> = ({ onPick }) => {
const [selected, setSelected] = useState<StockPhoto | null>(null);
const [importing, setImporting] = useState(false);
const [searched, setSearched] = useState(false);
// Only the newest request may update the grid: an older (aborted or slow)
// one resolving late must not clear or replace newer results.
const seq = useRef(0);
const runSearch = useCallback(async () => {
const q = query.trim();
if (!q) return;
const mine = ++seq.current;
setSubmitted(q);
setSelected(null);
const res = await search(q, 1);
if (mine !== seq.current) return;
if (res) { setPhotos(res.results); setNextPage(res.nextPage); setSearched(true); }
else setPhotos([]);
}, [query, search]);
const loadMore = useCallback(async () => {
if (nextPage == null) return;
const mine = ++seq.current;
const res = await search(submitted, nextPage);
if (mine !== seq.current) return;
if (res) { setPhotos((p) => [...p, ...res.results]); setNextPage(res.nextPage); }
}, [nextPage, search, submitted]);