Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(chat): kv-unified dropdown, thinking-budget submenu resolved at send time

Akarshan Biswasfbaf5412abf4
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index ca65e2049..06e14df2b 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -390,10 +390,15 @@
{
"key": "kv_unified",
"title": "Unified KV Cache",
- "description": "Use a single unified KV buffer shared across all slots. Saves memory when running multiple parallel slots; default is auto.",
- "controllerType": "checkbox",
+ "description": "Use a single unified KV buffer shared across all slots. Saves memory when running multiple parallel slots.",
+ "controllerType": "dropdown",
"controllerProps": {
- "value": false
+ "value": "auto",
+ "options": [
+ { "value": "auto", "name": "Auto" },
+ { "value": "on", "name": "On" },
+ { "value": "off", "name": "Off" }
+ ]
}
},
{
diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.ts
index 24c51c5be..fe0c4c448 100644
--- a/extensions/llamacpp-extension/src/preset.ts
+++ b/extensions/llamacpp-extension/src/preset.ts
@@ -307,10 +307,11 @@ export async function generatePreset(
if (config.swa_full === true) {
lines.push('swa-full = true')
}
- // kv-unified default = auto (enabled when slot count is auto); explicit
- // opt-in only, since the auto default already covers the common case.
- if (config.kv_unified === true) {
+ // auto = omit the flag, let llama.cpp decide based on slot count
+ if (config.kv_unified === 'on') {
lines.push('kv-unified = true')
+ } else if (config.kv_unified === 'off') {
+ lines.push('kv-unified = false')
}
// keep default = 0
if (
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
index c56df0690..ae11f9b6c 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
@@ -116,7 +116,7 @@ export function normalizeLlamacppConfig(config: any): LlamacppConfig {
cache_reuse: asI32(config.cache_reuse, 0),
swa_full: asBool(config.swa_full),
keep: asI32(config.keep, 0),
- kv_unified: asBool(config.kv_unified),
+ kv_unified: asString(config.kv_unified, 'auto'),
}
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
index dfe11ba3f..3143dacfb 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
@@ -80,7 +80,7 @@ export type LlamacppConfig = {
cache_reuse: number
swa_full: boolean
keep: number
- kv_unified: boolean
+ kv_unified: string
}
export type ModelPlan = {
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 06e2fe9fc..a2f7b61e8 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -15,6 +15,10 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubTrigger,
+ DropdownMenuSubContent,
} from '@/components/ui/dropdown-menu'
import { ArrowRight, PlusIcon } from 'lucide-react'
import {
@@ -39,6 +43,14 @@ import { BotIcon } from 'lucide-react'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { useGeneralSetting } from '@/hooks/useGeneralSetting'
import { useModelProvider } from '@/hooks/useModelProvider'
+import { useTokensCount } from '@/hooks/useTokensCount'
+import {
+ THINKING_BUDGET_LEVELS,
+ DEFAULT_THINKING_BUDGET_LEVEL,
+ tokensForThinkingBudgetLevel,
+ isThinkingBudgetLevelKey,
+ type ThinkingBudgetLevelKey,
+} from '@/lib/thinkingBudget'
import { useReconcileVideoCapability } from '@/hooks/useReconcileVideoCapability'
import { useAppState } from '@/hooks/useAppState'
@@ -120,6 +132,7 @@ const videoMimeForExt = (ext: string | undefined): string => {
}
}
+
const ChatInput = memo(function ChatInput({
className,
initialMessage,
@@ -191,6 +204,8 @@ const ChatInput = memo(function ChatInput({
(state) => state.selectModelProvider
)
const updateProvider = useModelProvider((state) => state.updateProvider)
+ const { maxTokens: liveMaxTokens, configuredCtxLen } =
+ useTokensCount(threadMessages || [])
const [message, setMessage] = useState('')
const [dropdownToolsAvailable, setDropdownToolsAvailable] = useState(false)
const [tooltipShown, setTooltipShown] = useState<
@@ -2224,7 +2239,12 @@ const ChatInput = memo(function ChatInput({
const reasoningValue =
(selectedModel?.settings?.reasoning?.controller_props
?.value as 'auto' | 'on' | 'off' | undefined) ?? 'auto'
- const setReasoning = (value: 'auto' | 'on' | 'off') => {
+ const updateModelSetting = (
+ settingKey: string,
+ title: string,
+ controllerType: string,
+ value: unknown
+ ) => {
if (!selectedProvider || !selectedModel) return
const providerObj = getProviderByName(selectedProvider)
if (!providerObj) return
@@ -2232,19 +2252,18 @@ const ChatInput = memo(function ChatInput({
(m) => m.id === selectedModel.id
)
if (modelIndex === -1) return
- const existing =
- selectedModel.settings?.reasoning ?? {
- key: 'reasoning',
- title: 'Reasoning',
- description: '',
- controller_type: 'dropdown',
- controller_props: { value },
- }
+ const existing = selectedModel.settings?.[settingKey] ?? {
+ key: settingKey,
+ title,
+ description: '',
+ controller_type: controllerType,
+ controller_props: { value },
+ }
const updatedModel = {
...selectedModel,
settings: {
...selectedModel.settings,
- reasoning: {
+ [settingKey]: {
...existing,
controller_props: {
...(existing.controller_props ?? {}),
@@ -2263,6 +2282,13 @@ const ChatInput = memo(function ChatInput({
// chat transport both observe the new value.
selectModelProvider(selectedProvider, selectedModel.id)
}
+ const setReasoning = (value: 'auto' | 'on' | 'off') =>
+ updateModelSetting(
+ 'reasoning',
+ 'Reasoning',
+ 'dropdown',
+ value
+ )
const label =
reasoningValue === 'on'
? 'On'
@@ -2275,6 +2301,35 @@ const ChatInput = memo(function ChatInput({
: reasoningValue === 'off'
? 'Reasoning disabled for every request.'
: "Reasoning auto-detected from the model's chat template."
+
+ // Stored as a symbolic level, not an absolute token count:
+ // the live context size (post auto-fit) is only known once
+ // the model is actually loaded, so resolving to tokens
+ // happens at send time (custom-chat-transport.ts) against
+ // whatever the context size turns out to be then.
+ const rawBudgetLevel =
+ selectedModel?.settings?.thinking_budget_tokens
+ ?.controller_props?.value
+ const currentBudgetLevel = isThinkingBudgetLevelKey(
+ rawBudgetLevel
+ )
+ ? rawBudgetLevel
+ : DEFAULT_THINKING_BUDGET_LEVEL
+ const setThinkingBudget = (level: ThinkingBudgetLevelKey) =>
+ updateModelSetting(
+ 'thinking_budget_tokens',
+ 'Thinking Budget',
+ 'dropdown',
+ level
+ )
+ const currentBudgetLabel = THINKING_BUDGET_LEVELS.find(
+ (l) => l.key === currentBudgetLevel
+ )!.label
+ // Best-effort preview only; the request-time value may
+ // differ once the model is loaded and fit settles n_ctx.
+ const approxContextSize =
+ liveMaxTokens || configuredCtxLen || 8192
+
return (
<DropdownMenu>
<Tooltip>
@@ -2325,6 +2380,44 @@ const ChatInput = memo(function ChatInput({
</span>
)}
</DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">Thinking Budget</span>
+ <span className="text-xs text-muted-foreground">
+ {currentBudgetLabel}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ collisionPadding={{ bottom: 16 }}
+ >
+ {THINKING_BUDGET_LEVELS.map((level) => {
+ const approxTokens = tokensForThinkingBudgetLevel(
+ level.key,
+ approxContextSize
+ )
+ return (
+ <DropdownMenuItem
+ key={level.key}
+ onClick={() => setThinkingBudget(level.key)}
+ className="gap-2"
+ >
+ <span className="flex-1">{level.label}</span>
+ <span className="w-14 shrink-0 text-right text-xs text-muted-foreground tabular-nums">
+ {approxTokens === -1
+ ? ''
+ : `~${approxTokens}`}
+ </span>
+ <span className="w-3 shrink-0 text-xs text-muted-foreground">
+ {currentBudgetLevel === level.key
+ ? '✓'
+ : ''}
+ </span>
+ </DropdownMenuItem>
+ )
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
</DropdownMenuContent>
</DropdownMenu>
)
diff --git a/web-app/src/containers/SamplerDefaults.tsx b/web-app/src/containers/SamplerDefaults.tsx
index 7d44a670c..f17a22c95 100644
--- a/web-app/src/containers/SamplerDefaults.tsx
+++ b/web-app/src/containers/SamplerDefaults.tsx
@@ -45,18 +45,20 @@ export function SamplerDefaults({
return (
<div key={key} className="space-y-2">
<div className="flex items-start justify-between gap-8">
- <div className="mb-1 truncate">
+ <div className="mb-1 shrink-0 basis-28 truncate">
<span title={def.title} className="font-medium">
{def.title}
</span>
</div>
- <DynamicControllerSetting
- title={def.title}
- description={def.description}
- controllerType={def.controllerType}
- controllerProps={{ ...(def.controllerProps ?? {}), value }}
- onChange={(newValue) => onChange(key, newValue)}
- />
+ <div className="flex-1 min-w-0">
+ <DynamicControllerSetting
+ title={def.title}
+ description={def.description}
+ controllerType={def.controllerType}
+ controllerProps={{ ...(def.controllerProps ?? {}), value }}
+ onChange={(newValue) => onChange(key, newValue)}
+ />
+ </div>
</div>
<p className="text-muted-foreground leading-normal text-xs">
{def.description}
diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsx
index 11d3f3332..033d9ba13 100644
--- a/web-app/src/containers/__tests__/ChatInput.test.tsx
+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx
@@ -80,6 +80,18 @@ vi.mock('@/hooks/useModelProvider', () => ({
}),
}))
+vi.mock('@/hooks/useTokensCount', () => ({
+ useTokensCount: () => ({
+ maxTokens: undefined,
+ configuredCtxLen: undefined,
+ tokenCount: 0,
+ isNearLimit: false,
+ loading: false,
+ fitEnabled: false,
+ calculateTokens: vi.fn(),
+ }),
+}))
+
vi.mock('@/hooks/useAssistant', () => ({
useAssistant: () => ({
loading: false,
diff --git a/web-app/src/hooks/useTokensCount.ts b/web-app/src/hooks/useTokensCount.ts
index bc75ed9e0..62c26c034 100644
--- a/web-app/src/hooks/useTokensCount.ts
+++ b/web-app/src/hooks/useTokensCount.ts
@@ -1,16 +1,14 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { ThreadMessage } from '@janhq/core'
-import { ExtensionManager } from '@/lib/extension'
import { parseContextOverflow } from '@/utils/error'
+import {
+ getLlamacppExtension,
+ type LlamacppModelProps,
+} from '@/lib/llamacppRouterProps'
import { useModelProvider } from './useModelProvider'
import { useAppState } from './useAppState'
-export interface ModelProps {
- nCtx: number
- totalSlots?: number
- modelAlias?: string
- isSleeping?: boolean
-}
+export type ModelProps = LlamacppModelProps
export interface TokenCountData {
tokenCount: number
@@ -35,10 +33,6 @@ interface UsageMeta {
totalTokens?: number
}
-interface LlamacppExtensionLike {
- getModelProps?: (modelId: string) => Promise<ModelProps | undefined>
-}
-
// The token-usage popup normally reflects the last *successful* turn. When a
// request overflows, that turn is never recorded, so the popup would keep
// showing a comfortable percentage next to an "out of context" error. Parse
@@ -63,22 +57,6 @@ const getLatestServerUsage = (messages: ThreadMessage[]): UsageMeta => {
return {}
}
-const getLlamacppExtension = (): LlamacppExtensionLike | undefined => {
- const mgr = ExtensionManager.getInstance()
- const candidates = [
- mgr.getByName('@janhq/llamacpp-extension'),
- mgr.getByName('llamacpp-extension'),
- ]
- for (const c of candidates) {
- if (c && typeof (c as LlamacppExtensionLike).getModelProps === 'function')
- return c as LlamacppExtensionLike
- }
- return mgr.listExtensions().find(
- (ext) =>
- typeof (ext as LlamacppExtensionLike).getModelProps === 'function'
- ) as LlamacppExtensionLike | undefined
-}
-
const readSettingNumber = (v: unknown): number | undefined => {
if (typeof v === 'number' && Number.isFinite(v)) return v
if (typeof v === 'string') {
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index daa036761..9d8ef1cd5 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -23,6 +23,11 @@ import { useMCPServers } from '@/hooks/useMCPServers'
import { useAppState } from '@/hooks/useAppState'
import { invoke } from '@tauri-apps/api/core'
import { ExtensionManager } from '@/lib/extension'
+import { getLlamacppExtension } from '@/lib/llamacppRouterProps'
+import {
+ tokensForThinkingBudgetLevel,
+ isThinkingBudgetLevelKey,
+} from '@/lib/thinkingBudget'
import {
ExtensionTypeEnum,
VectorDBExtension,
@@ -120,6 +125,42 @@ function extractModelSamplingDefaults(
return out
}
+/**
+ * `thinking_budget_tokens` is stored as a symbolic level (low/medium/high/
+ * xhigh/unlimited), not a frozen absolute count — llama.cpp's --fit can pick
+ * a runtime n_ctx far from the configured/default size, and that's only known
+ * once the model is actually loaded. Resolve against the live n_ctx here, at
+ * send time, instead of whatever context size was in scope when the level
+ * was picked in ChatInput.
+ */
+async function resolveThinkingBudgetTokens(
+ model: Model | null | undefined,
+ modelId: string | undefined
+): Promise<number | undefined> {
+ const rawLevel = model?.settings?.thinking_budget_tokens?.controller_props?.value
+ if (!isThinkingBudgetLevelKey(rawLevel)) return undefined
+ if (rawLevel === 'unlimited') return -1
+
+ let contextSize: number | undefined
+ if (modelId) {
+ try {
+ contextSize = (await getLlamacppExtension()?.getModelProps?.(modelId))?.nCtx
+ } catch {
+ // Model not loaded yet or router unreachable; fall through to configured/default.
+ }
+ }
+ if (!contextSize) {
+ const configured = model?.settings?.ctx_len?.controller_props?.value
+ contextSize =
+ typeof configured === 'number'
+ ? configured
+ : typeof configured === 'string' && configured !== ''
+ ? Number(configured)
+ : undefined
+ }
+ return tokensForThinkingBudgetLevel(rawLevel, contextSize || 8192)
+}
+
/**
* Coerce a schema-node slot into a valid sub-schema. Some tool generators
* emit shorthand like `{ "properties": { "foo": "string" } }` instead of
@@ -907,6 +948,15 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// overrides (router mode can't bake them into CLI args). Assistant
// params still win — they're the explicit per-conversation override.
const modelSamplingDefaults = extractModelSamplingDefaults(selectedModel)
+ if (providerId === 'llamacpp') {
+ const thinkingBudgetTokens = await resolveThinkingBudgetTokens(
+ selectedModel,
+ modelId
+ )
+ if (thinkingBudgetTokens !== undefined) {
+ modelSamplingDefaults.thinking_budget_tokens = thinkingBudgetTokens
+ }
+ }
// Create the model before refreshing tools so the MCP orchestrator can run
// structured LLM routing when many servers are connected.
diff --git a/web-app/src/lib/llamacppRouterProps.ts b/web-app/src/lib/llamacppRouterProps.ts
new file mode 100644
index 000000000..ef54f1632
--- /dev/null
+++ b/web-app/src/lib/llamacppRouterProps.ts
@@ -0,0 +1,29 @@
+import { ExtensionManager } from '@/lib/extension'
+
+export interface LlamacppModelProps {
+ nCtx: number
+ totalSlots?: number
+ modelAlias?: string
+ isSleeping?: boolean
+}
+
+interface LlamacppExtensionLike {
+ getModelProps?: (modelId: string) => Promise<LlamacppModelProps | undefined>
+}
+
+/** Post-fit `nCtx` is only available once the router has actually loaded the
+ * model; callers must fall back to a configured/default context size until then. */
+export const getLlamacppExtension = (): LlamacppExtensionLike | undefined => {
+ const mgr = ExtensionManager.getInstance()
+ const candidates = [
+ mgr.getByName('@janhq/llamacpp-extension'),
+ mgr.getByName('llamacpp-extension'),
+ ]
+ for (const c of candidates) {
+ if (c && typeof (c as LlamacppExtensionLike).getModelProps === 'function')
+ return c as LlamacppExtensionLike
+ }
+ return mgr.listExtensions().find(
+ (ext) => typeof (ext as LlamacppExtensionLike).getModelProps === 'function'
+ ) as LlamacppExtensionLike | undefined
+}
diff --git a/web-app/src/lib/thinkingBudget.ts b/web-app/src/lib/thinkingBudget.ts
new file mode 100644
index 000000000..b1fac7fa7
--- /dev/null
+++ b/web-app/src/lib/thinkingBudget.ts
@@ -0,0 +1,41 @@
+export type ThinkingBudgetLevelKey =
+ | 'low'
+ | 'medium'
+ | 'high'
+ | 'xhigh'
+ | 'unlimited'
+
+// Fractions of the model's context window; null = unlimited (-1, llama.cpp's
+// sentinel for "don't cap reasoning"). Resolved against the LIVE (post-fit)
+// context size at send time, not the configured/default size at selection
+// time, since llama.cpp's --fit can pick a runtime n_ctx far from either.
+export const THINKING_BUDGET_LEVELS: Array<{
+ key: ThinkingBudgetLevelKey
+ label: string
+ ratio: number | null
+}> = [
+ { key: 'low', label: 'Low', ratio: 0.1 },
+ { key: 'medium', label: 'Medium', ratio: 0.25 },
+ { key: 'high', label: 'High', ratio: 0.5 },
+ { key: 'xhigh', label: 'XHigh', ratio: 0.75 },
+ { key: 'unlimited', label: 'Unlimited', ratio: null },
+]
+
+export const DEFAULT_THINKING_BUDGET_LEVEL: ThinkingBudgetLevelKey = 'unlimited'
+
+export function tokensForThinkingBudgetLevel(
+ level: ThinkingBudgetLevelKey,
+ contextSize: number
+): number {
+ const ratio = THINKING_BUDGET_LEVELS.find((l) => l.key === level)?.ratio
+ return ratio == null ? -1 : Math.max(1, Math.round(contextSize * ratio))
+}
+
+export function isThinkingBudgetLevelKey(
+ value: unknown
+): value is ThinkingBudgetLevelKey {
+ return (
+ typeof value === 'string' &&
+ THINKING_BUDGET_LEVELS.some((l) => l.key === value)
+ )
+}