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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: honor Ollama context sizes in abuse guard and playground (#9436)
[._.]/ Adam Eivy3d2dd5c9ffe5
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.jsindex 996e45684c..0fc376cd52 100644--- a/server/services/localLlmPlayground.js+++ b/server/services/localLlmPlayground.js@@ -138,7 +138,8 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, systemallowCustomEndpoint: provider.allowCustomEndpoint === true,});- const stream = backend === 'ollama' && nativeOllamaUsage ? streamOllamaChat : streamOpenAiChat;+ const requestBody = { ...(Number(provider.numCtx) > 0 ? { num_ctx: Number(provider.numCtx) } : {}), ...extraBody };+ const stream = backend === 'ollama' && (nativeOllamaUsage || Number(requestBody.num_ctx) > 0) ? streamOllamaChat : streamOpenAiChat;return stream({endpoint: provider.endpoint,apiKey: provider.apiKey,@@ -147,11 +148,9 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, systemtemperature,maxTokens,// The caller's knobs win over the provider default, so a caller measuring a- // specific value is never silently run at the provider's. (Ollama is not one- // of those callers: its OpenAI-compatible endpoint drops unknown body fields,- // so its context window is a daemon-restart knob — see the transport rule in- // `lib/localModelTuning.js` and `ollamaManager.ensureContextWindow`.)- extraBody: { ...(Number(provider.numCtx) > 0 ? { num_ctx: Number(provider.numCtx) } : {}), ...extraBody },+ // specific value is never silently run at the provider's. A requested+ // Ollama context uses native chat, which maps it to options.num_ctx.+ extraBody: requestBody,signal,onChunk,// Registering `onStats` is what asks the daemon for token counts; a runtime@@ -183,8 +182,8 @@ export async function runLocalLlmTest({// 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.+ // decode/prefill durations survive. A requested num_ctx also needs native+ // chat; other playground runs keep the OpenAI-compatible transport.nativeOllamaUsage = false,}) {const provider = await resolveLocalProvider(backend);diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.jsindex 96180c575b..431e9a8791 100644--- a/server/services/localLlmPlayground.test.js+++ b/server/services/localLlmPlayground.test.js@@ -138,6 +138,42 @@ describe('runLocalLlmTest timeout/abort contract', () => {global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, body: { getReader: () => reader } });};+ it.each([+ { numCtx: 16384, extraBody: {} },+ { numCtx: 4096, extraBody: { num_ctx: 16384 } },+ ])('honors the configured or caller-overridden Ollama context on normal playground runs: %j', async ({ numCtx, extraBody }) => {+ getProviderById.mockResolvedValue({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1', numCtx });+ createRun.mockResolvedValue({ runId: 'run-1', provider: { id: 'ollama' } });+ stubStream(makeReader([`${JSON.stringify({ message: { content: 'Done.' }, done: true, done_reason: 'stop', prompt_eval_count: 10, eval_count: 2 })}\n`]));+ const tokens = [];+ const result = await runLocalLlmTest({ backend: 'ollama', modelId: 'm1', prompt: 'hi', maxTokens: 32, extraBody, onToken: delta => tokens.push(delta) });+ expect(result.error).toBeUndefined();+ expect(result.text).toBe('Done.');+ expect(tokens).toEqual(['Done.']);+ const [url, request] = global.fetch.mock.calls[0];+ expect(url).toBe('http://localhost:11434/api/chat');+ expect(JSON.parse(request.body)).toMatchObject({ model: 'm1', stream: true, options: { num_ctx: 16384, num_predict: 32 } });+ expect(finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({ output: 'Done.', success: true }));+ });++ it('keeps the OpenAI transport for Ollama without a context override and for other backends', async () => {+ for (const [backend, numCtx] of [['ollama', undefined], ['lmstudio', 16384]]) {+ const endpoint = backend === 'ollama' ? 'http://localhost:11434/v1' : 'http://localhost:1234/v1';+ getProviderById.mockResolvedValue({ id: backend, type: 'api', endpoint, numCtx });+ createRun.mockResolvedValue({ runId: 'run-1', provider: { id: backend } });+ stubStream(makeReader([sse({ content: 'Done.' })]));+ const result = await runLocalLlmTest({ backend, modelId: 'm1', prompt: 'hi', maxTokens: 32 });+ expect(result.error).toBeUndefined();+ const [url, request] = global.fetch.mock.calls[0];+ expect(url).toBe(`${endpoint}/chat/completions`);+ expect(JSON.parse(request.body)).toEqual({+ model: 'm1', messages: [{ role: 'user', content: 'hi' }], stream: true,+ temperature: 0.3, max_tokens: 32, stream_options: { include_usage: true },+ ...(numCtx ? { num_ctx: numCtx } : {}),+ });+ }+ });+it('returns the content streamed before an abort as text and persists it on the failed run', async () => {stubStream(makeReader([sse({ content: 'Hello ' }), sse({ content: 'world' })], { abort: true }));diff --git a/server/services/untrustedContent.js b/server/services/untrustedContent.jsindex efa6009a68..287b72fe3b 100644--- a/server/services/untrustedContent.js+++ b/server/services/untrustedContent.js@@ -15,6 +15,7 @@ import { formatUntrustedContent, isUntrustedContentProvider, resolveUntrustedCon// headroom for.import { withOllamaRuntimeContextWindow } from '../lib/ollamaContext.js';import { knownContextWindow } from '../lib/aiToolkit/providerStatus.js';+import { ollamaNativeChatUrl } from '../lib/aiToolkit/internal/ollamaNativeChat.js';const failure = (code, message) => ({ ok: false, safe: false, code, message });@@ -330,20 +331,28 @@ async function analyzeScreenedContent({ provider, model, content, prompt, source// This transport deliberately has no runner failure hooks, run archives,// model healing, agent escalation, fallback, redirect, or tool execution.// Otherwise attacker-controlled diagnostics could become an autofixer task.+ const nativeUrl = ollamaNativeChatUrl(selected);const result = await withAbortTimeout(Math.min(Math.max(Number(selected.timeout) || 300_000, 1000), 300_000), async signal => {- const response = await fetch(`${selected.endpoint.replace(/\/$/, '')}/chat/completions`, {+ const response = await fetch(nativeUrl || `${selected.endpoint.replace(/\/$/, '')}/chat/completions`, {method: 'POST', redirect: 'error', signal,headers: { 'Content-Type': 'application/json', ...(selected.apiKey ? { Authorization: `Bearer ${selected.apiKey}` } : {}) },body: JSON.stringify({model: effectiveModel,messages: [{ role: 'system', content: taskPrompt }, { role: 'user', content: evidence }],- stream: false, max_tokens: maxTokens,- ...(Number(selected.numCtx) > 0 ? { num_ctx: Number(selected.numCtx) } : {}),+ stream: false,+ ...(nativeUrl+ ? { options: { num_ctx: Math.floor(Number(selected.numCtx)), num_predict: maxTokens } }+ : { max_tokens: maxTokens, ...(Number(selected.numCtx) > 0 ? { num_ctx: Number(selected.numCtx) } : {}) }),}),});if (!response.ok || response.redirected) return null;const buffer = await readBodyCapped(response, config.maxOutputChars * 8 + 4096);const parsed = buffer ? safeJSONParse(buffer.toString('utf8')) : null;+ if (nativeUrl) {+ if (parsed?.error || parsed?.done !== true || parsed.done_reason !== 'stop'+ || parsed.message?.tool_calls?.length || parsed.message?.function_call) return null;+ return { text: parsed.message?.content };+ }if (!Array.isArray(parsed?.choices) || parsed.choices.length !== 1) return null;const choice = parsed.choices[0];if (choice.finish_reason !== 'stop' || choice.message?.tool_calls?.length || choice.message?.function_call) return null;diff --git a/server/services/untrustedContent.test.js b/server/services/untrustedContent.test.jsindex f1e0eb524b..d2f400920b 100644--- a/server/services/untrustedContent.test.js+++ b/server/services/untrustedContent.test.js@@ -53,6 +53,60 @@ describe('shared external-content boundary', () => {expect(await runUntrustedContentAnalysis({ ...args, content: 'x'.repeat(4096) })).toMatchObject({ code: 'untrusted-content-context-too-small' });expect(mocks.fetch).not.toHaveBeenCalled();});+ it('sends complete wider evidence through native Ollama chat with the configured context and output budget', async () => {+ mocks.fetch.mockResolvedValue(new Response(JSON.stringify({+ message: { content: '{"action":"review"}' }, done: true, done_reason: 'stop',+ })));+ const content = 'Example evidence. '.repeat(500);+ expect(await runUntrustedContentAnalysis({ ...args, content, provider: { ...local, numCtx: 16384 } }))+ .toMatchObject({ ok: true, value: { action: 'review' } });+ const [url, request] = mocks.fetch.mock.calls[0];+ expect(url).toBe('http://127.0.0.1:11434/api/chat');+ expect(request).toMatchObject({ method: 'POST', redirect: 'error', signal: expect.any(AbortSignal) });+ const body = JSON.parse(request.body);+ expect(body).toEqual({+ model: 'example-text', stream: false, options: { num_ctx: 16384, num_predict: 4096 },+ messages: [{ role: 'system', content: expect.any(String) }, { role: 'user', content: expect.stringContaining(content) }],+ });+ expect(mocks.fetch).toHaveBeenCalledTimes(1);+ });+ it('preserves the OpenAI request body for endpoints that cannot use native Ollama chat', async () => {+ for (const provider of [local, { ...local, endpoint: 'http://127.0.0.1:1234/v1', numCtx: 16384 }]) {+ expect(await runUntrustedContentAnalysis({ ...args, provider })).toMatchObject({ ok: true });+ const [url, request] = mocks.fetch.mock.calls.at(-1);+ expect(url).toBe(`${provider.endpoint}/chat/completions`);+ expect(JSON.parse(request.body)).toEqual({+ model: 'example-text', stream: false,+ max_tokens: 1024,+ ...(provider.numCtx ? { num_ctx: 16384 } : {}),+ messages: [{ role: 'system', content: expect.any(String) }, { role: 'user', content: expect.any(String) }],+ });+ }+ });+ it('fails closed on native redirects, oversized bodies, tools and incomplete or erroneous endings without fallback', async () => {+ const valid = { message: { content: '{"action":"review"}' }, done: true, done_reason: 'stop' };+ const nativeResponses = [+ { ...valid, done_reason: 'length' },+ { ...valid, done_reason: undefined },+ { ...valid, done: false },+ { ...valid, error: 'example daemon error' },+ { ...valid, message: { ...valid.message, tool_calls: [{}] } },+ { ...valid, message: { ...valid.message, function_call: {} } },+ { ...valid, padding: 'x'.repeat(32_000 * 8 + 4096) },+ ].map(body => new Response(JSON.stringify(body)));+ const redirected = new Response(JSON.stringify(valid));+ Object.defineProperty(redirected, 'redirected', { value: true });+ nativeResponses.push(redirected);+ for (const nativeResponse of nativeResponses) {+ mocks.fetch.mockResolvedValue(nativeResponse);+ expect(await runUntrustedContentAnalysis({ ...args, provider: { ...local, numCtx: 16384 } }))+ .toMatchObject({ ok: false, code: 'untrusted-content-reasoner-failed' });+ }+ mocks.fetch.mockRejectedValue(new TypeError('Redirect rejected'));+ expect(await runUntrustedContentAnalysis({ ...args, provider: { ...local, numCtx: 16384 } }))+ .toMatchObject({ code: 'untrusted-content-reasoner-failed' });+ expect(mocks.fetch).toHaveBeenCalledTimes(nativeResponses.length + 1);+ });it('fails closed on corrupt policies, unsafe pins and cloud processing of private messages', async () => {mocks.read.mockResolvedValue({ corrupt: true, settings: {} });expect(await runUntrustedContentAnalysis(args)).toMatchObject({ code: 'untrusted-content-settings-unreadable' });