Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

agent: a catalog sync's round looks at each file once; a write reads the disk (#1665)

yetone5160809d2e1d
diff --git a/internal/agent/sync.go b/internal/agent/sync.go
index cfa3d9083..3853fca87 100644
--- a/internal/agent/sync.go
+++ b/internal/agent/sync.go
@@ -10,6 +10,7 @@ import (
"sync"
"github.com/yetone/magpie/internal/edit"
+ "github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/provider"
"gopkg.in/yaml.v3"
)
@@ -45,6 +46,10 @@ func SyncCatalog() {
// the catalog built once for every agent's lists, not for each
// look-up of each (thousands at magpie's start, with 30 providers)
release := provider.Hold()
+ // and each agent's files looked at once a round, not each time
+ // one is asked about (#1665: settings.json hundreds of times a
+ // round); a write is made from what is on the disk (edit.Read)
+ unhold := filememo.Hold()
renaming := setToFoundGroups()
for _, a := range All() {
if a.Sync != nil {
@@ -55,6 +60,7 @@ func SyncCatalog() {
a.renameFoundGroups()
}
}
+ unhold()
release()
syncing.Lock()
if !syncing.again {
diff --git a/internal/edit/env.go b/internal/edit/env.go
index 2591568c9..0f8c47836 100644
--- a/internal/edit/env.go
+++ b/internal/edit/env.go
@@ -11,7 +11,7 @@ var envLine = regexp.MustCompile(`^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=
// GetEnvFile reads one key from a dotenv file.
func GetEnvFile(path, key string) (string, bool) {
- raw, err := Read(path)
+ raw, err := readHeld(path)
if err != nil {
return "", false
}
diff --git a/internal/edit/file.go b/internal/edit/file.go
index 8926bf8fb..e30a1f3f5 100644
--- a/internal/edit/file.go
+++ b/internal/edit/file.go
@@ -23,7 +23,11 @@ import (
// Read returns the file contents, or (nil, nil) when the file does not exist.
// A file unchanged since it was last read is not read again (the Agents
// page looks at each agent's files many times over), and what is returned
-// is the caller's own to change.
+// is the caller's own to change. It is looked at even while a request
+// holds what was read (filememo.Hold), as what is read here is what a
+// write is made from: bytes held from a second ago would write back over
+// what another app wrote since. A look that only reads goes through
+// readHeld.
//
// A UTF-8 byte order mark at the start is not part of what is returned:
// Windows tools (PowerShell's UTF8 encoding, Notepad, Claude Code channel
@@ -31,7 +35,19 @@ import (
// which the agent reads through while a JSON or TOML parser refuses it
// (#1534). WriteAtomic puts it back, see keepBOM.
func Read(path string) ([]byte, error) {
- b, err := filememo.Read("bytes", path, func(b []byte) ([]byte, error) { return b, nil })
+ return readThrough(path, filememo.ReadNow[[]byte])
+}
+
+// readHeld is Read for a look that writes nothing (GetJSON, GetTOMLTop):
+// while a request holds what was read, a file found unchanged within the
+// second is not looked at again (#1665: one catalog sync looked at an
+// agent's settings.json hundreds of times).
+func readHeld(path string) ([]byte, error) {
+ return readThrough(path, filememo.Read[[]byte])
+}
+
+func readThrough(path string, through func(string, string, func([]byte) ([]byte, error)) ([]byte, error)) ([]byte, error) {
+ b, err := through("bytes", path, func(b []byte) ([]byte, error) { return b, nil })
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
@@ -97,7 +113,6 @@ func Filtered(f func(path string, data []byte) []byte, fn func() error) error {
// links is written in place, see writeInPlace. Once written, temp files
// earlier writes of path left behind go, see removeStaleTemps.
func WriteAtomic(path string, data []byte) error {
- defer filememo.Forget() // read again, where a request holds it
path, err := Target(path)
if err != nil {
return err
@@ -112,6 +127,10 @@ func WriteAtomic(path string, data []byte) error {
if cur, err := os.ReadFile(path); err == nil && bytes.Equal(cur, data) {
return nil
}
+ // read again, where a request holds it; a file left alone above keeps
+ // what was held of every file (a catalog sync writes each agent's
+ // files each round, almost always as they are)
+ defer filememo.Forget()
if hardLinked(path) {
f, err := os.OpenFile(path, os.O_WRONLY, 0)
if err == nil {
diff --git a/internal/edit/held_test.go b/internal/edit/held_test.go
new file mode 100644
index 000000000..1e7b03a36
--- /dev/null
+++ b/internal/edit/held_test.go
@@ -0,0 +1,95 @@
+package edit
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/filememo"
+)
+
+// #1665: a catalog sync holds what was read for its round, so an agent's
+// files are looked at once a round; a write is still made from what is on
+// the disk, never over what another app wrote inside the held second.
+func TestHeldReadIsNotWhatAWriteIsMadeFrom(t *testing.T) {
+ cases := []struct {
+ name, file, start, theirs string
+ get func(path string) (string, bool)
+ set func(path string) error
+ want []string
+ }{
+ {"json", "settings.json", `{"a": 1}`, `{"a": 1, "theirs": true}`,
+ func(p string) (string, bool) { return GetJSON(p, "a") },
+ func(p string) error { return SetJSON(p, KV{"ours", 2}) },
+ []string{`"theirs": true`, `"ours"`}},
+ {"toml", "config.toml", "a = 1\n", "a = 1\ntheirs = true\n",
+ func(p string) (string, bool) { return GetTOMLTop(p, "a") },
+ func(p string) error { return SetTOMLTop(p, KV{"ours", 2}) },
+ []string{"theirs = true", "ours = 2"}},
+ {"yaml", "config.yaml", "a: 1\n", "a: 1\ntheirs: true\n",
+ func(p string) (string, bool) { return GetYAMLTop(p, "a") },
+ func(p string) error { return SetYAMLTop(p, KV{"ours", 2}) },
+ []string{"theirs: true", "ours: 2"}},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), c.file)
+ old := time.Now().Add(-time.Hour)
+ writeAged(t, path, c.start, old)
+ release := filememo.Hold()
+ defer release()
+ if v, ok := c.get(path); !ok || v != "1" {
+ t.Fatalf("get = %q, %v", v, ok)
+ }
+ // another app's write, past the time a stamp can't tell apart
+ writeAged(t, path, c.theirs, old.Add(time.Minute))
+ if v, ok := c.get(path); !ok || v != "1" {
+ t.Fatalf("held get = %q, %v", v, ok)
+ }
+ if err := c.set(path); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := os.ReadFile(path)
+ for _, w := range c.want {
+ if !strings.Contains(string(b), w) {
+ t.Fatalf("missing %q after the write:\n%s", w, b)
+ }
+ }
+ })
+ }
+}
+
+func writeAged(t *testing.T, path, text string, at time.Time) {
+ t.Helper()
+ if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chtimes(path, at, at); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A write that leaves a file as it is keeps what is held of every file:
+// a sync writes each agent's files each round, almost always unchanged.
+func TestUnchangedWriteKeepsWhatIsHeld(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "settings.json")
+ writeAged(t, path, `{"a": 1}`, time.Now().Add(-time.Hour))
+ release := filememo.Hold()
+ defer release()
+ GetJSON(path, "a")
+ g := filememo.Gen()
+ if err := SetJSON(path, KV{"a", 1}); err != nil {
+ t.Fatal(err)
+ }
+ if filememo.Gen() != g {
+ t.Fatal("an unchanged write forgot what was held")
+ }
+ if err := SetJSON(path, KV{"a", 2}); err != nil {
+ t.Fatal(err)
+ }
+ if filememo.Gen() == g {
+ t.Fatal("a write that changed the file kept what was held")
+ }
+}
diff --git a/internal/edit/json.go b/internal/edit/json.go
index 79a71d5f8..3cefc1cb1 100644
--- a/internal/edit/json.go
+++ b/internal/edit/json.go
@@ -18,7 +18,7 @@ type KV struct {
// GetJSON reads a dot-separated key path from a JSON or JSONC file.
func GetJSON(path, keyPath string) (string, bool) {
- raw, err := Read(path)
+ raw, err := readHeld(path)
if err != nil || len(raw) == 0 {
return "", false
}
@@ -33,7 +33,7 @@ func GetJSON(path, keyPath string) (string, bool) {
// the file (a string with its quotes, a number, true), for putting back
// exactly as it was (a json.RawMessage given to SetJSON).
func GetJSONRaw(path, keyPath string) (string, bool) {
- raw, err := Read(path)
+ raw, err := readHeld(path)
if err != nil || len(raw) == 0 {
return "", false
}
diff --git a/internal/edit/jsonarray.go b/internal/edit/jsonarray.go
index 45e54f43e..48f9ca533 100644
--- a/internal/edit/jsonarray.go
+++ b/internal/edit/jsonarray.go
@@ -18,7 +18,7 @@ import (
// GetJSONItem returns the raw JSON of the first element of the file's
// top-level array that has every member of where.
func GetJSONItem(path string, where map[string]string) (string, bool) {
- raw, err := Read(path)
+ raw, err := readHeld(path)
if err != nil || len(bytes.TrimSpace(raw)) == 0 {
return "", false
}
diff --git a/internal/edit/toml.go b/internal/edit/toml.go
index d6850eef9..370b44fbf 100644
--- a/internal/edit/toml.go
+++ b/internal/edit/toml.go
@@ -300,7 +300,7 @@ func GetTOMLTop(path, key string) (string, bool) {
// getTOMLTopLines is GetTOMLTop for a file that isn't valid TOML: the first
// line that looks like `key = value` before one that looks like a header.
func getTOMLTopLines(path, key string) (string, bool) {
- raw, err := Read(path)
+ raw, err := readHeld(path)
if err != nil || raw == nil {
return "", false
}
diff --git a/internal/edit/yaml.go b/internal/edit/yaml.go
index c0108a5e9..a0a0ff33d 100644
--- a/internal/edit/yaml.go
+++ b/internal/edit/yaml.go
@@ -287,7 +287,7 @@ func JSONToYAML(src, dst string) error {
// Unrelated duplicate keys, complex keys or invalid tags must not hide a
// readable model setting. Writers use loadYAMLForEdit to validate the whole file.
func loadYAML(path string) (*yaml.Node, error) {
- raw, err := Read(path)
+ raw, err := readHeld(path)
if err != nil || len(bytes.TrimSpace(raw)) == 0 {
return nil, err
}
diff --git a/internal/edit/yaml_top.go b/internal/edit/yaml_top.go
index d8bfc037e..64c521e82 100644
--- a/internal/edit/yaml_top.go
+++ b/internal/edit/yaml_top.go
@@ -13,7 +13,7 @@ import (
// GetYAMLTop reads a top-level scalar key from a YAML file. Quoted keys and
// string values are decoded; malformed files return ("", false).
func GetYAMLTop(path, key string) (string, bool) {
- raw, err := Read(path)
+ raw, err := readHeld(path)
if err != nil {
return "", false
}
diff --git a/internal/filememo/filememo.go b/internal/filememo/filememo.go
index c3aeb5ee8..55c60d7d7 100644
--- a/internal/filememo/filememo.go
+++ b/internal/filememo/filememo.go
@@ -162,15 +162,26 @@ func Look(path string) {
// bytes). kind tells apart two parses of
// one file. What it returns is shared: the caller must not change it.
func Read[T any](kind, path string, parse func([]byte) (T, error)) (T, error) {
+ return read(kind, path, parse, true)
+}
+
+// ReadNow is Read with the file looked at even while a request holds what
+// was read (Hold): for bytes a write is made from, which a write another
+// process made inside the held second would otherwise be lost under.
+func ReadNow[T any](kind, path string, parse func([]byte) (T, error)) (T, error) {
+ return read(kind, path, parse, false)
+}
+
+func read[T any](kind, path string, parse func([]byte) (T, error), held bool) (T, error) {
var zero T
key := kind + "\x00" + path
mu.Lock()
e, ok := seen[key]
- if ok && holds > 0 && e.raw == nil && e.gen == gen && time.Since(e.checked) < heldFor {
+ if ok && held && holds > 0 && e.raw == nil && e.gen == gen && time.Since(e.checked) < heldFor {
mu.Unlock()
return e.v.(T), nil
}
- if m, ok := missing[path]; ok && holds > 0 && m.gen == gen && time.Since(m.checked) < heldFor {
+ if m, ok := missing[path]; ok && held && holds > 0 && m.gen == gen && time.Since(m.checked) < heldFor {
mu.Unlock()
return zero, m.err
}
diff --git a/internal/settings/held_test.go b/internal/settings/held_test.go
new file mode 100644
index 000000000..5af114d2a
--- /dev/null
+++ b/internal/settings/held_test.go
@@ -0,0 +1,50 @@
+package settings
+
+import (
+ "bytes"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/filememo"
+)
+
+// #1665: a catalog sync holds what was read for its round. A change to the
+// settings made while it holds them is made from settings.json as it is on
+// the disk: what the user or another magpie saved inside the held second
+// stays.
+func TestHeldSettingsAreNotWhatAWriteIsMadeFrom(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ if err := Save(Settings{Theme: "light"}); err != nil {
+ t.Fatal(err)
+ }
+ old := time.Now().Add(-time.Hour)
+ if err := os.Chtimes(Path(), old, old); err != nil {
+ t.Fatal(err)
+ }
+ release := filememo.Hold()
+ defer release()
+ if Load().Theme != "light" {
+ t.Fatal("theme not saved")
+ }
+ // another magpie's save, past the time a stamp can't tell apart
+ b, err := os.ReadFile(Path())
+ if err != nil || !bytes.Contains(b, []byte(`"light"`)) {
+ t.Fatalf("%v: %s", err, b)
+ }
+ if err := os.WriteFile(Path(), bytes.Replace(b, []byte(`"light"`), []byte(`"dark"`), 1), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chtimes(Path(), old.Add(time.Minute), old.Add(time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ if Load().Theme != "light" {
+ t.Fatal("not held: the test no longer holds what it is about")
+ }
+ if err := SetGatewayConversations(true); err != nil {
+ t.Fatal(err)
+ }
+ if got := Load(); got.Theme != "dark" || !got.GatewayConversations {
+ t.Fatalf("theme %q, recording %v: the other save was written over", got.Theme, got.GatewayConversations)
+ }
+}
diff --git a/internal/settings/settings.go b/internal/settings/settings.go
index 3e39e8055..1e8dd085c 100644
--- a/internal/settings/settings.go
+++ b/internal/settings/settings.go
@@ -1182,6 +1182,22 @@ func Portable() string { return appdir.Portable() }
// writing them in place rather than replacing their inode.
var fileMu sync.RWMutex
+// writing is set while fileMu is held for a write: what a write is made
+// from is read from the disk even while a request holds what was read
+// (filememo.Hold), or a change another magpie or the user made in the
+// held second would be written over. Only set or read under fileMu.
+var writing bool
+
+// lockFile takes fileMu for a write, and returns what lets it go.
+func lockFile() (unlock func()) {
+ fileMu.Lock()
+ writing = true
+ return func() {
+ writing = false
+ fileMu.Unlock()
+ }
+}
+
// Load reads the settings; anything missing or unreadable is the default.
func Load() Settings {
fileMu.RLock()
@@ -1254,7 +1270,11 @@ func loadChecked() (Settings, error) {
// read again only once the file changed: a look at the agents asks for
// the settings for every model of every agent (hundreds of reads, a
// fifth of the Agents page's wait)
- b, err := filememo.Read("settings", Path(), func(b []byte) ([]byte, error) { return b, nil })
+ through := filememo.Read[[]byte]
+ if writing {
+ through = filememo.ReadNow[[]byte]
+ }
+ b, err := through("settings", Path(), func(b []byte) ([]byte, error) { return b, nil })
if err != nil {
if os.IsNotExist(err) {
return s.normal(), nil
@@ -1382,16 +1402,14 @@ func SavedAddr() string {
// Save validates and writes the settings, preserving current recording consent.
func Save(s Settings) error {
- fileMu.Lock()
- defer fileMu.Unlock()
+ defer lockFile()()
return save(s, false)
}
// SetGatewayConversations changes local recording consent without overwriting
// other settings from an earlier snapshot.
func SetGatewayConversations(on bool) error {
- fileMu.Lock()
- defer fileMu.Unlock()
+ defer lockFile()()
s := load()
s.GatewayConversations = on
return save(s, true)
@@ -1401,8 +1419,7 @@ func SetGatewayConversations(on bool) error {
// file holds now, so a save elsewhere from an older snapshot isn't undone.
// A settings file that can't be read is left as it is, with the error.
func EditCheckinOff(edit func([]string) []string) error {
- fileMu.Lock()
- defer fileMu.Unlock()
+ defer lockFile()()
s, err := loadChecked()
if err != nil {
return err
@@ -1421,8 +1438,7 @@ func EditCheckinOff(edit func([]string) []string) error {
// error: what it holds is unknown, not "no aliases". edit is given a copy,
// and an error from it saves nothing.
func EditUsageAliases(edit func(map[string]string) (map[string]string, error)) error {
- fileMu.Lock()
- defer fileMu.Unlock()
+ defer lockFile()()
s, err := loadChecked()
if err != nil {
return err
@@ -1441,8 +1457,7 @@ func EditUsageAliases(edit func(map[string]string) (map[string]string, error)) e
// SetRedactModel turns the local masking model on or off, on its own, as
// Settings → Privacy does once the model is downloaded.
func SetRedactModel(on bool) error {
- fileMu.Lock()
- defer fileMu.Unlock()
+ defer lockFile()()
s := load()
s.RedactModel = on
return save(s, false)
@@ -1451,8 +1466,7 @@ func SetRedactModel(on bool) error {
// SetRedactModelName keeps the local model the user picked while it is
// off, for turning it on.
func SetRedactModelName(name string) error {
- fileMu.Lock()
- defer fileMu.Unlock()
+ defer lockFile()()
s := load()
s.RedactModelName = name
return save(s, false)
@@ -1461,8 +1475,7 @@ func SetRedactModelName(name string) error {
// SetRedactModelScore keeps score as the local model id's threshold; 0
// is back to the model's own.
func SetRedactModelScore(id string, score float64) error {
- fileMu.Lock()
- defer fileMu.Unlock()
+ defer lockFile()()
s := load()
m := maps.Clone(s.RedactModelScore)
if m == nil {
@@ -1483,8 +1496,7 @@ func SetRedactModelScore(id string, score float64) error {
// UseRedactModel turns the local masking model on as name, the model
// the user picked, once that model is downloaded.
func UseRedactModel(name string) error {
- fileMu.Lock()
- defer fileMu.Unlock()
+ defer lockFile()()
s := load()
s.RedactModel, s.RedactModelName = true, name
return save(s, false)