diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index 35b31d03c..11045b16b 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -79,6 +79,23 @@ values in and clears `Own`. A Restore brings everything and clears it too. The three maps survive a change of server (`TestOwnModelStaysOnEachComputer`, `TestNewPicksStillGoBothWays`, `sync-own-fields.test.cjs`). +A whole agent's picks can be kept to one computer on purpose, as an MCP +server can (chenxiang0010 on Discord): the Agents row's menu has **This +computer only** (`POST /api/agents/here`), which adds the agent's id to +`Settings.AgentsHere`, a computer's own kept by `KeepOwn` and by a save of +the Settings page (`settingsapi.Apply`). It is off by default, so an upgrade +changes no pick anywhere. For each such agent, `withHere` adds `.*` to +the own set (`isOwn` matches every field of it), so a sync neither pushes its +fields nor brings the server's in, a Restore from the server leaves them, +and `backup.Restore` skips the agent in a backup file. sync-state.json +records the list as of the last sync (`Here`): the hashes before a sync use +it and those after use the current list, so turning it on or off is no +change on either side, and the list changing forces the sync past its early +returns. Turned off, the next pick here goes up again; the other agents +sync both ways throughout. A kept agent is not listed under Kept on this +computer, which is the implicit own fields only (`TestAgentHereThroughSync`, +`TestAgentsHereIsThisComputers`, `agent-here.test.cjs`). + Sharing turned on at one computer never turns it on or off at another (Lullaby on Discord). A backup restored onto a new computer leaves sharing as that computer has it, off on a fresh one: sharing opens the gateway to the diff --git a/internal/backup/backup.go b/internal/backup/backup.go index 4dc2353be..260c709e6 100644 --- a/internal/backup/backup.go +++ b/internal/backup/backup.go @@ -490,10 +490,23 @@ func Restore(b Bundle, parts Parts) (Result, error) { for _, a := range agent.Detected() { here[a.ID] = true } + // an agent whose picks stay on this computer (AgentsHere) takes + // none from elsewhere; unread settings tell nothing, so none go in + cur, err := settings.LoadChecked() + if err != nil { + return r, err + } + kept := map[string]bool{} + for _, id := range cur.AgentsHere { + kept[id] = true + } // one value at a time, so one that fails (a model of a subscription // not signed in here) leaves the rest to go in for _, k := range profileKeys(b.Agents) { id := k[:max(strings.LastIndex(k, "."), 0)] // codex@wsl:Ubuntu-24.04.model + if kept[id] { + continue + } if !here[id] { r.Skipped = append(r.Skipped, k) continue diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 2a985fced..85c3cfcbb 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -176,6 +176,7 @@ var notYet = map[string]string{ "GET /api/state": W, // api.go "POST /api/agents/{action}/{id}": A, // api.go "POST /api/agents/arrange": W, // api.go + "POST /api/agents/here": A, // api.go "POST /api/agents/cli/{id}": A, // api.go "POST /api/agents/disconnect-offline/{id}": A, // api.go "POST /api/agents/rescan": A, // api.go diff --git a/internal/davsync/agent_here_test.go b/internal/davsync/agent_here_test.go new file mode 100644 index 000000000..c799b00bc --- /dev/null +++ b/internal/davsync/agent_here_test.go @@ -0,0 +1,146 @@ +package davsync + +import ( + "context" + "testing" + + "github.com/yetone/magpie/internal/backup" + "github.com/yetone/magpie/internal/profile" + "github.com/yetone/magpie/internal/settings" +) + +// hereAgents sets the agents whose picks stay on this computer, as the +// Agents row's This computer only does (POST /api/agents/here). +func hereAgents(t *testing.T, ids ...string) { + t.Helper() + s, err := settings.LoadChecked() + if err != nil { + t.Fatal(err) + } + s.AgentsHere = ids + if err := settings.Save(s); err != nil { + t.Fatal(err) + } +} + +// An agent's picks kept to one computer, as an MCP server can be +// (chenxiang0010 on Discord: Codex on two computers, each with its own +// model). Turning it on changes nothing anywhere. From then on that +// computer's Codex picks, model and effort alike, neither go up nor take +// the others' in, by sync, a Restore from the server or a backup file; +// every other agent's picks still sync both ways. Turned off, the next +// pick here reaches the others again. +func TestAgentHereThroughSync(t *testing.T) { + f := newGithubFixture(t) + ctx := context.Background() + c := githubConfig() + now := func(t *testing.T) { + t.Helper() + if err := Now(ctx); err != nil { + t.Fatal(err) + } + if st := Status(); st.Notice != nil || st.Error != "" { + t.Fatalf("a sync that replaced nothing: %+v %q", st.Notice, st.Error) + } + } + server := func(t *testing.T) map[string]string { + t.Helper() + b, err := backup.Open(f.objects[backupAt], c.Passphrase) + if err != nil { + t.Fatal(err) + } + return b.Agents + } + codexIs := func(t *testing.T, at, model, effort string) { + t.Helper() + if m, e := codexHere(); m != model || e != effort { + t.Fatalf("%s: Codex %q %q, want %q %q", at, m, e, model, effort) + } + } + a, b := newComputer(t), newComputer(t) + + a.use(t) + codexPick(t, "gpt-a1", "low") + if m, _ := codexHere(); m != "gpt-a1" { + t.Skipf("Codex isn't seen here: %v", profile.Fields()) + } + if err := Configure(c); err != nil { + t.Fatal(err) + } + now(t) + + b.use(t) + codexPick(t, "gpt-b0", "low") + if err := Configure(c); err != nil { + t.Fatal(err) + } + if err := Now(ctx); err != nil { + t.Fatal(err) + } + if err := Dismiss(); err != nil { + t.Fatal(err) + } + codexIs(t, "B joining", "gpt-a1", "low") + + // B keeps Codex's picks here: nothing changes on either side + hereAgents(t, "codex") + now(t) + codexIs(t, "B turning it on", "gpt-a1", "low") + + // B's picks stay on B + codexPick(t, "gpt-b1", "high") + now(t) + if got := server(t); got["codex.model"] != "gpt-a1" || got["codex.effort"] != "low" { + t.Fatalf("B's kept picks went up: %q %q", got["codex.model"], got["codex.effort"]) + } + + // A's picks go up, Claude Code's too + a.use(t) + now(t) + codexIs(t, "A after B's kept pick", "gpt-a1", "low") + codexPick(t, "gpt-a2", "medium") + if _, err := profile.ApplyFields(map[string]string{"claude.model": "claude-from-a"}); err != nil { + t.Fatal(err) + } + if profile.Fields()["claude.model"] != "claude-from-a" { + t.Skipf("Claude Code isn't seen here: %v", profile.Fields()) + } + now(t) + if got := server(t); got["codex.model"] != "gpt-a2" || got["claude.model"] != "claude-from-a" { + t.Fatalf("A's picks: server has %q %q", got["codex.model"], got["claude.model"]) + } + + // at B, Claude Code's comes in, Codex's stays B's + b.use(t) + now(t) + codexIs(t, "B after A's pick", "gpt-b1", "high") + if m := profile.Fields()["claude.model"]; m != "claude-from-a" { + t.Fatalf("A's Claude Code model didn't reach B: %q", m) + } + if v := Status(); len(v.Own) != 0 { + t.Fatalf("a kept agent is no Follow the others: %+v", v.Own) + } + + // a Restore from the server and a backup file keep it too + if _, err := Restore(ctx); err != nil { + t.Fatal(err) + } + codexIs(t, "B after a Restore", "gpt-b1", "high") + if _, err := backup.Restore(backup.Bundle{Agents: map[string]string{"codex.model": "gpt-file", "codex.effort": "low"}}, backup.Parts{Agents: true}); err != nil { + t.Fatal(err) + } + codexIs(t, "B after a backup file", "gpt-b1", "high") + + // turned off, nothing changes until a pick, which goes up again + hereAgents(t) + now(t) + codexIs(t, "B turning it off", "gpt-b1", "high") + codexPick(t, "gpt-b2", "high") + now(t) + if got := server(t); got["codex.model"] != "gpt-b2" { + t.Fatalf("B's pick after turning it off didn't go up: %q", got["codex.model"]) + } + a.use(t) + now(t) + codexIs(t, "A after B turned it off", "gpt-b2", "high") +} diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 73adc329b..d9c59ba9d 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -225,6 +225,10 @@ type state struct { Replaced map[string]string `json:"replaced,omitempty"` Own map[string]bool `json:"own,omitempty"` Follow bool `json:"follow,omitempty"` + // Here is the agents whose picks stayed on this computer (settings' + // AgentsHere) as the last sync left them: an agent turned so since is + // a change the next sync settles, its hashes made as before it. + Here []string `json:"here,omitempty"` } // blind is a write the server didn't check: the file it wrote (Sum), and @@ -693,7 +697,7 @@ func syncNow(ctx context.Context, force bool) error { } st := loadState() if st.Key != stateKey(c) { // another folder or passphrase: start afresh - st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Follow: st.Follow} + st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Follow: st.Follow, Here: st.Here} } err = syncOnce(ctx, c, &st) if errors.Is(err, errChanged) { // another computer got in between: again, over its version @@ -1108,7 +1112,9 @@ func syncOnce(ctx context.Context, c Config, st *state) error { // owned now is a change here, never a change on both sides. own is // every field kept here this time, and after what the next sync's // hashes leave out: none of them, once Settings gave them back. - prev := maps.Clone(st.Own) + // An agent whose picks stay here (hereOf) is own in every field, as + // the last sync had it in prev, as it is now in keep and afterW. + prev := withHere(maps.Clone(st.Own), st.Here) if c.Agents { noticeOwn(st, local.Agents) } @@ -1118,9 +1124,12 @@ func syncOnce(ctx context.Context, c Config, st *state) error { after = nil } st.Follow = false + kept := hereOf(c, local) + moved := !slices.Equal(kept, st.Here) + keep, afterW := withHere(own, kept), withHere(after, kept) L := hashesOwn(local, prev) if unchanged { - if maps.Equal(L, st.Local) && !follow { + if maps.Equal(L, st.Local) && !follow && !moved { return nil // nothing changed on either side } // changed here: merged with the server's file as last seen, or, @@ -1145,7 +1154,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { if err != nil { return err } - st.Sum, st.Server, st.Remote = sum(sealed), v, hashesOwn(b, after) + st.Sum, st.Server, st.Remote = sum(sealed), v, hashesOwn(b, afterW) if v.Blind { were.Sum = st.Sum st.Blind = &were @@ -1157,11 +1166,11 @@ func syncOnce(ctx context.Context, c Config, st *state) error { if err := push(local, "", blind{}); err != nil { return err } - st.Own = after - st.Local = hashesOwn(local, after) + st.Own, st.Here = after, kept + st.Local = hashesOwn(local, afterW) return nil } - if sum(data) == st.Sum && maps.Equal(L, st.Local) && !follow { + if sum(data) == st.Sum && maps.Equal(L, st.Local) && !follow && !moved { st.Server = ver remember(data) return nil // nothing changed on either side @@ -1226,7 +1235,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { // R compares with the last sync as its hashes were; Rafter is the // server's file as this sync leaves it read, both before the merge // below changes remote (a join's unseen gateway keys) - R, Rafter := hashesOwn(remote, prev), hashesOwn(remote, after) + R, Rafter := hashesOwn(remote, prev), hashesOwn(remote, afterW) first := st.Local == nil merged := remote var bringIn, here, there []string @@ -1244,7 +1253,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { case lc && !rc: take(&merged, local, p) if p == "agents" { - keepServersOwn(&merged, remote, own) + keepServersOwn(&merged, remote, keep) } case rc && !lc: if first && p == "settings" { @@ -1258,7 +1267,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { if changed(p, c.Keys).After(remote.Created) { take(&merged, local, p) if p == "agents" { - keepServersOwn(&merged, remote, own) + keepServersOwn(&merged, remote, keep) } there = append(there, p) } else { @@ -1284,7 +1293,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { } for _, p := range bringIn { if p == "agents" { - got, err := bringAgents(remote.Agents, after) + got, err := bringAgents(remote.Agents, afterW) broughtIn(st, got) if err != nil { return fmt.Errorf("bringing in the %s: %w", p, err) @@ -1310,7 +1319,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { return fmt.Errorf("bringing in the agents: %w", err) } } - st.Own, R = after, Rafter + st.Own, st.Here, R = after, kept, Rafter // the server's file is in; what is pushed next counts as changed here // until the push is done if len(bringIn) > 0 || follow { @@ -1318,8 +1327,8 @@ func syncOnce(ctx context.Context, c Config, st *state) error { return err } } - now := hashesOwn(local, after) - M, pending := hashesOwn(merged, after), map[string]string{} + now := hashesOwn(local, afterW) + M, pending := hashesOwn(merged, afterW), map[string]string{} for _, p := range Parts { pending[p] = now[p] if M[p] != R[p] && st.Local != nil { diff --git a/internal/davsync/own.go b/internal/davsync/own.go index 9b4026a7d..26918dc59 100644 --- a/internal/davsync/own.go +++ b/internal/davsync/own.go @@ -53,13 +53,55 @@ func withoutOwn(b backup.Bundle, own map[string]bool) backup.Bundle { if len(own) == 0 || b.Agents == nil { return b } - b.Agents = maps.Clone(b.Agents) - for k := range own { - delete(b.Agents, k) + a := maps.Clone(b.Agents) + for k := range b.Agents { + if isOwn(own, k) { + delete(a, k) + } } + b.Agents = a return b } +// An agent whose picks stay on this computer (settings' AgentsHere, +// chenxiang0010 on Discord, as an MCP server can be kept to one) is in an +// own set as ".*": every field of it, the ones it gains later too. +// That set is made for each sync and never kept in Own, so Settings' +// Follow the others doesn't give it back; the agent's row does. + +// withHere is own with every field of here's agents. +func withHere(own map[string]bool, here []string) map[string]bool { + if len(here) == 0 { + return own + } + out := maps.Clone(own) + if out == nil { + out = map[string]bool{} + } + for _, id := range here { + out[id+".*"] = true + } + return out +} + +// isOwn is whether field k is in own: by itself, or as its agent's. +func isOwn(own map[string]bool, k string) bool { + if own[k] { + return true + } + id, _ := splitField(k) + return own[id+".*"] +} + +// hereOf is the agents whose picks stay here, as b's settings say, in +// order; none when sync leaves the agents out. +func hereOf(c Config, b backup.Bundle) []string { + if !c.Agents || b.Settings == nil { + return nil + } + return slices.Compact(slices.Sorted(slices.Values(b.Settings.AgentsHere))) +} + // hashesOwn is hashes of b with this computer's own fields left out. func hashesOwn(b backup.Bundle, own map[string]bool) map[string]string { return hashes(withoutOwn(b, own)) @@ -75,13 +117,16 @@ func keepServersOwn(merged *backup.Bundle, remote backup.Bundle, own map[string] if a == nil { a = map[string]string{} } - for k := range own { - if v, ok := remote.Agents[k]; ok { - a[k] = v - } else { + for k := range merged.Agents { + if isOwn(own, k) { delete(a, k) } } + for k, v := range remote.Agents { + if isOwn(own, k) { + a[k] = v + } + } merged.Agents = a } @@ -95,15 +140,17 @@ type brought struct{ was, now string } // each field the bring changed here. func bringAgents(fields map[string]string, keep map[string]bool) (map[string]brought, error) { in := maps.Clone(fields) - for k := range keep { - delete(in, k) + for k := range fields { + if isOwn(keep, k) { + delete(in, k) + } } before := profile.Fields() _, err := backup.Restore(backup.Bundle{Agents: in}, backup.Parts{Agents: true}) after := profile.Fields() back := map[string]string{} - for k := range keep { - if v, ok := before[k]; ok && after[k] != v { + for k, v := range before { + if isOwn(keep, k) && after[k] != v { back[k] = v } } @@ -115,7 +162,7 @@ func bringAgents(fields map[string]string, keep map[string]bool) (map[string]bro } got := map[string]brought{} for k, v := range after { - if !keep[k] && before[k] != v { + if !isOwn(keep, k) && before[k] != v { got[k] = brought{before[k], v} } } diff --git a/internal/davsync/restore.go b/internal/davsync/restore.go index 2787aff10..638a61f0c 100644 --- a/internal/davsync/restore.go +++ b/internal/davsync/restore.go @@ -76,7 +76,8 @@ func Restore(ctx context.Context) ([]string, error) { if err != nil { return err } - L, R := hashes(local), hashes(remote) + here := withHere(nil, hereOf(c, local)) // an agent's picks kept here are no change + L, R := hashesOwn(local, here), hashesOwn(remote, here) for _, p := range Parts { if L[p] == R[p] || !c.syncs(p) || (p == "library" && remote.Library == nil) { continue @@ -85,7 +86,7 @@ func Restore(ctx context.Context) ([]string, error) { } st := loadState() if st.Key != stateKey(c) { - st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own} + st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Here: st.Here} } if len(brought) > 0 { kept, err := keepHere(c) @@ -96,7 +97,7 @@ func Restore(ctx context.Context) ([]string, error) { if p == "agents" { // the server's whole, the fields kept here too: they // follow the others again, as Follow leaves them - got, err := bringAgents(remote.Agents, nil) + got, err := bringAgents(remote.Agents, here) broughtIn(&st, got) st.Own, st.Follow = nil, false if err != nil { @@ -116,7 +117,9 @@ func Restore(ctx context.Context) ([]string, error) { } // as a sync that brought them in leaves it: the next one has // nothing to push back - st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, st.Own), hashesOwn(remote, st.Own), sum(data), ver + st.Here = hereOf(c, local) + own := withHere(st.Own, st.Here) + st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, own), hashesOwn(remote, own), sum(data), ver st.Blind = nil // what is here now is what the server has remember(data) st.Last, st.Error = time.Now(), "" @@ -186,10 +189,12 @@ func Upload(ctx context.Context) error { } st := loadState() if st.Key != stateKey(c) { - st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own} + st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Here: st.Here} } // as the first sync to an empty server leaves it - st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, st.Own), hashesOwn(b, st.Own), sum(sealed), v + st.Here = hereOf(c, local) + own := withHere(st.Own, st.Here) + st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, own), hashesOwn(b, own), sum(sealed), v st.Blind = nil // it replaced what wasn't a backup: nothing to merge again remember(sealed) st.Last, st.Error, st.File = time.Now(), "", nil diff --git a/internal/gui/api.go b/internal/gui/api.go index 1a6a09a40..2f706b834 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2130,6 +2130,36 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) + // an agent whose picks stay on this computer, or go to the others again + // (settings' AgentsHere, chenxiang0010 on Discord) + mux.HandleFunc("POST /api/agents/here", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Agent string + On bool + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if in.Agent = strings.TrimSpace(in.Agent); in.Agent == "" { + fail(rw, errors.New("no agent")) + return + } + s, err := settings.LoadChecked() + if err != nil { + fail(rw, err) + return + } + s.AgentsHere = slices.DeleteFunc(s.AgentsHere, func(x string) bool { return x == in.Agent }) + if in.On { + s.AgentsHere = append(s.AgentsHere, in.Agent) + } + if err := settings.Save(s); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) // the Usage page's order of its cards, which the tray panel's Allowances // tab follows, what that tab leaves out, the clients the page's Agents // list leaves out, the allowance cards its Overview leaves out diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 2da645d3e..5877eb833 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -740,6 +740,8 @@ body.window .row.agent .who .ag-cli { flex: 0 1 auto; overflow: hidden; } @container (max-width: 250px) { body.window .row.agent .ag-app { display: none; } } .ag-offpath { flex: 0 1 auto; min-width: 0; } @container (max-width: 250px) { body.window .row.agent .ag-offpath { display: none; } } +.ag-here { flex: 0 1 auto; min-width: 0; } +@container (max-width: 250px) { body.window .row.agent .ag-here { display: none; } } .ag-cli { display: inline-flex; align-items: center; gap: 6px; flex: none; min-width: 0; } .ag-cli:empty { display: none; } .ag-missing { font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: default; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index f11d18d66..ab5f5f643 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -489,13 +489,7 @@ function renderAgents() { // so the controls line up down the list const fields = el("div", "fields"); const wide = (f) => f.label === "model" || f.label === "large" || f.label === "executor" || f.label === "planner"; - // an effort or ultracode the model has none of (Claude Code on Haiku - // 4.5, ultracode short of xhigh) isn't drawn at all, nor are subagents - // with no model to go on, or a sign-in with no other to take (Claude - // Code's, until it runs through magpie where magpie takes any key), or - // a small model with none to pick (Snow CLI's, on a profile of the - // user's own) - // nor Aside's account with one account only (#1499) + // a field with nothing to pick and nothing set isn't drawn (#1499) const none = (f) => (f.key === "effort" || f.key === "ultracode" || f.label === "subagents" || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === AUTO_MODE || f.label === MEMORIES || f.label === "sign-in" || f.key === "small" || asideAccount(a, f)) && !f.options.length && !f.value; const shownFields = a.fields.filter((f) => !grouped(a, f) && !none(f) && !codexOwnSub(a, f) && !codexRowed(a, f) && !hermesBot(f)); const tiers = tierMenu(a); @@ -543,13 +537,10 @@ function renderAgents() { // command as its one control, in words const launchOnly = !!a.launch && !a.fields.length && !a.import; if (a.launch && !launchOnly) extras.append(launchButton(a)); - // the panel's opened row has no room for the settings: a line of its - // own opens them in a sheet; the window's opened row holds them - // (connectPanel) + // the panel's settings open in a sheet (connectPanel) if (mode === "panel" && agentPrefsOf(a)) fields.append(agentPrefsButton(a)); if (extras.childNodes.length) fields.append(extras); - // an app that takes magpie by a link of its own (Cindy) has nothing to - // pick: its row opens the link, and the app asks to add magpie + // an app taking magpie by a link (Cindy): its row opens it if (a.import && mode !== "panel") fields.append(importButton(a)); if (launchOnly && mode !== "panel") fields.append(launchSolo(a)); // the panel shows what's set as words, and a row's controls only @@ -624,8 +615,7 @@ function renderAgents() { if (ev.target.closest(".ag-open, .ag-handle, .ag-fix, .ag-show")) return; const open = panelOpenAgent !== a.id; panelOpenAgent = open ? a.id : null; - // the rows ease open and shut, and the panel's edge moves with them: - // it goes now to where they will be, over the same time and curve + // the panel's edge moves with the rows, on their curve let grow = open ? openBox.querySelector(".ag-body").offsetHeight : 0; for (const r of $("#agents").querySelectorAll(".row.agent.open")) { grow -= r.querySelector(".ag-in")?.offsetHeight || 0; @@ -643,9 +633,7 @@ function renderAgents() { openBox.addEventListener("transitionend", settle); }; } - // one hidden by hand gives its way back in words, rather than being a - // greyed row whose way back is its menu. One nothing is set on isn't - // hidden: setting something on it brings it up the list. + // one hidden by hand says its way back in words if (inFold && isHidden(a)) { row.classList.add("put-away"); const back = el("button", "ag-show"); @@ -655,10 +643,8 @@ function renderAgents() { back.onclick = (e) => { e.stopPropagation(); setAgentHidden(a, false); }; who.append(back); } - // its CLI uninstalled, its folder left behind (#2177, #2173): none of - // its settings is offered, as nothing would read them, only that it is - // gone; one still connected keeps its switch, which puts back what it - // had before magpie (its menu's Disconnect too) + // its CLI uninstalled (#2177, #2173): only that it is gone, and the + // switch of one still connected if (a.cliMissing) { row.classList.add("gone"); row.classList.remove("open"); @@ -676,9 +662,7 @@ function renderAgents() { if (a.wired && connectable(a)) row.append(connectSwitch(a)); return row; } - // on the name's own line, so the row keeps its height and the pickers - // their columns - // a row with 「接入」 says it on its line under the name instead + // on the name's line; a row with 「接入」 says it under the name const kind = mode !== "panel" ? connectKind(a) : ""; if (a.drift) { row.classList.add("drifted"); @@ -686,9 +670,9 @@ function renderAgents() { } // an app started before magpie's last change (the panel's row) else if (!kind && a.appRestart) who.append(appRestart(a)); - // the CLI's version, and an update when one is out (#202); the panel's - // name column has no room for it + // the CLI's version and its update (#202) if (mode !== "panel") who.append(cliTag(a)); + if (mode !== "panel" && isHere(a)) who.append(Object.assign(el("span", "ag-missing ag-here", t(HERE)), { title: t(HERE_TIP, { agent: a.name }) })); // which of magpie's models its lists show, on a line under the name if (mode !== "panel" && a.models && !kind) { const line = el("div", "ag-models-line"); @@ -3073,6 +3057,17 @@ function moveAgent(id, to) { saveArrangement([...ids, ...folded.map((a) => a.id)], hiddenIds(), []); } +const HERE = "This computer only", HERE_TIP = "{agent}'s picks (model, effort…) stay as set here: sync, a Restore and a backup file neither bring another computer's in nor take these to the others"; +const HERE_GLYPH = "M3.5 4.5h9v6h-9zM2 12.5h12"; +const isHere = (a) => !!state.settings?.agentsHere?.includes(a.id); +async function setAgentHere(a, on) { + try { + const s = await api("agents/here", { agent: a.id, on }); + state.settings = { ...state.settings, agentsHere: s.agentsHere || [] }; + renderAgents(); + status(t(on ? "{agent}'s picks stay on this computer" : "{agent}'s picks sync with your other computers again", { agent: a.name }), "ok", 2500); + } catch (e) { statusErr(e); } +} function setAgentHidden(a, hide) { const s = state.settings || {}; const { all } = arrangeAgents(); @@ -3896,6 +3891,8 @@ function openAgentMenu(anchor, a, inFold) { ...term, // its own settings, as the square on its row opens them ...(agentPrefsOf(a) ? [{ name: t("{agent} settings", { agent: a.name }), literal: true, icon: PREFS_GLYPH, sep: true, run: () => openAgentPrefs(a) }] : []), + // its picks kept off sync, as an MCP server can be (chenxiang0010) + ...(a.fields.length ? [{ name: HERE, icon: isHere(a) ? CHECK : HERE_GLYPH, sep: !agentPrefsOf(a), tip: t(HERE_TIP, { agent: a.name }), run: () => setAgentHere(a, !isHere(a)) }] : []), // for a config rewritten in a way magpie can't see: set it again anyway ...(reapply ? [{ name: "Apply again", icon: REAPPLY, sep: true, run: () => reapplyAgent(a) }] : []), ...(a.drift?.kind === "replaced" ? [{ name: "Keep current settings", icon: CHECK, run: () => keepAgent(a) }] : []), diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5633fafd9..4158e9af3 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2825,6 +2825,10 @@ const I18N = { "This backup's settings use {names}, which isn't signed in on this computer. A backup carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "这份备份的设置用到了 {names},但本机尚未登录。备份只带设置,不带登录信息:要在本机使用,请在 供应商 → 添加供应商 中登录;不在本机使用可忽略。", "{agent} {field}": "{agent} {field}", "Kept on this computer": "仅本机保留", + "This computer only": "只在这台电脑", + "{agent}'s picks (model, effort…) stay as set here: sync, a Restore and a backup file neither bring another computer's in nor take these to the others": "{agent} 的选择(模型、推理强度…)保持这台电脑所设:同步、恢复和备份文件都不会带入其他电脑的选择,也不会把这里的带给其他电脑", + "{agent}'s picks stay on this computer": "{agent} 的选择只在这台电脑生效", + "{agent}'s picks sync with your other computers again": "{agent} 的选择重新与你的其他电脑同步", "{fields}: set back here after a sync changed them, so they stay as picked here.": "{fields}:同步改动后在本机改了回来,所以保持本机的选择。", "Follow the others": "跟随其他电脑", "Your synced settings use {names}, which isn't signed in on this computer. Sync carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "同步过来的设置用到了 {names},但本机尚未登录。同步只带设置,不带登录信息:要在本机使用,请在 供应商 → 添加供应商 中登录;不在本机使用可忽略。", @@ -7245,6 +7249,10 @@ const I18N = { "This backup's settings use {names}, which isn't signed in on this computer. A backup carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "這份備份的設定用到了 {names},但本機尚未登入。備份只帶設定,不帶登入資訊:要在本機使用,請在 供應商 → 新增供應商 中登入;不在本機使用可忽略。", "{agent} {field}": "{agent} {field}", "Kept on this computer": "僅本機保留", + "This computer only": "只在這台電腦", + "{agent}'s picks (model, effort…) stay as set here: sync, a Restore and a backup file neither bring another computer's in nor take these to the others": "{agent} 的選擇(模型、推理強度…)維持這台電腦所設:同步、還原和備份檔都不會帶入其他電腦的選擇,也不會把這裡的帶到其他電腦", + "{agent}'s picks stay on this computer": "{agent} 的選擇只在這台電腦生效", + "{agent}'s picks sync with your other computers again": "{agent} 的選擇重新與你的其他電腦同步", "{fields}: set back here after a sync changed them, so they stay as picked here.": "{fields}:同步改動後在本機改了回來,所以保持本機的選擇。", "Follow the others": "跟隨其他電腦", "Your synced settings use {names}, which isn't signed in on this computer. Sync carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "同步過來的設定用到了 {names},但本機尚未登入。同步只帶設定,不帶登入資訊:要在本機使用,請在 供應商 → 新增供應商 中登入;不在本機使用可忽略。", @@ -11664,6 +11672,10 @@ const I18N = { "This backup's settings use {names}, which isn't signed in on this computer. A backup carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "このバックアップの設定は {names} を使っていますが、このコンピュータではまだサインインしていません。バックアップに含まれるのは設定だけで、サインイン情報は含まれません。ここで使うなら プロバイダ → プロバイダを追加 でサインインしてください。使わないなら何もしなくて構いません。", "{agent} {field}": "{agent} の{field}", "Kept on this computer": "このコンピュータだけで保持", + "This computer only": "このコンピュータだけ", + "{agent}'s picks (model, effort…) stay as set here: sync, a Restore and a backup file neither bring another computer's in nor take these to the others": "{agent} の選択(モデル、推論レベル…)はこのコンピュータでの設定のままです。同期、復元、バックアップファイルはほかのコンピュータの選択を持ち込まず、ここの選択もほかへ送りません", + "{agent}'s picks stay on this computer": "{agent} の選択はこのコンピュータだけで有効です", + "{agent}'s picks sync with your other computers again": "{agent} の選択はふたたびほかのコンピュータと同期されます", "{fields}: set back here after a sync changed them, so they stay as picked here.": "{fields}:同期で変わった後にここで元に戻したため、ここでの選択のままです。", "Follow the others": "ほかのコンピュータに合わせる", "Your synced settings use {names}, which isn't signed in on this computer. Sync carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "同期した設定は {names} を使っていますが、このコンピュータではまだサインインしていません。同期で届くのは設定だけで、サインイン情報は含まれません。ここで使うなら プロバイダ → プロバイダを追加 でサインインしてください。使わないなら何もしなくて構いません。", @@ -16094,6 +16106,10 @@ const I18N = { "This backup's settings use {names}, which isn't signed in on this computer. A backup carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "Die Einstellungen dieser Sicherung nutzen {names}, auf diesem Computer aber nicht angemeldet. Eine Sicherung enthält Einstellungen, keine Anmeldungen: Um es hier zu nutzen, melde dich unter Anbieter → Anbieter hinzufügen an; sonst ist nichts zu tun.", "{agent} {field}": "{agent}: {field}", "Kept on this computer": "Nur auf diesem Computer", + "This computer only": "Nur dieser Computer", + "{agent}'s picks (model, effort…) stay as set here: sync, a Restore and a backup file neither bring another computer's in nor take these to the others": "Die Auswahl für {agent} (Modell, Reasoning-Effort …) bleibt, wie sie hier eingestellt ist: Synchronisierung, Wiederherstellen und Sicherungsdateien übernehmen weder die eines anderen Computers noch bringen sie diese auf deine anderen Computer", + "{agent}'s picks stay on this computer": "Die Auswahl für {agent} gilt nur auf diesem Computer", + "{agent}'s picks sync with your other computers again": "Die Auswahl für {agent} wird wieder mit deinen anderen Computern synchronisiert", "{fields}: set back here after a sync changed them, so they stay as picked here.": "{fields}: nach einer Synchronisierung hier zurückgesetzt, daher bleibt die Auswahl dieses Computers.", "Follow the others": "Den anderen folgen", "Your synced settings use {names}, which isn't signed in on this computer. Sync carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "Deine synchronisierten Einstellungen nutzen {names}, auf diesem Computer aber nicht angemeldet. Die Synchronisierung überträgt Einstellungen, keine Anmeldungen: Um es hier zu nutzen, melde dich unter Anbieter → Anbieter hinzufügen an; sonst ist nichts zu tun.", diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index d06e1dafd..c2ef91807 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -3,7 +3,6 @@ magpie.strings({ zh: { "Show more ({n} left)": "显示更多(还有 {n} 个)", - "This computer only": "只在这台电脑", "Not through the router": "不经过路由", "Each agent is given its own entry for it, as with the MCP router off": "每个 Agent 各自有它的条目,和关掉 MCP 路由时一样", "Through the MCP router": "经过 MCP 路由", @@ -760,7 +759,6 @@ magpie.strings({ }, "zh-TW": { "Show more ({n} left)": "顯示更多(還有 {n} 個)", - "This computer only": "只在這台電腦", "Not through the router": "不經過路由", "Each agent is given its own entry for it, as with the MCP router off": "每個 Agent 各自有它的條目,和關掉 MCP 路由時一樣", "Through the MCP router": "經過 MCP 路由", @@ -1517,7 +1515,6 @@ magpie.strings({ }, ja: { "Show more ({n} left)": "さらに表示(残り {n} 件)", - "This computer only": "このコンピュータだけ", "Not through the router": "ルーターを通さない", "Each agent is given its own entry for it, as with the MCP router off": "各エージェントに個別のエントリを渡します(MCP ルーターがオフのときと同じ)", "Through the MCP router": "MCP ルーターを通す", @@ -2274,7 +2271,6 @@ magpie.strings({ }, de: { "Show more ({n} left)": "Mehr zeigen (noch {n})", - "This computer only": "Nur dieser Computer", "Not through the router": "Nicht über den Router", "Each agent is given its own entry for it, as with the MCP router off": "Jeder Agent bekommt einen eigenen Eintrag dafür, wie bei ausgeschaltetem MCP-Router", "Through the MCP router": "Über den MCP-Router", diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index e80c75d08..1f2358eda 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -110,6 +110,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { AgentOrder: []string{"codex"}, AgentsHidden: []string{"goose"}, AgentsShown: []string{"pi"}, + AgentsHere: []string{"codex"}, Visible: map[string][]string{"claude": {"anthropic"}}, HiddenModels: map[string][]string{"claude": {"p/m"}, "codex": {"p/n", "group/g"}}, DisabledModels: []string{"*fable*", "p/m"}, diff --git a/internal/gui/tests/agent-here.test.cjs b/internal/gui/tests/agent-here.test.cjs new file mode 100644 index 000000000..4eaf27b74 --- /dev/null +++ b/internal/gui/tests/agent-here.test.cjs @@ -0,0 +1,111 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An agent's picks can be kept to this computer, as an MCP server can +// (chenxiang0010 on Discord: 「agent当前选择的模型可不可以像mcp那样 只对当前设备生效」). +// The row's menu has This computer only: it posts agents/here, is ticked +// once on, and the window's row says it beside the version, in every +// language, in Chromium and WebKit, in the window and the tray panel. +// Off again, the tick and the words go. No backend: 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 CHECK = "m3.5 8.5 3 3 6-7"; + +function fixture(lang, posts) { + let here = []; + const settings = () => ({ lang, theme: "light", agentsHere: here }); + const state = () => ({ + agents: [{ + id: "codex", name: "Codex", path: "~/.codex/config.toml", icon: "codex", wired: true, + fields: [{ key: "model", label: "model", value: "glm-5.3-flash", options: [{ value: "glm-5.3-flash", label: "GLM-5.3-Flash", icon: "generic" }] }], + }], + profiles: [], settings: settings(), + }); + async function serve(route) { + const req = route.request(), url = new URL(req.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 === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state()); + if (url.pathname === "/api/agents/here") { + const b = req.postDataJSON(); + posts.push(b); + here = here.filter((x) => x !== b.agent); + if (b.on) here.push(b.agent); + return json(settings()); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/agents/cli") return json({ agents: { codex: { version: "0.166.0" } }, pending: false }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } }); + 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)]; + const body = await fs.readFile(file).catch(() => null); + await route.fulfill(body ? { body, contentType } : { status: 404, body: "" }); + } + return { serve }; +} + +const row = '.row.agent[data-id="codex"]'; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const where of ["window", "narrow", "panel"]) { + test(`${engine} ${lang} ${where}: an agent's picks kept to this computer`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const size = { window: { width: 1100, height: 700 }, narrow: { width: 640, height: 700 }, panel: { width: 360, height: 640 } }[where]; + const page = await browser.newPage({ viewport: size }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, posts).serve); + await page.goto("http://magpie.test/" + (where === "panel" ? "?mode=panel" : "")); + await page.locator(row).waitFor(); + const name = await page.evaluate(() => t("This computer only")); + if (lang !== "en") assert.notEqual(name, "This computer only", "not translated"); + const item = () => page.locator(".row-menu .rm-item", { hasText: name }); + const open = async () => { + await page.locator(row).click({ button: "right" }); + await item().waitFor(); + }; + const ticked = () => item().locator("path").getAttribute("d").then((d) => d === CHECK); + + await open(); + assert.equal(await ticked(), false, "ticked before it was turned on"); + await item().click(); + await page.waitForFunction(() => !document.querySelector(".row-menu")); + assert.deepEqual(posts, [{ agent: "codex", on: true }]); + const tag = page.locator(`${row} .ag-here`); + if (where === "panel") assert.equal(await tag.count(), 0, "the panel's row has no room for it"); + else { + await tag.waitFor(); + assert.equal(await tag.textContent(), name); + // the row keeps its width and the name stays whole + const fit = await page.locator(row).evaluate((r) => { + const n = r.querySelector(".who .name"); + return { over: r.scrollWidth - r.clientWidth, cut: n.scrollWidth - n.clientWidth }; + }); + assert.ok(fit.over <= 0 && fit.cut <= 0, `the row overflows: ${JSON.stringify(fit)}`); + } + await open(); + assert.equal(await ticked(), true, "not ticked once on"); + + // off again: the tick and the words go + await item().click(); + await page.waitForFunction(() => !document.querySelector(".row-menu")); + assert.deepEqual(posts.at(-1), { agent: "codex", on: false }); + await page.waitForFunction((sel) => !document.querySelector(sel), `${row} .ag-here`); + await open(); + assert.equal(await ticked(), false, "still ticked once off"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/settings/agents_here_test.go b/internal/settings/agents_here_test.go new file mode 100644 index 000000000..38aa72d22 --- /dev/null +++ b/internal/settings/agents_here_test.go @@ -0,0 +1,24 @@ +package settings + +import ( + "slices" + "testing" +) + +// The agents whose picks stay on this computer are this computer's own: +// another computer's list never comes in by sync, a Restore or a backup +// file (chenxiang0010 on Discord). +func TestAgentsHereIsThisComputers(t *testing.T) { + from := Settings{AgentsHere: []string{"codex"}, AgentsHidden: []string{"gemini"}} + from.KeepOwn(Settings{}) + if from.AgentsHere != nil { + t.Fatalf("another computer's kept agents came in: %v", from.AgentsHere) + } + if !slices.Equal(from.AgentsHidden, []string{"gemini"}) { + t.Fatal("the rest of the settings are synced") + } + from.KeepOwn(Settings{AgentsHere: []string{"claude"}}) + if !slices.Equal(from.AgentsHere, []string{"claude"}) { + t.Fatalf("this computer's own was lost: %v", from.AgentsHere) + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index f3a37e644..8ab8faac2 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -757,6 +757,11 @@ type Settings struct { AgentOrder []string `json:"agentOrder,omitempty"` AgentsHidden []string `json:"agentsHidden,omitempty"` AgentsShown []string `json:"agentsShown,omitempty"` + // AgentsHere are the agents, by id, whose picks (model, effort…) stay + // on this computer (chenxiang0010 on Discord), as an MCP server can: + // sync, a Restore and a backup file neither bring another computer's + // picks in for one nor take this computer's up. This computer's own. + AgentsHere []string `json:"agentsHere,omitempty"` // UsageOrder is how the Usage page's cards are listed, by provider id, // as they were dragged there; one it doesn't name follows in magpie's // own order. Only the page's: the order providers are tried in is the @@ -1344,6 +1349,7 @@ func (s *Settings) KeepOwn(cur Settings) { s.RedactModelOff, s.RedactModelAuto = cur.RedactModelOff, cur.RedactModelAuto s.ClaudeRunsMost = cur.ClaudeRunsMost s.RequestArchiveLocal, s.RequestArchiveLocalMB = cur.RequestArchiveLocal, cur.RequestArchiveLocalMB + s.AgentsHere = cur.AgentsHere } // Wires is ModelWires with the provider's own id of each model the user @@ -2150,6 +2156,7 @@ func saveOwn(s Settings, recording, reads bool) error { return err } s.AgentOrder, s.AgentsHidden, s.AgentsShown = ids(s.AgentOrder), ids(s.AgentsHidden), ids(s.AgentsShown) + s.AgentsHere = ids(s.AgentsHere) s.UsageOrder = ids(s.UsageOrder) s.PanelUsageHidden = ids(s.PanelUsageHidden) s.UsageAgentsHidden = ids(s.UsageAgentsHidden) diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index 8fb7ebd2a..d1336cf8c 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -223,7 +223,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err if _, sent := fields["maskAlert"]; !sent { in.MaskAlert = cur.MaskAlert } - in.AgentOrder, in.AgentsHidden, in.AgentsShown = cur.AgentOrder, cur.AgentsHidden, cur.AgentsShown + in.AgentOrder, in.AgentsHidden, in.AgentsShown, in.AgentsHere = cur.AgentOrder, cur.AgentsHidden, cur.AgentsShown, cur.AgentsHere in.Window, in.WindowMaximised, in.WindowAt = cur.Window, cur.WindowMaximised, cur.WindowAt // the window's own, as it was last resized and moved // and what other pages keep here: which models an agent is shown, and // everything the user said of a model anywhere else in the app, set on