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

fix(ollama): pass numCtx through so local minds aren't truncated to 2K

atomanticagentd7ed7ca164ce
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 66f5233b99..24b6913b6d 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -234,6 +234,22 @@ Two caveats:
The Models → Runtimes page shows the window loaded models are actually running
at, and flags it when it's below what an agent harness needs.
+### Ollama API provider ignores its num_ctx (prompts truncated to ~2K tokens)
+
+**Symptom**: a local mind or CoS run on the `ollama` API provider behaves as if
+it forgot most of its prompt; the Ollama log repeats
+`truncating input prompt limit=2050 prompt=14776` and `ollama ps` shows the
+model at `CONTEXT 4096` even though **Local num_ctx** is set higher.
+
+**Cause**: Ollama's OpenAI-compatible `/v1/chat/completions` has no way to set
+the context window — it ignores `num_ctx` in any position — so each `/v1`
+request loads the model at the daemon default.
+
+**Solution**: update PortOS. An API run whose Ollama provider sets **Local
+num_ctx** is sent to Ollama's native `/api/chat` with `options.num_ctx`, which
+loads the model at that window. Runs with no num_ctx stay on `/v1` and use the
+daemon default (`OLLAMA_CONTEXT_LENGTH`).
+
## Chief of Staff Issues
### CoS Not Running
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.md
index 2b85b3c0ef..cd1d1acbde 100644
--- a/server/lib/aiToolkit/AGENTS.md
+++ b/server/lib/aiToolkit/AGENTS.md
@@ -6,6 +6,7 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous
- `index.js` exports `createAIToolkit`, `createProviderStatusService`, the four Router factories (providers / runs / prompts / providerStatus), and the context-fit pair `knownContextWindow` / `contextWindowRejection` — the host applies the same rule to the EXPLICITLY requested provider, which `getFallbackProvider` never sees. Both answer `null` for an unknown window, which every caller must keep reading as "no constraint"; nothing infers a window from a model id.
- **The Ollama `num_ctx` ceiling is declared ONCE, in `internal/ollamaBacked.js`** (`clampToRuntimeContextWindow`), beside the predicate that gates it. `knownContextWindow` applies it through that helper and must never restate the `Math.min` inline — the host's prompt budgeter (`server/services/stageRunner.js#effectiveContextWindow`), the untrusted-content abuse guard (`server/services/untrustedContent.js#runUntrustedContentAnalysis`, which held its own hand-rolled `Math.min` pair until #7473) and the browser's provider-card meter call the same function, and when the rule was stated twice they drifted (#7466). It is an upper BOUND over every planning rung, a user's explicit `contextWindow` included, and the answer outright when nothing else declared one. Host callers import the `internal/` leaf directly, or `knownContextWindow`/`contextWindowRejection` straight off `providerStatus.js` (both deep imports skip the public barrel's `fs`/`child_process` reach): `stageRunner.js` sits inside the server suite's import budget, and `untrustedContent.js` — a request-path module — deliberately imports `providerStatus.js` rather than `stageRunner.js`, whose own closure would cost that budget ~40 extra module instantiations per reaching test file for no behavior it needs.
- **A rung of that ceiling this directory cannot resolve arrives as DATA, never as an import out.** PortOS also sets the daemon-wide window through the ambient `OLLAMA_CONTEXT_LENGTH` (`server/lib/ollamaContext.js#resolveOllamaContextLength`), which the toolkit may not reach and the browser cannot read at all — so the host resolves it and stamps it onto an in-memory provider projection with `withRuntimeContextWindow`, declared in the same file as the clamp that reads it. `runtimeContextWindow` ranks BELOW `provider.numCtx`, exactly as `resolveOllamaContextLength` ranks the two, and is never persisted to `providers.json` (it describes the process running right now). Adding another host-resolved rung follows the same shape: stamp a field beside the reader, do not import out. Precedent: #7472.
+- **An Ollama API run with a `numCtx` streams from the native `/api/chat`, not `/v1/chat/completions`** (`internal/ollamaNativeChat.js`). Ollama's OpenAI-compatible endpoint has no context-window knob — it ignores `num_ctx` top-level and under `options` — so a `/v1` run loads the model at the daemon default and silently keeps only the prompt's tail. The native NDJSON frames are reshaped into the OpenAI chunk the runner already reads, so cancellation, stall bounds, reasoning salvage and finalization stay shared; runs without `numCtx` and every non-Ollama endpoint stay on `/v1`.
- Provider configuration (models, tiers, fallbacks) is persisted and migrated by `internal/providerServiceState.js`; the public facade is `providers.js`
- `loadProviders()` auto-migrates legacy codex configs to the `codex-configured-default` sentinel; `server/index.js` warms it at startup so the rewrite happens before any request
- PortOS extends toolkit routes in `server/routes/providers.js` for vision testing and provider status (status routes live in PortOS, not the toolkit, because they call PortOS-side socket helpers)
diff --git a/server/lib/aiToolkit/internal/ollamaBacked.js b/server/lib/aiToolkit/internal/ollamaBacked.js
index 4afd240078..b554585f94 100644
--- a/server/lib/aiToolkit/internal/ollamaBacked.js
+++ b/server/lib/aiToolkit/internal/ollamaBacked.js
@@ -76,10 +76,11 @@ export function ollamaBaseFromProvider(provider) {
* `numCtx` falls THROUGH to the runtime rung rather than collapsing the whole
* ceiling to "none", so a malformed record cannot silently widen the budget.
*
- * One deliberate limit, conservative (it can only under-plan): only Ollama
- * honors the runner's top-level `num_ctx`; every other OpenAI-compatible
- * endpoint ignores it, so there the field describes a window nothing enforces
- * and must never refuse a request. Hence the `isOllamaBackedProvider` gate —
+ * One deliberate limit, conservative (it can only under-plan): only an Ollama
+ * daemon is sent `numCtx` (the runner moves such a run to the native
+ * `/api/chat`, see ./ollamaNativeChat.js, because `/v1` ignores `num_ctx`);
+ * every other OpenAI-compatible endpoint has no such knob, so there the field
+ * describes a window nothing enforces and must never refuse a request. Hence the `isOllamaBackedProvider` gate —
* and why this lives beside that predicate rather than in its own module, which
* would add a module to the import closure of every suite reaching either end
* of one rule.
diff --git a/server/lib/aiToolkit/internal/ollamaNativeChat.js b/server/lib/aiToolkit/internal/ollamaNativeChat.js
new file mode 100644
index 0000000000..07f2938b24
--- /dev/null
+++ b/server/lib/aiToolkit/internal/ollamaNativeChat.js
@@ -0,0 +1,111 @@
+import { isOllamaBackedProvider, ollamaBaseFromProvider } from './ollamaBacked.js';
+
+/**
+ * Ollama's native `/api/chat` transport for API runs that carry a `numCtx`.
+ *
+ * Ollama's OpenAI-compatible `/v1/chat/completions` has no way to set the
+ * context window: it ignores both a top-level `num_ctx` and an `options`
+ * object, so every `/v1` request loads the model at the daemon default
+ * (`OLLAMA_CONTEXT_LENGTH`, 4096 when unset) and the daemon silently keeps
+ * only the prompt's tail (`truncating input prompt limit=2050 …`). A
+ * configured `numCtx` therefore never took effect for a `/v1` run, and a model
+ * loaded at a wider window by another caller was reloaded back down by the
+ * next `/v1` request. The native endpoint honors `options.num_ctx`, so a run
+ * whose provider asks for a window goes there instead. Runs with no `numCtx`
+ * stay on `/v1`, where the daemon default is exactly what they asked for.
+ *
+ * The native stream is NDJSON (`{message:{content,thinking},done,done_reason}`
+ * per line, `{error}` on failure) rather than SSE; {@link ollamaNativeFrameToChunk}
+ * reshapes each frame into the OpenAI chunk the runner's reader already
+ * consumes, so cancellation, stall bounds, reasoning salvage and finalization
+ * are shared with the `/v1` path rather than restated.
+ *
+ * Self-contained like the rest of this directory (see ../AGENTS.md).
+ */
+
+/** The configured window as a positive integer, or `null`. */
+function requestedNumCtx(provider) {
+ const n = Number(provider?.numCtx);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
+}
+
+/**
+ * The native chat URL to use for this provider's API run, or `null` to keep
+ * the OpenAI-compatible `/v1/chat/completions` request. Only an Ollama daemon
+ * with an explicit `numCtx` moves: that is the one setting `/v1` cannot carry.
+ *
+ * @param {object|null|undefined} provider
+ * @returns {string|null}
+ */
+export function ollamaNativeChatUrl(provider) {
+ if (!requestedNumCtx(provider) || !provider?.endpoint) return null;
+ if (!isOllamaBackedProvider(provider)) return null;
+ return `${ollamaBaseFromProvider({ endpoint: provider.endpoint })}/api/chat`;
+}
+
+/** `data:image/png;base64,AAAA` → `AAAA`; native messages take bare base64. */
+function bareBase64(dataUrl) {
+ const s = String(dataUrl || '');
+ const comma = s.indexOf(',');
+ return s.startsWith('data:') && comma !== -1 ? s.slice(comma + 1) : s;
+}
+
+/**
+ * One OpenAI-style user message (string or content-part array) as a native
+ * Ollama message: text joined into `content`, images into `images`.
+ */
+function toNativeMessage(messageContent) {
+ if (!Array.isArray(messageContent)) return { role: 'user', content: String(messageContent ?? '') };
+ const text = [];
+ const images = [];
+ for (const part of messageContent) {
+ if (part?.type === 'text' && typeof part.text === 'string') text.push(part.text);
+ else if (part?.type === 'image_url') {
+ const url = typeof part.image_url === 'string' ? part.image_url : part.image_url?.url;
+ if (url) images.push(bareBase64(url));
+ }
+ }
+ return { role: 'user', content: text.join('\n'), ...(images.length ? { images } : {}) };
+}
+
+/**
+ * The native `/api/chat` body equivalent to the runner's `/v1` body.
+ * `generation` is the `apiGenerationOptions(provider)` result: sampling knobs
+ * move under `options`, Ollama's own `think` flag stays top-level.
+ *
+ * @param {{ model: string, messageContent: string|Array<object>, provider: object, generation?: object, maxTokens?: number }} args
+ */
+export function buildOllamaNativeChatBody({ model, messageContent, provider, generation = {}, maxTokens }) {
+ const { think, temperature, top_p: topP } = generation;
+ return {
+ model,
+ messages: [toNativeMessage(messageContent)],
+ stream: true,
+ ...(typeof think === 'boolean' ? { think } : {}),
+ options: {
+ num_ctx: requestedNumCtx(provider),
+ ...(temperature === undefined ? {} : { temperature }),
+ ...(topP === undefined ? {} : { top_p: topP }),
+ ...(Number.isInteger(maxTokens) && maxTokens > 0 ? { num_predict: maxTokens } : {}),
+ },
+ };
+}
+
+/**
+ * One parsed native stream frame as the OpenAI chunk shape the runner reads
+ * (`choices[0].delta.{content,thinking}` + `finish_reason`). A frame carrying
+ * `error` throws so the run finalizes as a stream error instead of a silent,
+ * empty success.
+ *
+ * @param {object} frame
+ * @returns {object}
+ */
+export function ollamaNativeFrameToChunk(frame) {
+ if (frame?.error) throw new Error(`Ollama stream error: ${String(frame.error)}`);
+ const message = frame?.message || {};
+ const delta = {};
+ if (typeof message.content === 'string' && message.content) delta.content = message.content;
+ if (typeof message.thinking === 'string' && message.thinking) delta.thinking = message.thinking;
+ const finishReason = frame?.done === true ? (frame.done_reason || 'stop') : null;
+ return { choices: [{ delta, ...(finishReason ? { finish_reason: finishReason } : {}) }] };
+}
diff --git a/server/lib/aiToolkit/internal/ollamaNativeChat.test.js b/server/lib/aiToolkit/internal/ollamaNativeChat.test.js
new file mode 100644
index 0000000000..8801aad946
--- /dev/null
+++ b/server/lib/aiToolkit/internal/ollamaNativeChat.test.js
@@ -0,0 +1,32 @@
+import { describe, it, expect } from 'vitest';
+import { buildOllamaNativeChatBody, ollamaNativeChatUrl } from './ollamaNativeChat.js';
+
+describe('ollamaNativeChat', () => {
+ // Endpoint spelling is user input; every Ollama shape must land on the same
+ // native URL, and anything that is not an Ollama daemon must stay on /v1.
+ it('resolves the native URL only for an Ollama daemon with a positive numCtx', () => {
+ expect(ollamaNativeChatUrl({ id: 'ollama', endpoint: 'http://localhost:11434/v1/', numCtx: 8192 }))
+ .toBe('http://localhost:11434/api/chat');
+ expect(ollamaNativeChatUrl({ id: 'custom', type: 'api', endpoint: 'http://192.0.2.10:11434/v1', numCtx: '16384' }))
+ .toBe('http://192.0.2.10:11434/api/chat');
+ expect(ollamaNativeChatUrl({ id: 'ollama', endpoint: 'http://localhost:11434/v1', numCtx: null })).toBeNull();
+ expect(ollamaNativeChatUrl({ id: 'ollama', endpoint: 'http://localhost:11434/v1', numCtx: 0 })).toBeNull();
+ expect(ollamaNativeChatUrl({ id: 'lmstudio', endpoint: 'http://localhost:1234/v1', lmstudioBacked: true, numCtx: 8192 })).toBeNull();
+ });
+
+ // The native message format differs from OpenAI's content parts: images are
+ // bare base64 strings beside the text, not data-URL parts inside it.
+ it('converts OpenAI content parts with images into a native message', () => {
+ const body = buildOllamaNativeChatBody({
+ model: 'example-vision',
+ provider: { numCtx: 8192 },
+ messageContent: [
+ { type: 'image_url', image_url: { url: 'data:image/png;base64,AAAA' } },
+ { type: 'text', text: 'describe' },
+ ],
+ });
+ expect(body.messages).toEqual([{ role: 'user', content: 'describe', images: ['AAAA'] }]);
+ expect(body.options).toEqual({ num_ctx: 8192 });
+ expect('think' in body).toBe(false);
+ });
+});
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index bd87d4b31a..a5e48030d6 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -7,6 +7,7 @@ import { spawn, ChildProcess } from 'child_process';
import { randomUUID } from 'crypto';
import { analyzeError, ERROR_CATEGORIES } from './errorDetection.js';
import { apiGenerationOptions } from './internal/generationOptions.js';
+import { buildOllamaNativeChatBody, ollamaNativeChatUrl, ollamaNativeFrameToChunk } from './internal/ollamaNativeChat.js';
import { describeTransportError, fetchWithPreHeaderRetry, isReplaySafeLocalRequest } from './internal/preHeaderRetry.js';
// The two streaming ceilings (no-progress bound, absolute runtime cap) live in
// a leaf module so a host's own backstop timer can read the absolute bound
@@ -768,10 +769,26 @@ export function createRunnerService(config = {}) {
return runId;
}
}
+ // An Ollama provider with a `numCtx` goes to the native `/api/chat`:
+ // `/v1/chat/completions` cannot carry a context window (it ignores
+ // `num_ctx` in any position), so the model would load at the daemon
+ // default and silently drop the prompt's head. See
+ // ./internal/ollamaNativeChat.js.
+ const nativeOllamaUrl = ollamaNativeChatUrl(provider);
+ const requestModel = model || provider.defaultModel;
+ const requestBody = nativeOllamaUrl
+ ? buildOllamaNativeChatBody({ model: requestModel, messageContent, provider, generation: apiGenerationOptions(provider), maxTokens })
+ : {
+ model: requestModel,
+ messages: [{ role: 'user', content: messageContent }],
+ stream: true,
+ ...apiGenerationOptions(provider),
+ ...(Number.isInteger(maxTokens) && maxTokens > 0 ? { max_tokens: maxTokens } : {}),
+ };
const response = !endpointGuard.allowed
? { ok: false, error: `Endpoint blocked: ${endpointGuard.reason}`, status: 0 }
: ready.success
- ? await fetchWithPreHeaderRetry(() => fetch(`${provider.endpoint}/chat/completions`, {
+ ? await fetchWithPreHeaderRetry(() => fetch(nativeOllamaUrl || `${provider.endpoint}/chat/completions`, {
method: 'POST',
headers,
signal: controller.signal,
@@ -779,18 +796,7 @@ export function createRunnerService(config = {}) {
// / `absoluteTimeout` above as the run's only bounds — see
// ./internal/streamTransport.js for what fired first without it.
dispatcher: streamTransportDispatcher(),
- body: JSON.stringify({
- model: model || provider.defaultModel,
- messages: [{ role: 'user', content: messageContent }],
- stream: true,
- ...apiGenerationOptions(provider),
- ...(Number.isInteger(maxTokens) && maxTokens > 0 ? { max_tokens: maxTokens } : {}),
- // 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
- // OpenAI-style endpoints). Only sent when the provider opts in.
- ...(Number(provider.numCtx) > 0 ? { num_ctx: Number(provider.numCtx) } : {})
- })
+ body: JSON.stringify(requestBody)
}), {
signal: controller.signal,
// A caller-owned budget/admission hook accounts for one invocation;
@@ -836,6 +842,18 @@ export function createRunnerService(config = {}) {
// the terminal-sentinel comparison, or `[DONE]\r` falls through to
// JSON.parse and throws at the very end of an otherwise-good stream.
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
+ // The native Ollama stream is NDJSON — one bare JSON object per line,
+ // no `data: ` framing — reshaped into the OpenAI chunk read below.
+ if (nativeOllamaUrl) {
+ if (!line.trim()) return;
+ const frame = safeJsonParse(line, null);
+ if (!frame) {
+ console.error(`❌ Run ${runId} skipped an unparseable stream frame (${line.length} chars)`);
+ return;
+ }
+ consumeChunk(ollamaNativeFrameToChunk(frame));
+ return;
+ }
if (!line.startsWith('data: ')) return;
const data = line.slice(6);
@@ -853,6 +871,12 @@ export function createRunnerService(config = {}) {
console.error(`❌ Run ${runId} skipped an unparseable stream frame (${data.length} chars)`);
return;
}
+ consumeChunk(parsed);
+ };
+
+ // One OpenAI-shaped chunk — an SSE `data:` frame, or a native Ollama
+ // frame already reshaped by ollamaNativeFrameToChunk.
+ const consumeChunk = (parsed) => {
const choice = parsed?.choices?.[0];
if (typeof choice?.finish_reason === 'string') finishReason = choice.finish_reason;
const delta = choice?.delta;
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 7ad935753a..3a9a982c77 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -402,22 +402,92 @@ describe('AI Toolkit runner service', () => {
expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ success: false }));
});
- it('sends num_ctx in the request body when the provider opts in', async () => {
+ // Ollama's `/v1/chat/completions` ignores `num_ctx` in every position, so a
+ // configured window silently never applied and every long prompt was cut to
+ // its ~2K-token tail. A run that asks for a window must reach `/api/chat`.
+ const stubNdjsonFetch = (frames) => {
+ const encoder = new TextEncoder();
+ let i = 0;
+ const fetch = vi.fn(async () => ({ ok: true, body: { getReader: () => ({
+ read: async () => (i < frames.length
+ ? { done: false, value: encoder.encode(frames[i++]) }
+ : { done: true, value: undefined }),
+ }) } }));
+ vi.stubGlobal('fetch', fetch);
+ return fetch;
+ };
+
+ it('sends an Ollama run with numCtx to native /api/chat and reads its NDJSON stream', async () => {
const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
tempDirs.push(dataDir);
- const fetch = stubStreamingFetch();
+ const line = (frame) => `${JSON.stringify(frame)}\n`;
+ // The first frame is split mid-JSON across two reads.
+ const first = line({ message: { role: 'assistant', content: '', thinking: 'mull' }, done: false });
+ const fetch = stubNdjsonFetch([
+ first.slice(0, 20), first.slice(20),
+ line({ message: { role: 'assistant', content: 'he' }, done: false }),
+ line({ message: { role: 'assistant', content: 'llo' }, done: false }),
+ line({ message: { role: 'assistant', content: '' }, done: true, done_reason: 'length', prompt_eval_count: 9000 }),
+ ]);
+ const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) } });
+ let complete;
+ const completed = new Promise((resolve) => { complete = resolve; });
- const runner = createRunnerService({
- dataDir,
- hooks: { ensureProviderReady: async () => ({ success: true }) }
+ await runner.executeApiRun({
+ runId: 'run-numctx',
+ provider: runReady({ numCtx: 16384, temperature: 0.6, thinking: false }),
+ model: null, prompt: 'hi', maxTokens: 256, workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,
});
+
+ expect(await completed).toMatchObject({ success: true, finishReason: 'length' });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch.mock.calls[0][0]).toBe('http://localhost:11434/api/chat');
+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual({
+ model: 'llama3',
+ messages: [{ role: 'user', content: 'hi' }],
+ stream: true,
+ think: false,
+ options: { num_ctx: 16384, temperature: 0.6, num_predict: 256 },
+ });
+ expect(await readFile(join(dataDir, 'runs', 'run-numctx', 'output.txt'), 'utf-8')).toBe('hello');
+ });
+
+ it('fails an Ollama native run whose stream reports an error frame', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ stubNdjsonFetch([`${JSON.stringify({ error: 'model runner has unexpectedly stopped' })}\n`]);
+ const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) } });
+ let complete;
+ const completed = new Promise((resolve) => { complete = resolve; });
+
+ await runner.executeApiRun({
+ runId: 'run-numctx-error', provider: runReady({ numCtx: 16384 }), model: null, prompt: 'hi',
+ workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,
+ });
+
+ const result = await completed;
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('model runner has unexpectedly stopped');
+ });
+
+ it('keeps a non-Ollama endpoint with numCtx on /chat/completions and sends it no num_ctx', 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-numctx', provider: runReady({ numCtx: 32768 }), model: null, prompt: 'hi', workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: () => done() });
+ await runner.executeApiRun({
+ runId: 'run-llama-numctx',
+ provider: runReady({ id: 'llama', endpoint: 'http://127.0.0.1:5568/v1', llamaBacked: true, numCtx: 16384 }),
+ model: null, prompt: 'hi', workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: () => done(),
+ });
await completed;
- expect(fetch).toHaveBeenCalledTimes(1);
- expect(JSON.parse(fetch.mock.calls[0][1].body).num_ctx).toBe(32768);
+ expect(fetch.mock.calls[0][0]).toBe('http://127.0.0.1:5568/v1/chat/completions');
+ const body = JSON.parse(fetch.mock.calls[0][1].body);
+ expect(body.num_ctx).toBeUndefined();
+ expect(body.options).toBeUndefined();
});
it('sends configured Ollama temperature and thinking mode', async () => {
@@ -512,6 +582,7 @@ describe('AI Toolkit runner service', () => {
await completed;
expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch.mock.calls[0][0]).toBe('http://localhost:11434/v1/chat/completions');
expect('num_ctx' in JSON.parse(fetch.mock.calls[0][1].body)).toBe(false);
});
diff --git a/server/services/stageRunner.test.js b/server/services/stageRunner.test.js
index 54b9d1b050..e580ca73ae 100644
--- a/server/services/stageRunner.test.js
+++ b/server/services/stageRunner.test.js
@@ -181,7 +181,7 @@ describe('stageRunner — context windows', () => {
{ type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 131_072, modelContextWindows: { 'qwen3:32b': 40_960 } },
'qwen3:32b'
)).toBe(40_960);
- // Only Ollama honors the runner's top-level num_ctx; for anything else the
+ // Only an Ollama daemon is sent num_ctx (native /api/chat); for anything else the
// field constrains nothing, so the ladder is untouched.
expect(effectiveContextWindow(
{ id: 'codex', type: 'cli', command: 'codex', numCtx: 32_768 },