profiles: a saved profile renames, in its details, the TUI and magpie rename (#2721, erlinerd)

erlinerd's patch on #2721 (profile.Rename, /api/state profile/rename,
a Rename button in the details), reviewed against main and adapted:

- profile.Rename trims both names, refuses an empty, taken or missing
  name and leaves profiles.json as it was, renames by case only
  (home -> Home), and keeps what the profile holds.
- GUI: Rename turns the details' name into a field. Enter renames
  through profileAction, so the chip is renamed at once, pending, and
  rolled back with the error if magpie refuses; the details stay open
  under the new name, with In use kept. Escape or a click away puts
  the name back. The field lives in profilerename.js, imported on
  press, so the core script stays under its budget (no raise; 50 bytes
  under after comments in app.js were cut). While the field is open
  In use, Apply and Rename hide so a 360px panel's field has room.
- TUI: ctrl+e on a profile renames it on the name line.
- CLI: `magpie rename <old> <new>`; a flag is never taken for a name.
- WebDAV: a rename syncs as the old name gone and the new one in
  (davsync test).

Run on mote at 47672f11c (on 70b96126e), and again after rebasing on
52195b6b0 (backup), as 3b279fdee:
- go test ./internal/profile ./internal/cli ./internal/gui ./internal/tui
  ./internal/davsync: ok except TestEveryRouteHasACommandOrIsNamed
  (#4826) and TestMainWindowCorners (#3949), both red on origin/main
  07f4d46c5 too. gofmt clean; GOOS=linux (-tags nogui) and
  GOOS=windows go vet ok.
- GUI, chromium and webkit: profile-rename (en, zh, zh-TW, ja, de;
  900x560 window and 360x420 panel), panel-profiles, profile-confirm,
  profile-in-use, profile-details, hermes-profiles,
  view-wheel-after-click, i18n-keys, gui-de, gui-ja, gui-zh-tw,
  editor-roomy: 219 pass, 0 fail. After the rebase: profile, cli,
  gui, tui and vet again (same two reds only, core budget ok), and the
  GUI files above with auto-backup in place of editor-roomy: 161 pass.
  Then rebased over ea51526b6 (gateway, plugin, provider only; no
  file of this change, no GUI asset) without another run.

Broken by hand, each red, then restored:
- Rename comparing names with EqualFold: TestRename red (case-only).
- Dropping the CLI's "-" check: TestRenameCommand red.
- Dropping `profileOpen = to`: profile-rename 22 of 22 red, both engines.

Not tried: the real app on Linux (WebKitGTK) or Windows; a rename
synced over a real WebDAV server.

Co-authored-by: erlinerd <erlinerd@outlook.com>
This commit is contained in:
yetone
2026-11-02 18:37:25 +08:00
co-authored by erlinerd
parent ea51526b69
commit 1cb4d43013
14 changed files with 526 additions and 33 deletions
+13 -1
View File
@@ -66,6 +66,7 @@ const usage = `magpie — one place to pick every agent's model
magpie save <name> snapshot every agent's settings as a profile
magpie use <name> apply a profile
magpie profiles list profiles
magpie rename <old> <new> rename a profile
magpie rm <name> delete a profile
magpie backup [--no-keys] [--no-library] [file] providers, keys, settings, profiles, agent models and the library in one file, sealed with a passphrase
@@ -495,7 +496,7 @@ func run(args []string) error {
fmt.Println(green.Render("✓"), "catalog saved to", catalog.CachePath())
refreshLive(ctx)
return nil
case "save", "use", "rm", "profiles":
case "save", "use", "rm", "rename", "profiles":
return profiles(args)
case "import":
return importCmd(args[1:])
@@ -947,6 +948,17 @@ func profiles(args []string) error {
}
fmt.Println(green.Render("✓"), "deleted profile", bold.Render(args[1]))
return nil
case "rename":
// a flag is never taken for a name to write (magpie snow --help
// wrote "--help" into a profile)
if len(args) != 3 || strings.HasPrefix(args[2], "-") {
return fmt.Errorf("usage: magpie rename <old> <new>")
}
if err := profile.Rename(args[1], args[2]); err != nil {
return err
}
fmt.Println(green.Render("✓"), "renamed profile", bold.Render(args[1]), "to", bold.Render(args[2]))
return nil
}
return nil
}
+38
View File
@@ -0,0 +1,38 @@
package cli
import (
"slices"
"testing"
"github.com/yetone/magpie/internal/profile"
)
// magpie rename moves a profile's name; a flag or a missing or extra word
// is no name to write, and leaves the profiles as they were (#2721).
func TestRenameCommand(t *testing.T) {
helpHome(t)
if err := profile.Save("work", profile.Profile{Fields: map[string]string{"codex.model": "m"}}); err != nil {
t.Fatal(err)
}
names := func() []string {
ps, err := profile.Load()
if err != nil {
t.Fatal(err)
}
return profile.Names(ps)
}
for _, args := range [][]string{{"rename"}, {"rename", "work"}, {"rename", "work", "-x"}, {"rename", "work", "a", "b"}} {
if _, err := runOut(t, args...); err == nil {
t.Errorf("magpie %v went through", args)
}
if got := names(); !slices.Equal(got, []string{"work"}) {
t.Fatalf("magpie %v: %v", args, got)
}
}
if _, err := runOut(t, "rename", "work", "desk"); err != nil {
t.Fatal(err)
}
if got := names(); !slices.Equal(got, []string{"desk"}) {
t.Fatalf("after magpie rename work desk: %v", got)
}
}
+13 -1
View File
@@ -265,8 +265,20 @@ func TestSync(t *testing.T) {
if got := ids(); !slices.Equal(got, []string{"deepseek=k1", "kimi=k2"}) {
t.Fatalf("b after a added: %v", got)
}
// b renames a profile: a has it under the new name alone, what it
// held the same (#2721)
if err := profile.Rename("work", "desk"); err != nil {
t.Fatal(err)
}
now(t)
a.use(t)
now(t)
if ps, _ := profile.Load(); len(ps) != 1 || ps["desk"].Fields["claude.model"] != "x" {
t.Fatalf("a after b renamed: %v", ps)
}
b.use(t)
provider.Delete("deepseek")
profile.Delete("work")
profile.Delete("desk")
now(t)
a.use(t)
if v := now(t); v.Notice != nil {
+4 -1
View File
@@ -1280,9 +1280,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
writeJSON(rw, s)
})
mux.HandleFunc("POST /api/profile/{action}", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Name string }
var in struct{ Name, To string }
_ = json.NewDecoder(r.Body).Decode(&in)
in.Name = strings.TrimSpace(in.Name)
in.To = strings.TrimSpace(in.To)
var err error
var applied profile.Applied
switch r.PathValue("action") {
@@ -1303,6 +1304,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
case "delete":
err = profile.Delete(in.Name)
case "rename":
err = profile.Rename(in.Name, in.To)
default:
http.NotFound(rw, r)
return
+4 -2
View File
@@ -2158,7 +2158,7 @@ body.panel .foot { min-height: 0; padding: 5px 8px 7px 14px; border-top: 1px sol
}
.chip:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
.chip .cur-tick { margin: 0 4px 0 -2px; font-size: 11px; font-weight: 600; color: var(--accent); flex: none; }
.pd-cur { flex: none; font-size: 11.5px; color: var(--accent); }
.pd-cur { flex: 0 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 11.5px; color: var(--accent); }
.chip .lib { width: 5px; height: 5px; margin: 0 2px 0 4px; border-radius: 50%; background: var(--accent); opacity: .7; flex: none; }
.chip .x { width: 16px; height: 16px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; font-size: 12px; line-height: 1; opacity: 0; transition: opacity .12s; }
.chip:hover .x { opacity: .6; }
@@ -2176,7 +2176,9 @@ body.panel .foot { min-height: 0; padding: 5px 8px 7px 14px; border-top: 1px sol
body.window .profiles.detailed { align-items: flex-start; }
body.window .profiles.detailed > .label { line-height: 30px; }
body.window .profiles.detailed > #save { margin-top: 4px; }
.pd-name { flex: 1 1 auto; min-width: 0; font-weight: 600; color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* the name, or the field renaming it (#2721), keeps room beside its buttons */
.pd-head > .chip-input { flex: 1 1 auto; min-width: 6em; width: auto; }
.pd-name { flex: 1 1 auto; min-width: 3em; font-weight: 600; color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pd-apply { flex: none; height: 24px; padding: 0 12px; }
.pd-close { flex: none; width: 24px; height: 24px; padding: 0; border: 0; border-radius: 6px; background: none; color: var(--muted); font-size: 16px; line-height: 1; cursor: pointer; }
.pd-close:hover { color: var(--fg); background: rgba(127, 127, 127, .15); }
+27 -25
View File
@@ -853,11 +853,9 @@ function renderAgents() {
agentsGlide = null;
}
// renderProfiles draws the saved profiles as chips, a chip whose save,
// update or use is on its way dimmed until the answer is in. A click on a
// chip shows what the profile holds, and its Apply applies it (#467): it was
// applied at once, so what it held could be seen only by applying it over
// the setup in use.
// renderProfiles draws the saved profiles as chips, one on its way dimmed.
// A click on a chip shows what the profile holds, and its Apply applies it
// (#467).
function renderProfiles() {
const chips = $("#profiles");
if (!state.profiles.some((p) => p.name === profileOpen)) profileOpen = null;
@@ -865,10 +863,8 @@ function renderProfiles() {
$(".profiles > .chip-input")?.remove(); // a name field open goes with the list it was for
$(".profiles").classList.remove("naming", "detailed");
$("#save").textContent = t("+ Save current");
// the panel's button names the profile in use, as a pop-up button shows
// what is picked, else how many there are (superhtoooth on X: it read
// 方案 1, 方案 2, a count taken for the name the profile was saved under,
// and nothing said which one was in use)
// the panel's button names the profile in use, else how many there are
// (superhtoooth on X: a count read as a name)
const cur = state.profiles.find((p) => p.inUse);
const n = $("#profN");
n.textContent = cur ? cur.name : state.profiles.length || "";
@@ -1027,9 +1023,12 @@ function profileDetail(p, footed) {
closeProfileDetail();
chip?.focus(NO_SCROLL);
};
const rename = el("button", "text pd-rename", t("Rename"));
rename.type = "button";
rename.onclick = () => import("./profilerename.js").then(() => profRename(d, p), statusErr);
head.append(el("span", "pd-name", p.name));
if (p.inUse) head.append(el("span", "pd-cur", t("In use")));
head.append(apply, close);
head.append(apply, rename, close);
if (!footed) d.append(head);
const groups = p.agents || [];
if (!groups.length) d.append(el("div", "pd-none", t("No agent settings saved")));
@@ -5804,26 +5803,27 @@ function profileLibrary(l) {
return parts.length ? t("+ Library: {what}", { what: parts.join(t(", ")) }) : t("+ Library: nothing on");
}
// profilePending are the profiles a save, update, delete or use is on its
// way for. What the click does shows at once — the chip saved is there, the
// one deleted gone, the name field closed — rather than when magpie has read
// every agent again for the answer: that took seconds, and a Save or × that
// changed nothing for that long looked broken. An error puts the list back.
// profilePending are the profiles a save, update, delete, rename or use is
// on its way for: the click shows at once, not seconds later when magpie
// has read every agent again. An error puts the list back.
const profilePending = new Set();
async function profileAction(action, name, update) {
const before = state.profiles;
// A rename (to) keeps what the profile holds and its details open (#2721).
async function profileAction(action, name, update, to) {
const before = state.profiles, open = profileOpen, key = to || name;
// where magpie will list it: by name, as Go's sort.Strings has them
const byName = (l) => l.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
if (action === "delete") state.profiles = before.filter((p) => p.name !== name);
else if (action === "save" && !before.some((p) => p.name === name)) {
// where magpie will list it: by name, as Go's sort.Strings has them
state.profiles = [...before, { name, summary: "" }].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
}
if (action !== "delete") profilePending.add(name);
else if (to) {
state.profiles = byName(before.map((p) => (p.name === name ? { ...p, name: to } : p)));
if (open === name) profileOpen = to;
} else if (action === "save" && !before.some((p) => p.name === name)) state.profiles = byName([...before, { name, summary: "" }]);
if (action !== "delete") profilePending.add(key);
renderProfiles();
fit();
try {
const data = await api("profile/" + action, { name });
profilePending.delete(name);
const data = await api("profile/" + action, { name, to });
profilePending.delete(key);
state = data;
renderAgents();
if (action === "use") {
@@ -5839,10 +5839,12 @@ async function profileAction(action, name, update) {
else status(msg, "ok", lib?.missing?.length ? 6000 : 3500);
}
else if (action === "save") status(t(update ? "Updated {name} to the current setup" : "Saved {name}", { name }), "ok");
else if (to) status(t("Renamed {name} to {new}", { name, new: to }), "ok");
else status(t("Deleted {name}", { name }));
} catch (e) {
profilePending.delete(name);
profilePending.delete(key);
state.profiles = before;
profileOpen = open;
renderProfiles();
fit();
statusErr(e);
+4
View File
@@ -1893,6 +1893,7 @@ const I18N = {
"{user} · click to rename": "{user} · 点击改名",
"The same seat as the key plan {name}, shown once, on this account's card": "与 Key 套餐「{name}」是同一个席位,只在此账号的卡片上显示一次",
"Rename": "重命名",
"Renamed {name} to {new}": "已将 {name} 重命名为 {new}",
"Key removed": "已移除密钥",
"Key added — it takes over when the ones before it run out": "已添加密钥,前面的密钥用完时由它接上",
"Use": "使用",
@@ -6293,6 +6294,7 @@ const I18N = {
"{user} · click to rename": "{user} · 點擊改名",
"The same seat as the key plan {name}, shown once, on this account's card": "與 Key 方案「{name}」是同一個席位,只在此帳號的卡片上顯示一次",
"Rename": "重新命名",
"Renamed {name} to {new}": "已將 {name} 重新命名為 {new}",
"Key removed": "已移除金鑰",
"Key added — it takes over when the ones before it run out": "已新增金鑰,前面的金鑰用完時由它接上",
"Use": "使用",
@@ -10669,6 +10671,7 @@ const I18N = {
"{user} · click to rename": "{user} · クリックで名前を変更",
"The same seat as the key plan {name}, shown once, on this account's card": "キーのプラン「{name}」と同じシートです。このアカウントのカードに一度だけ表示されます",
"Rename": "名前を変更",
"Renamed {name} to {new}": "{name} の名前を {new} に変更しました",
"Key removed": "キーを削除しました",
"Key added — it takes over when the ones before it run out": "キーを追加しました。前のキーを使い切ると引き継ぎます",
"Use": "使用",
@@ -15076,6 +15079,7 @@ const I18N = {
"{user} · click to rename": "{user} · Klicken zum Umbenennen",
"The same seat as the key plan {name}, shown once, on this account's card": "Derselbe Platz wie der Schlüssel-Tarif {name}, nur einmal angezeigt, auf der Karte dieses Kontos",
"Rename": "Umbenennen",
"Renamed {name} to {new}": "{name} in {new} umbenannt",
"Key removed": "Schlüssel entfernt",
"Key added — it takes over when the ones before it run out": "Schlüssel hinzugefügt — er übernimmt, wenn die vorherigen aufgebraucht sind",
"Use": "Verwenden",
+27
View File
@@ -0,0 +1,27 @@
// A profile's Rename (#2721, erlinerd): the details' name becomes a field
// holding it, Enter renames through profileAction (its pending chip and
// rollback), Escape or a click away puts the name back. app.js imports
// this when Rename is pressed, so it weighs nothing on the core.
window.profRename = function (d, p) {
const name = d.querySelector(".pd-name");
if (!name) return;
const input = el("input", "chip-input pd-rename-input");
input.value = p.name;
input.setAttribute("aria-label", t("Profile name"));
// while it is open the field has the head, × aside: In use, Apply and
// Rename left a narrow panel's field no room to type in
const rest = [...d.querySelectorAll(".pd-cur, .pd-apply, .pd-rename")];
const show = (on) => rest.forEach((b) => (b.hidden = !on));
show(false);
const back = () => { if (input.isConnected) { input.replaceWith(name); show(true); } };
input.onkeydown = (e) => {
e.stopPropagation(); // Escape is the field's, not the details'
const to = input.value.trim();
if (e.key === "Enter" && to && to !== p.name) { input.onblur = null; profileAction("rename", p.name, false, to); }
else if (e.key === "Enter" || e.key === "Escape") back();
};
input.onblur = () => setTimeout(back, 100);
name.replaceWith(input);
input.focus(NO_SCROLL);
input.select();
};
+88
View File
@@ -0,0 +1,88 @@
package gui
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/profile"
"github.com/yetone/magpie/internal/provider"
)
// Renaming a profile through the page's own call moves its key and keeps the
// setup it held, and a name already taken is rejected without dropping either
// profile (#2721).
func TestStateProfileRename(t *testing.T) {
home := sandboxHome(t)
t.Setenv("CODEX_HOME", home+"/.codex")
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
h := Handler(nil, nil)
call := func(path, body string) (stateJSON, int) {
t.Helper()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
var s stateJSON
if rec.Code == 200 {
if err := json.Unmarshal(rec.Body.Bytes(), &s); err != nil {
t.Fatal(err)
}
}
return s, rec.Code
}
names := func(s stateJSON) []string {
var ns []string
for _, p := range s.Profiles {
ns = append(ns, p.Name)
}
return ns
}
has := func(ns []string, want string) bool {
for _, n := range ns {
if n == want {
return true
}
}
return false
}
if _, code := call("/api/profile/save", `{"name":"work"}`); code != 200 {
t.Fatalf("save code %d", code)
}
if err := profile.Save("taken", profile.Profile{Fields: map[string]string{"codex.model": "relay/m1"}}); err != nil {
t.Fatal(err)
}
// rename success: old name gone, new name present
s, code := call("/api/profile/rename", `{"name":"work","to":"home"}`)
if code != 200 {
t.Fatalf("rename code %d", code)
}
if has(names(s), "work") {
t.Errorf("old name still present: %v", names(s))
}
if !has(names(s), "home") {
t.Errorf("new name missing: %v", names(s))
}
// content kept: the renamed profile keeps what work held
ps, err := profile.Load()
if err != nil {
t.Fatal(err)
}
if _, ok := ps["home"]; !ok {
t.Errorf("renamed profile not written: %v", ps)
}
// rename onto a taken name is rejected, both names survive
s, code = call("/api/profile/rename", `{"name":"home","to":"taken"}`)
if code == 200 {
t.Fatalf("rename onto taken should fail: %v", names(s))
}
ps, _ = profile.Load()
if _, ok := ps["home"]; !ok {
t.Errorf("rejected rename dropped the source: %v", ps)
}
if _, ok := ps["taken"]; !ok {
t.Errorf("rejected rename dropped the taken one: %v", ps)
}
}
+135
View File
@@ -0,0 +1,135 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Renaming a profile from its details (#2721, erlinerd): Rename turns the
// name into a field holding it; Enter renames, the chip under its new name
// at once, the details still open on it, what it holds and its In use kept;
// Escape renames nothing; a name already taken is refused, the list put
// back and the reason shown. In the window and the tray panel, in every
// language. No backend: the API is faked here.
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(__dirname, "../assets");
const models = ["model-a", "model-b"].map((m) => ({ value: m, label: m }));
const agent = { id: "codex", name: "Codex", path: "/test/codex", fields: [{ key: "model", label: "model", value: "model-a", options: models }] };
const profile = (name, inUse) => ({ name, summary: "", inUse, agents: [{ id: "codex", name: "Codex", fields: [{ key: "model", label: "model", value: name + "-model" }] }] });
function server(lang, calls) {
let profiles = [profile("home"), profile("work", true)];
return async (route) => {
const req = route.request(), url = new URL(req.url());
const state = () => ({ agents: [agent], profiles, settings: { lang, theme: "light" } });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: state() });
if (url.pathname.startsWith("/api/profile/")) {
const action = url.pathname.slice("/api/profile/".length), body = req.postDataJSON();
calls.push(action + " " + JSON.stringify(body));
if (action === "rename") {
if (profiles.some((p) => p.name === body.to)) return route.fulfill({ status: 400, json: { error: `a profile named "${body.to}" already exists` } });
await new Promise((r) => setTimeout(r, 300)); // magpie reading every agent again
profiles = profiles.map((p) => (p.name === body.name ? { ...p, name: body.to } : p)).sort((a, b) => (a.name < b.name ? -1 : 1));
}
return route.fulfill({ json: state() });
}
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
if (url.pathname.startsWith("/api/")) return route.fulfill({ 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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const words = {
en: { rename: "Rename", renamed: "Renamed work to team", inUse: "In use" },
zh: { rename: "重命名", renamed: "已将 work 重命名为 team", inUse: "使用中" },
"zh-TW": { rename: "重新命名", renamed: "已將 work 重新命名為 team", inUse: "使用中" },
ja: { rename: "名前を変更", renamed: "work の名前を team に変更しました", inUse: "使用中" },
de: { rename: "Umbenennen", renamed: "work in team umbenannt", inUse: "In Verwendung" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a profile renames from its details", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of Object.keys(words)) for (const panel of [false, true]) {
await t.test(`${lang}, ${panel ? "panel" : "window"}`, async () => {
const w = words[lang], calls = [], errors = [];
const page = await (await browser.newContext({ viewport: panel ? { width: 360, height: 420 } : { width: 900, height: 560 } })).newPage();
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, calls));
await page.goto("http://magpie.test/" + (panel ? "?mode=panel" : ""));
const chip = (name) => page.locator("#profiles .chip", { hasText: new RegExp("^✓?" + name) });
await chip("work").waitFor({ state: "attached" });
if (panel) {
await page.locator("#profBtn").click();
await page.locator(".profiles.open").waitFor();
}
const detail = page.locator(".prof-detail");
const field = detail.locator(".pd-rename-input");
const names = () => page.locator("#profiles .chip").evaluateAll((cs) => cs.map((c) => c._profile));
await chip("work").locator("span").first().click();
await detail.waitFor();
assert.equal((await detail.locator(".pd-rename").textContent()).trim(), w.rename);
// Escape: the name back, nothing sent, the details still open
await detail.locator(".pd-rename").click();
await field.waitFor();
assert.equal(await field.inputValue(), "work", "the field holds the name");
await field.fill("other");
await field.press("Escape");
await detail.locator(".pd-name").waitFor();
assert.equal(await field.count(), 0);
assert.equal(await detail.count(), 1, "Escape on the field leaves the details open");
assert.deepEqual(calls, []);
// Enter: the chip renamed at once, the details on it, In use kept
await detail.locator(".pd-rename").click();
await field.fill(" team ");
await field.press("Enter");
await chip("team").waitFor({ state: "attached" });
assert.deepEqual(await names(), ["home", "team"], "renamed before magpie answered");
assert.match(await chip("team").getAttribute("class"), /pending/);
await page.waitForFunction(() => !document.querySelector("#profiles .chip.pending"));
assert.deepEqual(calls, ['rename {"name":"work","to":"team"}']);
assert.equal((await page.locator("#status").textContent()).trim(), w.renamed);
assert.equal(await detail.locator(".pd-name").textContent(), "team", "the details follow the new name");
assert.equal(await detail.locator(".pd-cur").textContent(), w.inUse);
assert.match(await chip("team").getAttribute("class"), /\bcur\b/);
assert.match(await detail.textContent(), /work-model/, "what it holds is kept");
// a name taken: refused, the list as it was, the reason shown
calls.length = 0;
await detail.locator(".pd-rename").click();
await field.fill("home");
await field.press("Enter");
await page.waitForFunction(() => document.querySelector("#status").classList.contains("err"));
assert.equal((await page.locator("#status").textContent()).trim(), 'a profile named "home" already exists');
assert.deepEqual(await names(), ["home", "team"]);
assert.equal(await detail.locator(".pd-name").textContent(), "team");
assert.deepEqual(calls, ['rename {"name":"team","to":"home"}']);
// the head fits: the field and its buttons inside the details
await detail.locator(".pd-rename").click();
const box = await detail.boundingBox(), f = await field.boundingBox();
assert(f.x >= box.x && f.x + f.width <= box.x + box.width + 0.5, `field ${JSON.stringify(f)} out of ${JSON.stringify(box)}`);
assert(f.width >= 60, "the field has room to type in: " + f.width);
const x = await detail.locator(".pd-close").boundingBox();
assert(x.x + x.width <= box.x + box.width + 0.5, `× ${JSON.stringify(x)} out of ${JSON.stringify(box)}`);
await field.press("Escape");
assert((await detail.locator(".pd-name").boundingBox()).width >= 20, "the name keeps room beside the buttons");
assert.deepEqual(errors, []);
});
}
});
}
+29
View File
@@ -210,6 +210,35 @@ func Delete(name string) error {
return store(ps)
}
// Rename moves what old held onto to, changing only its key in
// profiles.json: nothing is snapshotted again, so a profile in use is still
// in use under its new name (#2721). A name that differs only in case is a
// rename too, and an unreadable profiles.json writes nothing, as Save and
// Delete do.
func Rename(old, to string) error {
old, to = strings.TrimSpace(old), strings.TrimSpace(to)
if to == "" {
return fmt.Errorf("profile name is empty")
}
ps, err := Load()
if err != nil {
return err
}
p, ok := ps[old]
if !ok {
return fmt.Errorf("no profile named %q", old)
}
if to == old {
return nil
}
if _, ok := ps[to]; ok {
return fmt.Errorf("a profile named %q already exists", to)
}
delete(ps, old)
ps[to] = p
return store(ps)
}
// Applied is what applying a profile did.
type Applied struct {
Changed int // agent fields changed, and model lists
+60
View File
@@ -204,3 +204,63 @@ func TestApplySkipsUndetectedAgents(t *testing.T) {
t.Error(err)
}
}
// Rename moves a profile's key without snapshotting it again: what it held
// is the same under the new name, a name differing only in case is a rename,
// and each refusal writes nothing (#2721, erlinerd).
func TestRename(t *testing.T) {
sandbox(t)
work := Profile{Fields: map[string]string{"codex.model": "gpt-5"}, Library: &library.Setup{}}
if err := Save("work", work); err != nil {
t.Fatal(err)
}
if err := Save("taken", Profile{Fields: map[string]string{"claude.model": "acme/m1"}}); err != nil {
t.Fatal(err)
}
keys := func() []string { return Names(must[map[string]Profile](t)(Load())) }
if err := Rename(" work ", " home "); err != nil {
t.Fatal(err)
}
ps := must[map[string]Profile](t)(Load())
if got := Names(ps); !slices.Equal(got, []string{"home", "taken"}) {
t.Fatalf("after work → home: %v", got)
}
if got := ps["home"]; got.Fields["codex.model"] != "gpt-5" || got.Library == nil {
t.Errorf("home lost what work held: %+v", got)
}
if err := Rename("home", "Home"); err != nil {
t.Fatal(err)
}
if got := keys(); !slices.Equal(got, []string{"Home", "taken"}) {
t.Errorf("a rename by case only: %v", got)
}
before := read(t, Path())
for _, c := range []struct{ old, to, err string }{
{"Home", " ", "profile name is empty"},
{"Home", "taken", `a profile named "taken" already exists`},
{"nope", "other", `no profile named "nope"`},
{"Home", "Home", ""},
} {
err := Rename(c.old, c.to)
if (err == nil) != (c.err == "") || (err != nil && err.Error() != c.err) {
t.Errorf("Rename(%q, %q) = %v, want %q", c.old, c.to, err, c.err)
}
if got := read(t, Path()); got != before {
t.Errorf("Rename(%q, %q) wrote profiles.json: %s", c.old, c.to, got)
}
}
// profiles.json unreadable (here a folder): an error, nothing written
sandbox(t)
if err := os.MkdirAll(Path(), 0o755); err != nil {
t.Fatal(err)
}
if err := Rename("Home", "moved"); err == nil {
t.Error("a rename over an unreadable profiles.json went through")
}
if fi, err := os.Stat(Path()); err != nil || !fi.IsDir() {
t.Errorf("an unreadable profiles.json was written over: %v", err)
}
}
+30 -3
View File
@@ -98,6 +98,7 @@ type model struct {
mode mode
pk picker
name textinput.Model
rename string // the profile the name line renames, "" when it saves one
flash string
flashOK bool
w, h int
@@ -460,7 +461,7 @@ func (m model) updateList(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m, syncCmd
}
case "s":
m.mode = modeName
m.mode, m.rename = modeName, ""
m.name = newInput("profile name")
case "p":
m.openProfiles()
@@ -570,6 +571,15 @@ func (m model) updatePicker(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m, m.pk.refetch()
}
return m, nil
case "ctrl+e":
// the profile picked, renamed on a line holding its name (#2721)
if m.mode == modeProfiles && len(m.pk.match) > 0 {
m.rename = m.pk.items[m.pk.match[m.pk.cursor]].Value
m.name = newInput("new name")
m.name.SetValue(m.rename)
m.mode = modeName
}
return m, nil
case "ctrl+d":
if m.mode == modeProfiles && m.pk.onDel != nil && len(m.pk.match) > 0 {
n := m.pk.items[m.pk.match[m.pk.cursor]].Value
@@ -605,7 +615,7 @@ func (m model) updatePicker(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
func (m model) updateName(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "esc":
m.mode = modeList
m.mode, m.rename = modeList, ""
return m, nil
case "enter":
n := strings.TrimSpace(m.name.Value())
@@ -613,6 +623,15 @@ func (m model) updateName(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m, nil
}
m.mode = modeList
if old := m.rename; old != "" {
m.rename = ""
return m, func() tea.Msg {
if err := profile.Rename(old, n); err != nil {
return flashMsg{text: err.Error()}
}
return flashMsg{text: "profile " + old + " renamed to " + n, ok: true}
}
}
return m, func() tea.Msg {
p, err := profile.Snapshot()
if err != nil {
@@ -786,7 +805,7 @@ func (m model) View() string {
body = m.viewPicker()
switch {
case m.mode == modeProfiles:
footer = hints("↑↓", "move", "↵", "apply", "ctrl+d", "delete", "esc", "back")
footer = hints("↑↓", "move", "↵", "apply", "ctrl+e", "rename", "ctrl+d", "delete", "esc", "back")
case m.pk.refetch != nil:
footer = hints("↑↓", "move", "↵", "on / off", "ctrl+r", "fetch models again", "esc", "back")
case m.pk.toggle != nil:
@@ -805,6 +824,9 @@ func (m model) View() string {
case modeName:
body = m.viewName()
footer = hints("↵", "save", "esc", "cancel")
if m.rename != "" {
footer = hints("↵", "rename", "esc", "cancel")
}
}
status := ""
@@ -966,6 +988,11 @@ func (m model) viewPicker() string {
func (m model) viewName() string {
var b strings.Builder
if m.rename != "" {
b.WriteString(m.header("rename profile") + "\n\n" + pad + sCursor.Render("❯ ") + m.name.View() + "\n\n")
b.WriteString(pad + " " + sMuted.Render("renames "+m.rename+" · the settings it holds stay as they are"))
return b.String()
}
b.WriteString(m.header("save profile"))
b.WriteString("\n\n")
b.WriteString(pad + sCursor.Render("❯ ") + m.name.View())
+54
View File
@@ -14,6 +14,7 @@ import (
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/agentenv"
"github.com/yetone/magpie/internal/library"
"github.com/yetone/magpie/internal/profile"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
@@ -81,6 +82,8 @@ func keyMsg(k string) tea.KeyMsg {
return tea.KeyMsg{Type: tea.KeyCtrlU}
case "ctrl+r":
return tea.KeyMsg{Type: tea.KeyCtrlR}
case "ctrl+e":
return tea.KeyMsg{Type: tea.KeyCtrlE}
}
return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(k)}
}
@@ -456,3 +459,54 @@ func TestAgentsViewKeepsTheRowPicked(t *testing.T) {
t.Fatalf("a tall terminal dropped the top of the list:\n%s", v)
}
}
// ctrl+e on the profiles renames the one picked on a line holding its
// name; what it holds stays, esc renames nothing, and a taken name is
// refused with both kept (#2721).
func TestProfileRename(t *testing.T) {
home(t)
for _, n := range []string{"base", "work"} {
if err := profile.Save(n, profile.Profile{Fields: map[string]string{"codex.model": n + "-model"}}); err != nil {
t.Fatal(err)
}
}
names := func() []string {
ps, err := profile.Load()
if err != nil {
t.Fatal(err)
}
return profile.Names(ps)
}
m := press(t, model{w: 120, h: 40}, "p")
if !strings.Contains(m.View(), "ctrl+e rename") {
t.Fatalf("the profiles' footer names no rename:\n%s", m.View())
}
m = press(t, m, "down", "ctrl+e")
if m.mode != modeName || m.name.Value() != "work" || !strings.Contains(m.View(), "rename profile") {
t.Fatalf("mode %d, line %q:\n%s", m.mode, m.name.Value(), m.View())
}
m = press(t, m, "esc")
if got := names(); !slices.Equal(got, []string{"base", "work"}) {
t.Fatalf("esc renamed: %v", got)
}
m = press(t, m, "p", "down", "ctrl+e", "ctrl+u")
m = typeIn(m, "desk")
m = press(t, m, "enter")
wantFlash(t, m, true, "work renamed to desk")
ps, _ := profile.Load()
if got := names(); !slices.Equal(got, []string{"base", "desk"}) || ps["desk"].Fields["codex.model"] != "work-model" {
t.Fatalf("after the rename: %v %+v", got, ps["desk"])
}
m = press(t, m, "p", "down", "ctrl+e", "ctrl+u")
m = typeIn(m, "base")
m = press(t, m, "enter")
if m.mode != modeList {
t.Fatalf("mode %d:\n%s", m.mode, m.View())
}
wantFlash(t, m, false, `a profile named "base" already exists`)
if got := names(); !slices.Equal(got, []string{"base", "desk"}) {
t.Fatalf("a taken name: %v", got)
}
}