Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(plugins): page, sort and filter the marketplace through the center (#2397)

Lanf91799f3f190
diff --git a/apps/desktop/electron/main/ipc/market-ipc.ts b/apps/desktop/electron/main/ipc/market-ipc.ts
index c74734565..8faf20200 100644
--- a/apps/desktop/electron/main/ipc/market-ipc.ts
+++ b/apps/desktop/electron/main/ipc/market-ipc.ts
@@ -46,6 +46,31 @@ export function registerMarketIpc({
});
});
+ // One page of the marketplace. The host owns normalization, the plugin
+ // center request and the snapshot fallback; the bridge only shapes the
+ // payload so a renderer bug cannot smuggle extra fields to the host.
+ handle(IPC.invoke.marketBrowse, async (payload?: {
+ query?: unknown;
+ category?: unknown;
+ sort?: unknown;
+ seed?: unknown;
+ page?: unknown;
+ pageSize?: unknown;
+ }) => {
+ if (!host) throw new Error("host unavailable");
+ const text = (value: unknown) => (typeof value === "string" ? value : "");
+ const count = (value: unknown) =>
+ typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
+ return host.call("market.browse", {
+ query: text(payload?.query),
+ category: text(payload?.category),
+ sort: text(payload?.sort),
+ seed: count(payload?.seed),
+ page: count(payload?.page),
+ pageSize: count(payload?.pageSize),
+ });
+ });
+
handle(IPC.invoke.marketGetDetail, async (id: string) => {
if (!host) throw new Error("host unavailable");
return host.call("market.getDetail", { id });
diff --git a/apps/desktop/src/capture/capture-rig.ts b/apps/desktop/src/capture/capture-rig.ts
index 4fb0b4fa4..a22934ac9 100644
--- a/apps/desktop/src/capture/capture-rig.ts
+++ b/apps/desktop/src/capture/capture-rig.ts
@@ -60,6 +60,7 @@ export function installCaptureRig(): CaptureRig {
useAppStore.getState().refreshNotifications;
const originalListPluginServices = api.listPluginServices;
const originalMarketSearch = api.marketSearch;
+ const originalMarketBrowse = api.marketBrowse;
const originalMarketDetail = api.marketGetDetail;
const originalListMcpServers = api.listMcpServers;
const originalListUserSkills = api.listUserSkills;
@@ -513,6 +514,7 @@ export function installCaptureRig(): CaptureRig {
useAppStore.setState({ plugins: [] });
(api as any).listPluginServices = originalListPluginServices;
(api as any).marketSearch = originalMarketSearch;
+ (api as any).marketBrowse = originalMarketBrowse;
(api as any).marketGetDetail = originalMarketDetail;
return;
}
@@ -624,6 +626,26 @@ export function installCaptureRig(): CaptureRig {
},
],
});
+ // The paged browse wraps the same cards in one page of results.
+ (api as any).marketBrowse = async () => {
+ const { plugins } = await (api as any).marketSearch();
+ const counts = new Map<string, number>();
+ for (const plugin of plugins) {
+ for (const id of plugin.categories ?? []) counts.set(id, (counts.get(id) ?? 0) + 1);
+ }
+ return {
+ plugins,
+ total: plugins.length,
+ page: 1,
+ pageSize: 24,
+ pageCount: 1,
+ sort: "recommended",
+ categories: [...counts].map(([id, count]) => ({ id, count })),
+ source: "remote",
+ providerId: "official",
+ sourceUrl: "https://example.invalid/catalog.json",
+ };
+ };
// The rows read service state straight from IPC, which reports nothing
// for a fixture plugin; stand in for the supervisor here.
(api as any).listPluginServices = async () => [
@@ -1181,6 +1203,7 @@ export function installCaptureRig(): CaptureRig {
});
api.listPluginServices = originalListPluginServices;
api.marketSearch = originalMarketSearch;
+ api.marketBrowse = originalMarketBrowse;
api.marketGetDetail = originalMarketDetail;
api.listMcpServers = originalListMcpServers;
api.listUserSkills = originalListUserSkills;
diff --git a/apps/desktop/src/features/plugins/MarketLoadMore.tsx b/apps/desktop/src/features/plugins/MarketLoadMore.tsx
new file mode 100644
index 000000000..3a7acdb68
--- /dev/null
+++ b/apps/desktop/src/features/plugins/MarketLoadMore.tsx
@@ -0,0 +1,62 @@
+import { useEffect, useRef } from "react";
+import type { TFunction } from "i18next";
+import { Button } from "../../components/ui";
+import { MARKET_PREFETCH_MARGIN } from "./market-paging";
+
+/**
+ * The end of the marketplace list. While more pages exist it asks for the next
+ * one as it approaches the viewport, and it always carries a button that does
+ * the same, for keyboard users and for retrying after a failed page. A failed
+ * page pauses the automatic request until the button is used.
+ */
+export function MarketLoadMore({
+ t,
+ loaded,
+ total,
+ hasMore,
+ loading,
+ failed,
+ onLoadMore,
+}: {
+ t: TFunction;
+ loaded: number;
+ total: number;
+ hasMore: boolean;
+ loading: boolean;
+ failed: boolean;
+ onLoadMore: () => void;
+}) {
+ const sentinel = useRef<HTMLDivElement>(null);
+ const onLoadMoreRef = useRef(onLoadMore);
+ onLoadMoreRef.current = onLoadMore;
+ const armed = hasMore && !loading && !failed;
+
+ useEffect(() => {
+ const node = sentinel.current;
+ if (!armed || !node || typeof IntersectionObserver === "undefined") return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) onLoadMoreRef.current();
+ },
+ { rootMargin: MARKET_PREFETCH_MARGIN },
+ );
+ observer.observe(node);
+ return () => observer.disconnect();
+ // `loaded` re-arms the observer after each page, so a sentinel that is
+ // still in view after an append asks for the next page too.
+ }, [armed, loaded]);
+
+ if (total === 0) return null;
+ return (
+ <div ref={sentinel} className="plugins-load-more">
+ <span className="plugins-result-count" aria-live="polite">
+ {t("plugins.loadedCount", { count: loaded, total })}
+ </span>
+ {hasMore ? (
+ <Button variant="secondary" size="sm" disabled={loading} onClick={onLoadMore}>
+ {loading ? t("plugins.loadingMore") : failed ? t("plugins.loadMoreRetry") : t("plugins.loadMore")}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/plugins/MarketplacePanel.tsx b/apps/desktop/src/features/plugins/MarketplacePanel.tsx
index ea2e32d13..5f9adf4e4 100644
--- a/apps/desktop/src/features/plugins/MarketplacePanel.tsx
+++ b/apps/desktop/src/features/plugins/MarketplacePanel.tsx
@@ -1,7 +1,9 @@
-import { Button, cx } from "../../components/ui";
+import { Button, Tooltip, cx } from "../../components/ui";
import { IconCheck, IconSearch, IconShield } from "../../components/icons";
import { PermissionChips, RatingChip } from "./presentation";
import { ReviewTicker } from "./ReviewTicker";
+import { MarketLoadMore } from "./MarketLoadMore";
+import { MARKET_SORTS, MARKET_SORT_LABEL_KEYS } from "./market-paging";
import {
formatDate,
monogram,
@@ -18,7 +20,15 @@ export function MarketplacePanel({
categories,
category,
setCategory,
+ sort,
+ setSort,
marketLoading,
+ marketLoadingMore,
+ marketLoadMoreFailed,
+ marketTotal,
+ marketHasMore,
+ loadMoreMarket,
+ browseOrigin,
market,
visibleMarket,
installedById,
@@ -29,39 +39,82 @@ export function MarketplacePanel({
reviewSummaries,
reviewTickers,
}: PluginsPageModel) {
+ const selected = category.toLowerCase();
return (
<div
id="plugins-panel-market"
role="tabpanel"
aria-labelledby="plugins-tab-market"
+ aria-busy={marketLoading || undefined}
className="plugins-panel"
>
- {categories.length > 1 ? (
+ <div className="plugins-browse-bar">
+ {categories.length > 0 ? (
+ <div
+ className="plugins-filters"
+ role="group"
+ aria-label={t("plugins.categories")}
+ >
+ <button
+ type="button"
+ className={cx("plugins-filter", !category && "active")}
+ aria-pressed={!category}
+ onClick={() => setCategory("")}
+ >
+ {t("plugins.categoryAll")}
+ </button>
+ {categories.map((facet) => {
+ const active = facet.id.toLowerCase() === selected;
+ return (
+ <button
+ key={facet.id}
+ type="button"
+ className={cx("plugins-filter", active && "active")}
+ aria-pressed={active}
+ onClick={() => setCategory(active ? "" : facet.id)}
+ >
+ {facet.id}
+ {facet.count > 0 ? (
+ <span className="plugins-filter-count">{facet.count}</span>
+ ) : null}
+ </button>
+ );
+ })}
+ </div>
+ ) : (
+ <span />
+ )}
<div
- className="plugins-filters"
- role="group"
- aria-label={t("plugins.categories")}
+ className="plugins-sort"
+ role="radiogroup"
+ aria-label={t("plugins.sortLabel")}
>
- <button
- type="button"
- className={cx("plugins-filter", !category && "active")}
- aria-pressed={!category}
- onClick={() => setCategory("")}
- >
- {t("plugins.categoryAll")}
- </button>
- {categories.map((value) => (
+ {MARKET_SORTS.map((value) => (
<button
key={value}
type="button"
- className={cx("plugins-filter", category === value && "active")}
- aria-pressed={category === value}
- onClick={() => setCategory(category === value ? "" : value)}
+ role="radio"
+ aria-checked={sort === value}
+ className={cx("plugins-sort-btn", sort === value && "active")}
+ onClick={() => setSort(value)}
>
- {value}
+ {t(MARKET_SORT_LABEL_KEYS[value])}
</button>
))}
</div>
+ </div>
+
+ {browseOrigin || marketTotal > 0 ? (
+ <div className="plugins-browse-meta" aria-live="polite">
+ <span className="plugins-result-count">
+ {t("plugins.browseTotal", { count: marketTotal })}
+ </span>
+ {browseOrigin === "local" ? (
+ <Tooltip label={t("plugins.sourceLocalHint")}>
+ <span className="plugins-source-chip">{t("plugins.sourceLocal")}</span>
+ </Tooltip>
+ ) : null}
+ </div>
) : null}
{marketLoading && market.length === 0 ? (
@@ -94,14 +147,17 @@ export function MarketplacePanel({
) : null}
<Button
variant="secondary"
- onClick={() => void refreshMarket(query, { refreshRemote: true })}
+ onClick={() => void refreshMarket({ refreshRemote: true })}
>
{t("plugins.refreshMarket")}
</Button>
</div>
</div>
) : (
- <div className="plugins-card-grid" role="list">
+ <div
+ className={cx("plugins-card-grid", marketLoading && "is-refreshing")}
+ role="list"
+ >
{visibleMarket.map((item) => {
const installed = installedById.get(item.id);
const upgradable = !!installed && !!item.updateAvailable;
@@ -217,6 +273,18 @@ export function MarketplacePanel({
})}
</div>
)}
+
+ {!marketLoading || market.length > 0 ? (
+ <MarketLoadMore
+ t={t}
+ loaded={market.length}
+ total={marketTotal}
+ hasMore={marketHasMore}
+ loading={marketLoadingMore}
+ failed={marketLoadMoreFailed}
+ onLoadMore={() => void loadMoreMarket()}
+ />
+ ) : null}
</div>
);
}
diff --git a/apps/desktop/src/features/plugins/browse-state.ts b/apps/desktop/src/features/plugins/browse-state.ts
index 1c8271f19..149673762 100644
--- a/apps/desktop/src/features/plugins/browse-state.ts
+++ b/apps/desktop/src/features/plugins/browse-state.ts
@@ -1,23 +1,37 @@
import { create } from "zustand";
+import type { MarketBrowseSort } from "@pi-desktop/shared";
import type { TabId } from "./model";
+import { newBrowseSeed } from "./market-paging";
-/** Retain only browsing choices across route unmounts, never dialogs or work. */
+/**
+ * Retain only browsing choices across route unmounts, never dialogs or work.
+ *
+ * The seed lives for the app session, so the recommended order a user scrolled
+ * through is still the same order when they come back to the tab. How many
+ * pages are loaded is not a choice and is not kept here.
+ */
export const usePluginBrowseState = create<{
tab: TabId;
installedQuery: string;
query: string;
category: string;
+ sort: MarketBrowseSort;
+ seed: number;
setTab: (tab: TabId) => void;
setInstalledQuery: (installedQuery: string) => void;
setQuery: (query: string) => void;
setCategory: (category: string) => void;
+ setSort: (sort: MarketBrowseSort) => void;
}>((set) => ({
tab: "installed",
installedQuery: "",
query: "",
category: "",
+ sort: "recommended",
+ seed: newBrowseSeed(),
setTab: (tab) => set({ tab }),
setInstalledQuery: (installedQuery) => set({ installedQuery }),
setQuery: (query) => set({ query }),
setCategory: (category) => set({ category }),
+ setSort: (sort) => set({ sort }),
}));
diff --git a/apps/desktop/src/features/plugins/market-paging.ts b/apps/desktop/src/features/plugins/market-paging.ts
new file mode 100644
index 000000000..84f6ac724
--- /dev/null
+++ b/apps/desktop/src/features/plugins/market-paging.ts
@@ -0,0 +1,70 @@
+import type {
+ MarketBrowseSort,
+ MarketCategoryFacet,
+ MarketPluginSummary,
+} from "@pi-desktop/shared";
+
+/** Cards fetched per request: four rows of the widest grid, six of the narrowest. */
+export const MARKET_PAGE_SIZE = 24;
+
+/** Start the next page this far before the end of the list comes into view. */
+export const MARKET_PREFETCH_MARGIN = "600px 0px";
+
+export const MARKET_SORTS: readonly MarketBrowseSort[] = [
+ "recommended",
+ "popular",
+ "updated",
+ "name",
+];
+
+export const MARKET_SORT_LABEL_KEYS: Record<MarketBrowseSort, string> = {
+ recommended: "plugins.sortRecommended",
+ popular: "plugins.sortPopular",
+ updated: "plugins.sortUpdated",
+ name: "plugins.sortName",
+};
+
+/** A positive 31-bit seed, so it survives JSON and every integer check. */
+export function newBrowseSeed(random: () => number = Math.random): number {
+ return 1 + Math.floor(random() * 0x7ffffffe);
+}
+
+/**
+ * Append a page to what is already on screen. A plugin that moved between
+ * pages while the user scrolled (a publish reordered the catalog) is kept
+ * where it was first shown rather than appearing twice.
+ */
+export function appendPage(
+ loaded: readonly MarketPluginSummary[],
+ page: readonly MarketPluginSummary[],
+): MarketPluginSummary[] {
+ const seen = new Set(loaded.map((plugin) => plugin.id));
+ const next = [...loaded];
+ for (const plugin of page) {
+ if (seen.has(plugin.id)) continue;
+ seen.add(plugin.id);
+ next.push(plugin);
+ }
+ return next;
+}
+
+/** Whether another page exists after `loadedPages` pages. */
+export function hasMorePages(loadedPages: number, pageCount: number): boolean {
+ return loadedPages > 0 && loadedPages < pageCount;
+}
+
+/**
+ * Category chips for the current answer. The selected category stays visible
+ * even when the current query no longer matches it, so the user can always
+ * see — and clear — the filter that is in effect.
+ */
+export function categoryChips(
+ facets: readonly MarketCategoryFacet[],
+ selected: string,
+): MarketCategoryFacet[] {
+ const chips = [...facets];
+ if (selected && !chips.some((chip) => chip.id.toLowerCase() === selected.toLowerCase())) {
+ chips.unshift({ id: selected, count: 0 });
+ }
+ return chips;
+}
diff --git a/apps/desktop/src/features/plugins/useMarketBrowse.ts b/apps/desktop/src/features/plugins/useMarketBrowse.ts
new file mode 100644
index 000000000..b89030f32
--- /dev/null
+++ b/apps/desktop/src/features/plugins/useMarketBrowse.ts
@@ -0,0 +1,187 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type {
+ MarketBrowseResult,
+ MarketCategoryFacet,
+ MarketPluginSummary,
+} from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import { usePluginBrowseState } from "./browse-state";
+import { isClientVisibleMarketPlugin } from "./model";
+import { MARKET_PAGE_SIZE, appendPage, categoryChips, hasMorePages } from "./market-paging";
+
+/** Typing waits this long before it asks; sorting and filtering do not. */
+export const MARKET_QUERY_DEBOUNCE_MS = 240;
+
+type Feed = {
+ items: MarketPluginSummary[];
+ loadedPages: number;
+ total: number;
+ pageCount: number;
+ facets: MarketCategoryFacet[];
+ source: MarketBrowseResult["source"] | null;
+};
+
+const EMPTY_FEED: Feed = {
+ items: [],
+ loadedPages: 0,
+ total: 0,
+ pageCount: 0,
+ facets: [],
+ source: null,
+};
+
+/**
+ * The marketplace as one growing list: the first page arrives when the query,
+ * category, sort or language changes, and every further page is appended as
+ * the user scrolls toward the end.
+ *
+ * A change of what is browsed starts a new generation. Answers carry the
+ * generation they were asked for, so a first page for an older query, or a
+ * next page still loading when the query changed, is dropped rather than mixed
+ * into the new list. Only one next-page request runs at a time, and a failed
+ * one stops automatic loading until the user retries, so an offline scroll
+ * does not turn into a stream of errors.
+ */
+export function useMarketBrowse({
+ active,
+ locale,
+ onError,
+}: {
+ active: boolean;
+ locale: string;
+ onError: (error: unknown) => void;
+}) {
+ const { query, category, sort, seed } = usePluginBrowseState();
+ const [feed, setFeed] = useState<Feed>(EMPTY_FEED);
+ const [loading, setLoading] = useState(false);
+ const [loadingMore, setLoadingMore] = useState(false);
+ const [loadMoreFailed, setLoadMoreFailed] = useState(false);
+ const generation = useRef(0);
+ const feedRef = useRef(feed);
+ feedRef.current = feed;
+ const moreInFlight = useRef(false);
+ const lastQuery = useRef<string | null>(null);
+ const onErrorRef = useRef(onError);
+ onErrorRef.current = onError;
+
+ const ask = useCallback(
+ (page: number) =>
+ api.marketBrowse({ query, category, sort, seed, page, pageSize: MARKET_PAGE_SIZE }),
+ [query, category, sort, seed],
+ );
+
+ /** Start a new generation from the first page. */
+ const reload = useCallback(async () => {
+ const id = ++generation.current;
+ moreInFlight.current = false;
+ setLoadingMore(false);
+ setLoadMoreFailed(false);
+ setLoading(true);
+ try {
+ const answer = await ask(1);
+ if (id !== generation.current) return;
+ setFeed({
+ items: appendPage([], answer.plugins.filter(isClientVisibleMarketPlugin)),
+ loadedPages: 1,
+ total: answer.total,
+ pageCount: answer.pageCount,
+ facets: answer.categories,
+ source: answer.source,
+ });
+ } catch (error) {
+ if (id === generation.current) onErrorRef.current(error);
+ } finally {
+ if (id === generation.current) setLoading(false);
+ }
+ }, [ask]);
+
+ /** Append the next page, if there is one and nothing else is loading it. */
+ const loadMore = useCallback(async () => {
+ const current = feedRef.current;
+ if (moreInFlight.current || !hasMorePages(current.loadedPages, current.pageCount)) return;
+ const id = generation.current;
+ moreInFlight.current = true;
+ setLoadingMore(true);
+ setLoadMoreFailed(false);
+ try {
+ const answer = await ask(current.loadedPages + 1);
+ if (id !== generation.current) return;
+ setFeed((previous) => ({
+ ...previous,
+ items: appendPage(previous.items, answer.plugins.filter(isClientVisibleMarketPlugin)),
+ loadedPages: previous.loadedPages + 1,
+ total: answer.total,
+ pageCount: answer.pageCount,
+ // A page from the snapshot after a remote first page still says so.
+ source: answer.source === "local" ? "local" : previous.source,
+ }));
+ } catch (error) {
+ if (id !== generation.current) return;
+ setLoadMoreFailed(true);
+ onErrorRef.current(error);
+ } finally {
+ if (id === generation.current) {
+ moreInFlight.current = false;
+ setLoadingMore(false);
+ }
+ }
+ }, [ask]);
+
+ // `locale` re-reads because plugin labels are resolved in the host
+ // (ADR 0160); otherwise the previous language stays on the cards.
+ useEffect(() => {
+ if (!active) return;
+ // Retire whatever is in flight now, not when the debounce fires: an answer
+ // for the previous query must not land during the typing window.
+ generation.current += 1;
+ const typed = lastQuery.current !== null && lastQuery.current !== query && query.trim() !== "";
+ lastQuery.current = query;
+ const handle = window.setTimeout(() => void reload(), typed ? MARKET_QUERY_DEBOUNCE_MS : 0);
+ return () => window.clearTimeout(handle);
+ }, [active, reload, locale, query]);
+
+ // Leaving the tab abandons any answer still in flight.
+ useEffect(() => {
+ if (active) return;
+ generation.current += 1;
+ moreInFlight.current = false;
+ setLoading(false);
+ setLoadingMore(false);
+ }, [active]);
+
+ /**
+ * Reflect an install on its card in place: reloading would throw away every
+ * page the user scrolled through to reach it.
+ */
+ const markInstalled = useCallback((id: string, version?: string) => {
+ setFeed((previous) => ({
+ ...previous,
+ items: previous.items.map((item) =>
+ item.id === id
+ ? {
+ ...item,
+ installed: true,
+ installedVersion: version ?? item.latestVersion,
+ updateAvailable: false,
+ }
+ : item,
+ ),
+ }));
+ }, []);
+
+ const categories = useMemo(() => categoryChips(feed.facets, category), [feed.facets, category]);
+
+ return {
+ market: feed.items,
+ marketLoading: loading,
+ marketLoadingMore: loadingMore,
+ marketLoadMoreFailed: loadMoreFailed,
+ marketTotal: feed.total,
+ marketHasMore: hasMorePages(feed.loadedPages, feed.pageCount),
+ browseOrigin: feed.source,
+ categories,
+ reloadMarket: reload,
+ loadMoreMarket: loadMore,
+ markMarketInstalled: markInstalled,
+ };
+}
diff --git a/apps/desktop/src/features/plugins/usePluginsPage.ts b/apps/desktop/src/features/plugins/usePluginsPage.ts
index 67d959f55..35c6c0bd2 100644
--- a/apps/desktop/src/features/plugins/usePluginsPage.ts
+++ b/apps/desktop/src/features/plugins/usePluginsPage.ts
@@ -4,6 +4,7 @@ import { useAppStore } from "../../stores/app-store";
import { api } from "../../lib/api";
import { useRowBusy } from "../../hooks/use-row-busy";
import { usePluginBrowseState } from "./browse-state";
+import { useMarketBrowse } from "./useMarketBrowse";
import type {
MarketPluginDetail,
MarketPluginSummary,
@@ -20,7 +21,6 @@ import {
TEMPLATE_IDS,
type TemplateId,
groupOf,
- isClientVisibleMarketPlugin,
matchesQuery,
orderPermissions,
versionInstallable,
@@ -51,10 +51,36 @@ export function usePluginsPage() {
*/
const currentProjectPath = useAppStore((s) => s.workspace?.path ?? null);
- const { tab, setTab, installedQuery, setInstalledQuery, query, setQuery, category, setCategory } = usePluginBrowseState();
+ const {
+ tab,
+ setTab,
+ installedQuery,
+ setInstalledQuery,
+ query,
+ setQuery,
+ category,
+ setCategory,
+ sort,
+ setSort,
+ } = usePluginBrowseState();
const [projects, setProjects] = useState<ProjectRecord[]>([]);
- const [market, setMarket] = useState<MarketPluginSummary[]>([]);
- const [marketLoading, setMarketLoading] = useState(false);
+ const {
+ market,
+ marketLoading,
+ marketLoadingMore,
+ marketLoadMoreFailed,
+ marketTotal,
+ marketHasMore,
+ browseOrigin,
+ categories,
+ reloadMarket,
+ loadMoreMarket,
+ markMarketInstalled,
+ } = useMarketBrowse({
+ active: tab === "market",
+ locale,
+ onError: (e) => showToast(e instanceof Error ? e.message : String(e), { variant: "error" }),
+ });
// One busy key per plugin row: the first request to settle must not re-arm
// a row that is still in flight, and a busy row does not lock the others
// (the same contract the capability pages pin).
@@ -139,10 +165,13 @@ export function usePluginsPage() {
setInstallJob(null);
};
- const refreshMarket = async (q = query, opts?: { refreshRemote?: boolean }) => {
- setMarketLoading(true);
- try {
- if (opts?.refreshRemote) {
+ /**
+ * Re-read the current page. An explicit refresh first pulls the catalog
+ * from the plugin center, which also drops the host's cached pages.
+ */
+ const refreshMarket = async (opts?: { refreshRemote?: boolean }) => {
+ if (opts?.refreshRemote) {
+ try {
const meta = await api.marketRefresh(true);
showToast(
t("plugins.marketRefreshed", {
@@ -151,14 +180,11 @@ export function usePluginsPage() {
}),
{ variant: "success" },
);
+ } catch (e) {
+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });
}
- const res = await api.marketSearch(q);
- setMarket((res.plugins ?? []).filter(isClientVisibleMarketPlugin));
- } catch (e) {
- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });
- } finally {
- setMarketLoading(false);
}
+ await reloadMarket();
};
const openDetail = async (id: string) => {
@@ -231,24 +257,8 @@ export function usePluginsPage() {
})();
}, [refreshPlugins]);
- // The marketplace query drives a debounced provider search: typing is the only
- // control, so there is no separate Search button that can fall out of sync.
- useEffect(() => {
- if (tab !== "market") return;
- const delay = query.trim() ? 240 : 0;
- const handle = window.setTimeout(() => void refreshMarket(query), delay);
- return () => window.clearTimeout(handle);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [tab, query]);
-
- // Plugin and catalog labels are resolved in the host, so a language switch
- // has to re-read the marketplace list; otherwise the previous language stays
- // on the cards until the user happens to type (ADR 0160).
- useEffect(() => {
- if (tab !== "market") return;
- void refreshMarket(query);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [locale]);
+ // The marketplace page (query, category, sort, page, locale) is loaded by
+ // useMarketBrowse: typing is debounced, every other control asks at once.
// Escape closes the detail sheet, but only while it owns the top layer: the
// permission dialog, the install dialog, and the review drawer in front of
@@ -437,21 +447,8 @@ export function usePluginsPage() {
});
}, [filteredInstalled]);
- const categories = useMemo(() => {
- const seen = new Set<string>();
- for (const item of market) {
- for (const value of item.categories ?? []) if (value) seen.add(value);
- }
- return [...seen].sort((a, b) => a.localeCompare(b));
- }, [market]);
-
- const visibleMarket = useMemo(
- () =>
- category
- ? market.filter((item) => (item.categories ?? []).includes(category))
- : market,
- [market, category],
- );
+ // The host filters by category, so the page is already what is visible.
+ const visibleMarket = market;
const activeVersion = useMemo(() => {
if (!detail?.versions?.length) return null;
@@ -665,7 +662,7 @@ export function usePluginsPage() {
grantedPermissions: request.grantedPermissions,
});
await refreshPlugins();
- await refreshMarket();
+ markMarketInstalled(request.id, request.version);
if (selectedId === request.id) await openDetail(request.id);
showToast(t("plugins.installed", { name: request.name }), {
variant: "success",
@@ -782,8 +779,16 @@ export function usePluginsPage() {
setQuery,
category,
setCategory,
+ sort,
+ setSort,
market,
marketLoading,
+ marketLoadingMore,
+ marketLoadMoreFailed,
+ marketTotal,
+ marketHasMore,
+ loadMoreMarket,
+ browseOrigin,
isPluginBusy: rowBusy.isBusy,
reloadingId,
pendingInstall,
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index fcf471cb1..d8d650c5c 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -77,6 +77,8 @@ import type {
PluginViewMeta,
PluginScenicThemesDestinationMeta,
PluginTheme,
+ MarketBrowseQuery,
+ MarketBrowseResult,
MarketPluginSummary,
MarketPluginDetail,
PluginInstallResult,
@@ -1606,6 +1608,9 @@ export const api = {
providerId: string;
sourceUrl: string;
}>(IPC.invoke.marketSearch, { query, category }),
+ /** One page of the marketplace; the host falls back to its snapshot offline. */
+ marketBrowse: (query: MarketBrowseQuery) =>
+ invoke<MarketBrowseResult>(IPC.invoke.marketBrowse, query),
marketGetDetail: (id: string) =>
invoke<{ plugin: MarketPluginDetail }>(IPC.invoke.marketGetDetail, id),
marketInstall: (input: {
diff --git a/apps/desktop/src/pages/PluginsPage.tsx b/apps/desktop/src/pages/PluginsPage.tsx
index ede35e84f..6cf2b6dab 100644
--- a/apps/desktop/src/pages/PluginsPage.tsx
+++ b/apps/desktop/src/pages/PluginsPage.tsx
@@ -27,7 +27,7 @@ export function PluginsPage() {
filteredInstalled,
setInstalledQuery,
marketLoading,
- market,
+ marketTotal,
showToast,
} = page;
@@ -62,7 +62,7 @@ export function PluginsPage() {
<Button
variant="primary"
size="sm"
- onClick={() => void refreshMarket(query, { refreshRemote: true })}
+ onClick={() => void refreshMarket({ refreshRemote: true })}
>
<IconCloudDown size={14} />
{t("plugins.refreshMarket")}
@@ -138,8 +138,8 @@ export function PluginsPage() {
onClick={() => setTab("market")}
>
{t("plugins.tabMarket")}
- {market.length ? (
- <span className="plugins-segment-count">{market.length}</span>
+ {marketTotal ? (
+ <span className="plugins-segment-count">{marketTotal}</span>
) : null}
</button>
</div>
diff --git a/apps/desktop/src/styles/plugins.css b/apps/desktop/src/styles/plugins.css
index 4caefdbeb..2fad6c189 100644
--- a/apps/desktop/src/styles/plugins.css
+++ b/apps/desktop/src/styles/plugins.css
@@ -997,6 +997,107 @@
color: var(--ds-text-primary);
}
+/* Browse bar: category chips on the left, sort pills on the right. */
+.plugins-browse-bar {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 10px 16px;
+ flex-wrap: wrap;
+}
+
+.plugins-browse-bar > .plugins-filters {
+ flex: 1 1 320px;
+ min-width: 0;
+}
+
+.plugins-filter-count {
+ margin-left: 6px;
+ color: var(--ds-text-muted);
+ font-size: var(--text-3xs);
+ font-variant-numeric: tabular-nums;
+}
+
+.plugins-filter.active .plugins-filter-count {
+ color: var(--ds-text-secondary);
+}
+
+.plugins-sort {
+ display: inline-flex;
+ align-items: center;
+ flex: 0 0 auto;
+ gap: 2px;
+ padding: 2px;
+ border-radius: var(--radius-full);
+ background: var(--plugins-tile);
+}
+
+.plugins-sort-btn {
+ height: 24px;
+ padding: 0 10px;
+ border-radius: var(--radius-full);
+ color: var(--ds-text-muted);
+ font-size: var(--text-xs-plus);
+ white-space: nowrap;
+ transition:
+ background var(--motion-duration-fast) var(--motion-ease-out),
+ color var(--motion-duration-fast) var(--motion-ease-out);
+}
+
+.plugins-sort-btn:hover {
+ color: var(--ds-text-primary);
+}
+
+.plugins-sort-btn.active {
+ background: var(--plugins-raised);
+ color: var(--ds-text-primary);
+ box-shadow: var(--plugins-raised-shadow);
+}
+
+/* Result line sits close under the bar it describes. */
+.plugins-browse-meta {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: -12px;
+}
+
+.plugins-source-chip {
+ display: inline-flex;
+ align-items: center;
+ height: 20px;
+ padding: 0 8px;
+ border-radius: var(--radius-full);
+ background: color-mix(in oklab, var(--ds-warning) 14%, transparent);
+ color: var(--ds-text-secondary);
+ font-size: var(--text-3xs);
+ cursor: default;
+}
+
+/* A page being replaced stays readable but visibly settling. */
+.plugins-card-grid.is-refreshing {
+ opacity: 0.55;
+ pointer-events: none;
+ transition: opacity var(--motion-duration-fast) var(--motion-ease-out);
+}
+
+/* End of the list: the loaded count, and a manual "load more" for keyboard
+ users and retries. The next page is fetched before this comes into view. */
+.plugins-load-more {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ padding: 4px 0 12px;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .plugins-card-grid.is-refreshing,
+ .plugins-sort-btn {
+ transition: none;
+ }
+}
+
.plugins-card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(272px, 1fr));
diff --git a/apps/desktop/test/extensions-page.test.mjs b/apps/desktop/test/extensions-page.test.mjs
index e88b71364..a27cfe4d4 100644
--- a/apps/desktop/test/extensions-page.test.mjs
+++ b/apps/desktop/test/extensions-page.test.mjs
@@ -118,7 +118,7 @@ test("marketplace keeps refresh and install actions without source switching", (
source,
/MarketplaceSourceSettings|pluginMarketSource|pluginMarketCustomUrl|marketProvider|marketCustomUrl|marketSource/,
);
- assert.match(marketPanelSrc, /refreshMarket\(query, \{ refreshRemote: true \}\)/);
+ assert.match(marketPanelSrc, /refreshMarket\(\{ refreshRemote: true \}\)/);
assert.match(marketPanelSrc, /queueInstall/);
});
@@ -141,7 +141,9 @@ test("extension row actions stay visible and labelled", () => {
test("the client hides development-only demo plugins from marketplace results", () => {
assert.match(pageSrc, /function isClientVisibleMarketPlugin/);
assert.match(pageSrc, /!plugin\.id\.startsWith\("demo\."\)/);
- assert.match(pageSrc, /setMarket\(\(res\.plugins \?\? \[\]\)\.filter\(isClientVisibleMarketPlugin\)\)/);
+ // The host already drops samples from a page; the client filter stays as a
+ // second line for a snapshot or center that does not.
+ assert.match(pageSrc, /answer\.plugins\.filter\(isClientVisibleMarketPlugin\)/);
});
test("Settings exposes three independent Agent capability destinations", () => {
diff --git a/apps/desktop/test/market-browse-render.test.mjs b/apps/desktop/test/market-browse-render.test.mjs
new file mode 100644
index 000000000..32c69bd84
--- /dev/null
+++ b/apps/desktop/test/market-browse-render.test.mjs
@@ -0,0 +1,168 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { createInstance } from "i18next";
+import { catalogs } from "@pi-desktop/i18n";
+import { createServer } from "vite";
+import { fileURLToPath } from "node:url";
+
+/*
+ * Marketplace paging: the pure pager/facet helpers, the browse-state
+ * transitions every control goes through, and the panel as it renders one
+ * page of a host answer. Loaded through Vite's SSR module graph so the real
+ * TypeScript sources are what run.
+ */
+
+const ROOT = fileURLToPath(new URL("..", import.meta.url));
+
+async function withModules(run) {
+ const server = await createServer({
+ root: ROOT,
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ esbuild: { jsx: "automatic" },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ try {
+ const paging = await server.ssrLoadModule("/src/features/plugins/market-paging.ts");
+ const { usePluginBrowseState } = await server.ssrLoadModule("/src/features/plugins/browse-state.ts");
+ const { MarketplacePanel } = await server.ssrLoadModule("/src/features/plugins/MarketplacePanel.tsx");
+ const i18n = createInstance();
+ await i18n.init({ lng: "en", resources: { en: { translation: catalogs.en } } });
+ await run({ paging, usePluginBrowseState, MarketplacePanel, t: i18n.t.bind(i18n) });
+ } finally {
+ await server.close();
+ }
+}
+
+test("appending a page keeps the first position of a plugin that moved between pages", async () => {
+ await withModules(({ paging: { appendPage, hasMorePages, categoryChips, newBrowseSeed } }) => {
+ const a = { id: "a" }, b = { id: "b" }, c = { id: "c" };
+ assert.deepEqual(appendPage([a, b], [b, c]).map((p) => p.id), ["a", "b", "c"]);
+ assert.deepEqual(appendPage([], [a]).map((p) => p.id), ["a"]);
+ assert.equal(hasMorePages(0, 3), false, "nothing loaded yet is not 'more'");
+ assert.equal(hasMorePages(1, 3), true);
+ assert.equal(hasMorePages(3, 3), false);
+ const facets = [{ id: "Tools", count: 3 }];
+ assert.deepEqual(categoryChips(facets, "tools"), facets);
+ assert.deepEqual(categoryChips(facets, "Writing"), [{ id: "Writing", count: 0 }, ...facets]);
+ assert.equal(newBrowseSeed(() => 0), 1);
+ assert.equal(newBrowseSeed(() => 1 - Number.EPSILON), 0x7ffffffe);
+ });
+});
+
+test("browse choices are kept and the session seed never changes", async () => {
+ await withModules(({ usePluginBrowseState }) => {
+ const state = () => usePluginBrowseState.getState();
+ const seed = state().seed;
+ assert.ok(Number.isInteger(seed) && seed > 0);
+ state().setQuery("todo");
+ state().setCategory("Tools");
+ state().setSort("popular");
+ assert.deepEqual([state().query, state().category, state().sort], ["todo", "Tools", "popular"]);
+ assert.equal(state().seed, seed);
+ });
+});
+
+function card(id, extra = {}) {
+ return {
+ id,
+ name: id,
+ description: `${id} description`,
+ author: "acme",
+ latestVersion: "1.0.0",
+ updatedAt: "2026-01-01T00:00:00Z",
+ categories: ["Tools"],
+ permissionSummary: [],
+ installable: true,
+ ...extra,
+ };
+}
+
+function model(t, overrides = {}) {
+ const market = [card("acme.one"), card("acme.two")];
+ return {
+ t,
+ locale: "en",
+ query: "",
+ setQuery: () => {},
+ refreshMarket: async () => {},
+ categories: [{ id: "Tools", count: 30 }, { id: "Writing", count: 4 }],
+ category: "",
+ setCategory: () => {},
+ sort: "recommended",
+ setSort: () => {},
+ marketLoading: false,
+ marketLoadingMore: false,
+ marketLoadMoreFailed: false,
+ marketTotal: 30,
+ marketHasMore: true,
+ loadMoreMarket: async () => {},
+ browseOrigin: "remote",
+ market,
+ visibleMarket: market,
+ installedById: new Map(),
+ selectedId: null,
+ openDetail: async () => {},
+ isPluginBusy: () => false,
+ queueInstall: () => {},
+ reviewSummaries: {},
+ reviewTickers: {},
+ ...overrides,
+ };
+}
+
+test("the list renders its facets, sort, total and an end-of-list loader", async () => {
+ await withModules(({ MarketplacePanel, t }) => {
+ const html = renderToStaticMarkup(createElement(MarketplacePanel, model(t)));
+ assert.match(html, />Tools<span class="plugins-filter-count">30<\/span>/);
+ assert.match(html, /role="radio" aria-checked="true" class="plugins-sort-btn active">Recommended</);
+ assert.match(html, /30 plugins/);
+ assert.equal((html.match(/class="plugins-card"/g) ?? []).length, 2);
+ assert.match(html, /class="plugins-load-more"/);
+ assert.match(html, /2 of 30 loaded/);
+ assert.match(html, />Load more</);
+ assert.doesNotMatch(html, /plugins-pager|plugins-source-chip/);
+ });
+});
+
+test("the loader reports loading and retry, and drops its button at the end", async () => {
+ await withModules(({ MarketplacePanel, t }) => {
+ const loading = renderToStaticMarkup(createElement(MarketplacePanel, model(t, { marketLoadingMore: true })));
+ assert.match(loading, /disabled="">Loading…</);
+ const failed = renderToStaticMarkup(createElement(MarketplacePanel, model(t, { marketLoadMoreFailed: true })));
+ assert.match(failed, />Retry loading</);
+ const done = renderToStaticMarkup(
+ createElement(MarketplacePanel, model(t, { marketHasMore: false, marketTotal: 2 })),
+ );
+ assert.match(done, /2 of 2 loaded/);
+ assert.doesNotMatch(done, />Load more</);
+ });
+});
+
+test("a snapshot answer is labelled and a refresh dims the list", async () => {
+ await withModules(({ MarketplacePanel, t }) => {
+ const html = renderToStaticMarkup(
+ createElement(MarketplacePanel, model(t, { browseOrigin: "local", marketLoading: true })),
+ );
+ assert.match(html, /class="plugins-source-chip">Saved catalog</);
+ assert.match(html, /aria-busy="true"/);
+ assert.match(html, /plugins-card-grid is-refreshing/);
+ });
+});
+
+test("an empty result offers to clear the filters that produced it", async () => {
+ await withModules(({ MarketplacePanel, t }) => {
+ const html = renderToStaticMarkup(
+ createElement(
+ MarketplacePanel,
+ model(t, { query: "nothing", market: [], visibleMarket: [], marketTotal: 0, marketHasMore: false }),
+ ),
+ );
+ assert.match(html, /No plugins matched your search/);
+ assert.match(html, /Clear search/);
+ assert.doesNotMatch(html, /plugins-load-more/);
+ });
+});
diff --git a/apps/desktop/test/market-browse-user-path.test.mjs b/apps/desktop/test/market-browse-user-path.test.mjs
new file mode 100644
index 000000000..fa07a6e0d
--- /dev/null
+++ b/apps/desktop/test/market-browse-user-path.test.mjs
@@ -0,0 +1,256 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+import { loadStyles } from "./helpers/styles.mjs";
+
+/*
+ * The marketplace browse path as a user drives it: open the tab, scroll to the
+ * end so the next pages load on their own, re-order, filter by category, retry
+ * a page that failed, then type a search — and an answer for something the user
+ * has since left (a first page or a next page) must never land in the list.
+ *
+ * The real Extensions page runs in a sandboxed Electron renderer. Only the
+ * preload bridge is stubbed: `market.browse` is answered by a small fake
+ * center that pages sixty plugins, so every request the page sends is the
+ * contract the host receives.
+ */
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+const fixture = String.raw`
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { IPC } from "@pi-desktop/shared";
+import { PluginsPage } from "../../apps/desktop/src/pages/PluginsPage";
+import { usePluginBrowseState } from "../../apps/desktop/src/features/plugins/browse-state";
+
+await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,
+ resources: { en: { translation: flattenCatalog(catalogs.en) } }, interpolation: { escapeValue: false } });
+const label = (key, options) => i18n.t("plugins." + key, options);
+
+const catalog = Array.from({ length: 60 }, (_, i) => ({
+ id: "acme.plugin-" + String(i + 1).padStart(2, "0"),
+ name: "Plugin " + (i + 1),
+ description: "Fixture plugin " + (i + 1),
+ author: "acme",
+ latestVersion: "1.0.0",
+ updatedAt: "2026-01-01T00:00:00Z",
+ categories: [i % 5 === 0 ? "Writing" : "Tools"],
+ permissionSummary: [],
+ installable: true,
+ downloads: 100 - i,
+}));
+const browseCalls = [];
+let hold = null;
+let failNext = null;
+function answer(input) {
+ const q = (input.query || "").toLowerCase();
+ const matches = catalog.filter((p) => !q || p.name.toLowerCase().includes(q));
+ const counts = new Map();
+ for (const p of matches) for (const c of p.categories) counts.set(c, (counts.get(c) || 0) + 1);
+ const filtered = matches.filter((p) => !input.category || p.categories.includes(input.category));
+ if (input.sort === "popular") filtered.sort((a, b) => b.downloads - a.downloads);
+ else if (input.sort === "name") filtered.sort((a, b) => a.name.localeCompare(b.name));
+ const size = input.pageSize || 24;
+ const page = input.page || 1;
+ return {
+ plugins: filtered.slice((page - 1) * size, page * size),
+ total: filtered.length, page, pageSize: size, pageCount: Math.ceil(filtered.length / size),
+ sort: input.sort || "recommended",
+ categories: [...counts].map(([id, count]) => ({ id, count })),
+ source: "remote", providerId: "official", sourceUrl: "https://center.invalid/catalog.json",
+ };
+}
+window.piDesktop = { platform: "darwin", channels: IPC,
+ on() { return () => {}; },
+ async invoke(channel, input) {
+ let data;
+ if (channel === IPC.invoke.marketBrowse) {
+ browseCalls.push(JSON.parse(JSON.stringify(input)));
+ if (hold && hold.match(input)) { const gate = hold; hold = null; await gate.promise; }
+ if (failNext && failNext(input)) { failNext = null; return { ok: false, error: { code: "PLUGIN_NETWORK", message: "center unreachable" } }; }
+ data = answer(input);
+ } else if (channel === IPC.invoke.listProjects) data = { projects: [] };
+ else if (channel === IPC.invoke.marketCheckUpdates) data = { updates: [], plugins: [] };
+ else if (channel === IPC.invoke.marketReviewSummaries) data = { summaries: {} };
+ else if (channel === IPC.invoke.marketReviewTickers) data = { tickers: {} };
+ else if (channel === IPC.invoke.pluginServices) data = [];
+ else if (channel === IPC.invoke.pluginList) data = { plugins: [] };
+ else data = {};
+ return { ok: true, data };
+ },
+};
+usePluginBrowseState.setState({ tab: "market" });
+
+const check = (value, message) => { if (!value) throw new Error(message); };
+const frame = () => new Promise(requestAnimationFrame);
+const until = async (condition, message) => {
+ const end = performance.now() + 5000;
+ while (!condition()) { if (performance.now() > end) throw new Error(message); await frame(); }
+};
+const cards = () => [...document.querySelectorAll(".plugins-card-name")].map((n) => n.textContent);
+const lastCall = () => browseCalls.at(-1);
+const byText = (selector, text) => [...document.querySelectorAll(selector)].find((n) => n.textContent.trim() === text);
+const click = async (node, message) => { check(node && !node.disabled, message); flushSync(() => node.click()); await frame(); };
+const type = async (value) => {
+ const input = document.querySelector('input[aria-label="' + label("marketSearchPlaceholder") + '"]');
+ check(input, "search field missing");
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await frame();
+};
+const settled = () => !document.querySelector("#plugins-panel-market[aria-busy]");
+
+createRoot(document.getElementById("root")).render(React.createElement(PluginsPage));
+
+const scrollEnd = async () => {
+ const end = document.querySelector(".plugins-load-more");
+ check(end, "end of list missing");
+ end.scrollIntoView({ block: "end" });
+ await frame();
+};
+const loaded = () => document.querySelector(".plugins-load-more .plugins-result-count")?.textContent ?? "";
+const gate = (match) => { let release; hold = { match, promise: new Promise((r) => { release = r; }) }; return () => release(); };
+const pages = (filter) => browseCalls.filter(filter).map((c) => c.page);
+
+window.marketProbe = async () => {
+ await until(() => cards().length >= 24 && settled(), "first page did not render");
+ const first = browseCalls[0];
+ check(first.page === 1 && first.pageSize === 24 && first.sort === "recommended", "first request " + JSON.stringify(first));
+ check(Number.isInteger(first.seed) && first.seed > 0, "no session seed");
+ check(document.body.textContent.includes(label("browseTotal", { count: 60 })), "total missing");
+ check(!document.querySelector(".plugins-pager"), "a pager must not render");
+
+ // Scrolling to the end loads the remaining pages on its own, in order.
+ for (let i = 0; i < 4 && cards().length < 60; i++) {
+ await scrollEnd();
+ await until(() => !document.querySelector(".plugins-load-more button[disabled]"), "next page did not settle");
+ }
+ await until(() => cards().length === 60, "pages did not append: " + cards().length);
+ check(new Set(cards()).size === 60, "a plugin appeared twice");
+ check(pages((c) => c.sort === "recommended").join() === "1,2,3", "pages " + pages((c) => c.sort === "recommended"));
+ check(browseCalls.every((c) => c.seed === first.seed), "seed changed while scrolling");
+ check(loaded() === label("loadedCount", { count: 60, total: 60 }), "loaded count " + loaded());
+ check(!document.querySelector(".plugins-load-more button"), "load more must leave at the end");
+
+ // A next page still loading when the sort changes must not join the new list.
+ const releaseNamePage = gate((c) => c.sort === "name" && c.page === 2);
+ await click(byText(".plugins-sort-btn", label("sortName")), "name sort missing");
+ await until(() => lastCall().sort === "name" && settled(), "name sort not requested");
+ await scrollEnd();
+ await until(() => browseCalls.some((c) => c.sort === "name" && c.page === 2), "name page two not requested");
+ await click(byText(".plugins-sort-btn", label("sortPopular")), "popular sort missing");
+ await until(() => lastCall().sort === "popular" && lastCall().page === 1 && settled(), "popular not requested");
+ check(lastCall().page === 1 || browseCalls.at(-2)?.page === 1, "sorting must restart the list");
+ // Popular is Plugin 1, 2, 3… in order; any name-sorted card from the stale
+ // page would break that run.
+ const popularRun = () => cards().every((name, i) => name === "Plugin " + (i + 1));
+ releaseNamePage();
+ await new Promise((r) => setTimeout(r, 150));
+ await frame();
+ check(popularRun(), "a stale next page joined the new list: " + cards().slice(0, 30).join(","));
+
+ // A failed page pauses automatic loading until the user retries.
+ failNext = (c) => c.sort === "popular" && c.page === 2;
+ await scrollEnd();
+ const retry = () => byText(".plugins-load-more button", label("loadMoreRetry"));
+ await until(() => retry(), "retry did not appear");
+ const before = browseCalls.length;
+ await scrollEnd();
+ await new Promise((r) => setTimeout(r, 100));
+ check(browseCalls.length === before, "a failed page must not be retried on its own");
+ await click(retry(), "retry unavailable");
+ await until(() => cards().length >= 48, "retry did not load the page");
+
+ await click(byText(".plugins-sort-btn", label("sortRecommended")), "recommended missing");
+ const writing = [...document.querySelectorAll(".plugins-filter")].find((n) => n.textContent.startsWith("Writing"));
+ check(writing?.querySelector(".plugins-filter-count")?.textContent === "12", "category count missing");
+ await click(writing, "writing chip missing");
+ await until(() => lastCall().category === "Writing" && cards().length === 12 && settled(), "category not applied");
+ await click([...document.querySelectorAll(".plugins-filter")].find((n) => n.textContent.trim() === label("categoryAll")), "all chip missing");
+ await until(() => lastCall().category === "" && settled(), "category not cleared");
+
+ // A slow first page for an earlier search must not land over the latest one.
+ const releaseSearch = gate((c) => c.query === "plugin 1");
+ await type("plugin 1");
+ await until(() => lastCall().query === "plugin 1", "first search not sent");
+ await type("plugin 2");
+ await until(() => lastCall().query === "plugin 2" && settled(), "second search did not settle");
+ const latest = cards().join(",");
+ releaseSearch();
+ await new Promise((r) => setTimeout(r, 100));
+ await frame();
+ check(cards().join(",") === latest, "stale search replaced the latest: " + cards().join(","));
+ check(cards().includes("Plugin 2") && cards().includes("Plugin 20") && !cards().includes("Plugin 1"), "wrong results " + latest);
+ return { passed: true, requests: browseCalls.length };
+};
+`;
+
+test("marketplace browse user path pages, sorts, filters and searches without stale answers", {
+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,
+}, async () => {
+ const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "market-browse-"));
+ try {
+ await build({
+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },
+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ loader: { ".css": "empty", ".svg": "dataurl", ".png": "dataurl" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),
+ "@pi-desktop/shared": join(root, "packages/shared/src"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(join(temp, "styles.css"), (await loadStyles()).replace(/@theme(?: inline)?\s*\{/g, ":root {"));
+ await writeFile(join(temp, "index.html"), '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'; img-src \'self\' data:"><link rel="stylesheet" href="styles.css"><div id="root"></div><script type="module" src="renderer.js"></script>');
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow, session } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ session.defaultSession.webRequest.onBeforeRequest({ urls: ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"] }, (_details, callback) => callback({ cancel: true }));
+ const win = new BrowserWindow({ show: false, width: 1100, height: 700,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ win.webContents.on("console-message", (event) => console.log("RENDERER " + event.message));
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ console.log("MARKET_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.marketProbe()")));
+ app.exit(0);
+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }
+});`);
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => { output += chunk; });
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });
+ } finally { clearTimeout(timer); }
+ assert.equal(code, 0, output.slice(-6000));
+ assert.match(output, /MARKET_PROBE \{"passed":true/);
+ } finally {
+ await rm(temp, { recursive: true, force: true });
+ }
+});
diff --git a/apps/desktop/test/market-review-ipc.test.mjs b/apps/desktop/test/market-review-ipc.test.mjs
index b5b67106d..a1469372b 100644
--- a/apps/desktop/test/market-review-ipc.test.mjs
+++ b/apps/desktop/test/market-review-ipc.test.mjs
@@ -166,3 +166,47 @@ test("review reads require a running host", async () => {
message: "host unavailable",
});
});
+
+test("browse forwards only the shaped query and returns the host page unchanged", async () => {
+ assert.equal(IPC.invoke.marketBrowse, "pi-desktop/market/browse");
+ assert.equal(IPC_WHITELIST.has(IPC.invoke.marketBrowse), true);
+ const page = { plugins: [], total: 0, page: 1, pageSize: 24, pageCount: 0, source: "remote" };
+ const { invoke, calls } = setup({ "market.browse": page });
+ const answer = await invoke(IPC.invoke.marketBrowse, {
+ query: "todo",
+ category: "Tools",
+ sort: "popular",
+ seed: 42,
+ page: 3,
+ pageSize: 24,
+ extra: "dropped",
+ });
+ assert.equal(answer, page);
+ assert.deepEqual(calls, [
+ {
+ method: "market.browse",
+ params: { query: "todo", category: "Tools", sort: "popular", seed: 42, page: 3, pageSize: 24 },
+ },
+ ]);
+});
+
+test("browse drops malformed fields instead of passing them to the host", async () => {
+ const { invoke, calls } = setup({ "market.browse": {} });
+ await invoke(IPC.invoke.marketBrowse, { query: 7, sort: null, seed: -1, page: 1.5, pageSize: "24" });
+ await invoke(IPC.invoke.marketBrowse);
+ for (const call of calls) {
+ assert.deepEqual(call.params, {
+ query: "",
+ category: "",
+ sort: "",
+ seed: undefined,
+ page: undefined,
+ pageSize: undefined,
+ });
+ }
+});
+
+test("browse without a host rejects instead of answering an empty page", async () => {
+ const { invoke } = setup({}, { host: false });
+ await assert.rejects(() => invoke(IPC.invoke.marketBrowse, {}), /host unavailable/);
+});
diff --git a/apps/desktop/test/settings-general.test.mjs b/apps/desktop/test/settings-general.test.mjs
index a5e2752bd..7b6875afb 100644
--- a/apps/desktop/test/settings-general.test.mjs
+++ b/apps/desktop/test/settings-general.test.mjs
@@ -592,7 +592,7 @@ test("Plugins marketplace keeps official refresh without source settings", () =>
/MarketplaceSourceSettings|pluginMarketSource|pluginMarketCustomUrl|marketProvider|marketCustomUrl|marketSource/,
);
assert.match(pluginsPageSource, /api\.marketRefresh\(true\)/);
- assert.match(pluginsPageSource, /refreshMarket\(query, \{ refreshRemote: true \}\)/);
+ assert.match(pluginsPageSource, /refreshMarket\(\{ refreshRemote: true \}\)/);
assert.doesNotMatch(settingsPageSource, /ExtensionMarketSection/);
assert.doesNotMatch(settingsPageSource, /tab === "extensions"/);
});
diff --git a/apps/desktop/test/utility-navigation.test.mjs b/apps/desktop/test/utility-navigation.test.mjs
index 854d33d8e..7f0de2869 100644
--- a/apps/desktop/test/utility-navigation.test.mjs
+++ b/apps/desktop/test/utility-navigation.test.mjs
@@ -104,6 +104,6 @@ test("plugin browsing choices survive subscribers disconnecting without retainin
assert.equal(reopened.installedQuery, "local");
assert.equal(reopened.category, "productivity");
assert.deepEqual(Object.keys(reopened).filter((key) => typeof reopened[key] !== "function").sort(),
- ["category", "installedQuery", "query", "tab"]);
+ ["category", "installedQuery", "query", "seed", "sort", "tab"]);
} finally { usePluginBrowseState.setState(before, true); }
});
diff --git a/crates/host-core/src/plugins.rs b/crates/host-core/src/plugins.rs
index 4d23e4b9b..96f3d365e 100644
--- a/crates/host-core/src/plugins.rs
+++ b/crates/host-core/src/plugins.rs
@@ -20,6 +20,7 @@ pub(crate) const MAX_PACKAGE_FILES: usize = 2000;
mod device;
mod install;
mod manifest;
+pub(crate) mod market_browse;
pub mod marketplace;
mod model;
mod permissions;
diff --git a/crates/host-core/src/plugins/market_browse.rs b/crates/host-core/src/plugins/market_browse.rs
new file mode 100644
index 000000000..6bd89e7e2
--- /dev/null
+++ b/crates/host-core/src/plugins/market_browse.rs
@@ -0,0 +1,794 @@
+//! Paged marketplace browsing (`market.browse`).
+//!
+//! The plugin center answers one page of its catalog at
+//! `/api/v1/catalog/search`, so the Extensions surface does not have to hold
+//! the whole marketplace to show a page of it. The entries it returns are the
+//! same shape `catalog.json` carries; the host resolves their package URLs
+//! against the catalog source and maps them to summaries exactly as it does
+//! for the full document, so trust, install and update rules stay in one place.
+//!
+//! A center that predates the route, an unreachable one, or a source that is
+//! not an http(s) center (a git mirror or a local file) falls back to paging
+//! the last valid catalog snapshot with the same query semantics. Remote pages
+//! are cached in-process for a minute, and a center that does not serve the
+//! route is remembered for five, so browsing an older center does not cost a
+//! failed request per keystroke.
+
+use std::collections::{BTreeMap, HashMap};
+use std::sync::{Mutex, OnceLock};
+use std::time::Instant;
+
+use super::reviews::{encode_component, get_json_limited, review_origin_for_catalog};
+use super::*;
+
+pub(crate) const DEFAULT_PAGE_SIZE: u32 = 24;
+pub(crate) const MAX_PAGE_SIZE: u32 = 60;
+const MAX_QUERY_CHARS: usize = 200;
+const MAX_CATEGORY_CHARS: usize = 100;
+/// A page carries complete entries including readmes; larger is broken.
+pub(crate) const MAX_BROWSE_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
+pub(crate) const BROWSE_CACHE_TTL: Duration = Duration::from_secs(60);
+const BROWSE_UNSUPPORTED_TTL: Duration = Duration::from_secs(300);
+/// An unreachable center is not asked again for this long, so typing offline
+/// answers from the snapshot at once instead of waiting out each timeout.
+const BROWSE_UNREACHABLE_TTL: Duration = Duration::from_secs(30);
+const BROWSE_CACHE_ENTRIES: usize = 64;
+
+/// Orders a browse can ask for. The names are the center's wire values.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum BrowseSort {
+ Recommended,
+ Popular,
+ Updated,
+ Name,
+}
+
+impl BrowseSort {
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ Self::Recommended => "recommended",
+ Self::Popular => "popular",
+ Self::Updated => "updated",
+ Self::Name => "name",
+ }
+ }
+
+ fn parse(value: &str) -> Self {
+ match value.trim() {
+ "popular" => Self::Popular,
+ "updated" => Self::Updated,
+ "name" => Self::Name,
+ _ => Self::Recommended,
+ }
+ }
+}
+
+/// One normalized browse request.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct MarketBrowseQuery {
+ pub(crate) query: String,
+ pub(crate) category: String,
+ pub(crate) sort: BrowseSort,
+ pub(crate) seed: u32,
+ pub(crate) page: u32,
+ pub(crate) page_size: u32,
+}
+
+impl MarketBrowseQuery {
+ /// Read RPC params leniently: a browse is never worth an error, so a
+ /// malformed field falls back to its default and an oversized one is
+ /// clamped.
+ pub(crate) fn from_params(params: &Value) -> Self {
+ let text = |key: &str, max: usize| -> String {
+ let raw = params.get(key).and_then(Value::as_str).unwrap_or("");
+ // Control characters are never meaningful in a search and would
+ // collide with the cache-key separator.
+ raw.replace(|c: char| c.is_control(), " ")
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+ .chars()
+ .take(max)
+ .collect()
+ };
+ let number = |key: &str| params.get(key).and_then(Value::as_u64);
+ Self {
+ query: text("query", MAX_QUERY_CHARS),
+ category: text("category", MAX_CATEGORY_CHARS),
+ sort: BrowseSort::parse(params.get("sort").and_then(Value::as_str).unwrap_or("")),
+ seed: number("seed")
+ .and_then(|seed| u32::try_from(seed).ok())
+ .unwrap_or(0),
+ page: number("page")
+ .and_then(|page| u32::try_from(page).ok())
+ .filter(|page| *page >= 1)
+ .unwrap_or(1),
+ page_size: number("pageSize")
+ .and_then(|size| u32::try_from(size).ok())
+ .filter(|size| *size >= 1)
+ .map(|size| size.min(MAX_PAGE_SIZE))
+ .unwrap_or(DEFAULT_PAGE_SIZE),
+ }
+ }
+
+ fn cache_key(&self, catalog_url: &str) -> String {
+ format!(
+ "{catalog_url}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}",
+ self.query.to_lowercase(),
+ self.category.to_lowercase(),
+ self.sort.as_str(),
+ self.seed,
+ self.page,
+ self.page_size
+ )
+ }
+}
+
+/// One category and how many of the query's matches carry it.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MarketCategoryFacet {
+ pub id: String,
+ pub count: u64,
+}
+
+/// Entries of one page, before the host maps them to summaries.
+#[derive(Clone, Debug, Default)]
+pub(crate) struct BrowsePage {
+ pub(crate) entries: Vec<MarketCatalogEntry>,
+ pub(crate) total: u64,
+ pub(crate) categories: Vec<MarketCategoryFacet>,
+}
+
+/// Where a page came from.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum BrowseSource {
+ Remote,
+ Local,
+}
+
+/// The `market.browse` answer.
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MarketBrowseResult {
+ pub plugins: Vec<MarketPluginSummary>,
+ pub total: u64,
+ pub page: u32,
+ pub page_size: u32,
+ pub page_count: u32,
+ pub sort: &'static str,
+ pub categories: Vec<MarketCategoryFacet>,
+ /// `remote` for a page the center answered, `local` for the snapshot.
+ pub source: &'static str,
+ /// Why the remote page was not used, when the snapshot answered instead.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub fallback_reason: Option<String>,
+ pub provider_id: String,
+ pub source_url: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct BrowseWire {
+ total: u64,
+ #[serde(default)]
+ categories: Vec<MarketCategoryFacet>,
+ plugins: Vec<MarketCatalogEntry>,
+ #[serde(default)]
+ artifact_base_url: Option<String>,
+}
+
+#[derive(Default)]
+struct BrowseCache {
+ pages: HashMap<String, (Instant, BrowsePage)>,
+ /// Catalog sources whose center does not serve the route, and since when.
+ unsupported: HashMap<String, Instant>,
+ /// Catalog sources whose center could not be reached, and since when.
+ unreachable: HashMap<String, Instant>,
+}
+
+fn browse_cache() -> &'static Mutex<BrowseCache> {
+ static CACHE: OnceLock<Mutex<BrowseCache>> = OnceLock::new();
+ CACHE.get_or_init(|| Mutex::new(BrowseCache::default()))
+}
+
+fn with_cache<T>(f: impl FnOnce(&mut BrowseCache) -> T) -> T {
+ let mut guard = browse_cache()
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ f(&mut guard)
+}
+
+/// Forget every cached page. An explicit marketplace refresh calls this, so
+/// "refresh" never answers with a page from before it.
+pub(crate) fn clear_browse_cache() {
+ with_cache(|cache| {
+ cache.pages.clear();
+ cache.unsupported.clear();
+ cache.unreachable.clear();
+ });
+}
+
+/// An entry a fresh remote page carried for this source.
+///
+/// The detail sheet opens from a card, and a card may come from a remote page
+/// newer than the local snapshot; this keeps the detail readable offline of
+/// the snapshot until the next refresh catches up.
+pub(crate) fn cached_browse_entry(
+ catalog_url: &str,
+ plugin_id: &str,
+) -> Option<MarketCatalogEntry> {
+ let prefix = format!("{catalog_url}\u{1f}");
+ with_cache(|cache| {
+ cache
+ .pages
+ .iter()
+ .filter(|(key, (at, _))| key.starts_with(&prefix) && at.elapsed() < BROWSE_CACHE_TTL)
+ .filter_map(|(_, (at, page))| {
+ page.entries
+ .iter()
+ .find(|e| e.id == plugin_id)
+ .map(|entry| (*at, entry))
+ })
+ // Several pages may carry the plugin; the newest answer wins.
+ .max_by_key(|(at, _)| *at)
+ .map(|(_, entry)| entry.clone())
+ })
+}
+
+/// Search URL for one query on the trusted origin.
+pub(crate) fn browse_url(origin: &str, query: &MarketBrowseQuery) -> String {
+ let mut url = format!(
+ "{origin}/api/v1/catalog/search?sort={}&page={}&pageSize={}",
+ query.sort.as_str(),
+ query.page,
+ query.page_size
+ );
+ if query.seed != 0 {
+ url.push_str(&format!("&seed={}", query.seed));
+ }
+ if !query.query.is_empty() {
+ url.push_str("&q=");
+ url.push_str(&encode_component(&query.query));
+ }
+ if !query.category.is_empty() {
+ url.push_str("&category=");
+ url.push_str(&encode_component(&query.category));
+ }
+ url
+}
+
+/// Read one page from the center, through the in-process cache.
+///
+/// `catalog_url` is the effective catalog source: the origin is derived from
+/// it, and relative package URLs resolve against it exactly as the full
+/// catalog's do.
+pub(crate) fn fetch_remote_page(
+ catalog_url: &str,
+ query: &MarketBrowseQuery,
+) -> Result<BrowsePage> {
+ let origin = review_origin_for_catalog(catalog_url).ok_or_else(|| {
+ anyhow!("PLUGIN_MARKET_UNSUPPORTED: the catalog source is not a plugin center")
+ })?;
+ let key = query.cache_key(catalog_url);
+ let cached = with_cache(|cache| {
+ if let Some(since) = cache.unsupported.get(catalog_url) {
+ if since.elapsed() < BROWSE_UNSUPPORTED_TTL {
+ return Some(Err(anyhow!(
+ "PLUGIN_MARKET_UNSUPPORTED: the plugin center does not serve paged search"
+ )));
+ }
+ }
+ if let Some(since) = cache.unreachable.get(catalog_url) {
+ if since.elapsed() < BROWSE_UNREACHABLE_TTL {
+ return Some(Err(anyhow!(
+ "PLUGIN_NETWORK: the plugin center was unreachable moments ago"
+ )));
+ }
+ }
+ cache
+ .pages
+ .get(&key)
+ .filter(|(at, _)| at.elapsed() < BROWSE_CACHE_TTL)
+ .map(|(_, page)| Ok(page.clone()))
+ });
+ if let Some(answer) = cached {
+ return answer;
+ }
+
+ let url = browse_url(&origin, query);
+ let (status, payload) =
+ match get_json_limited(&url, MAX_BROWSE_RESPONSE_BYTES, "marketplace search") {
+ Ok(answer) => answer,
+ Err(error) => {
+ with_cache(|cache| {
+ cache
+ .unreachable
+ .insert(catalog_url.to_string(), Instant::now());
+ });
+ return Err(error);
+ }
+ };
+ if status == 404 || status == 405 {
+ with_cache(|cache| {
+ cache
+ .unsupported
+ .insert(catalog_url.to_string(), Instant::now());
+ });
+ bail!("PLUGIN_MARKET_UNSUPPORTED: the plugin center does not serve paged search");
+ }
+ if status != 200 {
+ with_cache(|cache| {
+ cache
+ .unreachable
+ .insert(catalog_url.to_string(), Instant::now());
+ });
+ bail!("PLUGIN_NETWORK: the plugin center answered marketplace search with http {status}");
+ }
+ let page = parse_remote_page(catalog_url, query, &payload)?;
+ with_cache(|cache| {
+ if cache.pages.len() >= BROWSE_CACHE_ENTRIES {
+ cache
+ .pages
+ .retain(|_, (at, _)| at.elapsed() < BROWSE_CACHE_TTL);
+ if cache.pages.len() >= BROWSE_CACHE_ENTRIES {
+ cache.pages.clear();
+ }
+ }
+ cache.pages.insert(key, (Instant::now(), page.clone()));
+ });
+ Ok(page)
+}
+
+/// Validate a center answer and resolve its package URLs.
+pub(crate) fn parse_remote_page(
+ catalog_url: &str,
+ query: &MarketBrowseQuery,
+ payload: &[u8],
+) -> Result<BrowsePage> {
+ let wire: BrowseWire = serde_json::from_slice(payload).map_err(|error| {
+ anyhow!("PLUGIN_MARKET_INVALID: the plugin center's search answer is not readable: {error}")
+ })?;
+ if wire.plugins.len() > query.page_size as usize {
+ bail!("PLUGIN_MARKET_INVALID: the plugin center returned more plugins than the page size");
+ }
+ if (wire.plugins.len() as u64) > wire.total {
+ bail!("PLUGIN_MARKET_INVALID: the plugin center's search total is smaller than its page");
+ }
+ let base = wire.artifact_base_url;
+ let mut entries = Vec::with_capacity(wire.plugins.len());
+ for mut entry in wire.plugins {
+ if entry.id.trim().is_empty() {
+ bail!("PLUGIN_MARKET_INVALID: the plugin center returned a plugin without an id");
+ }
+ for version in &mut entry.versions {
+ version.url =
+ PluginManager::resolve_package_url(catalog_url, base.as_deref(), &version.url);
+ }
+ entries.push(entry);
+ }
+ Ok(BrowsePage {
+ entries,
+ total: wire.total,
+ categories: wire
+ .categories
+ .into_iter()
+ .filter(|facet| !facet.id.trim().is_empty())
+ .collect(),
+ })
+}
+
+/// Page a catalog snapshot with the center's query semantics.
+///
+/// The order of a seeded shuffle differs from the center's — only its
+/// stability across pages matters — while filtering, facets, the other sorts
+/// and paging agree.
+pub(crate) fn local_browse(catalog: &MarketCatalogFile, query: &MarketBrowseQuery) -> BrowsePage {
+ let tokens: Vec<String> = query
+ .query
+ .to_lowercase()
+ .split_whitespace()
+ .map(str::to_string)
+ .collect();
+ let mut facets: BTreeMap<String, MarketCategoryFacet> = BTreeMap::new();
+ let mut hits: Vec<(u32, &MarketCatalogEntry)> = Vec::new();
+ for entry in &catalog.plugins {
+ if entry.id.starts_with("demo.") {
+ continue;
+ }
+ let Some(score) = match_score(entry, &tokens) else {
+ continue;
+ };
+ let mut seen = Vec::new();
+ for category in &entry.categories {
+ let category = category.trim();
+ let key = category.to_lowercase();
+ if category.is_empty() || seen.contains(&key) {
+ continue;
+ }
+ seen.push(key.clone());
+ facets
+ .entry(key)
+ .and_modify(|facet| facet.count += 1)
+ .or_insert_with(|| MarketCategoryFacet {
+ id: category.to_string(),
+ count: 1,
+ });
+ }
+ if !query.category.is_empty()
+ && !entry
+ .categories
+ .iter()
+ .any(|c| c.trim().eq_ignore_ascii_case(&query.category))
+ {
+ continue;
+ }
+ hits.push((score, entry));
+ }
+
+ hits.sort_by(|a, b| a.1.id.cmp(&b.1.id));
+ let by_name = |a: &MarketCatalogEntry, b: &MarketCatalogEntry| {
+ a.name
+ .to_lowercase()
+ .cmp(&b.name.to_lowercase())
+ .then_with(|| a.id.cmp(&b.id))
+ };
+ match query.sort {
+ BrowseSort::Popular => hits.sort_by(|a, b| {
+ b.1.downloads
+ .unwrap_or(0)
+ .cmp(&a.1.downloads.unwrap_or(0))
+ .then_with(|| by_name(a.1, b.1))
+ }),
+ BrowseSort::Updated => hits.sort_by(|a, b| {
+ latest_published(b.1)
+ .cmp(latest_published(a.1))
+ .then_with(|| by_name(a.1, b.1))
+ }),
+ BrowseSort::Name => hits.sort_by(|a, b| by_name(a.1, b.1)),
+ BrowseSort::Recommended => {
+ seeded_shuffle(
+ &mut hits,
+ if query.seed == 0 {
+ 0x9e37_79b9
+ } else {
+ query.seed
+ },
+ );
+ if !tokens.is_empty() {
+ hits.sort_by_key(|hit| std::cmp::Reverse(hit.0));
+ }
+ }
+ }
+
+ let total = hits.len() as u64;
+ let start = (query.page.saturating_sub(1) as usize).saturating_mul(query.page_size as usize);
+ let entries = hits
+ .into_iter()
+ .skip(start)
+ .take(query.page_size as usize)
+ .map(|(_, entry)| entry.clone())
+ .collect();
+ let mut categories: Vec<MarketCategoryFacet> = facets.into_values().collect();
+ categories.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.id.cmp(&b.id)));
+ BrowsePage {
+ entries,
+ total,
+ categories,
+ }
+}
+
+/// Every token must match; a name or id hit outranks a description hit.
+fn match_score(entry: &MarketCatalogEntry, tokens: &[String]) -> Option<u32> {
+ if tokens.is_empty() {
+ return Some(0);
+ }
+ let mut names = vec![entry.id.to_lowercase(), entry.name.to_lowercase()];
+ let mut rest = vec![
+ entry.description.to_lowercase(),
+ entry.author.to_lowercase(),
+ ];
+ rest.extend(entry.categories.iter().map(|c| c.to_lowercase()));
+ if let Some(map) = entry.i18n.as_ref() {
+ for text in map.values() {
+ if let Some(name) = &text.name {
+ names.push(name.to_lowercase());
+ }
+ if let Some(description) = &text.description {
+ rest.push(description.to_lowercase());
+ }
+ }
+ }
+ let mut score = 0;
+ for token in tokens {
+ let best = names
+ .iter()
+ .map(|name| {
+ if name == token {
+ 100
+ } else if name.starts_with(token.as_str()) {
+ 60
+ } else if name.contains(token.as_str()) {
+ 40
+ } else {
+ 0
+ }
+ })
+ .max()
+ .unwrap_or(0);
+ let best = if best == 0 && rest.iter().any(|text| text.contains(token.as_str())) {
+ 10
+ } else {
+ best
+ };
+ if best == 0 {
+ return None;
+ }
+ score += best;
+ }
+ Some(score)
+}
+
+fn latest_published(entry: &MarketCatalogEntry) -> &str {
+ entry
+ .versions
+ .iter()
+ .filter(|version| !version.yanked)
+ .map(|version| version.published_at.as_str())
+ .max()
+ .unwrap_or("")
+}
+
+/// Fisher–Yates driven by xorshift32: deterministic for a seed, no RNG crate.
+fn seeded_shuffle<T>(items: &mut [T], seed: u32) {
+ let mut state = seed.max(1);
+ for i in (1..items.len()).rev() {
+ state ^= state << 13;
+ state ^= state >> 17;
+ state ^= state << 5;
+ let j = (state as usize) % (i + 1);
+ items.swap(i, j);
+ }
+}
+
+impl PluginManager {
+ /// The effective catalog source, for a browse that runs off the state lock.
+ pub(crate) fn browse_catalog_url(&self) -> String {
+ self.market_source_url()
+ }
+
+ /// Page the last valid catalog snapshot. Never touches the network.
+ pub(crate) fn market_browse_local(&self, query: &MarketBrowseQuery) -> Result<BrowsePage> {
+ let catalog = self.load_cached_catalog()?;
+ Ok(local_browse(&catalog, query))
+ }
+
+ /// Map a page to the answer the renderer renders.
+ pub(crate) fn market_browse_result(
+ &self,
+ query: &MarketBrowseQuery,
+ page: BrowsePage,
+ source: BrowseSource,
+ fallback_reason: Option<String>,
+ ) -> MarketBrowseResult {
+ let page_size = query.page_size.max(1);
+ let page_count =
+ u32::try_from(page.total.div_ceil(u64::from(page_size))).unwrap_or(u32::MAX);
+ MarketBrowseResult {
+ plugins: page
+ .entries
+ .iter()
+ .map(|entry| self.to_market_summary(entry))
+ .collect(),
+ total: page.total,
+ page: query.page,
+ page_size,
+ page_count,
+ sort: query.sort.as_str(),
+ categories: page.categories,
+ source: match source {
+ BrowseSource::Remote => "remote",
+ BrowseSource::Local => "local",
+ },
+ fallback_reason,
+ provider_id: self.channel().as_str().to_string(),
+ source_url: self.market_source_url(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(
+ id: &str,
+ name: &str,
+ description: &str,
+ downloads: u64,
+ published: &str,
+ categories: &[&str],
+ ) -> MarketCatalogEntry {
+ MarketCatalogEntry {
+ id: id.into(),
+ name: name.into(),
+ description: description.into(),
+ author: "acme".into(),
+ categories: categories.iter().map(|c| c.to_string()).collect(),
+ downloads: Some(downloads),
+ versions: vec![MarketVersion {
+ version: "1.0.0".into(),
+ published_at: published.into(),
+ url: "packages/x.piplug".into(),
+ shasum: "ab".repeat(32),
+ ..MarketVersion::default()
+ }],
+ ..MarketCatalogEntry::default()
+ }
+ }
+
+ fn fixture() -> MarketCatalogFile {
+ MarketCatalogFile {
+ plugins: vec![
+ entry(
+ "pi.todo",
+ "Todo",
+ "Task list",
+ 50,
+ "2026-01-03T00:00:00Z",
+ &["Productivity"],
+ ),
+ entry(
+ "pi.notes",
+ "Notes",
+ "Write notes and todo lists",
+ 80,
+ "2026-01-01T00:00:00Z",
+ &["productivity", "Writing"],
+ ),
+ entry(
+ "pi.browser",
+ "Browser",
+ "Drive a browser",
+ 10,
+ "2026-01-05T00:00:00Z",
+ &["Tools"],
+ ),
+ entry(
+ "pi.git",
+ "Git",
+ "Repository tools",
+ 30,
+ "2026-01-02T00:00:00Z",
+ &["Tools"],
+ ),
+ entry(
+ "demo.hello",
+ "Hello",
+ "Sample",
+ 999,
+ "2026-01-09T00:00:00Z",
+ &["Tools"],
+ ),
+ ],
+ ..MarketCatalogFile::default()
+ }
+ }
+
+ fn query(params: Value) -> MarketBrowseQuery {
+ MarketBrowseQuery::from_params(&params)
+ }
+
+ fn ids(page: &BrowsePage) -> Vec<&str> {
+ page.entries.iter().map(|e| e.id.as_str()).collect()
+ }
+
+ #[test]
+ fn params_are_normalized_and_clamped() {
+ let q = query(
+ json!({ "query": " a b ", "sort": "bogus", "page": 0, "pageSize": 9999, "seed": -1 }),
+ );
+ assert_eq!(q.query, "a b");
+ assert_eq!(q.sort, BrowseSort::Recommended);
+ assert_eq!((q.page, q.page_size, q.seed), (1, MAX_PAGE_SIZE, 0));
+ let q = query(json!({}));
+ assert_eq!((q.page, q.page_size), (1, DEFAULT_PAGE_SIZE));
+ }
+
+ #[test]
+ fn local_pages_cover_every_plugin_once_and_skip_samples() {
+ let catalog = fixture();
+ let mut seen = Vec::new();
+ for page in 1..=3 {
+ let got = local_browse(
+ &catalog,
+ &query(json!({ "seed": 7, "page": page, "pageSize": 2 })),
+ );
+ assert_eq!(got.total, 4);
+ seen.extend(ids(&got).into_iter().map(str::to_string));
+ }
+ seen.sort();
+ assert_eq!(seen, ["pi.browser", "pi.git", "pi.notes", "pi.todo"]);
+ }
+
+ #[test]
+ fn local_search_filters_ranks_and_counts_facets() {
+ let catalog = fixture();
+ let got = local_browse(&catalog, &query(json!({ "query": "todo" })));
+ assert_eq!(ids(&got), ["pi.todo", "pi.notes"]);
+ let got = local_browse(
+ &catalog,
+ &query(json!({ "category": "PRODUCTIVITY", "sort": "name" })),
+ );
+ assert_eq!(ids(&got), ["pi.notes", "pi.todo"]);
+ assert_eq!(
+ got.categories,
+ vec![
+ MarketCategoryFacet {
+ id: "Productivity".into(),
+ count: 2
+ },
+ MarketCategoryFacet {
+ id: "Tools".into(),
+ count: 2
+ },
+ MarketCategoryFacet {
+ id: "Writing".into(),
+ count: 1
+ },
+ ]
+ );
+ let got = local_browse(&catalog, &query(json!({ "sort": "popular" })));
+ assert_eq!(ids(&got), ["pi.notes", "pi.todo", "pi.git", "pi.browser"]);
+ let got = local_browse(&catalog, &query(json!({ "sort": "updated" })));
+ assert_eq!(ids(&got), ["pi.browser", "pi.todo", "pi.git", "pi.notes"]);
+ }
+
+ #[test]
+ fn browse_url_encodes_the_query() {
+ let q = query(json!({ "query": "待办 a&b", "category": "AI Tools", "seed": 9, "page": 2 }));
+ assert_eq!(
+ browse_url("https://plugins.example", &q),
+ "https://plugins.example/api/v1/catalog/search?sort=recommended&page=2&pageSize=24&seed=9&q=%E5%BE%85%E5%8A%9E%20a%26b&category=AI%20Tools"
+ );
+ }
+
+ #[test]
+ fn remote_pages_resolve_package_urls_and_reject_oversized_pages() {
+ let q = query(json!({ "pageSize": 1 }));
+ let payload = json!({
+ "total": 3,
+ "artifactBaseUrl": "https://cdn.example/dl",
+ "categories": [{ "id": "Tools", "count": 3 }, { "id": " ", "count": 1 }],
+ "plugins": [{
+ "id": "pi.git", "name": "Git", "description": "", "author": "acme",
+ "versions": [{ "version": "1.0.0", "publishedAt": "2026-01-01T00:00:00Z",
+ "shasum": "ab", "url": "packages/pi.git-1.0.0.piplug", "sizeBytes": 1, "permissions": [] }]
+ }]
+ });
+ let page = parse_remote_page(
+ "https://plugins.example/catalog.json",
+ &q,
+ payload.to_string().as_bytes(),
+ )
+ .unwrap();
+ assert_eq!(page.total, 3);
+ assert_eq!(page.categories.len(), 1);
+ assert_eq!(
+ page.entries[0].versions[0].url,
+ "https://cdn.example/dl/packages/pi.git-1.0.0.piplug"
+ );
+
+ let mut too_many = payload.clone();
+ too_many["plugins"] = json!([payload["plugins"][0], payload["plugins"][0]]);
+ assert!(parse_remote_page(
+ "https://plugins.example/catalog.json",
+ &q,
+ too_many.to_string().as_bytes()
+ )
+ .is_err());
+ assert!(
+ parse_remote_page("https://plugins.example/catalog.json", &q, b"not json").is_err()
+ );
+ }
+}
diff --git a/crates/host-core/src/plugins/marketplace.rs b/crates/host-core/src/plugins/marketplace.rs
index 15ec80d9f..832f0de25 100644
--- a/crates/host-core/src/plugins/marketplace.rs
+++ b/crates/host-core/src/plugins/marketplace.rs
@@ -272,6 +272,11 @@ impl PluginManager {
pub fn refresh_market(&self, force: bool) -> Result<Value> {
let catalog = self.refresh_catalog_from_remote(force)?;
+ // A refresh the user asked for must not be answered by a page cached
+ // before it.
+ if force {
+ super::market_browse::clear_browse_cache();
+ }
Ok(json!({
"providerId": catalog.provider_id,
"name": catalog.name,
@@ -298,7 +303,7 @@ impl PluginManager {
/// A snapshot left by a different source is skipped rather than deleted,
/// so its package URLs and checksums cannot be paired with the official
/// catalog.
- fn load_cached_catalog(&self) -> Result<MarketCatalogFile> {
+ pub(crate) fn load_cached_catalog(&self) -> Result<MarketCatalogFile> {
if self.cached_catalog_matches_source(&self.market_source_url()) {
if let Ok(raw) = fs::read_to_string(self.catalog_path()) {
if let Ok(catalog) = serde_json::from_str::<MarketCatalogFile>(&raw) {
@@ -362,11 +367,12 @@ impl PluginManager {
pub fn market_get(&self, plugin_id: &str) -> Result<MarketPluginDetail> {
let catalog = self.load_catalog()?;
- let mut entry = catalog
- .plugins
- .into_iter()
- .find(|p| p.id == plugin_id)
- .ok_or_else(|| anyhow!("PLUGIN_NOT_FOUND: {plugin_id}"))?;
+ // A card from a remote page can be newer than the snapshot; its entry
+ // is what the user just clicked, so the detail reads it from there.
+ let mut entry =
+ super::market_browse::cached_browse_entry(&self.market_source_url(), plugin_id)
+ .or_else(|| catalog.plugins.into_iter().find(|p| p.id == plugin_id))
+ .ok_or_else(|| anyhow!("PLUGIN_NOT_FOUND: {plugin_id}"))?;
entry
.versions
.sort_by(|a, b| compare_plugin_versions(&b.version, &a.version));
diff --git a/crates/host-core/src/plugins/reviews.rs b/crates/host-core/src/plugins/reviews.rs
index 5a5b1fb53..782e871ec 100644
--- a/crates/host-core/src/plugins/reviews.rs
+++ b/crates/host-core/src/plugins/reviews.rs
@@ -591,14 +591,26 @@ fn center_refusal(url: &str, status: u16, payload: &[u8]) -> anyhow::Error {
/// Redirects are never followed: the request already targets the trusted
/// origin, and `3xx` answers become refusals.
fn get_json(url: &str) -> Result<(u16, Vec<u8>)> {
+ get_json_limited(url, MAX_REVIEW_RESPONSE_BYTES, "review")
+}
+
+/// Bounded anonymous GET against the trusted plugin center.
+///
+/// `limit` caps the body and `what` names the read in its errors ("review",
+/// "marketplace search"), so every center read shares one transport with its
+/// own size policy.
+pub(crate) fn get_json_limited(url: &str, limit: usize, what: &str) -> Result<(u16, Vec<u8>)> {
let response_path = super::install::download_scratch_path();
let mut args: Vec<String> = vec![
"--silent".into(),
"--show-error".into(),
"--max-time".into(),
REVIEW_TIMEOUT_SECONDS.to_string(),
+ // The center sits behind a compressing CDN; JSON shrinks several-fold.
+ // The size check below runs on the decoded body.
+ "--compressed".into(),
"--max-filesize".into(),
- MAX_REVIEW_RESPONSE_BYTES.to_string(),
+ limit.to_string(),
"--output".into(),
response_path.to_string_lossy().into_owned(),
"--write-out".into(),
@@ -623,9 +635,10 @@ fn get_json(url: &str) -> Result<(u16, Vec<u8>)> {
.unwrap_or(0);
let payload = fs::read(&response_path).unwrap_or_default();
let _ = fs::remove_file(&response_path);
- if payload.len() > MAX_REVIEW_RESPONSE_BYTES {
+ if payload.len() > limit {
bail!(
- "PLUGIN_MARKET_INVALID: the plugin center's review answer exceeds the 1MiB limit"
+ "PLUGIN_MARKET_INVALID: the plugin center's {what} answer exceeds the {} limit",
+ byte_limit_label(limit)
);
}
if status == 0 {
@@ -639,11 +652,12 @@ fn get_json(url: &str) -> Result<(u16, Vec<u8>)> {
// outage.
if output.status.code() == Some(63) {
bail!(
- "PLUGIN_MARKET_INVALID: the plugin center's review answer exceeds the 1MiB limit"
+ "PLUGIN_MARKET_INVALID: the plugin center's {what} answer exceeds the {} limit",
+ byte_limit_label(limit)
);
}
bail!(
- "PLUGIN_NETWORK: review request failed for {url}: {}",
+ "PLUGIN_NETWORK: {what} request failed for {url}: {}",
decode_curl_output(&output.stderr)
)
}
@@ -653,11 +667,20 @@ fn get_json(url: &str) -> Result<(u16, Vec<u8>)> {
}
}
+/// `1MiB`-style label for a byte limit, as the refusals have always said it.
+fn byte_limit_label(limit: usize) -> String {
+ if limit.is_multiple_of(1024 * 1024) {
+ format!("{}MiB", limit / (1024 * 1024))
+ } else {
+ format!("{limit} byte")
+ }
+}
+
/// Percent-encode one URL component.
///
/// Ids are validated before they get here, but the cursor is opaque center
/// state, so everything outside the unreserved set is encoded.
-fn encode_component(value: &str) -> String {
+pub(crate) fn encode_component(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
match byte {
diff --git a/crates/host-core/src/rpc/market_browse_rpc.rs b/crates/host-core/src/rpc/market_browse_rpc.rs
new file mode 100644
index 000000000..534a532fc
--- /dev/null
+++ b/crates/host-core/src/rpc/market_browse_rpc.rs
@@ -0,0 +1,65 @@
+//! `market.browse`: one page of the marketplace.
+//!
+//! The catalog source is captured under the host state lock and the lock is
+//! released before the plugin center is asked, so a slow center cannot queue
+//! every other host method behind the search deadline. The page is mapped to
+//! summaries under the lock again, because installed state and the display
+//! locale live there. A remote failure is not an error: the last valid
+//! snapshot answers the same query, and the answer says so.
+
+use std::sync::Arc;
+
+use serde_json::Value;
+use tokio::sync::Mutex;
+
+use super::{plugin_err, rpc_err, JsonRpcError};
+use crate::plugins::market_browse::{fetch_remote_page, BrowseSource, MarketBrowseQuery};
+use crate::state::AppState;
+
+pub(super) async fn browse(
+ state: &Arc<Mutex<AppState>>,
+ params: Value,
+) -> Result<Value, JsonRpcError> {
+ let query = MarketBrowseQuery::from_params(&params);
+ let catalog_url = {
+ let st = state.lock().await;
+ st.plugins.browse_catalog_url()
+ };
+ let remote = {
+ let query = query.clone();
+ let catalog_url = catalog_url.clone();
+ tokio::task::spawn_blocking(move || fetch_remote_page(&catalog_url, &query))
+ .await
+ .map_err(|error| rpc_err(1000, format!("browse worker failed: {error}"), "INTERNAL"))?
+ };
+
+ let st = state.lock().await;
+ // The source can change while the center was being asked; a page from the
+ // old source must not be presented as the current one.
+ let current_url = st.plugins.browse_catalog_url();
+ let (page, source, fallback_reason) = match remote {
+ Ok(page) if current_url == catalog_url => (page, BrowseSource::Remote, None),
+ Ok(_) => (
+ st.plugins.market_browse_local(&query).map_err(plugin_err)?,
+ BrowseSource::Local,
+ Some(
+ "PLUGIN_MARKET_SOURCE_CHANGED: the catalog source changed during the search".into(),
+ ),
+ ),
+ Err(error) => (
+ st.plugins.market_browse_local(&query).map_err(plugin_err)?,
+ BrowseSource::Local,
+ Some(error.to_string()),
+ ),
+ };
+ let result = st
+ .plugins
+ .market_browse_result(&query, page, source, fallback_reason);
+ serde_json::to_value(result).map_err(|error| {
+ rpc_err(
+ 1000,
+ format!("browse page is not serializable: {error}"),
+ "INTERNAL",
+ )
+ })
+}
diff --git a/crates/host-core/src/rpc/market_browse_rpc_tests.rs b/crates/host-core/src/rpc/market_browse_rpc_tests.rs
new file mode 100644
index 000000000..ce838e998
--- /dev/null
+++ b/crates/host-core/src/rpc/market_browse_rpc_tests.rs
@@ -0,0 +1,288 @@
+// Test-only: every test here repoints the process-global
+// `PI_DESKTOP_PLUGIN_MARKET_URL` and holds the shared market lock across the
+// awaited RPC so no other test can move the source mid-call.
+#![allow(clippy::await_holding_lock)]
+
+use std::ffi::OsString;
+use std::sync::{Arc, Mutex as StdMutex, MutexGuard};
+
+use serde_json::{json, Value};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::{TcpListener, TcpStream};
+use tokio::sync::{mpsc, Mutex};
+
+use super::handle_request;
+use crate::plugins::market_browse::clear_browse_cache;
+use crate::plugins::tests::MARKET_ENV_LOCK;
+use crate::state::AppState;
+
+const OFFLINE_MARKET_URL: &str = "file:///nope/does-not-exist-catalog.json";
+
+struct MarketEnv {
+ _guard: MutexGuard<'static, ()>,
+ previous: Option<OsString>,
+}
+
+impl MarketEnv {
+ fn hold() -> Self {
+ let guard = MARKET_ENV_LOCK
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ clear_browse_cache();
+ Self {
+ _guard: guard,
+ previous: std::env::var_os("PI_DESKTOP_PLUGIN_MARKET_URL"),
+ }
+ }
+
+ fn point_at(&self, value: &str) {
+ // Safety: test-only process env mutation, serialized by the lock.
+ unsafe { std::env::set_var("PI_DESKTOP_PLUGIN_MARKET_URL", value) };
+ }
+}
+
+impl Drop for MarketEnv {
+ fn drop(&mut self) {
+ clear_browse_cache();
+ match &self.previous {
+ Some(value) => unsafe { std::env::set_var("PI_DESKTOP_PLUGIN_MARKET_URL", value) },
+ None => unsafe { std::env::remove_var("PI_DESKTOP_PLUGIN_MARKET_URL") },
+ }
+ }
+}
+
+fn fixture_state() -> (
+ tempfile::TempDir,
+ Arc<Mutex<AppState>>,
+ mpsc::UnboundedSender<String>,
+) {
+ let data = tempfile::tempdir().unwrap();
+ let mut app_state = AppState::open(data.path()).unwrap();
+ app_state.handshook = true;
+ (
+ data,
+ Arc::new(Mutex::new(app_state)),
+ mpsc::unbounded_channel().0,
+ )
+}
+
+/// A center that answers the search route with a fixed status and body and
+/// records every search target it saw.
+struct Center {
+ catalog_url: String,
+ searches: Arc<StdMutex<Vec<String>>>,
+}
+
+impl Center {
+ async fn start(status: u16, body: Value) -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let searches = Arc::new(StdMutex::new(Vec::new()));
+ let seen = searches.clone();
+ let body = body.to_string();
+ tokio::spawn(async move {
+ while let Ok((stream, _)) = listener.accept().await {
+ let seen = seen.clone();
+ let body = body.clone();
+ tokio::spawn(async move { serve(stream, status, body, seen).await });
+ }
+ });
+ Self {
+ catalog_url: format!("http://{address}/catalog.json"),
+ searches,
+ }
+ }
+
+ fn searches(&self) -> Vec<String> {
+ self.searches.lock().unwrap().clone()
+ }
+}
+
+async fn serve(mut stream: TcpStream, status: u16, body: String, seen: Arc<StdMutex<Vec<String>>>) {
+ let mut buffer = Vec::new();
+ let mut chunk = [0_u8; 4096];
+ while let Ok(read) = stream.read(&mut chunk).await {
+ if read == 0 {
+ break;
+ }
+ buffer.extend_from_slice(&chunk[..read]);
+ if buffer.windows(4).any(|window| window == b"\r\n\r\n") {
+ break;
+ }
+ }
+ let request = String::from_utf8_lossy(&buffer);
+ let target = request
+ .lines()
+ .next()
+ .and_then(|line| line.split_whitespace().nth(1))
+ .unwrap_or("/")
+ .to_string();
+ let (status, body) = if target.starts_with("/api/v1/catalog/search") {
+ seen.lock().unwrap().push(target);
+ (status, body)
+ } else {
+ (404, "{}".to_string())
+ };
+ let head = format!(
+ "HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = stream.write_all(head.as_bytes()).await;
+ let _ = stream.write_all(body.as_bytes()).await;
+ let _ = stream.flush().await;
+}
+
+fn remote_page() -> Value {
+ json!({
+ "total": 30,
+ "pageCount": 15,
+ "categories": [{ "id": "Tools", "count": 30 }],
+ "artifactBaseUrl": null,
+ "plugins": [
+ {
+ "id": "acme.remote-only", "name": "Remote Only", "description": "From the center",
+ "author": "acme", "categories": ["Tools"], "trust": "community", "downloads": 7,
+ "versions": [{ "version": "2.0.0", "publishedAt": "2026-03-01T00:00:00Z",
+ "shasum": "ab".repeat(32), "url": "packages/acme.remote-only-2.0.0.piplug",
+ "sizeBytes": 10, "permissions": ["ui.panel"] }]
+ },
+ {
+ "id": "acme.second", "name": "Second", "description": "",
+ "author": "acme", "categories": ["Tools"],
+ "versions": [{ "version": "1.0.0", "publishedAt": "2026-02-01T00:00:00Z",
+ "shasum": "cd".repeat(32), "url": "packages/acme.second-1.0.0.piplug",
+ "sizeBytes": 10, "permissions": [] }]
+ }
+ ]
+ })
+}
+
+async fn browse(
+ state: &Arc<Mutex<AppState>>,
+ tx: &mpsc::UnboundedSender<String>,
+ params: Value,
+) -> Value {
+ handle_request(state.clone(), "market.browse", params, tx.clone())
+ .await
+ .unwrap()
+}
+
+#[tokio::test]
+async fn browse_serves_the_centers_page_caches_it_and_opens_its_detail() {
+ let env = MarketEnv::hold();
+ env.point_at(OFFLINE_MARKET_URL);
+ let (_data, state, tx) = fixture_state();
+ let center = Center::start(200, remote_page()).await;
+ env.point_at(&center.catalog_url);
+
+ let params = json!({ "query": "remote", "category": "Tools", "sort": "popular", "seed": 5, "page": 2, "pageSize": 2 });
+ let first = browse(&state, &tx, params.clone()).await;
+ assert_eq!(first["source"], "remote");
+ assert_eq!(first["total"], 30);
+ assert_eq!(
+ (
+ first["page"].as_u64(),
+ first["pageSize"].as_u64(),
+ first["pageCount"].as_u64()
+ ),
+ (Some(2), Some(2), Some(15))
+ );
+ assert_eq!(first["sort"], "popular");
+ assert_eq!(first["categories"][0]["id"], "Tools");
+ let plugins = first["plugins"].as_array().unwrap();
+ assert_eq!(plugins.len(), 2);
+ assert_eq!(plugins[0]["id"], "acme.remote-only");
+ assert_eq!(plugins[0]["latestVersion"], "2.0.0");
+ assert_eq!(plugins[0]["installed"], false);
+
+ let searches = center.searches();
+ assert_eq!(searches.len(), 1);
+ assert!(
+ searches[0].contains("sort=popular&page=2&pageSize=2&seed=5&q=remote&category=Tools"),
+ "{}",
+ searches[0]
+ );
+
+ // The same query inside the TTL is answered from the cache.
+ browse(&state, &tx, params).await;
+ assert_eq!(center.searches().len(), 1);
+
+ // A card from the remote page opens even though the snapshot lacks it.
+ let detail = handle_request(
+ state.clone(),
+ "market.getDetail",
+ json!({ "id": "acme.remote-only" }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(detail["plugin"]["id"], "acme.remote-only");
+}
+
+#[tokio::test]
+async fn browse_falls_back_to_the_snapshot_when_the_center_lacks_the_route() {
+ let env = MarketEnv::hold();
+ env.point_at(OFFLINE_MARKET_URL);
+ let (_data, state, tx) = fixture_state();
+ let center = Center::start(404, json!({ "error": { "code": "NOT_FOUND" } })).await;
+ env.point_at(&center.catalog_url);
+
+ let first = browse(&state, &tx, json!({ "pageSize": 1 })).await;
+ assert_eq!(first["source"], "local");
+ assert!(first["fallbackReason"]
+ .as_str()
+ .unwrap()
+ .contains("PLUGIN_MARKET_UNSUPPORTED"));
+ assert_eq!(first["pageSize"], 1);
+ assert!(first["plugins"].as_array().unwrap().len() <= 1);
+ // The bundled snapshot carries only `demo.*` samples, which browse hides.
+ assert!(first["plugins"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .all(|p| !p["id"].as_str().unwrap().starts_with("demo.")));
+
+ // An unsupported center is remembered rather than asked per keystroke.
+ browse(&state, &tx, json!({ "query": "x" })).await;
+ assert_eq!(center.searches().len(), 1);
+}
+
+#[tokio::test]
+async fn browse_rejects_an_oversized_page_and_falls_back() {
+ let env = MarketEnv::hold();
+ env.point_at(OFFLINE_MARKET_URL);
+ let (_data, state, tx) = fixture_state();
+ let center = Center::start(200, remote_page()).await;
+ env.point_at(&center.catalog_url);
+
+ let answer = browse(&state, &tx, json!({ "pageSize": 1 })).await;
+ assert_eq!(answer["source"], "local");
+ assert!(answer["fallbackReason"]
+ .as_str()
+ .unwrap()
+ .contains("PLUGIN_MARKET_INVALID"));
+}
+
+#[tokio::test]
+async fn browse_backs_off_a_failing_center_and_refresh_clears_it() {
+ let env = MarketEnv::hold();
+ env.point_at(OFFLINE_MARKET_URL);
+ let (_data, state, tx) = fixture_state();
+ let center = Center::start(500, json!({ "error": { "code": "INTERNAL" } })).await;
+ env.point_at(&center.catalog_url);
+
+ let first = browse(&state, &tx, json!({ "query": "a" })).await;
+ assert_eq!(first["source"], "local");
+ assert!(first["fallbackReason"]
+ .as_str()
+ .unwrap()
+ .contains("PLUGIN_NETWORK"));
+ // Typing on while the center is failing answers from the snapshot without
+ // asking it again.
+ browse(&state, &tx, json!({ "query": "ab" })).await;
+ assert_eq!(center.searches().len(), 1);
+
+ clear_browse_cache();
+ browse(&state, &tx, json!({ "query": "abc" })).await;
+ assert_eq!(center.searches().len(), 2);
+}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index b72249e8c..144c8a504 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -3,6 +3,7 @@ mod computer_rpc;
mod config_sync_rpc;
mod file_batches;
mod gen_ui;
+mod market_browse_rpc;
mod modes_rpc;
mod plugin_reviews_rpc;
mod remote_tools;
@@ -23,6 +24,8 @@ mod session_mode_create_tests;
#[cfg(test)]
mod session_mode_migration_tests;
+#[cfg(test)]
+mod market_browse_rpc_tests;
#[cfg(test)]
mod plugin_reviews_rpc_tests;
#[cfg(test)]
@@ -5710,6 +5713,7 @@ async fn handle_request(
let meta = st.plugins.refresh_market(force).map_err(plugin_err)?;
Ok(meta)
}
+ "market.browse" => market_browse_rpc::browse(&state, params).await,
"market.search" => {
let query = params.get("query").and_then(|v| v.as_str());
let category = params.get("category").and_then(|v| v.as_str());
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index d15769339..d7312f78b 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -819,6 +819,10 @@ against a live host, and replaying one after the final row would be wrong.
### Marketplace
- `market.refresh` — fetch and cache the catalog from the configured URL
- `market.search` / `market.getDetail`
+- `market.browse` — one page of the marketplace from the plugin center's
+ `/api/v1/catalog/search`, fetched off the state lock and cached for 60 s;
+ falls back to paging the local snapshot (`source: "local"`, with
+ `fallbackReason`) instead of failing
- `market.install` — download, verify (`PLUGIN_INTEGRITY`,
`PLUGIN_MARKET_*`), and install one catalog release
- `market.checkUpdates` / `market.applyUpdates`
diff --git a/docs/spec/07-plugins/07-plugin-marketplace.md b/docs/spec/07-plugins/07-plugin-marketplace.md
index 03fbe797b..e4a6e92cb 100644
--- a/docs/spec/07-plugins/07-plugin-marketplace.md
+++ b/docs/spec/07-plugins/07-plugin-marketplace.md
@@ -501,8 +501,10 @@ Extensions
├─ Skills
├─ Marketplace
│ ├─ Search
-│ ├─ Categories
-│ └─ Card grid
+│ ├─ Categories (with match counts) + Sort
+│ ├─ Result total
+│ ├─ Card grid (grows as you scroll)
+│ └─ End of list: loaded count + Load more
├─ Detail sheet (shared by both tabs)
│ └─ Review drawer (public reads; covers the detail sheet)
└─ Permission dialog (install / upgrade)
@@ -584,6 +586,41 @@ error states.
Marketplace cards render a monogram glyph rather than fetching `iconUrl`; the
renderer performs no remote image loads (D169).
+### Paged browsing
+
+The Marketplace tab is one growing list fed 24 cards at a time by `market.browse`
+(`{ query, category, sort, seed, page, pageSize }` →
+`{ plugins, total, page, pageSize, pageCount, sort, categories[{id,count}],
+source, fallbackReason?, providerId, sourceUrl }`). The host asks the plugin
+center's `GET /api/v1/catalog/search` off the state lock (bounded like the
+review reads, 8 MiB per page), resolves package URLs against the catalog
+source exactly as for `catalog.json`, and maps entries through the same
+summary rules, so trust, installability and update state are unchanged.
+
+- Sort is `recommended` (relevance for a query, otherwise a shuffle seeded per
+ app session so every page agrees), `popular`, `updated` or `name`.
+- Categories are counted over the query's matches before the category filter;
+ the selected category stays a chip even at zero matches so it can be cleared.
+- The next page is requested when the end of the list comes within 600 px of
+ the viewport; a "Load more" button does the same for keyboard users. The
+ end shows "N of M loaded". Only one next-page request runs at a time, a
+ plugin already shown is not appended twice, and a failed page pauses
+ automatic loading until the user presses Retry.
+- Changing the query, category, sort or language restarts the list from the
+ first page; typing is debounced, every other control asks at once. Any
+ answer — first or next page — for something the user has since left is
+ dropped. An install updates its card in place instead of reloading the list.
+- Remote pages are cached in the host for 60 s and cleared by an explicit
+ marketplace refresh; a center without the route is remembered for 5 min and
+ an unreachable one for 30 s, so offline typing answers from the snapshot at
+ once.
+- A center that is unreachable, predates the route, or a source that is not an
+ http(s) center falls back to paging the last valid local snapshot with the
+ same semantics (`source: "local"`), and the tab shows a "Saved catalog"
+ chip. A detail sheet opened from a remote card reads that card's entry when
+ the snapshot does not have it yet. Install still resolves against a fresh
+ full catalog.
+
Closing a detail sheet with Escape clears focus from its marketplace opener,
matching pointer dismissal: no line or focus ring remains on the card.
Subsequent Tab navigation still shows a complete focus ring inside the rounded
@@ -649,7 +686,7 @@ All download metadata must include `shasum`.
Desktop Extensions page now includes a Marketplace tab that calls:
-- `market.search`
+- `market.browse` (paged; `market.search` remains for the MCP control surface)
- `market.getDetail`
- `market.install`
- `market.checkUpdates`
diff --git a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
index 9747e9edb..62df55c1c 100644
--- a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
+++ b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
@@ -98,6 +98,7 @@ acknowledgement for renderer handling; trusted-extension commands use
### market domain (implemented)
- `market/refresh`
- `market/search`
+- `market/browse`
- `market/getDetail`
- `market/install`
- `market/checkUpdates`
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 3594bd590..18d3245fa 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -2516,6 +2516,18 @@ sklm: {
"marketSource": "Quelle: {{url}}",
"marketLoading": "Marktplatz wird geladen…",
"marketEmpty": "Keine Plugins entsprechen Ihrer Suche",
+ "browseTotal": "{{count}} Plugins",
+ "sortLabel": "Sortieren",
+ "sortRecommended": "Empfohlen",
+ "sortPopular": "Beliebt",
+ "sortUpdated": "Neueste",
+ "sortName": "Name",
+ "sourceLocal": "Gespeicherter Katalog",
+ "sourceLocalHint": "Das Plugin-Center ist nicht verfügbar, daher wird der auf diesem Gerät gespeicherte Katalog angezeigt.",
+ "loadMore": "Mehr laden",
+ "loadingMore": "Wird geladen…",
+ "loadMoreRetry": "Erneut laden",
+ "loadedCount": "{{count}} von {{total}} geladen",
"categories": "Kategorien",
"categoryAll": "Alle",
"verified": "Verifiziert",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 927337fdf..4521ecd92 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -2536,6 +2536,18 @@ importConfirm: "Imported extensions run inside the agent process with the same a
marketSource: "Source: {{url}}",
marketLoading: "Loading marketplace…",
marketEmpty: "No plugins matched your search",
+ browseTotal: "{{count}} plugins",
+ sortLabel: "Sort",
+ sortRecommended: "Recommended",
+ sortPopular: "Popular",
+ sortUpdated: "Newest",
+ sortName: "Name",
+ sourceLocal: "Saved catalog",
+ sourceLocalHint: "The plugin center is unavailable, so the catalog saved on this device is shown.",
+ loadMore: "Load more",
+ loadingMore: "Loading…",
+ loadMoreRetry: "Retry loading",
+ loadedCount: "{{count}} of {{total}} loaded",
categories: "Categories",
categoryAll: "All",
verified: "Verified",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index d81f94b25..1b0da73b9 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -2516,6 +2516,18 @@ sklm: {
"marketSource": "Fuente: {{url}}",
"marketLoading": "Cargando mercado...",
"marketEmpty": "Ningún complemento coincidió con su búsqueda",
+ "browseTotal": "{{count}} complementos",
+ "sortLabel": "Ordenar",
+ "sortRecommended": "Recomendados",
+ "sortPopular": "Populares",
+ "sortUpdated": "Recientes",
+ "sortName": "Nombre",
+ "sourceLocal": "Catálogo guardado",
+ "sourceLocalHint": "El centro de complementos no está disponible, así que se muestra el catálogo guardado en este dispositivo.",
+ "loadMore": "Cargar más",
+ "loadingMore": "Cargando…",
+ "loadMoreRetry": "Reintentar",
+ "loadedCount": "{{count}} de {{total}} cargados",
"categories": "Categorías",
"categoryAll": "Todos",
"verified": "Verificado",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 90745ae56..2dd14691b 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -2516,6 +2516,18 @@ sklm: {
"marketSource": "Source : {{url}}",
"marketLoading": "Chargement du marché…",
"marketEmpty": "Aucun plugin ne correspond à votre recherche",
+ "browseTotal": "{{count}} plugins",
+ "sortLabel": "Trier",
+ "sortRecommended": "Recommandés",
+ "sortPopular": "Populaires",
+ "sortUpdated": "Récents",
+ "sortName": "Nom",
+ "sourceLocal": "Catalogue enregistré",
+ "sourceLocalHint": "Le centre de plugins est indisponible ; le catalogue enregistré sur cet appareil est affiché.",
+ "loadMore": "Charger plus",
+ "loadingMore": "Chargement…",
+ "loadMoreRetry": "Réessayer",
+ "loadedCount": "{{count}} sur {{total}} chargés",
"categories": "Catégories",
"categoryAll": "Tous",
"verified": "Vérifié",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 8a8de219d..4cc4b931c 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -2532,6 +2532,18 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
marketSource: "출처: {{url}}",
marketLoading: "마켓플레이스 불러오는 중…",
marketEmpty: "검색과 일치하는 플러그인 없음",
+ browseTotal: "플러그인 {{count}}개",
+ sortLabel: "정렬",
+ sortRecommended: "추천",
+ sortPopular: "인기",
+ sortUpdated: "최신",
+ sortName: "이름",
+ sourceLocal: "저장된 카탈로그",
+ sourceLocalHint: "플러그인 센터를 사용할 수 없어 이 기기에 저장된 카탈로그를 표시합니다.",
+ loadMore: "더 불러오기",
+ loadingMore: "불러오는 중…",
+ loadMoreRetry: "다시 불러오기",
+ loadedCount: "{{total}}개 중 {{count}}개 불러옴",
categories: "카테고리",
categoryAll: "모두",
verified: "확인됨",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 9277bd7e5..3cdaf36fd 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -2482,6 +2482,18 @@ export const ptBR = {
marketSource: "Fonte: {{url}}",
marketLoading: "Carregando marketplace…",
marketEmpty: "Nenhum plugin corresponde à sua pesquisa.",
+ browseTotal: "{{count}} plugins",
+ sortLabel: "Ordenar",
+ sortRecommended: "Recomendados",
+ sortPopular: "Populares",
+ sortUpdated: "Recentes",
+ sortName: "Nome",
+ sourceLocal: "Catálogo salvo",
+ sourceLocalHint: "A central de plugins está indisponível, então o catálogo salvo neste dispositivo é exibido.",
+ loadMore: "Carregar mais",
+ loadingMore: "Carregando…",
+ loadMoreRetry: "Tentar novamente",
+ loadedCount: "{{count}} de {{total}} carregados",
categories: "Categorias",
categoryAll: "Todas",
verified: "Verificado",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 493143bbc..dc816236a 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -2526,6 +2526,18 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
marketSource: "Kaynak: {{url}}",
marketLoading: "Mağaza yükleniyor…",
marketEmpty: "Aramanızla eşleşen eklenti yok",
+ browseTotal: "{{count}} eklenti",
+ sortLabel: "Sırala",
+ sortRecommended: "Önerilen",
+ sortPopular: "Popüler",
+ sortUpdated: "En yeni",
+ sortName: "Ad",
+ sourceLocal: "Kayıtlı katalog",
+ sourceLocalHint: "Eklenti merkezi kullanılamıyor; bu cihazda kayıtlı katalog gösteriliyor.",
+ loadMore: "Daha fazla yükle",
+ loadingMore: "Yükleniyor…",
+ loadMoreRetry: "Yeniden dene",
+ loadedCount: "{{total}} eklentiden {{count}} yüklendi",
categories: "Kategoriler",
categoryAll: "Tümü",
verified: "Doğrulanmış",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 3a79a2c2d..2af8f334a 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -2511,6 +2511,18 @@ sklm: {
marketSource: "来源:{{url}}",
marketLoading: "正在加载插件市场…",
marketEmpty: "没有匹配的插件",
+ browseTotal: "共 {{count}} 个插件",
+ sortLabel: "排序",
+ sortRecommended: "推荐",
+ sortPopular: "最热",
+ sortUpdated: "最新",
+ sortName: "名称",
+ sourceLocal: "本地目录",
+ sourceLocalHint: "插件中心暂不可用,当前显示本机保存的目录。",
+ loadMore: "加载更多",
+ loadingMore: "正在加载…",
+ loadMoreRetry: "重新加载",
+ loadedCount: "已加载 {{count}} / {{total}}",
categories: "分类",
categoryAll: "全部",
verified: "已验证",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index a9cf965ce..8e9222ca5 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -2511,6 +2511,18 @@ sklm: {
marketSource: "來源:{{url}}",
marketLoading: "正在載入外掛市場…",
marketEmpty: "沒有匹配的外掛",
+ browseTotal: "共 {{count}} 個外掛",
+ sortLabel: "排序",
+ sortRecommended: "推薦",
+ sortPopular: "最熱門",
+ sortUpdated: "最新",
+ sortName: "名稱",
+ sourceLocal: "本機目錄",
+ sourceLocalHint: "外掛中心暫時無法使用,目前顯示本機儲存的目錄。",
+ loadMore: "載入更多",
+ loadingMore: "正在載入…",
+ loadMoreRetry: "重新載入",
+ loadedCount: "已載入 {{count}} / {{total}}",
categories: "分類",
categoryAll: "全部",
verified: "已驗證",
diff --git a/packages/shared/src/changelog-de.ts b/packages/shared/src/changelog-de.ts
index e32d41000..bf7469955 100644
--- a/packages/shared/src/changelog-de.ts
+++ b/packages/shared/src/changelog-de.ts
@@ -11,6 +11,7 @@ export const deEntries: ChangelogEntry[] = [
"Der Kontextindikator zeigt die komprimierte Schätzung sofort nach manueller oder automatischer Komprimierung an.",
"Bei chinesischer IME-Eingabe warten Slash-Befehle auf den Abschluss der Eingabe und bewahren den Entwurf, statt einen Schrägstrich zu duplizieren.",
"Neu generierte Prompts bleiben nach der letzten Antwort an der richtigen Stelle, wenn ihr Archiv außerhalb des geladenen Verlaufs fertig wird.",
+ "Den Plugin-Marktplatz als eine Liste durchsuchen, die beim Scrollen nachlädt, nach Empfohlen, Beliebt, Neueste oder Name sortieren und die Trefferzahl je Kategorie sehen; ist das Plugin-Center nicht erreichbar, antwortet der zuletzt gespeicherte Katalog.",
],
},
{
diff --git a/packages/shared/src/changelog-en.ts b/packages/shared/src/changelog-en.ts
index 31234473f..c94c4529b 100644
--- a/packages/shared/src/changelog-en.ts
+++ b/packages/shared/src/changelog-en.ts
@@ -11,6 +11,7 @@ export const enEntries: ChangelogEntry[] = [
"The context ring updates to the compacted estimate as soon as manual or automatic compaction finishes.",
"With a Chinese IME, slash commands wait for composition to commit and preserve the draft instead of inserting a duplicate slash.",
"Regenerated prompts keep their position after the latest reply when their archive finishes outside the loaded history.",
+ "Browse the plugin marketplace as one list that loads more as you scroll, sort by recommended, popular, newest, or name, and see how many plugins match each category; the last saved catalog answers when the plugin center is unreachable.",
],
},
{
diff --git a/packages/shared/src/changelog-es.ts b/packages/shared/src/changelog-es.ts
index 5f26b826d..3726917e2 100644
--- a/packages/shared/src/changelog-es.ts
+++ b/packages/shared/src/changelog-es.ts
@@ -11,6 +11,7 @@ export const esEntries: ChangelogEntry[] = [
"El indicador de contexto muestra la estimación compactada en cuanto termina una compactación manual o automática.",
"Con un IME chino, los comandos con barra esperan a que termine la composición y conservan el borrador para evitar insertar una barra duplicada.",
"Los prompts regenerados mantienen su posición después de la respuesta más reciente cuando su archivo se completa fuera del historial cargado.",
+ "Explora el marketplace de complementos en una lista que carga más al desplazarte, ordena por recomendados, populares, recientes o nombre y consulta cuántos coinciden en cada categoría; si el centro de complementos no responde, se usa el último catálogo guardado.",
],
},
{
diff --git a/packages/shared/src/changelog-fr.ts b/packages/shared/src/changelog-fr.ts
index d8e9cff50..c51fb7460 100644
--- a/packages/shared/src/changelog-fr.ts
+++ b/packages/shared/src/changelog-fr.ts
@@ -11,6 +11,7 @@ export const frEntries: ChangelogEntry[] = [
"L’indicateur de contexte affiche l’estimation compactée dès la fin d’une compression manuelle ou automatique.",
"Avec une IME chinoise, les commandes slash attendent la validation de la composition et préservent le brouillon au lieu de dupliquer la barre oblique.",
"Les prompts régénérés gardent leur place après la réponse la plus récente lorsque leur archivage se termine hors de l’historique chargé.",
+ "Parcourez la marketplace de plugins dans une liste qui se charge au défilement, triez par recommandés, populaires, récents ou nom, et voyez le nombre de résultats par catégorie ; le dernier catalogue enregistré répond si le centre de plugins est injoignable.",
],
},
{
diff --git a/packages/shared/src/changelog-ko.ts b/packages/shared/src/changelog-ko.ts
index 5b5b6de29..c83db841c 100644
--- a/packages/shared/src/changelog-ko.ts
+++ b/packages/shared/src/changelog-ko.ts
@@ -11,6 +11,7 @@ export const koEntries: ChangelogEntry[] = [
"수동 또는 자동 컨텍스트 압축이 끝나는 즉시 컨텍스트 링에 압축된 예상 사용량이 반영됩니다.",
"중국어 IME 사용 중에는 입력 조합이 끝날 때까지 슬래시 명령을 적용하지 않고 초안을 보존해 슬래시 중복 삽입을 막습니다.",
"다시 생성한 프롬프트는 보관 처리가 로드된 기록 범위 밖에서 끝나도 최신 답변 뒤의 올바른 위치를 유지합니다.",
+ "플러그인 마켓플레이스를 스크롤하면 계속 불러오는 하나의 목록으로 탐색하고 추천·인기·최신·이름순으로 정렬하며 카테고리별 일치 수를 확인할 수 있습니다. 플러그인 센터에 연결할 수 없으면 마지막으로 저장된 카탈로그를 사용합니다.",
],
},
{
diff --git a/packages/shared/src/changelog-pt-BR.ts b/packages/shared/src/changelog-pt-BR.ts
index 16ac484b6..bcd0893e7 100644
--- a/packages/shared/src/changelog-pt-BR.ts
+++ b/packages/shared/src/changelog-pt-BR.ts
@@ -11,6 +11,7 @@ export const ptBREntries: ChangelogEntry[] = [
"O indicador de contexto mostra a estimativa compactada assim que a compactação manual ou automática termina.",
"Com um IME chinês, comandos com barra aguardam o fim da composição e preservam o rascunho, evitando inserir uma barra duplicada.",
"Prompts regenerados permanecem na posição correta após a resposta mais recente quando o arquivamento termina fora do histórico carregado.",
+ "Navegue pelo marketplace de plugins em uma lista que carrega mais ao rolar, ordene por recomendados, populares, recentes ou nome e veja quantos plugins correspondem a cada categoria; se a central de plugins não responder, o último catálogo salvo é usado.",
],
},
{
diff --git a/packages/shared/src/changelog-tr.ts b/packages/shared/src/changelog-tr.ts
index 429ab7fff..63ac64ebd 100644
--- a/packages/shared/src/changelog-tr.ts
+++ b/packages/shared/src/changelog-tr.ts
@@ -11,6 +11,7 @@ export const trEntries: ChangelogEntry[] = [
"Elle veya otomatik bağlam sıkıştırması tamamlanır tamamlanmaz bağlam halkası sıkıştırılmış tahmini gösterir.",
"Çince IME kullanırken eğik çizgi komutları, taslağı koruyarak metin girişinin tamamlanmasını bekler ve yinelenen eğik çizgiyi önler.",
"Yeniden oluşturulan istemler, arşivleri yüklenen geçmişin dışında tamamlandığında en son yanıttan sonraki doğru konumlarında kalır.",
+ "Eklenti pazarına kaydırdıkça yüklenen tek bir listede göz atın, önerilen, popüler, en yeni veya ada göre sıralayın ve her kategoride kaç eklentinin eşleştiğini görün; eklenti merkezine ulaşılamazsa son kaydedilen katalog kullanılır.",
],
},
{
diff --git a/packages/shared/src/changelog-zh-CN.ts b/packages/shared/src/changelog-zh-CN.ts
index c75bed4b2..f8d9230cd 100644
--- a/packages/shared/src/changelog-zh-CN.ts
+++ b/packages/shared/src/changelog-zh-CN.ts
@@ -11,6 +11,7 @@ export const zhCNEntries: ChangelogEntry[] = [
"手动或自动压缩完成后,上下文环会立即更新为压缩后的估算用量。",
"使用中文输入法时,斜杠命令会等输入提交后再应用,同时保留草稿,避免重复插入斜杠。",
"重新生成的提示即使在已加载历史范围之外完成归档,也会保持在最新回答之后的正确位置。",
+ "插件市场改为滚动自动加载,可按推荐、最热、最新或名称排序,分类显示匹配数量;插件中心不可用时使用本机保存的目录。",
],
},
{
diff --git a/packages/shared/src/changelog-zh-TW.ts b/packages/shared/src/changelog-zh-TW.ts
index 68b6b206d..15fe0a7ff 100644
--- a/packages/shared/src/changelog-zh-TW.ts
+++ b/packages/shared/src/changelog-zh-TW.ts
@@ -11,6 +11,7 @@ export const zhTWEntries: ChangelogEntry[] = [
"手動或自動壓縮完成後,上下文環會立即更新為壓縮後的估算用量。",
"使用中文輸入法時,斜線命令會等輸入提交後才套用,同時保留草稿,避免重複插入斜線。",
"重新產生的提示即使在已載入歷史範圍之外完成封存,也會維持在最新回覆之後的正確位置。",
+ "外掛市集改為捲動自動載入,可依推薦、最熱門、最新或名稱排序,分類會顯示符合數量;外掛中心無法使用時改用本機儲存的目錄。",
],
},
{
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 1714301ec..afff5650f 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -435,6 +435,7 @@ export const IPC = {
subagentReveal: "pi-desktop/subagent/reveal",
marketRefresh: "pi-desktop/market/refresh",
marketSearch: "pi-desktop/market/search",
+ marketBrowse: "pi-desktop/market/browse",
marketGetDetail: "pi-desktop/market/getDetail",
marketInstall: "pi-desktop/market/install",
marketCheckUpdates: "pi-desktop/market/checkUpdates",
diff --git a/packages/shared/src/types/marketplace.ts b/packages/shared/src/types/marketplace.ts
index 87f8f8ef2..94e08748b 100644
--- a/packages/shared/src/types/marketplace.ts
+++ b/packages/shared/src/types/marketplace.ts
@@ -30,6 +30,41 @@ export type MarketPluginSummary = {
yanked?: boolean;
};
+/** Orders `market.browse` accepts; `recommended` is a seeded shuffle. */
+export type MarketBrowseSort = "recommended" | "popular" | "updated" | "name";
+
+export type MarketBrowseQuery = {
+ query?: string;
+ category?: string;
+ sort?: MarketBrowseSort;
+ /** Keeps a `recommended` order stable across the pages of one session. */
+ seed?: number;
+ /** 1-based. */
+ page?: number;
+ /** Defaults to 24, capped at 60 by the host. */
+ pageSize?: number;
+};
+
+/** One category and how many of the query's matches carry it. */
+export type MarketCategoryFacet = { id: string; count: number };
+
+/** One page of the marketplace, as `market.browse` answers it. */
+export type MarketBrowseResult = {
+ plugins: MarketPluginSummary[];
+ total: number;
+ page: number;
+ pageSize: number;
+ pageCount: number;
+ sort: MarketBrowseSort;
+ categories: MarketCategoryFacet[];
+ /** `remote`: the plugin center answered; `local`: the cached snapshot did. */
+ source: "remote" | "local";
+ /** Why the plugin center's page was not used, when `source` is `local`. */
+ fallbackReason?: string;
+ providerId: string;
+ sourceUrl: string;
+};
+
export type MarketPluginDetail = MarketPluginSummary & {
readmeMarkdown?: string;
versions: Array<{