provider, gui: a provider imported under a subscription's name comes in beside it, and a colliding name can be changed in the picker (#1487, Dudung1018)
Dudung1018's CC Switch had third-party providers named as magpie's subscriptions are: a Pi proxy "workbuddy", an OpenCode relay "Claude". Reproduced in a sandbox GUI with a CC Switch db in cc-switch's real schema: - the default import answered 400 "workbuddy is the id of the workbuddy subscription; pick another name", after some picks had already been written. That is why the reporter later saw "already added" and couldn't find where the key went. - the "Replace it" choice on a row named "claude" wrote the relay's models as the Claude subscription's picks, and dropped its key and address. What changed: - importapps: a row whose id is a subscription's (signed in or not), or magpie's own, is marked reserved. It is picked like a new one and added under a free id beside the subscription. Replace is refused for it, and key mode never joins an account or a provider at another address. - the picker has a name field on every row whose name collides. A renamed row is added under its new name, and Replace is no longer offered for it. "Add as another key" names the provider the key went to. - import links (magpie://import, magpie import) named or id'd as a subscription get a free id. - the new sub-line is in en, zh, zh-TW, ja and de. What was run: - sandbox GUI on the old build (the 400, the partial write, the Replace case), then on the new one. The same picks gave 200 ["Relay 1487", "Claude (findcg)", "workbuddy"]: findcg got one more key, and relay-1487 and workbuddy-2 were added at their own addresses. - importapps_reserved_test.go: 4 tests on the real cc-switch schema, all red on the old code. - import-collision.test.cjs: chromium and webkit, in en/zh/zh-TW/ja/de, at 900 and 390px, 20/20 passing and red on the old assets. provider-discovery.test.cjs still passes. - go test -tags nogui ./... green, gofmt -l, and GOOS=linux and windows go vet for internal/provider and internal/gui.
This commit is contained in:
@@ -2997,6 +2997,7 @@ body.panel .modal { padding: 16px 12px; }
|
||||
.editor.importapps .approw .name .from { font-size: 11px; color: var(--muted); }
|
||||
.editor.importapps .approw .sub { font-size: 11.5px; color: var(--muted); overflow-wrap: anywhere; }
|
||||
.editor.importapps .approw .segs { margin-top: 3px; max-width: 100%; overflow-x: auto; }
|
||||
.editor.importapps .approw input.appname[type="text"] { margin: 3px 0 0; flex: none; width: 100%; max-width: 280px; box-sizing: border-box; font-size: 12.5px; padding: 4px 8px; border-radius: 6px; }
|
||||
.editor.importapps .approw .segs .opt { white-space: nowrap; flex: none; }
|
||||
.editor.importapps .apptag { flex: none; font-size: 11px; color: var(--fg-2); background: var(--pill); border-radius: 5px; padding: 1px 6px; margin-top: 1px; }
|
||||
.editor.importapps .bar .note { font-size: 12px; color: var(--muted); }
|
||||
|
||||
@@ -8931,7 +8931,9 @@ async function openImportApps(discovered) {
|
||||
for (const s of sources) for (const it of s.items) {
|
||||
if (it.skip || it.status === "same") continue;
|
||||
const offered = !(discovered instanceof Set) || discovered.has(it.fingerprint);
|
||||
picks[s.id + "\n" + it.ref] = { on: offered && !it.off && (it.status !== "taken" || !!it.keyOf), mode: it.keyOf ? "key" : "add" };
|
||||
// one named as a subscription (claude, workbuddy) comes in beside
|
||||
// it, so it is picked like a new one (#1487)
|
||||
picks[s.id + "\n" + it.ref] = { on: offered && !it.off && (it.status !== "taken" || !!it.keyOf || !!it.reserved), mode: it.keyOf ? "key" : "add" };
|
||||
}
|
||||
if (!importingApps) return;
|
||||
const tab = sources.find((s) => s.items.some((it) => picks[s.id + "\n" + it.ref]?.on))?.id;
|
||||
@@ -9050,7 +9052,7 @@ function renderImportApps(ia) {
|
||||
for (const [k, v] of Object.entries(ia.picks)) {
|
||||
if (!v.on) continue;
|
||||
const [source, ref] = k.split("\n");
|
||||
picks.push({ source, ref, mode: v.mode });
|
||||
picks.push({ source, ref, mode: v.mode, ...(v.name?.trim() ? { name: v.name.trim() } : {}) });
|
||||
}
|
||||
go.classList.add("busy");
|
||||
try {
|
||||
@@ -9105,13 +9107,38 @@ function importAppRow(ia, s, it, recount, boxes) {
|
||||
who.append(el("div", "sub", bits.join(" · ")));
|
||||
if (pick && it.off) who.append(el("div", "sub", t(it.off)));
|
||||
if (pick && (it.keyOf || it.status === "taken")) {
|
||||
const opts = [];
|
||||
if (it.keyOf) opts.push(["key", t("Add as another key")]);
|
||||
opts.push(["add", t(it.status === "taken" ? "Keep both" : "Add as a new provider")]);
|
||||
if (it.status === "taken") opts.push(["replace", t("Replace it")]);
|
||||
who.append(el("div", "sub", t("magpie has {name} already", { name: it.existing })));
|
||||
const sg = segs(opts, pick.mode, (m) => { pick.mode = m; if (!pick.on) { pick.on = box.checked = true; recount(); } });
|
||||
sg.onclick = (e) => e.preventDefault(); // a click on a choice is not a click on the checkbox
|
||||
const renamed = () => !!pick.name?.trim() && pick.name.trim() !== p.name;
|
||||
const choices = () => {
|
||||
const opts = [];
|
||||
if (it.keyOf) opts.push(["key", t("Add as another key")]);
|
||||
opts.push(["add", t(it.status === "taken" && !it.reserved && !renamed() ? "Keep both" : "Add as a new provider")]);
|
||||
// a subscription is never replaced by a provider of keys, nor is
|
||||
// anything by one the user gave a name of its own (#1487)
|
||||
if (it.status === "taken" && !it.reserved && !renamed()) opts.push(["replace", t("Replace it")]);
|
||||
// one way in alone needs no choice
|
||||
if (opts.length === 1) { pick.mode = opts[0][0]; const none = el("span"); none.hidden = true; return none; }
|
||||
const sg = segs(opts, pick.mode, (m) => { pick.mode = m; if (!pick.on) { pick.on = box.checked = true; recount(); } });
|
||||
sg.onclick = (e) => e.preventDefault(); // a click on a choice is not a click on the checkbox
|
||||
return sg;
|
||||
};
|
||||
who.append(el("div", "sub", t(it.reserved ? "{name} is a subscription in magpie; this one comes in beside it as a provider of its own" : "magpie has {name} already", { name: it.existing })));
|
||||
let sg = choices();
|
||||
if (it.status === "taken") {
|
||||
// a name that collides can be changed right here (#1487)
|
||||
const nm = input(pick.name ?? p.name, t("e.g. My Relay"));
|
||||
nm.className = "appname";
|
||||
nm.setAttribute("aria-label", t("Name"));
|
||||
nm.onclick = (e) => e.preventDefault(); // typing in it never ticks the row
|
||||
nm.oninput = () => {
|
||||
pick.name = nm.value;
|
||||
if (renamed() && pick.mode === "replace") pick.mode = "add";
|
||||
const next = choices();
|
||||
sg.replaceWith(next);
|
||||
sg = next;
|
||||
if (renamed() && !pick.on) { pick.on = box.checked = true; recount(); }
|
||||
};
|
||||
who.append(nm);
|
||||
}
|
||||
who.append(sg);
|
||||
}
|
||||
let tag = null;
|
||||
|
||||
@@ -1501,6 +1501,7 @@ const I18N = {
|
||||
"1 model": "1 个模型",
|
||||
"Add as another key": "作为另一个密钥加入",
|
||||
"magpie has {name} already": "magpie 里已有 {name}",
|
||||
"{name} is a subscription in magpie; this one comes in beside it as a provider of its own": "{name} 是 magpie 里的订阅;这一项会作为单独的供应商加在它旁边",
|
||||
"Add as a new provider": "作为新的供应商",
|
||||
"Keep both": "两个都保留",
|
||||
"Replace it": "替换原有的",
|
||||
@@ -5576,6 +5577,7 @@ const I18N = {
|
||||
"1 model": "1 個模型",
|
||||
"Add as another key": "作為另一個金鑰加入",
|
||||
"magpie has {name} already": "magpie 裡已有 {name}",
|
||||
"{name} is a subscription in magpie; this one comes in beside it as a provider of its own": "{name} 是 magpie 裡的訂閱;這一項會作為單獨的供應商加在它旁邊",
|
||||
"Add as a new provider": "作為新的供應商",
|
||||
"Keep both": "兩個都保留",
|
||||
"Replace it": "替換原有的",
|
||||
@@ -9627,6 +9629,7 @@ const I18N = {
|
||||
"1 model": "1 個のモデル",
|
||||
"Add as another key": "別のキーとして追加",
|
||||
"magpie has {name} already": "magpie にはすでに {name} があります",
|
||||
"{name} is a subscription in magpie; this one comes in beside it as a provider of its own": "{name} は magpie のサブスクリプションです。これはその横に別のプロバイダとして追加されます",
|
||||
"Add as a new provider": "新しいプロバイダとして追加",
|
||||
"Keep both": "両方残す",
|
||||
"Replace it": "置き換える",
|
||||
@@ -13697,6 +13700,7 @@ const I18N = {
|
||||
"1 model": "1 Modell",
|
||||
"Add as another key": "Als weiteren Schlüssel hinzufügen",
|
||||
"magpie has {name} already": "magpie hat {name} bereits",
|
||||
"{name} is a subscription in magpie; this one comes in beside it as a provider of its own": "{name} ist ein Abo in magpie; dieser Eintrag kommt als eigener Anbieter daneben hinzu",
|
||||
"Add as a new provider": "Als neuen Anbieter hinzufügen",
|
||||
"Keep both": "Beide behalten",
|
||||
"Replace it": "Ersetzen",
|
||||
|
||||
@@ -37,7 +37,7 @@ func importAppsRoutes(mux *http.ServeMux) {
|
||||
for _, it := range s.Items {
|
||||
// Match openImportApps' default selection: disabled entries and
|
||||
// ID collisions without an add-key option need a manual choice.
|
||||
if it.Skip == "" && it.Status != "same" && it.Off == "" && (it.Status != "taken" || it.KeyOf != "") {
|
||||
if it.Skip == "" && it.Status != "same" && it.Off == "" && (it.Status != "taken" || it.KeyOf != "" || it.Reserved) {
|
||||
out = append(out, candidate{importFingerprint(s.ID, it), s.Name})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
// A provider another app has, named as one magpie has (#1487, Dudung1018):
|
||||
// one named as a subscription (a relay called "claude", a proxy called
|
||||
// "workbuddy") is picked like a new one and is never offered to replace the
|
||||
// subscription; a name that collides can be changed right in the row, and
|
||||
// a renamed one is added under that name, never in another's place. All
|
||||
// APIs and keys are fixtures.
|
||||
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 = process.env.ASSET_DIR || path.resolve(__dirname, "../assets");
|
||||
const engines = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"];
|
||||
const langs = ["en", "zh", "zh-TW", "ja", "de"];
|
||||
|
||||
const sources = () => [{
|
||||
id: "cc-switch", name: "CC Switch", path: "/fixture/.cc-switch/cc-switch.db", found: true,
|
||||
items: [
|
||||
{ ref: "claude/cl2", from: "Claude Code", fingerprint: "cl2", status: "taken", reserved: true, existing: "Claude",
|
||||
provider: { id: "claude", name: "claude", anthropic: "https://relay-1487.example.com", key: "sk-…beef", models: ["claude-sonnet-5"] } },
|
||||
{ ref: "pi/wb", from: "Pi", fingerprint: "wb", status: "taken", reserved: true, existing: "workbuddy",
|
||||
provider: { id: "workbuddy", name: "workbuddy", chat: "http://127.0.0.1:7863/v1", key: "sk-5…3432", models: ["glm-5"] } },
|
||||
{ ref: "opencode/mine", from: "OpenCode", fingerprint: "mine", status: "taken", existing: "My Relay",
|
||||
provider: { id: "my-relay", name: "My Relay", chat: "https://other.example.com/v1", key: "sk-…1234", models: [] } },
|
||||
],
|
||||
}];
|
||||
|
||||
async function fixture(t, engine, lang, width) {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
|
||||
page.setDefaultTimeout(7000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.stack || e.message));
|
||||
await page.route("**/*", async (route) => {
|
||||
const req = route.request(), url = new URL(req.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 === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
|
||||
if (url.pathname === "/api/importapps/discovery") return json([]);
|
||||
if (url.pathname === "/api/importapps") {
|
||||
if (req.method() === "GET") return json(sources());
|
||||
posts.push(req.postDataJSON());
|
||||
return json({ added: ["x"], state: { providers: [], presets: [], excluded: [], gateway: { running: true, window: true } } });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/trace") return new Promise(() => {});
|
||||
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: "" }); }
|
||||
});
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-import-collision.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.waitForFunction(() => typeof openImportApps === "function");
|
||||
await page.evaluate(() => openImportApps());
|
||||
const picker = page.locator("#modal .importapps");
|
||||
await picker.locator(".approw").first().waitFor();
|
||||
return { page, picker, posts };
|
||||
}
|
||||
|
||||
const opts = (row) => row.locator(".segs .opt").allTextContents();
|
||||
|
||||
for (const engine of engines) {
|
||||
for (const lang of langs) {
|
||||
for (const width of [900, 390]) {
|
||||
test(`${engine} ${lang} ${width}px: a name that collides can be changed in the row, and a subscription is never replaced`, async (t) => {
|
||||
const { page, picker, posts } = await fixture(t, engine, lang, width);
|
||||
const T = (s, v) => page.evaluate(([s, v]) => t(s, v), [s, v]);
|
||||
const claude = picker.locator(".approw", { hasText: "Claude Code" });
|
||||
const wb = picker.locator(".approw", { hasText: "127.0.0.1:7863" });
|
||||
const mine = picker.locator(".approw", { hasText: "OpenCode" });
|
||||
|
||||
// named as a subscription: picked, said so, added beside it only
|
||||
for (const row of [claude, wb]) {
|
||||
assert.equal(await row.locator('input[type="checkbox"]').isChecked(), true);
|
||||
assert.deepEqual(await opts(row), [], "no choice: it can only come in beside the subscription");
|
||||
assert.equal(await row.locator("input.appname").isVisible(), true);
|
||||
}
|
||||
assert.equal(await claude.locator(".sub", { hasText: await T("{name} is a subscription in magpie; this one comes in beside it as a provider of its own", { name: "Claude" }) }).count(), 1);
|
||||
// a name of the user's own provider: off until chosen, Replace offered
|
||||
assert.equal(await mine.locator('input[type="checkbox"]').isChecked(), false);
|
||||
assert.deepEqual(await opts(mine), [await T("Keep both"), await T("Replace it")]);
|
||||
|
||||
// renamed right there: picked, and Replace is gone
|
||||
await mine.locator(".segs .opt", { hasText: await T("Replace it") }).click();
|
||||
await mine.locator("input.appname").fill("Other Relay");
|
||||
assert.equal(await mine.locator('input[type="checkbox"]').isChecked(), true);
|
||||
assert.deepEqual(await opts(mine), [], "renamed, it can only be added");
|
||||
// typing in the field never ticks or unticks the row
|
||||
await claude.locator("input.appname").click();
|
||||
assert.equal(await claude.locator('input[type="checkbox"]').isChecked(), true);
|
||||
await claude.locator("input.appname").fill("Findcg Claude");
|
||||
|
||||
// the rows fit the window
|
||||
const fits = await picker.evaluate((ed) => [...ed.querySelectorAll(".approw")].every((r) => r.scrollWidth <= r.clientWidth + 1) && ed.getBoundingClientRect().right <= innerWidth);
|
||||
assert(fits, "rows fit the window");
|
||||
|
||||
await picker.locator(".bar button.primary").click();
|
||||
await page.waitForFunction(() => !importingApps);
|
||||
assert.deepEqual(posts.length, 1);
|
||||
const picks = Object.fromEntries(posts[0].picks.map((p) => [p.ref, p]));
|
||||
assert.deepEqual(picks["claude/cl2"], { source: "cc-switch", ref: "claude/cl2", mode: "add", name: "Findcg Claude" });
|
||||
assert.deepEqual(picks["pi/wb"], { source: "cc-switch", ref: "pi/wb", mode: "add" });
|
||||
assert.deepEqual(picks["opencode/mine"], { source: "cc-switch", ref: "opencode/mine", mode: "add", name: "Other Relay" });
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -289,7 +289,7 @@ for (const engine of engines) {
|
||||
assert.equal(control.reads, 0);
|
||||
if (await page.locator("#addSheet").isHidden()) await page.locator("#addProvider").click();
|
||||
await page.locator("#addSheet").getByRole("button", { name: "Import…", exact: true }).click();
|
||||
const picker = page.locator("#modal .importapps"), box = picker.locator(".approw input");
|
||||
const picker = page.locator("#modal .importapps"), box = picker.locator(".approw input[type=\"checkbox\"]");
|
||||
await box.waitFor();
|
||||
assert.equal(await box.isChecked(), false);
|
||||
assert.equal(await box.isDisabled(), false, "manual import still allows selecting the configuration");
|
||||
|
||||
@@ -50,17 +50,24 @@ type AppImport struct {
|
||||
// this one can join it as one more key instead of being a provider
|
||||
// of its own.
|
||||
KeyOf string `json:"keyOf,omitempty"`
|
||||
Off string `json:"off,omitempty"` // why it isn't picked by default
|
||||
Skip string `json:"skip,omitempty"` // why it can't be imported at all
|
||||
// Reserved: its id is a subscription's (claude, workbuddy…), whose
|
||||
// name it happens to have. It can't replace that subscription, only
|
||||
// come in as a provider of its own beside it.
|
||||
Reserved bool `json:"reserved,omitempty"`
|
||||
Off string `json:"off,omitempty"` // why it isn't picked by default
|
||||
Skip string `json:"skip,omitempty"` // why it can't be imported at all
|
||||
}
|
||||
|
||||
// AppPick is one entry the user chose, and how it comes in: as a provider
|
||||
// ("add", beside any with its id), in place of the one with its id
|
||||
// ("replace"), or as one more key of the provider KeyOf names ("key").
|
||||
// Name is the name the user gave it in the picker, when its own collides
|
||||
// with one magpie has (#1487); a renamed entry is added, never replaces.
|
||||
type AppPick struct {
|
||||
Source string `json:"source"`
|
||||
Ref string `json:"ref"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// appReaders are the apps magpie knows, by name as the picker lists them.
|
||||
@@ -117,17 +124,43 @@ func ImportFromApps(picks []AppPick) ([]string, error) {
|
||||
continue
|
||||
}
|
||||
p := it.Provider
|
||||
mode := pk.Mode
|
||||
if name := strings.TrimSpace(pk.Name); name != "" && name != p.Name {
|
||||
// renamed in the picker: its id follows the new name, unless it
|
||||
// is a preset's, which keeps the preset's id
|
||||
p.Name = name
|
||||
if p.Preset == "" {
|
||||
p.ID = cmp.Or(Slug(name), p.ID)
|
||||
}
|
||||
if mode != "key" {
|
||||
mode = "add"
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case pk.Mode == "key" && it.KeyOf != "":
|
||||
if h, err := Find(it.KeyOf); err == nil && sameProvider(*h, p) {
|
||||
case mode == "key" && it.KeyOf != "":
|
||||
h, err := Find(it.KeyOf)
|
||||
if err != nil {
|
||||
return added, errorf("%s: %v", p.Name, err)
|
||||
}
|
||||
if sameProvider(*h, p) {
|
||||
continue // picked twice, from two apps
|
||||
}
|
||||
// a key joins a provider only at its own address: one taken
|
||||
// to another host would be sent there
|
||||
if h.Account != nil || !sameProvider(Provider{Key: p.Key, Chat: h.Chat, Responses: h.Responses, Anthropic: h.Anthropic, Headers: h.Headers}, p) {
|
||||
return added, errorf("%s: %s isn't at %s; add it as a provider of its own", p.Name, h.Name, hostOf(firstURL(p)))
|
||||
}
|
||||
if err := AddKey(it.KeyOf, p.Name, p.Key, ""); err != nil {
|
||||
return added, errorf("%s: %v", p.Name, err)
|
||||
}
|
||||
added = append(added, p.Name)
|
||||
added = append(added, p.Name+" ("+h.Name+")")
|
||||
continue
|
||||
case pk.Mode == "replace":
|
||||
case mode == "replace" && !reservedID(p.ID):
|
||||
case mode == "replace":
|
||||
// a subscription is never replaced by a provider of keys: its
|
||||
// sign-in would be lost, and Kiro's would take the key to its
|
||||
// own host
|
||||
return added, errorf("%s: %q is a subscription in magpie and can't be replaced; add it as a new provider", p.Name, p.ID)
|
||||
default:
|
||||
// an account a provider holds already is not added twice: the
|
||||
// same relay is often both a CC Switch entry and what Claude
|
||||
@@ -138,14 +171,14 @@ func ImportFromApps(picks []AppPick) ([]string, error) {
|
||||
continue
|
||||
}
|
||||
// the id may have been taken since, by an earlier pick
|
||||
if h, err := Find(p.ID); err == nil {
|
||||
if sameProvider(*h, p) {
|
||||
continue
|
||||
}
|
||||
// a second one of a preset is still that preset's, under an
|
||||
// id of its own
|
||||
p.ID = freeID(p.ID)
|
||||
if h, err := Find(p.ID); err == nil && sameProvider(*h, p) {
|
||||
continue
|
||||
}
|
||||
// a second one of a preset is still that preset's, under an id
|
||||
// of its own; one named as a subscription is (claude,
|
||||
// workbuddy) takes an id of its own too, whether or not that
|
||||
// subscription is signed in (#1487)
|
||||
p.ID = freeID(p.ID)
|
||||
p.Name = freeName(p.Name) // found by name too, so never two alike
|
||||
}
|
||||
if err := Save(p); err != nil {
|
||||
@@ -156,6 +189,16 @@ func ImportFromApps(picks []AppPick) ([]string, error) {
|
||||
return added, nil
|
||||
}
|
||||
|
||||
// reservedID is an id no imported provider can have: the gateway's own, a
|
||||
// subscription's or a plugin's, signed in or not.
|
||||
func reservedID(id string) bool {
|
||||
if id == "magpie" || subscriptionID(id) {
|
||||
return true
|
||||
}
|
||||
_, ok := find(Accounts(), id)
|
||||
return ok
|
||||
}
|
||||
|
||||
// holds says a provider of magpie's has p's account: its key at its
|
||||
// address, as the import list's "same" says (settle).
|
||||
func holds(p Provider) bool {
|
||||
@@ -239,8 +282,15 @@ func settle(items []AppImport, have []Provider, used map[string]bool) []AppImpor
|
||||
it.Existing = h.Name
|
||||
}
|
||||
}
|
||||
if _, ok := find(Accounts(), p.ID); ok && it.Status == "new" {
|
||||
it.Status, it.Existing = "taken", p.ID
|
||||
if reservedID(p.ID) && it.Status != "same" {
|
||||
// named as a subscription: only ever added beside it (#1487)
|
||||
it.Status, it.Reserved = "taken", true
|
||||
if it.Existing == "" {
|
||||
it.Existing = p.ID
|
||||
if h, err := Find(p.ID); err == nil {
|
||||
it.Existing = h.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// importable first, then by name; what can't be imported goes last
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ccSwitchSchema is CC Switch's own providers table (src-tauri/src/database/
|
||||
// schema.rs), so the fixture is read as the app's database is.
|
||||
const ccSwitchSchema = `CREATE TABLE IF NOT EXISTS providers (
|
||||
id TEXT NOT NULL, app_type TEXT NOT NULL, name TEXT NOT NULL, settings_config TEXT NOT NULL,
|
||||
website_url TEXT, category TEXT, created_at INTEGER, sort_index INTEGER, notes TEXT, icon TEXT, icon_color TEXT,
|
||||
meta TEXT NOT NULL DEFAULT '{}', is_current BOOLEAN NOT NULL DEFAULT 0, in_failover_queue BOOLEAN NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (id, app_type))`
|
||||
|
||||
// reservedHome is a home signed in to Claude, with a CC Switch whose
|
||||
// third-party providers are named as magpie's subscriptions are: a Pi
|
||||
// "workbuddy" at a local proxy and an OpenCode "Claude" at a relay magpie
|
||||
// has under another name, as #1487's screenshots show, a Claude Code
|
||||
// "claude" at a relay of its own, and a "Kiro" at another.
|
||||
func reservedHome(t *testing.T) string {
|
||||
t.Helper()
|
||||
home := claudeHome(t)
|
||||
t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming")) // Windows: never the real Alma
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude"))
|
||||
claudeSignIn(t, home, time.Now().Add(24*time.Hour))
|
||||
sqliteFixture(t, filepath.Join(home, ".cc-switch", "cc-switch.db"), ccSwitchSchema,
|
||||
`INSERT INTO providers (id,app_type,name,settings_config,website_url,category,created_at,sort_index) VALUES
|
||||
('wb','pi','workbuddy','{"api":"openai-completions","apiKey":"sk-5wb-3432","baseUrl":"http://127.0.0.1:7863/v1","models":[{"id":"glm-5"},{"id":"kimi-k2"}]}','','custom',1,0),
|
||||
('cl','opencode','Claude','{"npm":"@ai-sdk/anthropic","options":{"baseURL":"https://www.findcg.example/v1","apiKey":"sk-dcl-a39e"},"models":{"claude-sonnet-5":{"name":"Sonnet"},"claude-opus-5":{"name":"Opus"}}}','','custom',2,0),
|
||||
('cl2','claude','claude','{"env":{"ANTHROPIC_BASE_URL":"https://relay-1487.example.com","ANTHROPIC_AUTH_TOKEN":"sk-relay-beef","ANTHROPIC_MODEL":"claude-sonnet-5"}}','','custom',3,0),
|
||||
('kr','claude-desktop','Kiro','{"env":{"ANTHROPIC_BASE_URL":"https://kiro-relay.example.com","ANTHROPIC_AUTH_TOKEN":"sk-kiro-relay"}}','','custom',4,0)`,
|
||||
)
|
||||
if err := Save(Provider{ID: "findcg", Name: "findcg", Anthropic: "https://www.findcg.example/v1", Key: "sk-findcg-own"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return home
|
||||
}
|
||||
|
||||
// A third-party provider named as a subscription is, whether or not that
|
||||
// subscription is signed in, comes in beside it as a provider of its own,
|
||||
// with its own key at its own address (#1487, Dudung1018).
|
||||
func TestImportNamedAsSubscription(t *testing.T) {
|
||||
reservedHome(t)
|
||||
if _, ok := find(Accounts(), "claude"); !ok {
|
||||
t.Fatal("the fixture's Claude sign-in isn't read")
|
||||
}
|
||||
items := itemsOf(t, "cc-switch")
|
||||
wb := items["pi/wb"]
|
||||
if wb.Status != "taken" || !wb.Reserved {
|
||||
t.Fatalf("workbuddy isn't told apart from the subscription: %+v", wb)
|
||||
}
|
||||
cl := items["claude/cl2"]
|
||||
if cl.Status != "taken" || !cl.Reserved || cl.KeyOf != "" {
|
||||
t.Fatalf("claude: %+v", cl)
|
||||
}
|
||||
// what the picker turns on for them: added, never "pick another name"
|
||||
added, err := ImportFromApps([]AppPick{{Source: "cc-switch", Ref: "pi/wb", Mode: "add"}, {Source: "cc-switch", Ref: "claude/cl2", Mode: "add"}})
|
||||
if err != nil || len(added) != 2 {
|
||||
t.Fatalf("import: %v %v", added, err)
|
||||
}
|
||||
var wbp, clp *Provider
|
||||
for _, p := range load().Providers {
|
||||
switch p.Key {
|
||||
case "sk-5wb-3432":
|
||||
wbp = &p
|
||||
case "sk-relay-beef":
|
||||
clp = &p
|
||||
}
|
||||
}
|
||||
if wbp == nil || wbp.ID == "workbuddy" || wbp.Chat != "http://127.0.0.1:7863/v1" {
|
||||
t.Fatalf("workbuddy saved as %+v", wbp)
|
||||
}
|
||||
if clp == nil || clp.ID == "claude" || clp.Anthropic != "https://relay-1487.example.com" {
|
||||
t.Fatalf("claude relay saved as %+v", clp)
|
||||
}
|
||||
// the subscription is as it was
|
||||
if c, ok := find(Accounts(), "claude"); !ok || c.Account == nil || c.Key != "" {
|
||||
t.Fatalf("the Claude subscription: %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
// A subscription is never replaced by an imported provider: Replace took
|
||||
// the relay's models as the Claude subscription's picks and dropped its key
|
||||
// and address, and a Kiro would have kept the relay's key, to be sent to
|
||||
// Kiro's host (#1487).
|
||||
func TestImportNeverReplacesASubscription(t *testing.T) {
|
||||
reservedHome(t)
|
||||
for _, ref := range []string{"claude/cl2", "claude-desktop/kr"} {
|
||||
if _, err := ImportFromApps([]AppPick{{Source: "cc-switch", Ref: ref, Mode: "replace"}}); err == nil {
|
||||
t.Errorf("%s replaced a subscription", ref)
|
||||
}
|
||||
}
|
||||
for _, p := range load().Providers {
|
||||
if p.ID == "claude" || p.ID == "kiro" || strings.Contains(p.Key, "relay") {
|
||||
t.Fatalf("written: %+v", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A name that collides can be changed in the picker: the provider comes in
|
||||
// under it, at its own address (#1487).
|
||||
func TestImportRenamedInPicker(t *testing.T) {
|
||||
reservedHome(t)
|
||||
// renamed, a "replace" is an add: the name is the user's own now
|
||||
added, err := ImportFromApps([]AppPick{{Source: "cc-switch", Ref: "claude/cl2", Mode: "replace", Name: "My Claude Relay"}})
|
||||
if err != nil || len(added) != 1 {
|
||||
t.Fatalf("import: %v %v", added, err)
|
||||
}
|
||||
p, err := Find("my-claude-relay")
|
||||
if err != nil || p.Name != "My Claude Relay" || p.Key != "sk-relay-beef" || p.Anthropic != "https://relay-1487.example.com" {
|
||||
t.Fatalf("renamed: %+v %v", p, err)
|
||||
}
|
||||
// the OpenCode "Claude" joins findcg, at its address, as one more key;
|
||||
// the answer names where it went
|
||||
added, err = ImportFromApps([]AppPick{{Source: "cc-switch", Ref: "opencode/cl", Mode: "key"}})
|
||||
if err != nil || len(added) != 1 || !strings.Contains(added[0], "findcg") {
|
||||
t.Fatalf("as a key: %v %v", added, err)
|
||||
}
|
||||
if h, _ := Find("findcg"); len(h.Keys) != 1 || h.Keys[0].Key != "sk-dcl-a39e" {
|
||||
t.Fatalf("findcg: %+v", h)
|
||||
}
|
||||
}
|
||||
|
||||
// An import link named as a subscription is a provider of its own too:
|
||||
// never in the subscription's place (#1487).
|
||||
func TestImportLinkNamedAsSubscription(t *testing.T) {
|
||||
claudeHome(t)
|
||||
for _, link := range []string{
|
||||
"magpie://import?name=Claude&anthropic=https://relay-1487.example.com&key=sk-x",
|
||||
"magpie://import?name=Relay&id=kiro&anthropic=https://relay-1487.example.com&key=sk-x",
|
||||
} {
|
||||
p, err := ParseImport(link)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if subscriptionID(p.ID) {
|
||||
t.Errorf("%s: id %q is a subscription's", link, p.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,13 @@ func ParseImport(link string) (Provider, error) {
|
||||
if p.ID == "magpie" {
|
||||
return Provider{}, errors.New(`"magpie" is what agents call the gateway itself; the link needs another id`)
|
||||
}
|
||||
if subscriptionID(p.ID) {
|
||||
// named as a subscription is (claude, kiro): a provider of its own
|
||||
// beside it, never in its place, where the subscription's sign-in
|
||||
// would be lost, or Kiro's take the link's key to its own host
|
||||
// (#1487)
|
||||
p.ID = freeID(p.ID)
|
||||
}
|
||||
if len(p.Name) > 80 {
|
||||
p.Name = p.Name[:80]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user