providers: import from other apps — the add sheet's Import… reads the providers CC Switch (its database, or the older config.json) and Alma have set up, read-only, and lists them to pick from: what magpie has already is marked, a key for a vendor that is already here can join it as another key, an id in use is kept beside or replaced, and sign-ins, Azure, Gemini-protocol relays and entries pointing at magpie itself are shown but not offered; keys are read again on import and only reach the window masked

This commit is contained in:
yetone
2026-09-24 18:48:08 +08:00
parent e1d211cc4b
commit 0b0f258c0f
9 changed files with 1109 additions and 2 deletions
+9
View File
@@ -11,6 +11,7 @@ require (
github.com/tidwall/jsonc v0.3.3
github.com/wailsapp/wails/v3 v3.0.0-beta.24
golang.org/x/sys v0.46.0
modernc.org/sqlite v1.44.3
)
require (
@@ -25,8 +26,10 @@ require (
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.5.0 // indirect
github.com/coder/websocket v1.8.14 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
@@ -35,9 +38,15 @@ require (
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
golang.org/x/text v0.39.0 // indirect
modernc.org/libc v1.67.6 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)
+16
View File
@@ -28,6 +28,8 @@ github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e h1:Lf/gRkoycfOBPa42vU2bbgPurFong6zXeFtPoxholzU=
@@ -38,6 +40,8 @@ github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
@@ -56,8 +60,12 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
@@ -85,3 +93,11 @@ golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.67.6 h1:eVOQvpModVLKOdT+LvBPjdQqfrZq+pC39BygcT+E7OI=
modernc.org/libc v1.67.6/go.mod h1:JAhxUVlolfYDErnwiqaLvUqc8nfb2r6S6slAgZOnaiE=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.44.3 h1:+39JvV/HWMcYslAwRxHb8067w+2zowvFOUrOWIy9PjY=
modernc.org/sqlite v1.44.3/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
+21
View File
@@ -840,3 +840,24 @@ body.panel .modal { padding: 16px 12px; }
*, *::before, *::after { animation-duration: .01ms !important; transition-duration: .01ms !important; }
.skeleton, .effort-sparkles::before, .effort-sparkles::after, .effort-sparkles i { animation: none !important; }
}
/* Import from other apps: a checklist per app */
.editor.importapps { grid-template-columns: minmax(0, 1fr); }
.editor.importapps .appnote { font-size: 12px; color: var(--muted); line-height: 1.5; }
.editor.importapps .applist { display: flex; flex-direction: column; gap: 14px; max-height: min(56vh, 460px); overflow-y: auto; margin: 0 -4px; padding: 0 4px; }
.editor.importapps .apphead { display: flex; align-items: baseline; gap: 8px; padding-bottom: 4px; }
.editor.importapps .apphead b { font-weight: 600; font-size: 13px; flex: none; }
.editor.importapps .apphead code { flex: 1; min-width: 0; font: 11px var(--code); color: var(--faint); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.editor.importapps .appempty { font-size: 12px; color: var(--muted); padding: 2px 0 4px; }
.editor.importapps .approw { text-align: left; font-weight: 400; color: var(--fg); display: flex; align-items: flex-start; gap: 10px; padding: 8px 6px; border-radius: 8px; cursor: pointer; }
.editor.importapps .approw:hover:not(.dim) { background: var(--pill); }
.editor.importapps .approw.dim { cursor: default; opacity: .55; }
.editor.importapps .approw input { margin: 3px 0 0; accent-color: var(--fg); flex: none; }
.editor.importapps .approw .ic { width: 18px; height: 18px; flex: none; margin-top: 1px; }
.editor.importapps .approw .appwho { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.editor.importapps .approw .name { display: flex; align-items: baseline; gap: 6px; font-size: 13px; }
.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; }
.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); }
+143 -2
View File
@@ -23,6 +23,7 @@ let editing = null; // provider id being edited; { preset } or { custom: true }
let draft = null; // the editor's working copy
let adding = false; // the preset sheet is open
let importing = null; // a magpie://import link waiting for a yes: { provider, error, replaces }
let importingApps = null; // the Import from other apps dialog: { sources, picks }
// the gateway tab's choices, kept per machine
let flavor = params.get("flavor") || localStorage.getItem("magpie.flavor") || "openai"; // which API the snippets speak
let lang = params.get("lang") || localStorage.getItem("magpie.lang") || "shell"; // which snippet
@@ -545,7 +546,7 @@ $("#q").addEventListener("keydown", (e) => {
document.addEventListener("mousedown", (e) => { if (pick && !$("#pop").contains(e.target)) closePicker(); });
document.addEventListener("keydown", (e) => {
if (e.key !== "Escape" || pick) return;
if (editing !== null) cancelEdit();
if (editing !== null || importingApps) cancelEdit();
else if (mode === "panel") api("window/hide", {});
});
@@ -643,6 +644,7 @@ function renderProviders() {
renderExcluded();
dialog = renderAdd() || dialog;
if (importing) dialog = renderImport(importing);
if (importingApps) dialog = renderImportApps(importingApps);
if (dialog) openModal(dialog); else closeModal();
view.scrollTop = top;
}
@@ -1120,6 +1122,10 @@ function renderAdd() {
q.className = "find";
q.oninput = () => { presetQuery = q.value; drawTiles(); };
head.append(q);
const imp = el("button", "text", t("Import…"));
imp.title = t("Bring over providers set up in CC Switch or Alma");
imp.onclick = openImportApps;
head.append(imp);
if (providers.providers.length) {
const x = el("button", "text", t("Close"));
x.onclick = () => { adding = false; editing = null; draft = null; presetQuery = ""; renderProviders(); };
@@ -1225,7 +1231,7 @@ function input(value, placeholder, type = "text") {
i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); };
return i;
}
function cancelEdit() { editing = null; draft = null; importing = null; renderProviders(); }
function cancelEdit() { editing = null; draft = null; importing = null; importingApps = null; renderProviders(); }
// Custom request headers: the draft keeps them as an ordered [name, value,
// json?] list so a half-typed row (and its open JSON editor) survives a
@@ -1654,6 +1660,141 @@ function fetchImportIcon(p, head, ed) {
// renderImport: what a magpie://import link would add, for the user to
// check. Nothing is saved until they press Add; the key stays hidden unless
// they ask to see it.
// Providers other apps (CC Switch, Alma) have set up, for the user to pick
// from. magpie only reads those apps; the keys stay on the server side and
// the dialog sees them masked.
async function openImportApps() {
importingApps = { loading: true, sources: [], picks: {} };
renderProviders();
try {
const sources = await api("importapps");
const picks = {};
for (const s of sources) for (const it of s.items) {
if (it.skip || it.status === "same") continue;
picks[s.id + "\n" + it.ref] = { on: !it.off && (it.status !== "taken" || !!it.keyOf), mode: it.keyOf ? "key" : "add" };
}
if (!importingApps) return;
importingApps = { sources, picks };
} catch (e) {
if (!importingApps) return;
importingApps = { error: e.message, sources: [], picks: {} };
}
renderProviders();
}
function renderImportApps(ia) {
const ed = el("div", "editor new importapps");
ed.onclick = (e) => e.stopPropagation();
const h = el("div", "ehead");
h.append(el("b", "", t("Import from other apps")));
ed.append(h);
const bar = el("div", "bar");
const count = el("span", "note grow");
const cancel = el("button", "text", t("Cancel"));
cancel.onclick = cancelEdit;
const go = el("button", "text primary", t("Import"));
const recount = () => {
const n = Object.values(ia.picks).filter((x) => x.on).length;
count.textContent = n ? t("{n} selected", { n }) : "";
go.disabled = !n;
};
bar.append(count, cancel, go);
if (ia.loading) {
ed.append(el("div", "appnote", t("Reading CC Switch and Alma…")), bar);
go.disabled = true;
return ed;
}
if (ia.error) {
ed.append(el("div", "warnbox", ia.error), bar);
go.disabled = true;
return ed;
}
ed.append(el("div", "appnote", t("magpie reads these apps' settings and changes nothing in them. Pick the providers to bring over.")));
const list = el("div", "applist");
for (const s of ia.sources) {
const sec = el("div", "appsrc");
const sh = el("div", "apphead");
sh.append(el("b", "", s.name), el("code", "", s.path.replace(/^\/Users\/[^/]+|^\/home\/[^/]+/, "~")));
sec.append(sh);
if (!s.found) sec.append(el("div", "appempty", t("Not found on this computer")));
else if (s.error) sec.append(el("div", "appempty", s.error));
else if (!s.items.length) sec.append(el("div", "appempty", t("No providers in it")));
for (const it of s.items) sec.append(importAppRow(ia, s, it, recount));
list.append(sec);
}
ed.append(list);
go.onclick = async () => {
const picks = [];
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 });
}
go.classList.add("busy");
try {
const r = await api("importapps", { picks });
providers = r.state;
importingApps = null;
adding = false;
editing = null;
draft = null;
renderProviders();
state = await api("state");
renderAgents();
status(t("Imported {n}: {names}", { n: r.added.length, names: r.added.join(", ") }), "ok");
} catch (e) {
go.classList.remove("busy");
if (!editorError(e.message, "err")) status(e.message, "err");
}
};
ed.append(bar);
recount();
return ed;
}
function importAppRow(ia, s, it, recount) {
const p = it.provider;
const pick = ia.picks[s.id + "\n" + it.ref];
const row = el("label", "approw" + (pick ? "" : " dim"));
const box = el("input");
box.type = "checkbox";
box.checked = !!pick?.on;
box.disabled = !pick;
box.onchange = () => { pick.on = box.checked; recount(); };
const who = el("div", "appwho");
const name = el("div", "name");
name.append(el("span", "", p.name || it.ref));
if (it.from) name.append(el("span", "from", it.from));
who.append(name);
const bits = [];
const host = hostOf(p.anthropic || p.chat || p.responses || "");
if (it.skip) bits.push(t(it.skip));
else {
if (host) bits.push(host);
if (p.key) bits.push(p.key);
if (p.models?.length) bits.push(t(p.models.length === 1 ? "1 model" : "{n} models", { n: p.models.length }));
}
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 of {name}", { name: it.existing })]);
opts.push(["add", t(it.status === "taken" ? "Keep both" : "Add as a new provider")]);
if (it.status === "taken") opts.push(["replace", t("Replace {name}", { 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
who.append(sg);
}
let tag = null;
if (it.status === "same") tag = el("span", "apptag", t("Already added"));
else if (it.skip) tag = el("span", "apptag", t("Can't import"));
else if (it.status === "taken") tag = el("span", "apptag", t("Name in use"));
else if (it.keyOf) tag = el("span", "apptag", t("Same vendor"));
row.append(box, icon(p.icon || "generic"), who);
if (tag) row.append(tag);
return row;
}
function renderImport(im) {
const ed = el("div", "editor new import");
ed.onclick = (e) => e.stopPropagation();
+29
View File
@@ -196,6 +196,35 @@ const I18N = {
"Hide": "隐藏",
"Get a key ↗": "获取密钥 ↗",
"Import link": "导入链接",
"Import…": "导入…",
"Bring over providers set up in CC Switch or Alma": "把 CC Switch 或 Alma 里已配置的供应商导入进来",
"Import from other apps": "从其他应用导入",
"Import": "导入",
"{n} selected": "已选 {n} 个",
"Reading CC Switch and Alma…": "正在读取 CC Switch 和 Alma…",
"magpie reads these apps' settings and changes nothing in them. Pick the providers to bring over.": "magpie 只读取这些应用的配置,不会改动它们。勾选要导入的供应商。",
"Not found on this computer": "这台电脑上没有找到",
"No providers in it": "里面没有供应商",
"Imported {n}: {names}": "已导入 {n} 个:{names}",
"1 model": "1 个模型",
"Add as another key of {name}": "作为 {name} 的另一个密钥",
"Add as a new provider": "作为新的供应商",
"Keep both": "两个都保留",
"Replace {name}": "替换 {name}",
"Already added": "已添加",
"Can't import": "无法导入",
"Name in use": "重名",
"Same vendor": "同一服务商",
"turned off in Alma": "在 Alma 里是关闭的",
"it is the agent's own sign-in; add the subscription in magpie": "这是 agent 自己的登录,请在 magpie 里添加订阅",
"it is the agent's own sign-in": "这是 agent 自己的登录",
"it is a sign-in, not a key; add the subscription in magpie": "这是登录账号而不是密钥,请在 magpie 里添加订阅",
"magpie doesn't talk the Gemini protocol to relays yet": "magpie 暂不支持以 Gemini 协议连接中转",
"magpie doesn't support Azure OpenAI yet": "magpie 暂不支持 Azure OpenAI",
"it points at magpie itself": "它指向的就是 magpie 自己",
"it has no base URL": "没有 Base URL",
"it has no API key": "没有 API 密钥",
"its base URL isn't valid": "Base URL 无效",
"from a link": "来自链接",
"Fetching {host}’s icon…": "正在获取 {host} 的图标…",
"the vendor": "该厂商",
+42
View File
@@ -0,0 +1,42 @@
package gui
import (
"encoding/json"
"net/http"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
// Bringing over the providers another app (CC Switch, Alma) has set up:
// the page lists them, keys masked, and posts back the ones the user
// picked; the keys are read again here, never sent to the page.
func importAppsRoutes(mux *http.ServeMux, gw *gateway.Server) {
mux.HandleFunc("GET /api/importapps", func(rw http.ResponseWriter, r *http.Request) {
sources := provider.ImportSources()
for i := range sources {
for j := range sources[i].Items {
p := &sources[i].Items[j].Provider
p.Key, p.Keys = provider.Mask(p.Key), nil
}
}
writeJSON(rw, sources)
})
mux.HandleFunc("POST /api/importapps", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Picks []provider.AppPick }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
added, err := provider.ImportFromApps(in.Picks)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, struct {
Added []string `json:"added"`
State any `json:"state"`
}{added, providersState(gw)})
})
}
+1
View File
@@ -221,6 +221,7 @@ func ago(t time.Time) string {
}
func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) {
importAppsRoutes(mux, gw)
mux.HandleFunc("GET /api/providers", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, providersState(gw))
})
+710
View File
@@ -0,0 +1,710 @@
package provider
// Providers another app has already set up — CC Switch, Alma — offered for
// the user to bring over: each source is read (never written), every entry
// turned into the provider magpie would add, and matched against what is
// already here, so the picker can say which are new, which are already in,
// and which would take an id that is in use. Nothing is added until the
// user picks.
import (
"database/sql"
"encoding/json"
"errors"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"github.com/tidwall/jsonc"
_ "modernc.org/sqlite"
)
// AppSource is one app magpie can import from, with what it holds.
type AppSource struct {
ID string `json:"id"` // cc-switch, alma
Name string `json:"name"` // as the app calls itself
Path string `json:"path"` // the file read
Found bool `json:"found"`
Error string `json:"error,omitempty"`
Items []AppImport `json:"items"`
}
// AppImport is one provider an app holds, as magpie would add it.
type AppImport struct {
Ref string `json:"ref"` // stable within its source
From string `json:"from,omitempty"` // where in the app: Claude Code, Codex…
Provider Provider `json:"provider"`
// Status is "new", "same" (magpie has it already: same endpoint and
// key) or "taken" (its id is another provider's here).
Status string `json:"status"`
Existing string `json:"existing,omitempty"` // the magpie provider it matches or collides with
// KeyOf is a magpie provider at the same address with another key:
// 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
}
// 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").
type AppPick struct {
Source string `json:"source"`
Ref string `json:"ref"`
Mode string `json:"mode,omitempty"`
}
// appReaders are the apps magpie knows, in the order the picker shows them.
var appReaders = []struct {
id, name string
path func() string
read func(path string) ([]AppImport, error)
}{
{"cc-switch", "CC Switch", ccSwitchPath, readCCSwitch},
{"alma", "Alma", almaPath, readAlma},
}
// ImportSources reads every app magpie can import from.
func ImportSources() []AppSource {
have := load().Providers
used := map[string]bool{} // ids across all sources, so two never collide
var out []AppSource
for _, r := range appReaders {
s := AppSource{ID: r.id, Name: r.name, Path: r.path(), Items: []AppImport{}}
if _, err := os.Stat(s.Path); err == nil {
s.Found = true
items, err := r.read(s.Path)
if err != nil {
s.Error = err.Error()
}
s.Items = settle(items, have, used)
}
out = append(out, s)
}
return out
}
// ImportFromApps adds what the user picked, reading the sources again so
// keys never pass through the window. It answers the names added.
func ImportFromApps(picks []AppPick) ([]string, error) {
sources := map[string]AppSource{}
for _, s := range ImportSources() {
sources[s.ID] = s
}
var added []string
for _, pk := range picks {
var it *AppImport
for i, x := range sources[pk.Source].Items {
if x.Ref == pk.Ref {
it = &sources[pk.Source].Items[i]
}
}
if it == nil {
return added, errorf("%s no longer has that provider; reopen the import", pk.Source)
}
if it.Skip != "" || it.Status == "same" {
continue
}
p := it.Provider
switch {
case pk.Mode == "key" && it.KeyOf != "":
if h, err := Find(it.KeyOf); err == nil && sameProvider(*h, p) {
continue // picked twice, from two apps
}
if err := AddKey(it.KeyOf, p.Name, p.Key, ""); err != nil {
return added, errorf("%s: %v", p.Name, err)
}
added = append(added, p.Name)
continue
case pk.Mode == "replace":
default:
// the id may have been taken since, by an earlier pick
if h, err := Find(p.ID); err == nil {
if sameProvider(*h, p) {
continue
}
p.ID = freeID(p.ID)
p.Preset = "" // a second one of a preset is a custom provider
}
}
if err := Save(p); err != nil {
return added, errorf("%s: %v", p.Name, err)
}
added = append(added, p.Name)
}
return added, nil
}
// freeID is id, or id-2, id-3… whichever no provider has.
func freeID(id string) string {
taken := map[string]bool{"magpie": true}
for _, p := range All() {
taken[p.ID] = true
}
for _, p := range load().Providers {
taken[p.ID] = true
}
for n, try := 2, id; ; n++ {
if !taken[try] {
return try
}
try = id + "-" + itoa(n)
}
}
func itoa(n int) string {
b, _ := json.Marshal(n)
return string(b)
}
// settle gives each importable entry a unique id and says how it stands
// against the providers magpie has.
func settle(items []AppImport, have []Provider, used map[string]bool) []AppImport {
for i := range items {
it := &items[i]
if it.Skip != "" {
continue
}
p := &it.Provider
if p.ID == "" || p.ID == "magpie" {
p.ID = Slug(p.Name)
}
if p.ID == "" || p.ID == "magpie" {
p.ID = "imported"
}
for base, n := p.ID, 2; used[p.ID]; n++ {
p.ID = base + "-" + itoa(n)
}
used[p.ID] = true
it.Status = "new"
for _, h := range have {
if h.Hidden {
continue
}
if sameProvider(h, *p) {
it.Status, it.Existing = "same", h.Name
break
}
if h.ID == p.ID {
it.Status, it.Existing = "taken", h.Name
}
if it.KeyOf == "" && h.Key != "" && sameProvider(Provider{Key: p.Key, Chat: h.Chat, Responses: h.Responses, Anthropic: h.Anthropic}, *p) {
it.KeyOf = h.ID
}
}
if it.Status == "same" {
it.KeyOf = ""
} else if it.KeyOf != "" && it.Existing == "" {
if h, err := Find(it.KeyOf); err == nil {
it.Existing = h.Name
}
}
if _, ok := find(Accounts(), p.ID); ok && it.Status == "new" {
it.Status, it.Existing = "taken", p.ID
}
}
// importable first, then by name; what can't be imported goes last
sort.SliceStable(items, func(i, j int) bool { return (items[i].Skip == "") && (items[j].Skip != "") })
return items
}
// sameProvider: the same key at the same host is the same account; a is
// the provider magpie has, which may hold the key among its others.
func sameProvider(a, b Provider) bool {
has := a.Key == b.Key
for _, k := range a.Keys {
has = has || k.Key == b.Key
}
if !has {
return false
}
hosts := map[string]bool{}
for _, u := range []string{a.Chat, a.Responses, a.Anthropic} {
if h := hostOf(u); h != "" {
hosts[h] = true
}
}
for _, u := range []string{b.Chat, b.Responses, b.Anthropic} {
if hosts[hostOf(u)] {
return true
}
}
return false
}
func hostOf(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return ""
}
return strings.ToLower(u.Host)
}
// endpoints are the base URLs an entry names, by protocol.
type endpoints struct{ chat, responses, anthropic string }
// imported builds the provider for an entry: a preset's when the entry
// points at one magpie knows (its endpoints whole when the URL is the
// preset's own, only its name and logo when it is another path on the same
// host, like a coding plan), a custom one otherwise.
func imported(name, key string, e endpoints, models []string) (Provider, string) {
e.chat, e.responses, e.anthropic = cleanBase(e.chat), cleanBase(e.responses), cleanBase(e.anthropic)
for _, u := range []string{e.chat, e.responses, e.anthropic} {
if u == "" {
continue
}
pu, err := url.Parse(u)
if err != nil || (pu.Scheme != "http" && pu.Scheme != "https") || pu.Host == "" || !strings.Contains(pu.Host, ".") && !strings.HasPrefix(pu.Host, "localhost") {
return Provider{}, "its base URL isn't valid"
}
if gatewayURL(pu) {
return Provider{}, "it points at magpie itself"
}
}
if e.chat == "" && e.responses == "" && e.anthropic == "" {
return Provider{}, "it has no base URL"
}
p := Provider{ID: Slug(name), Name: name, Key: key, Chat: e.chat, Responses: e.responses, Anthropic: e.anthropic, Models: models}
if pr, exact := presetAt(e); pr != nil {
p.ID, p.Icon, p.Catalog = pr.ID, pr.Icon, pr.Catalog
if exact {
p.Preset, p.Website, p.KeysURL = pr.ID, pr.Website, pr.KeysURL
p.Chat, p.Responses, p.Anthropic = pr.Chat, pr.Responses, pr.Anthropic
if n := strings.ToLower(name); n == "" || n == "default" {
p.Name = pr.Name
}
}
}
if p.Key == "" && !keyOptional(p) {
return Provider{}, "it has no API key"
}
return p, ""
}
func cleanBase(u string) string {
u = strings.TrimRight(strings.TrimSpace(u), "/")
if u != "" && !strings.Contains(u, "://") {
u = "https://" + u
}
return u
}
// gatewayURL is magpie's own address: importing it would loop.
func gatewayURL(u *url.URL) bool {
h := u.Hostname()
return (h == "127.0.0.1" || h == "localhost") && u.Port() == "3425"
}
// presetAt finds the preset serving an entry's host, and whether the entry
// uses exactly that preset's endpoints.
func presetAt(e endpoints) (*PresetDef, bool) {
given := map[string]string{"chat": e.chat, "responses": e.responses, "anthropic": e.anthropic}
for i := range presets {
pr := &presets[i]
if pr.Kind == KindLocal {
continue
}
own := map[string]string{"chat": pr.Chat, "responses": pr.Responses, "anthropic": pr.Anthropic}
hit, exact := false, true
for k, u := range given {
if u == "" {
continue
}
if own[k] != "" && hostOf(own[k]) == hostOf(u) || hostOf(pr.Chat) == hostOf(u) || hostOf(pr.Anthropic) == hostOf(u) {
hit = true
}
if !strings.EqualFold(own[k], u) {
exact = false
}
}
if hit {
return pr, exact
}
}
return nil, false
}
// ---- CC Switch -------------------------------------------------------------
func ccSwitchPath() string {
home, _ := os.UserHomeDir()
dir := filepath.Join(home, ".cc-switch")
if db := filepath.Join(dir, "cc-switch.db"); fileExists(db) {
return db
}
if js := filepath.Join(dir, "config.json"); fileExists(js) {
return js
}
return filepath.Join(dir, "cc-switch.db")
}
func fileExists(p string) bool {
_, err := os.Stat(p)
return err == nil
}
// ccSwitchApps names CC Switch's app types as the picker shows them.
var ccSwitchApps = map[string]string{
"claude": "Claude Code", "claude-desktop": "Claude Desktop", "codex": "Codex",
"gemini": "Gemini CLI", "opencode": "OpenCode", "openclaw": "OpenClaw", "pi": "Pi", "hermes": "Hermes",
}
type ccEntry struct {
id, app, name, website, category string
settings map[string]any
}
func readCCSwitch(path string) ([]AppImport, error) {
var entries []ccEntry
if strings.HasSuffix(path, ".db") {
db, err := openReadOnly(path)
if err != nil {
return nil, err
}
defer db.Close()
rows, err := db.Query(`SELECT id, app_type, name, settings_config, COALESCE(website_url,''), COALESCE(category,'') FROM providers ORDER BY app_type, COALESCE(sort_index, 0), created_at`)
if err != nil {
return nil, errors.New("CC Switch's database: " + err.Error())
}
defer rows.Close()
for rows.Next() {
var e ccEntry
var raw string
if rows.Scan(&e.id, &e.app, &e.name, &raw, &e.website, &e.category) != nil {
continue
}
json.Unmarshal([]byte(raw), &e.settings)
entries = append(entries, e)
}
} else {
// CC Switch before its database: one config.json, a section per app
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var cfg map[string]json.RawMessage
if err := json.Unmarshal(jsonc.ToJSON(raw), &cfg); err != nil {
return nil, errors.New("CC Switch's config.json: " + err.Error())
}
for app, sec := range cfg {
var s struct {
Providers map[string]struct {
Name string `json:"name"`
Settings map[string]any `json:"settingsConfig"`
Website string `json:"websiteUrl"`
Category string `json:"category"`
} `json:"providers"`
}
if json.Unmarshal(sec, &s) != nil {
continue
}
for id, p := range s.Providers {
entries = append(entries, ccEntry{id: id, app: app, name: p.Name, website: p.Website, category: p.Category, settings: p.Settings})
}
}
sort.Slice(entries, func(i, j int) bool { return entries[i].app+entries[i].id < entries[j].app+entries[j].id })
}
var out []AppImport
for _, e := range entries {
it := AppImport{Ref: e.app + "/" + e.id, From: ccSwitchApps[e.app]}
if it.From == "" {
it.From = e.app
}
name, key, eps, models, skip := ccSwitchEntry(e)
if skip == "" {
it.Provider, skip = imported(name, key, eps, models)
}
if skip != "" {
it.Provider = Provider{Name: e.name}
it.Skip = skip
} else if w := cleanBase(e.website); strings.HasPrefix(w, "http") && it.Provider.Preset == "" {
it.Provider.Website = w
}
out = append(out, merge(out, it)...)
}
return out, nil
}
// merge folds an entry into one already read for the same account — a
// relay set up for both Claude Code and Codex is one provider with two
// endpoints — or answers it to be added.
func merge(have []AppImport, it AppImport) []AppImport {
if it.Skip != "" {
return []AppImport{it}
}
for i := range have {
h := &have[i].Provider
if have[i].Skip != "" || h.Key != it.Provider.Key || h.Key == "" || !sameProvider(*h, it.Provider) && hostOf(firstURL(*h)) != hostOf(firstURL(it.Provider)) {
continue
}
for _, f := range []struct{ dst, src *string }{{&h.Chat, &it.Provider.Chat}, {&h.Responses, &it.Provider.Responses}, {&h.Anthropic, &it.Provider.Anthropic}} {
if *f.dst == "" {
*f.dst = *f.src
}
}
h.Models = append(h.Models, it.Provider.Models...)
have[i].From += ", " + it.From
return nil
}
return []AppImport{it}
}
func firstURL(p Provider) string {
for _, u := range []string{p.Chat, p.Responses, p.Anthropic} {
if u != "" {
return u
}
}
return ""
}
// ccSwitchEntry reads one CC Switch provider: its settings are the agent's
// own configuration, which differs per app.
func ccSwitchEntry(e ccEntry) (name, key string, eps endpoints, models []string, skip string) {
s := e.settings
name = strings.TrimSpace(e.name)
env := mapOf(s["env"])
str := func(m map[string]any, keys ...string) string {
for _, k := range keys {
if v, ok := m[k].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
}
return ""
}
switch e.app {
case "claude", "claude-desktop":
base := str(env, "ANTHROPIC_BASE_URL")
key = str(env, "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY")
if base == "" && key == "" {
return name, "", eps, nil, "it is the agent's own sign-in; add the subscription in magpie"
}
if base == "" {
base = "https://api.anthropic.com"
}
eps.anthropic = base
for _, k := range []string{"ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL"} {
if m := str(env, k); m != "" {
models = append(models, m)
}
}
case "codex":
key = str(mapOf(s["auth"]), "OPENAI_API_KEY")
cfg, _ := s["config"].(string)
top, tables := parseTOML(cfg)
mp := tables["model_providers."+top["model_provider"]]
if top["model_provider"] != "" && mp == nil {
mp = tables[`model_providers."`+top["model_provider"]+`"`]
}
base := mp["base_url"]
if key == "" {
key = mp["experimental_bearer_token"]
}
if base == "" && key == "" {
return name, "", eps, nil, "it is the agent's own sign-in; add the subscription in magpie"
}
if base == "" {
base = "https://api.openai.com/v1"
}
if mp["wire_api"] == "chat" {
eps.chat = base
} else {
eps.responses = base
}
if m := top["model"]; m != "" {
models = append(models, m)
}
case "gemini":
key = str(env, "GEMINI_API_KEY", "GOOGLE_API_KEY")
if str(env, "GOOGLE_GEMINI_BASE_URL") != "" {
return name, "", eps, nil, "magpie doesn't talk the Gemini protocol to relays yet"
}
if key == "" {
return name, "", eps, nil, "it is the agent's own sign-in"
}
pr := Preset("google")
eps.chat, eps.responses, eps.anthropic = pr.Chat, pr.Responses, pr.Anthropic
if m := str(env, "GEMINI_MODEL"); m != "" {
models = append(models, m)
}
default:
// OpenCode, OpenClaw, Pi…: a base URL and a key, with the API's
// shape named by an api or npm field
opts := mapOf(s["options"])
base := str(s, "baseUrl", "baseURL", "base_url")
if base == "" {
base = str(opts, "baseURL", "baseUrl", "base_url")
}
key = str(s, "apiKey", "api_key")
if key == "" {
key = str(opts, "apiKey", "api_key")
}
if base == "" {
return name, "", eps, nil, "it has no base URL"
}
switch api := strings.ToLower(str(s, "api", "npm", "type")); {
case strings.Contains(api, "anthropic"):
eps.anthropic = base
case strings.Contains(api, "responses"):
eps.responses = base
default:
eps.chat = base
}
switch ms := s["models"].(type) {
case []any:
for _, m := range ms {
if id := str(mapOf(m), "id"); id != "" {
models = append(models, id)
} else if id, ok := m.(string); ok {
models = append(models, id)
}
}
case map[string]any:
for id := range ms {
models = append(models, id)
}
sort.Strings(models)
}
}
return name, key, eps, models, ""
}
func mapOf(v any) map[string]any {
m, _ := v.(map[string]any)
if m == nil {
return map[string]any{}
}
return m
}
// parseTOML reads the string values of a Codex config: top-level keys, and
// each table's keys under its header.
func parseTOML(s string) (map[string]string, map[string]map[string]string) {
top, tables := map[string]string{}, map[string]map[string]string{}
cur := top
for _, line := range strings.Split(s, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
name := strings.TrimSpace(strings.Trim(line, "[]"))
cur = map[string]string{}
tables[name] = cur
continue
}
k, v, ok := strings.Cut(line, "=")
if !ok {
continue
}
v = strings.TrimSpace(v)
if i := strings.Index(v, " #"); i > 0 && !strings.HasPrefix(v, `"`) {
v = strings.TrimSpace(v[:i])
}
if len(v) >= 2 && (v[0] == '"' || v[0] == '\'') {
if end := strings.LastIndexByte(v, v[0]); end > 0 {
v = v[1:end]
}
}
cur[strings.Trim(strings.TrimSpace(k), `"`)] = v
}
return top, tables
}
// ---- Alma ------------------------------------------------------------------
func almaPath() string {
dir, _ := os.UserConfigDir()
return filepath.Join(dir, "alma", "chat_threads.db")
}
// almaPresets are Alma's built-in provider types by the preset they are.
var almaPresets = map[string]string{
"openai": "openai", "anthropic": "anthropic", "google": "google", "deepseek": "deepseek",
"openrouter": "openrouter", "moonshot": "moonshot", "xai": "xai", "mistral": "mistral",
"groq": "groq", "aihubmix": "aihubmix", "together": "together", "fireworks": "fireworks",
"siliconflow": "siliconflow", "ollama": "ollama", "lmstudio": "lmstudio", "opencode-go": "opencode-go",
}
// almaSignIns are Alma's types that are an app's own sign-in, not a key.
var almaSignIns = map[string]bool{
"acp": true, "copilot": true, "claude-subscription": true, "codex-subscription": true,
"gemini-cli": true, "antigravity": true, "cursor": true,
}
func readAlma(path string) ([]AppImport, error) {
db, err := openReadOnly(path)
if err != nil {
return nil, err
}
defer db.Close()
rows, err := db.Query(`SELECT id, name, type, api_key, models, COALESCE(base_url,''), enabled, COALESCE(api_format,''), COALESCE(is_response_api,0), COALESCE(custom_headers,'') FROM providers ORDER BY created_at`)
if err != nil {
return nil, errors.New("Alma's database: " + err.Error())
}
defer rows.Close()
var out []AppImport
for rows.Next() {
var id, name, typ, key, modelsJSON, base, format, headers string
var enabled, responses bool
if err := rows.Scan(&id, &name, &typ, &key, &modelsJSON, &base, &enabled, &format, &responses, &headers); err != nil {
continue
}
it := AppImport{Ref: id}
var models []string
json.Unmarshal([]byte(modelsJSON), &models)
var eps endpoints
skip := ""
switch {
case almaSignIns[typ]:
skip = "it is a sign-in, not a key; add the subscription in magpie"
case typ == "azure":
skip = "magpie doesn't support Azure OpenAI yet"
case base == "" && Preset(almaPresets[typ]) != nil:
pr := Preset(almaPresets[typ])
eps = endpoints{pr.Chat, pr.Responses, pr.Anthropic}
case format == "anthropic" || typ == "anthropic":
eps.anthropic = base
case format == "gemini" || typ == "google" && base != "":
skip = "magpie doesn't talk the Gemini protocol to relays yet"
case responses || format == "openai-responses":
eps.responses = base
default:
eps.chat = base
}
if skip == "" {
it.Provider, skip = imported(name, key, eps, models)
}
if skip != "" {
it.Provider, it.Skip = Provider{Name: name}, skip
} else {
var hs map[string]string
if json.Unmarshal([]byte(headers), &hs) == nil && it.Provider.Preset == "" {
it.Provider.Headers = hs
}
if !enabled {
it.Off = "turned off in Alma"
}
}
out = append(out, it)
}
return out, nil
}
// openReadOnly opens another app's SQLite database without writing to it,
// waiting out the app's own writes.
func openReadOnly(path string) (*sql.DB, error) {
u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), RawQuery: "mode=ro&_pragma=busy_timeout(3000)"}
db, err := sql.Open("sqlite", u.String())
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
db.Close()
return nil, errors.New("can't open " + path + ": " + err.Error())
}
return db, nil
}
+138
View File
@@ -0,0 +1,138 @@
package provider
import (
"database/sql"
"os"
"path/filepath"
"testing"
)
func sqliteFixture(t *testing.T, path string, stmts ...string) {
t.Helper()
os.MkdirAll(filepath.Dir(path), 0o700)
db, err := sql.Open("sqlite", path)
if err != nil {
t.Fatal(err)
}
defer db.Close()
for _, s := range stmts {
if _, err := db.Exec(s); err != nil {
t.Fatalf("%s: %v", s, err)
}
}
}
func itemsOf(t *testing.T, id string) map[string]AppImport {
t.Helper()
for _, s := range ImportSources() {
if s.ID == id {
if !s.Found || s.Error != "" {
t.Fatalf("%s: found %v, %s", id, s.Found, s.Error)
}
out := map[string]AppImport{}
for _, it := range s.Items {
out[it.Ref] = it
}
return out
}
}
t.Fatalf("no source %s", id)
return nil
}
// CC Switch keeps each agent's own settings; magpie reads them as the
// providers they point at, and adds only what the user picks.
func TestImportCCSwitch(t *testing.T) {
isolate(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
sqliteFixture(t, filepath.Join(home, ".cc-switch", "cc-switch.db"),
`CREATE TABLE providers (id TEXT, app_type TEXT, name TEXT, settings_config TEXT, website_url TEXT, category TEXT, created_at INTEGER, sort_index INTEGER, PRIMARY KEY (id, app_type))`,
`INSERT INTO providers VALUES ('official','claude','Claude Official','{"env":{}}','','official',1,0)`,
`INSERT INTO providers VALUES ('relay','claude','Some Relay','{"env":{"ANTHROPIC_BASE_URL":"https://relay.example.com","ANTHROPIC_AUTH_TOKEN":"sk-relay","ANTHROPIC_MODEL":"claude-sonnet-5"}}','https://relay.example.com','custom',2,1)`,
`INSERT INTO providers VALUES ('relay','codex','Some Relay','{"auth":{"OPENAI_API_KEY":"sk-relay"},"config":"model_provider = \"relay\"\nmodel = \"gpt-5.5\"\n\n[model_providers.relay]\nname = \"relay\"\nbase_url = \"https://relay.example.com/v1\"\nwire_api = \"responses\"\n"}','','custom',3,0)`,
`INSERT INTO providers VALUES ('ds','claude','DeepSeek','{"env":{"ANTHROPIC_BASE_URL":"https://api.deepseek.com/anthropic","ANTHROPIC_AUTH_TOKEN":"sk-ds"}}','','cn_official',4,2)`,
`INSERT INTO providers VALUES ('dial','pi','dial','{"api":"openai-completions","apiKey":"magpie","baseUrl":"http://127.0.0.1:3425/v1"}','','custom',5,0)`,
`INSERT INTO providers VALUES ('g','gemini','Gemini relay','{"env":{"GOOGLE_GEMINI_BASE_URL":"https://g.example.com","GEMINI_API_KEY":"k"}}','','custom',6,0)`,
)
// DeepSeek is already here under its preset id, with another key
if err := Save(FromPresetKey(t, "deepseek", "sk-other")); err != nil {
t.Fatal(err)
}
items := itemsOf(t, "cc-switch")
if it := items["claude/official"]; it.Skip == "" {
t.Fatalf("official sign-in offered: %+v", it)
}
if it := items["pi/dial"]; it.Skip == "" {
t.Fatalf("magpie itself offered: %+v", it)
}
if it := items["gemini/g"]; it.Skip == "" {
t.Fatalf("gemini relay offered: %+v", it)
}
relay := items["claude/relay"]
if relay.Skip != "" || relay.Status != "new" || relay.Provider.Anthropic != "https://relay.example.com" || relay.Provider.Responses != "https://relay.example.com/v1" || relay.From != "Claude Code, Codex" {
t.Fatalf("relay: %+v", relay)
}
if _, ok := items["codex/relay"]; ok {
t.Fatal("the Codex half of the relay listed on its own")
}
ds := items["claude/ds"]
if ds.Status != "taken" || ds.Provider.ID != "deepseek" || ds.Provider.Preset != "deepseek" || ds.KeyOf != "deepseek" {
t.Fatalf("deepseek: %+v", ds)
}
added, err := ImportFromApps([]AppPick{{Source: "cc-switch", Ref: "claude/relay"}, {Source: "cc-switch", Ref: "claude/ds", Mode: "key"}})
if err != nil || len(added) != 2 {
t.Fatalf("import: %v %v", added, err)
}
if p, err := Find("some-relay"); err != nil || p.Key != "sk-relay" || len(p.Models) != 2 {
t.Fatalf("relay saved: %+v", p)
}
if p, _ := Find("deepseek"); p.Key != "sk-other" || len(p.Keys) != 1 || p.Keys[0].Key != "sk-ds" {
t.Fatalf("deepseek's second key: %+v", p)
}
if it := itemsOf(t, "cc-switch")["claude/ds"]; it.Status != "same" {
t.Fatalf("second key again: %+v", it)
}
// imported once, it is there already
if it := itemsOf(t, "cc-switch")["claude/relay"]; it.Status != "same" {
t.Fatalf("after import: %+v", it)
}
}
func TestImportAlma(t *testing.T) {
isolate(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
cfg, _ := os.UserConfigDir()
sqliteFixture(t, filepath.Join(cfg, "alma", "chat_threads.db"),
`CREATE TABLE providers (id TEXT PRIMARY KEY, name TEXT, type TEXT, api_key TEXT, models TEXT, base_url TEXT, enabled INTEGER, created_at TEXT, api_format TEXT, is_response_api INTEGER, custom_headers TEXT)`,
`INSERT INTO providers VALUES ('a1','OpenRouter','openrouter','sk-or','["anthropic/claude-sonnet-5"]',NULL,1,'1',NULL,0,NULL)`,
`INSERT INTO providers VALUES ('a2','My Proxy','custom','sk-p','[]','https://proxy.example.com/v1',0,'2','openai-chat',0,'{"X-Team":"a"}')`,
`INSERT INTO providers VALUES ('a3','Copilot','copilot','','[]',NULL,1,'3',NULL,0,NULL)`,
`INSERT INTO providers VALUES ('a4','junk','custom','x','[]','bbb',0,'4',NULL,0,NULL)`,
)
items := itemsOf(t, "alma")
if it := items["a1"]; it.Provider.Preset != "openrouter" || it.Provider.Key != "sk-or" || len(it.Provider.Models) != 1 {
t.Fatalf("openrouter: %+v", it)
}
if it := items["a2"]; it.Off == "" || it.Provider.Chat != "https://proxy.example.com/v1" || it.Provider.Headers["X-Team"] != "a" {
t.Fatalf("proxy: %+v", it)
}
if items["a3"].Skip == "" || items["a4"].Skip == "" {
t.Fatalf("sign-in or junk offered: %+v %+v", items["a3"], items["a4"])
}
}
func FromPresetKey(t *testing.T, id, key string) Provider {
p, err := FromPreset(id)
if err != nil {
t.Fatalf("no preset %s", id)
}
p.Key = key
return p
}