A local-first multi-agent app development platform, built on PenguinHarness
fix(models): 保存 / 设为默认 / 设为视觉代理的确认框只在写成功之后收起(条目 7.15)
lmlihenga58d505cf074
diff --git a/changelog/unreleased/2026-10-20-models-save-refusal.md b/changelog/unreleased/2026-10-20-models-save-refusal.mdnew file mode 100644index 00000000..544a596b--- /dev/null+++ b/changelog/unreleased/2026-10-20-models-save-refusal.md@@ -0,0 +1,35 @@+# Saving a model's config: the confirmation closes only after the save lands++- **Date:** 2026-10-20+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文版](2026-10-20-models-save-refusal.zh.md)++The model config dialog asks before it writes: save the changes, make this model the default, or+make it the vision proxy model. That confirmation — and the dialog behind it — used to close as+soon as the request left, **whether the write had succeeded or not**, while `persist` keeps the+attempted rows and the attempted pointer. A refused save therefore left the page showing a model+under the name the server had not accepted, and a refused "set as default" left the card wearing+the 默认 tag while the server still pointed at another model. The sentence naming the change was+gone with the dialogs, and the card that opens them had to be found again to try once more.++Now every one of those actions is written before either dialog is dismissed, and a refused one+leaves the page on the table and the pointers the server still holds.++## Details++- Both dialogs stay open until the table write lands; on a refusal the sentence stays verbatim,+ the draft stays in the form, the error toast shows the server's own words, and the retry is that+ same confirmation.+- A refused write leaves the table and both pointers as they stood before it, so the page never+ claims a change the server declined.+- The confirmation is marked busy while the request is in flight, and the dialog's own confirm+ button locks with it, so a second click cannot start a second write.+- This is the same rule the delete, the group delete, "sync presets" and "clear errors" already+ follow: a dialog is dismissed by the write's outcome, not by the click.++## Compatibility++- No API, wire-format or dependency change: this is only the order of writing and dismissing.diff --git a/changelog/unreleased/2026-10-20-models-save-refusal.zh.md b/changelog/unreleased/2026-10-20-models-save-refusal.zh.mdnew file mode 100644index 00000000..4811f0fe--- /dev/null+++ b/changelog/unreleased/2026-10-20-models-save-refusal.zh.md@@ -0,0 +1,29 @@+# 保存模型配置:写成功才收起确认框,被拒的修改不留在页面上++- **Date:** 2026-10-20+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[English](2026-10-20-models-save-refusal.md)++模型的配置对话框在写入前都会问一句:保存修改、把这个模型设为默认、或设为视觉代理模型。而这张确认框+和它背后的配置对话框此前在请求发出时就关闭,**不管写没写成**;同时 `persist` 会保留尝试中的表与尝试+中的指针。于是被拒的一次保存让页面显示着一个服务器没有接受的名字,被拒的「设为默认模型」让卡片挂上+「默认」标记、服务器却仍指着别的模型。写着这次改动的那个句子随着对话框一起没了,要再试一次就得重新+找到打开对话框的那张卡片。++现在这三个动作都把写入做完之后才收起这两张对话框,被拒时页面留在服务器仍然持有的那张表与那两个指针上。++## 细节++- 两张对话框一直开到表写入有结果为止;被拒时句子原样留着、草稿仍留在表单里,错误提示照旧显示服务端+ 那句话,重试就是同一张确认框。+- 写入被拒时页面上的表与两个指针都退回写入前:页面不会宣称一件服务器拒绝了的改动。+- 请求在飞的时候确认框标为 busy,对话框自己的确认按钮一同锁住,连点不会发出第二次写入。+- 这与删除、删除分组、「同步预置」、「清空错误记录」用的是同一条规则:对话框由写入的结果收起,而不是+ 由那一次点击收起。++## 兼容性++- 没有接口、传输格式或依赖变化;只改了页面里写入与收起的先后。diff --git a/packages/web/e2e/models-save-refusal.spec.mjs b/packages/web/e2e/models-save-refusal.spec.mjsnew file mode 100644index 00000000..3191b15a--- /dev/null+++ b/packages/web/e2e/models-save-refusal.spec.mjs@@ -0,0 +1,263 @@+/**+ * Regression: the config dialog's save and "set as default" wait for their write, and a refused+ * one leaves the page on what the server still holds.+ *+ * Both of these used to dismiss the confirmation (and the config dialog behind it) on the click,+ * while `persist` kept the attempted rows and the attempted pointer — so a refused save left the+ * page showing a renamed model the server had not renamed (measured: both dialogs gone, the card+ * carrying the new name, `displayName` on the server unchanged), and a refused "set as default"+ * left a card wearing the 默认 tag while the server still pointed at another model. Nothing was+ * left to retry from: the card that opens the dialog had to be found again, and the sentence+ * naming the change was gone. The retry is now the same confirmation, and only a written change+ * closes both dialogs.+ *+ * Both tests work on a hand-added model inside a user-defined group, seeded through the table PUT+ * so nothing here depends on the built-in catalog.+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const P = "password123";++/** The group and model the tests write to; unique enough to appear nowhere else. */+const GROUP = "probesave";+const MODEL = "probe-save";+const NAME = "Probe Save";+const RENAMED = "Probe Save Renamed";++/** The row the model is, as this file seeds it: a hand-added model of a user-defined group. */+const ROW = {+ provider: GROUP,+ modelId: MODEL,+ displayName: NAME,+ contextWindow: 32000,+ clientType: "openai-chat",+ baseUrl: "http://127.0.0.1:9/v1",+ maxTokens: 4096,+};++/** The table entry a `ModelInfo` came from: every field the response reports, sent back as-is. */+function toEntry(m) {+ const entry = { provider: m.provider, modelId: m.modelId };+ for (const key of [+ "displayName",+ "contextWindow",+ "clientType",+ "vision",+ "maxTokens",+ "fastMode",+ "pricing",+ ]) {+ if (m[key] !== undefined) entry[key] = m[key];+ }+ if (m.credential?.baseUrl !== undefined) entry.baseUrl = m.credential.baseUrl;+ return entry;+}++/**+ * Provision the user and seed their Project: the model under its seeded name, and the default+ * pointer NOT on it (so "set as default" has something to change). Idempotent: a rerun on the+ * same data root rewrites the row the tests expect and moves a pointer an earlier run left here+ * rather than trusting either.+ */+async function projectWithModel(page, userId) {+ await provisionAndLogin(page.request, userId, P);+ const { projects } = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects[0].projectId;+ const read = async () =>+ (await page.request.get(`${BASE}/api/projects/${projectId}/models`)).json();+ const rowOf = async () =>+ (await read()).models.find((m) => m.provider === GROUP && m.modelId === MODEL);++ const table = await read();+ const current = table.models.find((m) => m.provider === GROUP && m.modelId === MODEL);+ const pointerIsOurs = table.defaultModel?.modelId === MODEL;+ if (!current || (current.displayName ?? "") !== NAME || pointerIsOurs) {+ // A pointer already on our model is moved to any other row: the PUT only rewrites the+ // pointer it is given, and omitting it would leave the stale one in place.+ const other = table.models.find((m) => m.modelId !== MODEL);+ const defaultModel =+ pointerIsOurs && other+ ? { provider: other.provider, modelId: other.modelId }+ : table.defaultModel;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel,+ models: [...table.models.filter((m) => toEntry(m).provider !== GROUP).map(toEntry), ROW],+ },+ });+ expect(put.ok(), "seed the model through the table PUT").toBeTruthy();+ }+ expect(await rowOf(), "the Project holds the model").toBeTruthy();+ return { read };+}++/** Refuse every table write with a code the app has no local copy for, so the server's words show. */+async function refuseWrites(page, seen) {+ await page.route("**/api/projects/*/models", async (route) => {+ if (route.request().method() !== "PUT") return route.fallback();+ seen.push(route.request().url());+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({+ error: { code: "models_store_closed", message: "models store is closed" },+ }),+ });+ });+}++/**+ * Open the model's config dialog. The list is filtered rather than scrolled: a user-defined group+ * sits far below the built-in ones, and a search force-opens every group it leaves visible.+ */+async function openModelDialog(page) {+ await page.locator('input[placeholder*="搜索"]').first().fill(NAME);+ const card = page.getByText(NAME, { exact: true }).first();+ await expect(card).toBeVisible();+ await card.click();+ const dialog = page.getByRole("dialog");+ await expect(dialog).toBeVisible();+ await expect(page.getByRole("button", { name: "删除模型" })).toBeVisible();+ return dialog;+}++/**+ * The confirmation stacked on the config dialog, told apart by its own sentence ("确定保存对…" /+ * "确定把…设为默认模型"): its title and the dialog's buttons repeat labels the page already uses.+ */+function confirmation(page, sentence) {+ return page.getByRole("dialog").filter({ hasText: sentence });+}++/** The model card the named model is: the card's own button, whose text carries its marks. */+function cardFor(page, name) {+ return page.getByText(name, { exact: true }).first().locator("xpath=ancestor::button[1]");+}++test("a refused save keeps both dialogs and the name the server still holds", async ({ page }) => {+ const { read } = await projectWithModel(page, "r93save");++ await page.goto("/models");+ const dialog = await openModelDialog(page);+ const nameInput = dialog.locator('input[placeholder*="留空则展示模型 ID"]');+ await expect(nameInput).toHaveValue(NAME);+ await nameInput.fill(RENAMED);++ await dialog.getByRole("button", { name: "确认" }).click();+ const confirm = confirmation(page, "确定保存对");+ await expect(confirm).toBeVisible();+ const sentence = await confirm.innerText();+ expect(sentence).toContain(NAME);++ const puts = [];+ await refuseWrites(page, puts);+ await confirm.getByRole("button", { name: "确认" }).click();++ // The write was refused: the server's words show, and both dialogs are still exactly as they+ // were — the same sentence, the draft still in the field.+ await expect(page.getByText("models store is closed")).toBeVisible();+ expect(puts).toHaveLength(1);+ await expect(confirm).toBeVisible();+ expect(await confirm.innerText()).toBe(sentence);+ await expect(nameInput).toHaveValue(RENAMED);+ await expect(page.getByRole("button", { name: "删除模型" })).toBeVisible();++ // And the card behind it is back to the name the server still holds: the page must not claim+ // a rename that did not happen.+ const card = cardFor(page, NAME);+ await expect(card).toContainText(NAME);+ expect(await card.innerText()).not.toContain(RENAMED);+ const table = await read();+ expect(table.models.find((m) => m.provider === GROUP && m.modelId === MODEL).displayName).toBe(+ NAME,+ );++ // Canceling the confirmation decides nothing: the config dialog and its draft stay.+ await confirm.getByRole("button", { name: "取消" }).click();+ await expect(confirmation(page, "确定保存对")).toHaveCount(0);+ await expect(nameInput).toHaveValue(RENAMED);+});++test("the retry of a refused save is the same confirmation, and only a written one closes the dialog", async ({+ page,+}) => {+ const { read } = await projectWithModel(page, "r93saveretry");++ await page.goto("/models");+ const dialog = await openModelDialog(page);+ const nameInput = dialog.locator('input[placeholder*="留空则展示模型 ID"]');+ await nameInput.fill(RENAMED);++ const puts = [];+ let refuse = true;+ await page.route("**/api/projects/*/models", async (route) => {+ if (route.request().method() !== "PUT") return route.fallback();+ puts.push(route.request().url());+ if (!refuse) return route.fallback();+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({+ error: { code: "models_store_closed", message: "models store is closed" },+ }),+ });+ });++ await dialog.getByRole("button", { name: "确认" }).click();+ const confirm = confirmation(page, "确定保存对");+ await confirm.getByRole("button", { name: "确认" }).click();+ await expect(page.getByText("models store is closed")).toBeVisible();+ await expect(confirm).toBeVisible();+ expect(puts).toHaveLength(1);++ // The retry is the same confirmation — no reopening the card, no second 确认 inside the dialog.+ refuse = false;+ await confirm.getByRole("button", { name: "确认" }).click();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ expect(puts).toHaveLength(2);+ await expect(cardFor(page, RENAMED)).toContainText(RENAMED);+ const table = await read();+ expect(table.models.find((m) => m.provider === GROUP && m.modelId === MODEL).displayName).toBe(+ RENAMED,+ );+});++test("a refused set-as-default keeps both dialogs and the pointer the server still holds", async ({+ page,+}) => {+ const { read } = await projectWithModel(page, "r93default");++ await page.goto("/models");+ const dialog = await openModelDialog(page);+ const row = async () =>+ (await read()).models.find((m) => m.provider === GROUP && m.modelId === MODEL);+ const before = (await read()).defaultModel;+ expect(before?.modelId).not.toBe(MODEL);++ await dialog.getByRole("button", { name: "设为默认模型" }).click();+ const confirm = confirmation(page, "设为默认模型?");+ await expect(confirm).toBeVisible();++ const puts = [];+ await refuseWrites(page, puts);+ await confirm.getByRole("button", { name: "确认" }).click();++ await expect(page.getByText("models store is closed")).toBeVisible();+ expect(puts).toHaveLength(1);+ // Both dialogs stay up: the confirmation over the config dialog it was started from.+ await expect(page.getByRole("dialog")).toHaveCount(2);+ await expect(confirm).toBeVisible();+ // The card behind them does not wear the 默认 tag the server never granted.+ expect(await cardFor(page, NAME).innerText()).not.toContain("默认");+ expect((await read()).defaultModel).toEqual(before);+ expect((await row()).modelId).toBe(MODEL);++ // Retrying from the same confirmation, once the write is let through, is what grants it.+ await page.unroute("**/api/projects/*/models");+ await page.getByRole("dialog").last().getByRole("button", { name: "确认" }).click();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(cardFor(page, NAME)).toContainText("默认");+ expect((await read()).defaultModel).toEqual({ provider: GROUP, modelId: MODEL });+});diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex 9011ee97..28a2c80f 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -903,7 +903,8 @@ export function ModelsPage() {/*** Changes save immediately (dialog confirm / set default / set vision model / delete):* avoids the trap of "still have to click save after confirming". On failure, the error- * is echoed back and local changes are kept so the user can fix and retry.+ * is echoed back with the table the caller names (see `refusedRows`), so a retry starts+ * from something the server still holds rather than from a change it declined.*/const persist = async (nextRows: RowState[],@@ -913,10 +914,11 @@ export function ModelsPage() {successText?: string,/*** The table to leave on the page when the write is refused. Default: the attempted rows,- * which is right for a field edit the user is still holding. A delete passes the table as- * it stood instead — its attempted rows are a table without the model, and showing it for- * the instant before the caller restores them unmounts the config dialog, which is gated on- * its row still being in the table.+ * which is right for a write made on the page itself (the bulk key for a group). Every+ * write made from the config dialog passes the table as it stood instead: its attempted+ * rows are what the server declined, and showing them — for the instant before the caller+ * restores the real table, or for good — unmounts that dialog, which is gated on its row+ * still being in the table, and claims a change that did not happen.*/refusedRows?: RowState[],): Promise<boolean> => {@@ -1886,7 +1888,6 @@ export function ModelsPage() {return saved;});}- closeModelDialog();const nextRows = isNew? [...rows, next]: rows.map((r) => (sameModelRef(rowRef(r), editing) ? next : r));@@ -1897,7 +1898,29 @@ export function ModelsPage() {defaultModel,visionModel,});- void persist(nextRows, ptr.defaultModel, ptr.visionModel);+ // Save / set-default / set-vision-proxy report back too, and the dialog stays up+ // until they do. A refused one leaves the page on the table and the pointers the+ // server still holds: the draft lives in the dialog, so there is nothing to keep+ // on screen for a retry — and a refused "set as default" used to leave the card+ // wearing the 默认 tag while the server still pointed elsewhere (measured: page+ // said 默认 on the edited model, `defaultModel` on the server unchanged, both+ // dialogs gone). `before` goes in as `refusedRows` for the same reason the delete+ // passes it: a rename or a move to another group would otherwise take the dialog+ // (gated on its row still being in the table) down for one render.+ const before = rows;+ const beforeDefault = defaultModel;+ const beforeVision = visionModel;+ return persist(nextRows, ptr.defaultModel, ptr.visionModel, undefined, before).then(+ (saved) => {+ if (saved) {+ closeModelDialog();+ return true;+ }+ setDefaultModel(beforeDefault);+ setVisionModel(beforeVision);+ return false;+ },+ );}}/>)}@@ -2490,9 +2513,12 @@ function ModelDialog({/** Closes the dialog and runs the header's "sync presets" merge; absent for a member, who cannot write the config. */onSyncPresets?: () => void;/**- * Commit one action. The remove action reports whether its write landed (and keeps this- * dialog up until then); every other action closes on the way out as before, so they- * return nothing.+ * Commit one action and report whether its write landed. Every action answers now: this+ * dialog and its confirmation stay up until the answer arrives, so a refused save, a+ * refused "set as default / as vision proxy" and a refused delete all keep their sentence+ * and their retry where the user left them. Only a written change closes them (the page+ * does that for the actions it owns). `void` stays in the type for a caller with nothing+ * to wait for.*/onSubmit: (row: RowState, action: DialogAction) => Promise<boolean> | void;}) {@@ -2563,8 +2589,12 @@ function ModelDialog({* (Adding a new custom model isn't confirmed: opening the dialog is itself a clear intent.)*/const [confirming, setConfirming] = useState<DialogAction | null>(null);- /** The confirmed remove is on the wire: its confirmation waits for the answer instead of closing on the click. */- const [removing, setRemoving] = useState(false);+ /**+ * The confirmed write is on the wire: its confirmation waits for the answer instead of+ * closing on the click, and its buttons are locked so a second click cannot fire a rival+ * write against the same sentence.+ */+ const [writing, setWriting] = useState(false);/** Fast mode is being switched ON and awaits the premium-billing warning's confirmation. */const [confirmingFastMode, setConfirmingFastMode] = useState(false);/** Protocol detection in progress (custom / user-defined groups only). */@@ -2995,33 +3025,31 @@ function ModelDialog({const submit = async (action: DialogAction) => {const next = validated();if (!next) return;+ let payload = next;if (needsProtocolDetectOnSave(action, next.provider, next.clientType)) {// Joins a run already started from the Detect button rather than probing twice.const detected = await runDetect("save");- onSubmit(- {- ...next,- clientType: detected?.clientType ?? DEFAULT_CUSTOM_CLIENT_TYPE,- // The draft was snapshotted before the probe, so a base URL the probe corrected- // has to be carried over by hand — otherwise the entry saves a URL the detected- // protocol is not served at.- ...(detected?.baseUrl !== undefined ? { baseUrl: detected.baseUrl } : {}),- },- action,- );- return;+ payload = {+ ...next,+ clientType: detected?.clientType ?? DEFAULT_CUSTOM_CLIENT_TYPE,+ // The draft was snapshotted before the probe, so a base URL the probe corrected+ // has to be carried over by hand — otherwise the entry saves a URL the detected+ // protocol is not served at.+ ...(detected?.baseUrl !== undefined ? { baseUrl: detected.baseUrl } : {}),+ };}- const written = onSubmit(next, action);+ const written = onSubmit(payload, action);if (written === undefined) return;- // Only the remove action reports back. A refused delete has to keep this dialog and its- // confirmation exactly as they are — the sentence names the model and what goes with it,- // and the retry is the same click — so the confirmation is dismissed here, once the write- // landed (on success the page closes this dialog too, which unmounts both).- setRemoving(true);+ // Every action reports back now, not just the remove: a refused save or a refused+ // "set as default" used to take this dialog and its confirmation down with the request,+ // so the sentence that named the change was gone and the only way to retry was to find+ // the card again (and the page behind it showed the change the server had refused).+ // Keeping both until the answer arrives makes the retry the same click.+ setWriting(true);try {if (await written) setConfirming(null);} finally {- setRemoving(false);+ setWriting(false);}};@@ -3220,8 +3248,10 @@ function ModelDialog({variant="primary"// Saving may have to probe the endpoint first (protocol still unset), which// is a network round-trip: the label says so and the button locks, matching- // the "test connection" convention used inside this dialog.- disabled={detecting}+ // the "test connection" convention used inside this dialog. It also locks+ // while the write itself is on the wire (a new model has no confirmation, so+ // this is the only button that could send a second one).+ disabled={detecting || writing}onClick={() => {// Validate first: if validation fails, the inline field errors show right away without popping the confirm dialog.if (!validated()) return;@@ -3806,13 +3836,12 @@ function ModelDialog({opentitle={CONFIRM_TITLE[confirming]()}tone={confirming === "remove" ? "danger" : "primary"}- busy={confirming === "remove" && removing}+ busy={writing}onClose={() => setConfirming(null)}onConfirm={() => {const action = confirming;- // The remove confirmation lives until its write lands (see `submit`): dismissed on- // the click it could only ever say nothing about a refusal.- if (action !== "remove") setConfirming(null);+ // The confirmation lives until its write lands (see `submit`): dismissed on the+ // click it could only ever say nothing about a refusal.void submit(action);}}confirmLabel={S.common.confirm}