Files
magpie/internal/provider/session_identity.go
T
forever 8a7f600cb0 provider: the Requests page keeps its cache when magpie first saves a signed-in account (#1049)
SessionIdentities lists the identity in Codex's auth.json (and Claude's
profile), then one per saved login. Once rememberLogins had saved a copy
of the account signed in now, that account was listed twice. QueryPage
keys the request cache on this list, so the save that added the copy
changed the key, and the next Requests page query dropped every cached
chunk and read and priced every session log again, though no identity
had changed. Users could see that as one more slow Requests page after
magpie saved its first copy of an account: one an agent was signed in
to outside magpie (codex login, Claude Code's /login), or the one
already signed in when magpie first ran. Switching between saved
accounts and signing in through magpie never caused it: rememberLogins
replaces a saved account in place, and magpie's own sign-in (addLogin)
writes logins.json together with auth.json. The resolver gets nothing
from the duplicate: an identical entry never changes which email or
login a session resolves to.

SessionIdentities now leaves out a saved identity equal to one already
in the list. One that differs in any field is still listed, such as
another member of the same workspace (the same account id, another
email): sessionResolver.codexUser names no member when two identities
share a workspace and user id but not the email.

TestSessionIdentitiesListTheSavedCurrentAccountOnce saves the account
Codex is signed in to with rememberLogins(true), checks that it was
saved and that the identities are unchanged, then saves a second
member of the same workspace and checks that it is listed.

A scratch test on main (c5a54bc7) showed when the list changed:
switching between two saved Codex accounts changed it once and the save
after that didn't; writing a new account into auth.json changed it, and
the save after that changed it again (3 to 4 identities). With this
change the second change is gone. Found while characterising
TestQueryPageSourceAndIdentityInvalidation: run alone on main with only
this change applied, it gets past request_page_test.go:224 "unchanged
source rebuilt" (the cache is kept) and stops at
request_page_test.go:237, an assumption of the test's own, fixed in
#1045.

Verified on 698da36f (go test -tags nogui under a temp HOME, Go caches
pinned), as first on c5a54bc7:
- -run '^TestSessionIdentities' ./internal/provider: both PASS, also at
  local 23:59:59.9, 00:00:30 and 12:00:00.
- go test ./internal/provider ok, and ok with -shuffle=11. With
  -shuffle=22 and 33, TestCopilotSignAndModels fails
  (account_test.go:403: available after fetch: ...), and at 33
  TestPlanQuotas too (planquota_test.go:290: cards: map[]). They fail
  the same with this commit's test skipped and session_identity.go as on
  main: -shuffle orders every test before -skip leaves one out, so the
  others keep their order. Main fails TestCopilotSignAndModels at
  -shuffle=33 too. It is an order dependence among the provider tests,
  apart from this change.
- Broken on purpose, the new test fails each time. A dedupe on Agent and
  AccountID alone: "session_identity_test.go:63: another member of the
  workspace was left out: [{Agent:codex AccountID:acct-1 ...
  User:me@example.com ...}]". rememberLogins writing nothing:
  "session_identity_test.go:49: the signed-in account wasn't saved: 0
  saved logins".

Without the change in session_identity.go:
  --- FAIL: TestSessionIdentitiesListTheSavedCurrentAccountOnce
  session_identity_test.go:53: saving the signed-in account changed its
  identities: before [{Agent:codex AccountID:acct-1 ...}], after
  [{Agent:codex AccountID:acct-1 ...}
  {Agent:codex AccountID:acct-1 ...}]

On this commit: go test -tags nogui ./... ok, go vet ./... ok, gofmt
clean, and -race -count=20 -run '^TestSessionIdentities'
./internal/provider ok.
2026-10-07 02:09:17 +08:00

91 lines
3.2 KiB
Go

package provider
// Local identities for associating historical session metadata. No credential
// refresh, sign-in discovery command or login-store write is needed here.
import (
"cmp"
"encoding/json"
"path/filepath"
"slices"
"github.com/yetone/magpie/internal/filememo"
)
// SessionIdentity is an account's public identity, without its credentials.
type SessionIdentity struct {
Agent, AccountID, UserID, OrganizationID, User string
// OfficialLogin describes this account's recorded login method, not the
// route or credentials used for any particular historical request.
OfficialLogin bool
}
// SessionIdentities reads the agent's current identity and remembered identities.
// Callers must match the IDs recorded in a session; presence alone is not evidence
// that the account served that session's requests.
func SessionIdentities(codexDir string) []SessionIdentity {
out := currentSessionIdentities(codexDir)
for _, l := range readLogins() {
// The account signed in now is saved too once rememberLogins has
// seen it. It is listed once, so the usage cache keyed on this list
// isn't thrown away when that copy is saved.
if id, ok := savedSessionIdentity(l); ok && !slices.Contains(out, id) {
out = append(out, id)
}
}
return out
}
func savedSessionIdentity(l savedLogin) (SessionIdentity, bool) {
switch l.Agent {
case "codex":
return codexSessionIdentity(l.Auth)
case "claude":
return claudeSessionIdentity(l.Profile)
}
return SessionIdentity{}, false
}
func codexSessionIdentity(b []byte) (SessionIdentity, bool) {
var a codexAuth
if json.Unmarshal(b, &a) != nil || a.AuthMode == "apikey" {
return SessionIdentity{}, false
}
claims := jwtClaims(a.Tokens.IDToken)
id := cmp.Or(a.Tokens.AccountID, claimString(claims, "https://api.openai.com/auth", "chatgpt_account_id"))
user := codexUser(claims)
return SessionIdentity{Agent: "codex", AccountID: id, OfficialLogin: a.AuthMode == "chatgpt",
UserID: cmp.Or(claimString(claims, "https://api.openai.com/auth", "chatgpt_user_id"), claimString(claims, "https://api.openai.com/auth", "user_id")), User: user}, id != "" && user != ""
}
func claudeSessionIdentity(b []byte) (SessionIdentity, bool) {
var a struct {
Account string `json:"accountUuid"`
Org string `json:"organizationUuid"`
Email string `json:"emailAddress"`
}
if json.Unmarshal(b, &a) != nil {
return SessionIdentity{}, false
}
// This profile is read only from Claude's oauthAccount or its saved copy.
return SessionIdentity{Agent: "claude", AccountID: a.Account, OrganizationID: a.Org, User: a.Email, OfficialLogin: true}, a.Account != "" && a.Email != ""
}
func currentSessionIdentities(codexDir string) []SessionIdentity {
var out []SessionIdentity
// Cache only the identity parse, not another copy of the credential blob.
current, _ := filememo.Read("session codex identity", filepath.Join(codexDir, "auth.json"), func(b []byte) ([]SessionIdentity, error) {
if id, ok := codexSessionIdentity(b); ok {
return []SessionIdentity{id}, nil
}
return nil, nil
})
out = append(out, current...)
if acct, ok := claudeProfileAccount(); ok {
b, _ := json.Marshal(acct)
if id, ok := claudeSessionIdentity(b); ok {
out = append(out, id)
}
}
return out
}