feat(frontend): show context usage on the composer model pill

The model pill shows the context percentage with a tone meter, and the model picker gains a context strip with a Compact action.
This commit is contained in:
Chris Scott committed 2026-10-23 20:18:21 -04:00
1 parent 36d35cc974
commit 52162d5c4a
14 files changed
+438 -13

No files matched your search

@@ -56,6 +56,7 @@ vi.mock('@/hooks/useOpenCode', async () => {
...actual,
useAgents: () => ({ data: mocks.agents }),
useSkills: () => ({ data: mocks.skills }),
useSession: () => ({ data: undefined }),
}
})
@@ -21,6 +21,8 @@ const mocks = vi.hoisted(() => ({
useSendErrorStore: vi.fn(),
useHasBackgroundActivity: vi.fn(),
useSendPrompt: vi.fn(),
useContextUsage: vi.fn(),
sessionData: undefined as { revert?: { messageID: string } } | undefined,
hasPendingPermission: vi.fn(() => false),
setShowDialog: vi.fn(),
}))
@@ -54,9 +56,11 @@ vi.mock('@/hooks/useOpenCode', () => ({
useSendShell: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(() => Promise.resolve()), isPending: false }),
useAgents: () => ({ data: [] }),
useSkills: () => ({ data: [] }),
useSession: () => ({ data: mocks.sessionData }),
}))
vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ data: undefined }) }))
vi.mock('@/hooks/useContextUsage', () => ({ useContextUsage: mocks.useContextUsage }))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
@@ -153,6 +157,8 @@ describe('PromptInput composer layout', () => {
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
mocks.useHasBackgroundActivity.mockReturnValue(false)
mocks.useContextUsage.mockReturnValue({ usage: null, isLoading: false })
mocks.sessionData = undefined
})
it('anchors the activity bar in the gap above the controls row', () => {
@@ -242,6 +248,71 @@ describe('PromptInput composer layout', () => {
})
})
describe('model pill context usage', () => {
const setUsage = (usage: { totalTokens: number, usagePercentage: number | null, contextLimit: number | null }) => {
mocks.useContextUsage.mockReturnValue({ usage, isLoading: false })
}
it('shows the percentage with its tone and the meter on the model pill', () => {
setUsage({ totalTokens: 84000, usagePercentage: 42, contextLimit: 200000 })
renderComponent()
const pill = screen.getByRole('button', { name: /test-model, context 42% used/ })
const usage = screen.getByTestId('model-pill-context-usage')
expect(pill).toContainElement(usage)
expect(usage).toHaveTextContent('42%')
expect(usage).toHaveClass('text-success')
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '42%' })
})
it('tints the warning tone from 50 percent', () => {
setUsage({ totalTokens: 120000, usagePercentage: 50, contextLimit: 240000 })
renderComponent()
expect(screen.getByTestId('model-pill-context-usage')).toHaveClass('text-warning')
})
it('tints the destructive tone from 80 percent', () => {
setUsage({ totalTokens: 176000, usagePercentage: 88, contextLimit: 200000 })
renderComponent()
expect(screen.getByTestId('model-pill-context-usage')).toHaveClass('text-destructive')
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '88%' })
})
it('caps the meter at full width when usage exceeds the context window', () => {
setUsage({ totalTokens: 260000, usagePercentage: 130, contextLimit: 200000 })
renderComponent()
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '100%' })
})
it('falls back to a compact token count without a known context limit', () => {
setUsage({ totalTokens: 12400, usagePercentage: null, contextLimit: null })
renderComponent()
expect(screen.getByRole('button', { name: /test-model, context 12k tokens used/ })).toBeInTheDocument()
expect(screen.getByTestId('model-pill-context-usage')).toHaveTextContent('12k')
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '0%' })
})
it('hides the usage without context data', () => {
renderComponent()
expect(screen.getByRole('button', { name: 'test-model' })).toBeInTheDocument()
expect(screen.queryByTestId('model-pill-context-usage')).not.toBeInTheDocument()
expect(screen.queryByTestId('context-usage-meter')).not.toBeInTheDocument()
})
it('measures usage up to the staged revert boundary', () => {
mocks.sessionData = { revert: { messageID: 'msg_2' } }
renderComponent()
expect(mocks.useContextUsage).toHaveBeenCalledWith('test-session', '/test', 'msg_2')
})
})
describe('mobile key bar', () => {
beforeEach(() => {
mocks.useMobile.mockReturnValue(true)
@@ -54,6 +54,7 @@ vi.mock('@/hooks/useOpenCode', () => ({
useSendShell: () => ({ mutate: mocks.useSendShell, mutateAsync: mocks.useSendShell, isPending: false }),
useAgents: () => ({ data: [] }),
useSkills: () => ({ data: [] }),
useSession: () => ({ data: undefined }),
}))
vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ data: undefined }) }))
@@ -47,6 +47,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
useInterruptSession: () => ({ mutate: mocks.interrupt }),
useAgents: () => ({ data: mocks.agents }),
useSkills: () => ({ data: mocks.skills }),
useSession: () => ({ data: undefined }),
}
})
@@ -44,6 +44,7 @@ vi.mock('@/hooks/useOpenCode', async () => {
...actual,
useAgents: () => ({ data: mocks.agents }),
useSkills: () => ({ data: mocks.skills }),
useSession: () => ({ data: undefined }),
}
})
@@ -59,6 +59,7 @@ vi.mock('@/hooks/useOpenCode', () => ({
useSendShell: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(() => Promise.resolve()), isPending: false }),
useAgents: () => ({ data: [] }),
useSkills: () => ({ data: [] }),
useSession: () => ({ data: undefined }),
}))
vi.mock('@/hooks/useCommands', () => ({
@@ -1,5 +1,6 @@
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent } from 'react'
import { useSendPrompt, useInterruptSession, useSendShell, useAgents, useSkills } from '@/hooks/useOpenCode'
import { useContextUsage } from '@/hooks/useContextUsage'
import { useSendPrompt, useInterruptSession, useSendShell, useAgents, useSkills, useSession } from '@/hooks/useOpenCode'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
@@ -13,7 +14,7 @@ import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { useSendErrorStore } from '@/stores/sendErrorStore'
import { useComposerDraftStore, type ComposerDraft } from '@/stores/composerDraftStore'
import { useRecentCommandsStore } from '@/stores/recentCommandsStore'
import { useHasBackgroundActivity } from '@/stores/sessionStatusStore'
import { useHasBackgroundActivity, useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
import { useMobile } from '@/hooks/useMobile'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
@@ -32,6 +33,7 @@ import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceConversation, type VoiceConversationHandle } from './VoiceConversation'
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { SessionSandboxMenu } from '@/components/session/SessionSandboxMenu'
import { ContextUsageMeter } from '@/components/session/ContextUsageMeter'
import { ComposerToolsMenu } from './ComposerToolsMenu'
import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals'
import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
@@ -39,7 +41,8 @@ import { detectMentionTrigger, parsePromptToInput, getFilename, getDirectory, ty
import { matchText, rankByMatch, type MatchRange } from '@/lib/fuzzyMatch'
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
import { getNextFavoriteModel } from '@/lib/favoriteModels'
import { randomId } from '@/lib/utils'
import { randomId, cn } from '@/lib/utils'
import { CONTEXT_USAGE_TEXT_CLASS, contextUsageAccessibleLabel, contextUsageTone, formatContextUsage } from '@/lib/contextUsage'
import { showToast } from '@/lib/toast'
import { findModelInfo, isSameModelSelection } from '@opencode-manager/shared/opencode'
import { isOpenSessionGoal } from '@opencode-manager/shared/schemas'
@@ -1012,6 +1015,18 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions()
const hasPendingPermissionForSession = hasPermissionsForSession(sessionID)
const { hasVariants, currentVariant, cycleVariant } = useVariants(directory, modelSelectionSession)
const { data: session } = useSession(sessionID, directory)
const revertMessageID = session?.revert?.messageID
const { usage: contextUsage } = useContextUsage(sessionID, directory, revertMessageID)
const isCompacting = useSessionStatusForSession(sessionID).type === 'compact'
const modelPillVariant = hasVariants && currentVariant ? currentVariant : null
const modelPillUsage = contextUsage ? formatContextUsage(contextUsage) : null
const modelPillUsageTone = CONTEXT_USAGE_TEXT_CLASS[contextUsageTone(contextUsage?.usagePercentage ?? null)]
const modelPillLabel = [
displayModelName || 'Select model',
modelPillVariant ? `${modelPillVariant} variant` : null,
contextUsage ? contextUsageAccessibleLabel(contextUsage) : null,
].filter((part): part is string => part !== null).join(', ')
const handleAgentChange = useCallback((agentId: string) => {
setLocalMode(agentId)
@@ -1345,13 +1360,38 @@ return (
open={isModelPickerOpen}
onOpenChange={setIsModelPickerOpen}
session={modelSelectionSession}
contextUsage={contextUsage}
isCompacting={isCompacting}
onCompact={() => commandActions.compact('')}
>
<button
className="px-2.5 py-0.5 md:px-3 min-h-11 md:min-h-9 min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
aria-label={modelPillLabel}
className="relative px-2.5 py-0.5 md:px-3 min-h-11 md:min-h-9 min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
>
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
{hasVariants && currentVariant && (
<span className="text-[10px] text-highlight truncate w-full text-left capitalize">{currentVariant}</span>
{(modelPillVariant || modelPillUsage) && (
<span className="flex w-full min-w-0 items-center gap-1 text-[10px] leading-tight">
{modelPillVariant && (
<span className="truncate text-left capitalize text-highlight">{modelPillVariant}</span>
)}
{modelPillVariant && modelPillUsage && (
<span aria-hidden="true" className="text-muted-foreground">·</span>
)}
{modelPillUsage && (
<span
data-testid="model-pill-context-usage"
className={cn('shrink-0 font-medium', modelPillUsageTone)}
>
{modelPillUsage}
</span>
)}
</span>
)}
{contextUsage && (
<ContextUsageMeter
percentage={contextUsage.usagePercentage}
className="absolute inset-x-0 bottom-0"
/>
)}
</button>
</ModelQuickSelect>