A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 记忆页签的删除与导入被拒时,框留着,原因也留在框里(7.32)
lmlihengdbd2d583bc1c
diff --git a/changelog/unreleased/2026-10-23-memory-write-refusal.md b/changelog/unreleased/2026-10-23-memory-write-refusal.mdnew file mode 100644index 00000000..62d84bf9--- /dev/null+++ b/changelog/unreleased/2026-10-23-memory-write-refusal.md@@ -0,0 +1,50 @@+# Memory tab: a refused delete or import keeps its question — and the reason — instead of closing++- **Date:** 2026-10-23+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-10-23-memory-write-refusal.zh.md)++Agent settings › Memory has two writes that ask first: deleting one memory, and importing a memory+export document back into a group. Both questions used to close themselves once the request came+back: when the server refused, the memory (and the files the import would have overwritten) were+still on the page and on disk, while the reason arrived as a toast that dismissed itself after six+seconds and sat above the modal — and the delete confirmation closed itself before the request even+left.++Both writes now close only once they landed. A refused delete keeps its confirmation open with the+server's words drawn under its sentence; an import reports in whichever layer asked — the plan+confirmation when one was shown, the "import memory" modal underneath it when nothing would have+been lost. The retry is the same button in every case.++## Details++- The rule is the one the model library, the plugin cards, the Skills / Hooks / MCP / Vault /+ schedules pages and the two bulk-update confirmations already follow (`ConfirmModal`'s `refusal`+ slot, 7.19 — 7.31): the reason is drawn in the card that asked for the write.+- `features/agents/memory-tab.tsx`: `confirmRemove` no longer calls `setRemoving(null)` first; a+ refusal hands the message to `deleteRefusal` and returns early, and the card closes, the list+ reloads and the agent card's count refreshes only on a written delete. The row's trash button, the+ drawer's and the phone sheet's all go through one `askRemove`, which opens the card and then drops+ the previous reason — that sentence belonged to the memory the last attempt named.+- `runImport` no longer raises its failure as a toast but hands it to `importRefusal`; the success+ path is unchanged. Where it is drawn depends on which layer asked: the plan confirmation+ (`ConfirmModal`) draws it in its own `refusal` slot, a direct import that needed no confirmation+ draws it in the import modal (same `S.common.refused` lead-in on both sides). Cancelling the plan+ comes back to the import modal with that sentence still on screen; picking a file again or+ switching modes clears it.+- New browser test `e2e/memory-write-refusal.spec.mjs` (three): a refused delete keeps the card, its+ sentence and the memory (no toast in the notification region; the card's text is unchanged apart+ from that one line), and cancelling changes nothing; the retry that lands closes the card and+ sends exactly that DELETE; a refused import keeps the plan confirmation with the reason inside,+ the group still holds what it held on disk and on the page, and only the permitted retry writes+ it. The seeded memory comes from the import route itself (the tab has no "new file" form by+ design), and both refusals come from `page.route`, so the page's contract with the server is what+ is checked.++## Compatibility++- No interface, wire-format, stored-data or dependency change: only *when* the surface closes and+ *where* the reason is drawn. No new copy beyond the existing `S.common.refused` prefix.diff --git a/changelog/unreleased/2026-10-23-memory-write-refusal.zh.md b/changelog/unreleased/2026-10-23-memory-write-refusal.zh.mdnew file mode 100644index 00000000..0113b3b3--- /dev/null+++ b/changelog/unreleased/2026-10-23-memory-write-refusal.zh.md@@ -0,0 +1,36 @@+# 记忆页签:删除与导入被拒时,框留着、原因也留在框里++- **Date:** 2026-10-23+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[English](2026-10-23-memory-write-refusal.md)++智能体设置 › 记忆里的两条写入都会先问一句:删掉一条记忆,或者把一份记忆导出文档导回某一组。过去两句问法都+在请求返回后自己关掉:被拒的时候,那条记忆(以及导入要覆盖的文件)还在页面上、也还在磁盘上,原因却只落在一条+六秒后自己消失、还浮在弹框上方的 toast 里 —— 删除框甚至在发请求之前就先关掉了。++现在两条写入都只在**真的落地之后**才收框:被拒时删除确认框留着,服务端的原话画在它那句话下面;导入则把原话画在+发起它的那一层 —— 走过计划确认的落在计划确认里,不需要确认的那条落在下面那层「导入记忆」里。重试都是同一个按钮。++## 细节++- 规则沿用模型库、插件卡、技能 / 钩子 / MCP / 密钥保险柜 / 定时任务页与两张批量更新确认框那几轮(`ConfirmModal`+ 的 `refusal` 槽,7.19—7.31):原因画在发起它的那张卡片里。+- `features/agents/memory-tab.tsx`:`confirmRemove` 不再先 `setRemoving(null)`,被拒时把消息交给+ `deleteRefusal` 并提前返回;只有删除真的写下才关框、刷新列表并重载智能体卡片上的条数。行的垃圾桶、抽屉与+ 手机面板底部的删除都走同一个 `askRemove`,它先开框再清上一次的原因 —— 那句话属于上次点名的记忆。+- `runImport` 失败时不再弹 toast,而是把消息交给 `importRefusal`;成功路径不变。原因的画法按「哪一层在问」分:+ 计划确认(`ConfirmModal`)画在它自己的 `refusal` 槽,没走确认的直接导入画在导入弹框里(`S.common.refused`+ 前缀两边一致)。取消计划确认回到导入弹框时,那句话仍然看得见;重新挑文件或换一种模式即清掉。+- 新增浏览器用例 `e2e/memory-write-refusal.spec.mjs`(三条):删除被拒时框、句子与记忆都在(通知区没有 toast,+ 框里的文字除那一行外逐字不变),取消不改变任何东西;放行重试才关框,且它发出的正是那条 DELETE;导入被拒时+ 计划确认留着、原话在里面,那一组在磁盘上与页面上都还是导入前的样子,只有放行重试才写下去。初始的记忆文件由+ 导入接口自己种下(这个页签按设计没有「新建文件」表单),两处拒绝都由 `page.route` 造,验的是页面与服务器之间+ 的契约。++## 兼容性++- 没有接口、传输格式、已存数据或依赖变化:只改了「框什么时候收」与「原因画在哪」。除既有的+ `S.common.refused` 前缀外没有新文案。diff --git a/packages/web/e2e/memory-write-refusal.spec.mjs b/packages/web/e2e/memory-write-refusal.spec.mjsnew file mode 100644index 00000000..58e4b957--- /dev/null+++ b/packages/web/e2e/memory-write-refusal.spec.mjs@@ -0,0 +1,238 @@+/**+ * Regression: deleting a memory and importing a memory document both ask first, and a refused+ * write keeps that question — with the server's words inside it — instead of closing on the way+ * out of the request.+ *+ * The delete confirmation used to close itself before the request even left, and the import ran+ * behind a toast: when the server refused, the memory (and the document's target files) were+ * still there, on the page and on disk, while the reason arrived as a toast that dismissed itself+ * after six seconds and sat above the modal. Both surfaces now close only once the write landed:+ * the delete confirmation keeps the server's words in `ConfirmModal`'s `refusal` slot, and an+ * import reports inside whichever surface asked — the plan confirmation when one was shown, the+ * import modal when nothing would have been lost — so the retry is the same button.+ *+ * The memory files are seeded through the export document the import route accepts, because the+ * tab has no "new file" form by design (a memory's text is the model's document; the tab bridges+ * to a chat). Only the owner may import, and provisioning makes this user the owner.+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;+const P = "password123";+const AGENT = "default_agent";+const FILE = "probe-memory.md";+const TITLE = "Probe memory";++/** The refused write: a 500 with its own words proves the reason came back into the surface. */+const REFUSAL = { code: "memory_store_closed", message: "memory store is closed" };++/** One memory document as the export route writes it (the import route's own shape). */+function documentFor(content) {+ return {+ format: "penguin-memory-scope",+ version: 1,+ scopeKey: "user",+ kind: "user",+ exportedAt: new Date().toISOString(),+ index: `- [${TITLE}](${FILE}) — seeded by the e2e run\n`,+ files: [+ {+ name: FILE,+ content: `---\nname: ${TITLE}\ndescription: A memory the refusal tests act on.\n---\n\n${content}\n`,+ },+ ],+ };+}++/**+ * Provision the user, give the Project a model (the onboarding overlay covers the page without+ * one), and seed one user-scope memory through the import route. Rerunning this file shares one+ * data root with earlier runs, so the seed overwrites what a previous run left.+ */+async function projectWithMemory(page, user, content) {+ await provisionAndLogin(page.request, user, P);+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]+ .projectId;+ const models = 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(models.ok(), "put models").toBeTruthy();++ const scopeBase = `${BASE}/api/projects/${projectId}/agents/${AGENT}/memory/scopes/user`;+ const seeded = await page.request.post(`${scopeBase}/import`, {+ data: { mode: "overwrite", confirm: true, payload: documentFor(content) },+ });+ expect(seeded.ok(), "seed the memory").toBeTruthy();++ /** The scope's topic files as the server holds them: what the page reads. */+ const files = async () => (await (await page.request.get(`${scopeBase}/files`)).json()).files;++ return { projectId, files };+}++/** The seeded memory's row, addressed by its title rather than by position. */+function rowOf(page) {+ return page+ .locator("li")+ .filter({ has: page.getByText(TITLE, { exact: true }) })+ .filter({ has: page.getByRole("button", { name: `删除 ${TITLE}` }) })+ .last();+}++/** The row's trash button → the shared confirmation. */+async function openDeleteDialog(page) {+ await rowOf(page)+ .getByRole("button", { name: `删除 ${TITLE}` })+ .click();+ const dialog = page.getByRole("dialog");+ await expect(dialog).toBeVisible();+ return dialog;+}++test("a refused delete keeps the confirmation, its sentence and the memory", async ({ page }) => {+ const { files } = await projectWithMemory(page, "r116mem1", "The first version of the probe.");+ const before = await files();++ await page.goto(`/agents/${AGENT}?tab=memory`);+ await expect(page.getByText(TITLE, { exact: true })).toBeVisible();+ const dialog = await openDeleteDialog(page);+ const sentence = await dialog.innerText();+ expect(sentence).toContain(TITLE);++ const deletes = [];+ await page.route("**/api/projects/*/agents/*/memory/scopes/*/files/*", async (route) => {+ if (route.request().method() !== "DELETE") return route.fallback();+ deletes.push(route.request().url());+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ });+ await dialog.getByRole("button", { name: "删除", exact: true }).click();++ // The reason is in the card that asked, and it is not a toast: the notification region holds+ // no dismissible button, and the card reads exactly as it did before the attempt plus the one+ // refusal line.+ await expect(dialog.getByText(REFUSAL.message)).toBeVisible();+ await expect(page.getByRole("region", { name: "通知" }).getByRole("button")).toHaveCount(0);+ expect(deletes).toHaveLength(1);+ await expect(dialog).toBeVisible();+ expect((await dialog.innerText()).replace(/\n操作被拒绝:[^\n]*/, "")).toBe(sentence);++ // Nothing was deleted anywhere: the row is still on the page and the server still holds it.+ await expect(rowOf(page)).toBeVisible();+ expect(await files()).toEqual(before);++ // Closing the card decides nothing.+ await dialog.getByRole("button", { name: "取消" }).click();+ await expect(dialog).toHaveCount(0);+ await expect(rowOf(page)).toBeVisible();+});++test("the retry after a refused delete removes it, and only a written one closes the card", async ({+ page,+}) => {+ const { files } = await projectWithMemory(page, "r116mem2", "A memory kept until it is removed.");++ const deletes = [];+ let refuse = true;+ await page.route("**/api/projects/*/agents/*/memory/scopes/*/files/*", async (route) => {+ if (route.request().method() !== "DELETE") return route.fallback();+ deletes.push(route.request().url());+ if (!refuse) return route.fallback();+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ });++ await page.goto(`/agents/${AGENT}?tab=memory`);+ await expect(page.getByText(TITLE, { exact: true })).toBeVisible();+ const dialog = await openDeleteDialog(page);+ await dialog.getByRole("button", { name: "删除", exact: true }).click();+ await expect(dialog.getByText(REFUSAL.message)).toBeVisible();+ await expect(dialog).toBeVisible();+ expect(deletes).toHaveLength(1);++ // The retry is the same card, and this time the write lands: card gone, memory gone.+ refuse = false;+ await dialog.getByRole("button", { name: "删除", exact: true }).click();+ await expect(dialog).toHaveCount(0);+ expect(deletes).toHaveLength(2);+ await expect(rowOf(page)).toHaveCount(0);+ expect((await files()).some((f) => f.name === FILE)).toBe(false);+});++test("a refused import keeps the plan confirmation and the memories it named", async ({ page }) => {+ const { files } = await projectWithMemory(page, "r116mem3", "What the scope held first.");++ const imports = [];+ await page.route("**/api/projects/*/agents/*/memory/scopes/*/import", async (route) => {+ if (route.request().method() !== "POST") return route.fallback();+ imports.push(route.request().url());+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ });++ await page.goto(`/agents/${AGENT}?tab=memory`);+ await expect(page.getByText(TITLE, { exact: true })).toBeVisible();+ // The user scope is the first group, so its header's file input is the first on the page.+ await page+ .locator('input[type="file"]')+ .first()+ .setInputFiles({+ name: "probe-scope.json",+ mimeType: "application/json",+ buffer: Buffer.from(JSON.stringify(documentFor("What the document brought."))),+ });++ const importModal = page.getByRole("dialog").filter({ hasText: "导入记忆" });+ await expect(importModal).toBeVisible();+ // A mode that would overwrite the same-named memory: the plan confirmation sits on top.+ await importModal.getByRole("radio", { name: "改用文件里的版本" }).click();+ await importModal.getByRole("button", { name: "导入", exact: true }).click();+ // ConfirmModal renders no title bar: its name lives on the dialog's accessible name only.+ const plan = page.getByRole("dialog", { name: "确认导入" });+ await expect(plan).toBeVisible();++ const sentence = await plan.innerText();+ await plan.getByRole("button", { name: "导入", exact: true }).click();+ await expect(plan.getByText(REFUSAL.message)).toBeVisible();+ await expect(plan).toBeVisible();+ expect(imports).toHaveLength(1);+ // The card's own sentence is untouched apart from the refusal line.+ expect((await plan.innerText()).replace(/\n操作被拒绝:[^\n]*/, "")).toBe(sentence);++ // The scope still holds what it held: nothing was written.+ const held = await files();+ expect(held).toHaveLength(1);+ expect(held[0].name).toBe(FILE);++ // Cancelling the plan comes back to the import modal — which now carries the same reason, so+ // the sentence is still on screen when the mode choice returns.+ await plan.getByRole("button", { name: "取消" }).click();+ await expect(plan).toHaveCount(0);+ await expect(importModal.getByText(REFUSAL.message)).toBeVisible();++ // Choosing another mode starts clean: that reason named the attempt before it.+ await importModal.getByRole("radio", { name: "保留现有的这条" }).click();+ await expect(importModal.getByText(REFUSAL.message)).toHaveCount(0);+});diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsxindex b377ee7f..b46619d2 100644--- a/packages/web/src/features/agents/memory-tab.tsx+++ b/packages/web/src/features/agents/memory-tab.tsx@@ -179,7 +179,13 @@ export function MemoryTab({const [importMode, setImportMode] = useState<MemoryImportMode>("skip");const [importPlan, setImportPlan] = useState<MemoryImportPlan | null>(null);const [importBusy, setImportBusy] = useState(false);+ // The server's words for a write it refused, drawn in the surface that asked for it: an+ // import refused from the plan confirmation appears in that card, one that needed no+ // confirmation (nothing would be lost) appears in the import modal still underneath it.+ const [importRefusal, setImportRefusal] = useState<string | null>(null);const [removing, setRemoving] = useState<Selected | null>(null);+ // Same for a refused delete, in the confirmation that named the memory (see confirmRemove).+ const [deleteRefusal, setDeleteRefusal] = useState<string | null>(null);// ≥1024px the view opens as a right Drawer, below as a bottom Sheet — same live-updating// breakpoint as the chat page's panels; the two are mounted mutually exclusively.const [isDesktop, setIsDesktop] = useState(() => window.matchMedia(DESKTOP_QUERY).matches);@@ -414,12 +420,20 @@ export function MemoryTab({try {const doc = parseMemoryScopeDocument(await file.text());setImportMode("skip");+ // A newly picked document starts without the previous attempt's reason.+ setImportRefusal(null);setImporting({ scope, fileName: file.name, doc });} catch (e) {toastError(e instanceof MemoryDocumentError ? e.message : S.memory.importInvalidFile);}};+ /**+ * Runs the import the person just asked for (with `confirm` once a plan was shown). Only a+ * written import closes the surfaces: a refused one leaves whichever surface asked — the plan+ * confirmation, or the import modal when nothing would have been lost — with the server's+ * words in it, so the retry is the same button rather than a fresh file pick.+ */const runImport = async (confirm: boolean) => {if (!projectId || !importing) return;setImportBusy(true);@@ -441,7 +455,7 @@ export function MemoryTab({// The agent card's memory count changed; refresh the list provider too.void reloadAgents();} catch (e) {- toastError(apiErrorText(e));+ setImportRefusal(apiErrorText(e));} finally {setImportBusy(false);}@@ -450,6 +464,8 @@ export function MemoryTab({/** Import's first click: straight through when nothing would be lost, otherwise into the confirmation. */const submitImport = () => {if (!importing) return;+ // A fresh decision starts without the previous attempt's reason.+ setImportRefusal(null);const group = groups?.find((g) => g.scope.scopeKey === importing.scope.scopeKey);const plan = planMemoryImport(importing.doc,@@ -460,20 +476,37 @@ export function MemoryTab({else void runImport(false);};+ /**+ * A memory's delete entry — the row's trash button, the drawer's, or the sheet's: opens the+ * confirmation without the previous attempt's reason, which belonged to the memory that+ * attempt named rather than to this one.+ */+ const askRemove = (target: Selected) => {+ setRemoving(target);+ setDeleteRefusal(null);+ };++ /**+ * Confirm modal's "Delete": only a written delete closes it. A refused one leaves the memory+ * on the page and on disk exactly as it was, so the card stays open with the server's words in+ * it and the same button retries — closing as the request left used to carry that reason into+ * a toast that dismisses itself after six seconds and sits above the card.+ */const confirmRemove = async () => {if (!projectId || !removing) return;const target = removing;- setRemoving(null);try {await api.deleteMemoryFile(projectId, agentId, target.scope.scopeKey, target.file.name);- toastSuccess(S.memory.deleteDone);- if (viewing && viewing.file.name === target.file.name) setViewOpen(false);- await load();- // The agent card's memory count changed; refresh the list provider too.- void reloadAgents();} catch (e) {- toastError(apiErrorText(e));+ setDeleteRefusal(apiErrorText(e));+ return;}+ toastSuccess(S.memory.deleteDone);+ if (viewing && viewing.file.name === target.file.name) setViewOpen(false);+ setRemoving(null);+ await load();+ // The agent card's memory count changed; refresh the list provider too.+ void reloadAgents();};if (error) return <p className="text-sm text-red-600 dark:text-red-400">{error}</p>;@@ -505,7 +538,7 @@ export function MemoryTab({variant="danger"label={`${S.memory.delete} ${file.title}`}title={S.memory.delete}- onClick={() => setRemoving({ scope, file })}+ onClick={() => askRemove({ scope, file })}><GlyphIcon d={ICONS.trash} size={14} /></IconButton>@@ -548,7 +581,7 @@ export function MemoryTab({<Button size="sm" onClick={() => openEditor(viewing.scope, viewing.file)}>{S.memory.edit}</Button>- <Button size="sm" variant="danger" onClick={() => setRemoving(viewing)}>+ <Button size="sm" variant="danger" onClick={() => askRemove(viewing)}>{S.memory.delete}</Button></div>@@ -885,7 +918,11 @@ export function MemoryTab({label={S.memory.importModeLabel}name="memory-import-mode"value={importMode}- onChange={setImportMode}+ onChange={(mode) => {+ setImportMode(mode);+ // The reason named the mode that was refused; choosing another starts clean.+ setImportRefusal(null);+ }}options={[{value: "skip",@@ -904,6 +941,13 @@ export function MemoryTab({},]}/>+ {/* This modal is where an import that needed no confirmation reports a refusal (the+ one that went through the plan confirmation prints it inside that card instead). */}+ {importRefusal !== null && importPlan === null && (+ <p className="text-xs text-red-600 dark:text-red-400">+ {S.common.refused(importRefusal)}+ </p>+ )}<div className="flex justify-end"><Button size="sm" variant="primary" disabled={importBusy} onClick={submitImport}>{S.memory.importAction}@@ -925,6 +969,7 @@ export function MemoryTab({busy={importBusy}onClose={() => setImportPlan(null)}onConfirm={() => void runImport(true)}+ refusal={importRefusal === null ? undefined : S.common.refused(importRefusal)}><div className="space-y-1.5 text-sm text-gray-700 dark:text-gray-300">{importPlan && importPlan.overwritten.length > 0 && (@@ -946,6 +991,7 @@ export function MemoryTab({cancelLabel={S.common.cancel}onClose={() => setRemoving(null)}onConfirm={() => void confirmRemove()}+ refusal={deleteRefusal === null ? undefined : S.common.refused(deleteRefusal)}><p className="text-sm text-gray-700 dark:text-gray-300">{removing ? S.memory.deleteConfirm(removing.file.title) : ""}