mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Keep usage loading state, model filter, and session table range consistent
This commit is contained in:
1 parent
8163941ea2
commit
288975f7b8
6 files changed
+178
-23
No files matched your search
@@ -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()
|
||||
|
||||
@@ -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(
|
||||
() =>
|
||||
|
||||
@@ -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(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
|
||||
...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' }))
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<div className="space-y-6">
|
||||
@@ -106,7 +105,7 @@ export function UsageDashboard({ serverId }: UsageDashboardProps) {
|
||||
{statsData.tools.mode === 'detail' && (
|
||||
<UsageToolsTable totals={statsData.tools.totals} usage={statsData.tools.usage} />
|
||||
)}
|
||||
<UsageSessionsTable serverId={serverId} range={activeRange} />
|
||||
<UsageSessionsTable serverId={serverId} range={statsData.range} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -135,7 +134,7 @@ export function UsageDashboard({ serverId }: UsageDashboardProps) {
|
||||
)
|
||||
}
|
||||
if (!stats.data) return null
|
||||
return renderStats(stats.data, resolvedRange)
|
||||
return renderStats(stats.data)
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -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<void>((resolve) => {
|
||||
releaseSecondPage = resolve
|
||||
})
|
||||
|
||||
const result = renderWithProviders(
|
||||
<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />,
|
||||
{
|
||||
...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({
|
||||
|
||||
@@ -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) ? (
|
||||
<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>
|
||||
|
||||
Reference in new issue
Block a user