Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(ai): set temperature, top-p and thinking defaults on every local provider

Adam Eivya6bde19f00af
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index a669b767e2..98d2a55d2e 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -7,7 +7,7 @@ import { processScreenshotUploads, processAttachmentUploads } from '../../servic
import { ATTACHMENT_ACCEPT } from '../../utils/fileUpload';
import FilePickerButton from '../ui/FilePickerButton';
import { formatBytes } from '../../utils/formatters';
-import { effectiveModelFor, effortAwareModelOptions, effortSurvivingModel, isTuiProvider, isCliProvider, isProcessProvider, isCodexProvider, isOpencodeOllamaProvider, seedModelEffort } from '../../utils/providers';
+import { effectiveModelFor, effortAwareModelOptions, effortSurvivingModel, isTuiProvider, isCliProvider, isProcessProvider, isCodexProvider, isOpencodeLocalProvider, generationControlsFor, seedModelEffort } from '../../utils/providers';
import { DEFAULT_PR_COMPLETION, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, PR_COMPLETION_OPTIONS, prCompletionOption } from './constants';
import { clickableProps } from '../../lib/a11yKeyboard';
import { slashdoLabel } from '../../lib/slashdoCatalog';
@@ -715,21 +715,26 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
className="sm:w-40 w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"
/>
</div>
- {isOpencodeOllamaProvider(selectedProvider) && (
+ {isOpencodeLocalProvider(selectedProvider) && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <div>
- <label htmlFor="task-thinking" className="sr-only">Thinking</label>
- <select
- id="task-thinking"
- value={newTask.thinking}
- onChange={e => setNewTask(t => ({ ...t, thinking: e.target.value }))}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"
- >
- <option value="">Provider thinking default</option>
- <option value="true">Thinking on</option>
- <option value="false">Thinking off</option>
- </select>
- </div>
+ {/* OrcaRouter fronts cloud models that own their own reasoning
+ switch, so it is the one local-namespace wrapper with no
+ thinking toggle to override. */}
+ {generationControlsFor(selectedProvider)?.thinking && (
+ <div>
+ <label htmlFor="task-thinking" className="sr-only">Thinking</label>
+ <select
+ id="task-thinking"
+ value={newTask.thinking}
+ onChange={e => setNewTask(t => ({ ...t, thinking: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"
+ >
+ <option value="">Provider thinking default</option>
+ <option value="true">Thinking on</option>
+ <option value="false">Thinking off</option>
+ </select>
+ </div>
+ )}
<div>
<label htmlFor="task-temperature" className="sr-only">Temperature</label>
<input
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 694da240a5..252d2dec0a 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -949,7 +949,7 @@ export function LocalLlmTab() {
Both backends can be installed and running at the same time — <span className="text-gray-400">Default</span> just sets which one PortOS routes local-LLM runs to. Use <span className="text-gray-400">Import from…</span> to copy or link models between them without re-downloading.
</p>
<p className="text-xs text-gray-500">
- For Ollama coding agents, configure the shared <Link to="/ai" className="text-port-accent hover:underline">temperature and thinking defaults in AI Providers</Link>. Native Ollama and OpenCode receive both controls; Claude/Ollama honors the thinking toggle. New local providers start at temperature 0.6.
+ For local coding agents, configure the shared <Link to="/ai" className="text-port-accent hover:underline">temperature, top-p and thinking defaults in AI Providers</Link>. Every local OpenAI-compatible backend receives them — Ollama, llama.cpp and MTPLX, whether reached directly or through an OpenCode CLI/TUI wrapper. New local providers start at temperature 0.6.
</p>
{loading && !status ? (
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index 45b55c2be3..03a2a1bb01 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -99,9 +99,9 @@ describe('LocalLlmTab backend disable state', () => {
});
describe('LocalLlmTab installed models', () => {
- it('links to the shared Ollama generation controls', async () => {
+ it('links to the shared local generation controls', async () => {
await renderTab();
- expect(screen.getByRole('link', { name: /temperature and thinking defaults/i }).getAttribute('href')).toBe('/ai');
+ expect(screen.getByRole('link', { name: /temperature, top-p and thinking defaults/i }).getAttribute('href')).toBe('/ai');
});
it('lets a long model id wrap instead of truncating it', async () => {
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index d4953dd167..b662eae465 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -4,7 +4,7 @@ import { AlertTriangle } from 'lucide-react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
-import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isGrokBuildCli, isLocalEndpoint, isLocalInstanceProvider, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, isOrcaRouterBackedProvider, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';
+import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isGrokBuildCli, isLocalEndpoint, isLocalInstanceProvider, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, isOrcaRouterBackedProvider, generationControlsFor, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import BrailleSpinner from '../components/BrailleSpinner';
@@ -82,6 +82,7 @@ const PROVIDER_FIELD_RANGES = {
contextWindow: { min: 512, max: 2097152 },
numCtx: { min: 512, max: 1048576 },
temperature: { min: 0, max: 2 },
+ topP: { min: 0, max: 1 },
};
const rangeMessage = (label, { min, max }, unit = '') =>
@@ -859,6 +860,9 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
fallbackModel: provider?.fallbackModel || '',
numCtx: provider?.numCtx ?? '',
temperature: provider?.temperature ?? 0.6,
+ // Blank means "don't send a top_p" — the backend keeps its own default,
+ // which is NOT the same as pinning 1. No numeric seed here for that reason.
+ topP: provider?.topP ?? '',
thinking: provider?.thinking ?? true,
contextWindow: provider?.contextWindow ?? '',
timeout: provider?.timeout || 300000,
@@ -941,6 +945,11 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
// `ollamaBacked` marker that identifies opencode-ollama (whose envVars carry
// no ANTHROPIC_BASE_URL) is not a form field.
const showsNumCtx = formData.type === 'api' || isOllamaBackedProvider(capabilityProvider);
+ // Default sampling/reasoning controls, offered only for the backends PortOS
+ // actually forwards them to (see `generationControlsFor`). Reads
+ // `capabilityProvider` for the same reason `showsNumCtx` does: `llamaBacked`
+ // and friends are record markers, not form fields.
+ const generationControls = generationControlsFor(capabilityProvider);
const parseOptionalIntField = (value) => {
const input = String(value ?? '').trim();
if (!input) return null;
@@ -993,13 +1002,16 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
if (outOfRange(formData.contextWindow, PROVIDER_FIELD_RANGES.contextWindow)) {
return { tab: 'generation', message: rangeMessage('Planning Window', PROVIDER_FIELD_RANGES.contextWindow, 'tokens') };
}
- if (showsNumCtx) {
- if (outOfRange(formData.numCtx, PROVIDER_FIELD_RANGES.numCtx)) {
- return { tab: 'generation', message: rangeMessage('Local num_ctx', PROVIDER_FIELD_RANGES.numCtx, 'tokens') };
- }
+ if (showsNumCtx && outOfRange(formData.numCtx, PROVIDER_FIELD_RANGES.numCtx)) {
+ return { tab: 'generation', message: rangeMessage('Local num_ctx', PROVIDER_FIELD_RANGES.numCtx, 'tokens') };
+ }
+ if (generationControls) {
if (outOfRange(formData.temperature, PROVIDER_FIELD_RANGES.temperature)) {
return { tab: 'generation', message: rangeMessage('Temperature', PROVIDER_FIELD_RANGES.temperature) };
}
+ if (outOfRange(formData.topP, PROVIDER_FIELD_RANGES.topP)) {
+ return { tab: 'generation', message: rangeMessage('Top-P', PROVIDER_FIELD_RANGES.topP) };
+ }
}
return null;
};
@@ -1028,8 +1040,22 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
headlessArgs: formData.headlessArgs ? formData.headlessArgs.split(' ').filter(Boolean) : [],
contextWindow: parseOptionalIntField(formData.contextWindow),
numCtx: showsNumCtx ? parseOptionalIntField(formData.numCtx) : null,
- ...(showsNumCtx ? { temperature: parseNumberField(formData.temperature), thinking: formData.thinking } : {}),
+ // Blank Top-P clears back to "let the backend pick" (null) rather than
+ // `undefined`, which the server's spread-merge would read as "unchanged"
+ // and leave the old pin in place.
+ ...(generationControls
+ ? { temperature: parseNumberField(formData.temperature), topP: parseNumberField(formData.topP) ?? null }
+ : {}),
};
+ // `data` opens as a spread of the WHOLE form, so a control this provider
+ // doesn't offer rides along regardless of the branch above — and `topP: ''`
+ // isn't even a number the server schema accepts. Drop what can't be used;
+ // the server merges by spread, so anything already stored is left alone.
+ if (!generationControls) {
+ delete data.temperature;
+ delete data.topP;
+ }
+ if (!generationControls?.thinking) delete data.thinking;
// The generation/fallback pickers filter out embedding-only models, so a
// stored embedding (from an older config) would be hidden in the UI yet
// still spread into `data` and silently persisted on an unrelated edit.
@@ -1476,7 +1502,7 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
value={formData.effort}
onChange={(effort) => setFormData(prev => ({ ...prev, effort }))}
label="Default Effort"
- hint={showsNumCtx
+ hint={generationControls
? 'Reasoning effort used when a run does not specify one — passed to the local model as reasoningEffort.'
: 'Reasoning effort used when a run does not specify one.'}
/>
@@ -1547,9 +1573,14 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
</div>
</div>
- {showsNumCtx && (
+ {generationControls && (
<div className="border-t border-port-border pt-4 mt-4">
- <h4 className="text-sm font-medium text-gray-300 mb-3">Ollama Generation</h4>
+ <h4 className="text-sm font-medium text-gray-300 mb-3">Generation Defaults</h4>
+ <p className="text-xs text-gray-500 mb-3">
+ Applied to every run this provider starts — HTTP, CLI, and TUI alike. OpenCode wrappers
+ receive them as its <code className="text-gray-400">agent.build</code> options; a task can
+ still override temperature and thinking for one run.
+ </p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<FormField label="Temperature">
<input
@@ -1563,24 +1594,43 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
/>
<p className="text-xs text-gray-500 mt-1">Defaults to 0.6 for local Ollama agent runs.</p>
</FormField>
- {/* Hand-rolled rather than FormField: the control is a
- checkbox inside its own <label>, so FormField's
- "bind the label to the first child" rule would point
- htmlFor at that <label> instead of the input. */}
- <div>
- <span className="block text-sm text-gray-400 mb-1">Thinking mode</span>
- <label htmlFor="provider-thinking" className="flex items-center gap-2 min-h-10 text-sm text-gray-300">
- <input
- id="provider-thinking"
- type="checkbox"
- checked={formData.thinking}
- onChange={(e) => setFormData(prev => ({ ...prev, thinking: e.target.checked }))}
- className="w-4 h-4 rounded border-port-border bg-port-bg"
- />
- Enable model reasoning
- </label>
- <p className="text-xs text-gray-500 mt-1">Sent to thinking-capable Ollama models; unsupported models ignore it.</p>
- </div>
+ <FormField label="Top-P">
+ <input
+ type="number"
+ min={PROVIDER_FIELD_RANGES.topP.min}
+ max={PROVIDER_FIELD_RANGES.topP.max}
+ step="0.05"
+ value={formData.topP}
+ onChange={(e) => setFormData(prev => ({ ...prev, topP: e.target.value }))}
+ placeholder="Backend default"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ />
+ <p className="text-xs text-gray-500 mt-1">Nucleus sampling. Leave blank to send no top_p at all.</p>
+ </FormField>
+ {generationControls.thinking && (
+ /* Hand-rolled rather than FormField: the control is a
+ checkbox inside its own <label>, so FormField's
+ "bind the label to the first child" rule would point
+ htmlFor at that <label> instead of the input. */
+ <div>
+ <span className="block text-sm text-gray-400 mb-1">Thinking mode</span>
+ <label htmlFor="provider-thinking" className="flex items-center gap-2 min-h-10 text-sm text-gray-300">
+ <input
+ id="provider-thinking"
+ type="checkbox"
+ checked={formData.thinking}
+ onChange={(e) => setFormData(prev => ({ ...prev, thinking: e.target.checked }))}
+ className="w-4 h-4 rounded border-port-border bg-port-bg"
+ />
+ Enable model reasoning
+ </label>
+ <p className="text-xs text-gray-500 mt-1">
+ Ollama receives its native <code className="text-gray-400">think</code> flag; llama.cpp and
+ MTPLX get <code className="text-gray-400">enable_thinking</code> through the chat template.
+ Models without a reasoning mode ignore it.
+ </p>
+ </div>
+ )}
</div>
</div>
)}
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index 51ec23a7c6..b04281131c 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -673,6 +673,79 @@ describe('provider reasoning defaults', () => {
expect.objectContaining({ effort: 'high', thinking: false }),
));
});
+
+ // The OpenCode llama TUI is the headline case: `llamaBacked` is a record
+ // marker, not a form field, and the block used to be gated on the Ollama
+ // check alone — so the provider that most needs a temperature had none.
+ it('offers effort, temperature, top-p and thinking on a llama.cpp-backed OpenCode TUI', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{
+ id: 'opencode-llama-tui',
+ name: 'OpenCode llama TUI',
+ type: 'tui',
+ command: 'opencode',
+ args: [],
+ enabled: true,
+ llamaBacked: true,
+ models: ['qwen3.8-27b'],
+ defaultModel: 'qwen3.8-27b',
+ effort: '',
+ thinking: true,
+ envVars: {},
+ }],
+ activeProvider: 'opencode-llama-tui',
+ });
+
+ renderPage();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
+ await openEditorTab('Generation');
+
+ fireEvent.change(await screen.findByLabelText('Default Effort'), { target: { value: 'high' } });
+ fireEvent.change(screen.getByLabelText('Temperature'), { target: { value: '0.2' } });
+ fireEvent.change(screen.getByLabelText('Top-P'), { target: { value: '0.9' } });
+ expect(screen.getByLabelText('Enable model reasoning')).toBeChecked();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalledWith(
+ 'opencode-llama-tui',
+ expect.objectContaining({ effort: 'high', temperature: 0.2, topP: 0.9, thinking: true }),
+ ));
+ });
+
+ // A stored default PortOS never forwards is a control that lies. The editor
+ // hides the block for cloud providers, and the payload must not carry the
+ // form's seeded values either (`topP: ''` isn't even a valid number).
+ it('sends no generation defaults for a cloud API provider', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{
+ id: 'anthropic',
+ name: 'Anthropic',
+ type: 'api',
+ endpoint: 'https://api.anthropic.com/v1',
+ enabled: true,
+ models: ['claude-opus-5'],
+ defaultModel: 'claude-opus-5',
+ envVars: {},
+ }],
+ activeProvider: 'anthropic',
+ });
+
+ renderPage();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
+ await openEditorTab('Generation');
+
+ expect(screen.queryByLabelText('Temperature')).toBeNull();
+ expect(screen.queryByLabelText('Enable model reasoning')).toBeNull();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalled());
+ const payload = api.updateProvider.mock.calls[0][1];
+ expect(payload).not.toHaveProperty('temperature');
+ expect(payload).not.toHaveProperty('topP');
+ expect(payload).not.toHaveProperty('thinking');
+ });
});
describe('provider editor deep links', () => {
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 3f06777fdc..5337efb317 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -198,20 +198,29 @@ export const CLAUDE_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhi
export const CODEX_EFFORT_LEVELS = Object.freeze(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
export const ANTIGRAVITY_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
// OpenCode passes this through as `reasoningEffort` to its configured local
-// provider. Ollama's OpenAI-compatible API accepts this narrow ladder for
+// provider. The OpenAI-compatible local backends accept this narrow ladder for
// thinking models; the broader vendor-CLI ladders are not portable here.
-export const OPENCODE_OLLAMA_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
+export const OPENCODE_LOCAL_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
// Cursor Agent. MIRROR of `CURSOR_EFFORT_LEVELS`. Cursor takes NO `--effort`
// flag — the server folds the level into the model id as Cursor's own variant
// syntax (`gpt-5[effort=max]`) — but the level is still user-pickable, so this
// ladder drives the same selects as every other CLI's.
export const CURSOR_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
-/** True when an OpenCode process provider is backed by the local Ollama daemon. */
-export const isOpencodeOllamaProvider = (provider) =>
+/**
+ * True when an OpenCode process provider runs against one of the local
+ * OpenAI-compatible backends (Ollama / MTPLX / llama.cpp / OrcaRouter) rather
+ * than a vendor cloud model. MIRROR of `isOpencodeProvider(p) &&
+ * getOpencodeLocalProviderNamespace(p)` in server/lib/providerModels.js, which
+ * is exactly what gates the effort ladder there.
+ */
+export const isOpencodeLocalProvider = (provider) =>
(['opencode', 'opencode-tui'].includes(String(provider?.id || '').toLowerCase())
|| commandBasename(provider?.command) === 'opencode')
- && provider?.ollamaBacked === true;
+ && (provider?.ollamaBacked === true
+ || provider?.mtplxBacked === true
+ || provider?.llamaBacked === true
+ || provider?.orcarouterBacked === true);
/**
* Antigravity base-model ↔ effort-suffix split — MIRROR of
@@ -386,7 +395,7 @@ export const seedModelEffort = (provider, model, effort) => {
*/
export const effortLevelsForProvider = (provider, model = null) => {
if (!provider) return null;
- if (isOpencodeOllamaProvider(provider)) return OPENCODE_OLLAMA_EFFORT_LEVELS;
+ if (isOpencodeLocalProvider(provider)) return OPENCODE_LOCAL_EFFORT_LEVELS;
if (isCodexProvider(provider)) return CODEX_EFFORT_LEVELS;
if (isAntigravityProvider(provider)) {
const perModel = model ? antigravityModelEffortLevels(model, provider.models) : null;
@@ -980,6 +989,32 @@ export const isOllamaBackedProvider = (provider) => {
*/
export const isOrcaRouterBackedProvider = (provider) => provider?.orcarouterBacked === true;
+/**
+ * Which default generation controls the provider editor should offer, or null
+ * when the provider has none.
+ *
+ * Only the local OpenAI-compatible backends qualify — Ollama, llama.cpp and
+ * MTPLX (reached directly as an `api` provider, or through an OpenCode CLI/TUI
+ * wrapper), plus the OrcaRouter gateway. A hosted cloud provider is deliberately
+ * excluded: PortOS sends it no sampling fields at all, so offering a stored
+ * temperature there would be a control that silently does nothing.
+ *
+ * `thinking` is false for OrcaRouter, whose upstream models own their own
+ * reasoning switch. MIRROR of `THINKING_STYLE` / `buildAgentGeneration` in
+ * server/lib/opencodeConfig.js and `apiGenerationOptions` in
+ * server/lib/aiToolkit/internal/generationOptions.js; keep in lockstep.
+ * @param {object|null|undefined} provider
+ * @returns {{temperature:boolean, topP:boolean, thinking:boolean}|null}
+ */
+export const generationControlsFor = (provider) => {
+ const orcarouter = isOrcaRouterBackedProvider(provider);
+ const local = isOllamaBackedProvider(provider)
+ || provider?.llamaBacked === true
+ || provider?.mtplxBacked === true;
+ if (!local && !orcarouter) return null;
+ return { temperature: true, topP: true, thinking: !orcarouter };
+};
+
// Environment variables whose names are conventionally credentials. The
// explicit secretEnvVars list remains the primary source, but it is a masking
// list rather than a credential schema — providers may mark optional values
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 5f2472784f..3173150317 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -45,6 +45,7 @@ import {
supportsModelRefresh,
isAntigravityProvider,
effortLevelsForProvider,
+ generationControlsFor,
resolveCliEffort,
CLAUDE_EFFORT_LEVELS,
CODEX_EFFORT_LEVELS,
@@ -123,6 +124,11 @@ describe('effortLevelsForProvider (server mirror)', () => {
['claude code', { id: 'claude-code', command: 'claude' }, CLAUDE_EFFORT_LEVELS],
['codex', { id: 'codex', command: 'codex' }, CODEX_EFFORT_LEVELS],
['OpenCode Ollama', { id: 'opencode-ollama', command: 'opencode', ollamaBacked: true }, ['low', 'medium', 'high']],
+ // OpenCode forwards `reasoningEffort` to whichever local backend it is wired
+ // to, so the ladder belongs to every local namespace, not just Ollama.
+ ['OpenCode llama TUI', { id: 'opencode-llama-tui', command: 'opencode', llamaBacked: true }, ['low', 'medium', 'high']],
+ ['OpenCode MTPLX', { id: 'opencode-mtplx', command: 'opencode', mtplxBacked: true }, ['low', 'medium', 'high']],
+ ['OpenCode with no local backend', { id: 'opencode', command: 'opencode' }, null],
['grok (no effort control)', { id: 'grok-cli', command: 'grok' }, null],
['blank command is not claude', { id: 'ollama' }, null],
];
@@ -133,6 +139,26 @@ describe('effortLevelsForProvider (server mirror)', () => {
});
});
+// Which providers the Generation Defaults block is offered for. The rule has to
+// match what the server actually forwards, or the editor advertises a control
+// that does nothing: `buildAgentGeneration` (server/lib/opencodeConfig.js) for
+// the OpenCode wrappers, `apiGenerationOptions`
+// (server/lib/aiToolkit/internal/generationOptions.js) for HTTP runs.
+describe('generationControlsFor', () => {
+ it.each([
+ ['OpenCode llama TUI', { id: 'opencode-llama-tui', command: 'opencode', llamaBacked: true }, { temperature: true, topP: true, thinking: true }],
+ ['OpenCode MTPLX', { id: 'opencode-mtplx', command: 'opencode', mtplxBacked: true }, { temperature: true, topP: true, thinking: true }],
+ ['Claude Ollama TUI', { id: 'claude-ollama-tui', command: 'claude', ollamaBacked: true }, { temperature: true, topP: true, thinking: true }],
+ ['native Ollama API', { id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' }, { temperature: true, topP: true, thinking: true }],
+ // OrcaRouter proxies cloud models that own their own reasoning switch.
+ ['OpenCode OrcaRouter', { id: 'opencode-orcarouter', command: 'opencode', orcarouterBacked: true }, { temperature: true, topP: true, thinking: false }],
+ ['cloud API provider', { id: 'anthropic', type: 'api', endpoint: 'https://api.anthropic.com/v1' }, null],
+ ['vendor CLI', { id: 'claude-code', command: 'claude' }, null],
+ ])('%s', (_label, provider, expected) => {
+ expect(generationControlsFor(provider)).toEqual(expected);
+ });
+});
+
// Antigravity lists one model id per effort tier (`gemini-3.6-flash-high`), but
// agy also takes the BASE id with a separate `--effort` flag — so the pickers
// show base models and carry effort as its own control. Both sides must agree on
diff --git a/docs/features/dflash2.md b/docs/features/dflash2.md
index 01852a094b..0c9c3ee29a 100644
--- a/docs/features/dflash2.md
+++ b/docs/features/dflash2.md
@@ -91,6 +91,22 @@ llama-server \
3. Click **Refresh Models** to pull the live aliases from `llama-server`, or use the default `dflash` model.
4. Select **OpenCode llama TUI** in the CoS task creator or terminal runner to execute coding and agent tasks with speculative acceleration.
+### Generation defaults
+
+**AI Providers → edit the provider → Generation** carries the defaults every run
+of that provider starts with — **Temperature**, **Top-P**, **Thinking mode**, and
+**Default Effort**. They apply to HTTP, CLI, and TUI launches alike, so the same
+local model keeps one posture however it is reached; OpenCode receives them as
+its `agent.build` options, and a CoS task can still override temperature and
+thinking for a single run.
+
+The block is offered only for the backends PortOS actually forwards these to —
+Ollama, llama.cpp, and MTPLX, plus the OrcaRouter gateway. Thinking is not a
+portable flag: Ollama takes its native `think` boolean while llama.cpp and MTPLX
+receive `enable_thinking` through the chat template, so a model with no reasoning
+mode simply ignores it. Leaving **Top-P** blank sends no `top_p` at all, which is
+not the same as pinning `1` — the backend keeps its own default.
+
### Checking the requirements from the Providers page
Every provider backed by a local daemon carries a **requirements checklist** on
diff --git a/server/lib/aiToolkit/internal/generationOptions.js b/server/lib/aiToolkit/internal/generationOptions.js
new file mode 100644
index 0000000000..c4fa1d9c5d
--- /dev/null
+++ b/server/lib/aiToolkit/internal/generationOptions.js
@@ -0,0 +1,47 @@
+/**
+ * Default generation controls, rendered into an OpenAI `/chat/completions` body.
+ *
+ * These are the same provider-level defaults the OpenCode wrappers turn into an
+ * `agent.build` block (`server/lib/opencodeConfig.js` — `buildAgentGeneration`),
+ * so one local model keeps its temperature / top_p / thinking posture whether it
+ * is reached through this HTTP runner, a CLI, or a TUI.
+ *
+ * Scoped to the LOCAL OpenAI-compatible backends on purpose. A cloud provider is
+ * left exactly as it was: its request body carries no sampling fields at all
+ * unless the user pins them, so a stored default can never quietly re-shape a
+ * hosted model's output.
+ *
+ * Lives in `internal/` beside `ollamaBacked.js` so `runner.js` can build the
+ * body without importing `providers.js` and forming a module cycle.
+ */
+import { isOllamaBackedProvider } from './ollamaBacked.js';
+
+const finiteNumber = (value, min, max) => {
+ if (value === null || value === undefined || value === '') return undefined;
+ const n = Number(value);
+ return Number.isFinite(n) && n >= min && n <= max ? n : undefined;
+};
+
+/**
+ * @param {{temperature?:unknown, topP?:unknown, thinking?:unknown, llamaBacked?:boolean, mtplxBacked?:boolean}|null|undefined} provider
+ * @returns {{temperature?:number, top_p?:number, think?:boolean, chat_template_kwargs?:{enable_thinking:boolean}}}
+ */
+export function apiGenerationOptions(provider) {
+ const ollama = isOllamaBackedProvider(provider);
+ if (!ollama && provider?.llamaBacked !== true && provider?.mtplxBacked !== true) return {};
+ // Ollama API runs have defaulted to 0.6 since this control shipped; the other
+ // local backends keep their own default until the user pins one.
+ const temperature = finiteNumber(provider.temperature, 0, 2) ?? (ollama ? 0.6 : undefined);
+ const topP = finiteNumber(provider.topP, 0, 1);
+ return {
+ ...(temperature === undefined ? {} : { temperature }),
+ ...(topP === undefined ? {} : { top_p: topP }),
+ // Ollama takes its own native `think` boolean; llama.cpp / MTPLX route the
+ // toggle through the chat template instead.
+ ...(typeof provider.thinking !== 'boolean'
+ ? {}
+ : ollama
+ ? { think: provider.thinking }
+ : { chat_template_kwargs: { enable_thinking: provider.thinking } }),
+ };
+}
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 288b192958..4e43a70808 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -594,6 +594,7 @@ export function createProviderService(config = {}) {
fallbackModel: providerData.fallbackModel || null,
numCtx: providerData.numCtx || null,
temperature: providerData.temperature,
+ topP: providerData.topP,
thinking: providerData.thinking,
contextWindow: providerData.contextWindow || null,
timeout: providerData.timeout || 300000,
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 4a3ec3e992..a0bf44692d 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -6,7 +6,7 @@ import { join, extname, basename, isAbsolute, delimiter } from 'path';
import { spawn, ChildProcess } from 'child_process';
import { randomUUID } from 'crypto';
import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';
-import { isOllamaBackedProvider } from './internal/ollamaBacked.js';
+import { apiGenerationOptions } from './internal/generationOptions.js';
// npm-installed CLI providers (claude, codex, opencode, …) are .cmd/.bat
// shims on Windows; Node's spawn() can't execute those without going through
@@ -651,12 +651,7 @@ export function createRunnerService(config = {}) {
model: model || provider.defaultModel,
messages: [{ role: 'user', content: messageContent }],
stream: true,
- ...(isOllamaBackedProvider(provider)
- ? {
- temperature: Number.isFinite(Number(provider.temperature)) ? Number(provider.temperature) : 0.6,
- ...(typeof provider.thinking === 'boolean' ? { think: provider.thinking } : {})
- }
- : {}),
+ ...apiGenerationOptions(provider),
// Ollama's OpenAI-compatible endpoint defaults to a ~4K context
// window and silently truncates longer prompts. A top-level
// num_ctx lifts it (honored by Ollama, ignored by other
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 8da9e6dc61..16defe8354 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -129,6 +129,47 @@ describe('AI Toolkit runner service', () => {
expect(JSON.parse(fetch.mock.calls[0][1].body)).toMatchObject({ temperature: 0.6, think: false });
});
+ it('sends llama.cpp its temperature/top_p and routes thinking through the chat template', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ const fetch = stubStreamingFetch();
+ const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) } });
+ let done;
+ const completed = new Promise((resolve) => { done = resolve; });
+ await runner.executeApiRun({
+ runId: 'run-llama-options',
+ // A llama.cpp endpoint, so the ollama-shaped `think` flag would be dropped.
+ provider: runReady({ id: 'llama', endpoint: 'http://127.0.0.1:5568/v1', llamaBacked: true, temperature: 0.2, topP: 0.9, thinking: true }),
+ model: null, prompt: 'hi', workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: () => done(),
+ });
+ await completed;
+
+ const body = JSON.parse(fetch.mock.calls[0][1].body);
+ expect(body).toMatchObject({ temperature: 0.2, top_p: 0.9, chat_template_kwargs: { enable_thinking: true } });
+ expect(body.think).toBeUndefined();
+ });
+
+ it('sends a cloud provider no sampling fields at all', async () => {
+ // Widening the editor must not start re-shaping hosted models' output.
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ const fetch = stubStreamingFetch();
+ const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) } });
+ let done;
+ const completed = new Promise((resolve) => { done = resolve; });
+ await runner.executeApiRun({
+ runId: 'run-cloud-options',
+ provider: runReady({ id: 'openai', endpoint: 'https://api.example.com/v1', temperature: 0.6, topP: 0.9, thinking: true }),
+ model: null, prompt: 'hi', workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: () => done(),
+ });
+ await completed;
+
+ const body = JSON.parse(fetch.mock.calls[0][1].body);
+ expect(body.temperature).toBeUndefined();
+ expect(body.top_p).toBeUndefined();
+ expect(body.think).toBeUndefined();
+ });
+
it('omits num_ctx when the provider does not set it', async () => {
const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
tempDirs.push(dataDir);
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index f3b1eaf918..cdc7e9b942 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -86,9 +86,14 @@ export const providerSchema = z.object({
// Per-request context window (Ollama num_ctx). Lifts the ~4K default so long
// prompts (e.g. a whole manuscript) aren't silently truncated. Null = unset.
numCtx: z.number().int().min(512).max(1048576).nullable().optional(),
- // Ollama generation controls. These are provider-level so the same local
- // model keeps its defaults across API, CLI, and TUI launchers.
+ // Default generation controls for the local OpenAI-compatible backends
+ // (Ollama, llama.cpp, MTPLX) and the OpenCode wrappers in front of them.
+ // Provider-level so the same local model keeps its defaults across API, CLI,
+ // and TUI launchers; a run may still override them per task.
temperature: z.number().min(0).max(2).optional(),
+ // Nucleus sampling. Optional with no default: a backend that is never told a
+ // top_p keeps its own, which is not the same as being pinned to 1.
+ topP: z.number().min(0).max(1).nullable().optional(),
thinking: z.boolean().optional(),
// Planning-time context window (tokens) the editorial budgeter may assume for
// this provider — distinct from numCtx (what we *ask Ollama for*). For cloud
diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.js
index b46573e76a..14d311c87c 100644
--- a/server/lib/opencodeConfig.js
+++ b/server/lib/opencodeConfig.js
@@ -109,6 +109,79 @@ export function toBareModelIds(models, providerKey = 'ollama') {
)];
}
+/**
+ * How each local OpenCode provider entry carries a "thinking" toggle.
+ *
+ * `temperature`, `topP` and `reasoningEffort` are portable — every daemon behind
+ * these entries speaks the OpenAI chat-completions shape, so they are emitted
+ * for all of them. The thinking toggle is NOT: Ollama takes its own native
+ * `think` boolean, while a llama.cpp / MTPLX OpenAI endpoint routes it through
+ * the chat template (`chat_template_kwargs.enable_thinking`). OrcaRouter fronts
+ * cloud models that own their reasoning switch upstream, so it gets no toggle at
+ * all and the editor hides the checkbox for it. MIRROR of
+ * `generationControlsFor` in `client/src/utils/providers.js`; keep in lockstep.
+ * @type {Record<'ollama'|'mtplx'|'llama'|'orcarouter', 'think'|'chatTemplate'|null>}
+ */
+const THINKING_STYLE = {
+ ollama: 'think',
+ mtplx: 'chatTemplate',
+ llama: 'chatTemplate',
+ orcarouter: null,
+};
+
+const numberInRange = (value, min, max) => {
+ if (value === null || value === undefined || value === '') return undefined;
+ const n = Number(value);
+ return Number.isFinite(n) && n >= min && n <= max ? n : undefined;
+};
+
+// TASKS.md metadata is text, so a persisted task re-enters the lifecycle as
+// `'true'`/`'false'`. Accept both wire forms without treating an absent or
+// malformed value as an intentional override.
+const readBoolean = (value) =>
+ value === true || value === 'true'
+ ? true
+ : value === false || value === 'false'
+ ? false
+ : undefined;
+
+/**
+ * The `agent.build` generation overrides for one local OpenCode provider entry,
+ * or null when nothing is configured. OpenCode applies generation controls to
+ * agents, not provider definitions; `build` is its primary coding agent for both
+ * `opencode run` and the TUI, and unknown agent options are passed through to
+ * the provider.
+ *
+ * @param {{temperature?:unknown, topP?:unknown, thinking?:unknown, effort?:unknown}|null|undefined} generation
+ * @param {'ollama'|'mtplx'|'llama'|'orcarouter'} providerKey
+ * @returns {object|null}
+ */
+export function buildAgentGeneration(generation, providerKey) {
+ if (!generation || !Object.hasOwn(THINKING_STYLE, providerKey)) return null;
+ // Ollama agent runs have defaulted to 0.6 since this control shipped. The
+ // other backends keep their own server-side default until the user sets one,
+ // so opening the editor up to them changes nothing on its own.
+ const temperature = numberInRange(generation.temperature, 0, 2)
+ ?? (providerKey === 'ollama' ? 0.6 : undefined);
+ const topP = numberInRange(generation.topP, 0, 1);
+ const thinking = readBoolean(generation.thinking);
+ const thinkingStyle = THINKING_STYLE[providerKey];
+ const effort = typeof generation.effort === 'string' && generation.effort.trim()
+ ? generation.effort.trim()
+ : undefined;
+ const build = {
+ ...(temperature === undefined ? {} : { temperature }),
+ ...(topP === undefined ? {} : { topP }),
+ ...(thinking === undefined || thinkingStyle === null
+ ? {}
+ : thinkingStyle === 'think'
+ ? { think: thinking }
+ : { chat_template_kwargs: { enable_thinking: thinking } }),
+ ...(effort === undefined ? {} : { reasoningEffort: effort }),
+ };
+ return Object.keys(build).length > 0 ? build : null;
+}
+
/**
* Build an OpenCode config object declaring the given models under the selected
* local provider. Accepts a single id or a list (bare or namespace-prefixed —
@@ -145,29 +218,12 @@ export function buildOpencodeConfig(models, base = null, providerKey = 'ollama',
...Object.fromEntries(bareIds.map((id) => [id, { name: id, tool_call: true }])),
};
}
- // OpenCode applies generation controls to agents, not provider definitions.
- // `build` is its primary coding agent for both `opencode run` and the TUI;
- // unknown agent options are passed through to the provider, including
- // Ollama's native `think` flag.
- if (generation && providerKey === 'ollama') {
- const temperature = Number.isFinite(Number(generation.temperature)) ? Number(generation.temperature) : 0.6;
- // TASKS.md metadata is text, so a persisted task re-enters the lifecycle as
- // `'true'`/`'false'`. Accept both wire forms without treating an absent or
- // malformed value as an intentional override.
- const thinking = generation.thinking === true || generation.thinking === 'true'
- ? true
- : generation.thinking === false || generation.thinking === 'false'
- ? false
- : undefined;
- const effort = typeof generation.effort === 'string' && generation.effort.trim()
- ? generation.effort.trim()
- : undefined;
+ const build = buildAgentGeneration(generation, providerKey);
+ if (build) {
config.agent = { ...(config.agent && typeof config.agent === 'object' ? config.agent : {}) };
config.agent.build = {
...(config.agent.build && typeof config.agent.build === 'object' ? config.agent.build : {}),
- temperature,
- ...(thinking === undefined ? {} : { think: thinking }),
- ...(effort === undefined ? {} : { reasoningEffort: effort }),
+ ...build,
};
}
return config;
diff --git a/server/lib/opencodeConfig.test.js b/server/lib/opencodeConfig.test.js
index ad65c1771a..689b9a5d8d 100644
--- a/server/lib/opencodeConfig.test.js
+++ b/server/lib/opencodeConfig.test.js
@@ -177,6 +177,35 @@ describe('buildOpencodeEnvVars', () => {
expect(cfg.agent.build).toEqual({ temperature: 0.25, think: true, reasoningEffort: 'high' });
});
+ it('sends llama.cpp its generation defaults, routing thinking through the chat template', () => {
+ // The OpenCode llama TUI is the headline case: llama.cpp has no native
+ // `think` flag, so a toggle emitted as Ollama's would be silently dropped.
+ const result = buildOpencodeEnvVars(
+ { command: 'opencode', llamaBacked: true, models: [], temperature: 0.2, topP: 0.9, thinking: true, effort: 'high' },
+ 'qwen3.8-27b',
+ );
+ const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);
+ expect(cfg.agent.build).toEqual({
+ temperature: 0.2,
+ topP: 0.9,
+ chat_template_kwargs: { enable_thinking: true },
+ reasoningEffort: 'high',
+ });
+ });
+
+ it('leaves a llama.cpp provider with no configured generation alone', () => {
+ // Only Ollama carries the historical 0.6 default — opening the editor up to
+ // the other backends must not start pinning a temperature they never had.
+ const result = buildOpencodeEnvVars({ command: 'opencode', llamaBacked: true, models: [] }, 'qwen3.8-27b');
+ const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);
+ expect(cfg.agent).toBeUndefined();
+ });
+
+ it('omits the thinking toggle for OrcaRouter, whose upstreams own it', () => {
+ const cfg = buildOpencodeConfig('gpt-5', null, 'orcarouter', { temperature: 0.4, thinking: true });
+ expect(cfg.agent.build).toEqual({ temperature: 0.4 });
+ });
+
it('declares the run model under provider.mtplx.models for MTPLX-backed OpenCode', () => {
const result = buildOpencodeEnvVars({ command: 'opencode', mtplxBacked: true, models: ['mtplx'] }, 'mtplx');
const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index 0fdb927fd4..5932749dd3 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -87,8 +87,9 @@ export const CLAUDE_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhi
export const CODEX_EFFORT_LEVELS = Object.freeze(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
export const ANTIGRAVITY_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
// OpenCode forwards this narrow OpenAI-compatible ladder as `reasoningEffort`
-// to a local Ollama model. Keep it separate from vendor-CLI-only levels.
-export const OPENCODE_OLLAMA_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
+// to whichever local backend it is wired to (Ollama, llama.cpp, MTPLX,
+// OrcaRouter). Keep it separate from vendor-CLI-only levels.
+export const OPENCODE_LOCAL_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
// Cursor Agent's ladder. Cursor has NO `--effort` flag — the level is a
// parameter of the model id itself (`gpt-5[effort=max]`), folded in by
// `foldCursorEffortIntoModel` — so `buildEffortArgs` deliberately emits nothing
@@ -351,7 +352,7 @@ export function foldCursorEffortIntoModel(model, effort) {
*/
export function effortLevelsForProvider(provider, model = null) {
if (!provider) return null;
- if (isOpencodeProvider(provider) && provider.ollamaBacked === true) return OPENCODE_OLLAMA_EFFORT_LEVELS;
+ if (isOpencodeProvider(provider) && getOpencodeLocalProviderNamespace(provider)) return OPENCODE_LOCAL_EFFORT_LEVELS;
if (isCodexProvider(provider)) return CODEX_EFFORT_LEVELS;
if (isAntigravityProvider(provider)) {
const perModel = model ? antigravityModelEffortLevels(model, provider.models) : null;