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
+2
View File
@@ -35,6 +35,8 @@ jobs:
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.4
# Windows ARM64 cache restores can leave Bun missing when the workspace is on D:.
no-cache: ${{ matrix.target == 'windows-arm64' }}
- name: Install dependencies
run: bun install --frozen-lockfile --ignore-scripts
- name: Build CLI archive and installer
+2
View File
@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
- **sessions**: See total tokens and estimated cost in the session logs footer, with a breakdown of input, output, and cached tokens.
### Fixed
### Changed
+1 -1
View File
@@ -67,7 +67,7 @@ apps/web/e2e/
| Owner changes a team member role in the members dialog and permissions update | `tests/team/change-member-role.spec.ts` |
| Owner manages resource quotas in settings and resets usage from the dashboard | `tests/team/quotas-settings.spec.ts` |
| Owner creates an API token that is shown once, listed by hint, and authenticates API calls | `tests/team/api-tokens.spec.ts` |
| Session logs stay within the dialog and scroll through long messages and expanded records on desktop and narrow screens | `tests/team/agent-session-logs.spec.ts` |
| Session logs scroll through long messages and expanded records with the usage footer pinned and the token breakdown available on desktop and narrow screens | `tests/team/agent-session-logs.spec.ts` |
| Provider cards open the editor by click and keyboard, keep menu actions independent, and show a scrollable model preview on desktop and mobile | `tests/team/provider-model-refresh.spec.ts` |
### project
@@ -1,6 +1,6 @@
import { expect, test } from '../../fixtures'
test('session logs stay within the dialog and scroll through long messages and expanded records', async ({
test('session logs scroll with usage pinned below long messages and expanded records', async ({
owner,
prisma,
}) => {
@@ -25,6 +25,13 @@ test('session logs stay within the dialog and scroll through long messages and e
type: 'chat',
name: 'Scrollable Session Logs',
cwd: '/test',
accountedUsage: {
inputTokens: 12800,
outputTokens: 1580,
cacheReadTokens: 10000,
totalTokens: 24380,
cost: 0.014,
},
},
})
await prisma.agentSessionCommit.create({
@@ -64,6 +71,10 @@ test('session logs stay within the dialog and scroll through long messages and e
await expect(dialog.getByText(/^(Entry ID|条目 ID):/)).toHaveCount(0)
const viewport = dialog.locator('[data-slot="scroll-area-viewport"]')
const heading = dialog.getByRole('heading')
const footer = dialog.locator('footer')
const breakdown = footer.getByRole('button', { name: /^(Breakdown|明细|상세 내역)$/ })
await expect(footer).toContainText('24,380')
await expect(footer).toContainText('$0.014')
for (const size of [
{ width: 1280, height: 800 },
@@ -97,6 +108,7 @@ test('session logs stay within the dialog and scroll through long messages and e
)
.toBe(true)
const headerTop = (await heading.boundingBox())!.y
const footerTop = (await footer.boundingBox())!.y
await viewport.evaluate((element) => {
element.scrollTop = 0
})
@@ -110,6 +122,26 @@ test('session logs stay within the dialog and scroll through long messages and e
})
await expect(record.locator('summary')).toBeInViewport()
expect((await heading.boundingBox())!.y).toBeCloseTo(headerTop, 0)
expect((await footer.boundingBox())!.y).toBeCloseTo(footerTop, 0)
await expect(footer).toBeInViewport()
await breakdown.click()
const popover = page.getByRole('dialog', {
name: /Token breakdown|Token 用量明细|토큰 사용량 상세 내역/,
})
await expect(popover).toBeVisible()
for (const count of ['12,800', '1,580', '10,000']) {
await expect(popover.getByText(count, { exact: true })).toBeVisible()
}
await expect
.poll(async () => {
const bounds = await popover.boundingBox()
return bounds ? bounds.y + bounds.height : Infinity
})
.toBeLessThan(footerTop + 1)
await page.keyboard.press('Escape')
await expect(popover).toBeHidden()
await expect(breakdown).toBeFocused()
await record.locator('summary').click()
await viewport.evaluate((element) => {
+6 -5
View File
@@ -1,11 +1,12 @@
import type { EntryRecord } from '@earendil-works/pi-durable'
import type { AgentSessionLogs } from '@shumai/dtos'
import type { TypedResponse } from 'hono'
/** Pi records are already JSON; retain their public types without recursively remapping SDK schemas. */
export function agentEntriesResponse(
entries: EntryRecord[],
): Response & TypedResponse<EntryRecord[], 200, 'json'> {
return new Response(JSON.stringify(entries), {
export function agentEntriesResponse<T extends EntryRecord[] | AgentSessionLogs>(
body: T,
): Response & TypedResponse<T, 200, 'json'> {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
}) as Response & TypedResponse<EntryRecord[], 200, 'json'>
}) as Response & TypedResponse<T, 200, 'json'>
}
+57 -8
View File
@@ -2,12 +2,14 @@ import { ROOT_CONVERSATION_ID, type EntryId, type EntryRecord } from '@earendil-
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { HTTPException } from 'hono/http-exception'
import { agentService } from '@shumai/core/src/agent/agent'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { authzService } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import type { AgentInfo } from '@shumai/dtos'
import app from './agent'
vi.mock('@shumai/core/src/agent/agent')
vi.mock('@shumai/core/src/agent/session-service')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
@@ -352,15 +354,16 @@ describe('Agent API', () => {
})
describe('GET /agent-sessions/:sessionId/entries', () => {
const mockEntries: EntryRecord[] = [
{
id: 7 as EntryId,
conversationId: ROOT_CONVERSATION_ID,
kind: 'pi.user',
model: [{ role: 'user', content: 'Step 1', timestamp: 1 }],
},
]
it('returns entries of agent session if user is admin', async () => {
const mockEntries: EntryRecord[] = [
{
id: 7 as EntryId,
conversationId: ROOT_CONVERSATION_ID,
kind: 'pi.user',
model: [{ role: 'user', content: 'Step 1', timestamp: 1 }],
},
]
vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries)
const res = await app.request('/agent-sessions/session1/entries', {
@@ -373,6 +376,7 @@ describe('Agent API', () => {
expect(data[0].id).toBe(7)
expect(data[0].kind).toBe('pi.user')
expect(data[0].model[0].content).toBe('Step 1')
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: undefined,
permission: 'Admin',
@@ -381,6 +385,51 @@ describe('Agent API', () => {
})
})
it.each([
{
inputTokens: 12800,
outputTokens: 1580,
cacheReadTokens: 10000,
totalTokens: 24380,
cost: 0.014,
},
null,
])('includes requested usage with the session entries (%j)', async (usage) => {
vi.mocked(agentSessionService.getLogs).mockResolvedValue({ entries: mockEntries, usage })
const res = await app.request('/agent-sessions/session1/entries?includeUsage=true')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ entries: mockEntries, usage })
expect(agentSessionService.getLogs).toHaveBeenCalledWith('session1')
expect(agentService.getSessionEntries).not.toHaveBeenCalled()
})
it('checks session admin permission before loading requested usage', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(
new HTTPException(403, { message: 'Forbidden' }),
)
const res = await app.request('/agent-sessions/session1/entries?includeUsage=true')
expect(res.status).toBe(403)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: undefined,
permission: 'Admin',
type: 'agentSession',
id: 'session1',
})
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
})
it('rejects invalid includeUsage values', async () => {
const res = await app.request('/agent-sessions/session1/entries?includeUsage=invalid')
expect(res.status).toBe(400)
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
expect(agentService.getSessionEntries).not.toHaveBeenCalled()
})
it('denies access if user is not admin', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
+22 -12
View File
@@ -1,5 +1,6 @@
import { zValidator } from '@hono/zod-validator'
import { agentService } from '@shumai/core/src/agent/agent'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
AgentInfo,
@@ -11,6 +12,7 @@ import {
} from '@shumai/dtos'
import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { z } from 'zod'
import { agentEntriesResponse } from './agent-entries'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
@@ -18,6 +20,8 @@ import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
const sessionEntriesQuerySchema = z.object({ includeUsage: z.enum(['true', 'false']).optional() })
const route = new Hono<{ Variables: { user: User } }>()
.get('/teams/:teamId/agents', async (c) => {
const teamId = c.req.param('teamId')
@@ -208,20 +212,26 @@ const route = new Hono<{ Variables: { user: User } }>()
return new Response(null, { status: 204 })
})
.get('/agent-sessions/:sessionId/entries', async (c) => {
const sessionId = c.req.param('sessionId')
const userReq = c.get('user')
.get(
'/agent-sessions/:sessionId/entries',
zValidator('query', sessionEntriesQuerySchema),
async (c) => {
const sessionId = c.req.param('sessionId')
const userReq = c.get('user')
await authzService.hasPermission({
user: userReq,
permission: Permission.Admin,
type: ResourceType.AgentSession,
id: sessionId,
})
await authzService.hasPermission({
user: userReq,
permission: Permission.Admin,
type: ResourceType.AgentSession,
id: sessionId,
})
const entries = await agentService.getSessionEntries({ sessionId })
return agentEntriesResponse(entries)
})
if (c.req.valid('query').includeUsage === 'true') {
return agentEntriesResponse(await agentSessionService.getLogs(sessionId))
}
return agentEntriesResponse(await agentService.getSessionEntries({ sessionId }))
},
)
.get('/teams/:teamId/agent-sessions', zValidator('query', paginationParamsSchema), async (c) => {
const teamId = c.req.param('teamId')
const userReq = c.get('user')
@@ -60,6 +60,16 @@ describe('Native session storage and PostgreSQL synchronization', () => {
expect(await prisma.agentSessionEntry.count({ where: { sessionId: session.id } })).toBe(0)
})
it('returns logs with unavailable usage before a session has an accounting checkpoint', async () => {
const { session } = await fixture()
expect(await agentSessionService.getLogs(session.id)).toEqual({ entries: [], usage: null })
const entries = await appendSessionEntries(session.id, [
{ kind: 'pi.user', model: [{ role: 'user', content: 'No usage yet', timestamp: 1 }] },
])
expect(await agentSessionService.getLogs(session.id)).toEqual({ entries, usage: null })
})
it.each(['missing', 'corrupt', 'dirty'] as const)(
'rebuilds a %s local cache from mirrored commits',
async (failure) => {
@@ -438,6 +448,10 @@ describe('Native session storage and PostgreSQL synchronization', () => {
expect(Number(usage.totalTokens)).toBeGreaterThan(0)
expect(Number(usage.totalTokens)).toBe(checkpoint.totalTokens)
expect(Number(usage.cost)).toBe(checkpoint.cost)
const logs = await agentSessionService.getLogs(session.id)
expect(logs.entries).not.toHaveLength(0)
expect(logs.entries).toEqual(await agentSessionService.getEntries(session.id))
expect(logs.usage).toEqual(checkpoint)
})
it('rolls back usage if PostgreSQL cannot persist the native commit', async () => {
@@ -476,5 +490,6 @@ describe('Native session storage and PostgreSQL synchronization', () => {
await prisma.agentSession.delete({ where: { id: session.id } })
expect(await prisma.agentSessionCommit.count({ where: { sessionId: session.id } })).toBe(0)
await expect(agentSessionService.getEntries(session.id)).rejects.toThrow('Session not found')
await expect(agentSessionService.getLogs(session.id)).rejects.toThrow('Session not found')
})
})
+33 -20
View File
@@ -9,6 +9,7 @@ import {
} from '@earendil-works/pi-durable'
import { prisma, type Prisma, type TeamMemberRole } from '@shumai/db'
import { acquireAdvisoryLock } from '@shumai/db/src/advisory-lock'
import type { AgentSessionLogs } from '@shumai/dtos'
import { AiUsageService } from '../ai-usage/ai-usage'
import { quotaService } from '../quota/quota-service'
import { openSessionCache, removeSessionCaches } from './session-cache'
@@ -184,20 +185,22 @@ export class AgentSessionService {
private async read<T>(
sessionId: string,
use: (storage: SessionReader) => Promise<T>,
use: (storage: SessionReader, usage: PrismaJson.AgentSessionUsage | null) => Promise<T>,
{ includeUsage = false } = {},
): Promise<T> {
if (this.closing) throw new Error('Session service is closing')
return this.withCacheAccess(sessionId, async () => {
const session = await prisma.agentSession.findUnique({
where: { id: sessionId },
select: { id: true },
select: { id: true, accountedUsage: includeUsage },
})
if (!session) throw new Error('Session not found')
const usage = session.accountedUsage ?? null
const writer = this.writers.get(sessionId)
if (writer) return use(writer.reader)
if (writer) return use(writer.reader, usage)
const cache = await openSessionCache(sessionId)
try {
return await use(cache.storage)
return await use(cache.storage, usage)
} finally {
await cache.storage.close(BACKGROUND_CONTEXT)
}
@@ -225,22 +228,32 @@ export class AgentSessionService {
}
async getEntries(sessionId: string): Promise<EntryRecord[]> {
return this.read(sessionId, async (storage) => {
const entries: EntryRecord[] = []
if (!(await storage.conversation(ROOT_CONVERSATION_ID, BACKGROUND_CONTEXT))) return entries
let cursor: Cursor | undefined
do {
const page = await storage.scanEntries(
{ conversationId: ROOT_CONVERSATION_ID, order: 'ascending' },
100,
cursor,
BACKGROUND_CONTEXT,
)
entries.push(...page.items)
cursor = page.next
} while (cursor)
return entries
})
return this.read(sessionId, this.readAllEntries)
}
async getLogs(sessionId: string): Promise<AgentSessionLogs> {
return this.read(
sessionId,
async (storage, usage) => ({ entries: await this.readAllEntries(storage), usage }),
{ includeUsage: true },
)
}
private async readAllEntries(storage: SessionReader): Promise<EntryRecord[]> {
const entries: EntryRecord[] = []
if (!(await storage.conversation(ROOT_CONVERSATION_ID, BACKGROUND_CONTEXT))) return entries
let cursor: Cursor | undefined
do {
const page = await storage.scanEntries(
{ conversationId: ROOT_CONVERSATION_ID, order: 'ascending' },
100,
cursor,
BACKGROUND_CONTEXT,
)
entries.push(...page.items)
cursor = page.next
} while (cursor)
return entries
}
async getEntryForRequest(sessionId: string, requestId: string) {
+1 -7
View File
@@ -8,13 +8,7 @@ declare global {
writes: import('./generated/prisma/internal/prismaNamespace').JsonValue[]
}
export interface AgentSessionUsage {
inputTokens: number
outputTokens: number
cacheReadTokens: number
totalTokens: number
cost: number
}
export type AgentSessionUsage = import('@shumai/dtos').AiUsageMetrics
export type PiSessionEntryData = { [key: string]: unknown }
+7
View File
@@ -1,5 +1,7 @@
import type { EntryRecord } from '@earendil-works/pi-durable'
import { AgentType } from '@shumai/db/enums'
import { z } from 'zod'
import type { AiUsageMetrics } from './ai'
export * from './agent-avatar'
@@ -143,3 +145,8 @@ export const agentSessionSchema = z.object({
agentId: z.string().optional(),
})
export type AgentSessionInfo = z.infer<typeof agentSessionSchema>
export interface AgentSessionLogs {
entries: EntryRecord[]
usage: AiUsageMetrics | null
}
@@ -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>
)
@@ -183,6 +183,7 @@ export function AgentSessionsDashboard({ teamId }: AgentSessionsDashboardProps)
<AgentSessionLogsDialog
sessionId={selectedSessionId}
showUsage
open={!!selectedSessionId}
onOpenChange={(open) => {
if (!open) setSelectedSessionId(null)
+6
View File
@@ -1141,6 +1141,12 @@
"reply": "Reply",
"agent_session_logs": "Agent Session Logs",
"agent_logs_description": "Step-by-step execution trace of the agent's background tasks and tool calls.",
"session_usage": "Session usage",
"session_usage_unavailable": "Session usage unavailable",
"session_usage_estimated_cost": "est. cost",
"session_usage_breakdown": "Breakdown",
"session_usage_token_breakdown": "Token breakdown",
"session_usage_cost_explanation": "Cost is estimated using configured model prices.",
"role_user": "User",
"role_agent": "Agent",
"tool_result": "Tool Result:",
+6
View File
@@ -1095,6 +1095,12 @@
"reply": "답글",
"agent_session_logs": "에이전트 세션 로그",
"agent_logs_description": "에이전트 백그라운드 작업과 도구 호출의 단계별 실행 기록입니다.",
"session_usage": "세션 사용량",
"session_usage_unavailable": "세션 사용량을 확인할 수 없습니다",
"session_usage_estimated_cost": "예상 비용",
"session_usage_breakdown": "상세 내역",
"session_usage_token_breakdown": "토큰 사용량 상세 내역",
"session_usage_cost_explanation": "설정된 모델 요금을 기준으로 비용을 추정합니다.",
"role_user": "사용자",
"role_agent": "에이전트",
"tool_result": "도구 결과:",
+6
View File
@@ -1141,6 +1141,12 @@
"reply": "回复",
"agent_session_logs": "智能体会话日志",
"agent_logs_description": "智能体后台任务和工具调用的逐步执行跟踪。",
"session_usage": "会话用量",
"session_usage_unavailable": "暂无会话用量",
"session_usage_estimated_cost": "预估费用",
"session_usage_breakdown": "明细",
"session_usage_token_breakdown": "Token 用量明细",
"session_usage_cost_explanation": "费用根据配置的模型价格估算。",
"role_user": "用户",
"role_agent": "智能体",
"tool_result": "工具结果:",