provider: a signed-out Claude Code account goes away, and any account can be removed (#9)

Logging out of Claude Code can leave its credentials behind; claude auth status
now decides. Removing a Claude, Codex or Copilot account hides it from magpie
(the agent stays signed in); Add it back, or magpie provider add <id>, restores it.
This commit is contained in:
yetone
2026-09-24 12:42:14 +08:00
parent 14663c3a65
commit d77e14701b
7 changed files with 146 additions and 43 deletions
+12 -3
View File
@@ -605,14 +605,19 @@ function renderProviders() {
}
// Sign-ins magpie found but leaves alone, so nobody wonders why an agent that
// is clearly logged in is not in the list. Empty today.
// is clearly logged in is not in the list: the ones the user removed.
function renderExcluded() {
const box = $("#excluded");
box.replaceChildren();
for (const x of providers.excluded) {
const r = el("div", "excluded");
r.append(icon(x.agentIcon), el("span", "", ""));
r.lastChild.append(el("b", "", t("{agent} is signed in, but stays out of this list. ", { agent: x.agentName })), x.why);
r.lastChild.append(el("b", "", t("{agent} is signed in, but stays out of this list. ", { agent: x.agentName })), t(x.why));
if (x.provider) {
const back = el("button", "link", t("Add it back"));
back.onclick = () => providerAction("save", { id: x.provider }, t("{name} added back", { name: x.agentName }));
r.lastChild.append(" ", back);
}
box.append(r);
}
}
@@ -1246,7 +1251,11 @@ function renderEditor(p, presetID) {
ed.append(...field(t("Models"), renderModels(p), ""));
ed.append(...field(t("Endpoints"), renderEndpoints(p, p)));
const bar = el("div", "bar");
bar.append(el("span", "grow"));
// removing only hides it from magpie; the agent stays signed in
const del = el("button", "text danger", t("Remove"));
del.title = t("{agent} stays signed in; magpie just stops offering it", { agent: a.agentName });
del.onclick = () => providerAction("delete", { id: p.id }, t("{name} removed", { name: p.name }));
bar.append(del, el("span", "grow"));
const cancel = el("button", "text", t("Cancel"));
cancel.onclick = cancelEdit;
const saveBtn = el("button", "text primary", t("Save"));
+4
View File
@@ -28,6 +28,10 @@ const I18N = {
"same as model": "同主模型",
"same as model ({model})": "同主模型({model})",
"Same as model": "同主模型",
"{agent} stays signed in; magpie just stops offering it": "{agent} 仍保持登录,只是 magpie 不再提供它",
"You removed it from magpie.": "你已把它从 magpie 中移除。",
"Add it back": "加回来",
"{name} added back": "已加回 {name}",
"auth": "认证",
"agent default": "Agent 默认值",
"default": "默认",
+43 -18
View File
@@ -69,14 +69,20 @@ func (p Provider) Prepare(body []byte) []byte {
// Exclusion is a sign-in magpie found but will not offer as a provider.
type Exclusion struct {
Agent string `json:"agent"`
Why string `json:"why"`
Agent string `json:"agent"`
Provider string `json:"provider,omitempty"` // set when the user removed it; saving it brings it back
Why string `json:"why"`
}
// Excluded lists sign-ins magpie detects but cannot expose. It is currently
// empty, but remains part of the API so the CLI and GUI can explain future
// account types that are detectable but not usable.
func Excluded() []Exclusion { return nil }
// Excluded lists sign-ins magpie detects but leaves out: the accounts the
// user removed from magpie.
func Excluded() []Exclusion {
var out []Exclusion
for _, a := range Hidden() {
out = append(out, Exclusion{Agent: a.Account.Agent, Provider: a.ID, Why: "You removed it from magpie."})
}
return out
}
const (
claudeClientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
@@ -111,6 +117,7 @@ var (
claudeStatusAt time.Time
claudeStatusUser string
claudeStatusPlan string
claudeStatusOut bool // Claude Code says nobody is signed in
claudeCacheMu sync.Mutex
claudeCacheAt time.Time
@@ -265,7 +272,8 @@ func saveClaudeCredential(loc claudeCredentialLocation, c claudeCredentials) err
return nil
}
func claudeExecutable() string {
// claudeExecutable finds the claude CLI; a var so tests can fake it.
var claudeExecutable = func() string {
if p, err := exec.LookPath("claude"); err == nil {
return p
}
@@ -282,33 +290,40 @@ func claudeExecutable() string {
// blob intentionally contains tokens and plan metadata but no display identity;
// `claude auth status --json` is the authoritative, non-secret view shown by the
// CLI. Cache it briefly because the providers screen refreshes often.
func claudeIdentity() (string, string) {
//
// It also says when Claude Code is signed out even though credentials are
// still lying around (a keychain item logout left behind), so a signed-out
// account stops showing up as a provider.
func claudeIdentity() (user, plan string, signedOut bool) {
claudeStatusMu.Lock()
defer claudeStatusMu.Unlock()
if time.Since(claudeStatusAt) < 30*time.Second {
return claudeStatusUser, claudeStatusPlan
return claudeStatusUser, claudeStatusPlan, claudeStatusOut
}
claudeStatusAt = time.Now()
path := claudeExecutable()
if path == "" {
return claudeStatusUser, claudeStatusPlan
return claudeStatusUser, claudeStatusPlan, claudeStatusOut
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, path, "auth", "status", "--json").Output()
if err != nil {
return claudeStatusUser, claudeStatusPlan
}
// signed out, `claude auth status` exits 1 but still prints the JSON
out, _ := exec.CommandContext(ctx, path, "auth", "status", "--json").Output()
var status struct {
LoggedIn bool `json:"loggedIn"`
LoggedIn *bool `json:"loggedIn"`
Email string `json:"email"`
SubscriptionType string `json:"subscriptionType"`
}
if json.Unmarshal(out, &status) == nil && status.LoggedIn {
if json.Unmarshal(out, &status) != nil || status.LoggedIn == nil {
return claudeStatusUser, claudeStatusPlan, claudeStatusOut
}
claudeStatusOut = !*status.LoggedIn
claudeStatusUser, claudeStatusPlan = "", ""
if *status.LoggedIn {
claudeStatusUser = strings.TrimSpace(status.Email)
claudeStatusPlan = strings.TrimSpace(status.SubscriptionType)
}
return claudeStatusUser, claudeStatusPlan
return claudeStatusUser, claudeStatusPlan, claudeStatusOut
}
func claudeAccount() (Provider, bool) {
@@ -316,7 +331,10 @@ func claudeAccount() (Provider, bool) {
if !ok {
return Provider{}, false
}
user, statusPlan := claudeIdentity()
user, statusPlan, signedOut := claudeIdentity()
if signedOut {
return Provider{}, false
}
plan := c.OAuth.SubscriptionType
if statusPlan != "" {
plan = statusPlan
@@ -889,3 +907,10 @@ func copilotModels(ctx context.Context, github string) ([]catalog.Model, error)
}
return out, nil
}
// forgetClaudeStatus drops what `claude auth status` said; tests use it.
func forgetClaudeStatus() {
claudeStatusMu.Lock()
claudeStatusAt, claudeStatusUser, claudeStatusPlan, claudeStatusOut = time.Time{}, "", "", false
claudeStatusMu.Unlock()
}
+44 -4
View File
@@ -63,12 +63,15 @@ func signIn(t *testing.T) string {
// forgets anything a previous test cached.
func isolate(t *testing.T) {
t.Helper()
oldKeychain, oldURL, oldBase := claudeKeychain, claudeTokenURL, claudeBase
oldKeychain, oldURL, oldBase, oldExe := claudeKeychain, claudeTokenURL, claudeBase, claudeExecutable
claudeKeychain = false
claudeExecutable = func() string { return "" }
forgetClaudeCredential()
forgetClaudeStatus()
t.Cleanup(func() {
claudeKeychain, claudeTokenURL, claudeBase = oldKeychain, oldURL, oldBase
claudeKeychain, claudeTokenURL, claudeBase, claudeExecutable = oldKeychain, oldURL, oldBase, oldExe
forgetClaudeCredential()
forgetClaudeStatus()
})
}
@@ -107,11 +110,25 @@ func TestAccountsAreProviders(t *testing.T) {
if len(codex.Exposed()) != 1 || codex.Exposed()[0].ID != "gpt-5.5" || codex.Responses == "" {
t.Fatalf("picks: %+v", codex.Exposed())
}
// removing an account hides it from magpie; adding it back restores
// it with its picks
if err := Delete("codex"); err != nil {
t.Fatal(err)
}
if codex, _ = find(All(), "codex"); len(codex.Models) != 0 || codex.Account == nil {
t.Fatalf("after delete: %+v", codex)
if _, ok := find(All(), "codex"); ok {
t.Fatal("codex still listed after remove")
}
if _, _, ok := Resolve("codex/gpt-5.5"); ok {
t.Fatal("removed codex still resolves")
}
if x := Excluded(); len(x) != 1 || x[0].Provider != "codex" || x[0].Agent != "codex" {
t.Fatalf("excluded: %+v", x)
}
if err := Save(Provider{ID: "codex", Models: []string{"gpt-5.5"}}); err != nil {
t.Fatal(err)
}
if codex, ok = find(All(), "codex"); !ok || len(codex.Models) != 1 || codex.Account == nil || len(Excluded()) != 0 {
t.Fatalf("after add back: %+v", codex)
}
// signed out: gone, and a stale picks entry is not a provider
@@ -453,3 +470,26 @@ func TestClaudeBillingBody(t *testing.T) {
t.Fatalf("non-json: %s", out)
}
}
// Logging out of Claude Code can leave its credentials behind; what the CLI
// says wins, so a signed-out account is not a provider.
func TestClaudeSignedOut(t *testing.T) {
home := claudeHome(t)
claudeSignIn(t, home, time.Now().Add(time.Hour))
status := `{"loggedIn": true, "email": "me@example.com", "subscriptionType": "max"}`
exe := filepath.Join(home, "claude")
fake := func() {
os.WriteFile(exe, []byte("#!/bin/sh\ncat <<'X'\n"+status+"\nX\n"), 0o755)
forgetClaudeStatus()
}
claudeExecutable = func() string { return exe }
fake()
if p, ok := find(All(), "claude"); !ok || p.Account.User != "me@example.com" {
t.Fatalf("signed in: %+v %v", p, ok)
}
status = `{"loggedIn": false, "authMethod": "none"}`
fake()
if _, ok := find(All(), "claude"); ok {
t.Fatal("claude listed after sign-out")
}
}
+29 -12
View File
@@ -52,6 +52,10 @@ type Provider struct {
Website string `json:"website,omitempty"`
KeysURL string `json:"keysUrl,omitempty"`
// Hidden is set on an account the user removed from magpie; the
// agent stays signed in, magpie just leaves it alone.
Hidden bool `json:"hidden,omitempty"`
// Account is set when the provider is an agent the user signed in to
// (see account.go); it is derived, never stored.
Account *Account `json:"-"`
@@ -98,26 +102,39 @@ func store(f file) error {
// model picks for one of those accounts.
func All() []Provider {
stored := load().Providers
picks := map[string][]string{}
picks := map[string]Provider{}
var out []Provider
for _, p := range stored {
p = normalize(p)
if p.Chat == "" && p.Responses == "" && p.Anthropic == "" {
picks[p.ID] = p.Models
picks[p.ID] = p
continue
}
out = append(out, p)
}
for _, a := range Accounts() {
if _, taken := find(out, a.ID); taken {
if _, taken := find(out, a.ID); taken || picks[a.ID].Hidden {
continue
}
a.Models = picks[a.ID]
a.Models = picks[a.ID].Models
out = append(out, a)
}
return out
}
// Hidden lists the signed-in accounts the user removed from magpie.
func Hidden() []Provider {
var out []Provider
for _, a := range Accounts() {
for _, p := range load().Providers {
if p.ID == a.ID && p.Hidden {
out = append(out, a)
}
}
}
return out
}
func find(ps []Provider, id string) (Provider, bool) {
for _, p := range ps {
if p.ID == id {
@@ -162,7 +179,7 @@ func Save(p Provider) error {
}
if a, ok := find(Accounts(), p.ID); ok {
// an account keeps only the user's model picks; the rest is the
// agent's own sign-in
// agent's own sign-in. Saving it again brings a removed one back.
p = Provider{ID: a.ID, Models: p.Models}
} else {
if p.Chat == "" && p.Responses == "" && p.Anthropic == "" {
@@ -183,18 +200,18 @@ func Save(p Provider) error {
return store(f)
}
// Delete removes a provider. For an account it forgets the model picks;
// signing out is the agent's job.
// Delete removes a provider. An account is only hidden from magpie (its
// model picks kept); signing out is the agent's job.
func Delete(id string) error {
if _, ok := find(Accounts(), id); ok {
f := load()
keep := f.Providers[:0]
for _, p := range f.Providers {
if p.ID != id {
keep = append(keep, p)
for i := range f.Providers {
if f.Providers[i].ID == id {
f.Providers[i].Hidden = true
return store(f)
}
}
f.Providers = keep
f.Providers = append(f.Providers, Provider{ID: id, Hidden: true})
return store(f)
}
f := load()
+8 -4
View File
@@ -49,18 +49,22 @@ func SubscriptionUsage(ctx context.Context) []SubscriptionQuota {
return append([]SubscriptionQuota(nil), subscriptionUsageCache.data...)
}
var out []SubscriptionQuota
if _, _, ok := claudeCredential(); ok {
hidden := map[string]bool{}
for _, p := range load().Providers {
hidden[p.ID] = p.Hidden
}
if _, ok := claudeAccount(); ok && !hidden["claude"] {
out = append(out, claudeSubscriptionUsage(ctx))
}
if home, err := os.UserHomeDir(); err == nil {
if _, ok := codexAccount(home); ok {
if p, ok := codexAccount(home); ok && !hidden[p.ID] {
out = append(out, codexSubscriptionUsage(ctx, filepath.Join(home, ".codex", "auth.json")))
}
cfg := os.Getenv("XDG_CONFIG_HOME")
if cfg == "" {
cfg = filepath.Join(home, ".config")
}
if app, ok := copilotLogin(cfg); ok {
if app, ok := copilotLogin(cfg); ok && !hidden["copilot"] {
out = append(out, copilotSubscriptionUsage(ctx, app.Token))
}
}
@@ -101,7 +105,7 @@ func claudeSubscriptionUsage(ctx context.Context) SubscriptionQuota {
q.Error = err.Error()
return q
}
_, plan := claudeIdentity()
_, plan, _ := claudeIdentity()
q.Plan = plan
var data struct {
FiveHour *quotaWire `json:"five_hour"`
+6 -2
View File
@@ -34,7 +34,7 @@ const providerUsage = `usage:
// providers: `magpie providers`
func providers() error {
all := provider.All()
if len(all) == 0 {
if len(all) == 0 && len(provider.Excluded()) == 0 {
fmt.Println(muted.Render("no providers yet ·"), "magpie provider add deepseek sk-…", muted.Render("· magpie presets lists the vendors"))
return nil
}
@@ -80,7 +80,11 @@ func providers() error {
name = a.Name
}
fmt.Println()
fmt.Println(" ", muted.Render(name+" is signed in but not offered: "+x.Why))
back := ""
if x.Provider != "" {
back = " · magpie provider add " + x.Provider + " brings it back"
}
fmt.Println(" ", muted.Render(name+" is signed in but not offered: "+x.Why+back))
}
return nil
}