Skip to content
Closed
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
17 changes: 17 additions & 0 deletions changelog/unreleased/maintenance-task-registry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
### English

- Renew credentials in the background before they expire. An account whose access token is within ten minutes of expiry is refreshed on a five-minute sweep, with per-account backoff (1m, 5m, 30m, 2h); only a definitive auth refusal marks the account `login_required`, after three consecutive failures.
- Add a unified liveness task (default every six hours, configurable, `0` disables it). Providers with a real usage or catalog read (`kiro`, `codex`, `zhipu`, `command`, `opencode`) use it; everyone else falls back to the existing probe. Network errors only count toward the failure total and never paint an account red on the first failure.
- Refresh credits periodically (default every 30 minutes, provider and account overrides, `0` disables it) and keep the existing exhausted-account backoff ladder.
- Move every maintenance job into one task registry: check-in scheduling, WorkBuddy's daily pass, resource sampling, worker liveness, exhausted-quota probing, credential renewal, liveness, periodic credits. Cadence and semantics are unchanged.
- Add the attempt source to the check-in ledger so the console can distinguish a manual click, a scheduled claim, and a catch-up retry.
- Console: a "Background maintenance" card in system settings (probe hours, credit interval, renewal switch), renewal/probe timestamps and failure badges on account cards, and source chips in the check-in history.

### 中文

- 后台在凭据到期前主动续期:距离过期十分钟内即进入五分钟一轮的刷新,单账号失败按 1 分钟、5 分钟、30 分钟、2 小时退避;只有连续三次明确被拒才标记 `login_required`。
- 新增统一探活任务(默认六小时一轮,可配置,`0` 关闭)。有真实用量或目录读接口的供应商(`kiro`、`codex`、`zhipu`、`command`、`opencode`)走该接口,其余回退到原有 Probe;网络错误只累计次数,首次失败不会把账号标红。
- 额度按周期刷新(默认 30 分钟,可供应商级或账号级覆盖,`0` 关闭),并保留已耗尽账号的既有退避梯子。
- 所有维护任务收进统一任务注册表:签到调度、WorkBuddy 每日保活、资源采样、worker 心跳、耗尽额度探测、凭据续期、统一探活、周期额度。周期与语义保持不变。
- 签到台账新增来源列,控制台可区分手动签到、定时签到与补跑。
- 控制台:系统设置新增「后台维护」卡片(探活周期、额度间隔、续期开关),账号卡展示续期/探活时间与失败次数徽章,签到历史显示来源标签。
18 changes: 18 additions & 0 deletions docs/ARCHITECTURE_SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,24 @@ cmd/server
| `server` | 路由和 web UI | 业务策略、store、runtime Manager |
| `app` | 组装依赖和启动关闭 | 领域业务规则 |

## 维护任务注册表

`runtime.Manager.RunMaintenanceLoop` 只做调度:任务名、周期、首跑延迟和单次超时集中声明在 [`internal/runtime/manager_tasks.go`](../internal/runtime/manager_tasks.go),循环按注册表执行。新增一个后台维护动作应在这里注册,不要往 tick 本体加 if 块。

| 任务 | 周期 | 契约 |
|---|---|---|
| `checkin-status-sync` | 15min | 只读对账上游签到状态,不写签到成功 |
| `scheduled-checkins` | 30s tick | 每拍最多 2 个账号、2s+抖动、02:05/12:05/21:00 补跑 |
| `workbuddy-daily` | 30s tick,22:00 后 | 每天每账号至少一轮真实保活 |
| `resources` | 30s | 服务端与 worker 采样 |
| `worker-liveness` | 30s | 仅旧 `qoder-native-v1` worker 的 `/health` 看护 |
| `stale-quota` | 5min 扫描 | 已耗尽账号按 5m→24h 梯子重探 |
| `credential-refresh` | 5min 扫描 | 到期前 10min 续期;退避 1m/5m/30m/2h;连续 3 次 auth 拒绝才 `login_required` |
| `liveness-probe` | 5min 扫描,账号级默认 6h | 优先 provider `Keepaliver`,否则 `Prober`;连续 3 次失败才改状态 |
| `quota-policy-refresh` | 5min 扫描 | 账号级 → 供应商策略 → 全局(默认 30min,0 关闭) |

维护状态写在新表 `account_maintenance`,不往 `accounts` 加列。Provider 能力通过 `providers.Adapter` 的可选 `Refresher` / `Keepaliver` 暴露;实现方必须带账号锁并落盘,网络错误不得写成 `login_required`。

## Provider 边界

- Qoder Global 和 Qoder CN 是同一个 `provider=qoder`,通过 `region` 区分,不创建新的 provider family。
Expand Down
264 changes: 264 additions & 0 deletions docs/PROVIDER_LIVENESS_CHECKIN.md

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion frontend/src/api/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ export type SystemSettings = {
workbuddy_checkin_time: string
checkin_times: Record<string, string>
timezone: string
maintenance_probe_hours: number
maintenance_credential_refresh: boolean
maintenance_quota_minutes: number
session_affinity?: {
ttl_seconds?: number
capacity?: number
Expand Down Expand Up @@ -99,7 +102,7 @@ export function fetchSystemSettings() {
return api<SystemSettings>('/api/system/settings')
}

export function updateSystemSettings(input: { cross_provider_model_pool?: boolean; checkin_disabled_accounts?: boolean; routing_strategy?: SystemSettings['routing_strategy']; proxy_url?: string; workbuddy_checkin_time?: string; checkin_times?: Record<string, string> }) {
export function updateSystemSettings(input: { cross_provider_model_pool?: boolean; checkin_disabled_accounts?: boolean; routing_strategy?: SystemSettings['routing_strategy']; proxy_url?: string; workbuddy_checkin_time?: string; checkin_times?: Record<string, string>; maintenance_probe_hours?: number; maintenance_credential_refresh?: boolean; maintenance_quota_minutes?: number }) {
return api<SystemSettings>('/api/system/settings', {
method: 'PATCH',
body: JSON.stringify(input),
Expand Down
11 changes: 11 additions & 0 deletions frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,19 @@ export type CheckinRecord = {
account_id: string
status: string
message?: string
source?: string
created_at: string
}

export type AccountMaintenance = {
account_id: string
last_refresh_at?: string
refresh_failures?: number
last_probe_at?: string
probe_failures?: number
quota_refresh_minutes?: number
}

export type Overview = {
ok?: boolean
time?: string
Expand Down Expand Up @@ -192,6 +202,7 @@ export type Overview = {
checkin_auto_time?: string
quota?: AccountQuota
overage_writable?: boolean
maintenance?: AccountMaintenance
created_at?: string
updated_at?: string
}>
Expand Down
27 changes: 27 additions & 0 deletions frontend/src/components/account/AccountCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ function formatCheckinMoment(value: string, timezone: string) {
}
}

// Maintenance timestamps come from the backend in RFC3339. Show a compact
// local time; an empty value means the task has not touched the account yet.
function maintenanceAge(value?: string) {
if (!value) return '—'
const date = new Date(value)
if (Number.isNaN(date.getTime())) return value
return new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'short' }).format(date)
}

// Transient check-in feedback pushed from the page after a manual check-in.
// `kind` selects the glyph/colour; `message` is the raw upstream error text
// (only present for failures) and may be truncated in the UI with a copy button.
Expand Down Expand Up @@ -209,6 +218,7 @@ export function AccountCard({
const checkinSchedule = account.checkin_time || account.checkin_auto_time || checkinDefaultTime
const checkinTimeZone = checkinTimezone && checkinTimezone !== 'Local' ? checkinTimezone : 'Asia/Shanghai'
const syncedAt = account.last_checkin_synced_at ? formatCheckinMoment(account.last_checkin_synced_at, checkinTimeZone) : ''
const maintenance = account.maintenance

useLayoutEffect(() => {
const chip = chipRef.current
Expand Down Expand Up @@ -345,6 +355,23 @@ export function AccountCard({
<Card.Content className="gap-1.5 px-4 pb-3">
<RuntimeMeter state={state} stateCopy={stateCopy} t={t} />

{maintenance ? (
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-caption text-muted">
<span className="mono">{t('maintenanceRenewed', { time: maintenanceAge(maintenance.last_refresh_at) })}</span>
<span className="mono">{t('maintenanceProbed', { time: maintenanceAge(maintenance.last_probe_at) })}</span>
{Number(maintenance.refresh_failures || 0) > 0 ? (
<Chip size="sm" variant="soft" color="warning">
{t('maintenanceRefreshFailures', { count: Number(maintenance.refresh_failures || 0) })}
</Chip>
) : null}
{Number(maintenance.probe_failures || 0) > 0 ? (
<Chip size="sm" variant="soft" color="warning">
{t('maintenanceProbeFailures', { count: Number(maintenance.probe_failures || 0) })}
</Chip>
) : null}
</div>
) : null}

{quotaHasMeter(account.quota) && account.quota ? (
<QuotaMeter
quota={account.quota}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ export function AccountCheckinRecordsModal({ account, t, onClose }: Props) {
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<Chip size="sm" variant="soft" color={status.color}>{status.label}</Chip>
{record.source ? (
<Chip size="sm" variant="soft" color="default">
{record.source === 'scheduled' ? t('checkinSourceScheduled') : record.source === 'retry' ? t('checkinSourceRetry') : t('checkinSourceManual')}
</Chip>
) : null}
<span className="mono text-caption text-muted">{formatRecordTime(record.created_at)}</span>
</div>
<p className="mt-1 break-words text-caption leading-5 text-foreground/75">{record.message || '—'}</p>
Expand Down
30 changes: 30 additions & 0 deletions frontend/src/i18n/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,21 @@ export const messages: Record<Lang, Dict> = {
checkinRecords: 'Check-in records',
checkinRecordsTitle: 'Check-in records · {name}',
checkinRecordsHint: 'The latest 20 check-in attempts for this account.',
checkinSourceManual: 'Manual',
checkinSourceScheduled: 'Scheduled',
checkinSourceRetry: 'Retry',
maintenanceRenewed: 'Renewed {time}',
maintenanceProbed: 'Probed {time}',
maintenanceRefreshFailures: 'Renewal failed {count}x',
maintenanceProbeFailures: 'Probe failed {count}x',
maintenanceSettingsTitle: 'Background maintenance',
maintenanceSettingsHint: 'Credential renewal, liveness probes, and periodic credit refresh run without a restart.',
maintenanceProbeHours: 'Liveness interval (hours)',
maintenanceProbeHoursHint: '0 disables the unified probe.',
maintenanceQuotaMinutes: 'Credit refresh interval (minutes)',
maintenanceQuotaMinutesHint: '0 disables periodic refresh; exhausted accounts still use their own backoff.',
maintenanceCredentialRefresh: 'Renew credentials in the background',
maintenanceCredentialRefreshHint: 'Renews an expiring credential ahead of time and keeps the WorkBuddy daily chain alive.',
checkinRecordsEmpty: 'No check-in records yet',
checkinRecordsCount: '{count} records',
checkinRecordSuccess: 'Success',
Expand Down Expand Up @@ -2183,6 +2198,21 @@ export const messages: Record<Lang, Dict> = {
checkinRecords: '签到记录',
checkinRecordsTitle: '签到记录 · {name}',
checkinRecordsHint: '显示该账号最近 20 次签到结果。',
checkinSourceManual: '手动',
checkinSourceScheduled: '定时',
checkinSourceRetry: '补跑',
maintenanceRenewed: '续期 {time}',
maintenanceProbed: '探活 {time}',
maintenanceRefreshFailures: '续期失败 {count} 次',
maintenanceProbeFailures: '探活失败 {count} 次',
maintenanceSettingsTitle: '后台维护',
maintenanceSettingsHint: '凭据续期、探活与额度周期刷新在后台运行,修改后无需重启。',
maintenanceProbeHours: '探活周期(小时)',
maintenanceProbeHoursHint: '0 表示关闭统一探活。',
maintenanceQuotaMinutes: '额度刷新间隔(分钟)',
maintenanceQuotaMinutesHint: '0 表示关闭周期刷新;已耗尽的账号仍按自身退避节奏探测。',
maintenanceCredentialRefresh: '后台自动续期凭据',
maintenanceCredentialRefreshHint: '到期前主动续期,并维持 WorkBuddy 每日刷新链。',
checkinRecordsEmpty: '还没有签到记录',
checkinRecordsCount: '{count} 条记录',
checkinRecordSuccess: '成功',
Expand Down
80 changes: 78 additions & 2 deletions frontend/src/pages/SystemPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export function SystemPage() {
const [consoleKey, setConsoleKey] = useState<ConsoleKeyView | null>(null)
const [settings, setSettings] = useState<SystemSettings | null>(null)
const [proxyDraft, setProxyDraft] = useState('')
const [probeDraft, setProbeDraft] = useState('6')
const [quotaDraft, setQuotaDraft] = useState('30')
const [settingsBusy, setSettingsBusy] = useState(false)
const [consoleBusy, setConsoleBusy] = useState(false)
const [rotateOpen, setRotateOpen] = useState(false)
Expand All @@ -66,6 +68,8 @@ export function SystemPage() {
void fetchSystemSettings().then((result) => {
setSettings(result)
setProxyDraft(result.proxy_url || '')
setProbeDraft(String(result.maintenance_probe_hours ?? 6))
setQuotaDraft(String(result.maintenance_quota_minutes ?? 30))
}).catch((err) => setError(err instanceof Error ? err.message : String(err)))
}, 0)
return () => window.clearTimeout(timer)
Expand All @@ -90,8 +94,7 @@ export function SystemPage() {
}
}

async function updateCheckinDisabledAccounts(enabled: boolean) {
const previous = settings?.checkin_disabled_accounts ?? false
async function updateCheckinDisabledAccounts(enabled: boolean) { const previous = settings?.checkin_disabled_accounts ?? false
setSettings((current) => current ? { ...current, checkin_disabled_accounts: enabled } : current)
setSettingsBusy(true)
setError('')
Expand All @@ -105,6 +108,37 @@ export function SystemPage() {
}
}

async function saveMaintenance(patch: { maintenance_probe_hours?: number; maintenance_quota_minutes?: number; maintenance_credential_refresh?: boolean }) {
setSettingsBusy(true)
setError('')
try {
const next = await updateSystemSettings(patch)
setSettings(next)
setProbeDraft(String(next.maintenance_probe_hours ?? 6))
setQuotaDraft(String(next.maintenance_quota_minutes ?? 30))
} catch (err) {
setError(err instanceof Error ? err.message : String(err))
} finally {
setSettingsBusy(false)
}
}

function commitMaintenanceNumber(kind: 'probe' | 'quota', raw: string) {
const parsed = Number.parseInt(raw.trim(), 10)
if (!Number.isFinite(parsed) || parsed < 0) {
setProbeDraft(String(settings?.maintenance_probe_hours ?? 6))
setQuotaDraft(String(settings?.maintenance_quota_minutes ?? 30))
return
}
if (kind === 'probe') {
if (parsed === (settings?.maintenance_probe_hours ?? 6)) return
void saveMaintenance({ maintenance_probe_hours: parsed })
return
}
if (parsed === (settings?.maintenance_quota_minutes ?? 30)) return
void saveMaintenance({ maintenance_quota_minutes: parsed })
}

async function updateProxyURL(value: string) {
const saved = settings?.proxy_url || ''
// Nothing changed in the field: keep the draft as-is and skip the PATCH so
Expand Down Expand Up @@ -222,6 +256,48 @@ export function SystemPage() {
<span className="font-medium text-foreground">{settings?.checkin_disabled_accounts ? t('enabled') : t('disabled')}</span>
</div>
</Card>
<Card data-gsap-reveal>
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3">
<div className="grid size-8 shrink-0 place-items-center rounded-lg bg-surface-secondary text-foreground"><ArrowClockwise size={15} /></div>
<div>
<h3 className="font-semibold">{t('maintenanceSettingsTitle')}</h3>
<p className="mt-1 text-caption leading-5 text-muted">{t('maintenanceSettingsHint')}</p>
</div>
</div>
<CompactSwitch
isSelected={settings?.maintenance_credential_refresh ?? true}
isDisabled={settingsBusy || !settings}
ariaLabel={t('maintenanceCredentialRefresh')}
onChange={(selected) => void saveMaintenance({ maintenance_credential_refresh: selected })}
/>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-2">
<div className="space-y-1.5">
<Label className="text-body font-medium text-muted">{t('maintenanceProbeHours')}</Label>
<Input
inputMode="numeric"
value={probeDraft}
onChange={(event) => setProbeDraft(event.target.value)}
onBlur={(event) => commitMaintenanceNumber('probe', event.target.value)}
disabled={settingsBusy || !settings}
/>
<Description className="text-caption leading-5 text-muted">{t('maintenanceProbeHoursHint')}</Description>
</div>
<div className="space-y-1.5">
<Label className="text-body font-medium text-muted">{t('maintenanceQuotaMinutes')}</Label>
<Input
inputMode="numeric"
value={quotaDraft}
onChange={(event) => setQuotaDraft(event.target.value)}
onBlur={(event) => commitMaintenanceNumber('quota', event.target.value)}
disabled={settingsBusy || !settings}
/>
<Description className="text-caption leading-5 text-muted">{t('maintenanceQuotaMinutesHint')}</Description>
</div>
</div>
<Description className="mt-3 text-caption leading-5 text-muted">{t('maintenanceCredentialRefreshHint')}</Description>
</Card>
</div>
</Tabs.Panel>
<Tabs.Panel id="routing" className="pt-5">
Expand Down
8 changes: 8 additions & 0 deletions internal/accounts/provider_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ type ProviderPolicy struct {
// the upstream window + 1 hour without a migration. Manual mode keeps the
// operator's CheckinTime.
CheckinAuto *bool `json:"checkin_auto,omitempty"`
// QuotaRefreshMinutes is the provider-wide periodic credit refresh
// interval. Nil inherits the global default (30 minutes); zero disables
// periodic refresh for this provider (an explicit account override still
// wins).
QuotaRefreshMinutes *int `json:"quota_refresh_minutes,omitempty"`
}

func (policy ProviderPolicy) CheckinScheduleAuto() bool {
Expand All @@ -56,6 +61,9 @@ func NormalizeProviderPolicy(policy ProviderPolicy) (ProviderPolicy, error) {
return ProviderPolicy{}, fmt.Errorf("percent_floor must be between 0 and 100")
}
policy.ProxyURL = strings.TrimSpace(policy.ProxyURL)
if policy.QuotaRefreshMinutes != nil && *policy.QuotaRefreshMinutes < 0 {
return ProviderPolicy{}, fmt.Errorf("quota_refresh_minutes must be >= 0")
}
if err := ValidateAccountProxy(policy.Provider, policy.Region, policy.ProxyURL); err != nil {
return ProviderPolicy{}, err
}
Expand Down
Loading
Loading