From d5322cfbf1d3a3e096966a334b60a1c44eafff7c Mon Sep 17 00:00:00 2001 From: Snowyy <142957559+Snowyyyyyy1@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:37:07 +0800 Subject: [PATCH] agents: dsh's route is written again while magpie serves, not only when magpie starts (#528) dsh resolves a session's model from the patch list before it contacts the gateway, so a route that lists a model magpie no longer gives dsh fails every session, with nothing reaching magpie to show for it. While magpie serves the gateway it now writes the fields it manages on existing dsh magpie routes again every 30s where they are not what magpie would write now, from gateway.WhileServing next to the WebDAV sync. A route the user removed stays removed, agent-default-model stays the user's choice, and an empty catalog writes nothing. --- internal/agent/dsh.go | 221 +++++++++++++++++++++++----- internal/agent/dsh_route_test.go | 243 +++++++++++++++++++++++++++++++ internal/agent/dsh_test.go | 63 +++++++- internal/agent/sync_test.go | 2 +- main.go | 4 + 5 files changed, 496 insertions(+), 37 deletions(-) diff --git a/internal/agent/dsh.go b/internal/agent/dsh.go index 6e82bbe3b..f1f71232b 100644 --- a/internal/agent/dsh.go +++ b/internal/agent/dsh.go @@ -25,15 +25,21 @@ package agent import ( "bytes" + "context" "encoding/json" + "errors" "fmt" + "log" "os" "path/filepath" "regexp" "strings" + "sync" + "time" "gopkg.in/yaml.v3" + "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/gateway" ) @@ -538,27 +544,36 @@ func yamlScalar(v string) string { func dshStashKey(path, id string) string { return "dsh:" + path + ":" + id } +// dshWrites serializes magpie's own writers of dsh's patch lists: the sync a +// catalog change asks for, a model picked here, and the round magpie does +// while it serves the gateway. Two of them reading one file and then writing +// it would leave whichever read first as its content. +var dshWrites sync.Mutex + // dshSet writes v as the model new sessions start on: a catalog model // through the gateway, one of dsh's own models directly, or "" for dsh's own // default. Every profile gets it; config.yaml only where there are none. func dshSet(dir, v string) error { + dshWrites.Lock() + defer dshWrites.Unlock() ref, viaGateway := strings.CutPrefix(v, magpieID+"/") if viaGateway && !isMagpie(ref) { return fmt.Errorf("unknown model %q", v) } legacy := filepath.Join(dir, "config.yaml") + models := magpieModels("dsh") files := dshProfiles(dir) if len(files) == 0 { - return dshSetFile(legacy, v, false) + return dshSetFile(legacy, v, false, models) } for _, f := range files { - if err := dshSetFile(f, v, true); err != nil { + if err := dshSetFile(f, v, true, models); err != nil { return err } } // what an older dsh was given is no use now if _, err := os.Stat(legacy); err == nil { - if err := dshSetFile(legacy, "", false); err != nil { + if err := dshSetFile(legacy, "", false, models); err != nil { return err } } @@ -598,7 +613,7 @@ func dshEnv(dir string, on bool) error { // dshSetFile writes v into one patch list; modern is the layout of dsh // 0.1.5 on. -func dshSetFile(path, v string, modern bool) error { +func dshSetFile(path, v string, modern bool, models []catalog.Model) error { head, items, err := dshRead(path) if err != nil { return err @@ -640,12 +655,12 @@ func dshSetFile(path, v string, modern bool) error { drop("api-gateway") drop("agent-loop") drop("llm-deepseek") - if items, err = dshPutRoute(items, false); err != nil { + if items, err = dshPutRoute(items, false, nil); err != nil { return err } case modern && viaGateway: drop("llm-deepseek") // magpie's before it was a provider of its own - if items, err = dshPutRoute(items, true); err != nil { + if items, err = dshPutRoute(items, true, models); err != nil { return err } if !contains(dshLevels(ref), effort) { @@ -654,7 +669,7 @@ func dshSetFile(path, v string, modern bool) error { put("agent-default-model", dshDefaultLines(dshRoute, ref, effort)) case modern: drop("llm-deepseek") - if items, err = dshPutRoute(items, false); err != nil { + if items, err = dshPutRoute(items, false, nil); err != nil { return err } if !contains(dshEfforts, effort) { @@ -662,7 +677,7 @@ func dshSetFile(path, v string, modern bool) error { } put("agent-default-model", dshDefaultLines("deepseek-official", v, effort)) case viaGateway: - put("llm-deepseek", dshProviderLines(effort)) + put("llm-deepseek", dshProviderLines(effort, models)) put("agent-loop", dshLoopLines(ref)) put("api-gateway", dshRouteLines(ref)) default: @@ -677,7 +692,7 @@ func dshSetFile(path, v string, modern bool) error { // custom providers of the llm-pi-ai entry, or with on false takes it out. // Other routes there, the user's or ones dsh added beside magpie's, stay; an // entry left with nothing goes. -func dshPutRoute(items []dshItem, on bool) ([]dshItem, error) { +func dshPutRoute(items []dshItem, on bool, models []catalog.Model) ([]dshItem, error) { i := dshFindLast(items, dshPiRow) if i < 0 && !on { return items, nil @@ -697,7 +712,7 @@ func dshPutRoute(items []dshItem, on bool) ([]dshItem, error) { providers := yamlMapping(config, "providers") if on { var route yaml.Node - if err := route.Encode(dshRouteConfig()); err != nil { + if err := route.Encode(dshRouteConfig(models)); err != nil { return nil, err } // what dsh's Models page added to it (a default level, headers) @@ -816,9 +831,11 @@ func dshLevels(ref string) []string { return nil } -func dshRouteConfig() dshPiRoute { +// dshRouteConfig is magpie's route for models, the catalog one round read: +// what the round decides from and what it writes come from the same list. +func dshRouteConfig(models []catalog.Model) dshPiRoute { r := dshPiRoute{DisplayName: "Magpie", APIKeyEnv: dshKeyRef, API: "openai-completions", BaseURL: gatewayV1(), Models: []dshPiModel{}} - for _, m := range magpieModels("dsh") { + for _, m := range models { e := dshPiModel{ID: m.ID, Name: m.Name, ContextWindow: m.Context} if m.Output > 0 { e.MaxTokens = maxTokens(m) @@ -844,7 +861,7 @@ func yamlQuote(s string) string { // the gateway, with the catalog as the models its /model offers and the key // in the entry. effort is the thinking effort sessions start with, high // (dsh's own default) when "". -func dshProviderLines(effort string) []string { +func dshProviderLines(effort string, models []catalog.Model) []string { if effort == "" { effort = "high" } @@ -857,7 +874,7 @@ func dshProviderLines(effort string) []string { " reasoningEffort: " + effort, " models:", } - ms := magpieModels("dsh") + ms := models if len(ms) == 0 { lines[len(lines)-1] = " models: []" } @@ -923,9 +940,12 @@ func dshRouteLines(model string) []string { // profile still on dsh's DeepSeek row taken over moves to the route. // Nothing else in the patch lists changes. func dshSync(dir string) error { + dshWrites.Lock() + defer dshWrites.Unlock() + models := magpieModels("dsh") files := dshProfiles(dir) if len(files) == 0 { - return dshSyncLegacy(filepath.Join(dir, "config.yaml")) + return dshSyncLegacy(filepath.Join(dir, "config.yaml"), models) } defer func() { // the key under the name the route gives it, moved from the old one @@ -934,12 +954,12 @@ func dshSync(dir string) error { } }() for _, f := range files { - head, items, err := dshRead(f) + _, items, err := dshRead(f) if err != nil { continue } if dshOldWiring(items) { - if err := dshMove(f, items); err != nil { + if err := dshMove(f, items, models); err != nil { return err } continue @@ -947,24 +967,143 @@ func dshSync(dir string) error { if !dshWired(items) { continue } - i := dshFindLast(items, dshPiRow) - before := strings.Join(items[i].lines, "\n") - if items, err = dshPutRoute(items, true); err != nil { - continue - } - if strings.Join(items[i].lines, "\n") == before { - continue - } - if err := dshWrite(f, head, items); err != nil { + if _, err := dshRouteAgain(f, models); err != nil { return err } } - return dshFillNewProfiles(files) + return dshFillNewProfiles(files, models) +} + +// dshRouteAgain writes magpie's route again in one patch list where it is no +// longer what magpie would write, and says whether it wrote. It is the one +// thing that may be done again at any time: the route is magpie's list of +// its own models, while the model a session starts on is the user's pick +// (see dshCheck). A patch list without magpie's route is left as it is — +// one the user took out stays out — and so is one written between the read +// and the write, which is the newer of the two: the next round reads it. +// models is the catalog the round read: with none there is no route to write, +// and writing an empty one would take a working list away. +func dshRouteAgain(f string, models []catalog.Model) (bool, error) { + if len(models) == 0 { + return false, nil + } + raw, err := edit.Read(f) + if err != nil { + return false, nil + } + head, items, err := dshParse(f, string(raw)) + if err != nil || !dshWired(items) { + return false, nil + } + i := dshFindLast(items, dshPiRow) + before := strings.Join(items[i].lines, "\n") + if items, err = dshPutRoute(items, true, models); err != nil { + return false, nil + } + if strings.Join(items[i].lines, "\n") == before { + return false, nil + } + if now, err := edit.Read(f); err != nil || !bytes.Equal(now, raw) { + return false, nil + } + return true, dshWrite(f, head, items) +} + +// dshWiredEvery is how often a magpie serving the gateway looks at dsh's +// patch lists. +const dshWiredEvery = 30 * time.Second + +// KeepDshWired keeps magpie's route in dsh's patch lists as magpie's catalog +// is now, for as long as magpie serves the gateway. dsh reads a patch list +// live, so one left behind by something else writing the file — dsh's own +// Models page, an older magpie — fails every session there with no such +// configured model until the route is written again. What is written is +// magpie's own list, never the model a session starts on. +func KeepDshWired(ctx context.Context) { + keepDshWired(ctx, dshWiredEvery) +} + +// keepDshWired is KeepDshWired at an interval the tests can shorten. One +// round at a time, each after the one before it has finished, and a round +// that could not write something is said once rather than every round. +func keepDshWired(ctx context.Context, every time.Duration) { + var said dshSaidOnce + for { + if trouble := dshWiredOnce(); said.first(trouble) { + log.Print(trouble) + } + select { + case <-ctx.Done(): + return + case <-time.After(every): + } + } +} + +// dshSaidOnce is what a round could not write, as it was last said: a round +// repeating it says nothing, so a profile magpie cannot write to is reported +// once rather than every 30s. +type dshSaidOnce struct{ last string } + +// first reports whether this trouble has not been said yet, and is to be said. +func (s *dshSaidOnce) first(trouble string) bool { + if trouble == s.last { + return false + } + s.last = trouble + return trouble != "" +} + +// dshWiredOnce writes magpie's route again in every patch list whose route +// is not what magpie would write now, and says what could not be written. +func dshWiredOnce() string { + dshWrites.Lock() + defer dshWrites.Unlock() + dir := dshHome() + if dir == "" { + return "" + } + var trouble []string + models := magpieModels("dsh") + for _, f := range dshProfiles(dir) { + written, err := dshRouteAgain(f, models) + if err != nil { + trouble = append(trouble, fmt.Sprintf("writing dsh's route again in %s: %s", f, dshWriteError(err))) + continue + } + if written { + log.Printf("wrote dsh's route again in %s", f) + } + } + return strings.Join(trouble, "; ") +} + +// dshWriteError is why a write failed, without the name of the temporary file +// the atomic write makes: that name is new every attempt, and a trouble that +// reads differently every round would be said every round (see dshSaidOnce). +func dshWriteError(err error) string { + var pe *os.PathError + if errors.As(err, &pe) { + return pe.Op + ": " + pe.Err.Error() + } + return err.Error() +} + +// dshHome is where dsh keeps its profiles: $DSH_HOME, or ~/.dsh. +func dshHome() string { + if dir := os.Getenv("DSH_HOME"); dir != "" { + return dir + } + home, err := os.UserHomeDir() + if err != nil { + return "" + } + return filepath.Join(home, ".dsh") } // dshMove moves a profile magpie wired by taking over dsh's DeepSeek row // onto magpie's route, the model and effort kept. -func dshMove(f string, items []dshItem) error { +func dshMove(f string, items []dshItem, models []catalog.Model) error { model := "" if i := dshFindLast(items, "agent-default-model"); i >= 0 { if c := dshConfig(items[i]); c["provider"] == "deepseek-official" { @@ -985,11 +1124,11 @@ func dshMove(f string, items []dshItem) error { } return dshWrite(f, head, items) } - return dshSetFile(f, magpieID+"/"+model, true) + return dshSetFile(f, magpieID+"/"+model, true, models) } // dshSyncLegacy is dshSync on a config.yaml before 0.1.5. -func dshSyncLegacy(f string) error { +func dshSyncLegacy(f string, models []catalog.Model) error { head, items, err := dshRead(f) if err != nil { return nil @@ -998,7 +1137,10 @@ func dshSyncLegacy(f string) error { if i < 0 || !items[i].magpie { return nil } - lines := dshProviderLines(dshEffortIn(items)) + if len(models) == 0 { + return nil + } + lines := dshProviderLines(dshEffortIn(items), models) if strings.Join(lines, "\n") == strings.Join(items[i].lines, "\n") { return nil } @@ -1010,7 +1152,10 @@ func dshSyncLegacy(f string) error { // desktop app's, opened for the first time after the web's was wired — // magpie's route, and the model magpie set in the others when it starts on // none of the user's: until then it lists dsh's own models alone. -func dshFillNewProfiles(files []string) error { +func dshFillNewProfiles(files []string, models []catalog.Model) error { + if len(models) == 0 { + return nil + } model := "" var bare []string for _, f := range files { @@ -1037,13 +1182,13 @@ func dshFillNewProfiles(files []string) error { continue } if i := dshFind(items, "agent-default-model"); i < 0 || dshOurs(items[i]) { - if err := dshSetFile(f, magpieID+"/"+model, true); err != nil { + if err := dshSetFile(f, magpieID+"/"+model, true, models); err != nil { return err } continue } // a model of the user's: magpie's are listed beside it - if items, err = dshPutRoute(items, true); err != nil { + if items, err = dshPutRoute(items, true, models); err != nil { continue } if err := dshWrite(f, head, items); err != nil { @@ -1118,6 +1263,8 @@ func dshGetEffort(dir string) string { // agent-default-model (0.1.5 on), or into magpie's llm-deepseek entry // before, dsh's own row being used whole when there is none. func dshSetEffort(dir, v string) error { + dshWrites.Lock() + defer dshWrites.Unlock() files := dshProfiles(dir) if len(files) > 0 { model := dshGet(dir) @@ -1177,7 +1324,11 @@ func dshSetEffort(dir, v string) error { head, items, err := dshRead(f) if err == nil { if i := dshFind(items, "llm-deepseek"); i >= 0 && items[i].magpie { - items[i].lines = dshProviderLines(v) + models := magpieModels("dsh") + if len(models) == 0 { + return fmt.Errorf("DeepSeek Harness has no models to write: magpie has none to hand it") + } + items[i].lines = dshProviderLines(v, models) return dshWrite(f, head, items) } } diff --git a/internal/agent/dsh_route_test.go b/internal/agent/dsh_route_test.go index 28f574427..f4353aa49 100644 --- a/internal/agent/dsh_route_test.go +++ b/internal/agent/dsh_route_test.go @@ -1,10 +1,12 @@ package agent import ( + "context" "os" "path/filepath" "strings" "testing" + "time" "github.com/yetone/magpie/internal/provider" ) @@ -260,3 +262,244 @@ func TestDshCheckSaysWhenTheModelItStartsOnIsOneMagpieNoLongerGives(t *testing.T t.Fatal("a sync that cannot list the model it starts on says nothing") } } + +// dshRouteFixture is magpie's route listing those models, as dsh's Models +// page would write it. +func dshRouteFixture(ids ...string) string { + s := "- id: llm-pi-ai\n name: \"@deepseek-ai/dsh-llm-pi-ai\"\n config:\n providers:\n" + + " magpie:\n displayName: Magpie\n apiKeyEnv: " + dshKeyRef + "\n api: openai-completions\n baseURL: " + gatewayV1() + "\n models:\n" + for _, id := range ids { + s += " - id: " + id + "\n name: " + id + " · DeepSeek\n" + } + return s +} + +// dsh reads the patch list live, so a route left behind while magpie runs — +// by dsh's own Models page, an older magpie — fails every session there with +// no such configured model until it is written again. It is written again +// while magpie serves, and the model a session starts on stays the user's. +func TestDshRouteIsWrittenAgainWhileServing(t *testing.T) { + home, dir, web := dshRouteHome(t) + os.WriteFile(filepath.Join(dir, ".env"), []byte(dshKeyRef+"=magpie\n"), 0o600) + os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"+ + dshRouteFixture("deepseek/pro")+ + "- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/flash\n"), 0o644) + a := dsh(home) + if d := a.Check(); d == "" { + t.Fatal("a route without the model it starts on is not named") + } + dshWiredOnce() + b, _ := os.ReadFile(web) + s := string(b) + if !strings.Contains(s, "deepseek/pro") || !strings.Contains(s, "deepseek/flash") { + t.Fatalf("the route is not what magpie writes:\n%s", s) + } + if !strings.Contains(s, "provider: magpie\n model: deepseek/flash") { + t.Fatalf("the model it starts on is not the user's still:\n%s", s) + } + if d := a.Check(); d != "" { + t.Fatalf("after writing the route again: %s", d) + } + // what is already what magpie writes is not written again + dshWiredOnce() + if again, _ := os.ReadFile(web); string(again) != s { + t.Fatalf("the same route written again:\n%s", again) + } +} + +// The loop is what runs while magpie serves: a patch list changed under it +// is written again on the next round, not only at the next start. +func TestKeepDshWiredWritesTheRouteAgain(t *testing.T) { + home, dir, web := dshRouteHome(t) + os.WriteFile(filepath.Join(dir, ".env"), []byte(dshKeyRef+"=magpie\n"), 0o600) + os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"+ + dshRouteFixture("deepseek/pro", "deepseek/flash")+ + "- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/flash\n"), 0o644) + a := dsh(home) + if d := a.Check(); d != "" { + t.Fatalf("the route magpie writes is not clean: %s", d) + } + ctx, stop := context.WithCancel(context.Background()) + done := make(chan struct{}) + t.Cleanup(func() { stop(); <-done }) + go func() { defer close(done); keepDshWired(ctx, 10*time.Millisecond) }() + time.Sleep(100 * time.Millisecond) // a round or two with the route already right + // something else writes the file while magpie serves + os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"+ + dshRouteFixture("deepseek/pro")+ + "- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/flash\n"), 0o644) + if d := a.Check(); d == "" { + t.Fatal("the route changed under magpie is not named") + } + deadline := time.Now().Add(5 * time.Second) + for a.Check() != "" { + if time.Now().After(deadline) { + t.Fatal("the route was not written again while magpie served") + } + time.Sleep(5 * time.Millisecond) + } + if b, _ := os.ReadFile(web); !strings.Contains(string(b), "deepseek/flash") { + t.Fatalf("the route written again:\n%s", b) + } +} + +// A patch list without magpie's route is the user's: writing the route again +// does not put it back. +func TestDshRouteAgainLeavesAListWithoutMagpieAlone(t *testing.T) { + _, _, web := dshRouteHome(t) + mine := "# Your patch layer for this dsh profile.\n- id: mine\n config:\n model: m\n" + os.WriteFile(web, []byte(mine), 0o644) + dshWiredOnce() + if b, _ := os.ReadFile(web); string(b) != mine { + t.Fatalf("a list without magpie's route:\n%s", b) + } +} + +// A route is written from the catalog: with no providers there is no list to +// write, and an empty one would be worse than the route left as it is. +func TestDshRouteAgainLeavesTheRouteWithNoCatalog(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("DSH_HOME", "") + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if n := len(magpieModels("dsh")); n != 0 { + t.Fatalf("a catalog to write from: %d models", n) + } + stale := "# Your patch layer for this dsh profile.\n" + + dshRouteFixture("deepseek/pro") + + "- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/flash\n" + web := filepath.Join(home, ".dsh", "profiles", "web", "cordis.patch.yml") + os.MkdirAll(filepath.Dir(web), 0o755) + os.WriteFile(web, []byte(stale), 0o644) + if _, err := dshRouteAgain(web, magpieModels("dsh")); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(web); string(b) != stale { + t.Fatalf("a route written with no catalog:\n%s", b) + } + if err := dshSync(filepath.Join(home, ".dsh")); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(web); string(b) != stale { + t.Fatalf("the sync wrote a route with no catalog:\n%s", b) + } + dshWiredOnce() + if b, _ := os.ReadFile(web); string(b) != stale { + t.Fatalf("a route written with no catalog:\n%s", b) + } +} + +// dsh's own writers keep a patch list in flow style (#445). A route that is +// what magpie writes is read out of it as the same list; whatever the round +// writes, the round after it writes nothing: a list that came back different +// every time would be written again every 30 seconds. +func TestDshRouteAgainSettlesOnAFlowList(t *testing.T) { + home, dir, web := dshRouteHome(t) + os.WriteFile(filepath.Join(dir, ".env"), []byte(dshKeyRef+"=magpie\n"), 0o600) + os.WriteFile(web, []byte("# Your patch layer for this dsh profile\n# a top-level YAML array\n"+ + "[ { id: llm-pi-ai, name: \"@deepseek-ai/dsh-llm-pi-ai\", config: { providers: { magpie: { displayName: Magpie, apiKeyEnv: "+ + dshKeyRef+", api: openai-completions, baseURL: "+gatewayV1()+ + ", models: [ { id: deepseek/pro, name: pro }, { id: deepseek/flash, name: flash } ] } } } }, { id: agent-default-model, config: { provider: magpie, model: deepseek/flash } } ]\n"), 0o644) + a := dsh(home) + if d := a.Check(); d != "" { + t.Fatalf("a route magpie writes, kept in flow style: %s", d) + } + dshWiredOnce() + first, _ := os.ReadFile(web) + if !strings.Contains(string(first), "deepseek/pro") || !strings.Contains(string(first), "deepseek/flash") { + t.Fatalf("the route read out of a flow list:\n%s", first) + } + dshWiredOnce() + if second, _ := os.ReadFile(web); string(second) != string(first) { + t.Fatalf("a flow list written again and again:\n%s", second) + } +} + +// A profile dsh made after magpie wired the others is filled with the route +// and the model they start on. With no catalog there is nothing to fill it +// with: a list of no models, and a default pointing at one, is what a session +// there fails on. A route written again never reaches this profile. +func TestDshFillNewProfilesLeavesABareProfileWithNoCatalog(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("DSH_HOME", "") + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if n := len(magpieModels("dsh")); n != 0 { + t.Fatalf("a catalog to write from: %d models", n) + } + dir := filepath.Join(home, ".dsh") + web := filepath.Join(dir, "profiles", "web", "cordis.patch.yml") + desktop := filepath.Join(dir, "profiles", "desktop", "cordis.patch.yml") + for _, f := range []string{web, desktop} { + os.MkdirAll(filepath.Dir(f), 0o755) + } + os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"+ + dshRouteFixture("deepseek/pro")+ + "- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/pro\n"), 0o644) + bare := "# A new profile.\n[]\n" + os.WriteFile(desktop, []byte(bare), 0o644) + if err := dshSync(dir); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(desktop); string(b) != bare { + t.Fatalf("a new profile filled with no catalog:\n%s", b) + } +} + +// The other way round: with a catalog the new profile is filled as before. +func TestDshFillNewProfilesFillsABareProfile(t *testing.T) { + home, dir, web := dshRouteHome(t) + desktop := filepath.Join(dir, "profiles", "desktop", "cordis.patch.yml") + os.MkdirAll(filepath.Dir(desktop), 0o755) + os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"+ + dshRouteFixture("deepseek/pro", "deepseek/flash")+ + "- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/flash\n"), 0o644) + os.WriteFile(desktop, []byte("# A new profile.\n[]\n"), 0o644) + if err := dshSync(dir); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(desktop) + for _, want := range []string{"id: llm-pi-ai", "displayName: Magpie", " magpie:", "provider: magpie", "id: deepseek/pro"} { + if !strings.Contains(string(b), want) { + t.Fatalf("a new profile not filled with %q:\n%s", want, b) + } + } + if d := dsh(home).Check(); d != "" { + t.Fatalf("check: %s", d) + } +} + +func TestDshWriteErrorReadsTheSameEveryRound(t *testing.T) { + one := dshWriteError(&os.PathError{Op: "open", Path: "/x/.cordis.patch.yml.4236419057.tmp", Err: os.ErrPermission}) + two := dshWriteError(&os.PathError{Op: "open", Path: "/x/.cordis.patch.yml.3958428140.tmp", Err: os.ErrPermission}) + if one != two { + t.Fatalf("the same trouble reads two ways: %q and %q", one, two) + } + if strings.Contains(one, ".tmp") { + t.Fatalf("what is said carries the temporary name: %q", one) + } + if !strings.Contains(one, "permission denied") { + t.Fatalf("what is said does not say why: %q", one) + } +} + +func TestDshSaidOnceSaysATroubleOnce(t *testing.T) { + var said dshSaidOnce + const trouble = "writing dsh's route again in /x: open: permission denied" + if !said.first(trouble) { + t.Fatal("the first round said nothing") + } + if said.first(trouble) { + t.Fatal("the same trouble was said again") + } + if said.first("") { + t.Fatal("a quiet round said something") + } + if !said.first(trouble) { + t.Fatal("trouble after a quiet round was not said") + } +} diff --git a/internal/agent/dsh_test.go b/internal/agent/dsh_test.go index 9ebc47208..4a2df7e2c 100644 --- a/internal/agent/dsh_test.go +++ b/internal/agent/dsh_test.go @@ -190,7 +190,7 @@ func TestDshModelLimits(t *testing.T) { }); err != nil { t.Fatal(err) } - b, _ := yaml.Marshal(dshRouteConfig()) + b, _ := yaml.Marshal(dshRouteConfig(magpieModels("dsh"))) s := string(b) want := ` - id: v/see name: see · V @@ -259,3 +259,64 @@ func TestDshProfileMadeLater(t *testing.T) { t.Fatalf("after the sync: %s", d) } } + +// A dsh before 0.1.5 keeps its endpoint in config.yaml. With no catalog there +// is nothing to write into that entry, so the effort change is refused rather +// than blanking the models magpie put there. +func TestDshSetEffortLeavesALegacyEntryWithNoCatalogAlone(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("DSH_HOME", "") + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if n := len(magpieModels("dsh")); n != 0 { + t.Fatalf("a catalog to write from: %d models", n) + } + dir := filepath.Join(home, ".dsh") + path := filepath.Join(dir, "config.yaml") + own := "# mine\n- id: llm-deepseek # magpie\n config:\n models:\n - id: \"deepseek/pro\"\n" + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(own), 0o644); err != nil { + t.Fatal(err) + } + if err := dshSetEffort(dir, "high"); err == nil { + t.Fatal("an empty catalog should refuse the write") + } + if b, _ := os.ReadFile(path); string(b) != own { + t.Fatalf("the file changed:\n%s", b) + } +} + +// With a catalog the legacy entry is rewritten as before. +func TestDshSetEffortWritesALegacyEntryWithTheCatalog(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("DSH_HOME", "") + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil { + t.Fatal(err) + } + dir := filepath.Join(home, ".dsh") + path := filepath.Join(dir, "config.yaml") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("# mine\n- id: llm-deepseek # magpie\n config:\n models:\n - id: \"deepseek/pro\"\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := dshSetEffort(dir, "high"); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + s := string(b) + for _, want := range []string{"# mine", "- id: llm-deepseek # magpie", "reasoningEffort: high", `- id: "deepseek/pro"`, `- id: "deepseek/flash"`} { + if !strings.Contains(s, want) { + t.Fatalf("missing %q in\n%s", want, s) + } + } +} diff --git a/internal/agent/sync_test.go b/internal/agent/sync_test.go index c44173f15..a26d21ece 100644 --- a/internal/agent/sync_test.go +++ b/internal/agent/sync_test.go @@ -143,7 +143,7 @@ func TestMaxTokensWithinContextWindow(t *testing.T) { pi, _ := json.Marshal(magpieProviderJSON("pi")) cline, _ := json.Marshal(clineModels("")) omp, _ := yaml.Marshal(ompProvider()) - dshRoute, _ := yaml.Marshal(dshRouteConfig()) + dshRoute, _ := yaml.Marshal(dshRouteConfig(magpieModels("dsh"))) droid, _ := json.Marshal(droidEntries()) qoder, _ := json.Marshal(qoderProvider("qoder", "")) hanako, _ := json.Marshal(hanakoProvider()) diff --git a/main.go b/main.go index 4ab4b1327..f936b7886 100644 --- a/main.go +++ b/main.go @@ -153,6 +153,10 @@ func run(args []string) error { gateway.StandIn = agent.StandIn // the setup kept the same on every computer, by whichever serves gateway.WhileServing = append(gateway.WhileServing, davsync.Run) + // and dsh's patch lists, which dsh reads live: a route left behind by + // something else writing the file fails every session there until + // magpie writes its own list again + gateway.WhileServing = append(gateway.WhileServing, agent.KeepDshWired) // and the request archive, when it is on, goes to the bucket sync is to gateway.ArchiveBucket = func() (gateway.Putter, bool) { if b, ok := davsync.S3Bucket(); ok {