A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 插件导入被拒时,原因留在发号施令的那个对话框里,不再只活六秒
lmliheng630372c9a27e
diff --git a/changelog/unreleased/2026-11-05-plugin-import-refusal.md b/changelog/unreleased/2026-11-05-plugin-import-refusal.mdnew file mode 100644index 00000000..f38801c0--- /dev/null+++ b/changelog/unreleased/2026-11-05-plugin-import-refusal.md@@ -0,0 +1,57 @@+# A refused plugin import says why inside the dialog that asked, not in a six-second toast++- **Date:** 2026-11-05+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-05-plugin-import-refusal.zh.md)++The plugin library's two import dialogs (the header's "Upload plugin" and "Download from an+address or npm") each ask for a source plus an optional name. A refused import writes nothing:+the dialog stays open with the archive picked or the address typed exactly as it was, and the+confirm button is the retry. The reason arrived as one notification that dismissed itself after+six seconds — afterwards the dialog looked precisely as it had before the press, with the thing+that has to be fixed (the address, the file) sitting there and nothing said about it.++The reason now stays under the source field of the dialog that asked (`role="alert"`, danger+colour, two lines with the whole text on hover) until the source is edited, the next import is+started, the dialog is closed or the import lands — so it always describes the last attempt. Two+cases keep the homes they already had: a 409 `plugin_exists` is a question, and it is asked in the+overwrite confirmation (which names the plugin); and an answer that lands after Cancel was pressed+(both dialogs' Cancel stays live during a request) keeps the notification, because a sentence+drawn into a closed dialog is a sentence nobody reads.++Whose words: the plugin codes get their own copy, everything else follows `refusalText`, the rule+every refusal slot in the app uses (7.19) — a request the server answered is read through its+code's localized sentence, and a value this codebase raised itself is shown as it wrote it.++## Details++- `packages/web/src/features/plugins/plugin-import-refusal.ts` (new): `importFailure(error,+ fallbackName, dialogOpen)` — one of three outcomes (`ask` with the plugin name, `field` with the+ sentence, `toast` with the sentence when no dialog is left to keep it in), so the branch the+ dialogs used to spell inline is one testable decision.+- `packages/web/src/features/plugins/plugin-import-dialog.tsx`: a `refusal` state keyed by the+ dialog that asked, the ref mirrors of both open flags (the answer decides where it goes, not+ the press), `ImportRefusalLine` — the shared line — under the file picker in the upload dialog+ and under the URL field in the download dialog, cleared by every edit, every new attempt,+ closing either dialog and a landed import.++## Tests++- `packages/web/test/plugin-import-refusal.test.ts` (new, 7): the 409 reads the plugin name out of+ the server's message and falls back to the caller's name; a refusal keeps the dialog's slot+ while it is open; the plugin codes use their own copy rather than the server's English; an+ unmapped code falls back to the shared table; a closed dialog gets the notification instead; an+ error this codebase raised keeps its own message; the interface language is respected.+- `packages/web/e2e/plugin-import-refusal.spec.mjs` (new, real server + real browser, 2): a+ refused download draws the sentence under the address, the notification region never carries+ it, the dialog the address and the button all survive; still there after 7 seconds; editing the+ address clears it; the retry closes the dialog and reports the import. The second test cancels+ during the request and finds the sentence in the notification instead.++## Compatibility++No interface change, no new dependency, no Project configuration change. The routes, the payloads+and the 409 confirmation are untouched.diff --git a/changelog/unreleased/2026-11-05-plugin-import-refusal.zh.md b/changelog/unreleased/2026-11-05-plugin-import-refusal.zh.mdnew file mode 100644index 00000000..7173e561--- /dev/null+++ b/changelog/unreleased/2026-11-05-plugin-import-refusal.zh.md@@ -0,0 +1,44 @@+# 插件导入被拒时,原因留在发问的那个对话框里,不再只活六秒++- **日期:** 2026-11-05+- **类型:** fix+- **范围:** `web`+- **破坏性:** 否++[English](2026-11-05-plugin-import-refusal.md)++插件库标题行里的两个导入对话框(「上传插件」与「远程下载」)都要一个来源,外加一个可选的插件名。+导入被拒时什么都没写:对话框留在原地,选好的压缩包或填好的地址一个字没变,而那颗确认按钮就是+重试。可理由只落进一条六秒后自己消失的通知 —— 六秒之后对话框与按下之前一模一样,而真正要改的东西+(地址、文件)就在眼前,却没有一句话说它。++那句话现在留在发问的那个对话框的来源字段下面(`role="alert"`、危险色、限两行、整句挂悬停),直到+来源被改动、下一笔导入开始、对话框关闭或导入成功 —— 所以它说的总是最近一次尝试。两种情况保留原来的+位置:409 `plugin_exists` 是一句提问,仍然在覆盖确认里问(那里会点出插件名);而按下「取消」之后才+回来的答复(两个对话框的取消在请求进行中都可用)仍然走通知 —— 画进已关闭对话框的句子没人看得到。++用谁的措辞:插件自己的错误码用自己的文案,其余按 `refusalText` —— 全应用拒绝位都走这条规则(7.19)。+服务端答过的请求念它错误码对应的本地化句子,本仓库自己抛出的值按它写好的原话显示。++## 明细++- `packages/web/src/features/plugins/plugin-import-refusal.ts`(新):`importFailure(error,+ fallbackName, dialogOpen)` —— 三种去向之一(`ask` 带插件名、`field` 带句子、对话框已不在时+ `toast` 带句子),把原先写在两个对话框里的分支收成一个可测的判定。+- `packages/web/src/features/plugins/plugin-import-dialog.tsx`:新增按「发问的对话框」区分的+ `refusal` 状态;两个打开标记的 ref 影子(答复回来时才决定去哪,而不是按下那一刻);+ `ImportRefusalLine`(与全应用同形的那一行)在上传对话框里画在文件选择行下面、在下载对话框里画在+ 地址字段下面;每次编辑、每次新尝试、关闭任一对话框与导入成功都会清掉它。++## 测试++- `packages/web/test/plugin-import-refusal.test.ts`(新,7 条):409 从服务端原话里读出插件名,读不出+ 就用调用方给的名字;对话框还开着时拒绝留在对话框里;插件错误码用自己的文案而不是服务端英文;未映射+ 的错误码退回共享码表;对话框已关时改走通知;本仓库自己抛的错误保留原话;界面语言跟着切换。+- `packages/web/e2e/plugin-import-refusal.spec.mjs`(新,真服务端 + 真浏览器,2 条):被拒的下载把句子+ 画在地址下面、通知区里没有它、对话框/地址/按钮都还在;**7 秒后**仍在;改动地址它就消失;重试后对话框+ 关闭并报出导入成功。第二条规定请求进行中按取消,句子出现在通知里。++## 兼容性++不碰接口、不引入新依赖、不改 Project 配置。路由、请求体与覆盖确认都没动。diff --git a/packages/web/e2e/plugin-import-refusal.spec.mjs b/packages/web/e2e/plugin-import-refusal.spec.mjsnew file mode 100644index 00000000..707fd2af--- /dev/null+++ b/packages/web/e2e/plugin-import-refusal.spec.mjs@@ -0,0 +1,134 @@+/**+ * Regression: a plugin import the server refuses keeps its reason inside the dialog that asked,+ * under the source field it names — instead of leaving only a toast behind.+ *+ * `features/plugins/plugin-import-dialog.tsx` refused nothing on screen and closed nothing: the+ * dialog stayed open with the URL typed and the confirm button in place, and the reason fell+ * into a notification that dismissed itself after six seconds. Afterwards the dialog looked+ * exactly as it had before the press — same address, same button — with no word about why+ * nothing was imported, while the address is precisely the thing that has to be fixed.+ *+ * Both halves of the failure rule are measured here, because they are two different places:+ * an answer that arrives while the dialog is still open stays under the URL field, and one that+ * arrives after Cancel was pressed (Cancel stays live during a request) keeps the notification+ * it always had — a sentence drawn into a closed dialog is a sentence nobody reads.+ *+ * The import write is stubbed: the real route would fetch the address over the network, and what+ * this test measures is where the refusal is drawn, not what the registry answers. The library+ * read is the page's own real one.+ */+import { test, expect } from "@playwright/test";+import { ADMIN_ID, ADMIN_PASSWORD, login } from "./auth.mjs";++/** The route's own refusal code for a failed fetch, so the sentence on screen is its localized copy. */+const REFUSAL = { code: "download_failed", message: "the archive host answered 502" };+/** S.plugins.importErrors.download_failed, the copy that code stands for in a zh-CN interface. */+const SENTENCE = "下载失败,请确认该地址可以访问。";+const URL_TEXT = "https://example.com/probe-plugin.zip";++/** The dialog's own openers and fields, by their visible labels. */+const openButton = (page) => page.getByRole("button", { name: "远程下载", exact: true });+const urlField = (dialog) => dialog.getByRole("textbox", { name: "插件地址或 npm 包名" });+const importButton = (dialog) => dialog.getByRole("button", { name: "下载并导入", exact: true });++/**+ * Take over the import write. `state.refuse` is what the retry flips; `state.delay` holds the+ * answer back far enough for a test to close the dialog before it lands.+ */+async function stubImportWrite(page, state) {+ await page.route("**/api/plugins/download", async (route) => {+ if (route.request().method() !== "POST") return route.fallback();+ state.posts.push(route.request().postDataJSON());+ if (state.delay > 0) await new Promise((resolve) => setTimeout(resolve, state.delay));+ if (state.refuse) {+ return route.fulfill({+ status: 502,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ }+ return route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ plugin: {+ source: "user",+ name: "probe-plugin",+ version: "2026.11.5.1",+ skills: [],+ hooks: [],+ },+ path: "/tmp/probe-plugin",+ }),+ });+ });+}++/** The plugins page with the download dialog open on one typed address. */+async function openDownloadDialog(page) {+ await page.goto("/plugins");+ await openButton(page).click();+ const dialog = page.getByRole("dialog");+ await expect(dialog).toBeVisible();+ await urlField(dialog).fill(URL_TEXT);+ return dialog;+}++test("a refused import keeps its reason under the address, and is not a toast", async ({+ page,+}) => {+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);+ const state = { refuse: true, delay: 0, posts: [] };+ await stubImportWrite(page, state);++ const dialog = await openDownloadDialog(page);+ await importButton(dialog).click();++ // The reason is under the URL field, in the dialog that asked — the notification region+ // (which may still hold the page's own notices) never carries it.+ const line = dialog.getByRole("alert");+ await expect(line).toHaveText(SENTENCE);+ await expect(page.getByRole("region", { name: "通知" })).not.toContainText(SENTENCE);+ expect(state.posts).toEqual([{ url: URL_TEXT }]);++ // Nothing was imported and nothing was lost: the dialog, the address and the button that+ // retries it are all still there.+ await expect(dialog).toBeVisible();+ await expect(urlField(dialog)).toHaveValue(URL_TEXT);+ await expect(importButton(dialog)).toBeEnabled();++ // Still there after the toast would have gone.+ await page.waitForTimeout(7000);+ await expect(dialog.getByRole("alert")).toHaveText(SENTENCE);++ // Editing the address answers a new question: the line goes with the address it described.+ await urlField(dialog).fill(`${URL_TEXT}?v=2`);+ await expect(dialog.getByRole("alert")).toHaveCount(0);++ // The retry lands: the dialog closes and the import is reported.+ state.refuse = false;+ await importButton(dialog).click();+ await expect(dialog).toHaveCount(0);+ await expect(page.getByRole("region", { name: "通知" })).toContainText("已导入插件 probe-plugin");+ expect(state.posts).toHaveLength(2);++ // Closing and reopening does not carry the old reason over.+ const reopened = await openDownloadDialog(page);+ await expect(reopened.getByRole("alert")).toHaveCount(0);+});++test("an import refused after the dialog was closed still reports itself", async ({ page }) => {+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);+ const state = { refuse: true, delay: 1500, posts: [] };+ await stubImportWrite(page, state);++ const dialog = await openDownloadDialog(page);+ await importButton(dialog).click();+ // Cancel stays live during a request, so the dialog can be gone before the answer: there is+ // no surface left to keep the sentence in, and the notification is what the reader gets.+ await dialog.getByRole("button", { name: "取消", exact: true }).click();+ await expect(dialog).toHaveCount(0);++ await expect(page.getByRole("region", { name: "通知" })).toContainText(SENTENCE);+ expect(state.posts).toHaveLength(1);+});diff --git a/packages/web/src/features/plugins/plugin-import-dialog.tsx b/packages/web/src/features/plugins/plugin-import-dialog.tsxindex 151e8bba..b578a858 100644--- a/packages/web/src/features/plugins/plugin-import-dialog.tsx+++ b/packages/web/src/features/plugins/plugin-import-dialog.tsx@@ -6,9 +6,10 @@* Both are the same import twice: one carries the archive in the request, the other a URL the* server fetches, and everything after the POST is shared — a 409 `plugin_exists` opens the* overwrite confirmation, whose confirm resends THAT request with `overwrite: true` (so the- * user never picks the file twice, nor retypes the name), and any other failure rolls back to a- * toast. The library list and the directory line are re-read on success, which is how the new- * card appears.+ * user never picks the file twice, nor retypes the name), and any other failure keeps its+ * sentence inside the dialog that asked, under the source field it names (see+ * ImportRefusalLine and plugin-import-refusal.ts). The library list and the directory line are+ * re-read on success, which is how the new card appears.** Each dialog carries the same optional name field, for the one case the archive cannot answer* itself: plugin.json at the very root of the zip has no directory to take a name from. Left@@ -27,7 +28,7 @@* by every Project, so a member cannot write into it — the caller (plugins-page) renders this* component only for an admin, and the routes answer 403 `admin_required` regardless.*/-import { useState } from "react";+import { useRef, useState } from "react";import type { ChangeEvent } from "react";import {Button,@@ -42,18 +43,17 @@ import {toastSuccess,} from "@adelie/ui";import * as api from "../../api/endpoints";-import { ApiError } from "../../api/client";import { S } from "../../lib/strings";+import { toneInk } from "../../lib/tone";import { UPLOAD_LABEL_CLASS } from "../agents/skills-tab";import {PLUGIN_ZIP_LIMIT_MB,- pluginImportErrorText,pluginNameBody,- pluginNameFromError,pluginNameFromUrl,pluginNameInvalid,pluginZipTooLarge,} from "./plugin-import";+import { importFailure } from "./plugin-import-refusal";/*** One import request, in the shape the retry needs: repeatable exactly as it was sent, `name`@@ -146,6 +146,27 @@ function PluginRulesDialog({ open, onClose }: { open: boolean; onClose: () => vo);}+/**+ * One refused import's sentence, drawn under the source field of the dialog that asked.+ *+ * The same line every refusal slot in the app draws (7.19's family): an alert to a screen+ * reader, the danger tone, two lines with the whole text on hover — a long upstream sentence+ * (a registry error, a 403 from the hosting site) must not be able to heighten the dialog past+ * the fields and buttons, and it is still all there for whoever needs it.+ */+function ImportRefusalLine({ text }: { text: string }) {+ return (+ <p+ role="alert"+ data-tooltip={text}+ data-tooltip-content="text"+ className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {text}+ </p>+ );+}+/** The opener: a text button where the panel used to sit, so the rules stay at the same foot. */function RulesLink({ onClick }: { onClick: () => void }) {return (@@ -177,16 +198,31 @@ export function PluginImportActions({const [downloadName, setDownloadName] = useState("");// The 409 confirmation, and the only state both flows share.const [pending, setPending] = useState<PendingOverwrite | null>(null);+ /**+ * The words of a refused import, under the source field of the dialog that asked — keyed by+ * that dialog, so a sentence can never surface under the wrong one.+ */+ const [refusal, setRefusal] = useState<{ source: "upload" | "download"; text: string } | null>(+ null,+ );// The rules dialog is shared by both import dialogs: they describe one plugin shape, so a// single open flag keeps the two from stacking two copies of the same prose.const [rulesOpen, setRulesOpen] = useState(false);+ // Where a refusal goes is decided when the answer comes back, not when the request left:+ // Cancel stays live during an import, so the dialog may be gone by then (importFailure).+ const uploadOpenRef = useRef(uploadOpen);+ uploadOpenRef.current = uploadOpen;+ const downloadOpenRef = useRef(downloadOpen);+ downloadOpenRef.current = downloadOpen;+const uploadNameInvalid = pluginNameInvalid(uploadName);const downloadNameInvalid = pluginNameInvalid(downloadName);/** Success path, shared by both flows: close what was open, toast, re-read the library. */const imported = async (name: string) => {setPending(null);+ setRefusal(null);setUploadOpen(false);setPicked(null);setUploadName("");@@ -201,24 +237,46 @@ export function PluginImportActions({* Closing the upload dialog drops what was picked with it — unlike the download dialog's URL,* which survives a cancel (it is one pasted string the user would have to find again), the* archive is a base64 body held in memory, and a dialog opened to start over has no use for it.+ * A refusal goes with it for the same reason: it described that archive.*/const closeUpload = () => {setUploadOpen(false);setPicked(null);setUploadName("");+ setRefusal(null);+ };++ /** Opens the download dialog without the previous attempt's reason: that one is answered. */+ const openDownload = () => {+ setRefusal(null);+ setDownloadOpen(true);+ };++ const closeDownload = () => {+ setDownloadOpen(false);+ setRefusal(null);};/**- * 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 — it is a question, not a failure — and every+ * other refusal keeps its sentence in the dialog that asked, where the source field it names+ * and the button that retries it both still are (importFailure decides which of the three).*/const failed = (e: unknown, request: ImportRequest, fallbackName: string) => {- if (e instanceof ApiError && e.status === 409 && e.code === "plugin_exists") {- setPending({ ...request, pluginName: pluginNameFromError(e, fallbackName) });- } else {- setPending(null);- toastError(pluginImportErrorText(e));+ const opened = request.source === "upload" ? uploadOpenRef : downloadOpenRef;+ const outcome = importFailure(e, fallbackName, opened.current);+ if (outcome.kind === "ask") {+ setRefusal(null);+ setPending({ ...request, pluginName: outcome.pluginName });+ return;}+ setPending(null);+ if (outcome.kind === "field") {+ setRefusal({ source: request.source, text: outcome.text });+ return;+ }+ setRefusal(null);+ toastError(outcome.text);};/** POST the archive body; `overwrite` only ever set by the confirmation's retry. */@@ -228,6 +286,8 @@ export function PluginImportActions({fallbackName: string,overwrite: boolean,) => {+ // The sentence the last attempt left described the last attempt: this one replaces it.+ setRefusal(null);setBusy("upload");try {const res = await api.importPluginArchive({@@ -246,6 +306,8 @@ export function PluginImportActions({/** POST the URL; the server derives the name from it (and `subdir` from a tree URL). */const download = async (target: string, name: string, overwrite: boolean) => {+ // Same as the upload above: this attempt is what the dialog will be asked about.+ setRefusal(null);setBusy("download");try {const res = await api.importPluginFromUrl({@@ -280,6 +342,8 @@ export function PluginImportActions({const reader = new FileReader();reader.onload = () => {const dataUrl = reader.result as string;+ // A newly picked archive starts without the previous one's reason.+ setRefusal(null);// Strip the `data:…;base64,` prefix the FileReader adds.setPicked({dataBase64: dataUrl.slice(dataUrl.indexOf(",") + 1),@@ -312,15 +376,17 @@ export function PluginImportActions({import runs, since one import at a time is what the confirmation's single pending slotcan carry. */}<div className="ml-auto flex shrink-0 items-center gap-2">- <Button size="sm" disabled={busy !== null} onClick={() => setUploadOpen(true)}>- {busy === "upload" ? S.plugins.importUploading : S.plugins.importUpload}- </Button><Buttonsize="sm"- variant="primary"disabled={busy !== null}- onClick={() => setDownloadOpen(true)}+ onClick={() => {+ setRefusal(null);+ setUploadOpen(true);+ }}>+ {busy === "upload" ? S.plugins.importUploading : S.plugins.importUpload}+ </Button>+ <Button size="sm" variant="primary" disabled={busy !== null} onClick={openDownload}>{busy === "download" ? S.plugins.importDownloading : S.plugins.importDownload}</Button></div>@@ -366,13 +432,19 @@ export function PluginImportActions({</span>)}</div>+ {/* Under the archive it was about: a refused upload wrote nothing, so the file and the+ name above are still exactly what the next press will send. */}+ {refusal?.source === "upload" && <ImportRefusalLine text={refusal.text} />}<Inputsize="sm"label={S.plugins.pluginNameLabel}hint={S.plugins.pluginNameHint}placeholder={S.plugins.pluginNamePlaceholder}value={uploadName}- onChange={(e) => setUploadName(e.target.value)}+ onChange={(e) => {+ setUploadName(e.target.value);+ setRefusal(null);+ }}error={uploadNameInvalid ? S.plugins.pluginNameInvalid : undefined}autoComplete="off"/>@@ -383,7 +455,7 @@ export function PluginImportActions({<Modalopen={downloadOpen}title={S.plugins.downloadTitle}- onClose={() => setDownloadOpen(false)}+ onClose={closeDownload}widthClass="sm:max-w-lg"footer={<>@@ -391,7 +463,7 @@ export function PluginImportActions({modal): the request is already on its way, and it still reports itself — asuccess through the toast and the refreshed list, a 409 through the overwriteconfirmation, which is a dialog of its own. */}- <Button size="sm" onClick={() => setDownloadOpen(false)}>+ <Button size="sm" onClick={closeDownload}>{S.common.cancel}</Button><Button@@ -412,18 +484,27 @@ export function PluginImportActions({label={S.plugins.downloadUrlLabel}hint={S.plugins.downloadUrlHint}value={url}- onChange={(e) => setUrl(e.target.value)}+ onChange={(e) => {+ setUrl(e.target.value);+ setRefusal(null);+ }}placeholder={S.plugins.downloadUrlPlaceholder}autoComplete="off"autoFocus/>+ {/* Under the address it names: a refused download wrote nothing, so the URL and the+ name above are still exactly what the next press will send. */}+ {refusal?.source === "download" && <ImportRefusalLine text={refusal.text} />}<Inputsize="sm"label={S.plugins.pluginNameLabel}hint={S.plugins.pluginNameHint}placeholder={S.plugins.pluginNamePlaceholder}value={downloadName}- onChange={(e) => setDownloadName(e.target.value)}+ onChange={(e) => {+ setDownloadName(e.target.value);+ setRefusal(null);+ }}error={downloadNameInvalid ? S.plugins.pluginNameInvalid : undefined}autoComplete="off"/>diff --git a/packages/web/src/features/plugins/plugin-import-refusal.ts b/packages/web/src/features/plugins/plugin-import-refusal.tsnew file mode 100644index 00000000..4723054f--- /dev/null+++ b/packages/web/src/features/plugins/plugin-import-refusal.ts@@ -0,0 +1,55 @@+/**+ * The plugin library's import dialogs: what one failed import leaves behind, and where.+ *+ * Both dialogs are a source plus an optional name, and a refused import writes nothing: the+ * dialog stays open with the archive picked or the URL typed exactly as it was, and the confirm+ * button is the retry. The reason used to arrive as a notification that dismissed itself after+ * six seconds, over the dialog — afterwards the surface looked precisely as it had before the+ * press, and the thing the reader has to fix (the address, the picked file, the name) sat there+ * with nothing said about it.+ *+ * So a refusal now stays under the source field of the dialog that asked. The one case that is+ * not a refusal keeps its own place: a 409 `plugin_exists` is a question, and the overwrite+ * confirmation is where it is asked (it carries the plugin name, which is what makes the+ * question answerable).+ *+ * Whose words: the plugin codes get their own copy (`pluginImportErrorText`, which falls back to+ * the shared code table), and a value this codebase raised itself — nothing the server answered —+ * is read through `refusalText`, the rule every refusal slot in the app follows (7.19).+ */+import { ApiError } from "../../api/client";+import { refusalText } from "../../lib/api-error";+import { pluginImportErrorText, pluginNameFromError } from "./plugin-import";++/** What one failed import should do next. */+export type ImportFailure =+ /** The name is taken: ask before overwriting, naming the plugin. */+ | { readonly kind: "ask"; readonly pluginName: string }+ /** Keep the sentence under the source field of the dialog that asked. */+ | { readonly kind: "field"; readonly text: string }+ /** Put it in a notification — there is no dialog on screen to keep it in. */+ | { readonly kind: "toast"; readonly text: string };++/**+ * The reason one refused import leaves, and where.+ *+ * `dialogOpen` is the state of the dialog that sent the request AT THE MOMENT THE ANSWER CAME+ * BACK, not when it was pressed: both dialog's Cancel stays live during a request (the request is+ * already on its way and still reports itself), so a failure can land after the dialog it belongs+ * to was closed — and a sentence drawn into a closed dialog is a sentence nobody reads. Those keep+ * the notification they always had.+ *+ * `fallbackName` is only read by the 409 branch, which needs a plugin name for its copy even when+ * the server's message does not carry one (see pluginNameFromError).+ */+export function importFailure(+ error: unknown,+ fallbackName: string,+ dialogOpen: boolean,+): ImportFailure {+ if (error instanceof ApiError && error.status === 409 && error.code === "plugin_exists") {+ return { kind: "ask", pluginName: pluginNameFromError(error, fallbackName) };+ }+ const text = error instanceof ApiError ? pluginImportErrorText(error) : refusalText(error);+ return { kind: dialogOpen ? "field" : "toast", text };+}diff --git a/packages/web/test/plugin-import-refusal.test.ts b/packages/web/test/plugin-import-refusal.test.tsnew file mode 100644index 00000000..e6a5edaf--- /dev/null+++ b/packages/web/test/plugin-import-refusal.test.ts@@ -0,0 +1,90 @@+/**+ * The plugin import dialogs' failure branch (src/features/plugins/plugin-import-refusal.ts):+ * which of the three things one failed import does, and whose words it uses.+ *+ * A refused import writes nothing, so the dialog that asked is still open with the address or+ * the picked archive in it — that surface is where the sentence belongs, and it is the whole+ * reason this test exists: a toast would be gone after six seconds while the thing to fix sits+ * on screen. The two exceptions have to keep their old homes: a 409 is a question (the overwrite+ * confirmation), and a failure that lands after the dialog was closed has no surface to go to.+ */+import { afterEach, describe, expect, it } from "vitest";+import { ApiError } from "../src/api/client";+import { en as EN } from "../src/lib/strings-en";+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";+import { importFailure } from "../src/features/plugins/plugin-import-refusal";++afterEach(() => {+ setActiveStrings(ZH);+});++describe("importFailure", () => {+ it("asks about overwriting when the name is taken, naming the plugin", () => {+ // The route's own wording (see http/routes/plugins.ts): the name is in the message.+ const refused = new ApiError(+ 409,+ "plugin_exists",+ "A user plugin named use-firecrawl is already installed.",+ );+ expect(importFailure(refused, "fallback-name", true)).toEqual({+ kind: "ask",+ pluginName: "use-firecrawl",+ });+ // Even with the dialog closed: a question is asked wherever the reader is, and the+ // confirmation carries its own Cancel (nothing is written without an answer).+ expect(importFailure(refused, "fallback-name", false).kind).toBe("ask");+ });++ it("gives the question a name the server did not, when the message carries none", () => {+ const refused = new ApiError(409, "plugin_exists", "that plugin is already installed");+ expect(importFailure(refused, "from-the-url", true)).toEqual({+ kind: "ask",+ pluginName: "from-the-url",+ });+ });++ it("keeps a refused import in the dialog that asked, while it is still open", () => {+ // `download_failed` has its own copy in S.plugins.importErrors — the reason the plugin+ // codes do not go through the generic table.+ const answer = importFailure(+ new ApiError(502, "download_failed", "RAW ENGLISH SERVER MESSAGE"),+ "x",+ true,+ );+ expect(answer).toEqual({ kind: "field", text: S.plugins.importErrors.download_failed });+ expect(S.plugins.importErrors.download_failed).not.toContain("RAW ENGLISH");+ });++ it("falls back to the shared code table for a code the plugin routes do not own", () => {+ const answer = importFailure(new ApiError(500, "internal", "RAW ENGLISH"), "x", true);+ expect(answer).toEqual({ kind: "field", text: S.errors.byCode["internal"] as string });+ });++ it("toasts instead when the dialog was closed before the answer came back", () => {+ // Both dialogs' Cancel stays live during an import, so the answer can land on a closed+ // dialog — a sentence drawn there would be a sentence nobody reads.+ expect(importFailure(new ApiError(500, "internal", "x"), "x", false)).toEqual({+ kind: "toast",+ text: S.errors.byCode["internal"] as string,+ });+ });++ it("shows an error the client raised itself as it wrote it", () => {+ // `refusalText`'s rule: only an ApiError is read through a code table.+ expect(importFailure(new TypeError("Failed to fetch"), "x", true)).toEqual({+ kind: "field",+ text: "Failed to fetch",+ });+ expect(importFailure(undefined, "x", true)).toEqual({+ kind: "field",+ text: S.common.unknownError,+ });+ });++ it("speaks the interface language", () => {+ setActiveStrings(EN);+ const answer = importFailure(new ApiError(502, "download_failed", "raw"), "x", true);+ expect(answer).toEqual({ kind: "field", text: S.plugins.importErrors.download_failed });+ expect(S.plugins.importErrors.download_failed).toContain("download failed");+ });+});