| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "testing" |
| 14 | "time" |
| 15 | ) |
| 16 | |
| 17 | func TestClaudeAccountPanelConcurrentWindowsAndLock(t *testing.T) { |
| 18 | s := testServer(t) |
| 19 | accountID := strings.Repeat("a", 24) |
| 20 | list := claudeAccountList{Accounts: []claudeAccount{{ID: accountID, Label: "原名称", Enabled: true, Status: "ready"}}} |
| 21 | if err := s.saveClaudeAccounts(list); err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | var wg sync.WaitGroup |
| 25 | for _, mutation := range []string{`"label":"工作"`, `"enabled":false`} { |
| 26 | wg.Add(1) |
| 27 | go func(mutation string) { |
| 28 | defer wg.Done() |
| 29 | w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"update","id":"`+accountID+`",`+mutation+`}`, true) |
| 30 | if w.Code != http.StatusOK { |
| 31 | t.Errorf("update: %d %s", w.Code, w.Body) |
| 32 | } |
| 33 | }(mutation) |
| 34 | } |
| 35 | wg.Wait() |
| 36 | list, err := s.loadClaudeAccounts() |
| 37 | if err != nil || len(list.Accounts) != 1 || list.Accounts[0].Enabled || list.Accounts[0].Label != "工作" { |
| 38 | t.Fatalf("lost concurrent edit: %+v %v", list, err) |
| 39 | } |
| 40 | a := list.Accounts[0] |
| 41 | w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"update","id":"`+a.ID+`","label":"已归档","enabled":false}`, true) |
| 42 | if w.Code != 200 { |
| 43 | t.Fatal(w.Code, w.Body) |
| 44 | } |
| 45 | reopened := &Server{profile: s.profile} |
| 46 | list, err = reopened.loadClaudeAccounts() |
| 47 | if err != nil || list.Accounts[0].Enabled || list.Accounts[0].Label != "已归档" { |
| 48 | t.Fatalf("updated settings did not persist: %+v %v", list, err) |
| 49 | } |
| 50 | w = request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"update","id":"`+a.ID+`","enabled":true}`, true) |
| 51 | if w.Code != 200 || !strings.Contains(w.Body.String(), `"enabled":true`) { |
| 52 | t.Fatal(w.Code, w.Body) |
| 53 | } |
| 54 | s.account.lock() |
| 55 | if w = request(s, "GET", "/api/claude-accounts", "", "", true); w.Code != http.StatusLocked { |
| 56 | t.Fatal("locked Cage exposed account data", w.Code) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | func TestClaudeAccountOnlyEmptyRegistryFallsBack(t *testing.T) { |
| 61 | s := testServer(t) |
| 62 | if id, err := s.selectClaudeAccount("", false, ""); err != nil || id.ID != "" { |
| 63 | t.Fatalf("existing user compatibility: %q %v", id, err) |
| 64 | } |
| 65 | list := claudeAccountList{Accounts: []claudeAccount{{ID: strings.Repeat("a", 24), Label: "A", Enabled: true, Status: "pending"}}} |
| 66 | if err := s.saveClaudeAccounts(list); err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | if _, err := s.selectClaudeAccount("", false, ""); err == nil { |
| 70 | t.Fatal("unsigned managed account silently switched to legacy") |
| 71 | } |
| 72 | list.Accounts[0].Enabled = false |
| 73 | list.Accounts[0].Status = "ready" |
| 74 | if err := s.saveClaudeAccounts(list); err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | if _, err := s.selectClaudeAccount("", false, ""); err == nil { |
| 78 | t.Fatal("disabled pool silently switched to legacy") |
| 79 | } |
| 80 | if id, err := s.selectClaudeAccount(list.Accounts[0].ID, true, ""); err != nil || id.ID != list.Accounts[0].ID { |
| 81 | t.Fatalf("cannot reauthenticate paused profile: %q %v", id, err) |
| 82 | } |
| 83 | if err := os.WriteFile(filepath.Join(s.profile, "claude-accounts.json"), []byte("{"), 0600); err != nil { |
| 84 | t.Fatal(err) |
| 85 | } |
| 86 | if _, err := s.selectClaudeAccount("", false, ""); err == nil { |
| 87 | t.Fatal("corrupt registry silently switched to legacy") |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | func TestClaudeGuestIdentityAndPartialQuota(t *testing.T) { |
| 92 | now := time.Unix(1700000000, 0) |
| 93 | list := claudeAccountList{Accounts: []claudeAccount{{ID: "one"}, {ID: "two"}}} |
| 94 | first := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "work", Quota: &claudeQuota{ |
| 95 | FiveHour: &claudeWindow{UsedPercentage: 80, ResetsAt: now.Add(time.Hour).Unix()}, SevenDay: &claudeWindow{UsedPercentage: 100, ResetsAt: now.Add(48 * time.Hour).Unix()}, ObservedAt: now.Unix(), |
| 96 | }} |
| 97 | _ = list.observe("one", first, now) |
| 98 | _ = list.observe("two", first, now) |
| 99 | if list.Accounts[0].Status != "ready" || list.Accounts[1].Status != "duplicate" || list.Accounts[1].Quota != nil { |
| 100 | t.Fatalf("same signed-in subscription counted twice: %+v", list) |
| 101 | } |
| 102 | first.Quota = &claudeQuota{FiveHour: &claudeWindow{UsedPercentage: 32, ResetsAt: now.Add(3 * time.Hour).Unix()}, ObservedAt: now.Add(time.Hour).Unix()} |
| 103 | _ = list.observe("one", first, now.Add(time.Hour)) |
| 104 | |
| 105 | |
| 106 | first.Quota.SevenDay = &claudeWindow{UsedPercentage: 100, ResetsAt: now.Add(48 * time.Hour).Unix(), ObservedAt: now.Unix()} |
| 107 | _ = list.observe("one", first, now.Add(time.Hour)) |
| 108 | if list.Accounts[0].Quota.SevenDay.ObservedAt != now.Unix() { |
| 109 | t.Fatal("missing weekly window updated its timestamp") |
| 110 | } |
| 111 | if _, eligible := list.Accounts[0].headroom(now.Add(time.Hour)); eligible { |
| 112 | t.Fatal("stale exhausted weekly window became available") |
| 113 | } |
| 114 | if score, eligible := list.Accounts[0].headroom(now.Add(49 * time.Hour)); !eligible || score != -1 { |
| 115 | t.Fatal("reset became a fabricated live reading", score, eligible) |
| 116 | } |
| 117 | first.Email = "[email protected]" |
| 118 | _ = list.observe("one", first, now.Add(time.Hour)) |
| 119 | if list.Accounts[0].Status != "changed" || list.Accounts[0].Quota == nil || list.Accounts[0].Email != "[email protected]" { |
| 120 | t.Fatal("silent replacement of a bound identity", list.Accounts[0]) |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | func TestClaudeAllocationReadsGuestWithoutOpeningPanel(t *testing.T) { |
| 125 | s := testServer(t) |
| 126 | list := claudeAccountList{Accounts: []claudeAccount{ |
| 127 | {ID: strings.Repeat("a", 24), Label: "A", Enabled: true, Status: "ready", Email: "[email protected]"}, |
| 128 | {ID: strings.Repeat("b", 24), Label: "B", Enabled: true, Status: "ready", Email: "[email protected]"}, |
| 129 | {ID: strings.Repeat("c", 24), Label: "C", Enabled: false, Status: "ready"}, |
| 130 | }} |
| 131 | if err := s.saveClaudeAccounts(list); err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | now := time.Now() |
| 135 | var calls int |
| 136 | read := func(ctx context.Context, ids []string) (map[string]claudeGuestQuota, error) { |
| 137 | calls++ |
| 138 | if !sort.StringsAreSorted(ids) || len(ids) != 2 { |
| 139 | t.Fatalf("expected one batch of participating profiles: %v", ids) |
| 140 | } |
| 141 | q := claudeQuota{FiveHour: &claudeWindow{UsedPercentage: 100, ResetsAt: now.Add(time.Hour).Unix()}, ObservedAt: now.Unix()} |
| 142 | return map[string]claudeGuestQuota{ |
| 143 | ids[0]: {claudeQuota: q, Identity: claudeIdentityHash("[email protected]", "")}, |
| 144 | ids[1]: {claudeQuota: q, Identity: claudeIdentityHash("[email protected]", "")}, |
| 145 | }, nil |
| 146 | } |
| 147 | want := list.Accounts[1].ID |
| 148 | id, err := s.allocateClaudeAccount(list, "", read) |
| 149 | if err != nil || id.ID != want || calls != 1 { |
| 150 | t.Fatalf("did not react to A's new quota or accepted another identity's reading: %q %v", id, err) |
| 151 | } |
| 152 | id, err = s.allocateClaudeAccount(list, "", func(context.Context, []string) (map[string]claudeGuestQuota, error) { |
| 153 | return nil, errors.New("VM temporarily unavailable") |
| 154 | }) |
| 155 | if err != nil || id.ID != want { |
| 156 | t.Fatalf("guest failure erased confirmed exhaustion: %q %v", id, err) |
| 157 | } |
| 158 | saved, _ := s.loadClaudeAccounts() |
| 159 | if saved.Accounts[1].Quota != nil || saved.Accounts[0].Quota.FiveHour.UsedPercentage != 100 { |
| 160 | t.Fatal("new observations did not persist with their source identity") |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | func TestClaudeAccountRotationReservesActiveSessions(t *testing.T) { |
| 165 | list := claudeAccountList{Accounts: []claudeAccount{{ID: "one", Enabled: true, Status: "ready"}, {ID: "two", Enabled: true, Status: "ready"}}} |
| 166 | now := time.Now() |
| 167 | if id := pickClaudeAccount(list, map[string]int{"one": 1}, nil, "two", "", now); id != "two" { |
| 168 | t.Fatal("did not account for occupied terminal", id) |
| 169 | } |
| 170 | if id := pickClaudeAccount(list, nil, nil, "one", "", now); id != "two" { |
| 171 | t.Fatal("equal profiles did not rotate", id) |
| 172 | } |
| 173 | if id := pickClaudeAccount(list, nil, map[string]bool{"two": true}, "one", "", now); id != "one" { |
| 174 | t.Fatal("assigned profile currently signing in", id) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | func TestClaudeQuotaWireFormat(t *testing.T) { |
| 179 | var q claudeGuestQuota |
| 180 | if err := json.Unmarshal([]byte(`{"identity":"digest","five_hour":{"used_percentage":39,"resets_at":150},"observed_at":100}`), &q); err != nil || q.FiveHour == nil || q.FiveHour.UsedPercentage != 39 || q.Identity != "digest" { |
| 181 | t.Fatalf("guest/host envelope mismatch: %+v %v", q, err) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | func TestClaudeProjectAffinityYieldsToAvailabilityAndLoad(t *testing.T) { |
| 186 | s := testServer(t) |
| 187 | list := claudeAccountList{Accounts: []claudeAccount{ |
| 188 | {ID: strings.Repeat("a", 24), Enabled: true, Status: "ready"}, |
| 189 | {ID: strings.Repeat("b", 24), Enabled: true, Status: "ready"}, |
| 190 | }} |
| 191 | if err := s.saveClaudeAccounts(list); err != nil { |
| 192 | t.Fatal(err) |
| 193 | } |
| 194 | noReadings := func(context.Context, []string) (map[string]claudeGuestQuota, error) { return nil, nil } |
| 195 | a, b := list.Accounts[0].ID, list.Accounts[1].ID |
| 196 | s.noteClaudeSelection(a, "/project") |
| 197 | check := func(project, want string) { |
| 198 | t.Helper() |
| 199 | if id, err := s.allocateClaudeAccount(list, project, noReadings); err != nil || id.ID != want { |
| 200 | t.Fatalf("project %q selected %q, want %q (%v)", project, id, want, err) |
| 201 | } |
| 202 | } |
| 203 | check("/project", a) |
| 204 | check("/other", b) |
| 205 | if id := pickClaudeAccount(list, map[string]int{a: 1}, nil, a, a, time.Now()); id != b { |
| 206 | t.Fatal("affinity overrode a busier terminal", id) |
| 207 | } |
| 208 | list.Accounts[0].Enabled = false |
| 209 | if err := s.saveClaudeAccounts(list); err != nil { |
| 210 | t.Fatal(err) |
| 211 | } |
| 212 | check("/project", b) |
| 213 | list.Accounts[0].Enabled = true |
| 214 | if err := s.saveClaudeAccounts(list); err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | s.claudeAccounts.recent["/project"] = claudeProjectPick{id: a, at: time.Now().Add(-2 * claudeProjectAffinity)} |
| 218 | check("/project", b) |
| 219 | } |
| 220 | |
| 221 | func TestClaudeDraftCancellationRespectsAdmissionsAndBoundIdentities(t *testing.T) { |
| 222 | s := testServer(t) |
| 223 | draft := strings.Repeat("a", 24) |
| 224 | list := claudeAccountList{Accounts: []claudeAccount{{ID: draft, Label: "新账号", Status: "pending", Enabled: true}}} |
| 225 | if err := s.saveClaudeAccounts(list); err != nil { |
| 226 | t.Fatal(err) |
| 227 | } |
| 228 | cancel := func(want int) { |
| 229 | t.Helper() |
| 230 | w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"cancel","id":"`+draft+`"}`, true) |
| 231 | if w.Code != want { |
| 232 | t.Fatalf("cancel got %d, want %d: %s", w.Code, want, w.Body) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | s.op.Lock() |
| 237 | cancel(409) |
| 238 | s.op.Unlock() |
| 239 | s.terminals.sessions = map[string]*terminalSession{"login": {claudeAccountID: draft, kind: "claude-login"}} |
| 240 | cancel(409) |
| 241 | delete(s.terminals.sessions, "login") |
| 242 | s.claudeAccounts.mu.Lock() |
| 243 | poll := s.claudeAccounts.claim(draft) |
| 244 | s.claudeAccounts.mu.Unlock() |
| 245 | cancel(409) |
| 246 | s.claudeAccounts.finish(draft, poll, nil) |
| 247 | cancel(200) |
| 248 | cancel(200) |
| 249 | if id, err := s.selectClaudeAccount("", false, ""); err != nil || id.ID != "" { |
| 250 | t.Fatalf("cancelling the last draft did not restore existing behavior: %q %v", id, err) |
| 251 | } |
| 252 | list.Accounts[0].Email = "[email protected]" |
| 253 | list.Accounts[0].Status = "signed_out" |
| 254 | if err := s.saveClaudeAccounts(list); err != nil { |
| 255 | t.Fatal(err) |
| 256 | } |
| 257 | cancel(409) |
| 258 | kept, _ := s.loadClaudeAccounts() |
| 259 | if kept.find(draft) == nil { |
| 260 | t.Fatal("cancellation removed a previously bound identity") |
| 261 | } |
| 262 | } |