From 37fec124095cc3ff91960d3f4e6fa2d010b4044b Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 19:19:54 +0800 Subject: [PATCH] import: OpenCode's keys come in from its auth.json, Go's on OpenCode Go (@hu_xiaomi on X) @hu_xiaomi on X asked whether magpie could pick up OpenCode Go's API key by itself. OpenCode keeps what `opencode auth login` signs in to in auth.json, in $XDG_DATA_HOME/opencode (~/.local/share/opencode when that is unset, on Windows too). Its format and path were checked against anomalyco/opencode v1.19.0, packages/opencode/src/auth/index.ts. - OpenCode is now a source in the import picker (appReaders, import_opencode.go). An "api" key comes in on the magpie preset with the same id: opencode-go on OpenCode Go, opencode (Zen) on OpenCode Zen, and a vendor's key (openai, anthropic, deepseek, openrouter, ...) on that vendor's preset, the same way Alma's almaPresets work. - auth.json keeps no address beside a key, so a key for a provider with no preset is listed and skipped ("it has no base URL"). Sign-ins (oauth: Claude Pro/Max, Copilot; wellknown: an enterprise server's token) are listed and skipped with the reason the picker already translates. No new GUI strings. - OpenCode is read only when the user opens the picker. The Providers page's automatic discovery leaves it out (DiscoverSources, the `asked` flag), because the file holds every sign-in OpenCode has. magpie never writes to it. OPENCODE_AUTH_CONTENT is not read. - presetAt: the first preset at a host won even when a later one matched the URL exactly. OpenCode Zen and Go share opencode.ai, so a Zen key would have landed on Go. An exact match now wins. - importSources: a source whose stat fails with anything but not-exist (a folder magpie can't search) is found with an error, which means unknown. Before, it read as "Not found". - The picker's tab shows OpenCode's own mark (icons/opencode.svg). - docs/reference.md describes the source. Not added: an "use the key OpenCode has" offer in the OpenCode Go add sheet, because no other app has one there (no sibling to follow). Run (macOS, go1.26.8, worktree at dd25997a4 before the rebase): - go test -tags nogui -timeout 40m ./...: every package ok (63 ok, none failed; gateway 1806s, agent 1769s at load ~160-230) - gofmt -l internal/provider internal/gui: clean - go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: clean - GUI, playwright 1.62.0: import-opencode.test.cjs in chromium and webkit, en/zh/zh-TW/ja/de, at 900 and 390px: 20/20. import-collision, import-row, provider-discovery and key-import pass. login-import fails in chromium (fill/click timeouts) at load ~230. It fails the same way with HEAD's app.js (dd25997a4 = origin/main, just fetched), and #1307 already tracks it. - Broken by hand, each went red and was then put back: 1. presetAt's old first-hit rule: TestImportOpenCodeAuth, Zen came in as opencode-go-2. 2. no sign-in skip: TestImportOpenCodeAuth, anthropic's oauth entry. 3. stat errors read as not found: TestImportOpenCodeAuthUnknown, unreadable folder. 4. discovery reads OpenCode: TestImportOpenCodeAuth and TestOpenCodeWaitsForThePicker. 5. XDG_DATA_HOME ignored: TestImportOpenCodeAuth, TestImportOpenCodeAuthUnknown and TestOpenCodeWaitsForThePicker. 6. tab icon left at app-opencode.png: import-opencode.test.cjs. Fixtures are auth.json as OpenCode v1.19.0 writes it (JSON.stringify(data, null, 2), 0600), under a sandbox HOME and XDG_DATA_HOME. Not tried: a real OpenCode install with a real key, and the Windows box (the path logic is the same there; GOOS=windows vet only). --- docs/reference.md | 12 ++ internal/gui/assets/app.js | 6 +- internal/gui/importapps.go | 3 +- internal/gui/importapps_test.go | 44 +++++ internal/gui/tests/import-opencode.test.cjs | 86 ++++++++ internal/provider/import_opencode.go | 86 ++++++++ internal/provider/import_opencode_test.go | 205 ++++++++++++++++++++ internal/provider/importapps.go | 48 +++-- 8 files changed, 473 insertions(+), 17 deletions(-) create mode 100644 internal/gui/tests/import-opencode.test.cjs create mode 100644 internal/provider/import_opencode.go create mode 100644 internal/provider/import_opencode_test.go diff --git a/docs/reference.md b/docs/reference.md index 422dfa889..c74d30701 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1343,6 +1343,18 @@ including fixed headers for custom providers in subsequent changes to agent settings are not automatically copied to magpie. Entries that point back to magpie or only name an `env_key` are skipped. +The same dialog reads OpenCode's own sign-ins, `auth.json` in +`$XDG_DATA_HOME/opencode` (`~/.local/share/opencode` when unset, on Windows +too), where `opencode auth login` keeps them. An API key comes in on the +magpie preset at the same address: OpenCode Go's key on OpenCode Go, Zen's +(`opencode`) on OpenCode Zen, and a vendor's (OpenAI, Anthropic, DeepSeek, +OpenRouter and others) on its own. OpenCode keeps no address beside a key, +so one of a provider magpie has no preset for is listed and skipped. Sign-ins +(Claude Pro/Max, Copilot, an enterprise server's token) are listed and +skipped; add the subscription in magpie instead. OpenCode is read only when +you open the dialog: the Providers page's automatic check leaves it out, as +the file holds every sign-in OpenCode has. magpie never writes to it. + ### How magpie picks an account When a subscription has several accounts on (Claude Code's or Codex's diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 5894b91f6..c0c3abd02 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -9572,9 +9572,9 @@ async function openImportApps(discovered) { renderProviders(); } -// appIcon is an import source's logo; Claude Code has its mark among the -// vendor icons rather than an app tile of its own. -const appIcon = (id) => id === "claude-code" ? "icons/claudecode-color.svg" : id === "codex" ? "icons/codex-color.svg" : `icons/app-${id}.png`; +// appIcon is an import source's logo; Claude Code, Codex and OpenCode have +// their marks among the vendor icons rather than an app tile of their own. +const appIcon = (id) => id === "claude-code" ? "icons/claudecode-color.svg" : id === "codex" ? "icons/codex-color.svg" : id === "opencode" ? "icons/opencode.svg" : `icons/app-${id}.png`; function renderImportApps(ia) { const ed = el("div", "editor new importapps"); diff --git a/internal/gui/importapps.go b/internal/gui/importapps.go index 7d29ca445..e3b4fc931 100644 --- a/internal/gui/importapps.go +++ b/internal/gui/importapps.go @@ -33,7 +33,8 @@ func importAppsRoutes(mux *http.ServeMux) { Source string `json:"source"` } out := []candidate{} - for _, s := range provider.ImportSources() { + // only the apps looked in unasked: OpenCode waits for the picker + for _, s := range provider.DiscoverSources() { for _, it := range s.Items { // Match openImportApps' default selection: disabled entries and // ID collisions without an add-key option need a manual choice. diff --git a/internal/gui/importapps_test.go b/internal/gui/importapps_test.go index 5acee3766..e167b24cf 100644 --- a/internal/gui/importapps_test.go +++ b/internal/gui/importapps_test.go @@ -217,3 +217,47 @@ env_key = "UNSET_DISCOVERY_KEY" write(codex, codexConfig) check("Codex") } + +// OpenCode's auth.json holds every sign-in OpenCode has, so the Providers +// page's own look passes it by; the picker the user opens reads it, its +// keys masked (@hu_xiaomi on X). +func TestOpenCodeWaitsForThePicker(t *testing.T) { + home := sandboxHome(t) + data := filepath.Join(home, "data") + t.Setenv("XDG_DATA_HOME", data) + t.Setenv("CODEX_HOME", filepath.Join(home, ".codex")) + t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude")) + auth := filepath.Join(data, "opencode", "auth.json") + body := "{\n \"opencode-go\": {\n \"type\": \"api\",\n \"key\": \"secret-go\"\n }\n}" + if err := os.MkdirAll(filepath.Dir(auth), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(auth, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + importAppsRoutes(mux) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/importapps/discovery", nil)) + if strings.TrimSpace(w.Body.String()) != "[]" { + t.Fatalf("discovery read OpenCode: %s", w.Body) + } + w = httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/importapps", nil)) + if strings.Contains(w.Body.String(), "secret-go") { + t.Fatal("the picker was sent OpenCode's key") + } + var sources []provider.AppSource + if err := json.Unmarshal(w.Body.Bytes(), &sources); err != nil { + t.Fatal(err) + } + found := false + for _, s := range sources { + for _, it := range s.Items { + found = found || s.ID == "opencode" && it.Ref == "opencode-go" && it.Skip == "" && it.Provider.Preset == "opencode-go" + } + } + if !found { + t.Fatalf("the picker has no OpenCode Go: %s", w.Body) + } +} diff --git a/internal/gui/tests/import-opencode.test.cjs b/internal/gui/tests/import-opencode.test.cjs new file mode 100644 index 000000000..7c02b159a --- /dev/null +++ b/internal/gui/tests/import-opencode.test.cjs @@ -0,0 +1,86 @@ +// OpenCode in the import picker (@hu_xiaomi on X): its tab carries +// OpenCode's own mark, OpenCode Go's key is picked to come in on its +// preset, and a sign-in (Claude Pro/Max) is listed, said why, and can't be +// picked. 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: "opencode", name: "OpenCode", path: "/fixture/.local/share/opencode/auth.json", found: true, + items: [ + { ref: "opencode-go", from: "auth.json", fingerprint: "go", status: "new", + provider: { id: "opencode-go", name: "OpenCode Go", icon: "opencode", preset: "opencode-go", chat: "https://opencode.ai/zen/go/v1", key: "sk-g…7c" } }, + { ref: "anthropic", from: "auth.json", fingerprint: "ant", skip: "it is a sign-in, not a key; add the subscription in magpie", + provider: { name: "anthropic" } }, + ], +}]; + +for (const engine of engines) { + for (const lang of langs) { + for (const width of [900, 390]) { + test(`${engine} ${lang} ${width}px: OpenCode's key is picked, its sign-in is not`, async (t) => { + 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: ["OpenCode Go"], 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 () => { + 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(); + const T = (s, v) => page.evaluate(([s, v]) => t(s, v), [s, v]); + + // the tab's mark is OpenCode's, and it loads + const logo = picker.locator(".apptab .applogo"); + assert.match(await logo.getAttribute("src"), /icons\/opencode\.svg$/); + await page.waitForFunction(() => document.querySelector("#modal .apptab .applogo").complete); + assert((await logo.evaluate((img) => img.naturalWidth)) > 0, "OpenCode's mark loads"); + + const go = picker.locator(".approw", { hasText: "OpenCode Go" }); + const ant = picker.locator(".approw", { hasText: "anthropic" }); + assert.equal(await go.locator('input[type="checkbox"]').isChecked(), true); + assert.equal(await ant.locator('input[type="checkbox"]').isDisabled(), true); + assert.equal(await ant.locator(".sub", { hasText: await T("it is a sign-in, not a key; add the subscription in magpie") }).count(), 1); + assert.equal(await ant.locator(".apptag").textContent(), await T("Can't import")); + if (lang !== "en") assert.notEqual(await T("it is a sign-in, not a key; add the subscription in magpie"), "it is a sign-in, not a key; add the subscription in magpie"); + + 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, [{ picks: [{ source: "opencode", ref: "opencode-go", mode: "add" }] }]); + }); + } + } +} diff --git a/internal/provider/import_opencode.go b/internal/provider/import_opencode.go new file mode 100644 index 000000000..24a71c968 --- /dev/null +++ b/internal/provider/import_opencode.go @@ -0,0 +1,86 @@ +package provider + +import ( + "encoding/json" + "errors" + "maps" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/edit" +) + +// OpenCode's own sign-ins, as `opencode auth login` keeps them: auth.json in +// its data folder, $XDG_DATA_HOME/opencode, else ~/.local/share/opencode +// (xdg-basedir's, on Windows too). It maps a provider id (models.dev's) to +// {"type":"api","key":…}, {"type":"oauth",…} or {"type":"wellknown",…} +// (packages/opencode/src/auth/index.ts). It holds keys only, never where +// they go: an id is imported when magpie has its preset. + +func openCodeAuthPath() string { + if d := appdir.Getenv("XDG_DATA_HOME"); d != "" { + return filepath.Join(d, "opencode", "auth.json") + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".local", "share", "opencode", "auth.json") +} + +// openCodePresets are OpenCode's provider ids by the magpie preset at the +// same address. An id at a host the preset doesn't serve (SiliconFlow's +// .com beside the preset's .cn) is left out: its key would be sent there. +var openCodePresets = map[string]string{ + "opencode": "opencode-zen", "opencode-go": "opencode-go", + "openai": "openai", "anthropic": "anthropic", "google": "google", "deepseek": "deepseek", + "xai": "xai", "moonshotai": "moonshot", "moonshotai-cn": "moonshot-cn", "mistral": "mistral", + "groq": "groq", "openrouter": "openrouter", "togetherai": "together", "fireworks-ai": "fireworks", + "siliconflow-cn": "siliconflow", "nvidia": "nvidia", "aihubmix": "aihubmix", "302ai": "302ai", + "ollama-cloud": "ollama-cloud", +} + +func readOpenCodeAuth(path string) ([]AppImport, error) { + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var all map[string]json.RawMessage + if err := json.Unmarshal(edit.TrimBOM(raw), &all); err != nil { + return nil, errors.New("OpenCode's auth.json: " + err.Error()) + } + var out []AppImport + for _, id := range slices.Sorted(maps.Keys(all)) { + var e struct { + Type string `json:"type"` + Key string `json:"key"` + } + if json.Unmarshal(all[id], &e) != nil { + continue // OpenCode passes over what it can't read too + } + it := AppImport{Ref: id, From: "auth.json"} + pr := Preset(openCodePresets[id]) + name := id + if pr != nil { + name = pr.Name + } + skip := "" + switch { + case e.Type == "oauth" || e.Type == "wellknown": + skip = "it is a sign-in, not a key; add the subscription in magpie" + case e.Type != "api": + continue + case pr == nil: + skip = "it has no base URL" // OpenCode keeps only its key here + case strings.TrimSpace(e.Key) == "": + skip = "it has no API key" + default: + it.Provider, skip = imported(name, strings.TrimSpace(e.Key), endpoints{pr.Chat, pr.Responses, pr.Anthropic}, nil) + } + if skip != "" { + it.Provider, it.Skip = Provider{Name: name}, skip + } + out = append(out, it) + } + return out, nil +} diff --git a/internal/provider/import_opencode_test.go b/internal/provider/import_opencode_test.go new file mode 100644 index 000000000..3a3d2aeff --- /dev/null +++ b/internal/provider/import_opencode_test.go @@ -0,0 +1,205 @@ +package provider + +import ( + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// openCodeAuth is auth.json as OpenCode v1.19.0 writes it +// (JSON.stringify(data, null, 2), mode 0600), from `opencode auth login`: +// two keys of its own (Zen and Go), a vendor's key with metadata, a +// provider magpie has no preset for, Claude Pro/Max and Copilot sign-ins, +// and an enterprise server's well-known token. +const openCodeAuth = `{ + "opencode": { + "type": "api", + "key": "sk-zen-1f2e3d" + }, + "opencode-go": { + "type": "api", + "key": "sk-go-9a8b7c" + }, + "deepseek": { + "type": "api", + "key": "sk-ds-oc", + "metadata": { + "source": "login" + } + }, + "my-relay": { + "type": "api", + "key": "sk-relay-oc" + }, + "anthropic": { + "type": "oauth", + "refresh": "sk-ant-ort01-abc", + "access": "sk-ant-oat01-def", + "expires": 1792000000000 + }, + "github-copilot": { + "type": "oauth", + "refresh": "gho_refresh", + "access": "tid=abc", + "expires": 0, + "enterpriseUrl": "github.example.com" + }, + "https://opencode.example.com": { + "type": "wellknown", + "key": "OPENCODE_TOKEN", + "token": "wk-token" + } +}` + +func writeOpenCodeAuth(t *testing.T, dir string) string { + t.Helper() + p := filepath.Join(dir, "opencode", "auth.json") + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(openCodeAuth), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +func openCodeHome(t *testing.T) string { + t.Helper() + isolate(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) // Windows + t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming")) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + return home +} + +func openCodeSource(t *testing.T) AppSource { + t.Helper() + for _, s := range ImportSources() { + if s.ID == "opencode" { + return s + } + } + t.Fatal("OpenCode isn't an import source") + return AppSource{} +} + +// OpenCode's keys come over onto magpie's presets: OpenCode Go's on +// OpenCode Go, Zen's on OpenCode Zen (not Go, whose host it shares), a +// vendor's on its own; its sign-ins are listed and never imported. +// auth.json is only read (@hu_xiaomi on X). +func TestImportOpenCodeAuth(t *testing.T) { + home := openCodeHome(t) + data := filepath.Join(home, "data") + t.Setenv("XDG_DATA_HOME", data) + path := writeOpenCodeAuth(t, data) + old := time.Now().Add(-time.Hour).Truncate(time.Second) + os.Chtimes(path, old, old) + + items := itemsOf(t, "opencode") + if s := openCodeSource(t); s.Path != path { + t.Fatalf("read %s, want %s", s.Path, path) + } + goKey := items["opencode-go"] + if p := goKey.Provider; goKey.Skip != "" || goKey.Status != "new" || p.Preset != "opencode-go" || p.ID != "opencode-go" || p.Key != "sk-go-9a8b7c" || + p.Chat != Preset("opencode-go").Chat || p.Anthropic != Preset("opencode-go").Anthropic || p.Name != "OpenCode Go" || goKey.From != "auth.json" { + t.Fatalf("OpenCode Go: %+v", goKey) + } + zen := items["opencode"] + if p := zen.Provider; zen.Skip != "" || p.Preset != "opencode-zen" || p.ID != "opencode-zen" || p.Key != "sk-zen-1f2e3d" || p.Chat != Preset("opencode-zen").Chat || p.Name != "OpenCode Zen" { + t.Fatalf("OpenCode Zen: %+v", zen) + } + if ds := items["deepseek"]; ds.Skip != "" || ds.Provider.Preset != "deepseek" || ds.Provider.Key != "sk-ds-oc" { + t.Fatalf("DeepSeek: %+v", ds) + } + if it := items["my-relay"]; it.Skip != "it has no base URL" || it.Provider.Key != "" { + t.Fatalf("a provider with no preset: %+v", it) + } + for _, ref := range []string{"anthropic", "github-copilot", "https://opencode.example.com"} { + it := items[ref] + if it.Skip != "it is a sign-in, not a key; add the subscription in magpie" || it.Provider.Key != "" || it.Provider.Chat != "" || it.Provider.Anthropic != "" { + t.Fatalf("sign-in %s: %+v", ref, it) + } + } + if len(items) != 7 { + t.Fatalf("items: %d", len(items)) + } + // the Providers page's own look leaves OpenCode for the user to ask + for _, s := range DiscoverSources() { + if s.ID == "opencode" { + t.Fatal("OpenCode read without being asked") + } + } + + added, err := ImportFromApps([]AppPick{{Source: "opencode", Ref: "opencode-go"}, {Source: "opencode", Ref: "opencode"}, {Source: "opencode", Ref: "anthropic"}}) + if err != nil || len(added) != 2 { + t.Fatalf("import: %v %v", added, err) + } + if p, err := Find("opencode-go"); err != nil || p.Key != "sk-go-9a8b7c" || p.Preset != "opencode-go" { + t.Fatalf("OpenCode Go saved: %+v %v", p, err) + } + if p, err := Find("opencode-zen"); err != nil || p.Key != "sk-zen-1f2e3d" || p.Preset != "opencode-zen" { + t.Fatalf("OpenCode Zen saved: %+v %v", p, err) + } + if _, err := Find("anthropic"); err == nil { + t.Fatal("a sign-in came in as a provider") + } + if it := itemsOf(t, "opencode")["opencode-go"]; it.Status != "same" { + t.Fatalf("after import: %+v", it) + } + if b, err := os.ReadFile(path); err != nil || string(b) != openCodeAuth { + t.Fatalf("auth.json changed: %v", err) + } + if fi, err := os.Stat(path); err != nil || !fi.ModTime().Equal(old) { + t.Fatalf("auth.json touched: %v", err) + } +} + +// With no XDG_DATA_HOME OpenCode keeps it in ~/.local/share/opencode, on +// Windows too. +func TestImportOpenCodeAuthWithoutXDG(t *testing.T) { + home := openCodeHome(t) + t.Setenv("XDG_DATA_HOME", "") + path := writeOpenCodeAuth(t, filepath.Join(home, ".local", "share")) + if s := openCodeSource(t); s.Path != path || !s.Found || s.Error != "" { + t.Fatalf("source: %+v", s) + } + if it := itemsOf(t, "opencode")["opencode-go"]; it.Provider.Key != "sk-go-9a8b7c" { + t.Fatalf("OpenCode Go: %+v", it) + } +} + +// A file that isn't there is "not found"; one that can't be read or +// parsed is unknown, an error, never an OpenCode with nothing in it. +func TestImportOpenCodeAuthUnknown(t *testing.T) { + home := openCodeHome(t) + data := filepath.Join(home, "data") + t.Setenv("XDG_DATA_HOME", data) + if s := openCodeSource(t); s.Found || s.Error != "" || len(s.Items) != 0 { + t.Fatalf("missing: %+v", s) + } + path := writeOpenCodeAuth(t, data) + os.WriteFile(path, []byte(`{"opencode-go": {"type": "api", "key": "sk-go`), 0o600) + if s := openCodeSource(t); !s.Found || s.Error == "" || len(s.Items) != 0 { + t.Fatalf("cut short: %+v", s) + } + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + return // no permission bits to take away, or none that bind root + } + writeOpenCodeAuth(t, data) + os.Chmod(path, 0) + if s := openCodeSource(t); !s.Found || s.Error == "" || len(s.Items) != 0 { + t.Fatalf("unreadable file: %+v", s) + } + os.Chmod(path, 0o600) + dir := filepath.Dir(path) + os.Chmod(dir, 0) + t.Cleanup(func() { os.Chmod(dir, 0o700) }) + if s := openCodeSource(t); !s.Found || s.Error == "" || len(s.Items) != 0 { + t.Fatalf("unreadable folder: %+v", s) + } +} diff --git a/internal/provider/importapps.go b/internal/provider/importapps.go index 85dc6b699..13dc70708 100644 --- a/internal/provider/importapps.go +++ b/internal/provider/importapps.go @@ -1,7 +1,7 @@ package provider // Providers another app has already set up — CC Switch, Alma, Claude Code's -// own settings — offered for the user to bring over: each source is read +// own settings, OpenCode's sign-ins — 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. @@ -12,6 +12,7 @@ import ( "database/sql" "encoding/json" "errors" + "io/fs" "maps" "net" "net/url" @@ -72,23 +73,37 @@ type AppPick struct { } // appReaders are the apps magpie knows, by name as the picker lists them. +// One asked is read only when the user opens the import, never by the +// Providers page's own look for configurations (DiscoverSources): +// OpenCode's auth.json holds every sign-in OpenCode has, not only keys. var appReaders = []struct { id, name string path func() string read func(path string) ([]AppImport, error) + asked bool }{ - {"alma", "Alma", almaPath, readAlma}, - {"cc-switch", "CC Switch", ccSwitchPath, readCCSwitch}, - {"claude-code", "Claude Code", claudeSettingsPath, readClaudeSettings}, - {"codex", "Codex", codexConfigPath, readCodexConfig}, + {"alma", "Alma", almaPath, readAlma, false}, + {"cc-switch", "CC Switch", ccSwitchPath, readCCSwitch, false}, + {"claude-code", "Claude Code", claudeSettingsPath, readClaudeSettings, false}, + {"codex", "Codex", codexConfigPath, readCodexConfig, false}, + {"opencode", "OpenCode", openCodeAuthPath, readOpenCodeAuth, true}, } -// ImportSources reads every app magpie can import from. -func ImportSources() []AppSource { +// ImportSources reads every app magpie can import from, as the user asked. +func ImportSources() []AppSource { return importSources(true) } + +// DiscoverSources reads the apps the Providers page looks in by itself: +// those not read only when asked. +func DiscoverSources() []AppSource { return importSources(false) } + +func importSources(asked bool) []AppSource { have := load().Providers used := map[string]bool{} // ids across all sources, so two never collide var out []AppSource for _, r := range appReaders { + if r.asked && !asked { + continue + } s := AppSource{ID: r.id, Name: r.name, Path: r.path(), Items: []AppImport{}} if _, err := os.Stat(s.Path); err == nil { s.Found = true @@ -97,6 +112,10 @@ func ImportSources() []AppSource { s.Error = err.Error() } s.Items = append(s.Items, settle(items, have, used)...) // [] rather than null when there is nothing + } else if !errors.Is(err, fs.ErrNotExist) { + // there, as far as anyone can tell, but not to be looked at: not + // "not found", which would say the app has nothing + s.Found, s.Error = true, err.Error() } out = append(out, s) } @@ -432,6 +451,10 @@ func presetAt(e endpoints) (*PresetDef, *Region, bool) { } return hit, exact } + // a preset whose endpoints the entry uses wins over an earlier one at + // the same host: OpenCode Zen's are on opencode.ai beside OpenCode Go's + var first *PresetDef + var firstNear *Region for i := range presets { pr := &presets[i] if pr.Kind == KindLocal { @@ -453,14 +476,13 @@ func presetAt(e endpoints) (*PresetDef, *Region, bool) { near = r } } - if hit { - return pr, nil, false - } - if near != nil { - return pr, near, false + if first == nil && hit { + first = pr + } else if first == nil && near != nil { + first, firstNear = pr, near } } - return nil, nil, false + return first, firstNear, false } // ---- CC Switch -------------------------------------------------------------