Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): stop hiding the llama.cpp token counter during chat
Akarshan Biswascef7856df7d7
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex f8add4f78..0d6faa789 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -83,6 +83,7 @@ import { ExtensionManager } from '@/lib/extension'import { useAttachments } from '@/hooks/useAttachments'import { toast } from 'sonner'import { isPlatformTauri } from '@/lib/platform/utils'+import { shouldShowTokenCounter } from '@/lib/tokenCounterVisibility'import { useAttachmentIngestionPrompt } from '@/hooks/useAttachmentIngestionPrompt'import {NEW_THREAD_ATTACHMENT_KEY,@@ -218,6 +219,14 @@ const ChatInput = memo(function ChatInput({// Reconcile video capability from /props once the model is loaded.useReconcileVideoCapability(selectedModel?.id, selectedProvider, isModelActive)++ const tokenCounterVisible = shouldShowTokenCounter({+ hasSelectedModel: !!selectedModel,+ isAgentMode: effectiveAgentMode,+ isInitialMessage: !!initialMessage,+ hasMessages: (threadMessages?.length ?? 0) > 0,+ hasPromptText: prompt.trim().length > 0,+ })const [selectedAssistantId, setSelectedAssistantId] = useState<string | undefined>(loading ? undefined : currentAssistant?.id || '')@@ -2540,18 +2549,11 @@ const ChatInput = memo(function ChatInput({</div><div className="flex items-center gap-2">- {(selectedProvider === 'llamacpp' ? isModelActive : !!selectedModel) &&- tokenCounterCompact &&- !effectiveAgentMode &&- !initialMessage &&- (threadMessages?.length > 0 || prompt.trim().length > 0) && (- <div className="flex-1 flex justify-center">- <TokenCounter- messages={threadMessages || []}- compact={true}- />- </div>- )}+ {tokenCounterVisible && tokenCounterCompact && (+ <div className="flex-1 flex justify-center">+ <TokenCounter messages={threadMessages || []} compact={true} />+ </div>+ )}{isStreaming ? (<Tooltip>@@ -2612,15 +2614,11 @@ const ChatInput = memo(function ChatInput({</div>)}- {(selectedProvider === 'llamacpp' ? isModelActive : !!selectedModel) &&- !effectiveAgentMode &&- !tokenCounterCompact &&- !initialMessage &&- (threadMessages?.length > 0 || prompt.trim().length > 0) && (- <div className="flex-1 w-full flex justify-start px-2">- <TokenCounter messages={threadMessages || []} />- </div>- )}+ {tokenCounterVisible && !tokenCounterCompact && (+ <div className="flex-1 w-full flex justify-start px-2">+ <TokenCounter messages={threadMessages || []} />+ </div>+ )}<JanBrowserExtensionDialogopen={extensionDialogOpen}diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsxindex 033d9ba13..1f64e1395 100644--- a/web-app/src/containers/__tests__/ChatInput.test.tsx+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx@@ -67,12 +67,13 @@ let selectedModelOverride: any = {capabilities: ['tools'],provider: 'llamacpp',}+let selectedProviderOverride: any = 'llamacpp'const getProviderByNameMock = vi.fn()vi.mock('@/hooks/useModelProvider', () => ({useModelProvider: (selector: any) =>selector({selectedModel: selectedModelOverride,- selectedProvider: { provider: 'llamacpp' },+ selectedProvider: selectedProviderOverride,providers: [],selectModelProvider: vi.fn(),updateProvider: vi.fn(),@@ -197,6 +198,8 @@ vi.mock('@/lib/extension', () => ({ExtensionManager: {getInstance: () => ({get: () => undefined,+ getByName: () => undefined,+ listExtensions: () => [],}),},}))@@ -269,6 +272,7 @@ vi.mock('@/components/ui/dropdown-menu', () => {</button>),DropdownMenuTrigger: Pass,+ DropdownMenuSeparator: () => null,DropdownMenuSub: Pass,DropdownMenuSubContent: Pass,DropdownMenuSubTrigger: Pass,@@ -303,6 +307,7 @@ const resetAll = () => {capabilities: ['tools'],provider: 'llamacpp',}+ selectedProviderOverride = { provider: 'llamacpp' }setPromptMock.mockClear()addToHistoryMock.mockClear()navigateHistoryMock.mockClear()@@ -529,4 +534,38 @@ describe('ChatInput', () => {const svg = container.querySelector('.text-destructive svg')expect(svg).toBeTruthy()})++ describe('token counter visibility', () => {+ // Regression: llama.cpp is a string provider ('llamacpp') and loads lazily,+ // so it is never present in `activeModels` during a chat turn. The counter+ // must still render off model selection + prompt/messages alone.+ it('renders for llama.cpp even when activeModels is empty', () => {+ selectedProviderOverride = { provider: 'llamacpp' }+ appStateOverrides = { activeModels: [] }+ promptState = 'hello'+ renderInput()+ expect(screen.getByTestId('stub-token-counter')).toBeInTheDocument()+ })++ it('renders for a remote provider (openai) with a selected model', () => {+ selectedProviderOverride = 'openai'+ appStateOverrides = { activeModels: [] }+ promptState = 'hello'+ renderInput()+ expect(screen.getByTestId('stub-token-counter')).toBeInTheDocument()+ })++ it('does not render when no model is selected', () => {+ selectedModelOverride = null+ promptState = 'hello'+ renderInput()+ expect(screen.queryByTestId('stub-token-counter')).not.toBeInTheDocument()+ })++ it('does not render with no messages and an empty prompt', () => {+ promptState = ''+ renderInput()+ expect(screen.queryByTestId('stub-token-counter')).not.toBeInTheDocument()+ })+ })})diff --git a/web-app/src/lib/__tests__/tokenCounterVisibility.test.ts b/web-app/src/lib/__tests__/tokenCounterVisibility.test.tsnew file mode 100644index 000000000..545753fa2--- /dev/null+++ b/web-app/src/lib/__tests__/tokenCounterVisibility.test.ts@@ -0,0 +1,107 @@+import { describe, it, expect } from 'vitest'+import { shouldShowTokenCounter } from '@/lib/tokenCounterVisibility'++const base = {+ hasSelectedModel: true,+ isAgentMode: false,+ isInitialMessage: false,+ hasMessages: true,+ hasPromptText: false,+}++describe('shouldShowTokenCounter', () => {+ it('shows when a model is selected and the thread has messages', () => {+ expect(shouldShowTokenCounter(base)).toBe(true)+ })++ it('shows when a model is selected and the prompt has text but no messages yet', () => {+ expect(+ shouldShowTokenCounter({+ ...base,+ hasMessages: false,+ hasPromptText: true,+ })+ ).toBe(true)+ })++ it('hides when no model is selected', () => {+ expect(shouldShowTokenCounter({ ...base, hasSelectedModel: false })).toBe(+ false+ )+ })++ it('hides in agent mode', () => {+ expect(shouldShowTokenCounter({ ...base, isAgentMode: true })).toBe(false)+ })++ it('hides for the initial-message (new-thread) input', () => {+ expect(shouldShowTokenCounter({ ...base, isInitialMessage: true })).toBe(+ false+ )+ })++ it('hides when there are neither messages nor prompt text', () => {+ expect(+ shouldShowTokenCounter({+ ...base,+ hasMessages: false,+ hasPromptText: false,+ })+ ).toBe(false)+ })++ // Regression: the token counter must NOT depend on whether the model is+ // currently in `activeModels`. Router-mode llama.cpp loads lazily and never+ // writes the model back into `activeModels` during a chat turn, so a gate on+ // "is the model active" hid the counter for llama.cpp entirely while remote+ // providers (which were gated only on model selection) kept showing it.+ // Visibility is decided by model selection + conversation state only; the+ // TokenCounter component itself decides whether it has data worth rendering.+ it('shows for a local (llama.cpp) model regardless of active-model state', () => {+ // There is no `isModelActive` input at all: the predicate is provider- and+ // load-state-agnostic by construction.+ expect(shouldShowTokenCounter(base)).toBe(true)+ expect(+ shouldShowTokenCounter({ ...base, hasMessages: false, hasPromptText: true })+ ).toBe(true)+ })++ it('shows identically for local and remote providers given the same inputs', () => {+ const inputs = { ...base, hasMessages: true, hasPromptText: false }+ // Predicate takes no provider argument; same inputs => same result.+ expect(shouldShowTokenCounter(inputs)).toBe(true)+ })++ it('agent mode wins even with a selected model and messages', () => {+ expect(+ shouldShowTokenCounter({+ ...base,+ isAgentMode: true,+ hasSelectedModel: true,+ hasMessages: true,+ hasPromptText: true,+ })+ ).toBe(false)+ })++ it('initial-message wins even with a selected model and prompt text', () => {+ expect(+ shouldShowTokenCounter({+ ...base,+ isInitialMessage: true,+ hasPromptText: true,+ })+ ).toBe(false)+ })++ it('requires a selected model even when messages exist', () => {+ expect(+ shouldShowTokenCounter({+ ...base,+ hasSelectedModel: false,+ hasMessages: true,+ hasPromptText: true,+ })+ ).toBe(false)+ })+})diff --git a/web-app/src/lib/tokenCounterVisibility.ts b/web-app/src/lib/tokenCounterVisibility.tsnew file mode 100644index 000000000..7ce6e9663--- /dev/null+++ b/web-app/src/lib/tokenCounterVisibility.ts@@ -0,0 +1,25 @@+export interface TokenCounterVisibilityInput {+ hasSelectedModel: boolean+ isAgentMode: boolean+ isInitialMessage: boolean+ hasMessages: boolean+ hasPromptText: boolean+}++/**+ * Whether the chat-input token counter should mount. Deliberately provider- and+ * load-state-agnostic: `TokenCounter` decides on its own whether it has data+ * worth rendering, so gating here on model load state (`activeModels`) only ever+ * hid the counter for lazily-loaded local engines. See tokenCounterVisibility.test.ts.+ */+export const shouldShowTokenCounter = ({+ hasSelectedModel,+ isAgentMode,+ isInitialMessage,+ hasMessages,+ hasPromptText,+}: TokenCounterVisibilityInput): boolean =>+ hasSelectedModel &&+ !isAgentMode &&+ !isInitialMessage &&+ (hasMessages || hasPromptText)