Track session context usage

This commit is contained in:
Alex Gleason committed 2025-09-09 23:22:57 -05:00
1 parent 6e9e04a65f
commit facbeff722
5 files changed
+136 -8

No files matched your search

+35
View File
@@ -3,6 +3,7 @@ import { useSearchParams } from 'react-router-dom';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
import { CircularProgress } from '@/components/ui/circular-progress';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { Send, Square, Loader2, ChevronDown } from 'lucide-react'; import { Send, Square, Loader2, ChevronDown } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings'; import { useAISettings } from '@/hooks/useAISettings';
@@ -10,6 +11,7 @@ import { useFS } from '@/hooks/useFS';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useKeepAlive } from '@/hooks/useKeepAlive'; import { useKeepAlive } from '@/hooks/useKeepAlive';
import { useAIChat } from '@/hooks/useAIChat'; import { useAIChat } from '@/hooks/useAIChat';
import { useProviderModels } from '@/hooks/useProviderModels';
import type { AIMessage } from '@/lib/SessionManager'; import type { AIMessage } from '@/lib/SessionManager';
import { ModelSelector } from '@/components/ModelSelector'; import { ModelSelector } from '@/components/ModelSelector';
import { AIMessageItem } from '@/components/AIMessageItem'; import { AIMessageItem } from '@/components/AIMessageItem';
@@ -81,6 +83,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const { fs: browserFS } = useFS(); const { fs: browserFS } = useFS();
const { user } = useCurrentUser(); const { user } = useCurrentUser();
const { models } = useProviderModels();
// Initialize AI chat with tools // Initialize AI chat with tools
const cwd = `/projects/${projectId}`; const cwd = `/projects/${projectId}`;
@@ -139,6 +142,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
streamingMessage, streamingMessage,
isLoading: internalIsLoading, isLoading: internalIsLoading,
totalCost, totalCost,
lastInputTokens,
sendMessage, sendMessage,
startGeneration, startGeneration,
stopGeneration, stopGeneration,
@@ -157,6 +161,17 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Use external loading state if provided, otherwise use internal state // Use external loading state if provided, otherwise use internal state
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading; const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
// Calculate context usage percentage
const currentModel = useMemo(() => {
if (!providerModel.trim()) return null;
return models.find(model => model.fullId === providerModel.trim());
}, [models, providerModel]);
const contextUsagePercentage = useMemo(() => {
if (!currentModel?.contextLength || !lastInputTokens) return 0;
return Math.min((lastInputTokens / currentModel.contextLength) * 100, 100);
}, [currentModel, lastInputTokens]);
// Notify parent of loading state changes // Notify parent of loading state changes
useEffect(() => { useEffect(() => {
if (onLoadingChange) { if (onLoadingChange) {
@@ -427,6 +442,26 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
{/* Bottom Controls Row */} {/* Bottom Controls Row */}
<div className="absolute bottom-2 left-2 right-2 flex items-center gap-2"> <div className="absolute bottom-2 left-2 right-2 flex items-center gap-2">
{/* Context Usage Wheel */}
{currentModel?.contextLength && lastInputTokens > 0 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="cursor-help">
<CircularProgress
value={contextUsagePercentage}
size={20}
strokeWidth={2}
/>
</div>
</TooltipTrigger>
<TooltipContent>
<p>Context usage: {lastInputTokens.toLocaleString()} / {currentModel.contextLength.toLocaleString()} tokens ({contextUsagePercentage.toFixed(1)}%)</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Cost Display */} {/* Cost Display */}
{totalCost > 0 && ( {totalCost > 0 && (
<TooltipProvider> <TooltipProvider>
+65
View File
@@ -0,0 +1,65 @@
import * as React from "react"
import { cn } from "@/lib/utils"
interface CircularProgressProps {
value?: number;
size?: number;
strokeWidth?: number;
className?: string;
children?: React.ReactNode;
}
const CircularProgress = React.forwardRef<
SVGSVGElement,
CircularProgressProps
>(({ value = 0, size = 24, strokeWidth = 2, className, children }, ref) => {
const radius = (size - strokeWidth) / 2;
const circumference = 2 * Math.PI * radius;
const strokeDasharray = circumference;
const strokeDashoffset = circumference - (value / 100) * circumference;
return (
<div className={cn("relative inline-flex items-center justify-center", className)}>
<svg
ref={ref}
width={size}
height={size}
className="transform -rotate-90"
viewBox={`0 0 ${size} ${size}`}
>
{/* Background circle */}
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
className="text-muted/30"
/>
{/* Progress circle */}
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeDasharray={strokeDasharray}
strokeDashoffset={strokeDashoffset}
className="text-primary transition-all duration-300 ease-in-out"
/>
</svg>
{children && (
<div className="absolute inset-0 flex items-center justify-center">
{children}
</div>
)}
</div>
);
});
CircularProgress.displayName = "CircularProgress";
export { CircularProgress };
+15
View File
@@ -160,6 +160,19 @@ export function useAIChat({
} }
}, [sessionId, sessionManager]); }, [sessionId, sessionManager]);
useSessionSubscription('contextUsageUpdated', (updatedSessionId: string, _inputTokens: number) => {
if (updatedSessionId === sessionId) {
const session = sessionManager.getSession(sessionId);
if (session) {
setSessionState({
...session,
messages: [...session.messages],
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
});
}
}
}, [sessionId, sessionManager]);
// Derived state // Derived state
@@ -167,6 +180,7 @@ export function useAIChat({
const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage; const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage;
const isLoading = sessionState?.isLoading || false; const isLoading = sessionState?.isLoading || false;
const totalCost = sessionState?.totalCost || 0; const totalCost = sessionState?.totalCost || 0;
const lastInputTokens = sessionState?.lastInputTokens || 0;
// Actions // Actions
const sendMessage = useCallback(async (content: string, providerModel: string) => { const sendMessage = useCallback(async (content: string, providerModel: string) => {
@@ -217,6 +231,7 @@ export function useAIChat({
streamingMessage, streamingMessage,
isLoading, isLoading,
totalCost, totalCost,
lastInputTokens,
sendMessage, sendMessage,
startGeneration, startGeneration,
stopGeneration, stopGeneration,
+2 -2
View File
@@ -10,7 +10,7 @@ interface ProviderModel {
provider: string; provider: string;
fullId: string; // provider/model format fullId: string; // provider/model format
/** Maximum size of context window, if available */ /** Maximum size of context window, if available */
context_length?: number; contextLength?: number;
/** Pricing information, if available */ /** Pricing information, if available */
pricing?: { pricing?: {
/** Input/prompt pricing per token */ /** Input/prompt pricing per token */
@@ -68,7 +68,7 @@ export function useProviderModels(): ModelFetchResult {
}; };
if ('context_length' in model && typeof model.context_length === 'number') { if ('context_length' in model && typeof model.context_length === 'number') {
providerModel.context_length = model.context_length; providerModel.contextLength = model.context_length;
} }
if ( if (
+19 -6
View File
@@ -44,6 +44,7 @@ export interface SessionState {
lastActivity: Date; lastActivity: Date;
abortController?: AbortController; abortController?: AbortController;
totalCost?: number; // Total cost in USD for this session totalCost?: number; // Total cost in USD for this session
lastInputTokens?: number; // Input tokens from the last AI request
} }
export interface SessionManagerEvents { export interface SessionManagerEvents {
@@ -54,6 +55,7 @@ export interface SessionManagerEvents {
streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void; streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
loadingChanged: (sessionId: string, isLoading: boolean) => void; loadingChanged: (sessionId: string, isLoading: boolean) => void;
costUpdated: (sessionId: string, totalCost: number) => void; costUpdated: (sessionId: string, totalCost: number) => void;
contextUsageUpdated: (sessionId: string, inputTokens: number) => void;
} }
/** /**
@@ -66,7 +68,7 @@ export class SessionManager {
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {}; private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
private fs: JSRuntimeFS; private fs: JSRuntimeFS;
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> }; private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> };
private getProviderModels?: () => Array<{ id: string; provider: string; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>; private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
// Performance constants // Performance constants
private readonly MAX_SESSIONS = 50; private readonly MAX_SESSIONS = 50;
@@ -77,7 +79,7 @@ export class SessionManager {
constructor( constructor(
fs: JSRuntimeFS, fs: JSRuntimeFS,
aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> }, aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> },
getProviderModels?: () => Array<{ id: string; provider: string; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }> getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>
) { ) {
this.fs = fs; this.fs = fs;
this.aiSettings = aiSettings; this.aiSettings = aiSettings;
@@ -103,6 +105,7 @@ export class SessionManager {
sessionName: DotAI.generateSessionName(), sessionName: DotAI.generateSessionName(),
lastActivity: new Date(), lastActivity: new Date(),
totalCost: 0, totalCost: 0,
lastInputTokens: 0,
}; };
// Try to load existing history // Try to load existing history
@@ -465,9 +468,11 @@ export class SessionManager {
session.sessionName = DotAI.generateSessionName(); session.sessionName = DotAI.generateSessionName();
session.lastActivity = new Date(); session.lastActivity = new Date();
session.totalCost = 0; session.totalCost = 0;
session.lastInputTokens = 0;
this.debouncedPersist(); this.debouncedPersist();
this.emit('costUpdated', sessionId, 0); this.emit('costUpdated', sessionId, 0);
this.emit('contextUsageUpdated', sessionId, 0);
this.emit('sessionUpdated', sessionId, session); this.emit('sessionUpdated', sessionId, session);
} }
@@ -486,7 +491,7 @@ export class SessionManager {
} }
/** /**
* Update session cost based on usage data * Update session cost and context usage based on usage data
*/ */
private updateSessionCost(sessionId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void { private updateSessionCost(sessionId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void {
if (!this.getProviderModels) return; if (!this.getProviderModels) return;
@@ -499,11 +504,18 @@ export class SessionManager {
const modelName = parsed.model; const modelName = parsed.model;
const providerName = parsed.provider; const providerName = parsed.provider;
// Find the model in provider models to get pricing // Find the model in provider models to get pricing and context length
const models = this.getProviderModels(); const models = this.getProviderModels();
const model = models.find(m => m.id === modelName && m.provider === providerName); const model = models.find(m => m.id === modelName && m.provider === providerName);
if (!model?.pricing) return; // Update input tokens for context usage tracking
session.lastInputTokens = usage.prompt_tokens;
this.emit('contextUsageUpdated', sessionId, usage.prompt_tokens);
if (!model?.pricing) {
this.emit('sessionUpdated', sessionId, session);
return;
}
// Calculate cost for this request // Calculate cost for this request
const promptCost = model.pricing.prompt.mul(usage.prompt_tokens).div(1000); // pricing is per 1k tokens const promptCost = model.pricing.prompt.mul(usage.prompt_tokens).div(1000); // pricing is per 1k tokens
@@ -613,7 +625,8 @@ export class SessionManager {
this.sessions.set(id, { this.sessions.set(id, {
...session, ...session,
lastActivity: new Date(session.lastActivity), lastActivity: new Date(session.lastActivity),
totalCost: session.totalCost || 0 // Ensure totalCost is set for older sessions totalCost: session.totalCost || 0, // Ensure totalCost is set for older sessions
lastInputTokens: session.lastInputTokens || 0 // Ensure lastInputTokens is set for older sessions
}); });
}); });