Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
provider: Codex's list's tag is built again only when what it is built from changes
yetone0e84db8f5f9a
diff --git a/internal/provider/codex_list_tag.go b/internal/provider/codex_list_tag.gonew file mode 100644index 000000000..00f4e0fc1--- /dev/null+++ b/internal/provider/codex_list_tag.go@@ -0,0 +1,100 @@+package provider++import (+ "path/filepath"+ "sync"+ "time"++ "github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/filememo"+ "github.com/yetone/magpie/internal/settings"+)++// Codex's list's tag is asked for on every GET of its models and every+// backend reply that carries X-Models-Etag (gateway.modelsEtag), and+// each time it built the whole catalog: 3.5 MB a call while a request+// held the catalog, 22 MB without, with 8 providers of 40 models. A live+// heap profile of a magpie at rest had 2.1 GB of it in 67 minutes, the+// Codex app asking for its models. It is kept now while nothing it is+// built from changed.++// codexListTagFor is how long a kept tag is used at most: what the stamp+// can't see (an account another app signed in to, held in a keychain; a+// model retired by its date) reaches Codex's list within it.+var codexListTagFor = time.Minute++// codexListSettled is how old a stamped file's time must be to tell a+// later write by: two writes of one size inside a tick of a coarse clock+// leave the same time and size (filememo's settled).+const codexListSettled = 2 * time.Second++// codexListStamp is what the tag is built from, read without building it:+// the writes this magpie made or was told of (Changed, a plugin's change,+// catalog.Touched or Reset, filememo.Forget), the environment, and the+// files another process writes — magpie's providers, settings and+// models.dev catalog, and Codex's config (the effort new sessions start+// at), sign-in and model cache.+type codexListStamp struct {+ gen, fgen, env uint64+ files [6]rootStamp+}++func codexListStampNow() codexListStamp {+ held.Lock()+ gen := held.gen+ held.Unlock()+ home := catalog.CodexHome()+ return codexListStamp{gen: gen, fgen: filememo.Gen(), env: environSum(), files: [6]rootStamp{+ stampOf(Path()), stampOf(settings.Path()), stampOf(catalog.CachePath()),+ stampOf(filepath.Join(home, "config.toml")), stampOf(filepath.Join(home, "auth.json")),+ stampOf(catalog.CodexModelsCache()),+ }}+}++// settled reports whether every file's time is old enough that a write+// after it would stamp another.+func (s codexListStamp) settled(now time.Time) bool {+ for _, f := range s.files {+ if f.ok && now.Sub(f.mod) < codexListSettled {+ return false+ }+ }+ return true+}++var codexListTags struct {+ sync.Mutex+ stamp codexListStamp+ at time.Time+ of map[string]string+}++// codexListTag is buildCodexListTag's, built again only when its stamp+// moved or codexListTagFor went by.+func codexListTag(kind string) string {+ st := codexListStampNow()+ now := time.Now()+ codexListTags.Lock()+ if codexListTags.stamp != st || now.Sub(codexListTags.at) >= codexListTagFor {+ codexListTags.stamp, codexListTags.at, codexListTags.of = st, now, nil+ }+ if tag, ok := codexListTags.of[kind]; ok {+ codexListTags.Unlock()+ return tag+ }+ codexListTags.Unlock()+ // built from what is there after st was taken: never older than st+ tag := buildCodexListTag(kind)+ if !st.settled(now) {+ return tag+ }+ codexListTags.Lock()+ if codexListTags.stamp == st {+ if codexListTags.of == nil {+ codexListTags.of = map[string]string{}+ }+ codexListTags.of[kind] = tag+ }+ codexListTags.Unlock()+ return tag+}diff --git a/internal/provider/codex_list_tag_test.go b/internal/provider/codex_list_tag_test.gonew file mode 100644index 000000000..4e4ff92d9--- /dev/null+++ b/internal/provider/codex_list_tag_test.go@@ -0,0 +1,217 @@+package provider++import (+ "bytes"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/filememo"+ "github.com/yetone/magpie/internal/settings"+)++// listTagHome is a ChatGPT account signed in to Codex beside 8 providers+// of 40 models each, as a magpie in daily use has them, its files written+// long ago.+func listTagHome(t *testing.T) {+ t.Helper()+ signIn(t)+ for p := range 8 {+ id := fmt.Sprintf("relay%d", p)+ var ids []string+ var live []catalog.Model+ for m := range 40 {+ ids = append(ids, fmt.Sprintf("model-%d", m))+ live = append(live, catalog.Model{ID: fmt.Sprintf("model-%d", m), Context: 200000})+ }+ if err := Save(Provider{ID: id, Name: id, Chat: "https://" + id + ".test/v1", Key: "k", Models: ids}); err != nil {+ t.Fatal(err)+ }+ if err := catalog.SaveLive(id, "https://"+id+".test/v1", live); err != nil {+ t.Fatal(err)+ }+ }+ writeCodexConfig(t, "model_reasoning_effort = \"high\"\n")+ ageListFiles(t)+}++func writeCodexConfig(t *testing.T, body string) {+ t.Helper()+ path := filepath.Join(catalog.CodexHome(), "config.toml")+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {+ t.Fatal(err)+ }+}++// ageListFiles has the files the tag is stamped by written long ago, as+// a magpie at rest has them, all at one time: a file changes its stamp+// by its size alone, as a write within one tick of a coarse clock does.+func ageListFiles(t *testing.T) {+ t.Helper()+ old := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)+ home := catalog.CodexHome()+ for _, p := range []string{Path(), settings.Path(), catalog.CachePath(),+ filepath.Join(home, "config.toml"), filepath.Join(home, "auth.json"), catalog.CodexModelsCache()} {+ if err := os.Chtimes(p, old, old); err != nil && !os.IsNotExist(err) {+ t.Fatal(err)+ }+ }+}++// measure is the allocations and bytes of one call of f, on average.+func measure(f func()) (allocs, bytes float64) {+ const runs = 50+ f()+ var a, z runtime.MemStats+ runtime.GC()+ runtime.ReadMemStats(&a)+ for range runs {+ f()+ }+ runtime.ReadMemStats(&z)+ return float64(z.Mallocs-a.Mallocs) / runs, float64(z.TotalAlloc-a.TotalAlloc) / runs+}++// The tag of Codex's list is asked for on every GET of Codex's models and+// every backend reply, and built the whole catalog each time: 22 MB a call+// here, 2.1 GB in an hour of a magpie at rest. While nothing it is built+// from changed, it is kept.+func TestCodexListTagKeptWhileNothingChanged(t *testing.T) {+ listTagHome(t)+ want := buildCodexListTag("")+ wantOwn := buildCodexListTag("own")+ if CodexListTag() != want || CodexOwnListTag() != wantOwn {+ t.Fatal("the tag isn't the one built afresh")+ }+ n, by := measure(func() { CodexListTag(); CodexOwnListTag() })+ t.Logf("CodexListTag and CodexOwnListTag: %.0f allocs, %.0f bytes a call", n, by)+ if n > 200 {+ t.Errorf("with nothing changed, the tags took %.0f allocations (%.0f bytes) a call: the catalog built again", n, by)+ }+ release := Hold()+ n, by = measure(func() { CodexListTag(); CodexOwnListTag() })+ release()+ t.Logf("held: %.0f allocs, %.0f bytes a call", n, by)+ if n > 200 {+ t.Errorf("held, the tags took %.0f allocations (%.0f bytes) a call", n, by)+ }+ if CodexListTag() != want || CodexOwnListTag() != wantOwn {+ t.Fatal("the kept tag isn't the one built afresh")+ }+}++// A kept tag follows every change to what it is built from: magpie's own+// writes, and files another process writes behind its back.+func TestCodexListTagFollowsChanges(t *testing.T) {+ listTagHome(t)+ step := func(name string, change func()) {+ t.Helper()+ before := CodexListTag()+ if before != CodexListTag() {+ t.Fatalf("%s: the tag moved with nothing changed", name)+ }+ change()+ ageListFiles(t)+ got := CodexListTag()+ if got == before {+ t.Errorf("%s: the tag stayed %s", name, got)+ }+ if want := buildCodexListTag(""); got != want {+ t.Errorf("%s: the tag is %s, built afresh %s", name, got, want)+ }+ }+ step("a provider saved", func() {+ if err := Save(Provider{ID: "more", Name: "more", Chat: "https://more.test/v1", Key: "k", Models: []string{"m-1"}}); err != nil {+ t.Fatal(err)+ }+ })+ step("a setting saved", func() {+ s := settings.Load()+ s.CodexAutoReview = "relay0/model-1"+ if err := settings.Save(s); err != nil {+ t.Fatal(err)+ }+ })+ // a list's windows rewritten behind the stamp's files: only what+ // this process is told of says so+ relist := func(id string, n int) {+ t.Helper()+ b, err := os.ReadFile(catalog.LivePath(id))+ if err != nil {+ t.Fatal(err)+ }+ b = bytes.ReplaceAll(b, []byte(`"Context": 200000`), []byte(fmt.Sprintf(`"Context": %d`, n)))+ if err := os.WriteFile(catalog.LivePath(id), b, 0o644); err != nil {+ t.Fatal(err)+ }+ }+ step("a list written, filememo told", func() {+ relist("relay1", 120000)+ filememo.Forget()+ })+ step("a list written, what is held dropped (a plugin's change)", func() {+ relist("relay2", 110000)+ dropHeld()+ })+ step("a vendor's list fetched", func() {+ if err := catalog.SaveLive("relay3", "https://relay3.test/v1", []catalog.Model{{ID: "model-1", Context: 100000}}); err != nil {+ t.Fatal(err)+ }+ })+ step("Codex's effort set in Codex", func() {+ writeCodexConfig(t, "model_reasoning_effort = \"low\"\n")+ })++ // the providers' file as another magpie (the CLI) leaves it: nothing+ // in this process is told+ before, err := os.ReadFile(Path())+ if err != nil {+ t.Fatal(err)+ }+ if err := Save(Provider{ID: "elsewhere", Name: "elsewhere", Chat: "https://elsewhere.test/v1", Key: "k", Models: []string{"e-1"}}); err != nil {+ t.Fatal(err)+ }+ after, err := os.ReadFile(Path())+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(Path(), before, 0o600); err != nil {+ t.Fatal(err)+ }+ ageListFiles(t)+ step("the providers' file written by another magpie", func() {+ if err := os.WriteFile(Path(), after, 0o600); err != nil {+ t.Fatal(err)+ }+ })+}++// What the stamp can't see reaches the tag within codexListTagFor.+func TestCodexListTagBuiltAgainAfterItsTime(t *testing.T) {+ listTagHome(t)+ CodexListTag()+ old := codexListTagFor+ codexListTagFor = 0+ t.Cleanup(func() { codexListTagFor = old })+ if n, _ := measure(func() { CodexListTag() }); n < 1000 {+ t.Errorf("past its time, the tag took %.0f allocations a call: not built again", n)+ }+}++// A file written just now may be written again inside one tick of a+// coarse clock with the same size: a tag built then isn't kept.+func TestCodexListTagNotKeptOverAFreshFile(t *testing.T) {+ listTagHome(t)+ writeCodexConfig(t, "model_reasoning_effort = \"high\"\n")+ CodexListTag()+ if n, _ := measure(func() { CodexListTag() }); n < 1000 {+ t.Errorf("over a file written just now, the tag took %.0f allocations a call: kept", n)+ }+}diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.goindex fa3a69366..3ceea0bba 100644--- a/internal/provider/codex_models.go+++ b/internal/provider/codex_models.go@@ -494,7 +494,8 @@ func CodexListTag() string { return codexListTag("") }// moves from one list to the other; a V1 list's mark stays in front.func CodexOwnListTag() string { return codexListTag("own") }-func codexListTag(kind string) string {+// buildCodexListTag is codexListTag built afresh from the catalog.+func buildCodexListTag(kind string) string {ms := CodexListed()off := slices.Sorted(maps.Keys(CodexNativeHidden()))for _, slug := range off {