feat(sessions): show token usage and estimated cost in logs (#557)

* feat(sessions): show token usage and estimated cost in logs

* fix(sessions): compact the usage footer

* fix(ci): bypass Bun cache for Windows ARM64
This commit is contained in:
Yiling-J
2026-12-01 20:49:07 +08:00
committed by GitHub
parent e3fe5792b9
commit bfeabb8244
16 changed files with 292 additions and 60 deletions
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import {
Dialog,
DialogContent,
@@ -6,18 +7,21 @@ import {
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { Skeleton } from '@/ui/components/ui/skeleton'
import { formatTimeAgo } from '@/ui/lib/time'
import { m } from '@/ui/paraglide/messages.js'
import { getLocale } from '@/ui/paraglide/runtime.js'
import type { EntryRecord } from '@earendil-works/pi-durable'
import { getShumaiMessage, serializeContextToXml } from '@shumai/dtos'
import { getShumaiMessage, serializeContextToXml, type AiUsageMetrics } from '@shumai/dtos'
import { useQuery } from '@tanstack/react-query'
import { Terminal } from 'lucide-react'
import Markdown from 'react-markdown'
interface AgentSessionLogsDialogProps {
sessionId?: string | null
showUsage?: boolean
open: boolean
onOpenChange: (open: boolean) => void
}
@@ -61,20 +65,85 @@ function EntryLog({ entry }: { entry: EntryRecord }) {
)
}
function SessionUsage({ usage }: { usage: AiUsageMetrics }) {
const locale = getLocale()
const tokens = new Intl.NumberFormat(locale)
const currency = new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD',
currencyDisplay: 'narrowSymbol',
maximumFractionDigits: 3,
})
const cost =
usage.cost > 0 && usage.cost < 0.001
? `<${currency.format(0.001)}`
: currency.format(usage.cost)
const breakdown = [
{ label: m.input_tokens(), count: usage.inputTokens },
{ label: m.output_tokens(), count: usage.outputTokens },
{ label: m.cache_read_tokens(), count: usage.cacheReadTokens },
]
return (
<>
<div className="flex flex-wrap gap-x-3 gap-y-1 tabular-nums">
<span>
{tokens.format(usage.totalTokens)} {m.tokens()}
</span>
<span>
{cost} {m.session_usage_estimated_cost()}
</span>
</div>
<PopoverTrigger asChild>
<Button
type="button"
variant="ghost"
size="xs"
className="font-normal text-muted-foreground"
>
{m.session_usage_breakdown()}
</Button>
</PopoverTrigger>
<PopoverContent
side="top"
align="end"
aria-label={m.session_usage_token_breakdown()}
className="w-60 space-y-2 p-3 text-sm"
>
<p className="font-semibold">{m.session_usage_token_breakdown()}</p>
<dl className="space-y-1 tabular-nums">
{breakdown.map(({ label, count }) => (
<div key={label} className="flex justify-between gap-3">
<dt className="text-muted-foreground">{label}</dt>
<dd>{tokens.format(count)}</dd>
</div>
))}
</dl>
<p className="border-t pt-2 text-xs text-muted-foreground">
{m.session_usage_cost_explanation()}
</p>
</PopoverContent>
</>
)
}
export function AgentSessionLogsDialog({
sessionId,
showUsage = false,
open,
onOpenChange,
}: AgentSessionLogsDialogProps) {
const { data: entries, isLoading } = useQuery({
queryKey: ['agent-sessions', sessionId, 'entries'],
const { data: logs, isLoading } = useQuery({
queryKey: ['agent-sessions', sessionId, 'entries', showUsage],
queryFn: async () => {
if (!sessionId) return []
if (!sessionId) return { entries: [], usage: null }
const response = await client.api['agent-sessions'][':sessionId'].entries.$get({
param: { sessionId },
query: showUsage ? { includeUsage: 'true' } : {},
})
if (!response.ok) throw new Error('Failed to fetch session logs')
return (await response.json()) as EntryRecord[]
const data = await response.json()
return Array.isArray(data) ? { entries: data, usage: null } : data
},
enabled: open && !!sessionId,
})
@@ -93,10 +162,29 @@ export function AgentSessionLogsDialog({
{isLoading ? (
<Skeleton className="h-32 w-full" />
) : (
entries?.map((entry) => <EntryLog key={entry.id} entry={entry} />)
logs?.entries.map((entry) => <EntryLog key={entry.id} entry={entry} />)
)}
</div>
</ScrollArea>
{showUsage && (
<Popover>
<PopoverAnchor asChild>
<footer
aria-label={m.session_usage()}
aria-busy={isLoading}
className="-mx-6 -mb-6 flex min-h-8 shrink-0 flex-wrap items-center justify-between gap-x-3 border-t bg-muted/30 px-3 py-0.5 text-xs text-muted-foreground"
>
{isLoading ? (
<Skeleton className="h-4 w-44" />
) : logs?.usage ? (
<SessionUsage usage={logs.usage} />
) : (
m.session_usage_unavailable()
)}
</footer>
</PopoverAnchor>
</Popover>
)}
</DialogContent>
</Dialog>
)