Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog/unreleased/checkin-all-coverage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### English

- One-click check-in now runs on the server across every eligible account, regardless of the current browser filter/page or per-account timezone parsing. It honors the system setting for disabled accounts, reports `success`, `already`, `skipped`, and `error` separately, and no longer treats upstream `skipped` as a failure.
- Scheduled check-in now retries `skipped` attempts in the existing 21:00 retry window instead of treating them as completed for the whole day.

### 中文

- 一键签到改为服务端遍历所有符合条件的账号执行,不再受浏览器当前筛选、分页或本地时区判断影响。它会遵循“签到包含停用账号”的系统设置,并分别统计 `success`、`already`、`skipped`、`error`,不再把上游返回的 `skipped` 误判为失败。
- 自动签到不再把 `skipped` 当成当天已完成;这类尝试会在现有的 21:00 重试窗口中再试一次。
15 changes: 15 additions & 0 deletions frontend/src/api/overview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,21 @@ export function checkinAccount(accountId: string) {
)
}

export type CheckinAllResult = {
account_id: string
provider: string
region: string
status: string
message?: string
}

export function checkinAll(input?: { force?: boolean; include_disabled?: boolean }) {
return api<{ object?: string; data?: CheckinAllResult[] }>('/api/accounts/checkin-all', {
method: 'POST',
body: JSON.stringify(input || {}),
})
}

export function fetchCheckinRecords(accountId: string) {
return api<{ object?: string; data?: CheckinRecord[] }>(`/api/accounts/${encodeURIComponent(accountId)}/checkins`)
}
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/i18n/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const messages: Record<Lang, Dict> = {
checkinInherit: 'Follow provider default',
checkinDefaultValue: 'Provider default: {time}',
checkinCustom: 'Account override',
checkinScheduleHint: 'Uses the displayed timezone, normally within about 90 seconds of the chosen time; sequential account processing can take longer. Earlier failures retry once around 21:00. Disabled campaigns are skipped for the day. Chat is unaffected.',
checkinScheduleHint: 'Uses the displayed timezone, normally within about 90 seconds of the chosen time; sequential account processing can take longer. Failed or skipped attempts retry once around 21:00. Chat is unaffected.',
checkinTimeInvalid: 'Enter a valid check-in time (HH:mm).',
checkinRecordSkipped: 'Activity unavailable',
navUsage: 'Usage',
Expand Down Expand Up @@ -1061,7 +1061,7 @@ export const messages: Record<Lang, Dict> = {
checkinInherit: '跟随供应商默认',
checkinDefaultValue: '供应商默认:{time}',
checkinCustom: '账号自定义',
checkinScheduleHint: '按显示的时区执行,通常在设定时间后的约 90 秒内开始,多账号顺序处理可能延后;较早的失败会在约 21:00 重试一次,活动未开放则当天跳过。签到不影响聊天。',
checkinScheduleHint: '按显示的时区执行,通常在设定时间后的约 90 秒内开始,多账号顺序处理可能延后;失败或跳过的尝试会在约 21:00 重试一次。签到不影响聊天。',
checkinTimeInvalid: '请输入有效的签到时间(HH:mm)。',
checkinRecordSkipped: '活动未开放',
navUsage: '用量',
Expand Down
94 changes: 28 additions & 66 deletions frontend/src/pages/AccountsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { SearchBar } from '@/components/ui/SearchBar'
import { useI18n } from '@/hooks/useI18n'
import {
checkinAccount,
checkinAll,
deleteAccount,
exportAccount,
exportAccountBundle,
Expand All @@ -45,7 +46,6 @@ import { fetchSystemSettings, type SystemSettings } from '@/api/system'
import { AccountsPageSkeleton } from '@/components/ui/PageSkeletons'
import {
accountState,
checkedInToday,
type AccountRow,
} from '@/lib/account'
import { accountProviderFamilyLabel } from '@/lib/provider'
Expand Down Expand Up @@ -594,85 +594,47 @@ export function AccountsPage() {
})
}

function alreadyCheckedInToday(account: AccountRow) {
return checkedInToday(account, checkinTimezoneFor(account))
}

async function onCheckinAll() {
let eligible: AccountRow[]
let pending: AccountRow[]
try {
eligible = displayRows.filter((account) => account.enabled && checkinPolicyFor(account))
pending = eligible.filter((account) => !alreadyCheckedInToday(account))
} catch (error) {
// A bad check-in timezone must not swallow the click. The button
// otherwise stays idle and the page shows nothing.
toast({
id: 'checkin-all',
type: 'error',
title: t('toastFailed'),
description: error instanceof Error ? error.message : String(error),
})
return
}
if (eligible.length === 0) {
toast({ id: 'checkin-all', type: 'info', title: t('checkinAllEmpty') })
return
}
if (pending.length === 0) {
toast({ id: 'checkin-all', type: 'success', title: t('checkinAllDone', { count: eligible.length }) })
return
}
// Show the progress before the first account responds. With many
// accounts the first result can take a while, and the toast would
// otherwise appear only after it.
setCheckinAllRunning(true)
toast({
id: 'checkin-all',
type: 'loading',
title: t('toastCheckingInAll', { done: 0, total: pending.length }),
title: t('toastCheckingInAll', { done: 0, total: rows.length }),
})
setCheckinAllRunning(true)
const summary = { checked: 0, skipped: eligible.length - pending.length, failed: 0 }
try {
for (let index = 0; index < pending.length; index += 1) {
// One account at a time, with a pause before every account after the
// first, so a manual pass cannot burst every upstream call at once.
// Accounts already checked in today never reach here.
if (index > 0) {
await new Promise((resolve) => setTimeout(resolve, 4000))
}
try {
const result = await checkinAccount(pending[index].id)
const status = result?.last_checkin_status
const message = result?.last_checkin_msg
const kind = status === 'already' ? 'already' : status === 'skipped' ? 'skipped' : status === 'error' ? 'error' : 'success'
if (kind === 'error' || kind === 'skipped') summary.failed += 1
else summary.checked += 1
setCheckinFeedbackById((current) => ({
...current,
[pending[index].id]: { kind, message: kind === 'error' ? message || t('checkinRecordFailed') : message },
}))
} catch (error) {
summary.failed += 1
setCheckinFeedbackById((current) => ({
...current,
[pending[index].id]: { kind: 'error', message: error instanceof Error ? error.message : String(error) },
}))
}
if (index < pending.length - 1) {
toast({
id: 'checkin-all',
type: 'loading',
title: t('toastCheckingInAll', { done: index + 1, total: pending.length }),
})
const response = await checkinAll()
const results = response.data || []
if (results.length === 0) {
toast({ id: 'checkin-all', type: 'info', title: t('checkinAllEmpty') })
return
}
const summary = { checked: 0, skipped: 0, failed: 0 }
const feedback: Record<string, { kind: 'already' | 'skipped' | 'error' | 'success'; message?: string }> = {}
for (const result of results) {
const raw = String(result.status || '').toLowerCase()
const kind = raw === 'already' || raw === 'skipped' || raw === 'error' ? raw : 'success'
if (kind === 'error') summary.failed += 1
else if (kind === 'skipped' || kind === 'already') summary.skipped += 1
else summary.checked += 1
feedback[result.account_id] = {
kind,
message: kind === 'error' ? result.message || t('checkinRecordFailed') : result.message,
}
}
setCheckinFeedbackById((current) => ({ ...current, ...feedback }))
const values = { checked: summary.checked, skipped: summary.skipped, failed: summary.failed }
toast({
id: 'checkin-all',
type: summary.failed ? 'error' : 'success',
title: t(summary.failed ? 'toastCheckedInAllFailed' : 'toastCheckedInAll', values),
})
} catch (error) {
toast({
id: 'checkin-all',
type: 'error',
title: t('toastFailed'),
description: error instanceof Error ? error.message : String(error),
})
} finally {
setCheckinAllRunning(false)
await reloadAccounts(false).catch(() => undefined)
Expand Down
8 changes: 8 additions & 0 deletions internal/accounts/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ type Account struct {
UpdatedAt time.Time `json:"updated_at"`
}

type CheckinAllResult struct {
AccountID string `json:"account_id"`
Provider string `json:"provider"`
Region string `json:"region"`
Status string `json:"status"`
Message string `json:"message,omitempty"`
}

type CreateAccount struct {
AutoCheckin *bool
CheckinTime string
Expand Down
1 change: 1 addition & 0 deletions internal/api/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ func TestManagementRoutesRequireAPIKey(t *testing.T) {
"/api/models",
"/api/chat",
"/api/accounts",
"/api/accounts/checkin-all",
"/api/logs/requests",
"/api/logs/runtime",
"/api/system/update",
Expand Down
28 changes: 28 additions & 0 deletions internal/console/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,34 @@ func (h *Handler) HandleAccounts(w http.ResponseWriter, r *http.Request) {
}
}

func (h *Handler) HandleCheckinAll(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeErr(w, http.StatusMethodNotAllowed, "method_not_allowed", "POST only")
return
}
var input struct {
Force bool `json:"force"`
IncludeDisabled *bool `json:"include_disabled"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxConsoleBodyBytes)).Decode(&input); err != nil && err != io.EOF {
writeErr(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
includeDisabled := false
if h.System != nil {
includeDisabled = h.System.Current(r.Context()).CheckinDisabledAccounts
}
if input.IncludeDisabled != nil {
includeDisabled = *input.IncludeDisabled
}
results, err := h.Control.Accounts.CheckinAll(r.Context(), input.Force, includeDisabled)
if err != nil {
writeOperationError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"object": "list", "data": results})
}

func (h *Handler) HandleAccountImport(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeErr(w, http.StatusMethodNotAllowed, "method_not_allowed", "POST only")
Expand Down
9 changes: 9 additions & 0 deletions internal/control/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type Runtime interface {
RefreshAccount(ctx context.Context, id string, forceQuota bool) error
RefreshAll(ctx context.Context, forceQuota bool) error
CheckinAccount(ctx context.Context, accountID string) (accounts.Account, error)
CheckinAll(ctx context.Context, force, includeDisabled bool) ([]accounts.CheckinAllResult, error)
ReloadProxyURL(ctx context.Context, value string) error
ReplaceProxyAPIKey(ctx context.Context, key string) error
WorkerAdmin(ctx context.Context, input providers.AdminRequest) (providers.AdminResponse, error)
Expand Down Expand Up @@ -187,6 +188,14 @@ func (a *Accounts) Checkin(ctx context.Context, id string) (accounts.Account, er
return a.runtime.CheckinAccount(ctx, id)
}

func (a *Accounts) CheckinAll(ctx context.Context, force, includeDisabled bool) ([]accounts.CheckinAllResult, error) {
results, err := a.runtime.CheckinAll(ctx, force, includeDisabled)
if err != nil {
return nil, operationError("checkin_all_failed", err.Error())
}
return results, nil
}

func (a *Accounts) LoadCredentialPayload(ctx context.Context, id string) (string, []byte, error) {
return a.store().LoadCredentialPayload(ctx, id)
}
Expand Down
9 changes: 8 additions & 1 deletion internal/control/s06_control_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ func (s *fakeStore) Observe(context.Context, string, string, string, string, str
return nil
}
func (s *fakeStore) ObserveHealth(context.Context, string, string, string, string) error { return nil }
func (s *fakeStore) SaveQuota(context.Context, string, *accounts.QuotaSnapshot) error { return nil }
func (s *fakeStore) SaveQuota(context.Context, string, *accounts.QuotaSnapshot) error { return nil }
func (s *fakeStore) RecordCheckin(context.Context, string, string, string, time.Time) error {
return nil
}
Expand Down Expand Up @@ -373,6 +373,13 @@ func (r *fakeRuntime) CheckinAccount(_ context.Context, id string) (accounts.Acc
}
return r.checkedIn, nil
}
func (r *fakeRuntime) CheckinAll(context.Context, bool, bool) ([]accounts.CheckinAllResult, error) {
r.log.add("runtime.CheckinAll")
if r.checkinErr != nil {
return nil, r.checkinErr
}
return []accounts.CheckinAllResult{{AccountID: r.checkedIn.ID, Status: "success"}}, nil
}
func (r *fakeRuntime) ReloadProxyURL(_ context.Context, value string) error {
r.log.add("runtime.ReloadProxyURL")
r.proxyURL = value
Expand Down
8 changes: 4 additions & 4 deletions internal/runtime/checkin_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func TestCheckinCanceledAttemptIsPersistedWithoutChatCooldown(t *testing.T) {
}
}

func TestCheckinSchedulerSkipsDisabledCampaignButManualCanRecheck(t *testing.T) {
func TestCheckinSchedulerRetriesSkippedCampaignAtRetryWindow(t *testing.T) {
var calls atomic.Int64
manager, account := newCheckinManager(t, checkinFunc(func(context.Context, string) (providers.CheckinResult, error) {
calls.Add(1)
Expand All @@ -107,13 +107,13 @@ func TestCheckinSchedulerSkipsDisabledCampaignButManualCanRecheck(t *testing.T)
location, _ := time.LoadLocation("Asia/Shanghai")
now := time.Now().In(location)
manager.runScheduledCheckins(context.Background(), time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 0, 0, location))
if calls.Load() != 1 {
t.Fatal("disabled campaign ran repeatedly")
if calls.Load() != 2 {
t.Fatalf("skipped campaign should retry at the retry window, calls=%d", calls.Load())
}
if _, err := manager.CheckinAccount(context.Background(), account.ID); err != nil {
t.Fatal(err)
}
if calls.Load() != 2 {
if calls.Load() != 3 {
t.Fatal("manual recheck must remain available")
}
}
Expand Down
16 changes: 9 additions & 7 deletions internal/runtime/maintenance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,20 @@ func TestCheckinSchedule(t *testing.T) {
t.Fatal("did not catch up after scheduled time")
}
account.LastCheckinAt = base.Add(2 * time.Hour).Format(time.RFC3339)
for _, status := range []string{"success", "already", "skipped"} {
for _, status := range []string{"success", "already"} {
account.LastCheckinStatus = status
if checkinDue(account, "09:00", base.Add(14*time.Hour)) {
t.Fatalf("repeated terminal status %s", status)
}
}
account.LastCheckinStatus = "error"
if checkinDue(account, "09:00", base.Add(3*time.Hour)) {
t.Fatal("retried a failure before evening slot")
}
if !checkinDue(account, "09:00", base.Add(14*time.Hour)) {
t.Fatal("did not retry morning failure")
for _, status := range []string{"skipped", "error"} {
account.LastCheckinStatus = status
if checkinDue(account, "09:00", base.Add(3*time.Hour)) {
t.Fatalf("retried %s before evening slot", status)
}
if !checkinDue(account, "09:00", base.Add(14*time.Hour)) {
t.Fatalf("did not retry morning %s", status)
}
}
account.LastCheckinAt = base.Add(14 * time.Hour).Format(time.RFC3339)
if checkinDue(account, "09:00", base.Add(15*time.Hour)) {
Expand Down
Loading
Loading