providers: a Remote magpie that is this magpie says so and is left out, unless kept (hanslin1666)

B uses A through a Remote magpie provider, and sync carries that
provider to A, where it points at A. Each of its models was one of A's
own, listed again beside it and taken by A's found groups, and a request
through it passed through A's gateway twice.

A fetch of a Remote magpie's list now reads its models' magpie_via: when
the magpie that listed them (the last entry) is this magpie's own
catalog.Self, remote-self.json keeps the provider id and the address it
answered at (noteSelf). Another lister, or a list with no via, takes
the record away; an empty list or a failed fetch changes nothing; a
provider moved to another address is not self until a fetch there says
so. The file is this computer's own, never in a backup or sync.

Such a provider is left out (SelfLeftOut in On, SwitchedOff and
remoteMagpies): not in /v1/models, the catalog or a found group. A
request naming one of its models, an agent's pick synced from B, is
served here with the remote's id taken off (ThroughSelf in Resolve and
ResolveRoute), once through the gateway. A 404 for it says why and how
to keep it.

The Providers row shows "This magpie" (greyed while left out), with the
reason as its title; the editor has a note and a "Use it anyway" tick
(KeepSelf, POST /api/provider/keepself). KeepSelf belongs to the user
and to this computer: Mirror and Restore keep the local value (false for
a provider new here), davsync's hashes blank it, and a provider save
keeps it. Strings in en, zh, zh-TW, ja, de.

Docs: providers-accounts.md (two magpies row), sync-backup.md (what
stays on each computer).

Run at this tree on origin/main 4e85cac01:
- gofmt -l: nothing. app.js 1,309,132 bytes (budget 1,316,874).
- mote: go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  provider, gateway, gui, davsync, catalog: ok.
- mote: go test catalog, davsync ok; gui red only in
  TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27); provider and
  gateway did not build there (mote's disk full, "no space left on
  device"), so they were run on:
- Linux (WSL magpie-desktop): go test -tags nogui provider, gateway,
  gui, davsync: all ok.
- Windows (xiaomi-gpu): go test -run 'RemoteSelf|KeepSelf|RemoteMagpie|
  Mirror|KeepLogin' provider, gateway, davsync: ok.
- mote: remote-self.test.cjs 16 of 16 (chromium and webkit, 1100 and
  420, en zh ja de), before the rebase; the rebase touched no line of it.

Broken by hand, each red, then restored:
- noteSelf a no-op: TestRemoteSelfRecord and
  TestRemoteMagpieThatIsThisOneIsLeftOut red.
- ThroughSelf a no-op: the gateway test red (404 for rem/own/m1).
- On() without SelfLeftOut: the gateway test red (listed, 2 passes).
- davsync hashes without the KeepSelf blank: TestKeepSelfIsNoChange red.
- Mirror without keeping KeepSelf: TestMirrorKeepsKeepSelf red.
- The row's badge removed: remote-self.test.cjs red (chromium 1100 en).
- The tick's onchange a no-op: remote-self.test.cjs red (webkit 420 zh).

Not tried: two real computers syncing each other (the case is built in
one process: the gateway test's Remote magpie is its own gateway);
the Linux and Windows apps' webviews; the whole GUI suite (mote's disk is full);
remote-self.test.cjs again after the rebase.
This commit is contained in:
yetone
2026-11-05 12:37:30 +08:00
parent 583fe70751
commit 1826c4bd99
19 changed files with 755 additions and 14 deletions
File diff suppressed because one or more lines are too long
+10
View File
@@ -61,6 +61,16 @@ 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`).
A Remote magpie's **Use it anyway** (`KeepSelf`) is kept the same way. Sync
carries a Remote magpie provider to the computer it names (hanslin1666 on
Discord: B uses A through one, and on A it points at A), and there it is
found to be this magpie and left out unless kept (see
[providers and accounts](providers-accounts.md)). Whether it is this magpie
is about one computer only, so it is kept in `remote-self.json`, which no
backup or sync carries, and `KeepSelf` is kept by `Mirror` and `Restore`
(false for a provider new here) and blanked by `hashes`
(`TestMirrorKeepsKeepSelf`, `TestKeepSelfIsNoChange`).
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
+1
View File
@@ -846,6 +846,7 @@ func hashes(b backup.Bundle) map[string]string {
ps := slices.Clone(b.Providers)
for i := range ps { // this computer's own: kept by Mirror, never synced
ps[i].KeepLogin, ps[i].KeepLoginAs, ps[i].SwitchOnly, ps[i].RestartApp = false, "", false, false
ps[i].KeepSelf = false
}
providers := []any{ps, b.Icons, b.Groups}
if b.Searches != nil && len(*b.Searches) > 0 { // as before them, without one
+25
View File
@@ -0,0 +1,25 @@
package davsync
import (
"testing"
"github.com/yetone/magpie/internal/backup"
"github.com/yetone/magpie/internal/provider"
)
// Whether a Remote magpie that is this magpie is used anyway is this
// computer's own (provider.Mirror keeps it): on the other computer the
// same provider points at a magpie that is not that one (hanslin1666 on
// Discord). Changing it uploads nothing.
func TestKeepSelfIsNoChange(t *testing.T) {
p := provider.Provider{ID: "rem", Name: "Rem", Preset: provider.RemoteMagpiePreset}
b := backup.Bundle{Providers: []provider.Provider{p}}
p.KeepSelf = true
kept := backup.Bundle{Providers: []provider.Provider{p}}
if hashes(b)["providers"] != hashes(kept)["providers"] {
t.Fatal("Use it anyway changed the providers hash")
}
if !kept.Providers[0].KeepSelf {
t.Fatal("hashing changed the bundle")
}
}
+5 -1
View File
@@ -266,8 +266,12 @@ func namesInCatalog() map[string]bool {
// switchedOff says a request for model went nowhere because p, which
// serves it, is switched off in magpie (provider.Provider.Off), or kept to
// Claude Code's own sign-in (provider.Provider.KeptToAgent).
// Claude Code's own sign-in (provider.Provider.KeptToAgent), or a Remote
// magpie that is this one (provider.Provider.SelfLeftOut).
func switchedOff(p provider.Provider, model string) string {
if p.SelfLeftOut() && !p.Off {
return fmt.Sprintf("%s is a Remote magpie that is this magpie itself, so %q is not served through it; ask for the model without %q in front, or tick \"Use it anyway\" on it in Magpie's Providers", p.Name, model, p.ID+"/")
}
if p.KeptToAgent() {
return fmt.Sprintf("%s's accounts are kept to Claude Code's own sign-in in Magpie, so %q is not served; untick \"Only switch Claude Code's sign-in\" under its accounts in Magpie's Providers to use it", p.Name, model)
}
+3
View File
@@ -31,6 +31,9 @@ func TestMain(m *testing.M) {
limitsOn = gwbudget.Limit(budget.Limiter{})
// the test binary is no magpie: it runs no claude-tui-helper
claudeTUIRuns = false
// the tests serve their Remote magpie from this process, which is
// then this magpie itself (remote_self_test.go turns it on again)
provider.LeaveOutSelf = false
code, err := isolatedTests(m)
if err != nil {
fmt.Fprintln(os.Stderr, err)
+133
View File
@@ -0,0 +1,133 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// A Remote magpie that is this magpie (hanslin1666 on Discord: B uses A
// through one, and sync carried it to A, where it points at A) is left
// out: its models are not listed beside this magpie's own, a found group
// doesn't take them, and a request naming one (an agent's pick synced
// from B) is served here at once, not passed through the gateway again.
// "Use it anyway" (KeepSelf) has it back.
func TestRemoteMagpieThatIsThisOneIsLeftOut(t *testing.T) {
provider.LeaveOutSelf = true
t.Cleanup(func() { provider.LeaveOutSelf = false })
var vendor atomic.Int32
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
io.WriteString(w, `{"object":"list","data":[]}`)
return
}
vendor.Add(1)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"}}]}`)
}))
t.Cleanup(up.Close)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "own", Name: "Own", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("own", up.URL+"/v1", []catalog.Model{{ID: "m1"}}); err != nil {
t.Fatal(err)
}
var passes atomic.Int32 // chat requests this gateway was asked
h := New().Handler()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
passes.Add(1)
}
h.ServeHTTP(w, r)
}))
t.Cleanup(srv.Close)
id, err := provider.Add(provider.Provider{ID: "rem", Name: "Rem", Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(srv.URL, "http://")})
if err != nil {
t.Fatal(err)
}
rem, _ := provider.Find(id)
if _, err := rem.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
rem, _ = provider.Find(id)
if !rem.SelfAnswered() || !rem.SelfLeftOut() || rem.On() {
t.Fatalf("a Remote magpie at this magpie's own address: answered as self %v, left out %v, on %v; want true, true, false", rem.SelfAnswered(), rem.SelfLeftOut(), rem.On())
}
listed := func() map[string]bool {
t.Helper()
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/v1/models", nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var l struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&l); err != nil {
t.Fatal(err)
}
out := map[string]bool{}
for _, m := range l.Data {
out[m.ID] = true
}
return out
}
if l := listed(); l["rem/own/m1"] || !l["own/m1"] {
t.Errorf("listed %v; want own/m1 and not rem/own/m1", l)
}
for _, e := range provider.Catalog() {
if e.Provider.ID == "rem" {
t.Errorf("the catalog has %s through this magpie's own Remote magpie", e.ID)
}
}
ask := func(model string) int {
t.Helper()
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "curl/8")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
return resp.StatusCode
}
if code := ask("rem/own/m1"); code != http.StatusOK {
t.Fatalf("a request for rem/own/m1: %d, want 200", code)
}
if p, v := passes.Load(), vendor.Load(); p != 1 || v != 1 {
t.Errorf("rem/own/m1 took %d passes through the gateway and %d vendor requests; want 1 and 1", p, v)
}
// kept by the user: through the remote as before
if err := provider.SetKeepSelf(id, true); err != nil {
t.Fatal(err)
}
rem, _ = provider.Find(id)
if !rem.SelfAnswered() || rem.SelfLeftOut() || !rem.On() {
t.Fatalf("kept: answered as self %v, left out %v, on %v; want true, false, true", rem.SelfAnswered(), rem.SelfLeftOut(), rem.On())
}
if l := listed(); !l["rem/own/m1"] {
t.Errorf("kept, listed %v; want rem/own/m1 again", l)
}
passes.Store(0)
if code := ask("rem/own/m1"); code != http.StatusOK || passes.Load() != 2 {
t.Errorf("kept, rem/own/m1: %d in %d passes; want 200 in 2", code, passes.Load())
}
}
+1
View File
@@ -2702,6 +2702,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.row.model .minfo .mi-img svg, .rt-gedit .fbrow .minfo .mi-img svg { display: block; }
.provider .pswitch { margin-left: 8px; }
.editor .off-note { grid-column: 1 / -1; }
.editor .self-note label.tick { margin-top: 6px; }
.uses { display: flex; align-items: center; gap: 4px; margin-left: auto; flex: none; }
.use {
width: 26px; height: 26px; border-radius: 8px;
+14
View File
@@ -6224,6 +6224,7 @@ function renderProviders(quiet) {
const name = el("div", "name", p.name);
if (p.sponsored) name.append(el("span", "badge", t("sponsored")));
if (p.off) name.append(el("span", "badge off", t("Switched off")));
if (p.self) name.append(Object.assign(el("span", "badge" + (p.keepSelf ? "" : " off"), t("This magpie")), { title: selfNote(p) }));
if (p.move && p.move.state !== "plugin") name.append(deprecatedBadge());
const n = p.models.filter((m) => m.on).length;
// rate windows: what it bills at now (#2463)
@@ -9230,6 +9231,14 @@ function drawEditor(p, presetID) {
if (p) h.append(providerSwitch(p));
ed.append(h);
if (p?.off) ed.append(el("div", "hint off-note", t("Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.")));
// a Remote magpie that is this magpie, which sync brought here (hanslin1666)
if (p?.self) {
const [keep, cb] = tick(t("Use it anyway"), !!p.keepSelf);
cb.onchange = () => accountAction("provider/keepself", { id: p.id, keepSelf: cb.checked }, t(cb.checked ? "{name} is used anyway" : "{name} is left out: it is this magpie", { name: p.name }));
const note = el("div", "hint off-note self-note", selfNote(p));
note.append(keep);
ed.append(note);
}
}
// a vendor's global and China endpoints are presets of their own, one row
@@ -20414,6 +20423,11 @@ function askLANNames(urls, then) {
}, 300);
}
function selfNote(p) {
return t(p.keepSelf ? "This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice."
: "This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.");
}
function tick(label, on) {
const l = el("label", "tick");
const c = el("input");
+24
View File
@@ -1668,6 +1668,12 @@ const I18N = {
"{agent} is back on its default": "{agent} 已恢复为默认模型",
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} 仍在用 magpie 已不再提供的 {model}:{error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "已关闭:不向 Agent 提供其模型,也不向它发请求。密钥和设置保留,开启即可恢复使用。",
"This magpie": "本机 magpie",
"This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.": "这个远程 magpie 就是本机的 magpie。仍在使用:它的模型与本机自己的模型并列,经它的请求会两次经过本机 magpie。",
"This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.": "这个远程 magpie 就是本机的 magpie:是同步从使用本机的另一台电脑带过来的。它已被排除,模型不会重复列出;请求它的模型时直接由本机提供。",
"Use it anyway": "仍然使用",
"{name} is used anyway": "仍在使用 {name}",
"{name} is left out: it is this magpie": "已排除 {name}:它就是本机 magpie",
"API key {masked}": "API 密钥 {masked}",
"Local servers need no key": "本地服务无需密钥",
"Open the row and paste an API key": "展开这一行并粘贴 API 密钥",
@@ -6275,6 +6281,12 @@ const I18N = {
"{agent} is back on its default": "{agent} 已恢復為預設模型",
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} 仍在用 magpie 已不再提供的 {model}:{error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "已關閉:不向 Agent 提供其模型,也不向它發請求。金鑰和設定保留,開啟即可恢復使用。",
"This magpie": "本機 magpie",
"This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.": "這個遠端 magpie 就是本機的 magpie。仍在使用:它的模型與本機自己的模型並列,經它的請求會兩次經過本機 magpie。",
"This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.": "這個遠端 magpie 就是本機的 magpie:是同步從使用本機的另一台電腦帶過來的。它已被排除,模型不會重複列出;請求它的模型時直接由本機提供。",
"Use it anyway": "仍然使用",
"{name} is used anyway": "仍在使用 {name}",
"{name} is left out: it is this magpie": "已排除 {name}:它就是本機 magpie",
"API key {masked}": "API 金鑰 {masked}",
"Local servers need no key": "本地服務無需金鑰",
"Open the row and paste an API key": "展開這一行並貼上 API 金鑰",
@@ -10856,6 +10868,12 @@ const I18N = {
"{agent} is back on its default": "{agent} をデフォルトに戻しました",
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} はまだ {model} を使っていますが、magpie はもう提供していません:{error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "オフ:エージェントにそのモデルは渡されず、リクエストも送られません。キーと設定は保持されます。オンにすると再び使えます。",
"This magpie": "この magpie",
"This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.": "このリモート magpie はこの magpie 自身です。それでも使用中:モデルがこの magpie 自身のモデルと並んで表示され、これを通るリクエストはこの magpie を 2 回通ります。",
"This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.": "このリモート magpie はこの magpie 自身です:この magpie を使う別のコンピューターから同期で届きました。除外されているため、モデルは二重に表示されず、そのモデルへのリクエストはここで直接処理されます。",
"Use it anyway": "それでも使う",
"{name} is used anyway": "{name} をそれでも使います",
"{name} is left out: it is this magpie": "{name} を除外しました:この magpie 自身です",
"API key {masked}": "APIキー {masked}",
"Local servers need no key": "ローカルサーバーにキーは不要です",
"Open the row and paste an API key": "行を開いて APIキーを貼り付けてください",
@@ -15468,6 +15486,12 @@ const I18N = {
"{agent} is back on its default": "{agent} nutzt wieder sein Standardmodell",
"{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} nutzt noch {model}, das magpie nicht mehr bereitstellt: {error}",
"Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "Ausgeschaltet: Agenten erhalten seine Modelle nicht, und keine Anfrage geht an ihn. Schlüssel und Einstellungen bleiben erhalten; zum erneuten Verwenden einschalten.",
"This magpie": "Dieses magpie",
"This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.": "Dieses Remote-magpie ist dieses magpie selbst. Es wird trotzdem genutzt: Seine Modelle stehen neben den eigenen dieses magpie, und eine Anfrage darüber läuft zweimal durch dieses magpie.",
"This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.": "Dieses Remote-magpie ist dieses magpie selbst: Die Synchronisierung hat es von einem Computer gebracht, der dieses nutzt. Es bleibt außen vor, damit seine Modelle nicht doppelt erscheinen; eine Anfrage nach einem davon wird gleich hier bedient.",
"Use it anyway": "Trotzdem nutzen",
"{name} is used anyway": "{name} wird trotzdem genutzt",
"{name} is left out: it is this magpie": "{name} bleibt außen vor: Es ist dieses magpie",
"API key {masked}": "API-Schlüssel {masked}",
"Local servers need no key": "Lokale Server brauchen keinen Schlüssel",
"Open the row and paste an API key": "Zeile aufklappen und API-Schlüssel einfügen",
+14 -1
View File
@@ -251,6 +251,11 @@ type providerJSON struct {
// RestartApp: magpie restarts the Codex app's app-server for an
// account change it makes by itself (provider.Provider.RestartApp)
RestartApp bool `json:"restartApp,omitempty"`
// Self: a Remote magpie that turned out to be this magpie (sync
// brought it from the computer that uses this one), left out of
// routing unless KeepSelf (provider.Provider.SelfAnswered)
Self bool `json:"self,omitempty"`
KeepSelf bool `json:"keepSelf,omitempty"`
// CapStop and CapCareful: how its accounts end at their caps
// (plugins#349), set on their own with capstop and capcareful
CapStop bool `json:"capStop,omitempty"`
@@ -702,7 +707,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()),
AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM,
@@ -2001,6 +2006,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
in.KeepLogin = old.KeepLogin // set on its own, with keeplogin
in.KeepLoginAs = old.KeepLoginAs
in.SwitchOnly, in.RestartApp = old.SwitchOnly, old.RestartApp // switchonly, restartapp
in.KeepSelf = old.KeepSelf // keepself
in.CapStop, in.CapCareful = old.CapStop, old.CapCareful // capstop, capcareful
in.Off = old.Off // and this with off and on
if in.Contexts == nil {
@@ -2246,6 +2252,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
fail(rw, err)
return
}
case "keepself":
// a Remote magpie that is this magpie, used anyway or left out
// (hanslin1666 on Discord)
if err := provider.SetKeepSelf(in.ID, in.KeepSelf); err != nil {
fail(rw, err)
return
}
case "capstop":
// a request ends at the accounts' caps, 429, or goes on to the
// fallbacks (plugins#349)
+123
View File
@@ -0,0 +1,123 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// hanslin1666 on Discord: B uses A through a Remote magpie, and sync
// carried that provider to A, where it points at A itself. magpie now
// finds it (the list it fetches was listed by this magpie) and leaves it
// out. Its row says "This magpie", its editor says why, and "Use it
// anyway" keeps it in: ticking posts provider/keepself, the redraw keeps
// it ticked, unticking posts it off. Another Remote magpie says nothing.
// The page doesn't move. In English, Chinese, Japanese and German,
// Chromium and WebKit, at 1100 and 420 wide.
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 remote = (id, name, more = {}) => ({
id, name, preset: "remote-magpie", icon: "magpie", host: "192.168.1.20:3425", chat: "http://192.168.1.20:3425/v1", responses: "", anthropic: "", catalog: "", routing: "",
models: [{ id: "own/m1", name: "m1", on: true }], agents: [], fallback: [], headers: {}, keyList: [], key: { set: true, masked: "mg-…a1b2" }, ready: true, ...more,
});
function serve(lang, first, posts) {
let list = first;
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });
return async (route) => {
const url = new URL(route.request().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/providers") return json(providers());
if (url.pathname === "/api/provider/keepself") {
const body = route.request().postDataJSON();
posts.push(body);
list = list.map((p) => p.id === body.id ? { ...p, keepSelf: body.keepSelf } : p);
return json(providers());
}
if (url.pathname === "/api/groups") return json({ groups: [] });
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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const said = {
en: ["This magpie", "Use it anyway"],
zh: ["本机 magpie", "仍然使用"],
ja: ["この magpie", "それでも使う"],
de: ["Dieses magpie", "Trotzdem nutzen"],
};
const strings = [
"This magpie",
"This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.",
"This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.",
"Use it anyway",
"{name} is used anyway",
"{name} is left out: it is this magpie",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 420]) {
for (const lang of Object.keys(said)) {
const open = async (t, list) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, list, posts));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider").first().waitFor();
return { page, errors, posts };
};
test(`${engine} ${width} ${lang}: a Remote magpie that is this magpie says so, and Use it anyway keeps it`, async (t) => {
const { page, errors, posts } = await open(t, [remote("home", "Home", { self: true }), remote("office", "Office")]);
const row = page.locator(".row.provider", { hasText: "Home" }).first();
const badge = row.locator(".name .badge", { hasText: said[lang][0] });
assert.equal(await badge.count(), 1, "the row says it is this magpie");
assert.ok((await badge.getAttribute("title")).length > 20, "the badge says why");
assert.match(await badge.getAttribute("class"), /\boff\b/, "left out, it reads as off");
assert.equal(await page.locator(".row.provider", { hasText: "Office" }).locator(".name .badge").count(), 0, "another Remote magpie says nothing");
if (lang === "en") {
const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);
assert.deepEqual(missing, [], "every string has its translations");
}
await row.click();
const note = page.locator(".editor .self-note");
await note.waitFor();
const keep = note.locator("label.tick");
assert.equal((await keep.textContent()).trim(), said[lang][1]);
assert.equal(await keep.locator("input").isChecked(), false);
assert.ok((await note.textContent()).length > said[lang][1].length + 20, "the note says why");
await keep.scrollIntoViewIfNeeded();
const box = await note.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= width, `the note fits across ${width}`);
const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop));
const before = await scrollers();
await keep.locator("input").click();
await page.waitForFunction(() => document.querySelector(".editor .self-note input")?.checked === true);
assert.deepEqual(posts, [{ id: "home", keepSelf: true }]);
await page.waitForFunction(() => [...document.querySelectorAll(".row.provider[data-id=home] .name .badge")].some((b) => b.title && !b.classList.contains("off")));
assert.deepEqual(await scrollers(), before, "the page doesn't move");
assert.doesNotMatch(await badge.getAttribute("class"), /\boff\b/, "kept, it no longer reads as off");
await page.locator(".editor .self-note input").click();
await page.waitForFunction(() => document.querySelector(".editor .self-note input")?.checked === false);
await page.waitForFunction(() => document.querySelector(".row.provider[data-id=home] .name .badge[title].off"));
assert.deepEqual(posts, [{ id: "home", keepSelf: true }, { id: "home", keepSelf: false }]);
await page.keyboard.press("Escape");
await page.locator(".editor").waitFor({ state: "detached" });
await page.locator(".row.provider", { hasText: "Office" }).first().click();
await page.locator(".editor .ehead", { hasText: "Office" }).waitFor();
assert.equal(await page.locator(".editor .self-note").count(), 0, "another Remote magpie's editor has no note");
assert.deepEqual(errors, []);
});
}
}
}
+8 -2
View File
@@ -44,11 +44,14 @@ func Restore(ps []Provider) (added, replaced int, err error) {
}
}
if i < 0 {
p.KeepSelf = false
f.Providers = append(f.Providers, p)
added++
continue
}
keepSelf := f.Providers[i].KeepSelf // this computer's own (Mirror)
f.Providers[i] = KeepSecrets(p, f.Providers[i], p.Key == "" && len(p.Keys) == 0)
f.Providers[i].KeepSelf = keepSelf
replaced++
}
if added+replaced == 0 {
@@ -92,8 +95,9 @@ func RestoreGroups(gs []Group) error {
// from another computer: one not among them goes, one that came without
// keys keeps the keys it has here, and an access key or balance token it
// came without is kept too (KeepSecrets). Which account an agent is kept
// signed in to (KeepLogin, KeepLoginAs, SwitchOnly), and whether its app is
// restarted to follow (RestartApp), is this computer's own:
// signed in to (KeepLogin, KeepLoginAs, SwitchOnly), whether its app is
// restarted to follow (RestartApp), and whether a Remote magpie that is
// this magpie is used anyway (KeepSelf), is this computer's own:
// one person signs in to a personal account at home and a work account at
// the office, and sync set each computer to the other's every day.
func Mirror(ps []Provider, gs []Group) error {
@@ -114,8 +118,10 @@ func Mirror(ps []Provider, gs []Group) error {
if h, ok := here[p.ID]; ok {
p = KeepSecrets(p, h, p.Key == "" && len(p.Keys) == 0)
p.KeepLogin, p.KeepLoginAs, p.SwitchOnly, p.RestartApp = h.KeepLogin, h.KeepLoginAs, h.SwitchOnly, h.RestartApp
p.KeepSelf = h.KeepSelf
} else {
p.KeepLoginAs = "" // an account signed in on the other computer
p.KeepSelf = false // kept on the other computer, of a magpie that isn't this one
}
out = append(out, p)
}
+1 -1
View File
@@ -1136,7 +1136,7 @@ func unpicked(find entryOf, p Provider, m string) bool {
// Resolve, which still takes it.
func ResolveRoute(id string) (Provider, string, bool) {
entries := providerEntries()
p, m, ok := resolveIn(entries, strings.TrimSuffix(strings.TrimSpace(id), "[1m]"))
p, m, ok := resolveIn(entries, ThroughSelf(strings.TrimSuffix(strings.TrimSpace(id), "[1m]")))
// one pass for the one model, not a map of every entry (entriesBy):
// a request asks it for each fallback it may go to
find := func(pid, model string) int {
+11 -2
View File
@@ -423,8 +423,17 @@ func relistPicks(q *Provider, now map[string]bool) bool {
return true
}
// fetch is Fetch without the picks looked after.
// fetch is Fetch without the picks looked after. A Remote magpie's list
// also tells whether it is this magpie (noteSelf).
func (p Provider) fetch(ctx context.Context) ([]catalog.Model, error) {
ms, err := p.fetchList(ctx)
if err == nil {
noteSelf(p, ms)
}
return ms, err
}
func (p Provider) fetchList(ctx context.Context) ([]catalog.Model, error) {
ctx = p.ownRequests(p.Via(ctx), probelog.KindList)
if p.DecideOnly() {
return p.fetchDecide(ctx)
@@ -3240,7 +3249,7 @@ func entryIn(entries []Entry, id string) (Entry, bool) {
func Resolve(id string) (Provider, string, bool) {
// Claude Code's mark for a model with a 1M window; it drops it before
// asking, but a value in its settings still has it
id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]")
id = ThroughSelf(strings.TrimSuffix(strings.TrimSpace(id), "[1m]"))
if IsGroupRef(id) {
// the groups' entries first: Catalog copies every entry, and was
// built for each group an agent's settings name (the window's drift
+12 -5
View File
@@ -178,6 +178,12 @@ type Provider struct {
// used-up account (a switch off it, becoming its provider for it)
// restart it either way: the app greys Send there (8b0132b3d).
RestartApp bool `json:"restartApp,omitempty"`
// KeepSelf, on a Remote magpie that turned out to be this magpie
// (SelfAnswered), keeps it in routing anyway: left alone, such a
// provider is left out (SelfLeftOut). It is this computer's own, as
// sync's copy of the provider on the other computer points at a
// magpie that is not that one (hanslin1666 on Discord).
KeepSelf bool `json:"keepSelf,omitempty"`
// MaxConcurrency is how many requests may be out at the vendor at once
// on each of its keys or accounts (Discord, Lemon: a Codex account is
@@ -2250,9 +2256,10 @@ func (p Provider) Ready() bool {
return p.Account != nil || p.Key != "" || keyOptional(p)
}
// On is whether the provider takes requests: ready, not switched off and
// not kept to its agent's own sign-in (KeptToAgent).
func (p Provider) On() bool { return p.Ready() && !p.Off && !p.KeptToAgent() }
// On is whether the provider takes requests: ready, not switched off,
// not kept to its agent's own sign-in (KeptToAgent) and not a Remote
// magpie that is this magpie (SelfLeftOut).
func (p Provider) On() bool { return p.Ready() && !p.Off && !p.KeptToAgent() && !p.SelfLeftOut() }
// KeptToAgent is whether the provider is Claude's subscription with
// SwitchOnly on: its accounts are Claude Code's own sign-in alone, which
@@ -2282,12 +2289,12 @@ func SetOff(id string, off bool) error {
func SwitchedOff(id string) (Provider, bool) {
id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]")
if pid, _, ok := strings.Cut(id, "/"); ok {
if p, err := Find(pid); err == nil && (p.Off || p.KeptToAgent()) {
if p, err := Find(pid); err == nil && (p.Off || p.KeptToAgent() || p.SelfLeftOut()) {
return *p, true
}
}
for _, p := range All() {
if !p.Off && !p.KeptToAgent() || !p.Ready() {
if !p.Off && !p.KeptToAgent() && !p.SelfLeftOut() || !p.Ready() {
continue
}
if slices.ContainsFunc(p.Exposed(), func(m catalog.Model) bool { return m.ID == id }) {
+1 -1
View File
@@ -207,7 +207,7 @@ func ForgetKeptCardsForTest() {
func remoteMagpies() []Provider {
var out []Provider
for _, p := range All() {
if p.IsRemoteMagpie() && !p.Hidden && !p.Off && p.Key != "" && p.Anthropic != "" {
if p.IsRemoteMagpie() && !p.Hidden && !p.Off && !p.SelfLeftOut() && p.Key != "" && p.Anthropic != "" {
out = append(out, p)
}
}
+214
View File
@@ -0,0 +1,214 @@
package provider
// A Remote magpie that is this magpie itself (hanslin1666 on Discord):
// computer B uses A through a Remote magpie provider, sync carries that
// provider to A, and on A it points at A. Each of its models is one of
// A's own, a request for it a pass more through A's gateway on its way
// there, and each one stands beside the model it is in A's lists and
// groups. The list A fetches from it says so: each model's magpie_via
// ends with the magpie that listed it (catalog.ViaHere), and that is A's
// own catalog.Self. So the fetch keeps, in remote-self.json, that this
// provider at this address is this magpie, and the provider is left out
// of routing and lists (SelfLeftOut), unless the user keeps it anyway
// (KeepSelf, the editor's "Use it anyway").
//
// The file is this computer's own: it is never in a backup or a sync, as
// B's copy of the provider points at A, which is not B. Self is made up
// again each run, so the record is what stands between runs, until the
// next fetch: one whose lister is another magpie, or one from before
// magpie_via, which names none, takes it away. An empty list or a failed
// fetch tells nothing and changes nothing. The record holds the address
// it was found at: a provider moved to another address is not this
// magpie until a fetch there says so.
import (
"encoding/json"
"errors"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/filelock"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/steady"
)
// LeaveOutSelf is whether a Remote magpie found to be this magpie is left
// out. The gateway's tests serve their Remote magpie from their own
// process, and turn it off.
var LeaveOutSelf = true
func remoteSelfPath() string { return filepath.Join(settings.Dir(), "remote-self.json") }
var remoteSelfMu = filelock.Mutex{Path: func() string { return remoteSelfPath() + ".lock" }}
// remoteSelf is the file as read, by provider id the address it answered
// as this magpie at, for the settings folder it was read from.
var remoteSelf struct {
sync.RWMutex
path string
ids map[string]string
}
// readRemoteSelf reads the file. None yet is no record; one that can't be
// read or parsed is an error.
func readRemoteSelf(path string) (map[string]string, error) {
b, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return map[string]string{}, nil
}
if err != nil {
return nil, err
}
ids := map[string]string{}
if err := json.Unmarshal(b, &ids); err != nil {
return nil, err
}
return ids, nil
}
// selfAt is the address provider id was found to be this magpie at, if
// it was. A file that can't be read records nothing: the provider is
// served as it was before, until a fetch writes the file again.
func selfAt(id string) (string, bool) {
path := remoteSelfPath()
remoteSelf.RLock()
if remoteSelf.path == path {
at, ok := remoteSelf.ids[id]
remoteSelf.RUnlock()
return at, ok
}
remoteSelf.RUnlock()
remoteSelf.Lock()
defer remoteSelf.Unlock()
if remoteSelf.path != path {
ids, err := readRemoteSelf(path)
if err != nil {
log.Printf("%s: %v", path, err)
ids = map[string]string{}
}
remoteSelf.path, remoteSelf.ids = path, ids
}
at, ok := remoteSelf.ids[id]
return at, ok
}
// anySelf says some provider was found to be this magpie: the fast way
// past ThroughSelf for everyone else.
func anySelf() bool {
selfAt("") // loaded for this settings folder
remoteSelf.RLock()
defer remoteSelf.RUnlock()
return len(remoteSelf.ids) > 0
}
// selfRoot is the address a record is kept by: the provider's Chat, as
// remoteMagpieEndpoints wrote it.
func (p Provider) selfRoot() string { return strings.TrimRight(strings.TrimSpace(p.Chat), "/") }
// SelfAnswered says this Remote magpie was found to be this magpie, at
// the address it has now.
func (p Provider) SelfAnswered() bool {
if !p.IsRemoteMagpie() {
return false
}
at, ok := selfAt(p.ID)
return ok && at == p.selfRoot()
}
// SelfLeftOut is whether the provider is left out of routing and lists as
// a Remote magpie that is this magpie, which the user didn't keep.
func (p Provider) SelfLeftOut() bool {
return LeaveOutSelf && !p.KeepSelf && p.SelfAnswered()
}
// noteSelf keeps what a Remote magpie's fetched list says of whether it is
// this magpie: the magpie that listed a model is its magpie_via's last.
func noteSelf(p Provider, ms []catalog.Model) {
if !p.IsRemoteMagpie() || len(ms) == 0 {
return
}
self := false
for _, m := range ms {
if len(m.Via) > 0 {
self = m.Via[len(m.Via)-1] == catalog.Self()
break
}
}
at, was := selfAt(p.ID)
if self == (was && at == p.selfRoot()) {
return
}
remoteSelfMu.Lock()
defer remoteSelfMu.Unlock()
path := remoteSelfPath()
ids, err := readRemoteSelf(path)
if err != nil {
// a record a fetch made, and the next fetch makes again
log.Printf("%s: %v; written again", path, err)
ids = map[string]string{}
}
if self {
ids[p.ID] = p.selfRoot()
} else {
delete(ids, p.ID)
}
b, _ := json.MarshalIndent(ids, "", " ")
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
log.Printf("%s: %v", path, err)
return
}
if err := steady.WriteFile(path, b, 0o600); err != nil {
log.Printf("%s: %v", path, err)
return
}
remoteSelf.Lock()
remoteSelf.path, remoteSelf.ids = path, ids
remoteSelf.Unlock()
if self {
log.Printf("%s: this Remote magpie is this magpie itself; left out of routing unless kept (Providers → %s → Use it anyway)", p.ID, p.Name)
}
}
// ThroughSelf is the model id a request names with a Remote magpie that is
// this magpie, and left out, taken off the front: rem/own/m1 is own/m1
// here, as it is on the other computer, whose agents' picks sync brings
// over (hanslin1666).
func ThroughSelf(id string) string {
if !anySelf() {
return id
}
for range catalog.MaxVia {
pid, rest, ok := strings.Cut(id, "/")
if !ok || rest == "" {
return id
}
if _, ok := selfAt(pid); !ok {
return id
}
p, err := Find(pid)
if err != nil || p.ID != pid || !p.SelfLeftOut() {
return id
}
id = rest
}
return id
}
// SetKeepSelf keeps a Remote magpie that is this magpie in routing, or
// leaves it out again (Provider.KeepSelf).
func SetKeepSelf(id string, keep bool) error {
p, err := Find(id)
if err != nil {
return err
}
if !p.IsRemoteMagpie() {
return errors.New(p.Name + " is not a Remote magpie")
}
p.KeepSelf = keep
return Save(*p)
}
+154
View File
@@ -0,0 +1,154 @@
package provider
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/settings"
)
// A Remote magpie's list says which magpie listed each model (the last of
// its magpie_via). One this magpie listed is this magpie: the provider is
// left out, and the record outlives the run (Self is made up again each
// one) until a list another magpie gives, or one from before magpie_via,
// says otherwise. An empty list or a failed fetch changes nothing, and a
// provider moved to another address is not this magpie there.
func TestRemoteSelfRecord(t *testing.T) {
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
var answer atomic.Value // the list the remote gives
var down atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if down.Load() {
http.Error(w, "down", http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, answer.Load().(string))
}))
t.Cleanup(srv.Close)
list := func(lister string) string {
via := ""
if lister != "" {
via = `,"magpie_via":["` + lister + `"]`
}
return `{"object":"list","data":[{"id":"own/m1","object":"model"` + via + `}]}`
}
id, err := Add(Provider{ID: "rem", Name: "Rem", Preset: RemoteMagpiePreset, Chat: strings.TrimPrefix(srv.URL, "http://")})
if err != nil {
t.Fatal(err)
}
fetch := func() Provider {
t.Helper()
p, err := Find(id)
if err != nil {
t.Fatal(err)
}
p.Fetch(context.Background())
p, _ = Find(id)
return *p
}
answer.Store(list("another"))
if p := fetch(); p.SelfAnswered() || !p.On() {
t.Fatalf("another magpie's list: self %v, on %v", p.SelfAnswered(), p.On())
}
if _, err := os.Stat(filepath.Join(settings.Dir(), "remote-self.json")); err == nil {
t.Error("another magpie's list wrote a record")
}
answer.Store(list(catalog.Self()))
if p := fetch(); !p.SelfAnswered() || !p.SelfLeftOut() || p.On() {
t.Fatalf("this magpie's list: self %v, left out %v, on %v", p.SelfAnswered(), p.SelfLeftOut(), p.On())
}
if got := ThroughSelf("rem/own/m1"); got != "own/m1" {
t.Errorf("ThroughSelf(rem/own/m1) = %q, want own/m1", got)
}
if got := ThroughSelf("rem/rem/own/m1"); got != "own/m1" {
t.Errorf("ThroughSelf(rem/rem/own/m1) = %q, want own/m1", got)
}
if got := ThroughSelf("other/m1"); got != "other/m1" {
t.Errorf("ThroughSelf(other/m1) = %q", got)
}
if p, ok := SwitchedOff("rem/x/y"); !ok || p.ID != "rem" {
t.Errorf("SwitchedOff(rem/x/y) = %q %v; want the left-out remote", p.ID, ok)
}
// the record is read again in another run, from the file
remoteSelf.Lock()
remoteSelf.path = ""
remoteSelf.Unlock()
if p, _ := Find(id); !p.SelfAnswered() {
t.Fatal("the record didn't outlive the run")
}
// an empty list and a failed fetch tell nothing
answer.Store(`{"object":"list","data":[]}`)
if p := fetch(); !p.SelfAnswered() {
t.Error("an empty list took the record away")
}
down.Store(true)
if p := fetch(); !p.SelfAnswered() {
t.Error("a failed fetch took the record away")
}
down.Store(false)
// moved to another address: not this magpie there
p, _ := Find(id)
moved := *p
moved.Chat = "http://192.0.2.1:3425/v1"
if moved.SelfAnswered() {
t.Error("a provider at another address is taken for this magpie")
}
// a magpie from before magpie_via names none: no longer this one
answer.Store(list(""))
if p := fetch(); p.SelfAnswered() || !p.On() {
t.Errorf("a list from before magpie_via: self %v, on %v", p.SelfAnswered(), p.On())
}
if got := ThroughSelf("rem/own/m1"); got != "rem/own/m1" {
t.Errorf("ThroughSelf after the record went = %q", got)
}
}
// Use it anyway is this computer's own: sync brings the provider from the
// computer it is not this magpie on, and a backup put back here keeps it.
func TestMirrorKeepsKeepSelf(t *testing.T) {
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
if err := Save(Provider{ID: "rem", Name: "Rem", Preset: RemoteMagpiePreset, Chat: "http://192.0.2.1:3425/v1", Key: "k", KeepSelf: true}); err != nil {
t.Fatal(err)
}
other := Provider{ID: "rem", Name: "Rem renamed", Preset: RemoteMagpiePreset, Chat: "http://192.0.2.1:3425/v1", Key: "k"}
fresh := Provider{ID: "rem2", Name: "Rem 2", Preset: RemoteMagpiePreset, Chat: "http://192.0.2.2:3425/v1", Key: "k", KeepSelf: true}
if err := Mirror([]Provider{other, fresh}, nil); err != nil {
t.Fatal(err)
}
ps, _ := Stored()
if len(ps) != 2 || ps[0].Name != other.Name || !ps[0].KeepSelf || ps[1].KeepSelf {
for _, p := range ps {
t.Logf("%s %q KeepSelf %v", p.ID, p.Name, p.KeepSelf)
}
t.Fatal("mirrored: want the other's name, this computer's KeepSelf, none on the new one")
}
if _, _, err := Restore([]Provider{other, {ID: "rem3", Name: "Rem 3", Preset: RemoteMagpiePreset, Chat: "http://192.0.2.3:3425/v1", Key: "k", KeepSelf: true}}); err != nil {
t.Fatal(err)
}
ps, _ = Stored()
for _, p := range ps {
if p.ID == "rem" && !p.KeepSelf || p.ID == "rem3" && p.KeepSelf {
t.Errorf("restored %s: KeepSelf %v", p.ID, p.KeepSelf)
}
}
}