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

Benchmark OpenCode Qwen runtime performance (#4796)

[._.]/ Adam Eivy7b93c5f28a30
diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsx
index 1a4aebdce9..1bcdf4d600 100644
--- a/client/src/components/settings/LocalModelAssessments.jsx
+++ b/client/src/components/settings/LocalModelAssessments.jsx
@@ -23,7 +23,7 @@
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { Gauge, RefreshCw, Trash2, Play, AlertTriangle, History, SlidersHorizontal, ChevronDown, ChevronUp } from 'lucide-react';
+import { Gauge, RefreshCw, Trash2, Play, AlertTriangle, History, SlidersHorizontal, ChevronDown, ChevronUp, Terminal } from 'lucide-react';
import socket from '../../services/socket';
import Drawer from '../Drawer';
import BrailleSpinner from '../BrailleSpinner';
@@ -36,7 +36,7 @@ import ModelThroughputReport from './ModelThroughputReport';
import { formatContextTokens, formatDurationMs, throughputLabel } from '../../utils/formatters';
import { tuningNoticeChip } from '../../lib/assessmentTuningNotice';
import {
- getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment,
+ getLocalLlmAssessments, runLocalLlmAssessment, runOpenCodeAgentBenchmark, deleteLocalLlmAssessment,
} from '../../services/api';
const INTENTS = [
@@ -53,6 +53,12 @@ const BACKEND_LABEL = {
ollama: 'Ollama', lmstudio: 'LM Studio', llama: 'llama.cpp', mtplx: 'MTPLX', vllm: 'vLLM',
};
+const OPENCODE_AGENT_TARGETS = [
+ { backend: 'llama', label: 'OpenCode llama TUI', modelId: 'qwen3.8-27b-dflash2' },
+ { backend: 'mtplx', label: 'OpenCode MTPLX TUI', modelId: 'mtplx-qwen38-27b-optimized-speed' },
+ { backend: 'ollama', label: 'OpenCode Ollama TUI', modelId: 'qwen3.8:27b-mlx' },
+];
+
const VERDICT_META = {
fits: { label: 'Fits', cls: 'text-emerald-400 border-emerald-400/50' },
'does-not-fit': { label: 'Does not fit', cls: 'text-port-warning border-port-warning/50' },
@@ -462,6 +468,8 @@ function TuningComparison({ rows, runtimeLabelFor }) {
<h3 className="text-xs font-medium text-gray-400">Tuning comparison</h3>
<p className="text-[11px] text-gray-500">
Throughput of each launch configuration, relative to the best one measured for that model.
+ The comparison uses exact tokens/s when every variant reports tokenizer counts; otherwise it
+ uses chars/s so estimates and missing usage do not decide the winner.
</p>
{rows.map((row) => (
<div key={`${row.backend}:${row.modelId}`} className="border border-port-border rounded-lg p-3 space-y-1.5">
@@ -484,7 +492,9 @@ function TuningComparison({ rows, runtimeLabelFor }) {
</span>
</div>
<div className="text-right text-gray-400 shrink-0">
- {variant.charsPerSecond} chars/s
+ {Number.isFinite(variant.rate)
+ ? `${variant.rate} ${row.metricLabel || (row.metric === 'tokensPerSecond' ? 'tokens/s' : 'chars/s')}`
+ : 'not measured'}
<span className="text-gray-600 ml-1.5">{variant.deltaPercent}%</span>
</div>
</div>
@@ -524,6 +534,70 @@ function RuntimeRoster({ runtimes }) {
);
}
+function OpenCodeAgentBenchmarkPanel({ results, running, onRun }) {
+ const completed = OPENCODE_AGENT_TARGETS
+ .map((target) => ({ target, result: results?.[target.backend] }))
+ .filter(({ result }) => result?.completed);
+ const comparableTokens = completed.length > 0
+ && completed.every(({ result }) => Number.isFinite(result.taskTokensPerSecond));
+ const metricKey = comparableTokens ? 'taskTokensPerSecond' : 'taskCharsPerSecond';
+ const metricLabel = comparableTokens ? 'tok/s' : 'chars/s';
+ const leader = [...completed]
+ .filter(({ result }) => Number.isFinite(result[metricKey]))
+ .sort((a, b) => b.result[metricKey] - a.result[metricKey])[0];
+
+ return (
+ <div className="border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-center gap-1.5 text-xs text-gray-300">
+ <Terminal size={12} className="text-port-accent" />
+ <h3 className="font-medium">OpenCode agent-task check</h3>
+ </div>
+ <p className="text-[11px] text-gray-500">
+ Runs one disposable task through each configured OpenCode local preset. The agent must create and
+ read a sentinel file in a temporary workspace, so this measures tool-loop completion rather than raw
+ decoder speed. Terminal paste/render overhead is intentionally excluded; compare the direct report
+ above for engine throughput.
+ </p>
+ {leader && (
+ <div className="text-[11px] text-port-accent border border-port-accent/30 rounded px-2 py-1">
+ Current task leader: <span className="font-medium">{leader.target.label}</span> — {leader.result[metricKey]} {metricLabel}
+ {comparableTokens ? ' (exact OpenCode output counts)' : ' (chars/s fallback until every check reports tokens)'}
+ </div>
+ )}
+ <div className="grid gap-1.5 sm:grid-cols-3">
+ {OPENCODE_AGENT_TARGETS.map((target) => {
+ const result = results?.[target.backend];
+ return (
+ <div key={target.backend} className="border border-port-border/70 rounded p-2 space-y-1.5">
+ <div className="text-[11px] text-gray-300">{target.label}</div>
+ <div className="text-[10px] text-gray-500 font-mono break-all">{target.modelId}</div>
+ {result && (
+ <div className={`text-[10px] ${result.completed ? 'text-emerald-400' : 'text-port-warning'}`}>
+ {result.completed ? 'sentinel complete' : (result.error || 'task failed')}
+ </div>
+ )}
+ {result?.completed && (
+ <div className="text-[10px] text-gray-400 space-y-0.5">
+ <div>{Number.isFinite(result.taskTokensPerSecond) ? `${result.taskTokensPerSecond} tok/s · ` : ''}{Number.isFinite(result.taskCharsPerSecond) ? `${result.taskCharsPerSecond} chars/s` : 'chars/s n/a'}</div>
+ <div>{result.toolCalls} tool call{result.toolCalls === 1 ? '' : 's'} · {formatDurationMs(result.elapsedMs)}</div>
+ </div>
+ )}
+ <button
+ type="button"
+ onClick={() => onRun(target)}
+ disabled={running}
+ className="w-full flex items-center justify-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:border-port-accent hover:text-white transition-colors disabled:opacity-50"
+ >
+ <Play size={10} /> {running ? 'Running…' : 'Run task check'}
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
export function LocalModelAssessments() {
const [intent, setIntent] = useState('balanced');
const [report, setReport] = useState(null);
@@ -545,6 +619,7 @@ export function LocalModelAssessments() {
// gate and the progress for BOTH sweeps — there is only one server-side queue,
// so there is only one place that renders it.
const [tuningSweepRequest, setTuningSweepRequest] = useState(null);
+ const [agentBenchmarkResults, setAgentBenchmarkResults] = useState({});
const [searchParams, updateParams] = useUrlParams();
const measureBackend = searchParams.get('measureBackend') || '';
@@ -705,6 +780,17 @@ export function LocalModelAssessments() {
return true;
}, { errorMessage: 'Could not discard that measurement' });
+ const [runAgentBenchmark, agentBenchmarkRunning] = useAsyncAction(async (target) => {
+ const result = await runOpenCodeAgentBenchmark({ backend: target.backend, modelId: target.modelId });
+ setAgentBenchmarkResults((previous) => ({ ...previous, [target.backend]: result }));
+ if (result?.completed) {
+ toast.success(`${target.label}: agent task completed`);
+ } else if (result) {
+ toast.warning(`${target.label}: ${result.error || 'agent task did not complete'}`);
+ }
+ return result;
+ }, { errorMessage: 'OpenCode agent benchmark failed' });
+
const cancelRun = () => {
runControllerRef.current?.abort();
// Stop accepting frames for the abandoned run BEFORE the drawer closes, or a
@@ -771,6 +857,12 @@ export function LocalModelAssessments() {
<RuntimeRoster runtimes={report?.runtimes} />
+ <OpenCodeAgentBenchmarkPanel
+ results={agentBenchmarkResults}
+ running={agentBenchmarkRunning || busy}
+ onRun={runAgentBenchmark}
+ />
+
{/* The batch run. Kept above the ranking because it is what you come here
to press at the end of the day; the results below are what you read the
next morning. Disabled while a single-model run holds the provider —
diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsx
index 5b1fcd765b..5d3e525353 100644
--- a/client/src/components/settings/LocalModelAssessments.test.jsx
+++ b/client/src/components/settings/LocalModelAssessments.test.jsx
@@ -6,6 +6,7 @@ import { MemoryRouter, useLocation } from 'react-router';
vi.mock('../../services/api', () => ({
getLocalLlmAssessments: vi.fn(),
runLocalLlmAssessment: vi.fn(),
+ runOpenCodeAgentBenchmark: vi.fn(),
deleteLocalLlmAssessment: vi.fn(),
// The sweep panel is a child of this one and polls the queue on mount. Its own
// behavior has a dedicated suite; here it just has to be idle and quiet.
@@ -23,7 +24,7 @@ vi.mock('../../services/socket', () => ({
}));
import {
- getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment,
+ getLocalLlmAssessments, runLocalLlmAssessment, runOpenCodeAgentBenchmark, deleteLocalLlmAssessment,
getLocalLlmAssessmentSweep, startLocalLlmAssessmentSweep, cancelLocalLlmAssessmentSweep,
} from '../../services/api';
import toast from '../ui/Toast';
@@ -133,6 +134,22 @@ describe('LocalModelAssessments', () => {
expect(runLocalLlmAssessment).not.toHaveBeenCalled();
});
+ it('runs an explicit OpenCode task check and renders its task-level rates', async () => {
+ runOpenCodeAgentBenchmark.mockResolvedValue({
+ backend: 'llama', modelId: 'qwen3.8-27b-dflash2', completed: true,
+ taskTokensPerSecond: 27.5, taskCharsPerSecond: 110, toolCalls: 2, elapsedMs: 4000,
+ });
+ const user = userEvent.setup();
+ renderPanel();
+ await user.click(screen.getAllByRole('button', { name: 'Run task check' })[0]);
+ await waitFor(() => expect(runOpenCodeAgentBenchmark).toHaveBeenCalledWith({
+ backend: 'llama', modelId: 'qwen3.8-27b-dflash2',
+ }));
+ expect(await screen.findByText('sentinel complete')).toBeInTheDocument();
+ expect(screen.getAllByText(/27\.5 tok\/s/)).toHaveLength(2);
+ expect(screen.getByText(/exact OpenCode output counts/)).toBeInTheDocument();
+ });
+
it('renders measured numbers for a ranked model', async () => {
getLocalLlmAssessments.mockResolvedValue(report({ ranked: [rankedEntry()] }));
renderPanel();
diff --git a/client/src/components/settings/ModelThroughputReport.jsx b/client/src/components/settings/ModelThroughputReport.jsx
index e35a4e6700..03b5e82f1c 100644
--- a/client/src/components/settings/ModelThroughputReport.jsx
+++ b/client/src/components/settings/ModelThroughputReport.jsx
@@ -42,7 +42,7 @@ const pointsByContext = (row) => new Map((row.points || []).map((p) => [p.contex
/** The report as a markdown table — what a copy of this is actually useful as. */
export function toMarkdown(report) {
const contexts = report?.contexts || [];
- const header = ['Model', 'Runtime', 'Tuning', 'tok/s', 'Prefill tok/s', 'TTFT', ...contexts.map((c) => `${formatContextTokens(c)} tok/s`)];
+ const header = ['Model', 'Runtime', 'Tuning', 'tok/s', 'chars/s', 'Prefill tok/s', 'TTFT', ...contexts.map((c) => `${formatContextTokens(c)} tok/s`)];
const lines = [
`| ${header.join(' | ')} |`,
`| ${header.map(() => '---').join(' | ')} |`,
@@ -54,6 +54,7 @@ export function toMarkdown(report) {
row.backend,
row.tuningLabel || 'backend defaults',
rateText(row.meanTokensPerSecond, row.tokensEstimated),
+ rateText(row.meanCharsPerSecond, false),
rateText(row.meanPromptTokensPerSecond, row.tokensEstimated),
Number.isFinite(row.meanTtftMs) ? formatDurationMs(row.meanTtftMs) : '—',
...contexts.map((c) => rateText(byContext.get(c)?.tokensPerSecond, row.tokensEstimated)),
@@ -101,9 +102,10 @@ export default function ModelThroughputReport({ report, runtimeLabelFor }) {
</button>
</div>
<p className="text-[11px] text-gray-500">
- Generation speed after the first token — the same figure llama.cpp and Ollama report. Prefill speed
- (how fast the prompt was read) and time to first token are beside it, so a model that decodes fast
- but chews slowly through long context is visible as such.
+ Generation speed after the first token — exact tokens/s when the runtime reports usage, with chars/s
+ beside it as the universal cross-runtime fallback. Prefill speed (how fast the prompt was read) and
+ time to first token are beside them, so a model that decodes fast but chews slowly through long context
+ is visible as such.
{report.modelsWithTokenRates < rows.length && (
<> A <span className="text-gray-400">—</span> means the runtime reported no token counts for that
reading; its chars/s figure is in the ranked list above.</>
@@ -118,6 +120,7 @@ export default function ModelThroughputReport({ report, runtimeLabelFor }) {
<tr className="text-gray-500 border-b border-port-border">
<th scope="col" className="text-left font-medium px-2 py-1.5">Model</th>
<th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">tok/s</th>
+ <th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">chars/s</th>
<th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">Prefill</th>
<th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">TTFT</th>
{contexts.map((context) => (
@@ -143,6 +146,7 @@ export default function ModelThroughputReport({ report, runtimeLabelFor }) {
</div>
</td>
<td className="px-2 py-1.5 text-right"><Rate value={row.meanTokensPerSecond} estimated={row.tokensEstimated} /></td>
+ <td className="px-2 py-1.5 text-right"><Rate value={row.meanCharsPerSecond} estimated={false} /></td>
<td className="px-2 py-1.5 text-right"><Rate value={row.meanPromptTokensPerSecond} estimated={row.tokensEstimated} /></td>
<td className="px-2 py-1.5 text-right text-gray-200 whitespace-nowrap">
{Number.isFinite(row.meanTtftMs) ? formatDurationMs(row.meanTtftMs) : <span className="text-gray-600">—</span>}
diff --git a/client/src/components/settings/ModelThroughputReport.test.jsx b/client/src/components/settings/ModelThroughputReport.test.jsx
index 48350eb81d..c94be79b2c 100644
--- a/client/src/components/settings/ModelThroughputReport.test.jsx
+++ b/client/src/components/settings/ModelThroughputReport.test.jsx
@@ -119,7 +119,7 @@ describe('toMarkdown', () => {
it('emits one row per measurement with a column per context', () => {
const md = toMarkdown(report([row('example-model:7b')]));
const lines = md.split('\n');
- expect(lines[0]).toBe('| Model | Runtime | Tuning | tok/s | Prefill tok/s | TTFT | 512 tok/s | 4K tok/s |');
+ expect(lines[0]).toBe('| Model | Runtime | Tuning | tok/s | chars/s | Prefill tok/s | TTFT | 512 tok/s | 4K tok/s |');
expect(lines[2]).toContain('| example-model:7b | ollama | backend defaults | 50.0 |');
expect(lines[2]).toContain('| 60.0 | 40.0 |');
});
@@ -130,6 +130,6 @@ describe('toMarkdown', () => {
points: [point(512, null)],
});
const md = toMarkdown(report([quiet]));
- expect(md).toContain('| quiet-model | ollama | backend defaults | — | — | — |');
+ expect(md).toContain('| quiet-model | ollama | backend defaults | — | 200.0 | — | — |');
});
});
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index bf330a3d13..43ce96ae7c 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -240,6 +240,11 @@ export const getLocalLlmAssessments = (intent = 'balanced', options) =>
export const runLocalLlmAssessment = (payload, options) =>
request('/local-llm/assessments/run', { method: 'POST', body: JSON.stringify(payload), ...options });
+// Run one disposable OpenCode agent task through a local TUI provider preset.
+// This measures tool-loop completion separately from direct decoder throughput.
+export const runOpenCodeAgentBenchmark = (payload, options) =>
+ request('/local-llm/assessments/agent-benchmark', { method: 'POST', body: JSON.stringify(payload), ...options });
+
// === The overnight sweep =====================================================
// Measure every model the scope covers, in one server-side queue. Unlike
// `runLocalLlmAssessment` this returns as soon as the queue is built — the run
diff --git a/docs/plans/2026-08-21-models-navigation.md b/docs/plans/2026-08-21-models-navigation.md
index e35982e038..be3b60d03b 100644
--- a/docs/plans/2026-08-21-models-navigation.md
+++ b/docs/plans/2026-08-21-models-navigation.md
@@ -57,7 +57,7 @@ rule, and partial-output-on-abort.
PortOS can actually **do** with it:
- `launch` — PortOS puts it on the daemon's command line (llama.cpp only:
- `-b`, `-ub`, `-t`, `--flash-attn`, `--cache-type-k|v`, `--draft-max`).
+ `-b`, `-ub`, `-t`, `--flash-attn`, `--cache-type-k|v`, `--spec-draft-n-max`).
- `request` — sent with each measurement request (Ollama's `num_ctx`).
- `record` — PortOS cannot set it; the user states how the daemon was launched so
two readings stay comparable (LM Studio, MTPLX, vLLM).
diff --git a/server/lib/README.md b/server/lib/README.md
index 53a8a74d74..e2c0f4c16d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -143,7 +143,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (a local directory listing — no network, no model load) and `pickMtplxCachedModel(models)` → the repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. |
| `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator-cloned syv-ai/qwen38-27b-rtx3090 compose project, plus `vllmStartBlockedReason(project)` → the prose refusal (or `null`). Directory reads only — never runs docker or touches a registry. `hasWeights` is tri-state: `true` found / `false` caches read and empty / `null` no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and `services/localRuntimeSetup.js` refuses to `docker compose up` on anything but `true` so the start button can never kick off the ~20 GB prepare. Overrides: `VLLM_QWEN_PROJECT_DIR`, `VLLM_QWEN_WEIGHTS_DIR`. |
| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |
-| `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk, onStats })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon, plus `buildMessages`, `parseStreamFrame` (content/reasoning delta + the terminal `usage` block; skips a malformed SSE frame instead of aborting the stream), `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported). Registering `onStats` is what asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint and `resolvePartialOutput` (content, else reasoning, else `''`). Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
+| `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk, onStats })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon; `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
@@ -318,7 +318,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), `buildThroughputReport` (every measurement as one tokens/s table, fastest first, per-context readings intact), `selectSweepTargets`/`summarizeSweepScopes`/`SWEEP_SCOPES` (which measurements a "measure everything" run covers, and how many), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
-| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and `applies` + the user-facing `note` are DERIVED from it: `config` (llama.cpp's `-b`/`-ub`/`-t`/`--parallel`/`--flash-attn`/`--cache-type-k\|v`/`--draft-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (a flag on the launch line of a daemon PortOS re-runs — LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, and MTPLX's `mtplx serve --context-window`/`--depth`/`--generation-mode`/`--kv-quant`/`--batching-preset`/`--profile` — via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). vLLM declares none: PortOS does not start it, so there is no launch line to put a flag on. Read the MTPLX verification note in the module before adding an `mtplx serve` flag — it exits before it binds on one it does not recognize. Also `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, and `compareTunings` (which tuning won per model, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner), and `tuningGridFor` (the candidate grid a tuning sweep runs — backend defaults plus one variant per knob declaring a `sweep` value, capped by `maxVariants`; `sweepWith` carries a knob's documented prerequisite). Pure. || `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
+| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and `applies` + the user-facing `note` are DERIVED from it: `config` (llama.cpp's `-b`/`-ub`/`-t`/`--parallel`/`--flash-attn`/`--cache-type-k\|v`/`--spec-draft-n-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (a flag on the launch line of a daemon PortOS re-runs — LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, and MTPLX's `mtplx serve --context-window`/`--depth`/`--generation-mode`/`--kv-quant`/`--batching-preset`/`--profile` — via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). vLLM declares none: PortOS does not start it, so there is no launch line to put a flag on. Read the MTPLX verification note in the module before adding an `mtplx serve` flag — it exits before it binds on one it does not recognize. Also `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, and `compareTunings` (which tuning won per model using exact tokens/s when all variants have tokenizer counts and chars/s otherwise, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner), and `tuningGridFor` (the candidate grid a tuning sweep runs — backend defaults plus one variant per knob declaring a `sweep` value, capped by `maxVariants`; `sweepWith` carries a knob's documented prerequisite). Pure. || `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `loraTriggers.js` | Pure trigger-word weaving for renders that load a LoRA (#4665): `weaveLoraTriggers(prompt, triggerWordLists)` → `{ prompt, added }` appends each selected LoRA's FIRST activation token to the prompt when it is not already there, in selection order, as a trailing comma clause so the user's own phrasing keeps its position and weight. `promptHasTriggerWord` is the whole-token, case-insensitive presence test (`aria_tok` does not match inside `aria_token`); `firstTriggerWord` picks the canonical token out of a Civitai `trainedWords` list. Idempotent, so a re-render of an already-woven prompt is a no-op. Consumed by `services/imageGen/local.js` and `services/videoGen/local.js` (paired with `services/loras.js#readTriggerWordsByFilename` for the sidecar reads). The comic pipeline shares it rather than opting out — its own "<Name> (<trigger>)" clause uses the same token, so the weave adds nothing there except for the characters that clause drops. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors `client/src/lib/musicDuration.js`. |
diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.js
index 9d79ec1175..9ae6c09480 100644
--- a/server/lib/bufferedSpawn.js
+++ b/server/lib/bufferedSpawn.js
@@ -275,11 +275,12 @@ export function killProcessTree(child, signal = 'SIGTERM', { processGroup = fals
* @param {string[]} args
* @param {object} options
* @param {string} [options.cwd]
+ * @param {NodeJS.ProcessEnv} [options.env] - complete child environment
* @param {number} [options.timeoutMs] - kill + resolve as timed-out after this
* @param {boolean} [options.shell] - defaults to `needsShell(cmd)`
* @returns {Promise<object>} structured result (never rejects)
*/
-export function bufferedSpawn(cmd, args, { cwd, timeoutMs, shell } = {}) {
+export function bufferedSpawn(cmd, args, { cwd, env = process.env, timeoutMs, shell } = {}) {
return new Promise((resolve) => {
const child = spawn(cmd, args, {
cwd,
@@ -288,7 +289,7 @@ export function bufferedSpawn(cmd, args, { cwd, timeoutMs, shell } = {}) {
// bufferedSpawn user inherits it; `withSpawnCwdEnv` returns an unchanged
// copy of process.env when no cwd was given, matching the previous
// implicit-inherit behavior exactly.
- env: withSpawnCwdEnv(process.env, cwd),
+ env: withSpawnCwdEnv(env, cwd),
shell: shell === undefined ? needsShell(cmd) : shell,
});
let stdout = '';
diff --git a/server/lib/localModelTuning.js b/server/lib/localModelTuning.js
index c23a8e463d..8537ba24cc 100644
--- a/server/lib/localModelTuning.js
+++ b/server/lib/localModelTuning.js
@@ -176,7 +176,7 @@ const RAW_SPECS = {
// attention is on, so a V-only variant would fail to launch rather than
// measure anything. The `flashAttn` variant above is the honest single knob.
{ id: 'cacheTypeV', label: 'KV cache type (V)', type: 'enum', config: true, options: CACHE_TYPES, hint: 'Quantizing the value cache buys context length with a little quality.' },
- { id: 'draftMax', label: 'Draft tokens', type: 'number', config: true, min: 0, max: 64, hint: 'Speculative-decoding lookahead. Only does anything when a drafter model is loaded.' },
+ { id: 'draftMax', label: 'Draft tokens', type: 'number', config: true, min: 0, max: 64, sweep: [3], hint: 'Speculative-decoding lookahead (`--spec-draft-n-max`). Only does anything when a drafter model is loaded.' },
],
// Every Ollama knob is daemon-wide environment, applied by restarting
// `ollama serve` — including the context window. A `num_ctx` in the request
@@ -490,6 +490,16 @@ const throughputOf = (a) => {
return Number.isFinite(value) ? value : null;
};
+// Token rates are the better tuning signal only when every variant has an
+// exact daemon-reported count. A frame-count estimate is useful evidence, but
+// mixing it with tokenizer counts would make the winner depend on reporting
+// behavior rather than runtime speed. Fall back to chars/s for that group — it
+// is the unit every assessment can measure without a tokenizer.
+const tokenThroughputOf = (a) => {
+ const value = a?.performance?.meanTokensPerSecond;
+ return Number.isFinite(value) && a?.performance?.tokensEstimated !== true ? value : null;
+};
+
/**
* Group measured assessments by (backend, model) and report which tuning won.
*
@@ -516,27 +526,38 @@ export function compareTunings(assessments) {
const rows = [];
for (const list of groups.values()) {
if (list.length < 2) continue;
- const sorted = [...list].sort((a, b) => throughputOf(b) - throughputOf(a));
- const winner = throughputOf(sorted[0]);
+ const useTokens = list.every((assessment) => tokenThroughputOf(assessment) !== null);
+ const metric = useTokens ? 'tokensPerSecond' : 'charsPerSecond';
+ const rateOf = useTokens ? tokenThroughputOf : throughputOf;
+ const sorted = [...list].sort((a, b) => rateOf(b) - rateOf(a));
+ const winner = rateOf(sorted[0]);
rows.push({
backend: sorted[0].backend,
modelId: sorted[0].modelId,
+ metric,
+ metricLabel: useTokens ? 'tokens/s' : 'chars/s',
best: {
tuning: sorted[0].tuning || {},
label: labelOf(sorted[0]),
- charsPerSecond: winner,
+ charsPerSecond: throughputOf(sorted[0]),
+ tokensPerSecond: tokenThroughputOf(sorted[0]),
+ rate: winner,
},
variants: sorted.map((a) => ({
tuning: a.tuning || {},
label: labelOf(a),
charsPerSecond: throughputOf(a),
+ tokensPerSecond: tokenThroughputOf(a),
+ rate: rateOf(a),
+ metric,
+ tokensEstimated: a?.performance?.tokensEstimated === true,
maxWorkingContextTokens: Number.isFinite(a.performance?.maxWorkingContextTokens)
? a.performance.maxWorkingContextTokens
: null,
assessedAt: a.assessedAt || null,
// Relative to the winner, so 100 is the best measured tuning and 74
// means "a quarter slower than the best this model managed here".
- deltaPercent: winner > 0 ? Number(((throughputOf(a) / winner) * 100).toFixed(1)) : null,
+ deltaPercent: winner > 0 ? Number(((rateOf(a) / winner) * 100).toFixed(1)) : null,
})),
});
}
diff --git a/server/lib/localModelTuning.test.js b/server/lib/localModelTuning.test.js
index d94ec96b8e..4ee9c14139 100644
--- a/server/lib/localModelTuning.test.js
+++ b/server/lib/localModelTuning.test.js
@@ -272,6 +272,24 @@ describe('compareTunings', () => {
expect(row.variants.map((v) => v.deltaPercent)).toEqual([100, 75]);
});
+ it('ranks by exact tokens per second when every variant reports tokenizer usage', () => {
+ const [row] = compareTunings([
+ measured({ ubatchSize: 256 }, 100, {
+ performance: { meanCharsPerSecond: 100, meanTokensPerSecond: 20, tokensEstimated: false, maxWorkingContextTokens: 16384 },
+ }),
+ measured({ ubatchSize: 512 }, 90, {
+ performance: { meanCharsPerSecond: 90, meanTokensPerSecond: 30, tokensEstimated: false, maxWorkingContextTokens: 16384 },
+ }),
+ ]);
+ expect(row.metric).toBe('tokensPerSecond');
+ expect(row.metricLabel).toBe('tokens/s');
+ expect(row.best.rate).toBe(30);
+ expect(row.best.tokensPerSecond).toBe(30);
+ expect(row.best.charsPerSecond).toBe(90);
+ expect(row.variants.map((variant) => variant.rate)).toEqual([30, 20]);
+ expect(row.variants.map((variant) => variant.deltaPercent)).toEqual([100, 66.7]);
+ });
+
it('labels the untuned variant as backend defaults rather than an empty string', () => {
const [row] = compareTunings([measured({}, 120), measured({ ubatchSize: 512 }, 90)]);
expect(row.best.label).toBe('Backend defaults');
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index aa0f1ff061..a8ecca4d2b 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -305,6 +305,14 @@ export const localLlmAssessmentSweepSchema = z.object({
export const localLlmAssessmentIntentSchema = z.object({
intent: z.enum(['balanced', 'smartest', 'fastest', 'lightweight']).optional().default('balanced'),
});
+// One explicit OpenCode task through each of the three Qwen runtime presets.
+// The service still restricts the model id to the named target for that backend
+// so this endpoint cannot become an arbitrary CLI launcher.
+export const localLlmAgentBenchmarkSchema = z.object({
+ backend: z.enum(['ollama', 'mtplx', 'llama']),
+ modelId: localLlmModelIdSchema,
+ timeoutMs: z.coerce.number().int().min(10000).max(600000).optional().default(600000),
+});
// `tuningKey` identifies WHICH measurement of a model to drop — several can now
// coexist, one per tuning. Absent/'' targets the backend-defaults record, which
// is exactly what a pre-tuning client sends.
diff --git a/server/lib/openAiChatStream.js b/server/lib/openAiChatStream.js
index f2226ee07d..35b7a77fc8 100644
--- a/server/lib/openAiChatStream.js
+++ b/server/lib/openAiChatStream.js
@@ -91,6 +91,36 @@ export function normalizeUsage(usage) {
};
}
+/**
+ * Parse one native Ollama `/api/chat` NDJSON frame.
+ *
+ * Ollama reports exact tokenizer counts and nanosecond timings on the terminal
+ * `done` frame, but its OpenAI-compatible shim does not consistently forward
+ * those fields. Keep this parser next to the SSE parser so the assessment
+ * service can choose the native path without growing a second streaming loop.
+ * A malformed line is skipped for the same reason as a malformed SSE frame:
+ * one keep-alive or proxy fragment must not discard the output already read.
+ */
+export function parseOllamaStreamFrame(rawLine) {
+ const line = String(rawLine || '').trim();
+ if (!line) return null;
+ let parsed;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ return null;
+ }
+ const message = parsed?.message && typeof parsed.message === 'object' ? parsed.message : {};
+ return {
+ content: typeof message.content === 'string' ? message.content : '',
+ reasoning: typeof message.thinking === 'string'
+ ? message.thinking
+ : (typeof message.reasoning === 'string' ? message.reasoning : ''),
+ usage: parsed && typeof parsed === 'object' ? parsed : null,
+ done: parsed?.done === true,
+ };
+}
+
/**
* Resolve the text to surface from a (possibly interrupted) stream: prefer the
* visible content, fall back to reasoning when no content arrived (some models
@@ -288,3 +318,131 @@ export async function streamOpenAiChat({
return resolvePartialOutput({ output, reasoning });
}
+
+/**
+ * Stream Ollama's native `/api/chat` endpoint.
+ *
+ * This is intentionally an assessment-only transport. OpenCode and the local
+ * playground use the OpenAI-compatible endpoint because that is the provider
+ * contract they exercise; the Performance page uses this native route only to
+ * obtain Ollama's exact `eval_count`, `prompt_eval_count`, `eval_duration`, and
+ * `prompt_eval_duration` values. `extraBody.num_ctx` is translated into the
+ * native `options.num_ctx` field, matching Ollama's API rather than the shim.
+ *
+ * @returns {Promise<string>} visible content, or reasoning when content is
+ * absent; an interrupted stream throws with `.partialOutput`.
+ */
+export async function streamOllamaChat({
+ endpoint,
+ apiKey,
+ model,
+ messages,
+ temperature,
+ maxTokens,
+ extraBody = {},
+ signal,
+ onChunk,
+ onStats,
+}) {
+ const headers = { 'Content-Type': 'application/json' };
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
+ const base = String(endpoint || '').replace(/\/v1\/?$/, '').replace(/\/+$/, '');
+ const url = `${base}/api/chat`;
+ const { num_ctx: numCtx, think, ...nativeExtra } = extraBody || {};
+ const options = {
+ ...nativeExtra,
+ ...(Number.isFinite(Number(numCtx)) && Number(numCtx) > 0 ? { num_ctx: Number(numCtx) } : {}),
+ ...(Number.isFinite(Number(temperature)) ? { temperature: Number(temperature) } : {}),
+ ...(Number.isFinite(Number(maxTokens)) && Number(maxTokens) > 0 ? { num_predict: Number(maxTokens) } : {}),
+ };
+ const response = await fetch(url, {
+ method: 'POST',
+ headers,
+ signal,
+ body: JSON.stringify({
+ model,
+ messages,
+ stream: true,
+ ...(Object.keys(options).length ? { options } : {}),
+ ...(typeof think === 'boolean' ? { think } : {}),
+ }),
+ }).catch((err) => ({ ok: false, status: 0, error: err.message }));
+
+ if (!response.ok) {
+ const body = response.text ? await response.text().catch(() => '') : response.error || '';
+ throw new Error(`Ollama returned ${response.status || 0}: ${body || response.error || response.statusText || 'request failed'}`);
+ }
+
+ const emitStats = (stats) => {
+ if (typeof onStats !== 'function') return;
+ try { onStats(stats); }
+ catch (err) { console.error(`❌ Local LLM: Ollama usage listener failed: ${err.message}`); }
+ };
+
+ let output = '';
+ let reasoning = '';
+ let usage = null;
+ let contentFrames = 0;
+ let promptMs = null;
+ let completionMs = null;
+ let reader = null;
+
+ const consumeLine = async (rawLine) => {
+ const frame = parseOllamaStreamFrame(rawLine);
+ if (!frame) return;
+ if (frame.usage) usage = frame.usage;
+ if (Number.isFinite(frame.usage?.prompt_eval_duration)) {
+ promptMs = frame.usage.prompt_eval_duration / 1e6;
+ }
+ if (Number.isFinite(frame.usage?.eval_duration)) {
+ completionMs = frame.usage.eval_duration / 1e6;
+ }
+ if (frame.content) {
+ contentFrames += 1;
+ output += frame.content;
+ await onChunk?.(frame.content, 'content');
+ }
+ if (frame.reasoning) {
+ reasoning += frame.reasoning;
+ await onChunk?.(frame.reasoning, 'reasoning');
+ }
+ };
+
+ try {
+ if (!response.body?.getReader) {
+ const body = await response.text?.() || '';
+ for (const line of body.split(/\r?\n/)) await consumeLine(line);
+ } else {
+ reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ for (const line of lines) await consumeLine(line);
+ }
+ if (buffer.trim()) await consumeLine(buffer);
+ }
+ } catch (err) {
+ err.partialOutput = resolvePartialOutput({ output, reasoning });
+ throw err;
+ } finally {
+ const reported = normalizeUsage(usage);
+ emitStats({
+ ...reported,
+ // Ollama's durations are nanoseconds. Keep the converted milliseconds
+ // beside the counts so the caller can calculate decode and prefill rates
+ // without subtracting two clocks that include different work.
+ ...(Number.isFinite(completionMs) ? { completionMs } : {}),
+ ...(Number.isFinite(promptMs) ? { promptMs } : {}),
+ estimated: reported.completionTokens === null && contentFrames > 0,
+ ...(reported.completionTokens === null && contentFrames > 0 ? { completionTokens: contentFrames } : {}),
+ });
+ await reader?.cancel?.().catch(() => {});
+ }
+
+ return resolvePartialOutput({ output, reasoning });
+}
diff --git a/server/lib/openAiChatStream.test.js b/server/lib/openAiChatStream.test.js
index f4b03b4051..3b27022a29 100644
--- a/server/lib/openAiChatStream.test.js
+++ b/server/lib/openAiChatStream.test.js
@@ -9,8 +9,15 @@
* reasoning-only model must still surface its output.
*/
-import { describe, it, expect } from 'vitest';
-import { buildMessages, normalizeUsage, parseStreamFrame, resolvePartialOutput } from './openAiChatStream.js';
+import { describe, it, expect, vi } from 'vitest';
+import {
+ buildMessages,
+ normalizeUsage,
+ parseOllamaStreamFrame,
+ parseStreamFrame,
+ resolvePartialOutput,
+ streamOllamaChat,
+} from './openAiChatStream.js';
describe('buildMessages', () => {
it('omits the system message when blank', () => {
@@ -109,3 +116,61 @@ describe('normalizeUsage', () => {
.toEqual({ completionTokens: null, promptTokens: null });
});
});
+
+describe('parseOllamaStreamFrame', () => {
+ it('reads native content and thinking deltas', () => {
+ expect(parseOllamaStreamFrame(JSON.stringify({ message: { content: 'answer', thinking: 'hmm' } })))
+ .toEqual({ content: 'answer', reasoning: 'hmm', usage: { message: { content: 'answer', thinking: 'hmm' } }, done: false });
+ });
+
+ it('skips malformed native lines and preserves terminal usage', () => {
+ expect(parseOllamaStreamFrame('{nope')).toBeNull();
+ expect(parseOllamaStreamFrame(JSON.stringify({
+ done: true,
+ eval_count: 42,
+ prompt_eval_count: 900,
+ eval_duration: 250000000,
+ prompt_eval_duration: 50000000,
+ }))).toMatchObject({ content: '', reasoning: '', done: true, usage: { eval_count: 42 } });
+ });
+});
+
+describe('streamOllamaChat', () => {
+ it('uses native options and reports exact counts plus durations', async () => {
+ const lines = [
+ JSON.stringify({ message: { content: 'Done.' }, done: false }),
+ JSON.stringify({ done: true, eval_count: 42, prompt_eval_count: 900, eval_duration: 250000000, prompt_eval_duration: 50000000 }),
+ ];
+ let index = 0;
+ const reader = {
+ read: vi.fn(async () => index < lines.length
+ ? { done: false, value: new TextEncoder().encode(`${lines[index++]}\n`) }
+ : { done: true, value: undefined }),
+ cancel: vi.fn(async () => {}),
+ };
+ global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, body: { getReader: () => reader } });
+ const stats = [];
+ const result = await streamOllamaChat({
+ endpoint: 'http://localhost:11434/v1',
+ model: 'qwen3.8:27b-mlx',
+ messages: [{ role: 'user', content: 'hi' }],
+ temperature: 0,
+ maxTokens: 96,
+ extraBody: { num_ctx: 4096 },
+ onStats: (value) => stats.push(value),
+ });
+
+ expect(result).toBe('Done.');
+ expect(global.fetch).toHaveBeenCalledWith('http://localhost:11434/api/chat', expect.objectContaining({
+ body: expect.stringContaining('"num_ctx":4096'),
+ }));
+ expect(stats).toEqual([{
+ completionTokens: 42,
+ promptTokens: 900,
+ completionMs: 250,
+ promptMs: 50,
+ estimated: false,
+ }]);
+ delete global.fetch;
+ });
+});
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index abd9bc723d..44124bee5b 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -25,6 +25,7 @@ import {
localLlmCompareSchema,
localLlmAssessmentRunSchema,
localLlmAssessmentIntentSchema,
+ localLlmAgentBenchmarkSchema,
localLlmAssessmentDeleteSchema,
localLlmAssessmentSweepSchema,
localLlmLlamaServerStartSchema,
@@ -54,6 +55,7 @@ import { getSettings } from '../services/settings.js'
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'
import { getAssessmentReport, runAssessment, deleteAssessment } from '../services/localModelAssessments.js'
import { startSweep, getSweepStatus, cancelSweep } from '../services/localModelAssessmentSweep.js'
+import { runOpenCodeAgentBenchmark } from '../services/localModelAgentBenchmark.js'
import { listUserModels } from '../services/audioModels.js'
import { ENGINES } from '../services/pipeline/musicGen.js'
import { abortSignalFromResponse } from '../lib/requestAbort.js'
@@ -487,6 +489,15 @@ router.post('/assessments/run', asyncHandler(async (req, res) => {
res.json(await runAssessment({ backend, modelId, contextTokens, tuning, signal: abortSignalFromResponse(res), onProgress }))
}))
+// POST /api/local-llm/assessments/agent-benchmark — run one explicit,
+// disposable OpenCode task through a configured local TUI provider. This is
+// deliberately separate from `/run`: it measures task-loop completion, not just
+// decoder speed, and never runs from a read/poll/bootstrap path.
+router.post('/assessments/agent-benchmark', asyncHandler(async (req, res) => {
+ const { backend, modelId, timeoutMs } = validateRequest(localLlmAgentBenchmarkSchema, req.body)
+ res.json(await runOpenCodeAgentBenchmark({ backend, modelId, timeoutMs }))
+}))
+
// POST /api/local-llm/assessments/sweep — measure EVERY model the scope covers,
// or (with `tunings: true` plus a backend/modelId) ONE model across the tuning
// grid its runtime declares.
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index ed325f6867..be2371c7f3 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -8,6 +8,7 @@ import { enrichCatalogWithVariants, applyMeasuredFit } from '../services/hugging
import { getMeasuredFits } from '../services/localModelAssessmentStore.js';
import { runAssessment } from '../services/localModelAssessments.js';
import { startSweep, getSweepStatus, cancelSweep } from '../services/localModelAssessmentSweep.js';
+import { runOpenCodeAgentBenchmark } from '../services/localModelAgentBenchmark.js';
import { getLoadedModels, unloadModel } from '../services/ollamaManager.js';
import { getLoadedModels as getLoadedLmStudioModels, getLastLoadedModelsError as getLmStudioResidencyError } from '../services/lmStudioManager.js';
import { getSettings } from '../services/settings.js';
@@ -78,6 +79,12 @@ vi.mock('../services/localModelAssessmentSweep.js', () => ({
cancelSweep: vi.fn(() => ({ status: 'cancelled', total: 3, completed: 1, results: [] })),
}));
+vi.mock('../services/localModelAgentBenchmark.js', () => ({
+ runOpenCodeAgentBenchmark: vi.fn(async ({ backend, modelId, timeoutMs }) => ({
+ backend, modelId, timeoutMs, completed: true, taskCharsPerSecond: 100,
+ })),
+}));
+
vi.mock('../services/llamaServerManager.js', () => ({
getLlamaServerStatus: vi.fn(async () => ({ installed: true, running: false })),
startLlamaServer: vi.fn(async () => ({ success: true, pid: 123 })),
@@ -513,6 +520,29 @@ describe('measured assessments wiring', () => {
});
});
+ it('runs the explicit OpenCode agent benchmark with a bounded timeout', async () => {
+ const res = await request(makeApp())
+ .post('/api/local-llm/assessments/agent-benchmark')
+ .send({ backend: 'ollama', modelId: 'qwen3.8:27b-mlx', timeoutMs: 120000 });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ backend: 'ollama', modelId: 'qwen3.8:27b-mlx', timeoutMs: 120000, completed: true,
+ });
+ expect(runOpenCodeAgentBenchmark).toHaveBeenCalledWith({
+ backend: 'ollama', modelId: 'qwen3.8:27b-mlx', timeoutMs: 120000,
+ });
+ });
+
+ it('rejects an agent benchmark backend outside the three local targets', async () => {
+ const res = await request(makeApp())
+ .post('/api/local-llm/assessments/agent-benchmark')
+ .send({ backend: 'vllm', modelId: 'qwen3.8-27b-dflash2' });
+
+ expect(res.status).toBe(400);
+ expect(runOpenCodeAgentBenchmark).not.toHaveBeenCalled();
+ });
+
// The sweep is the overnight path: it must return as soon as the queue exists,
// because the run outlives the request that started it.
it('POST /assessments/sweep starts a queue and returns its snapshot', async () => {
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index be77eda5a4..32ad53a642 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -142,7 +142,12 @@ function parseConfigFromArgs(args) {
flashAttn: list.includes('--flash-attn') || list.includes('-fa'),
cacheTypeK: getArg('--cache-type-k'),
cacheTypeV: getArg('--cache-type-v'),
- draftMax: getArg('--draft-max') !== null ? Number(getArg('--draft-max')) : null,
+ // Current llama.cpp calls this `--spec-draft-n-max`; retain the older
+ // spelling on read so a pre-upgrade PortOS launch line can still be captured
+ // and restored without inventing a new value.
+ draftMax: getArg('--spec-draft-n-max') !== null
+ ? Number(getArg('--spec-draft-n-max'))
+ : (getArg('--draft-max') !== null ? Number(getArg('--draft-max')) : null),
};
}
@@ -353,7 +358,7 @@ export async function startLlamaServer(options = {}) {
if (cacheTypeV) args.push('--cache-type-v', String(cacheTypeV));
// Only meaningful alongside a drafter — passing it without one makes
// llama-server reject the launch line outright.
- if (Number.isFinite(draftMax) && draftPath) args.push('--draft-max', String(draftMax));
+ if (Number.isFinite(draftMax) && draftPath) args.push('--spec-draft-n-max', String(draftMax));
if (alias) args.push('--alias', alias);
lastExitError = null;
@@ -1063,4 +1068,3 @@ export function _resetLlamaServerStateForTests({ relaunchReadyTimeout, pm2ReadRe
relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 120000;
pm2ReadRetryDelayMs = Number.isFinite(pm2ReadRetryDelay) ? pm2ReadRetryDelay : PM2_READ_RETRY_DELAY_MS;
}
-
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index de6e9f532e..5f3c0e3d39 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -7,7 +7,7 @@ import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManage
import { anyAbortSignal } from '../lib/requestAbort.js';
// The SSE read loop lives in `lib/openAiChatStream.js` so the assessments
// service can measure a bare loopback daemon that has no provider record.
-import { buildMessages, streamOpenAiChat } from '../lib/openAiChatStream.js';
+import { buildMessages, streamOllamaChat, streamOpenAiChat } from '../lib/openAiChatStream.js';
import { assertSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';
const PROVIDER_BY_BACKEND = { ollama: 'ollama', lmstudio: 'lmstudio' };
@@ -53,7 +53,13 @@ export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage
// Decode window: everything after the first token arrived. Falls back to the
// full wall clock when TTFT was never observed (a non-streamed response), which
// understates the rate rather than inventing a prefill split that wasn't seen.
- const decodeMs = Number.isFinite(ttftMs) ? totalMs - ttftMs : totalMs;
+ const reportedDecodeMs = Number.isFinite(usage?.completionMs) && usage.completionMs > 0
+ ? usage.completionMs
+ : null;
+ const reportedPromptMs = Number.isFinite(usage?.promptMs) && usage.promptMs > 0
+ ? usage.promptMs
+ : null;
+ const decodeMs = reportedDecodeMs ?? (Number.isFinite(ttftMs) ? totalMs - ttftMs : totalMs);
const rate = (tokens, ms) =>
(Number.isFinite(tokens) && tokens > 0 && ms > 0 ? Number((tokens / (ms / 1000)).toFixed(2)) : null);
@@ -72,7 +78,13 @@ export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage
// Prompt processing (prefill) speed: how fast the daemon chewed through the
// context before the first token. Needs BOTH a prompt-token count and a
// measured TTFT, so it is null on a non-streamed response.
- promptTokensPerSecond: Number.isFinite(ttftMs) ? rate(promptTokens, ttftMs) : null,
+ promptTokensPerSecond: reportedPromptMs
+ ? rate(promptTokens, reportedPromptMs)
+ : (Number.isFinite(ttftMs) ? rate(promptTokens, ttftMs) : null),
+ // Native Ollama reports these directly. Keeping them in the sample makes
+ // the report auditable and avoids forcing readers to reverse the rates.
+ decodeMs: reportedDecodeMs,
+ promptMs: reportedPromptMs,
// Whether the token count came from the daemon's own tokenizer (`false`) or
// from counting streamed frames (`true`). `null` = no token count at all.
// A consumer must label an estimate as one — PortOS has no tokenizer, and
@@ -99,7 +111,7 @@ async function resolveLocalProvider(backend) {
return provider;
}
-async function streamChatCompletion({ provider, backend, modelId, prompt, systemPrompt, temperature, maxTokens, extraBody = {}, signal, onChunk, onStats }) {
+async function streamChatCompletion({ provider, backend, modelId, prompt, systemPrompt, temperature, maxTokens, extraBody = {}, signal, onChunk, onStats, nativeOllamaUsage = false }) {
if (backend === 'ollama') {
const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
if (!ready.success) {
@@ -115,7 +127,8 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
allowCustomEndpoint: provider.allowCustomEndpoint === true,
});
- return streamOpenAiChat({
+ const stream = backend === 'ollama' && nativeOllamaUsage ? streamOllamaChat : streamOpenAiChat;
+ return stream({
endpoint: provider.endpoint,
apiKey: provider.apiKey,
model: modelId,
@@ -154,6 +167,10 @@ export async function runLocalLlmTest({
// channel). The returned result is unchanged, so non-streaming callers ignore
// this entirely.
onToken,
+ // The Performance page opts into Ollama's native API so exact eval counts and
+ // decode/prefill durations survive. Normal playground runs stay on the same
+ // OpenAI-compatible path OpenCode uses.
+ nativeOllamaUsage = false,
}) {
const provider = await resolveLocalProvider(backend);
const fullPrompt = buildPrompt({ systemPrompt, prompt });
@@ -197,6 +214,7 @@ export async function runLocalLlmTest({
maxTokens,
extraBody,
signal,
+ nativeOllamaUsage,
onStats,
onChunk: (chunk, kind = 'content') => {
// First token of EITHER channel marks TTFT: for a reasoning model the
@@ -221,7 +239,7 @@ export async function runLocalLlmTest({
runId,
text,
timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage }),
- options: { temperature, maxTokens, timeoutMs },
+ options: { temperature, maxTokens, timeoutMs, nativeOllamaUsage },
};
} catch (err) {
const endedAt = Date.now();
@@ -250,7 +268,7 @@ export async function runLocalLlmTest({
error,
text: partialText,
timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text: partialText, usage }),
- options: { temperature, maxTokens, timeoutMs },
+ options: { temperature, maxTokens, timeoutMs, nativeOllamaUsage },
};
}
}
diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.js
index 895789a7a0..8d3d5f1ece 100644
--- a/server/services/localLlmPlayground.test.js
+++ b/server/services/localLlmPlayground.test.js
@@ -58,6 +58,19 @@ describe('summarizeTimings', () => {
expect(t.tokensEstimated).toBe(false);
});
+ it('prefers native decode and prefill durations when the runtime reports them', () => {
+ const t = summarizeTimings({
+ startedAt: 0, firstChunkAt: 1000, endedAt: 3000, text: 'abc',
+ usage: {
+ completionTokens: 100, promptTokens: 4000, completionMs: 500, promptMs: 250, estimated: false,
+ },
+ });
+ expect(t.decodeMs).toBe(500);
+ expect(t.promptMs).toBe(250);
+ expect(t.tokensPerSecond).toBe(200);
+ expect(t.promptTokensPerSecond).toBe(16000);
+ });
+
it('marks a frame-counted token figure as an estimate', () => {
const t = summarizeTimings({
startedAt: 0, firstChunkAt: 500, endedAt: 1500, text: 'abc',
diff --git a/server/services/localModelAgentBenchmark.js b/server/services/localModelAgentBenchmark.js
new file mode 100644
index 0000000000..23ea06d68a
--- /dev/null
+++ b/server/services/localModelAgentBenchmark.js
@@ -0,0 +1,188 @@
+/**
+ * User-triggered OpenCode agent-task checks for the local Qwen runtimes.
+ *
+ * The ordinary assessment measures one direct generation at several context
+ * lengths. That is the right instrument for decoder throughput, but it cannot
+ * answer whether a CoS task actually completes through the OpenCode tool loop.
+ * This service runs one bounded, disposable task through the configured
+ * OpenCode TUI provider preset, then reports task-level chars/s and any output
+ * token counts OpenCode exposes in its JSON event stream.
+ *
+ * It deliberately uses `opencode run --format json` rather than a PTY. The
+ * provider config, model namespace, local endpoint, permissions, and tool loop
+ * are the same; terminal paste/render latency is not included. The UI labels
+ * that distinction so a task result is never mistaken for raw decode speed.
+ */
+
+import { mkdtemp, readFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { ServerError } from '../lib/errorHandler.js';
+import { bufferedSpawn, prepareCliSpawn } from '../lib/bufferedSpawn.js';
+import { buildCliChildEnv } from '../lib/cliChildEnv.js';
+import { isOpencodeCommand, prefixOpencodeModel } from '../lib/providerModels.js';
+import { getProviderById } from './providers.js';
+
+export const OPENCODE_AGENT_BENCHMARK_TARGETS = Object.freeze({
+ llama: Object.freeze({
+ providerId: 'opencode-llama-tui',
+ label: 'OpenCode llama TUI',
+ modelId: 'qwen3.8-27b-dflash2',
+ aliases: Object.freeze(['dflash']),
+ }),
+ mtplx: Object.freeze({
+ providerId: 'opencode-mtplx-tui',
+ label: 'OpenCode MTPLX TUI',
+ modelId: 'mtplx-qwen38-27b-optimized-speed',
+ aliases: Object.freeze([]),
+ }),
+ ollama: Object.freeze({
+ providerId: 'opencode-ollama-tui',
+ label: 'OpenCode Ollama TUI',
+ modelId: 'qwen3.8:27b-mlx',
+ aliases: Object.freeze([]),
+ }),
+});
+
+export const OPENCODE_AGENT_BENCHMARK_PROMPT = [
+ 'This is a disposable PortOS runtime benchmark. You must exercise the terminal tool loop.',
+ 'In the current scratch workspace, create a file named PORTOS_AGENT_BENCHMARK.txt',
+ 'whose entire contents are exactly PORTOS_AGENT_BENCHMARK_OK (with no extra newline if your tool permits).',
+ 'Read that file back with a terminal tool, verify the exact sentinel, and then reply with exactly',
+ 'PORTOS_AGENT_BENCHMARK_OK. Do not create or modify any other file.',
+].join(' ');
+
+const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
+
+const targetFor = (backend, modelId) => {
+ const target = OPENCODE_AGENT_BENCHMARK_TARGETS[backend];
+ if (!target || (modelId !== target.modelId && !target.aliases.includes(modelId))) {
+ throw new ServerError(
+ `OpenCode agent benchmark supports only the configured ${backend || 'local'} Qwen target`,
+ { status: 400, code: 'LOCAL_AGENT_BENCHMARK_TARGET_INVALID' },
+ );
+ }
+ return target;
+};
+
+const jsonLines = (output) => String(output || '').split(/\r?\n/).map((line) => {
+ const trimmed = line.trim();
+ if (!trimmed) return null;
+ try { return JSON.parse(trimmed); }
+ catch { return null; }
+}).filter(Boolean);
+
+/**
+ * Extract task evidence from OpenCode's `--format json` event stream.
+ * OpenCode has used both `type: 'text', part: { text }` and
+ * `type: 'message.part.updated', properties: { part: { type: 'text', text } }`
+ * shapes, so the parser accepts both without counting tool arguments as answer
+ * text. It is pure and exported for fixture-driven tests.
+ */
+export function summarizeOpenCodeEvents(output) {
+ let assistantText = '';
+ let toolCalls = 0;
+ let outputTokens = 0;
+ let hasOutputTokens = false;
+
+ for (const event of jsonLines(output)) {
+ const part = event?.part || event?.properties?.part || event?.data?.part || null;
+ const partType = part?.type || event?.type;
+ if (partType === 'text') {
+ const text = typeof part?.text === 'string' ? part.text : event?.text;
+ if (typeof text === 'string') assistantText += text;
+ }
+ if (partType === 'tool' || partType === 'tool_use' || partType === 'tool-call' || event?.type === 'tool_use') toolCalls += 1;
+
+ const candidate = part?.tokens?.output ?? event?.tokens?.output ?? event?.usage?.completion_tokens ?? event?.usage?.output_tokens;
+ if (typeof candidate === 'number' && Number.isFinite(candidate) && candidate >= 0) {
+ outputTokens += candidate;
+ hasOutputTokens = true;
+ }
+ }
+
+ return {
+ assistantChars: assistantText.length,
+ toolCalls,
+ outputTokens: hasOutputTokens ? outputTokens : null,
+ };
+}
+
+const validateProvider = (provider, target) => {
+ if (!provider) {
+ throw new ServerError(`Provider "${target.providerId}" is not configured`, { status: 503, code: 'LOCAL_AGENT_BENCHMARK_PROVIDER_MISSING' });
+ }
+ if (provider.type !== 'tui' || !isOpencodeCommand(provider.command)) {
+ throw new ServerError(`Provider "${target.providerId}" is not an OpenCode TUI provider`, { status: 503, code: 'LOCAL_AGENT_BENCHMARK_PROVIDER_INVALID' });
+ }
+};
+
+/**
+ * Run one explicit OpenCode task benchmark.
+ *
+ * @param {{backend:'llama'|'mtplx'|'ollama', modelId:string, timeoutMs?:number}} options
+ */
+export async function runOpenCodeAgentBenchmark({ backend, modelId, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
+ const target = targetFor(backend, modelId);
+ const provider = await getProviderById(target.providerId);
+ validateProvider(provider, target);
+
+ const scratchDir = await mkdtemp(join(tmpdir(), 'portos-opencode-agent-benchmark-'));
+ const startedAt = Date.now();
+ try {
+ // Reuse the same model-prefix and dynamic OpenCode config path as the real
+ // TUI spawner. The benchmark cannot accidentally route a bare model to a
+ // cloud provider or fail because the per-run model was not declared.
+ const qualifiedModel = prefixOpencodeModel(provider, modelId);
+ const command = provider.command;
+ const baseArgs = Array.isArray(provider.args) ? provider.args : [];
+ const args = ['run', '--format', 'json', '--auto', '--dir', scratchDir, ...baseArgs, '--model', qualifiedModel, OPENCODE_AGENT_BENCHMARK_PROMPT];
+ const env = buildCliChildEnv({ provider, model: modelId, cwd: scratchDir, guard: true });
+ const spawnTarget = prepareCliSpawn(command, args, env);
+ const result = await bufferedSpawn(spawnTarget.command, spawnTarget.args, {
+ cwd: scratchDir,
+ env,
+ timeoutMs,
+ });
+ const evidence = summarizeOpenCodeEvents(result.stdout);
+ const sentinel = await readFile(join(scratchDir, 'PORTOS_AGENT_BENCHMARK.txt'), 'utf8')
+ .then((value) => value.trim())
+ .catch(() => '');
+ const elapsedMs = Math.max(0, Date.now() - startedAt);
+ const completed = result.success && sentinel === 'PORTOS_AGENT_BENCHMARK_OK';
+ const taskCharsPerSecond = elapsedMs > 0 && evidence.assistantChars > 0
+ ? Number((evidence.assistantChars / (elapsedMs / 1000)).toFixed(2))
+ : null;
+ const taskTokensPerSecond = elapsedMs > 0 && Number.isFinite(evidence.outputTokens) && evidence.outputTokens > 0
+ ? Number((evidence.outputTokens / (elapsedMs / 1000)).toFixed(2))
+ : null;
+
+ return {
+ backend,
+ modelId,
+ providerId: target.providerId,
+ providerLabel: target.label,
+ completed,
+ elapsedMs,
+ assistantChars: evidence.assistantChars,
+ outputTokens: evidence.outputTokens,
+ toolCalls: evidence.toolCalls,
+ taskCharsPerSecond,
+ taskTokensPerSecond,
+ exitCode: result.code,
+ timedOut: result.timedOut,
+ error: completed
+ ? null
+ : (result.timedOut
+ ? `OpenCode task timed out after ${Math.round(timeoutMs / 1000)}s`
+ : (result.success ? 'OpenCode finished without the benchmark sentinel' : `OpenCode exited with code ${result.code ?? 'unknown'}`)),
+ // Deliberately no stdout/stderr or scratch path in the API response: a
+ // local model may echo environment details, and the page needs rates, not
+ // a transcript that could contain user data.
+ };
+ } finally {
+ await rm(scratchDir, { recursive: true, force: true }).catch((err) => {
+ console.error(`⚠️ Local LLM: could not remove the OpenCode benchmark scratch directory — ${err.message}`);
+ });
+ }
+}
diff --git a/server/services/localModelAgentBenchmark.test.js b/server/services/localModelAgentBenchmark.test.js
new file mode 100644
index 0000000000..0f80ac9f2e
--- /dev/null
+++ b/server/services/localModelAgentBenchmark.test.js
@@ -0,0 +1,94 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { writeFile } from 'fs/promises';
+
+vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));
+vi.mock('../lib/bufferedSpawn.js', () => ({
+ bufferedSpawn: vi.fn(),
+ prepareCliSpawn: vi.fn((command, args) => ({ command, args })),
+}));
+vi.mock('../lib/cliChildEnv.js', () => ({ buildCliChildEnv: vi.fn(() => ({ PATH: '/example/bin' })) }));
+vi.mock('../lib/providerModels.js', () => ({
+ isOpencodeCommand: vi.fn(() => true),
+ prefixOpencodeModel: vi.fn((_provider, model) => `llama/${model}`),
+}));
+
+import { getProviderById } from './providers.js';
+import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+import { buildCliChildEnv } from '../lib/cliChildEnv.js';
+import {
+ OPENCODE_AGENT_BENCHMARK_PROMPT,
+ runOpenCodeAgentBenchmark,
+ summarizeOpenCodeEvents,
+} from './localModelAgentBenchmark.js';
+
+describe('summarizeOpenCodeEvents', () => {
+ it('counts assistant text, tool calls, and output tokens without counting tool input', () => {
+ const output = [
+ JSON.stringify({ type: 'text', part: { type: 'text', text: 'PORTOS_' } }),
+ JSON.stringify({ type: 'tool_use', part: { type: 'tool', tool: 'bash', input: 'secret-looking command' } }),
+ JSON.stringify({ type: 'text', text: 'AGENT_BENCHMARK_OK' }),
+ JSON.stringify({ type: 'step_finish', part: { tokens: { output: 12 } } }),
+ ].join('\n');
+ expect(summarizeOpenCodeEvents(output)).toEqual({ assistantChars: 25, toolCalls: 1, outputTokens: 12 });
+ });
+
+ it('keeps token rate unavailable when OpenCode exposes no usage', () => {
+ expect(summarizeOpenCodeEvents(JSON.stringify({ type: 'text', text: 'done' })))
+ .toEqual({ assistantChars: 4, toolCalls: 0, outputTokens: null });
+ });
+});
+
+describe('runOpenCodeAgentBenchmark', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getProviderById.mockResolvedValue({
+ id: 'opencode-llama-tui',
+ type: 'tui',
+ command: 'opencode',
+ args: [],
+ llamaBacked: true,
+ });
+ bufferedSpawn.mockImplementation(async (_command, args) => {
+ const dir = args[args.indexOf('--dir') + 1];
+ await writeFile(`${dir}/PORTOS_AGENT_BENCHMARK.txt`, 'PORTOS_AGENT_BENCHMARK_OK');
+ return {
+ success: true,
+ code: 0,
+ signal: null,
+ stdout: [
+ JSON.stringify({ type: 'tool_use', part: { type: 'tool' } }),
+ JSON.stringify({ type: 'text', text: 'PORTOS_AGENT_BENCHMARK_OK' }),
+ JSON.stringify({ type: 'step_finish', part: { tokens: { output: 9 } } }),
+ ].join('\n'),
+ stderr: '',
+ timedOut: false,
+ };
+ });
+ });
+
+ it('runs the named target in a scratch workspace and returns task rates', async () => {
+ const result = await runOpenCodeAgentBenchmark({ backend: 'llama', modelId: 'qwen3.8-27b-dflash2' });
+
+ expect(result).toMatchObject({
+ backend: 'llama',
+ modelId: 'qwen3.8-27b-dflash2',
+ providerId: 'opencode-llama-tui',
+ completed: true,
+ toolCalls: 1,
+ outputTokens: 9,
+ error: null,
+ });
+ expect(result.taskCharsPerSecond).toBeGreaterThan(0);
+ expect(result.taskTokensPerSecond).toBeGreaterThan(0);
+ expect(buildCliChildEnv).toHaveBeenCalledWith(expect.objectContaining({ model: 'qwen3.8-27b-dflash2', guard: true }));
+ expect(bufferedSpawn).toHaveBeenCalledWith('opencode', expect.arrayContaining([
+ 'run', '--format', 'json', '--auto', '--model', 'llama/qwen3.8-27b-dflash2', OPENCODE_AGENT_BENCHMARK_PROMPT,
+ ]), expect.objectContaining({ timeoutMs: 600000, env: { PATH: '/example/bin' } }));
+ });
+
+ it('rejects a model outside the three explicit benchmark targets', async () => {
+ await expect(runOpenCodeAgentBenchmark({ backend: 'llama', modelId: 'other-model' }))
+ .rejects.toMatchObject({ code: 'LOCAL_AGENT_BENCHMARK_TARGET_INVALID', status: 400 });
+ expect(getProviderById).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/localModelAssessmentSweep.js b/server/services/localModelAssessmentSweep.js
index 25f52d5f86..787e4fc3a6 100644
--- a/server/services/localModelAssessmentSweep.js
+++ b/server/services/localModelAssessmentSweep.js
@@ -56,11 +56,11 @@
* what is still unmeasured. Persisting the queue would buy a resumable pointer
* into a job that is cheap to restart and must never auto-resume on boot.
*
- * One consequence is worth naming: a restart during a TUNING sweep also loses
- * the captured launch configuration, so llama-server stays on whichever variant
- * was in flight. That is visible and fixable on the LLMs page, and the
- * alternative — persisting it and relaunching a daemon at boot to put it back —
- * is exactly the boot-time work this module refuses to do.
+ * One consequence is worth naming: a restart during a MODEL or TUNING sweep
+ * also loses the captured launch configuration, so llama-server stays on
+ * whichever variant/model was in flight. That is visible and fixable on the
+ * LLMs page, and the alternative — persisting it and relaunching a daemon at
+ * boot to put it back — is exactly the boot-time work this module refuses to do.
*/
import { selectSweepTargets, SWEEP_SCOPES } from '../lib/localModelAssessment.js';
@@ -164,8 +164,8 @@ export function getSweepStatus() {
* on the sweep's last variant, which is the thing this exists to prevent. It
* waits, bounded, then restores anyway and lets the reason be reported.
*/
-async function restoreUnderClaim(run, backend) {
- if (!run.launchState) return { restored: false, reason: 'nothing to restore' };
+async function restoreUnderClaim(run, backend, launchState = run.launchState) {
+ if (!launchState) return { restored: false, reason: 'nothing to restore' };
const claim = await claimHeavyLocalJob({
kind: 'local-model assessment',
id: `${backend} launch restore`,
@@ -175,12 +175,25 @@ async function restoreUnderClaim(run, backend) {
console.error(`⚠️ Local LLM: restoring the launch configuration without the accelerator claim — ${claim.message}`);
}
try {
- return await restoreLaunchState(backend, run.launchState);
+ return await restoreLaunchState(backend, launchState);
} finally {
if (claim.ok) await claim.release();
}
}
+/** Restore every backend touched by a model or tuning sweep, one at a time. */
+async function restoreAllUnderClaim(run) {
+ const failures = [];
+ for (const [backend, launchState] of Object.entries(run.launchStates || {})) {
+ const result = await restoreUnderClaim(run, backend, launchState)
+ .catch((err) => ({ restored: false, reason: err?.message || 'restore failed' }));
+ if (result?.restored === false) {
+ failures.push(`${backend}: ${result.reason || 'the launch configuration could not be put back'}`);
+ }
+ }
+ return failures;
+}
+
/**
* Ask the running sweep to stop.
*
@@ -217,11 +230,11 @@ export function __resetSweep() {
// queue is replaceable the moment it is cancelled, and a loop still winding down
// its last model must not write its results into the sweep that succeeded it.
async function runSweepLoop(run, targets, contextTokens, emit) {
- // A tuning sweep asks each variant to be the COMPLETE tuning, so the launch
- // line is exactly that variant's knobs and the baseline's is none of them.
- // `beginSweep` captured what was running first, and the `finally` below puts
- // it back — the running daemon is the only record of the flags the user chose.
- const resetTuning = run.mode === 'tunings';
+ // A tuning sweep asks each variant to be the COMPLETE tuning, while a model
+ // sweep applies each model's recorded tuning. In both cases the launch line
+ // is made explicit before the measurement, and `beginSweep` captured what
+ // was running first so the final restore can put the user's configuration
+ // back.
for (const target of targets) {
if (run.cancelRequested) break;
run.current = { backend: target.backend, modelId: target.modelId, tuningLabel: target.tuningLabel, startedAt: nowIso() };
@@ -241,6 +254,12 @@ async function runSweepLoop(run, targets, contextTokens, emit) {
// One model failing is a RESULT, not a reason to abandon the queue — the
// whole point of an overnight run is that it gets through the list.
+ // A llama model sweep must reset the launch line before applying the stored
+ // tuning for each model. Without this, model B inherited model A's batch /
+ // KV / speculative flags while its record named only B's tuning (#4774).
+ // Other endpoint runtimes have no sweep-safe reset/restore path, so they
+ // remain ordinary model measurements.
+ const resetTuning = run.mode === 'tunings' || isTuningSweepable(target.backend);
const result = await runAssessment({
backend: target.backend,
modelId: target.modelId,
@@ -310,10 +329,10 @@ async function runSweepLoop(run, targets, contextTokens, emit) {
export async function startSweep({ scope = 'unmeasured', backend, modelId, tunings = false, contextTokens, onProgress } = {}) {
if (sweep?.status === 'running' || startingSweep) return { ...snapshot(), rejected: 'a sweep is already running' };
// A CANCELLED sweep is not finished with the machine: its last measurement is
- // still aborting and, for a tuning sweep, it has a launch configuration to put
- // back. Starting the next one on top of that would have the old sweep relaunch
- // the daemon partway through the new one's first measurement — and every
- // number the new sweep produced up to then would describe that relaunch.
+ // still aborting and it may have a launch configuration to put back. Starting
+ // the next one on top of that would have the old sweep relaunch the daemon
+ // partway through the new one's first measurement — and every number the new
+ // sweep produced up to then would describe that relaunch.
if (sweep && !sweep.settled) return { ...snapshot(), rejected: 'the previous sweep is still winding down' };
// Reserved here, synchronously, so the check above and this claim cannot be
// split by the await inside. Released in the `finally` — by which point either
@@ -384,21 +403,22 @@ async function beginSweep({ scope, backend, modelId, tunings, contextTokens, onP
catch (err) { console.error(`❌ Local LLM: sweep progress listener failed: ${err.message}`); }
};
- // Captured BEFORE the first variant relaunches anything. A sweep rewrites the
- // launch line once per variant, and the running daemon is the only record of
- // the flags the user chose — the LLMs page seeds its form from hardcoded
- // defaults, not from what is running.
- const launchState = grid ? await captureLaunchState(named.backend) : null;
- // Nothing to capture means the daemon is stopped, or someone else started it —
- // either way PortOS cannot put a tuning on its launch line, so every variant
- // would record `tuningApplied: false` and the comparison would rank a set of
- // configurations that never ran. Refusing costs a click; running costs the
- // whole sweep.
- if (grid && !launchState) {
- return {
- ...snapshot(),
- rejected: `PortOS is not running ${named.backend}, so it cannot vary the launch configuration — start it from the LLMs page first`,
- };
+ // Capture BEFORE the first model/variant relaunches anything. A model sweep
+ // can cross several llama targets, each with a different stored tuning; the
+ // llama daemon is machine-wide, so the one launch state has to be restored
+ // after the whole queue, not after each model. Endpoint runtimes that cannot
+ // reset safely are intentionally absent from this map.
+ const restoreBackends = [...new Set(targets.map((target) => target.backend).filter(isTuningSweepable))];
+ const launchStates = {};
+ for (const restoreBackend of restoreBackends) {
+ const state = await captureLaunchState(restoreBackend);
+ if (!state) {
+ return {
+ ...snapshot(),
+ rejected: `PortOS is not running ${restoreBackend}, so it cannot vary the launch configuration safely — start it from the LLMs page first`,
+ };
+ }
+ launchStates[restoreBackend] = state;
}
const run = {
@@ -420,7 +440,10 @@ async function beginSweep({ scope, backend, modelId, tunings, contextTokens, onP
// while it is false, so a cancelled sweep cannot relaunch the daemon
// underneath the sweep that replaced it.
settled: false,
- launchState,
+ // Kept as a compatibility alias for callers/tests that only ever had one
+ // tuning backend. The restore path uses the per-backend map above.
+ launchState: named ? launchStates[named.backend] || null : null,
+ launchStates,
controller: new AbortController(),
};
sweep = run;
@@ -443,14 +466,14 @@ async function beginSweep({ scope, backend, modelId, tunings, contextTokens, onP
// Not in the `finally`: putting the daemon back is real work that can fail,
// and it has to finish before the page is told the sweep is over — a user
// reading "complete" must not still be racing a relaunch.
- .then(() => restoreUnderClaim(run, named?.backend)
- .then((result) => {
- // `restored: false` with a captured state means the daemon is still on
+ .then(() => restoreAllUnderClaim(run)
+ .then((failures) => {
+ // A captured state that did not restore means that backend is still on
// the last variant. Recording the reason is the only way the user finds
// out; swallowing it leaves them running a configuration they did not
// choose and cannot see.
- if (run.launchState && result?.restored === false) {
- run.restoreError = result.reason || 'the launch configuration could not be put back';
+ if (failures.length) {
+ run.restoreError = failures.join('; ');
console.error(`❌ Local LLM: sweep finished but the launch configuration was not restored — ${run.restoreError}`);
}
})
diff --git a/server/services/localModelAssessmentSweep.test.js b/server/services/localModelAssessmentSweep.test.js
index 1f11eff36c..16ff0a8c69 100644
--- a/server/services/localModelAssessmentSweep.test.js
+++ b/server/services/localModelAssessmentSweep.test.js
@@ -397,9 +397,9 @@ describe('startSweep — the tuning dimension', () => {
for (const [args] of runAssessment.mock.calls) expect(args.resetTuning).toBe(true);
});
- // A plain model sweep re-measures each model under the tuning it already
- // carries. Resetting there would wipe launch flags the user chose.
- it('never asks a model sweep for a reset', async () => {
+ // A plain endpoint model sweep re-measures each model under the tuning it
+ // already carries. Endpoint runtimes have no sweep-safe reset/restore path.
+ it('does not reset an endpoint model sweep', async () => {
getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));
runAssessment.mockResolvedValue(measured());
@@ -409,6 +409,23 @@ describe('startSweep — the tuning dimension', () => {
expect(captureLaunchState).not.toHaveBeenCalled();
});
+ it('resets each llama model to its recorded tuning and restores the daemon afterwards', async () => {
+ getAssessmentReport.mockResolvedValue(report({
+ unassessed: [
+ { backend: 'llama', modelId: 'model-a' },
+ { backend: 'llama', modelId: 'model-b' },
+ ],
+ }));
+ runAssessment.mockResolvedValue(measured());
+
+ await startSweep({ scope: 'unmeasured' });
+ await settle();
+
+ expect(captureLaunchState).toHaveBeenCalledWith('llama');
+ expect(runAssessment.mock.calls.map(([args]) => args.resetTuning)).toEqual([true, true]);
+ expect(restoreLaunchState).toHaveBeenCalledWith('llama', { model: '/models/example.gguf' });
+ });
+
// The running daemon is the only record of the launch flags the user chose, so
// a sweep that rewrote it has to put it back — however the queue ended.
it('captures the launch configuration first and restores it when the queue ends', async () => {
diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.js
index 21b5a9cea7..03758c9947 100644
--- a/server/services/localModelAssessments.js
+++ b/server/services/localModelAssessments.js
@@ -268,6 +268,8 @@ export function toSample(contextTokens, result) {
promptTokens: measured(timings.promptTokens),
tokensPerSecond: measured(timings.tokensPerSecond),
promptTokensPerSecond: measured(timings.promptTokensPerSecond),
+ decodeMs: measured(timings.decodeMs),
+ promptMs: measured(timings.promptMs),
// `true` = the count came from counting streamed frames rather than the
// daemon's tokenizer, and every figure derived from it must be labelled.
tokensEstimated: ok && typeof timings.tokensEstimated === 'boolean' ? timings.tokensEstimated : null,
@@ -629,6 +631,11 @@ async function measureModel({ backend, modelId, contexts, tuning, resetTuning, s
timeoutMs: SAMPLE_TIMEOUT_MS,
extraBody: request,
signal,
+ // Ollama's OpenAI-compatible shim frequently omits usage even though the
+ // native `/api/chat` final frame reports exact tokenizer counts and
+ // eval/prefill durations. Use that transport only for Performance-page
+ // evidence; OpenCode remains on its normal provider endpoint.
+ nativeOllamaUsage: backend === 'ollama',
};
const result = await (endpoint
? runEndpointLlmTest({ ...shared, runtime: backend, endpoint, apiKey })