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(sampling): sampling settings per conversation, unberuehrte Werte nicht mitschicken
purplef674ffa32e3d
diff --git a/src/api/__tests__/sampling-reaches-the-cloud-body.test.ts b/src/api/__tests__/sampling-reaches-the-cloud-body.test.tsindex 98a1942f..f93656a9 100644--- a/src/api/__tests__/sampling-reaches-the-cloud-body.test.ts+++ b/src/api/__tests__/sampling-reaches-the-cloud-body.test.ts@@ -1,24 +1,29 @@/**- * Which of the four sampling values really reach an LU Cloud request.+ * Which of the sampling values really reach an LU Cloud request.** A project note said "the temperature slider writes to settings.n and has no* effect in the cloud". Both halves are wrong, and the note is what sent this* check out: there is no `n` anywhere in the app (not in the `Settings`* interface in types/settings.ts:49-52, not in DEFAULT_SETTINGS in* lib/constants.ts:12-15, and `OpenAIChatRequest` in openai-provider.ts:86-100- * has no member it could be assigned to), and temperature goes on the wire.- * SamplingControls writes three keys, all through one setter (the FIELDS table- * for the two sliders, the Max tokens box for the third), and useChat.ts hands- * four to the provider: those three plus Top K from the settings page.+ * has no member it could be assigned to), and temperature goes on the wire,+ * when it differs from the app default.*- * The value that really has no effect in the cloud is TOP K. The OpenAI- * compatible body has no field for it: it is read by ollama-provider.ts:150 and- * anthropic-provider.ts:320 and dropped by openai-provider, which never looks at- * `options.topK` at all, so it works on Ollama and Anthropic and is inert on- * every OpenAI-protocol backend, LU Cloud and this app's own engine included.- * Since R5-13 it is therefore no longer a slider in the per-chat popup, only a- * control on the settings page. Documented on the wire here rather than argued- * about again.+ * R5-10/R5-11 (3.0.1-Liste), David's Entscheid vom 18.09.2026: since then a+ * field NEITHER this chat NOR the Settings page ever moved away from the app+ * default is left off the request entirely (src/lib/sampling.ts,+ * `buildSamplingRequest`), so the model gets the upstream's own default+ * instead of a number LU picked for every model at once. This file used to+ * assert the opposite (defaults always sent); that assertion is what changed,+ * not the fact that a moved slider reaches the wire.+ *+ * The value that has no effect in the cloud regardless is TOP K. The OpenAI+ * compatible body has no field for it: it is read by ollama-provider.ts:150+ * and anthropic-provider.ts:320 and dropped by openai-provider, which never+ * looks at `options.topK` at all, so it works on Ollama and Anthropic and is+ * inert on every OpenAI-protocol backend, LU Cloud and this app's own engine+ * included. Since R5-13 it is not in the per-chat popup at all, only a+ * Settings-page control that useChat.ts still forwards unconditionally.** Asserted on the JSON body of a real request, because a note about a slider* is exactly the kind of claim that source-reading gets wrong twice.@@ -35,6 +40,7 @@ import type { ProviderConfig } from '../providers/types'import { sentJson } from './provider-test-support'import { useSettingsStore } from '../../stores/settingsStore'import { normalizeMaxTokens } from '../../components/chat/SamplingControls'+import { buildSamplingRequest, type SamplingOverrides } from '../../lib/sampling'import { DEFAULT_SETTINGS } from '../../lib/constants'vi.mock('../cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))@@ -51,33 +57,33 @@ const src = (rel: string) =>readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), rel), 'utf8')/**- * The option object useChat.ts:824-838 builds, read out of the live settings- * store exactly as it reads them. Not a copy of four numbers: if a slider ever- * stopped writing the key the send reads, this stops carrying the value.+ * The option object useChat.ts builds for ONE conversation, read out of the+ * live settings store plus that conversation's own overrides, the same+ * `buildSamplingRequest(...)` spread useChat.ts uses, with `topK` forwarded+ * unconditionally alongside it (F3/R5-13: it never was subject to the+ * untouched-omission rule, only the popup that used to show it).*/-function chatOptsFromSettings() {+function chatOptsFromSettings(overrides?: SamplingOverrides) {const s = useSettingsStore.getState().settingsreturn {- temperature: s.temperature,- topP: s.topP,+ ...buildSamplingRequest(s, overrides),topK: s.topK,- maxTokens: s.maxTokens || undefined,}}/** One cloud turn, and the JSON body it put on the wire. */-async function cloudBody(): Promise<OpenAIChatRequest> {+async function cloudBody(overrides?: SamplingOverrides): Promise<OpenAIChatRequest> {const spy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(okStream())const gen = new LuCloudProvider(config).chatStream('zai-org/GLM-5.3',[{ role: 'user' as const, content: 'hello' }],- chatOptsFromSettings(),+ chatOptsFromSettings(overrides),)for await (const _ of gen) { /* the fetch only fires on the first next() */ }return sentJson<OpenAIChatRequest>(spy.mock.calls)}-/** Move the sliders, the way SamplingControls does. */+/** Move the SETTINGS PAGE sliders. */function sliders(patch: Partial<typeof DEFAULT_SETTINGS>) {useSettingsStore.getState().updateSettings(patch)}@@ -87,8 +93,8 @@ beforeEach(() => {})afterEach(() => vi.restoreAllMocks())-describe('what the sliders put on the wire', () => {- it('carries temperature, top_p and max_tokens under the OpenAI names', async () => {+describe('what a moved slider puts on the wire', () => {+ it('carries temperature, top_p and max_tokens under the OpenAI names, moved on the Settings page', async () => {sliders({ temperature: 1.35, topP: 0.42, topK: 7, maxTokens: 512 })const body = await cloudBody()expect(body.temperature).toBe(1.35)@@ -96,9 +102,18 @@ describe('what the sliders put on the wire', () => {expect(body.max_tokens).toBe(512)})+ it('carries the same three when it is THIS CHAT that moved them, not the Settings page', async () => {+ // The Settings page stays at the shipped default the whole time.+ const body = await cloudBody({ temperature: 1.35, topP: 0.42, maxTokens: 512 })+ expect(body.temperature).toBe(1.35)+ expect(body.top_p).toBe(0.42)+ expect(body.max_tokens).toBe(512)+ expect(useSettingsStore.getState().settings.temperature).toBe(DEFAULT_SETTINGS.temperature)+ })+it('carries a temperature of zero, which a truthiness test would eat', async () => {- // The guard is `!== undefined`, and 0 is the one setting on this panel a- // user picks on purpose: it is the whole point of the left end of the slider.+ // The guard is `!== undefined`, and 0 is a value a user picks on purpose:+ // it is the whole point of the left end of the slider.sliders({ temperature: 0 })expect((await cloudBody()).temperature).toBe(0)})@@ -119,14 +134,28 @@ describe('what the sliders put on the wire', () => {expect(Object.keys(useSettingsStore.getState().settings)).not.toContain('n')})- it('COUNTER-CHECK: the defaults are not what was asserted above', async () => {- // Without this, a body that ignored the settings entirely and sent its own- // numbers could pass the first case by coincidence.+ it('puts the NUMBER on the wire for the text the box used to keep', async () => {+ // The field kept `0512` on screen while the store already held 512 (T1+ // nebenfund 5), so the one thing worth proving on a real body is that what+ // leaves the app is a number and not the text somebody typed. `0512` is+ // the exact string the old field produced.+ const body = await cloudBody({ maxTokens: normalizeMaxTokens('0512') })+ expect(body.max_tokens).toBe(512)+ expect(typeof body.max_tokens).toBe('number')+ })+})++/**+ * R5-10/R5-11: the rule the fixliste and David's Entscheid ask for. Nothing+ * NEITHER the chat NOR the Settings page ever moved reaches the wire.+ */+describe('what an UNTOUCHED value does NOT put on the wire', () => {+ it('sends no temperature or top_p at all while both are still at the shipped default', async () => {const body = await cloudBody()- expect(body.temperature).toBe(DEFAULT_SETTINGS.temperature)- expect(body.top_p).toBe(DEFAULT_SETTINGS.topP)- expect(DEFAULT_SETTINGS.temperature).not.toBe(1.35)- expect(DEFAULT_SETTINGS.topP).not.toBe(0.42)+ expect(body.temperature).toBeUndefined()+ expect(body.top_p).toBeUndefined()+ expect('temperature' in body).toBe(false)+ expect('top_p' in body).toBe(false)})it('sends no max_tokens at all on the auto default of 0', async () => {@@ -136,27 +165,31 @@ describe('what the sliders put on the wire', () => {expect((await cloudBody()).max_tokens).toBeUndefined()})- it('puts the NUMBER on the wire for the text the box used to keep', async () => {- // The field kept `0512` on screen while the store already held 512 (T1- // nebenfund 5), so the one thing worth proving on a real body is that what- // leaves the app is a number and not the text somebody typed. `0512` is- // the exact string the old field produced.- sliders({ maxTokens: normalizeMaxTokens('0512') })+ it('NEGATIVKONTROLLE: a chat with its OWN override still sends it, only the untouched fields are omitted', async () => {+ // Counter-check for the two cases above: a body that dropped every+ // sampling field unconditionally would pass them by coincidence.+ const body = await cloudBody({ temperature: 1.9 })+ expect(body.temperature).toBe(1.9)+ expect(body.top_p).toBeUndefined() // still untouched+ })++ it('NEGATIVKONTROLLE: a Settings-page value that really moved is not mistaken for untouched', async () => {+ sliders({ topP: 0.42 })const body = await cloudBody()- expect(body.max_tokens).toBe(512)- expect(typeof body.max_tokens).toBe('number')+ expect(body.top_p).toBe(0.42)+ expect(DEFAULT_SETTINGS.topP).not.toBe(0.42)})})-describe('the panel writes the keys the send reads', () => {- it('the two sliders and the number field write those three settings', () => {+describe('the panel writes to the conversation the send reads', () => {+ it('the two sliders and the number field write through one setter, keyed off the FIELDS table', () => {const panel = src('../../components/chat/SamplingControls.tsx')expect(panel).toMatch(/key: 'temperature'/)expect(panel).toMatch(/key: 'topP'/)- expect(panel).toMatch(/update\(\{ maxTokens:/)+ expect(panel).toMatch(/write\(\{ maxTokens:/)// The slider setter is keyed off the FIELDS table, so it cannot write a// name that is not in it.- expect(panel).toMatch(/update\(\{ \[f\.key\]: Number\(e\.target\.value\) \}\)/)+ expect(panel).toMatch(/write\(\{ \[f\.key\]: Number\(e\.target\.value\) \}\)/)})/**@@ -168,7 +201,6 @@ describe('the panel writes the keys the send reads', () => {it('R5-13: the popup offers no Top K, and names itself the way the web app does', () => {const panel = src('../../components/chat/SamplingControls.tsx')expect(panel).not.toContain("key: 'topK'")- expect(panel).not.toContain('topK: DEFAULT_SETTINGS.topK')expect(panel).toContain('title="Sampling for this chat"')})@@ -180,11 +212,9 @@ describe('the panel writes the keys the send reads', () => {expect(src('../providers/ollama-provider.ts')).toContain('top_k')})- it('and the send reads exactly those four', () => {+ it('and the send reads sampling through buildSamplingRequest, topK straight from settings', () => {const chat = src('../../hooks/useChat.ts')- expect(chat).toMatch(/temperature: settings\.temperature/)- expect(chat).toMatch(/topP: settings\.topP/)+ expect(chat).toMatch(/buildSamplingRequest\(settings, conv\??\.sampling\)/)expect(chat).toMatch(/topK: settings\.topK/)- expect(chat).toMatch(/maxTokens: settings\.maxTokens \|\| undefined/)})})diff --git a/src/components/chat/SamplingControls.tsx b/src/components/chat/SamplingControls.tsxindex 22e3933b..dee98dd5 100644--- a/src/components/chat/SamplingControls.tsx+++ b/src/components/chat/SamplingControls.tsx@@ -1,16 +1,23 @@import { useCallback, useEffect, useId, useRef, useState } from 'react'import { X } from 'lucide-react'import { useSettingsStore } from '../../stores/settingsStore'-import { DEFAULT_SETTINGS } from '../../lib/constants'+import { useChatStore } from '../../stores/chatStore'import { HINWEIS_TEXT } from '../../lib/hinweis'import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'+import { SAMPLING_DEFAULTS, effectiveSampling, samplingIsChanged } from '../../lib/sampling'+import type { SamplingOverrides } from '../../lib/sampling'/**- * Sampling controls next to the composer.+ * Sampling controls next to the composer, scoped to ONE conversation.*- * The values already existed in settings and already reached the request; they- * were just buried in the settings page, where nobody adjusts them per- * conversation. Closed by default so the composer stays quiet.+ * R5-10/R5-11 (3.0.1-Liste): until 18.09.2026 this panel read and wrote the+ * global Settings page, so every open chat shared one temperature and a+ * slider moved in chat A also moved chat B's next request. Two earlier+ * bauers left the rewrite as "braucht Entscheid" (bau/w2ui.md); the values+ * now live on the CONVERSATION (`Conversation.sampling`, src/lib/sampling.ts):+ * a moved slider applies to this chat only, and a chat that never moved a+ * given slider keeps following the Settings page for that field, exactly as+ * every chat did before this change.** Every catalogue model accepts these parameters (measured 2026-09-10, no* request was rejected for one). Reasoning models accept them and react less,@@ -75,7 +82,7 @@ const FIELDS = [* a new number.*/export function normalizeMaxTokens(raw: string): number {- if (raw.trim() === '') return DEFAULT_SETTINGS.maxTokens+ if (raw.trim() === '') return SAMPLING_DEFAULTS.maxTokensreturn Math.max(0, Math.trunc(Number(raw)) || 0)}@@ -99,9 +106,22 @@ export function SamplingControls() {const panelRef = useRef<HTMLDivElement>(null)const panelId = useId()const settings = useSettingsStore((s) => s.settings)- const update = useSettingsStore((s) => s.updateSettings)- const changed = FIELDS.some((f) => settings[f.key] !== DEFAULT_SETTINGS[f.key])- || settings.maxTokens !== DEFAULT_SETTINGS.maxTokens+ const activeId = useChatStore((s) => s.activeConversationId)+ // Only re-renders when THIS chat's own sampling changes, not on every+ // message or on a different chat's edit.+ const overrides = useChatStore((s) =>+ s.activeConversationId+ ? s.conversations.find((c) => c.id === s.activeConversationId)?.sampling+ : undefined+ )+ const setSampling = useChatStore((s) => s.setConversationSampling)+ const resetSampling = useChatStore((s) => s.resetConversationSampling)++ const value = effectiveSampling(settings, overrides)+ const changed = samplingIsChanged(settings, overrides)+ const write = (patch: SamplingOverrides) => {+ if (activeId) setSampling(activeId, patch)+ }/** Give the keyboard back to the trigger, but only while it is still in the* popup: on an outside press the browser is already moving it somewhere the@@ -154,6 +174,11 @@ export function SamplingControls() {panelRef.current?.querySelector<HTMLElement>(FOCUSABLE)?.focus()}, [open])+ // ChatInput only mounts the composer once a conversation exists (the+ // launcher shows instead), so this is "mounted without a chat", not a state+ // a user can actually reach. Nothing to write to means nothing to show.+ if (!activeId) return null+return (<div className="relative text-xs" ref={wrapRef} data-testid="sampling-controls"><button@@ -166,12 +191,12 @@ export function SamplingControls() {// SamplingControls.tsx:82-83), so the button has one name on Windows,// Mac and the web app instead of being read out as a bare number.title="Sampling for this chat"- aria-label={`Sampling: temperature ${settings.temperature}`}+ aria-label={`Sampling: temperature ${value.temperature}`}// Opens, never closes. A trigger that also closed made the panel// disappear under the pointer on the second click.onClick={() => setOpen(true)}>- Sampling: {settings.temperature.toFixed(2)}+ Sampling: {value.temperature.toFixed(2)}{/* Ein geaenderter Regler ist kein Zwischenfall, also traegt derStern den ruhigen Ton und keine eigene Warnfarbe. */}{changed && <span className={`ml-1 ${HINWEIS_TEXT.ruhig}`} title="Changed from the defaults">*</span>}@@ -218,11 +243,11 @@ export function SamplingControls() {min={f.min}max={f.max}step={f.step}- value={settings[f.key]}+ value={value[f.key]}aria-label={f.label}- onChange={(e) => update({ [f.key]: Number(e.target.value) })}+ onChange={(e) => write({ [f.key]: Number(e.target.value) })}/>- <span className="w-10 shrink-0 text-right tabular-nums text-gray-300">{settings[f.key]}</span>+ <span className="w-10 shrink-0 text-right tabular-nums text-gray-300">{value[f.key]}</span></label>))}@@ -233,17 +258,17 @@ export function SamplingControls() {className="min-w-0 flex-1 rounded border border-gray-700 bg-transparent px-1 py-0.5"min={0}step={128}- value={draft ?? String(settings.maxTokens)}+ value={draft ?? String(value.maxTokens)}aria-label="Max tokens"onChange={(e) => {const raw = e.target.valueconst next = normalizeMaxTokens(raw)setDraft(raw.trim() === '' ? raw : String(next))- update({ maxTokens: next })+ write({ maxTokens: next })}}onBlur={() => setDraft(null)}/>- <span className="w-10 shrink-0 text-right text-gray-500">{settings.maxTokens === 0 ? 'auto' : ''}</span>+ <span className="w-10 shrink-0 text-right text-gray-500">{value.maxTokens === 0 ? 'auto' : ''}</span></label><div className="flex items-center justify-between pt-1">@@ -254,13 +279,11 @@ export function SamplingControls() {disabled={!changed}onClick={() => {setDraft(null)- // Resets what this popup shows. Top K is not on it, so this- // button does not silently reach over to the settings page.- update({- temperature: DEFAULT_SETTINGS.temperature,- topP: DEFAULT_SETTINGS.topP,- maxTokens: DEFAULT_SETTINGS.maxTokens,- })+ // Deletes this chat's own values (David's Entscheid,+ // R5-10/R5-11): the chat goes back to following the Settings+ // page, rather than pinning today's defaults into it forever+ // the way a plain "write the defaults" reset would.+ if (activeId) resetSampling(activeId)}}>Resetdiff --git a/src/components/chat/__tests__/sampling-controls.test.tsx b/src/components/chat/__tests__/sampling-controls.test.tsxindex 462289e0..e378caf2 100644--- a/src/components/chat/__tests__/sampling-controls.test.tsx+++ b/src/components/chat/__tests__/sampling-controls.test.tsx@@ -1,16 +1,39 @@// @vitest-environment jsdom-import { beforeEach, describe, expect, it } from 'vitest'+/**+ * R5-10/R5-11 (3.0.1-Liste), David's Entscheid vom 18.09.2026.+ *+ * Until this change the popup read and wrote the GLOBAL settings, so two+ * chats open one after another shared one temperature: moving the slider in+ * chat A silently changed what chat B would send on its next turn. The test+ * that matters most here is the one that watches a SECOND, untouched chat+ * stay exactly where it was.+ */+import { beforeEach, afterEach, describe, expect, it } from 'vitest'import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { useChatStore } from '../../../stores/chatStore'import { useSettingsStore } from '../../../stores/settingsStore'import { DEFAULT_SETTINGS } from '../../../lib/constants'import { SAMPLING_CLOSE_LABEL, SAMPLING_DIALOG_LABEL, SamplingControls } from '../SamplingControls'-const settings = () => useSettingsStore.getState().settings+const conversation = (id: string) => ({+ id,+ title: id,+ messages: [],+ model: 'm',+ systemPrompt: '',+ createdAt: 0,+ updatedAt: 0,+})++const chat = (id = 'c1') => useChatStore.getState().conversations.find((c) => c.id === id)const trigger = () => screen.getByTestId('sampling-trigger')const open = () => fireEvent.click(trigger())beforeEach(() => {- cleanup()+ useChatStore.setState({+ conversations: [conversation('c1'), conversation('c2')] as never,+ activeConversationId: 'c1',+ })useSettingsStore.getState().updateSettings({temperature: DEFAULT_SETTINGS.temperature,topP: DEFAULT_SETTINGS.topP,@@ -19,6 +42,8 @@ beforeEach(() => {})})+afterEach(() => cleanup())+describe('SamplingControls', () => {it('stays collapsed until asked, so the composer stays quiet', () => {render(<SamplingControls />)@@ -27,19 +52,42 @@ describe('SamplingControls', () => {expect(screen.getByTestId('sampling-panel')).toBeTruthy()})- it('shows the live temperature on the closed control', () => {- useSettingsStore.getState().updateSettings({ temperature: 1.15 })+ it('shows nothing while no chat is open, nothing to write to means nothing to show', () => {+ useChatStore.setState({ activeConversationId: null })+ const { container } = render(<SamplingControls />)+ expect(container.firstChild).toBeNull()+ })++ it('shows the temperature THIS chat will use while it is closed', () => {+ useChatStore.getState().setConversationSampling('c1', { temperature: 1.15 })render(<SamplingControls />)expect(screen.getByRole('button', { name: /1\.15/ })).toBeTruthy()})- it('writes each value into the settings the request already reads', () => {+ it('writes the CONVERSATION and never the global settings', () => {render(<SamplingControls />)open()fireEvent.change(screen.getByLabelText('Temperature'), { target: { value: '1.3' } })fireEvent.change(screen.getByLabelText('Top P'), { target: { value: '0.5' } })- expect(settings().temperature).toBe(1.3)- expect(settings().topP).toBe(0.5)+ expect(chat()?.sampling).toEqual({ temperature: 1.3, topP: 0.5 })+ // The whole reason this control moved out of the settings page.+ expect(useSettingsStore.getState().settings.temperature).toBe(DEFAULT_SETTINGS.temperature)+ expect(useSettingsStore.getState().settings.topP).toBe(DEFAULT_SETTINGS.topP)+ })++ it('leaves the OTHER chat exactly as it was', () => {+ render(<SamplingControls />)+ open()+ fireEvent.change(screen.getByLabelText('Temperature'), { target: { value: '1.8' } })+ expect(chat('c1')?.sampling).toEqual({ temperature: 1.8 })+ expect(chat('c2')?.sampling).toBeUndefined()+ })++ it('a chat with no override of its own follows the Settings page', () => {+ useSettingsStore.getState().updateSettings({ temperature: 1.4 })+ render(<SamplingControls />)+ expect(screen.getByRole('button', { name: /1\.4\b/ })).toBeTruthy()+ expect(chat()?.sampling).toBeUndefined()})/**@@ -57,12 +105,10 @@ describe('SamplingControls', () => {})it('R5-13 NEGATIVKONTROLLE: Top K keeps its stored value, this popup only stops showing it', () => {- // The value is not deleted and the settings page keeps offering it. What- // falls away is a control that wrote a number nobody could see again.useSettingsStore.getState().updateSettings({ topK: 55 })render(<SamplingControls />)open()- expect(settings().topK).toBe(55)+ expect(useSettingsStore.getState().settings.topK).toBe(55)expect(screen.getByLabelText('Temperature')).toBeTruthy()})@@ -72,7 +118,6 @@ describe('SamplingControls', () => {* (apps/web/components/chat/SamplingControls.tsx:82-83).*/it('R5-14: the trigger has the same name and title as the web app', () => {- useSettingsStore.getState().updateSettings({ temperature: 0.7 })render(<SamplingControls />)expect(trigger().getAttribute('title')).toBe('Sampling for this chat')expect(trigger().getAttribute('aria-label')).toBe('Sampling: temperature 0.7')@@ -83,18 +128,9 @@ describe('SamplingControls', () => {render(<SamplingControls />)open()fireEvent.change(screen.getByLabelText('Max tokens'), { target: { value: '-500' } })- expect(settings().maxTokens).toBe(0)+ expect(chat()?.sampling?.maxTokens).toBe(0)})- /**- * Max tokens used to APPEND what you typed instead of replacing it: the box- * showed 0, you typed 512, and `0512` stayed on screen (measured on the box,- * T1 nebenfund 5). React keeps a controlled number input in step with a- * loose comparison, so "0512" and the number 512 counted as equal and the- * DOM was never corrected. Typed here one keystroke at a time, each one- * appended to whatever the field really shows, because that is the gesture- * that produced the wrong number.- */const maxTokens = () => screen.getByLabelText('Max tokens') as HTMLInputElementconst typeInto = (field: HTMLInputElement, chars: string) => {for (const c of chars) fireEvent.change(field, { target: { value: field.value + c } })@@ -107,16 +143,16 @@ describe('SamplingControls', () => {expect(field.value).toBe('0')typeInto(field, '512')expect(field.value).toBe('512')- expect(settings().maxTokens).toBe(512)+ expect(chat()?.sampling?.maxTokens).toBe(512)})- it('falls back to the default when max tokens is cleared, and shows it again on blur', () => {- useSettingsStore.getState().updateSettings({ maxTokens: 512 })+ it('falls back to the app default when max tokens is cleared, and shows it again on blur', () => {+ useChatStore.getState().setConversationSampling('c1', { maxTokens: 512 })render(<SamplingControls />)open()const field = maxTokens()fireEvent.change(field, { target: { value: '' } })- expect(settings().maxTokens).toBe(DEFAULT_SETTINGS.maxTokens)+ expect(chat()?.sampling?.maxTokens).toBe(DEFAULT_SETTINGS.maxTokens)expect(field.value).toBe('')fireEvent.blur(field)expect(field.value).toBe(String(DEFAULT_SETTINGS.maxTokens))@@ -126,31 +162,46 @@ describe('SamplingControls', () => {render(<SamplingControls />)open()fireEvent.change(maxTokens(), { target: { value: '512.7' } })- expect(settings().maxTokens).toBe(512)- expect(Number.isInteger(settings().maxTokens)).toBe(true)+ expect(chat()?.sampling?.maxTokens).toBe(512)+ expect(Number.isInteger(chat()?.sampling?.maxTokens)).toBe(true)})- it('marks a changed setup and resets every field at once', () => {- useSettingsStore.getState().updateSettings({ temperature: 1.9, topP: 0.3, maxTokens: 512 })+ it('marks a changed chat, and deletes ALL of its own values on Reset', () => {+ useChatStore.getState().setConversationSampling('c1', { temperature: 1.9, topP: 0.3, maxTokens: 512 })render(<SamplingControls />)expect(screen.getByTitle(/Changed from the defaults/)).toBeTruthy()open()fireEvent.click(screen.getByRole('button', { name: 'Reset' }))- expect(settings().temperature).toBe(DEFAULT_SETTINGS.temperature)- expect(settings().topP).toBe(DEFAULT_SETTINGS.topP)- expect(settings().maxTokens).toBe(DEFAULT_SETTINGS.maxTokens)+ // David's Entscheid: Reset DELETES the chat's own values instead of+ // writing today's defaults into it (see SamplingControls.tsx). Deleted,+ // not "set to defaults": the negative control right below is the whole+ // point of that distinction.+ expect(chat()?.sampling).toBeUndefined()expect(screen.queryByTitle(/Changed from the defaults/)).toBeNull()})+ it('NEGATIVKONTROLLE: after Reset the chat follows LATER Settings page changes, unlike a chat pinned to the old defaults', () => {+ useChatStore.getState().setConversationSampling('c1', { temperature: 1.9 })+ render(<SamplingControls />)+ open()+ fireEvent.click(screen.getByRole('button', { name: 'Reset' }))+ cleanup()+ // The Settings page moves AFTER the reset, and a chat truly following it+ // again must pick the new number up, not stay pinned to the moment Reset+ // was pressed.+ useSettingsStore.getState().updateSettings({ temperature: 1.1 })+ render(<SamplingControls />)+ expect(screen.getByRole('button', { name: /1\.1\b/ })).toBeTruthy()+ expect(chat()?.sampling).toBeUndefined()+ })+it('R5-13: Reset stays inside this popup and leaves Top K alone', () => {- // Top K is not on this panel any more, so a Reset here must not reach over- // to the settings page and undo a value the user set there.- useSettingsStore.getState().updateSettings({ temperature: 1.9, topK: 55 })+ useChatStore.getState().setConversationSampling('c1', { temperature: 1.9 })+ useSettingsStore.getState().updateSettings({ topK: 55 })render(<SamplingControls />)open()fireEvent.click(screen.getByRole('button', { name: 'Reset' }))- expect(settings().temperature).toBe(DEFAULT_SETTINGS.temperature)- expect(settings().topK).toBe(55)+ expect(useSettingsStore.getState().settings.topK).toBe(55)})it('offers no reset while everything is at its default', () => {@@ -159,6 +210,16 @@ describe('SamplingControls', () => {expect((screen.getByRole('button', { name: 'Reset' }) as HTMLButtonElement).disabled).toBe(true)})+ it('offers no reset for a chat that only follows an already-moved Settings page', () => {+ // "Changed" has to mean something is really on the wire, not "this chat+ // has its own record": a chat with no override that merely inherits a+ // moved Settings slider is exactly that case.+ useSettingsStore.getState().updateSettings({ temperature: 1.9 })+ render(<SamplingControls />)+ open()+ expect((screen.getByRole('button', { name: 'Reset' }) as HTMLButtonElement).disabled).toBe(false)+ })+it('says plainly that reasoning models react less, instead of hiding the control', () => {render(<SamplingControls />)open()@@ -172,22 +233,15 @@ describe('SamplingControls', () => {* wegklicken und nicht einfach wieder auf den text klicken zum entfernen, soll* windows mac und webapp ueberall gleich sein."*- * The old panel was a sibling in the composer's flow, so opening it grew the- * prompt window and pushed the text field down. jsdom has no layout at all- * (every box measures 0), so a height comparison here would pass whatever the- * component did. What jsdom CAN answer is the fact the layout follows from:- * whether the panel is in the flow. The pixels are measured for real in- * e2e/sampling-popup.spec.ts, against the bounding box of the composer row.+ * This form is untouched by the R5-10/R5-11 rewrite. HAUSREGEL: a sampling+ * popup with an X, Escape closes it too, unchanged everywhere.*/describe('the sampling popup', () => {it('is a popup over the row, not a panel inside it', () => {render(<SamplingControls />)open()const panel = screen.getByTestId('sampling-panel')- // Out of the flow: nothing around it can be moved by its height.expect(panel.style.position).toBe('absolute')- // Anchored to the top edge of the trigger, so it opens upward over the- // transcript and never downward into the send row.expect(panel.style.bottom).toBe('100%')expect(panel.getAttribute('role')).toBe('dialog')expect(panel.getAttribute('aria-label')).toBe(SAMPLING_DIALOG_LABEL)@@ -229,8 +283,6 @@ describe('the sampling popup', () => {expect(screen.queryByTestId('sampling-panel')).not.toBeNull()})- // The half of David's sentence that is easiest to lose again: a trigger that- // toggles makes the popup vanish under the pointer on the second press.it('does NOT close when the trigger is pressed a second time', () => {render(<SamplingControls />)open()@@ -248,8 +300,7 @@ describe('the sampling popup', () => {open()expect((screen.getByLabelText('Temperature') as HTMLInputElement).value).toBe('1.45')expect((screen.getByLabelText('Max tokens') as HTMLInputElement).value).toBe('2048')- expect(settings().temperature).toBe(1.45)- expect(settings().maxTokens).toBe(2048)+ expect(chat()?.sampling).toEqual({ temperature: 1.45, maxTokens: 2048 })})it('takes the keyboard into the popup and hands it back to the trigger', () => {@@ -269,29 +320,8 @@ describe('the sampling popup', () => {})})-/**- * Closing the popup drops the Max tokens draft, and it does so on purpose.- *- * The draft is a display string: every keystroke has already been written to- * the settings, so there is no unsaved value to lose. What CAN be left behind- * is an emptied box. Cleared, the field shows "" while the store already holds- * the default, and until 2026-09-11 the only thing that ever cleared that- * string again was the field's own onBlur.- *- * Which means the popup was correct by luck. A real user has the keyboard in- * the field while typing, close() moves that keyboard to the trigger before the- * panel unmounts, the blur fires, the draft goes. Take the focus out of the- * picture and the empty box came back on the next open, over a store holding 0.- * Measured that way before the fix: three of these five red.- *- * So the cases below drive the field WITHOUT focusing it, which is exactly what- * the old version got away with. They are not modelling a user; they are- * holding the line that close() clears the draft itself instead of hoping the- * focus rule keeps doing it.- */describe('the Max tokens draft does not outlive the popup', () => {const feld = () => screen.getByLabelText('Max tokens') as HTMLInputElement- /** Deliberately no focus() first: that is the whole point of these cases. */const leeren = () => {fireEvent.change(feld(), { target: { value: '512' } })fireEvent.change(feld(), { target: { value: '' } })@@ -325,8 +355,6 @@ describe('the Max tokens draft does not outlive the popup', () => {expect(feld().value).toBe(String(DEFAULT_SETTINGS.maxTokens))})- // The counterpart, so the fix cannot be "throw the number away as well":- // a value the user really typed is in the settings and comes back.it('but a number that was typed comes back, because it was never a draft', () => {render(<SamplingControls />)open()@@ -334,11 +362,9 @@ describe('the Max tokens draft does not outlive the popup', () => {fireEvent.keyDown(document, { key: 'Escape' })open()expect(feld().value).toBe('2048')- expect(settings().maxTokens).toBe(2048)+ expect(chat()?.sampling?.maxTokens).toBe(2048)})- // And the half onBlur still owns: leaving the field while the popup stays- // open. Losing this would make the onBlur line dead, which it is not.it('leaving the field with the popup still open normalises it too', () => {render(<SamplingControls />)open()diff --git a/src/hooks/useABCompare.ts b/src/hooks/useABCompare.tsindex 3dfaeeb4..2f3fa3c7 100644--- a/src/hooks/useABCompare.ts+++ b/src/hooks/useABCompare.ts@@ -16,6 +16,7 @@ import type { Message } from '../types/chat'import { createThinkStreamSplitter } from '../lib/hermes-stream'import { settleThinking } from '../lib/thinking-stripper'import { isThinkingCompatible } from '../lib/model-compatibility'+import { buildSamplingRequest } from '../lib/sampling'import { runInLane } from '../lib/run-slot'import { laneOf, currentLaneFacts } from '../lib/run-lane-of-model'import { useGenerationStore } from '../stores/generationStore'@@ -107,11 +108,12 @@ export function useABCompare() {)const sendMessages = applySendBudget(chatMessages, budget).messages+ // R5-10/R5-11: Compare has no conversation of its own (compareStore, not+ // chatStore), so there is no per-chat override to read; only the "omit a+ // field still at the app default" half of the rule applies here.const opts = {- temperature: settings.temperature,- topP: settings.topP,+ ...buildSamplingRequest(settings),topK: settings.topK,- maxTokens: settings.maxTokens || undefined,// Bug AA v2.5.0: forward num_ctx override to both A/B sides.contextWindow: settings.contextWindowOverride || undefined,}diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex e07b740c..f48948b8 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -26,6 +26,7 @@ import { runInLane } from '../lib/run-slot'import { laneOf, currentLaneFacts } from '../lib/run-lane-of-model'import { useModelStore } from '../stores/modelStore'import { useSettingsStore } from '../stores/settingsStore'+import { buildSamplingRequest, effectiveSampling } from '../lib/sampling'import { useRAGStore } from '../stores/ragStore'import { retrieveContext } from '../api/rag'import { buildRagSuffix, RETRIEVAL_FAILED_MESSAGE } from '../lib/rag-prompt'@@ -1056,15 +1057,25 @@ export function useAgentChat() {const agentCtx: number = await resolveAgentNumCtx(modelId, providerId, settings.contextWindowOverride, activeModel,)- const chatOptions = {+ // R5-10/R5-11: this chat's own sampling, falling back to the Settings+ // page for whatever field it never touched. buildSamplingRequest+ // omits a field left at the app default; Small-Model Mode below+ // overrides temperature regardless, so it is not subject to that+ // omission (it never was: David's clamp is a correctness measure,+ // not a preference the user can leave untouched).+ const convSampling = store.conversations.find((c) => c.id === convId)?.sampling+ const sampling = buildSamplingRequest(settings, convSampling)+ if (settings.smallModelMode) {// Small-Model Mode (Knob 6): gently clamp temperature for tool turns.// FOLKLORE, not measured — research found NO temperature finding for// tool-calling. A low, low-entropy setting is *plausible* for valid// tool-call JSON, so we cap downward (never raise) rather than force.- temperature: settings.smallModelMode ? Math.min(settings.temperature, 0.3) : settings.temperature,- topP: settings.topP,+ const effectiveTemp = effectiveSampling(settings, convSampling).temperature+ sampling.temperature = Math.min(effectiveTemp, 0.3)+ }+ const chatOptions = {+ ...sampling,topK: settings.topK,- maxTokens: settings.maxTokens || undefined,contextWindow: agentCtx,thinking: thinkOpt as unknown as boolean,reasoningEffort: settings.reasoningEffort,diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 40118ac2..18c0ce6f 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -19,6 +19,7 @@ import { isTooManyMessagesError, halveHistory, TOO_MANY_MESSAGES_MAX_HALVINGS }import { getModelContextCached } from "../api/ollama"import { requestGenerationCancel } from "../api/vram-handoff"import { effectiveContextWindow } from "../lib/context-window"+import { buildSamplingRequest } from "../lib/sampling"import { useAgentChat } from "./useAgentChat"import { parseAgentCommand, parseLoopSpec } from '../lib/agent-commands'import { runCompactForConversation, compactOutcomeMessage, maybeAutoCompact } from '../lib/run-compact-command'@@ -179,10 +180,8 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],}const stream = provider.chatStream(modelId, messages, {- temperature: settings.temperature,- topP: settings.topP,+ ...buildSamplingRequest(settings, conv?.sampling),topK: settings.topK,- maxTokens: settings.maxTokens || undefined,contextWindow: effectiveCtx,thinking: useThinking,signal: abort.signal,@@ -995,10 +994,8 @@ export function useChat() {} catch { /* keep override-or-undefined on failure */ }}const chatOpts = {- temperature: settings.temperature,- topP: settings.topP,+ ...buildSamplingRequest(settings, conv.sampling),topK: settings.topK,- maxTokens: settings.maxTokens || undefined,// num_ctx: real model context (capped) for Ollama, else override-or-none.contextWindow: effectiveCtx,thinking: useThinking,diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex bbaaa638..0aeb515d 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -7,6 +7,7 @@ import { runCompactForConversation, compactOutcomeMessage, maybeAutoCompact } frimport { applyStoredCompaction } from '../lib/compact-summary'import { useSettingsStore } from '../stores/settingsStore'import { useChatStore, flushChatPersist } from '../stores/chatStore'+import { buildSamplingRequest } from '../lib/sampling'import { endTurnDurably } from '../stores/durability'import { getProviderForModel, getProviderIdFromModel } from '../api/providers'import { markToolsUnsupported } from '../api/tool-capability'@@ -1179,9 +1180,18 @@ export function useCodex() {: undefinedconst cxEffort = codexEffort(activeModel)+ // R5-10/R5-11: max tokens follows this chat's own sampling override+ // (or the Settings page, or "auto", buildSamplingRequest's usual+ // rule). Temperature stays fixed at 0.1 regardless: that clamp is for+ // coding precision, not a preference the sampling popup's slider+ // controls, so it is deliberately outside buildSamplingRequest.+ const cxSampling = buildSamplingRequest(+ settings,+ convId ? useChatStore.getState().conversations.find((c) => c.id === convId)?.sampling : undefined,+ )const chatOptions = {temperature: 0.1, // Low temp for coding precision- maxTokens: settings.maxTokens || undefined,+ maxTokens: cxSampling.maxTokens,thinking: thinkOptCx as unknown as boolean,// The Coding Agent is the third caller that builds its own options,// and the one where a forgotten field costs the most tokens.diff --git a/src/lib/__tests__/sampling.test.ts b/src/lib/__tests__/sampling.test.tsnew file mode 100644index 00000000..d342d114--- /dev/null+++ b/src/lib/__tests__/sampling.test.ts@@ -0,0 +1,109 @@+import { describe, it, expect } from 'vitest'+import { DEFAULT_SETTINGS } from '../constants'+import {+ SAMPLING_DEFAULTS,+ buildSamplingRequest,+ clampSampling,+ effectiveSampling,+ samplingIsChanged,+} from '../sampling'++/**+ * R5-10/R5-11 (3.0.1-Liste): the pure request rule, tested for itself before+ * the store and the popup that call it (David's Entscheid, empfohlene+ * Reihenfolge in bau/w2ui.md).+ */+describe('SAMPLING_DEFAULTS', () => {+ it('mirrors the app defaults, so a fresh chat and a fresh settings page agree', () => {+ expect(SAMPLING_DEFAULTS).toEqual({+ temperature: DEFAULT_SETTINGS.temperature,+ topP: DEFAULT_SETTINGS.topP,+ maxTokens: DEFAULT_SETTINGS.maxTokens,+ })+ })+})++describe('effectiveSampling', () => {+ it('falls back to the app default when neither the chat nor the settings page said anything', () => {+ expect(effectiveSampling(SAMPLING_DEFAULTS)).toEqual(SAMPLING_DEFAULTS)+ })++ it('follows the Settings page for a field this chat never touched', () => {+ const settings = { ...SAMPLING_DEFAULTS, temperature: 1.4 }+ expect(effectiveSampling(settings).temperature).toBe(1.4)+ })++ it('lets the CHAT win over the Settings page once it has its own value', () => {+ const settings = { ...SAMPLING_DEFAULTS, temperature: 1.4 }+ expect(effectiveSampling(settings, { temperature: 0.2 }).temperature).toBe(0.2)+ })++ it('resolves each field independently, one touched, one not', () => {+ const settings = { ...SAMPLING_DEFAULTS, temperature: 1.4, topP: 0.5 }+ const value = effectiveSampling(settings, { temperature: 0.2 })+ expect(value.temperature).toBe(0.2) // this chat's own value+ expect(value.topP).toBe(0.5) // still the settings page's value+ })+})++describe('buildSamplingRequest: the rule the fixliste asks for', () => {+ it('sends an empty body once nothing anywhere differs from the app default', () => {+ expect(buildSamplingRequest(SAMPLING_DEFAULTS)).toEqual({})+ expect(buildSamplingRequest(SAMPLING_DEFAULTS, {})).toEqual({})+ })++ it('carries a value this chat moved, even to zero', () => {+ expect(buildSamplingRequest(SAMPLING_DEFAULTS, { temperature: 0 })).toEqual({ temperature: 0 })+ })++ it('carries a value only the Settings page moved, for a chat with no override', () => {+ const settings = { ...SAMPLING_DEFAULTS, topP: 0.42 }+ expect(buildSamplingRequest(settings)).toEqual({ topP: 0.42 })+ })++ it('NEGATIVKONTROLLE: a chat without its own value follows the Settings page, not the app default', () => {+ // If this chat's override were ignored (or the Settings page were), the+ // request would carry the wrong number or none at all.+ const settings = { ...SAMPLING_DEFAULTS, temperature: 1.9 }+ expect(buildSamplingRequest(settings)).toEqual({ temperature: 1.9 })+ expect(buildSamplingRequest(settings, { topP: 0.1 })).toEqual({ temperature: 1.9, topP: 0.1 })+ })++ it('treats max tokens 0 as auto, and omits it the same way a default is omitted', () => {+ expect(buildSamplingRequest(SAMPLING_DEFAULTS, { maxTokens: 0 })).toEqual({})+ expect(buildSamplingRequest(SAMPLING_DEFAULTS, { maxTokens: 512 })).toEqual({ maxTokens: 512 })+ })+})++describe('samplingIsChanged', () => {+ it('is false for two untouched chats sharing the same settings', () => {+ expect(samplingIsChanged(SAMPLING_DEFAULTS)).toBe(false)+ expect(samplingIsChanged(SAMPLING_DEFAULTS, {})).toBe(false)+ })++ it('is true the moment any field would actually go on the wire', () => {+ expect(samplingIsChanged(SAMPLING_DEFAULTS, { topP: 0.3 })).toBe(true)+ })+})++describe('clampSampling', () => {+ it('holds a written value inside its bounds', () => {+ expect(clampSampling({ temperature: 5, topP: -1, maxTokens: -10 })).toEqual({+ temperature: 2,+ topP: 0,+ maxTokens: 0,+ })+ })++ it('drops anything that is not a finite number, keeping the rest', () => {+ expect(clampSampling({ temperature: Number.NaN, topP: 0.4 })).toEqual({ topP: 0.4 })+ })++ it('NEGATIVKONTROLLE: an already-valid value passes through unchanged', () => {+ expect(clampSampling({ temperature: 1.1, topP: 0.6, maxTokens: 2048 })).toEqual({+ temperature: 1.1,+ topP: 0.6,+ maxTokens: 2048,+ })+ })+})diff --git a/src/lib/release-notes.ts b/src/lib/release-notes.tsindex ebac0457..84d582fa 100644--- a/src/lib/release-notes.ts+++ b/src/lib/release-notes.ts@@ -136,6 +136,7 @@ export const RELEASE_NOTES: ReleaseNote[] = ['Sending in one conversation while another is still streaming no longer mixes their text together, and a second agent run no longer gets silently dropped while the first one is still going, both now finish on their own.','The local model runs one conversation at a time, and a chat that has to wait its turn now says so, with a line showing how many chats are ahead of it. Stop works while it is still waiting, and takes it out of the line.','Stop, signing out and quitting the app now reach every conversation, including one that has not started running yet and is only waiting its turn, not just the one open on screen.',+ 'Moving the Temperature, Top P or Max tokens slider now changes that one conversation only, instead of every open chat sharing one value from the Settings page. A chat with no slider of its own still follows Settings, and a field nobody moved anywhere is left out of the request so the model applies its own default.',],},],diff --git a/src/lib/sampling.ts b/src/lib/sampling.tsnew file mode 100644index 00000000..abcbb295--- /dev/null+++ b/src/lib/sampling.ts@@ -0,0 +1,121 @@+import { DEFAULT_SETTINGS } from './constants'+import type { Settings } from '../types/settings'++/**+ * Sampling for one conversation: temperature, top_p and a max output cap.+ *+ * R5-10/R5-11 (3.0.1-Liste), David's Entscheid vom 18.09.2026 (two earlier+ * bauers left this "braucht Entscheid", see bau/w2ui.md):+ *+ * 1. The values belong to the CHAT, not to the app. A moved slider applies to+ * THIS conversation only; a chat that never touched its own slider follows+ * the Settings page value, and the Settings page keeps setting the+ * starting point for every new chat, exactly as before.+ *+ * 2. Only a value that differs from the app default goes on the wire. A field+ * still sitting on the shipped default is left out of the request+ * entirely, so the model answers at whatever the upstream considers+ * normal for it instead of at a number LU picked for every model at once.+ *+ * 3. Top K is deliberately absent here (see SamplingControls.tsx): the+ * OpenAI-compatible body never serialises it, so it stays a page-level+ * setting for the providers that do read it (Ollama, Anthropic; F3 /+ * R5-13). This module never touches it.+ *+ * Mirrors apps/web/lib/sampling.ts (the 3.0.0 VORBILD) field for field, minus+ * the web-only max-tokens warning copy this popup does not carry.+ */++/** What one conversation overrides. A key that is absent was never touched+ * BY THIS CHAT, though it may still differ from the app default via the+ * Settings page, which effectiveSampling below accounts for. */+export interface SamplingOverrides {+ temperature?: number+ topP?: number+ maxTokens?: number+}++/** The three fields as they go into the request options object. */+export type SamplingRequest = SamplingOverrides++/** Where a field with nothing chosen anywhere sits. Same numbers as+ * DEFAULT_SETTINGS, named here so the request rule reads as one idea rather+ * than three lookups. */+export const SAMPLING_DEFAULTS: Required<SamplingOverrides> = {+ temperature: DEFAULT_SETTINGS.temperature,+ topP: DEFAULT_SETTINGS.topP,+ maxTokens: DEFAULT_SETTINGS.maxTokens,+}++const BOUNDS: Record<keyof SamplingOverrides, [number, number]> = {+ temperature: [0, 2],+ topP: [0, 1],+ // A cap above any context window served is the same as no cap; the ceiling+ // here only stops a hand-edited store from putting nonsense on the wire.+ maxTokens: [0, 1_000_000],+}++/** Hold a written value inside its field's range and drop anything that is+ * not a finite number. The store calls this on every write, so a persisted+ * record can only ever hold values the request builder is allowed to+ * forward. */+export function clampSampling(patch: SamplingOverrides): SamplingOverrides {+ const out: SamplingOverrides = {}+ for (const key of Object.keys(BOUNDS) as (keyof SamplingOverrides)[]) {+ const value = patch[key]+ if (value === undefined) continue+ if (typeof value !== 'number' || !Number.isFinite(value)) continue+ const [min, max] = BOUNDS[key]+ out[key] = Math.min(max, Math.max(min, value))+ }+ return out+}++/**+ * The value the control shows for each field: what this chat chose, else the+ * global setting, else the app default. Always three numbers, because a+ * slider needs a position even for a field nobody has touched.+ */+export function effectiveSampling(+ settings: Pick<Settings, 'temperature' | 'topP' | 'maxTokens'>,+ overrides?: SamplingOverrides,+): Required<SamplingOverrides> {+ return {+ temperature: overrides?.temperature ?? settings.temperature ?? SAMPLING_DEFAULTS.temperature,+ topP: overrides?.topP ?? settings.topP ?? SAMPLING_DEFAULTS.topP,+ maxTokens: overrides?.maxTokens ?? settings.maxTokens ?? SAMPLING_DEFAULTS.maxTokens,+ }+}++/**+ * What this turn puts in the request options, and nothing more.+ *+ * A field whose effective value is still the app default is omitted, so the+ * provider never serialises it and the upstream applies its own default. A+ * field the user moved, in this chat or on the Settings page, is present with+ * that number. Max tokens counts 0 as "auto", which is both the app default+ * and the absence of a cap, so it is omitted the same way.+ */+export function buildSamplingRequest(+ settings: Pick<Settings, 'temperature' | 'topP' | 'maxTokens'>,+ overrides?: SamplingOverrides,+): SamplingRequest {+ const value = effectiveSampling(settings, overrides)+ const request: SamplingRequest = {}+ if (value.temperature !== SAMPLING_DEFAULTS.temperature) request.temperature = value.temperature+ if (value.topP !== SAMPLING_DEFAULTS.topP) request.topP = value.topP+ if (value.maxTokens > 0) request.maxTokens = value.maxTokens+ return request+}++/**+ * Whether this chat sends any sampling value at all. Drives the quiet marker+ * on the closed control and the enabled state of Reset, so the marker means+ * exactly one thing: something about this chat is on the wire.+ */+export function samplingIsChanged(+ settings: Pick<Settings, 'temperature' | 'topP' | 'maxTokens'>,+ overrides?: SamplingOverrides,+): boolean {+ return Object.keys(buildSamplingRequest(settings, overrides)).length > 0+}diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.tsindex ea0f9661..4fbf4b63 100644--- a/src/lib/workflow-engine.ts+++ b/src/lib/workflow-engine.ts@@ -8,7 +8,9 @@import { useModelStore } from '../stores/modelStore'import { errorText } from '../types/json-guards'import { useSettingsStore } from '../stores/settingsStore'+import { useChatStore } from '../stores/chatStore'import { useMemoryStore } from '../stores/memoryStore'+import { buildSamplingRequest } from './sampling'// Audit W-T2: hier stand `from '../api/tool-registry'` — der als @deprecated// markierte Kompatibilitäts-Shim. Der zieht das ganze MCP-Barrel herein// (api/mcp/index.ts, das registerBuiltinTools ausführt), und weil@@ -235,6 +237,12 @@ export class WorkflowEngine {]const { settings } = useSettingsStore.getState()+ // R5-10/R5-11: this run's own conversation may have its own sampling; a+ // field neither it nor the Settings page ever moved stays off the wire.+ const convSampling = useChatStore.getState().conversations.find(+ (c) => c.id === this.conversationId,+ )?.sampling+ const sampling = buildSamplingRequest(settings, convSampling)let output = ''if (step.allowedTools && step.allowedTools.length === 0) {@@ -244,7 +252,7 @@ export class WorkflowEngine {// hermes branch here posted to Ollama unconditionally (G32b), which// 404s the moment the model lives on LM Studio.const stream = provider.chatStream(modelToUse, messages, {- temperature: settings.temperature,+ temperature: sampling.temperature,// Bug AA v2.5.0 — keep num_ctx override for workflow steps too.contextWindow: settings.contextWindowOverride || undefined,signal: this.abortController.signal,@@ -262,7 +270,7 @@ export class WorkflowEngine {if (strategy === 'native') {const turn = await provider.chatWithTools(modelToUse, messages, allowedTools, {- temperature: settings.temperature,+ temperature: sampling.temperature,// Bug AA v2.5.0 — same num_ctx override on tool calls.contextWindow: settings.contextWindowOverride || undefined,signal: this.abortController.signal,@@ -294,7 +302,7 @@ export class WorkflowEngine {modelToUse,hermesMessages.map(m => ({ role: m.role, content: m.content })),{- temperature: settings.temperature,+ temperature: sampling.temperature,contextWindow: settings.contextWindowOverride || undefined,signal: this.abortController.signal,},diff --git a/src/stores/__tests__/chatStore-sampling.test.ts b/src/stores/__tests__/chatStore-sampling.test.tsnew file mode 100644index 00000000..e64e8fac--- /dev/null+++ b/src/stores/__tests__/chatStore-sampling.test.ts@@ -0,0 +1,90 @@+/**+ * R5-10/R5-11 (3.0.1-Liste), David's Entscheid vom 18.09.2026: sampling per+ * conversation, stored additively on `Conversation.sampling` (types/chat.ts).+ *+ * No store `version` bump: the field is optional and additive, so a chat+ * persisted by an older build simply has no `sampling` key and reads as+ * "follow the Settings page", exactly the fallback effectiveSampling already+ * gives an absent override. `migratePersistedChat` therefore has nothing to+ * do for it, and the test below proves that directly, the same way+ * chatStore's own `merge` comment argues for skipping a version bump.+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { useChatStore, migratePersistedChat } from '../chatStore'+import type { Conversation } from '../../types/chat'++const conv = (id: string, extra: Partial<Conversation> = {}): Conversation => ({+ id,+ title: id,+ messages: [],+ model: 'm',+ systemPrompt: '',+ createdAt: 0,+ updatedAt: 0,+ ...extra,+})++beforeEach(() => {+ useChatStore.setState({ conversations: [], activeConversationId: null })+})++describe('chatStore: old persisted chats load unchanged', () => {+ it('a legacy conversation with no `sampling` key survives migratePersistedChat byte for byte', () => {+ const legacy = { conversations: [conv('c1'), conv('c2')] }+ const before = JSON.stringify(legacy)+ const migrated = migratePersistedChat(structuredClone(legacy)) as typeof legacy+ expect(JSON.stringify(migrated)).toBe(before)+ expect(migrated.conversations[0]).not.toHaveProperty('sampling')+ })++ it('NEGATIVKONTROLLE: a conversation that DOES carry sampling is left as-is too, nothing rewrites it', () => {+ const withSampling = { conversations: [conv('c1', { sampling: { temperature: 1.2 } })] }+ const migrated = migratePersistedChat(structuredClone(withSampling)) as typeof withSampling+ expect(migrated.conversations[0].sampling).toEqual({ temperature: 1.2 })+ })++ it('a rehydrated legacy chat follows the Settings page for every field, having none of its own', () => {+ useChatStore.setState({ conversations: [conv('c1')], activeConversationId: 'c1' })+ const legacyChat = useChatStore.getState().conversations[0]+ expect(legacyChat.sampling).toBeUndefined()+ })+})++describe('chatStore: setConversationSampling / resetConversationSampling', () => {+ beforeEach(() => {+ useChatStore.setState({ conversations: [conv('c1'), conv('c2')], activeConversationId: 'c1' })+ })++ const chat = (id: string) => useChatStore.getState().conversations.find((c) => c.id === id)++ it('merges a patch into ONE conversation, leaving the other alone', () => {+ useChatStore.getState().setConversationSampling('c1', { temperature: 1.3 })+ expect(chat('c1')?.sampling).toEqual({ temperature: 1.3 })+ expect(chat('c2')?.sampling).toBeUndefined()+ })++ it('merges rather than replaces: a second patch keeps the first field', () => {+ useChatStore.getState().setConversationSampling('c1', { temperature: 1.3 })+ useChatStore.getState().setConversationSampling('c1', { topP: 0.2 })+ expect(chat('c1')?.sampling).toEqual({ temperature: 1.3, topP: 0.2 })+ })++ it('clamps out-of-range and non-finite values on write', () => {+ useChatStore.getState().setConversationSampling('c1', { temperature: 99, topP: Number.NaN })+ expect(chat('c1')?.sampling).toEqual({ temperature: 2 })+ })++ it('resetConversationSampling DELETES the field rather than writing defaults into it', () => {+ useChatStore.getState().setConversationSampling('c1', { temperature: 1.9, topP: 0.3 })+ useChatStore.getState().resetConversationSampling('c1')+ expect(chat('c1')).not.toHaveProperty('sampling')+ })++ it('NEGATIVKONTROLLE: reset only touches the named conversation', () => {+ useChatStore.getState().setConversationSampling('c1', { temperature: 1.9 })+ useChatStore.getState().setConversationSampling('c2', { temperature: 0.4 })+ useChatStore.getState().resetConversationSampling('c1')+ expect(chat('c1')?.sampling).toBeUndefined()+ expect(chat('c2')?.sampling).toEqual({ temperature: 0.4 })+ })+})diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 7a255097..67868c14 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -3,6 +3,7 @@ import { persist } from 'zustand/middleware'import { v4 as uuid } from 'uuid'import type { Conversation, Message, ChatArtifact, CompactionRecord } from '../types/chat'import type { AgentBlock } from '../types/agent-mode'+import { clampSampling, type SamplingOverrides } from '../lib/sampling'import { idbStorage } from '../lib/idbStorage'import { coalescedJSONStorage } from '../lib/coalescedStorage'import { migrateBlockInPlace } from '../api/agents/block-helpers'@@ -109,6 +110,15 @@ interface ChatState {* persona's systemPrompt without changing the global Settings* selection. */setConversationPersonaEnabled: (id: string, enabled: boolean) => void+ /** R5-10/R5-11 (3.0.1-Liste): merge sampling values into ONE chat. Only the+ * keys in the patch move, the rest keep whatever the chat already had,+ * which is how "send only what THIS chat changed" survives a second visit+ * to the popup. */+ setConversationSampling: (id: string, patch: SamplingOverrides) => void+ /** Delete this chat's own sampling values entirely (the popup's Reset),+ * so it goes back to following the Settings page instead of pinning+ * today's defaults into the conversation forever. */+ resetConversationSampling: (id: string) => void/** Group chat v1: the models that answer in turn (capped at 4). */setGroupModels: (id: string, models: string[]) => void/** Write the model the open chat is actually running on.@@ -325,6 +335,25 @@ export const useChatStore = create<ChatState>()(),})),+ setConversationSampling: (id, patch) =>+ set((state) => ({+ conversations: state.conversations.map((c) =>+ c.id === id+ ? { ...c, sampling: { ...c.sampling, ...clampSampling(patch) }, updatedAt: Date.now() }+ : c+ ),+ })),++ resetConversationSampling: (id) =>+ set((state) => ({+ conversations: state.conversations.map((c) => {+ if (c.id !== id) return c+ const next = { ...c, updatedAt: Date.now() }+ delete next.sampling+ return next+ }),+ })),+setGroupModels: (id, models) =>set((state) => ({conversations: state.conversations.map((c) =>diff --git a/src/types/chat.ts b/src/types/chat.tsindex 5703e1f6..1a7f95d2 100644--- a/src/types/chat.ts+++ b/src/types/chat.ts@@ -1,4 +1,5 @@import type { AgentBlock } from './agent-mode'+import type { SamplingOverrides } from '../lib/sampling'export type Role = 'user' | 'assistant' | 'system' | 'tool'@@ -153,6 +154,14 @@ export interface Conversation {* been compacted. Both read as "no compaction", which is what they are.*/compactions?: CompactionRecord[]+ /** R5-10/R5-11 (3.0.1-Liste): sampling this chat has chosen for itself.+ * Additive and optional, so a chat persisted before this field existed+ * loads unchanged and needs no store migration. Absent means "follow the+ * Settings page", not "use the app default"; src/lib/sampling.ts has the+ * full rule. Reset in the popup deletes this field rather than writing the+ * defaults into it, so a reset chat keeps following the Settings page even+ * if its sliders move again afterwards. */+ sampling?: SamplingOverridescreatedAt: numberupdatedAt: number}