sync: an agent's model set back on a computer after a sync stays that computer's (hayden4608)

hayden4608 on Discord syncs two computers through GitHub, both with
Codex, and wants each one's Codex default model kept apart. Until now
the agents part carried every agent field ("codex.model", effort,
provider...) as one set: A's pick went up, B's sync brought it over B's,
B's pick went up again and A's next sync took it back. The two
computers fought, and the only way out was turning "agents' models"
off for every agent.

Now a sync that brings an agent field over this computer's value
records what it brought (Brought) and what it wrote over (Replaced,
only when that was picked here, not itself brought). If the user then
sets the field back to the value the sync replaced, the field is this
computer's own (Own): it leaves the hashes, a sync no longer brings it,
and a push keeps the server's value, so the other computer is not
changed either. Every other new pick is an ordinary pick and still goes
both ways, so a computer that changes the model for everyone (and
TestSyncAgentDefaults' reset) still reaches the rest. Nothing to set
up: the user's own act on this computer decides it, and a synced value
never overrides it again.

Settings > Sync lists the kept fields in one row ("Kept on this
computer: Codex model ...") with a "Follow the others" button
(davsync/follow), which brings the server's values on the next sync and
ends the keeping. Restore brings everything and ends it too. The row is
drawn only while sync and agents' models are on and something is kept;
plain row and button, no new layout. app.js grew 623 bytes; the budgets
are raised by that with a note.

Tests:
- internal/davsync/own_model_test.go TestOwnModelStaysOnEachComputer:
  two sandbox HOMEs (CODEX_HOME per computer) on the GitHub fixture.
  A picks a1, B joins and gets it, B picks b1 (goes up), A gets b1, A
  sets a1 back (own; the server keeps b1), B picks b2 + effort +
  provider (A gets effort and provider, keeps a1), A picks a2 and a
  Claude model (both go up, B gets them), A follows (gets b2), B's b3
  reaches A. TestNewPicksStillGoBothWays: alternating new picks always
  reach the other computer.
- internal/gui/tests/sync-own-fields.test.cjs: the row in en, zh,
  zh-TW, ja, de at 420px, no overflow, Follow posts once and the row
  goes, no scroll; no row without own fields or with agents off.

Broken by hand, each red: noticeOwn off (own_model_test:122); any pick
after a sync counts as own (TestSyncAgentDefaults and own test:106);
keepServersOwn off (:166); the bring ignoring Own (:146); withoutOwn
off in the hashes (:143, a notice); Follow off (:182).

Run at this head (rebased on 47173f593) on mote:
gofmt -l internal/davsync internal/gui clean; go vet ./..., GOOS=linux
go vet -tags nogui ./..., GOOS=windows go vet ./... ok; go test
./internal/davsync ok, ./internal/backup ok, ./internal/gui ok but
TestSettingsSaveKeepsWhatItDoesNotSend (#4514, red on main) and the
eleven real-window AppKit tests (dock, panel, tray, corners), which
time out on mote at origin/main 47173f593 too (#4125, #2645);
-run 'Budget|Sync|Backup|Settings' passes TestCoreScriptBudget.
GUI (node --test): sync-own-fields, sync-note-show, github-sync,
s3-sync, sync-other-kind, sync-not-backup, sync-auto-restore,
sync-usage-error, i18n-keys. Chromium on mote: all pass but
sync-not-backup and sync-usage-error, whose chromium.launch({channel:
"chromium"}) segfaults on mote at origin/main 47173f593 too; on the
WSL box (magpie-desktop) they pass, 25 of 25 with sync-own-fields.
WebKit on mote hangs on launch for every file, untouched ones too; on
WSL all nine files ran: 49 of 52, the reds being i18n-keys' "a
plugin's words are its own" (#4524, red on main) and the first
page.goto of sync-own-fields and sync-note-show at 5s under nine
files at once, which pass run alone (9 of 9).
Red on main and not from this change: TestSettingsSaveKeepsWhatItDoesNotSend
(#4514), i18n-keys "Unmarked" (#4524).

Not tried: a real GitHub repo and a real Codex on two computers; the
CLI has no follow command (only the GUI and Restore end the keeping);
Undo after a Restore doesn't bring Own back.
This commit is contained in:
yetone
2026-10-31 18:01:04 +08:00
parent 47173f593a
commit a511b11d8b
11 changed files with 717 additions and 17 deletions
+7
View File
@@ -3032,6 +3032,13 @@ ever stores ciphertext. Each machine writes only over the version it read (a
conditional write), so an update that another machine made in between is
merged rather than lost.
A change to an agent's model (or any of its fields) on one machine reaches
the others. When sync changes one on a machine and you set it back there,
that machine keeps its own: the other machines' picks no longer change it
there, and its picks stay there, while everything else keeps syncing.
Settings → Sync lists those fields under **Kept on this computer**, and
**Follow the others** takes the synced value again.
```sh
magpie webdav on https://dav.jianguoyun.com/dav/ user=me@example.com
magpie s3 on s3://my-bucket/magpie endpoint=https://<account>.r2.cloudflarestorage.com access-key-id=…
+18
View File
@@ -61,6 +61,24 @@ this computer's values for a provider it has, and brings a new one without
`KeepLoginAs`, an account signed in on the other computer; `hashes` blanks
all three (`TestMirrorKeepsKeepLogin`, `TestKeepLoginIsNoChange`).
The agents part keeps a computer's own pick the same way, field by field
(hayden4608 on Discord: two computers on one GitHub sync, each wanting its own
Codex model, set each other's on every sync). Each field a sync changes here
is recorded in sync-state.json (`Brought`), with the value it wrote over when
that value was picked here, not brought by an earlier sync (`Replaced`). A
field the user then sets back to that value is this computer's own (`Own`,
[`noticeOwn`](../../internal/davsync/own.go)). Setting a new value is a pick
like any other: it goes up, so a change made on either computer still reaches
the other. For an own field, `hashesOwn` leaves it out, so picking it is no
change to push and the server's value is no change to bring; `bringAgents`
brings the agents' other fields and puts an own field back if a provider moved
it; `keepServersOwn` keeps the server's value of it in what this computer
pushes. Settings → Sync lists the own fields under Kept on this computer, with
**Follow the others** (`davsync.Follow`): the next sync brings the server's
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`).
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
+77 -11
View File
@@ -212,6 +212,17 @@ type state struct {
// Blind is the last write, when the server didn't check the version
// it went over (version.Blind), until a sync reads it back
Blind *blind `json:"blind,omitempty"`
// Brought is each agent field's value as the last sync that changed it
// here wrote it, Replaced the value picked here that it wrote over,
// and Own the fields put back to that value since: this computer's
// own, never brought in or taken up (own.go). Follow is Settings
// asking for the own ones to follow the others again, on the next
// sync. They are this computer's choices, kept when sync moves to
// another server.
Brought map[string]string `json:"brought,omitempty"`
Replaced map[string]string `json:"replaced,omitempty"`
Own map[string]bool `json:"own,omitempty"`
Follow bool `json:"follow,omitempty"`
}
// blind is a write the server didn't check: the file it wrote (Sum), and
@@ -475,6 +486,9 @@ type View struct {
// account here: sync carries no sign-in, so each is to be signed in to
// on this computer before it is listed
SignIn []string `json:"signIn,omitempty"`
// Own is the agent fields picked on this computer after a sync set
// them, which sync leaves as they are here (own.go)
Own []OwnField `json:"own,omitempty"`
}
// OtherView is the other kind's server as the Settings page shows it.
@@ -516,6 +530,9 @@ func Status() View {
}
}
v.Usage = c.Usage
if c.Agents {
v.Own = ownFields(st)
}
if o := c.Other; o != nil {
v.Other = &OtherView{Kind: strings.ToLower(o.config().Kind()), URL: o.URL, User: o.User, PasswordSet: o.Password != "",
Endpoint: o.Endpoint, Region: o.Region, PathStyle: o.PathStyle, Branch: o.Branch}
@@ -664,7 +681,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)}
st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Follow: st.Follow}
}
err = syncOnce(ctx, c, &st)
if errors.Is(err, errChanged) { // another computer got in between: again, over its version
@@ -1073,9 +1090,25 @@ func syncOnce(ctx context.Context, c Config, st *state) error {
if err != nil {
return err
}
L := hashes(local)
// An agent field picked here after a sync set it is this computer's
// own from now on (own.go). prev is the own fields the last sync's
// hashes left out, so this one's compare with them alike: a field
// 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)
if c.Agents {
noticeOwn(st, local.Agents)
}
own, after := st.Own, st.Own
follow := st.Follow && len(own) > 0 && c.Agents
if follow {
after = nil
}
st.Follow = false
L := hashesOwn(local, prev)
if unchanged {
if maps.Equal(L, st.Local) {
if maps.Equal(L, st.Local) && !follow {
return nil // nothing changed on either side
}
// changed here: merged with the server's file as last seen, or,
@@ -1100,7 +1133,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, hashes(b)
st.Sum, st.Server, st.Remote = sum(sealed), v, hashesOwn(b, after)
if v.Blind {
were.Sum = st.Sum
st.Blind = &were
@@ -1112,10 +1145,11 @@ func syncOnce(ctx context.Context, c Config, st *state) error {
if err := push(local, "", blind{}); err != nil {
return err
}
st.Local = L
st.Own = after
st.Local = hashesOwn(local, after)
return nil
}
if sum(data) == st.Sum && maps.Equal(L, st.Local) {
if sum(data) == st.Sum && maps.Equal(L, st.Local) && !follow {
st.Server = ver
remember(data)
return nil // nothing changed on either side
@@ -1177,7 +1211,10 @@ func syncOnce(ctx context.Context, c Config, st *state) error {
data = good
rebuilt = true // push the merged result even if it matches the cached copy
}
R := hashes(remote)
// 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)
first := st.Local == nil
merged := remote
var bringIn, here, there []string
@@ -1194,6 +1231,9 @@ func syncOnce(ctx context.Context, c Config, st *state) error {
switch {
case lc && !rc:
take(&merged, local, p)
if p == "agents" {
keepServersOwn(&merged, remote, own)
}
case rc && !lc:
if first && p == "settings" {
keepUnseenGatewayKeys(&remote, local)
@@ -1205,6 +1245,9 @@ func syncOnce(ctx context.Context, c Config, st *state) error {
case lc && rc: // both: the newer stays
if changed(p, c.Keys).After(remote.Created) {
take(&merged, local, p)
if p == "agents" {
keepServersOwn(&merged, remote, own)
}
there = append(there, p)
} else {
bringIn = append(bringIn, p)
@@ -1228,20 +1271,43 @@ func syncOnce(ctx context.Context, c Config, st *state) error {
saved = dir
}
for _, p := range bringIn {
if p == "agents" {
got, err := bringAgents(remote.Agents, after)
broughtIn(st, got)
if err != nil {
return fmt.Errorf("bringing in the %s: %w", p, err)
}
continue
}
if err := bring(remote, p); err != nil {
return fmt.Errorf("bringing in the %s: %w", p, err)
}
}
if follow && c.Agents && !slices.Contains(bringIn, "agents") {
// the fields given back to sync take the server's values, the
// agents' other fields left as they are here
fields := map[string]string{}
for k := range own {
if v, ok := remote.Agents[k]; ok {
fields[k] = v
}
}
got, err := bringAgents(fields, nil)
broughtIn(st, got)
if err != nil {
return fmt.Errorf("bringing in the agents: %w", err)
}
}
st.Own, R = after, Rafter
// the server's file is in; what is pushed next counts as changed here
// until the push is done
now := L
if len(bringIn) > 0 {
if len(bringIn) > 0 || follow {
if local, err = collect(c); err != nil {
return err
}
now = hashes(local)
}
M, pending := hashes(merged), map[string]string{}
now := hashesOwn(local, after)
M, pending := hashesOwn(merged, after), map[string]string{}
for _, p := range Parts {
pending[p] = now[p]
if M[p] != R[p] && st.Local != nil {
+208
View File
@@ -0,0 +1,208 @@
package davsync
import (
"context"
"maps"
"slices"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/backup"
"github.com/yetone/magpie/internal/profile"
)
// An agent's field that sync wrote over a value picked on this computer,
// and that the user then puts back, is this computer's own (hayden4608 on
// Discord: two computers on one GitHub sync, each wanting its own Codex
// model, set each other's every sync). Putting the value back is what says
// it: a new value picked after a sync still goes up, as before, so a
// change made on any computer still reaches the others. From then on sync
// neither brings an own field in nor takes this computer's value up, while
// the agent's other fields, and every other part, still sync.
//
// The state is this computer's alone (sync-state.json): Brought is each
// field's value as the last sync that changed it here wrote it, Replaced
// the value picked here that it wrote over, if it was one (not one an
// earlier sync brought), and Own the fields put back since. Follow, from
// the Settings page, gives the own fields back to sync: the next sync
// brings the server's values in.
// noticeOwn makes own each field sync wrote over a pick, put back to that
// pick here since. Another value picked since is a pick like any other: it
// goes up, and what sync brought before is forgotten.
func noticeOwn(st *state, here map[string]string) {
for k, v := range st.Brought {
now, ok := here[k]
if !ok || now == v { // the agent isn't here now, or the field is as sync left it
continue
}
if was, ok := st.Replaced[k]; ok && now == was {
if st.Own == nil {
st.Own = map[string]bool{}
}
st.Own[k] = true
}
delete(st.Brought, k)
delete(st.Replaced, k)
}
}
// withoutOwn is b without this computer's own agent fields: what is
// hashed to tell a change, so a pick of an own field is no change to push
// and the server's value of one is no change to bring.
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)
}
return b
}
// 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))
}
// keepServersOwn puts the server's values of this computer's own fields
// back into the agents a sync takes up from here: they never go up.
func keepServersOwn(merged *backup.Bundle, remote backup.Bundle, own map[string]bool) {
if len(own) == 0 {
return
}
a := maps.Clone(merged.Agents)
if a == nil {
a = map[string]string{}
}
for k := range own {
if v, ok := remote.Agents[k]; ok {
a[k] = v
} else {
delete(a, k)
}
}
merged.Agents = a
}
// brought is a field a bring changed here: the value it wrote over, and
// the value it reads now.
type brought struct{ was, now string }
// bringAgents puts fields (the server's agents) in here, but for keep's,
// this computer's own. An own field that another's change moved with it
// (a provider re-settling the model behind it) is put back. It returns
// 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)
}
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 {
back[k] = v
}
}
if len(back) > 0 {
if _, berr := profile.ApplyFields(back); berr != nil && err == nil {
err = berr
}
after = profile.Fields()
}
got := map[string]brought{}
for k, v := range after {
if !keep[k] && before[k] != v {
got[k] = brought{before[k], v}
}
}
return got, err
}
// broughtIn records what a bring set here, and what it wrote over when
// that was picked here rather than brought by an earlier sync.
func broughtIn(st *state, got map[string]brought) {
if len(got) == 0 {
return
}
if st.Brought == nil {
st.Brought = map[string]string{}
}
if st.Replaced == nil {
st.Replaced = map[string]string{}
}
for k, b := range got {
if last, ok := st.Brought[k]; ok && last == b.was {
delete(st.Replaced, k) // sync's own value, written over by sync
} else {
st.Replaced[k] = b.was
}
st.Brought[k] = b.now
}
}
// OwnField is an agent field kept on this computer, as Settings names it.
type OwnField struct {
Agent string `json:"agent"` // the agent's name
Field string `json:"field"` // the field's label: model, effort…
}
// ownFields names st's own fields, by agent then field.
func ownFields(st state) []OwnField {
if len(st.Own) == 0 {
return nil
}
agents := map[string]*agent.Agent{}
for _, a := range agent.Detected() {
agents[a.ID] = a
}
keys := slices.Sorted(maps.Keys(st.Own))
out := make([]OwnField, 0, len(keys))
for _, k := range keys {
id, field := splitField(k)
f := OwnField{Agent: id, Field: field}
if a := agents[id]; a != nil {
f.Agent = a.Name
if x := a.Field(field); x != nil && x.Label != "" {
f.Field = x.Label
}
}
out = append(out, f)
}
return out
}
// splitField is a field's agent and key: the last dot, as a WSL distro's
// name may have one (codex@wsl:Ubuntu-24.04.model).
func splitField(k string) (string, string) {
for i := len(k) - 1; i >= 0; i-- {
if k[i] == '.' {
return k[:i], k[i+1:]
}
}
return k, ""
}
// Follow gives this computer's own agent fields back to sync, and syncs:
// the server's values come in, and the others' picks follow again.
func Follow(ctx context.Context) error {
err := locked(func() error {
if _, ok := Load(); !ok {
return ErrOff
}
st := loadState()
if len(st.Own) == 0 {
return nil
}
st.Follow = true
saveState(st)
return nil
})
if err != nil {
return err
}
return SyncNow(ctx)
}
+251
View File
@@ -0,0 +1,251 @@
package davsync
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/backup"
"github.com/yetone/magpie/internal/profile"
"github.com/yetone/magpie/internal/provider"
)
// codexPick writes Codex's model and effort into this computer's
// config.toml, as a pick in Codex or in magpie does.
func codexPick(t *testing.T, model, effort string) {
t.Helper()
dir := os.Getenv("CODEX_HOME")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
body := "model = \"" + model + "\"\nmodel_reasoning_effort = \"" + effort + "\"\n"
if err := os.WriteFile(filepath.Join(dir, "config.toml"), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
func codexHere() (string, string) {
f := profile.Fields()
return f["codex.model"], f["codex.effort"]
}
// Two computers on one GitHub sync, each wanting its own Codex model
// (hayden4608 on Discord). A sets its model and syncs; B picks another and
// syncs, which brings B's over A's at A's next sync, as before. A puts its
// own back: from then on it stays A's, neither B's later picks come in nor
// A's own go up. The rest still syncs both ways: Codex's effort, Claude
// Code's model, a provider. Follow the others gives it back to sync.
func TestOwnModelStaysOnEachComputer(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
}
own := func(t *testing.T, want int) {
t.Helper()
v := Status()
if len(v.Own) != want {
t.Fatalf("own fields: %+v, want %d", v.Own, want)
}
if want == 1 && (!strings.Contains(v.Own[0].Agent, "Codex") || v.Own[0].Field != "model") {
t.Fatalf("own fields: %+v, want Codex's model", v.Own)
}
}
a, b := newComputer(t), newComputer(t)
// A sets its model and syncs
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 joins: A's model comes in, as before (a joining computer's own
// setup is saved aside, with a notice)
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)
}
if m, _ := codexHere(); m != "gpt-a1" {
t.Fatalf("B joining: model %q, want A's", m)
}
// B picks a new model: it goes up, and comes in at A, as before
codexPick(t, "gpt-b1", "low")
now(t)
if m := server(t)["codex.model"]; m != "gpt-b1" {
t.Fatalf("B's pick didn't go up: %q", m)
}
own(t, 0)
a.use(t)
now(t)
if m, _ := codexHere(); m != "gpt-b1" {
t.Fatalf("A after B's pick: %q", m)
}
// A puts its own back: it stays on A, the server keeps B's
codexPick(t, "gpt-a1", "low")
now(t)
if m, _ := codexHere(); m != "gpt-a1" {
t.Fatalf("A's own: %q", m)
}
if m := server(t)["codex.model"]; m != "gpt-b1" {
t.Fatalf("A's own went up: %q", m)
}
own(t, 1)
// B picks again, with another effort, and adds a provider
b.use(t)
now(t)
codexPick(t, "gpt-b2", "high")
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "fixture-provider-key"}); err != nil {
t.Fatal(err)
}
now(t)
if m := server(t)["codex.model"]; m != "gpt-b2" {
t.Fatalf("B's pick didn't go up: %q", m)
}
// A picks its own again before it syncs: a change of its own is no
// change on both sides, so B's effort and provider come in with no
// notice, and A's model stays
a.use(t)
codexPick(t, "gpt-a1b", "low")
now(t)
m, e := codexHere()
if m != "gpt-a1b" {
t.Fatalf("B's later pick came over A's own: %q", m)
}
if e != "high" {
t.Fatalf("B's effort didn't come in: %q", e)
}
if !slices.Equal(ids(), []string{"deepseek=fixture-provider-key"}) {
t.Fatalf("B's provider didn't come in: %v", ids())
}
// A picks again, a new effort too, and Claude Code's model: those go
// up, Codex's model stays A's
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-b2" || got["codex.effort"] != "medium" || got["claude.model"] != "claude-from-a" {
t.Fatalf("A's second pick: server has %q %q %q", got["codex.model"], got["codex.effort"], got["claude.model"])
}
own(t, 1)
b.use(t)
now(t)
if m, e := codexHere(); m != "gpt-b2" || e != "medium" || profile.Fields()["claude.model"] != "claude-from-a" {
t.Fatalf("B after A's second pick: %q %q %q", m, e, profile.Fields()["claude.model"])
}
own(t, 0)
// A follows the others again: the server's model comes in
a.use(t)
if err := Follow(ctx); err != nil {
t.Fatal(err)
}
if m, _ := codexHere(); m != "gpt-b2" {
t.Fatalf("A following: %q", m)
}
if v := Status(); len(v.Own) != 0 || v.Notice != nil {
t.Fatalf("A following: own %+v, notice %+v", v.Own, v.Notice)
}
// and B's next pick reaches A again
b.use(t)
codexPick(t, "gpt-b3", "medium")
now(t)
a.use(t)
now(t)
if m, _ := codexHere(); m != "gpt-b3" {
t.Fatalf("A after following: %q", m)
}
}
// New picks still go both ways: a computer that picks a model it never had
// changes it for the others, however often the two take turns. Only
// putting back the value sync wrote over keeps one.
func TestNewPicksStillGoBothWays(t *testing.T) {
newGithubFixture(t)
ctx := context.Background()
c := githubConfig()
a, b := newComputer(t), newComputer(t)
a.use(t)
codexPick(t, "gpt-1", "low")
if m, _ := codexHere(); m != "gpt-1" {
t.Skipf("Codex isn't seen here: %v", profile.Fields())
}
if err := Configure(c); err != nil {
t.Fatal(err)
}
joined := map[computer]bool{a: true}
for _, step := range []struct {
c computer
pick string
model string
}{
{a, "", "gpt-1"},
{b, "", "gpt-1"},
{b, "gpt-2", "gpt-2"},
{a, "", "gpt-2"},
{a, "gpt-3", "gpt-3"},
{b, "", "gpt-3"},
{b, "gpt-4", "gpt-4"},
{a, "", "gpt-4"},
{a, "gpt-5", "gpt-5"},
{b, "", "gpt-5"},
} {
step.c.use(t)
if !joined[step.c] {
joined[step.c] = true
if err := Configure(c); err != nil {
t.Fatal(err)
}
}
if step.pick != "" {
codexPick(t, step.pick, "low")
}
if err := Now(ctx); err != nil {
t.Fatal(err)
}
if m, _ := codexHere(); m != step.model {
t.Fatalf("model %q, want %q", m, step.model)
}
if v := Status(); len(v.Own) != 0 {
t.Fatalf("own: %+v", v.Own)
}
}
}
+15 -4
View File
@@ -85,7 +85,7 @@ func Restore(ctx context.Context) ([]string, error) {
}
st := loadState()
if st.Key != stateKey(c) {
st = state{Key: stateKey(c)}
st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own}
}
if len(brought) > 0 {
kept, err := keepHere(c)
@@ -93,6 +93,17 @@ func Restore(ctx context.Context) ([]string, error) {
return fmt.Errorf("keeping this computer's setup before restoring: %w", err)
}
for _, p := range brought {
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)
broughtIn(&st, got)
st.Own, st.Follow = nil, false
if err != nil {
return fmt.Errorf("bringing in the %s: %w", p, err)
}
continue
}
if err := bring(remote, p); err != nil {
return fmt.Errorf("bringing in the %s: %w", p, err)
}
@@ -105,7 +116,7 @@ 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 = hashes(local), R, sum(data), ver
st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, st.Own), hashesOwn(remote, st.Own), sum(data), ver
st.Blind = nil // what is here now is what the server has
remember(data)
st.Last, st.Error = time.Now(), ""
@@ -175,10 +186,10 @@ func Upload(ctx context.Context) error {
}
st := loadState()
if st.Key != stateKey(c) {
st = state{Key: stateKey(c)}
st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own}
}
// as the first sync to an empty server leaves it
st.Local, st.Remote, st.Sum, st.Server = hashes(local), hashes(b), sum(sealed), v
st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, st.Own), hashesOwn(b, st.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
+10
View File
@@ -20016,6 +20016,16 @@ async function renderSync(v) {
row(t("Upload this computer's setup"), t("It replaces the file on the server. That file is kept in the sync folder first."),
btn(t("Upload…"), () => askUpload(v.serverFile)));
}
// agent fields set back here after a sync changed them (hayden4608)
if (v.on && v.agents !== false && v.own?.length) {
const fields = v.own.map((f) => t("{agent} {field}", { agent: f.agent, field: t(f.field) })).join(t(", "));
row(t("Kept on this computer"), t("{fields}: set back here after a sync changed them, so they stay as picked here.", { fields }),
btn(t("Follow the others"), async (e) => {
e.target.classList.add("busy");
renderSync(await api("davsync/follow", {}).catch((x) => ({ ...v, error: x.message })));
refreshAfterSync();
})).classList.add("wraps", "sync-own");
}
if (v.notice) {
const n = v.notice, r = el("div", "row pref sync-note");
const lines = [];
+16
View File
@@ -2695,6 +2695,10 @@ const I18N = {
"Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed": "供应商:新增 {added} 个,替换 {replaced} 个;Profile {profiles} 个;agent 设置改动 {agents} 项",
"Needs a key: {names}": "需要填写 Key:{names}",
"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": "仅本机保留",
"{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},但本机尚未登录。同步只带设置,不带登录信息:要在本机使用,请在 供应商 → 添加供应商 中登录;不在本机使用可忽略。",
"Plugins added: {names}": "已添加插件:{names}",
"Couldn't add the plugin {spec}: {error}": "无法添加插件 {spec}:{error}",
@@ -6939,6 +6943,10 @@ const I18N = {
"Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed": "供應商:新增 {added} 個,替換 {replaced} 個;Profile {profiles} 個;agent 設定改動 {agents} 項",
"Needs a key: {names}": "需要填寫 Key:{names}",
"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": "僅本機保留",
"{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},但本機尚未登入。同步只帶設定,不帶登入資訊:要在本機使用,請在 供應商 → 新增供應商 中登入;不在本機使用可忽略。",
"Plugins added: {names}": "已新增外掛:{names}",
"Couldn't add the plugin {spec}: {error}": "無法新增外掛 {spec}:{error}",
@@ -11182,6 +11190,10 @@ const I18N = {
"Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed": "プロバイダ:{added} 件追加、{replaced} 件置換。プロファイル {profiles} 件。エージェント設定 {agents} 件を変更",
"Needs a key: {names}": "キーが必要です:{names}",
"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": "このコンピュータだけで保持",
"{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} を使っていますが、このコンピュータではまだサインインしていません。同期で届くのは設定だけで、サインイン情報は含まれません。ここで使うなら プロバイダ → プロバイダを追加 でサインインしてください。使わないなら何もしなくて構いません。",
"Plugins added: {names}": "追加したプラグイン:{names}",
"Couldn't add the plugin {spec}: {error}": "プラグイン {spec} を追加できませんでした:{error}",
@@ -15436,6 +15448,10 @@ const I18N = {
"Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed": "Anbieter: {added} hinzugefügt, {replaced} ersetzt; {profiles} Profile; {agents} Agenteneinstellungen geändert",
"Needs a key: {names}": "Schlüssel erforderlich: {names}",
"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",
"{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.",
"Plugins added: {names}": "Hinzugefügte Erweiterungen: {names}",
"Couldn't add the plugin {spec}: {error}": "Die Erweiterung {spec} konnte nicht hinzugefügt werden: {error}",
+2
View File
@@ -127,6 +127,8 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
_, err = davsync.Undo()
case "upload": // this computer's setup over a server file that isn't a backup, kept first
err = davsync.Upload(ctx)
case "follow": // the agent fields kept on this computer follow the others again
err = busy(davsync.Follow(ctx))
case "reveal":
err = w.OpenFolder(filepath.Join(settings.Dir(), "sync"))
default:
File diff suppressed because one or more lines are too long
+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 field set back on a computer after a sync changed it stays that
// computer's (hayden4608 on Discord: two computers on one GitHub sync, each
// wanting its own Codex model). Settings → Sync names the fields kept here,
// in the page's language, and Follow the others gives them back to sync:
// it asks the server once, and the row goes with the fields. A sync with no
// such fields, or with agents' models off, shows no row. In every language,
// Chromium and WebKit, at a narrow width with nothing wider than the page.
// The API is faked; nothing is synced.
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 { openPart } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
function serve(lang, sync, posts) {
const settings = {
theme: "light", lang, tray: "panel", version: "test", dir: "/tmp/magpie",
gateway: "http://127.0.0.1:3425", visionModels: [], imageGenModels: [],
fx: { rate: 7.2, stale: false },
};
return async (route) => {
const request = route.request();
const pathname = new URL(request.url()).pathname;
const json = (data) => route.fulfill({ json: data });
if (pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (pathname === "/api/settings") return json(settings);
if (pathname === "/api/usage/quotas") return json([]);
if (pathname === "/api/groups") return json({ groups: [], models: [] });
if (pathname === "/api/plugins") return json({ plugins: [] });
if (pathname === "/api/davsync") return json(sync);
if (pathname === "/api/davsync/follow") {
posts.push("follow");
const { own, ...rest } = sync;
return json(rest);
}
if (pathname.startsWith("/api/")) return json({});
const file = path.join(assets, pathname === "/" ? "index.html" : pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
return route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const words = {
en: { title: "Kept on this computer", follow: "Follow the others", field: "Codex model" },
zh: { title: "仅本机保留", follow: "跟随其他电脑", field: "Codex 模型" },
"zh-TW": { title: "僅本機保留", follow: "跟隨其他電腦", field: "Codex 模型" },
ja: { title: "このコンピュータだけで保持", follow: "ほかのコンピュータに合わせる", field: "Codex のモデル" },
de: { title: "Nur auf diesem Computer", follow: "Den anderen folgen", field: "Codex: Modell" },
};
const base = () => ({ on: true, kind: "github", url: "github://alice/private/team", passwordSet: true, passphraseSet: true,
keys: true, agents: true, library: true, auto: 3, last: new Date().toISOString() });
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
const open = async (t, lang, sync, posts, width = 900) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, sync, posts));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-sync-own-fields.png`), fullPage: true });
}
await browser.close();
});
page.setDefaultTimeout(5000);
await page.goto("http://magpie.test/");
await page.locator("#prefs").click();
await openPart(page, "sync");
await page.locator("#syncList .row").first().waitFor({ state: "visible" });
return { page, errors };
};
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: the fields kept on this computer are named, and follow the others on a click`, async (t) => {
const posts = [];
const sync = { ...base(), own: [{ agent: "Codex", field: "model" }] };
const { page, errors } = await open(t, lang, sync, posts, 420);
const row = page.locator("#syncList .row", { has: page.locator(".sync-own") });
await row.waitFor({ state: "visible" });
assert.equal((await row.locator(".name").textContent()).trim(), w.title);
assert.ok((await row.locator(".sync-own").textContent()).includes(w.field), `names ${w.field}`);
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert.ok(over <= 0, `nothing wider than the page (${over}px over)`);
const y = await page.evaluate(() => document.scrollingElement.scrollTop);
await row.getByRole("button", { name: w.follow, exact: true }).click();
await row.waitFor({ state: "detached" });
assert.deepEqual(posts, ["follow"], "asked the server once");
assert.equal(await page.evaluate(() => document.scrollingElement.scrollTop), y, "the click moved nothing");
assert.deepEqual(errors, [], "nothing threw");
});
}
for (const [name, sync] of [["no fields kept", base()], ["agents' models off", { ...base(), agents: false, own: [{ agent: "Codex", field: "model" }] }]]) {
test(`${engine}: ${name} shows no row for them`, async (t) => {
const { page, errors } = await open(t, "en", sync, []);
assert.equal(await page.locator("#syncList .sync-own").count(), 0);
assert.equal(await page.getByText("Kept on this computer").count(), 0);
assert.deepEqual(errors, [], "nothing threw");
});
}
}