Skip to content

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

feat(plugins): add the official channel with backups and install progress

Tioit-Wang56c5b6ee0a55
diff --git a/apps/desktop/electron/main/ipc/market-ipc.ts b/apps/desktop/electron/main/ipc/market-ipc.ts
index 758718ef4..cb8550c1e 100644
--- a/apps/desktop/electron/main/ipc/market-ipc.ts
+++ b/apps/desktop/electron/main/ipc/market-ipc.ts
@@ -95,6 +95,14 @@ export function registerMarketIpc({
return applied;
});
+ handle(IPC.invoke.marketCancelInstall, async (payload: { id: string }) => {
+ if (!host) throw new Error("host unavailable");
+ // The host answers whether an install was actually running: only a
+ // download can be interrupted, and the surface says so rather than
+ // assuming the click did something.
+ return host.call<{ cancelled: boolean; id: string }>("market.cancelInstall", payload);
+ });
+
handle(IPC.invoke.commandPaletteSearch, async (query: string) => {
const q = (query || "").toLowerCase();
const builtin = builtinPaletteItems();
diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.ts
index 58e7b76f0..78472f297 100644
--- a/apps/desktop/electron/main/runtime/host.ts
+++ b/apps/desktop/electron/main/runtime/host.ts
@@ -76,6 +76,13 @@ export function createHostRuntime({
// Notifications from a previous host generation must never reach the
// current plugin/renderer bridge after a restart.
if (runtimeState.host !== h) return;
+ // An install reports itself, so the dialog that shows it can follow the
+ // phases, the mirror being tried and the bytes that have arrived. Nothing
+ // here decides anything: the request's own answer is still the outcome.
+ if (method === "plugin.installProgress") {
+ sendToRenderer(IPC.event.pluginInstallProgress, params);
+ return;
+ }
if (method === "permissions.request") {
const permission = params as {
requestId: string;
diff --git a/apps/desktop/src/components/plugins/MarketplaceSourceSettings.tsx b/apps/desktop/src/components/plugins/MarketplaceSourceSettings.tsx
index 6a0b87759..db890ec6b 100644
--- a/apps/desktop/src/components/plugins/MarketplaceSourceSettings.tsx
+++ b/apps/desktop/src/components/plugins/MarketplaceSourceSettings.tsx
@@ -76,6 +76,7 @@ export function MarketplaceSourceSettings({
}
options={[
{ id: "official", label: t("settings.marketProviderOfficial") },
+ { id: "github", label: t("settings.marketProviderGithub") },
{ id: "mirror", label: t("settings.marketProviderMirror") },
{ id: "custom", label: t("settings.marketProviderCustom") },
]}
diff --git a/apps/desktop/src/components/plugins/PluginInstallDialog.tsx b/apps/desktop/src/components/plugins/PluginInstallDialog.tsx
new file mode 100644
index 000000000..c2a1a4d6d
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginInstallDialog.tsx
@@ -0,0 +1,257 @@
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ canCancelInstall,
+ formatTransfer,
+ type PluginInstallJob,
+} from "../../features/plugins/install-progress";
+import { useAppStore } from "../../stores/app-store";
+import { Button, cx } from "../ui";
+import {
+ IconCircleCheck,
+ IconCopy,
+ IconDownload,
+ IconRefresh,
+ IconTriangleAlert,
+} from "../icons";
+
+/** How long a finished install is shown before it closes itself. */
+const SUCCESS_DWELL_MS = 2000;
+
+const PHASE_KEYS: Record<PluginInstallJob["phase"], string> = {
+ resolve: "plugins.installPhase.resolve",
+ download: "plugins.installPhase.download",
+ verify: "plugins.installPhase.verify",
+ install: "plugins.installPhase.install",
+ enable: "plugins.installPhase.enable",
+};
+
+type Props = {
+ job: PluginInstallJob;
+ onCancel: () => Promise<void> | void;
+ onRetry: () => Promise<void> | void;
+ onClose: () => void;
+};
+
+/**
+ * The one dialog a manual install or update runs behind.
+ *
+ * It is opened by the confirmed permission review and then follows what the
+ * host reports: the phase it is in, the mirror it is trying, the bytes that
+ * arrived. Cancelling is offered only while a download can still be stopped;
+ * a failure stays on screen with the mirrors it tried and the option to run
+ * the same request again; a success shows and steps aside.
+ */
+export function PluginInstallDialog({ job, onCancel, onRetry, onClose }: Props) {
+ const { t } = useTranslation();
+ const showToast = useAppStore((state) => state.showToast);
+ const [hovered, setHovered] = useState(false);
+ /**
+ * The page hands these callbacks in fresh on every progress report, so the
+ * timer and the key listener read them through a ref instead of restarting.
+ */
+ const closeRef = useRef(onClose);
+
+ useEffect(() => {
+ closeRef.current = onClose;
+ }, [onClose]);
+
+ const stoppable = canCancelInstall(job);
+ const running = job.status === "running";
+ // Escape obeys the same rule the cancel button does: a download is not
+ // dismissed by accident, a finished install is.
+ const escapeLocked = running && (job.phase === "resolve" || job.phase === "download");
+
+ useEffect(() => {
+ if (escapeLocked) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") closeRef.current();
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, [escapeLocked]);
+
+ // A finished install reports itself and then leaves, unless the pointer is
+ // still on it: the confirmation is worth reading before it goes.
+ useEffect(() => {
+ if (job.status !== "success" || hovered) return;
+ const handle = window.setTimeout(() => closeRef.current(), SUCCESS_DWELL_MS);
+ return () => window.clearTimeout(handle);
+ }, [job.status, hovered]);
+
+ const determinate = job.totalBytes > 0;
+ const percent = determinate
+ ? Math.min(100, Math.max(0, Math.round((job.receivedBytes / job.totalBytes) * 100)))
+ : 0;
+
+ const copyDetails = () => {
+ const lines = [
+ `${job.request.name}${job.request.version ? ` v${job.request.version}` : ""}: ${job.error ?? ""}`,
+ ...job.tried.map((mirror) =>
+ [
+ `- ${mirror.source || t("plugins.installMirrorUnknown")}${mirror.error ? `: ${mirror.error}` : ""}`,
+ ` ${mirror.url}`,
+ ].join("\n"),
+ ),
+ ];
+ void navigator.clipboard.writeText(lines.join("\n")).then(
+ () => showToast(t("plugins.installCopied"), { variant: "success" }),
+ () => showToast(t("plugins.installCopyFailed"), { variant: "error" }),
+ );
+ };
+
+ const outcomeIcon = (size: number) => {
+ if (job.status === "success") return <IconCircleCheck size={size} />;
+ if (job.status === "failed") return <IconTriangleAlert size={size} />;
+ return <IconDownload size={size} />;
+ };
+
+ return (
+ <div className="plugins-modal-backdrop" role="presentation">
+ <div
+ className="plugins-modal plugins-install-modal"
+ role="dialog"
+ aria-modal="true"
+ aria-label={t("plugins.installDialogTitle", { name: job.request.name })}
+ onPointerEnter={() => setHovered(true)}
+ onPointerLeave={() => setHovered(false)}
+ >
+ <header className="plugins-modal-head">
+ <span
+ className={cx(
+ "plugins-modal-icon",
+ job.status === "success" && "is-success",
+ job.status === "failed" && "is-error",
+ )}
+ aria-hidden
+ >
+ {outcomeIcon(17)}
+ </span>
+ <div>
+ <h2 className="plugins-modal-title">
+ {t("plugins.installDialogTitle", { name: job.request.name })}
+ </h2>
+ {job.request.version ? (
+ <p className="plugins-modal-subtitle">
+ {t("plugins.installingVersion", { version: job.request.version })}
+ </p>
+ ) : null}
+ </div>
+ </header>
+
+ <div className="plugins-modal-body">
+ {job.status === "failed" ? (
+ <>
+ <div className="plugins-install-failure" role="alert">
+ <p className="plugins-install-outcome">
+ {t("plugins.installFailed", { name: job.request.name })}
+ </p>
+ {job.error ? <p className="plugins-install-error">{job.error}</p> : null}
+ </div>
+ {job.tried.length > 0 ? (
+ <div className="plugins-install-tried">
+ <p className="plugins-install-tried-title">
+ {t("plugins.installTriedTitle", { count: job.tried.length })}
+ </p>
+ <ul className="plugins-install-mirrors">
+ {job.tried.map((mirror, index) => (
+ <li key={`${mirror.source}:${mirror.url}:${index}`}>
+ <details className="plugins-install-mirror">
+ <summary className="plugins-install-mirror-head">
+ <span className="plugins-install-mirror-source">
+ {mirror.source || t("plugins.installMirrorUnknown")}
+ </span>
+ {mirror.error ? (
+ <span className="plugins-install-mirror-error">{mirror.error}</span>
+ ) : null}
+ </summary>
+ <code className="plugins-install-mirror-url">{mirror.url}</code>
+ </details>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ </>
+ ) : job.status === "success" ? (
+ <p className="plugins-install-outcome is-success" role="status">
+ {t("plugins.installSuccess", { name: job.request.name })}
+ </p>
+ ) : (
+ <>
+ <div className="plugins-install-phase" aria-live="polite">
+ <span className="plugins-install-phase-label">{t(PHASE_KEYS[job.phase])}</span>
+ {job.phase === "download" && job.attempts > 0 ? (
+ <span className="plugins-install-mirror-label">
+ {t("plugins.installMirror", {
+ index: job.attempt,
+ total: job.attempts,
+ source: job.source ?? "",
+ })}
+ </span>
+ ) : null}
+ </div>
+ <div
+ className={cx("plugins-install-bar", !determinate && "is-indeterminate")}
+ role="progressbar"
+ aria-label={t("plugins.installProgressLabel")}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={determinate ? percent : undefined}
+ aria-valuetext={determinate ? `${percent}%` : undefined}
+ >
+ <span
+ className="plugins-install-bar-fill"
+ style={determinate ? { width: `${percent}%` } : undefined}
+ />
+ </div>
+ <div className="plugins-install-figures">
+ <span className="plugins-install-size">
+ {determinate
+ ? t("plugins.installReceived", {
+ received: formatTransfer(job.receivedBytes),
+ total: formatTransfer(job.totalBytes),
+ })
+ : t("plugins.installReceivedUnknown", {
+ received: formatTransfer(job.receivedBytes),
+ })}
+ </span>
+ {job.phase === "download" && job.speed > 0 ? (
+ <span className="plugins-install-speed">
+ {t("plugins.installSpeed", { rate: formatTransfer(job.speed) })}
+ </span>
+ ) : null}
+ </div>
+ </>
+ )}
+ </div>
+
+ <div className="plugins-modal-actions">
+ {running ? (
+ <Button variant="secondary" disabled={!stoppable} onClick={() => void onCancel()}>
+ {job.cancelling ? t("plugins.installCancelling") : t("plugins.installCancel")}
+ </Button>
+ ) : (
+ <>
+ <Button variant="secondary" onClick={() => onClose()}>
+ {t("plugins.installClose")}
+ </Button>
+ {job.status === "failed" ? (
+ <>
+ <Button variant="secondary" onClick={copyDetails}>
+ <IconCopy size={14} aria-hidden />
+ {t("plugins.installCopyDetails")}
+ </Button>
+ <Button variant="primary" onClick={() => void onRetry()}>
+ <IconRefresh size={14} aria-hidden />
+ {t("plugins.installRetry")}
+ </Button>
+ </>
+ ) : null}
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/plugins/PluginDialogs.tsx b/apps/desktop/src/features/plugins/PluginDialogs.tsx
index 9689d86ec..65b9573a6 100644
--- a/apps/desktop/src/features/plugins/PluginDialogs.tsx
+++ b/apps/desktop/src/features/plugins/PluginDialogs.tsx
@@ -1,5 +1,6 @@
import { Button, cx } from "../../components/ui";
import { IconCheck, IconShield, IconSparkles, IconTriangleAlert } from "../../components/icons";
+import { PluginInstallDialog } from "../../components/plugins/PluginInstallDialog";
import { PluginSettingsSheet } from "../../components/plugins/PluginSettingsSheet";
import { useAppStore } from "../../stores/app-store";
import {
@@ -19,6 +20,10 @@ export function PluginDialogs({
setAutoUpdate,
busyId,
confirmInstall,
+ installJob,
+ cancelInstallDownload,
+ retryInstall,
+ closeInstallDialog,
settingsPlugin,
setSettingsPlugin,
refreshPlugins,
@@ -134,6 +139,14 @@ export function PluginDialogs({
</div>
</div>
) : null}
+ {installJob ? (
+ <PluginInstallDialog
+ job={installJob}
+ onCancel={cancelInstallDownload}
+ onRetry={retryInstall}
+ onClose={closeInstallDialog}
+ />
+ ) : null}
{settingsPlugin ? (
<PluginSettingsSheet
plugin={settingsPlugin}
diff --git a/apps/desktop/src/features/plugins/install-progress.ts b/apps/desktop/src/features/plugins/install-progress.ts
new file mode 100644
index 000000000..23400a948
--- /dev/null
+++ b/apps/desktop/src/features/plugins/install-progress.ts
@@ -0,0 +1,169 @@
+/**
+ * What the install dialog shows, folded out of the host's progress reports.
+ *
+ * An install is a single request that answers only once it is over, so
+ * everything the dialog draws between the click and that answer comes from
+ * `plugin.installProgress` events: the phase, the mirror being tried, the bytes
+ * that arrived, and the mirrors a failure tried. Folding them into one job —
+ * and the transfer speed, which only exists as a difference between two reports
+ * — is pure transformation, so it lives here rather than in the page hook that
+ * owns the subscription.
+ */
+import type { PluginInstallMirror, PluginInstallProgress } from "@pi-desktop/shared";
+
+/** What the dialog asks the host for, and what a retry asks for again. */
+export type PluginInstallRequest = {
+ id: string;
+ name: string;
+ version?: string;
+ autoUpdate: boolean;
+ grantedPermissions: string[];
+};
+
+/** One install the dialog follows, from the confirmed click to its outcome. */
+export type PluginInstallJob = {
+ /** The accepted request, kept whole so a retry repeats it exactly. */
+ request: PluginInstallRequest;
+ status: "running" | "success" | "failed";
+ phase: PluginInstallProgress["phase"];
+ source: string | null;
+ attempt: number;
+ attempts: number;
+ receivedBytes: number;
+ totalBytes: number;
+ /** Bytes per second from successive reports; 0 until two reports arrive. */
+ speed: number;
+ /** The user asked to stop, and the host has not answered yet. */
+ cancelling: boolean;
+ error: string | null;
+ /** Mirrors the install tried, with what each answered. */
+ tried: PluginInstallMirror[];
+};
+
+/** The marker a cancelled install ends with. */
+const CANCELLED_MARKER = "PLUGIN_CANCELLED";
+
+/**
+ * A job that has just been confirmed. The dialog opens on `resolve`, the phase
+ * the host starts with, so a slow first step never looks like a frozen window.
+ */
+export function newInstallJob(request: PluginInstallRequest): PluginInstallJob {
+ return {
+ request,
+ status: "running",
+ phase: "resolve",
+ source: null,
+ attempt: 0,
+ attempts: 0,
+ receivedBytes: 0,
+ totalBytes: 0,
+ speed: 0,
+ cancelling: false,
+ error: null,
+ tried: [],
+ };
+}
+
+/**
+ * Whether this install can still be stopped. Only a download can be
+ * interrupted, and only once: while the host is answering a cancel, the button
+ * that called it is a "cancelling" state instead of a second request.
+ */
+export function canCancelInstall(job: PluginInstallJob): boolean {
+ return (
+ job.status === "running" &&
+ !job.cancelling &&
+ (job.phase === "resolve" || job.phase === "download")
+ );
+}
+
+/**
+ * The user's own cancellation, which is not a failure to report. The host marks
+ * it in the JSON-RPC error code and in the message.
+ */
+export function isInstallCancelled(error: unknown): boolean {
+ if (typeof error === "string") return error.includes(CANCELLED_MARKER);
+ if (!(error instanceof Error)) return false;
+ if (error.message.includes(CANCELLED_MARKER)) return true;
+ return (error as { code?: unknown }).code === CANCELLED_MARKER;
+}
+
+/** The reading a speed is measured against: the last report, and its mirror. */
+export type InstallSample = {
+ attempt: number;
+ received: number;
+ at: number;
+ speed: number;
+};
+
+/** How much of a new reading replaces the displayed speed. */
+const SPEED_SMOOTHING = 0.4;
+
+/**
+ * The transfer speed a report implies, and the reading the next one compares
+ * to. A mirror change restarts the count at zero, so that report is only a new
+ * baseline; the reading is smoothed because a single chunk says very little.
+ */
+export function nextInstallSample(
+ sample: InstallSample | null,
+ event: PluginInstallProgress,
+ at: number,
+): InstallSample {
+ const received = event.receivedBytes ?? 0;
+ const attempt = event.attempt ?? 0;
+ if (!sample || sample.attempt !== attempt || received < sample.received) {
+ return { attempt, received, at, speed: 0 };
+ }
+ const seconds = (at - sample.at) / 1000;
+ // Two reports can share a millisecond: keep the old baseline rather than
+ // divide by zero, so the next report still measures real elapsed time.
+ if (seconds <= 0) return sample;
+ const instant = (received - sample.received) / seconds;
+ return {
+ attempt,
+ received,
+ at,
+ speed: sample.speed > 0 ? sample.speed * (1 - SPEED_SMOOTHING) + instant * SPEED_SMOOTHING : instant,
+ };
+}
+
+/**
+ * Fold one report into the job.
+ *
+ * A report carries a whole picture rather than a delta, so the job takes what
+ * the report knows and keeps what it does not. The report that ends a failed
+ * install carries the mirrors it tried, which the request's own rejection
+ * cannot: a failure already shown is completed here rather than replaced.
+ */
+export function withInstallProgress(
+ job: PluginInstallJob,
+ event: PluginInstallProgress,
+ sample: InstallSample,
+): PluginInstallJob {
+ return {
+ ...job,
+ status: event.error ? "failed" : job.status,
+ phase: event.phase,
+ source: event.source ?? null,
+ attempt: event.attempt ?? 0,
+ attempts: event.attempts ?? 0,
+ receivedBytes: event.receivedBytes ?? 0,
+ totalBytes: event.totalBytes ?? 0,
+ speed: event.phase === "download" ? sample.speed : 0,
+ error: event.error ?? job.error,
+ tried: event.tried?.length ? event.tried : job.tried,
+ };
+}
+
+/**
+ * A byte count a person can read, for both sizes and rates. Unlike the catalog
+ * formatter this has no "unknown" reading: a download that has received nothing
+ * is zero bytes, not missing information.
+ */
+export function formatTransfer(bytes: number): string {
+ const value = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
+ if (value < 1024) return `${Math.round(value)} B`;
+ if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
+ if (value < 1024 * 1024 * 1024) return `${(value / (1024 * 1024)).toFixed(2)} MB`;
+ return `${(value / (1024 * 1024 * 1024)).toFixed(2)} GB`;
+}
diff --git a/apps/desktop/src/features/plugins/usePluginsPage.ts b/apps/desktop/src/features/plugins/usePluginsPage.ts
index bcaf38538..200d5a1f3 100644
--- a/apps/desktop/src/features/plugins/usePluginsPage.ts
+++ b/apps/desktop/src/features/plugins/usePluginsPage.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAppStore } from "../../stores/app-store";
import { api } from "../../lib/api";
@@ -24,6 +24,16 @@ import {
versionInstallable,
versionWithdrawn,
} from "./model";
+import {
+ canCancelInstall,
+ isInstallCancelled,
+ newInstallJob,
+ nextInstallSample,
+ withInstallProgress,
+ type InstallSample,
+ type PluginInstallJob,
+ type PluginInstallRequest,
+} from "./install-progress";
export function usePluginsPage() {
const { t, i18n } = useTranslation();
@@ -45,6 +55,14 @@ export function usePluginsPage() {
const [market, setMarket] = useState<MarketPluginSummary[]>([]);
const [marketLoading, setMarketLoading] = useState(false);
const [busyId, setBusyId] = useState<string | null>(null);
+ const [installJob, setInstallJob] = useState<PluginInstallJob | null>(null);
+ /**
+ * The job, and the reading a transfer speed is measured against, are mirrored
+ * in refs: the progress subscription and the request's own answer must both
+ * see the install as it is now, not as it was when it started.
+ */
+ const installJobRef = useRef<PluginInstallJob | null>(null);
+ const installSampleRef = useRef<InstallSample | null>(null);
const [reloadingId, setReloadingId] = useState<string | null>(null);
const [pendingInstall, setPendingInstall] = useState<{
id: string;
@@ -66,6 +84,28 @@ export function usePluginsPage() {
const [selectedVersion, setSelectedVersion] = useState("");
const [settingsPlugin, setSettingsPlugin] = useState<PluginSummary | null>(null);
+ /**
+ * The install dialog is the top layer while it is open: the permission review
+ * behind it and the detail sheet below that both leave Escape to it.
+ */
+ const installDialogOpen = installJob !== null;
+
+ /** Apply a change to the open install; reports whether a dialog was there. */
+ const updateInstallJob = (update: (job: PluginInstallJob) => PluginInstallJob): boolean => {
+ const current = installJobRef.current;
+ if (!current) return false;
+ const next = update(current);
+ installJobRef.current = next;
+ setInstallJob(next);
+ return true;
+ };
+
+ const closeInstallDialog = () => {
+ installJobRef.current = null;
+ installSampleRef.current = null;
+ setInstallJob(null);
+ };
+
const refreshMarket = async (q = query, opts?: { refreshRemote?: boolean }) => {
setMarketLoading(true);
try {
@@ -173,15 +213,16 @@ export function usePluginsPage() {
}, [locale]);
// Escape closes the detail sheet, but only while it owns the top layer: the
- // permission dialog in front of it handles its own dismissal.
+ // permission dialog and the install dialog in front of it handle their own
+ // dismissal.
useEffect(() => {
- if (!selectedId || pendingInstall) return;
+ if (!selectedId || pendingInstall || installDialogOpen) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") closeDetail();
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
- }, [selectedId, pendingInstall]);
+ }, [selectedId, pendingInstall, installDialogOpen]);
useEffect(() => {
if (!pendingInstall) return;
@@ -192,6 +233,28 @@ export function usePluginsPage() {
return () => document.removeEventListener("keydown", onKeyDown);
}, [pendingInstall]);
+ // An install reports itself while it runs: the phase, the mirror it is trying
+ // and the bytes that have arrived. Reports for another plugin are ignored, and
+ // the request's own answer still decides how the install ends.
+ useEffect(() => {
+ return api.onPluginInstallProgress((event) => {
+ const job = installJobRef.current;
+ if (!job || job.request.id !== event.pluginId) return;
+ // A cancellation is the user's own action, not a failure to report: the
+ // dialog leaves quietly instead of showing it as an error.
+ if (event.error && isInstallCancelled(event.error)) {
+ closeInstallDialog();
+ return;
+ }
+ const sample = nextInstallSample(installSampleRef.current, event, Date.now());
+ installSampleRef.current = sample;
+ const next = withInstallProgress(job, event, sample);
+ installJobRef.current = next;
+ setInstallJob(next);
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
// Service state changes arrive as pluginChanged events, so the list stays
// truthful while the supervisor restarts a crashed worker.
useEffect(() => {
@@ -417,31 +480,95 @@ export function usePluginsPage() {
setRowMenu(null);
};
- const confirmInstall = async () => {
- if (!pendingInstall) return;
- setBusyId(pendingInstall.id);
+ /**
+ * Run one install: the request the review approved, or the same request again
+ * after a failure. The dialog opens before the request is sent, so a slow
+ * first step is visible, and the request's own answer is what ends it.
+ */
+ const runInstall = async (request: PluginInstallRequest) => {
+ installSampleRef.current = null;
+ const job = newInstallJob(request);
+ installJobRef.current = job;
+ setInstallJob(job);
+ setBusyId(request.id);
try {
await api.marketInstall({
- id: pendingInstall.id,
- version: pendingInstall.version,
+ id: request.id,
+ version: request.version,
enable: true,
- autoUpdate,
- grantedPermissions: pendingInstall.permissions,
+ autoUpdate: request.autoUpdate,
+ grantedPermissions: request.grantedPermissions,
});
await refreshPlugins();
await refreshMarket();
- if (selectedId === pendingInstall.id) await openDetail(pendingInstall.id);
- showToast(t("plugins.installed", { name: pendingInstall.name }), {
+ if (selectedId === request.id) await openDetail(request.id);
+ showToast(t("plugins.installed", { name: request.name }), {
variant: "success",
});
- setPendingInstall(null);
+ updateInstallJob((current) => ({
+ ...current,
+ status: "success",
+ phase: "enable",
+ speed: 0,
+ error: null,
+ }));
} catch (e) {
- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });
+ const message = e instanceof Error ? e.message : String(e);
+ if (isInstallCancelled(e)) {
+ // The user stopped it: the dialog leaves quietly, without an error.
+ closeInstallDialog();
+ return;
+ }
+ const shown = updateInstallJob((current) => ({
+ ...current,
+ status: "failed",
+ speed: 0,
+ error: message,
+ }));
+ // The dialog was dismissed while the install ran, so the failure has to
+ // be reported where the user is looking.
+ if (!shown) showToast(message, { variant: "error" });
} finally {
setBusyId(null);
}
};
+ const confirmInstall = async () => {
+ if (!pendingInstall) return;
+ const request: PluginInstallRequest = {
+ id: pendingInstall.id,
+ name: pendingInstall.name,
+ version: pendingInstall.version,
+ autoUpdate,
+ grantedPermissions: pendingInstall.permissions,
+ };
+ // The review is answered, so it steps aside for the install it approved.
+ setPendingInstall(null);
+ await runInstall(request);
+ };
+
+ /** Ask the host to stop the running download, at most once. */
+ const cancelInstallDownload = async () => {
+ const job = installJobRef.current;
+ if (!job || !canCancelInstall(job)) return;
+ updateInstallJob((current) => ({ ...current, cancelling: true }));
+ try {
+ const res = await api.marketCancelInstall(job.request.id);
+ // Nothing was running: the install is past its last safe stop, so the
+ // dialog keeps watching it instead of pretending it stopped.
+ if (!res.cancelled) updateInstallJob((current) => ({ ...current, cancelling: false }));
+ } catch (e) {
+ updateInstallJob((current) => ({ ...current, cancelling: false }));
+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });
+ }
+ };
+
+ const retryInstall = async () => {
+ const job = installJobRef.current;
+ if (!job || job.status === "running") return;
+ await runInstall(job.request);
+ };
+
const overflowActions = [
{ key: "checkUpdates", run: checkUpdates },
{ key: "applyAutoUpdates", run: applyAutoUpdates },
@@ -537,6 +664,10 @@ export function usePluginsPage() {
applyAutoUpdates,
queueInstall,
confirmInstall,
+ installJob,
+ cancelInstallDownload,
+ retryInstall,
+ closeInstallDialog,
overflowActions,
installTarget,
installedDetail,
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index bc282c853..1a225b373 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -58,6 +58,7 @@ import type {
MarketPluginSummary,
MarketPluginDetail,
PluginInstallResult,
+ PluginInstallProgress,
ProjectRecord,
ProjectGroupRecord,
ProjectMemory,
@@ -923,6 +924,9 @@ export const api = {
IPC.invoke.marketApplyUpdates,
{ onlyAuto },
),
+ /** Ask the running install to stop. Only a download can be interrupted. */
+ marketCancelInstall: (id: string) =>
+ invoke<{ cancelled: boolean; id: string }>(IPC.invoke.marketCancelInstall, { id }),
/** Import a pi CLI extension file or directory as a development plugin (spec 16 §3). */
importPiExtension: () =>
invoke<
@@ -1176,6 +1180,13 @@ export const api = {
listener(payload as UpdateState),
);
},
+ onPluginInstallProgress: (listener: (event: PluginInstallProgress) => void) => {
+ if (!window.piDesktop?.on) return () => undefined;
+ return window.piDesktop.on(IPC.event.pluginInstallProgress, (payload) =>
+ listener(payload as PluginInstallProgress),
+ );
+ },
+
onPluginChanged: (
listener: (event: { reason?: string; pluginId?: string }) => void,
) => {
diff --git a/apps/desktop/src/styles/plugins.css b/apps/desktop/src/styles/plugins.css
index df8c8c285..b00ec885b 100644
--- a/apps/desktop/src/styles/plugins.css
+++ b/apps/desktop/src/styles/plugins.css
@@ -1888,3 +1888,170 @@
gap: 8px;
padding: 14px 18px 18px;
}
+
+/* Manual install and update: one dialog follows the host's reports — the phase
+ it is in, the mirror being tried, the bytes that arrived — and ends either on
+ its own success or as a failure report naming the mirrors that were tried. */
+.plugins-install-modal {
+ width: min(560px, 100%);
+}
+
+.plugins-modal-icon.is-success {
+ background: color-mix(in oklab, var(--ds-success) 14%, transparent);
+ color: var(--ds-success);
+}
+
+.plugins-modal-icon.is-error {
+ background: color-mix(in oklab, var(--ds-error) 14%, transparent);
+ color: var(--ds-error);
+}
+
+.plugins-install-phase {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 10px;
+}
+
+.plugins-install-phase-label {
+ color: var(--ds-text-primary);
+ font-size: var(--text-sm-plus);
+ font-weight: var(--font-weight-medium-plus);
+}
+
+.plugins-install-mirror-label {
+ overflow: hidden;
+ color: var(--ds-text-muted);
+ font-size: var(--text-sm);
+ font-variant-numeric: tabular-nums;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.plugins-install-bar {
+ position: relative;
+ height: 6px;
+ overflow: hidden;
+ border-radius: var(--radius-full);
+ background: color-mix(in oklab, var(--ds-text-primary) 10%, transparent);
+}
+
+.plugins-install-bar-fill {
+ display: block;
+ height: 100%;
+ border-radius: inherit;
+ background: var(--ds-accent);
+ transition: width var(--motion-duration-normal) var(--motion-ease-out);
+}
+
+/* No size was announced, so the bar reports activity instead of a fraction:
+ the same sliding mark the session switch uses for an open-ended wait. */
+.plugins-install-bar.is-indeterminate .plugins-install-bar-fill {
+ width: 28%;
+ animation: plugins-install-slide 720ms var(--motion-ease-standard) infinite;
+ transform: translateX(-110%);
+}
+
+@keyframes plugins-install-slide {
+ to {
+ transform: translateX(460%);
+ }
+}
+
+.plugins-install-figures {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 10px;
+ color: var(--ds-text-muted);
+ font-size: var(--text-sm);
+ font-variant-numeric: tabular-nums;
+}
+
+.plugins-install-outcome {
+ margin: 0;
+ color: var(--ds-text-primary);
+ font-size: var(--text-md);
+ font-weight: var(--font-weight-medium);
+}
+
+.plugins-install-outcome.is-success {
+ color: var(--ds-success);
+}
+
+.plugins-install-failure {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.plugins-install-error {
+ margin: 0;
+ overflow-wrap: anywhere;
+ color: var(--ds-error);
+ font-size: var(--text-sm-plus);
+ line-height: var(--leading-body);
+}
+
+.plugins-install-tried {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ border-radius: var(--radius-md-plus);
+ padding: 10px 12px;
+ background: var(--plugins-tile);
+}
+
+.plugins-install-tried-title {
+ margin: 0;
+ color: var(--ds-text-muted);
+ font-size: var(--text-3xs);
+ font-weight: var(--font-weight-medium);
+ letter-spacing: var(--tracking-wide);
+ text-transform: uppercase;
+}
+
+.plugins-install-mirrors {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.plugins-install-mirror-head {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm-plus);
+ cursor: pointer;
+}
+
+.plugins-install-mirror-source {
+ flex: 0 0 auto;
+ color: var(--ds-text-primary);
+ font-weight: var(--font-weight-medium);
+}
+
+.plugins-install-mirror-error {
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.plugins-install-mirror-url {
+ display: block;
+ margin: 4px 0 0;
+ overflow-wrap: anywhere;
+ color: var(--ds-text-muted);
+ font-size: var(--text-xs);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .plugins-install-bar-fill,
+ .plugins-install-bar.is-indeterminate .plugins-install-bar-fill {
+ animation: none;
+ transition: none;
+ }
+}
diff --git a/apps/desktop/test/plugin-install-dialog.test.mjs b/apps/desktop/test/plugin-install-dialog.test.mjs
new file mode 100644
index 000000000..cc61750d2
--- /dev/null
+++ b/apps/desktop/test/plugin-install-dialog.test.mjs
@@ -0,0 +1,280 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { readPluginsSourceSync } from "./helpers/source-contracts.mjs";
+import { loadStyles } from "./helpers/styles.mjs";
+import {
+ canCancelInstall,
+ formatTransfer,
+ isInstallCancelled,
+ newInstallJob,
+ nextInstallSample,
+ withInstallProgress,
+} from "../src/features/plugins/install-progress.ts";
+import { de } from "../../../packages/i18n/src/locales/de/index.ts";
+import { en } from "../../../packages/i18n/src/locales/en/index.ts";
+import { es } from "../../../packages/i18n/src/locales/es/index.ts";
+import { fr } from "../../../packages/i18n/src/locales/fr/index.ts";
+import { ko } from "../../../packages/i18n/src/locales/ko/index.ts";
+import { tr } from "../../../packages/i18n/src/locales/tr/index.ts";
+import { zhCN } from "../../../packages/i18n/src/locales/zh-CN/index.ts";
+import { zhTW } from "../../../packages/i18n/src/locales/zh-TW/index.ts";
+
+const catalogs = { en, "zh-CN": zhCN, "zh-TW": zhTW, de, es, fr, ko, tr };
+
+const here = dirname(fileURLToPath(import.meta.url));
+const dialogSrc = readFileSync(
+ join(here, "../src/components/plugins/PluginInstallDialog.tsx"),
+ "utf8",
+);
+const dialogsSrc = readFileSync(join(here, "../src/features/plugins/PluginDialogs.tsx"), "utf8");
+const pageSrc = readPluginsSourceSync();
+const pluginsCss = readFileSync(join(here, "../src/styles/plugins.css"), "utf8");
+const styles = await loadStyles();
+
+function lookup(catalog, key) {
+ return key.split(".").reduce((node, part) => (node == null ? undefined : node[part]), catalog);
+}
+
+function request(overrides = {}) {
+ return {
+ id: "acme.todo",
+ name: "Acme Todo",
+ version: "1.2.0",
+ autoUpdate: false,
+ grantedPermissions: ["notify"],
+ ...overrides,
+ };
+}
+
+function report(overrides = {}) {
+ return {
+ pluginId: "acme.todo",
+ version: "1.2.0",
+ phase: "download",
+ ...overrides,
+ };
+}
+
+test("the install dialog opens on resolve before the first report arrives", () => {
+ const job = newInstallJob(request());
+
+ assert.equal(job.status, "running");
+ // A slow resolve is the step that has nothing to report, so the dialog shows
+ // it from the click rather than waiting for an event.
+ assert.equal(job.phase, "resolve");
+ assert.deepEqual(
+ [job.attempt, job.attempts, job.receivedBytes, job.totalBytes, job.speed],
+ [0, 0, 0, 0, 0],
+ );
+ assert.deepEqual(job.tried, []);
+ assert.equal(dialogSrc.includes('resolve: "plugins.installPhase.resolve"'), true);
+});
+
+test("the page subscribes to install progress and cleans the subscription up", () => {
+ // The effect returns what `onPluginInstallProgress` returns, which is the
+ // unsubscribe function: the listener must not outlive the page.
+ assert.match(pageSrc, /useEffect\(\(\) => \{\s*return api\.onPluginInstallProgress\(/);
+ assert.match(pageSrc, /api\.onPluginInstallProgress\(\(event\) => \{/);
+ // Reports for another plugin must not move this dialog.
+ assert.match(pageSrc, /job\.request\.id !== event\.pluginId/);
+});
+
+test("only a download that is still running can be cancelled", () => {
+ const job = newInstallJob(request());
+
+ assert.equal(canCancelInstall(job), true, "resolve is still interruptible");
+ assert.equal(canCancelInstall({ ...job, phase: "download" }), true);
+ assert.equal(
+ canCancelInstall({ ...job, phase: "verify" }),
+ false,
+ "the last safe stop is behind the download",
+ );
+ assert.equal(canCancelInstall({ ...job, phase: "install" }), false);
+ assert.equal(canCancelInstall({ ...job, phase: "enable" }), false);
+ assert.equal(canCancelInstall({ ...job, phase: "download", cancelling: true }), false);
+ assert.equal(canCancelInstall({ ...job, phase: "download", status: "failed" }), false);
+
+ // One click is one request: the button reads this, and the handler refuses a
+ // second call while the host is answering the first.
+ assert.match(dialogSrc, /const stoppable = canCancelInstall\(job\)/);
+ assert.match(dialogSrc, /disabled=\{!stoppable\}/);
+ assert.match(pageSrc, /if \(!job \|\| !canCancelInstall\(job\)\) return;/);
+ assert.match(pageSrc, /api\.marketCancelInstall\(job\.request\.id\)/);
+ assert.match(dialogSrc, /plugins\.installCancelling/);
+});
+
+test("progress reports fill in the mirror, the bytes and the transfer speed", () => {
+ const job = newInstallJob(request());
+ const first = nextInstallSample(
+ null,
+ report({ receivedBytes: 0, totalBytes: 4096, attempt: 2, attempts: 3, source: "cnb" }),
+ 1_000,
+ );
+ assert.equal(first.speed, 0, "a first report is only a baseline");
+
+ const second = nextInstallSample(
+ first,
+ report({ receivedBytes: 1024, totalBytes: 4096, attempt: 2, attempts: 3, source: "cnb" }),
+ 2_000,
+ );
+ assert.equal(second.speed, 1024, "1024 bytes in one second");
+
+ const filled = withInstallProgress(
+ job,
+ report({ receivedBytes: 1024, totalBytes: 4096, attempt: 2, attempts: 3, source: "cnb" }),
+ second,
+ );
+ assert.equal(filled.phase, "download");
+ assert.equal(filled.source, "cnb");
+ assert.deepEqual([filled.attempt, filled.attempts], [2, 3]);
+ assert.deepEqual([filled.receivedBytes, filled.totalBytes], [1024, 4096]);
+ assert.equal(filled.speed, 1024);
+
+ // A new mirror counts from zero again, so it starts a fresh reading instead of
+ // dividing a smaller number by the previous mirror's elapsed time.
+ assert.equal(
+ nextInstallSample(second, report({ receivedBytes: 0, attempt: 3, attempts: 3 }), 3_000).speed,
+ 0,
+ );
+ assert.equal(formatTransfer(1024), "1.0 KB");
+ assert.equal(formatTransfer(0), "0 B");
+});
+
+test("a failure report carries the mirrors that were tried", () => {
+ const job = newInstallJob(request());
+ const terminal = report({
+ error: "PLUGIN_NETWORK: every mirror refused",
+ tried: [
+ { source: "cnb", url: "https://cnb.example/acme.tgz", error: "PLUGIN_NETWORK: 502" },
+ { source: "github", url: "https://github.example/acme.tgz", error: null },
+ ],
+ });
+ const failed = withInstallProgress(job, terminal, { attempt: 0, received: 0, at: 0, speed: 0 });
+
+ assert.equal(failed.status, "failed");
+ assert.equal(failed.error, "PLUGIN_NETWORK: every mirror refused");
+ assert.equal(failed.tried.length, 2);
+ assert.equal(failed.tried[0].source, "cnb");
+ assert.equal(failed.tried[0].url, "https://cnb.example/acme.tgz");
+
+ // The request can reject before the terminal report lands: the report
+ // completes the failure instead of erasing what the rejection already showed.
+ const rejected = { ...job, status: "failed", error: "PLUGIN_NETWORK: boom" };
+ const merged = withInstallProgress(rejected, terminal, { attempt: 0, received: 0, at: 0, speed: 0 });
+ assert.equal(merged.tried.length, 2);
+ assert.equal(merged.error, "PLUGIN_NETWORK: every mirror refused");
+
+ assert.equal(isInstallCancelled("PLUGIN_CANCELLED: the install was cancelled"), true);
+ const cancellation = new Error("PLUGIN_CANCELLED: the install was cancelled");
+ cancellation.code = "PLUGIN_CANCELLED";
+ assert.equal(isInstallCancelled(cancellation), true);
+ assert.equal(isInstallCancelled(new Error("PLUGIN_NETWORK: 502")), false);
+ // A cancellation closes the dialog quietly in both places it can surface.
+ assert.match(pageSrc, /if \(event\.error && isInstallCancelled\(event\.error\)\)/);
+ assert.match(pageSrc, /if \(isInstallCancelled\(e\)\) \{/);
+});
+
+test("the dialog renders the phase, the progress bar and the tried mirrors", () => {
+ assert.match(dialogSrc, /phase === "download" && job\.attempts > 0/);
+ assert.match(dialogSrc, /plugins\.installMirror", \{/);
+ assert.match(dialogSrc, /role="progressbar"/);
+ assert.match(dialogSrc, /!determinate && "is-indeterminate"/);
+ assert.match(dialogSrc, /style=\{determinate \? \{ width: `\$\{percent\}%` \} : undefined\}/);
+ assert.match(dialogSrc, /plugins\.installReceived/);
+ assert.match(dialogSrc, /plugins\.installSpeed/);
+ assert.match(dialogSrc, /formatTransfer\(job\.speed\)/);
+
+ // A failure lists every mirror with the error it answered, and the URL behind
+ // a disclosure rather than in the way.
+ assert.match(dialogSrc, /job\.tried\.map\(\(mirror, index\) => \(/);
+ assert.match(dialogSrc, /<details className="plugins-install-mirror">/);
+ assert.match(dialogSrc, /<code className="plugins-install-mirror-url">\{mirror\.url\}<\/code>/);
+ assert.match(dialogSrc, /plugins\.installCopyDetails/);
+ assert.match(dialogSrc, /navigator\.clipboard\.writeText\(lines\.join\("\\n"\)\)/);
+ assert.match(dialogSrc, /onClick=\{\(\) => void onRetry\(\)\}/);
+ assert.match(dialogSrc, /plugins\.installClose/);
+
+ // The page owns the state and the calls the dialog makes, and renders it
+ // beside the permission review it follows.
+ assert.match(dialogsSrc, /<PluginInstallDialog/);
+ assert.match(dialogsSrc, /onCancel=\{cancelInstallDownload\}/);
+ assert.match(dialogsSrc, /onRetry=\{retryInstall\}/);
+ assert.match(dialogsSrc, /onClose=\{closeInstallDialog\}/);
+});
+
+test("a successful install is dismissed on its own unless the pointer is on it", () => {
+ assert.match(dialogSrc, /const SUCCESS_DWELL_MS = 2000;/);
+ assert.match(dialogSrc, /if \(job\.status !== "success" \|\| hovered\) return;/);
+ assert.match(dialogSrc, /window\.setTimeout\(\(\) => closeRef\.current\(\), SUCCESS_DWELL_MS\)/);
+ assert.match(dialogSrc, /onPointerEnter=\{\(\) => setHovered\(true\)\}/);
+ assert.match(dialogSrc, /onPointerLeave=\{\(\) => setHovered\(false\)\}/);
+});
+
+test("Escape dismisses a finished install but never a running download", () => {
+ assert.match(
+ dialogSrc,
+ /const escapeLocked = running && \(job\.phase === "resolve" \|\| job\.phase === "download"\);/,
+ );
+ assert.match(dialogSrc, /if \(escapeLocked\) return;/);
+ assert.match(dialogSrc, /if \(event\.key === "Escape"\) closeRef\.current\(\);/);
+ // The dialog reuses the page's modal primitives instead of a second skin.
+ assert.match(dialogSrc, /className="plugins-modal-backdrop"/);
+ assert.match(dialogSrc, /className="plugins-modal plugins-install-modal"/);
+ assert.match(dialogSrc, /className="plugins-modal-actions"/);
+});
+
+test("install dialog copy exists in every shipped locale", () => {
+ const keys = [
+ "plugins.installDialogTitle",
+ "plugins.installPhase.resolve",
+ "plugins.installPhase.download",
+ "plugins.installPhase.verify",
+ "plugins.installPhase.install",
+ "plugins.installPhase.enable",
+ "plugins.installMirror",
+ "plugins.installMirrorUnknown",
+ "plugins.installProgressLabel",
+ "plugins.installReceived",
+ "plugins.installReceivedUnknown",
+ "plugins.installSpeed",
+ "plugins.installCancel",
+ "plugins.installCancelling",
+ "plugins.installSuccess",
+ "plugins.installFailed",
+ "plugins.installTriedTitle",
+ "plugins.installRetry",
+ "plugins.installClose",
+ "plugins.installCopyDetails",
+ "plugins.installCopied",
+ "plugins.installCopyFailed",
+ ];
+ const missing = Object.fromEntries(Object.keys(catalogs).map((id) => [id, []]));
+ for (const key of keys) {
+ for (const [id, catalog] of Object.entries(catalogs)) {
+ if (typeof lookup(catalog, key) !== "string") missing[id].push(key);
+ }
+ }
+ assert.deepEqual(missing, Object.fromEntries(Object.keys(catalogs).map((id) => [id, []])));
+ // The phase label is resolved by key at render time, so the companion test
+ // that scans literal `t("…")` calls cannot see these five.
+ assert.match(dialogSrc, /PHASE_KEYS\[job\.phase\]/);
+ assert.match(dialogSrc, /t\(PHASE_KEYS\[job\.phase\]\)/);
+});
+
+test("install dialog styles use design tokens and honour reduced motion", () => {
+ const start = styles.indexOf(".plugins-install-modal {");
+ assert.ok(start >= 0, "install dialog styles are missing");
+ const section = pluginsCss.slice(pluginsCss.indexOf(".plugins-install-modal"));
+
+ assert.match(section, /\.plugins-install-bar-fill\s*\{[^}]*background:\s*var\(--ds-accent\)/);
+ assert.match(section, /\.plugins-install-outcome\.is-success\s*\{[^}]*var\(--ds-success\)/);
+ assert.match(section, /\.plugins-install-error\s*\{[^}]*var\(--ds-error\)/);
+ assert.match(section, /@media \(prefers-reduced-motion: reduce\)/);
+ assert.doesNotMatch(section, /#[0-9a-fA-F]{3,8}\b/);
+ assert.doesNotMatch(section, /rgba?\(/);
+ assert.match(styles, /\.plugins-install-mirror-url\s*\{/);
+});
diff --git a/apps/desktop/test/plugin-runtime-risk.test.mjs b/apps/desktop/test/plugin-runtime-risk.test.mjs
index 84df67c49..042b428a9 100644
--- a/apps/desktop/test/plugin-runtime-risk.test.mjs
+++ b/apps/desktop/test/plugin-runtime-risk.test.mjs
@@ -213,9 +213,16 @@ test("marketplace package downloads stay inside the host allowlist", () => {
);
assert.match(hostSrc, /fn package_host_allowed\(package_url: &str, catalog_url: &str\) -> Result<\(\)>/);
// Refuse before the request leaves the machine, then hold the redirect
- // chain to the same rule: a release asset always redirects.
- assert.match(hostSrc, /package_host_allowed\(&info\.url, &catalog_url\)\?;/);
- assert.match(hostSrc, /download_url_guarded\(&info\.url, Some\(&catalog_url\)\)/);
+ // chain to the same rule: a release asset always redirects. Every package
+ // URL passes through this one path, whichever channel named it — the
+ // official channel's mirror list included.
+ assert.match(hostSrc, /package_host_allowed\(url, &catalog_url\)\?;/);
+ // The observed downloader is the same boundary: it refuses an off-allowlist
+ // host before the request and re-checks the effective URL after redirects.
+ assert.match(
+ hostSrc,
+ /download_url_observed\(\s*url,\s*Some\(&catalog_url\),\s*expected_size,\s*report\)/,
+ );
assert.match(hostSrc, /"--proto-redir"\.into\(\)/);
assert.match(hostSrc, /"%\{url_effective\}"\.into\(\)/);
assert.match(hostSrc, /must not embed credentials/);
@@ -245,7 +252,7 @@ test("a withdrawn version is never offered and never silently disabled", () => {
test("verified trust is not something a catalog entry can grant itself", () => {
const hostSrc = marketplaceSrc;
assert.match(hostSrc, /fn resolve_trust\(&self, entry: &MarketCatalogEntry\) -> String/);
- assert.match(hostSrc, /"verified" if self\.is_official_market_source\(\) => "verified"/);
+ assert.match(hostSrc, /"verified" if self\.is_trusted_channel\(\) => "verified"/);
assert.match(hostSrc, /"verified" => "community"/);
assert.match(pageSrc, /function showsVerifiedBadge\(/);
diff --git a/crates/host-core/Cargo.toml b/crates/host-core/Cargo.toml
index d7ab09c00..d4c464124 100644
--- a/crates/host-core/Cargo.toml
+++ b/crates/host-core/Cargo.toml
@@ -37,6 +37,7 @@ windows-sys = { version = "0.61.2", features = [
"Win32_Globalization",
"Win32_System_JobObjects",
"Win32_System_LibraryLoader",
+ "Win32_System_Registry",
"Win32_UI_WindowsAndMessaging",
] }
diff --git a/crates/host-core/src/plugins.rs b/crates/host-core/src/plugins.rs
index 768083561..7c22dd4d1 100644
--- a/crates/host-core/src/plugins.rs
+++ b/crates/host-core/src/plugins.rs
@@ -17,18 +17,22 @@ pub(crate) use crate::activation::ActivationScope;
pub(crate) const MAX_PACKAGE_BYTES: u64 = 50 * 1024 * 1024;
pub(crate) const MAX_PACKAGE_FILES: usize = 2000;
+mod device;
mod install;
mod manifest;
pub mod marketplace;
mod model;
mod permissions;
+mod progress;
mod providers;
mod registry;
+mod resolve;
mod validation;
pub use manifest::PluginManifest;
pub use marketplace::{
- market_source_from_settings, MIRROR_MARKET_CATALOG_URL, OFFICIAL_MARKET_CATALOG_URL,
+ market_channel_from_settings, MarketChannel, GITHUB_BACKUP_CHANNEL_CATALOG_URL,
+ MIRROR_MARKET_CATALOG_URL, OFFICIAL_CHANNEL_CATALOG_URL,
};
pub use model::{
InstallOptions, InstallResult, MarketDownloadInfo, MarketPluginDetail, MarketPluginSummary,
@@ -37,6 +41,10 @@ pub use model::{
PluginUiMeta, PluginUpdateInfo, PluginYankNotice,
};
pub(crate) use model::{MarketCatalogEntry, MarketCatalogFile};
+pub(crate) use progress::{
+ CancelToken, DownloadReport, InstallObserver, InstallPhase, InstallProgress, NoProgress,
+ TriedMirror,
+};
/// Locale resolution for plugin/catalog display strings, shared by the
/// registry and the marketplace readers.
diff --git a/crates/host-core/src/plugins/device.rs b/crates/host-core/src/plugins/device.rs
new file mode 100644
index 000000000..3765b2929
--- /dev/null
+++ b/crates/host-core/src/plugins/device.rs
@@ -0,0 +1,208 @@
+//! Stable device identity for the plugin center's download interface.
+//!
+//! The platform resolves a download once per install and deduplicates the
+//! statistic per (identity, plugin, version, UTC day). Its contract asks the
+//! client for a value that is stable per installation, so this module derives
+//! one from the machine and falls back to a value generated once and kept.
+//!
+//! What leaves the machine is a digest, never the machine code itself. The
+//! platform only ever counts, so it has no use for the raw value, and a digest
+//! keeps a hardware identifier out of a third party's request log.
+
+use super::*;
+use std::sync::OnceLock;
+
+/// Namespace folded into the digest.
+///
+/// It carries the derivation version, so a future change to how the identifier
+/// is derived cannot silently keep matching identities derived the old way.
+const DEVICE_ID_NAMESPACE: &str = "pi-desktop.device.v1:";
+
+/// Where a machine without a readable identifier keeps the value it generated.
+const DEVICE_ID_FILE: &str = "plugins/market/device.json";
+
+/// The device id for this installation, computed once per process.
+pub(crate) fn device_id(data_dir: &Path) -> String {
+ static CACHED: OnceLock<String> = OnceLock::new();
+ CACHED
+ .get_or_init(|| derive_device_id(raw_machine_id().as_deref(), data_dir))
+ .clone()
+}
+
+/// Derive the identifier the platform is told about.
+///
+/// Split out from [`device_id`] so both arms can be exercised without depending
+/// on the machine a test runs on.
+pub(crate) fn derive_device_id(machine_id: Option<&str>, data_dir: &Path) -> String {
+ if let Some(machine) = machine_id.map(str::trim).filter(|value| !value.is_empty()) {
+ return digest(machine);
+ }
+
+ let path = data_dir.join(DEVICE_ID_FILE);
+ if let Some(existing) = fs::read_to_string(&path)
+ .ok()
+ .as_deref()
+ .and_then(parse_stored)
+ {
+ return existing;
+ }
+
+ let generated = generated_id();
+ if let Some(parent) = path.parent() {
+ let _ = fs::create_dir_all(parent);
+ }
+ // A failure to persist it must not fail an install: the value is still
+ // stable for this run, and the next run generates another one.
+ let _ = fs::write(&path, format!("{{\"deviceId\":\"{generated}\"}}\n"));
+ generated
+}
+
+fn digest(value: &str) -> String {
+ let mut hasher = Sha256::new();
+ hasher.update(DEVICE_ID_NAMESPACE.as_bytes());
+ hasher.update(value.as_bytes());
+ hex::encode(hasher.finalize())
+}
+
+/// 64 hex characters, from two v4 UUIDs so no extra random source is needed.
+fn generated_id() -> String {
+ format!(
+ "{}{}",
+ uuid::Uuid::new_v4().simple(),
+ uuid::Uuid::new_v4().simple()
+ )
+}
+
+/// A stored value, when it is a device id this module wrote.
+fn parse_stored(raw: &str) -> Option<String> {
+ let value: Value = serde_json::from_str(raw).ok()?;
+ let id = value.get("deviceId")?.as_str()?.trim();
+ if id.len() == 64 && id.chars().all(|c| c.is_ascii_hexdigit()) {
+ return Some(id.to_ascii_lowercase());
+ }
+ None
+}
+
+/// The machine's own identifier, when this platform has a readable one.
+///
+/// Windows reads `MachineGuid`, macOS the platform UUID, and Linux the machine
+/// id the distribution writes. All three survive a reinstall of PI-Desktop and
+/// change when the operating system is installed again, which is the stability
+/// the platform's deduplication wants.
+#[cfg(windows)]
+fn raw_machine_id() -> Option<String> {
+ use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ};
+
+ const SUBKEY: &str = "SOFTWARE\\Microsoft\\Cryptography";
+ const VALUE: &str = "MachineGuid";
+
+ let subkey: Vec<u16> = SUBKEY.encode_utf16().chain(std::iter::once(0)).collect();
+ let value: Vec<u16> = VALUE.encode_utf16().chain(std::iter::once(0)).collect();
+ let mut buffer = [0u16; 64];
+ let mut size = std::mem::size_of_val(&buffer) as u32;
+ let status = unsafe {
+ RegGetValueW(
+ HKEY_LOCAL_MACHINE,
+ subkey.as_ptr(),
+ value.as_ptr(),
+ RRF_RT_REG_SZ,
+ std::ptr::null_mut(),
+ buffer.as_mut_ptr().cast(),
+ &mut size,
+ )
+ };
+ if status != 0 {
+ return None;
+ }
+ // The size is in bytes and includes the terminating NUL.
+ let len = (size as usize / 2).saturating_sub(1).min(buffer.len());
+ let text = String::from_utf16_lossy(&buffer[..len]);
+ Some(text).filter(|value| !value.trim().is_empty())
+}
+
+/// macOS: the platform UUID, through libc so no Objective-C runtime is needed.
+#[cfg(target_os = "macos")]
+fn raw_machine_id() -> Option<String> {
+ let mut uuid = [0u8; 16];
+ let timeout = libc::timespec {
+ tv_sec: 0,
+ tv_nsec: 0,
+ };
+ let status = unsafe { libc::gethostuuid(uuid.as_mut_ptr(), &timeout) };
+ if status != 0 {
+ return None;
+ }
+ Some(hex::encode(uuid))
+}
+
+/// Linux and the other unices: the machine id file the distribution maintains.
+#[cfg(all(unix, not(target_os = "macos")))]
+fn raw_machine_id() -> Option<String> {
+ for path in [
+ "/etc/machine-id",
+ "/var/lib/dbus/machine-id",
+ "/sys/class/dmi/id/product_uuid",
+ ] {
+ if let Ok(text) = fs::read_to_string(path) {
+ let value = text.trim();
+ if !value.is_empty() {
+ return Some(value.to_string());
+ }
+ }
+ }
+ None
+}
+
+#[cfg(not(any(windows, unix)))]
+fn raw_machine_id() -> Option<String> {
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_machine_identifier_is_reported_as_a_digest() {
+ let id = derive_device_id(Some("machine-guid-1234"), Path::new("."));
+ assert_eq!(id.len(), 64, "the id is a sha256 digest: {id}");
+ assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
+ assert_ne!(id, "machine-guid-1234", "the raw value must not be sent");
+ assert_eq!(
+ id,
+ derive_device_id(Some("machine-guid-1234"), Path::new(".")),
+ "the same machine keeps the same id"
+ );
+ assert_ne!(
+ id,
+ derive_device_id(Some("another-machine"), Path::new(".")),
+ "two machines do not share an id"
+ );
+ }
+
+ #[test]
+ fn a_machine_without_an_identifier_keeps_what_it_generated() {
+ let dir = tempfile::tempdir().unwrap();
+ let first = derive_device_id(None, dir.path());
+ assert_eq!(first.len(), 64);
+ assert_eq!(
+ derive_device_id(None, dir.path()),
+ first,
+ "a relaunch must reuse the stored value"
+ );
+ }
+
+ #[test]
+ fn an_unusable_stored_value_is_replaced() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join(DEVICE_ID_FILE);
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(&path, "{\"deviceId\":\"too-short\"}\n").unwrap();
+ let id = derive_device_id(None, dir.path());
+ assert_eq!(id.len(), 64);
+ assert_ne!(id, "too-short");
+ // The replacement is written back, so the next run reads a usable one.
+ let stored = fs::read_to_string(&path).unwrap();
+ assert!(stored.contains(&id), "the new value is stored: {stored}");
+ }
+}
diff --git a/crates/host-core/src/plugins/install.rs b/crates/host-core/src/plugins/install.rs
index a63ce53e7..687609bd8 100644
--- a/crates/host-core/src/plugins/install.rs
+++ b/crates/host-core/src/plugins/install.rs
@@ -164,12 +164,40 @@ impl PluginManager {
enable: bool,
auto_update: bool,
granted_permissions: Option<Vec<String>>,
+ ) -> Result<InstallResult> {
+ let mut observer = NoProgress;
+ self.install_from_market_observed(
+ plugin_id,
+ version,
+ enable,
+ auto_update,
+ granted_permissions,
+ &mut observer,
+ )
+ }
+
+ /// Install a marketplace plugin, reporting what it is doing.
+ ///
+ /// The observer sees every phase the install passes through and decides how
+ /// often to tell anyone: it is called for each chunk of bytes that lands and
+ /// again whenever the phase changes.
+ pub fn install_from_market_observed(
+ &mut self,
+ plugin_id: &str,
+ version: Option<&str>,
+ enable: bool,
+ auto_update: bool,
+ granted_permissions: Option<Vec<String>>,
+ observer: &mut dyn InstallObserver,
) -> Result<InstallResult> {
let info = self.market_download_info(plugin_id, version)?;
- let package_path = self.download_market_package(&info)?;
+ let mut report = DownloadReport::new(observer, &info.plugin_id, &info.version);
+ let (package_path, shasum) = self.fetch_market_package(&info, &mut report)?;
let marketplace = PluginMarketplaceMeta {
- provider_id: "official".into(),
- shasum: Some(info.shasum.clone()),
+ // The channel the bytes actually came from, so an installed row can
+ // be told apart from one installed through another source.
+ provider_id: self.channel().as_str().into(),
+ shasum: Some(shasum.clone()),
// Record the publisher the catalog named. Falling back to the
// project keeps registries written before publisher-owned sources
// readable, but a v2 entry must not be relabelled as ours.
@@ -181,18 +209,29 @@ impl PluginManager {
trust: info.trust.clone(),
provenance: info.provenance.clone(),
};
+ // The last safe point: after this the package is being written into the
+ // plugin directory, and stopping half way is worse than finishing.
+ if report.cancelled() {
+ return Err(report.failed(Vec::new(), anyhow!(super::progress::CANCELLED)));
+ }
+ report.phase(InstallPhase::Install);
let result = self.install_from_path(
&package_path.to_string_lossy(),
InstallOptions {
source: "marketplace".into(),
enable,
marketplace: Some(marketplace),
- expected_shasum: Some(info.shasum),
+ expected_shasum: Some(shasum),
auto_update,
granted_permissions,
},
);
let _ = fs::remove_file(package_path);
+ if result.is_ok() {
+ // The last thing an install does is make the plugin live; the
+ // caller loads the renderer side of it after this returns.
+ report.phase(InstallPhase::Enable);
+ }
result
}
@@ -245,7 +284,115 @@ impl PluginManager {
Ok(results)
}
- fn download_market_package(&self, info: &MarketDownloadInfo) -> Result<PathBuf> {
+ /// Fetch the package an install needs, through the channel's own path.
+ ///
+ /// Answers with the file it wrote and the digest it verified. The failure
+ /// that ends the install is reported here, exactly once, so a surface
+ /// showing progress always learns how the install finished.
+ fn fetch_market_package(
+ &self,
+ info: &MarketDownloadInfo,
+ report: &mut DownloadReport<'_>,
+ ) -> Result<(PathBuf, String)> {
+ let mut tried: Vec<TriedMirror> = Vec::new();
+ if self.uses_download_resolve() {
+ report.phase(InstallPhase::Resolve);
+ match self.download_market_package_via_resolve(info, report, &mut tried) {
+ Ok(fetched) => return Ok(fetched),
+ // A refusal is an answer, and so is a cancellation: install
+ // nothing, fall back to nothing, and say why.
+ Err(error)
+ if !super::resolve::is_recoverable(&error)
+ || super::progress::is_cancelled(&error) =>
+ {
+ return Err(report.failed(tried, error))
+ }
+ Err(error) => tracing::warn!(
+ plugin = %info.plugin_id,
+ version = %info.version,
+ %error,
+ "the plugin center did not answer; using the catalog url"
+ ),
+ }
+ }
+ // The catalog's own URL, which is also the documented fallback for a
+ // platform that cannot be reached.
+ report.mirror(None, 0, 0);
+ match self.download_market_package(info, &info.url, &info.shasum, info.size_bytes, report) {
+ Ok(path) => Ok((path, info.shasum.clone())),
+ Err(error) => Err(report.failed(tried, error)),
+ }
+ }
+
+ /// Download through the plugin center's resolve interface.
+ ///
+ /// Every mirror the platform lists is tried in the order it gave: they are
+ /// different hosts, and one can be unreachable, rate limited, or holding
+ /// different bytes under the same version — which the digest catches before
+ /// anything is extracted. The mirrors that failed are recorded in `tried`,
+ /// which the terminal report carries so the surface can list what was
+ /// attempted.
+ fn download_market_package_via_resolve(
+ &self,
+ info: &MarketDownloadInfo,
+ report: &mut DownloadReport<'_>,
+ tried: &mut Vec<TriedMirror>,
+ ) -> Result<(PathBuf, String)> {
+ let catalog_url = self.market_source_url();
+ let device_id = super::device::device_id(&self.data_dir);
+ let resolved =
+ super::resolve::request(&catalog_url, &device_id, &info.plugin_id, &info.version)?;
+ let expected = resolved.sha256.trim().to_ascii_lowercase();
+ let attempts = resolved.downloads.len() as u32;
+ let mut last_error: Option<anyhow::Error> = None;
+ for (index, mirror) in resolved.downloads.iter().enumerate() {
+ if report.cancelled() {
+ return Err(anyhow!(super::progress::CANCELLED));
+ }
+ let url = mirror.url.trim();
+ if url.is_empty() {
+ continue;
+ }
+ report.mirror(Some(&mirror.source), index as u32 + 1, attempts);
+ match self.download_market_package(info, url, &expected, resolved.size_bytes, report) {
+ Ok(path) => return Ok((path, expected)),
+ Err(error) => {
+ tracing::warn!(
+ source = %mirror.source,
+ %url,
+ %error,
+ "this mirror did not serve the package"
+ );
+ // A cancellation is not a mirror's fault: stop asking.
+ if super::progress::is_cancelled(&error) {
+ return Err(error);
+ }
+ tried.push(TriedMirror {
+ source: mirror.source.clone(),
+ url: url.to_string(),
+ error: Some(error.to_string()),
+ });
+ last_error = Some(error);
+ }
+ }
+ }
+ Err(last_error.unwrap_or_else(|| {
+ anyhow!("PLUGIN_MARKET_NO_SOURCE: the plugin center listed no usable mirror")
+ }))
+ }
+
+ /// Download one package URL, verify it, and leave it in the cache.
+ fn download_market_package(
+ &self,
+ info: &MarketDownloadInfo,
+ url: &str,
+ expected_shasum: &str,
+ expected_size: u64,
+ report: &mut DownloadReport<'_>,
+ ) -> Result<PathBuf> {
+ if report.cancelled() {
+ bail!("{}", super::progress::CANCELLED);
+ }
let cache = self.data_dir.join("plugins/cache/download").join(format!(
"{}-{}.piplug",
sanitize_id(&info.plugin_id),
@@ -254,23 +401,41 @@ impl PluginManager {
if let Some(parent) = cache.parent() {
fs::create_dir_all(parent)?;
}
- let bytes = if let Some(path) = info.url.strip_prefix("file://") {
- fs::read(path).with_context(|| format!("read market package {path}"))?
- } else if info.url.starts_with("http://") || info.url.starts_with("https://") {
+ let bytes = if let Some(path) = url.strip_prefix("file://") {
+ let bytes = fs::read(path).with_context(|| format!("read market package {path}"))?;
+ report.bytes(bytes.len() as u64, expected_size.max(bytes.len() as u64));
+ bytes
+ } else if url.starts_with("http://") || url.starts_with("https://") {
// Refuse an off-allowlist host before any request leaves the
// machine, then hold the redirect chain to the same rule.
let catalog_url = self.market_source_url();
- package_host_allowed(&info.url, &catalog_url)?;
- download_url_guarded(&info.url, Some(&catalog_url))?
+ package_host_allowed(url, &catalog_url)?;
+ download_url_observed(url, Some(&catalog_url), expected_size, report)?
} else {
// Allow bare local paths in catalogs.
- fs::read(&info.url).with_context(|| format!("read market package {}", info.url))?
+ let bytes = fs::read(url).with_context(|| format!("read market package {url}"))?;
+ report.bytes(bytes.len() as u64, expected_size.max(bytes.len() as u64));
+ bytes
};
+ // A cancellation that arrived while the bytes were being read still
+ // stops before anything is verified or written.
+ if report.cancelled() {
+ bail!("{}", super::progress::CANCELLED);
+ }
+ report.phase(InstallPhase::Verify);
if bytes.len() as u64 > MAX_PACKAGE_BYTES {
bail!("PLUGIN_INVALID: package exceeds 50MB limit");
}
+ // A size the platform stated is a sanity check that costs nothing and
+ // catches a mirror serving an unrelated file before the digest does.
+ if expected_size > 0 && bytes.len() as u64 != expected_size {
+ bail!(
+ "PLUGIN_INTEGRITY: package is {} bytes, {expected_size} were announced",
+ bytes.len()
+ );
+ }
let actual = sha256_hex(&bytes);
- if !actual.eq_ignore_ascii_case(&info.shasum) {
+ if !actual.eq_ignore_ascii_case(expected_shasum) {
bail!("PLUGIN_INTEGRITY: checksum mismatch");
}
fs::write(&cache, &bytes)?;
@@ -504,7 +669,7 @@ pub(crate) fn decode_windows_code_page(bytes: &[u8], code_page: u32) -> Option<S
///
/// curl writes the body to a file so stdout can carry only the effective URL;
/// mixing them would corrupt a binary package.
-fn download_scratch_path() -> PathBuf {
+pub(crate) fn download_scratch_path() -> PathBuf {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, AtomicOrdering::Relaxed);
let nanos = SystemTime::now()
@@ -526,12 +691,35 @@ fn download_scratch_path() -> PathBuf {
/// own: redirects are restricted to HTTPS and the effective URL is re-checked
/// under the same rule before the bytes are accepted.
pub(crate) fn download_url_guarded(url: &str, package_guard: Option<&str>) -> Result<Vec<u8>> {
+ let mut observer = NoProgress;
+ let mut report = DownloadReport::new(&mut observer, "", "");
+ download_url_observed(url, package_guard, 0, &mut report)
+}
+
+/// Fetch a URL while reporting the bytes that arrive, and stop when asked to.
+///
+/// Same contract as [`download_url_guarded`]. `total_bytes` is what the catalog
+/// or the platform announced for the package, and `0` means nothing announced
+/// one — a surface reads that as an indeterminate transfer. The transfer is a
+/// child process, so progress is the size of the file curl has written so far,
+/// which is exactly what watching the disk would show.
+pub(crate) fn download_url_observed(
+ url: &str,
+ package_guard: Option<&str>,
+ total_bytes: u64,
+ report: &mut DownloadReport<'_>,
+) -> Result<Vec<u8>> {
if let Some(path) = url.strip_prefix("file://") {
- return fs::read(path).with_context(|| format!("read local url {path}"));
+ let bytes = fs::read(path).with_context(|| format!("read local url {path}"))?;
+ report.bytes(bytes.len() as u64, total_bytes.max(bytes.len() as u64));
+ return Ok(bytes);
+ }
+ if report.cancelled() {
+ bail!("{}", super::progress::CANCELLED);
}
// Prefer curl for robust HTTPS support on developer and CI machines.
- let scratch = package_guard.map(|_| download_scratch_path());
+ let scratch = download_scratch_path();
let max_filesize = MAX_PACKAGE_BYTES.to_string();
let mut args: Vec<String> = vec![
"--silent".into(),
@@ -556,42 +744,63 @@ pub(crate) fn download_url_guarded(url: &str, package_guard: Option<&str>) -> Re
args.push("--proto-redir".into());
args.push("=https".into());
}
- if let Some(scratch) = scratch.as_ref() {
- args.push("--output".into());
- args.push(scratch.to_string_lossy().into_owned());
- args.push("--write-out".into());
- args.push("%{url_effective}".into());
- }
+ args.push("--output".into());
+ args.push(scratch.to_string_lossy().into_owned());
+ args.push("--write-out".into());
+ args.push("%{url_effective}".into());
args.push(url.to_string());
- let outcome = std::process::Command::new("curl").args(&args).output();
- if let Ok(output) = outcome {
+ let spawned = std::process::Command::new("curl")
+ .args(&args)
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn();
+ if let Ok(mut child) = spawned {
+ // Watch what curl writes until it exits. This loop is also where a
+ // cancellation lands: killing the transfer and dropping the partial
+ // file is the whole of "stop the download".
+ loop {
+ if report.cancelled() {
+ let _ = child.kill();
+ let _ = child.wait();
+ let _ = fs::remove_file(&scratch);
+ bail!("{}", super::progress::CANCELLED);
+ }
+ match child.try_wait() {
+ Ok(Some(_)) => break,
+ Ok(None) => {
+ let received = fs::metadata(&scratch).map(|meta| meta.len()).unwrap_or(0);
+ report.bytes(received, total_bytes);
+ std::thread::sleep(Duration::from_millis(120));
+ }
+ Err(error) => {
+ let _ = fs::remove_file(&scratch);
+ bail!("PLUGIN_NETWORK: curl failed for {url}: {error}");
+ }
+ }
+ }
+ let output = child
+ .wait_with_output()
+ .with_context(|| format!("collect download {url}"))?;
if output.status.success() {
- let body = match scratch.as_ref() {
- Some(scratch) => {
- let effective = String::from_utf8_lossy(&output.stdout).trim().to_string();
- let guard_result = match package_guard {
- Some(catalog_url) if !effective.is_empty() => {
- package_host_allowed(&effective, catalog_url)
- }
- _ => Ok(()),
- };
- let body = guard_result.and_then(|()| {
- fs::read(scratch).with_context(|| format!("read download {url}"))
- });
- let _ = fs::remove_file(scratch);
- body?
+ let effective = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ let guard_result = match package_guard {
+ Some(catalog_url) if !effective.is_empty() => {
+ package_host_allowed(&effective, catalog_url)
}
- None => output.stdout,
+ _ => Ok(()),
};
+ let body = guard_result
+ .and_then(|()| fs::read(&scratch).with_context(|| format!("read download {url}")));
+ let _ = fs::remove_file(&scratch);
+ let body = body?;
if body.len() as u64 > MAX_PACKAGE_BYTES {
bail!("PLUGIN_INVALID: package exceeds 50MB limit");
}
+ report.bytes(body.len() as u64, total_bytes.max(body.len() as u64));
return Ok(body);
}
- if let Some(scratch) = scratch.as_ref() {
- let _ = fs::remove_file(scratch);
- }
+ let _ = fs::remove_file(&scratch);
let err = decode_curl_output(&output.stderr);
// Fall through to raw HTTP only for http:// URLs.
if url.starts_with("https://") {
@@ -632,6 +841,7 @@ pub(crate) fn download_url_guarded(url: &str, package_guard: Option<&str>) -> Re
if body.len() as u64 > MAX_PACKAGE_BYTES {
bail!("PLUGIN_INVALID: package exceeds 50MB limit");
}
+ report.bytes(body.len() as u64, total_bytes.max(body.len() as u64));
return Ok(body);
}
diff --git a/crates/host-core/src/plugins/marketplace.rs b/crates/host-core/src/plugins/marketplace.rs
index 8a75277f4..689416c4f 100644
--- a/crates/host-core/src/plugins/marketplace.rs
+++ b/crates/host-core/src/plugins/marketplace.rs
@@ -3,62 +3,170 @@ use super::*;
pub mod catalog;
pub(crate) use catalog::{built_in_catalog, bundled_package_bytes};
-/// Official marketplace catalog, served from the dedicated GitHub repo.
-pub const OFFICIAL_MARKET_CATALOG_URL: &str =
- "https://raw.githubusercontent.com/vastsa/pi-desktop-plugins/main/catalog.json";
+/// Official channel: the plugin center.
+///
+/// The catalog it serves is the client's listing contract, and an install asks
+/// the same host where the package is (`plugins::resolve`) instead of resolving
+/// a relative package URL against a git host.
+pub const OFFICIAL_CHANNEL_CATALOG_URL: &str = "https://plugins.aiuo.net/catalog.json";
-/// Mirror for networks that cannot reach `raw.githubusercontent.com`.
+/// Backup channel: the GitHub copy of the distribution repository.
///
-/// The mirror serves a byte-identical catalog and packages, and catalog
-/// package URLs are relative, so `resolve_package_url` keeps downloads on
-/// whichever source the catalog came from and shasum verification is
-/// unaffected by the switch.
+/// Catalog and packages live in one tree, so a relative package URL resolves
+/// against whichever host served the catalog and a switch can never cross
+/// providers.
+pub const GITHUB_BACKUP_CHANNEL_CATALOG_URL: &str =
+ "https://raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main/catalog.json";
+
+/// Backup channel: the CNB copy, for networks that cannot reach GitHub.
pub const MIRROR_MARKET_CATALOG_URL: &str =
"https://cnb.cool/aixk/pi-desktop-plugins/-/git/raw/main/catalog.json";
-/// Resolve the catalog URL pinned by persisted app settings.
+/// The catalog source a user chose.
///
-/// `pluginMarketSource` selects the provider; `custom` reads the URL from
-/// `pluginMarketCustomUrl`. Returns `None` when settings do not pin a source
-/// (or pin `custom` without a URL), which leaves the official default in
-/// place.
-pub fn market_source_from_settings(settings: Option<&Value>) -> Option<String> {
- let settings = settings?;
- match settings.get("pluginMarketSource").and_then(Value::as_str) {
- Some("mirror") => Some(MIRROR_MARKET_CATALOG_URL.to_string()),
- Some("custom") => settings
- .get("pluginMarketCustomUrl")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|url| !url.is_empty())
- .map(str::to_string),
- _ => None,
+/// `official` keeps its meaning — "the official one" — and the official one is
+/// now the plugin center. That is why a settings row written before this change
+/// keeps meaning what its author picked, and why no migration is needed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MarketChannel {
+ /// The plugin center (the default).
+ Official,
+ /// The GitHub backup.
+ Github,
+ /// The CNB backup.
+ Mirror,
+ /// A catalog URL the user typed.
+ Custom,
+}
+
+impl MarketChannel {
+ /// Persisted value, and the `providerId` an install records.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ MarketChannel::Official => "official",
+ MarketChannel::Github => "github",
+ MarketChannel::Mirror => "mirror",
+ MarketChannel::Custom => "custom",
+ }
+ }
+
+ /// Channel named by a persisted `pluginMarketSource` value.
+ ///
+ /// An absent value, the legacy `official`, and anything unrecognised all
+ /// mean the official channel: the old resolution fell back to its default
+ /// for exactly those three cases, and the default is now the center.
+ pub fn from_setting(value: Option<&str>) -> Self {
+ match value.map(str::trim) {
+ Some("github") => MarketChannel::Github,
+ Some("mirror") => MarketChannel::Mirror,
+ Some("custom") => MarketChannel::Custom,
+ _ => MarketChannel::Official,
+ }
+ }
+
+ /// Catalog URL, for every channel that has a fixed one.
+ pub fn catalog_url(self) -> Option<&'static str> {
+ match self {
+ MarketChannel::Official => Some(OFFICIAL_CHANNEL_CATALOG_URL),
+ MarketChannel::Github => Some(GITHUB_BACKUP_CHANNEL_CATALOG_URL),
+ MarketChannel::Mirror => Some(MIRROR_MARKET_CATALOG_URL),
+ MarketChannel::Custom => None,
+ }
}
}
+/// Catalog URL forced by the environment, when one is set.
+///
+/// Dev builds and tests point this at a local catalog so they never touch
+/// persisted settings, and it outranks the channel on purpose.
+pub(crate) fn market_source_env_override() -> Option<String> {
+ std::env::var("PI_DESKTOP_PLUGIN_MARKET_URL")
+ .ok()
+ .map(|url| url.trim().to_string())
+ .filter(|url| !url.is_empty())
+}
+
+/// Channel and custom URL pinned by persisted app settings.
+pub fn market_channel_from_settings(settings: Option<&Value>) -> (MarketChannel, Option<String>) {
+ let Some(settings) = settings else {
+ return (MarketChannel::Official, None);
+ };
+ let channel =
+ MarketChannel::from_setting(settings.get("pluginMarketSource").and_then(Value::as_str));
+ let custom_url = settings
+ .get("pluginMarketCustomUrl")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|url| !url.is_empty())
+ .map(str::to_string);
+ (channel, custom_url)
+}
+
impl PluginManager {
/// Catalog URL in effect, highest precedence first.
///
/// The environment override stays on top so dev builds and tests can point
/// at a local catalog without touching persisted settings.
pub fn market_source_url(&self) -> String {
- if let Ok(url) = std::env::var("PI_DESKTOP_PLUGIN_MARKET_URL") {
- if !url.trim().is_empty() {
- return url;
- }
+ if let Some(url) = market_source_env_override() {
+ return url;
+ }
+ match self.market_channel {
+ // A custom channel with no URL keeps the official default, which is
+ // what an empty setting meant before the channel existed.
+ MarketChannel::Custom => self
+ .market_custom_url
+ .clone()
+ .unwrap_or_else(|| OFFICIAL_CHANNEL_CATALOG_URL.to_string()),
+ channel => channel
+ .catalog_url()
+ .unwrap_or(OFFICIAL_CHANNEL_CATALOG_URL)
+ .to_string(),
}
- self.market_source
- .clone()
- .unwrap_or_else(|| OFFICIAL_MARKET_CATALOG_URL.to_string())
}
- /// Re-pin the catalog source after the user switches providers.
+ /// Channel the user selected.
+ pub fn channel(&self) -> MarketChannel {
+ self.market_channel
+ }
+
+ /// Re-pin the catalog channel after the user switches sources.
///
/// Cached snapshots are left on disk: they are keyed back to their source
- /// through `cache-meta.json`, so a snapshot from another provider is
- /// ignored rather than deleted and switching back keeps working offline.
- pub fn set_market_source(&mut self, market_source: Option<String>) {
- self.market_source = market_source;
+ /// through `cache-meta.json`, so a snapshot from another channel is ignored
+ /// rather than deleted and switching back keeps working offline.
+ pub fn set_market_channel(&mut self, channel: MarketChannel, custom_url: Option<String>) {
+ self.market_channel = channel;
+ self.market_custom_url = custom_url;
+ }
+
+ /// Whether an install asks the plugin center where the package is.
+ ///
+ /// Only the official channel does, and only when the catalog really is the
+ /// center's: an environment override names a catalog file somebody put
+ /// somewhere, and such a catalog lists packages the way a git host serves
+ /// them, so it keeps the relative-URL path.
+ pub(crate) fn uses_download_resolve(&self) -> bool {
+ self.market_channel == MarketChannel::Official && market_source_env_override().is_none()
+ }
+
+ /// Make the install that is about to run cancellable.
+ ///
+ /// The token is held here rather than passed around, because the cancel
+ /// action arrives as its own RPC while the install is still running.
+ pub(crate) fn set_install_cancel(&mut self, token: Option<CancelToken>) {
+ self.install_cancel = token;
+ }
+
+ /// Ask the running install to stop. Answers whether one was running.
+ pub(crate) fn cancel_install(&self) -> bool {
+ match self.install_cancel.as_ref() {
+ Some(token) => {
+ token.cancel();
+ true
+ }
+ None => false,
+ }
}
pub(crate) fn market_cache_meta_path(&self) -> PathBuf {
@@ -573,17 +681,25 @@ impl PluginManager {
}
});
match declared.as_str() {
- "verified" if self.is_official_market_source() => "verified".into(),
+ "verified" if self.is_trusted_channel() => "verified".into(),
"verified" => "community".into(),
"community" => "community".into(),
_ => "unknown".into(),
}
}
- /// Whether the catalog in effect is the project's own source or its mirror.
- fn is_official_market_source(&self) -> bool {
+ /// Whether the catalog in effect is one this project issues.
+ ///
+ /// The three channels are the project's own catalogs; a URL somebody typed
+ /// into `custom` may describe its own plugins but cannot assert a tier. The
+ /// comparison stays on the effective URL rather than on the setting, so a
+ /// catalog reached through `PI_DESKTOP_PLUGIN_MARKET_URL` counts only when
+ /// it actually names one of them.
+ fn is_trusted_channel(&self) -> bool {
let url = self.market_source_url();
- url == OFFICIAL_MARKET_CATALOG_URL || url == MIRROR_MARKET_CATALOG_URL
+ url == OFFICIAL_CHANNEL_CATALOG_URL
+ || url == GITHUB_BACKUP_CHANNEL_CATALOG_URL
+ || url == MIRROR_MARKET_CATALOG_URL
}
}
diff --git a/crates/host-core/src/plugins/progress.rs b/crates/host-core/src/plugins/progress.rs
new file mode 100644
index 000000000..f0c57562c
--- /dev/null
+++ b/crates/host-core/src/plugins/progress.rs
@@ -0,0 +1,283 @@
+//! Progress an install reports while it runs, and the way a user cancels one.
+//!
+//! The install path is a single request: it resolves where the package is,
+//! downloads it from one mirror after another, verifies it, extracts it and
+//! registers it. Only the last step answers the caller, so a download that takes
+//! a minute looks like a frozen window unless the work reports itself. That is
+//! what an [`InstallObserver`] is for: the install calls it, and whoever owns
+//! the interface decides what to do with it.
+//!
+//! Nothing here knows about JSON, RPC or the renderer on purpose: the caller
+//! that emits an event is the RPC layer, and the tests use a recorder.
+
+use super::*;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+
+/// What an install is doing right now.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum InstallPhase {
+ /// Asking the plugin center where the package is (official channel).
+ Resolve,
+ /// Downloading from a mirror.
+ Download,
+ /// Checking the bytes against the digest the catalog or the platform named.
+ Verify,
+ /// Unpacking the package and writing the plugin's row.
+ Install,
+ /// Loading the plugin so it is live.
+ Enable,
+}
+
+impl InstallPhase {
+ /// Wire name, and the name the dialog shows.
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ InstallPhase::Resolve => "resolve",
+ InstallPhase::Download => "download",
+ InstallPhase::Verify => "verify",
+ InstallPhase::Install => "install",
+ InstallPhase::Enable => "enable",
+ }
+ }
+}
+
+/// A mirror that was tried, and what it answered.
+#[derive(Clone, Debug)]
+pub(crate) struct TriedMirror {
+ pub source: String,
+ pub url: String,
+ /// `None` while this mirror is the one being tried.
+ pub error: Option<String>,
+}
+
+/// One report from an install.
+#[derive(Clone, Debug)]
+pub(crate) struct InstallProgress {
+ pub plugin_id: String,
+ pub version: String,
+ pub phase: InstallPhase,
+ /// Mirror the download is coming from, when one is in use.
+ pub source: Option<String>,
+ /// 1-based index of the mirror being tried, within `attempts`.
+ pub attempt: u32,
+ pub attempts: u32,
+ pub received_bytes: u64,
+ pub total_bytes: u64,
+ /// Every mirror tried so far, in order, with what each answered.
+ pub tried: Vec<TriedMirror>,
+ /// Set on the report that ends the install with a failure.
+ pub error: Option<String>,
+}
+
+impl InstallProgress {
+ /// The report that starts a phase for a plugin.
+ pub(crate) fn phase(plugin_id: &str, version: &str, phase: InstallPhase) -> Self {
+ Self {
+ plugin_id: plugin_id.to_string(),
+ version: version.to_string(),
+ phase,
+ source: None,
+ attempt: 0,
+ attempts: 0,
+ received_bytes: 0,
+ total_bytes: 0,
+ tried: Vec::new(),
+ error: None,
+ }
+ }
+}
+
+/// Receives progress from an install, and answers whether it should stop.
+pub(crate) trait InstallObserver {
+ /// Report progress. Called often while bytes arrive, so an implementation
+ /// that talks to an interface has to throttle.
+ fn progress(&mut self, event: InstallProgress);
+
+ /// Whether the user asked to cancel. Checked between chunks, before every
+ /// mirror, and before anything is written to disk.
+ fn cancelled(&self) -> bool {
+ false
+ }
+}
+
+/// An observer for a caller with no interface to report to.
+pub(crate) struct NoProgress;
+
+impl InstallObserver for NoProgress {
+ fn progress(&mut self, _event: InstallProgress) {}
+}
+
+/// A one-way flag the cancel action flips and the download loop reads.
+#[derive(Clone, Default, Debug)]
+pub(crate) struct CancelToken(Arc<AtomicBool>);
+
+impl CancelToken {
+ pub(crate) fn cancel(&self) {
+ self.0.store(true, Ordering::SeqCst);
+ }
+
+ pub(crate) fn is_cancelled(&self) -> bool {
+ self.0.load(Ordering::SeqCst)
+ }
+}
+
+/// The error a cancelled install ends with.
+///
+/// Its own marker, so the RPC layer can answer "you cancelled this" instead of
+/// an integrity or network failure, and the surface can close quietly.
+pub(crate) const CANCELLED: &str = "PLUGIN_CANCELLED: the install was cancelled";
+
+/// Whether an error is the user's own cancellation.
+pub(crate) fn is_cancelled(error: &anyhow::Error) -> bool {
+ error.to_string().starts_with("PLUGIN_CANCELLED")
+}
+
+/// Everything one download reports against.
+///
+/// Bundled so the download call sites stay readable: a package is fetched by
+/// mirror `attempt` of `attempts`, for a plugin, on behalf of an observer.
+pub(crate) struct DownloadReport<'a> {
+ pub observer: &'a mut dyn InstallObserver,
+ pub plugin_id: String,
+ pub version: String,
+ pub source: Option<String>,
+ pub attempt: u32,
+ pub attempts: u32,
+}
+
+impl<'a> DownloadReport<'a> {
+ pub(crate) fn new(
+ observer: &'a mut dyn InstallObserver,
+ plugin_id: &str,
+ version: &str,
+ ) -> Self {
+ Self {
+ observer,
+ plugin_id: plugin_id.to_string(),
+ version: version.to_string(),
+ source: None,
+ attempt: 0,
+ attempts: 0,
+ }
+ }
+
+ /// Point the report at one mirror of a list.
+ pub(crate) fn mirror(&mut self, source: Option<&str>, attempt: u32, attempts: u32) {
+ self.source = source.map(str::to_string);
+ self.attempt = attempt;
+ self.attempts = attempts;
+ }
+
+ /// A phase with no bytes to report.
+ pub(crate) fn phase(&mut self, phase: InstallPhase) {
+ let mut event = InstallProgress::phase(&self.plugin_id, &self.version, phase);
+ event.source = self.source.clone();
+ event.attempt = self.attempt;
+ event.attempts = self.attempts;
+ self.observer.progress(event);
+ }
+
+ /// Bytes received so far, out of the announced total (0 when unknown).
+ pub(crate) fn bytes(&mut self, received: u64, total: u64) {
+ let mut event =
+ InstallProgress::phase(&self.plugin_id, &self.version, InstallPhase::Download);
+ event.source = self.source.clone();
+ event.attempt = self.attempt;
+ event.attempts = self.attempts;
+ event.received_bytes = received;
+ event.total_bytes = total;
+ self.observer.progress(event);
+ }
+ /// Report the failure that ends the install, and hand it back.
+ ///
+ /// Exactly one terminal report per install: whoever knows the final error
+ /// reports it, so a surface showing progress is never told twice — or never
+ /// told at all.
+ pub(crate) fn failed(
+ &mut self,
+ tried: Vec<TriedMirror>,
+ error: anyhow::Error,
+ ) -> anyhow::Error {
+ let mut event =
+ InstallProgress::phase(&self.plugin_id, &self.version, InstallPhase::Download);
+ event.source = self.source.clone();
+ event.attempt = self.attempt;
+ event.attempts = self.attempts;
+ event.tried = tried;
+ event.error = Some(error.to_string());
+ self.observer.progress(event);
+ error
+ }
+
+ pub(crate) fn cancelled(&self) -> bool {
+ self.observer.cancelled()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[derive(Default)]
+ struct Recorder {
+ events: Vec<InstallProgress>,
+ cancel_after: Option<usize>,
+ }
+
+ impl InstallObserver for Recorder {
+ fn progress(&mut self, event: InstallProgress) {
+ self.events.push(event);
+ }
+
+ fn cancelled(&self) -> bool {
+ self.cancel_after
+ .is_some_and(|after| self.events.len() >= after)
+ }
+ }
+
+ #[test]
+ fn a_report_carries_the_mirror_it_is_about() {
+ let mut recorder = Recorder::default();
+ {
+ let mut report = DownloadReport::new(&mut recorder, "acme.todo", "1.2.0");
+ report.mirror(Some("cnb"), 2, 3);
+ report.bytes(120, 480);
+ report.phase(InstallPhase::Verify);
+ }
+ assert_eq!(recorder.events.len(), 2);
+ let bytes = &recorder.events[0];
+ assert_eq!(bytes.plugin_id, "acme.todo");
+ assert_eq!(bytes.phase, InstallPhase::Download);
+ assert_eq!(bytes.source.as_deref(), Some("cnb"));
+ assert_eq!((bytes.attempt, bytes.attempts), (2, 3));
+ assert_eq!((bytes.received_bytes, bytes.total_bytes), (120, 480));
+ assert_eq!(recorder.events[1].phase, InstallPhase::Verify);
+ }
+
+ #[test]
+ fn a_cancel_after_the_first_report_is_visible_to_the_install() {
+ let mut recorder = Recorder {
+ cancel_after: Some(1),
+ ..Recorder::default()
+ };
+ {
+ let mut report = DownloadReport::new(&mut recorder, "acme.todo", "1.2.0");
+ assert!(!report.cancelled(), "nothing reported yet");
+ report.bytes(1, 10);
+ assert!(
+ report.cancelled(),
+ "the user asked to stop after one report"
+ );
+ }
+ }
+
+ #[test]
+ fn only_a_cancellation_reads_as_one() {
+ let cancelled = anyhow!(CANCELLED);
+ assert!(is_cancelled(&cancelled));
+ assert!(!is_cancelled(&anyhow!(
+ "PLUGIN_INTEGRITY: checksum mismatch"
+ )));
+ }
+}
diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rs
index c600e1eea..e0ff84af2 100644
--- a/crates/host-core/src/plugins/providers/tests.rs
+++ b/crates/host-core/src/plugins/providers/tests.rs
@@ -489,7 +489,7 @@ fn startup_reconciliation_removes_a_row_whose_plugin_is_gone() {
secrets.set(&key_ref, "sk-demo").unwrap();
// No plugin is registered in this data directory, so the row has no owner
// to answer for it.
- let plugins = PluginManager::new(dir.path(), None);
+ let plugins = PluginManager::new(dir.path(), MarketChannel::Official, None);
assert_eq!(
crate::plugins::reconcile_all(&db, &secrets, &plugins).unwrap(),
1
diff --git a/crates/host-core/src/plugins/registry.rs b/crates/host-core/src/plugins/registry.rs
index 7b3db3981..75c057e36 100644
--- a/crates/host-core/src/plugins/registry.rs
+++ b/crates/host-core/src/plugins/registry.rs
@@ -23,8 +23,15 @@ pub struct PluginManager {
/// build stops shipping must stop being protected immediately, whatever the
/// row that survives it looks like.
pub(crate) bundled_ids: BTreeSet<String>,
- /// Catalog URL pinned by app settings; `None` keeps the official default.
- pub(crate) market_source: Option<String>,
+ /// Catalog channel pinned by app settings, and the URL for `custom`.
+ pub(crate) market_channel: MarketChannel,
+ pub(crate) market_custom_url: Option<String>,
+ /// Cancel token of the install currently running, when one is.
+ ///
+ /// The renderer's cancel action flips it and the download loop reads it.
+ /// Only one install runs at a time — the RPC that starts one holds the
+ /// state lock — so a single slot is enough.
+ pub(crate) install_cancel: Option<CancelToken>,
/// Locale a row's display fields are resolved against.
///
/// The desktop shell owns the app language — `settings.language`, or the
@@ -34,17 +41,23 @@ pub struct PluginManager {
}
impl PluginManager {
- /// Build a manager against a specific catalog source.
+ /// Build a manager against a specific catalog channel.
///
- /// The source is applied before the first catalog fetch so a mirror
- /// configured in settings is honoured on the very first launch, not only
- /// after an explicit refresh.
- pub fn new(data_dir: &Path, market_source: Option<String>) -> Self {
+ /// The channel is applied before the first catalog fetch so a non-default
+ /// source configured in settings is honoured on the very first launch, not
+ /// only after an explicit refresh.
+ pub fn new(
+ data_dir: &Path,
+ market_channel: MarketChannel,
+ market_custom_url: Option<String>,
+ ) -> Self {
let mut mgr = Self {
data_dir: data_dir.to_path_buf(),
runtime: Vec::new(),
bundled_ids: BTreeSet::new(),
- market_source,
+ market_channel,
+ market_custom_url,
+ install_cancel: None,
locale: "en".into(),
};
let _ = mgr.ensure_dirs();
diff --git a/crates/host-core/src/plugins/resolve.rs b/crates/host-core/src/plugins/resolve.rs
new file mode 100644
index 000000000..98eb6109d
--- /dev/null
+++ b/crates/host-core/src/plugins/resolve.rs
@@ -0,0 +1,333 @@
+//! The plugin center's download interface.
+//!
+//! The platform says where a package is and never carries its bytes. One call
+//! answers with the digest and every mirror that can serve the package; the
+//! client picks one and verifies what it got.
+//!
+//! Two kinds of failure are worth telling apart, because the caller answers
+//! them differently: a platform that could not be *reached* is covered by the
+//! catalog's own URL (the platform's contract says so explicitly), while a
+//! platform that *answered* has an opinion — not published, archived, unknown,
+//! rate limited — and papering over it would install something it is not
+//! offering.
+
+use super::*;
+
+/// One place a package can be fetched from.
+#[derive(Debug, Clone, Deserialize)]
+pub(crate) struct ResolvedMirror {
+ #[serde(default)]
+ pub source: String,
+ pub url: String,
+}
+
+/// Where a package can be fetched from, and the digest to check it against.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct ResolvedDownload {
+ pub sha256: String,
+ #[serde(default)]
+ pub size_bytes: u64,
+ #[serde(default)]
+ pub downloads: Vec<ResolvedMirror>,
+}
+
+/// Resolve endpoint for a catalog URL.
+///
+/// Built from the catalog's own origin, so the request cannot leave the host
+/// the catalog came from. A non-http(s) catalog — a local file a test or a
+/// developer pointed the environment override at — has no endpoint.
+pub(crate) fn endpoint_for(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];
+ // Credentials in the authority would make the request authenticate against
+ // a host the user never chose.
+ if authority.is_empty() || authority.contains('@') {
+ return None;
+ }
+ Some(format!("{scheme}://{authority}/api/v1/download/resolve"))
+}
+
+/// Ask the platform where a package is.
+pub(crate) fn request(
+ catalog_url: &str,
+ device_id: &str,
+ plugin_id: &str,
+ version: &str,
+) -> Result<ResolvedDownload> {
+ let endpoint = endpoint_for(catalog_url)
+ .ok_or_else(|| anyhow!("PLUGIN_NETWORK: {catalog_url} is not an http(s) catalog"))?;
+ let body = json!({
+ "deviceId": device_id,
+ "pluginId": plugin_id,
+ "version": version,
+ })
+ .to_string();
+ match resolve_once(&endpoint, &body) {
+ Ok(resolved) => Ok(resolved),
+ Err(Attempt::Failed(error)) => Err(error),
+ // The platform answers a caller that asks too often with the interval
+ // to wait. One retry is what its contract describes, and a longer loop
+ // would be the broken client the limit exists to catch.
+ Err(Attempt::RateLimited { wait, .. }) => {
+ std::thread::sleep(wait);
+ match resolve_once(&endpoint, &body) {
+ Ok(resolved) => Ok(resolved),
+ Err(Attempt::Failed(error)) | Err(Attempt::RateLimited { error, .. }) => Err(error),
+ }
+ }
+ }
+}
+
+/// What one resolve attempt produced.
+enum Attempt {
+ /// The platform could not answer, or answered something unusable.
+ Failed(anyhow::Error),
+ /// It answered `429` and named how long to wait.
+ RateLimited {
+ error: anyhow::Error,
+ wait: Duration,
+ },
+}
+
+/// One resolve request.
+fn resolve_once(endpoint: &str, body: &str) -> std::result::Result<ResolvedDownload, Attempt> {
+ let (status, payload, headers) = post_json(endpoint, body).map_err(Attempt::Failed)?;
+ if status != 200 {
+ let error = refusal(status, &payload);
+ if status == 429 {
+ return Err(Attempt::RateLimited {
+ error,
+ wait: retry_after(&headers).unwrap_or(Duration::from_secs(1)),
+ });
+ }
+ return Err(Attempt::Failed(error));
+ }
+ let resolved: ResolvedDownload = serde_json::from_slice(&payload).map_err(|error| {
+ Attempt::Failed(anyhow!(
+ "PLUGIN_MARKET_INVALID: the plugin center's answer is not readable: {error}"
+ ))
+ })?;
+ if resolved.sha256.trim().is_empty() {
+ return Err(Attempt::Failed(anyhow!(
+ "PLUGIN_MARKET_INVALID: the plugin center named no digest"
+ )));
+ }
+ if resolved.downloads.is_empty() {
+ return Err(Attempt::Failed(anyhow!(
+ "PLUGIN_MARKET_INVALID: the plugin center listed no download"
+ )));
+ }
+ Ok(resolved)
+}
+
+/// Seconds the platform asked the caller to wait, when it said so.
+///
+/// Clamped: a deployment may name a longer interval than an install should
+/// block on, and the platform's own default is sixty seconds.
+fn retry_after(headers: &str) -> Option<Duration> {
+ let value = headers.lines().find_map(|line| {
+ let (name, value) = line.split_once(':')?;
+ name.trim()
+ .eq_ignore_ascii_case("retry-after")
+ .then(|| value.trim())
+ })?;
+ let seconds: u64 = value.parse().ok()?;
+ Some(Duration::from_secs(seconds.clamp(1, 60)))
+}
+
+/// Whether a resolve failure is one the catalog's own URL may answer.
+///
+/// Only a transport failure or an unavailable deployment: those are the cases
+/// the platform's contract covers with "install from the catalog's URL". Every
+/// refusal keeps its own error so the surface can say what happened.
+pub(crate) fn is_recoverable(error: &anyhow::Error) -> bool {
+ error.to_string().starts_with("PLUGIN_NETWORK")
+}
+
+/// The error a non-2xx answer becomes.
+fn refusal(status: u16, payload: &[u8]) -> anyhow::Error {
+ let envelope: Option<Value> = serde_json::from_slice(payload).ok();
+ let error = envelope.as_ref().and_then(|value| value.get("error"));
+ let code = error
+ .and_then(|error| error.get("code"))
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ let message = 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");
+ let prefix = match code {
+ "NOT_PUBLISHED" => "PLUGIN_MARKET_NOT_PUBLISHED",
+ "PLUGIN_ARCHIVED" => "PLUGIN_MARKET_ARCHIVED",
+ "NOT_FOUND" => "PLUGIN_MARKET_NOT_FOUND",
+ "TOO_MANY_REQUESTS" => "PLUGIN_MARKET_RATE_LIMITED",
+ "NO_DOWNLOAD_SOURCE" => "PLUGIN_MARKET_NO_SOURCE",
+ "PLUGIN_REQUIRED" | "BAD_REQUEST" | "BAD_BODY" | "METHOD" => "PLUGIN_MARKET_INVALID",
+ // Anything else is a deployment that could not answer, which the
+ // catalog's own URL is allowed to cover.
+ _ => "PLUGIN_NETWORK",
+ };
+ anyhow!("{prefix}: the plugin center answered {status}: {message}")
+}
+
+/// POST a JSON body with curl.
+///
+/// Answers with the status, the response body and the response headers: the
+/// body carries the platform's error envelope, and the headers carry the
+/// interval a rate-limited caller is asked to wait. The body is written to a
+/// scratch file and the status is read from `--write-out`, so an error answer
+/// still yields the envelope instead of a curl diagnostic.
+fn post_json(url: &str, body: &str) -> Result<(u16, Vec<u8>, String)> {
+ let body_path = super::install::download_scratch_path();
+ let response_path = super::install::download_scratch_path();
+ let headers_path = super::install::download_scratch_path();
+ fs::write(&body_path, body).with_context(|| format!("write resolve body for {url}"))?;
+
+ let mut args: Vec<String> = vec![
+ "--silent".into(),
+ "--show-error".into(),
+ "--request".into(),
+ "POST".into(),
+ "--header".into(),
+ "Content-Type: application/json".into(),
+ "--header".into(),
+ "Accept: application/json".into(),
+ "--data-binary".into(),
+ format!("@{}", body_path.to_string_lossy()),
+ "--output".into(),
+ response_path.to_string_lossy().into_owned(),
+ // The retry interval arrives in a header, so the headers are kept.
+ "--dump-header".into(),
+ headers_path.to_string_lossy().into_owned(),
+ "--write-out".into(),
+ "%{http_code}".into(),
+ "--max-time".into(),
+ "30".into(),
+ "--max-redirs".into(),
+ "3".into(),
+ "--location".into(),
+ // Keep a redirect a POST: curl otherwise re-sends it as a GET, which the
+ // endpoint does answer but which would drop the body it reads.
+ "--post301".into(),
+ "--post302".into(),
+ "--post303".into(),
+ "--user-agent".into(),
+ "pi-desktop-host-core".into(),
+ ];
+ args.extend(crate::network_proxy::curl_proxy_args());
+ if url.starts_with("https://") {
+ args.push("--proto".into());
+ args.push("=https".into());
+ args.push("--proto-redir".into());
+ args.push("=https".into());
+ }
+ args.push(url.to_string());
+
+ let outcome = std::process::Command::new("curl").args(&args).output();
+ let result = 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 headers = fs::read_to_string(&headers_path).unwrap_or_default();
+ Ok((status, payload, headers))
+ }
+ Ok(output) => {
+ let err = decode_curl_output(&output.stderr);
+ Err(anyhow!(
+ "PLUGIN_NETWORK: resolve request failed for {url}: {err}"
+ ))
+ }
+ Err(error) => Err(anyhow!(
+ "PLUGIN_NETWORK: curl is required to reach the plugin center: {error}"
+ )),
+ };
+ let _ = fs::remove_file(&body_path);
+ let _ = fs::remove_file(&response_path);
+ let _ = fs::remove_file(&headers_path);
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_endpoint_keeps_the_catalogs_origin() {
+ assert_eq!(
+ endpoint_for("https://plugins.aiuo.net/catalog.json").as_deref(),
+ Some("https://plugins.aiuo.net/api/v1/download/resolve")
+ );
+ assert_eq!(
+ endpoint_for("http://127.0.0.1:8787/catalog.json").as_deref(),
+ Some("http://127.0.0.1:8787/api/v1/download/resolve"),
+ "a development deployment on a port keeps it"
+ );
+ assert_eq!(endpoint_for("file:///tmp/catalog.json"), None);
+ assert_eq!(
+ endpoint_for("https://user:[email protected]/catalog.json"),
+ None,
+ "a catalog url carrying credentials is not one to send a device id to"
+ );
+ }
+
+ #[test]
+ fn a_refusal_is_not_recoverable_and_a_dead_deployment_is() {
+ let refused = refusal(
+ 403,
+ br#"{"error":{"code":"NOT_PUBLISHED","message":"not yet"}}"#,
+ );
+ let text = refused.to_string();
+ assert!(text.starts_with("PLUGIN_MARKET_NOT_PUBLISHED"), "{text}");
+ assert!(!is_recoverable(&refused));
+
+ let archived = refusal(403, br#"{"error":{"code":"PLUGIN_ARCHIVED"}}"#);
+ assert!(archived.to_string().starts_with("PLUGIN_MARKET_ARCHIVED"));
+
+ let limited = refusal(429, br#"{"error":{"code":"TOO_MANY_REQUESTS"}}"#);
+ assert!(limited
+ .to_string()
+ .starts_with("PLUGIN_MARKET_RATE_LIMITED"));
+
+ let no_source = refusal(503, br#"{"error":{"code":"NO_DOWNLOAD_SOURCE"}}"#);
+ assert!(no_source.to_string().starts_with("PLUGIN_MARKET_NO_SOURCE"));
+
+ let down = refusal(502, b"<html>bad gateway</html>");
+ assert!(down.to_string().starts_with("PLUGIN_NETWORK"), "{down}");
+ assert!(is_recoverable(&down));
+
+ // A body this client mangled is its own defect: falling back to the
+ // catalog would install something the platform was never asked for.
+ let mangled = refusal(400, br#"{"error":{"code":"BAD_BODY"}}"#);
+ assert!(mangled.to_string().starts_with("PLUGIN_MARKET_INVALID"));
+ assert!(!is_recoverable(&mangled));
+ }
+
+ #[test]
+ fn a_rate_limit_waits_what_the_platform_asked_for() {
+ let headers = "HTTP/1.1 429 Too Many Requests\r\nRetry-After: 12\r\n\r\n";
+ assert_eq!(retry_after(headers), Some(Duration::from_secs(12)));
+ // The header name is case-insensitive and the value may carry spaces.
+ assert_eq!(
+ retry_after("retry-after: 7 \r\n"),
+ Some(Duration::from_secs(7))
+ );
+ // A deployment may ask for longer than an install should block on.
+ assert_eq!(
+ retry_after("Retry-After: 600\r\n"),
+ Some(Duration::from_secs(60))
+ );
+ // No header, or one that is not a number of seconds: wait the minimum.
+ assert_eq!(retry_after("HTTP/1.1 429\r\n\r\n"), None);
+ assert_eq!(retry_after("Retry-After: soon\r\n"), None);
+ }
+}
diff --git a/crates/host-core/src/plugins/tests.rs b/crates/host-core/src/plugins/tests.rs
index 98b583748..ba34c61cc 100644
--- a/crates/host-core/src/plugins/tests.rs
+++ b/crates/host-core/src/plugins/tests.rs
@@ -37,7 +37,7 @@ fn install_market_package_and_check_update_metadata() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
}
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
let search = mgr.market_search(Some("hello"), None).unwrap();
assert!(!search.is_empty());
let installed = mgr
@@ -76,7 +76,7 @@ fn marketplace_install_refreshes_catalog_before_checksum_verification() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
}
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
let package_bytes = bundled_package_bytes("demo.hello", "0.2.0").unwrap();
let package_path = dir.path().join("fresh-demo.hello.piplug");
fs::write(&package_path, &package_bytes).unwrap();
@@ -131,7 +131,7 @@ fn marketplace_uses_highest_semver_when_catalog_versions_are_unsorted() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
}
- let mgr = PluginManager::new(dir.path(), None);
+ let mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
let entry = MarketCatalogEntry {
id: "pi.todo".into(),
name: "Fresh Todo".into(),
@@ -210,7 +210,7 @@ fn market_entry_offers_an_update_only_when_the_catalog_is_newer() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
}
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
mgr.sync_builtin(Some(ship.path())).unwrap();
assert_eq!(mgr.get("pi.todo").unwrap().version, "0.6.0");
@@ -256,7 +256,7 @@ fn announced_version_without_a_package_is_visible_but_not_installable() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
}
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
mgr.install_from_market("demo.hello", None, true, true, None)
.unwrap();
@@ -313,7 +313,7 @@ fn silent_update_check_uses_cached_catalog_without_refreshing_remote() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
}
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
mgr.install_from_market("demo.hello", None, true, false, None)
.unwrap();
@@ -367,7 +367,7 @@ fn package_path_traversal_rejected() {
let bad = make_zip(&[("../evil.js", b"alert(1)")]);
let pkg = dir.path().join("bad.piplug");
fs::write(&pkg, bad).unwrap();
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
let err = mgr
.install_from_package(
pkg.to_str().unwrap(),
@@ -400,7 +400,7 @@ fn high_risk_permissions_roundtrip_on_notes_plugin() {
if packages_dir.exists() {
let _ = fs::remove_dir_all(&packages_dir);
}
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
let installed = mgr
.install_from_market("demo.workspace-notes", None, true, false, None)
.unwrap();
@@ -420,21 +420,21 @@ fn high_risk_permissions_roundtrip_on_notes_plugin() {
#[test]
fn resolve_relative_package_urls_against_catalog() {
let resolved = PluginManager::resolve_package_url(
- "https://raw.githubusercontent.com/vastsa/pi-desktop-plugins/main/catalog.json",
+ GITHUB_BACKUP_CHANNEL_CATALOG_URL,
None,
"packages/demo.hello-0.2.0.piplug",
);
assert_eq!(
- resolved,
- "https://raw.githubusercontent.com/vastsa/pi-desktop-plugins/main/packages/demo.hello-0.2.0.piplug"
- );
+ resolved,
+ "https://raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main/packages/demo.hello-0.2.0.piplug"
+ );
}
#[test]
-fn refresh_catalog_from_official_repo_when_network_available() {
+fn refresh_catalog_from_the_github_backup_when_network_available() {
let _guard = lock_market_env();
// Skip cleanly if offline / rate-limited.
- let url = "https://raw.githubusercontent.com/vastsa/pi-desktop-plugins/main/catalog.json";
+ let url = GITHUB_BACKUP_CHANNEL_CATALOG_URL;
if download_url(url).is_err() {
return;
}
@@ -443,51 +443,131 @@ fn refresh_catalog_from_official_repo_when_network_available() {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
std::env::set_var("PI_DESKTOP_PLUGIN_MARKET_URL", url);
}
- let mgr = PluginManager::new(dir.path(), None);
- let meta = mgr.refresh_market(true).expect("remote catalog");
+ let mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
+ let Ok(meta) = mgr.refresh_market(true) else {
+ // The repository answered the probe above and then rate limited or
+ // dropped the real refresh: a network hiccup is not a client defect.
+ return;
+ };
assert_eq!(meta["providerId"], "official");
assert!(meta["pluginCount"].as_u64().unwrap_or(0) >= 1);
assert!(meta["sourceUrl"]
.as_str()
.unwrap_or("")
.contains("pi-desktop-plugins"));
- let search = mgr.market_search(Some("hello"), None).unwrap();
- assert!(search.iter().any(|p| p.id == "demo.hello"));
+ // Which plugins the repository publishes is the publisher's business; that
+ // the catalog is readable and reaches the search path is the client's.
+ let search = mgr.market_search(None, None).unwrap();
+ assert!(
+ !search.is_empty(),
+ "a published catalog lists at least one installable plugin"
+ );
unsafe {
std::env::remove_var("PI_DESKTOP_DATA_DIR");
std::env::remove_var("PI_DESKTOP_PLUGIN_MARKET_URL");
}
}
+/// The official channel's install path, against the deployment that serves it.
+///
+/// Everything the test needs comes from the published catalog, so it does not
+/// pin a version a later release removes. It skips when the platform or the
+/// catalog cannot be reached, like the refresh above: the unit suite has to stay
+/// green on a machine with no route to either.
+#[test]
+fn the_plugin_center_resolves_a_published_package() {
+ let _guard = lock_market_env();
+ let Ok(bytes) = download_url(OFFICIAL_CHANNEL_CATALOG_URL) else {
+ return;
+ };
+ let catalog: MarketCatalogFile =
+ serde_json::from_slice(&bytes).expect("the published catalog parses");
+ // A device id of the shape the platform is sent, so a failure here is the
+ // interface's and not the identifier's.
+ let device = "0".repeat(64);
+ for plugin in &catalog.plugins {
+ for version in &plugin.versions {
+ if version.shasum.trim().is_empty() {
+ continue;
+ }
+ let Ok(resolved) = super::resolve::request(
+ OFFICIAL_CHANNEL_CATALOG_URL,
+ &device,
+ &plugin.id,
+ &version.version,
+ ) else {
+ // Not published yet, withdrawn since, or the deployment cannot
+ // answer: none of those is what this test is about.
+ continue;
+ };
+ assert_eq!(
+ resolved.sha256.trim().to_ascii_lowercase(),
+ version.shasum.trim().to_ascii_lowercase(),
+ "the platform answers with the digest the catalog carries for {}",
+ plugin.id
+ );
+ assert!(
+ !resolved.downloads.is_empty(),
+ "a 200 carries at least one mirror for {}",
+ plugin.id
+ );
+ for mirror in &resolved.downloads {
+ assert!(
+ mirror.url.starts_with("https://"),
+ "a mirror is fetched over https: {}",
+ mirror.url
+ );
+ }
+ return;
+ }
+ }
+}
+
#[test]
-fn market_source_from_settings_selects_the_configured_provider() {
- assert_eq!(market_source_from_settings(None), None);
- assert_eq!(market_source_from_settings(Some(&json!({}))), None);
- // `official` stays on the built-in default rather than pinning a URL,
- // so a later default change reaches users who never switched.
+fn market_channel_from_settings_selects_the_configured_channel() {
+ // Nothing saved, and the legacy `official`, both mean the official channel:
+ // it is the default, so a later default change reaches a user who never
+ // switched away.
assert_eq!(
- market_source_from_settings(Some(&json!({"pluginMarketSource": "official"}))),
- None
+ market_channel_from_settings(None).0,
+ MarketChannel::Official
);
assert_eq!(
- market_source_from_settings(Some(&json!({"pluginMarketSource": "mirror"}))).as_deref(),
- Some(MIRROR_MARKET_CATALOG_URL)
+ market_channel_from_settings(Some(&json!({}))).0,
+ MarketChannel::Official
);
assert_eq!(
- market_source_from_settings(Some(&json!({
- "pluginMarketSource": "custom",
- "pluginMarketCustomUrl": " https://example.test/catalog.json ",
- })))
- .as_deref(),
- Some("https://example.test/catalog.json")
+ market_channel_from_settings(Some(&json!({"pluginMarketSource": "official"}))).0,
+ MarketChannel::Official
+ );
+ // An unrecognised value falls back to the official channel rather than
+ // stranding the marketplace on an empty endpoint.
+ assert_eq!(
+ market_channel_from_settings(Some(&json!({"pluginMarketSource": "nonsense"}))).0,
+ MarketChannel::Official
);
- // A custom source with no URL must not strand the marketplace on an
+ assert_eq!(
+ market_channel_from_settings(Some(&json!({"pluginMarketSource": "github"}))).0,
+ MarketChannel::Github
+ );
+ assert_eq!(
+ market_channel_from_settings(Some(&json!({"pluginMarketSource": "mirror"}))).0,
+ MarketChannel::Mirror
+ );
+ let (channel, url) = market_channel_from_settings(Some(&json!({
+ "pluginMarketSource": "custom",
+ "pluginMarketCustomUrl": " https://example.test/catalog.json ",
+ })));
+ assert_eq!(channel, MarketChannel::Custom);
+ assert_eq!(url.as_deref(), Some("https://example.test/catalog.json"));
+ // A custom channel with no URL must not strand the marketplace on an
// empty endpoint.
assert_eq!(
- market_source_from_settings(Some(&json!({
+ market_channel_from_settings(Some(&json!({
"pluginMarketSource": "custom",
"pluginMarketCustomUrl": " ",
- }))),
+ })))
+ .1,
None
);
}
@@ -499,11 +579,11 @@ fn cached_catalog_is_scoped_to_the_source_that_fetched_it() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
}
- let mgr = PluginManager::new(dir.path(), None);
+ let mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
// A bundled offline snapshot records no source and stays usable
// whichever provider is selected.
let _ = fs::remove_file(mgr.market_cache_meta_path());
- assert!(mgr.cached_catalog_matches_source(OFFICIAL_MARKET_CATALOG_URL));
+ assert!(mgr.cached_catalog_matches_source(OFFICIAL_CHANNEL_CATALOG_URL));
assert!(mgr.cached_catalog_matches_source(MIRROR_MARKET_CATALOG_URL));
fs::create_dir_all(dir.path().join("plugins/market")).unwrap();
@@ -513,7 +593,7 @@ fn cached_catalog_is_scoped_to_the_source_that_fetched_it() {
)
.unwrap();
assert!(mgr.cached_catalog_matches_source(MIRROR_MARKET_CATALOG_URL));
- assert!(!mgr.cached_catalog_matches_source(OFFICIAL_MARKET_CATALOG_URL));
+ assert!(!mgr.cached_catalog_matches_source(OFFICIAL_CHANNEL_CATALOG_URL));
});
}
@@ -525,7 +605,7 @@ fn switching_source_ignores_the_previous_providers_snapshot() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
}
- let mgr = PluginManager::new(dir.path(), None);
+ let mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
// A snapshot carrying a plugin the built-in catalog does not have,
// written while a different provider was selected.
@@ -659,7 +739,7 @@ fn accepts_and_summarizes_new_contributions() {
unsafe {
std::env::set_var("PI_DESKTOP_DATA_DIR", data.path());
}
- let mut mgr = PluginManager::new(data.path(), None);
+ let mut mgr = PluginManager::new(data.path(), MarketChannel::Official, None);
let summary = mgr.load_dev(root.to_str().unwrap()).unwrap();
assert!(summary.capabilities.contains(&"mcp".to_string()));
assert!(summary.capabilities.contains(&"bus".to_string()));
@@ -925,7 +1005,7 @@ fn bundled_plugins_refresh_from_disk_but_keep_user_state() {
);
let data = tempdir().unwrap();
- let mut mgr = PluginManager::new(data.path(), None);
+ let mut mgr = PluginManager::new(data.path(), MarketChannel::Official, None);
mgr.sync_builtin(Some(ship.path())).unwrap();
let listed = mgr.get("pi.files").expect("bundled plugin is registered");
@@ -979,7 +1059,7 @@ fn bundled_plugin_can_default_to_disabled_without_overwriting_user_state() {
);
let data = tempdir().unwrap();
- let mut mgr = PluginManager::new(data.path(), None);
+ let mut mgr = PluginManager::new(data.path(), MarketChannel::Official, None);
mgr.sync_builtin(Some(ship.path())).unwrap();
let listed = mgr.get("pi.opt-in").expect("bundled plugin is registered");
assert!(!listed.enabled, "opt-in bundled plugins start disabled");
@@ -1015,7 +1095,7 @@ fn a_bundled_plugin_keeps_the_update_the_user_installed() {
write_plugin(&shipped, shipped_manifest("1.0.0"), &[]);
let data = tempdir().unwrap();
- let mut mgr = PluginManager::new(data.path(), None);
+ let mut mgr = PluginManager::new(data.path(), MarketChannel::Official, None);
mgr.sync_builtin(Some(ship.path())).unwrap();
assert!(mgr.get("pi.view").unwrap().bundled);
@@ -1038,7 +1118,7 @@ fn a_bundled_plugin_keeps_the_update_the_user_installed() {
);
// The next launch reconciles against the shipped 1.0.0 again.
- let mut mgr = PluginManager::new(data.path(), None);
+ let mut mgr = PluginManager::new(data.path(), MarketChannel::Official, None);
mgr.sync_builtin(Some(ship.path())).unwrap();
let after = mgr.get("pi.view").unwrap();
assert_eq!(
@@ -1077,7 +1157,7 @@ fn a_newer_shipped_version_replaces_an_older_user_install() {
write_plugin(&shipped, manifest("1.0.0"), &[]);
let data = tempdir().unwrap();
- let mut mgr = PluginManager::new(data.path(), None);
+ let mut mgr = PluginManager::new(data.path(), MarketChannel::Official, None);
mgr.sync_builtin(Some(ship.path())).unwrap();
let update = data.path().join("package");
@@ -1121,7 +1201,7 @@ fn a_plugin_a_build_stops_shipping_is_no_longer_bundled() {
write_plugin(&shipped, manifest("1.0.0"), &[]);
let data = tempdir().unwrap();
- let mut mgr = PluginManager::new(data.path(), None);
+ let mut mgr = PluginManager::new(data.path(), MarketChannel::Official, None);
mgr.sync_builtin(Some(ship.path())).unwrap();
let update = data.path().join("package");
@@ -1267,7 +1347,7 @@ fn a_project_scope_survives_a_reload_and_a_reinstall() {
&[],
);
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
let installed = mgr
.install_from_path(
source.to_str().unwrap(),
@@ -1299,7 +1379,7 @@ fn a_project_scope_survives_a_reload_and_a_reinstall() {
assert!(!disabled.enabled);
assert_eq!(disabled.scope.projects, vec!["/work/api".to_string()]);
- let reloaded = PluginManager::new(dir.path(), None);
+ let reloaded = PluginManager::new(dir.path(), MarketChannel::Official, None);
let after = reloaded.get("demo.scoped").expect("plugin missing");
assert_eq!(after.scope.mode, ActivationMode::Projects);
assert_eq!(after.scope.projects, vec!["/work/api".to_string()]);
@@ -1307,7 +1387,7 @@ fn a_project_scope_survives_a_reload_and_a_reinstall() {
// Reinstalling over the top is an update, not a reset: widening a
// project-scoped plugin back to everywhere would hand it reach the user
// never granted.
- let mut mgr = PluginManager::new(dir.path(), None);
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
let again = mgr
.install_from_path(
source.to_str().unwrap(),
@@ -1347,7 +1427,7 @@ fn offline_manager(dir: &Path) -> PluginManager {
.unwrap(),
)
.unwrap();
- PluginManager::new(dir, None)
+ PluginManager::new(dir, MarketChannel::Official, None)
}
/// Build a catalog v2 entry with one live and one withdrawn version.
@@ -1478,19 +1558,20 @@ fn relative_package_urls_resolve_against_the_declared_artifact_base() {
);
}
-/// The distribution repository serves `catalog.json` from its root and
-/// packages from `packages/`, and the CNB copy is a Git mirror of it. Both
-/// therefore work with a relative URL and no declared base, which is the
-/// reason moving publishing into the plugin center needs no client change.
+/// The backup channels serve `catalog.json` from their tree root and packages
+/// from `packages/`, so a relative URL needs no declared base. The official
+/// channel does not use this path at all: an install asks the plugin center
+/// where the package is.
#[test]
-fn official_and_mirror_sources_each_resolve_their_own_packages() {
+fn backup_channels_each_resolve_their_own_packages() {
let relative = "packages/acme.todo-1.0.0.piplug";
- let github = PluginManager::resolve_package_url(OFFICIAL_MARKET_CATALOG_URL, None, relative);
+ let github =
+ PluginManager::resolve_package_url(GITHUB_BACKUP_CHANNEL_CATALOG_URL, None, relative);
assert_eq!(
- github,
- "https://raw.githubusercontent.com/vastsa/pi-desktop-plugins/main/packages/acme.todo-1.0.0.piplug"
- );
+ github,
+ "https://raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main/packages/acme.todo-1.0.0.piplug"
+ );
let mirror = PluginManager::resolve_package_url(MIRROR_MARKET_CATALOG_URL, None, relative);
assert_eq!(
@@ -1500,9 +1581,9 @@ fn official_and_mirror_sources_each_resolve_their_own_packages() {
// Neither resolution leaves the source the user picked, and both hosts
// are ones the download boundary already accepts.
- package_host_allowed(&github, OFFICIAL_MARKET_CATALOG_URL).unwrap();
+ package_host_allowed(&github, GITHUB_BACKUP_CHANNEL_CATALOG_URL).unwrap();
package_host_allowed(&mirror, MIRROR_MARKET_CATALOG_URL).unwrap();
- assert!(github.starts_with("https://raw.githubusercontent.com/"));
+ assert!(github.starts_with("https://raw.githubusercontent.com/AIUO-Net/"));
assert!(mirror.starts_with("https://cnb.cool/"));
}
@@ -1589,7 +1670,7 @@ fn verified_trust_is_honoured_only_from_the_official_source() {
// flaky.
// Safety: test-only process env mutation, serialized by the market lock.
unsafe {
- std::env::set_var("PI_DESKTOP_PLUGIN_MARKET_URL", OFFICIAL_MARKET_CATALOG_URL);
+ std::env::set_var("PI_DESKTOP_PLUGIN_MARKET_URL", OFFICIAL_CHANNEL_CATALOG_URL);
}
let official = offline_manager(dir.path());
assert_eq!(official.resolve_trust(&v2_entry()), "verified");
@@ -1901,7 +1982,7 @@ fn the_registry_never_persists_the_i18n_block() {
// A restart re-reads each manifest, so rows are localized again without
// the registry having carried anything.
- let mut reloaded = PluginManager::new(dir.path(), None);
+ let mut reloaded = PluginManager::new(dir.path(), MarketChannel::Official, None);
reloaded.set_locale("zh-CN");
assert_eq!(reloaded.get("acme.stored").unwrap().name, "已存");
}
@@ -1967,3 +2048,81 @@ fn market_cards_and_details_read_the_catalog_i18n_block() {
Some("Reads nothing else")
);
}
+
+/// An install reports the phases it passes through, and a user who cancels
+/// stops it before anything is written.
+#[test]
+fn an_install_reports_progress_and_honours_a_cancel() {
+ #[derive(Default)]
+ struct InstallLog {
+ phases: Vec<&'static str>,
+ bytes: Vec<(u64, u64)>,
+ errors: Vec<String>,
+ }
+
+ impl InstallObserver for InstallLog {
+ fn progress(&mut self, event: InstallProgress) {
+ self.phases.push(event.phase.as_str());
+ if event.received_bytes > 0 {
+ self.bytes.push((event.received_bytes, event.total_bytes));
+ }
+ if let Some(error) = event.error {
+ self.errors.push(error);
+ }
+ }
+ }
+
+ struct CancelAfterFirstReport {
+ seen: usize,
+ }
+
+ impl InstallObserver for CancelAfterFirstReport {
+ fn progress(&mut self, _event: InstallProgress) {
+ self.seen += 1;
+ }
+
+ fn cancelled(&self) -> bool {
+ self.seen > 0
+ }
+ }
+
+ with_local_market(|| {
+ let dir = tempdir().unwrap();
+ unsafe {
+ std::env::set_var("PI_DESKTOP_DATA_DIR", dir.path());
+ }
+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);
+
+ let mut log = InstallLog::default();
+ let installed = mgr
+ .install_from_market_observed("demo.workspace-notes", None, true, false, None, &mut log)
+ .expect("the fixture package installs");
+ assert_eq!(installed.plugin.id, "demo.workspace-notes");
+ // The fixture catalog serves a local package, so resolution is skipped
+ // and the phases are the ones a download has: bytes, verify, install.
+ for phase in ["download", "verify", "install"] {
+ assert!(
+ log.phases.contains(&phase),
+ "{phase} missing from {:?}",
+ log.phases
+ );
+ }
+ assert!(
+ log.bytes
+ .iter()
+ .any(|(received, total)| *received > 0 && *total >= *received),
+ "bytes were reported against the announced size: {:?}",
+ log.bytes
+ );
+ assert!(log.errors.is_empty(), "{:?}", log.errors);
+
+ // A cancel that arrives while the bytes arrive stops the install before
+ // it is verified, written or registered.
+ let mut cancelling = CancelAfterFirstReport { seen: 0 };
+ let error = mgr
+ .install_from_market_observed("demo.hello", None, true, false, None, &mut cancelling)
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("PLUGIN_CANCELLED"), "{error}");
+ });
+}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 48a3594c1..c51666a63 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -927,7 +927,8 @@ fn resolve_plan_workspace_if_available(
Ok(resolve_persisted_project_workspace(state, session_id)?.map(PathBuf::from))
}
-async fn emit_notification(tx: &mpsc::UnboundedSender<String>, method: &str, params: Value) {
+/// Push one notification line to the caller's stream.
+fn send_notification(tx: &mpsc::UnboundedSender<String>, method: &str, params: Value) {
let note = JsonRpcNotification {
jsonrpc: "2.0",
method: method.to_string(),
@@ -938,6 +939,71 @@ async fn emit_notification(tx: &mpsc::UnboundedSender<String>, method: &str, par
}
}
+async fn emit_notification(tx: &mpsc::UnboundedSender<String>, method: &str, params: Value) {
+ send_notification(tx, method, params);
+}
+
+/// Reports install progress to the renderer, and reads the cancel flag.
+///
+/// Throttled on purpose: an install reports every chunk of bytes it sees, and
+/// an interface needs a few of those per second rather than thousands. A phase
+/// change and the terminal report always go through, so a dialog never misses
+/// the transition it is displaying.
+struct RpcInstallObserver {
+ tx: mpsc::UnboundedSender<String>,
+ cancel: crate::plugins::CancelToken,
+ last: Option<std::time::Instant>,
+ last_phase: Option<crate::plugins::InstallPhase>,
+}
+
+impl crate::plugins::InstallObserver for RpcInstallObserver {
+ fn progress(&mut self, event: crate::plugins::InstallProgress) {
+ const MIN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(200);
+ let phase_changed = self.last_phase != Some(event.phase);
+ let terminal = event.error.is_some();
+ let due = self
+ .last
+ .map(|at| at.elapsed() >= MIN_INTERVAL)
+ .unwrap_or(true);
+ if !phase_changed && !terminal && !due {
+ return;
+ }
+ self.last = Some(std::time::Instant::now());
+ self.last_phase = Some(event.phase);
+ let tried: Vec<Value> = event
+ .tried
+ .iter()
+ .map(|mirror| {
+ json!({
+ "source": mirror.source,
+ "url": mirror.url,
+ "error": mirror.error,
+ })
+ })
+ .collect();
+ send_notification(
+ &self.tx,
+ "plugin.installProgress",
+ json!({
+ "pluginId": event.plugin_id,
+ "version": event.version,
+ "phase": event.phase.as_str(),
+ "source": event.source,
+ "attempt": event.attempt,
+ "attempts": event.attempts,
+ "receivedBytes": event.received_bytes,
+ "totalBytes": event.total_bytes,
+ "tried": tried,
+ "error": event.error,
+ }),
+ );
+ }
+
+ fn cancelled(&self) -> bool {
+ self.cancel.is_cancelled()
+ }
+}
+
async fn wait_for_bash_cancellation(
receiver: &mut Option<tokio::sync::watch::Receiver<bool>>,
) -> bool {
@@ -1066,6 +1132,22 @@ fn plugin_err(err: impl ToString) -> JsonRpcError {
rpc_err(1013, msg, "PLUGIN_PERMISSION_DENIED")
} else if msg.contains("PLUGIN_NOT_FOUND") {
rpc_err(1003, msg, "NOT_FOUND")
+ } else if msg.contains("PLUGIN_CANCELLED") {
+ // The user's own action rather than a failure: the surface closes the
+ // dialog quietly instead of reporting an error.
+ rpc_err(1019, msg, "PLUGIN_CANCELLED")
+ } else if msg.contains("PLUGIN_MARKET_NOT_PUBLISHED") {
+ // The platform has the version and is not offering it yet: a state to
+ // report, not a bug to sweep into INTERNAL.
+ rpc_err(1020, msg, "PLUGIN_MARKET_NOT_PUBLISHED")
+ } else if msg.contains("PLUGIN_MARKET_ARCHIVED") {
+ rpc_err(1021, msg, "PLUGIN_MARKET_ARCHIVED")
+ } else if msg.contains("PLUGIN_MARKET_NOT_FOUND") {
+ rpc_err(1022, msg, "PLUGIN_MARKET_NOT_FOUND")
+ } else if msg.contains("PLUGIN_MARKET_RATE_LIMITED") {
+ 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_NETWORK") {
rpc_err(1014, msg, "PLUGIN_NETWORK")
} else {
@@ -1654,11 +1736,12 @@ async fn handle_request(
st.db
.set_setting("app", &settings)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- // Re-pin the marketplace source in memory. Fetching here would hold
+ // Re-pin the marketplace channel in memory. Fetching here would hold
// the state lock behind a remote timeout, so the renderer triggers
- // `market.refresh` after switching sources.
- let market_source = crate::plugins::market_source_from_settings(Some(&settings));
- st.plugins.set_market_source(market_source);
+ // `market.refresh` after switching channels.
+ let (channel, custom_url) =
+ crate::plugins::market_channel_from_settings(Some(&settings));
+ st.plugins.set_market_channel(channel, custom_url);
// A concrete app language pins the plugin display locale here, so a
// shell that only writes settings still gets localized plugin rows.
// `auto` is resolved by the shell and pushed through
@@ -4348,13 +4431,46 @@ async fn handle_request(
.get("grantedPermissions")
.cloned()
.and_then(|v| serde_json::from_value::<Vec<String>>(v).ok());
+ // An install outlives one request from the interface's point of
+ // view: it resolves where the package is, downloads it from one
+ // mirror after another, verifies it and registers it. Every one of
+ // those steps is worth showing, which is what the observer does,
+ // and the token is what the cancel channel flips.
+ let cancel = crate::plugins::CancelToken::default();
+ let mut observer = RpcInstallObserver {
+ tx: tx.clone(),
+ cancel: cancel.clone(),
+ last: None,
+ last_phase: None,
+ };
let mut st = state.lock().await;
- let result = st
- .plugins
- .install_from_market(id, version, enable, auto_update, granted)
- .map_err(plugin_err)?;
+ st.plugins.set_install_cancel(Some(cancel));
+ let outcome = st.plugins.install_from_market_observed(
+ id,
+ version,
+ enable,
+ auto_update,
+ granted,
+ &mut observer,
+ );
+ // Whatever happened, nothing is cancellable any more: a token left
+ // in place would answer the next cancel for an install that is
+ // already over.
+ st.plugins.set_install_cancel(None);
+ let result = outcome.map_err(plugin_err)?;
Ok(json!({ "result": result }))
}
+ "market.cancelInstall" => {
+ let id = params
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
+ let st = state.lock().await;
+ // Answer whether an install was actually cancelled rather than
+ // letting the surface assume the click did something.
+ let cancelled = st.plugins.cancel_install();
+ Ok(json!({ "cancelled": cancelled, "id": id }))
+ }
"market.checkUpdates" => {
let refresh_remote = params
.get("refreshRemote")
diff --git a/crates/host-core/src/state.rs b/crates/host-core/src/state.rs
index aa760a168..8c100ebe4 100644
--- a/crates/host-core/src/state.rs
+++ b/crates/host-core/src/state.rs
@@ -94,15 +94,14 @@ impl AppState {
Err(error) => tracing::warn!(%error, "in-flight reply sweep failed"),
}
let secrets = SecretStore::open(data_dir)?;
- // The marketplace source is read before the manager builds its first
- // catalog, so a mirror configured for networks without GitHub access
+ // The marketplace channel is read before the manager builds its first
+ // catalog, so a source configured for networks without GitHub access
// applies on launch instead of only after a manual refresh.
let app_settings = db.get_setting("app").unwrap_or_default();
crate::network_proxy::apply_from_settings(app_settings.as_ref());
- let plugins = PluginManager::new(
- data_dir,
- crate::plugins::market_source_from_settings(app_settings.as_ref()),
- );
+ let (channel, custom_url) =
+ crate::plugins::market_channel_from_settings(app_settings.as_ref());
+ let plugins = PluginManager::new(data_dir, channel, custom_url);
// Provider rows a plugin declared are rebuilt from the registry on
// launch, so the table matches the enabled plugins whatever path
// (install, enable, an upgraded manifest) last changed them.
diff --git a/docs/adr/0274-official-plugin-channel-and-backup-channels.md b/docs/adr/0274-official-plugin-channel-and-backup-channels.md
new file mode 100644
index 000000000..16282d4b4
--- /dev/null
+++ b/docs/adr/0274-official-plugin-channel-and-backup-channels.md
@@ -0,0 +1,238 @@
+# ADR 0274: Official plugin channel and backup channels
+
+- Status: Accepted for implementation
+- Date: 2026-09-17
+- Deciders: PI-Desktop plugin and distribution maintainers
+- Related: ADR 0102, D238, E2E-024P, E2E-PLUGIN-official-channel-resolves-through-the-platform
+
+## Context
+
+The client's marketplace source was a three-value union — `official`, `mirror`,
+`custom` — mapped to hardcoded catalog URLs, and `official` was
+indistinguishable from "never set": both landed on the GitHub default. A
+package was fetched by joining the catalog's relative `url` onto
+`artifactBaseUrl` or the catalog directory, and the `verified` trust tier was
+recognized only while the catalog URL equaled one of two constants.
+
+Since ADR 0102 the plugin center at `plugins.aiuo.net` is the publishing
+authority, and it defines the client-facing download contract:
+
+```text
+GET /catalog.json the catalog the client reads
+POST /api/v1/download/resolve JSON { deviceId, pluginId, version? }
+ -> 200 { sha256, sizeBytes, downloads[] }
+ Cache-Control: no-store
+GET /download/{id}/{version} byte route for the marketplace page and
+ console; not the client's path
+```
+
+The platform's own rules, verified against production: it never hosts the bytes
+of a published package, only answers where they are; `downloads` is ordered and
+never empty on `200`; a client calls resolve once per install or update, sends a
+**stable** device identifier, never caches the answer, verifies `sha256` before
+installing, and tries the next mirror when one fails; `counted: false` is normal;
+rate limiting is per device identifier (otherwise per source address), 600
+requests per minute by default, with `429` and `Retry-After`; refusals are
+`400 PLUGIN_REQUIRED`, `403 NOT_PUBLISHED`, `403 PLUGIN_ARCHIVED`,
+`404 NOT_FOUND`, `429`, and `503 NO_DOWNLOAD_SOURCE`; and a platform-unreachable
+install falls back to the catalog's URL and is not counted. Counting identity is
+the device identifier, the platform stores counts rather than identities, and
+the optional `source` field is a statistics hint only.
+
+Measured on the same day: the catalog declares
+`artifactBaseUrl = raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main`;
+all three mirrors answered `200` and every mirror host is already inside the
+client's download allowlist; the CNB mirror still served an older distribution
+(22 plugins, and `pi.todo-0.6.5` at 92487 bytes where the other mirror served
+92951 bytes). A version string may contain `+` (for example `0.3.0+0.2.0`), so
+the platform's byte route cannot be assumed to carry every published version.
+
+The client's source model therefore has to become "the center first, the two Git
+hosts as backups", and the install path has to follow the platform's contract.
+
+## Decision
+
+### 1. Four channels, and `official` keeps its meaning
+
+| # | Channel | Value | Catalog URL | Install path |
+| --- | --- | --- | --- | --- |
+| 1 | Official channel | `official` (default) | `https://plugins.aiuo.net/catalog.json` | Platform resolve |
+| 2 | GitHub backup | `github` (new) | `https://raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main/catalog.json` | Static relative URL |
+| 3 | CNB backup | `mirror` (unchanged) | `https://cnb.cool/aixk/pi-desktop-plugins/-/git/raw/main/catalog.json` | Static relative URL |
+| 4 | Custom | `custom` (unchanged) | user-provided | Static relative URL |
+
+`official` keeps meaning "the project's own first-party channel" and now points
+at the center, so an unset value and an unrecognized value resolve to it and no
+persisted setting is migrated. `mirror` keeps meaning CNB; `github` is new
+because the GitHub backup no longer is the default. Display names are
+localized — Official channel / GitHub backup / CNB backup / Custom in English.
+A package URL never crosses providers: whichever channel served the catalog also
+serves the package.
+
+### 2. The official channel resolves through the platform
+
+1. Refresh the catalog, then `POST {center origin}/api/v1/download/resolve` with
+ `{ deviceId, pluginId, version }` — once per install or update. POST rather
+ than GET, because the platform documents that a device id in a query string
+ ends up in access logs.
+2. Try the returned `downloads` entries in order. Every attempt is downloaded to
+ a temporary file, checked against the returned `sha256` and the announced
+ `sizeBytes`, and extracted only when both agree. A mirror that fails —
+ network error, HTTP error, digest mismatch, size mismatch — is abandoned and
+ the next one is tried. Requests stay on the download allowlist.
+3. Only when the platform could not be reached, or when no mirror in the list
+ could serve the version, the client falls back to the catalog's own package
+ URL (`artifactBaseUrl` plus the relative `url`). That is the fallback the
+ platform defines, and that install is not counted.
+4. The answer is never cached (`Cache-Control: no-store` is the platform's
+ confirmation of this), so two installs of the same version are two calls.
+5. The resolve digest is authoritative on the resolve path; the catalog's
+ `shasum` stays authoritative on the fallback and on the backup channels.
+ `sizeBytes` is a sanity check on both.
+6. Refusals are reported, not papered over: `403 NOT_PUBLISHED` (no retry),
+ `403 PLUGIN_ARCHIVED` (hide the plugin from install and update selection),
+ `404` (the platform has no such version — including a `+`-suffixed version
+ the byte route cannot carry), `429` (wait the `Retry-After` interval, retry
+ once, then report), `503` (report the deployment problem; `NO_DOWNLOAD_SOURCE`
+ means no mirror can serve the version).
+7. Nothing switches the channel automatically. An unreachable platform is
+ reported after the fallback, and the user switches through the existing
+ selector.
+
+### 3. A stable device identifier, sent as a digest
+
+The resolve request carries a `deviceId` that host-core derives from the machine
+identity the operating system exposes — the Windows
+`HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid`, the macOS platform UUID, or
+Linux `/etc/machine-id` (falling back to `/var/lib/dbus/machine-id` and
+`/sys/class/dmi/id/product_uuid`). What leaves the machine is
+`sha256("pi-desktop.device.v1:" + <machine id>)` as 64-character lowercase hex,
+never the machine code itself: the platform only needs to compare two requests
+for equality, so it has no use for the code, and a raw hardware identifier in a
+third-party request is a privacy downgrade the counting feature does not
+require. The fixed prefix domain-separates the value from every other hash the
+app computes, so a leaked digest cannot be matched against another digest of the
+same machine.
+
+When no machine identity is readable, host-core generates one random 64-hex id
+on first use and persists it under the application data directory
+(`plugins/market/device.json`), reusing it from then on. Either way the value is
+read once per process, is stable for an installation across restarts, is never
+shown in the UI, and is not a setting. It is a counting and rate-limit key, not
+an account.
+
+### 4. The backup channels and `custom` are unchanged
+
+`github`, `mirror`, and `custom` keep the static relative-URL resolution,
+including `artifactBaseUrl` precedence, the download allowlist, redirect
+re-validation, and shasum verification, byte for byte. The persisted source
+keeps working for existing users, the cache stays keyed by `sourceUrl` so a
+switch ignores rather than deletes another channel's snapshot, and an installed
+record's `providerId` now names the channel it actually came from — already
+installed records are not rewritten.
+
+### 5. Trust tiers follow the trusted channels
+
+`verified` renders as written only from the three project channels (official,
+GitHub backup, CNB backup). `custom` still degrades to `community`, and a v1
+catalog's boolean `verified` mapping is unchanged. The predicate changes from
+"is this the official source" to "is this a trusted channel".
+
+### 6. The download allowlist does not change
+
+The allowlist stays `github.com`, `githubusercontent.com`, `cnb.cool`, and the
+host that served the current catalog. The platform's resolve answers name
+mirrors on exactly those hosts today, so no entry is added. A mirror on any
+other host is refused like any other package URL: the next mirror is tried, and
+if every entry names such a host the install fails instead of widening the list.
+Moving a mirror outside the table is therefore a client-release dependency, not
+a platform-side change.
+
+### 7. An install reports progress, and can be cancelled while it downloads
+
+An install or update is a single request, so a download that takes a minute is
+otherwise indistinguishable from a frozen window. Host-core therefore reports
+where the install is: `plugin.installProgress` carries `pluginId`, `version`,
+`phase` (`resolve`, `download`, `verify`, `install`, `enable`), the mirror in
+use (`source`) with its 1-based `attempt` / `attempts`, `receivedBytes` /
+`totalBytes` (`0` meaning the size is unknown), every mirror tried so far
+(`tried[]`, each `{ source, url, error }`), and `error` on the report that ends
+a failed install. Reports are throttled to at most one per 200 ms, plus one per
+phase change and the terminal report, so byte-level progress cannot flood the
+RPC channel or the interface.
+
+The report goes to the interface rather than only to the log. A log line helps
+an operator afterwards; the person waiting needs to see that the install moved
+on to the second mirror and how far it is. Progress is therefore
+observer-shaped, host-core emits it as a notification, and the RPC layer owns
+the throttle.
+
+`market.cancelInstall { id }` answers `{ cancelled, id }` and cancels only an
+install that is running right now, never a queued or finished one. Cancellation
+is honoured while bytes arrive, before each mirror is tried, and at the last
+safe point before the package is written, so only a download is actually
+interruptible: stopping after the package has been unpacked and the plugin's row
+is being written would leave the plugin directory and the registry in a state
+no later step can describe, which is worse than letting that step finish. A
+cancelled install fails with `PLUGIN_CANCELLED` (code 1019), and the dialog closes quietly instead of reporting an error.
+
+The dialog is for a manual install or update only; a background auto-update
+stays silent. It shows the phase, `mirror n/N · name`, a determinate bar, and a
+cancel button enabled only during `resolve` and `download`; success closes it
+about two seconds after the install finishes, failure keeps it open with the
+readable error, the mirrors that were tried with a copy action, and a retry
+action.
+
+## Consequences
+
+- The official channel gains per-mirror fallback, withdrawal and archive
+ signals, and download counting, and it acquires a dependency: an install asks
+ the platform. The documented catalog-URL fallback and the two backup channels
+ are the mitigation.
+- Per-mirror digest verification becomes the reason a divergent mirror cannot
+ break an install. The measured CNB divergence (`pi.todo-0.6.5` at 92487 bytes
+ versus 92951) is exactly the case this absorbs.
+- A first third-party service now receives an installation-level identifier.
+ Only a digest is sent, the platform stores counts rather than identities, and
+ the privacy policy and the decisions log state it.
+- `429` costs at most one `Retry-After` wait per install; a batch update makes
+ one call per plugin, not one per mirror.
+- An install is no longer opaque: the interface sees the phase, the mirror being
+ tried, and the byte count, and a user can stop a download without leaving a
+ half-installed plugin. The cost is progress notifications on the RPC channel,
+ bounded by the 200 ms throttle and the per-phase reports.
+- No `.piplug` or manifest change, no catalog v1/v2 parsing change, no
+ permission-review change, no storage schema change, no migration of persisted
+ source values, and no change to the two backup install paths.
+- Still open, deliberately: signature verification (optional as before), any
+ automatic channel switching, and the center's own byte route, which stays the
+ marketplace page and console path.
+
+## Rejected alternatives
+
+- **Keep resolving the catalog's declared base on the client only.** The catalog
+ is a static file, so it cannot say which mirrors currently serve a version, it
+ cannot refuse an archived or unpublished plugin, and it is the same list for
+ every install. The client would also keep trusting a publisher-influenced base
+ without any per-mirror signal, and the platform would lose the counting and
+ rate-limit identity its contract depends on.
+- **Send a per-request identifier.** The platform counts one download per
+ device, version, and day and rate-limits per device, so a value that changes
+ per call counts every call as a new installation and degrades the limiter to
+ the source address. The requirement is stability.
+- **Send the raw machine code, or hash it without a prefix.** The platform only
+ compares values, so shipping the code itself would hand a third party a
+ reusable hardware identifier for no functional gain, and an unprefixed digest
+ could be correlated with other digests of the same machine.
+- **Expose the identifier in Settings (show or reset it).** It answers no user
+ question, it invites treating a counting key as an account, and a reset button
+ would silently let one machine inflate the platform's counters. The fallback
+ file is documented instead.
+- **An automatic fallback between channels.** A channel switch changes which
+ catalog, versions, trust verdicts, and bytes the user sees, so doing it
+ silently would attribute an install to a source the user did not choose. The
+ only automatic fallback stays inside the official channel, to the catalog URL
+ that channel served, and it is not counted.
+- **Cache the resolve answer.** The platform marks it `no-store` because mirrors
+ and availability change; a cached answer would pin a dead mirror and could
+ serve a version the platform has since withdrawn.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 50df04fc9..6e3396728 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -300,3 +300,4 @@ Each ADR includes:
| 0268 | Remove quotes, annotations, and side chats | Accepted (supersedes message-quotes-and-side-chats / response-annotations / floating-annotation-index) |
| 0272 | [Judge a public-network address on the route the request will dial](0272-connection-time-public-network-route.md) | Accepted for implementation (amends ADR 0243; issue #419 / PR #473) |
| 0273 | [Git checkout as a Create project source](0273-git-checkout-create-project-source.md) | Accepted for implementation (amends ADR 0233; ADR 0247) |
+| 0274 | [Official plugin channel and backup channels](0274-official-plugin-channel-and-backup-channels.md) | Accepted for implementation (amends ADR 0102; D438) |
diff --git a/docs/privacy-policy.md b/docs/privacy-policy.md
index b0afa8e3b..d9e31f880 100644
--- a/docs/privacy-policy.md
+++ b/docs/privacy-policy.md
@@ -94,6 +94,17 @@ endpoints, GitHub release/update endpoints, provider OAuth endpoints, and
other services required by features you enable. Those services may receive
network metadata such as your IP address and user agent.
+Installing or updating a plugin through the official plugin channel also
+contacts the plugin marketplace endpoint used by that channel, the plugin
+center at `https://plugins.aiuo.net/api/v1/download/resolve`. That request
+carries a device identifier: a SHA-256 digest derived from a machine identifier
+the operating system exposes, or, when no machine identifier can be read, a
+random identifier generated once and stored in the application data directory.
+The value sent is the digest, not the machine code, and the machine code cannot
+be recovered from it. The service uses the identifier to de-duplicate and
+rate-limit a download, and it keeps counts for a device rather than the identity
+behind it. The two backup channels and a custom source do not send it.
+
Links opened through the application are handled by the operating system or an
external browser. Markdown written by a model may include remote images,
audio, or video; when rendered, the relevant host may receive a request from
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 480e4f33f..2c87d144b 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1092,6 +1092,12 @@ numeric slot; the string is the contract, the number is transport detail.
| 1016 | SKILL_INVALID | user skill document failed validation |
| 1017 | SUBAGENT_INVALID | user subagent document failed validation |
| 1018 | CAPABILITY_INVALID | agent capability root/scope setting failed validation |
+| 1019 | PLUGIN_CANCELLED | the user cancelled a marketplace install while it was downloading |
+| 1020 | PLUGIN_MARKET_NOT_PUBLISHED | the platform has the version and is not offering it yet |
+| 1021 | PLUGIN_MARKET_ARCHIVED | the plugin was withdrawn from the platform |
+| 1022 | PLUGIN_MARKET_NOT_FOUND | the platform does not have that plugin or version |
+| 1023 | PLUGIN_MARKET_RATE_LIMITED | the download endpoint asked the client to wait |
+| 1024 | PLUGIN_MARKET_NO_SOURCE | no distribution target can serve the package |
| -32029 | HOST_OVERLOADED | RPC dispatcher capacity exhausted |
| -32601 | — | unknown method |
| -32700 | — | unparseable request line |
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 2f15adcd1..18ce495d2 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -231,6 +231,12 @@ malformed.
| `PLUGIN_MARKET_INVALID` | no | the marketplace catalog is malformed or missing required release fields |
| `PLUGIN_MARKET_UNTRUSTED_HOST` | no | the catalog or package URL is outside the trusted marketplace hosts |
| `PLUGIN_MARKET_YANKED` | no | the requested release was withdrawn from the catalog |
+| `PLUGIN_MARKET_NOT_PUBLISHED` | no | the platform has the version and is not offering it yet |
+| `PLUGIN_MARKET_ARCHIVED` | no | the plugin was withdrawn from the platform |
+| `PLUGIN_MARKET_NOT_FOUND` | no | the platform does not have that plugin or version |
+| `PLUGIN_MARKET_RATE_LIMITED` | yes | the download endpoint asked the client to wait |
+| `PLUGIN_MARKET_NO_SOURCE` | maybe | no distribution target can serve the package |
+| `PLUGIN_CANCELLED` | no | the user cancelled an install while it was downloading |
| `MCP_INVALID` | no | a user MCP server definition failed validation |
| `SKILL_INVALID` | no | a user skill document failed validation |
| `SUBAGENT_INVALID` | no | a user subagent document failed validation |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 316512b9f..247333de8 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2202,10 +2202,10 @@ identify the platform validation still needed.
#### E2E-024P: Switch the marketplace catalog source
-- **Preconditions**: Network available to `cnb.cool`.
-- **Steps**: 1) Open Extensions → Marketplace. 2) Switch Marketplace source from GitHub (official) to Mirror (cnb.cool). 3) Confirm the catalog refreshes in the same surface. 4) Install a plugin.
-- **Expected**: Switching triggers a refresh and reports the new plugin count; the source selector remains the only source-status control, with no redundant provider explanation or active-source status line; the install downloads its package from the mirror and passes shasum verification. Switching back to official restores the GitHub source. Choosing Custom URL with an empty value falls back to the official default rather than an empty endpoint.
-- **Specs linked**: `07-plugins/07-plugin-marketplace.md`
+- **Preconditions**: Network available to `plugins.aiuo.net`, `raw.githubusercontent.com`, and `cnb.cool`.
+- **Steps**: 1) Open Extensions → Marketplace on a clean profile and confirm the source line reads Official channel. 2) Switch to GitHub backup, then CNB backup, then Custom with a URL, then back to Official channel. 3) After each switch, confirm the catalog refreshes in the same surface. 4) Install a plugin from the official channel, then one from the CNB backup. 5) Choose Custom URL with an empty value.
+- **Expected**: A fresh profile opens on the official channel, whose catalog comes from `plugins.aiuo.net/catalog.json`; the four choices are labelled Official channel / GitHub backup / CNB backup / Custom in that order; switching triggers a refresh and reports the new plugin count; the source selector remains the only source-status control, with no redundant provider explanation or active-source status line; the official install resolves through the platform while the CNB install downloads from the mirror and passes the same shasum verification as before, so the two backup paths are unchanged; switching back to a source reuses its cached snapshot instead of deleting it and never rounds trips; the installed record names the channel the plugin came from; choosing Custom URL with an empty value falls back to the official default rather than an empty endpoint.
+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §2
- **Acceptance**: G (remote marketplace source)
- **Status**: Documented / host-core unit covered
@@ -12611,3 +12611,72 @@ plugin-form fixtures in an isolated temporary directory at runtime.
marked); `packages/shared/src/model-catalog.test.ts` covers the four source rules;
`crates/host-core/src/providers/catalog.rs` covers the config round trip, the
unmarked record, and the dropped unknown marker. The end-to-end settings journey
+#### E2E-PLUGIN-official-channel-resolves-through-the-platform: An official-channel install resolves through the platform and installs from the first working mirror
+
+- **Preconditions**: A clean profile on the official channel, a plugin present in `plugins.aiuo.net/catalog.json`, and a request log for the platform and both mirror hosts (a local stub may stand in for each).
+- **Steps**: 1) Open Extensions → Marketplace and confirm the source line reads Official channel and that the catalog came from `plugins.aiuo.net`. 2) Install the plugin. 3) Capture the request the platform received. 4) Inspect which mirror served the package. 5) Install a second plugin, then install the same version of the first one again.
+- **Expected**: Exactly one `POST /api/v1/download/resolve` is sent per install or update, with a JSON body carrying `deviceId`, `pluginId`, and the version when one was picked; the package comes from the first entry in `downloads` that answers, and its bytes match the returned `sha256` and `sizeBytes` before anything is extracted; a mirror that is unreachable or fails is abandoned and the next one is used without user interaction; reinstalling the same version issues a fresh resolve call rather than reusing the earlier answer, because the response is never cached; the installed plugin passes the ordinary permission review and its record names the official channel as its provider.
+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §2, `07-plugins/15-plugin-center.md` §10
+- **Acceptance**: G (remote marketplace source)
+- **Milestone**: M6+
+- **Status**: Draft
+
+#### E2E-PLUGIN-mirror-digest-mismatch-falls-through-to-the-next-mirror: A mirror whose bytes fail the digest is rejected before extraction
+
+- **Preconditions**: An official-channel install whose `downloads` list has at least two entries, with the first mirror serving bytes that do not match the returned `sha256` (a stale distribution, or a stub that serves the CNB-era bytes for `pi.todo-0.6.5`), plus a view of the install cache and the plugin directory.
+- **Steps**: 1) Start the install. 2) Watch the first mirror's download and the digest check. 3) Inspect the install cache and the plugin directory before the install finishes. 4) Let the install continue. 5) Repeat with a stub whose first mirror fails only the announced `sizeBytes`.
+- **Expected**: The mismatching bytes are discarded without being extracted or handed to the installer, nothing lands in the plugin directory, and the rejection is reported in the install progress instead of being swallowed; the next mirror's bytes are verified against the same digest and the install completes from there; the size-mismatch case behaves identically; when every entry fails, the install ends as a reported failure rather than a partially installed plugin.
+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §2
+- **Acceptance**: G (remote marketplace source) + Security
+- **Milestone**: M6+
+- **Status**: Draft
+
+#### E2E-PLUGIN-platform-unreachable-install-falls-back-to-the-catalog-url: An install falls back to the catalog URL when the platform cannot be reached
+
+- **Preconditions**: The official catalog is already cached from a successful refresh, and `plugins.aiuo.net` becomes unreachable for the install (a blocked stub, or a refused DNS/proxy route).
+- **Steps**: 1) Refresh the catalog while the platform is reachable, then make it unreachable. 2) Install a plugin whose catalog entry carries a relative `url`. 3) Confirm which host served the package and whether the platform received a resolve request. 4) Restore reachability and install a version the platform refuses in turn with `403 NOT_PUBLISHED`, `403 PLUGIN_ARCHIVED`, `404`, `429`, and `503`.
+- **Expected**: The install resolves the package from the catalog's own URL — `artifactBaseUrl` plus the relative `url` — and completes after the same shasum verification; no resolve request reaches the platform for that install and the fallback install is not counted; the failed resolve call is visible in the install log instead of being hidden; once the platform answers again each refusal produces its own message — not-published with no retry, archived hiding the plugin from install and update selection, not-found, one `Retry-After` wait for the rate limit, and a deployment error for `503` — and no refusal silently switches to another channel or another version.
+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §2
+- **Acceptance**: G (remote marketplace source)
+- **Milestone**: M6+
+- **Status**: Draft
+
+#### E2E-PLUGIN-device-identifier-is-stable-and-never-the-machine-code: The device identifier is stable across launches and is not the raw machine code
+
+- **Preconditions**: A host whose machine identifier is readable (Windows `MachineGuid`, the macOS platform UUID, or `/etc/machine-id`), a second environment where it is not readable, and a request-logging stub for `POST /api/v1/download/resolve`.
+- **Steps**: 1) Trigger two installs in one session and compare the recorded `deviceId` values. 2) Restart the app and trigger a third install. 3) Compare the value with the raw machine identifier of the host. 4) Search the settings, the Marketplace surface, and the installed-plugin detail view for the value. 5) Repeat steps 1 and 2 where no machine identifier is readable, then inspect the application data directory.
+- **Expected**: Every resolve request from one installation carries the same 64-character lowercase hex value, including after a restart and after an app reinstall while the machine identifier is unchanged; the value is neither the machine code nor a prefix of it, and it equals `sha256("pi-desktop.device.v1:" + <machine identifier>)`; the identifier never appears in the UI and no setting can reveal or reset it; in the unreadable case the value is a different 64-hex string that is generated once and persisted under `plugins/market/device.json`, then repeated across restarts.
+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §2, ADR 0274
+- **Acceptance**: G (remote marketplace source) + Security
+- **Milestone**: M6+
+- **Status**: Draft
+
+#### E2E-PLUGIN-install-progress-shows-phases-and-mirror: An official-channel install reports its phases and the mirror it is using, then completes
+
+- **Preconditions**: A clean profile on the official channel, a plugin whose resolve answer lists at least two entries, a first mirror that fails or is slow so a second attempt is observable, and a renderer subscribed to `plugin.installProgress`.
+- **Steps**: 1) Start a manual install from the marketplace detail sheet. 2) Record the reports that arrive while it runs. 3) Hover the dialog after the install succeeds. 4) Look at the installed plugin once the install ends. 5) Install again with a large package and count the reports over a window of at least one second.
+- **Expected**: The dialog shows the phases in order — `resolve`, `download`, `verify`, `install`, `enable` — with `mirror n/N · name` and a determinate bar from `receivedBytes` / `totalBytes`; every report carries `pluginId` and `version`, only the report that names a mirror carries `source`, and `attempt` counts 1-based within `attempts` while a mirror switch increments `attempt` without changing `attempts`; byte reports arrive at most once per 200 ms, with one extra report per phase change and one terminal report; the install ends with no `error` and the plugin is installed and enabled after the ordinary permission review; the dialog closes about two seconds after success, that countdown pauses while it is hovered, and a background auto-update installs the same way without opening the dialog at all.
+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §2, `07-plugins/15-plugin-center.md` §10, ADR 0274 §7
+- **Acceptance**: G (remote marketplace source)
+- **Milestone**: M6+
+- **Status**: Draft
+
+#### E2E-PLUGIN-cancel-during-download-installs-nothing: Cancelling during the download stops the install, leaves nothing installed, and closes the dialog without an error
+
+- **Preconditions**: An official-channel install of a package large enough or a mirror slow enough that the download phase lasts, a way to answer `market.cancelInstall`, and a view of the plugin directory, the install cache, and the Installed list.
+- **Steps**: 1) Start the install and wait for the download phase. 2) Press the cancel action in the dialog. 3) Watch the dialog and capture the RPC answer. 4) Inspect the plugin directory, the install cache, and the Installed list after the install ends. 5) Send `market.cancelInstall` again for the same id, for an install that is not running, and once after the download has finished.
+- **Expected**: The cancel call answers `{ cancelled: true, id }` for the running install, and the install fails with `PLUGIN_CANCELLED` (JSON-RPC code 1019); the dialog closes without reporting an error; nothing is installed — no plugin directory, no installed row, no enabled plugin — and no partial package survives in the cache; the second call for the same id, the call for an install that is not running, and a call after the download finished answer `{ cancelled: false, id }` and change nothing, so a cancel can never interrupt the write of the plugin directory.
+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §2, ADR 0274 §7
+- **Acceptance**: G (remote marketplace source) + Security
+- **Milestone**: M6+
+- **Status**: Draft
+
+#### E2E-PLUGIN-failed-install-lists-tried-mirrors: A failed install keeps the dialog open and lists the mirrors it tried with a copy action
+
+- **Preconditions**: An official-channel install whose every mirror fails — for example a digest mismatch on the first and a network error on the second — with a renderer subscribed to `plugin.installProgress` and a clipboard readback.
+- **Steps**: 1) Start the install. 2) Let every mirror fail. 3) Read the terminal report and the dialog. 4) Use the copy action, then the retry action once the mirrors serve valid bytes again.
+- **Expected**: The terminal report carries `error` and a `tried[]` entry per mirror in the order they were tried, each naming its `source`, `url`, and the error that mirror answered; the dialog stays open and shows the readable error plus that list; the copy action puts the tried mirrors on the clipboard; the retry action starts a new install of the same version and completes it when the mirrors answer, without reusing the failed attempt's partial state; nothing was installed by the failed attempt.
+- **Specs linked**: `07-plugins/07-plugin-marketplace.md` §2, ADR 0274 §7
+- **Acceptance**: G (remote marketplace source)
+- **Milestone**: M6+
+- **Status**: Draft
diff --git a/docs/spec/07-plugins/07-plugin-marketplace.md b/docs/spec/07-plugins/07-plugin-marketplace.md
index f6ccaf7c1..1978cf394 100644
--- a/docs/spec/07-plugins/07-plugin-marketplace.md
+++ b/docs/spec/07-plugins/07-plugin-marketplace.md
@@ -40,21 +40,36 @@ The host is responsible for:
### Catalog source selection
-Plugins → Marketplace picks where the catalog comes from. host-core resolves
-the URL with the environment override on top, so dev builds and tests can point
-at a local catalog without touching persisted settings:
-
-| Precedence | Source | Value |
-| --- | --- | --- |
-| 1 | `PI_DESKTOP_PLUGIN_MARKET_URL` | any URL |
-| 2 | `pluginMarketSource: "mirror"` | `https://cnb.cool/aixk/pi-desktop-plugins/-/git/raw/main/catalog.json` |
-| 2 | `pluginMarketSource: "custom"` | `pluginMarketCustomUrl` |
-| 3 | `pluginMarketSource: "official"` (default) | the default catalog URL above |
-
-The mirror exists for networks that cannot reach `raw.githubusercontent.com`.
-It serves a byte-identical catalog, and catalog package URLs are relative, so
-`resolve_package_url` keeps package downloads on whichever source served the
-catalog and shasum verification is unaffected by the switch.
+Plugins → Marketplace picks where the catalog comes from. There are four
+channels, and the user can switch between them at any time:
+
+| # | Channel | `pluginMarketSource` | Catalog URL | Package resolution |
+| --- | --- | --- | --- | --- |
+| 1 | Official channel | `"official"` (default) | `https://plugins.aiuo.net/catalog.json` | Platform resolve (below) |
+| 2 | GitHub backup | `"github"` | `https://raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main/catalog.json` | Relative URL against the catalog |
+| 3 | CNB backup | `"mirror"` | `https://cnb.cool/aixk/pi-desktop-plugins/-/git/raw/main/catalog.json` | Relative URL against the catalog |
+| 4 | Custom | `"custom"` | `pluginMarketCustomUrl` | Relative URL against the catalog |
+
+The selector labels are localized; the English locale uses exactly these four
+strings: Official channel, GitHub backup, CNB backup, Custom. An unset value
+and an unrecognized value both resolve to the official channel, and `mirror`
+still means CNB, so no persisted setting is migrated. The environment override
+`PI_DESKTOP_PLUGIN_MARKET_URL` stays above every channel so dev builds and
+tests can point at a local catalog without touching persisted settings.
+
+The official channel is the plugin center: its catalog is the generated
+`catalog.json` the center publishes, and a package installed from it is
+resolved through the platform's download API instead of by joining a relative
+path onto a base URL. The two backup channels and `custom` keep the static v1
+and v2 behavior: a relative package URL resolves against the catalog that
+carried it (`artifactBaseUrl` first, then the catalog directory), so a package
+URL never crosses providers and a source switch cannot change the checksum
+being verified. The GitHub and CNB backups exist for networks that cannot reach
+`plugins.aiuo.net` or each other. The CNB mirror is expected to replicate the
+distribution repository, but it can lag — a measured catalog there was older
+(22 plugins, and different bytes for a version the other mirror serves) — which
+is why the official channel verifies each mirror's bytes instead of trusting
+one URL.
Cached catalogs are keyed to their source in `plugins/market/cache-meta.json`.
A snapshot fetched from a different source is ignored rather than deleted —
@@ -64,6 +79,94 @@ re-pins the source in memory; fetching there would hold the host RPC state lock
behind a marketplace timeout, so the renderer triggers `market.refresh` after
the switch.
+### Device identifier
+
+The official channel's resolve call carries a `deviceId`. host-core derives it
+from the machine identity the operating system exposes: the Windows
+`HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid`, the macOS platform UUID, or
+Linux `/etc/machine-id` (falling back to `/var/lib/dbus/machine-id` and
+`/sys/class/dmi/id/product_uuid`). What is sent is
+`sha256("pi-desktop.device.v1:" + <machine id>)` as 64-character lowercase hex,
+so the machine code itself never leaves the machine and the digest is
+domain-separated from every other hash the app computes. When no machine
+identity is readable, host-core generates one random 64-hex id and persists it
+under the application data directory (`plugins/market/device.json`), reusing it
+from then on. The value is read once per process, is stable for the installation
+across restarts, is never shown in the UI, and is not a setting the user can
+edit or reset. It is the platform's counting and rate-limit key (see
+[15-plugin-center.md](15-plugin-center.md) §10), not an account or a login.
+
+### Resolve-based install (official channel)
+
+Every install or update from the official channel resolves its package through
+the platform after the catalog has been refreshed:
+
+1. Refresh the catalog and pick the plugin and version, exactly as for any other
+ channel.
+2. `POST {center origin}/api/v1/download/resolve` — the origin that served the
+ official catalog — with a JSON body of `{ deviceId, pluginId, version }`,
+ where `version` is present when the user picked one. POST is used rather than
+ GET because the platform's own contract notes that a device id in a query
+ string lands in access logs.
+3. Try every entry of the returned `downloads` array in order: download, verify
+ the returned `sha256` and the announced `sizeBytes`, then hand the bytes to
+ the installer. A mirror that fails — network error, HTTP error, digest
+ mismatch, size mismatch — is abandoned and the next one is tried. Requests
+ stay on the allowlisted hosts below.
+4. If the list is exhausted, or the resolve call itself failed, fall back to the
+ catalog's own package URL (`artifactBaseUrl` plus the relative `url`). That
+ is the fallback the platform documents, and the install is not counted.
+5. One resolve call per install or update. The answer is never cached, which is
+ why the platform sends `Cache-Control: no-store`; `counted: false` is a
+ normal reply and never an error.
+
+A `200` response always carries a non-empty `downloads` array. Refusals are
+reported, never papered over:
+
+- `403 NOT_PUBLISHED` — the version is not published. Report it and do not
+ retry.
+- `403 PLUGIN_ARCHIVED` — the plugin is archived. Hide it from install and
+ update selection.
+- `404` — the platform has no such version. Report it; a version string the
+ byte route cannot carry (a `+` build-metadata suffix, for example) is a
+ missing version, not a URL to guess at.
+- `429` — the platform rate-limits per device id (600 requests per minute by
+ default). Wait the `Retry-After` interval, retry once, then report.
+- `503` — a deployment problem (`NO_DOWNLOAD_SOURCE` when no mirror can serve
+ the version). Report it without a retry loop.
+
+The resolve digest is authoritative on this path; the catalog's `shasum` stays
+authoritative on the two backup channels and on the step-4 fallback. Nothing
+here switches the channel automatically: an unreachable platform is reported
+after the fallback, and the user changes channels through the existing selector.
+
+### Install progress and cancellation
+
+An install or update is one request, so while it runs it reports where it is.
+The `plugin.installProgress` notification carries `pluginId`, `version`, `phase`
+(`resolve`, `download`, `verify`, `install`, `enable`), `source` (the mirror in
+use) with its 1-based `attempt` / `attempts`, `receivedBytes` / `totalBytes`
+(`0` total means the size is unknown), and `tried[]` — every mirror tried so
+far, each `{ source, url, error }`. The report that ends a failed install also
+carries `error`. Reports are throttled to at most one per 200 ms, plus one per
+phase change and the terminal report, so byte progress cannot flood the
+interface.
+
+`market.cancelInstall { id }` answers `{ cancelled, id }` and cancels only an
+install that is running right now. Only a download can actually be interrupted:
+the request is honoured while bytes arrive, before each mirror is tried, and at
+the last safe point before the package is written. A cancelled install fails
+with `PLUGIN_CANCELLED` (JSON-RPC code 1019), and the dialog closes quietly
+instead of reporting an error.
+
+The dialog opens for a manual install or update, never for a background
+auto-update. It shows the current phase, `mirror n/N · name`, a determinate bar
+from `receivedBytes` / `totalBytes` with the transfer speed, and a cancel button
+enabled only during `download` and `resolve`. A successful install closes the
+dialog about two seconds after it finishes, and that countdown pauses while the
+dialog is hovered. A failed install keeps it open with the readable error and
+the mirrors that were tried, offering a copy action for them and a retry action.
+
### Client-visible catalog policy
Development-only sample entries whose stable ID starts with `demo.` remain
@@ -337,6 +440,14 @@ redirection must satisfy the same rules as the initial URL. A custom or
enterprise catalog is trusted for its own host only — pointing the client at a
private catalog does not widen the allowlist for arbitrary third-party hosts.
+The official channel's resolve response names mirrors rather than a free-form
+URL list, and those mirrors are the distribution hosts above: the GitHub raw
+repository and the CNB mirror the platform already publishes from. A mirror
+entry on any other host is refused exactly like a package URL on that host, so
+the next mirror in the list is tried; if every entry names such a host the
+install fails instead of widening the list. Moving a mirror to a host outside
+this table therefore needs a client release, not a platform-side change.
+
An off-allowlist package URL fails with `PLUGIN_MARKET_UNTRUSTED_HOST` before any
network request is made, and the failure names the rejected host so an operator
can tell a misconfigured private source apart from a hostile catalog entry.
diff --git a/docs/spec/07-plugins/15-plugin-center.md b/docs/spec/07-plugins/15-plugin-center.md
index 0fbb65383..40f709ef2 100644
--- a/docs/spec/07-plugins/15-plugin-center.md
+++ b/docs/spec/07-plugins/15-plugin-center.md
@@ -351,11 +351,24 @@ Public responses contain only published data and carry a schema version.
Mutations require a session, CSRF and Origin checks, an idempotency key, and an
audit event. Internal routes reject browser sessions.
-**The desktop client depends only on the generated catalog, not on this API.**
-The API can be unavailable without breaking browse, install, or update, because
-the catalog and artifacts are static files in the distribution repository and its
-CNB mirror. This is the main resilience benefit of dropping object storage, and
-the reason the client needs no code change to reach center-published plugins.
+**The desktop client reads the generated catalog and calls one download route.**
+The official plugin channel resolves each install or update through
+`POST /api/v1/download/resolve`, sending the plugin id, the version when the
+user picked one, and a stable device identifier (`deviceId`), so the platform can
+de-duplicate a download and rate-limit per device instead of per source address.
+The byte sibling of that route, `GET /download/{id}/{version}`, is the
+marketplace page and console path, not the client's. Browse and update checking
+still need nothing but static files, and an install whose resolve call cannot
+reach the platform falls back to the catalog's own package URL, so the API can
+be unavailable without making published plugins unreachable. The client-side
+contract — channels, mirrors, digest verification, and how the identifier is
+derived — is in [07-plugin-marketplace.md](07-plugin-marketplace.md).
+
+A running install reports its own progress on `plugin.installProgress` — the
+phase, the mirror being tried, and the bytes received — and `market.cancelInstall`
+cancels an install that is still running, where only the download is
+interruptible. Both are client-side contract: the platform's resolve call is
+unchanged and still sees one request per install or update.
## 11. Trust tiers
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 7d83ae5ac..74923526c 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -112,6 +112,7 @@ This log freezes previously open questions into concrete decisions.
| D341 | Per-provider custom HTTP headers | **Amend D339 / ADR 0176: each AI-service and OAuth row stores optional `config_json.headers`. Empty / `{}` keeps adapter defaults. A non-empty map is last-writer on that row's outbound HTTP (turns, subagents, one-shots, discovery, connection test, OAuth refresh) via a fetch wrapper plus stream-option headers. Leftover `userAgent` migrates to `headers["User-Agent"]`. Max 32 headers; key ≤ 256 bytes; value ≤ 4096 bytes; no CR/LF; reserved auth/hop-by-hop/routing keys rejected. Compact KeyValueRows Advanced UI; first OAuth login does not collect headers. `matches()` includes the map. No schema/protocol bump.** | Users needed arbitrary non-secret headers, not only User-Agent. See ADR 0178 and E2E-005G. |
| D242 | Builtin subagents inherit the parent permission mode | **Builtin subagents use the default `permission: inherit` behavior. The builtin `fixer` no longer overrides the parent session, so `auto` covers its in-root and explicit external-path calls without a second authorization card; explicit non-`inherit` scopes on eligible builtin or user definitions remain intentional overrides.** | The observed popup came from the builtin `fixer` replacing an `auto` parent with `accept-edits`; inheriting the parent fixes the UX without weakening host-core containment or external-path permission rules (ADR 0100). |
| D241 | Titled Settings navigation clusters | **Keep the eight-destination Settings directory flat and searchable, but render four non-interactive localized group headings — Personal / 个人 (Basics, AI, Shortcuts), Agent / 智能体 (Instructions, Model configuration), Workspace / 工作区 (Import, Project archive), and About / 关于 (Info). Headings use whitespace for separation and no divider lines. Empty groups disappear with filtered search. This supersedes only D238's prohibition on group headings; destination order, IDs, search ownership, and marketplace placement remain unchanged.** | The flat rows became visually dense without scan landmarks. Muted headings restore grouping while preserving one-level navigation and the existing destination ownership. |
+| D438 | Marketplace download requests carry a device identifier | **Amend D238: the official plugin channel resolves every install and update through `POST /api/v1/download/resolve` and sends a stable `deviceId` — the SHA-256 digest of a platform machine identifier, or a locally persisted random id when none is readable. The client tries the returned mirrors in order, verifies `sha256` and `sizeBytes` before extracting, never caches the answer, and falls back to the catalog's own package URL only when the platform could not be reached. The GitHub and CNB backup channels and `custom` keep the existing static relative-URL resolution. See ADR 0274 and E2E-PLUGIN-official-channel-resolves-through-the-platform.** | The platform needs one stable installation identity to count a download once and to rate-limit per device instead of per source address; the value is a digest, so no machine code leaves the machine, and no new UI surface is introduced. |
## D. Codex visual parity decisions (0.3.5+)
diff --git a/docs/zh-CN/adr/index.md b/docs/zh-CN/adr/index.md
index 22ea64fa6..46d03604a 100644
--- a/docs/zh-CN/adr/index.md
+++ b/docs/zh-CN/adr/index.md
@@ -286,6 +286,7 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索
| 0265 | [排队队列的优先区块与行内操作](/adr/0265-turn-queue-priority-block-and-row-actions) | 已接受待实现(修订 ADR 0213 / 0118) |
| 0267 | [插件标签跟随应用语言](/adr/0267-plugin-labels-follow-the-app-language) | 已接受(修订 ADR 0160;ADR 0182) |
| 0272 | [按请求实际会走的线路判定公网地址](/adr/0272-connection-time-public-network-route) | 已接受待实现(修订 ADR 0243;issue #419 / PR #473) |
+| 0274 | [官方插件渠道与备份渠道](/adr/0274-official-plugin-channel-and-backup-channels) | 已接受待实现(修订 ADR 0102;D438) |
## 什么时候看 ADR
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index c4f0d43dc..4e96211ac 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -886,6 +886,12 @@ JSON-RPC 错误携带一个数字 `code` 以及 `data.errorCode`,后者是来
| 1016 | SKILL_INVALID | 用户技能文档校验失败 |
| 1017 | SUBAGENT_INVALID | 用户子代理文档校验失败 |
| 1018 | CAPABILITY_INVALID | Agent 能力 root/scope 设置校验失败 |
+| 1019 | PLUGIN_CANCELLED | 用户在下载过程中取消了市场安装 |
+| 1020 | PLUGIN_MARKET_NOT_PUBLISHED | 平台有该版本但尚未对外提供 |
+| 1021 | PLUGIN_MARKET_ARCHIVED | 插件已被平台下架 |
+| 1022 | PLUGIN_MARKET_NOT_FOUND | 平台没有该插件或该版本 |
+| 1023 | PLUGIN_MARKET_RATE_LIMITED | 下载接口要求客户端等待后重试 |
+| 1024 | PLUGIN_MARKET_NO_SOURCE | 没有任何分发目标能提供该包 |
| -32029 | HOST_OVERLOADED | RPC 调度程序容量已耗尽 |
| -32601 | — | 未知方法 |
| -32700 | — | 无法解析的请求行 |
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 9ef6c8812..da07e4b40 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -226,6 +226,12 @@ reveal 不并入任何行,必须重新读取。
| `PLUGIN_MARKET_INVALID` | 不 | 市场目录格式错误或缺少必需的发布字段 |
| `PLUGIN_MARKET_UNTRUSTED_HOST` | 不 | 目录或包 URL 不在可信市场主机之内 |
| `PLUGIN_MARKET_YANKED` | 不 | 请求的发布版本已从目录中撤回 |
+| `PLUGIN_MARKET_NOT_PUBLISHED` | 不 | 平台有该版本但尚未对外提供 |
+| `PLUGIN_MARKET_ARCHIVED` | 不 | 插件已被平台下架 |
+| `PLUGIN_MARKET_NOT_FOUND` | 不 | 平台没有该插件或该版本 |
+| `PLUGIN_MARKET_RATE_LIMITED` | 是 | 下载接口要求客户端等待后重试 |
+| `PLUGIN_MARKET_NO_SOURCE` | 也许 | 没有任何分发目标能提供该包 |
+| `PLUGIN_CANCELLED` | 不 | 用户在下载过程中取消了安装 |
| `MCP_INVALID` | 不 | 用户的 MCP 服务器定义校验失败 |
| `SKILL_INVALID` | 不 | 用户的技能文档校验失败 |
| `SUBAGENT_INVALID` | 不 | 用户的子代理文档校验失败 |
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 0f22169f0..3bce92628 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -1220,12 +1220,12 @@ unit/integration 测试;代码 pull request 使用有选择且高价值的 E2E
#### E2E-024P:切换市场目录来源
-- **先决条件**:网络可访问 `cnb.cool`。
-- **步骤**:1) 打开扩展 → 市场。 2) 将「插件市场来源」从 GitHub(官方)切换到镜像(cnb.cool)。 3) 确认同一页面完成目录刷新。 4) 安装一个插件。
-- **预期**:切换后自动触发刷新并报告新的插件数量;来源选择器是唯一的来源状态控件,不显示重复的提供商说明或当前来源状态行;安装从镜像下载安装包并通过 shasum 校验。切回官方可恢复 GitHub 来源。选择自定义地址但留空时回退到官方默认地址,而不是空端点。
-- **链接规格**:`07-plugins/07-plugin-marketplace.md`
+- **先决条件**:网络可访问 `plugins.aiuo.net`、`raw.githubusercontent.com` 与 `cnb.cool`。
+- **步骤**:1) 在全新配置下打开扩展 → 市场,确认来源行显示官方渠道。 2) 依次切换到海外备份、国内备份、填写地址的自定义,再切回官方渠道。 3) 每次切换后确认同一页面完成目录刷新。 4) 先从官方渠道安装一个插件,再从国内备份安装一个。 5) 选择自定义地址但留空。
+- **预期**:全新配置默认停在官方渠道,其目录来自 `plugins.aiuo.net/catalog.json`;四个选项按官方渠道 / 海外备份 / 国内备份 / 自定义的顺序显示;切换后自动触发刷新并报告新的插件数量;来源选择器仍是唯一的来源状态控件,不显示重复的提供商说明或当前来源状态行;官方渠道的安装通过平台 resolve,国内备份的安装仍从镜像下载并通过与以前相同的 shasum 校验,因此两条备份路径逐字节不变;切回某个来源时直接复用其缓存快照而不是删除,也不产生额外往返;已安装记录标明插件来自哪个渠道;选择自定义地址但留空时回退到官方默认地址,而不是空端点。
+- **链接规格**:`07-plugins/07-plugin-marketplace.md` §2
- **接受**:G(远程市场来源)
-- **状态**:已记录/涵盖 host-core 单元
+- **状态**:已记录 / 涵盖 host-core 单元
#### E2E-024B:带有权限审查的市场安装
@@ -7543,3 +7543,72 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture
目录、继承值保持 `catalog` 标记);`packages/shared/src/model-catalog.test.ts` 覆盖
四条来源规则;`crates/host-core/src/providers/catalog.rs` 覆盖配置往返、无标记记录与
被丢弃的未知标记。端到端的设置旅程与实际启动窗口断言为草稿。
+#### E2E-PLUGIN-official-channel-resolves-through-the-platform:官方渠道的安装通过平台解析,并从第一个可用镜像安装
+
+- **先决条件**:全新配置停留在官方渠道;`plugins.aiuo.net/catalog.json` 中存在一个插件;平台与两个镜像主机各有请求日志(可用本地存根代替)。
+- **步骤**:1) 打开扩展 → 市场,确认来源行显示官方渠道,且目录来自 `plugins.aiuo.net`。 2) 安装该插件。 3) 抓取平台收到的请求。 4) 检查是哪个镜像提供了安装包。 5) 再安装第二个插件,然后重新安装第一个插件的同一版本。
+- **预期**:每次安装或更新只发出一次 `POST /api/v1/download/resolve`,JSON body 含 `deviceId`、`pluginId`,用户选定版本时含版本号;安装包来自 `downloads` 中第一个可应答的条目,且在解压之前其字节与返回的 `sha256` 和 `sizeBytes` 一致;不可达或失败的镜像被放弃并自动尝试下一个,无需用户操作;重新安装同一版本会发出新的 resolve 调用,而不是复用上一次的应答,因为响应从不缓存;插件通过常规权限审查安装,其记录标明来源为官方渠道。
+- **链接规格**:`07-plugins/07-plugin-marketplace.md` §2、`07-plugins/15-plugin-center.md` §10
+- **验收**:G(远程市场来源)
+- **里程碑**:M6+
+- **状态**:草稿
+
+#### E2E-PLUGIN-mirror-digest-mismatch-falls-through-to-the-next-mirror:字节与摘要不符的镜像在解压前被拒绝
+
+- **先决条件**:一次官方渠道安装,其 `downloads` 至少有两个条目,第一个镜像提供的字节与返回的 `sha256` 不符(旧分发内容,或提供 `pi.todo-0.6.5` 的 CNB 时代字节的存根);同时可以查看安装缓存与插件目录。
+- **步骤**:1) 启动安装。 2) 观察第一个镜像的下载与摘要校验。 3) 在安装结束前检查安装缓存与插件目录。 4) 让安装继续。 5) 换成一个只在第一个镜像上让声明的 `sizeBytes` 不符的存根重做一遍。
+- **预期**:不符的字节被丢弃,不会被解压或交给安装器,插件目录里不会留下任何内容,拒绝会显示在安装进度里而不是被吞掉;下一个镜像的字节按同一摘要校验,安装从那里完成;大小不符的情形表现完全相同;所有条目都失败时安装以明确的失败结束,而不是留下半安装的插件。
+- **链接规格**:`07-plugins/07-plugin-marketplace.md` §2
+- **验收**:G(远程市场来源)+ 安全性
+- **里程碑**:M6+
+- **状态**:草稿
+
+#### E2E-PLUGIN-platform-unreachable-install-falls-back-to-the-catalog-url:平台不可达时安装回退到目录地址
+
+- **先决条件**:官方目录已成功刷新并缓存;安装期间 `plugins.aiuo.net` 不可达(被阻断的存根,或被拒绝的 DNS/代理线路)。
+- **步骤**:1) 在平台可达时刷新目录,然后让它不可达。 2) 安装一个目录条目里带相对 `url` 的插件。 3) 确认是哪个主机提供了安装包,以及平台是否收到 resolve 请求。 4) 恢复可达后,依次安装平台分别以 `403 NOT_PUBLISHED`、`403 PLUGIN_ARCHIVED`、`404`、`429` 和 `503` 拒绝的版本。
+- **预期**:安装从目录自身的地址解析安装包——`artifactBaseUrl` 加相对 `url`——并在同样的 shasum 校验之后完成;该次安装不会向平台发出 resolve 请求,也不计入统计;resolve 失败的原因会出现在安装日志里而不是被隐藏;平台恢复应答后,各拒绝码各自给出对应的提示——尚未发布不重试、已归档会从安装与更新选择中隐藏该插件、平台没有该版本、限流按 `Retry-After` 等待一次、`503` 报部署问题——并且任何拒绝都不会静默切到别的渠道或别的版本。
+- **链接规格**:`07-plugins/07-plugin-marketplace.md` §2
+- **验收**:G(远程市场来源)
+- **里程碑**:M6+
+- **状态**:草稿
+
+#### E2E-PLUGIN-device-identifier-is-stable-and-never-the-machine-code:设备标识跨启动稳定,且不是机器码原文
+
+- **先决条件**:一个能读到机器标识的主机(Windows `MachineGuid`、macOS 平台 UUID,或 `/etc/machine-id`),一个读不到机器标识的环境,以及为 `POST /api/v1/download/resolve` 记录请求的存根。
+- **步骤**:1) 在同一会话内触发两次安装,比较记录的 `deviceId`。 2) 重启应用后再触发一次安装。 3) 把该值与主机的机器标识原文比较。 4) 在设置、市场页面与已安装插件详情中查找该值。 5) 在读不到机器标识的环境里重复步骤 1 与 2,然后检查应用数据目录。
+- **预期**:同一安装发出的每次 resolve 请求都携带同一个 64 位小写十六进制值,包括重启之后,以及机器标识未变时的应用重装之后;该值既不是机器码原文也不是它的前缀,并等于 `sha256("pi-desktop.device.v1:" + 机器标识)`;该标识从不出现在界面上,也没有任何设置可以显示或重置它;读不到机器标识时,该值是另一个 64 位十六进制字符串,只生成一次并持久化在 `plugins/market/device.json`,之后跨重启一直复用。
+- **链接规格**:`07-plugins/07-plugin-marketplace.md` §2、ADR 0274
+- **验收**:G(远程市场来源)+ 安全性
+- **里程碑**:M6+
+- **状态**:草稿
+
+#### E2E-PLUGIN-install-progress-shows-phases-and-mirror:官方渠道安装显示各阶段与正在尝试的镜像并完成
+
+- **先决条件**:全新配置停留在官方渠道;一个插件的 resolve 应答至少列出两个条目;第一个镜像失败或很慢,以便观察到第二次尝试;渲染进程已订阅 `plugin.installProgress`。
+- **步骤**:1) 从市场详情面板发起一次手动安装。 2) 记录安装期间收到的报告。 3) 安装成功后把指针悬停在对话框上。 4) 安装结束后查看已安装插件。 5) 用一个较大的安装包再次安装,并统计至少一秒窗口内的报告数量。
+- **预期**:对话框按顺序显示各阶段——`resolve`、`download`、`verify`、`install`、`enable`——以及 `mirror n/N · name` 和由 `receivedBytes` / `totalBytes` 得出的确定进度条;每条报告都带 `pluginId` 与 `version`,只有指明镜像的报告才带 `source`,`attempt` 按 1 在 `attempts` 内计数,切换镜像会递增 `attempt` 而不改变 `attempts`;字节报告最多每 200 ms 一条,另有每次阶段变化一条与最终一条;安装以不带 `error` 的状态结束,插件通过常规权限审查后完成安装并启用;成功后对话框约 2 秒自动关闭,悬停时该倒计时暂停;后台自动更新以同样方式安装,但完全不打开对话框。
+- **链接规格**:`07-plugins/07-plugin-marketplace.md` §2、`07-plugins/15-plugin-center.md` §10、ADR 0274 §7
+- **验收**:G(远程市场来源)
+- **里程碑**:M6+
+- **状态**:草稿
+
+#### E2E-PLUGIN-cancel-during-download-installs-nothing:在下载期间取消会停止安装、不留下任何已安装内容,并让对话框静默关闭
+
+- **先决条件**:一次官方渠道安装,其安装包足够大或镜像足够慢,使下载阶段持续一段时间;能够应答 `market.cancelInstall`;同时可以查看插件目录、安装缓存与已安装列表。
+- **步骤**:1) 启动安装并等待进入下载阶段。 2) 按下对话框中的取消操作。 3) 观察对话框并抓取 RPC 应答。 4) 安装结束后检查插件目录、安装缓存与已安装列表。 5) 对同一 id、对一个并未在运行的安装,以及在下载已结束之后,分别再次发出 `market.cancelInstall`。
+- **预期**:对正在运行的安装,取消调用返回 `{ cancelled: true, id }`,安装以 `PLUGIN_CANCELLED`(JSON-RPC 码 1019)失败;对话框不报告错误就关闭;没有任何东西被安装——没有插件目录、没有已安装行、没有已启用的插件——缓存中也不残留任何不完整的安装包;对同一 id 的第二次调用、对并未在运行的安装的调用,以及下载已结束之后的调用都返回 `{ cancelled: false, id }` 且不改变任何状态,因此取消永远不会中断插件目录的写入。
+- **链接规格**:`07-plugins/07-plugin-marketplace.md` §2、ADR 0274 §7
+- **验收**:G(远程市场来源)+ 安全性
+- **里程碑**:M6+
+- **状态**:草稿
+
+#### E2E-PLUGIN-failed-install-lists-tried-mirrors:安装失败时对话框保持打开,并列出尝试过的镜像与复制操作
+
+- **先决条件**:一次官方渠道安装,其所有镜像都失败——例如第一个摘要不符、第二个网络错误;渲染进程已订阅 `plugin.installProgress`,且可以读回剪贴板。
+- **步骤**:1) 启动安装。 2) 让所有镜像失败。 3) 读取最终报告与对话框。 4) 使用复制操作,然后在镜像恢复正常后使用重试操作。
+- **预期**:最终报告带有 `error`,并按尝试顺序为每个镜像提供一条 `tried[]` 记录,各自标明 `source`、`url` 与该镜像给出的错误;对话框保持打开,显示可读的错误与这份列表;复制操作把尝试过的镜像放入剪贴板;重试操作会对同一版本发起一次新的安装,并在镜像正常应答后完成,且不会复用失败尝试的不完整状态;失败的尝试没有安装任何东西。
+- **链接规格**:`07-plugins/07-plugin-marketplace.md` §2、ADR 0274 §7
+- **验收**:G(远程市场来源)
+- **里程碑**:M6+
+- **状态**:草稿
diff --git a/docs/zh-CN/spec/07-plugins/07-plugin-marketplace.md b/docs/zh-CN/spec/07-plugins/07-plugin-marketplace.md
index 545f83362..2be836ad7 100644
--- a/docs/zh-CN/spec/07-plugins/07-plugin-marketplace.md
+++ b/docs/zh-CN/spec/07-plugins/07-plugin-marketplace.md
@@ -40,25 +40,97 @@
### 目录来源选择
-「扩展 → 市场」决定目录从哪里获取。host-core 解析 URL 时把环境变量放在最高
-优先级,这样开发构建和测试可以指向本地目录,而不必改动已持久化的设置:
-
-| 优先级 | 来源 | 取值 |
-| --- | --- | --- |
-| 1 | `PI_DESKTOP_PLUGIN_MARKET_URL` | 任意 URL |
-| 2 | `pluginMarketSource: "mirror"` | `https://cnb.cool/aixk/pi-desktop-plugins/-/git/raw/main/catalog.json` |
-| 2 | `pluginMarketSource: "custom"` | `pluginMarketCustomUrl` |
-| 3 | `pluginMarketSource: "official"`(默认) | 上面的默认目录 URL |
-
-镜像用于无法访问 `raw.githubusercontent.com` 的网络环境。镜像提供的目录与官方
-逐字节一致,且目录中的包路径是相对路径,因此 `resolve_package_url` 会让安装包
-下载跟随提供该目录的来源,切换来源不影响 shasum 校验。
+「插件 → 市场」决定目录从哪里获取。共有四个渠道,用户可以随时切换:
+
+| # | 渠道 | `pluginMarketSource` | 目录地址 | 包地址解析 |
+| --- | --- | --- | --- | --- |
+| 1 | 官方渠道 | `"official"`(默认) | `https://plugins.aiuo.net/catalog.json` | 平台 resolve(见下) |
+| 2 | 海外备份 | `"github"` | `https://raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main/catalog.json` | 相对 URL + 目录 |
+| 3 | 国内备份 | `"mirror"` | `https://cnb.cool/aixk/pi-desktop-plugins/-/git/raw/main/catalog.json` | 相对 URL + 目录 |
+| 4 | 自定义 | `"custom"` | `pluginMarketCustomUrl` | 相对 URL + 目录 |
+
+来源标签按应用语言本地化:简体中文为官方渠道、海外备份、国内备份、自定义。未设置与
+无法识别的取值都归到官方渠道,`mirror` 仍然表示 CNB,因此不需要迁移任何已持久化的
+设置。环境变量 `PI_DESKTOP_PLUGIN_MARKET_URL` 仍高于所有渠道,开发构建和测试可以指向
+本地目录而不改动持久化设置。
+
+官方渠道就是插件中心:它的目录是中心发布的 `catalog.json`,从中安装的包通过平台的
+下载接口解析,而不再把相对路径拼到基址上。两个备份渠道与自定义仍沿用静态解析:
+相对包 URL 按携带它的那份目录解析(先 `artifactBaseUrl`,再目录所在目录),因此包
+URL 绝不跨提供方,切换来源也不会改变正在校验的摘要。海外备份与国内备份用于无法访问
+`plugins.aiuo.net` 或彼此的网络环境。国内备份本应复制分发仓库,但可能滞后——实测该
+镜像上的目录更旧(22 个插件,且同一版本的字节与另一镜像不同)——所以官方渠道逐个
+校验镜像的字节,而不是信任单一地址。
缓存目录会通过 `plugins/market/cache-meta.json` 记录其来源。来自其他来源的快照
只被忽略而不删除——它的包 URL 指向用户刚切走的那个提供商——所以切回去时无需
重新请求即可恢复该目录。`settings.set` 只在内存中重新指定来源;在那里发起抓取
会让 host RPC 状态锁卡在市场超时上,因此切换后由渲染进程触发 `market.refresh`。
+### 设备标识
+
+官方渠道的 resolve 请求携带 `deviceId`。host-core 从操作系统暴露的机器标识派生:
+Windows 的 `HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid`、macOS 的平台 UUID,
+或 Linux 的 `/etc/machine-id`(回退 `/var/lib/dbus/machine-id` 与
+`/sys/class/dmi/id/product_uuid`)。上报的是 `sha256("pi-desktop.device.v1:" + 机器码)`
+的 64 位小写十六进制,因此机器码原文不出本机,该摘要也与应用计算的其他哈希做了域
+分隔。读不到机器标识时,host-core 生成一个随机 64 位十六进制 ID,持久化在应用数据
+目录(`plugins/market/device.json`),之后一直复用。该值每个进程只读取一次,跨重启
+对同一安装保持稳定,不显示在界面上,也不是用户可编辑或重置的设置。它是平台的计数与
+限流键(见 [15-plugin-center.md](15-plugin-center.md) §10),不是账号或登录态。
+
+### 官方渠道的 resolve 安装
+
+官方渠道的每一次安装或更新都在刷新目录之后通过平台解析安装包:
+
+1. 刷新目录并选定插件与版本,与其他渠道完全一致。
+2. `POST {中心 origin}/api/v1/download/resolve`——即提供该官方目录的 origin——JSON
+ body 为 `{ deviceId, pluginId, version }`,用户选定版本时才带 `version`。使用
+ POST 而非 GET,因为平台自己的契约指出设备 ID 出现在查询串里会落到访问日志。
+3. 按顺序尝试返回的 `downloads` 每一项:下载、校验返回的 `sha256` 与声明的
+ `sizeBytes`,再把字节交给安装器。某个镜像失败——网络错误、HTTP 错误、摘要不符、
+ 大小不符——就放弃它并尝试下一个。请求仍限于下文的白名单主机。
+4. 列表耗尽,或 resolve 本身失败时,回退到目录自身的包地址(`artifactBaseUrl` 加
+ 相对 `url`)。这是平台文档规定的回退路径,该次安装不计入统计。
+5. 每次安装或更新只调用一次 resolve。响应从不缓存,这也是平台发送
+ `Cache-Control: no-store` 的原因;`counted: false` 是正常应答,不是错误。
+
+`200` 响应的 `downloads` 永不为空。拒绝要如实报告,而不是掩盖:
+
+- `403 NOT_PUBLISHED`——该版本尚未发布。报告且不重试。
+- `403 PLUGIN_ARCHIVED`——插件已归档。从安装与更新选择中隐藏它。
+- `404`——平台没有该版本。报告它;字节路由无法承载的版本字符串(例如带 `+` 的构建
+ 元数据后缀)属于版本缺失,不能靠猜 URL 绕过。
+- `429`——平台按设备 ID 限流(默认每分钟 600 次)。按 `Retry-After` 等待后重试一次,
+ 然后报告。
+- `503`——部署问题(没有任何镜像可服务该版本时为 `NO_DOWNLOAD_SOURCE`)。报告它,
+ 不进入重试循环。
+
+这条路径上以 resolve 返回的摘要为准;两个备份渠道与第 4 步的回退仍以目录的 `shasum`
+为准。此处不会自动切换渠道:平台不可达会在回退之后如实报告,用户通过既有选择器切换
+渠道。
+
+### 安装进度与取消
+
+安装或更新是一次请求,因此它在进行期间会报告自己处于哪一步。
+`plugin.installProgress` 通知携带 `pluginId`、`version`、`phase`(`resolve`、
+`download`、`verify`、`install`、`enable`)、`source`(正在使用的镜像)及其从 1 开始的
+`attempt` / `attempts`、`receivedBytes` / `totalBytes`(`totalBytes` 为 `0` 表示大小
+未知),以及 `tried[]`——迄今尝试过的每个镜像,每项为 `{ source, url, error }`。
+以失败结束安装的那一条报告还会带上 `error`。报告被限流为每 200 ms 最多一条,外加每次
+阶段变化与最终报告,因此字节级进度不会淹没界面。
+
+`market.cancelInstall { id }` 返回 `{ cancelled, id }`,且只取消当前正在运行的安装。
+真正能被中断的只有下载:该请求在字节到达时、尝试每个镜像之前,以及写入安装包之前的
+最后一个安全点被检查。被取消的安装以 `PLUGIN_CANCELLED`(JSON-RPC 码 1019)失败,
+对话框静默关闭,而不是报告错误。
+
+对话框只用于手动安装或更新,后台自动更新不会打开它。它显示当前阶段、
+`mirror n/N · name`、由 `receivedBytes` / `totalBytes` 得出的确定进度条与传输速度,
+以及仅在 `download` 与 `resolve` 期间可用的取消按钮。安装成功后约 2 秒自动关闭,
+悬停时暂停该倒计时。安装失败时对话框保持打开,显示可读的错误与尝试过的镜像,
+并提供复制与重试操作。
+
### 客户端可见的目录策略
保留稳定 ID 以 `demo.` 开头的仅开发示例条目
@@ -287,6 +359,12 @@ URL 描述的是一个受发布者影响的 release,所以宿主还必须约
自定义或企业目录只被信任其自身主机——把客户端指向一个私有目录,并不会为任意第三方
主机放宽白名单。
+官方渠道的 resolve 响应给出的是镜像列表,而不是任意 URL 清单,而这些镜像正是上表中的
+分发主机:平台已经发布的 GitHub raw 仓库与 CNB 镜像。位于其他主机的镜像条目会像该
+主机上的包 URL 一样被拒绝,因此客户端会尝试列表中的下一个镜像;如果所有条目都指向
+这类主机,安装就会失败,而不是放宽白名单。因此把镜像迁到本表之外的主机需要客户端
+发版,而不是在平台侧改配置。
+
白名单之外的包 URL 在任何网络请求发出之前就以 `PLUGIN_MARKET_UNTRUSTED_HOST` 失败,
错误信息会指出被拒绝的主机,便于运维区分配置错误的私有源和恶意目录条目。
diff --git a/docs/zh-CN/spec/07-plugins/15-plugin-center.md b/docs/zh-CN/spec/07-plugins/15-plugin-center.md
index 9cff93887..141a2a453 100644
--- a/docs/zh-CN/spec/07-plugins/15-plugin-center.md
+++ b/docs/zh-CN/spec/07-plugins/15-plugin-center.md
@@ -320,9 +320,19 @@ POST /v2/webhooks/github
公开响应只包含已发布数据并带 schema 版本。变更操作要求会话、CSRF 与 Origin 校验、
幂等键和审计事件。内部路由拒绝浏览器会话。
-**桌面客户端只依赖生成出来的目录,不依赖该 API。** API 不可用不会影响浏览、安装和
-更新,因为目录和制品都是分发仓库及其 CNB 镜像上的静态文件。这是放弃对象存储换来的
-主要韧性收益,也是客户端无需任何代码改动就能访问中心发布插件的原因。
+**桌面客户端读取生成出来的目录,并调用一条下载路由。** 官方插件渠道的每次安装或更新
+都通过 `POST /api/v1/download/resolve` 解析,发送插件 ID、用户选定版本时的版本号,以及
+稳定的设备标识(`deviceId`),让平台能够对下载去重,并按设备而不是按来源地址限流。
+该路由的字节兄弟 `GET /download/{id}/{version}` 供市场页面与控制台使用,不是客户端的
+路径。浏览与检查更新仍然只需要静态文件;当 resolve 请求无法到达平台时,安装会回退到
+目录自身的包地址,因此该 API 不可用不会让已发布插件无法安装。客户端一侧的契约——
+渠道、镜像、摘要校验以及标识的派生方式——见
+[07-plugin-marketplace.md](/zh-CN/spec/07-plugins/07-plugin-marketplace)。
+
+正在运行的安装通过 `plugin.installProgress` 报告自己的进度——当前阶段、正在尝试的镜像
+与已收到的字节数——并可用 `market.cancelInstall` 取消仍在运行的安装,其中只有下载阶段
+可被中断。两者都是客户端一侧的契约:平台的 resolve 调用不变,每次安装或更新仍然只收到
+一次请求。
## 11. 信任层级
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index b3109d52d..2c9484b0c 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -115,6 +115,7 @@
| D242 | 内置子智能体继承父会话权限模式 | **内置子智能体默认使用 `permission: inherit`。内置 `fixer` 不再覆盖父会话,因此 `auto` 会覆盖其工作区内和明确外部路径调用,避免第二张授权卡;合格的内置或用户定义仍可显式声明非 `inherit` scope。** | 观察到的弹窗来自内置 `fixer` 将 `auto` 父会话替换为 `accept-edits`;继承父会话可以修复体验,同时不削弱 host-core 的 containment 和外部路径权限规则(ADR 0100)。 |
| D241 | 带标题的设置导航视觉分组 | **设置目录保持八个目的地、扁平且可搜索,但显示四个非交互式本地化分组标题:Personal / 个人(基础、全局 AI、快捷键)、Agent / 智能体(说明、模型配置)、Workspace / 工作区(导入、项目存档)和 About / 关于(信息)。标题之间使用留白,不绘制分割线。搜索过滤时,空分组及其标题一并消失。本决策仅覆盖 D238 对分组标题的禁止,不改变目的地顺序、ID、搜索归属或市场位置。** | 扁平行缺少扫描锚点,视觉上过于紧密。柔和标题可以恢复分组,同时保持单层导航和既有目的地归属。 |
+| D438 | 市场下载请求携带设备标识 | **修订 D238:官方插件渠道的每次安装与更新都通过 `POST /api/v1/download/resolve` 解析并携带稳定的 `deviceId` —— 平台机器标识的 SHA-256 摘要,读不到机器标识时为本地持久化的随机 ID。客户端按顺序尝试返回的镜像,解压前校验 `sha256` 与 `sizeBytes`,从不缓存响应,只在平台不可达时回退到目录自身的包地址。GitHub 与 CNB 两个备份渠道以及 `custom` 继续沿用现有的静态相对 URL 解析。见 ADR 0274 与 E2E-PLUGIN-official-channel-resolves-through-the-platform。** | 平台需要一个稳定的安装标识,才能把一次下载只计一次,并按设备而不是按来源地址限流;上报的是摘要,因此机器码不出本机,也不新增任何界面入口。 |
## D. 法典视觉平等决策 (0.3.5+)
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 3aaed52fb..56449d186 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -794,9 +794,10 @@ sklm: {
"backToApp": "Zurück zur App",
"marketProviderTitle": "Erweiterungs-Marktplatz",
"marketProvider": "Marktplatz-Quelle",
- "marketProviderOfficial": "GitHub (offiziell)",
- "marketProviderMirror": "Mirror (cnb.cool)",
- "marketProviderCustom": "Benutzerdefinierte URL",
+ "marketProviderOfficial": "Offizieller Kanal",
+ "marketProviderGithub": "GitHub-Backup",
+ "marketProviderMirror": "CNB-Backup",
+ "marketProviderCustom": "Benutzerdefiniert",
"marketCustomUrl": "Katalog-URL",
"marketCustomUrlDesc": "Vollständige URL eines Katalogs.json. Die darin enthaltenen Paketpfade werden anhand dieser Adresse aufgelöst.",
"marketCustomUrlPlaceholder": "https://example.com/catalog.json",
@@ -1485,6 +1486,30 @@ sklm: {
"readmeEmpty": "Dieses Plugin enthielt keine Readme-Datei.",
"installVersion": "v{{version}} installieren",
"installingVersion": "Version v{{version}} installieren",
+ "installDialogTitle": "{{name}} wird installiert",
+ "installPhase": {
+ "resolve": "Download-Adresse wird ermittelt",
+ "download": "Wird heruntergeladen",
+ "verify": "Paket wird geprüft",
+ "install": "Wird installiert",
+ "enable": "Wird aktiviert",
+ },
+ "installMirror": "Mirror {{index}}/{{total}} · {{source}}",
+ "installMirrorUnknown": "Unbekannter Mirror",
+ "installProgressLabel": "Installationsfortschritt",
+ "installReceived": "{{received}} von {{total}}",
+ "installReceivedUnknown": "{{received}} empfangen",
+ "installSpeed": "{{rate}}/s",
+ "installCancel": "Download abbrechen",
+ "installCancelling": "Wird abgebrochen…",
+ "installSuccess": "{{name}} installiert",
+ "installFailed": "{{name}} konnte nicht installiert werden",
+ "installTriedTitle": "Getestete Mirrors ({{count}})",
+ "installRetry": "Wiederholen",
+ "installClose": "Schließen",
+ "installCopyDetails": "Details kopieren",
+ "installCopied": "Installationsdetails kopiert",
+ "installCopyFailed": "Installationsdetails konnten nicht kopiert werden",
"contributeGuide": "So tragen Sie bei",
"capabilities": {
"panel": "Panel",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 6c71ed613..de5e14e5d 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -802,9 +802,10 @@ sklm: {
backToApp: "Back to app",
marketProviderTitle: "Extension marketplace",
marketProvider: "Marketplace source",
- marketProviderOfficial: "GitHub (official)",
- marketProviderMirror: "Mirror (cnb.cool)",
- marketProviderCustom: "Custom URL",
+ marketProviderOfficial: "Official channel",
+ marketProviderGithub: "GitHub backup",
+ marketProviderMirror: "CNB backup",
+ marketProviderCustom: "Custom",
marketCustomUrl: "Catalog URL",
marketCustomUrlDesc:
"Full URL of a catalog.json. Package paths inside it resolve against this address.",
@@ -1502,6 +1503,30 @@ importConfirm: "Imported extensions run inside the agent process with the same a
readmeEmpty: "This plugin didn't include a readme.",
installVersion: "Install v{{version}}",
installingVersion: "Installing version v{{version}}",
+ installDialogTitle: "Installing {{name}}",
+ installPhase: {
+ resolve: "Resolving the download address",
+ download: "Downloading",
+ verify: "Verifying the package",
+ install: "Installing",
+ enable: "Enabling",
+ },
+ installMirror: "Mirror {{index}}/{{total}} · {{source}}",
+ installMirrorUnknown: "Unknown mirror",
+ installProgressLabel: "Install progress",
+ installReceived: "{{received}} of {{total}}",
+ installReceivedUnknown: "{{received}} received",
+ installSpeed: "{{rate}}/s",
+ installCancel: "Cancel download",
+ installCancelling: "Cancelling…",
+ installSuccess: "{{name}} installed",
+ installFailed: "Couldn't install {{name}}",
+ installTriedTitle: "Mirrors tried ({{count}})",
+ installRetry: "Retry",
+ installClose: "Close",
+ installCopyDetails: "Copy details",
+ installCopied: "Install details copied",
+ installCopyFailed: "Couldn't copy the install details",
contributeGuide: "How to contribute",
capabilities: {
panel: "Panel",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index ae3aa3502..e9586406e 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -794,9 +794,10 @@ sklm: {
"backToApp": "Volver a la aplicación",
"marketProviderTitle": "Mercado de extensión",
"marketProvider": "Fuente de Marketplace",
- "marketProviderOfficial": "GitHub (oficial)",
- "marketProviderMirror": "Espejo (cnb.cool)",
- "marketProviderCustom": "URL personalizada",
+ "marketProviderOfficial": "Canal oficial",
+ "marketProviderGithub": "Copia de seguridad de GitHub",
+ "marketProviderMirror": "Copia de seguridad de CNB",
+ "marketProviderCustom": "Personalizado",
"marketCustomUrl": "URL del catálogo",
"marketCustomUrlDesc": "URL completa de un catalog.json. Las rutas de los paquetes dentro de él se resuelven en esta dirección.",
"marketCustomUrlPlaceholder": "https://example.com/catalog.json",
@@ -1485,6 +1486,30 @@ sklm: {
"readmeEmpty": "Este complemento no incluye un Léame.",
"installVersion": "Instalar v{{version}}",
"installingVersion": "Instalando la versión v{{version}}",
+ "installDialogTitle": "Instalando {{name}}",
+ "installPhase": {
+ "resolve": "Resolviendo la dirección de descarga",
+ "download": "Descargando",
+ "verify": "Verificando el paquete",
+ "install": "Instalando",
+ "enable": "Activando",
+ },
+ "installMirror": "Espejo {{index}}/{{total}} · {{source}}",
+ "installMirrorUnknown": "Espejo desconocido",
+ "installProgressLabel": "Progreso de instalación",
+ "installReceived": "{{received}} de {{total}}",
+ "installReceivedUnknown": "{{received}} recibidos",
+ "installSpeed": "{{rate}}/s",
+ "installCancel": "Cancelar descarga",
+ "installCancelling": "Cancelando…",
+ "installSuccess": "{{name}} instalado",
+ "installFailed": "No se pudo instalar {{name}}",
+ "installTriedTitle": "Espejos probados ({{count}})",
+ "installRetry": "Reintentar",
+ "installClose": "Cerrar",
+ "installCopyDetails": "Copiar detalles",
+ "installCopied": "Detalles de instalación copiados",
+ "installCopyFailed": "No se pudieron copiar los detalles",
"contributeGuide": "Cómo contribuir",
"capabilities": {
"panel": "Panel",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 0c87debbd..26e21b92b 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -794,9 +794,10 @@ sklm: {
"backToApp": "Retour à l'application",
"marketProviderTitle": "Extension Marketplace",
"marketProvider": "Source Marketplace",
- "marketProviderOfficial": "GitHub (officiel)",
- "marketProviderMirror": "Miroir (cnb.cool)",
- "marketProviderCustom": "URL personnalisée",
+ "marketProviderOfficial": "Canal officiel",
+ "marketProviderGithub": "Sauvegarde GitHub",
+ "marketProviderMirror": "Sauvegarde CNB",
+ "marketProviderCustom": "Personnalisé",
"marketCustomUrl": "URL du catalogue",
"marketCustomUrlDesc": "URL complète d'un catalog.json. Les chemins de package à l’intérieur sont résolus par rapport à cette adresse.",
"marketCustomUrlPlaceholder": "https://example.com/catalog.json",
@@ -1485,6 +1486,30 @@ sklm: {
"readmeEmpty": "Ce plugin n'incluait pas de fichier Lisez-moi.",
"installVersion": "Installer v{{version}}",
"installingVersion": "Installer la version v{{version}}",
+ "installDialogTitle": "Installation de {{name}}",
+ "installPhase": {
+ "resolve": "Résolution de l'adresse de téléchargement",
+ "download": "Téléchargement",
+ "verify": "Vérification du paquet",
+ "install": "Installation",
+ "enable": "Activation",
+ },
+ "installMirror": "Miroir {{index}}/{{total}} · {{source}}",
+ "installMirrorUnknown": "Miroir inconnu",
+ "installProgressLabel": "Progression de l'installation",
+ "installReceived": "{{received}} sur {{total}}",
+ "installReceivedUnknown": "{{received}} reçus",
+ "installSpeed": "{{rate}}/s",
+ "installCancel": "Annuler le téléchargement",
+ "installCancelling": "Annulation…",
+ "installSuccess": "{{name}} installé",
+ "installFailed": "Impossible d'installer {{name}}",
+ "installTriedTitle": "Miroirs essayés ({{count}})",
+ "installRetry": "Réessayer",
+ "installClose": "Fermer",
+ "installCopyDetails": "Copier les détails",
+ "installCopied": "Détails d'installation copiés",
+ "installCopyFailed": "Impossible de copier les détails",
"contributeGuide": "Comment contribuer",
"capabilities": {
"panel": "Panneau",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 725475c35..30c6c327d 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -803,9 +803,10 @@ sklm: {
backToApp: "앱으로 돌아가기",
marketProviderTitle: "확장 기능 마켓플레이스",
marketProvider: "마켓플레이스 소스",
- marketProviderOfficial: "GitHub (공식)",
- marketProviderMirror: "미러 (cnb.cool)",
- marketProviderCustom: "사용자 지정 URL",
+ marketProviderOfficial: "공식 채널",
+ marketProviderGithub: "GitHub 백업",
+ marketProviderMirror: "CNB 백업",
+ marketProviderCustom: "사용자 지정",
marketCustomUrl: "카탈로그 URL",
marketCustomUrlDesc:
"catalog.json의 전체 URL입니다. 내부 패키지 경로는 이 주소를 기준으로 해석됩니다.",
@@ -1503,6 +1504,30 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
readmeEmpty: "이 플러그인에는 Readme가 포함되어 있지 않습니다.",
installVersion: "v{{version}} 설치",
installingVersion: "v{{version}} 버전 설치 중",
+ installDialogTitle: "{{name}} 설치 중",
+ installPhase: {
+ resolve: "다운로드 주소 확인 중",
+ download: "다운로드 중",
+ verify: "패키지 검사 중",
+ install: "설치 중",
+ enable: "사용 설정 중",
+ },
+ installMirror: "미러 {{index}}/{{total}} · {{source}}",
+ installMirrorUnknown: "알 수 없는 미러",
+ installProgressLabel: "설치 진행률",
+ installReceived: "{{received}} / {{total}}",
+ installReceivedUnknown: "{{received}} 받음",
+ installSpeed: "{{rate}}/초",
+ installCancel: "다운로드 취소",
+ installCancelling: "취소 중…",
+ installSuccess: "{{name}} 설치됨",
+ installFailed: "{{name}}을(를) 설치하지 못했습니다",
+ installTriedTitle: "시도한 미러 ({{count}})",
+ installRetry: "다시 시도",
+ installClose: "닫기",
+ installCopyDetails: "세부 정보 복사",
+ installCopied: "설치 세부 정보를 복사했습니다",
+ installCopyFailed: "설치 세부 정보를 복사하지 못했습니다",
contributeGuide: "기여 방법",
capabilities: {
panel: "패널",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index ea195ef66..90cc85042 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -803,9 +803,10 @@ sklm: {
backToApp: "Uygulamaya dön",
marketProviderTitle: "Uzantı mağazası",
marketProvider: "Mağaza kaynağı",
- marketProviderOfficial: "GitHub (resmi)",
- marketProviderMirror: "Ayna (cnb.cool)",
- marketProviderCustom: "Özel URL",
+ marketProviderOfficial: "Resmî kanal",
+ marketProviderGithub: "GitHub yedeği",
+ marketProviderMirror: "CNB yedeği",
+ marketProviderCustom: "Özel",
marketCustomUrl: "Katalog URL’si",
marketCustomUrlDesc:
"Bir catalog.json dosyasının tam URL’si. İçindeki paket yolları bu adrese göre çözülür.",
@@ -1503,6 +1504,30 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
readmeEmpty: "Bu eklenti bir readme içermiyor.",
installVersion: "v{{version}} kur",
installingVersion: "v{{version}} sürümü kuruluyor",
+ installDialogTitle: "{{name}} kuruluyor",
+ installPhase: {
+ resolve: "İndirme adresi çözümleniyor",
+ download: "İndiriliyor",
+ verify: "Paket doğrulanıyor",
+ install: "Kuruluyor",
+ enable: "Etkinleştiriliyor",
+ },
+ installMirror: "Yansı {{index}}/{{total}} · {{source}}",
+ installMirrorUnknown: "Bilinmeyen yansı",
+ installProgressLabel: "Kurulum ilerlemesi",
+ installReceived: "{{received}} / {{total}}",
+ installReceivedUnknown: "{{received}} alındı",
+ installSpeed: "{{rate}}/sn",
+ installCancel: "İndirmeyi iptal et",
+ installCancelling: "İptal ediliyor…",
+ installSuccess: "{{name}} kuruldu",
+ installFailed: "{{name}} kurulamadı",
+ installTriedTitle: "Denenen yansılar ({{count}})",
+ installRetry: "Yeniden dene",
+ installClose: "Kapat",
+ installCopyDetails: "Ayrıntıları kopyala",
+ installCopied: "Kurulum ayrıntıları kopyalandı",
+ installCopyFailed: "Kurulum ayrıntıları kopyalanamadı",
contributeGuide: "Nasıl katkıda bulunulur",
capabilities: {
panel: "Panel",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index c3ad3510b..da0b3140c 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -795,9 +795,10 @@ sklm: {
backToApp: "返回应用",
marketProviderTitle: "扩展市场",
marketProvider: "插件市场来源",
- marketProviderOfficial: "GitHub(官方)",
- marketProviderMirror: "镜像(cnb.cool)",
- marketProviderCustom: "自定义地址",
+ marketProviderOfficial: "官方渠道",
+ marketProviderGithub: "海外备份",
+ marketProviderMirror: "国内备份",
+ marketProviderCustom: "自定义",
marketCustomUrl: "目录地址",
marketCustomUrlDesc:
"catalog.json 的完整地址。目录内的安装包相对路径会基于该地址解析。",
@@ -1488,6 +1489,30 @@ sklm: {
readmeEmpty: "此插件未提供说明文档。",
installVersion: "安装 v{{version}}",
installingVersion: "将安装版本 v{{version}}",
+ installDialogTitle: "正在安装 {{name}}",
+ installPhase: {
+ resolve: "正在解析下载地址",
+ download: "正在下载",
+ verify: "正在校验安装包",
+ install: "正在安装",
+ enable: "正在启用",
+ },
+ installMirror: "镜像 {{index}}/{{total}} · {{source}}",
+ installMirrorUnknown: "未知镜像",
+ installProgressLabel: "安装进度",
+ installReceived: "已收到 {{received}},共 {{total}}",
+ installReceivedUnknown: "已收到 {{received}}",
+ installSpeed: "{{rate}}/秒",
+ installCancel: "取消下载",
+ installCancelling: "正在取消…",
+ installSuccess: "{{name}} 已安装",
+ installFailed: "{{name}} 安装失败",
+ installTriedTitle: "已尝试的镜像({{count}} 个)",
+ installRetry: "重试",
+ installClose: "关闭",
+ installCopyDetails: "复制详情",
+ installCopied: "已复制安装详情",
+ installCopyFailed: "复制安装详情失败",
contributeGuide: "贡献指南",
capabilities: {
panel: "面板",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 1e1adccf0..c979e7506 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -795,9 +795,10 @@ sklm: {
backToApp: "返回應用",
marketProviderTitle: "擴充套件市場",
marketProvider: "外掛市場來源",
- marketProviderOfficial: "GitHub(官方)",
- marketProviderMirror: "映象(cnb.cool)",
- marketProviderCustom: "自定義地址",
+ marketProviderOfficial: "官方渠道",
+ marketProviderGithub: "海外備份",
+ marketProviderMirror: "國內備份",
+ marketProviderCustom: "自訂",
marketCustomUrl: "目錄地址",
marketCustomUrlDesc:
"catalog.json 的完整地址。目錄內的安裝包相對路徑會基於該地址解析。",
@@ -1488,6 +1489,30 @@ sklm: {
readmeEmpty: "此外掛未提供說明文件。",
installVersion: "安裝 v{{version}}",
installingVersion: "將安裝版本 v{{version}}",
+ installDialogTitle: "正在安裝 {{name}}",
+ installPhase: {
+ resolve: "正在解析下載位址",
+ download: "正在下載",
+ verify: "正在驗證安裝套件",
+ install: "正在安裝",
+ enable: "正在啟用",
+ },
+ installMirror: "鏡像 {{index}}/{{total}} · {{source}}",
+ installMirrorUnknown: "未知鏡像",
+ installProgressLabel: "安裝進度",
+ installReceived: "已收到 {{received}},共 {{total}}",
+ installReceivedUnknown: "已收到 {{received}}",
+ installSpeed: "{{rate}}/秒",
+ installCancel: "取消下載",
+ installCancelling: "正在取消…",
+ installSuccess: "{{name}} 已安裝",
+ installFailed: "{{name}} 安裝失敗",
+ installTriedTitle: "已嘗試的鏡像({{count}} 個)",
+ installRetry: "重試",
+ installClose: "關閉",
+ installCopyDetails: "複製詳情",
+ installCopied: "已複製安裝詳情",
+ installCopyFailed: "複製安裝詳情失敗",
contributeGuide: "貢獻指南",
capabilities: {
panel: "面板",
diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.ts
index 9e121dc0b..e73ec2987 100644
--- a/packages/shared/src/errors.ts
+++ b/packages/shared/src/errors.ts
@@ -182,6 +182,18 @@ export const ErrorCodes = {
PLUGIN_MARKET_INVALID: "PLUGIN_MARKET_INVALID",
PLUGIN_MARKET_UNTRUSTED_HOST: "PLUGIN_MARKET_UNTRUSTED_HOST",
PLUGIN_MARKET_YANKED: "PLUGIN_MARKET_YANKED",
+ /** The platform has the version and is not offering it yet. */
+ PLUGIN_MARKET_NOT_PUBLISHED: "PLUGIN_MARKET_NOT_PUBLISHED",
+ /** The plugin was withdrawn from the platform. */
+ PLUGIN_MARKET_ARCHIVED: "PLUGIN_MARKET_ARCHIVED",
+ /** The platform does not have that plugin or version. */
+ PLUGIN_MARKET_NOT_FOUND: "PLUGIN_MARKET_NOT_FOUND",
+ /** The download endpoint asked the client to wait before asking again. */
+ PLUGIN_MARKET_RATE_LIMITED: "PLUGIN_MARKET_RATE_LIMITED",
+ /** No distribution target can serve the package. */
+ PLUGIN_MARKET_NO_SOURCE: "PLUGIN_MARKET_NO_SOURCE",
+ /** The user cancelled an install while it was downloading. */
+ PLUGIN_CANCELLED: "PLUGIN_CANCELLED",
MCP_INVALID: "MCP_INVALID",
SKILL_INVALID: "SKILL_INVALID",
SUBAGENT_INVALID: "SUBAGENT_INVALID",
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 2d0e70d6d..6661cffee 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -230,6 +230,7 @@ export const IPC = {
marketInstall: "pi-desktop/market/install",
marketCheckUpdates: "pi-desktop/market/checkUpdates",
marketApplyUpdates: "pi-desktop/market/applyUpdates",
+ marketCancelInstall: "pi-desktop/market/cancelInstall",
commandPaletteSearch: "pi-desktop/commandPalette/search",
commandPaletteExecute: "pi-desktop/commandPalette/execute",
logOpenFolder: "pi-desktop/log/openFolder",
@@ -268,6 +269,8 @@ export const IPC = {
},
event: {
pluginChanged: "pi-desktop/event/pluginChanged",
+ /** Progress of an install or update, while it is still running. */
+ pluginInstallProgress: "pi-desktop/plugin/event/installProgress",
/** Host-originated app settings mutation (e.g. plugin `app.setTheme`). */
settingsChanged: "pi-desktop/app/event/settingsChanged",
extensionsUiPrompt: "pi-desktop/extensions/event/uiPrompt",
diff --git a/packages/shared/src/types/plugins.ts b/packages/shared/src/types/plugins.ts
index 61d9e520a..9738c7414 100644
--- a/packages/shared/src/types/plugins.ts
+++ b/packages/shared/src/types/plugins.ts
@@ -2,7 +2,15 @@
import type { ActivationScope } from "../activation.js";
import type { TrustedExtensionDiagnostic } from "../trusted-extensions.js";
-export type PluginMarketSource = "official" | "mirror" | "custom";
+/**
+ * Where the marketplace catalog comes from.
+ *
+ * `official` keeps its meaning — the official one — and the official one is the
+ * plugin center, so a settings row written before the center existed keeps
+ * meaning what its author picked instead of needing a migration. `github` and
+ * `mirror` are the two backup channels, and `custom` is a URL the user typed.
+ */
+export type PluginMarketSource = "official" | "github" | "mirror" | "custom";
export type PluginUpdateInfo = {
version: string;
@@ -291,3 +299,31 @@ export type PluginWorkspaceInfo = {
/** Every registered folder of that group, primary first. */
roots?: PluginWorkspaceRoot[];
};
+
+/** One mirror an install tried, and what it answered. */
+export type PluginInstallMirror = {
+ source: string;
+ url: string;
+ error?: string | null;
+};
+
+/**
+ * What an install is doing, reported while it runs.
+ *
+ * The install is a single request, so without these the interface has nothing
+ * to show between the click and the answer. `error` is set on the report that
+ * ends a failed install; `receivedBytes`/`totalBytes` are a progress pair and
+ * `totalBytes` is 0 when nothing announced a size.
+ */
+export type PluginInstallProgress = {
+ pluginId: string;
+ version: string;
+ phase: "resolve" | "download" | "verify" | "install" | "enable";
+ source?: string | null;
+ attempt?: number;
+ attempts?: number;
+ receivedBytes?: number;
+ totalBytes?: number;
+ tried?: PluginInstallMirror[];
+ error?: string | null;
+};
diff --git a/scripts/check-marketplace-catalog.mjs b/scripts/check-marketplace-catalog.mjs
index 517599438..dca53d2f4 100644
--- a/scripts/check-marketplace-catalog.mjs
+++ b/scripts/check-marketplace-catalog.mjs
@@ -4,17 +4,20 @@ import { readFile } from "node:fs/promises";
import { realpathSync } from "node:fs";
import { pathToFileURL } from "node:url";
+// The distribution repository the plugin center publishes to, which is what a
+// release gate has to read: the center serves the same document with a package
+// base filled in.
const DEFAULT_URL =
process.env.PI_DESKTOP_PLUGIN_MARKET_URL ||
- "https://raw.githubusercontent.com/vastsa/pi-desktop-plugins/main/catalog.json";
+ "https://raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main/catalog.json";
/**
* Hosts a published package may be served from.
*
- * Mirrors PACKAGE_HOST_ALLOWLIST in crates/host-core/src/plugins.rs. A catalog
- * that passes preflight but names a host the client refuses would be a release
- * nobody can install, so the gate is checked here rather than discovered by the
- * first user.
+ * Mirrors PACKAGE_HOST_ALLOWLIST in
+ * crates/host-core/src/plugins/validation.rs. A catalog that passes preflight
+ * but names a host the client refuses would be a release nobody can install, so
+ * the gate is checked here rather than discovered by the first user.
*/
const PACKAGE_HOST_ALLOWLIST = ["github.com", "githubusercontent.com", "cnb.cool"];