diff --git a/changelog/unreleased/account-select-checkbox-fix.md b/changelog/unreleased/account-select-checkbox-fix.md new file mode 100644 index 00000000..01563d66 --- /dev/null +++ b/changelog/unreleased/account-select-checkbox-fix.md @@ -0,0 +1,7 @@ +### English + +- Accounts page: the bulk re-login checkbox is clickable again. HeroUI v3 keeps the interactive control inside `Checkbox.Content`; the card rendered the indicator on its own, so it looked correct but swallowed every click and no account could be selected. + +### 中文 + +- 账号页:批量重新登录的勾选框恢复可点。HeroUI v3 的可交互控件在 `Checkbox.Content` 里,卡片此前只渲染了指示器本身,看上去正常但吃掉了所有点击,导致一个账号都选不中。 diff --git a/changelog/unreleased/console-bulk-relogin.md b/changelog/unreleased/console-bulk-relogin.md new file mode 100644 index 00000000..fd9218da --- /dev/null +++ b/changelog/unreleased/console-bulk-relogin.md @@ -0,0 +1,9 @@ +### English + +- Accounts page: new "Re-login" mode. Tick the account cards, press confirm, and the console walks the selected accounts one by one, opening each account's authorization page, polling the login status, and advancing automatically once an account is signed in. A cancel button stops the walkthrough at any point; each row keeps its own status and the verbatim upstream message. +- Accounts are authorized sequentially on purpose: WorkBuddy accounts often share one SSO session, and parallel flows would hand the same freshly issued token to different account records. + +### 中文 + +- 账号页新增「重新登录」模式:勾选账号卡片后点确定,控制台会按顺序逐个走授权流程——打开该账号的登录页、轮询登录状态,登录成功后自动进入下一个;随时可点取消中止,每一行都保留自己的状态和上游原文消息。 +- 故意串行授权:多个 WorkBuddy 账号常共用一个 SSO 会话,并发授权会把同一份新签发的令牌塞给不同账号。 diff --git a/changelog/unreleased/console-realtime-truthful-ops.md b/changelog/unreleased/console-realtime-truthful-ops.md new file mode 100644 index 00000000..89013c32 --- /dev/null +++ b/changelog/unreleased/console-realtime-truthful-ops.md @@ -0,0 +1,15 @@ +### English + +- Check in all / refresh credits now fan out to every account in one pass: the new bulk endpoints return one result per account with the verbatim upstream error, and the console no longer batches or queues requests. +- Console state is pushed over `GET /api/events` (SSE) with replay by sequence id, so account health, cooldown, quota, check-in and bulk progress reach the page within a second; a 5s poll takes over when the stream is unavailable. +- The console shows real data only: the synthetic inflight demo board and its toggle are gone, an unmeasured P95 renders as "—", a force-ready account is badged, and each quota snapshot states how old it is. +- Check-in results carry the real upstream reward credits plus error code/HTTP status, and a provider that reports no status is shown as unknown instead of success. +- Requests carrying video, audio or file parts are refused with a real 400 `invalid_request` rather than being silently dropped while prompts are built, and Trae streams now fail over when the upstream accepts a request and then sends nothing. + +### 中文 + +- 一键签到 / 一键获取积分改为一次全量扇出:新的批量接口按账号返回真实结果与上游原始错误,控制台不再分批或排队。 +- 控制台通过 `GET /api/events`(SSE,按序号补发)推送状态,账号健康、冷却、额度、签到与批量进度在一秒内到达页面;通道不可用时自动降级为 5 秒轮询。 +- 控制台只显示真实数据:合成并发演示面板及其开关已删除,未测得的 P95 显示“—”,强制就绪账号带徽标,额度快照标注了读取时间。 +- 签到结果携带上游真实奖励积分与错误码 / HTTP 状态;上游未回报状态时显示为“未知”,不再当作成功。 +- 携带视频、音频或文件片段的请求会收到真实的 400 `invalid_request`,不再在拼装提示词时被静默丢弃;Trae 流在上游接受请求却持续无响应时会切换账号重试。 diff --git a/frontend/src/api/events.ts b/frontend/src/api/events.ts new file mode 100644 index 00000000..293eacdc --- /dev/null +++ b/frontend/src/api/events.ts @@ -0,0 +1,179 @@ +import { ApiError } from './client' +import { readStoredApiKey } from '@/hooks/useApiKey' +import type { AccountQuota } from './types' + +/** Event types published by the runtime event bus (`internal/events`). */ +export type ServerEventType = 'account' | 'accounts' | 'quota' | 'checkin' | 'refresh' | 'bulk' + +/** Real per-account payloads carried by each event type. */ +export type AccountStateEvent = { + account_id?: string + runtime_state?: string + ready?: boolean + cooldown_until?: string + last_error?: string + last_kind?: string +} + +export type QuotaStateEvent = { + account_id?: string + quota?: AccountQuota +} + +export type CheckinStateEvent = { + account_id?: string + status?: string + message?: string + reward_credits?: number + at?: string +} + +export type RefreshStateEvent = { + account_id?: string + provider?: string + region?: string + ok?: boolean + status?: string + code?: string + kind?: string + message?: string + http_status?: number + quota?: AccountQuota +} + +export type BulkEventData = { + op_id?: string + kind?: 'checkin' | 'refresh' + phase?: 'start' | 'account' | 'done' + total?: number + done?: number + account_id?: string + result?: Record +} + +/** One SSE frame as delivered by GET /api/events. */ +export type ServerEvent = { + seq: number + type: ServerEventType + time: string + account_id?: string + op_id?: string + data?: AccountStateEvent | QuotaStateEvent | CheckinStateEvent | RefreshStateEvent | BulkEventData +} + +export type EventStreamStatus = 'connecting' | 'live' | 'offline' + +type StreamOptions = { + /** Last seen seq; the server replays newer ring events before streaming live. */ + lastSeq: number + signal: AbortSignal + onEvent: (event: ServerEvent) => void + onOpen?: () => void +} + +function splitFrames(buffer: string): { frames: string[]; rest: string } { + const frames: string[] = [] + let rest = buffer.replace(/\r\n/g, '\n') + let index = rest.indexOf('\n\n') + while (index !== -1) { + frames.push(rest.slice(0, index)) + rest = rest.slice(index + 2) + index = rest.indexOf('\n\n') + } + return { frames, rest } +} + +function parseFrame(frame: string): { id?: number; event?: string; data?: string } { + const out: { id?: number; event?: string; data?: string } = {} + const dataLines: string[] = [] + for (const line of frame.split('\n')) { + if (!line || line.startsWith(':')) continue + const colon = line.indexOf(':') + const field = colon === -1 ? line : line.slice(0, colon) + const rawValue = colon === -1 ? '' : line.slice(colon + 1) + const value = rawValue.startsWith(' ') ? rawValue.slice(1) : rawValue + if (field === 'id') { + const id = Number(value) + if (Number.isFinite(id)) out.id = id + } else if (field === 'event') { + out.event = value + } else if (field === 'data') { + dataLines.push(value) + } + } + if (dataLines.length) out.data = dataLines.join('\n') + return out +} + +/** + * Opens one console event stream and resolves when it ends (server close, + * network failure, or abort). The console key travels in the Authorization + * header — EventSource cannot do that, so the stream is read with fetch. + */ +export async function openEventStream(opts: StreamOptions): Promise { + const headers: Record = { Accept: 'text/event-stream' } + const key = readStoredApiKey().trim() + if (key) headers.Authorization = `Bearer ${key}` + if (opts.lastSeq > 0) headers['Last-Event-ID'] = String(opts.lastSeq) + const url = opts.lastSeq > 0 ? `/api/events?last_seq=${opts.lastSeq}` : '/api/events' + + let res: Response + try { + res = await fetch(url, { headers, signal: opts.signal, cache: 'no-store' }) + } catch (error) { + if (opts.signal.aborted) return + throw error + } + if (!res.ok) { + let message = `${res.status} ${res.statusText}` + try { + const body = await res.text() + try { + const parsed = JSON.parse(body) + message = parsed?.error?.message || parsed?.message || message + } catch { + if (body) message = body.slice(0, 200) + } + } catch { + /* keep status text */ + } + throw new ApiError(message, res.status) + } + + opts.onOpen?.() + const reader = res.body?.getReader() + if (!reader) throw new ApiError('event stream unavailable', res.status) + + const decoder = new TextDecoder() + let buffer = '' + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + buffer += decoder.decode(value, { stream: true }) + const split = splitFrames(buffer) + buffer = split.rest + for (const frame of split.frames) { + const parsed = parseFrame(frame) + // Comments (heartbeats) and bare `id:` frames carry no state change. + if (!parsed.data) continue + let payload: ServerEvent + try { + payload = JSON.parse(parsed.data) as ServerEvent + } catch { + continue + } + if (typeof payload?.type !== 'string') continue + if (!Number.isFinite(payload.seq) && parsed.id != null) payload.seq = parsed.id + opts.onEvent(payload) + } + if (opts.signal.aborted) break + } + } finally { + try { + await reader.cancel() + } catch { + /* stream already closed */ + } + } +} diff --git a/frontend/src/api/overview.ts b/frontend/src/api/overview.ts index dac73d7b..605ada21 100644 --- a/frontend/src/api/overview.ts +++ b/frontend/src/api/overview.ts @@ -1,6 +1,6 @@ import { api, ApiError } from './client' import { readStoredApiKey } from '@/hooks/useApiKey' -import type { CheckinRecord, Overview } from './types' +import type { AccountQuota, CheckinRecord, Overview } from './types' export function fetchOverviewSummary(keyOverride?: string) { return api('/api/overview/summary', {}, keyOverride) @@ -525,6 +525,13 @@ export type CheckinAllResult = { region: string status: string message?: string + /** Real upstream grant amount; absent when the provider reported none. */ + reward_credits?: number + /** Verbatim upstream error classification when the check-in failed. */ + code?: string + kind?: string + http_status?: number + quota_refreshed?: boolean } export function checkinAll(input?: { force?: boolean; include_disabled?: boolean }) { @@ -534,6 +541,31 @@ export function checkinAll(input?: { force?: boolean; include_disabled?: boolean }) } +export type AccountRefreshResult = { + account_id: string + provider?: string + region?: string + ok: boolean + status?: string + code?: string + kind?: string + message?: string + http_status?: number + quota?: AccountQuota +} + +/** + * One-shot refresh for every account, fully concurrent on the backend — no + * client batching or queueing. Each row carries the real probe outcome and the + * verbatim upstream error, so a partial failure stays visible per account. + */ +export function refreshAllAccounts(input?: { quota?: boolean; include_disabled?: boolean }) { + return api<{ object?: string; data?: AccountRefreshResult[] }>('/api/accounts/refresh-all', { + method: 'POST', + body: JSON.stringify(input || {}), + }) +} + export function fetchCheckinRecords(accountId: string) { return api<{ object?: string; data?: CheckinRecord[] }>(`/api/accounts/${encodeURIComponent(accountId)}/checkins`) } diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 189db8ea..342ea765 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -184,6 +184,9 @@ export type Overview = { last_checkin_synced_at?: string checkin_auto_time?: string quota?: AccountQuota + /** Local force-ready marker is active: the account enters the pool without + * a real probe. Quota below still comes from the real stored snapshot. */ + force_ready_override?: boolean created_at?: string updated_at?: string }> diff --git a/frontend/src/components/account/AccountCard.tsx b/frontend/src/components/account/AccountCard.tsx index 8f571f93..7c8e6262 100644 --- a/frontend/src/components/account/AccountCard.tsx +++ b/frontend/src/components/account/AccountCard.tsx @@ -1,7 +1,7 @@ import { CopyIcon } from '@/components/motion/CopyIcon' import { useEffect, useLayoutEffect, useRef, useState } from 'react' import { useSharedClock } from '@/hooks/useSharedClock' -import { Button, Card, Chip, Dropdown, Input, Label, TextArea, TextField, Tooltip } from '@heroui/react' +import { Button, Card, Checkbox, Chip, Dropdown, Input, Label, TextArea, TextField, Tooltip } from '@heroui/react' import { ArrowClockwise, ArrowSquareOut, @@ -59,7 +59,7 @@ function formatCheckinMoment(value: string, timezone: string) { // `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. export type CheckinFeedback = { - kind: 'success' | 'already' | 'skipped' | 'error' + kind: 'success' | 'already' | 'skipped' | 'error' | 'unknown' message?: string } @@ -90,6 +90,11 @@ type Props = { onEdit: () => void onToggleAuthPanel: () => void onViewModels: () => void + // Selection mode used by the bulk re-login flow. The checkbox stays out of + // the normal card layout so single-account work is unchanged. + selectable?: boolean + selected?: boolean + onSelectToggle?: () => void } function stateCopyFor(state: ReturnType, cooldown: string, t: Translate) { @@ -133,6 +138,9 @@ export function AccountCard({ onEdit, onToggleAuthPanel, onViewModels, + selectable = false, + selected = false, + onSelectToggle, }: Props) { const chipRef = useRef(null) const authRef = useRef(null) @@ -249,7 +257,17 @@ export function AccountCard({ >
-
+ {selectable ? ( + // HeroUI v3 keeps the clickable control in Checkbox.Content: a + // Checkbox without it renders the indicator as a plain span and + // nothing responds to clicks. + onSelectToggle?.()} className="shrink-0"> + + + + + ) : null} +
@@ -303,6 +321,14 @@ export function AccountCard({ {stateCopy} )} + {account.force_ready_override ? ( + + + {t('forceReadyBadge')} + + {t('forceReadyHint')} + + ) : null} {modelCooldowns.length && state !== 'cooling' ? ( @@ -377,6 +403,8 @@ export function AccountCard({ {t('checkinRecordAlready')} ) : feedback.kind === 'skipped' ? ( {t('checkinRecordSkipped')} + ) : feedback.kind === 'unknown' ? ( + {t('checkinStatusUnknown')} ) : ( {t('checkinRecordFailed')} )} diff --git a/frontend/src/components/account/BatchReloginModal.tsx b/frontend/src/components/account/BatchReloginModal.tsx new file mode 100644 index 00000000..da774218 --- /dev/null +++ b/frontend/src/components/account/BatchReloginModal.tsx @@ -0,0 +1,183 @@ +import { useEffect, useRef, useState } from 'react' +import { Button, Chip, Modal } from '@heroui/react' +import { fetchLoginStatus, startDeviceLogin } from '@/api/overview' +import type { AccountRow } from '@/lib/account' +import { ProviderMark } from '@/components/ProviderMark' + +type Translate = (key: string, vars?: Record) => string + +export type BatchLoginPhase = 'pending' | 'starting' | 'waiting' | 'ok' | 'error' | 'skipped' | 'stopped' + +export type BatchLoginRow = { + account: AccountRow + phase: BatchLoginPhase + message: string + authUrl: string +} + +const POLL_INTERVAL_MS = 2000 +const ACCOUNT_TIMEOUT_MS = 5 * 60 * 1000 + +/** + * Re-login several accounts one after another. Each account gets its own + * authorization page: the console starts the flow, the operator authorizes + * (an already signed-in browser does it silently), and polling moves on to + * the next account. Accounts are never started in parallel on purpose — several + * WorkBuddy accounts often share one SSO session, and parallel flows would hand + * the same fresh token to different account records. + */ +export function BatchReloginModal({ + isOpen, + accounts, + t, + onClose, + onFinished, +}: { + isOpen: boolean + accounts: AccountRow[] + t: Translate + onClose: () => void + onFinished: () => void +}) { + const [rows, setRows] = useState([]) + const cancelled = useRef(false) + const running = useRef(false) + + useEffect(() => { + if (!isOpen) { + cancelled.current = true + running.current = false + return + } + cancelled.current = false + setRows(accounts.map((account) => ({ account, phase: 'pending', message: '', authUrl: '' }))) + if (running.current) return + running.current = true + void run(accounts) + return () => { + cancelled.current = true + running.current = false + } + // accounts is the snapshot captured by the page when the dialog opened. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isOpen]) + + function patch(id: string, next: Partial) { + setRows((current) => current.map((row) => (row.account.id === id ? { ...row, ...next } : row))) + } + + async function run(list: AccountRow[]) { + for (const account of list) { + if (cancelled.current) { + patch(account.id, { phase: 'stopped', message: t('reloginStopped') }) + continue + } + patch(account.id, { phase: 'starting', message: t('wizardStartingSession') }) + let authUrl = '' + try { + const output = await startDeviceLogin(account.id) + authUrl = output.authUrl || '' + patch(account.id, { authUrl, phase: 'waiting', message: output.message || t('reloginWaitingAuth') }) + } catch (error) { + patch(account.id, { phase: 'error', message: error instanceof Error ? error.message : String(error) }) + continue + } + const deadline = Date.now() + ACCOUNT_TIMEOUT_MS + let settled = false + while (!settled) { + if (cancelled.current) { + patch(account.id, { phase: 'stopped', message: t('reloginStopped') }) + break + } + if (Date.now() > deadline) { + patch(account.id, { phase: 'error', message: t('reloginTimeout') }) + break + } + await new Promise((resolve) => window.setTimeout(resolve, POLL_INTERVAL_MS)) + try { + const status = await fetchLoginStatus(account.id) + const login = status.login || {} + const message = login.message || '' + if (login.status === 'ok') { + patch(account.id, { phase: 'ok', message: message || t('reloginDone') }) + settled = true + } else if (login.status === 'error') { + patch(account.id, { phase: 'error', message: message || t('reloginFailed') }) + settled = true + } else if (message) { + patch(account.id, { message }) + } + } catch (error) { + patch(account.id, { message: error instanceof Error ? error.message : String(error) }) + } + } + } + running.current = false + if (!cancelled.current) onFinished() + } + + function stop() { + cancelled.current = true + running.current = false + onClose() + } + + const finished = rows.filter((row) => row.phase === 'ok' || row.phase === 'error' || row.phase === 'stopped').length + + return ( + { if (!next) stop() }}> + + + + + {t('reloginTitle')} +

{t('reloginHint')}

+
+ +
+ {t('reloginProgress', { done: finished, total: rows.length })} +
+ {rows.map((row) => ( +
+
+ + {row.account.name || row.account.id} + {t(phaseKey(row.phase))} + {row.authUrl ? ( + + ) : null} +
+ {row.message ?

{row.message}

: null} + {row.authUrl ?

{row.authUrl}

: null} +
+ ))} +
+ + + +
+
+
+
+ ) +} + +function phaseKey(phase: BatchLoginPhase) { + switch (phase) { + case 'starting': return 'reloginPhaseStarting' + case 'waiting': return 'reloginPhaseWaiting' + case 'ok': return 'reloginPhaseDone' + case 'error': return 'reloginPhaseFailed' + case 'stopped': return 'reloginPhaseStopped' + default: return 'reloginPhasePending' + } +} + +function phaseColor(phase: BatchLoginPhase) { + if (phase === 'ok') return 'success' + if (phase === 'error') return 'danger' + if (phase === 'waiting' || phase === 'starting') return 'warning' + return 'default' +} diff --git a/frontend/src/components/account/QuotaMeter.tsx b/frontend/src/components/account/QuotaMeter.tsx index 550f6d40..1ae0ae0b 100644 --- a/frontend/src/components/account/QuotaMeter.tsx +++ b/frontend/src/components/account/QuotaMeter.tsx @@ -27,6 +27,19 @@ type Props = { provider?: string } +/** + * Honest snapshot age: the meter shows the real stored reading, so tell the + * operator how old it is instead of implying it is live. Anything ≥5 minutes + * reads as stale (the background sweep refreshes every 60s by default). + */ +function quotaAgeLabel(fetchedAt: string | undefined, t: Translate) { + if (!fetchedAt) return '' + const at = Date.parse(fetchedAt) + if (!Number.isFinite(at)) return '' + const minutes = Math.max(0, Math.round((Date.now() - at) / 60_000)) + return minutes >= 5 ? t('quotaStale', { n: minutes }) : t('quotaUsedAt', { n: minutes }) +} + function extraQuotaLines(quota: AccountQuota, remainingLabel: string, addOnLabel: string, resourcePackageLabel: string, t: Translate, provider?: string) { const addOn = quota.has_add_on && quota.add_on_available !== false ? `${addOnLabel} ${formatQuotaAmount(quota.add_on_used)} / ${formatQuotaAmount(quota.add_on_total)} ${quota.add_on_unit || 'credits'}` @@ -109,6 +122,7 @@ export function QuotaMeter({ quota, t, label, usedLabel, remainingLabel, addOnLa const color = tone === 'danger' ? 'danger' : tone === 'warn' ? 'warning' : 'success' const rootRef = useRef(null) useFillReveal(rootRef) + const age = quotaAgeLabel(quota.fetched_at, t) const valueLabel = `${usedLabel} ${used} ${unit} · ${remainingLabel} ${remaining} ${unit}${extra.length ? ` · ${extra.join(' · ')}` : ''}` if (windows.length > 0) { @@ -129,6 +143,7 @@ export function QuotaMeter({ quota, t, label, usedLabel, remainingLabel, addOnLa />
))} + {age ?
{age}
: null}
) } @@ -159,6 +174,7 @@ export function QuotaMeter({ quota, t, label, usedLabel, remainingLabel, addOnLa + {age ?
{age}
: null}
@@ -166,6 +182,7 @@ export function QuotaMeter({ quota, t, label, usedLabel, remainingLabel, addOnLa
{usedLabel} {used} {unit}
{remainingLabel} {remaining} {unit}
{extra.map((line) =>
{line}
)} + {age ?
{age}
: null}
diff --git a/frontend/src/components/overview/InflightLiveCard.tsx b/frontend/src/components/overview/InflightLiveCard.tsx index 1f9083c9..2b2fcf54 100644 --- a/frontend/src/components/overview/InflightLiveCard.tsx +++ b/frontend/src/components/overview/InflightLiveCard.tsx @@ -8,42 +8,20 @@ import { MotionPathPlugin } from 'gsap/MotionPathPlugin' import { applyLiveProjection, clampSlotConcurrency, - cloneMockInflight, - getIdleInflightSnapshot, - getMockInflightSnapshot, - isIdleInflightSnapshot, - summarizeMockInflight, - tickMockInflight, - type MockAccountSlot, - type MockInflightJob, - type MockInflightSnapshot, - type MockJobKind, -} from '@/lib/mockInflight' + cloneInflight, + emptyInflightSnapshot, + summarizeInflight, + type LiveAccountSlot, + type LiveInflightJob, + type LiveInflightSnapshot, + type LiveJobKind, +} from '@/lib/liveInflight' import { CountUp } from '@/components/overview/CountUp' import { ProviderMark } from '@/components/ProviderMark' -import { CompactSwitch } from '@/components/ui/CompactSwitch' import { ease, gsap, motionDuration, prefersReducedMotion } from '@/lib/motion' const InflightDepthChart = lazy(() => import('@/components/overview/InflightDepthChart').then((mod) => ({ default: mod.InflightDepthChart }))) -const MOCK_DEMO_STORAGE_KEY = 'cli2api_inflight_mock_demo' - -function readMockDemoPref(): boolean { - try { - return localStorage.getItem(MOCK_DEMO_STORAGE_KEY) === '1' - } catch { - return false - } -} - -function writeMockDemoPref(on: boolean) { - try { - localStorage.setItem(MOCK_DEMO_STORAGE_KEY, on ? '1' : '0') - } catch { - /* ignore quota / private mode */ - } -} - gsap.registerPlugin(CustomEase, MotionPathPlugin) const queueEase = CustomEase.get('inflightQueue') || @@ -92,7 +70,7 @@ function formatElapsed(ms: number) { } /** Busy-slot elapsed: prefer wall-clock startedAtMs + live clock; else mock elapsedMs. */ -function jobElapsedMs(job: MockInflightJob | undefined, clockMs: number): number { +function jobElapsedMs(job: LiveInflightJob | undefined, clockMs: number): number { if (!job) return 0 if (job.startedAtMs != null) return Math.max(0, clockMs - job.startedAtMs) return Math.max(0, job.elapsedMs) @@ -102,7 +80,7 @@ function jobElapsedMs(job: MockInflightJob | undefined, clockMs: number): number * Kind identity from public AffectUI demo hierarchy (llm/tool/agent washes), * remapped to project chart / foreground tokens — never a second brand palette. */ -function kindDot(kind: MockJobKind): string { +function kindDot(kind: LiveJobKind): string { switch (kind) { case 'chat': return 'bg-[color-mix(in_oklab,var(--chart-1)_55%,var(--surface))]' @@ -115,7 +93,7 @@ function kindDot(kind: MockJobKind): string { } } -function kindIcon(kind: MockJobKind) { +function kindIcon(kind: LiveJobKind) { const glyph = kind === 'embed' ? : kind === 'tools' @@ -135,7 +113,7 @@ function kindIcon(kind: MockJobKind) { ) } -function kindPill(kind: MockJobKind): string { +function kindPill(kind: LiveJobKind): string { switch (kind) { case 'chat': return 'border border-[color-mix(in_oklab,var(--chart-1)_16%,transparent)] bg-[color-mix(in_oklab,var(--chart-1)_8%,var(--surface))] text-foreground/75' @@ -155,8 +133,8 @@ function SlotBar({ idleLabel, landedCellIds, }: { - slot: MockAccountSlot - jobById: Map + slot: LiveAccountSlot + jobById: Map clockMs: number idleLabel: string /** Cell ids whose inbound fly has landed (or no-fly grace / auto-land). */ @@ -264,10 +242,10 @@ function SlotBar({ /** * Overview summary: Agent Queue feel over cli2api pool/inflight concepts. - * Default collapsed — no /api/live consume and no mock loop until expanded + * Default collapsed — no /api/live consume until expanded * (toggle or LiveStrip「当前并发」). When open, project live workers / - * sticky (in-progress only — no rate-limit remaining chips/bands); mock tick - * only when 示意/demo is on (default off). Session Done/Failed reset on each expand. + * sticky (in-progress only — no rate-limit remaining chips/bands). Only real + * /api/live data is shown; each expand starts a fresh session. * Motion timings from public AffectUI Agent Queue demo (mapped to project * tokens). Link targets `/live` later — no Pause/Cancel/stepper. */ @@ -275,25 +253,22 @@ export function InflightLiveCard({ t, snapshot, live = null, + liveError = null, expanded: expandedProp, onExpandedChange, defaultExpanded = false, - forceMockDemo = false, - mockPace = 1, bare = false, }: { t: T - snapshot?: MockInflightSnapshot + snapshot?: LiveInflightSnapshot /** Parent /api/live snapshot — only passed while expanded so the card does not drive fetches. */ live?: LiveSnapshot | null + /** Real /api/live fetch error, shown instead of pretending data exists. */ + liveError?: string | null expanded?: boolean onExpandedChange?: (open: boolean) => void defaultExpanded?: boolean - /** Login showcase: play the mock loop without reading or writing the overview demo preference. */ - forceMockDemo?: boolean - /** Scale mock time. Login uses a slower pace; overview stays at 1. */ - mockPace?: number - /** Login showcase: animation only — no title, chrome, demo switch, or view-all link. */ + /** Login showcase: animation only — no title, chrome, or view-all link. */ bare?: boolean }) { const controlled = snapshot !== undefined @@ -304,17 +279,11 @@ export function InflightLiveCard({ if (expandedProp === undefined) setUncontrolledOpen(open) } - const [mockDemoEnabled, setMockDemoEnabled] = useState(() => forceMockDemo || readMockDemoPref()) - const setMockDemo = (on: boolean) => { - setMockDemoEnabled(on) - if (!forceMockDemo) writeMockDemoPref(on) - } - const [liveSnap, setLiveSnap] = useState(() => - cloneMockInflight(snapshot ?? getIdleInflightSnapshot()), + const [liveSnap, setLiveSnap] = useState(() => + cloneInflight(snapshot ?? emptyInflightSnapshot()), ) - const [useMockFallback, setUseMockFallback] = useState(false) const [sticky, setSticky] = useState(null) - /** Wall clock for live startedAtMs elapsed (mock uses tickMockInflight elapsedMs). */ + /** Wall clock for live startedAtMs elapsed. */ const [clockMs, setClockMs] = useState(() => Date.now()) /** * Display-only land gate: occupied chrome (model + elapsed) shows only after @@ -352,10 +321,10 @@ export function InflightLiveCard({ ) } const snap = controlled ? snapshot! : liveSnap - const summary = useMemo(() => summarizeMockInflight(snap), [snap]) + const summary = useMemo(() => summarizeInflight(snap), [snap]) const rootRef = useRef(null) const enteredRef = useRef(false) - const prevRef = useRef(snap) + const prevRef = useRef(snap) /** Last painted rects — handoff flies read these after the source unmounts. */ const rectCache = useRef<{ wait: Record @@ -387,79 +356,40 @@ export function InflightLiveCard({ const viewingSessionRef = useRef(false) // External snapshot (tests) wins. Otherwise: when expanded, project /api/live - // (even idle — no mock throughput/p95/depth bleed). Mock tick only if - // live is null AND 示意/demo is on (default off → calm idle zeros). + // (even idle — zeros mean the pool really is idle, never a synthetic demo). // useLayoutEffect so the first expanded paint is already clean. useLayoutEffect(() => { if (controlled) { - setLiveSnap(cloneMockInflight(snapshot!)) - setUseMockFallback(false) + setLiveSnap(cloneInflight(snapshot!)) setSticky(null) viewingSessionRef.current = false return } if (!expanded) { - setUseMockFallback(false) viewingSessionRef.current = false return } if (live !== null) { - setUseMockFallback(false) setSticky(live.sticky) setClockMs(Date.now()) // First live projection this expand: keep enteredRef false so soft // bootstrap syncLandGate('all') and never treats hydrate as flies. if (!viewingSessionRef.current) enteredRef.current = false setLiveSnap((prev) => { - // New viewing session → force first projection (totals 0, depth reset). - const base = !viewingSessionRef.current - ? { ...cloneMockInflight(prev), waitP95Ms: 1, totals: { done: 0, failed: 0 } } - : prev + // New viewing session starts from an honest empty board: totals 0, + // depth zeros. Every number afterwards comes from /api/live. + const base = !viewingSessionRef.current ? emptyInflightSnapshot() : prev viewingSessionRef.current = true return applyLiveProjection(base, live) }) return } - // live === null → optional Stage-1 mock (示意) or calm idle board. + // live === null → no real data yet. Show the honest empty board. setSticky(null) viewingSessionRef.current = false enteredRef.current = false - if (mockDemoEnabled) { - setUseMockFallback(true) - setLiveSnap((prev) => - isIdleInflightSnapshot(prev) - ? cloneMockInflight(getMockInflightSnapshot()) - : prev, - ) - } else { - setUseMockFallback(false) - setLiveSnap(cloneMockInflight(getIdleInflightSnapshot())) - } - }, [controlled, snapshot, expanded, live, mockDemoEnabled]) - - // Mock raf loop — gated on useMockFallback + 示意 on (live === null only). - useEffect(() => { - if (controlled || !expanded || !useMockFallback || !mockDemoEnabled || live !== null) return - if (prefersReducedMotion()) return - let raf = 0 - let last = performance.now() - let alive = true - const step = (now: number) => { - if (!alive) return - const dt = now - last - if (!document.hidden && dt >= 260) { - last = now - const pace = Number.isFinite(mockPace) ? Math.min(1, Math.max(0.2, mockPace ?? 1)) : 1 - setLiveSnap((prev) => tickMockInflight(prev, dt * pace)) - } - raf = requestAnimationFrame(step) - } - raf = requestAnimationFrame(step) - return () => { - alive = false - cancelAnimationFrame(raf) - } - }, [controlled, expanded, useMockFallback, mockDemoEnabled, live, mockPace]) + setLiveSnap(cloneInflight(emptyInflightSnapshot())) + }, [controlled, snapshot, expanded, live]) // Elapsed tick (~150ms): wall-clock since started_at so busy slots don't stick at 0.0s between /api/live polls. useEffect(() => { @@ -612,8 +542,7 @@ export function InflightLiveCard({ const bootstrapped = controlled || viewingSessionRef.current || - (live === null && mockDemoEnabled && useMockFallback) || - (live === null && !mockDemoEnabled && isIdleInflightSnapshot(snap)) + live === null if (!bootstrapped) { gsap.set(root, { opacity: 0 }) } else { @@ -661,7 +590,7 @@ export function InflightLiveCard({ from: DOMRect | HTMLElement | null | undefined, to: DOMRect | HTMLElement | null | undefined, label: string, - kind: MockJobKind, + kind: LiveJobKind, tone: 'run' | 'ok' | 'danger' | 'retry', beatEl?: HTMLElement | null, onLand?: () => void, @@ -961,7 +890,7 @@ export function InflightLiveCard({ const flyQueueToSlot = ( id: string, label: string, - kind: MockJobKind, + kind: LiveJobKind, workerId: string, ) => { if (!workerId || flewFromQueue.has(id)) return @@ -1113,7 +1042,7 @@ export function InflightLiveCard({ type CellExit = { id: string name: string - kind: MockJobKind + kind: LiveJobKind workerId: string cellIndex: number } @@ -1381,11 +1310,11 @@ export function InflightLiveCard({ } refreshCache() - }, [snap, expanded, controlled, useMockFallback, mockDemoEnabled, live]) + }, [snap, expanded, controlled, live]) const depthLabel = t('inflightDepthHint', { n: summary.depthNow }) - const liveBadge = !useMockFallback && Boolean(live) - const mockBadge = useMockFallback && mockDemoEnabled && !live + const liveBadge = Boolean(live) + const offlineBadge = !live && Boolean(liveError) const stickyBindings = sticky?.bindings ?? 0 return ( @@ -1460,8 +1389,8 @@ export function InflightLiveCard({ {liveBadge ? t('inflightLiveBadge') - : mockBadge - ? t('inflightMockBadge') + : offlineBadge + ? t('inflightOfflineBadge') : t('inflightIdleBadge')} {expanded && stickyBindings > 0 ? ( @@ -1494,21 +1423,6 @@ export function InflightLiveCard({ )} - {expanded && !controlled ? ( -
e.stopPropagation()} - onKeyDown={(e) => e.stopPropagation()} - > - -
- ) : null} } @@ -1526,8 +1440,15 @@ export function InflightLiveCard({ suffix={`/${summary.workerSlots}`} /> - + {/* The live API reports no P95 yet: render an honest dash instead + of a fabricated 0ms. */} + 0 ? snap.waitP95Ms : null} kind="ms" /> + {liveError ? ( +
+ {liveError} +
+ ) : null} {/* Waiting → account-slot bars → Done/Failed (AffectUI Agent Queue flow) */}
@@ -1659,7 +1580,8 @@ function Metric({ warn, }: { label: string - value: number + /** null renders an honest "—" (not measured), never a fabricated zero. */ + value: number | null suffix?: string kind?: 'int' | 'ms' warn?: boolean @@ -1672,7 +1594,11 @@ function Metric({ warn ? 'text-[var(--il-warn-fg)]' : 'text-foreground' }`} > - + {value == null ? ( + — + ) : ( + + )} {suffix ? {suffix} : null}
diff --git a/frontend/src/hooks/useAccountEvents.ts b/frontend/src/hooks/useAccountEvents.ts new file mode 100644 index 00000000..41e5c756 --- /dev/null +++ b/frontend/src/hooks/useAccountEvents.ts @@ -0,0 +1,86 @@ +import { useEffect, useRef, useState } from 'react' +import { openEventStream, type EventStreamStatus, type ServerEvent } from '@/api/events' + +const MIN_BACKOFF_MS = 1000 +const MAX_BACKOFF_MS = 15_000 + +/** + * Console real-time channel: streams real runtime events from `GET /api/events`. + * Reconnects with capped exponential backoff, replays from the last seen seq + * (the bus ring buffers 1024 events), and tears the connection down while the + * document is hidden so a background tab costs nothing. `status` lets a page + * degrade to polling exactly when the stream is not live. + */ +export function useAccountEvents( + onEvent: (event: ServerEvent) => void, + opts?: { enabled?: boolean }, +): { status: EventStreamStatus; lastSeq: number } { + const handlerRef = useRef(onEvent) + useEffect(() => { + handlerRef.current = onEvent + }, [onEvent]) + const enabled = opts?.enabled !== false + const [status, setStatus] = useState('connecting') + const [visible, setVisible] = useState(() => (typeof document === 'undefined' ? true : !document.hidden)) + const [lastSeq, setLastSeq] = useState(0) + const lastSeqRef = useRef(0) + + useEffect(() => { + if (typeof document === 'undefined') return + const onVisibility = () => setVisible(!document.hidden) + document.addEventListener('visibilitychange', onVisibility) + return () => document.removeEventListener('visibilitychange', onVisibility) + }, []) + + useEffect(() => { + if (!enabled || !visible) return + let disposed = false + const controller = new AbortController() + let backoff = MIN_BACKOFF_MS + let timer: number | null = null + setStatus((current) => (current === 'live' ? current : 'connecting')) + + const run = async () => { + while (!disposed) { + try { + await openEventStream({ + lastSeq: lastSeqRef.current, + signal: controller.signal, + onOpen: () => { + backoff = MIN_BACKOFF_MS + if (!disposed) setStatus('live') + }, + onEvent: (event) => { + if (event.seq > lastSeqRef.current) { + lastSeqRef.current = event.seq + setLastSeq(event.seq) + } + if (!disposed) handlerRef.current(event) + }, + }) + if (disposed) break + setStatus('offline') + } catch { + if (disposed || controller.signal.aborted) break + setStatus('offline') + } + // Wait before reconnecting; the delay doubles until the cap so a + // down console does not get hammered. + await new Promise((resolve) => { + timer = window.setTimeout(resolve, backoff) + }) + timer = null + backoff = Math.min(MAX_BACKOFF_MS, backoff * 2) + } + } + + void run() + return () => { + disposed = true + controller.abort() + if (timer != null) window.clearTimeout(timer) + } + }, [enabled, visible]) + + return { status, lastSeq } +} diff --git a/frontend/src/hooks/useLive.ts b/frontend/src/hooks/useLive.ts index 716475e0..5a779973 100644 --- a/frontend/src/hooks/useLive.ts +++ b/frontend/src/hooks/useLive.ts @@ -21,6 +21,7 @@ export const LIVE_POLL_EXPANDED_MS = 800 export function useLive(opts?: { intervalMs?: number }) { const intervalMs = opts?.intervalMs ?? LIVE_POLL_MS const [live, setLive] = useState(null) + const [error, setError] = useState(null) const [samples, setSamples] = useState([]) useEffect(() => { @@ -32,11 +33,17 @@ export function useLive(opts?: { intervalMs?: number }) { .then((data) => { if (cancelled) return setLive(data) + setError(null) // Keep ~60s of sparkline history even when expanded poll is faster. const keep = Math.max(LIVE_SAMPLES, Math.round(60_000 / intervalMs)) setSamples((prev) => [...prev, { at: Date.now(), value: data.in_flight }].slice(-keep)) }) - .catch(() => { /* keep last good snapshot */ }) + .catch((err: unknown) => { + // Keep the last good snapshot, but surface the real failure instead of + // pretending the pool is idle. + if (cancelled) return + setError(err instanceof Error ? err.message : String(err)) + }) } const start = () => { if (timer || document.hidden) return @@ -57,5 +64,5 @@ export function useLive(opts?: { intervalMs?: number }) { } }, [intervalMs]) - return { live, samples } + return { live, samples, error } } diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.ts index aa6c78df..1268796e 100644 --- a/frontend/src/i18n/messages.ts +++ b/frontend/src/i18n/messages.ts @@ -44,6 +44,27 @@ export const messages: Record = { navAccounts: 'Accounts', checkinDefaultsTitle: 'Automatic check-in', checkinDefaultsHint: 'Set a default time for each provider. Accounts following the default pick up changes automatically; custom times stay unchanged.', + reloginEntry: 'Re-login', + reloginSelected: 'Selected {count}', + reloginSelectPage: 'Select page', + reloginClear: 'Clear selection', + reloginConfirm: 'Re-login selected', + reloginSelectAccount: 'Select account', + reloginTitle: 'Re-login accounts', + reloginHint: 'Accounts are authorized one at a time: open each account login page, sign in, and the console moves on to the next automatically. An account whose browser session is already signed in completes without typing.', + reloginProgress: '{done}/{total} finished', + reloginOpenPage: 'Open login page', + reloginWaitingAuth: 'Waiting for authorization', + reloginDone: 'Signed in', + reloginFailed: 'Login failed', + reloginTimeout: 'Timed out waiting for authorization', + reloginStopped: 'Cancelled', + reloginPhasePending: 'Queued', + reloginPhaseStarting: 'Starting', + reloginPhaseWaiting: 'Waiting', + reloginPhaseDone: 'Done', + reloginPhaseFailed: 'Failed', + reloginPhaseStopped: 'Cancelled', checkinDisabledAccountsTitle: 'Check in disabled accounts', checkinDisabledAccountsHint: 'When enabled, accounts disabled for chat can still run their opted-in automatic check-in. Manual check-in remains unavailable for disabled accounts.', checkinDisabledAccountsStatus: 'Current status', @@ -157,6 +178,19 @@ export const messages: Record = { modelPoolFailover: 'Failover', modelPoolMaxAttempts: 'Max attempts', modelPoolMaxAttemptsHint: 'Maximum providers tried before the request fails (1-64).', + modelPoolCapabilities: 'Model capabilities', + modelPoolCapabilitiesHint: 'What the logical model advertises in /v1/models. Leave automatic to use the conservative intersection of its members.', + modelPoolContextLength: 'Context length', + modelPoolContextLengthHint: '0 = automatic: the smallest window every member declares.', + modelPoolMaxOutput: 'Max output', + modelPoolMaxOutputHint: '0 = automatic: the smallest output ceiling every member declares.', + modelPoolReasoningLevels: 'Reasoning levels', + modelPoolReasoningLevelsHint: 'Levels the logical model advertises. Select none to use the levels every member shares.', + modelPoolReasoningDefault: 'Default level', + modelPoolReasoningDefaultHint: 'Advertised as the default effort. Clients may still request any other advertised level.', + modelPoolReasoningAuto: 'Automatic', + modelPoolCapabilitiesInvalid: 'Context length and max output must be 0 or at least 1024, and max output cannot exceed the context length.', + modelPoolReasoningInvalid: 'The default level must be one of the selected reasoning levels.', modelPoolMembers: 'Provider models', modelPoolMembersHint: 'Only connected providers and the models enabled in their provider settings are selectable. The provider account pool picks the serving account automatically; order sets priority.', modelPoolAddMember: 'Add provider model', @@ -757,10 +791,8 @@ export const messages: Record = { livePeak: 'peak {n}', liveSaturated: 'Saturated', inflightTitle: 'Live now', - inflightMockBadge: 'mock', + inflightOfflineBadge: 'offline', inflightIdleBadge: 'idle', - inflightMockToggle: 'Demo', - inflightMockToggleAria: 'Show mock demo when live is unavailable', inflightLiveBadge: 'live', inflightHint: 'Slots · in-flight · cooldown', inflightCardAria: 'Open live detail', @@ -802,6 +834,8 @@ export const messages: Record = { toastCheckingInAll: 'Checking in {done} of {total}…', toastCheckedInAll: 'Checked in {checked}, skipped {skipped}', toastCheckedInAllFailed: 'Checked in {checked}, skipped {skipped}, failed {failed}', + checkinRewardSuffix: ' · +{credits} credits', + checkinRewardTotal: '{credits} credits granted in total', lastCheckin: 'Last check-in', lastCheckinNone: 'No check-in yet', checkinStatus: 'Check-in', @@ -839,6 +873,11 @@ export const messages: Record = { quota: 'Quota', quotaUsed: 'Used', + quotaUsedAt: 'quota read {n} min ago', + quotaStale: 'quota snapshot is {n} min old', + forceReadyBadge: 'Force ready', + forceReadyHint: 'A local force-ready marker is active: this account enters the pool without a real probe. The quota shown still comes from the last real upstream snapshot.', + eventsOffline: 'Live stream offline — polling every 5s', quotaRemaining: 'Remaining', quotaDaily: 'Daily quota', quotaWeekly: 'Weekly quota', @@ -1166,6 +1205,27 @@ export const messages: Record = { navAccounts: '账号', checkinDefaultsTitle: '自动签到', checkinDefaultsHint: '按供应商设置默认时间。跟随默认的账号会立即采用新时间,账号自定义时间不受影响。', + reloginEntry: '重新登录', + reloginSelected: '已选 {count} 个', + reloginSelectPage: '全选本页', + reloginClear: '清空选择', + reloginConfirm: '确定重新登录', + reloginSelectAccount: '选择账号', + reloginTitle: '重新登录账号', + reloginHint: '按顺序逐个授权:打开每个账号的登录页完成登录后,控制台会自动进入下一个。浏览器已登录同一身份时会自动完成,无需输入。', + reloginProgress: '已完成 {done}/{total}', + reloginOpenPage: '打开登录页', + reloginWaitingAuth: '等待授权', + reloginDone: '已登录', + reloginFailed: '登录失败', + reloginTimeout: '等待授权超时', + reloginStopped: '已取消', + reloginPhasePending: '待处理', + reloginPhaseStarting: '启动中', + reloginPhaseWaiting: '等待授权', + reloginPhaseDone: '成功', + reloginPhaseFailed: '失败', + reloginPhaseStopped: '已取消', checkinDisabledAccountsTitle: '停用账号也自动签到', checkinDisabledAccountsHint: '开启后,停用聊天功能的账号仍可执行已开启的自动签到;停用账号仍不可手动签到。', checkinDisabledAccountsStatus: '当前状态', @@ -1279,6 +1339,19 @@ export const messages: Record = { modelPoolFailover: '故障转移', modelPoolMaxAttempts: '最大尝试次数', modelPoolMaxAttemptsHint: '请求失败前最多尝试的供应商数量(1-64)。', + modelPoolCapabilities: '模型能力', + modelPoolCapabilitiesHint: '逻辑模型在 /v1/models 中对外声明的参数。留空自动时取各成员保守的交集。', + modelPoolContextLength: '上下文长度', + modelPoolContextLengthHint: '0 = 自动:取所有成员声明的最小窗口。', + modelPoolMaxOutput: '最大输出', + modelPoolMaxOutputHint: '0 = 自动:取所有成员声明的最小输出上限。', + modelPoolReasoningLevels: '思考档位', + modelPoolReasoningLevelsHint: '逻辑模型对外声明的思考档位。不选时取所有成员共有的档位。', + modelPoolReasoningDefault: '默认档位', + modelPoolReasoningDefaultHint: '作为默认思考强度对外声明;客户端仍可请求任一已声明的档位。', + modelPoolReasoningAuto: '自动', + modelPoolCapabilitiesInvalid: '上下文长度和最大输出需为 0 或至少 1024,且最大输出不能超过上下文长度。', + modelPoolReasoningInvalid: '默认档位必须从已选中的思考档位中选择。', modelPoolMembers: '供应商模型', modelPoolMembersHint: '仅可选出已接入的供应商,以及对应供应商设置中启用的模型。账号由供应商账号池自动选择,顺序即优先级。', modelPoolAddMember: '添加供应商模型', @@ -1879,10 +1952,8 @@ export const messages: Record = { livePeak: '峰值 {n}', liveSaturated: '已满载', inflightTitle: '实时进行中', - inflightMockBadge: '示意', + inflightOfflineBadge: '未连接', inflightIdleBadge: '空闲', - inflightMockToggle: '示意', - inflightMockToggleAria: '无实时数据时显示示意动画', inflightLiveBadge: '实时', inflightHint: '槽位 · 进行中 · 冷却', inflightCardAria: '打开实时详情', @@ -1924,6 +1995,8 @@ export const messages: Record = { toastCheckingInAll: '正在签到 {done}/{total}…', toastCheckedInAll: '已签到 {checked} 个,跳过 {skipped} 个', toastCheckedInAllFailed: '已签到 {checked} 个,跳过 {skipped} 个,失败 {failed} 个', + checkinRewardSuffix: ' · +{credits} 积分', + checkinRewardTotal: '本次共获得 {credits} 积分', lastCheckin: '最近签到', lastCheckinNone: '还没有签到记录', checkinStatus: '签到', @@ -1961,6 +2034,11 @@ export const messages: Record = { quota: '额度', quotaUsed: '已用', + quotaUsedAt: '额度 {n} 分钟前读取', + quotaStale: '额度快照已过期 {n} 分钟', + forceReadyBadge: '强制就绪', + forceReadyHint: '本地强制就绪标记生效中:该账号跳过真实探测直接进池;这里显示的额度仍来自最近一次真实上游快照。', + eventsOffline: '实时通道未连接,已降级为 5 秒轮询', quotaRemaining: '剩余', quotaDaily: '日额度', quotaWeekly: '周额度', diff --git a/frontend/src/lib/mockInflight.ts b/frontend/src/lib/liveInflight.ts similarity index 51% rename from frontend/src/lib/mockInflight.ts rename to frontend/src/lib/liveInflight.ts index 19ebfa74..a4c5e1ce 100644 --- a/frontend/src/lib/mockInflight.ts +++ b/frontend/src/lib/liveInflight.ts @@ -1,31 +1,28 @@ /** - * Phase-1 fake snapshot for Overview「实时进行中」. - * Shaped like cli2api runtime concepts (not a parallel control plane): - * jobs ≈ in-flight / waiting proxy requests - * workers ≈ account slots currently (or recently) hitting upstream - * rateLimits≈ cooldown / provider rate-limit windows - * depth ≈ recent waiting + concurrency approx - * totals ≈ session Done/Failed while viewing (mock tick; live bumps) - * Stage-3 swaps workers/rateLimits/sticky/queue onto /api/live (LiveWorker, - * LiveRateLimit, LiveSticky, LiveJob); depth stays client-rolled. Do not invent - * a parallel /api/inflight*. + * Real inflight projection for Overview「实时进行中」. * - * Live loop (`tickMockInflight`) mirrors public AffectUI Motion prose: - * progress fill, queue→worker handoff, DONE/FAILED stack, depth scroll — - * Stage-1 only; real /api/live projection stays read-only. + * Everything rendered comes from /api/live: workers (account slots + their + * in-flight cells), rate-limit/cooldown windows, the selecting queue, occupied + * requests, sticky stats and RPM. There is no seed, no tick, and no demo mode: + * when live data is unavailable the card shows an honest empty state. */ -export type MockJobKind = 'chat' | 'embed' | 'tools' | 'other' -export type MockJobStatus = 'queued' | 'running' | 'done' | 'failed' +export type LiveJobKind = 'chat' | 'embed' | 'tools' | 'other' +export type LiveJobStatus = 'queued' | 'running' | 'done' | 'failed' -export type MockJobPriority = 'high' | 'normal' | 'low' +export type LiveJobPriority = 'high' | 'normal' | 'low' -export type MockInflightJob = { +/** Recent concurrency depth window kept for the sparkline. */ +const DEPTH_SERIES_LEN = 24 +/** Queue depth at which the waiting metric turns amber (UI guideline). */ +const BACKPRESSURE_DEPTH = 6 + +export type LiveInflightJob = { id: string /** Short label — model / route style. */ name: string - kind: MockJobKind - status: MockJobStatus + kind: LiveJobKind + status: LiveJobStatus /** Account id holding the request when running. */ accountId?: string progress: number @@ -36,13 +33,13 @@ export type MockInflightJob = { /** Sticky session hint (affinity hit). */ sticky?: boolean /** AffectUI priority — high lands at back then glides past. */ - priority?: MockJobPriority + priority?: LiveJobPriority /** Retry attempt count when failed job slides back to queue. */ attempt?: number } /** One occupied concurrency cell on an account slot bar. */ -export type MockSlotCell = { +export type LiveSlotCell = { id: string /** Requested model / short label. */ name: string @@ -57,7 +54,7 @@ export type MockSlotCell = { pendingInbound?: boolean } -export type MockAccountSlot = { +export type LiveAccountSlot = { id: string /** Account display name. */ name: string @@ -77,10 +74,10 @@ export type MockAccountSlot = { /** Current occupied concurrency cells (in_flight). */ inFlight?: number /** Per-cell model + elapsed (length ≤ inFlight). */ - cells?: MockSlotCell[] + cells?: LiveSlotCell[] } -export type MockRateLimitWindow = { +export type LiveRateLimitWindow = { id: string label: string /** Remaining cooldown / rate-limit window in ms. */ @@ -91,17 +88,17 @@ export type MockRateLimitWindow = { } /** One job that just landed on Done or Failed this tick (GSAP fly-out routing). */ -export type MockCompletion = { +export type LiveCompletion = { id: string name: string - kind: MockJobKind + kind: LiveJobKind ok: boolean } -export type MockInflightSnapshot = { - jobs: MockInflightJob[] - workers: MockAccountSlot[] - rateLimits: MockRateLimitWindow[] +export type LiveInflightSnapshot = { + jobs: LiveInflightJob[] + workers: LiveAccountSlot[] + rateLimits: LiveRateLimitWindow[] /** Recent waiting+concurrency depth (oldest → newest). */ depthSeries: number[] /** Soft backpressure guide on the depth chart. */ @@ -117,81 +114,10 @@ export type MockInflightSnapshot = { * Live `totals` are session counters (since expand/mount), bumped from * completions — not historical DB totals. priorIsLive uses waitP95Ms === 0. */ - completions?: MockCompletion[] -} - -/** Stable demo seed — deterministic for first paint / screenshots. */ -export const MOCK_INFLIGHT: MockInflightSnapshot = { - generatedAt: 0, - backpressure: 6, - throughputPerMin: 42, - waitP95Ms: 2800, - totals: { done: 186, failed: 4 }, - workers: [ - { - id: 'acc-wb-a1', name: 'WorkBuddy', provider: 'workbuddy', busy: true, progress: 0.72, jobId: 'j1', concurrency: 4, inFlight: 3, - cells: [ - { id: 'j1', name: 'glm-5.2', startedAtMs: 0, elapsedMs: 11_200 }, - { id: 'j1b', name: 'kimi-k2.7-code', startedAtMs: 0, elapsedMs: 8400 }, - { id: 'j1c', name: 'qwen3-embedding', startedAtMs: 0, elapsedMs: 4100 }, - ], - }, - { - id: 'acc-wb-a2', name: 'Zhipu', provider: 'zhipu', busy: true, progress: 0.41, jobId: 'j2', rateLimited: true, concurrency: 2, inFlight: 1, - cells: [{ id: 'j2', name: 'deepseek-v4-pro', startedAtMs: 0, elapsedMs: 9400 }], - }, - { - id: 'acc-qd-b1', name: 'Qoder', provider: 'qoder', busy: true, progress: 0.88, jobId: 'j3', concurrency: 1, inFlight: 1, - cells: [{ id: 'j3', name: 'glm-5.3', startedAtMs: 0, elapsedMs: 6200 }], - }, - { id: 'acc-qd-b2', name: 'Kimi', provider: 'kimi', busy: false, progress: 0, concurrency: 4, inFlight: 0, cells: [] }, - { - id: 'acc-trae-c1', name: 'Trae', provider: 'trae', busy: true, progress: 0.23, jobId: 'j4', concurrency: 3, inFlight: 2, - cells: [ - { id: 'j4', name: 'qwen3-coder', startedAtMs: 0, elapsedMs: 3100 }, - { id: 'j4b', name: 'glm-5.3-flash', startedAtMs: 0, elapsedMs: 1800 }, - ], - }, - { id: 'acc-codex-d1', name: 'Codex', provider: 'codex', busy: false, progress: 0, rateLimited: true, concurrency: 2, inFlight: 0, cells: [] }, - ], - jobs: [ - { id: 'j1', name: 'glm-5.2', kind: 'chat', status: 'running', accountId: 'acc-wb-a1', progress: 0.72, elapsedMs: 11_200, sticky: true }, - { id: 'j1b', name: 'kimi-k2.7-code', kind: 'chat', status: 'running', accountId: 'acc-wb-a1', progress: 0.55, elapsedMs: 8400 }, - { id: 'j1c', name: 'qwen3-embedding', kind: 'embed', status: 'running', accountId: 'acc-wb-a1', progress: 0.3, elapsedMs: 4100 }, - { id: 'j2', name: 'deepseek-v4-pro', kind: 'embed', status: 'running', accountId: 'acc-wb-a2', progress: 0.41, elapsedMs: 9400 }, - { id: 'j3', name: 'glm-5.3', kind: 'chat', status: 'running', accountId: 'acc-qd-b1', progress: 0.88, elapsedMs: 6200 }, - { id: 'j4', name: 'qwen3-coder', kind: 'tools', status: 'running', accountId: 'acc-trae-c1', progress: 0.23, elapsedMs: 3100 }, - { id: 'j4b', name: 'glm-5.3-flash', kind: 'chat', status: 'running', accountId: 'acc-trae-c1', progress: 0.15, elapsedMs: 1800 }, - { id: 'j5', name: 'deepseek-v4.1-flash', kind: 'chat', status: 'queued', progress: 0, elapsedMs: 7200 }, - { id: 'j6', name: 'glm-5.2', kind: 'chat', status: 'queued', progress: 0, elapsedMs: 5100 }, - { id: 'j7', name: 'kimi-k2.7-code', kind: 'chat', status: 'queued', progress: 0, elapsedMs: 2800, sticky: true, priority: 'high' }, - { id: 'j8', name: 'qwen3-embedding', kind: 'embed', status: 'queued', progress: 0, elapsedMs: 1400 }, - { id: 'j9', name: 'qwen3-coder', kind: 'tools', status: 'queued', progress: 0, elapsedMs: 900 }, - { id: 'j10', name: 'glm-5.3-flash', kind: 'chat', status: 'queued', progress: 0, elapsedMs: 600 }, - { id: 'j11', name: 'deepseek-v4-pro', kind: 'embed', status: 'queued', progress: 0, elapsedMs: 400 }, - { id: 'j12', name: 'glm-5.3', kind: 'chat', status: 'queued', progress: 0, elapsedMs: 200, priority: 'high' }, - ], - rateLimits: [ - { id: 'rl1', label: 'Zhipu 限流', remainingMs: 97_000, from: 0.55, until: 0.72 }, - { id: 'rl2', label: 'Codex 冷却', remainingMs: 41_000, from: 0.82, until: 1 }, - ], - // Soft hump under rate-limit, then partial drain. - depthSeries: [1, 1, 2, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 4, 5, 6, 5, 4, 3, 3, 2, 3, 4, 3], + completions?: LiveCompletion[] } -const SEED_NAMES: Array<{ name: string; kind: MockJobKind; sticky?: boolean }> = [ - { name: 'glm-5.3', kind: 'chat' }, - { name: 'qwen3-embedding', kind: 'embed' }, - { name: 'qwen3-coder', kind: 'tools' }, - { name: 'glm-5.3-flash', kind: 'chat', sticky: true }, - { name: 'deepseek-v4.1-flash', kind: 'chat' }, - { name: 'deepseek-v4-pro', kind: 'embed' }, - { name: 'kimi-k2.7-code', kind: 'chat' }, -] - -let seq = 100 - -export function cloneMockInflight(snap: MockInflightSnapshot = MOCK_INFLIGHT): MockInflightSnapshot { +export function cloneInflight(snap: LiveInflightSnapshot): LiveInflightSnapshot { return { ...snap, workers: snap.workers.map((w) => ({ @@ -207,215 +133,19 @@ export function cloneMockInflight(snap: MockInflightSnapshot = MOCK_INFLIGHT): M } } -export function getMockInflightSnapshot(): MockInflightSnapshot { - return cloneMockInflight() -} - -/** Calm empty board when live is unavailable and mock 示意 is off. */ -export function getIdleInflightSnapshot(): MockInflightSnapshot { - const n = Math.max(1, MOCK_INFLIGHT.depthSeries.length) +/** Honest empty board: no fabricated numbers, used until /api/live responds. */ +export function emptyInflightSnapshot(): LiveInflightSnapshot { return { generatedAt: Date.now(), - backpressure: MOCK_INFLIGHT.backpressure, + backpressure: BACKPRESSURE_DEPTH, throughputPerMin: 0, waitP95Ms: 0, totals: { done: 0, failed: 0 }, workers: [], jobs: [], rateLimits: [], - depthSeries: Array.from({ length: n }, () => 0), - } -} - -export function isIdleInflightSnapshot(snap: MockInflightSnapshot): boolean { - return ( - snap.jobs.length === 0 && - snap.workers.length === 0 && - snap.throughputPerMin === 0 && - (snap.totals?.done ?? 0) === 0 && - (snap.totals?.failed ?? 0) === 0 - ) -} - -/** - * Advance the Stage-1 mock one frame. Mirrors public AffectUI loop: - * progress fills (frozen under rate-limit), completed jobs → Done/Failed, - * free slots pull the front of the waiting queue, depth series scrolls, - * rate-limit remaining counts down. Deterministic-ish for a given dt. - */ -export function tickMockInflight(prev: MockInflightSnapshot, dtMs: number): MockInflightSnapshot { - const dt = Math.max(16, Math.min(500, dtMs)) - const next = cloneMockInflight(prev) - next.generatedAt = (prev.generatedAt || 0) + dt - - // Countdown rate-limit windows; clear expired → unfreeze matching slots. - next.rateLimits = next.rateLimits - .map((r) => ({ ...r, remainingMs: Math.max(0, r.remainingMs - dt) })) - .filter((r) => r.remainingMs > 0) - // Keep rateLimited flag in sync with remaining windows (seed label → slot). - for (const w of next.workers) { - if (w.id === 'acc-wb-a2') w.rateLimited = next.rateLimits.some((r) => r.label.includes('Zhipu')) - else if (w.id === 'acc-codex-d1') w.rateLimited = next.rateLimits.some((r) => r.label.includes('Codex')) - } - - const jobById = new Map(next.jobs.map((j) => [j.id, j])) - - // Per-cell elapsed + independent progress (rate-limit freezes the account). - for (const w of next.workers) { - if (w.cells?.length) { - for (const c of w.cells) c.elapsedMs += dt - } - if (w.rateLimited) continue - let maxP = 0 - for (const c of w.cells ?? []) { - const job = jobById.get(c.id) - if (!job || job.status !== 'running') continue - job.elapsedMs = c.elapsedMs - // ~8–14s per cell from current progress, paced by dt + cell id. - const speed = 0.045 + (c.id.charCodeAt(c.id.length - 1) % 5) * 0.008 - job.progress = Math.min(1, job.progress + speed * (dt / 1000)) - maxP = Math.max(maxP, job.progress) - } - if ((w.cells?.length ?? 0) > 0) { - w.progress = maxP - w.busy = true - w.jobId = w.cells![0].id - w.inFlight = w.cells!.length - } - } - - // Finish ONE ready cell per worker per tick so each concurrency cell gets - // its own Done/Failed fly-out (do not clear the whole account at once). - const finished: Array<{ jobId: string; workerId: string; ok: boolean }> = [] - for (const w of next.workers) { - if (w.rateLimited || !(w.cells?.length)) continue - const ready = w.cells.find((c) => { - const j = jobById.get(c.id) - return Boolean(j && j.status === 'running' && j.progress >= 0.995) - }) - if (!ready) continue - const ok = (ready.id.charCodeAt(1) + Math.floor(next.generatedAt / 1000)) % 9 !== 0 - finished.push({ jobId: ready.id, workerId: w.id, ok }) - } - for (const f of finished) { - const job = jobById.get(f.jobId) - const w = next.workers.find((x) => x.id === f.workerId) - if (!job || !w) continue - w.cells = (w.cells ?? []).filter((c) => c.id !== f.jobId) - w.inFlight = w.cells.length - w.jobId = w.cells[0]?.id - w.busy = w.cells.length > 0 - w.progress = w.busy - ? Math.max(0.04, ...w.cells.map((c) => jobById.get(c.id)?.progress ?? 0.04)) - : 0 - job.accountId = undefined - if (f.ok) { - job.status = 'done' - job.progress = 1 - next.totals.done += 1 - continue - } - // AffectUI: failed shakes — or retry slides back to queue (same id). - const attempt = (job.attempt ?? 1) + 1 - const canRetry = attempt <= 3 && (f.jobId.charCodeAt(0) + Math.floor(next.generatedAt / 900)) % 2 === 0 - if (canRetry) { - job.status = 'queued' - job.progress = 0 - job.elapsedMs = 80 - job.attempt = attempt - job.priority = 'high' - continue - } - job.status = 'failed' - job.progress = 1 - next.totals.failed += 1 - } - - // Per-job outcomes for GSAP (retry back to queue is not a sink landing). - const completions: MockCompletion[] = [] - for (const f of finished) { - const job = jobById.get(f.jobId) - if (!job) continue - if (job.status === 'done' || job.status === 'failed') { - completions.push({ id: job.id, name: job.name, kind: job.kind, ok: job.status === 'done' }) - } - } - next.completions = completions.length > 0 ? completions : undefined - - // Drop terminal jobs from the active list (keep queue + running only). - next.jobs = next.jobs.filter((j) => j.status === 'queued' || j.status === 'running') - - // Waiting elapsed ticks up. - for (const j of next.jobs) { - if (j.status === 'queued') j.elapsedMs += dt - } - - // Free concurrency cells pull front of queue (partially busy accounts included). - const queue = next.jobs.filter((j) => j.status === 'queued') - for (const w of next.workers) { - if (w.rateLimited) continue - const cap = clampSlotConcurrency(w.concurrency ?? 1) - w.cells = w.cells ?? [] - while (w.cells.length < cap) { - const job = queue.shift() - if (!job) break - job.status = 'running' - job.accountId = w.id - job.progress = 0.04 - job.elapsedMs = 0 - const cell = { id: job.id, name: job.name, startedAtMs: Date.now(), elapsedMs: 0 } - w.cells = [...w.cells.filter((c) => c.id !== job.id), cell].slice(0, cap) - w.busy = true - w.progress = Math.max(w.progress, 0.04) - w.jobId = w.cells[0]?.id - w.inFlight = w.cells.length - } - } - - // Soft enqueue so the waiting rail doesn’t drain dry. Keep enough - // queued jobs that the rail shows several timed pills, not just dots. - const waiting = next.jobs.filter((j) => j.status === 'queued').length - if (waiting < 10 && next.generatedAt % 1600 < dt) { - const pick = SEED_NAMES[seq % SEED_NAMES.length] - seq += 1 - // Every ~4th job is high priority (lands at back, then glides past). - const priority = seq % 4 === 0 ? 'high' as const : 'normal' as const - next.jobs.push({ - id: `j${seq}`, - name: pick.name, - kind: pick.kind, - status: 'queued', - progress: 0, - elapsedMs: 200 + (seq % 7) * 400, - sticky: pick.sticky, - priority, - }) - } - - // High-priority: after a brief back-of-queue land (~400ms), glide past to front. - { - const running = next.jobs.filter((j) => j.status === 'running') - const queued = next.jobs.filter((j) => j.status === 'queued') - const promote = queued.filter((j) => j.priority === 'high' && j.elapsedMs >= 400) - const rest = queued.filter((j) => !(j.priority === 'high' && j.elapsedMs >= 400)) - // Stable: already-promoted highs keep relative order at front; new promotes append after them. - const highs = promote - next.jobs = [...running, ...highs, ...rest] + depthSeries: Array.from({ length: DEPTH_SERIES_LEN }, () => 0), } - - // Depth chart scrolls: shift left, append current waiting+busy approx. - const busy = next.workers.filter((w) => w.busy).length - const waitNow = next.jobs.filter((j) => j.status === 'queued').length - const depthNow = Math.max(1, waitNow + Math.max(0, busy - 2)) - const series = next.depthSeries.slice(1) - series.push(depthNow) - next.depthSeries = series - - // Throughput / p95 drift gently. - next.throughputPerMin = Math.max(28, Math.min(58, next.throughputPerMin + ((seq % 3) - 1))) - next.waitP95Ms = Math.max(900, Math.min(5200, next.waitP95Ms + (waitNow > 4 ? 40 : -20))) - - return next } /** Clamp account concurrency for slot-bar cells (UI + summary). */ @@ -424,7 +154,7 @@ export function clampSlotConcurrency(n: number | undefined): number { return Math.max(1, Math.min(16, Math.floor(n))) } -export function summarizeMockInflight(snap: MockInflightSnapshot) { +export function summarizeInflight(snap: LiveInflightSnapshot) { const running = snap.jobs.filter((j) => j.status === 'running').length const waiting = snap.jobs.filter((j) => j.status === 'queued').length const busyWorkers = snap.workers.filter((w) => w.busy).length @@ -455,7 +185,7 @@ export function summarizeMockInflight(snap: MockInflightSnapshot) { } /** Optional sticky projection from /api/live (Stage-3 wire). */ -export type MockStickyStats = { +export type LiveStickyStats = { bindings: number hits: number misses: number @@ -506,7 +236,7 @@ export type LiveStickyLike = { export type LiveQueueJobLike = { id: string name: string - /** RequestStatus* — UI maps selecting onto MockJobStatus queued. */ + /** RequestStatus* — UI maps selecting onto LiveJobStatus queued. */ status: string started_at?: string /** Bind target while dwell still projects onto the waiting rail. */ @@ -541,14 +271,14 @@ export type LiveProjectionInput = { * showing occupied chrome until the inbound animation lands. */ export function applyLiveProjection( - base: MockInflightSnapshot, + base: LiveInflightSnapshot, live: LiveProjectionInput, -): MockInflightSnapshot { +): LiveInflightSnapshot { const now = Date.now() const prevById = new Map(base.jobs.map((j) => [j.id, j])) - const n = Math.max(1, MOCK_INFLIGHT.depthSeries.length) - const rateLimits: MockRateLimitWindow[] = live.rate_limits.map((r, i) => { + const n = DEPTH_SERIES_LEN + const rateLimits: LiveRateLimitWindow[] = live.rate_limits.map((r, i) => { const span = 0.14 const from = Math.min(0.86, ((i * 0.22) % 0.86)) return { @@ -561,7 +291,7 @@ export function applyLiveProjection( }) // Selecting queue first — ids still on wait rail (incl. dwell-bound). - const queuedJobs: MockInflightJob[] = (live.queue ?? []).map((q) => { + const queuedJobs: LiveInflightJob[] = (live.queue ?? []).map((q) => { const id = (q.id || '').trim() const prev = prevById.get(id) let startedAtMs: number | undefined @@ -608,7 +338,7 @@ export function applyLiveProjection( occByAccount.set(acc, list) } - const prevCellsByAccount = new Map() + const prevCellsByAccount = new Map() for (const w of base.workers) { if (w.cells?.length) prevCellsByAccount.set(w.id, w.cells) } @@ -627,7 +357,7 @@ export function applyLiveProjection( return fallback } - const workers: MockAccountSlot[] = live.workers.map((w) => { + const workers: LiveAccountSlot[] = live.workers.map((w) => { const concurrency = clampSlotConcurrency(w.max_inflight ?? 4) const rawIn = w.in_flight != null && Number.isFinite(w.in_flight) @@ -639,7 +369,7 @@ export function applyLiveProjection( const prevCells = prevCellsByAccount.get(w.id) ?? [] const prevByCellId = new Map(prevCells.map((c) => [c.id, c])) const occ = occByAccount.get(w.id) ?? [] - const cells: MockSlotCell[] = [] + const cells: LiveSlotCell[] = [] for (const o of occ) { if (cells.length >= inFlight) break @@ -696,7 +426,7 @@ export function applyLiveProjection( }) // Running jobs = occupancy cells not still on the wait rail (dwell). - const runningJobs: MockInflightJob[] = [] + const runningJobs: LiveInflightJob[] = [] for (const w of workers) { for (const c of w.cells ?? []) { if (queueIds.has(c.id)) continue // still selecting for display @@ -704,7 +434,7 @@ export function applyLiveProjection( runningJobs.push({ id: c.id, name: c.name, - kind: (prev?.kind as MockJobKind | undefined) ?? 'chat', + kind: (prev?.kind as LiveJobKind | undefined) ?? 'chat', status: 'running', accountId: w.id, progress: w.progress, @@ -714,7 +444,7 @@ export function applyLiveProjection( } } - const jobs: MockInflightJob[] = [...runningJobs, ...queuedJobs] + const jobs: LiveInflightJob[] = [...runningJobs, ...queuedJobs] // Continue rolling depth only after a prior live projection (cleared p95). // Mock seed/tick always leaves waitP95Ms > 0 — start zeros. Session totals @@ -741,7 +471,7 @@ export function applyLiveProjection( pendingByAccount.set(acc, list) } const stillIds = new Set(jobs.map((j) => j.id)) - const completions: MockCompletion[] = [] + const completions: LiveCompletion[] = [] for (const prev of base.jobs) { if (prev.status !== 'running') continue if (stillIds.has(prev.id)) continue diff --git a/frontend/src/pages/AccountsPage.tsx b/frontend/src/pages/AccountsPage.tsx index 8928e1cf..4560ed20 100644 --- a/frontend/src/pages/AccountsPage.tsx +++ b/frontend/src/pages/AccountsPage.tsx @@ -1,6 +1,6 @@ import { toast } from '@/lib/toast' import { copyText } from '@/lib/clipboard' -import { useCallback, useEffect, useMemo, useState, type ChangeEvent } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent } from 'react' import { Button, Label, ListBox, Select } from '@heroui/react' import { ArrowsClockwise, @@ -8,9 +8,11 @@ import { DownloadSimple, MagnifyingGlass, Plus, + SignIn, UploadSimple, } from '@phosphor-icons/react' import { AccountCard, type AccountBusyKind, type CheckinFeedback } from '@/components/account/AccountCard' +import { BatchReloginModal } from '@/components/account/BatchReloginModal' import { AccountCheckinRecordsModal } from '@/components/account/AccountCheckinRecordsModal' import { AccountModelsModal } from '@/components/account/AccountModelsModal' import { EditAccountModal } from '@/components/account/EditAccountModal' @@ -38,6 +40,7 @@ import { importAccount, loginWithPat, refreshAccount, + refreshAllAccounts, startDeviceLogin, updateAccount, type ProviderDescriptor, @@ -46,8 +49,17 @@ import { fetchSystemSettings, type SystemSettings } from '@/api/system' import { AccountsPageSkeleton } from '@/components/ui/PageSkeletons' import { accountState, + formatQuotaAmount, type AccountRow, } from '@/lib/account' +import { useAccountEvents } from '@/hooks/useAccountEvents' +import type { + AccountStateEvent, + BulkEventData, + CheckinStateEvent, + QuotaStateEvent, + ServerEvent, +} from '@/api/events' import { accountProviderFamilyLabel } from '@/lib/provider' import { ProviderMark } from '@/components/ProviderMark' import { BatchImportConfirmModal } from '@/components/account/BatchImportConfirmModal' @@ -99,7 +111,6 @@ type AccountFilter = 'all' | 'available' | 'attention' | 'disabled' const ALL_PROVIDERS = '__all__' const EMPTY_ACCOUNTS: AccountRow[] = [] -const ACCOUNT_REFRESH_BATCH_SIZE = 2 export function AccountsPage() { const { t } = useI18n() @@ -143,6 +154,16 @@ export function AccountsPage() { const [priorityById, setPriorityById] = useState>({}) const [quotaRefreshing, setQuotaRefreshing] = useState(false) const [checkinAllRunning, setCheckinAllRunning] = useState(false) + // Bulk re-login: selection mode on the account cards, then a sequential + // authorization walkthrough (see BatchReloginModal). + const [reloginMode, setReloginMode] = useState(false) + const [reloginSelected, setReloginSelected] = useState([]) + const [reloginOpen, setReloginOpen] = useState(false) + /** + * Live bulk-op progress streamed from GET /api/events (real per-account + * frames). Null when no bulk op is running. + */ + const [bulkProgress, setBulkProgress] = useState<{ kind: 'checkin' | 'refresh'; total: number; done: number } | null>(null) const reloadAccounts = useCallback(async (refresh = false) => { try { const response = await fetchAccounts(refresh) @@ -154,36 +175,158 @@ export function AccountsPage() { } }, []) - const refreshAccountsInBatches = useCallback(async (ids: string[], forceQuota = true) => { - const accountIds = [...new Set(ids)] - if (!accountIds.length) return { total: 0, failed: 0, errors: [] as string[] } - const total = accountIds.length - // Aggregate failures per account instead of mutating a shared object inside - // the concurrent Promise.all workers: those interleaved `failed += 1` - // updates race each other and lose counts, so a batch where several - // accounts failed could under-report how many really did. - const failures = new Map() - for (let start = 0; start < accountIds.length; start += ACCOUNT_REFRESH_BATCH_SIZE) { - const batch = accountIds.slice(start, start + ACCOUNT_REFRESH_BATCH_SIZE) - await Promise.all(batch.map(async (id) => { - try { - const refreshed = await refreshAccount(id, { quota: forceQuota }) - setAccounts((current) => current.map((account) => account.id === id ? refreshed : account)) - } catch (error) { - // Surface the failure to the caller instead of swallowing it: a - // batch where every account failed must not report success. - const message = error instanceof Error ? error.message : String(error) - failures.set(id, message) - setNoteById((current) => ({ ...current, [id]: message })) + /** Single-account refresh: the response is the real post-probe row. */ + const refreshOne = useCallback(async (id: string, forceQuota = true) => { + const refreshed = await refreshAccount(id, { quota: forceQuota }) + setAccounts((current) => current.map((account) => account.id === id ? { ...account, ...refreshed } : account)) + }, []) + + /** + * One-shot refresh for every account. The backend fans out to all accounts + * concurrently — no client batching, no queue — and every row returns the + * real probe outcome with the verbatim upstream error. + */ + const refreshEveryAccount = useCallback(async (forceQuota = true) => { + const response = await refreshAllAccounts({ quota: forceQuota }) + const results = response.data || [] + const notes: Record = {} + const errors: string[] = [] + const quotas: Record> = {} + let failed = 0 + for (const result of results) { + if (result.ok) { + if (result.quota) quotas[result.account_id] = result.quota + continue + } + failed += 1 + const message = result.message || result.code || result.kind || t('toastFailed') + notes[result.account_id] = message + errors.push(message) + } + if (Object.keys(quotas).length) { + setAccounts((current) => current.map((account) => quotas[account.id] + ? { ...account, quota: quotas[account.id] } + : account)) + } + if (failed) setNoteById((current) => ({ ...current, ...notes })) + // Events already patch rows as they land; this pull keeps the list truthful + // when the stream is offline. + await reloadAccounts(false).catch(() => undefined) + return { total: results.length, failed, errors } + }, [reloadAccounts, t]) + + /** + * Events patch rows in place for instant feedback; a trailing debounced re-read + * then reconciles every field with the server's truth (derived status, hot + * flags, fields the event does not carry) without a manual reload. + */ + const reconcileTimer = useRef(null) + const scheduleReconcile = useCallback(() => { + if (reconcileTimer.current != null) return + reconcileTimer.current = window.setTimeout(() => { + reconcileTimer.current = null + void reloadAccounts(false).catch(() => undefined) + }, 400) + }, [reloadAccounts]) + + const onAccountEvent = useCallback((event: ServerEvent) => { + const type = event.type + if (type === 'account') { + const data = (event.data || {}) as AccountStateEvent + const id = data.account_id || event.account_id + if (!id) return + setAccounts((current) => current.map((account) => { + if (account.id !== id) return account + const next = { ...account } + if (data.runtime_state) next.runtime_state = data.runtime_state + if (typeof data.ready === 'boolean') { + next.ready = data.ready + if (data.ready) next.hot = account.hot && data.runtime_state !== 'ready' } + if (data.cooldown_until) next.cooldown_until = data.cooldown_until + else if (data.ready) next.cooldown_until = null + if (data.last_error !== undefined) { + next.last_error = data.last_error + next.lastError = data.last_error || undefined + } + if (data.last_kind !== undefined) next.last_error_kind = data.last_kind || undefined + return next + })) + scheduleReconcile() + return + } + if (type === 'quota') { + const data = (event.data || {}) as QuotaStateEvent + const id = data.account_id || event.account_id + if (!id || !data.quota) return + setAccounts((current) => current.map((account) => account.id === id ? { ...account, quota: data.quota } : account)) + scheduleReconcile() + return + } + if (type === 'checkin') { + const data = (event.data || {}) as CheckinStateEvent + const id = data.account_id || event.account_id + if (!id) return + const status = String(data.status || '').toLowerCase() + const kind = status === 'already' || status === 'skipped' || status === 'error' || status === 'unknown' + ? status + : 'success' + const reward = typeof data.reward_credits === 'number' && data.reward_credits > 0 + ? t('checkinRewardSuffix', { credits: formatQuotaAmount(data.reward_credits) }) + : '' + const message = `${data.message || (kind === 'error' ? t('checkinRecordFailed') : kind === 'unknown' ? t('checkinStatusUnknown') : '')}${reward}`.trim() + setCheckinFeedbackById((current) => ({ + ...current, + [id]: { kind, message: message || undefined }, })) + setAccounts((current) => current.map((account) => account.id === id + ? { + ...account, + last_checkin_status: data.status || account.last_checkin_status, + last_checkin_msg: data.message || account.last_checkin_msg, + last_checkin_at: data.at || account.last_checkin_at, + } + : account)) + return + } + if (type === 'accounts') { + void reloadAccounts(false).catch(() => undefined) + return } - return { total, failed: failures.size, errors: [...failures.values()] } + if (type === 'bulk') { + const data = (event.data || {}) as BulkEventData + const kind = data.kind === 'refresh' ? 'refresh' : data.kind === 'checkin' ? 'checkin' : null + if (!kind) return + if (data.phase === 'done') { + setBulkProgress(null) + return + } + if (!data.total) return + setBulkProgress({ kind, total: data.total, done: data.done || 0 }) + } + }, [reloadAccounts, scheduleReconcile, t]) + + const { status: eventStatus } = useAccountEvents(onAccountEvent) + + useEffect(() => () => { + if (reconcileTimer.current != null) window.clearTimeout(reconcileTimer.current) }, []) useEffect(() => { void reloadAccounts(false).catch(() => undefined) }, [reloadAccounts]) + // The page no longer re-probes every account on mount: the background quota + // sweep already keeps snapshots fresh, and the event stream patches rows live. + useEffect(() => { + if (eventStatus === 'live') return + // Stream unavailable (401/offline): fall back to a 5s list poll so the page + // still converges on real state without manual refreshes. + const timer = window.setInterval(() => { + if (document.hidden) return + void reloadAccounts(false).catch(() => undefined) + }, 5000) + return () => window.clearInterval(timer) + }, [eventStatus, reloadAccounts]) useEffect(() => { let active = true void Promise.all([fetchProviders(), fetchSystemSettings()]).then(([providerData, systemData]) => { @@ -195,18 +338,9 @@ export function AccountsPage() { }) return () => { active = false } }, []) - // Each time the page mounts (navigated into), re-pull the real upstream - // quota and last check-in status so cards show the freshest state. - useEffect(() => { - let active = true - void reloadAccounts(false) - .then((next) => { - if (!active) return - return refreshAccountsInBatches((next || []).map((account) => account.id)) - }) - .catch(() => undefined) - return () => { active = false } - }, [reloadAccounts, refreshAccountsInBatches]) + // On mount the page reads the real stored state once. It no longer re-probes + // every account: the background quota sweep keeps snapshots fresh and the + // event stream patches cards live, so mounting stays cheap and truthful. function checkinPolicyFor(account: AccountRow) { return providers.find((provider) => provider.id === account.provider)?.regions.find((region) => region.id === account.region)?.checkin @@ -290,6 +424,10 @@ export function AccountsPage() { const start = (currentPage - 1) * pageSize return filteredRows.slice(start, start + pageSize) }, [currentPage, filteredRows, pageSize]) + const reloginAccounts = useMemo( + () => rows.filter((account) => reloginSelected.includes(account.id)), + [rows, reloginSelected], + ) if (accountsLoading && !hasAccounts) return @@ -323,7 +461,7 @@ export function AccountsPage() { if (login.status === 'ok' || login.status === 'error') break } await reloadAccounts(false) - await refreshAccountsInBatches([id]) + await refreshOne(id) }) } @@ -338,7 +476,7 @@ export function AccountsPage() { await completeLoginCallback(id, pasted) setCallbackById((current) => ({ ...current, [id]: '' })) await reloadAccounts(false) - await refreshAccountsInBatches([id]) + await refreshOne(id) }) if (ok) { setAuthPanelId((current) => (current === id ? null : current)) @@ -357,7 +495,7 @@ export function AccountsPage() { await loginWithPat(pat, id) setPatById((current) => ({ ...current, [id]: '' })) await reloadAccounts(false) - await refreshAccountsInBatches([id]) + await refreshOne(id) }) } @@ -481,17 +619,12 @@ export function AccountsPage() { return next }) try { - const result = await refreshAccountsInBatches([id]) - if (result.failed > 0) { - toast({ - id: `refresh-${id}`, - type: 'error', - title: t('toastFailed'), - description: result.errors[0] || t('toastFailed'), - }) - return - } + await refreshOne(id) toast({ id: `refresh-${id}`, type: 'success', title: t('toastAccountRefreshed') }) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + setNoteById((current) => ({ ...current, [id]: message })) + toast({ id: `refresh-${id}`, type: 'error', title: t('toastFailed'), description: message }) } finally { setBusy(null) } @@ -501,7 +634,7 @@ export function AccountsPage() { setQuotaRefreshing(true) toast({ id: 'refresh-credits', type: 'loading', title: t('toastRefreshingCredits') }) try { - const result = await refreshAccountsInBatches(accounts.map((account) => account.id)) + const result = await refreshEveryAccount(true) if (result.failed > 0) { // Report a partial failure honestly: some accounts refreshed fine, so // name how many failed instead of implying the whole batch did. @@ -517,6 +650,14 @@ export function AccountsPage() { return } toast({ id: 'refresh-credits', type: 'success', title: t('toastCreditsRefreshed') }) + } catch (error) { + // A whole-request failure (network / console key) surfaces verbatim. + toast({ + id: 'refresh-credits', + type: 'error', + title: t('toastFailed'), + description: error instanceof Error ? error.message : String(error), + }) } finally { setQuotaRefreshing(false) } @@ -609,25 +750,51 @@ export function AccountsPage() { toast({ id: 'checkin-all', type: 'info', title: t('checkinAllEmpty') }) return } - const summary = { checked: 0, skipped: 0, failed: 0 } - const feedback: Record = {} + const summary = { checked: 0, skipped: 0, failed: 0, unknown: 0, credits: 0 } + const feedback: Record = {} + const notes: Record = {} + let firstError = '' 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 + const kind: CheckinFeedback['kind'] = raw === 'already' || raw === 'skipped' || raw === 'error' || raw === 'unknown' + ? raw + : 'success' + if (kind === 'error') { + summary.failed += 1 + if (!firstError) firstError = result.message || '' + } else if (kind === 'skipped' || kind === 'already') summary.skipped += 1 + else if (kind === 'unknown') summary.unknown += 1 else summary.checked += 1 - feedback[result.account_id] = { - kind, - message: kind === 'error' ? result.message || t('checkinRecordFailed') : result.message, + // Real upstream grant only — omitted when the provider reported none. + if (typeof result.reward_credits === 'number' && result.reward_credits > 0) { + summary.credits += result.reward_credits + } + const reward = result.reward_credits && result.reward_credits > 0 + ? t('checkinRewardSuffix', { credits: formatQuotaAmount(result.reward_credits) }) + : '' + const message = `${result.message || (kind === 'error' ? t('checkinRecordFailed') : kind === 'unknown' ? t('checkinStatusUnknown') : '')}${reward}`.trim() + feedback[result.account_id] = { kind, message: message || undefined } + // Keep the verbatim upstream classification on the card so a failure + // never collapses into a generic "failed". + if (kind === 'error') { + notes[result.account_id] = [ + result.message, + result.code, + result.http_status ? `HTTP ${result.http_status}` : '', + ].filter(Boolean).join(' · ') || t('checkinRecordFailed') } } setCheckinFeedbackById((current) => ({ ...current, ...feedback })) - const values = { checked: summary.checked, skipped: summary.skipped, failed: summary.failed } + if (Object.keys(notes).length) setNoteById((current) => ({ ...current, ...notes })) + const values = { checked: summary.checked, skipped: summary.skipped, failed: summary.failed, total: results.length } + const description = summary.credits > 0 + ? t('checkinRewardTotal', { credits: formatQuotaAmount(summary.credits) }) + : summary.failed && firstError ? firstError : undefined toast({ id: 'checkin-all', - type: summary.failed ? 'error' : 'success', + type: summary.failed ? 'error' : summary.unknown ? 'info' : 'success', title: t(summary.failed ? 'toastCheckedInAllFailed' : 'toastCheckedInAll', values), + description, }) } catch (error) { toast({ @@ -653,12 +820,12 @@ export function AccountsPage() { [id]: { kind: 'error', message: error instanceof Error ? error.message : String(error) }, })) await reloadAccounts(false).catch(() => undefined) - await refreshAccountsInBatches([id]).catch(() => undefined) + await refreshOne(id).catch(() => undefined) return } const status = result?.last_checkin_status const message = result?.last_checkin_msg - const kind = status === 'already' ? 'already' : status === 'skipped' ? 'skipped' : status === 'error' ? 'error' : 'success' + const kind = status === 'already' ? 'already' : status === 'skipped' ? 'skipped' : status === 'error' ? 'error' : status === 'unknown' ? 'unknown' : 'success' setCheckinFeedbackById((current) => ({ ...current, [id]: { kind, message: kind === 'error' ? message || t('checkinRecordFailed') : message }, @@ -666,7 +833,7 @@ export function AccountsPage() { await reloadAccounts(false).catch(() => undefined) // Pull the real upstream quota/credits once more so the card reflects // the check-in grant (do not rely on the check-in response alone). - await refreshAccountsInBatches([id]).catch(() => undefined) + await refreshOne(id).catch(() => undefined) }) } @@ -785,6 +952,17 @@ export function AccountsPage() { + {/* Mobile Safari ignores programmatic input.click() from React Aria onPress when the file input is display:none. Associate a real @@ -810,8 +988,38 @@ export function AccountsPage() { /> + {eventStatus === 'offline' ? ( + + + {t('eventsOffline')} + + ) : null} + {bulkProgress ? ( +
+ + + {bulkProgress.kind === 'checkin' ? t('checkinAll') : t('refreshCredits')} + + + {bulkProgress.done}/{bulkProgress.total} + +
+
+
+
+ ) : null} + setAddOpen(false)} onAdded={() => { toast({ type: 'success', title: t('toastAccountAdded') }); void reloadAccounts(false) }} /> { void onBatchImportConfirm(region) }} /> setModelsId(null)} /> + { setReloginOpen(false); setReloginMode(false); setReloginSelected([]) }} + onFinished={() => { void reloadAccounts(false) }} + /> setCheckinHistoryId(null)} /> ) : null} + {reloginMode ? ( +
+ {t('reloginSelected', { count: reloginSelected.length })} + + +
+ + +
+
+ ) : null} +
{pagedRows.map((account) => ( setReloginSelected((current) => ( + current.includes(account.id) ? current.filter((id) => id !== account.id) : [...current, account.id] + ))} busyKind={busy?.id === account.id ? busy.kind : ''} authPanelOpen={authPanelId === account.id} authUrl={urlById[account.id]} diff --git a/frontend/src/pages/LoginPage.tsx b/frontend/src/pages/LoginPage.tsx index e85635c3..817a7451 100644 --- a/frontend/src/pages/LoginPage.tsx +++ b/frontend/src/pages/LoginPage.tsx @@ -3,7 +3,6 @@ import { Navigate, useLocation, useNavigate } from 'react-router-dom' import { Button, Card, InputGroup, Label, TextField, Toolbar, Tooltip } from '@heroui/react' import { ArrowRight, Eye, EyeSlash, Globe, Moon, Sun } from '@phosphor-icons/react' import { BrandMark } from '@/components/BrandMark' -import { InflightLiveCard } from '@/components/overview/InflightLiveCard' import { PageAlert } from '@/components/ui/PageAlert' import { useI18n } from '@/hooks/useI18n' import { useApiKey } from '@/hooks/useApiKey' @@ -82,11 +81,7 @@ export function LoginPage() { -
- -
- -