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(thinking): der eingebaute Motor bekommt den Denk-Schalter endlich zu sehen
purple97fd967d17ad
diff --git a/src/api/providers/__tests__/openai-template-thinking.test.ts b/src/api/providers/__tests__/openai-template-thinking.test.tsnew file mode 100644index 00000000..ce6ce922--- /dev/null+++ b/src/api/providers/__tests__/openai-template-thinking.test.ts@@ -0,0 +1,153 @@+/**+ * The Think button has to reach the built-in engine.+ *+ * David, 2026-08-29: thinking was switched on, the model plainly did not+ * think, and no thinking block ever appeared. The audit found nothing on the+ * wire that asks for it. `reasoning_effort` is an OpenAI-API concept; a server+ * that renders the MODEL'S OWN Jinja template has no reasoning mode of its+ * own, the switch is the `enable_thinking` variable inside the template and it+ * is reached through `chat_template_kwargs`.+ *+ * Counter-check against the real bundled binary (lu-llama-server b1-049326a,+ * Mac, 2026-08-29), using a chat template that prints the branch it took and+ * llama-server's own /apply-template endpoint:+ *+ * reasoning_effort: 'high' -> MARKER_THINK_OFF+ * chat_template_kwargs: {enable_thinking:true} -> MARKER_THINK_ON+ * chat_template_kwargs: {enable_thinking:false} -> MARKER_THINK_OFF+ *+ * and a /v1/chat/completions carrying reasoning_effort answered 200, so the+ * existing walk-down ladder never engaged and nothing ever complained. The+ * same kwarg against the model's OWN template (Qwen 2.5, which never reads+ * the variable) rendered a byte-identical prompt, so sending it is free where+ * it is not used.+ *+ * Run: npx vitest run src/api/providers/__tests__/openai-template-thinking.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++const streamBody = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n'++let sent: { url: string; body: Record<string, any> }[]+/** Status the fake server answers with, one entry per request in order. */+let statuses: number[]++function answer(url: string, init: any) {+ const body = JSON.parse(init.body as string)+ sent.push({ url, body })+ const status = statuses.shift() ?? 200+ if (status !== 200) {+ return new Response(JSON.stringify({ error: { message: 'unknown field' } }), { status })+ }+ if (body.stream) return new Response(streamBody, { status: 200 })+ return new Response(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }), { status: 200 })+}++async function makeProvider(config: Record<string, unknown>) {+ vi.resetModules()+ sent = []+ statuses = []+ vi.doMock('../../backend', () => ({+ localFetch: vi.fn(async (url: string, init: any) => answer(url, init)),+ localFetchStream: vi.fn(async (url: string, init: any) => answer(url, init)),+ backendCall: vi.fn(),+ isPrivateOrLanHost: (host: string) => host === 'localhost' || host === '127.0.0.1',+ isDirectFetchAllowed: () => true,+ hostnameOf: (url: string) => new URL(url).hostname,+ ensureProxyAllowsHost: vi.fn(),+ isTauri: () => false,+ }))+ vi.doMock('../../builtin-ensure', () => ({+ ensureBuiltinEngineAlive: vi.fn(),+ explainDeadEngine: (e: unknown) => e,+ explainEngineTransportMessage: (m: string) => m,+ isManagedBuiltinSlot: () => false,+ }))+ const mod = await import('../openai-provider')+ return new mod.OpenAIProvider(config as any)+}++const BUILTIN = {+ id: 'openai', name: 'Built-in Engine', apiKey: '', enabled: true,+ baseUrl: 'http://127.0.0.1:8127/v1', isLocal: true, managed: true,+}+const CLOUD = {+ id: 'openai', name: 'OpenAI', apiKey: 'sk-test', enabled: true,+ baseUrl: 'https://api.openai.com/v1', isLocal: false,+}++async function drain(gen: AsyncGenerator<any>) {+ for await (const _ of gen) { /* the fetch only fires on the first next() */ }+}++beforeEach(() => { vi.spyOn(globalThis, 'fetch').mockImplementation(((url: any, init: any) => answer(String(url), init)) as any) })+afterEach(() => {+ vi.doUnmock('../../backend')+ vi.doUnmock('../../builtin-ensure')+ vi.restoreAllMocks()+ vi.resetModules()+})++describe('the built-in engine is told to think', () => {+ it('Thinking ON puts enable_thinking:true on the wire', async () => {+ const p = await makeProvider(BUILTIN)+ await drain(p.chatStream('kw-on', [{ role: 'user', content: 'hi' }], { thinking: true }))+ expect(sent[0].body.chat_template_kwargs).toEqual({ enable_thinking: true })+ })++ it('Thinking OFF puts enable_thinking:false on the wire', async () => {+ const p = await makeProvider(BUILTIN)+ await drain(p.chatStream('kw-off', [{ role: 'user', content: 'hi' }], { thinking: false }))+ expect(sent[0].body.chat_template_kwargs).toEqual({ enable_thinking: false })+ })++ it('the tool turn carries it too, not just plain chat', async () => {+ const p = await makeProvider(BUILTIN)+ await p.chatWithTools('kw-tools', [{ role: 'user', content: 'hi' }], [], { thinking: true })+ expect(sent[0].body.chat_template_kwargs).toEqual({ enable_thinking: true })+ })++ it('reasoning_effort still rides along, so a template-less local server keeps working', async () => {+ const p = await makeProvider(BUILTIN)+ await drain(p.chatStream('kw-both', [{ role: 'user', content: 'hi' }], { thinking: true }))+ expect(sent[0].body.reasoning_effort).toBe('high')+ })+})++describe('negative control: nobody else gets the field', () => {+ it('a model with no declared think capability sends no kwargs at all', async () => {+ const p = await makeProvider(BUILTIN)+ await drain(p.chatStream('kw-undef', [{ role: 'user', content: 'hi' }], {}))+ expect('chat_template_kwargs' in sent[0].body).toBe(false)+ })++ it('a cloud endpoint never sees it, it refuses unknown body fields', async () => {+ const p = await makeProvider(CLOUD)+ await drain(p.chatStream('kw-cloud', [{ role: 'user', content: 'hi' }], { thinking: true }))+ expect('chat_template_kwargs' in sent[0].body).toBe(false)+ expect(sent[0].body.reasoning_effort).toBe('high')+ })+})++describe('a local server that refuses the field is not mistaken for one that cannot think', () => {+ it('the field is dropped on 400 and the thinking knob survives', async () => {+ const p = await makeProvider({ ...BUILTIN, baseUrl: 'http://127.0.0.1:8129/v1' })+ statuses = [400, 200]+ await drain(p.chatStream('kw-refused', [{ role: 'user', content: 'hi' }], { thinking: true }))+ expect(sent).toHaveLength(2)+ expect(sent[0].body.chat_template_kwargs).toEqual({ enable_thinking: true })+ expect('chat_template_kwargs' in sent[1].body).toBe(false)+ expect(sent[1].body.reasoning_effort).toBe('high')+ })++ it('and the refusal is remembered, so the next message pays one request', async () => {+ const p = await makeProvider({ ...BUILTIN, baseUrl: 'http://127.0.0.1:8130/v1' })+ statuses = [400, 200]+ await drain(p.chatStream('kw-mem', [{ role: 'user', content: 'hi' }], { thinking: true }))+ sent = []+ await drain(p.chatStream('kw-mem', [{ role: 'user', content: 'again' }], { thinking: true }))+ expect(sent).toHaveLength(1)+ expect(sent[0].body.reasoning_effort).toBe('high')+ expect('chat_template_kwargs' in sent[0].body).toBe(false)+ })+})diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 87c292b4..0f307fc0 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -281,6 +281,40 @@ export class OpenAIProvider implements ProviderClient {return walked?.off === 'minimal' ? 'minimal' : 'none'}+ /**+ * The thinking knob a backend that renders the MODEL'S OWN template reads.+ *+ * `reasoning_effort` is an OpenAI-API concept. A server that runs the+ * model's Jinja template itself does not have a reasoning mode of its own:+ * the switch lives INSIDE the template, as the `enable_thinking` variable+ * the Qwen, GLM, Nemotron and Hunyuan cards branch on, and it is reached+ * through `chat_template_kwargs`.+ *+ * Counter-check on the bundled engine (lu-llama-server b1-049326a,+ * 2026-08-29), asking /apply-template with a template that prints which+ * branch it took:+ *+ * reasoning_effort: 'high' -> MARKER_THINK_OFF+ * chat_template_kwargs: {enable_thinking:true} -> MARKER_THINK_ON+ *+ * and the chat request carrying reasoning_effort answered 200, so nothing+ * ever complained. That is David's report exactly: the Think button was on,+ * the model did not think, and no thinking block appeared, because nothing+ * on the wire ever asked it to.+ *+ * Only for a backend on this machine or the LAN. A cloud endpoint+ * implements the protocol itself, does not render a template, and the+ * strict ones (api.openai.com) refuse an unknown body field outright.+ * The ladder in sendChat drops the field for a local server that refuses it+ * too, and remembers, so the cost is one round trip once.+ */+ private templateThinkingKwargs(thinking: boolean | undefined): Record<string, unknown> | undefined {+ if (thinking === undefined) return undefined+ if (!this.isLanBackend) return undefined+ if (OpenAIProvider.templateKwargsRefused.has(this.baseUrl)) return undefined+ return { enable_thinking: thinking }+ }+/** Remember a walk, for one direction of the switch only. */private rememberEffort(model: string, lane: 'on' | 'off', value: 'minimal' | 'omit'): void {const key = this.catalogKey(model)@@ -335,6 +369,16 @@ export class OpenAIProvider implements ProviderClient {res = await post()}+ // Its own rung, ahead of both the knob and stream_options: a server that+ // refuses the template kwargs must not be remembered as one that cannot+ // think. Dropped for the whole endpoint once it succeeds without it, so+ // the extra round trip is paid once and not on every message.+ if (!stopped() && refused(res) && 'chat_template_kwargs' in body) {+ delete body.chat_template_kwargs+ res = await post()+ if (res.ok) OpenAIProvider.templateKwargsRefused.add(this.baseUrl)+ }+if (!stopped() && refused(res) && 'stream_options' in body) {delete body.stream_optionsres = await post()@@ -434,6 +478,11 @@ export class OpenAIProvider implements ProviderClient {// endpoint that rejects it is handled by the ladder in sendChat.const effort = this.thinkingEffort(model, options?.thinking)if (effort) body.reasoning_effort = effort+ // The knob a template-rendering backend actually reads. See+ // templateThinkingKwargs for the counter-check that reasoning_effort+ // alone leaves the built-in engine's Think button doing nothing.+ const tmplKwargs = this.templateThinkingKwargs(options?.thinking)+ if (tmplKwargs) body.chat_template_kwargs = tmplKwargs// Ask the server for REAL token usage in a final stream chunk// (choices:[] + usage:{...}). OpenAI, DeepInfra (LU Cloud), Groq, vLLM and// LM Studio all honor stream_options; an endpoint that rejects unknown@@ -596,6 +645,9 @@ export class OpenAIProvider implements ProviderClient {// Same reasoning_effort gate as chatStream.const effort = this.thinkingEffort(model, options?.thinking)if (effort) body.reasoning_effort = effort+ // Same template-kwargs gate as chatStream.+ const tmplKwargs = this.templateThinkingKwargs(options?.thinking)+ if (tmplKwargs) body.chat_template_kwargs = tmplKwargs// Same self-heal as chatStream: agent/tool turns after a Create render// must revive the offloaded built-in engine before hitting its port.@@ -844,6 +896,15 @@ export class OpenAIProvider implements ProviderClient {*/private static effortMemory = new Map<string, { on?: 'omit'; off?: 'minimal' | 'omit' }>()+ /**+ * Endpoints that refused `chat_template_kwargs`. Keyed by base URL, not by+ * model: it is the SERVER that either forwards template kwargs or does not,+ * and llama-server does it for every model it ever loads. Remembered so a+ * backend that dislikes the field pays one extra round trip once instead of+ * one on every message.+ */+ private static templateKwargsRefused = new Set<string>()+/** Live tool-capability answers per endpoint (G37b). Static for the same* reason as probeCache, and TTL-bound like it: an LM Studio reload or an* engine swap with a different template lands within 5 minutes. */