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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): the trim notice stops planting a system message mid conversation
purple63e584893638
diff --git a/src/api/__tests__/context-compaction.test.ts b/src/api/__tests__/context-compaction.test.tsindex 5ad4c489..d2d5de28 100644--- a/src/api/__tests__/context-compaction.test.ts+++ b/src/api/__tests__/context-compaction.test.ts@@ -201,8 +201,12 @@ describe('compactMessages', () => {const result = compactMessages(messages, 120)// Real system prompt stays first.expect(result[0].content).toBe('sys')- // A trim notice is present (not a "[Previous conversation summary]").- expect(result.some((m) => m.role === 'system' && m.content.includes('trimmed to fit'))).toBe(true)+ // A trim notice is present (not a "[Previous conversation summary]") and+ // it rides inside user material: a system message mid conversation makes+ // strict Jinja templates raise "System message must be at the beginning"+ // (Discord #bug-reports 2026-08-21).+ expect(result.some((m) => m.role === 'user' && m.content.includes('trimmed to fit'))).toBe(true)+ expect(result.some((m, i) => m.role === 'system' && i > 0)).toBe(false)// Newest message preserved verbatim.expect(result[result.length - 1].content).toBe('latest')})@@ -282,7 +286,8 @@ describe('compactMessages — oversized tool results', () => {})),]const result = compactMessages(messages, 120)- const notice = result.find((m) => m.role === 'system' && m.content.includes('trimmed to fit'))+ // The notice rides user material since the Jinja fix, never role:system.+ const notice = result.find((m) => m.role === 'user' && m.content.includes('trimmed to fit'))expect(notice).toBeDefined()// The old wording ("Re-read any file you still need with file_read.")// actively FED the re-read loop.diff --git a/src/lib/__tests__/compaction-keeps-progress.test.ts b/src/lib/__tests__/compaction-keeps-progress.test.tsindex ecb5d161..609c2ad1 100644--- a/src/lib/__tests__/compaction-keeps-progress.test.ts+++ b/src/lib/__tests__/compaction-keeps-progress.test.ts@@ -57,11 +57,16 @@ const buildRun = (round: (t: string, n?: number) => Msg[]): Msg[] => [...PLAN_TOOLS.flatMap((t) => round(t)),]+// The notice rides inside user material since the Jinja fix (a mid+// conversation system message crashed strict chat templates), so it is+// extracted by its block shape, wherever it sits.const noticeOf = (msgs: Msg[]): string => {- const n = msgs.find(- (m) => m.role === 'system' && typeof m.content === 'string' && m.content.startsWith('['),- )- return n && typeof n.content === 'string' ? n.content : ''+ for (const m of msgs) {+ if (typeof m.content !== 'string') continue+ const hit = m.content.match(/\[\d+ earlier messages? (?:was|were) trimmed to fit the context window\.[^\]]*\]/)+ if (hit) return hit[0]+ }+ return ''}describe('the trim notice carries the trail of what already ran', () => {diff --git a/src/lib/__tests__/compaction-system-position.test.ts b/src/lib/__tests__/compaction-system-position.test.tsnew file mode 100644index 00000000..b2f4e136--- /dev/null+++ b/src/lib/__tests__/compaction-system-position.test.ts@@ -0,0 +1,105 @@+/**+ * The trim notice was a role:'system' message pushed BETWEEN the pinned task+ * and the kept window, so every compaction planted a system message mid+ * conversation. Strict Jinja chat templates refuse exactly that; llama-server+ * and LM Studio render them with the template's own raise_exception, and the+ * run dies with "System message must be at the beginning".+ *+ * Reported on Discord #bug-reports (2026-08-21): platorius, "the problem is+ * only in LU. It has very often problems. When i use Unsloth Desktop, i can+ * copy paste the same prompts and no problem" (same prompts elsewhere are+ * fine because compaction only fires once the history is long), and+ * helpslowlydying's diagnosis of the crash, "the system instructions or+ * tools are being injected in the wrong order, causing the Jinja template+ * engine to crash with System message must be at the beginning".+ *+ * The notice now rides inside a user message (appended to the pinned task,+ * or prefixed to the first kept user turn, or as its own user turn when the+ * window starts with an assistant turn), so after compaction there is at+ * most ONE system message and it sits at index 0.+ *+ * Run: npx vitest run src/lib/__tests__/compaction-system-position.test.ts+ */+import { describe, it, expect } from 'vitest'+import { compactMessages } from '../context-compaction'++type Msg = Parameters<typeof compactMessages>[0][number]++const big = (n: number) => 'x'.repeat(n)++const round = (tool: string, resultSize = 1200): Msg[] => [+ { role: 'assistant', content: '', tool_calls: [{ function: { name: tool } }] } as unknown as Msg,+ { role: 'tool', content: big(resultSize) } as Msg,+]++const longRun = (): Msg[] => [+ { role: 'system', content: 'You are a helpful agent.' } as Msg,+ { role: 'user', content: 'Work through the plan.' } as Msg,+ ...['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].flatMap((t) => round(`tool_${t}`)),+]++const systemIndices = (msgs: Msg[]): number[] =>+ msgs.map((m, i) => (m.role === 'system' ? i : -1)).filter((i) => i >= 0)++const noticeCount = (msgs: Msg[]): number =>+ msgs.reduce((n, m) => {+ const c = typeof m.content === 'string' ? m.content : ''+ return n + (c.match(/\[\d+ earlier message/g)?.length ?? 0)+ }, 0)++describe('after compaction, system only ever sits at index 0', () => {+ it('a compacted run has exactly one system message and it is first', () => {+ const out = compactMessages(longRun(), 1500)+ expect(noticeCount(out)).toBe(1)+ expect(systemIndices(out)).toEqual([0])+ })++ it('a run without any system prompt gains none from compaction', () => {+ const out = compactMessages(longRun().slice(1), 1500)+ expect(noticeCount(out)).toBe(1)+ expect(systemIndices(out)).toEqual([])+ })++ it('the notice rides the pinned task instead of trailing it as system', () => {+ const out = compactMessages(longRun(), 1500)+ const task = out.find(+ (m) => m.role === 'user' && typeof m.content === 'string' && m.content.includes('Work through the plan.'),+ )+ expect(task).toBeTruthy()+ expect(task!.content).toMatch(/\[\d+ earlier messages? (?:was|were) trimmed to fit the context window\./)+ })++ it('without any user turn in history the notice becomes its own user turn, never system', () => {+ const noUser: Msg[] = [+ { role: 'system', content: 'sys' } as Msg,+ ...['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].flatMap((t) => round(`tool_${t}`)),+ ]+ const out = compactMessages(noUser, 1500)+ expect(systemIndices(out)).toEqual([0])+ const carrier = out.find(+ (m) => typeof m.content === 'string' && /\[\d+ earlier message/.test(m.content),+ )+ expect(carrier).toBeTruthy()+ expect(carrier!.role).toBe('user')+ })++ it('REGRESSION: compacting an already-compacted history does not stack notices', () => {+ const once = compactMessages(longRun(), 1500)+ const grown: Msg[] = [+ ...once,+ ...['i', 'j', 'k', 'l', 'm', 'n'].flatMap((t) => round(`tool_${t}`)),+ ]+ const twice = compactMessages(grown, 1500)+ expect(noticeCount(twice)).toBe(1)+ expect(systemIndices(twice)).toEqual([0])+ })++ it('NEGATIVE CONTROL: within budget nothing is added or moved', () => {+ const short: Msg[] = [+ { role: 'system', content: 'sys' } as Msg,+ { role: 'user', content: 'hi' } as Msg,+ { role: 'assistant', content: 'hello' } as Msg,+ ]+ expect(compactMessages(short, 100000)).toEqual(short)+ })+})diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.tsindex b97f3083..bf28e954 100644--- a/src/lib/context-compaction.ts+++ b/src/lib/context-compaction.ts@@ -110,6 +110,20 @@ function toolNamesIn(msg: OllamaChatMessage): string[] {return out}+/**+ * The trim notice block, wherever it rides. Kept as a factory because a+ * shared /g regex carries lastIndex state between .test and .replace calls.+ */+const trimNoticeRe = () =>+ /\s*\[\d+ earlier messages? (?:was|were) trimmed to fit the context window\.[^\]]*\]\s*/g++/** Remove an earlier trim notice from a message body, so repeated compaction+ * rounds never stack notices inside the pinned task or the kept window. */+export function stripTrimNotice(text: string): string {+ if (!trimNoticeRe().test(text)) return text+ return text.replace(trimNoticeRe(), '\n\n').replace(/\n{3,}/g, '\n\n').trim()+}+/*** True for a message that is a tool RESULT — either the native `tool` role or* a Hermes `<tool_response>` carried on a user message. Used to trim a leading@@ -148,9 +162,15 @@ export function compactMessages(// Already within budgetif (currentTokens <= maxTokens) return messages- // Separate system prompt (always kept)+ // Separate system prompt (always kept). A stray system message deeper in+ // the history that is only an old trim notice is dropped outright here:+ // strict Jinja chat templates raise on any mid-conversation system message+ // ("System message must be at the beginning", Discord #bug-reports+ // 2026-08-21), so one may never survive a compaction round.const systemMsg = messages[0]?.role === 'system' ? messages[0] : null- const nonSystem = systemMsg ? messages.slice(1) : [...messages]+ const nonSystem = (systemMsg ? messages.slice(1) : [...messages]).filter(+ (m) => !(m.role === 'system' && typeof m.content === 'string' && trimNoticeRe().test(m.content)),+ )// If we have fewer messages than KEEP_RECENT, can't compact furtherif (nonSystem.length <= KEEP_RECENT) return messages@@ -178,14 +198,20 @@ export function compactMessages(// results imply instead of what was asked. Keep the first user message// (capped) out of the drop zone, alongside the system prompt.const firstUserIdx = capped.findIndex((m) => m.role === 'user')- const pinnedTask =+ // Strip an earlier round's trim notice BEFORE capping, so the notice this+ // round appends below never stacks and never gets sliced apart by the cap.+ const rawTask =firstUserIdx >= 0 && typeof capped[firstUserIdx].content === 'string'+ ? stripTrimNotice(capped[firstUserIdx].content)+ : null+ const pinnedTask =+ rawTask !== null? {...capped[firstUserIdx],content:- capped[firstUserIdx].content.length > PINNED_TASK_MAX_CHARS- ? truncateToolResult(capped[firstUserIdx].content, PINNED_TASK_MAX_CHARS)- : capped[firstUserIdx].content,+ rawTask.length > PINNED_TASK_MAX_CHARS+ ? truncateToolResult(rawTask, PINNED_TASK_MAX_CHARS)+ : rawTask,}: nullconst pinnedTokens = pinnedTask ? estimateMessageTokens([pinnedTask]) : 0@@ -216,9 +242,7 @@ export function compactMessages(const droppedCount = capped.length - kept.length - (pinNeeded ? 1 : 0)const compacted: OllamaChatMessage[] = []if (systemMsg) compacted.push(systemMsg)- if (pinNeeded && pinnedTask) {- compacted.push(pinnedTask)- }+ let notice: string | null = nullif (droppedCount > 0) {// What was dropped is exactly the record of the work already done, while// the pin keeps the instruction alive forever. Measured on the installed@@ -244,10 +268,29 @@ export function compactMessages(// with file_read.") actively FED a re-read loop — every iteration the// model was told to read again what it had just read. Keep the honest// recovery path but make it single-shot and anti-repeat.- compacted.push({- role: 'system',- content: `[${droppedCount} earlier message${droppedCount === 1 ? '' : 's'} were trimmed to fit the context window. The original task above still stands. Results you already saw still hold.${doneLine} If a detail is genuinely missing, re-read that specific file once; never repeat a call that already ran.]`,- })+ notice = `[${droppedCount} earlier message${droppedCount === 1 ? ' was' : 's were'} trimmed to fit the context window. The original task still stands. Results you already saw still hold.${doneLine} If a detail is genuinely missing, re-read that specific file once; never repeat a call that already ran.]`+ }++ // The notice used to be its own role:'system' message pushed right here,+ // between the pin and the window — a system message mid conversation, which+ // strict Jinja chat templates refuse with "System message must be at the+ // beginning" (platorius, Discord #bug-reports 2026-08-21: "the problem is+ // only in LU", same prompts fine elsewhere because compaction only fires+ // once the history is long). It now rides inside user material: appended to+ // the pinned task, else prefixed to the first kept user turn, else as its+ // own user turn. After compaction, system only ever sits at index 0.+ if (pinNeeded && pinnedTask) {+ compacted.push(+ notice ? { ...pinnedTask, content: `${pinnedTask.content}\n\n${notice}` } : pinnedTask,+ )+ notice = null+ }+ if (notice) {+ if (kept[0]?.role === 'user' && typeof kept[0].content === 'string') {+ kept[0] = { ...kept[0], content: `${notice}\n\n${stripTrimNotice(kept[0].content)}` }+ } else {+ compacted.push({ role: 'user', content: notice })+ }}compacted.push(...kept)return compacted