providers: a Remote magpie's MCP servers go to the Library only when switched on, and follow its rename

treeman_26897 (Discord) on v0.1.3127's bridge MCP auto-discovery:

- Renamed (name and id), a Remote magpie's auto-added MCP server went:
  adoptBridges keyed it on the provider id, and after provider.Rename
  that id is gone, so the server was taken out as the provider's. Now
  RemoteHub carries the provider's Was, and adoptBridges moves the
  server's bridge, bridgesOn and bridgesOffered from an id it had to
  the id it has (one that another provider has now stays that one's).
  The server keeps its name.
- The add dialog had only the address and key. A new Remote magpie's
  editor has a Name and an ID under the key; blank, they are the
  preset's as before (provider.Add numbers them when taken), and the
  ID follows the name until one is typed.
- Adding its MCP servers is opt-in: a switch, "Add its MCP servers to
  the Library", in the add dialog (off) and in a saved one's editor.
  It lives in library.json (bridgesOn); /api/providers says it as
  libraryMCP and the save takes it (library.SetRemoteMCP). On asks the
  remote at once (provider.AskRemoteHub) when no model list is fetched
  on that save; off takes its server out. Only one switched on is
  asked (bridgeWanted). A server auto-added before this (no bridgesOn)
  is kept, and its switch shows on. A server removed in the Library
  turns its switch off; the provider gone takes its switch with it.

Run (mote, at this tree):
- go test ./internal/library ./internal/provider ./internal/gui:
  library ok; provider ok but TestRenewLoginsKeepsClaudeReading
  (#5481, red the same at the base); gui ok but TestMainWindowCorners
  (#3949). The first gui run had TestCoreScriptBudget red (app.js
  over by ~1.2KB); the new code was made compact and seven editor
  comment blocks cut to one line each. Rebased on 09812e66b the core
  was 68 bytes over again, so three more comments near the editor
  (decidesModel, modelAPIs, pickedOf) were cut: app.js is 161 bytes
  smaller than at its base, and the budget (not raised) passes there:
  go test -run 'TestCoreScriptBudget|Provider' ./internal/gui ok.
- go vet ./..., GOOS=windows go vet ./..., GOOS=linux go vet -tags
  nogui ./...: ok; gofmt -l clean.
- node --test remote-magpie (chromium + webkit, en + zh), i18n-keys,
  i18n-en-no-cjk, gui-de, gui-ja, gui-zh-tw, preset-name,
  name-suffix-remote, remote-self, provider-unmasked, key-row-chips-fit,
  ctx-head-narrow, routing-remote-windows, usage-remote-cards,
  old-webkit: all
  green except reds that are red the same at the base 1ccad582d and
  filed: remote-magpie's "asks for the other magpie's address" fails
  at its decision-model chips before reaching anything this changes
  (#5013, #4398), and i18n-keys' "a plugin's words are its own"
  (#5332, #5426, #5482). With that one chips assertion bypassed in a
  local copy, remote-magpie's new assertions are 12 of 12 green.
  name-suffix-remote went red in Chromium (zh, zh-TW, de) beside 10
  other files, its scrollends.js import failing (#5147); alone it is
  10 of 10 green. The switch's label in the editor is the existing
  "MCP servers".

Broken by hand:
- the Was mapping off: TestRemoteMagpieMCPFollowsRename red ("renamed
  home, read before a sync: switch map[]").
- bridgeWanted/adoptBridge not asking bridgesOn: TestRemoteMagpieMCPIsOptIn
  red ("switched off, asked").
- the new editor's switch defaulting on: remote-magpie red ("off when
  added") in both engines.

Not tried: a real rename against a real second magpie (the library
tests fake RemoteHubs; the provider test renames a real providers.json
in a sandbox and checks Was reaches RemoteHubs). The CLI (provider
add/set remote-magpie) and the TUI have no switch: from there a new
Remote magpie gets no MCP server until it is switched on in the GUI.

Reported-by: treeman_26897 (Discord)
This commit is contained in:
yetone
2026-11-06 15:41:43 +08:00
parent 09812e66bc
commit 4c8e1cfdfc
11 changed files with 384 additions and 56 deletions
+2 -2
View File
@@ -19,7 +19,7 @@ With the Library's switch "MCP router" on (#2679, @minggang123 on X), each agent
| Backends | One `backend` per Library server, shared by every agent (`hubPool`, keyed by the server's name; an edit or a sign-in since makes it a new one and ends the old). A command is started as `CheckServers` starts one (`startServer`: `proc` tree, home as its folder, `${NAME}` env expanded), on its first list or call, and initialized once. A URL (`http`, `sse`) is reached with its headers and the Library's MCP sign-in (`mcpauth`), and a session the server forgot is opened again once. A `notifications/tools/list_changed` from a server makes the next list ask it again. | `backendOf`, `connect`, `dialHub`, `dialStdio`, `dialSSE`, `dialHTTP` in `mcp_hub.go`; `startServer`, `httpSession` in [`mcp_check.go`](../../internal/library/mcp_check.go) |
| Lifetime | A server with no call for `hubIdle` (10 minutes) is ended; the tools it listed are kept, so a list doesn't start it again, and the next call does. A command that died is started again on the next call. Turning the switch off, an edit, and the gateway stopping (`StopHub` on drain) end them: stdin closed, then the process tree. The switch can be turned off, or a server edited or unticked, by another magpie (the window while `magpie serve` runs, the CLI), and an agent given each server's own entry again never asks the router, so the serving gateway also prunes every `hubPruneEvery` (5s) while it holds a server: each one the library no longer has as it was started, or every one once the switch is off, is ended (`hubPrune`). A server ticked for no agent is still served at `/mcp/magpie/hub`, so it is kept. | `use`, `done`, `stop`, `hubStopAll`, `hubPrune` in `mcp_hub.go`; `StopHub`, `keepHubPruned` in `hub_mcp.go` |
| GUI | Below the server list in the Library's MCP tab: a row with the switch (`.lib-switch`, role=switch) saying what it does; on, a line counting what it serves (`.lib-hubstats`: servers, tools, the agents given it), then a row "Other apps" with the address (`.lib-hubURL`, copied with a click) and Connect…, then a Router name row (`.lib-hubnoterow`) with a field (`.lib-hubname`, no native control) holding `hubNote` and `hubName` as its placeholder, saved on Enter or leaving it through `servers/hub-note` `{note}` (Escape puts the saved words back; an input method's Enter is its own), then a Tools on demand row (`.lib-hubtoolsrow`) whose switch is on while `hubAllTools` is false and posts `servers/hub-tools` `{on}` (on: every tool whole), and under them the agents that keep their own entries, grouped by why (`.lib-hub-why[data-why]`). The address is `mcpAddress`: the public one in a browser, the gateway in the app. Connect… opens a sheet (`connectHub`, `.lib-hubsheet`) of two tabs. Agents: agents → magpie → servers, drawn as icons with magpie's bird in the middle, a line of where things stand, then every agent `mcpAgents` lists (each detected, shown agent that takes MCP servers) in groups (`.lib-hubgrp[data-group]`): `off` (not connected), `on` (connected), `kept` (keeps each server's own entry). Each row (`.lib-hubagent[data-state]`: `on`, `none`, `own`, `taken`, `no-remote`) has a switch that posts `servers/agents-all` `{agents:[id], on}`, as By agent's Turn all on/off does: on gives it every Library server, so `hubFor` gives it the entry; off takes every Library server from it. A kept agent has a word for why and the reason in full behind (i) (`.lib-hubinfo`, `.lib-hubwhy`); an agent that reaches no server over HTTP says so even with none ticked. magpie-image is drawn and counted with the others. Connect all (`.lib-huball`) posts every `none` agent at once. With more than 8 agents a search (`.lib-hubsearch`) narrows every group, and the connected and the kept fold to one row each (`.lib-hubfolded`) until unfolded. The sheet stays open while it changes, and an agent is never handed to the user as a command to run. Other apps: the address (`.lib-hubaddr`), and a row per app (`.lib-hubapp[data-app]`): Cursor (only when it isn't one of the agents), VS Code, Windsurf and any JSON app, each with where its entry goes and a Copy entry (`.lib-hubcopy`) that copies its JSON. In the app, Cursor and VS Code also get Add (`.lib-hubadd`): the page posts `servers/hub-open` `{app}` and the window opens that app's install link (`HubLink`), which the app asks the user to confirm. The page never sends a link; an app with none is an error, and nothing is opened. In a browser there is no Add. With the router on, the server editor has a switch "Through the MCP router" (on for shared; not shown with the router off) saved as `hub`, a direct server's row has a tag (`.lib-tag.lib-direct`), and the line under the switch and the sheet name the direct servers as given directly (`inHub`, `directNames` in client.js; `mcp-hub-direct.test.cjs`). The TUI keeps the policy on edit. With no agent to write to, or in gateway mode (where no agent is shown), the Library is its MCP tab alone (`agentless` in client.js): the servers without agent chips, found servers or projects, the router's switch even before the first server, its lines saying any app connects at the address, the status saying the router is on or off, the servers it serves checked once it is on, and Connect… on Other apps alone. A server for remote clients is set up this way on a headless magpie (treeman_26897 on Discord); the remote client still needs a gateway key, through the same `serveMCP` guard (`TestHubMCPRemoteEntryNeedsKey`, `library-mcp-agentless.test.cjs`). | `hubPart`, `hubStats`, `connectHub` in [`client.js`](../../internal/gui/assets/plugins/library/client.js), [`library.css`](../../internal/gui/assets/plugins/library/library.css), [`i18n.js`](../../internal/gui/assets/plugins/library/i18n.js); `HubLink` in `mcp_hub.go`; `servers/hub-open` in `gui/library.go` |
| A Remote magpie's router | With another magpie as a provider (preset `remote-magpie`), its router's servers took adding that magpie again under Library → MCP (treeman_26897 on Discord). The gateway's info (`GET /v1`) says `"mcp_hub": true` to a caller it serves MCP to (`local` or `sharedWith`) while the switch is on with a server that isn't another magpie's router (`hubServes`). A fetch of a Remote magpie's models (`fetch` → `noteRemoteHub`, not one found to be this magpie) asks that info with the provider's key, only while the library would give it a server (`RemoteHubAsk`: its id isn't in `bridgesOffered`), and `RemoteHubFound` then adds one server: named for the provider (`bridgeName`), `http` at `<root>/mcp/magpie/hub` with `Authorization: Bearer <key>`, `bridge` = the provider's id, `local`, on for the agents given the hub's entry. Offered once: a user who removes it or switches it off keeps it so until the provider is removed and added again. A server the user has at that magpie's router already (same origin, the router's path) is the one, and none is added. The provider gone takes the server out (`adoptBridges`, at Sync and the View read); providers.json unreadable takes nothing out; the provider's address and key changed change the server's; edited to another address or key it is the user's own (`keptBridge`). No loop: every dial to a URL under `/mcp/magpie/hub` carries `X-Magpie-Router` (`remoteHeaders`), and a request with it (`gateway.FromRouter`) is given no `bridge` server, neither listed (`Tools`, `hubServersOf`) nor run (`Call`, `hubToolNamed`). | [`bridge_mcp.go`](../../internal/library/bridge_mcp.go); [`remote_hub.go`](../../internal/provider/remote_hub.go); `RouterHeader`, `hubServes` in [`hub_mcp.go`](../../internal/gateway/hub_mcp.go) |
| A Remote magpie's router | With another magpie as a provider (preset `remote-magpie`), its router's servers took adding that magpie again under Library → MCP (treeman_26897 on Discord). The gateway's info (`GET /v1`) says `"mcp_hub": true` to a caller it serves MCP to (`local` or `sharedWith`) while the switch is on with a server that isn't another magpie's router (`hubServes`). A fetch of a Remote magpie's models (`fetch` → `noteRemoteHub`, not one found to be this magpie) asks that info with the provider's key, only while the library would give it a server (`RemoteHubAsk`: its id is in `bridgesOn` and isn't in `bridgesOffered`), and `RemoteHubFound` then adds one server: named for the provider (`bridgeName`), `http` at `<root>/mcp/magpie/hub` with `Authorization: Bearer <key>`, `bridge` = the provider's id, `local`, on for the agents given the hub's entry. It is the user's call (treeman_26897 again): the Remote magpie's editor has a switch, "Add its MCP servers to the Library" (`libraryMCP` in `/api/providers` and the save; `library.RemoteMCPOn`, `library.SetRemoteMCP`), off when one is added. On puts its id in `bridgesOn` and asks at once (`provider.AskRemoteHub`); off takes its server out. A server added before the switch (no `bridgesOn`) is kept and shows the switch on. Offered once each time it is switched on: a server removed in the Library turns the switch off (`removeServer`), one switched off for an agent stays off. Renamed, the provider's `Was` carries its server's `bridge`, `bridgesOn` and `bridgesOffered` to its id now (`adoptBridges`); the server keeps its name. A server the user has at that magpie's router already (same origin, the router's path) is the one, and none is added. The provider gone takes the server out (`adoptBridges`, at Sync and the View read); providers.json unreadable takes nothing out; the provider's address and key changed change the server's; edited to another address or key it is the user's own (`keptBridge`). No loop: every dial to a URL under `/mcp/magpie/hub` carries `X-Magpie-Router` (`remoteHeaders`), and a request with it (`gateway.FromRouter`) is given no `bridge` server, neither listed (`Tools`, `hubServersOf`) nor run (`Call`, `hubToolNamed`). | [`bridge_mcp.go`](../../internal/library/bridge_mcp.go); [`remote_hub.go`](../../internal/provider/remote_hub.go); `RouterHeader`, `hubServes` in [`hub_mcp.go`](../../internal/gateway/hub_mcp.go) |
The CLI's `magpie library mcp router on|off` (`hub`, its name before, still works) calls `SetMCPHub`, and `magpie library mcp router <name> shared|direct` calls `ServerHub`. `magpie library` lists the agents given magpie's entry and those that keep their own, with why (`libraryStatus` in [`library_cli.go`](../../internal/cli/library_cli.go)).
@@ -50,7 +50,7 @@ The gateway can't import the library (the library imports the gateway), so the g
```sh
go test -tags nogui ./internal/gui -run 'TestHubOpen|TestHubNote|TestHubAllTools'
go test -tags nogui ./internal/library -run 'TestHub|TestRunDirect|TestFakeMCPServer|TestCheck|TestPluginTools|TestRemoteMagpieRouter|TestCarriedServerIsNoBridge'
go test -tags nogui ./internal/library -run 'TestHub|TestRunDirect|TestFakeMCPServer|TestCheck|TestPluginTools|TestRemoteMagpieRouter|TestRemoteMagpieMCP|TestCarriedServerIsNoBridge'
go test -tags nogui ./internal/settings -run TestRouterNote
go test -tags nogui ./internal/gateway -run 'HubMCP|OwnMCPRejects|TestHubLeavesRemoteRouterToARouter|TestInfoSaysMCPHub' -timeout 45m
go test -tags nogui ./internal/provider -run 'TestRemoteHubNoted|TestRemoteSelf'
+31 -28
View File
@@ -9164,11 +9164,9 @@ function vertexOfDraft() {
return { project: (v.project || "").trim(), location: (v.location || "").trim(), credentials: (v.credentials || "").trim(), impersonate: (v.impersonate || "").trim() };
}
const decideOnly = (p) => !!p?.decide && !(p.chat || p.responses || p.anthropic || p.gemini);
// a provider that lists its decision models apart (OpenRouter) says which
// they are: its Jev Router (typesafe/jev-router) is a chat model
// OpenRouter lists its decision models apart
const decidesModel = (p, id) => !!p.decide && (decideOnly(p) || (p.deciders ? p.deciders.includes(id) : id.split("/").some((s) => /^jev(?:-|$)/i.test(s))));
// modelAPIs: the APIs one of p's models can be asked on alone, those it has
// a URL for when it has more than one, Gemini's too (01huadalang, Kayphoon)
// modelAPIs: those p has a URL for, if 2+ (01huadalang, Kayphoon)
const modelAPIs = (p) => {
const urls = ["chat", "responses", "anthropic", "gemini"].filter((k) => ((draft?.id === p.id ? draft[k] : undefined) ?? p[k] ?? "").trim());
return urls.length < 2 ? [] : PROTOS.filter(([k]) => urls.includes(k));
@@ -9179,8 +9177,7 @@ function pickedOf(p) {
const on = p.models.filter((m) => m.on);
if (!Array.isArray(p.chosen)) return on.map((m) => m.id); // no picks said: those served, as before
const picks = new Set(p.chosen);
// a pick agents aren't offered for want of its API's URL stays picked
// (#2094): it is offered again once the URL is added
// one with no URL for its API stays picked (#2094)
return p.models.filter((m) => (m.on || m.noAPI) && picks.has(m.id)).map((m) => m.id);
}
@@ -9266,8 +9263,7 @@ function drawEditor(p, presetID) {
}
}
// a vendor's global and China endpoints are presets of their own, one row
// in the add sheet: here the new provider picks between them, the key kept
// a vendor's global and China endpoints: one row in the add sheet, picked here
const pair = isNew && pr ? (globalOf(pr) ? [globalOf(pr), pr] : chinaOf(pr) ? [pr, chinaOf(pr)] : null) : null;
if (pair) {
const seg = el("div", "segs area");
@@ -9286,9 +9282,7 @@ function drawEditor(p, presetID) {
ed.append(...field(t("Region"), seg, ""));
}
// who uses it: just the agents already pointed here, so a click changes
// one's model. Pointing a new agent at the provider happens in the Agent
// tab's picker, not here.
// the agents already pointed here; a new one is pointed in the Agents tab
if (p) {
const on = p.agents.filter((a) => a.current);
if (on.length) {
@@ -9306,7 +9300,8 @@ function drawEditor(p, presetID) {
}
let name, url;
if (another) {
const remoteNew = isNew && pr?.id === "remote-magpie";
if (another && !remoteNew) {
name = input(draft.name === pr.name ? "" : draft.name, t("e.g. {name} · Work", { name: pr.name }));
const hint = el("div", "hint");
const idHint = () => { hint.textContent = t("id {id} — a number is added if it is taken", { id: draft.id }); };
@@ -9316,10 +9311,7 @@ function drawEditor(p, presetID) {
wrap.append(name, hint);
ed.append(el("label", "", t("Name")), wrap);
}
// an added preset's name is the user's, as a custom provider's is: two
// of a vendor's sites (Kimi and Kimi (China)) named as they tell them
// apart, in the list and every picker (yapechan on Discord). Left empty,
// it is the preset's again
// an added preset's name is the user's (yapechan on Discord); empty, the preset's
if (p && pr && !p.account) {
name = input(draft.name === pr.name ? "" : draft.name, pr.name);
name.className = "provider-name";
@@ -9373,18 +9365,14 @@ function drawEditor(p, presetID) {
ed.append(...field(t("Name"), name));
if (p) idField();
// the base URL is the one the chosen protocol is asked at; a vendor
// that serves only the Responses API is added (and tested) with that
// alone, since /chat/completions would only fail (#73)
// the base URL is the chosen protocol's; Responses alone where only it serves (#73)
const seg = el("div", "segs base-apis");
for (const [v, hint] of [["openai", "…/v1 — chat completions, and responses when the vendor has it"], ["responses", "…/v1 — for a vendor that serves only the Responses API, not chat completions"], ["anthropic", "the root URL, what ANTHROPIC_BASE_URL would take"], ["gemini", "…/v1beta — Google's Gemini API (generateContent), or one that answers as it does; the key goes in x-goog-api-key"], ["decide", "a decision API's root, POST …/systemone under it: its models are a routing group's classifier, never an agent's"]]) {
const b = el("button", "opt" + (draft.api === v ? " on" : ""), t(API_NAMES[v]));
b.title = t(hint);
b.onclick = () => {
if (draft.api === v) return;
// each protocol keeps its own URL (#105); an unsaved one moves to a
// protocol without one, in its spelling (#73), and goes back once
// that protocol is given its own (#1231)
// each protocol keeps its own URL (#105, #73, #1231)
const from = apiField[draft.api], to = apiField[v];
carried = null;
if (!draft[to] && draft[from] && draft[from] !== (p?.[from] || "")) {
@@ -9605,14 +9593,10 @@ function drawEditor(p, presetID) {
addressField = field(t("Server address"), address, t("Where the server listens; change the port, or give another computer's address"));
}
// null, not false, when there is none: false?.key is undefined, and a
// provider with no key read .set of it (willz: a local Ollama without a
// key opened no editor, its row just toggling)
// null, not false, with no key (willz)
const copied = (!p && draft.copyOf && providers.providers.find((x) => x.id === draft.copyOf)) || null;
const key = input(draft.key || "", p?.key.set ? t("{masked} · paste a new key to replace it", { masked: p.key.masked }) : copied?.key.set ? t("{masked} · {name}'s key, or paste another", { masked: copied.key.masked, name: copied.name }) : t(pr?.keyHint || (pr?.noKey || p?.key.optional ? "optional for local servers" : "paste an API key")), "password");
// many keys pasted at once (361 on Discord): one a line, or separated by
// commas or spaces, are kept as one list; saved, the first is the key
// and the others are added to its accounts, as Paste several does
// many keys pasted at once (361 on Discord): the first is the key, the others its accounts
const keyCount = el("span", "hint key-count");
const countKeys = () => {
const n = splitKeys(key.value).length;
@@ -9713,6 +9697,24 @@ function drawEditor(p, presetID) {
// keys are replaced in Accounts; the box is for no key yet (Kylin_Cloud on X)
else if (!p?.keyList?.length) ed.append(...field(t("API key"), keyWrap, isNew ? t("Kept in ~/.config/magpie/providers.json, readable by you alone. Nothing is read from your shell.") : ""));
// blank, the preset's (treeman_26897)
if (remoteNew) {
const idIn = input("", pr.id);
name = input("", pr.name);
name.className = "provider-name";
idIn.className = "provider-id";
name.oninput = idIn.oninput = () => { draft.name = name.value.trim() || pr.name; draft.id = slug(idIn.value) || slug(name.value) || pr.id; idIn.placeholder = draft.id; };
name.onkeydown = idIn.onkeydown = key.onkeydown;
ed.append(...field(t("Name"), name), ...field(t("ID"), idIn));
}
// 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));
}
// A user-defined provider can have its own picture; presets keep theirs.
if (custom) ed.append(...field(t("Icon"), iconPicker(ed), ""));
@@ -10160,6 +10162,7 @@ function drawEditor(p, presetID) {
if (custom) { body.icon = draft.icon || "generic"; body.iconFrom = draft.iconFrom || ""; body.balanceURL = (draft.balanceURL || "").trim(); body.balancePath = (draft.balancePath || "").trim(); body.balanceMethod = draft.balanceMethod || ""; body.modelsURL = (draft.modelsURL || "").trim(); }
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;
body.pinUpstream = !!draft.pinUpstream;
if (twoKeyHeaders()) body.authHeader = draft.authHeader || "";
body.unredacted = !!draft.unredacted && unmaskable();
+4
View File
@@ -2570,6 +2570,7 @@ const I18N = {
"Add": "添加",
"{name} added": "已添加 {name}",
"Give it a name": "先起个名字",
"Add its MCP servers to the Library": "把它的 MCP 服务器加到资源库",
"A base URL is needed": "需要填写 Base URL",
"Endpoint": "接口地址",
"Your resource's endpoint is needed": "需要填写你的资源接口地址",
@@ -7198,6 +7199,7 @@ const I18N = {
"Add": "新增",
"{name} added": "已新增 {name}",
"Give it a name": "先起個名字",
"Add its MCP servers to the Library": "把它的 MCP 伺服器加到資源庫",
"A base URL is needed": "需要填寫 Base URL",
"Endpoint": "端點位址",
"Your resource's endpoint is needed": "需要填寫你的資源端點",
@@ -11804,6 +11806,7 @@ const I18N = {
"Add": "追加",
"{name} added": "{name} を追加しました",
"Give it a name": "名前を付けてください",
"Add its MCP servers to the Library": "その MCP サーバーをライブラリに追加",
"A base URL is needed": "ベース URL が必要です",
"Endpoint": "エンドポイント",
"Your resource's endpoint is needed": "リソースのエンドポイントが必要です",
@@ -16441,6 +16444,7 @@ const I18N = {
"Add": "Hinzufügen",
"{name} added": "{name} hinzugefügt",
"Give it a name": "Vergeben Sie einen Namen",
"Add its MCP servers to the Library": "Seine MCP-Server zur Bibliothek hinzufügen",
"A base URL is needed": "Eine Basis-URL ist erforderlich",
"Endpoint": "Endpunkt",
"Your resource's endpoint is needed": "Der Endpunkt Ihrer Ressource ist erforderlich",
+31 -1
View File
@@ -19,6 +19,7 @@ import (
"github.com/yetone/magpie/internal/autostart"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/library"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
@@ -268,6 +269,9 @@ type providerJSON struct {
// routing unless KeepSelf (provider.Provider.SelfAnswered)
Self bool `json:"self,omitempty"`
KeepSelf bool `json:"keepSelf,omitempty"`
// LibraryMCP: a Remote magpie whose router is a Library server, or
// is to be one (library.RemoteMCPOn)
LibraryMCP bool `json:"libraryMCP,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"`
@@ -1169,10 +1173,18 @@ func providersState() providersJSON {
uses := agentUses(agents, findGroup)
desktop := desktopNumbers(uses)
have := map[string]bool{}
var remoteMCP map[string]bool // read once, at the first Remote magpie
for _, p := range provider.All() {
// a preset is added once any provider is its, whatever its id
have[p.ID], have[p.Preset] = true, true
s.Providers = append(s.Providers, providerInfoWith(p, provider.KeptListing(p), uses, desktop))
info := providerInfoWith(p, provider.KeptListing(p), uses, desktop)
if p.IsRemoteMagpie() {
if remoteMCP == nil {
remoteMCP = library.RemoteMCPOn()
}
info.LibraryMCP = remoteMCP[p.ID]
}
s.Providers = append(s.Providers, info)
}
// partners first, as the add sheet lists them
for _, pa := range provider.Partners() {
@@ -1515,6 +1527,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
ClearAccessKey bool `json:"clearAccessKey"`
// From is the id the provider had: another is a rename
From string `json:"from"`
// LibraryMCP, on a Remote magpie, is its editor's switch: its
// router a Library server (library.SetRemoteMCP); left out,
// it stays as it is
LibraryMCP *bool `json:"libraryMCP"`
// 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
@@ -2134,6 +2150,18 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
return
}
}
// a Remote magpie's router given a server or taken out, before
// its list below asks it
askHub := false
if req.LibraryMCP != nil {
if p, err := provider.Find(in.ID); err == nil && p.IsRemoteMagpie() && library.RemoteMCPOn()[in.ID] != *req.LibraryMCP {
if _, err := library.SetRemoteMCP(in.ID, *req.LibraryMCP); err != nil {
fail(rw, err)
return
}
askHub = *req.LibraryMCP
}
}
provider.ForgetBalances()
if old == nil || old.AccessKeyID != in.AccessKeyID || old.SecretAccessKey != in.SecretAccessKey {
// the plan's windows are read afresh with the new access key
@@ -2155,6 +2183,8 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
wg.Go(func() { provider.PrefillNewKeys(ctx, had, in.ID) })
if old == nil || old.Key != p.Key {
p.Fetch(ctx)
} else if askHub {
provider.AskRemoteHub(ctx, in.ID)
}
wg.Wait()
cancel()
+54 -3
View File
@@ -8,6 +8,10 @@
// goes on in the API the agent spoke. Adding without one says so in its
// own words and sends nothing; with one, the address goes as the preset's
// endpoint, however it was typed (the backend puts every API on it).
// Below the key, a Name and an ID, left blank the preset's, the ID
// following the name until one is typed; and a switch, off, for its MCP
// servers to be added to the Library (treeman_26897 on Discord), which a
// saved one's editor has too, as the backend reads it.
// Nothing moves the page. English and Chinese; no backend, the API is
// faked here.
const assert = require("node:assert/strict");
@@ -29,7 +33,7 @@ const presets = [
];
const providers = [{ id: "openrouter", name: "OpenRouter", icon: "openai", preset: "openrouter", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } },
{ id: "office", name: "Office", icon: "magpie", preset: "remote-magpie", chat: "http://office/v1", responses: "http://office/v1", anthropic: "http://office", decide: "http://office/v1",
deciders: ["judge/custom-a", "judge/custom-b"], models: [{ id: "lib/m1", name: "Chat", on: true }, { id: "judge/custom-a", name: "custom-a · judge", on: false }, { id: "judge/custom-b", name: "custom-b · judge", on: false }], agents: [], key: { set: true, masked: "sk-…ab12" } },
libraryMCP: true, deciders: ["judge/custom-a", "judge/custom-b"], models: [{ id: "lib/m1", name: "Chat", on: true }, { id: "judge/custom-a", name: "custom-a · judge", on: false }, { id: "judge/custom-b", name: "custom-b · judge", on: false }], agents: [], key: { set: true, masked: "sk-…ab12" } },
];
function server(lang, saves) {
@@ -55,9 +59,9 @@ function server(lang, saves) {
}
const L = {
en: { field: "Endpoint", hint: /Settings → Network and sharing, under Share on local network.*the API the agent spoke/, needed: "The other magpie's address is needed", note: "another computer's magpie, shared on its network", add: "Add",
en: { field: "Endpoint", hint: /Settings → Network and sharing, under Share on local network.*the API the agent spoke/, needed: "The other magpie's address is needed", note: "another computer's magpie, shared on its network", add: "Add", name: "Name", mcp: "Add its MCP servers to the Library",
decide: ["Jev endpoint", "System One endpoint"] },
zh: { field: "接口地址", hint: /设置 → 网络与共享 → 局域网共享.*原样转发/, needed: "需要填写另一台 magpie 的地址", note: "远程:另一台电脑上的 magpie,局域网共享", add: "添加",
zh: { field: "接口地址", hint: /设置 → 网络与共享 → 局域网共享.*原样转发/, needed: "需要填写另一台 magpie 的地址", note: "远程:另一台电脑上的 magpie,局域网共享", add: "添加", name: "名称", mcp: "把它的 MCP 服务器加到资源库",
decide: ["Jev 端点", "System One 端点"] },
};
@@ -152,6 +156,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the decision model's own address field, by its label as i18n.js has it
for (const label of w.decide) assert.equal(await saved.locator("label", { hasText: label }).count(), 0, label);
assert.equal(await saved.locator('input[type="url"]').count(), 1, "only the remote's address is editable");
assert.equal(await saved.locator(".library-mcp", { hasText: w.mcp }).locator("input").isChecked(), true, "the switch as the backend reads it");
assert.deepEqual(await saved.locator(".mchip > span:first-child").allTextContents(),
decisions ? ["Chat", "custom-a · judge", "custom-b · judge"] : ["Chat"]);
if (process.env.ARTIFACT_DIR && engine === "chromium" && lang === "en") {
@@ -193,6 +198,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
editor.querySelector("input.endpoint"), editor.querySelector('input[type="password"]'),
].map((input) => input.getBoundingClientRect().top));
assert(ey < ky, "the endpoint above the key");
// a Name and an ID under the key, blank; the switch off
const name = ed.locator("input.provider-name"), id = ed.locator("input.provider-id");
assert.equal(await ed.locator("label", { hasText: new RegExp("^" + w.name + "$") }).count(), 1);
assert.equal(await name.getAttribute("placeholder"), "Remote magpie");
assert.equal(await id.getAttribute("placeholder"), "remote-magpie");
const ny = await name.evaluate((n) => n.getBoundingClientRect().top);
assert(ky < ny, "the name under the key");
const mcp = ed.locator(".library-mcp", { hasText: w.mcp }).locator("input");
assert.equal(await mcp.isChecked(), false, "off when added");
// no endpoint: said, nothing sent, the page where it was
await key.fill("sk-magpie-x");
@@ -212,12 +226,49 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(s.preset, "remote-magpie");
assert.equal(s.key, "sk-magpie-x");
assert.equal(s.chat, "192.168.1.20:3425");
assert.equal(s.name, "Remote magpie");
assert.equal(s.id, "remote-magpie");
assert.equal(s.libraryMCP, false);
// named, its id following; then an id of its own; switched on
await page.locator("#addProvider").click();
await tile.click();
await ed.locator(".ehead b", { hasText: "Remote magpie" }).waitFor();
await ed.locator("input.endpoint").fill("192.168.1.21:3425");
await ed.locator("input[type=password]").first().fill("sk-magpie-y");
await ed.locator("input.provider-name").fill("Home Lab");
assert.equal(await ed.locator("input.provider-id").getAttribute("placeholder"), "home-lab");
await ed.locator(".library-mcp input").check();
await ed.locator(".bar button.primary", { hasText: w.add }).click();
await page.waitForFunction(() => !document.querySelector(".editor.new"));
assert.deepEqual([saves[1].name, saves[1].id, saves[1].libraryMCP], ["Home Lab", "home-lab", true]);
await page.locator("#addProvider").click();
await tile.click();
await ed.locator(".ehead b", { hasText: "Remote magpie" }).waitFor();
await ed.locator("input.endpoint").fill("192.168.1.22:3425");
await ed.locator("input[type=password]").first().fill("sk-magpie-z");
await ed.locator("input.provider-name").fill("Home Lab");
await ed.locator("input.provider-id").fill("Lab 2");
await ed.locator(".bar button.primary", { hasText: w.add }).click();
await page.waitForFunction(() => !document.querySelector(".editor.new"));
assert.deepEqual([saves[2].name, saves[2].id, saves[2].libraryMCP], ["Home Lab", "lab-2", false]);
// another preset's editor has no endpoint field
await page.locator("#addProvider").click();
await sheet.locator(".tile .n", { hasText: /^OpenAI$/ }).click();
await ed.locator(".ehead b", { hasText: "OpenAI" }).waitFor();
assert.equal(await ed.locator("input.endpoint").count(), 0);
assert.equal(await ed.locator(".library-mcp").count(), 0, "no switch on another preset");
await page.keyboard.press("Escape");
await ed.waitFor({ state: "detached" });
// a saved one's switch turned off: sent so
await page.locator('#providers .row[data-id="office"]').click();
await saved.locator(".ehead b", { hasText: "Office" }).waitFor();
await saved.locator(".library-mcp input").uncheck();
await Promise.all([page.waitForResponse((r) => r.url().endsWith("/api/provider/save")), saved.locator(".bar button.primary").first().click()]);
assert.equal(saves.length, 4);
assert.deepEqual([saves[3].from, saves[3].libraryMCP], ["office", false]);
assert.deepEqual(errors, []);
await page.context().close();
});
+103 -14
View File
@@ -10,9 +10,15 @@ package library
// turned off one by one, behind the MCP hub as <name>__<tool>, or written
// into an agent as its own entry with the hub off.
//
// - It is offered once (BridgesOffered): a user who removes the server
// doesn't get it back until the provider is removed and added again.
// - It is the user's call (treeman_26897 again): a Remote magpie's
// editor has a switch for it, off when one is added, and only one
// switched on (BridgesOn) is asked. Switched off, its server is taken
// out; a server added before the switch was there stays, the switch
// shown on. One taken out in the Library turns the switch off.
// - It is offered once each time it is switched on (BridgesOffered).
// One the user switched off for an agent stays off.
// - It follows the provider's rename: a server, an offer and a switch
// under an id the provider had (its Was) are under its id now.
// - A server the user has at that magpie's router already (its host and
// the router's path) is the one: none is added beside it.
// - It goes with the provider: once providers.json no longer has it, the
@@ -79,12 +85,62 @@ func originOf(u string) string {
}
// bridgeWanted is whether the Remote magpie id would be given a server,
// were it to say it serves its router: it wasn't offered one yet.
// were it to say it serves its router: switched on and not offered one
// yet.
func bridgeWanted(id string) bool {
mu.Lock()
l, err := load()
mu.Unlock()
return err == nil && !slices.Contains(l.BridgesOffered, id)
return err == nil && slices.Contains(l.BridgesOn, id) && !slices.Contains(l.BridgesOffered, id)
}
// RemoteMCPOn are the Remote magpies (provider ids) whose editor's switch
// is on: switched on, or with a server of their router in the library
// (one added before the switch was there too). Nil when the library
// can't be read.
func RemoteMCPOn() map[string]bool {
mu.Lock()
l, err := load()
mu.Unlock()
if err != nil {
return nil
}
l.adoptBridges() // a rename not yet written down: read as it will be
on := map[string]bool{}
for _, id := range l.BridgesOn {
on[id] = true
}
for _, s := range l.MCP {
if s.Bridge != "" {
on[s.Bridge] = true
}
}
return on
}
// SetRemoteMCP turns the switch of the Remote magpie id on or off. On, it
// is asked again at its next model list (provider.AskRemoteHub asks at
// once); off, its server is taken out of the library and the agents.
func SetRemoteMCP(id string, on bool) (*Result, error) {
return change(func(l *Library) error {
l.adoptBridges()
if on {
if !slices.Contains(l.BridgesOn, id) {
l.BridgesOn = append(l.BridgesOn, id)
}
l.BridgesOffered = slices.DeleteFunc(l.BridgesOffered, func(x string) bool { return x == id })
return nil
}
l.BridgesOn = slices.DeleteFunc(l.BridgesOn, func(x string) bool { return x == id })
for _, s := range slices.Clone(l.MCP) {
if s.Bridge == id {
if err := removeServer(l, s.Name); err != nil {
return err
}
}
}
return nil
})
}
// adoptBridge gives the router of the Remote magpie id a server, it having
@@ -106,7 +162,8 @@ func adoptBridge(id string) (bool, error) {
if err != nil {
return false, err
}
if slices.Contains(l.BridgesOffered, id) {
l.adoptBridges()
if slices.Contains(l.BridgesOffered, id) || !slices.Contains(l.BridgesOn, id) {
return false, nil
}
l.BridgesOffered = append(l.BridgesOffered, id)
@@ -119,11 +176,12 @@ func adoptBridge(id string) (bool, error) {
}
// adoptBridges brings the library's Remote magpie servers in line with the
// providers: one whose provider is gone is taken out, and its offer with
// it; the others' address and key are the provider's now. It asks no
// magpie; true when it changed the library.
// providers: what is under an id a provider had is under its id now; one
// whose provider is gone is taken out, and its offer and switch with it;
// the others' address and key are the provider's now. It asks no magpie;
// true when it changed the library.
func (l *Library) adoptBridges() bool {
if len(l.BridgesOffered) == 0 && !slices.ContainsFunc(l.MCP, func(s *Server) bool { return s.Bridge != "" }) {
if len(l.BridgesOffered) == 0 && len(l.BridgesOn) == 0 && !slices.ContainsFunc(l.MCP, func(s *Server) bool { return s.Bridge != "" }) {
return false
}
hs, err := remoteHubs()
@@ -134,12 +192,43 @@ func (l *Library) adoptBridges() bool {
for _, h := range hs {
by[h.ID] = h
}
// renamed (treeman_26897: its name and id changed, the server went):
// an id no provider has now that one had is that one's
now := map[string]string{}
for _, h := range hs {
for _, w := range h.Was {
if _, taken := by[w]; !taken && w != "" {
now[w] = h.ID
}
}
}
changed := false
if n := len(l.BridgesOffered); n > 0 {
l.BridgesOffered = slices.DeleteFunc(l.BridgesOffered, func(id string) bool { _, ok := by[id]; return !ok })
changed = len(l.BridgesOffered) != n
if len(l.BridgesOffered) == 0 {
l.BridgesOffered = nil
renamed := func(ids []string) []string {
var out []string
for _, id := range ids {
if to, ok := now[id]; ok {
id, changed = to, true
}
if !slices.Contains(out, id) {
out = append(out, id)
}
}
return out
}
l.BridgesOffered, l.BridgesOn = renamed(l.BridgesOffered), renamed(l.BridgesOn)
for _, s := range l.MCP {
if to, ok := now[s.Bridge]; ok && s.Bridge != "" {
s.Bridge, changed = to, true
}
}
gone := func(id string) bool { _, ok := by[id]; return !ok }
for _, ids := range []*[]string{&l.BridgesOffered, &l.BridgesOn} {
if n := len(*ids); n > 0 {
*ids = slices.DeleteFunc(*ids, gone)
changed = changed || len(*ids) != n
}
if len(*ids) == 0 {
*ids = nil
}
}
if n := len(l.MCP); n > 0 {
+122 -5
View File
@@ -57,8 +57,12 @@ func TestRemoteMagpieRouterIsAServer(t *testing.T) {
ok(t)(SaveServer("", *fake))
ok(t)(SetMCPHub(true))
if provider.RemoteHubAsk("home") {
t.Fatal("a Remote magpie whose switch is off is asked")
}
ok(t)(SetRemoteMCP("home", true))
if !provider.RemoteHubAsk("home") {
t.Fatal("a Remote magpie not offered yet isn't asked")
t.Fatal("a Remote magpie switched on, not offered yet, isn't asked")
}
provider.RemoteHubFound("home")
l := loaded(t)
@@ -120,9 +124,10 @@ func TestRemoteMagpieRouterIsAServer(t *testing.T) {
}
}
// The server is offered once: removed by the user, it isn't added again
// until the provider is removed and added again; switched off for an
// agent, it stays off. One the user has at that magpie's router already
// The server is offered once each time its switch is turned on: removed
// by the user, it isn't added again until the switch is turned on again
// (removing it turned the switch off); the provider removed and added
// again, its switch is off. Switched off for an agent, it stays off. One the user has at that magpie's router already
// is the one. The provider removed takes its server with it; one turned
// off keeps it (RemoteHubs still lists it); providers.json unreadable
// takes nothing out. A name a server has already, or the hub's own entry's,
@@ -135,6 +140,7 @@ func TestRemoteMagpieRouterOfferedOnce(t *testing.T) {
// the user's own at that magpie's router: none beside it
ok(t)(SaveServer("", Server{Name: "office", Transport: "http", URL: "http://192.168.1.9:3425" + gateway.HubMCPPath + "claude"}))
ok(t)(SetRemoteMCP("home", true))
provider.RemoteHubFound("home")
if l := loaded(t); len(l.MCP) != 1 || !slices.Contains(l.BridgesOffered, "home") {
t.Fatalf("beside the user's own: %+v, offered %v", l.MCP, l.BridgesOffered)
@@ -153,8 +159,13 @@ func TestRemoteMagpieRouterOfferedOnce(t *testing.T) {
}
f.hs = []provider.RemoteHub{home}
provider.RemoteHubFound("home")
if has("home") || RemoteMCPOn()["home"] {
t.Fatal("the provider added again, its switch on")
}
ok(t)(SetRemoteMCP("home", true))
provider.RemoteHubFound("home")
if !has("home") {
t.Fatal("the provider added again, no server")
t.Fatal("the provider added again and switched on, no server")
}
if a := loaded(t).server("home").Agents; len(a) != 0 {
t.Errorf("with the hub off, on for %v, want none", a)
@@ -174,11 +185,15 @@ func TestRemoteMagpieRouterOfferedOnce(t *testing.T) {
if has("home") {
t.Fatal("a server the user removed came back")
}
if RemoteMCPOn()["home"] || provider.RemoteHubAsk("home") {
t.Fatal("its server removed in the Library, the switch is still on")
}
// providers.json unreadable takes nothing out
f.hs = nil
ok(t)(Sync())
f.hs = []provider.RemoteHub{home}
ok(t)(SetRemoteMCP("home", true))
provider.RemoteHubFound("home")
f.err = errors.New("unreadable")
f.hs = nil
@@ -191,6 +206,9 @@ func TestRemoteMagpieRouterOfferedOnce(t *testing.T) {
if has("home") {
t.Fatal("the provider removed kept its server")
}
if l := loaded(t); len(l.BridgesOn) != 0 {
t.Fatalf("the provider removed kept its switch: %v", l.BridgesOn)
}
// a provider being tried in the editor, not saved: nothing
provider.RemoteHubFound("nope")
@@ -201,6 +219,8 @@ func TestRemoteMagpieRouterOfferedOnce(t *testing.T) {
// names: the hub's own entry's isn't given, nor one a server has
ok(t)(SaveServer("", Server{Name: "magpie-remote", Transport: "http", URL: "https://example.com/mcp"}))
f.hs = []provider.RemoteHub{{ID: "m", Name: "magpie", Root: "http://10.0.0.2:3425", Key: "k"}, {ID: "x", Name: "!!", Root: "http://10.0.0.3:3425", Key: "k"}}
ok(t)(SetRemoteMCP("m", true))
ok(t)(SetRemoteMCP("x", true))
provider.RemoteHubFound("m")
provider.RemoteHubFound("x")
l := loaded(t)
@@ -212,6 +232,103 @@ func TestRemoteMagpieRouterOfferedOnce(t *testing.T) {
}
}
// Adding a Remote magpie's router to the Library is the user's call
// (treeman_26897): with the switch off it isn't asked nor given a server;
// turned on, it is; turned off, its server is taken out, and on again it
// is offered again. A server added before the switch was there (no
// BridgesOn) is kept, the switch shown on, and the provider's key still
// reaches it.
func TestRemoteMagpieMCPIsOptIn(t *testing.T) {
hubSandbox(t)
f := fakeRemoteHubs(t, provider.RemoteHub{ID: "home", Name: "Home", Root: "http://192.168.1.9:3425", Key: "k"})
has := func() bool { t.Helper(); return loaded(t).server("home") != nil }
if provider.RemoteHubAsk("home") || RemoteMCPOn()["home"] {
t.Fatal("switched off, asked")
}
provider.RemoteHubFound("home")
if has() {
t.Fatal("switched off, given a server")
}
ok(t)(SetRemoteMCP("home", true))
if !RemoteMCPOn()["home"] {
t.Fatal("switched on, read as off")
}
provider.RemoteHubFound("home")
if !has() {
t.Fatal("switched on, no server")
}
ok(t)(SetRemoteMCP("home", false))
if has() || RemoteMCPOn()["home"] || provider.RemoteHubAsk("home") {
t.Fatal("switched off, its server kept")
}
ok(t)(SetRemoteMCP("home", true))
provider.RemoteHubFound("home")
if !has() {
t.Fatal("switched on again, not offered again")
}
// one added before the switch: a server with its Bridge, no BridgesOn
ok(t)(change(func(l *Library) error { l.BridgesOn = nil; return nil }))
if !has() || !RemoteMCPOn()["home"] {
t.Fatalf("a server from before the switch: kept %v, switch on %v", has(), RemoteMCPOn()["home"])
}
f.hs[0].Key = "k2"
ok(t)(Sync())
if s := loaded(t).server("home"); s == nil || s.Headers["Authorization"] != "Bearer k2" {
t.Fatalf("a server from before the switch, the key changed: %+v", s)
}
ok(t)(SetRemoteMCP("home", false))
if has() {
t.Fatal("a server from before the switch, switched off, kept")
}
}
// A Remote magpie renamed, its name and id (treeman_26897: its server
// went), keeps its server, under the id it has now, with its switch and
// its offer; and renamed again, still.
func TestRemoteMagpieMCPFollowsRename(t *testing.T) {
hubSandbox(t)
f := fakeRemoteHubs(t, provider.RemoteHub{ID: "remote-magpie", Name: "Remote magpie", Root: "http://192.168.1.9:3425", Key: "k"})
ok(t)(SetRemoteMCP("remote-magpie", true))
provider.RemoteHubFound("remote-magpie")
if s := loaded(t).server("remote-magpie"); s == nil || s.Bridge != "remote-magpie" {
t.Fatalf("no server: %+v", loaded(t).MCP)
}
for _, to := range []provider.RemoteHub{
{ID: "home", Name: "Home", Root: "http://192.168.1.9:3425", Key: "k", Was: []string{"remote-magpie"}},
{ID: "lab", Name: "Lab", Root: "http://192.168.1.9:3425", Key: "k", Was: []string{"remote-magpie", "home"}},
} {
f.hs = []provider.RemoteHub{to}
if on := RemoteMCPOn(); !on[to.ID] {
t.Fatalf("renamed %s, read before a sync: switch %v", to.ID, on)
}
ok(t)(Sync())
l := loaded(t)
s := l.server("remote-magpie")
if s == nil || s.Bridge != to.ID {
t.Fatalf("renamed %s, the server: %+v", to.ID, l.MCP)
}
if !slices.Equal(l.BridgesOn, []string{to.ID}) || !slices.Equal(l.BridgesOffered, []string{to.ID}) {
t.Fatalf("renamed %s: on %v, offered %v", to.ID, l.BridgesOn, l.BridgesOffered)
}
if provider.RemoteHubAsk(to.ID) {
t.Errorf("renamed %s, offered again", to.ID)
}
}
// an id it had that another provider has now is that one's
f.hs = append(f.hs, provider.RemoteHub{ID: "home", Name: "Home", Root: "http://10.0.0.7:3425", Key: "k"})
ok(t)(Sync())
if l := loaded(t); len(l.MCP) != 1 || l.MCP[0].Bridge != "lab" || slices.Contains(l.BridgesOn, "home") {
t.Fatalf("an id taken by another: %+v, on %v", l.MCP, l.BridgesOn)
}
// switched off under its id now
ok(t)(SetRemoteMCP("lab", false))
if l := loaded(t); len(l.MCP) != 0 {
t.Fatalf("switched off after the rename: %+v", l.MCP)
}
}
// A server carried in from another computer is never that computer's
// Remote magpie's here.
func TestCarriedServerIsNoBridge(t *testing.T) {
+3
View File
@@ -67,6 +67,9 @@ type Library struct {
// router was given a server, for one the user removed not to come
// back (bridge_mcp.go)
BridgesOffered []string `json:"bridgesOffered,omitempty"`
// BridgesOn are the Remote magpies (provider ids) the user asked to
// give their router a server, in the editor's switch (bridge_mcp.go)
BridgesOn []string `json:"bridgesOn,omitempty"`
// SeenSkills are, by repository and ref ("owner/repo@ref"), the
// folders of skills there the page has offered: picked or not at
// install, or set aside after a check. A check offers only the others
+4
View File
@@ -926,6 +926,10 @@ func removeServer(l *Library, name string) error {
return fmt.Errorf("no server called %s", name)
}
k := serverKey(l.MCP[i])
if b := l.MCP[i].Bridge; b != "" {
// a Remote magpie's router taken out: its editor's switch is off
l.BridgesOn = slices.DeleteFunc(l.BridgesOn, func(id string) bool { return id == b })
}
l.MCP = slices.Delete(l.MCP, i, i+1)
for _, p := range l.Projects {
delete(p.Servers, name)
+13 -2
View File
@@ -3,6 +3,7 @@ package provider
import (
"context"
"encoding/json"
"slices"
"strings"
"time"
)
@@ -28,9 +29,11 @@ var (
var RemoteHubWait = 5 * time.Second
// RemoteHub is a Remote magpie as its router's server is made: its
// address (the gateway's root) and its key.
// address (the gateway's root) and its key, and the ids it had before it
// was renamed (Provider.Was), which its server follows.
type RemoteHub struct {
ID, Name, Root, Key string
Was []string
}
// RemoteHubs are the Remote magpies in providers.json, turned off or not,
@@ -47,7 +50,7 @@ func RemoteHubs() ([]RemoteHub, error) {
if !p.IsRemoteMagpie() || p.SelfAnswered() || p.Key == "" || p.Anthropic == "" {
continue
}
out = append(out, RemoteHub{ID: p.ID, Name: p.Name, Root: strings.TrimRight(p.Anthropic, "/"), Key: p.Key})
out = append(out, RemoteHub{ID: p.ID, Name: p.Name, Root: strings.TrimRight(p.Anthropic, "/"), Key: p.Key, Was: slices.Clone(p.Was)})
}
return out, nil
}
@@ -71,3 +74,11 @@ func noteRemoteHub(ctx context.Context, p Provider) {
found(p.ID)
}
}
// AskRemoteHub asks the Remote magpie id at once whether it serves its
// router, as its next model list would: its switch just turned on.
func AskRemoteHub(ctx context.Context, id string) {
if p, err := Find(id); err == nil && !p.Off {
noteRemoteHub(ctx, *p)
}
}
+17 -1
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"path/filepath"
"reflect"
"slices"
"strings"
"sync"
@@ -70,9 +71,24 @@ func TestRemoteHubNoted(t *testing.T) {
t.Fatalf("found %v, asked %v; want rem, with its key", found, asked)
}
hs, err := RemoteHubs()
if err != nil || len(hs) != 1 || hs[0] != (RemoteHub{ID: "rem", Name: "Rem", Root: srv.URL, Key: "k1"}) {
if err != nil || len(hs) != 1 || !reflect.DeepEqual(hs[0], RemoteHub{ID: "rem", Name: "Rem", Root: srv.URL, Key: "k1"}) {
t.Fatalf("RemoteHubs: %+v %v", hs, err)
}
// renamed (treeman_26897): listed under its id now, with the one it
// had, which its Library server follows
if err := Rename("rem", "office"); err != nil {
t.Fatal(err)
}
id = "office"
if hs, err := RemoteHubs(); err != nil || len(hs) != 1 || hs[0].ID != "office" || !slices.Equal(hs[0].Was, []string{"rem"}) {
t.Fatalf("RemoteHubs after a rename: %+v %v", hs, err)
}
// its switch turned on: asked at once, under its id now
reset()
AskRemoteHub(context.Background(), "office")
if !slices.Equal(found, []string{"office"}) || len(asked) != 1 {
t.Fatalf("asked at once: found %v, asked %v", found, asked)
}
reset()
want = false