Files
magpie/internal/gateway/required_tools_test.go
T
yetone 07a445f42b provider: Devin's built-in is retired; its plugin serves it
"devin" joins retiredBuiltins, as Zed (c0605abc2) and Grok (60ecd598c)
did. @magpie-community/opencode-devin-auth serves it, moved or not.

Removed:
- Sign-in: the PKCE localhost listen and callback branch in signin.go,
  devinExchange/devinExchangeURL. The exchange is Codex's alone again.
- Accounts: devinAccount and devinProvider in the account list, and the
  Logins, switch, on and forget cases (devinSide, devinLoginList,
  switchDevinLogin, setDevinLoginOn, forgetDevinLogin, removeDevinHome,
  addDevinLogin, devinAlsoOn). "devin" keeps its place in Logins("") with
  a nil list.
- Usage: devin_usage.go whole (perLogin fetch, usageLogins, loginQuota).
  devinUsageVersion moved to devin_images.go, which still uses it.
- asksOwnBackend's "devin".
- Gateway: attempt()'s serveDevin dispatch and the Devin translator
  (serveDevin, askDevin, buildDevin, decodeDevin, the Gemini schema and
  tool-description rewriting, the call-id helpers). gateway/devin.go is
  now connect_pb.go and keeps only the protobuf and Connect framing that
  cursor.go uses.
- Tests of the built-in alone: gateway devin_test, devin_gemini_schema,
  devin_sampling and devin_tool_ids; provider devin_usage_test,
  devin_cli_signed_out_test, TestDevinSignIn, TestDevinSeveralAccounts,
  TestSignInInstallsMissingCLI, TestDevinSignInUnseen, the Devin case of
  the required-tools test, and TestDevinSplitParallelCallsKeepTheirResults.

Kept, because the plugin, the devin agent or the move uses them:
- The mover, devinLogins, devinIdentity/devinStatus, DevinAuthAt,
  devinCredentialsAt, newDevinHome, devinCommand/devinProxy.
- DevinFamilies, DevinVariant and models.go's p.ID == "devin" shaping
  (the plugin's provider id is "devin" too). internal/agent/devin.go
  reads the families.
- The installer's "devin" case: the plugin's sign-in installs the CLI.
- The PLUGIN-SERVED notices in devin.go, devin_accounts.go and
  devin_images.go, reworded as retired.

Also fixed:
- cliIdentities no longer lists devinStatus. No look at the accounts
  asks it now, so it stayed unsettled, and FetchNewBehind told every page
  that lists were on their way (TestFetchingNewOnceStarted went red).
- 60ecd598c (Grok) left TestFetchingNewForgottenWhileListed red: its
  hook was GrokExecutable in the account listing. It and
  TestFetchNewListsAgainForAnAnswerWhileListing now hook kiroCLIDB,
  which is read after Cursor's account. Retiring Kiro will need another
  hook.

Tests whose meaning changed:
- TestSignInInstallFails and TestSignInCanceledWhileInstalling go
  through StartPluginSignIn("devin"), the plugin's install of the CLI.
- TestDevinCLIGoesThroughItsProxy seeds both accounts in logins.json
  instead of signing one in. The sign-in's proxy is covered by
  TestPluginSignInGoesThroughItsProxy.
- TestLeftAloneRunsNoCLI no longer expects `devin auth status` when the
  subscription is switched on.
- TestFetchingNewOnceStarted's unanswered CLI is Cursor's.
- devinRawID moved to anthropic_call_ids_test.go. A Devin call id is
  checked as safeCallID("dv_", ...).

Run:
- gofmt -l internal: clean.
- go vet -tags nogui ./... on darwin, GOOS=linux and GOOS=windows: clean.
- staticcheck U1000 on provider and gateway: no Devin leftovers.
- go test -tags nogui -count=1 -run '^(every test in provider, cli and
  gateway that names Devin|TestFetchNew.*|TestFetchingNew.*|
  TestLeftAlone.*|.*Identit.*)$' ./internal/provider ./internal/cli
  ./internal/gateway: ok.
- -run 'Migrat|Move|Moved|Retir|SignIn|AsksOwnBackend|SideLogin|Logins|
  Unmoved|Install|Proxy|Account' ./internal/provider: ok.
- -run 'Devin|Required|Split|CallID|Cursor|Connect|Parity|ToolImage|
  Format|BillingLine' ./internal/gateway: ok.
- -run 'Devin|Plugin|Retired|Moved' ./internal/gui ./internal/agent: ok.
- Not run: the whole packages, the full suite, the GUI node suite (the
  machine is loaded).
2026-10-17 23:11:01 +08:00

151 lines
7.2 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Required tool choices must never turn into a plain-text request when the
// allowlist does not match a declared callable function.
func TestRequiredEmptyAllowlistTranslation(t *testing.T) {
for _, tc := range []struct{ name, path, body string }{
{"responses unknown", "/v1/responses", `{"model":"probe/m","input":"hi","tools":[{"type":"function","name":"known"}],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[{"type":"function","name":"unknown"}]}}`},
{"responses only unsupported", "/v1/responses", `{"model":"probe/m","input":"hi","tools":[{"type":"function","name":"known"}],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[{"type":"mcp","name":"external"}]}}`},
{"gemini unknown", "/v1beta/models/probe/m:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"tools":[{"functionDeclarations":[{"name":"known"}]}],"toolConfig":{"functionCallingConfig":{"mode":"ANY","allowedFunctionNames":["unknown"]}}}`},
} {
t.Run(tc.name, func(t *testing.T) {
fresh(t)
sent := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sent++
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"id":"x","choices":[{"delta":{"content":"wrong"},"finish_reason":"stop"}]}`, `data: [DONE]`))
}))
t.Cleanup(upstream.Close)
if err := provider.Save(provider.Provider{ID: "probe", Name: "Probe", Key: "k", Chat: upstream.URL + "/v1", Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)))
if rec.Code != 400 || sent != 0 || !strings.Contains(rec.Body.String(), "callable") {
t.Fatalf("status=%d sent=%d body=%s", rec.Code, sent, rec.Body.String())
}
})
}
}
func TestRequiredAllowlistStillPermitsSearchAndPassthrough(t *testing.T) {
for _, tc := range []struct {
name, path, body string
native bool
}{
{"responses allowed search", "/v1/responses", `{"model":"probe/m","input":"hi","tools":[{"type":"function","name":"known"},{"type":"web_search_preview"}],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[{"type":"web_search_preview"}]}}`, false},
{"gemini allowed search", "/v1beta/models/probe/m:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"tools":[{"googleSearch":{}},{"functionDeclarations":[{"name":"known"}]}],"toolConfig":{"functionCallingConfig":{"mode":"ANY","allowedFunctionNames":["unknown"]}}}`, false},
{"responses native unknown", "/v1/responses", `{"model":"probe/m","input":"hi","tools":[{"type":"function","name":"known"}],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[{"type":"function","name":"unknown"}]}}`, true},
} {
t.Run(tc.name, func(t *testing.T) {
fresh(t)
sent := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sent++
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"x","output":[],"candidates":[]}`)
}))
t.Cleanup(upstream.Close)
p := provider.Provider{ID: "probe", Name: "Probe", Key: "k", Models: []string{"m"}}
// In a translated request, a nonempty allowed web-search offer remains
// callable even if no function declaration survived filtering.
if strings.HasPrefix(tc.path, "/v1/responses") {
if tc.native {
p.Responses = upstream.URL + "/v1"
} else {
p.Anthropic = upstream.URL
}
} else {
p.Anthropic = upstream.URL
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)))
// A web-search request may ask the fake provider more than once;
// its own fake reply is not a valid streamed search response. The
// important contract is that the request wasn't rejected as an empty
// callable set before any provider could be contacted.
if sent == 0 || rec.Code == 400 {
t.Fatalf("code=%d sent=%d body=%s", rec.Code, sent, rec.Body.String())
}
})
}
}
// The global "required and no tools" rule is too broad: non-function tools
// remain meaningful to the original protocol even when our IR omits them.
func TestUnfilteredRequiredChoicesStillForward(t *testing.T) {
for _, tc := range []struct{ name, path, body string }{
{"Anthropic server tool", "/v1/messages", `{"model":"probe/m","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"web_fetch_20250910","name":"web_fetch"}],"tool_choice":{"type":"any"}}`},
{"Chat custom tool", "/v1/chat/completions", `{"model":"probe/m","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"custom","name":"run"}],"tool_choice":"required"}`},
{"Responses custom tool", "/v1/responses", `{"model":"probe/m","input":"hi","tools":[{"type":"custom","name":"apply_patch"}],"tool_choice":"required"}`},
{"Responses MCP tool", "/v1/responses", `{"model":"probe/m","input":"hi","tools":[{"type":"mcp","server_label":"search"}],"tool_choice":"required"}`},
} {
t.Run(tc.name, func(t *testing.T) {
fresh(t)
sent := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sent++
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"id":"x","choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]}`, `data: [DONE]`))
}))
t.Cleanup(upstream.Close)
var p provider.Provider
p.ID, p.Name, p.Key, p.Models = "probe", "Probe", "k", []string{"m"}
switch tc.path {
case "/v1/messages":
p.Chat = upstream.URL + "/v1"
default:
p.Anthropic = upstream.URL
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)))
if rec.Code == 400 || sent == 0 {
t.Fatalf("status=%d sent=%d body=%s", rec.Code, sent, rec.Body.String())
}
})
}
}
func TestEmptyGeminiAllowlistRejectedBySubscriptionPaths(t *testing.T) {
const body = `{"model":"m","contents":[{"role":"user","parts":[{"text":"hi"}]}],"tools":[{"functionDeclarations":[{"name":"known"}]}],"toolConfig":{"functionCallingConfig":{"mode":"ANY","allowedFunctionNames":["unknown"]}}}`
for _, tc := range []struct {
name string
call func(*Server, http.ResponseWriter, *http.Request, *Usage) (int, string)
}{
{"Claude subscription", func(s *Server, w http.ResponseWriter, r *http.Request, u *Usage) (int, string) {
return s.serveClaudeSubscription(w, r, provider.Gemini, provider.Provider{ID: "claude"}, "m", []byte(body), u)
}},
} {
t.Run(tc.name, func(t *testing.T) {
fresh(t)
rec := httptest.NewRecorder()
s := New()
u := Usage{}
code, _ := tc.call(s, rec, httptest.NewRequest("POST", "/", strings.NewReader(body)), &u)
if code != 400 || rec.Code != 400 || !strings.Contains(rec.Body.String(), "callable") {
t.Fatalf("code=%d recorder=%d body=%s", code, rec.Code, rec.Body.String())
}
})
}
}