diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index aa1667624..cbb505876 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -414,6 +414,17 @@ switch that anyone with the file and the passphrase can use those accounts. form says so (`TestMergeSignInsTheLaterRenewedStays`, `TestMergeSignInsRemovedOnlyWhenTheOtherSideRemovedIt`, `TestApplySignInsKeepsWhatChangedSinceTheMerge`, `sync-signins.test.cjs`). +- **Left out here** (`Config.SignInsExcept`, provider ids; Ethereal499 on + X): under the Sign-ins tick, **Not synced** picks subscriptions whose + sign-ins stay on this computer. [`SignIns.Except`](../../internal/provider/signins_except.go) + takes them out of what `collect` sends, and out of the server's before + `MergeSignIns`, the preview and a Restore, so the server's are never put + in and none here is removed for being missing there. `syncOnce` puts the + server's ones back with `With`, so the computers that sync them keep + them. An id names its `-plugin` sign-ins too. The choice is this + computer's: the setup text doesn't carry it, and a setup without it + leaves nothing out (`TestSyncSignInsExcept`, `TestSignInsExcept`, + `sync-signins-except.test.cjs`; `magpie webdav set sign-ins-except=claude`). ## GitHub constraints and errors diff --git a/internal/cli/webdav_cli.go b/internal/cli/webdav_cli.go index 2f0a7ddd3..622d2cb4e 100644 --- a/internal/cli/webdav_cli.go +++ b/internal/cli/webdav_cli.go @@ -7,6 +7,7 @@ import ( "net/url" "os" "path/filepath" + "slices" "strings" "time" @@ -59,6 +60,10 @@ const webdavUsage = `usage: passphrase, so a computer that syncs is signed in without signing in again. Off unless set. Anyone with the passphrase and the server's file can use those accounts. An account used on two computers may be signed out on one when the other renews it + sign-ins-except + the subscriptions whose sign-ins stay on this computer, by id (claude,codex): theirs + here never go up, the server's never come in, and nothing here is taken away; + none: every one syncs first sync on a computer that had its own setup, each part that differs becomes the server's; what was here is kept in the sync folder beside magpie's files, and magpie webdav says so moving magpie webdav on with S3 sync on moves sync to the folder; the bucket, endpoint, access key @@ -115,6 +120,10 @@ const s3Usage = `usage: passphrase, so a computer that syncs is signed in without signing in again. Off unless set. Anyone with the passphrase and the server's file can use those accounts. An account used on two computers may be signed out on one when the other renews it + sign-ins-except + the subscriptions whose sign-ins stay on this computer, by id (claude,codex): theirs + here never go up, the server's never come in, and nothing here is taken away; + none: every one syncs moving magpie s3 on with WebDAV sync on moves sync to the bucket; the WebDAV address, user and password are kept, and magpie webdav on alone moves back to them @@ -150,6 +159,8 @@ const githubUsage = `usage: passphrase the same on every computer; GitHub only ever receives the sealed file. sign-ins yes: the subscriptions' accounts and the plugins' sign-ins go too, sealed with the passphrase. Off unless set + sign-ins-except + the subscriptions whose sign-ins stay on this computer, by id (claude,codex) providers, settings, profiles, agents, library, memory no: that part stays as it is on each computer, never brought in nor sent up ` @@ -317,7 +328,7 @@ func syncSet(k syncKind, args []string, on bool) error { if !on { return fmt.Errorf("%s sync is on, not %s: magpie %s set changes it; %s", c.Kind(), k.name, strings.ToLower(c.Kind()), k.turnOn()) } - next := davsync.Config{Passphrase: c.Passphrase, Keys: c.Keys, Agents: c.Agents, Library: c.Library, Memory: c.Memory, Usage: c.Usage, SignIns: c.SignIns, + next := davsync.Config{Passphrase: c.Passphrase, Keys: c.Keys, Agents: c.Agents, Library: c.Library, Memory: c.Memory, Usage: c.Usage, SignIns: c.SignIns, SignInsExcept: c.SignInsExcept, Providers: c.Providers, Settings: c.Settings, Profiles: c.Profiles} if o, ok := c.Kept(k.name); ok { // its server, as it was kept when sync moved from it next.URL, next.User, next.Endpoint, next.Region, next.PathStyle, next.Branch = o.URL, o.User, o.Endpoint, o.Region, o.PathStyle, o.Branch @@ -371,6 +382,16 @@ func syncSet(k syncKind, args []string, on bool) error { } else { askPhrase = true } + case key == "sign-ins-except": // ids, comma-separated; none: none left out + c.SignInsExcept = nil + for _, id := range strings.Split(v, ",") { + if strings.EqualFold(strings.TrimSpace(v), "none") { + break + } + if id = strings.TrimSpace(id); id != "" && !slices.Contains(c.SignInsExcept, id) { + c.SignInsExcept = append(c.SignInsExcept, id) + } + } case key == "keys", key == "agents", key == "library", key == "usage", key == "sign-ins", key == "path-style" && k.cmd == "s3", key == "providers", key == "settings", key == "profiles", key == "memory": if v != "yes" && v != "no" { @@ -400,11 +421,11 @@ func syncSet(k syncKind, args []string, on bool) error { c.Library = &yes } case k.cmd == "s3": - return fmt.Errorf("unknown field %q (address, bucket, prefix, endpoint, region, access-key-id, secret, passphrase, path-style, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins)", key) + return fmt.Errorf("unknown field %q (address, bucket, prefix, endpoint, region, access-key-id, secret, passphrase, path-style, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins, sign-ins-except)", key) case k.cmd == "github": - return fmt.Errorf("unknown field %q (address, branch, token, passphrase, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins)", key) + return fmt.Errorf("unknown field %q (address, branch, token, passphrase, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins, sign-ins-except)", key) default: - return fmt.Errorf("unknown field %q (address, user, password, passphrase, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins)", key) + return fmt.Errorf("unknown field %q (address, user, password, passphrase, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins, sign-ins-except)", key) } } if bucket != nil || prefix != nil { @@ -585,6 +606,9 @@ func syncShow(k syncKind) error { } if v.SignIns { what = append(what, "sign-ins") + if len(v.SignInsExcept) > 0 { + what[len(what)-1] += " (not " + strings.Join(v.SignInsExcept, ", ") + ")" + } } fmt.Println(" syncs", strings.Join(what, ", ")) if left := leftOut(v); len(left) > 0 { diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 93ae03908..04e529c33 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -110,6 +110,14 @@ type Config struct { // Passphrase: off unless the user turns it on // (provider.MergeSignIns says how two computers' are merged). SignIns bool `json:"signIns,omitempty"` + // SignInsExcept are the subscriptions (provider ids) whose sign-ins + // this computer leaves out of SignIns (Ethereal499 on X: Claude's, as + // Claude is wary of where its accounts are used): theirs here never go + // up, the server's are never put in here, and theirs here are kept as + // they are, none taken away for the server lacking it. The server's + // copy goes on as it was for the computers that sync them. None, as + // in a setup made before the choice, leaves none out. + SignInsExcept []string `json:"signInsExcept,omitempty"` // Other is the most recently left server, retained for older clients. // Servers holds every inactive kind. Nothing syncs to them. Other *Server `json:"other,omitempty"` @@ -546,6 +554,9 @@ type View struct { Profiles bool `json:"profiles"` Usage bool `json:"usage,omitempty"` SignIns bool `json:"signIns,omitempty"` + // SignInsExcept are the subscriptions whose sign-ins stay out + // (Config.SignInsExcept) + SignInsExcept []string `json:"signInsExcept,omitempty"` // UsageError is why usage couldn't be shared the last time it was tried UsageError string `json:"usageError,omitempty"` Last time.Time `json:"last,omitzero"` @@ -620,7 +631,7 @@ func Status() View { } } } - v.Usage, v.SignIns = c.Usage, c.SignIns + v.Usage, v.SignIns, v.SignInsExcept = c.Usage, c.SignIns, c.SignInsExcept if c.Agents { v.Own = ownFields(st) } @@ -915,6 +926,8 @@ func collect(c Config) (backup.Bundle, error) { if serr := backup.WithSignIns(&b); serr != nil { return b, fmt.Errorf("the sign-ins couldn't be read: %w", serr) } + // the subscriptions left out here never go up + b.SignIns, _ = b.SignIns.Except(c.SignInsExcept) } return b, err } @@ -1663,7 +1676,11 @@ func syncOnce(ctx context.Context, c Config, st *state, pv *Plan) error { var shared map[string]string if c.SignIns { var plan provider.SignInPlan - merged.SignIns, plan, shared = provider.MergeSignIns(local.SignIns, remote.SignIns, st.SignIns) + // the server's of the subscriptions left out here: not put in + // here, and going on up as they were, for the others + theirs, held := remote.SignIns.Except(c.SignInsExcept) + merged.SignIns, plan, shared = provider.MergeSignIns(local.SignIns, theirs, st.SignIns) + merged.SignIns = merged.SignIns.With(held) if !plan.Empty() { if _, err := provider.ApplySignIns(plan); err != nil { return fmt.Errorf("bringing in the sign-ins: %w", err) diff --git a/internal/davsync/plan.go b/internal/davsync/plan.go index a25f4e3dd..ae971f1ff 100644 --- a/internal/davsync/plan.go +++ b/internal/davsync/plan.go @@ -177,7 +177,8 @@ func previewed(pv *Plan, c Config, local, remote, merged backup.Bundle, bringIn, } } if c.SignIns { - _, plan, _ := provider.MergeSignIns(local.SignIns, remote.SignIns, prevSignIns) + theirs, _ := remote.SignIns.Except(c.SignInsExcept) // the server's left out here: not put in + _, plan, _ := provider.MergeSignIns(local.SignIns, theirs, prevSignIns) pv.SignIns = plan.Count() } return nil diff --git a/internal/davsync/restore.go b/internal/davsync/restore.go index 410927770..2e68a53c8 100644 --- a/internal/davsync/restore.go +++ b/internal/davsync/restore.go @@ -143,8 +143,9 @@ func Restore(ctx context.Context) ([]string, error) { } // the server's sign-ins, when they go: put in as a backup's are, // nothing renewed later here written over - if c.SignIns && remote.SignIns != nil { - if _, err := provider.RestoreSignIns(remote.SignIns); err != nil { + // (those of the subscriptions left out here aren't) + if theirs, _ := remote.SignIns.Except(c.SignInsExcept); c.SignIns && theirs != nil { + if _, err := provider.RestoreSignIns(theirs); err != nil { return fmt.Errorf("bringing in the sign-ins: %w", err) } if local, err = collect(c); err != nil { diff --git a/internal/davsync/signins_except_test.go b/internal/davsync/signins_except_test.go new file mode 100644 index 000000000..830b855bd --- /dev/null +++ b/internal/davsync/signins_except_test.go @@ -0,0 +1,151 @@ +package davsync + +import ( + "context" + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// Sign-ins in sync with one subscription left out on one computer +// (Ethereal499 on X: Claude's accounts kept out of sync, since Claude is +// wary of where they are used). On the computer leaving Claude out, its +// Claude accounts never go up, the server's never come in, and none here +// is taken away for the server lacking it; every other sign-in syncs as +// before, and the server's Claude accounts go on for the computer that +// syncs them. The preview counts no Claude account either. +func TestSyncSignInsExcept(t *testing.T) { + fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}} + srv := httptest.NewServer(fake) + defer srv.Close() + cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse", SignIns: true} + noClaude := cfg + noClaude.SignInsExcept = []string{"claude"} + now := func(t *testing.T) { + t.Helper() + if err := Now(context.Background()); err != nil { + t.Fatal(err) + } + if v := Status(); v.Error != "" { + t.Fatal(v.Error) + } + } + file := func() string { return filepath.Join(settings.Dir(), "logins.json") } + rows := func(t *testing.T) []map[string]any { + t.Helper() + var out []map[string]any + b, err := os.ReadFile(file()) + if os.IsNotExist(err) { + return nil + } + if err != nil || json.Unmarshal(b, &out) != nil { + t.Fatalf("logins.json: %v %s", err, b) + } + return out + } + write := func(t *testing.T, rs []map[string]any) { + t.Helper() + if err := os.MkdirAll(settings.Dir(), 0o700); err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(rs) + if err := os.WriteFile(file(), b, 0o600); err != nil { + t.Fatal(err) + } + } + claude := func(user, token string, exp int) map[string]any { + return map[string]any{"agent": "claude", "user": user, + "profile": map[string]any{"emailAddress": user, "organizationUuid": "org-" + user}, + "auth": map[string]any{"claudeAiOauth": map[string]any{"accessToken": token, "refreshToken": "r-" + token, "expiresAt": exp}}} + } + gemini := func(user, token string, exp int) map[string]any { + return map[string]any{"agent": "gemini", "user": user, + "auth": map[string]any{"access_token": token, "refresh_token": "r-" + token, "expiry_date": exp}} + } + add := func(t *testing.T, r map[string]any) { t.Helper(); write(t, append(rows(t), r)) } + here := func(t *testing.T) string { + t.Helper() + b, _ := os.ReadFile(file()) + return string(b) + } + has := func(t *testing.T, who string, want, not []string) { + t.Helper() + h := here(t) + for _, s := range want { + if !strings.Contains(h, s) { + t.Fatalf("%s hasn't %q:\n%s", who, s, h) + } + } + for _, s := range not { + if strings.Contains(h, s) { + t.Fatalf("%s has %q:\n%s", who, s, h) + } + } + } + + // a syncs every sign-in; b joins syncing them all too + a, b := newComputer(t), newComputer(t) + a.use(t) + write(t, []map[string]any{claude("a@x.com", "claude-a", 2000), gemini("a@x.com", "gem-a", 2000)}) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + now(t) + b.use(t) + write(t, []map[string]any{gemini("b@x.com", "gem-b", 2000)}) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + now(t) + has(t, "b, joined", []string{"claude-a", "gem-a", "gem-b"}, nil) + + // b leaves Claude out, then signs in to a Claude account of its own: + // it doesn't go up, while its new Gemini one does + if err := Configure(noClaude); err != nil { + t.Fatal(err) + } + if v := Status(); !slices.Equal(v.SignInsExcept, []string{"claude"}) { + t.Fatalf("status: %+v", v.SignInsExcept) + } + add(t, claude("b@x.com", "claude-b", 3000)) + add(t, gemini("b2@x.com", "gem-b2", 3000)) + now(t) + a.use(t) + now(t) + has(t, "a", []string{"claude-a", "gem-b", "gem-b2"}, []string{"claude-b"}) + + // a removes its Claude account and signs in to another: b keeps the + // one it has, and doesn't get the new one, nor count it in a preview + write(t, slices.DeleteFunc(rows(t), func(r map[string]any) bool { return r["user"] == "a@x.com" && r["agent"] == "claude" })) + add(t, claude("c@x.com", "claude-c", 4000)) + now(t) + has(t, "a", []string{"claude-c"}, []string{"claude-a"}) + b.use(t) + p, err := Preview(context.Background()) + if err != nil { + t.Fatal(err) + } + if p.SignIns != 0 { + t.Fatalf("the preview counts %d sign-ins changing here, Claude's left out", p.SignIns) + } + now(t) + has(t, "b", []string{"claude-a", "claude-b", "gem-a", "gem-b2"}, []string{"claude-c"}) + + // and a, syncing Claude, still has the server's Claude accounts after b's + // syncs: b's leaving them out took none away there + a.use(t) + now(t) + has(t, "a, after b's syncs", []string{"claude-c", "gem-b", "gem-b2"}, []string{"claude-a", "claude-b"}) + + // a setup from before the choice leaves nothing out + var old Config + if err := json.Unmarshal([]byte(`{"url":"x","passphrase":"p","signIns":true}`), &old); err != nil || old.SignInsExcept != nil { + t.Fatalf("%+v %v", old, err) + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 06f1be03b..1e398742e 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -5627,6 +5627,14 @@ body.linux:not(.side-nav) #view-settings .set-head::before, body.linux .action-confirm::backdrop { -webkit-backdrop-filter: none; backdrop-filter: none; } /* what syncs (#6428): the keys' tick under Providers; a preview's items */ .editor.sync-form .sync-sub-tick { padding-left: 22px; } +.editor.sync-form .sync-except { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 13px; } +.editor.sync-form .sync-except[hidden] { display: none; } +.sync-except .proto.pick { flex: 0 1 auto; min-width: 0; display: inline-flex; align-items: center; gap: 3px; height: 24px; padding: 0 6px 0 9px; font: inherit; font-size: 12px; color: var(--fg-2); border: 0; border-radius: 7px; background: var(--pill); cursor: default; transition: background .12s, color .12s; } +.sync-except .proto.pick span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.sync-except .proto.pick svg { flex: none; opacity: .7; transition: transform .15s var(--ease); } +.sync-except .proto.pick.open svg { transform: rotate(180deg); } +.sync-except .proto.pick:hover, .sync-except .proto.pick.open { color: var(--fg); background: var(--pill-hover); } +.sync-except .proto.pick.busy { opacity: .6; } .sync-preview .sync-items { display: grid; gap: 2px; margin: -2px 0 8px; padding: 6px 10px; border-radius: 8px; background: var(--pill); font-size: 12.5px; max-height: 180px; overflow-y: auto; } .sync-preview .sync-item { display: flex; justify-content: space-between; gap: 12px; min-width: 0; } .sync-preview .sync-item span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } diff --git a/internal/gui/assets/syncfiles.js b/internal/gui/assets/syncfiles.js index 0251aee54..1ef0e1689 100644 --- a/internal/gui/assets/syncfiles.js +++ b/internal/gui/assets/syncfiles.js @@ -52,14 +52,40 @@ window.davForm = function (v) { // (qianxunji, curtinp118 on Discord); what it lets in is said beside it const [siL, si] = tick(t("Sign-ins: subscription accounts and plugin sign-ins"), !!v.signIns); const siSay = el("div", "hint sync-signins-say", t("Another computer that syncs is signed in without signing in again. Anyone with the passphrase and the server's file can use these accounts. An account used on two computers can be signed out on one when the other renews it.")); - siSay.hidden = !si.checked; - si.onchange = () => { siSay.hidden = !si.checked; }; + // subscriptions whose sign-ins stay on this computer (Ethereal499 on X: + // Claude, wary of where it is used): theirs here never go up, the + // server's never come in, and none here is taken away + let except = [...(v.signInsExcept || [])]; + const exL = el("div", "sync-sub-tick sync-except"); + const exPick = el("button", "proto pick"); + exPick.type = "button"; + const subName = (id) => providers?.providers?.find((p) => p.id === id)?.name || id; + const exPaint = () => { + exPick.classList.toggle("set", !!except.length); + exPick.replaceChildren(el("span", "", !except.length ? t("None") : except.length > 2 ? t("{n} subscriptions", { n: except.length }) : except.map(subName).join(", ")), svg(CHEV, 11, 1.6)); + }; + exPaint(); + if (except.length && !providers) loadProviders().catch(() => {}).then(exPaint); + exPick.onclick = async (e) => { + e.stopPropagation(); + if (exPick.classList.contains("open")) return closeProtoMenu(); + if (!providers) { exPick.classList.add("busy"); await loadProviders().catch(() => {}); exPick.classList.remove("busy"); if (!exPick.isConnected) return; } + const opts = (providers?.providers || []).filter((p) => p.account).map((p) => ({ v: p.id, name: p.name || p.id, note: "", literalName: true })); + // one left out that isn't here now stays to be ticked back + for (const id of except) if (!opts.some((o) => o.v === id)) opts.push({ v: id, name: id, note: "", literalName: true }); + if (!opts.length) opts.push({ v: "\x00", name: "No subscriptions yet", note: "" }); + openProtoMenu(exPick, opts, except, (ids) => { except = ids; exPaint(); }, "Not synced", "", "left", true); + }; + exL.append(el("span", "", t("Not synced")), exPick); + const siShow = () => { siSay.hidden = exL.hidden = !si.checked; }; + siShow(); + si.onchange = siShow; const what = el("div", "stack"); what.append(provL, keysL, setL, agentsL, libL, memL); const adv = el("details", "more advanced sync-advanced"); adv.open = v.profiles === false || !!v.usage || !!v.signIns; const advIn = el("div", "stack"); - advIn.append(profL, useL, siL, siSay, el("div", "hint", t("Usage goes as a file a day: times, tokens, models and costs, never what was said. Turn it on on each computer that shares its own."))); + advIn.append(profL, useL, siL, exL, siSay, el("div", "hint", t("Usage goes as a file a day: times, tokens, models and costs, never what was said. Turn it on on each computer that shares its own."))); adv.append(el("summary", "", t("Advanced")), advIn); const davFields = [...field(t("Address"), url, t("A folder named magpie is made in it.")), ...field(t("User"), user), @@ -129,7 +155,7 @@ window.davForm = function (v) { prov.checked = s.providers !== false; sets.checked = s.settings !== false; prof.checked = s.profiles !== false; keysShow(); if (!prof.checked || use.checked || si.checked) adv.open = true; - siSay.hidden = !si.checked; + siShow(); // the kind picked as a click on it would, its thumb moved too to[1].querySelector(`.segs [data-seg="${kind}"]`)?.click(); show(); @@ -177,7 +203,7 @@ window.davForm = function (v) { // so a setup from before the choice is saved as it was const outs = {}; for (const [k, c] of [["providers", prov], ["settings", sets], ["profiles", prof]]) if (!c.checked || v[k] === false) outs[k] = c.checked; - return { ...where, passphrase: phrase.value, keys: keys.checked, agents: agents.checked, library: lib.checked, memory: mem.checked, ...outs, ...(use.checked || v.usage ? { usage: use.checked } : {}), ...(si.checked || v.signIns ? { signIns: si.checked } : {}) }; + return { ...where, passphrase: phrase.value, keys: keys.checked, agents: agents.checked, library: lib.checked, memory: mem.checked, ...outs, ...(use.checked || v.usage ? { usage: use.checked } : {}), ...(si.checked || v.signIns ? { signIns: si.checked } : {}), ...(except.length || v.signInsExcept?.length ? { signInsExcept: except } : {}) }; }; peek.onclick = async () => { if (!(await openPasted())) return; diff --git a/internal/gui/tests/sync-signins-except.test.cjs b/internal/gui/tests/sync-signins-except.test.cjs new file mode 100644 index 000000000..254ee6b1d --- /dev/null +++ b/internal/gui/tests/sync-signins-except.test.cjs @@ -0,0 +1,166 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Subscriptions left out of syncing sign-ins (Ethereal499 on X: Claude +// kept out, since it is wary of where its accounts are used). Under the +// Sign-ins tick in Sync's form, Not synced shows only while the tick is +// on, None until picked: +// - a setup from before the choice posts no signInsExcept at all; +// - its menu lists the subscriptions with accounts, not a key provider; +// picking Claude shows it there and Save posts ["claude"]; +// - opened again, Advanced is open with Claude shown, and unticking the +// sign-ins hides the row. +// In all five languages, at 1100 and 420px, Chromium and WebKit, nothing +// wider than the window. 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 { reach, openPart } = require("./reader.cjs"); +const { strings } = require("./strings.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const { I18N } = strings(); +const tr = (lang, k, vars = {}) => { + const s = lang === "en" ? k : I18N[lang][k]; + assert.equal(typeof s, "string", `${lang} has ${JSON.stringify(k)}`); + return s.replace(/\{(\w+)\}/g, (_, v) => vars[v]); +}; + +const base = { on: true, kind: "webdav", url: "https://dav.example.invalid/dav/", user: "me", passwordSet: true, passphraseSet: true, keys: true, agents: true, library: true, signIns: true, last: new Date(Date.now() - 60000).toISOString() }; +const subs = [ + { id: "claude", name: "Claude", account: { logins: [{ user: "me@x.com", active: true }] } }, + { id: "codex", name: "Codex", account: { logins: [{ user: "me@x.com", active: true }] } }, + { id: "deepseek", name: "DeepSeek" }, +]; + +function serve(lang, 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 }, + }; + let sync = { ...base }; + 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/providers") return json({ providers: subs, presets: [] }); + if (pathname === "/api/davsync") return json(sync); + if (pathname === "/api/davsync/save") { + const b = request.postDataJSON(); + posts.push(b); + sync = { ...sync, signIns: !!b.signIns, signInsExcept: b.signInsExcept }; + return json(sync); + } + 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 }); + }; +} + +async function noneWider(page) { + const wide = await page.evaluate(() => { + const out = []; + if (document.scrollingElement.scrollWidth > innerWidth) out.push("page " + document.scrollingElement.scrollWidth); + for (const r of document.querySelectorAll("#syncList .sync-form, #syncList .sync-except, .proto-menu")) { + const b = r.getBoundingClientRect(); + if (b.right > innerWidth + 0.5) out.push(r.className + " " + b.right); + } + return out; + }); + assert.deepEqual(wide, [], "wider than the window"); +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + const w = (k, vars) => tr(lang, k, vars); + test(`${engine} ${width}px ${lang}: a subscription's sign-ins can be left out of sync`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, 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}-${width}-${lang}-sync-signins-except.png`), fullPage: true }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const waitPost = async (n) => { + for (let i = 0; i < 250 && posts.length < n; i++) await page.waitForTimeout(20); + assert.equal(posts.length, n, "saves posted"); + return posts[n - 1]; + }; + const click = async (loc) => { await reach(page, loc); await loc.click(); }; + const exact = (s) => new RegExp("^" + s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "$"); + + await page.goto("http://magpie.test/"); + await page.locator("#prefs").click(); + await openPart(page, "sync"); + const list = page.locator("#syncList"); + const first = list.locator(".row.pref").first(); + await first.waitFor({ state: "visible" }); + const edit = async () => { + await click(first.locator("button", { hasText: exact(w("Edit")) })); + return list.locator(".sync-form"); + }; + + // a setup from before the choice: shown with None, posted without it + let form = await edit(); + assert.equal(await form.locator("details.sync-advanced").evaluate((d) => d.open), true, "Advanced folded with sign-ins on"); + const row = form.locator(".sync-except"); + const pick = row.locator("button.pick"); + await row.waitFor({ state: "visible" }); + assert.equal(await row.locator("> span").textContent(), w("Not synced")); + assert.equal(await pick.textContent(), w("None")); + await noneWider(page); + await click(form.locator("button.primary")); + assert.ok(!("signInsExcept" in await waitPost(1)), "an old setup posted signInsExcept"); + await form.waitFor({ state: "detached" }); + + // Claude left out + form = await edit(); + await click(pick); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + assert.equal(await menu.locator(".pm-head").textContent(), w("Not synced")); + assert.deepEqual(await menu.locator(".pm-name").allTextContents(), ["Claude", "Codex"], "the menu lists the subscriptions with accounts"); + await noneWider(page); + await click(menu.locator(".pm-item", { hasText: "Claude" })); + await page.waitForFunction(() => document.querySelector(".sync-except button.pick")?.textContent === "Claude"); + await click(pick); + await menu.waitFor({ state: "detached" }); + await click(form.locator("button.primary")); + const saved = await waitPost(2); + assert.deepEqual(saved.signInsExcept, ["claude"]); + assert.equal(saved.signIns, true); + await form.waitFor({ state: "detached" }); + + // opened again: shown; the sign-ins unticked hide it + form = await edit(); + await page.waitForFunction(() => document.querySelector(".sync-except button.pick")?.textContent === "Claude"); + const siTick = form.locator("label.tick", { hasText: w("Sign-ins: subscription accounts and plugin sign-ins") }).locator("input"); + await click(siTick); + await row.waitFor({ state: "hidden" }); + await click(siTick); + await row.waitFor({ state: "visible" }); + await noneWider(page); + await click(first.locator("button", { hasText: exact(w("Close")) })); + await form.waitFor({ state: "detached" }); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/signins_except.go b/internal/provider/signins_except.go new file mode 100644 index 000000000..f87014683 --- /dev/null +++ b/internal/provider/signins_except.go @@ -0,0 +1,102 @@ +package provider + +import ( + "encoding/json" + "maps" + "strings" + + "github.com/yetone/magpie/internal/plugin" +) + +// Subscriptions whose sign-ins a sync leaves out on one computer +// (Ethereal499 on X: Claude's accounts kept out, since Claude is wary of +// the place they are used from). Their accounts here never go up, and +// theirs on the server are never put in here; the server's are carried +// through as they are, for the computers that do sync them, and nothing +// here is taken away for their missing there. + +// Except splits s by subscription: kept is s without the sign-ins of the +// subscriptions named in except (provider ids, a built-in's or its +// plugin's, either naming both), held is theirs alone. With none named, +// kept is s itself and held nil; a nil s gives nil for both. +func (s *SignIns) Except(except []string) (kept, held *SignIns) { + if s == nil || len(except) == 0 { + return s, nil + } + out := exceptIDs(except) + if len(out) == 0 { + return s, nil + } + kept, held = &SignIns{}, &SignIns{} + for _, l := range s.Logins { + if out[l.Agent] { + held.Logins = append(held.Logins, l) + } else { + kept.Logins = append(kept.Logins, l) + } + } + for k, raw := range s.Plugins { + to := kept + if out[plugin.ProviderOf(k)] { + to = held + } + if to.Plugins == nil { + to.Plugins = map[string]json.RawMessage{} + } + to.Plugins[k] = raw + } + if agent, _, _ := strings.Cut(s.Codex, "|"); s.Codex != "" && out[agent] { + held.Codex = s.Codex + } else { + kept.Codex = s.Codex + } + if len(held.Logins) == 0 && held.Plugins == nil && held.Codex == "" { + held = nil + } + return kept, held +} + +// With is s with held's sign-ins put back beside its own, as Except took +// them out: held's plugins and Codex only where s has none of its own. +func (s *SignIns) With(held *SignIns) *SignIns { + if held == nil { + return s + } + out := &SignIns{} + if s != nil { + out.Logins, out.Codex = append(out.Logins, s.Logins...), s.Codex + out.Plugins = maps.Clone(s.Plugins) + } + out.Logins = append(out.Logins, held.Logins...) + for k, raw := range held.Plugins { + if _, ok := out.Plugins[k]; ok { + continue + } + if out.Plugins == nil { + out.Plugins = map[string]json.RawMessage{} + } + out.Plugins[k] = raw + } + if out.Codex == "" { + out.Codex = held.Codex + } + return out +} + +// exceptIDs are the provider ids in except, each with its other id: the +// plugin signed in beside a subscription (claude-plugin) and the +// subscription a -plugin id stands beside. +func exceptIDs(except []string) map[string]bool { + out := map[string]bool{} + for _, id := range except { + id = strings.TrimSpace(id) + if id == "" { + continue + } + out[id], out[id+"-plugin"] = true, true + if base, ok := strings.CutSuffix(id, "-plugin"); ok && base != "" { + out[base] = true + } + } + return out +} diff --git a/internal/provider/signins_except_test.go b/internal/provider/signins_except_test.go new file mode 100644 index 000000000..44eb37dfe --- /dev/null +++ b/internal/provider/signins_except_test.go @@ -0,0 +1,52 @@ +package provider + +import ( + "encoding/json" + "testing" +) + +// A subscription left out of sync is left out under each of its ids: its +// own accounts, its plugin's sign-ins (claude-plugin) and its Codex +// record; With puts what Except took back, without writing over s's own. +func TestSignInsExcept(t *testing.T) { + s := &SignIns{ + Logins: []savedLogin{{Agent: "claude", User: "c@x.com"}, {Agent: "gemini", User: "g@x.com"}}, + Plugins: map[string]json.RawMessage{ + "claude-plugin#c@x.com": json.RawMessage(`1`), + "kiro": json.RawMessage(`2`), + "zed": json.RawMessage(`3`), + }, + Codex: "codex|me@x.com|org", + } + if k, h := s.Except(nil); k != s || h != nil { + t.Fatal("nothing left out isn't s as it is") + } + if k, h := s.Except([]string{" "}); k != s || h != nil { + t.Fatal("a blank id left something out") + } + for _, ids := range [][]string{{"claude", "kiro-plugin", "codex"}, {"claude-plugin", "kiro", "codex"}} { + kept, held := s.Except(ids) + if len(kept.Logins) != 1 || kept.Logins[0].Agent != "gemini" || kept.Codex != "" || len(kept.Plugins) != 1 || kept.Plugins["zed"] == nil { + t.Fatalf("%v kept %+v", ids, kept) + } + if len(held.Logins) != 1 || held.Logins[0].Agent != "claude" || held.Codex != s.Codex || len(held.Plugins) != 2 || held.Plugins["kiro"] == nil || held.Plugins["claude-plugin#c@x.com"] == nil { + t.Fatalf("%v held %+v", ids, held) + } + back := kept.With(held) + if len(back.Logins) != 2 || len(back.Plugins) != 3 || back.Codex != s.Codex { + t.Fatalf("%v put back %+v", ids, back) + } + } + if _, h := s.Except([]string{"grok"}); h != nil { + t.Fatalf("a subscription with no sign-ins here held %+v", h) + } + // s's own plugin sign-in and Codex record stay over held's + mine := &SignIns{Plugins: map[string]json.RawMessage{"kiro": json.RawMessage(`9`)}, Codex: "codex|b@x.com|o"} + out := mine.With(&SignIns{Plugins: map[string]json.RawMessage{"kiro": json.RawMessage(`2`)}, Codex: "codex|a@x.com|o"}) + if string(out.Plugins["kiro"]) != "9" || out.Codex != mine.Codex { + t.Fatalf("held wrote over s's own: %+v", out) + } + if string(mine.Plugins["kiro"]) != "9" || len(mine.Plugins) != 1 { + t.Fatal("With changed s") + } +}