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): a hosted chat past the message limit shrinks the request instead of dying

purple14d6a5733f36
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 7ac3146f..a9c1f9be 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -9,6 +9,7 @@ import { useVoiceStore } from "../stores/voiceStore"
import { autoSpeak } from "../lib/ttsBridge"
import { retrieveContext } from "../api/rag"
import { getModelMaxTokens } from "../lib/context-compaction"
+import { isTooManyMessagesError, halveHistory, TOO_MANY_MESSAGES_MAX_HALVINGS } from "../lib/too-many-messages"
import { getModelContextCached } from "../api/ollama"
import { requestGenerationCancel } from "../api/vram-handoff"
import { effectiveContextWindow } from "../lib/context-window"
@@ -552,11 +553,32 @@ export function useChat() {
}
// Helper: create stream, retrying without the think field if the
- // provider rejects it (old Ollama builds, edge-case models).
+ // provider rejects it (old Ollama builds, edge-case models), and
+ // retrying with a halved history when the hosted backend refuses the
+ // message COUNT ("HTTP 400 too many messages", yaserrieh 2026-08-21).
+ // Plain chat sends the whole conversation, so without this a long
+ // hosted chat is stuck forever: every further turn only grows the
+ // payload the server just refused. The 400 fires on request
+ // validation, before any token streams, so a retry never duplicates
+ // visible output. The conversation itself is never touched.
async function* createStreamWithFallback() {
try {
yield* provider.chatStream(modelId, messages, chatOpts)
} catch (err: any) {
+ if (isTooManyMessagesError(err)) {
+ let trimmed = halveHistory(messages)
+ for (let attempt = 0; trimmed; attempt++) {
+ try {
+ log.info('chat.too_many_messages_retry', { sent: trimmed.length, attempt })
+ yield* provider.chatStream(modelId, trimmed, chatOpts)
+ return
+ } catch (retryErr: any) {
+ if (!isTooManyMessagesError(retryErr) || attempt >= TOO_MANY_MESSAGES_MAX_HALVINGS) throw retryErr
+ trimmed = halveHistory(trimmed)
+ }
+ }
+ throw err
+ }
if (useThinking !== undefined && (err?.message?.includes('does not support thinking') || err?.status === 400 || err?.status === 422)) {
yield* provider.chatStream(modelId, messages, { ...chatOpts, thinking: undefined })
} else {
diff --git a/src/lib/__tests__/too-many-messages.test.ts b/src/lib/__tests__/too-many-messages.test.ts
new file mode 100644
index 00000000..9addc624
--- /dev/null
+++ b/src/lib/__tests__/too-many-messages.test.ts
@@ -0,0 +1,95 @@
+/**
+ * Feedback 2026-08-21 ([email protected], hosted-pro, route /): "Error:
+ * [network] HTTP 400 too many messages". Plain chat sends the whole
+ * conversation every turn, so past the server's message-count limit the
+ * chat is stuck forever. The recovery halves the sent history and retries,
+ * no guessed server number, and never touches the stored conversation.
+ *
+ * Run: npx vitest run src/lib/__tests__/too-many-messages.test.ts
+ */
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { describe, it, expect } from 'vitest'
+import { isTooManyMessagesError, halveHistory, TOO_MANY_MESSAGES_MAX_HALVINGS } from '../too-many-messages'
+
+type Msg = { role: string; content: string }
+const m = (role: string, i: number): Msg => ({ role, content: `${role} ${i}` })
+
+const history = (turns: number): Msg[] => [
+ { role: 'system', content: 'sys' },
+ ...Array.from({ length: turns }, (_, i) => [m('user', i), m('assistant', i)]).flat(),
+]
+
+describe('isTooManyMessagesError', () => {
+ it('matches the exact server refusal, case-insensitively', () => {
+ expect(isTooManyMessagesError(new Error('[network] HTTP 400 too many messages'))).toBe(true)
+ expect(isTooManyMessagesError(new Error('Too Many Messages'))).toBe(true)
+ })
+
+ it('NEGATIVE CONTROL: other 400s and other errors never trigger the halving', () => {
+ expect(isTooManyMessagesError(new Error('HTTP 400 invalid payload'))).toBe(false)
+ expect(isTooManyMessagesError(new Error('does not support thinking'))).toBe(false)
+ expect(isTooManyMessagesError(new Error('too many requests'))).toBe(false)
+ expect(isTooManyMessagesError(undefined)).toBe(false)
+ })
+})
+
+describe('halveHistory', () => {
+ it('keeps the system prompt and the newest half, starting on a user turn', () => {
+ const out = halveHistory(history(20))!
+ expect(out[0].role).toBe('system')
+ expect(out.length).toBeLessThan(41)
+ expect(out[1].role).toBe('user')
+ expect(out[out.length - 1].content).toBe('assistant 19')
+ })
+
+ it('always retains the latest user turn, however small the half', () => {
+ let msgs: Msg[] | null = history(50)
+ for (let i = 0; i < TOO_MANY_MESSAGES_MAX_HALVINGS; i++) {
+ const next: Msg[] | null = halveHistory(msgs!)
+ if (!next) break
+ expect(next.some((x) => x.content === 'user 49')).toBe(true)
+ msgs = next
+ }
+ })
+
+ it('works without a system prompt', () => {
+ const out = halveHistory(history(10).slice(1))!
+ expect(out[0].role).toBe('user')
+ expect(out.length).toBeLessThan(20)
+ })
+
+ it('returns null once nothing sensible is left, so the caller surfaces the real error', () => {
+ expect(halveHistory([{ role: 'system', content: 's' }, m('user', 0), m('assistant', 0)])).toBeNull()
+ expect(halveHistory([m('user', 0)])).toBeNull()
+ expect(halveHistory([])).toBeNull()
+ })
+
+ it('NEGATIVE CONTROL: the input array is never mutated', () => {
+ const msgs = history(12)
+ const before = JSON.stringify(msgs)
+ halveHistory(msgs)
+ expect(JSON.stringify(msgs)).toBe(before)
+ })
+
+ it('a handful of halvings shrinks any long history below any plausible limit', () => {
+ let msgs: Msg[] | null = history(500)
+ for (let i = 0; i < TOO_MANY_MESSAGES_MAX_HALVINGS && msgs; i++) msgs = halveHistory(msgs)
+ expect(msgs).not.toBeNull()
+ expect(msgs!.length).toBeLessThanOrEqual(33)
+ })
+})
+
+describe('wiring (source guards)', () => {
+ const chatSrc = readFileSync(join(__dirname, '../../hooks/useChat.ts'), 'utf8').replace(/\r\n/g, '\n')
+
+ it('the plain-chat stream fallback halves and retries on the count refusal', () => {
+ expect(chatSrc).toContain('if (isTooManyMessagesError(err))')
+ expect(chatSrc).toContain('halveHistory(messages)')
+ expect(chatSrc).toContain('provider.chatStream(modelId, trimmed, chatOpts)')
+ })
+
+ it('the retry is bounded and re-throws anything that is not the count refusal', () => {
+ expect(chatSrc).toContain('attempt >= TOO_MANY_MESSAGES_MAX_HALVINGS) throw retryErr')
+ })
+})
diff --git a/src/lib/too-many-messages.ts b/src/lib/too-many-messages.ts
new file mode 100644
index 00000000..395a2602
--- /dev/null
+++ b/src/lib/too-many-messages.ts
@@ -0,0 +1,42 @@
+/**
+ * Feedback 2026-08-21 ([email protected], hosted-pro, route /): "Error:
+ * [network] HTTP 400 too many messages". The plain chat path sends the WHOLE
+ * conversation on every turn (unlike the agent and coding loops, which
+ * compact), so once a hosted conversation crosses the server's message-count
+ * limit every further turn is refused and the user is stuck in that chat
+ * forever, each new message only making the payload longer.
+ *
+ * The server's exact limit is not knowable from the client and may change,
+ * so the recovery does not guess a number: when the server answers with the
+ * too-many-messages 400, the client halves the sent history (keeping the
+ * system prompt and the newest half, always including the latest user turn)
+ * and retries. A few halvings reach any positive limit; the conversation
+ * itself is never touched, only the request shrinks.
+ */
+
+/** True for the server's message-count refusal, and nothing else. */
+export function isTooManyMessagesError(err: unknown): boolean {
+ const msg = err instanceof Error ? err.message : typeof err === 'string' ? err : ''
+ return /too many messages/i.test(msg)
+}
+
+/**
+ * Halve the non-system history, newest half wins. Returns null once there is
+ * nothing sensible left to drop (2 or fewer non-system messages), so the
+ * caller stops retrying and surfaces the real error. Leading assistant/tool
+ * messages after the cut are dropped so the trimmed history starts on a user
+ * turn, some strict providers refuse anything else after the system prompt.
+ */
+export function halveHistory<T extends { role: string }>(messages: T[]): T[] | null {
+ if (messages.length === 0) return null
+ const system = messages[0].role === 'system' ? [messages[0]] : []
+ let rest = messages.slice(system.length)
+ if (rest.length <= 2) return null
+ rest = rest.slice(Math.ceil(rest.length / 2))
+ while (rest.length > 1 && rest[0].role !== 'user') rest.shift()
+ if (rest.length === 0) return null
+ return [...system, ...rest]
+}
+
+/** Retry budget: 2^5 = 32-fold shrink reaches any plausible server limit. */
+export const TOO_MANY_MESSAGES_MAX_HALVINGS = 5