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
stop local-Ollama runs from silently truncating long prompts to 4K tokens
[._.]/ Adam Eivya1d8665b26ad
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b16678a832..8ef7b2507c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,7 @@## Fixed+- **[ollama-context-truncation] Local-Ollama runs no longer silently truncate long prompts to ~4K tokens.** PortOS sends stage prompts to Ollama's OpenAI-compatible `/v1/chat/completions`, which defaults to a ~4K context window and silently drops anything past it — so whole-manuscript editorial passes (the completeness pass concatenates up to 200K chars ≈ 50K tokens) were really only reviewing the tail of the manuscript with no error raised. The toolkit runner now sends a per-request `num_ctx` when the provider config carries one (a new optional `numCtx` provider field, honored by Ollama and ignored by other OpenAI-style endpoints), and `ensureBackendProvider` defaults the Ollama provider to a generous window at boot (`OLLAMA_NUM_CTX` env override, default 32768). LM Studio is unaffected (it sets context at model load). Cloud providers were never affected. This is the urgent half of the editorial context work; the full context-window-aware full-manuscript↔chunked strategy is planned in `docs/plans/2026-05-31-context-aware-manuscript-editorial.md` (`[context-aware-editorial-budgeting]`).- **[provider-fallback-model-leak] Falling back to another provider no longer leaks the primary's model id onto it.** When a stage's primary provider was unavailable (e.g. Codex benched after an OpenAI content-safety refusal), the model resolved against the primary — `codex-configured-default` — was carried verbatim onto the fallback provider, so the run logged `LM Studio/codex-configured-default` and then 400'd because LM Studio has no such model (and Claude Code rejected it the same way). `stageRunner` now re-resolves the model against the *fallback* provider (honoring its configured `fallbackModel`, else its own default / args-baked model) instead of forwarding the primary's resolved model, and the toolkit `createRun` run record + log line do the same.- **[ltx2-fflf-skips-last-image-resize-when-both-frames-set] ltx2 FFLF now resizes both anchor frames.** The two-keyframe ltx2 FFLF path passes both `--image` and `--last-image` into `scripts/generate_ltx2.py`, but Video Gen only resized the start image when both anchors were present. The end frame could therefore reach `KeyframeInterpolationPipeline.generate_and_save()` at its original dimensions. `videoGen/local.js` now treats ltx2 true-FFLF as a real last-image consumer and runs the same ffmpeg resize/crop pass used for multi-keyframes, with a regression test asserting the helper receives resized start and end paths.- **[ref-watch-phosphene-teacache-extend-a2v-denoise] TeaCache now accelerates ltx2 Extend and A2V Stage 1.** `scripts/generate_ltx2.py` now patches the LTX-2 `extend` and `a2vid_two_stage` denoise-loop import sites (the modules where `ExtendPipeline`/`AudioToVideoPipeline` actually call `guided_denoise_loop`), activating the existing Stage-1 TeaCache controller only around Extend and A2V calls and clearing the gate afterward. TeaCache stays default-on for those slow paths, with `--no-teacache` to opt out and `--teacache-thresh` to trade fidelity for speed (~1.2× at the 0.5 default, up to ~3× at 1.5).diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex c1247e4730..5e446ea435 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -221,6 +221,7 @@ export function createProviderService(config = {}) {heavyModel: providerData.heavyModel || null,fallbackProvider: providerData.fallbackProvider || null,fallbackModel: providerData.fallbackModel || null,+ numCtx: providerData.numCtx || null,timeout: providerData.timeout || 300000,enabled: providerData.enabled !== false,envVars: providerData.envVars || {},diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 5215cf41ab..8ee2b1abd0 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -335,7 +335,12 @@ export function createRunnerService(config = {}) {body: JSON.stringify({model: model || provider.defaultModel,messages: [{ role: 'user', content: messageContent }],- stream: true+ stream: true,+ // 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) } : {})})}).catch(err => ({ ok: false, error: err.message, status: 0 })): { ok: false, error: `Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`, status: 0 };diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex f45824fb48..ef9450595f 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -62,4 +62,67 @@ describe('AI Toolkit runner service', () => {errorCategory: 'unknown'});});++ const stubStreamingFetch = () => {+ const encoder = new TextEncoder();+ const chunks = [+ encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'hi' } }] })}\n`),+ encoder.encode('data: [DONE]\n')+ ];+ let i = 0;+ const body = {+ getReader: () => ({+ read: async () => (i < chunks.length+ ? { done: false, value: chunks[i++] }+ : { done: true, value: undefined })+ })+ };+ const fetch = vi.fn(async () => ({ ok: true, body }));+ vi.stubGlobal('fetch', fetch);+ return fetch;+ };++ const runReady = (overrides = {}) => ({+ id: 'ollama',+ name: 'Ollama',+ endpoint: 'http://localhost:11434/v1',+ defaultModel: 'llama3',+ ...overrides+ });++ it('sends num_ctx in the request body when the provider opts in', 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('run-numctx', runReady({ numCtx: 32768 }), null, 'hi', process.cwd(), [], undefined, () => done());+ await completed;++ expect(fetch).toHaveBeenCalledTimes(1);+ expect(JSON.parse(fetch.mock.calls[0][1].body).num_ctx).toBe(32768);+ });++ it('omits num_ctx when the provider does not set it', 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('run-no-numctx', runReady(), null, 'hi', process.cwd(), [], undefined, () => done());+ await completed;++ expect(fetch).toHaveBeenCalledTimes(1);+ expect('num_ctx' in JSON.parse(fetch.mock.calls[0][1].body)).toBe(false);+ });});diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex dea488b8a2..22273f99ef 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -25,6 +25,9 @@ export const providerSchema = z.object({// Model to run on the fallback provider. The UI sends '' when no model is// pinned (fall back to the fallback provider's own default), so allow empty.fallbackModel: z.string().nullable().optional(),+ // Per-request context window (Ollama num_ctx). Lifts the ~4K default so long+ // prompts (e.g. a whole manuscript) aren't silently truncated. Null = unset.+ numCtx: z.number().int().min(512).max(1048576).nullable().optional(),timeout: z.number().int().min(1000).max(1800000).optional(),enabled: z.boolean().optional(),envVars: z.record(z.string()).optional(),diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 863c10e7fe..376f90a412 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -165,15 +165,27 @@ export async function ensureBackendProvider(backend) {const id = PROVIDER_ID[backend]if (!id) returnconst provider = await getProviderById(id).catch(() => null)- if (provider && !provider.enabled) {- const enabled = await updateProvider(id, { enabled: true })- .then(() => true)- .catch((err) => {- console.error(`⚠️ Failed to enable ${id} provider: ${err.message}`)- return false- })- if (enabled) console.log(`🔌 Enabled ${id} provider for active local LLM backend`)- }+ if (!provider) return++ const patch = {}+ if (!provider.enabled) patch.enabled = true+ // Ollama's OpenAI-compatible endpoint silently truncates to a ~4K context+ // window unless a per-request num_ctx is sent. Editorial passes feed the+ // whole manuscript (tens of thousands of tokens), so default a generous+ // window (override with OLLAMA_NUM_CTX). LM Studio sets context at model+ // load, so this only applies to Ollama.+ if (backend === 'ollama' && !(Number(provider.numCtx) > 0)) {+ patch.numCtx = Number(process.env.OLLAMA_NUM_CTX) || 32768+ }+ if (Object.keys(patch).length === 0) return++ const ok = await updateProvider(id, patch)+ .then(() => true)+ .catch((err) => {+ console.error(`⚠️ Failed to configure ${id} provider: ${err.message}`)+ return false+ })+ if (ok) console.log(`🔌 Configured ${id} provider for local LLM backend (${Object.keys(patch).join(', ')})`)}// ---- backend capability probes ----------------------------------------------diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex aa57a9277e..8180a5d9ca 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -100,11 +100,21 @@ describe('localLlm', () => {});describe('ensureBackendProvider', () => {- it('does not re-enable an already-enabled provider', async () => {- mocks.providers.getProviderById.mockResolvedValueOnce({ id: 'ollama', enabled: true });+ it('does not touch a provider already enabled with a context window set', async () => {+ mocks.providers.getProviderById.mockResolvedValueOnce({ id: 'ollama', enabled: true, numCtx: 32768 });await svc.ensureBackendProvider('ollama');expect(mocks.providers.updateProvider).not.toHaveBeenCalled();});+ it('defaults a context window on an enabled Ollama provider that lacks one', async () => {+ mocks.providers.getProviderById.mockResolvedValueOnce({ id: 'ollama', enabled: true });+ await svc.ensureBackendProvider('ollama');+ expect(mocks.providers.updateProvider).toHaveBeenCalledWith('ollama', { numCtx: 32768 });+ });+ it('enables and sets a context window for a disabled Ollama provider', async () => {+ mocks.providers.getProviderById.mockResolvedValueOnce({ id: 'ollama', enabled: false });+ await svc.ensureBackendProvider('ollama');+ expect(mocks.providers.updateProvider).toHaveBeenCalledWith('ollama', { enabled: true, numCtx: 32768 });+ });});describe('installModel / deleteModel dispatch', () => {