diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index 3b78b1c..5b304d2 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -585,6 +585,41 @@ test.describe('Mobile Swipe Viewer', () => { const historyLength = await page.evaluate(() => window.history.length); expect(historyLength).toBeLessThanOrEqual(2); }); + + test('a refresh whose stories all fail to load keeps the cached feed without paging through older days', async ({ page }) => { + // The list of top story ids loads, but every story read fails. + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ errorItemIds: mockTopItemIds })); + let dayRequests = 0; + await page.route(`${ALGOLIA_API}/search*`, async (route) => { + if (!route.request().url().includes('numericFilters')) return route.fallback(); + dayRequests += 1; + const base = 900_000 + dayRequests * 10; + await route.fulfill({ + json: { + hits: [0, 1, 2].map((i) => ({ + objectID: String(base + i), title: `Older story ${base + i}`, url: 'https://example.com/older', + author: 'someone', points: 1, num_comments: 0, created_at_i: Math.floor(Date.now() / 1000) - 86_400 * dayRequests, + _tags: ['story'], + })), + nbHits: 3, page: 0, nbPages: 1, hitsPerPage: 30, + }, + }); + }); + await page.addInitScript((ids) => { + const stories = ids.map((id) => ({ + id, type: 'story', title: `Cached story ${id}`, url: `https://example.com/${id}`, + points: 1, author: 'someone', createdAt: Date.now() - 3_600_000, commentCount: 0, + })); + localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 3_600_000 })); + }, mockTopItemIds); + + await page.goto('/#/'); + await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', String(mockTopItemIds[0])); + await page.waitForTimeout(3000); + + expect(dayRequests).toBe(0); + await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', String(mockTopItemIds[0])); + }); }); test.describe('Mobile Direct Item Access', () => { diff --git a/e2e/story-browsing.spec.ts b/e2e/story-browsing.spec.ts index 08c8dd0..c5984ee 100644 --- a/e2e/story-browsing.spec.ts +++ b/e2e/story-browsing.spec.ts @@ -1,8 +1,8 @@ import { expect } from '@playwright/test'; import { test as baseTest } from '@playwright/test'; import { test as fixtureTest } from './fixtures/test'; -import { setupApiMocks, setupApiMocksWithDelay } from './fixtures/api-mocks'; -import { ALGOLIA_API } from './fixtures/mock-data'; +import { setupApiMocks, setupApiMocksWithDelay, createFirebaseWsHandler, FIREBASE_WS_PATTERN } from './fixtures/api-mocks'; +import { ALGOLIA_API, mockTopItemIds } from './fixtures/mock-data'; const test = baseTest; @@ -192,6 +192,50 @@ test.describe('Item Browsing - Desktop Back between feeds', () => { }); }); +test.describe('Item Browsing - Desktop refresh', () => { + test.use({ viewport: { width: 1280, height: 720 } }); + + test('a refresh whose stories all fail to load keeps the cached feed without paging through older days', async ({ page }, testInfo) => { + if (testInfo.project.name.startsWith('Mobile')) { + test.skip(); + return; + } + await setupApiMocks(page); + // The list of top story ids loads, but every story read fails. + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ errorItemIds: mockTopItemIds })); + let dayRequests = 0; + await page.route(`${ALGOLIA_API}/search*`, async (route) => { + if (!route.request().url().includes('numericFilters')) return route.fallback(); + dayRequests += 1; + const base = 900_000 + dayRequests * 10; + await route.fulfill({ + json: { + hits: [0, 1, 2].map((i) => ({ + objectID: String(base + i), title: `Older story ${base + i}`, url: 'https://example.com/older', + author: 'someone', points: 1, num_comments: 0, created_at_i: Math.floor(Date.now() / 1000) - 86_400 * dayRequests, + _tags: ['story'], + })), + nbHits: 3, page: 0, nbPages: 1, hitsPerPage: 30, + }, + }); + }); + await page.addInitScript((ids) => { + const stories = ids.map((id) => ({ + id, type: 'story', title: `Cached story ${id}`, url: `https://example.com/${id}`, + points: 1, author: 'someone', createdAt: Date.now() - 3_600_000, commentCount: 0, + })); + localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 3_600_000 })); + }, mockTopItemIds); + + await page.goto('/#/'); + await expect(page.getByText(`Cached story ${mockTopItemIds[0]}`)).toBeVisible(); + await page.waitForTimeout(3000); + + expect(dayRequests).toBe(0); + await expect(page.locator('[data-testid="story-card"]')).toHaveCount(mockTopItemIds.length); + }); +}); + /** * Error handling tests use fixtureTest which provides errorMockedPage. * This fixture sets up routes on browserContext BEFORE page creation, diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts index e2923cb..6d33ff0 100644 --- a/src/hooks/useInfiniteStories.test.ts +++ b/src/hooks/useInfiniteStories.test.ts @@ -219,4 +219,36 @@ describe('useInfiniteStories', () => { expect(result.current.stories.map(s => s.id)).toEqual(getCachedFeed('top')!.stories.map(s => s.id)); }); }); + + describe('a refresh that comes back empty', () => { + it.each(['top', 'best', 'ask'])('fails the %s refresh and keeps the cached stories', async (type) => { + setCachedFeed(type, [5, 29, 3].map(id => createStoryItem({ id }))); + // Every item read fails, but the page request itself succeeds. + vi.mocked(hnSdk.readItem).mockRejectedValue(new Error('permission_denied')); + const { result } = renderHook(() => useInfiniteStories(type)); + + await act(() => expect(result.current.loadMore()).rejects.toThrow(/none came back/)); + + expect(result.current.error).toMatch(/none came back/); + expect(result.current.stories.map(s => s.id)).toEqual([5, 29, 3]); + }); + + it('asks for the front page again on the retry, not an older day', async () => { + setCachedFeed('top', [5, 29, 3].map(id => createStoryItem({ id }))); + let failReads = true; + vi.mocked(hnSdk.readItem).mockImplementation(async (id) => { + if (failReads) throw new Error('permission_denied'); + return makeFirebaseItem(Number(id)); + }); + const { result } = renderHook(() => useInfiniteStories('top')); + + await act(() => expect(result.current.loadMore()).rejects.toThrow(/none came back/)); + failReads = false; + await act(() => result.current.loadMore()); + + expect(result.current.error).toBeNull(); + expect(result.current.isFromCache).toBe(false); + expect(result.current.stories.map(s => s.id)).toEqual(rankedIds.slice(0, 20)); + }); + }); }); diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts index ecc8372..4a8c243 100644 --- a/src/hooks/useInfiniteStories.ts +++ b/src/hooks/useInfiniteStories.ts @@ -63,6 +63,14 @@ function getCachedState(type: FeedType): InitialState { }; } +// A page request succeeds even when every item read in it fails. A refresh +// that brings nothing back has still failed: as a success it would leave +// isFromCache set, and the callers that refresh eagerly would page through +// the whole feed. +function emptyRefreshError(type: FeedType): Error { + return new Error(`Failed to fetch ${type} stories: none came back`); +} + export function useInfiniteStories(type: FeedType = 'top') { const [initialState] = useState(() => getInitialState(type)); const [stories, setStories] = useState(initialState.stories); @@ -140,8 +148,9 @@ export function useInfiniteStories(type: FeedType = 'top') { const frontPage = await fetchTopStories(20); if (versionRef.current !== currentVersion) return; + if (isRevalidating && frontPage.length === 0) throw emptyRefreshError(type); - if (isRevalidating && frontPage.length > 0) { + if (isRevalidating) { kept = startRevalidation(); } @@ -201,9 +210,10 @@ export function useInfiniteStories(type: FeedType = 'top') { const result = await fetchFn(positionRef.current, 30); if (versionRef.current !== currentVersion) return; + if (isRevalidatingBest && result.stories.length === 0) throw emptyRefreshError(type); // As in the top branch. - const kept = isRevalidatingBest && result.stories.length > 0 ? startRevalidation() : null; + const kept = isRevalidatingBest ? startRevalidation() : null; const uniqueStories = result.stories.filter(story => { if (seenIdsRef.current.has(story.id)) { @@ -236,9 +246,10 @@ export function useInfiniteStories(type: FeedType = 'top') { const result = await fetchFn(positionRef.current); if (versionRef.current !== currentVersion) return; + if (isRevalidating && result.stories.length === 0) throw emptyRefreshError(type); // As in the top branch. - const kept = isRevalidating && result.stories.length > 0 ? startRevalidation() : null; + const kept = isRevalidating ? startRevalidation() : null; const uniqueStories = result.stories.filter(story => { if (seenIdsRef.current.has(story.id)) {