diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 87dac9632..fd6f145f5 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -106,6 +106,18 @@ type Agent struct { // environment (agy), is the command that starts it on magpie, while // it is on one of magpie's models; "" otherwise. Launch func() string + // SplitSuffix, for an agent whose model values carry something of its + // own after the model that varies from value to value (omp's thinking + // level, "…:max"), splits a value into the model the picker offers and + // that suffix, "" when there is none. What matches a value against the + // picker (drift, Reseat, RenameProvider, Spell) matches the model and + // puts the suffix back after the one it moves to. A mark that is always + // the same for a model (Claude Code's [1m]) rides on the option instead. + // one is false for a value that is no one model but a list the agent + // falls back through (omp's "a,b"): that is the user's own whatever it + // names, never taken for one of magpie's models nor moved by what + // matches the picker (RenameRefs moves the names in it). + SplitSuffix func(v string) (model, suffix string, one bool) // detect, when set, says whether the agent is here in place of looking // for its files and binary: a distro's, probed once. detect func() bool @@ -275,19 +287,25 @@ func ids(as []*Agent) []string { // in others, and either is taken in both. A value the picker offers as is // stays, and so does one it doesn't know (a model the agent reaches on its // own that isn't listed); a "magpie/…" value the catalog doesn't have is an -// error rather than a model the agent would ask its own vendor for. +// error rather than a model the agent would ask its own vendor for. The +// agent's suffix after the model (SplitSuffix) stays as typed, and so does +// a list of models, the user's own. func (a *Agent) Spell(key, v string) (string, error) { f := a.Field(key) if f == nil || f.Options == nil || v == "" { return v, nil } + model, suffix, one := a.split(v) + if !one { + return v, nil + } opts := f.Options(a.Values()) for _, o := range opts { - if o.Value == v { + if o.Value == model { return v, nil } } - ref, prefixed := strings.CutPrefix(v, magpieID+"/") + ref, prefixed := strings.CutPrefix(model, magpieID+"/") // a provider renamed since (a profile saved before) is the same one refs := []string{ref} if r := provider.RenamedRef(ref); r != ref { @@ -296,7 +314,7 @@ func (a *Agent) Spell(key, v string) (string, error) { for _, r := range refs { for _, o := range opts { if o.Ref != "" && o.Ref == r { - return o.Value, nil + return o.Value + suffix, nil } } } @@ -306,6 +324,16 @@ func (a *Agent) Spell(key, v string) (string, error) { return v, nil } +// split is v as the model the picker offers and the agent's suffix after +// it (SplitSuffix), one false for a list of models; the whole of v for an +// agent without one. +func (a *Agent) split(v string) (model, suffix string, one bool) { + if a.SplitSuffix == nil { + return v, "", true + } + return a.SplitSuffix(v) +} + // atomic makes each of an agent's field sets, and its Sync, one edit of the // files at paths: one that fails part way puts them all back as they were, // rather than leaving, say, Codex's config.toml with magpie's provider table diff --git a/internal/agent/applied.go b/internal/agent/applied.go index a081d73c2..c1ead7f29 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -193,11 +193,17 @@ func bypassed(used, applied, seen time.Time) bool { time.Since(used) > grace && seen.Before(used.Add(-2*time.Second)) } -// magpieValue: the value is one of magpie's models as this agent spells it. +// magpieValue: the value is one of magpie's models as this agent spells it, +// its suffix after the model (SplitSuffix) aside; a list of models is the +// user's own. func magpieValue(a *Agent, f Field, v string, vals map[string]string) bool { if v == "" { return false } + v, _, one := a.split(v) + if !one { + return false + } if isMagpie(v) { return true } diff --git a/internal/agent/omp.go b/internal/agent/omp.go index af9b22cda..f95f0208d 100644 --- a/internal/agent/omp.go +++ b/internal/agent/omp.go @@ -25,10 +25,13 @@ import ( var ompEfforts = []string{"minimal", "low", "medium", "high", "xhigh", "max"} // ompRefKeys are where omp's config names models: each role (a list to try -// in order, "a,b" or a sequence), the retry fallback chains (model keys and -// their entries), the models it cycles through (enabledModels, also scoped -// to paths) and the models of task agents. An entry may end in a thinking -// level ("magpie/deepseek/pro:max"). +// in order, "a,b" or a sequence), the retry fallback chains (a list of +// models under each key; the key is a role's name, the only kind omp 16 +// takes (agent-session.ts), or from omp 18 a model selector as well +// (retry-fallback-chains.ts) — a role's name read with them is no model of +// magpie's and is passed over), the models it cycles through (enabledModels, +// also scoped to paths) and the models of task agents. An entry may end in a +// thinking level ("magpie/deepseek/pro:max"). var ompRefKeys = []string{"modelRoles", "retry.fallbackChains", "enabledModels", "task.agentModelOverrides"} // ompRefs calls fn on each model of a value under ompRefKeys, the spaces @@ -42,6 +45,42 @@ func ompRefs(v string, fn func(string) string) string { return strings.Join(parts, ",") } +// ompLevel splits a role's model from the thinking level omp reads off its +// end, "provider/model:level" (model-resolver.ts), the level returned with +// its colon: one of the efforts, off, or auto, omp's own pick each turn. +// Anything else after a colon is part of the model id (ollama's qwen3:8b), +// and a list of models omp falls back through ("a,b:high") has no level of +// its own, each of its models its own. +func ompLevel(v string) (model, level string) { + if i := strings.LastIndexByte(v, ':'); i > 0 && !strings.Contains(v, ",") { + if l := v[i+1:]; l == "off" || l == "auto" || slices.Contains(ompEfforts, l) { + return v[:i], v[i:] + } + } + return v, "" +} + +// ompSplit is omp's SplitSuffix: a role's model and its thinking level +// (ompLevel), one false for a list of models omp falls back through ("a,b", +// or a YAML list, read as one), which is the user's own whatever it names. +func ompSplit(v string) (model, level string, one bool) { + if strings.Contains(v, ",") { + return v, "", false + } + model, level = ompLevel(v) + return model, level, true +} + +// ompOnMagpie: a role's value is one of magpie's models, at a level or not. +func ompOnMagpie(v string) bool { + _, _, one := ompSplit(v) + return one && usesMagpie(v) +} + +// ompYAMLList: a value the stash keeps is a list as the YAML it was written +// in ("[a, b]", "- a"), which no model reads as. +func ompYAMLList(v string) bool { return strings.HasPrefix(v, "[") || strings.HasPrefix(v, "- ") } + // ompProfileName is a profile name omp takes (pi-utils dirs.ts, // normalizeProfileName); it refuses any other. var ompProfileName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) @@ -82,17 +121,26 @@ func omp(home string) *Agent { return yml } path := pick("config") - get := func() string { v, _ := edit.GetYAML(path, "modelRoles.default"); return v } - dropMagpie := func() error { - // another role, a fallback chain, … may still go through magpie - used := false - if err := edit.EditYAMLStrings(path, ompRefKeys, func(v string) string { + roleGet := func(name string) func() string { + return func() string { + k := "modelRoles." + name + if v, ok := edit.GetYAML(path, k); ok { + return v + } + // a YAML list of models omp falls back through reads as the + // comma-separated string it takes for one too: what the stash + // keeps, and a reset writes back + return strings.Join(edit.GetYAMLList(path, k), ",") + } + } + // onMagpie: a role, a fallback chain, … (ompRefKeys) still names one of + // magpie's models + onMagpie := func() (used bool, err error) { + err = edit.EditYAMLStrings(path, ompRefKeys, func(v string) string { ompRefs(v, func(m string) string { used = used || usesMagpie(m); return m }) return v - }); err != nil || used { - return err - } - return edit.DelYAML(pick("models"), "providers."+magpieID) + }) + return used, err } writeMagpie := func() error { models := pick("models") @@ -105,28 +153,151 @@ func omp(home string) *Agent { } return edit.SetYAML(models, edit.KV{Path: "providers." + magpieID, Value: ompProvider()}) } + // dropMagpie takes magpie's provider out of models.yml once nothing in + // the config is on magpie; while something is (a fallback chain, another + // role), it writes it afresh instead, so a role set off magpie — applying + // again what Check found — mends the wiring that is left. + dropMagpie := func() error { + used, err := onMagpie() + switch { + case err != nil: + return err + case used: + return writeMagpie() + } + return edit.DelYAML(pick("models"), "providers."+magpieID) + } + // was are the stash's keys for the roles, one each + var was []string + // role is the field for one of omp's model roles: one of magpie's brings + // magpie's provider into models.yml, and it goes once nothing is on it. + // What the user had there before magpie took the role over is stashed, + // and resetting the role puts it back: a list of models as the YAML it + // was written in, a flow list flow and a block one block. + role := func(key, label, name string, quiet bool) Field { + k := "modelRoles." + name + get := roleGet(name) + w := "omp:" + path + ":" + k + was = append(was, w) + kept := func() string { + if v, ok := edit.GetYAML(path, k); ok { + return v + } + v, _ := edit.GetYAMLText(path, k) + return v + } + return Field{ + Key: key, Label: label, Quiet: quiet, + Get: get, + Set: func(v string) error { + cur := get() + if v == "" { + if ompOnMagpie(cur) { + v = unstash(w) + } + if v == "" { + if err := edit.DelYAML(path, k); err != nil { + return err + } + return dropMagpie() + } + if ompYAMLList(v) { + if err := edit.SetYAML(path, edit.KV{Path: k, Value: edit.YAMLText(v)}); err != nil { + return err + } + return dropMagpie() + } + } else if _, level, one := ompSplit(v); one && level == "" { + // another model keeps the role's thinking level; omp + // clamps one the model lacks to the highest it has below + // it (its lowest when none is) and drops it for a model + // that doesn't reason (pi-catalog model-thinking.ts), + // never fails. + // The same model picked without one is the way to have + // none: its option with the level beside it keeps it + if model, level := ompLevel(cur); level != "" && model != v { + v += level + } + } + model, _, one := ompSplit(v) + if ref, ok := strings.CutPrefix(model, magpieID+"/"); one && ok && isMagpie(ref) { + if !ompOnMagpie(cur) { + stash(map[string]string{w: kept()}) + } + if err := writeMagpie(); err != nil { + return err + } + return edit.SetYAML(path, edit.KV{Path: k, Value: v}) + } + forget(w) + if err := edit.SetYAML(path, edit.KV{Path: k, Value: v}); err != nil { + return err + } + return dropMagpie() + }, + Options: func(cur map[string]string) []Option { + opts := append(ownOptions("", cur[key]), viaMagpie("omp", magpieID+"/")...) + // a catalog model with a thinking level is offered as it + // reads, beside the model: that keeps the level, the model + // alone clears it + if model, level := ompLevel(cur[key]); level != "" { + if i := slices.IndexFunc(opts, func(o Option) bool { return o.Ref != "" && o.Value == model }); i >= 0 { + o := opts[i] + o.Value, o.Label = cur[key], o.Label+" · "+level[1:] + opts = slices.Insert(opts, i+1, o) + } + } + return opts + }, + } + } return &Agent{ ID: "omp", Name: "omp", Icon: "omp", Aliases: []string{"oh-my-pi"}, UA: []string{"oh-my-pi"}, Bin: "omp", Dir: dir, Path: path, + // a role's thinking level is omp's, after whichever model it is on; + // a list of models is the user's own + SplitSuffix: ompSplit, Sync: func() error { return syncYAML(pick("models"), "providers."+magpieID, func() any { return ompProvider() }) }, // a provider renamed takes its models' ids in models.yml with it; a - // name left on the old one omp would pass over, with a warning + // name left on the old one omp would pass over, with a warning. So + // does what a role had before magpie (a list may name magpie's + // models), which a reset puts back RenameRefs: func(from, to string) (bool, error) { old, now := magpieID+"/"+from+"/", magpieID+"/"+to+"/" - moved := false - err := edit.EditYAMLStrings(path, ompRefKeys, func(v string) string { + move := func(v string) string { return ompRefs(v, func(m string) string { if rest, ok := strings.CutPrefix(m, old); ok { - moved = true return now + rest } return m }) - }) - return moved, err + } + moved := false + if err := edit.EditYAMLStrings(path, ompRefKeys, func(v string) string { + nv := move(v) + moved = moved || nv != v + return nv + }); err != nil { + return moved, err + } + for _, w := range was { + s := stashLoad()[w] + ns := move(s) + if ompYAMLList(s) { + t, err := edit.EditYAMLTextStrings(edit.YAMLText(s), move) + if err != nil { + return moved, err + } + ns = string(t) + } + if ns != s { + stash(map[string]string{w: ns}) + } + } + return moved, nil }, Notice: func() string { if Running(`(^|/)omp( |$)`, `@oh-my-pi/pi-coding-agent`) { @@ -135,53 +306,45 @@ func omp(home string) *Agent { return "" }, Check: func() string { - if !usesMagpie(get()) { + // whatever keeps magpie's provider in models.yml has its wiring + // checked, a fallback chain alone as much as a role + if used, _ := onMagpie(); !used { return "" } models := pick("models") return wiringOff("omp", models, func(k string) (string, bool) { return edit.GetYAML(models, "providers."+magpieID+"."+k) }, "baseUrl", gatewayV1()) }, - Fields: []Field{{ - Key: "model", Label: "model", - Get: get, - Set: func(v string) error { - if v == "" { - if err := edit.DelYAML(path, "modelRoles.default"); err != nil { - return err + Fields: []Field{ + role("model", "model", "default", false), + // omp's own agents run on its roles (src/task/agents.ts, + // prompts/agents): task on @task; scout and sonic on @smol; + // reviewer on @slow, also the eval tool's "slow" tier. Unset, + // task gives its agent the parent session's model, and smol + // and slow take the default role's (model-resolver.ts, + // shouldInheritDefaultBeforePriority). The designer role went + // in omp 18.1.5. smol is labelled as omp names it: "small" is + // other agents' picker of its own + role("subagent", "subagents", "task", true), + role("small", "smol", "smol", true), + role("slow", "slow", "slow", true), + { + // the thinking level sessions start with, as omp's settings save + // it; unset omp takes high. auto has omp pick a level each turn: + // not a level a model lists, so it is offered here and kept out of + // ompEfforts, which a model's thinking levels are filtered by. First, + // as omp's own picker has it (16.3.5 and 18.4.4 alike) + Key: "effort", Label: "thinking", + Get: func() string { v, _ := edit.GetYAML(path, "defaultThinkingLevel"); return v }, + Set: func(v string) error { + if v == "" { + return edit.DelYAML(path, "defaultThinkingLevel") } - return dropMagpie() - } - if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { - if err := writeMagpie(); err != nil { - return err - } - return edit.SetYAML(path, edit.KV{Path: "modelRoles.default", Value: v}) - } - if err := edit.SetYAML(path, edit.KV{Path: "modelRoles.default", Value: v}); err != nil { - return err - } - return dropMagpie() + return edit.SetYAML(path, edit.KV{Path: "defaultThinkingLevel", Value: v}) + }, + Options: func(map[string]string) []Option { return static(append([]string{"auto"}, ompEfforts...)...) }, }, - Options: func(cur map[string]string) []Option { - return append(ownOptions("", cur["model"]), viaMagpie("omp", magpieID+"/")...) - }, - }, { - // the thinking level sessions start with, as omp's settings save - // it; unset omp takes high. auto has omp pick a level each turn: - // not a level a model lists, so it is offered here and kept out of - // ompEfforts, which a model's thinking levels are filtered by. First, - // as omp's own picker has it (16.3.5 and 18.4.4 alike) - Key: "effort", Label: "thinking", - Get: func() string { v, _ := edit.GetYAML(path, "defaultThinkingLevel"); return v }, - Set: func(v string) error { - if v == "" { - return edit.DelYAML(path, "defaultThinkingLevel") - } - return edit.SetYAML(path, edit.KV{Path: "defaultThinkingLevel", Value: v}) - }, - Options: func(map[string]string) []Option { return static(append([]string{"auto"}, ompEfforts...)...) }, - }}, + }, } } diff --git a/internal/agent/omp_test.go b/internal/agent/omp_test.go index 29ffc07e8..30adc17c5 100644 --- a/internal/agent/omp_test.go +++ b/internal/agent/omp_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/usage" "gopkg.in/yaml.v3" @@ -74,7 +75,8 @@ func TestOmp(t *testing.T) { t.Fatalf("own: %v %v", c, m) } - // another role through magpie keeps it in models.yml + // another role through magpie keeps it in models.yml; the reset puts + // back the model default had before magpie took it over f.Set("magpie/deepseek/flash") os.WriteFile(configPath, []byte("modelRoles:\n default: magpie/deepseek/flash\n smol: magpie/deepseek/pro\n"), 0o644) if err := f.Set(""); err != nil { @@ -82,11 +84,11 @@ func TestOmp(t *testing.T) { } c, _ = read(configPath) m, _ = read(modelsPath) - if roles(c)["default"] != nil || roles(c)["smol"] != "magpie/deepseek/pro" || providers(m)["magpie"] == nil { + if roles(c)["default"] != "moonshotai/kimi-k3" || roles(c)["smol"] != "magpie/deepseek/pro" || providers(m)["magpie"] == nil { t.Fatalf("reset with smol: %v %v", c, m) } - // reset: only default goes, and magpie with it + // reset with nothing stashed: only default goes, and magpie with it os.WriteFile(configPath, []byte("theme: dark\nmodelRoles:\n default: magpie/deepseek/flash\n smol: openai/gpt-6-mini\n"), 0o644) if err := f.Set(""); err != nil { t.Fatal(err) @@ -228,3 +230,377 @@ func TestOmpNamedToTheGateway(t *testing.T) { t.Fatal("Bun's own User-Agent is taken for omp's, so the header proves nothing") } } + +// omp's own agents pick their models apart from the main one: through +// magpie on its own, a role brings magpie's provider in, has its wiring +// checked, and takes the provider out again when it is the last. +func TestOmpRoles(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + 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, ".omp", "agent") + configPath, modelsPath := filepath.Join(dir, "config.yml"), filepath.Join(dir, "models.yml") + os.MkdirAll(dir, 0o755) + os.WriteFile(configPath, []byte("modelRoles:\n default: anthropic/claude-opus-5\n"), 0o644) + roles := func() map[string]any { + var c map[string]any + b, _ := os.ReadFile(configPath) + yaml.Unmarshal(b, &c) + r, _ := c["modelRoles"].(map[string]any) + return r + } + magpieIn := func() bool { v, ok := edit.GetYAML(modelsPath, "providers.magpie.baseUrl"); return ok && v != "" } + + a := omp(home) + sub, small := a.Field("subagent"), a.Field("small") + if small.Label != "smol" || a.Field("designer") != nil { + t.Fatalf("small labelled %q; designer: %+v", small.Label, a.Field("designer")) + } + for _, k := range []string{"subagent", "small", "slow"} { + if f := a.Field(k); f == nil || !f.Quiet { + t.Fatalf("field %s: %+v", k, f) + } + } + if err := sub.Set("magpie/deepseek/flash"); err != nil { + t.Fatal(err) + } + if r := roles(); r["task"] != "magpie/deepseek/flash" || r["default"] != "anthropic/claude-opus-5" || !magpieIn() { + t.Fatalf("subagent on magpie: %v, magpie in models.yml: %v", r, magpieIn()) + } + if sub.Get() != "magpie/deepseek/flash" { + t.Fatalf("get: %q", sub.Get()) + } + // the main model isn't magpie's, the subagents' is: its wiring is checked + if a.Check() != "" { + t.Fatalf("check, wired: %q", a.Check()) + } + edit.SetYAML(modelsPath, edit.KV{Path: "providers.magpie.baseUrl", Value: "http://127.0.0.1:1/v1"}) + if a.Check() == "" { + t.Fatal("check missed the subagents' broken wiring") + } + a.Sync() + + if err := small.Set("openai/gpt-6-mini"); err != nil { + t.Fatal(err) + } + if r := roles(); r["smol"] != "openai/gpt-6-mini" || !magpieIn() { + t.Fatalf("small, own: %v", r) + } + // the last role on magpie goes: so does magpie's provider + if err := sub.Set(""); err != nil { + t.Fatal(err) + } + if r := roles(); r["task"] != nil || r["smol"] != "openai/gpt-6-mini" || r["default"] != "anthropic/claude-opus-5" || magpieIn() { + t.Fatalf("subagent reset: %v, magpie in models.yml: %v", r, magpieIn()) + } +} + +// A role's thinking level ("…:max") stays with it when another model is +// picked, and the model the user had before magpie comes back, level and +// all, when the role is reset. +func TestOmpLevels(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("PATH", t.TempDir()) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + for _, p := range []provider.Provider{ + {ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}, + {ID: "other", Name: "Other", Chat: "https://other.example/v1", Key: "k", Models: []string{"pro"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + dir := filepath.Join(home, ".omp", "agent") + configPath := filepath.Join(dir, "config.yml") + os.MkdirAll(dir, 0o755) + os.WriteFile(configPath, []byte("modelRoles:\n default: anthropic/claude-opus-5:max\n slow: openai/gpt-6:auto\n"), 0o644) + a := omp(home) + get := func(k string) string { return a.Field(k).Get() } + apply := func(k, v, want string) { + t.Helper() + if err := a.Apply(k, v); err != nil { + t.Fatal(err) + } + if got := get(k); got != want { + t.Fatalf("%s set to %q: %q, want %q", k, v, got, want) + } + } + + // deepseek/pro has no max of its own: omp clamps it, so it stays + apply("model", "magpie/deepseek/pro", "magpie/deepseek/pro:max") + if d := a.Drift(); d != nil { + t.Fatalf("drift on what magpie set: %+v", d) + } + apply("model", "magpie/deepseek/flash", "magpie/deepseek/flash:max") + apply("model", "magpie/deepseek/pro:low", "magpie/deepseek/pro:low") // its own level wins + // offered at its level beside the model: that keeps the level, the + // model alone clears it + var at, plain bool + for _, o := range a.Field("model").Options(a.Values()) { + at = at || o.Value == "magpie/deepseek/pro:low" && strings.HasSuffix(o.Label, " · low") + plain = plain || o.Value == "magpie/deepseek/pro" + } + if !at || !plain { + t.Fatalf("options: at its level %v, the model %v", at, plain) + } + apply("model", "magpie/deepseek/pro:low", "magpie/deepseek/pro:low") + apply("model", "magpie/deepseek/pro", "magpie/deepseek/pro") + apply("model", "magpie/deepseek/flash", "magpie/deepseek/flash") + apply("model", "magpie/deepseek/pro:low", "magpie/deepseek/pro:low") + apply("slow", "magpie/deepseek/pro", "magpie/deepseek/pro:auto") + + // the first model stashed, not the magpie ones after it + apply("model", "", "anthropic/claude-opus-5:max") + apply("slow", "", "openai/gpt-6:auto") + // a colon that is no level is the model's + apply("model", "ollama/qwen3:8b", "ollama/qwen3:8b:max") + + // a model of the user's own in between is the one put back + apply("model", "magpie/deepseek/pro", "magpie/deepseek/pro:max") + apply("model", "openai/gpt-6", "openai/gpt-6:max") + apply("model", "magpie/deepseek/pro", "magpie/deepseek/pro:max") + apply("model", "", "openai/gpt-6:max") + + // a provider removed moves the role to the same model elsewhere, level + // and all + apply("model", "magpie/deepseek/pro", "magpie/deepseek/pro:max") + if _, err := Reseat(func() error { return provider.Delete("deepseek") }); err != nil { + t.Fatal(err) + } + if got := get("model"); got != "magpie/other/pro:max" { + t.Fatalf("reseated: %q", got) + } +} + +// A role on one of magpie's models with a thinking level is that model +// wherever magpie matches a value against the picker: offered once, typed +// at a level on the command line, missed when omp puts it back to its own, +// and moved, level and all, when its provider is renamed. +func TestOmpLevelSuffix(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("PATH", t.TempDir()) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + 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, ".omp", "agent") + configPath := filepath.Join(dir, "config.yml") + os.MkdirAll(dir, 0o755) + os.WriteFile(configPath, []byte("modelRoles:\n default: anthropic/claude-opus-5:max\n"), 0o644) + a := omp(home) + f := a.Field("model") + + v, err := a.Spell("model", "magpie/deepseek/pro:high") + if err != nil || v != "magpie/deepseek/pro:high" { + t.Fatalf("spell at a level: %q %v", v, err) + } + if err := a.Apply("model", v); err != nil { + t.Fatal(err) + } + // the subagents on the same model at another level: moved with it too + if err := a.Apply("subagent", "magpie/deepseek/pro:max"); err != nil { + t.Fatal(err) + } + if d := a.Drift(); d != nil { + t.Fatalf("drift on what magpie set: %+v", d) + } + // omp's own /model puts the role back on the user's model + edit.SetYAML(configPath, edit.KV{Path: "modelRoles.default", Value: "anthropic/claude-opus-5:high"}) + if d := a.Drift(); d == nil || d.Kind != "replaced" || d.Want != "magpie/deepseek/pro:high" { + t.Fatalf("drift, replaced: %+v", d) + } + if err := a.Reapply(); err != nil || f.Get() != "magpie/deepseek/pro:high" { + t.Fatalf("reapplied: %q %v", f.Get(), err) + } + + if _, err := RenameProvider("deepseek", "ds"); err != nil { + t.Fatal(err) + } + if f.Get() != "magpie/ds/pro:high" || a.Field("subagent").Get() != "magpie/ds/pro:max" { + t.Fatalf("renamed: %q, subagent %q", f.Get(), a.Field("subagent").Get()) + } +} + +// A role omp falls back through, a list of models (a YAML list or the +// comma-separated string omp also takes), is the user's to have back when +// magpie lets go of the role; a level on its last model is no role's level. +func TestOmpRoleList(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + 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, ".omp", "agent") + configPath := filepath.Join(dir, "config.yml") + os.MkdirAll(dir, 0o755) + os.WriteFile(configPath, []byte("modelRoles:\n slow:\n - openai/gpt-6\n - anthropic/claude-opus-5:high\n task: openai/gpt-6,anthropic/claude-opus-5:high\n"), 0o644) + a := omp(home) + for _, k := range []string{"slow", "subagent"} { + if got := a.Field(k).Get(); got != "openai/gpt-6,anthropic/claude-opus-5:high" { + t.Fatalf("%s reads %q", k, got) + } + if err := a.Apply(k, "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if got := a.Field(k).Get(); got != "magpie/deepseek/pro" { + t.Fatalf("%s on magpie: %q", k, got) + } + if err := a.Apply(k, ""); err != nil { + t.Fatal(err) + } + if got := a.Field(k).Get(); got != "openai/gpt-6,anthropic/claude-opus-5:high" { + t.Fatalf("%s reset: %q", k, got) + } + } +} + +// A role on magpie at a thinking level that a fallback chain names too: a +// provider renamed moves each once, the level kept. The role back on omp's +// own, the chain alone keeps magpie's provider, has its wiring checked, and +// applying again mends it. +func TestOmpRoleAndChain(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + 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, ".omp", "agent") + configPath, modelsPath := filepath.Join(dir, "config.yml"), filepath.Join(dir, "models.yml") + os.MkdirAll(dir, 0o755) + os.WriteFile(configPath, []byte("modelRoles:\n default: anthropic/claude-opus-5\nretry:\n fallbackChains:\n slow:\n - magpie/deepseek/pro:max\n - openai/gpt-6\n"), 0o644) + a := omp(home) + if err := a.Apply("slow", "magpie/deepseek/pro:max"); err != nil { + t.Fatal(err) + } + if _, err := RenameProvider("deepseek", "ds"); err != nil { + t.Fatal(err) + } + chain := edit.GetYAMLList(configPath, "retry.fallbackChains.slow") + if s := a.Field("slow").Get(); s != "magpie/ds/pro:max" || !slices.Equal(chain, []string{"magpie/ds/pro:max", "openai/gpt-6"}) { + t.Fatalf("renamed: slow %q, chain %v", s, chain) + } + + if err := a.Apply("slow", ""); err != nil { + t.Fatal(err) + } + if v, _ := edit.GetYAML(modelsPath, "providers.magpie.baseUrl"); v == "" || a.Field("slow").Get() != "" { + t.Fatalf("the chain lost magpie's provider, or slow stayed: %q", a.Field("slow").Get()) + } + edit.SetYAML(modelsPath, edit.KV{Path: "providers.magpie.baseUrl", Value: "http://127.0.0.1:1/v1"}) + if d := a.Drift(); d == nil || d.Kind != "unwired" { + t.Fatalf("a chain's broken wiring: %+v", d) + } + if err := a.Reapply(); err != nil { + t.Fatal(err) + } + if c := a.Check(); c != "" { + t.Fatalf("applying again left: %s", c) + } +} + +// A role that is a list of models omp falls back through is the user's own, +// even when it starts on one of magpie's: magpie taking the role over +// stashes it, and a reset puts it back written as it was — a YAML list or a +// comma-separated string. +func TestOmpListRole(t *testing.T) { + for _, slow := range []string{ + " [magpie/deepseek/flash, openai/gpt-6]", + " magpie/deepseek/flash, openai/gpt-6", + "\n - magpie/deepseek/flash\n - openai/gpt-6", + } { + t.Run(slow, func(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + 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, ".omp", "agent") + configPath := filepath.Join(dir, "config.yml") + os.MkdirAll(dir, 0o755) + before := "modelRoles:\n default: anthropic/claude-opus-5\n slow:" + slow + "\n" + os.WriteFile(configPath, []byte(before), 0o644) + a := omp(home) + if err := a.Apply("slow", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if err := a.Apply("slow", ""); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(configPath) + if string(b) != before { + t.Fatalf("reset:\n%s\nwant:\n%s", b, before) + } + }) + } +} + +// A provider renamed moves the magpie models in a list role once, the list +// written as it was, and in the list the stash keeps for a role magpie took +// over, which a reset then puts back. +func TestOmpListRoleRenamed(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + 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, ".omp", "agent") + configPath := filepath.Join(dir, "config.yml") + os.MkdirAll(dir, 0o755) + os.WriteFile(configPath, []byte("modelRoles:\n default: anthropic/claude-opus-5\n slow: [magpie/deepseek/flash, openai/gpt-6]\n task: [magpie/deepseek/pro:high, openai/gpt-6]\n"), 0o644) + a := omp(home) + if err := a.Apply("slow", "magpie/deepseek/pro:max"); err != nil { + t.Fatal(err) + } + if _, err := RenameProvider("deepseek", "ds"); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(configPath) + task := edit.GetYAMLList(configPath, "modelRoles.task") + if s := a.Field("slow").Get(); s != "magpie/ds/pro:max" || !slices.Equal(task, []string{"magpie/ds/pro:high", "openai/gpt-6"}) || !strings.Contains(string(b), "task: [") { + t.Fatalf("renamed: slow %q\n%s", s, b) + } + if err := a.Apply("slow", ""); err != nil { + t.Fatal(err) + } + b, _ = os.ReadFile(configPath) + if !strings.Contains(string(b), "slow: [magpie/ds/flash, openai/gpt-6]") { + t.Fatalf("reset:\n%s", b) + } +} diff --git a/internal/agent/rename.go b/internal/agent/rename.go index 098a7b9c5..226aabb9e 100644 --- a/internal/agent/rename.go +++ b/internal/agent/rename.go @@ -29,12 +29,19 @@ func RenameProvider(from, to string) ([]string, error) { if v == "" { continue } + // the agent's suffix after the model (SplitSuffix) stays; a + // list of models is the user's own, its names moved by + // RenameRefs where the agent has one + model, suffix, one := a.split(v) + if !one { + continue + } nv := "" if f.Options != nil { for _, o := range f.Options(vals) { - if o.Value == v && strings.HasPrefix(o.Ref, from+"/") { + if o.Value == model && strings.HasPrefix(o.Ref, from+"/") { now := to + "/" + strings.TrimPrefix(o.Ref, from+"/") - nv = strings.Replace(v, o.Ref, now, 1) + nv = strings.Replace(model, o.Ref, now, 1) + suffix break } } diff --git a/internal/agent/reseat.go b/internal/agent/reseat.go index 233e4a368..cd1adc9b5 100644 --- a/internal/agent/reseat.go +++ b/internal/agent/reseat.go @@ -58,8 +58,13 @@ func picks() []pick { if v == "" || f.Options == nil { continue } + // a list of models is the user's own, left as it is + model, _, one := a.split(v) + if !one { + continue + } for _, o := range f.Options(vals) { - if o.Value == v && o.Ref != "" { + if o.Value == model && o.Ref != "" { out = append(out, pick{a, f.Key, v, o.Ref}) break } @@ -101,6 +106,12 @@ func Reseat(change func() error) ([]Move, error) { to = sameModel(f.Options(vals), p.ref) } m := Move{Agent: p.a.Name, Field: f.Label, From: p.ref, To: to.Ref} + // the same model elsewhere keeps the agent's suffix after it (omp's + // thinking level); the agent's own default has none + if to.Value != "" { + _, suffix, _ := p.a.split(p.val) + to.Value += suffix + } if err := p.a.Apply(p.key, to.Value); err != nil { m.To, m.Error = "", err.Error() } diff --git a/internal/edit/yaml.go b/internal/edit/yaml.go index 073a41654..28e15c7b0 100644 --- a/internal/edit/yaml.go +++ b/internal/edit/yaml.go @@ -44,8 +44,68 @@ func GetYAMLMap(path, keyPath string) map[string]string { return out } +// GetYAMLList reads the scalar items of the list at a key path. +func GetYAMLList(path, keyPath string) []string { + root, err := loadYAML(path) + if err != nil || root == nil { + return nil + } + n := lookupYAML(root, strings.Split(keyPath, ".")) + if n == nil || n.Kind != yaml.SequenceNode { + return nil + } + var out []string + for _, c := range n.Content { + if c.Kind == yaml.ScalarNode { + out = append(out, c.Value) + } + } + return out +} + +// GetYAMLText reads the value at a key path as the YAML it is written in — +// a list flow ("[a, b]") or block as it is — for SetYAML to put back as a +// YAMLText. +func GetYAMLText(path, keyPath string) (string, bool) { + root, err := loadYAML(path) + if err != nil || root == nil { + return "", false + } + n := lookupYAML(root, strings.Split(keyPath, ".")) + if n == nil { + return "", false + } + b, err := yaml.Marshal(n) + if err != nil { + return "", false + } + return strings.TrimSuffix(string(b), "\n"), true +} + +// YAMLText, as a KV's value, is set as the YAML it reads as rather than as +// a string: a list read with GetYAMLText goes back written as it was. +type YAMLText string + +// EditYAMLTextStrings is EditYAMLStrings on YAML text (a YAMLText) rather +// than a file: fn's answers in place of every string in it. +func EditYAMLTextStrings(text YAMLText, fn func(string) string) (YAMLText, error) { + var doc yaml.Node + if err := yaml.Unmarshal([]byte(text), &doc); err != nil || len(doc.Content) == 0 { + return text, err + } + if !mapStrings(doc.Content[0], fn) { + return text, nil + } + b, err := yaml.Marshal(doc.Content[0]) + if err != nil { + return text, err + } + return YAMLText(strings.TrimSuffix(string(b), "\n")), nil +} + // SetYAML sets key paths in a YAML file; a value may be a scalar, a map, -// a slice or a struct with yaml tags. Missing files and parents are created. +// a slice, a struct with yaml tags or YAMLText. Missing files and parents +// are created. func SetYAML(path string, kvs ...KV) error { root, err := loadYAML(path) if err != nil { @@ -56,7 +116,13 @@ func SetYAML(path string, kvs ...KV) error { } for _, kv := range kvs { var v yaml.Node - if err := v.Encode(kv.Value); err != nil { + if t, ok := kv.Value.(YAMLText); ok { + var doc yaml.Node + if err := yaml.Unmarshal([]byte(t), &doc); err != nil || len(doc.Content) == 0 { + return fmt.Errorf("%s: %s: not YAML: %q", path, kv.Path, string(t)) + } + v = *doc.Content[0] + } else if err := v.Encode(kv.Value); err != nil { return fmt.Errorf("%s: %w", path, err) } setYAML(root, strings.Split(kv.Path, "."), &v) @@ -105,20 +171,9 @@ func EditYAMLStrings(path string, keyPaths []string, fn func(string) string) err return err } changed := false - var walk func(*yaml.Node) - walk = func(n *yaml.Node) { - if n.Kind == yaml.ScalarNode && n.ShortTag() == "!!str" { - if v := fn(n.Value); v != n.Value { - n.Value, changed = v, true - } - } - for _, c := range n.Content { - walk(c) - } - } for _, kp := range keyPaths { if n := lookupYAML(root, strings.Split(kp, ".")); n != nil { - walk(n) + changed = mapStrings(n, fn) || changed } } if !changed { @@ -127,6 +182,21 @@ func EditYAMLStrings(path string, keyPaths []string, fn func(string) string) err return writeYAML(path, root) } +// mapStrings puts fn's answer in place of every string under n, and says +// whether any differs. +func mapStrings(n *yaml.Node, fn func(string) string) bool { + changed := false + if n.Kind == yaml.ScalarNode && n.ShortTag() == "!!str" { + if v := fn(n.Value); v != n.Value { + n.Value, changed = v, true + } + } + for _, c := range n.Content { + changed = mapStrings(c, fn) || changed + } + return changed +} + // JSONToYAML writes a JSON or JSONC file out as block-style YAML, key // order kept, for agents that moved from one to the other. func JSONToYAML(src, dst string) error { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 4c7682f9c..53410a950 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1144,16 +1144,21 @@ function openRowMenu(anchor, acts) { // once it runs through magpie. They share one button, which lists the four; // picking one opens the model picker for it. const TIERS = ["opus", "sonnet", "haiku", "fable"]; -// fields that fall back to the agent's model when unset -const FOLLOWS_MODEL = [...TIERS, "subagents"]; +// fields that fall back to the agent's model when unset: omp's smol and +// slow roles take the session's, as its subagents do ("smol", not "small": +// other agents' small model is a picker of its own) +const FOLLOWS_MODEL = [...TIERS, "subagents", "smol", "slow"]; // A field that follows the model unless set — Codex's subagents, Claude -// Code's tiers — is a small square after the pickers rather than a third -// picker, which a row has no room for: it wrapped onto a line of its own. -// So is Codex's sign-in, ChatGPT or magpie as its provider. +// Code's tiers, omp's roles — is a small square after the pickers rather +// than a third picker, which a row has no room for: it wrapped onto a line +// of its own. So is Codex's sign-in, ChatGPT or magpie as its provider. const extra = (f) => f.key === "tiers" || FOLLOWS_MODEL.includes(f.label) || f.label === "sign-in"; const EXTRA_GLYPH = { subagents: "M4.5 2.75v10.5M4.5 9.25c0-2.2 1.6-3.75 3.9-3.75h3.35M9.9 3.6l1.9 1.9-1.9 1.9", + // a feather for omp's smol role, an hourglass for its slow one + smol: "M12.75 3.25c-4.5 0-8 3.5-8 8v1.5M12.75 3.25c0 4-2.75 7-6.75 7.25M4.75 12.75l-1.5 1.5", + slow: "M4.5 2.5h7M4.5 13.5h7M5.25 2.5c0 3 5.5 3 5.5 5.5s-5.5 2.5-5.5 5.5M10.75 2.5c0 3-5.5 3-5.5 5.5s5.5 2.5 5.5 5.5", tiers: "M8 2.6 2.75 5.4 8 8.2l5.25-2.8zM2.75 8.1 8 10.9l5.25-2.8M2.75 10.8 8 13.6l5.25-2.8", "sign-in": "M8 2.5a2.75 2.75 0 1 1 0 5.5 2.75 2.75 0 0 1 0-5.5zM3 13.5c.4-2.4 2.4-3.9 5-3.9s4.6 1.5 5 3.9", }; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 491ef3fe3..69aefdf71 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -73,6 +73,8 @@ const I18N = { "large": "大模型", "tiers": "分档", "subagents": "子 agent", + "slow": "慢模型", + "smol": "小模型", "sign-in": "登录方式", "magpie's models join Codex's own; Codex stays signed in to ChatGPT": "默认。Codex 保持 ChatGPT 登录,magpie 的模型和 Codex 自带的模型一起出现", "magpie is Codex's provider; the Codex app is in its API state, with magpie's models only": "magpie 作为 Codex 的供应商,Codex 应用显示为 API 登录状态,只列出 magpie 的模型", diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 360d15aae..eba0c707a 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -70,6 +70,13 @@ group's "Show all" comes on hover, "Hide all" at the foot sends every one but the model in use, "Show all" there sends none, and Esc or a click elsewhere closes it. +`omp-roles.test.cjs` draws omp's subagents, smol and slow roles in Chromium +and WebKit, English and Chinese: each is a square after the model's picker, +not a picker of its own, as they follow the model while unset; unset it is +named "same as model" (「同主模型」), its picker opens on "Same as model" with +the model beside it, and picked it names the model it is on. OpenCode's +small model, which doesn't follow the model, stays a picker. + `gateway-fold.test.cjs` folds Connect on the Gateway page with the view scrolled: its fields hide, the head keeps the base URL and a copy button, the head stays where it was, and the fold is remembered across a reload. @@ -478,7 +485,7 @@ and the next stop is the lowest level. Chromium and WebKit. With Node.js and Playwright available: ```sh -node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-resets.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs +node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-resets.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/omp-roles.test.cjs b/internal/gui/tests/omp-roles.test.cjs new file mode 100644 index 000000000..906bf4613 --- /dev/null +++ b/internal/gui/tests/omp-roles.test.cjs @@ -0,0 +1,112 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// omp's subagents, smol and slow roles fall back to its model when unset +// (#325), so each is a square after the pickers, not a picker of its own: +// unset it says it follows the model, its picker opens on "Same as model", +// and set it names the model it is on. OpenCode's small model, which +// doesn't follow the model, stays a picker. In English and Chinese. +// No backend: the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const options = [ + { value: "magpie/deepseek/pro", label: "DeepSeek Pro", ref: "deepseek/pro" }, + { value: "magpie/deepseek/flash", label: "DeepSeek Flash", ref: "deepseek/flash" }, +]; +const field = (key, label, value) => ({ key, label, value, options }); +const fresh = () => ({ + agents: [ + { + id: "omp", name: "omp", path: "/test/config.yml", icon: "omp", + fields: [field("model", "model", "magpie/deepseek/pro"), field("subagent", "subagents", ""), field("small", "smol", ""), field("slow", "slow", "magpie/deepseek/flash")], + }, + { id: "opencode", name: "OpenCode", path: "/test/opencode.json", fields: [field("model", "model", "magpie/deepseek/pro"), field("small", "small", "")] }, + ], + profiles: [], +}); + +function server(lang, sets) { + let cur = fresh(); + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { ...cur, settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/set") { + const body = req.postDataJSON(); + sets.push(body); + cur = JSON.parse(JSON.stringify(cur)); + cur.agents.find((a) => a.id === body.agent).fields.find((f) => f.key === body.field).value = body.value; + return route.fulfill({ json: { ...cur, settings: { lang, theme: "light" } } }); + } + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/agents/cli") return route.fulfill({ json: { agents: {}, pending: false } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// the words as i18n.js has them +const W = { + en: { follows: (l) => `${l}: same as model`, on: (l, m) => `${l}: ${m}`, same: "Same as model", subagents: "subagents", smol: "smol", slow: "slow" }, + zh: { follows: (l) => `${l}:同主模型`, on: (l, m) => `${l}:${m}`, same: "同主模型", subagents: "子 agent", smol: "小模型", slow: "慢模型" }, +}; + +const omp = '.row.agent[data-id="omp"]'; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: omp's roles follow the model as squares, OpenCode's small model is a picker`, async (t) => { + const w = W[lang]; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await browser.newPage({ viewport: { width: 1100, height: 700 } }); + page.setDefaultTimeout(5000); + const errors = [], sets = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, sets)); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-omp-roles.png`) }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/"); + await page.locator(omp).waitFor(); + + // the three roles are squares in the row's squares cell; the model alone is a picker + const square = (key) => page.locator(`${omp} .extras-cell .field.extra[data-key="${key}"]`); + for (const key of ["subagent", "small", "slow"]) assert.equal(await square(key).count(), 1, `${key} is a square`); + assert.deepEqual(await page.locator(`${omp} .field:not(.extra)`).evaluateAll((es) => es.map((e) => e.dataset.key)), ["model"]); + // unset: following the model; set: the model it is on + assert.equal(await square("subagent").getAttribute("aria-label"), w.follows(w.subagents)); + assert.equal(await square("small").getAttribute("aria-label"), w.follows(w.smol)); + assert.equal(await square("small").evaluate((e) => e.classList.contains("set")), false); + assert.equal(await square("slow").getAttribute("aria-label"), w.on(w.slow, "DeepSeek Flash")); + assert.equal(await square("slow").evaluate((e) => e.classList.contains("set")), true); + + // smol's picker opens on following the model, the model named beside it + await square("small").click(); + const first = page.locator("#pop:not([hidden]) #list li").first(); + await first.waitFor(); + assert.match(await first.innerText(), new RegExp(`${w.same}[\\s\\S]*DeepSeek Pro`)); + await page.locator("#pop:not([hidden]) #list li").filter({ hasText: "DeepSeek Flash" }).first().click(); + await page.waitForFunction(() => document.querySelector('.row.agent[data-id="omp"] .field.extra.set[data-key="small"]')); + assert.deepEqual(sets, [{ ...sets[0], agent: "omp", field: "small", value: "magpie/deepseek/flash" }]); + assert.equal(await square("small").getAttribute("aria-label"), w.on(w.smol, "DeepSeek Flash")); + + // OpenCode's small model doesn't follow the model: a picker, not a square + const oc = '.row.agent[data-id="opencode"]'; + assert.equal(await page.locator(`${oc} .field.extra`).count(), 0); + assert.equal(await page.locator(`${oc} .field[data-key="small"]`).count(), 1); + assert.deepEqual(errors, []); + }); + } +} diff --git a/main.go b/main.go index d0ffd8b45..37cbe0c34 100644 --- a/main.go +++ b/main.go @@ -304,6 +304,16 @@ func set(a *agent.Agent, key, value string) error { func fieldForValue(a *agent.Agent, v string) *agent.Field { vals := a.Values() + // the agent's suffix after a model (omp's ":max") aside: a role on the + // same model at that level offers it as typed, and would take it. A list + // of models no picker offers: it is for the model + if a.SplitSuffix != nil { + m, _, one := a.SplitSuffix(v) + if !one { + return nil + } + v = m + } // a model stays with the model, even where other fields offer it too // (Claude Code's opus/sonnet/haiku/fable) for _, o := range a.Fields[0].Options(vals) {