Files
magpie/internal/gateway/remote_magpie_test.go
T
a998a36367 provider, gateway: remote magpie serves decision and retrieval APIs (#1282)
* provider, gateway: remote magpie serves decision and retrieval APIs

Configure System One from the remote address and discover explicitly marked
decision models, including Clef and custom names. Keep exposed retrieval
models when importing the remote catalog, without treating decisions as
chat or image generators. Refresh removes stale decisions and the editor
receives an explicit empty decision list when none remain.

Forward caller/session attribution for decision, retrieval and media APIs.
Preserve TUI model-list errors for a remote that cannot be reached. Document
the HTTP API surface and old-peer compatibility.

Verified with the full nogui Go suite, focused race checks, go vet, native
macOS and Linux/Windows cross-builds, and the Remote magpie browser tests in
Chromium and WebKit in English and Chinese. The new System One integration
test fails on the old code with an empty model list, and the retrieval test
fails because the remote embedding model is filtered out. Integration tests
exercise two gateways and simulated upstreams; live vendor accounts were
not used.

* gateway, provider: remote forwards keep official client headers

Claude Code and Codex keep their User-Agent through both gateways, so a
relay behind the remote that admits only official clients accepts their
requests. Only decision, retrieval and media calls set magpie's User-Agent
at their own call sites. The two-hop test covers Messages, Responses, Chat
Completions and a Codex originator with another User-Agent.

Keep entryFor limited to remote decision providers. Test rejection of
unlisted remote decisions and remove the redundant resolveDecideModel
early return: the explicit model marker and list-only Jev already exclude
vendor aliases. Document retrieval entries remaining in the shared agent
catalog and TUI list errors being shown for other mixed providers too.

Verified with the Remote magpie provider/gateway tests. Before the fix,
TestRemoteMagpieClientHeaders fails all four cases with the relay receiving
magpie/dev and returning 403 official client required; all pass after it.
Follow-up to yetone's review of #1282.

* provider, gateway, gui: remote discovery reports only the decisions it lists (#1282)

Show CLI list failures and catalog counts for mixed providers. Derive the
remote decision endpoint from its one editable address, name custom decisions
by their ids, and reuse successful discovery in endpoint tests without an
empty decide OK row. Bare-provider decision selection is documented.

Simplify decision classification around the explicit remote list and reuse
model markers while building Available, Catalog and Deciders, avoiding a
whole-list copy and scan for every model. Other providers keep their rules.

The regression tests failed before the fixes on swallowed CLI errors, blank
labels, extra endpoint fields, empty decide results and repeated discovery.
Deliberately removing retrieval/video User-Agent or System One caller
attribution makes all three receiving-side tests fail with lost agent/via.

Verified with sandboxed Go tests, targeted race checks, Linux GUI/nogui and
Windows vet/build, Chromium/WebKit en/zh browser tests and zh-TW/ja/de checks.
The two-hop tests use real gateway handlers with simulated vendor replies;
real vendor accounts and native Windows/macOS runs were not used.

Co-authored-by: XYenon <register@xyenon.bid>
Amp-Thread-ID: https://ampcode.com/threads/T-01a11cd6-93aa-767c-9d6e-f0db2a9c5bab

* gui, gateway tests: remote decision refresh leaves only its current model choices (#1282)

The empty-decision browser fixture cleared deciders but kept decision
entries in models, so its screenshot still showed the same chips. Remove
those entries and assert the visible choices in both states. Check the
real providerInfo model list after refresh too, with Jev Router retained
as chat, and verify an unnamed remote decision reaches the local picker
with its id and provider label.

No production code changes. Verified all Remote magpie tests in root,
provider, gateway and gui under a sandbox HOME with -race; the new
assertions in gateway/gui pass. Chromium and WebKit pass all six browser
cases in English and Chinese; the corrected screenshot run passes 3/3.
Targeted Linux and Windows nogui vet and gofmt are clean.

Amp-Thread-ID: https://ampcode.com/threads/T-01a11cd6-93aa-767c-9d6e-f0db2a9c5bab
Co-authored-by: XYenon <register@xyenon.bid>

---------

Co-authored-by: Amp <amp@ampcode.com>
2026-10-10 03:55:45 +08:00

135 lines
5.3 KiB
Go

package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// A remote magpie (another computer's gateway as a provider) is asked in
// the API the model's own provider speaks there: a Chat client's request
// for a model served on Anthropic's Messages goes to it as Messages, not as
// Chat to be translated on the other side too; a routing group's, which
// could be any member, goes on in the client's own API. Here the gateway is
// both computers': "office" is it, reached over HTTP, and the vendor behind
// it speaks Anthropic's Messages alone.
func TestRemoteMagpieNativeAPI(t *testing.T) {
var mu sync.Mutex
var vendor, hops []string // paths the vendor, and the remote magpie, were asked on
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
vendor = append(vendor, r.URL.Path+" "+gjsonModel(b))
mu.Unlock()
if strings.HasSuffix(r.URL.Path, "/count_tokens") {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"input_tokens":42}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m1","usage":{"input_tokens":7}}}`,
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}`,
`data: {"type":"content_block_stop","index":0}`,
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":4}}`,
`data: {"type":"message_stop"}`))
}))
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: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Anthropic: up.URL}); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"fake/m1"}}); err != nil {
t.Fatal(err)
}
h := New().Handler()
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
mu.Lock()
hops = append(hops, r.URL.Path)
mu.Unlock()
}
h.ServeHTTP(w, r)
}))
t.Cleanup(remote.Close)
// added as the Add sheet does: the address alone, on the Chat field
id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(remote.URL, "http://")})
if err != nil {
t.Fatal(err)
}
office, err := provider.Find(id)
if err != nil {
t.Fatal(err)
}
if office.Chat != remote.URL+"/v1" || office.Responses != remote.URL+"/v1" || office.Anthropic != remote.URL {
t.Fatalf("endpoints: %q %q %q", office.Chat, office.Responses, office.Anthropic)
}
if _, err := office.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
live, _, _ := catalog.Live("office")
apis := map[string][]string{}
for _, m := range live {
apis[m.ID] = m.APIs
}
if !slices.Equal(apis["fake/m1"], []string{"anthropic"}) {
t.Fatalf("fake/m1 is served on Messages there: %v", apis)
}
if a, ok := apis["group/g"]; !ok || a != nil {
t.Fatalf("the group is listed, on no one API: %v", apis)
}
calls := []struct{ path, body, hop, vendor string }{
// Chat client, a model served on Messages: turned into Messages here, once
{"/v1/chat/completions", `{"model":"office/fake/m1","messages":[{"role":"user","content":"hi"}]}`, "/v1/messages", "/v1/messages m1"},
// Anthropic client: Messages all the way
{"/v1/messages", `{"model":"office/fake/m1","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`, "/v1/messages", "/v1/messages m1"},
{"/v1/messages/count_tokens", `{"model":"office/fake/m1","messages":[{"role":"user","content":"hi"}]}`, "/v1/messages/count_tokens", "/v1/messages/count_tokens m1"},
// a group's request goes on in the client's API; the remote picks
{"/v1/responses", `{"model":"office/group/g","input":"hi","stream":true}`, "/v1/responses", "/v1/messages m1"},
{"/v1beta/models/office/fake/m1:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, "/v1/messages", "/v1/messages m1"},
{"/v1beta/models/office/fake/m1:streamGenerateContent?alt=sse", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, "/v1/messages", "/v1/messages m1"},
}
for _, c := range calls {
mu.Lock()
vendor, hops = nil, nil
mu.Unlock()
code, body := post(t, c.path, c.body)
mu.Lock()
gotHops, gotVendor := slices.Clone(hops), slices.Clone(vendor)
mu.Unlock()
if code != 200 {
t.Fatalf("%s: %d %s", c.path, code, body)
}
if !slices.Equal(gotHops, []string{c.hop}) || !slices.Equal(gotVendor, []string{c.vendor}) {
t.Errorf("%s: remote asked on %v, vendor on %v; want %s, %s", c.path, gotHops, gotVendor, c.hop, c.vendor)
}
if strings.HasSuffix(c.path, "count_tokens") && !strings.Contains(body, `"input_tokens":42`) {
t.Errorf("count: %s", body)
}
if !strings.HasSuffix(c.path, "count_tokens") && !strings.Contains(body, "hello") {
t.Errorf("%s reply: %s", c.path, body)
}
}
}
func gjsonModel(b []byte) string {
var v struct {
Model string `json:"model"`
}
json.Unmarshal(b, &v)
return v.Model
}