Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(plugins): add ratings and reviews with installed card grid
Tioit-Wang1c624aac287b
diff --git a/apps/desktop/electron/main/ipc/market-ipc.ts b/apps/desktop/electron/main/ipc/market-ipc.tsindex cb8550c1e..3508e23d1 100644--- a/apps/desktop/electron/main/ipc/market-ipc.ts+++ b/apps/desktop/electron/main/ipc/market-ipc.ts@@ -1,4 +1,5 @@import { IPC, ErrorCodes, trustedExtensionCommandId, trustedExtensionCommandName } from "@pi-desktop/shared";+import type { PluginReviewQuery } from "@pi-desktop/shared";import { builtinPaletteItems } from "../builtin-commands";import type { AgentExtensionBridge } from "../agent-extensions";import type { HostProcess } from "../host-process";@@ -103,6 +104,20 @@ export function registerMarketIpc({return host.call<{ cancelled: boolean; id: string }>("market.cancelInstall", payload);});+ // Public reviews are read anonymously through the host: the renderer names+ // plugin ids or one query, and host-core owns the trusted center origin,+ // the bounds, and the error mapping. Nothing here authenticates or mutates.+ handle(IPC.invoke.marketReviewSummaries, async (payload?: { pluginIds?: unknown }) => {+ if (!host) throw new Error("host unavailable");+ const pluginIds = Array.isArray(payload?.pluginIds) ? payload.pluginIds : [];+ return host.call("market.reviewSummaries", { pluginIds });+ });++ handle(IPC.invoke.marketReviews, async (payload?: Partial<PluginReviewQuery>) => {+ if (!host) throw new Error("host unavailable");+ return host.call("market.reviews", { ...(payload ?? {}) });+ });+handle(IPC.invoke.commandPaletteSearch, async (query: string) => {const q = (query || "").toLowerCase();const builtin = builtinPaletteItems();diff --git a/apps/desktop/src/features/plugins/InstalledPluginsPanel.tsx b/apps/desktop/src/features/plugins/InstalledPluginsPanel.tsxindex e6abe19b2..2fba42045 100644--- a/apps/desktop/src/features/plugins/InstalledPluginsPanel.tsx+++ b/apps/desktop/src/features/plugins/InstalledPluginsPanel.tsx@@ -8,18 +8,20 @@ import {IconReview,IconSearch,IconSettings,+ IconShield,IconTrash,} from "../../components/icons";import { ScopeControl } from "../../components/extensions/ScopeControl";import { AnchoredMenu } from "../../components/settings/AnchoredMenu";import type { ActivationScope } from "@pi-desktop/shared";-import { GROUP_LABEL_KEYS, TEMPLATE_IDS } from "./model";-import { PluginRowDetails } from "./presentation";+import { GROUP_LABEL_KEYS, TEMPLATE_IDS, showsVerifiedBadge } from "./model";+import { PluginRowDetails, RatingChip } from "./presentation";import type { PluginsPageModel } from "./usePluginsPage";import { api } from "../../lib/api";export function InstalledPluginsPanel({t,+ locale,plugins,setTab,loadDev,@@ -38,6 +40,7 @@ export function InstalledPluginsPanel({reloadPlugin,setSettingsPlugin,servicesByPlugin,+ reviewSummaries,}: PluginsPageModel) {return (<div@@ -95,8 +98,14 @@ export function InstalledPluginsPanel({const broken = group.id === "attention";const menuOpen = rowMenu === plugin.id;const update = plugin.updateAvailable;+ /**+ * The card's one call to action: an available update, or+ * opening the plugin's own panel. A disabled plugin has+ * neither, so it never carries a primary button.+ */+ const canOpenPanel = plugin.enabled && !!plugin.ui?.panel;return (- <div+ <articlekey={plugin.id}role="listitem"className={cx(@@ -106,16 +115,25 @@ export function InstalledPluginsPanel({menuOpen && "menu-open",)}>- <span className="plugins-glyph" aria-hidden>- {broken ? (- <IconCircleAlert size={15} />- ) : (- <IconPlug size={15} />- )}- </span>- <div className="plugins-row-copy">+ <div className="plugins-row-head">+ <span className="plugins-glyph" aria-hidden>+ {broken ? (+ <IconCircleAlert size={15} />+ ) : (+ <IconPlug size={15} />+ )}+ </span><div className="plugins-row-title"><span className="plugins-row-name">{plugin.name}</span>+ {showsVerifiedBadge(plugin.marketplace) ? (+ <span+ className="plugins-verified"+ title={t("plugins.verified")}+ aria-label={t("plugins.verified")}+ >+ <IconShield size={12} />+ </span>+ ) : null}{plugin.source === "dev" ? (<span className="plugins-tag">{t("plugins.tagLocal")}</span>) : null}@@ -123,12 +141,18 @@ export function InstalledPluginsPanel({<span className="plugins-tag">{t("plugins.tagBundled")}</span>) : null}</div>+ </div>+ <div className="plugins-row-copy"><div className="plugins-row-meta"><span className="plugins-row-id">{plugin.id}</span><span className="plugins-dot" aria-hidden>·</span><span>v{plugin.version}</span>+ <RatingChip+ summary={reviewSummaries[plugin.id]}+ locale={locale}+ /></div>{plugin.errorMessage ? (<p className="plugins-row-error">{plugin.errorMessage}</p>@@ -139,26 +163,6 @@ export function InstalledPluginsPanel({/></div><div className="plugins-row-controls">- {update ? (- <Button- variant="secondary"- size="sm"- disabled={busyId === plugin.id}- onClick={() =>- queueInstall({- id: plugin.id,- name: plugin.name,- version: update.version,- permissions: plugin.permissions ?? [],- newPermissions: update.permissionDiff ?? [],- })- }- >- {busyId === plugin.id- ? t("plugins.updating")- : t("plugins.updateNow")}- </Button>- ) : null}<ScopeControltarget={plugin}label={plugin.name}@@ -179,122 +183,138 @@ export function InstalledPluginsPanel({})}/>- <div className="plugins-row-actions">- {plugin.ui?.panel ? (+ {plugin.enabled && update ? (+ <Button+ variant="primary"+ size="sm"+ disabled={busyId === plugin.id}+ onClick={() =>+ queueInstall({+ id: plugin.id,+ name: plugin.name,+ version: update.version,+ permissions: plugin.permissions ?? [],+ newPermissions: update.permissionDiff ?? [],+ })+ }+ >+ {busyId === plugin.id+ ? t("plugins.updating")+ : t("plugins.updateTo", { version: update.version })}+ </Button>+ ) : canOpenPanel ? (+ <Button+ variant="secondary"+ size="sm"+ onClick={() =>+ void run(() => api.openPluginPanel(plugin.id))+ }+ >+ <IconPanel size={14} />+ {t("plugins.openPanel")}+ </Button>+ ) : null}+ {plugin.enabled && plugin.settings?.length ? (+ <TooltipButton+ type="button"+ className="plugins-icon-btn"+ tooltip={t("plugins.openSettings")}+ ariaLabel={t("plugins.openSettings")}+ onClick={() => setSettingsPlugin(plugin)}+ >+ <IconSettings size={15} />+ </TooltipButton>+ ) : null}+ <AnchoredMenu+ className="plugins-menu-wrap"+ open={menuOpen}+ onClose={() => setRowMenu(null)}+ menuClassName="plugins-menu is-end"+ label={t("plugins.rowActions", { name: plugin.name })}+ role="menu"+ align="end"+ trigger={(ref) => (<TooltipButton+ ref={ref}type="button"className="plugins-icon-btn"- tooltip={t("plugins.openPanel")}- ariaLabel={t("plugins.openPanel")}+ tooltip={t("plugins.rowActions", { name: plugin.name })}+ ariaLabel={t("plugins.rowActions", { name: plugin.name })}+ aria-haspopup="menu"+ aria-expanded={menuOpen}onClick={() =>- void run(() => api.openPluginPanel(plugin.id))+ setRowMenu((cur) =>+ cur === plugin.id ? null : plugin.id,+ )}>- <IconPanel size={15} />+ <IconMore size={15} /></TooltipButton>- ) : null}- {plugin.enabled && plugin.settings?.length ? (- <TooltipButton- type="button"- className="plugins-icon-btn"- tooltip={t("plugins.openSettings")}- ariaLabel={t("plugins.openSettings")}- onClick={() => setSettingsPlugin(plugin)}- >- <IconSettings size={15} />- </TooltipButton>- ) : null}- <AnchoredMenu- className="plugins-menu-wrap"- open={menuOpen}- onClose={() => setRowMenu(null)}- menuClassName="plugins-menu is-end"- label={t("plugins.rowActions", { name: plugin.name })}- role="menu"- align="end"- trigger={(ref) => (- <TooltipButton- ref={ref}+ )}+ >+ {plugin.source === "dev" ? (+ <button+ type="button"+ role="menuitem"+ disabled={+ busyId === plugin.id ||+ reloadingId === plugin.id+ }+ onClick={() => {+ setRowMenu(null);+ void reloadPlugin(plugin.id);+ }}+ >+ <IconReview size={14} />+ {t("plugins.reload")}+ </button>+ ) : null}+ <buttontype="button"- className="plugins-icon-btn"- tooltip={t("plugins.rowActions", { name: plugin.name })}- ariaLabel={t("plugins.rowActions", { name: plugin.name })}- aria-haspopup="menu"- aria-expanded={menuOpen}- onClick={() =>- setRowMenu((cur) =>- cur === plugin.id ? null : plugin.id,- )- }+ role="menuitem"+ onClick={() => {+ setRowMenu(null);+ void run(async () => {+ await api.setPluginAutoUpdate(+ plugin.id,+ !plugin.autoUpdate,+ );+ await refreshPlugins();+ });+ }}>- <IconMore size={15} />- </TooltipButton>- )}- >- {plugin.source === "dev" ? (+ <IconCloudDown size={14} />+ {plugin.autoUpdate+ ? t("plugins.disableAutoUpdate")+ : t("plugins.enableAutoUpdate")}+ </button>+ {/* A bundled plugin belongs to the+ application: the host refuses the+ removal, so the action is not offered+ (ADR 0104, ADR 0241). */}+ {plugin.bundled ? null : (+ <>+ <div className="plugins-menu-sep" /><buttontype="button"role="menuitem"- disabled={- busyId === plugin.id ||- reloadingId === plugin.id- }+ className="danger"onClick={() => {setRowMenu(null);- void reloadPlugin(plugin.id);+ void run(async () => {+ await api.uninstallPlugin(plugin.id);+ await refreshPlugins();+ });}}>- <IconReview size={14} />- {t("plugins.reload")}+ <IconTrash size={14} />+ {t("plugins.uninstall")}</button>- ) : null}- <button- type="button"- role="menuitem"- onClick={() => {- setRowMenu(null);- void run(async () => {- await api.setPluginAutoUpdate(- plugin.id,- !plugin.autoUpdate,- );- await refreshPlugins();- });- }}- >- <IconCloudDown size={14} />- {plugin.autoUpdate- ? t("plugins.disableAutoUpdate")- : t("plugins.enableAutoUpdate")}- </button>- {/* A bundled plugin belongs to the- application: the host refuses the- removal, so the action is not offered- (ADR 0104, ADR 0241). */}- {plugin.bundled ? null : (- <>- <div className="plugins-menu-sep" />- <button- type="button"- role="menuitem"- className="danger"- onClick={() => {- setRowMenu(null);- void run(async () => {- await api.uninstallPlugin(plugin.id);- await refreshPlugins();- });- }}- >- <IconTrash size={14} />- {t("plugins.uninstall")}- </button>- </>- )}- </AnchoredMenu>- </div>+ </>+ )}+ </AnchoredMenu></div>- </div>+ </article>);})}</div>diff --git a/apps/desktop/src/features/plugins/MarketplacePanel.tsx b/apps/desktop/src/features/plugins/MarketplacePanel.tsxindex 1029f171f..8134024fd 100644--- a/apps/desktop/src/features/plugins/MarketplacePanel.tsx+++ b/apps/desktop/src/features/plugins/MarketplacePanel.tsx@@ -1,6 +1,6 @@import { Button, cx } from "../../components/ui";import { IconCheck, IconSearch, IconShield } from "../../components/icons";-import { PermissionChips } from "./presentation";+import { PermissionChips, RatingChip } from "./presentation";import {formatDate,monogram,@@ -25,6 +25,7 @@ export function MarketplacePanel({openDetail,busyId,queueInstall,+ reviewSummaries,}: PluginsPageModel) {return (<div@@ -150,6 +151,10 @@ export function MarketplacePanel({</span></>) : null}+ <RatingChip+ summary={reviewSummaries[item.id]}+ locale={locale}+ /></span></span></span>diff --git a/apps/desktop/src/features/plugins/PluginDetailSheet.tsx b/apps/desktop/src/features/plugins/PluginDetailSheet.tsxindex c21a309a2..ad0fd30c3 100644--- a/apps/desktop/src/features/plugins/PluginDetailSheet.tsx+++ b/apps/desktop/src/features/plugins/PluginDetailSheet.tsx@@ -1,4 +1,4 @@-import type { ReactNode } from "react";+import { useEffect, useRef, type ReactNode } from "react";import { Button, TooltipButton, cx, portalOverlay } from "../../components/ui";import { useBlockingOverlay } from "../../lib/blocking-overlay";import {@@ -22,6 +22,8 @@ import {versionInstallable,versionWithdrawn,} from "./model";+import { ReviewSummaryBlock } from "./presentation";+import { PluginReviewsDrawer } from "./PluginReviewsDrawer";import type { PluginsPageModel } from "./usePluginsPage";function PluginDetailBlockingHost({ children }: { children: ReactNode }) {@@ -46,7 +48,24 @@ export function PluginDetailSheet({busyId,queueInstall,setSelectedVersion,+ reviewSummaries,+ reviewsStatus,+ reviewsId,+ openReviews,+ closeReviews,}: PluginsPageModel) {+ const reviewSummary = detail ? reviewSummaries[detail.id] : undefined;+ const reviewsOpen = selectedId !== null && reviewsId === selectedId;+ /** The button that opened the drawer; focus returns here when it closes. */+ const reviewsOpenerRef = useRef<HTMLButtonElement | null>(null);+ const wasReviewsOpen = useRef(false);+ useEffect(() => {+ if (wasReviewsOpen.current && !reviewsOpen) {+ reviewsOpenerRef.current?.focus();+ }+ wasReviewsOpen.current = reviewsOpen;+ }, [reviewsOpen]);+return selectedId? portalOverlay(<PluginDetailBlockingHost>@@ -56,12 +75,17 @@ export function PluginDetailSheet({className="plugins-sheet-scrim"aria-label={t("plugins.closeDetail")}onClick={closeDetail}+ inert={reviewsOpen}/><asideclassName="plugins-sheet"role="dialog"aria-modal="true"aria-label={t("plugins.detailTitle")}+ /* The review drawer is the top layer while it covers this sheet:+ the sheet stays mounted (and keeps its scroll position) but is+ not reachable by pointer or keyboard until the drawer leaves. */+ inert={reviewsOpen}><header className="plugins-sheet-head"><span className="plugins-card-glyph is-large" aria-hidden>@@ -279,6 +303,41 @@ export function PluginDetailSheet({)}</section>+ {/* Ratings and reviews, between permissions and versions:+ what other users said, then the release history it+ belongs to. Reviews themselves open in the drawer that+ covers this sheet. */}+ <section className="plugins-sheet-section">+ <h3 className="plugins-sheet-section-title">+ {t("plugins.reviews.summaryTitle")}+ </h3>+ {reviewSummary && reviewSummary.ratingCount > 0 ? (+ <ReviewSummaryBlock summary={reviewSummary} locale={locale} />+ ) : reviewSummary ? (+ <p className="plugins-sheet-desc">{t("plugins.reviews.empty")}</p>+ ) : reviewsStatus === "loading" ? (+ <p className="plugins-sheet-desc">{t("plugins.reviews.loading")}</p>+ ) : (+ <p className="plugins-sheet-desc">+ {t("plugins.reviews.unavailable")}+ </p>+ )}+ {/* The entry stays reachable even when the summary read+ failed: the drawer is where the list is retried, and+ it always carries the disabled composer plus the+ link out to the centre's own page. */}+ <div className="plugins-sheet-reviews-action">+ <Button+ variant="secondary"+ size="sm"+ ref={reviewsOpenerRef}+ onClick={() => openReviews(detail.id)}+ >+ {t("plugins.reviews.viewAll")}+ </Button>+ </div>+ </section>+<section className="plugins-sheet-section"><h3 className="plugins-sheet-section-title">{t("plugins.versions")}@@ -361,6 +420,13 @@ export function PluginDetailSheet({</>)}</aside>+ {reviewsOpen && detail ? (+ <PluginReviewsDrawer+ pluginId={detail.id}+ pluginName={detail.name}+ onClose={closeReviews}+ />+ ) : null}</div></PluginDetailBlockingHost>,)diff --git a/apps/desktop/src/features/plugins/PluginReviewsDrawer.tsx b/apps/desktop/src/features/plugins/PluginReviewsDrawer.tsxnew file mode 100644index 000000000..c789dda10--- /dev/null+++ b/apps/desktop/src/features/plugins/PluginReviewsDrawer.tsx@@ -0,0 +1,348 @@+/**+ * The public review drawer: a read-only list of what the plugin centre shows,+ * opened from the detail sheet's ratings summary.+ *+ * It is an independent surface at the same dialog level as the detail sheet —+ * it slides over it while the sheet stays mounted underneath, so closing the+ * drawer returns to the exact reading position it covered. Reviews are written+ * on the plugin centre; the desktop never signs in, never posts, and never+ * offers signed-in actions, so the composer is a permanently greyed field and+ * the one call to action is a real link out to the centre's page.+ */+import { useEffect, useId, useRef } from "react";+import { useTranslation } from "react-i18next";+import { Button, Textarea, TooltipButton, cx } from "../../components/ui";+import { IconExternal, IconStar, IconX } from "../../components/icons";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import { formatDate } from "./model";+import {+ REVIEW_SENTIMENTS,+ REVIEW_SORT_LABEL_KEYS,+ REVIEW_SORTS,+ REVIEW_SENTIMENT_LABEL_KEYS,+ formatReviewRating,+ type ReviewSentiment,+ type ReviewSort,+} from "./reviews";+import { ReviewSummaryBlock } from "./presentation";+import { usePluginReviews } from "./usePluginReviews";++/** What Tab can reach inside the drawer's own surface. */+const FOCUSABLE_SELECTOR = [+ "a[href]",+ "button:not([disabled])",+ "textarea:not([disabled])",+ "input:not([disabled])",+ "select:not([disabled])",+ '[tabindex]:not([tabindex="-1"])',+].join(",");++function focusableWithin(root: HTMLElement): HTMLElement[] {+ return [...root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)].filter(+ (element) => element.getAttribute("aria-hidden") !== "true",+ );+}++export function PluginReviewsDrawer({+ pluginId,+ pluginName,+ onClose,+}: {+ pluginId: string;+ pluginName: string;+ onClose: () => void;+}) {+ const { t, i18n } = useTranslation();+ const locale = i18n.language;+ const showToast = useAppStore((state) => state.showToast);+ const {+ state,+ sentiment,+ sort,+ setSentiment,+ setSort,+ loadMore,+ retry,+ reviewUrl,+ } = usePluginReviews(pluginId);+ const dialogRef = useRef<HTMLElement | null>(null);+ const titleId = useId();++ // The drawer is the top layer when it mounts: focus it so Escape and Tab+ // start here, and let the sheet restore its own opener on close.+ useEffect(() => {+ dialogRef.current?.focus();+ }, []);++ /**+ * Escape and Tab belong to the top layer. Escape is claimed before anything+ * under the drawer sees it (the detail sheet also stands down while this+ * surface is open, see usePluginsPage); Tab cycles inside the dialog, so+ * keyboard focus can never reach the covered sheet or the page behind it.+ */+ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ onClose();+ return;+ }+ if (event.key !== "Tab") return;+ const root = dialogRef.current;+ if (!root) return;+ const focusables = focusableWithin(root);+ if (!focusables.length) return;+ const first = focusables[0];+ const last = focusables[focusables.length - 1];+ const active = document.activeElement;+ const inside = active instanceof HTMLElement && root.contains(active);+ if (!inside) {+ event.preventDefault();+ (event.shiftKey ? last : first).focus();+ return;+ }+ if (!event.shiftKey && active === last) {+ event.preventDefault();+ first.focus();+ } else if (event.shiftKey && active === first) {+ event.preventDefault();+ last.focus();+ }+ };+ document.addEventListener("keydown", onKeyDown, true);+ return () => document.removeEventListener("keydown", onKeyDown, true);+ }, [onClose]);++ /** Open the centre's page in the system browser; report a failure. */+ const openReviewLink = () => {+ void (async () => {+ try {+ await api.browserOpenExternal(reviewUrl);+ } catch (error) {+ showToast(error instanceof Error ? error.message : String(error), {+ variant: "error",+ });+ }+ })();+ };++ const reviewSummary = state.summary;+ const showSummary = !!reviewSummary && reviewSummary.ratingCount > 0;+ const showList = state.reviews.length > 0;+ const failedWithoutRows = state.status === "error" && !showList;++ return (+ <div className="plugins-reviews-layer">+ <button+ type="button"+ className="plugins-reviews-scrim"+ aria-label={t("plugins.reviews.close")}+ onClick={onClose}+ />+ <aside+ ref={dialogRef}+ className="plugins-reviews"+ role="dialog"+ aria-modal="true"+ aria-labelledby={titleId}+ tabIndex={-1}+ >+ <header className="plugins-reviews-head">+ <h2 className="plugins-reviews-title" id={titleId}>+ {t("plugins.reviews.title", { name: pluginName })}+ </h2>+ <TooltipButton+ type="button"+ className="plugins-icon-btn"+ ariaLabel={t("plugins.reviews.close")}+ tooltip={t("plugins.reviews.close")}+ onClick={onClose}+ >+ <IconX size={15} />+ </TooltipButton>+ </header>++ <div className="plugins-reviews-body">+ {showSummary && reviewSummary ? (+ <ReviewSummaryBlock summary={reviewSummary} locale={locale} />+ ) : null}++ <div className="plugins-reviews-controls">+ <div+ className="plugins-reviews-filters"+ role="group"+ aria-label={t("plugins.reviews.filterLabel")}+ >+ {REVIEW_SENTIMENTS.map((value: ReviewSentiment) => (+ <button+ key={value}+ type="button"+ className={cx("plugins-filter", sentiment === value && "active")}+ aria-pressed={sentiment === value}+ onClick={() => setSentiment(value)}+ >+ {t(REVIEW_SENTIMENT_LABEL_KEYS[value])}+ </button>+ ))}+ </div>+ <div+ className="plugins-reviews-filters"+ role="group"+ aria-label={t("plugins.reviews.sortLabel")}+ >+ {REVIEW_SORTS.map((value: ReviewSort) => (+ <button+ key={value}+ type="button"+ className={cx("plugins-filter", sort === value && "active")}+ aria-pressed={sort === value}+ onClick={() => setSort(value)}+ >+ {t(REVIEW_SORT_LABEL_KEYS[value])}+ </button>+ ))}+ </div>+ </div>++ {state.status === "loading" && !showList ? (+ <p className="plugins-reviews-state" role="status">+ {t("plugins.reviews.loading")}+ </p>+ ) : failedWithoutRows ? (+ <div className="plugins-reviews-state" role="alert">+ <p className="plugins-reviews-state-title">+ {t("plugins.reviews.loadFailed")}+ </p>+ {state.error ? (+ <p className="plugins-reviews-state-detail">{state.error}</p>+ ) : null}+ <Button variant="secondary" size="sm" onClick={retry}>+ {t("plugins.reviews.retry")}+ </Button>+ </div>+ ) : !showList ? (+ <p className="plugins-reviews-state">{t("plugins.reviews.empty")}</p>+ ) : (+ <ul className="plugins-reviews-list" aria-label={t("plugins.reviews.listAria")}>+ {state.reviews.map((review) => (+ <li key={review.id} className="plugins-review">+ <div className="plugins-review-head">+ <span className="plugins-review-author">{review.authorName}</span>+ <span+ className="plugins-review-rating"+ role="img"+ aria-label={t("plugins.reviews.reviewRatingAria", {+ rating: formatReviewRating(review.ratingHalfStars),+ })}+ >+ <IconStar+ size={12}+ style={{ fill: "currentColor" }}+ aria-hidden="true"+ />+ <span>{formatReviewRating(review.ratingHalfStars)}</span>+ </span>+ </div>+ <div className="plugins-review-meta">+ <span>{formatDate(review.createdAt, locale)}</span>+ {review.pluginVersion ? (+ <>+ <span className="plugins-dot" aria-hidden>+ ·+ </span>+ {/* The author asserts this; it is not an installed+ version, so it is labelled as what it is. */}+ <span>+ {t("plugins.reviews.reviewVersion", {+ version: review.pluginVersion,+ })}+ </span>+ </>+ ) : null}+ {review.editedAt ? (+ <>+ <span className="plugins-dot" aria-hidden>+ ·+ </span>+ <span>{t("plugins.reviews.edited")}</span>+ </>+ ) : null}+ {review.helpfulCount > 0 ? (+ <>+ <span className="plugins-dot" aria-hidden>+ ·+ </span>+ <span>+ {t("plugins.reviews.helpfulCount", {+ count: review.helpfulCount,+ })}+ </span>+ </>+ ) : null}+ </div>+ <p className="plugins-review-body">{review.body}</p>+ </li>+ ))}+ </ul>+ )}++ {state.error && showList ? (+ <div className="plugins-reviews-state is-inline" role="alert">+ <span className="plugins-reviews-state-detail">{state.error}</span>+ <Button variant="secondary" size="sm" onClick={retry}>+ {t("plugins.reviews.retry")}+ </Button>+ </div>+ ) : null}++ {state.nextCursor ? (+ <div className="plugins-reviews-more">+ <Button+ variant="secondary"+ size="sm"+ disabled={state.loadingMore}+ onClick={loadMore}+ >+ {state.loadingMore+ ? t("plugins.reviews.loading")+ : t("plugins.reviews.loadMore")}+ </Button>+ </div>+ ) : null}+ </div>++ <div className="plugins-reviews-composer">+ <Textarea+ className="plugins-reviews-composer-field"+ disabled+ rows={2}+ aria-label={t("plugins.reviews.composeHint")}+ placeholder={t("plugins.reviews.composeHint")}+ />+ {/* A real link: the OS browser opens the centre's page, where a+ signed-in account can post. The desktop never writes reviews. */}+ <a+ className="plugins-reviews-write"+ href={reviewUrl}+ onClick={(event) => {+ event.preventDefault();+ openReviewLink();+ }}+ onAuxClick={(event) => {+ // Middle-click only: a right-click belongs to the platform+ // menu, never to opening the page.+ if (event.button !== 1) return;+ event.preventDefault();+ openReviewLink();+ }}+ >+ <IconExternal size={13} aria-hidden="true" />+ {t("plugins.reviews.composeCta")}+ </a>+ </div>+ </aside>+ </div>+ );+}diff --git a/apps/desktop/src/features/plugins/presentation.tsx b/apps/desktop/src/features/plugins/presentation.tsxindex f6d5f7e64..7a455dcdd 100644--- a/apps/desktop/src/features/plugins/presentation.tsx+++ b/apps/desktop/src/features/plugins/presentation.tsx@@ -1,11 +1,12 @@import { useRef } from "react";import { useTranslation } from "react-i18next";import { TooltipButton, cx } from "../../components/ui";-import { IconChevronDown, IconSearch, IconX } from "../../components/icons";+import { IconChevronDown, IconSearch, IconStar, IconX } from "../../components/icons";import type {PluginAgentExtensionStatus,PluginCapability,PluginFsPolicy,+ PluginReviewSummary,PluginServiceStatus,PluginSummary,} from "@pi-desktop/shared";@@ -18,6 +19,11 @@ import {permissionRisk,orderPermissions,} from "./model";+import {+ REVIEW_SENTIMENT_LABEL_KEYS,+ formatRatingAvg,+ sentimentShares,+} from "./reviews";export function PermissionChips({permissions,@@ -196,6 +202,107 @@ export function AgentExtensionDetails({ status }: { status: PluginAgentExtension);}+/**+ * The compact rating readout cards carry in their metadata line: one star,+ * the average, and how many ratings it is worth. Nothing renders when the+ * centre has no summary for the plugin — an unavailable service must not read+ * as a zero rating.+ */+export function RatingChip({+ summary,+ locale,+}: {+ summary: PluginReviewSummary | undefined;+ locale: string;+}) {+ const { t } = useTranslation();+ const avg = summary ? formatRatingAvg(summary.ratingAvg, locale) : null;+ if (!summary || !avg || summary.ratingCount <= 0) return null;+ return (+ <span+ className="plugins-rating"+ role="img"+ aria-label={t("plugins.reviews.ratingSummaryAria", {+ avg,+ count: summary.ratingCount,+ })}+ >+ <span className="plugins-dot" aria-hidden>+ ·+ </span>+ <IconStar size={11} style={{ fill: "currentColor" }} aria-hidden="true" />+ <span className="plugins-rating-text">+ {t("plugins.reviews.ratingChip", { avg, count: summary.ratingCount })}+ </span>+ </span>+ );+}++/**+ * The average, its rating count, and the good / medium / bad split as bars.+ * Shown in the detail sheet between permissions and versions, and again at the+ * top of the review drawer; rendering it only when there is at least one+ * rating keeps the empty case to a single sentence at the call site.+ */+export function ReviewSummaryBlock({+ summary,+ locale,+}: {+ summary: PluginReviewSummary;+ locale: string;+}) {+ const { t } = useTranslation();+ const avg = formatRatingAvg(summary.ratingAvg, locale);+ if (avg === null || summary.ratingCount <= 0) return null;+ return (+ <div className="plugins-reviews-summary">+ <div className="plugins-reviews-score">+ <span className="plugins-reviews-avg">{avg}</span>+ <span+ className="plugins-reviews-stars"+ role="img"+ aria-label={t("plugins.reviews.ratingSummaryAria", {+ avg,+ count: summary.ratingCount,+ })}+ >+ <IconStar size={13} style={{ fill: "currentColor" }} aria-hidden="true" />+ </span>+ <span className="plugins-reviews-count">+ {t("plugins.reviews.count", { count: summary.ratingCount })}+ </span>+ </div>+ <ul className="plugins-reviews-dist">+ {sentimentShares(summary).map((share) => {+ const label = t(REVIEW_SENTIMENT_LABEL_KEYS[share.key]);+ return (+ <li+ key={share.key}+ className={cx("plugins-reviews-dist-row", `is-${share.key}`)}+ >+ <span className="plugins-reviews-dist-label">{label}</span>+ <span+ className="plugins-reviews-dist-bar"+ role="img"+ aria-label={t("plugins.reviews.distributionAria", {+ label,+ count: share.count,+ })}+ >+ <span+ className="plugins-reviews-dist-fill"+ style={{ width: `${share.percent}%` }}+ />+ </span>+ <span className="plugins-reviews-dist-count">{share.count}</span>+ </li>+ );+ })}+ </ul>+ </div>+ );+}+/** Keep the installed row calm while retaining the full capability readout on demand. */export function PluginRowDetails({plugin,diff --git a/apps/desktop/src/features/plugins/reviews.ts b/apps/desktop/src/features/plugins/reviews.tsnew file mode 100644index 000000000..573bbd5fb--- /dev/null+++ b/apps/desktop/src/features/plugins/reviews.ts@@ -0,0 +1,300 @@+/**+ * Public review reads: the values the plugins page shows, and the state a+ * review list moves through.+ *+ * Reviews are written on the plugin center, so the desktop only ever reads+ * them. Everything here is pure transformation — what a chip says, how one+ * page of results folds into the list, and which answer belongs to the query+ * still on screen — so the drawer's behaviour is testable without an IPC+ * boundary. Fetching lives in `usePluginReviews`.+ */+import type {+ PluginReview,+ PluginReviewPage,+ PluginReviewQuery,+ PluginReviewSummary,+} from "@pi-desktop/shared";++/** The sentiment filter the center accepts; `all` asks for every visible row. */+export type ReviewSentiment = "all" | "positive" | "neutral" | "negative";++/** Order the center offers; both cursors stay bound to the choice. */+export type ReviewSort = "newest" | "helpful";++export const REVIEW_SENTIMENTS: readonly ReviewSentiment[] = [+ "all",+ "positive",+ "neutral",+ "negative",+];++export const REVIEW_SORTS: readonly ReviewSort[] = ["newest", "helpful"];++/** Catalog keys for the filter chips and the distribution rows. */+export const REVIEW_SENTIMENT_LABEL_KEYS: Record<ReviewSentiment, string> = {+ all: "plugins.reviews.sentimentAll",+ positive: "plugins.reviews.sentimentPositive",+ neutral: "plugins.reviews.sentimentNeutral",+ negative: "plugins.reviews.sentimentNegative",+};++/** Catalog keys for the sort chips. */+export const REVIEW_SORT_LABEL_KEYS: Record<ReviewSort, string> = {+ newest: "plugins.reviews.sortNewest",+ helpful: "plugins.reviews.sortHelpful",+};++/** One page of reviews, as the contract's `limit` default. */+export const REVIEW_PAGE_LIMIT = 20;++/**+ * Origin of the plugin center. The host bridge returns the effective+ * `reviewUrl` for whatever catalog origin is in effect (a fixture environment+ * override included); this is the fallback used when only the plugin id is+ * known, so the write link never depends on catalogue or review content.+ */+export const OFFICIAL_PLUGIN_CENTER_ORIGIN = "https://plugins.aiuo.net";++/** The public page where a review for `pluginId` is written. */+export function officialReviewUrl(pluginId: string): string {+ return `${OFFICIAL_PLUGIN_CENTER_ORIGIN}/plugins/${encodeURIComponent(pluginId)}#reviews`;+}++/**+ * Prefer the host-provided page URL; fall back to the official page. A value+ * that is not an http(s) URL is refused rather than rendered as a link.+ */+export function effectiveReviewUrl(+ pluginId: string,+ pageUrl: string | null | undefined,+): string {+ const trimmed = pageUrl?.trim();+ if (trimmed && /^https?:\/\//i.test(trimmed)) return trimmed;+ return officialReviewUrl(pluginId);+}++/** The identity of one review query: switching any part starts a new list. */+export function reviewQueryKey(+ pluginId: string,+ sentiment: ReviewSentiment,+ sort: ReviewSort,+): string {+ return [pluginId, sentiment, sort].join("\u0000");+}++/**+ * Append a page without ever repeating a row. Helpful ordering is not a+ * snapshot, so a review can move between pages while the user reads; the id+ * is what decides whether a row was already shown.+ */+export function mergeReviews(+ existing: readonly PluginReview[],+ incoming: readonly PluginReview[],+): PluginReview[] {+ const seen = new Set(existing.map((review) => review.id));+ const merged = [...existing];+ for (const review of incoming) {+ if (seen.has(review.id)) continue;+ seen.add(review.id);+ merged.push(review);+ }+ return merged;+}++/**+ * The average, written with the locale's decimal separator and exactly one+ * decimal. `null` means the centre reported no average (no visible reviews),+ * which is not the same as zero.+ */+export function formatRatingAvg(+ avg: number | null | undefined,+ locale: string,+): string | null {+ if (avg == null || !Number.isFinite(avg)) return null;+ try {+ return new Intl.NumberFormat(locale || undefined, {+ minimumFractionDigits: 1,+ maximumFractionDigits: 1,+ }).format(avg);+ } catch {+ return avg.toFixed(1);+ }+}++/** One review's half-star rating as a star value (`9` → `4.5`, `10` → `5`). */+export function formatReviewRating(halfStars: number): string {+ const stars = Math.max(0, halfStars) / 2;+ const fixed = stars.toFixed(1);+ return fixed.endsWith(".0") ? fixed.slice(0, -2) : fixed;+}++export type SentimentShare = {+ key: "positive" | "neutral" | "negative";+ count: number;+ percent: number;+};++/**+ * The distribution readout: how many ratings each sentiment holds, each as a+ * share of the three buckets. A summary with no rows yields zeroed buckets so+ * the surface keeps its shape rather than dividing by zero.+ */+export function sentimentShares(+ summary:+ | Pick<PluginReviewSummary, "positiveCount" | "neutralCount" | "negativeCount">+ | null+ | undefined,+): SentimentShare[] {+ const counts = {+ positive: Math.max(0, summary?.positiveCount ?? 0),+ neutral: Math.max(0, summary?.neutralCount ?? 0),+ negative: Math.max(0, summary?.negativeCount ?? 0),+ };+ const total = counts.positive + counts.neutral + counts.negative;+ return (["positive", "neutral", "negative"] as const).map((key) => ({+ key,+ count: counts[key],+ percent: total > 0 ? Math.round((counts[key] / total) * 100) : 0,+ }));+}++/**+ * The summary map a successful batched answer produces.+ *+ * A success is the whole truth for the ids that were asked about: the centre+ * deliberately omits ids it no longer serves (an archived or unpublished+ * plugin), so an id the answer omits must lose its rating rather than keep an+ * older one merged underneath. Ids that were not requested are ignored, so a+ * stray key cannot leak into the map.+ */+export function nextSummaryMap(+ requestedIds: readonly string[],+ response: Record<string, PluginReviewSummary>,+): Record<string, PluginReviewSummary> {+ const next: Record<string, PluginReviewSummary> = {};+ for (const id of requestedIds) {+ const answer = response[id];+ if (answer) next[id] = answer;+ }+ return next;+}++export type ReviewListStatus = "idle" | "loading" | "ready" | "error";+/** What the drawer draws, including which query the rows belong to. */+export type ReviewListState = {+ /** `reviewQueryKey` of the rows on screen; null before the first load. */+ key: string | null;+ reviews: PluginReview[];+ nextCursor: string | null;+ summary: PluginReviewSummary | null;+ reviewUrl: string | null;+ status: ReviewListStatus;+ loadingMore: boolean;+ error: string | null;+};++export function initialReviewListState(): ReviewListState {+ return {+ key: null,+ reviews: [],+ nextCursor: null,+ summary: null,+ reviewUrl: null,+ status: "idle",+ loadingMore: false,+ error: null,+ };+}++/**+ * Start the first page for `key`. A different query clears the previous rows —+ * they answer a question the user moved on from; the same query keeps them so+ * a retry never blanks what is already readable.+ */+export function beginReviewLoad(state: ReviewListState, key: string): ReviewListState {+ if (state.key !== key) {+ return { ...initialReviewListState(), key, status: "loading" };+ }+ return {+ ...state,+ status: state.reviews.length ? "ready" : "loading",+ loadingMore: false,+ error: null,+ };+}++/** Fold a first page in; a late answer for another query is ignored. */+export function applyReviewPage(+ state: ReviewListState,+ key: string,+ page: PluginReviewPage,+ pluginId: string,+): ReviewListState {+ if (state.key !== key) return state;+ return {+ ...state,+ reviews: mergeReviews([], page.reviews ?? []),+ nextCursor: page.nextCursor ?? null,+ summary: page.summary ?? state.summary,+ reviewUrl: effectiveReviewUrl(pluginId, page.reviewUrl),+ status: "ready",+ loadingMore: false,+ error: null,+ };+}++/** Append a later page, deduplicated by review id. */+export function applyNextReviewPage(+ state: ReviewListState,+ key: string,+ page: PluginReviewPage,+): ReviewListState {+ if (state.key !== key) return state;+ return {+ ...state,+ reviews: mergeReviews(state.reviews, page.reviews ?? []),+ nextCursor: page.nextCursor ?? null,+ summary: page.summary ?? state.summary,+ loadingMore: false,+ error: null,+ };+}++export function beginReviewLoadMore(state: ReviewListState): ReviewListState {+ return { ...state, loadingMore: true, error: null };+}++/**+ * A failed request for the current query: the whole list becomes an error+ * only when there is nothing to read; a failed "load more" keeps the rows and+ * reports the failure beside them.+ */+export function failReviewLoad(+ state: ReviewListState,+ key: string,+ error: string,+): ReviewListState {+ if (state.key !== key) return state;+ return {+ ...state,+ status: state.reviews.length ? "ready" : "error",+ loadingMore: false,+ error,+ };+}++/** The query object one page request sends. */+export function reviewQuery(+ pluginId: string,+ sentiment: ReviewSentiment,+ sort: ReviewSort,+ cursor?: string | null,+): PluginReviewQuery {+ return {+ pluginId,+ sentiment,+ sort,+ limit: REVIEW_PAGE_LIMIT,+ ...(cursor ? { cursor } : {}),+ };+}diff --git a/apps/desktop/src/features/plugins/usePluginReviews.ts b/apps/desktop/src/features/plugins/usePluginReviews.tsnew file mode 100644index 000000000..f19557ca1--- /dev/null+++ b/apps/desktop/src/features/plugins/usePluginReviews.ts@@ -0,0 +1,121 @@+/**+ * Reads the public review list for one plugin: first page, sentiment filter,+ * sort, and cursor paging. The centre is optional infrastructure — an+ * unreachable or older service fails this surface alone and never touches+ * install or update paths — so every failure lands as a retryable error here.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import { api } from "../../lib/api";+import {+ applyNextReviewPage,+ applyReviewPage,+ beginReviewLoad,+ beginReviewLoadMore,+ effectiveReviewUrl,+ failReviewLoad,+ initialReviewListState,+ reviewQuery,+ reviewQueryKey,+ type ReviewListState,+ type ReviewSentiment,+ type ReviewSort,+} from "./reviews";++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++export function usePluginReviews(pluginId: string) {+ const [sentiment, setSentiment] = useState<ReviewSentiment>("all");+ const [sort, setSort] = useState<ReviewSort>("newest");+ const [state, setState] = useState<ReviewListState>(initialReviewListState);+ /**+ * Request identity: switching query or pressing retry invalidates every+ * answer still in flight, and the pure helpers refuse a mismatched key+ * again so a race cannot smuggle another filter's rows into the list.+ */+ const generation = useRef(0);++ // A drawer that closes mid-request must not walk an old answer back into a+ // component that no longer exists: bumping the generation on unmount makes+ // every in-flight response stale.+ useEffect(() => {+ return () => {+ generation.current += 1;+ };+ }, []);++ const requestFirstPage = useCallback(+ (key: string, query: { sentiment: ReviewSentiment; sort: ReviewSort }) => {+ const request = ++generation.current;+ void (async () => {+ try {+ const page = await api.marketReviews(+ reviewQuery(pluginId, query.sentiment, query.sort),+ );+ if (generation.current !== request) return;+ setState((current) => applyReviewPage(current, key, page, pluginId));+ } catch (error) {+ if (generation.current !== request) return;+ setState((current) => failReviewLoad(current, key, errorMessage(error)));+ }+ })();+ },+ [pluginId],+ );++ useEffect(() => {+ const key = reviewQueryKey(pluginId, sentiment, sort);+ setState((current) => beginReviewLoad(current, key));+ requestFirstPage(key, { sentiment, sort });+ }, [pluginId, sentiment, sort, requestFirstPage]);++ const loadMore = useCallback(() => {+ const cursor = state.nextCursor;+ const key = state.key;+ if (!cursor || !key || state.loadingMore) return;+ setState((current) => beginReviewLoadMore(current));+ const request = ++generation.current;+ void (async () => {+ try {+ const page = await api.marketReviews(reviewQuery(pluginId, sentiment, sort, cursor));+ if (generation.current !== request) return;+ setState((current) => applyNextReviewPage(current, key, page));+ } catch (error) {+ if (generation.current !== request) return;+ setState((current) => failReviewLoad(current, key, errorMessage(error)));+ }+ })();+ }, [pluginId, sentiment, sort, state.key, state.loadingMore, state.nextCursor]);++ /** Retry whichever request failed: the first page, or the next one. */+ const retry = useCallback(() => {+ if (state.reviews.length && state.nextCursor) {+ loadMore();+ return;+ }+ const key = reviewQueryKey(pluginId, sentiment, sort);+ setState((current) => beginReviewLoad(current, key));+ requestFirstPage(key, { sentiment, sort });+ }, [+ loadMore,+ pluginId,+ requestFirstPage,+ sentiment,+ sort,+ state.nextCursor,+ state.reviews.length,+ ]);++ return {+ state,+ sentiment,+ sort,+ setSentiment,+ setSort,+ loadMore,+ retry,+ /** The write link: the centre's page URL, or the official fallback. */+ reviewUrl: state.reviewUrl ?? effectiveReviewUrl(pluginId, null),+ };+}diff --git a/apps/desktop/src/features/plugins/usePluginsPage.ts b/apps/desktop/src/features/plugins/usePluginsPage.tsindex 77a36458c..1282b6379 100644--- a/apps/desktop/src/features/plugins/usePluginsPage.ts+++ b/apps/desktop/src/features/plugins/usePluginsPage.ts@@ -7,6 +7,7 @@ import type {MarketPluginDetail,MarketPluginSummary,PluginPermissionReview,+ PluginReviewSummary,PluginServiceStatus,PluginSummary,ProjectRecord,@@ -33,6 +34,7 @@ import {type PluginInstallJob,type PluginInstallRequest,} from "./install-progress";+import { nextSummaryMap } from "./reviews";export function usePluginsPage() {const { t, i18n } = useTranslation();@@ -85,6 +87,21 @@ export function usePluginsPage() {const [services, setServices] = useState<PluginServiceStatus[]>([]);const [selectedVersion, setSelectedVersion] = useState("");const [settingsPlugin, setSettingsPlugin] = useState<PluginSummary | null>(null);+ /**+ * Public rating summaries for every installed and marketplace plugin id.+ * Batched so the installed tab can show a rating without a marketplace+ * refresh, and kept as a map because it is a read that never holds anything+ * else on the page back. `reviewsStatus` is `unavailable` — never zeros —+ * when the centre cannot answer.+ */+ const [reviewSummaries, setReviewSummaries] = useState<+ Record<string, PluginReviewSummary>+ >({});+ const [reviewsStatus, setReviewsStatus] = useState<+ "idle" | "loading" | "ready" | "unavailable"+ >("idle");+ /** The plugin whose public review drawer is open over its detail sheet. */+ const [reviewsId, setReviewsId] = useState<string | null>(null);/*** The install dialog is the top layer while it is open: the permission review@@ -167,11 +184,16 @@ export function usePluginsPage() {if (focused instanceof HTMLElement && focused.matches(".plugins-card-hit")) {focused.blur();}+ // The review drawer only ever covers this sheet, so it leaves with it.+ setReviewsId(null);setSelectedId(null);setDetail(null);setSelectedVersion("");};+ const openReviews = (id: string) => setReviewsId(id);+ const closeReviews = () => setReviewsId(null);+// Every scope control offers the same folder list, so it is fetched once here// and handed down rather than re-queried per row.useEffect(() => {@@ -215,16 +237,16 @@ export function usePluginsPage() {}, [locale]);// Escape closes the detail sheet, but only while it owns the top layer: the- // permission dialog and the install dialog in front of it handle their own- // dismissal.+ // permission dialog, the install dialog, and the review drawer in front of+ // it handle their own dismissal.useEffect(() => {- if (!selectedId || pendingInstall || installDialogOpen) return;+ if (!selectedId || pendingInstall || installDialogOpen || reviewsId) return;const onKeyDown = (event: KeyboardEvent) => {if (event.key === "Escape") closeDetail();};document.addEventListener("keydown", onKeyDown);return () => document.removeEventListener("keydown", onKeyDown);- }, [selectedId, pendingInstall, installDialogOpen]);+ }, [selectedId, pendingInstall, installDialogOpen, reviewsId]);useEffect(() => {if (!pendingInstall) return;@@ -270,6 +292,47 @@ export function usePluginsPage() {return api.onPluginChanged(refresh);}, []);+ /**+ * Public rating summaries are one batched read for every id either tab can+ * show, debounced so a marketplace search that also refreshes the installed+ * list still asks once. The installed tab therefore reads the same map+ * without waiting for a marketplace refresh, and a centre that predates the+ * review API fails this read alone — install and update never depend on it.+ */+ useEffect(() => {+ const ids = [+ ...new Set([...plugins.map((plugin) => plugin.id), ...market.map((item) => item.id)]),+ ];+ if (!ids.length) {+ setReviewsStatus("idle");+ return;+ }+ let cancelled = false;+ const handle = window.setTimeout(() => {+ setReviewsStatus("loading");+ void (async () => {+ try {+ const summaries = await api.marketReviewSummaries(ids);+ if (cancelled) return;+ // A success answers every id just requested, so it replaces the map+ // for them: the centre omits ids it no longer serves, and a rating+ // that stopped existing must stop rendering (see nextSummaryMap).+ setReviewSummaries(nextSummaryMap(ids, summaries));+ setReviewsStatus("ready");+ } catch {+ // Unsupported or unreachable service: an explicit unavailable state,+ // never fabricated zeros.+ if (cancelled) return;+ setReviewsStatus("unavailable");+ }+ })();+ }, 200);+ return () => {+ cancelled = true;+ window.clearTimeout(handle);+ };+ }, [plugins, market]);+const servicesByPlugin = useMemo(() => {const map = new Map<string, PluginServiceStatus[]>();for (const status of services) {@@ -280,8 +343,7 @@ export function usePluginsPage() {return map;}, [services]);- const installedById = useMemo(() => {- const map = new Map<string, PluginSummary>();+ const installedById = useMemo(() => { const map = new Map<string, PluginSummary>();for (const plugin of plugins) map.set(plugin.id, plugin);return map;}, [plugins]);@@ -690,6 +752,11 @@ export function usePluginsPage() {setSelectedVersion,settingsPlugin,setSettingsPlugin,+ reviewSummaries,+ reviewsStatus,+ reviewsId,+ openReviews,+ closeReviews,refreshMarket,openDetail,closeDetail,diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex bae97d22a..7f6af9022 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -72,6 +72,9 @@ import type {MarketPluginDetail,PluginInstallResult,PluginInstallProgress,+ PluginReviewPage,+ PluginReviewQuery,+ PluginReviewSummary,ProjectRecord,ProjectGroupRecord,ProjectMemory,@@ -1475,6 +1478,19 @@ export const api = {/** Ask the running install to stop. Only a download can be interrupted. */marketCancelInstall: (id: string) =>invoke<{ cancelled: boolean; id: string }>(IPC.invoke.marketCancelInstall, { id }),+ /**+ * Public rating summaries for plugin ids, keyed by id. Anonymous read+ * through the host; an unreachable or older center rejects instead of+ * answering fabricated zeros, so callers show an unavailable state.+ */+ marketReviewSummaries: (pluginIds: string[]) =>+ invoke<{ summaries: Record<string, PluginReviewSummary> }>(+ IPC.invoke.marketReviewSummaries,+ { pluginIds },+ ).then((result) => result.summaries),+ /** One page of public reviews, its summary, and the trusted review URL. */+ marketReviews: (query: PluginReviewQuery) =>+ invoke<PluginReviewPage>(IPC.invoke.marketReviews, query),/** Import a pi CLI extension file or directory as a development plugin (spec 16 §3). */importPiExtension: () =>invoke<diff --git a/apps/desktop/src/styles/plugins.css b/apps/desktop/src/styles/plugins.cssindex 01cba17ef..fce04f75d 100644--- a/apps/desktop/src/styles/plugins.css+++ b/apps/desktop/src/styles/plugins.css@@ -277,21 +277,23 @@font-variant-numeric: tabular-nums;}-/* Installed rows are soft tiles stacked with a small gap; the gap does the- work a hairline used to. Nothing clips, so row menus can overhang freely. */+/* Installed plugins are cards in an auto-filling grid: every card is its own+ soft tile, the gap does the work a hairline used to, and nothing clips so a+ card's menu can overhang the tile below. `min(340px, 100%)` keeps the+ computed column from overflowing a container narrower than one card. */.plugins-list {- display: flex;- flex-direction: column;- gap: 6px;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(min(340px, 100%), 1fr));+ gap: 12px;min-width: 0;}.plugins-row {display: flex;- align-items: center;- gap: 12px;- padding: 13px 16px;- border-radius: var(--radius-md-plus);+ flex-direction: column;+ gap: 10px;+ padding: 14px;+ border-radius: var(--radius-lg);background: var(--plugins-tile);transition: background var(--motion-duration-fast) var(--motion-ease-out);}@@ -302,8 +304,11 @@background: var(--plugins-tile-hover);}-.plugins-row:has(.plugins-row-details[open]) {- align-items: flex-start;+.plugins-row-head {+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;}.plugins-glyph {@@ -383,6 +388,29 @@color: var(--ds-text-faint);}+/* Rating chip in a card's metadata line: star, average, rating count. It+ renders nothing without a summary, so an unavailable centre reads as no+ chip rather than a zero score. */+.plugins-rating {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ flex: 0 0 auto;+ color: var(--ds-text-muted);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}++.plugins-rating > svg {+ flex: 0 0 auto;+ color: var(--ds-warning);+}++.plugins-rating-text {+ overflow: hidden;+ text-overflow: ellipsis;+}+/* A plugin that failed to load keeps its own reason on the row: the row staysbroken until the user fixes it, so the message is state, not an announcement. */.plugins-row-error {@@ -605,13 +633,18 @@color: inherit;}+/* The card's control rail: scope first, then the one call to action, then the+ 28px icon actions. It clusters at the card's left edge and wraps rather than+ shrinking, so a narrow card grows a second line instead of clipping a+ control. */.plugins-row-controls {display: flex;align-items: center;gap: 8px;- flex: 0 0 auto;- margin-left: auto;- padding-top: 0;+ flex-wrap: wrap;+ justify-content: flex-start;+ margin-top: auto;+ min-width: 0;}/* Keep row actions visible so available operations are discoverable at rest. */@@ -1155,6 +1188,330 @@}}+/* ---- Public ratings and reviews ----+ Reads only: averages and review rows come from the plugin centre, and the+ one write path is a link that opens the centre's page in the system+ browser. Every surface here goes through --ds-* tokens. */++/* Summary: the average on the left, the good / medium / bad split on the+ right. Shared by the detail sheet and the review drawer. */+.plugins-reviews-summary {+ display: flex;+ align-items: center;+ gap: 18px;+ border-radius: var(--radius-md-plus);+ padding: 12px 14px;+ background: var(--plugins-tile);+}++.plugins-reviews-score {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 2px;+ flex: 0 0 auto;+}++.plugins-reviews-avg {+ color: var(--ds-text-primary);+ font-size: var(--text-xl);+ font-weight: var(--font-weight-strong);+ font-variant-numeric: tabular-nums;+ line-height: var(--leading-tighter);+}++.plugins-reviews-stars {+ display: inline-flex;+ color: var(--ds-warning);+}++.plugins-reviews-count {+ color: var(--ds-text-muted);+ font-size: var(--text-xs-plus);+ white-space: nowrap;+}++.plugins-reviews-dist {+ display: flex;+ flex: 1;+ min-width: 0;+ flex-direction: column;+ gap: 5px;+ margin: 0;+ padding: 0;+ list-style: none;+}++.plugins-reviews-dist-row {+ display: flex;+ align-items: center;+ gap: 8px;+ color: var(--ds-text-muted);+ font-size: var(--text-xs-plus);+}++.plugins-reviews-dist-label {+ flex: 0 0 auto;+ min-width: 58px;+}++.plugins-reviews-dist-bar {+ flex: 1;+ min-width: 0;+ height: 6px;+ border-radius: var(--radius-full);+ background: color-mix(in oklab, var(--ds-text-primary) 8%, transparent);+ overflow: hidden;+}++.plugins-reviews-dist-fill {+ display: block;+ height: 100%;+ border-radius: inherit;+ background: var(--ds-text-faint);+}++.plugins-reviews-dist-row.is-positive .plugins-reviews-dist-fill {+ background: var(--ds-success);+}++.plugins-reviews-dist-row.is-negative .plugins-reviews-dist-fill {+ background: var(--ds-error);+}++.plugins-reviews-dist-count {+ flex: 0 0 auto;+ min-width: 18px;+ text-align: right;+ font-variant-numeric: tabular-nums;+}++.plugins-sheet-reviews-action {+ display: flex;+ justify-content: flex-start;+ margin-top: 10px;+}++/* The drawer: a second dialog-level surface that covers the detail sheet+ while the sheet keeps its mounted state and scroll position. */+.plugins-reviews-layer {+ position: absolute;+ inset: 0;+ z-index: 1;+ display: flex;+ justify-content: flex-end;+}++.plugins-reviews-scrim {+ position: absolute;+ inset: 0;+ background: var(--ds-modal-veil);+ animation: plugins-fade-in var(--motion-duration-fast) var(--motion-ease-out) both;+}++.plugins-reviews {+ position: relative;+ display: flex;+ flex-direction: column;+ width: min(560px, 100%);+ height: 100%;+ padding-top: var(--ds-toolbar-height);+ background: var(--ds-bg-elevated-opaque, var(--ds-bg-primary));+ box-shadow: 0 0 0 0.5px var(--ds-border-default), -18px 0 48px rgba(0, 0, 0, 0.26);+ animation: plugins-sheet-in var(--motion-duration-normal) var(--motion-ease-out) both;+}++.plugins-reviews-head {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 16px 16px 10px;+ -webkit-app-region: no-drag;+ app-region: no-drag;+}++.plugins-reviews-title {+ overflow: hidden;+ flex: 1;+ min-width: 0;+ margin: 0;+ color: var(--ds-text-primary);+ font-size: var(--text-lg);+ font-weight: var(--font-weight-strong);+ letter-spacing: var(--tracking-tight);+ text-overflow: ellipsis;+ white-space: nowrap;+}++.plugins-reviews-body {+ display: flex;+ flex-direction: column;+ gap: 12px;+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 6px 16px 16px;+}++.plugins-reviews-controls {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.plugins-reviews-filters {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+}++.plugins-reviews-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin: 0;+ padding: 0;+ list-style: none;+}++.plugins-review {+ display: flex;+ flex-direction: column;+ gap: 6px;+ border-radius: var(--radius-md);+ padding: 12px 14px;+ background: var(--plugins-tile);+}++.plugins-review-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+}++.plugins-review-author {+ overflow: hidden;+ color: var(--ds-text-primary);+ font-size: var(--text-sm-plus);+ font-weight: var(--font-weight-medium);+ text-overflow: ellipsis;+ white-space: nowrap;+}++.plugins-review-rating {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ flex: 0 0 auto;+ color: var(--ds-text-secondary);+ font-size: var(--text-xs-plus);+ font-variant-numeric: tabular-nums;+}++.plugins-review-rating > svg {+ color: var(--ds-warning);+}++.plugins-review-meta {+ display: flex;+ align-items: center;+ gap: 5px;+ flex-wrap: wrap;+ color: var(--ds-text-muted);+ font-size: var(--text-xs);+}++.plugins-review-body {+ margin: 0;+ color: var(--ds-text-secondary);+ font-size: var(--text-sm-plus);+ line-height: var(--leading-body);+ overflow-wrap: anywhere;+ white-space: pre-wrap;+}++.plugins-reviews-state {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 8px;+ margin: 0;+ padding: 14px 2px;+ color: var(--ds-text-secondary);+ font-size: var(--text-sm-plus);+}++.plugins-reviews-state.is-inline {+ flex-direction: row;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ padding: 0;+}++.plugins-reviews-state-title {+ margin: 0;+}++.plugins-reviews-state-detail {+ margin: 0;+ color: var(--ds-text-muted);+ font-size: var(--text-xs-plus);+ overflow-wrap: anywhere;+}++.plugins-reviews-more {+ display: flex;+ justify-content: center;+}++/* The composer stays inert — reviews are written on the centre — and its one+ action is a real link there. */+.plugins-reviews-composer {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 12px 16px 16px;+ background: var(--plugins-tile);+}++.plugins-reviews-composer-field {+ width: 100%;+ min-height: 54px;+ resize: none;+ border: 0;+ border-radius: var(--radius-md);+ padding: 9px 12px;+ background: var(--ds-field-inset-bg);+ color: var(--ds-text-muted);+ font: inherit;+ font-size: var(--text-sm-plus);+}++.plugins-reviews-write {+ display: inline-flex;+ align-items: center;+ align-self: center;+ gap: 6px;+ border-radius: var(--radius-2xs);+ padding: 4px 8px;+ color: var(--ds-text-primary);+ font-size: var(--text-sm-plus);+ font-weight: var(--font-weight-medium);+ transition: background var(--motion-duration-fast) var(--motion-ease-out);+}++.plugins-reviews-write:hover {+ background: var(--ds-bg-hover);+}++.plugins-reviews-write > svg {+ flex: 0 0 auto;+ color: var(--ds-text-muted);+}+/* Detail sheet: a right-side overlay instead of a nested-border sidebar. */#pi-desktop-overlays > .plugins-sheet-layer {pointer-events: auto;diff --git a/apps/desktop/src/styles/responsive.css b/apps/desktop/src/styles/responsive.cssindex f401bb3d1..062ebaa85 100644--- a/apps/desktop/src/styles/responsive.css+++ b/apps/desktop/src/styles/responsive.css@@ -12,10 +12,6 @@.plugins-search-wrap {flex: 1 1 auto;}-- .plugins-row-controls {- align-self: flex-start;- }}/*@@ -90,6 +86,8 @@.plugins-menu,.plugins-sheet,.plugins-sheet-scrim,+ .plugins-reviews,+ .plugins-reviews-scrim,.plugins-modal,.plugins-modal-backdrop,.plugins-skeleton-line {diff --git a/apps/desktop/test/extensions-page.test.mjs b/apps/desktop/test/extensions-page.test.mjsindex fd7d59f58..67487b7ea 100644--- a/apps/desktop/test/extensions-page.test.mjs+++ b/apps/desktop/test/extensions-page.test.mjs@@ -129,7 +129,10 @@ test("installed plugin rows keep secondary detail behind a disclosure", () => {});test("extension row actions stay visible and labelled", () => {- assert.match(pageSrc, /<TooltipButton[\s\S]*?tooltip=\{t\("plugins\.openPanel"\)\}/);+ // The card's one call to action is a visible, labelled button; the icon+ // actions stay visible at rest and carry tooltips and accessible names.+ assert.match(pageSrc, /t\("plugins\.openPanel"\)/);+ assert.match(pageSrc, /<TooltipButton[\s\S]*?tooltip=\{t\("plugins\.openSettings"\)\}/);assert.match(pageSrc, /<TooltipButton[\s\S]*?tooltip=\{t\("plugins\.rowActions", \{ name: plugin\.name \}\)\}/);assert.match(styles, /\.ui-tooltip\s*\{[\s\S]*?position:\s*fixed;/);const actionBlock = styles.match(/\.ext-row-actions\s*\{[^}]*\}/)?.[0] ?? "";diff --git a/apps/desktop/test/market-review-ipc.test.mjs b/apps/desktop/test/market-review-ipc.test.mjsnew file mode 100644index 000000000..b5b67106d--- /dev/null+++ b/apps/desktop/test/market-review-ipc.test.mjs@@ -0,0 +1,168 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import ts from "typescript";+import { IPC, IPC_WHITELIST } from "@pi-desktop/shared";++/**+ * The review channels are a thin pass-through: the renderer names plugin ids+ * or one query, and host-core owns the trusted origin, the five-second bound,+ * and the refusal mapping. These tests pin the bridge half of that contract.+ *+ * The module is transpiled with stubbed dependencies, the pattern the other+ * Electron IPC tests use, so the test exercises the real registration code+ * without loading unrelated main-process modules.+ */+function loadMarketIpc() {+ const file = new URL("../electron/main/ipc/market-ipc.ts", import.meta.url);+ const { outputText } = ts.transpileModule(readFileSync(file, "utf8"), {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },+ fileName: file.pathname,+ });+ const module = { exports: {} };+ const dependencies = {+ "@pi-desktop/shared": {+ IPC,+ ErrorCodes: {},+ trustedExtensionCommandId: (name) => `builtin.${name}`,+ trustedExtensionCommandName: () => undefined,+ },+ "../builtin-commands": { builtinPaletteItems: () => [] },+ };+ new Function("require", "exports", "module", outputText)(+ (id) => {+ assert.ok(Object.hasOwn(dependencies, id), `unexpected market IPC dependency: ${id}`);+ return dependencies[id];+ },+ module.exports,+ module,+ );+ return module.exports.registerMarketIpc;+}++function setup(responses = {}, { host = true } = {}) {+ const handlers = new Map();+ const calls = [];+ const hostProcess = {+ async call(method, params) {+ calls.push({ method, params });+ const response = responses[method];+ if (response instanceof Error) throw response;+ return typeof response === "function" ? response(params) : response ?? {};+ },+ };+ loadMarketIpc()({+ registrar: {+ handle: (channel, handler) => handlers.set(channel, handler),+ },+ getHost: () => (host ? hostProcess : null),+ plugins: {+ loadFromPath: async () => {},+ drainToasts: () => [],+ getCommands: () => [],+ },+ agentExtensions: { allCommands: () => [] },+ optionalWorkspaceRoot: async () => null,+ pluginActiveInProject: () => true,+ sendToRenderer: () => {},+ });+ const invoke = (channel, ...args) => handlers.get(channel)(...args);+ return { invoke, calls };+}++test("review channels are registered and allowed through the preload gate", () => {+ assert.equal(IPC.invoke.marketReviewSummaries, "pi-desktop/market/reviewSummaries");+ assert.equal(IPC.invoke.marketReviews, "pi-desktop/market/reviews");+ assert.equal(IPC_WHITELIST.has(IPC.invoke.marketReviewSummaries), true);+ assert.equal(IPC_WHITELIST.has(IPC.invoke.marketReviews), true);+});++test("summary reads forward the ids and return the host payload unchanged", async () => {+ const summaries = {+ "demo.hello": {+ pluginId: "demo.hello",+ ratingAvg: 4.5,+ ratingCount: 2,+ ratingDist: [0, 0, 0, 1, 1],+ positiveCount: 2,+ neutralCount: 0,+ negativeCount: 0,+ },+ };+ const { invoke, calls } = setup({ "market.reviewSummaries": { summaries } });+ assert.deepEqual(await invoke(IPC.invoke.marketReviewSummaries, { pluginIds: ["demo.hello"] }), {+ summaries,+ });+ assert.deepEqual(calls, [+ { method: "market.reviewSummaries", params: { pluginIds: ["demo.hello"] } },+ ]);+});++test("a missing or malformed id list becomes an empty request, never a crash", async () => {+ const { invoke, calls } = setup({ "market.reviewSummaries": { summaries: {} } });+ await invoke(IPC.invoke.marketReviewSummaries);+ await invoke(IPC.invoke.marketReviewSummaries, { pluginIds: "demo.hello" });+ assert.deepEqual(calls, [+ { method: "market.reviewSummaries", params: { pluginIds: [] } },+ { method: "market.reviewSummaries", params: { pluginIds: [] } },+ ]);+});++test("review reads forward the query and return the page unchanged", async () => {+ const page = {+ reviews: [+ {+ id: "r1",+ pluginId: "demo.hello",+ authorName: "Ada",+ ratingHalfStars: 9,+ body: "Great plugin",+ status: "visible",+ pluginVersion: "",+ helpfulCount: 3,+ createdAt: "2026-10-01T00:00:00Z",+ updatedAt: "2026-10-01T00:00:00Z",+ editedAt: null,+ },+ ],+ nextCursor: null,+ summary: {+ pluginId: "demo.hello",+ ratingAvg: 4.5,+ ratingCount: 1,+ ratingDist: [0, 0, 0, 1, 0],+ positiveCount: 1,+ neutralCount: 0,+ negativeCount: 0,+ },+ reviewUrl: "https://plugins.aiuo.net/plugins/demo.hello#reviews",+ };+ const query = {+ pluginId: "demo.hello",+ limit: 20,+ sentiment: "all",+ sort: "newest",+ cursor: "cursor-2",+ };+ const { invoke, calls } = setup({ "market.reviews": page });+ assert.deepEqual(await invoke(IPC.invoke.marketReviews, query), page);+ assert.deepEqual(calls, [{ method: "market.reviews", params: query }]);+});++test("an unsupported or unreachable center reaches the caller unchanged", async () => {+ const outage = Object.assign(new Error("PLUGIN_NETWORK: review request failed"), {+ data: { errorCode: "PLUGIN_NETWORK" },+ });+ const { invoke } = setup({ "market.reviews": outage });+ await assert.rejects(+ invoke(IPC.invoke.marketReviews, { pluginId: "demo.hello" }),+ (error) => error.data?.errorCode === "PLUGIN_NETWORK",+ );+});++test("review reads require a running host", async () => {+ const { invoke } = setup({}, { host: false });+ await assert.rejects(invoke(IPC.invoke.marketReviewSummaries, { pluginIds: ["demo.hello"] }), {+ message: "host unavailable",+ });+});diff --git a/apps/desktop/test/plugin-reviews-logic.test.mjs b/apps/desktop/test/plugin-reviews-logic.test.mjsnew file mode 100644index 000000000..c7c8b6ec6--- /dev/null+++ b/apps/desktop/test/plugin-reviews-logic.test.mjs@@ -0,0 +1,324 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ REVIEW_PAGE_LIMIT,+ applyNextReviewPage,+ applyReviewPage,+ beginReviewLoad,+ beginReviewLoadMore,+ effectiveReviewUrl,+ failReviewLoad,+ formatRatingAvg,+ formatReviewRating,+ initialReviewListState,+ mergeReviews,+ nextSummaryMap,+ officialReviewUrl,+ reviewQuery,+ reviewQueryKey,+ sentimentShares,+} from "../src/features/plugins/reviews.ts";++function review(overrides = {}) {+ return {+ id: "r1",+ pluginId: "acme.todo",+ authorName: "Ada",+ ratingHalfStars: 9,+ body: "Works well.",+ status: "visible",+ pluginVersion: "1.2.0",+ helpfulCount: 2,+ createdAt: "2026-10-01T00:00:00Z",+ updatedAt: "2026-10-01T00:00:00Z",+ editedAt: null,+ ...overrides,+ };+}++function summary(overrides = {}) {+ return {+ pluginId: "acme.todo",+ ratingAvg: 4.5,+ ratingCount: 3,+ ratingDist: [0, 0, 0, 1, 2],+ positiveCount: 2,+ neutralCount: 1,+ negativeCount: 0,+ ...overrides,+ };+}++function page(overrides = {}) {+ return {+ reviews: [review()],+ nextCursor: null,+ summary: summary(),+ reviewUrl: "https://plugins.aiuo.net/plugins/acme.todo#reviews",+ ...overrides,+ };+}++test("the official review URL encodes the plugin id into the fallback page", () => {+ assert.equal(+ officialReviewUrl("acme.todo"),+ "https://plugins.aiuo.net/plugins/acme.todo#reviews",+ );+ assert.equal(+ officialReviewUrl("a/b c#d"),+ "https://plugins.aiuo.net/plugins/a%2Fb%20c%23d#reviews",+ );+});++test("the page URL wins only when it is a usable http(s) address", () => {+ assert.equal(+ effectiveReviewUrl("acme.todo", " http://127.0.0.1:8787/plugins/acme.todo#reviews "),+ "http://127.0.0.1:8787/plugins/acme.todo#reviews",+ );+ for (const bad of [null, undefined, "", " ", "javascript:alert(1)", "/relative", "data:text/plain"]) {+ assert.equal(+ effectiveReviewUrl("acme.todo", bad),+ "https://plugins.aiuo.net/plugins/acme.todo#reviews",+ `expected fallback for ${String(bad)}`,+ );+ }+});++test("one query key names exactly one plugin, sentiment and sort", () => {+ const a = reviewQueryKey("acme.todo", "all", "newest");+ assert.notEqual(a, reviewQueryKey("acme.todo", "positive", "newest"));+ assert.notEqual(a, reviewQueryKey("acme.todo", "all", "helpful"));+ assert.notEqual(a, reviewQueryKey("other.plugin", "all", "newest"));+ assert.equal(a, reviewQueryKey("acme.todo", "all", "newest"));+});++test("mergeReviews appends unseen rows once and keeps the shown order", () => {+ const first = review({ id: "r1" });+ const second = review({ id: "r2" });+ assert.deepEqual(+ mergeReviews([first], [first, second]).map((row) => row.id),+ ["r1", "r2"],+ );+ assert.deepEqual(+ mergeReviews([second], [first]).map((row) => row.id),+ ["r2", "r1"],+ );+ assert.deepEqual(mergeReviews([], []), []);+});++test("rating formatting follows the contract: one decimal, half stars trimmed", () => {+ assert.equal(formatRatingAvg(4.5, "en"), "4.5");+ assert.equal(formatRatingAvg(5, "en"), "5.0");+ assert.equal(formatRatingAvg(null, "en"), null);+ assert.equal(formatRatingAvg(undefined, "en"), null);+ assert.equal(formatRatingAvg(Number.NaN, "en"), null);++ assert.equal(formatReviewRating(9), "4.5");+ assert.equal(formatReviewRating(10), "5");+ assert.equal(formatReviewRating(2), "1");+ assert.equal(formatReviewRating(0), "0");+});++test("sentiment shares split the good / medium / bad counts into percentages", () => {+ const shares = sentimentShares(summary({ positiveCount: 2, neutralCount: 1, negativeCount: 0 }));+ assert.deepEqual(+ shares.map(({ key, count }) => [key, count]),+ [+ ["positive", 2],+ ["neutral", 1],+ ["negative", 0],+ ],+ );+ assert.deepEqual(+ shares.map(({ percent }) => percent),+ [67, 33, 0],+ );++ const empty = sentimentShares(null);+ assert.deepEqual(+ empty.map(({ count, percent }) => [count, percent]),+ [+ [0, 0],+ [0, 0],+ [0, 0],+ ],+ );+});++test("a query carries the page limit and only adds a cursor when paging", () => {+ assert.deepEqual(reviewQuery("acme.todo", "all", "newest"), {+ pluginId: "acme.todo",+ sentiment: "all",+ sort: "newest",+ limit: REVIEW_PAGE_LIMIT,+ });+ assert.deepEqual(reviewQuery("acme.todo", "negative", "helpful", "cursor-1"), {+ pluginId: "acme.todo",+ sentiment: "negative",+ sort: "helpful",+ limit: REVIEW_PAGE_LIMIT,+ cursor: "cursor-1",+ });+});++test("a first page fills the list and closes the load", () => {+ const key = reviewQueryKey("acme.todo", "all", "newest");+ const loading = beginReviewLoad(initialReviewListState(), key);+ assert.equal(loading.key, key);+ assert.equal(loading.status, "loading");++ const ready = applyReviewPage(loading, key, page({ nextCursor: "next-1" }), "acme.todo");+ assert.equal(ready.status, "ready");+ assert.equal(ready.error, null);+ assert.equal(ready.nextCursor, "next-1");+ assert.deepEqual(ready.reviews.map((row) => row.id), ["r1"]);+ assert.equal(ready.summary?.ratingAvg, 4.5);+ assert.equal(ready.reviewUrl, "https://plugins.aiuo.net/plugins/acme.todo#reviews");+});++test("a summary of zero reviews is carried through as zero, not as unavailable", () => {+ // The centre answers known plugins without reviews with a zero summary+ // (`ratingAvg: null`, `ratingCount: 0`); that is data the detail sheet can+ // show as "no reviews yet", which must stay distinct from "unavailable".+ const key = reviewQueryKey("acme.todo", "all", "newest");+ const zero = summary({+ ratingAvg: null,+ ratingCount: 0,+ ratingDist: [0, 0, 0, 0, 0],+ positiveCount: 0,+ neutralCount: 0,+ negativeCount: 0,+ });+ const state = applyReviewPage(+ beginReviewLoad(initialReviewListState(), key),+ key,+ page({ reviews: [], nextCursor: null, summary: zero }),+ "acme.todo",+ );+ assert.equal(state.status, "ready");+ assert.equal(state.summary?.ratingCount, 0);+ assert.equal(state.summary?.ratingAvg, null);+ assert.equal(formatRatingAvg(state.summary?.ratingAvg, "en"), null);+});++test("a summary answer replaces the requested ids, so an omitted id loses its rating", () => {+ // First batch: both ids answered.+ const first = nextSummaryMap(+ ["a.plugin", "b.plugin"],+ { "a.plugin": summary(), "b.plugin": summary({ pluginId: "b.plugin" }) },+ );+ assert.deepEqual(Object.keys(first).sort(), ["a.plugin", "b.plugin"]);++ // The centre deliberately omits an id it no longer serves (archived or+ // unpublished): the rating that was showing must go with it.+ const second = nextSummaryMap(["a.plugin", "b.plugin"], { "a.plugin": summary() });+ assert.deepEqual(Object.keys(second), ["a.plugin"]);++ // A key that was not requested never enters the map.+ const third = nextSummaryMap(+ ["a.plugin"],+ { "c.plugin": summary({ pluginId: "c.plugin" }) },+ );+ assert.deepEqual(third, {});++ // A requested id answered with a zero summary stays as zero, not missing.+ const zero = nextSummaryMap(+ ["a.plugin"],+ { "a.plugin": summary({ ratingAvg: null, ratingCount: 0 }) },+ );+ assert.equal(zero["a.plugin"]?.ratingCount, 0);+ assert.equal(zero["a.plugin"]?.ratingAvg, null);+});++test("a page that does not carry reviewUrl falls back to the official page", () => {+ // The host derives the trusted centre URL; until a host adds it, or if the+ // server page omits it, the write link still points somewhere real.+ const key = reviewQueryKey("acme.todo", "all", "newest");+ const state = applyReviewPage(+ beginReviewLoad(initialReviewListState(), key),+ key,+ page({ reviewUrl: undefined }),+ "acme.todo",+ );+ assert.equal(state.reviewUrl, "https://plugins.aiuo.net/plugins/acme.todo#reviews");+});++test("an answer for another query cannot reach the list on screen", () => {+ const keyA = reviewQueryKey("acme.todo", "all", "newest");+ const keyB = reviewQueryKey("acme.todo", "positive", "newest");+ const loadingB = beginReviewLoad(beginReviewLoad(initialReviewListState(), keyA), keyB);+ // The answer for A arrives while B owns the list: dropped entirely.+ const afterLateA = applyReviewPage(loadingB, keyA, page(), "acme.todo");+ assert.equal(afterLateA, loadingB);+ assert.deepEqual(afterLateA.reviews, []);+ assert.equal(afterLateA.status, "loading");+});++test("switching filter drops the old rows; retrying the same filter keeps them", () => {+ const keyA = reviewQueryKey("acme.todo", "all", "newest");+ const ready = applyReviewPage(+ beginReviewLoad(initialReviewListState(), keyA),+ keyA,+ page(),+ "acme.todo",+ );++ const switched = beginReviewLoad(ready, reviewQueryKey("acme.todo", "negative", "newest"));+ assert.deepEqual(switched.reviews, []);+ assert.equal(switched.status, "loading");+ assert.equal(switched.summary, null);++ const retried = beginReviewLoad(ready, keyA);+ assert.deepEqual(retried.reviews.map((row) => row.id), ["r1"]);+ assert.equal(retried.status, "ready");+ assert.equal(retried.error, null);+});++test("paging appends without repeating a row that moved between pages", () => {+ const key = reviewQueryKey("acme.todo", "all", "newest");+ let state = applyReviewPage(+ beginReviewLoad(initialReviewListState(), key),+ key,+ page({ reviews: [review({ id: "r1" }), review({ id: "r2" })], nextCursor: "next-1" }),+ "acme.todo",+ );+ state = beginReviewLoadMore(state);+ assert.equal(state.loadingMore, true);+ // The stable keyset cursor can hand back a row the user already saw when+ // the helpful order shifted; the id decides.+ state = applyNextReviewPage(+ state,+ key,+ page({ reviews: [review({ id: "r2" }), review({ id: "r3" })], nextCursor: null }),+ );+ assert.equal(state.loadingMore, false);+ assert.deepEqual(state.reviews.map((row) => row.id), ["r1", "r2", "r3"]);+ assert.equal(state.nextCursor, null);+});++test("a failure keeps readable rows and only replaces an empty list", () => {+ const key = reviewQueryKey("acme.todo", "all", "newest");+ const withRows = applyReviewPage(+ beginReviewLoad(initialReviewListState(), key),+ key,+ page(),+ "acme.todo",+ );+ const moreFailed = failReviewLoad(withRows, key, "boom");+ assert.equal(moreFailed.status, "ready");+ assert.equal(moreFailed.error, "boom");+ assert.deepEqual(moreFailed.reviews.map((row) => row.id), ["r1"]);++ const firstFailed = failReviewLoad(beginReviewLoad(initialReviewListState(), key), key, "boom");+ assert.equal(firstFailed.status, "error");+ assert.equal(firstFailed.error, "boom");+ assert.deepEqual(firstFailed.reviews, []);+});++test("a failure for a query that is no longer on screen is ignored", () => {+ const keyA = reviewQueryKey("acme.todo", "all", "newest");+ const keyB = reviewQueryKey("acme.todo", "helpful", "newest");+ const loadingB = beginReviewLoad(initialReviewListState(), keyB);+ assert.equal(failReviewLoad(loadingB, keyA, "boom"), loadingB);+});diff --git a/apps/desktop/test/plugin-reviews-surface.test.mjs b/apps/desktop/test/plugin-reviews-surface.test.mjsnew file mode 100644index 000000000..21555c061--- /dev/null+++ b/apps/desktop/test/plugin-reviews-surface.test.mjs@@ -0,0 +1,252 @@+/**+ * Source contracts for the installed plugin cards and the public review+ * surface. These pin the behaviour the redesign promised: grouped cards, one+ * call to action per enabled card, a read-only review drawer that covers the+ * detail sheet without unmounting it, and a composer that only ever links out+ * to the plugin centre.+ */+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { readPluginsSourceSync } from "./helpers/source-contracts.mjs";++const here = dirname(fileURLToPath(import.meta.url));+const read = (rel) => readFileSync(join(here, rel), "utf8");++const pageSrc = readPluginsSourceSync();+const installedPanel = read("../src/features/plugins/InstalledPluginsPanel.tsx");+const marketPanel = read("../src/features/plugins/MarketplacePanel.tsx");+const detailSheet = read("../src/features/plugins/PluginDetailSheet.tsx");+const drawer = read("../src/features/plugins/PluginReviewsDrawer.tsx");+const presentation = read("../src/features/plugins/presentation.tsx");+const hook = read("../src/features/plugins/usePluginReviews.ts");+const pageHook = read("../src/features/plugins/usePluginsPage.ts");+const pluginsCss = read("../src/styles/plugins.css");++test("installed plugins keep their state groups and their disclosure", () => {+ assert.match(installedPanel, /GROUP_LABEL_KEYS\[group\.id\]/);+ assert.match(installedPanel, /className="plugins-list"/);+ assert.match(installedPanel, /role="list"/);+ assert.match(installedPanel, /<PluginRowDetails/);+ assert.match(installedPanel, /<ScopeControl[\s\S]*?compact/);+ assert.match(pageSrc, /GROUP_ORDER: GroupId\[\] = \["attention", "updates", "active", "disabled"\]/);+});++test("an installed card grows one call to action: update, then open panel", () => {+ // The update button names the version it lands on.+ assert.match(installedPanel, /t\("plugins\.updateTo", \{ version: update\.version \}\)/);+ assert.match(installedPanel, /variant="primary"/);+ // Opening the panel is only offered while the plugin is enabled: the host+ // throws for a plugin it has not loaded.+ assert.match(installedPanel, /const canOpenPanel = plugin\.enabled && !!plugin\.ui\?\.panel/);+ assert.doesNotMatch(installedPanel, /\{plugin\.ui\?\.panel \?/);+ // Settings stay behind enabled + declared settings.+ assert.match(installedPanel, /plugin\.enabled && plugin\.settings\?\.length/);+ // A disabled plugin has no primary: both branches read plugin.enabled.+ assert.match(installedPanel, /\{plugin\.enabled && update \? \(/);+});++test("installed and marketplace cards carry the rating chip in their metadata", () => {+ assert.match(presentation, /export function RatingChip/);+ assert.match(presentation, /formatRatingAvg/);+ assert.match(presentation, /summary\.ratingCount <= 0/);+ assert.match(marketPanel, /<RatingChip[\s\S]*?summary=\{reviewSummaries\[item\.id\]\}/);+ assert.match(installedPanel, /<RatingChip[\s\S]*?summary=\{reviewSummaries\[plugin\.id\]\}/);+ // A chip lives inside the existing metadata line, so the card grows no row.+ assert.match(marketPanel, /plugins-card-meta[\s\S]*?<RatingChip/);+ assert.match(installedPanel, /plugins-row-meta[\s\S]*?<RatingChip/);+});++test("the installed card shows the trust glyph only from installed metadata", () => {+ assert.match(installedPanel, /showsVerifiedBadge\(plugin\.marketplace\)/);+ assert.match(installedPanel, /t\("plugins\.verified"\)/);+ // No "verified installed" wording anywhere: the shield carries the claim.+ assert.doesNotMatch(installedPanel, /verified installed/i);+});++test("the detail sheet puts the ratings summary between permissions and versions", () => {+ const permissions = detailSheet.indexOf('t("plugins.permissionsTitle")');+ const reviews = detailSheet.indexOf('t("plugins.reviews.summaryTitle")');+ const versions = detailSheet.indexOf('t("plugins.versions")');+ assert.ok(permissions >= 0 && reviews >= 0 && versions >= 0, "sections missing");+ assert.ok(permissions < reviews && reviews < versions, "ratings summary in the wrong place");+ assert.match(detailSheet, /<ReviewSummaryBlock summary=\{reviewSummary\} locale=\{locale\} \/>/);+ assert.match(detailSheet, /reviewSummary\.ratingCount > 0/);+ assert.match(detailSheet, /t\("plugins\.reviews\.unavailable"\)/);+ assert.match(detailSheet, /<Button[\s\S]*?ref=\{reviewsOpenerRef\}[\s\S]*?t\("plugins\.reviews\.viewAll"\)/);+ // The drawer entry is not gated on the summary: when the summary read+ // fails, the drawer stays reachable for its retry and its link out.+ assert.match(+ detailSheet,+ /<div className="plugins-sheet-reviews-action">[\s\S]*?ref=\{reviewsOpenerRef\}/,+ );+ assert.doesNotMatch(+ detailSheet,+ /\{reviewSummary \? \(\s*<div className="plugins-sheet-reviews-action">/,+ );+});++test("the review drawer mounts over the detail sheet without unmounting it", () => {+ // Same layer, rendered after the sheet: equal z-index, later DOM wins.+ assert.match(detailSheet, /<\/aside>\s*\{reviewsOpen && detail \? \([\s\S]*?<PluginReviewsDrawer/);+ assert.match(drawer, /className="plugins-reviews-layer"/);+ assert.match(pluginsCss, /\.plugins-reviews-layer\s*\{[^}]*position:\s*absolute[^}]*z-index:\s*1/);+ // The covered sheet keeps its mounted state but leaves the interaction+ // order until the drawer closes — its scrim included.+ assert.match(detailSheet, /inert=\{reviewsOpen\}/);+ assert.match(detailSheet, /className="plugins-sheet-scrim"[\s\S]*?inert=\{reviewsOpen\}/);+});++test("Escape closes the top drawer only and focus comes back to its opener", () => {+ // Escape is claimed with preventDefault + stopPropagation before anything+ // under the drawer sees it…+ assert.match(+ drawer,+ /if \(event\.key === "Escape"\) \{\s*event\.preventDefault\(\);\s*event\.stopPropagation\(\);\s*onClose\(\);\s*return;\s*\}/,+ );+ // …while the detail sheet stands down for as long as the drawer owns it.+ assert.match(pageHook, /if \(!selectedId \|\| pendingInstall \|\| installDialogOpen \|\| reviewsId\) return;/);+ // Tab is trapped inside the dialog's own surface, so focus can never reach+ // the covered sheet (also inert) or the page behind it.+ assert.match(drawer, /const focusables = focusableWithin\(root\)/);+ assert.match(drawer, /active === last[\s\S]*?first\.focus\(\)/);+ assert.match(drawer, /active === first[\s\S]*?last\.focus\(\)/);+ assert.match(drawer, /document\.addEventListener\("keydown", onKeyDown, true\)/);+ assert.match(detailSheet, /inert=\{reviewsOpen\}/);+ // Focus lands on the dialog when it opens and returns to the opener after.+ assert.match(drawer, /dialogRef\.current\?\.focus\(\)/);+ assert.match(detailSheet, /wasReviewsOpen\.current && !reviewsOpen/);+ assert.match(detailSheet, /reviewsOpenerRef\.current\?\.focus\(\)/);+ assert.match(drawer, /role="dialog"/);+ assert.match(drawer, /aria-modal="true"/);+ assert.match(drawer, /aria-labelledby=\{titleId\}/);+ assert.match(drawer, /tabIndex=\{-1\}/);+});++test("the drawer is a read-only surface whose one write path is the centre page", () => {+ // The scoped primitive, not a raw textarea.+ assert.match(drawer, /<Textarea[\s\S]*?className="plugins-reviews-composer-field"/);+ assert.match(drawer, /import \{ Button, Textarea, TooltipButton, cx \} from "\.\.\/\.\.\/components\/ui"/);+ assert.doesNotMatch(drawer, /<textarea/);+ assert.match(drawer, /disabled/);+ // A real anchor: middle-click and copy-link stay meaningful, and both the+ // primary click and a middle-click route through the system browser.+ assert.match(drawer, /<a\s[\s\S]*?className="plugins-reviews-write"[\s\S]*?href=\{reviewUrl\}/);+ assert.match(drawer, /event\.preventDefault\(\);\s*openReviewLink\(\);/);+ assert.match(drawer, /if \(event\.button !== 1\) return;/);+ // A refused or failed open is reported where the user is looking.+ assert.match(drawer, /await api\.browserOpenExternal\(reviewUrl\)/);+ assert.match(drawer, /showToast\([\s\S]*?variant: "error"/);+ assert.match(drawer, /t\("plugins\.reviews\.composeCta"\)/);+ // No desktop auth, votes, reports, or writes.+ assert.doesNotMatch(drawer, /marketReviewHelpful|marketReport|marketPostReview|fetch\(/);+ assert.doesNotMatch(drawer, /login|signIn/i);+});++test("a review's version reads as self-reported, never as an installed version", () => {+ assert.match(+ drawer,+ /t\("plugins\.reviews\.reviewVersion", \{\s*version: review\.pluginVersion,\s*\}\)/,+ );+ assert.doesNotMatch(drawer, /<span>v\{review\.pluginVersion\}<\/span>/);+});++test("the drawer filters, sorts, and pages with stale answers dropped", () => {+ assert.match(drawer, /REVIEW_SENTIMENTS\.map/);+ assert.match(drawer, /REVIEW_SORTS\.map/);+ assert.match(drawer, /aria-pressed=\{sentiment === value\}/);+ assert.match(drawer, /aria-pressed=\{sort === value\}/);+ assert.match(drawer, /state\.nextCursor/);+ assert.match(drawer, /t\("plugins\.reviews\.loadMore"\)/);+ assert.match(drawer, /t\("plugins\.reviews\.retry"\)/);+ assert.match(drawer, /role="alert"/);+ // The hook invalidates an in-flight answer's identity on every change, and+ // on unmount so a closed drawer never receives an old answer.+ assert.match(hook, /const generation = useRef\(0\)/);+ assert.match(hook, /if \(generation\.current !== request\) return;/);+ assert.match(hook, /return \(\) => \{\s*generation\.current \+= 1;\s*\};/);+ assert.match(hook, /reviewQuery\(pluginId, query\.sentiment, query\.sort\)/);+});++test("every installed and marketplace id is batched without a tab refresh", () => {+ assert.match(+ pageHook,+ /new Set\(\[\.\.\.plugins\.map\(\(plugin\) => plugin\.id\), \.\.\.market\.map\(\(item\) => item\.id\)\]\)/,+ );+ assert.match(pageHook, /api\.marketReviewSummaries\(ids\)/);+ // A successful answer replaces the map for the requested ids: an id the+ // centre omits (archived/unpublished) loses its stale rating.+ assert.match(pageHook, /setReviewSummaries\(nextSummaryMap\(ids, summaries\)\)/);+ assert.doesNotMatch(pageHook, /setReviewSummaries\(\(current\) => \(\{ \.\.\.current/);+ // An unsupported or unreachable centre is unavailable, never zero.+ assert.match(pageHook, /setReviewsStatus\("unavailable"\)/);+ assert.match(pageHook, /setReviewsStatus\("ready"\)/);+});++test("closing the detail closes the drawer with it", () => {+ assert.match(pageHook, /setReviewsId\(null\);\s*setSelectedId\(null\);/);+});++test("the review drawer keeps a real-Chromium user-path fixture", () => {+ // The source and reducer tests above are not the only evidence: the shipped+ // harness drives the real components through card -> summary -> drawer ->+ // filters/paging/error/link -> Escape in Electron. A refactor that breaks+ // that path must break this pin too.+ const harness = readFileSync(+ join(here, "../../../scripts/e2e-plugin-reviews-drawer.mjs"),+ "utf8",+ );+ const fixture = readFileSync(+ join(here, "../../../scripts/e2e/plugin-reviews-drawer.tsx"),+ "utf8",+ );+ assert.match(harness, /pluginReviewsDrawerProbe/);+ assert.match(harness, /pluginReviewsStaleSummaryProbe/);+ assert.match(harness, /pluginReviewsUnavailableSummaryProbe/);+ assert.match(harness, /pluginReviewsBatchProbe/);+ assert.match(harness, /pluginReviewsNarrowDrawerProbe/);+ assert.match(harness, /setContentSize/);+ assert.match(fixture, /usePluginsPage/);+ assert.match(fixture, /pluginReviewsDrawerProbe/);+ assert.match(fixture, /pluginReviewsStaleSummaryProbe/);+ assert.match(fixture, /pluginReviewsUnavailableSummaryProbe/);+ // The two closers: a narrow-viewport geometry pass and the rapid-typing+ // summaries batch that must never render a stale answer.+ assert.match(fixture, /pluginReviewsNarrowDrawerProbe/);+ assert.match(fixture, /pluginReviewsBatchProbe/);+ assert.match(fixture, /drawerRect/);+ assert.match(fixture, /lastIds/);+ assert.match(fixture, /plugins-reviews-write/);+ assert.match(fixture, /key: "Tab"/);+ assert.match(fixture, /key: "Escape"/);+ assert.match(fixture, /inert/);+ assert.match(fixture, /User-reported version/);+});++test("the installed grid keeps a real-Chromium user-path fixture", () => {+ const harness = readFileSync(+ join(here, "../../../scripts/e2e-installed-grid.mjs"),+ "utf8",+ );+ const fixture = readFileSync(+ join(here, "../../../scripts/e2e/installed-grid.tsx"),+ "utf8",+ );+ assert.match(harness, /installedGridLayoutProbe/);+ assert.match(harness, /installedGridActionsProbe/);+ assert.match(fixture, /InstalledPluginsPanel/);+ assert.match(fixture, /PluginDialogs/);+ // The behaviors the probe pins: the real scope control and its menu, the+ // rail shapes, group membership, the 340px grid floor, and the action path.+ assert.match(fixture, /scope-compact-trigger/);+ assert.match(fixture, /scope-compact-menu\.is-open/);+ assert.match(fixture, /plugins-row-controls/);+ assert.match(fixture, /marketInstall/);+ assert.match(fixture, /disablePlugin/);+ assert.match(fixture, /setPluginScope/);+ assert.match(fixture, /gridTemplateColumns/);+ assert.match(fixture, /340/);+});diff --git a/apps/desktop/test/plugins-page-style.test.mjs b/apps/desktop/test/plugins-page-style.test.mjsindex 1100f0487..40a0525f5 100644--- a/apps/desktop/test/plugins-page-style.test.mjs+++ b/apps/desktop/test/plugins-page-style.test.mjs@@ -79,15 +79,20 @@ test("plugins page styles tier permission risk with semantic tokens", () => {assert.match(section, /@media \(prefers-reduced-motion: reduce\)/);});-// D296: installed rows are separate soft tiles stacked with a gap, not one-// hairline-separated panel. Nothing clips, so the row overflow menu can overhang-// the tile below. AnchoredMenu owns viewport clamping for rows near the bottom.-test("plugins installed rows are stacked tiles that let row menus overhang", () => {+// The installed list is an auto-filling grid of soft tile cards: the gap does+// the work a hairline used to, `min(340px, 100%)` stops a column from+// overflowing a container narrower than one card, and nothing clips so a+// card's menu can overhang the tile below. AnchoredMenu owns viewport clamping+// for cards near the bottom.+test("installed plugins are cards in an auto-filling grid that lets menus overhang", () => {const section = pluginsSection(stylesSource);- assert.match(section, /\.plugins-list\s*\{[^}]*display:\s*flex[^}]*gap:\s*6px/);+ assert.match(+ section,+ /\.plugins-list\s*\{[^}]*display:\s*grid[^}]*grid-template-columns:\s*repeat\(auto-fill,\s*minmax\(min\(340px,\s*100%\),\s*1fr\)\)/,+ );assert.doesNotMatch(section, /\.plugins-list\s*\{[^}]*overflow:\s*hidden/);- assert.match(section, /\.plugins-row\s*\{[^}]*border-radius:\s*var\(--radius-md-plus\)[^}]*background:\s*var\(--plugins-tile\)/);+ assert.match(section, /\.plugins-row\s*\{[^}]*border-radius:\s*var\(--radius-lg\)[^}]*background:\s*var\(--plugins-tile\)/);assert.doesNotMatch(section, /\.plugins-row \+ \.plugins-row/);assert.doesNotMatch(section, /\.plugins-row:(first|last)-child/);assert.match(section, /\.plugins-menu\s*\{[\s\S]*?position:\s*fixed;/);@@ -114,24 +119,44 @@ test("extensions page draws no in-flow dividers", async () => {assert.doesNotMatch(pluginsCss, /\.plugins-market-settings/);});-test("installed rows default to a calm summary with accessible details", () => {+test("installed cards default to a calm summary with accessible details", () => {const section = pluginsSection(stylesSource);- assert.match(section, /\.plugins-row\s*\{[^}]*align-items:\s*center[^}]*padding:\s*13px 16px/);+ assert.match(section, /\.plugins-row\s*\{[^}]*flex-direction:\s*column[^}]*padding:\s*14px/);assert.match(section, /\.plugins-row-details\s*\{/);assert.match(section, /\.plugins-row-details-body\s*\{[^}]*background:\s*var\(--plugins-raised\)[^}]*box-shadow:\s*var\(--plugins-raised-shadow\)/);assert.match(section, /\.plugins-row-details-toggle:focus-visible\s*\{/);assert.match(section, /\.plugins-row-details\[open\] \.plugins-row-details-toggle > svg/);});-test("installed row controls share one aligned rail and explain icon actions", () => {+// The rail clusters at the card's left edge and wraps: compact scope first,+// then the card's one call to action, then the icon actions. It never pushes+// itself to the right edge, so a wrapped line still starts where the first+// one does.+test("installed card controls wrap from the card's left edge", () => {const section = pluginsSection(stylesSource);- assert.match(section, /\.plugins-row-controls\s*\{[\s\S]*?margin-left:\s*auto/);+ assert.match(section, /\.plugins-row-controls\s*\{[\s\S]*?flex-wrap:\s*wrap/);+ assert.doesNotMatch(section, /\.plugins-row-controls\s*\{[^}]*margin-left:\s*auto/);assert.match(section, /\.plugins-row-actions\s*\{[\s\S]*?opacity:\s*1/);assert.doesNotMatch(section, /\.plugins-row:hover \.plugins-row-actions/);assert.match(section, /\.plugins-icon-btn\s*\{[\s\S]*?position:\s*relative/);- assert.match(section, /\.plugins-icon-btn\s*\{/);+ assert.match(section, /\.plugins-icon-btn\s*\{[\s\S]*?width:\s*28px[\s\S]*?height:\s*28px/);+});++// Ratings and reviews are reads whose surfaces go through tokens in both+// themes: the chip rides a card's metadata line, and the drawer scrim is the+// modal veil token rather than a literal, so it reads over either palette.+test("review surfaces use design tokens in both themes", () => {+ const section = pluginsSection(stylesSource);++ assert.match(section, /\.plugins-rating\s*\{[^}]*font-variant-numeric:\s*tabular-nums/);+ assert.match(section, /\.plugins-reviews-summary\s*\{[^}]*background:\s*var\(--plugins-tile\)/);+ assert.match(section, /\.plugins-reviews-scrim\s*\{[^}]*background:\s*var\(--ds-modal-veil\)/);+ assert.match(section, /\.plugins-reviews\s*\{[\s\S]*?padding-top:\s*var\(--ds-toolbar-height\)/);+ assert.match(section, /\.plugins-reviews-composer-field\s*\{[^}]*background:\s*var\(--ds-field-inset-bg\)/);+ assert.match(section, /\.plugins-reviews-write\s*\{/);+ assert.match(stylesSource, /\.plugins-reviews,\s*\n\s*\.plugins-reviews-scrim,/);});// The 46px titlebar band floats over the destination pages on every platform: itdiff --git a/crates/host-core/src/plugins.rs b/crates/host-core/src/plugins.rsindex 2158e2ef4..4d23e4b9b 100644--- a/crates/host-core/src/plugins.rs+++ b/crates/host-core/src/plugins.rs@@ -29,6 +29,7 @@ mod providers;mod registry;mod renderer;mod resolve;+pub(crate) mod reviews;mod validation;pub use manifest::PluginManifest;@@ -76,4 +77,4 @@ pub(crate) use renderer::validate_renderer;pub(crate) use validation::{is_local_package_url, package_host_allowed, validate_contributions};#[cfg(test)]-mod tests;+pub(crate) mod tests;diff --git a/crates/host-core/src/plugins/reviews.rs b/crates/host-core/src/plugins/reviews.rsnew file mode 100644index 000000000..af1567a9c--- /dev/null+++ b/crates/host-core/src/plugins/reviews.rs@@ -0,0 +1,760 @@+//! Anonymous plugin reviews read from the plugin center.+//!+//! The desktop reads reviews and rating summaries through the host, so the+//! renderer keeps no network access of its own and no account, cookie, or+//! device credential is involved. Every request URL is built from the origin+//! of the effective catalog source — the trusted official center, or the+//! environment override that points a dev build or a test at a local fixture —+//! so review content can never redirect a request to another host.+//!+//! Reads are bounded: five seconds and one mebibyte per request, with ids+//! deduplicated and batched to the center's hundred-id summaries limit. A+//! failure propagates as an error; a zero summary is only ever the center's+//! own answer, never something this module made up. Redirects are refused —+//! every URL is already built against the trusted origin, so a 3xx is an+//! answer to reject, not a hop to follow — and curl is required, exactly as+//! for the plugin center's other endpoints.++use std::collections::{BTreeMap, BTreeSet};++use chrono::DateTime;++use super::*;++/// How long one review read may take before it is abandoned.+pub(crate) const REVIEW_TIMEOUT_SECONDS: u64 = 5;++/// Reviews are text; a larger answer is a broken one, not a page to render.+pub(crate) const MAX_REVIEW_RESPONSE_BYTES: usize = 1024 * 1024;++/// The number of plugin ids one summaries request may carry.+pub(crate) const MAX_SUMMARY_IDS: usize = 100;++/// Bodies a public read may carry; the write contract bounds them at 2000+/// unicode codepoints.+const MAX_REVIEW_BODY_CHARS: usize = 2000;++/// Display bounds for the strings a review row carries.+const MAX_AUTHOR_NAME_CHARS: usize = 200;+const MAX_PLUGIN_VERSION_CHARS: usize = 128;++/// Aggregated visible reviews for one plugin.+///+/// `rating_avg` is null exactly when nothing visible can be averaged; the+/// distribution is floored into whole-star buckets (4.5 -> index 3), matching+/// the center's contract.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PluginReviewSummary {+ pub plugin_id: String,+ pub rating_avg: Option<f64>,+ pub rating_count: u64,+ pub rating_dist: [u64; 5],+ pub positive_count: u64,+ pub neutral_count: u64,+ pub negative_count: u64,+}++/// Moderation state of one review.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum PluginReviewStatus {+ Visible,+ Pending,+ Hidden,+ Deleted,+}++/// One review as the public read returns it.+///+/// The field set is deliberately the public contract: the author's account id,+/// a hidden reason, and moderation/audit fields are not part of it, and serde+/// drops anything a misbehaving center might attach beyond these fields.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PluginReview {+ pub id: String,+ pub plugin_id: String,+ pub author_name: String,+ pub rating_half_stars: u8,+ pub body: String,+ pub status: PluginReviewStatus,+ pub plugin_version: String,+ pub helpful_count: u64,+ pub created_at: String,+ pub updated_at: String,+ #[serde(default)]+ pub edited_at: Option<String>,+}++/// One page of public reviews plus where the full list lives on the web.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PluginReviewPage {+ pub reviews: Vec<PluginReview>,+ pub next_cursor: Option<String>,+ pub summary: PluginReviewSummary,+ /// Reviews webpage on the trusted center, built by the host.+ pub review_url: String,+}++/// Which reviews one read asks for.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct PluginReviewQuery {+ pub(crate) plugin_id: String,+ pub(crate) cursor: Option<String>,+ pub(crate) limit: u32,+ pub(crate) sentiment: ReviewSentiment,+ pub(crate) sort: ReviewSort,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ReviewSentiment {+ All,+ Positive,+ Neutral,+ Negative,+}++impl ReviewSentiment {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::All => "all",+ Self::Positive => "positive",+ Self::Neutral => "neutral",+ Self::Negative => "negative",+ }+ }++ pub(crate) fn parse(value: &str) -> Option<Self> {+ match value {+ "all" => Some(Self::All),+ "positive" => Some(Self::Positive),+ "neutral" => Some(Self::Neutral),+ "negative" => Some(Self::Negative),+ _ => None,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ReviewSort {+ Newest,+ Helpful,+}++impl ReviewSort {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::Newest => "newest",+ Self::Helpful => "helpful",+ }+ }++ pub(crate) fn parse(value: &str) -> Option<Self> {+ match value {+ "newest" => Some(Self::Newest),+ "helpful" => Some(Self::Helpful),+ _ => None,+ }+ }+}++impl PluginManager {+ /// Origin of the trusted plugin center in effect.+ ///+ /// The effective catalog source decides: the configured official center,+ /// or the environment override a dev build or a test pointed at a local+ /// fixture. Only the origin is kept — review reads cannot leave the host+ /// the catalog came from — and a non-http(s) source has no review service+ /// at all, which callers report as unavailable rather than as zero data.+ pub(crate) fn review_origin(&self) -> Result<String> {+ review_origin_for_catalog(&self.market_source_url())+ .ok_or_else(|| anyhow!("PLUGIN_NETWORK: plugin reviews need an http(s) plugin center"))+ }+}++/// Trusted origin of a catalog URL.+///+/// The same rule the download-resolve endpoint uses: the scheme must be+/// http(s), the authority must be present and free of credentials, and only a+/// small host/port alphabet is admitted, so an odd catalog URL cannot smuggle+/// a query, fragment, or userinfo into a review request.+pub(crate) fn review_origin_for_catalog(catalog_url: &str) -> Option<String> {+ let (scheme, rest) = catalog_url.split_once("://")?;+ if scheme != "https" && scheme != "http" {+ return None;+ }+ let authority_end = rest.find('/').unwrap_or(rest.len());+ let authority = &rest[..authority_end];+ if authority.is_empty()+ || !authority+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']'))+ {+ return None;+ }+ Some(format!("{scheme}://{authority}"))+}++/// Deduplicate plugin ids and split them into center-sized batches.+///+/// The center accepts at most [`MAX_SUMMARY_IDS`] ids per summaries request,+/// and callers hand over the ids of whatever rows they are showing; dedup+/// keeps a plugin from being asked twice when several surfaces contribute the+/// same id.+pub(crate) fn summary_id_chunks(ids: &[String]) -> Vec<Vec<String>> {+ let mut seen = BTreeSet::new();+ let mut unique = Vec::with_capacity(ids.len());+ for id in ids {+ if seen.insert(id.as_str()) {+ unique.push(id.clone());+ }+ }+ unique+ .chunks(MAX_SUMMARY_IDS)+ .map(<[String]>::to_vec)+ .collect()+}++/// Summaries URL for one batch of ids on the trusted origin.+pub(crate) fn summaries_url(origin: &str, ids: &[String]) -> String {+ format!(+ "{origin}/api/v1/review-summaries?pluginIds={}",+ ids.join(",")+ )+}++/// Reviews URL for one query on the trusted origin.+pub(crate) fn reviews_url(origin: &str, query: &PluginReviewQuery) -> String {+ let mut url = format!(+ "{origin}/api/v1/plugins/{}/reviews?limit={}&sentiment={}&sort={}",+ encode_component(&query.plugin_id),+ query.limit,+ query.sentiment.as_str(),+ query.sort.as_str(),+ );+ if let Some(cursor) = &query.cursor {+ url.push_str("&cursor=");+ url.push_str(&encode_component(cursor));+ }+ url+}++/// Public reviews webpage for one plugin on the trusted center.+pub(crate) fn review_page_url(origin: &str, plugin_id: &str) -> String {+ format!("{origin}/plugins/{}#reviews", encode_component(plugin_id))+}++/// Read summaries for the given ids, batched and deduplicated.+///+/// Ids the center does not know are left out; ids the center answers for but+/// nobody asked about are dropped. A failed batch fails the whole read — a+/// partial map would be indistinguishable from "no reviews".+pub(crate) fn fetch_review_summaries(+ origin: &str,+ ids: &[String],+) -> Result<BTreeMap<String, PluginReviewSummary>> {+ let requested: BTreeSet<&str> = ids.iter().map(String::as_str).collect();+ let mut summaries = BTreeMap::new();+ for chunk in summary_id_chunks(ids) {+ let url = summaries_url(origin, &chunk);+ let (status, payload) = get_json(&url)?;+ if status != 200 {+ return Err(center_refusal(&url, status, &payload));+ }+ let wire: SummariesWire = serde_json::from_slice(&payload).map_err(|error| {+ anyhow!("PLUGIN_MARKET_INVALID: the plugin center's review summary answer is not readable: {error}")+ })?;+ for (id, summary) in wire.summaries {+ if !requested.contains(id.as_str()) {+ continue;+ }+ validate_summary(&summary, &id)?;+ summaries.insert(id, summary);+ }+ }+ Ok(summaries)+}++/// Read one page of public reviews plus its summary and webpage URL.+pub(crate) fn fetch_reviews(origin: &str, query: &PluginReviewQuery) -> Result<PluginReviewPage> {+ let url = reviews_url(origin, query);+ let (status, payload) = get_json(&url)?;+ if status != 200 {+ return Err(center_refusal(&url, status, &payload));+ }+ let wire: ReviewsWire = serde_json::from_slice(&payload).map_err(|error| {+ anyhow!("PLUGIN_MARKET_INVALID: the plugin center's review answer is not readable: {error}")+ })?;+ validate_summary(&wire.summary, &query.plugin_id)?;+ // The center owns paging, but a page larger than the limit that was asked+ // for is not one this client will render.+ if wire.reviews.len() > query.limit as usize {+ bail!("PLUGIN_MARKET_INVALID: the plugin center returned more reviews than the page limit");+ }+ for review in &wire.reviews {+ validate_review(review, &query.plugin_id)?;+ }+ validate_cursor(wire.next_cursor.as_deref())?;+ Ok(PluginReviewPage {+ reviews: wire.reviews,+ next_cursor: wire.next_cursor,+ summary: wire.summary,+ review_url: review_page_url(origin, &query.plugin_id),+ })+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct SummariesWire {+ summaries: BTreeMap<String, PluginReviewSummary>,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct ReviewsWire {+ reviews: Vec<PluginReview>,+ next_cursor: Option<String>,+ summary: PluginReviewSummary,+}++/// Validate one summary against the public contract.+///+/// The counters are one partition of the same visible rows: the five floor+/// buckets and the three sentiment counts each add up to `ratingCount`, and+/// the average exists exactly when there is at least one rating.+fn validate_summary(summary: &PluginReviewSummary, expected_id: &str) -> Result<()> {+ if summary.plugin_id != expected_id {+ bail!(+ "PLUGIN_MARKET_INVALID: review summary for {expected_id} names {}",+ summary.plugin_id+ );+ }+ let distribution = summary+ .rating_dist+ .iter()+ .try_fold(0_u64, |total, count| total.checked_add(*count));+ if distribution != Some(summary.rating_count) {+ bail!("PLUGIN_MARKET_INVALID: review summary for {expected_id} does not add up to its rating count");+ }+ let sentiments = summary+ .positive_count+ .checked_add(summary.neutral_count)+ .and_then(|total| total.checked_add(summary.negative_count));+ if sentiments != Some(summary.rating_count) {+ bail!("PLUGIN_MARKET_INVALID: review summary for {expected_id} sentiment counts do not add up to its rating count");+ }+ match (summary.rating_count, summary.rating_avg) {+ // No visible ratings means no average; a number there would render as+ // ratings nobody left.+ (0, Some(_)) => {+ bail!("PLUGIN_MARKET_INVALID: review summary for {expected_id} averages zero ratings")+ }+ (count, None) if count > 0 => {+ bail!("PLUGIN_MARKET_INVALID: review summary for {expected_id} has ratings but no average")+ }+ (_, Some(average)) if !average.is_finite() || !(0.0..=5.0).contains(&average) => {+ bail!("PLUGIN_MARKET_INVALID: review summary for {expected_id} has an out-of-range average");+ }+ _ => {}+ }+ Ok(())+}++/// Validate one public review row against the public contract.+///+/// The row must belong to the plugin that was asked about, carry a visible+/// moderation state, a 2..=10 half-star rating, ISO-8601 timestamps, and+/// display-bounded text; the author's account id and moderation details are+/// not part of the shape at all.+fn validate_review(review: &PluginReview, expected_plugin_id: &str) -> Result<()> {+ if review.plugin_id != expected_plugin_id {+ bail!(+ "PLUGIN_MARKET_INVALID: review {} belongs to {}, not {expected_plugin_id}",+ review.id,+ review.plugin_id+ );+ }+ if review.id.trim().is_empty() {+ bail!("PLUGIN_MARKET_INVALID: the public review list carried a review without an id");+ }+ if !(2..=10).contains(&review.rating_half_stars) {+ bail!(+ "PLUGIN_MARKET_INVALID: review {} has an out-of-range rating",+ review.id+ );+ }+ // The public list carries visible rows only; a moderation state leaking+ // into it is a contract violation, not something to render.+ if review.status != PluginReviewStatus::Visible {+ bail!("PLUGIN_MARKET_INVALID: the public review list carried a non-visible row");+ }+ if review.body.trim().is_empty() || review.body.chars().count() > MAX_REVIEW_BODY_CHARS {+ bail!(+ "PLUGIN_MARKET_INVALID: review {} has a body outside the public bounds",+ review.id+ );+ }+ if review.author_name.chars().count() > MAX_AUTHOR_NAME_CHARS {+ bail!(+ "PLUGIN_MARKET_INVALID: review {} has an author name outside the public bounds",+ review.id+ );+ }+ if review.plugin_version.chars().count() > MAX_PLUGIN_VERSION_CHARS {+ bail!(+ "PLUGIN_MARKET_INVALID: review {} has a plugin version outside the public bounds",+ review.id+ );+ }+ validate_review_date(&review.id, "createdAt", &review.created_at)?;+ validate_review_date(&review.id, "updatedAt", &review.updated_at)?;+ if let Some(edited_at) = &review.edited_at {+ validate_review_date(&review.id, "editedAt", edited_at)?;+ }+ Ok(())+}++fn validate_review_date(review_id: &str, field: &str, value: &str) -> Result<()> {+ if DateTime::parse_from_rfc3339(value).is_err() {+ bail!("PLUGIN_MARKET_INVALID: review {review_id} has an invalid {field} timestamp");+ }+ Ok(())+}++fn validate_cursor(cursor: Option<&str>) -> Result<()> {+ if let Some(cursor) = cursor {+ if cursor.len() > 4096 || cursor.chars().any(char::is_control) {+ bail!("PLUGIN_MARKET_INVALID: the plugin center returned an invalid review cursor");+ }+ }+ Ok(())+}++/// The error a non-2xx review answer becomes.+///+/// A center without the review routes (legacy deployment) is unavailable, not+/// a client mistake; a rate limit is its own state; a malformed request the+/// center rejected stays a market-invalid answer.+fn center_refusal(url: &str, status: u16, payload: &[u8]) -> anyhow::Error {+ let envelope: Option<Value> = serde_json::from_slice(payload).ok();+ let message = envelope+ .as_ref()+ .and_then(|value| value.get("error"))+ .and_then(|error| error.get("message"))+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|text| !text.is_empty())+ .unwrap_or("no reason given");+ match status {+ 429 => anyhow!("PLUGIN_MARKET_RATE_LIMITED: the plugin center asked to wait: {message}"),+ 400 => anyhow!(+ "PLUGIN_MARKET_INVALID: the plugin center refused the review request: {message}"+ ),+ // Every review URL is already built against the trusted origin, so a+ // redirect is an answer to reject: following one would move the read+ // to a host the catalog never named.+ 301 | 302 | 303 | 307 | 308 => anyhow!(+ "PLUGIN_NETWORK: the plugin center redirected {url}; review reads do not follow redirects"+ ),+ 404 | 405 | 501 => {+ anyhow!("PLUGIN_NETWORK: the plugin center does not serve plugin reviews ({status})")+ }+ _ => anyhow!("PLUGIN_NETWORK: the plugin center answered {status} for {url}: {message}"),+ }+}++/// One bounded anonymous GET against the trusted center origin.+///+/// Mirrors the marketplace download path, so proxy settings and TLS handling+/// stay identical to every other plugin-center request. The body lands in a+/// scratch file and the status is read from `--write-out`, so an error answer+/// still yields the center's error envelope instead of a curl diagnostic.+/// 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>)> {+ 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(),+ "--max-filesize".into(),+ MAX_REVIEW_RESPONSE_BYTES.to_string(),+ "--output".into(),+ response_path.to_string_lossy().into_owned(),+ "--write-out".into(),+ "%{http_code}".into(),+ "--user-agent".into(),+ "pi-desktop-host-core".into(),+ ];+ args.extend(crate::network_proxy::curl_proxy_args());+ args.extend(crate::network_proxy::curl_tls_args());+ if url.starts_with("https://") {+ args.push("--proto".into());+ args.push("=https".into());+ }+ args.push(url.to_string());++ let outcome = std::process::Command::new("curl").args(&args).output();+ match outcome {+ Ok(output) if output.status.success() => {+ let status = String::from_utf8_lossy(&output.stdout)+ .trim()+ .parse::<u16>()+ .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 {+ bail!(+ "PLUGIN_MARKET_INVALID: the plugin center's review answer exceeds the 1MiB limit"+ );+ }+ if status == 0 {+ bail!("PLUGIN_NETWORK: the plugin center gave no http status for {url}");+ }+ Ok((status, payload))+ }+ Ok(output) => {+ let _ = fs::remove_file(&response_path);+ // 63 is curl's `--max-filesize` refusal: a policy limit, not an+ // outage.+ if output.status.code() == Some(63) {+ bail!(+ "PLUGIN_MARKET_INVALID: the plugin center's review answer exceeds the 1MiB limit"+ );+ }+ bail!(+ "PLUGIN_NETWORK: review request failed for {url}: {}",+ decode_curl_output(&output.stderr)+ )+ }+ Err(error) => Err(anyhow!(+ "PLUGIN_NETWORK: curl is required to reach the plugin center: {error}"+ )),+ }+}++/// 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 {+ let mut out = String::with_capacity(value.len());+ for byte in value.bytes() {+ match byte {+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {+ out.push(byte as char);+ }+ _ => out.push_str(&format!("%{byte:02X}")),+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn review_reads_are_bounded() {+ assert_eq!(REVIEW_TIMEOUT_SECONDS, 5);+ assert_eq!(MAX_REVIEW_RESPONSE_BYTES, 1024 * 1024);+ assert_eq!(MAX_SUMMARY_IDS, 100);+ }++ #[test]+ fn the_origin_keeps_only_the_catalogs_host() {+ assert_eq!(+ review_origin_for_catalog("https://plugins.aiuo.net/catalog.json").as_deref(),+ Some("https://plugins.aiuo.net")+ );+ assert_eq!(+ review_origin_for_catalog("http://127.0.0.1:8787/catalog.json").as_deref(),+ Some("http://127.0.0.1:8787"),+ "a fixture deployment on a port keeps it"+ );+ assert_eq!(review_origin_for_catalog("file:///tmp/catalog.json"), None);+ assert_eq!(+ review_origin_for_catalog("https://user:[email protected]/catalog.json"),+ None,+ "credentials in a catalog url are not a review origin"+ );+ assert_eq!(+ review_origin_for_catalog("https://plugins.aiuo.net?x=1/catalog.json"),+ None,+ "a query smuggled into the authority is not a host"+ );+ }++ #[test]+ fn summaries_batches_dedupe_and_cap_at_one_hundred() {+ let mut ids: Vec<String> = (0..205).map(|index| format!("demo.p{index}")).collect();+ ids.push("demo.p0".into());+ ids.push("demo.p100".into());+ let chunks = summary_id_chunks(&ids);+ assert_eq!(chunks.len(), 3);+ assert_eq!(chunks[0].len(), 100);+ assert_eq!(chunks[1].len(), 100);+ assert_eq!(chunks[2].len(), 5);+ assert_eq!(chunks[0].iter().filter(|id| *id == "demo.p0").count(), 1);+ assert_eq!(chunks[1].iter().filter(|id| *id == "demo.p100").count(), 1);+ }++ #[test]+ fn review_urls_stay_on_the_trusted_origin() {+ let query = PluginReviewQuery {+ plugin_id: "demo.hello".into(),+ cursor: Some("a b/c+d=e".into()),+ limit: 10,+ sentiment: ReviewSentiment::Positive,+ sort: ReviewSort::Helpful,+ };+ assert_eq!(+ reviews_url("https://plugins.aiuo.net", &query),+ "https://plugins.aiuo.net/api/v1/plugins/demo.hello/reviews?limit=10&sentiment=positive&sort=helpful&cursor=a%20b%2Fc%2Bd%3De"+ );+ assert_eq!(+ summaries_url("http://127.0.0.1:8787", &["a.b".into(), "c-d".into()]),+ "http://127.0.0.1:8787/api/v1/review-summaries?pluginIds=a.b,c-d"+ );+ assert_eq!(+ review_page_url("https://plugins.aiuo.net", "demo.hello"),+ "https://plugins.aiuo.net/plugins/demo.hello#reviews"+ );+ }++ fn summary_consistent() -> PluginReviewSummary {+ PluginReviewSummary {+ plugin_id: "demo.hello".into(),+ rating_avg: Some(4.5),+ rating_count: 2,+ rating_dist: [0, 0, 0, 1, 1],+ positive_count: 2,+ neutral_count: 0,+ negative_count: 0,+ }+ }++ #[test]+ fn summary_consistency_is_enforced() {+ let valid = summary_consistent();+ assert!(validate_summary(&valid, "demo.hello").is_ok());++ let mut wrong_plugin = valid.clone();+ wrong_plugin.plugin_id = "demo.other".into();+ assert!(validate_summary(&wrong_plugin, "demo.hello").is_err());++ // A zero-count summary must carry no average.+ let zero_with_average = PluginReviewSummary {+ rating_avg: Some(1.0),+ rating_count: 0,+ rating_dist: [0, 0, 0, 0, 0],+ positive_count: 0,+ neutral_count: 0,+ negative_count: 0,+ ..valid.clone()+ };+ assert!(validate_summary(&zero_with_average, "demo.hello").is_err());++ // Ratings without an average are equally inconsistent.+ let missing_average = PluginReviewSummary {+ rating_avg: None,+ ..valid.clone()+ };+ assert!(validate_summary(&missing_average, "demo.hello").is_err());++ // The distribution must add up to the rating count.+ let bad_dist = PluginReviewSummary {+ rating_dist: [0, 0, 0, 1, 0],+ ..valid.clone()+ };+ assert!(validate_summary(&bad_dist, "demo.hello").is_err());++ // So must the sentiment counts.+ let bad_sentiments = PluginReviewSummary {+ positive_count: 1,+ neutral_count: 1,+ negative_count: 1,+ ..valid.clone()+ };+ assert!(validate_summary(&bad_sentiments, "demo.hello").is_err());++ let out_of_range = PluginReviewSummary {+ rating_avg: Some(5.5),+ ..valid.clone()+ };+ assert!(validate_summary(&out_of_range, "demo.hello").is_err());++ let zero = PluginReviewSummary {+ plugin_id: "demo.hello".into(),+ rating_avg: None,+ rating_count: 0,+ rating_dist: [0, 0, 0, 0, 0],+ positive_count: 0,+ neutral_count: 0,+ negative_count: 0,+ };+ assert!(validate_summary(&zero, "demo.hello").is_ok());+ }++ fn review_consistent() -> PluginReview {+ PluginReview {+ id: "r1".into(),+ plugin_id: "demo.hello".into(),+ author_name: "Ada".into(),+ rating_half_stars: 9,+ body: "Works well.".into(),+ status: PluginReviewStatus::Visible,+ plugin_version: "1.2.0".into(),+ helpful_count: 3,+ created_at: "2026-10-01T00:00:00Z".into(),+ updated_at: "2026-10-01T00:00:00Z".into(),+ edited_at: None,+ }+ }++ #[test]+ fn review_contract_is_enforced() {+ let valid = review_consistent();+ assert!(validate_review(&valid, "demo.hello").is_ok());++ let wrong_plugin = PluginReview {+ plugin_id: "demo.other".into(),+ ..valid.clone()+ };+ assert!(validate_review(&wrong_plugin, "demo.hello").is_err());++ let mut pending = valid.clone();+ pending.status = PluginReviewStatus::Pending;+ assert!(validate_review(&pending, "demo.hello").is_err());++ let mut bad_rating = valid.clone();+ bad_rating.rating_half_stars = 1;+ assert!(validate_review(&bad_rating, "demo.hello").is_err());++ let mut bad_created = valid.clone();+ bad_created.created_at = "yesterday".into();+ assert!(validate_review(&bad_created, "demo.hello").is_err());++ let mut bad_edited = valid.clone();+ bad_edited.edited_at = Some("2026-13-45T00:00:00Z".into());+ assert!(validate_review(&bad_edited, "demo.hello").is_err());++ let mut empty_body = valid.clone();+ empty_body.body = " ".into();+ assert!(validate_review(&empty_body, "demo.hello").is_err());++ let mut long_body = valid.clone();+ long_body.body = "x".repeat(MAX_REVIEW_BODY_CHARS + 1);+ assert!(validate_review(&long_body, "demo.hello").is_err());++ // The empty version the contract permits, and an edit timestamp, both+ // stay acceptable.+ let mut edited = valid.clone();+ edited.plugin_version = String::new();+ edited.edited_at = Some("2026-10-02T00:00:00Z".into());+ assert!(validate_review(&edited, "demo.hello").is_ok());+ }+}diff --git a/crates/host-core/src/plugins/tests.rs b/crates/host-core/src/plugins/tests.rsindex 966838994..78a4fba17 100644--- a/crates/host-core/src/plugins/tests.rs+++ b/crates/host-core/src/plugins/tests.rs@@ -6,8 +6,9 @@ use tempfile::tempdir;////// The marketplace source is process-global, so two tests pointing it at/// different catalogs — or one clearing it while another is mid-fetch —-/// read each other's value.-static MARKET_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+/// read each other's value. Shared with the review RPC tests, which repoint+/// the same variable at an in-process fixture center.+pub(crate) static MARKET_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());fn lock_market_env() -> std::sync::MutexGuard<'static, ()> {MARKET_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex ea707e45f..790e318d0 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -1,4 +1,5 @@mod config_sync_rpc;+mod plugin_reviews_rpc;mod remote_tools;mod scheduled_rpc;mod scheduled_tools;@@ -6,6 +7,9 @@ mod todos;mod window_corner_rpc;mod worktree_rpc;+#[cfg(test)]+mod plugin_reviews_rpc_tests;+use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};use std::path::{Path, PathBuf};use std::sync::Arc;@@ -1669,6 +1673,10 @@ fn plugin_err(err: impl ToString) -> JsonRpcError {rpc_err(1023, msg, "PLUGIN_MARKET_RATE_LIMITED")} else if msg.contains("PLUGIN_MARKET_NO_SOURCE") {rpc_err(1024, msg, "PLUGIN_MARKET_NO_SOURCE")+ } else if msg.contains("PLUGIN_MARKET_INVALID") {+ // The center answered something this client refuses to render, which+ // is the client's contract violation, not an internal crash.+ rpc_err(1026, msg, "PLUGIN_MARKET_INVALID")} else if msg.contains("PLUGIN_NETWORK") {rpc_err(1014, msg, "PLUGIN_NETWORK")} else {@@ -5246,6 +5254,9 @@ async fn handle_request(.map_err(|message| rpc_err(1002, message, "INVALID_PARAMS"))?;Ok(json!({ "ok": true }))}+ "market.reviewSummaries" | "market.reviews" => {+ plugin_reviews_rpc::handle(&state, method, params).await+ }"market.refresh" => {let force = params.get("force")diff --git a/crates/host-core/src/rpc/plugin_reviews_rpc.rs b/crates/host-core/src/rpc/plugin_reviews_rpc.rsnew file mode 100644index 000000000..8a2d97a7b--- /dev/null+++ b/crates/host-core/src/rpc/plugin_reviews_rpc.rs@@ -0,0 +1,195 @@+//! `market.reviewSummaries` and `market.reviews` (plugin reviews, read-only).+//!+//! The desktop reads reviews anonymously through the host: the renderer never+//! touches the network, and no session or credential is involved. The trusted+//! center origin is captured under the host state lock and the lock is+//! released before any I/O, so a slow or down center cannot stall unrelated+//! host requests behind the five-second review deadline.++use std::sync::Arc;++use serde_json::{json, Value};+use tokio::sync::Mutex;++use super::{plugin_err, rpc_err, JsonRpcError};+use crate::plugins::reviews::{+ fetch_review_summaries, fetch_reviews, PluginReviewQuery, ReviewSentiment, ReviewSort,+};+use crate::state::AppState;++/// Longest plugin id accepted; the manifest and catalog alphabet is far+/// smaller, and the bound keeps a renderer bug from building an endless URL.+const MAX_PLUGIN_ID_LEN: usize = 128;+const MAX_CURSOR_LEN: usize = 4096;+const DEFAULT_REVIEW_LIMIT: u32 = 20;+const MAX_REVIEW_LIMIT: u32 = 100;++pub(super) async fn handle(+ state: &Arc<Mutex<AppState>>,+ method: &str,+ params: Value,+) -> Result<Value, JsonRpcError> {+ match method {+ "market.reviewSummaries" => review_summaries(state, params).await,+ "market.reviews" => reviews(state, params).await,+ _ => Err(rpc_err(+ -32601,+ format!("method not found: {method}"),+ "NOT_FOUND",+ )),+ }+}++/// Rating summaries for the given plugin ids.+///+/// The renderer sends whatever ids it is showing; the host deduplicates them+/// and batches to the center's hundred-id limit. An empty list answers with an+/// empty map without touching the network, because there is nothing to ask.+async fn review_summaries(+ state: &Arc<Mutex<AppState>>,+ params: Value,+) -> Result<Value, JsonRpcError> {+ let ids = parse_ids(¶ms)?;+ if ids.is_empty() {+ return Ok(json!({ "summaries": {} }));+ }+ let origin = review_origin(state).await?;+ let summaries = tokio::task::spawn_blocking(move || fetch_review_summaries(&origin, &ids))+ .await+ .map_err(worker_error)?+ .map_err(plugin_err)?;+ Ok(json!({ "summaries": summaries }))+}++/// One page of public reviews, with the summary and the trusted webpage URL.+async fn reviews(state: &Arc<Mutex<AppState>>, params: Value) -> Result<Value, JsonRpcError> {+ let query = parse_query(¶ms)?;+ let origin = review_origin(state).await?;+ let page = tokio::task::spawn_blocking(move || fetch_reviews(&origin, &query))+ .await+ .map_err(worker_error)?+ .map_err(plugin_err)?;+ serde_json::to_value(page).map_err(|error| {+ rpc_err(+ 1000,+ format!("review page is not serializable: {error}"),+ "INTERNAL",+ )+ })+}++/// Capture the trusted review origin and release the state lock.+///+/// The center must never be able to hold `AppState`: a request that awaits the+/// network while the lock is held would queue every other host method behind+/// its deadline.+async fn review_origin(state: &Arc<Mutex<AppState>>) -> Result<String, JsonRpcError> {+ let origin = {+ let st = state.lock().await;+ st.plugins.review_origin()+ };+ origin.map_err(plugin_err)+}++fn worker_error(error: tokio::task::JoinError) -> JsonRpcError {+ rpc_err(1000, format!("review worker failed: {error}"), "INTERNAL")+}++fn parse_ids(params: &Value) -> Result<Vec<String>, JsonRpcError> {+ let raw = params+ .get("pluginIds")+ .ok_or_else(|| rpc_err(1002, "pluginIds required", "INVALID_PARAMS"))?;+ let items = raw.as_array().ok_or_else(|| {+ rpc_err(+ 1002,+ "pluginIds must be an array of strings",+ "INVALID_PARAMS",+ )+ })?;+ let mut ids = Vec::with_capacity(items.len());+ for item in items {+ let id = item.as_str().ok_or_else(|| {+ rpc_err(+ 1002,+ "pluginIds must be an array of strings",+ "INVALID_PARAMS",+ )+ })?;+ ids.push(validate_plugin_id(id)?);+ }+ Ok(ids)+}++fn parse_query(params: &Value) -> Result<PluginReviewQuery, JsonRpcError> {+ let plugin_id = params+ .get("pluginId")+ .and_then(Value::as_str)+ .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;+ let plugin_id = validate_plugin_id(plugin_id)?;+ let cursor = match params.get("cursor") {+ None | Some(Value::Null) => None,+ Some(Value::String(value)) => {+ let value = value.trim();+ if value.is_empty() {+ None+ } else if value.len() > MAX_CURSOR_LEN || value.chars().any(char::is_control) {+ return Err(rpc_err(1002, "cursor is invalid", "INVALID_PARAMS"));+ } else {+ Some(value.to_string())+ }+ }+ Some(_) => return Err(rpc_err(1002, "cursor must be a string", "INVALID_PARAMS")),+ };+ let limit = match params.get("limit") {+ None | Some(Value::Null) => DEFAULT_REVIEW_LIMIT,+ Some(value) => {+ let number = value+ .as_u64()+ .ok_or_else(|| rpc_err(1002, "limit must be a number", "INVALID_PARAMS"))?;+ if number == 0 || number > u64::from(MAX_REVIEW_LIMIT) {+ return Err(rpc_err(+ 1002,+ format!("limit must be between 1 and {MAX_REVIEW_LIMIT}"),+ "INVALID_PARAMS",+ ));+ }+ number as u32+ }+ };+ let sentiment = match params.get("sentiment") {+ None | Some(Value::Null) => ReviewSentiment::All,+ Some(value) => ReviewSentiment::parse(value.as_str().unwrap_or_default())+ .ok_or_else(|| rpc_err(1002, "sentiment is invalid", "INVALID_PARAMS"))?,+ };+ let sort = match params.get("sort") {+ None | Some(Value::Null) => ReviewSort::Newest,+ Some(value) => ReviewSort::parse(value.as_str().unwrap_or_default())+ .ok_or_else(|| rpc_err(1002, "sort is invalid", "INVALID_PARAMS"))?,+ };+ Ok(PluginReviewQuery {+ plugin_id,+ cursor,+ limit,+ sentiment,+ sort,+ })+}++/// A plugin id as the catalog and manifests spell it.+fn validate_plugin_id(value: &str) -> Result<String, JsonRpcError> {+ let id = value.trim();+ let valid = !id.is_empty()+ && id.len() <= MAX_PLUGIN_ID_LEN+ && id+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'));+ if !valid {+ let shown: String = value.chars().take(80).collect();+ return Err(rpc_err(+ 1002,+ format!("invalid pluginId: {shown}"),+ "INVALID_PARAMS",+ ));+ }+ Ok(id.to_string())+}diff --git a/crates/host-core/src/rpc/plugin_reviews_rpc_tests.rs b/crates/host-core/src/rpc/plugin_reviews_rpc_tests.rsnew file mode 100644index 000000000..2dec99da5--- /dev/null+++ b/crates/host-core/src/rpc/plugin_reviews_rpc_tests.rs@@ -0,0 +1,791 @@+// 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::collections::BTreeMap;+use std::ffi::OsString;+use std::sync::{Arc, Mutex as StdMutex, MutexGuard};+use std::time::{Duration, Instant};++use serde_json::{json, Map, Value};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::{TcpListener, TcpStream};+use tokio::sync::{mpsc, Mutex};++use super::handle_request;+use crate::plugins::reviews::MAX_REVIEW_RESPONSE_BYTES;+use crate::plugins::tests::MARKET_ENV_LOCK;+use crate::state::AppState;++/// Catalog source used while the host state is built, so opening it never+/// touches the fixture (the runtime is single-threaded and the listener could+/// not be accepted while `AppState::open` blocks).+const OFFLINE_MARKET_URL: &str = "file:///nope/does-not-exist-catalog.json";++/// Holds the shared market lock and restores the previous source on drop.+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());+ let previous = std::env::var_os("PI_DESKTOP_PLUGIN_MARKET_URL");+ Self {+ _guard: guard,+ previous,+ }+ }++ 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) {+ 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;+ let state = Arc::new(Mutex::new(app_state));+ let tx = mpsc::unbounded_channel().0;+ (data, state, tx)+}++#[derive(Default)]+struct CenterState {+ /// Summary values keyed by plugin id; ids missing here are omitted, which+ /// is how the center reports unknown plugins.+ summaries: BTreeMap<String, Value>,+ /// Status and JSON body for the reviews route.+ reviews: Option<(u16, Value)>,+ /// Raw status and body for the summaries route, for malformed answers.+ summaries_override: Option<(u16, String)>,+ /// Answer the next request with a redirect to this location instead.+ redirect_to: Option<String>,+ /// Accept the request and never answer.+ hang: bool,+ /// Query strings the summaries route saw, in arrival order.+ summary_queries: Vec<String>,+ /// Every request target seen.+ requests: Vec<String>,+}++/// What one fixture request is answered with.+enum Reply {+ Body(u16, String),+ Redirect(String),+}++struct Center {+ catalog_url: String,+ state: Arc<StdMutex<CenterState>>,+}++impl Center {+ async fn start() -> Self {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let state = Arc::new(StdMutex::new(CenterState::default()));+ let serving = state.clone();+ tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ break;+ };+ let state = serving.clone();+ tokio::spawn(async move { serve(stream, state).await });+ }+ });+ Self {+ catalog_url: format!("http://{address}/catalog.json"),+ state,+ }+ }++ fn set(&self, update: impl FnOnce(&mut CenterState)) {+ update(&mut self.state.lock().unwrap());+ }++ fn origin(&self) -> String {+ self.catalog_url+ .strip_suffix("/catalog.json")+ .unwrap()+ .to_string()+ }++ fn summary_queries(&self) -> Vec<String> {+ self.state.lock().unwrap().summary_queries.clone()+ }++ fn requests(&self) -> Vec<String> {+ self.state.lock().unwrap().requests.clone()+ }+}++async fn serve(mut stream: TcpStream, state: Arc<StdMutex<CenterState>>) {+ let mut buffer = Vec::new();+ let mut chunk = [0_u8; 4096];+ loop {+ match stream.read(&mut chunk).await {+ Ok(0) => break,+ Ok(read) => {+ buffer.extend_from_slice(&chunk[..read]);+ if buffer.windows(4).any(|window| window == b"\r\n\r\n") {+ break;+ }+ }+ Err(_) => return,+ }+ }+ 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 (path, query) = match target.split_once('?') {+ Some((path, query)) => (path.to_string(), query.to_string()),+ None => (target.clone(), String::new()),+ };+ let response = {+ let mut state = state.lock().unwrap();+ state.requests.push(target.clone());+ if state.hang {+ None+ } else if let Some(location) = state.redirect_to.take() {+ Some(Reply::Redirect(location))+ } else if path == "/api/v1/review-summaries" {+ state.summary_queries.push(query.clone());+ match &state.summaries_override {+ Some((status, body)) => Some(Reply::Body(*status, body.clone())),+ None => {+ let requested = query.strip_prefix("pluginIds=").unwrap_or("");+ let mut map = Map::new();+ for id in requested.split(',').filter(|id| !id.is_empty()) {+ if let Some(summary) = state.summaries.get(id) {+ map.insert(id.to_string(), summary.clone());+ }+ }+ Some(Reply::Body(200, json!({ "summaries": map }).to_string()))+ }+ }+ } else if path.starts_with("/api/v1/plugins/") && path.ends_with("/reviews") {+ match &state.reviews {+ Some((status, body)) => Some(Reply::Body(*status, body.to_string())),+ None => Some(Reply::Body(+ 404,+ "{\"error\":{\"code\":\"NOT_FOUND\"}}".to_string(),+ )),+ }+ } else {+ Some(Reply::Body(+ 404,+ "{\"error\":{\"code\":\"NOT_FOUND\"}}".to_string(),+ ))+ }+ };+ let (status, body, location) = match response {+ // Hang: keep the connection open without ever answering.+ None => {+ tokio::time::sleep(Duration::from_secs(30)).await;+ return;+ }+ Some(Reply::Body(status, body)) => (status, body, None),+ Some(Reply::Redirect(location)) => (302, String::new(), Some(location)),+ };+ let head = match location {+ Some(location) => format!(+ "HTTP/1.1 {status} Fixture\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"+ ),+ None => 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 zero_summary(plugin_id: &str) -> Value {+ json!({+ "pluginId": plugin_id,+ "ratingAvg": null,+ "ratingCount": 0,+ "ratingDist": [0, 0, 0, 0, 0],+ "positiveCount": 0,+ "neutralCount": 0,+ "negativeCount": 0,+ })+}++fn error_code(error: &super::JsonRpcError) -> String {+ error+ .data+ .as_ref()+ .and_then(|data| data.get("errorCode"))+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string()+}++async fn summaries_via(+ state: Arc<Mutex<AppState>>,+ tx: mpsc::UnboundedSender<String>,+ ids: Value,+) -> Result<Value, super::JsonRpcError> {+ handle_request(+ state,+ "market.reviewSummaries",+ json!({ "pluginIds": ids }),+ tx,+ )+ .await+}++#[tokio::test]+async fn review_summaries_rpc_returns_only_the_centers_answers() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| {+ fixture.summaries.insert(+ "demo.hello".into(),+ json!({+ "pluginId": "demo.hello",+ "ratingAvg": 4.5,+ "ratingCount": 2,+ "ratingDist": [0, 0, 0, 1, 1],+ "positiveCount": 2,+ "neutralCount": 0,+ "negativeCount": 0,+ }),+ );+ fixture+ .summaries+ .insert("demo.notes".into(), zero_summary("demo.notes"));+ });+ env.point_at(¢er.catalog_url);++ let result = summaries_via(+ state,+ tx,+ json!(["demo.hello", "demo.notes", "demo.unknown"]),+ )+ .await+ .unwrap();++ assert_eq!(result["summaries"]["demo.hello"]["ratingAvg"], json!(4.5));+ assert_eq!(+ result["summaries"]["demo.hello"]["ratingDist"],+ json!([0, 0, 0, 1, 1])+ );+ // A known plugin without reviews gets the center's own zero summary.+ assert_eq!(result["summaries"]["demo.notes"]["ratingCount"], json!(0));+ // An unknown plugin is omitted, never fabricated as a zero row.+ assert!(result["summaries"].get("demo.unknown").is_none());+ assert_eq!(+ center.summary_queries(),+ vec!["pluginIds=demo.hello,demo.notes,demo.unknown"]+ );+}++#[tokio::test]+async fn review_summaries_rpc_dedupes_and_chunks_installed_ids() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ env.point_at(¢er.catalog_url);++ let mut ids: Vec<String> = (0..205).map(|index| format!("demo.p{index}")).collect();+ ids.push("demo.p0".into());+ ids.push("demo.p100".into());+ let result = summaries_via(state, tx, json!(ids)).await.unwrap();+ assert_eq!(result["summaries"], json!({}));++ let queries = center.summary_queries();+ assert_eq!(queries.len(), 3, "{queries:?}");+ let batches: Vec<Vec<&str>> = queries+ .iter()+ .map(|query| {+ query+ .strip_prefix("pluginIds=")+ .unwrap()+ .split(',')+ .collect()+ })+ .collect();+ assert_eq!(batches[0].len(), 100);+ assert_eq!(batches[1].len(), 100);+ assert_eq!(batches[2].len(), 5);+ assert_eq!(batches[0].iter().filter(|id| **id == "demo.p0").count(), 1);+ assert_eq!(+ batches[1].iter().filter(|id| **id == "demo.p100").count(),+ 1+ );+ assert_eq!(batches[2].first(), Some(&"demo.p200"));+}++#[tokio::test]+async fn review_summaries_rpc_is_empty_without_asking_the_center() {+ let env = MarketEnv::hold();+ // No service at all: an empty request must not need one.+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();++ let result = summaries_via(state, tx, json!([])).await.unwrap();+ assert_eq!(result, json!({ "summaries": {} }));+}++#[tokio::test]+async fn review_summaries_rpc_rejects_malformed_center_answers() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| {+ fixture.summaries_override = Some((+ 200,+ "{\"summaries\":{\"demo.hello\":{\"pluginId\":\"demo.hello\"}}}".into(),+ ));+ });+ env.point_at(¢er.catalog_url);++ let error = summaries_via(state, tx, json!(["demo.hello"]))+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_MARKET_INVALID");+ assert_eq!(error.code, 1026);+ assert!(error.message.contains("not readable"), "{}", error.message);+}++#[tokio::test]+async fn review_summaries_rpc_reports_a_legacy_center_as_unavailable() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| {+ fixture.summaries_override = Some((404, "{\"error\":{\"code\":\"NOT_FOUND\"}}".into()));+ });+ env.point_at(¢er.catalog_url);++ let error = summaries_via(state, tx, json!(["demo.hello"]))+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_NETWORK");+ assert!(+ error.message.contains("does not serve plugin reviews"),+ "{}",+ error.message+ );+}++#[tokio::test]+async fn review_summaries_rpc_never_fabricates_zeros_when_the_center_is_down() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ // Bind and drop a port so nothing answers on it.+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ drop(listener);+ env.point_at(&format!("http://{address}/catalog.json"));++ let error = summaries_via(state, tx, json!(["demo.hello"]))+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_NETWORK");+ assert!(+ error.message.contains("review request failed"),+ "{}",+ error.message+ );+}++#[tokio::test]+async fn review_summaries_rpc_stays_bounded_when_the_center_stalls() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| fixture.hang = true);+ env.point_at(¢er.catalog_url);++ let started = Instant::now();+ let error = summaries_via(state, tx, json!(["demo.hello"]))+ .await+ .unwrap_err();+ let elapsed = started.elapsed();+ assert_eq!(error_code(&error), "PLUGIN_NETWORK");+ assert!(+ elapsed >= Duration::from_secs(4),+ "answered too soon: {elapsed:?}"+ );+ assert!(+ elapsed < Duration::from_secs(15),+ "not bounded: {elapsed:?}"+ );+}++#[tokio::test]+async fn review_summaries_rpc_never_holds_the_host_state_lock_across_io() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| fixture.hang = true);+ env.point_at(¢er.catalog_url);++ let call_state = state.clone();+ let call =+ tokio::spawn(async move { summaries_via(call_state, tx, json!(["demo.hello"])).await });+ // Let the review request reach the stalled center, then prove every other+ // host method can still take the state lock while it waits.+ tokio::time::sleep(Duration::from_millis(300)).await;+ let held = tokio::time::timeout(Duration::from_secs(1), state.lock()).await;+ assert!(+ held.is_ok(),+ "the host state lock was held across review network I/O"+ );+ drop(held);++ let error = call.await.unwrap().unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_NETWORK");+}++#[tokio::test]+async fn review_summaries_rpc_refuses_a_non_http_center() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();++ let error = summaries_via(state, tx, json!(["demo.hello"]))+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_NETWORK");+ assert!(error.message.contains("http(s)"), "{}", error.message);+}++#[tokio::test]+async fn review_summaries_rpc_keeps_the_center_bounded() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| {+ let mut body = String::with_capacity(MAX_REVIEW_RESPONSE_BYTES + 64);+ body.push_str("{\"summaries\":{}}");+ body.push_str(&" ".repeat(MAX_REVIEW_RESPONSE_BYTES));+ fixture.summaries_override = Some((200, body));+ });+ env.point_at(¢er.catalog_url);++ let error = summaries_via(state, tx, json!(["demo.hello"]))+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_MARKET_INVALID");+ assert!(error.message.contains("1MiB"), "{}", error.message);+}++#[tokio::test]+async fn reviews_rpc_returns_the_page_with_a_trusted_review_url() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| {+ fixture.reviews = Some((+ 200,+ json!({+ "reviews": [{+ "id": "r1",+ "pluginId": "demo.hello",+ "userId": "account-secret",+ "authorName": "Ada",+ "ratingHalfStars": 9,+ "body": "Great plugin",+ "status": "visible",+ "pluginVersion": "1.2.0",+ "helpfulCount": 3,+ "createdAt": "2026-10-01T00:00:00Z",+ "updatedAt": "2026-10-01T00:00:00Z",+ "editedAt": null,+ "hiddenReason": "internal moderation note",+ }],+ "nextCursor": "cursor-2",+ "summary": zero_summary("demo.hello"),+ }),+ ));+ });+ env.point_at(¢er.catalog_url);++ let result = handle_request(+ state,+ "market.reviews",+ json!({+ "pluginId": "demo.hello",+ "limit": 10,+ "sentiment": "positive",+ "sort": "helpful",+ "cursor": "a b/c+d=e",+ }),+ tx,+ )+ .await+ .unwrap();++ assert_eq!(+ result["reviewUrl"],+ json!(format!("{}/plugins/demo.hello#reviews", center.origin()))+ );+ assert_eq!(result["reviews"][0]["authorName"], json!("Ada"));+ assert_eq!(result["reviews"][0]["ratingHalfStars"], json!(9));+ assert_eq!(result["nextCursor"], json!("cursor-2"));+ assert_eq!(result["summary"]["ratingCount"], json!(0));+ // A public read never carries the account id or moderation data, even+ // when a misbehaving center attaches them.+ let text = result.to_string();+ assert!(!text.contains("account-secret"), "{text}");+ assert!(!text.contains("hiddenReason"), "{text}");+ assert!(!text.contains("internal moderation note"), "{text}");+ assert_eq!(+ center.requests(),+ vec![+ "/api/v1/plugins/demo.hello/reviews?limit=10&sentiment=positive&sort=helpful&cursor=a%20b%2Fc%2Bd%3De"+ ]+ );+}++#[tokio::test]+async fn reviews_rpc_refuses_non_visible_rows_in_the_public_list() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| {+ fixture.reviews = Some((+ 200,+ json!({+ "reviews": [{+ "id": "r1",+ "pluginId": "demo.hello",+ "authorName": "Ada",+ "ratingHalfStars": 9,+ "body": "Held for moderation",+ "status": "pending",+ "pluginVersion": "",+ "helpfulCount": 0,+ "createdAt": "2026-10-01T00:00:00Z",+ "updatedAt": "2026-10-01T00:00:00Z",+ "editedAt": null,+ }],+ "nextCursor": null,+ "summary": zero_summary("demo.hello"),+ }),+ ));+ });+ env.point_at(¢er.catalog_url);++ let error = handle_request(+ state,+ "market.reviews",+ json!({ "pluginId": "demo.hello" }),+ tx,+ )+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_MARKET_INVALID");+}++#[tokio::test]+async fn reviews_rpc_propagates_center_outages() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| {+ fixture.reviews = Some((503, json!({ "error": { "code": "UNAVAILABLE" } })));+ });+ env.point_at(¢er.catalog_url);++ let error = handle_request(+ state,+ "market.reviews",+ json!({ "pluginId": "demo.hello" }),+ tx,+ )+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_NETWORK");+}++#[tokio::test]+async fn reviews_rpc_rejects_invalid_input_before_any_network() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ env.point_at(¢er.catalog_url);++ let cases = [+ json!({}),+ json!({ "pluginId": "demo.hello", "limit": 0 }),+ json!({ "pluginId": "demo.hello", "limit": 101 }),+ json!({ "pluginId": "demo.hello", "sort": "oldest" }),+ json!({ "pluginId": "demo.hello", "sentiment": "angry" }),+ json!({ "pluginId": "demo.hello", "cursor": 7 }),+ json!({ "pluginId": "demo.hello/../admin" }),+ ];+ for case in cases {+ let error = handle_request(state.clone(), "market.reviews", case.clone(), tx.clone())+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "INVALID_PARAMS", "{case}");+ }++ let error = summaries_via(state.clone(), tx.clone(), json!("demo.hello"))+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "INVALID_PARAMS");+ let error = summaries_via(state, tx, json!(["demo.hello", 42]))+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "INVALID_PARAMS");+ assert!(center.requests().is_empty(), "{:?}", center.requests());+}++/// One valid public row; cases mutate a copy.+fn valid_review(id: &str) -> Value {+ json!({+ "id": id,+ "pluginId": "demo.hello",+ "authorName": "Ada",+ "ratingHalfStars": 9,+ "body": "Works well.",+ "status": "visible",+ "pluginVersion": "1.2.0",+ "helpfulCount": 1,+ "createdAt": "2026-10-01T00:00:00Z",+ "updatedAt": "2026-10-01T00:00:00Z",+ "editedAt": null,+ })+}++fn valid_page(reviews: Vec<Value>) -> Value {+ json!({+ "reviews": reviews,+ "nextCursor": null,+ "summary": zero_summary("demo.hello"),+ })+}++#[tokio::test]+async fn reviews_rpc_rejects_pages_that_break_the_public_contract() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ env.point_at(¢er.catalog_url);++ let mut wrong_plugin = valid_review("r1");+ wrong_plugin["pluginId"] = json!("demo.other");++ let mut bad_date = valid_review("r1");+ bad_date["createdAt"] = json!("not-a-date");++ let inconsistent_summary = json!({+ "pluginId": "demo.hello",+ "ratingAvg": 4.0,+ "ratingCount": 3,+ "ratingDist": [0, 0, 0, 0, 0],+ "positiveCount": 3,+ "neutralCount": 0,+ "negativeCount": 0,+ });++ let cases: Vec<(&str, Value, u64)> = vec![+ ("wrong plugin", valid_page(vec![wrong_plugin]), 20),+ (+ "page over the limit",+ valid_page(vec![valid_review("r1"), valid_review("r2")]),+ 1,+ ),+ ("invalid timestamp", valid_page(vec![bad_date]), 20),+ (+ "inconsistent summary",+ json!({+ "reviews": [],+ "nextCursor": null,+ "summary": inconsistent_summary,+ }),+ 20,+ ),+ ];+ for (label, body, limit) in cases {+ center.set(|fixture| fixture.reviews = Some((200, body.clone())));+ let error = handle_request(+ state.clone(),+ "market.reviews",+ json!({ "pluginId": "demo.hello", "limit": limit }),+ tx.clone(),+ )+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_MARKET_INVALID", "{label}");+ }+}++#[tokio::test]+async fn reviews_rpc_never_follows_redirects() {+ let env = MarketEnv::hold();+ env.point_at(OFFLINE_MARKET_URL);+ let (_data, state, tx) = fixture_state();+ let center = Center::start().await;+ center.set(|fixture| {+ // If the read followed this, the fixture would answer the second+ // request with a valid page and the call would succeed.+ fixture.redirect_to =+ Some("/api/v1/plugins/demo.hello/reviews?limit=20&sentiment=all&sort=newest".into());+ fixture.reviews = Some((200, valid_page(vec![valid_review("r1")])));+ });+ env.point_at(¢er.catalog_url);++ let error = handle_request(+ state,+ "market.reviews",+ json!({ "pluginId": "demo.hello" }),+ tx,+ )+ .await+ .unwrap_err();+ assert_eq!(error_code(&error), "PLUGIN_NETWORK");+ assert!(error.message.contains("redirect"), "{}", error.message);+ assert_eq!(+ center.requests().len(),+ 1,+ "the redirect was followed: {:?}",+ center.requests()+ );+}diff --git a/docs/privacy-policy.md b/docs/privacy-policy.mdindex aaca383ff..7699c176a 100644--- a/docs/privacy-policy.md+++ b/docs/privacy-policy.md@@ -1,6 +1,6 @@# Privacy Policy-**Effective date: 2026-09-20**+**Effective date: 2026-10-16**This Privacy Policy describes how PI-Desktop handles information when you usethe PI-Desktop desktop application. PI-Desktop is a local-first, open-source@@ -107,6 +107,15 @@ be recovered from it. The service uses the identifier to de-duplicate andrate-limit a download, and it keeps counts for a device rather than the identitybehind it. The two backup channels and a custom source do not send it.+Viewing a plugin's public ratings and reviews also contacts the plugin center+configured for the marketplace. The app sends the ids of the plugins currently+shown to fetch their public rating summaries and, when a review list is opened+or filtered, that plugin's id with the chosen sentiment, sort, and paging+cursor. These are anonymous public reads: no account, sign-in, cookie, or+device identifier is sent, and the desktop cannot write, vote on, or report a+review. Writing one happens on the center's web page, opened in your browser+from the review drawer.+Links opened through the application are handled by the operating system or anexternal browser. Markdown written by a model may include remote images,audio, or video; when rendered, the relevant host may receive a request fromdiff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.mdindex 477c59011..fe40a2ce4 100644--- a/docs/spec/04-ux/01-ui-ia.md+++ b/docs/spec/04-ux/01-ui-ia.md@@ -372,13 +372,17 @@ schedule. Renaming an Hourly task does not restart its interval.### 3.4 ExtensionsThe Extensions destination is a focused plugin surface with a compact header and-only two tabs: **Installed** and **Marketplace**. Installed groups plugin rows+only two tabs: **Installed** and **Marketplace**. Installed groups plugin cardsby state — Needs attention / Updates available / Active / Turned off — as soft-tiles stacked under a group label (D296). Marketplace remains the browse/install-card grid and always uses the official catalog. The page draws no dividers:-header, toolbar, rows, cards and the detail sheet's sections are set apart by-tone and spacing, and hairlines are reserved for floating layers (menus, sheet,-dialogs). MCP, Skills, and Subagents are not tabs or sections of Extensions.+tiles in an auto-filling card grid under a group label (D296). Marketplace+remains the browse/install card grid and always uses the official catalog.+Public ratings and reviews are read-only here: cards carry a rating chip, the+detail sheet carries a ratings summary, and a review drawer opens over the+sheet; writing a review is a link out to the plugin centre's own page. The page+draws no dividers: header, toolbar, cards and the detail sheet's sections are+set apart by tone and spacing, and hairlines are reserved for floating layers+(menus, sheet, dialogs). MCP, Skills, and Subagents are not tabs or sections of+Extensions.### 3.5 Settings (full-page takeover)### 3.5 Settings (full-page takeover)diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 9196917ff..e9069f3c5 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3501,6 +3501,15 @@ identify the platform validation still needed.- **Focus regression**: In light and dark themes, open a marketplace card and press Escape. Like pointer dismissal, Escape leaves no line or focus ring on the card. Then use Tab and Shift+Tab: the detail button shows a complete, unclipped ring, and Install remains separately focusable. Automated focus-state regression: `node scripts/e2e-plugin-detail-focus.mjs`; verify the rendered ring visually.+#### E2E-PLUGIN-reviews-public-reads: Public ratings and reviews stay read-only in the desktop++- **Preconditions**: Extensions reachable with at least one installed and one marketplace plugin the centre knows, plus a second run against a centre that has no review API.+- **Steps**: 1) Open Extensions → Installed and, without visiting Marketplace, confirm a published plugin's card shows a rating chip only when the centre returned a summary. 2) Open a marketplace card's detail sheet and read the ratings summary between Permissions and Versions; press "See all reviews". 3) In the drawer, filter by sentiment and switch between newest and most helpful; page with Load more. 4) Inspect the composer: it is disabled, and its one action is the link to the plugin centre page. 5) Press Escape once (only the drawer closes) and again (the sheet closes). 6) Reopen the sheet and confirm the drawer left its scroll position untouched. 7) Repeat against the centre without review support and read the summary.+- **Expected**: Installed and marketplace ids are batched into one summary read that never requires a Marketplace refresh; an unavailable centre shows no fabricated zeros, and the detail summary says ratings are unavailable — while the review entry stays reachable and the drawer retries its own list, so its disabled composer and its web link (official fallback until the host reports `reviewUrl`) are never lost; a successful summary read replaces the ratings for the ids just requested, so a plugin the centre stops serving loses its stale rating chip; the chip rides the card's existing metadata line and adds no row; the drawer covers the mounted detail sheet, keeps its scroll position, closes on the first Escape only, returns focus to its opener (Escape claims the key with preventDefault/stopPropagation; the covered sheet is inert and Tab is trapped inside the drawer), appends pages deduplicated by review id, and drops an answer for a filter the user already left; a review's version reads as user-reported, never as an installed version; the composer accepts no input, and the only write path is the real link opened through `browserOpenExternal` in the system browser on a primary or middle click (right-click stays with the platform menu), with a failed open reported as a toast; no sign-in, vote, report, or review-writing UI exists in any locale.+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §7, `07-plugins/14-plugin-roadmap.md`+- **Acceptance**: G (Extensions page) + Security+- **Status**: Automated fixture (`node scripts/e2e-plugin-reviews-drawer.mjs`: three probes — full path with card chip, section order, paging/dedup, filter stale-drop, error+retry, link href/middle-click-only/failure toast, Tab trap + inert, Escape/focus/scroll restoration; stale-summary replacement; unavailable-summary drawer entry + retry + fallback link) plus unit-covered (`plugin-reviews-logic.test.mjs`, `plugin-reviews-surface.test.mjs`)+#### E2E-024F: Refresh the official marketplace catalog- **Preconditions**: Network available to `plugins.aiuo.net`.@@ -3631,7 +3640,7 @@ identify the platform validation still needed.- **Preconditions**: At least one enabled plugin, one disabled plugin, and one plugin whose load failed.- **Steps**: 1) Open Extensions → Installed while plugin changed events are arriving in a burst. 2) Read the tab and group counts. 3) Confirm the failed plugin sits under Needs attention with its error message. 4) Search by author and by permission. 5) Clear the search.-- **Expected**: The page remains usable during transient host backpressure: identical plugin and extension registry refreshes coalesce, and renderer-facing RPC calls retry explicit `HOST_OVERLOADED` responses with bounded backoff before surfacing an error. Rows group as Needs attention / Updates available / Active / Turned off with counts; `status: "error" | "load_error"` renders the error message inline instead of being silent; each row defaults to a two-line name/id/version summary, while a Details disclosure reveals risk-tinted permission chips, capabilities, and resident service status; the single scope trigger opens explained Off / This project / Everywhere choices and the project picker; row icon actions expose hover/focus labels; the result count reflects the filtered subset and clearing restores every group.+- **Expected**: The page remains usable during transient host backpressure: identical plugin and extension registry refreshes coalesce, and renderer-facing RPC calls retry explicit `HOST_OVERLOADED` responses with bounded backoff before surfacing an error. Plugins group as Needs attention / Updates available / Active / Turned off with counts; `status: "error" | "load_error"` renders the error message inline instead of being silent; each plugin is a card in an auto-filling grid, defaulting to a quiet name/id/version summary (plus a rating chip when the centre has one), while a Details disclosure reveals risk-tinted permission chips, capabilities, and resident service status; the single scope trigger opens explained Off / This project / Everywhere choices and the project picker; card icon actions expose hover/focus labels; the result count reflects the filtered subset and clearing restores every group.- **Specs linked**: `04-ux/01-ui-ia.md`, `07-plugins/13-plugin-permissions-matrix.md`- **Acceptance**: G (installed plugin management)- **Status**: Documented@@ -3857,11 +3866,14 @@ window; opening a normal panel afterward must still work.the compact two-tier header presents the extension mark/title and contextualaction rail below the native window-control band, then confirm the Installed and Marketplace tabs are the only tabs and both reach the contentwithout a four-card numeric overview band or explanatory header/section- paragraphs. 3) Confirm installed rows begin- as a quiet two-line summary, then expand Details on one row and inspect its- capabilities, service status, and permissions. 4) Use the compact scope- control and its explained scope menu, contextual primary action, and a- secondary update/action button. 5)+ paragraphs. 3) Confirm installed plugins are cards in an+ auto-filling grid — cards keep their width above 340px and collapse below —+ then expand Details on one card and inspect its capabilities, service status,+ and permissions. 4) Use the compact scope+ control and its explained scope menu, the card's one call to action (Update to+ the available version, or Open panel), and the 28px settings and overflow icon+ actions; widen and narrow the window to see the rail wrap at the card's left+ edge rather than clip. 5)Switch to light theme and repeat. 6) Keyboard-focus the Details disclosure,scope states, and each action.- **Expected**: The four numeric overview cards are absent; the header uses a@@ -3870,10 +3882,11 @@ window; opening a normal panel afterward must still work.installed group counts, and any update alert remain available in theirrelevant surfaces. The page header, section headers, empty states, and updatealert use compact labels and actions; decision-specific explanations remain- in disclosures, details, and dialogs. Installed rows keep their default height low while the+ in disclosures, details, and dialogs. Cards keep their default height low while thedisclosure exposes the complete secondary readout. The scope trigger stays- aligned with the row action rail, its menu explains each state, and icon- actions remain visible at rest while showing labels on hover and focus.+ aligned with the card's control rail, its menu explains each state, and icon+ actions remain visible at rest while showing labels on hover and focus; a+ disabled card shows no primary action and no settings icon.Primary and secondary buttons keepvisible semantic surfaces, text, borders, hover states, and focus rings inboth themes, and keyboard focus does not depend on pointer hover.@@ -3881,7 +3894,8 @@ window; opening a normal panel afterward must still work.`07-plugins/07-plugin-marketplace.md`, ADR 0058, D196- **Acceptance**: G (Extensions page) + Quality- **Status**: Unit-covered (`extensions-page.test.mjs`,- `plugins-page-style.test.mjs`); visual scenario Draft+ `plugins-page-style.test.mjs`, `plugin-reviews-surface.test.mjs`);+ visual scenario Draft#### E2E-024O: Marketplace hides development-only sample plugins@@ -10108,9 +10122,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.| F — Persistence | E2E-020, E2E-021, E2E-021a, E2E-038, E2E-SETTINGS-inline-capability-imports, E2E-040, E2E-042, E2E-047, E2E-048, E2E-051, E2E-054, E2E-056, E2E-061, E2E-062, E2E-064, E2E-066, E2E-068, E2E-071, E2E-072, E2E-073, E2E-082, E2E-084, E2E-096, E2E-098, E2E-102, E2E-102b, E2E-102c, E2E-102d, E2E-102g, E2E-102i, E2E-103, E2E-AGENTS-001, E2E-061a, E2E-073a, E2E-104, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-118, E2E-119, E2E-120, E2E-121, E2E-123, E2E-142, E2E-146, E2E-146a, E2E-148, E2E-151, E2E-158, E2E-160, E2E-168, E2E-171, E2E-177, E2E-178, E2E-183, E2E-186, E2E-005J, E2E-PROVIDER-custom-endpoint-no-api-key, E2E-PLUGIN-session-orchestrator-real-workers, E2E-PLUGIN-provider-catalog-add-service, E2E-SESSION-outbox-unclassifiable-failure-does-not-stall-the-queue || F — Persistence (project ordering) | E2E-251 || G / Security — Fetch redirect policy | E2E-PLUGIN-fetch-redirect-policy |-| G — Plugins | E2E-022, E2E-022A, E2E-022B, E2E-022C, E2E-023, E2E-024, E2E-024B, E2E-024C, E2E-024D, E2E-024AA, E2E-024E, E2E-024W, E2E-024F, E2E-024G, E2E-024H, E2E-024I, E2E-024J, E2E-024K, E2E-024L, E2E-024M, E2E-024N, E2E-024O, E2E-024P, E2E-025, E2E-026, E2E-105, E2E-117, E2E-120, E2E-122, E2E-123, E2E-024Q, E2E-148, E2E-152, E2E-153, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-imported-pi-package-wrapper, E2E-PLUGIN-import-extension-installs-dependencies, E2E-PLUGIN-import-extension-reports-missing-dependency, E2E-PLUGIN-global-shortcut-owns-only-its-own-command, E2E-PLUGIN-permission-gate-for-real-time-capabilities, E2E-PLUGIN-background-audio-and-realtime-connection, E2E-PLUGIN-fs-root-follows-the-calling-session, E2E-PLUGIN-provider-catalog-add-service |+| G — Plugins | E2E-022, E2E-022A, E2E-022B, E2E-022C, E2E-023, E2E-024, E2E-024B, E2E-024C, E2E-024D, E2E-024AA, E2E-024E, E2E-024W, E2E-024F, E2E-024G, E2E-024H, E2E-024I, E2E-024J, E2E-024K, E2E-024L, E2E-024M, E2E-024N, E2E-024O, E2E-024P, E2E-025, E2E-026, E2E-105, E2E-117, E2E-120, E2E-122, E2E-123, E2E-024Q, E2E-148, E2E-152, E2E-153, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-imported-pi-package-wrapper, E2E-PLUGIN-import-extension-installs-dependencies, E2E-PLUGIN-import-extension-reports-missing-dependency, E2E-PLUGIN-global-shortcut-owns-only-its-own-command, E2E-PLUGIN-permission-gate-for-real-time-capabilities, E2E-PLUGIN-background-audio-and-realtime-connection, E2E-PLUGIN-fs-root-follows-the-calling-session, E2E-PLUGIN-provider-catalog-add-service, E2E-PLUGIN-reviews-public-reads || H — Diagnostics | E2E-027, E2E-031, E2E-034, E2E-042, E2E-096, E2E-098, E2E-104, E2E-107, E2E-108, E2E-109, E2E-110, E2E-113, E2E-115, E2E-116, E2E-118, E2E-121, E2E-146, E2E-146a, E2E-155, E2E-159, E2E-176, E2E-194, E2E-195 |-| Security | E2E-SETTINGS-inline-capability-imports, E2E-028, E2E-029, E2E-030, E2E-024J, E2E-024K, E2E-024M, E2E-049, E2E-068, E2E-086, E2E-102c, E2E-102d, E2E-102e, E2E-105, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-113, E2E-115, E2E-116, E2E-117, E2E-119, E2E-121, E2E-122, E2E-123, E2E-142, E2E-148, E2E-151, E2E-153, E2E-158, E2E-187, E2E-196c, E2E-196b, E2E-196, E2E-PROVIDER-custom-endpoint-no-api-key, E2E-PLUGIN-fs-root-follows-the-calling-session, E2E-PLUGIN-provider-catalog-add-service |+| Security | E2E-SETTINGS-inline-capability-imports, E2E-028, E2E-029, E2E-030, E2E-024J, E2E-024K, E2E-024M, E2E-049, E2E-068, E2E-086, E2E-102c, E2E-102d, E2E-102e, E2E-105, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-113, E2E-115, E2E-116, E2E-117, E2E-119, E2E-121, E2E-122, E2E-123, E2E-142, E2E-148, E2E-151, E2E-153, E2E-158, E2E-187, E2E-196c, E2E-196b, E2E-196, E2E-PROVIDER-custom-endpoint-no-api-key, E2E-PLUGIN-fs-root-follows-the-calling-session, E2E-PLUGIN-provider-catalog-add-service, E2E-PLUGIN-reviews-public-reads || Quality | E2E-SETTINGS-inline-capability-imports, E2E-CHAT-long-history-stream-keeps-responsive, E2E-CHAT-running-status-survives-output-pauses, E2E-032, E2E-033, E2E-039, E2E-043, E2E-044, E2E-045, E2E-046, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-050, E2E-053, E2E-055, E2E-056, E2E-057, E2E-058, E2E-059, E2E-060, E2E-061, E2E-062, E2E-063, E2E-064, E2E-065, E2E-066, E2E-067, E2E-068, E2E-069, E2E-070, E2E-071, E2E-072, E2E-073, E2E-074, E2E-075, E2E-076, E2E-077, E2E-078, E2E-079, E2E-080, E2E-081, E2E-082, E2E-083, E2E-084, E2E-085, E2E-086, E2E-092, E2E-093, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102e, E2E-103, E2E-AGENTS-001, E2E-021a, E2E-024N, E2E-059a, E2E-060b, E2E-060c, E2E-061a, E2E-073a, E2E-111, E2E-114, E2E-117, E2E-118, E2E-119, E2E-120, E2E-122, E2E-123, E2E-142, E2E-143, E2E-144, E2E-145, E2E-146, E2E-147, E2E-148, E2E-150, E2E-151, E2E-153, E2E-155, E2E-158, E2E-159, E2E-160, E2E-161, E2E-162, E2E-163, E2E-168, E2E-172, E2E-173, E2E-174, E2E-011g, E2E-176, E2E-177, E2E-178, E2E-179, E2E-180, E2E-181, E2E-182, E2E-183, E2E-186, E2E-187, E2E-194, E2E-195, E2E-196a, E2E-196b, E2E-196c, E2E-198, E2E-199, E2E-200, E2E-196, E2E-201, E2E-204, E2E-202, E2E-203, E2E-205, E2E-206, E2E-207, E2E-208, E2E-209, E2E-210, E2E-UPDATE-preference-and-once-only-reminder, E2E-218, E2E-259, E2E-219, E2E-250, E2E-252, E2E-102i, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-fs-root-follows-the-calling-session, E2E-SUBAGENT-resume-a-settled-delegation, E2E-PLUGIN-provider-catalog-add-service || Quality (sidebar menu placement) | E2E-021c || Quality (project ordering) | E2E-253 |diff --git a/docs/spec/06-delivery/plugin-reviews-test-plan.md b/docs/spec/06-delivery/plugin-reviews-test-plan.mdnew file mode 100644index 000000000..cb1e4ca76--- /dev/null+++ b/docs/spec/06-delivery/plugin-reviews-test-plan.md@@ -0,0 +1,350 @@+# Plugin reviews test plan (desktop)++Portable, repo-resident test plan for the read-only public plugin-reviews+surface: shared types, host-core RPC/HTTP client, Electron IPC bridge, renderer+data layer, installed-grid/detail-sheet UI, review drawer, locale coverage, and+the Electron fixtures.++References used as source of truth:++- `docs/spec/07-plugins/07-plugin-marketplace.md` — marketplace/review behavior.+- `docs/spec/06-delivery/04-e2e-test-plan.md` — fixture conventions and commands.+- Center counterpart: the center repository's `docs/reviews-test-plan.md` (API+ rules and the Go/service/store evidence this plan pairs with).+- Shared types: `packages/shared/src/types/marketplace.ts`; protocol channels in+ `packages/shared/src/protocol.ts`.+- Automated evidence: `apps/desktop/test/market-review-ipc.test.mjs`,+ `plugin-reviews-logic.test.mjs`, `plugin-reviews-surface.test.mjs`,+ `plugins-page-style.test.mjs`; `crates/host-core/src/plugins/reviews.rs` unit+ tests; `crates/host-core/src/rpc/plugin_reviews_rpc_tests.rs`; fixtures under+ `scripts/e2e/` with their runners in `scripts/`.++## 0. Result statuses++| Tag | Meaning |+| --- | --- |+| `verified` | Final actual result recorded in the Final execution record after a run against this worktree. |+| `baseline:fail` | Pre-existing full-suite failure in this environment, not a review regression. |+| `executed; baseline failures` | The command ran end to end; only the known baselines failed — not green. |++Test titles below are copied verbatim from the repository files named in each+row. If a title no longer matches the source, update the row.++## 1. Scope and prohibitions++- Task worktree only; no commits, pushes, tags, release, or packaging.+- Never attach the user's running instance or profile; never use `verify:ui:*`.+ The sanctioned pattern is the headless Electron fixtures in §2.5 with isolated+ `userData` profiles under `.cache/`.+- No broad config or ignore-file changes.+- Desktop stays read-only: no login, posting, votes, reports, or credentials in+ the renderer.+- Tests are the evidence; this plan does not claim any run happened.++## 2. Commands++### 2.1 Windows invocation workaround (tsc / electron-vite)++Canonical scripts are `pnpm --filter @pi-desktop/desktop typecheck`,+`pnpm --filter @pi-desktop/desktop build`, and the repo `pnpm test`. When the+pnpm script shim does not resolve on Windows, invoke the worktree-local binaries+directly with `node` — same inputs and outputs, no configuration change:++```powershell+cd apps/desktop+node node_modules/typescript/bin/tsc -p tsconfig.json --noEmit+node node_modules/electron-vite/bin/electron-vite.js build+cd ../..+```++Rebuild workspace dists first only if stale (the fixtures resolve them):++```powershell+cd packages/shared; node node_modules/typescript/bin/tsc -p tsconfig.json; cd ../..+cd packages/plugin-sdk; node node_modules/typescript/bin/tsc -p tsconfig.json; cd ../..+```++### 2.2 Targeted JS tests (final six-file run)++```powershell+node --test apps/desktop/test/market-review-ipc.test.mjs apps/desktop/test/plugin-reviews-logic.test.mjs apps/desktop/test/plugin-reviews-surface.test.mjs apps/desktop/test/plugins-page-style.test.mjs apps/desktop/test/extensions-page.test.mjs apps/desktop/test/settings-dialog-overlay.test.mjs+```++Final independent run: **64/64 pass** — IPC 6, logic 16, surface 14, style 8,+extensions 16, overlay host suite 4. The review cases map to the first four+files plus RVD-UI-14's installed-grid pin; extensions and overlay are the+adjacent regression companions the renderer change touches (the detail sheet+mounts on the viewport overlay host).++### 2.3 Targeted Rust tests++```powershell+cargo test -p host-core --bin pi-desktop-host-core review+cargo fmt --check+cargo clippy -p host-core --all-targets+```++Known unrelated clippy warning (warn-level): `crates/host-core/src/transcripts.rs:893`+`clippy::filter_next`.++### 2.4 Full host-core suite context++```powershell+cargo test -p host-core --bin pi-desktop-host-core+```++Known baseline in this environment: **912 passed; 38 failed; 1 ignored**, all 38+in Windows shell/worktree areas (`background_tasks`, `data_relocation`,+`rpc::*`, `session_worktrees`, `tools::bash_*`, `tools::powershell_*`) — not+review regressions. Report them as `baseline:fail`; do not attempt to fix them+from this plan.++### 2.5 i18n++```powershell+# Catalogue integrity+cd packages/i18n+node node_modules/vitest/vitest.mjs run+cd ../..++# Review-block and key parity (every locale must print reviewsBlock=1 sevenKeys=7)+$root = 'C:\Code\ReactProjects\PI-Desktop\.slim\worktrees\plugin-reviews'+foreach ($l in 'de','en','es','fr','ko','pt-BR','tr','zh-CN','zh-TW') {+ $f = "$root\packages\i18n\src\locales\$l\index.ts"+ $block = (Select-String -Path $f -Pattern '^\s*reviews: \{' -CaseSensitive).Count+ $keys = (Select-String -Path $f -Pattern 'summaryTitle:|viewAll:|composeHint:|composeCta:|reviewVersion:|filterLabel:|sortLabel:' -CaseSensitive).Count+ "$l : reviewsBlock=$block sevenKeys=$keys"+}+```++`-CaseSensitive` matters: without it the key count reads 8 because+`capabilityFilterLabel` (an unrelated key) also matches `filterLabel:`. Verify+`reviewsBlock=1 sevenKeys=7` per locale.++### 2.6 Electron fixtures (real Chromium, headless)++```powershell+node scripts/e2e-plugin-reviews-drawer.mjs # five probes: drawer / batch-stale-guard / narrow drawer / stale summary / unavailable summary+node scripts/e2e-installed-grid.mjs # installed grid + control rails + dialogs+node scripts/e2e-plugin-detail-focus.mjs # detail-sheet focus interplay+```++Each runner builds the real components with esbuild, loads them in a hidden+Electron window with a private profile, and prints one PASS line per probe. No+install leaves the renderer; no user instance is touched.++## 3. Cases++### 3.1 Shared types and renderer API++| ID | Check | Expected | Status |+| --- | --- | --- | --- |+| RVD-TYP-01 | `PluginReviewSummary` matches the center contract: `ratingAvg: number \| null`, five floor buckets, three sentiment counts | Compiles in shared + desktop typecheck; no private fields (`userId`, `hiddenReason`) in the public type | `verified` (2026-10-16 final typecheck + build) |+| RVD-TYP-02 | `PluginReviewPage` carries `reviews`, `nextCursor: string \| null`, `summary`, host-built `reviewUrl`; `PluginReviewQuery` allows `cursor?/limit?/sentiment?/sort?` | `api.marketReviewSummaries(ids)` / `api.marketReviews(query)` return the shared types through the preload whitelist | `verified` (2026-10-16 final typecheck + build) |++### 3.2 Electron IPC bridge — `market-review-ipc.test.mjs`++| ID | Test title (verbatim) | Expected assertion | Status |+| --- | --- | --- | --- |+| RVD-IPC-01 | review channels are registered and allowed through the preload gate | `IPC.invoke.marketReviewSummaries === "pi-desktop/market/reviewSummaries"`, `marketReviews === "pi-desktop/market/reviews"`, both in `IPC_WHITELIST` | `verified` (2026-10-16 six-file run) |+| RVD-IPC-02 | summary reads forward the ids and return the host payload unchanged | Handler calls host `market.reviewSummaries` with `{pluginIds}` and returns `{summaries}` unchanged | `verified` (2026-10-16 six-file run) |+| RVD-IPC-03 | a missing or malformed id list becomes an empty request, never a crash | Missing payload and `pluginIds: "demo.hello"` both forward `{pluginIds: []}` | `verified` (2026-10-16 six-file run) |+| RVD-IPC-04 | review reads forward the query and return the page unchanged | Full query (incl. `cursor`) forwarded; page returned unchanged | `verified` (2026-10-16 six-file run) |+| RVD-IPC-05 | an unsupported or unreachable center reaches the caller unchanged | Rejection carries `data.errorCode === "PLUGIN_NETWORK"` — no remapping or masking | `verified` (2026-10-16 six-file run) |+| RVD-IPC-06 | review reads require a running host | No host → rejects `host unavailable` | `verified` (2026-10-16 six-file run) |++### 3.3 Host RPC — `plugin_reviews_rpc_tests.rs`++Preconditions: a fixture HTTP server plays the trusted center on a loopback+origin; host-core is driven through the real request handler.++| ID | Test (verbatim) | Expected assertion | Status |+| --- | --- | --- | --- |+| RVD-RPC-01 | `review_summaries_rpc_returns_only_the_centers_answers` | Requested-and-answered ids only; unrequested center answers dropped | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-02 | `review_summaries_rpc_dedupes_and_chunks_installed_ids` | Duplicates collapse; chunks of ≤100 ids; requests recorded | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-03 | `review_summaries_rpc_is_empty_without_asking_the_center` | Empty ids → `{summaries:{}}` with no HTTP request | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-04 | `review_summaries_rpc_rejects_malformed_center_answers` | Bad JSON/shape → `PLUGIN_MARKET_INVALID` | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-05 | `review_summaries_rpc_reports_a_legacy_center_as_unavailable` | 404 → `PLUGIN_NETWORK` (unavailable), never zeros | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-06 | `review_summaries_rpc_never_fabricates_zeros_when_the_center_is_down` | Down center → error; no zero summaries invented | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-07 | `review_summaries_rpc_stays_bounded_when_the_center_stalls` | Stall → fails within the 5 s review deadline | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-08 | `review_summaries_rpc_never_holds_the_host_state_lock_across_io` | Trusted origin captured, state lock released before I/O | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-09 | `review_summaries_rpc_refuses_a_non_http_center` | `file://` catalog → unavailable, no request | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-10 | `review_summaries_rpc_keeps_the_center_bounded` | Request carries 5 s timeout, 1 MiB cap, no redirect following | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-11 | `reviews_rpc_returns_the_page_with_a_trusted_review_url` | Page + summary + `reviewUrl` from the effective trusted origin (fixture override included) | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-12 | `reviews_rpc_refuses_non_visible_rows_in_the_public_list` | Non-visible row → `PLUGIN_MARKET_INVALID` | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-13 | `reviews_rpc_propagates_center_outages` | Center error → propagated as `PLUGIN_NETWORK` | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-14 | `reviews_rpc_rejects_invalid_input_before_any_network` | Bad `pluginId`/`limit`/`cursor`/`sentiment`/`sort` → `INVALID_PARAMS`, zero requests | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-15 | `reviews_rpc_rejects_pages_that_break_the_public_contract` | Over-limit page, wrong pluginId, bad rating/timestamps/bounds → `PLUGIN_MARKET_INVALID` | `verified` (2026-10-16 hardened Rust run) |+| RVD-RPC-16 | `reviews_rpc_never_follows_redirects` | 3xx from the center → refusal, not a hop | `verified` (2026-10-16 hardened Rust run) |++A 2026-10-16 cross-host run additionally exercised this layer end to end+against a real running center (host stdio RPC, zero-state 9/9 and nonzero 11/11)+— see §5 row 12. It complements, but does not replace, the focused tests above.++### 3.4 Host client bounds/validation — `plugins/reviews.rs`++| ID | Test (verbatim) | Expected | Status |+| --- | --- | --- | --- |+| RVD-CLI-01 | `review_reads_are_bounded` | Timeout 5 s; 1 MiB response cap; 100 summary ids | `verified` (2026-10-16 hardened Rust run) |+| RVD-CLI-02 | `the_origin_keeps_only_the_catalogs_host` | http(s) origins kept incl. port; `file://`, credential URLs, query-smuggled authority refused | `verified` (2026-10-16 hardened Rust run) |+| RVD-CLI-03 | `summaries_batches_dedupe_and_cap_at_one_hundred` | 205 unique + duplicates → chunks 100/100/5, each id once | `verified` (2026-10-16 hardened Rust run) |+| RVD-CLI-04 | `review_urls_stay_on_the_trusted_origin` | Cursor percent-encoded; list/summary/page URLs stay on the origin | `verified` (2026-10-16 hardened Rust run) |+| RVD-CLI-05 | `summary_consistency_is_enforced` | Distribution and sentiments sum to `ratingCount`; zero count ⇔ null average; 0..5 range | `verified` (2026-10-16 hardened Rust run) |+| RVD-CLI-06 | `review_contract_is_enforced` | Right plugin, visible status, 2..=10 half stars, ISO timestamps, body ≤2000 chars, version ≤128, name ≤200; empty version + `editedAt` accepted | `verified` (2026-10-16 hardened Rust run) |++### 3.5 Renderer pure logic — `plugin-reviews-logic.test.mjs`++| ID | Test title (verbatim) | Expected assertion | Status |+| --- | --- | --- | --- |+| RVD-LOG-01 | the official review URL encodes the plugin id into the fallback page | Official URL with percent-encoded id (`/`, space, `#`) | `verified` (2026-10-16 six-file run) |+| RVD-LOG-02 | the page URL wins only when it is a usable http(s) address | Host `reviewUrl` used when http(s); `javascript:`, `data:`, relative, blank → official fallback | `verified` (2026-10-16 six-file run) |+| RVD-LOG-03 | one query key names exactly one plugin, sentiment and sort | Distinct plugin/filter/sort → distinct keys | `verified` (2026-10-16 six-file run) |+| RVD-LOG-04 | mergeReviews appends unseen rows once and keeps the shown order | Deduped append, first-seen order | `verified` (2026-10-16 six-file run) |+| RVD-LOG-05 | rating formatting follows the contract: one decimal, half stars trimmed | `4.5→"4.5"`, `5→"5.0"`, null/NaN → null; half stars trimmed to whole/half star text | `verified` (2026-10-16 six-file run) |+| RVD-LOG-06 | sentiment shares split the good / medium / bad counts into percentages | `[2,1,0] → 67/33/0`; null summary → zeros | `verified` (2026-10-16 six-file run) |+| RVD-LOG-07 | a query carries the page limit and only adds a cursor when paging | Limit always; cursor only when paging | `verified` (2026-10-16 six-file run) |+| RVD-LOG-08 | a first page fills the list and closes the load | Ready state, rows, `nextCursor`, summary, effective URL | `verified` (2026-10-16 six-file run) |+| RVD-LOG-09 | a summary of zero reviews is carried through as zero, not as unavailable | `ratingCount 0`, null average — distinct from unavailable | `verified` (2026-10-16 six-file run) |+| RVD-LOG-10 | a summary answer replaces the requested ids, so an omitted id loses its rating | Requested subset replaces the map; unrequested key never enters; zero stays zero (stale-chip behavior) | `verified` (2026-10-16 six-file run) |+| RVD-LOG-11 | a page that does not carry reviewUrl falls back to the official page | Missing `reviewUrl` → official URL | `verified` (2026-10-16 six-file run) |+| RVD-LOG-12 | an answer for another query cannot reach the list on screen | Late answer for an abandoned key → dropped | `verified` (2026-10-16 six-file run) |+| RVD-LOG-13 | switching filter drops the old rows; retrying the same filter keeps them | Filter switch clears to loading; same-key retry keeps rows | `verified` (2026-10-16 six-file run) |+| RVD-LOG-14 | paging appends without repeating a row that moved between pages | Dedup by id; cursor cleared at end | `verified` (2026-10-16 six-file run) |+| RVD-LOG-15 | a failure keeps readable rows and only replaces an empty list | Rows kept on later-page failure; first-page failure is an error state | `verified` (2026-10-16 six-file run) |+| RVD-LOG-16 | a failure for a query that is no longer on screen is ignored | Stale failure → state unchanged | `verified` (2026-10-16 six-file run) |++### 3.6 UI source contracts — `plugin-reviews-surface.test.mjs`++| ID | Test title (verbatim) | Expected assertion | Status |+| --- | --- | --- | --- |+| RVD-UI-01 | installed plugins keep their state groups and their disclosure | Group order `attention, updates, active, disabled`; `role="list"`; details disclosure kept | `verified` (2026-10-16 six-file run) |+| RVD-UI-02 | an installed card grows one call to action: update, then open panel | Update button names the target version; panel only when enabled+declared; settings behind enabled+declared; disabled card has no primary | `verified` (2026-10-16 six-file run) |+| RVD-UI-03 | installed and marketplace cards carry the rating chip in their metadata | `RatingChip` inside the existing meta line; hidden when `ratingCount <= 0` | `verified` (2026-10-16 six-file run) |+| RVD-UI-04 | the installed card shows the trust glyph only from installed metadata | Shield from installed trust tier; no "verified installed" wording | `verified` (2026-10-16 six-file run) |+| RVD-UI-05 | the detail sheet puts the ratings summary between permissions and versions | Section order Permissions < Ratings & reviews < Versions; unavailable copy; drawer entry not gated on the summary (unavailable-entry behavior) | `verified` (2026-10-16 six-file run) |+| RVD-UI-06 | the review drawer mounts over the detail sheet without unmounting it | Same layer, later DOM; absolute z-index 1; sheet + scrim `inert` while open | `verified` (2026-10-16 six-file run) |+| RVD-UI-07 | Escape closes the top drawer only and focus comes back to its opener | Escape claimed before the sheet; Tab trap wraps both directions; dialog focus + return to opener | `verified` (2026-10-16 six-file run) |+| RVD-UI-08 | the drawer is a read-only surface whose one write path is the centre page | Disabled scoped-composer field; real anchor; click + middle-click open via `api.browserOpenExternal`; failure toast; no login/vote/report/`fetch` | `verified` (2026-10-16 six-file run) |+| RVD-UI-09 | a review's version reads as self-reported, never as an installed version | `reviewVersion` label; no bare `v{version}` span | `verified` (2026-10-16 six-file run) |+| RVD-UI-10 | the drawer filters, sorts, and pages with stale answers dropped | Sentiment/sort groups with `aria-pressed`; cursor load-more; retry; `role="alert"`; generation invalidation incl. unmount | `verified` (2026-10-16 six-file run) |+| RVD-UI-11 | every installed and marketplace id is batched without a tab refresh | One `Set` of installed+market ids → one summaries call; success replaces via `nextSummaryMap(ids, …)`; failure → unavailable, never zero | `verified` (2026-10-16 six-file run) |+| RVD-UI-12 | closing the detail closes the drawer with it | Drawer id and selection cleared together | `verified` (2026-10-16 six-file run) |+| RVD-UI-13 | the review drawer keeps a real-Chromium user-path fixture | Harness pins the drawer probes — now five, including `pluginReviewsBatchProbe` and `pluginReviewsNarrowDrawerProbe` (with the 320×720 `setContentSize` switch); fixture drives the page hook, Tab/Escape, inert, write link | `verified` (2026-10-16 six-file run + 2026-10-17 probes) |+| RVD-UI-14 | the installed grid keeps a real-Chromium user-path fixture | Pins the installed-grid harness + fixture: `installedGridLayoutProbe`/`installedGridActionsProbe`, real `InstalledPluginsPanel` + `PluginDialogs`, the scope control and its menu (`scope-compact-trigger`, `scope-compact-menu.is-open`), the rail (`plugins-row-controls`), the action path (`marketInstall`, `disablePlugin`, `setPluginScope`), and the 340px grid floor (`gridTemplateColumns`) | `verified` (2026-10-16 six-file run) |++### 3.7 Page integration (fetcher semantics)++| ID | Check | Expected | Status |+| --- | --- | --- | --- |+| RVD-PAGE-01 | Summary batch under rapid typing: settled cards come from the final query, a held earlier answer cannot overwrite them | `pluginReviewsBatchProbe` (ordering-controlled — the first summaries answer is gated and released only after the final answer lands; **no wall-clock debounce claim**): settled cards are exactly the final query's plugins; the fresh chip reads 4.5 (3); the plugin the final batch does not rate shows no chip; the final batch's requested ids equal the displayed ids; after the held answer is released the fresh chip is unchanged and no stale chip appears | `verified` (2026-10-17 batch-stale-guard probe) |+| RVD-PAGE-02 | Summary failure is isolated | Unavailable status; install/update never waits on it | `verified` (2026-10-16 six-file run / drawer probes) |+| RVD-PAGE-03 | Center predating the review API | Unavailable — distinct from zero; no fabricated zeros | `verified` (2026-10-16 six-file run / drawer probes) |+| RVD-PAGE-04 | Drawer list failure independent from summary | Drawer retries its own list; disabled composer + link out remain reachable | `verified` (2026-10-16 six-file run / drawer probes) |++### 3.8 Electron fixture E2E — `scripts/e2e-plugin-reviews-drawer.mjs`++| ID | Probe (verbatim) | Steps / expected | Status |+| --- | --- | --- | --- |+| RVD-E2E-01 | `pluginReviewsDrawerProbe` | Card chip (`aria-label "Rated 4.5 out of 5 from 3 ratings"`, text `4.5 (3)`) → detail section order → opener scrolled into view → drawer takes focus, sheet+scrim inert → Tab trap wraps both ways → first page with "User-reported version v1.2.0" → Load more appends r1/r2/r3 deduplicated → slow "All" answer outrun by a filter switch is dropped → Negative failure shows error + retry recovers → write link href is the host URL; primary and middle-click open it; right-click does not → open failure toast → Escape closes only the drawer, focus and sheet scroll restored | `verified` (2026-10-16 six-probe rerun) |+| RVD-E2E-02 | `pluginReviewsStaleSummaryProbe` | A summaries refresh whose answer omits a requested id removes that plugin's stale rating chip | `verified` (2026-10-16 six-probe rerun) |+| RVD-E2E-03 | `pluginReviewsUnavailableSummaryProbe` | Summary read fails → no chip; detail shows "Ratings aren't available from this source." with the drawer entry present; drawer retry state, disabled composer, official fallback link; retry recovers the list and the host `reviewUrl` replaces the fallback | `verified` (2026-10-16 six-probe rerun) |++The drawer harness runs five probes: the three above plus `pluginReviewsBatchProbe`+(RVD-PAGE-01) and `pluginReviewsNarrowDrawerProbe` (RVD-NARROW-01, with the+320×720 `useContentSize` switch). Full run: 5/5 PASS.++### 3.9 Installed grid, detail focus, and the installed-card fixture++| ID | Runner | Scope / expected | Status |+| --- | --- | --- | --- |+| RVD-E2E-04 | `node scripts/e2e-installed-grid.mjs` (`scripts/e2e/installed-grid.tsx`), probes `installedGridLayoutProbe` + `installedGridActionsProbe` | Real `InstalledPluginsPanel` + `PluginDialogs` in a 1100×900 fixture window, only the IPC boundary fixtured; seven plugins (error, disabled-with-update, plain disabled, panel-only, settings-only, updater, long id). Layout probe PASS: groups/members/error, rail order + disabled gating, disclosure, real scope menu, chip inline + long-id truncation, 340px grid floor + sub-340 fallback, narrow rail wrap. Actions probe PASS: update→permission→`marketInstall`(v1.2.3), panel id, settings sheet opens/closes, overflow auto-update false + uninstall. Reported 2/2 pass; the final rerun decides | `verified` (2026-10-16 six-probe rerun, 2/2) |+| RVD-E2E-05 | `node scripts/e2e-plugin-detail-focus.mjs` (`scripts/e2e/plugin-detail-focus.tsx`) | Detail-sheet focus/scroll interplay while the summary read returns `{}` — sheet behavior independent of the review surface | `verified` (2026-10-16 six-probe rerun) |++**Installed-card real-component fixture (landed).** Runner+`scripts/e2e-installed-grid.mjs`, fixture `scripts/e2e/installed-grid.tsx`,+probes `installedGridLayoutProbe` (groups, rail, disclosure, scope, meta, grid)+and `installedGridActionsProbe` (update path, panel, settings, row menu). Only+the IPC boundary is fixtured; nothing installs outside the renderer. Rows below+state only what the fixture asserts.++| ID | Case | Steps / expected (as asserted by the fixture) | Status |+| --- | --- | --- | --- |+| RVD-GRID-01 | Grid — wide | At the 1100px host, `.plugins-list` computed columns are ≥2 and every column is ≥340−1px (the 340px floor) | `verified` (2026-10-16 installed-grid layout probe) |+| RVD-GRID-02 | Grid — narrow | Host forced to 300px: exactly one column ≤300px; the grid does not overflow horizontally (`scrollWidth <= clientWidth + 1`); the card's right edge stays inside the grid | `verified` (2026-10-16 installed-grid layout probe) |+| RVD-GRID-03 | Control order | Updater rail exactly 4: scope-control → primary "Update to v1.2.3" → settings icon (`aria-label "Plugin settings"`) → menu wrap; panel-only rail 3: scope → "Open panel" → menu; settings-only rail 3 with the settings icon second; each disabled card: rail 2 (scope + menu), no primary, no settings icon, no panel action | `verified` (2026-10-16 installed-grid layout probe) |+| RVD-GRID-04 | Update CTA | Primary click → permission dialog "Install Acme Updater?" naming "v1.2.3" → accept → `marketInstall` recorded as `{id:"acme.updater", version:"1.2.3", enable:true, autoUpdate:true}`; the install dialog steps aside | `verified` (2026-10-16 installed-grid actions probe) |+| RVD-GRID-05 | Panel CTA | "Open panel" on the panel-only card → `openPluginPanel("acme.panel")`; disabled cards offer no panel action | `verified` (2026-10-16 installed-grid actions probe) |+| RVD-GRID-06 | Settings | Settings icon → `.plugins-settings-modal` titled "Acme Updater settings"; the close control dismisses it | `verified` (2026-10-16 installed-grid actions probe) |+| RVD-GRID-07 | Groups, membership, disabled states | Seven fixtures in four groups: Needs attention 1 (Acme Broken, error text "Manifest could not be read"); Updates available 2 (Acme Dormant, Acme Updater); Active 3 (Acme Panel, Acme Settings, Long Identifier); Turned off 1 (Acme Off). Disabled gating as in GRID-03 | `verified` (2026-10-16 installed-grid layout probe) |+| RVD-GRID-08 | Scope | Compact scope trigger (first control) opens `.scope-compact-menu.is-open` with 3 `role="menuitemradio"` choices; "Off" → `disablePlugin("acme.updater")` and the menu closes; "Projects" → `setPluginScope("acme.updater", {mode:"projects", projects:[]})` | `verified` (2026-10-16 installed-grid layout probe) |+| RVD-GRID-09 | Row overflow menu | Trigger `aria-label "Actions for Acme Updater"`: "Disable auto-update" → `setPluginAutoUpdate("acme.updater", false)`, menu closes; reopen → "Uninstall" → `uninstallPlugin("acme.updater")`. Source-level (not exercised — no such plugin seeded): Reload appears only for `source === "dev"`, and bundled plugins omit Uninstall | `verified` (2026-10-16 installed-grid actions probe) |+| RVD-GRID-10 | Disclosure | Updater's `details.plugins-row-details` starts closed, opens on summary click, and its body includes "Capabilities"; the settings-only card has no details section | `verified` (2026-10-16 installed-grid layout probe) |+| RVD-GRID-11 | Rating chip geometry | Chip sits inside `.plugins-row-meta` (chipRect within metaRect ±1px — it does not wrap onto its own line); meta line height ≤24px; the zero-summary card renders no chip; the long-id card's `.plugins-row-id` truncates (`scrollWidth > clientWidth + 8`) while staying inside the card. No card-height comparison between chip present/absent is asserted here | `verified` (2026-10-16 installed-grid layout probe) |++### 3.10 Locales, accessibility, narrow width, style++| ID | Check | Expected | Status |+| --- | --- | --- | --- |+| RVD-I18N-01 | Review strings in all nine locales (`de,en,es,fr,ko,pt-BR,tr,zh-CN,zh-TW`) | Every locale carries exactly one nested `reviews: {` block and all seven key names (`summaryTitle`, `viewAll`, `composeHint`, `composeCta`, `reviewVersion`, `filterLabel`, `sortLabel`); the §2.5 check prints `reviewsBlock=1 sevenKeys=7` per locale; vitest catalogue suite green | `verified` (catalogue 30/30 + shared 1272; locale parity re-checked) |+| RVD-A11Y-01 | Accessible names/states of the drawer surface | `role="dialog"`, `aria-modal="true"`, labelled title; filters/sorts `aria-pressed`; list label; load error `role="alert"`; star rating `role="img"` with a rating label; Tab trap + inert; Escape returns focus | `verified` (2026-10-16 six-probe rerun) |+| RVD-NARROW-01 | Narrow drawer at 320×720 (real geometry) | `pluginReviewsNarrowDrawerProbe` on the real components with the hidden window resized to 320×720 (`useContentSize`): drawer rect fully inside the viewport; document and drawer-body have no horizontal overflow; 7+ controls (4 sentiment, 2 sort, close, write link) stay inside the drawer; filter/sort `aria-pressed`; body scrolls (`scrollTop > 0`); composer inside the viewport; write link routes `browserOpenExternal(REVIEW_URL)`; close leaves the detail sheet. Harness applies `base.css` and the repo's reduced-motion `animation: none`. **320 is the only asserted narrow width** — 375 is covered by the probe's `<= 375` guard, not a second run | `verified` (2026-10-17 narrow-drawer probe) |+| RVD-STYLE-01 | `plugins-page-style.test.mjs` — "review surfaces use design tokens in both themes" | Chip tabular numerals; summary uses `--plugins-tile`; scrim uses `--ds-modal-veil`; drawer reserves `--ds-toolbar-height`; composer field token; write link styled | `verified` (2026-10-16 six-file run) |++### 3.11 Non-interference invariants++| ID | Check | Expected | Status |+| --- | --- | --- | --- |+| RVD-REL-01 | Center downtime / legacy center never affects install, update, or plugin actions | Review reads fail in isolation; installed grid and marketplace actions stay usable while summary/list reads fail | `verified` (probe + focused-test evidence, 2026-10-16) |+| RVD-REL-02 | No renderer network or auth for reviews | Only host RPC channels; no `fetch` in the drawer; `browserOpenExternal` is the sole external navigation, host-URL only | `verified` (probe + focused-test evidence, 2026-10-16) |+| RVD-REL-03 | URL trust | No URL derived from package or review content; `reviewUrl` only from the effective trusted origin (fixture override included) | `verified` (probe + focused-test evidence, 2026-10-16) |++## 4. Final evidence summary++All behavior rows below are closed on the frozen source; the execution record in+§5 carries the artifacts.++| Behavior | Cases |+| --- | --- |+| Unavailable entry retained (drawer entry, retry, link out) | Probe verified 2026-10-16 (RVD-E2E-03); RVD-UI-05 verified in the six-file run; RVD-PAGE-04 verified (drawer failure independence pinned by the probes) |+| Stale chip omission removes the chip | Probe verified 2026-10-16 (RVD-E2E-02); RVD-LOG-10 / RVD-UI-11 verified in the six-file run |+| Bridge hardening: response identity, redirect refusal, time bounds | Verified — 22 Rust tests (16 RPC + 6 client-unit) passed after hardening with no Rust source changes since (`host-core-after-hardening.txt`) |+| Installed-card real-component fixture | Verified 2026-10-16 (RVD-E2E-04 + RVD-GRID-01 … RVD-GRID-11); RVD-UI-14 verified in the six-file run |++## 5. Final execution record (this run)++Local execution environment for this run: Windows / PowerShell; isolated+Electron fixture profiles under `.cache/`; worktree revision recorded per row.+Results below are the final recorded execution; each row cites its evidence+artifact. Sources are frozen; the two manual geometry/behavior checks remain+listed as manual, separately from the automated evidence.++Dated result for this run: **2026-10-16/17, coordinator-verified** — 64 targeted+JS tests across the six files and the eight Electron probes (5 drawer + 2+installed-grid + 1 detail-focus) pass on the current exact source; full desktop+typecheck and the production `electron-vite` build exit 0 (main/preload/renderer+built). The cross-host contract check (zero 9/9, nonzero 11/11) was independently+read and accepted. No further desktop production-code changes are expected for+this run; this plan is the only remaining mutable artifact.++| # | Command / path | Status | Evidence recorded | Notes |+| --- | --- | --- | --- | --- |+| 1 | `node --test … market-review-ipc / plugin-reviews-logic / plugin-reviews-surface / plugins-page-style / extensions-page / settings-dialog-overlay …` | verified | 2026-10-16 coordinator targeted six-file run: 64/64 pass (shell output) | Per file: IPC 6, logic 16, surface 14, style 8, extensions 16, overlay host suite 4. Confirm the overlay filename against the run's shell output when archiving the log |+| 2 | `cargo test -p host-core --bin pi-desktop-host-core review` | verified | 22 Rust tests (16 RPC + 6 client-unit) passed after hardening; no Rust source changes since (`host-core-after-hardening.txt`) | Accepted existing evidence — no gratuitous rerun |+| 3 | `cargo fmt --check` / `cargo clippy -p host-core --all-targets` | verified | fmt clean; clippy exit 0 (`clippy-after-hardening.txt`) | Known unrelated warn at `transcripts.rs:893` |+| 4 | `node node_modules/typescript/bin/tsc -p tsconfig.json --noEmit` (desktop) | verified | 2026-10-16 final rerun on the F7/F8 code: exit 0 (`plugin-reviews-desktop-finalbuild.log`) | Full desktop typecheck passed |+| 5 | `node node_modules/electron-vite/bin/electron-vite.js build` (desktop) | verified | 2026-10-16 final rerun on the F7/F8 code: exit 0 (`plugin-reviews-desktop-finalbuild.log`) | main/preload/renderer built; only the pre-existing large-chunk warning |+| 6 | `node scripts/e2e-plugin-reviews-drawer.mjs` | verified | 2026-10-17: drawer harness 5/5 PASS, exit 0 (incl. the batch-stale-guard and narrow-drawer probes) | Total Electron probes now 8 (5 drawer + 2 grid + 1 detail-focus); supersedes the earlier 3-probe drawer run |+| 7 | `node scripts/e2e-installed-grid.mjs` (`installedGridLayoutProbe` + `installedGridActionsProbe`) | verified | 2026-10-16 coordinator six-probe rerun (exit 0) | Installed grid 2/2; carries RVD-GRID-01 … 11 |+| 8 | `node scripts/e2e-plugin-detail-focus.mjs` | verified | 2026-10-16 coordinator six-probe rerun (exit 0) | Detail focus passed |+| 9 | i18n §2.5 checks + vitest catalogue suite | verified | Catalogue suite 30/30 and shared 1272 passed (recorded earlier); `reviewsBlock=1 sevenKeys=7` re-checked mechanically on the current source for all nine locales | Review keys present in every locale; no UI reruns |+| 10 | `cargo test -p host-core --bin pi-desktop-host-core` (full) | executed; baseline failures | 912 passed / 38 `baseline:fail` / 1 ignored (`host-core-after-hardening.txt`) | Environment failures only; not a green suite |+| 11 | Narrow-window check | verified | `pluginReviewsNarrowDrawerProbe` at 320×720 (2026-10-17): no overflow, controls inside, body scrolls, composer inside, link routes, close leaves the sheet. Installed-grid narrow covered separately by the 300px probe (RVD-GRID-02) | 320 is the only asserted narrow width; 375 covered by the `<= 375` guard only |+| 12 | Cross-host contract check (host stdio RPC → real center) | verified | 2026-10-16 — zero run 9/9 + nonzero run 11/11, independently read and accepted | Same host binary (no rebuild); nonzero seed via the center's real write API; no private fields despite one report fixture. Complements the focused RVD-RPC-01…16 tests, which passed after hardening (row 2) |+| 13 | Final oracle gate | PASS | All eight known findings closed on the frozen source; no further production fixes expected | Cross-repo gate covering both plans |++## 6. Change control++- This document is the repo deliverable; corrections land here only.+- Final results are recorded in §5 and the affected case rows are updated in+ place.+- No commits, pushes, tags, or packaging from this plan.diff --git a/docs/spec/07-plugins/07-plugin-marketplace.md b/docs/spec/07-plugins/07-plugin-marketplace.mdindex 5bb49b451..731c05804 100644--- a/docs/spec/07-plugins/07-plugin-marketplace.md+++ b/docs/spec/07-plugins/07-plugin-marketplace.md@@ -194,7 +194,9 @@ user who never installed anything.### Phase C (partial ✅)- Auto-update policy + permission-diff gating implemented-- Ratings / mandatory signing still planned+- Ratings: the desktop reads public summaries and reviews (anonymous, no+ account) and links out to the centre for writing; mandatory signing still+ planned### Phase D (in progress)@@ -502,6 +504,7 @@ Extensions│ ├─ Categories│ └─ Card grid├─ Detail sheet (shared by both tabs)+│ └─ Review drawer (public reads; covers the detail sheet)└─ Permission dialog (install / upgrade)```@@ -513,27 +516,65 @@ contextual primary action (Browse marketplace / Refresh marketplace) and movesCheck for updates, Apply automatic updates, Install package, and Load localplugin into an overflow menu (D169).-Installed rows intentionally default to a quiet two-line summary containing the-plugin name, optional local-source marker, id, and version. The state group-heading carries Active / Turned off / Updates available / Needs attention, and-load errors remain inline. Capabilities, resident service status, and-risk-tinted permission chips are rendered inside a collapsed native Details-disclosure; expanding it exposes the existing full readout without making every-row tall. Installed rows use one current-state scope trigger; opening it shows-the three scope choices with their explanations, and choosing This project-opens the existing project picker. Row icon actions remain visible at rest and-show their labels on hover and keyboard focus. This is a renderer-only-presentation choice; plugin-permissions and activation contracts are unchanged.+Installed plugins are cards in an auto-filling grid+(`minmax(min(340px, 100%), 1fr)`), so a column never overflows a container+narrower than one card. Each card defaults to a quiet summary with the plugin+name, optional local-source marker, id, version, and a public rating chip. The+state group heading carries Active / Turned off / Updates available / Needs+attention, and load errors remain inline. Capabilities, resident service+status, and risk-tinted permission chips are rendered inside a collapsed native+Details disclosure; expanding it exposes the existing full readout without+making every card tall. A card's control rail clusters at its left edge and+wraps: the compact scope trigger first, then the card's one call to action+(update to the available version, or open the plugin's panel), then the 28px+settings and overflow icon actions. A disabled plugin has no primary action and+no settings icon. Opening the scope trigger shows the three scope choices with+their explanations, and choosing This project opens the existing project+picker. Icon actions remain visible at rest and show their labels on hover and+keyboard focus. A verified card shows the trust shield when the installed+record carries a verified trust tier; there is no "verified installed" label.+This is a renderer-only presentation choice; plugin permissions and activation+contracts are unchanged.The Detail sheet must show:- Permissions, grouped and labeled by risk tier+- Ratings summary between permissions and versions: the one-decimal average,+ the rating count, and the good / medium / bad split; an unavailable centre+ reads as unavailable, never as zero, and the review entry stays reachable+ so its retry and its link out are never lost- Author- Version (selectable version list)- Update time- Risk description (safety notes callout)- Install button+Public reviews are reads. Hovering nothing, signing in nowhere: the desktop+never authenticates, never posts, votes, or reports. "See all reviews" opens an+independent review drawer at the same dialog level as the detail sheet; it+covers the sheet while the sheet keeps its mounted state and scroll position,+and Escape closes only the topmost drawer. The covered sheet is `inert` and Tab+is trapped inside the drawer, so keyboard focus can never land on what it+covers; closing returns focus to the button that opened it. The drawer entry is+not gated on the summary: when the summary read fails or the centre predates+review support, the drawer is still reachable — it retries its own list and+always carries the disabled composer plus the link out, which falls back to the+official plugin page until the host reports the effective `reviewUrl`. The+drawer filters+by sentiment, sorts by newest or most helpful, and pages with a stable cursor+(rows deduplicated by id; an answer for a filter the user has left is dropped;+a successful summary read replaces the ratings for the ids just requested, so+a plugin the centre stops serving loses its rating instead of keeping a stale+one); every visible string, including accessible names, is localized. A+review's+version is labelled as user-reported — it is the author's claim, not an+installed version. Its composer is permanently+disabled and its one action is a real link — "Write a review on the plugin+center" — that opens the centre's own page in the system browser+(`browserOpenExternal`), using the host-provided `reviewUrl` for the effective+centre origin and falling back to+`https://plugins.aiuo.net/plugins/{encodedId}#reviews`. Reading reviews never+gates or delays install, update, or any other plugin action.+The Extensions list page keeps its overview copy compact: the page header andtab labels identify the surface, while section headers and empty states usedirect labels and actions without explanatory paragraphs. Explanations remain@@ -591,7 +632,9 @@ All download metadata must include `shasum`.- Remote plugin code hot patching- Silent auto-install- Unverified download-and-execute-- Comment/social system (can be deferred)+- Comment/social system inside the desktop: public reads only, while writing,+ voting, and reporting stay on the centre's own web page (the composer is a+ link out, never a desktop form)## 12. Acceptance (marketplace read-only + install)diff --git a/docs/spec/07-plugins/14-plugin-roadmap.md b/docs/spec/07-plugins/14-plugin-roadmap.mdindex ac6c1f5ec..a07d15efd 100644--- a/docs/spec/07-plugins/14-plugin-roadmap.md+++ b/docs/spec/07-plugins/14-plugin-roadmap.md@@ -63,7 +63,9 @@ Local plugins usable → developer-friendly → marketplace distribution → sig- Inter-plugin message bus ✅ — declared topics, `pi.bus.*` (D178)- Theme plugins ✅ — plugins ship CSS files (D175)- Enterprise private sources (still planned)-- Marketplace reviews / quality score (optional, still planned)+- Marketplace reviews / quality score (partial: the desktop reads public+ summaries and reviews anonymously and links out to the centre to write;+ accounts, writing, voting, and reporting live on the centre's web page)### R7 — Agent extensions (v1.1 ✅, D387 / D388)- v1: ExtensionAPI adapter in the Agent sidecar; tools, commands, lifecycle anddiff --git a/docs/spec/07-plugins/15-plugin-center.md b/docs/spec/07-plugins/15-plugin-center.mdindex 9c35c64e1..83de7b144 100644--- a/docs/spec/07-plugins/15-plugin-center.md+++ b/docs/spec/07-plugins/15-plugin-center.md@@ -376,6 +376,23 @@ cancels an install that is still running, where only the download isinterruptible. Both are client-side contract: the platform's resolve call isunchanged and still sees one request per install or update.+The client also reads public plugin reviews, anonymously:++```text+GET /api/v1/review-summaries?pluginIds=id1,id2+GET /api/v1/plugins/{pluginId}/reviews?cursor=&limit=&sentiment=&sort=+```++The summary route answers aggregate ratings for the plugin ids on screen (a+known plugin without reviews gets a zero summary; an unavailable service is+distinct from zero), so cards can show a rating without a catalog refresh. The+reviews route answers one page of visible reviews plus its summary and a+stable opaque cursor. Both carry only the plugin ids and the chosen filter,+sort, page size, and cursor — no account, session, or device identifier — and+the desktop client cannot post, vote, or report: writing a review happens on+the center's own web page. Public reads are anonymous and never gate install,+update, or any other client action.+## 11. Trust tiers| Tier | Meaning | Who can set it |diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex f8dac6e2b..d2cbb9641 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2211,6 +2211,7 @@ sklm: {"installedLabel": "Installiert","installedVersion": "Installiert v{{version}}","updateNow": "Update",+ updateTo: "Auf v{{version}} aktualisieren","updating": "Wird aktualisiert…","updated": "Aktualisiert {{name}} auf v{{version}}","updateAvailable": "v{{version}} verfügbar",@@ -2299,6 +2300,40 @@ sklm: {"installCopied": "Installationsdetails kopiert","installCopyFailed": "Installationsdetails konnten nicht kopiert werden","contributeGuide": "So tragen Sie bei",+ reviews: {+ ratingChip: "{{avg}} ({{count}})",+ ratingSummaryAria_one: "Mit {{avg}} von 5 aus 1 Bewertung bewertet",+ ratingSummaryAria_other: "Mit {{avg}} von 5 aus {{count}} Bewertungen bewertet",+ summaryTitle: "Bewertungen",+ count_one: "1 Bewertung",+ count_other: "{{count}} Bewertungen",+ empty: "Noch keine Bewertungen.",+ unavailable: "Bewertungen sind für diese Quelle nicht verfügbar.",+ loading: "Bewertungen werden geladen…",+ loadFailed: "Bewertungen konnten nicht geladen werden.",+ retry: "Erneut versuchen",+ loadMore: "Weitere Bewertungen laden",+ close: "Bewertungen schließen",+ title: "Bewertungen für {{name}}",+ viewAll: "Alle Bewertungen ansehen",+ composeHint: "Bewertungen werden im Plugin-Center verfasst.",+ composeCta: "Im Plugin-Center eine Bewertung schreiben",+ reviewVersion: "Vom Nutzer angegebene Version v{{version}}",+ edited: "bearbeitet",+ helpfulCount_one: "1 Person fand das hilfreich",+ helpfulCount_other: "{{count}} Personen fanden das hilfreich",+ reviewRatingAria: "Mit {{rating}} von 5 bewertet",+ distributionAria: "{{label}}: {{count}}",+ filterLabel: "Nach Stimmung filtern",+ sentimentAll: "Alle",+ sentimentPositive: "Positiv",+ sentimentNeutral: "Neutral",+ sentimentNegative: "Negativ",+ sortLabel: "Bewertungen sortieren",+ sortNewest: "Neueste",+ sortHelpful: "Hilfreichste",+ listAria: "Bewertungen",+ },"capabilities": {"panel": "Panel","views": "Arbeitsfensteransichten",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 3f4178648..2df043a0a 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2231,6 +2231,7 @@ importConfirm: "Imported extensions run inside the agent process with the same ainstalledLabel: "Installed",installedVersion: "Installed v{{version}}",updateNow: "Update",+ updateTo: "Update to v{{version}}",updating: "Updating…",updated: "Updated {{name}} to v{{version}}",updateAvailable: "v{{version}} available",@@ -2320,6 +2321,40 @@ importConfirm: "Imported extensions run inside the agent process with the same ainstallCopied: "Install details copied",installCopyFailed: "Couldn't copy the install details",contributeGuide: "How to contribute",+ reviews: {+ ratingChip: "{{avg}} ({{count}})",+ ratingSummaryAria_one: "Rated {{avg}} out of 5 from 1 rating",+ ratingSummaryAria_other: "Rated {{avg}} out of 5 from {{count}} ratings",+ summaryTitle: "Ratings & reviews",+ count_one: "1 rating",+ count_other: "{{count}} ratings",+ empty: "No reviews yet.",+ unavailable: "Ratings aren't available from this source.",+ loading: "Loading reviews…",+ loadFailed: "Couldn't load reviews.",+ retry: "Retry",+ loadMore: "Load more reviews",+ close: "Close reviews",+ title: "{{name}} reviews",+ viewAll: "See all reviews",+ composeHint: "Reviews are written on the plugin center.",+ composeCta: "Write a review on the plugin center",+ reviewVersion: "User-reported version v{{version}}",+ edited: "edited",+ helpfulCount_one: "1 person found this helpful",+ helpfulCount_other: "{{count}} people found this helpful",+ reviewRatingAria: "Rated {{rating}} out of 5",+ distributionAria: "{{label}}: {{count}}",+ filterLabel: "Filter by sentiment",+ sentimentAll: "All",+ sentimentPositive: "Positive",+ sentimentNeutral: "Neutral",+ sentimentNegative: "Negative",+ sortLabel: "Sort reviews",+ sortNewest: "Newest",+ sortHelpful: "Most helpful",+ listAria: "Reviews",+ },capabilities: {panel: "Panel",views: "Work panel views",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 5ecd296b7..c24df4e10 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2211,6 +2211,7 @@ sklm: {"installedLabel": "Instalado","installedVersion": "Instalado v{{version}}","updateNow": "Actualización",+ updateTo: "Actualizar a v{{version}}","updating": "Actualizando…","updated": "Actualizado {{name}} a v{{version}}","updateAvailable": "v{{version}} disponible",@@ -2299,6 +2300,40 @@ sklm: {"installCopied": "Detalles de instalación copiados","installCopyFailed": "No se pudieron copiar los detalles","contributeGuide": "Cómo contribuir",+ reviews: {+ ratingChip: "{{avg}} ({{count}})",+ ratingSummaryAria_one: "Valorado con {{avg}} de 5 a partir de 1 valoración",+ ratingSummaryAria_other: "Valorado con {{avg}} de 5 a partir de {{count}} valoraciones",+ summaryTitle: "Valoraciones y reseñas",+ count_one: "1 valoración",+ count_other: "{{count}} valoraciones",+ empty: "Todavía no hay reseñas.",+ unavailable: "Las valoraciones no están disponibles para esta fuente.",+ loading: "Cargando reseñas…",+ loadFailed: "No se pudieron cargar las reseñas.",+ retry: "Reintentar",+ loadMore: "Cargar más reseñas",+ close: "Cerrar reseñas",+ title: "Reseñas de {{name}}",+ viewAll: "Ver todas las reseñas",+ composeHint: "Las reseñas se escriben en el centro de plugins.",+ composeCta: "Escribir una reseña en el centro de plugins",+ reviewVersion: "Versión indicada por el usuario v{{version}}",+ edited: "editada",+ helpfulCount_one: "A 1 persona le resultó útil",+ helpfulCount_other: "A {{count}} personas les resultó útil",+ reviewRatingAria: "Valorada con {{rating}} de 5",+ distributionAria: "{{label}}: {{count}}",+ filterLabel: "Filtrar por sentimiento",+ sentimentAll: "Todas",+ sentimentPositive: "Positivas",+ sentimentNeutral: "Neutras",+ sentimentNegative: "Negativas",+ sortLabel: "Ordenar reseñas",+ sortNewest: "Más recientes",+ sortHelpful: "Más útiles",+ listAria: "Reseñas",+ },"capabilities": {"panel": "Panel","views": "Vistas del panel de trabajo",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 06c4466d8..40a112469 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2211,6 +2211,7 @@ sklm: {"installedLabel": "Installé","installedVersion": "Installé v{{version}}","updateNow": "Mise à jour",+ updateTo: "Mettre à jour vers v{{version}}","updating": "Mise à jour…","updated": "Mis à jour {{name}} vers v{{version}}","updateAvailable": "v{{version}} disponible",@@ -2299,6 +2300,40 @@ sklm: {"installCopied": "Détails d'installation copiés","installCopyFailed": "Impossible de copier les détails","contributeGuide": "Comment contribuer",+ reviews: {+ ratingChip: "{{avg}} ({{count}})",+ ratingSummaryAria_one: "Noté {{avg}} sur 5 d'après 1 avis",+ ratingSummaryAria_other: "Noté {{avg}} sur 5 d'après {{count}} avis",+ summaryTitle: "Notes et avis",+ count_one: "1 avis",+ count_other: "{{count}} avis",+ empty: "Aucun avis pour le moment.",+ unavailable: "Les notes ne sont pas disponibles pour cette source.",+ loading: "Chargement des avis…",+ loadFailed: "Impossible de charger les avis.",+ retry: "Réessayer",+ loadMore: "Charger plus d'avis",+ close: "Fermer les avis",+ title: "Avis sur {{name}}",+ viewAll: "Voir tous les avis",+ composeHint: "Les avis s'écrivent sur le centre de plugins.",+ composeCta: "Écrire un avis sur le centre de plugins",+ reviewVersion: "Version indiquée par l'utilisateur v{{version}}",+ edited: "modifié",+ helpfulCount_one: "1 personne a trouvé cela utile",+ helpfulCount_other: "{{count}} personnes ont trouvé cela utile",+ reviewRatingAria: "Noté {{rating}} sur 5",+ distributionAria: "{{label}} : {{count}}",+ filterLabel: "Filtrer par sentiment",+ sentimentAll: "Tous",+ sentimentPositive: "Positifs",+ sentimentNeutral: "Neutres",+ sentimentNegative: "Négatifs",+ sortLabel: "Trier les avis",+ sortNewest: "Plus récents",+ sortHelpful: "Plus utiles",+ listAria: "Avis",+ },"capabilities": {"panel": "Panneau","views": "Vues du panneau de travail",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 2a2672f95..57c0fb1c5 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2227,6 +2227,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이installedLabel: "설치됨",installedVersion: "v{{version}} 설치됨",updateNow: "업데이트",+ updateTo: "v{{version}}(으)로 업데이트",updating: "업데이트 중…",updated: "{{name}}을(를) v{{version}}로 업데이트함",updateAvailable: "v{{version}} 사용 가능",@@ -2316,6 +2317,40 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이installCopied: "설치 세부 정보를 복사했습니다",installCopyFailed: "설치 세부 정보를 복사하지 못했습니다",contributeGuide: "기여 방법",+ reviews: {+ ratingChip: "{{avg}} ({{count}})",+ ratingSummaryAria_one: "평가 1개 기준 5점 만점에 {{avg}}점",+ ratingSummaryAria_other: "평가 {{count}}개 기준 5점 만점에 {{avg}}점",+ summaryTitle: "평점 및 리뷰",+ count_one: "평가 1개",+ count_other: "평가 {{count}}개",+ empty: "아직 리뷰가 없습니다.",+ unavailable: "이 소스에서는 평점을 사용할 수 없습니다.",+ loading: "리뷰 불러오는 중…",+ loadFailed: "리뷰를 불러오지 못했습니다.",+ retry: "다시 시도",+ loadMore: "리뷰 더 불러오기",+ close: "리뷰 닫기",+ title: "{{name}} 리뷰",+ viewAll: "모든 리뷰 보기",+ composeHint: "리뷰는 플러그인 센터에서 작성합니다.",+ composeCta: "플러그인 센터에서 리뷰 작성",+ reviewVersion: "사용자 표기 버전 v{{version}}",+ edited: "수정됨",+ helpfulCount_one: "1명이 도움이 되었다고 했습니다",+ helpfulCount_other: "{{count}}명이 도움이 되었다고 했습니다",+ reviewRatingAria: "5점 만점에 {{rating}}점",+ distributionAria: "{{label}}: {{count}}",+ filterLabel: "평가 유형으로 필터",+ sentimentAll: "전체",+ sentimentPositive: "긍정",+ sentimentNeutral: "보통",+ sentimentNegative: "부정",+ sortLabel: "리뷰 정렬",+ sortNewest: "최신순",+ sortHelpful: "도움순",+ listAria: "리뷰",+ },capabilities: {panel: "패널",views: "작업 패널 화면",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex e8da8824b..3bd9ab3bf 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -2177,6 +2177,7 @@ export const ptBR = {installedLabel: "Instalado",installedVersion: "Instalado v{{version}}",updateNow: "Atualizar",+ updateTo: "Atualizar para v{{version}}",updating: "Atualizando…",updated: "{{name}} atualizado para v{{version}}",updateAvailable: "v{{version}} disponível",@@ -2265,6 +2266,40 @@ export const ptBR = {installCopied: "Detalhes da instalação copiados",installCopyFailed: "Não foi possível copiar os detalhes da instalação",contributeGuide: "Como contribuir",+ reviews: {+ ratingChip: "{{avg}} ({{count}})",+ ratingSummaryAria_one: "Avaliado em {{avg}} de 5 com base em 1 avaliação",+ ratingSummaryAria_other: "Avaliado em {{avg}} de 5 com base em {{count}} avaliações",+ summaryTitle: "Notas e avaliações",+ count_one: "1 avaliação",+ count_other: "{{count}} avaliações",+ empty: "Ainda não há avaliações.",+ unavailable: "As notas não estão disponíveis para esta fonte.",+ loading: "Carregando avaliações…",+ loadFailed: "Não foi possível carregar as avaliações.",+ retry: "Tentar novamente",+ loadMore: "Carregar mais avaliações",+ close: "Fechar avaliações",+ title: "Avaliações de {{name}}",+ viewAll: "Ver todas as avaliações",+ composeHint: "As avaliações são escritas no centro de plugins.",+ composeCta: "Escrever uma avaliação no centro de plugins",+ reviewVersion: "Versão informada pelo usuário v{{version}}",+ edited: "editada",+ helpfulCount_one: "1 pessoa achou útil",+ helpfulCount_other: "{{count}} pessoas acharam útil",+ reviewRatingAria: "Avaliado em {{rating}} de 5",+ distributionAria: "{{label}}: {{count}}",+ filterLabel: "Filtrar por sentimento",+ sentimentAll: "Todas",+ sentimentPositive: "Positivas",+ sentimentNeutral: "Neutras",+ sentimentNegative: "Negativas",+ sortLabel: "Ordenar avaliações",+ sortNewest: "Mais recentes",+ sortHelpful: "Mais úteis",+ listAria: "Avaliações",+ },capabilities: {panel: "Painel",views: "Visualizações do painel de trabalho",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 9deb04c57..5e3505206 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2221,6 +2221,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçinstalledLabel: "Kurulu",installedVersion: "Kurulu v{{version}}",updateNow: "Güncelle",+ updateTo: "v{{version}} sürümüne güncelle",updating: "Güncelleniyor…",updated: "{{name}} v{{version}} sürümüne güncellendi",updateAvailable: "v{{version}} kullanılabilir",@@ -2310,6 +2311,40 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçinstallCopied: "Kurulum ayrıntıları kopyalandı",installCopyFailed: "Kurulum ayrıntıları kopyalanamadı",contributeGuide: "Nasıl katkıda bulunulur",+ reviews: {+ ratingChip: "{{avg}} ({{count}})",+ ratingSummaryAria_one: "1 değerlendirme ile 5 üzerinden {{avg}}",+ ratingSummaryAria_other: "{{count}} değerlendirme ile 5 üzerinden {{avg}}",+ summaryTitle: "Puanlar ve değerlendirmeler",+ count_one: "1 değerlendirme",+ count_other: "{{count}} değerlendirme",+ empty: "Henüz değerlendirme yok.",+ unavailable: "Puanlar bu kaynak için kullanılamıyor.",+ loading: "Değerlendirmeler yükleniyor…",+ loadFailed: "Değerlendirmeler yüklenemedi.",+ retry: "Yeniden dene",+ loadMore: "Daha fazla değerlendirme yükle",+ close: "Değerlendirmeleri kapat",+ title: "{{name}} değerlendirmeleri",+ viewAll: "Tüm değerlendirmeleri gör",+ composeHint: "Değerlendirmeler eklenti merkezinde yazılır.",+ composeCta: "Eklenti merkezinde değerlendirme yaz",+ reviewVersion: "Kullanıcının bildirdiği sürüm v{{version}}",+ edited: "düzenlendi",+ helpfulCount_one: "1 kişi bunu faydalı buldu",+ helpfulCount_other: "{{count}} kişi bunu faydalı buldu",+ reviewRatingAria: "5 üzerinden {{rating}}",+ distributionAria: "{{label}}: {{count}}",+ filterLabel: "Duyguya göre filtrele",+ sentimentAll: "Tümü",+ sentimentPositive: "Olumlu",+ sentimentNeutral: "Nötr",+ sentimentNegative: "Olumsuz",+ sortLabel: "Değerlendirmeleri sırala",+ sortNewest: "En yeni",+ sortHelpful: "En faydalı",+ listAria: "Değerlendirmeler",+ },capabilities: {panel: "Panel",views: "Çalışma paneli görünümleri",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 000694a23..82acfa5bd 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2206,6 +2206,7 @@ sklm: {installedLabel: "已安装",installedVersion: "已安装 v{{version}}",updateNow: "更新",+ updateTo: "更新至 v{{version}}",updating: "更新中…",updated: "已将 {{name}} 更新到 v{{version}}",updateAvailable: "可更新到 v{{version}}",@@ -2294,6 +2295,40 @@ sklm: {installCopied: "已复制安装详情",installCopyFailed: "复制安装详情失败",contributeGuide: "贡献指南",+ reviews: {+ ratingChip: "{{avg}}({{count}})",+ ratingSummaryAria_one: "{{avg}} 分(满分 5 分,来自 1 条评分)",+ ratingSummaryAria_other: "{{avg}} 分(满分 5 分,来自 {{count}} 条评分)",+ summaryTitle: "评分与评价",+ count_one: "1 条评分",+ count_other: "{{count}} 条评分",+ empty: "还没有评价。",+ unavailable: "当前来源不提供评分。",+ loading: "正在加载评价…",+ loadFailed: "评价加载失败。",+ retry: "重试",+ loadMore: "加载更多评价",+ close: "关闭评价",+ title: "{{name}} 的评价",+ viewAll: "查看全部评价",+ composeHint: "评价在插件中心发表。",+ composeCta: "前往插件中心发表评论",+ reviewVersion: "用户自报版本 v{{version}}",+ edited: "已编辑",+ helpfulCount_one: "1 人觉得有帮助",+ helpfulCount_other: "{{count}} 人觉得有帮助",+ reviewRatingAria: "评分 {{rating}} 分(满分 5 分)",+ distributionAria: "{{label}}:{{count}}",+ filterLabel: "按评价类型筛选",+ sentimentAll: "全部",+ sentimentPositive: "好评",+ sentimentNeutral: "中评",+ sentimentNegative: "差评",+ sortLabel: "评价排序",+ sortNewest: "最新",+ sortHelpful: "最有帮助",+ listAria: "评价",+ },capabilities: {panel: "面板",views: "工作面板视图",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex e179acdeb..5454a3aee 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2206,6 +2206,7 @@ sklm: {installedLabel: "已安裝",installedVersion: "已安裝 v{{version}}",updateNow: "更新",+ updateTo: "更新至 v{{version}}",updating: "更新中…",updated: "已將 {{name}} 更新到 v{{version}}",updateAvailable: "可更新到 v{{version}}",@@ -2294,6 +2295,40 @@ sklm: {installCopied: "已複製安裝詳情",installCopyFailed: "複製安裝詳情失敗",contributeGuide: "貢獻指南",+ reviews: {+ ratingChip: "{{avg}}({{count}})",+ ratingSummaryAria_one: "{{avg}} 分(滿分 5 分,來自 1 則評分)",+ ratingSummaryAria_other: "{{avg}} 分(滿分 5 分,來自 {{count}} 則評分)",+ summaryTitle: "評分與評價",+ count_one: "1 則評分",+ count_other: "{{count}} 則評分",+ empty: "還沒有評價。",+ unavailable: "目前來源不提供評分。",+ loading: "正在載入評價…",+ loadFailed: "評價載入失敗。",+ retry: "重試",+ loadMore: "載入更多評價",+ close: "關閉評價",+ title: "{{name}} 的評價",+ viewAll: "查看全部評價",+ composeHint: "評價在外掛中心發表。",+ composeCta: "前往外掛中心發表評論",+ reviewVersion: "使用者自報版本 v{{version}}",+ edited: "已編輯",+ helpfulCount_one: "1 人覺得有幫助",+ helpfulCount_other: "{{count}} 人覺得有幫助",+ reviewRatingAria: "評分 {{rating}} 分(滿分 5 分)",+ distributionAria: "{{label}}:{{count}}",+ filterLabel: "依評價類型篩選",+ sentimentAll: "全部",+ sentimentPositive: "好評",+ sentimentNeutral: "中評",+ sentimentNegative: "差評",+ sortLabel: "評價排序",+ sortNewest: "最新",+ sortHelpful: "最有幫助",+ listAria: "評價",+ },capabilities: {panel: "面板",views: "工作面板檢視",diff --git a/packages/shared/src/changelog-de.ts b/packages/shared/src/changelog-de.tsindex d3bba74b2..c5510a04f 100644--- a/packages/shared/src/changelog-de.ts+++ b/packages/shared/src/changelog-de.ts@@ -5,6 +5,8 @@ export const deEntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "Installierte Plugins erscheinen als Karten in einem selbst füllenden Raster, jede mit einer klaren Aktion und sichtbarem Vertrauens-, Update- und Geltungsstatus.",+ "Öffentliche Bewertungen und Rezensionen für Marketplace-Plugins lesen und im Plugin-Center eine schreiben — die Desktop-App meldet sich nie an.","Lange Bash-Befehle laufen nach dem Agenten-Turn als Hintergrundaufgaben weiter; ihre Ausgabe lässt sich später prüfen.","Parallele Sitzungen eines Projekts laufen jeweils in einem eigenen Git-Worktree.","Die Todo-Liste bleibt neben dem Composer angedockt und lässt sich bei Bedarf erweitern.",diff --git a/packages/shared/src/changelog-en.ts b/packages/shared/src/changelog-en.tsindex 9c5bbbba9..5349c3ec0 100644--- a/packages/shared/src/changelog-en.ts+++ b/packages/shared/src/changelog-en.ts@@ -5,6 +5,8 @@ export const enEntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "Browse installed plugins as cards in an auto-filling grid, each with one clear action and its trust, update, and scope state at a glance.",+ "Read public ratings and reviews for marketplace plugins, and open the plugin center to write one — the desktop never signs in.","Keep long-running Bash commands going after a turn ends, then review their output as background tasks.","Run parallel conversations in a project with an isolated Git worktree for each session.","Keep the Todo list docked beside the Composer and expand it when you need the full checklist.",diff --git a/packages/shared/src/changelog-es.ts b/packages/shared/src/changelog-es.tsindex a3cfac5c0..d82673a63 100644--- a/packages/shared/src/changelog-es.ts+++ b/packages/shared/src/changelog-es.ts@@ -5,6 +5,8 @@ export const esEntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "Los plugins instalados aparecen como tarjetas en una cuadrícula autoajustable, cada una con una acción clara y su estado de confianza, actualización y alcance a la vista.",+ "Lee valoraciones y reseñas públicas de los plugins del mercado y abre el centro de plugins para escribir una: la aplicación de escritorio nunca inicia sesión.","Los comandos Bash largos continúan como tareas en segundo plano cuando termina el turno, y puedes consultar su salida después.","Las conversaciones paralelas de un proyecto se ejecutan en worktrees de Git independientes.","Mantén la lista Todo junto al cuadro de composición y amplíala cuando necesites verla completa.",diff --git a/packages/shared/src/changelog-fr.ts b/packages/shared/src/changelog-fr.tsindex e1e1d81df..46a7092a4 100644--- a/packages/shared/src/changelog-fr.ts+++ b/packages/shared/src/changelog-fr.ts@@ -5,6 +5,8 @@ export const frEntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "Les plugins installés s'affichent en cartes dans une grille auto-adaptative, chacune avec une action claire et son état de confiance, de mise à jour et de portée visible.",+ "Consultez les notes et avis publics des plugins du marché et ouvrez le centre de plugins pour en écrire un — l'application de bureau ne se connecte jamais.","Les longues commandes Bash continuent en tâche de fond à la fin du tour, et leur sortie reste consultable.","Les conversations parallèles d’un projet s’exécutent chacune dans un worktree Git isolé.","Gardez la liste Todo à côté du Composer et développez-la pour voir toute la liste.",diff --git a/packages/shared/src/changelog-ko.ts b/packages/shared/src/changelog-ko.tsindex c23241056..45e453c13 100644--- a/packages/shared/src/changelog-ko.ts+++ b/packages/shared/src/changelog-ko.ts@@ -5,6 +5,8 @@ export const koEntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "설치된 플러그인이 자동 채움 카드 그리드로 표시되고, 각 카드에 명확한 동작과 신뢰·업데이트·적용 범위 상태가 함께 보입니다.",+ "마켓플레이스 플러그인의 공개 평점과 리뷰를 읽고, 플러그인 센터에서 리뷰를 작성할 수 있습니다. 데스크톱은 로그인하지 않습니다.","긴 Bash 명령은 턴이 끝난 뒤에도 백그라운드 작업으로 계속 실행되며, 나중에 출력을 확인할 수 있습니다.","한 프로젝트의 병렬 대화는 각각 분리된 Git worktree에서 실행됩니다.","Todo 목록을 작성창 옆에 고정하고 필요할 때 전체 목록을 펼쳐 보세요.",diff --git a/packages/shared/src/changelog-pt-BR.ts b/packages/shared/src/changelog-pt-BR.tsindex aadf679b0..54e6961eb 100644--- a/packages/shared/src/changelog-pt-BR.ts+++ b/packages/shared/src/changelog-pt-BR.ts@@ -5,6 +5,8 @@ export const ptBREntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "Os plugins instalados aparecem como cartões em uma grade de preenchimento automático, cada um com uma ação clara e o estado de confiança, atualização e escopo à vista.",+ "Leia notas e avaliações públicas dos plugins do mercado e abra o centro de plugins para escrever uma — o aplicativo de desktop nunca faz login.","Comandos Bash longos continuam em tarefas em segundo plano após o turno, e você pode consultar a saída depois.","Conversas paralelas do mesmo projeto são executadas em worktrees Git isoladas.","Mantenha a lista Todo ao lado do Composer e expanda-a quando precisar ver tudo.",diff --git a/packages/shared/src/changelog-tr.ts b/packages/shared/src/changelog-tr.tsindex 0e2812f70..45c2b4548 100644--- a/packages/shared/src/changelog-tr.ts+++ b/packages/shared/src/changelog-tr.ts@@ -5,6 +5,8 @@ export const trEntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "Yüklü eklentiler kendiliğinden dolan bir kart ızgarasında görünür; her kartta net bir eylem ile güven, güncelleme ve kapsam durumu yer alır.",+ "Mağaza eklentilerinin herkese açık puanlarını ve değerlendirmelerini okuyun, yazmak için eklenti merkezini açın — masaüstü uygulaması hiçbir zaman oturum açmaz.","Uzun Bash komutları tur bittikten sonra arka plan görevleri olarak çalışmaya devam eder; çıktıları daha sonra inceleyebilirsiniz.","Aynı projedeki paralel konuşmalar birbirinden yalıtılmış Git worktree'lerinde çalışır.","Todo listesini Composer'ın yanında sabit tutun, gerektiğinde tamamını açın.",diff --git a/packages/shared/src/changelog-zh-CN.ts b/packages/shared/src/changelog-zh-CN.tsindex 912baa669..ea3e0d033 100644--- a/packages/shared/src/changelog-zh-CN.ts+++ b/packages/shared/src/changelog-zh-CN.ts@@ -5,6 +5,8 @@ export const zhCNEntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "已安装插件改为自适应卡片网格,每张卡片都有明确的主操作,信任、更新与作用范围一目了然。",+ "可查看插件市场的公开评分与评论,并可前往插件中心发表评论——桌面端无需登录。","长时间运行的 Bash 命令可转为后台任务,在本轮结束后继续执行,并可随时查看输出。","同一项目中的并行会话各自在独立的 Git 工作树中运行。","Todo 清单可停靠在输入框旁,需要时展开查看完整列表。",diff --git a/packages/shared/src/changelog-zh-TW.ts b/packages/shared/src/changelog-zh-TW.tsindex c101ca1c9..3cebb6e98 100644--- a/packages/shared/src/changelog-zh-TW.ts+++ b/packages/shared/src/changelog-zh-TW.ts@@ -5,6 +5,8 @@ export const zhTWEntries: ChangelogEntry[] = [version: "0.21.0",date: "2026-10-16",highlights: [+ "已安裝外掛改為自適應卡片網格,每張卡片都有明確的主要操作,信任、更新與作用範圍一目了然。",+ "可查看外掛市場的公開評分與評論,並可前往外掛中心發表評論——桌面端無需登入。","長時間執行的 Bash 命令可轉為背景工作,在本輪結束後繼續執行,並可隨時查看輸出。","同一專案中的平行對話各自在獨立的 Git 工作樹中執行。","Todo 清單可停駐在輸入框旁,需要時展開查看完整清單。",diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex d03bb7ce9..6425d25be 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -383,6 +383,8 @@ export const IPC = {marketCheckUpdates: "pi-desktop/market/checkUpdates",marketApplyUpdates: "pi-desktop/market/applyUpdates",marketCancelInstall: "pi-desktop/market/cancelInstall",+ marketReviewSummaries: "pi-desktop/market/reviewSummaries",+ marketReviews: "pi-desktop/market/reviews",commandPaletteSearch: "pi-desktop/commandPalette/search",commandPaletteExecute: "pi-desktop/commandPalette/execute",logOpenFolder: "pi-desktop/log/openFolder",diff --git a/packages/shared/src/types/marketplace.ts b/packages/shared/src/types/marketplace.tsindex 14dd57c1a..06c9c9b22 100644--- a/packages/shared/src/types/marketplace.ts+++ b/packages/shared/src/types/marketplace.ts@@ -62,3 +62,61 @@ export type PluginInstallResult = {upgraded: boolean;permissionDiff: string[];};++// --- Public plugin reviews --------------------------------------------------+// Read anonymously through the host from the trusted plugin center. The+// desktop only reads: reviewing happens on the center's own web page, and no+// account, cookie, or device credential crosses this bridge.++/** Aggregated visible reviews for one plugin. */+export type PluginReviewSummary = {+ pluginId: string;+ /** One-decimal average of visible ratings; null when nothing is visible. */+ ratingAvg: number | null;+ ratingCount: number;+ /** Floor star buckets: index 0 is 1 star, index 4 is 5 stars. */+ ratingDist: [number, number, number, number, number];+ positiveCount: number;+ neutralCount: number;+ negativeCount: number;+};++/** Moderation state of one review. Public reads carry `visible` only. */+export type PluginReviewStatus = "visible" | "pending" | "hidden" | "deleted";++/**+ * One public review. The account id, a hidden reason, and moderation data are+ * never part of the public shape; the author is shown by `authorName` only.+ */+export type PluginReview = {+ id: string;+ pluginId: string;+ authorName: string;+ /** Rating in half stars, 2..10 (one to five whole stars). */+ ratingHalfStars: number;+ body: string;+ status: PluginReviewStatus;+ pluginVersion: string;+ helpfulCount: number;+ createdAt: string;+ updatedAt: string;+ editedAt: string | null;+};++/** One page of public reviews plus the trusted center webpage for the plugin. */+export type PluginReviewPage = {+ reviews: PluginReview[];+ nextCursor: string | null;+ summary: PluginReviewSummary;+ /** Built by the host from the effective trusted center origin. */+ reviewUrl: string;+};++/** What one review read asks for. */+export type PluginReviewQuery = {+ pluginId: string;+ cursor?: string;+ limit?: number;+ sentiment?: "all" | "positive" | "neutral" | "negative";+ sort?: "newest" | "helpful";+};diff --git a/scripts/e2e-installed-grid.mjs b/scripts/e2e-installed-grid.mjsnew file mode 100644index 000000000..bdd3883c2--- /dev/null+++ b/scripts/e2e-installed-grid.mjs@@ -0,0 +1,116 @@+#!/usr/bin/env node+// Real installed-grid components and Chromium behaviour; only host APIs are+// fixtures. Drives the installed user path: groups and counts, control-rail+// order and gating (scope first, update OR panel, disabled none), the detail+// disclosure, the real compact scope menu, chip-in-meta and long-id+// truncation, the 340px grid floor with the sub-340 fallback, narrow rail+// wrapping, and the action path update -> permission review -> marketInstall,+// open-panel id, settings sheet, and the overflow auto-update/uninstall+// controls. Nothing installs outside the renderer.+import { spawnSync } from "node:child_process";+import { existsSync, readFileSync } from "node:fs";+import { createRequire } from "node:module";+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const desktop = join(root, "apps/desktop");+const require = createRequire(join(root, "packages/agent-runtime/package.json"));++/**+ * Electron's download is shared with the host checkout: prefer the worktree's+ * own linked install, otherwise resolve the hoisted package. Dependency+ * linking itself is owned by the environment setup, not by this script.+ */+function resolveElectronBinary() {+ const localDir = join(desktop, "node_modules", "electron");+ const localPathFile = join(localDir, "path.txt");+ const fallbackDir = dirname(require.resolve("electron"));+ const electronDir = existsSync(localPathFile) ? localDir : fallbackDir;+ const relativeBinary = existsSync(join(electronDir, "path.txt"))+ ? readFileSync(join(electronDir, "path.txt"), "utf8").trim()+ : process.platform === "win32"+ ? "electron.exe"+ : "electron";+ const binary = join(electronDir, "dist", relativeBinary);+ if (!existsSync(binary)) throw new Error("Electron binary missing: " + binary);+ return binary;+}++const cache = join(root, ".cache/installed-grid");+await mkdir(cache, { recursive: true });+const temp = await mkdtemp(join(cache, "run-"));+await require("esbuild").build({+ entryPoints: [join(root, "scripts/e2e/installed-grid.tsx")],+ outfile: join(temp, "renderer.js"),+ bundle: true,+ platform: "browser",+ format: "iife",+ loader: { ".css": "empty" },+ jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"' },+ // `render-diagnostics.ts` reads `import.meta.env`; the iife probe does not.+ logOverride: { "empty-import-meta": "silent" },+ // The browser packages resolve through the checkout's node_modules; the+ // workspace packages must come from THIS worktree's built sources, not a+ // possibly older copy under the host install.+ alias: {+ "@pi-desktop/shared": join(root, "packages/shared/dist/index.js"),+ "@pi-desktop/plugin-sdk": join(root, "packages/plugin-sdk/dist/index.js"),+ },+});+// The real stylesheets that lay these surfaces out (tokens, the app-shell+// base, the shared kit, the plugins page, and the extension scope controls)+// are inlined, so geometry and scroll containment match the shipping cascade+// without a full renderer build. Entrance animations are disabled exactly as+// the repo's reduced-motion tail does: a hidden window does not advance them.+await writeFile(+ join(temp, "index.html"),+ `<!doctype html><html><head><style>${readFileSync(+ join(desktop, "src/styles/tokens.css"),+ "utf8",+ )}\n${readFileSync(join(desktop, "src/styles/base.css"), "utf8")}\n${readFileSync(+ join(desktop, "src/styles/ui-kit.css"),+ "utf8",+ )}\n${readFileSync(+ join(desktop, "src/styles/plugins.css"),+ "utf8",+ )}\n${readFileSync(+ join(desktop, "src/styles/extensions.css"),+ "utf8",+ )}\n.plugins-reviews,.plugins-reviews-scrim,.plugins-sheet,.plugins-sheet-scrim,.plugins-menu,.plugins-modal,.plugins-modal-backdrop{animation:none !important;}+</style></head><body><script src="renderer.js"></script></body></html>`,+);+await writeFile(+ join(temp, "main.cjs"),+ `+const {app,BrowserWindow}=require('electron');+app.setPath('userData',require('node:path').join(__dirname,'profile'));+app.disableHardwareAcceleration();+app.whenReady().then(async()=>{+ try {+ const win=new BrowserWindow({show:false,width:1100,height:900,webPreferences:{backgroundThrottling:false,sandbox:true,contextIsolation:true}});+ await win.loadFile(require('node:path').join(__dirname,'index.html'));+ const probes=['installedGridLayoutProbe','installedGridActionsProbe'];+ let failed=false;+ for(const name of probes){+ const guarded='(async()=>{try{const value=await Promise.race([globalThis.'+name+'(),new Promise((_,reject)=>setTimeout(()=>reject(new Error("probe timeout")),40000))]);return {ok:true,value:value};}catch(error){return {ok:false,message:(error&&error.message)||String(error),step:globalThis.__probeStep||"unknown"};}})()';+ const result=await win.webContents.executeJavaScript(guarded);+ if(result&&result.ok){+ console.log(result.value);+ } else {+ failed=true;+ console.error(name+': '+((result&&result.message)||'unknown failure')+' (step: '+((result&&result.step)||'unknown')+')');+ }+ }+ app.exit(failed?1:0);+ } catch(error) { console.error(error); app.exit(1); }+});`,+);+const result = spawnSync(resolveElectronBinary(), [join(temp, "main.cjs")], {+ stdio: "inherit",+ timeout: 90000,+});+if (result.error) throw result.error;+process.exitCode = result.status ?? 1;diff --git a/scripts/e2e-plugin-detail-focus.mjs b/scripts/e2e-plugin-detail-focus.mjsindex cf9b385ed..777f345fd 100644--- a/scripts/e2e-plugin-detail-focus.mjs+++ b/scripts/e2e-plugin-detail-focus.mjs@@ -17,6 +17,8 @@ await require("esbuild").build({entryPoints: [join(root, "scripts/e2e/plugin-detail-focus.tsx")],outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "iife",loader: { ".css": "empty" }, jsx: "automatic", define: { "process.env.NODE_ENV": '"production"' },+ // `render-diagnostics.ts` reads `import.meta.env`; the iife probe does not.+ logOverride: { "empty-import-meta": "silent" },alias: { react: join(desktop, "node_modules/react"), "react-dom": join(desktop, "node_modules/react-dom") },nodePaths: [join(desktop, "node_modules")],});diff --git a/scripts/e2e-plugin-reviews-drawer.mjs b/scripts/e2e-plugin-reviews-drawer.mjsnew file mode 100644index 000000000..db46e83ca--- /dev/null+++ b/scripts/e2e-plugin-reviews-drawer.mjs@@ -0,0 +1,113 @@+#!/usr/bin/env node+// Real review-drawer components and Chromium behaviour; only host APIs are+// fixtures. Drives the public user path: card chip -> detail summary ->+// drawer (paging/dedup, filter stale-drop, error+retry) -> write link ->+// Tab trap/inert -> Escape with focus and scroll restoration.+import { spawnSync } from "node:child_process";+import { existsSync, readFileSync } from "node:fs";+import { createRequire } from "node:module";+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const desktop = join(root, "apps/desktop");+const require = createRequire(join(root, "packages/agent-runtime/package.json"));++/**+ * Electron's download is shared with the host checkout: prefer the worktree's+ * own linked install, otherwise resolve the hoisted package. Dependency+ * linking itself is owned by the environment setup, not by this script.+ */+function resolveElectronBinary() {+ const localDir = join(desktop, "node_modules", "electron");+ const localPathFile = join(localDir, "path.txt");+ const fallbackDir = dirname(require.resolve("electron"));+ const electronDir = existsSync(localPathFile) ? localDir : fallbackDir;+ const relativeBinary = existsSync(join(electronDir, "path.txt"))+ ? readFileSync(join(electronDir, "path.txt"), "utf8").trim()+ : process.platform === "win32"+ ? "electron.exe"+ : "electron";+ const binary = join(electronDir, "dist", relativeBinary);+ if (!existsSync(binary)) throw new Error("Electron binary missing: " + binary);+ return binary;+}++const cache = join(root, ".cache/plugin-reviews-drawer");+await mkdir(cache, { recursive: true });+const temp = await mkdtemp(join(cache, "run-"));+await require("esbuild").build({+ entryPoints: [join(root, "scripts/e2e/plugin-reviews-drawer.tsx")],+ outfile: join(temp, "renderer.js"),+ bundle: true,+ platform: "browser",+ format: "iife",+ loader: { ".css": "empty" },+ jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"' },+ // `render-diagnostics.ts` reads `import.meta.env`; the iife bundle cannot+ // carry it and the probe does not depend on it.+ logOverride: { "empty-import-meta": "silent" },+ // The browser packages resolve through the checkout's node_modules; the+ // workspace packages must come from THIS worktree's built sources, not a+ // possibly older copy under the host install.+ alias: {+ "@pi-desktop/shared": join(root, "packages/shared/dist/index.js"),+ "@pi-desktop/plugin-sdk": join(root, "packages/plugin-sdk/dist/index.js"),+ },+});+// The real stylesheets that lay this surface out (tokens, the app-shell base,+// the shared kit, and the plugins page) are inlined, so scroll containment and+// geometry match the shipping cascade without a full renderer build. Entrance+// animations are disabled exactly as the repo's reduced-motion tail does: a+// hidden window does not advance them, and geometry must be measured settled.+await writeFile(+ join(temp, "index.html"),+ `<!doctype html><html><head><style>${readFileSync(+ join(desktop, "src/styles/tokens.css"),+ "utf8",+ )}\n${readFileSync(join(desktop, "src/styles/base.css"), "utf8")}\n${readFileSync(+ join(desktop, "src/styles/ui-kit.css"),+ "utf8",+ )}\n${readFileSync(+ join(desktop, "src/styles/plugins.css"),+ "utf8",+ )}\n.plugins-reviews,.plugins-reviews-scrim,.plugins-sheet,.plugins-sheet-scrim,.plugins-menu,.plugins-modal,.plugins-modal-backdrop{animation:none !important;}+</style></head><body><script src="renderer.js"></script></body></html>`,+);+await writeFile(+ join(temp, "main.cjs"),+ `+const {app,BrowserWindow}=require('electron');+app.setPath('userData',require('node:path').join(__dirname,'profile'));+app.disableHardwareAcceleration();+app.whenReady().then(async()=>{+ try {+ const win=new BrowserWindow({show:false,useContentSize:true,width:900,height:720,webPreferences:{backgroundThrottling:false,sandbox:true,contextIsolation:true}});+ await win.loadFile(require('node:path').join(__dirname,'index.html'));+ const probes=['pluginReviewsDrawerProbe','pluginReviewsStaleSummaryProbe','pluginReviewsUnavailableSummaryProbe','pluginReviewsBatchProbe','pluginReviewsNarrowDrawerProbe'];+ let failed=false;+ for(const name of probes){+ // The narrow probe runs against a phone-sized viewport; everything else+ // keeps the desktop one.+ win.setContentSize(name==='pluginReviewsNarrowDrawerProbe'?320:900,name==='pluginReviewsNarrowDrawerProbe'?720:720);+ const guarded='(async()=>{try{const value=await Promise.race([globalThis.'+name+'(),new Promise((_,reject)=>setTimeout(()=>reject(new Error("probe timeout")),45000))]);return {ok:true,value:value};}catch(error){return {ok:false,message:(error&&error.message)||String(error),step:globalThis.__probeStep||"unknown"};}})()';+ const outcome=await win.webContents.executeJavaScript(guarded);+ if(outcome&&outcome.ok){+ console.log(outcome.value);+ } else {+ failed=true;+ console.error(name+': '+((outcome&&outcome.message)||'unknown failure')+' (step: '+((outcome&&outcome.step)||'unknown')+')');+ }+ }+ app.exit(failed?1:0);+ } catch(error) { console.error(error); app.exit(1); }+});`,+);+const result = spawnSync(resolveElectronBinary(), [join(temp, "main.cjs")], {+ stdio: "inherit",+ timeout: 60000,+});+if (result.error) throw result.error;+process.exitCode = result.status ?? 1;diff --git a/scripts/e2e/installed-grid.tsx b/scripts/e2e/installed-grid.tsxnew file mode 100644index 000000000..00a0737ef--- /dev/null+++ b/scripts/e2e/installed-grid.tsx@@ -0,0 +1,572 @@+/**+ * The installed-plugins card grid and its control rail, driven through the+ * real components in Chromium.+ *+ * Only the IPC boundary is fixtured (`api`); `usePluginsPage`,+ * `InstalledPluginsPanel`, the real `ScopeControl`, the overflow menu, the+ * permission dialog, the install dialog and the plugin settings sheet are the+ * shipping implementations. Runs headless through+ * `scripts/e2e-installed-grid.mjs`; each probe returns a PASS summary the+ * harness prints, and no install ever leaves the renderer.+ */+import React from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import i18n from "i18next";+import { I18nextProvider } from "react-i18next";+import { en } from "../../packages/i18n/src/index";+import { api } from "../../apps/desktop/src/lib/api";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";+import { usePluginsPage } from "../../apps/desktop/src/features/plugins/usePluginsPage";+import { InstalledPluginsPanel } from "../../apps/desktop/src/features/plugins/InstalledPluginsPanel";+import { PluginDialogs } from "../../apps/desktop/src/features/plugins/PluginDialogs";+import { usePluginBrowseState } from "../../apps/desktop/src/features/plugins/browse-state";++const check = (ok: boolean, label: string) => {+ if (!ok) throw new Error(label);+};+const find = <T extends HTMLElement = HTMLElement>(selector: string): T => {+ const node = document.querySelector<T>(selector);+ if (!node) throw new Error(`Missing ${selector}`);+ return node;+};+const maybe = <T extends HTMLElement = HTMLElement>(selector: string): T | null =>+ document.querySelector<T>(selector);+const settle = async (predicate: () => boolean, label: string) => {+ for (let tick = 0; tick < 400; tick++) {+ if (predicate()) return;+ // A hidden Chromium window can stop producing animation frames; whichever+ // of the two fires first advances the wait, so the probe never stalls.+ await new Promise<void>((resolve) => {+ let done = false;+ const finish = () => {+ if (done) return;+ done = true;+ resolve();+ };+ requestAnimationFrame(finish);+ setTimeout(finish, 16);+ });+ }+ throw new Error(`Did not settle: ${label}`);+};++const LONG_ID = "acme.some-really-long-plugin-identifier.for-the-fixture-that-must-truncate";++/**+ * Seven plugins covering every group and every rail shape: enabled with an+ * update (and a panel and settings), enabled with only a panel, enabled with+ * only settings, a disabled plugin that still has an update, a plain disabled+ * plugin, a broken plugin, and one whose id must truncate.+ */+const installFixtures = () => [+ {+ id: "acme.updater",+ name: "Acme Updater",+ version: "1.0.0",+ enabled: true,+ status: "ready",+ source: "marketplace",+ permissions: ["ui.panel"],+ capabilities: ["panel", "commands"],+ settings: [{ key: "token", title: "Token", type: "string" }],+ ui: { panel: "panel.html" },+ autoUpdate: true,+ marketplace: { providerId: "official", trust: "verified" },+ updateAvailable: {+ version: "1.2.3",+ shasum: "abc",+ url: "https://example.test/updater.piplug",+ permissionDiff: ["net.fetch"],+ },+ },+ {+ id: "acme.panel",+ name: "Acme Panel",+ version: "2.0.0",+ enabled: true,+ status: "ready",+ source: "marketplace",+ permissions: ["ui.panel"],+ capabilities: ["panel"],+ ui: { panel: "panel.html" },+ },+ {+ id: "acme.settings-only",+ name: "Acme Settings",+ version: "0.4.0",+ enabled: true,+ status: "ready",+ source: "installed",+ permissions: [],+ settings: [{ key: "note", title: "Note", type: "string" }],+ },+ {+ id: "acme.disabled-update",+ name: "Acme Dormant",+ version: "1.0.0",+ enabled: false,+ status: "disabled",+ source: "marketplace",+ permissions: ["ui.panel"],+ capabilities: ["panel"],+ settings: [{ key: "token", title: "Token", type: "string" }],+ ui: { panel: "panel.html" },+ updateAvailable: {+ version: "2.0.0",+ shasum: "def",+ url: "https://example.test/dormant.piplug",+ permissionDiff: [],+ },+ },+ {+ id: "acme.disabled",+ name: "Acme Off",+ version: "3.1.0",+ enabled: false,+ status: "disabled",+ source: "installed",+ permissions: [],+ },+ {+ id: "acme.broken",+ name: "Acme Broken",+ version: "0.1.0",+ enabled: false,+ status: "error",+ errorMessage: "Manifest could not be read",+ source: "installed",+ permissions: [],+ },+ {+ id: LONG_ID,+ name: "Long Identifier",+ version: "9.9.9",+ enabled: true,+ status: "ready",+ source: "marketplace",+ permissions: [],+ },+];++const pageMocks = () => ({+ listProjects: async () => ({ projects: [] }),+ listPlugins: async () => ({ plugins: installFixtures() }),+ listPluginServices: async () => [],+ marketCheckUpdates: async () => ({}),+ marketSearch: async () => ({ plugins: [] }),+ onPluginChanged: () => () => {},+ onPluginInstallProgress: () => () => {},+});++function mountProbe() {+ document.body.style.margin = "0";+ const host = document.createElement("div");+ host.id = "installed-grid-host";+ host.style.width = "960px";+ document.body.append(host);+ const root = createRoot(host);+ flushSync(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <Probe />+ </I18nextProvider>,+ ),+ );+ return { host, root };+}++/** Marks the phase a hung probe stopped in; the harness reports it. */+const step = (name: string) => {+ (globalThis as Record<string, unknown>).__probeStep = name;+};++const cardByName = (name: string) =>+ [...document.querySelectorAll<HTMLElement>(".plugins-row")].find(+ (card) => card.querySelector(".plugins-row-name")?.textContent === name,+ )!;+const controlsOf = (card: HTMLElement) =>+ [...card.querySelector<HTMLElement>(".plugins-row-controls")!.children];+const menuItemByText = (text: string) =>+ [+ ...document.querySelectorAll<HTMLButtonElement>(+ ".scope-compact-menu.is-open button, .plugins-menu.is-open button",+ ),+ ].find((button) => button.textContent?.includes(text))!;+const columnsOf = (list: HTMLElement) =>+ window+ .getComputedStyle(list)+ .gridTemplateColumns.split(" ")+ .filter(Boolean)+ .map((value) => Number.parseFloat(value));++Object.assign(globalThis, {+ installedGridLayoutProbe: async () => {+ step("init");+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ step("mocks");+ Object.assign(api, {+ ...pageMocks(),+ // A verified rating for the updater, a zero summary for the panel, and+ // nothing for the rest: the chip must appear once, never for zero.+ marketReviewSummaries: async () => ({+ "acme.updater": {+ pluginId: "acme.updater",+ ratingAvg: 4.5,+ ratingCount: 3,+ ratingDist: [0, 0, 0, 1, 2],+ positiveCount: 2,+ neutralCount: 1,+ negativeCount: 0,+ },+ "acme.panel": {+ pluginId: "acme.panel",+ ratingAvg: null,+ ratingCount: 0,+ ratingDist: [0, 0, 0, 0, 0],+ positiveCount: 0,+ neutralCount: 0,+ negativeCount: 0,+ },+ }),+ setPluginScope: async () => ({ ok: true }),+ enablePlugin: async () => ({ ok: true }),+ disablePlugin: async () => ({ ok: true }),+ });++ useAppStore.setState({ plugins: installFixtures() });+ usePluginBrowseState.setState({ tab: "installed", installedQuery: "" });+ step("render");+ const { host, root } = mountProbe();++ step("mount");+ await settle(() => !!maybe(".plugins-list"), "installed grid");+ await settle(() => !!maybe(".plugins-rating"), "rating chip");++ step("groups");+ // --- Groups and their members ----------------------------------------+ const groups = [...document.querySelectorAll<HTMLElement>(".plugins-group")].map(+ (group) => ({+ label: group.querySelector(".plugins-group-label")?.textContent,+ count: group.querySelector(".plugins-group-count")?.textContent,+ names: [...group.querySelectorAll<HTMLElement>(".plugins-row-name")].map(+ (node) => node.textContent,+ ),+ }),+ );+ check(+ JSON.stringify(groups) ===+ JSON.stringify([+ { label: "Needs attention", count: "1", names: ["Acme Broken"] },+ { label: "Updates available", count: "2", names: ["Acme Dormant", "Acme Updater"] },+ { label: "Active", count: "3", names: ["Acme Panel", "Acme Settings", "Long Identifier"] },+ { label: "Turned off", count: "1", names: ["Acme Off"] },+ ]),+ `groups: ${JSON.stringify(groups)}`,+ );+ check(+ cardByName("Acme Broken").querySelector(".plugins-row-error")?.textContent?.includes(+ "Manifest could not be read",+ ) === true,+ "broken error message missing",+ );++ step("rail");+ // --- Control rail: order and gating ----------------------------------+ const updaterRail = controlsOf(cardByName("Acme Updater"));+ check(+ updaterRail.length === 4 &&+ updaterRail[0].classList.contains("scope-control") &&+ updaterRail[1].classList.contains("btn-primary") &&+ updaterRail[1].textContent?.includes("Update to v1.2.3") === true &&+ updaterRail[2].getAttribute("aria-label") === "Plugin settings" &&+ updaterRail[3].classList.contains("plugins-menu-wrap"),+ `updater rail: ${updaterRail.map((node) => node.className).join(" | ")}`,+ );+ const panelRail = controlsOf(cardByName("Acme Panel"));+ check(+ panelRail.length === 3 &&+ panelRail[0].classList.contains("scope-control") &&+ panelRail[1].textContent?.includes("Open panel") === true &&+ panelRail[2].classList.contains("plugins-menu-wrap"),+ `panel rail: ${panelRail.map((node) => node.className).join(" | ")}`,+ );+ const settingsRail = controlsOf(cardByName("Acme Settings"));+ check(+ settingsRail.length === 3 &&+ settingsRail[1].getAttribute("aria-label") === "Plugin settings",+ `settings rail: ${settingsRail.map((node) => node.className).join(" | ")}`,+ );+ for (const name of ["Acme Dormant", "Acme Off"]) {+ const card = cardByName(name);+ const rail = controlsOf(card);+ check(card.querySelector(".btn-primary") === null, `${name} has a primary`);+ check(+ card.querySelector('[aria-label="Plugin settings"]') === null,+ `${name} has a settings icon`,+ );+ check(+ rail.length === 2 && rail[1].classList.contains("plugins-menu-wrap"),+ `${name} rail: ${rail.map((node) => node.className).join(" | ")}`,+ );+ check(+ card.querySelector(".plugins-row-controls")?.textContent?.includes("Open panel") === false,+ `${name} offered the panel action`,+ );+ }++ step("details");+ // --- Disclosure stays, and only when there is something to disclose ---+ const updaterDetails = cardByName("Acme Updater").querySelector<HTMLDetailsElement>(+ "details.plugins-row-details",+ );+ check(!!updaterDetails, "details disclosure missing");+ check(updaterDetails.open === false, "details started open");+ updaterDetails.querySelector("summary")!.click();+ check(updaterDetails.open === true, "details did not open");+ check(+ updaterDetails.querySelector(".plugins-row-details-body")?.textContent?.includes(+ "Capabilities",+ ) === true,+ "opened details missing the readout",+ );+ check(+ cardByName("Acme Settings").querySelector("details.plugins-row-details") === null,+ "a plugin with nothing to disclose grew a details section",+ );++ step("scope");+ // --- ScopeControl is real and first -----------------------------------+ const scopeTrigger = cardByName("Acme Updater").querySelector<HTMLButtonElement>(+ ".scope-compact-trigger",+ );+ check(!!scopeTrigger, "compact scope trigger missing");+ step("scope:open");+ scopeTrigger.click();+ await settle(() => !!maybe(".scope-compact-menu.is-open"), "scope menu");+ step("scope:menu");+ check(+ document.querySelectorAll('.scope-compact-menu.is-open [role="menuitemradio"]').length === 3,+ "scope menu does not offer the three choices",+ );+ const disableCalls: string[] = [];+ const scopes: Array<[string, unknown]> = [];+ Object.assign(api, {+ setPluginScope: async (id: string, scope: unknown) => {+ scopes.push([id, scope]);+ return { ok: true };+ },+ disablePlugin: async (id: string) => {+ disableCalls.push(id);+ return { ok: true };+ },+ });+ step("scope:choose");+ menuItemByText("Off").click();+ await settle(() => disableCalls.length === 1, "scope off recorded");+ check(disableCalls[0] === "acme.updater", `disable call: ${JSON.stringify(disableCalls)}`);+ await settle(() => !maybe(".scope-compact-menu.is-open"), "scope menu closed");++ // "Projects" is not the current state, so choosing it reaches the host+ // with the resolved scope.+ step("scope:projects");+ cardByName("Acme Updater")+ .querySelector<HTMLButtonElement>(".scope-compact-trigger")!+ .click();+ await settle(() => !!maybe(".scope-compact-menu.is-open"), "scope menu reopened");+ menuItemByText("Projects").click();+ await settle(() => scopes.length === 1, "scope choice recorded");+ check(+ scopes[0][0] === "acme.updater" &&+ JSON.stringify(scopes[0][1]) === JSON.stringify({ mode: "projects", projects: [] }),+ `scope call: ${JSON.stringify(scopes)}`,+ );++ step("meta");+ // --- Ratings meta adds no line, long ids truncate ----------------------+ const updaterCard = cardByName("Acme Updater");+ const meta = updaterCard.querySelector<HTMLElement>(".plugins-row-meta")!;+ const chip = meta.querySelector<HTMLElement>(".plugins-rating");+ check(!!chip, "rating chip missing from the meta line");+ const metaRect = meta.getBoundingClientRect();+ const chipRect = chip.getBoundingClientRect();+ check(+ chipRect.top >= metaRect.top - 1 && chipRect.bottom <= metaRect.bottom + 1,+ "rating chip wrapped onto its own line",+ );+ check(metaRect.height <= 24, `meta line grew: ${metaRect.height}`);+ check(+ cardByName("Acme Panel").querySelector(".plugins-rating") === null,+ "zero summary rendered a chip",+ );++ const longCard = cardByName("Long Identifier");+ const idElement = longCard.querySelector<HTMLElement>(".plugins-row-id")!;+ check(+ idElement.scrollWidth > idElement.clientWidth + 8,+ `long id was not truncated: ${idElement.scrollWidth}/${idElement.clientWidth}`,+ );+ check(+ idElement.getBoundingClientRect().right <= longCard.getBoundingClientRect().right + 0.5,+ "long id overflows the card",+ );++ step("grid");+ // --- Grid: 340px floor at width, min() fallback when narrower ---------+ const wideColumns = columnsOf(find(".plugins-list"));+ check(wideColumns.length >= 2, `wide host columns: ${wideColumns.join(",")}`);+ check(+ Math.min(...wideColumns) >= 340 - 1,+ `a wide column is under 340px: ${wideColumns.join(",")}`,+ );++ host.style.width = "300px";+ const narrowList = find(".plugins-list");+ const narrowColumns = columnsOf(narrowList);+ check(narrowColumns.length === 1, `narrow host columns: ${narrowColumns.join(",")}`);+ check(narrowColumns[0] <= 300, `narrow column overflows the host: ${narrowColumns[0]}`);+ check(+ narrowList.scrollWidth <= narrowList.clientWidth + 1,+ "grid overflows horizontally below 340px",+ );+ const narrowCard = cardByName("Acme Updater");+ const narrowCardRect = narrowCard.getBoundingClientRect();+ check(+ narrowCardRect.right <= narrowList.getBoundingClientRect().right + 0.5,+ "card overflows the narrow grid",+ );++ step("narrow");+ // --- Narrow rail wraps and stays usable -------------------------------+ const narrowControls = narrowCard.querySelector<HTMLElement>(".plugins-row-controls")!;+ check(+ narrowControls.scrollWidth <= narrowControls.clientWidth + 1,+ "control rail overflows the narrow card",+ );+ check(+ narrowControls.getBoundingClientRect().height > 40,+ `control rail did not wrap: ${narrowControls.getBoundingClientRect().height}`,+ );+ for (const control of [...narrowControls.children]) {+ const rect = control.getBoundingClientRect();+ check(+ rect.right <= narrowCardRect.right + 0.5 && rect.bottom <= narrowCardRect.bottom + 0.5,+ "a control sits outside the narrow card",+ );+ }++ root.unmount();+ host.remove();+ return "PASS: groups/members/error, rail order + disabled gating, disclosure, real scope menu, chip inline + long-id truncation, 340px grid floor + sub-340 fallback, narrow rail wrap";+ },++ installedGridActionsProbe: async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ const installs: Array<Record<string, unknown>> = [];+ const panels: string[] = [];+ const autoUpdates: Array<[string, boolean]> = [];+ const uninstalls: string[] = [];+ Object.assign(api, {+ ...pageMocks(),+ marketReviewSummaries: async () => ({}),+ marketInstall: async (input: Record<string, unknown>) => {+ installs.push(input);+ return { result: { plugin: installFixtures()[0], upgraded: true, permissionDiff: [] } };+ },+ openPluginPanel: async (id: string) => {+ panels.push(id);+ return { ok: true };+ },+ setPluginAutoUpdate: async (id: string, enabled: boolean) => {+ autoUpdates.push([id, enabled]);+ return { ok: true };+ },+ uninstallPlugin: async (id: string) => {+ uninstalls.push(id);+ return { ok: true };+ },+ });++ useAppStore.setState({ plugins: installFixtures() });+ usePluginBrowseState.setState({ tab: "installed", installedQuery: "" });+ const { host, root } = mountProbe();+ step("mount");+ await settle(() => !!maybe(".plugins-list"), "installed grid");++ // --- Update carries the updating version into the install -------------+ const updaterCard = cardByName("Acme Updater");+ updaterCard.querySelector<HTMLButtonElement>(".btn-primary")!.click();+ await settle(() => !!maybe(".plugins-modal"), "permission dialog");+ const permissionDialog = [...document.querySelectorAll<HTMLElement>(".plugins-modal")].find(+ (node) => node.textContent?.includes("Install Acme Updater?"),+ );+ check(!!permissionDialog, "permission dialog missing");+ check(+ permissionDialog!.textContent?.includes("v1.2.3") === true,+ "permission dialog does not name the target version",+ );+ permissionDialog!.querySelector<HTMLButtonElement>(".plugins-modal-actions .btn-primary")!.click();+ await settle(() => installs.length === 1, "marketInstall recorded");+ check(+ installs[0].id === "acme.updater" &&+ installs[0].version === "1.2.3" &&+ installs[0].enable === true &&+ installs[0].autoUpdate === true,+ `install call: ${JSON.stringify(installs[0])}`,+ );+ await settle(() => !maybe(".plugins-install-modal"), "install dialog stepped aside");++ // --- Open panel names the plugin ---------------------------------------+ cardByName("Acme Panel")+ .querySelector<HTMLButtonElement>(".plugins-row-controls .btn-secondary")!+ .click();+ await settle(() => panels.length === 1, "openPluginPanel recorded");+ check(panels[0] === "acme.panel", `panel call: ${JSON.stringify(panels)}`);++ // --- Settings opens only where declared --------------------------------+ cardByName("Acme Updater")+ .querySelector<HTMLButtonElement>('[aria-label="Plugin settings"]')!+ .click();+ await settle(() => !!maybe(".plugins-settings-modal"), "settings sheet");+ check(+ find(".plugins-settings-modal").textContent?.includes("Acme Updater settings") === true,+ "settings sheet title missing",+ );+ find<HTMLButtonElement>('[aria-label="Close plugin settings"]').click();+ await settle(() => !maybe(".plugins-settings-modal"), "settings sheet closed");++ // --- Overflow: auto-update toggle, uninstall, and no uninstall for a+ // bundled plugin ------------------------------------------------------+ updaterCard.querySelector<HTMLButtonElement>('[aria-label="Actions for Acme Updater"]')!.click();+ await settle(() => !!maybe(".plugins-menu.is-open"), "row menu");+ menuItemByText("Disable auto-update").click();+ await settle(() => autoUpdates.length === 1, "auto-update recorded");+ check(+ autoUpdates[0][0] === "acme.updater" && autoUpdates[0][1] === false,+ `auto-update call: ${JSON.stringify(autoUpdates)}`,+ );++ await settle(() => !maybe(".plugins-menu.is-open"), "row menu closed");+ cardByName("Acme Updater")+ .querySelector<HTMLButtonElement>('[aria-label="Actions for Acme Updater"]')!+ .click();+ await settle(() => !!maybe(".plugins-menu.is-open"), "row menu reopened");+ menuItemByText("Uninstall").click();+ await settle(() => uninstalls.length === 1, "uninstall recorded");+ check(uninstalls[0] === "acme.updater", `uninstall call: ${JSON.stringify(uninstalls)}`);++ root.unmount();+ host.remove();+ return "PASS: update->permission->marketInstall(v1.2.3), panel id, settings sheet opens/closes, overflow auto-update false + uninstall";+ },+});++function Probe() {+ const model = usePluginsPage();+ return (+ <>+ <InstalledPluginsPanel {...model} />+ <PluginDialogs {...model} />+ </>+ );+}diff --git a/scripts/e2e/plugin-detail-focus.tsx b/scripts/e2e/plugin-detail-focus.tsxindex ae151b1aa..b5f716709 100644--- a/scripts/e2e/plugin-detail-focus.tsx+++ b/scripts/e2e/plugin-detail-focus.tsx@@ -36,6 +36,9 @@ Object.assign(globalThis, { pluginDetailFocusProbe: async () => {listProjects: async () => ({ projects: [] }), listPlugins: async () => ({ plugins: [] }),listPluginServices: async () => [], marketCheckUpdates: async () => ({}),marketSearch: async () => ({ plugins: [plugin] }), marketGetDetail: async () => ({ plugin }),+ // The page batches public rating summaries for every id it can show; the+ // fixture answers with none, which reads as "no chip".+ marketReviewSummaries: async () => ({}),onPluginChanged: () => () => {}, onPluginInstallProgress: () => () => {},});usePluginBrowseState.setState({ tab: "market" });diff --git a/scripts/e2e/plugin-reviews-drawer.tsx b/scripts/e2e/plugin-reviews-drawer.tsxnew file mode 100644index 000000000..acd68526e--- /dev/null+++ b/scripts/e2e/plugin-reviews-drawer.tsx@@ -0,0 +1,718 @@+/**+ * The public review drawer, driven through the real components in Chromium.+ *+ * Only the IPC boundary is fixtured (`api`); the page hook, the detail sheet,+ * the summary block, the drawer, its filters, paging, error/retry, the write+ * link, focus trapping and Escape are the shipping implementations. Runs+ * headless through `scripts/e2e-plugin-reviews-drawer.mjs`; returns a PASS+ * summary the harness prints.+ */+import React from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import i18n from "i18next";+import { I18nextProvider } from "react-i18next";+import { en } from "../../packages/i18n/src/index";+import { api } from "../../apps/desktop/src/lib/api";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";+import { usePluginsPage } from "../../apps/desktop/src/features/plugins/usePluginsPage";+import { MarketplacePanel } from "../../apps/desktop/src/features/plugins/MarketplacePanel";+import { PluginDetailSheet } from "../../apps/desktop/src/features/plugins/PluginDetailSheet";+import { usePluginBrowseState } from "../../apps/desktop/src/features/plugins/browse-state";++const check = (ok: boolean, label: string) => {+ if (!ok) throw new Error(label);+};+const find = <T extends HTMLElement = HTMLElement>(selector: string): T => {+ const node = document.querySelector<T>(selector);+ if (!node) throw new Error(`Missing ${selector}`);+ return node;+};+const maybe = <T extends HTMLElement = HTMLElement>(selector: string): T | null =>+ document.querySelector<T>(selector);+const settle = async (predicate: () => boolean, label: string) => {+ for (let frame = 0; frame < 240; frame++) {+ if (predicate()) return;+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ }+ throw new Error(`Did not settle: ${label}`);+};+const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));+const texts = (selector: string) =>+ [...document.querySelectorAll<HTMLElement>(selector)].map((node) => node.textContent ?? "");++/** Marks the phase a hung probe stopped in; the harness reports it. */+const step = (name: string) => {+ (globalThis as Record<string, unknown>).__probeStep = name;+};++const cardByName = (name: string) =>+ [...document.querySelectorAll<HTMLElement>(".plugins-card")].find(+ (card) => card.querySelector(".plugins-card-name")?.textContent === name,+ )!;++const REVIEW_URL = "https://centre.example.test/plugins/test.focus#reviews";+const OPEN_FAILURE = "open refused by the system browser";++type ReviewCall = { pluginId: string; sentiment?: string; sort?: string; cursor?: string };++const summary = {+ pluginId: "test.focus",+ ratingAvg: 4.5,+ ratingCount: 3,+ ratingDist: [0, 0, 1, 0, 2],+ positiveCount: 2,+ neutralCount: 1,+ negativeCount: 0,+};++const review = (id: string, body: string, overrides: Record<string, unknown> = {}) => ({+ id,+ pluginId: "test.focus",+ authorName: "Ada",+ ratingHalfStars: 9,+ body,+ status: "visible",+ pluginVersion: "1.2.0",+ helpfulCount: 1,+ createdAt: "2026-10-01T00:00:00Z",+ updatedAt: "2026-10-01T00:00:00Z",+ editedAt: null,+ ...overrides,+});++const plugin = {+ id: "test.focus",+ name: "Focus test",+ // Long enough that the ratings summary sits below the sheet's first+ // screen, so "scroll preserved" is a measurable claim.+ description: "A test marketplace card used by the drawer fixture. ".repeat(60),+ author: "Test",+ latestVersion: "1.0.0",+ updatedAt: "2026-09-01T00:00:00Z",+ permissionSummary: [],+ categories: [],+ versions: [],+ permissions: [],+ readmeMarkdown: `# Long readme\n\n${"A line of readme content.\n\n".repeat(120)}`,+};++/** The page-agnostic IPC mocks shared by every probe. */+const pageMocks = () => ({+ listProjects: async () => ({ projects: [] }),+ listPlugins: async () => ({ plugins: [] }),+ listPluginServices: async () => [],+ marketCheckUpdates: async () => ({}),+ marketSearch: async () => ({ plugins: [plugin] }),+ marketGetDetail: async () => ({ plugin }),+ onPluginChanged: () => () => {},+ onPluginInstallProgress: () => () => {},+});++function mountProbe() {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ flushSync(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <Probe />+ </I18nextProvider>,+ ),+ );+ return { container, root };+}++Object.assign(globalThis, {+ pluginReviewsDrawerProbe: async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });++ const reviewCalls: ReviewCall[] = [];+ const opened: string[] = [];+ let failNegativeOnce = false;+ let failOpenOnce = false;++ // Fixture only the IPC boundary; the hook, sheet, drawer and focus logic+ // are real. "all" is slow on purpose so a filter switch can outrun it.+ Object.assign(api, {+ listProjects: async () => ({ projects: [] }),+ listPlugins: async () => ({ plugins: [] }),+ listPluginServices: async () => [],+ marketCheckUpdates: async () => ({}),+ marketSearch: async () => ({ plugins: [plugin] }),+ marketGetDetail: async () => ({ plugin }),+ marketReviewSummaries: async () => ({ "test.focus": summary }),+ marketReviews: async (query: ReviewCall) => {+ reviewCalls.push(query);+ if (query.sentiment === "all") await delay(250);+ if (query.sentiment === "negative" && failNegativeOnce) {+ failNegativeOnce = false;+ throw new Error("centre unavailable");+ }+ if (query.sentiment === "positive") {+ return {+ reviews: [review("p1", "positive only", { ratingHalfStars: 10 })],+ nextCursor: null,+ summary,+ reviewUrl: REVIEW_URL,+ };+ }+ if (query.sentiment === "negative") {+ return {+ reviews: [review("n1", "negative only", { ratingHalfStars: 3 })],+ nextCursor: null,+ summary,+ reviewUrl: REVIEW_URL,+ };+ }+ if (query.cursor === "c1") {+ // A stable keyset cursor can repeat a row the user has seen; the+ // drawer must deduplicate by id.+ return {+ reviews: [review("r1", "first"), review("r2", "second"), review("r3", "third")],+ nextCursor: null,+ summary,+ reviewUrl: REVIEW_URL,+ };+ }+ return {+ reviews: [review("r1", "first")],+ nextCursor: "c1",+ summary,+ reviewUrl: REVIEW_URL,+ };+ },+ browserOpenExternal: async (url?: string) => {+ if (failOpenOnce) {+ failOpenOnce = false;+ throw new Error(OPEN_FAILURE);+ }+ opened.push(String(url));+ return { ok: true };+ },+ onPluginChanged: () => () => {},+ onPluginInstallProgress: () => () => {},+ });++ usePluginBrowseState.setState({ tab: "market" });+ const { container, root } = mountProbe();++ // --- Card chip + summary in the detail sheet -------------------------+ await settle(() => !!maybe(".plugins-card-hit"), "marketplace card");+ await settle(() => !!maybe(".plugins-rating"), "card rating chip");+ const chip = find(".plugins-rating");+ check(+ chip.getAttribute("aria-label") === "Rated 4.5 out of 5 from 3 ratings",+ `rating chip aria-label: ${chip.getAttribute("aria-label")}`,+ );+ check(chip.textContent?.includes("4.5 (3)") === true, `rating chip text: ${chip.textContent}`);++ find(".plugins-card-hit").click();+ await settle(() => !!maybe(".plugins-sheet"), "detail sheet");+ await settle(+ () => texts(".plugins-sheet-section-title").includes("Ratings & reviews"),+ "ratings summary section",+ );+ const sections = texts(".plugins-sheet-section-title");+ const order = ["Permissions", "Ratings & reviews", "Versions"].map((title) =>+ sections.findIndex((text) => text.includes(title)),+ );+ check(+ order[0] >= 0 && order[0] < order[1] && order[1] < order[2],+ `section order: ${sections.join(" | ")}`,+ );+ check(!!maybe(".plugins-reviews-summary"), "summary block missing");+ check(!!maybe(".plugins-reviews-dist"), "sentiment distribution missing");++ const sheetBody = find(".plugins-sheet-body");++ // --- Open the drawer --------------------------------------------------+ const opener = find<HTMLButtonElement>(".plugins-sheet-reviews-action button");+ // Put the opener on screen with the sheet scrolled, so "position+ // preserved" is a measurable claim rather than a no-op.+ const bodyRect = sheetBody.getBoundingClientRect();+ const openerRect = opener.getBoundingClientRect();+ if (openerRect.bottom > bodyRect.bottom - 8) {+ sheetBody.scrollTop += openerRect.bottom - (bodyRect.bottom - 56);+ } else if (openerRect.top < bodyRect.top + 8) {+ sheetBody.scrollTop -= bodyRect.top + 56 - openerRect.top;+ }+ check(sheetBody.scrollTop > 0, "detail sheet did not scroll");+ const settledOpener = opener.getBoundingClientRect();+ check(+ settledOpener.top >= bodyRect.top && settledOpener.bottom <= bodyRect.bottom,+ "opener is not on screen for the user path",+ );+ const preservedScroll = sheetBody.scrollTop;+ opener.focus();+ opener.click();+ await settle(() => !!maybe(".plugins-reviews"), "review drawer");+ const drawer = find(".plugins-reviews");+ check(document.activeElement === drawer, "drawer did not take initial focus");+ check(find(".plugins-sheet").inert === true, "detail sheet not inert behind the drawer");+ check(find(".plugins-sheet-scrim").inert === true, "sheet scrim not inert behind the drawer");+ // An inert surface refuses focus, so the covered sheet is unreachable.+ const sheetButton = find<HTMLButtonElement>(".plugins-sheet .plugins-icon-btn");+ sheetButton.focus();+ check(document.activeElement !== sheetButton, "inert detail sheet accepted focus");++ // --- Focus trap -------------------------------------------------------+ const focusables = [+ ...drawer.querySelectorAll<HTMLElement>(+ 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])',+ ),+ ];+ check(focusables.length >= 4, `expected several focusables, saw ${focusables.length}`);+ const first = focusables[0];+ const last = focusables[focusables.length - 1];+ last.focus();+ const forward = new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true });+ const forwardCarried = document.dispatchEvent(forward);+ check(forwardCarried === false, "Tab was not prevented at the drawer edge");+ check(document.activeElement === first, "Tab did not wrap to the first control");+ first.focus();+ const backward = new KeyboardEvent("keydown", {+ key: "Tab",+ shiftKey: true,+ bubbles: true,+ cancelable: true,+ });+ const backwardCarried = document.dispatchEvent(backward);+ check(backwardCarried === false, "Shift+Tab was not prevented at the drawer edge");+ check(document.activeElement === last, "Shift+Tab did not wrap to the last control");++ // --- First page, paging and dedup -------------------------------------+ await settle(+ () => texts(".plugins-review-body").includes("first"),+ "first review page",+ );+ check(+ find(".plugins-review-meta").textContent?.includes("User-reported version v1.2.0") === true,+ `version label: ${find(".plugins-review-meta").textContent}`,+ );+ find(".plugins-reviews-more button").click();+ await settle(() => texts(".plugins-review-body").includes("third"), "second review page");+ const bodies = texts(".plugins-review-body");+ check(+ bodies.length === 3 && bodies[0] === "first" && bodies[1] === "second" && bodies[2] === "third",+ `deduplicated rows: ${bodies.join(" | ")}`,+ );+ check(!maybe(".plugins-reviews-more"), "load more survived the last page");++ // --- Filter switch wins over a slow earlier answer --------------------+ const filterButton = (label: string) =>+ [...drawer.querySelectorAll<HTMLButtonElement>(".plugins-reviews-filters button")].find(+ (button) => button.textContent === label,+ )!;+ // Land on Positive first, then start the slow "All" query and outrun it+ // with another Positive switch before it answers.+ filterButton("Positive").click();+ await settle(+ () => texts(".plugins-review-body").includes("positive only"),+ "positive filter applied",+ );+ filterButton("All").click();+ await delay(30);+ filterButton("Positive").click();+ await settle(+ () => texts(".plugins-review-body").includes("positive only"),+ "positive filter re-applied",+ );+ await delay(400);+ const afterStale = texts(".plugins-review-body");+ check(+ afterStale.includes("positive only") && !afterStale.includes("first"),+ `stale answer reached the list: ${afterStale.join(" | ")}`,+ );+ const positiveCall = reviewCalls.find((call) => call.sentiment === "positive");+ check(+ positiveCall?.cursor === undefined && positiveCall?.sort === "newest",+ `positive first page query: ${JSON.stringify(positiveCall)}`,+ );++ // --- Error, alert, retry ---------------------------------------------+ failNegativeOnce = true;+ filterButton("Negative").click();+ await settle(() => !!maybe(".plugins-reviews-state[role='alert']"), "load error alert");+ check(+ find(".plugins-reviews-state[role='alert']").textContent?.includes("Couldn't load reviews.") ===+ true,+ "load error copy missing",+ );+ find(".plugins-reviews-state[role='alert'] button").click();+ await settle(+ () => texts(".plugins-review-body").includes("negative only"),+ "retry recovered the list",+ );++ // --- Write link: real anchor, page URL wins, middle-click only --------+ const write = find<HTMLAnchorElement>(".plugins-reviews-write");+ check(write.href === REVIEW_URL, `write link href: ${write.href}`);+ write.click();+ check(opened.length === 1 && opened[0] === REVIEW_URL, `open calls: ${JSON.stringify(opened)}`);+ const middle = new MouseEvent("auxclick", { button: 1, bubbles: true, cancelable: true });+ const middleCarried = write.dispatchEvent(middle);+ check(middleCarried === false, "middle-click was not prevented");+ check(opened.length === 2, "middle-click did not open the centre page");+ write.dispatchEvent(new MouseEvent("auxclick", { button: 2, bubbles: true, cancelable: true }));+ check(opened.length === 2, "right-click opened the centre page");+ failOpenOnce = true;+ const toastsBefore = useAppStore.getState().toasts.length;+ write.click();+ await settle(+ () =>+ useAppStore+ .getState()+ .toasts.some((toast) => toast.message === OPEN_FAILURE),+ "open failure toast",+ );+ check(useAppStore.getState().toasts.length > toastsBefore, "toast not appended");++ // --- Escape: top layer only, restore focus and position ---------------+ const escape = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });+ const escapeCarried = document.dispatchEvent(escape);+ check(escapeCarried === false, "Escape was not prevented");+ await settle(() => !maybe(".plugins-reviews"), "drawer closed by Escape");+ check(!!maybe(".plugins-sheet"), "Escape closed the detail sheet too");+ check(find(".plugins-sheet").inert === false, "detail sheet stayed inert after the drawer");+ check(document.activeElement === opener, "focus did not return to the opener");+ check(+ find(".plugins-sheet-body").scrollTop === preservedScroll,+ `sheet scroll moved: ${find(".plugins-sheet-body").scrollTop} vs ${preservedScroll}`,+ );++ root.unmount();+ container.remove();+ return "PASS: chip+summary order, drawer paging/dedup, filter stale-drop, error+retry, link (middle-only, href, failure toast), Tab trap + inert, Escape/focus/scroll restore";+ },++ pluginReviewsStaleSummaryProbe: async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ let summaryCalls = 0;+ let omitSummaries = false;+ Object.assign(api, {+ ...pageMocks(),+ // The first batch answers the id; once `omitSummaries` flips, the+ // answer drops it the way the centre drops an archived plugin.+ marketReviewSummaries: async () => {+ summaryCalls += 1;+ return omitSummaries ? {} : { "test.focus": summary };+ },+ marketReviews: async () => ({+ reviews: [],+ nextCursor: null,+ summary,+ reviewUrl: REVIEW_URL,+ }),+ });++ usePluginBrowseState.setState({ tab: "market", query: "" });+ const { container, root } = mountProbe();+ await settle(() => !!maybe(".plugins-card-hit"), "stale probe: card");+ await settle(() => !!maybe(".plugins-rating"), "stale probe: first rating chip");+ check(summaryCalls >= 1, "stale probe: no summaries batch ran");++ // Any marketplace refresh asks again with the full id set; the second+ // answer omits the plugin, so its rating must stop rendering.+ const callsBefore = summaryCalls;+ omitSummaries = true;+ usePluginBrowseState.setState({ query: "focus" });+ await settle(() => summaryCalls > callsBefore, "stale probe: second summaries batch");+ await settle(() => !maybe(".plugins-rating"), "stale probe: stale chip survived");++ root.unmount();+ container.remove();+ return "PASS: a summaries success that omits a requested id removes its stale rating chip";+ },++ pluginReviewsUnavailableSummaryProbe: async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ let summaryCalls = 0;+ let reviewsFailOnce = true;+ Object.assign(api, {+ ...pageMocks(),+ marketReviewSummaries: async () => {+ summaryCalls += 1;+ throw new Error("centre unavailable");+ },+ marketReviews: async () => {+ if (reviewsFailOnce) {+ reviewsFailOnce = false;+ throw new Error("centre unavailable");+ }+ return {+ reviews: [review("f1", "fallback works")],+ nextCursor: null,+ summary,+ reviewUrl: REVIEW_URL,+ };+ },+ });++ usePluginBrowseState.setState({ tab: "market", query: "" });+ const { container, root } = mountProbe();+ await settle(() => !!maybe(".plugins-card-hit"), "unavailable probe: card");+ await settle(() => summaryCalls >= 1, "unavailable probe: summaries attempt");+ check(!maybe(".plugins-rating"), "unavailable probe: chip rendered without a summary");++ find(".plugins-card-hit").click();+ await settle(() => !!maybe(".plugins-sheet"), "unavailable probe: detail sheet");+ const ratingsSection = () =>+ [...document.querySelectorAll<HTMLElement>(".plugins-sheet-section")].find(+ (node) =>+ node+ .querySelector(".plugins-sheet-section-title")+ ?.textContent?.includes("Ratings & reviews") ?? false,+ );+ await settle(() => !!ratingsSection(), "unavailable probe: ratings section");+ check(+ ratingsSection()?.textContent?.includes("Ratings aren't available from this source.") ===+ true,+ `unavailable probe: copy missing: ${ratingsSection()?.textContent}`,+ );+ const opener = ratingsSection()?.querySelector<HTMLButtonElement>(+ ".plugins-sheet-reviews-action button",+ );+ check(!!opener, "unavailable probe: drawer entry missing without a summary");+ opener.click();++ await settle(() => !!maybe(".plugins-reviews"), "unavailable probe: drawer");+ await settle(+ () => !!maybe(".plugins-reviews-state[role='alert']"),+ "unavailable probe: drawer retry state",+ );+ const composer = find<HTMLTextAreaElement>(".plugins-reviews-composer-field");+ check(composer.disabled === true, "unavailable probe: composer is not disabled");+ const fallbackWrite = find<HTMLAnchorElement>(".plugins-reviews-write");+ check(+ fallbackWrite.href === "https://plugins.aiuo.net/plugins/test.focus#reviews",+ `unavailable probe: fallback write link: ${fallbackWrite.href}`,+ );++ // The retry recovers the independent list, and the host's page URL takes+ // over from the fallback.+ find(".plugins-reviews-state[role='alert'] button").click();+ await settle(+ () => texts(".plugins-review-body").includes("fallback works"),+ "unavailable probe: retry recovered the list",+ );+ check(+ find<HTMLAnchorElement>(".plugins-reviews-write").href === REVIEW_URL,+ "unavailable probe: page URL did not replace the fallback",+ );++ root.unmount();+ container.remove();+ return "PASS: unavailable summary keeps the drawer entry; retry recovers the list and the fallback web link stays";+ },++ pluginReviewsNarrowDrawerProbe: async () => {+ step("narrow:init");+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ // Enough rows to make the drawer body scroll at a narrow viewport.+ const manyReviews = Array.from({ length: 14 }, (_, index) =>+ review(`r${index + 1}`, `Review body number ${index + 1}, long enough to occupy a line.`),+ );+ Object.assign(api, {+ ...pageMocks(),+ marketReviewSummaries: async () => ({ "test.focus": summary }),+ marketReviews: async () => ({+ reviews: manyReviews,+ nextCursor: null,+ summary,+ reviewUrl: REVIEW_URL,+ }),+ });++ usePluginBrowseState.setState({ tab: "market", query: "" });+ step("narrow:render");+ const { container, root } = mountProbe();+ await settle(() => !!maybe(".plugins-card-hit"), "narrow probe: card");+ find(".plugins-card-hit").click();+ await settle(() => !!maybe(".plugins-sheet-reviews-action button"), "narrow probe: opener");+ find(".plugins-sheet-reviews-action button").click();+ await settle(() => !!maybe(".plugins-reviews"), "narrow probe: drawer");++ step("narrow:geometry");+ const viewport = window.innerWidth;+ check(viewport <= 375, `viewport is not narrow: ${viewport}`);+ const drawer = find(".plugins-reviews");+ const drawerRect = drawer.getBoundingClientRect();+ check(+ drawerRect.left >= -0.5 && drawerRect.right <= viewport + 0.5 && drawerRect.width <= viewport,+ `drawer outside the viewport: ${JSON.stringify(drawerRect)} parent ${JSON.stringify(drawer.parentElement!.getBoundingClientRect())} viewport ${viewport}`,+ );+ check(+ document.documentElement.scrollWidth <= viewport + 1,+ `page overflows horizontally: ${document.documentElement.scrollWidth} > ${viewport}`,+ );+ const body = find(".plugins-reviews-body");+ check(body.scrollWidth <= body.clientWidth + 1, "drawer body overflows horizontally");++ step("narrow:controls");+ const controls = [+ ...document.querySelectorAll<HTMLElement>(".plugins-reviews-filters button"),+ ...document.querySelectorAll<HTMLElement>(".plugins-reviews-head button"),+ find(".plugins-reviews-write"),+ ];+ check(controls.length >= 7, `expected filter/sort/close/link controls, saw ${controls.length}`);+ for (const control of controls) {+ const rect = control.getBoundingClientRect();+ check(+ rect.left >= drawerRect.left - 0.5 && rect.right <= drawerRect.right + 0.5,+ `control outside the drawer: ${control.className || control.getAttribute("aria-label")}`,+ );+ }+ const filterByText = (text: string) =>+ [...document.querySelectorAll<HTMLButtonElement>(".plugins-reviews-filters button")].find(+ (button) => button.textContent === text,+ )!;+ filterByText("Positive").click();+ await settle(+ () => filterByText("Positive").getAttribute("aria-pressed") === "true",+ "narrow probe: filter usable",+ );+ filterByText("Most helpful").click();+ await settle(+ () => filterByText("Most helpful").getAttribute("aria-pressed") === "true",+ "narrow probe: sort usable",+ );++ step("narrow:scroll");+ check(body.scrollHeight > body.clientHeight, "drawer body does not scroll");+ body.scrollTop = 120;+ check(body.scrollTop > 0, "drawer body did not scroll");+ const composerRect = find(".plugins-reviews-composer").getBoundingClientRect();+ check(+ composerRect.bottom <= window.innerHeight + 0.5 && composerRect.top >= -0.5,+ `composer is not pinned inside the viewport: ${JSON.stringify(composerRect)}`,+ );++ const opened: string[] = [];+ Object.assign(api, {+ browserOpenExternal: async (url?: string) => {+ opened.push(String(url));+ return { ok: true };+ },+ });+ find<HTMLAnchorElement>(".plugins-reviews-write").click();+ check(opened.length === 1 && opened[0] === REVIEW_URL, `write link: ${JSON.stringify(opened)}`);++ step("narrow:close");+ const close = [...document.querySelectorAll<HTMLButtonElement>(".plugins-reviews-head button")].find(+ (button) => button.getAttribute("aria-label") === "Close reviews",+ )!;+ check(!!close, "close button missing");+ close.click();+ await settle(() => !maybe(".plugins-reviews"), "narrow probe: drawer closed");+ check(!!maybe(".plugins-sheet"), "closing the drawer closed the sheet");++ root.unmount();+ container.remove();+ return "PASS: at a narrow viewport the drawer stays inside it with no horizontal overflow; filters, sort, close and the write link are all usable; the body scrolls and the composer stays pinned";+ },++ pluginReviewsBatchProbe: async () => {+ step("batch:init");+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ const otherPlugin = { ...plugin, id: "other.plugin", name: "Other Plugin" };+ const freshPlugin = { ...plugin, id: "fresh.plugin", name: "Fresh Plugin" };+ let summariesCalls = 0;+ let lastIds: string[] = [];+ let releaseStale: (() => void) | null = null;+ const staleGate = new Promise<void>((resolve) => {+ releaseStale = resolve;+ });+ Object.assign(api, {+ ...pageMocks(),+ // An empty query shows one plugin; a typed query shows two. The summary+ // batch for the first market list is held back so it can only land after+ // the batch for the final list.+ marketSearch: async (query?: string) => ({+ plugins: String(query ?? "").trim() ? [freshPlugin, otherPlugin] : [otherPlugin],+ }),+ marketReviewSummaries: async (ids: string[]) => {+ summariesCalls += 1;+ lastIds = [...ids];+ if (summariesCalls === 1) {+ await staleGate;+ // The abandoned query's answer would paint a chip for a plugin the+ // final batch no longer rates.+ return { "other.plugin": summary };+ }+ return { "fresh.plugin": summary };+ },+ marketReviews: async () => ({+ reviews: [],+ nextCursor: null,+ summary,+ reviewUrl: REVIEW_URL,+ }),+ });++ usePluginBrowseState.setState({ tab: "market", query: "" });+ step("batch:render");+ const { container, root } = mountProbe();+ await settle(() => !!maybe(".plugins-card-hit"), "batch probe: first market list");+ await settle(() => summariesCalls >= 1, "batch probe: first summaries batch");+ check(+ texts(".plugins-card-name").join("|") === "Other Plugin",+ `first list: ${texts(".plugins-card-name").join("|")}`,+ );++ // Typing settles on the fresh query: same behavior as the debounced+ // search, asserted as stable content rather than a fixed delay.+ step("batch:type");+ usePluginBrowseState.setState({ query: "fr" });+ await settle(+ () => texts(".plugins-card-name").join("|") === "Fresh Plugin|Other Plugin",+ "batch probe: fresh query rendered",+ );+ await settle(() => !!maybe(".plugins-rating"), "batch probe: fresh chip");+ check(+ find(".plugins-rating").textContent?.includes("4.5 (3)") === true,+ `fresh chip text: ${find(".plugins-rating").textContent}`,+ );+ check(+ cardByName("Other Plugin").querySelector(".plugins-rating") === null,+ "other plugin rendered a chip the final batch did not rate",+ );+ check(+ JSON.stringify([...lastIds].sort()) === JSON.stringify(["fresh.plugin", "other.plugin"]),+ `final batch ids: ${JSON.stringify(lastIds)}`,+ );++ step("batch:release");+ releaseStale?.();+ await delay(250);+ // The late answer for the left-behind id paints nothing: the fresh chip+ // stays and the stale rating never appears on the visible card.+ check(!!maybe(".plugins-rating"), "fresh chip lost after the stale answer landed");+ check(+ find(".plugins-rating").textContent?.includes("4.5 (3)") === true,+ "fresh chip changed after the stale answer landed",+ );+ check(+ cardByName("Other Plugin").querySelector(".plugins-rating") === null,+ "a late summaries answer for an abandoned query painted a chip",+ );+ check(+ JSON.stringify(texts(".plugins-card-name")) === JSON.stringify(["Fresh Plugin", "Other Plugin"]),+ `cards after settling: ${texts(".plugins-card-name").join("|")}`,+ );++ root.unmount();+ container.remove();+ return "PASS: the final summaries batch carries exactly the displayed ids, and a late answer for an abandoned query is discarded";+ },+});++function Probe() {+ const model = usePluginsPage();+ return (+ <>+ <MarketplacePanel {...model} />+ <PluginDetailSheet {...model} />+ </>+ );+}