address: a scheme already typed is kept once, in any letter case (eachg0 on X)

Remote magpie and System One addresses got "http://" put in front by
several normalisers that each tested for "://" their own way, and one
saved "http://http://host" stayed that way until the address was deleted
and added again.

provider.WithScheme (new, internal/provider/scheme.go) is the one rule:
trim, add the default scheme when none is there, lowercase http/https,
and collapse a repeated http/https prefix to the innermost one. Path and
trailing slash are left as written; "host:3425/x?u=http://y" has no
scheme. It is used by provider.normalize (every provider URL, on read),
remoteMagpieEndpoints, DetectDecide, parseAddress and gui remoteAddr.
app.js has withScheme as its mirror, used by hostOf, localAddress,
vertexRoot and respellURL (whose gemini/openai regexes now match any
letter case).

Old data: an address saved with a doubled scheme is repaired when it is
read (provider.normalize for providers and System One addresses,
loadRemote for remote-magpie.json). The file is written out correctly on
the next save; nobody has to delete and re-add. Reading alone does not
rewrite the file.

app.js: the core script budget is met without a raise;
withScheme was cut down to fit (final package run after the rebase on fd9033cbf: gui and provider ok).

Run:
- go test ./internal/provider ./internal/gui ./internal/settings
  ./internal/cli on mote: ok, except TestCoreScriptBudget (284 over),
  fixed by shortening the JS and re-run alone: ok.
- gofmt -l, go vet darwin, GOOS=windows, GOOS=linux -tags nogui: clean.
- GUI on mica, chromium and webkit: scheme-once, local-address,
  custom-systemone-url, decide-endpoint-label, azure-endpoint, remote-*,
  i18n-keys, connect-address-kept: 158 of 164 pass; the 6 reds are
  "Remote magpie asks for the other magpie's address", red the same at
  origin/main 5e933e153 (#6099).
- add-sheet-custom, provider-fetch-again, provider-gemini: 14 of 54 red
  on mica, the same 14 at origin/main ab98228cc (#5232, #6209).
Red on the old code: scheme_test.go, remote_test.go (Go) and
scheme-once.test.cjs (withScheme undefined) were run against an
origin/main copy and failed there.

Not tried: the place that produced "http://http://" was not found by
reading (every guard used Contains("://")), so this hardens every
normaliser instead of one site; no real remote magpie was used; the full
GUI suite was not run.
This commit is contained in:
yetone
2026-11-12 19:48:02 +08:00
parent 7199afbb66
commit 6055f626e8
10 changed files with 262 additions and 24 deletions
+12 -7
View File
@@ -9213,10 +9213,7 @@ const apiLabel = (proto) => (PROTOS.find(([k]) => k === proto) || [])[1] || prot
// vertexBase: a Vertex AI provider's address (provider.vertexBase), "" till its project is one
// vertexRoot: the base URL typed as a root, as provider.vertexRootOf keeps it
function vertexRoot(u) {
u = (u || "").trim().replace(/\/+$/, "");
if (!u) return "";
if (!u.includes("://")) u = "https://" + u;
return u.replace(/\/v1(?:beta1)?$/, "");
return withScheme(u, "https").replace(/\/+$/, "").replace(/\/v1(?:beta1)?$/, "");
}
function vertexBase(v, keyed) {
const project = (v?.project || "").trim().toLowerCase(), loc = (v?.location || "").trim().toLowerCase() || "global";
@@ -15430,7 +15427,7 @@ function workspaceOf(tmpl, url) {
}
function respellURL(u, api) {
u = u.trim().replace(/\/+$/, "");
u = withScheme(u).replace(/\/+$/, "");
if (api === "anthropic") return u.replace(/\/v1$/, "");
if (api === "decide") u = u.replace(/\/systemone$/, "");
if (api === "gemini") return /^https?:\/\/[^/]+\/v1$/.test(u) ? u + "beta" : /^https?:\/\/[^/]+$/.test(u) ? u + "/v1beta" : u;
@@ -15616,7 +15613,15 @@ function slug(s) { return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^
// groupSlug: a routing group's id as provider.GroupSlug derives it, the
// dots kept (gpt-6.1-sol, #968).
function groupSlug(s) { return s.toLowerCase().replace(/[^a-z0-9.]+/g, "-").replace(/\.{2,}/g, ".").replace(/^[-.]+|[-.]+$/g, ""); }
function hostOf(u) { try { return new URL(u.includes("://") ? u : "https://" + u).host; } catch { return ""; } }
// withScheme: a typed address with its scheme certain, as provider.WithScheme
// has it: http or https already there stays, in any letter case, and is never
// given a second; one saved twice ("http://http://host") is one again; none
// gets def (none, when def is empty).
function withScheme(s, def) {
s = (s || "").trim();
return /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s.replace(/^(?:https?:\/\/)*(https?)(?=:\/\/)/i, (_, x) => x.toLowerCase()) : s && def ? def + "://" + s : s;
}
function hostOf(u) { try { return new URL(withScheme(u, "https")).host; } catch { return ""; } }
// localAddress is a local server's address as typed, as provider.AtAddress
// takes it: its origin, http when no scheme is given, any path dropped; ""
@@ -15626,7 +15631,7 @@ function localAddress(s) {
if (!s) return "";
if (/\s/.test(s)) return null;
try {
const u = new URL(s.includes("://") ? s : "http://" + s);
const u = new URL(withScheme(s, "http"));
if ((u.protocol !== "http:" && u.protocol !== "https:") || !u.hostname) return null;
return u.protocol + "//" + u.host;
} catch { return null; }
+6 -3
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
@@ -50,6 +51,10 @@ func loadRemote() (remoteConf, error) {
if err := json.Unmarshal(b, &c); err != nil {
return remoteConf{}, fmt.Errorf("%s: %w", remoteFile(), err)
}
// an address saved with its scheme twice reads as one
if c.URL != "" {
c.URL = provider.WithScheme(c.URL, "https")
}
return c, nil
}
@@ -88,9 +93,7 @@ func remoteAddr(raw string) (addr, key string, err error) {
if raw == "" {
return "", "", errors.New("type the other magpie's address")
}
if !strings.Contains(raw, "://") {
raw = "https://" + raw
}
raw = provider.WithScheme(raw, "https")
u, err := url.Parse(raw)
if err != nil || u.Host == "" || u.Hostname() == "" {
return "", "", fmt.Errorf("%q isn't an address such as https://magpie.example.com", raw)
+20
View File
@@ -6,6 +6,7 @@ import (
"net/http/cookiejar"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
@@ -45,6 +46,10 @@ func TestRemoteAddr(t *testing.T) {
{"http://nas.local:3430", "http://nas.local:3430/", "", ""},
{"http://server:3430", "http://server:3430/", "", ""},
{"https://example.com/magpie/", "https://example.com/magpie/", "", ""},
{"HTTP://192.168.1.20:3430/", "http://192.168.1.20:3430/", "", ""},
{"HTTPS://Magpie.example.com/?k=abc", "https://Magpie.example.com/", "abc", ""},
{"http://http://192.168.1.20:3430", "http://192.168.1.20:3430/", "", ""},
{"https://https://magpie.example.com", "https://magpie.example.com/", "", ""},
{"http://magpie.example.com:3430", "", "", "name on the internet"},
{"https://u:p@magpie.example.com", "", "", "user name"},
{"ftp://example.com", "", "", "http:// or https://"},
@@ -64,6 +69,21 @@ func TestRemoteAddr(t *testing.T) {
}
}
// An address saved with its scheme twice (eachg0 on X) reads as one.
func TestRemoteReadsADoubledScheme(t *testing.T) {
onePortHome(t)
if err := os.MkdirAll(filepath.Dir(remoteFile()), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(remoteFile(), []byte(`{"url":"http://http://192.168.1.20:3430/","key":"k"}`), 0o600); err != nil {
t.Fatal(err)
}
c, err := loadRemote()
if err != nil || c.URL != "http://192.168.1.20:3430/" {
t.Errorf("loadRemote = %+v, %v", c, err)
}
}
// xuanwo on X: the app opens a server's magpie, its routing and usage, in
// a window. The key is checked against that magpie's own page before the
// window opens, kept 0600 on this computer, never read back into the page,
+100
View File
@@ -0,0 +1,100 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// An address that already has its scheme is never given another (eachg0 on
// X: a Remote magpie's "http://…" became "http://http://…"): http or https,
// in any letter case, with or without a trailing slash. One saved twice
// reads as one. The helpers are tried in the page, and a local server's
// Server address is typed each way and the Endpoints follow.
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 presets = [
{ id: "openai", name: "OpenAI", icon: "openai", kind: "vendor", chat: "https://api.openai.com/v1", added: false },
{ id: "ollama", name: "Ollama", icon: "ollama", kind: "local", chat: "http://localhost:11434/v1", anthropic: "http://localhost:11434", noKey: true, note: "your local models", added: false },
{ id: "lmstudio", name: "LM Studio", icon: "lmstudio", kind: "local", chat: "http://localhost:1234/v1", noKey: true, note: "local server, port 1234 by default", added: true },
{ id: "omlx", name: "oMLX", icon: "omlx", kind: "local", chat: "http://localhost:8000/v1", responses: "http://localhost:8000/v1", anthropic: "http://localhost:8000", decide: "http://localhost:8000/v1", noKey: true, note: "local server, port 8000 by default", added: true },
];
const base = {
icon: "generic", chat: "", responses: "", anthropic: "", catalog: "",
models: [{ id: "qwen3", name: "Qwen3", on: true }], agents: [], fallback: [], headers: {},
key: { set: false, masked: "", optional: true }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false, unredacted: false,
};
// an oMLX on another computer, and one whose URLs were set apart (another
// app's import): its Anthropic URL on another host than its chat one
const studio = { ...base, id: "omlx", name: "oMLX", icon: "omlx", preset: "omlx", host: "192.168.1.5:8000", chat: "http://192.168.1.5:8000/v1", responses: "http://192.168.1.5:8000/v1", anthropic: "http://192.168.1.5:8000", decide: "http://192.168.1.5:8000/v1" };
// an LM Studio where the preset puts it
const home = { ...base, id: "lmstudio", name: "LM Studio", icon: "lmstudio", preset: "lmstudio", host: "localhost:1234", chat: "http://localhost:1234/v1" };
const apart = { ...base, id: "omlx-2", name: "oMLX Apart", icon: "omlx", preset: "omlx", host: "10.0.0.2:8000", chat: "http://10.0.0.2:8000/v1", anthropic: "http://10.0.0.3:9000" };
function server(lang, saves, asks) {
const list = { providers: [studio, apart, home], presets, excluded: [], gateway: { running: true, window: true } };
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: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(list);
if (url.pathname === "/api/provider/save") {
saves.push(route.request().postDataJSON());
return json(list);
}
// a Test asks with the URLs as typed, before a Save
if (url.pathname === "/api/provider/test") {
asks.push(route.request().postDataJSON());
return json({ results: [] });
}
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a scheme already there is kept once", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const saves = [], asks = [];
const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server("en", saves, asks));
await page.goto("http://magpie.test/?view=providers");
const ws = await page.evaluate(() => [
"192.168.1.20:3425", "http://192.168.1.20:3425", "HTTP://192.168.1.20:3425/", "Http://h:1/v1/",
"http://http://192.168.1.20:3425", "https://http://h", "HTTPS://HTTP://h:1/", " http://h:1 ", "", "ftp://box",
].map((u) => withScheme(u, "http")));
assert.deepEqual(ws, [
"http://192.168.1.20:3425", "http://192.168.1.20:3425", "http://192.168.1.20:3425/", "http://h:1/v1/",
"http://192.168.1.20:3425", "http://h", "http://h:1/", "http://h:1", "", "ftp://box",
]);
const las = await page.evaluate(() => ["http://h:1", "HTTP://h:1/", "http://http://h:1", "https://h", "h:1", ""].map(localAddress));
assert.deepEqual(las, ["http://h:1", "http://h:1", "http://h:1", "https://h", "http://h:1", ""]);
const rs = await page.evaluate(() => [respellURL("HTTP://h:1/", "openai"), respellURL("http://http://h/", "anthropic"), respellURL("Http://h", "gemini"), respellURL("http://http://h:1/systemone", "decide")]);
assert.deepEqual(rs, ["http://h:1/v1", "http://h", "http://h/v1beta", "http://h:1/v1"]);
// a saved oMLX on another computer, its Server address typed each way
const ed = page.locator(".editor");
await page.locator(".row.provider", { hasText: /^oMLX$|oMLX(?! Apart)/ }).first().click();
await ed.locator(".ehead").waitFor();
const address = ed.locator("input.address");
const eps = async () => (await ed.locator(".eps code").allTextContents()).join(" ");
for (const typed of ["http://10.0.0.9:9000", "HTTP://10.0.0.9:9000/", "http://http://10.0.0.9:9000", "https://10.0.0.9:9000"]) {
await address.fill(typed);
const scheme = typed.toLowerCase().startsWith("https") ? "https" : "http";
assert.equal(await eps(), `${scheme}://10.0.0.9:9000/v1 ${scheme}://10.0.0.9:9000/v1 ${scheme}://10.0.0.9:9000 ${scheme}://10.0.0.9:9000/v1`, typed);
}
assert.deepEqual(errors, []);
});
}
+1 -3
View File
@@ -205,9 +205,7 @@ func (q Provider) detectOne(proto Protocol, m string, wait time.Duration) (Detec
// the one p is asked with when none is given, and says how it answered.
func (p Provider) DetectDecide(ctx context.Context, model string) Detection {
p.Decide = strings.TrimSuffix(strings.TrimRight(strings.TrimSpace(p.Decide), "/"), "/systemone")
if p.Decide != "" && !strings.Contains(p.Decide, "://") {
p.Decide = "https://" + p.Decide
}
p.Decide = WithScheme(p.Decide, "https")
if model = strings.TrimSpace(model); model == "" {
model = p.Jev()
}
+1 -4
View File
@@ -72,10 +72,7 @@ func parseAddress(addr string) (*url.URL, error) {
if strings.ContainsAny(addr, " \t\r\n") {
return nil, bad
}
s := addr
if !strings.Contains(s, "://") {
s = "http://" + s
}
s := WithScheme(addr, "http")
u, err := url.Parse(s)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" {
return nil, bad
+3 -4
View File
@@ -1865,10 +1865,9 @@ func normalize(p Provider) Provider {
}
p.remoteMagpieEndpoints()
for _, u := range []*string{&p.Chat, &p.Responses, &p.Anthropic, &p.Gemini, &p.Decide, &p.Website, &p.KeysURL} {
*u = strings.TrimRight(strings.TrimSpace(*u), "/")
if *u != "" && !strings.Contains(*u, "://") {
*u = "https://" + *u
}
// a scheme already there stays (WithScheme), whatever its case; one
// saved twice by an older editor is one again
*u = strings.TrimRight(WithScheme(*u, "https"), "/")
}
// the Anthropic base is the root /v1/messages is asked at: one given as
// .../v1 or .../v1/messages, as vendors' docs often show it, would have
+1 -3
View File
@@ -88,9 +88,7 @@ func (p *Provider) remoteMagpieEndpoints() {
if root == "" {
return
}
if !strings.Contains(root, "://") {
root = "http://" + root
}
root = strings.TrimRight(WithScheme(root, "http"), "/")
for _, suf := range []string{
"/v1/messages/count_tokens", "/v1/messages",
"/v1/chat/completions", "/v1/responses", "/v1/systemone",
+44
View File
@@ -0,0 +1,44 @@
package provider
import "strings"
// WithScheme is a typed address with its scheme made certain: one that is
// there already, http or https in any letter case, stays (its scheme in
// lower case) and is never given a second; one with none gets def. A
// scheme saved twice ("http://http://host", from before this was
// checked) is one again. Other schemes are left as they are. The rest of
// the address, its path and trailing slash, is not touched.
func WithScheme(raw, def string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
scheme, rest := splitScheme(raw)
if scheme == "" {
return def + "://" + raw
}
// the repeats: "http://https://host" is host, at the last scheme said
for {
inner, more := splitScheme(rest)
if inner != "http" && inner != "https" || scheme != "http" && scheme != "https" {
break
}
scheme, rest = inner, more
}
return scheme + "://" + rest
}
// splitScheme cuts a leading "http://" or "https://" (any case) or another
// "scheme://" off s; scheme is lower case, "" when s has none.
func splitScheme(s string) (scheme, rest string) {
i := strings.Index(s, "://")
if i <= 0 {
return "", s
}
for _, c := range s[:i] {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '+' || c == '-' || c == '.') {
return "", s
}
}
return strings.ToLower(s[:i]), s[i+3:]
}
+74
View File
@@ -0,0 +1,74 @@
package provider
import "testing"
func TestWithScheme(t *testing.T) {
for in, want := range map[string]string{
"192.168.1.20:3425": "http://192.168.1.20:3425",
"http://192.168.1.20:3425": "http://192.168.1.20:3425",
"HTTP://192.168.1.20:3425/": "http://192.168.1.20:3425/",
"Http://h:1/v1/": "http://h:1/v1/",
"https://h": "https://h",
"HTTPS://h/": "https://h/",
"http://http://192.168.1.20:3425": "http://192.168.1.20:3425",
"http://http://h:1/": "http://h:1/",
"https://https://h": "https://h",
"HTTP://HTTP://h": "http://h",
" http://h:1 ": "http://h:1",
"localhost:3425/x?u=http://y": "http://localhost:3425/x?u=http://y",
"": "",
} {
if got := WithScheme(in, "http"); got != want {
t.Errorf("WithScheme(%q) = %q, want %q", in, got, want)
}
}
}
// A Remote magpie's address typed with its scheme, in any case, with or
// without the slash, is one scheme in every URL; one saved twice by an older
// editor reads as one (eachg0 on X).
func TestRemoteMagpieSchemeOnce(t *testing.T) {
for _, in := range []string{
"http://192.168.1.20:3425", "HTTP://192.168.1.20:3425/", "Http://192.168.1.20:3425/v1",
"http://http://192.168.1.20:3425", "http://http://192.168.1.20:3425/v1/", "192.168.1.20:3425",
} {
for _, field := range []string{"chat", "decide", "anthropic"} {
p := Provider{ID: "r", Preset: RemoteMagpiePreset}
switch field {
case "chat":
p.Chat, p.Responses = in, in
case "decide":
p.Decide = in
case "anthropic":
p.Anthropic = in
}
p = normalize(p)
for name, got := range map[string]string{"chat": p.Chat, "responses": p.Responses, "decide": p.Decide, "anthropic": p.Anthropic} {
want := "http://192.168.1.20:3425"
if name != "anthropic" {
want += "/v1"
}
if got != want {
t.Errorf("%s=%q: %s = %q, want %q", field, in, name, got, want)
}
}
}
}
}
// A custom provider's System One address with its scheme already there.
func TestDecideSchemeOnce(t *testing.T) {
p := normalize(Provider{ID: "c", Chat: "https://api.example.com/v1", Decide: "HTTPS://https://api.example.com/v1/"})
if p.Decide != "https://api.example.com/v1" {
t.Errorf("Decide = %q", p.Decide)
}
}
func TestAddressSchemeOnce(t *testing.T) {
for _, in := range []string{"HTTP://h:1/", "http://http://h:1", "http://h:1"} {
u, err := parseAddress(in)
if err != nil || u.String() != "http://h:1" {
t.Errorf("parseAddress(%q) = %v, %v", in, u, err)
}
}
}