Files
opencode-manager/frontend/src/hooks/useContextUsage.ts
T
Chris Scott 10158ac164 fix(sessions): match OpenCode TUI context usage
The header context count differed from the OpenCode TUI and dipped then jumped
back up mid-session:

- cache write tokens were left out of the total, so context stored as a cache
  write was dropped and then reappeared as a cache read on the next step
- the newest assistant message without token data was skipped only one message
  back, so a step without usage showed 0 or a stale count

The total now includes cache write tokens and the newest assistant message that
reports tokens is counted, matching the TUI: messages before the latest completed
compaction are ignored, messages at or after a revert point are ignored, and the
indicator is hidden when no message qualifies or the total is zero.
2026-10-12 01:12:55 +00:00

83 lines
3.1 KiB
TypeScript

import { useMemo } from 'react'
import { skipToken, useQuery } from '@tanstack/react-query'
import { findModelInfo } from '@opencode-manager/shared/opencode'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { useProviders } from '@/hooks/useProviders'
import { sessionTranscriptQueryKey } from '@/lib/queryInvalidation'
import type { TranscriptCache } from '@/lib/session-projection'
export interface ContextUsage {
totalTokens: number
usagePercentage: number | null
}
interface ContextUsageResult {
usage: ContextUsage | null
isLoading: boolean
}
function lastCompletedCompactionIndex(messages: SessionMessageInfo[], end: number): number {
for (let index = end - 1; index >= 0; index -= 1) {
const message = messages[index]
if (message?.type === 'compaction' && message.status === 'completed') return index
}
return -1
}
function lastAssistantWithUsageIndex(messages: SessionMessageInfo[], start: number, end: number): number {
for (let index = end - 1; index > start; index -= 1) {
const message = messages[index]
if (message?.type === 'assistant' && message.tokens !== undefined) return index
}
return -1
}
export const useContextUsage = (
sessionID: string | undefined,
directory?: string,
revertMessageID?: string,
): ContextUsageResult => {
const transcriptQuery = useQuery<TranscriptCache>({
queryKey: sessionTranscriptQueryKey(sessionID ?? ''),
queryFn: skipToken,
})
const transcriptData = transcriptQuery.data
const messagesLoading = transcriptQuery.isPending
const { data: providersData } = useProviders(directory)
const models = providersData?.models
return useMemo(() => {
const messages = transcriptData?.transcript.messages ?? []
const boundaryIndex = revertMessageID
? messages.findIndex((message) => message.id === revertMessageID)
: -1
if (revertMessageID && boundaryIndex === -1) {
return { usage: null, isLoading: messagesLoading }
}
const end = boundaryIndex === -1 ? messages.length : boundaryIndex
const compactionIndex = lastCompletedCompactionIndex(messages, end)
const assistantIndex = lastAssistantWithUsageIndex(messages, compactionIndex, end)
const assistant = assistantIndex === -1 ? undefined : messages[assistantIndex]
if (assistant?.type !== 'assistant' || assistant.tokens === undefined) {
return { usage: null, isLoading: messagesLoading }
}
const { input, output, reasoning, cache } = assistant.tokens
const totalTokens = input + output + reasoning + cache.read + cache.write
if (totalTokens <= 0) {
return { usage: null, isLoading: messagesLoading }
}
const model = models
? findModelInfo(models, { providerID: assistant.model.providerID, modelID: assistant.model.id })
: undefined
const contextLimit = model?.limit.context
const usagePercentage = contextLimit ? Math.round((totalTokens / contextLimit) * 100) : null
return { usage: { totalTokens, usagePercentage }, isLoading: messagesLoading }
}, [transcriptData, messagesLoading, models, revertMessageID])
}