Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(settings): bound context window and max tokens where entered and sent

purplef252c318946a
diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.ts
index beb43dc9..429f7b9d 100644
--- a/src/api/builtin-ensure.ts
+++ b/src/api/builtin-ensure.ts
@@ -35,6 +35,7 @@ import { announceEngineCpuFallback } from '../lib/engine-offload'
import { customModelDirs } from '../lib/custom-model-dirs'
import { singleModelSlot } from '../lib/capabilities'
import { claimSlotForChatLoad, getMobileContextCap } from '../lib/model-slot'
+import { clampContextWindow } from '../lib/number-limits'
interface EngineStatusLite {
running: boolean
@@ -427,9 +428,10 @@ export async function ensureBuiltinAgentCtx(modelName: string): Promise<void> {
const hit = models.find((m) => m.name === bare)
if (!hit) return
- const override = settings.contextWindowOverride
+ // Clamped (B13), the same bound the Settings field and set_setting use.
+ const override = clampContextWindow(settings.contextWindowOverride)
let want = 0
- if (typeof override === 'number' && override > 0) {
+ if (override > 0) {
want = override
} else if (typeof hit.ctx_train === 'number' && hit.ctx_train > 0) {
want = Math.max(ENGINE_DEFAULT_CTX, Math.min(hit.ctx_train, AGENT_CONTEXT_CAP))
diff --git a/src/api/ollama.ts b/src/api/ollama.ts
index aa08b1f5..d4aad21f 100644
--- a/src/api/ollama.ts
+++ b/src/api/ollama.ts
@@ -8,6 +8,7 @@ import { isLocalTransportFailure, localBackendUnreachableMessage } from "../lib/
import { ollamaWindowFor, type WindowChoice, type WindowUse } from "../lib/context-window"
import { useSettingsStore } from "../stores/settingsStore"
import { callLimit, CallTimeoutError, type CallLimitOptions } from "../lib/call-limit"
+import { clampContextWindow } from "../lib/number-limits"
/**
* How long a load may take before the app stops waiting.
@@ -228,9 +229,10 @@ const lastSentWindow = new Map<string, number>()
* over both, at once, for every caller.
*/
export async function ollamaNumCtx(model: string, use?: WindowUse): Promise<number> {
- const override = useSettingsStore.getState().settings.contextWindowOverride
+ // Clamped (B13): a typo of 999999999 is a KV-cache reservation of that size.
+ const override = clampContextWindow(useSettingsStore.getState().settings.contextWindowOverride)
let window: number
- if (override && override > 0) {
+ if (override > 0) {
// With an override the model's own maximum is never read, so nothing is asked.
window = override
} else if (use) {
diff --git a/src/components/settings/BoundedNumberInput.tsx b/src/components/settings/BoundedNumberInput.tsx
new file mode 100644
index 00000000..d86e56f5
--- /dev/null
+++ b/src/components/settings/BoundedNumberInput.tsx
@@ -0,0 +1,58 @@
+import { useState, type KeyboardEvent } from 'react'
+import { clampCount } from '../../lib/number-limits'
+
+interface Props {
+ ariaLabel: string
+ value: number
+ max: number
+ onCommit: (value: number) => void
+ placeholder?: string
+}
+
+/**
+ * A whole-number Settings field with an upper bound (Jaeger B, B9 and B13).
+ * Same pattern as CompactThresholdInput and the chat reply timeout: what is
+ * typed stays as typed until the field loses focus or Enter is pressed, then
+ * it is clamped to 0..max and saved. A value above the bound is shown as the
+ * bound right away, with a short line under the field that says so, so a
+ * slip of one extra zero does not travel silently into a request.
+ */
+export function BoundedNumberInput({ ariaLabel, value, max, onCommit, placeholder = '0' }: Props) {
+ const [draft, setDraft] = useState<string | null>(null)
+ const [clampedFrom, setClampedFrom] = useState<string | null>(null)
+
+ const commit = () => {
+ if (draft === null) return
+ const raw = parseInt(draft, 10)
+ const next = clampCount(raw, max)
+ setClampedFrom(Number.isFinite(raw) && raw > max ? draft : null)
+ onCommit(next)
+ setDraft(null)
+ }
+
+ const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter') commit()
+ }
+
+ return (
+ <span className="flex flex-col items-end">
+ <input
+ aria-label={ariaLabel}
+ type="number"
+ value={draft ?? String(clampCount(value, max))}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={onKeyDown}
+ onBlur={commit}
+ min={0}
+ max={max}
+ placeholder={placeholder}
+ className="w-20 px-1.5 py-0.5 rounded bg-transparent border border-white/8 t-mono text-right text-gray-300 focus:outline-none focus:border-white/20"
+ />
+ {clampedFrom !== null && (
+ <span role="status" className="t-micro text-amber-500 pt-0.5">
+ {`${clampedFrom} is above the limit, set to ${max.toLocaleString('en-US')}`}
+ </span>
+ )}
+ </span>
+ )
+}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 8e3cc215..8f1ccd38 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -14,6 +14,7 @@ import { CompactThresholdInput } from './CompactThresholdInput'
import { HowItWorks } from '../ui/HowItWorks'
import { HOWTO } from '../../lib/howto'
import { useSettingsStore } from '../../stores/settingsStore'
+import { rerunOnboarding } from '../../lib/onboarding-rerun'
import { useUIStore } from '../../stores/uiStore'
import { SliderControl } from './SliderControl'
import { THINK_BUDGET_STEP, normalizeThinkBudget } from '../../lib/think-budget'
@@ -88,6 +89,8 @@ import { ContentPolicySettings } from './ContentPolicySettings'
import { isLmStudioProvider } from '../../lib/hf-to-provider'
import { TEMPERATURE_MAX, TEMPERATURE_HELP, TEMPERATURE_HELP_LABEL } from '../../lib/sampling'
import { HighTemperatureWarning } from '../chat/HighTemperatureWarning'
+import { BoundedNumberInput } from './BoundedNumberInput'
+import { CONTEXT_WINDOW_MAX, MAX_TOKENS_MAX } from '../../lib/number-limits'
// ── User profile picture (Appearance) ───────────────────────────
// Self-contained like HfDownloadPathSetting. Stores the picture as a
@@ -2040,14 +2043,11 @@ export function SettingsPage() {
die Werte untereinander nicht wandern). */}
<div className="flex items-center justify-between">
<span className="t-micro text-gray-700 dark:text-gray-400">Max Tokens</span>
- <input
- aria-label="Max Tokens"
- type="number"
+ <BoundedNumberInput
+ ariaLabel="Max Tokens"
value={settings.maxTokens}
- onChange={(e) => updateSettings({ maxTokens: Math.max(0, parseInt(e.target.value) || 0) })}
- min={0}
- placeholder="0"
- className="w-20 px-1.5 py-0.5 rounded bg-transparent border border-white/8 t-mono text-right text-gray-300 focus:outline-none focus:border-white/20"
+ max={MAX_TOKENS_MAX}
+ onCommit={(v) => updateSettings({ maxTokens: v })}
/>
</div>
{/* Think budget (D12). Same row shape as Max Tokens above; 0 is
@@ -2079,18 +2079,15 @@ export function SettingsPage() {
context window. Ignored by Anthropic / OpenAI providers. */}
<div className="flex items-center justify-between">
<span className="t-micro text-gray-700 dark:text-gray-400" title="Forwarded as Ollama num_ctx. 0 = provider default (Ollama defaults to 2048, which clips RAG and long chats). Bump up to use the model's full context. Ignored by cloud providers.">Context window (Ollama)</span>
- <input
- aria-label="Context window (Ollama)"
- type="number"
+ <BoundedNumberInput
+ ariaLabel="Context window (Ollama)"
value={settings.contextWindowOverride ?? 0}
- onChange={(e) => updateSettings({ contextWindowOverride: Math.max(0, parseInt(e.target.value) || 0) })}
- min={0}
- placeholder="0"
- className="w-20 px-1.5 py-0.5 rounded bg-transparent border border-white/8 t-mono text-right text-gray-300 focus:outline-none focus:border-white/20"
+ max={CONTEXT_WINDOW_MAX}
+ onCommit={(v) => updateSettings({ contextWindowOverride: v })}
/>
</div>
<div className="t-micro text-gray-500 dark:text-gray-500 leading-relaxed pt-0.5">
- 0 = let Ollama decide (defaults to 2048). Set to e.g. 8192 or 16384 if RAG / long chats get clipped. Cloud providers ignore this.
+ 0 = let Ollama decide (defaults to 2048). Set to e.g. 8192 or 16384 if RAG / long chats get clipped, at most 1,048,576. Cloud providers ignore this. Max Tokens goes up to 1,000,000.
</div>
{/* Auto-compact (2.6.8, on by default since 3.0.7). The switch is
its own row; the threshold is shown as a percentage and stored
@@ -2282,22 +2279,7 @@ export function SettingsPage() {
</div>
</div>
<button
- onClick={async () => {
- // The line above is what actually re-runs the wizard: AppShell
- // gates it on settings.onboardingDone, and that store is
- // persisted, so it survives the reload below. The backend call
- // only clears the marker FILE, which is read in one place,
- // the NSIS-update recovery in AppShell, and only when the
- // store itself was lost.
- //
- // Level (a): silent on purpose. The visible action succeeds
- // either way, and the reload on the next line would wipe any
- // message before it could be read. A stale marker costs
- // nothing until a store-loss recovery, which re-writes it.
- useSettingsStore.getState().updateSettings({ onboardingDone: false })
- try { await backendCall('set_onboarding_done', { done: false }) } catch { /* see above */ }
- window.location.reload()
- }}
+ onClick={() => { void rerunOnboarding() }}
className="ml-3 shrink-0 px-2.5 py-1 rounded-md text-[0.6rem] font-medium bg-white dark:bg-white/10 text-gray-800 dark:text-white hover:bg-gray-100 dark:hover:bg-white/15 border border-gray-200 dark:border-white/15 transition-colors"
>
Re-run onboarding
diff --git a/src/lib/__tests__/context-and-answer-limits-are-bounded.test.tsx b/src/lib/__tests__/context-and-answer-limits-are-bounded.test.tsx
new file mode 100644
index 00000000..7b96cda0
--- /dev/null
+++ b/src/lib/__tests__/context-and-answer-limits-are-bounded.test.tsx
@@ -0,0 +1,54 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Jaeger B, B13: "Context window (Ollama)" and "Max Tokens" took any number,
+ * and 999999999 went out unchanged as num_ctx (a KV-cache reservation of that
+ * size) and as the answer budget. The fields now clamp on blur and say so,
+ * and the request paths clamp again for a value that reached the store by
+ * any other way.
+ *
+ * Run: npx vitest run src/lib/__tests__/context-and-answer-limits-are-bounded.test.tsx
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { createElement } from 'react'
+import { render, screen, fireEvent, cleanup } from '@testing-library/react'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { DEFAULT_SETTINGS } from '../constants'
+import { ollamaNumCtx } from '../../api/ollama'
+import { effectiveSampling } from '../sampling'
+import { CONTEXT_WINDOW_MAX, MAX_TOKENS_MAX } from '../number-limits'
+import { BoundedNumberInput } from '../../components/settings/BoundedNumberInput'
+
+beforeEach(() => useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS } }))
+afterEach(() => cleanup())
+
+describe('B13: context window and max tokens have an upper bound', () => {
+ it('num_ctx never carries more than the cap, whatever the store holds', async () => {
+ useSettingsStore.getState().updateSettings({ contextWindowOverride: 999_999_999 })
+ expect(await ollamaNumCtx('llama3:8b', 'chat')).toBe(CONTEXT_WINDOW_MAX)
+ useSettingsStore.getState().updateSettings({ contextWindowOverride: 16_384 })
+ expect(await ollamaNumCtx('llama3:8b', 'chat')).toBe(16_384)
+ })
+
+ it('the answer budget sent is clamped, 0 stays model default', () => {
+ expect(effectiveSampling({ temperature: 0.7, topP: 0.9, maxTokens: 2_000_000_000 }).maxTokens).toBe(MAX_TOKENS_MAX)
+ expect(effectiveSampling({ temperature: 0.7, topP: 0.9, maxTokens: 0 }).maxTokens).toBe(0)
+ expect(effectiveSampling({ temperature: 0.7, topP: 0.9, maxTokens: 999 }).maxTokens).toBe(999)
+ })
+
+ it('the field keeps the draft while typing, clamps on blur and says so', () => {
+ let saved = -1
+ render(createElement(BoundedNumberInput, { ariaLabel: 'Context window (Ollama)', value: 0, max: CONTEXT_WINDOW_MAX, onCommit: (v: number) => { saved = v } }))
+ const el = screen.getByLabelText('Context window (Ollama)') as HTMLInputElement
+ fireEvent.change(el, { target: { value: '999999999' } })
+ expect(saved).toBe(-1)
+ expect(el.value).toBe('999999999')
+ fireEvent.blur(el)
+ expect(saved).toBe(CONTEXT_WINDOW_MAX)
+ expect(screen.getByRole('status').textContent).toContain('1,048,576')
+ fireEvent.change(el, { target: { value: '8192' } })
+ fireEvent.keyDown(el, { key: 'Enter' })
+ expect(saved).toBe(8192)
+ expect(screen.queryByRole('status')).toBeNull()
+ })
+})
diff --git a/src/lib/number-limits.ts b/src/lib/number-limits.ts
new file mode 100644
index 00000000..4a202a5e
--- /dev/null
+++ b/src/lib/number-limits.ts
@@ -0,0 +1,30 @@
+/**
+ * Upper bounds for the number fields whose value travels straight into a
+ * request or a run (Jaeger B, B9 and B13). Before, the Settings fields took
+ * any whole number: 999999999 in "Context window (Ollama)" went out as
+ * num_ctx, which asks Ollama or the LU Engine to reserve a KV cache of that
+ * size, and a sub-agent could get 99999999 tool calls although it runs
+ * unattended. The same numbers bound set_setting from the chat
+ * (lib/settings-catalog.ts), so the field, the chat command and the request
+ * agree.
+ *
+ * 0 keeps its meaning everywhere: auto, model default, or "use the default".
+ */
+
+/** num_ctx: 1M tokens, above the largest context any local model ships with. */
+export const CONTEXT_WINDOW_MAX = 1_048_576
+/** Longest answer in tokens. */
+export const MAX_TOKENS_MAX = 1_000_000
+/** Tool calls or steps of one sub-agent. */
+export const SUB_AGENT_LIMIT_MAX = 1_000
+
+/** A whole number from 0 to `max`; anything not a positive number is 0. */
+export function clampCount(value: unknown, max: number): number {
+ const n = typeof value === 'number' ? value : Number(value)
+ if (!Number.isFinite(n) || n <= 0) return 0
+ return Math.min(max, Math.floor(n))
+}
+
+export const clampContextWindow = (v: unknown): number => clampCount(v, CONTEXT_WINDOW_MAX)
+export const clampMaxTokens = (v: unknown): number => clampCount(v, MAX_TOKENS_MAX)
+export const clampSubAgentLimit = (v: unknown): number => clampCount(v, SUB_AGENT_LIMIT_MAX)
diff --git a/src/lib/sampling.ts b/src/lib/sampling.ts
index 2bf1494a..20077b95 100644
--- a/src/lib/sampling.ts
+++ b/src/lib/sampling.ts
@@ -1,5 +1,6 @@
import { DEFAULT_SETTINGS } from './constants'
import type { Settings, SamplerValues } from '../types/settings'
+import { clampMaxTokens, MAX_TOKENS_MAX } from './number-limits'
/**
* Sampling for one conversation: temperature, top_p and a max output cap,
@@ -154,7 +155,7 @@ const BOUNDS: Record<keyof SamplingOverrides, [number, number]> = {
topP: [0, 1],
// A cap above any context window served is the same as no cap; the ceiling
// here only stops a hand-edited store from putting nonsense on the wire.
- maxTokens: [0, 1_000_000],
+ maxTokens: [0, MAX_TOKENS_MAX],
topK: [0, 1000],
minP: [0, 1],
repeatPenalty: [0, 2],
@@ -198,7 +199,8 @@ export function effectiveSampling(
return {
temperature: Number.isFinite(temperature) ? Math.min(TEMPERATURE_MAX, Math.max(0, temperature)) : SAMPLING_DEFAULTS.temperature,
topP: overrides?.topP ?? preset?.topP ?? settings.topP ?? SAMPLING_DEFAULTS.topP,
- maxTokens: overrides?.maxTokens ?? preset?.maxTokens ?? settings.maxTokens ?? SAMPLING_DEFAULTS.maxTokens,
+ // Clamped (B13) like the temperature above, 0 stays "model default".
+ maxTokens: clampMaxTokens(overrides?.maxTokens ?? preset?.maxTokens ?? settings.maxTokens ?? SAMPLING_DEFAULTS.maxTokens),
}
}
diff --git a/src/lib/settings-catalog.ts b/src/lib/settings-catalog.ts
index 8f7f6d02..de57751b 100644
--- a/src/lib/settings-catalog.ts
+++ b/src/lib/settings-catalog.ts
@@ -20,6 +20,7 @@ import { EFFORT_STEPS } from './effort'
import { normalizeThinkBudget } from './think-budget'
import { normalizeChatFirstReplySeconds } from './chat-reply-timeout'
import { TEMPERATURE_MAX } from './sampling'
+import { CONTEXT_WINDOW_MAX, MAX_TOKENS_MAX } from './number-limits'
type Parsed = { ok: true; value: unknown } | { ok: false; error: string }
@@ -177,7 +178,7 @@ export const CATALOG: readonly CatalogEntry[] = [
// Context. Three different knobs, the help says which is which.
e('autoCompact', 'Auto-compact', 'general', 'Summarise older turns automatically when the chat nears the context window.', bool()),
e('autoCompactThreshold', 'Auto-compact at', 'general', 'How full the context window gets before auto-compact runs.', compactThreshold),
- e('contextWindowOverride', 'Context window (Ollama)', 'general', 'num_ctx sent to Ollama, in tokens. Other backends ignore it.', int(0, 1_048_576, 'tokens', 'auto')),
+ e('contextWindowOverride', 'Context window (Ollama)', 'general', 'num_ctx sent to Ollama, in tokens. Other backends ignore it.', int(0, CONTEXT_WINDOW_MAX, 'tokens', 'auto')),
e('engineIdleUnloadMinutes', 'Unload the model when unused', 'backends', 'Minutes without use before LU Engine frees the model.', int(0, 1_440, 'min', 'never')),
e('builtinEngine.ctx', 'Context window (LU Engine)', 'backends', 'Context size of LU Engine, in tokens. Applies on the next engine start.', int(0, 1_048_576, 'tokens', 'default 8192')),
e('attachmentTokenLimit', 'Attachment limit', 'general', 'Most tokens one attached text file may take.', int(0, 1_048_576, 'tokens', 'no limit')),
@@ -188,7 +189,7 @@ export const CATALOG: readonly CatalogEntry[] = [
e('temperature', 'Temperature', 'general', 'Randomness of answers.', real(0, TEMPERATURE_MAX)),
e('topP', 'Top P', 'general', 'Nucleus sampling.', real(0, 1)),
e('topK', 'Top K', 'general', 'Sample from the K most likely tokens.', int(1, 100)),
- e('maxTokens', 'Max tokens', 'general', 'Longest answer in tokens.', int(0, 1_000_000, 'tokens', 'model default')),
+ e('maxTokens', 'Max tokens', 'general', 'Longest answer in tokens.', int(0, MAX_TOKENS_MAX, 'tokens', 'model default')),
// Thinking
e('thinkingEnabled', 'Thinking', 'general', 'Let reasoning models think before answering.', bool()),
e('reasoningEffort', 'Reasoning effort', 'general', 'How hard a reasoning model thinks.', oneOf(EFFORT_STEPS)),