The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): a full context compacts in the model's own tokens, and never ends in silence (CA)
purplec482912594dc
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 2543ade7..e86bf489 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -140,6 +140,8 @@ import { buildLoopRecheck, loopPassSaysDone } from '../lib/agent-commands'import { applyStoredCompaction } from '../lib/compact-summary'import { maybeAutoCompact } from '../lib/run-compact-command'import { autoCompactOn } from '../lib/compact-trigger'+import { ContextFullError, fitToWindow } from '../lib/fit-to-window'+import { TokenCalibration } from '../lib/token-calibration'import { compactRunMidway, newRunCompactState, runCompactionDue, MEMORY_FLUSH_NOTE } from '../lib/run-compact-midway'import { generateEmbeddings } from '../api/rag'import { truncateToolResult } from '../lib/truncate-tool-result'@@ -1699,6 +1701,9 @@ export function useAgentChat() {const executedCallKeys = new Set<string>()/** Size of the tool catalogue the step before sent. Zero before the first step. */let catalogTokens = 0+ // The run's estimate held against the model's own count (lib/token-calibration.ts).+ const calib = new TokenCalibration()+ let stepEstimate = 0// Canonical arguments (lib/agent-core/repeat-note.ts): a re-ordered or// re-spaced copy of a call is the same call.const callKey = (tc: { function: { name: string; arguments: unknown } }) =>@@ -1936,7 +1941,9 @@ export function useAgentChat() {const personaNote = samplingConv? personaNoteOf(speakerPersonaFor(samplingConv, activeModel, allPersonas, pickedPersonaId, settings.personasEnabled !== false)): null- const besideCatalog = budgetBesideTheCatalog(sendWindow, catalogTokens)+ // In the model's own tokens: the estimate reads low on code and logs,+ // and a budget it measures has to be read that much smaller.+ const besideCatalog = budgetBesideTheCatalog(calib.budget(sendWindow), catalogTokens)const sendBudget = personaNote ? Math.max(1, besideCatalog - noteTokens(personaNote)) : besideCataloglet sendMessages: ChatMessage[] = agentMessages.slice()let trimmedReadKeys: ReadonlySet<string> = NO_TRIMMED_KEYS@@ -1985,6 +1992,14 @@ export function useAgentChat() {keepWhole: neededAgain,})sendMessages = built.messages+ // The last check (lib/fit-to-window.ts): against the model's own+ // window, never past it. Ollama would cut the start silently.+ {+ const fit = fitToWindow(sendMessages, calib.budget(agentCtx), catalogTokens)+ if (!fit.fits) throw new ContextFullError(fit.tokens, agentCtx)+ sendMessages = fit.messages+ stepEstimate = fit.tokens+ }trimmedReadKeys = new Set(built.trimmedKeys)if (convId) {useSendSizeStore.getState().report(convId, {@@ -2387,6 +2402,7 @@ export function useAgentChat() {})}requestUsage.add(turn)+ calib.observe(stepEstimate, turn.promptEvalCount)costBrake.record(turn.promptEvalCount, { output: turn.evalCount, billing: billingOf(turn) })// Native thinking field (Ollama; LU Cloud reasoning_content)if (turn.thinking) turnThinking = turn.thinking@@ -2481,6 +2497,7 @@ export function useAgentChat() {// abschneiden, und dann steht hier ebenfalls kein Werkzeugaufruf.turnFinishReason = hermesTurn.finishReasonrequestUsage.add(hermesTurn)+ calib.observe(stepEstimate, hermesTurn.promptEvalCount)costBrake.record(hermesTurn.promptEvalCount, { output: hermesTurn.evalCount, billing: billingOf(hermesTurn) })notePhoneCount(hermesTurn.promptEvalCount)if (hermesTurn.thinking) {diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex e1bc8f67..43a62b73 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -67,6 +67,7 @@ import { fileMessageFields, filesWithoutWorkspace, type ChatFileInput } from "..import { fitFilesForSend, requestTextOf } from "./chat-file-room"import { isGroupChat, availableGroupMembers, groupSystemPrompt, groupHistory, groupSpeakers, stripImpersonatedSpeakers, hasGroupHistory, soloSpeakers, soloTurnAuthorFields, soloHistoryTag, SOLO_HISTORY_LINE } from "../lib/group-chat"import { explainSendRefusal } from "../lib/template-refusal"+import { ContextFullError, fitToWindow } from "../lib/fit-to-window"import { laterAnswersInRound, nextRoundSpeakers, regenerateSpeakers, copiesForNewVersion } from "../lib/group-rounds"import { groupTurnStarted, groupRoundEnded } from "../stores/groupRoundStore"import { forkStart } from "../lib/chat-forks"@@ -1656,7 +1657,12 @@ export function useChat() {}const continued = continueInPlace ? wireForContinue(budgeted, opts?.continueFrom ?? '') : nullif (continued) markContinuation(convId, assistantMessage.id)- const messages = continued ?? budgeted+ // The last check (lib/fit-to-window.ts): against the model's own window,+ // never past it. Ollama would cut the start of the chat silently. The+ // verdict is acted on inside the try below, so the turn ends with the+ // sentence that says why (explainSendRefusal), never with nothing.+ const fitted = fitToWindow(continued ?? budgeted, modelWindowTokens)+ const messages = fitted.messages// Lane admission (Runde 4, review-lanes.md Blocker 1+6): the built-in// engine runs llama-server with n_parallel=1, so two local sends racing@@ -1706,6 +1712,7 @@ export function useChat() {const frames = frameFlush()try {+ if (!fitted.fits) throw new ContextFullError(fitted.tokens, modelWindowTokens)// ── Multi-Provider: resolve provider for active model ──const { provider, modelId } = getProviderForModel(activeModel)diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 6fd833b1..2bc0b806 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -9,6 +9,8 @@ import { useCodexStore } from '../stores/codexStore'import { useModelStore } from '../stores/modelStore'import { runCompactForConversation, compactOutcomeMessage, maybeAutoCompact } from '../lib/run-compact-command'import { autoCompactOn } from '../lib/compact-trigger'+import { ContextFullError, fitToWindow } from '../lib/fit-to-window'+import { TokenCalibration } from '../lib/token-calibration'import { compactRunMidway, newRunCompactState } from '../lib/run-compact-midway'import { applyStoredCompaction } from '../lib/compact-summary'import { useSettingsStore } from '../stores/settingsStore'@@ -1263,6 +1265,10 @@ export function useCodex() {// Keyed on the raw id, like the Agent tab: an Ollama agent variant// (`<model>-agent`) has no picker row and no context entry of its own.+ // The catalogue size of the step before, for the fit check (fit-to-window).+ let lastToolsEstimate = 0+ // The run's estimate held against the model's own count (lib/token-calibration.ts).+ const calib = new TokenCalibration()const numCtx: number = await resolveAgentNumCtx(modelId, providerId, settings.contextWindowOverride, activeModel,)@@ -1441,14 +1447,16 @@ export function useCodex() {// fear is largely a myth). effectiveSendWindow carries that profile,// and on a paid provider it also carries the send cap.const decayOn = settings.contextDecay !== false- const sendWindow = capToLearnedWindow(effectiveSendWindow({+ // In the model's own tokens (lib/token-calibration.ts): the estimate+ // reads low on code and logs, so the budget it measures is read smaller.+ const sendWindow = calib.budget(capToLearnedWindow(effectiveSendWindow({providerId,modelWindow: numCtx,sendWindowTokens: sendWindowFor(settings, activeModel),capEnabled: decayOn,smallModelMode: settings.smallModelMode,localBackend: sendsToALanBackend(providerId, activeModel),- }), modelToUse, numCtx)+ }), modelToUse, numCtx))// What this step sends, estimated: the history, and the catalogue that// rides beside it on the native transport. Read when the server// refuses the step as too large (GH #140).@@ -1540,6 +1548,16 @@ export function useCodex() {// Building is best-effort; fall through with the raw history.sendMessages = messages.slice()}+ // The last check (lib/fit-to-window.ts), outside the best-effort catch+ // above: against the model's own window, never past it. Ollama would+ // cut the start silently; the outer catch says why nothing was sent.+ {+ // The catalogue is chosen further down; the last step's size stands in.+ const fit = fitToWindow(sendMessages, calib.budget(numCtx), lastToolsEstimate)+ if (!fit.fits) throw new ContextFullError(fit.tokens, numCtx)+ sendMessages = fit.messages+ if (fit.shortened) stepPromptEstimate = Math.max(0, fit.tokens - lastToolsEstimate)+ }// Live paint for EVERY transport branch below (Ollama, openai-compat// stream, Hermes). Takes the cumulative content of the current model@@ -1682,6 +1700,7 @@ export function useCodex() {// built. Without this the meter showed the messages alone: 732 tokens// on the first coding step against 2.400 on the wire.stepToolsEstimate = estimateTokens(JSON.stringify(tools))+ lastToolsEstimate = stepToolsEstimateif (convId) {useSendSizeStore.getState().reportTools(convId, stepToolsEstimate)// CA U5: what this step sent, by kind, for the context breakdown.@@ -1782,6 +1801,7 @@ export function useCodex() {turnFinishReason = turn.doneReasonreportTurnUsage(convId!, assistantMsg.id, turn)requestUsage.add(turn)+ calib.observe(stepPromptEstimate + stepToolsEstimate, turn.promptEvalCount)costBrake.record(turn.promptEvalCount, { output: turn.evalCount, billing: billingOf(turn) })diagLog('streamWithTools-return', {iter: i,@@ -1841,6 +1861,7 @@ export function useCodex() {turnFinishReason = turn.finishReasonreportTurnUsage(convId!, assistantMsg.id, turn)requestUsage.add(turn)+ calib.observe(stepPromptEstimate + stepToolsEstimate, turn.promptEvalCount)costBrake.record(turn.promptEvalCount, { output: turn.evalCount, billing: billingOf(turn) })// GH #147: a model on LU Cloud wrote its calls into the text// (!function_call:{"call": "file_read", ...}). This path never@@ -1981,6 +2002,7 @@ export function useCodex() {// Gleiche Stelle wie in useAgentChat.turnFinishReason = hermesTurn.finishReasonrequestUsage.add(hermesTurn)+ calib.observe(stepPromptEstimate + stepToolsEstimate, hermesTurn.promptEvalCount)costBrake.record(hermesTurn.promptEvalCount, { output: hermesTurn.evalCount, billing: billingOf(hermesTurn) })if (keepThinking && hermesTurn.thinking) {thinkingContent += (thinkingContent ? '\n\n' : '') + hermesTurn.thinkingdiff --git a/src/lib/__tests__/a-full-context-never-ends-silently.test.ts b/src/lib/__tests__/a-full-context-never-ends-silently.test.tsnew file mode 100644index 00000000..5272e56a--- /dev/null+++ b/src/lib/__tests__/a-full-context-never-ends-silently.test.ts@@ -0,0 +1,138 @@+/**+ * CA, 14.11.2026. David, on a local 27B in Agent mode: the context filled to+ * the brim, the request never finished, no answer came, and auto-compact did+ * not fire. "Der sollte natuerlich autokompaktieren." Three causes, pinned:+ * 1. the default ran only from a 32K model window; every Ollama chat has 16K;+ * 2. under 8 messages nothing was ever summarised, however full;+ * 3. nothing checked that the request fits before it left; Ollama cuts the+ * start silently.+ * A full context now compacts, else shortens the longest older turns, else+ * ends the turn with the sentence that says why. Never silence.+ */+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { answerRoom, ContextFullError, fitToWindow, isContextFull } from '../fit-to-window'+import { resolveCompactThreshold, shouldAutoCompact } from '../compact-trigger'+import { DEFAULT_CONTEXT_CAP } from '../context-window'+import { CONTEXT_OVERFLOW_REFUSAL_SENTENCE, explainSendRefusal } from '../template-refusal'+import { estimateMessageTokens } from '../context-compaction'++const words = (n: number) => Array.from({ length: n }, (_, i) => `word${i % 97}`).join(' ')+const tokens = (ms: Array<{ role: string; content: string }>) => estimateMessageTokens(ms as never)++describe('auto-compact on an Ollama chat', () => {+ it('the 16K window every Ollama chat gets compacts by default', () => {+ expect(DEFAULT_CONTEXT_CAP).toBe(16384)+ expect(resolveCompactThreshold({ autoCompact: true, autoCompactThreshold: 0 }, DEFAULT_CONTEXT_CAP)).not.toBeNull()+ })++ it('three huge turns over the threshold are summarised, not left alone', () => {+ const v = shouldAutoCompact({ used: 15_000, window: 16_384, source: 'built', real: true, windowIsTrue: true, messageCount: 3, threshold: 0.74 })+ expect(v.shouldCompact).toBe(true)+ })+})++describe('fitToWindow, the last check', () => {+ const sys = { role: 'system', content: 'You are LU.' }++ it('a request that fits leaves untouched', () => {+ const ms = [sys, { role: 'user', content: 'hi' }]+ const r = fitToWindow(ms, 16_384)+ expect(r.fits).toBe(true)+ expect(r.messages).toBe(ms)+ expect(r.shortened).toBe(0)+ })++ it('a long older turn is shortened for the request, head and tail kept, the question whole', () => {+ const pasted = 'START ' + words(30_000) + ' END'+ const ms = [sys, { role: 'user', content: pasted }, { role: 'assistant', content: 'ok' }, { role: 'user', content: 'Summarise it.' }]+ const r = fitToWindow(ms, 16_384)+ expect(r.fits).toBe(true)+ expect(r.shortened).toBe(1)+ expect(tokens(r.messages)).toBeLessThanOrEqual(16_384 - answerRoom(16_384))+ expect(r.messages[1].content.startsWith('START')).toBe(true)+ expect(r.messages[1].content.endsWith('END')).toBe(true)+ expect(r.messages[3].content).toBe('Summarise it.')+ // Only the request copy: the input array is not changed.+ expect(ms[1].content).toBe(pasted)+ })++ it('the tool catalogue counts', () => {+ const ms = [sys, { role: 'user', content: words(3_000) }, { role: 'user', content: 'go' }]+ expect(fitToWindow(ms, 16_384).shortened).toBe(0)+ expect(fitToWindow(ms, 16_384, 9_000).shortened).toBe(1)+ })++ it('when even the question alone is too big, it does not fit and says so', () => {+ const ms = [sys, { role: 'user', content: words(40_000) }]+ const r = fitToWindow(ms, 16_384)+ expect(r.fits).toBe(false)+ const err = new ContextFullError(r.tokens, 16_384)+ expect(isContextFull(err)).toBe(true)+ expect(explainSendRefusal(err)).toBe(CONTEXT_OVERFLOW_REFUSAL_SENTENCE)+ })++ it('an unknown window checks nothing', () => {+ const ms = [sys, { role: 'user', content: words(40_000) }]+ expect(fitToWindow(ms, 0).fits).toBe(true)+ })+})++describe('every path runs it before the request leaves', () => {+ it('plain chat, inside the try whose catch explains it', () => {+ const src = readFileSync('src/hooks/useChat.ts', 'utf8')+ expect(src).toMatch(/const fitted = fitToWindow\(continued \?\? budgeted, modelWindowTokens\)/)+ expect(src).toMatch(/try \{\n\s*if \(!fitted\.fits\) throw new ContextFullError/)+ })++ it('the Agent tab, against the model window, after the build', () => {+ const src = readFileSync('src/hooks/useAgentChat.ts', 'utf8')+ const build = src.indexOf('sendMessages = built.messages')+ const fit = src.indexOf('fitToWindow(sendMessages, calib.budget(agentCtx), catalogTokens)')+ expect(build).toBeGreaterThan(0)+ expect(fit).toBeGreaterThan(build)+ expect(src).toMatch(/if \(!fit\.fits\) throw new ContextFullError\(fit\.tokens, agentCtx\)/)+ })++ it('the Code tab, outside the best-effort catch', () => {+ const src = readFileSync('src/hooks/useCodex.ts', 'utf8')+ const bestEffort = src.indexOf('// Building is best-effort; fall through with the raw history.')+ const fit = src.indexOf('fitToWindow(sendMessages, calib.budget(numCtx), lastToolsEstimate)')+ expect(fit).toBeGreaterThan(bestEffort)+ expect(src).toMatch(/if \(!fit\.fits\) throw new ContextFullError\(fit\.tokens, numCtx\)/)+ })+})++describe("David's numbers: about 31K of a 32K window in Agent mode, no compaction", () => {+ // The loop built against 80 % of the window (26214) by its own estimate. The+ // model counted about a fifth more: 31K. Nothing in the loop saw a reason to+ // compact, and about 1K was left for the answer of a thinking model.+ it('after one step the loop measures in the model\'s own tokens', async () => {+ const { TokenCalibration, MAX_CALIBRATION } = await import('../token-calibration')+ const c = new TokenCalibration()+ expect(c.budget(26_214)).toBe(26_214)+ c.observe(26_000, 31_200)+ expect(c.factor).toBeCloseTo(1.2, 2)+ // The same 26214 budget now holds what the model counts as 26214.+ expect(c.budget(26_214) * c.factor).toBeLessThanOrEqual(26_214)+ expect(c.budget(26_214)).toBeLessThan(22_000)+ // Only upward, at most double, and a missing count changes nothing.+ c.observe(26_000, 20_000)+ expect(c.factor).toBe(1)+ c.observe(1_000, 50_000)+ expect(c.factor).toBe(MAX_CALIBRATION)+ c.observe(1_000, undefined)+ expect(c.factor).toBe(MAX_CALIBRATION)+ })++ it('both tool loops feed it from every step and read every budget through it', () => {+ const agent = readFileSync('src/hooks/useAgentChat.ts', 'utf8')+ expect(agent).toMatch(/budgetBesideTheCatalog\(calib\.budget\(sendWindow\), catalogTokens\)/)+ expect(agent).toMatch(/fitToWindow\(sendMessages, calib\.budget\(agentCtx\), catalogTokens\)/)+ expect(agent.match(/calib\.observe\(stepEstimate, (turn|hermesTurn)\.promptEvalCount\)/g)?.length).toBe(2)+ const code = readFileSync('src/hooks/useCodex.ts', 'utf8')+ expect(code).toMatch(/const sendWindow = calib\.budget\(capToLearnedWindow\(/)+ expect(code).toMatch(/fitToWindow\(sendMessages, calib\.budget\(numCtx\), lastToolsEstimate\)/)+ expect(code.match(/calib\.observe\(stepPromptEstimate \+ stepToolsEstimate, (turn|hermesTurn)\.promptEvalCount\)/g)?.length).toBe(3)+ })+})diff --git a/src/lib/__tests__/auto-compact-vor-dem-kuerzen.test.ts b/src/lib/__tests__/auto-compact-vor-dem-kuerzen.test.tsindex 285c3762..6a2266f7 100644--- a/src/lib/__tests__/auto-compact-vor-dem-kuerzen.test.ts+++ b/src/lib/__tests__/auto-compact-vor-dem-kuerzen.test.ts@@ -14,7 +14,7 @@import { describe, it, expect } from 'vitest'import { readFileSync } from 'node:fs'import { resolve } from 'node:path'-import { shouldAutoCompact, resolveCompactThreshold, MIN_MESSAGES_TO_COMPACT } from '../compact-trigger'+import { shouldAutoCompact, resolveCompactThreshold } from '../compact-trigger'import { sendBudgetWouldTrim, applyChatSendBudget } from '../chat-send-budget'import { cheapWords } from './token-estimate-samples'@@ -65,7 +65,9 @@ describe('the trim no longer runs instead of the summary', () => {it('NEGATIVE CONTROL: off, too short and cooldown still say no', () => {expect(shouldAutoCompact({ ...base, threshold: undefined, trimImminent: true }).reason).toBe('off')- expect(shouldAutoCompact({ ...base, messageCount: MIN_MESSAGES_TO_COMPACT - 1, trimImminent: true }).reason).toBe('too-short')+ // Below three there is nothing older to summarise. From three on a full+ // chat may compact (CA, 14.11.2026, a-full-context-never-ends-silently).+ expect(shouldAutoCompact({ ...base, messageCount: 2, trimImminent: true }).reason).toBe('too-short')expect(shouldAutoCompact({ ...base, lastCompactAtMessageCount: base.messageCount - 1, trimImminent: true }).reason).toBe('cooldown')expect(shouldAutoCompact({ ...base, window: 0, trimImminent: true }).reason).toBe('no-window')})diff --git a/src/lib/__tests__/compact-fits-the-window.test.ts b/src/lib/__tests__/compact-fits-the-window.test.tsindex 2663b321..7bcfde2f 100644--- a/src/lib/__tests__/compact-fits-the-window.test.ts+++ b/src/lib/__tests__/compact-fits-the-window.test.ts@@ -67,14 +67,16 @@ describe('the threshold follows the window', () => {expect(compactThresholdCeiling(8192)).toBeLessThan(0.95)})- it('the default runs from a 32K model window up, never below', () => {+ it('the default runs from a 16K model window up, never at 8K', () => {// Owner decision 18.10.2026: "bei 8k nie, bei 32k immer und alles darueber auch immer an".+ // 16K since 14.11.2026: it is every Ollama chat's window, and David's local+ // chat filled up with no summary ("der sollte natuerlich autokompaktieren").const standard = { autoCompact: true, autoCompactThreshold: 0 }- expect(MIN_AUTO_COMPACT_WINDOW).toBe(32768)+ expect(MIN_AUTO_COMPACT_WINDOW).toBe(16384)expect(resolveCompactThreshold(standard, 4096)).toBeNull()expect(resolveCompactThreshold(standard, 8192)).toBeNull()- expect(resolveCompactThreshold(standard, 16384)).toBeNull()- expect(resolveCompactThreshold(standard, 32767)).toBeNull()+ expect(resolveCompactThreshold(standard, 16383)).toBeNull()+ expect(resolveCompactThreshold(standard, 16384)).toBe(0.74)expect(resolveCompactThreshold(standard, 32768)).toBe(0.81)expect(resolveCompactThreshold(standard, 131072)).toBe(0.85)expect(resolveCompactThreshold(standard, 1_048_576)).toBe(0.85)@@ -86,6 +88,8 @@ describe('the threshold follows the window', () => {expect(resolveCompactThreshold(standard, 26214, 32768)).toBe(adaptiveCompactThreshold(26214))// A large send window on an 8K model does not count.expect(resolveCompactThreshold(standard, 32768, 8192)).toBeNull()+ // The Ollama chat window (DEFAULT_CONTEXT_CAP) compacts by default.+ expect(resolveCompactThreshold(standard, 16384, 16384)).toBe(0.74)})it('off is only an explicit false', () => {diff --git a/src/lib/__tests__/compact-trigger.test.ts b/src/lib/__tests__/compact-trigger.test.tsindex 8775b332..c3ba13d6 100644--- a/src/lib/__tests__/compact-trigger.test.ts+++ b/src/lib/__tests__/compact-trigger.test.ts@@ -22,6 +22,7 @@ import {MIN_THRESHOLD,MAX_THRESHOLD,MIN_MESSAGES_TO_COMPACT,+ MIN_MESSAGES_WHEN_FULL,MIN_MESSAGES_SINCE_COMPACT,type CompactTriggerInput,} from '../compact-trigger'@@ -78,11 +79,20 @@ describe('der Nenner muss aufgelöst sein', () => {})describe('zu kurz zum Zusammenfassen', () => {- it('feuert unterhalb der Mindestlänge nicht', () => {- const r = shouldAutoCompact({ ...feuernd, messageCount: MIN_MESSAGES_TO_COMPACT - 1 })+ it('feuert unterhalb der Mindestlänge nicht, solange das Fenster nicht voll ist', () => {+ const r = shouldAutoCompact({ ...feuernd, used: 0.2 * feuernd.window, messageCount: MIN_MESSAGES_TO_COMPACT - 1 })expect(r.reason).toBe('too-short')})+ it('ein voller Chat aus wenigen, grossen Nachrichten wird doch zusammengefasst (CA, 14.11.2026)', () => {+ // Drei Runden mit eingefuegten Dokumenten fuellten das Fenster, und nichts+ // durfte es verkleinern: keine Zusammenfassung, keine Antwort.+ expect(shouldAutoCompact({ ...feuernd, messageCount: MIN_MESSAGES_WHEN_FULL }).shouldCompact).toBe(true)+ expect(shouldAutoCompact({ ...feuernd, messageCount: MIN_MESSAGES_TO_COMPACT - 1 }).shouldCompact).toBe(true)+ // Zwei sind zu wenig: es gaebe nichts Aelteres zusammenzufassen.+ expect(shouldAutoCompact({ ...feuernd, messageCount: MIN_MESSAGES_WHEN_FULL - 1 }).reason).toBe('too-short')+ })+it('feuert genau ab der Mindestlänge', () => {expect(shouldAutoCompact({ ...feuernd, messageCount: MIN_MESSAGES_TO_COMPACT }).shouldCompact,diff --git a/src/lib/__tests__/run-compact-midway.test.ts b/src/lib/__tests__/run-compact-midway.test.tsindex f81e240f..95aac0ab 100644--- a/src/lib/__tests__/run-compact-midway.test.ts+++ b/src/lib/__tests__/run-compact-midway.test.ts@@ -271,14 +271,15 @@ describe('compactRunMidway', () => {expect(notices(convId).filter((n) => n.notice === 'warn')).toHaveLength(1)})- it('by default never runs below a 32K model window, and always from 32K up', async () => {+ it('by default never runs at 8K, and always from 16K up', async () => {// Owner decision 18.10.2026: "bei 8k nie, bei 32k immer und alles darueber".- for (const modelWindow of [8192, 16384]) {+ // 16K since 14.11.2026: every Ollama chat window (compact-trigger.ts).+ for (const modelWindow of [8192, 12288]) {const out = await compactRunMidway({ messages: run(30), budgetTokens: modelWindow, modelWindow, activeModel: 'ollama::qwen3:8b', state: newRunCompactState() })expect(out.reason, `${modelWindow}`).toBe('off')}expect(summarise).not.toHaveBeenCalled()- for (const modelWindow of [32768, 131072]) {+ for (const modelWindow of [16384, 32768, 131072]) {const out = await compactRunMidway({ messages: run(30), budgetTokens: 16384, modelWindow, activeModel: 'ollama::qwen3:8b', state: newRunCompactState() })expect(out.compacted, `${modelWindow}`).toBe(true)}diff --git a/src/lib/compact-trigger.ts b/src/lib/compact-trigger.tsindex 81a48a97..952c84be 100644--- a/src/lib/compact-trigger.ts+++ b/src/lib/compact-trigger.ts@@ -101,6 +101,9 @@ export const MAX_THRESHOLD = 0.95*/export const MIN_MESSAGES_TO_COMPACT = 8+/** Over the threshold, this many are enough (see shouldAutoCompact). */+export const MIN_MESSAGES_WHEN_FULL = 3+/*** Messages that must arrive after a compaction before another one may fire.*@@ -254,8 +257,15 @@ export function compactThresholdCeiling(window: number): number {* itself next to the answer, and the mechanical trim does the work alone. It* is the MODEL window, not the send window: a 32K model whose steps send a* share of it is still a 32K model.+ *+ * 16K since 14.11.2026 (CA). The 18.10. decision left 16K open, and 16K is+ * exactly what LU gives every Ollama chat (DEFAULT_CONTEXT_CAP) and every+ * Ollama agent run on a model that reports no maximum: auto-compact was off+ * for all of them. David saw a local 27B chat fill to the brim with no+ * summary and no answer: "der sollte natuerlich autokompaktieren". At 16K the+ * fitted threshold is 0.74, room enough for the summary call; 8K stays never.*/-export const MIN_AUTO_COMPACT_WINDOW = 32768+export const MIN_AUTO_COMPACT_WINDOW = 16384/*** The threshold auto-compact runs at, from the two settings and the window.@@ -310,7 +320,15 @@ export function shouldAutoCompact(input: CompactTriggerInput): CompactTriggerRes// error, it is a different question. useActiveContextWindow reports 0 until// the provider answers, and every consumer already handles that state.if (input.window <= 0) return no('no-window')- if (input.messageCount < MIN_MESSAGES_TO_COMPACT) return no('too-short')+ // Few messages are rarely worth a summary, unless they are what fills the+ // window: three turns with a pasted document or a long answer each left the+ // chat over the brim with nothing allowed to shrink it (CA, 14.11.2026; the+ // mechanical trim keeps the newest four whole). Over the threshold, three+ // messages are enough: the summary replaces the older two.+ const overNow = ratio >= effectiveThreshold || input.trimImminent === true+ if (input.messageCount < MIN_MESSAGES_TO_COMPACT && !(overNow && input.messageCount >= MIN_MESSAGES_WHEN_FULL)) {+ return no('too-short')+ }if (input.lastCompactAtMessageCount !== undefined &&input.messageCount - input.lastCompactAtMessageCount < MIN_MESSAGES_SINCE_COMPACTdiff --git a/src/lib/fit-to-window.ts b/src/lib/fit-to-window.tsnew file mode 100644index 00000000..6886ee17--- /dev/null+++ b/src/lib/fit-to-window.ts@@ -0,0 +1,73 @@+/**+ * The last check before a request leaves: does it fit the window at all?+ * (CA, 14.11.2026.)+ *+ * Compaction and the mechanical trim run before this, in every path. Neither+ * promised the result fits: compaction keeps the newest turns whole and needs+ * enough of them to summarise, the trim always keeps the newest four. A chat of+ * a few very long turns stayed over the window, and nothing checked. On LU's+ * own engine that is a 400 the paths explain; on Ollama it is silent: Ollama+ * cuts the start of the prompt and the model answers a conversation it never+ * saw whole, or, as David saw with a local 27B in Agent mode, not at all.+ *+ * So: measured once more on what is actually sent. Too big, and the longest+ * older turns are shortened (head and tail kept, shortenLongTurns, the request+ * copy only; the chat keeps every word). Still too big, and nothing is sent:+ * the turn ends with the honest sentence instead of a silent cut or a hang.+ */+import { estimateMessageTokens, shortenLongTurns } from './context-compaction'+import { CONTEXT_OVERFLOW_REFUSAL_SENTENCE } from './template-refusal'+import type { OllamaChatMessage } from '../types/agent-mode'++/** Room the answer needs beside the prompt, as in compact-trigger. */+const ANSWER_ROOM_SHARE = 0.12+const ANSWER_ROOM_MIN_TOKENS = 1024++export function answerRoom(window: number): number {+ return Math.min(Math.floor(window / 2), Math.max(ANSWER_ROOM_MIN_TOKENS, Math.floor(window * ANSWER_ROOM_SHARE)))+}++export interface FitResult<T> {+ messages: T[]+ /** Turns shortened for this request. */+ shortened: number+ /** Estimated prompt tokens after shortening (tools included). */+ tokens: number+ fits: boolean+}++/**+ * Fit `messages` (plus `extraTokens`, e.g. the tool catalogue) into `window`,+ * leaving room for the answer. A window of 0 or less is unknown: nothing is+ * checked, nothing changes.+ */+export function fitToWindow<T extends { role: string; content: string }>(+ messages: T[],+ window: number,+ extraTokens = 0,+): FitResult<T> {+ const size = (ms: T[]) => estimateMessageTokens(ms as unknown as OllamaChatMessage[]) + extraTokens+ const before = size(messages)+ if (!(Number.isFinite(window) && window > 0)) return { messages, shortened: 0, tokens: before, fits: true }+ const budget = window - answerRoom(window)+ if (before <= budget) return { messages, shortened: 0, tokens: before, fits: true }+ const cut = shortenLongTurns(messages, Math.max(0, budget - extraTokens))+ const after = size(cut.messages)+ return { messages: cut.messages, shortened: cut.shortened, tokens: after, fits: after <= window - Math.min(512, answerRoom(window)) }+}++/** Thrown by a send path when even the shortened request does not fit. */+export class ContextFullError extends Error {+ readonly tokens: number+ readonly window: number+ constructor(tokens: number, window: number) {+ super(CONTEXT_OVERFLOW_REFUSAL_SENTENCE)+ this.name = 'ContextFullError'+ this.tokens = tokens+ this.window = window+ }+}++export function isContextFull(err: unknown): err is ContextFullError {+ return err instanceof Error && err.name === 'ContextFullError'+}diff --git a/src/lib/template-refusal.ts b/src/lib/template-refusal.tsindex 34778cd2..134ef6ba 100644--- a/src/lib/template-refusal.ts+++ b/src/lib/template-refusal.ts@@ -74,6 +74,9 @@ export const TEMPERATURE_REFUSAL_SENTENCE =* message; the raw text is kept underneath it, because support reads it.*/export function explainSendRefusal(err: unknown): string | null {+ // fit-to-window.ts: the request was measured too big and never sent (CA,+ // 14.11.2026). Same sentence as the engine's own refusal, no detail to add.+ if (err instanceof Error && err.name === 'ContextFullError') return CONTEXT_OVERFLOW_REFUSAL_SENTENCEif (isTemplateRefusal(err)) return withDetail(TEMPLATE_REFUSAL_SENTENCE, err)if (httpStatusOf(err) === 400 && TEMPERATURE_MARKERS.test(detailOf(err))) return withDetail(TEMPERATURE_REFUSAL_SENTENCE, err)if (httpStatusOf(err) === 400 && isContextOverflow(detailOf(err))) return withDetail(CONTEXT_OVERFLOW_REFUSAL_SENTENCE, err)diff --git a/src/lib/token-calibration.ts b/src/lib/token-calibration.tsnew file mode 100644index 00000000..ffd8c455--- /dev/null+++ b/src/lib/token-calibration.ts@@ -0,0 +1,40 @@+/**+ * The run's own count, held against the model's (CA, 14.11.2026).+ *+ * The agent loops size every step with an estimate (characters per token,+ * lib/token-estimate.ts). The context meter shows what the model reported,+ * when it reports. On code, logs and JSON the estimate reads low; a local+ * tokenizer can count a fifth more. David saw a local 27B in Agent mode at+ * about 31K of a 32K window with no compaction and no answer: the loop had+ * built against 80 % of the window by its own count (about 26K), so it never+ * saw a reason to compact, and the model, given about 1K for its answer, spent+ * that thinking.+ *+ * So after every step the loop holds the estimate it sent against the real+ * prompt count the backend reported, and divides its budgets by the ratio for+ * the steps after: the trigger, the trim and the last check then measure in the+ * model's own tokens. Only upward (an estimate that reads high is safe), and at+ * most double (a count from a backend that reports something else entirely+ * must not starve the run).+ */+export const MAX_CALIBRATION = 2++export class TokenCalibration {+ private ratio = 1++ /** One step: what the loop estimated it sent, and what the backend counted. */+ observe(estimated: number, real: number | undefined | null): void {+ if (!(typeof real === 'number' && real > 0 && estimated > 0)) return+ this.ratio = Math.min(MAX_CALIBRATION, Math.max(1, real / estimated))+ }++ /** Real tokens per estimated token, 1 until a step reported. */+ get factor(): number {+ return this.ratio+ }++ /** A budget in real tokens, as the estimate has to read it. */+ budget(tokens: number): number {+ return tokens > 0 ? Math.max(1, Math.floor(tokens / this.ratio)) : tokens+ }+}