Files
magpie/internal/gateway/hub_roots_test.go
T
yetone b78b1de003 library: magpie-image is behind the MCP hub, saving into the calling agent's project
magpie-image was the one MCP server the hub left out, because it saves
what it makes on disk and needs to know whose project that is. The hub
now serves its tools like any other server's and tells it where the
caller works:

1. the hub answers a tools/call as SSE and asks the agent roots/list on
   that stream (3s), as Claude Code answers;
2. else Codex's _meta x-codex-turn-metadata.workspaces (git repos only);
3. else the Codex thread's cwd from its session file
   (sessions.CodexThreadCwd), only with session consent;
4. else none, and the image goes to ~/Pictures/Magpie as before.

The hub passes `magpie/roots` and `magpie/client` in the call's _meta;
imagemcp saves into the first root and names the agent on its usage
row. Its result carries `magpie/model`, which the hub's own usage row
takes, so the row says which image model drew it. A WSL agent keeps
magpie-image as its own entry (the hub can't reach a path inside the
distro). docs/subsystems/mcp-hub.md (mcp-router.md after the next commit), gateway-routing.md and
gateway-sessions.md say so.

It is rebased on #4382 (b889ffe81), which lets the user keep a server
out of the hub (Server.Hub = direct). inHub now asks both: a server
kept direct is out, and magpie-image is in unless the agent is in WSL,
so the user can keep magpie-image direct too; the editor's switch
shows for it like any server, and the hub's line counts it with the
others (mcp-hub-direct.test.cjs follows).

Run at e2583df31 (this stack on 86fef947e), on mote: gofmt -l clean;
go vet for darwin, linux (-tags nogui) and windows; go build ./...;
go test -tags nogui ./... -timeout 45m, 81 packages ok, 0 FAIL;
library, gateway, imagemcp, sessions, cli and gui again alone, ok;
site's node --test, 49 of 49. GUI on xiaomi-gpu (Windows; mote's
browsers crashed under other sessions' suites): library-*, image*,
mcp-hub-direct, i18n-keys, list-sort and plugin-tools, both engines and
every language, 1055 of 1056: i18n-keys found "{name} is given to each
agent directly" dropped from the library's strings in the rebase. Put
back in the first commit; at the pushed head i18n-keys, mcp-hub-direct
and library-mcp-hub are 48 of 48. That is the only difference from
e2583df31.
Broken by hand at e2583df31: imagemcp ignoring magpie/roots fails
TestHubCallSavesInTheCallersProject; the router asking anything but
roots/list fails TestHubAsksTheAgentItsRoots and TestHubRootsUnasked;
inHub leaving magpie-image out fails TestHubGivesMagpieImage.
Real use, sandbox HOME and gateway, at 62421e570 (before the rebase): Claude Code saved into its project
via roots/list; Codex in a git repo via its workspaces _meta; Codex
outside a repo with session consent via the thread's cwd.
At 62421e570 the whole GUI suite ran on WSL magpie-desktop at load 116 to 135 from other
runs: 504 of 15757 red in 118 files, WebKit timeouts, none in a file
this change touches; filed as #4471 with the list.

Rebased once more onto 2570efb5f, which changed library-mcp-hub,
list-sort, mcp-hub-direct and gateway-routing.md. Run at the pushed
head: go build; gateway, library, cli and imagemcp tests ok; the GUI
budget tests ok; on xiaomi-gpu i18n-keys, mcp-hub-direct,
library-mcp-hub and list-sort, 51 of 54. The three reds were WebKit
420px library-mcp-hub cases with no Connect sheet after a reload.
origin/main d77da5bff goes red the same way (de 420px, 9 of 11). In a
second run of library-mcp-hub on WebKit at this head, 11 of 11 passed.
Filed as #4483.
Not tried: Codex outside a git repo without consent (it saves to
~/Pictures/Magpie, #4435); agents on Windows and in WSL with real use.
2026-10-31 02:49:08 +08:00

254 lines
9.9 KiB
Go

package gateway
import (
"bufio"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/usage"
)
// rootsHub is a hub with magpie's image server (a Roots tool) and another,
// each call's caller kept.
func rootsHub(t *testing.T) (*fakeHub, chan HubCaller) {
t.Helper()
got := make(chan HubCaller, 8)
f := &fakeHub{on: true, tools: map[string][]HubTool{"claude": {
{Server: "magpie-image", Tool: "generate_image", Spec: hubSpec("generate_image"), Roots: true},
{Server: "fs", Tool: "read", Spec: hubSpec("read")},
}}}
f.call = func(ctx context.Context, server, tool string) (json.RawMessage, error) {
got <- HubCallerOf(ctx)
return json.RawMessage(`{"content":[{"type":"text","text":"ran ` + server + `"}]}`), nil
}
withHub(t, f)
return f, got
}
// hubEvents reads a stream's data lines, one message each.
func hubEvents(t *testing.T, res *http.Response) <-chan mcpMessage {
t.Helper()
out := make(chan mcpMessage, 8)
go func() {
defer close(out)
sc := bufio.NewScanner(res.Body)
for sc.Scan() {
if d, ok := strings.CutPrefix(sc.Text(), "data: "); ok {
var m mcpMessage
json.Unmarshal([]byte(d), &m)
out <- m
}
}
}()
return out
}
func nextEvent(t *testing.T, ev <-chan mcpMessage, what string) mcpMessage {
t.Helper()
select {
case m, ok := <-ev:
if !ok {
t.Fatalf("the stream ended before %s", what)
}
return m
case <-time.After(10 * time.Second):
t.Fatalf("no %s in 10s", what)
}
return mcpMessage{}
}
func hubPostTo(t *testing.T, url, body, accept, ua string) *http.Response {
t.Helper()
r, _ := http.NewRequest(http.MethodPost, url, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Accept", accept)
r.Header.Set("User-Agent", ua)
res, err := http.DefaultClient.Do(r)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { res.Body.Close() })
return res
}
const bothAccept = "application/json, text/event-stream"
// magpie-image behind the hub saves into the calling agent's project: a
// call of it asks the agent roots/list on the call's own event stream
// (Claude Code answers so), and the image server is called with the
// file roots the agent answered and the agent's name. A tool that
// doesn't write into the project is answered as before, in JSON, and
// asks nothing.
func TestHubAsksTheAgentItsRoots(t *testing.T) {
fresh(t)
_, got := rootsHub(t)
srv := httptest.NewServer(lanGuard(New().Handler()))
t.Cleanup(srv.Close)
url := srv.URL + HubMCPPath + "claude"
res := hubPostTo(t, url, toolsCall("magpie-image__generate_image", `{"prompt":"a magpie"}`), bothAccept, "claude-code/2.1.314 (sdk-cli)")
if res.StatusCode != 200 || !strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") {
t.Fatalf("%d %s", res.StatusCode, res.Header.Get("Content-Type"))
}
ev := hubEvents(t, res)
ask := nextEvent(t, ev, "roots/list")
if ask.Method != "roots/list" || len(ask.ID) == 0 {
t.Fatalf("asked %+v, want roots/list", ask)
}
ans := hubPostTo(t, url, `{"jsonrpc":"2.0","id":`+string(ask.ID)+`,"result":{"roots":[{"uri":"file:///work/proj","name":"proj"},{"uri":"https://example.com/x"}]}}`, bothAccept, "claude-code/2.1.314 (sdk-cli)")
if ans.StatusCode != http.StatusAccepted {
t.Fatalf("the answer: %d", ans.StatusCode)
}
done := nextEvent(t, ev, "the call's result")
if string(done.ID) != "3" || !strings.Contains(string(done.Result), "ran magpie-image") {
t.Fatalf("result %s %s", done.ID, done.Result)
}
c := <-got
if strings.Join(c.Roots, " ") != "file:///work/proj" || c.Client != "claude-code/2.1.314" {
t.Fatalf("called for %+v, want the file root and claude-code/2.1.314", c)
}
// another server: JSON, as before, with no caller
res = hubPostTo(t, url, toolsCall("fs__read", `{"q":"x"}`), bothAccept, "claude-code/2.1.314 (sdk-cli)")
if !strings.HasPrefix(res.Header.Get("Content-Type"), "application/json") {
t.Fatalf("fs__read answered as %s", res.Header.Get("Content-Type"))
}
if c := <-got; len(c.Roots) != 0 || c.Client != "" {
t.Fatalf("fs__read called for %+v", c)
}
}
// An agent that takes no event stream back isn't asked, and one that
// doesn't answer holds the call no longer than hubRootsWait: the image
// server is called with no roots (it saves into ~/Pictures/Magpie then).
func TestHubRootsUnasked(t *testing.T) {
fresh(t)
_, got := rootsHub(t)
old := hubRootsWait
hubRootsWait = 200 * time.Millisecond
t.Cleanup(func() { hubRootsWait = old })
srv := httptest.NewServer(lanGuard(New().Handler()))
t.Cleanup(srv.Close)
url := srv.URL + HubMCPPath + "claude"
call := toolsCall("magpie-image__generate_image", `{}`)
res := hubPostTo(t, url, call, "application/json", "some-client/1")
if !strings.HasPrefix(res.Header.Get("Content-Type"), "application/json") {
t.Fatalf("JSON only: answered as %s", res.Header.Get("Content-Type"))
}
if c := <-got; len(c.Roots) != 0 || c.Client != "some-client/1" {
t.Fatalf("JSON only: called for %+v", c)
}
start := time.Now()
ev := hubEvents(t, hubPostTo(t, url, call, bothAccept, "some-client/1"))
if m := nextEvent(t, ev, "roots/list"); m.Method != "roots/list" {
t.Fatalf("asked %+v", m)
}
if m := nextEvent(t, ev, "the call's result"); !strings.Contains(string(m.Result), "ran magpie-image") {
t.Fatalf("result %s", m.Result)
}
if c := <-got; len(c.Roots) != 0 {
t.Fatalf("unanswered: called for %+v", c)
}
if d := time.Since(start); d < hubRootsWait {
t.Errorf("the call didn't wait for the answer: %s", d)
}
}
// Codex declares no roots and answers roots/list with none, but names
// its thread in each call's _meta, and in a git repository the repository
// too: the image server is given that folder, else the one the thread
// runs in. A call from another computer is given no folder
// of this one, whatever it names.
func TestHubRootsOfACodexThread(t *testing.T) {
fresh(t)
codex := t.TempDir()
t.Setenv("CODEX_HOME", codex)
const id = "019a1111-2222-7333-8444-555566667777"
day := filepath.Join(codex, "sessions", "2026", "10", "30")
os.MkdirAll(day, 0o755)
os.WriteFile(filepath.Join(day, "rollout-2026-10-30T09-00-00-"+id+".jsonl"),
[]byte(`{"timestamp":"2026-10-30T09:00:00Z","type":"session_meta","payload":{"id":"`+id+`","cwd":"/work/proj"}}`+"\n"), 0o644)
f, got := rootsHub(t)
f.tools["codex"] = f.tools["claude"]
srv := httptest.NewServer(lanGuard(New().Handler()))
t.Cleanup(srv.Close)
call := `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"magpie-image__generate_image","arguments":{},"_meta":{"threadId":"` + id + `"}}}`
ev := hubEvents(t, hubPostTo(t, srv.URL+HubMCPPath+"codex", call, bothAccept, "codex-mcp-client/0.165.0"))
ask := nextEvent(t, ev, "roots/list")
hubPostTo(t, srv.URL+HubMCPPath+"codex", `{"jsonrpc":"2.0","id":`+string(ask.ID)+`,"result":{"roots":[]}}`, bothAccept, "codex-mcp-client/0.165.0")
nextEvent(t, ev, "the call's result")
if c := <-got; strings.Join(c.Roots, " ") != "file:///work/proj" || c.Client != "codex-mcp-client/0.165.0" {
t.Fatalf("called for %+v, want the thread's folder", c)
}
// in a git repository Codex names it in the turn's metadata, which is
// read before any rollout (a thread this computer has none of here)
inRepo := `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"magpie-image__generate_image","arguments":{},"_meta":{"threadId":"019a0000-0000-7000-8000-000000000000","x-codex-turn-metadata":{"workspaces":{"/work/repo":{"has_changes":false},"relative":{}}}}}}`
ev = hubEvents(t, hubPostTo(t, srv.URL+HubMCPPath+"codex", inRepo, bothAccept, "codex-mcp-client/0.165.0"))
ask = nextEvent(t, ev, "roots/list")
hubPostTo(t, srv.URL+HubMCPPath+"codex", `{"jsonrpc":"2.0","id":`+string(ask.ID)+`,"result":{"roots":[]}}`, bothAccept, "codex-mcp-client/0.165.0")
nextEvent(t, ev, "the call's result")
if c := <-got; strings.Join(c.Roots, " ") != "file:///work/repo" {
t.Fatalf("called for %+v, want the turn's workspace", c)
}
_, secrets := newCaller(t, "Laptop")
h := lanGuard(New().Handler())
m := readMCP(t, hubPost(h, "codex", "192.0.2.7:4000", call, "Authorization", "Bearer "+secrets[0], "Accept", "application/json"))
if m.Result.IsError {
t.Fatalf("remote call: %+v", m)
}
if c := <-got; len(c.Roots) != 0 {
t.Fatalf("a call from another computer was given %v", c.Roots)
}
}
func TestFileURI(t *testing.T) {
for in, want := range map[string]string{"/work/my proj": "file:///work/my%20proj", `C:\Users\me\p`: "file:///C:/Users/me/p"} {
if filepath.Separator == '/' && strings.Contains(in, `\`) {
continue // a Windows path is one name elsewhere
}
if got := fileURI(in); got != want {
t.Errorf("fileURI(%q) = %q, want %q", in, got, want)
}
}
}
// magpie's image server draws through the gateway on a connection of its
// own, so the hub's row of its call learns the model from the result's
// _meta, as the server's own report gave it before the hub. Another
// server's _meta names nothing: only magpie's own tools say a model.
func TestHubRowNamesTheImageModel(t *testing.T) {
fresh(t)
f, _ := rootsHub(t)
f.call = func(ctx context.Context, server, tool string) (json.RawMessage, error) {
return json.RawMessage(`{"content":[{"type":"text","text":"ran ` + server + `"}],"_meta":{"` + HubModelMeta + `":"art/painter-` + server + `"}}`), nil
}
srv := httptest.NewServer(lanGuard(New().Handler()))
t.Cleanup(srv.Close)
url := srv.URL + HubMCPPath + "claude"
hubPostTo(t, url, toolsCall("magpie-image__generate_image", `{}`), "application/json", "claude-code/2.1.314 (sdk-cli)")
hubPostTo(t, url, toolsCall("fs__read", `{}`), "application/json", "claude-code/2.1.314 (sdk-cli)")
var rows []usage.Record
for end := time.Now().Add(10 * time.Second); time.Now().Before(end) && len(rows) < 2; time.Sleep(5 * time.Millisecond) {
rows = mcpRows(t)
}
got := map[string]string{}
for _, r := range rows {
got[r.Requested] = r.Provider + "/" + r.Model
}
if got["magpie-image__generate_image"] != "art/painter-magpie-image" || got["fs__read"] != "/" {
t.Fatalf("rows name %v", got)
}
}