Merge branch 'main' into worktree-agent-a3ec65b20dc3028b9
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
// Account switching (see internal/claudeaccounts) acts on the Claude Code home
|
||||
// a chat's directory selects: the CLAUDE_CONFIG_DIR its processes run with.
|
||||
|
||||
// ErrNoConfigDir is returned for a chat whose directory selects no Claude
|
||||
// home of its own.
|
||||
var ErrNoConfigDir = errors.New("this chat's directory does not set CLAUDE_CONFIG_DIR, so it has no Claude home of its own to switch")
|
||||
|
||||
// AccountConfigDir is the CLAUDE_CONFIG_DIR a process started in directory
|
||||
// runs with: the directory's own environment (direnv, mise) over base.
|
||||
func AccountConfigDir(ctx context.Context, resolver *workenv.Resolver, directory string, base []string) (string, error) {
|
||||
env := base
|
||||
if resolver != nil && strings.TrimSpace(directory) != "" {
|
||||
env = resolver.Resolve(ctx, directory, base).Apply(base)
|
||||
}
|
||||
dir, ok := envValue(env, "CLAUDE_CONFIG_DIR")
|
||||
dir = strings.TrimSpace(dir)
|
||||
if !ok || dir == "" || !filepath.IsAbs(dir) {
|
||||
return "", ErrNoConfigDir
|
||||
}
|
||||
return filepath.Clean(dir), nil
|
||||
}
|
||||
|
||||
func (c *Chat) accountConfigDir(ctx context.Context, directory string) (string, error) {
|
||||
return AccountConfigDir(ctx, c.dirEnv, directory, os.Environ())
|
||||
}
|
||||
|
||||
// accountKeyFor is the quota key decodeAccountIdentity derives from an
|
||||
// initialize response for a subscription login.
|
||||
func accountKeyFor(email, organization string) string {
|
||||
return strings.TrimSpace(email) + "\x00" + strings.TrimSpace(organization) + "\x00" + "firstParty"
|
||||
}
|
||||
|
||||
// ClaudeAccounts runs one claude_account* operation for the chat sessionID in
|
||||
// directory ("" uses the open session's directory). After a switch every
|
||||
// open chat on the same Claude home is moved to the new account's quota and
|
||||
// told so, which clears a usage limit the old account had reached.
|
||||
func (c *Chat) ClaudeAccounts(ctx context.Context, sessionID, directory, operation, name string) (protocol.ClaudeAccountList, error) {
|
||||
if strings.TrimSpace(directory) == "" {
|
||||
if s := c.session(sessionID); s != nil {
|
||||
s.mu.Lock()
|
||||
directory = s.directory
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
configDir, err := c.accountConfigDir(ctx, directory)
|
||||
if err != nil {
|
||||
return protocol.ClaudeAccountList{}, err
|
||||
}
|
||||
store := claudeaccounts.Store{ConfigDir: configDir}
|
||||
switch operation {
|
||||
case protocol.ClaudeAccounts:
|
||||
return store.List()
|
||||
case protocol.ClaudeAccountSave:
|
||||
return store.Save(name)
|
||||
case protocol.ClaudeAccountRemove:
|
||||
return store.Remove(name)
|
||||
case protocol.ClaudeAccountUse:
|
||||
list, err := store.Use(name)
|
||||
if err != nil {
|
||||
return list, err
|
||||
}
|
||||
email, org, plan, ok := store.Identity()
|
||||
if ok {
|
||||
list.Usage = c.switchAccount(ctx, configDir, accountKeyFor(email, org), plan)
|
||||
log.Printf("claude account: %s switched to a saved account", configDir)
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation)
|
||||
}
|
||||
|
||||
// switchAccount records that configDir now signs in as key: its quota report
|
||||
// is marked switched (an empty one when nothing is known yet), and every open
|
||||
// session on that Claude home takes the new key and republishes its usage.
|
||||
func (c *Chat) switchAccount(ctx context.Context, configDir, key, plan string) *protocol.ChatAccountUsage {
|
||||
now := time.Now().UnixMilli()
|
||||
c.quotaMu.Lock()
|
||||
usage := c.quotas[key].Clone()
|
||||
if usage == nil {
|
||||
usage = &protocol.ChatAccountUsage{Harness: quotaHarness, Source: "account_switch", Plan: plan, AsOf: now}
|
||||
}
|
||||
usage.SwitchedAt = now
|
||||
if c.quotas == nil {
|
||||
c.quotas = map[string]*protocol.ChatAccountUsage{}
|
||||
}
|
||||
c.quotas[key] = usage
|
||||
c.quotaMu.Unlock()
|
||||
|
||||
c.mu.Lock()
|
||||
sessions := make([]*session, 0, len(c.sessions))
|
||||
for _, s := range c.sessions {
|
||||
sessions = append(sessions, s)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
for _, s := range sessions {
|
||||
s.mu.Lock()
|
||||
directory := s.directory
|
||||
s.mu.Unlock()
|
||||
if dir, err := c.accountConfigDir(ctx, directory); err != nil || dir != configDir {
|
||||
continue
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.account = accountIdentity{key: key, plan: plan}
|
||||
s.mu.Unlock()
|
||||
s.republishUsage()
|
||||
}
|
||||
return usage.Clone()
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func writeLogin(t *testing.T, profile, email, uuid, token string) {
|
||||
t.Helper()
|
||||
writeFile(t, filepath.Join(profile, ".credentials.json"), `{"claudeAiOauth":{"accessToken":"access-`+token+`","refreshToken":"refresh-`+token+`","expiresAt":1,"subscriptionType":"pro","accountUuid":"`+uuid+`"}}`)
|
||||
writeFile(t, filepath.Join(profile, ".claude.json"), "{\n \"numStartups\": 3,\n \"oauthAccount\": {\"accountUuid\":\""+uuid+"\",\"emailAddress\":\""+email+"\",\"organizationName\":\"Org\"}\n}")
|
||||
}
|
||||
|
||||
func TestUseAccountMovesTheHomesChatsToTheNewAccountQuota(t *testing.T) {
|
||||
chat := directoryChat(t)
|
||||
var logs bytes.Buffer
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(os.Stderr)
|
||||
profile := t.TempDir()
|
||||
directory := t.TempDir()
|
||||
writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.allowed"), "")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`"}`)
|
||||
ctx := context.Background()
|
||||
|
||||
writeLogin(t, profile, "a@example.invalid", "uuid-a", "a1")
|
||||
if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountSave, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeLogin(t, profile, "b@example.invalid", "uuid-b", "b1")
|
||||
if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountSave, "B"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Two chats on the home are on b, which is out of quota; a third chat
|
||||
// elsewhere is on another account.
|
||||
oldKey := accountKeyFor("b@example.invalid", "Org")
|
||||
limited := &protocol.ChatAccountUsage{Harness: quotaHarness, Windows: []protocol.ChatQuotaWindow{{ID: "five_hour", Label: "5-hour", UsedPercent: 100, ResetsAt: 1}}}
|
||||
chat.quotas = map[string]*protocol.ChatAccountUsage{oldKey: limited}
|
||||
here := chat.sessionFor("11111111-1111-4111-8111-111111111111", directory)
|
||||
alsoHere := chat.sessionFor("22222222-2222-4222-8222-222222222222", directory)
|
||||
elsewhere := chat.sessionFor("33333333-3333-4333-8333-333333333333", t.TempDir())
|
||||
for _, s := range []*session{here, alsoHere} {
|
||||
s.account = accountIdentity{key: oldKey, plan: "pro"}
|
||||
}
|
||||
elsewhere.account = accountIdentity{key: "other"}
|
||||
frames := subscribe(t, chat, here.id)
|
||||
|
||||
list, err := chat.ClaudeAccounts(ctx, here.id, "", protocol.ClaudeAccountUse, "a@example.invalid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list.Active == nil || list.Active.Email != "a@example.invalid" || list.Usage == nil || list.Usage.SwitchedAt == 0 || len(list.Usage.Windows) != 0 {
|
||||
t.Fatalf("use reply = %+v usage=%+v", list, list.Usage)
|
||||
}
|
||||
newKey := accountKeyFor("a@example.invalid", "Org")
|
||||
if here.account.key != newKey || alsoHere.account.key != newKey || elsewhere.account.key != "other" {
|
||||
t.Fatalf("keys = %q %q %q", here.account.key, alsoHere.account.key, elsewhere.account.key)
|
||||
}
|
||||
pushed := waitFrame(t, frames, "switched usage", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil && frame.Usage.Account.SwitchedAt != 0
|
||||
}).Usage.Account
|
||||
if len(pushed.Windows) != 0 {
|
||||
t.Fatalf("the new account inherited the old quota: %+v", pushed)
|
||||
}
|
||||
data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json"))
|
||||
if !strings.Contains(string(data), "refresh-a1") {
|
||||
t.Fatal("credentials not switched")
|
||||
}
|
||||
for _, secret := range []string{"access-", "refresh-"} {
|
||||
if strings.Contains(logs.String(), secret) {
|
||||
t.Fatalf("log carries a token: %s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// A later quota report on the new account keeps the switch.
|
||||
known := mergeRateLimit(chat.quotas[newKey], []byte(`{"rateLimitType":"five_hour","utilization":0.2,"resetsAt":1900000000}`), "pro", time.Now())
|
||||
if known == nil || known.SwitchedAt != pushed.SwitchedAt {
|
||||
t.Fatalf("merge dropped the switch: %+v", known)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountsRefusedWithoutAClaudeHome(t *testing.T) {
|
||||
chat := directoryChat(t)
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
||||
os.Unsetenv("CLAUDE_CONFIG_DIR")
|
||||
if _, err := chat.ClaudeAccounts(context.Background(), "s", t.TempDir(), protocol.ClaudeAccounts, ""); err != ErrNoConfigDir {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -123,8 +123,13 @@ func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, pl
|
||||
return nil
|
||||
}
|
||||
next := &protocol.ChatAccountUsage{Harness: quotaHarness, Source: quotaSource, Plan: plan, AsOf: now.UnixMilli()}
|
||||
if next.Plan == "" && previous != nil {
|
||||
next.Plan = previous.Plan
|
||||
if previous != nil {
|
||||
if next.Plan == "" {
|
||||
next.Plan = previous.Plan
|
||||
}
|
||||
// A switch stays recorded: the refusal it cleared is still in the
|
||||
// transcript.
|
||||
next.SwitchedAt = previous.SwitchedAt
|
||||
}
|
||||
for _, entry := range quotaWindowOrder {
|
||||
if w, ok := windows[entry.id]; ok {
|
||||
|
||||
Reference in New Issue
Block a user