diff --git a/src/features/app/hooks/useAppServerEvents.ts b/src/features/app/hooks/useAppServerEvents.ts index 45dd3dffb..137f5f49b 100644 --- a/src/features/app/hooks/useAppServerEvents.ts +++ b/src/features/app/hooks/useAppServerEvents.ts @@ -77,7 +77,7 @@ type AppServerEventHandlers = { onThreadTokenUsageUpdated?: ( workspaceId: string, threadId: string, - tokenUsage: Record, + tokenUsage: Record | null, ) => void; onAccountRateLimitsUpdated?: ( workspaceId: string, @@ -299,9 +299,9 @@ export function useAppServerEvents(handlers: AppServerEventHandlers) { if (method === "thread/tokenUsage/updated") { const threadId = String(params.threadId ?? params.thread_id ?? ""); const tokenUsage = - (params.tokenUsage as Record | undefined) ?? - (params.token_usage as Record | undefined); - if (threadId && tokenUsage) { + (params.tokenUsage as Record | null | undefined) ?? + (params.token_usage as Record | null | undefined); + if (threadId && tokenUsage !== undefined) { handlers.onThreadTokenUsageUpdated?.(workspace_id, threadId, tokenUsage); } return; diff --git a/src/features/threads/hooks/useThreadTurnEvents.ts b/src/features/threads/hooks/useThreadTurnEvents.ts index 4f1913bc9..dac3dbda5 100644 --- a/src/features/threads/hooks/useThreadTurnEvents.ts +++ b/src/features/threads/hooks/useThreadTurnEvents.ts @@ -171,7 +171,11 @@ export function useThreadTurnEvents({ ); const onThreadTokenUsageUpdated = useCallback( - (workspaceId: string, threadId: string, tokenUsage: Record) => { + ( + workspaceId: string, + threadId: string, + tokenUsage: Record | null, + ) => { dispatch({ type: "ensureThread", workspaceId, threadId }); dispatch({ type: "setThreadTokenUsage", diff --git a/src/features/threads/utils/threadNormalize.ts b/src/features/threads/utils/threadNormalize.ts index dbcc0625c..4a62be296 100644 --- a/src/features/threads/utils/threadNormalize.ts +++ b/src/features/threads/utils/threadNormalize.ts @@ -73,9 +73,12 @@ export function extractReviewThreadId(response: unknown): string | null { return threadId || null; } -export function normalizeTokenUsage(raw: Record): ThreadTokenUsage { - const total = (raw.total as Record) ?? {}; - const last = (raw.last as Record) ?? {}; +export function normalizeTokenUsage( + raw: Record | null | undefined, +): ThreadTokenUsage { + const source = raw ?? {}; + const total = (source.total as Record) ?? {}; + const last = (source.last as Record) ?? {}; return { total: { totalTokens: asNumber(total.totalTokens ?? total.total_tokens), @@ -98,7 +101,7 @@ export function normalizeTokenUsage(raw: Record): ThreadTokenUs ), }, modelContextWindow: (() => { - const value = raw.modelContextWindow ?? raw.model_context_window; + const value = source.modelContextWindow ?? source.model_context_window; if (typeof value === "number") { return value; }