diff --git a/internal/provider/cli_identity.go b/internal/provider/cli_identity.go index 71b64d35e..6a4d275aa 100644 --- a/internal/provider/cli_identity.go +++ b/internal/provider/cli_identity.go @@ -188,9 +188,7 @@ func cliIdentities() []*cliIdentity { return []*cliIdentity{cursorStatus, devinS 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() + pending, done := c.asking() if !pending { continue } @@ -204,6 +202,45 @@ func awaitIdentities(timeout time.Duration) (waited, unknown bool) { return waited, false } +// asking says whether the CLI is being asked who is signed in for the +// first time, and the channel closed when it has answered. +func (c *cliIdentity) asking() (pending bool, done chan struct{}) { + c.Lock() + defer c.Unlock() + return c.at.IsZero() && c.refreshing, c.done +} + +// identitiesUnsettled says whether a CLI never answered who is signed in +// is being asked, or would be asked and waited for by the next look: +// listing the accounts then may wait on it, as FetchNew does, which a page +// doesn't (#541). Not while discovery is off, as no look asks then. +func identitiesUnsettled() bool { + if settings.AccountDiscoveryOff() { + return false + } + for _, c := range cliIdentities() { + c.Lock() + unsettled := c.at.IsZero() && (c.refreshing || !c.waited) + c.Unlock() + if unsettled { + return true + } + } + return false +} + +// identitiesAnswered is how many CLIs have answered who is signed in. +func identitiesAnswered() (n int) { + for _, c := range cliIdentities() { + c.Lock() + if !c.at.IsZero() { + n++ + } + c.Unlock() + } + return n +} + // 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 28ac784be..0c01a0c72 100644 --- a/internal/provider/fetch_new_test.go +++ b/internal/provider/fetch_new_test.go @@ -176,3 +176,71 @@ esac t.Fatalf("FetchNew didn't wait for cursor-agent about: %v", ids) } } + +// A CLI that answers while the accounts are listed, after its look gave up +// waiting, has its account's list fetched in the same pass: with nothing +// left to wait on, awaitIdentities didn't wait, and the account it said is +// signed in was missing from the list read before (yetone on #1147). +func TestFetchNewListsAgainForAnAnswerWhileListing(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 +models) printf 'Available models\n\nauto - Auto (default)\ncomposer-2.5 - Composer 2.5\n' ;; +*) exit 1 ;; +esac +`) + wasExe, wasOut, wasFirst := CursorExecutable, cursorSignedOut, firstAsk + wasCursor, wasDevin := cursorStatus, devinStatus + CursorExecutable = func() string { return exe } + cursorSignedOut = func() bool { return false } + firstAsk = 5 * time.Second // Devin's look waits for its answer + t.Cleanup(func() { + cursorStatus, devinStatus = wasCursor, wasDevin + CursorExecutable, cursorSignedOut, firstAsk = wasExe, wasOut, wasFirst + ForgetAccounts() + }) + ForgetAccounts() + + // Cursor's look gave up waiting already, so the list leaves it out; + // it answers while Devin's look, read after it, waits + cursorAnswer := make(chan struct{}) + cursor := &cliIdentity{name: "cursor-test", exe: func() string { return exe }, read: true, waited: true, + ask: func() (string, string, bool, error) { <-cursorAnswer; return "cursor@example.com", "pro", true, nil }} + devin := &cliIdentity{name: "devin-test", exe: func() string { return "" }, read: true, + ask: func() (string, string, bool, error) { + cursor.Lock() + done := cursor.done + cursor.Unlock() + close(cursorAnswer) + <-done + return "", "", false, nil + }} + cursorStatus, devinStatus = cursor, devin + + 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("Cursor's list not fetched in the pass its CLI answered in: %v", ids) + } +} diff --git a/internal/provider/fetching_new_test.go b/internal/provider/fetching_new_test.go new file mode 100644 index 000000000..32797d3ed --- /dev/null +++ b/internal/provider/fetching_new_test.go @@ -0,0 +1,259 @@ +package provider + +import ( + "net/http" + "net/http/httptest" + "path/filepath" + "runtime" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" +) + +// FetchingNew says a fetch is on its way as soon as FetchNewBehind or +// FetchNewSoon has started one, not once its goroutine reaches FetchNew: the +// Providers page reads it straight after FetchNewBehind and stops asking on +// false, so it kept the list it had while the fetch was about to run, and a +// test's cleanup that waited on it let its fetch run into the next test +// (TestProvidersAnswerWhileListsComeIn failed on CI). And a page's poll with +// no account due starts nothing it then counts: counted, each poll found +// the last one's still under way and the page asked for ever. A CLI still +// asked who is signed in is waited for behind the page, counted meanwhile. +// One P keeps a started goroutine from running before FetchingNew is read. +func TestFetchingNewOnceStarted(t *testing.T) { + 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")) + reset := func() { + newFetches.Lock() + newFetches.m = map[string]time.Time{} + newFetches.Unlock() + newSoonAt.Store(0) + wbTokens.Lock() + wbTokens.m = map[string]wbCreds{} + wbTokens.Unlock() + forgetAccountCaches() + } + reset() + + // the vendor answers once the test lets it + release := make(chan struct{}, 8) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v3/config" { + w.WriteHeader(404) + return + } + select { + case <-release: + case <-time.After(5 * time.Second): + } + w.Write([]byte(`{"code":0,"data":{"agents":[{"name":"cli","models":["hy4-preview"]}], + "models":[{"id":"hy4-preview","name":"Hy4 preview"}]}}`)) + })) + old := wbEndpoint + wbEndpoint = srv.URL + t.Cleanup(func() { + close(release) + waitFetchingNew(t) + srv.Close() + wbEndpoint = old + reset() + }) + future := time.Now().Add(24 * time.Hour).UnixMilli() + writeFile(t, wbAuthFile(home), map[string]any{ + "account": map[string]any{"uid": "u1", "nickname": "旅行者"}, + "auth": map[string]any{"accessToken": "a", "refreshToken": "r", + "expiresAt": future, "refreshExpiresAt": future, "domain": "www.codebuddy.cn"}, + }) + forgetAccountCaches() + All() + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) + + // the Providers page: the account's list is due + FetchNewBehind(5 * time.Second) + if !FetchingNew() { + t.Fatal("FetchNewBehind started a fetch, and FetchingNew says none is on its way") + } + release <- struct{}{} + waitFetchingNew(t) + + // the page asks again with the list in: nothing is due, nothing runs + FetchNewBehind(5 * time.Second) + if FetchingNew() { + t.Fatal("a poll with nothing due keeps FetchingNew up") + } + waitFetchingNew(t) + + // the panel, with the list due again + if err := catalog.SaveLive("workbuddy", "", nil); err != nil { + t.Fatal(err) + } + newFetches.Lock() + newFetches.m = map[string]time.Time{} + newFetches.Unlock() + newSoonAt.Store(0) + FetchNewSoon(5 * time.Second) + if !FetchingNew() { + t.Fatal("FetchNewSoon started a fetch, and FetchingNew says none is on its way") + } + release <- struct{}{} + waitFetchingNew(t) + + // a FetchNew under way (start-up's) holds the accounts: the page + // doesn't wait on it, and is told lists are on their way + newFetches.Lock() + start := time.Now() + FetchNewBehind(5 * time.Second) + took := time.Since(start) + busy := FetchingNew() + newFetches.Unlock() + if took > time.Second || !busy { + t.Fatalf("behind a FetchNew under way: took %v, fetching %v", took, busy) + } + waitFetchingNew(t) + + // a second page asks while the first's fetch still picks the accounts + // due (held on reading them): it starts nothing, and is told lists are + // on their way (tsuixl on #1147) + if err := catalog.SaveLive("workbuddy", "", nil); err != nil { + t.Fatal(err) + } + newFetches.Lock() + newFetches.m = map[string]time.Time{} + newFetches.Unlock() + held.Lock() + first := make(chan struct{}) + go func() { + defer close(first) + FetchNewBehind(5 * time.Second) + }() + for deadline := time.Now().Add(5 * time.Second); !fetchingNew.Load(); { + if time.Now().After(deadline) { + held.Unlock() + t.Fatal("the first FetchNewBehind didn't start") + } + runtime.Gosched() + } + FetchNewBehind(5 * time.Second) + busy = FetchingNew() + held.Unlock() + <-first + if !busy { + t.Fatal("a FetchNewBehind behind one still picking the accounts due is told none is on its way") + } + release <- struct{}{} + waitFetchingNew(t) + + // the panel's FetchNewSoon lists nothing before it returns, so + // /api/state?last=1 answers at once (#1519) while the accounts' read + // is held, and is counted still + newSoonAt.Store(0) + held.Lock() + soon := make(chan bool) + go func() { + FetchNewSoon(5 * time.Second) + soon <- FetchingNew() + }() + select { + case busy = <-soon: + held.Unlock() + case <-time.After(time.Second): + held.Unlock() + <-soon + t.Fatal("FetchNewSoon waited on the accounts' read") + } + if !busy { + t.Fatal("FetchNewSoon started a fetch, and FetchingNew says none is on its way") + } + waitFetchingNew(t) + + // a CLI never asked who is signed in, as after a sign-in forgot it, or + // one still asked: which accounts are due can't be known without + // waiting on it, which the page doesn't (#541); the fetch lists them + // and waits behind the page, which is told lists are on their way until + // it has (yetone on #1147, #1789) + wasDevin, wasFirst := devinStatus, firstAsk + defer func() { devinStatus, firstAsk = wasDevin, wasFirst }() + firstAsk = 5 * time.Second // long, to tell a look's wait from none + for _, asked := range []bool{false, true} { + answer := make(chan struct{}) + devinStatus = &cliIdentity{name: "devin-test", exe: func() string { return "" }, read: true, + ask: func() (string, string, bool, error) { <-answer; return "", "", false, nil }} + if asked { + devinStatus.Lock() + devinStatus.waited = true // its look gave up already + devinStatus.refresh() + devinStatus.Unlock() + } + start = time.Now() + FetchNewBehind(5 * time.Second) + took = time.Since(start) + busy = FetchingNew() + if took > time.Second || !busy { + close(answer) + waitFetchingNew(t) + t.Fatalf("with a CLI asked %v who is signed in: took %v, fetching %v", asked, took, busy) + } + close(answer) + waitFetchingNew(t) + } +} + +// A CLI forgotten while the Providers page's FetchNewBehind lists the +// accounts (a sign-in finishing then) left its account out of that list: +// the fetch is asked behind the page, which is told lists are on their +// way, not that none is due. +func TestFetchingNewForgottenWhileListed(t *testing.T) { + 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() + newSoonAt.Store(0) + ForgetAccounts() + wasCursor, wasDevin, wasGrok := cursorStatus, devinStatus, GrokExecutable + t.Cleanup(func() { + waitFetchingNew(t) + cursorStatus, devinStatus, GrokExecutable = wasCursor, wasDevin, wasGrok + ForgetAccounts() + }) + nobody := func() (string, string, bool, error) { return "", "", false, nil } + now := time.Now() + cursor := &cliIdentity{name: "cursor-test", exe: func() string { return "" }, read: true, at: now, ask: nobody} + cursorStatus = cursor + devinStatus = &cliIdentity{name: "devin-test", exe: func() string { return "" }, read: true, at: now, ask: nobody} + // Grok's account is read after Cursor's: the sign-in lands there + var once sync.Once + GrokExecutable = func() string { + once.Do(cursor.forget) + return "" + } + + FetchNewBehind(5 * time.Second) + busy := FetchingNew() + waitFetchingNew(t) + if !busy { + t.Fatal("a CLI forgotten while the accounts were listed, and FetchingNew says none is on its way") + } +} + +// waitFetchingNew waits for the fetches under way to end, the ones started +// in the background included. +func waitFetchingNew(t *testing.T) { + t.Helper() + for deadline := time.Now().Add(10 * time.Second); FetchingNew() || fetchingNew.Load(); { + if time.Now().After(deadline) { + t.Fatal("a fetch still runs after 10s") + } + time.Sleep(5 * time.Millisecond) + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index b8bc12d4b..3a89f554c 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -360,8 +360,9 @@ var newFetches = struct { // restarted by hand). var newFetchRetry = time.Minute -// fetchingNew is set while a FetchNewSoon runs; newSoonAt is when the last -// one started. +// fetchingNew is set while a FetchNew started in the background +// (FetchNewSoon, FetchNewBehind) picks the accounts due or runs; newSoonAt +// is when the last one started. var ( fetchingNew atomic.Bool newSoonAt atomic.Int64 @@ -380,6 +381,9 @@ func FetchNewSoon(timeout time.Duration) { return } newSoonAt.Store(now) + // the panel reads nothing first, and /api/state?last=1 answers at once + // (#1519): even the accounts are listed behind it, told by fetchingNew + // until FetchNew counts itself go func() { defer fetchingNew.Store(false) FetchNew(timeout) @@ -395,18 +399,70 @@ func FetchNewBehind(timeout time.Duration) { return } newSoonAt.Store(time.Now().UnixNano()) - go func() { - defer fetchingNew.Store(false) - FetchNew(timeout) - }() + fetchNewGo(timeout) } -// newRunning counts the FetchNew calls under way. +// fetchNewGo is FetchNew in the background, counted in newRunning before +// it returns when there is work, so a page reading FetchingNew straight +// after is told; with none nothing is started or counted. Which accounts +// are due is known at once unless a CLI is still asked who is signed in: +// then the fetch is counted and waits for it in its goroutine, as the page +// doesn't wait on a CLI (#541), and isn't told nothing is coming before +// that account's list does (#1789). The accounts are listed here only once +// no CLI is left to wait on. +func fetchNewGo(timeout time.Duration) { + run := func(fetch func()) { + newRunning.Add(1) + go func() { + defer newRunning.Add(-1) + defer fetchingNew.Store(false) + fetch() + }() + } + if !newFetches.TryLock() { + // behind a FetchNew under way, which the page doesn't wait on + run(func() { FetchNew(timeout) }) + return + } + behind := func() { + run(func() { + defer newFetches.Unlock() + fetchNewHeld(timeout) + }) + } + if identitiesUnsettled() { + behind() + return + } + // no CLI left to ask, unless one was forgotten while they were listed + // (a sign-in just finished): asked behind the page, as left out + ps := All() + if identitiesUnsettled() { + behind() + return + } + due, _ := newDue(ps) + if len(due) == 0 { + newFetches.Unlock() + fetchingNew.Store(false) + return + } + run(func() { + defer newFetches.Unlock() + fetchDue(due, timeout) + }) +} + +// newRunning counts the FetchNew calls under way, those started in the +// background included. var newRunning atomic.Int32 // FetchingNew reports whether a FetchNew is under way (start-up's, or one -// started behind a page): accounts' lists may be on their way still. -func FetchingNew() bool { return newRunning.Load() > 0 } +// started behind a page): accounts' lists may be on their way still. One +// started behind a page counts from its start, while it still picks the +// accounts due: a page whose FetchNewBehind found it so returned at once, +// and was told none was on its way until the one picking counted itself. +func FetchingNew() bool { return newRunning.Load() > 0 || fetchingNew.Load() } // FetchNew asks each signed-in account whose vendor list magpie hasn't // fetched yet for it, each for at most timeout. Start-up does this for the @@ -422,14 +478,45 @@ func FetchNew(timeout time.Duration) (missing bool) { defer newRunning.Add(-1) newFetches.Lock() defer newFetches.Unlock() + return fetchNewHeld(timeout) +} + +// fetchNewHeld is FetchNew with newFetches held. +func fetchNewHeld(timeout time.Duration) (missing bool) { // 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 + answered := identitiesAnswered() ps := All() + // one answered since, while they were listed (its look gave up + // waiting) or after: an account it says is signed in was left out if waited, unknown := awaitIdentities(timeout); unknown { missing = true - } else if waited { + } else if waited || answered != identitiesAnswered() { ps = All() } + due, skipped := newDue(ps) + if fetchDue(due, timeout) { + missing = true + } + // one waiting to be asked again, unless another's fetch listed it + for _, f := range skipped { + if _, ok := f.p.Listed(); !ok || f.decide { + missing = true + } + } + return missing +} + +// newFetch is a provider FetchNew asks for its list, and whether for its +// decision models. +type newFetch struct { + p Provider + decide bool +} + +// newDue is those of ps FetchNew asks for their lists now, and those +// skipped as they failed less than newFetchRetry ago; newFetches held. +func newDue(ps []Provider) (due, skipped []newFetch) { for _, p := range ps { // a list of decision models fetched before magpie kept their // windows and input, or not fetched yet (ARNO on Discord) @@ -442,24 +529,38 @@ func FetchNew(timeout time.Duration) (missing bool) { continue } if t, ok := newFetches.m[p.ID]; ok && time.Since(t) < newFetchRetry { - missing = true + skipped = append(skipped, newFetch{p, decide}) + continue + } + due = append(due, newFetch{p, decide}) + } + return due, skipped +} + +// fetchDue asks each of due for its list, each for at most timeout, and +// reports whether one failed; newFetches held. +func fetchDue(due []newFetch, timeout time.Duration) (failed bool) { + for _, f := range due { + p := f.p + // listed since by another's fetch, as a plugin's accounts are + if _, ok := p.Listed(); ok && !f.decide { continue } newFetches.m[p.ID] = time.Now() ctx, cancel := context.WithTimeout(context.Background(), timeout) var err error - if decide && p.Account == nil { + if f.decide && p.Account == nil { _, err = p.fetchDecide(p.Via(ctx)) } else { _, err = p.Fetch(ctx) } if err != nil { log.Println(p.ID + ": " + err.Error()) - missing = true + failed = true } cancel() } - return missing + return failed } // a fetched list: every endpoint's models merged, the base kept for