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(group): a long answer earlier in the round goes out shortened, not refused

purple2f8944d68330
diff --git a/src/hooks/__tests__/group-long-answer-in-the-round.test.ts b/src/hooks/__tests__/group-long-answer-in-the-round.test.ts
new file mode 100644
index 00000000..71dccadc
--- /dev/null
+++ b/src/hooks/__tests__/group-long-answer-in-the-round.test.ts
@@ -0,0 +1,187 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * T1 2026-10-29 (GH #201 follow-up): three local members on a 16K window. The
+ * first speaker wrote 82 500 characters, and both later speakers of the round
+ * ended on "This message is longer than the model can read at once": the
+ * trim drops only older turns and always keeps the newest, and the newest was
+ * that one answer. The refusal sentence then went to the next speaker as the
+ * failed speaker's answer, since it carried no error field.
+ *
+ * Driven through the real `useChat().sendMessage`, only the network and the
+ * window lookup replaced: what is asserted is the request each model receives.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))
+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))
+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))
+vi.mock('../useMemory', () => ({
+ useMemory: () => ({ extractAndSave: async () => {} }),
+ extractMemoriesFromPair: async () => {},
+}))
+vi.mock('../../lib/run-lane-of-model', () => ({
+ laneOf: () => 'cloud',
+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),
+}))
+vi.mock('../../lib/lan-openai-slot', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../lib/lan-openai-slot')>()),
+ sendsToALanBackend: () => true,
+}))
+vi.mock('../../lib/context-compaction', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../lib/context-compaction')>()),
+ getChatWindowTokens: async () => 16384,
+}))
+
+import { useChat } from '../useChat'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { __resetRunLanesForTests } from '../../lib/run-lanes'
+import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../../lib/constants'
+import { estimateMessageTokens, shortenLongTurns } from '../../lib/context-compaction'
+import { chatSendBudget } from '../../lib/chat-send-budget'
+import { historyTrimNote } from '../../lib/history-trim-note'
+
+const A = 'openai::qwen05'
+const B = 'openai::qwen05-zwei'
+const C = 'openai::coder15'
+
+interface WireMessage { role: string; content: string }
+interface Request { model: string; messages: WireMessage[] }
+let requests: Request[] = []
+let reply: (model: string) => Response
+
+const LONG = 'The robot walked on. '.repeat(3929).slice(0, 82_500)
+const sse = (text: string) =>
+ new Response(`data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\ndata: [DONE]\n\n`, {
+ status: 200, headers: { 'content-type': 'text/event-stream' },
+ })
+const refused = () =>
+ new Response(JSON.stringify({ error: { code: 400, message: 'request (16866 tokens) exceeds the available context size (16384 tokens), try increasing it', type: 'exceed_context_size_error' } }), {
+ status: 400, headers: { 'content-type': 'application/json' },
+ })
+
+beforeEach(() => {
+ requests = []
+ __resetRunLanesForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ models: [], activeModel: A })
+ useSettingsStore.setState({
+ settings: { ...DEFAULT_SETTINGS, appMode: 'local', cavemanMode: 'off' },
+ personas: [...BUILT_IN_PERSONAS],
+ })
+ useProviderStore.setState((s) => ({
+ providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },
+ }))
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ if (!String(input).includes('/chat/completions')) return new Response('{}', { status: 200 })
+ const body = JSON.parse(String((init as RequestInit).body)) as Request
+ requests.push(body)
+ return reply(body.model)
+ })
+})
+afterEach(() => vi.restoreAllMocks())
+
+function openGroup(): string {
+ const convId = useChatStore.getState().createConversation(A, '')
+ useChatStore.getState().setActiveConversation(convId)
+ useChatStore.getState().setGroupModels(convId, [A, B, C])
+ return convId
+}
+
+const wireSize = (r: Request) => estimateMessageTokens(r.messages as never)
+const allText = (r: Request) => r.messages.map((m) => m.content).join('\n')
+const turns = (id: string) =>
+ useChatStore.getState().conversations.find((c) => c.id === id)!.messages.filter((m) => m.role === 'assistant')
+
+async function round(text: string) {
+ const { result } = renderHook(() => useChat())
+ await act(async () => { await result.current.sendMessage(text) })
+}
+
+describe('a long answer earlier in the same round', () => {
+ it('goes to the later speakers shortened to their window, and the chat keeps it whole', async () => {
+ reply = (model) => sse(model === 'qwen05' ? LONG : `${model} answer.`)
+ const convId = openGroup()
+ await round('Write a long story of 600 words about a robot.')
+
+ expect(requests.map((r) => r.model)).toEqual(['qwen05', 'qwen05-zwei', 'coder15'])
+ const budget = chatSendBudget({ providerId: 'openai', modelWindow: 16384, contextDecay: true, localBackend: true })!
+ for (const r of requests.slice(1)) {
+ expect(wireSize(r)).toBeLessThanOrEqual(budget)
+ // Head and tail of the long answer are still there, the middle is cut.
+ const text = allText(r)
+ expect(text).toContain('[openai::qwen05] The robot walked on.') // tagged as the other speaker
+ expect(text).toContain('The robot walked on.')
+ expect(text).toMatch(/…\[truncated \d+ chars\]…/)
+ // And the person's own line, the one being answered, went out whole.
+ expect(text).toContain('Write a long story of 600 words about a robot.')
+ }
+ const said = turns(convId)
+ expect(said[0].content).toBe(LONG)
+ expect(said.slice(1).map((m) => m.content)).toEqual(['qwen05-zwei answer.', 'coder15 answer.'])
+ expect(said.slice(1).map((m) => m.historyTrim)).toEqual([{ dropped: 0, window: 16384, shortened: 1 }, { dropped: 0, window: 16384, shortened: 1 }])
+ expect(historyTrimNote(said[1].historyTrim!, 'qwen05-zwei')).toBe(
+ '1 long message was sent shortened to qwen05-zwei to fit its 16K context. The chat itself keeps it whole.',
+ )
+ })
+
+ it('a refused speaker\'s sentence is not sent to the next speaker as its answer', async () => {
+ reply = (model) => (model === 'qwen05' ? refused() : sse(`${model} answer.`))
+ const convId = openGroup()
+ await round('hallo')
+
+ const said = turns(convId)
+ expect(said[0].content).not.toBe('')
+ expect(said[0].error).toBeTruthy()
+ expect(said[0].error!.at).toBe(0)
+ const later = requests.filter((r) => r.model !== 'qwen05')
+ expect(later.map((r) => r.model)).toEqual(['qwen05-zwei', 'coder15'])
+ for (const r of later) {
+ expect(allText(r)).not.toContain(said[0].content)
+ expect(allText(r)).not.toContain('[openai::qwen05]')
+ }
+ })
+})
+
+describe('shortenLongTurns', () => {
+ const m = (role: string, content: string) => ({ role, content })
+
+ it('leaves a payload that fits as it is', () => {
+ const msgs = [m('system', 's'), m('user', 'a'), m('assistant', 'b')]
+ expect(shortenLongTurns(msgs, 1000)).toEqual({ messages: msgs, shortened: 0 })
+ })
+
+ it('a group keeps the person\'s line and cuts the speaker before, even when that one is last', () => {
+ const msgs = [m('system', 's'), m('user', 'go on'), m('user', '[a] ' + 'x'.repeat(80_000))]
+ const out = shortenLongTurns(msgs, 4000, (x) => x.content.includes('go on'))
+ expect(out.shortened).toBe(1)
+ expect(out.messages[1].content).toBe('go on')
+ expect(out.messages[2].content.startsWith('[a] xxx')).toBe(true)
+ expect(estimateMessageTokens(out.messages as never)).toBeLessThanOrEqual(4000)
+ })
+
+ it('never cuts the system prompt or the message being answered', () => {
+ const big = 'x'.repeat(40_000)
+ const msgs = [m('system', big), m('user', big), m('user', big)]
+ const out = shortenLongTurns(msgs, 12_000)
+ expect(out.shortened).toBe(1)
+ expect(out.messages[0].content).toBe(big)
+ expect(out.messages[2].content).toBe(big)
+ expect(out.messages[1].content.length).toBeLessThan(big.length)
+ })
+
+ it('cuts the longest turn first and only as far as needed', () => {
+ const msgs = [m('system', 's'), m('user', 'y'.repeat(4000)), m('user', 'x'.repeat(80_000)), m('user', 'go')]
+ const out = shortenLongTurns(msgs, 6000)
+ expect(out.shortened).toBe(1)
+ expect(out.messages[1].content).toBe('y'.repeat(4000))
+ expect(estimateMessageTokens(out.messages as never)).toBeLessThanOrEqual(6000)
+ expect(estimateMessageTokens(out.messages as never)).toBeGreaterThan(5000)
+ })
+})
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index c36463ee..9b19f4be 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -28,7 +28,7 @@ import { isSearchStopped, waitForSlotOrStop } from "../lib/slot-wait"
import { sourcesFromChunks } from "../lib/rag-sources"
import { buildRagSuffix, RETRIEVAL_FAILED_MESSAGE } from "../lib/rag-prompt"
import { buildTurnContext, withTurnContext } from "../lib/turn-context"
-import { getChatWindowTokens, capMessageCount, compactMessages, compactMessagesWithCount, estimateMessageTokens } from "../lib/context-compaction"
+import { getChatWindowTokens, capMessageCount, compactMessages, compactMessagesWithCount, estimateMessageTokens, shortenLongTurns } from "../lib/context-compaction"
import { contextOverflowOf, shrunkSendWindow } from "./codex/context-overflow"
import { applyChatSendBudget, chatBudgetApplies, sendBudgetWouldTrim } from "../lib/chat-send-budget"
import { sendsToALanBackend } from "../lib/lan-openai-slot"
@@ -218,11 +218,22 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
answerTokens: settings.maxTokens,
notice: 'chat',
})
- let messages = sent.messages
+ // Dropping older turns never touches the newest ones, and in a round the
+ // newest is the speaker before this one. One very long answer there filled
+ // a small window alone and the engine refused every later speaker of the
+ // round (T1 2026-10-29). It goes out shortened, head and tail kept.
+ // Kept whole: the person's newest line, the one the round answers. The
+ // trim notice may sit in front of or behind it, so it is found as a part.
+ const personLine = [...conv.messages].reverse().find((m) => m.role === 'user')?.content.trim() ?? ''
+ const keepPersonLine = (m: { role: string; content: string }) => !!personLine && m.role === 'user' && m.content.includes(personLine)
+ const fitted = sent.budget !== null ? shortenLongTurns(sent.messages, sent.budget, keepPersonLine) : { messages: sent.messages, shortened: 0 }
+ let messages = fitted.messages
// Said in the chat, next to this answer: older turns did not go out.
let dropped = full.length - counted.length + sent.droppedMessages
+ let shortened = fitted.shortened
const noteTrim = () => useChatStore.getState().updateMessageHistoryTrim(
- convId, assistantMessage.id, dropped > 0 ? { dropped, window: modelWindow } : null,
+ convId, assistantMessage.id,
+ dropped > 0 || shortened > 0 ? { dropped, window: modelWindow, ...(shortened ? { shortened } : {}) } : null,
)
noteTrim()
@@ -306,11 +317,14 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
type Wire = Parameters<typeof estimateMessageTokens>[0]
const size = estimateMessageTokens(messages as unknown as Wire)
const next = shrunkSendWindow(size, overflow, size)
- const cut = next !== null ? compactMessagesWithCount(messages as unknown as Wire, next, { notice: 'chat' }) : null
- if (!cut || cut.messages.length >= messages.length) throw err
- log.info('chat.group_context_overflow_retry', { sent: size, next, window: overflow.window, promptTokens: overflow.promptTokens, kept: cut.messages.length })
- messages = cut.messages as unknown as typeof messages
+ if (next === null) throw err
+ const cut = compactMessagesWithCount(messages as unknown as Wire, next, { notice: 'chat' })
+ const fit = shortenLongTurns(cut.messages as unknown as typeof messages, next, keepPersonLine)
+ if (cut.messages.length >= messages.length && !fit.shortened) throw err
+ log.info('chat.group_context_overflow_retry', { sent: size, next, window: overflow.window, promptTokens: overflow.promptTokens, kept: cut.messages.length, shortened: fit.shortened })
+ messages = fit.messages
dropped += cut.dropped
+ shortened += fit.shortened
noteTrim()
yield* provider.chatStream(modelId, messages, streamOpts)
}
@@ -409,16 +423,14 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
assistantMessage.id,
refusal ?? `Error from ${model}: ${errorText(err) || 'Connection failed'}`,
)
- // The kind of the failure as a field, for a reader that draws its own
- // error box (lib/message-error.ts). The sentence above replaces the
- // whole bubble, so none of it is answer text.
- if (!refusal) {
- useChatStore.getState().updateMessageError(
- convId,
- assistantMessage.id,
- messageErrorFor(err, { cloud: getProviderIdFromModel(model) === 'lu-cloud' }, ''),
- )
- }
+ // The failure as a field (lib/message-error.ts), a refusal too: the
+ // sentence is not answer text, and groupHistory sends none of it on
+ // (T1 2026-10-29: it reached the next speaker as this one's answer).
+ useChatStore.getState().updateMessageError(
+ convId,
+ assistantMessage.id,
+ messageErrorFor(err, { cloud: getProviderIdFromModel(model) === 'lu-cloud' }, ''),
+ )
}
}
}
diff --git a/src/lib/__tests__/history-trim-note.test.ts b/src/lib/__tests__/history-trim-note.test.ts
index 0394ea54..9f17898b 100644
--- a/src/lib/__tests__/history-trim-note.test.ts
+++ b/src/lib/__tests__/history-trim-note.test.ts
@@ -9,6 +9,12 @@ describe('historyTrimNote', () => {
expect(historyTrimNote({ dropped: 1, window: 8192 }))
.toBe('1 earlier message was not sent: it no longer fits its 8K context. The chat itself keeps it.')
})
+ it('says a long message went out shortened (T1 2026-10-29)', () => {
+ expect(historyTrimNote({ dropped: 0, window: 16384, shortened: 1 }, 'coder15'))
+ .toBe('1 long message was sent shortened to coder15 to fit its 16K context. The chat itself keeps it whole.')
+ expect(historyTrimNote({ dropped: 2, window: 16384, shortened: 2 }))
+ .toBe('2 earlier messages were not sent: they no longer fit its 16K context. The chat itself keeps them. 2 long messages were sent shortened.')
+ })
it('never an agent word', () => {
expect(historyTrimNote({ dropped: 3, window: 0 })).not.toMatch(/task|file|re-read/)
})
diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.ts
index aa582790..99936816 100644
--- a/src/lib/context-compaction.ts
+++ b/src/lib/context-compaction.ts
@@ -505,3 +505,51 @@ export function compactMessagesWithCount(
dropped: Math.max(0, droppedCount),
}
}
+
+/** The least a shortened turn keeps, in tokens: enough for its start and its end. */
+const SHORTENED_TURN_FLOOR = 256
+
+/**
+ * Shorten the longest turns until the payload fits `maxTokens`, keeping the
+ * head and the tail of each. Never the system prompt (index 0), and never the
+ * message being answered: by default the last one, or whatever `isKept` names.
+ * A group round passes `isKept`, because there the last message is usually the
+ * speaker before this one, and that is exactly the turn that may be too long.
+ *
+ * compactMessages only drops whole older messages and always keeps the newest
+ * KEEP_RECENT, so one very long answer inside that window rode along whole. In
+ * a group round that is the speaker before this one: an 82K-character answer
+ * against a 16K model and every later speaker of the round was refused by the
+ * engine (T1 2026-10-29, GH #201 follow-up). The person's history keeps the
+ * full text; only this request carries the shortened copy.
+ */
+export function shortenLongTurns<T extends { role: string; content: string }>(
+ messages: T[],
+ maxTokens: number,
+ isKept: (m: T, index: number) => boolean = (_m, i) => i === messages.length - 1,
+): { messages: T[]; shortened: number } {
+ const size = (m: T) => estimateMessageTokens([m as unknown as OllamaChatMessage])
+ let total = estimateMessageTokens(messages as unknown as OllamaChatMessage[])
+ if (total <= maxTokens) return { messages, shortened: 0 }
+ const out = [...messages]
+ const touched = new Set<number>()
+ const first = out[0]?.role === 'system' ? 1 : 0
+ for (let round = 0; round < out.length && total > maxTokens; round++) {
+ let at = -1
+ let largest = SHORTENED_TURN_FLOOR
+ for (let i = first; i < out.length; i++) {
+ if (isKept(messages[i], i)) continue
+ const t = size(out[i])
+ if (t > largest) { largest = t; at = i }
+ }
+ if (at < 0) break
+ const keep = Math.max(SHORTENED_TURN_FLOOR, largest - (total - maxTokens) - 32)
+ const text = out[at].content
+ const chars = Math.max(200, Math.floor((text.length * keep) / largest) - 40)
+ if (chars >= text.length) break
+ out[at] = { ...out[at], content: truncateToolResult(text, chars) }
+ touched.add(at)
+ total = estimateMessageTokens(out as unknown as OllamaChatMessage[])
+ }
+ return touched.size ? { messages: out, shortened: touched.size } : { messages, shortened: 0 }
+}
diff --git a/src/lib/group-chat.ts b/src/lib/group-chat.ts
index d513436f..87a2a5dd 100644
--- a/src/lib/group-chat.ts
+++ b/src/lib/group-chat.ts
@@ -256,6 +256,11 @@ export function groupHistory(
): GroupWireMessage[] {
const self = speakerKey(model, speakers)
return messages
+ // A failed turn carries the app's sentence behind its answer (`error.at`,
+ // lib/message-error.ts). That sentence is not the speaker's: sent along,
+ // the next speaker read "This message is longer than the model can read"
+ // as what the one before it had said (T1 2026-10-29).
+ .map((m) => (m.error ? { ...m, content: m.content.slice(0, Math.max(0, m.error.at)).trimEnd() } : m))
.filter((m) => m.role !== 'system' && m.content.trim() !== '')
.map((m) => {
const author = m.role === 'assistant' ? groupTurnAuthor(m, speakers, authors) : null
diff --git a/src/lib/history-trim-note.ts b/src/lib/history-trim-note.ts
index bdd8a751..f635d8b4 100644
--- a/src/lib/history-trim-note.ts
+++ b/src/lib/history-trim-note.ts
@@ -3,11 +3,20 @@
// agent's words, and the person found out from a token counter.
import { formatContextWindow } from './formatters'
-/** "12 earlier messages were not sent to Baron: they no longer fit its 256K context." */
-export function historyTrimNote(trim: { dropped: number; window: number }, speaker?: string): string {
- const what = trim.dropped === 1 ? '1 earlier message was' : `${trim.dropped} earlier messages were`
+/**
+ * "12 earlier messages were not sent to Baron: they no longer fit its 256K context."
+ * A long turn that went out shortened (head and tail) is said as well.
+ */
+export function historyTrimNote(trim: { dropped: number; window: number; shortened?: number }, speaker?: string): string {
const who = speaker ? ` to ${speaker}` : ''
const fit = trim.window > 0 ? `its ${formatContextWindow(trim.window)} context` : 'its context'
+ const shortened = trim.shortened ?? 0
+ const long = shortened === 1 ? '1 long message was' : `${shortened} long messages were`
+ if (!trim.dropped) {
+ return `${long} sent shortened${who} to fit ${fit}. The chat itself keeps ${shortened === 1 ? 'it' : 'them'} whole.`
+ }
+ const what = trim.dropped === 1 ? '1 earlier message was' : `${trim.dropped} earlier messages were`
const rest = trim.dropped === 1 ? `it no longer fits ${fit}. The chat itself keeps it.` : `they no longer fit ${fit}. The chat itself keeps them.`
- return `${what} not sent${who}: ${rest}`
+ const also = shortened ? ` ${long} sent shortened.` : ''
+ return `${what} not sent${who}: ${rest}${also}`
}
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 71a3d9ca..1813af49 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -901,7 +901,7 @@ export const useChatStore = create<ChatState>()(
...c,
messages: c.messages.map((m) => {
if (m.id !== messageId) return m
- if (trim && trim.dropped > 0) return { ...m, historyTrim: trim }
+ if (trim && (trim.dropped > 0 || (trim.shortened ?? 0) > 0)) return { ...m, historyTrim: trim }
if (!m.historyTrim) return m
const next = { ...m }
delete next.historyTrim
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 41a899b5..af217faf 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -137,7 +137,7 @@ export interface Message {
/** GH #201: the request behind this answer left out `dropped` older
* messages to fit `window` tokens. The chat says so next to the answer.
* Absent when the whole conversation went out. */
- historyTrim?: { dropped: number; window: number }
+ historyTrim?: { dropped: number; window: number; shortened?: number }
timestamp: number
images?: ImageAttachment[]
/** Files attached to this user message. `content` already carries their