mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Usage data layer: types, API calls, range and aggregation
This commit is contained in:
1 parent
7ed857f7ea
commit
4d5a2c745e
12 files changed
+1592
No files matched your search
@@ -129,6 +129,7 @@ export interface SessionMessagesPage {
|
||||
export interface SessionMessagesInput {
|
||||
cursor?: string
|
||||
limit?: number
|
||||
type?: 'assistant'
|
||||
}
|
||||
|
||||
export interface SendPromptInput {
|
||||
@@ -505,6 +506,7 @@ export async function listSessionMessages(
|
||||
sessionID,
|
||||
limit: input.limit,
|
||||
cursor: input.cursor,
|
||||
type: input.type,
|
||||
order: input.cursor === undefined ? 'desc' : undefined,
|
||||
}),
|
||||
serverId,
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { JsonObject } from '@opencode-manager/shared/utils'
|
||||
import { createFetchFake, type FetchFake, type FetchRoute } from '@/test/fetchFake'
|
||||
import {
|
||||
SESSION_USAGE_MAX_PAGES,
|
||||
SESSION_USAGE_PAGE_LIMIT,
|
||||
getSessionStats,
|
||||
loadSessionUsageMessages,
|
||||
} from './usage'
|
||||
|
||||
const localStatsUrl = '/api/opencode/api/experimental/session/stats'
|
||||
|
||||
const remoteStatsUrl = '/api/opencode/servers/srv_kitchen/api/experimental/session/stats'
|
||||
|
||||
const messagesUrl = '/api/opencode/api/session/ses_1/message'
|
||||
|
||||
const statsQuery = 'from=1700000000000&to=1700086400000&timezone=UTC&tools=detail'
|
||||
|
||||
const statsInput = { from: 1700000000000, to: 1700086400000, timezone: 'UTC', tools: 'detail' as const }
|
||||
|
||||
function assistantMessage(id: string, created: number) {
|
||||
return {
|
||||
id,
|
||||
type: 'assistant' as const,
|
||||
agent: 'build',
|
||||
model: { providerID: 'anthropic', id: 'claude' },
|
||||
time: { created },
|
||||
content: [],
|
||||
}
|
||||
}
|
||||
|
||||
function userMessage(id: string, created: number) {
|
||||
return { id, type: 'user', time: { created }, payload: { text: 'Run the tests' } }
|
||||
}
|
||||
|
||||
function shellMessage(id: string, created: number) {
|
||||
return { id, type: 'shell', time: { created }, command: 'ls' }
|
||||
}
|
||||
|
||||
function installRoutes(routes: FetchRoute[]): FetchFake {
|
||||
const fetchFake = createFetchFake(routes)
|
||||
fetchFake.install()
|
||||
return fetchFake
|
||||
}
|
||||
|
||||
function respondTo(method: FetchRoute['method'], path: string, json: JsonObject): FetchRoute {
|
||||
return { method, path, respond: () => ({ json }) }
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('usage api', () => {
|
||||
it('caps session usage paging at 200 messages per page and five pages', () => {
|
||||
expect(SESSION_USAGE_PAGE_LIMIT).toBe(200)
|
||||
expect(SESSION_USAGE_MAX_PAGES).toBe(5)
|
||||
})
|
||||
|
||||
it('requests local session stats with the range, timezone, and tool detail', async () => {
|
||||
const stats = { sessions: 3, steps: 40, cost: 12 }
|
||||
const fetchFake = installRoutes([respondTo('GET', localStatsUrl, { data: stats })])
|
||||
|
||||
const result = await getSessionStats(statsInput)
|
||||
|
||||
expect(fetchFake.lastRequest('GET', localStatsUrl)?.searchParams.toString()).toBe(statsQuery)
|
||||
expect(result).toEqual(stats)
|
||||
})
|
||||
|
||||
it('requests session stats from a remote server route', async () => {
|
||||
const stats = { sessions: 1, steps: 9, cost: 2 }
|
||||
const fetchFake = installRoutes([respondTo('GET', remoteStatsUrl, { data: stats })])
|
||||
|
||||
const result = await getSessionStats(statsInput, 'srv_kitchen')
|
||||
|
||||
expect(fetchFake.lastRequest('GET', remoteStatsUrl)?.searchParams.toString()).toBe(statsQuery)
|
||||
expect(fetchFake.findRequests('GET', localStatsUrl)).toHaveLength(0)
|
||||
expect(result).toEqual(stats)
|
||||
})
|
||||
|
||||
it('pages through assistant messages with a descending first page and cursor continuations', async () => {
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'GET',
|
||||
path: messagesUrl,
|
||||
respond: (request) =>
|
||||
request.searchParams.get('cursor') === 'cursor_1'
|
||||
? { json: { data: [assistantMessage('msg_1', 1000)], cursor: {} } }
|
||||
: { json: { data: [assistantMessage('msg_2', 2000)], cursor: { next: 'cursor_1' } } },
|
||||
},
|
||||
])
|
||||
|
||||
await loadSessionUsageMessages('ses_1')
|
||||
|
||||
expect(fetchFake.findRequests('GET', messagesUrl).map((request) => request.searchParams.toString())).toEqual([
|
||||
'limit=200&order=desc&type=assistant',
|
||||
'limit=200&cursor=cursor_1&type=assistant',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps only assistant steps and joins pages oldest-first', async () => {
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'GET',
|
||||
path: messagesUrl,
|
||||
respond: (request) =>
|
||||
request.searchParams.get('cursor') === 'cursor_1'
|
||||
? {
|
||||
json: {
|
||||
data: [shellMessage('msg_2', 2000), assistantMessage('msg_1', 1000)],
|
||||
cursor: {},
|
||||
},
|
||||
}
|
||||
: {
|
||||
json: {
|
||||
data: [
|
||||
assistantMessage('msg_5', 5000),
|
||||
userMessage('msg_4', 4000),
|
||||
assistantMessage('msg_3', 3000),
|
||||
],
|
||||
cursor: { next: 'cursor_1' },
|
||||
},
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const result = await loadSessionUsageMessages('ses_1')
|
||||
|
||||
expect(result.steps.map((step) => step.id)).toEqual(['msg_1', 'msg_3', 'msg_5'])
|
||||
expect(result.truncated).toBe(false)
|
||||
expect(fetchFake.findRequests('GET', messagesUrl)).toHaveLength(2)
|
||||
})
|
||||
|
||||
const truncationCases: Array<{ title: string; fifthCursor: string | undefined; truncated: boolean }> = [
|
||||
{
|
||||
title: 'reports truncation when the fifth page still has a cursor',
|
||||
fifthCursor: 'cursor_5',
|
||||
truncated: true,
|
||||
},
|
||||
{
|
||||
title: 'reports no truncation when the fifth page is the last one',
|
||||
fifthCursor: undefined,
|
||||
truncated: false,
|
||||
},
|
||||
]
|
||||
|
||||
it.each(truncationCases)('$title', async ({ fifthCursor, truncated }) => {
|
||||
let page = 0
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'GET',
|
||||
path: messagesUrl,
|
||||
respond: () => {
|
||||
page += 1
|
||||
return {
|
||||
json: {
|
||||
data: [assistantMessage(`msg_${page}`, page * 1000)],
|
||||
cursor: page < 5 ? { next: `cursor_${page}` } : fifthCursor ? { next: fifthCursor } : {},
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const result = await loadSessionUsageMessages('ses_1')
|
||||
|
||||
expect(fetchFake.findRequests('GET', messagesUrl)).toHaveLength(5)
|
||||
expect(result.truncated).toBe(truncated)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
import type {
|
||||
ExperimentalSessionStatsInput,
|
||||
SessionMessageAssistant,
|
||||
SessionMessageInfo,
|
||||
SessionStatsInfo,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { listSessionMessages } from './opencode'
|
||||
import { callOpenCode } from './opencodeApi'
|
||||
|
||||
export const SESSION_USAGE_PAGE_LIMIT = 200
|
||||
export const SESSION_USAGE_MAX_PAGES = 5
|
||||
|
||||
export interface SessionUsageMessages {
|
||||
steps: SessionMessageAssistant[]
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export async function getSessionStats(
|
||||
input: ExperimentalSessionStatsInput,
|
||||
serverId?: string,
|
||||
): Promise<SessionStatsInfo> {
|
||||
return callOpenCode((api) => api.experimental.session.stats(input), serverId)
|
||||
}
|
||||
|
||||
function isAssistantMessage(message: SessionMessageInfo): message is SessionMessageAssistant {
|
||||
return message.type === 'assistant'
|
||||
}
|
||||
|
||||
export async function loadSessionUsageMessages(
|
||||
sessionID: string,
|
||||
serverId?: string,
|
||||
): Promise<SessionUsageMessages> {
|
||||
const steps: SessionMessageAssistant[] = []
|
||||
let cursor: string | undefined
|
||||
|
||||
for (let page = 0; page < SESSION_USAGE_MAX_PAGES; page += 1) {
|
||||
const result = await listSessionMessages(
|
||||
sessionID,
|
||||
{ limit: SESSION_USAGE_PAGE_LIMIT, type: 'assistant', cursor },
|
||||
serverId,
|
||||
)
|
||||
steps.unshift(...result.messages.filter(isAssistantMessage))
|
||||
cursor = result.nextCursor
|
||||
if (cursor === undefined) {
|
||||
return { steps, truncated: false }
|
||||
}
|
||||
}
|
||||
|
||||
return { steps, truncated: true }
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { SessionStatsInfo } from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
sessionUsageQueryKey,
|
||||
usageStatsQueryKey,
|
||||
useSessionUsage,
|
||||
useSessionUsageQueries,
|
||||
useUsageStats,
|
||||
} from './useUsage'
|
||||
import { renderHookWithProviders } from '@/test/render'
|
||||
import type { FetchRoute } from '@/test/fetchFake'
|
||||
|
||||
const hookProviders = {
|
||||
auth: false,
|
||||
theme: false,
|
||||
tts: false,
|
||||
} as const
|
||||
|
||||
const statsPath = '/api/opencode/api/experimental/session/stats'
|
||||
|
||||
const remoteStatsPath = '/api/opencode/servers/srv_kitchen/api/experimental/session/stats'
|
||||
|
||||
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
|
||||
const stats: SessionStatsInfo = {
|
||||
range: { from: 1, to: 2 },
|
||||
sessions: 2,
|
||||
subagents: 0,
|
||||
prompts: 3,
|
||||
steps: 4,
|
||||
tokens: { input: 10, output: 20, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
cost: 0.25,
|
||||
tools: {
|
||||
mode: 'detail',
|
||||
totals: { calls: 1, succeeded: 1, failed: 0, unfinished: 0 },
|
||||
usage: [],
|
||||
},
|
||||
activeDays: 1,
|
||||
streak: 1,
|
||||
activity: [],
|
||||
models: [],
|
||||
}
|
||||
|
||||
function assistantMessage(id: string, created: number) {
|
||||
return {
|
||||
id,
|
||||
type: 'assistant' as const,
|
||||
agent: 'build',
|
||||
model: { providerID: 'anthropic', id: 'claude' },
|
||||
time: { created },
|
||||
content: [],
|
||||
}
|
||||
}
|
||||
|
||||
function userMessage(id: string, created: number) {
|
||||
return { id, type: 'user', time: { created }, text: 'Run the tests' }
|
||||
}
|
||||
|
||||
function statsRoute(path: string = statsPath): FetchRoute {
|
||||
return { method: 'GET', path, respond: () => ({ json: { data: stats } }) }
|
||||
}
|
||||
|
||||
function messagesRoute(sessionID: string, messages: object[]): FetchRoute {
|
||||
return {
|
||||
method: 'GET',
|
||||
path: `/api/opencode/api/session/${sessionID}/message`,
|
||||
respond: () => ({ json: { data: messages, cursor: {} } }),
|
||||
}
|
||||
}
|
||||
|
||||
describe('usage query keys', () => {
|
||||
it('scopes the stats key by selection, timezone, and server', () => {
|
||||
expect(usageStatsQueryKey({ preset: '4h' }, 'Europe/Berlin', LOCAL_OPENCODE_SERVER_ID)).toEqual([
|
||||
'opencode',
|
||||
'usage',
|
||||
'stats',
|
||||
{ preset: '4h' },
|
||||
'Europe/Berlin',
|
||||
])
|
||||
expect(usageStatsQueryKey({ preset: '4h' }, 'Europe/Berlin', 'srv_kitchen')).toEqual([
|
||||
'opencode',
|
||||
'usage',
|
||||
'stats',
|
||||
{ preset: '4h' },
|
||||
'Europe/Berlin',
|
||||
'srv_kitchen',
|
||||
])
|
||||
})
|
||||
|
||||
it('scopes the session usage key by server', () => {
|
||||
expect(sessionUsageQueryKey('ses_1', LOCAL_OPENCODE_SERVER_ID)).toEqual([
|
||||
'opencode',
|
||||
'session-usage',
|
||||
'ses_1',
|
||||
])
|
||||
expect(sessionUsageQueryKey('ses_1', 'srv_kitchen')).toEqual([
|
||||
'opencode',
|
||||
'session-usage',
|
||||
'ses_1',
|
||||
'srv_kitchen',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('useUsageStats', () => {
|
||||
it('requests the 4h stats range for the browser timezone', async () => {
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useUsageStats({ preset: '4h' }, LOCAL_OPENCODE_SERVER_ID),
|
||||
{ ...hookProviders, fetchRoutes: [statsRoute()] },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.data).toEqual(stats))
|
||||
|
||||
const requests = fetchFake.findRequests('GET', statsPath)
|
||||
expect(requests).toHaveLength(1)
|
||||
const request = fetchFake.lastRequest('GET', statsPath)
|
||||
expect(request?.searchParams.get('tools')).toBe('detail')
|
||||
expect(request?.searchParams.get('timezone')).toBe(timezone)
|
||||
expect(Number(request?.searchParams.get('to')) - Number(request?.searchParams.get('from'))).toBe(
|
||||
14_400_000,
|
||||
)
|
||||
})
|
||||
|
||||
it('stays idle without requesting stats for an incomplete custom range', async () => {
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useUsageStats({ preset: 'custom', from: 1000, to: null }, LOCAL_OPENCODE_SERVER_ID),
|
||||
{ ...hookProviders, fetchRoutes: [statsRoute()] },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.fetchStatus).toBe('idle'))
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
expect(fetchFake.findRequests('GET', statsPath)).toHaveLength(0)
|
||||
expect(result.current.isError).toBe(false)
|
||||
})
|
||||
|
||||
it('requests stats from the linked server route', async () => {
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useUsageStats({ preset: '1h' }, 'srv_kitchen'),
|
||||
{ ...hookProviders, fetchRoutes: [statsRoute(remoteStatsPath)] },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.data).toEqual(stats))
|
||||
|
||||
expect(fetchFake.findRequests('GET', remoteStatsPath)).toHaveLength(1)
|
||||
expect(fetchFake.findRequests('GET', statsPath)).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSessionUsage', () => {
|
||||
it('does not request messages without a session id', async () => {
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useSessionUsage(undefined, LOCAL_OPENCODE_SERVER_ID),
|
||||
{ ...hookProviders, fetchRoutes: [messagesRoute('ses_1', [])] },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.fetchStatus).toBe('idle'))
|
||||
|
||||
expect(fetchFake.findRequests('GET', '/api/opencode/api/session/ses_1/message')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('loads assistant steps for a session', async () => {
|
||||
const assistant = assistantMessage('msg_1', 1000)
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useSessionUsage('ses_1', LOCAL_OPENCODE_SERVER_ID),
|
||||
{ ...hookProviders, fetchRoutes: [messagesRoute('ses_1', [userMessage('msg_2', 2000), assistant])] },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.data).toEqual({ steps: [assistant], truncated: false }))
|
||||
|
||||
const request = fetchFake.lastRequest('GET', '/api/opencode/api/session/ses_1/message')
|
||||
expect(request?.searchParams.toString()).toBe('limit=200&order=desc&type=assistant')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSessionUsageQueries', () => {
|
||||
it('loads usage for every requested session', async () => {
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useSessionUsageQueries(['ses_1', 'ses_2'], LOCAL_OPENCODE_SERVER_ID),
|
||||
{
|
||||
...hookProviders,
|
||||
fetchRoutes: [
|
||||
messagesRoute('ses_1', [assistantMessage('msg_1', 1000)]),
|
||||
messagesRoute('ses_2', [assistantMessage('msg_2', 2000)]),
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.map((query) => query.data?.steps.map((step) => step.id))).toEqual([
|
||||
['msg_1'],
|
||||
['msg_2'],
|
||||
]),
|
||||
)
|
||||
|
||||
expect(fetchFake.findRequests('GET', '/api/opencode/api/session/ses_1/message')).toHaveLength(1)
|
||||
expect(fetchFake.findRequests('GET', '/api/opencode/api/session/ses_2/message')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useQueries, useQuery } from '@tanstack/react-query'
|
||||
import { getSessionStats, loadSessionUsageMessages } from '@/api/usage'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { resolveUsageRange, type UsageRangeSelection } from '@/lib/usageRange'
|
||||
|
||||
export function usageStatsQueryKey(
|
||||
selection: UsageRangeSelection,
|
||||
timezone: string,
|
||||
serverId: string,
|
||||
) {
|
||||
return serverScopedKey(['opencode', 'usage', 'stats', selection, timezone], serverId)
|
||||
}
|
||||
|
||||
export function sessionUsageQueryKey(sessionID: string, serverId: string) {
|
||||
return serverScopedKey(['opencode', 'session-usage', sessionID], serverId)
|
||||
}
|
||||
|
||||
export function useUsageStats(selection: UsageRangeSelection, serverId: string) {
|
||||
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
return useQuery({
|
||||
queryKey: usageStatsQueryKey(selection, timezone, serverId),
|
||||
queryFn: () => {
|
||||
const range = resolveUsageRange(selection, Date.now())
|
||||
if (range === null) return Promise.reject(new Error('Usage range is incomplete'))
|
||||
return getSessionStats({ ...range, timezone, tools: 'detail' }, serverId)
|
||||
},
|
||||
enabled: resolveUsageRange(selection, Date.now()) !== null,
|
||||
staleTime: 60_000,
|
||||
retry: false,
|
||||
})
|
||||
}
|
||||
|
||||
function buildSessionUsageQueryOptions(sessionID: string | undefined, serverId: string) {
|
||||
return {
|
||||
queryKey: sessionUsageQueryKey(sessionID ?? '', serverId),
|
||||
queryFn: () => {
|
||||
if (sessionID === undefined) return Promise.reject(new Error('Session usage needs a session id'))
|
||||
return loadSessionUsageMessages(sessionID, serverId)
|
||||
},
|
||||
enabled: sessionID !== undefined,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
}
|
||||
}
|
||||
|
||||
export function useSessionUsage(sessionID: string | undefined, serverId: string) {
|
||||
return useQuery(buildSessionUsageQueryOptions(sessionID, serverId))
|
||||
}
|
||||
|
||||
export function useSessionUsageQueries(sessionIDs: readonly string[], serverId: string) {
|
||||
return useQueries({
|
||||
queries: sessionIDs.map((sessionID) => buildSessionUsageQueryOptions(sessionID, serverId)),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import {
|
||||
useUsageRangePreference,
|
||||
useUsageModelsPreference,
|
||||
USAGE_RANGE_STORAGE_KEY,
|
||||
SESSION_USAGE_RANGE_STORAGE_KEY,
|
||||
USAGE_MODELS_STORAGE_KEY,
|
||||
} from './useUsagePreferences'
|
||||
|
||||
const realLocalStorage = window.localStorage
|
||||
|
||||
function createLocalStorageMock() {
|
||||
const store = new Map<string, string>()
|
||||
|
||||
return {
|
||||
getItem: vi.fn((key: string) => store.get(key) ?? null),
|
||||
setItem: vi.fn((key: string, value: string) => {
|
||||
store.set(key, value)
|
||||
}),
|
||||
removeItem: vi.fn((key: string) => {
|
||||
store.delete(key)
|
||||
}),
|
||||
clear: vi.fn(() => {
|
||||
store.clear()
|
||||
}),
|
||||
key: vi.fn((index: number) => Array.from(store.keys())[index] ?? null),
|
||||
get length(): number {
|
||||
return store.size
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let storage = createLocalStorageMock()
|
||||
|
||||
describe('useUsagePreferences', () => {
|
||||
beforeEach(() => {
|
||||
storage = createLocalStorageMock()
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: storage,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: realLocalStorage,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('useUsageRangePreference', () => {
|
||||
it('returns the fallback and reads the passed storage key when nothing is stored', () => {
|
||||
const fallback = { preset: '4h' } as const
|
||||
|
||||
const { result } = renderHook(() => useUsageRangePreference(USAGE_RANGE_STORAGE_KEY, fallback))
|
||||
|
||||
expect(storage.getItem).toHaveBeenCalledWith(USAGE_RANGE_STORAGE_KEY)
|
||||
expect(result.current[0]).toEqual(fallback)
|
||||
})
|
||||
|
||||
it('returns a valid stored selection for the session storage key', () => {
|
||||
storage.setItem(SESSION_USAGE_RANGE_STORAGE_KEY, JSON.stringify({ preset: 'custom', from: 1000, to: 2000 }))
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useUsageRangePreference(SESSION_USAGE_RANGE_STORAGE_KEY, { preset: 'all' }),
|
||||
)
|
||||
|
||||
expect(storage.getItem).toHaveBeenCalledWith(SESSION_USAGE_RANGE_STORAGE_KEY)
|
||||
expect(result.current[0]).toEqual({ preset: 'custom', from: 1000, to: 2000 })
|
||||
})
|
||||
|
||||
it('falls back when the stored value is corrupt JSON', () => {
|
||||
storage.setItem(USAGE_RANGE_STORAGE_KEY, 'not-json{{')
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useUsageRangePreference(USAGE_RANGE_STORAGE_KEY, { preset: '24h' }),
|
||||
)
|
||||
|
||||
expect(result.current[0]).toEqual({ preset: '24h' })
|
||||
})
|
||||
|
||||
it('falls back when the stored value is valid JSON but not a valid selection', () => {
|
||||
storage.setItem(USAGE_RANGE_STORAGE_KEY, JSON.stringify({ preset: 'tomorrow' }))
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useUsageRangePreference(USAGE_RANGE_STORAGE_KEY, { preset: '24h' }),
|
||||
)
|
||||
|
||||
expect(result.current[0]).toEqual({ preset: '24h' })
|
||||
})
|
||||
|
||||
it('persists a new selection under the passed key and reads it back on a fresh mount', () => {
|
||||
const selection = { preset: 'custom', from: 1000, to: 2000 } as const
|
||||
|
||||
const { result, unmount } = renderHook(() =>
|
||||
useUsageRangePreference(USAGE_RANGE_STORAGE_KEY, { preset: '4h' }),
|
||||
)
|
||||
|
||||
act(() => {
|
||||
result.current[1](selection)
|
||||
})
|
||||
|
||||
expect(storage.setItem).toHaveBeenCalledWith(
|
||||
USAGE_RANGE_STORAGE_KEY,
|
||||
JSON.stringify({ preset: 'custom', from: 1000, to: 2000 }),
|
||||
)
|
||||
expect(result.current[0]).toEqual(selection)
|
||||
|
||||
unmount()
|
||||
|
||||
const remount = renderHook(() =>
|
||||
useUsageRangePreference(USAGE_RANGE_STORAGE_KEY, { preset: '4h' }),
|
||||
)
|
||||
|
||||
expect(remount.result.current[0]).toEqual(selection)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useUsageModelsPreference', () => {
|
||||
it('returns an empty list and reads the models storage key when nothing is stored', () => {
|
||||
const { result } = renderHook(() => useUsageModelsPreference())
|
||||
|
||||
expect(storage.getItem).toHaveBeenCalledWith(USAGE_MODELS_STORAGE_KEY)
|
||||
expect(result.current[0]).toEqual([])
|
||||
})
|
||||
|
||||
it('returns a valid stored model list', () => {
|
||||
storage.setItem(USAGE_MODELS_STORAGE_KEY, JSON.stringify(['anthropic/claude', 'openai/gpt']))
|
||||
|
||||
const { result } = renderHook(() => useUsageModelsPreference())
|
||||
|
||||
expect(result.current[0]).toEqual(['anthropic/claude', 'openai/gpt'])
|
||||
})
|
||||
|
||||
it('falls back to an empty list for corrupt JSON and invalid shapes', () => {
|
||||
storage.setItem(USAGE_MODELS_STORAGE_KEY, 'not-json{{')
|
||||
const corrupt = renderHook(() => useUsageModelsPreference())
|
||||
expect(corrupt.result.current[0]).toEqual([])
|
||||
|
||||
storage.setItem(USAGE_MODELS_STORAGE_KEY, JSON.stringify([1, 2]))
|
||||
const invalid = renderHook(() => useUsageModelsPreference())
|
||||
expect(invalid.result.current[0]).toEqual([])
|
||||
})
|
||||
|
||||
it('persists a new list under the models key and reads it back on a fresh mount', () => {
|
||||
const { result, unmount } = renderHook(() => useUsageModelsPreference())
|
||||
|
||||
act(() => {
|
||||
result.current[1](['anthropic/claude'])
|
||||
})
|
||||
|
||||
expect(storage.setItem).toHaveBeenCalledWith(USAGE_MODELS_STORAGE_KEY, JSON.stringify(['anthropic/claude']))
|
||||
expect(result.current[0]).toEqual(['anthropic/claude'])
|
||||
|
||||
unmount()
|
||||
|
||||
const remount = renderHook(() => useUsageModelsPreference())
|
||||
|
||||
expect(remount.result.current[0]).toEqual(['anthropic/claude'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('storage keys', () => {
|
||||
it('exports the expected oc:usage storage keys', () => {
|
||||
expect(USAGE_RANGE_STORAGE_KEY).toBe('oc:usage:range')
|
||||
expect(SESSION_USAGE_RANGE_STORAGE_KEY).toBe('oc:usage:session-range')
|
||||
expect(USAGE_MODELS_STORAGE_KEY).toBe('oc:usage:models')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useState, useCallback } from 'react'
|
||||
import { z } from 'zod'
|
||||
import type { JsonValue } from '@opencode-manager/shared/utils'
|
||||
import { parseJsonText } from '@opencode-manager/shared/utils'
|
||||
import { readStoredValue, writeStoredValue } from '@/lib/persistentStorage'
|
||||
import { usageRangeSelectionSchema } from '@/lib/usageRange'
|
||||
import type { UsageRangeSelection } from '@/lib/usageRange'
|
||||
|
||||
export const USAGE_RANGE_STORAGE_KEY = 'oc:usage:range'
|
||||
export const SESSION_USAGE_RANGE_STORAGE_KEY = 'oc:usage:session-range'
|
||||
export const USAGE_MODELS_STORAGE_KEY = 'oc:usage:models'
|
||||
|
||||
const usageModelsSchema = z.array(z.string())
|
||||
|
||||
function readStoredJson<T extends JsonValue>(
|
||||
storageKey: string,
|
||||
schema: z.ZodType<T>,
|
||||
fallback: T,
|
||||
): T {
|
||||
const stored = readStoredValue(storageKey)
|
||||
if (stored === null) {
|
||||
return fallback
|
||||
}
|
||||
const parsed = schema.safeParse(parseJsonText(stored))
|
||||
return parsed.success ? parsed.data : fallback
|
||||
}
|
||||
|
||||
function useStoredJson<T extends JsonValue>(
|
||||
storageKey: string,
|
||||
schema: z.ZodType<T>,
|
||||
fallback: T,
|
||||
): [T, (value: T) => void] {
|
||||
const [value, setValue] = useState<T>(() => readStoredJson(storageKey, schema, fallback))
|
||||
|
||||
const setStoredValue = useCallback(
|
||||
(next: T) => {
|
||||
writeStoredValue(storageKey, next)
|
||||
setValue(next)
|
||||
},
|
||||
[storageKey],
|
||||
)
|
||||
|
||||
return [value, setStoredValue]
|
||||
}
|
||||
|
||||
export function useUsageRangePreference(
|
||||
storageKey: string,
|
||||
fallback: UsageRangeSelection,
|
||||
): [UsageRangeSelection, (selection: UsageRangeSelection) => void] {
|
||||
return useStoredJson(storageKey, usageRangeSelectionSchema, fallback)
|
||||
}
|
||||
|
||||
export function useUsageModelsPreference(): [string[], (models: string[]) => void] {
|
||||
return useStoredJson(USAGE_MODELS_STORAGE_KEY, usageModelsSchema, [])
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
DEFAULT_GLOBAL_USAGE_RANGE,
|
||||
DEFAULT_SESSION_USAGE_RANGE,
|
||||
USAGE_RANGE_LABELS,
|
||||
USAGE_RANGE_PRESETS,
|
||||
isWithinUsageRange,
|
||||
rangeHasDailyActivity,
|
||||
resolveUsageRange,
|
||||
usageRangeSelectionSchema,
|
||||
} from './usageRange'
|
||||
import type { UsageRangePreset, UsageRangeSelection } from './usageRange'
|
||||
|
||||
const NOW = 1_000_000_000
|
||||
|
||||
describe('USAGE_RANGE_PRESETS', () => {
|
||||
it('lists every preset in display order', () => {
|
||||
expect([...USAGE_RANGE_PRESETS]).toEqual([
|
||||
'15m',
|
||||
'1h',
|
||||
'4h',
|
||||
'8h',
|
||||
'24h',
|
||||
'48h',
|
||||
'7d',
|
||||
'30d',
|
||||
'90d',
|
||||
'all',
|
||||
'custom',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('USAGE_RANGE_LABELS', () => {
|
||||
it('labels every preset', () => {
|
||||
expect(USAGE_RANGE_LABELS).toEqual({
|
||||
'15m': 'Last 15 minutes',
|
||||
'1h': 'Last hour',
|
||||
'4h': 'Last 4 hours',
|
||||
'8h': 'Last 8 hours',
|
||||
'24h': 'Last 24 hours',
|
||||
'48h': 'Last 48 hours',
|
||||
'7d': 'Last 7 days',
|
||||
'30d': 'Last 30 days',
|
||||
'90d': 'Last 90 days',
|
||||
all: 'All time',
|
||||
custom: 'Custom',
|
||||
})
|
||||
})
|
||||
|
||||
it('has a label for each preset in the preset list', () => {
|
||||
for (const preset of USAGE_RANGE_PRESETS) {
|
||||
expect(USAGE_RANGE_LABELS[preset satisfies UsageRangePreset]).toEqual(expect.any(String))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('defaults', () => {
|
||||
it('defaults the global range to four hours and sessions to all time', () => {
|
||||
expect(DEFAULT_GLOBAL_USAGE_RANGE).toEqual({ preset: '4h' })
|
||||
expect(DEFAULT_SESSION_USAGE_RANGE).toEqual({ preset: 'all' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveUsageRange', () => {
|
||||
it('resolves the four hour preset to exact bounds', () => {
|
||||
expect(resolveUsageRange({ preset: '4h' }, NOW)).toEqual({
|
||||
from: NOW - 14_400_000,
|
||||
to: NOW,
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves each relative preset duration', () => {
|
||||
const durations: Array<[Exclude<UsageRangePreset, 'all' | 'custom'>, number]> = [
|
||||
['15m', 900_000],
|
||||
['1h', 3_600_000],
|
||||
['4h', 14_400_000],
|
||||
['8h', 28_800_000],
|
||||
['24h', 86_400_000],
|
||||
['48h', 172_800_000],
|
||||
['7d', 604_800_000],
|
||||
['30d', 2_592_000_000],
|
||||
['90d', 7_776_000_000],
|
||||
]
|
||||
|
||||
for (const [preset, duration] of durations) {
|
||||
expect(resolveUsageRange({ preset }, NOW)).toEqual({ from: NOW - duration, to: NOW })
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves all time to an unbounded range', () => {
|
||||
expect(resolveUsageRange({ preset: 'all' }, NOW)).toEqual({})
|
||||
})
|
||||
|
||||
it('resolves a complete custom range to its bounds', () => {
|
||||
expect(resolveUsageRange({ preset: 'custom', from: 10, to: 20 }, NOW)).toEqual({
|
||||
from: 10,
|
||||
to: 20,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects custom ranges with a missing bound', () => {
|
||||
expect(resolveUsageRange({ preset: 'custom', from: null, to: 20 }, NOW)).toBeNull()
|
||||
expect(resolveUsageRange({ preset: 'custom', from: 10, to: null }, NOW)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects custom ranges that are empty or reversed', () => {
|
||||
expect(resolveUsageRange({ preset: 'custom', from: 10, to: 10 }, NOW)).toBeNull()
|
||||
expect(resolveUsageRange({ preset: 'custom', from: 20, to: 10 }, NOW)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('rangeHasDailyActivity', () => {
|
||||
it('enables daily activity for multi-day presets and all time', () => {
|
||||
for (const preset of ['7d', '30d', '90d', 'all'] as const) {
|
||||
expect(rangeHasDailyActivity({ preset }, NOW)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('disables daily activity for short presets', () => {
|
||||
for (const preset of ['15m', '1h', '4h', '8h', '24h', '48h'] as const) {
|
||||
expect(rangeHasDailyActivity({ preset }, NOW)).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('enables daily activity for custom ranges spanning at least 48 hours', () => {
|
||||
const fortyEightHours: UsageRangeSelection = { preset: 'custom', from: 0, to: 172_800_000 }
|
||||
expect(rangeHasDailyActivity(fortyEightHours, NOW)).toBe(true)
|
||||
})
|
||||
|
||||
it('disables daily activity for custom ranges under 48 hours', () => {
|
||||
const fortySevenHours: UsageRangeSelection = { preset: 'custom', from: 0, to: 169_200_000 }
|
||||
expect(rangeHasDailyActivity(fortySevenHours, NOW)).toBe(false)
|
||||
})
|
||||
|
||||
it('disables daily activity for incomplete custom ranges', () => {
|
||||
expect(rangeHasDailyActivity({ preset: 'custom', from: null, to: 20 }, NOW)).toBe(false)
|
||||
expect(rangeHasDailyActivity({ preset: 'custom', from: 10, to: null }, NOW)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isWithinUsageRange', () => {
|
||||
it('checks both bounds inclusively', () => {
|
||||
expect(isWithinUsageRange(5, { from: 5, to: 10 })).toBe(true)
|
||||
expect(isWithinUsageRange(10, { from: 5, to: 10 })).toBe(true)
|
||||
expect(isWithinUsageRange(7, { from: 5, to: 10 })).toBe(true)
|
||||
expect(isWithinUsageRange(4, { from: 5, to: 10 })).toBe(false)
|
||||
expect(isWithinUsageRange(11, { from: 5, to: 10 })).toBe(false)
|
||||
})
|
||||
|
||||
it('treats a missing lower bound as open', () => {
|
||||
expect(isWithinUsageRange(-1_000, { to: 10 })).toBe(true)
|
||||
expect(isWithinUsageRange(11, { to: 10 })).toBe(false)
|
||||
})
|
||||
|
||||
it('treats a missing upper bound as open', () => {
|
||||
expect(isWithinUsageRange(1_000, { from: 5 })).toBe(true)
|
||||
expect(isWithinUsageRange(4, { from: 5 })).toBe(false)
|
||||
})
|
||||
|
||||
it('treats an empty range as unbounded', () => {
|
||||
expect(isWithinUsageRange(0, {})).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('usageRangeSelectionSchema', () => {
|
||||
it('accepts preset selections', () => {
|
||||
expect(usageRangeSelectionSchema.parse({ preset: '4h' })).toEqual({ preset: '4h' })
|
||||
expect(usageRangeSelectionSchema.parse({ preset: 'all' })).toEqual({ preset: 'all' })
|
||||
})
|
||||
|
||||
it('accepts complete custom selections with nullable bounds', () => {
|
||||
expect(usageRangeSelectionSchema.parse({ preset: 'custom', from: 1, to: 2 })).toEqual({
|
||||
preset: 'custom',
|
||||
from: 1,
|
||||
to: 2,
|
||||
})
|
||||
expect(
|
||||
usageRangeSelectionSchema.parse({ preset: 'custom', from: null, to: null }),
|
||||
).toEqual({ preset: 'custom', from: null, to: null })
|
||||
})
|
||||
|
||||
it('rejects unknown presets', () => {
|
||||
expect(usageRangeSelectionSchema.safeParse({ preset: '2h' }).success).toBe(false)
|
||||
expect(usageRangeSelectionSchema.safeParse({ preset: '' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects custom selections without bounds', () => {
|
||||
expect(usageRangeSelectionSchema.safeParse({ preset: 'custom' }).success).toBe(false)
|
||||
expect(usageRangeSelectionSchema.safeParse({ preset: 'custom', from: 1 }).success).toBe(false)
|
||||
expect(usageRangeSelectionSchema.safeParse({ preset: 'custom', to: 2 }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects non-numeric bounds', () => {
|
||||
expect(
|
||||
usageRangeSelectionSchema.safeParse({ preset: 'custom', from: '1', to: 2 }).success,
|
||||
).toBe(false)
|
||||
expect(
|
||||
usageRangeSelectionSchema.safeParse({ preset: 'custom', from: 1, to: '2' }).success,
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const USAGE_RANGE_PRESETS = [
|
||||
'15m',
|
||||
'1h',
|
||||
'4h',
|
||||
'8h',
|
||||
'24h',
|
||||
'48h',
|
||||
'7d',
|
||||
'30d',
|
||||
'90d',
|
||||
'all',
|
||||
'custom',
|
||||
] as const
|
||||
|
||||
export type UsageRangePreset = (typeof USAGE_RANGE_PRESETS)[number]
|
||||
|
||||
type RelativeUsageRangePreset = Exclude<UsageRangePreset, 'all' | 'custom'>
|
||||
type BoundedUsageRangePreset = Exclude<UsageRangePreset, 'custom'>
|
||||
|
||||
export const USAGE_RANGE_LABELS: Record<UsageRangePreset, string> = {
|
||||
'15m': 'Last 15 minutes',
|
||||
'1h': 'Last hour',
|
||||
'4h': 'Last 4 hours',
|
||||
'8h': 'Last 8 hours',
|
||||
'24h': 'Last 24 hours',
|
||||
'48h': 'Last 48 hours',
|
||||
'7d': 'Last 7 days',
|
||||
'30d': 'Last 30 days',
|
||||
'90d': 'Last 90 days',
|
||||
all: 'All time',
|
||||
custom: 'Custom',
|
||||
}
|
||||
|
||||
export type UsageRangeSelection =
|
||||
| { preset: Exclude<UsageRangePreset, 'custom'> }
|
||||
| { preset: 'custom'; from: number | null; to: number | null }
|
||||
|
||||
const RELATIVE_USAGE_RANGE_DURATIONS: Record<RelativeUsageRangePreset, number> = {
|
||||
'15m': 900_000,
|
||||
'1h': 3_600_000,
|
||||
'4h': 14_400_000,
|
||||
'8h': 28_800_000,
|
||||
'24h': 86_400_000,
|
||||
'48h': 172_800_000,
|
||||
'7d': 604_800_000,
|
||||
'30d': 2_592_000_000,
|
||||
'90d': 7_776_000_000,
|
||||
}
|
||||
|
||||
const DAILY_ACTIVITY_PRESETS: ReadonlySet<UsageRangePreset> = new Set([
|
||||
'7d',
|
||||
'30d',
|
||||
'90d',
|
||||
'all',
|
||||
])
|
||||
|
||||
const MIN_DAILY_ACTIVITY_SPAN_MS = 172_800_000
|
||||
|
||||
const BOUNDED_USAGE_RANGE_PRESETS = USAGE_RANGE_PRESETS.filter(
|
||||
(preset): preset is BoundedUsageRangePreset => preset !== 'custom',
|
||||
)
|
||||
|
||||
const CustomUsageRangeSelectionSchema = z.object({
|
||||
preset: z.literal('custom'),
|
||||
from: z.number().nullable(),
|
||||
to: z.number().nullable(),
|
||||
})
|
||||
|
||||
export const usageRangeSelectionSchema: z.ZodType<UsageRangeSelection> = z.discriminatedUnion(
|
||||
'preset',
|
||||
[
|
||||
z.object({ preset: z.enum(BOUNDED_USAGE_RANGE_PRESETS) }),
|
||||
CustomUsageRangeSelectionSchema,
|
||||
],
|
||||
)
|
||||
|
||||
export const DEFAULT_GLOBAL_USAGE_RANGE: UsageRangeSelection = { preset: '4h' }
|
||||
|
||||
export const DEFAULT_SESSION_USAGE_RANGE: UsageRangeSelection = { preset: 'all' }
|
||||
|
||||
export type ResolvedUsageRange = { from?: number; to?: number }
|
||||
|
||||
export function resolveUsageRange(
|
||||
selection: UsageRangeSelection,
|
||||
now: number,
|
||||
): ResolvedUsageRange | null {
|
||||
if (selection.preset === 'custom') {
|
||||
if (selection.from === null || selection.to === null) return null
|
||||
if (selection.from >= selection.to) return null
|
||||
return { from: selection.from, to: selection.to }
|
||||
}
|
||||
|
||||
if (selection.preset === 'all') return {}
|
||||
|
||||
return { from: now - RELATIVE_USAGE_RANGE_DURATIONS[selection.preset], to: now }
|
||||
}
|
||||
|
||||
export function rangeHasDailyActivity(selection: UsageRangeSelection, now: number): boolean {
|
||||
if (selection.preset !== 'custom') return DAILY_ACTIVITY_PRESETS.has(selection.preset)
|
||||
|
||||
const range = resolveUsageRange(selection, now)
|
||||
if (range?.from === undefined || range.to === undefined) return false
|
||||
return range.to - range.from >= MIN_DAILY_ACTIVITY_SPAN_MS
|
||||
}
|
||||
|
||||
export function isWithinUsageRange(time: number, range: ResolvedUsageRange): boolean {
|
||||
if (range.from !== undefined && time < range.from) return false
|
||||
if (range.to !== undefined && time > range.to) return false
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type {
|
||||
ModelRef,
|
||||
SessionMessageAssistant,
|
||||
SessionMessageAssistantTool,
|
||||
SessionStatsModelUsage,
|
||||
TokenUsageInfo,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
filterModelUsage,
|
||||
formatTokensPerSecond,
|
||||
formatUsd,
|
||||
modelUsageKey,
|
||||
stepThroughput,
|
||||
summarizeSessionSteps,
|
||||
sumModelUsage,
|
||||
totalTokens,
|
||||
} from './usageStats'
|
||||
|
||||
const MODEL_A: ModelRef = { providerID: 'anthropic', id: 'claude-opus-5-5' }
|
||||
const MODEL_B: ModelRef = { providerID: 'openai', id: 'gpt-5', variant: 'high' }
|
||||
|
||||
function tokens(
|
||||
fields: {
|
||||
input?: number
|
||||
output?: number
|
||||
reasoning?: number
|
||||
cacheRead?: number
|
||||
cacheWrite?: number
|
||||
} = {},
|
||||
): TokenUsageInfo {
|
||||
return {
|
||||
input: fields.input ?? 0,
|
||||
output: fields.output ?? 0,
|
||||
reasoning: fields.reasoning ?? 0,
|
||||
cache: { read: fields.cacheRead ?? 0, write: fields.cacheWrite ?? 0 },
|
||||
}
|
||||
}
|
||||
|
||||
let stepSequence = 0
|
||||
|
||||
function step(
|
||||
overrides: Partial<Omit<SessionMessageAssistant, 'id' | 'type'>> & {
|
||||
time: SessionMessageAssistant['time']
|
||||
},
|
||||
): SessionMessageAssistant {
|
||||
stepSequence += 1
|
||||
return {
|
||||
id: `msg_${stepSequence}`,
|
||||
type: 'assistant',
|
||||
agent: 'build',
|
||||
model: MODEL_A,
|
||||
content: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
let toolSequence = 0
|
||||
|
||||
function completedTool(
|
||||
name: string,
|
||||
time: { created: number; ran?: number; completed: number },
|
||||
): SessionMessageAssistantTool {
|
||||
toolSequence += 1
|
||||
return {
|
||||
type: 'tool',
|
||||
id: `tool_${toolSequence}`,
|
||||
name,
|
||||
time,
|
||||
state: { status: 'completed', input: {}, content: [{ type: 'text', text: 'ok' }] },
|
||||
}
|
||||
}
|
||||
|
||||
function failedTool(name: string, created: number): SessionMessageAssistantTool {
|
||||
toolSequence += 1
|
||||
return {
|
||||
type: 'tool',
|
||||
id: `tool_${toolSequence}`,
|
||||
name,
|
||||
time: { created },
|
||||
state: { status: 'error', input: {}, error: { type: 'tool_error', message: 'boom' } },
|
||||
}
|
||||
}
|
||||
|
||||
function runningTool(name: string, created: number): SessionMessageAssistantTool {
|
||||
toolSequence += 1
|
||||
return {
|
||||
type: 'tool',
|
||||
id: `tool_${toolSequence}`,
|
||||
name,
|
||||
time: { created },
|
||||
state: { status: 'running', input: {}, metadata: {} },
|
||||
}
|
||||
}
|
||||
|
||||
const RANGE = { from: 0, to: 5000 }
|
||||
|
||||
function sessionSteps(): SessionMessageAssistant[] {
|
||||
return [
|
||||
step({
|
||||
time: { created: 1000, streamed: 3000 },
|
||||
model: MODEL_A,
|
||||
tokens: tokens({ input: 100, output: 20, reasoning: 5, cacheRead: 10, cacheWrite: 2 }),
|
||||
cost: 0.5,
|
||||
content: [completedTool('bash', { created: 1000, ran: 1500, completed: 3500 })],
|
||||
}),
|
||||
step({
|
||||
time: { created: 2000, streamed: 4000 },
|
||||
model: MODEL_B,
|
||||
tokens: tokens({ input: 200, output: 30, reasoning: 10, cacheRead: 20, cacheWrite: 4 }),
|
||||
cost: 0.25,
|
||||
content: [failedTool('bash', 2000), runningTool('bash', 2500)],
|
||||
}),
|
||||
step({
|
||||
time: { created: 3000, completed: 9000 },
|
||||
model: MODEL_A,
|
||||
tokens: tokens({ input: 50, output: 10 }),
|
||||
cost: 0.05,
|
||||
content: [completedTool('read', { created: 3000, completed: 4000 })],
|
||||
}),
|
||||
step({
|
||||
time: { created: 10_000, streamed: 12_000 },
|
||||
model: MODEL_B,
|
||||
tokens: tokens({ input: 999, output: 999 }),
|
||||
cost: 9,
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
describe('totalTokens', () => {
|
||||
it('sums input, output, reasoning and both cache fields', () => {
|
||||
expect(
|
||||
totalTokens(
|
||||
tokens({ input: 1, output: 2, reasoning: 3, cacheRead: 4, cacheWrite: 5 }),
|
||||
),
|
||||
).toBe(15)
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelUsageKey', () => {
|
||||
it('formats provider and model id', () => {
|
||||
expect(modelUsageKey(MODEL_A)).toBe('anthropic/claude-opus-5-5')
|
||||
})
|
||||
|
||||
it('includes the variant suffix when present', () => {
|
||||
expect(modelUsageKey(MODEL_B)).toBe('openai/gpt-5#high')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatUsd', () => {
|
||||
it('shows four fraction digits below one dollar', () => {
|
||||
expect(formatUsd(0.0123)).toBe('$0.0123')
|
||||
})
|
||||
|
||||
it('shows two fraction digits from one dollar', () => {
|
||||
expect(formatUsd(1.5)).toBe('$1.50')
|
||||
})
|
||||
|
||||
it('shows a four digit zero for no spend', () => {
|
||||
expect(formatUsd(0)).toBe('$0.0000')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatTokensPerSecond', () => {
|
||||
it('shows a dash when the rate is unknown', () => {
|
||||
expect(formatTokensPerSecond(null)).toBe('—')
|
||||
})
|
||||
|
||||
it('shows one fraction digit with a unit', () => {
|
||||
expect(formatTokensPerSecond(42.14)).toBe('42.1 tok/s')
|
||||
})
|
||||
})
|
||||
|
||||
describe('stepThroughput', () => {
|
||||
it('measures output and reasoning tokens over the streamed span', () => {
|
||||
const measured = step({
|
||||
time: { created: 1000, streamed: 3000 },
|
||||
tokens: tokens({ output: 40, reasoning: 2 }),
|
||||
})
|
||||
expect(stepThroughput(measured)).toEqual({ tokens: 42, seconds: 2 })
|
||||
})
|
||||
|
||||
it('ignores the completed time when streamed is missing', () => {
|
||||
const measured = step({
|
||||
time: { created: 1000, completed: 5000 },
|
||||
tokens: tokens({ output: 40 }),
|
||||
})
|
||||
expect(stepThroughput(measured)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when streaming did not advance past creation', () => {
|
||||
const measured = step({
|
||||
time: { created: 1000, streamed: 1000 },
|
||||
tokens: tokens({ output: 40 }),
|
||||
})
|
||||
expect(stepThroughput(measured)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when the step has no tokens', () => {
|
||||
const measured = step({ time: { created: 1000, streamed: 3000 } })
|
||||
expect(stepThroughput(measured)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeSessionSteps', () => {
|
||||
it('totals steps, cost and every token field', () => {
|
||||
const summary = summarizeSessionSteps(sessionSteps(), { range: RANGE, models: [] })
|
||||
expect(summary.steps).toBe(3)
|
||||
expect(summary.cost).toBeCloseTo(0.8)
|
||||
expect(summary.tokens).toEqual(
|
||||
tokens({ input: 350, output: 60, reasoning: 15, cacheRead: 30, cacheWrite: 6 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('excludes steps outside the range', () => {
|
||||
const all = summarizeSessionSteps(sessionSteps(), { range: {}, models: [] })
|
||||
const ranged = summarizeSessionSteps(sessionSteps(), { range: RANGE, models: [] })
|
||||
expect(all.steps).toBe(4)
|
||||
expect(ranged.steps).toBe(3)
|
||||
expect(ranged.cost).toBeCloseTo(0.8)
|
||||
})
|
||||
|
||||
it('keeps every available model while filtering to the selected one', () => {
|
||||
const summary = summarizeSessionSteps(sessionSteps(), {
|
||||
range: RANGE,
|
||||
models: [modelUsageKey(MODEL_B)],
|
||||
})
|
||||
expect(summary.steps).toBe(1)
|
||||
expect(summary.cost).toBeCloseTo(0.25)
|
||||
expect(summary.models).toHaveLength(1)
|
||||
expect(summary.models[0].model).toEqual(MODEL_B)
|
||||
expect(summary.models[0].tokens).toEqual(
|
||||
tokens({ input: 200, output: 30, reasoning: 10, cacheRead: 20, cacheWrite: 4 }),
|
||||
)
|
||||
expect(summary.availableModels).toEqual(['anthropic/claude-opus-5-5', 'openai/gpt-5#high'])
|
||||
})
|
||||
|
||||
it('groups models by key and sorts them by cost, then steps', () => {
|
||||
const summary = summarizeSessionSteps(sessionSteps(), { range: RANGE, models: [] })
|
||||
expect(summary.models.map((entry) => modelUsageKey(entry.model))).toEqual([
|
||||
'anthropic/claude-opus-5-5',
|
||||
'openai/gpt-5#high',
|
||||
])
|
||||
expect(summary.models[0].steps).toBe(2)
|
||||
expect(summary.models[0].cost).toBeCloseTo(0.55)
|
||||
expect(summary.models[1].steps).toBe(1)
|
||||
|
||||
const tiedCost = [
|
||||
step({ time: { created: 1000 }, model: MODEL_A, cost: 0.75, tokens: tokens({ input: 1 }) }),
|
||||
step({ time: { created: 1000 }, model: MODEL_B, cost: 0.25, tokens: tokens({ input: 1 }) }),
|
||||
step({ time: { created: 1000 }, model: MODEL_B, cost: 0.25, tokens: tokens({ input: 1 }) }),
|
||||
step({ time: { created: 1000 }, model: MODEL_B, cost: 0.25, tokens: tokens({ input: 1 }) }),
|
||||
]
|
||||
const bySteps = summarizeSessionSteps(tiedCost, { range: {}, models: [] })
|
||||
expect(bySteps.models.map((entry) => modelUsageKey(entry.model))).toEqual([
|
||||
'openai/gpt-5#high',
|
||||
'anthropic/claude-opus-5-5',
|
||||
])
|
||||
})
|
||||
|
||||
it('weights tokens per second over steps that streamed, ignoring completed-only spans', () => {
|
||||
const summary = summarizeSessionSteps(sessionSteps(), { range: RANGE, models: [] })
|
||||
expect(summary.averageTokensPerSecond).toBeCloseTo(16.25)
|
||||
|
||||
const withoutThroughput = summarizeSessionSteps(
|
||||
[step({ time: { created: 1000, completed: 11_000 }, tokens: tokens({ output: 10 }) })],
|
||||
{ range: {}, models: [] },
|
||||
)
|
||||
expect(withoutThroughput.averageTokensPerSecond).toBeNull()
|
||||
})
|
||||
|
||||
it('counts tool outcomes and takes the median duration', () => {
|
||||
const summary = summarizeSessionSteps(sessionSteps(), { range: RANGE, models: [] })
|
||||
expect(summary.tools).toEqual([
|
||||
{ name: 'bash', calls: 3, succeeded: 1, failed: 1, unfinished: 1, durationP50: 2000 },
|
||||
{ name: 'read', calls: 1, succeeded: 1, failed: 0, unfinished: 0, durationP50: 1000 },
|
||||
])
|
||||
})
|
||||
|
||||
it('averages the two middle tool durations for an even count', () => {
|
||||
const summary = summarizeSessionSteps(
|
||||
[
|
||||
step({
|
||||
time: { created: 1000 },
|
||||
content: [
|
||||
completedTool('bash', { created: 0, completed: 1000 }),
|
||||
completedTool('bash', { created: 0, completed: 3000 }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
{ range: {}, models: [] },
|
||||
)
|
||||
expect(summary.tools).toEqual([
|
||||
{ name: 'bash', calls: 2, succeeded: 2, failed: 0, unfinished: 0, durationP50: 2000 },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
const modelUsage: SessionStatsModelUsage[] = [
|
||||
{
|
||||
model: MODEL_A,
|
||||
steps: 2,
|
||||
tokens: tokens({ input: 10, output: 5, reasoning: 1, cacheRead: 2, cacheWrite: 1 }),
|
||||
cost: 0.5,
|
||||
},
|
||||
{
|
||||
model: MODEL_B,
|
||||
steps: 1,
|
||||
tokens: tokens({ input: 3, output: 2, reasoning: 0, cacheRead: 1, cacheWrite: 0 }),
|
||||
cost: 0.25,
|
||||
},
|
||||
]
|
||||
|
||||
describe('sumModelUsage', () => {
|
||||
it('sums steps, cost and every token field', () => {
|
||||
expect(sumModelUsage(modelUsage)).toEqual({
|
||||
steps: 3,
|
||||
tokens: tokens({ input: 13, output: 7, reasoning: 1, cacheRead: 3, cacheWrite: 1 }),
|
||||
cost: 0.75,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns zeroed totals for no models', () => {
|
||||
expect(sumModelUsage([])).toEqual({ steps: 0, tokens: tokens(), cost: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('filterModelUsage', () => {
|
||||
it('treats an empty selection as every model', () => {
|
||||
expect(filterModelUsage(modelUsage, [])).toEqual(sumModelUsage(modelUsage))
|
||||
})
|
||||
|
||||
it('keeps only the selected model keys', () => {
|
||||
expect(filterModelUsage(modelUsage, [modelUsageKey(MODEL_B)])).toEqual({
|
||||
steps: 1,
|
||||
tokens: tokens({ input: 3, output: 2, reasoning: 0, cacheRead: 1, cacheWrite: 0 }),
|
||||
cost: 0.25,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
import { formatOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
import type {
|
||||
ModelRef,
|
||||
SessionMessageAssistant,
|
||||
SessionStatsModelUsage,
|
||||
TokenUsageInfo,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { isWithinUsageRange } from '@/lib/usageRange'
|
||||
|
||||
export interface ModelUsageTotals {
|
||||
steps: number
|
||||
tokens: TokenUsageInfo
|
||||
cost: number
|
||||
}
|
||||
|
||||
export interface StepThroughput {
|
||||
tokens: number
|
||||
seconds: number
|
||||
}
|
||||
|
||||
export interface SessionUsageSummary {
|
||||
steps: number
|
||||
cost: number
|
||||
tokens: TokenUsageInfo
|
||||
averageTokensPerSecond: number | null
|
||||
models: Array<{ model: ModelRef; steps: number; tokens: TokenUsageInfo; cost: number }>
|
||||
tools: Array<{
|
||||
name: string
|
||||
calls: number
|
||||
succeeded: number
|
||||
failed: number
|
||||
unfinished: number
|
||||
durationP50?: number
|
||||
}>
|
||||
availableModels: string[]
|
||||
}
|
||||
|
||||
interface ModelUsageGroup {
|
||||
model: ModelRef
|
||||
steps: number
|
||||
tokens: TokenUsageInfo
|
||||
cost: number
|
||||
}
|
||||
|
||||
interface ToolUsageGroup {
|
||||
name: string
|
||||
calls: number
|
||||
succeeded: number
|
||||
failed: number
|
||||
unfinished: number
|
||||
durations: number[]
|
||||
}
|
||||
|
||||
function emptyTokens(): TokenUsageInfo {
|
||||
return { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
|
||||
}
|
||||
|
||||
function addTokens(target: TokenUsageInfo, tokens: TokenUsageInfo): void {
|
||||
target.input += tokens.input
|
||||
target.output += tokens.output
|
||||
target.reasoning += tokens.reasoning
|
||||
target.cache.read += tokens.cache.read
|
||||
target.cache.write += tokens.cache.write
|
||||
}
|
||||
|
||||
function median(values: number[]): number | undefined {
|
||||
if (values.length === 0) return undefined
|
||||
const sorted = [...values].sort((a, b) => a - b)
|
||||
const middle = Math.floor(sorted.length / 2)
|
||||
if (sorted.length % 2 === 0) return (sorted[middle - 1] + sorted[middle]) / 2
|
||||
return sorted[middle]
|
||||
}
|
||||
|
||||
export function totalTokens(tokens: TokenUsageInfo): number {
|
||||
return (
|
||||
tokens.input + tokens.output + tokens.reasoning + tokens.cache.read + tokens.cache.write
|
||||
)
|
||||
}
|
||||
|
||||
export function modelUsageKey(ref: ModelRef): string {
|
||||
return formatOpenCodeModelRef(ref)
|
||||
}
|
||||
|
||||
export function formatUsd(cost: number): string {
|
||||
const fractionDigits = cost < 1 ? 4 : 2
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: fractionDigits,
|
||||
maximumFractionDigits: fractionDigits,
|
||||
}).format(cost)
|
||||
}
|
||||
|
||||
export function formatTokensPerSecond(value: number | null): string {
|
||||
return value === null ? '—' : `${value.toFixed(1)} tok/s`
|
||||
}
|
||||
|
||||
export function stepThroughput(step: SessionMessageAssistant): StepThroughput | null {
|
||||
const streamed = step.time.streamed
|
||||
if (!step.tokens || streamed === undefined || streamed <= step.time.created) return null
|
||||
return {
|
||||
tokens: step.tokens.output + step.tokens.reasoning,
|
||||
seconds: (streamed - step.time.created) / 1000,
|
||||
}
|
||||
}
|
||||
|
||||
export function sumModelUsage(models: SessionStatsModelUsage[]): ModelUsageTotals {
|
||||
const tokens = emptyTokens()
|
||||
let steps = 0
|
||||
let cost = 0
|
||||
for (const model of models) {
|
||||
steps += model.steps
|
||||
cost += model.cost
|
||||
addTokens(tokens, model.tokens)
|
||||
}
|
||||
return { steps, tokens, cost }
|
||||
}
|
||||
|
||||
export function filterModelUsage(
|
||||
models: SessionStatsModelUsage[],
|
||||
selectedKeys: string[],
|
||||
): ModelUsageTotals {
|
||||
if (selectedKeys.length === 0) return sumModelUsage(models)
|
||||
const selected = new Set(selectedKeys)
|
||||
return sumModelUsage(models.filter((model) => selected.has(modelUsageKey(model.model))))
|
||||
}
|
||||
|
||||
export function summarizeSessionSteps(
|
||||
steps: SessionMessageAssistant[],
|
||||
options: { range: { from?: number; to?: number }; models: string[] },
|
||||
): SessionUsageSummary {
|
||||
const inRange = steps.filter((step) => isWithinUsageRange(step.time.created, options.range))
|
||||
const availableModels = [...new Set(inRange.map((step) => modelUsageKey(step.model)))].sort()
|
||||
const selected = new Set(options.models)
|
||||
const filtered =
|
||||
selected.size === 0
|
||||
? inRange
|
||||
: inRange.filter((step) => selected.has(modelUsageKey(step.model)))
|
||||
|
||||
const tokens = emptyTokens()
|
||||
const modelsByKey = new Map<string, ModelUsageGroup>()
|
||||
const toolsByName = new Map<string, ToolUsageGroup>()
|
||||
let cost = 0
|
||||
let throughputTokens = 0
|
||||
let throughputSeconds = 0
|
||||
let throughputSteps = 0
|
||||
|
||||
for (const step of filtered) {
|
||||
cost += step.cost ?? 0
|
||||
if (step.tokens) addTokens(tokens, step.tokens)
|
||||
|
||||
const throughput = stepThroughput(step)
|
||||
if (throughput) {
|
||||
throughputSteps += 1
|
||||
throughputTokens += throughput.tokens
|
||||
throughputSeconds += throughput.seconds
|
||||
}
|
||||
|
||||
const key = modelUsageKey(step.model)
|
||||
let modelGroup = modelsByKey.get(key)
|
||||
if (!modelGroup) {
|
||||
modelGroup = { model: step.model, steps: 0, tokens: emptyTokens(), cost: 0 }
|
||||
modelsByKey.set(key, modelGroup)
|
||||
}
|
||||
modelGroup.steps += 1
|
||||
modelGroup.cost += step.cost ?? 0
|
||||
if (step.tokens) addTokens(modelGroup.tokens, step.tokens)
|
||||
|
||||
for (const item of step.content) {
|
||||
if (item.type !== 'tool') continue
|
||||
let toolGroup = toolsByName.get(item.name)
|
||||
if (!toolGroup) {
|
||||
toolGroup = {
|
||||
name: item.name,
|
||||
calls: 0,
|
||||
succeeded: 0,
|
||||
failed: 0,
|
||||
unfinished: 0,
|
||||
durations: [],
|
||||
}
|
||||
toolsByName.set(item.name, toolGroup)
|
||||
}
|
||||
toolGroup.calls += 1
|
||||
if (item.state.status === 'completed') toolGroup.succeeded += 1
|
||||
else if (item.state.status === 'error') toolGroup.failed += 1
|
||||
else toolGroup.unfinished += 1
|
||||
if (item.time.completed !== undefined) {
|
||||
toolGroup.durations.push(item.time.completed - (item.time.ran ?? item.time.created))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const modelEntries = [...modelsByKey.values()].sort(
|
||||
(a, b) => b.cost - a.cost || b.steps - a.steps,
|
||||
)
|
||||
|
||||
const toolEntries = [...toolsByName.values()]
|
||||
.sort((a, b) => b.calls - a.calls)
|
||||
.map((group) => {
|
||||
const durationP50 = median(group.durations)
|
||||
const entry = {
|
||||
name: group.name,
|
||||
calls: group.calls,
|
||||
succeeded: group.succeeded,
|
||||
failed: group.failed,
|
||||
unfinished: group.unfinished,
|
||||
}
|
||||
return durationP50 === undefined ? entry : { ...entry, durationP50 }
|
||||
})
|
||||
|
||||
return {
|
||||
steps: filtered.length,
|
||||
cost,
|
||||
tokens,
|
||||
averageTokensPerSecond:
|
||||
throughputSteps > 0 && throughputSeconds > 0
|
||||
? throughputTokens / throughputSeconds
|
||||
: null,
|
||||
models: modelEntries,
|
||||
tools: toolEntries,
|
||||
availableModels,
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ export type {
|
||||
AgentInfo,
|
||||
CommandInfo,
|
||||
ConfigEntry,
|
||||
ExperimentalSessionStatsInput,
|
||||
FileDiffInfo,
|
||||
FormAnswer,
|
||||
FormExternalField,
|
||||
@@ -42,10 +43,16 @@ export type {
|
||||
SessionMessageShell,
|
||||
SessionMessageUser,
|
||||
SessionRevert,
|
||||
SessionStatsActivity,
|
||||
SessionStatsInfo,
|
||||
SessionStatsModelUsage,
|
||||
SessionStatsTools,
|
||||
SessionStatsToolUsage,
|
||||
SessionStatus,
|
||||
SessionStructuredError,
|
||||
SessionTransferData,
|
||||
SkillInfo,
|
||||
TokenUsageInfo,
|
||||
V2Event,
|
||||
} from '@opencode/client'
|
||||
|
||||
|
||||
Reference in new issue
Block a user