agents: an agent's picks can be kept to this computer, as an MCP server can

chenxiang0010 on Discord: 「agent当前选择的模型可不可以像mcp那样 只对当前设备生效」.
Sync carries every agent's picks (model, effort...) between computers;
an MCP server has an opt-in "This computer only" that sync and backup
files never carry. Agents now have the same: the row's menu (right-click
or ...) has This computer only, off by default, so an upgrade changes no
pick on any computer.

- settings: AgentsHere, this computer's own (KeepOwn), and kept by a save
  of the Settings page (settingsapi.Apply), which doesn't send it.
- davsync: each kept agent adds "<id>.*" to the own set (withHere, isOwn),
  so a sync neither pushes its fields nor brings the server's; a Restore
  from the server leaves them. sync-state.json records the list as of the
  last sync (Here): hashes before a sync use it and after use the current
  list, so turning it on or off is no change on either side, and a changed
  list forces the sync past its early returns. Turned off, the next pick
  goes up again. Other agents still sync both ways; the implicit own
  fields (hayden4608) are unchanged.
- backup.Restore skips a kept agent in a backup file.
- gui: POST /api/agents/here; the row says "This computer only" beside
  the version (hidden in the tray panel and in a narrow row), menu ticks.
  Core words moved from the library plugin's i18n into core i18n
  (zh/zh-TW/ja/de). Comments in renderAgents cut to pay for it under the
  core budget (no raise).
- cli: the route is named under stage 3 (no command yet).
- docs/subsystems/sync-backup.md describes it.

Run on mote, at the base eb8b840dd (Go and the GUI files below) and again
at this head's base for internal/gui (core budget) and agent-here,
i18n-keys, agent-menu-label:
- go test -tags nogui ./internal/davsync ./internal/settings
  ./internal/backup ./internal/gui ./internal/settingsapi: ok
- go test ./internal/cli: ok but TestEveryRouteHasACommandOrIsNamed,
  red on main for POST /api/usage/checkin-account alone (#4826)
- GOOS=linux and GOOS=windows go vet ./...: ok; gofmt -l: clean
- GUI, chromium + webkit: agent-here (en/zh/zh-TW/ja/de x 1100/640/360),
  i18n-keys, sync-own-fields, mcp-local-server, agent-menu-label:
  90/90 ok
- the whole GUI suite: cut off at test 3783 by a session restart; the
  rest (key-* on) is still running at push. Reds seen so far, under
  three GUI suites at once on mote, none in an agent file: account-eye,
  balance-fix (Sub2API, /api/user/self), codex-auto-reset, context-map,
  editor-advanced-align; being checked at main and filed there.

Broken by hand, each red then restored:
- hereOf returns nil: TestAgentHereThroughSync "B's kept picks went up"
- backup.Restore's kept skip off: "B after a backup file"
- KeepOwn line dropped: TestAgentsHereIsThisComputers "another
  computer's kept agents came in"
- TestSettingsSaveKeepsWhatItDoesNotSend went red on this change before
  settingsapi kept AgentsHere (a Settings save would have dropped it).

Not tried: a real two-computer sync with real accounts; no CLI/TUI
command for the flag; Settings -> Sync doesn't list kept agents; WSL
agent ids (codex@wsl:...) only through the key format.
This commit is contained in:
yetone
2026-11-03 02:27:20 +08:00
parent 5ec2375688
commit 2ab9235711
17 changed files with 485 additions and 63 deletions
+17
View File
@@ -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 `<id>.*` 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
+13
View File
@@ -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
+1
View File
@@ -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
+146
View File
@@ -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")
}
+23 -14
View File
@@ -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 {
+59 -12
View File
@@ -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 "<agent>.*": 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}
}
}
+11 -6
View File
@@ -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
+30
View File
@@ -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
+2
View File
@@ -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; }
+23 -26
View File
@@ -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) }] : []),
+16
View File
@@ -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.",
@@ -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",
+1
View File
@@ -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"},
+111
View File
@@ -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, []);
});
}
}
}
+24
View File
@@ -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)
}
}
+7
View File
@@ -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)
+1 -1
View File
@@ -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