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): the message order now fits the template that has to render it

purplec18141e64004
diff --git a/src/api/__tests__/provider-ollama.test.ts b/src/api/__tests__/provider-ollama.test.ts
index 1e842811..6ebe5cae 100644
--- a/src/api/__tests__/provider-ollama.test.ts
+++ b/src/api/__tests__/provider-ollama.test.ts
@@ -697,13 +697,19 @@ describe('OllamaProvider', () => {
tool_calls: [{ function: { name: 'test', arguments: { x: 1 } } }],
}
+ // Bug B3 round 2: with a real tool contract in the request the native
+ // tool channel is kept untouched. Without one (tools: []) the model was
+ // never shown a tool contract at all, so a tool_calls field in the
+ // history is a shape the chat template has no branch for, and the
+ // contract in providers/normalize-system.ts carries it as prompt text
+ // instead. That case is proven in providers/__tests__/template-contract.
await provider.chatWithTools(
'llama3.1:8b',
[
{ role: 'user', content: 'test' },
toolCallMessage,
],
- [],
+ [{ type: 'function', function: { name: 'test', description: '', parameters: { type: 'object', properties: {}, required: [] } } }],
)
const body = JSON.parse(mockLocalFetch.mock.calls[0][1]?.body as string)
diff --git a/src/api/hermes-tool-calling.ts b/src/api/hermes-tool-calling.ts
index 13edf300..3e132768 100644
--- a/src/api/hermes-tool-calling.ts
+++ b/src/api/hermes-tool-calling.ts
@@ -168,3 +168,22 @@ export function stripToolCallTags(output: string): string {
export function hasToolCallTags(output: string): boolean {
return /<tool_call>/.test(output)
}
+
+// ── Build a Tool CALL as prompt text ────────────────────────────
+
+/**
+ * The other half of the prompt transport: the model's own call, written back
+ * into the history as text.
+ *
+ * On the native channel the call rides in `assistant.tool_calls` and the chat
+ * template renders it. A template that has no tool support renders nothing at
+ * all for that field, so the next turn shows the model a RESULT for a call it
+ * can no longer see. Same dialect as buildHermesToolResult, so a history that
+ * mixes the two reads as one conversation to the model.
+ */
+export function buildHermesToolCall(toolName: string, args: unknown): string {
+ const body = JSON.stringify({ name: String(toolName ?? ''), arguments: args ?? {} })
+ return `<tool_call>
+${neutralizeToolTags(body)}
+</tool_call>`
+}
diff --git a/src/api/providers/__tests__/template-contract.test.ts b/src/api/providers/__tests__/template-contract.test.ts
new file mode 100644
index 00000000..32cc6d3e
--- /dev/null
+++ b/src/api/providers/__tests__/template-contract.test.ts
@@ -0,0 +1,517 @@
+/**
+ * Bug B3, round 2 (2.6.7): the strict Jinja template, everything round 1
+ * missed.
+ *
+ * Round 1 put one system message at the front and stopped there. The
+ * counter-check then ran the shipped 2.6.7 build against a real strict
+ * template (mlabonne_gemma-3-4b-it-abliterated, whose Jinja calls
+ * raise_exception on every rule it checks) on the built-in engine, and killed
+ * it three ways:
+ *
+ * 1. Agent mode with tools. After the first tool result the wire carried
+ * [system, user, assistant, tool] and NO `tools` field, because the run
+ * was on the prompt transport. The template has no branch for a `tool`
+ * role. HTTP 400, the round died.
+ * 2. Plain chat. The chat tools are on by default, so an ordinary question
+ * that triggered web_search produced the same four roles and the same
+ * death, with Agent mode switched off.
+ * 3. Group chat. From round two the history holds two assistant messages in
+ * a row, one per speaker, and the template demands strict alternation.
+ * Both speakers died.
+ *
+ * The same payloads run on Hermes 3 (plain ChatML, no raise_exception), which
+ * is the proof that the shape is wrong for the template, not wrong in itself.
+ *
+ * `gemmaGate` below is a SIMULATION of that template's guard, extended from
+ * round 1's `jinjaGate` with the two rules the counter-check tripped: no
+ * `tool` role, and strict user/assistant alternation behind the system
+ * message. It is not a real llama-server; a real-engine proof belongs to the
+ * counter-check agent.
+ *
+ * Run: npx vitest run src/api/providers/__tests__/template-contract.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { applyTemplateContract } from '../normalize-system'
+import { groupHistory, groupSystemPrompt } from '../../../lib/group-chat'
+import { isTemplateRefusal, explainSendRefusal } from '../../../lib/template-refusal'
+import type { Message } from '../../../types/chat'
+
+// ── The guard Gemma 3 actually contains ────────────────────────
+
+/**
+ * Raises the way the shipped template does: a system message only at index 0,
+ * every later turn either user or assistant, and those two strictly
+ * alternating starting with user. Wording taken from the two templates the
+ * bug was reported against.
+ */
+function gemmaGate(messages: { role: string; content?: unknown }[]): void {
+ const lead = messages[0]?.role === 'system' ? 1 : 0
+ const body = messages.slice(lead)
+ if (body.some((m) => m.role === 'system')) {
+ throw new Error('System message must be at the beginning')
+ }
+ body.forEach((m, i) => {
+ const expected = i % 2 === 0 ? 'user' : 'assistant'
+ if (m.role !== expected) {
+ throw new Error('Conversation roles must alternate user/assistant/user/assistant/...')
+ }
+ })
+}
+
+const STRICT = { toolRole: 'text', alternate: true } as const
+const TOLERANT = { toolRole: 'native', alternate: false } as const
+
+// Weg 1 of the counter-check, copied from logs/wire-b3-12-agent-round2.json:
+// the agent's own history after one approved file_write, on the prompt
+// transport, with no `tools` field in the request.
+const AGENT_AFTER_A_TOOL = [
+ { role: 'system', content: 'You are a function calling AI model. <tools>...</tools>' },
+ { role: 'user', content: 'Create a file called notes.txt containing the word hello, then read it back.' },
+ {
+ role: 'assistant',
+ content: "Okay, let's start!",
+ tool_calls: [{ id: 'call_1', function: { name: 'file_write', arguments: { path: 'notes.txt', content: 'hello' } } }],
+ },
+ { role: 'tool', content: 'File saved: C:\\Users\\ddrob\\agent-workspace\\notes.txt', tool_call_id: 'call_1' },
+]
+
+// ── 1. The contract itself ─────────────────────────────────────
+
+describe('the template contract', () => {
+ it('NEGATIVE CONTROL: the payload that killed the real engine trips the guard', () => {
+ // Without this the rest proves nothing.
+ expect(() => gemmaGate(AGENT_AFTER_A_TOOL)).toThrow('Conversation roles must alternate')
+ })
+
+ it('carries a tool result as a user turn when the template has no tool role', () => {
+ const out = applyTemplateContract(AGENT_AFTER_A_TOOL, STRICT)
+ expect(out.some((m) => m.role === 'tool')).toBe(false)
+ expect(out[3].role).toBe('user')
+ expect(out[3].content).toContain('<tool_response>')
+ expect(out[3].content).toContain('File saved')
+ expect(() => gemmaGate(out)).not.toThrow()
+ })
+
+ it('and keeps the CALL with it, so the result is not an orphan', () => {
+ // The counter-check found a tool result whose call had vanished from the
+ // history. A result with no question in front of it is a mutilated
+ // conversation even on a template that renders it.
+ const out = applyTemplateContract(AGENT_AFTER_A_TOOL, STRICT)
+ expect(out[2].role).toBe('assistant')
+ expect(out[2].content).toContain("Okay, let's start!")
+ expect(out[2].content).toContain('<tool_call>')
+ expect(out[2].content).toContain('file_write')
+ expect((out[2] as { tool_calls?: unknown }).tool_calls).toBeUndefined()
+ })
+
+ it('names the tool in the result even when the result carries no id', () => {
+ const idless = [
+ { role: 'system', content: 's' },
+ { role: 'user', content: 'u' },
+ { role: 'assistant', content: '', tool_calls: [{ function: { name: 'web_search', arguments: { query: 'x' } } }] },
+ { role: 'tool', content: 'three results' },
+ ]
+ const out = applyTemplateContract(idless, STRICT)
+ expect(out[3].content).toContain('web_search')
+ })
+
+ it('merges two turns of the same role instead of dropping one', () => {
+ // Every consecutive pair in the wild is two things somebody said: a tool
+ // result and the steer that follows it, or two speakers in a group.
+ const out = applyTemplateContract(
+ [
+ { role: 'system', content: 's' },
+ { role: 'user', content: 'first' },
+ { role: 'user', content: 'second' },
+ { role: 'assistant', content: 'a' },
+ ],
+ STRICT,
+ )
+ expect(out.map((m) => m.content)).toEqual(['s', 'first\n\nsecond', 'a'])
+ expect(() => gemmaGate(out)).not.toThrow()
+ })
+
+ it('opens on a user turn even when the history starts with an assistant', () => {
+ const out = applyTemplateContract(
+ [
+ { role: 'system', content: 's' },
+ { role: 'assistant', content: 'I was here first' },
+ { role: 'user', content: 'hi' },
+ ],
+ STRICT,
+ )
+ expect(out[1].role).toBe('user')
+ expect(() => gemmaGate(out)).not.toThrow()
+ })
+
+ it('separates with a minimal turn when the contents cannot be merged', () => {
+ // A user turn carrying images has no string content to join, so a bridge
+ // is the only way to keep both turns AND the alternation.
+ const withImages = [
+ { role: 'user', content: 'look at this', images: [{ data: 'AAA', mimeType: 'image/png' }] },
+ { role: 'user', content: 42 as unknown as string },
+ ]
+ const out = applyTemplateContract(withImages, STRICT)
+ expect(out).toHaveLength(3)
+ expect(out.map((m) => m.role)).toEqual(['user', 'assistant', 'user'])
+ expect(() => gemmaGate(out)).not.toThrow()
+ })
+
+ it('keeps images when it merges two user turns', () => {
+ const out = applyTemplateContract(
+ [
+ { role: 'user', content: 'one', images: [{ data: 'AAA', mimeType: 'image/png' }] },
+ { role: 'user', content: 'two', images: [{ data: 'BBB', mimeType: 'image/png' }] },
+ ],
+ STRICT,
+ )
+ expect(out).toHaveLength(1)
+ expect(out[0].images).toEqual([
+ { data: 'AAA', mimeType: 'image/png' },
+ { data: 'BBB', mimeType: 'image/png' },
+ ])
+ })
+
+ it('NEGATIVE CONTROL: on the tolerant contract the native tool channel is untouched', () => {
+ // A cloud endpoint implements the protocol itself and needs the ids. This
+ // is what must NOT be rewritten, or DeepInfra answers 422 on every turn.
+ const out = applyTemplateContract(AGENT_AFTER_A_TOOL, TOLERANT)
+ expect(out).toBe(AGENT_AFTER_A_TOOL)
+ expect(out[3].role).toBe('tool')
+ expect(out[2].tool_calls).toHaveLength(1)
+ })
+
+ it('NEGATIVE CONTROL: a payload that already fits is returned BY REFERENCE', () => {
+ // A new array every request is a new prompt prefix 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' },
+ { role: 'user', content: 'again' },
+ ]
+ expect(applyTemplateContract(fine, STRICT)).toBe(fine)
+ })
+
+ it('NEGATIVE CONTROL: nothing but the tool channel and the order changes', () => {
+ const out = applyTemplateContract(AGENT_AFTER_A_TOOL, STRICT)
+ expect(out).toHaveLength(AGENT_AFTER_A_TOOL.length)
+ expect(out[0]).toBe(AGENT_AFTER_A_TOOL[0])
+ expect(out[1]).toBe(AGENT_AFTER_A_TOOL[1])
+ })
+})
+
+// ── 2. Which endpoint gets which contract ──────────────────────
+
+const backendMock = (capture: (url: string, init: any) => Response, opts?: { lan?: boolean }) => ({
+ 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: () => opts?.lan !== false,
+ // false so a cloud endpoint also goes through localFetch and can be captured
+ isDirectFetchAllowed: () => false,
+ hostnameOf: (url: string) => new URL(url).hostname,
+ ensureProxyAllowsHost: vi.fn(),
+})
+
+const okJson = (body: unknown) =>
+ new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' } })
+
+async function sendVia(
+ config: { baseUrl: string; isLocal: boolean; managed?: boolean },
+ tools: any[],
+ lan: boolean,
+): Promise<any> {
+ vi.resetModules()
+ let sent: any = null
+ vi.doMock('../../backend', () =>
+ backendMock((url, init) => {
+ if (url.includes('/chat/completions')) {
+ sent = JSON.parse(init.body)
+ return okJson({ choices: [{ message: { content: 'ok' } }] })
+ }
+ return new Response('{}', { status: 404 })
+ }, { lan }),
+ )
+ vi.doMock('../../builtin-ensure', () => ({
+ ensureBuiltinEngineAlive: vi.fn(),
+ explainDeadEngine: (e: unknown) => e,
+ isManagedBuiltinSlot: () => config.managed === true,
+ }))
+ const { OpenAIProvider } = await import('../openai-provider')
+ const p = new OpenAIProvider({
+ id: 'openai', name: 'test', enabled: true, apiKey: '', ...config,
+ } as any)
+ await p.chatWithTools('m', AGENT_AFTER_A_TOOL as any, tools as any)
+ return sent
+}
+
+afterEach(() => {
+ vi.doUnmock('../../backend')
+ vi.doUnmock('../../builtin-ensure')
+ vi.resetModules()
+})
+
+describe('the body that leaves for each kind of endpoint', () => {
+ it('the built-in engine on the prompt transport gets the tolerant sequence', async () => {
+ const sent = await sendVia(
+ { baseUrl: 'http://127.0.0.1:8127/v1', isLocal: true, managed: true }, [], true,
+ )
+ expect(sent.tools).toBeUndefined()
+ expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(false)
+ expect(() => gemmaGate(sent.messages)).not.toThrow()
+ })
+
+ it('LM Studio on the prompt transport gets it too', async () => {
+ const sent = await sendVia(
+ { baseUrl: 'http://localhost:1234/v1', isLocal: true }, [], true,
+ )
+ expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(false)
+ expect(() => gemmaGate(sent.messages)).not.toThrow()
+ })
+
+ it('a local engine that DID get a native tools payload keeps the tool role', async () => {
+ // The strategy resolution only sends `tools` after this same server said
+ // its template understands them (/props chat_template_caps, or the LM
+ // Studio per-model listing). Rewriting then would throw away a working
+ // channel for nothing.
+ const sent = await sendVia(
+ { baseUrl: 'http://localhost:1234/v1', isLocal: true },
+ [{ type: 'function', function: { name: 'file_write', description: '', parameters: { type: 'object', properties: {}, required: [] } } }],
+ true,
+ )
+ expect(sent.tools).toHaveLength(1)
+ expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(true)
+ expect(sent.messages[2].tool_calls).toHaveLength(1)
+ })
+
+ it('NEGATIVE CONTROL: a cloud endpoint is never rewritten', async () => {
+ // DeepInfra (LU Cloud) validates the OpenAI tool shape strictly: the
+ // assistant tool_calls and the matching tool_call_id must both survive.
+ const sent = await sendVia(
+ { baseUrl: 'https://api.example-cloud.com/v1', isLocal: false }, [], false,
+ )
+ expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(true)
+ expect(sent.messages[3].tool_call_id).toBe('call_1')
+ expect(sent.messages[2].tool_calls[0].id).toBe('call_1')
+ })
+
+ it('Ollama chatStream, which never carries tools, gets the tolerant sequence', 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('gemma3:4b', AGENT_AFTER_A_TOOL as any)) { void chunk }
+ expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(false)
+ expect(() => gemmaGate(sent.messages)).not.toThrow()
+ })
+
+ it('Ollama chatWithTools with a real tools payload keeps the tool role', async () => {
+ vi.resetModules()
+ let sent: any = null
+ vi.doMock('../../backend', () =>
+ backendMock((_url, init) => {
+ sent = JSON.parse(init.body)
+ return okJson({ message: { content: 'ok' } })
+ }),
+ )
+ 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', AGENT_AFTER_A_TOOL as any, [
+ { type: 'function', function: { name: 'file_write', description: '', parameters: { type: 'object', properties: {}, required: [] } } },
+ ] as any)
+ expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(true)
+ })
+})
+
+// ── 3. Group chat ──────────────────────────────────────────────
+
+describe('a group round reaches every speaker as a legal conversation', () => {
+ const msg = (o: Partial<Message>): Message => ({
+ id: `m-${Math.random().toString(36).slice(2)}`,
+ role: 'user', content: 'x', timestamp: 1, ...o,
+ })
+
+ // Round 2 of the counter-check's two-model group, from
+ // logs/wire-b3-18-group.json.
+ const history: Message[] = [
+ msg({ role: 'user', content: 'Runde 1' }),
+ msg({ role: 'assistant', content: 'round1', modelId: 'hermes' }),
+ msg({ role: 'assistant', content: "I didn't return a visible answer that time.", modelId: 'gemma' }),
+ msg({ role: 'user', content: 'Runde 2' }),
+ ]
+
+ const payloadFor = (model: string) => [
+ { role: 'system', content: groupSystemPrompt(model, ['hermes', 'gemma'], '') },
+ ...groupHistory(history, model),
+ ]
+
+ it('NEGATIVE CONTROL: two assistant turns in a row are what the template refuses', () => {
+ expect(() =>
+ gemmaGate([
+ { role: 'system', content: 's' },
+ { role: 'user', content: 'Runde 1' },
+ { role: 'assistant', content: 'round1' },
+ { role: 'assistant', content: '[gemma] ...' },
+ { role: 'user', content: 'Runde 2' },
+ ]),
+ ).toThrow('Conversation roles must alternate')
+ })
+
+ it('the other speakers arrive as tagged user turns, own turns stay assistant', () => {
+ const out = groupHistory(history, 'hermes')
+ expect(out.map((m) => m.role)).toEqual(['user', 'assistant', 'user', 'user'])
+ expect(out[1].content).toBe('round1')
+ expect(out[2].content).toBe("[gemma] I didn't return a visible answer that time.")
+ })
+
+ it('and the whole round 2 payload passes the guard, for BOTH speakers', () => {
+ for (const model of ['hermes', 'gemma']) {
+ const out = applyTemplateContract(payloadFor(model), STRICT)
+ expect(() => gemmaGate(out)).not.toThrow()
+ }
+ })
+
+ it('round 1 no longer ends the second speaker prompt on a foreign assistant turn', () => {
+ // The counter-check saw the second speaker asked to carry on straight
+ // after another model's turn, and it answered with nothing at all.
+ const roundOne = [history[0], history[1]]
+ const out = applyTemplateContract(
+ [
+ { role: 'system', content: groupSystemPrompt('gemma', ['hermes', 'gemma'], '') },
+ ...groupHistory(roundOne, 'gemma'),
+ ],
+ STRICT,
+ )
+ expect(out[out.length - 1].role).toBe('user')
+ expect(() => gemmaGate(out)).not.toThrow()
+ })
+
+ it('the system prompt tells the model where the other voices are', () => {
+ const p = groupSystemPrompt('hermes', ['hermes', 'gemma'], '')
+ expect(p).toContain('user messages that start with a [model-name] tag')
+ })
+})
+
+// ── 4. The tool_call that vanished from the history ────────────
+
+const src = (rel: string) => readFileSync(join(process.cwd(), 'src', rel), 'utf8')
+
+describe('a stored tool call survives the rebuild of the history', () => {
+ // The store persists tool_calls and tool_call_id (types/chat.ts says so, and
+ // says why). Both payload builders rebuilt the history without them, so from
+ // the second user message on, the model saw a tool result with no call in
+ // front of it. Guarded at the source: the rebuild lives inside a hook with
+ // no test harness, and what matters is the field list.
+ it('the agent payload builder carries both fields through', () => {
+ const agent = src('hooks/useAgentChat.ts')
+ expect(agent).toContain("...(m.tool_calls?.length ? { tool_calls: m.tool_calls as unknown as ChatMessage['tool_calls'] } : {}),")
+ expect(agent).toContain('...(m.tool_call_id ? { tool_call_id: m.tool_call_id } : {}),')
+ })
+
+ it('the plain chat payload builder carries both fields through', () => {
+ const chat = src('hooks/useChat.ts')
+ expect(chat).toContain('...(m.tool_calls?.length ? { tool_calls: m.tool_calls } : {}),')
+ expect(chat).toContain('...(m.tool_call_id ? { tool_call_id: m.tool_call_id } : {}),')
+ })
+
+ it('the prompt-transport send no longer strips the message down to role and content', () => {
+ const agent = src('hooks/useAgentChat.ts')
+ expect(agent).not.toContain('sendMessages.map(m => ({ role: m.role, content: m.content }))')
+ })
+
+ it('the coding agent writes it for the transport too', () => {
+ const codex = src('hooks/useCodex.ts')
+ const transport = codex.indexOf("if (strategy === 'hermes_xml') {")
+ const byProvider = codex.indexOf("} else if (providerId === 'openai' || providerId === 'anthropic' || providerId === 'lu-cloud') {")
+ expect(transport).toBeGreaterThan(-1)
+ expect(byProvider).toBeGreaterThan(-1)
+ expect(transport).toBeLessThan(byProvider)
+ })
+
+ it('the tool result is written for the TRANSPORT, not for the provider name', () => {
+ // The built-in engine and LM Studio are providerId 'openai', so the
+ // provider-first branch wrote native `tool` messages for a run that was
+ // driving the model by prompt. That is the payload the engine died on.
+ const agent = src('hooks/useAgentChat.ts')
+ const transport = agent.indexOf("if (strategy === 'hermes_xml') {")
+ const byProvider = agent.indexOf("} else if (providerId === 'openai' || providerId === 'anthropic' || providerId === 'lu-cloud') {")
+ expect(transport).toBeGreaterThan(-1)
+ expect(byProvider).toBeGreaterThan(-1)
+ expect(transport).toBeLessThan(byProvider)
+ })
+})
+
+// ── 5. What the user reads when a template refuses anyway ──────
+
+describe('a template refusal says what happened, in English', () => {
+ const gemmaError = Object.assign(
+ new Error(
+ 'Unable to generate parser for this template. Automatic parser generation failed: ' +
+ 'While executing CallExpression at line 19, column 27 in source: ... ' +
+ 'Error: Jinja Exception: Conversation roles must alternate user/assistant/user/assistant/...',
+ ),
+ { status: 400 },
+ )
+
+ it('recognises the template wordings', () => {
+ expect(isTemplateRefusal(gemmaError)).toBe(true)
+ expect(isTemplateRefusal(new Error('System message must be at the beginning'))).toBe(true)
+ })
+
+ it('NEGATIVE CONTROL: an ordinary failure is not dressed up as a template problem', () => {
+ expect(isTemplateRefusal(new Error('Connection failed'))).toBe(false)
+ expect(explainSendRefusal(new Error('Connection failed'))).toBeNull()
+ expect(explainSendRefusal(Object.assign(new Error('too many requests'), { status: 429 }))).toBeNull()
+ })
+
+ it('the sentence is ours and the raw text is kept underneath it', () => {
+ const out = explainSendRefusal(gemmaError)!
+ expect(out).toContain("chat template refused the conversation")
+ expect(out).toContain('Jinja Exception')
+ expect(out.startsWith('Unable to generate parser')).toBe(false)
+ })
+
+ it('a bare 400 gets its own sentence rather than the raw body', () => {
+ const out = explainSendRefusal(Object.assign(new Error('invalid request'), { status: 400 }))!
+ expect(out).toContain('refused the request before generating anything')
+ })
+
+ it('no dashes anywhere in the user-facing text', () => {
+ const text = readFileSync(join(process.cwd(), 'src/lib/template-refusal.ts'), 'utf8')
+ expect(text).not.toMatch(/[\u2013\u2014]/)
+ })
+
+ it('the agent judges it BEFORE it falls back to "Agent error"', () => {
+ // Plain chat routes its tool turns through the agent executor, so the
+ // template's Jinja trace used to reach a user who never touched Agent
+ // mode under the heading "Agent error".
+ const agent = src('hooks/useAgentChat.ts')
+ const branch = agent.indexOf('} else if (sendRefusal) {')
+ const generic = agent.indexOf("'\\n\\nAgent error: ' + errorMsg")
+ expect(branch).toBeGreaterThan(-1)
+ expect(branch).toBeLessThan(generic)
+ })
+
+ it('plain chat and the group round say it too', () => {
+ const chat = src('hooks/useChat.ts')
+ expect(chat).toContain('} else if (sendRefusal) {')
+ expect(chat).toContain('refusal ?? `Error from ${model}:')
+ })
+})
diff --git a/src/api/providers/normalize-system.ts b/src/api/providers/normalize-system.ts
index 0aad56d2..dcb37792 100644
--- a/src/api/providers/normalize-system.ts
+++ b/src/api/providers/normalize-system.ts
@@ -36,6 +36,8 @@
* builders intended.
*/
+import { buildHermesToolResult, buildHermesToolCall } from '../hermes-tool-calling'
+
/** The shape this works on. Deliberately looser than ChatMessage so the same
* function serves the wire types of all providers. */
export interface RoledMessage {
@@ -91,3 +93,197 @@ export function normalizeSystemMessages<T extends RoledMessage>(messages: T[]):
if (parts.length === 0) return rest
return [{ ...messages[firstSystem], content: parts.join('\n\n') } as T, ...rest]
}
+
+// ══ The template contract (bug B3, round 2) ════════════════════
+//
+// The counter-check ran the round-1 fix against a real strict template
+// (Gemma 3, whose Jinja raises on every rule it can check) on the installed
+// 2.6.7 build, and the crash was still reachable three ways. One system
+// message at the front was necessary and nowhere near sufficient:
+//
+// 1. Agent turn with tools. After the first tool result the wire carried
+// [system, user, assistant, tool] and NO `tools` field, because the run
+// was on the prompt transport. The template has no branch for a `tool`
+// role, so it raised and the next round died.
+// 2. Plain chat. The chat tools (web_search and friends) are on by default,
+// so an ordinary question produced the very same four roles and the very
+// same death, with no agent mode anywhere in sight.
+// 3. Group chat. From round two on, the history holds two assistant
+// messages in a row (one per speaker), and the template demands strict
+// user/assistant alternation. Both speakers died.
+//
+// The same payloads run on Hermes 3, whose ChatML template loops over the
+// messages and renders whatever it is handed. So the request shape is not
+// wrong in the abstract: it is wrong for the template that has to render it.
+//
+// Hence a CONTRACT rather than one more rule. Where the model's own template
+// does the rendering, the wire gets a sequence every template can render:
+// no `tool` role, no two turns of the same role in a row, and a user turn
+// first. Where the SERVER implements the protocol (a cloud endpoint) or has
+// declared its template understands tools (the run then carries a native
+// `tools` payload), nothing is rewritten and the tool calls stay native.
+//
+// Why the tolerant sequence rather than a per-template capability probe: the
+// engine does publish its template on /props, but reading a Jinja source and
+// deciding what it will accept is guesswork, the answer is cached and can be
+// a model swap out of date, and being wrong means a dead turn. The tolerant
+// sequence also renders correctly on a tolerant template, so the cost of
+// choosing it when it was not needed is a slightly wordier prompt, and the
+// cost of the other mistake is a chat that cannot be used at all.
+
+/** Messages as the contract sees them. Deliberately looser than ChatMessage. */
+export interface ContractMessage extends RoledMessage {
+ tool_calls?: { id?: string; function: { name: string; arguments: unknown } }[]
+ tool_call_id?: string
+ images?: { data: string; mimeType: string }[]
+}
+
+export interface TemplateContract {
+ /**
+ * 'native' leaves `tool` messages and `assistant.tool_calls` alone; the
+ * server or the template handles them.
+ * 'text' carries both as prompt text instead, in the Hermes dialect LU has
+ * used for tool-less models since 2.5.3.
+ */
+ toolRole: 'native' | 'text'
+ /** Enforce strict user/assistant alternation behind the system message. */
+ alternate: boolean
+}
+
+/** The minimal turn used when two same-role turns cannot be merged. */
+const BRIDGE_USER = 'Continue.'
+const BRIDGE_ASSISTANT = 'Understood.'
+
+function textOf(content: unknown): string | null {
+ return typeof content === 'string' ? content : null
+}
+
+/**
+ * Rewrite the tool channel as prompt text.
+ *
+ * A `tool` message becomes a user turn holding <tool_response>, and the
+ * assistant turn that asked for it keeps its call as <tool_call> text. Doing
+ * only the first half is what produced the orphaned results the counter-check
+ * found on the wire: the model saw an answer to a question it never asked.
+ */
+function toolRoleAsText<T extends ContractMessage>(messages: T[]): T[] {
+ const nameById = new Map<string, string>()
+ for (const m of messages) {
+ if (m?.role !== 'assistant' || !Array.isArray(m.tool_calls)) continue
+ for (const tc of m.tool_calls) {
+ if (tc?.id && tc.function?.name) nameById.set(String(tc.id), String(tc.function.name))
+ }
+ }
+
+ // Names of the calls the last assistant turn made, for a result that carries
+ // no id (the Ollama shape, and every call the prompt transport parsed).
+ let pending: string[] = []
+ const out: T[] = []
+ let changed = false
+
+ for (const m of messages) {
+ if (m?.role === 'assistant' && Array.isArray(m.tool_calls) && m.tool_calls.length) {
+ pending = m.tool_calls.map((tc) => String(tc?.function?.name ?? ''))
+ const calls = m.tool_calls
+ .map((tc) => buildHermesToolCall(tc?.function?.name ?? '', tc?.function?.arguments))
+ .join('\n')
+ const body = textOf(m.content) ?? ''
+ const next = { ...m, content: body ? `${body}\n${calls}` : calls } as T
+ delete (next as ContractMessage).tool_calls
+ out.push(next)
+ changed = true
+ continue
+ }
+ if (m?.role === 'tool') {
+ const byId = m.tool_call_id ? nameById.get(String(m.tool_call_id)) : undefined
+ const name = byId || pending.shift() || 'tool'
+ const next = {
+ ...m,
+ role: 'user',
+ content: buildHermesToolResult(name, textOf(m.content) ?? ''),
+ } as unknown as T
+ delete (next as ContractMessage).tool_call_id
+ delete (next as ContractMessage).tool_calls
+ out.push(next)
+ changed = true
+ continue
+ }
+ if (m?.role === 'assistant') pending = []
+ out.push(m)
+ }
+
+ return changed ? out : messages
+}
+
+/**
+ * Strict user/assistant alternation behind the optional system message.
+ *
+ * Merging is preferred over dropping and over padding: two consecutive user
+ * turns are two things the user (or the tool transport) said, and the model
+ * has to see both. A bridging turn is only used where a merge is impossible,
+ * which is a non-string content (an image payload) and a history that opens
+ * on an assistant turn.
+ */
+function alternateRoles<T extends ContractMessage>(messages: T[]): T[] {
+ const lead = messages[0]?.role === 'system' ? 1 : 0
+ const head = messages.slice(0, lead)
+ const body = messages.slice(lead)
+ if (body.length === 0) return messages
+
+ const out: T[] = []
+ let changed = false
+
+ // A template that alternates from user expects the first turn to be one.
+ if (body[0]?.role === 'assistant') {
+ out.push({ role: 'user', content: BRIDGE_USER } as unknown as T)
+ changed = true
+ }
+
+ for (const m of body) {
+ const prev = out[out.length - 1]
+ if (!prev || prev.role !== m.role) {
+ out.push(m)
+ continue
+ }
+ const a = textOf(prev.content)
+ const b = textOf(m.content)
+ if (a !== null && b !== null) {
+ const merged = { ...prev, content: a && b ? `${a}\n\n${b}` : a || b } as T
+ const images = [
+ ...(Array.isArray(prev.images) ? prev.images : []),
+ ...(Array.isArray(m.images) ? m.images : []),
+ ]
+ if (images.length) (merged as ContractMessage).images = images
+ out[out.length - 1] = merged
+ } else {
+ out.push({
+ role: m.role === 'user' ? 'assistant' : 'user',
+ content: m.role === 'user' ? BRIDGE_ASSISTANT : BRIDGE_USER,
+ } as unknown as T)
+ out.push(m)
+ }
+ changed = true
+ }
+
+ return changed ? [...head, ...out] : messages
+}
+
+/**
+ * The whole contract, in the order the rules depend on each other: system
+ * first (round 1), then the tool channel, then alternation, because turning
+ * a tool result into a user turn is what creates most of the consecutive
+ * user turns alternation then has to merge.
+ *
+ * Returns the SAME array reference when nothing had to change, which is the
+ * common case and keeps the upstream prefix cache warm. See
+ * normalizeSystemMessages for why that matters.
+ */
+export function applyTemplateContract<T extends ContractMessage>(
+ messages: T[],
+ contract: TemplateContract,
+): T[] {
+ let out = normalizeSystemMessages(messages)
+ if (contract.toolRole === 'text') out = toolRoleAsText(out)
+ if (contract.alternate) out = alternateRoles(out)
+ return out
+}
diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.ts
index 64d69514..c38d1515 100644
--- a/src/api/providers/ollama-provider.ts
+++ b/src/api/providers/ollama-provider.ts
@@ -13,7 +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'
+import { applyTemplateContract } from './normalize-system'
// ── Ollama-specific types ──────────────────────────────────────
@@ -79,9 +79,15 @@ export class OllamaProvider implements ProviderClient {
messages: ChatMessage[],
options?: ChatOptions,
): AsyncGenerator<ChatStreamChunk> {
- // 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 => {
+ // Bug B3: one system message first, and, because this call carries no
+ // `tools` payload, no `tool` role and no two turns of the same role in a
+ // row either. Ollama renders the model's own template exactly the way
+ // llama.cpp does, and a strict one raises instead of improvising. See
+ // providers/normalize-system.ts for the whole contract.
+ const ollamaMessages = applyTemplateContract(messages, {
+ toolRole: 'text',
+ alternate: true,
+ }).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
@@ -188,8 +194,14 @@ export class OllamaProvider implements ProviderClient {
tools: ToolDefinition[],
options?: ChatOptions,
): Promise<{ content: string; toolCalls: ToolCall[] }> {
- // Bug B3: same invariant as chatStream, see providers/normalize-system.ts.
- const ollamaMessages = normalizeSystemMessages(messages).map(m => {
+ // Bug B3: same contract as chatStream. A turn that really carries a
+ // `tools` payload keeps the native tool channel. The strategy resolution
+ // only sends one after Ollama itself reported the `tools` capability for
+ // this model (/api/show, see lib/tool-support.ts).
+ const ollamaMessages = applyTemplateContract(messages, {
+ toolRole: tools.length > 0 ? 'native' : 'text',
+ alternate: tools.length === 0,
+ }).map(m => {
const msg: Record<string, any> = { role: m.role, content: m.content }
if (m.tool_calls) msg.tool_calls = m.tool_calls
if (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.ts
index c3247016..9636065a 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -20,7 +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'
+import { applyTemplateContract } 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
@@ -215,6 +215,33 @@ export class OpenAIProvider implements ProviderClient {
return this.isLanBackend || !isDirectFetchAllowed(hostnameOf(this.baseUrl))
}
+ /**
+ * Bug B3 round 2: the message sequence this endpoint can actually render.
+ *
+ * A LAN backend (the bundled engine, LM Studio, llama.cpp, vLLM, Jan, …)
+ * renders the MODEL's own Jinja chat template, and a strict one raises
+ * rather than improvises: no `tool` role, no two turns of the same role in
+ * a row, user first. A cloud endpoint implements the protocol itself and
+ * wants the plain OpenAI shape, so it is left alone.
+ *
+ * `nativeTools` is the second half of the rule and the reason this is not
+ * a blanket downgrade. When the request carries a `tools` payload, the
+ * strategy resolution already asked this very server whether its template
+ * understands tools (serverToolSupport, /props chat_template_caps or the
+ * LM Studio per-model listing) and got a yes. Then the tool channel stays
+ * native, ids and all. When it does NOT carry one, the run is on the
+ * prompt transport, and a leftover `tool` message in the history is a role
+ * this template has no branch for. That is exactly the payload the
+ * counter-check killed the built-in engine with.
+ */
+ private templateContract(messages: ChatMessage[], nativeTools: boolean): ChatMessage[] {
+ const rendersTemplate = this.isLanBackend && !nativeTools
+ return applyTemplateContract(messages, {
+ toolRole: rendersTemplate ? 'text' : 'native',
+ alternate: rendersTemplate,
+ })
+ }
+
/**
* Run a send and, when this slot is the app's own engine, translate a
* transport failure into a sentence about the engine. A refused connection
@@ -389,7 +416,7 @@ export class OpenAIProvider implements ProviderClient {
// 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)),
+ messages: this.templateContract(messages, (options?.tools?.length ?? 0) > 0).map(m => this.toOpenAIMessage(m)),
stream: true,
}
@@ -554,7 +581,7 @@ export class OpenAIProvider implements ProviderClient {
const body: Record<string, any> = {
model,
// Bug B3: same invariant as chatStream, see providers/normalize-system.ts.
- messages: normalizeSystemMessages(messages).map(m => this.toOpenAIMessage(m)),
+ messages: this.templateContract(messages, tools.length > 0).map(m => this.toOpenAIMessage(m)),
stream: false,
}
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index b062c569..2f758866 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -31,7 +31,7 @@ import { resolveToolCallingStrategy } from '../lib/agent-strategy'
import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from '../lib/ollama-errors'
import { stripVisionFeedbackMessages } from '../lib/vision-heal'
import { log } from '../lib/logger'
-import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
+import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToolName } from '../lib/loose-tool-parse'
import { mediaCallSucceeded } from '../lib/media-result'
import { summarizeTurn } from '../lib/turn-summary'
@@ -76,6 +76,7 @@ import { reasoningOnlyRound, REASONING_CONTINUE_BUDGET, REASONING_CONTINUE_STEER
import { findUnbackedLinks, unbackedLinksSteer } from '../lib/unbacked-links'
import { useTodoStore } from '../stores/todoStore'
import { platformPromptLine, hostClockLine } from '../lib/host-platform'
+import { explainSendRefusal } from '../lib/template-refusal'
import { httpStatusOf, isTerminalModelError, retryDelayMs } from '../lib/http-status'
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
@@ -547,6 +548,16 @@ export function useAgentChat() {
? `${cavemanReminder}\n${m.content}`
: m.content,
...(m.images?.length ? { images: m.images.map(img => ({ data: img.data, mimeType: img.mimeType })) } : {}),
+ // Bug B3 round 2: the store persists tool_calls and tool_call_id
+ // (types/chat.ts says so, and says why), and this rebuild threw both
+ // away. From the second user message of a chat on, the model got a
+ // tool RESULT with no call in front of it and no id to tie it to
+ // one. A mutilated history on a tolerant template, and on the id
+ // strict cloud shape a 422 on every follow-up turn. Carried through
+ // now; where the template cannot render them, the contract in
+ // api/providers/normalize-system.ts turns both into prompt text.
+ ...(m.tool_calls?.length ? { tool_calls: m.tool_calls as unknown as ChatMessage['tool_calls'] } : {}),
+ ...(m.tool_call_id ? { tool_call_id: m.tool_call_id } : {}),
})),
]
@@ -1137,7 +1148,12 @@ export function useAgentChat() {
const hermesTurn = await streamProviderTurn(
provider,
modelToUse,
- sendMessages.map(m => ({ role: m.role, content: m.content })),
+ // Bug B3 round 2: this used to rebuild every message as bare
+ // role+content, which dropped tool_calls, tool_call_id AND image
+ // attachments on the prompt-transport path only. The provider
+ // contract decides what a template can render; it must be given
+ // the whole message to decide on.
+ sendMessages,
{ ...chatOptions, thinking: undefined as unknown as boolean },
(_full, delta) => feedUI(splitter.feed(display.feed(delta))),
)
@@ -1814,7 +1830,28 @@ export function useAgentChat() {
guardKeyOfResult.set(msg as unknown as object, guardKeyFor(tc))
return msg
}
- if (providerId === 'openai' || providerId === 'anthropic' || providerId === 'lu-cloud') {
+ // Bug B3 round 2, the first cause the counter-check proved on the
+ // real engine: this chain asked WHICH PROVIDER, never WHICH TRANSPORT.
+ // The built-in engine and LM Studio are providerId 'openai', so a run
+ // on the prompt transport still wrote its results into the native
+ // `tool` role, a role the model's template has no branch for, and no
+ // `tools` payload anywhere in the request to justify it. The wire read
+ // [system, user, assistant, tool] and the strict template raised on
+ // the next round. The transport decides the shape; the provider only
+ // decides whether the native shape needs ids.
+ if (strategy === 'hermes_xml') {
+ for (const { tc } of batch) {
+ const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
+ agentMessages.push({
+ role: 'assistant',
+ content: buildHermesToolCall(tc.function.name, tc.function.arguments),
+ })
+ agentMessages.push(rememberResult({
+ role: 'user',
+ content: buildHermesToolResult(tc.function.name, resultTextFor(result) + mediaNote(tc.function.name, result)),
+ }, tc))
+ }
+ } else if (providerId === 'openai' || providerId === 'anthropic' || providerId === 'lu-cloud') {
agentMessages.push({
role: 'assistant',
content: turnContent || '',
@@ -1844,11 +1881,14 @@ export function useAgentChat() {
}, tc))
}
} else {
+ // Ollama on a non-native strategy that is not hermes_xml. Same
+ // prompt transport, same dialect, written by the same builders as
+ // the branch above so the two can never drift apart again.
for (const { tc } of batch) {
const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
agentMessages.push({
role: 'assistant',
- content: `<tool_call>\n{"name": "${tc.function.name}", "arguments": ${JSON.stringify(tc.function.arguments)}}\n</tool_call>`,
+ content: buildHermesToolCall(tc.function.name, tc.function.arguments),
})
agentMessages.push(rememberResult({
role: 'user',
@@ -1965,6 +2005,10 @@ export function useAgentChat() {
} catch (err) {
if ((err as Error).name !== 'AbortError') {
const errorMsg = (err as Error).message || 'Connection failed'
+ // Bug B3 round 2: a refusal that produced nothing at all (the model's
+ // chat template raised, or the backend 400'd) gets its own English
+ // sentence instead of the raw Jinja trace under an "Agent error" head.
+ const sendRefusal = explainSendRefusal(err)
if (isMultimodalUnsupportedError(errorMsg)) {
useChatStore.getState().updateMessageContent(
@@ -2039,6 +2083,16 @@ export function useAgentChat() {
(contentRef.current ? contentRef.current + '\n\n' : '') +
`The server is limiting how many requests this account may send in a short window, and the run waited for it once already. Give it ${when}, then send your message again. Nothing was charged for the refused attempts.`
)
+ } else if (sendRefusal) {
+ // Bug B3 round 2, nebenbefund 3: a chat-tools turn in PLAIN chat
+ // runs through this same executor, so the template's own Jinja
+ // stack trace used to reach the user under the heading "Agent
+ // error" with Agent mode switched off. It is neither the agent's
+ // failure nor a sentence anyone can act on.
+ useChatStore.getState().updateMessageContent(
+ convId!, assistantMessage.id,
+ (contentRef.current ? contentRef.current + '\n\n' : '') + sendRefusal,
+ )
} else if (/failed to fetch|connection refused|connection reset|error sending request|proxy_localhost|network ?error|timed out|timeout|tcp connect|llama runner process|backend unreachable|HTTP 5\d\d/i.test(errorMsg)) {
// Connection-class failure — after the transient retries above this
// means the backend really dropped mid-run (crashed, was killed, or
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index e0bf2017..86c94c62 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -31,6 +31,7 @@ import { stripNonCanonicalTags, finalStripThinkingTags } from "../lib/thinking-s
import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from "../lib/ollama-errors"
import type { ImageAttachment, Message } from "../types/chat"
import { isGroupChat, groupSystemPrompt, groupHistory, stripImpersonatedSpeakers } from "../lib/group-chat"
+import { explainSendRefusal } from "../lib/template-refusal"
import { emptyAnswerExplanation } from "../lib/answer-notes"
import { log } from "../lib/logger"
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
@@ -203,10 +204,14 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
} catch (err) {
if ((err as Error).name !== 'AbortError') {
syncOllamaHealthFromError(err)
+ // Bug B3 round 2: a group round on a strict template used to paste the
+ // template's own Jinja trace into the bubble. Say what happened instead,
+ // and keep the raw text underneath it for support.
+ const refusal = explainSendRefusal(err)
useChatStore.getState().updateMessageContent(
convId,
assistantMessage.id,
- `Error from ${model}: ${(err as Error).message || 'Connection failed'}`,
+ refusal ?? `Error from ${model}: ${(err as Error).message || 'Connection failed'}`,
)
}
}
@@ -541,6 +546,15 @@ export function useChat() {
? `${cavemanReminder}\n${m.content}`
: m.content,
...(m.images?.length ? { images: m.images.map(img => ({ data: img.data, mimeType: img.mimeType })) } : {}),
+ // Bug B3 round 2: a plain chat can hold tool turns, because the
+ // chat tools (web_search and friends) run inside it by default.
+ // The store keeps tool_calls and tool_call_id for exactly this
+ // rebuild, and this rebuild dropped both, so every later send
+ // showed the model a tool RESULT with no call in front of it.
+ // Where the model's template cannot render them, the contract in
+ // api/providers/normalize-system.ts carries them as prompt text.
+ ...(m.tool_calls?.length ? { tool_calls: m.tool_calls } : {}),
+ ...(m.tool_call_id ? { tool_call_id: m.tool_call_id } : {}),
})),
]),
{
@@ -846,6 +860,9 @@ export function useChat() {
: (err as any).code === 'rate_limit'
? (err as Error).message
: `Error: ${(err as Error).message || 'Connection failed'}`
+ // Bug B3 round 2: a refusal that produced nothing at all gets its own
+ // English sentence, not the template's raw Jinja trace.
+ const sendRefusal = explainSendRefusal(err)
// Image attached to a non-vision model → friendly guidance instead of
// the raw 400 JSON (gthvidsten, GH Discussion #67).
@@ -864,6 +881,15 @@ export function useChat() {
(contentRef.current ? contentRef.current + '\n\n' : '') + CREDITS_EXHAUSTED_MESSAGE
)
// Show user-friendly message for thinking errors
+ // Bug B3 round 2: same treatment as the agent path. A template that
+ // raised produced nothing at all, and its Jinja trace is not an
+ // answer to anything the user asked.
+ } else if (sendRefusal) {
+ useChatStore.getState().updateMessageContent(
+ convId!,
+ assistantMessage.id,
+ (contentRef.current ? contentRef.current + "\n\n" : "") + sendRefusal,
+ )
} else if (errorMsg.includes('does not support thinking')) {
useChatStore.getState().updateMessageContent(
convId!,
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 373f760e..09c821ff 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -14,7 +14,7 @@ import { applyGoalCommand } from '../lib/goal-command'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { useAgentLoopStore } from '../stores/agentLoopStore'
import { CODEX_CONFIRM_TOOLS } from './codexShellGate'
-import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
+import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-stream'
import { createHermesDisplayFilter } from '../lib/hermes-stream'
import { beginAgentRun, endAgentRun, chatWorkspaceSlug, setActiveAgentModel, type AgentRunContext } from '../api/agent-context'
@@ -2143,7 +2143,26 @@ export function useCodex() {
guardKeyOfResult.set(msg as unknown as object, guardKeyFor(tc))
return msg
}
- if (providerId === 'openai' || providerId === 'anthropic' || providerId === 'lu-cloud') {
+ // Bug B3 round 2: same reorder as the Agent surface. This chain asked
+ // WHICH PROVIDER, and the built-in engine and LM Studio are providerId
+ // 'openai', so a coding run driving the model by prompt still wrote
+ // its results into the native `tool` role, with no `tools` payload in
+ // the request to justify it. A strict chat template has no branch for
+ // that role and refuses the whole conversation. The transport decides
+ // the shape; the provider only decides whether it needs ids.
+ if (strategy === 'hermes_xml') {
+ for (const entry of batch) {
+ const result = results.find((r) => r.id === entry.ac.id)!
+ messages.push({
+ role: 'assistant',
+ content: buildHermesToolCall(entry.ac.toolName, entry.injectedArgs),
+ })
+ messages.push(rememberResult(
+ { role: 'user', content: buildHermesToolResult(entry.ac.toolName, resultTextFor(result)) },
+ entry.tc,
+ ))
+ }
+ } else if (providerId === 'openai' || providerId === 'anthropic' || providerId === 'lu-cloud') {
messages.push({ role: 'assistant', content: turnContent || '', tool_calls: toolCalls })
for (const { tc } of batch) {
const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
@@ -2162,11 +2181,14 @@ export function useCodex() {
messages.push(rememberResult({ role: 'tool', content: resultTextFor(result) }, tc))
}
} else {
+ // Ollama on a non-native strategy that is not hermes_xml. Same
+ // dialect, written by the same builders as the branch above so the
+ // two can never drift apart again.
for (const entry of batch) {
const result = results.find((r) => r.id === entry.ac.id)!
messages.push({
role: 'assistant',
- content: `<tool_call>\n{"name": "${entry.ac.toolName}", "arguments": ${JSON.stringify(entry.injectedArgs)}}\n</tool_call>`,
+ content: buildHermesToolCall(entry.ac.toolName, entry.injectedArgs),
})
messages.push(rememberResult(
{ role: 'user', content: buildHermesToolResult(entry.ac.toolName, resultTextFor(result)) },
diff --git a/src/lib/group-chat.ts b/src/lib/group-chat.ts
index fe5a219e..364d9686 100644
--- a/src/lib/group-chat.ts
+++ b/src/lib/group-chat.ts
@@ -21,7 +21,7 @@ export function groupSystemPrompt(model: string, allModels: string[], personaPro
const others = allModels.filter((m) => m !== model).map((m) => `"${m}"`).join(', ')
const line =
`You are "${model}", one of several AI models answering in the same group conversation with ${others}. ` +
- `Earlier assistant messages starting with a [model-name] tag were written by the other models; untagged assistant messages are your own. ` +
+ `What the other models said arrives as user messages that start with a [model-name] tag; the assistant messages are your own earlier turns. ` +
`Answer as yourself in your own voice, add something new, and do not repeat what another model already said.`
return personaPrompt ? `${personaPrompt}\n\n${line}` : line
}
@@ -53,23 +53,35 @@ export function stripImpersonatedSpeakers(text: string, otherModels: string[]):
return cut === -1 ? text : lines.slice(0, cut).join('\n').trim()
}
-/** The shared history as one model sees it: other speakers tagged, own turns
- * clean, empty placeholders and app notices dropped.
+/** The shared history as one model sees it: the OTHER speakers arrive as
+ * tagged user turns, this model's own turns stay assistant, empty
+ * placeholders and app notices are 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". */
+ * beginning".
+ *
+ * Bug B3 round 2: the other speakers used to arrive as assistant turns, tagged
+ * but assistant all the same. From round two on that puts two assistant
+ * messages next to each other in every payload, one per speaker, and a
+ * template that demands strict user/assistant alternation raises on it. The
+ * counter-check killed both speakers of a two-model group that way on the
+ * installed 2.6.7 build. A foreign turn is not this model's own speech, so
+ * the honest role for it is user; the [model-name] tag and the system prompt
+ * above say who is talking, which is how attribution worked all along. It
+ * also fixes round one for the second speaker, whose prompt used to end on
+ * somebody else's assistant turn and asked it to carry on mid-sentence. */
export function groupHistory(messages: Message[], model: string): GroupWireMessage[] {
return messages
.filter((m) => m.role !== 'system' && m.content.trim() !== '')
- .map((m) => ({
- role: m.role as GroupWireMessage['role'],
- content:
- m.role === 'assistant' && m.modelId && m.modelId !== model
- ? `[${m.modelId}] ${m.content}`
- : m.content,
- ...(m.images?.length ? { images: m.images.map((i) => ({ data: i.data, mimeType: i.mimeType })) } : {}),
- }))
+ .map((m) => {
+ const foreign = m.role === 'assistant' && !!m.modelId && m.modelId !== model
+ return {
+ role: (foreign ? 'user' : m.role) as GroupWireMessage['role'],
+ content: foreign ? `[${m.modelId}] ${m.content}` : m.content,
+ ...(m.images?.length ? { images: m.images.map((i) => ({ data: i.data, mimeType: i.mimeType })) } : {}),
+ }
+ })
}
diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.ts
index e4058786..f06c3940 100644
--- a/src/lib/ollama-stream-tools.ts
+++ b/src/lib/ollama-stream-tools.ts
@@ -1,6 +1,7 @@
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
import { ollamaUrl, localFetchStream } from '../api/backend'
import { repairToolCallArgs } from './tool-call-repair'
+import { applyTemplateContract } from '../api/providers/normalize-system'
/**
* Streaming Ollama `/api/chat` call with native `tools` support.
@@ -31,7 +32,15 @@ export async function streamOllamaChatWithTools(
onContent: (content: string) => void,
onThinking: (thinking: string) => void,
): Promise<{ content: string; toolCalls: ToolCall[]; thinking: string; promptEvalCount: number; evalCount: number }> {
- const ollamaMessages = messages.map((m) => {
+ // Bug B3: this path talks to /api/chat behind the provider's back, so it
+ // needs the same contract. It always sends a native `tools` payload (the
+ // strategy resolution only routes here after Ollama reported the model's
+ // `tools` capability), so the tool channel stays native and only the
+ // system-first rule is enforced.
+ const ollamaMessages = applyTemplateContract(messages, {
+ toolRole: 'native',
+ alternate: false,
+ }).map((m) => {
const msg: Record<string, any> = { role: m.role, content: m.content }
if (m.tool_calls) msg.tool_calls = m.tool_calls
if ((m as any).images?.length) msg.images = (m as any).images.map((img: any) => img.data)
diff --git a/src/lib/template-refusal.ts b/src/lib/template-refusal.ts
new file mode 100644
index 00000000..3fd61ca7
--- /dev/null
+++ b/src/lib/template-refusal.ts
@@ -0,0 +1,60 @@
+/**
+ * When the model's own chat template refuses the conversation (bug B3, 2.6.7).
+ *
+ * llama.cpp, the bundled engine, LM Studio and Ollama all render the GGUF's
+ * Jinja chat template before the model sees anything. A strict template calls
+ * raise_exception when the message sequence breaks its rules, the engine turns
+ * that into HTTP 400, and the turn dies without a single token. The text that
+ * comes back is written by the template author, not by us:
+ *
+ * "System message must be at the beginning" (Mistral style)
+ * "Conversation roles must alternate user/assistant/..." (Gemma 3)
+ * "Unable to generate parser for this template ... Jinja Exception: ..."
+ *
+ * Two things were wrong with how that reached the user. It was pasted in raw,
+ * a Jinja stack trace with a line and column number into a chat bubble. And in
+ * plain chat it arrived under the heading "Agent error", because the chat
+ * tools route their turn through the agent executor, so a user who had never
+ * touched Agent mode was told the agent had failed.
+ *
+ * The sequence itself is fixed in api/providers/normalize-system.ts. This is
+ * what the user reads when a template refuses anyway.
+ */
+
+import { detailOf, withDetail } from './error-text'
+import { httpStatusOf } from './http-status'
+
+/**
+ * Wordings from the templates themselves plus the wrappers the engines put
+ * around them. Deliberately narrow: a plain "invalid request" must not be
+ * explained as a template problem.
+ */
+const TEMPLATE_MARKERS =
+ /jinja|raise_exception|chat[ _]template|template error|generate parser for this template|system message must be at the beginning|roles must alternate|conversation roles|last message must be/i
+
+/** Did the model's chat template refuse to render this conversation? */
+export function isTemplateRefusal(err: unknown): boolean {
+ return TEMPLATE_MARKERS.test(detailOf(err))
+}
+
+export const TEMPLATE_REFUSAL_SENTENCE =
+ "This model's chat template refused the conversation, so the request never reached the model. " +
+ 'Templates like this one accept only a strict order of turns. LU reshapes the history for them, ' +
+ 'and this one still did not fit. Send the message again, start a new chat, or pick a model whose ' +
+ 'template is more forgiving.'
+
+export const BAD_REQUEST_SENTENCE =
+ 'The model backend refused the request before generating anything (HTTP 400). ' +
+ 'Nothing was sent to the model, so nothing was charged. Send the message again, and if it keeps ' +
+ 'happening, start a new chat or pick another model.'
+
+/**
+ * The English sentence for a refusal that produced no output at all, or null
+ * when this error is not one of those. Callers put it in place of the raw
+ * message; the raw text is kept underneath it, because support reads it.
+ */
+export function explainSendRefusal(err: unknown): string | null {
+ if (isTemplateRefusal(err)) return withDetail(TEMPLATE_REFUSAL_SENTENCE, err)
+ if (httpStatusOf(err) === 400) return withDetail(BAD_REQUEST_SENTENCE, err)
+ return null
+}