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 system prompt reaches the engine first, or not at all
David1bfcf5dbce91
diff --git a/src/api/providers/__tests__/system-message-first.test.ts b/src/api/providers/__tests__/system-message-first.test.tsnew file mode 100644index 00000000..c4a02a1c--- /dev/null+++ b/src/api/providers/__tests__/system-message-first.test.ts@@ -0,0 +1,260 @@+/**+ * Bug B3 (2.6.7): "System message must be at the beginning".+ *+ * Discord #bug-reports, 2026-08-21. helpslowlydying diagnosed it: "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". platorius, who was hitting it: "the problem is only in LU",+ * with the same model and the same prompts working in other frontends.+ *+ * The local engines (bundled llama-server, LM Studio, llama.cpp, Ollama)+ * render the model's OWN Jinja chat template, and the strict ones raise on a+ * system message anywhere but index 0, and several also raise on a second+ * system message. The request dies before the model sees it, so the turn+ * produces nothing at all.+ *+ * 2.6.6 fixed one producer (the compaction trim notice, proven in+ * lib/__tests__/compaction-system-position.test.ts). This file covers the+ * central guarantee instead of one producer: whatever the dozen builders in+ * the app hand over, the array that reaches the wire has at most one system+ * message and it is first.+ *+ * `jinjaGate` below is a SIMULATION of the template guard, not a real+ * llama-server. It reproduces the two conditions the shipped Qwen, Mistral and+ * ChatML templates check, so a payload that passes it here is a payload those+ * templates render. A real-engine proof belongs to the counter-check agent.+ *+ * Run: npx vitest run src/api/providers/__tests__/system-message-first.test.ts+ */+import { describe, it, expect, vi, afterEach } from 'vitest'+import { normalizeSystemMessages } from '../normalize-system'+import { groupHistory } from '../../../lib/group-chat'+import type { Message } from '../../../types/chat'++// ── The guard the shipped chat templates actually contain ──────++/** Throws the template's own wording when the payload breaks its contract. */+function jinjaGate(messages: { role: string }[]): void {+ const systems = messages.map((m, i) => (m.role === 'system' ? i : -1)).filter((i) => i >= 0)+ if (systems.length > 1 || (systems.length === 1 && systems[0] !== 0)) {+ throw new Error('System message must be at the beginning')+ }+}++// The history the reporter had: an agent turn with tools, and a second system+// block injected behind the first user message. This is what dies today.+const CRASHING_HISTORY = [+ { role: 'system', content: 'You are a helpful agent.' },+ { role: 'user', content: 'List the files in my project.' },+ { role: 'system', content: 'Available tools: file_list, file_read.' },+ { role: 'assistant', content: '', tool_calls: [{ function: { name: 'file_list', arguments: {} } }] },+ { role: 'tool', content: 'src, docs, README.md' },+ { role: 'user', content: 'And now read the README.' },+]++// ── Unit: the normalizer itself ────────────────────────────────++describe('normalizeSystemMessages', () => {+ it('pulls a mid-conversation system block to the front and merges it', () => {+ const out = normalizeSystemMessages(CRASHING_HISTORY)+ expect(out.filter((m) => m.role === 'system')).toHaveLength(1)+ expect(out[0].role).toBe('system')+ expect(() => jinjaGate(out)).not.toThrow()+ })++ it('keeps every instruction, in the order the builders put them', () => {+ const out = normalizeSystemMessages(CRASHING_HISTORY)+ expect(out[0].content).toBe(+ 'You are a helpful agent.\n\nAvailable tools: file_list, file_read.',+ )+ })++ it('drops nothing else and moves nothing else', () => {+ const out = normalizeSystemMessages(CRASHING_HISTORY)+ expect(out.slice(1)).toEqual(CRASHING_HISTORY.filter((m) => m.role !== 'system'))+ })++ it('two system messages at the front become one', () => {+ const out = normalizeSystemMessages([+ { role: 'system', content: 'tool catalog' },+ { role: 'system', content: 'persona' },+ { role: 'user', content: 'hi' },+ ])+ expect(out).toEqual([+ { role: 'system', content: 'tool catalog\n\npersona' },+ { role: 'user', content: 'hi' },+ ])+ })++ it('an empty stray system message is removed, not merged as blank text', () => {+ const out = normalizeSystemMessages([+ { role: 'system', content: 'persona' },+ { role: 'user', content: 'hi' },+ { role: 'system', content: ' ' },+ ])+ expect(out).toEqual([+ { role: 'system', content: 'persona' },+ { role: 'user', content: 'hi' },+ ])+ })++ it('a payload whose ONLY system parts are empty loses the system message entirely', () => {+ const out = normalizeSystemMessages([+ { role: 'user', content: 'hi' },+ { role: 'system', content: '' },+ ])+ expect(out).toEqual([{ role: 'user', content: 'hi' }])+ })++ it('fields other than content survive the merge', () => {+ const out = normalizeSystemMessages([+ { role: 'system', content: 'a', marker: 1 } as { role: string; content: string; marker: number },+ { role: 'user', content: 'hi' },+ { role: 'system', content: 'b' } as { role: string; content: string; marker?: number },+ ])+ expect(out[0]).toEqual({ role: 'system', content: 'a\n\nb', marker: 1 })+ })++ it('NEGATIVE CONTROL: a correct payload is returned BY REFERENCE, untouched', () => {+ // A new array on every request would be a new prompt prefix on every+ // request, which is a cold upstream cache and a full re-bill.+ const fine = [+ { role: 'system', content: 'persona' },+ { role: 'user', content: 'hi' },+ { role: 'assistant', content: 'hello' },+ ]+ expect(normalizeSystemMessages(fine)).toBe(fine)+ })++ it('NEGATIVE CONTROL: a payload with no system message at all is returned by reference', () => {+ const none = [{ role: 'user', content: 'hi' }]+ expect(normalizeSystemMessages(none)).toBe(none)+ })++ it('NEGATIVE CONTROL: the raw history trips the template guard', () => {+ // Without this the tests above prove nothing: they would pass on a payload+ // that was never broken in the first place.+ expect(() => jinjaGate(CRASHING_HISTORY)).toThrow('System message must be at the beginning')+ })+})++// ── The wire: what the local engines actually receive ──────────++const backendMock = (capture: (url: string, init: any) => Response) => ({+ isTauri: () => false,+ localFetch: vi.fn(async (url: string, init: any) => capture(url, init)),+ localFetchStream: vi.fn(async (url: string, init: any) => capture(url, init)),+ ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,+ backendCall: vi.fn(),+ isPrivateOrLanHost: () => true,+ isDirectFetchAllowed: () => true,+ hostnameOf: (url: string) => new URL(url).hostname,+ ensureProxyAllowsHost: vi.fn(),+})++afterEach(() => {+ vi.doUnmock('../../backend')+ vi.doUnmock('../../builtin-ensure')+ vi.resetModules()+})++describe('the body that leaves for a local engine', () => {+ it('Ollama chatStream sends one system message, first', async () => {+ vi.resetModules()+ let sent: any = null+ vi.doMock('../../backend', () =>+ backendMock((_url, init) => {+ sent = JSON.parse(init.body)+ return new Response('{"message":{"content":"ok"},"done":true}\n')+ }),+ )+ const { OllamaProvider } = await import('../ollama-provider')+ const p = new OllamaProvider({+ id: 'ollama', name: 'Ollama', enabled: true,+ baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,+ })+ for await (const chunk of p.chatStream('qwen3:8b', CRASHING_HISTORY as any)) { void chunk }+ expect(sent.messages.filter((m: any) => m.role === 'system')).toHaveLength(1)+ expect(sent.messages[0].role).toBe('system')+ expect(() => jinjaGate(sent.messages)).not.toThrow()+ })++ it('Ollama chatWithTools sends one system message, first', async () => {+ vi.resetModules()+ let sent: any = null+ vi.doMock('../../backend', () =>+ backendMock((_url, init) => {+ sent = JSON.parse(init.body)+ return new Response(JSON.stringify({ message: { content: 'ok' } }), {+ headers: { 'Content-Type': 'application/json' },+ })+ }),+ )+ const { OllamaProvider } = await import('../ollama-provider')+ const p = new OllamaProvider({+ id: 'ollama', name: 'Ollama', enabled: true,+ baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,+ })+ await p.chatWithTools('qwen3:8b', CRASHING_HISTORY as any, [])+ expect(() => jinjaGate(sent.messages)).not.toThrow()+ expect(sent.messages[0].content).toContain('Available tools: file_list, file_read.')+ })++ it('the built-in engine (OpenAI-compatible) gets one system message, first', async () => {+ vi.resetModules()+ let sent: any = null+ vi.doMock('../../backend', () =>+ backendMock((url, init) => {+ if (url.includes('/chat/completions')) {+ sent = JSON.parse(init.body)+ return new Response(+ JSON.stringify({ choices: [{ message: { content: 'ok' } }] }),+ { headers: { 'Content-Type': 'application/json' } },+ )+ }+ return new Response('{}', { status: 404 })+ }),+ )+ vi.doMock('../../builtin-ensure', () => ({+ ensureBuiltinEngineAlive: vi.fn(),+ explainDeadEngine: (e: unknown) => e,+ isManagedBuiltinSlot: () => true,+ }))+ const { OpenAIProvider } = await import('../openai-provider')+ const p = new OpenAIProvider({+ id: 'openai', name: 'Built-in Engine', enabled: true,+ baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', isLocal: true, managed: true,+ })+ await p.chatWithTools('qwen3-8b', CRASHING_HISTORY as any, [])+ expect(sent.messages.filter((m: any) => m.role === 'system')).toHaveLength(1)+ expect(sent.messages[0].role).toBe('system')+ expect(() => jinjaGate(sent.messages)).not.toThrow()+ })+})++// ── The producer this fix also closes at the source ────────────++describe('a stored app notice never becomes a chat turn', () => {+ const stored = [+ { id: '1', role: 'user', content: 'hi', timestamp: 1 },+ { id: '2', role: 'assistant', content: 'hello', timestamp: 2 },+ // What staged-apply.ts writes into the conversation. MessageList hides it,+ // useCodex and useAgentChat drop it, and plain chat used to send it.+ { id: '3', role: 'system', content: 'Applied staged change: src/a.ts', timestamp: 3, notice: 'info' },+ { id: '4', role: 'user', content: 'and now?', timestamp: 4 },+ ] as unknown as Message[]++ it('groupHistory drops it instead of putting it mid conversation', () => {+ const out = groupHistory(stored, 'qwen3:8b')+ expect(out.some((m) => m.role === 'system')).toBe(false)+ expect(out.map((m) => m.content)).toEqual(['hi', 'hello', 'and now?'])+ })++ it('and the group payload as a whole passes the template guard', () => {+ const payload = [+ { role: 'system', content: 'group prompt' },+ ...groupHistory(stored, 'qwen3:8b'),+ ]+ expect(() => jinjaGate(payload)).not.toThrow()+ })+})diff --git a/src/api/providers/normalize-system.ts b/src/api/providers/normalize-system.tsnew file mode 100644index 00000000..0aad56d2--- /dev/null+++ b/src/api/providers/normalize-system.ts@@ -0,0 +1,93 @@+/**+ * One system message, and it sits first. Enforced on the last piece of code+ * every request passes through, right before the body is serialized.+ *+ * Why this exists (bug B3, 2.6.7). Discord #bug-reports 2026-08-21:+ * helpslowlydying diagnosed it as "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", and platorius, who was hitting it,+ * added "the problem is only in LU" with the same model and the same prompts+ * working in other frontends.+ *+ * That is exactly what a strict Jinja chat template does. llama.cpp+ * (llama-server, the built-in engine) and LM Studio render the model's own+ * template, and the Qwen, Mistral and ChatML style templates shipped with many+ * GGUFs contain a literal+ *+ * {{ raise_exception('System message must be at the beginning') }}+ *+ * guard that fires on ANY message with role "system" at an index other than 0,+ * and several of them fire on a SECOND system message even when both sit at the+ * front. The request never reaches the model, so nothing partial streams: the+ * turn just dies.+ *+ * 2.6.6 fixed one producer (the compaction trim notice, see+ * lib/__tests__/compaction-system-position.test.ts). This is the other half of+ * the job: instead of auditing every one of the dozen places that assemble a+ * message array, the invariant is checked once on the way out. A payload that+ * already satisfies it is returned BY REFERENCE, untouched, so the upstream+ * prefix cache still matches byte for byte and the normal path pays nothing.+ *+ * Merging rather than dropping is deliberate. Every system message in the array+ * is an instruction someone meant the model to follow (a persona, a tool+ * catalog, a memory block, an injected context header). Dropping the late ones+ * would silently disarm a feature; merging them into the leading system message+ * in their original order keeps every instruction and keeps the order the+ * builders intended.+ */++/** The shape this works on. Deliberately looser than ChatMessage so the same+ * function serves the wire types of all providers. */+export interface RoledMessage {+ role: string+ content?: unknown+}++/**+ * Pull every system part to the front and merge it into one system message.+ *+ * Returns the SAME array reference when the payload is already correct, which+ * is the overwhelmingly common case: zero system messages, or exactly one at+ * index 0. Only a payload that would have crashed a strict template is rebuilt.+ *+ * Notes on the merge:+ * - Content order follows the array order, so the leading system prompt stays+ * the leading text and a later injection is appended behind it.+ * - Empty and whitespace-only system parts are dropped. If that leaves+ * nothing, the system message disappears entirely instead of going out as+ * an empty one, which some templates also refuse.+ * - Fields other than `content` are taken from the FIRST system message+ * (that is the one carrying the real prompt), so nothing a provider adds+ * to its own wire shape is lost.+ * - Non-system messages keep their order and their identity untouched.+ */+export function normalizeSystemMessages<T extends RoledMessage>(messages: T[]): T[] {+ let firstSystem = -1+ let systemCount = 0+ for (let i = 0; i < messages.length; i++) {+ if (messages[i]?.role === 'system') {+ if (firstSystem < 0) firstSystem = i+ systemCount+++ }+ }++ // Already legal. Hand back the very same array: a new array here would be a+ // new JSON body on every single request, and on the cloud side a moved+ // prefix is a cold cache and a full re-bill.+ if (systemCount === 0) return messages+ if (systemCount === 1 && firstSystem === 0) return messages++ const parts: string[] = []+ const rest: T[] = []+ for (const m of messages) {+ if (m?.role === 'system') {+ const text = typeof m.content === 'string' ? m.content.trim() : ''+ if (text) parts.push(text)+ } else {+ rest.push(m)+ }+ }++ if (parts.length === 0) return rest+ return [{ ...messages[firstSystem], content: parts.join('\n\n') } as T, ...rest]+}diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex 15bf2752..64d69514 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -13,6 +13,7 @@ import { ProviderError } from './types'import { localFetch, localFetchStream, ollamaUrl } from '../backend'import { parseNDJSONStream } from '../stream'import { repairToolCallArgs, extractToolCallsFromContent } from '../../lib/tool-call-repair'+import { normalizeSystemMessages } from './normalize-system'// ── Ollama-specific types ──────────────────────────────────────@@ -78,7 +79,9 @@ export class OllamaProvider implements ProviderClient {messages: ChatMessage[],options?: ChatOptions,): AsyncGenerator<ChatStreamChunk> {- const ollamaMessages = messages.map(m => {+ // Bug B3: one system message, first, or Ollama's own template rendering+ // raises the same way llama.cpp's does. See providers/normalize-system.ts.+ const ollamaMessages = normalizeSystemMessages(messages).map(m => {const msg: Record<string, any> = { role: m.role, content: m.content }if (m.images?.length) msg.images = m.images.map(img => img.data)return msg@@ -185,7 +188,8 @@ export class OllamaProvider implements ProviderClient {tools: ToolDefinition[],options?: ChatOptions,): Promise<{ content: string; toolCalls: ToolCall[] }> {- const ollamaMessages = messages.map(m => {+ // Bug B3: same invariant as chatStream, see providers/normalize-system.ts.+ const ollamaMessages = normalizeSystemMessages(messages).map(m => {const msg: Record<string, any> = { role: m.role, content: m.content }if (m.tool_calls) msg.tool_calls = m.tool_callsif (m.images?.length) msg.images = m.images.map(img => img.data)diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 92e1627c..c3247016 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -20,6 +20,7 @@ import { signalCreditsExhausted } from '../../lib/credits-exhausted'import { parseRetryAfter } from '../../lib/http-status'import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost, backendCall } from '../backend'import { ensureBuiltinEngineAlive, explainDeadEngine, isManagedBuiltinSlot } from '../builtin-ensure'+import { normalizeSystemMessages } from './normalize-system'// Transport routing lives in the `useLocalProxy` getter (below) plus the shared// host helpers in backend.ts. A direct webview fetch only works for hosts the@@ -384,7 +385,11 @@ export class OpenAIProvider implements ProviderClient {): AsyncGenerator<ChatStreamChunk> {const body: Record<string, any> = {model,- messages: messages.map(m => this.toOpenAIMessage(m)),+ // Bug B3: one system message, first. The built-in engine and LM Studio+ // render the model's own Jinja template, which raises "System message+ // must be at the beginning" on anything else and kills the whole turn+ // before a byte streams. See providers/normalize-system.ts.+ messages: normalizeSystemMessages(messages).map(m => this.toOpenAIMessage(m)),stream: true,}@@ -548,7 +553,8 @@ export class OpenAIProvider implements ProviderClient {): Promise<{ content: string; toolCalls: ToolCall[]; promptEvalCount?: number; evalCount?: number; thinking?: string }> {const body: Record<string, any> = {model,- messages: messages.map(m => this.toOpenAIMessage(m)),+ // Bug B3: same invariant as chatStream, see providers/normalize-system.ts.+ messages: normalizeSystemMessages(messages).map(m => this.toOpenAIMessage(m)),stream: false,}diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 6c84ef8f..e0bf2017 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -525,10 +525,18 @@ export function useChat() {const messages = applyChatSendBudget(capMessageCount([...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),+ // Bug B3: a stored role:'system' message is an APP notice, never a+ // model turn. MessageList hides it, useCodex and useAgentChat both+ // drop it from their payloads, and staged-apply.ts writes one on the+ // promise that "it still never reaches the model". Plain chat was the+ // one path that did not filter, so such a message rode along at+ // whatever index it happened to sit at, and a strict Jinja template+ // answers a mid-conversation system message with "System message must+ // be at the beginning" instead of a reply....conv.messages- .filter((m) => m.content.trim() !== '')+ .filter((m) => m.role !== 'system' && m.content.trim() !== '').map((m) => ({- role: m.role as 'user' | 'assistant' | 'system' | 'tool',+ role: m.role as 'user' | 'assistant' | 'tool',content: m.role === 'user' && cavemanReminder? `${cavemanReminder}\n${m.content}`: m.content,diff --git a/src/lib/group-chat.ts b/src/lib/group-chat.tsindex 9074ebb6..fe5a219e 100644--- a/src/lib/group-chat.ts+++ b/src/lib/group-chat.ts@@ -54,10 +54,16 @@ export function stripImpersonatedSpeakers(text: string, otherModels: string[]):}/** The shared history as one model sees it: other speakers tagged, own turns- * clean, empty placeholders dropped. */+ * clean, empty placeholders and app notices dropped.+ *+ * Bug B3: role:'system' is an app notice here, not a turn. The caller puts the+ * group system prompt at index 0 itself, so letting a stored one through would+ * hand the engine a second system message somewhere in the middle, and a strict+ * Jinja chat template refuses that outright with "System message must be at the+ * beginning". */export function groupHistory(messages: Message[], model: string): GroupWireMessage[] {return messages- .filter((m) => m.content.trim() !== '')+ .filter((m) => m.role !== 'system' && m.content.trim() !== '').map((m) => ({role: m.role as GroupWireMessage['role'],content: