diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 8782b2e51..00fbe835a 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -39,7 +39,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) | | Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) | | Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) | -| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. User-supplied headers still apply through `Sign`. | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) | +| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) | ## Remote magpie diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 1baae5c6c..2afbfedbc 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2533,6 +2533,10 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .eps .detect-acts .text { margin: 0; } .detect-acts .pick-api.on { background: var(--pill); } .detect-acts .hint { font-size: 11.5px; color: var(--faint); } +/* what is missing or went wrong, said under the buttons (#1545) */ +.detect-out .detect-say { font-size: 11.5px; overflow-wrap: anywhere; } +.detect-out .detect-say.warn { color: var(--amber); } +.detect-out .detect-say.err { color: var(--red); } .detect-row .detect-each { flex: none; } .add-models .detect-row input { flex: 1; min-width: 0; } .add-models-list { max-height: 260px; overflow-y: auto; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index e1e9265a0..0ab3c616c 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -9467,31 +9467,50 @@ function detectAPIs(p, base, use) { out.append(e); } }; + // what is missing, or what went wrong, said here under the buttons + // rather than in the toast at the top (#1545) + const say = (msg, kind) => { out.hidden = false; out.replaceChildren(el("span", "hint detect-say " + kind, msg)); }; + // the models the form has picked, saved or not: a new provider's typed + // or ticked in its Models field (draft.extra), a saved one's chips with + // the ids still in its add box + const picked = () => p ? chosenIds() : (draft.extra || []).filter((id, i, all) => id && all.indexOf(id) === i); + // no key typed, none saved and none copied: a refusal is likely the key + const keyless = () => { + if ((draft.key || "").trim() || p?.key?.set || draft.vertex) return false; + const of = !p && draft.copyOf && providers.providers.find((x) => x.id === draft.copyOf); + return !of?.key?.set; + }; + const noneAnswered = () => el("span", "hint", keyless() ? t("None answered, and no API key is typed: paste the key under API key and detect again") + : t("None answered: check the URL and the key, or type a model the vendor serves")); const ask = async (btn, extra) => { const typedBase = (base() || "").trim(); - if (!typedBase && !(draft.chat || draft.responses || draft.anthropic || draft.gemini || "").trim()) { status(t("Type the base URL first"), "warn"); return null; } + if (!typedBase && !(draft.chat || draft.responses || draft.anthropic || draft.gemini || "").trim()) { say(t("Type the base URL first"), "warn"); return null; } btn.classList.add("busy"); out.hidden = false; out.replaceChildren(el("span", "hint", t("Asking each API…"))); try { // the URL typed is asked as each API takes it, not as the field - // holding it would send it; URLs given under More endpoints as they are + // holding it would send it; URLs given under More endpoints as they are. + // The form as it stands is asked and nothing is saved: a saved + // provider's key (or the copied one's) stands for a key not typed. const body = { ...asTyped(), id: p?.id, base: typedBase, ...extra }; + if (!p && draft.copyOf) Object.assign(body, { new: true, copyOf: draft.copyOf }); for (const k of ["chat", "responses", "anthropic", "gemini"]) if (body[k] === typedBase) body[k] = ""; const r = await api("provider/detect", body); out.replaceChildren(); return r; - } catch (e) { out.replaceChildren(); out.hidden = true; status(e.message, "err"); return null; } + } catch (e) { say(e.message, "err"); return null; } finally { btn.classList.remove("busy"); } }; go.onclick = async () => { const m = model.value.trim(); - const r = await ask(go, { model: m }); + // no model typed: one of those the form has picked, else the vendor's + const r = await ask(go, m ? { model: m } : { model: "", picked: picked().slice(0, DETECT_MAX) }); if (!r) return; byAPI(r.results); const ok = r.results.filter((x) => x.ok); const acts = el("div", "detect-acts"); - if (!ok.length) acts.append(el("span", "hint", t("None answered: check the URL and the key, or type a model the vendor serves"))); + if (!ok.length) acts.append(noneAnswered()); else { const take = el("button", "text action", t("Use these")); take.title = t("Set the URLs of the APIs that answered; one not found there is cleared"); @@ -9528,9 +9547,9 @@ function detectAPIs(p, base, use) { if (!Object.keys(prefs[id]).length) delete prefs[id]; }; each.onclick = async () => { - if (draft.api === "decide") { status(t("A decision API is asked with one model: type it and press Detect APIs"), "warn"); return; } - const ids = chosenIds(); - if (!ids.length) { status(t("Pick models first, or type one and press Detect APIs"), "warn"); return; } + if (draft.api === "decide") { say(t("A decision API is asked with one model: type it and press Detect APIs"), "warn"); return; } + const ids = picked(); + if (!ids.length) { say(t("Pick models first, or type one and press Detect APIs"), "warn"); return; } const r = await ask(each, { detectModels: ids }); if (!r) return; byAPI(r.results); @@ -9564,7 +9583,7 @@ function detectAPIs(p, base, use) { out.append(grid); if (ids.length > r.models.length) out.append(el("span", "hint", t("Only the first {n} of {all} models were asked", { n: r.models.length, all: ids.length }))); const acts = el("div", "detect-acts"); - if (!r.results.some((x) => x.ok)) acts.append(el("span", "hint", t("None answered: check the URL and the key, or type a model the vendor serves"))); + if (!r.results.some((x) => x.ok)) acts.append(noneAnswered()); else { const take = el("button", "text action", t("Use these")); // only a saved provider's models are given an API; a new one's, in diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index cd3608e28..d57a1d035 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1926,6 +1926,7 @@ const I18N = { "Type the base URL first": "请先填写 Base URL", "Asking each API…": "正在逐个检测协议…", "None answered: check the URL and the key, or type a model the vendor serves": "都没有响应:请检查地址和密钥,或填写一个供应商提供的模型", + "None answered, and no API key is typed: paste the key under API key and detect again": "都没有响应,且还没有填写 API 密钥:请在「API 密钥」中粘贴密钥后再检测", "Use these": "使用检测结果", "Set the URLs of the APIs that answered; one not found there is cleared": "填入有响应的协议地址;不存在的协议地址会被清空", "Taken · save to keep": "已填入 · 保存后生效", @@ -6097,6 +6098,7 @@ const I18N = { "Type the base URL first": "請先填寫 Base URL", "Asking each API…": "正在逐個檢測協議…", "None answered: check the URL and the key, or type a model the vendor serves": "都沒有回應:請檢查位址和金鑰,或填寫一個供應商提供的模型", + "None answered, and no API key is typed: paste the key under API key and detect again": "都沒有回應,且還沒有填寫 API 金鑰:請在「API 金鑰」中貼上金鑰後再檢測", "Use these": "使用檢測結果", "Set the URLs of the APIs that answered; one not found there is cleared": "填入有回應的協議位址;不存在的協議位址會被清空", "Taken · save to keep": "已填入 · 儲存後生效", @@ -10286,6 +10288,7 @@ const I18N = { "Type the base URL first": "先にベース URL を入力してください", "Asking each API…": "各 API に問い合わせ中…", "None answered: check the URL and the key, or type a model the vendor serves": "どれも応答しませんでした。URL とキーを確認するか、ベンダーが提供するモデルを入力してください", + "None answered, and no API key is typed: paste the key under API key and detect again": "どれも応答しませんでした。APIキーが未入力です。「APIキー」にキーを貼り付けてもう一度検出してください", "Use these": "これを使う", "Set the URLs of the APIs that answered; one not found there is cleared": "応答した API の URL を設定します。見つからなかったものは消去されます", "Taken · save to keep": "反映済み · 保存して確定", @@ -14474,6 +14477,7 @@ const I18N = { "Type the base URL first": "Geben Sie zuerst die Basis-URL ein", "Asking each API…": "Jede API wird angefragt…", "None answered: check the URL and the key, or type a model the vendor serves": "Keine hat geantwortet: Prüfen Sie URL und Schlüssel oder geben Sie ein Modell des Anbieters ein", + "None answered, and no API key is typed: paste the key under API key and detect again": "Keine hat geantwortet, und kein API-Schlüssel ist eingegeben: Fügen Sie den Schlüssel unter API-Schlüssel ein und erkennen Sie erneut", "Use these": "Diese verwenden", "Set the URLs of the APIs that answered; one not found there is cleared": "URLs der antwortenden APIs eintragen; nicht gefundene werden geleert", "Taken · save to keep": "Übernommen · zum Behalten speichern", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index d24e98b4d..83ea867ae 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1016,6 +1016,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // DetectModels, for detect: models to ask on each API, each // answered on its own, in place of Model DetectModels []string `json:"detectModels"` + // Picked, for detect with no Model: the models the form has + // picked and not saved yet, one of which each API is asked + // for before the saved picks or the vendor's list (#1545) + Picked []string `json:"picked"` // Account and Allow, for accountmodels: the account (its name) // or key (its id) and the models it alone serves, none for all // the provider's (#474) @@ -1522,10 +1526,17 @@ func providerRoutes(mux *http.ServeMux, w Windows) { case "detect": // which APIs answer at the URL typed (Model, or one from the // list for each), the form as it stands: a new provider's, - // or a saved one's with its key when none is typed + // or a saved one's with its key when none is typed — a copy + // not saved yet with the key of the one it copies (CopyOf), + // as its Add takes it. Nothing is written: the provider is + // only asked, never kept, listed or routed to (#1545). var p provider.Provider - if in.ID != "" { - saved, err := provider.Find(in.ID) + from := in.ID + if from == "" && req.New { + from = req.CopyOf + } + if from != "" { + saved, err := provider.Find(from) if err != nil { fail(rw, err) return @@ -1556,7 +1567,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) defer cancel() - got, err := p.Detect(ctx, req.Base, req.Model) + got, err := p.Detect(ctx, req.Base, req.Model, req.Picked...) if err != nil { fail(rw, err) return diff --git a/internal/gui/providers_detect_draft_test.go b/internal/gui/providers_detect_draft_test.go new file mode 100644 index 000000000..e9a2d0d5d --- /dev/null +++ b/internal/gui/providers_detect_draft_test.go @@ -0,0 +1,203 @@ +package gui + +import ( + "encoding/json" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/provider" +) + +// #1545 (thedavidweng): Detect APIs and Each picked model ask with the +// form as it stands, not saved: a new provider's typed key and the models +// typed in its Models field, a saved one's picks not saved yet with its +// saved key when none is typed, and a copy not saved yet with the key of +// the one it copies. None of it writes anything: providers.json and the +// rest of the config folder are as they were, and no provider is added. +func TestProviderDetectDraft(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + var mu sync.Mutex + var asked []string + // a relay with no model list (its /v1/models is a 404) that chats only + // for the model typed in the form, "draft-m", and the keys it knows + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var body struct{ Model string } + json.Unmarshal(b, &body) + auth := r.Header.Get("Authorization") + mu.Lock() + asked = append(asked, r.Method+" "+r.URL.Path+" "+body.Model+" "+auth) + mu.Unlock() + if r.URL.Path != "/v1/chat/completions" { + http.NotFound(w, r) + return + } + if auth != "Bearer sk-typed" && auth != "Bearer sk-saved" { + http.Error(w, `{"error":{"message":"invalid api key"}}`, http.StatusUnauthorized) + return + } + if body.Model != "draft-m" { + http.Error(w, `{"error":{"message":"model not found"}}`, http.StatusNotFound) + return + } + io.WriteString(w, `{"choices":[{"message":{"content":"hi"}}]}`) + })) + defer up.Close() + mux := http.NewServeMux() + providerRoutes(mux, nil) + post := func(h http.Handler, action, body string) *httptest.ResponseRecorder { + t.Helper() + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/"+action, strings.NewReader(body))) + return w + } + type answer struct { + Results []provider.Detection + Models []provider.ModelDetection + } + detect := func(body string) answer { + t.Helper() + w := post(mux, "detect", body) + if w.Code != 200 { + t.Fatalf("%s: %d %s", body, w.Code, w.Body) + } + var got answer + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + return got + } + chat := func(rs []provider.Detection) provider.Detection { + for _, r := range rs { + if r.Protocol == provider.Chat { + return r + } + } + t.Fatalf("no chat in %+v", rs) + return provider.Detection{} + } + keys := func() []string { + mu.Lock() + defer mu.Unlock() + var out []string + for _, a := range asked { + if strings.Contains(a, "/chat/completions") { + out = append(out, a[strings.LastIndex(a, " ")+1:]) + } + } + asked = nil + return out + } + base := up.URL + "/v1" + + // a new provider: the key just typed and the models typed in its form + if r := chat(detect(`{"typed":true,"key":"sk-typed","base":"` + base + `","model":"","picked":["draft-m","other"]}`).Results); !r.OK || r.Model != "draft-m" { + t.Fatalf("new, models typed: %+v", r) + } + if got := keys(); len(got) != 1 || got[0] != "sk-typed" { + t.Fatalf("new asked with %v", got) + } + got := detect(`{"typed":true,"key":"sk-typed","base":"` + base + `","detectModels":["draft-m","gone"]}`) + if len(got.Models) != 2 || !chat(got.Models[0].Results).OK || chat(got.Models[1].Results).OK { + t.Fatalf("new, each model: %+v", got.Models) + } + keys() + if ps := provider.All(); len(ps) != 0 { + t.Fatalf("a detection added %v", ps) + } + + // a saved provider, its key shown masked and not typed again, with a + // model picked in the form and not saved + if w := post(mux, "save", `{"id":"relay","name":"Relay","key":"sk-saved","chat":"`+base+`","models":["saved-m"],"new":true}`); w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + keys() + before := draftFiles(t, appdir.Config()) + if _, ok := before["providers.json"]; !ok { + t.Fatalf("no providers.json in %v", before) + } + if r := chat(detect(`{"id":"relay","typed":true,"key":"","base":"` + base + `","model":"","picked":["draft-m"]}`).Results); !r.OK || r.Model != "draft-m" { + t.Fatalf("saved, a pick not saved: %+v", r) + } + if got := keys(); len(got) != 1 || got[0] != "sk-saved" { + t.Fatalf("saved asked with %v", got) + } + // a copy of it, not saved yet, with no key typed: the copied one's key + if r := chat(detect(`{"new":true,"copyOf":"relay","typed":true,"key":"","base":"` + base + `","model":"","picked":["draft-m"]}`).Results); !r.OK { + t.Fatalf("copy: %+v", r) + } + if got := keys(); len(got) != 1 || got[0] != "sk-saved" { + t.Fatalf("copy asked with %v", got) + } + // a key typed over the saved one is the one asked with + if r := chat(detect(`{"new":true,"copyOf":"relay","typed":true,"key":"sk-typed","base":"` + base + `","model":"draft-m"}`).Results); !r.OK { + t.Fatalf("copy, key typed: %+v", r) + } + if got := keys(); len(got) != 1 || got[0] != "sk-typed" { + t.Fatalf("copy with a key typed asked with %v", got) + } + if after := draftFiles(t, appdir.Config()); !draftSame(before, after) { + t.Fatalf("a detection wrote to the config folder:\nbefore %v\nafter %v", draftNames(before), draftNames(after)) + } + if ps := provider.All(); len(ps) != 1 || ps[0].ID != "relay" || len(ps[0].Models) != 1 { + t.Fatalf("providers now %+v", ps) + } + + // magpie web: without its key a draft probe is turned away, and the + // vendor is never asked + guarded := webHandler("3999", "0123456789abcdef-1545", time.Hour, mux) + if w := post(guarded, "detect", `{"typed":true,"key":"sk-typed","base":"`+base+`","picked":["draft-m"]}`); w.Code != http.StatusUnauthorized { + t.Fatalf("no web key: %d %s", w.Code, w.Body) + } + if got := keys(); len(got) != 0 { + t.Fatalf("asked without the web key: %v", got) + } +} + +// draftFiles is every file under dir, by its path, with its bytes. +func draftFiles(t *testing.T, dir string) map[string]string { + t.Helper() + out := map[string]string{} + filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return nil + } + b, _ := os.ReadFile(p) + rel, _ := filepath.Rel(dir, p) + out[filepath.ToSlash(rel)] = string(b) + return nil + }) + return out +} + +func draftSame(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if w, ok := b[k]; !ok || w != v { + return false + } + } + return true +} + +func draftNames(m map[string]string) []string { + var out []string + for k := range m { + out = append(out, k) + } + return out +} diff --git a/internal/gui/tests/provider-detect-draft.test.cjs b/internal/gui/tests/provider-detect-draft.test.cjs new file mode 100644 index 000000000..1a343c603 --- /dev/null +++ b/internal/gui/tests/provider-detect-draft.test.cjs @@ -0,0 +1,172 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #1545 (thedavidweng): Detect APIs and Each picked model ask with the +// form as it stands, before any Save. A custom provider being added sends +// the URL and key typed and the models typed in its Models field — Detect +// APIs as the models to try (picked), Each picked model as the models to +// ask — with no id, and nothing posts a save. What is missing (the URL, the +// models) and what went wrong are said in place under the buttons, not in +// a toast. No click moves the page, there is no native