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(chat): die Historie kann das 400-Nachrichten-Tor nicht mehr reissen

Davidcd821243ca23
diff --git a/src/api/__tests__/context-compaction.test.ts b/src/api/__tests__/context-compaction.test.ts
index 5ad4c489..5208bc43 100644
--- a/src/api/__tests__/context-compaction.test.ts
+++ b/src/api/__tests__/context-compaction.test.ts
@@ -290,3 +290,68 @@ describe('compactMessages — oversized tool results', () => {
expect(notice!.content).toMatch(/never repeat a call/)
})
})
+
+// ── Message-count ceiling (yaserrieh, 2026-08-21) ────────────────
+// A chat of many SHORT turns sits under every token budget while the count
+// grows past the LU Cloud proxy's 400-message gate; from then on every send
+// 400s ("too many messages") and the chat is a permanent dead end. The cap
+// must fire on COUNT alone.
+
+import { MAX_SEND_MESSAGES, capMessageCount } from '../../lib/context-compaction'
+
+describe('message-count ceiling', () => {
+ const tiny = (n: number): OllamaChatMessage[] => [
+ { role: 'system', content: 'sys' },
+ ...Array.from({ length: n }, (_, i) => ({
+ role: (i % 2 === 0 ? 'user' : 'assistant') as 'user' | 'assistant',
+ content: `m${i}`,
+ })),
+ ]
+
+ it('compactMessages shrinks a count-heavy history even under the token budget', () => {
+ const messages = tiny(450)
+ // Huge token budget: the OLD code returned this unchanged.
+ const out = compactMessages(messages, 10_000_000)
+ expect(out.length).toBeLessThanOrEqual(MAX_SEND_MESSAGES)
+ expect(out[0].role).toBe('system')
+ expect(out[out.length - 1].content).toBe('m449')
+ })
+
+ it('compactMessages leaves a history under both budgets alone', () => {
+ const messages = tiny(100)
+ expect(compactMessages(messages, 10_000_000)).toEqual(messages)
+ })
+
+ it('count trim announces itself like a token trim', () => {
+ const out = compactMessages(tiny(450), 10_000_000)
+ const notice = out.find(
+ (m) => m.role === 'system' && typeof m.content === 'string' && m.content.includes('trimmed'),
+ )
+ expect(notice).toBeTruthy()
+ })
+
+ it('capMessageCount keeps system prompt and the newest messages', () => {
+ const out = capMessageCount(tiny(450))
+ expect(out.length).toBe(MAX_SEND_MESSAGES)
+ expect(out[0].content).toBe('sys')
+ expect(out[out.length - 1].content).toBe('m449')
+ })
+
+ it('capMessageCount never starts the window on an orphan tool result', () => {
+ const msgs: OllamaChatMessage[] = [
+ { role: 'system', content: 'sys' },
+ ...Array.from({ length: 500 }, (_, i) => ({
+ role: (i % 2 === 0 ? 'assistant' : 'tool') as 'assistant' | 'tool',
+ content: `m${i}`,
+ })),
+ ]
+ const out = capMessageCount(msgs)
+ expect(out[1].role).not.toBe('tool')
+ expect(out.length).toBeLessThanOrEqual(MAX_SEND_MESSAGES)
+ })
+
+ it('capMessageCount is the identity under the ceiling', () => {
+ const messages = tiny(50)
+ expect(capMessageCount(messages)).toBe(messages)
+ })
+})
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 7ac3146f..951bd9cc 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -8,7 +8,7 @@ import { useMemoryStore } from "../stores/memoryStore"
import { useVoiceStore } from "../stores/voiceStore"
import { autoSpeak } from "../lib/ttsBridge"
import { retrieveContext } from "../api/rag"
-import { getModelMaxTokens } from "../lib/context-compaction"
+import { getModelMaxTokens, capMessageCount } from "../lib/context-compaction"
import { getModelContextCached } from "../api/ollama"
import { requestGenerationCancel } from "../api/vram-handoff"
import { effectiveContextWindow } from "../lib/context-window"
@@ -73,10 +73,12 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
useChatStore.getState().addMessage(convId, assistantMessage)
const personaPrompt = conv.personaEnabled === true ? conv.systemPrompt : ''
- const messages = [
+ // Same count cap as the plain path: a long group chat must not outgrow the
+ // proxy's message gate either.
+ const messages = capMessageCount([
{ role: 'system' as const, content: groupSystemPrompt(model, allModels, personaPrompt) },
...groupHistory(conv.messages, model),
- ]
+ ])
const providerId = getProviderIdFromModel(model)
const canThink = isThinkingCompatible(model)
@@ -469,7 +471,12 @@ export function useChat() {
? (await import('../lib/constants')).CAVEMAN_REMINDERS?.[settings.cavemanMode as 'lite' | 'full' | 'ultra'] || ''
: ''
- const messages = [
+ // Count cap (web parity, MAX_SEND_MESSAGES): plain chat sends the whole
+ // history verbatim, and a long chat of many short turns stays under every
+ // token budget while the count climbs past the LU Cloud proxy's
+ // 400-message gate — after which EVERY send 400s and the chat is a
+ // permanent dead end (yaserrieh, 2026-08-21).
+ const messages = capMessageCount([
...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
...conv.messages
.filter((m) => m.content.trim() !== '')
@@ -480,7 +487,7 @@ export function useChat() {
: m.content,
...(m.images?.length ? { images: m.images.map(img => ({ data: img.data, mimeType: img.mimeType })) } : {}),
})),
- ]
+ ])
const abort = new AbortController()
abortRef.current = abort
diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.ts
index b97f3083..e6e6848c 100644
--- a/src/lib/context-compaction.ts
+++ b/src/lib/context-compaction.ts
@@ -78,6 +78,20 @@ export async function getModelMaxTokens(modelName: string): Promise<number> {
const KEEP_RECENT = 4 // Always keep at least the last N messages untouched
+/** Hard ceiling on how many messages one request may carry, independent of
+ * tokens. The LU Cloud proxy rejects anything above 400 messages, and a chat
+ * of many SHORT turns sits under every token budget while the count keeps
+ * growing — the token-only compaction never fired and the chat hard-400ed on
+ * every send, permanently (yaserrieh, 2026-08-21: "[network] HTTP 400 too
+ * many messages" after ~7 coding tasks in one chat). 380 mirrors the web
+ * app's MAX_SEND_MESSAGES and leaves room for the pin and the trim notice. */
+export const MAX_SEND_MESSAGES = 380
+
+/** Suffix quota inside compactMessages: system prompt, pinned task and trim
+ * notice ride on top of the kept window, so the window itself stays 3 short
+ * of the ceiling. */
+const COUNT_BUDGET = MAX_SEND_MESSAGES - 3
+
/** How much of the pinned first user message survives compaction. Enough for
* any real instruction; a pasted 200 KB file does not ride along forever. */
const PINNED_TASK_MAX_CHARS = 8000
@@ -139,14 +153,35 @@ function isToolResultMessage(msg: OllamaChatMessage): boolean {
* Dropping is honest: the model re-reads with file_read when it needs the bytes
* again, instead of trusting a lossy stub.
*/
+/**
+ * Count-only cap for paths that never token-compact (the plain chat path).
+ * Keeps the system prompt plus the newest messages and never starts the kept
+ * window on an orphan tool result. Token budgets are compactMessages' job;
+ * this only guarantees the proxy's message-count gate can't be tripped.
+ */
+export function capMessageCount<T extends { role: string; content?: unknown }>(
+ messages: T[],
+ max = MAX_SEND_MESSAGES,
+): T[] {
+ if (messages.length <= max) return messages
+ const sys = messages[0]?.role === 'system' ? [messages[0]] : []
+ const rest = sys.length ? messages.slice(1) : messages
+ const kept = rest.slice(-(max - sys.length))
+ while (kept.length > 0 && isToolResultMessage(kept[0] as unknown as OllamaChatMessage)) {
+ kept.shift()
+ }
+ return [...sys, ...kept]
+}
+
export function compactMessages(
messages: OllamaChatMessage[],
maxTokens: number
): OllamaChatMessage[] {
const currentTokens = estimateMessageTokens(messages)
- // Already within budget
- if (currentTokens <= maxTokens) return messages
+ // Already within budget — BOTH budgets. A history that fits the token
+ // window but exceeds the message-count ceiling still has to shrink.
+ if (currentTokens <= maxTokens && messages.length <= MAX_SEND_MESSAGES) return messages
// Separate system prompt (always kept)
const systemMsg = messages[0]?.role === 'system' ? messages[0] : null
@@ -197,6 +232,10 @@ export function compactMessages(
const kept: OllamaChatMessage[] = []
let used = 0
for (let i = capped.length - 1; i >= 0; i--) {
+ // Count bound first: it holds even where the token check would keep
+ // adding, otherwise a many-short-turns history fits every token budget
+ // and still trips the proxy's message-count cap.
+ if (kept.length >= COUNT_BUDGET) break
const t = estimateMessageTokens([capped[i]])
if (used + t > suffixBudget && kept.length >= KEEP_RECENT) break
kept.unshift(capped[i])