diff --git a/client/src/hooks/searchReturnState.test.ts b/client/src/hooks/searchReturnState.test.ts
new file mode 100644
index 0000000..9fc0a90
--- /dev/null
+++ b/client/src/hooks/searchReturnState.test.ts
@@ -0,0 +1,37 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ clearSearchReturnState,
+ readSearchReturnState,
+ saveSearchReturnState,
+} from './searchReturnState.js';
+
+beforeEach(() => window.sessionStorage.clear());
+afterEach(() => window.sessionStorage.clear());
+
+describe('search return state', () => {
+ it('restores the loaded result count and scroll only for the matching URL', () => {
+ const state = { url: '/project2/?q=the', visibleCount: 40, scrollY: 24739 };
+ saveSearchReturnState(state);
+
+ expect(readSearchReturnState(state.url)).toEqual(state);
+ expect(readSearchReturnState('/project2/?q=abbey')).toBeNull();
+ });
+
+ it('ignores malformed or unsafe state', () => {
+ window.sessionStorage.setItem('crate.search-return-state', '{broken');
+ expect(readSearchReturnState('/project2/')).toBeNull();
+
+ window.sessionStorage.setItem(
+ 'crate.search-return-state',
+ JSON.stringify({ url: '/project2/', visibleCount: -1, scrollY: -5 }),
+ );
+ expect(readSearchReturnState('/project2/')).toBeNull();
+ });
+
+ it('clears the saved state after it is restored', () => {
+ saveSearchReturnState({ url: '/project2/', visibleCount: 20, scrollY: 800 });
+ clearSearchReturnState();
+ expect(readSearchReturnState('/project2/')).toBeNull();
+ });
+});
diff --git a/client/src/hooks/searchReturnState.ts b/client/src/hooks/searchReturnState.ts
new file mode 100644
index 0000000..ab7b637
--- /dev/null
+++ b/client/src/hooks/searchReturnState.ts
@@ -0,0 +1,56 @@
+const STORAGE_KEY = 'crate.search-return-state';
+
+export interface SearchReturnState {
+ url: string;
+ visibleCount: number;
+ scrollY: number;
+}
+
+export function saveSearchReturnState(state: SearchReturnState): void {
+ try {
+ window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state));
+ } catch {
+ // Search navigation still works if session storage is unavailable.
+ }
+}
+
+export function readSearchReturnState(url: string): SearchReturnState | null {
+ try {
+ const stored = window.sessionStorage.getItem(STORAGE_KEY);
+ if (!stored) return null;
+
+ const state: unknown = JSON.parse(stored);
+ if (
+ typeof state !== 'object' ||
+ state === null ||
+ !('url' in state) ||
+ state.url !== url ||
+ !('visibleCount' in state) ||
+ typeof state.visibleCount !== 'number' ||
+ !Number.isInteger(state.visibleCount) ||
+ state.visibleCount < 1 ||
+ !('scrollY' in state) ||
+ typeof state.scrollY !== 'number' ||
+ !Number.isFinite(state.scrollY) ||
+ state.scrollY < 0
+ ) {
+ return null;
+ }
+
+ return {
+ url,
+ visibleCount: state.visibleCount,
+ scrollY: state.scrollY,
+ };
+ } catch {
+ return null;
+ }
+}
+
+export function clearSearchReturnState(): void {
+ try {
+ window.sessionStorage.removeItem(STORAGE_KEY);
+ } catch {
+ // Search navigation still works if session storage is unavailable.
+ }
+}
diff --git a/client/src/hooks/useAlbumSearch.test.tsx b/client/src/hooks/useAlbumSearch.test.tsx
new file mode 100644
index 0000000..1bc3f39
--- /dev/null
+++ b/client/src/hooks/useAlbumSearch.test.tsx
@@ -0,0 +1,88 @@
+import { MockedProvider } from '@apollo/client/testing/react';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { expect, it, vi } from 'vitest';
+
+import { cache } from '../api/client.js';
+import { SEARCH_ALBUMS, SEARCH_ALBUMS_PAGE } from '../api/searchAlbums.js';
+import { useAlbumSearch } from './useAlbumSearch.js';
+import { clearSearchReturnState, saveSearchReturnState } from './searchReturnState.js';
+
+const albums = Array.from({ length: 40 }, (_, index) => ({
+ __typename: 'Album' as const,
+ id: String(index + 1),
+ title: `Album ${index + 1}`,
+ releaseYear: 2000,
+ musicBrainzReleaseGroupId: null,
+ artists: [{ __typename: 'Artist' as const, id: 'artist-1', name: 'Test Artist' }],
+ genres: [],
+ averageRating: 0,
+ reviewCount: 0,
+ isInCrate: false,
+}));
+
+function albumPage(start: number, end: number, hasNextPage: boolean) {
+ const pageAlbums = albums.slice(start, end);
+ return {
+ data: {
+ searchAlbums: {
+ edges: pageAlbums.map((node) => ({ cursor: `cursor-${node.id}`, node })),
+ ...(start === 0
+ ? {
+ totalCount: albums.length,
+ genreFacets: [],
+ decadeFacets: [],
+ countryFacets: [],
+ reviewedCount: 0,
+ }
+ : {}),
+ pageInfo: {
+ hasNextPage,
+ endCursor: pageAlbums.at(-1) ? `cursor-${pageAlbums.at(-1)!.id}` : null,
+ },
+ },
+ },
+ };
+}
+
+it('reloads the previously visible pages before restoring scroll position', async () => {
+ const url = '/project2/?q=the';
+ const scrollTo = vi.fn();
+ window.scrollTo = scrollTo;
+ window.history.replaceState({}, '', url);
+ saveSearchReturnState({ url, visibleCount: 40, scrollY: 24739 });
+
+ const mocks = [
+ {
+ request: {
+ query: SEARCH_ALBUMS,
+ variables: { input: { query: 'the', sort: 'RELEVANCE' }, first: 20, after: null },
+ },
+ result: albumPage(0, 20, true),
+ },
+ {
+ request: {
+ query: SEARCH_ALBUMS_PAGE,
+ variables: {
+ input: { query: 'the', sort: 'RELEVANCE' },
+ first: 20,
+ after: 'cursor-20',
+ },
+ },
+ result: albumPage(20, 40, false),
+ },
+ ];
+ const wrapper = ({ children }: { children: ReactNode }) => (
+
+ {children}
+
+ );
+
+ const { result, unmount } = renderHook(() => useAlbumSearch(), { wrapper });
+ await waitFor(() => expect(result.current.albums).toHaveLength(40));
+ await waitFor(() => expect(scrollTo).toHaveBeenCalledWith(0, 24739));
+ expect(result.current.hasNextPage).toBe(false);
+
+ unmount();
+ act(() => clearSearchReturnState());
+});
diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts
index 3052c4d..35b0f77 100644
--- a/client/src/hooks/useAlbumSearch.ts
+++ b/client/src/hooks/useAlbumSearch.ts
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQuery } from '@apollo/client/react';
import { NetworkStatus } from '@apollo/client';
@@ -7,6 +7,11 @@ import {
SEARCH_ALBUMS_PAGE,
type AlbumSearchInput,
} from '../api/searchAlbums.js';
+import {
+ clearSearchReturnState,
+ readSearchReturnState,
+ saveSearchReturnState,
+} from './searchReturnState.js';
import { useSearchState } from './useSearchState.js';
const PAGE_SIZE = 20;
@@ -24,6 +29,10 @@ export function useAlbumSearch() {
clearFilters,
resetSearch,
} = useSearchState();
+ const [savedReturnState] = useState(() =>
+ readSearchReturnState(`${window.location.pathname}${window.location.search}`),
+ );
+ const returnState = useRef(savedReturnState);
const query = state.q;
const hasQuery = query.length > 0;
const retryInFlight = useRef(false);
@@ -192,6 +201,94 @@ export function useAlbumSearch() {
// Facets come from the last answer while the next one loads, so the filter
// panel does not collapse and lose keyboard focus on every click.
const facets = (data ?? previousData)?.searchAlbums;
+ const visibleAlbumCount = Math.min(pagination.visibleCount, edges.length);
+
+ useEffect(() => {
+ const basePath = import.meta.env.BASE_URL.replace(/\/$/, '');
+ const albumPathPrefix = `${basePath}/album/`;
+
+ function saveBeforeOpeningAlbum(event: MouseEvent) {
+ if (
+ event.defaultPrevented ||
+ event.button !== 0 ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.shiftKey ||
+ !(event.target instanceof Element)
+ ) {
+ return;
+ }
+
+ const link = event.target.closest('a[href]');
+ if (!link || link.hasAttribute('download')) return;
+ const target = link.getAttribute('target');
+ if (target && target !== '_self') return;
+
+ const destination = new URL(link.href, window.location.href);
+ if (
+ destination.origin !== window.location.origin ||
+ !destination.pathname.startsWith(albumPathPrefix)
+ ) {
+ return;
+ }
+
+ saveSearchReturnState({
+ url: `${window.location.pathname}${window.location.search}`,
+ visibleCount: visibleAlbumCount,
+ scrollY: Math.max(0, window.scrollY),
+ });
+ }
+
+ document.addEventListener('click', saveBeforeOpeningAlbum);
+ return () => document.removeEventListener('click', saveBeforeOpeningAlbum);
+ }, [visibleAlbumCount]);
+
+ useEffect(() => {
+ const saved = returnState.current;
+ if (
+ !saved ||
+ !data ||
+ loading ||
+ pagination.key !== key ||
+ pagination.loadingMore ||
+ pagination.pageError
+ ) {
+ return;
+ }
+
+ if (edges.length < saved.visibleCount && pageInfo?.hasNextPage) {
+ loadMore();
+ return;
+ }
+
+ const restoredCount = Math.min(saved.visibleCount, edges.length);
+ returnState.current = null;
+ clearSearchReturnState();
+ setPagination((current) =>
+ current.key === key
+ ? {
+ ...current,
+ visibleCount: restoredCount,
+ automaticPages: Math.min(
+ AUTOMATIC_PAGE_LIMIT,
+ Math.max(0, Math.ceil(restoredCount / PAGE_SIZE) - 1),
+ ),
+ }
+ : current,
+ );
+ window.requestAnimationFrame(() => window.scrollTo(0, saved.scrollY));
+ }, [
+ data,
+ loading,
+ pagination.key,
+ pagination.loadingMore,
+ pagination.pageError,
+ key,
+ edges.length,
+ pageInfo?.hasNextPage,
+ loadMore,
+ ]);
return {
query,
diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md
index e95c2c6..93db65c 100644
--- a/docs/AI-USAGE.md
+++ b/docs/AI-USAGE.md
@@ -112,6 +112,7 @@ the part that matters most.
| 2026-11-22 | erikhfj | Antigravity | #117, stabilized `ReviewForm.test.tsx`: traced the intermittent CI failure (run `88055`) to `findByRole('status')` resolving via `MutationObserver` before React's passive `useEffect` focused `statusRef`, and wrapped the status focus assertions in `waitFor`. Verified with 10 consecutive test runs plus `pnpm format:check && pnpm lint && pnpm typecheck && pnpm test`. |
| 2026-11-22 | erikhfj | Antigravity | #107, documented the team's AI task delegation, verification, and review workflow in `docs/AI-USAGE.md`, reflecting actual practices across all four contributors and complementing #97's prompt-context section. Verified with `pnpm format:check && pnpm lint && pnpm typecheck && pnpm test`. |
| 2026-11-23 | robertky | Codex (ChatGPT) | #94: Added an accessible character count for review comments, linked it to the textarea without live announcements on every keystroke, and added component tests. Verified with `pnpm format:check`, `pnpm lint`, `pnpm typecheck`, `pnpm test`, and `pnpm build`. |
+| 2026-11-23 | robertky | Codex (ChatGPT) | #121: Preserved the visible search page count and scroll position when opening an album, then restored the saved result pages on return. Added state and pagination regression tests. |
| 2026-11-23 | robertky | Codex (ChatGPT) | #104 review follow-up: combined the side drawer with the merged country preview, added backdrop dismissal and a keyboard focus loop, corrected the results-status test matcher and component documentation, and expanded the Playwright filter journey. Verified with `pnpm format:check`, `pnpm lint`, `pnpm typecheck`, `pnpm test`, `pnpm build`, and `pnpm test:e2e` against an isolated seeded PostgreSQL database. |
## Task delegation and verification workflow
diff --git a/e2e/tests/search.spec.ts b/e2e/tests/search.spec.ts
index d14152e..93600c6 100644
--- a/e2e/tests/search.spec.ts
+++ b/e2e/tests/search.spec.ts
@@ -132,6 +132,30 @@ test('search is case-insensitive', async ({ page }) => {
await expect(resultTitles(page)).toHaveText(upper);
});
+test('browser back restores the previous search and scroll position', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 390, height: 400 });
+ await page.goto('./');
+ await search(page, 'beatles');
+ await expect(
+ page.getByRole('status').filter({ hasText: 'Showing 2 of 2' }),
+ ).toBeVisible();
+
+ const results = page.getByRole('region', { name: 'Search results' });
+ const lastResult = results.getByRole('link').last();
+ await lastResult.scrollIntoViewIfNeeded();
+ const savedScrollY = await page.evaluate(() => window.scrollY);
+ const albumTitle = (await lastResult.innerText()).trim();
+ await lastResult.click();
+ await expect(page.getByRole('heading', { level: 1, name: albumTitle })).toBeVisible();
+
+ await page.goBack();
+ await expect(page).toHaveURL(/[?&]q=beatles/);
+ await expect(results.getByRole('link')).toHaveCount(2);
+ await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(savedScrollY);
+});
+
test('keyboard only: skip link, search and open a result', async ({ page }) => {
await page.goto('./');