Apply remaining changes

This commit is contained in:
Chris Scott authored and Forge Sandbox committed 2026-11-30 05:49:21 +00:00
1 parent 47bf801e34
commit 71fe35cd02
11 files changed
+592 -48

No files matched your search

+49 -13
View File
@@ -29,6 +29,12 @@ function assistantMessage(id: string, created: number) {
}
}
function fullPage(page: number): ReturnType<typeof assistantMessage>[] {
return Array.from({ length: SESSION_USAGE_PAGE_LIMIT }, (_, index) =>
assistantMessage(`msg_${page}_${index}`, page * 10_000 + index),
)
}
function userMessage(id: string, created: number) {
return { id, type: 'user', time: { created }, payload: { text: 'Run the tests' } }
}
@@ -86,7 +92,7 @@ describe('usage api', () => {
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' } } },
: { json: { data: fullPage(2), cursor: { next: 'cursor_1' } } },
},
])
@@ -98,7 +104,33 @@ describe('usage api', () => {
])
})
it('stops after a short page even when the server still returns a cursor', async () => {
const fetchFake = installRoutes([
{
method: 'GET',
path: messagesUrl,
respond: () => ({
json: {
data: [assistantMessage('msg_2', 2000), assistantMessage('msg_1', 1000)],
cursor: { next: 'cursor_1' },
},
}),
},
])
const result = await loadSessionUsageMessages('ses_1')
expect(result.steps.map((step) => step.id)).toEqual(['msg_1', 'msg_2'])
expect(result.truncated).toBe(false)
expect(fetchFake.findRequests('GET', messagesUrl).map((request) => request.searchParams.toString())).toEqual([
'limit=200&order=desc&type=assistant',
])
})
it('keeps only assistant steps and joins pages oldest-first', async () => {
const olderShells = Array.from({ length: SESSION_USAGE_PAGE_LIMIT - 3 }, (_, index) =>
shellMessage(`msg_shell_${index}`, 100 + index),
)
const fetchFake = installRoutes([
{
method: 'GET',
@@ -117,6 +149,7 @@ describe('usage api', () => {
assistantMessage('msg_5', 5000),
userMessage('msg_4', 4000),
assistantMessage('msg_3', 3000),
...olderShells,
],
cursor: { next: 'cursor_1' },
},
@@ -131,20 +164,20 @@ describe('usage api', () => {
expect(fetchFake.findRequests('GET', messagesUrl)).toHaveLength(2)
})
const truncationCases: Array<{ title: string; fifthCursor: string | undefined; truncated: boolean }> = [
const truncationCases: Array<{ title: string; fifthPageLength: number; truncated: boolean }> = [
{
title: 'reports truncation when the fifth page still has a cursor',
fifthCursor: 'cursor_5',
title: 'reports truncation when five full pages still leave a cursor',
fifthPageLength: SESSION_USAGE_PAGE_LIMIT,
truncated: true,
},
{
title: 'reports no truncation when the fifth page is the last one',
fifthCursor: undefined,
title: 'reports no truncation when the fifth page is short',
fifthPageLength: SESSION_USAGE_PAGE_LIMIT - 1,
truncated: false,
},
]
it.each(truncationCases)('$title', async ({ fifthCursor, truncated }) => {
it.each(truncationCases)('$title', async ({ fifthPageLength, truncated }) => {
let page = 0
const fetchFake = installRoutes([
{
@@ -152,12 +185,12 @@ describe('usage api', () => {
path: messagesUrl,
respond: () => {
page += 1
return {
json: {
data: [assistantMessage(`msg_${page}`, page * 1000)],
cursor: page < 5 ? { next: `cursor_${page}` } : fifthCursor ? { next: fifthCursor } : {},
},
}
const current = page
const messages =
current < SESSION_USAGE_MAX_PAGES
? fullPage(current)
: fullPage(current).slice(0, fifthPageLength)
return { json: { data: messages, cursor: { next: `cursor_${current}` } } }
},
},
])
@@ -165,6 +198,9 @@ describe('usage api', () => {
const result = await loadSessionUsageMessages('ses_1')
expect(fetchFake.findRequests('GET', messagesUrl)).toHaveLength(5)
expect(result.steps).toHaveLength(
(SESSION_USAGE_MAX_PAGES - 1) * SESSION_USAGE_PAGE_LIMIT + fifthPageLength,
)
expect(result.truncated).toBe(truncated)
})
})
+2 -2
View File
@@ -40,10 +40,10 @@ export async function loadSessionUsageMessages(
serverId,
)
steps.unshift(...result.messages.filter(isAssistantMessage))
cursor = result.nextCursor
if (cursor === undefined) {
if (result.nextCursor === undefined || result.messages.length < SESSION_USAGE_PAGE_LIMIT) {
return { steps, truncated: false }
}
cursor = result.nextCursor
}
return { steps, truncated: true }
@@ -6,6 +6,7 @@ import type {
SessionMessageAssistant,
SessionMessageAssistantTool,
} from '@opencode-manager/shared/opencode'
import { SESSION_USAGE_PAGE_LIMIT } from '@/api/usage'
import { installPointerCapture } from '@/test/browserFakes'
import type { FetchRoute } from '@/test/fetchFake'
import { renderWithProviders, type TestProviderOptions } from '@/test/render'
@@ -100,6 +101,12 @@ function statText(label: string): string {
return within(grid).getByText(label).parentElement?.textContent ?? ''
}
function assistantPage(page: number): SessionMessageAssistant[] {
return Array.from({ length: SESSION_USAGE_PAGE_LIMIT }, (_, index) =>
assistantStep({ id: `msg_${page}_${index}`, created: page * 10_000 + index }),
)
}
interface RenderOptions {
sessionId?: string
serverId?: string
@@ -301,7 +308,7 @@ describe('SessionUsageContent', () => {
page += 1
return {
json: {
data: [assistantStep({ id: `msg_${page}`, created: page })],
data: assistantPage(page),
cursor: { next: `cursor_${page}` },
},
}
@@ -315,6 +322,39 @@ describe('SessionUsageContent', () => {
expect(result.fetchFake.findRequests('GET', LOCAL_MESSAGES_PATH)).toHaveLength(5)
})
it('asks for a custom range instead of summarizing all time when the range is incomplete', async () => {
window.localStorage.setItem(
'oc:usage:session-range',
JSON.stringify({ preset: 'custom', from: null, to: null }),
)
renderContent({
fetchRoutes: [
messagesRoute({
messages: [assistantStep({ id: 'msg_1', created: 1000, cost: 1, input: 1000 })],
}),
],
})
expect(
await screen.findByText('Choose a start and end time to see usage for a custom range.'),
).toBeInTheDocument()
expect(screen.getByRole('combobox', { name: 'Range' })).toHaveTextContent('Custom')
expect(screen.queryByText('Spend')).not.toBeInTheDocument()
expect(screen.queryByText('No assistant steps in this range.')).not.toBeInTheDocument()
})
it('scrolls compact content inside the panel body', () => {
const result = renderWithProviders(<SessionUsageContent sessionId="ses_1" compact />, {
...providerOptions,
toaster: false,
fetchRoutes: [messagesRoute({ messages: [] })],
})
expect(result.container.firstElementChild).toHaveClass('overflow-y-auto')
expect(result.container.firstElementChild).toHaveClass('min-h-0', 'flex-1')
})
it('shows the error banner when the request fails', async () => {
renderContent({ fetchRoutes: [messagesRoute({ status: 500 })] })
@@ -1,10 +1,15 @@
import { useEffect, useMemo, useState } from 'react'
import { SESSION_USAGE_MAX_PAGES, SESSION_USAGE_PAGE_LIMIT } from '@/api/usage'
import { ActivitySpinner } from '@/components/ui/activity-spinner'
import { ErrorBanner } from '@/components/ui/error-banner'
import { useOpenCodeServerId } from '@/contexts/opencode-server-context'
import { useSessionUsage } from '@/hooks/useUsage'
import { SESSION_USAGE_RANGE_STORAGE_KEY, useUsageRangePreference } from '@/hooks/useUsagePreferences'
import { DEFAULT_SESSION_USAGE_RANGE, resolveUsageRange } from '@/lib/usageRange'
import {
DEFAULT_SESSION_USAGE_RANGE,
describeUnresolvedUsageRange,
resolveUsageRange,
} from '@/lib/usageRange'
import { summarizeSessionSteps } from '@/lib/usageStats'
import { UsageModelFilter } from './UsageModelFilter'
import { UsageModelsTable } from './UsageModelsTable'
@@ -27,14 +32,18 @@ export function SessionUsageContent({ sessionId, compact }: SessionUsageContentP
DEFAULT_SESSION_USAGE_RANGE,
)
const [models, setModels] = useState<string[]>([])
const resolvedRange = useMemo(
() => resolveUsageRange(range, query.dataUpdatedAt || Date.now()),
[range, query.dataUpdatedAt],
)
const summary = useMemo(
() =>
summarizeSessionSteps(steps ?? [], {
range: resolveUsageRange(range, Date.now()) ?? {},
summarizeSessionSteps(resolvedRange === null ? [] : (steps ?? []), {
range: resolvedRange ?? {},
models,
}),
[steps, range, models],
[steps, resolvedRange, models],
)
useEffect(() => {
@@ -61,7 +70,7 @@ export function SessionUsageContent({ sessionId, compact }: SessionUsageContentP
query.error instanceof Error ? query.error.message : 'The session usage request failed.'
return (
<div className={compact ? 'space-y-4' : 'space-y-6'}>
<div className={compact ? 'min-h-0 flex-1 space-y-4 overflow-y-auto px-3 pb-3' : 'space-y-6'}>
<div className="flex flex-wrap items-end gap-2">
<UsageRangePicker value={range} onChange={setRange} />
<UsageModelFilter
@@ -71,7 +80,9 @@ export function SessionUsageContent({ sessionId, compact }: SessionUsageContentP
/>
</div>
{query.isPending ? (
{resolvedRange === null ? (
<p className="text-sm text-muted-foreground">{describeUnresolvedUsageRange(range)}</p>
) : query.isPending ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<ActivitySpinner />
<span>Loading session usage…</span>
@@ -100,7 +111,7 @@ export function SessionUsageContent({ sessionId, compact }: SessionUsageContentP
{query.data?.truncated === true && (
<p className="text-xs text-muted-foreground">
Only the newest 1,000 steps of this session are summarized.
{`Only the newest ${(SESSION_USAGE_PAGE_LIMIT * SESSION_USAGE_MAX_PAGES).toLocaleString('en-US')} steps of this session are summarized.`}
</p>
)}
</div>
@@ -382,4 +382,24 @@ describe('UsageDashboard', () => {
expect(screen.queryByText('Loading usage…')).not.toBeInTheDocument()
expect(result.fetchFake.findRequests('GET', statsPath)).toHaveLength(0)
})
it('reports a reversed custom range instead of loading stats', () => {
window.localStorage.setItem(
'oc:usage:range',
JSON.stringify({ preset: 'custom', from: 2_000, to: 1_000 }),
)
const result = renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
expect(screen.getByText('End must be after start.')).toBeInTheDocument()
expect(
screen.queryByText('Choose a start and end time to see usage for a custom range.'),
).not.toBeInTheDocument()
expect(screen.queryByText('Loading usage…')).not.toBeInTheDocument()
expect(result.fetchFake.findRequests('GET', statsPath)).toHaveLength(0)
})
})
@@ -1,4 +1,4 @@
import { useEffect } from 'react'
import { useEffect, useMemo } from 'react'
import { format } from 'date-fns'
import type { SessionStatsInfo } from '@opencode-manager/shared/opencode'
import { ActivitySpinner } from '@/components/ui/activity-spinner'
@@ -12,6 +12,7 @@ import {
} from '@/hooks/useUsagePreferences'
import {
DEFAULT_GLOBAL_USAGE_RANGE,
describeUnresolvedUsageRange,
rangeHasDailyActivity,
resolveUsageRange,
type ResolvedUsageRange,
@@ -50,8 +51,11 @@ export function UsageDashboard({ serverId }: UsageDashboardProps) {
DEFAULT_GLOBAL_USAGE_RANGE,
)
const [models, setModels] = useUsageModelsPreference()
const resolvedRange = resolveUsageRange(range, Date.now())
const stats = useUsageStats(range, serverId)
const resolvedRange = useMemo(
() => resolveUsageRange(range, stats.dataUpdatedAt || Date.now()),
[range, stats.dataUpdatedAt],
)
const data = stats.data
useEffect(() => {
@@ -112,7 +116,7 @@ export function UsageDashboard({ serverId }: UsageDashboardProps) {
function renderContent() {
if (resolvedRange === null) {
return <p>Choose a start and end time to see usage for a custom range.</p>
return <p>{describeUnresolvedUsageRange(range)}</p>
}
if (stats.isPending) {
return (
@@ -52,6 +52,21 @@ function sessionsRoute(sessions: SessionInfo[], serverId = LOCAL_OPENCODE_SERVER
}
}
const localSessionsPath = '/api/opencode/api/session'
function pagedSessionsRoute(pages: SessionInfo[][]): FetchRoute {
return {
method: 'GET',
path: localSessionsPath,
respond: (request) => {
const cursor = request.searchParams.get('cursor')
const index = cursor === null ? 0 : Number(cursor)
const next = index + 1 < pages.length ? { next: String(index + 1) } : {}
return { json: { data: pages[index] ?? [], cursor: next } }
},
}
}
function messagesRoute(serverId = LOCAL_OPENCODE_SERVER_ID): FetchRoute {
const path =
serverId === LOCAL_OPENCODE_SERVER_ID
@@ -66,6 +81,25 @@ function messagesRoute(serverId = LOCAL_OPENCODE_SERVER_ID): FetchRoute {
}
}
const localMessagesPath = '/api/opencode/api/session/:sessionID/message'
function pagedMessagesRoute(pageSizes: number[]): FetchRoute {
return {
method: 'GET',
path: localMessagesPath,
respond: (request, params) => {
const cursor = request.searchParams.get('cursor')
const index = cursor === null ? 0 : Number(cursor)
const size = pageSizes[index] ?? 0
const data = Array.from({ length: size }, (_, itemIndex) =>
assistantStep(`msg_${params.sessionID}_${index}_${itemIndex}`),
)
const next = index + 1 <= pageSizes.length ? { next: String(index + 1) } : {}
return { json: { data, cursor: next } }
},
}
}
function rowTitles(): string[] {
return screen
.getAllByRole('row')
@@ -273,4 +307,278 @@ describe('UsageSessionsTable', () => {
expect(screen.queryByText('Out of range')).not.toBeInTheDocument()
expect(screen.queryByText('Empty session')).not.toBeInTheDocument()
})
it('links sessions without leaking the usage query parameters into the target', async () => {
const sessions = [
makeSession({
id: 'ses_demo',
title: 'Demo session',
cost: 0.4,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
location: { directory: '/workspace/demo' },
}),
]
renderWithProviders(<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />, {
...localOptions,
initialEntries: ['/?assistant=1&repoTab=x&usage=open'],
fetchRoutes: [reposRoute(), sessionsRoute(sessions), messagesRoute()],
})
const link = await screen.findByRole('link', { name: 'Demo session' })
expect(link).toHaveAttribute('href', '/repos/1/sessions/ses_demo')
})
it('keeps only the panel parameter in session links', async () => {
const sessions = [
makeSession({
id: 'ses_demo',
title: 'Demo session',
cost: 0.4,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
location: { directory: '/workspace/demo' },
}),
]
renderWithProviders(<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />, {
...localOptions,
initialEntries: ['/?panel=files&usage=open'],
fetchRoutes: [reposRoute(), sessionsRoute(sessions), messagesRoute()],
})
const link = await screen.findByRole('link', { name: 'Demo session' })
expect(link).toHaveAttribute('href', '/repos/1/sessions/ses_demo?panel=files')
})
it('keeps sessions updated after the range end when they were active since the start', async () => {
const sessions = [
makeSession({
id: 'ses_later',
title: 'Updated later',
cost: 0.4,
tokens: spentTokens,
time: { created: 1000, updated: 9000 },
}),
makeSession({
id: 'ses_active',
title: 'Active in range',
cost: 0.2,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
}),
]
renderWithProviders(
<UsageSessionsTable
serverId={LOCAL_OPENCODE_SERVER_ID}
range={{ from: 1000, to: 3000 }}
/>,
{
...localOptions,
fetchRoutes: [reposRoute(), sessionsRoute(sessions), messagesRoute()],
},
)
await screen.findByText('Updated later')
expect(rowTitles()).toEqual(['Updated later', 'Active in range'])
})
it('renders an error banner when the session list request fails', async () => {
renderWithProviders(<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />, {
...localOptions,
fetchRoutes: [
reposRoute(),
{
method: 'GET',
path: localSessionsPath,
respond: () => ({ status: 500, json: { error: 'boom' } }),
},
messagesRoute(),
],
})
expect(await screen.findByText('Sessions unavailable')).toBeInTheDocument()
expect(
screen.getByText('This OpenCode server could not list its sessions.'),
).toBeInTheDocument()
expect(screen.getByText('UnexpectedStatus: 500')).toBeInTheDocument()
expect(screen.queryByText('No sessions in this range.')).not.toBeInTheDocument()
})
it('keeps loaded rows and notes an incomplete ranking when a later page fails', async () => {
const firstPage = Array.from({ length: 100 }, (_, index) =>
makeSession({
id: `ses_first_${index}`,
title: `First page ${index}`,
cost: 0.5,
tokens: spentTokens,
time: { created: 1000, updated: 10_000 - index },
}),
)
renderWithProviders(<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />, {
...localOptions,
fetchRoutes: [
reposRoute(),
{
method: 'GET',
path: localSessionsPath,
respond: (request) =>
request.searchParams.get('cursor') === null
? { json: { data: firstPage, cursor: { next: '1' } } }
: { status: 500, json: { error: 'boom' } },
},
messagesRoute(),
],
})
expect(
await screen.findByText('Some sessions could not be loaded, so this ranking may be incomplete.'),
).toBeInTheDocument()
expect(screen.getByText('First page 0')).toBeInTheDocument()
expect(screen.queryByText('Sessions unavailable')).not.toBeInTheDocument()
})
it('loads further pages while the oldest loaded session is still in range', async () => {
const firstPage = Array.from({ length: 100 }, (_, index) =>
makeSession({
id: `ses_first_${index}`,
title: `First page ${index}`,
cost: 0.5,
tokens: spentTokens,
time: { created: 1000, updated: 10_000 - index },
}),
)
const secondPage = [
makeSession({
id: 'ses_second_0',
title: 'Second page session',
cost: 0.9,
tokens: spentTokens,
time: { created: 1000, updated: 9000 },
}),
]
const result = renderWithProviders(
<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />,
{
...localOptions,
fetchRoutes: [
reposRoute(),
pagedSessionsRoute([firstPage, secondPage]),
messagesRoute(),
],
},
)
expect(await screen.findByText('Second page session')).toBeInTheDocument()
const sessionRequests = result.fetchFake.findRequests('GET', localSessionsPath)
expect(sessionRequests).toHaveLength(2)
expect(sessionRequests[1]?.searchParams.get('cursor')).toBe('1')
})
it('does not load further pages once the oldest loaded session is older than the range start', async () => {
const firstPage = Array.from({ length: 100 }, (_, index) =>
makeSession({
id: `ses_first_${index}`,
title: `First page ${index}`,
cost: 0.5,
tokens: spentTokens,
time: { created: 1000, updated: 10_000 - index * 60 },
}),
)
const secondPage = [
makeSession({
id: 'ses_beyond_0',
title: 'Beyond range session',
cost: 10,
tokens: spentTokens,
time: { created: 1000, updated: 9000 },
}),
]
const result = renderWithProviders(
<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 5000 }} />,
{
...localOptions,
fetchRoutes: [
reposRoute(),
pagedSessionsRoute([firstPage, secondPage]),
messagesRoute(),
],
},
)
await screen.findByText('First page 0')
await waitFor(() =>
expect(result.fetchFake.findRequests('GET', localMessagesPath)).toHaveLength(10),
)
expect(result.fetchFake.findRequests('GET', localSessionsPath)).toHaveLength(1)
expect(screen.queryByText('Beyond range session')).not.toBeInTheDocument()
})
it('notes when ranking stops at the 500 most recently active sessions', async () => {
const pages = Array.from({ length: 6 }, (_, pageIndex) =>
Array.from({ length: 100 }, (_, index) =>
makeSession({
id: `ses_cap_${pageIndex}_${index}`,
title: `Cap session ${pageIndex}-${index}`,
cost: 0.01,
tokens: spentTokens,
time: { created: 1000, updated: 10_000 - (pageIndex * 100 + index) },
}),
),
)
const result = renderWithProviders(
<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />,
{
...localOptions,
fetchRoutes: [reposRoute(), pagedSessionsRoute(pages), messagesRoute()],
},
)
await waitFor(
() => expect(result.fetchFake.findRequests('GET', localSessionsPath)).toHaveLength(5),
{ timeout: 5000 },
)
expect(
screen.getByText('Ranked from the 500 most recently active sessions.'),
).toBeInTheDocument()
})
it('marks a truncated step count with a plus', async () => {
const sessions = [
makeSession({
id: 'ses_long',
title: 'Long session',
cost: 0.4,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
}),
]
const result = renderWithProviders(
<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />,
{
...localOptions,
fetchRoutes: [
reposRoute(),
sessionsRoute(sessions),
pagedMessagesRoute([200, 200, 200, 200, 200]),
],
},
)
await screen.findByText('Long session')
await waitFor(() => expect(cellsFor('Long session')[1]).toHaveTextContent('1000+'))
expect(cellsFor('Long session')[5]).toHaveTextContent('50.0 tok/s')
expect(result.fetchFake.findRequests('GET', localMessagesPath)).toHaveLength(5)
})
})
@@ -1,16 +1,17 @@
import { useMemo, useState } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import type { UseQueryResult } from '@tanstack/react-query'
import type { SessionInfo } from '@opencode-manager/shared/opencode'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import type { SessionUsageMessages } from '@/api/usage'
import { findRepoForDirectory } from '@/components/navigation/sidebar-session-tree'
import { ErrorBanner } from '@/components/ui/error-banner'
import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { useSessionUsageQueries } from '@/hooks/useUsage'
import { formatCompactTokens } from '@/lib/contextUsage'
import { getServerSessionPath, getSessionPath } from '@/lib/navigation'
import { isWithinUsageRange, type ResolvedUsageRange } from '@/lib/usageRange'
import { getServerSessionPath, getSessionPath, withQueryParam } from '@/lib/navigation'
import type { ResolvedUsageRange } from '@/lib/usageRange'
import {
formatTokensPerSecond,
formatUsd,
@@ -28,6 +29,9 @@ interface SessionMetrics {
throughput: string
}
const SESSION_PAGE_LIMIT = 100
const MAX_SESSION_PAGES = 5
const SESSION_CAP = SESSION_PAGE_LIMIT * MAX_SESSION_PAGES
const INITIAL_ROWS = 10
const ROW_INCREMENT = 10
@@ -35,22 +39,40 @@ function hasSpendOrTokens(session: SessionInfo): boolean {
return session.cost > 0 || totalTokens(session.tokens) > 0
}
function isSessionActiveFrom(session: SessionInfo, range: ResolvedUsageRange): boolean {
return range.from === undefined || session.time.updated >= range.from
}
const sessionMetricsCache = new WeakMap<SessionUsageMessages, SessionMetrics>()
function sessionMetrics(
query: UseQueryResult<SessionUsageMessages> | undefined,
): SessionMetrics {
if (!query || query.isPending) return { steps: '…', throughput: '…' }
if (!query.data) return { steps: '—', throughput: '—' }
const cached = sessionMetricsCache.get(query.data)
if (cached) return cached
const summary = summarizeSessionSteps(query.data.steps, { range: {}, models: [] })
return {
steps: String(summary.steps),
const metrics = {
steps: query.data.truncated ? `${summary.steps}+` : String(summary.steps),
throughput: formatTokensPerSecond(summary.averageTokensPerSecond),
}
sessionMetricsCache.set(query.data, metrics)
return metrics
}
export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps) {
const { data: sessions, isLoading } = useSessionsAcrossDirectories([], {
const {
data: sessions,
isLoading,
isError,
error,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useSessionsAcrossDirectories([], {
allDirectories: true,
limit: 100,
limit: SESSION_PAGE_LIMIT,
serverId,
})
const isLocal = serverId === LOCAL_OPENCODE_SERVER_ID
@@ -58,20 +80,40 @@ export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps)
const location = useLocation()
const [showCount, setShowCount] = useState(INITIAL_ROWS)
const search = useMemo(() => {
const params = new URLSearchParams(location.search)
params.delete('usage')
const remaining = params.toString()
return remaining ? `?${remaining}` : ''
}, [location.search])
const panelId = useMemo(
() => new URLSearchParams(location.search).get('panel'),
[location.search],
)
const hasLoadedSessions = sessions.length > 0
const oldestLoadedUpdated = hasLoadedSessions
? sessions[sessions.length - 1].time.updated
: undefined
const isOldestLoadedInRange =
range.from === undefined ||
(oldestLoadedUpdated !== undefined && oldestLoadedUpdated >= range.from)
const isAtSessionCap = sessions.length >= SESSION_CAP
const showsCapNote = isAtSessionCap && hasNextPage && isOldestLoadedInRange
useEffect(() => {
if (!hasLoadedSessions || !hasNextPage || isFetchingNextPage || isError) return
if (isAtSessionCap || !isOldestLoadedInRange) return
void fetchNextPage()
}, [
fetchNextPage,
hasLoadedSessions,
hasNextPage,
isAtSessionCap,
isError,
isFetchingNextPage,
isOldestLoadedInRange,
sessions.length,
])
const sortedSessions = useMemo(
() =>
sessions
.filter(
(session) =>
isWithinUsageRange(session.time.updated, range) && hasSpendOrTokens(session),
)
.filter((session) => isSessionActiveFrom(session, range) && hasSpendOrTokens(session))
.sort((a, b) => b.cost - a.cost || totalTokens(b.tokens) - totalTokens(a.tokens)),
[sessions, range],
)
@@ -82,6 +124,10 @@ export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps)
serverId,
)
function sessionLinkPath(path: string): string {
return panelId ? withQueryParam(path, 'panel', panelId) : path
}
function renderTitle(session: SessionInfo) {
const title = session.title ?? session.id
if (isLocal) {
@@ -89,7 +135,7 @@ export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps)
if (repo) {
return (
<Link
to={{ pathname: getSessionPath(repo.id, session.id), search }}
to={sessionLinkPath(getSessionPath(repo.id, session.id))}
className="transition-colors hover:text-primary"
>
{title}
@@ -100,7 +146,7 @@ export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps)
}
return (
<Link
to={{ pathname: getServerSessionPath(serverId, session.id), search }}
to={sessionLinkPath(getServerSessionPath(serverId, session.id))}
className="transition-colors hover:text-primary"
>
{title}
@@ -114,7 +160,13 @@ export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps)
<p className="text-xs text-muted-foreground">
Lifetime totals of sessions active in this range.
</p>
{isLoading && sortedSessions.length === 0 ? (
{isError && sessions.length === 0 ? (
<ErrorBanner
title="Sessions unavailable"
summary="This OpenCode server could not list its sessions."
detail={error instanceof Error ? error.message : undefined}
/>
) : isLoading && sortedSessions.length === 0 ? (
<p className="text-sm text-muted-foreground">Loading sessions…</p>
) : sortedSessions.length === 0 ? (
<p className="text-sm text-muted-foreground">No sessions in this range.</p>
@@ -180,8 +232,18 @@ export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps)
Show more
</button>
)}
{showsCapNote && (
<p className="text-xs text-muted-foreground">
{`Ranked from the ${SESSION_CAP} most recently active sessions.`}
</p>
)}
</>
)}
{isError && sessions.length > 0 && (
<p className="text-xs text-muted-foreground">
Some sessions could not be loaded, so this ranking may be incomplete.
</p>
)}
</div>
)
}
+1
View File
@@ -39,6 +39,7 @@ function buildSessionUsageQueryOptions(sessionID: string | undefined, serverId:
},
enabled: sessionID !== undefined,
staleTime: 30_000,
refetchOnWindowFocus: false,
retry: false,
}
}
+51
View File
@@ -4,6 +4,7 @@ import {
DEFAULT_SESSION_USAGE_RANGE,
USAGE_RANGE_LABELS,
USAGE_RANGE_PRESETS,
describeUnresolvedUsageRange,
isWithinUsageRange,
rangeHasDailyActivity,
resolveUsageRange,
@@ -110,6 +111,30 @@ describe('resolveUsageRange', () => {
})
})
describe('describeUnresolvedUsageRange', () => {
it('asks for both bounds when a custom range is incomplete', () => {
const message = 'Choose a start and end time to see usage for a custom range.'
expect(describeUnresolvedUsageRange({ preset: 'custom', from: null, to: null })).toBe(message)
expect(describeUnresolvedUsageRange({ preset: 'custom', from: 10, to: null })).toBe(message)
expect(describeUnresolvedUsageRange({ preset: 'custom', from: null, to: 20 })).toBe(message)
})
it('reports a reversed or empty custom range', () => {
expect(describeUnresolvedUsageRange({ preset: 'custom', from: 20, to: 10 })).toBe(
'End must be after start.',
)
expect(describeUnresolvedUsageRange({ preset: 'custom', from: 10, to: 10 })).toBe(
'End must be after start.',
)
})
it('falls back to asking for a custom range for presets', () => {
expect(describeUnresolvedUsageRange({ preset: 'all' })).toBe(
'Choose a start and end time to see usage for a custom range.',
)
})
})
describe('rangeHasDailyActivity', () => {
it('enables daily activity for multi-day presets and all time', () => {
for (const preset of ['7d', '30d', '90d', 'all'] as const) {
@@ -199,4 +224,30 @@ describe('usageRangeSelectionSchema', () => {
usageRangeSelectionSchema.safeParse({ preset: 'custom', from: 1, to: '2' }).success,
).toBe(false)
})
it('rejects corrupt stored bounds outside the supported timestamp range', () => {
expect(usageRangeSelectionSchema.safeParse({ preset: 'custom', from: 1e20, to: 2 }).success).toBe(
false,
)
expect(
usageRangeSelectionSchema.safeParse({ preset: 'custom', from: -1, to: 2 }).success,
).toBe(false)
expect(
usageRangeSelectionSchema.safeParse({ preset: 'custom', from: 1, to: 1.5 }).success,
).toBe(false)
expect(
usageRangeSelectionSchema.safeParse({
preset: 'custom',
from: 1,
to: 8_640_000_000_000_001,
}).success,
).toBe(false)
expect(
usageRangeSelectionSchema.safeParse({
preset: 'custom',
from: 0,
to: 8_640_000_000_000_000,
}).success,
).toBe(true)
})
})
+13 -2
View File
@@ -62,10 +62,12 @@ const BOUNDED_USAGE_RANGE_PRESETS = USAGE_RANGE_PRESETS.filter(
(preset): preset is BoundedUsageRangePreset => preset !== 'custom',
)
const USAGE_RANGE_MAX_TIMESTAMP = 8_640_000_000_000_000
const CustomUsageRangeSelectionSchema = z.object({
preset: z.literal('custom'),
from: z.number().nullable(),
to: z.number().nullable(),
from: z.number().int().min(0).max(USAGE_RANGE_MAX_TIMESTAMP).nullable(),
to: z.number().int().min(0).max(USAGE_RANGE_MAX_TIMESTAMP).nullable(),
})
export const usageRangeSelectionSchema: z.ZodType<UsageRangeSelection> = z.discriminatedUnion(
@@ -97,6 +99,15 @@ export function resolveUsageRange(
return { from: now - RELATIVE_USAGE_RANGE_DURATIONS[selection.preset], to: now }
}
export function describeUnresolvedUsageRange(selection: UsageRangeSelection): string {
if (selection.preset === 'custom') {
if (selection.from !== null && selection.to !== null && selection.from >= selection.to) {
return 'End must be after start.'
}
}
return 'Choose a start and end time to see usage for a custom range.'
}
export function rangeHasDailyActivity(selection: UsageRangeSelection, now: number): boolean {
if (selection.preset !== 'custom') return DAILY_ACTIVITY_PRESETS.has(selection.preset)