Skip to content

Open-source Xbox-inspired desktop launcher for Xodus on Linux

TypeScript

fix(store): continue public catalog pages without cursor loops

Nexus Maintainer4022cfcf1a7d
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 17e2fe0..54e1fe0 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -345,6 +345,7 @@
"store.available_with": "Available with {{plan}}",
"store.id": "Store ID {{id}}",
"store.package_id": "Package ID {{id}}",
+ "store.no_more_pages": "The Store did not return any more games.",
"store.us_price_context": "Public Store prices come from the US Store and are shown in USD. Checkout price and local availability can differ.",
"store.us_price_short": "US Store, USD",
"store.verified_msixvc": "PC MSIXVC verified",
diff --git a/src/main/catalog.test.ts b/src/main/catalog.test.ts
index 565b689..ea394c3 100644
--- a/src/main/catalog.test.ts
+++ b/src/main/catalog.test.ts
@@ -352,6 +352,148 @@ describe('Public Store landing collections', () => {
const result = await new CatalogService(landingFetcher(collections, details, [])).featured('US');
expect(result.products.map(product => product.title)).toEqual(['Paid With Demo']);
});
+
+ const browsePages = (pages: number, extra: (index: number) => Record<string, unknown>[] = () => []) => {
+ const collections: Record<string, unknown[]> = { TopPaid: [] };
+ for (let index = 1; index <= pages; index += 1) {
+ collections.TopPaid.push({
+ title: 'Top paid games',
+ hasMorePages: index < pages,
+ nextPageNumber: index < pages ? index + 1 : -1,
+ productsList: [row(`9BROWSE00${index}`, `Browse ${index}`, 9.99 + index), ...extra(index)],
+ });
+ }
+ return collections;
+ };
+ const browseDetails = (pages: number, extra: string[] = []) => Object.fromEntries([
+ ...Array.from({ length: pages }, (_, index) => [`9BROWSE00${index + 1}`, game(`9BROWSE00${index + 1}`, [paidSku(9.99 + index + 1)])]),
+ ...extra.map(id => [id, game(id, [paidSku(19.99)])]),
+ ]);
+
+ it('continues from the exact page the featured read did not cover', async () => {
+ const requests: string[] = [];
+ const service = new CatalogService(landingFetcher(browsePages(6), browseDetails(6), requests));
+ const featured = await service.featured('US');
+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:1', 'TopPaid:2', 'TopPaid:3']);
+ expect(featured.hasMore).toBe(true);
+ expect(featured.cursor).toBe('paid-4');
+ const first = await service.browse('US', featured.cursor);
+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:1', 'TopPaid:2', 'TopPaid:3', 'TopPaid:4']);
+ expect(first.products.map(product => product.title)).toEqual(['Browse 4']);
+ expect(first.hasMore).toBe(true);
+ expect(first.cursor).toBe('paid-5');
+ const second = await service.browse('US', first.cursor);
+ expect(second.products.map(product => product.title)).toEqual(['Browse 5']);
+ expect(second.cursor).toBe('paid-6');
+ const third = await service.browse('US', second.cursor);
+ expect(third.hasMore).toBe(false);
+ expect(third.cursor).toBeUndefined();
+ });
+
+ it('offers no continuation when the paid feed ended inside the featured budget', async () => {
+ const requests: string[] = [];
+ const featured = await new CatalogService(landingFetcher(browsePages(2), browseDetails(2), requests)).featured('US');
+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:1', 'TopPaid:2']);
+ expect(featured.products.map(product => product.title)).toEqual(['Browse 1', 'Browse 2']);
+ expect(featured.hasMore).toBe(false);
+ expect(featured.cursor).toBeUndefined();
+ });
+
+ it('restarts the paid feed from its first page when the featured paid read failed', async () => {
+ const requests: string[] = [];
+ const collections = { ...browsePages(6), TopTrending: [{ title: 'Trending games', hasMorePages: false, productsList: [row('9TRENDING01', 'Trending Paid', 9.99)] }] };
+ const details = { ...browseDetails(6), '9TRENDING01': game('9TRENDING01', [paidSku(9.99)]) }, state = { failPage2: true };
+ const fetcher = (async (input: URL | RequestInfo) => {
+ const url = new URL(String(input));
+ if (url.pathname.includes('GetComputedProductsList')) {
+ const name = url.searchParams.get('listName') ?? '', page = Number(url.searchParams.get('pgNo') ?? '1');
+ requests.push(`${name}:${page}`);
+ if (name === 'TopPaid' && page === 2 && state.failPage2) return new Response('{}', { status: 503 });
+ const payload = collections[name]?.[page - 1];
+ return payload ? new Response(JSON.stringify(payload), { status: 200 }) : new Response('{}', { status: 404 });
+ }
+ if (url.pathname.includes('/v7.0/products')) {
+ const ids = (url.searchParams.get('bigIds') ?? '').split(',').map(id => id.toUpperCase());
+ return new Response(JSON.stringify({ Products: ids.flatMap(id => details[id] ? [details[id]] : []) }), { status: 200 });
+ }
+ return new Response('{}', { status: 404 });
+ }) as typeof fetch;
+ const service = new CatalogService(fetcher);
+ const featured = await service.featured('US');
+ // A failed paid read contributes nothing; its items are recovered from page 1.
+ expect(featured.products.map(product => product.title)).toEqual(['Trending Paid']);
+ expect(featured.hasMore).toBe(true);
+ expect(featured.cursor).toBe('paid-1');
+ // Recovery reads the skipped first page again instead of assuming it exists.
+ const recovered = await service.browse('US', featured.cursor);
+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:1', 'TopPaid:2', 'TopPaid:1']);
+ expect(recovered.products.map(product => product.title)).toEqual(['Browse 1']);
+ expect(recovered.cursor).toBe('paid-2');
+ });
+
+ it('rejects a totally failed featured read and returns a real continuation after a retry', async () => {
+ const requests: string[] = [];
+ const collections = browsePages(6), details = browseDetails(6), state = { fail: true };
+ const fetcher = (async (input: URL | RequestInfo) => {
+ const url = new URL(String(input));
+ if (url.pathname.includes('GetComputedProductsList')) {
+ const name = url.searchParams.get('listName') ?? '', page = Number(url.searchParams.get('pgNo') ?? '1');
+ requests.push(`${name}:${page}`);
+ if (state.fail) return new Response('{}', { status: 503 });
+ const payload = collections[name]?.[page - 1];
+ return payload ? new Response(JSON.stringify(payload), { status: 200 }) : new Response('{}', { status: 404 });
+ }
+ if (url.pathname.includes('/v7.0/products')) {
+ const ids = (url.searchParams.get('bigIds') ?? '').split(',').map(id => id.toUpperCase());
+ return new Response(JSON.stringify({ Products: ids.flatMap(id => details[id] ? [details[id]] : []) }), { status: 200 });
+ }
+ return new Response('{}', { status: 404 });
+ }) as typeof fetch;
+ const service = new CatalogService(fetcher);
+ await expect(service.featured('US')).rejects.toThrow('TopTrending');
+ state.fail = false;
+ const retried = await service.featured('US');
+ expect(retried.products.map(product => product.title)).toEqual(['Browse 1', 'Browse 2', 'Browse 3']);
+ expect(retried.hasMore).toBe(true);
+ expect(retried.cursor).toBe('paid-4');
+ });
+
+ it('reads the first paid page when no cursor is provided, so a page-1 recovery request is honest', async () => {
+ const requests: string[] = [];
+ const result = await new CatalogService(landingFetcher(browsePages(4), browseDetails(4), requests)).browse('US');
+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:1']);
+ expect(result.products.map(product => product.title)).toEqual(['Browse 1']);
+ expect(result.cursor).toBe('paid-2');
+ });
+
+ it('serves a repeated cursor from one shared request and never redirects the page budget', async () => {
+ const requests: string[] = [];
+ const service = new CatalogService(landingFetcher(browsePages(6), browseDetails(6), requests));
+ const [left, right] = await Promise.all([service.browse('US', 'paid-5'), service.browse('US', 'paid-5')]);
+ expect(left.products).toEqual(right.products);
+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:5']);
+ });
+
+ it('stops at the last bounded page even when the feed still offers a continuation', async () => {
+ const pages = browsePages(41);
+ pages.TopPaid[39] = { title: 'Top paid games', hasMorePages: true, nextPageNumber: 41, productsList: [row('9BROWSE0040', 'Browse 40', 29.99)] };
+ const result = await new CatalogService(landingFetcher(pages, browseDetails(41), [])).browse('US', 'paid-40');
+ expect(result.hasMore).toBe(false);
+ expect(result.cursor).toBeUndefined();
+ });
+
+ it('keeps the public browsing policy on continued pages', async () => {
+ const collections = browsePages(4, index => index === 4 ? [row('9BROWSETRIAL', 'Browse Trial', 29.99), row('9BROWSEFREE0', 'Browse Free', 0)] : []);
+ const details = { ...browseDetails(4), '9BROWSETRIAL': game('9BROWSETRIAL', [trialSku()]), '9BROWSEFREE0': game('9BROWSEFREE0', [freeSku()]) };
+ const result = await new CatalogService(landingFetcher(collections, details, [])).browse('US', 'paid-4');
+ expect(result.products.map(product => product.title)).toEqual(['Browse 4']);
+ });
+
+ it.each(['paid-0', 'paid-41', 'paid-1000', 'paid-4x', '4', 'cursor', '', 'paid-'])('rejects the invalid browse cursor %s without any request', async cursor => {
+ const requests: string[] = [];
+ await expect(new CatalogService(landingFetcher({}, {}, requests)).browse('US', cursor)).rejects.toThrow('browse cursor');
+ expect(requests).toEqual([]);
+ });
});
describe('Store-only offer policy',()=>{
diff --git a/src/main/catalog.ts b/src/main/catalog.ts
index faa4dc2..59aaab4 100644
--- a/src/main/catalog.ts
+++ b/src/main/catalog.ts
@@ -97,6 +97,20 @@ function raceCallerDeadline<T>(promise: Promise<T>, signal: AbortSignal): Promis
const FEATURED_PAGE_ITEMS = 12;
const FEATURED_TRENDING_PAGES = 1;
const FEATURED_PAID_PAGES = 3;
+// The landing page shows a bounded featured set. Its own result carries the
+// cursor for the next unread Top paid page, so the renderer continues the exact
+// feed that was actually read instead of assuming which pages exist.
+const BROWSE_COLLECTION = 'TopPaid';
+const BROWSE_FIRST_PAGE = 1;
+const BROWSE_LAST_PAGE = 40;
+
+function browsePage(value: unknown): number {
+ if (value === undefined) return BROWSE_FIRST_PAGE;
+ const digits = string(value)?.match(/^paid-([0-9]{1,2})$/)?.[1];
+ const page = digits === undefined ? NaN : Number(digits);
+ if (!Number.isInteger(page) || page < 1 || page > BROWSE_LAST_PAGE) throw new Error('The Store browse cursor is invalid.');
+ return page;
+}
// Box art is square and carries the game's title branding, matching the
// square library tiles; promotional square art is the textless fallback.
const POSTER_PURPOSES = ['BoxArt', 'TitledPoster', 'Poster', 'FeaturePromotionalSquareArt'];
@@ -629,22 +643,30 @@ export class CatalogService {
}
/** Read one public Store recommendation feed, bounded to a fixed page count. */
- private async computedCollection(listName: string, market: string, pages: number): Promise<StoreSearchResponse & { title?: unknown }> {
+ private async collectionPage(listName: string, market: string, page: number): Promise<StoreSearchResponse & { title?: unknown }> {
+ const url = new URL('https://apps.microsoft.com/api/Reco/GetComputedProductsList');
+ for (const [key, value] of Object.entries({
+ listName, pgNo: String(page), noItems: String(FEATURED_PAGE_ITEMS), filteredCategories: 'AllProducts',
+ mediaType: 'Games', gl: market, hl: 'en-us', exp: '0',
+ })) url.searchParams.set(key, value);
+ const response = await this.fetcher(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });
+ if (!response.ok) throw new Error(`Microsoft Store ${listName} collection returned HTTP ${response.status}.`);
+ return await response.json() as StoreSearchResponse & { title?: unknown };
+ }
+
+ private async computedCollection(listName: string, market: string, pages: number): Promise<StoreSearchResponse & { title?: unknown; nextPage?: number }> {
const collected: StoreSearchProduct[] = [];
let title: unknown;
let page = 1;
+ // `nextPage` stays set only when this bounded read stopped while the feed
+ // still offered its exact documented continuation.
+ let nextPage: number | undefined;
for (let index = 0; index < pages; index += 1) {
- const url = new URL('https://apps.microsoft.com/api/Reco/GetComputedProductsList');
- for (const [key, value] of Object.entries({
- listName, pgNo: String(page), noItems: String(FEATURED_PAGE_ITEMS), filteredCategories: 'AllProducts',
- mediaType: 'Games', gl: market, hl: 'en-us', exp: '0',
- })) url.searchParams.set(key, value);
- const response = await this.fetcher(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });
- if (!response.ok) throw new Error(`Microsoft Store ${listName} collection returned HTTP ${response.status}.`);
- const payload = await response.json() as StoreSearchResponse & { title?: unknown };
+ const payload = await this.collectionPage(listName, market, page);
title = title ?? payload.title;
const products = Array.isArray(payload.productsList) ? payload.productsList as StoreSearchProduct[] : [];
collected.push(...products);
+ nextPage = undefined;
if (payload.hasMorePages !== true || products.length === 0) break;
// Captured contract (US pages 1..10, CZ pages 1..3, TopPaid pages 1..3):
// a continuation names exactly the next page while hasMorePages is true,
@@ -653,9 +675,10 @@ export class CatalogService {
// pagination and keeps the products already collected instead of
// following it, so the request budget cannot be redirected.
if (payload.nextPageNumber !== page + 1) break;
+ nextPage = page + 1;
page += 1;
}
- return { productsList: collected, title };
+ return { productsList: collected, title, nextPage };
}
private async featuredResult(market: string): Promise<CatalogSearchResult> {
@@ -678,7 +701,34 @@ export class CatalogService {
const title = string(trending.status === 'fulfilled' ? trending.value.title : undefined)
?? string(paid.status === 'fulfilled' ? paid.value.title : undefined)
?? 'Featured games';
- return this.result(merged, title, market, false);
+ // The continuation names the next unread paid page of the read that really
+ // happened. A paid read that failed while trending worked restarts the paid
+ // feed from its first page, so no paid item is silently skipped.
+ const nextPage = paid.status === 'fulfilled' ? paid.value.nextPage : 1;
+ const cursor = nextPage === undefined || nextPage > BROWSE_LAST_PAGE ? undefined : `paid-${nextPage}`;
+ return { ...await this.result(merged, title, market, false), cursor, hasMore: Boolean(cursor) };
+ }
+
+ /** Continue the public landing collection after the bounded featured set.
+ * One upstream page per call, one shared page per cursor and the same public
+ * browsing policy as the landing page, so demos, trials and free offers stay
+ * excluded. An unknown, repeated or out-of-budget cursor never starts a
+ * request. */
+ async browse(rawMarket: string, rawCursor?: string): Promise<CatalogSearchResult> {
+ const market = normalizeMarket(rawMarket);
+ const page = browsePage(rawCursor);
+ return this.cachedResult(`${market}\u0000browse\u0000${page}`, () => this.browseResult(market, page));
+ }
+
+ private async browseResult(market: string, page: number): Promise<CatalogSearchResult> {
+ const payload = await this.collectionPage(BROWSE_COLLECTION, market, page);
+ const title = string(payload.title) ?? 'Top paid games';
+ const rows = Array.isArray(payload.productsList) ? payload.productsList as StoreSearchProduct[] : [];
+ const result = await this.result(payload, title, market, false);
+ // Continue only on the documented exact continuation of a non-empty page.
+ const next = rows.length > 0 && payload.hasMorePages === true &&
+ payload.nextPageNumber === page + 1 && page + 1 <= BROWSE_LAST_PAGE;
+ return { ...result, cursor: next ? `paid-${page + 1}` : undefined, hasMore: next };
}
async posters(ids: string[], rawMarket: string): Promise<Map<string, string>> {
diff --git a/src/main/index.ts b/src/main/index.ts
index fce8ab9..7b6b4f2 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1793,6 +1793,7 @@ function registerDemoIpc(catalogMarket: () => string): void {
ipcMain.handle('set-offline-permissions', (_event, enabled: boolean) => ({ enabled: Boolean(enabled), requestSuccess: true, remainingToggles: 1, maxToggles: 3, periodDays: 365, checkedAt: new Date().toISOString() }));
ipcMain.handle('catalog-search', (_event, query: string, cursor?: string) => catalog.search(query, publicStoreMarket(), cursor));
ipcMain.handle('catalog-featured', () => catalog.featured(publicStoreMarket()));
+ ipcMain.handle('catalog-browse', (_event, cursor?: string) => catalog.browse(publicStoreMarket(), cursor));
ipcMain.handle('catalog-recent-gamepass', () => homeGamePassShelf.get(publicStoreMarket()));
ipcMain.handle('store-access', () => ({configuredMarket:snapshot().settings.market,account:snapshot().auth.username??'demo',backend:snapshot().backend.binaryPath??'',market:catalogMarket(),checkedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+60_000).toISOString(),accessByProductId:{}}));
ipcMain.handle('account-library', (_event, kind: 'all' | 'owned' | 'gamepass') => demoAccountLibrary(kind, demoArtwork));
@@ -2095,6 +2096,7 @@ function registerIpc(): void {
});
ipcMain.handle('save-diagnostic-report', (_event, content: unknown) => saveReviewedReport(content));
ipcMain.handle('catalog-featured', () => catalog.featured(publicStoreMarket()));
+ ipcMain.handle('catalog-browse', (_event, cursor?: string) => catalog.browse(publicStoreMarket(), cursor));
ipcMain.handle('catalog-recent-gamepass', () => homeGamePassShelf.get(publicStoreMarket()));
ipcMain.handle('start-install', (_event, request: InstallRequest) => startInstall(request));
ipcMain.handle('install-plan', async (_event, raw: string, destination?: string) => {
diff --git a/src/main/public-store-ipc.test.ts b/src/main/public-store-ipc.test.ts
index f8715e4..9c86bb6 100644
--- a/src/main/public-store-ipc.test.ts
+++ b/src/main/public-store-ipc.test.ts
@@ -29,15 +29,15 @@ function handlerStatements(names:string[],owner:string):string{
if(missing.length)throw Error(`Missing IPC handlers: ${missing.join(', ')}.`);
return found.map(node=>node.getText(parsed)).join('\n');
}
-const mainNames=['catalog-search','catalog-featured','catalog-recent-gamepass','game-details','store-access','account-library','install-plan','game-activity','game-achievements'];
+const mainNames=['catalog-search','catalog-featured','catalog-browse','catalog-recent-gamepass','game-details','store-access','account-library','install-plan','game-activity','game-achievements'];
const mainCode=ts.transpileModule([declarations(['storeAccess']),handlerStatements(mainNames,'registerIpc')].join('\n'),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
-const demoCode=ts.transpileModule(handlerStatements(['catalog-search','catalog-featured','catalog-recent-gamepass','game-details','store-access'],'registerDemoIpc'),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
+const demoCode=ts.transpileModule(handlerStatements(['catalog-search','catalog-featured','catalog-browse','catalog-recent-gamepass','game-details','store-access'],'registerDemoIpc'),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
function fixture(mode:'main'|'demo'){
const handlers=new Map<string,Function>(),products={query:'q',market:'US',products:[],hasMore:false,fetchedAt:'',source:'Microsoft Store'};
// CZ desktop with settings.market 'neutral': the effective account region.
let market='CZ';
- const catalog={search:vi.fn(async()=>products),featured:vi.fn(async()=>products),gameDetails:vi.fn(async(productId:string)=>({productId,xboxTitleId:'123'}))};
+ const catalog={search:vi.fn(async()=>products),featured:vi.fn(async()=>products),browse:vi.fn(async()=>products),gameDetails:vi.fn(async(productId:string)=>({productId,xboxTitleId:'123'}))};
const homeGamePassShelf={get:vi.fn(async(market:string)=>({market,products:[],fetchedAt:'2026-11-04T10:00:00.000Z',source:'Microsoft Game Pass catalog'}))};
const games=[{id:'owned-game',storeId:'9GGGGGGGGGGG',title:'Owned Game',path:'/synthetic/game'}];
const store={games,settings:{market:'neutral'}};
@@ -61,6 +61,8 @@ it('browses the neutral US Store on a CZ desktop while Store access keeps the ef
expect(f.catalog.search).toHaveBeenCalledWith('gears','US','cursor');
await f.call('catalog-featured');
expect(f.catalog.featured).toHaveBeenCalledWith('US');
+ await f.call('catalog-browse','paid-4');
+ expect(f.catalog.browse).toHaveBeenCalledWith('US','paid-4');
await f.call('catalog-recent-gamepass');
expect(f.homeGamePassShelf.get).toHaveBeenCalledWith('US');
// A public shelf never reads or verifies account access.
@@ -122,6 +124,8 @@ it('demo applies the same scoped policy instead of an all-US catalog',async()=>{
expect(f.catalog.search).toHaveBeenCalledWith('gears','US','cursor');
await f.call('catalog-featured');
expect(f.catalog.featured).toHaveBeenCalledWith('US');
+ await f.call('catalog-browse');
+ expect(f.catalog.browse).toHaveBeenCalledWith('US',undefined);
await f.call('catalog-recent-gamepass');
expect(f.homeGamePassShelf.get).toHaveBeenCalledWith('US');
await f.call('game-details',{productId:'9PUBLICGAME1',scope:'public-store'});
diff --git a/src/preload/index.cts b/src/preload/index.cts
index c7bc740..c89fd60 100644
--- a/src/preload/index.cts
+++ b/src/preload/index.cts
@@ -123,6 +123,7 @@ const api: LauncherApi = {
setOfflinePermissions: (enabled: boolean) => ipcRenderer.invoke('set-offline-permissions', enabled),
searchCatalog: (query: string, cursor?: string) => ipcRenderer.invoke('catalog-search', query, cursor),
getFeaturedCatalog: () => ipcRenderer.invoke('catalog-featured'),
+ browseCatalog: (cursor?: string) => ipcRenderer.invoke('catalog-browse', cursor),
getRecentGamePassShelf: () => ipcRenderer.invoke('catalog-recent-gamepass'),
getStoreAccess: () => ipcRenderer.invoke('store-access'),
getAccountLibrary: (kind, cursor, refresh, sort) => ipcRenderer.invoke('account-library', kind, cursor, refresh, sort),
diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx
index 385fce9..75da062 100644
--- a/src/renderer/App.tsx
+++ b/src/renderer/App.tsx
@@ -35,7 +35,8 @@ import { requestTextKeyboard } from './touch-keyboard';
import { ConfirmationProvider, useConfirmation } from './Confirmation';
import { GameRemovalContents } from './GameRemovalContents';
import { GameDetails } from './GameDetails';
-import {CatalogGameDetails,catalogGameInstalled,publicStorePrice} from './CatalogGameDetails';
+import { CatalogGameDetails,catalogGameInstalled,publicStorePrice } from './CatalogGameDetails';
+import { appendStoreProducts, storePageState, storeRequested, type StoreListPage } from './store-pagination';
import {HomeGamePassSection,useRecentGamePassShelf} from './HomeGamePass';
import {recentlyInstalledGames} from './home-shelves';
import { GameLanguage } from './GameLanguage';
@@ -342,40 +343,103 @@ export function StoreProductCard({ product, selected, disabled, label, select, i
</article>;
}
+export function StorePagination({ page, loading, error, load }: { page?: StoreListPage; loading: boolean; error?: string; load: () => void }) {
+ if (!page && !error) return null;
+ if (page && !loading && !page.hasMore && !page.stalled && !error) return null;
+ return <div className="load-more store-pagination" data-gamepad-library-footer>
+ {error ? <div className="alert amber" role="alert"><CircleAlert /><span>{uiText(error)}</span><button className="secondary" data-gamepad-skip disabled={loading} onClick={load}>{loading ? <LoaderCircle className="spin" /> : <RefreshCw />}{ui("ui.try_again_d8b839")}</button></div> : null}
+ {page?.stalled && !error ? <p className="account-library-note" role="status">{ui('store.no_more_pages')}</p> : null}
+ {page?.hasMore ? <button className="secondary" aria-disabled={loading} aria-busy={loading} onClick={() => { if (!loading) load(); }}>{loading ? <LoaderCircle className="spin" /> : <Plus />}{ui("ui.load_more_results_e03f1e4")}</button> : null}
+ {loading && !page?.hasMore ? <span className="library-loading" role="status"><LoaderCircle className="spin" />{ui("ui.loading_live_store_collection_20763b0")}</span> : null}
+ </div>;
+}
+
export function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot; toast: (value: Toast) => void; go: (page: Page) => void; initialQuery: string }) {
const startPackageInstall = usePackageInstall();
const access = useStoreAccess(data);
- const [catalog, setCatalog] = useState<CatalogSearchResult>();
+ // The Store shows one paged list at a time: public search results, or the
+ // featured landing page continued by the same collection feed.
+ const [search, setSearch] = useState<(StoreListPage & { query: string })>();
+ const [searching, setSearching] = useState(false);
+ const [searchError, setSearchError] = useState<string>();
+ const [searchPageError, setSearchPageError] = useState<string>();
+ const [searchPageLoading, setSearchPageLoading] = useState(false);
+ // A page request belongs to the search generation that started it. A newer
+ // query owns its own in-flight marker and busy state, so a late answer from
+ // an older generation can neither block nor clear the visible one.
+ const searchGeneration = useRef(0), searchPageInFlight = useRef<number>();
+ const [browseAvailable] = useState(() => typeof window !== 'undefined' && typeof window.launcher?.browseCatalog === 'function');
+ const [browse, setBrowse] = useState<StoreListPage>(() => ({ products: [], hasMore: false, stalled: false, requested: [] }));
+ const [browseLoading, setBrowseLoading] = useState(false);
+ const [browseError, setBrowseError] = useState<string>();
+ const browseInFlight = useRef(false);
const [featured, setFeatured] = useState<CatalogSearchResult>();
const [featuredLoading, setFeaturedLoading] = useState(true);
const [featuredError, setFeaturedError] = useState<string>();
+ const [featuredRevision, setFeaturedRevision] = useState(0);
const [selected, setSelected] = useState<CatalogProduct>();
const [detailOpen,setDetailOpen]=useState(false);
- const pageRef=useRef<HTMLElement>(null),savedScroll=useRef(0),wasOpen=useRef(false);
+ const pageRef=useRef<HTMLElement>(null),savedScroll=useRef(0),wasOpen=useRef(false),sentinel=useRef<HTMLDivElement>(null);
useBrowserLayoutEffect(()=>{
const scroll=pageRef.current?.closest('.page-scroll');
if(detailOpen&&selected){if(scroll)scroll.scrollTop=0;focusDetailEntry(pageRef.current);}
else if(wasOpen.current){if(scroll)scroll.scrollTop=savedScroll.current;[...pageRef.current?.querySelectorAll<HTMLElement>('[data-gamepad-detail-target]')??[]].find(card=>card.getAttribute('data-gamepad-detail-target')===selected?.productId)?.focus({preventScroll:true});}
wasOpen.current=detailOpen&&Boolean(selected);
},[detailOpen,selected?.productId]);
- const [loadingMore, setLoadingMore] = useState(false);
const [busy, setBusy] = useState<string>();
+
+ /** Drops every page-scoped search value instead of leaving it to a stale
+ * request, so a later feed never inherits the previous query's state. */
+ function resetSearchState() {
+ searchGeneration.current += 1;
+ searchPageInFlight.current = undefined;
+ setSearch(undefined); setSearchError(undefined); setSearching(false);
+ setSearchPageError(undefined); setSearchPageLoading(false);
+ }
+ // First page of a public search. A newer query always invalidates the older
+ // request so a slow answer can never replace the visible results.
+ async function runSearch(query: string) {
+ const generation = ++searchGeneration.current;
+ searchPageInFlight.current = undefined;
+ setSearch(undefined); setSearching(true); setSearchError(undefined);
+ setSearchPageError(undefined); setSearchPageLoading(false);
+ try {
+ const next = await window.launcher.searchCatalog(query);
+ if (generation !== searchGeneration.current) return;
+ setSearch({ ...storePageState([], next, []), query: next.query });
+ setSelected(undefined);
+ } catch (error) {
+ if (generation === searchGeneration.current) setSearchError(errorMessage(error));
+ } finally {
+ if (generation === searchGeneration.current) setSearching(false);
+ }
+ }
useEffect(() => {
- if (initialQuery.trim().length < 2) return;
- let cancelled = false;
- window.launcher.searchCatalog(initialQuery).then((result) => {
- if (!cancelled) { setCatalog(result); setSelected(undefined); }
- }).catch((error) => { if (!cancelled) toast({ kind: 'error', message: errorMessage(error) }); });
- return () => { cancelled = true; };
+ const query = initialQuery.trim();
+ if (query.length < 2) { resetSearchState(); return; }
+ void runSearch(query);
+ return () => { searchGeneration.current += 1; };
}, [initialQuery]);
useEffect(() => {
let cancelled = false;
window.launcher.getFeaturedCatalog()
- .then((result) => { if (!cancelled) setFeatured(result); })
- .catch((error) => { if (!cancelled) setFeaturedError(errorMessage(error)); })
+ .then((result) => {
+ if (cancelled) return;
+ setFeatured(result); setFeaturedError(undefined);
+ // The landing continuation is the exact next page of the read that
+ // really happened, never an assumed page number.
+ setBrowse(current => current.products.length ? current : { products: [], cursor: result.cursor, hasMore: Boolean(result.hasMore && result.cursor && browseAvailable), stalled: false, requested: [] });
+ })
+ .catch((error) => {
+ if (cancelled) return;
+ setFeaturedError(errorMessage(error));
+ // A failed landing is not a dead end: the first paid page is an honest
+ // recovery path with the same public policy.
+ setBrowse(current => current.products.length ? current : { products: [], cursor: undefined, hasMore: browseAvailable, stalled: false, requested: [] });
+ })
.finally(() => { if (!cancelled) setFeaturedLoading(false); });
return () => { cancelled = true; };
- }, []);
+ }, [featuredRevision]);
function installDestination(product: CatalogProduct): string {
const folder = product.title.normalize('NFKD').replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '').slice(0, 80) || product.productId;
@@ -387,16 +451,78 @@ export function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot
if(openDetails){savedScroll.current=pageRef.current?.closest('.page-scroll')?.scrollTop??0;setDetailOpen(true);}
}
- async function loadMore() {
- if (!catalog?.cursor) return;
- setLoadingMore(true);
+ async function loadMoreSearch() {
+ const cursor = search?.cursor;
+ const generation = searchGeneration.current;
+ if (!search || !cursor || !search.hasMore) return;
+ if (searchPageInFlight.current === generation) return;
+ searchPageInFlight.current = generation; setSearchPageError(undefined); setSearchPageLoading(true);
try {
- const next = await window.launcher.searchCatalog(catalog.query, catalog.cursor);
- setCatalog({ ...next, products: [...catalog.products, ...next.products] });
- } catch (error) { toast({ kind: 'error', message: errorMessage(error) }); }
- finally { setLoadingMore(false); }
+ const next = await window.launcher.searchCatalog(search.query, cursor);
+ if (generation !== searchGeneration.current) return;
+ setSearch(current => {
+ if (!current || current.query !== search.query) return current;
+ return { ...storePageState(current.products, next, storeRequested(current, cursor)), query: current.query };
+ });
+ } catch (error) {
+ if (generation === searchGeneration.current) setSearchPageError(errorMessage(error));
+ } finally {
+ // Only the generation that owns the marker may release it or clear the
+ // busy state, so a late finish never clobbers a newer page request.
+ if (searchPageInFlight.current === generation) searchPageInFlight.current = undefined;
+ if (generation === searchGeneration.current) setSearchPageLoading(false);
+ }
+ }
+
+ async function loadMoreBrowse() {
+ if (!browse.hasMore || browseInFlight.current) return;
+ const cursor = browse.cursor;
+ browseInFlight.current = true; setBrowseLoading(true); setBrowseError(undefined);
+ try {
+ const next = await window.launcher.browseCatalog(cursor);
+ setBrowse(current => storePageState(current.products, next, storeRequested(current, cursor)));
+ } catch (error) {
+ setBrowseError(errorMessage(error));
+ } finally {
+ browseInFlight.current = false; setBrowseLoading(false);
+ }
}
+ function retryFeatured() { setFeaturedRevision(value => value + 1); }
+
+ // The landing grid and the paged collection are one list; the featured cards
+ // stay first and every later page appends after them.
+ const landingProducts = appendStoreProducts(featured?.products.slice(3) ?? [], browse.products);
+ const featuredRail = featured?.products.slice(0, 3) ?? [];
+ // Scrolling near the end of the real scroll container continues the list. A
+ // failure is never retried automatically; the visible control retries.
+ // Only the feed that is actually displayed gates auto-load: an old search
+ // error or a browse failure must never block the other feed.
+ const autoLoad = useRef<() => void>(() => {});
+ autoLoad.current = () => {
+ if (search) {
+ if (searchPageError || searchPageLoading || !search.hasMore) return;
+ void loadMoreSearch();
+ return;
+ }
+ if (browseError || browseLoading || !browse.hasMore) return;
+ void loadMoreBrowse();
+ };
+ const autoKey = search
+ ? `search:${search.cursor ?? ''}:${search.hasMore}:${searchPageError ?? ''}:${searchPageLoading}`
+ : `browse:${browse.cursor ?? ''}:${browse.hasMore}:${browseError ?? ''}:${browseLoading}`;
+ // The sentinel only exists once a list is on screen, so its arrival must
+ // re-create the observer even when the cursor did not change.
+ const listOnScreen = Boolean(search) || Boolean(featured?.products.length) || Boolean(featuredError);
+ useEffect(() => {
+ const node = sentinel.current, root = pageRef.current?.closest('.page-scroll');
+ if (!node || !root || typeof IntersectionObserver !== 'function') return;
+ if (!(search ?? browse).hasMore) return;
+ const observer = new IntersectionObserver((entries) => { if (entries.some(entry => entry.isIntersecting)) autoLoad.current(); }, { root, rootMargin: '400px 0px' });
+ observer.observe(node);
+ return () => { observer.disconnect(); };
+ }, [autoKey, listOnScreen, detailOpen]);
+
async function install(product: CatalogProduct, target = installDestination(product)) {
if (!access.canInstall(product)) return;
setBusy(product.productId);
@@ -424,13 +550,28 @@ export function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot
if(detailOpen&&selected)return <main ref={pageRef} className="page store-page library-detail-open"><CatalogGameDetails key={`${selected.productId}:${data.auth.username}:${data.auth.player}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} product={selected} data={data} storeMode storeAccess={access} back={()=>setDetailOpen(false)} backLabel={ui('game.back_to_store')} toast={toast}/></main>;
// Only the product grid renders a price. The first three featured tiles are
// artwork-only, and all catalog results render in the price-bearing grid.
- const priceGrid=catalog?catalog.products:featured?.products.slice(3)??[];
- const publicPriceShown=priceGrid.some(product=>Boolean(publicStorePrice(product)));
return <main ref={pageRef} className="page store-page">
- <header className="page-header"><div><h1>{ui("ui.store_ee7da93")}</h1>{publicPriceShown?<p>{ui('store.us_price_context')}</p>:null}</div><span className="catalog-source"><StatusDot />Microsoft Store</span></header>
- {!catalog ? <section className="featured-catalog"><SectionTitle title={ui("ui.featured_c533caf")} />{featuredLoading ? <div className="catalog-loading"><LoaderCircle className="spin" /><span>{ui("ui.loading_live_store_collection_20763b0")}</span></div> : featured?.products.length ? <><div className="featured-rail">{featured.products.slice(0, 3).map((product) => <button className="featured-tile" key={product.productId} data-gamepad-detail-target={product.productId} onClick={() => selectProduct(product)}>{product.heroUrl || product.posterUrl ? <img src={product.heroUrl ?? product.posterUrl} alt="" /> : <div className="featured-tile-placeholder"><Gamepad2 /></div>}<span className="featured-tile-copy"><GameTitle title={product.title} /><small>{product.publisher ?? 'Microsoft Store'} · {product.installability === 'supported' ? ui('store.verified_pc') : ui("ui.check_package_support_79592da")}</small></span></button>)}</div><SectionTitle title={ui("ui.top_paid_games_8040f77")} />{productGrid(featured.products.slice(3))}</> : <div className="catalog-empty"><Store /><h2>{ui("ui.featured_games_are_temporarily_unavailable_3901a69")}</h2><p>{featuredError ?? ui("ui.search_still_works_with_live_microsoft_store_dat_b3eeb72")}</p></div>}</section> : null}
+ <header className="page-header"><div><h1>{ui("ui.store_ee7da93")}</h1></div><span className="catalog-source"><StatusDot />Microsoft Store</span></header>
+ {!search && !searching && !searchError ? <section className="featured-catalog"><SectionTitle title={ui("ui.featured_c533caf")} />
+ {featuredLoading ? <div className="catalog-loading"><LoaderCircle className="spin" /><span>{ui("ui.loading_live_store_collection_20763b0")}</span></div> : <>
+ {featuredError && landingProducts.length ? <div className="empty-strip"><CircleAlert /><div><strong>{ui("ui.featured_games_are_temporarily_unavailable_3901a69")}</strong><span>{uiText(featuredError)}</span></div><button className="secondary" onClick={retryFeatured}><RefreshCw />{ui("ui.try_again_d8b839")}</button></div> : null}
+ {featuredRail.length ? <div className="featured-rail">{featuredRail.map((product) => <button className="featured-tile" key={product.productId} data-gamepad-detail-target={product.productId} onClick={() => selectProduct(product)}>{product.heroUrl || product.posterUrl ? <img src={product.heroUrl ?? product.posterUrl} alt="" /> : <div className="featured-tile-placeholder"><Gamepad2 /></div>}<span className="featured-tile-copy"><GameTitle title={product.title} /><small>{product.publisher ?? 'Microsoft Store'} · {product.installability === 'supported' ? ui('store.verified_pc') : ui("ui.check_package_support_79592da")}</small></span></button>)}</div> : null}
+ {landingProducts.length ? <><SectionTitle title={ui("ui.top_paid_games_8040f77")} />{productGrid(landingProducts)}</> : null}
+ {featuredError && !landingProducts.length ? <div className="catalog-empty"><Store /><h2>{ui("ui.featured_games_are_temporarily_unavailable_3901a69")}</h2><p>{uiText(featuredError)}</p><button className="secondary" onClick={retryFeatured}><RefreshCw />{ui("ui.try_again_d8b839")}</button></div> : null}
+ {!featuredError && !landingProducts.length ? <div className="catalog-empty"><Store /><h2>{ui("ui.featured_games_are_temporarily_unavailable_3901a69")}</h2><p>{ui("ui.search_still_works_with_live_microsoft_store_dat_b3eeb72")}</p></div> : null}
+ </>}
+ </section> : null}
+
+ {search || searching || searchError ? <><SectionTitle title={search ? ui("ui.results_for_343a212", { query: search.query }) : ui("ui.results_for_343a212", { query: initialQuery.trim() })} />
+ {searchError ? <div className="alert amber" role="alert"><CircleAlert /><span>{uiText(searchError)}</span><button className="secondary" disabled={searching} onClick={() => void runSearch(initialQuery.trim())}><RefreshCw />{ui("ui.try_again_d8b839")}</button></div> : null}
+ {searching && !search ? <div className="catalog-loading"><LoaderCircle className="spin" /><span>{ui("ui.loading_live_store_collection_20763b0")}</span></div> : null}
+ {search ? productGrid(search.products) : null}
+ {search && search.products.length === 0 && !search.hasMore ? <div className="empty-state compact"><div><Search /></div><h2>{ui("ui.no_games_found_6da4c04")}</h2><p>{ui("ui.try_a_different_title_or_a_microsoft_store_produ_326af8c")}</p></div> : null}
+ {search ? <div ref={sentinel} /> : null}
+ <StorePagination page={search} loading={searchPageLoading} error={searchPageError} load={() => void loadMoreSearch()} />
+ </> : null}
- {catalog ? <><SectionTitle title={ui("ui.results_for_343a212", { query: catalog.query })} />{productGrid(catalog.products)}{catalog.products.length === 0 ? <div className="empty-state compact"><div><Search /></div><h2>{ui("ui.no_games_found_6da4c04")}</h2><p>{ui("ui.try_a_different_title_or_a_microsoft_store_produ_326af8c")}</p></div> : null}{catalog.hasMore ? <div className="load-more" data-gamepad-library-footer><button className="secondary" aria-disabled={loadingMore} aria-busy={loadingMore} onClick={() => { if (!loadingMore) void loadMore(); }}>{loadingMore ? <LoaderCircle className="spin" /> : <Plus />}{ui("ui.load_more_results_e03f1e4")}</button></div> : null}</> : null}
+ {!search && !searching && !searchError && !featuredLoading ? <><div ref={sentinel} /><StorePagination page={browse} loading={browseLoading} error={browseError} load={() => void loadMoreBrowse()} /></> : null}
</main>;
}
diff --git a/src/renderer/public-store-price.test.tsx b/src/renderer/public-store-price.test.tsx
index 23927e5..c71097e 100644
--- a/src/renderer/public-store-price.test.tsx
+++ b/src/renderer/public-store-price.test.tsx
@@ -129,24 +129,17 @@ it('marks a priced public Store card with its US market and keeps a missing pric
expect(free).not.toContain('US Store, USD');
});
-it('shows the US price note only when the rendered Store grid contains a formatted price',async()=>{
+it('marks real US prices on the cards without repeating a price paragraph in the Store header',async()=>{
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);
const data=snapshot('CZ');
- const page=async(products:CatalogProduct[])=>{
- installLauncher(products);
- return mount(<StorePage data={data} toast={()=>{}} go={()=>{}} initialQuery=""/>);
- };
// The first three featured entries are artwork-only hero tiles with no price.
- const pricedHeroes=await page([item('9HERO0000001','$29.99'),item('9HERO0000002','$19.99'),item('9HERO0000003','$9.99')]);
- try{expect(pricedHeroes.node.innerHTML).not.toContain(note);}
- finally{await pricedHeroes.unmount();}
- const pricedGrid=await page([item('9HERO0000001'),item('9HERO0000002'),item('9HERO0000003'),item('9GRID0000001','$29.99')]);
+ installLauncher([item('9HERO0000001'),item('9HERO0000002'),item('9HERO0000003'),item('9GRID0000001','$29.99')]);
+ const view=await mount(<StorePage data={data} toast={()=>{}} go={()=>{}} initialQuery=""/>);
try{
- expect(pricedGrid.node.innerHTML).toContain(note);
- expect(pricedGrid.node.innerHTML).toContain('US Store, USD');
+ const html=view.node.innerHTML;
+ expect(view.node.querySelector('.page-header p')).toBeNull();
+ expect(html).toContain('$29.99 · US Store, USD');
+ expect(html).toContain('US Store, USD');
expect(data.settings.market).toBe('CZ');
- }finally{await pricedGrid.unmount();}
- const unpricedGrid=await page([item('9HERO0000001','$29.99'),item('9HERO0000002'),item('9HERO0000003'),item('9GRID0000001')]);
- try{expect(unpricedGrid.node.innerHTML).not.toContain(note);}
- finally{await unpricedGrid.unmount();}
+ }finally{await view.unmount();}
});
diff --git a/src/renderer/store-browse.test.tsx b/src/renderer/store-browse.test.tsx
new file mode 100644
index 0000000..8340f92
--- /dev/null
+++ b/src/renderer/store-browse.test.tsx
@@ -0,0 +1,218 @@
+// @vitest-environment jsdom
+import {act} from 'react';
+import {createRoot,type Root} from 'react-dom/client';
+import {afterEach,beforeEach,expect,it,vi} from 'vitest';
+import {StorePage} from './App';
+import {demoSnapshot} from '../shared/demo-data';
+import type {CatalogProduct,CatalogSearchResult} from '../shared/types';
+
+let root:Root;
+const product=(id:string):CatalogProduct=>({productId:id,title:id,description:'',categories:[],installability:'supported',supportNote:'Supported'});
+const result=(products:CatalogProduct[],cursor?:string,hasMore=false,query='Top paid games'):CatalogSearchResult=>({query,market:'US',products,cursor,hasMore,fetchedAt:new Date().toISOString(),source:'Microsoft Store'});
+const featured=[product('9HERO0000001'),product('9HERO0000002'),product('9HERO0000003'),product('9FEATURED01'),product('9FEATURED02')];
+const button=(label:string)=>[...document.querySelectorAll('button')].find(node=>node.textContent?.includes(label)) as HTMLButtonElement|undefined;
+const cards=()=>[...document.querySelectorAll('.catalog-card')].map(node=>node.textContent);
+const click=async(node:Element|undefined)=>{expect(node).toBeDefined();await act(async()=>(node as HTMLElement).click());};
+const page=(initialQuery='')=><StorePage data={demoSnapshot()} toast={()=>{}} go={()=>{}} initialQuery={initialQuery}/>;
+const render=async(initialQuery='',wrapped=false)=>{await act(async()=>root.render(wrapped?<div className="page-scroll">{page(initialQuery)}</div>:page(initialQuery)));};
+const flush=async()=>{await act(async()=>{await Promise.resolve();});await act(async()=>{await Promise.resolve();});};
+const remount=async(initialQuery='',wrapped=false)=>{await act(async()=>root.unmount());document.body.innerHTML='<div id="root"></div>';root=createRoot(document.getElementById('root')!);await render(initialQuery,wrapped);await flush();};
+
+type Observed={root:Element|Document|null;callback:IntersectionObserverCallback};
+function stubObserver():Observed[]{
+ const seen:Observed[]=[];
+ class FakeObserver{
+ root:Element|Document|null=null;rootMargin='';thresholds:number[]=[];
+ constructor(callback:IntersectionObserverCallback,options?:IntersectionObserverInit){seen.push({root:options?.root??null,callback});}
+ observe(){}unobserve(){}disconnect(){}takeRecords(){return [];}
+ }
+ vi.stubGlobal('IntersectionObserver',FakeObserver);
+ return seen;
+}
+const intersect=async(observed:Observed[])=>{await act(async()=>observed.at(-1)!.callback([{isIntersecting:true} as IntersectionObserverEntry],{} as IntersectionObserver));await flush();};
+
+let toast:ReturnType<typeof vi.fn>;
+beforeEach(async()=>{
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);
+ toast=vi.fn();
+ window.launcher={
+ getFeaturedCatalog:vi.fn(async()=>result(featured,'paid-4',true)),
+ browseCatalog:vi.fn(async()=>result([],undefined,false)),
+ searchCatalog:vi.fn(async(query:string)=>result([],undefined,false,query)),
+ getStoreAccess:vi.fn(async()=>undefined),
+ } as unknown as Window['launcher'];
+ document.body.innerHTML='<div id="root"></div>';root=createRoot(document.getElementById('root')!);
+ await render();await flush();
+});
+afterEach(async()=>{await act(async()=>root.unmount());vi.restoreAllMocks();vi.unstubAllGlobals();document.body.innerHTML='';});
+
+it('continues from the exact cursor the featured result returned, without duplicating a card',async()=>{
+ expect(cards()).toHaveLength(2);
+ vi.mocked(window.launcher.browseCatalog).mockResolvedValueOnce(result([product('9FEATURED02'),product('9BROWSE0001')],'paid-5',true));
+ await click(button('Load more results'));await flush();
+ expect(window.launcher.browseCatalog).toHaveBeenCalledWith('paid-4');
+ expect(cards()).toHaveLength(3);
+ expect(document.body.textContent).toContain('9BROWSE0001');
+ expect(cards().filter(text=>text?.includes('9FEATURED02'))).toHaveLength(1);
+ vi.mocked(window.launcher.browseCatalog).mockResolvedValueOnce(result([product('9BROWSE0002')],'paid-6',true));
+ await click(button('Load more results'));await flush();
+ expect(window.launcher.browseCatalog).toHaveBeenLastCalledWith('paid-5');
+ expect(cards()).toHaveLength(4);
+});
+
+it('shows no continuation when the featured read already covered the whole paid feed',async()=>{
+ vi.mocked(window.launcher.getFeaturedCatalog).mockResolvedValue(result(featured,undefined,false));
+ await remount();
+ expect(button('Load more results')).toBeUndefined();
+ expect(cards()).toHaveLength(2);
+});
+
+it('sends one request for a held page and keeps the control busy',async()=>{
+ let resolve!:(value:CatalogSearchResult)=>void;
+ vi.mocked(window.launcher.browseCatalog).mockReturnValueOnce(new Promise<CatalogSearchResult>(done=>resolve=done));
+ await click(button('Load more results'));
+ await click(button('Load more results'));
+ expect(window.launcher.browseCatalog).toHaveBeenCalledTimes(1);
+ expect(button('Load more results')?.getAttribute('aria-busy')).toBe('true');
+ await act(async()=>resolve(result([product('9BROWSE0001')],undefined,false)));await flush();
+ expect(button('Load more results')).toBeUndefined();
+ expect(cards()).toHaveLength(3);
+});
+
+it('stops an A to B to A cursor cycle instead of loading the same page again',async()=>{
+ vi.mocked(window.launcher.browseCatalog).mockResolvedValueOnce(result([product('9BROWSE0001')],'paid-5',true));
+ await click(button('Load more results'));await flush();
+ expect(button('Load more results')).toBeDefined();
+ vi.mocked(window.launcher.browseCatalog).mockResolvedValueOnce(result([product('9BROWSE0002')],'paid-4',true));
+ await click(button('Load more results'));await flush();
+ expect(window.launcher.browseCatalog).toHaveBeenCalledTimes(2);
+ expect(button('Load more results')).toBeUndefined();
+ expect(document.body.textContent).toContain('The Store did not return any more games.');
+ expect(cards()).toHaveLength(4);
+});
+
+it('reports a failed page in place and retries it on request without losing the loaded cards',async()=>{
+ vi.mocked(window.launcher.browseCatalog).mockRejectedValueOnce(Error('Microsoft Store TopPaid collection returned HTTP 503.'));
+ await click(button('Load more results'));await flush();
+ expect(document.querySelector('[role="alert"]')?.textContent).toContain('HTTP 503');
+ expect(cards()).toHaveLength(2);
+ expect(toast).not.toHaveBeenCalled();
+ vi.mocked(window.launcher.browseCatalog).mockResolvedValueOnce(result([product('9BROWSE0001')],undefined,false));
+ await click(button('Try again'));await flush();
+ expect(window.launcher.browseCatalog).toHaveBeenCalledTimes(2);
+ expect(cards()).toHaveLength(3);
+ expect(document.querySelector('[role="alert"]')).toBeNull();
+});
+
+it('offers a featured retry and a first paid page recovery after a total featured failure',async()=>{
+ vi.mocked(window.launcher.getFeaturedCatalog).mockRejectedValueOnce(Error('Microsoft Store TopTrending collection returned HTTP 503.'));
+ await remount();
+ expect(document.body.textContent).toContain('HTTP 503');
+ expect(button('Try again')).toBeDefined();
+ // Recovery: the first paid page is reachable instead of a dead end.
+ vi.mocked(window.launcher.browseCatalog).mockResolvedValueOnce(result([product('9RECOVER0001')],'paid-2',true));
+ await click(button('Load more results'));await flush();
+ expect(window.launcher.browseCatalog).toHaveBeenCalledWith(undefined);
+ expect(document.body.textContent).toContain('9RECOVER0001');
+ // A featured retry must not drop the recovered paid page.
+ vi.mocked(window.launcher.getFeaturedCatalog).mockResolvedValueOnce(result(featured,'paid-4',true));
+ vi.mocked(window.launcher.getFeaturedCatalog).mockClear();
+ await click(button('Try again'));await flush();
+ expect(window.launcher.getFeaturedCatalog).toHaveBeenCalledTimes(1);
+ expect(document.body.textContent).toContain('9RECOVER0001');
+ expect(cards()).toHaveLength(3);
+});
+
+it('keeps only the newest search answer when an older query resolves late',async()=>{
+ let resolveOld!:(value:CatalogSearchResult)=>void;
+ vi.mocked(window.launcher.searchCatalog)
+ .mockReturnValueOnce(new Promise<CatalogSearchResult>(done=>resolveOld=done))
+ .mockResolvedValueOnce(result([product('9NEW00000001')],undefined,false,'newer'));
+ await render('older');await flush();
+ await render('newer');await flush();
+ await act(async()=>resolveOld(result([product('9OLD00000001')],undefined,false,'older')));await flush();
+ expect(document.body.textContent).toContain('9NEW00000001');
+ expect(document.body.textContent).not.toContain('9OLD00000001');
+ expect(document.body.textContent).toContain('Results for “newer”');
+});
+
+it('lets a new query page run and survive while an older page is still held',async()=>{
+ let resolveOld!:(value:CatalogSearchResult)=>void, resolveNew!:(value:CatalogSearchResult)=>void;
+ vi.mocked(window.launcher.searchCatalog)
+ .mockResolvedValueOnce(result([product('9OLD00000001')],'old-page-2',true,'older'))
+ .mockReturnValueOnce(new Promise<CatalogSearchResult>(done=>resolveOld=done))
+ .mockResolvedValueOnce(result([product('9NEW00000001')],'new-page-2',true,'newer'))
+ .mockReturnValueOnce(new Promise<CatalogSearchResult>(done=>resolveNew=done));
+ await render('older');await flush();
+ await click(button('Load more results'));
+ await render('newer');await flush();
+ expect(cards()).toHaveLength(1);
+ await click(button('Load more results'));await flush();
+ expect(window.launcher.searchCatalog).toHaveBeenCalledTimes(4);
+ expect(button('Load more results')?.getAttribute('aria-busy')).toBe('true');
+ await act(async()=>resolveOld(result([product('9OLD00000002')],'old-page-3',true,'older')));await flush();
+ expect(document.body.textContent).not.toContain('9OLD00000002');
+ expect(button('Load more results')?.getAttribute('aria-busy')).toBe('true');
+ await act(async()=>resolveNew(result([product('9NEW00000002')],undefined,false,'newer')));await flush();
+ expect(cards()).toHaveLength(2);
+ expect(document.body.textContent).toContain('9NEW00000002');
+});
+
+it('ignores a late rejection and finish from an older search page',async()=>{
+ let rejectOld!:(error:Error)=>void;
+ vi.mocked(window.launcher.searchCatalog)
+ .mockResolvedValueOnce(result([product('9OLD00000001')],'old-page-2',true,'older'))
+ .mockReturnValueOnce(new Promise<CatalogSearchResult>((_done,fail)=>{rejectOld=fail;}))
+ .mockResolvedValueOnce(result([product('9NEW00000001')],'new-page-2',true,'newer'))
+ .mockResolvedValueOnce(result([product('9NEW00000002')],'new-page-3',true,'newer'));
+ await render('older');await flush();
+ await click(button('Load more results'));
+ await render('newer');await flush();
+ await click(button('Load more results'));await flush();
+ expect(cards()).toHaveLength(2);
+ await act(async()=>rejectOld(Error('Microsoft Store search returned HTTP 503.')));await flush();
+ expect(document.querySelector('[role="alert"]')).toBeNull();
+ expect(button('Load more results')).toBeDefined();
+ expect(button('Load more results')?.getAttribute('aria-busy')).toBe('false');
+});
+
+it('resumes landing auto-load after a search page failure is cleared',async()=>{
+ const observed=stubObserver();
+ vi.mocked(window.launcher.searchCatalog)
+ .mockResolvedValueOnce(result([product('9RESULT00001')],'next-page',true,'gears'))
+ .mockRejectedValueOnce(Error('Microsoft Store search returned HTTP 503.'));
+ await remount('gears',true);
+ await click(button('Load more results'));await flush();
+ expect(document.querySelector('[role="alert"]')?.textContent).toContain('HTTP 503');
+ vi.mocked(window.launcher.browseCatalog).mockResolvedValueOnce(result([product('9BROWSE0001')],undefined,false));
+ await render('',true);await flush();
+ expect(document.body.textContent).not.toContain('HTTP 503');
+ await intersect(observed);
+ expect(window.launcher.browseCatalog).toHaveBeenCalledTimes(1);
+ expect(cards()).toHaveLength(3);
+});
+
+it('does not let a browse failure block search auto-load',async()=>{
+ const observed=stubObserver();
+ await remount('',true);
+ vi.mocked(window.launcher.browseCatalog).mockRejectedValueOnce(Error('Microsoft Store TopPaid collection returned HTTP 503.'));
+ await click(button('Load more results'));await flush();
+ expect(document.querySelector('[role="alert"]')?.textContent).toContain('HTTP 503');
+ vi.mocked(window.launcher.searchCatalog)
+ .mockResolvedValueOnce(result([product('9RESULT00001')],'next-page',true,'gears'))
+ .mockResolvedValueOnce(result([product('9RESULT00002')],undefined,false,'gears'));
+ await render('gears',true);await flush();
+ await intersect(observed);
+ expect(window.launcher.searchCatalog).toHaveBeenLastCalledWith('gears','next-page');
+ expect(cards()).toHaveLength(2);
+});
+
+it('observes the real page scroll container and continues the list when its end comes into view',async()=>{
+ const observed:Observed[]=stubObserver();
+ vi.mocked(window.launcher.browseCatalog).mockResolvedValueOnce(result([product('9BROWSE0001')],undefined,false));
+ await render('',true);await flush();
+ expect(observed.at(-1)!.root).toBe(document.querySelector('.page-scroll'));
+ await intersect(observed);
+ expect(window.launcher.browseCatalog).toHaveBeenCalledTimes(1);
+ expect(cards()).toHaveLength(3);
+});
diff --git a/src/renderer/store-pagination.test.ts b/src/renderer/store-pagination.test.ts
new file mode 100644
index 0000000..45c2c59
--- /dev/null
+++ b/src/renderer/store-pagination.test.ts
@@ -0,0 +1,52 @@
+import {expect,it} from 'vitest';
+import {appendStoreProducts,storePageState,storeRequested} from './store-pagination';
+import type {CatalogProduct,CatalogSearchResult} from '../shared/types';
+
+const product=(id:string):CatalogProduct=>({productId:id,title:id,description:'',categories:[],installability:'supported',supportNote:'Supported'});
+const result=(products:CatalogProduct[],cursor?:string,hasMore=false):CatalogSearchResult=>({query:'Top paid games',market:'US',products,cursor,hasMore,fetchedAt:new Date().toISOString(),source:'Microsoft Store'});
+
+it('appends only unseen product IDs so repeated Store pages never duplicate a card',()=>{
+ const current=[product('9A'),product('9B')];
+ expect(appendStoreProducts(current,[product('9B'),product('9C')]).map(item=>item.productId)).toEqual(['9A','9B','9C']);
+ expect(appendStoreProducts(current,[product('9A')])).toBe(current);
+ expect(appendStoreProducts(current,[])).toBe(current);
+});
+
+it('records the requested cursor with the feed cursors that were already used',()=>{
+ const page={requested:[] as readonly string[]};
+ expect(storeRequested(page,undefined)).toEqual([]);
+ expect(storeRequested({requested:['paid-4']},'paid-5')).toEqual(['paid-4','paid-5']);
+});
+
+it('continues on a genuinely new cursor',()=>{
+ const state=storePageState([product('9A')],result([product('9B')],'paid-5',true),['paid-4']);
+ expect(state.products.map(item=>item.productId)).toEqual(['9A','9B']);
+ expect(state.cursor).toBe('paid-5');expect(state.hasMore).toBe(true);expect(state.stalled).toBe(false);
+ expect(state.requested).toEqual(['paid-4']);
+});
+
+it('ends the list once when any earlier cursor repeats instead of loading the same page again',()=>{
+ const repeated=storePageState([product('9A')],result([product('9B')],'paid-4',true),['paid-4','paid-5']);
+ expect(repeated.cursor).toBeUndefined();expect(repeated.hasMore).toBe(false);expect(repeated.stalled).toBe(true);
+ // Loaded cards are preserved when the cycle is detected.
+ expect(repeated.products.map(item=>item.productId)).toEqual(['9A','9B']);
+});
+
+it('stops an A to B to A cursor cycle while keeping every loaded card',()=>{
+ let feed=storePageState([],result([product('9P1')],'paid-4',true),[]);
+ expect(feed.cursor).toBe('paid-4');
+ const first=storePageState(feed.products,result([product('9P2')],'paid-5',true),storeRequested(feed,feed.cursor));
+ expect(first.cursor).toBe('paid-5');expect(first.hasMore).toBe(true);expect(first.products).toHaveLength(2);
+ const used=storeRequested(first,first.cursor);
+ expect(used).toEqual(['paid-4','paid-5']);
+ const cycle=storePageState(first.products,result([product('9P3')],'paid-4',true),used);
+ expect(cycle.hasMore).toBe(false);expect(cycle.cursor).toBeUndefined();expect(cycle.stalled).toBe(true);
+ expect(cycle.products.map(item=>item.productId)).toEqual(['9P1','9P2','9P3']);
+});
+
+it('ends the list when the Store claims more pages without a usable cursor',()=>{
+ const missing=storePageState([],result([product('9A')],undefined,true),[]);
+ expect(missing.hasMore).toBe(false);expect(missing.stalled).toBe(true);
+ const ended=storePageState([],result([product('9A')],undefined,false),[]);
+ expect(ended.hasMore).toBe(false);expect(ended.stalled).toBe(false);expect(ended.cursor).toBeUndefined();
+});
diff --git a/src/renderer/store-pagination.ts b/src/renderer/store-pagination.ts
new file mode 100644
index 0000000..ff167cd
--- /dev/null
+++ b/src/renderer/store-pagination.ts
@@ -0,0 +1,29 @@
+import type {CatalogProduct,CatalogSearchResult} from '../shared/types';
+
+/** One paged public Store list. It only ever grows by explicit continuation. */
+export type StoreListPage = {products:CatalogProduct[];cursor?:string;hasMore:boolean;stalled:boolean;requested:readonly string[]};
+
+/** Cards are unique by real product ID. The featured set and later collection
+ * pages can repeat the same title, so every append is deduplicated. */
+export function appendStoreProducts(current:CatalogProduct[],next:CatalogProduct[]):CatalogProduct[] {
+ const seen=new Set(current.map(product=>product.productId));
+ const appended=next.filter(product=>{if(seen.has(product.productId))return false;seen.add(product.productId);return true;});
+ return appended.length?[...current,...appended]:current;
+}
+
+/** Cursors already used by this feed, including the page about to be requested.
+ * Every cursor is recorded once, so an A to B to A cycle is visible. */
+export function storeRequested(page:Pick<StoreListPage,'requested'>,cursor?:string):readonly string[] {
+ return cursor?[...page.requested,cursor]:page.requested;
+}
+
+/** A cursor that repeats any earlier page of this feed would refetch an already
+ * loaded page forever. It ends the list exactly once instead of starting a
+ * duplicate request loop, and the loaded cards stay visible. */
+export function storePageState(current:CatalogProduct[],next:CatalogSearchResult,requested:readonly string[]):StoreListPage {
+ const products=appendStoreProducts(current,next.products);
+ const cursor=next.cursor;
+ const repeated=Boolean(cursor)&&requested.includes(cursor as string);
+ const advanced=Boolean(cursor)&&!repeated;
+ return {products,cursor:advanced?cursor:undefined,hasMore:next.hasMore&&advanced,stalled:next.hasMore&&!advanced,requested};
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 4f77ff1..fffd8e7 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -290,6 +290,8 @@ button.primary svg, button.secondary svg { width: 17px; height: 17px; }
.catalog-card-install:disabled { opacity: .42; cursor: not-allowed; }
.catalog-card-install svg { width: 14px; height: 14px; }
.load-more { padding: 24px 0 4px; display: flex; justify-content: center; }
+.store-pagination { flex-direction: column; gap: 10px; align-items: center; }
+.store-pagination > .alert.amber { width: 100%; margin: 0; text-align: left; }
.featured-catalog { margin-top: 4px; }
.catalog-loading { min-height: 260px; display: flex; align-items: center; justify-content: center; gap: 10px; border: 1px dashed #454a50; color: var(--muted); font-size: 10px; }
.catalog-loading svg { width: 18px; color: var(--green); }
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 07e9ab0..362b849 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -680,6 +680,7 @@ export interface LauncherApi {
setOfflinePermissions(enabled: boolean): Promise<OfflinePermissions>;
searchCatalog(query: string, cursor?: string): Promise<CatalogSearchResult>;
getFeaturedCatalog(): Promise<CatalogSearchResult>;
+ browseCatalog(cursor?: string): Promise<CatalogSearchResult>;
getRecentGamePassShelf(): Promise<RecentGamePassShelf>;
getStoreAccess(): Promise<StoreAccess>;
getAccountLibrary(kind: AccountLibraryPage['kind'], cursor?: string, refresh?: boolean, sort?: AccountLibraryPage['sort']): Promise<AccountLibraryPage>;