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 (#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:
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user