agents, profiles: a profile keeps each agent's model list, and switching profiles switches it (#1368, liuheo)

Saving a profile (+ Save current, magpie save, the TUI) now keeps, beside
every detected agent's fields and the library, the agent's model list as
the Agents page's Pick sets it: the models taken out one by one
(hiddenModels), or "only the models I pick" and those picks
(pickedModels), the order put on them (orderedModels), and the
visibility `magpie visible` narrows it to (visible). It is kept under the
id the lists are kept by (agent.ListsFor), in profiles.json under a
"models" key beside "library". Applying a profile puts each list back
exactly (provider.SetModelLists: one settings write, renamed providers'
ids followed), then the fields, so the model is set last over the list;
the lists are written once through catalog.Touched, the same path a pick
made by hand takes, so Codex's magpie-models.json and the other agents'
model files are rewritten. A list that changed counts in "N settings
changed".

Left out on purpose: fastPicks (how a model is sent, not whether it is
listed, and it stays with the model) and agentEfforts (Cursor Private
Inference's effort is already an agent field a profile keeps).

A profile saved before this has no "models": it is read with none, leaves
every agent's list as it is (unknown, not empty), and is written back
byte for byte. An agent a new profile doesn't name keeps its list too.
A profile's details show a Model list line per agent: "8 hidden", "only
the 3 picked" or "every model shown", in all five languages.

Verified:
- internal/profile TestProfileSwitchesModelList: three profiles (two
  hidden; all shown with an order; only-picked), each applied rewrites
  settings and Codex's magpie-models.json to that list. Fails with Apply's
  list step removed ("applying home changed nothing", the hidden list
  not restored) and with catalog.Touched taken out of SetModelLists
  (Codex's file keeps the old list).
- TestOldProfileKeepsModelList: an old profile keeps codex's hidden and
  claude's only-picked, writes back unchanged; one naming only codex's
  list leaves claude's. Fails when a missing "models" is read as empty.
- The built nogui binary in a sandbox HOME (env -i): magpie save home /
  save work / use home / use work switched Codex's magpie-models.json
  between m1 and m1-m3.
- profile-details.test.cjs (en, zh window and panel, zh-TW, ja, de) in
  Chromium and WebKit; fails without the app.js line. With
  profile-confirm, panel-profiles, gui-ja, gui-de, gui-zh-tw, i18n-keys
  and click-scroll: 38/38 in each engine.
- gofmt -l clean; go vet (darwin), GOOS=linux go vet -tags nogui,
  GOOS=windows go vet on profile, provider, gui; go build, linux nogui
  and windows builds; go test -tags nogui ./... under a temp HOME, all ok.
Not tried in the real window with a live gateway.
This commit is contained in:
yetone
2026-10-09 11:06:07 +08:00
parent 16dc154589
commit 6d1322e58e
9 changed files with 449 additions and 17 deletions
+1 -1
View File
@@ -121,7 +121,7 @@ flowchart LR
Click a value and a searchable list opens: every model of every provider you added, as `provider/model`. Pick one and the agent's config is rewritten safely and atomically. Start a new session and the agent is on the new model.
**Profiles** save the setup of every agent under one name ("Budget", "Focus") and switch them all back in one move. Each agent can also have its own short list of models, so its picker shows only what you want there.
**Profiles** save the setup of every agent under one name ("Budget", "Focus") and switch them all back in one move. Each agent can also have its own short list of models, so its picker shows only what you want there; a profile keeps that list too.
magpie lives where you are: a **menu bar** panel on macOS, Windows and Linux, a full **window**, a **TUI** (`magpie tui`), a **web UI** (`magpie web`, for WSL or a server over SSH) and a plain **CLI**.
+1 -1
View File
@@ -121,7 +121,7 @@ flowchart LR
点一下模型,弹出可搜索的列表:你添加的每个 provider 的每个模型,格式是 `provider/model`。选中后,magpie 安全、原子地改写 Agent 的配置。开一个新会话,Agent 就用上新模型了。
**方案(Profile)**把所有 Agent 的配置存成一个名字,比如「省钱」「专注」,一键全部切回去。每个 Agent 还可以有自己的常用模型短名单,选择器里只显示你想要的。
**方案(Profile)**把所有 Agent 的配置存成一个名字,比如「省钱」「专注」,一键全部切回去。每个 Agent 还可以有自己的常用模型短名单,选择器里只显示你想要的;方案也会一并保存这份名单。
magpie 在你需要的地方:macOS、Windows 和 Linux 的**菜单栏**面板、完整的**窗口**、**TUI**(`magpie tui`)、**Web 界面**(`magpie web`,适合 WSL 或通过 SSH 管服务器)和纯 **CLI**。
+3
View File
@@ -758,6 +758,9 @@ function profileDetail(p, footed) {
else if (!f.value) row(t(f.label), t("agent default"), "pd-default");
else row(t(f.label), effort ? effortName({ value: f.value }) : f.value);
}
// the models its list shows, which applying it switches to (#1368)
const m = g.models;
if (m) row(t("Model list"), m.only ? t("only the {n} picked", { n: m.picked }) : m.hidden ? t("{n} hidden", { n: m.hidden }) : t("every model shown"), m.only || m.hidden ? "" : "pd-default");
if (g.servers?.length) row(t("MCP servers"), g.servers.join(t(", ")));
if (g.skills?.length) row(t("Skills"), g.skills.join(t(", ")));
if (g.instructions) row(t("Instructions"), t("on"));
+8
View File
@@ -418,6 +418,8 @@ const I18N = {
"A model of 1M or more is listed once, as its 1M entry. Quit and reopen Claude Desktop after a change.": "上下文达到 1M 或以上的模型只列一项,即它的 1M 版本。改动后需退出并重新打开 Claude Desktop。",
"Saved — quit and reopen Claude Desktop to see it": "已保存——退出并重新打开 Claude Desktop 后生效",
"Model list": "模型列表",
"only the {n} picked": "仅显示所选的 {n} 个",
"every model shown": "全部显示",
"New sessions": "新会话默认",
"The same choice as {agent}'s {cmd}: change it here or there": "与 {agent} 的 {cmd} 同步,两边均可修改",
"Reopen {agent}: its own models stay in {cmd}, and magpie's join them.": "重开 {agent} 后,{cmd} 中既有它自己的模型,也有 magpie 的模型。",
@@ -4219,6 +4221,8 @@ const I18N = {
"A model of 1M or more is listed once, as its 1M entry. Quit and reopen Claude Desktop after a change.": "上下文達到 1M 或以上的模型只列一項,即它的 1M 版本。改動後需結束並重新開啟 Claude Desktop。",
"Saved — quit and reopen Claude Desktop to see it": "已儲存——結束並重新開啟 Claude Desktop 後生效",
"Model list": "模型列表",
"only the {n} picked": "僅顯示所選的 {n} 個",
"every model shown": "全部顯示",
"New sessions": "新會話預設",
"The same choice as {agent}'s {cmd}: change it here or there": "與 {agent} 的 {cmd} 同步,兩邊均可修改",
"Reopen {agent}: its own models stay in {cmd}, and magpie's join them.": "重開 {agent} 後,{cmd} 中既有它自己的模型,也有 magpie 的模型。",
@@ -7985,6 +7989,8 @@ const I18N = {
"A model of 1M or more is listed once, as its 1M entry. Quit and reopen Claude Desktop after a change.": "1M 以上のコンテキストを持つモデルは 1M 版の 1 項目だけ表示されます。変更後は Claude Desktop を終了して開き直してください。",
"Saved — quit and reopen Claude Desktop to see it": "保存しました。Claude Desktop を終了して開き直すと反映されます",
"Model list": "モデル一覧",
"only the {n} picked": "選んだ {n} 件のみ",
"every model shown": "すべて表示",
"New sessions": "新しいセッション",
"The same choice as {agent}'s {cmd}: change it here or there": "{agent} の {cmd} と同じ選択です。ここでもそちらでも変更できます",
"Reopen {agent}: its own models stay in {cmd}, and magpie's join them.": "{agent} を開き直してください。{cmd} には独自のモデルが残り、magpie のモデルが加わります。",
@@ -11769,6 +11775,8 @@ const I18N = {
"A model of 1M or more is listed once, as its 1M entry. Quit and reopen Claude Desktop after a change.": "Ein Modell mit 1M oder mehr erscheint nur einmal, als 1M-Eintrag. Beende Claude Desktop nach einer Änderung und öffne es neu.",
"Saved — quit and reopen Claude Desktop to see it": "Gespeichert – beende Claude Desktop und öffne es neu, um es zu sehen",
"Model list": "Modellliste",
"only the {n} picked": "nur die {n} ausgewählten",
"every model shown": "alle angezeigt",
"New sessions": "Neue Sitzungen",
"The same choice as {agent}'s {cmd}: change it here or there": "Dieselbe Auswahl wie {cmd} von {agent}: hier oder dort ändern",
"Reopen {agent}: its own models stay in {cmd}, and magpie's join them.": "{agent} neu öffnen: die eigenen Modelle bleiben in {cmd}, die von magpie kommen hinzu.",
+36 -6
View File
@@ -32,12 +32,14 @@ const work = {
{ key: "haiku", label: "haiku", value: "", follows: "model" },
{ key: "fable", label: "fable", value: "", follows: "model" },
{ key: "subagent", label: "subagents", value: "" },
], servers: ["github"], skills: ["review"] },
], servers: ["github"], skills: ["review"], models: { hidden: 0 } },
{ id: "codex", name: "Codex", fields: [
{ key: "model", label: "model", value: "magpie/openai/gpt-5" },
{ key: "effort", label: "effort", value: "high" },
{ key: "token", label: "token", value: "", hidden: true },
], instructions: true },
], instructions: true, models: { hidden: 8 } },
// an agent with no fields saved, only a model list: shown only its picks
{ id: "opencode", name: "OpenCode", fields: [], models: { hidden: 0, only: true, picked: 3 } },
],
};
@@ -66,8 +68,8 @@ function server(lang, calls, count) {
}
const words = {
en: { model: "model", effort: "effort", high: "high", def: "agent default", follows: "follows the main model (magpie/a/main)", subagents: "subagents", servers: "MCP servers", skills: "Skills", instructions: "Instructions", on: "on", apply: "Apply" },
zh: { model: "模型", effort: "推理强度", high: "高", def: "Agent 默认值", follows: "跟随主模型(magpie/a/main)", subagents: "子 agent", servers: "MCP 服务器", skills: "技能", instructions: "指令", on: "开启", apply: "应用" },
en: { model: "model", effort: "effort", high: "high", def: "agent default", follows: "follows the main model (magpie/a/main)", subagents: "subagents", servers: "MCP servers", skills: "Skills", instructions: "Instructions", on: "on", apply: "Apply", list: "Model list", all: "every model shown", hidden8: "8 hidden", picked3: "only the 3 picked" },
zh: { model: "模型", effort: "推理强度", high: "高", def: "Agent 默认值", follows: "跟随主模型(magpie/a/main)", subagents: "子 agent", servers: "MCP 服务器", skills: "技能", instructions: "指令", on: "开启", apply: "应用", list: "模型列表", all: "全部显示", hidden8: "已隐藏 8 个", picked3: "仅显示所选的 3 个" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -134,8 +136,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(read.apply, w.apply);
assert(read.inView, "the details must be drawn");
assert.deepEqual(read.groups, [
{ name: "Claude Code", rows: [`${w.model}=magpie/a/main`, `opus=${w.follows}`, "sonnet=magpie/a/s", `haiku=${w.follows}`, `fable=${w.follows}`, `${w.subagents}=${w.def}`, `${w.servers}=github`, `${w.skills}=review`] },
{ name: "Codex", rows: [`${w.model}=magpie/openai/gpt-5`, `${w.effort}=${w.high}`, "token=••••••", `${w.instructions}=${w.on}`] },
{ name: "Claude Code", rows: [`${w.model}=magpie/a/main`, `opus=${w.follows}`, "sonnet=magpie/a/s", `haiku=${w.follows}`, `fable=${w.follows}`, `${w.subagents}=${w.def}`, `${w.list}=${w.all}`, `${w.servers}=github`, `${w.skills}=review`] },
{ name: "Codex", rows: [`${w.model}=magpie/openai/gpt-5`, `${w.effort}=${w.high}`, "token=••••••", `${w.list}=${w.hidden8}`, `${w.instructions}=${w.on}`] },
{ name: "OpenCode", rows: [`${w.list}=${w.picked3}`] },
]);
// a second click closes them; a third opens them again
@@ -154,5 +157,32 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
}
// the model list's line in the other languages (#1368)
const lists = {
"zh-TW": ["模型列表=全部顯示", "模型列表=已隱藏 8 個", "模型列表=僅顯示所選的 3 個"],
ja: ["モデル一覧=すべて表示", "モデル一覧=8 件非表示", "モデル一覧=選んだ 3 件のみ"],
de: ["Modellliste=alle angezeigt", "Modellliste=8 ausgeblendet", "Modellliste=nur die 3 ausgewählten"],
};
for (const [lang, want] of Object.entries(lists)) {
await t.test(`${lang}, the model lists`, async () => {
const errors = [];
const page = await (await browser.newContext({ viewport: { width: 900, height: 560 } })).newPage();
pages.push(page);
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, [], 3));
await page.goto("http://magpie.test/");
const chip = page.locator("#profiles .chip", { hasText: /^work/ });
await chip.waitFor({ state: "attached" });
await chip.scrollIntoViewIfNeeded();
await chip.click();
await page.locator(".prof-detail").waitFor();
const rows = await page.locator(".prof-detail").evaluate((d) =>
[...d.querySelectorAll(".pd-agent dt")].map((dt) => dt.textContent + "=" + dt.nextElementSibling.textContent));
assert.deepEqual(rows.filter((r) => r.startsWith(want[0].split("=")[0] + "=")), want);
assert.deepEqual(errors, []);
});
}
});
}
+22 -1
View File
@@ -22,6 +22,17 @@ type Group struct {
Servers []string `json:"servers,omitempty"`
Skills []string `json:"skills,omitempty"`
Instructions bool `json:"instructions,omitempty"`
// Models is the model list it is switched to (#1368); nil when the
// profile keeps none for it, which leaves its list as it is
Models *Models `json:"models,omitempty"`
}
// Models is a model list as a profile's details tell it: how many models
// are taken out, or, Only, how many are the only ones picked.
type Models struct {
Hidden int `json:"hidden"`
Only bool `json:"only,omitempty"`
Picked int `json:"picked,omitempty"`
}
// Item is one saved field. Value "" is the agent's own default, or, with
@@ -91,6 +102,13 @@ func Details(p Profile) []Group {
take(id)
}
}
// a list nobody picked for is told only beside the agent's model: an
// agent of no fields and no list of its own is no line of the details
for id, ml := range p.Models {
if !ml.Default() {
take(id)
}
}
var unknown []string
for id := range byID {
if known[id] == nil {
@@ -147,7 +165,10 @@ func Details(p Profile) []Group {
i := l.Instructions
g.Instructions = i.Extra[id] != "" || i.Shared != "" && slices.Contains(i.Agents, id)
}
if len(g.Fields) == 0 && len(g.Servers) == 0 && len(g.Skills) == 0 && !g.Instructions {
if ml, ok := p.Models[id]; ok && (!ml.Default() || len(g.Fields) > 0) {
g.Models = &Models{Hidden: len(ml.Hidden), Only: ml.Only, Picked: len(ml.Picked)}
}
if len(g.Fields) == 0 && len(g.Servers) == 0 && len(g.Skills) == 0 && !g.Instructions && g.Models == nil {
continue
}
out = append(out, g)
+196
View File
@@ -0,0 +1,196 @@
package profile
import (
"encoding/json"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// modelsHome is the sandbox with a provider of three models and Codex set up
// with magpie as its provider, whose model list magpie writes into
// magpie-models.json, and the agents' files following a change of the
// catalog as they do in magpie (main sets catalog.Changed).
func modelsHome(t *testing.T) (catalogFile string) {
t.Helper()
h := sandbox(t)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1", "m2", "m3"}}); err != nil {
t.Fatal(err)
}
catalogFile = filepath.Join(h, ".codex", "magpie-models.json")
write(t, filepath.Join(h, ".codex", "config.toml"), "model = \"relay/m1\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = \""+filepath.ToSlash(catalogFile)+"\"\n\n[model_providers.magpie]\nname = \"magpie\"\nbase_url = \"http://127.0.0.1:1/v1\"\nwire_api = \"responses\"\n")
was := catalog.Changed
catalog.Changed = agent.SyncCatalog
t.Cleanup(func() { catalog.Changed = was })
catalog.Touched()
return catalogFile
}
// lists is which of the relay's models magpie-models.json gives Codex.
func lists(t *testing.T, file string) []string {
t.Helper()
var out []string
for _, m := range []string{"relay/m1", "relay/m2", "relay/m3"} {
if strings.Contains(read(t, file), `"`+m+`"`) {
out = append(out, m)
}
}
return out
}
// A profile keeps each agent's model list beside its fields (#1368):
// switching profiles switches which models Codex lists — the ones taken
// out, the mode of showing only the ones picked, the order — and writes
// Codex's model list again, as a pick made by hand on the Agents page does.
func TestProfileSwitchesModelList(t *testing.T) {
file := modelsHome(t)
if got := lists(t, file); len(got) != 3 {
t.Fatalf("set up: %v in\n%s", got, read(t, file))
}
// 家里: two taken out
if err := provider.SetHiddenModels("codex", []string{"relay/m2", "relay/m3"}); err != nil {
t.Fatal(err)
}
if err := Save("home", must[Profile](t)(Snapshot())); err != nil {
t.Fatal(err)
}
// 公司: every one shown, put in an order
if err := provider.SetHiddenModels("codex", nil); err != nil {
t.Fatal(err)
}
if err := provider.SetModelOrder("codex", []string{"relay/m3"}); err != nil {
t.Fatal(err)
}
if err := Save("work", must[Profile](t)(Snapshot())); err != nil {
t.Fatal(err)
}
// only the ones picked: m2, and m1 Codex is on, which the Agents page
// keeps among them
if err := provider.SetOnlyPicked("codex", true); err != nil {
t.Fatal(err)
}
if err := provider.SetPickedModels("codex", []string{"relay/m1", "relay/m2"}); err != nil {
t.Fatal(err)
}
if err := Save("picked", must[Profile](t)(Snapshot())); err != nil {
t.Fatal(err)
}
ps := must[map[string]Profile](t)(Load())
a := must[Applied](t)(Apply(ps["home"]))
if a.Changed == 0 {
t.Error("applying home changed nothing")
}
s := settings.Load()
if _, only := s.PickedModels["codex"]; only || !slices.Equal(s.HiddenModels["codex"], []string{"relay/m2", "relay/m3"}) || len(s.OrderedModels["codex"]) != 0 {
t.Fatalf("home: hidden %v picked %v order %v", s.HiddenModels, s.PickedModels, s.OrderedModels)
}
if got := lists(t, file); !slices.Equal(got, []string{"relay/m1"}) {
t.Fatalf("home: Codex lists %v\n%s", got, read(t, file))
}
must[Applied](t)(Apply(ps["work"]))
s = settings.Load()
if len(s.HiddenModels["codex"]) != 0 || !slices.Equal(s.OrderedModels["codex"], []string{"relay/m3"}) {
t.Fatalf("work: hidden %v order %v", s.HiddenModels, s.OrderedModels)
}
if got := lists(t, file); len(got) != 3 {
t.Fatalf("work: Codex lists %v\n%s", got, read(t, file))
}
if b := read(t, file); strings.Index(b, `"relay/m3"`) > strings.Index(b, `"relay/m1"`) {
t.Errorf("work: m3 not put first\n%s", b)
}
must[Applied](t)(Apply(ps["picked"]))
if on, only := provider.PickedModels("codex"); !only || len(on) != 2 || !on["relay/m1"] || !on["relay/m2"] {
t.Fatalf("picked: %v %v", on, only)
}
if got := lists(t, file); !slices.Equal(got, []string{"relay/m1", "relay/m2"}) {
t.Fatalf("picked: Codex lists %v", got)
}
// applied again, nothing to change in the list
if a := must[Applied](t)(Apply(ps["picked"])); a.Changed != 0 {
t.Errorf("applied twice: %d changed", a.Changed)
}
// what the details tell before it is applied
for name, want := range map[string]Models{"home": {Hidden: 2}, "work": {}, "picked": {Only: true, Picked: 2}} {
var got *Models
for _, g := range Details(ps[name]) {
if g.ID == "codex" {
got = g.Models
}
}
if got == nil || *got != want {
t.Errorf("%s details: %+v, want %+v", name, got, want)
}
}
}
// A profile saved before profiles kept the model lists leaves each agent's
// list as it is: a list it says nothing of is unknown, not empty, so none is
// shown every model, nor any hidden.
func TestOldProfileKeepsModelList(t *testing.T) {
file := modelsHome(t)
if err := provider.SetHiddenModels("codex", []string{"relay/m2"}); err != nil {
t.Fatal(err)
}
if err := provider.SetOnlyPicked("claude", true); err != nil {
t.Fatal(err)
}
old := `{
"work": {
"codex.model": "relay/m1"
}
}
`
write(t, Path(), old)
ps := must[map[string]Profile](t)(Load())
if ps["work"].Models != nil {
t.Fatalf("an old profile read with lists: %+v", ps["work"].Models)
}
must[Applied](t)(Apply(ps["work"]))
s := settings.Load()
if !slices.Equal(s.HiddenModels["codex"], []string{"relay/m2"}) {
t.Errorf("codex's hidden: %v", s.HiddenModels["codex"])
}
if _, only := s.PickedModels["claude"]; !only {
t.Errorf("claude's only-picked lost: %v", s.PickedModels)
}
if got := lists(t, file); !slices.Equal(got, []string{"relay/m1", "relay/m3"}) {
t.Errorf("Codex lists %v", got)
}
// and written back as it was, with no lists made up for it
if err := store(ps); err != nil {
t.Fatal(err)
}
if b := read(t, Path()); b != old {
t.Errorf("written back as\n%s", b)
}
// a profile naming one agent's list leaves the others' alone
p := Profile{Fields: map[string]string{}, Models: map[string]provider.ModelList{"codex": {}}}
b, err := json.Marshal(p)
if err != nil {
t.Fatal(err)
}
var back Profile
if err := json.Unmarshal(b, &back); err != nil {
t.Fatal(err)
}
must[Applied](t)(Apply(back))
s = settings.Load()
if len(s.HiddenModels["codex"]) != 0 {
t.Errorf("codex kept %v", s.HiddenModels["codex"])
}
if _, only := s.PickedModels["claude"]; !only {
t.Errorf("claude's list changed by a profile naming only codex's: %v", s.PickedModels)
}
}
+50 -8
View File
@@ -25,6 +25,11 @@ type Profile struct {
// instructions; nil for a profile saved while the library was empty,
// or before profiles kept it, which leaves the library as it is.
Library *library.Setup
// Models are the agents' model lists (#1368), by the id their lists are
// kept under (agent.ListsFor): which of magpie's models each shows and
// in what order. An agent not named, every one in a profile saved
// before profiles kept them, keeps the list it has.
Models map[string]provider.ModelList
}
// libraryKey holds the library's setup among a profile's "agent.field"
@@ -32,6 +37,9 @@ type Profile struct {
// before it is read as it always was.
const libraryKey = "library"
// modelsKey holds the agents' model lists, as libraryKey the library's.
const modelsKey = "models"
// MarshalJSON writes the fields and the library's setup side by side.
func (p Profile) MarshalJSON() ([]byte, error) {
m := make(map[string]any, len(p.Fields)+1)
@@ -41,6 +49,9 @@ func (p Profile) MarshalJSON() ([]byte, error) {
if p.Library != nil {
m[libraryKey] = p.Library
}
if p.Models != nil {
m[modelsKey] = p.Models
}
return json.Marshal(m)
}
@@ -63,6 +74,15 @@ func (p *Profile) UnmarshalJSON(b []byte) error {
}
continue
}
if k == modelsKey {
if string(raw) == "null" {
continue
}
if err := json.Unmarshal(raw, &p.Models); err != nil {
return fmt.Errorf("%s: %w", k, err)
}
continue
}
var v string
if err := json.Unmarshal(raw, &v); err != nil {
return fmt.Errorf("%s: %w", k, err)
@@ -121,10 +141,21 @@ func Fields() map[string]string {
return p
}
// Snapshot captures every detected agent's fields, and the library's setup
// unless the library is empty.
// ModelLists captures every detected agent's model list, one the user never
// picked for included: applied, it shows that agent every model again.
func ModelLists() map[string]provider.ModelList {
out := map[string]provider.ModelList{}
for _, a := range agent.Detected() {
id := strings.ToLower(a.ListsFor())
out[id] = provider.ModelListOf(id)
}
return out
}
// Snapshot captures every detected agent's fields and model list, and the
// library's setup unless the library is empty.
func Snapshot() (Profile, error) {
p := Profile{Fields: Fields()}
p := Profile{Fields: Fields(), Models: ModelLists()}
s, err := library.Snapshot()
if err != nil {
return p, err
@@ -164,18 +195,29 @@ func Delete(name string) error {
// Applied is what applying a profile did.
type Applied struct {
Changed int // agent fields changed
Changed int // agent fields changed, and model lists
// Library is what bringing the library's setup back wrote into the
// agents; nil for a profile that carries none.
Library *library.Result
}
// Apply writes every field in p that differs from what is set now, then
// brings the library's setup back when p carries one and writes it into
// the agents (their files kept aside first). It stops at the first error.
// Apply puts back the agents' model lists p carries, writes every field in
// p that differs from what is set now, then brings the library's setup back
// when p carries one and writes it into the agents (their files kept aside
// first). It stops at the first error. The lists go first, so the files
// that list an agent's models are written for the list it is switched to,
// and its model is set last, over them.
func Apply(p Profile) (Applied, error) {
var out Applied
if len(p.Models) > 0 {
lists, err := provider.SetModelLists(p.Models)
out.Changed = len(lists)
if err != nil {
return out, err
}
}
n, err := ApplyFields(p.Fields)
out := Applied{Changed: n}
out.Changed += n
if err != nil || p.Library == nil {
return out, err
}
+132
View File
@@ -0,0 +1,132 @@
package provider
import (
"errors"
"maps"
"slices"
"strings"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/settings"
)
// ModelList is everything that decides which of magpie's models an agent's
// lists show, and in what order, as a profile keeps it (#1368): its
// visibility (Visible), the models taken out one by one (HiddenModels) or,
// for an agent shown only its picks, the ones picked (PickedModels), and the
// order it was put in (OrderedModels). The fast picks are not here: they say
// how a model is sent, not whether it is listed.
type ModelList struct {
// Visible is what its lists are narrowed to; nil when they aren't.
Visible *[]string `json:"visible,omitempty"`
Hidden []string `json:"hidden,omitempty"`
// Only: it is shown only Picked, none when Picked is empty.
Only bool `json:"only,omitempty"`
Picked []string `json:"picked,omitempty"`
Order []string `json:"order,omitempty"`
}
// Default reports whether l is what an agent never picked for is shown:
// every model, in magpie's own order.
func (l ModelList) Default() bool {
return l.Visible == nil && len(l.Hidden) == 0 && !l.Only && len(l.Order) == 0
}
// ModelListOf is agent's model list as it is now.
func ModelListOf(agent string) ModelList {
agent = strings.ToLower(strings.TrimSpace(agent))
s := heldSettings()
var l ModelList
if v, ok := s.Visible[agent]; ok {
v = slices.Clone(v)
l.Visible = &v
}
if p, ok := s.PickedModels[agent]; ok {
l.Only, l.Picked = true, slices.Clone(p)
} else {
l.Hidden = slices.Clone(s.HiddenModels[agent])
}
l.Order = slices.Clone(s.OrderedModels[agent])
return l
}
// SetModelLists puts each agent's model list back as it was kept, exactly,
// and tells the agents that keep the models in files of their own once, as
// a pick made by hand does (catalog.Touched). A model of a provider renamed
// since is the same model by its new id. It returns the agents whose list
// changed, sorted.
func SetModelLists(ls map[string]ModelList) ([]string, error) {
s := settings.Load()
was := Renamed()
var changed []string
put := func(m *map[string][]string, agent string, ids []string, on bool) bool {
cur, had := (*m)[agent]
if !on {
if !had {
return false
}
delete(*m, agent)
return true
}
if had && slices.Equal(cur, ids) {
return false
}
if *m == nil {
*m = map[string][]string{}
}
(*m)[agent] = ids
return true
}
renamed := func(ids []string) []string {
out := make([]string, 0, len(ids))
for _, id := range ids {
for old, now := range was {
if r := renamedRef(id, old, now); r != id {
id = r
break
}
}
out = append(out, id)
}
return out
}
for _, agent := range slices.Sorted(maps.Keys(ls)) {
l := ls[agent]
agent = strings.ToLower(strings.TrimSpace(agent))
if agent == "" {
return nil, errors.New("no agent")
}
var visible []string
if l.Visible != nil {
for _, n := range *l.Visible {
for old, now := range was {
if strings.EqualFold(n, old) {
n = now
}
}
visible = append(visible, n)
}
if visible == nil {
visible = []string{}
}
}
hidden := sortedIDs(renamed(l.Hidden))
picked := sortedIDs(renamed(l.Picked))
order := renamed(l.Order)
a := put(&s.Visible, agent, visible, l.Visible != nil)
b := put(&s.PickedModels, agent, picked, l.Only)
c := put(&s.HiddenModels, agent, hidden, !l.Only && len(hidden) > 0)
d := put(&s.OrderedModels, agent, order, len(order) > 0)
if a || b || c || d {
changed = append(changed, agent)
}
}
if len(changed) == 0 {
return nil, nil
}
if err := settings.Save(s); err != nil {
return nil, err
}
catalog.Touched()
return changed, nil
}