diff --git a/docs/reference.md b/docs/reference.md index 01a6203ff..425e3f993 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -300,8 +300,23 @@ Completions, token counting — and a model the shared magpie's provider serves on another API only is turned into that API once, never on both computers. Its list is the models the shared magpie's agents are shown, each named with its provider there (`Claude Sonnet 5 · Relay A · office`) — the ids stay ids -(`office/relay-a/claude-sonnet-5`), only these labels carry the names — and its image -models are listed under Settings → Images and draw through it. +(`office/relay-a/claude-sonnet-5`), only these labels carry the names. +Its image and video models are discovered automatically and served through +its image generation/edit and video creation/status/content APIs. System One +is also configured automatically at its `/v1/systemone`: refresh the remote +provider's model list to discover its decision models, including Jev, Clef +and models with custom names. These appear as decision models rather than +chat models. A bare provider id such as `office` asks the first listed +decision model; it does not pick another model to satisfy a key's limits. +If the key permits only another model, use its full `office/provider/model` +id to avoid a 403. Embeddings and rerank requests use the remote's corresponding +APIs, and its exposed retrieval models are kept when fetching its list. +These remain in agent model lists as on the remote; being listed does not +mean an embedding or rerank model can hold a conversation. +The remote must serve the requested API and model, and allow the supplied +key to use them. Responses uses HTTP, including SSE, rather than WebSocket. +An older remote without decision-model discovery still serves its existing +APIs; update it and refresh the list to expose System One models here. Its quotas show too: the Usage page, the menu bar and `magpie quota` list the shared magpie's cards named with it (`Codex · office`, id `office/codex`), as that magpie last read them — only the computer holding the sign-ins asks the diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 8b622c5ab..6836d4f7b 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -67,9 +67,34 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN: `geminiCompat`) is asked for the model's thoughts in `extra_body.google.thinking_config`. A 400 naming it (`refusesThinkingConfig`) marks the provider unfit for the field (`thinking_config`), and it is asked again with `reasoning_effort` alone. Gemini 3 can't stop thinking, so reasoning turned off goes at `minimal`, or at the model's lowest level where its levels are known and have no `minimal` (`geminiOffLevel`). Google's 400 for `minimal` (`geminiMinimalRefused`; gemini-3.8-flash's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL") names thinking too, but isn't the field turned away: the model is marked as refusing reasoning off (`offRefused`) and asked again at its lowest level, and so from then on, still asked for its thoughts. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta's `extra_content.google.thought`, and such a chunk is read as thinking. - A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`). +## Remote magpie APIs + +A remote provider serves the conversation, token-counting, System One, +embeddings, rerank, image generation/edit and video creation/status/content +APIs. Gemini clients enter through the local Gemini adapter and follow the +same model routing as other conversation clients. Responses uses HTTP/SSE; +its WebSocket route still answers 426. Discovery and older-peer behavior +are described in [Providers and accounts](providers-accounts.md#remote-magpie). + +System One uses `RouteDecider` and `postDecide` in +[`decide.go`](../../internal/gateway/decide.go), taking one provider prefix +off at each hop and preserving the state, questions and vendor errors. +[`embeddings.go`](../../internal/gateway/embeddings.go) relays retrieval +bodies and options, [`draw.go`](../../internal/gateway/draw.go) sends images +to the remote's images API, and [`video.go`](../../internal/gateway/video.go) +wraps remote task ids for later polls and downloads. `passOnCaller` in +[`remote_magpie.go`](../../internal/gateway/remote_magpie.go) supplies +caller/session headers without replacing the outgoing User-Agent. +Conversation forwarding preserves Claude Code and Codex client headers +(including Codex's `originator`) so relays behind the remote can recognize +them. Decision, retrieval and media requests set magpie's User-Agent at +their own call sites, so the remote accepts their attribution. Vendors +receive no caller labels. + ## Verification ```sh +go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie' go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestGeminiThinkingOffAtItsLowest|TestGeminiThoughtsMarkedInExtraContent|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls' go test -tags nogui ./internal/gateway -run 'TestCodexModelList|TestCodexModelsEtag' go test -tags nogui ./internal/provider -run 'TestGroup|TestCodexCreditsSwitch|TestRenewedAccountForgetsItsAllowance|TestDeclareSearch|TestNative|TestKeyAllowance|TestPlanKeyAllowance|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestSkipsRedaction|TestSetRPM' diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 84b00d47c..9860af533 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -35,6 +35,47 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) | | Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. User-supplied headers still apply through `Sign`. | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) | +## Remote magpie + +A `remote-magpie` provider derives Chat, Responses, Messages and System One +bases from one address (`remoteMagpieEndpoints` in +[`remote_magpie.go`](../../internal/provider/remote_magpie.go)). Its model +list requests images, videos and decisions with `X-Magpie-Drawers`, +`X-Magpie-Videomakers` and `X-Magpie-Deciders`. The gateway includes these +only when asked, with `kind` of `image`, `video` or `decision`. Decision +entries pass through `keyAllowed`, including model and account restrictions. +[`catalog/live.go`](../../internal/catalog/live.go) keeps each kind and all +models the remote already exposed, including retrieval models. The shared +list has no separate retrieval kind: these entries remain in `Catalog` and +agent model lists, just as on the remote. Keeping them makes retrieval +routing possible; their presence does not mean they support conversations. + +`DecidesModel` uses the remote's explicit decision marker, so Clef and custom +names work and a chat model named Jev Router stays a chat model. `Deciders` +and the provider editor offer these decisions even when the user's local +conversation picks omit them. Only remote decision entries use `entryFor` +to apply user model names and limits; other decision providers retain their +previous entry formatting. The editor's `providerInfo` in +[`providers.go`](../../internal/gui/providers.go) sends `deciders: []` when +the remote has none, suppressing the UI's legacy name-based guessing. +The editor offers one remote address; its System One endpoint is derived +from that address and has no separate input. Unnamed decisions use their +model ids for display names and provider labels. +Refresh replaces the list: removed decisions stop routing, and an empty +remote list never gains a fabricated Jev alias. +An older peer without the decision-list extension continues serving its +other APIs but must be updated before its decisions can be discovered. +See [`decide.go`](../../internal/provider/decide.go). + +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 +(`announce` in [`providers_cli.go`](../../providers_cli.go), `addKeyAsk` in +[`pages.go`](../../internal/tui/pages.go)). A remote's endpoint test reuses +successful model discovery for its decision result, and reports none when +no decision model was discovered (`Test` in +[`test.go`](../../internal/provider/test.go)). + ## Runtime path 1. **Add.** The Providers page adds a key provider through `Add` or `Save`, or an account through `StartSignIn`. An agent signed in on its own is found by `Accounts` with no step from the user. @@ -70,6 +111,7 @@ go test -tags nogui ./internal/provider -run 'TestAccount|TestCodex|TestGroup|Te go test -tags nogui ./internal/provider -run 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap' go test -tags nogui . -run TestAccountCapCmd node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs +go test -tags nogui ./internal/provider -run 'TestRemoteMagpie' go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestAddCopy|TestBackupBalanceToken' go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret go test -tags nogui ./internal/backup ./internal/davsync -run 'TestRoundTrip|TestNoKeys|BalanceToken' diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index e64e8261a..8f238bb0e 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -77,6 +77,9 @@ type Model struct { // with (a Remote magpie's Grok Imagine Video): kept with the list for // its videos API, never offered as a model to talk to or draw with. Films bool `json:",omitempty"` + // Decides marks a decision model another magpie explicitly lists, + // including models whose ids don't name Jev. + Decides bool `json:",omitempty"` // Free is set on a model a subscription serves at no cost to its // allowance: WorkBuddy's "credits": "x0.00". Free bool `json:",omitempty"` diff --git a/internal/catalog/live.go b/internal/catalog/live.go index 350537ca3..9a83d4557 100644 --- a/internal/catalog/live.go +++ b/internal/catalog/live.go @@ -287,11 +287,13 @@ func fetchOne(ctx context.Context, url, key string, anthropic bool, headers map[ if id == "" { continue } - // a model that draws is kept, marked, for Settings → Images; any - // other that isn't for text (embeddings, speech) is left out + // Another magpie's list is already what its user exposed. Keep + // its retrieval models too; a vendor's general list still leaves + // out models agents can't chat with. + decision := r.Kind == "decision" films := r.Kind == "video" - drawer := !films && (DrawsID(id) && !strings.Contains(strings.ToLower(id), "deep-research") || r.Kind == "image") - if !drawer && !films && !textModel(mdModel{ID: id}) { + drawer := !films && !decision && (DrawsID(id) && !strings.Contains(strings.ToLower(id), "deep-research") || r.Kind == "image") + if !drawer && !films && !decision && headers["X-Magpie-Drawers"] == "" && !textModel(mdModel{ID: id}) { continue } name := r.DisplayName @@ -309,7 +311,7 @@ func fetchOne(ctx context.Context, url, key string, anthropic bool, headers map[ if len(apis) == 0 { apis = targetAPIs(r.TypeTarget) } - m := Model{ID: id, Name: name, ImageInput: input, APIs: apis, Draws: drawer, Films: films} + m := Model{ID: id, Name: name, ImageInput: input, APIs: apis, Draws: drawer, Films: films, Decides: decision} if n, ok := r.ContextLength.(float64); ok && n > 0 { m.Context = int(n) } @@ -382,8 +384,7 @@ type liveModel struct { Output any `json:"max_output_tokens"` Levels any `json:"supported_reasoning_levels"` // another magpie's name for the model with its provider there after - // it, and "image" on one it draws with, "video" on one it makes videos - // with + // it, and "image", "video" or "decision" for its other models Label string `json:"magpie_label"` Kind string `json:"kind"` // how another magpie searches the web for the model: "native" or diff --git a/internal/gateway/decide.go b/internal/gateway/decide.go index 600752f33..9b485b584 100644 --- a/internal/gateway/decide.go +++ b/internal/gateway/decide.go @@ -366,6 +366,10 @@ func (s *Server) postDecide(ctx context.Context, p provider.Provider, model stri } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", RouterAgent) + if p.IsRemoteMagpie() { + req.Header.Set("User-Agent", "magpie/"+Version) + passOnCaller(ctx, req) + } if via == provider.ViaVercelEval { // what the AI SDK's gateway provider sends with an evaluation req.Header.Set("ai-gateway-protocol-version", "0.0.1") @@ -376,7 +380,7 @@ func (s *Server) postDecide(ctx context.Context, p provider.Provider, model stri if err := p.Sign(ctx, req, provider.Chat, body); err != nil { return 0, nil, "", err } - res, err := s.client.Do(req) + res, err := p.Do(s.client, req) if err != nil { return 0, nil, "", fmt.Errorf("%s: %v", p.Name, err) } @@ -456,7 +460,8 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) { } seat := decideSeat(p, model) var used Usage - tr := s.trace.begin(Route{Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Model: asked, Provider: p.ID, + who := callerOf(r) + tr := s.trace.begin(Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: p.ID, Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Start: start}}}) end := func(status int, msg string, tokens int) { ms := time.Since(start).Milliseconds() @@ -494,7 +499,7 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) { if p.Account == nil && p.Key != "" { keyID, keyName = provider.KeyID(p.Key), p.KeyName } - appendUsage(r, usage.Record{RouteID: tr.ID, Time: start, Agent: agentOf(r), Provider: p.ID, Host: p.Where(), Model: model, Requested: asked, Served: use.Model, + appendUsage(r, usage.Record{RouteID: tr.ID, Time: start, Agent: who.agent, Via: who.via, Provider: p.ID, Host: p.Where(), Model: model, Requested: asked, Served: use.Model, ProviderKeyID: keyID, ProviderKeyName: keyName, ProviderAccount: accountOf(p), Input: use.Usage.Input, Output: use.Usage.Output, Millis: time.Since(start).Milliseconds(), Status: status}) end(status, errMsg, tokens) diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 34d4c019e..a081e4327 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -702,6 +702,7 @@ func (s *Server) sendWith(ctx context.Context, p provider.Provider, method, url, req.Header.Set("Content-Type", contentType) } if p.IsRemoteMagpie() { + req.Header.Set("User-Agent", "magpie/"+Version) passOnCaller(ctx, req) } if sign { diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index 01898ded4..ea4451309 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -189,6 +189,7 @@ func (s *Server) retrieveFrom(ctx context.Context, p provider.Provider, url stri req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") if p.IsRemoteMagpie() { + req.Header.Set("User-Agent", "magpie/"+Version) passOnCaller(ctx, req) } if err := p.Sign(ctx, req, provider.Chat, body); err != nil { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 917f7c591..182fc128d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -840,6 +840,19 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) { if r.Header.Get(provider.VideomakersHeader) != "" { data = append(data, videomakerObjects()...) } + if r.Header.Get(provider.DecidersHeader) != "" { + deciders := keyAllowed(r, provider.Deciders()) + for i := range deciders { + deciders[i].Name = cmp.Or(deciders[i].Name, deciders[i].Model) + } + labels := provider.Labels(deciders) + for i, e := range deciders { + m := modelObject(e) + m["kind"], m["magpie_label"] = "decision", labels[i] + m["native_endpoints"] = []string{"/v1/systemone"} + data = append(data, m) + } + } // ?format=text: the ids one a line, to paste into a client that takes // its models typed by hand, one a line, and asks no list of its own // (ZCode's custom provider), from a browser on another computer with diff --git a/internal/gateway/remote_magpie_apis_test.go b/internal/gateway/remote_magpie_apis_test.go new file mode 100644 index 000000000..4b2d6c423 --- /dev/null +++ b/internal/gateway/remote_magpie_apis_test.go @@ -0,0 +1,241 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// Discover decision models through a real gateway, including names that +// aren't Jev's, then ask them through another gateway with caller attribution. +func TestRemoteMagpieSystemOne(t *testing.T) { + fresh(t) + type hit struct { + path, body string + head http.Header + } + var mu sync.Mutex + var vendor, hops []hit + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + vendor = append(vendor, hit{r.URL.Path, string(b), r.Header.Clone()}) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"answers":{"ok":{"value":true}},"usage":{"input_tokens":3,"output_tokens":1}}`) + })) + t.Cleanup(up.Close) + models := []string{"jev-latest", "@cf/cloudflare/clef", "decision-model-preview", "custom-image-decision"} + if err := provider.Save(provider.Provider{ID: "judge", Name: "Judge", Key: "vendor-key", Decide: up.URL + "/v1", Models: models}); err != nil { + t.Fatal(err) + } + peer := New() + remoteHandler := peer.Handler() + remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(strings.NewReader(string(b))) + mu.Lock() + hops = append(hops, hit{r.URL.Path, string(b), r.Header.Clone()}) + mu.Unlock() + remoteHandler.ServeHTTP(w, r) + })) + t.Cleanup(remote.Close) + if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Chat: remote.URL, Key: "remote-key"}); err != nil { + t.Fatal(err) + } + p, _ := provider.Find("office") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + var got []string + for _, e := range provider.Deciders() { + if e.Provider.ID == "office" { + got = append(got, e.Model) + if e.Model == "judge/custom-image-decision" && e.Name != "custom-image-decision · Judge" { + t.Errorf("unnamed remote decision in the local picker: %q", e.Name) + } + } + } + want := make([]string, len(models)) + for i, m := range models { + want[i] = "judge/" + m + } + if !slices.Equal(got, want) { + t.Fatalf("remote decision models: %v; want %v", got, want) + } + if ms := p.DecisionModels(); len(ms) != len(models) { + t.Fatalf("decision picker has %v", ms) + } + for _, e := range provider.Catalog() { + if e.Provider.ID == "office" && slices.Contains(want, e.Model) { + t.Fatalf("decision model offered for chat: %s", e.ID) + } + } + // Ordinary agent lists never acquire decision models. + plain := httptest.NewRecorder() + remoteHandler.ServeHTTP(plain, httptest.NewRequest("GET", "/v1/models", nil)) + if strings.Contains(plain.Body.String(), `"kind":"decision"`) || strings.Contains(plain.Body.String(), "judge/") { + t.Fatalf("decisions leaked into ordinary models: %s", plain.Body.String()) + } + s := New() + for _, model := range models { + req := httptest.NewRequest("POST", "/v1/systemone", strings.NewReader(`{"model":"office/judge/`+model+`","state":{"message":"hello"},"questions":{"ok":{"type":"noul"}}}`)) + req.Header.Set("User-Agent", "pi/1.0") + req.Header.Set(SessionHeader, "decision-session") + req.Header.Set("session_id", "native-session") + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"value":true`) { + t.Fatalf("%s: %d %s", model, rec.Code, rec.Body.String()) + } + } + mu.Lock() + defer mu.Unlock() + if len(vendor) != len(models) { + t.Fatalf("vendor calls: %v", vendor) + } + for i, h := range vendor { + if h.path != "/v1/systemone" || gjsonModel([]byte(h.body)) != models[i] || h.head.Get("Authorization") != "Bearer vendor-key" || !strings.Contains(h.body, `"message":"hello"`) { + t.Errorf("vendor call: %+v", h) + } + if h.head.Get(AgentHeader) != "" || h.head.Get(SessionHeader) != "" || h.head.Get("session_id") != "" { + t.Errorf("caller headers reached vendor: %v", h.head) + } + } + for _, h := range hops { + if h.path != "/v1/systemone" { + continue + } + if h.head.Get("Authorization") != "Bearer remote-key" || h.head.Get(AgentHeader) != "pi" || h.head.Get(ViaHeader) == "" || h.head.Get(SessionHeader) != "decision-session" || h.head.Get("session_id") != "native-session" || !strings.HasPrefix(h.head.Get("User-Agent"), "magpie/") { + t.Errorf("remote caller: %v", h.head) + } + } + if route := s.trace.routes[0]; route.Agent != "pi" || route.Session != "decision-session" || !route.Done { + t.Errorf("decision trace: %+v", route) + } + for _, route := range peer.trace.routes { + if route.Agent != "pi" || route.Session != "decision-session" { + t.Errorf("remote decision trace lost caller: %+v", route) + } + } + var recorded int + for _, r := range usage.Load(time.Time{}) { + if r.Provider == "judge" { + recorded++ + if r.Agent != "pi" || r.Via != hostName() { + t.Errorf("remote decision usage lost caller: %+v", r) + } + } + } + if recorded != len(models) { + t.Errorf("remote decision usage: %d records; want %d", recorded, len(models)) + } +} + +// Decision discovery applies the gateway key's model restrictions, while +// an ordinary /models request continues to contain conversation models only. +func TestRemoteMagpieDecisionListPermissions(t *testing.T) { + fresh(t) + if err := provider.Save(provider.Provider{ID: "judge", Decide: "http://127.0.0.1:1/v1", Key: "k", Models: []string{"custom-a", "custom-b"}}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Held") + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"judge/custom-a"}}); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("GET", "/v1/models", nil) + req.Header.Set("Authorization", "Bearer "+secrets[0]) + req.Header.Set(provider.DecidersHeader, "1") + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + var list struct { + Data []struct { + ID, Kind string + Name string `json:"display_name"` + Label string `json:"magpie_label"` + } + } + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &list) != nil || len(list.Data) != 1 || list.Data[0].ID != "judge/custom-a" || list.Data[0].Kind != "decision" { + t.Fatalf("held decision list: %d %s", rec.Code, rec.Body.String()) + } + if list.Data[0].Name != "custom-a" || list.Data[0].Label != "custom-a · judge" { + t.Errorf("unnamed decision lost its id: %+v", list.Data[0]) + } +} + +// A remote's exposed retrieval models survive discovery, and their requests +// keep the input and options through both gateways. +func TestRemoteMagpieRetrieval(t *testing.T) { + s, lib := shelved(t) + remote := httptest.NewServer(s.Handler()) + t.Cleanup(remote.Close) + if err := provider.Save(provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Chat: remote.URL, Key: "remote-key"}); err != nil { + t.Fatal(err) + } + p, _ := provider.Find("office") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + live, _, _ := catalog.Live("office") + if !slices.ContainsFunc(live, func(m catalog.Model) bool { return m.ID == "lib/embed-1" }) { + t.Fatalf("remote embedding model lost: %v", live) + } + // The shared list has no separate retrieval kind, so these stay in + // the local catalog just as they do in the remote's agent list. + entries := provider.Catalog() + for _, id := range []string{"office/lib/embed-1", "office/lib/rerank-1"} { + if !slices.ContainsFunc(entries, func(e provider.Entry) bool { return e.ID == id }) { + t.Errorf("remote retrieval entry missing from catalog: %s", id) + } + } + for _, tc := range []struct{ path, body, result, model string }{ + {"/v1/embeddings", `{"model":"office/lib/embed-1","input":["hello","world"],"dimensions":2,"encoding_format":"float"}`, `"embedding":[0.1,-0.2]`, "embed-1"}, + {"/v1/rerank", `{"model":"office/lib/rerank-1","query":"magpie","documents":["a crow","a magpie"],"top_n":2,"return_documents":true}`, `"relevance_score":0.9`, "rerank-1"}, + } { + req := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)) + req.Header.Set("User-Agent", "pi/1.0") + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + code, raw := rec.Code, rec.Body.String() + if code != 200 || !strings.Contains(raw, tc.result) { + t.Fatalf("%s: %d %s", tc.path, code, raw) + } + got := lib.got(tc.path) + if len(got) != 1 || gjsonModel([]byte(got[0])) != tc.model { + t.Fatalf("vendor request: %v", got) + } + var asked, sent map[string]any + json.Unmarshal([]byte(tc.body), &asked) + json.Unmarshal([]byte(got[0]), &sent) + asked["model"] = tc.model + a, _ := json.Marshal(asked) + b, _ := json.Marshal(sent) + if string(a) != string(b) { + t.Errorf("retrieval options changed: %s; want %s", b, a) + } + } + var recorded int + for _, r := range usage.Load(time.Time{}) { + if r.Provider == "lib" { + recorded++ + if r.Agent != "pi" || r.Via != hostName() { + t.Errorf("remote retrieval usage lost caller: %+v", r) + } + } + } + if recorded != 2 { + t.Errorf("remote retrieval usage: %d records; want 2", recorded) + } +} diff --git a/internal/gateway/remote_magpie_client_test.go b/internal/gateway/remote_magpie_client_test.go new file mode 100644 index 000000000..1faff72ac --- /dev/null +++ b/internal/gateway/remote_magpie_client_test.go @@ -0,0 +1,90 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A relay that admits only its official client must see the same client +// headers after both gateways, on Messages, Responses and Chat Completions. +func TestRemoteMagpieClientHeaders(t *testing.T) { + for _, tc := range []struct { + name, path, body, agent, originator, reply string + proto provider.Protocol + }{ + {"claude", "/v1/messages", `{"model":"office/relay/m1","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, + "claude-cli/2.1.0 (external, cli)", "", `{"id":"m","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"hello"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`, provider.Anthropic}, + {"codex-responses", "/v1/responses", `{"model":"office/relay/m1","input":"hi","stream":false}`, + "codex_cli_rs/0.159.2 (Mac OS 26.6.0; arm64) kitty", "codex_cli_rs", `{"id":"r","object":"response","status":"completed","output":[]}`, provider.Responses}, + {"codex-chat", "/v1/chat/completions", `{"model":"office/relay/m1","messages":[{"role":"user","content":"hi"}],"stream":false}`, + "Codex Desktop/0.162.3 (Windows 10.0.26100; x86_64) unknown", "Codex Desktop", `{"id":"c","choices":[{"message":{"role":"assistant","content":"hello"},"finish_reason":"stop"}]}`, provider.Chat}, + {"codex-originator", "/v1/chat/completions", `{"model":"office/relay/m1","messages":[{"role":"user","content":"hi"}],"stream":false}`, + "client/1.0", "codex_exec", `{"id":"c","choices":[{"message":{"role":"assistant","content":"hello"},"finish_reason":"stop"}]}`, provider.Chat}, + } { + t.Run(tc.name, func(t *testing.T) { + fresh(t) + headers := make(chan http.Header, 1) + relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case headers <- r.Header.Clone(): + default: + } + if r.Header.Get("User-Agent") != tc.agent || r.Header.Get("originator") != tc.originator { + http.Error(w, "official client required", http.StatusForbidden) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, tc.reply) + })) + t.Cleanup(relay.Close) + p := provider.Provider{ID: "relay", Key: "relay-key", Models: []string{"m1"}} + switch tc.proto { + case provider.Anthropic: + p.Anthropic = relay.URL + case provider.Responses: + p.Responses = relay.URL + "/v1" + case provider.Chat: + p.Chat = relay.URL + "/v1" + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + remote := httptest.NewServer(New().Handler()) + t.Cleanup(remote.Close) + if err := provider.Save(provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Chat: remote.URL, Key: "remote-key"}); err != nil { + t.Fatal(err) + } + office, _ := provider.Find("office") + if _, err := office.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)) + req.Header.Set("User-Agent", tc.agent) + req.Header.Set("originator", tc.originator) + req.Header.Set("x-app", "cli") + req.Header.Set("session_id", "client-session") + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + select { + case h := <-headers: + if h.Get("User-Agent") != tc.agent || h.Get("originator") != tc.originator { + t.Errorf("relay client headers: %v", h) + } + if h.Get("Authorization") != "Bearer relay-key" || h.Get(AgentHeader) != "" || h.Get(ViaHeader) != "" { + t.Errorf("relay authentication or caller headers: %v", h) + } + default: + t.Error("relay received no request") + } + if rec.Code != http.StatusOK { + t.Fatalf("%s: %d %s", tc.path, rec.Code, rec.Body.String()) + } + }) + } +} diff --git a/internal/gateway/remote_magpie_media_test.go b/internal/gateway/remote_magpie_media_test.go new file mode 100644 index 000000000..fd855692f --- /dev/null +++ b/internal/gateway/remote_magpie_media_test.go @@ -0,0 +1,128 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/json" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Remote media uses the remote's images and videos APIs, including edits, +// polls and content downloads, with local video ids surviving every poll. +func TestRemoteMagpieMedia(t *testing.T) { + grokSignedIn(t) + up := newGrokMedia(t) + remote := httptest.NewServer(New().Handler()) + t.Cleanup(remote.Close) + if err := provider.Save(provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Chat: remote.URL, Key: "remote-key"}); err != nil { + t.Fatal(err) + } + p, _ := provider.Find("office") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + if len(Drawers(*p)) == 0 || len(Videomakers(*p)) == 0 { + t.Fatal("remote image or video models weren't discovered") + } + s := New() + code, _, raw, _ := request(t, s, "POST", "/v1/images/generations", "application/json", `{"model":"office/grok/grok-imagine-image","prompt":"a kite"}`) + if code != 200 || !bytes.Contains(raw, []byte(`"b64_json"`)) { + t.Fatalf("image: %d %s", code, raw) + } + var edit bytes.Buffer + form := multipart.NewWriter(&edit) + form.WriteField("model", "office/grok/grok-imagine-image") + form.WriteField("prompt", "add a kite") + part, err := form.CreateFormFile("image", "input.png") + if err != nil { + t.Fatal(err) + } + part.Write(pngBytes) + form.Close() + code, _, raw, _ = request(t, s, "POST", "/v1/images/edits", form.FormDataContentType(), edit.String()) + if code != 200 || !bytes.Contains(raw, []byte(`"b64_json"`)) { + t.Fatalf("edit: %d %s", code, raw) + } + if b := up.body("/v1/images/edits", 0); !strings.Contains(b, "data:image/png;base64,") || !strings.Contains(b, "add a kite") { + t.Fatalf("edit lost image or prompt: %s", b) + } + code, obj, raw, _ := request(t, s, "POST", "/v1/videos", "application/json", `{"model":"office/grok/grok-imagine-video","prompt":"a kite sways","seconds":"6","size":"1280x720"}`) + id, _ := obj["id"].(string) + if code != 200 || id == "" || obj["model"] != "office/grok/grok-imagine-video" || obj["status"] != "queued" { + t.Fatalf("video: %d %s", code, raw) + } + for i, want := range []string{"queued", "in_progress", "completed"} { + code, obj, raw, _ = request(t, s, "GET", "/v1/videos/"+id, "", "") + if code != 200 || obj["id"] != id || obj["status"] != want || obj["model"] != "office/grok/grok-imagine-video" { + t.Fatalf("poll %d: %d %s", i, code, raw) + } + } + code, _, raw, headers := request(t, s, "GET", "/v1/videos/"+id+"/content", "", "") + if code != 200 || string(raw) != "fake-mp4-bytes" || headers.Get("Content-Type") != "video/mp4" { + t.Fatalf("content: %d %s %v", code, raw, headers) + } + var sent map[string]any + json.Unmarshal([]byte(up.body("/v1/videos/generations", 0)), &sent) + if sent["model"] != "grok-imagine-video" || sent["duration"] != float64(6) || sent["aspect_ratio"] != "16:9" || sent["resolution"] != "720p" { + t.Errorf("video options: %v", sent) + } + // Caller metadata is accepted by the remote for every media path. + arrived := make(chan http.Header, 1) + peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + arrived <- r.Header.Clone() + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"data":[{"b64_json":"aGVsbG8="}]}`) + })) + t.Cleanup(peer.Close) + q := *p + q.Chat = peer.URL + r := httptest.NewRequest("POST", "/", nil) + r.Header.Set("User-Agent", "pi/1.0") + r.Header.Set(SessionHeader, "media-session") + withCaller(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, err := s.send(r.Context(), q, peer.URL+"/images/generations", "application/json", []byte(`{"model":"m","prompt":"kite"}`), true) + if err != nil { + t.Fatal(err) + } + })).ServeHTTP(httptest.NewRecorder(), r) + head := <-arrived + if head.Get(AgentHeader) != "pi" || head.Get(SessionHeader) != "media-session" || !strings.HasPrefix(head.Get("User-Agent"), "magpie/") { + t.Errorf("media caller: %v", head) + } +} + +func TestRemoteMagpieVideoContentCaller(t *testing.T) { + fresh(t) + arrived := make(chan caller, 1) + remote := httptest.NewServer(withCaller(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + arrived <- callerOf(r) + w.Header().Set("Content-Type", "video/mp4") + io.WriteString(w, "fake-mp4-bytes") + }))) + t.Cleanup(remote.Close) + if err := provider.Save(provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Chat: remote.URL, Key: "remote-key"}); err != nil { + t.Fatal(err) + } + p, _ := provider.Find("office") + req := httptest.NewRequest("GET", "/v1/videos/"+videoID(*p, "task", time.Now())+"/content", nil) + req.Header.Set("User-Agent", "pi/1.0") + req.Header.Set(SessionHeader, "video-session") + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 || rec.Body.String() != "fake-mp4-bytes" { + t.Fatalf("video content: %d %s", rec.Code, rec.Body.String()) + } + // Content downloads have no usage record of their own. Check the + // caller accepted by the remote's real receiving middleware instead. + if c := <-arrived; c.agent != "pi" || c.via != hostName() || c.session != "video-session" { + t.Errorf("remote video content lost caller: %+v", c) + } +} diff --git a/internal/gateway/remote_magpie_test.go b/internal/gateway/remote_magpie_test.go index c3c0cb575..9cf47cc0d 100644 --- a/internal/gateway/remote_magpie_test.go +++ b/internal/gateway/remote_magpie_test.go @@ -99,6 +99,8 @@ func TestRemoteMagpieNativeAPI(t *testing.T) { {"/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() diff --git a/internal/gateway/video.go b/internal/gateway/video.go index a14d63bb0..d77f7437d 100644 --- a/internal/gateway/video.go +++ b/internal/gateway/video.go @@ -742,6 +742,7 @@ func (s *Server) remoteVideoContent(ctx context.Context, w http.ResponseWriter, writeError(w, provider.Chat, 502, err.Error()) return } + req.Header.Set("User-Agent", "magpie/"+Version) passOnCaller(ctx, req) if err := p.Sign(ctx, req, provider.Chat, nil); err != nil { writeError(w, provider.Chat, 502, err.Error()) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index b186f75c8..14594ff7c 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -8352,7 +8352,7 @@ function drawEditor(p, presetID) { // Jev's endpoint can be the one its gateway's docs give — Cloudflare's // names the account, …/accounts//ai/run — in place of the preset's - if (decides && !custom) { + if (decides && !custom && (p?.preset || pr?.id) !== "remote-magpie") { if (draft.decide === undefined) draft.decide = p?.decide || pr?.decide || ""; const du = input(draft.decide, pr?.decide || "https://…", "url"); // Bailian's is at the host of the key's workspace (#647): its id is diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 1db4577af..8475b2fba 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -126,9 +126,9 @@ type providerJSON struct { // System One question (provider.AsksDecideModels): a mixed // provider's Jev too, beside its conversation models DecideTest bool `json:"decideTest,omitempty"` - // Deciders are its decision models when it lists them apart from its - // chat models (OpenRouter's): those, and no Jev-named chat model - Deciders []string `json:"deciders,omitempty"` + // Deciders explicitly identifies decision models for OpenRouter and + // remote magpie. An empty remote list suppresses name-based guessing. + Deciders *[]string `json:"deciders,omitempty"` Key struct { Set bool `json:"set"` @@ -586,15 +586,22 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { seen[m.ID] = true out.Models = append(out.Models, named(m, exposed[m.ID])) } - // OpenRouter's decision models, listed apart from its chat models - // (ARNO on Discord), after them + // Keep an explicit empty list for remote magpie: the editor must not + // guess that a Jev Router chat model answers System One. + var deciders []string + if p.IsRemoteMagpie() { + deciders = []string{} + } for _, m := range p.DecisionModels() { - out.Deciders = append(out.Deciders, m.ID) + deciders = append(deciders, m.ID) if !seen[m.ID] { seen[m.ID] = true out.Models = append(out.Models, named(m, exposed[m.ID])) } } + if deciders != nil { + out.Deciders = &deciders + } // picks the vendor list does not know go first, so they are visible for _, m := range p.Exposed() { if !seen[m.ID] { diff --git a/internal/gui/providers_remote_decide_test.go b/internal/gui/providers_remote_decide_test.go new file mode 100644 index 000000000..b976800c4 --- /dev/null +++ b/internal/gui/providers_remote_decide_test.go @@ -0,0 +1,60 @@ +package gui + +import ( + "encoding/json" + "slices" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// The editor receives an authoritative list, even empty, so a Jev Router +// chat model on a remote isn't guessed to be a System One model. +func TestRemoteMagpieDecisionPicker(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if err := provider.Save(provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Chat: "http://127.0.0.1:1", Key: "remote-key"}); err != nil { + t.Fatal(err) + } + p, _ := provider.Find("office") + for _, decisions := range [][]catalog.Model{ + {{ID: "judge/custom", Decides: true}}, + nil, + } { + ms := append([]catalog.Model{{ID: "relay/typesafe/jev-router"}}, decisions...) + if err := catalog.SaveLive(p.ID, p.Chat, ms); err != nil { + t.Fatal(err) + } + out := providerInfo(*p, nil) + want := []string{"relay/typesafe/jev-router"} + for _, m := range decisions { + want = append(want, m.ID) + } + var got []string + for _, m := range out.Models { + got = append(got, m.ID) + } + if !slices.Equal(got, want) { + t.Fatalf("editor models after refresh: %v; want %v", got, want) + } + if out.Deciders == nil || len(*out.Deciders) != len(decisions) { + t.Fatalf("editor decision list: %v", out.Deciders) + } + if len(decisions) > 0 && !slices.Equal(*out.Deciders, []string{"judge/custom"}) { + t.Fatalf("editor decisions: %v", *out.Deciders) + } + b, err := json.Marshal(out) + if err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + json.Unmarshal(b, &fields) + if len(decisions) == 0 && string(fields["deciders"]) != "[]" { + t.Fatalf("empty decisions omitted: %s", b) + } + if out.Decide != "http://127.0.0.1:1/v1" || out.Chat != out.Decide { + t.Fatalf("remote API bases: %+v", out) + } + } +} diff --git a/internal/gui/tests/remote-magpie.test.cjs b/internal/gui/tests/remote-magpie.test.cjs index 39c519436..68d9b57f8 100644 --- a/internal/gui/tests/remote-magpie.test.cjs +++ b/internal/gui/tests/remote-magpie.test.cjs @@ -22,7 +22,10 @@ const presets = [ endpointHint: "The address and API key the other computer's magpie shows in Settings, under Share on local network. Its models and routing groups are listed here; each request goes on in the API the agent spoke.", endpointNeeded: "The other magpie's address is needed" }, ]; -const providers = [{ id: "openrouter", name: "OpenRouter", icon: "openai", preset: "openrouter", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }]; +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" } }, +]; function server(lang, saves) { return async (route) => { @@ -60,11 +63,49 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await t.test(lang, async () => { const w = L[lang]; const saves = []; - const page = await (await browser.newContext({ viewport: { width: 900, height: 700 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width: 900, height: process.env.ARTIFACT_DIR ? 1500 : 700 } })).newPage(); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", server(lang, saves)); await page.goto("http://magpie.test/?view=providers"); + // A remote's explicit list is authoritative, including an empty + // list after refresh: Jev Router still belongs to chat. + const classifications = await page.evaluate(() => { + const remote = { + preset: "remote-magpie", chat: "http://office/v1", decide: "http://office/v1", + deciders: ["judge/custom", "judge/@cf/cloudflare/clef"], + }; + return [ + decidesModel(remote, "judge/custom"), + decidesModel(remote, "judge/@cf/cloudflare/clef"), + decidesModel(remote, "relay/typesafe/jev-router"), + decidesModel({ ...remote, deciders: [] }, "relay/typesafe/jev-router"), + ]; + }); + assert.deepEqual(classifications, [true, true, false, false]); + + // A remote's decision URL is derived from its one address. Both + // a current peer and one without decisions omit the separate field. + const saved = page.locator(".editor"); + for (const decisions of [true, false]) { + if (!decisions) await page.evaluate(() => { + const remote = providers.providers.find((p) => p.id === "office"); + remote.models = remote.models.filter((m) => !remote.deciders.includes(m.id)); + remote.deciders = []; + }); + await page.locator('#providers .row[data-id="office"]').click(); + await saved.locator(".ehead b", { hasText: "Office" }).waitFor(); + assert.equal(await saved.locator("label", { hasText: /Jev endpoint|Jev 终结点|System One endpoint|System One 终结点/ }).count(), 0); + assert.equal(await saved.locator('input[type="url"]').count(), 1, "only the remote's address is editable"); + 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") { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await saved.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `remote-editor-${decisions ? "decisions" : "chat-only"}.png`) }); + } + await page.keyboard.press("Escape"); + await saved.waitFor({ state: "detached" }); + } await page.locator("#addProvider").click(); const sheet = page.locator("#addSheet"); const tile = sheet.locator(".tile", { has: page.locator(".n", { hasText: /^Remote magpie$/ }) }); @@ -82,7 +123,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.match(await endpoint.locator("xpath=following-sibling::div[contains(@class,'hint')]").textContent(), w.hint); await page.waitForFunction(() => document.activeElement?.classList.contains("endpoint")); const key = ed.locator("input[type=password]").first(); - const [ey, ky] = [await endpoint.boundingBox(), await key.boundingBox()].map((b) => b.y); + // Compare both fields in one frame while the editor opens. + const [ey, ky] = await ed.evaluate((editor) => [ + editor.querySelector("input.endpoint"), editor.querySelector('input[type="password"]'), + ].map((input) => input.getBoundingClientRect().top)); assert(ey < ky, "the endpoint above the key"); // no endpoint: said, nothing sent, the page where it was diff --git a/internal/provider/decide.go b/internal/provider/decide.go index 62243fa64..eb691f507 100644 --- a/internal/provider/decide.go +++ b/internal/provider/decide.go @@ -25,6 +25,7 @@ import ( "time" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" ) // JevLatest is the Jev a decision provider is asked with when the user @@ -78,13 +79,22 @@ func (p Provider) DecidesModel(model string) bool { if p.DecideOnly() { return true } - if p.listsDecisions() { + if p.IsRemoteMagpie() || p.listsDecisions() { // OpenRouter's Jev Router (typesafe/jev-router) is a chat model return slices.ContainsFunc(p.decideListed(), func(m catalog.Model) bool { return m.ID == model }) } return jevID(model) || p.DecideVia() == ViaCloudflare && CloudflareClef(model) } +// isDecision uses a listed remote model's marker without reading its whole +// list again. Other providers keep their endpoint and name-based rules. +func (p Provider) isDecision(m catalog.Model) bool { + if p.IsRemoteMagpie() { + return m.Decides + } + return p.DecidesModel(m.ID) +} + // OpenRouter lists its decision models apart from its chat models (ARNO // on Discord): its /models has the chat ones alone, Jev Router among them // (typesafe/jev-router, a chat model that picks one), and @@ -106,11 +116,10 @@ func (p Provider) listsDecisions() bool { return openRouterDecisions(p.Decide) ! // list of its decision models, beside its chat models' list. func decisionsID(id string) string { return id + ".decisions" } -// DecisionModels are the decision models a provider that serves -// conversations too lists apart from them (OpenRouter's), for its editor -// to show beside its chat models; nil for any other provider. +// DecisionModels are the decision models listed separately from a provider's +// conversations: OpenRouter's own list, or a remote magpie's marked models. func (p Provider) DecisionModels() []catalog.Model { - if p.DecideOnly() || !p.listsDecisions() { + if !p.IsRemoteMagpie() && (p.DecideOnly() || !p.listsDecisions()) { return nil } return p.decideModels() @@ -182,6 +191,9 @@ const ( // the gateway's own path (Vercel's /typesafe or /v4/ai, Cloudflare's // /client/v4). func (p Provider) DecideVia() string { + if p.IsRemoteMagpie() { + return ViaSystemOne + } base := strings.TrimRight(p.Decide, "/") switch h := HostOf(base); { case strings.HasSuffix(base, "/v4/ai"): @@ -197,6 +209,12 @@ func (p Provider) DecideVia() string { // Jev is the model a decision provider is asked with when the user picked // none: TypeSafe's latest stable one, or the one Jev a gateway serves. func (p Provider) Jev() string { + if p.IsRemoteMagpie() { + if models := p.decideListed(); len(models) > 0 { + return models[0].ID + } + return "" + } switch p.DecideVia() { case ViaVercel, ViaVercelEval: return "typesafe-ai/jev" @@ -292,6 +310,11 @@ func withDecideFacts(ms []catalog.Model) []catalog.Model { } func (p Provider) decideListed() []catalog.Model { + if p.IsRemoteMagpie() { + live, _, _ := catalog.Live(p.ID) + // Live returns a filtered copy, so it can be compacted in place. + return slices.DeleteFunc(live, func(m catalog.Model) bool { return !m.Decides }) + } if p.listsDecisions() && !p.DecideOnly() { if live, _, ok := catalog.Live(decisionsID(p.ID)); ok && len(live) > 0 { return live @@ -450,17 +473,22 @@ func (p Provider) cloudflareAccount(ctx context.Context) (string, error) { // group's classifier names them. func Deciders() []Entry { var out []Entry + s := settings.Load() for _, p := range All() { if !p.Decides() || !p.On() { continue } ms := p.Exposed() - if !p.DecideOnly() && (len(p.Models) == 0 || p.listsDecisions()) { + if !p.DecideOnly() && (len(p.Models) == 0 || p.listsDecisions() || p.IsRemoteMagpie()) { ms = p.decideModels() // the conversation picker's limit does not hide Jev } for _, m := range ms { - if p.DecidesModel(m.ID) { - out = append(out, Entry{ID: p.ID + "/" + m.ID, Model: m.ID, Name: m.Name, Provider: p}) + if p.isDecision(m) { + if p.IsRemoteMagpie() { + out = append(out, entryFor(p, m, s)) + } else { + out = append(out, Entry{ID: p.ID + "/" + m.ID, Model: m.ID, Name: m.Name, Provider: p}) + } } } } @@ -505,7 +533,10 @@ func RouteDecider(model string) (Provider, string, error) { if !p.On() { return Provider{}, "", decideBadRequest("%s is switched off in magpie", p.Name) } - return p, p.Jev(), nil + if m := p.Jev(); m != "" { + return p, m, nil + } + return Provider{}, "", decideBadRequest("%s lists no decision models", p.Name) } var listed []Provider for _, p := range on { @@ -631,6 +662,12 @@ func deciderByID(id string) (Provider, bool) { // account's Workers AI models, or by finding its account) and Jev is the // model. func (p Provider) fetchDecide(ctx context.Context) ([]catalog.Model, error) { + if p.IsRemoteMagpie() { + if _, err := p.fetch(ctx); err != nil { + return nil, err + } + return p.decideModels(), nil + } ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() switch p.DecideVia() { diff --git a/internal/provider/models.go b/internal/provider/models.go index b0e41c854..cea86f1d8 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -36,7 +36,7 @@ func (p Provider) Available() []catalog.Model { // a gateway's Jev among its chat models, with its window and input ms = slices.Clone(ms) for i, m := range ms { - if p.DecidesModel(m.ID) { + if p.isDecision(m) { ms[i] = withDecideFacts([]catalog.Model{m})[0] } } @@ -1268,7 +1268,7 @@ func buildEntries() []Entry { continue } for _, m := range p.Exposed() { - if !p.DecidesModel(m.ID) { + if !p.isDecision(m) { out = append(out, entryFor(p, m, s)) } } diff --git a/internal/provider/remote_magpie.go b/internal/provider/remote_magpie.go index d21c8b65f..655ff149c 100644 --- a/internal/provider/remote_magpie.go +++ b/internal/provider/remote_magpie.go @@ -40,6 +40,10 @@ import ( // one from before it tells nothing, which leaves the models priced as // they were: by models.dev. +// Its decision models are requested with DecidersHeader, marked +// "kind": "decision", and asked at its System One API, including models +// whose names aren't Jev's. + // DrawersHeader asks a magpie's model list for its image models as well. const DrawersHeader = "X-Magpie-Drawers" @@ -53,6 +57,9 @@ const VideomakersHeader = "X-Magpie-Videomakers" // more than before. const PricesHeader = "X-Magpie-Prices" +// DecidersHeader asks a magpie's model list for its decision models too. +const DecidersHeader = "X-Magpie-Deciders" + // RemoteMagpiePreset is the preset's id. const RemoteMagpiePreset = "remote-magpie" @@ -67,7 +74,7 @@ func (p *Provider) remoteMagpieEndpoints() { return } root := "" - for _, u := range []string{p.Chat, p.Responses, p.Anthropic} { + for _, u := range []string{p.Chat, p.Responses, p.Anthropic, p.Decide} { if u = strings.TrimRight(strings.TrimSpace(u), "/"); u != "" { root = u break @@ -79,17 +86,24 @@ func (p *Provider) remoteMagpieEndpoints() { if !strings.Contains(root, "://") { root = "http://" + root } - for _, suf := range []string{"/v1/messages", "/v1/chat/completions", "/v1/responses", "/v1"} { + for _, suf := range []string{ + "/v1/messages/count_tokens", "/v1/messages", + "/v1/chat/completions", "/v1/responses", "/v1/systemone", + "/v1/embeddings", "/v1/rerank", + "/v1/images/generations", "/v1/images/edits", + "/v1/videos", "/v1", + } { if b, ok := strings.CutSuffix(root, suf); ok { root = b break } } p.Chat, p.Responses, p.Anthropic = root+"/v1", root+"/v1", root + p.Decide = p.Chat } // listHeaders are the headers p's model list is asked with: a remote -// magpie is asked for its image and video models too, and its prices. +// magpie is asked for its image, video and decision models too, and its prices. func (p Provider) listHeaders() map[string]string { if !p.IsRemoteMagpie() { return p.Headers @@ -101,6 +115,7 @@ func (p Provider) listHeaders() map[string]string { h[DrawersHeader] = "1" h[VideomakersHeader] = "1" h[PricesHeader] = "1" + h[DecidersHeader] = "1" return h } diff --git a/internal/provider/remote_magpie_decide_test.go b/internal/provider/remote_magpie_decide_test.go new file mode 100644 index 000000000..a73f4b8ab --- /dev/null +++ b/internal/provider/remote_magpie_decide_test.go @@ -0,0 +1,192 @@ +package provider + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +func TestRemoteMagpieUnlistedDecisions(t *testing.T) { + azureHome(t) + p := normalize(Provider{ID: "office", Preset: RemoteMagpiePreset, Chat: "http://127.0.0.1:1/typesafe"}) + if err := Save(p); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive(p.ID, p.Chat, []catalog.Model{ + {ID: "judge/custom", Decides: true}, + {ID: "judge/jev-preview"}, + }); err != nil { + t.Fatal(err) + } + if got, ok := resolveDecideModel(p, "judge/custom"); !ok || got != "judge/custom" { + t.Fatalf("listed decision: %q %v", got, ok) + } + for _, name := range []string{"judge/missing", "judge/jev-preview", "jev-latest", "jev-preview", "typesafe-ai/jev", "@cf/cloudflare/clef"} { + if got, ok := resolveDecideModel(p, name); ok || got != "" { + t.Errorf("unlisted decision %q resolved as %q", name, got) + } + if _, _, err := RouteDecider(p.ID + "/" + name); err == nil { + t.Errorf("unlisted decision %q routed", name) + } + } +} + +// Entry formatting for other decision providers keeps its earlier behavior; +// only a remote's entries inherit conversation model names and limits. +func TestRemoteMagpieDecidersKeepOtherEntries(t *testing.T) { + azureHome(t) + for _, p := range []Provider{ + {ID: "openrouter", Key: "k", Decide: "https://openrouter.ai/api/v1", Models: []string{OpenRouterJev}}, + {ID: "cloudflare", Key: "k", Decide: "https://api.cloudflare.com/client/v4/accounts/test/ai", Models: []string{CloudflareJev}}, + {ID: "vercel", Key: "k", Decide: "https://ai-gateway.vercel.sh/typesafe", Models: []string{"typesafe-ai/jev"}}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + s := settings.Load() + if s.ModelNames == nil { + s.ModelNames = map[string]string{} + } + s.ModelNames[p.ID+"/"+p.Models[0]] = "My judge" + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + } + entries := Deciders() + if len(entries) != 3 { + t.Fatalf("decision entries: %v", entries) + } + for _, e := range entries { + if e.Name == "My judge" || e.Context != 0 || len(e.Efforts) != 0 { + t.Errorf("non-remote entry gained conversation overrides: %+v", e) + } + } +} + +func TestRemoteMagpieDecisionRefresh(t *testing.T) { + azureHome(t) + var mu sync.Mutex + list := `{"data":[{"id":"relay/typesafe/jev-router"},{"id":"judge/custom-image-decision","kind":"decision","context_length":65536,"modalities":{"input":["text","image"]}}]}` + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/models" || r.Header.Get(DecidersHeader) != "1" || r.Header.Get(DrawersHeader) != "1" || r.Header.Get(VideomakersHeader) != "1" || r.Header.Get("Authorization") != "Bearer remote-key" { + t.Errorf("remote discovery: %s %v", r.URL.Path, r.Header) + } + mu.Lock() + defer mu.Unlock() + io.WriteString(w, list) + })) + t.Cleanup(up.Close) + if err := Save(Provider{ID: "office", Preset: RemoteMagpiePreset, Key: "remote-key", Chat: up.URL, Models: []string{"relay/typesafe/jev-router"}}); err != nil { + t.Fatal(err) + } + p, _ := Find("office") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + if !p.DecidesModel("judge/custom-image-decision") || p.DecidesModel("relay/typesafe/jev-router") || p.DecidesModel("jev-latest") { + t.Fatal("remote decisions must come from the list's explicit kind") + } + if ms := p.DecisionModels(); len(ms) != 1 || !ms[0].Decides || ms[0].Context != 65536 || !ms[0].Images { + t.Fatalf("decision facts lost: %v", ms) + } + if ds := Deciders(); len(ds) != 1 || ds[0].ID != "office/judge/custom-image-decision" || ds[0].Context != 65536 || !ds[0].Images { + t.Fatalf("conversation picks hid decision models: %v", ds) + } + if _, model, err := RouteDecider("office"); err != nil || model != "judge/custom-image-decision" { + t.Fatalf("default remote decision: %s %v", model, err) + } + if len(catalog.LiveDrawers("office")) != 0 { + t.Fatal("a decision with image in its name became an image generator") + } + mu.Lock() + list = `{"data":[{"id":"relay/typesafe/jev-router"}]}` + mu.Unlock() + if _, _, err := p.Refetch(context.Background()); err != nil { + t.Fatal(err) + } + if p.DecidesModel("judge/custom-image-decision") || len(Deciders()) != 0 { + t.Fatal("removed remote decisions survived refresh") + } + for _, id := range []string{"office", "office/judge/custom-image-decision", "office/jev-latest"} { + if _, _, err := RouteDecider(id); err == nil { + t.Errorf("unlisted remote decision accepted: %s", id) + } + } + if e, ok := EntryOf("office/relay/typesafe/jev-router"); !ok || e.Model != "relay/typesafe/jev-router" { + t.Fatal("Jev Router chat model was removed") + } + // Older peers with no decision metadata still serve their chat list. + live, _, _ := catalog.Live("office") + if len(live) != 1 || !strings.Contains(live[0].ID, "jev-router") { + t.Fatalf("old list: %v", live) + } + // All URL fields can be the entry point; the remote itself always + // speaks System One even behind paths resembling a vendor's API. + for _, p := range []Provider{ + {Preset: RemoteMagpiePreset, Responses: up.URL + "/v1"}, + {Preset: RemoteMagpiePreset, Anthropic: up.URL}, + {Preset: RemoteMagpiePreset, Decide: up.URL + "/v1/systemone"}, + {Preset: RemoteMagpiePreset, Chat: up.URL + "/typesafe"}, + } { + p = normalize(p) + u, err := p.DecideURL(context.Background()) + if err != nil || u != p.Chat+"/systemone" || p.DecideVia() != ViaSystemOne || !slices.Contains(p.Speaks(), Chat) { + t.Errorf("remote endpoints: %+v %s %v", p, u, err) + } + } +} + +func TestRemoteMagpieEndpointTests(t *testing.T) { + for _, decisions := range []bool{false, true} { + t.Run(fmt.Sprint(decisions), func(t *testing.T) { + azureHome(t) + var lists atomic.Int32 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/v1/models" { + lists.Add(1) + list := `{"data":[{"id":"lib/m1"}` + if decisions { + list += `,{"id":"judge/custom","kind":"decision"}` + } + io.WriteString(w, list+`]}`) + return + } + io.WriteString(w, `{"choices":[{"message":{"content":"hello"}}]}`) + })) + t.Cleanup(up.Close) + if err := Save(Provider{ID: "office", Preset: RemoteMagpiePreset, Chat: up.URL, Key: "remote-key"}); err != nil { + t.Fatal(err) + } + p, _ := Find("office") + var decide []Result + for _, r := range p.Test(context.Background()) { + if r.Protocol == "decide" { + decide = append(decide, r) + } else if !r.OK || r.Model != "lib/m1" { + t.Errorf("conversation probe: %+v", r) + } + } + if decisions { + if len(decide) != 1 || !decide[0].OK || decide[0].Model != "judge/custom" { + t.Errorf("listed decision probe: %+v", decide) + } + } else if len(decide) != 0 { + t.Errorf("unlisted decision reported as tested: %+v", decide) + } + if n := lists.Load(); n != 1 { + t.Errorf("model list fetched %d times; want once", n) + } + }) + } +} diff --git a/internal/provider/remote_magpie_test.go b/internal/provider/remote_magpie_test.go index 5a91ff7ac..33adf13f7 100644 --- a/internal/provider/remote_magpie_test.go +++ b/internal/provider/remote_magpie_test.go @@ -12,9 +12,21 @@ import ( // Its whole list is offered, being already what its user exposed. func TestRemoteMagpie(t *testing.T) { azureHome(t) - for _, in := range []string{"192.168.1.20:3425", "http://192.168.1.20:3425/", "http://192.168.1.20:3425/v1", "http://192.168.1.20:3425/v1/messages"} { + for _, in := range []string{ + "192.168.1.20:3425", + "http://192.168.1.20:3425/", + "http://192.168.1.20:3425/v1", + "http://192.168.1.20:3425/v1/messages", + "http://192.168.1.20:3425/v1/systemone", + "http://192.168.1.20:3425/v1/embeddings", + "http://192.168.1.20:3425/v1/rerank", + "http://192.168.1.20:3425/v1/images/generations", + "http://192.168.1.20:3425/v1/images/edits", + "http://192.168.1.20:3425/v1/videos", + "http://192.168.1.20:3425/v1/messages/count_tokens", + } { p := normalize(Provider{Preset: RemoteMagpiePreset, Chat: in}) - if p.Chat != "http://192.168.1.20:3425/v1" || p.Responses != p.Chat || p.Anthropic != "http://192.168.1.20:3425" { + if p.Chat != "http://192.168.1.20:3425/v1" || p.Responses != p.Chat || p.Anthropic != "http://192.168.1.20:3425" || p.Decide != p.Chat { t.Errorf("%q: %q %q %q", in, p.Chat, p.Responses, p.Anthropic) } } diff --git a/internal/provider/test.go b/internal/provider/test.go index 0935dfef2..1250a84ae 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -38,7 +38,7 @@ func (p Provider) Test(ctx context.Context) []Result { if p.DecideOnly() { return p.testDecide(ctx) } - p.Fetch(ctx) + _, listErr := p.Fetch(ctx) if p.isClaudeAccount() { return []Result{p.testClaude(ctx, p.testModel(p, Anthropic))} } @@ -53,7 +53,12 @@ func (p Provider) Test(ctx context.Context) []Result { url, body := tiny(q, proto, UpstreamName(p, model)) out = append(out, probe(ctx, q, proto, url, q.Prepare([]byte(body)), model, testWait)) } - if p.Decides() { + if p.IsRemoteMagpie() { + // The model list already checked its key and named its decisions. + if model := p.Jev(); listErr == nil && model != "" { + out = append(out, Result{Protocol: "decide", Model: model, OK: true, Status: http.StatusOK}) + } + } else if p.Decides() { out = append(out, p.testDecide(ctx)...) } return out diff --git a/internal/tui/pages.go b/internal/tui/pages.go index 554ddb3e0..6249137da 100644 --- a/internal/tui/pages.go +++ b/internal/tui/pages.go @@ -471,7 +471,7 @@ func addKeyAsk(p provider.Provider) ask { // (akic404 on Discord) text := "added " + saved.Name ms, err := saved.Fetch(ctx) - if err != nil && saved.Decides() { + if err != nil && saved.DecideOnly() { // a System One API: its list isn't what it is for return flashMsg{text: text, ok: true} } diff --git a/providers_cli.go b/providers_cli.go index 771c5a62c..350ca17ee 100644 --- a/providers_cli.go +++ b/providers_cli.go @@ -648,12 +648,12 @@ func announce(id string) error { defer cancel() if ms, err := saved.Fetch(ctx); err == nil { fmt.Println(green.Render("✓"), len(ms), "models from", fetchedFrom(*saved)) - } else if !saved.Decides() { + } else if !saved.DecideOnly() { // the URLs asked and what they said; the base stays as given fmt.Println(amber.Render("!"), muted.Render(err.Error())) } n := len(saved.Exposed()) - if saved.Decides() { + if saved.DecideOnly() { fmt.Println(" it routes groups: magpie group set effort=auto classifier="+saved.ID+"/"+saved.Jev(), muted.Render("· or a rule's intent=…")) return nil diff --git a/providers_decide_cli_test.go b/providers_decide_cli_test.go index cf46fc819..cb437ff61 100644 --- a/providers_decide_cli_test.go +++ b/providers_decide_cli_test.go @@ -1,6 +1,9 @@ package main import ( + "io" + "net/http" + "net/http/httptest" "strings" "testing" @@ -48,3 +51,33 @@ func TestProviderDecidePairs(t *testing.T) { t.Fatalf("custom: %+v asked as %s", c, c.Jev()) } } + +func TestRemoteMagpieAddReportsModels(t *testing.T) { + for _, tc := range []struct{ name, list, want string }{ + {"unreachable", "", "no models exposed yet"}, + {"chat only", `{"data":[{"id":"lib/m1"}]}`, "1 models in the catalog"}, + } { + t.Run(tc.name, func(t *testing.T) { + groupsHome(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, tc.list) + })) + t.Cleanup(up.Close) + if tc.list == "" { + up.Close() + } + out, err := stdoutOf(t, func() error { + return providerCmd([]string{"provider", "add", "remote-magpie", "remote-key", "url=" + up.URL, "id=office"}) + }) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, tc.want) || strings.Contains(out, "classifier=office/") { + t.Errorf("remote add said %q; want %q and no empty classifier", out, tc.want) + } + if tc.list == "" && !strings.Contains(out, "refused") { + t.Errorf("remote list error hidden: %q", out) + } + }) + } +}