Skip to content
Open
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
7 changes: 7 additions & 0 deletions changelog/unreleased/account-select-checkbox-fix.md
Original file line number Diff line number Diff line change
@@ -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` 里,卡片此前只渲染了指示器本身,看上去正常但吃掉了所有点击,导致一个账号都选不中。
9 changes: 9 additions & 0 deletions changelog/unreleased/console-bulk-relogin.md
Original file line number Diff line number Diff line change
@@ -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 会话,并发授权会把同一份新签发的令牌塞给不同账号。
15 changes: 15 additions & 0 deletions changelog/unreleased/console-realtime-truthful-ops.md
Original file line number Diff line number Diff line change
@@ -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 流在上游接受请求却持续无响应时会切换账号重试。
179 changes: 179 additions & 0 deletions frontend/src/api/events.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>
}

/** 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<void> {
const headers: Record<string, string> = { 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 */
}
}
}
34 changes: 33 additions & 1 deletion frontend/src/api/overview.ts
Original file line number Diff line number Diff line change
@@ -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<Overview>('/api/overview/summary', {}, keyOverride)
Expand Down Expand Up @@ -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 }) {
Expand All @@ -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`)
}
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}>
Expand Down
34 changes: 31 additions & 3 deletions frontend/src/components/account/AccountCard.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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<typeof accountState>, cooldown: string, t: Translate) {
Expand Down Expand Up @@ -133,6 +138,9 @@ export function AccountCard({
onEdit,
onToggleAuthPanel,
onViewModels,
selectable = false,
selected = false,
onSelectToggle,
}: Props) {
const chipRef = useRef<HTMLSpanElement>(null)
const authRef = useRef<HTMLElement>(null)
Expand Down Expand Up @@ -249,7 +257,17 @@ export function AccountCard({
>
<Card.Header className="flex-row items-start justify-between gap-2.5 px-4 pt-3.5 pb-2">
<div className="flex min-w-0 items-center gap-2.5">
<div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-surface-tertiary" title={provider}>
{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.
<Checkbox isSelected={selected} onChange={() => onSelectToggle?.()} className="shrink-0">
<Checkbox.Content aria-label={`${t('reloginSelectAccount')} ${account.name || account.id}`} className="cursor-pointer p-1">
<Checkbox.Control><Checkbox.Indicator /></Checkbox.Control>
</Checkbox.Content>
</Checkbox>
) : null}
<div className={`flex size-8 shrink-0 items-center justify-center rounded-lg bg-surface-tertiary ${selected ? 'ring-2 ring-accent' : ''}`} title={provider}>
<ProviderMark provider={account.provider} size={20} />
</div>
<div className="min-w-0">
Expand Down Expand Up @@ -303,6 +321,14 @@ export function AccountCard({
<Chip size="sm" variant="soft" color={stateColor}>{stateCopy}</Chip>
)}
</span>
{account.force_ready_override ? (
<Tooltip>
<Tooltip.Trigger>
<span className="inline-flex cursor-help"><Chip size="sm" variant="soft" color="warning">{t('forceReadyBadge')}</Chip></span>
</Tooltip.Trigger>
<Tooltip.Content>{t('forceReadyHint')}</Tooltip.Content>
</Tooltip>
) : null}
{modelCooldowns.length && state !== 'cooling' ? (
<Tooltip>
<Tooltip.Trigger>
Expand Down Expand Up @@ -377,6 +403,8 @@ export function AccountCard({
<span className="font-medium text-warning">{t('checkinRecordAlready')}</span>
) : feedback.kind === 'skipped' ? (
<span className="font-medium text-warning">{t('checkinRecordSkipped')}</span>
) : feedback.kind === 'unknown' ? (
<span className="font-medium text-muted">{t('checkinStatusUnknown')}</span>
) : (
<span className="font-medium text-danger">{t('checkinRecordFailed')}</span>
)}
Expand Down
Loading
Loading