diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 565d7ac1..d71c5cbb 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -3,6 +3,7 @@ import { useSearchParams } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Skeleton } from '@/components/ui/skeleton'; +import { CircularProgress } from '@/components/ui/circular-progress'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { Send, Square, Loader2, ChevronDown } from 'lucide-react'; import { useAISettings } from '@/hooks/useAISettings'; @@ -10,6 +11,7 @@ import { useFS } from '@/hooks/useFS'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useKeepAlive } from '@/hooks/useKeepAlive'; import { useAIChat } from '@/hooks/useAIChat'; +import { useProviderModels } from '@/hooks/useProviderModels'; import type { AIMessage } from '@/lib/SessionManager'; import { ModelSelector } from '@/components/ModelSelector'; import { AIMessageItem } from '@/components/AIMessageItem'; @@ -81,6 +83,7 @@ export const ChatPane = forwardRef(({ const [searchParams, setSearchParams] = useSearchParams(); const { fs: browserFS } = useFS(); const { user } = useCurrentUser(); + const { models } = useProviderModels(); // Initialize AI chat with tools const cwd = `/projects/${projectId}`; @@ -139,6 +142,7 @@ export const ChatPane = forwardRef(({ streamingMessage, isLoading: internalIsLoading, totalCost, + lastInputTokens, sendMessage, startGeneration, stopGeneration, @@ -157,6 +161,17 @@ export const ChatPane = forwardRef(({ // Use external loading state if provided, otherwise use internal state 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 useEffect(() => { if (onLoadingChange) { @@ -427,6 +442,26 @@ export const ChatPane = forwardRef(({ {/* Bottom Controls Row */}
+ {/* Context Usage Wheel */} + {currentModel?.contextLength && lastInputTokens > 0 && ( + + + +
+ +
+
+ +

Context usage: {lastInputTokens.toLocaleString()} / {currentModel.contextLength.toLocaleString()} tokens ({contextUsagePercentage.toFixed(1)}%)

+
+
+
+ )} + {/* Cost Display */} {totalCost > 0 && ( diff --git a/src/components/ui/circular-progress.tsx b/src/components/ui/circular-progress.tsx new file mode 100644 index 00000000..c0f2b995 --- /dev/null +++ b/src/components/ui/circular-progress.tsx @@ -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 ( +
+ + {/* Background circle */} + + {/* Progress circle */} + + + {children && ( +
+ {children} +
+ )} +
+ ); +}); + +CircularProgress.displayName = "CircularProgress"; + +export { CircularProgress }; \ No newline at end of file diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index f487b3fd..47c21a18 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -160,6 +160,19 @@ export function useAIChat({ } }, [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 @@ -167,6 +180,7 @@ export function useAIChat({ const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage; const isLoading = sessionState?.isLoading || false; const totalCost = sessionState?.totalCost || 0; + const lastInputTokens = sessionState?.lastInputTokens || 0; // Actions const sendMessage = useCallback(async (content: string, providerModel: string) => { @@ -217,6 +231,7 @@ export function useAIChat({ streamingMessage, isLoading, totalCost, + lastInputTokens, sendMessage, startGeneration, stopGeneration, diff --git a/src/hooks/useProviderModels.ts b/src/hooks/useProviderModels.ts index 952f93a0..6ee6e738 100644 --- a/src/hooks/useProviderModels.ts +++ b/src/hooks/useProviderModels.ts @@ -10,7 +10,7 @@ interface ProviderModel { provider: string; fullId: string; // provider/model format /** Maximum size of context window, if available */ - context_length?: number; + contextLength?: number; /** Pricing information, if available */ pricing?: { /** Input/prompt pricing per token */ @@ -68,7 +68,7 @@ export function useProviderModels(): ModelFetchResult { }; if ('context_length' in model && typeof model.context_length === 'number') { - providerModel.context_length = model.context_length; + providerModel.contextLength = model.context_length; } if ( diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 38bad823..ffdf50e8 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -44,6 +44,7 @@ export interface SessionState { lastActivity: Date; abortController?: AbortController; totalCost?: number; // Total cost in USD for this session + lastInputTokens?: number; // Input tokens from the last AI request } export interface SessionManagerEvents { @@ -54,6 +55,7 @@ export interface SessionManagerEvents { streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void; loadingChanged: (sessionId: string, isLoading: boolean) => void; costUpdated: (sessionId: string, totalCost: number) => void; + contextUsageUpdated: (sessionId: string, inputTokens: number) => void; } /** @@ -66,7 +68,7 @@ export class SessionManager { private listeners: Partial void>>> = {}; private fs: JSRuntimeFS; private aiSettings: { providers: Record }; - 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 private readonly MAX_SESSIONS = 50; @@ -77,7 +79,7 @@ export class SessionManager { constructor( fs: JSRuntimeFS, aiSettings: { providers: Record }, - 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.aiSettings = aiSettings; @@ -103,6 +105,7 @@ export class SessionManager { sessionName: DotAI.generateSessionName(), lastActivity: new Date(), totalCost: 0, + lastInputTokens: 0, }; // Try to load existing history @@ -465,9 +468,11 @@ export class SessionManager { session.sessionName = DotAI.generateSessionName(); session.lastActivity = new Date(); session.totalCost = 0; + session.lastInputTokens = 0; this.debouncedPersist(); this.emit('costUpdated', sessionId, 0); + this.emit('contextUsageUpdated', sessionId, 0); 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 { if (!this.getProviderModels) return; @@ -499,11 +504,18 @@ export class SessionManager { const modelName = parsed.model; 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 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 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, { ...session, 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 }); });