provider: a relay URL typed without its /v1 (CRS's …/openai) is tested, detected and listed under it (Cyrus_4433 on X)

Cyrus_4433 added a claude-relay-service provider as OpenAI compatible at
http://<ip>:55088/openai. The list couldn't be fetched and Test models
said "gpt-6.1-sol: 404 · Not Found". From CRS's src/app.js and routes:
/openai mounts unifiedRoutes (POST /v1/chat/completions) and
openaiRoutes (/responses, /v1/responses); /api mounts GET /v1/models.
There is no /openai/chat/completions or /openai/models, and anything
unrouted is 404 {"error":"Not Found",...}. magpie asked base +
/chat/completions, i.e. /openai/chat/completions.

- probe: a Chat/Responses 404 at an unversioned base equal to the
  provider's URL is asked once more at base/v1/... (missingV1; not
  accounts, Azure, Bedrock, Vertex). Answered OK there, the saved URL
  takes /v1 (setV1) and the result carries it (Result.V1); Detect uses
  it as the base; the editor's URL field follows (draft.onV1) so Save
  doesn't undo it. A 404 at both stays the first 404.
- catalog: an unversioned …/openai base is also listed at
  <origin>/api/v1/models (RelayOpenAIList), and fixV1 adds /v1 when the
  list answered there.

Run (WSL magpie-desktop via wsl-run; mote's sshd reset every
connection this session):
- at 630b0de98 (this change on 987eac0aa): go vet -tags nogui (linux),
  CGO_ENABLED=0 GOOS=windows and GOOS=darwin go vet of the touched
  packages ok; go test -tags nogui ./internal/catalog ./internal/provider
  ./internal/gui ok; GUI chromium + webkit: provider-test-v1 (new: en/zh,
  900/420px, Test models and a chip's Test this model, then Save posts
  .../v1), model-test-one, model-test-why, model-test-stop,
  provider-detect-models, provider-base-api: 54 pass, 0 fail.
- rebased again on 6b92824ff, the core went 366 bytes over its budget;
  five provider-test comments cut in app.js pay for it, no raise
  (core 1,533,689 <= 1,533,802). At this head: internal/gui's budget
  tests, internal/catalog and internal/provider, and the
  provider-test-v1 and model-test-one GUI files: all ok, 20 pass 0 fail.
- models-works-only is red, also red on untouched origin/main
  7c41060c2: #4391 (commented there). gofmt -l clean.

Broken by hand: missingV1 returning false and RelayOpenAIList returning
"" -> TestCRSOpenAIBaseTestsUnderV1/ListsAtAPI/DetectsV1 red with
"gpt-6.1-sol: 404 Not Found"; restored.

Not tried: a real CRS instance (the fake follows its routes and 404
body); the gateway itself doesn't retry /v1 for a provider never
tested, listed or detected since this release (the user presses Test
models or types .../openai/v1); the full suite runs after the tag; no
Windows or macOS run.
This commit is contained in:
yetone
2026-11-10 18:07:27 +08:00
parent 185ee6d5c1
commit 2fbead7983
9 changed files with 334 additions and 9 deletions
File diff suppressed because one or more lines are too long
+19
View File
@@ -603,10 +603,29 @@ func listURLs(base string, anthropic bool) []string {
}
add(root + "/v1/models")
add(root + "/models")
if u := RelayOpenAIList(base); u != "" {
add(u)
}
}
return urls
}
// RelayOpenAIList is the model list of a relay that serves OpenAI's API
// under …/openai with no /v1 in the base, and its list at the root's
// /api/v1/models alone: claude-relay-service mounts its unified routes
// (/v1/chat/completions) and Codex's (/responses, /v1/responses) under
// /openai, and the models list on /api and /claude only (src/app.js,
// src/routes/api.js). "" for any other base. A list found there means
// chat is at the base's /v1 (Cyrus_4433 on X: …/openai was asked
// …/openai/chat/completions and answered 404 Not Found).
func RelayOpenAIList(base string) string {
base = strings.TrimRight(base, "/")
if !strings.HasSuffix(base, "/openai") || Versioned(base) {
return ""
}
return strings.TrimSuffix(base, "/openai") + "/api/v1/models"
}
// Versioned reports whether an API base URL has a version in its path — a
// segment like v1, v3, v4 or v1beta — and so names the vendor's API as it
// is, with no /v1 left out of it.
+9 -6
View File
@@ -9487,8 +9487,6 @@ function drawEditor(p, presetID) {
b.dataset.api = v;
seg.append(b);
}
// the protocol the base URL is for, shown as picked: by its button,
// or by a detection taken (useDetected)
const showApi = (v) => {
draft.api = v;
url.value = draft[apiField[v]] || "";
@@ -9524,6 +9522,10 @@ function drawEditor(p, presetID) {
showApi(v || draft.api);
draft.onModelPrefs?.(); // the APIs a model can be given follow the URLs
};
draft.onV1 = (rs) => {
for (const x of rs) if (x.v1 && (draft[x.protocol] || "").trim().replace(/\/+$/, "") + "/v1" === x.v1) draft[x.protocol] = x.v1;
showApi(draft.api);
};
curlBase = (api, base) => {
carried = null;
draft[apiField[api]] = base;
@@ -11211,23 +11213,24 @@ function detectAPIs(p, base, use) {
return box;
}
// modelTestWhy: why p's models can't be tested one by one (providerJSON.modelTest), or ""
function modelTestWhy(p) {
if (p.modelTest === "decide") return t("A classifier's models aren't sent test requests: Test under Endpoints asks Jev's endpoint for them.");
if (p.modelTest === "own-api") return t("{name} is reached through its own API, which magpie translates each agent request for, so a test request can't be sent to it on its own. Ask the model from an agent to try it.", { name: p.name });
return "";
}
// modelTests: each provider's Test models answers by id, null while asked
const modelTests = {};
// testsOn: a provider's tests under way, by run; Stop ends them on the server too (RIck)
const testsOn = {};
async function provTest(id, body) {
const run = Math.random().toString(36).slice(2), ac = new AbortController(), on = testsOn[id] ||= new Map();
on.set(run, ac);
testBtns(id);
try { return await api("provider/test", { ...body, id, run }, null, ac.signal); }
try {
const r = await api("provider/test", { ...body, id, run }, null, ac.signal);
if (editing === id && r?.results?.some((x) => x.v1)) draft?.onV1?.(r.results);
return r;
}
catch (e) { e.stopped = ac.signal.aborted; throw e; }
finally { on.delete(run); testBtns(id); }
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,91 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A relay typed without the /v1 it serves OpenAI's API under (Cyrus_4433 on
// X: claude-relay-service at http://host:port/openai, every model 404 Not
// Found): Test models is answered under …/openai/v1 and says so (v1), and the
// editor's Base URL takes it, so Save keeps …/openai/v1 instead of putting
// the URL back as typed. Right-click's one-model test does the same. In
// English and Chinese, Chromium and WebKit, at 900px and 420px.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const BASE = "http://216.36.117.18:55088/openai";
const IDS = ["gpt-6.1-sol", "gpt-6-sol"];
const relay = {
id: "my-relay", name: "My Relay", icon: "generic", chat: BASE, responses: "", anthropic: "", catalog: "",
models: IDS.map((id) => ({ id, name: id, on: true })), chosen: IDS, agents: [], fallback: [], headers: {},
key: { set: true, masked: "cr_1…4209" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", listOff: true,
};
function serve(lang, posts) {
const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname.startsWith("/api/provider/")) {
const body = route.request().postDataJSON();
posts.push({ path: url.pathname, body });
if (url.pathname === "/api/provider/test") return json({ results: body.test.map((id) => ({ ok: true, ms: 321, model: id, protocol: "chat", status: 200, v1: BASE + "/v1" })) });
return json({});
}
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
for (const width of [900, 420]) {
for (const how of ["all", "one"]) {
test(`${engine} ${lang} ${width}px ${how}: a test answered under /v1 sets the Base URL`, async (t) => {
const zh = lang === "zh";
const L = { all: zh ? "测试模型" : "Test models", item: zh ? "测试此模型" : "Test this model", save: zh ? "保存" : "Save" };
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
t.after(() => browser.close());
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "My Relay" }).click();
const ed = page.locator(".editor");
await ed.locator(".base-url").waitFor();
assert.equal(await ed.locator(".base-url").inputValue(), BASE);
const tested = () => posts.filter((p) => p.path === "/api/provider/test").length;
if (how === "all") {
await ed.locator(".mfoot").getByRole("button", { name: L.all, exact: true }).click();
} else {
const chip = ed.locator(".mchips .mchip", { hasText: IDS[0] });
await chip.scrollIntoViewIfNeeded();
await page.waitForTimeout(150); // the editor's scroll settles (model-test-one)
await chip.click({ button: "right" });
await page.locator(".pop.row-menu").getByRole("menuitem", { name: L.item }).click();
}
for (let i = 0; i < 60 && !tested(); i++) await page.waitForTimeout(50);
assert.equal(tested(), 1);
await page.waitForFunction((want) => document.querySelector(".editor .base-url")?.value === want, BASE + "/v1");
await ed.locator(":scope > .bar").getByRole("button", { name: L.save, exact: true }).click();
for (let i = 0; i < 60 && !posts.some((p) => p.path === "/api/provider/save"); i++) await page.waitForTimeout(50);
const save = posts.find((p) => p.path === "/api/provider/save");
assert(save, "saved");
assert.equal(save.body.chat, BASE + "/v1", "Save keeps the /v1 the test found");
assert.deepEqual(errors, []);
});
}
}
}
}
+157
View File
@@ -0,0 +1,157 @@
package provider
import (
"context"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/agentenv"
)
// crsRelay answers as claude-relay-service routes (src/app.js): OpenAI's
// chat at /openai/v1/chat/completions (and /api/v1/…), Codex's Responses
// at /openai/responses and /openai/v1/responses, the model list at
// /api/v1/models alone, and its own 404 body for anything else.
func crsRelay(t *testing.T) (*httptest.Server, func() []string) {
var mu sync.Mutex
var asked []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, r.Method+" "+r.URL.Path)
mu.Unlock()
io.Copy(io.Discard, r.Body)
switch r.Method + " " + r.URL.Path {
case "POST /openai/v1/chat/completions", "POST /api/v1/chat/completions":
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"id":"c","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`))
case "POST /openai/responses", "POST /openai/v1/responses":
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"id":"r","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}]}`))
case "GET /api/v1/models", "GET /claude/v1/models":
w.Write([]byte(`{"object":"list","data":[{"id":"gpt-5.6-sol","object":"model"},{"id":"claude-sonnet-4-5-20250929","object":"model"}]}`))
default:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(`{"error":"Not Found","message":"Route ` + r.URL.Path + ` not found","timestamp":"2026-11-10T00:00:00.000Z"}`))
}
}))
t.Cleanup(srv.Close)
return srv, func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), asked...)
}
}
func crsHome(t *testing.T) {
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("PATH", h)
for _, v := range agentenv.Vars {
t.Setenv(v, "")
}
}
// Cyrus_4433 on X: a claude-relay-service added as OpenAI compatible at
// http://host:port/openai, models typed in by hand, and Test models said
// "gpt-6.1-sol: 404 · Not Found" — magpie asked …/openai/chat/completions,
// which CRS doesn't serve. The model is now asked at …/openai/v1 too, its
// answer there is the model's, and the base is saved with the /v1.
func TestCRSOpenAIBaseTestsUnderV1(t *testing.T) {
crsHome(t)
srv, _ := crsRelay(t)
base := srv.URL + "/openai"
if err := Save(Provider{ID: "my-relay", Name: "My Relay", Chat: base, Key: "cr_1x4209", Models: []string{"gpt-6.1-sol", "gpt-6-sol"}, ListOff: true}); err != nil {
t.Fatal(err)
}
p, err := Find("my-relay")
if err != nil {
t.Fatal(err)
}
rs := p.TestModels(context.Background(), []string{"gpt-6.1-sol", "gpt-6-sol"})
for _, r := range rs {
if !r.OK {
t.Errorf("%s: %d %s", r.Model, r.Status, r.Error)
}
}
if rs[0].V1 != base+"/v1" {
t.Errorf("v1 %q", rs[0].V1)
}
if q, _ := Find("my-relay"); q.Chat != base+"/v1" {
t.Errorf("chat base %q, want %s/v1", q.Chat, base)
}
}
// Its model list is at the root's /api/v1/models: fetched there, and the
// base given its /v1 by it, before any test.
func TestCRSOpenAIBaseListsAtAPI(t *testing.T) {
crsHome(t)
srv, asked := crsRelay(t)
base := srv.URL + "/openai"
if err := Save(Provider{ID: "my-relay", Name: "My Relay", Chat: base, Key: "cr_1x4209"}); err != nil {
t.Fatal(err)
}
p, _ := Find("my-relay")
ms, err := p.Fetch(context.Background())
if err != nil {
t.Fatalf("fetch: %v (asked %v)", err, asked())
}
if len(ms) == 0 {
t.Fatal("no models")
}
if q, _ := Find("my-relay"); q.Chat != base+"/v1" {
t.Errorf("chat base %q, want %s/v1", q.Chat, base)
}
}
// Detect at the URL as typed finds chat under its /v1 and says that base.
func TestCRSOpenAIBaseDetectsV1(t *testing.T) {
crsHome(t)
srv, _ := crsRelay(t)
base := srv.URL + "/openai"
ds, err := Provider{ID: "new-relay", Name: "New", Key: "cr_1x4209"}.Detect(context.Background(), base, "gpt-6.1-sol")
if err != nil {
t.Fatal(err)
}
for _, d := range ds {
if d.Protocol == Chat && (!d.OK || d.Base != base+"/v1") {
t.Errorf("chat: ok %v base %q error %q", d.OK, d.Base, d.Error)
}
}
}
// A 404 that is the model's (a relay that doesn't serve it, at the right
// path) is the answer: /v1 is asked, answers 404 too, and the base stays.
func TestModel404KeepsBase(t *testing.T) {
crsHome(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
if strings.HasPrefix(r.URL.Path, "/relay/v1/") {
w.Write([]byte(`{"error":"Not Found"}`))
return
}
w.Write([]byte(`{"error":{"message":"model gpt-x not found"}}`))
}))
defer srv.Close()
base := srv.URL + "/relay"
if err := Save(Provider{ID: "r", Name: "R", Chat: base, Key: "k", Models: []string{"gpt-x"}, ListOff: true}); err != nil {
t.Fatal(err)
}
p, _ := Find("r")
r := p.TestModels(context.Background(), []string{"gpt-x"})[0]
if r.OK || r.Status != 404 || !strings.Contains(r.Error, "gpt-x") || r.V1 != "" {
t.Errorf("%+v", r)
}
if q, _ := Find("r"); q.Chat != base {
t.Errorf("chat base changed to %q", q.Chat)
}
}
+7
View File
@@ -116,6 +116,13 @@ func (p Provider) Detect(ctx context.Context, base, model string, picked ...stri
}()
}
wg.Wait()
for i := range out {
if out[i].V1 != "" {
// answered under the /v1 the URL was typed without: the
// base the editor keeps for it is that one
out[i].Base = out[i].V1
}
}
return out, nil
}
+8 -1
View File
@@ -1351,9 +1351,16 @@ func (p Provider) planMedia(ids func(*Region) []string, draws, films bool, serve
// for under one there (catalog.FetchAt), and none is added here.
func (p Provider) fixV1(base, at string) string {
base = strings.TrimRight(strings.TrimSpace(base), "/")
if base == "" || at != base+"/v1/models" || catalog.Versioned(base) {
if base == "" || at != base+"/v1/models" && at != catalog.RelayOpenAIList(base) || catalog.Versioned(base) {
return base
}
return p.setV1(base)
}
// setV1 is base with the /v1 it was given without, set on p's OpenAI
// URLs that were base, as saved; base when p can't be saved.
func (p Provider) setV1(base string) string {
base = strings.TrimRight(strings.TrimSpace(base), "/")
fixed := base + "/v1"
f, err := read()
if err != nil {
+41
View File
@@ -38,6 +38,9 @@ type Result struct {
// otherAPI: the vendor said the model isn't served on the API asked
// (catalog.WrongEndpoint), so another may be asked instead
otherAPI bool
// V1 is the base the request was answered at once the /v1 it was
// typed without was added (missingV1): the editor's URL takes it
V1 string `json:"v1,omitempty"`
}
// Test sends the smallest possible request to each endpoint the vendor
@@ -781,6 +784,26 @@ func (p Provider) ownRequests(ctx context.Context, kind string) context.Context
// write the status alone, so a failed test's row said nothing of why
// (ysm119 on Discord: "no answer", and no error to find anywhere).
func probe(ctx context.Context, p Provider, proto Protocol, url string, body []byte, model string, wait time.Duration) Result {
r := probeAt(ctx, p, proto, url, body, model, wait)
if r.Status != http.StatusNotFound {
return r
}
// a relay given without the /v1 it serves OpenAI's API under
// (Cyrus_4433 on X: claude-relay-service's …/openai, whose chat is at
// …/openai/v1/chat/completions, answered every model 404 Not Found)
// is asked there too, and an answer there sets the base right, so
// the gateway's requests go there as well
if base, at, ok := p.missingV1(proto, url); ok {
if v := probeAt(ctx, p, proto, at, body, model, wait); v.OK {
p.setV1(base)
v.V1 = base + "/v1"
return v
}
}
return r
}
func probeAt(ctx context.Context, p Provider, proto Protocol, url string, body []byte, model string, wait time.Duration) Result {
r := probeOnce(ctx, p, proto, url, body, model, wait)
if proto == Chat && r.Status == http.StatusBadRequest {
// a vendor whose 400 names the other reply-length field as the
@@ -794,6 +817,24 @@ func probe(ctx context.Context, p Provider, proto Protocol, url string, body []b
return r
}
// missingV1 is the base of url, proto's endpoint at an OpenAI-style base
// with no version in its path, and the same endpoint under that base's
// /v1. Only a key's own base is asked so: a sign-in, a plugin, Azure,
// Bedrock and Vertex AI have paths of their own, and a versioned base
// (…/api/plan/v3) is the vendor's API as written (fixV1).
func (p Provider) missingV1(proto Protocol, url string) (base, at string, ok bool) {
end := map[Protocol]string{Chat: "/chat/completions", Responses: "/responses"}[proto]
if end == "" || p.Account != nil || p.IsAzure() || p.IsBedrock() || p.IsVertex() {
return "", "", false
}
base, found := strings.CutSuffix(url, end)
if !found || base == "" || catalog.Versioned(base) || strings.TrimRight(base, "/") != strings.TrimRight(p.Base(proto), "/") {
return "", "", false
}
base = strings.TrimRight(base, "/")
return base, base + "/v1" + end, true
}
func probeOnce(ctx context.Context, p Provider, proto Protocol, url string, body []byte, model string, wait time.Duration) (r Result) {
ctx = WithModel(ctx, p.ID, model) // the model's own headers, as its requests carry
r = Result{Protocol: proto, Model: model}