Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): 主题导入被拒时原因留在对话框里与被点的那张卡片上(条目 7.63)

lmliheng68864f88d476
diff --git a/changelog/unreleased/2026-11-01-theme-import-refusal.md b/changelog/unreleased/2026-11-01-theme-import-refusal.md
new file mode 100644
index 00000000..acb02b33
--- /dev/null
+++ b/changelog/unreleased/2026-11-01-theme-import-refusal.md
@@ -0,0 +1,58 @@
+# A refused theme import says why in the dialog, and on the card, instead of in a toast that expires
+
+- **Date:** 2026-11-01
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-11-01-theme-import-refusal.zh.md)
+
+Importing a theme happens on two surfaces of the appearance page, and both kept their refusal
+nowhere. The dialog (a picked `.json` file, or an address the server fetches) stays open on a
+failure — nothing was written, and the picked file or the typed address is still there to retry —
+but the reason went to a toast that dismissed itself after six seconds, above a dialog that said
+nothing about what had just failed. The library's cards are the same story one level down: a card
+is a theme and one import button, the button writes nothing optimistically, and a refused import
+(that entry is gone from the catalogue, its file is not the id it was listed under, the fetch
+failed) left every card looking exactly as it did, with the explanation in that same six-second
+toast. With two or more cards on screen, the toast did not even say which one to think about.
+
+Both surfaces now keep the sentence where the import was asked: the dialog draws it under the file
+or the address field, and a card draws it under its own import button. Both use the shared lead-in
+`S.common.refused`, the danger ink and `role="alert"`; the card's line is clamped to two lines with
+the whole sentence on hover. No new copy was written — every code already had its own localized
+sentence in `themeImportErrorText`.
+
+## Details
+
+- `packages/web/src/features/settings/theme-import.ts`: `themeImportRefusal(err)` — the rule "409
+ `theme_exists` is a question (open the overwrite confirmation), everything else is a refusal"
+ now lives here once, returning `null` for the question and the existing sentence otherwise. Both
+ callers had written that branch out themselves; neither could have got it right by accident.
+- `packages/web/src/features/settings/theme-import-dialog.tsx`: a `refusal` state, filled from the
+ failed import instead of `toastError`, cleared when the dialog opens, when it closes, when the
+ source switches (a sentence about a file must not sit beside a URL) and when the next attempt
+ starts; the sentence is a `NoticeStrip` at the bottom of the dialog's body, under the source it
+ was about. A 409 still opens the overwrite card, which resends that very request.
+- `packages/web/src/features/settings/theme-registry-section.tsx`: a `refusal` of `{id, text}` —
+ one attempt at a time, like the import itself — cleared by the next attempt and by every
+ re-read of the catalogue (a sentence about a card of the old grid is stale); the card whose
+ button was refused draws it, and no other card does.
+
+## Tests
+
+- `packages/web/test/theme-import.test.ts` (+3 unit cases): the 409 is the only answer that comes
+ back as "ask"; every other code — including a 409 with some other code, which has no card to
+ open — is a refusal carrying the same sentence the failure mapping gives, and never an empty
+ line.
+- `packages/web/e2e/theme-import-refusal.spec.mjs` (new, three browser cases against the real
+ server, catalogue stubbed): a refused registry import leaves the reason on that card and nowhere
+ else, with no dismissible toast and the line still there seven seconds later, and the same
+ button lands once the refusal is lifted; a 409 still opens the overwrite question instead of
+ drawing a line; a refused import by address keeps the dialog, the address and the reason, and
+ the confirm beside it retries that same address.
+
+## Compatibility
+
+- No API, catalogue or request-shape change: the dialog sends the same bodies and the card sends
+ the same `{id, overwrite}`. Only the failed paths stopped using a toast.
diff --git a/changelog/unreleased/2026-11-01-theme-import-refusal.zh.md b/changelog/unreleased/2026-11-01-theme-import-refusal.zh.md
new file mode 100644
index 00000000..81fdc68c
--- /dev/null
+++ b/changelog/unreleased/2026-11-01-theme-import-refusal.zh.md
@@ -0,0 +1,46 @@
+# 主题导入被拒时,原因留在对话框里、留在被点的那张卡片上,不再只活六秒
+
+- **日期:** 2026-11-01
+- **类型:** fix
+- **范围:** `web`
+- **破坏性:** 无
+
+[English](2026-11-01-theme-import-refusal.md)
+
+外观页上有两处「导入主题」,此前两处被拒时都把原因弄丢了。对话框(选一个 `.json` 文件,或交给
+服务端去取一个地址)在失败时本来就是留着的 —— 什么都没写进去,选好的文件或亲手敲的地址都还在,
+按同一个按钮就是重试 —— 但原因进了六秒后自己消失的 toast,浮在一个对此一声不吭的对话框上面。
+主题库的卡片是同一件事的下一层:一张卡就是一个主题加一颗导入按钮,按钮不做乐观写入,而被拒的
+导入(目录里已经没有这一条、它指向的文件不是那个 id、取不回来)让每一张卡看起来都和点之前一样,
+解释同样在那条六秒的 toast 里。屏上不止一张卡时,那条 toast 甚至没有说是哪一张。
+
+现在两处都把这句话留在发起导入的地方:对话框画在文件 / 地址字段下面,卡片画在自己那颗导入按钮
+下面。两处都用共享引子 `S.common.refused`、danger 色与 `role="alert"`;卡片那一行限两行、整句
+挂悬停。没有新增文案 —— 每个码在 `themeImportErrorText` 里本来就有自己的本地化句子。
+
+## 细节
+
+- `packages/web/src/features/settings/theme-import.ts`:新增 `themeImportRefusal(err)` —— 「409
+ `theme_exists` 是问题(去开覆盖确认),其余都是拒绝」这条规则从此只有一处:前者返回 `null`,
+ 后者给已有的那句话。两个调用方此前各自把这条分支写了一遍。
+- `packages/web/src/features/settings/theme-import-dialog.tsx`:多一个 `refusal` 状态,由失败的导入
+ 填上(不再走 `toastError`),开框、关框、切换来源(关于文件的句子不能留在地址旁边)与下一次
+ 尝试开始时各清一次;句子是对话框正文底部的一条 `NoticeStrip`,就在它针对的那个来源下面。409
+ 照旧打开覆盖确认,确认后重发的就是那条请求。
+- `packages/web/src/features/settings/theme-registry-section.tsx`:`refusal` 记「哪张卡、哪句话」,
+ 一次一条(与导入本身一样),下一次尝试与每一次重读目录都清空(关于旧网格里某张卡的句子是过期的);
+ 只有被点的那张卡画它,别的卡一个字都不加。
+
+## 测试
+
+- `packages/web/test/theme-import.test.ts`(+3 条单测):409 是唯一一种「去问」的答复;其余每个码
+ —— 包括行为上另一个码的 409,它没有卡片可开 —— 都是拒绝,带的就是失败映射给的那句话,且绝不为空。
+- `packages/web/e2e/theme-import-refusal.spec.mjs`(新,真服务端三条,目录是假数据):被拒的主题库
+ 导入把原因留在那一张卡上、别处没有,通知区里没有可点的 toast,七秒后那一行仍在,放开拒绝后同
+ 一颗按钮真的落地;409 照旧打开覆盖确认、不画那句话;按地址导入被拒时对话框、地址与原因都留着,
+ 旁边的确认按钮重试的是同一个地址。
+
+## 兼容
+
+- 接口、目录格式、请求体都没变:对话框发的还是原来那两个正文,卡片发的还是同一个 `{id, overwrite}`。
+ 只有失败那条路不再用 toast。
diff --git a/packages/web/e2e/theme-import-refusal.spec.mjs b/packages/web/e2e/theme-import-refusal.spec.mjs
new file mode 100644
index 00000000..f76bdab2
--- /dev/null
+++ b/packages/web/e2e/theme-import-refusal.spec.mjs
@@ -0,0 +1,258 @@
+/**
+ * Regression: a theme import that was REFUSED says why where it was asked — inside the import
+ * dialog, and on the registry card whose button was clicked — and the sentence outlives the six
+ * seconds a toast lives.
+ *
+ * Both surfaces stayed as they were on a failure: the dialog kept its file or address (nothing was
+ * written), the card kept its button, and the reason arrived as a notification that dismissed
+ * itself over them. A reader who looked away was left with a dialog that would not close on
+ * success and a grid of cards that all looked untouched, without knowing which one to think about.
+ *
+ * The catalogue is stubbed rather than fetched: a registry is a remote index (the server reads
+ * npmmirror, then jsDelivr), and what this spec is about is what the page does with the answer.
+ * The refusals are codes the app has its own sentence for, so the line on screen is the localized
+ * one — `registry_theme_not_found` on a card, `download_failed` in the dialog — and a 409
+ * `theme_exists` still opens the overwrite question instead of becoming a line.
+ */
+import { test, expect } from "@playwright/test";
+import { ADMIN_ID, ADMIN_PASSWORD, login } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+
+/** The line a refused card / import draws: the shared lead-in plus the app's sentence for the code. */
+const CARD_REFUSED = "操作被拒绝:主题库里已经没有这个主题了,刷新一下再看。";
+const DIALOG_REFUSED = "操作被拒绝:取不回来:地址、网络或对方的状态码有问题。";
+
+/** The catalogue both tests see: two cards, neither of them installed. */
+const CATALOGUE = {
+ base: "https://registry.example.invalid/",
+ name: "probe registry",
+ updatedAt: "2026-11-01T00:00:00Z",
+ fetchedAt: 0,
+ themes: [
+ {
+ id: "probe-warm",
+ name: "Probe Warm",
+ author: "probe",
+ description: "a warm card",
+ file: "themes/probe-warm.json",
+ version: "1.0.0",
+ installed: false,
+ },
+ {
+ id: "probe-cool",
+ name: "Probe Cool",
+ author: "probe",
+ description: "a cool card",
+ file: "themes/probe-cool.json",
+ version: "1.0.0",
+ installed: false,
+ },
+ ],
+};
+
+/** What an import that lands answers: the file it wrote and the theme inside it. */
+const IMPORTED = { file: "probe-warm.json", theme: { id: "probe-warm", name: "Probe Warm" } };
+
+/**
+ * Sign in as the seeded administrator (both surfaces are the admin's) and give the Project a
+ * model — the onboarding overlay covers the page without one.
+ */
+async function ready(page) {
+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);
+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+ return projectId;
+}
+
+/** The settings dialog, opened the way a person opens it: the user menu, then 外观. */
+async function openAppearance(page) {
+ // The user menu shares its name with the Project switcher, so take the last match (as chat.spec).
+ await page.getByRole("button", { name: ADMIN_ID }).last().click();
+ await page.getByRole("menuitem", { name: "设置", exact: true }).click();
+ const settings = page.getByRole("dialog", { name: "设置" });
+ await expect(settings).toBeVisible();
+ await settings.getByRole("button", { name: "外观", exact: true }).click();
+ return settings;
+}
+
+/** One card of the registry grid, found by the name it shows: the card is the name's nearest div. */
+function cardOf(scope, name) {
+ return scope.getByText(name, { exact: true }).locator("xpath=ancestor::div[1]");
+}
+
+/** Refuse the registry import with the answer "that entry is gone"; counted, and switchable. */
+async function refuseRegistryImport(page, seen) {
+ let refuse = true;
+ await page.route("**/api/themes/registry/import", async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ seen.push(route.request().postDataJSON());
+ if (!refuse) {
+ await route.fulfill({
+ status: 201,
+ contentType: "application/json",
+ body: JSON.stringify(IMPORTED),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 404,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: { code: "registry_theme_not_found", message: "No such theme: probe-warm" },
+ }),
+ });
+ });
+ return () => {
+ refuse = false;
+ };
+}
+
+test("a refused registry import keeps its reason on that card, and only that card", async ({
+ page,
+}) => {
+ await ready(page);
+ await page.route("**/api/themes/registry", (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(CATALOGUE),
+ }),
+ );
+ const attempts = [];
+ const letThrough = await refuseRegistryImport(page, attempts);
+
+ await page.goto("/");
+ const settings = await openAppearance(page);
+ const warm = cardOf(settings, "Probe Warm");
+ const cool = cardOf(settings, "Probe Cool");
+ await expect(warm).toBeVisible();
+ await expect(cool).toBeVisible();
+
+ await warm.getByRole("button", { name: "导入", exact: true }).click();
+
+ // The reason is on the card that asked, it is not a toast, and the other card says nothing.
+ await expect(warm.getByRole("alert")).toHaveText(CARD_REFUSED);
+ await expect(cool.getByRole("alert")).toHaveCount(0);
+ await expect(page.getByRole("region", { name: "通知" }).getByRole("button")).toHaveCount(0);
+ expect(attempts.map((body) => body.id)).toEqual(["probe-warm"]);
+
+ // Six seconds is how long a toast lives; this line has to still be there after it.
+ await page.waitForTimeout(7_000);
+ await expect(warm.getByRole("alert")).toHaveText(CARD_REFUSED);
+
+ // The same button, second click: this time the import lands, so the sentence goes.
+ letThrough();
+ await warm.getByRole("button", { name: "导入", exact: true }).click();
+ await expect(warm.getByRole("alert")).toHaveCount(0);
+ expect(attempts).toHaveLength(2);
+});
+
+test("a 409 still asks to overwrite instead of drawing a refusal", async ({ page }) => {
+ await ready(page);
+ await page.route("**/api/themes/registry", (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(CATALOGUE),
+ }),
+ );
+ await page.route("**/api/themes/registry/import", (route) =>
+ route.fulfill({
+ status: 409,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: { code: "theme_exists", message: "A theme with this id is already installed" },
+ }),
+ }),
+ );
+
+ await page.goto("/");
+ const settings = await openAppearance(page);
+ const warm = cardOf(settings, "Probe Warm");
+ await expect(warm).toBeVisible();
+
+ await warm.getByRole("button", { name: "导入", exact: true }).click();
+
+ // The question, not a refusal: the overwrite card is up and the grid kept its silence.
+ await expect(page.getByRole("dialog", { name: "覆盖已导入的主题" })).toBeVisible();
+ await expect(warm.getByRole("alert")).toHaveCount(0);
+});
+
+test("a refused theme dialog keeps its reason in the dialog, under the address it was about", async ({
+ page,
+}) => {
+ await ready(page);
+ await page.route("**/api/themes/registry", (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(CATALOGUE),
+ }),
+ );
+ let refuse = true;
+ const attempts = [];
+ await page.route("**/api/themes/download", async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ attempts.push(route.request().postDataJSON());
+ if (!refuse) {
+ await route.fulfill({
+ status: 201,
+ contentType: "application/json",
+ body: JSON.stringify(IMPORTED),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 400,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: { code: "download_failed", message: "GET https://example.com/theme.json failed" },
+ }),
+ });
+ });
+
+ await page.goto("/");
+ await openAppearance(page);
+ await page.getByRole("button", { name: "导入主题…", exact: true }).click();
+ const dialog = page.getByRole("dialog", { name: "导入主题" });
+ await expect(dialog).toBeVisible();
+
+ // By address, so no file has to be written: the server would fetch it, and the route answers first.
+ await dialog.getByRole("button", { name: "地址", exact: true }).click();
+ const address = dialog.getByLabel("主题文件地址");
+ await address.fill("https://example.com/theme.json");
+ await dialog.getByRole("button", { name: "下载并导入", exact: true }).click();
+
+ // The dialog stays with both the address and the reason; nothing lands in the notification area.
+ await expect(dialog.getByRole("alert")).toHaveText(DIALOG_REFUSED);
+ await expect(dialog).toBeVisible();
+ await expect(address).toHaveValue("https://example.com/theme.json");
+ await expect(page.getByRole("region", { name: "通知" }).getByRole("button")).toHaveCount(0);
+ expect(attempts.map((body) => body.url)).toEqual(["https://example.com/theme.json"]);
+
+ await page.waitForTimeout(7_000);
+ await expect(dialog.getByRole("alert")).toHaveText(DIALOG_REFUSED);
+
+ // The confirm beside it retries the same address; this time it lands and the dialog closes.
+ refuse = false;
+ await dialog.getByRole("button", { name: "下载并导入", exact: true }).click();
+ await expect(dialog).toHaveCount(0);
+ expect(attempts).toHaveLength(2);
+});
diff --git a/packages/web/src/features/settings/theme-import-dialog.tsx b/packages/web/src/features/settings/theme-import-dialog.tsx
index c50faaea..8d767e67 100644
--- a/packages/web/src/features/settings/theme-import-dialog.tsx
+++ b/packages/web/src/features/settings/theme-import-dialog.tsx
@@ -14,8 +14,10 @@
* Both flows are the same import twice, as in the plugin dialogs: one carries the file in the
* request, the other a URL the server fetches, and a 409 `theme_exists` opens the overwrite
* confirmation whose confirm resends THAT request with `overwrite: true` (so the user never picks
- * the file twice), while any other failure rolls back to a toast. The list is re-read on success,
- * which is how the new theme appears in the picker above.
+ * the file twice), while any other failure is kept in the dialog's own body — the file or the
+ * address is still there, the confirm button still sends it, and the reason belongs beside them
+ * rather than in a notification that dismisses itself over an open dialog. The list is re-read on
+ * success, which is how the new theme appears in the picker above.
*
* Admin-only by the server's own rule — the themes directory is installation-level, and every
* browser that signs in on this machine is painted by it — so the caller (the appearance section)
@@ -29,17 +31,17 @@ import {
HiddenFileInput,
Input,
Modal,
+ NoticeStrip,
Segmented,
toastError,
toastSuccess,
} from "@adelie/ui";
import * as api from "../../api/endpoints";
-import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
import { useLocale } from "../../state/locale";
import { localizedText } from "../chat/skill-use";
import { UPLOAD_LABEL_CLASS } from "../agents/skills-tab";
-import { themeFileTooLarge, themeImportErrorText } from "./theme-import";
+import { themeFileTooLarge, themeImportRefusal } from "./theme-import";
/** Which way the file arrives: picked here, or fetched by the server from an address. */
type Source = "upload" | "download";
@@ -73,10 +75,17 @@ export function ThemeImportActions({
const [url, setUrl] = useState("");
// The 409 confirmation, the only state the two flows share.
const [pending, setPending] = useState<ImportRequest | null>(null);
+ /**
+ * The last attempt's refusal, kept in the dialog's body. It belongs to the request that was sent
+ * (a picked file, an address), so opening the dialog, closing it, switching the source and the
+ * next attempt each clear it: a sentence about the file must not sit beside a URL.
+ */
+ const [refusal, setRefusal] = useState<string | null>(null);
const close = () => {
setOpen(false);
setPicked(null);
+ setRefusal(null);
};
/** Success path, shared by both flows: close, toast, re-read the list. */
@@ -90,20 +99,23 @@ export function ThemeImportActions({
};
/**
- * A 409 lands in the overwrite confirmation instead of a toast — it is a question, not a failure
- * — and every other refusal (or a missing admin right) rolls back to one.
+ * A 409 lands in the overwrite confirmation instead of the body — it is a question, not a failure
+ * — and every other refusal (or a missing admin right) stays in the dialog, under the file or the
+ * address it was about, until the next attempt.
*/
const failed = (e: unknown, request: ImportRequest) => {
- if (e instanceof ApiError && e.status === 409 && e.code === "theme_exists") {
+ const text = themeImportRefusal(e);
+ if (text === null) {
setPending(request);
} else {
setPending(null);
- toastError(themeImportErrorText(e));
+ setRefusal(text);
}
};
const upload = async (dataBase64: string, overwrite: boolean) => {
setBusy(true);
+ setRefusal(null);
try {
const res = await api.importThemeArchive({ dataBase64, ...(overwrite ? { overwrite } : {}) });
await imported(localizedText(locale, res.theme.name, res.theme.nameZh));
@@ -116,6 +128,7 @@ export function ThemeImportActions({
const download = async (target: string, overwrite: boolean) => {
setBusy(true);
+ setRefusal(null);
try {
const res = await api.importThemeFromUrl({
url: target,
@@ -176,7 +189,15 @@ export function ThemeImportActions({
{/* The entry sits beside "read again": the two are the same read and the same write, so they
belong to one row of actions on the folder. Bordered rather than a third line of small
text, because it is the only one of them that brings something in. */}
- <Button size="sm" variant="secondary" onClick={() => setOpen(true)}>
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ // A fresh opening asks nothing of the last one: no sentence from an earlier attempt.
+ setRefusal(null);
+ setOpen(true);
+ }}
+ >
{S.settings.themeImport}
</Button>
@@ -210,7 +231,11 @@ export function ThemeImportActions({
{ value: "download", label: S.settings.themeImportSourceUrl },
]}
value={source}
- onChange={setSource}
+ onChange={(next) => {
+ // The refusal was about the other source's request; this one has sent nothing yet.
+ setRefusal(null);
+ setSource(next);
+ }}
/>
{source === "upload" ? (
<>
@@ -252,6 +277,18 @@ export function ThemeImportActions({
/>
</>
)}
+ {/* The refusal sits under the source it was about, inside the dialog that asked: the
+ picked file or the address is still here, and the confirm button beside it is what
+ retries. A toast said the same thing over an open dialog and left with it. */}
+ {refusal !== null && (
+ <NoticeStrip
+ tone="danger"
+ role="alert"
+ className="rounded-md border px-2.5 py-2 text-xs"
+ >
+ <span data-slot="body">{S.common.refused(refusal)}</span>
+ </NoticeStrip>
+ )}
</div>
</Modal>
diff --git a/packages/web/src/features/settings/theme-import.ts b/packages/web/src/features/settings/theme-import.ts
index 84d2ed02..ef62fbc5 100644
--- a/packages/web/src/features/settings/theme-import.ts
+++ b/packages/web/src/features/settings/theme-import.ts
@@ -64,3 +64,18 @@ export function themeImportErrorText(err: unknown): string {
}
return apiErrorText(err);
}
+
+/**
+ * The same failure, told apart from the ONE answer that is a question rather than a refusal.
+ *
+ * A 409 `theme_exists` is the overwrite confirmation's cue: both flows answer it by asking, and its
+ * card resends the very request. Everything else is a refusal — the reason the surface that asked
+ * keeps on screen (the dialog's own body, the card under the button that offered it) instead of a
+ * notification that dismisses itself while the reader is still looking at what did not happen. So
+ * the rule "409 means ask, anything else means say why" lives here once rather than in each
+ * caller's catch, and `null` means "open the question" — never "nothing to say".
+ */
+export function themeImportRefusal(err: unknown): string | null {
+ if (err instanceof ApiError && err.status === 409 && err.code === "theme_exists") return null;
+ return themeImportErrorText(err);
+}
diff --git a/packages/web/src/features/settings/theme-registry-section.tsx b/packages/web/src/features/settings/theme-registry-section.tsx
index a6b9eb84..a75f97d0 100644
--- a/packages/web/src/features/settings/theme-registry-section.tsx
+++ b/packages/web/src/features/settings/theme-registry-section.tsx
@@ -22,16 +22,21 @@
* opens the overwrite confirmation, whose confirm resends with `overwrite: true`. The card carries
* "installed" from the server's answer (it compares the catalogue against the directory per
* request), so after an import the grid is re-read rather than guessed at.
+ *
+ * AN IMPORT THAT WAS REFUSED SAYS WHY ON ITS OWN CARD. The card is what the operator clicked, and
+ * the catalogue above it is where "that entry is gone" or "the file does not match the id it was
+ * listed under" has to be read; a toast said it over a grid the reader could not tell apart, and
+ * dismissed itself while the card that would retry sat there looking untouched.
*/
import { useCallback, useEffect, useState } from "react";
-import { Button, ConfirmModal, InfoPopover, toastError, toastSuccess } from "@adelie/ui";
+import { Button, ConfirmModal, InfoPopover, toastSuccess } from "@adelie/ui";
import type { ThemeRegistryResponse, ThemeRegistryTheme } from "@adelie/server/api";
import * as api from "../../api/endpoints";
-import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
+import { toneInk } from "../../lib/tone";
import { useLocale } from "../../state/locale";
import { localizedText } from "../chat/skill-use";
-import { themeImportErrorText } from "./theme-import";
+import { themeImportRefusal } from "./theme-import";
/** One mode's four colours, filled in where the catalogue left a name out. */
type ModeColours = Readonly<Record<string, string>>;
@@ -100,11 +105,14 @@ function RegistryCard({
entry,
locale,
busy,
+ refusal,
onInstall,
}: {
entry: ThemeRegistryTheme;
locale: "zh" | "en";
busy: boolean;
+ /** Why this card's import was refused, or null — another card's sentence never lands here. */
+ refusal: string | null;
onInstall: () => void;
}) {
const description =
@@ -143,6 +151,19 @@ function RegistryCard({
: S.settings.themeRegistryImport}
</Button>
</span>
+ {/* The sentence stays on the card whose button was refused, in the card's own width, with the
+ whole of it on hover: two cards can look alike, and the one that failed is the one whose
+ import has to be rethought (a stale entry, a mismatched file). */}
+ {refusal !== null && (
+ <p
+ role="alert"
+ data-tooltip={S.common.refused(refusal)}
+ data-tooltip-content="text"
+ className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}
+ >
+ {S.common.refused(refusal)}
+ </p>
+ )}
</div>
);
}
@@ -165,6 +186,8 @@ export function ThemeRegistrySection({
const [busyId, setBusyId] = useState<string | null>(null);
const [pending, setPending] = useState<Pending | null>(null);
const [failed, setFailed] = useState(false);
+ /** The card whose import was refused, and why — one at a time, like the import itself. */
+ const [refusal, setRefusal] = useState<{ id: string; text: string } | null>(null);
const load = useCallback(async () => {
setReading(true);
@@ -172,6 +195,8 @@ export function ThemeRegistrySection({
const res = await api.getThemeRegistry();
setCatalogue(res);
setFailed(false);
+ // The grid is re-read from the server, so a sentence about a card of the old one is stale.
+ setRefusal(null);
} catch {
// The request itself failed (not the registry): the shared sentence, and a row that can be
// asked again rather than a page that pretends there is no library.
@@ -187,6 +212,8 @@ export function ThemeRegistrySection({
const install = async (entry: ThemeRegistryTheme, overwrite: boolean) => {
setBusyId(entry.id);
+ // The sentence on the card belongs to the attempt before this one, whatever it says.
+ setRefusal(null);
try {
const res = await api.importThemeFromRegistry({
id: entry.id,
@@ -201,11 +228,12 @@ export function ThemeRegistrySection({
await onImported();
await load();
} catch (e) {
- if (e instanceof ApiError && e.status === 409 && e.code === "theme_exists") {
+ const text = themeImportRefusal(e);
+ if (text === null) {
setPending({ id: entry.id, name: localizedText(locale, entry.name, entry.nameZh) });
} else {
setPending(null);
- toastError(themeImportErrorText(e));
+ setRefusal({ id: entry.id, text });
}
} finally {
setBusyId(null);
@@ -258,6 +286,7 @@ export function ThemeRegistrySection({
entry={entry}
locale={locale}
busy={busyId === entry.id}
+ refusal={refusal?.id === entry.id ? refusal.text : null}
onInstall={() => void install(entry, entry.installed)}
/>
))}
diff --git a/packages/web/test/theme-import.test.ts b/packages/web/test/theme-import.test.ts
index c8bc7bb2..bd38f2c6 100644
--- a/packages/web/test/theme-import.test.ts
+++ b/packages/web/test/theme-import.test.ts
@@ -1,6 +1,7 @@
/**
- * The two pure parts of the theme import dialog (features/settings/theme-import.ts): what a failed
- * import says, and the check the browser makes before reading a picked file.
+ * The pure parts of the theme import (features/settings/theme-import.ts): what a failed import
+ * says, which of its answers are a refusal rather than a question, and the check the browser makes
+ * before reading a picked file.
*
* What is worth pinning here is that a refusal is never replaced by a sentence of the app's own
* when the server had something specific to say: `theme_invalid` carries the reader's collected
@@ -18,6 +19,7 @@ import {
THEME_FILE_LIMIT_KB,
themeFileTooLarge,
themeImportErrorText,
+ themeImportRefusal,
} from "../src/features/settings/theme-import";
describe("主题导入失败时说的话", () => {
@@ -77,6 +79,35 @@ describe("主题导入失败时说的话", () => {
});
});
+describe("拒绝与「问题」的分界", () => {
+ it("409 theme_exists 是问题,不是拒绝:调用方拿 null 去开覆盖确认", () => {
+ expect(themeImportRefusal(new ApiError(409, "theme_exists", "…"))).toBeNull();
+ });
+
+ it("其余一律是拒绝,且就是那句与失败同一个表里的话", () => {
+ // A code with its own copy: the localized sentence, so a reader who is on 中文 is not shown the
+ // server's English.
+ expect(themeImportRefusal(new ApiError(404, "registry_theme_not_found", "…"))).toBe(
+ S.settings.themeRegistryGone,
+ );
+ expect(themeImportRefusal(new ApiError(400, "download_failed", "…"))).toBe(
+ S.settings.themeImportDownloadFailed,
+ );
+ // A code nobody localized still says something: the shared mapping, never an empty line.
+ const odd = new ApiError(500, "something_new", "it broke");
+ expect(themeImportRefusal(odd)).toBe(apiErrorText(odd));
+ expect(themeImportRefusal(odd)).not.toBe("");
+ expect(themeImportRefusal(new Error("boom"))).toBe(S.common.unknownError);
+ });
+
+ it("409 别的码不是问题:它没有覆盖确认可开,仍按拒绝说", () => {
+ // `theme_exists` is the one 409 the flows ask about; a conflict from anywhere else has no card
+ // to open, so it must not vanish into a silent null.
+ const other = new ApiError(409, "conflict", "…");
+ expect(themeImportRefusal(other)).toBe(apiErrorText(other));
+ });
+});
+
describe("读取之前的那道上限", () => {
it("浏览器这边的上限就是 core 的格式上限", () => {
expect(THEME_FILE_LIMIT_KB * 1024).toBe(MAX_THEME_FILE_BYTES);