gui: Duplicate and Add another ask before they drop a provider's typed edits

In a provider's editor, Duplicate and "Add another {name}" open a new
draft in its place. Each dropped what was typed without a word, while
Cancel, Escape, the scrim and a row click ask "Discard unsaved changes?".
Both now ask the same way: Cancel keeps the edit as typed, Discard goes
on; an untouched editor asks nothing. Duplicate still copies the saved
provider, not the unsaved edit.

The scan also named Add provider, the add sheet's tiles and a plugin's
sign-in. The editor is a modal over them, so none can be reached while a
draft is open; they are left alone.

Paid for in the core budget, no raise: the five "providerDirty() &&
confirmDiscard()" checks are one leaveDraft(), and the eight "editing =
x; draft = null; renderProviders()" are one reEdit(x).

Run (mote, at this tree on origin/main e1e454398):
- provider-unsaved-paths (new), ux-safety, add-sheet, add-sheet-custom,
  group-duplicate, plugin-signin, account-cap, signin-again,
  zen-anon-key, Chromium and WebKit: 154 pass, 0 fail.
- go test ./internal/gui -run 'TestCoreScriptBudget|TestI18n|TestCSS': ok.
- duplicate-pause, key-import, provider-typed and vertex-editor: 12 of
  64 red, the same 12 on origin/main e1e454398 without this change, each
  filed: #6424, #6416, #4673, #4720.

Broken by hand: app.js put back to its base, provider-unsaved-paths 4 of
4 red (no question asked, the edit gone).

Not tried: the real app window.
This commit is contained in:
yetone
2026-11-18 12:44:01 +08:00
parent f17300d9c1
commit e5c0c23de0
2 changed files with 103 additions and 12 deletions
+16 -12
View File
@@ -6269,14 +6269,14 @@ function renderProviders(quiet) {
// right-click: Move to Top, Move Up, Move Down, Move to Bottom (#1614)
if (!p.off) row.oncontextmenu = (ev) => { ev.preventDefault(); openProviderMenu(row.querySelector(".pv-handle"), p, { x: ev.clientX, y: ev.clientY }); };
row.onclick = async () => {
if (providerDirty() && !(await confirmDiscard())) return;
if (!await leaveDraft()) return;
// a list drawn before the fresh one is in (#1519) leaves out what the
// editor shows (headers, proxies): the row opens on the fresh one
if (providers.last) {
try { await loadProviders(); } catch (e) { statusErr(e); return; }
if (!providers.providers.some((x) => x.id === p.id)) return;
}
editing = open ? null : p.id; draft = null; renderProviders();
reEdit(open ? null : p.id);
}; // the preset sheet stays as it is under the dialog
list.append(row);
if (open) dialog = renderEditor(p);
@@ -6367,7 +6367,7 @@ function openProviderMenu(anchor, p, at) {
// pvpick.js, imported when Select is first clicked, so they weigh nothing
// on the core. pvSel is the ids picked while picking, null otherwise.
let pvSel = null, pvSelLast = null;
$("#pvSelect").onclick = async () => (!providerDirty() || await confirmDiscard()) && import("./pvpick.js").then(() => startPicking(), statusErr);
$("#pvSelect").onclick = async () => await leaveDraft() && import("./pvpick.js").then(() => startPicking(), statusErr);
// Providers' search (#1614): the rows saying every word, on and off, by their
// text, ids, addresses, users and keys; a word they don't say is a model's
@@ -6569,7 +6569,7 @@ function renderMovable() {
// the editor opens over the list: the page itself doesn't move
review.onclick = () => {
if (ps.length > 1) { openPlugins(); return; }
editing = ps[0].id; draft = null; renderProviders();
reEdit(ps[0].id);
};
box.append(depLine("", ps.length > 1 ? t("These built-in subscriptions are deprecated: {names}", { names }) : t("{name}'s built-in subscription is deprecated", { name: names }), [t(DEPRECATED_WHY), t("Moving keeps your accounts, models and agents as they are.")].join(locale === "zh" || locale === "zh-TW" || locale === "ja" ? "" : " "), hide, review));
}
@@ -7173,7 +7173,7 @@ function pickForAgent(a, p, btn, ev) {
if (!field.options.some((o) => pre.test(o.value))) {
ev.stopPropagation();
status(t("{p} exposes no models yet — pick some below", { p: p.name }), "warn");
editing = p.id; draft = null; renderProviders();
reEdit(p.id);
return;
}
openPicker(agent, field, btn, ev, (o) => pre.test(o.value));
@@ -7244,7 +7244,7 @@ function renderAdd() {
c.append(svg(PLUS, 11, 1.8), t("Custom provider"));
c.dataset.pick = "custom";
c.title = t("any OpenAI or Anthropic compatible URL");
c.onclick = () => { editing = { custom: true }; draft = null; renderProviders(); };
c.onclick = () => reEdit({ custom: true });
const imp = el("button", "text", t("Import…"));
imp.title = t("Bring over providers set up in other apps");
imp.onclick = openImportApps;
@@ -7438,7 +7438,7 @@ async function pluginSignIn(id, e) {
// openProvider: a provider opened in the Providers tab
async function openProvider(id) {
if (view === "providers" && providerDirty() && !(await confirmDiscard())) return;
if (view === "providers" && !await leaveDraft()) return;
if (!await show("providers")) return;
closeModal();
adding = false; editing = id; draft = null; presetQuery = "";
@@ -7518,9 +7518,9 @@ function tile(pr) {
markAdded(b);
b.title = t("{name} is already added — open it", { name: pr.name });
const have = presetProvider(pr);
b.onclick = () => { editing = have?.id ?? pr.id; draft = null; renderProviders(); };
b.onclick = () => reEdit(have?.id ?? pr.id);
} else {
b.onclick = () => { editing = { preset: pr.id }; draft = null; renderProviders(); };
b.onclick = () => reEdit({ preset: pr.id });
}
return b;
}
@@ -7766,6 +7766,10 @@ function confirmRemoval(name, consequence = "This removes the selected item. Con
function confirmDiscard() {
return confirmAction(t("Discard"), t("Discard unsaved changes? Your changes will be lost."), t("Discard"));
}
// opens x's editor (a provider id, { preset } or { custom }) with a new draft
function reEdit(x) { editing = x; draft = null; renderProviders(); }
// true when the open provider draft has nothing to lose, or the reader lets it go
const leaveDraft = async () => !providerDirty() || await confirmDiscard();
async function cancelEdit(keep) {
if ((providerDirty() || ((importing || importingApps) && modalFormDirty())) && !(await confirmDiscard())) return false;
if (keep !== true) dropSigningIn(editing);
@@ -10404,13 +10408,13 @@ function drawEditor(p, presetID) {
// another key of the vendor, or the same key for another workspace
const more = el("button", "text", t("Add another {name}", { name: pr.name }));
more.title = vertex ? t("One more {name} provider, with its own project, credentials, headers and models", { name: pr.name }) : t("One more {name} provider, with its own key, headers and models", { name: pr.name });
more.onclick = () => { editing = { preset: pr.id }; draft = null; renderProviders(); };
more.onclick = async () => { if (await leaveDraft()) reEdit({ preset: pr.id }); };
bar.append(more);
}
if (p) {
const dup = el("button", "text", t("Duplicate"));
dup.title = vertex ? t("A new provider with {name}'s project, credentials, headers and models, to change before adding", { name: p.name }) : t("A new provider with {name}'s URLs, key, headers, models and balance settings, to change before adding", { name: p.name });
dup.onclick = () => duplicateProvider(p);
dup.onclick = async () => { if (await leaveDraft()) duplicateProvider(p); };
bar.append(dup);
}
bar.append(el("span", "grow"));
@@ -15957,7 +15961,7 @@ function atAddress(urls, origin) {
$("#addProvider").onclick = (e) => {
const view = $("#view-providers"), sheet = $("#addSheet");
if (!adding) {
adding = true; editing = null; draft = null; renderProviders();
adding = true; reEdit(null);
return unrollSheet(view, sheet, e);
}
if (!scrollOnPurpose(e, 700)) return;
@@ -0,0 +1,87 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Duplicate and Add another in a provider's editor open a new draft in its
// place, so they ask before dropping typed changes, as Cancel does. Cancel
// keeps the edit as typed; Discard goes on. An untouched draft asks nothing.
// Both engines, English and Chinese; the API is faked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));
function server(lang) {
const relay = { id: "relay", name: "Relay", icon: "generic", preset: "relay", host: "relay.test", chat: "https://relay.test/v1",
responses: "", anthropic: "", models: [{ id: "fixture-model", name: "Fixture model", on: true }], agents: [], fallback: [],
headers: { "X-Fixture": "kept" }, key: { set: true, masked: "sk-…1234" }, keyList: [], ready: true };
const presets = [
{ id: "relay", name: "Relay", icon: "generic", kind: "relay", chat: relay.chat, added: true },
{ id: "acme", name: "Acme", icon: "openai", kind: "vendor", chat: "https://api.acme.example.com/v1", added: false },
{ id: "beta", name: "Beta", icon: "openai", kind: "vendor", chat: "https://api.beta.example.com/v1", added: false },
];
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers: [relay], presets, excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const L = {
en: { dup: "Duplicate", more: "Add another Relay", ask: /Discard unsaved/, cancel: /^Cancel$/, copy: "Relay copy" },
zh: { dup: "复制", more: "再添加一个 Relay", ask: /放弃未保存/, cancel: /^取消$/, copy: "Relay 副本" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(L)) test(`${engine} ${lang}: Duplicate and Add another ask before dropping edits`, async (t) => {
const w = L[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { errors.push("native dialog"); d.dismiss(); });
await page.route("**/*", server(lang));
await page.goto("http://magpie.test/?view=providers");
const modal = page.locator("#modal"), ask = page.getByRole("alertdialog");
const name = modal.locator("input.provider-name");
for (const button of [w.dup, w.more]) {
await page.locator('#providers .row.provider[data-id="relay"]').click();
await name.waitFor();
// untouched: no question
await modal.getByRole("button", { name: button, exact: true }).click();
await page.waitForTimeout(200);
assert.equal(await ask.count(), 0, button + " asked with nothing typed");
await page.keyboard.press("Escape");
await modal.waitFor({ state: "hidden" });
await page.locator('#providers .row.provider[data-id="relay"]').click();
await name.fill("Relay edited");
await modal.getByRole("button", { name: button, exact: true }).click();
await ask.waitFor();
assert.match(await ask.textContent(), w.ask);
await ask.getByRole("button", { name: w.cancel }).click();
await ask.waitFor({ state: "detached" });
assert.equal(await name.inputValue(), "Relay edited", button + ": Cancel keeps the edit");
await modal.getByRole("button", { name: button, exact: true }).click();
await ask.waitFor();
await ask.locator("button").last().click();
await ask.waitFor({ state: "detached" });
await page.waitForFunction(() => !document.querySelector("#modal .bar")?.textContent.includes("Remove") && !document.querySelector("#modal .bar")?.textContent.includes("删除"));
if (button === w.dup) assert.ok(await modal.evaluate((m, copy) => [...m.querySelectorAll("input")].some((i) => i.value === copy), w.copy), "the copy opened");
await page.keyboard.press("Escape");
if (await ask.count()) { await ask.locator("button").last().click(); }
await modal.waitFor({ state: "hidden" });
}
assert.deepEqual(errors, []);
});
}