diff --git a/frontend/src/components/usage/SessionUsageContent.test.tsx b/frontend/src/components/usage/SessionUsageContent.test.tsx index 7cd16f6a..972adc6c 100644 --- a/frontend/src/components/usage/SessionUsageContent.test.tsx +++ b/frontend/src/components/usage/SessionUsageContent.test.tsx @@ -269,6 +269,58 @@ describe('SessionUsageContent', () => { expect(statText('Steps')).toContain('1') }) + it('keeps the selected model when the range becomes unresolved', async () => { + vi.spyOn(Date, 'now').mockReturnValue(NOW) + const user = userEvent.setup() + + renderContent({ + fetchRoutes: [ + messagesRoute({ + messages: [ + assistantStep({ + id: 'msg_a', + created: NOW - 60_000, + cost: 1, + input: 1000, + model: MODEL_A, + }), + assistantStep({ + id: 'msg_b', + created: NOW - 120_000, + cost: 2, + input: 2000, + model: MODEL_B, + }), + ], + }), + ], + }) + + await screen.findByRole('heading', { name: 'Models' }) + + await user.click(screen.getByRole('button', { name: 'Filter by model' })) + await user.click(await screen.findByRole('menuitemcheckbox', { name: 'anthropic/claude' })) + expect(screen.getByRole('button', { name: 'Filter by model' })).toHaveTextContent( + 'anthropic/claude', + ) + + await user.click(screen.getByRole('combobox', { name: 'Range' })) + await user.click(screen.getByRole('option', { name: 'Custom' })) + expect( + screen.getByText('Choose a start and end time to see usage for a custom range.'), + ).toBeInTheDocument() + + await user.click(screen.getByRole('combobox', { name: 'Range' })) + await user.click(screen.getByRole('option', { name: 'Last 4 hours' })) + + await waitFor(() => + expect(screen.getByRole('button', { name: 'Filter by model' })).toHaveTextContent( + 'anthropic/claude', + ), + ) + expect(screen.getByRole('heading', { name: 'Models' })).toBeInTheDocument() + }) + it('persists the range selection and keeps the model filter out of storage', async () => { vi.spyOn(Date, 'now').mockReturnValue(NOW) const user = userEvent.setup() diff --git a/frontend/src/components/usage/SessionUsageContent.tsx b/frontend/src/components/usage/SessionUsageContent.tsx index 381c1726..fc7e9b34 100644 --- a/frontend/src/components/usage/SessionUsageContent.tsx +++ b/frontend/src/components/usage/SessionUsageContent.tsx @@ -47,10 +47,11 @@ export function SessionUsageContent({ sessionId, compact }: SessionUsageContentP ) useEffect(() => { + if (resolvedRange === null || steps === undefined) return const available = new Set(summary.availableModels) const remaining = models.filter((key) => available.has(key)) if (remaining.length !== models.length) setModels(remaining) - }, [models, summary.availableModels]) + }, [models, resolvedRange, steps, summary.availableModels]) const toolTotals = useMemo( () => diff --git a/frontend/src/components/usage/UsageDashboard.test.tsx b/frontend/src/components/usage/UsageDashboard.test.tsx index ae4488fc..b875cad1 100644 --- a/frontend/src/components/usage/UsageDashboard.test.tsx +++ b/frontend/src/components/usage/UsageDashboard.test.tsx @@ -1,7 +1,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' import { screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import type { SessionStatsInfo } from '@opencode-manager/shared/opencode' +import type { SessionInfo, SessionStatsInfo } from '@opencode-manager/shared/opencode' import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' import { renderWithProviders } from '@/test/render' import { installPointerCapture } from '@/test/browserFakes' @@ -57,13 +57,18 @@ function statsRoute(path: string = statsPath): FetchRoute { return { method: 'GET', path, respond: () => ({ json: { data: statsFixture } }) } } -function localSessionsRoute(): FetchRoute { +const inRangeTime = { + created: statsFixture.range.from + 1000, + updated: statsFixture.range.from + 2000, +} + +function localSessionsRoute(sessions?: SessionInfo[]): FetchRoute { return { method: 'GET', path: '/api/opencode/api/session', respond: () => ({ json: { - data: [ + data: sessions ?? [ makeSession({ id: 'ses_1', title: 'Fix tests', @@ -75,7 +80,7 @@ function localSessionsRoute(): FetchRoute { reasoning: 0, cache: { read: 0, write: 0 }, }, - time: { created: 1, updated: 2 }, + time: inRangeTime, }), ], cursor: {}, @@ -95,7 +100,7 @@ function remoteSessionsRoute(serverId: string): FetchRoute { id: 'ses_remote', title: 'Remote session', cost: 1, - time: { created: 1, updated: 2 }, + time: inRangeTime, }), ], cursor: {}, @@ -180,6 +185,44 @@ describe('UsageDashboard', () => { expect(screen.queryByRole('heading', { name: 'Activity' })).not.toBeInTheDocument() }) + it('lists only sessions inside the range reported by the stats response', async () => { + freezeNow() + + const beforeRange = makeSession({ + id: 'ses_before', + title: 'Before stats range', + cost: 2, + tokens: { + input: 100, + output: 50, + reasoning: 0, + cache: { read: 0, write: 0 }, + }, + time: { created: statsFixture.range.from - 5000, updated: statsFixture.range.from - 1000 }, + }) + const insideRange = makeSession({ + id: 'ses_inside', + title: 'Inside stats range', + cost: 0.5, + tokens: { + input: 10, + output: 5, + reasoning: 0, + cache: { read: 0, write: 0 }, + }, + time: inRangeTime, + }) + + renderWithProviders(, { + ...providerOptions, + fetchRoutes: [statsRoute(), localSessionsRoute([beforeRange, insideRange]), reposRoute()], + fetchFallback: sessionMessageFallback, + }) + + expect(await screen.findByText('Inside stats range')).toBeInTheDocument() + expect(screen.queryByText('Before stats range')).not.toBeInTheDocument() + }) + it('shows the activity chart for a whole-day range', async () => { window.localStorage.setItem('oc:usage:range', JSON.stringify({ preset: '7d' })) diff --git a/frontend/src/components/usage/UsageDashboard.tsx b/frontend/src/components/usage/UsageDashboard.tsx index f5d6a6f9..ffc94aea 100644 --- a/frontend/src/components/usage/UsageDashboard.tsx +++ b/frontend/src/components/usage/UsageDashboard.tsx @@ -15,7 +15,6 @@ import { describeUnresolvedUsageRange, rangeHasDailyActivity, resolveUsageRange, - type ResolvedUsageRange, type UsageRangeSelection, } from '@/lib/usageRange' import { filterModelUsage, modelUsageKey } from '@/lib/usageStats' @@ -67,7 +66,7 @@ export function UsageDashboard({ serverId }: UsageDashboardProps) { const isFiltered = selectedModels.length > 0 const showReset = isFiltered || !isDefaultUsageRange(range) - function renderStats(statsData: SessionStatsInfo, activeRange: ResolvedUsageRange) { + function renderStats(statsData: SessionStatsInfo) { const totals = filterModelUsage(statsData.models, selectedModels) return (
@@ -106,7 +105,7 @@ export function UsageDashboard({ serverId }: UsageDashboardProps) { {statsData.tools.mode === 'detail' && ( )} - + )}
@@ -135,7 +134,7 @@ export function UsageDashboard({ serverId }: UsageDashboardProps) { ) } if (!stats.data) return null - return renderStats(stats.data, resolvedRange) + return renderStats(stats.data) } return ( diff --git a/frontend/src/components/usage/UsageSessionsTable.test.tsx b/frontend/src/components/usage/UsageSessionsTable.test.tsx index 706f2bf0..ffb58ca3 100644 --- a/frontend/src/components/usage/UsageSessionsTable.test.tsx +++ b/frontend/src/components/usage/UsageSessionsTable.test.tsx @@ -440,6 +440,73 @@ describe('UsageSessionsTable', () => { expect(sessionRequests[1]?.searchParams.get('cursor')).toBe('1') }) + it('keeps the loading state while more sessions outside the filter will be fetched', async () => { + const firstPage = [ + makeSession({ + id: 'ses_free_1', + title: 'Free session 1', + cost: 0, + tokens: zeroTokens, + time: { created: 1000, updated: 10_000 }, + }), + makeSession({ + id: 'ses_free_2', + title: 'Free session 2', + cost: 0, + tokens: zeroTokens, + time: { created: 1000, updated: 9000 }, + }), + ] + const secondPage = [ + makeSession({ + id: 'ses_spend', + title: 'Spending session', + cost: 0.5, + tokens: spentTokens, + time: { created: 1000, updated: 8000 }, + }), + ] + + let releaseSecondPage: () => void = () => {} + const secondPageGate = new Promise((resolve) => { + releaseSecondPage = resolve + }) + + const result = renderWithProviders( + , + { + ...localOptions, + fetchRoutes: [ + reposRoute(), + { + method: 'GET', + path: localSessionsPath, + respond: async (request) => { + if (request.searchParams.get('cursor') === null) { + return { json: { data: firstPage, cursor: { next: '1' } } } + } + await secondPageGate + return { json: { data: secondPage, cursor: {} } } + }, + }, + ], + }, + ) + + await waitFor(() => + expect(result.fetchFake.findRequests('GET', localSessionsPath)).toHaveLength(2), + ) + + expect(screen.getByText('Loading sessions…')).toBeInTheDocument() + expect(screen.queryByText('No sessions in this range.')).not.toBeInTheDocument() + expect(screen.queryByText('Spending session')).not.toBeInTheDocument() + + releaseSecondPage() + + expect(await screen.findByText('Spending session')).toBeInTheDocument() + expect(screen.queryByText('Loading sessions…')).not.toBeInTheDocument() + }) + 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({ diff --git a/frontend/src/components/usage/UsageSessionsTable.tsx b/frontend/src/components/usage/UsageSessionsTable.tsx index c7f5876f..ae2e4216 100644 --- a/frontend/src/components/usage/UsageSessionsTable.tsx +++ b/frontend/src/components/usage/UsageSessionsTable.tsx @@ -65,21 +65,13 @@ export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps) (oldestLoadedUpdated !== undefined && oldestLoadedUpdated >= range.from) const isAtSessionCap = sessions.length >= SESSION_CAP const showsCapNote = isAtSessionCap && hasNextPage && isOldestLoadedInRange + const willLoadMoreSessions = + hasLoadedSessions && hasNextPage === true && !isError && !isAtSessionCap && isOldestLoadedInRange useEffect(() => { - if (!hasLoadedSessions || !hasNextPage || isFetchingNextPage || isError) return - if (isAtSessionCap || !isOldestLoadedInRange) return + if (!willLoadMoreSessions || isFetchingNextPage) return void fetchNextPage() - }, [ - fetchNextPage, - hasLoadedSessions, - hasNextPage, - isAtSessionCap, - isError, - isFetchingNextPage, - isOldestLoadedInRange, - sessions.length, - ]) + }, [fetchNextPage, isFetchingNextPage, sessions.length, willLoadMoreSessions]) const sortedSessions = useMemo( () => @@ -133,7 +125,8 @@ export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps) summary="This OpenCode server could not list its sessions." detail={error instanceof Error ? error.message : undefined} /> - ) : isLoading && sortedSessions.length === 0 ? ( + ) : sortedSessions.length === 0 && + (isLoading || isFetchingNextPage || willLoadMoreSessions) ? (

Loading sessions…

) : sortedSessions.length === 0 ? (

No sessions in this range.