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): a negative Max Tokens broke Anthropic on every request

purple57c1feee4c94
diff --git a/src/api/__tests__/provider-maxtokens-guard.test.ts b/src/api/__tests__/provider-maxtokens-guard.test.ts
new file mode 100644
index 00000000..ca295737
--- /dev/null
+++ b/src/api/__tests__/provider-maxtokens-guard.test.ts
@@ -0,0 +1,108 @@
+/**
+ * A negative Max Tokens must never reach a provider (2026-07-28)
+ *
+ * The Settings field wrote `parseInt(value) || 0` with no clamp — the HTML
+ * `min={0}` does not bind what React puts in the store, so a typed or pasted
+ * "-500" was persisted as-is. Anthropic then sent `max_tokens: -500` (a
+ * negative is truthy, so `|| 4096` never fired) and the API rejected every
+ * request; Ollama forwarded it as num_predict, where negatives mean
+ * "unlimited"/"fill context" rather than a budget.
+ *
+ * Run: npx vitest run src/api/__tests__/provider-maxtokens-guard.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+const localFetchStream = vi.fn()
+vi.mock('../backend', () => ({
+ localFetch: vi.fn(),
+ localFetchStream: (...a: any[]) => localFetchStream(...(a as [])),
+ ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,
+ isPrivateOrLanHost: () => true,
+ isDirectFetchAllowed: () => true,
+ hostnameOf: (u: string) => { try { return new URL(u).hostname } catch { return '' } },
+ ensureProxyAllowsHost: async () => {},
+ isTauri: () => false,
+}))
+
+import { AnthropicProvider } from '../providers/anthropic-provider'
+import { OllamaProvider } from '../providers/ollama-provider'
+import type { ProviderConfig } from '../providers/types'
+
+function anthropicConfig(): ProviderConfig {
+ return {
+ id: 'anthropic',
+ name: 'Anthropic',
+ enabled: true,
+ baseUrl: 'https://api.anthropic.com',
+ apiKey: 'test-key',
+ isLocal: false,
+ } as ProviderConfig
+}
+
+function sse(events: string[]): Response {
+ return new Response(events.map(e => `data: ${e}\n\n`).join(''), {
+ status: 200,
+ headers: { 'Content-Type': 'text/event-stream' },
+ })
+}
+
+function bodyOf(mock: ReturnType<typeof vi.fn>): any {
+ const init = mock.mock.calls[0]?.[1]
+ return JSON.parse(String(init?.body ?? '{}'))
+}
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ localFetchStream.mockReset()
+})
+
+describe('max_tokens guard', () => {
+ it('anthropic falls back to its default instead of sending a negative', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(sse(['{"type":"message_stop"}']))
+ vi.stubGlobal('fetch', fetchMock)
+ const provider = new AnthropicProvider(anthropicConfig())
+ for await (const _ of provider.chatStream('claude-x', [{ role: 'user', content: 'hi' }], { maxTokens: -500 })) {
+ // drain
+ }
+ expect(bodyOf(fetchMock).max_tokens).toBe(4096)
+ })
+
+ it('anthropic still honours a real budget', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(sse(['{"type":"message_stop"}']))
+ vi.stubGlobal('fetch', fetchMock)
+ const provider = new AnthropicProvider(anthropicConfig())
+ for await (const _ of provider.chatStream('claude-x', [{ role: 'user', content: 'hi' }], { maxTokens: 1234 })) {
+ // drain
+ }
+ expect(bodyOf(fetchMock).max_tokens).toBe(1234)
+ })
+
+ it('ollama leaves num_predict unset for a negative budget', async () => {
+ const provider = new OllamaProvider({
+ id: 'ollama', name: 'Ollama', enabled: true,
+ baseUrl: 'http://localhost:11434', isLocal: true,
+ } as ProviderConfig)
+ localFetchStream.mockResolvedValue(
+ new Response('{"done":true}\n', { status: 200, headers: { 'Content-Type': 'application/x-ndjson' } }),
+ )
+ for await (const _ of provider.chatStream('llama3', [{ role: 'user', content: 'hi' }], { maxTokens: -500 })) {
+ // drain
+ }
+ const sent = JSON.parse(String(localFetchStream.mock.calls[0][1].body))
+ expect(sent.options?.num_predict).toBeUndefined()
+ })
+
+ it('ollama forwards a real budget as num_predict', async () => {
+ const provider = new OllamaProvider({
+ id: 'ollama', name: 'Ollama', enabled: true,
+ baseUrl: 'http://localhost:11434', isLocal: true,
+ } as ProviderConfig)
+ localFetchStream.mockResolvedValue(
+ new Response('{"done":true}\n', { status: 200, headers: { 'Content-Type': 'application/x-ndjson' } }),
+ )
+ for await (const _ of provider.chatStream('llama3', [{ role: 'user', content: 'hi' }], { maxTokens: 256 })) {
+ // drain
+ }
+ const sent = JSON.parse(String(localFetchStream.mock.calls[0][1].body))
+ expect(sent.options.num_predict).toBe(256)
+ })
+})
diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.ts
index 073fa5e4..2f9deabf 100644
--- a/src/api/providers/anthropic-provider.ts
+++ b/src/api/providers/anthropic-provider.ts
@@ -93,7 +93,7 @@ export class AnthropicProvider implements ProviderClient {
const body: Record<string, any> = {
model,
messages: anthropicMessages,
- max_tokens: options?.maxTokens || 4096,
+ max_tokens: options?.maxTokens && options.maxTokens > 0 ? options.maxTokens : 4096,
stream: true,
}
@@ -226,7 +226,7 @@ export class AnthropicProvider implements ProviderClient {
const body: Record<string, any> = {
model,
messages: anthropicMessages,
- max_tokens: options?.maxTokens || 4096,
+ max_tokens: options?.maxTokens && options.maxTokens > 0 ? options.maxTokens : 4096,
}
if (system) body.system = system
diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.ts
index 8be30644..146b4f1c 100644
--- a/src/api/providers/ollama-provider.ts
+++ b/src/api/providers/ollama-provider.ts
@@ -98,7 +98,7 @@ export class OllamaProvider implements ProviderClient {
if (options?.temperature !== undefined) ollamaOptions.temperature = options.temperature
if (options?.topP !== undefined) ollamaOptions.top_p = options.topP
if (options?.topK !== undefined) ollamaOptions.top_k = options.topK
- if (options?.maxTokens) ollamaOptions.num_predict = options.maxTokens
+ if (options?.maxTokens && options.maxTokens > 0) ollamaOptions.num_predict = options.maxTokens
// Bug AA v2.5.0 — forward user's context-window override. Without this
// Ollama silently uses num_ctx=2048 (its default), which RAG payloads
// and long-turn chats blow through immediately. Kj103x Discord
@@ -198,7 +198,7 @@ export class OllamaProvider implements ProviderClient {
if (options?.temperature !== undefined) ollamaOptions.temperature = options.temperature
if (options?.topP !== undefined) ollamaOptions.top_p = options.topP
if (options?.topK !== undefined) ollamaOptions.top_k = options.topK
- if (options?.maxTokens) ollamaOptions.num_predict = options.maxTokens
+ if (options?.maxTokens && options.maxTokens > 0) ollamaOptions.num_predict = options.maxTokens
// Bug AA v2.5.0 — see chatStream() for the why.
// num_ctx comes from the caller (hook): the user override OR the model's
// real context length (capped for VRAM safety). 0/undefined → Ollama keeps
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 36b02ec0..a14e424d 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -1121,7 +1121,7 @@ export function SettingsPage() {
<input
type="number"
value={settings.maxTokens}
- onChange={(e) => updateSettings({ maxTokens: parseInt(e.target.value) || 0 })}
+ 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 text-[0.65rem] text-right text-gray-300 font-mono focus:outline-none focus:border-white/20"