diff --git a/internal/sessions/codex_config_memo_test.go b/internal/sessions/codex_config_memo_test.go new file mode 100644 index 000000000..53a293c69 --- /dev/null +++ b/internal/sessions/codex_config_memo_test.go @@ -0,0 +1,33 @@ +package sessions + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// Sessions read Codex's config.toml on every visit, and one with a table for +// each of thousands of projects took ~0.15s of CPU to parse (#1665): it is +// parsed again only when it changes. +func TestCodexConfigParsedOncePerChange(t *testing.T) { + d := t.TempDir() + p := filepath.Join(d, "config.toml") + old := time.Now().Add(-time.Hour) + write := func(s string) { + os.WriteFile(p, []byte(s), 0o600) + os.Chtimes(p, old, old) + } + write("model_provider = \"aaaa\"\n") + if got := CodexProviderIn(d); got != "aaaa" { + t.Fatal(got) + } + write("model_provider = \"bbbb\"\n") + if got := CodexProviderIn(d); got != "aaaa" { + t.Fatalf("parsed again with the file unchanged by size and time: %q", got) + } + os.WriteFile(p, []byte("model_provider = \"cc\"\n"), 0o600) + if got := CodexProviderIn(d); got != "cc" { + t.Fatalf("after a change: %q", got) + } +} diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go index fda3682a4..6a1de69c0 100644 --- a/internal/sessions/codex_provider.go +++ b/internal/sessions/codex_provider.go @@ -19,6 +19,7 @@ import ( toml "github.com/pelletier/go-toml/v2" "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/steady" ) @@ -99,11 +100,16 @@ type codexConfig struct { } `toml:"profiles"` } +// readCodexConfig is the folder's codexConfig, parsed again only when +// config.toml changes: a config.toml holding a table for each of ten +// thousand projects took ~0.15s of CPU to parse, on each visit to Sessions +// (#1665). What it gives is shared and must not be changed. func readCodexConfig(home string) codexConfig { - var c codexConfig - if b, err := os.ReadFile(filepath.Join(home, "config.toml")); err == nil { + c, _ := filememo.Read("sessions codex config", filepath.Join(home, "config.toml"), func(b []byte) (codexConfig, error) { + var c codexConfig toml.Unmarshal(b, &c) - } + return c, nil + }) return c }