mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
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:
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>
|
||||
|
||||
@@ -563,3 +563,73 @@ describe('ModelQuickSelect keyboard navigation', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('ModelQuickSelect context strip', () => {
|
||||
const session = { id: 'ses_1' }
|
||||
const usage = { totalTokens: 12000, usagePercentage: 6, contextLimit: 200000 }
|
||||
|
||||
it('shows the used and limit tokens with the percentage and meter', () => {
|
||||
render(<ModelQuickSelect open session={session} contextUsage={usage} onCompact={vi.fn()} />)
|
||||
|
||||
const summary = screen.getByTestId('context-usage-summary')
|
||||
|
||||
expect(summary).toHaveTextContent('12k / 200k · 6%')
|
||||
expect(summary).toHaveClass('text-success')
|
||||
expect(summary).toHaveAttribute('aria-label', 'context 6% used')
|
||||
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '6%' })
|
||||
})
|
||||
|
||||
it('tints the summary with the warning and destructive tones', () => {
|
||||
const { rerender } = render(
|
||||
<ModelQuickSelect open session={session} contextUsage={{ ...usage, usagePercentage: 60 }} />,
|
||||
)
|
||||
expect(screen.getByTestId('context-usage-summary')).toHaveClass('text-warning')
|
||||
|
||||
rerender(<ModelQuickSelect open session={session} contextUsage={{ ...usage, usagePercentage: 85 }} />)
|
||||
expect(screen.getByTestId('context-usage-summary')).toHaveClass('text-destructive')
|
||||
})
|
||||
|
||||
it('compacts the session from the strip', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onCompact = vi.fn()
|
||||
|
||||
render(<ModelQuickSelect open session={session} contextUsage={usage} onCompact={onCompact} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Compact session' }))
|
||||
|
||||
expect(onCompact).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('disables compaction while compacting or without a session', () => {
|
||||
const onCompact = vi.fn()
|
||||
const { rerender } = render(
|
||||
<ModelQuickSelect open session={session} contextUsage={usage} isCompacting onCompact={onCompact} />,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Compact session' })).toBeDisabled()
|
||||
|
||||
rerender(<ModelQuickSelect open contextUsage={usage} onCompact={onCompact} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Compact session' })).toBeDisabled()
|
||||
expect(onCompact).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('falls back to tokens and an empty meter without a known limit', () => {
|
||||
render(
|
||||
<ModelQuickSelect
|
||||
open
|
||||
session={session}
|
||||
contextUsage={{ totalTokens: 12000, usagePercentage: null, contextLimit: null }}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('context-usage-summary')).toHaveTextContent('12k tokens')
|
||||
expect(screen.getByTestId('context-usage-meter-fill')).toHaveStyle({ width: '0%' })
|
||||
})
|
||||
|
||||
it('omits the strip without context usage', () => {
|
||||
render(<ModelQuickSelect open session={session} />)
|
||||
|
||||
expect(screen.queryByTestId('context-usage-strip')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -14,8 +14,16 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ContextUsageMeter } from '@/components/session/ContextUsageMeter'
|
||||
import { buildModelSections, filterModelSections, type ModelOption } from '@/lib/modelSections'
|
||||
import { isTextEntryElement } from '@/lib/domTargets'
|
||||
import {
|
||||
CONTEXT_USAGE_TEXT_CLASS,
|
||||
contextUsageAccessibleLabel,
|
||||
contextUsageTone,
|
||||
formatCompactTokens,
|
||||
type ContextUsage,
|
||||
} from '@/lib/contextUsage'
|
||||
|
||||
interface ModelQuickSelectProps {
|
||||
directory?: string
|
||||
@@ -24,6 +32,9 @@ interface ModelQuickSelectProps {
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
session?: ModelSelectionSession
|
||||
contextUsage?: ContextUsage | null
|
||||
isCompacting?: boolean
|
||||
onCompact?: () => void
|
||||
}
|
||||
|
||||
interface ModelListItem {
|
||||
@@ -70,6 +81,50 @@ function formatModelCount(count: number) {
|
||||
return `${count} ${count === 1 ? 'model' : 'models'}`
|
||||
}
|
||||
|
||||
interface ContextUsageStripProps {
|
||||
usage: ContextUsage
|
||||
onCompact?: () => void
|
||||
compactDisabled: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact context-window strip pinned above the picker header: the tone meter, then one line with the
|
||||
* used and limit token counts, the percentage, and the session compaction action.
|
||||
*/
|
||||
function ContextUsageStrip({ usage, onCompact, compactDisabled }: ContextUsageStripProps) {
|
||||
const percentage = usage.usagePercentage
|
||||
const toneClass = CONTEXT_USAGE_TEXT_CLASS[contextUsageTone(percentage)]
|
||||
const summary = usage.contextLimit === null || percentage === null
|
||||
? `${formatCompactTokens(usage.totalTokens)} tokens`
|
||||
: `${formatCompactTokens(usage.totalTokens)} / ${formatCompactTokens(usage.contextLimit)} · ${percentage}%`
|
||||
|
||||
return (
|
||||
<div data-testid="context-usage-strip" className="shrink-0 border-b border-border px-4 pb-2">
|
||||
<ContextUsageMeter percentage={percentage} />
|
||||
<div className="mt-1.5 flex items-center gap-3">
|
||||
<span
|
||||
data-testid="context-usage-summary"
|
||||
aria-label={contextUsageAccessibleLabel(usage)}
|
||||
className={`min-w-0 truncate text-xs font-medium ${toneClass}`}
|
||||
>
|
||||
{summary}
|
||||
</span>
|
||||
{onCompact && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCompact}
|
||||
disabled={compactDisabled}
|
||||
aria-label="Compact session"
|
||||
className="ml-auto shrink-0 rounded text-xs font-medium text-info hover:underline disabled:cursor-not-allowed disabled:opacity-40 disabled:no-underline"
|
||||
>
|
||||
Compact
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function VirtualizedList<T>({
|
||||
items,
|
||||
itemHeight,
|
||||
@@ -176,6 +231,9 @@ export function ModelQuickSelect({
|
||||
open,
|
||||
onOpenChange,
|
||||
session,
|
||||
contextUsage,
|
||||
isCompacting = false,
|
||||
onCompact,
|
||||
}: ModelQuickSelectProps) {
|
||||
const [internalIsOpen, setInternalIsOpen] = useState(false)
|
||||
const isOpen = open ?? internalIsOpen
|
||||
@@ -410,6 +468,11 @@ export function ModelQuickSelect({
|
||||
setSearchQuery('')
|
||||
}
|
||||
|
||||
const handleCompact = () => {
|
||||
onCompact?.()
|
||||
handleOpenChange(false)
|
||||
}
|
||||
|
||||
const getDescription = (item: ModelListItem) => {
|
||||
const context = item.model?.limit?.context
|
||||
if (context) {
|
||||
@@ -576,6 +639,13 @@ export function ModelQuickSelect({
|
||||
className="z-[300] border-border bg-popover text-foreground shadow-2xl md:mx-auto md:max-w-lg"
|
||||
ariaLabel="Select model"
|
||||
>
|
||||
{contextUsage && (
|
||||
<ContextUsageStrip
|
||||
usage={contextUsage}
|
||||
onCompact={onCompact ? handleCompact : undefined}
|
||||
compactDisabled={!session?.id || isCompacting}
|
||||
/>
|
||||
)}
|
||||
<div className={`flex items-center justify-between gap-2 px-4 ${showAllModels ? 'pb-2 pt-2' : 'pb-3 pt-0'}`}>
|
||||
{showAllModels ? (
|
||||
<>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
import { CONTEXT_USAGE_BG_CLASS, contextUsageTone } from '@/lib/contextUsage'
|
||||
|
||||
interface ContextUsageMeterProps {
|
||||
percentage: number | null
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Two-pixel context-window meter: a muted track with a tone-coloured fill sized to `min(percentage, 100)`.
|
||||
* Purely decorative, so the surrounding readout carries the accessible label.
|
||||
*/
|
||||
export function ContextUsageMeter({ percentage, className }: ContextUsageMeterProps) {
|
||||
const width = percentage === null ? 0 : Math.min(percentage, 100)
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="context-usage-meter"
|
||||
aria-hidden="true"
|
||||
className={cn('h-0.5 w-full overflow-hidden bg-border/50', className)}
|
||||
>
|
||||
<div
|
||||
data-testid="context-usage-meter-fill"
|
||||
className={cn('h-full', CONTEXT_USAGE_BG_CLASS[contextUsageTone(percentage)])}
|
||||
style={{ width: `${width}%` }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -111,6 +111,27 @@ describe('useContextUsage', () => {
|
||||
expect(result.current.usage?.usagePercentage).toBe(152)
|
||||
})
|
||||
|
||||
it('reports the context limit measured against', () => {
|
||||
mocks.useProviders.mockReturnValue({
|
||||
data: { models: [{ providerID: 'anthropic', id: 'claude-sonnet', limit: { context: 1000 } }] },
|
||||
})
|
||||
const queryClient = createQueryClient()
|
||||
seedTranscript(queryClient, [
|
||||
assistantMessage('assistant-1', {
|
||||
input: 10,
|
||||
output: 5,
|
||||
reasoning: 0,
|
||||
cache: { read: 1000, write: 500 },
|
||||
}),
|
||||
])
|
||||
|
||||
const { result } = renderHook(() => useContextUsage(SESSION_ID, DIRECTORY), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage?.contextLimit).toBe(1000)
|
||||
})
|
||||
|
||||
it('hides usage when the latest assistant has all-zero tokens even if an earlier one had usage', () => {
|
||||
const queryClient = createQueryClient()
|
||||
seedTranscript(queryClient, [
|
||||
|
||||
@@ -7,11 +7,7 @@ import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { sessionTranscriptQueryKey } from '@/lib/queryInvalidation'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import type { TranscriptCache } from '@/lib/session-projection'
|
||||
|
||||
export interface ContextUsage {
|
||||
totalTokens: number
|
||||
usagePercentage: number | null
|
||||
}
|
||||
import type { ContextUsage } from '@/lib/contextUsage'
|
||||
|
||||
interface ContextUsageResult {
|
||||
usage: ContextUsage | null
|
||||
@@ -77,9 +73,9 @@ export const useContextUsage = (
|
||||
const model = models
|
||||
? findModelInfo(models, { providerID: assistant.model.providerID, modelID: assistant.model.id })
|
||||
: undefined
|
||||
const contextLimit = model?.limit.context
|
||||
const contextLimit = model?.limit.context ?? null
|
||||
const usagePercentage = contextLimit ? Math.round((totalTokens / contextLimit) * 100) : null
|
||||
|
||||
return { usage: { totalTokens, usagePercentage }, isLoading: messagesLoading }
|
||||
return { usage: { totalTokens, usagePercentage, contextLimit }, isLoading: messagesLoading }
|
||||
}, [transcriptData, messagesLoading, models, revertMessageID])
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
contextUsageAccessibleLabel,
|
||||
contextUsageTone,
|
||||
formatCompactTokens,
|
||||
formatContextUsage,
|
||||
} from './contextUsage'
|
||||
|
||||
describe('contextUsageTone', () => {
|
||||
it('keeps usage below 50 percent in the success tone', () => {
|
||||
expect(contextUsageTone(0)).toBe('success')
|
||||
expect(contextUsageTone(49)).toBe('success')
|
||||
})
|
||||
|
||||
it('moves to warning from 50 percent and destructive from 80 percent', () => {
|
||||
expect(contextUsageTone(50)).toBe('warning')
|
||||
expect(contextUsageTone(79)).toBe('warning')
|
||||
expect(contextUsageTone(80)).toBe('destructive')
|
||||
expect(contextUsageTone(140)).toBe('destructive')
|
||||
})
|
||||
|
||||
it('treats an unknown percentage as success', () => {
|
||||
expect(contextUsageTone(null)).toBe('success')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatCompactTokens', () => {
|
||||
it('prints exact counts below a thousand', () => {
|
||||
expect(formatCompactTokens(999)).toBe('999')
|
||||
})
|
||||
|
||||
it('abbreviates thousands and millions', () => {
|
||||
expect(formatCompactTokens(12000)).toBe('12k')
|
||||
expect(formatCompactTokens(999999)).toBe('1M')
|
||||
expect(formatCompactTokens(1300000)).toBe('1.3M')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatContextUsage', () => {
|
||||
it('prefers the percentage when the limit is known', () => {
|
||||
expect(formatContextUsage({ totalTokens: 84000, usagePercentage: 42, contextLimit: 200000 })).toBe('42%')
|
||||
})
|
||||
|
||||
it('falls back to compact tokens without a limit', () => {
|
||||
expect(formatContextUsage({ totalTokens: 12400, usagePercentage: null, contextLimit: null })).toBe('12k')
|
||||
})
|
||||
})
|
||||
|
||||
describe('contextUsageAccessibleLabel', () => {
|
||||
it('announces the percentage when the limit is known', () => {
|
||||
expect(contextUsageAccessibleLabel({ totalTokens: 84000, usagePercentage: 42, contextLimit: 200000 }))
|
||||
.toBe('context 42% used')
|
||||
})
|
||||
|
||||
it('announces compact tokens without a limit', () => {
|
||||
expect(contextUsageAccessibleLabel({ totalTokens: 12400, usagePercentage: null, contextLimit: null }))
|
||||
.toBe('context 12k tokens used')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
export interface ContextUsage {
|
||||
totalTokens: number
|
||||
usagePercentage: number | null
|
||||
contextLimit: number | null
|
||||
}
|
||||
|
||||
export type ContextUsageTone = 'success' | 'warning' | 'destructive'
|
||||
|
||||
export const CONTEXT_USAGE_TEXT_CLASS: Record<ContextUsageTone, string> = {
|
||||
success: 'text-success',
|
||||
warning: 'text-warning',
|
||||
destructive: 'text-destructive',
|
||||
}
|
||||
|
||||
export const CONTEXT_USAGE_BG_CLASS: Record<ContextUsageTone, string> = {
|
||||
success: 'bg-success',
|
||||
warning: 'bg-warning',
|
||||
destructive: 'bg-destructive',
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a context-window percentage to a semantic tone: under 50 is `success`, under 80 is `warning`,
|
||||
* and 80 or more is `destructive`. An unknown percentage falls back to `success`.
|
||||
*/
|
||||
export function contextUsageTone(percentage: number | null): ContextUsageTone {
|
||||
if (percentage === null || percentage < 50) return 'success'
|
||||
if (percentage < 80) return 'warning'
|
||||
return 'destructive'
|
||||
}
|
||||
|
||||
/**
|
||||
* Abbreviates a token count so it fits a one-line readout: exact below a thousand, whole thousands up
|
||||
* to a million (`41k`), and millions to at most one decimal (`1M`, `1.3M`).
|
||||
*/
|
||||
export function formatCompactTokens(tokens: number): string {
|
||||
if (tokens < 1000) return String(tokens)
|
||||
if (tokens < 1000000) {
|
||||
const thousands = Math.round(tokens / 1000)
|
||||
if (thousands < 1000) return `${thousands}k`
|
||||
}
|
||||
return `${Number((tokens / 1000000).toFixed(1))}M`
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats context usage for a compact readout: the percentage of the model's context window when both
|
||||
* a limit and a percentage are known, otherwise a compact token count such as `41k`.
|
||||
*/
|
||||
export function formatContextUsage(usage: ContextUsage): string {
|
||||
if (usage.contextLimit !== null && usage.usagePercentage !== null) {
|
||||
return `${usage.usagePercentage}%`
|
||||
}
|
||||
return formatCompactTokens(usage.totalTokens)
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the screen-reader description of a context-window readout, e.g. `context 42% used` or, when
|
||||
* the limit is unknown, `context 12k tokens used`.
|
||||
*/
|
||||
export function contextUsageAccessibleLabel(usage: ContextUsage): string {
|
||||
if (usage.usagePercentage !== null) {
|
||||
return `context ${usage.usagePercentage}% used`
|
||||
}
|
||||
return `context ${formatCompactTokens(usage.totalTokens)} tokens used`
|
||||
}
|
||||
Reference in new issue
Block a user