mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-01 13:34:33 +00:00
* feat(sessions): show token usage and estimated cost in logs * fix(sessions): compact the usage footer * fix(ci): bypass Bun cache for Windows ARM64
192 lines
6.8 KiB
TypeScript
192 lines
6.8 KiB
TypeScript
import { client } from '@/ui/api/client'
|
|
import { Button } from '@/ui/components/ui/button'
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
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, 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
|
|
}
|
|
|
|
function EntryLog({ entry }: { entry: EntryRecord }) {
|
|
const application = getShumaiMessage(entry)
|
|
const message = entry.model?.[0]
|
|
const timestamp = application?.timestamp ?? message?.timestamp
|
|
const content = application
|
|
? `${application.displayText}\n\n${serializeContextToXml(application.context)}`
|
|
: message && typeof message.content === 'string'
|
|
? message.content
|
|
: (Array.isArray(message?.content) ? message.content : [])
|
|
.filter((block) => block.type === 'text')
|
|
.map((block) => block.text)
|
|
.join('\n')
|
|
const role =
|
|
application || message?.role === 'user'
|
|
? m.role_user()
|
|
: message?.role === 'assistant'
|
|
? m.role_agent()
|
|
: message?.role === 'toolResult'
|
|
? m.tool_result_with_name({ name: message.toolName })
|
|
: entry.kind
|
|
return (
|
|
<div className="min-w-0 rounded-lg border border-border bg-muted/30 p-3 space-y-2 [overflow-wrap:anywhere]">
|
|
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
|
<span className="font-semibold text-foreground">{role}</span>
|
|
{timestamp !== undefined && <span>{formatTimeAgo(new Date(timestamp).toISOString())}</span>}
|
|
</div>
|
|
{content && (
|
|
<div className="text-xs whitespace-pre-wrap break-words [&_pre]:whitespace-pre-wrap [&_pre]:break-all">
|
|
<Markdown>{content}</Markdown>
|
|
</div>
|
|
)}
|
|
<details className="text-xs text-muted-foreground">
|
|
<summary className="cursor-pointer font-mono">{entry.kind}</summary>
|
|
<pre className="mt-2 whitespace-pre-wrap break-all">{JSON.stringify(entry, null, 2)}</pre>
|
|
</details>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
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: logs, isLoading } = useQuery({
|
|
queryKey: ['agent-sessions', sessionId, 'entries', showUsage],
|
|
queryFn: async () => {
|
|
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')
|
|
const data = await response.json()
|
|
return Array.isArray(data) ? { entries: data, usage: null } : data
|
|
},
|
|
enabled: open && !!sessionId,
|
|
})
|
|
return (
|
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-2xl h-[80dvh] max-h-[80dvh] flex flex-col overflow-hidden">
|
|
<DialogHeader className="shrink-0">
|
|
<DialogTitle className="flex items-center gap-2">
|
|
<Terminal className="h-5 w-5" />
|
|
{m.agent_session_logs()}
|
|
</DialogTitle>
|
|
<DialogDescription>{m.agent_logs_description()}</DialogDescription>
|
|
</DialogHeader>
|
|
<ScrollArea className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
|
<div className="space-y-3 pr-3 py-2">
|
|
{isLoading ? (
|
|
<Skeleton className="h-32 w-full" />
|
|
) : (
|
|
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>
|
|
)
|
|
}
|