gui, provider: Detect APIs and Each picked model ask with the form as it stands before any Save, and say what is missing in place (#1545, thedavidweng)
What the user saw: on a custom provider being added (or a Duplicate not
added yet), "Each picked model" said "Pick models first" although models
were typed in the Models field, and on a relay with no model list "Detect
APIs" said "no model to try" on every API. Both worked only after a Save,
when the models became the provider's own. A Duplicate not added sent no
key at all. Hints for a missing URL or models went to the toast at the top.
Why: chosenIds() reads a saved provider's chips only, not a new one's
draft.extra; Detect picked its model from the saved provider's list or the
vendor's, never from the form; an unsaved copy posted no id, so the server
had no key to fill in.
What changed:
- provider.Detect takes the form's picks (picked ...string) and tries one
of them per API before the saved list or the vendor's.
- /api/provider/detect takes `picked`, and for `new` + `copyOf` fills
what the draft left empty from the copied provider, as a saved edit
fills from its id. It still only reads: nothing is written, no provider
is added, no route or health check changes. No new route; magpie web's
key guard is the same.
- detectAPIs sends the add form's models (draft.extra) for a new
provider, copyOf for an unsaved copy, and says a missing URL, missing
models, a refusal, and "none answered, and no API key is typed" inline
under the buttons (amber/red text, no border). One new string in zh,
zh-TW, ja, de.
- docs/subsystems/providers-accounts.md: the detection row says so.
What was run:
- TestProviderDetectDraft (new): new draft with picked models on a relay
with no list, Each picked model, saved provider with a masked key and an
unsaved pick, an unsaved copy with no key typed and with a key typed,
config folder bytes unchanged, provider.All unchanged, magpie web without
its key -> 401 and the vendor never asked. Fails on the old detect.go /
providers.go ("no model to try").
- provider-detect-draft.test.cjs (new): chromium + webkit, en/zh/zh-TW/ja/
de, 900 and 360px, 20/20 pass; no scroll on click, no <select>, no
left-border, no sideways scroll, nothing but detect posted. Fails on the
old app.js (no inline hint).
- provider-detect, provider-detect-models, provider-add-models,
duplicate-pause, i18n-keys: 29/29, both engines.
- go test -tags nogui ./internal/gui/ ./internal/provider/ ok; gofmt -l
clean; GOOS=linux and GOOS=windows go vet -tags nogui ok.
- Real use: sandbox `magpie web` (nogui build) with a fake upstream. New
provider, relay with no model list: Detect APIs and Each picked model
answered with the typed key and models, no providers.json written. Saved
provider with its key masked plus a model typed in its add box: both
asked with the saved key. Duplicate not added: asked with the copied
key. providers.json bytes unchanged. Without the web key: 401, the
upstream got nothing.
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 <select> and no
|
||||
// left-border accent, and at 360px nothing runs off the side. In every
|
||||
// language magpie speaks.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const fsp = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const URL_ = "https://relay.example.com/v1";
|
||||
|
||||
// the words as i18n.js has them
|
||||
const ctx = {};
|
||||
vm.runInNewContext(fs.readFileSync(path.join(assets, "i18n.js"), "utf8") + "\nthis.I18N = I18N;", ctx);
|
||||
const tr = (lang, s) => (lang === "en" ? s : ctx.I18N[lang][s] || assert.fail(`${lang} has no "${s}"`));
|
||||
|
||||
function serve(lang, posts, answer) {
|
||||
const providers = { providers: [{ id: "anthropic", name: "Anthropic", icon: "anthropic", preset: "anthropic", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data, status = 200) => route.fulfill({ json: data, status });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:false};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
|
||||
if (url.pathname.startsWith("/api/provider/")) {
|
||||
const body = route.request().postDataJSON();
|
||||
posts.push({ path: url.pathname, body });
|
||||
if (url.pathname === "/api/provider/detect") return answer(body, json);
|
||||
return json(providers);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
try { await route.fulfill({ body: await fsp.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
// a relay that chats with m-a only
|
||||
const one = (m, proto) => proto === "chat" && m === "m-a"
|
||||
? { protocol: proto, ok: true, ms: 140, model: m, base: URL_ }
|
||||
: { protocol: proto, ok: false, status: 404, error: "model not found", model: m, base: proto === "anthropic" ? "https://relay.example.com" : URL_ };
|
||||
const PROTOS = ["chat", "responses", "anthropic", "gemini"];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const width of [900, 360]) {
|
||||
test(`${engine} ${lang} ${width}px: Detect APIs and Each picked model ask the form not saved`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fsp.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.locator(".editor.new").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-provider-detect-draft.png`) }).catch(() => {});
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posts = [];
|
||||
let refuse = false, keyless = false;
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts, (body, json) => {
|
||||
if (refuse) return json({ error: "the base URL must start with http:// or https://" }, 400);
|
||||
if (body.detectModels) {
|
||||
const models = body.detectModels.map((m) => ({ model: m, results: PROTOS.map((p) => one(m, p)) }));
|
||||
return json({ results: PROTOS.map((_, i) => models.find((x) => x.results[i].ok)?.results[i] || models[0].results[i]), models });
|
||||
}
|
||||
const m = body.model || (body.picked || [])[0] || "";
|
||||
if (keyless) return json({ results: PROTOS.map((p) => ({ ...one(m, p), ok: false, status: 401, error: "invalid api key" })) });
|
||||
return json({ results: PROTOS.map((p) => one(m, p)) });
|
||||
}));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
const T = (s) => tr(lang, s);
|
||||
await page.locator("#addProvider").click();
|
||||
await page.locator("#addSheet .custom-foot .custom").click();
|
||||
const ed = page.locator(".editor.new");
|
||||
await ed.locator(".detect").waitFor();
|
||||
const detect = ed.getByRole("button", { name: T("Detect APIs"), exact: true });
|
||||
const each = ed.getByRole("button", { name: T("Each picked model"), exact: true });
|
||||
const out = ed.locator(".detect-out");
|
||||
const say = out.locator(".detect-say");
|
||||
const detects = () => posts.filter((p) => p.path === "/api/provider/detect");
|
||||
|
||||
// a click that leaves the page, and the button, where they were
|
||||
const still = async (loc, what) => {
|
||||
await loc.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(120);
|
||||
const before = await loc.evaluate((e) => e.getBoundingClientRect().top);
|
||||
const y = await page.evaluate(() => [scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop)].join());
|
||||
await loc.click();
|
||||
await page.waitForTimeout(250);
|
||||
assert.equal(await loc.evaluate((e) => e.getBoundingClientRect().top), before, what + " moved");
|
||||
assert.equal(await page.evaluate(() => [scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop)].join()), y, what + " scrolled the page");
|
||||
};
|
||||
const inPlace = async (kind, text, what) => {
|
||||
await say.waitFor();
|
||||
assert.equal(await say.getAttribute("class"), `hint detect-say ${kind}`, what);
|
||||
assert.equal(await say.textContent(), text, what);
|
||||
// in the form, under the buttons, not a toast at the top
|
||||
const [row, hint] = await Promise.all([ed.locator(".detect-row").first().boundingBox(), say.boundingBox()]);
|
||||
assert(hint.y >= row.y + row.height - 1, what + " is under the buttons");
|
||||
assert(hint.x >= 0 && hint.x + hint.width <= width + 0.5, what + " runs off the side");
|
||||
};
|
||||
|
||||
// nothing typed: the URL is asked for, in place, and nothing posted
|
||||
await still(detect, "Detect APIs with no URL");
|
||||
await inPlace("warn", T("Type the base URL first"), "no URL");
|
||||
// no model picked yet: said in place
|
||||
await still(each, "Each picked model with no models");
|
||||
await inPlace("warn", T("Pick models first, or type one and press Detect APIs"), "no models");
|
||||
// models, and still no URL
|
||||
await ed.locator(".add-models .detect-row input").fill("m-a, m-b");
|
||||
await still(each, "Each picked model with no URL");
|
||||
await inPlace("warn", T("Type the base URL first"), "no URL, each");
|
||||
assert.equal(detects().length, 0, "nothing asked without a URL or models");
|
||||
|
||||
// the URL, key and models typed in the add form, never saved
|
||||
await ed.locator('input[type="url"][placeholder="https://…/v1"]').first().fill(URL_);
|
||||
await ed.locator('input[type="password"]').first().fill("sk-typed");
|
||||
await still(detect, "Detect APIs");
|
||||
await out.locator('.ep[data-api="chat"] .res.ok').waitFor();
|
||||
let sent = detects().at(-1).body;
|
||||
assert.equal(sent.key, "sk-typed", "the key typed");
|
||||
assert.equal(sent.chat, "", "the URL typed is sent as base");
|
||||
assert.equal(sent.base, URL_);
|
||||
assert.equal(sent.model, "");
|
||||
assert.deepEqual(sent.picked, ["m-a", "m-b"], "the models typed are the ones tried");
|
||||
assert(!sent.id && !sent.copyOf, "no saved provider is asked");
|
||||
assert.equal(await say.count(), 0, "the hint gives way to the answer");
|
||||
|
||||
await still(each, "Each picked model");
|
||||
await out.locator(".detect-grid").waitFor();
|
||||
sent = detects().at(-1).body;
|
||||
assert.deepEqual(sent.detectModels, ["m-a", "m-b"], "each model typed is asked");
|
||||
assert.equal(sent.key, "sk-typed");
|
||||
assert.equal(await out.locator('.dg-cell.ok[data-model="m-a"][data-api="chat"]').count(), 1);
|
||||
assert.equal(await out.locator('.dg-cell.bad[data-model="m-b"][data-api="chat"]').count(), 1);
|
||||
|
||||
// what went wrong, in place
|
||||
refuse = true;
|
||||
await still(detect, "Detect APIs refused");
|
||||
await inPlace("err", "the base URL must start with http:// or https://", "a refusal");
|
||||
assert.equal(await page.locator("#status").evaluate((e) => e.textContent.includes("http://")), false, "not in the toast");
|
||||
|
||||
// no key typed, and nothing answers: said, as the likely cause
|
||||
refuse = false; keyless = true;
|
||||
await ed.locator('input[type="password"]').first().fill("");
|
||||
await still(detect, "Detect APIs with no key");
|
||||
await out.locator(".detect-acts .hint").waitFor();
|
||||
assert.equal(await out.locator(".detect-acts .hint").textContent(), T("None answered, and no API key is typed: paste the key under API key and detect again"));
|
||||
assert.equal(detects().at(-1).body.key, "");
|
||||
|
||||
assert.equal(posts.filter((p) => p.path !== "/api/provider/detect").length, 0, `nothing but detect posted: ${posts.map((p) => p.path)}`);
|
||||
assert.equal(await page.locator("select").count(), 0, "no native select");
|
||||
const border = await page.evaluate(() => [...document.querySelectorAll(".editor.new .detect, .editor.new .detect *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1));
|
||||
assert.deepEqual(border, [], "no left-border accent");
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "no sideways scroll");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,12 +71,14 @@ var ErrNoURL = errors.New("type the base URL first")
|
||||
// Detect asks each of Chat, Responses, Anthropic and Gemini at the URL p has for
|
||||
// it, else at base as it takes it (DetectBase), the smallest request, and
|
||||
// says what each answered, in that order. model is asked on all three;
|
||||
// with none, one from p's list is picked for each — a Claude model on
|
||||
// Anthropic's, an OpenAI one on Responses — and with no list, the vendor
|
||||
// is asked for one first (a GET of its models, which costs nothing).
|
||||
// Only those URLs are asked, and only a key's provider: a sign-in's API
|
||||
// is its agent's.
|
||||
func (p Provider) Detect(ctx context.Context, base, model string) ([]Detection, error) {
|
||||
// with none, one is picked for each — a Claude model on Anthropic's, an
|
||||
// OpenAI one on Responses — from picked, the models the editor's form has
|
||||
// and hasn't saved yet (#1545: a relay with no model list is asked for
|
||||
// the models typed in the form, not only after a Save), else from p's
|
||||
// list, and with no list the vendor is asked for one first (a GET of its
|
||||
// models, which costs nothing). Only those URLs are asked, and only a
|
||||
// key's provider: a sign-in's API is its agent's.
|
||||
func (p Provider) Detect(ctx context.Context, base, model string, picked ...string) ([]Detection, error) {
|
||||
q, err := p.detecting(base)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -85,7 +87,14 @@ func (p Provider) Detect(ctx context.Context, base, model string) ([]Detection,
|
||||
model = strings.TrimSpace(model)
|
||||
var ids []string
|
||||
if model == "" {
|
||||
ids = q.detectModels(ctx)
|
||||
for _, m := range picked {
|
||||
if m = strings.TrimSpace(m); m != "" && !slices.Contains(ids, m) {
|
||||
ids = append(ids, m)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
ids = q.detectModels(ctx)
|
||||
}
|
||||
}
|
||||
out := make([]Detection, len(detectProtocols))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
Reference in New Issue
Block a user