diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 154814429..6bc4adcea 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -100,6 +100,8 @@ no decision model was discovered (`Test` in Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json`, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed. +A signed-in account's model list exists only at its vendor (Cursor's `cursor-agent models`, WorkBuddy's config, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewWaitsForASlowSignIn`, `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it. + ## 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. diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index cedc7f057..f92ad34a5 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -1116,6 +1116,14 @@ func serve() error { s := gateway.New() go stats.Run(version, "serve") go catalog.KeepFresh() // new models' prices, in a gateway left running + // a signed-in account's list exists only at its vendor: asked for here + // as the app and the terminal ask (#1789), or a headless gateway offered + // the agents Cursor's fallback Auto alone; asked again while one is left + go func() { + for provider.FetchNew(20 * time.Second) { + time.Sleep(time.Minute) + } + }() // Codex's background app-server, restarted when it has the list from // before a change and no codex session is on it go agent.KeepCodexDaemonCurrent(context.Background()) diff --git a/internal/provider/cli_identity.go b/internal/provider/cli_identity.go index 96577530a..71b64d35e 100644 --- a/internal/provider/cli_identity.go +++ b/internal/provider/cli_identity.go @@ -176,6 +176,34 @@ func (c *cliIdentity) refresh() chan struct{} { return done } +// cliIdentities are the CLIs asked who is signed in. +func cliIdentities() []*cliIdentity { return []*cliIdentity{cursorStatus, devinStatus} } + +// awaitIdentities waits, at most timeout, for each CLI being asked who is +// signed in for the first time: waited, if one was, and unknown, if one +// still hasn't answered. FetchNew asks for the lists of the accounts known: +// at the start of a magpie with nothing kept from before, `cursor-agent +// about` (which asks Cursor's servers) answered after a look's 3s, and +// Cursor's list wasn't asked for at all (#1789). +func awaitIdentities(timeout time.Duration) (waited, unknown bool) { + deadline := time.After(timeout) + for _, c := range cliIdentities() { + c.Lock() + pending, done := c.at.IsZero() && c.refreshing, c.done + c.Unlock() + if !pending { + continue + } + waited = true + select { + case <-done: + case <-deadline: + return true, true + } + } + return waited, false +} + // forget has the next look ask the CLI and wait for it: after a sign-in or // a sign-out, the last answer is the wrong one. func (c *cliIdentity) forget() { diff --git a/internal/provider/fetch_new_test.go b/internal/provider/fetch_new_test.go index 503fd143a..28ac784be 100644 --- a/internal/provider/fetch_new_test.go +++ b/internal/provider/fetch_new_test.go @@ -4,11 +4,14 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "runtime" + "slices" "sync/atomic" "testing" "time" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/testenv" ) // An account signed in while magpie runs gets its vendor's list the next @@ -61,8 +64,10 @@ func TestFetchNewAccount(t *testing.T) { return out } - // nothing signed in yet: nothing asked - FetchNew(time.Second) + // nothing signed in yet: nothing asked, and nothing missing + if FetchNew(time.Second) { + t.Fatal("missing a list with no account") + } if n := asked.Load(); n != 0 { t.Fatalf("asked %d times with no account", n) } @@ -78,7 +83,9 @@ func TestFetchNewAccount(t *testing.T) { if ids()["hy4-preview"] { t.Fatal("the vendor's model listed before its list was fetched") } - FetchNew(5 * time.Second) + if FetchNew(5 * time.Second) { + t.Fatal("a list fetched said missing") + } got := ids() if !got["hy4-preview"] || !got["gpt-6-astra"] || len(got) != 3 { t.Fatalf("after FetchNew: %v", got) @@ -96,8 +103,14 @@ func TestFetchNewAccount(t *testing.T) { newFetches.m = map[string]time.Time{} newFetches.Unlock() down.Store(true) - FetchNew(5 * time.Second) - FetchNew(5 * time.Second) + // missing both times: when it failed, and while it waits to ask again, + // so the terminal and magpie serve try once more later (#1789) + if !FetchNew(5 * time.Second) { + t.Fatal("a list that failed not said missing") + } + if !FetchNew(5 * time.Second) { + t.Fatal("a list waiting to be asked again not said missing") + } if n := asked.Load(); n != 2 { t.Fatalf("a failing vendor asked %d times, want once more", n-1) } @@ -105,8 +118,61 @@ func TestFetchNewAccount(t *testing.T) { newFetchRetry = 0 defer func() { newFetchRetry = oldRetry }() down.Store(false) - FetchNew(5 * time.Second) + if FetchNew(5 * time.Second) { + t.Fatal("missing after the list came") + } if n := asked.Load(); n != 3 || !ids()["hy4-preview"] { t.Fatalf("not asked again after the retry time: %d %v", n, ids()) } } + +// A CLI asked who is signed in for the first time, answering after a look's +// wait, is waited for: `cursor-agent about` asks Cursor's servers, and at a +// start with nothing kept from before it answered after the look, so the +// terminal and magpie serve offered Cursor's fallback Auto alone (#1789). +func TestFetchNewWaitsForASlowSignIn(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the fake cursor-agent is a shell script") + } + isolate(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + newFetches.Lock() + newFetches.m = map[string]time.Time{} + newFetches.Unlock() + exe := filepath.Join(home, "cursor-agent") + testenv.Program(t, exe, `#!/bin/sh +case "$1" in +about) /bin/sleep 1; echo '{"userEmail":"cursor@example.com","subscriptionTier":"pro"}' ;; +models) printf 'Available models\n\nauto - Auto (default)\ncomposer-2.5 - Composer 2.5\n' ;; +*) exit 1 ;; +esac +`) + wasExe, wasOut, wasFirst := CursorExecutable, cursorSignedOut, firstAsk + CursorExecutable = func() string { return exe } + cursorSignedOut = func() bool { return false } + firstAsk = 10 * time.Millisecond // the look gives up before `about` answers + t.Cleanup(func() { + CursorExecutable, cursorSignedOut, firstAsk = wasExe, wasOut, wasFirst + ForgetAccounts() + }) + ForgetAccounts() + + if FetchNew(time.Minute) { + t.Fatal("Cursor's list said missing") + } + p, err := Find("cursor") + if err != nil { + t.Fatal(err) + } + var ids []string + for _, m := range p.Available() { + ids = append(ids, m.ID) + } + if !slices.Contains(ids, "composer-2.5") { + t.Fatalf("FetchNew didn't wait for cursor-agent about: %v", ids) + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 41d329174..eb819b376 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -387,13 +387,24 @@ func FetchingNew() bool { return newRunning.Load() > 0 } // accounts there then; an account signed in while magpie runs (in magpie or // in the agent's own app) otherwise showed magpie's built-in list, fewer // models than the vendor serves, until Refresh was clicked (#204). One that -// fails is asked again after newFetchRetry, not each time. -func FetchNew(timeout time.Duration) { +// fails is asked again after newFetchRetry, not each time. It reports +// whether an account is left without its list (one that failed, or that +// failed less than newFetchRetry ago), for a caller with no page to ask +// again from (the terminal, magpie serve) to try once more later. +func FetchNew(timeout time.Duration) (missing bool) { newRunning.Add(1) defer newRunning.Add(-1) newFetches.Lock() defer newFetches.Unlock() - for _, p := range All() { + // listing them asks a CLI who is signed in, if never asked: one that + // hasn't answered yet is waited for, and they are listed again + ps := All() + if waited, unknown := awaitIdentities(timeout); unknown { + missing = true + } else if waited { + ps = All() + } + for _, p := range ps { // a list of decision models fetched before magpie kept their // windows and input, or not fetched yet (ARNO on Discord) decide := p.decideListDue() @@ -405,6 +416,7 @@ func FetchNew(timeout time.Duration) { continue } if t, ok := newFetches.m[p.ID]; ok && time.Since(t) < newFetchRetry { + missing = true continue } newFetches.m[p.ID] = time.Now() @@ -417,9 +429,11 @@ func FetchNew(timeout time.Duration) { } if err != nil { log.Println(p.ID + ": " + err.Error()) + missing = true } cancel() } + return missing } // fetchOne asks the first endpoint that answers, with p's key. diff --git a/internal/tui/models_test.go b/internal/tui/models_test.go new file mode 100644 index 000000000..c2a9e1e1c --- /dev/null +++ b/internal/tui/models_test.go @@ -0,0 +1,203 @@ +package tui + +import ( + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/provider" +) + +// fakeCursor signs a Cursor account in through a cursor-agent of the test's +// own, the way the real CLI answers `about` and `models`. While down is +// there, `models` fails, as a CLI with no network does. +func fakeCursor(t *testing.T, h string) (down string) { + t.Helper() + cli := filepath.Join(h, "cursor-agent") + down = filepath.Join(h, "cursor-down") + write(t, cli, `#!/bin/sh +case "$1" in +about) echo '{"userEmail":"cursor@example.com","subscriptionTier":"pro"}' ;; +models) [ -e '`+down+`' ] && { echo 'network error' >&2; exit 1; } + printf 'Available models\n\nauto - Auto (default)\ncomposer-2.5 - Composer 2.5\ngpt-5.2 - GPT-5.2\ngpt-5.5 - GPT-5.5\n' ;; +*) exit 1 ;; +esac +`) + if err := os.Chmod(cli, 0o755); err != nil { + t.Fatal(err) + } + old := provider.CursorExecutable + provider.CursorExecutable = func() string { return cli } + provider.ForgetAccounts() + t.Cleanup(func() { + provider.CursorExecutable = old + provider.ForgetAccounts() + }) + // signed in once `about` has answered: a look waits 3s for it, which + // a loaded machine's shell can take longer than, and an ask past its + // own 10s (a new script's first run, under load) is asked again only a + // minute later, so it is asked afresh here once that 10s is over + asked := time.Now() + for deadline := asked.Add(2 * time.Minute); ; time.Sleep(20 * time.Millisecond) { + if p, err := provider.Find("cursor"); err == nil && p.Account != nil && p.Ready() { + break + } + if time.Now().After(deadline) { + t.Fatal("the fake cursor-agent's account never signed in") + } + if time.Since(asked) > 15*time.Second { + provider.ForgetAccounts() + asked = time.Now() + } + } + // 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 +} + +// Cursor's list exists only at Cursor: 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). +func TestTUIFetchesSubscriptionModels(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the fake cursor-agent is a shell script") + } + for _, view := range []string{"routing", "routing with catalog sync", "routing with catalog sync last", "provider", "classifier", "agent"} { + t.Run(view, func(t *testing.T) { + fakeCursor(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, "auto") + // GPT-5.5 is served by b too, so the list fetched adds a group + // sorting before cursor/auto under this filter: the model on + // the cursor stays, not its row + selected, _ := m.pk.choice() + if selected == "" { + t.Fatalf("Cursor's fallback Auto is not in the picker\n%s", m.View()) + } + m, _ = runModelsCmd(m, init, strings.HasSuffix(view, "last")) + if got, _ := m.pk.choice(); got != selected || m.pk.input.Value() != "auto" || 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("composer-2.5") + m.pk.refilter() + if got, _ := m.pk.choice(); got != want { + t.Fatalf("Cursor's picker left on Auto alone: 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) { + if runtime.GOOS == "windows" { + t.Skip("the fake cursor-agent is a shell script") + } + down := fakeCursor(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("Cursor'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("composer-2.5") + m.pk.refilter() + if got, _ := m.pk.choice(); got != "cursor/composer-2.5" { + t.Fatalf("asked again, still no Composer: %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 Composer 2.5 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 == "cursor" { + m.prow = i + } + } + m.openProviderModels("cursor") + return m, "composer-2.5" + 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() + default: + m.page = pageGroups + m.openMemberPicker(pickMsg{newGroup: "Test"}) + } + return m, "cursor/composer-2.5" +} + +// 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.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 +} diff --git a/internal/tui/pages.go b/internal/tui/pages.go index e2a594441..009e8c3ce 100644 --- a/internal/tui/pages.go +++ b/internal/tui/pages.go @@ -370,6 +370,7 @@ func (m *model) openProviderModels(id string) { crumbs: []string{"providers", p.Name, "models"}, input: newInput("filter models"), items: modelOptions(id), + relist: func() []agent.Option { return modelOptions(id) }, empty: "no models known yet · m on the providers list asks the vendor for them", toggle: func(model string) ([]agent.Option, string, bool) { p, err := provider.Find(id) diff --git a/internal/tui/routing.go b/internal/tui/routing.go index 26641e057..7c670bbf2 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -230,6 +230,7 @@ func (m *model) openMemberPicker(p pickMsg) { crumbs: crumbs, input: newInput("filter models and groups"), items: memberOptions(skip, p.group), + relist: func() []agent.Option { return memberOptions(skip, p.group) }, empty: empty, onPick: func(id string) tea.Cmd { if p.group != "" { @@ -257,21 +258,25 @@ func (m *model) openMemberPicker(p pickMsg) { // openClassifier picks the model that tells which intent a message is: // a model, or another group whose models are tried in turn. func (m *model) openClassifier(g provider.Group) { - var items []agent.Option - for _, e := range provider.Catalog() { - if e.Group == g.ID { - continue // it can't classify for itself + list := func() []agent.Option { + var items []agent.Option + for _, e := range provider.Catalog() { + if e.Group == g.ID { + continue // it can't classify for itself + } + note := e.Name + if e.ID == g.Classifier { + note = "● now · " + note + } + items = append(items, agent.Option{Value: e.ID, Note: note}) } - note := e.Name - if e.ID == g.Classifier { - note = "● now · " + note - } - items = append(items, agent.Option{Value: e.ID, Note: note}) + return items } m.pk = picker{ crumbs: []string{"routing", g.Name, "classifier"}, input: newInput("filter models · best a small fast one without reasoning"), - items: items, + items: list(), + relist: list, empty: "magpie has no models yet · add a provider first", onPick: func(id string) tea.Cmd { return saveGroup(g.ID, func(g *provider.Group) error { g.Classifier = id; return nil }, g.Name+" classifies with "+id) diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 263661e40..0bf1dccc9 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -72,6 +72,9 @@ type picker struct { crumbs []string input textinput.Model items []agent.Option + // relist, on a picker of models, lists them again when an account's + // list or the models.dev catalog arrives while it is open + relist func() []agent.Option match []int cursor int custom bool @@ -229,10 +232,44 @@ func (m *model) goTo(p page) tea.Cmd { } func (m model) Init() tea.Cmd { + // a signed-in account's list exists only at its vendor: asked for at + // start, as the app does, or Cursor offered its fallback Auto alone + // until m on the Providers page asked for it (#1789) if m.syncing { - return syncCmd + return tea.Batch(syncCmd, fetchModelsCmd) + } + return fetchModelsCmd +} + +// modelsMsg says FetchNew is done; missing, that an account is left +// without its list. +type modelsMsg struct{ missing bool } + +func fetchModelsCmd() tea.Msg { + return modelsMsg{missing: provider.FetchNew(20 * time.Second)} +} + +// modelsRetry is how long the terminal waits to ask again for a list it +// couldn't get (the network not up yet at start, a vendor slow to answer), +// while it stays open: the app asks again each time its page is read. +var modelsRetry = time.Minute + +// modelsChanged shows the models as they are now: the page, and a picker +// of models open meanwhile, its filter and the model on its cursor kept. +func (m *model) modelsChanged() { + m.reload() + if m.mode != modePick || m.pk.relist == nil { + return + } + on, _ := m.pk.choice() + m.pk.items = m.pk.relist() + m.pk.refilter() + for i, j := range m.pk.match { + if m.pk.items[j].Value == on { + m.pk.cursor = i + break + } } - return nil } func syncCmd() tea.Msg { @@ -299,8 +336,15 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } return m, saveInstructions(msg.text) + case modelsMsg: + m.modelsChanged() + if msg.missing { + return m, tea.Tick(modelsRetry, func(time.Time) tea.Msg { return fetchModelsCmd() }) + } + return m, nil case syncedMsg: m.syncing = false + m.modelsChanged() if msg.err != nil { m.flash, m.flashOK = "catalog sync failed: "+msg.err.Error(), false } else { @@ -425,6 +469,7 @@ func (m *model) openFieldPicker() { crumbs: []string{a.Name, f.Label}, input: newInput("type to filter, or enter a custom value"), items: items, + relist: func() []agent.Option { return withCurrent(a.Picks(f, a.Values()), f.Get()) }, custom: true, empty: "no models known yet, type one", onPick: func(v string) tea.Cmd {