Files
magpie/internal/tui/models_test.go
T
yetone e405315d79 provider: Cursor's built-in is retired; its plugin serves it
"cursor" joins retiredBuiltins (migrate.go), so PluginServes("cursor")
holds moved or not, and the built-in's code goes, as Zed's did in
c0605abc2 and Kiro's in the commit before this.

Removed:
- gateway/cursor.go (the Connect/protobuf translator) and its tests
  (cursor_test, cursor_conversation_test, cursor_maxmode_test,
  cursor_precision_test, cursor_stepusage_test), and gateway.go's
  Account.Agent == "cursor" dispatch to serveCursor;
- provider/cursor_usage.go (the usage card, cursorToken, cursorKeychain)
  and provider/cursor_picker.go, with their tests;
- from cursor.go: the built-in account (cursorAccount), its model list
  through `cursor-agent models` (cursorModels, parseCursorModels,
  cursorModelL), its sign-in (startCursorSignIn, cursorLinkWhole,
  cursorLoginUUID), the API client version (CursorClientVersion,
  cursorVersionFallback, cursorVersionRe) and the token refresh
  (CursorToken, cursorRefresh, tokenExpiry);
- StartSignIn's "cursor" case (signin.go), the usage fetch
  (subscription_usage.go), the login-list case and quota (login_usage.go)
  and the account (account.go);
- "cursor" from Native (provider.go) and asksOwnBackend (modelprefs.go).

Kept, because the mover, the plugin paths or other code need them:
- cursor.go's PLUGIN-SERVED notice (TestMovedBuiltinsSayTheirPlugin);
  cursorIdentity, cursorStatus, parseCursorAbout, readCursorToken,
  cursorTokenOf, cursorKeychainToken and cursorAuthFile: migrate_side.go
  and plugin_accounts.go ask whose account the agent is through them;
- cursorLoginURL (grok.go and claude_signin.go use it), cursorContext and
  withCursorContexts (the plugin's model contexts), CursorExecutable and
  isCursorAgent (the Cursor agent itself);
- cursor_models.go whole: CursorBase (agent/legacy.go), CursorVariants
  (groupfast.go, the plugin's fast pick), cursorPicks and the collapse
  (provider.go, models.go);
- accountIDs, builtinOrder, models.go's "cursor" live branch and
  servedByCursor, as Zed's and Kiro's commits left theirs. The live
  collapse and cursorPicks now only ever meet a built-in list, which a
  retired Cursor never has; they are left for a cleanup of their own.
- gateway/cursor_local_models_test.go (the Cursor agent, not the
  built-in) and the gateway's plugin_*_test.go parity tests.

Tests changed in meaning:
- cursor_signin_test.go became cli_signin_test.go: its two generic
  runCLISignIn tests stay (grok's), TestCursorSignInJoinsAWrappedLink
  goes with cursorLinkWhole.
- cursor_test.go keeps parseCursorModels as a test helper (the old
  parser, for the collapse tests' fixtures); TestParseCursorModels,
  TestCursorClientVersion, TestTokenExpiry and TestCursorLegacyPicks go,
  and cursor_names_test.go's TestCursorAvailableNames: they tested the
  built-in account's list and picks. Cursor's plugin lists its own
  picker models with their efforts (index.mjs), so magpie's collapse
  never runs for it; moving the two tests onto the plugin showed that.
- TestFetchNewWaitsForASlowSignIn (#1789) and
  TestFetchNewListsAgainForAnAnswerWhileListing (#1147) are gone: both
  were about a CLI account whose models `cursor-agent models` lists,
  and no built-in left lists its models through its CLI.
- internal/gui/providers_fetching_unix_test.go
  (TestProvidersAnswerWhileListsComeIn, #541) is gone: its slow vendor
  was the built-in's `cursor-agent models`. The guarantee (the
  Providers page answers while an account's list comes in) has no test
  now; re-homing it onto an HTTP-listed account (Antigravity, Copilot)
  needs exported test hooks and is left as a follow-up.
- TestNative drops its Cursor case; TestLeftAloneRunsNoCLI fakes and
  expects claude and devin only; isolate() and
  TestAccountDiscoveryOffReadsNoSignIn no longer set cursorKeychain
  (cursorTokenOf reads the Keychain on macOS only, as before).
- Dropped as built-in only: the Cursor case of the required-tools test,
  TestCodexToolImageCursor, TestCursorSplitParallelCallsKeepTheirResults.

Run at this tree (load ~300, so narrow runs only):
- gofmt -l internal: clean
- go vet -tags nogui ./... ; GOOS=linux and GOOS=windows the same: ok
- staticcheck -tags nogui -checks U1000 ./internal/provider/: clean;
  with -tests=false over provider and gateway: nothing Cursor or Kiro
- go test -tags nogui -count=1 -run 'Cursor|Kiro|Migrat|Mov|Retired|
  SignIn|AsksOwnBackend|Plugin|HandOver|NoWayBack|Adopt|Hide|
  RequiredTools|ToolImage|Split|Discovery|Account|Isolat' over
  provider, gateway, cli, gui: gateway ok 446s, cli ok 67s, gui ok 51s;
  provider failed TestCursorAvailableNames, TestCursorLegacyPicks,
  TestFetchNewWaitsForASlowSignIn (above) and
  TestSetUpstreamNameRefusesAnAccountBackend (Kiro's, fixed in that
  commit)
- every other test naming "cursor" or cursor-agent, by name, over the
  same four packages: gateway and cli ok; TestNative,
  TestLeftAloneRunsNoCLI, TestFetchNewListsAgainForAnAnswerWhileListing
  and TestProvidersAnswerWhileListsComeIn failed (above)
- after the changes: gofmt clean, vet ok on all three; -run 'Cursor|
  Kiro|Migrat|Mov|Retired|SignIn|AsksOwnBackend|Plugin|HandOver|
  NoWayBack|Adopt|Hide|Discovery|Account|Native|LeftAlone|SetUpstream|
  FetchNew|Hold|DailyCredits|NotSignedIn|ModelTest|Providers': provider
  ok 141s, gui ok 21s, cli ok 22s (gateway untouched since its ok run)
Not run: the whole packages, the full suite, the GUI node suite.
2026-10-17 23:11:00 +08:00

203 lines
6.8 KiB
Go

package tui
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/provider"
)
// fakeCodex signs a ChatGPT account in to Codex, its models listed by a
// server of the test's own the way ChatGPT's backend answers. While down is
// there, the list fails, as with no network.
func fakeCodex(t *testing.T, h string) (down string) {
t.Helper()
down = filepath.Join(h, "codex-down")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := os.Stat(down); err == nil || r.URL.Path != "/backend-api/codex/models" {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
var ms []map[string]any
for i, id := range []string{"gpt-5.5", "gpt-6-luna"} {
ms = append(ms, map[string]any{"slug": id, "display_name": id, "visibility": "list", "priority": i + 1})
}
b, _ := json.Marshal(map[string]any{"models": ms})
w.Write(b)
}))
old := provider.CodexBase
provider.CodexBase = srv.URL + "/backend-api/codex"
jwt := func(claims map[string]any) string {
b, _ := json.Marshal(claims)
return "e30." + base64.RawURLEncoding.EncodeToString(b) + ".sig"
}
b, _ := json.Marshal(map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
"id_token": jwt(map[string]any{"email": "me@example.com",
"https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "pro", "chatgpt_account_id": "acct-1"}}),
"access_token": jwt(map[string]any{"exp": float64(time.Now().Add(24 * time.Hour).Unix())}),
"refresh_token": "r", "account_id": "acct-1",
}})
write(t, filepath.Join(h, ".codex", "auth.json"), string(b))
provider.ForgetAccounts()
t.Cleanup(func() {
provider.CodexBase = old
srv.Close()
provider.ForgetAccounts()
})
if p, err := provider.Find("codex"); err != nil || p.Account == nil || !p.Ready() {
t.Fatalf("the ChatGPT account isn't signed in: %v", err)
}
// a cold models.dev sync answered here: no test request leaves this
// process
client := http.DefaultClient
http.DefaultClient = &http.Client{Transport: modelsTransport{}}
t.Cleanup(func() { http.DefaultClient = client })
return down
}
// A subscription's list exists only at its vendor: the terminal asks for it
// at start and fills a model picker opened before it came, with no m on the
// Providers page (#1789, reyoung: Routing offered cursor/auto alone, from
// Cursor's built-in, since retired; Codex's ChatGPT account stands in).
func TestTUIFetchesSubscriptionModels(t *testing.T) {
for _, view := range []string{"routing", "routing with catalog sync", "routing with catalog sync last", "provider", "classifier", "agent"} {
t.Run(view, func(t *testing.T) {
fakeCodex(t, home(t))
m := model{w: 120, h: 40, syncing: strings.Contains(view, "sync")}
init := m.Init()
m, want := openModelPicker(t, m, view)
m = typeIn(m, "gpt-5.5")
// the list fetched adds codex/gpt-5.5 under this filter: the
// model on the cursor stays, not its row
// (Codex's own picker has none before its list: nothing to hold)
selected, _ := m.pk.choice()
if selected == "" && view != "provider" {
t.Fatalf("no GPT-5.5 in the picker\n%s", m.View())
}
m, _ = runModelsCmd(m, init, strings.HasSuffix(view, "last"))
if got, _ := m.pk.choice(); selected != "" && got != selected || m.pk.input.Value() != "gpt-5.5" || m.mode != modePick {
t.Fatalf("the list arriving changed the open picker: choice %q, filter %q, mode %v", got, m.pk.input.Value(), m.mode)
}
m.pk.input.SetValue("gpt-6-luna")
m.pk.refilter()
if got, _ := m.pk.choice(); got != want {
t.Fatalf("the picker hasn't Codex's listed model: got %q, want %q\n%s", got, want, m.View())
}
})
}
}
// A list that couldn't be had at start (no network yet) is asked for again
// while the terminal stays open, not only after a restart.
func TestTUIAsksAgainForAMissingList(t *testing.T) {
down := fakeCodex(t, home(t))
write(t, down, "")
old := modelsRetry
modelsRetry = 0
t.Cleanup(func() { modelsRetry = old })
m, _ := openModelPicker(t, model{w: 120, h: 40}, "routing")
m, retry := runModelsCmd(m, m.Init(), false)
if retry == nil {
t.Fatal("Codex's list failed and nothing asks for it again")
}
if err := os.Remove(down); err != nil {
t.Fatal(err)
}
provider.ForgetAccounts() // the minute FetchNew waits after a failure
m, again := runModelsCmd(m, retry, false)
m.pk.input.SetValue("gpt-6-luna")
m.pk.refilter()
if got, _ := m.pk.choice(); got != "codex/gpt-6-luna" {
t.Fatalf("asked again, still no gpt-6-luna: %q\n%s", got, m.View())
}
if again != nil {
t.Fatal("asks again with every list there")
}
}
// openModelPicker opens one of the terminal's four pickers of models, and
// says what Codex's gpt-6-luna is called in it.
func openModelPicker(t *testing.T, m model, view string) (model, string) {
t.Helper()
switch view {
case "provider":
m.page = pageProviders
m.reloadProviders()
for i, p := range m.provs {
if p.ID == "codex" {
m.prow = i
}
}
m.openProviderModels("codex")
return m, "gpt-6-luna"
case "classifier":
m.page = pageGroups
m.openClassifier(provider.Group{ID: "test", Name: "Test"})
case "agent":
a, err := agent.Find("codex")
if err != nil {
t.Fatal(err)
}
m.agents = []*agent.Agent{a}
m.reload()
m.openFieldPicker()
return m, "gpt-6-luna" // Codex's own account: its models bare
default:
m.page = pageGroups
m.openMemberPicker(pickMsg{newGroup: "Test"})
}
return m, "codex/gpt-6-luna"
}
// runModelsCmd runs what Init or a retry returned and hands its messages to
// the model, as the program would, held until the picker is open to stand
// for a vendor answering late; reverse delivers a batch's last first. It
// returns the command the models' message left, the retry, if any.
func runModelsCmd(m model, cmd tea.Cmd, reverse bool) (model, tea.Cmd) {
if cmd == nil {
return m, nil
}
msg := cmd()
if batch, ok := msg.(tea.BatchMsg); ok {
var left tea.Cmd
for i := range batch {
j := i
if reverse {
j = len(batch) - 1 - i
}
var c tea.Cmd
if m, c = runModelsCmd(m, batch[j], reverse); c != nil {
left = c
}
}
return m, left
}
next, left := m.Update(msg)
return next.(model), left
}
type modelsTransport struct{}
func (modelsTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.Hostname() == "127.0.0.1" {
return http.DefaultTransport.RoundTrip(r) // the test's own vendor
}
if r.URL.String() != "https://models.dev/api.json" {
return nil, fmt.Errorf("unexpected request to %s", r.URL.Host)
}
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"openai":{"id":"openai","models":{}}}`)), Request: r}, nil
}