diff --git a/frontend/src/components/navigation/MoreDrawer.test.tsx b/frontend/src/components/navigation/MoreDrawer.test.tsx index 6c750fe5..ba6370c6 100644 --- a/frontend/src/components/navigation/MoreDrawer.test.tsx +++ b/frontend/src/components/navigation/MoreDrawer.test.tsx @@ -166,7 +166,7 @@ describe('MoreDrawer', () => { const sectionLabels = (name: string) => within(screen.getByRole('region', { name })).getAllByRole('button').map((button) => button.textContent) - expect(sectionLabels('Workspace')).toEqual(['Files', 'Source Control', 'Terminal', 'Walkthrough', 'Preview']) + expect(sectionLabels('Workspace')).toEqual(['Files', 'Source Control', 'Terminal', 'Walkthrough', 'Session usage', 'Preview']) expect(sectionLabels('Project')).toEqual(['MCP', 'Skills', 'Reset Permissions', 'Schedules', 'Actions']) expect(screen.getAllByText('Settings')).toHaveLength(1) expect(screen.getAllByText('Logout')).toHaveLength(1) @@ -253,6 +253,7 @@ describe('MoreDrawer', () => { expect(screen.getByText('Settings')).toBeInTheDocument() expect(screen.getByText('Logout')).toBeInTheDocument() expect(screen.getByText('Terminal')).toBeInTheDocument() + expect(screen.getByText('Session usage')).toBeInTheDocument() expect(screen.getByText('Sessions')).toBeInTheDocument() expect(screen.queryByText('Files')).not.toBeInTheDocument() expect(screen.getByText('Source Control')).toBeInTheDocument() @@ -260,6 +261,33 @@ describe('MoreDrawer', () => { expect(screen.queryByText('Schedules')).not.toBeInTheDocument() expect(screen.queryByText('Reset Permissions')).not.toBeInTheDocument() expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument() + + const workspaceButtons = within(screen.getByRole('region', { name: 'Workspace' })) + .getAllByRole('button') + .map((button) => button.textContent) + expect(workspaceButtons).toEqual(['Source Control', 'Terminal', 'Session usage']) + }) + + it('opens the Session usage dialog from a local session', async () => { + const { capturedPathname, capturedSearch } = renderMoreDrawer( + '/repos/1/sessions/session-1?mobileTab=more', + '/repos/:id/sessions/:sessionId', + ) + + fireEvent.click(screen.getByText('Session usage')) + + await waitFor(() => expect(new URLSearchParams(capturedSearch.current).get('dialog')).toBe('usage')) + expect(new URLSearchParams(capturedSearch.current).get('mobileTab')).toBeNull() + expect(capturedPathname.current).toBe('/repos/1/sessions/session-1') + }) + + it.each([ + ['/repos/1', '/repos/:id'], + ['/', '*'], + ])('does not render Session usage on %s', (entry, routePath) => { + renderMoreDrawer(entry, routePath) + + expect(screen.queryByText('Session usage')).not.toBeInTheDocument() }) it('shows unread reports and marks them all read', async () => { diff --git a/frontend/src/components/navigation/MoreDrawer.tsx b/frontend/src/components/navigation/MoreDrawer.tsx index a4bdcfc1..f89455ad 100644 --- a/frontend/src/components/navigation/MoreDrawer.tsx +++ b/frontend/src/components/navigation/MoreDrawer.tsx @@ -26,7 +26,7 @@ interface MoreDrawerProps { const ACCOUNT_ITEM_KEYS: ReadonlySet = new Set(['settings', 'logout']) const ITEM_GROUPS: ReadonlyArray<{ label: string; keys: ReadonlySet }> = [ - { label: 'Workspace', keys: new Set(['files', 'source-control', 'terminal', 'preview', 'walkthrough']) }, + { label: 'Workspace', keys: new Set(['files', 'source-control', 'terminal', 'preview', 'walkthrough', 'session-usage']) }, { label: 'Project', keys: new Set(['mcp', 'skills', 'actions', 'schedules', 'all-schedules', 'reset-permissions']) }, ] diff --git a/frontend/src/components/navigation/ToolSidePanel.test.tsx b/frontend/src/components/navigation/ToolSidePanel.test.tsx index dabda095..bacebec1 100644 --- a/frontend/src/components/navigation/ToolSidePanel.test.tsx +++ b/frontend/src/components/navigation/ToolSidePanel.test.tsx @@ -14,6 +14,7 @@ import { makeRepo, makeSession } from '@/test/fixtures/api' import { permissionAsked, sessionStatusUpdated } from '@/test/fixtures/events' import type { FetchRoute } from '@/test/fetchFake' import type { TerminalInfo } from '@opencode-manager/shared/types' +import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode' function LocationProbe() { const location = useLocation() @@ -109,6 +110,29 @@ function terminalRoute(terminals: TerminalInfo[]): FetchRoute { return { method: 'GET', path: '/api/repos/1/terminals', respond: () => ({ json: { terminals } }) } } +function usageStep(): SessionMessageAssistant { + return { + id: 'msg_usage', + type: 'assistant', + agent: 'build', + model: { providerID: 'anthropic', id: 'claude' }, + time: { created: 1000 }, + content: [], + cost: 1, + tokens: { input: 1000, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + } +} + +function usageMessagesRoute(serverId?: string): FetchRoute { + return { + method: 'GET', + path: serverId + ? `/api/opencode/servers/${serverId}/api/session/:sessionID/message` + : '/api/opencode/api/session/:sessionID/message', + respond: () => ({ json: { data: [usageStep()], cursor: {} } }), + } +} + function renderPanel(route: string, options: PanelOptions = {}) { const result = renderWithProviders( @@ -121,6 +145,7 @@ function renderPanel(route: string, options: PanelOptions = {}) { toaster: false, fetchRoutes: [ ...(options.terminals ? [terminalRoute(options.terminals)] : []), + usageMessagesRoute(), { method: 'DELETE', path: '/api/repos/1/terminals/:ptyID', @@ -539,12 +564,66 @@ describe('ToolSidePanel', () => { within(rail) .getAllByRole('button') .map((button) => button.getAttribute('aria-label') ?? button.textContent?.trim()), - ).toEqual(['Sessions', 'MCP', 'Skills', 'Source Control', 'Terminal']) + ).toEqual(['Sessions', 'MCP', 'Skills', 'Source Control', 'Terminal', 'Session usage']) await user.click(screen.getByRole('button', { name: 'MCP' })) expect(await screen.findByRole('complementary', { name: 'MCP' })).toBeInTheDocument() }) + it('opens the usage panel for a local session', async () => { + const user = userEvent.setup() + const { fetchFake } = renderPanel('') + + const rail = screen.getByRole('navigation', { name: 'Tools' }) + expect(within(rail).getByRole('button', { name: 'Session usage' })).toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Session usage' })) + + expect(await screen.findByRole('complementary', { name: 'Session usage' })).toBeInTheDocument() + expect(panelSearch().get('panel')).toBe('usage') + expect(panelSearch().has('dialog')).toBe(false) + expect(await screen.findByText('Spend')).toBeInTheDocument() + + const request = fetchFake.lastRequest('GET', '/api/opencode/api/session/ses_1/message') + expect(request?.path).toBe('/api/opencode/api/session/ses_1/message') + expect(request?.searchParams.get('type')).toBe('assistant') + expect(request?.searchParams.get('limit')).toBe('200') + }) + + it('opens the usage panel for a linked-server session', async () => { + const user = userEvent.setup() + const { fetchFake } = renderWithProviders( + + + , + { + route: '/servers/srv_kitchen/sessions/ses_remote', + serverId: 'srv_kitchen', + events: true, + theme: false, + toaster: false, + fetchRoutes: [...appRoutes(), usageMessagesRoute('srv_kitchen')], + fetchFallback: () => ({ json: {} }), + }, + ) + + await user.click(await screen.findByRole('button', { name: 'Session usage' })) + + expect(await screen.findByRole('complementary', { name: 'Session usage' })).toBeInTheDocument() + expect(panelSearch().get('panel')).toBe('usage') + expect(await screen.findByText('Spend')).toBeInTheDocument() + + const request = fetchFake.lastRequest( + 'GET', + '/api/opencode/servers/srv_kitchen/api/session/ses_remote/message', + ) + expect(request?.path).toBe('/api/opencode/servers/srv_kitchen/api/session/ses_remote/message') + expect(request?.searchParams.get('type')).toBe('assistant') + expect( + fetchFake.findRequests('GET', '/api/opencode/api/session/ses_remote/message'), + ).toHaveLength(0) + }) + it('opens the remote source control panel for a linked-server session', async () => { const user = userEvent.setup() const { fetchFake } = renderWithProviders( diff --git a/frontend/src/components/navigation/ToolSidePanel.tsx b/frontend/src/components/navigation/ToolSidePanel.tsx index 5690a9b6..5c82b9ab 100644 --- a/frontend/src/components/navigation/ToolSidePanel.tsx +++ b/frontend/src/components/navigation/ToolSidePanel.tsx @@ -21,6 +21,7 @@ import { RepoActionsContent } from '@/components/repo/RepoActionsDialog' import { RepoSkillsContent } from '@/components/repo/RepoSkillsDialog' import { RepoSecretsContent } from '@/components/secrets/RepoSecretsDialog' import { RepoSchedulesContent } from '@/components/schedules/RepoSchedulesContent' +import { SessionUsageContent } from '@/components/usage/SessionUsageContent' import type { SkillFileInfo } from '@opencode-manager/shared' import type { ModelRef } from '@opencode-manager/shared/opencode' import { buildToolItems, toolKeyOf, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems' @@ -128,7 +129,7 @@ function PanelResizeHandle({ width, minWidth, maxWidth, onWidthChange }: PanelRe ) } -const REMOTE_TOOL_KEYS: ReadonlySet = new Set(['sessions', 'mcp', 'skills', 'source-control', 'terminal']) +const REMOTE_TOOL_KEYS: ReadonlySet = new Set(['sessions', 'mcp', 'skills', 'source-control', 'terminal', 'session-usage']) function useFloatingPanelDismiss( floating: boolean, @@ -368,6 +369,7 @@ export function ToolSidePanel({ ? null : } + if (tool === 'usage') return sessionId ? : null if (repoId === undefined) return null switch (tool) { case 'actions': diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts index 6109b514..830c31b2 100644 --- a/frontend/src/components/navigation/moreDrawerItems.test.ts +++ b/frontend/src/components/navigation/moreDrawerItems.test.ts @@ -45,7 +45,7 @@ describe('buildMoreItems', () => { it('returns session-specific items for /repos/:id/sessions/:sid', () => { const items = buildMoreItems('/repos/42/sessions/abc') - expect(items).toHaveLength(14) + expect(items).toHaveLength(15) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[2].key).toBe('mcp') @@ -58,13 +58,16 @@ describe('buildMoreItems', () => { expect(items[7].dialog).toBe('terminal') expect(items[8].key).toBe('walkthrough') expect(items[8].dialog).toBe('walkthrough') - expect(items[9].key).toBe('actions') - expect(items[9].dialog).toBe('actions') - expect(items[10].key).toBe('preview') - expect(items[10].dialog).toBe('preview') - expect(items[11].key).toBe('usage') - expect(items[12].key).toBe('settings') - expect(items[13].key).toBe('logout') + expect(items[9].key).toBe('session-usage') + expect(items[9].label).toBe('Session usage') + expect(items[9].dialog).toBe('usage') + expect(items[10].key).toBe('actions') + expect(items[10].dialog).toBe('actions') + expect(items[11].key).toBe('preview') + expect(items[11].dialog).toBe('preview') + expect(items[12].key).toBe('usage') + expect(items[13].key).toBe('settings') + expect(items[14].key).toBe('logout') }) it('returns only the server tools a linked server can serve for /servers/:id/sessions/:sid', () => { @@ -75,6 +78,7 @@ describe('buildMoreItems', () => { 'skills', 'source-control', 'terminal', + 'session-usage', 'usage', 'settings', 'logout', @@ -98,15 +102,16 @@ describe('buildMoreItems', () => { it('omits the Actions item for an Assistant session', () => { const items = buildMoreItems('/repos/0/sessions/abc') - expect(items).toHaveLength(13) + expect(items).toHaveLength(14) expect(items.map((item) => item.key)).not.toContain('actions') expect(items[7].key).toBe('terminal') expect(items[8].key).toBe('walkthrough') - expect(items[9].key).toBe('preview') - expect(items[9].dialog).toBe('preview') - expect(items[10].key).toBe('usage') - expect(items[11].key).toBe('settings') - expect(items[12].key).toBe('logout') + expect(items[9].key).toBe('session-usage') + expect(items[10].key).toBe('preview') + expect(items[10].dialog).toBe('preview') + expect(items[11].key).toBe('usage') + expect(items[12].key).toBe('settings') + expect(items[13].key).toBe('logout') }) it('returns assistant workspace items for /repos/:id/assistant', () => { @@ -198,6 +203,7 @@ describe('buildToolItems', () => { 'source-control', 'terminal', 'walkthrough', + 'session-usage', 'actions', 'preview', ]) @@ -210,6 +216,7 @@ describe('buildToolItems', () => { 'skills', 'source-control', 'terminal', + 'session-usage', ]) }) diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts index 6e81f695..c445dd96 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -1,5 +1,5 @@ import type { LucideIcon } from 'lucide-react' -import { BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, List, Play, Globe, KeyRound, BarChart3 } from 'lucide-react' +import { BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, List, Play, Globe, KeyRound, BarChart3, Gauge } from 'lucide-react' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import { getAssistantPath, isAssistantPath } from '@/lib/navigation' @@ -84,7 +84,21 @@ export function toolKeyOf(item: MoreDrawerItem): string | null { function buildRouteNavModel(pathname: string): NavModel { const baseItems = getBaseItems() - if (SERVER_SESSION_DETAIL_PATH.test(pathname) || SERVER_PROJECT_PATH.test(pathname)) { + if (SERVER_SESSION_DETAIL_PATH.test(pathname)) { + return { + primary: [getAssistantNavItem()], + items: [ + { key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' }, + { key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' }, + { key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' }, + { key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' }, + { key: 'session-usage', label: 'Session usage', icon: Gauge, dialog: 'usage' }, + ...baseItems, + ], + } + } + + if (SERVER_PROJECT_PATH.test(pathname)) { return { primary: [getAssistantNavItem()], items: [ @@ -133,6 +147,7 @@ function buildRouteNavModel(pathname: string): NavModel { { key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' }, { key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' }, { key: 'walkthrough', label: 'Walkthrough', icon: BookOpen, dialog: 'walkthrough' }, + { key: 'session-usage', label: 'Session usage', icon: Gauge, dialog: 'usage' }, ...(isAssistantRepo ? [] : [{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' }]), diff --git a/frontend/src/components/usage/SessionUsageContent.test.tsx b/frontend/src/components/usage/SessionUsageContent.test.tsx new file mode 100644 index 00000000..76588cf5 --- /dev/null +++ b/frontend/src/components/usage/SessionUsageContent.test.tsx @@ -0,0 +1,356 @@ +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import { screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { + ModelRef, + SessionMessageAssistant, + SessionMessageAssistantTool, +} from '@opencode-manager/shared/opencode' +import { installPointerCapture } from '@/test/browserFakes' +import type { FetchRoute } from '@/test/fetchFake' +import { renderWithProviders, type TestProviderOptions } from '@/test/render' +import { SessionUsageContent } from './SessionUsageContent' + +const providerOptions = { auth: false, theme: false, tts: false } as const + +const LOCAL_MESSAGES_PATH = '/api/opencode/api/session/:sessionID/message' + +const MODEL_A: ModelRef = { providerID: 'anthropic', id: 'claude' } +const MODEL_B: ModelRef = { providerID: 'openai', id: 'gpt-5' } + +const NOW = 1_700_000_000_000 + +interface AssistantStepOptions { + id: string + created: number + streamed?: number + model?: ModelRef + cost?: number + input?: number + output?: number + content?: SessionMessageAssistant['content'] +} + +function assistantStep({ + id, + created, + streamed, + model, + cost, + input, + output, + content, +}: AssistantStepOptions): SessionMessageAssistant { + return { + id, + type: 'assistant', + agent: 'build', + model: model ?? MODEL_A, + time: streamed === undefined ? { created } : { created, streamed }, + content: content ?? [], + cost: cost ?? 0, + tokens: { + input: input ?? 0, + output: output ?? 0, + reasoning: 0, + cache: { read: 0, write: 0 }, + }, + } +} + +function bashTool(): SessionMessageAssistantTool { + return { + type: 'tool', + id: 'tool_1', + name: 'bash', + time: { created: 1000, ran: 1000, completed: 1500 }, + state: { status: 'completed', input: {}, content: [{ type: 'text', text: 'ok' }] }, + } +} + +interface MessagesRouteOptions { + serverId?: string + messages?: SessionMessageAssistant[] + cursor?: { next?: string; previous?: string } + status?: number +} + +function messagesRoute({ + serverId, + messages, + cursor, + status, +}: MessagesRouteOptions = {}): FetchRoute { + const path = serverId + ? `/api/opencode/servers/${serverId}/api/session/:sessionID/message` + : LOCAL_MESSAGES_PATH + return { + method: 'GET', + path, + respond: () => ({ + status: status ?? 200, + json: { data: messages ?? [], cursor: cursor ?? {} }, + }), + } +} + +function statText(label: string): string { + const grid = screen.getByText('Spend').parentElement?.parentElement + if (!grid) throw new Error('Summary grid not found') + return within(grid).getByText(label).parentElement?.textContent ?? '' +} + +interface RenderOptions { + sessionId?: string + serverId?: string + route?: string + fetchRoutes: FetchRoute[] +} + +function renderContent({ sessionId, serverId, route, fetchRoutes }: RenderOptions) { + const options: TestProviderOptions = { ...providerOptions, fetchRoutes } + if (serverId !== undefined) options.serverId = serverId + if (route !== undefined) options.route = route + return renderWithProviders(, options) +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +beforeAll(() => { + installPointerCapture() +}) + +describe('SessionUsageContent', () => { + it('renders summary cards, composition, models and tools for loaded local steps', async () => { + const result = renderContent({ + fetchRoutes: [ + messagesRoute({ + messages: [ + assistantStep({ + id: 'msg_1', + created: 1000, + streamed: 2000, + cost: 1.5, + input: 1000, + output: 100, + content: [bashTool()], + }), + ], + }), + ], + }) + + await screen.findByRole('heading', { name: 'Token composition' }) + + expect(statText('Spend')).toContain('$1.50') + expect(statText('Avg tokens/s')).toContain('100.0 tok/s') + expect(statText('Tokens')).toContain('1k') + expect(statText('Steps')).toContain('1') + + expect(screen.getByRole('heading', { name: 'Token composition' })).toBeInTheDocument() + expect(screen.getByRole('heading', { name: 'Models' })).toBeInTheDocument() + expect(screen.getByText('anthropic/claude')).toBeInTheDocument() + expect(screen.getByRole('heading', { name: 'Tools' })).toBeInTheDocument() + expect(screen.getByText('bash')).toBeInTheDocument() + + const request = result.fetchFake.lastRequest('GET', LOCAL_MESSAGES_PATH) + expect(request?.path).toBe('/api/opencode/api/session/ses_1/message') + expect(request?.searchParams.get('type')).toBe('assistant') + expect(request?.searchParams.get('limit')).toBe('200') + }) + + it('filters steps by the selected range', async () => { + vi.spyOn(Date, 'now').mockReturnValue(NOW) + const user = userEvent.setup() + + renderContent({ + fetchRoutes: [ + messagesRoute({ + messages: [ + assistantStep({ id: 'msg_recent', created: NOW - 60_000, cost: 1, input: 1000 }), + assistantStep({ id: 'msg_old', created: NOW - 7_200_000, cost: 5, input: 3000 }), + ], + }), + ], + }) + + await screen.findByRole('heading', { name: 'Token composition' }) + + expect(statText('Steps')).toContain('2') + expect(statText('Spend')).toContain('$6.00') + expect(statText('Tokens')).toContain('4k') + + await user.click(screen.getByRole('combobox', { name: 'Range' })) + await user.click(screen.getByRole('option', { name: 'Last hour' })) + + await waitFor(() => expect(statText('Steps')).toContain('1')) + expect(statText('Spend')).toContain('$1.00') + expect(statText('Tokens')).toContain('1k') + }) + + it('filters the summary and models table by the selected model', async () => { + const user = userEvent.setup() + + renderContent({ + fetchRoutes: [ + messagesRoute({ + messages: [ + assistantStep({ id: 'msg_a', created: 1000, cost: 1, input: 1000, model: MODEL_A }), + assistantStep({ id: 'msg_b', created: 2000, 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: 'openai/gpt-5' })) + + await waitFor(() => expect(statText('Steps')).toContain('1')) + expect(statText('Spend')).toContain('$2.00') + expect(statText('Tokens')).toContain('2k') + expect(screen.queryByText('anthropic/claude')).not.toBeInTheDocument() + expect(screen.getAllByText('openai/gpt-5').length).toBeGreaterThan(0) + }) + + it('prunes selected models that are no longer in range', async () => { + vi.spyOn(Date, 'now').mockReturnValue(NOW) + const user = userEvent.setup() + + renderContent({ + fetchRoutes: [ + messagesRoute({ + messages: [ + assistantStep({ + id: 'msg_a', + created: NOW - 7_200_000, + cost: 1, + input: 1000, + model: MODEL_A, + }), + assistantStep({ + id: 'msg_b', + created: NOW - 60_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: 'Last hour' })) + + await waitFor(() => + expect(screen.getByRole('button', { name: 'Filter by model' })).toHaveTextContent( + 'All models', + ), + ) + expect(statText('Steps')).toContain('1') + }) + + it('persists the range selection and keeps the model filter out of storage', async () => { + vi.spyOn(Date, 'now').mockReturnValue(NOW) + const user = userEvent.setup() + + renderContent({ + fetchRoutes: [ + messagesRoute({ + messages: [assistantStep({ id: 'msg_a', created: NOW - 1000, cost: 1, input: 1000 })], + }), + ], + }) + + await screen.findByRole('heading', { name: 'Token composition' }) + + await user.click(screen.getByRole('combobox', { name: 'Range' })) + await user.click(screen.getByRole('option', { name: 'Last 7 days' })) + + expect(JSON.parse(window.localStorage.getItem('oc:usage:session-range') ?? 'null')).toEqual({ + preset: '7d', + }) + + await user.click(screen.getByRole('button', { name: 'Filter by model' })) + await user.click(await screen.findByRole('menuitemcheckbox', { name: 'anthropic/claude' })) + + expect(window.localStorage.getItem('oc:usage:models')).toBeNull() + }) + + it('notes truncation after the fifth page and stops requesting messages', async () => { + let page = 0 + + const result = renderContent({ + fetchRoutes: [ + { + method: 'GET', + path: LOCAL_MESSAGES_PATH, + respond: () => { + page += 1 + return { + json: { + data: [assistantStep({ id: `msg_${page}`, created: page })], + cursor: { next: `cursor_${page}` }, + }, + } + }, + }, + ], + }) + + await screen.findByText('Only the newest 1,000 steps of this session are summarized.') + + expect(result.fetchFake.findRequests('GET', LOCAL_MESSAGES_PATH)).toHaveLength(5) + }) + + it('shows the error banner when the request fails', async () => { + renderContent({ fetchRoutes: [messagesRoute({ status: 500 })] }) + + expect(await screen.findByText('Session usage unavailable')).toBeInTheDocument() + }) + + it('shows the empty state when the session has no assistant steps', async () => { + renderContent({ fetchRoutes: [messagesRoute({ messages: [] })] }) + + expect(await screen.findByText('No assistant steps in this range.')).toBeInTheDocument() + }) + + it('loads steps from the linked server route only', async () => { + const result = renderContent({ + serverId: 'srv_kitchen', + route: '/servers/srv_kitchen/sessions/ses_1', + fetchRoutes: [ + messagesRoute({ + serverId: 'srv_kitchen', + messages: [ + assistantStep({ id: 'msg_remote', created: 1000, cost: 1, input: 1000 }), + ], + }), + ], + }) + + await screen.findByRole('heading', { name: 'Token composition' }) + + const request = result.fetchFake.lastRequest( + 'GET', + '/api/opencode/servers/srv_kitchen/api/session/ses_1/message', + ) + expect(request?.searchParams.get('type')).toBe('assistant') + expect(request?.searchParams.get('limit')).toBe('200') + expect( + result.fetchFake.findRequests('GET', '/api/opencode/api/session/ses_1/message'), + ).toHaveLength(0) + }) +}) diff --git a/frontend/src/components/usage/SessionUsageContent.tsx b/frontend/src/components/usage/SessionUsageContent.tsx new file mode 100644 index 00000000..12aecd84 --- /dev/null +++ b/frontend/src/components/usage/SessionUsageContent.tsx @@ -0,0 +1,108 @@ +import { useEffect, useMemo, useState } from 'react' +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 { summarizeSessionSteps } from '@/lib/usageStats' +import { UsageModelFilter } from './UsageModelFilter' +import { UsageModelsTable } from './UsageModelsTable' +import { UsageRangePicker } from './UsageRangePicker' +import { UsageSummaryCards } from './UsageSummaryCards' +import { UsageTokenComposition } from './UsageTokenComposition' +import { UsageToolsTable } from './UsageToolsTable' + +interface SessionUsageContentProps { + sessionId: string + compact?: boolean +} + +export function SessionUsageContent({ sessionId, compact }: SessionUsageContentProps) { + const serverId = useOpenCodeServerId() + const query = useSessionUsage(sessionId, serverId) + const steps = query.data?.steps + const [range, setRange] = useUsageRangePreference( + SESSION_USAGE_RANGE_STORAGE_KEY, + DEFAULT_SESSION_USAGE_RANGE, + ) + const [models, setModels] = useState([]) + + const summary = useMemo( + () => + summarizeSessionSteps(steps ?? [], { + range: resolveUsageRange(range, Date.now()) ?? {}, + models, + }), + [steps, range, models], + ) + + useEffect(() => { + const available = new Set(summary.availableModels) + const remaining = models.filter((key) => available.has(key)) + if (remaining.length !== models.length) setModels(remaining) + }, [models, summary.availableModels]) + + const toolTotals = useMemo( + () => + summary.tools.reduce( + (totals, tool) => ({ + calls: totals.calls + tool.calls, + succeeded: totals.succeeded + tool.succeeded, + failed: totals.failed + tool.failed, + unfinished: totals.unfinished + tool.unfinished, + }), + { calls: 0, succeeded: 0, failed: 0, unfinished: 0 }, + ), + [summary.tools], + ) + + const errorDetail = + query.error instanceof Error ? query.error.message : 'The session usage request failed.' + + return ( +
+
+ + +
+ + {query.isPending ? ( +
+ + Loading session usage… +
+ ) : query.isError ? ( + + ) : summary.steps === 0 ? ( +

No assistant steps in this range.

+ ) : ( + <> + + + + + + )} + + {query.data?.truncated === true && ( +

+ Only the newest 1,000 steps of this session are summarized. +

+ )} +
+ ) +} diff --git a/frontend/src/components/usage/SessionUsageDialog.test.tsx b/frontend/src/components/usage/SessionUsageDialog.test.tsx new file mode 100644 index 00000000..133403d4 --- /dev/null +++ b/frontend/src/components/usage/SessionUsageDialog.test.tsx @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from 'vitest' +import { screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode' +import type { FetchRoute } from '@/test/fetchFake' +import { renderWithProviders } from '@/test/render' +import { SessionUsageDialog } from './SessionUsageDialog' + +const providerOptions = { auth: false, theme: false, tts: false } as const + +function assistantStep(): SessionMessageAssistant { + return { + id: 'msg_1', + type: 'assistant', + agent: 'build', + model: { providerID: 'anthropic', id: 'claude' }, + time: { created: 1000 }, + content: [], + cost: 1, + tokens: { input: 1000, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + } +} + +function messagesRoute(): FetchRoute { + return { + method: 'GET', + path: '/api/opencode/api/session/:sessionID/message', + respond: () => ({ json: { data: [assistantStep()], cursor: {} } }), + } +} + +describe('SessionUsageDialog', () => { + it('renders nothing when closed', () => { + const result = renderWithProviders( + , + { ...providerOptions, fetchRoutes: [messagesRoute()] }, + ) + + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + expect(screen.queryByText('Session usage')).not.toBeInTheDocument() + expect(screen.queryByText('Spend')).not.toBeInTheDocument() + expect( + result.fetchFake.findRequests('GET', '/api/opencode/api/session/ses_1/message'), + ).toHaveLength(0) + }) + + it('shows the session usage title and summary when open', async () => { + renderWithProviders( + , + { ...providerOptions, fetchRoutes: [messagesRoute()] }, + ) + + expect(screen.getByText('Session usage')).toBeInTheDocument() + expect(await screen.findByText('Spend')).toBeInTheDocument() + }) + + it('requests closing when the close button is clicked', async () => { + const user = userEvent.setup() + const onOpenChange = vi.fn() + + renderWithProviders( + , + { ...providerOptions, fetchRoutes: [messagesRoute()] }, + ) + + await user.click(screen.getByRole('button', { name: 'Close' })) + + expect(onOpenChange).toHaveBeenCalledWith(false) + }) + + it('requests closing when Escape is pressed', async () => { + const user = userEvent.setup() + const onOpenChange = vi.fn() + + renderWithProviders( + , + { ...providerOptions, fetchRoutes: [messagesRoute()] }, + ) + + await user.keyboard('{Escape}') + + expect(onOpenChange).toHaveBeenCalledWith(false) + }) +}) diff --git a/frontend/src/components/usage/SessionUsageDialog.tsx b/frontend/src/components/usage/SessionUsageDialog.tsx new file mode 100644 index 00000000..0cdbbbf7 --- /dev/null +++ b/frontend/src/components/usage/SessionUsageDialog.tsx @@ -0,0 +1,27 @@ +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { SessionUsageContent } from './SessionUsageContent' + +interface SessionUsageDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + sessionId: string +} + +export function SessionUsageDialog({ open, onOpenChange, sessionId }: SessionUsageDialogProps) { + return ( + + + + Session usage + + +
+ {open && } +
+
+
+ ) +} diff --git a/frontend/src/components/usage/UsageSummaryCards.test.tsx b/frontend/src/components/usage/UsageSummaryCards.test.tsx index f0e8834c..be84e724 100644 --- a/frontend/src/components/usage/UsageSummaryCards.test.tsx +++ b/frontend/src/components/usage/UsageSummaryCards.test.tsx @@ -48,6 +48,31 @@ describe('UsageSummaryCards', () => { expect(screen.getByText('2')).toBeInTheDocument() }) + it('renders average tokens per second after spend when provided', () => { + renderWithProviders( + , + providerOptions, + ) + + const labels = screen.getAllByText(/^(Spend|Avg tokens\/s|Tokens|Steps)$/) + expect(labels.map((node) => node.textContent)).toEqual([ + 'Spend', + 'Avg tokens/s', + 'Tokens', + 'Steps', + ]) + expect(screen.getByText('100.0 tok/s')).toBeInTheDocument() + }) + + it('omits average tokens per second when undefined', () => { + renderWithProviders( + , + providerOptions, + ) + + expect(screen.queryByText('Avg tokens/s')).not.toBeInTheDocument() + }) + it('omits prompts, active days and streak when undefined', () => { renderWithProviders( , diff --git a/frontend/src/components/usage/UsageSummaryCards.tsx b/frontend/src/components/usage/UsageSummaryCards.tsx index 38311743..e9879b4e 100644 --- a/frontend/src/components/usage/UsageSummaryCards.tsx +++ b/frontend/src/components/usage/UsageSummaryCards.tsx @@ -1,12 +1,13 @@ import type { TokenUsageInfo } from '@opencode-manager/shared/opencode' import { Card, CardContent } from '@/components/ui/card' import { formatCompactTokens } from '@/lib/contextUsage' -import { formatUsd, totalTokens } from '@/lib/usageStats' +import { formatTokensPerSecond, formatUsd, totalTokens } from '@/lib/usageStats' interface UsageSummaryCardsProps { cost: number tokens: TokenUsageInfo steps: number + tokensPerSecond?: number | null prompts?: number activeDays?: number streak?: number @@ -21,15 +22,23 @@ export function UsageSummaryCards({ cost, tokens, steps, + tokensPerSecond, prompts, activeDays, streak, }: UsageSummaryCardsProps) { const stats: UsageStat[] = [ { label: 'Spend', value: formatUsd(cost) }, + ] + + if (tokensPerSecond !== undefined) { + stats.push({ label: 'Avg tokens/s', value: formatTokensPerSecond(tokensPerSecond) }) + } + + stats.push( { label: 'Tokens', value: formatCompactTokens(totalTokens(tokens)) }, { label: 'Steps', value: String(steps) }, - ] + ) if (prompts !== undefined) stats.push({ label: 'Prompts', value: String(prompts) }) if (activeDays !== undefined) stats.push({ label: 'Active days', value: String(activeDays) }) diff --git a/frontend/src/hooks/useToolPanel.test.ts b/frontend/src/hooks/useToolPanel.test.ts index 28090f3b..99ef1dac 100644 --- a/frontend/src/hooks/useToolPanel.test.ts +++ b/frontend/src/hooks/useToolPanel.test.ts @@ -29,6 +29,31 @@ describe('sessions tool', () => { }) }) +describe('usage tool', () => { + it('is a panel tool', () => { + expect(isPanelTool('usage')).toBe(true) + }) + + it('rewrites to the usage dialog when the panel is not docked', async () => { + function Probe() { + useToolPanel(false) + const location = useLocation() + return createElement('div', { 'data-testid': 'search' }, location.search) + } + + render( + createElement( + MemoryRouter, + { initialEntries: ['/repos/1/sessions/abc?panel=usage'] }, + createElement(Probe), + ), + ) + + await waitFor(() => expect(screen.getByTestId('search').textContent).not.toContain('panel=usage')) + expect(screen.getByTestId('search').textContent).toContain('dialog=usage') + }) +}) + describe('toggleToolPanelParams', () => { it('opens a tool, clears other tools owned params, and preserves unrelated params', () => { const params = new URLSearchParams('previewPort=3000&previewPath=%2Fx&keep=1') diff --git a/frontend/src/hooks/useToolPanel.ts b/frontend/src/hooks/useToolPanel.ts index c07e1b3e..dbf68a08 100644 --- a/frontend/src/hooks/useToolPanel.ts +++ b/frontend/src/hooks/useToolPanel.ts @@ -4,7 +4,7 @@ import { useUrlParams } from './useUrlParams' const PANEL_PARAM = 'panel' -const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules', 'sessions', 'secrets'] as const +const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules', 'sessions', 'secrets', 'usage'] as const export type PanelTool = (typeof PANEL_TOOLS)[number] diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 7f0995a4..8821e18a 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -47,6 +47,7 @@ import { ProjectActionsMenu } from "@/components/repo/ProjectActionsMenu"; import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog"; import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"; import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"; +import { SessionUsageDialog } from "@/components/usage/SessionUsageDialog"; import { compactSession, findRemoteProjectForDirectory, forkSession, listSessionMessages, remoteProjectName } from "@/api/opencode"; import { useOpenCodeServerId, isLocalOpenCodeServer } from "@/contexts/opencode-server-context"; import { useRemoteProjects } from "@/hooks/useRemoteProjects"; @@ -144,6 +145,7 @@ export function SessionDetail() { const [previewOpen, setPreviewOpen] = useDialogParam('preview'); const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions'); const [walkthroughOpen, setWalkthroughOpen] = useDialogParam('walkthrough'); + const [usageOpen, setUsageOpen] = useDialogParam('usage'); const [requestedWalkthroughSource, setRequestedWalkthroughSource] = useState(null); const [selectedFilePath, setSelectedFilePath] = useState(); const [showScrollButton, setShowScrollButton] = useState(false); @@ -1083,6 +1085,12 @@ export function SessionDetail() { /> )} + + {!isRemoteServer && sessionId && (