-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathapp_quota.go
More file actions
691 lines (655 loc) · 22.7 KB
/
Copy pathapp_quota.go
File metadata and controls
691 lines (655 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
package main
import (
"context"
"fmt"
"log"
"strings"
"sync"
"time"
"windsurf-tools-wails/backend/models"
"windsurf-tools-wails/backend/services"
"windsurf-tools-wails/backend/utils"
)
// ═══════════════════════════════════════
// 自动刷新 Token / JWT + 额度监控
// ═══════════════════════════════════════
func (a *App) startAutoRefresh() {
ctx, cancel := context.WithCancel(a.ctx)
a.mu.Lock()
a.cancelAutoRefresh = cancel
a.mu.Unlock()
go func() {
ticker := time.NewTicker(10 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
a.refreshAllTokens()
}
}
}()
}
func (a *App) startAutoQuotaRefresh() {
ctx, cancel := context.WithCancel(a.ctx)
a.mu.Lock()
a.cancelAutoQuotaRefresh = cancel
a.mu.Unlock()
log.Printf("[额度同步] 定时同步已启动 (间隔=5min)")
utils.DLog("[额度同步] 定时同步已启动 (间隔=5min)")
go func() {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
a.refreshDueQuotas()
for {
select {
case <-ctx.Done():
utils.DLog("[额度同步] 定时同步已停止")
return
case <-ticker.C:
a.refreshDueQuotas()
}
}
}()
}
func clampQuotaHotPollSeconds(sec int) int {
if sec < 5 {
return 5
}
if sec > 60 {
return 60
}
return sec
}
func clampRefreshConcurrentLimit(limit int) int {
if limit < 1 {
return 1
}
if limit > 8 {
return 8
}
return limit
}
func refreshBatchPause(limit int) time.Duration {
switch {
case limit >= 6:
return 120 * time.Millisecond
case limit >= 3:
return 180 * time.Millisecond
default:
return 260 * time.Millisecond
}
}
type accountRefreshOutcome struct {
label string
status string
account models.Account
updated bool
}
func runAccountRefreshBatches(accounts []models.Account, concurrency int, pause time.Duration, worker func(models.Account) accountRefreshOutcome) []accountRefreshOutcome {
return runAccountRefreshBatchesWithProgress(accounts, concurrency, pause, worker, nil)
}
// runAccountRefreshBatchesWithProgress 与 runAccountRefreshBatches 一致,但额外接受
// onItem 回调 —— 在每个 worker 完成(且 mutex 内安全可读)时调用一次,用于
// F1: TaskRegistry 实时推进度。onItem 必须线程安全(worker 是并发跑的)。
func runAccountRefreshBatchesWithProgress(
accounts []models.Account,
concurrency int,
pause time.Duration,
worker func(models.Account) accountRefreshOutcome,
onItem func(outcome accountRefreshOutcome),
) []accountRefreshOutcome {
if len(accounts) == 0 {
return nil
}
limit := clampRefreshConcurrentLimit(concurrency)
outcomes := make([]accountRefreshOutcome, 0, len(accounts))
for start := 0; start < len(accounts); start += limit {
end := start + limit
if end > len(accounts) {
end = len(accounts)
}
batch := accounts[start:end]
results := make([]accountRefreshOutcome, len(batch))
var wg sync.WaitGroup
for i, acc := range batch {
i := i
acc := acc
wg.Add(1)
go func() {
defer wg.Done()
r := worker(acc)
results[i] = r
if onItem != nil {
onItem(r)
}
}()
}
wg.Wait()
outcomes = append(outcomes, results...)
if end < len(accounts) && pause > 0 {
time.Sleep(pause)
}
}
return outcomes
}
func (a *App) stopQuotaHotPoll() {
a.mu.Lock()
cancel := a.cancelQuotaHotPoll
a.cancelQuotaHotPoll = nil
a.mu.Unlock()
if cancel != nil {
cancel()
}
}
// restartQuotaHotPollIfNeeded 在「定期同步额度 + 用尽自动切号」同时开启时,对当前 windsurf 会话高频拉额度以便尽快切号。
func (a *App) restartQuotaHotPollIfNeeded() {
a.stopQuotaHotPoll()
settings := a.store.GetSettings()
if !settings.AutoRefreshQuotas || !settings.AutoSwitchOnQuotaExhausted {
return
}
// F7-REMOVAL: 下面 if SmartFriendEnabled 分支删除
if settings.SmartFriendEnabled {
return
}
ctx, cancel := context.WithCancel(a.ctx)
a.mu.Lock()
a.cancelQuotaHotPoll = cancel
a.mu.Unlock()
go a.quotaHotPollLoop(ctx)
}
func (a *App) quotaHotPollLoop(ctx context.Context) {
for {
a.pollCurrentSessionQuotaAndMaybeSwitch()
delay := a.nextQuotaHotPollDelay()
t := time.NewTimer(delay)
select {
case <-ctx.Done():
t.Stop()
return
case <-t.C:
}
}
}
func (a *App) nextQuotaHotPollDelay() time.Duration {
settings := a.store.GetSettings()
base := time.Duration(clampQuotaHotPollSeconds(settings.QuotaHotPollSeconds)) * time.Second
curID := a.findCurrentMonitoredAccountID()
if curID == "" {
return base
}
cur, err := a.store.GetAccount(curID)
if err != nil {
return base
}
delay := utils.NextQuotaResetWakeDelayForExhausted(cur, time.Now(), base)
if delay < base {
utils.DLog("[热轮询/reset] wake-schedule account=%s base=%s next=%s reason=reset-window daily={%s} weekly={%s}",
labelAccountResult(cur), base, delay, describeQuotaResetField(cur.DailyRemaining, cur.DailyResetAt, cur.LastQuotaUpdate, time.Now()), describeQuotaResetField(cur.WeeklyRemaining, cur.WeeklyResetAt, cur.LastQuotaUpdate, time.Now()))
}
return delay
}
func (a *App) pollCurrentSessionQuotaAndMaybeSwitch() {
settings := a.store.GetSettings()
if !settings.AutoRefreshQuotas || !settings.AutoSwitchOnQuotaExhausted {
utils.DLog("[热轮询] 跳过: AutoRefreshQuotas=%v AutoSwitch=%v", settings.AutoRefreshQuotas, settings.AutoSwitchOnQuotaExhausted)
return
}
// F7-REMOVAL: 下面 if SmartFriendEnabled 分支删除
if settings.SmartFriendEnabled {
utils.DLog("[热轮询] 跳过: SmartFriend 模式已开启,不检测额度")
return
}
// Pin 优先:手动锁定时连热轮询额度刷新都做(让用户看到新数据),但
// 跳过最后的自动切号步骤。pin 中拉额度仍有意义;切号必须用户手动。
pinned := settings.ManualPinEnabled
curID := a.findCurrentMonitoredAccountID()
if curID == "" {
utils.DLog("[热轮询] 跳过: 无法匹配当前账号 (号池=%d)", a.store.AccountCount())
return
}
cur, err := a.store.GetAccount(curID)
if err != nil {
utils.DLog("[热轮询] 跳过: GetAccount(%s) 失败: %v", curID, err)
return
}
now := time.Now()
forceRefreshAfterReset := utils.QuotaRefreshDueAfterOfficialReset(cur, now)
a.logHotPollResetSnapshot("precheck", cur, forceRefreshAfterReset, now)
a.lastQuotaHotSwitchMu.Lock()
if t := a.lastQuotaHotSwitch; !t.IsZero() && time.Since(t) < 12*time.Second && !forceRefreshAfterReset {
a.lastQuotaHotSwitchMu.Unlock()
utils.DLog("[热轮询] 跳过: 距上次切号仅 %.1fs (<12s 冷却)", time.Since(t).Seconds())
return
}
a.lastQuotaHotSwitchMu.Unlock()
if forceRefreshAfterReset {
utils.DLog("[热轮询/reset] due-now account=%s action=force-refresh reason=official-reset-reached daily={%s} weekly={%s}",
labelAccountResult(cur), describeQuotaResetField(cur.DailyRemaining, cur.DailyResetAt, cur.LastQuotaUpdate, now), describeQuotaResetField(cur.WeeklyRemaining, cur.WeeklyResetAt, cur.LastQuotaUpdate, now))
}
if cur.WindsurfAPIKey == "" && strings.TrimSpace(cur.Token) == "" &&
cur.RefreshToken == "" && (cur.Email == "" || cur.Password == "") {
utils.DLog("[热轮询] 跳过: %s 无任何可用凭证", cur.Email)
return
}
utils.DLog("[热轮询] 开始查额度: %s (id=%s plan=%s)", cur.Email, curID[:min(8, len(curID))], cur.PlanName)
copyAcc := cur
a.syncAccountCredentials(©Acc)
// 热轮询仅拉额度,避免 RegisterUser / GetAccountInfo 等拖慢后台与重复请求
quotaOK := a.enrichAccountQuotaOnly(©Acc)
utils.DLog("[热轮询] enrichQuota 结果: ok=%v daily=%s weekly=%s total=%d used=%d", quotaOK, copyAcc.DailyRemaining, copyAcc.WeeklyRemaining, copyAcc.TotalQuota, copyAcc.UsedQuota)
if quotaOK {
copyAcc.LastQuotaUpdate = time.Now().Format(time.RFC3339)
}
a.logHotPollResetSnapshot("post-refresh", copyAcc, false, time.Now())
if err := a.store.UpdateAccount(copyAcc); err != nil {
utils.DLog("[热轮询] UpdateAccount 失败: %v", err)
return
}
a.syncMitmPoolKeys()
if !utils.AccountQuotaExhausted(©Acc) {
utils.DLog("[热轮询] %s 额度正常 (daily=%s weekly=%s)", copyAcc.Email, copyAcc.DailyRemaining, copyAcc.WeeklyRemaining)
utils.DLog("[热轮询/reset] decision account=%s result=keep-current daily={%s} weekly={%s}",
labelAccountResult(copyAcc), describeQuotaResetField(copyAcc.DailyRemaining, copyAcc.DailyResetAt, copyAcc.LastQuotaUpdate, time.Now()), describeQuotaResetField(copyAcc.WeeklyRemaining, copyAcc.WeeklyResetAt, copyAcc.LastQuotaUpdate, time.Now()))
return
}
utils.DLog("[热轮询] ★ %s 额度用尽! (daily=%s weekly=%s plan=%s) → 触发切号", copyAcc.Email, copyAcc.DailyRemaining, copyAcc.WeeklyRemaining, copyAcc.PlanName)
utils.DLog("[热轮询/reset] decision account=%s result=exhausted-switch daily={%s} weekly={%s}",
labelAccountResult(copyAcc), describeQuotaResetField(copyAcc.DailyRemaining, copyAcc.DailyResetAt, copyAcc.LastQuotaUpdate, time.Now()), describeQuotaResetField(copyAcc.WeeklyRemaining, copyAcc.WeeklyResetAt, copyAcc.LastQuotaUpdate, time.Now()))
if pinned {
utils.DLog("[热轮询] ManualPin 生效 (pin=%s),已刷额度但跳过切号", settings.ManualPinAccountID[:min(8, len(settings.ManualPinAccountID))])
return
}
if next, err := a.rotateMitmToNextAvailable(curID, settings.AutoSwitchPlanFilter); err == nil {
utils.DLog("[热轮询] MITM轮换成功 → %s", next.Email)
a.lastQuotaHotSwitchMu.Lock()
a.lastQuotaHotSwitch = time.Now()
a.lastQuotaHotSwitchMu.Unlock()
} else {
utils.DLog("[热轮询] MITM轮换失败: %v", err)
}
}
func describeQuotaResetField(remaining, resetAt, lastQuotaUpdate string, now time.Time) string {
parts := make([]string, 0, 4)
if strings.TrimSpace(remaining) == "" {
parts = append(parts, "remaining=<empty>")
} else {
parts = append(parts, "remaining="+strings.TrimSpace(remaining))
}
resetAt = strings.TrimSpace(resetAt)
if resetAt == "" {
parts = append(parts, "reset=<none>")
} else if resetTime, err := time.Parse(time.RFC3339, resetAt); err == nil {
parts = append(parts, "reset="+resetAt)
delta := resetTime.Sub(now)
switch {
case delta > 0:
parts = append(parts, fmt.Sprintf("reset_in=%s", delta.Round(time.Second)))
case delta < 0:
parts = append(parts, fmt.Sprintf("reset_ago=%s", (-delta).Round(time.Second)))
default:
parts = append(parts, "reset_now=true")
}
} else {
parts = append(parts, "reset="+resetAt)
parts = append(parts, "reset_parse=invalid")
}
if strings.TrimSpace(lastQuotaUpdate) == "" {
parts = append(parts, "last=<none>")
} else {
parts = append(parts, "last="+strings.TrimSpace(lastQuotaUpdate))
}
return strings.Join(parts, " ")
}
func (a *App) logHotPollResetSnapshot(stage string, acc models.Account, force bool, now time.Time) {
utils.DLog("[热轮询/reset] %s account=%s plan=%s force=%v daily={%s} weekly={%s}",
stage, labelAccountResult(acc), acc.PlanName, force, describeQuotaResetField(acc.DailyRemaining, acc.DailyResetAt, acc.LastQuotaUpdate, now), describeQuotaResetField(acc.WeeklyRemaining, acc.WeeklyResetAt, acc.LastQuotaUpdate, now))
}
func (a *App) refreshDueQuotas() {
a.quotaRefreshRunMu.Lock()
defer a.quotaRefreshRunMu.Unlock()
var switchAfterUnlock struct {
currentID string
planFilter string
}
updatedPool := false
settings := a.store.GetSettings()
if !settings.AutoRefreshQuotas {
utils.DLog("[额度同步] AutoRefreshQuotas=false,跳过")
return
}
policy := strings.TrimSpace(settings.QuotaRefreshPolicy)
if policy == "" {
policy = utils.QuotaPolicyHybrid
}
now := time.Now()
customMins := settings.QuotaCustomIntervalMinutes
accounts := a.store.GetAllAccounts()
svc := a.windsurfSvc
if svc == nil {
utils.DLog("[额度同步] windsurfSvc=nil,跳过")
return
}
dueAccounts := make([]models.Account, 0, len(accounts))
for _, acc := range accounts {
if !utils.QuotaRefreshDue(acc.LastQuotaUpdate, policy, customMins, now) &&
!utils.QuotaRefreshDueAfterOfficialReset(acc, now) {
continue
}
if acc.WindsurfAPIKey == "" && acc.Token == "" && acc.RefreshToken == "" && (acc.Email == "" || acc.Password == "") {
continue
}
dueAccounts = append(dueAccounts, acc)
}
utils.DLog("[额度同步] policy=%s 总账号=%d due=%d", policy, len(accounts), len(dueAccounts))
pause := refreshBatchPause(settings.ConcurrentLimit)
outcomes := runAccountRefreshBatches(dueAccounts, settings.ConcurrentLimit, pause, func(acc models.Account) accountRefreshOutcome {
copyAcc := acc
a.syncAccountCredentialsWithService(svc, ©Acc)
gotData := a.enrichAccountInfoWithService(svc, ©Acc)
if gotData {
copyAcc.LastQuotaUpdate = now.Format(time.RFC3339)
}
return accountRefreshOutcome{
label: labelAccountResult(acc),
account: copyAcc,
updated: true,
}
})
var updatedCount int
for _, outcome := range outcomes {
if !outcome.updated {
continue
}
if err := a.store.UpdateAccount(outcome.account); err == nil {
updatedPool = true
updatedCount++
}
}
if len(dueAccounts) > 0 {
utils.DLog("[额度同步] 完成: 更新=%d/%d updatedPool=%v", updatedCount, len(dueAccounts), updatedPool)
}
// Pin 优先:手动锁定时跳过自动切(额度同步本身已完成不影响)
// F7-REMOVAL: 下两行注释 + case settings.SmartFriendEnabled 分支一并删除
// SmartFriend(F7) 优先:服务端按 SMART_FRIEND 计费、绕过日/周限额,
// 「显示耗尽」实际仍可用,定期同步后不应触发自动切号。
switch {
case settings.SmartFriendEnabled:
utils.DLog("[额度同步] SmartFriend 生效,跳过定期同步后的自动切号")
case settings.ManualPinEnabled && settings.AutoSwitchOnQuotaExhausted:
utils.DLog("[额度同步] ManualPin 生效,跳过定期同步后的自动切号")
case settings.AutoSwitchOnQuotaExhausted:
curID := a.findCurrentMonitoredAccountID()
if curID != "" {
if cur, err := a.store.GetAccount(curID); err == nil && utils.AccountQuotaExhausted(&cur) {
switchAfterUnlock.currentID = curID
switchAfterUnlock.planFilter = settings.AutoSwitchPlanFilter
}
}
}
if updatedPool {
a.syncMitmPoolKeys()
}
if switchAfterUnlock.currentID != "" {
_, _ = a.rotateMitmToNextAvailable(switchAfterUnlock.currentID, switchAfterUnlock.planFilter)
}
}
func findAccountIDForMITMAPIKey(accounts []models.Account, apiKey string) string {
want := strings.TrimSpace(apiKey)
if want == "" {
return ""
}
for _, acc := range accounts {
if strings.TrimSpace(acc.WindsurfAPIKey) == want {
return acc.ID
}
}
return ""
}
func (a *App) findCurrentMonitoredAccountID() string {
accounts := a.store.GetAllAccounts()
activeMITMKey := ""
if a.mitmProxy != nil {
activeMITMKey = a.mitmProxy.CurrentAPIKey()
}
id := findAccountIDForMITMAPIKey(accounts, activeMITMKey)
if id != "" {
utils.DLog("[匹配] findCurrentMonitored → id=%s (mitmKey=%v)", id[:min(8, len(id))], activeMITMKey != "")
} else {
utils.DLog("[匹配] findCurrentMonitored → 未匹配 (mitmKey=%v accounts=%d)", activeMITMKey != "", len(accounts))
}
return id
}
func (a *App) syncAccountCredentials(acc *models.Account) {
a.syncAccountCredentialsWithService(a.windsurfSvc, acc)
}
func (a *App) syncAccountCredentialsWithService(svc *services.WindsurfService, acc *models.Account) {
if svc == nil || acc == nil {
return
}
label := acc.Email
if label == "" {
label = acc.ID
}
utils.DLog("[凭证] %s 开始同步 (hasKey=%v hasRefresh=%v hasPass=%v)", label, acc.WindsurfAPIKey != "", acc.RefreshToken != "", acc.Password != "")
if acc.WindsurfAPIKey != "" {
var lastErr error
for attempt := 0; attempt < 2; attempt++ {
jwt, err := svc.GetJWTByAPIKey(acc.WindsurfAPIKey)
if err == nil && jwt != "" {
acc.Token = jwt
utils.DLog("[凭证] %s JWT获取成功(APIKey) tokenLen=%d", label, len(jwt))
return
}
lastErr = err
if attempt == 0 {
time.Sleep(500 * time.Millisecond)
}
}
utils.DLog("[凭证] %s JWT获取失败(APIKey): %v", label, lastErr)
log.Printf("[切号] %s JWT获取失败(APIKey): %v", label, lastErr)
acc.Token = ""
acc.TokenExpiresAt = ""
applyAccessErrorStatus(acc, lastErr)
return
}
if acc.RefreshToken != "" {
resp, err := svc.RefreshToken(acc.RefreshToken)
if err == nil {
acc.Token = resp.IDToken
acc.RefreshToken = resp.RefreshToken
acc.TokenExpiresAt = time.Now().Add(1 * time.Hour).Format(time.RFC3339)
maybeBackfillAuth1SessionKey(svc, acc, label)
utils.DLog("[凭证] %s RefreshToken成功 tokenLen=%d", label, len(resp.IDToken))
return
}
utils.DLog("[凭证] %s RefreshToken刷新失败: %v", label, err)
log.Printf("[切号] %s RefreshToken刷新失败: %v", label, err)
}
if acc.Email != "" && acc.Password != "" {
resp, err := svc.LoginWithEmail(acc.Email, acc.Password)
if err == nil {
acc.Token = resp.IDToken
acc.RefreshToken = resp.RefreshToken
acc.TokenExpiresAt = time.Now().Add(1 * time.Hour).Format(time.RFC3339)
maybeBackfillAuth1SessionKey(svc, acc, label)
utils.DLog("[凭证] %s 邮箱登录成功 tokenLen=%d", label, len(resp.IDToken))
return
}
utils.DLog("[凭证] %s 邮箱密码登录失败: %v", label, err)
log.Printf("[切号] %s 邮箱密码登录失败: %v", label, err)
}
utils.DLog("[凭证] %s 所有凭证同步路径均失败", label)
}
func (a *App) RefreshAllTokens() map[string]string { return a.refreshAllTokens() }
func (a *App) refreshAllTokens() map[string]string {
a.tokenRefreshRunMu.Lock()
defer a.tokenRefreshRunMu.Unlock()
results := make(map[string]string)
accounts := a.store.GetAllAccounts()
settings := a.store.GetSettings()
svc := a.windsurfSvc
if svc == nil {
for _, acc := range accounts {
results[labelAccountResult(acc)] = "刷新服务未初始化"
}
return results
}
// F1: 注册批量任务
var taskID string
if a.tasks != nil && len(accounts) > 0 {
taskID = a.tasks.Start("refresh_tokens", fmt.Sprintf("全量刷新 Token (%d)", len(accounts)), len(accounts))
defer a.tasks.Finish(taskID)
}
pause := refreshBatchPause(settings.ConcurrentLimit)
updatedPool := false
outcomes := runAccountRefreshBatchesWithProgress(accounts, settings.ConcurrentLimit, pause, func(acc models.Account) accountRefreshOutcome {
label := labelAccountResult(acc)
if acc.WindsurfAPIKey != "" {
jwt, err := svc.GetJWTByAPIKey(acc.WindsurfAPIKey)
if err != nil {
before := acc
applyAccessErrorStatus(&acc, err)
return accountRefreshOutcome{
label: label,
status: "JWT刷新失败: " + err.Error(),
account: acc,
updated: acc != before,
}
}
acc.Token = jwt
if a.enrichAccountInfoWithService(svc, &acc) {
acc.LastQuotaUpdate = time.Now().Format(time.RFC3339)
}
return accountRefreshOutcome{label: label, status: "JWT刷新成功", account: acc, updated: true}
}
if acc.RefreshToken != "" {
resp, err := svc.RefreshToken(acc.RefreshToken)
if err != nil {
return accountRefreshOutcome{label: label, status: "Token刷新失败: " + err.Error()}
}
acc.Token = resp.IDToken
acc.RefreshToken = resp.RefreshToken
acc.TokenExpiresAt = time.Now().Add(1 * time.Hour).Format(time.RFC3339)
a.enrichAccountInfoWithService(svc, &acc)
return accountRefreshOutcome{label: label, status: "Token刷新成功", account: acc, updated: true}
}
return accountRefreshOutcome{label: label, status: "无可用刷新凭证"}
}, func(o accountRefreshOutcome) {
if a.tasks == nil || taskID == "" {
return
}
ok := strings.Contains(o.status, "成功")
a.tasks.Add(taskID, o.label, ok, o.status)
})
for _, outcome := range outcomes {
results[outcome.label] = outcome.status
if !outcome.updated {
continue
}
if err := a.store.UpdateAccount(outcome.account); err != nil {
results[outcome.label] = "保存失败: " + err.Error()
continue
}
updatedPool = true
}
if updatedPool {
a.syncMitmPoolKeys()
}
return results
}
// RefreshAccountQuota 手动同步单账号额度(同步凭证 + 拉取 profile,不校验策略间隔)
func (a *App) RefreshAccountQuota(id string) error {
a.quotaRefreshRunMu.Lock()
defer a.quotaRefreshRunMu.Unlock()
acc, err := a.store.GetAccount(id)
if err != nil {
return err
}
if acc.WindsurfAPIKey == "" && acc.Token == "" && acc.RefreshToken == "" && (acc.Email == "" || acc.Password == "") {
return fmt.Errorf("该账号没有可用于拉取额度的凭证")
}
copyAcc := acc
svc := a.windsurfSvc
if svc == nil {
return fmt.Errorf("刷新服务未初始化")
}
a.syncAccountCredentialsWithService(svc, ©Acc)
if a.enrichAccountInfoWithService(svc, ©Acc) {
copyAcc.LastQuotaUpdate = time.Now().Format(time.RFC3339)
}
if err := a.store.UpdateAccount(copyAcc); err != nil {
return err
}
a.syncMitmPoolKeys()
return nil
}
// RefreshAllQuotas 手动同步全部账号额度(忽略 auto_refresh_quotas 与策略)
func (a *App) RefreshAllQuotas() map[string]string {
a.quotaRefreshRunMu.Lock()
defer a.quotaRefreshRunMu.Unlock()
results := make(map[string]string)
now := time.Now().Format(time.RFC3339)
settings := a.store.GetSettings()
accounts := a.store.GetAllAccounts()
svc := a.windsurfSvc
if svc == nil {
for _, acc := range accounts {
results[labelAccountResult(acc)] = "刷新服务未初始化"
}
return results
}
// F1: 注册批量任务
var taskID string
if a.tasks != nil && len(accounts) > 0 {
taskID = a.tasks.Start("refresh_quotas", fmt.Sprintf("全量同步额度 (%d)", len(accounts)), len(accounts))
defer a.tasks.Finish(taskID)
}
pause := refreshBatchPause(settings.ConcurrentLimit)
updatedPool := false
outcomes := runAccountRefreshBatchesWithProgress(accounts, settings.ConcurrentLimit, pause, func(acc models.Account) accountRefreshOutcome {
label := labelAccountResult(acc)
if acc.WindsurfAPIKey == "" && acc.Token == "" && acc.RefreshToken == "" && (acc.Email == "" || acc.Password == "") {
return accountRefreshOutcome{label: label, status: "跳过:无可用凭证"}
}
copyAcc := acc
a.syncAccountCredentialsWithService(svc, ©Acc)
gotData := a.enrichAccountInfoWithService(svc, ©Acc)
status := "额度已同步"
if gotData {
copyAcc.LastQuotaUpdate = now
} else {
status = "额度同步失败(API返回为空)"
}
return accountRefreshOutcome{label: label, status: status, account: copyAcc, updated: true}
}, func(o accountRefreshOutcome) {
if a.tasks == nil || taskID == "" {
return
}
ok := strings.Contains(o.status, "已同步")
a.tasks.Add(taskID, o.label, ok, o.status)
})
for _, outcome := range outcomes {
results[outcome.label] = outcome.status
if !outcome.updated {
continue
}
if err := a.store.UpdateAccount(outcome.account); err != nil {
results[outcome.label] = "失败: " + err.Error()
continue
}
updatedPool = true
}
if updatedPool {
a.syncMitmPoolKeys()
}
return results
}
func labelAccountResult(acc models.Account) string {
if acc.Email != "" {
return acc.Email
}
return acc.ID
}