From 8f943c8565df90955b58be6eddf55630508ce115 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Tue, 24 Nov 2026 16:32:36 +0800 Subject: [PATCH] feat(checkin): sync upstream status and schedule from provider windows Add provider check-in status reads, persist source and sync time, derive auto schedule from the upstream window, and run manual batches with bounded concurrency. --- README.md | 2 +- README_EN.md | 2 +- .../unreleased/upstream-checkin-status.md | 19 ++ internal/accounts/checkin.go | 38 ++- internal/accounts/store.go | 1 + internal/accounts/types.go | 39 ++- internal/control/s06_control_test.go | 3 + internal/providers/checkin.go | 59 +++- internal/providers/checkin_window.go | 56 ++++ internal/providers/checkin_window_test.go | 59 ++++ internal/providers/codearts/checkin.go | 267 +++++++++++++++--- internal/providers/codearts/client.go | 19 +- internal/providers/codearts/codearts_test.go | 185 ++++++++++++ internal/providers/codearts/doc.go | 7 +- internal/providers/doubaowork/adapter.go | 17 +- internal/providers/doubaowork/checkin.go | 36 ++- internal/providers/interfaces.go | 21 +- internal/providers/minimaxcode/checkin.go | 51 ++++ internal/providers/minimaxcode/client.go | 19 +- internal/providers/qoder/adapter.go | 13 +- internal/providers/qoder/checkin.go | 184 +++++++++--- .../providers/qoder/checkin_inprocess_test.go | 90 ++++++ internal/providers/qwenwork/checkin.go | 55 +++- internal/providers/qwenwork/client.go | 17 +- internal/providers/registry.go | 3 +- internal/providers/registry_test.go | 21 +- internal/providers/trae/checkin.go | 47 ++- internal/providers/trae/checkin_test.go | 43 +++ internal/providers/trae/client.go | 21 +- internal/providers/workbuddy/checkin.go | 122 ++++++++ .../workbuddy/checkin_status_test.go | 166 +++++++++++ internal/runtime/checkin_integration_test.go | 40 +++ internal/runtime/checkin_status_test.go | 185 ++++++++++++ internal/runtime/maintenance_test.go | 25 ++ internal/runtime/manager.go | 29 +- internal/runtime/manager_maintenance.go | 265 +++++++++++++++-- internal/store/backup_test.go | 1 + internal/store/checkin_test.go | 4 +- internal/store/migrations.go | 4 + internal/store/store.go | 72 ++++- internal/store/store_test.go | 4 +- 41 files changed, 2102 insertions(+), 209 deletions(-) create mode 100644 changelog/unreleased/upstream-checkin-status.md create mode 100644 internal/providers/checkin_window.go create mode 100644 internal/providers/checkin_window_test.go create mode 100644 internal/providers/workbuddy/checkin_status_test.go create mode 100644 internal/runtime/checkin_status_test.go diff --git a/README.md b/README.md index 5c9786b1..ec95f052 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Qoder 国内版、WorkBuddy、Trae 已实现,真账号验收未完成。Kimi C CLI2API 控制台 Accounts 页:每个账号显示登录方式、就绪状态与额度,右侧 Access 面板提供 Base URL 与快速验证

-就绪状态和额度在账号卡片上。Access 页可以复制 Base URL,并做一次快速验证。哪些供应商能签到由各供应商自己声明,目前是 WorkBuddy、QwenWork、Qoder、Trae、MiniMax Code、码道和 Doubao Work,在卡片上手动签到。自动签到按账号单独开启、默认关闭,时间在「系统 → 自动签到」里按供应商设默认值。真实账号签到验收仍待完成。 +就绪状态和额度在账号卡片上。Access 页可以复制 Base URL,并做一次快速验证。哪些供应商能签到由各供应商自己声明,目前是 WorkBuddy 国内版、QwenWork、Qoder、Trae、MiniMax Code、码道和 Doubao Work,在卡片上手动签到。自动签到按账号单独开启、默认关闭,时间在「系统 → 自动签到」里按供应商设默认值。真实账号签到验收仍待完成。 ## 最早到期优先 diff --git a/README_EN.md b/README_EN.md index e82ff619..37137173 100644 --- a/README_EN.md +++ b/README_EN.md @@ -77,7 +77,7 @@ Qoder CN, WorkBuddy, and Trae are implemented; live-account acceptance is still CLI2API console Accounts page: each account shows its login method, ready state, and quota, with an Access panel offering the Base URL and a quick check

-Readiness and quota sit on the account card. Access copies the Base URL and runs a quick check. Check-in is declared per provider; today that is WorkBuddy, QwenWork, Qoder, Trae, MiniMax Code, CodeArts, and Doubao Work, each with a manual check-in on the card. Automatic check-in is enabled per account and off by default, with the default time per provider under System → Automatic check-in. Live-account check-in acceptance is still pending. +Readiness and quota sit on the account card. Access copies the Base URL and runs a quick check. Check-in is declared per provider; today that is WorkBuddy CN, QwenWork, Qoder, Trae, MiniMax Code, CodeArts, and Doubao Work, each with a manual check-in on the card. Automatic check-in is enabled per account and off by default, with the default time per provider under System → Automatic check-in. Live-account check-in acceptance is still pending. ## Earliest expiry first diff --git a/changelog/unreleased/upstream-checkin-status.md b/changelog/unreleased/upstream-checkin-status.md new file mode 100644 index 00000000..5c085103 --- /dev/null +++ b/changelog/unreleased/upstream-checkin-status.md @@ -0,0 +1,19 @@ +### English + +- Check-in status is now read from the provider instead of trusting the last local attempt. The account API returns upstream `already`, `pending`, `skipped`, or `unknown`, with the last sync time. +- One-click check-in now runs up to four accounts in parallel instead of waiting through the scheduled check-in gap, so a full account set no longer stalls for tens of seconds. +- WorkBuddy queries `/v2/billing/meter/checkin-activity-status` before claiming. Inactive campaigns and same-day repeats are reported as `skipped`/`already` without a duplicate claim. The Global edition no longer advertises or attempts daily check-in because the official desktop disables it. +- Scheduled check-in is automatic by default: the upstream daily window start plus one hour (Qoder 10:00 → 11:00, other providers 00:00 → 01:00). Manual provider times still override auto mode. +- Check-in scheduling uses the provider server clock (`Asia/Shanghai`), not the operator PC's local timezone. +- A campaign status that carries no per-day flag (CodeArts) is treated as provisional until 02:00 Asia/Shanghai; an "already claimed" replay during the first two hours of the day is not recorded as today's success, and the scheduler retries at 02:05, 12:05, and 21:00. +- CodeArts reports `already` only for the `USER_LOGIN` daily campaign, not for a used-up new-user or student reward, and posts the IDE's confirmation step when the claim returns a benefit id. + +### 中文 + +- 签到状态改为读取上游真实状态,不再只信任本地上一次执行结果。账号接口返回上游的已签到、未签到、未开放或状态未知,并标注最近同步时间。 +- 一键签到改为最多四个账号并行执行,不再逐个等待定时签到间隔,整批账号不会再卡几十秒。 +- WorkBuddy 在领取前先查询 `/v2/billing/meter/checkin-activity-status`。活动未开启和今日已签分别返回 `skipped` / `already`,不会重复领取。由于官方国际版桌面端关闭了签到,国际版不再声明或尝试每日签到。 +- 自动签到时间默认改为“上游每日窗口开始 + 1 小时”(Qoder 10:00 → 11:00,其他供应商 00:00 → 01:00)。供应商设置切换为手动时仍按手动时间执行。 +- 签到排期按供应商服务器时钟(`Asia/Shanghai`)计算,不再跟随电脑本地时区。 +- 不带“当天”字段的活动状态(CodeArts)在服务器时间 02:00 前仍视为待确认;前两小时的“已领取”回放不会被记成今天的成功,调度会在 02:05、12:05、21:00 重试。 +- CodeArts 只有 `USER_LOGIN` 每日活动才显示“已签到”,不会再把已用完的新用户/学生奖励当成今天已签;领取返回 benefit id 时补发 IDE 的确认请求。 diff --git a/internal/accounts/checkin.go b/internal/accounts/checkin.go index a9d393e7..692dea0d 100644 --- a/internal/accounts/checkin.go +++ b/internal/accounts/checkin.go @@ -49,7 +49,43 @@ func ResolveCheckinTime(ctx context.Context, store CheckinSettingsReader, accoun if account.CheckinTime != "" { return NormalizeCheckinTime(account.CheckinTime) } - return CheckinTimeDefault(ctx, store, account.Provider) + if account.CheckinAutoTime != "" { + return NormalizeCheckinTime(account.CheckinAutoTime) + } + // Before the first upstream status sync, keep the legacy provider default + // as a fallback. The first sync writes CheckinAutoTime and takes over. + fallback, err := CheckinTimeDefault(ctx, store, account.Provider) + if err != nil { + return "", err + } + return fallback, nil +} + +// EarliestCheckinClock is the provider's fallback daily window start when the +// upstream status response does not carry one. Qoder's activity refreshes at +// 10:00 Asia/Shanghai; the other currently supported check-in providers roll +// over at local midnight. +func EarliestCheckinClock(provider string) string { + if provider == "qoder" { + return "10:00" + } + return "00:00" +} + +// AutoCheckinTimeFromEarliest delays the upstream window by one hour so the +// scheduler never races the reset. An invalid or empty clock returns empty. +func AutoCheckinTimeFromEarliest(earliest string) string { + parsed, err := time.Parse("15:04", strings.TrimSpace(earliest)) + if err != nil { + return "" + } + return parsed.Add(time.Hour).Format("15:04") +} + +// DefaultCheckinAutoTime is the provider fallback window + 1 hour, used before +// the first upstream sync has produced an account-specific value. +func DefaultCheckinAutoTime(provider string) string { + return AutoCheckinTimeFromEarliest(EarliestCheckinClock(provider)) } func ValidateCheckinSettings(providerID, regionID string, enabled bool, override string) error { diff --git a/internal/accounts/store.go b/internal/accounts/store.go index a5b19d2e..78aeffd8 100644 --- a/internal/accounts/store.go +++ b/internal/accounts/store.go @@ -51,6 +51,7 @@ type AccountStore interface { ObserveHealth(ctx context.Context, id, remoteUID, lastError, lastKind string) error SaveQuota(ctx context.Context, id string, quota *QuotaSnapshot) error RecordCheckin(ctx context.Context, id, status, msg string, at time.Time) error + RecordCheckinStatus(ctx context.Context, id string, update CheckinStatusUpdate) error ListCheckinRecords(ctx context.Context, accountID string, limit int) ([]CheckinRecord, error) GetSecret(ctx context.Context, name string) (string, bool, error) SetSecret(ctx context.Context, name, value string) error diff --git a/internal/accounts/types.go b/internal/accounts/types.go index f8b06522..6cfd3040 100644 --- a/internal/accounts/types.go +++ b/internal/accounts/types.go @@ -56,16 +56,24 @@ type Account struct { CheckinTime string `json:"checkin_time"` ProxyURL string `json:"-"` // LastCheckin* are display-only WorkBuddy ops results. - LastCheckinAt string `json:"last_checkin_at,omitempty"` - LastCheckinMsg string `json:"last_checkin_msg,omitempty"` - LastCheckinStatus string `json:"last_checkin_status,omitempty"` - Status string `json:"status"` - LastError string `json:"last_error,omitempty"` - LastErrorKind string `json:"last_error_kind,omitempty"` - CooldownUntil *time.Time `json:"cooldown_until,omitempty"` - Quota *QuotaSnapshot `json:"-"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + LastCheckinAt string `json:"last_checkin_at,omitempty"` + LastCheckinMsg string `json:"last_checkin_msg,omitempty"` + LastCheckinStatus string `json:"last_checkin_status,omitempty"` + // LastCheckinSource is "local" for a real check-in attempt and "upstream" + // for a status-only read. LastCheckinSyncedAt is when the upstream status + // was last verified, independent of when the check-in happened. + LastCheckinSource string `json:"last_checkin_source,omitempty"` + LastCheckinSyncedAt string `json:"last_checkin_synced_at,omitempty"` + // CheckinAutoTime is the upstream daily window start + 1 hour, stored as + // HH:MM in the provider timezone. Empty means use the provider fallback. + CheckinAutoTime string `json:"checkin_auto_time,omitempty"` + Status string `json:"status"` + LastError string `json:"last_error,omitempty"` + LastErrorKind string `json:"last_error_kind,omitempty"` + CooldownUntil *time.Time `json:"cooldown_until,omitempty"` + Quota *QuotaSnapshot `json:"-"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } type CheckinAllResult struct { @@ -76,6 +84,17 @@ type CheckinAllResult struct { Message string `json:"message,omitempty"` } +// CheckinStatusUpdate persists an upstream status read. CheckinAt is only set +// when upstream confirms today's check-in; AutoTime is the derived HH:MM slot. +type CheckinStatusUpdate struct { + Status string + Message string + Source string + CheckinAt string + AutoTime string + SyncedAt time.Time +} + type CreateAccount struct { AutoCheckin *bool CheckinTime string diff --git a/internal/control/s06_control_test.go b/internal/control/s06_control_test.go index b6e17e02..e7baf583 100644 --- a/internal/control/s06_control_test.go +++ b/internal/control/s06_control_test.go @@ -172,6 +172,9 @@ func (s *fakeStore) SaveQuota(context.Context, string, *accounts.QuotaSnapshot) func (s *fakeStore) RecordCheckin(context.Context, string, string, string, time.Time) error { return nil } +func (s *fakeStore) RecordCheckinStatus(context.Context, string, accounts.CheckinStatusUpdate) error { + return nil +} func (s *fakeStore) ListCheckinRecords(_ context.Context, accountID string, _ int) ([]accounts.CheckinRecord, error) { s.log.add("store.ListCheckinRecords") return s.checkins[accountID], nil diff --git a/internal/providers/checkin.go b/internal/providers/checkin.go index dbfdab64..6bf7b261 100644 --- a/internal/providers/checkin.go +++ b/internal/providers/checkin.go @@ -1,8 +1,51 @@ package providers -import "context" +import ( + "context" + "time" +) + +// CheckinSureHour is the first hour of the provider's UTC+8 day from which a +// campaign-level status without a per-day flag can be trusted. WorkBuddy +// (today_checked_in), Trae (checked_in), MiniMax (is_today) and QwenWork +// (CLAIMED_TODAY) carry a server-computed day flag and are read directly; +// CodeArts only exposes a campaign status that stays CONFIRMED across days. +// Two hours after the 00:00 rollover leaves room for cache and settlement +// lag before that campaign status is treated as today's. +const CheckinSureHour = 2 + +// CheckinClaimSettledHour is the first hour from which a claim endpoint's +// "already claimed" answer is trusted. The automatic schedule runs at 01:00 +// (earliest window + 1h); a vendor that has not rolled its day yet can still +// answer with yesterday's "already" at that hour. Treat that answer as +// unconfirmed for one more hour and let the retry pick it up, rather than +// recording a false success and skipping the whole day. +const CheckinClaimSettledHour = 2 + +var checkinCalendarZone = time.FixedZone("UTC+8", 8*3600) + +// CheckinCalendarNow returns t in the provider check-in calendar (UTC+8). +func CheckinCalendarNow(t time.Time) time.Time { + return t.In(checkinCalendarZone) +} + +// CheckinAnswerProvisional reports whether a campaign-level "already" answer +// at t may still describe the previous provider day. A fresh local success is +// always authoritative and is handled by the runtime separately. +func CheckinAnswerProvisional(t time.Time) bool { + return CheckinCalendarNow(t).Hour() < CheckinSureHour +} + +// CheckinClaimProvisional reports whether an "already claimed" answer from the +// claim endpoint is still early enough to be yesterday's stale state. +func CheckinClaimProvisional(t time.Time) bool { + return CheckinCalendarNow(t).Hour() < CheckinClaimSettledHour +} type CheckinPolicy struct { + // Timezone is the provider's server-side check-in calendar zone, not the + // operator PC's zone. Use an IANA location such as Asia/Shanghai; never + // "Local", so schedules stay stable when the host or browser moves. Timezone string `json:"timezone"` } @@ -10,16 +53,28 @@ type CheckinResult struct { Status string `json:"status"` Message string `json:"message"` RewardCredits float64 `json:"reward_credits,omitempty"` + Streak int `json:"streak,omitempty"` + // EarliestCheckin is the upstream daily window start as HH:MM in the + // provider's configured timezone. Empty means the provider did not expose it. + EarliestCheckin string `json:"earliest_checkin,omitempty"` } func (result CheckinResult) Valid() bool { - return result.Status == "success" || result.Status == "already" || result.Status == "skipped" + return result.Status == "success" || result.Status == "already" || result.Status == "skipped" || + result.Status == "pending" || result.Status == "unknown" || result.Status == "error" } type AccountCheckiner interface { Checkin(ctx context.Context, accountID string) (CheckinResult, error) } +// AccountCheckinStatusReader reads the upstream check-in state without claiming +// anything. Providers that share one endpoint for read and claim only implement +// this when the read path can be separated safely. +type AccountCheckinStatusReader interface { + CheckinStatus(ctx context.Context, accountID string) (CheckinResult, error) +} + func CheckinFor(providerID, regionID string) (*CheckinPolicy, bool) { _, region, err := Resolve(providerID, regionID) return region.Checkin, err == nil && region.Checkin != nil diff --git a/internal/providers/checkin_window.go b/internal/providers/checkin_window.go new file mode 100644 index 00000000..58297b57 --- /dev/null +++ b/internal/providers/checkin_window.go @@ -0,0 +1,56 @@ +package providers + +import ( + "strings" + "time" +) + +// CheckinClock formats a provider daily window start as HH:MM. Providers that +// return an absolute timestamp use the same +08:00 wall clock their desktop +// clients use for the daily reset, even when the host runs elsewhere. +func CheckinClock(value time.Time) string { + if value.IsZero() { + return "" + } + return value.In(time.FixedZone("UTC+8", 8*3600)).Format("15:04") +} + +// CheckinClockFromUnix converts Unix seconds (Qoder campaign windows) to HH:MM. +func CheckinClockFromUnix(seconds int64) string { + if seconds <= 0 { + return "" + } + return CheckinClock(time.Unix(seconds, 0)) +} + +// CheckinClockFromUnixMillis converts Unix milliseconds (QwenWork nextClaimAt) +// to HH:MM. +func CheckinClockFromUnixMillis(milliseconds int64) string { + if milliseconds <= 0 { + return "" + } + return CheckinClock(time.UnixMilli(milliseconds)) +} + +// CheckinClockFromText extracts the wall-clock time from the campaign timestamps +// providers return as plain strings ("2026-09-30 00:00:00" or RFC3339). +// +// Timestamps that carry a zone are converted to the provider's UTC+8 calendar; +// timestamps without a zone are already the server's wall clock, so they are +// formatted as-is. This keeps a UTC "00:00Z" from being mistaken for a Beijing +// midnight window. +func CheckinClockFromText(value string) string { + value = strings.TrimSpace(value) + if parsed, err := time.Parse(time.RFC3339Nano, value); err == nil { + return CheckinClock(parsed) + } + for _, layout := range []string{ + "2006-01-02 15:04:05", + "2006-01-02 15:04", + } { + if parsed, err := time.Parse(layout, value); err == nil { + return parsed.Format("15:04") + } + } + return "" +} diff --git a/internal/providers/checkin_window_test.go b/internal/providers/checkin_window_test.go new file mode 100644 index 00000000..612865c2 --- /dev/null +++ b/internal/providers/checkin_window_test.go @@ -0,0 +1,59 @@ +package providers + +import ( + "testing" + "time" +) + +func mustParse(t *testing.T, value string) time.Time { + t.Helper() + parsed, err := time.Parse(time.RFC3339, value) + if err != nil { + t.Fatal(err) + } + return parsed +} + +func TestCheckinClockFromTextUsesProviderCalendar(t *testing.T) { + cases := []struct { + name string + value string + want string + }{ + {"naive wall clock", "2026-11-24 00:00:00", "00:00"}, + {"utc midnight is beijing morning", "2026-11-23T16:00:00Z", "00:00"}, + {"explicit beijing midnight", "2026-11-24T00:00:00+08:00", "00:00"}, + {"utc ten is beijing eighteen", "2026-11-24T10:00:00Z", "18:00"}, + {"minute precision", "2026-11-24 09:59", "09:59"}, + {"empty", "", ""}, + {"garbage", "not-a-time", ""}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + if got := CheckinClockFromText(test.value); got != test.want { + t.Fatalf("CheckinClockFromText(%q)=%q want %q", test.value, got, test.want) + } + }) + } +} + +func TestCheckinAnswerProvisionalAtDayRollover(t *testing.T) { + if !CheckinAnswerProvisional(mustParse(t, "2026-11-23T17:59:59Z")) { // 01:59 Beijing + t.Fatal("01:59 Beijing must still be provisional") + } + if CheckinAnswerProvisional(mustParse(t, "2026-11-23T18:00:00Z")) { // 02:00 Beijing + t.Fatal("02:00 Beijing must be settled") + } +} + +func TestCheckinClaimProvisionalOnlyAroundMidnight(t *testing.T) { + if !CheckinClaimProvisional(mustParse(t, "2026-11-23T16:30:00Z")) { // 00:30 Beijing + t.Fatal("00:30 claim answer must be provisional") + } + if !CheckinClaimProvisional(mustParse(t, "2026-11-23T17:59:59Z")) { // 01:59 Beijing + t.Fatal("01:59 claim answer must be provisional") + } + if CheckinClaimProvisional(mustParse(t, "2026-11-23T18:00:00Z")) { // 02:00 Beijing + t.Fatal("02:00 claim answer must be settled") + } +} diff --git a/internal/providers/codearts/checkin.go b/internal/providers/codearts/checkin.go index 6b0af9e1..876025c1 100644 --- a/internal/providers/codearts/checkin.go +++ b/internal/providers/codearts/checkin.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -14,10 +15,20 @@ import ( "github.com/caigee-cmd/cli2api/internal/providers" ) -const creditChannel = "IDE" +var errCreditAlreadyClaimed = errors.New("codearts credit already claimed") + +const ( + creditChannel = "IDE" + // CodeArts publishes the daily check-in as campaign 1 and the one-time + // new-user reward as campaign 4. Titles are matched too so a regional + // rename does not silently stop the automatic path. + dailyCreditCampaignID = 1 + newUserCreditCampaignID = 4 +) type creditCampaign struct { ID int `json:"campaignId"` + Type string `json:"type"` Title string `json:"title"` Status string `json:"status"` Claimable bool `json:"claimable"` @@ -30,13 +41,67 @@ type creditCampaign struct { } `json:"extra"` } +func isDailyCreditCampaign(campaign creditCampaign) bool { + if strings.EqualFold(strings.TrimSpace(campaign.Type), "USER_LOGIN") { + return true + } + if campaign.ID == dailyCreditCampaignID { + return true + } + title := strings.ToLower(strings.TrimSpace(campaign.Title)) + return strings.Contains(title, "daily") || strings.Contains(title, "每日") || strings.Contains(title, "签到") +} + +func isNewUserCreditCampaign(campaign creditCampaign) bool { + return strings.EqualFold(strings.TrimSpace(campaign.Type), "NEW_USER_REGISTER") || + campaign.ID == newUserCreditCampaignID +} + +// isAutomaticCreditCampaign limits unattended claims to the daily check-in and +// the new-user campaign. Every claimable credit campaign is not safe to claim: +// student verification, invite rewards, and other manual benefit campaigns can +// also be "claimable" and must stay an explicit user action. +func isAutomaticCreditCampaign(campaign creditCampaign) bool { + return isDailyCreditCampaign(campaign) || isNewUserCreditCampaign(campaign) +} + +// creditCampaignTime parses both RFC3339 timestamps and the plain Asia/Shanghai +// wall-clock strings the ops API may return. +func creditCampaignTime(value string) (time.Time, bool) { + value = strings.TrimSpace(value) + if value == "" { + return time.Time{}, false + } + if parsed, err := time.Parse(time.RFC3339Nano, value); err == nil { + return parsed, true + } + zone := time.FixedZone("UTC+8", 8*3600) + for _, layout := range []string{"2006-01-02 15:04:05", "2006-01-02 15:04"} { + if parsed, err := time.ParseInLocation(layout, value, zone); err == nil { + return parsed, true + } + } + return time.Time{}, false +} + +func creditCampaignOpen(campaign creditCampaign, now time.Time) bool { + if start, ok := creditCampaignTime(campaign.Extra.StartTime); ok && now.Before(start) { + return false + } + if end, ok := creditCampaignTime(campaign.Extra.EndTime); ok && !now.Before(end) { + return false + } + return true +} + type creditClaim struct { - CampaignID int - Title string - OK bool - Status string - Credits float64 - Message string + CampaignID int + Title string + OK bool + Status string + Credits float64 + Provisional bool + Message string } // Checkin claims the daily check-in (campaign 1) and the new-user campaign @@ -54,16 +119,27 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check var claims []creditClaim total := 0.0 allOK := true + provisional := false for _, campaign := range campaigns { // The server marks the activities an account may actually claim. Only - // time-triggered credit rewards are automatic: student verification and - // invite campaigns are never claimed on the user's behalf. - if !campaign.Claimable || campaign.BenefitUnit != "" && campaign.BenefitUnit != "CREDIT" { + // the daily check-in and the new-user reward are automatic: student + // verification and invite campaigns are never claimed on behalf of the + // user even when the server marks them claimable. The daily campaign is + // read even when it is already claimed so the result says "already" + // instead of "no campaign". + if campaign.BenefitUnit != "" && campaign.BenefitUnit != "CREDIT" { + continue + } + if !isAutomaticCreditCampaign(campaign) { + continue + } + if !campaign.Claimable && !isDailyCreditCampaign(campaign) { continue } claim := c.claimCampaign(ctx, accountID, credential, campaign) claims = append(claims, claim) allOK = allOK && claim.OK + provisional = provisional || claim.Provisional total += claim.Credits } if len(claims) == 0 { @@ -81,6 +157,9 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check } if already { status = "already" + if provisional { + status = "unknown" + } } } parts := make([]string, 0, len(claims)) @@ -94,51 +173,170 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check }, nil } +func (c *Client) CheckinStatus(ctx context.Context, accountID string) (providers.CheckinResult, error) { + credential, err := c.credential(ctx, accountID) + if err != nil { + return providers.CheckinResult{}, err + } + campaigns, err := c.fetchCampaigns(ctx, accountID, credential) + if err != nil { + return providers.CheckinResult{}, err + } + now := c.now() + result := providers.CheckinResult{} + pending := false + dailyClaimed := false + for _, campaign := range campaigns { + if campaign.BenefitUnit != "" && campaign.BenefitUnit != "CREDIT" { + continue + } + if !isAutomaticCreditCampaign(campaign) { + continue + } + if isDailyCreditCampaign(campaign) && result.EarliestCheckin == "" { + // extra.startTime is the campaign's launch date, not the daily reset. + // The CodeArts daily panel rolls over at 00:00 Asia/Shanghai. + result.EarliestCheckin = "00:00" + } + if !creditCampaignOpen(campaign, now) { + continue + } + if campaign.Claimable { + pending = true + continue + } + if isDailyCreditCampaign(campaign) { + switch campaign.Status { + case "CONFIRMED", "CONSUMED", "CLAIMED": + dailyClaimed = true + } + } + } + switch { + case pending: + result.Status = "pending" + result.Message = "上游显示可签到" + case dailyClaimed: + // The new-user campaign stays CONFIRMED forever. Only the daily + // campaign may make the account look checked in, or a used-up new-user + // reward would report "already" every day. + if providers.CheckinAnswerProvisional(now) { + result.Status = "unknown" + result.Message = "上游日界尚未确认,稍后复核" + } else { + result.Status = "already" + result.Message = "今日已签到" + } + default: + result.Status = "skipped" + result.Message = "当前无可签到活动" + } + if result.EarliestCheckin == "" { + result.EarliestCheckin = "00:00" + } + return result, nil +} + func (c *Client) claimCampaign(ctx context.Context, accountID string, credential Credential, campaign creditCampaign) creditClaim { claim := creditClaim{CampaignID: campaign.ID, Title: campaign.Title, Status: campaign.Status, OK: true} if claim.Title == "" { claim.Title = fmt.Sprintf("credit campaign %d", campaign.ID) } now := c.now() - if end, err := time.Parse(time.RFC3339Nano, campaign.Extra.EndTime); err == nil && !now.Before(end) { + if end, ok := creditCampaignTime(campaign.Extra.EndTime); ok && !now.Before(end) { + claim.OK = false claim.Message = "campaign ended" return claim } - if start, err := time.Parse(time.RFC3339Nano, campaign.Extra.StartTime); err == nil && now.Before(start) { + if start, ok := creditCampaignTime(campaign.Extra.StartTime); ok && now.Before(start) { + claim.OK = false claim.Message = "campaign has not started" return claim } + // Before the provider day is confirmed, a daily campaign marked CONFIRMED + // may still be yesterday's. Re-issuing the idempotent claim tells the server + // to replay yesterday's result or deliver today's, instead of suppressing + // today's check-in. + provisionalDaily := isDailyCreditCampaign(campaign) && providers.CheckinAnswerProvisional(now) + claimedBefore := false switch campaign.Status { case "CONFIRMED", "CONSUMED": - claim.Message = "already claimed" - return claim + claimedBefore = true + if !provisionalDaily { + claim.Message = "already claimed" + return claim + } case "CLAIMED": + claimedBefore = true // Already delivered; only the confirm step may be missing. case "ELIGIBLE": - if _, err := c.creditRequest(ctx, accountID, credential, http.MethodPost, creditClaimPath, map[string]any{ - "campaignId": campaign.ID, "channel": creditChannel, - "idempotentKey": fmt.Sprintf("claim_%d_%d", campaign.ID, now.UnixMilli()), - }); err != nil { - claim.OK = false - claim.Message = err.Error() - return claim - } - claim.Status = "CLAIMED" - claim.Credits = campaign.PendingTotalAmount - if claim.Credits <= 0 { - claim.Credits = campaign.BenefitAmount + default: + claim.OK = false + if campaign.Status == "" { + claim.Message = "not eligible" + } else { + claim.Message = "unknown campaign status: " + campaign.Status } - case "": - claim.Message = "not eligible" return claim - default: + } + // The ops claim body is only {campaignId, channel}; the protocol has no + // client-supplied idempotency key. Repeated claims are deduplicated by the + // server with code 40001 instead. + raw, err := c.creditRequest(ctx, accountID, credential, http.MethodPost, creditClaimPath, map[string]any{ + "campaignId": campaign.ID, "channel": creditChannel, + }) + if err != nil { + if errors.Is(err, errCreditAlreadyClaimed) { + claim.Status = "CONFIRMED" + claim.Message = "今天已领取" + claim.Credits = 0 + claim.Provisional = providers.CheckinClaimProvisional(now) + return claim + } claim.OK = false - claim.Message = "unknown campaign status: " + campaign.Status + claim.Message = err.Error() return claim } - // The current ops API has no confirm step: a successful claim is final. - // Older builds polled /v1/ops/confirm, which now just returns 404 and made - // successful daily check-ins look like failures. + var benefit struct { + ID json.RawMessage `json:"id"` + BenefitAmount float64 `json:"benefitAmount"` + Credits float64 `json:"credits"` + Credit float64 `json:"credit"` + Amount float64 `json:"amount"` + CreditAmount float64 `json:"creditAmount"` + } + _ = json.Unmarshal(raw, &benefit) + if len(benefit.ID) > 0 && string(benefit.ID) != "null" { + // The IDE posts /v1/ops/confirm whenever the claim returns a benefit id; + // without it the credits can stay pending. This step is best effort: + // older builds answer 404 here and the claim is still successful. + _, _ = c.creditRequest(ctx, accountID, credential, http.MethodPost, creditConfirmPath, map[string]any{ + "campaignId": campaign.ID, + }) + } + claim.Status = "CONFIRMED" + if provisionalDaily && claimedBefore { + // The claim was a replay/verification of a state that may have been + // yesterday's. Do not report the old campaign amount as new credits. + claim.Credits = 0 + claim.Message = "已签到(复查确认)" + claim.Provisional = providers.CheckinClaimProvisional(now) + return claim + } + claim.Status = "CLAIMED" + claim.Credits = campaign.PendingTotalAmount + for _, value := range []float64{benefit.BenefitAmount, benefit.Credits, benefit.Credit, benefit.CreditAmount, benefit.Amount} { + if value > 0 { + claim.Credits = value + break + } + } + if claim.Credits <= 0 { + claim.Credits = campaign.BenefitAmount + } + // The claims endpoint is the source of truth. When it returned a benefit id + // this function already posted the IDE's best-effort /v1/ops/confirm above; + // a missing confirm response is not a failed claim. claim.Status = "CONFIRMED" if claim.Credits > 0 { claim.Message = fmt.Sprintf("claimed %g credits", claim.Credits) @@ -210,6 +408,9 @@ func (c *Client) creditRequest(ctx context.Context, accountID string, credential return nil, fmt.Errorf("codearts credit response missing business code") } if *envelope.Code != 0 { + if *envelope.Code == 40001 { + return nil, fmt.Errorf("%w: %s", errCreditAlreadyClaimed, envelope.Message) + } return nil, &providers.Error{Kind: accounts.KindInvalidRequest, Status: http.StatusBadRequest, Message: envelope.Message} } return envelope.Data, nil diff --git a/internal/providers/codearts/client.go b/internal/providers/codearts/client.go index 114042ac..0e2f5b69 100644 --- a/internal/providers/codearts/client.go +++ b/internal/providers/codearts/client.go @@ -295,15 +295,16 @@ func (c *Client) Probe(ctx context.Context, accountID string) (providers.Account // Adapter wires the capability surface. func (c *Client) Adapter() providers.Adapter { return providers.Adapter{ - ID: ProviderID, - Credential: credentialCodec{}, - Login: c, - Chat: c, - Models: c, - Classifier: classifier{}, - ImportExport: importer{}, - Prober: c, - Checkin: c, + ID: ProviderID, + Credential: credentialCodec{}, + Login: c, + Chat: c, + Models: c, + Classifier: classifier{}, + ImportExport: importer{}, + Prober: c, + Checkin: c, + CheckinStatus: c, } } diff --git a/internal/providers/codearts/codearts_test.go b/internal/providers/codearts/codearts_test.go index 01544031..0eb08f97 100644 --- a/internal/providers/codearts/codearts_test.go +++ b/internal/providers/codearts/codearts_test.go @@ -565,6 +565,191 @@ func TestProbeAndCheckin(t *testing.T) { } } +func TestCheckinStatusDoesNotTreatNewUserCampaignAsDaily(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != creditDeliveryPath { + http.NotFound(w, r) + return + } + _, _ = io.WriteString(w, `{"code":0,"data":{"items":[ + {"campaignId":4,"title":"New user","status":"CONFIRMED","claimable":false,"benefitUnit":"CREDIT","extra":{"startTime":"2026-01-01T00:00:00Z","endTime":"2027-01-01T00:00:00Z"}} + ]}}`) + })) + defer server.Close() + client, _ := newTestClient(t, server) + client.nowFn = func() time.Time { return time.Date(2026, 11, 24, 4, 0, 0, 0, time.UTC) } + + result, err := client.CheckinStatus(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "skipped" { + t.Fatalf("a used-up new-user reward must not mean today's daily check-in is done: %+v", result) + } +} + +func TestCheckinStatusDailyClaimIsProvisionalAtDayRollover(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != creditDeliveryPath { + http.NotFound(w, r) + return + } + _, _ = io.WriteString(w, `{"code":0,"data":{"items":[ + {"campaignId":1,"title":"Daily","status":"CONFIRMED","claimable":false,"benefitUnit":"CREDIT","extra":{"startTime":"2026-01-01T00:00:00Z","endTime":"2027-01-01T00:00:00Z"}} + ]}}`) + })) + defer server.Close() + client, _ := newTestClient(t, server) + + client.nowFn = func() time.Time { return time.Date(2026, 11, 23, 17, 0, 0, 0, time.UTC) } // 01:00 Beijing + result, err := client.CheckinStatus(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "unknown" { + t.Fatalf("01:00 answer must be provisional: %+v", result) + } + + client.nowFn = func() time.Time { return time.Date(2026, 11, 23, 18, 0, 0, 0, time.UTC) } // 02:00 Beijing + result, err = client.CheckinStatus(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "already" { + t.Fatalf("02:00 answer must be settled: %+v", result) + } +} + +func TestCheckinReclaimsDailyCampaignAtDayRollover(t *testing.T) { + claims := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case creditDeliveryPath: + _, _ = io.WriteString(w, `{"code":0,"data":{"items":[ + {"campaignId":1,"title":"Daily","status":"CONFIRMED","claimable":false,"benefitUnit":"CREDIT","benefitAmount":100,"extra":{"startTime":"2026-01-01T00:00:00Z","endTime":"2027-01-01T00:00:00Z"}} + ]}}`) + case creditClaimPath: + claims++ + _, _ = io.WriteString(w, `{"code":0,"data":{}}`) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client, _ := newTestClient(t, server) + client.nowFn = func() time.Time { return time.Date(2026, 11, 23, 17, 0, 0, 0, time.UTC) } // 01:00 Beijing + + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if claims != 1 { + t.Fatalf("01:00 CONFIRMED daily campaign must be re-claimed once, got %d", claims) + } + if result.Status != "unknown" || result.RewardCredits != 0 { + t.Fatalf("rollover replay must stay unconfirmed and must not be reported as new credits: %+v", result) + } +} + +func TestCheckinClaimsOnlyAutomaticCampaigns(t *testing.T) { + var claimed []string + var claimBodies []map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case creditDeliveryPath: + _, _ = io.WriteString(w, `{"code":0,"data":{"items":[ + {"campaignId":1,"type":"USER_LOGIN","title":"Daily","status":"ELIGIBLE","claimable":true,"benefitUnit":"CREDIT","benefitAmount":100,"pendingTotalAmount":100,"extra":{"startTime":"2026-01-01T00:00:00Z","endTime":"2027-01-01T00:00:00Z"}}, + {"campaignId":2,"type":"STUDENT_CERTIFIED","title":"Student verification","status":"ELIGIBLE","claimable":true,"benefitUnit":"CREDIT","benefitAmount":500,"extra":{"startTime":"2026-01-01T00:00:00Z","endTime":"2027-01-01T00:00:00Z"}} + ]}}`) + case creditClaimPath: + claimed = append(claimed, r.URL.Path) + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + claimBodies = append(claimBodies, body) + _, _ = io.WriteString(w, `{"code":0,"data":{}}`) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client, _ := newTestClient(t, server) + client.nowFn = func() time.Time { return time.Date(2026, 11, 24, 4, 0, 0, 0, time.UTC) } + + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "success" || len(claimed) != 1 { + t.Fatalf("result=%+v claims=%d; student campaign must not be auto-claimed", result, len(claimed)) + } + if _, ok := claimBodies[0]["idempotentKey"]; ok { + t.Fatalf("ops claim schema must not grow an idempotentKey: %v", claimBodies[0]) + } + if got := claimBodies[0]["campaignId"]; got != float64(1) { + t.Fatalf("campaignId=%v want 1", got) + } +} + +func TestCheckinTreatsAlreadyClaimedBusinessCodeAsAlready(t *testing.T) { + confirmations := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case creditDeliveryPath: + _, _ = io.WriteString(w, `{"code":0,"data":{"items":[ + {"campaignId":1,"type":"USER_LOGIN","title":"Daily","status":"ELIGIBLE","claimable":true,"benefitUnit":"CREDIT","benefitAmount":100,"extra":{"startTime":"2026-01-01T00:00:00Z","endTime":"2027-01-01T00:00:00Z"}} + ]}}`) + case creditClaimPath: + _, _ = io.WriteString(w, `{"code":40001,"message":"尚未到达权益刷新时间,暂时无法领取","data":null}`) + case creditConfirmPath: + confirmations++ + _, _ = io.WriteString(w, `{"code":0,"data":{}}`) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client, _ := newTestClient(t, server) + client.nowFn = func() time.Time { return time.Date(2026, 11, 24, 4, 0, 0, 0, time.UTC) } + + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "already" || confirmations != 0 { + t.Fatalf("40001 must be already, not a failure: result=%+v confirmations=%d", result, confirmations) + } +} + +func TestCheckinConfirmsBenefitWhenClaimReturnsID(t *testing.T) { + confirmations := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case creditDeliveryPath: + _, _ = io.WriteString(w, `{"code":0,"data":{"items":[ + {"campaignId":1,"type":"USER_LOGIN","title":"Daily","status":"ELIGIBLE","claimable":true,"benefitUnit":"CREDIT","benefitAmount":100,"extra":{"startTime":"2026-01-01T00:00:00Z","endTime":"2027-01-01T00:00:00Z"}} + ]}}`) + case creditClaimPath: + _, _ = io.WriteString(w, `{"code":0,"data":{"id":42,"benefitAmount":100}}`) + case creditConfirmPath: + confirmations++ + _, _ = io.WriteString(w, `{"code":0,"data":{}}`) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client, _ := newTestClient(t, server) + client.nowFn = func() time.Time { return time.Date(2026, 11, 24, 4, 0, 0, 0, time.UTC) } + + result, err := client.Checkin(context.Background(), "acct-1") + if err != nil { + t.Fatal(err) + } + if result.Status != "success" || result.RewardCredits != 100 || confirmations != 1 { + t.Fatalf("result=%+v confirmations=%d", result, confirmations) + } +} + func TestImporterAndClassifier(t *testing.T) { credential, _ := testCredential().Encode() imported, err := PrepareImport(credential) diff --git a/internal/providers/codearts/doc.go b/internal/providers/codearts/doc.go index 1e02cdf0..fcdc92a3 100644 --- a/internal/providers/codearts/doc.go +++ b/internal/providers/codearts/doc.go @@ -86,7 +86,8 @@ // // The daily check-in and new-user credits are two credit campaigns delivered by // the ops endpoints (/v1/ops/delivery, /v1/ops/claim, /v1/ops/confirm), not by -// the CLI. Claiming is idempotent and the confirm step is retried separately; -// the adapter reports the claimed amount and never presents it as the account -// balance. +// the CLI. Claims are deduplicated by the server (code 40001 = already claimed), +// and the IDE posts /v1/ops/confirm when the claim returns a benefit id; the +// adapter does the same and treats a missing confirm endpoint as non-fatal. It +// reports the claimed amount and never presents it as the account balance. package codearts diff --git a/internal/providers/doubaowork/adapter.go b/internal/providers/doubaowork/adapter.go index 87042132..cb0fe132 100644 --- a/internal/providers/doubaowork/adapter.go +++ b/internal/providers/doubaowork/adapter.go @@ -6,14 +6,15 @@ import "github.com/caigee-cmd/cli2api/internal/providers" // pasted session Cookie, exposed through the import/PAT path. func (c *Client) Adapter() providers.Adapter { return providers.Adapter{ - ID: "doubaowork", - Credential: credentialCodec{}, - Chat: c, - Models: c, - Classifier: classifier{}, - ImportExport: importer{}, - Prober: c, - Checkin: c, + ID: "doubaowork", + Credential: credentialCodec{}, + Chat: c, + Models: c, + Classifier: classifier{}, + ImportExport: importer{}, + Prober: c, + Checkin: c, + CheckinStatus: c, } } diff --git a/internal/providers/doubaowork/checkin.go b/internal/providers/doubaowork/checkin.go index ec7c2905..4487555a 100644 --- a/internal/providers/doubaowork/checkin.go +++ b/internal/providers/doubaowork/checkin.go @@ -117,19 +117,49 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check } state := readCheckin(detail) + earliest := doubaoEarliestClock(detail) if !state.Found { - return providers.CheckinResult{Status: "skipped", Message: "活动里没有每日签到任务"}, nil + return providers.CheckinResult{Status: "skipped", Message: "活动里没有每日签到任务", EarliestCheckin: earliest}, nil } if state.Claimed { message := "今天已签到" if state.Streak > 0 { message = "今天已签到,连续 " + itoa(state.Streak) + " 天" } - return providers.CheckinResult{Status: "already", Message: message, RewardCredits: float64(state.Points)}, nil + return providers.CheckinResult{Status: "already", Message: message, RewardCredits: float64(state.Points), Streak: state.Streak, EarliestCheckin: earliest}, nil } message := "今日未签。豆包把领取限死在电脑版客户端,请在那里点一下" if !state.Claimable { message = "今日签到暂不可领:豆包按账号投放这个活动,你的账号当前没被投放" } - return providers.CheckinResult{Status: "skipped", Message: message, RewardCredits: float64(state.Points)}, nil + return providers.CheckinResult{Status: "skipped", Message: message, RewardCredits: float64(state.Points), EarliestCheckin: earliest}, nil +} + +// CheckinStatus reports the same read-only state without treating the +// client-only claim as an unavailable activity. +func (c *Client) CheckinStatus(ctx context.Context, accountID string) (providers.CheckinResult, error) { + result, err := c.Checkin(ctx, accountID) + if err != nil { + return providers.CheckinResult{}, err + } + if result.Status == "skipped" && strings.Contains(result.Message, "今日未签") { + result.Status = "pending" + result.Message = "上游显示今日未签到(豆包电脑版领取)" + } + return result, nil +} + +func doubaoEarliestClock(detail map[string]any) string { + data, _ := detail["data"].(map[string]any) + if data == nil { + data = detail + } + for _, container := range []map[string]any{data, detail} { + for _, key := range []string{"start_time", "startTime", "begin_time"} { + if clock := providers.CheckinClockFromText(asString(container[key])); clock != "" { + return clock + } + } + } + return "00:00" } diff --git a/internal/providers/interfaces.go b/internal/providers/interfaces.go index bf28630b..a2a2a3c8 100644 --- a/internal/providers/interfaces.go +++ b/internal/providers/interfaces.go @@ -289,15 +289,16 @@ func (e *Error) Error() string { // Adapter bundles the optional capability interfaces. Every field may be nil; // use Supports() before calling so unsupported paths fail explicitly. type Adapter struct { - ID string - Credential CredentialCodec - Login LoginSessionProvider - Chat ProviderChat - Models ModelCatalogProvider - Classifier ErrorClassifier - ImportExport ImportExporter - Prober AccountProber - Checkin AccountCheckiner + ID string + Credential CredentialCodec + Login LoginSessionProvider + Chat ProviderChat + Models ModelCatalogProvider + Classifier ErrorClassifier + ImportExport ImportExporter + Prober AccountProber + Checkin AccountCheckiner + CheckinStatus AccountCheckinStatusReader // StreamFormat declares the SSE dialect ChatStream returns (see // StreamFormat* constants). Empty means chat-completions deltas. StreamFormat string @@ -324,6 +325,8 @@ func (a Adapter) Supports(capability string) bool { return a.Prober != nil case "checkin": return a.Checkin != nil + case "checkin_status": + return a.CheckinStatus != nil case "native_responses": return a.NativeResponses != nil default: diff --git a/internal/providers/minimaxcode/checkin.go b/internal/providers/minimaxcode/checkin.go index c5f50fbf..989705c9 100644 --- a/internal/providers/minimaxcode/checkin.go +++ b/internal/providers/minimaxcode/checkin.go @@ -73,6 +73,48 @@ type signinClaim struct { ExpireAtMs int64 `json:"expire_at_ms"` } +// CheckinStatus reads the seven-day panel without claiming. +func (c *Client) CheckinStatus(ctx context.Context, accountID string) (providers.CheckinResult, error) { + ctx, cancel := context.WithTimeout(ctx, checkinTimeout) + defer cancel() + credential, err := c.credential(ctx, accountID) + if err != nil { + return providers.CheckinResult{}, err + } + userID, err := c.checkinUserID(ctx, accountID, credential) + if err != nil { + return providers.CheckinResult{}, err + } + data, err := c.signedGatewayCall(ctx, accountID, http.MethodGet, signinStatusPath, "", userID, "status") + if err != nil { + return providers.CheckinResult{}, err + } + var panel signinPanel + if err := json.Unmarshal(data, &panel); err != nil { + return providers.CheckinResult{}, fmt.Errorf("minimaxcode check-in: invalid status payload") + } + today := todaySigninDay(panel) + result := providers.CheckinResult{EarliestCheckin: "00:00"} + switch { + case today != nil && today.Status == signinDayClaimed: + // is_today is computed by the provider panel; it is already the + // provider's own day, so no local date guess is layered on top. + result.Status = "already" + result.Message = "今天已签到" + result.RewardCredits = today.Points + case today != nil && today.Status == signinDayClaimable: + result.Status = "pending" + result.Message = "上游显示今日可签到" + case today != nil && today.Status == signinDayUpcoming: + result.Status = "skipped" + result.Message = "签到尚未开始" + default: + result.Status = "skipped" + result.Message = skippedCheckinMessage(panel) + } + return result, nil +} + // Checkin implements providers.AccountCheckiner for the MiniMax Code daily // sign-in. It reads the seven-day panel, claims today when the panel offers it, // and reports "already"/"skipped" otherwise so the console card and records stay @@ -102,6 +144,8 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check today := todaySigninDay(panel) switch { case today != nil && today.Status == signinDayClaimed: + // is_today already identifies the provider's current day; the panel is + // authoritative and does not need an extra claim to prove the date. return alreadyCheckedInResult(panel), nil case today != nil && today.Status == signinDayClaimable: return c.claimSignin(ctx, accountID, userID) @@ -128,6 +172,8 @@ func (c *Client) claimSignin(ctx context.Context, accountID, userID string) (pro } return providers.CheckinResult{Status: "success", Message: message, RewardCredits: claim.Points}, nil case signinAlreadyClaimed: + // The panel was CLAIMABLE before this claim in the provider's own day; + // "already claimed" is today's result, not a replay from yesterday. return providers.CheckinResult{Status: "already", Message: "今天已签到"}, nil default: return providers.CheckinResult{}, fmt.Errorf("minimaxcode check-in: unexpected claim result %d", claim.ClaimResult) @@ -247,6 +293,11 @@ func (c *Client) newSignedGatewayRequest(ctx context.Context, credential Credent query.Set("version_code", gatewayVersionCode) query.Set("unix", strconv.FormatInt(now.UnixMilli(), 10)) query.Set("timezone_offset", strconv.Itoa(gatewayTimezoneOffset)) + if path == signinStatusPath || path == signinClaimPath { + // The desktop signs with the numeric offset; the web panel also sends + // the IANA zone. Keep both so either server build resolves the same day. + query.Set("timezone_id", "Asia/Shanghai") + } language := "zh" if credential.Site == "global" { language = "en" diff --git a/internal/providers/minimaxcode/client.go b/internal/providers/minimaxcode/client.go index 9f11859a..02ff2e17 100644 --- a/internal/providers/minimaxcode/client.go +++ b/internal/providers/minimaxcode/client.go @@ -246,15 +246,16 @@ func (c *Client) storedReasoning(ctx context.Context, model string) string { func (c *Client) Adapter() providers.Adapter { return providers.Adapter{ - ID: ProviderID, - Credential: credentialCodec{}, - Login: c, - Chat: c, - Models: c, - Classifier: classifier{}, - ImportExport: importer{}, - Prober: c, - Checkin: c, + ID: ProviderID, + Credential: credentialCodec{}, + Login: c, + Chat: c, + Models: c, + Classifier: classifier{}, + ImportExport: importer{}, + Prober: c, + Checkin: c, + CheckinStatus: c, } } diff --git a/internal/providers/qoder/adapter.go b/internal/providers/qoder/adapter.go index cd0e4167..178a3471 100644 --- a/internal/providers/qoder/adapter.go +++ b/internal/providers/qoder/adapter.go @@ -155,12 +155,13 @@ func (c *Client) SetLoginWait(timeout, interval time.Duration) { func (c *Client) Adapter() providers.Adapter { return providers.Adapter{ - ID: "qoder", - Credential: patCodec{}, - Login: c, - Chat: c, - Models: c, - Checkin: c, + ID: "qoder", + Credential: patCodec{}, + Login: c, + Chat: c, + Models: c, + Checkin: c, + CheckinStatus: c, // Prober covers PAT-backed in-process accounts (no worker URL): Probe // bootstraps/renews the Bridge session and Quota pulls the OpenAPI // usage, so the console's status and "refresh credits" match the diff --git a/internal/providers/qoder/checkin.go b/internal/providers/qoder/checkin.go index d9838b76..a76bc08e 100644 --- a/internal/providers/qoder/checkin.go +++ b/internal/providers/qoder/checkin.go @@ -55,6 +55,19 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check return b.Checkin(ctx) } +// CheckinStatus reads the campaign state only; legacy worker accounts have no +// status-only endpoint, so they report unknown until the next real check-in. +func (c *Client) CheckinStatus(ctx context.Context, accountID string) (providers.CheckinResult, error) { + b, err := c.bridge(ctx, accountID) + if err != nil { + if errors.Is(err, ErrPATRequired) { + return providers.CheckinResult{Status: "unknown", Message: "旧版 Qoder 账号暂不支持上游状态同步", EarliestCheckin: "10:00"}, nil + } + return providers.CheckinResult{}, err + } + return b.CheckinStatus(ctx) +} + // workerCheckin is the legacy fallback for accounts that still carry a // qoder-native-v1 blob instead of a PAT. It POSTs the worker's /admin/checkin // endpoint and decodes its response. It will be removed with the worker in @@ -93,35 +106,25 @@ func (c *Client) workerCheckin(ctx context.Context, accountID string) (providers return payload.CheckinResult, nil } -// Checkin runs the daily credit-claim using the bridge's in-process session. -// It is a method on Bridge so the per-account session, machine identity, and -// token-rotation state are all reused across catalog/quota/checkin. -func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) { - // Rotate the session if needed before the call: a stale token surfaces as - // a 401 on the campaigns endpoint, and while the request path below - // retries once with ForceRefresh, proactively refreshing avoids the round - // trip. +// checkinDoer builds the signed campaign requester shared by the claim and +// status paths. The returned bearer pointer lets the caller switch to the COSY +// fallback token without rebuilding the closure. +func (b *Bridge) checkinDoer(ctx context.Context) (checkinRequester, *string, error) { if err := b.EnsureFreshSession(ctx); err != nil { - return providers.CheckinResult{}, fmt.Errorf("qoder check-in: session: %w", err) + return nil, nil, fmt.Errorf("qoder check-in: session: %w", err) } - endpoint := checkinEndpoint(b.Region) if endpoint == nil { - return providers.CheckinResult{Status: "skipped", Message: "签到活动未开放"}, nil + return nil, nil, errCheckinUnavailable } - - // The campaign endpoint's bearer differs by region: CN accepts the COSY - // securityOauthToken; Global rejects it (401) and needs a separately-issued - // OpenAPI bearer. quotaBearer returns the right one and caches the global - // token. Fall back to the COSY token if the exchange fails. bearer, err := b.quotaBearer(ctx) if err != nil || bearer == "" { bearer = b.CurrentSecurityOauth() } - + bearerRef := &bearer var doRequest checkinRequester doRequest = func(path, method string, refreshed bool) (map[string]any, int, error) { - token := bearer + token := *bearerRef if token == "" { return nil, 0, errors.New("qoder check-in: token unavailable") } @@ -139,13 +142,8 @@ func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) { req.Header.Set("User-Agent", "Qoder") req.Header.Set("Cosy-ClientType", "10") req.Header.Set("Cosy-Version", qauth.DesktopCosyVersion) - // The campaign endpoint serves the desktop activity iframe. Keep its - // browser origin/referer, while omitting derived machine headers that - // make upstream classify the request as non-official. req.Header.Set("Origin", endpoint.origin) req.Header.Set("Referer", endpoint.base+"/growth-page/activity-iframe") - // redirect: manual — the campaigns endpoint 302s to a login page when - // the token is rejected, and we want to see the 302 rather than follow it. resp, err := checkinHTTPClient.Do(req) if err != nil { return nil, 0, fmt.Errorf("qoder check-in: request failed: %w", err) @@ -153,10 +151,6 @@ func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) { if resp.StatusCode == http.StatusUnauthorized && !refreshed { io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<16)) resp.Body.Close() - // A global-region bearer is the cached OpenAPI token; if it was - // rejected, drop it so the next quotaBearer call re-exchanges rather - // than handing back the same stale token. Then rotate the COSY - // session and re-resolve the bearer before the single retry. if b.Region != nil && b.Region.NeedsOpenAPIToken { b.invalidateOpenAPIBearer() } @@ -164,9 +158,9 @@ func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) { return nil, 0, fmt.Errorf("qoder check-in: refresh failed: %w", err) } if fresh, berr := b.quotaBearer(ctx); berr == nil && fresh != "" { - bearer = fresh + *bearerRef = fresh } else { - bearer = b.CurrentSecurityOauth() + *bearerRef = b.CurrentSecurityOauth() } return doRequest(path, method, true) } @@ -181,6 +175,132 @@ func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) { } return parsed, resp.StatusCode, nil } + return doRequest, bearerRef, nil +} + +var errCheckinUnavailable = errors.New("qoder check-in: activity unavailable") + +// CheckinStatus lists campaigns without claiming. A CLAIMABLE credit campaign +// means the account still has today's grant available; a CLAIMED grant inside +// its window means the current window was already collected. +func (b *Bridge) CheckinStatus(ctx context.Context) (providers.CheckinResult, error) { + doRequest, bearer, err := b.checkinDoer(ctx) + if err != nil { + if errors.Is(err, errCheckinUnavailable) { + return providers.CheckinResult{Status: "skipped", Message: "签到活动未开放", EarliestCheckin: "10:00"}, nil + } + return providers.CheckinResult{}, err + } + cosyFallback := "" + if b.Region != nil && b.Region.NeedsOpenAPIToken { + cosyFallback = b.CurrentSecurityOauth() + } + var items []campaign + for attempt, wait := range checkinListRetryWaits { + raw, _, listErr := doRequest(checkinCampaignsPath, http.MethodGet, false) + if listErr == nil && cosyFallback != "" && *bearer != cosyFallback && attempt == 0 { + *bearer = cosyFallback + cosyFallback = "" + raw, _, listErr = doRequest(checkinCampaignsPath, http.MethodGet, false) + } + if listErr != nil { + var statusErr interface{ StatusCode() int } + if errors.As(listErr, &statusErr) && statusErr.StatusCode() == http.StatusNotFound { + return providers.CheckinResult{Status: "skipped", Message: "签到活动未开放", EarliestCheckin: "10:00"}, nil + } + return providers.CheckinResult{}, listErr + } + items = campaignsFrom(raw) + // Status reads only need one non-empty credit list; the claim path + // retries a CLAIMED list because the grant may be stale, but a status + // read must not turn that into three upstream calls every sweep. + if len(creditCampaigns(items)) > 0 || attempt == len(checkinListRetryWaits)-1 { + break + } + timer := time.NewTimer(wait) + select { + case <-ctx.Done(): + timer.Stop() + return providers.CheckinResult{}, ctx.Err() + case <-timer.C: + } + } + benefits := creditCampaigns(items) + result := providers.CheckinResult{EarliestCheckin: qoderEarliestClock(benefits)} + if len(benefits) == 0 { + result.Status = "skipped" + result.Message = "上游未返回可领取积分的签到活动" + return result, nil + } + now := time.Now() + if len(claimableCampaigns(benefits)) > 0 { + result.Status = "pending" + result.Message = "上游显示今日可签到" + return result, nil + } + if grant, ok := claimedCreditGrant(benefits, now); ok { + if qoderSameCheckinDay(int64(grant.StartAt), now) { + result.Status = "already" + result.Message = "今日已签到" + return result, nil + } + // Before 10:00 the list still carries yesterday's window. A CLAIMED row + // there is not today's check-in; reporting it as "already" is the stale + // status bug the account card used to show. + result.Status = "skipped" + result.Message = "签到窗口尚未刷新(10:00 开启)" + return result, nil + } + result.Status = "skipped" + result.Message = "签到活动当前不可领取" + return result, nil +} + +func qoderSameCheckinDay(unixSeconds int64, now time.Time) bool { + location := time.FixedZone("UTC+8", 8*3600) + start := time.Unix(unixSeconds, 0).In(location) + current := now.In(location) + return start.Year() == current.Year() && start.YearDay() == current.YearDay() +} + +// qoderEarliestClock derives the daily window from the current credit +// campaigns. The activity window closes at 09:59 and the next one opens at +// 10:00, so the earliest allowed time is the clock of the latest endAt plus +// one minute (minute precision keeps 09:59:00 from formatting as 09:59). +// A long-running multi-day grant would otherwise report an arbitrary date, so +// only an end within the next 24h contributes; the known Qoder reset is 10:00. +func qoderEarliestClock(items []campaign) string { + now := time.Now() + latestEnd := int64(0) + for _, c := range items { + end := int64(c.EndAt) + if end <= now.Unix() || end > now.Add(24*time.Hour).Unix() { + continue + } + if end > latestEnd { + latestEnd = end + } + } + if latestEnd > 0 { + // Round to the next minute: an endAt of 09:59:00 (minute-precision + // server value) still belongs to the 09:59 window; +60s makes the + // formatted clock the 10:00 start instead of reporting 09:59. + if clock := providers.CheckinClockFromUnix(latestEnd + 60); clock != "" { + return clock + } + } + return "10:00" +} // Checkin runs the daily credit-claim using the bridge's in-process session. +// It is a method on Bridge so the per-account session, machine identity, and +// token-rotation state are all reused across catalog/quota/checkin. +func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) { + doRequest, bearer, err := b.checkinDoer(ctx) + if err != nil { + if errors.Is(err, errCheckinUnavailable) { + return providers.CheckinResult{Status: "skipped", Message: "签到活动未开放", EarliestCheckin: "10:00"}, nil + } + return providers.CheckinResult{}, err + } // 1) List campaigns. A successful response with nothing claimable is // retried: the endpoint intermittently omits the daily campaign, and @@ -204,9 +324,9 @@ func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) { for attempt, wait := range checkinListRetryWaits { listRaw, _, err := doRequest(checkinCampaignsPath, http.MethodGet, false) items = campaignListFrom(listRaw, err) - if err == nil && cosyFallback != "" && bearer != cosyFallback && + if err == nil && cosyFallback != "" && *bearer != cosyFallback && !hasClaimableCreditCampaign(items) && attempt == 0 { - bearer = cosyFallback + *bearer = cosyFallback cosyFallback = "" listRaw, _, err = doRequest(checkinCampaignsPath, http.MethodGet, false) items = campaignListFrom(listRaw, err) @@ -216,7 +336,7 @@ func (b *Bridge) Checkin(ctx context.Context) (providers.CheckinResult, error) { // rather than an error so the scheduler logs a clean "already/none". var statusErr interface{ StatusCode() int } if errors.As(err, &statusErr) && statusErr.StatusCode() == http.StatusNotFound { - return providers.CheckinResult{Status: "skipped", Message: "签到活动未开放"}, nil + return providers.CheckinResult{Status: "skipped", Message: "签到活动未开放", EarliestCheckin: "10:00"}, nil } return providers.CheckinResult{}, err } diff --git a/internal/providers/qoder/checkin_inprocess_test.go b/internal/providers/qoder/checkin_inprocess_test.go index 6ce8a925..25dbdf63 100644 --- a/internal/providers/qoder/checkin_inprocess_test.go +++ b/internal/providers/qoder/checkin_inprocess_test.go @@ -13,6 +13,96 @@ import ( "github.com/caigee-cmd/cli2api/internal/providers/qoder/qauth" ) +func TestBridgeCheckinStatusNeverClaims(t *testing.T) { + origHook := CheckinEndpointHook + origClient := checkinHTTPClient + t.Cleanup(func() { + CheckinEndpointHook = origHook + checkinHTTPClient = origClient + }) + now := time.Now() + windowStart := now.Add(-time.Second) + windowEnd := now.Add(time.Hour) + var claims atomic.Int32 + openapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/sash/api/v1/me/campaigns": + _ = json.NewEncoder(w).Encode(map[string]any{"campaigns": []map[string]any{{ + "campaignId": "today-credit", "actionType": "CLAIM_BENEFIT", "claimStatus": "CLAIMED", + "startAt": float64(windowStart.Unix()), "endAt": float64(windowEnd.Unix()), + "benefit": map[string]any{"kind": "CREDITS", "amount": 50.0}, + }}}) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/claim"): + claims.Add(1) + _ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"status": "CLAIMED"}}) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + })) + defer openapi.Close() + CheckinEndpointHook = func(*qauth.RegionConfig) *checkinRegion { + return &checkinRegion{base: openapi.URL, origin: "https://stub.test"} + } + checkinHTTPClient = openapi.Client() + b := newTestBridge(t, "fake-pat-secret-0123456789abcdef") + + result, err := b.CheckinStatus(context.Background()) + if err != nil { + t.Fatal(err) + } + if result.Status != "already" { + t.Fatalf("result=%+v", result) + } + if claims.Load() != 0 { + t.Fatalf("status read claimed %d times", claims.Load()) + } +} + +func TestQoderEarliestClockUsesNextWindow(t *testing.T) { + now := time.Now() + todayWindowStart := time.Date(now.Year(), now.Month(), now.Day(), 10, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)) + end := todayWindowStart.Add(24*time.Hour - time.Second) + result := qoderEarliestClock([]campaign{{EndAt: float64(end.Unix())}}) + if result != "10:00" { + t.Fatalf("earliest=%q want 10:00 (end=%s)", result, end.Format(time.RFC3339)) + } +} + +func TestBridgeCheckinStatusClaimableIsPending(t *testing.T) { + origHook := CheckinEndpointHook + origClient := checkinHTTPClient + t.Cleanup(func() { + CheckinEndpointHook = origHook + checkinHTTPClient = origClient + }) + var claims atomic.Int32 + openapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + claims.Add(1) + t.Fatalf("status read wrote upstream: %s %s", r.Method, r.URL.Path) + } + _ = json.NewEncoder(w).Encode(map[string]any{"campaigns": []map[string]any{{ + "campaignId": "today-credit", "actionType": "CLAIM_BENEFIT", "claimStatus": "CLAIMABLE", + "benefit": map[string]any{"kind": "CREDITS", "amount": 50.0}, + }}}) + })) + defer openapi.Close() + CheckinEndpointHook = func(*qauth.RegionConfig) *checkinRegion { + return &checkinRegion{base: openapi.URL, origin: "https://stub.test"} + } + checkinHTTPClient = openapi.Client() + b := newTestBridge(t, "fake-pat-secret-0123456789abcdef") + + result, err := b.CheckinStatus(context.Background()) + if err != nil { + t.Fatal(err) + } + if result.Status != "pending" || result.EarliestCheckin != "10:00" || claims.Load() != 0 { + t.Fatalf("result=%+v claims=%d", result, claims.Load()) + } +} + // TestBridgeCheckinHappyPath stubs the OpenAPI campaigns + claim endpoints // and verifies the full in-process Go path: EnsureFreshSession is a no-op // (session pre-populated), GET /me/campaigns lists, POST /claim claims, diff --git a/internal/providers/qwenwork/checkin.go b/internal/providers/qwenwork/checkin.go index 64c73f75..3af38400 100644 --- a/internal/providers/qwenwork/checkin.go +++ b/internal/providers/qwenwork/checkin.go @@ -11,8 +11,8 @@ import ( "github.com/caigee-cmd/cli2api/internal/providers" ) -// Daily reward paths. The desktop bundles (global 1.0.4, CN 1.4.0) call the -// growth-card endpoints below; production gateways may answer 404 while the +// Daily reward paths. The current desktop bundles (both editions 2.1.0) call +// the growth-card endpoints below; production gateways may answer 404 while the // campaign is closed, so Checkin falls back to the daily-grant probe. const ( pathDailyCheckinStatus = "/sash/api/v1/me/daily-check-in/status" @@ -101,7 +101,7 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check } ctx, cancel := context.WithTimeout(ctx, checkinTimeout) defer cancel() - result, campaignHandled, err := c.claimDailyCampaign(ctx, accountID, st, credential) + result, campaignHandled, err := c.readDailyCampaign(ctx, accountID, st, credential, true) if err != nil { return providers.CheckinResult{}, err } @@ -111,10 +111,28 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check return c.confirmDailyGrant(ctx, accountID, st, credential) } -// claimDailyCampaign runs the growth-card status/claim flow. campaignHandled is +// CheckinStatus reads the growth-card status and wallet without claiming. +func (c *Client) CheckinStatus(ctx context.Context, accountID string) (providers.CheckinResult, error) { + credential, st, err := c.resolvedCredential(ctx, accountID) + if err != nil { + return providers.CheckinResult{}, err + } + ctx, cancel := context.WithTimeout(ctx, checkinTimeout) + defer cancel() + result, campaignHandled, err := c.readDailyCampaign(ctx, accountID, st, credential, false) + if err != nil { + return providers.CheckinResult{}, err + } + if campaignHandled { + return result, nil + } + return c.confirmDailyGrant(ctx, accountID, st, credential) +} + +// readDailyCampaign runs the growth-card status/claim flow. campaignHandled is // false when the gateway does not route the check-in prefix, which is the // current production state; the caller then confirms the server-side grant. -func (c *Client) claimDailyCampaign(ctx context.Context, accountID string, st site, credential Credential) (providers.CheckinResult, bool, error) { +func (c *Client) readDailyCampaign(ctx context.Context, accountID string, st site, credential Credential, claim bool) (providers.CheckinResult, bool, error) { body, status, err := c.do(ctx, accountID, http.MethodGet, st.Gateway+pathDailyCheckinStatus, nil, func(h http.Header) { setGrowthCardHeaders(h, st, credential.AccessToken) }) if err != nil { @@ -137,27 +155,37 @@ func (c *Client) claimDailyCampaign(ctx context.Context, accountID string, st si return providers.CheckinResult{}, false, fmt.Errorf("qwenwork check-in: status code=%s", document.Code) } state := strings.ToUpper(strings.TrimSpace(document.Data.Status)) + earliest := providers.CheckinClockFromUnixMillis(nextClaimMillis(document)) + if earliest == "" { + earliest = "00:00" + } switch state { case dailyCheckinClaimable: + if !claim { + return providers.CheckinResult{Status: "pending", Message: "上游显示今日可签到", EarliestCheckin: earliest}, true, nil + } return c.claimCampaign(ctx, accountID, st, credential) case dailyCheckinClaimedToday: - result := providers.CheckinResult{Status: "already", Message: checkinAlreadyMessage(document)} + result := providers.CheckinResult{Status: "already", Message: checkinAlreadyMessage(document), EarliestCheckin: earliest} if document.Data.RewardCredits != nil { result.RewardCredits = *document.Data.RewardCredits } + if document.Data.CurrentStreakDays != nil { + result.Streak = *document.Data.CurrentStreakDays + } return result, true, nil case dailyCheckinDisabled: - return providers.CheckinResult{Status: "skipped", Message: "签到活动未开放"}, true, nil + return providers.CheckinResult{Status: "skipped", Message: "签到活动未开放", EarliestCheckin: earliest}, true, nil case dailyCheckinNotStarted: - return providers.CheckinResult{Status: "skipped", Message: "签到活动未开始"}, true, nil + return providers.CheckinResult{Status: "skipped", Message: "签到活动未开始", EarliestCheckin: earliest}, true, nil case dailyCheckinEnded: - return providers.CheckinResult{Status: "skipped", Message: "签到活动已结束"}, true, nil + return providers.CheckinResult{Status: "skipped", Message: "签到活动已结束", EarliestCheckin: earliest}, true, nil default: message := "签到活动状态未知" if state != "" { message = fmt.Sprintf("签到活动状态 %s", state) } - return providers.CheckinResult{Status: "skipped", Message: message}, true, nil + return providers.CheckinResult{Status: "skipped", Message: message, EarliestCheckin: earliest}, true, nil } } @@ -287,6 +315,13 @@ func (c *Client) dailyQuotaRemaining(ctx context.Context, accountID string, st s return *envelope.Data.Quota.Remaining, true } +func nextClaimMillis(document dailyCheckinDocument) int64 { + if document.Data.NextClaimAt != nil && *document.Data.NextClaimAt > 0 { + return *document.Data.NextClaimAt + } + return 0 +} + // checkinAlreadyMessage renders the streak detail the growth card shows next to // "今日已签到", keeping the persisted message short. func checkinAlreadyMessage(document dailyCheckinDocument) string { diff --git a/internal/providers/qwenwork/client.go b/internal/providers/qwenwork/client.go index c9a0f623..3b23f31c 100644 --- a/internal/providers/qwenwork/client.go +++ b/internal/providers/qwenwork/client.go @@ -861,14 +861,15 @@ func numberOrZero(value *float64) float64 { // Adapter returns the provider capability bundle for registration. func (c *Client) Adapter() providers.Adapter { return providers.Adapter{ - ID: "qwenwork", - Credential: credentialCodec{}, - Login: c, - Chat: c, - Models: c, - Classifier: classifier{}, - Prober: c, - Checkin: c, + ID: "qwenwork", + Credential: credentialCodec{}, + Login: c, + Chat: c, + Models: c, + Classifier: classifier{}, + Prober: c, + Checkin: c, + CheckinStatus: c, } } diff --git a/internal/providers/registry.go b/internal/providers/registry.go index 5c160f29..3f89ea6b 100644 --- a/internal/providers/registry.go +++ b/internal/providers/registry.go @@ -131,13 +131,12 @@ var WorkBuddy = ProviderDescriptor{ ID: "cn", Label: "CN", ChatBase: "https://copilot.tencent.com", BillingBase: "https://www.codebuddy.cn", AuthBase: "https://copilot.tencent.com", DefaultDomain: "codebuddy.cn", - Checkin: &CheckinPolicy{Timezone: "Local"}, + Checkin: &CheckinPolicy{Timezone: "Asia/Shanghai"}, }, { ID: "global", Label: "Global", ChatBase: "https://www.workbuddy.ai", BillingBase: "https://www.workbuddy.ai", AuthBase: "https://www.workbuddy.ai", DefaultDomain: "workbuddy.ai", - Checkin: &CheckinPolicy{Timezone: "Local"}, }, }, DefaultRegion: "cn", diff --git a/internal/providers/registry_test.go b/internal/providers/registry_test.go index c5ea2695..c98a7a70 100644 --- a/internal/providers/registry_test.go +++ b/internal/providers/registry_test.go @@ -1,6 +1,25 @@ package providers -import "testing" +import ( + "testing" + "time" +) + +func TestCheckinPoliciesUseProviderServerClock(t *testing.T) { + for _, descriptor := range List() { + for _, region := range descriptor.Regions { + if region.Checkin == nil { + continue + } + if region.Checkin.Timezone == "" || region.Checkin.Timezone == "Local" { + t.Fatalf("%s/%s check-in must use an explicit server timezone, got %q", descriptor.ID, region.ID, region.Checkin.Timezone) + } + if _, err := time.LoadLocation(region.Checkin.Timezone); err != nil { + t.Fatalf("%s/%s invalid server timezone %q: %v", descriptor.ID, region.ID, region.Checkin.Timezone, err) + } + } + } +} func TestListIncludesEveryRegisteredDescriptor(t *testing.T) { listed := List() diff --git a/internal/providers/trae/checkin.go b/internal/providers/trae/checkin.go index aced9e25..58b9bc3e 100644 --- a/internal/providers/trae/checkin.go +++ b/internal/providers/trae/checkin.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "strings" + "time" "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/providers" @@ -40,6 +41,8 @@ func (client *Client) Checkin(ctx context.Context, accountID string) (providers. if err != nil { var already AlreadyCheckedInError if errors.As(err, &already) { + // checkin_credits/status is scoped to the provider's current day; an + // "already" business answer is today's, not yesterday's. return providers.CheckinResult{Status: "already", Message: already.Msg}, nil } return providers.CheckinResult{}, err @@ -57,6 +60,11 @@ func (client *Client) Checkin(ctx context.Context, accountID string) (providers. if err := client.checkinClaim(ctx, accountID, credential); err != nil { var already AlreadyCheckedInError if errors.As(err, &already) { + // The claim endpoint may replay yesterday's grant during the brief + // post-midnight window; do not record that as today's success. + if providers.CheckinClaimProvisional(time.Now()) { + return providers.CheckinResult{Status: "unknown", Message: "上游日界尚未确认,稍后复核"}, nil + } return providers.CheckinResult{Status: "already", Message: already.Msg}, nil } return providers.CheckinResult{}, err @@ -78,6 +86,43 @@ func (client *Client) Checkin(ctx context.Context, accountID string) (providers. }, nil } +// CheckinStatus reads the upstream status without attempting a claim. +func (client *Client) CheckinStatus(ctx context.Context, accountID string) (providers.CheckinResult, error) { + credential, err := client.credential(ctx, accountID) + if err != nil { + return providers.CheckinResult{}, err + } + st, err := client.checkinStatus(ctx, accountID, credential) + if err != nil { + var already AlreadyCheckedInError + if errors.As(err, &already) { + return providers.CheckinResult{ + Status: "already", + Message: already.Msg, + // Trae's status endpoint does not expose a window start; the + // desktop daily panel rolls over at 00:00 local. + EarliestCheckin: "00:00", + }, nil + } + return providers.CheckinResult{}, err + } + result := providers.CheckinResult{EarliestCheckin: "00:00"} + if st.checkedIn { + result.Status = "already" + result.Message = "今日已签到" + result.RewardCredits = float64(st.credits + st.extraCredits) + return result, nil + } + if !st.enable { + result.Status = "skipped" + result.Message = "签到活动未开放" + return result, nil + } + result.Status = "pending" + result.Message = "上游显示今日未签到" + return result, nil +} + type checkinState struct { checkedIn bool credits int64 @@ -89,7 +134,7 @@ type checkinState struct { // "already checked in" yields AlreadyCheckedInError so the caller can return // Status="already" without treating it as a failure. func (client *Client) checkinStatus(ctx context.Context, accountID string, credential Credential) (checkinState, error) { - body, err := client.CheckinStatus(ctx, accountID, credential) + body, err := client.checkinStatusBody(ctx, accountID, credential) if err != nil { return checkinState{}, err } diff --git a/internal/providers/trae/checkin_test.go b/internal/providers/trae/checkin_test.go index 1a6b9051..463531fd 100644 --- a/internal/providers/trae/checkin_test.go +++ b/internal/providers/trae/checkin_test.go @@ -172,6 +172,49 @@ func TestCheckinAuthDead(t *testing.T) { } } +func TestCheckinStatusIsReadOnly(t *testing.T) { + var calls []string + client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != pathCheckinStatus { + t.Fatalf("read-only status hit %s %s", r.Method, r.URL.Path) + } + calls = append(calls, r.URL.Path) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"checked_in": true, "credits": 120}) + })) + seedCheckinCredential(t, store) + + result, err := client.CheckinStatus(context.Background(), "acc1") + if err != nil { + t.Fatal(err) + } + if result.Status != "already" || result.RewardCredits != 120 || result.EarliestCheckin != "00:00" { + t.Fatalf("result=%+v", result) + } + if len(calls) != 1 { + t.Fatalf("status must not claim: %v", calls) + } +} + +func TestCheckinStatusPendingAndAdapterRegistration(t *testing.T) { + client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"checked_in": false, "enable": true}) + })) + seedCheckinCredential(t, store) + + result, err := client.CheckinStatus(context.Background(), "acc1") + if err != nil { + t.Fatal(err) + } + if result.Status != "pending" || result.EarliestCheckin != "00:00" { + t.Fatalf("result=%+v", result) + } + if client.Adapter().CheckinStatus == nil || !client.Adapter().Supports("checkin_status") { + t.Fatal("status reader not registered") + } +} + func TestCheckinRegisteredOnAdapter(t *testing.T) { client, _ := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) adapter := client.Adapter() diff --git a/internal/providers/trae/client.go b/internal/providers/trae/client.go index 428530ba..ec222c19 100644 --- a/internal/providers/trae/client.go +++ b/internal/providers/trae/client.go @@ -1566,7 +1566,7 @@ func int64FromAny(value any) int64 { } } -func (c *Client) CheckinStatus(ctx context.Context, accountID string, credential Credential) ([]byte, error) { +func (c *Client) checkinStatusBody(ctx context.Context, accountID string, credential Credential) ([]byte, error) { body, status, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinStatus, checkinReqSourceBody(credential), func(h http.Header) { SetUgHeaders(h, credential) }) if err != nil { @@ -1600,15 +1600,16 @@ func checkinReqSourceBody(credential Credential) []byte { func (c *Client) Adapter() providers.Adapter { return providers.Adapter{ - ID: "trae", - Credential: credentialCodec{}, - Login: c, - Chat: c, - Models: c, - Classifier: classifier{}, - ImportExport: importer{}, - Prober: c, - Checkin: c, + ID: "trae", + Credential: credentialCodec{}, + Login: c, + Chat: c, + Models: c, + Classifier: classifier{}, + ImportExport: importer{}, + Prober: c, + Checkin: c, + CheckinStatus: c, } } diff --git a/internal/providers/workbuddy/checkin.go b/internal/providers/workbuddy/checkin.go index 3df63bd8..b41cea1d 100644 --- a/internal/providers/workbuddy/checkin.go +++ b/internal/providers/workbuddy/checkin.go @@ -2,15 +2,137 @@ package workbuddy import ( "context" + "encoding/json" "errors" + "net/http" + "time" "github.com/caigee-cmd/cli2api/internal/providers" ) +const pathCheckinStatus = "/v2/billing/meter/checkin-activity-status" + +// checkinActivityStatus mirrors the official desktop flow: query the campaign +// switch before claiming, so an inactive campaign and a same-day repeat never +// produce a false failure. A failed status probe falls through to the claim, +// matching the desktop's "status unavailable, still check in" behaviour. +type checkinActivityStatus struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data struct { + Active *bool `json:"active"` + TodayCheckedIn *bool `json:"today_checked_in"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time"` + CurrentStreak *int `json:"current_streak"` + Points *float64 `json:"points"` + } `json:"data"` +} + +func (client *Client) checkinActivity(ctx context.Context, accountID string, credential Credential) (checkinActivityStatus, bool) { + body, status, err := client.do(ctx, accountID, http.MethodPost, + credential.BillingBase()+pathCheckinStatus, []byte("{}"), + func(h http.Header) { SetBillingHeaders(h, credential) }) + if err != nil || status >= 300 { + return checkinActivityStatus{}, false + } + var envelope checkinActivityStatus + if json.Unmarshal(body, &envelope) != nil || envelope.Code != 0 { + return checkinActivityStatus{}, false + } + if envelope.Data.Active == nil && envelope.Data.TodayCheckedIn == nil { + return checkinActivityStatus{}, false + } + // A response that only carries today_checked_in still describes a live + // campaign; treat a missing active flag as active. + if envelope.Data.Active == nil { + envelope.Data.Active = new(bool) + *envelope.Data.Active = true + } + if envelope.Data.TodayCheckedIn == nil { + envelope.Data.TodayCheckedIn = new(bool) + } + return envelope, true +} + +func (client *Client) checkinStatus(ctx context.Context, accountID string, credential Credential) (active, checked, known bool) { + activity, known := client.checkinActivity(ctx, accountID, credential) + if !known { + return false, false, false + } + return *activity.Data.Active, *activity.Data.TodayCheckedIn, true +} + +// CheckinStatus reads the campaign switch and today's flag without claiming. +func (client *Client) CheckinStatus(ctx context.Context, accountID string) (providers.CheckinResult, error) { + credential, err := client.resolvedCredential(ctx, accountID) + if err != nil { + return providers.CheckinResult{}, err + } + if credential.IsGlobal() { + return providers.CheckinResult{Status: "skipped", Message: "WorkBuddy Global has no daily check-in"}, nil + } + activity, known := client.checkinActivity(ctx, accountID, credential) + if !known { + return providers.CheckinResult{Status: "unknown", Message: "上游签到状态不可用"}, nil + } + earliest := providers.CheckinClockFromText(activity.Data.StartTime) + result := providers.CheckinResult{EarliestCheckin: earliest} + if activity.Data.CurrentStreak != nil { + result.Streak = *activity.Data.CurrentStreak + } + if activity.Data.Points != nil { + result.RewardCredits = *activity.Data.Points + } + if !*activity.Data.Active { + result.Status = "skipped" + result.Message = "签到活动未开放" + return result, nil + } + if *activity.Data.TodayCheckedIn { + // today_checked_in is computed by the provider for its own day, so it is + // trusted directly. Re-issuing the claim merely to prove the date would + // turn a valid answer into a false "unknown" every morning. + result.Status = "already" + result.Message = "今日已签到" + if result.Streak > 0 { + result.Message = "今日已签到" + } + return result, nil + } + result.Status = "pending" + result.Message = "上游显示今日未签到" + return result, nil +} + func (client *Client) Checkin(ctx context.Context, accountID string) (providers.CheckinResult, error) { + credential, err := client.resolvedCredential(ctx, accountID) + if err != nil { + return providers.CheckinResult{}, err + } + // The international desktop disables its check-in feature; there is no + // endpoint to emulate. Report a clean skip instead of a red failure. + if credential.IsGlobal() { + return providers.CheckinResult{Status: "skipped", Message: "WorkBuddy Global has no daily check-in"}, nil + } + active, checked, known := client.checkinStatus(ctx, accountID, credential) + if known { + if !active { + return providers.CheckinResult{Status: "skipped", Message: "check-in activity is not active"}, nil + } + // today_checked_in is the provider's own day flag; trust it and skip the + // extra claim. A claim endpoint "already" answer at 01:00 is still + // guarded separately because the campaign can replay yesterday's reward. + if checked { + return providers.CheckinResult{Status: "already", Message: "今日已签到"}, nil + } + } message, err := client.DailyCheckin(ctx, accountID) var already AlreadyCheckedInError if errors.As(err, &already) { + if providers.CheckinClaimProvisional(time.Now()) { + return providers.CheckinResult{Status: "unknown", Message: "上游日界尚未确认,稍后复核"}, nil + } return providers.CheckinResult{Status: "already", Message: message}, nil } if err != nil { diff --git a/internal/providers/workbuddy/checkin_status_test.go b/internal/providers/workbuddy/checkin_status_test.go new file mode 100644 index 00000000..d9c7a7db --- /dev/null +++ b/internal/providers/workbuddy/checkin_status_test.go @@ -0,0 +1,166 @@ +package workbuddy + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "sync/atomic" + "testing" +) + +func TestCheckinStatusReadsUpstreamWithoutClaiming(t *testing.T) { + client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != pathCheckinStatus { + t.Fatalf("status must never claim: %s", r.URL.Path) + } + if r.Method != http.MethodPost { + t.Fatalf("method=%s", r.Method) + } + raw, _ := io.ReadAll(r.Body) + if strings.TrimSpace(string(raw)) != "{}" { + t.Fatalf("body=%q", raw) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "", "data": map[string]any{ + "active": true, "today_checked_in": true, "start_time": "2026-09-30 00:00:00", + "end_time": "2026-12-31 23:59:59", "current_streak": 5, "points": 12.5, + }}) + })) + payload, _ := Credential{AccessToken: "at", RefreshToken: "rt", ExpiresAt: 4102444800, Domain: DomainCN, UID: "u1"}.Encode() + _ = store.SaveCredentialPayload(context.Background(), "acc1", CredentialFormat, payload) + + result, err := client.CheckinStatus(context.Background(), "acc1") + if err != nil { + t.Fatal(err) + } + if result.Status != "already" || result.EarliestCheckin != "00:00" || result.Streak != 5 || result.RewardCredits != 12.5 { + t.Fatalf("result=%+v", result) + } +} + +func TestCheckinStatusPendingWhenTodayMissing(t *testing.T) { + client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "active": true, "today_checked_in": false, "start_time": "2026-09-30 00:00:00", "current_streak": 4, + }}) + })) + payload, _ := Credential{AccessToken: "at", RefreshToken: "rt", ExpiresAt: 4102444800, Domain: DomainCN, UID: "u1"}.Encode() + _ = store.SaveCredentialPayload(context.Background(), "acc1", CredentialFormat, payload) + result, err := client.CheckinStatus(context.Background(), "acc1") + if err != nil { + t.Fatal(err) + } + if result.Status != "pending" || result.EarliestCheckin != "00:00" || result.Streak != 4 { + t.Fatalf("result=%+v", result) + } +} + +func saveCheckinCredential(t *testing.T, store *memStore, domain string) { + t.Helper() + payload, _ := json.Marshal(Credential{ + AccessToken: "at", RefreshToken: "rt", ExpiresAt: 4102444800, Domain: domain, UID: "u1", + }) + if err := store.SaveCredentialPayload(context.Background(), "acc1", CredentialFormat, payload); err != nil { + t.Fatal(err) + } +} + +func TestCheckinQueriesActivityStatusBeforeClaim(t *testing.T) { + var statusCalls, claimCalls atomic.Int32 + client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case pathCheckinStatus: + statusCalls.Add(1) + if r.Method != http.MethodPost { + t.Fatalf("status method=%s", r.Method) + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "code": 0, + "data": map[string]any{"active": true, "today_checked_in": false}, + }) + case pathDailyCheckin: + claimCalls.Add(1) + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "签到成功"}) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + saveCheckinCredential(t, store, DomainCN) + result, err := client.Checkin(context.Background(), "acc1") + if err != nil { + t.Fatal(err) + } + if result.Status != "success" || result.Message != "签到成功" { + t.Fatalf("result=%+v", result) + } + if statusCalls.Load() != 1 || claimCalls.Load() != 1 { + t.Fatalf("status=%d claim=%d", statusCalls.Load(), claimCalls.Load()) + } +} + +func TestCheckinInactiveActivitySkipsWithoutClaim(t *testing.T) { + var claimCalls atomic.Int32 + client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == pathCheckinStatus { + _ = json.NewEncoder(w).Encode(map[string]any{ + "code": 0, + "data": map[string]any{"active": false, "today_checked_in": false}, + }) + return + } + if r.URL.Path == pathDailyCheckin { + claimCalls.Add(1) + } + })) + saveCheckinCredential(t, store, DomainCN) + result, err := client.Checkin(context.Background(), "acc1") + if err != nil { + t.Fatal(err) + } + if result.Status != "skipped" || claimCalls.Load() != 0 { + t.Fatalf("result=%+v claim=%d", result, claimCalls.Load()) + } +} + +func TestCheckinStatusAlreadyCheckedInSkipsClaim(t *testing.T) { + var claimCalls atomic.Int32 + client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == pathCheckinStatus { + _ = json.NewEncoder(w).Encode(map[string]any{ + "code": 0, + "data": map[string]any{"active": true, "today_checked_in": true}, + }) + return + } + if r.URL.Path == pathDailyCheckin { + claimCalls.Add(1) + } + })) + saveCheckinCredential(t, store, DomainCN) + result, err := client.Checkin(context.Background(), "acc1") + if err != nil { + t.Fatal(err) + } + if result.Status != "already" || claimCalls.Load() != 0 { + t.Fatalf("result=%+v claim=%d", result, claimCalls.Load()) + } +} + +func TestCheckinGlobalSkipsBeforeAnyRequest(t *testing.T) { + var calls atomic.Int32 + client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + })) + saveCheckinCredential(t, store, DomainGlobal) + store.region = "global" + result, err := client.Checkin(context.Background(), "acc1") + if err != nil { + t.Fatal(err) + } + if result.Status != "skipped" || calls.Load() != 0 { + t.Fatalf("result=%+v calls=%d", result, calls.Load()) + } +} diff --git a/internal/runtime/checkin_integration_test.go b/internal/runtime/checkin_integration_test.go index 990633fd..122f2f85 100644 --- a/internal/runtime/checkin_integration_test.go +++ b/internal/runtime/checkin_integration_test.go @@ -57,6 +57,46 @@ func TestCheckinCapabilityRecordsAndDeduplicates(t *testing.T) { } } +func TestCheckinAllRunsWithBoundedConcurrency(t *testing.T) { + var active atomic.Int32 + var maxActive atomic.Int32 + manager, _ := newCheckinManager(t, checkinFunc(func(context.Context, string) (providers.CheckinResult, error) { + now := active.Add(1) + defer active.Add(-1) + for { + previous := maxActive.Load() + if now <= previous || maxActive.CompareAndSwap(previous, now) { + break + } + } + time.Sleep(40 * time.Millisecond) + return providers.CheckinResult{Status: "success", Message: "claimed"}, nil + })) + enabled := true + for i := 0; i < 8; i++ { + if _, err := manager.store.Create(context.Background(), accounts.CreateAccount{ + Name: "batch", Provider: "qoder", Region: "cn", Enabled: true, AutoCheckin: &enabled, + }); err != nil { + t.Fatal(err) + } + } + results, err := manager.CheckinAll(context.Background(), false, false) + if err != nil { + t.Fatal(err) + } + if len(results) != 9 { + t.Fatalf("results=%d want 9", len(results)) + } + for _, result := range results { + if result.Status != "success" { + t.Fatalf("result=%+v", result) + } + } + if got := maxActive.Load(); got < 2 || got > manualCheckinConcurrency { + t.Fatalf("max concurrency=%d want 2..%d", got, manualCheckinConcurrency) + } +} + func TestCheckinConcurrentManualAndScheduledDoNotOverlap(t *testing.T) { entered := make(chan struct{}) release := make(chan struct{}) diff --git a/internal/runtime/checkin_status_test.go b/internal/runtime/checkin_status_test.go new file mode 100644 index 00000000..c20f3917 --- /dev/null +++ b/internal/runtime/checkin_status_test.go @@ -0,0 +1,185 @@ +package runtime + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + sqlstore "github.com/caigee-cmd/cli2api/internal/store" +) + +type checkinStatusFunc func(context.Context, string) (providers.CheckinResult, error) + +func (read checkinStatusFunc) CheckinStatus(ctx context.Context, accountID string) (providers.CheckinResult, error) { + return read(ctx, accountID) +} + +func newStatusManager(t *testing.T, read providers.AccountCheckinStatusReader) (*Manager, Account) { + t.Helper() + store, err := sqlstore.OpenStore(filepath.Join(t.TempDir(), "checkin-status.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { store.Close() }) + manager := NewManager(ManagerConfig{DataDir: t.TempDir()}, store, nil) + t.Cleanup(func() { manager.Close() }) + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ + ID: "qoder", + Checkin: checkinFunc(func(context.Context, string) (providers.CheckinResult, error) { + return providers.CheckinResult{Status: "skipped"}, nil + }), + CheckinStatus: read, + }) + manager.SetProviders(registry) + enabled := true + account, err := store.Create(context.Background(), accounts.CreateAccount{Name: "CN", Provider: "qoder", Region: "cn", Enabled: true, AutoCheckin: &enabled}) + if err != nil { + t.Fatal(err) + } + return manager, account +} + +func TestSyncCheckinStatusPersistsUpstreamAlreadyAndAutoTime(t *testing.T) { + manager, account := newStatusManager(t, checkinStatusFunc(func(context.Context, string) (providers.CheckinResult, error) { + return providers.CheckinResult{Status: "already", Message: "今日已签到", EarliestCheckin: "10:00"}, nil + })) + manager.SyncCheckinStatuses(context.Background()) + updated, err := manager.store.Get(context.Background(), account.ID) + if err != nil { + t.Fatal(err) + } + if updated.LastCheckinStatus != "already" || updated.LastCheckinSource != "upstream" || + updated.LastCheckinSyncedAt == "" || updated.CheckinAutoTime != "11:00" || + updated.LastCheckinAt == "" { + t.Fatalf("synced=%+v", updated) + } + if len(mustCheckinRecords(t, manager, account.ID)) != 0 { + t.Fatal("status sync must not add a check-in history record") + } +} + +func TestSyncCheckinStatusPendingKeepsLastAttemptAndDerivesOneHour(t *testing.T) { + manager, account := newStatusManager(t, checkinStatusFunc(func(context.Context, string) (providers.CheckinResult, error) { + return providers.CheckinResult{Status: "pending", Message: "上游显示今日未签到", EarliestCheckin: "00:00"}, nil + })) + if err := manager.store.RecordCheckin(context.Background(), account.ID, "success", "claimed", time.Now().UTC()); err != nil { + t.Fatal(err) + } + manager.SyncCheckinStatuses(context.Background()) + updated, err := manager.store.Get(context.Background(), account.ID) + if err != nil { + t.Fatal(err) + } + if updated.LastCheckinStatus != "success" { + // Within the post-check-in grace window the fresh local success stands. + t.Fatalf("grace clobbered=%+v", updated) + } + if updated.CheckinAutoTime != "01:00" { + t.Fatalf("auto time=%q want 01:00", updated.CheckinAutoTime) + } + if updated.LastCheckinSource != "local" { + t.Fatalf("grace must keep the local source, got %q", updated.LastCheckinSource) + } +} + +func TestSyncCheckinStatusPendingWinsAfterGrace(t *testing.T) { + manager, account := newStatusManager(t, checkinStatusFunc(func(context.Context, string) (providers.CheckinResult, error) { + return providers.CheckinResult{Status: "pending", Message: "上游显示今日未签到", EarliestCheckin: "00:00"}, nil + })) + old := time.Now().UTC().Add(-time.Hour) + if err := manager.store.RecordCheckin(context.Background(), account.ID, "success", "claimed", old); err != nil { + t.Fatal(err) + } + manager.SyncCheckinStatuses(context.Background()) + updated, err := manager.store.Get(context.Background(), account.ID) + if err != nil { + t.Fatal(err) + } + if updated.LastCheckinStatus != "pending" || updated.LastCheckinSource != "upstream" || updated.CheckinAutoTime != "01:00" { + t.Fatalf("pending=%+v", updated) + } + if updated.LastCheckinAt == "" { + t.Fatal("pending sync erased the last real attempt timestamp") + } +} + +func TestSyncCheckinStatusErrorMarksUnknownWithoutFakeCheckin(t *testing.T) { + manager, account := newStatusManager(t, checkinStatusFunc(func(context.Context, string) (providers.CheckinResult, error) { + return providers.CheckinResult{}, errors.New("upstream unavailable") + })) + manager.SyncCheckinStatuses(context.Background()) + updated, err := manager.store.Get(context.Background(), account.ID) + if err != nil { + t.Fatal(err) + } + if updated.LastCheckinStatus != "unknown" || updated.LastCheckinSource != "upstream" || + updated.LastCheckinAt != "" || updated.CheckinAutoTime != "11:00" { + t.Fatalf("unknown=%+v", updated) + } +} + +func TestSyncCheckinStatusDoesNotOverwriteCheckinFinishedDuringProbe(t *testing.T) { + started := make(chan struct{}) + release := make(chan struct{}) + manager, account := newStatusManager(t, checkinStatusFunc(func(context.Context, string) (providers.CheckinResult, error) { + close(started) + <-release + return providers.CheckinResult{Status: "pending", Message: "上游显示今日未签到", EarliestCheckin: "10:00"}, nil + })) + done := make(chan struct{}) + go func() { + manager.SyncCheckinStatuses(context.Background()) + close(done) + }() + <-started + // The probe is still in flight when a real check-in lands. + if err := manager.store.RecordCheckin(context.Background(), account.ID, "success", "claimed while probing", time.Now().UTC()); err != nil { + t.Fatal(err) + } + close(release) + <-done + + updated, err := manager.store.Get(context.Background(), account.ID) + if err != nil { + t.Fatal(err) + } + if updated.LastCheckinStatus != "success" || updated.LastCheckinSource != "local" { + t.Fatalf("a stale probe overwrote the check-in: %+v", updated) + } + if updated.LastCheckinMsg != "claimed while probing" { + t.Fatalf("message=%q", updated.LastCheckinMsg) + } +} + +func TestSyncCheckinStatusUnknownKeepsRealLocalSuccess(t *testing.T) { + manager, account := newStatusManager(t, checkinStatusFunc(func(context.Context, string) (providers.CheckinResult, error) { + // A provisional rollover answer: the provider cannot yet confirm today. + return providers.CheckinResult{Status: "unknown", Message: "上游日界尚未确认,稍后复核", EarliestCheckin: "00:00"}, nil + })) + old := time.Now().UTC().Add(-2 * time.Hour) + if err := manager.store.RecordCheckin(context.Background(), account.ID, "success", "claimed earlier", old); err != nil { + t.Fatal(err) + } + manager.SyncCheckinStatuses(context.Background()) + updated, err := manager.store.Get(context.Background(), account.ID) + if err != nil { + t.Fatal(err) + } + if updated.LastCheckinStatus != "success" || updated.LastCheckinSource != "local" { + t.Fatalf("unknown must not erase a successful local day: %+v", updated) + } +} + +func mustCheckinRecords(t *testing.T, manager *Manager, id string) []accounts.CheckinRecord { + t.Helper() + records, err := manager.store.ListCheckinRecords(context.Background(), id, 20) + if err != nil { + t.Fatal(err) + } + return records +} diff --git a/internal/runtime/maintenance_test.go b/internal/runtime/maintenance_test.go index 6f703a12..23c7e796 100644 --- a/internal/runtime/maintenance_test.go +++ b/internal/runtime/maintenance_test.go @@ -40,6 +40,31 @@ func TestCheckinSchedule(t *testing.T) { } } +func TestCheckinScheduleRetriesAtRolloverWindow(t *testing.T) { + location := time.FixedZone("CST", 8*3600) + base := time.Date(2026, 11, 24, 1, 10, 0, 0, location) + account := Account{ + ID: "account", + Enabled: true, + AutoCheckin: true, + LastCheckinAt: base.Format(time.RFC3339Nano), + LastCheckinStatus: "unknown", + } + if checkinDue(account, "01:00", base.Add(20*time.Minute)) { + t.Fatal("02:05 retry must not run before its window") + } + if !checkinDue(account, "01:00", base.Add(time.Hour)) { // 02:10 + t.Fatal("unknown 01:00 result must retry at 02:05") + } + account.LastCheckinAt = base.Add(time.Hour).Format(time.RFC3339Nano) + if checkinDue(account, "01:00", base.Add(2*time.Hour)) { + t.Fatal("passed 02:05 window must not repeat") + } + if !checkinDue(account, "01:00", base.Add(11*time.Hour)) { // 12:10 + t.Fatal("midday safety retry must still run") + } +} + func TestCheckinScheduleSameTimeAndDisabled(t *testing.T) { now := time.Date(2026, 9, 19, 21, 30, 0, 0, time.UTC) account := Account{ID: "account", Enabled: true, AutoCheckin: true, LastCheckinAt: now.Add(-10 * time.Minute).Format(time.RFC3339), LastCheckinStatus: "error"} diff --git a/internal/runtime/manager.go b/internal/runtime/manager.go index e32ac7fc..04fa017c 100644 --- a/internal/runtime/manager.go +++ b/internal/runtime/manager.go @@ -65,20 +65,21 @@ type WorkBuddyMaintainer interface { } type Manager struct { - config ManagerConfig - store AccountStore - poolState PoolStateStore - starter ProcessStarter - pool *Pool - providers *providers.Registry - workbuddy WorkBuddyMaintainer - checkinRunning map[string]bool - mu sync.Mutex - processes map[string]ManagedProcess - restarts map[string]int - restartBackoff map[string]int - recovering map[string]bool - recoverPending map[string]string + config ManagerConfig + store AccountStore + poolState PoolStateStore + starter ProcessStarter + pool *Pool + providers *providers.Registry + workbuddy WorkBuddyMaintainer + checkinRunning map[string]bool + checkinStatusRunning bool + mu sync.Mutex + processes map[string]ManagedProcess + restarts map[string]int + restartBackoff map[string]int + recovering map[string]bool + recoverPending map[string]string // recoverUnwindHook runs (tests only) as a recovery goroutine starts unwinding. recoverUnwindHook func(id string) recoverDone sync.WaitGroup diff --git a/internal/runtime/manager_maintenance.go b/internal/runtime/manager_maintenance.go index 50aedd60..7407e097 100644 --- a/internal/runtime/manager_maintenance.go +++ b/internal/runtime/manager_maintenance.go @@ -7,6 +7,7 @@ import ( "hash/fnv" "log" "strings" + "sync" "time" _ "time/tzdata" @@ -22,6 +23,9 @@ func (manager *Manager) CheckinAccount(ctx context.Context, accountID string) (A // CheckinAll runs a manual all-account pass on the server. It selects from the // full store instead of the browser's current page/filter, honors the system // "check in disabled accounts" setting, and reports every account outcome. +// Manual passes use bounded concurrency instead of the scheduled loop's +// inter-account gap: waiting on the UI for 13 sequential network check-ins is +// unacceptable, while four in flight keeps upstream bursts modest. func (manager *Manager) CheckinAll(ctx context.Context, force, includeDisabled bool) ([]accounts.CheckinAllResult, error) { if manager == nil { return nil, fmt.Errorf("account manager unavailable") @@ -30,12 +34,8 @@ func (manager *Manager) CheckinAll(ctx context.Context, force, includeDisabled b if err != nil { return nil, err } - results := make([]accounts.CheckinAllResult, 0, len(items)) - processed := 0 + targets := make([]accounts.Account, 0, len(items)) for _, item := range items { - if ctx.Err() != nil { - return results, ctx.Err() - } if !includeDisabled && !item.Enabled { continue } @@ -45,29 +45,52 @@ func (manager *Manager) CheckinAll(ctx context.Context, force, includeDisabled b if adapter, registered := manager.providers.Get(item.Provider); !registered || adapter.Checkin == nil { continue } - if processed > 0 && !sleepMaintenanceGap(ctx, item.ID, maintenanceAccountGap) { - return results, ctx.Err() - } - updated, checkErr := manager.checkinAccount(ctx, item.ID, includeDisabled, force) - result := accounts.CheckinAllResult{ - AccountID: item.ID, - Provider: item.Provider, - Region: item.ProviderRegion, - Status: updated.LastCheckinStatus, - Message: updated.LastCheckinMsg, - } - if result.Status == "" { - result.Status = "success" + targets = append(targets, item) + } + results := make([]accounts.CheckinAllResult, len(targets)) + var wg sync.WaitGroup + sem := make(chan struct{}, manualCheckinConcurrency) + started := 0 +loop: + for i, item := range targets { + select { + case sem <- struct{}{}: + case <-ctx.Done(): + break loop } - if checkErr != nil { - result.Status = "error" - if result.Message == "" { - result.Message = checkErr.Error() + started = i + 1 + wg.Add(1) + go func(index int, account accounts.Account) { + defer wg.Done() + defer func() { <-sem }() + updated, checkErr := manager.checkinAccount(ctx, account.ID, includeDisabled, force) + result := accounts.CheckinAllResult{ + AccountID: account.ID, + Provider: account.Provider, + Region: account.ProviderRegion, + Status: updated.LastCheckinStatus, + Message: updated.LastCheckinMsg, } - } - results = append(results, result) - processed++ + if result.Status == "" { + result.Status = "success" + } + if checkErr != nil { + result.Status = "error" + if result.Message == "" { + result.Message = checkErr.Error() + } + } + results[index] = result + }(i, item) + } + wg.Wait() + if ctx.Err() != nil { + return results[:started], ctx.Err() } + // Verify the claims against upstream after the pass; this refreshes the + // true today flag and the derived auto schedule without delaying the UI. + syncCtx := context.WithoutCancel(ctx) + go manager.SyncCheckinStatuses(syncCtx) return results, nil } @@ -146,6 +169,178 @@ func (manager *Manager) checkinAccount(ctx context.Context, accountID string, al return updated, errors.Join(checkErr, err) } +const ( + // checkinStatusInterval is how often the console refreshes the true + // upstream check-in state. Verification is read-only and bounded; it never + // claims a reward. + checkinStatusInterval = 15 * time.Minute + checkinStatusTimeout = 75 * time.Second + checkinStatusConcurrency = 4 + // A real check-in can take a few seconds to become visible upstream. Do not + // downgrade a local success inside this grace window. + checkinStatusGrace = 15 * time.Minute +) + +// SyncCheckinStatuses refreshes every check-in-capable account from upstream. +// It is safe to call concurrently; only one pass runs at a time. +func (manager *Manager) SyncCheckinStatuses(ctx context.Context) { + if manager == nil { + return + } + manager.mu.Lock() + if manager.checkinStatusRunning { + manager.mu.Unlock() + return + } + manager.checkinStatusRunning = true + manager.mu.Unlock() + defer func() { + manager.mu.Lock() + manager.checkinStatusRunning = false + manager.mu.Unlock() + }() + items, err := manager.store.List(ctx) + if err != nil { + log.Printf("checkin status list: %v", err) + return + } + candidates := make([]Account, 0, len(items)) + for _, account := range items { + policy, supported := providers.CheckinFor(account.Provider, account.ProviderRegion) + adapter, registered := manager.providers.Get(account.Provider) + if !supported || !registered || adapter.CheckinStatus == nil { + continue + } + if policy.Timezone == "" { + continue + } + candidates = append(candidates, account) + } + var wg sync.WaitGroup + sem := make(chan struct{}, checkinStatusConcurrency) + for _, account := range candidates { + select { + case sem <- struct{}{}: + case <-ctx.Done(): + wg.Wait() + return + } + wg.Add(1) + go func(account Account) { + defer wg.Done() + defer func() { <-sem }() + manager.syncCheckinStatus(ctx, account) + }(account) + } + wg.Wait() +} + +func (manager *Manager) syncCheckinStatus(ctx context.Context, account Account) { + manager.mu.Lock() + busy := manager.checkinRunning[account.ID] + manager.mu.Unlock() + if busy { + return + } + adapter, ok := manager.providers.Get(account.Provider) + if !ok || adapter.CheckinStatus == nil { + return + } + policy, ok := providers.CheckinFor(account.Provider, account.ProviderRegion) + if !ok { + return + } + location, err := time.LoadLocation(policy.Timezone) + if err != nil { + return + } + syncCtx, cancel := context.WithTimeout(ctx, checkinStatusTimeout) + defer cancel() + stop := context.AfterFunc(manager.runCtx, cancel) + defer stop() + result, readErr := adapter.CheckinStatus.CheckinStatus(syncCtx, account.ID) + now := time.Now().UTC() + // A manual/scheduled check-in can finish while the read-only probe is in + // flight. Re-read the account before deciding, so the slower probe cannot + // overwrite a fresh success with the state that preceded it. + current, currentErr := manager.store.Get(ctx, account.ID) + if currentErr != nil { + log.Printf("checkin status account=%s refresh: %v", account.ID, currentErr) + return + } + account = current + manager.mu.Lock() + busy = manager.checkinRunning[account.ID] + manager.mu.Unlock() + if busy { + return + } + earliest := strings.TrimSpace(result.EarliestCheckin) + if earliest == "" { + earliest = accounts.EarliestCheckinClock(account.Provider) + } + update := accounts.CheckinStatusUpdate{ + Source: "upstream", + AutoTime: accounts.AutoCheckinTimeFromEarliest(earliest), + SyncedAt: now, + } + if readErr != nil { + update.Status = "unknown" + update.Message = "上游状态同步失败:" + readErr.Error() + } else { + switch result.Status { + case "already": + update.Status = "already" + update.Message = strings.TrimSpace(result.Message) + if update.Message == "" { + update.Message = "上游显示今日已签到" + } + if !CheckedInLocalDay(account.LastCheckinAt, account.LastCheckinStatus, now.In(location)) { + update.CheckinAt = now.Format(time.RFC3339Nano) + } + case "pending": + update.Status = "pending" + update.Message = strings.TrimSpace(result.Message) + if update.Message == "" { + update.Message = "上游显示今日未签到" + } + case "skipped": + update.Status = "skipped" + update.Message = strings.TrimSpace(result.Message) + default: + update.Status = "unknown" + update.Message = strings.TrimSpace(result.Message) + if update.Message == "" { + update.Message = "上游签到状态未知" + } + } + } + // An upstream lag right after a real check-in must not erase a fresh local + // success. An "unknown" answer is not evidence that today's check-in is + // missing, so a real local success stands for the rest of the provider day; + // pending/skipped may still replace it after the grace window. + if update.Status != "already" && CheckedInLocalDay(account.LastCheckinAt, account.LastCheckinStatus, now.In(location)) { + preserveLocal := update.Status == "unknown" + if last, err := time.Parse(time.RFC3339Nano, account.LastCheckinAt); err == nil && now.Sub(last) < checkinStatusGrace { + preserveLocal = true + } + if preserveLocal { + update.Status = account.LastCheckinStatus + update.Message = account.LastCheckinMsg + update.CheckinAt = "" + update.Source = account.LastCheckinSource + if update.Source == "" { + update.Source = "local" + } + } + } + persistCtx, cancelPersist := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancelPersist() + if err := manager.store.RecordCheckinStatus(persistCtx, account.ID, update); err != nil { + log.Printf("checkin status account=%s: %v", account.ID, err) + } +} + func (manager *Manager) clearCheckinCooldown(ctx context.Context, accountID string) error { if manager.pool != nil { if _, ok := manager.pool.ByID(accountID); ok { @@ -229,6 +424,9 @@ func recordedToday(at string, now time.Time) bool { const ( keepaliveTickTimeout = 90 * time.Second maintenanceGapJitterMS = 1000 + // manualCheckinConcurrency caps a user-triggered one-click check-in. It is + // independent of the scheduled loop's per-tick cap and gap. + manualCheckinConcurrency = 4 ) // Defaults are conservative; tests may override the vars to skip real sleeps. @@ -286,8 +484,16 @@ func checkinDueFor(account Account, configuredTime string, now time.Time, allowD if err != nil || last.Before(due) { return true } - retry, _ := checkinSlot("21:00", account.ID, now) - return due.Before(retry) && !now.Before(retry) && last.Before(retry) + // The 01:00 slot can return a provisional "already" while the provider is + // still settling its 00:00 day. Retry at 02:05 once that window is + // confirmed, then keep the midday and evening safety nets. + for _, retryClock := range []string{"02:05", "12:05", "21:00"} { + retry, err := checkinSlot(retryClock, account.ID, now) + if err == nil && due.Before(retry) && !now.Before(retry) && last.Before(retry) { + return true + } + } + return false } func (manager *Manager) runScheduledCheckins(ctx context.Context, now time.Time) { @@ -449,6 +655,7 @@ func (manager *Manager) RunMaintenanceLoop(stop <-chan struct{}) { // Seed the throttle so the first pass does not duplicate the boot-time // RefreshAll: the next stale-quota sweep runs 5 minutes after startup. lastStaleQuota := time.Now() + lastCheckinStatusSync := time.Time{} // Liveness probes start one tick in so boot-time RefreshAll owns the first // /health round-trip and short-lived tests with a stub worker are not probed // the instant the loop starts. @@ -458,6 +665,10 @@ func (manager *Manager) RunMaintenanceLoop(stop <-chan struct{}) { return } now := time.Now() + if now.Sub(lastCheckinStatusSync) >= checkinStatusInterval { + lastCheckinStatusSync = now + go manager.SyncCheckinStatuses(ctx) + } manager.runScheduledCheckins(ctx, now) day := now.Format("2006-01-02") if day != keepaliveProgressDay { diff --git a/internal/store/backup_test.go b/internal/store/backup_test.go index bd8d58c3..81969739 100644 --- a/internal/store/backup_test.go +++ b/internal/store/backup_test.go @@ -112,6 +112,7 @@ func TestPublishedMigrationsKeepOrderedFilenameAndSQLDigest(t *testing.T) { {"030_api_key_model_aggregation.sql", "373fe14496053692251b5260b8ad4daef4af0fd5105e461efdd37bf9639a79d1"}, {"031_aggregations.sql", "3edaa45d50fe907d4ace839297d0264ad199ae19de97f007f248c6301239f928"}, {"032_aggregation_member_account.sql", "2e24df6d7363faf5f383887d589ab47bf2f0398f1e30338812066587dbf0ea01"}, + {"033_account_checkin_status.sql", "0e4b4466a23d58eb9e7e370053ad7b52bc3285ea9461a8b99cac2bae88bba49d"}, } if len(sqliteMigrations) != len(want) { t.Fatalf("migration count = %d, want %d", len(sqliteMigrations), len(want)) diff --git a/internal/store/checkin_test.go b/internal/store/checkin_test.go index 618ca916..384fe85f 100644 --- a/internal/store/checkin_test.go +++ b/internal/store/checkin_test.go @@ -28,7 +28,7 @@ func TestProviderCheckinInheritanceAndReset(t *testing.T) { t.Fatal(err) } effective, err := accounts.ResolveCheckinTime(ctx, store, account) - if err != nil || effective != "10:30" { + if err != nil || effective != accounts.DefaultCheckinAutoTime(providerID) { t.Fatalf("effective=%q err=%v", effective, err) } if err := store.Update(ctx, account.ID, accounts.UpdateAccount{AutoCheckin: boolPtr(true), CheckinTime: stringPtr("18:30")}); err != nil { @@ -53,7 +53,7 @@ func TestProviderCheckinInheritanceAndReset(t *testing.T) { t.Fatal(err) } effective, err = accounts.ResolveCheckinTime(ctx, store, account) - if err != nil || effective != "11:30" || account.CheckinTime != "" { + if err != nil || effective != accounts.DefaultCheckinAutoTime(providerID) || account.CheckinTime != "" { t.Fatalf("reset=%q err=%v", effective, err) } } diff --git a/internal/store/migrations.go b/internal/store/migrations.go index f49e1a07..feb60cc1 100644 --- a/internal/store/migrations.go +++ b/internal/store/migrations.go @@ -285,6 +285,10 @@ CREATE TABLE IF NOT EXISTS aggregation_members ( CREATE INDEX IF NOT EXISTS aggregation_members_agg ON aggregation_members(agg_id);`}, {filename: "032_aggregation_member_account.sql", sql: ` ALTER TABLE aggregation_members ADD COLUMN account_id TEXT NOT NULL DEFAULT '';`}, + {filename: "033_account_checkin_status.sql", sql: ` +ALTER TABLE accounts ADD COLUMN last_checkin_source TEXT NOT NULL DEFAULT ''; +ALTER TABLE accounts ADD COLUMN last_checkin_synced_at TEXT NOT NULL DEFAULT ''; +ALTER TABLE accounts ADD COLUMN checkin_auto_time TEXT NOT NULL DEFAULT '';`}, } const schemaMigrationsDDL = ` diff --git a/internal/store/store.go b/internal/store/store.go index a202abbc..550e54b6 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -150,6 +150,10 @@ func (s *Store) Create(ctx context.Context, input accounts.CreateAccount) (accou checkinTime = override } } + checkinAutoTime := "" + if _, supported := providers.CheckinFor(descriptor.ID, region.ID); supported { + checkinAutoTime = accounts.DefaultCheckinAutoTime(descriptor.ID) + } account := accounts.Account{ ID: newAccountID(), Name: name, @@ -166,6 +170,7 @@ func (s *Store) Create(ctx context.Context, input accounts.CreateAccount) (accou WorkBuddyCheckinTime: checkinTime, AutoCheckin: genericAutoCheckin, CheckinTime: override, + CheckinAutoTime: checkinAutoTime, ProxyURL: strings.TrimSpace(input.ProxyURL), Status: "offline", CreatedAt: now, @@ -174,13 +179,13 @@ func (s *Store) Create(ctx context.Context, input accounts.CreateAccount) (accou _, err = s.db.ExecContext(ctx, ` INSERT INTO accounts ( id, name, provider, provider_region, auth_type, enabled, max_inflight, priority, credit_floor, percent_floor, drop_system_prompt, - workbuddy_auto_checkin, workbuddy_checkin_time, proxy_url, status, created_at, updated_at, auto_checkin, checkin_time - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + workbuddy_auto_checkin, workbuddy_checkin_time, proxy_url, status, created_at, updated_at, auto_checkin, checkin_time, checkin_auto_time + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, account.ID, account.Name, account.Provider, account.ProviderRegion, account.AuthType, account.Enabled, account.MaxInFlight, account.Priority, account.CreditFloor, account.PercentFloor, account.DropSystemPrompt, account.WorkBuddyAutoCheckin, account.WorkBuddyCheckinTime, account.ProxyURL, account.Status, formatTime(account.CreatedAt), formatTime(account.UpdatedAt), - account.AutoCheckin, account.CheckinTime, + account.AutoCheckin, account.CheckinTime, account.CheckinAutoTime, ) if err != nil { return accounts.Account{}, fmt.Errorf("create account: %w", err) @@ -192,6 +197,7 @@ func (s *Store) Get(ctx context.Context, id string) (accounts.Account, error) { row := s.db.QueryRowContext(ctx, ` SELECT id, name, provider, provider_region, remote_uid, auth_type, enabled, max_inflight, priority, credit_floor, percent_floor, drop_system_prompt, workbuddy_auto_checkin, workbuddy_checkin_time, proxy_url, last_checkin_at, last_checkin_msg, last_checkin_status, + last_checkin_source, last_checkin_synced_at, checkin_auto_time, status, last_error, last_error_kind, cooldown_until, quota_json, created_at, updated_at, auto_checkin, checkin_time FROM accounts WHERE id = ?`, strings.TrimSpace(id)) account, err := scanAccount(row) @@ -219,6 +225,7 @@ func scanAccount(row rowScanner) (accounts.Account, error) { &account.ID, &account.Name, &account.Provider, &account.ProviderRegion, &account.RemoteUID, &account.AuthType, &account.Enabled, &account.MaxInFlight, &account.Priority, &creditFloor, &percentFloor, &account.DropSystemPrompt, &account.WorkBuddyAutoCheckin, &account.WorkBuddyCheckinTime, &account.ProxyURL, &account.LastCheckinAt, &account.LastCheckinMsg, &account.LastCheckinStatus, + &account.LastCheckinSource, &account.LastCheckinSyncedAt, &account.CheckinAutoTime, &account.Status, &account.LastError, &account.LastErrorKind, &cooldown, "aJSON, &created, &updated, &account.AutoCheckin, &account.CheckinTime, ) @@ -242,6 +249,12 @@ func scanAccount(row rowScanner) (accounts.Account, error) { if account.WorkBuddyCheckinTime == "" { account.WorkBuddyCheckinTime = accounts.DefaultWorkBuddyCheckinTime } + if _, supported := providers.CheckinFor(account.Provider, account.ProviderRegion); supported && account.CheckinAutoTime == "" { + // The first upstream sync overwrites this with the observed window. The + // in-memory fallback makes the scheduler use the new auto rule immediately + // after upgrade instead of waiting for the first sweep. + account.CheckinAutoTime = accounts.DefaultCheckinAutoTime(account.Provider) + } account.CreatedAt = parseTime(created.String) account.UpdatedAt = parseTime(updated.String) if cooldown.Valid && cooldown.String != "" { @@ -278,6 +291,7 @@ func (s *Store) List(ctx context.Context) ([]accounts.Account, error) { rows, err := s.db.QueryContext(ctx, ` SELECT id, name, provider, provider_region, remote_uid, auth_type, enabled, max_inflight, priority, credit_floor, percent_floor, drop_system_prompt, workbuddy_auto_checkin, workbuddy_checkin_time, proxy_url, last_checkin_at, last_checkin_msg, last_checkin_status, + last_checkin_source, last_checkin_synced_at, checkin_auto_time, status, last_error, last_error_kind, cooldown_until, quota_json, created_at, updated_at, auto_checkin, checkin_time FROM accounts ORDER BY created_at, id`) if err != nil { @@ -914,8 +928,9 @@ func (s *Store) RecordCheckin(ctx context.Context, id, status, msg string, at ti } defer tx.Rollback() result, err := tx.ExecContext(ctx, ` -UPDATE accounts SET last_checkin_at = ?, last_checkin_msg = ?, last_checkin_status = ?, updated_at = ? -WHERE id = ?`, formatTime(at), message, status, formatTime(time.Now().UTC()), accountID) +UPDATE accounts SET last_checkin_at = ?, last_checkin_msg = ?, last_checkin_status = ?, + last_checkin_source = 'local', last_checkin_synced_at = ?, updated_at = ? +WHERE id = ?`, formatTime(at), message, status, formatTime(at), formatTime(time.Now().UTC()), accountID) if err != nil { return fmt.Errorf("record checkin: %w", err) } @@ -934,6 +949,53 @@ INSERT INTO checkin_records (id, account_id, status, message, created_at) VALUES return nil } +func (s *Store) RecordCheckinStatus(ctx context.Context, id string, update accounts.CheckinStatusUpdate) error { + accountID := strings.TrimSpace(id) + if accountID == "" { + return accounts.ErrAccountNotFound + } + if update.SyncedAt.IsZero() { + update.SyncedAt = time.Now().UTC() + } + status := strings.TrimSpace(update.Status) + if status == "" { + status = "unknown" + } + source := strings.TrimSpace(update.Source) + if source == "" { + source = "upstream" + } + setCheckinAt := "last_checkin_at" + if strings.TrimSpace(update.CheckinAt) == "" { + setCheckinAt = "" + } + // One statement keeps a status read from touching the checkin_records + // history: verification is not a new attempt. + query := ` +UPDATE accounts SET last_checkin_status = ?, last_checkin_msg = ?, last_checkin_source = ?, + last_checkin_synced_at = ?, updated_at = ?` + args := []any{status, strings.TrimSpace(update.Message), source, formatTime(update.SyncedAt), formatTime(time.Now().UTC())} + if setCheckinAt != "" { + query += ", last_checkin_at = ?" + args = append(args, strings.TrimSpace(update.CheckinAt)) + } + if auto := strings.TrimSpace(update.AutoTime); auto != "" { + query += ", checkin_auto_time = ?" + args = append(args, auto) + } + query += " WHERE id = ?" + args = append(args, accountID) + result, err := s.db.ExecContext(ctx, query, args...) + if err != nil { + return fmt.Errorf("record checkin status: %w", err) + } + changed, _ := result.RowsAffected() + if changed == 0 { + return accounts.ErrAccountNotFound + } + return nil +} + func (s *Store) ListCheckinRecords(ctx context.Context, accountID string, limit int) ([]accounts.CheckinRecord, error) { if _, err := s.Get(ctx, accountID); err != nil { return nil, err diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 2588f0be..839ceccb 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -521,7 +521,7 @@ func TestStoreDefaultsWorkBuddyAutoCheckinOff(t *testing.T) { } } -func TestStoreCreateUsesConfiguredWorkBuddyCheckinDefault(t *testing.T) { +func TestStoreCreateWorkBuddyCheckinTimeFallsBackToAuto(t *testing.T) { ctx := context.Background() store, err := OpenStore(filepath.Join(t.TempDir(), "qoder.db")) if err != nil { @@ -542,7 +542,7 @@ func TestStoreCreateUsesConfiguredWorkBuddyCheckinDefault(t *testing.T) { t.Fatal(err) } updated, err := store.Get(ctx, account.ID) - if err != nil || updated.WorkBuddyCheckinTime != "07:15" { + if err != nil || updated.WorkBuddyCheckinTime != "01:00" { t.Fatalf("updated=%+v err=%v", updated, err) } }