Skip to content

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

fix(settings): keep the last successful market list when a query fails

blackEvil2175aa66e2c85f4
diff --git a/apps/desktop/src/components/settings/McpMarketPanel.tsx b/apps/desktop/src/components/settings/McpMarketPanel.tsx
index e9be68bcf..71c695351 100644
--- a/apps/desktop/src/components/settings/McpMarketPanel.tsx
+++ b/apps/desktop/src/components/settings/McpMarketPanel.tsx
@@ -30,6 +30,11 @@ import {
IconX,
} from "../icons";
import { Field, Input, TooltipButton, cx } from "../ui";
+import {
+ snapshotMatchesQuery,
+ snapshotTimeText,
+ type MarketSnapshot,
+} from "../../lib/market-snapshot";
const CATEGORIES: readonly McpCatalogCategory[] = [
"devtools",
@@ -105,7 +110,7 @@ export function McpMarketPanel({
onBack: () => void;
onInstalled: (id: string) => void;
}) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const showToast = useAppStore((state) => state.showToast);
const [search, setSearch] = useState("");
const [category, setCategory] = useState<"all" | McpCatalogCategory>("all");
@@ -116,6 +121,13 @@ export function McpMarketPanel({
const [saving, setSaving] = useState(false);
const [remote, setRemote] = useState<RemoteState>(REMOTE_IDLE);
const [catalogRetry, setCatalogRetry] = useState(0);
+ /**
+ * The last successful search for this panel, kept so a later failure can
+ * still show the list the user just had (issue #1692) instead of dropping
+ * to built-in picks only. It answers one query only: a snapshot taken for
+ * a different search must not stand in for the one on screen.
+ */
+ const [snapshot, setSnapshot] = useState<MarketSnapshot<MarketItem> | null>(null);
const [sources, setSources] = useState<MarketSource[]>(loadSources);
// Whether a plaintext hop to a user-supplied source is allowed, from the
// stored `networkPolicy`. The panel validates its persisted list with the same
@@ -170,6 +182,12 @@ export function McpMarketPanel({
exhausted: result.exhausted ?? true,
loadingMore: false,
});
+ // The list the user was just shown is what a later failure falls
+ // back to. An empty answer is not a list, and keeping it would pin
+ // the pane to a stale snapshot after one success.
+ if (entries.length > 0) {
+ setSnapshot({ entries, at: Date.now(), query: search.trim() });
+ }
})
.catch(() => {
if (!cancelled && generation === requestGeneration.current) {
@@ -204,6 +222,9 @@ export function McpMarketPanel({
exhausted: result.exhausted ?? true,
loadingMore: false,
});
+ if (entries.length > 0) {
+ setSnapshot({ entries, at: Date.now(), query: query.trim() });
+ }
} catch {
if (generation === requestGeneration.current) {
setRemote((current) => ({ ...current, loadingMore: false }));
@@ -220,6 +241,19 @@ export function McpMarketPanel({
[remote.entries],
);
+ /**
+ * The last successful list stands in only while the current query has
+ * nothing of its own to show — a failure, or the retry that follows one.
+ * A snapshot taken for another query never answers this one, and a `ready`
+ * result with no entries is a real (empty) answer, not a failure to cover.
+ */
+ const snapshotForQuery = snapshotMatchesQuery(snapshot, search) ? snapshot : null;
+ const showingSnapshot =
+ snapshotForQuery != null &&
+ remote.entries.length === 0 &&
+ (remote.status === "error" || remote.status === "loading");
+ const displayEntries = showingSnapshot && snapshotForQuery ? snapshotForQuery.entries : remote.entries;
+
const visible = useMemo(() => {
const query = search.trim().toLocaleLowerCase();
const matches = (entry: McpCatalogEntry) => {
@@ -231,9 +265,9 @@ export function McpMarketPanel({
};
return mergeRegistryEntries(
servers.filter(matches),
- remote.entries.filter(matches),
+ displayEntries.filter(matches),
) as MarketItem[];
- }, [remote.entries, search, category]);
+ }, [displayEntries, search, category]);
const totalPages = Math.max(1, Math.ceil(visible.length / PAGE_SIZE));
const currentPage = Math.min(page, totalPages);
@@ -590,9 +624,21 @@ export function McpMarketPanel({
</div>
{remote.status === "loading" ? (
- <p className="mcpm-status" role="status">
- {t("settings.mcpMarket.remoteLoading")}
- </p>
+ <>
+ <p className="mcpm-status" role="status">
+ {t("settings.mcpMarket.remoteLoading")}
+ </p>
+ {showingSnapshot && snapshotForQuery ? (
+ <p className="mcpm-status is-snapshot">
+ {t("settings.mcpMarket.remoteStaleSnapshot", {
+ time: snapshotTimeText(
+ snapshotForQuery.at,
+ i18n.resolvedLanguage ?? i18n.language,
+ ),
+ })}
+ </p>
+ ) : null}
+ </>
) : null}
{remote.status === "error" ? (
<>
@@ -600,6 +646,16 @@ export function McpMarketPanel({
{t("settings.mcpMarket.remoteError")}
{remote.failed.length ? ` (${remote.failed.join(", ")})` : ""}
</p>
+ {showingSnapshot && snapshotForQuery ? (
+ <p className="mcpm-status is-snapshot">
+ {t("settings.mcpMarket.remoteStaleSnapshot", {
+ time: snapshotTimeText(
+ snapshotForQuery.at,
+ i18n.resolvedLanguage ?? i18n.language,
+ ),
+ })}
+ </p>
+ ) : null}
<button type="button" className="mcpm-install is-ghost" onClick={retryCatalog}>
{t("settings.mcpMarket.retry")}
</button>
diff --git a/apps/desktop/src/components/settings/SkillMarketPanel.tsx b/apps/desktop/src/components/settings/SkillMarketPanel.tsx
index a2059fd85..699a2ebad 100644
--- a/apps/desktop/src/components/settings/SkillMarketPanel.tsx
+++ b/apps/desktop/src/components/settings/SkillMarketPanel.tsx
@@ -36,6 +36,11 @@ import {
skillMarketFailureDetail,
type SkillMarketFailureKind,
} from "../../lib/skill-market-failure";
+import {
+ snapshotMatchesQuery,
+ snapshotTimeText,
+ type MarketSnapshot,
+} from "../../lib/market-snapshot";
const CATEGORIES: readonly SkillCatalogCategory[] = [
"workflow",
@@ -151,7 +156,7 @@ export function SkillMarketPanel({
onBack: () => void;
onInstalled: (id: string) => void;
}) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const showToast = useAppStore((state) => state.showToast);
const [search, setSearch] = useState("");
const [category, setCategory] = useState<"all" | SkillCatalogCategory>("all");
@@ -178,6 +183,13 @@ export function SkillMarketPanel({
});
const [remote, setRemote] = useState<RemoteState>(REMOTE_IDLE);
const [catalogRetry, setCatalogRetry] = useState(0);
+ /**
+ * The last successful search for this panel, kept so a later failure can
+ * still show the list the user just had (issue #1692) instead of dropping
+ * to built-in picks only. It answers one query only: a snapshot taken for
+ * a different search must not stand in for the one on screen.
+ */
+ const [snapshot, setSnapshot] = useState<MarketSnapshot<MarketItem> | null>(null);
useEffect(() => {
let cancelled = false;
@@ -217,6 +229,7 @@ export function SkillMarketPanel({
if (!cancelled) {
const failed = result.failedSources ?? [];
const entries = result.entries ?? [];
+ const query = search.trim();
setRemote({
status: entries.length === 0 && failed.length > 0 ? "error" : "ready",
entries,
@@ -225,6 +238,12 @@ export function SkillMarketPanel({
failureDetails: result.failureDetails ?? {},
queryError: "",
});
+ // The list the user was just shown is what a later failure falls
+ // back to. A response with no entries is not a list, and keeping
+ // it would pin the pane to a stale snapshot after one success.
+ if (entries.length > 0) {
+ setSnapshot({ entries, at: Date.now(), query });
+ }
}
})
.catch((error: unknown) => {
@@ -251,6 +270,19 @@ export function SkillMarketPanel({
? [...DEFAULT_SKILL_SOURCES, ...sources].find((source) => source.id === id)?.name
: undefined;
+ /**
+ * The last successful list stands in only while the current query has
+ * nothing of its own to show — a failure, or the retry that follows one.
+ * A snapshot taken for another query never answers this one, and a `ready`
+ * result with no entries is a real (empty) answer, not a failure to cover.
+ */
+ const snapshotForQuery = snapshotMatchesQuery(snapshot, search) ? snapshot : null;
+ const showingSnapshot =
+ snapshotForQuery != null &&
+ remote.entries.length === 0 &&
+ (remote.status === "error" || remote.status === "loading");
+ const displayEntries = showingSnapshot && snapshotForQuery ? snapshotForQuery.entries : remote.entries;
+
const visible = useMemo(() => {
const query = search.trim().toLocaleLowerCase();
const matches = (entry: SkillCatalogEntry) => {
@@ -262,9 +294,9 @@ export function SkillMarketPanel({
};
return mergeSkillEntries(
skills.filter(matches),
- remote.entries.filter(matches),
+ displayEntries.filter(matches),
) as MarketItem[];
- }, [remote.entries, search, category]);
+ }, [displayEntries, search, category]);
const totalPages = Math.max(1, Math.ceil(visible.length / PAGE_SIZE));
const currentPage = Math.min(page, totalPages);
@@ -658,15 +690,37 @@ export function SkillMarketPanel({
</div>
{remote.status === "loading" ? (
- <p className="sklm-status" role="status">
- {t("settings.sklm.remoteLoading")}
- </p>
+ <>
+ <p className="sklm-status" role="status">
+ {t("settings.sklm.remoteLoading")}
+ </p>
+ {showingSnapshot && snapshotForQuery ? (
+ <p className="sklm-status is-snapshot">
+ {t("settings.sklm.remoteStaleSnapshot", {
+ time: snapshotTimeText(
+ snapshotForQuery.at,
+ i18n.resolvedLanguage ?? i18n.language,
+ ),
+ })}
+ </p>
+ ) : null}
+ </>
) : null}
{remote.status === "error" ? (
<>
<p className="sklm-status is-error" role="status">
{remoteErrorText()}
</p>
+ {showingSnapshot && snapshotForQuery ? (
+ <p className="sklm-status is-snapshot">
+ {t("settings.sklm.remoteStaleSnapshot", {
+ time: snapshotTimeText(
+ snapshotForQuery.at,
+ i18n.resolvedLanguage ?? i18n.language,
+ ),
+ })}
+ </p>
+ ) : null}
{remote.failed.length ? (
<p className="sklm-status">{failedSourceLabels().join(", ")}</p>
) : null}
diff --git a/apps/desktop/src/lib/market-snapshot.ts b/apps/desktop/src/lib/market-snapshot.ts
new file mode 100644
index 000000000..e67fb3533
--- /dev/null
+++ b/apps/desktop/src/lib/market-snapshot.ts
@@ -0,0 +1,49 @@
+/**
+ * The last successful market result, kept so a later source failure can show
+ * the list the user last saw instead of an empty pane (issue #1692). Both the
+ * skill market and the MCP market keep one of these.
+ */
+export type MarketSnapshot<T> = {
+ entries: T[];
+ /** Epoch ms of the successful response, for the timestamp line. */
+ at: number;
+ /** The search text the snapshot was taken for; a stale snapshot must not
+ * answer a different query. */
+ query: string;
+};
+
+/** Whether a snapshot still describes the query currently on screen. */
+export function snapshotMatchesQuery<T>(
+ snapshot: MarketSnapshot<T> | null | undefined,
+ query: string,
+): boolean {
+ if (snapshot == null) return false;
+ // The main process filters case-insensitively, so the query identity that
+ // matters is the trimmed, lowercased one.
+ return snapshot.query.trim().toLocaleLowerCase() === query.trim().toLocaleLowerCase();
+}
+
+/**
+ * Localized time for the snapshot line: clock time for today's snapshot, a
+ * dated form otherwise, so "19:52" is never mistaken for today when the app
+ * sat open overnight. Mirrors `formatMessageTime` in the transcript.
+ */
+export function snapshotTimeText(at: number, locale: string): string {
+ const date = new Date(at);
+ if (Number.isNaN(date.getTime())) return "";
+ const now = new Date();
+ const isToday =
+ date.getFullYear() === now.getFullYear() &&
+ date.getMonth() === now.getMonth() &&
+ date.getDate() === now.getDate();
+ if (isToday) {
+ return date.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });
+ }
+ return date.toLocaleString(locale, {
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ });
+}
diff --git a/apps/desktop/src/styles/settings.css b/apps/desktop/src/styles/settings.css
index 0787181d1..e60f68a90 100644
--- a/apps/desktop/src/styles/settings.css
+++ b/apps/desktop/src/styles/settings.css
@@ -3585,6 +3585,10 @@
color: var(--ds-warning);
}
+.mcpm-status.is-snapshot {
+ color: var(--ds-text-secondary);
+}
+
.mcpm-badge.is-remote {
background: color-mix(in oklab, var(--ds-accent) 10%, transparent);
color: var(--ds-text-muted);
@@ -4098,6 +4102,10 @@
color: var(--ds-warning);
}
+.sklm-status.is-snapshot {
+ color: var(--ds-text-secondary);
+}
+
.sklm-badge.is-remote {
background: color-mix(in oklab, var(--ds-accent) 10%, transparent);
color: var(--ds-text-muted);
diff --git a/apps/desktop/test/mcp-market-panel.test.mjs b/apps/desktop/test/mcp-market-panel.test.mjs
index 2ae613319..50d966b01 100644
--- a/apps/desktop/test/mcp-market-panel.test.mjs
+++ b/apps/desktop/test/mcp-market-panel.test.mjs
@@ -37,6 +37,23 @@ test("failed and partial MCP catalog searches can be retried", () => {
assert.match(panel, /remote\.status === "ready" && remote\.failed\.length/);
});
+test("a failed query keeps the last successful list with its timestamp", () => {
+ // Issue #1692 follow-up, MCP side: the last successful registry answer stays
+ // on screen when a later query fails, with the time it was taken.
+ assert.match(panel, /useState<MarketSnapshot<MarketItem> \| null>\(null\)/);
+ assert.match(panel, /snapshotMatchesQuery\(snapshot, search\)/);
+ assert.match(panel, /setSnapshot\(\{ entries, at: Date\.now\(\), query: query\.trim\(\) \}\)/);
+ assert.match(
+ panel,
+ /const showingSnapshot =\s*\n\s*snapshotForQuery != null &&\s*\n\s*remote\.entries\.length === 0 &&\s*\n\s*\(remote\.status === "error" \|\| remote\.status === "loading"\)/,
+ );
+ assert.match(panel, /displayEntries\.filter\(matches\)/);
+ assert.match(panel, /settings\.mcpMarket\.remoteStaleSnapshot/);
+ // Pagination beyond the first page also refreshes the snapshot: the entries
+ // on screen after Load more are what a later failure should keep.
+ assert.match(panel, /if \(entries\.length > 0\) \{\s*\n\s*setSnapshot\(/);
+});
+
test("installed state comes from matching server ids", () => {
assert.match(panel, /installedIds\.includes\(entry\.id\)/);
assert.match(page, /installedIds=\{\[\.\.\.globalServers, \.\.\.projectServers\]/);
diff --git a/apps/desktop/test/skill-market-panel.test.mjs b/apps/desktop/test/skill-market-panel.test.mjs
index da04e4037..d85ab7719 100644
--- a/apps/desktop/test/skill-market-panel.test.mjs
+++ b/apps/desktop/test/skill-market-panel.test.mjs
@@ -120,6 +120,27 @@ test("failed and partial skill catalog searches can be retried", () => {
assert.match(panel, /setRemote\(\(current\) => \(\{ \.\.\.current, status: "loading" \}\)\)/);
});
+test("a failed query keeps the last successful list with its timestamp", () => {
+ // Issue #1692 follow-up: a source failure used to drop the whole list back to
+ // built-in picks, discarding what the user was just looking at. The panel now
+ // keeps the last successful result and says when it was taken.
+ assert.match(panel, /useState<MarketSnapshot<MarketItem> \| null>\(null\)/);
+ assert.match(panel, /snapshotMatchesQuery\(snapshot, search\)/);
+ assert.match(panel, /setSnapshot\(\{ entries, at: Date\.now\(\), query \}\)/);
+ // The fallback list answers the current query only, and only while the
+ // query itself has nothing to show — an empty `ready` answer is real.
+ assert.match(
+ panel,
+ /const showingSnapshot =\s*\n\s*snapshotForQuery != null &&\s*\n\s*remote\.entries\.length === 0 &&\s*\n\s*\(remote\.status === "error" \|\| remote\.status === "loading"\)/,
+ );
+ assert.match(panel, /displayEntries\.filter\(matches\)/);
+ assert.match(panel, /settings\.sklm\.remoteStaleSnapshot/);
+ assert.match(panel, /snapshotTimeText\(\s*\n?\s*snapshotForQuery\.at/);
+ // An empty response must not overwrite the snapshot: that would pin the
+ // pane to an empty list after one successful-but-empty query.
+ assert.match(panel, /if \(entries\.length > 0\) \{\s*\n\s*setSnapshot\(/);
+});
+
test("a resolver with no answer is explained as that, not as an address check", () => {
// Issue #419, second round: one `policy` bucket meant a local resolver that
// answered nothing produced the same sentence as an address the guard had
@@ -198,6 +219,7 @@ test("every shipped locale carries the new skill market strings", async () => {
"remoteErrorQuery",
"remotePartial",
"failureSourceHost",
+ "remoteStaleSnapshot",
];
for (const id of ids) {
const locale = await readFile(
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 3b3126aa4..a06c95fc1 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -707,7 +707,10 @@ system while preserving their different data ownership:
user sees that refusal while the same URL opens in their browser (ADR 0177).
A failed catalog query offers Retry; the same action remains available when
only some sources failed. It repeats the current search over the configured
- sources and announces loading while the request runs.
+ sources and announces loading while the request runs. After a successful
+ load, a later failure keeps that list on screen with the time it was taken
+ and still offers Retry; the retained list never answers a different query,
+ and it disappears once a retry succeeds.
Back reloads the skill list.
- Skills also exposes **Scan other tools** in its toolbar. The explicit scan
opens inline on the Skills page, and imported entries follow the current
@@ -719,7 +722,9 @@ system while preserving their different data ownership:
shown in candidate rows.
- MCP Market offers Retry after a failed query or partial source failure. It
repeats the current search through the existing market request path and
- announces loading while the request runs.
+ announces loading while the request runs. After a successful load, a later
+ failure keeps that list on screen with the time it was taken and still
+ offers Retry.
- The Subagents create/edit sheet pins a model with a searchable, provider-
grouped anchored menu — the same option-menu control the service picker uses
— over the configured, runnable models the Composer offers, plus an
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 5b00986fa..a0176f14c 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -16584,14 +16584,21 @@ plugin-form fixtures in an isolated temporary directory at runtime.
- **Preconditions**: Rendered Skill Market and MCP Market panels with the
market APIs stubbed at the IPC boundary. Each API returns a total failure,
- then a result with one failed source, then a complete result.
+ then a result with one failed source, then a complete result. A second run
+ loads a result first, fails afterwards, and recovers on retry; a third run
+ changes the query after a success so the failure carries a snapshot taken
+ for another query; a fourth run fails with nothing loaded.
- **Steps**: Open each market; click Retry after the total failure; confirm the
loading announcement and recovered entry; click Retry again after the
- partial failure.
+ partial failure. Then load a list, fail the next query, retry, and change
+ the query before failing once more.
- **Expected**: Both markets repeat the current search, show loading while the
request runs, retain a Retry action for partial failures, and clear the failed
- source after recovery. The test makes no live network request and does not
- change the main-process network policy.
+ source after recovery. After a successful load, a later failure keeps that
+ list on screen, says when it was taken, and still offers Retry; the retained
+ list disappears once a retry succeeds, and it never stands in for a
+ different query or for a failure with nothing loaded. The test makes no live
+ network request and does not change the main-process network policy.
- **Specs linked**: `04-ux/06-settings-ia.md`, ADR 0177, ADR 0272
- **Acceptance**: Quality
- **Milestone**: M6+
diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.md
index 39a02e805..18594deb8 100644
--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md
+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md
@@ -434,8 +434,8 @@ Token 用量**不是设置目的地**(D335 / ADR 0173)。已完成回合历
20. 命令 Shell 选择保留平台有效的目录 ID,仅在状态有额外信息时公开
默认、不可用、回退或无实际 Shell 文案,并且从不授权过时的 ID/dialect
21. 信息页提供「问题反馈」,打开已预填版本和操作系统的 GitHub bug 表单;设置搜索可索引该行
-22. 技能页的市场视图浏览公网 HTTPS 目录、预览组装后的文档,并只通过 `skills.create` 安装;超限展开文档拒绝写入,来源角标跟随 `sourceId`;预览失败时面板给出可读原因与重试入口(安装按钮可以禁用,但不得无解释地禁用);来源被公网策略守卫拒绝时明确说明,而不是笼统报「不可达」。目录查询全部失败或仅部分来源失败时都提供重试按钮;点击后按当前搜索和已配置来源重查,并在请求期间播报加载状态
-23. MCP 市场查询全部失败或部分来源失败时提供重试按钮;点击后重跑当前搜索,并在请求期间播报加载状态
+22. 技能页的市场视图浏览公网 HTTPS 目录、预览组装后的文档,并只通过 `skills.create` 安装;超限展开文档拒绝写入,来源角标跟随 `sourceId`;预览失败时面板给出可读原因与重试入口(安装按钮可以禁用,但不得无解释地禁用);来源被公网策略守卫拒绝时明确说明,而不是笼统报「不可达」。目录查询全部失败或仅部分来源失败时都提供重试按钮;点击后按当前搜索和已配置来源重查,并在请求期间播报加载状态。成功加载过后再遇失败时,列表保留上次成功加载的结果并标注时间,重试入口不变;该列表不回答其他搜索词,重试成功后即消失
+23. MCP 市场查询全部失败或部分来源失败时提供重试按钮;点击后重跑当前搜索,并在请求期间播报加载状态。成功加载过后再遇失败时,列表保留上次成功加载的结果并标注时间,重试入口不变
## 5. Chrome 指标常规
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 1bf5205a0..2a7454a1d 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
@@ -8689,9 +8689,9 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture
#### E2E-MARKET-CATALOG-RETRY:重试失败或部分可用的市场查询
-- **前提条件**:渲染技能市场和 MCP 市场面板,并在 IPC 边界模拟市场 API。每个 API 依次返回全部失败、一个来源失败的结果、完整成功结果。
-- **步骤**:打开两个市场;全部失败后点击重试;确认加载播报和恢复的目录条目;部分失败后再次点击重试。
-- **预期**:两个市场都按当前查询重新请求,期间显示加载状态;部分来源失败时仍有重试入口;来源恢复后失败项清除。测试不访问公网,也不改变主进程网络策略。
+- **前提条件**:渲染技能市场和 MCP 市场面板,并在 IPC 边界模拟市场 API。每个 API 依次返回全部失败、一个来源失败的结果、完整成功结果。第二组先加载成功、随后失败、重试后恢复;第三组在成功后切换搜索词再失败,使快照属于另一个查询;第四组在从未成功过的情况下失败。
+- **步骤**:打开两个市场;全部失败后点击重试;确认加载播报和恢复的目录条目;部分失败后再次点击重试。随后先加载出列表、令下一次查询失败、重试,再切换搜索词后失败一次。
+- **预期**:两个市场都按当前查询重新请求,期间显示加载状态;部分来源失败时仍有重试入口;来源恢复后失败项清除。成功加载过后再遇失败,列表保留上次成功加载的结果并标注时间,重试入口保留;重试成功后保留列表消失,且该列表不回答其他查询、也不在从未成功过时出现。测试不访问公网,也不改变主进程网络策略。
- **链接规格**:`04-ux/06-settings-ia.md`、ADR 0177、ADR 0272
- **验收**:Quality
- **里程碑**:M6+
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 3ee5d487a..fd4c40bfc 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -884,6 +884,7 @@ sklm: {
"Ein lokaler Proxy hat diesen Host auf einen fake-IP-Platzhalter in einem reservierten Bereich aufgelöst, nicht auf die echte Adresse der Quelle. Stelle den Proxy auf Systemproxy-Modus um oder prüfe Einstellungen → Allgemein → Netzwerk.",
remoteErrorQuery: "Der Skill-Markt konnte nicht abgefragt werden – integrierte Auswahl wird angezeigt",
remotePartial: "Einige Katalogquellen sind nicht verfügbar ({{names}})",
+ remoteStaleSnapshot: "Ergebnisse des letzten erfolgreichen Ladens werden angezeigt ({{time}})",
},
"title": "Einstellungen",
"providers": "KI-Anbieter",
@@ -1270,6 +1271,7 @@ sklm: {
remoteError: "Registry nicht erreichbar – integrierte Auswahl wird angezeigt",
remotePartial: "Einige Marktquellen sind nicht verfügbar ({{names}})",
retry: "Erneut versuchen",
+ remoteStaleSnapshot: "Ergebnisse des letzten erfolgreichen Ladens werden angezeigt ({{time}})",
manageSources: "Quellen",
sourcesHint: "Mehrere Marktquellen gleichzeitig abfragen. Registry-Quellen sprechen das offizielle MCP-Registrierungsprotokoll; Katalogquellen sind statische JSON-Dateien im Markt-Schema.",
addSource: "Quelle hinzufügen",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index a28e4dc3b..ef382349b 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -896,6 +896,7 @@ sklm: {
"A local proxy resolved this host to a fake-IP placeholder in a reserved range, not to the source's real address. Switch the proxy to system-proxy mode, or check Settings → General → Network.",
remoteErrorQuery: "Could not query the skill market — showing built-in picks",
remotePartial: "Some catalog sources are unavailable ({{names}})",
+ remoteStaleSnapshot: "Showing the results from your last successful load ({{time}})",
},
title: "Settings",
providers: "AI providers",
@@ -1124,6 +1125,7 @@ sklm: {
remoteError: "Registry unreachable — showing built-in picks",
remotePartial: "Some market sources are unavailable ({{names}})",
retry: "Retry",
+ remoteStaleSnapshot: "Showing the results from your last successful load ({{time}})",
manageSources: "Sources",
sourcesHint: "Query several market sources at once. Registry sources speak the official MCP registry protocol; catalog sources are static JSON files in the market schema.",
addSource: "Add source",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index dab1dccc4..0259becbc 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -884,6 +884,7 @@ sklm: {
"Un proxy local resolvió este host a un marcador fake-IP en un rango reservado, no a la dirección real de la fuente. Cambia el proxy al modo de proxy del sistema o revisa Ajustes → General → Red.",
remoteErrorQuery: "No se pudo consultar el mercado de skills: se muestran las selecciones integradas",
remotePartial: "Algunas fuentes del catálogo no están disponibles ({{names}})",
+ remoteStaleSnapshot: "Mostrando los resultados de la última carga correcta ({{time}})",
},
"title": "Configuración",
"providers": "Proveedores de IA",
@@ -1270,6 +1271,7 @@ sklm: {
remoteError: "Registro no disponible: se muestran las selecciones integradas",
remotePartial: "Algunas fuentes del mercado no están disponibles ({{names}})",
retry: "Reintentar",
+ remoteStaleSnapshot: "Mostrando los resultados de la última carga correcta ({{time}})",
manageSources: "Fuentes",
sourcesHint: "Consulta varias fuentes a la vez. Las fuentes de registro hablan el protocolo oficial MCP; las de catálogo son archivos JSON estáticos con el esquema del mercado.",
addSource: "Añadir fuente",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 701530342..72d89fa89 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -884,6 +884,7 @@ sklm: {
"Un proxy local a résolu cet hôte en une adresse factice d'une plage réservée, et non en l'adresse réelle de la source. Passez le proxy en mode proxy système, ou vérifiez Paramètres → Général → Réseau.",
remoteErrorQuery: "Impossible d'interroger le marché de skills – sélection intégrée affichée",
remotePartial: "Certaines sources du catalogue sont indisponibles ({{names}})",
+ remoteStaleSnapshot: "Affichage des résultats du dernier chargement réussi ({{time}})",
},
"title": "Paramètres",
"providers": "Fournisseurs d'IA",
@@ -1270,6 +1271,7 @@ sklm: {
remoteError: "Registre inaccessible – sélection intégrée affichée",
remotePartial: "Certaines sources du marché sont indisponibles ({{names}})",
retry: "Réessayer",
+ remoteStaleSnapshot: "Affichage des résultats du dernier chargement réussi ({{time}})",
manageSources: "Sources",
sourcesHint: "Interroge plusieurs sources à la fois. Les sources de registre parlent le protocole officiel MCP ; les sources de catalogue sont des fichiers JSON statiques au schéma du marché.",
addSource: "Ajouter une source",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index e4e1d2c10..ff9f4331c 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -893,6 +893,7 @@ sklm: {
"로컬 프록시가 이 호스트를 예약 대역의 fake-IP 자리표시자로 확인했습니다. 소스의 실제 주소가 아닙니다. 프록시를 시스템 프록시 모드로 전환하거나 설정 → 일반 → 네트워크를 확인하세요.",
remoteErrorQuery: "스킬 마켓을 조회하지 못했습니다. 내장 목록을 표시합니다",
remotePartial: "일부 카탈로그 소스를 사용할 수 없습니다 ({{names}})",
+ remoteStaleSnapshot: "마지막으로 성공한 불러오기의 결과를 표시합니다 ({{time}})",
},
title: "설정",
providers: "AI 프로바이더",
@@ -1280,6 +1281,7 @@ sklm: {
remoteError: "레지스트리에 연결할 수 없어 내장 목록을 표시합니다",
remotePartial: "일부 마켓 소스를 사용할 수 없습니다 ({{names}})",
retry: "다시 시도",
+ remoteStaleSnapshot: "마지막으로 성공한 불러오기의 결과를 표시합니다 ({{time}})",
manageSources: "마켓 소스",
sourcesHint: "여러 마켓 소스를 동시에 조회합니다. 레지스트리 소스는 공식 MCP 레지스트리 프로토콜을, 카탈로그 소스는 마켓 스키마의 정적 JSON 파일을 사용합니다.",
addSource: "소스 추가",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 54f3e679b..f74804837 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -871,7 +871,8 @@ export const ptBR = {
fakeIpHint: "Seu proxy respondeu {{host}} com {{address}}, uma faixa reservada usada como marcador fake-IP, não o endereço real da fonte. Altere o proxy para o modo de proxy do sistema ou revise Configurações → Geral → Rede.",
fakeIpHintPlain: "Um proxy local resolveu este host para um marcador fake-IP em uma faixa reservada, não o endereço real da fonte. Altere o proxy para o modo de proxy do sistema ou revise Configurações → Geral → Rede.",
remoteErrorQuery: "Não foi possível consultar o mercado de habilidades — exibindo seleções integradas",
- remotePartial: "Algumas fontes do catálogo não estão disponíveis ({{names}})"
+ remotePartial: "Algumas fontes do catálogo não estão disponíveis ({{names}})",
+ remoteStaleSnapshot: "Exibindo os resultados do último carregamento bem-sucedido ({{time}})"
},
title: "Configuração",
providers: "Provedores de IA",
@@ -1093,6 +1094,7 @@ export const ptBR = {
remoteError: "Registro inacessível — exibindo seleções integradas",
remotePartial: "Algumas fontes do mercado estão indisponíveis ({{names}})",
retry: "Tentar novamente",
+ remoteStaleSnapshot: "Exibindo os resultados do último carregamento bem-sucedido ({{time}})",
manageSources: "Fontes",
sourcesHint: "Consulte várias fontes do marketplace de uma só vez. Fontes de registro usam o protocolo oficial do MCP; fontes de catálogo são arquivos JSON estáticos no formato do marketplace.",
addSource: "Adicionar fonte",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index b8989edac..2340d8b7a 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -893,6 +893,7 @@ sklm: {
"Yerel bir proxy bu ana bilgisayarı ayrılmış bir aralıktaki fake-IP yer tutucusuna çözdü; kaynağın gerçek adresi değildir. Proxy'yi sistem proxy moduna alın veya Ayarlar → Genel → Ağ bölümünü kontrol edin.",
remoteErrorQuery: "Skill market sorgulanamadı – yerleşik seçkiler gösteriliyor",
remotePartial: "Bazı katalog kaynakları kullanılamıyor ({{names}})",
+ remoteStaleSnapshot: "Son başarılı yüklemenin sonuçları gösteriliyor ({{time}})",
},
title: "Ayarlar",
providers: "AI servisleri",
@@ -1274,6 +1275,7 @@ sklm: {
remoteError: "Kayıt erişilemiyor – yerleşik seçkiler gösteriliyor",
remotePartial: "Bazı market kaynakları kullanılamıyor ({{names}})",
retry: "Yeniden dene",
+ remoteStaleSnapshot: "Son başarılı yüklemenin sonuçları gösteriliyor ({{time}})",
manageSources: "Kaynaklar",
sourcesHint: "Birden fazla market kaynağını aynı anda sorgular. Kayıt kaynakları resmî MCP kayıt protokolünü; katalog kaynakları market şemasında statik JSON dosyalarını kullanır.",
addSource: "Kaynak ekle",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 7c026ae18..41c0437b1 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -884,6 +884,7 @@ sklm: {
"本地代理把该主机解析成了保留段里的 fake-IP 占位地址,而不是该源的真实地址。请把代理切换为系统代理模式,或检查 设置 → 通用 → 网络。",
remoteErrorQuery: "无法查询技能市场,已显示内置精选",
remotePartial: "部分目录源不可用({{names}})",
+ remoteStaleSnapshot: "正在显示上次成功加载的结果({{time}})",
},
title: "设置",
providers: "AI 服务",
@@ -1264,6 +1265,7 @@ sklm: {
remoteError: "官方注册表暂不可达,已显示内置精选",
remotePartial: "部分市场源暂不可用({{names}})",
retry: "重试",
+ remoteStaleSnapshot: "正在显示上次成功加载的结果({{time}})",
manageSources: "市场源",
sourcesHint: "同时查询多个市场源。Registry 型源走官方 MCP 注册表协议;目录型源是符合市场 schema 的静态 JSON 文件。",
addSource: "添加源",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 1ae7643a6..5854156ef 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -884,6 +884,7 @@ sklm: {
"本機代理將該主機解析成保留段中的 fake-IP 佔位位址,而不是該來源的真實位址。請將代理切換為系統代理模式,或檢查 設定 → 一般 → 網路。",
remoteErrorQuery: "無法查詢技能市場,已顯示內建精選",
remotePartial: "部分目錄源不可用({{names}})",
+ remoteStaleSnapshot: "正在顯示上次成功載入的結果({{time}})",
},
title: "設定",
providers: "AI 服務",
@@ -1264,6 +1265,7 @@ sklm: {
remoteError: "官方註冊表暫不可達,已顯示內建精選",
remotePartial: "部分市集來源暫時無法使用({{names}})",
retry: "重試",
+ remoteStaleSnapshot: "正在顯示上次成功載入的結果({{time}})",
manageSources: "市場源",
sourcesHint: "同時查詢多個市場源。Registry 型源走官方 MCP 註冊表協定;目錄型源是符合市集 schema 的靜態 JSON 檔案。",
addSource: "新增源",
diff --git a/scripts/e2e-market-retry.mjs b/scripts/e2e-market-retry.mjs
index 59edcead3..a81a3b341 100644
--- a/scripts/e2e-market-retry.mjs
+++ b/scripts/e2e-market-retry.mjs
@@ -3,9 +3,9 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { createRequire } from "node:module";
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
+import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveElectronBinary } from "./e2e/boot.mjs";
@@ -13,6 +13,7 @@ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const require = createRequire(join(root, "packages/agent-runtime/package.json"));
const { build } = require("esbuild");
const { electronBinary } = resolveElectronBinary(root);
+const evidence = process.env.PI_MARKET_EVIDENCE_DIR;
const temp = await mkdtemp(join(tmpdir(), "pi-market-retry-"));
try {
await build({
@@ -35,19 +36,37 @@ try {
join(temp, "index.html"),
'<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'; img-src \'self\' data:"><link rel="stylesheet" href="renderer.css"><title>Market retry interactions</title><body><script src="renderer.js"></script>',
);
+ const stageScript = evidence
+ ? [
+ ' const stages = ["error-with-snapshot", "retry-loading", "error-no-snapshot", "recovered"];',
+ ' const out = [];',
+ ' for (const stage of stages) {',
+ ' const result = await window.webContents.executeJavaScript(`globalThis.marketSnapshotStage(${JSON.stringify(stage)})`);',
+ ' await window.webContents.executeJavaScript("document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))))");',
+ ' const png = await window.webContents.capturePage();',
+ ' const target = path.join(__dirname, "shots", stage + ".png");',
+ ' await fs.mkdir(path.join(__dirname, "shots"), { recursive: true });',
+ ' await fs.writeFile(target, png.toPNG());',
+ ' out.push({ stage, ...result });',
+ ' }',
+ ' console.log("MARKET_SNAPSHOT_SHOTS " + JSON.stringify(out));',
+ ].join("\n")
+ : "";
await writeFile(
join(temp, "main.cjs"),
[
'const { app, BrowserWindow } = require("electron");',
'const path = require("node:path");',
+ 'const fs = require("node:fs/promises");',
'app.setPath("userData", path.join(__dirname, "profile"));',
'app.whenReady().then(async () => {',
- ' const window = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } });',
+ ' const window = new BrowserWindow({ show: false, width: 1280, height: 800, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });',
' window.webContents.on("console-message", (event) => console.error(event.message));',
' try {',
' await window.loadFile(path.join(__dirname, "index.html"));',
' const result = await window.webContents.executeJavaScript("globalThis.marketRetryProbe()");',
' console.log("MARKET_RETRY_PROBE " + JSON.stringify(result));',
+ stageScript,
' app.quit();',
' } catch (error) {',
' console.error("MARKET_RETRY_PROBE " + JSON.stringify({ ok: false, error: String(error) }));',
@@ -68,7 +87,7 @@ try {
output += data;
});
}
- const timeout = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 90_000);
let code;
try {
code = await new Promise((resolve, reject) => {
@@ -84,6 +103,21 @@ try {
console.log("MARKET_RETRY_PROBE " + JSON.stringify(result));
assert.equal(code, 0, output.slice(-6000));
assert.equal(result.ok, true);
+ if (evidence) {
+ const shots = output
+ .split(/\r?\n/)
+ .find((entry) => entry.startsWith("MARKET_SNAPSHOT_SHOTS "));
+ assert(shots, `renderer returned no stage shots: ${output.slice(-2000)}`);
+ await mkdir(resolve(evidence), { recursive: true });
+ const staged = JSON.parse(shots.slice("MARKET_SNAPSHOT_SHOTS ".length));
+ for (const stage of staged) {
+ assert.equal(stage.ok, true, `${stage.stage}: ${JSON.stringify(stage)}`);
+ const from = join(temp, "shots", `${stage.stage}.png`);
+ const to = join(resolve(evidence), `${stage.stage}.png`);
+ await (await import("node:fs/promises")).copyFile(from, to);
+ }
+ console.log(`MARKET_SNAPSHOT_SHOTS ok=${staged.length} dir=${resolve(evidence)}`);
+ }
} finally {
await rm(temp, { recursive: true, force: true });
}
diff --git a/scripts/e2e/market-retry.tsx b/scripts/e2e/market-retry.tsx
index e6f023ee6..2f58be190 100644
--- a/scripts/e2e/market-retry.tsx
+++ b/scripts/e2e/market-retry.tsx
@@ -12,6 +12,7 @@ import "../../apps/desktop/src/styles/settings.css";
declare global {
var marketRetryProbe: () => Promise<unknown>;
+ var marketSnapshotStage: (stage: string) => Promise<unknown>;
}
const assert = (condition: unknown, message: string) => {
@@ -47,38 +48,78 @@ const mcpEntry: McpCatalogEntry = {
categories: ["devtools"],
};
-globalThis.marketRetryProbe = async () => {
- const i18n = createInstance();
- await i18n.init({
- lng: "en",
- resources: { en: { translation: catalogs.en }, "zh-CN": { translation: catalogs["zh-CN"] } },
- });
+let i18n: ReturnType<typeof createInstance>;
+let container: HTMLDivElement | null = null;
+let root: ReturnType<typeof createRoot> | null = null;
+
+/** Drop the current mount point so the next `boot()` starts from an empty page. */
+function teardown() {
+ if (root) {
+ flushSync(() => root!.unmount());
+ root = null;
+ }
+ if (container) {
+ container.remove();
+ container = null;
+ }
+}
+
+async function boot() {
+ // Stages run one after another in the same window, and a viewport capture
+ // shows whatever sits at the top of the page — a leftover container would
+ // make every screenshot show the first stage's panel.
+ teardown();
+ if (!i18n) {
+ i18n = createInstance();
+ await i18n.init({
+ lng: "en",
+ resources: { en: { translation: catalogs.en }, "zh-CN": { translation: catalogs["zh-CN"] } },
+ });
+ }
api.getSettings = async () => structuredClone(settings);
- const container = document.createElement("div");
+ container = document.createElement("div");
document.body.append(container);
- const root = createRoot(container);
- const render = (panel: "skill" | "mcp") =>
- flushSync(() =>
- root.render(
- <I18nextProvider i18n={i18n}>
- {panel === "skill" ? (
- <SkillMarketPanel installedIds={[]} onBack={() => {}} onInstalled={() => {}} />
- ) : (
- <McpMarketPanel installedIds={[]} onBack={() => {}} onInstalled={() => {}} />
- )}
- </I18nextProvider>,
- ),
- );
- const click = (element: HTMLElement | undefined | null) => {
- assert(element, "missing retry button");
- flushSync(() => element!.click());
- };
- const button = (label: string) =>
- [...container.querySelectorAll<HTMLButtonElement>("button")].find(
- (element) => element.textContent?.trim() === label,
- );
- const status = () => container.querySelector<HTMLElement>('[role="status"]')?.textContent ?? "";
+ root = createRoot(container);
+}
+
+function mount(panel: "skill" | "mcp") {
+ flushSync(() => root!.render(<div />));
+ flushSync(() =>
+ root!.render(
+ <I18nextProvider i18n={i18n}>
+ {panel === "skill" ? (
+ <SkillMarketPanel installedIds={[]} onBack={() => {}} onInstalled={() => {}} />
+ ) : (
+ <McpMarketPanel installedIds={[]} onBack={() => {}} onInstalled={() => {}} />
+ )}
+ </I18nextProvider>,
+ ),
+ );
+}
+const click = (element: HTMLElement | undefined | null) => {
+ assert(element, "missing retry button");
+ flushSync(() => element!.click());
+};
+const button = (label: string) =>
+ [...container!.querySelectorAll<HTMLButtonElement>("button")].find(
+ (element) => element.textContent?.trim() === label,
+ );
+const status = () => container!.querySelector<HTMLElement>('[role="status"]')?.textContent ?? "";
+const snapshotLine = () =>
+ container!.querySelector<HTMLElement>(".sklm-status.is-snapshot, .mcpm-status.is-snapshot");
+const typeSearch = (value: string) => {
+ const input = container!.querySelector<HTMLInputElement>(".sklm-search-input, .mcpm-search-input");
+ assert(input, "missing search input");
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ flushSync(() => {
+ setter.call(input, value);
+ input!.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+};
+
+globalThis.marketRetryProbe = async () => {
+ await boot();
try {
for (const locale of ["en", "zh-CN"]) {
await i18n.changeLanguage(locale);
@@ -89,7 +130,7 @@ globalThis.marketRetryProbe = async () => {
if (skillCalls === 2) return { entries: [skillEntry], failedSources: ["obra/superpowers"] };
return { entries: [skillEntry], failedSources: [] };
};
- render("skill");
+ mount("skill");
await until(
() => status().includes(i18n.t("settings.sklm.remoteError")) || status().includes(i18n.t("settings.sklm.remoteErrorQuery")),
`${locale}: skill market error status missing`,
@@ -101,6 +142,53 @@ globalThis.marketRetryProbe = async () => {
click(button(i18n.t("settings.sklm.retryCatalog")));
await until(() => skillCalls === 3 && !container.textContent?.includes("obra/superpowers"), `${locale}: second skill retry did not clear partial failure`);
+ // --- Snapshot behavior: the last successful list survives a later failure.
+ let snapCalls = 0;
+ api.searchSkillMarket = async () => {
+ snapCalls += 1;
+ if (snapCalls === 1) return { entries: [skillEntry], failedSources: ["obra/superpowers"] };
+ if (snapCalls === 2) return { entries: [], failedSources: ["anthropics/skills", "obra/superpowers"] };
+ return { entries: [skillEntry], failedSources: [] };
+ };
+ mount("skill");
+ await until(() => snapCalls === 1 && container.textContent?.includes("Recovered Skill") === true, `${locale}: snapshot run 1 did not load`);
+ assert(!snapshotLine(), `${locale}: snapshot line shown before any failure`);
+ click(button(i18n.t("settings.sklm.retryCatalog")));
+ await until(
+ () => status().includes(i18n.t("settings.sklm.remoteError")) || status().includes(i18n.t("settings.sklm.remoteErrorQuery")),
+ `${locale}: snapshot run 2 did not fail`,
+ );
+ assert(snapshotLine(), `${locale}: failure with a snapshot shows no snapshot line`);
+ assert(container.textContent?.includes("Recovered Skill") === true, `${locale}: retained list is missing after failure`);
+ assert(button(i18n.t("settings.sklm.retryCatalog")), `${locale}: retained failure lost its retry`);
+ click(button(i18n.t("settings.sklm.retryCatalog")));
+ await until(() => snapCalls === 3 && !snapshotLine(), `${locale}: recovery kept the snapshot line`);
+
+ // A snapshot answers its own query only: a different search that fails
+ // must not be covered by results taken for another one.
+ let mismatchCalls = 0;
+ api.searchSkillMarket = async () => {
+ mismatchCalls += 1;
+ if (mismatchCalls === 1) return { entries: [skillEntry], failedSources: [] };
+ return { entries: [], failedSources: ["anthropics/skills"] };
+ };
+ mount("skill");
+ await until(() => mismatchCalls === 1 && container.textContent?.includes("Recovered Skill") === true, `${locale}: mismatch run 1 did not load`);
+ typeSearch("zzz");
+ await until(() => mismatchCalls === 2, `${locale}: mismatch query was never sent`);
+ await until(() => status().includes(i18n.t("settings.sklm.remoteError")), `${locale}: mismatch query did not fail`);
+ assert(!snapshotLine(), `${locale}: a snapshot for another query covered this one`);
+
+ // A fresh failure with nothing to fall back to stays as before: no line.
+ let bareCalls = 0;
+ api.searchSkillMarket = async () => {
+ bareCalls += 1;
+ return { entries: [], failedSources: ["anthropics/skills"] };
+ };
+ mount("skill");
+ await until(() => bareCalls === 1 && status().includes(i18n.t("settings.sklm.remoteError")), `${locale}: bare failure did not render`);
+ assert(!snapshotLine(), `${locale}: empty first failure claimed a snapshot`);
+
flushSync(() => root.render(<div />));
let mcpCalls = 0;
api.searchMcpMarketRegistry = async () => {
@@ -109,7 +197,7 @@ globalThis.marketRetryProbe = async () => {
if (mcpCalls === 2) return { entries: [mcpEntry], failedSources: ["community catalog"] };
return { entries: [mcpEntry], failedSources: [] };
};
- render("mcp");
+ mount("mcp");
await until(() => status().includes(i18n.t("settings.mcpMarket.remoteError")), `${locale}: MCP market error status missing`);
click(button(i18n.t("settings.mcpMarket.retry")));
await until(() => status().includes(i18n.t("settings.mcpMarket.remoteLoading")), `${locale}: MCP retry did not announce loading`);
@@ -117,10 +205,78 @@ globalThis.marketRetryProbe = async () => {
await until(() => button(i18n.t("settings.mcpMarket.retry")) !== undefined, `${locale}: partial MCP failure has no retry`);
click(button(i18n.t("settings.mcpMarket.retry")));
await until(() => mcpCalls === 3 && !container.textContent?.includes("community catalog"), `${locale}: second MCP retry did not clear partial failure`);
+
+ // MCP snapshot: same contract as the skill market.
+ let mcpSnap = 0;
+ api.searchMcpMarketRegistry = async () => {
+ mcpSnap += 1;
+ if (mcpSnap === 1) return { entries: [mcpEntry], failedSources: ["community catalog"] };
+ if (mcpSnap === 2) return { entries: [], failedSources: ["official registry"] };
+ return { entries: [mcpEntry], failedSources: [] };
+ };
+ mount("mcp");
+ await until(() => mcpSnap === 1 && container.textContent?.includes("Recovered Server") === true, `${locale}: MCP snapshot run 1 did not load`);
+ click(button(i18n.t("settings.mcpMarket.retry")));
+ await until(() => status().includes(i18n.t("settings.mcpMarket.remoteError")), `${locale}: MCP snapshot run 2 did not fail`);
+ assert(snapshotLine(), `${locale}: MCP failure with a snapshot shows no snapshot line`);
+ assert(container.textContent?.includes("Recovered Server") === true, `${locale}: MCP retained list is missing`);
}
return { ok: true };
} finally {
- flushSync(() => root.unmount());
- container.remove();
+ teardown();
+ }
+};
+
+/**
+ * One state per call, for review screenshots: `error-with-snapshot`,
+ * `retry-loading`, `error-no-snapshot`, `recovered`. Renders with zh-CN, the
+ * locale the reviewer reads, and leaves the state painted when it resolves.
+ */
+globalThis.marketSnapshotStage = async (stage: string) => {
+ await boot();
+ await i18n.changeLanguage("zh-CN");
+ const skillCalls = { count: 0 };
+ let pending: ((value: unknown) => void) | null = null;
+ api.searchSkillMarket = async () => {
+ skillCalls.count += 1;
+ if (stage === "error-no-snapshot") {
+ return { entries: [], failedSources: ["anthropics/skills", "obra/superpowers"] };
+ }
+ if (skillCalls.count === 1) {
+ return { entries: [skillEntry], failedSources: ["obra/superpowers"] };
+ }
+ if (stage === "retry-loading" && skillCalls.count === 3) {
+ // Third call hangs: the retry is in flight while the snapshot shows.
+ return new Promise((resolve) => {
+ pending = resolve;
+ });
+ }
+ if (stage === "recovered" && skillCalls.count === 3) {
+ // Second call fails (snapshot keeps the list), third recovers.
+ return { entries: [skillEntry], failedSources: [] };
+ }
+ return { entries: [], failedSources: ["anthropics/skills", "obra/superpowers"] };
+ };
+ mount("skill");
+ if (stage === "error-no-snapshot") {
+ await until(() => status().includes(i18n.t("settings.sklm.remoteError")), "no-snapshot error missing");
+ } else {
+ await until(() => container.textContent?.includes("Recovered Skill") === true, `${stage}: first load missing`);
+ }
+ if (stage === "error-with-snapshot" || stage === "retry-loading") {
+ click(button(i18n.t("settings.sklm.retryCatalog")));
+ await until(() => status().includes(i18n.t("settings.sklm.remoteError")), `${stage}: failure missing`);
+ }
+ if (stage === "retry-loading") {
+ click(button(i18n.t("settings.sklm.retryCatalog")));
+ await until(() => status().includes(i18n.t("settings.sklm.remoteLoading")), "retry-loading state missing");
+ }
+ if (stage === "recovered") {
+ click(button(i18n.t("settings.sklm.retryCatalog")));
+ await until(() => status().includes(i18n.t("settings.sklm.remoteError")), "recovered: failure missing");
+ click(button(i18n.t("settings.sklm.retryCatalog")));
+ await until(() => !snapshotLine() && container.textContent?.includes("Recovered Skill") === true, "recovered: list missing");
}
+ await painted();
+ return { ok: true, stage, pending: pending !== null };
};