cc-haha/desktop/src/lib/trace/formatters.ts
程序员阿江(Relakkes) a94e5b641a fix: unify token usage display across desktop and CLI (#757)
Token counts were rendered with five inconsistent formats across the
chat UI (header "181,117 t", in-progress bare "↓ 2514", background
agents "12,345 tokens", compact summary "1.5k", trace "1.2k"), and the
in-progress count was actually stale: the server never set the status
event's tokens field, so the indicator showed the previous turn's value
(hence "first message shows nothing", "sometimes appears, never moves").

- Add shared desktop lib/formatTokenCount; route header, streaming
  indicator, background agents, compact summary, and trace through it.
- Header shows compact "124.3k tokens" with the exact count on hover.
- Add common.tokens i18n key (en/zh/zh-TW/jp/kr).
- Estimate the in-progress count from streamed chars (÷4, mirroring the
  CLI spinner) via a new streamingResponseChars per-session field, reset
  on each send; drop the dead status.tokens/elapsed fields.
- CLI spinner rows use formatTokens to drop the "1.0k" artifact.
2026-06-12 15:25:56 +08:00

28 lines
1.1 KiB
TypeScript

import type { TraceCallUsage } from '../../types/trace'
import { formatTokenCount } from '../formatTokenCount'
import type { NormalizedUsage } from './types'
export { formatTokenCount }
export function formatDurationMs(ms?: number): string {
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return '--'
if (ms < 1000) return `${Math.round(ms)}ms`
if (ms < 10_000) return `${(ms / 1000).toFixed(2)}s`
if (ms < 60_000) return `${Math.round(ms / 1000)}s`
const totalSeconds = Math.round(ms / 1000)
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
return `${minutes}m ${String(seconds).padStart(2, '0')}s`
}
export function formatUsageBrief(u?: NormalizedUsage | TraceCallUsage): string {
if (!u) return '--'
return `${formatTokenCount(u.inputTokens)}${formatTokenCount(u.outputTokens)}`
}
export function formatClockTime(iso: string): string {
const date = new Date(iso)
if (Number.isNaN(date.getTime())) return iso
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
}