diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index a9c890383..80a461de6 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -207,6 +207,19 @@ a group made on the remote is a model of its list, offered at once (`TestRemoteMagpieNewGroupServedBesidePicks`). `TestConnectFollowsTheRemoteMagpiesPicks`, `TestSharedModelsTellsTheRefs`. +An agent installed here that isn't connected is left alone, unless the +remote's editor has "Connect new agents to this remote" on (Advanced, off +by default; kept per computer in the stash as +`remote..connectAgents`, `agent.SetConnectAgents`). Then the same +follow connects an agent the remote has connected, on the remote's pick +(`connectFromRemote`), and records it as `.remote.auto`. An agent +the user disconnected here is never connected again: one with the +Disconnect mark, and one recorded `on` that is no longer connected +(taken out by hand in its file) is recorded `off`. An agent magpie put +back on quit (`quit.restored`) is left to RewireOnStart. Connecting it +by hand records `on` again. `TestRemoteConnectsNewAgents`, +`TestProviderSaveConnectAgents`. + The CLI and TUI report model-list fetch errors for remote and other mixed providers (such as OpenRouter, serving conversation and decision models). Only a decision-only provider keeps the separate decision discovery behavior diff --git a/internal/agent/remote_connect_test.go b/internal/agent/remote_connect_test.go new file mode 100644 index 000000000..391998ba5 --- /dev/null +++ b/internal/agent/remote_connect_test.go @@ -0,0 +1,122 @@ +package agent + +import ( + "context" + "net/http/httptest" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// KoiLx0 on X: every agent on a client magpie had to be switched on by +// hand before it took the remote's models. With the Remote magpie's +// switch on (off by default), an agent installed here that the remote has +// connected is connected on the follow loop, on the remote's pick; one +// the remote hasn't connected is left alone; and one the user +// disconnected here, by the Agents page or by hand in its file, is never +// connected again, until the user connects it themselves. +func TestRemoteConnectsNewAgents(t *testing.T) { + home, _ := codexHome(t, "", "") + resetRemoteCache() + t.Cleanup(resetRemoteCache) + fake := &remotePicksFake{picks: map[string]map[string]string{}} + fake.set("claude", "model", "group/fast") + srv := httptest.NewServer(fake) + defer srv.Close() + if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Chat: srv.URL, Key: "secret", + Models: []string{"group/smart", "group/fast"}}); err != nil { + t.Fatal(err) + } + path := filepath.Join(home, ".claude", "settings.json") + own := `{"model": "opus"}` + writeFile(t, path, own) + c := claude(home) + ctx := context.Background() + tick := func() { connectFromRemote([]*Agent{c}, remotePicks(ctx, 0)) } + + // off by default: nothing connected + tick() + if c.Wired() || readFile(path) != own { + t.Fatalf("connected with the switch off:\n%s", readFile(path)) + } + if ConnectsAgents()["office"] { + t.Fatal("the switch is on by default") + } + + // on: connected on the remote's pick + SetConnectAgents("office", true) + if !ConnectsAgents()["office"] { + t.Fatal("the switch didn't turn on") + } + tick() + if !c.Wired() || writtenModel(path) != "office/group/fast" { + t.Fatalf("not connected on the remote's group/fast: on %q\n%s", writtenModel(path), readFile(path)) + } + + // disconnected on the Agents page: never again + if err := c.Disconnect(); err != nil { + t.Fatal(err) + } + tick() + tick() + if c.Wired() { + t.Fatal("an agent the user disconnected was connected again") + } + + // connected by hand: the switch follows it again; then taken out by + // hand in its file (no Disconnect mark): never again either + if err := c.Connect(); err != nil { + t.Fatal(err) + } + tick() + if got := stashShared()[autoKey(c.ID)]; got != "on" { + t.Fatalf("connected by hand, recorded %q", got) + } + writeFile(t, path, own) + if c.Wired() || c.Disconnected() { + t.Fatal("the file written by hand should leave it unconnected, unmarked") + } + tick() + tick() + if c.Wired() { + t.Fatal("an agent the user disconnected by hand in its file was connected again") + } + + // an agent the remote hasn't connected stays as it is + forget(autoKey(c.ID), c.ID+disconnectedKey) + fake.mu.Lock() + delete(fake.picks, "claude") + fake.mu.Unlock() + tick() + if c.Wired() { + t.Fatal("connected an agent the remote hasn't connected") + } + + // disconnected on the Agents page before the switch was on (no record + // of its own): not connected + fake.set("claude", "model", "group/fast") + stash(map[string]string{c.ID + disconnectedKey: "1"}) + tick() + if c.Wired() { + t.Fatal("an agent marked disconnected, never recorded, was connected") + } + forget(c.ID + disconnectedKey) + + // put back by magpie on quit (RewireOnStart connects it again): not + // connected here, and not taken for a disconnect by hand + fake.set("claude", "model", "group/fast") + stash(map[string]string{autoKey(c.ID): "on", quitRestoredKey: `["claude"]`}) + tick() + if c.Wired() || stashShared()[autoKey(c.ID)] != "on" { + t.Fatalf("a quit-restored agent: wired %v, recorded %q", c.Wired(), stashShared()[autoKey(c.ID)]) + } + forget(quitRestoredKey) + + // the switch off: nothing connected + SetConnectAgents("office", false) + tick() + if c.Wired() { + t.Fatal("connected with the switch turned off") + } +} diff --git a/internal/agent/remote_picks.go b/internal/agent/remote_picks.go index 57aed6d39..39076d1e2 100644 --- a/internal/agent/remote_picks.go +++ b/internal/agent/remote_picks.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "log" + "slices" "strings" "sync" "time" @@ -159,15 +160,26 @@ func (a *Agent) connectRemote() (c Connection, ok bool, err error) { return c, a.Wired(), nil } -var lastFollow time.Time +var followed struct { + sync.Mutex + last time.Time +} // FollowRemotePicks puts each connected agent's field that is on a Remote // magpie's pick onto that pick's change, at most every FollowRemoteEvery. func FollowRemotePicks(ctx context.Context) { - if time.Since(lastFollow) < FollowRemoteEvery || !provider.HasPickedMagpie() { + if !provider.HasPickedMagpie() { + return + } + followed.Lock() + due := time.Since(followed.last) >= FollowRemoteEvery + if due { + followed.last = time.Now() + } + followed.Unlock() + if !due { return } - lastFollow = time.Now() followRemote(ctx) } @@ -196,7 +208,9 @@ func followRemote(ctx context.Context) { if len(picks) == 0 { return } - for _, a := range DetectedIn(All()) { + as := DetectedIn(All()) + connectFromRemote(as, picks) + for _, a := range as { if a.Native != nil || a.Disconnected() || !a.Wired() { continue } @@ -204,6 +218,98 @@ func followRemote(ctx context.Context) { } } +// Connecting new agents from a Remote magpie (KoiLx0 on X: each agent +// still had to be switched on by hand on every client). The remote's +// editor, under Advanced, has a switch, off by default and kept on this +// computer alone (remoteConnectKey). While it is on, an agent installed +// here that the remote has connected, and that isn't connected here, is +// connected on the follow loop, on the remote's picks. +// +// - An agent the user disconnected here is never connected again: by +// the Agents page (its disconnectedKey mark), or by any other hand +// once it was connected (autoKey "off": seen connected, then not). +// - One a quit put back (RestoreOnQuit) is RewireOnStart's to connect. +// - Connecting it by hand again ends the "off": it is followed as any +// other from then on. + +func remoteConnectKey(provider string) string { return "remote." + provider + ".connectAgents" } + +// autoKey records, per agent, what the switch saw: "on" while it is +// connected, "off" once it was disconnected here. +func autoKey(id string) string { return id + ".remote.auto" } + +// ConnectsAgents reports, by Remote magpie id, whose switch is on. +func ConnectsAgents() map[string]bool { + out := map[string]bool{} + const pre, suf = "remote.", ".connectAgents" + for k, v := range stashShared() { + if v == "1" && strings.HasPrefix(k, pre) && strings.HasSuffix(k, suf) && len(k) > len(pre)+len(suf) { + out[k[len(pre):len(k)-len(suf)]] = true + } + } + return out +} + +// SetConnectAgents turns the switch of the Remote magpie id on or off. On, +// the next follow (FollowRemotePicks) is not waited for. +func SetConnectAgents(id string, on bool) { + if on { + stash(map[string]string{remoteConnectKey(id): "1"}) + followed.Lock() + followed.last = time.Time{} + followed.Unlock() + return + } + forget(remoteConnectKey(id)) +} + +func connectFromRemote(as []*Agent, picks []provider.RemotePicks) { + on := ConnectsAgents() + if len(on) == 0 { + return + } + var restored []string + json.Unmarshal([]byte(stashShared()[quitRestoredKey]), &restored) + for _, a := range as { + if a.Native != nil || len(a.Fields) == 0 { + continue + } + wanted := false + for _, rp := range picks { + if on[rp.Provider] && len(rp.Agents[a.ID]) > 0 { + wanted = true + break + } + } + if !wanted { + continue + } + rec := stashShared()[autoKey(a.ID)] + switch { + case a.Wired(): + if rec != "on" { + stash(map[string]string{autoKey(a.ID): "on"}) + } + continue + case rec == "on" && !slices.Contains(restored, a.ID): + // connected, now not: disconnected here, by the user's hand + stash(map[string]string{autoKey(a.ID): "off"}) + continue + case rec == "off" || a.Disconnected() || slices.Contains(restored, a.ID): + continue + } + c, err := a.ConnectHow() + if err != nil { + log.Printf("agent: %s, connected as the remote magpie's: %v", a.Name, err) + continue + } + if a.Wired() { + stash(map[string]string{autoKey(a.ID): "on"}) + log.Printf("agent: %s connected as the remote magpie's (%s)", a.Name, c.How) + } + } +} + // followRemote is followRemote for one agent. func (a *Agent) followRemote(picks []provider.RemotePicks) { for _, f := range a.Fields { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 50e9067d0..8f9b03cc0 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -8048,7 +8048,7 @@ function advancedSet(d, p) { [d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) || !!d.rateWindows?.length || !!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.billing || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.noBalanceProbe || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA || d.serverPin || d.resolve) || - !!d.fallback?.length || !!p?.balanceToken?.set; + !!d.fallback?.length || !!(p?.balanceToken?.set || p?.connectAgents); } function priceRateError(ed) { shown(ed.querySelector("input.price-rate"))?.focus(NO_SCROLL); @@ -9910,15 +9910,19 @@ function drawEditor(p, presetID) { } // off when added if ((p?.preset || pr?.id) === "remote-magpie" && !p?.account) { - const [l, c] = tick(t("Add its MCP servers to the Library"), (draft.libraryMCP ??= !!p?.libraryMCP)); - l.classList.add("library-mcp"); - c.onchange = () => (draft.libraryMCP = c.checked); - ed.append(...field(t("MCP servers"), l)); - // KoiLx0 on X - const [l2, c2] = tick(t("Use its skills and prompts"), (draft.libraryShared ??= !!p?.libraryShared)); - l2.classList.add("library-shared"); - c2.onchange = () => (draft.libraryShared = c2.checked); - ed.append(...field(t("Skills and prompts"), l2)); + // KoiLx0 on X: its skills and prompts; an agent connected there, + // installed here, connected here too, one disconnected here stays so + // (agent.SetConnectAgents) + for (const [k, say, head, to] of [ + ["libraryMCP", t("Add its MCP servers to the Library"), t("MCP servers"), ed], + ["libraryShared", t("Use its skills and prompts"), t("Skills and prompts"), ed], + ["connectAgents", t("Connect new agents to this remote"), t("Agents"), advIn], + ]) { + const [l, c] = tick(say, (draft[k] ??= !!p?.[k])); + l.classList.add(k.replace(/(?=[A-Z])/, "-").toLowerCase()); + c.onchange = () => (draft[k] = c.checked); + to.append(...field(head, l)); + } } // lcc580 on X if ((p?.preset || pr?.id) === "remote-magpie") { @@ -10412,8 +10416,7 @@ function drawEditor(p, presetID) { if (p?.takesListOff) body.listOff = !!draft.listOff; if (p) { body.fallback = draft.fallback; body.unlisted = draft.unlisted; body.hiddenDrawers = draft.hiddenDrawers; body.hiddenVideomakers = draft.hiddenVideomakers; body.noModels = noneChosen(); body.bestInFamily = bestChosen(); body.modelPrefs = modelPrefsOfDraft(); Object.assign(body, routingOfDraft(p)); } body.searches = !!draft.searches && searchable(); - if (draft.libraryMCP != null) body.libraryMCP = draft.libraryMCP; - if (draft.libraryShared != null) body.libraryShared = draft.libraryShared; + for (const k of ["libraryMCP", "libraryShared", "connectAgents"]) if (draft[k] != null) body[k] = draft[k]; body.pinUpstream = !!draft.pinUpstream; if (twoKeyHeaders()) body.authHeader = draft.authHeader || ""; body.unredacted = !!draft.unredacted; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 989f27a49..9c7e26b18 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3023,6 +3023,7 @@ const I18N = { "Give it a name": "先起个名字", "Add its MCP servers to the Library": "把它的 MCP 服务器加到资源库", "Use its skills and prompts": "使用它的技能和提示词", + "Connect new agents to this remote": "自动接入新 agent", "Skills and prompts": "技能和提示词", "Model names": "模型名", "With the provider serving it there": "带上它那边的供应商(穿透)", @@ -8368,6 +8369,7 @@ const I18N = { "Give it a name": "先起個名字", "Add its MCP servers to the Library": "把它的 MCP 伺服器加到資源庫", "Use its skills and prompts": "使用它的技能和提示詞", + "Connect new agents to this remote": "自動接入新 agent", "Skills and prompts": "技能和提示詞", "Model names": "模型名稱", "With the provider serving it there": "帶上它那邊的供應商(穿透)", @@ -13690,6 +13692,7 @@ const I18N = { "Give it a name": "名前を付けてください", "Add its MCP servers to the Library": "その MCP サーバーをライブラリに追加", "Use its skills and prompts": "そのスキルとプロンプトを使う", + "Connect new agents to this remote": "新しいエージェントを自動で接続する", "Skills and prompts": "スキルとプロンプト", "Model names": "モデル名", "With the provider serving it there": "向こうで提供しているプロバイダーを付ける", @@ -19043,6 +19046,7 @@ const I18N = { "Give it a name": "Vergeben Sie einen Namen", "Add its MCP servers to the Library": "Seine MCP-Server zur Bibliothek hinzufügen", "Use its skills and prompts": "Seine Skills und Prompts verwenden", + "Connect new agents to this remote": "Neue Agenten automatisch verbinden", "Skills and prompts": "Skills und Prompts", "Model names": "Modellnamen", "With the provider serving it there": "Mit dem Anbieter, der es dort bereitstellt", diff --git a/internal/gui/connect_agents_test.go b/internal/gui/connect_agents_test.go new file mode 100644 index 000000000..7505f1d3f --- /dev/null +++ b/internal/gui/connect_agents_test.go @@ -0,0 +1,67 @@ +package gui + +import ( + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/provider" +) + +// KoiLx0 on X: a Remote magpie editor's "Connect new agents to this +// remote" is saved on this computer (agent.SetConnectAgents), shown as +// saved, kept by a save that leaves it out, and refused another provider. +func TestProviderSaveConnectAgents(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := http.NewServeMux() + providerRoutes(mux, nil) + post := func(body string) { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body))) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + } + shown := func(id string) bool { + t.Helper() + for _, p := range providersState().Providers { + if p.ID == id { + return p.ConnectAgents + } + } + t.Fatalf("%s not listed", id) + return false + } + if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Chat: "http://192.168.1.20:3425/v1", Key: "secret"}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "vllm", Name: "vLLM", Chat: "http://192.168.1.21:8000/v1", Key: "k"}); err != nil { + t.Fatal(err) + } + if shown("office") || agent.ConnectsAgents()["office"] { + t.Fatal("on by default") + } + post(`{"id":"office","from":"office","name":"Office","preset":"remote-magpie","chat":"http://192.168.1.20:3425/v1","models":[],"headers":{},"connectAgents":true}`) + if !agent.ConnectsAgents()["office"] || !shown("office") { + t.Fatal("the switch wasn't saved or isn't shown") + } + post(`{"id":"office","from":"office","name":"Office","preset":"remote-magpie","chat":"http://192.168.1.20:3425/v1","models":[],"headers":{}}`) + if !shown("office") { + t.Fatal("a save that left it out turned it off") + } + post(`{"id":"vllm","from":"vllm","name":"vLLM","chat":"http://192.168.1.21:8000/v1","models":[],"headers":{},"connectAgents":true}`) + if agent.ConnectsAgents()["vllm"] { + t.Fatal("a provider that isn't a Remote magpie took the switch") + } + post(`{"id":"office","from":"office","name":"Office","preset":"remote-magpie","chat":"http://192.168.1.20:3425/v1","models":[],"headers":{},"connectAgents":false}`) + if agent.ConnectsAgents()["office"] || shown("office") { + t.Fatal("turning it off didn't") + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 1a5bf20ad..31346a5e3 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -421,6 +421,9 @@ type providerJSON struct { // read said went wrong or was left as the user's (KoiLx0 on X) LibraryShared bool `json:"libraryShared,omitempty"` LibraryNote string `json:"libraryNote,omitempty"` + // ConnectAgents: a Remote magpie whose connected agents are + // connected here too, those installed here (agent.ConnectsAgents) + ConnectAgents bool `json:"connectAgents,omitempty"` // RemoteUpdate: a Remote magpie's word on its last ask to follow // this magpie's version (remoteUpdateNote) RemoteUpdate *remoteUpdateJSON `json:"remoteUpdate,omitempty"` @@ -1522,6 +1525,7 @@ func providersState() providersJSON { desktop := desktopNumbers(uses) have := map[string]bool{} var remoteMCP map[string]bool // read once, at the first Remote magpie + var connects map[string]bool // the same all := provider.All() // both lists made once at their size: each grown by append was 6 MB of // what forty polls of the Providers page allocated with real accounts @@ -1539,6 +1543,10 @@ func providersState() providersJSON { info.LibraryMCP = remoteMCP[p.ID] info.LibraryShared = library.BorrowedOn()[p.ID] info.LibraryNote = library.BorrowNote(p.ID) + if connects == nil { + connects = agent.ConnectsAgents() + } + info.ConnectAgents = connects[p.ID] info.RemoteUpdate = remoteUpdateNote(p.ID, time.Now()) } s.Providers = append(s.Providers, info) @@ -1979,6 +1987,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // LibraryShared, on a Remote magpie, is the switch for its // Library's skills and prompts (library.SetBorrow) LibraryShared *bool `json:"libraryShared"` + // ConnectAgents, on a Remote magpie, is the switch that + // connects here the agents it has connected + // (agent.SetConnectAgents) + ConnectAgents *bool `json:"connectAgents"` // CopyOf, with New, is the provider the new one is a copy of // (#268): its key and what else the form doesn't carry are // taken from it when left out @@ -2718,6 +2730,14 @@ func providerRoutes(mux *http.ServeMux, w Windows) { askHub = *req.LibraryMCP } } + if req.ConnectAgents != nil { + if p, err := provider.Find(in.ID); err == nil && p.IsRemoteMagpie() && agent.ConnectsAgents()[in.ID] != *req.ConnectAgents { + agent.SetConnectAgents(in.ID, *req.ConnectAgents) + if *req.ConnectAgents { + go agent.FollowRemotePicks(context.Background()) + } + } + } if req.LibraryShared != nil { if p, err := provider.Find(in.ID); err == nil && p.IsRemoteMagpie() && library.BorrowedOn()[in.ID] != *req.LibraryShared { if _, err := library.SetBorrow(in.ID, *req.LibraryShared); err != nil { diff --git a/internal/gui/tests/remote-connect-agents.test.cjs b/internal/gui/tests/remote-connect-agents.test.cjs new file mode 100644 index 000000000..fc511ef33 --- /dev/null +++ b/internal/gui/tests/remote-connect-agents.test.cjs @@ -0,0 +1,103 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// KoiLx0 on X: a client magpie had each agent switched on by hand before +// it took the remote's models. A Remote magpie's editor has a switch for +// that, "Connect new agents to this remote", under Advanced: off, and the +// fold closed, while the backend says it is off; sent as ticked; and with +// it on, Advanced opens on it ticked. In every language, both engines, at +// a narrow width with no sideways scroll. No backend: the API is faked. +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 office = () => ({ id: "office", name: "Office", icon: "magpie", preset: "remote-magpie", chat: "http://office/v1", responses: "http://office/v1", anthropic: "http://office", + models: [{ id: "lib/m1", name: "Chat", on: true }], agents: [], key: { set: true, masked: "sk-…ab12" } }); +const presets = [{ id: "remote-magpie", name: "Remote magpie", icon: "magpie", kind: "remote", added: true, endpoint: "http://192.168.1.20:3425" }]; + +function server(lang, state, saves) { + 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:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [state.p], presets, excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/provider/save") { + const body = route.request().postDataJSON(); + saves.push(body); + if (body.connectAgents != null) state.p = { ...state.p, connectAgents: body.connectAgents || undefined }; + return json({ providers: [state.p], presets, excluded: [], gateway: { running: true, window: true } }); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/gateway/trace") return json({ routes: [] }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const L = { + en: "Connect new agents to this remote", + zh: "自动接入新 agent", + "zh-TW": "自動接入新 agent", + ja: "新しいエージェントを自動で接続する", + de: "Neue Agenten automatisch verbinden", +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a Remote magpie's switch to connect new agents, under Advanced", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const [lang, words] of Object.entries(L)) { + await t.test(lang, async () => { + const saves = [], state = { p: office() }; + const page = await (await browser.newContext({ viewport: { width: 420, height: 800 } })).newPage(); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, state, saves)); + await page.goto("http://magpie.test/?view=providers"); + const ed = page.locator(".editor"); + const open = async () => { + await page.locator('#providers .row[data-id="office"]').click(); + await ed.locator(".ehead b", { hasText: "Office" }).waitFor(); + }; + const save = () => Promise.all([page.waitForResponse((r) => r.url().endsWith("/api/provider/save")), ed.locator(".bar button.primary").first().click()]); + + // off: under Advanced, closed + await open(); + const adv = ed.locator("details.advanced"); + const sw = adv.locator(".connect-agents"); + assert.equal(await sw.count(), 1, "the switch is under Advanced"); + assert.equal(await sw.textContent(), words); + assert.equal(await adv.evaluate((d) => d.open), false, "Advanced closed while it is off"); + assert.equal(await sw.locator("input").isChecked(), false); + assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), true, "no sideways scroll"); + + // ticked: sent so + await adv.locator("summary").click(); + await sw.locator("input").check(); + await save(); + assert.equal(saves.at(-1).connectAgents, true); + await page.keyboard.press("Escape"); + await ed.waitFor({ state: "detached" }); + + // on: Advanced opens on it ticked; unticked, sent so + await page.evaluate(() => { advanced = null; }); + await open(); + assert.equal(await adv.evaluate((d) => d.open), true, "Advanced opens while it is on"); + assert.equal(await sw.locator("input").isChecked(), true); + await sw.locator("input").uncheck(); + await save(); + assert.equal(saves.at(-1).connectAgents, false); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + }); +}