Skip to content

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.

feat(compact): Compact-Mode nach Claude-Code-Desktop-Vorbild

Claude611defca046b
diff --git a/src/components/__tests__/compact-block.test.ts b/src/components/__tests__/compact-block.test.ts
new file mode 100644
index 00000000..a6ee1022
--- /dev/null
+++ b/src/components/__tests__/compact-block.test.ts
@@ -0,0 +1,301 @@
+/**
+ * Die Verdichtungslinie — und die Regel, die sie NICHT brechen darf.
+ *
+ * Im Kopf von `CompactBlock.tsx` steht die eigentliche Entscheidung: der Block
+ * LOESCHT NICHTS und VERSTECKT NICHTS. Verdichtet wird die Nutzlast an das
+ * Modell, nicht der Verlauf des Menschen. Sichtbar wird allein die LINIE: ab
+ * hier sieht das Modell die Zusammenfassung statt der Turns darueber.
+ *
+ * Diese Regel ist genau die Art Regel, die eine spaetere Aufraeumaktion
+ * kassiert, ohne dass irgendetwas kaputtgeht: die ersetzten Turns einzuklappen
+ * oder wegzufiltern sieht aufgeraeumter aus, laesst jeden Test gruen und nimmt
+ * dem Nutzer trotzdem sein Protokoll. Deshalb steht hier nicht nur „der Block
+ * rendert", sondern eine Zaehlung der Filter, die MessageList ueberhaupt auf
+ * `conversation.messages` legt. Kommt ein dritter dazu — egal mit welchem
+ * Argument — faellt dieser Test.
+ *
+ * ── Was hier gerendert wird und was nicht ──────────────────────────────────
+ *
+ * `CompactBlock` nimmt nur eine Prop und keinen Store, also laeuft er hier
+ * ECHT durch `renderToStaticMarkup` (dieselbe Bauform wie
+ * models/__tests__/das-raster-zaehlt-seine-knoten.test.ts). Zugeklappt-als-
+ * Voreinstellung und die Zahlen im Etikett sind darum gemessenes Verhalten,
+ * kein abgelesener Quelltext.
+ *
+ * `MessageList` und `CodexView` gehen nicht, dreimal nachgemessen am
+ * 02.09.2026:
+ * 1. `useChatStore` liefert beim Server-Rendern den ANFANGSZUSTAND —
+ * zustand v5 gibt `getInitialState` als `getServerSnapshot` in
+ * `useSyncExternalStore`. Ein im Test gesetzter Chat kommt in der
+ * Komponente nie an, sie rendert `null`.
+ * 2. Am Anfangszustand vorbei gerendert faellt `MessageBubble` ueber
+ * `SpeakerButton → useVoice → window.speechSynthesis`.
+ * 3. Mit einem `window`-Stub daneben faellt framer-motion
+ * (`target.addEventListener is not a function`).
+ * Es gibt in diesem Projekt keine Render-Umgebung fuer Store-Komponenten, und
+ * ein halber DOM-Nachbau waere hier mehr Testgeruest als Test. Die beiden
+ * Verlaufsflaechen sind darum am Quelltext gesichert — dasselbe Muster wie
+ * chat/__tests__/long-transcripts-stay-cheap.test.ts und
+ * cloud/__tests__/cloud-path-shortened.test.ts.
+ *
+ * Die Datei heisst `.test.ts` und nicht `.test.tsx`: `vitest.config.ts` sammelt
+ * `src/**\/__tests__/**\/*.test.ts`. Eine `.tsx`-Datei wird nie eingesammelt
+ * („No test files found") und waere ein Waechter, der nie laeuft — deshalb
+ * `createElement` statt JSX, so wie in den anderen rendernden Tests hier.
+ *
+ * Run: npx vitest run src/components/__tests__/compact-block.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { createElement } from 'react'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { resolve } from 'node:path'
+import { quelldateien, quelltext } from './quelldateien'
+import { CompactBlock } from '../chat/CompactBlock'
+import { renderCompactSummary, EMPTY_SUMMARY } from '../../lib/compact-summary'
+import type { CompactionRecord } from '../../types/chat'
+
+const SRC = resolve(__dirname, '..', '..')
+const DATEIEN = quelldateien(resolve(SRC, 'components'), { endungen: /\.tsx$/, relativZu: SRC })
+
+const LISTE = quelltext(DATEIEN, 'components/chat/MessageList.tsx')
+const CODEX = quelltext(DATEIEN, 'components/chat/CodexView.tsx')
+
+/** Zeilen ohne die auskommentierten — die Kommentare hier sind lang und reden
+ * ueber genau die Dinge, nach denen unten gesucht wird. */
+const codeZeilen = (src: string): string[] =>
+ src.split('\n').map((z) => z.trim()).filter((z) => z && !z.startsWith('//') && !z.startsWith('*') && !z.startsWith('/*'))
+
+/** Eine Zusammenfassung, wie sie wirklich im Datensatz steht: gerendert, mit
+ * Markern und Praeambel. MARKE ist das Wort, das zugeklappt nirgends
+ * auftauchen darf. */
+const ZUSAMMENFASSUNG = renderCompactSummary({
+ ...EMPTY_SUMMARY,
+ task: 'MARKE-TASK: den Audit-Build abnehmen',
+ progress: 'MARKE-PROGRESS: zwei Dateien gelesen',
+})
+
+const datensatz = (over: Partial<CompactionRecord> = {}): CompactionRecord => ({
+ id: 'c1',
+ summary: ZUSAMMENFASSUNG,
+ upToMessageId: 'm2',
+ replaced: 7,
+ atMessageCount: 9,
+ tokensBefore: 18240,
+ tokensAfter: 412,
+ trigger: 'auto',
+ at: 1_756_000_000_000,
+ ...over,
+})
+
+const rendern = (record: CompactionRecord): string =>
+ renderToStaticMarkup(createElement(CompactBlock, { record }))
+
+describe('Eine Verdichtung nimmt dem Verlauf nichts weg', () => {
+ it('MessageList filtert die Nachrichten genau zweimal: Rolle und hidden', () => {
+ // Die Zaehlung ist der Waechter, nicht die Formulierung. Wer die Liste
+ // spaeter „aufraeumt", schreibt einen dritten Filter — und der Verlauf
+ // verliert Nachrichten, die der Nutzer geschrieben und gelesen hat. Ein
+ // Test auf „der alte Filter ist noch da" wuerde das durchlassen.
+ //
+ // 2.6.8: die zweite Zeile ist umbrochen, seit App-Hinweise
+ // (`role:'system'` mit `notice`) im Verlauf stehen duerfen — sie
+ // erreichen das Modell nie und gehoeren trotzdem angezeigt. Der Waechter
+ // haengt deshalb an der ANZAHL und an dem, worauf gefiltert wird, nicht
+ // mehr am Wortlaut einer Zeile; sonst haette er bei jedem Umbruch
+ // angeschlagen, ohne dass sich die Regel geaendert hat.
+ const filter = codeZeilen(LISTE).filter((z) => z.includes('.filter('))
+ expect(filter.length).toBe(2)
+ expect(filter[0]).toContain("m.role === 'user'")
+ // Der zweite Filter entscheidet ueber die Sichtbarkeit und darf genau
+ // zwei Dinge lesen: die Rolle und `hidden` (plus `notice`, das eine
+ // Systemnachricht wieder sichtbar macht).
+ const sichtbarkeit = codeZeilen(LISTE)
+ .slice(codeZeilen(LISTE).indexOf(filter[1]))
+ .slice(0, 4).join(' ')
+ expect(sichtbarkeit).toContain('visibleMessages')
+ expect(sichtbarkeit).toMatch(/m\.role !== 'system'/)
+ expect(sichtbarkeit).toContain('m.hidden')
+ // Und nichts schneidet die Liste zu: kein Fenster, keine Seite.
+ expect(codeZeilen(LISTE).filter((z) => z.includes('.slice('))).toEqual([])
+ })
+
+ it('keine Verdichtung entscheidet, welche Nachrichten die Liste zeigt', () => {
+ // `compactions` und `upToMessageId` sind Anzeige-Eingaben. Sobald eines
+ // von beiden in einem Filter, einem Schnitt oder einer Bedingung um die
+ // Nachrichtenabbildung auftaucht, faengt die Anzeige an, den Verlauf zu
+ // beschneiden — und der Block behauptet dann etwas, was nicht mehr stimmt.
+ for (const z of codeZeilen(LISTE)) {
+ if (z.includes('.filter(') || z.includes('.slice(')) {
+ expect(z, 'ein Filter/Schnitt liest eine Verdichtung').not.toMatch(/compact|upTo/i)
+ }
+ }
+ // `compactions` wird an genau einer Stelle gelesen: als drittes Argument
+ // von compactionAnchors.
+ const compactions = codeZeilen(LISTE).filter((z) => z.includes('compactions'))
+ expect(compactions).toEqual(['conversation.compactions,'])
+ // Der Schnittpunkt selbst kommt in der Komponente gar nicht vor — die
+ // Zuordnung Nachricht → Linie macht compactionAnchors, nicht die Liste.
+ expect(LISTE).not.toContain('upToMessageId')
+ // Das Ergebnis wird nur nachgeschlagen, nie zum Aussortieren benutzt.
+ const compactAt = codeZeilen(LISTE).filter((z) => z.includes('compactAt'))
+ expect(compactAt).toEqual([
+ 'const compactAt = compactionAnchors(',
+ '{compactAt.get(message.id)?.map((record) => (',
+ ])
+ })
+
+ it('die Linie kommt zur Nachricht dazu, sie ersetzt sie nicht', () => {
+ // Beide stehen im selben Wrapper der Abbildung, und die Blase steht
+ // zuerst. Ein `record ? <CompactBlock/> : <MessageBubble/>` waere genau
+ // der Entwurf, den der Kopf von CompactBlock.tsx verwirft.
+ const wrapper = LISTE.indexOf('key={message.id}')
+ const blase = LISTE.indexOf('<MessageBubble')
+ const linie = LISTE.indexOf('<CompactBlock')
+ expect(wrapper).toBeGreaterThan(-1)
+ expect(blase).toBeGreaterThan(wrapper)
+ expect(linie).toBeGreaterThan(blase)
+ // Vom Wrapper bis zum Ende der Blase steht keine Verdichtung — die Blase
+ // haengt an nichts, was eine Verdichtung entscheidet.
+ expect(LISTE.slice(wrapper, LISTE.indexOf('/>', blase))).not.toMatch(/compactAt|compactions/)
+ })
+
+ it('auch der Code-Verlauf haengt die Linie an die Nachricht an', () => {
+ // CodexView baut die Nachricht in `gerendert` und gibt sie OHNE Linie
+ // unveraendert zurueck; mit Linie kommt sie im Fragment zuerst. Damit ist
+ // dort dieselbe Regel strukturell erzwungen wie in MessageList.
+ expect(CODEX).toContain('if (!linien?.length) return gerendert')
+ const fragment = CODEX.indexOf('{gerendert}')
+ const linie = CODEX.indexOf('<CompactBlock')
+ expect(fragment).toBeGreaterThan(-1)
+ expect(linie).toBeGreaterThan(fragment)
+ // Auch hier: die volle Liste geht in die Rechnung, gefiltert wird nur
+ // `hidden` — die Verdichtung filtert nichts.
+ expect(CODEX).toContain("messages.filter((m) => !m.hidden).map((m) => m.id)")
+ for (const z of codeZeilen(CODEX)) {
+ if (z.includes('messages.filter(') || z.includes('messages.slice(')) {
+ expect(z, 'ein Filter/Schnitt liest eine Verdichtung').not.toMatch(/compact|upTo/i)
+ }
+ }
+ })
+})
+
+describe('Die Linie steht in jedem Verlauf, nicht nur im ersten', () => {
+ /**
+ * Eine Verlaufsflaeche wird hier an ihren zwei Merkmalen erkannt, nicht am
+ * Namen: sie haengt am gemeinsamen Rollanker (`useAutoScroll`) und zeigt den
+ * Laufanker (`<WorkingAnchor`) unter dem Verlauf. Beides hat heute genau
+ * MessageList und CodexView.
+ *
+ * GRENZE: eine dritte Flaeche, die einen Verlauf OHNE diese beiden Teile
+ * zeigt, faellt durch dieses Raster. Darum stehen die zwei bekannten unten
+ * zusaetzlich beim Namen — dann kann die Ableitung nicht stillschweigend auf
+ * eine Datei zusammenschrumpfen und trotzdem gruen bleiben.
+ */
+ const verlaeufe = DATEIEN
+ .filter(([, inhalt]) => inhalt.includes('useAutoScroll(') && inhalt.includes('<WorkingAnchor'))
+ .map(([name]) => name)
+
+ it('jede Verlaufsflaeche montiert den Block', () => {
+ expect(verlaeufe).toContain('components/chat/MessageList.tsx')
+ expect(verlaeufe).toContain('components/chat/CodexView.tsx')
+ for (const name of verlaeufe) {
+ const src = quelltext(DATEIEN, name)
+ expect(src, `${name} importiert CompactBlock nicht`).toContain("from './CompactBlock'")
+ expect(src, `${name} rendert keine Verdichtungslinie`).toContain('<CompactBlock')
+ expect(src, `${name} rechnet die Linien nicht aus`).toContain('compactionAnchors(')
+ }
+ })
+
+ it('ein Datensatz, eine Linie — geschluesselt an record.id', () => {
+ // Der Index waere hier falsch: zwei Verdichtungen koennen auf derselben
+ // sichtbaren Zeile landen (compactionAnchors, Fall 3), und beim naechsten
+ // Lauf steht eine dritte dazwischen.
+ for (const name of verlaeufe) {
+ expect(quelltext(DATEIEN, name)).toContain('key={record.id}')
+ }
+ // Gemessen: ein Datensatz ergibt genau ein Etikett, zwei ergeben zwei.
+ const eins = rendern(datensatz())
+ expect(eins.match(/summarised/g)).toHaveLength(1)
+ const zwei = renderToStaticMarkup(
+ createElement(
+ 'div',
+ null,
+ [datensatz(), datensatz({ id: 'c2', replaced: 3 })].map((r) =>
+ createElement(CompactBlock, { key: r.id, record: r }),
+ ),
+ ),
+ )
+ expect(zwei.match(/summarised/g)).toHaveLength(2)
+ })
+})
+
+describe('Zugeklappt ist die Voreinstellung', () => {
+ it('die Zusammenfassung steht nicht im ersten Rendern', () => {
+ // Sie ist fuer das Modell geschrieben, nicht fuer den Leser. Aufgeklappt
+ // waere sie ein Textblock mitten im Verlauf, den niemand angefordert hat —
+ // und nach jeder Verdichtung einer mehr.
+ // Gegenprobe zuerst: die Marke steht wirklich im Datensatz. Ohne sie
+ // waeren die drei Verneinungen darunter still gruen — dieselbe Falle, die
+ // `quelltext` mit seinem Fehler statt `?? ''` schliesst.
+ expect(ZUSAMMENFASSUNG).toContain('MARKE-TASK')
+ expect(ZUSAMMENFASSUNG).toContain('MARKE-PROGRESS')
+ expect(ZUSAMMENFASSUNG).toContain('TASK')
+
+ const html = rendern(datensatz())
+ expect(html).toContain('aria-expanded="false"')
+ expect(html).not.toContain('MARKE-TASK')
+ expect(html).not.toContain('MARKE-PROGRESS')
+ expect(html).not.toContain('TASK')
+ // Die Linie selbst ist da — zugeklappt heisst nicht unsichtbar.
+ expect(html).toContain('7 messages summarised')
+ })
+
+ it('auch eine unlesbare Zusammenfassung klappt nichts auf', () => {
+ // Der Ruecktext „could not be read back" steht IM aufgeklappten Bereich.
+ // Stuende er aussen, wuerde ein alter oder kaputter Datensatz von selbst
+ // eine Fehlermeldung in den Verlauf schreiben.
+ const html = rendern(datensatz({ summary: '' }))
+ expect(html).toContain('aria-expanded="false"')
+ expect(html).not.toContain('could not be read back')
+ expect(html).toContain('7 messages summarised')
+ })
+})
+
+describe('Das Etikett sagt, was passiert ist', () => {
+ it('eine Nachricht heisst message, mehrere heissen messages', () => {
+ expect(rendern(datensatz({ replaced: 1 }))).toContain('1 message summarised')
+ expect(rendern(datensatz({ replaced: 2 }))).toContain('2 messages summarised')
+ // „auto" steht nur dran, wenn die Schwelle ausgeloest hat — bei /compact
+ // hat der Nutzer selbst gedrueckt und braucht die Auskunft nicht.
+ expect(rendern(datensatz({ trigger: 'auto' }))).toContain('>auto<')
+ expect(rendern(datensatz({ trigger: 'manual' }))).not.toContain('>auto<')
+ })
+
+ it('unter 1000 bleibt die Zahl ganz', () => {
+ // „0.4k" ist keine Verbesserung gegenueber „412": dieselbe Laenge, weniger
+ // Information. Genau das steht als Begruendung ueber `short`.
+ const html = rendern(datensatz({ tokensBefore: 999, tokensAfter: 412 }))
+ expect(html).toContain('999 → 412')
+ expect(html).not.toMatch(/0\.\dk/)
+ })
+
+ it('ab 1000 kuerzt die Anzeige auf k', () => {
+ expect(rendern(datensatz({ tokensBefore: 18240, tokensAfter: 412 }))).toContain('18.2k → 412')
+ expect(rendern(datensatz({ tokensBefore: 1000, tokensAfter: 1 }))).toContain('1.0k → 1')
+ })
+
+ it('eine kaputte Zahl wird zu 0, nicht zu einem Minus', () => {
+ // Die Zahlen kommen aus einer Schaetzung in einem gespeicherten Datensatz.
+ // Eine negative Restlaenge ist Unsinn, aber „-50" im Etikett sieht aus wie
+ // eine Aussage ueber den Chat.
+ expect(rendern(datensatz({ tokensBefore: 1000, tokensAfter: -50 }))).toContain('1.0k → 0')
+ })
+
+ it('ohne Ersparnis stehen gar keine Zahlen da', () => {
+ // Ein Pfeil zwischen zwei gleichen Zahlen behauptet einen Gewinn, den es
+ // nicht gab.
+ const html = rendern(datensatz({ tokensBefore: 500, tokensAfter: 500 }))
+ expect(html).not.toContain('→')
+ expect(html).toContain('7 messages summarised')
+ })
+})
diff --git a/src/components/chat/CompactBlock.tsx b/src/components/chat/CompactBlock.tsx
new file mode 100644
index 00000000..5f0a09f1
--- /dev/null
+++ b/src/components/chat/CompactBlock.tsx
@@ -0,0 +1,105 @@
+import { useState } from 'react'
+import { ChevronDown, FoldVertical } from 'lucide-react'
+import { summarySections } from '../../lib/compact-summary'
+import type { CompactionRecord } from '../../types/chat'
+
+/**
+ * Tausender kurz: 18240 → "18.2k". Unter 1000 bleibt die Zahl ganz, denn
+ * "0.4k" ist keine Verbesserung gegenueber "412" — es ist dieselbe Laenge mit
+ * weniger Information.
+ */
+function short(n: number): string {
+ if (!Number.isFinite(n) || n < 0) return '0'
+ if (n < 1000) return String(Math.round(n))
+ return `${(n / 1000).toFixed(1)}k`
+}
+
+interface Props {
+ record: CompactionRecord
+}
+
+/**
+ * Die Schnittstelle einer Verdichtung, sichtbar im Verlauf.
+ *
+ * WAS HIER NICHT PASSIERT — und warum das die eigentliche Entscheidung ist:
+ * dieser Block LOESCHT NICHTS und VERSTECKT NICHTS. Die Nachrichten oberhalb
+ * bleiben stehen, vollstaendig, scrollbar, kopierbar. Verdichtet wird allein
+ * die Nutzlast an das Modell.
+ *
+ * Der naheliegende Entwurf waere gewesen, die ersetzten Turns einzuklappen —
+ * er sieht aufgeraeumter aus und ist falsch. Der Nutzer hat diese Turns
+ * geschrieben und gelesen; sie wegzuraeumen, weil ein Fenster voll wurde,
+ * verwechselt das Gedaechtnis des Modells mit dem des Menschen. Der Verlauf
+ * ist das Protokoll, nicht der Puffer. Sichtbar wird darum nur die LINIE: ab
+ * hier sieht das Modell die Zusammenfassung statt der Turns darueber.
+ *
+ * Zugeklappt ist die Voreinstellung, weil die Zusammenfassung fuer das Modell
+ * geschrieben ist und nicht fuer den Leser — sie steht bereit, wenn jemand
+ * wissen will, WAS behalten wurde, und draengt sich sonst nicht auf. Genau
+ * das ist auch die Frage, die nach einer Verdichtung wirklich aufkommt: nicht
+ * "ist etwas passiert" (das sagt die Linie), sondern "was hat es sich
+ * gemerkt".
+ */
+export function CompactBlock({ record }: Props) {
+ const [open, setOpen] = useState(false)
+ const sections = summarySections(record.summary)
+
+ const saved = record.tokensBefore - record.tokensAfter
+ const label = `${record.replaced} ${record.replaced === 1 ? 'message' : 'messages'} summarised`
+
+ return (
+ <div className="my-3">
+ <button
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ className="group flex items-center gap-2 w-full text-left"
+ >
+ <span className="h-px flex-1 bg-gray-200 dark:bg-white/10" />
+ <span className="flex items-center gap-1.5 shrink-0 px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.03] group-hover:border-gray-300 dark:group-hover:border-white/20 transition-colors">
+ <FoldVertical size={10} className="text-gray-400 dark:text-gray-500 shrink-0" />
+ <span className="t-micro text-gray-500 dark:text-gray-400">{label}</span>
+ {saved > 0 && (
+ <span className="t-mono text-gray-400 dark:text-gray-600">
+ {short(record.tokensBefore)} → {short(record.tokensAfter)}
+ </span>
+ )}
+ {record.trigger === 'auto' && (
+ <span className="t-micro text-gray-400 dark:text-gray-600">auto</span>
+ )}
+ <ChevronDown
+ size={10}
+ className={`text-gray-400 shrink-0 transition-transform ${open ? 'rotate-180' : ''}`}
+ />
+ </span>
+ <span className="h-px flex-1 bg-gray-200 dark:bg-white/10" />
+ </button>
+
+ {open && (
+ <div className="mt-2 rounded border border-gray-200 dark:border-white/10 bg-gray-50/50 dark:bg-white/[0.02] px-3 py-2">
+ {sections.length ? (
+ <div className="space-y-2">
+ {sections.map((s) => (
+ <div key={s.heading}>
+ <div className="t-label text-gray-400 dark:text-gray-600">{s.heading}</div>
+ {/* whitespace-pre-wrap: die Zusammenfassung ist Klartext mit
+ eigenen Zeilen und Aufzaehlungen. Sie durch den
+ Markdown-Renderer zu schicken waere falsch — sie kommt
+ aus einem Modell, das gerade NICHT auf Format geprueft
+ wurde, und ein halboffener Codeblock darin wuerde den
+ Rest des Verlaufs mitreissen. */}
+ <div className="t-micro whitespace-pre-wrap text-gray-600 dark:text-gray-300 leading-relaxed">
+ {s.body}
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="t-micro text-gray-400 dark:text-gray-600">
+ This summary could not be read back.
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsx
index 005b466c..ac6c51ad 100644
--- a/src/components/chat/TokenCounter.tsx
+++ b/src/components/chat/TokenCounter.tsx
@@ -2,6 +2,9 @@ import { useChatStore } from '../../stores/chatStore'
import { computeContextFill } from '../../lib/token-usage'
import { useActiveContextWindow } from '../../hooks/useActiveContextWindow'
import { useSendSizeStore } from '../../stores/sendSizeStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { shouldAutoCompact, autoCompactHint } from '../../lib/compact-trigger'
+import { newestCompaction, isModelVisible } from '../../lib/run-compact-command'
export function TokenCounter() {
const activeConversationId = useChatStore((s) => s.activeConversationId)
@@ -15,6 +18,14 @@ export function TokenCounter() {
// (David: "muss immer stimmen"). Ollama = the num_ctx we send; LM Studio =
// loaded_context_length (what it actually loaded), NOT the model's max.
const ctx = useActiveContextWindow()
+ // MUSS vor dem fruehen `return null` weiter unten stehen. Als dieser Hook
+ // dort unten bei seiner Verwendung stand, hatte die Komponente vier Hooks im
+ // leeren Chat und fuenf im gefuellten — React 19 wirft dann beim Uebergang
+ // „Rendered more hooks than during the previous render", und das ist ein
+ // Absturz, kein Warnhinweis. Der Weg dorthin ist alltaeglich: neuer Chat mit
+ // einem Cloud-Modell (ContextDropdown rendert die Kinder auch, wenn das
+ // Fenster nicht verstellbar ist), erste Nachricht — fertig.
+ const autoSchwelle = useSettingsStore((s) => s.settings.autoCompactThreshold)
const conversation = conversations.find((c) => c.id === activeConversationId)
const messages = conversation?.messages || []
@@ -79,17 +90,66 @@ export function TokenCounter() {
? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}), anchored on the model's last reported usage (includes system prompt + tools + RAG); reasoning tokens are not context and aren't counted${capNote}`
: `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}), estimate until the model reports real usage${capNote}`
+ // ── Wie weit ist es noch bis zur automatischen Kompaktierung ────────────
+ //
+ // WARUM UEBERHAUPT: bis hierher stand die Schwelle ausschliesslich in den
+ // Einstellungen. Wer sie eingeschaltet hatte, sah im Chat nur den Fuellstand
+ // und konnte nicht wissen, ob die naechste Nachricht noch durchgeht oder
+ // eine Zusammenfassung ausloest. Die Claude-Code-Desktop-App schreibt genau
+ // diesen Satz in ihre Statuszeile, und er ist der Grund, warum dort niemand
+ // von einer Kompaktierung ueberrascht wird.
+ //
+ // WARUM ueber `shouldAutoCompact` und nicht mit einer eigenen Rechnung: die
+ // wirksame Schwelle ist NICHT die eingestellte. `shouldAutoCompact` zieht
+ // einen Sicherheitsabschlag ab, solange der Fuellstand nur geschaetzt ist —
+ // eine hier selbst gerechnete Prozentzahl waere im haeufigsten Fall (kein
+ // echter Usage-Report) schlicht die falsche. Dieselbe Funktion zu fragen,
+ // die spaeter auch entscheidet, ist der einzige Weg, bei dem Anzeige und
+ // Verhalten nicht auseinanderlaufen koennen.
+ const sichtbareAnzahl = messages.filter(isModelVisible).length
+ const autoUrteil = autoSchwelle
+ ? shouldAutoCompact({
+ used: rawUsed,
+ window: maxTokens,
+ source: fill.source,
+ real: fill.real,
+ // `maxTokens > 0` war immer wahr — auch fuer den 16384er-Notnagel
+ // weiter oben, den es nur gibt, solange die Anbieter-Abfrage laeuft.
+ // Der Zaehler behauptete damit sekundenlang ein bekanntes Fenster:
+ // 14k belegt auf einem 128k-Modell las sich als "triggers on the next
+ // message", bis die Antwort kam. `window` ist die Zahl VOR dem
+ // Notnagel und damit die ehrliche Auskunft.
+ windowIsTrue: window > 0,
+ messageCount: sichtbareAnzahl,
+ threshold: autoSchwelle,
+ lastCompactAtMessageCount: newestCompaction(conversation?.compactions)?.atMessageCount,
+ })
+ : null
+ const autoHinweis = autoCompactHint(autoUrteil)
+
// `span`, nicht `div`, und ohne eigenes Padding: seit D-S06 ist dieser
// Fuellstand die Beschriftung INNERHALB des Kontextfenster-Knopfes
// (`ContextDropdown`). Ein `div` im `<button>` ist kein gueltiges
// Phrasing-Content, und das Padding kam sonst zweimal.
return (
- <span className={`inline-flex items-center gap-1.5 ${color}`} title={title}>
- <span className="block w-12 h-1 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden">
+ <span className={`inline-flex items-center gap-1.5 ${color}`} title={autoHinweis ? `${title}. ${autoHinweis}` : title}>
+ <span className="relative block w-12 h-1 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden">
<span
className={`block h-full rounded-full transition-[width] duration-[var(--motion-slow)] ${barColor}`}
style={{ width: `${Math.min(ratio * 100, 100)}%` }}
/>
+ {/* Die Marke sitzt auf der WIRKSAMEN Schwelle, derselben, die
+ entscheidet. Nur gezeichnet, wenn sie ueberhaupt in den Balken
+ faellt — eine Marke am Rand behauptet eine Genauigkeit, die zwei
+ Pixel nicht tragen. */}
+ {autoUrteil && autoUrteil.effectiveThreshold > 0.02 && autoUrteil.effectiveThreshold < 0.98 && (
+ <span
+ aria-hidden
+ data-testid="auto-compact-mark"
+ className="absolute top-0 bottom-0 w-px bg-current opacity-50"
+ style={{ left: `${autoUrteil.effectiveThreshold * 100}%` }}
+ />
+ )}
</span>
{/* `font-mono tabular-nums` war dasselbe Rezept, nur an der Call-Site
buchstabiert. `.lu-hud-num` ist die eine Stelle, an der es steht. */}
diff --git a/src/lib/__tests__/auto-compact-wiring.test.ts b/src/lib/__tests__/auto-compact-wiring.test.ts
new file mode 100644
index 00000000..e207d04e
--- /dev/null
+++ b/src/lib/__tests__/auto-compact-wiring.test.ts
@@ -0,0 +1,498 @@
+/**
+ * Auto-Compact: das Opt-in und die Verdrahtung (2.6.8, Compact-Schritt 4).
+ *
+ * Zwei Zusicherungen, die einzeln wenig und zusammen alles wert sind.
+ *
+ * Die erste ist eine Negativ-Aussage. Mit den ausgelieferten Einstellungen
+ * darf `maybeAutoCompact` NICHTS tun — nicht den Gespraechs-Store lesen, nicht
+ * das Fenster aufloesen, erst recht kein Modell fragen. Die Entscheidung vom
+ * 02.09.2026 war "einstellbar sonst aus", und der Grund steht in
+ * compact-trigger.ts: eine Zusammenfassung ersetzt Gespraechsverlauf, und wenn
+ * sie falsch ist, verliert der Nutzer Arbeit, ohne es zu merken. Ein gespei-
+ * chertes Profil auf STORE_VERSION 21 liefert das Feld als `undefined` aus
+ * (der additive Merge fuellt es erst beim naechsten Versionssprung nach) —
+ * wuerde das als Zahl durchgehen, waere das Feature bei jedem Bestandsnutzer
+ * ungefragt an.
+ *
+ * Die zweite ist die Verdrahtung, und sie ist der eigentliche Wert dieser
+ * Datei. Die Funktion taugt nur so viel, wie es Sende-Pfade gibt, die sie
+ * aufrufen. Ein Hook, der sie vergisst, verliert das Feature auf einer ganzen
+ * Oberflaeche — nichts bricht, nichts wirft, die Chats werden nur wieder
+ * vollstaendig verschickt. Dasselbe gilt fuer die Nutz-Seite: wer eine
+ * Compaction aufzeichnet, sie aber beim Bauen der Anfrage nicht anwendet,
+ * bezahlt die Zusammenfassung und schickt trotzdem die ganze Historie.
+ * Deshalb wird die Liste der Sende-Hooks aus dem Quellverzeichnis abgeleitet
+ * und nicht hier hingeschrieben.
+ *
+ * Lauf: npx vitest run src/lib/__tests__/auto-compact-wiring.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { readFileSync, readdirSync } from 'node:fs'
+import { resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+// resolveAgentNumCtx ist der Netz-Rand dieses Pfades: es fragt Ollama bzw. den
+// Modellkatalog nach dem echten Fenster. Ersetzt, weil "wurde es ueberhaupt
+// gefragt?" GENAU die Aussage ist, um die es in dieser Datei geht — anders ist
+// ein nicht erfolgter Aufruf nicht beobachtbar — und weil sonst jeder Lauf an
+// einem laufenden Backend haengen wuerde. Das Modul unter Test bleibt echt.
+vi.mock('../agent-num-ctx', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../agent-num-ctx')>()
+ // Seit 2026-09-02 fragt der Auto-Ausloeser die Fassung MIT Vertrauensangabe
+ // — er braucht die Auskunft "gemessen oder geraten", die eine blosse Zahl
+ // nicht geben kann. Beide werden ersetzt, damit diese Datei weiterhin
+ // beobachtet, OB gefragt wurde, egal auf welchem der beiden Wege.
+ return {
+ ...actual,
+ resolveAgentNumCtx: vi.fn(async () => 32768),
+ resolveAgentNumCtxWithConfidence: vi.fn(async () => ({ ctx: 32768, gemessen: true })),
+ }
+})
+
+// Der Zusammenfasser ist der Modell-Rand dieses Pfades. Ersetzt, weil dieser
+// Abschnitt genau den Fall braucht, den ein echtes Modell nicht auf Bestellung
+// liefert: einen FEHLGESCHLAGENEN Lauf.
+vi.mock('../compact-run', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../compact-run')>()
+ return { ...actual, runCompactSummary: vi.fn(actual.runCompactSummary) }
+})
+
+import { maybeAutoCompact } from '../run-compact-command'
+import { runCompactSummary } from '../compact-run'
+import { resolveAgentNumCtxWithConfidence } from '../agent-num-ctx'
+import { usableThreshold, MIN_MESSAGES_TO_COMPACT, MIN_MESSAGES_SINCE_COMPACT } from '../compact-trigger'
+import { DEFAULT_SETTINGS } from '../constants'
+import { useChatStore } from '../../stores/chatStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import type { Settings } from '../../types/settings'
+
+const fensterAufloesen = vi.mocked(resolveAgentNumCtxWithConfidence)
+
+const here = dirname(fileURLToPath(import.meta.url))
+const hooksDir = resolve(here, '../../hooks')
+const lies = (datei: string) => readFileSync(resolve(hooksDir, datei), 'utf8')
+
+const MODELL = 'llama3:8b'
+
+/** Ein Gespraech, das lang genug ist, dass die Kuerze kein Ausgang mehr ist. */
+function seedGespraech(anzahl = MIN_MESSAGES_TO_COMPACT + 4): string {
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ const id = useChatStore.getState().createConversation(MODELL, '')
+ for (let i = 0; i < anzahl; i++) {
+ useChatStore.getState().addMessage(id, {
+ id: `m${i}`,
+ role: i % 2 === 0 ? 'user' : 'assistant',
+ content: `Nachricht ${i}`,
+ timestamp: i,
+ })
+ }
+ return id
+}
+
+/** Einstellungen wie ausgeliefert, mit genau einer geaenderten Schwelle. */
+function setzeSchwelle(schwelle: number) {
+ useSettingsStore.setState({
+ settings: { ...DEFAULT_SETTINGS, autoCompactThreshold: schwelle },
+ })
+}
+
+/** Ein Profil aus der Zeit vor dem Feld: der Schluessel fehlt ganz. */
+function setzeProfilOhneFeld() {
+ const ohne: Record<string, unknown> = { ...DEFAULT_SETTINGS }
+ delete ohne.autoCompactThreshold
+ useSettingsStore.setState({ settings: ohne as unknown as Settings })
+}
+
+/**
+ * Zaehlt Zugriffe auf den Gespraechs-Store. Erst NACH dem Seeden anhaengen,
+ * sonst zaehlt das Aufbauen des Falls als Zugriff der Funktion.
+ */
+function beobachteStore() {
+ return vi.spyOn(useChatStore, 'getState')
+}
+
+describe('Opt-in: mit den ausgelieferten Einstellungen passiert nichts', () => {
+ beforeEach(() => {
+ fensterAufloesen.mockClear()
+ useSettingsStore.setState({ settings: DEFAULT_SETTINGS })
+ })
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('die ausgelieferte Schwelle ist 0 und liest sich als "aus"', () => {
+ expect(DEFAULT_SETTINGS.autoCompactThreshold).toBe(0)
+ expect(DEFAULT_SETTINGS.autoCompactThreshold).toBeFalsy()
+ // Dieselbe 0 muss auch der Entscheider als "nie" lesen, sonst haengt das
+ // Aus-Sein an zwei Stellen, die auseinanderlaufen koennen.
+ expect(usableThreshold(DEFAULT_SETTINGS.autoCompactThreshold)).toBeNull()
+ })
+
+ it('mit den ausgelieferten Einstellungen liefert maybeAutoCompact null', async () => {
+ const convId = seedGespraech()
+ useSettingsStore.setState({ settings: DEFAULT_SETTINGS })
+ expect(await maybeAutoCompact({ conversationId: convId, activeModel: MODELL })).toBeNull()
+ })
+
+ it('ein gespeichertes Profil ohne das Feld ist aus, nicht 0.3', async () => {
+ // STORE_VERSION 21 hat fuer diesen Schluessel keinen Sprung bekommen, das
+ // Feld kommt also bei Bestandsnutzern als undefined an. Ein Default, der
+ // sich hier einschliche, waere das Feature bei allen von ihnen an.
+ const convId = seedGespraech()
+ setzeProfilOhneFeld()
+ expect(useSettingsStore.getState().settings.autoCompactThreshold).toBeUndefined()
+ expect(await maybeAutoCompact({ conversationId: convId, activeModel: MODELL })).toBeNull()
+ })
+
+ it('auch eine Schwelle ausserhalb des erlaubten Bereichs bleibt aus', async () => {
+ const convId = seedGespraech()
+ // 0.2 liegt unter MIN_THRESHOLD. Die Zahl ist wahr, aber unbrauchbar —
+ // die UI darf sie nicht liefern, und wenn doch, entscheidet der Trigger.
+ setzeSchwelle(0.2)
+ expect(await maybeAutoCompact({ conversationId: convId, activeModel: MODELL })).toBeNull()
+ })
+})
+
+describe('Reihenfolge: das Billige zuerst, denn das laeuft bei jedem Senden', () => {
+ beforeEach(() => {
+ fensterAufloesen.mockClear()
+ useSettingsStore.setState({ settings: DEFAULT_SETTINGS })
+ })
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('ohne Schwelle wird weder der Store gelesen noch das Fenster aufgeloest', async () => {
+ // Das ist die Eigenschaft, die das Feature bezahlbar macht: dieser Aufruf
+ // steht in jedem Sende-Pfad und muss ohne Opt-in ein Vergleich sein und
+ // sonst nichts. Ein Store-Lesen waere noch billig, das Fenster-Aufloesen
+ // ist ein Netzweg zum Backend — auf jeder Nachricht, fuer nichts.
+ const convId = seedGespraech()
+ const store = beobachteStore()
+
+ expect(await maybeAutoCompact({ conversationId: convId, activeModel: MODELL })).toBeNull()
+
+ expect(store).not.toHaveBeenCalled()
+ expect(fensterAufloesen).not.toHaveBeenCalled()
+ })
+
+ it('mit Schwelle werden beide sehr wohl gefragt — sonst hiesse die Prüfung nichts', async () => {
+ // Gegenprobe zur vorigen: ohne sie koennte maybeAutoCompact schlicht immer
+ // frueh aussteigen und beide Zusicherungen waeren erfuellt.
+ const convId = seedGespraech()
+ setzeSchwelle(0.8)
+ const store = beobachteStore()
+
+ // Kurze Nachrichten gegen ein 32k-Fenster: der Trigger sagt "below" und
+ // es kommt null zurueck, ohne dass ein Modell etwas schreiben muesste.
+ expect(await maybeAutoCompact({ conversationId: convId, activeModel: MODELL })).toBeNull()
+
+ expect(store).toHaveBeenCalled()
+ expect(fensterAufloesen).toHaveBeenCalled()
+ })
+
+ it('ohne aktives Modell null, und ebenfalls vor dem Fenster', async () => {
+ // Ohne Modell gibt es niemanden, der die Zusammenfassung schreiben koennte.
+ // Die Pruefung MUSS vor dem Aufloesen stehen, denn das Aufloesen fragt
+ // genau dieses Modell — mit null in der Hand ginge die Frage ins Leere.
+ const convId = seedGespraech()
+ setzeSchwelle(0.8)
+ const store = beobachteStore()
+
+ expect(await maybeAutoCompact({ conversationId: convId, activeModel: null })).toBeNull()
+
+ expect(fensterAufloesen).not.toHaveBeenCalled()
+ // Der Store wird ebenfalls nicht gebraucht: der Ausgang steht schon fest.
+ expect(store).not.toHaveBeenCalled()
+ })
+
+ it('ein Gespraech, das es nicht mehr gibt, endet ebenfalls ohne Fenster', async () => {
+ setzeSchwelle(0.8)
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+
+ expect(await maybeAutoCompact({ conversationId: 'weg', activeModel: MODELL })).toBeNull()
+ expect(fensterAufloesen).not.toHaveBeenCalled()
+ })
+})
+
+// ── Die Verdrahtung ────────────────────────────────────────────────────────
+
+/**
+ * Die Sende-Hooks, aus dem Verzeichnis abgeleitet statt hier aufgezaehlt.
+ *
+ * Merkmal ist `endTurnDurably(`: das ruft genau der Code, der eine Modell-
+ * Runde gegen ein Gespraech gefahren hat und sie abschliesst. Wer eine Runde
+ * faehrt, baut vorher eine Anfrage aus der Historie — und genau dort gehoeren
+ * beide Aufrufe hin. Das Merkmal ist bewusst NICHT compaction-bezogen, sonst
+ * wuerde ein Hook, der beides vergisst, sich selbst aus der Pruefung nehmen.
+ *
+ * EHRLICHE GRENZE: ein vierter Sende-Pfad, der seine Runde ohne
+ * endTurnDurably beendet, wird hier nicht erfasst. Das ist kein zweites
+ * Versehen, sondern dasselbe — wer das Flush-Ende vergisst, verliert schon
+ * die Persistenz der Runde und faellt in stores/durability auf.
+ */
+function sendePfadHooks(): string[] {
+ return readdirSync(hooksDir)
+ .filter((f) => f.startsWith('use') && f.endsWith('.ts'))
+ .filter((f) => /\bendTurnDurably\s*\(/.test(lies(f)))
+ .sort()
+}
+
+describe('Verdrahtung: jeder Sende-Pfad ruft maybeAutoCompact', () => {
+ it('die Ableitung findet die drei bekannten Oberflaechen', () => {
+ // Bricht das Merkmal weg, wird die Liste leer und alle Pruefungen unten
+ // waeren still erfuellt. Diese Zeile ist die Sicherung darunter.
+ const hooks = sendePfadHooks()
+ expect(hooks).toEqual(
+ expect.arrayContaining(['useAgentChat.ts', 'useChat.ts', 'useCodex.ts']),
+ )
+ expect(hooks.length).toBeGreaterThanOrEqual(3)
+ })
+
+ it.each(sendePfadHooks())('%s ruft maybeAutoCompact auf', (datei) => {
+ // Ein Hook ohne diesen Aufruf verliert das Feature komplett und lautlos:
+ // die Einstellung steht weiter da, auf dieser Oberflaeche passiert nur nie
+ // etwas. Der Import allein zaehlt nicht, es muss ein Aufruf sein.
+ expect(/\bmaybeAutoCompact\s*\(/.test(lies(datei))).toBe(true)
+ })
+
+ it.each(sendePfadHooks())('%s wendet applyStoredCompaction auf die Nutzlast an', (datei) => {
+ // Die Gegenseite: aufzeichnen ohne anwenden heisst, die Zusammenfassung
+ // wird bezahlt und die volle Historie trotzdem verschickt. Der Nutzer
+ // saehe den Block im Verlauf und haette nichts davon.
+ expect(/\bapplyStoredCompaction\s*\(/.test(lies(datei))).toBe(true)
+ })
+})
+
+
+// ── Der stumme Fehlschlag ─────────────────────────────────────────────────
+
+describe('Auto-Kompaktierung, die schiefgeht, sagt es', () => {
+ const zusammenfassen = vi.mocked(runCompactSummary)
+
+ beforeEach(() => {
+ fensterAufloesen.mockClear()
+ zusammenfassen.mockReset()
+ })
+ afterEach(() => { vi.restoreAllMocks() })
+
+ /** Ein Gespraech, das die Schwelle sicher reisst. */
+ function vollesGespraech(): string {
+ const id = seedGespraech(MIN_MESSAGES_TO_COMPACT + 4)
+ for (let i = 0; i < 40; i++) {
+ useChatStore.getState().addMessage(id, {
+ id: `lang${i}`, role: i % 2 === 0 ? 'user' : 'assistant',
+ content: 'x'.repeat(4000), timestamp: 1000 + i,
+ })
+ }
+ return id
+ }
+
+ const hinweise = (id: string) =>
+ (useChatStore.getState().conversations.find((c) => c.id === id)?.messages ?? [])
+ .filter((m) => m.role === 'system' && !!m.notice)
+
+ it('schreibt eine Warnung in den Verlauf, wenn das Modell nichts Brauchbares liefert', async () => {
+ setzeSchwelle(0.5)
+ const id = vollesGespraech()
+ zusammenfassen.mockResolvedValue({ ok: false, reason: 'unusable' } as never)
+
+ const rec = await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ expect(rec).toBeNull()
+
+ // OHNE diese Zeile war der Fehlschlag komplett unsichtbar: null zurueck,
+ // Senden laeuft weiter, und die Einstellung tut stumm nichts.
+ const w = hinweise(id)
+ expect(w).toHaveLength(1)
+ expect(w[0].notice).toBe('warn')
+ expect(w[0].content).toContain('Auto-compaction did not go through')
+ // Der Grund steht mit drin, nicht nur die Tatsache.
+ expect(w[0].content).toContain('did not produce a usable summary')
+ })
+
+ it('wiederholt dieselbe Warnung nicht bei jedem Senden', async () => {
+ // Die Ursache besteht fort — ohne Bremse stuende die Warnung nach zehn
+ // Nachrichten zehnmal da und der Chat waere unlesbar.
+ setzeSchwelle(0.5)
+ const id = vollesGespraech()
+ zusammenfassen.mockResolvedValue({ ok: false, reason: 'unusable' } as never)
+
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+
+ expect(hinweise(id)).toHaveLength(1)
+ })
+
+ it('warnt NICHT erneut, nur weil sich eine andere Notiz dazwischengeschoben hat', async () => {
+ // Der Ablauf, der die erste Fassung erledigt hat: verglichen wurde gegen
+ // den LETZTEN Hinweis im Verlauf. Seit eine fertige Hintergrundaufgabe
+ // sich ebenfalls als Hinweis meldet, ist die Warnung staendig nicht mehr
+ // die letzte — und dieselbe Ursache schrieb sie jedes Mal neu. Mit fuenf
+ // Hintergrundagenten stand derselbe Satz fuenfmal da.
+ setzeSchwelle(0.5)
+ const id = vollesGespraech()
+ zusammenfassen.mockResolvedValue({ ok: false, reason: 'unusable' } as never)
+
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ expect(hinweise(id)).toHaveLength(1)
+
+ useChatStore.getState().addMessage(id, {
+ id: 'bg-task-abc', role: 'system', notice: 'info',
+ content: 'Background agent [task-abc] finished: fertig', timestamp: Date.now(),
+ })
+
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ const warnungen = hinweise(id).filter((m) => m.id.startsWith('autocompact-fail-'))
+ expect(warnungen).toHaveLength(1)
+ })
+
+ it('warnt wieder, wenn genug Gespraech vergangen ist', async () => {
+ // Die Gegenrichtung, und sie ist der Grund, warum "nur einmal" falsch
+ // waere: warnt es bei Nachricht 20 und scheitert danach sechzig Mal
+ // weiter, bliebe es sechzig Nachrichten still — waehrend der Zaehler
+ // daneben "triggers on the next message" sagt. Also genau der Zustand,
+ // gegen den diese Warnung gebaut wurde.
+ setzeSchwelle(0.5)
+ const id = vollesGespraech()
+ zusammenfassen.mockResolvedValue({ ok: false, reason: 'unusable' } as never)
+
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ expect(hinweise(id).filter((m) => m.id.startsWith('autocompact-fail-'))).toHaveLength(1)
+
+ for (let i = 0; i < MIN_MESSAGES_SINCE_COMPACT; i++) {
+ useChatStore.getState().addMessage(id, {
+ id: `spaeter${i}`, role: i % 2 === 0 ? 'user' : 'assistant',
+ content: 'weiter', timestamp: Date.now(),
+ })
+ }
+
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ expect(hinweise(id).filter((m) => m.id.startsWith('autocompact-fail-'))).toHaveLength(2)
+ })
+
+ it('erkennt die eigene Warnung am Id-Praefix, nicht am Wortlaut', async () => {
+ // `compactOutcomeMessage` buendelt mehrere Restgruende auf DENSELBEN Satz.
+ // Ein Textvergleich haette zwei verschiedene Ursachen nicht auseinander-
+ // gehalten — und, schlimmer, eine fremde Notiz mit zufaellig gleichem
+ // Wortlaut faelschlich als eigene Warnung gelesen.
+ setzeSchwelle(0.5)
+ const id = vollesGespraech()
+ zusammenfassen.mockResolvedValue({ ok: false, reason: 'unusable' } as never)
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+
+ const [w] = hinweise(id).filter((m) => m.id.startsWith('autocompact-fail-'))
+ expect(w).toBeDefined()
+ // Eine gleichlautende Notiz ohne das Praefix darf die Sperre nicht setzen.
+ const id2 = vollesGespraech()
+ useChatStore.getState().addMessage(id2, {
+ id: 'fremd-1', role: 'system', notice: 'warn',
+ content: w.content, timestamp: Date.now(),
+ })
+ await maybeAutoCompact({ conversationId: id2, activeModel: MODELL })
+ expect(hinweise(id2).filter((m) => m.id.startsWith('autocompact-fail-'))).toHaveLength(1)
+ })
+
+ it('sagt nichts, wenn der Nutzer selbst abgebrochen hat', async () => {
+ // Er hat auf Stopp gedrueckt; ihm zu melden, dass daraufhin gestoppt
+ // wurde, ist Laerm.
+ setzeSchwelle(0.5)
+ const id = vollesGespraech()
+ zusammenfassen.mockResolvedValue({ ok: false, reason: 'aborted' } as never)
+
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ expect(hinweise(id)).toHaveLength(0)
+ })
+
+ it('sagt nichts, wenn es schlicht nichts zusammenzufassen gab', async () => {
+ // Dieser Weg laeuft VOR JEDEM SENDEN. Eine Zeile fuer "nichts zu tun"
+ // waere eine Zeile pro Nachricht.
+ setzeSchwelle(0.5)
+ const id = vollesGespraech()
+ zusammenfassen.mockResolvedValue({ ok: false, reason: 'nothing-to-compact' } as never)
+
+ await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ expect(hinweise(id)).toHaveLength(0)
+ })
+
+ it('schreibt nichts in den Verlauf, wenn es geklappt hat', async () => {
+ // Der Erfolg hat seine eigene Darstellung: den Compact-Block an der
+ // Schnittstelle. Ein zusaetzlicher Hinweis waere dasselbe zweimal.
+ setzeSchwelle(0.5)
+ const id = vollesGespraech()
+ zusammenfassen.mockResolvedValue({
+ ok: true,
+ summary: { task: 'T', requests: 'R', progress: 'P', decisions: 'D', facts: 'F', open: 'O', rest: '' },
+ } as never)
+
+ const rec = await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ expect(rec).not.toBeNull()
+ expect(hinweise(id)).toHaveLength(0)
+ })
+})
+
+
+// ── Ein Nenner fuer Anzeige UND Entscheidung ──────────────────────────────
+
+describe('Der Auto-Ausloeser rechnet gegen das SENDEfenster, nicht das Modellfenster', () => {
+ const zusammenfassen = vi.mocked(runCompactSummary)
+
+ beforeEach(() => {
+ fensterAufloesen.mockClear()
+ zusammenfassen.mockReset()
+ })
+ afterEach(() => { vi.restoreAllMocks() })
+
+ /**
+ * WARUM: die Agentenschleife baut ihre Nachrichten gegen
+ * `effectiveSendWindow` — einen Anteil des Modellfensters, bei bezahlten
+ * Anbietern zusaetzlich gekappt. Derselbe Wert ist der Nenner des
+ * Fuellbalkens. Der Ausloeser nahm stattdessen das rohe Modellfenster.
+ *
+ * Folge, bevor das behoben war: Balken bei 94 % samt "triggers on the next
+ * message", Ausloeser rechnet 0.3 und tut nie etwas. Nicht einmal, sondern
+ * fuer immer — der Nutzer sieht eine eingeschaltete Funktion, die stumm
+ * nichts tut, und das ist der Zustand, den dieser ganze Bereich vermeiden
+ * soll.
+ */
+ it('kompaktiert, wenn das SENDEfenster voll ist, obwohl das Modellfenster Platz haette', async () => {
+ // 32768 Modellfenster (die Attrappe), davon geht `effectiveSendWindow`
+ // auf einen Anteil herunter. Ein Gespraech, das den Anteil reisst, aber
+ // unter dem rohen Fenster bliebe, muss ausloesen.
+ setzeSchwelle(0.8)
+ const id = seedGespraech(MIN_MESSAGES_TO_COMPACT + 4)
+ // ~21k Zeichen ≈ 5,3k Token: ueber 0.8 des Anteils, deutlich unter 0.8
+ // des rohen 32768er-Fensters.
+ for (let i = 0; i < 22; i++) {
+ useChatStore.getState().addMessage(id, {
+ id: `f${i}`, role: i % 2 === 0 ? 'user' : 'assistant',
+ content: 'y'.repeat(4000), timestamp: 2000 + i,
+ })
+ }
+ zusammenfassen.mockResolvedValue({
+ ok: true,
+ summary: { task: 'T', requests: 'R', progress: 'P', decisions: 'D', facts: 'F', open: 'O', rest: '' },
+ } as never)
+
+ const rec = await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ expect(rec).not.toBeNull()
+ })
+
+ it('laesst ein selbst uebergebenes Fenster unangetastet', async () => {
+ // Der einfache Chat waehlt seinen Nenner selbst (`modelWindowTokens`) und
+ // kennt die Sende-Kappe der Agentenschleife gar nicht. Wer `window`
+ // uebergibt, bekommt genau dieses — sonst haette der Parameter keinen Sinn.
+ setzeSchwelle(0.8)
+ const id = seedGespraech(MIN_MESSAGES_TO_COMPACT + 4)
+ zusammenfassen.mockReset()
+
+ // Riesiges Fenster, kurzer Chat: nichts darf passieren, und der Aufloeser
+ // darf gar nicht erst gefragt werden.
+ const rec = await maybeAutoCompact({
+ conversationId: id, activeModel: MODELL, window: 1_000_000, windowIsTrue: true,
+ })
+ expect(rec).toBeNull()
+ expect(fensterAufloesen).not.toHaveBeenCalled()
+ expect(zusammenfassen).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/__tests__/chat-send-budget.test.ts b/src/lib/__tests__/chat-send-budget.test.ts
index c12d71a6..33313169 100644
--- a/src/lib/__tests__/chat-send-budget.test.ts
+++ b/src/lib/__tests__/chat-send-budget.test.ts
@@ -5,9 +5,14 @@
* Plain chat, a group round (per model) and compare (both sides) all resolve
* their payload through this module, so the numbers below are the numbers that
* go over the wire. Every claim has its negative control: the cap is one
- * setting away from off, and a local backend has to come out byte-identical to
- * 2.6.5 or the whole thing is a regression for everyone who does not pay per
- * token.
+ * setting away from off.
+ *
+ * Seit 2.6.8 (Compact-Schritt 2) gilt die Deckelung auch lokal — aber an einem
+ * anderen Mass: ein bezahlter Anbieter wird auf die KOSTEN-Decke gekappt, ein
+ * lokaler nur auf sein eigenes Fenster. Die Zusicherung fuer lokale Modelle ist
+ * damit nicht mehr "nie", sondern "erst beim Ueberlauf": unter 92 Prozent des
+ * Fensters ist die Nutzlast Wort fuer Wort die von 2.6.7, darueber wird gekappt
+ * statt vom Modell stillschweigend vorne abgeschnitten.
*/
import { describe, it, expect } from 'vitest'
@@ -44,6 +49,10 @@ function historyOf(tokens: number): Wire[] {
const CLOUD_32K = { providerId: 'lu-cloud', modelWindow: 32768, contextDecay: true }
const CLOUD_262K = { providerId: 'lu-cloud', modelWindow: 262144, contextDecay: true }
const OLLAMA = { providerId: 'ollama', modelWindow: 262144, contextDecay: true }
+/** Ein lokales Modell mit einem Fenster, das eine lange Unterhaltung sprengt. */
+const OLLAMA_8K = { providerId: 'ollama', modelWindow: 8192, contextDecay: true }
+/** Die Grenze, ab der die A3-Hysterese auf einem lokalen Modell greift. */
+const TRIGGER_8K = Math.floor(Math.floor(8192 * 0.8) * 1.15)
describe('A4: a long chat costs budget level, not history level', () => {
it('a 50k-token history plus a short question sends at most the budget', () => {
@@ -93,22 +102,54 @@ describe('A4: a long chat costs budget level, not history level', () => {
})
})
-describe('A4: a local backend is byte-identical to 2.6.5', () => {
- it('hands the very same array through, unchanged', () => {
- const history = historyOf(120000)
+describe('2.6.8: ein lokales Modell wird gekappt — aber erst, wo es ueberlaeuft', () => {
+ // Die Zusicherung, die 2.6.7 universell galt und jetzt eine Grenze hat: was
+ // ins Fenster passt, geht unveraendert raus. Der Nutzer soll von diesem
+ // Umbau in einer normalen Unterhaltung nichts merken.
+ it('laesst eine Unterhaltung unter der Grenze Wort fuer Wort durch', () => {
+ const history = historyOf(2000)
history.push({
role: 'user',
content: 'look',
images: [{ data: 'A'.repeat(40000), mimeType: 'image/png' }],
})
+ expect(size(history)).toBeLessThan(TRIGGER_8K)
const before = JSON.stringify(history)
- const sent = applyChatSendBudget(history, OLLAMA)
- expect(sent.budget).toBeNull()
- expect(sent.messages).toBe(history)
+ const sent = applyChatSendBudget(history, OLLAMA_8K)
expect(JSON.stringify(sent.messages)).toBe(before)
expect(sent.droppedImages).toBe(0)
})
+ // Der eigentliche Befund C1: hier hat 2.6.7 das ganze Array rausgeschickt,
+ // und das Modell hat vorne abgeschnitten, ohne es zu sagen.
+ it('kappt eine Unterhaltung, die das Fenster sprengt', () => {
+ const history = historyOf(50000)
+ expect(size(history)).toBeGreaterThan(TRIGGER_8K)
+ const sent = applyChatSendBudget(history, OLLAMA_8K)
+ expect(sent.budget).toBe(Math.floor(8192 * 0.8))
+ expect(sent.promptTokens).toBeLessThanOrEqual(sent.budget!)
+ expect(sent.messages.length).toBeLessThan(history.length)
+ })
+
+ // Negativkontrolle in der Zeit: derselbe Fall war vor diesem Umbau
+ // ungekappt, und der Notaus stellt genau diesen Zustand wieder her.
+ it('der Notaus stellt das Verhalten von 2.6.7 wieder her', () => {
+ const history = historyOf(50000)
+ const sent = applyChatSendBudget(history, { ...OLLAMA_8K, contextDecay: false })
+ expect(sent.budget).toBeNull()
+ expect(sent.messages).toBe(history)
+ })
+
+ // Die Zahl, die der Modulkopf von chat-send-budget.ts behauptet: nicht bei
+ // 0,8 des Fensters, sondern bei 1,15 x 0,8 = 0,92 — der Rest ist der Platz,
+ // den die ANTWORT braucht.
+ it('die Grenze liegt bei 92 Prozent des Fensters, nicht bei 80', () => {
+ expect(TRIGGER_8K / 8192).toBeCloseTo(0.92, 2)
+ const knappDrunter = historyOf(TRIGGER_8K - 800)
+ expect(applyChatSendBudget(knappDrunter, OLLAMA_8K).messages.length)
+ .toBe(knappDrunter.length)
+ })
+
it('negative control: the same history on lu-cloud does shrink', () => {
const history = historyOf(120000)
expect(applyChatSendBudget(history, CLOUD_262K).messages.length).toBeLessThan(history.length)
@@ -118,14 +159,26 @@ describe('A4: a local backend is byte-identical to 2.6.5', () => {
expect(chatSendBudget({ providerId: 'lu-cloud', modelWindow: 0, contextDecay: true })).toBeNull()
})
- it('says so before the window is looked up, so no round trip is spent on it', () => {
- // Resolving a window is an /api/show call. Asking it for a payload that
- // cannot be capped would put a new request on the local path.
- expect(chatBudgetApplies('ollama', true)).toBe(false)
- expect(chatBudgetApplies('lm-studio', true)).toBe(false)
- expect(chatBudgetApplies('lu-cloud', false)).toBe(false)
- expect(chatBudgetApplies('lu-cloud', true)).toBe(true)
+ it('nur der Notaus schliesst das Tor — der Anbieter nicht mehr', () => {
+ // Bis 2.6.7 fragte das Tor `isPaidProvider`, also eine KOSTEN-Frage. Die
+ // entscheidet weiter die GROESSE der Decke, aber nicht mehr, ob ueberhaupt
+ // gekappt wird: ein uebergelaufenes Fenster ist kein Abrechnungsproblem.
+ expect(chatBudgetApplies('ollama', true)).toBe(true)
+ expect(chatBudgetApplies('lm-studio', true)).toBe(true)
expect(chatBudgetApplies('openai', undefined)).toBe(true)
+ expect(chatBudgetApplies('lu-cloud', true)).toBe(true)
+ // Der Notaus gilt fuer alle, lokal wie Cloud.
+ expect(chatBudgetApplies('lu-cloud', false)).toBe(false)
+ expect(chatBudgetApplies('ollama', false)).toBe(false)
+ })
+
+ it('die Kostendecke bleibt den bezahlten Anbietern vorbehalten', () => {
+ // Gleiches Fenster, zwei Anbieter: der bezahlte wird zusaetzlich auf
+ // codexSendWindowTokens gedeckelt, der lokale nur auf sein eigenes
+ // Fenster. Das ist der Unterschied, den `isPaidProvider` weiter macht.
+ expect(chatSendBudget({ providerId: 'ollama', modelWindow: 262144, contextDecay: true }))
+ .toBe(Math.floor(262144 * 0.8))
+ expect(chatSendBudget(CLOUD_262K)).toBe(DEFAULT_SEND_WINDOW_TOKENS)
})
})
@@ -138,9 +191,23 @@ describe('A4: a group round is budgeted per model per round', () => {
}
})
- it('a local member of the line-up keeps its 2.6.5 payload', () => {
+ it('ein lokales Mitglied wird an seinem eigenen Fenster gemessen', () => {
+ // Der gefaehrlichste Platz fuer ein kleines lokales Modell: es traegt
+ // dieselbe geteilte Historie wie das 262k-Modell neben ihm. Bis 2.6.7 ging
+ // sie ungekappt an beide.
const shared = historyOf(120000)
- expect(applyChatSendBudget(shared, OLLAMA).messages).toBe(shared)
+ const sent = applyChatSendBudget(shared, OLLAMA_8K)
+ expect(sent.budget).toBe(Math.floor(8192 * 0.8))
+ expect(sent.promptTokens).toBeLessThanOrEqual(sent.budget!)
+ // Und das grosse lokale Modell derselben Runde behaelt ein Vielfaches
+ // davon. Was seine Nutzlast begrenzt, ist nicht die neue Token-Decke
+ // (209715 waere sie), sondern MAX_SEND_MESSAGES — die aeltere Anzahl-Decke,
+ // die diese Historie mit ihren ~480 kurzen Zuegen schon vorher traf.
+ const gross = applyChatSendBudget(shared, OLLAMA)
+ expect(gross.promptTokens).toBeGreaterThan(sent.promptTokens * 10)
+ expect(gross.promptTokens).toBeLessThan(gross.budget!)
+ expect(gross.messages.length).toBeLessThanOrEqual(MAX_SEND_MESSAGES)
+ expect(gross.messages.length).toBeLessThan(shared.length)
})
it('negative control: uncapped, one round bills the full history N times', () => {
@@ -169,8 +236,14 @@ describe('A4: compare caps the shared base before the fan-out', () => {
expect(applySendBudget(history, budget).messages.length).toBe(sent.messages.length)
})
- it('two local models are not capped at all', () => {
- expect(sharedChatSendBudget([OLLAMA, OLLAMA])).toBeNull()
+ it('zwei lokale Modelle teilen sich das engere ihrer Fenster', () => {
+ // Beide Seiten muessen denselben Prompt sehen, sonst ist der Vergleich
+ // keiner — also gilt auch unter lokalen Modellen das kleinere Fenster.
+ expect(sharedChatSendBudget([OLLAMA, OLLAMA])).toBe(Math.floor(262144 * 0.8))
+ expect(sharedChatSendBudget([OLLAMA, OLLAMA_8K])).toBe(Math.floor(8192 * 0.8))
+ // Mit dem Notaus auf beiden Seiten bleibt es beim ungekappten Array.
+ const aus = [OLLAMA, OLLAMA_8K].map((m) => ({ ...m, contextDecay: false }))
+ expect(sharedChatSendBudget(aus)).toBeNull()
const history = historyOf(50000)
expect(applySendBudget(history, null).messages).toBe(history)
})
diff --git a/src/lib/__tests__/compact-display.test.ts b/src/lib/__tests__/compact-display.test.ts
new file mode 100644
index 00000000..8bc1934e
--- /dev/null
+++ b/src/lib/__tests__/compact-display.test.ts
@@ -0,0 +1,231 @@
+/**
+ * Sperrklinken fuer die ANZEIGE-Haelfte der Zusammenfassung (compact-summary.ts,
+ * unterer Block).
+ *
+ * Diese Funktionen stehen zwischen einem gespeicherten Datensatz und dem, was
+ * der Nutzer im Verlauf zu sehen bekommt. Sie duerfen an genau einer Stelle
+ * streng sein — beim Wegschneiden unserer EIGENEN Verpackung — und sonst
+ * nirgends: ein Datensatz kann aus einer aelteren Fassung stammen, in der die
+ * Marker fehlten oder die Vorrede anders lautete. Jede Strenge, die dann
+ * zuschlaegt, verschluckt eine alte Zusammenfassung ganz, statt sie einfach
+ * etwas roher zu zeigen. Deshalb pruefen die Tests hier vor allem, was bei
+ * Eingaben passiert, die NICHT frisch aus renderCompactSummary kommen.
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ compactSummaryBody,
+ summarySections,
+ compactionAnchors,
+ renderCompactSummary,
+ SECTIONS,
+ COMPACT_OPEN,
+ COMPACT_CLOSE,
+ COMPACT_PREAMBLE,
+ EMPTY_SUMMARY,
+ type CompactSummary,
+ type StoredCompaction,
+} from '../compact-summary'
+
+const voll: CompactSummary = {
+ task: 'Den Fehler im Login beheben.',
+ // Woertlich, mit Anfuehrungszeichen: genau so soll dieser Abschnitt
+ // aussehen — die Worte des Nutzers, nicht ihre Nacherzaehlung.
+ requests: '"mach den login fix aber ohne refactoring"',
+ progress: 'auth.ts gelesen, den Nullwert in Zeile 40 gefunden.',
+ decisions: 'Kein Refactoring, nur der Nullwert.',
+ facts: 'src/auth.ts:40, Funktion verifyToken.',
+ open: 'Der Test dafuer fehlt noch.',
+ rest: '',
+}
+
+describe('compactSummaryBody — die eigene Verpackung wieder abnehmen', () => {
+ it('nimmt Marker und Vorrede weg und laesst den Abschnittstext Zeichen fuer Zeichen stehen', () => {
+ const gerendert = renderCompactSummary(voll)
+ const body = compactSummaryBody(gerendert)
+
+ expect(body).not.toContain(COMPACT_OPEN)
+ expect(body).not.toContain(COMPACT_CLOSE)
+ expect(body).not.toContain(COMPACT_PREAMBLE)
+ // Der Grund, warum die Vorrede eine Konstante ist: sie wird auf einer Seite
+ // geschrieben und auf der anderen wieder abgezogen. Stuende sie zweimal als
+ // Text da, zeigte die Anzeige sie nach dem naechsten Umformulieren still
+ // als Inhalt an.
+ expect(body).not.toContain('Earlier turns in this conversation')
+
+ // Aus SECTIONS abgeleitet, nicht von Hand hingeschrieben: die Liste der
+ // Ueberschriften wuchs am 02.09.2026 um USER REQUESTS, und eine hier
+ // eingetippte Reihenfolge waere in dem Moment zu einer Behauptung ueber
+ // einen Aufbau geworden, den es nicht mehr gibt.
+ expect(body).toBe(
+ SECTIONS.map((sec) => `${sec.heading}\n${voll[sec.key]}`).join('\n\n'),
+ )
+ // Und woertlich heisst woertlich — Anfuehrungszeichen und Kleinschreibung
+ // der Nutzernachricht stehen unveraendert da.
+ expect(body).toContain('"mach den login fix aber ohne refactoring"')
+ expect(body).toContain('src/auth.ts:40')
+ })
+
+ it('gibt einen Datensatz ganz ohne Marker unveraendert zurueck', () => {
+ // Ein alter gespeicherter Eintrag kann aus einer Fassung ohne Marker
+ // stammen. Wer hier auf den Marker besteht, zeigt dem Nutzer statt der
+ // alten Zusammenfassung gar nichts — der Datensatz ist dann verloren,
+ // obwohl er vollstaendig da liegt.
+ expect(compactSummaryBody('TASK\nA')).toBe('TASK\nA')
+ expect(compactSummaryBody('einfach nur Prosa vom Modell')).toBe('einfach nur Prosa vom Modell')
+ })
+
+ it('laesst eine fremde Vorrede stehen, statt sie blind wegzuschneiden', () => {
+ // Abgezogen wird nur der Satz, den wir selbst geschrieben haben. Eine
+ // andere erste Zeile ist Inhalt und bleibt Inhalt: lieber eine Zeile zu
+ // viel anzeigen als den ersten Satz einer alten Zusammenfassung stumm zu
+ // verlieren.
+ const alt = `${COMPACT_OPEN}\nEine aeltere Vorrede stand hier.\n\nTASK\nA\n${COMPACT_CLOSE}`
+ const body = compactSummaryBody(alt)
+ expect(body).toBe('Eine aeltere Vorrede stand hier.\n\nTASK\nA')
+ })
+
+ it('macht aus leerer und aus reiner Leerraum-Eingabe eine leere Zeichenkette', () => {
+ expect(compactSummaryBody('')).toBe('')
+ expect(compactSummaryBody(' \n \n')).toBe('')
+ expect(compactSummaryBody(undefined as unknown as string)).toBe('')
+ })
+
+ it('schneidet weg, was vor dem oeffnenden und hinter dem schliessenden Marker steht', () => {
+ // Die Zusammenfassung reitet auf Nutzermaterial, also steht neben ihr im
+ // selben Text noch die echte Nachricht. Angezeigt werden darf nur der
+ // Block zwischen den Markern.
+ const traeger = `davor\n${renderCompactSummary(voll)}\ndanach`
+ const body = compactSummaryBody(traeger)
+ expect(body).not.toContain('davor')
+ expect(body).not.toContain('danach')
+ expect(body.startsWith('TASK')).toBe(true)
+ })
+})
+
+describe('summarySections — die Abschnitte, wie die Anzeige sie braucht', () => {
+ it('gibt nach dem vollen Rundlauf jede Ueberschrift in der Reihenfolge der Leiter zurueck', () => {
+ const abschnitte = summarySections(renderCompactSummary(voll))
+ expect(abschnitte.map((a) => a.heading)).toEqual(SECTIONS.map((s) => s.heading))
+ for (const sec of SECTIONS) {
+ const treffer = abschnitte.find((a) => a.heading === sec.heading)
+ expect(treffer?.body).toBe(voll[sec.key])
+ }
+ })
+
+ it('laesst leere Abschnitte ganz weg, statt eine Ueberschrift ohne Text zu zeigen', () => {
+ const halb: CompactSummary = {
+ ...EMPTY_SUMMARY,
+ task: 'Den Login reparieren.',
+ requests: '', decisions: 'Kein Refactoring.',
+ open: 'Der Test fehlt.',
+ }
+ const abschnitte = summarySections(renderCompactSummary(halb))
+ expect(abschnitte).toEqual([
+ { heading: 'TASK', body: 'Den Login reparieren.' },
+ { heading: 'DECISIONS', body: 'Kein Refactoring.' },
+ { heading: 'OPEN', body: 'Der Test fehlt.' },
+ ])
+ expect(abschnitte.some((a) => a.heading === 'PROGRESS')).toBe(false)
+ expect(abschnitte.some((a) => a.heading === 'FACTS')).toBe(false)
+ })
+
+ it('zeigt bei reinem losen Text kein NOTES als erste Zeile', () => {
+ // NOTES ist unser eigenes Wort, nicht das des Modells: der Aufbau schreibt
+ // es als Ueberschrift, aber es steht nicht in SECTIONS. Steht es im Text
+ // der Anzeige, sieht es aus wie ein Formatfehler des Modells, obwohl wir
+ // es selbst hingeschrieben haben.
+ const nurRest: CompactSummary = { ...EMPTY_SUMMARY, rest: 'Der Build ist rot, sonst nichts.' }
+ const abschnitte = summarySections(renderCompactSummary(nurRest))
+
+ expect(abschnitte).toEqual([{ heading: 'NOTES', body: 'Der Build ist rot, sonst nichts.' }])
+ for (const a of abschnitte) expect(a.body.split('\n')[0].trim()).not.toBe('NOTES')
+ })
+
+ it('zeigt auch neben benannten Abschnitten kein NOTES als erste Zeile — und verliert den losen Text nicht', () => {
+ const gemischt: CompactSummary = {
+ ...EMPTY_SUMMARY,
+ task: 'Den Login reparieren.',
+ requests: '', open: 'Der Test fehlt.',
+ rest: 'Nebenbei: der Build ist rot.',
+ }
+ const abschnitte = summarySections(renderCompactSummary(gemischt))
+
+ for (const a of abschnitte) expect(a.body.split('\n')[0].trim()).not.toBe('NOTES')
+ // Der lose Text ist der Teil, den das Modell unter keine Ueberschrift
+ // gebracht hat. Genau der darf auf dem Weg in die Anzeige nicht
+ // verschwinden — sonst faellt weg, was am wenigsten vorhersehbar war.
+ expect(abschnitte.map((a) => a.body).join('\n')).toContain('Nebenbei: der Build ist rot.')
+ expect(abschnitte.some((a) => a.heading === 'TASK' && a.body === 'Den Login reparieren.')).toBe(true)
+ })
+
+ it('schneidet eine allein stehende NOTES-Zeile aus einem alten Datensatz heraus', () => {
+ // Ein gespeicherter Eintrag, der mit der NOTES-Ueberschrift beginnt, ohne
+ // dass eine benannte Ueberschrift davor steht. Der Parser kennt NOTES
+ // nicht, das Wort landet also im Rest — hier wird es weggeschnitten, damit
+ // die Anzeige nicht "NOTES" ueber dem Text NOTES stehen hat.
+ const alt = `${COMPACT_OPEN}\n${COMPACT_PREAMBLE}\n\nNOTES\nDer Build ist rot.\n${COMPACT_CLOSE}`
+ expect(summarySections(alt)).toEqual([{ heading: 'NOTES', body: 'Der Build ist rot.' }])
+ })
+
+ it('gibt bei unlesbarer Eingabe eine leere Liste zurueck, damit die Komponente ihren Rueckfall zeigt', () => {
+ expect(summarySections('')).toEqual([])
+ expect(summarySections(' \n\n ')).toEqual([])
+ expect(summarySections(`${COMPACT_OPEN}\n${COMPACT_PREAMBLE}\n${COMPACT_CLOSE}`)).toEqual([])
+ expect(summarySections(renderCompactSummary(EMPTY_SUMMARY))).toEqual([])
+ })
+})
+
+describe('compactionAnchors — an welcher sichtbaren Zeile die Linie haengt', () => {
+ const m = (id: string, role = 'user') => ({ id, role })
+ const alle = [m('m1'), m('m2', 'assistant'), m('sys1', 'system'), m('m3'), m('m4', 'assistant')]
+ const sichtbar = ['m1', 'm2', 'm3', 'm4']
+ const satz = (summary: string, upToMessageId: string): StoredCompaction => ({ summary, upToMessageId })
+
+ it('haengt die Linie an die letzte SICHTBARE Nachricht, wenn der Schnittpunkt unsichtbar ist', () => {
+ // Fall 1. Der Schnitt kann auf einer Systemnachricht liegen, die der
+ // Verlauf wegfiltert. Ohne diesen Rueckwaertsgang faende die Anzeige gar
+ // keine Zeile und zeigte die Verdichtung gar nicht an — obwohl sie
+ // stattgefunden hat.
+ const karte = compactionAnchors(alle, sichtbar, [satz('S', 'sys1')])
+ expect([...karte.keys()]).toEqual(['m2'])
+ expect(karte.get('m2')?.map((r) => r.summary)).toEqual(['S'])
+ })
+
+ it('haengt die Linie an den Schnittpunkt selbst, wenn der sichtbar ist', () => {
+ const karte = compactionAnchors(alle, sichtbar, [satz('S', 'm3')])
+ expect([...karte.keys()]).toEqual(['m3'])
+ })
+
+ it('ueberspringt einen Datensatz, dessen Schnittpunkt geloescht ist', () => {
+ // Fall 2. Ein Ersatzanker oben oder unten waere schlimmer als keine Linie:
+ // eine Linie an der falschen Stelle behauptet ueber den Verlauf etwas, was
+ // nicht stimmt — naemlich dass ab HIER die Zusammenfassung gilt.
+ const karte = compactionAnchors(alle, sichtbar, [satz('S', 'laengst-geloescht')])
+ expect(karte.size).toBe(0)
+ expect(karte.has('m1')).toBe(false)
+ expect(karte.has('m4')).toBe(false)
+ })
+
+ it('ueberspringt auch einen Datensatz, vor dem ueberhaupt nichts Sichtbares liegt', () => {
+ const nurSystemVorne = [m('sys0', 'system'), m('sys1', 'system'), m('m3')]
+ const karte = compactionAnchors(nurSystemVorne, ['m3'], [satz('S', 'sys1')])
+ expect(karte.size).toBe(0)
+ })
+
+ it('gibt bei zwei Datensaetzen auf derselben Zeile BEIDE zurueck, in ihrer Reihenfolge', () => {
+ // Fall 3. Nur den letzten zu zeigen verschwiege genau die Information, um
+ // die es geht: dass zweimal verdichtet wurde.
+ const karte = compactionAnchors(alle, sichtbar, [satz('erste', 'm2'), satz('zweite', 'sys1')])
+ const liste = karte.get('m2')
+ expect(liste).toHaveLength(2)
+ expect(liste?.map((r) => r.summary)).toEqual(['erste', 'zweite'])
+ expect(karte.size).toBe(1)
+ })
+
+ it('gibt eine leere Karte zurueck, wenn es nichts zu verankern gibt', () => {
+ expect(compactionAnchors(alle, sichtbar, undefined).size).toBe(0)
+ expect(compactionAnchors(alle, sichtbar, []).size).toBe(0)
+ expect(compactionAnchors(alle, [], [satz('S', 'm1')]).size).toBe(0)
+ expect(compactionAnchors([], sichtbar, [satz('S', 'm1')]).size).toBe(0)
+ })
+})
diff --git a/src/lib/__tests__/compact-run.test.ts b/src/lib/__tests__/compact-run.test.ts
new file mode 100644
index 00000000..40f0f075
--- /dev/null
+++ b/src/lib/__tests__/compact-run.test.ts
@@ -0,0 +1,203 @@
+/**
+ * Sperrklinken fuer den Modellaufruf des Zusammenfassers (2.6.8, Schritt 3b).
+ *
+ * Jede Pruefung hier haelt genau EINEN der sechs Fallstricke fest, die der
+ * Modulkopf von compact-run.ts benennt. Sie sind keine Vermutungen: jeder
+ * einzelne ist in diesem Projekt schon einmal echtes Verhalten gewesen, an
+ * einer anderen Aufrufstelle. Ohne diese Datei wandern sie in die naechste.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../../api/providers', () => ({
+ getProviderForModel: vi.fn(),
+ getProviderIdFromModel: vi.fn(),
+}))
+vi.mock('../agent-num-ctx', () => ({
+ resolveAgentNumCtx: vi.fn(),
+}))
+
+import { runCompactSummary, COMPACT_TEMPERATURE, COMPACT_MAX_TOKENS } from '../compact-run'
+import { getProviderForModel, getProviderIdFromModel } from '../../api/providers'
+import { resolveAgentNumCtx } from '../agent-num-ctx'
+import { COMPACT_OPEN, renderCompactSummary } from '../compact-summary'
+
+const providerFor = getProviderForModel as unknown as ReturnType<typeof vi.fn>
+const providerId = getProviderIdFromModel as unknown as ReturnType<typeof vi.fn>
+const numCtx = resolveAgentNumCtx as unknown as ReturnType<typeof vi.fn>
+
+/** Was der falsche Anbieter beim naechsten Aufruf zurueckgibt. */
+let antwort: string | (() => never)
+let verzoegerungMs: number
+/** Womit chatStream tatsaechlich gerufen wurde. */
+let gesehen: { model: string; messages: unknown[]; options: Record<string, unknown> } | null
+
+const GUT = `TASK
+Den Login reparieren.
+
+PROGRESS
+auth.ts gelesen, Nullwert in Zeile 40 gefunden.
+
+DECISIONS
+Kein Refactoring — der Rest ist getestet.
+
+FACTS
+src/auth.ts:40, verifyToken, "cannot read exp of undefined".
+
+OPEN
+Der Test fehlt.`
+
+const verlauf = Array.from({ length: 24 }, (_, i) => ({
+ role: i % 2 ? 'assistant' : 'user',
+ content: `Zug ${i}: ` + 'Inhalt '.repeat(60),
+}))
+
+describe('runCompactSummary', () => {
+ beforeEach(() => {
+ antwort = GUT
+ verzoegerungMs = 0
+ gesehen = null
+ providerId.mockReset(); providerId.mockReturnValue('ollama')
+ numCtx.mockReset(); numCtx.mockResolvedValue(32768)
+ providerFor.mockReset()
+ providerFor.mockImplementation((name: string) => ({
+ modelId: name.includes('::') ? name.split('::').slice(1).join('::') : name,
+ provider: {
+ chatStream: async function* (model: string, messages: unknown[], options: Record<string, unknown>) {
+ gesehen = { model, messages, options }
+ if (typeof antwort === 'function') antwort()
+ if (verzoegerungMs) await new Promise((r) => setTimeout(r, verzoegerungMs))
+ yield { content: antwort as string, done: false }
+ yield { content: '', done: true }
+ },
+ },
+ }))
+ })
+
+ it('liefert die gelesene Zusammenfassung', async () => {
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b' })
+ expect(r.ok).toBe(true)
+ expect(r.reason).toBe('ok')
+ expect(r.summary.facts).toContain('verifyToken')
+ expect(renderCompactSummary(r.summary)).toContain(COMPACT_OPEN)
+ })
+
+ // Falle 6 — und zugleich der Grund, warum das auf allen drei
+ // Werkzeug-Schemata identisch laeuft.
+ it('schickt NIE Werkzeuge mit', async () => {
+ await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b' })
+ expect(gesehen!.options.tools).toBeUndefined()
+ })
+
+ // Der Prompt ist eine einzige Nutzernachricht — keine Systemnachricht, an
+ // der eine strenge Chat-Vorlage abbrechen koennte.
+ it('sendet genau eine Nutzernachricht', async () => {
+ await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b' })
+ expect(gesehen!.messages).toHaveLength(1)
+ expect((gesehen!.messages[0] as { role: string }).role).toBe('user')
+ })
+
+ // Falle 4: ohne num_ctx wirft Ollama die KV-Belegung des Chats weg und
+ // laedt das Modell neu — gemessen an der ausgelieferten exe.
+ it('reicht dasselbe num_ctx durch wie der Chat', async () => {
+ await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b', contextWindowOverride: 0 })
+ expect(numCtx).toHaveBeenCalled()
+ expect(gesehen!.options.contextWindow).toBe(32768)
+ })
+
+ it('laeuft weiter, wenn die num_ctx-Aufloesung scheitert', async () => {
+ numCtx.mockRejectedValue(new Error('ollama weg'))
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b' })
+ expect(r.ok).toBe(true)
+ expect(gesehen!.options.contextWindow).toBeUndefined()
+ })
+
+ // Falle 5: mit `{}` als Optionen sieht der Abbruch die laufende Anfrage nie.
+ it('reicht ein Abbruchsignal durch', async () => {
+ await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b' })
+ expect(gesehen!.options.signal).toBeDefined()
+ })
+
+ it('nimmt die Sampling-Werte des Zusammenfassers, nicht die des Chats', async () => {
+ await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b' })
+ expect(gesehen!.options.temperature).toBe(COMPACT_TEMPERATURE)
+ expect(gesehen!.options.maxTokens).toBe(COMPACT_MAX_TOKENS)
+ })
+
+ // Falle 2: Qwen3 oeffnet <think> schon im PROMPT, die Antwort traegt also
+ // nur den SCHLIESSENDEN Tag. Ein naiver Stripper findet daran nichts.
+ it('entfernt Denktext ohne oeffnenden Tag', async () => {
+ antwort = `Ich sollte kurz ueberlegen, was hier wichtig ist.</think>\n\n${GUT}`
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b' })
+ expect(r.ok).toBe(true)
+ const alles = JSON.stringify(r.summary)
+ expect(alles).not.toContain('sollte kurz ueberlegen')
+ expect(alles).not.toContain('</think>')
+ expect(r.summary.facts).toContain('verifyToken')
+ })
+
+ it('entfernt auch einen vollstaendigen Denkblock', async () => {
+ antwort = `<think>lang und breit</think>\n${GUT}`
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'qwen:4b' })
+ expect(JSON.stringify(r.summary)).not.toContain('lang und breit')
+ })
+
+ describe('scheitert nie mit einer Ausnahme', () => {
+ it('ohne Modell', async () => {
+ const r = await runCompactSummary({ turns: verlauf, activeModel: '' })
+ expect(r).toMatchObject({ ok: false, reason: 'no-model' })
+ })
+
+ it('ohne Inhalt', async () => {
+ const r = await runCompactSummary({ turns: [{ role: 'user', content: ' ' }], activeModel: 'q' })
+ expect(r).toMatchObject({ ok: false, reason: 'empty-input' })
+ })
+
+ it('wenn der Anbieter wirft', async () => {
+ antwort = () => { throw new Error('backend tot') }
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'q' })
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('call-failed')
+ expect(r.detail).toContain('backend tot')
+ })
+
+ it('wenn die Antwort leer ist', async () => {
+ antwort = ' '
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'q' })
+ expect(r).toMatchObject({ ok: false, reason: 'unusable' })
+ })
+
+ // Falle 1: das eigene Zeitlimit. Der Waechter des Anbieters misst STILLE
+ // zwischen Bruchstuecken, nicht die Gesamtzeit.
+ it('wenn die Zeit ablaeuft', async () => {
+ verzoegerungMs = 60
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'q', timeoutMs: 10 })
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('call-failed')
+ })
+
+ it('wenn der Nutzer vorher abbricht', async () => {
+ const ac = new AbortController(); ac.abort()
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'q', signal: ac.signal })
+ expect(r).toMatchObject({ ok: false, reason: 'aborted' })
+ })
+ })
+
+ describe('die Brauchbarkeit entscheidet, nicht die Hoeflichkeit', () => {
+ it('lehnt eine Abschrift ab', async () => {
+ antwort = 'PROGRESS\n' + verlauf.map((t) => t.content).join('\n')
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'q' })
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('unusable')
+ expect(r.usability?.reason).toBe('not-smaller')
+ })
+
+ // Der Rueckfall, der den Sinn dieses Moduls traegt: ein Modell, das die
+ // Ueberschriften ignoriert, hat trotzdem etwas Brauchbares gesagt.
+ it('nimmt eine Antwort ganz ohne Ueberschriften an', async () => {
+ antwort = 'Der Nutzer wollte den Login reparieren. In src/auth.ts Zeile 40 steht ein Nullwert in verifyToken. Ein Test dafuer fehlt noch, sonst ist alles gruen.'
+ const r = await runCompactSummary({ turns: verlauf, activeModel: 'q' })
+ expect(r.ok).toBe(true)
+ expect(r.summary.rest).toContain('verifyToken')
+ })
+ })
+})
diff --git a/src/lib/__tests__/compact-summary.test.ts b/src/lib/__tests__/compact-summary.test.ts
new file mode 100644
index 00000000..fd57c3cd
--- /dev/null
+++ b/src/lib/__tests__/compact-summary.test.ts
@@ -0,0 +1,560 @@
+/**
+ * Sperrklinken fuer die geschriebene Zusammenfassung (2.6.8, Compact-Schritt 3).
+ *
+ * Die Leitfrage jeder Pruefung hier ist dieselbe: was passiert, wenn das Modell
+ * NICHT tut, was der Prompt verlangt? Dieses Modul wird von 4B-Modellen auf dem
+ * hermes_xml- und dem template_fix-Pfad bedient — also von genau den Modellen,
+ * deren Unzuverlaessigkeit der Grund fuer die Existenz dieser Pfade ist. Ein
+ * Parser, der nur die brave Antwort versteht, waere hier nutzlos.
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ buildCompactPrompt,
+ parseCompactSummary,
+ summaryFromLooseText,
+ renderCompactSummary,
+ stripCompactSummary,
+ hasCompactSummary,
+ isEmptySummary,
+ isUsableSummary,
+ renderTranscript,
+ summaryTokens,
+ applyCompactSummary,
+ SECTIONS,
+ COMPACT_OPEN,
+ COMPACT_CLOSE,
+ MAX_SUMMARY_SHARE,
+ MIN_SUMMARY_CHARS,
+ EMPTY_SUMMARY,
+ type CompactSummary,
+ minimalSummaryChars,
+ summaryCouldEverFit,
+ COMPACT_PREAMBLE,
+ REST_HEADING,
+ summarySections,
+ compactSummaryBody,
+} from '../compact-summary'
+
+const brav = `TASK
+Den Fehler im Login beheben.
+
+PROGRESS
+auth.ts gelesen, den Nullwert in Zeile 40 gefunden.
+
+DECISIONS
+Kein Refactoring, nur der Nullwert — der Rest ist getestet.
+
+FACTS
+src/auth.ts:40, Funktion verifyToken, Fehler "cannot read exp of undefined".
+
+OPEN
+Der Test dafuer fehlt noch.`
+
+const summe = (s: CompactSummary) =>
+ SECTIONS.map((sec) => s[sec.key]).join('') + s.rest
+
+describe('der Prompt', () => {
+ it('ist eine einzige Nutzernachricht ohne Systemanteil', () => {
+ const p = buildCompactPrompt([{ role: 'user', content: 'hallo' }])
+ // Der Grund steht im Modulkopf: ein Systemanteil an falscher Stelle ist
+ // genau das, woran strenge Chat-Vorlagen abbrechen.
+ expect(p).not.toMatch(/^system:/im)
+ expect(p).toContain('--- TRANSCRIPT ---')
+ })
+
+ it('verlangt alle fuenf Abschnitte', () => {
+ const p = buildCompactPrompt([{ role: 'user', content: 'x' }])
+ for (const sec of SECTIONS) expect(p).toContain(sec.heading)
+ })
+
+ it('nimmt einen Fokus auf, ohne die Abschnitte fallen zu lassen', () => {
+ const p = buildCompactPrompt([{ role: 'user', content: 'x' }], { focus: 'die Datenbank' })
+ expect(p).toContain('die Datenbank')
+ for (const sec of SECTIONS) expect(p).toContain(sec.heading)
+ })
+
+ it('traegt den Verlauf, gekappt auf das Zeichenbudget', () => {
+ const turns = Array.from({ length: 200 }, (_, i) => ({
+ role: 'user', content: `Zug ${i} ` + 'x'.repeat(500),
+ }))
+ const p = buildCompactPrompt(turns, { maxTranscriptChars: 4000 })
+ expect(p.length).toBeLessThan(9000)
+ })
+})
+
+describe('der Verlauf wird an beiden Enden erhalten', () => {
+ // Kopf-und-Fuss statt nur Kopf: die letzten Zuege vor dem Schnitt sind die,
+ // auf denen das Gespraech gerade steht.
+ it('behaelt Anfang UND Ende, wenn gekappt wird', () => {
+ const turns = [
+ { role: 'user', content: 'ERSTER ' + 'a'.repeat(3000) },
+ { role: 'user', content: 'b'.repeat(3000) },
+ { role: 'user', content: 'c'.repeat(3000) + ' LETZTER' },
+ ]
+ const t = renderTranscript(turns, 2000)
+ expect(t).toContain('ERSTER')
+ expect(t).toContain('LETZTER')
+ expect(t).toContain('omitted')
+ })
+
+ it('laesst einen kurzen Verlauf unangetastet', () => {
+ const t = renderTranscript([{ role: 'user', content: 'kurz' }], 2000)
+ expect(t).toBe('user: kurz')
+ })
+
+ it('ueberspringt leere Zuege', () => {
+ const t = renderTranscript([
+ { role: 'user', content: 'a' }, { role: 'assistant', content: ' ' },
+ ])
+ expect(t).toBe('user: a')
+ })
+})
+
+describe('der Parser versteht die brave Antwort', () => {
+ it('trennt alle fuenf Abschnitte', () => {
+ const s = parseCompactSummary(brav)
+ expect(s.task).toContain('Login')
+ expect(s.progress).toContain('auth.ts')
+ expect(s.decisions).toContain('Refactoring')
+ expect(s.facts).toContain('verifyToken')
+ expect(s.open).toContain('Test')
+ expect(s.rest).toBe('')
+ })
+
+ it('behaelt Bezeichner Zeichen fuer Zeichen', () => {
+ const s = parseCompactSummary(brav)
+ expect(s.facts).toContain('src/auth.ts:40')
+ expect(s.facts).toContain('cannot read exp of undefined')
+ })
+})
+
+describe('der Parser versteht die schlampige Antwort', () => {
+ it('nimmt Rauten, Sterne, Doppelpunkte und Kleinschreibung', () => {
+ const s = parseCompactSummary(
+ '## Task:\nA\n\n**PROGRESS**\nB\n\n- decisions -\nC\n\n__Facts:__\nD\n\nopen\nE',
+ )
+ expect(s.task).toBe('A')
+ expect(s.progress).toBe('B')
+ expect(s.facts).toBe('D')
+ expect(s.open).toBe('E')
+ })
+
+ it('wirft nichts weg, was vor der ersten Ueberschrift steht', () => {
+ const s = parseCompactSummary('Hier meine Zusammenfassung:\n\nTASK\nA')
+ expect(s.task).toBe('A')
+ expect(s.rest).toContain('Hier meine Zusammenfassung')
+ })
+
+ it('behaelt eine Antwort ganz ohne Ueberschriften', () => {
+ const roh = 'Der Nutzer wollte den Login reparieren, wir haben auth.ts gelesen.'
+ const s = parseCompactSummary(roh)
+ expect(summe(s)).toContain('auth.ts')
+ expect(s.rest).toBe(roh)
+ })
+
+ it('wirft "none" weg statt es zu bezahlen', () => {
+ const s = parseCompactSummary('TASK\nA\n\nDECISIONS\nnone\n\nOPEN\nNone.')
+ expect(s.task).toBe('A')
+ expect(s.decisions).toBe('')
+ expect(s.open).toBe('')
+ })
+
+ it('haelt eine leere Antwort aus', () => {
+ expect(parseCompactSummary('')).toEqual(EMPTY_SUMMARY)
+ expect(isEmptySummary(parseCompactSummary(' '))).toBe(true)
+ })
+
+ it('summaryFromLooseText ist der ausdrueckliche Rueckfall', () => {
+ const s = summaryFromLooseText('irgendein Text')
+ expect(s.rest).toBe('irgendein Text')
+ expect(isEmptySummary(s)).toBe(false)
+ })
+})
+
+describe('das Rendern', () => {
+ it('laesst leere Abschnitte weg', () => {
+ const t = renderCompactSummary({ ...EMPTY_SUMMARY, task: 'A' })
+ expect(t).toContain('TASK')
+ expect(t).not.toContain('PROGRESS')
+ })
+
+ it('rahmt die Zusammenfassung ein, damit sie wiederfindbar ist', () => {
+ const t = renderCompactSummary(parseCompactSummary(brav))
+ expect(t.startsWith(COMPACT_OPEN)).toBe(true)
+ expect(t.trimEnd().endsWith(COMPACT_CLOSE)).toBe(true)
+ expect(hasCompactSummary(t)).toBe(true)
+ })
+
+ it('rendert gar nichts, wenn es nichts zu rendern gibt', () => {
+ expect(renderCompactSummary(EMPTY_SUMMARY)).toBe('')
+ expect(summaryTokens(EMPTY_SUMMARY)).toBe(0)
+ })
+
+ it('behaelt losen Text als eigenen Abschnitt', () => {
+ const t = renderCompactSummary({ ...EMPTY_SUMMARY, task: 'A', requests: '', rest: 'Nebenbei: B' })
+ expect(t).toContain('NOTES')
+ expect(t).toContain('Nebenbei: B')
+ })
+})
+
+describe('Zusammenfassungen stapeln sich nicht', () => {
+ // Der Grund im Modulkopf: sonst faltet jede Kuerzung die vorige in sich und
+ // die Genauigkeit faellt geometrisch — dieselbe Form wie beim Stapeln der
+ // alten Trim-Notiz.
+ it('entfernt eine frueher eingebettete Zusammenfassung', () => {
+ const alt = renderCompactSummary(parseCompactSummary(brav))
+ const traeger = `${alt}\n\nUnd jetzt bitte weiter mit Teil 2.`
+ const sauber = stripCompactSummary(traeger)
+ expect(sauber).toBe('Und jetzt bitte weiter mit Teil 2.')
+ expect(hasCompactSummary(sauber)).toBe(false)
+ })
+
+ it('entfernt auch mehrere', () => {
+ const a = renderCompactSummary({ ...EMPTY_SUMMARY, task: 'A' })
+ const b = renderCompactSummary({ ...EMPTY_SUMMARY, task: 'B' })
+ expect(stripCompactSummary(`${a}\nX\n${b}\nY`)).toBe('X\n\nY'.replace('\n\n', '\n'))
+ })
+
+ it('laesst Text ohne Zusammenfassung in Ruhe', () => {
+ expect(stripCompactSummary('nur Text')).toBe('nur Text')
+ })
+
+ it('der Verlauf fuer den Zusammenfasser traegt keine alte Zusammenfassung', () => {
+ const alt = renderCompactSummary(parseCompactSummary(brav))
+ const t = renderTranscript([{ role: 'user', content: `${alt}\n\nweiter` }])
+ expect(t).not.toContain(COMPACT_OPEN)
+ expect(t).toContain('weiter')
+ })
+})
+
+describe('die Brauchbarkeitspruefung — der Rueckfall auf die mechanische Kuerzung', () => {
+ it('nimmt eine echte Zusammenfassung an', () => {
+ const r = isUsableSummary({ summary: parseCompactSummary(brav), replacedChars: 50000 })
+ expect(r.usable).toBe(true)
+ expect(r.reason).toBe('ok')
+ })
+
+ it('lehnt eine leere ab', () => {
+ expect(isUsableSummary({ summary: EMPTY_SUMMARY, replacedChars: 50000 }).reason).toBe('empty')
+ })
+
+ it('lehnt eine zu kurze ab', () => {
+ // Gemessen werden die eigenen Worte, nicht die Verpackung: die feste
+ // Vorrede der gerenderten Form ist allein schon laenger als der Boden.
+ const r = isUsableSummary({ summary: { ...EMPTY_SUMMARY, task: 'ok' }, replacedChars: 50000 })
+ expect(r.reason).toBe('too-short')
+ expect(r.contentChars).toBeLessThan(MIN_SUMMARY_CHARS)
+ expect(r.renderedChars).toBeGreaterThan(MIN_SUMMARY_CHARS)
+ })
+
+ // Der teuerste Fehlerfall: das Modell "fasst zusammen", indem es abschreibt.
+ it('lehnt eine ab, die kaum kleiner ist als ihre Quelle', () => {
+ const abschrift = { ...EMPTY_SUMMARY, progress: 'x'.repeat(6000) }
+ const r = isUsableSummary({ summary: abschrift, replacedChars: 8000 })
+ expect(r.usable).toBe(false)
+ expect(r.reason).toBe('not-smaller')
+ })
+
+ it('die Grenze liegt bei der Haelfte', () => {
+ const quelle = 10000
+ const knappDrunter = { ...EMPTY_SUMMARY, progress: 'x'.repeat(quelle * MAX_SUMMARY_SHARE - 400) }
+ expect(isUsableSummary({ summary: knappDrunter, replacedChars: quelle }).usable).toBe(true)
+ const knappDrueber = { ...EMPTY_SUMMARY, progress: 'x'.repeat(quelle * MAX_SUMMARY_SHARE + 400) }
+ expect(isUsableSummary({ summary: knappDrueber, replacedChars: quelle }).usable).toBe(false)
+ })
+
+ it('ohne bekannte Quellgroesse entscheidet nur der Inhalt', () => {
+ expect(isUsableSummary({ summary: parseCompactSummary(brav), replacedChars: 0 }).usable).toBe(true)
+ })
+})
+
+describe('das Anwenden — wo die Zusammenfassung landen darf', () => {
+ const w = (role: string, content: string) => ({ role, content })
+ const zus = parseCompactSummary(brav)
+ const lang = () => [
+ w('system', 'sei hilfreich'),
+ ...Array.from({ length: 30 }, (_, i) => w(i % 2 ? 'assistant' : 'user', `zug ${i}`)),
+ ]
+
+ it('setzt die Zusammenfassung vor das behaltene Fenster', () => {
+ const r = applyCompactSummary({ messages: lang(), keepRecent: 6, summary: zus })
+ expect(r.replaced).toBe(24)
+ expect(r.rendered).toContain(COMPACT_OPEN)
+ expect(r.messages.length).toBeLessThan(lang().length)
+ expect(JSON.stringify(r.messages)).toContain('verifyToken')
+ })
+
+ // Die Regel, an der diese App schon einmal gescheitert ist: eine
+ // Systemnachricht mitten im Gespraech beantwortet eine strenge Jinja-Vorlage
+ // mit "System message must be at the beginning" statt mit einer Antwort.
+ it('erzeugt NIE eine Systemnachricht ausserhalb von Index 0', () => {
+ const r = applyCompactSummary({ messages: lang(), keepRecent: 6, summary: zus })
+ expect(r.messages[0].role).toBe('system')
+ expect(r.messages.slice(1).some((m) => m.role === 'system')).toBe(false)
+ })
+
+ it('die Zusammenfassung reitet auf Nutzermaterial', () => {
+ const r = applyCompactSummary({ messages: lang(), keepRecent: 6, summary: zus })
+ const traeger = r.messages.find((m) => String(m.content).includes(COMPACT_OPEN))
+ expect(traeger).toBeDefined()
+ expect(traeger!.role).toBe('user')
+ })
+
+ it('kommt auch ohne Systemnachricht zurecht', () => {
+ const ohne = lang().slice(1)
+ const r = applyCompactSummary({ messages: ohne, keepRecent: 4, summary: zus })
+ expect(r.messages.every((m) => m.role !== 'system')).toBe(true)
+ expect(r.replaced).toBeGreaterThan(0)
+ })
+
+ // Ein Werkzeugergebnis ohne den Aufruf davor wird von strengen
+ // OpenAI-kompatiblen Anbietern abgelehnt.
+ it('laesst das behaltene Fenster nie mit einem verwaisten Werkzeugergebnis beginnen', () => {
+ const msgs = [
+ w('system', 's'),
+ ...Array.from({ length: 20 }, (_, i) => w('user', `alt ${i}`)),
+ w('tool', 'ergebnis ohne aufruf'),
+ w('assistant', 'antwort'),
+ w('user', 'frage'),
+ ]
+ const r = applyCompactSummary({ messages: msgs, keepRecent: 3, summary: zus })
+ const nachTraeger = r.messages.filter((m) => !String(m.content).includes(COMPACT_OPEN))
+ expect(nachTraeger[1]?.role).not.toBe('tool')
+ })
+
+ it('erkennt auch das Hermes-foermige Werkzeugergebnis', () => {
+ const msgs = [
+ ...Array.from({ length: 20 }, (_, i) => w('user', `alt ${i}`)),
+ w('user', '<tool_response>daten</tool_response>'),
+ w('assistant', 'a'),
+ ]
+ const r = applyCompactSummary({ messages: msgs, keepRecent: 2, summary: zus })
+ expect(JSON.stringify(r.messages)).not.toContain('<tool_response>')
+ })
+
+ it('tut nichts, wenn die Zusammenfassung leer ist', () => {
+ const m = lang()
+ const r = applyCompactSummary({ messages: m, keepRecent: 6, summary: EMPTY_SUMMARY })
+ expect(r.messages).toBe(m)
+ expect(r.replaced).toBe(0)
+ expect(r.rendered).toBe('')
+ })
+
+ it('tut nichts, wenn das Fenster ohnehin alles behaelt', () => {
+ const m = lang()
+ const r = applyCompactSummary({ messages: m, keepRecent: 999, summary: zus })
+ expect(r.messages).toBe(m)
+ expect(r.replaced).toBe(0)
+ })
+
+ // Sonst faltet jede Runde die vorige in sich.
+ it('stapelt keine Zusammenfassungen uebereinander', () => {
+ const einmal = applyCompactSummary({ messages: lang(), keepRecent: 6, summary: zus })
+ const zweimal = applyCompactSummary({
+ messages: [...einmal.messages, w('user', 'weiter'), w('assistant', 'ok'),
+ w('user', 'a'), w('assistant', 'b'), w('user', 'c'), w('assistant', 'd'),
+ w('user', 'e'), w('assistant', 'f')],
+ keepRecent: 4,
+ summary: parseCompactSummary('TASK\nNeue Fassung.\n\nOPEN\nRest.'),
+ })
+ const treffer = JSON.stringify(zweimal.messages).split(COMPACT_OPEN).length - 1
+ expect(treffer).toBe(1)
+ expect(JSON.stringify(zweimal.messages)).toContain('Neue Fassung')
+ })
+})
+
+// ── Die Rechnung VOR dem Modellaufruf ──────────────────────────────────────
+//
+// Gefunden am 02.09.2026 im laufenden Fenster, nicht am Schreibtisch: ein
+// /compact lief durch ein echtes Modell und wurde danach abgelehnt.
+//
+// Die erste Fassung dieser Pruefung behauptete, jener Fall sei vorher wissbar
+// gewesen — und genau das hat der Test unten widerlegt: bei 633 ersetzten
+// Zeichen sind 316 erlaubt, und die kleinste baubare Fassung misst 269. Sie
+// haette gepasst. Abgelehnt wurde erst die wirkliche Antwort ueber zehn Turns.
+//
+// Die Pruefung bleibt trotzdem richtig, nur enger als gedacht: unter rund 538
+// ersetzten Zeichen kann NICHTS passen. Dort spart sie einen aussichtslosen
+// Modellaufruf. Der Beschwerdefall selbst wird nicht hier geloest, sondern von
+// der ehrlichen Meldung in compactOutcomeMessage.
+describe('was nicht passen kann, wird nicht erst gerechnet', () => {
+ it('die kleinste Fassung wird gemessen, nicht geschaetzt', () => {
+ // Wenn diese Zahl je als Konstante hingeschrieben wird, faellt sie hier
+ // beim naechsten Umformulieren der Vorrede auf.
+ expect(minimalSummaryChars()).toBeGreaterThan(COMPACT_PREAMBLE.length)
+ expect(minimalSummaryChars()).toBeGreaterThanOrEqual(
+ COMPACT_PREAMBLE.length + MIN_SUMMARY_CHARS,
+ )
+ })
+
+ it('laesst den gemessenen Fall durch, statt ihn faelschlich vorab zu sperren', () => {
+ // 633 Zeichen erlauben 316, die kleinste Fassung misst 269. Ein Nein waere
+ // hier falsch gewesen: das Modell haette eine knappe Zusammenfassung
+ // liefern KOENNEN. Diese Zeile haelt die Pruefung davon ab, sich zu einer
+ // Sperre auszuwachsen, die gute kurze Zusammenfassungen verhindert.
+ expect(summaryCouldEverFit(633)).toBe(true)
+ })
+
+ it('sperrt dort, wo es wirklich aussichtslos ist', () => {
+ // Unterhalb der Schwelle passt selbst die kleinstmoegliche Fassung nicht.
+ const schwelle = minimalSummaryChars() / 0.5
+ expect(summaryCouldEverFit(Math.floor(schwelle) - 1)).toBe(false)
+ expect(summaryCouldEverFit(200)).toBe(false)
+ })
+
+ it('sagt ja, sobald der Platz wirklich reicht', () => {
+ const gerade = Math.ceil(minimalSummaryChars() / MAX_SUMMARY_SHARE)
+ expect(summaryCouldEverFit(gerade)).toBe(true)
+ expect(summaryCouldEverFit(gerade - 2)).toBe(false)
+ })
+
+ it('ohne Bezugsgroesse greift die Regel nicht, statt alles zu verbieten', () => {
+ // 0 heisst "nicht messbar", nicht "null Platz". Ein Nein waere hier eine
+ // Sperre, die niemand angeordnet hat.
+ expect(summaryCouldEverFit(0)).toBe(true)
+ expect(summaryCouldEverFit(-5)).toBe(true)
+ })
+
+ it('die Schranke haengt wirklich an MAX_SUMMARY_SHARE', () => {
+ // Beweist, dass die Funktion die Konstante liest und nicht eine zweite,
+ // still mitgefuehrte Zahl.
+ const min = minimalSummaryChars()
+ expect(summaryCouldEverFit(min / MAX_SUMMARY_SHARE)).toBe(true)
+ expect(summaryCouldEverFit(min / MAX_SUMMARY_SHARE - 1)).toBe(false)
+ })
+})
+
+// ── Aufbau und Lesen muessen dieselben Ueberschriften kennen ──────────────
+//
+// Gefunden am 02.09.2026 von einem Waechter, der den Rundlauf pruefen sollte.
+// renderCompactSummary schrieb `NOTES`, parseCompactSummary kannte das Wort
+// nicht — also fiel die Zeile samt Text in den Eimer der VORHERIGEN
+// Ueberschrift. Aus {task:'A', requests: '', rest:'X'} wurde EIN TASK-Block mit dem Wort
+// NOTES mittendrin. Kein Absturz, keine rote Pruefung: nur eine Anzeige, die
+// still das Falsche zeigte.
+//
+// Der alte Waechter war gruen, weil er nur fragte, ob NOTES als ERSTE Zeile
+// erscheint — das tat es nicht, es stand ja in der Mitte. Diese Pruefungen
+// fragen nach dem Rundlauf selbst, und der ist die eigentliche Zusage.
+describe('der Rundlauf verliert und verschiebt nichts', () => {
+ it('loser Text neben benannten Abschnitten kommt als eigener Abschnitt zurueck', () => {
+ const gerendert = renderCompactSummary({
+ ...EMPTY_SUMMARY, task: 'Videoschnitt', requests: '', rest: 'Nebenbei: die Datei liegt auf dem NAS.',
+ })
+ expect(summarySections(gerendert)).toEqual([
+ { heading: 'TASK', body: 'Videoschnitt' },
+ { heading: REST_HEADING, body: 'Nebenbei: die Datei liegt auf dem NAS.' },
+ ])
+ })
+
+ it('das Wort NOTES steht in keinem Abschnittstext, auch nicht in der Mitte', () => {
+ const voll = renderCompactSummary({
+ task: 'T', requests: '', progress: 'P', decisions: 'D', facts: 'F', open: 'O', rest: 'R',
+ })
+ for (const abschnitt of summarySections(voll)) {
+ expect(abschnitt.body).not.toMatch(/^\s*NOTES\s*$/m)
+ }
+ })
+
+ it('jeder Abschnitt kommt Zeichen fuer Zeichen zurueck, wie er hineinging', () => {
+ const quelle = {
+ task: 'Zeile eins\nZeile zwei', requests: '', progress: '- a\n- b', decisions: 'X weil Y',
+ facts: '1) eins', open: 'noch offen', rest: 'loses Ende',
+ }
+ const zurueck = summarySections(renderCompactSummary(quelle))
+ expect(zurueck.map((a) => a.body)).toEqual([
+ quelle.task, quelle.progress, quelle.decisions, quelle.facts, quelle.open, quelle.rest,
+ ])
+ })
+
+ it('ein Modell, das von sich aus NOTES schreibt, landet ebenfalls im Rest', () => {
+ // Vorher war das Zufall: das Wort fiel in den zuletzt geoeffneten Eimer.
+ const s = parseCompactSummary('TASK\nA\n\nNOTES\nB')
+ expect(s.task).toBe('A')
+ expect(s.rest).toBe('B')
+ })
+})
+
+// ── Die Worte des Nutzers ueberleben woertlich ────────────────────────────
+
+describe('USER REQUESTS — der einzige Abschnitt ohne zweite Quelle', () => {
+ /**
+ * WARUM ES DIESEN ABSCHNITT GIBT: alle anderen sind Nacherzaehlung. Eine
+ * Anweisung, die einmal falsch verstanden wurde, bliebe nach der Verdichtung
+ * fuer immer falsch — das Original ist weg, niemand kann nachlesen. Und
+ * Nebenbedingungen ("aber nie mehr als", "ausser im normalen Chat")
+ * ueberleben eine Zusammenfassung fast nie, obwohl der Nutzer die Arbeit
+ * genau daran misst.
+ *
+ * Werkzeugausgaben lassen sich neu erzeugen, Code neu lesen. Ein Satz, den
+ * der Mensch getippt hat, nicht.
+ */
+ it('steht in SECTIONS, direkt nach TASK', () => {
+ // Die Reihenfolge traegt Bedeutung: TASK ist die Destillation, USER
+ // REQUESTS das Rohprotokoll daneben. Wer sie ans Ende schoebe, liesse die
+ // Nacherzaehlung zuerst lesen und das Original als Nachtrag.
+ const namen = SECTIONS.map((s) => s.heading)
+ expect(namen[0]).toBe('TASK')
+ expect(namen[1]).toBe('USER REQUESTS')
+ })
+
+ it('der Auftrag ans Modell verlangt woertlich und verbietet Kuerzen', () => {
+ const p = buildCompactPrompt([{ role: 'user', content: 'x' }])
+ expect(p).toContain('USER REQUESTS')
+ expect(p).toContain('in their own words, quoted exactly')
+ // Die drei Verbote einzeln, weil jedes eine andere Art von Verlust ist:
+ // kuerzen nimmt Nebenbedingungen, uebersetzen nimmt den Ton, aufraeumen
+ // nimmt die Ungenauigkeit, an der man merkt, dass etwas offen war.
+ expect(p).toContain('Do not shorten, translate or tidy them')
+ // Und ausdruecklich die Nebenbedingungen, die sonst als Erstes wegfallen.
+ expect(p).toMatch(/conditions and exceptions/i)
+ })
+
+ it('verbietet "none" ausgerechnet an dieser Stelle', () => {
+ // Ueberall sonst ist "none" die ehrliche Antwort. Hier waere es fast immer
+ // Bequemlichkeit: gesagt hat der Mensch ja etwas, sonst gaebe es kein
+ // Gespraech. Ein Modell, das alle Abschnitte gleich behandelt, schreibt
+ // sonst gerade den teuersten leer.
+ const p = buildCompactPrompt([{ role: 'user', content: 'x' }])
+ expect(p).toContain('Never write "none" under USER REQUESTS')
+ })
+
+ // Der Rundlauf geht ueber `compactSummaryBody`, und nicht aus Bequemlichkeit:
+ // `parseCompactSummary` erwartet den INHALT, nicht die verpackte Fassung —
+ // genau deshalb nimmt `summarySections` die Verpackung zuerst ab. Wer hier
+ // direkt parst, misst einen Weg, den die App nie geht, und bekommt die
+ // Vorrede im `rest` und den Schlussmarker im letzten Abschnitt zurueck.
+ const rundlauf = (s: CompactSummary) =>
+ parseCompactSummary(compactSummaryBody(renderCompactSummary(s)))
+
+ it('ueberlebt den vollen Rundlauf Zeichen fuer Zeichen', () => {
+ // Mit allem, was ein Aufbau kaputtmachen koennte: Zeilenumbrueche,
+ // Anfuehrungszeichen, Umlaute, Kleinschreibung.
+ const woertlich = '"nutze fable 5.1 aber nie mehr als 250k context"\n"gilt fuer JEDEN bereich ausser normaler chat"'
+ expect(rundlauf({ ...EMPTY_SUMMARY, task: 'T', requests: woertlich }).requests)
+ .toBe(woertlich)
+ })
+
+ it('faellt nicht in den Nachbarabschnitt, wenn der naechste leer ist', () => {
+ // Dieselbe Falle, an der NOTES schon einmal haengengeblieben ist: eine
+ // Ueberschrift, die der Aufbau schreibt und der Parser nicht kennt, nimmt
+ // ihren Text in den Eimer davor mit.
+ const zurueck = rundlauf({ ...EMPTY_SUMMARY, requests: 'nur dies' })
+ expect(zurueck.requests).toBe('nur dies')
+ expect(zurueck.task).toBe('')
+ expect(zurueck.progress).toBe('')
+ })
+
+ it('bleibt woertlich, auch wenn der Text selbst wie eine Ueberschrift aussieht', () => {
+ // Ein Nutzer, der "OPEN" oder "FACTS" schreibt, darf seinen Satz nicht
+ // dadurch verlieren, dass der Parser ihn fuer eine Gliederung haelt. Das
+ // ist keine erfundene Sorge: der Parser erkennt Ueberschriften bewusst
+ // grosszuegig, mit Deko drumherum.
+ const zurueck = rundlauf({
+ ...EMPTY_SUMMARY,
+ requests: '"schreib OPEN gross"\n"und danach FACTS pruefen"',
+ })
+ expect(zurueck.requests).toContain('"schreib OPEN gross"')
+ expect(zurueck.requests).toContain('"und danach FACTS pruefen"')
+ })
+})
diff --git a/src/lib/__tests__/compact-trigger.test.ts b/src/lib/__tests__/compact-trigger.test.ts
new file mode 100644
index 00000000..8775b332
--- /dev/null
+++ b/src/lib/__tests__/compact-trigger.test.ts
@@ -0,0 +1,301 @@
+/**
+ * Sperrklinken für die Auto-Compact-Entscheidung (2.6.8, Compact-Schritt 1).
+ *
+ * Die wichtigste Zusicherung steht ganz oben und ist eine Negativ-Aussage:
+ * ohne gesetzte Schwelle darf dieses Modul NICHTS auslösen. Die Entscheidung
+ * vom 02.09.2026 war "einstellbar sonst aus", und ein Standardwert, der sich
+ * später einschleicht, wäre genau der Fehler, den diese Datei verhindern soll.
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ shouldAutoCompact,
+ autoCompactHint,
+ confidenceMargin,
+ numeratorMargin,
+ usableThreshold,
+ MARGIN_BUILT,
+ MARGIN_USAGE_REAL,
+ MARGIN_USAGE_ESTIMATED,
+ MARGIN_ESTIMATE,
+ MARGIN_WINDOW_GUESSED,
+ MIN_EFFECTIVE_THRESHOLD,
+ MIN_THRESHOLD,
+ MAX_THRESHOLD,
+ MIN_MESSAGES_TO_COMPACT,
+ MIN_MESSAGES_SINCE_COMPACT,
+ type CompactTriggerInput,
+} from '../compact-trigger'
+import { computeContextFill, type FillMessage } from '../token-usage'
+
+/** Ein Fall, der ohne Zutun feuern WÜRDE — jede Prüfung variiert genau ein Feld. */
+const feuernd: CompactTriggerInput = {
+ used: 9000,
+ window: 10000,
+ source: 'built',
+ real: false,
+ windowIsTrue: true,
+ messageCount: 40,
+ threshold: 0.8,
+}
+
+describe('opt-in: ohne Schwelle passiert nichts', () => {
+ it('feuert nicht ohne Schwelle', () => {
+ const r = shouldAutoCompact({ ...feuernd, threshold: undefined })
+ expect(r.shouldCompact).toBe(false)
+ expect(r.reason).toBe('off')
+ })
+
+ it('feuert nicht bei Schwelle 0 — der Aus-Zustand der Einstellung', () => {
+ expect(shouldAutoCompact({ ...feuernd, threshold: 0 }).reason).toBe('off')
+ })
+
+ it('feuert nicht bei unsinnigen Werten', () => {
+ for (const t of [NaN, Infinity, -1, 0.1, 0.99, 2]) {
+ expect(shouldAutoCompact({ ...feuernd, threshold: t }).reason).toBe('off')
+ }
+ })
+
+ it('usableThreshold nimmt nur den erlaubten Bereich an', () => {
+ expect(usableThreshold(MIN_THRESHOLD)).toBe(MIN_THRESHOLD)
+ expect(usableThreshold(MAX_THRESHOLD)).toBe(MAX_THRESHOLD)
+ expect(usableThreshold(MIN_THRESHOLD - 0.01)).toBeNull()
+ expect(usableThreshold(MAX_THRESHOLD + 0.01)).toBeNull()
+ expect(usableThreshold(undefined)).toBeNull()
+ })
+
+ it('derselbe Fall feuert, sobald eine Schwelle gesetzt ist', () => {
+ expect(shouldAutoCompact(feuernd).shouldCompact).toBe(true)
+ expect(shouldAutoCompact(feuernd).reason).toBe('over')
+ })
+})
+
+describe('der Nenner muss aufgelöst sein', () => {
+ it('feuert nicht, solange das Fenster 0 ist', () => {
+ const r = shouldAutoCompact({ ...feuernd, window: 0 })
+ expect(r.reason).toBe('no-window')
+ expect(r.ratio).toBe(0)
+ })
+})
+
+describe('zu kurz zum Zusammenfassen', () => {
+ it('feuert unterhalb der Mindestlänge nicht', () => {
+ const r = shouldAutoCompact({ ...feuernd, messageCount: MIN_MESSAGES_TO_COMPACT - 1 })
+ expect(r.reason).toBe('too-short')
+ })
+
+ it('feuert genau ab der Mindestlänge', () => {
+ expect(
+ shouldAutoCompact({ ...feuernd, messageCount: MIN_MESSAGES_TO_COMPACT }).shouldCompact,
+ ).toBe(true)
+ })
+})
+
+describe('Abklingzeit: keine Zusammenfassung der Zusammenfassung', () => {
+ it('feuert nicht direkt nach einer Kürzung', () => {
+ const r = shouldAutoCompact({ ...feuernd, messageCount: 40, lastCompactAtMessageCount: 38 })
+ expect(r.reason).toBe('cooldown')
+ })
+
+ it('feuert wieder, sobald genug Neues dazugekommen ist', () => {
+ const r = shouldAutoCompact({
+ ...feuernd,
+ messageCount: 40,
+ lastCompactAtMessageCount: 40 - MIN_MESSAGES_SINCE_COMPACT,
+ })
+ expect(r.shouldCompact).toBe(true)
+ })
+
+ it('ohne frühere Kürzung greift die Abklingzeit nicht', () => {
+ expect(shouldAutoCompact({ ...feuernd, lastCompactAtMessageCount: undefined }).shouldCompact)
+ .toBe(true)
+ })
+
+ // Der Fall, für den die Abklingzeit da ist: ein einzelnes riesiges
+ // Werkzeugergebnis hält das Verhältnis auch NACH dem Kürzen über der
+ // Schwelle. Ohne Sperre würde jeder folgende Zug erneut zusammenfassen.
+ it('ein weiter volles Fenster löst nicht sofort erneut aus', () => {
+ const nachKuerzung = { ...feuernd, used: 9500, messageCount: 41, lastCompactAtMessageCount: 40 }
+ expect(shouldAutoCompact(nachKuerzung).shouldCompact).toBe(false)
+ })
+})
+
+describe('der Verlässlichkeitsabschlag', () => {
+ it('gibt es für einen gebauten Wert nicht', () => {
+ expect(numeratorMargin('built', false)).toBe(MARGIN_BUILT)
+ expect(MARGIN_BUILT).toBe(0)
+ })
+
+ it('wächst, je weiter die Zahl von der Messung weg ist', () => {
+ expect(numeratorMargin('built', true)).toBeLessThan(numeratorMargin('usage', true))
+ expect(numeratorMargin('usage', true)).toBeLessThan(numeratorMargin('usage', false))
+ expect(numeratorMargin('usage', false)).toBeLessThan(numeratorMargin('estimate', false))
+ expect(numeratorMargin('estimate', false)).toBe(MARGIN_ESTIMATE)
+ expect(numeratorMargin('usage', true)).toBe(MARGIN_USAGE_REAL)
+ expect(numeratorMargin('usage', false)).toBe(MARGIN_USAGE_ESTIMATED)
+ })
+
+ it('ein geratenes Fenster trägt einen eigenen Abschlag', () => {
+ expect(confidenceMargin({ source: 'built', real: true, windowIsTrue: false }))
+ .toBe(MARGIN_WINDOW_GUESSED)
+ })
+
+ // Das ist die Regel, die im Modulkopf begründet ist: der schlechteste
+ // Abschlag gilt, nicht die Summe. Sonst wird aus einer eingestellten 0,8
+ // still eine 0,6, und die Zahl in den Einstellungen bedeutet nichts mehr.
+ it('nimmt den schlechtesten Abschlag, nicht die Summe', () => {
+ const beides = confidenceMargin({ source: 'estimate', real: false, windowIsTrue: false })
+ expect(beides).toBe(Math.max(MARGIN_ESTIMATE, MARGIN_WINDOW_GUESSED))
+ expect(beides).toBeLessThan(MARGIN_ESTIMATE + MARGIN_WINDOW_GUESSED)
+ })
+
+ it('zieht die Schwelle vor, wo die Zahlen unsicher sind', () => {
+ const sicher = shouldAutoCompact({ ...feuernd, source: 'built', windowIsTrue: true })
+ const unsicher = shouldAutoCompact({ ...feuernd, source: 'estimate', windowIsTrue: false })
+ expect(unsicher.effectiveThreshold).toBeLessThan(sicher.effectiveThreshold)
+ expect(sicher.effectiveThreshold).toBe(0.8)
+ })
+
+ // Genau der Fall, für den der Abschlag existiert: die Schätzung liest zu
+ // niedrig, das geratene Fenster zu hoch, das Verhältnis landet unter der
+ // eingestellten Schwelle — obwohl in Wahrheit schon gekürzt werden müsste.
+ it('feuert bei unsicheren Zahlen dort, wo die rohe Schwelle noch schwiege', () => {
+ const knapp = { ...feuernd, used: 7200, window: 10000, threshold: 0.8 }
+ expect(shouldAutoCompact({ ...knapp, source: 'built', windowIsTrue: true }).shouldCompact)
+ .toBe(false)
+ expect(shouldAutoCompact({ ...knapp, source: 'estimate', windowIsTrue: false }).shouldCompact)
+ .toBe(true)
+ })
+
+ it('unterschreitet nie den Boden', () => {
+ const r = shouldAutoCompact({
+ ...feuernd, threshold: MIN_THRESHOLD, source: 'estimate', windowIsTrue: false,
+ })
+ expect(r.effectiveThreshold).toBe(MIN_EFFECTIVE_THRESHOLD)
+ expect(r.effectiveThreshold).toBeGreaterThanOrEqual(MIN_EFFECTIVE_THRESHOLD)
+ })
+})
+
+describe('das Verhältnis selbst', () => {
+ it('wird nicht bei 1 gekappt — ein übervolles Fenster soll als solches lesbar sein', () => {
+ expect(shouldAutoCompact({ ...feuernd, used: 25000, window: 10000 }).ratio).toBe(2.5)
+ })
+
+ it('meldet das Verhältnis auch dann, wenn nicht gefeuert wird', () => {
+ const r = shouldAutoCompact({ ...feuernd, threshold: undefined })
+ expect(r.ratio).toBeCloseTo(0.9)
+ expect(r.shouldCompact).toBe(false)
+ })
+})
+
+describe('zusammen mit der echten Füllstandsrechnung', () => {
+ const msg = (role: string, content: string, extra: Partial<FillMessage> = {}): FillMessage =>
+ ({ role, content, ...extra })
+
+ it('nimmt Herkunft und Verlässlichkeit von computeContextFill entgegen', () => {
+ // Ein Verlauf ohne jede Modell-Rückmeldung: reine Schätzung.
+ const nurSchaetzung = Array.from({ length: 20 }, (_, i) => msg('user', 'x'.repeat(2000) + i))
+ const fill = computeContextFill(nurSchaetzung)
+ expect(fill.source).toBe('estimate')
+
+ const r = shouldAutoCompact({
+ used: fill.used,
+ window: 16384,
+ source: fill.source,
+ real: fill.real,
+ windowIsTrue: true,
+ messageCount: nurSchaetzung.length,
+ threshold: 0.8,
+ })
+ expect(r.margin).toBe(MARGIN_ESTIMATE)
+ expect(r.effectiveThreshold).toBeCloseTo(0.8 - MARGIN_ESTIMATE)
+ })
+
+ it('ein gebauter Anker führt zum Abschlag null', () => {
+ const verlauf = Array.from({ length: 12 }, () => msg('user', 'hallo'))
+ const fill = computeContextFill(verlauf, { tokens: 14000, atMessageCount: 12 })
+ expect(fill.source).toBe('built')
+
+ const r = shouldAutoCompact({
+ used: fill.used,
+ window: 16384,
+ source: fill.source,
+ real: fill.real,
+ windowIsTrue: true,
+ messageCount: verlauf.length,
+ threshold: 0.8,
+ })
+ expect(r.margin).toBe(0)
+ expect(r.effectiveThreshold).toBe(0.8)
+ expect(r.shouldCompact).toBe(true)
+ })
+})
+
+// ── Die Anzeige: wie weit ist es noch ─────────────────────────────────────
+
+describe('autoCompactHint — der Satz neben dem Fuellbalken', () => {
+ const urteil = (over: Partial<CompactTriggerInput> = {}) =>
+ shouldAutoCompact({
+ used: 1000, window: 10_000, source: 'estimate', real: false,
+ windowIsTrue: true, messageCount: MIN_MESSAGES_TO_COMPACT + 5,
+ threshold: 0.8, ...over,
+ })
+
+ it('sagt gar nichts, wenn die Auto-Kompaktierung aus ist', () => {
+ // Der ausgelieferte Zustand. Ein Hinweis auf ein abgeschaltetes Feature
+ // waere Werbung, kein Statustext.
+ expect(autoCompactHint(null)).toBe('')
+ expect(autoCompactHint(urteil({ threshold: 0 }))).toBe('')
+ })
+
+ it('nennt den Rest in Prozentpunkten DES FENSTERS', () => {
+ // 10 % voll, wirksame Schwelle 80 % (echtes Fenster, kein Abschlag noetig)
+ // → 70 Punkte Luft. Der Nutzer findet die Zahl direkt am Balken wieder;
+ // ein Anteil der Restspanne taete das nicht.
+ const u = urteil({ used: 1000, real: true, source: 'usage' })
+ expect(autoCompactHint(u)).toMatch(/^\d+% of the window left before auto-compaction$/)
+ const prozent = Number(autoCompactHint(u).match(/^(\d+)%/)![1])
+ expect(prozent).toBe(Math.round((u.effectiveThreshold - u.ratio) * 100))
+ })
+
+ it('rechnet mit der WIRKSAMEN Schwelle, nicht mit der eingestellten', () => {
+ // Der eigentliche Grund, warum diese Funktion das fertige Urteil bekommt
+ // statt selbst zu rechnen. Bei geschaetztem Fuellstand zieht
+ // shouldAutoCompact einen Sicherheitsabschlag ab — wer die eingestellten
+ // 80 % anzeigte, naennte eine Marke, bei der nichts passiert.
+ const geschaetzt = urteil({ used: 1000, real: false, source: 'estimate' })
+ const gemessen = urteil({ used: 1000, real: true, source: 'usage' })
+ expect(geschaetzt.effectiveThreshold).toBeLessThan(gemessen.effectiveThreshold)
+ const p = (t: string) => Number(t.match(/^(\d+)%/)![1])
+ expect(p(autoCompactHint(geschaetzt))).toBeLessThan(p(autoCompactHint(gemessen)))
+ })
+
+ it('kuendigt an, wenn es beim naechsten Mal soweit ist', () => {
+ // Die einzige Zeile, die der Nutzer VOR der Ueberraschung liest.
+ expect(autoCompactHint(urteil({ used: 9500, real: true, source: 'usage' })))
+ .toBe('Auto-compaction triggers on the next message')
+ })
+
+ it('nennt keine Prozentzahl, solange das Fenster unbekannt ist', () => {
+ // Ein Prozentwert auf einen Nenner, den niemand kennt, waere erfunden.
+ const t = autoCompactHint(urteil({ window: 0 }))
+ expect(t).toContain('waiting for the model to report its context window')
+ expect(t).not.toMatch(/\d+%/)
+ })
+
+ it('unterscheidet "noch zu kurz" von "noch viel Platz"', () => {
+ // Zwei verschiedene Gruende, nichts zu tun. Wer sie zusammenwirft, laesst
+ // den Nutzer auf eine Kompaktierung warten, die bei 12 Nachrichten gar
+ // nicht kommen kann.
+ const kurz = autoCompactHint(urteil({ messageCount: 2 }))
+ expect(kurz).toContain(`from ${MIN_MESSAGES_TO_COMPACT} messages`)
+ expect(kurz).not.toContain('% of the window')
+ })
+
+ it('sagt es, wenn nur die Abkuehlzeit im Weg steht', () => {
+ const t = autoCompactHint(urteil({
+ used: 9500, real: true, source: 'usage',
+ lastCompactAtMessageCount: MIN_MESSAGES_TO_COMPACT + 4,
+ }))
+ expect(t).toContain('paused briefly after the last summary')
+ })
+})
diff --git a/src/lib/__tests__/run-compact-command.test.ts b/src/lib/__tests__/run-compact-command.test.ts
new file mode 100644
index 00000000..81db5d4e
--- /dev/null
+++ b/src/lib/__tests__/run-compact-command.test.ts
@@ -0,0 +1,416 @@
+/**
+ * Sperrklinken fuer den einen Kompaktier-Lauf (2.6.8, Compact-Schritt 4).
+ *
+ * Drei Aufrufstellen teilen sich diese Funktion — Chat, Agenten-Schleife,
+ * Coding-Schleife. Was hier still kaputtgeht, geht in allen dreien kaputt, und
+ * zwar unsichtbar: eine Kompaktierung entfernt nichts, sie legt einen Datensatz
+ * an. Ein falscher Schnitt faellt daher nicht als Fehler auf, sondern erst
+ * Wochen spaeter daran, dass ein langer Lauf vergessen hat, was er getan hat.
+ *
+ * Der Zusammenfasser (compact-run) ist der EINZIGE Ersatz hier: er ist der
+ * Modellaufruf. Speicher und Auswertung laufen echt.
+ */
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../compact-run', () => ({
+ runCompactSummary: vi.fn(),
+}))
+
+import {
+ runCompactForConversation,
+ newestCompaction,
+ compactOutcomeMessage,
+ KEEP_AFTER_COMPACT,
+ type CompactOutcome,
+} from '../run-compact-command'
+import { runCompactSummary } from '../compact-run'
+import { useChatStore } from '../../stores/chatStore'
+import { COMPACT_OPEN, COMPACT_CLOSE, type CompactSummary, type TranscriptTurn } from '../compact-summary'
+import type { CompactionRecord, Conversation, Message, Role } from '../../types/chat'
+
+const zusammenfasser = runCompactSummary as unknown as ReturnType<typeof vi.fn>
+
+const SUMME: CompactSummary = {
+ task: 'Den Login reparieren.',
+ requests: '', progress: 'auth.ts gelesen, Nullwert in Zeile 40 gefunden.',
+ decisions: 'Kein Refactoring — der Rest ist getestet.',
+ facts: 'src/auth.ts:40, verifyToken.',
+ open: 'Der Test fehlt.',
+ rest: '',
+}
+
+const CHAT_ID = 'conv-1'
+
+const nachricht = (id: string, content: string, role: Role = 'user'): Message => ({
+ id,
+ role,
+ content,
+ timestamp: 1,
+})
+
+/** N sichtbare Nachrichten, m0 … m(N-1), abwechselnd Nutzer und Modell. */
+const verlauf = (n: number): Message[] =>
+ Array.from({ length: n }, (_, i) =>
+ nachricht(`m${i}`, `Zug ${i}: Inhalt`, i % 2 ? 'assistant' : 'user'),
+ )
+
+function chatMit(messages: Message[], compactions?: CompactionRecord[]): string {
+ const conv: Conversation = {
+ id: CHAT_ID,
+ title: 'Test',
+ messages,
+ model: 'qwen:4b',
+ systemPrompt: '',
+ compactions,
+ createdAt: 1,
+ updatedAt: 1,
+ }
+ useChatStore.setState({ conversations: [conv] })
+ return CHAT_ID
+}
+
+const datensatz = (upToMessageId: string): CompactionRecord => ({
+ id: 'rec-alt',
+ summary: 'alt',
+ upToMessageId,
+ replaced: 1,
+ atMessageCount: 1,
+ tokensBefore: 100,
+ tokensAfter: 10,
+ trigger: 'manual',
+ at: 1,
+})
+
+/** Was der Zusammenfasser tatsaechlich zu sehen bekam. */
+function gesehene(): TranscriptTurn[] {
+ expect(zusammenfasser).toHaveBeenCalledTimes(1)
+ return zusammenfasser.mock.calls[0][0].turns as TranscriptTurn[]
+}
+
+const lauf = (extra: Record<string, unknown> = {}) =>
+ runCompactForConversation({
+ conversationId: CHAT_ID,
+ activeModel: 'qwen:4b',
+ trigger: 'manual',
+ ...extra,
+ })
+
+beforeEach(() => {
+ zusammenfasser.mockReset()
+ zusammenfasser.mockResolvedValue({ ok: true, summary: SUMME, reason: 'ok' })
+ useChatStore.setState({ conversations: [] })
+})
+
+describe('runCompactForConversation — die Ausgaenge vor dem Modellaufruf', () => {
+ it('ohne aktives Modell: no-model', async () => {
+ chatMit(verlauf(20))
+ const r = await lauf({ activeModel: null })
+ expect(r).toEqual({ ok: false, reason: 'no-model' })
+ expect(zusammenfasser).not.toHaveBeenCalled()
+ })
+
+ // Die Reihenfolge ist Absicht, nicht Zufall: das Fenster aufzuloesen fragt
+ // das Modell. Wandert die Modellpruefung hinter den Speicherzugriff, zahlt
+ // jeder Aufruf ohne Modell trotzdem den Weg dorthin — dieselbe Regel, die
+ // maybeAutoCompact im Kopf ausdruecklich festhaelt.
+ it('ohne aktives Modell wird der Chat-Speicher gar nicht erst gelesen', async () => {
+ chatMit(verlauf(20))
+ const spion = vi.spyOn(useChatStore, 'getState')
+ try {
+ const r = await lauf({ activeModel: null })
+ expect(r.ok).toBe(false)
+ expect(spion).not.toHaveBeenCalled()
+ } finally {
+ spion.mockRestore()
+ }
+ })
+
+ it('unbekannte Chat-Id: no-conversation', async () => {
+ chatMit(verlauf(20))
+ const r = await runCompactForConversation({
+ conversationId: 'gibt-es-nicht',
+ activeModel: 'qwen:4b',
+ trigger: 'manual',
+ })
+ expect(r).toEqual({ ok: false, reason: 'no-conversation' })
+ expect(zusammenfasser).not.toHaveBeenCalled()
+ })
+
+ it('zu kurzer Chat: nothing-to-compact', async () => {
+ chatMit(verlauf(KEEP_AFTER_COMPACT))
+ const r = await lauf()
+ expect(r).toEqual({ ok: false, reason: 'nothing-to-compact' })
+ expect(zusammenfasser).not.toHaveBeenCalled()
+ })
+
+ // Systemzeilen sind App-Hinweise; kein Modell hat sie je gesehen. Zaehlten
+ // sie mit, liefe eine Kompaktierung auf einem Chat an, der aus Modellsicht
+ // noch aus sechs Zuegen besteht — und fasste Text zusammen, den niemand las.
+ it('Systemhinweise zaehlen nicht als Material', async () => {
+ chatMit([
+ ...verlauf(KEEP_AFTER_COMPACT),
+ nachricht('sys-1', 'Modell gewechselt', 'system'),
+ nachricht('leer', ' '),
+ ])
+ const r = await lauf()
+ expect(r).toEqual({ ok: false, reason: 'nothing-to-compact' })
+ })
+})
+
+describe('KEEP_AFTER_COMPACT — die juengsten Zuege bleiben woertlich', () => {
+ // Ohne diese Grenze verliert ein "mach das nochmal, aber kleiner" das "das".
+ // Der Schnitt darf nie an die juengsten sechs sichtbaren Nachrichten heran.
+ it('die letzten sechs sichtbaren Nachrichten gehen nie in die Zusammenfassung', async () => {
+ chatMit(verlauf(20))
+ const r = await lauf()
+ expect(r.ok).toBe(true)
+
+ const turns = gesehene()
+ expect(turns).toHaveLength(20 - KEEP_AFTER_COMPACT)
+ const text = turns.map((t) => t.content).join('\n')
+ for (let i = 20 - KEEP_AFTER_COMPACT; i < 20; i++) {
+ expect(text).not.toContain(`Zug ${i}:`)
+ }
+ expect(text).toContain('Zug 0:')
+ expect(text).toContain(`Zug ${20 - KEEP_AFTER_COMPACT - 1}:`)
+ })
+
+ it('der Anker ist die letzte zusammengefasste Nachricht, nicht die letzte des Chats', async () => {
+ chatMit(verlauf(20))
+ const r = await lauf()
+ expect(r.ok && r.record.upToMessageId).toBe(`m${20 - KEEP_AFTER_COMPACT - 1}`)
+ expect(r.ok && r.record.replaced).toBe(20 - KEEP_AFTER_COMPACT)
+ })
+
+ it('eine Nachricht mehr als die Sperre reicht fuer genau einen Zug', async () => {
+ chatMit(verlauf(KEEP_AFTER_COMPACT + 1))
+ const r = await lauf()
+ expect(r.ok).toBe(true)
+ expect(gesehene()).toHaveLength(1)
+ })
+
+ it('der Datensatz landet im Speicher', async () => {
+ chatMit(verlauf(20))
+ const r = await lauf()
+ expect(r.ok).toBe(true)
+ const gespeichert = useChatStore.getState().conversations[0].compactions
+ expect(gespeichert).toHaveLength(1)
+ expect(gespeichert![0].summary).toContain(COMPACT_OPEN)
+ expect(gespeichert![0].trigger).toBe('manual')
+ })
+})
+
+describe('Wiederholtes Zusammenfassen', () => {
+ // Der Kern des ganzen Features. Faengt der neue Schnitt vor dem Anker des
+ // alten Datensatzes an, wandert Material, das eine Zusammenfassung schon
+ // abdeckt, ein zweites Mal durch das Modell — Zusammenfassung einer
+ // Zusammenfassung, und genau so vergisst ein langer Lauf seinen Anfang.
+ it('der neue Schnitt beginnt HINTER dem Anker des letzten Datensatzes', async () => {
+ chatMit(verlauf(20), [datensatz('m5')])
+ const r = await lauf()
+ expect(r.ok).toBe(true)
+
+ const turns = gesehene()
+ expect(turns).toHaveLength(20 - KEEP_AFTER_COMPACT - 6)
+ const text = turns.map((t) => t.content).join('\n')
+ for (let i = 0; i <= 5; i++) expect(text).not.toContain(`Zug ${i}:`)
+ expect(text).toContain('Zug 6:')
+ expect(text).toContain('Zug 13:')
+ expect(r.ok && r.record.upToMessageId).toBe('m13')
+ })
+
+ // Nur der NEUESTE Datensatz formt die Nutzlast; ein aelterer darf den
+ // Schnitt nicht nach vorne ziehen und schon abgedecktes Material zurueckholen.
+ it('massgeblich ist der letzte Datensatz, nicht der erste', async () => {
+ chatMit(verlauf(20), [datensatz('m1'), datensatz('m9')])
+ const r = await lauf()
+ expect(r.ok).toBe(true)
+ const text = gesehene().map((t) => t.content).join('\n')
+ expect(text).not.toContain('Zug 9:')
+ expect(text).toContain('Zug 10:')
+ })
+
+ it('steht der alte Anker schon auf dem Schnitt: nothing-to-compact', async () => {
+ chatMit(verlauf(20), [datensatz(`m${20 - KEEP_AFTER_COMPACT - 1}`)])
+ const r = await lauf()
+ // `detail` unterscheidet die beiden Wege in denselben Grund: hier ist der
+ // Chat NICHT zu kurz, sondern schon verdichtet. Dem Nutzer zu sagen, er
+ // sei „still short enough to send whole", waehrend darueber eine
+ // Verdichtungslinie steht, war schlicht falsch (2.6.8).
+ expect(r).toEqual({ ok: false, reason: 'nothing-to-compact', detail: 'already-compacted' })
+ expect(zusammenfasser).not.toHaveBeenCalled()
+ })
+
+ it('steht der alte Anker hinter dem Schnitt: nothing-to-compact', async () => {
+ chatMit(verlauf(20), [datensatz('m17')])
+ const r = await lauf()
+ expect(r).toEqual({ ok: false, reason: 'nothing-to-compact', detail: 'already-compacted' })
+ expect(zusammenfasser).not.toHaveBeenCalled()
+ })
+
+ // Ein Anker, dessen Nachricht geloescht wurde, findet sich nicht mehr.
+ // Dann ist der ganze Verlauf wieder Material — lieber doppelt zusammenfassen
+ // als den Lauf mit einem stillen "nichts zu tun" haengen lassen.
+ it('ein verwaister Anker faellt auf den vollen Verlauf zurueck', async () => {
+ chatMit(verlauf(20), [datensatz('weg')])
+ const r = await lauf()
+ expect(r.ok).toBe(true)
+ expect(gesehene()).toHaveLength(20 - KEEP_AFTER_COMPACT)
+ })
+})
+
+describe('Eine gespeicherte Zusammenfassung ist kein Verlauf', () => {
+ // Reitet ein alter Block in einer gespeicherten Nachricht mit und wird
+ // ungefiltert weitergereicht, fasst das Modell eine Zusammenfassung
+ // zusammen. Was danach uebrig bleibt, wird mit jedem Durchlauf duenner.
+ it('ein alter Block wird aus dem Zug entfernt, der Rest der Nachricht bleibt', async () => {
+ const mitBlock = nachricht(
+ 'm0',
+ `${COMPACT_OPEN}\nTASK\nEtwas ganz Altes${COMPACT_CLOSE}\nZug 0: Inhalt`,
+ )
+ chatMit([mitBlock, ...verlauf(19).slice(1)])
+ const r = await lauf()
+ expect(r.ok).toBe(true)
+
+ const turns = gesehene()
+ expect(turns[0].content).toBe('Zug 0: Inhalt')
+ const text = turns.map((t) => t.content).join('\n')
+ expect(text).not.toContain(COMPACT_OPEN)
+ expect(text).not.toContain('Etwas ganz Altes')
+ })
+})
+
+describe('newestCompaction', () => {
+ it('ohne Datensaetze: undefined', () => {
+ expect(newestCompaction(undefined)).toBeUndefined()
+ expect(newestCompaction([])).toBeUndefined()
+ })
+
+ // Nur der letzte formt die Nutzlast — jeder aeltere deckt bereits alles vor
+ // seinem eigenen Schnitt ab, zwei angewandte Datensaetze schickten dasselbe
+ // Material doppelt.
+ it('liefert den letzten, nicht den ersten', () => {
+ const a = datensatz('m1')
+ const b = { ...datensatz('m9'), id: 'rec-neu' }
+ expect(newestCompaction([a, b])).toBe(b)
+ })
+})
+
+describe('compactOutcomeMessage', () => {
+ const quelle = (datei: string) => readFileSync(join(__dirname, '..', datei), 'utf8')
+
+ /** Die Zeichenketten einer Union, direkt aus dem Quelltext. */
+ function unionLiterale(src: string, deklaration: string): string[] {
+ const start = src.indexOf(deklaration)
+ expect(start).toBeGreaterThan(-1)
+ const rest = src.slice(start + deklaration.length)
+ const block = rest.split('\n\n')[0]
+ return [...block.matchAll(/'([^']+)'/g)].map((m) => m[1])
+ }
+
+ // Die Liste wird NICHT abgeschrieben: ein neuer Grund, der spaeter ohne
+ // eigenen Satz dazukommt, faellt sonst still in den Sammelfall und der
+ // Nutzer liest "konnte nicht geschrieben werden", wo etwas anderes stimmt.
+ const GRUENDE = [
+ ...unionLiterale(quelle('compact-run.ts'), 'export type CompactRunReason ='),
+ ...unionLiterale(quelle('run-compact-command.ts'), 'export type CompactOutcome ='),
+ ]
+
+ const satzZu = (reason: string) =>
+ compactOutcomeMessage({ ok: false, reason } as CompactOutcome)
+
+ it('liest die Gruende wirklich aus dem Quelltext', () => {
+ expect(GRUENDE).toEqual(
+ expect.arrayContaining([
+ 'ok', 'no-model', 'empty-input', 'aborted', 'call-failed', 'unusable',
+ 'no-conversation', 'nothing-to-compact',
+ ]),
+ )
+ })
+
+ it('jeder Grund ergibt einen nicht leeren Satz', () => {
+ for (const g of GRUENDE) expect(satzZu(g).trim()).not.toBe('')
+ })
+
+ // Der Sammelfall ist genau drei Gruenden zugestanden. Kommt ein vierter
+ // hinzu, ist das kein Zufall, sondern ein vergessener Satz — dann faellt
+ // diese Pruefung, nicht der Nutzer.
+ it('nur die drei bekannten Gruende teilen sich den Sammelsatz', () => {
+ const sammel = satzZu('call-failed')
+ const geteilt = GRUENDE.filter((g) => satzZu(g) === sammel).sort()
+ expect(geteilt).toEqual(['call-failed', 'empty-input', 'ok'])
+ })
+
+ it('jeder eigens benannte Grund hat seinen eigenen Satz', () => {
+ const sammel = satzZu('call-failed')
+ const eigene = GRUENDE.filter((g) => satzZu(g) !== sammel).map(satzZu)
+ expect(eigene.length).toBe(GRUENDE.length - 3)
+ expect(new Set(eigene).size).toBe(eigene.length)
+ })
+
+ it('der Erfolgsfall nennt die Zahl und sagt, dass nichts verloren ist', () => {
+ const record = { ...datensatz('m13'), replaced: 14, tokensBefore: 1000, tokensAfter: 120 }
+ const satz = compactOutcomeMessage({ ok: true, record })
+ expect(satz).toContain('14 earlier messages')
+ expect(satz).toContain('880')
+ expect(satz).toContain('The full conversation is still here')
+ })
+})
+
+// ── Die Meldung darf dem Modell nicht anlasten, was Arithmetik war ────────
+//
+// Gefunden am 02.09.2026 im laufenden Fenster: /compact auf einen Chat mit 633
+// zu ersetzenden Zeichen. Erlaubt waren 316, geliefert wurde eine korrekte
+// Zusammenfassung ueber zehn Turns — zu lang, also abgelehnt. Der Nutzer las
+// "The model did not produce a usable summary". Das Modell hatte sauber
+// gearbeitet; zu klein war der Chat.
+describe('unusable hat drei Ursachen und nicht eine Meldung', () => {
+ const satz = (detail?: string) =>
+ compactOutcomeMessage({ ok: false, reason: 'unusable', detail } as CompactOutcome)
+
+ it('not-smaller nennt die Laenge des Chats, nicht das Versagen des Modells', () => {
+ expect(satz('not-smaller')).not.toMatch(/model/i)
+ expect(satz('not-smaller')).toMatch(/short/i)
+ })
+
+ it('die anderen beiden Ursachen liegen beim Modell und sagen das auch', () => {
+ for (const d of ['too-short', 'empty']) {
+ expect(satz(d)).toMatch(/model/i)
+ }
+ })
+
+ it('ohne Angabe bleibt es bei der Modell-Meldung, statt zu raten', () => {
+ // Ein fehlendes `detail` heisst "unbekannt". Daraus "der Chat war zu kurz"
+ // zu machen waere dieselbe Sorte Luege, nur in die andere Richtung.
+ expect(satz(undefined)).toMatch(/model/i)
+ })
+
+ it('die beiden Meldungen sind wirklich verschieden', () => {
+ expect(satz('not-smaller')).not.toBe(satz('too-short'))
+ })
+})
+
+// ── Derselbe Grund, zwei Bedeutungen ──────────────────────────────────────
+describe('nothing-to-compact sagt, WELCHER der beiden Faelle vorliegt', () => {
+ it('ein kurzer Chat ohne Vorgeschichte traegt kein detail', async () => {
+ chatMit(verlauf(4))
+ const r = await lauf()
+ expect(r).toEqual({ ok: false, reason: 'nothing-to-compact' })
+ })
+
+ it('die beiden Saetze sind verschieden und benennen den richtigen Grund', () => {
+ const kurz = compactOutcomeMessage({ ok: false, reason: 'nothing-to-compact' } as CompactOutcome)
+ const schon = compactOutcomeMessage(
+ { ok: false, reason: 'nothing-to-compact', detail: 'already-compacted' } as CompactOutcome,
+ )
+ expect(kurz).not.toBe(schon)
+ // Der erste darf von der Laenge des Chats sprechen, der zweite nicht:
+ // ueber einem schon verdichteten Chat steht eine Linie, und „still short
+ // enough to send whole" widerspricht ihr sichtbar.
+ expect(kurz).toMatch(/short enough/i)
+ expect(schon).not.toMatch(/short enough/i)
+ expect(schon).toMatch(/already covered/i)
+ })
+})
diff --git a/src/lib/__tests__/token-usage.test.ts b/src/lib/__tests__/token-usage.test.ts
index 61015160..8e2406a4 100644
--- a/src/lib/__tests__/token-usage.test.ts
+++ b/src/lib/__tests__/token-usage.test.ts
@@ -140,3 +140,87 @@ describe('the tool chain a run writes back is not new context', () => {
)
})
})
+
+// ── App-Hinweise kosten nichts ────────────────────────────────────────────
+
+describe('computeContextFill zaehlt keine App-Hinweise', () => {
+ /**
+ * WARUM: `role:'system'` in einem GESPEICHERTEN Gespraech ist immer ein
+ * App-Hinweis — der echte Systemprompt steht nicht im Verlauf. Die Nutzlast
+ * verwirft diese Zeilen. Sie zu zaehlen hiess, dem Nutzer Token anzurechnen,
+ * die nie gesendet werden.
+ *
+ * Bis 2026-09-02 fiel das kaum auf, weil es fast keine solchen Zeilen gab.
+ * Dann bekam `/compact` seine Ein-/Ausgabe als Hinweis, eine fertige
+ * Hintergrundaufgabe meldet ihr GANZES Ergebnis als Hinweis, und die
+ * gescheiterte Auto-Kompaktierung meldet sich ebenfalls. Ein
+ * Rechercheergebnis von 5k Token liess den Balken um 5k springen, ohne dass
+ * je ein Byte davon verschickt wurde.
+ */
+ const lang = 'x'.repeat(20_000)
+
+ it('eine Notiz aendert den geschaetzten Fuellstand nicht', () => {
+ const ohne: FillMessage[] = [
+ { role: 'user', content: 'frage' },
+ { role: 'assistant', content: 'antwort' },
+ ]
+ const mit: FillMessage[] = [
+ ...ohne,
+ { role: 'system', content: `Background agent [task-ab] finished: ${lang}` },
+ ]
+ expect(computeContextFill(mit).used).toBe(computeContextFill(ohne).used)
+ })
+
+ it('auch nicht hinter einem echten Usage-Anker', () => {
+ const basis: FillMessage[] = [
+ { role: 'user', content: 'frage' },
+ {
+ role: 'assistant', content: 'antwort',
+ usage: { promptTokens: 900, completionTokens: 10, totalTokens: 910 },
+ },
+ ]
+ const mit: FillMessage[] = [...basis, { role: 'system', content: lang }]
+ const a = computeContextFill(basis)
+ const b = computeContextFill(mit)
+ expect(b.used).toBe(a.used)
+ // Die Quelle darf dabei nicht umkippen — sonst waere die Zahl zwar
+ // gleich, die Sicherheitsmarge im Auto-Ausloeser aber eine andere.
+ expect(b.source).toBe(a.source)
+ expect(b.real).toBe(a.real)
+ })
+
+ it('auch nicht hinter einem gebauten Anker', () => {
+ const basis: FillMessage[] = [
+ { role: 'user', content: 'a' }, { role: 'assistant', content: 'b' },
+ ]
+ const anker = { tokens: 5000, atMessageCount: 2 }
+ const mit: FillMessage[] = [...basis, { role: 'system', content: lang }]
+ expect(computeContextFill(mit, anker).used).toBe(computeContextFill(basis, anker).used)
+ expect(computeContextFill(mit, anker).source).toBe('built')
+ })
+
+ it('der gebaute Anker ueberlebt Notizen — er wird ungefiltert gezaehlt', () => {
+ // DIE eigentliche Falle. Beide Agentenschleifen zeichnen
+ // `atMessageCount = messages.length` UNGEFILTERT auf. Wer hier eine
+ // gefilterte Liste uebergibt, laesst `atMessageCount <= länge`
+ // fehlschlagen, sobald eine Notiz existiert — der Anker wird verworfen,
+ // die Quelle faellt still auf 'estimate' zurueck, und der Auto-Ausloeser
+ // urteilt ueber eine andere Zahl als die, die im Balken steht.
+ const mitNotiz: FillMessage[] = [
+ { role: 'user', content: 'a' },
+ { role: 'system', content: 'eine Notiz' },
+ { role: 'assistant', content: 'b' },
+ ]
+ expect(computeContextFill(mitNotiz, { tokens: 5000, atMessageCount: 3 }).source).toBe('built')
+ // Gefiltert waeren es nur 2 — und genau dann kippt es:
+ const gefiltert = mitNotiz.filter((m) => m.role !== 'system')
+ expect(computeContextFill(gefiltert, { tokens: 5000, atMessageCount: 3 }).source).not.toBe('built')
+ })
+
+ it('ein leeres Gespraech aus lauter Notizen ist leer, nicht voll', () => {
+ const nurNotizen: FillMessage[] = [
+ { role: 'system', content: lang }, { role: 'system', content: lang },
+ ]
+ expect(computeContextFill(nurNotizen).used).toBe(0)
+ })
+})
diff --git a/src/lib/chat-send-budget.ts b/src/lib/chat-send-budget.ts
index 56716127..7f13537e 100644
--- a/src/lib/chat-send-budget.ts
+++ b/src/lib/chat-send-budget.ts
@@ -11,11 +11,12 @@
* - compare sends it to both sides of the panel, every round, uncapped.
*
* So all three get the A2 number: min(0.8 x model window,
- * codexSendWindowTokens) on a paid provider, and nothing at all anywhere else.
- * Local backends are byte-identical to 2.6.5 because there is no bill on the
- * other end, and the contextDecay notaus returns every surface to exactly the
- * payload it sent before, which is what makes this supportable in the field
- * without a rollback release.
+ * codexSendWindowTokens) on a paid provider. Since 2.6.8 a local backend gets
+ * the same shape without the cost ceiling — 0.8 x its own window — because an
+ * overflowing window is not a billing problem; see chatBudgetApplies below,
+ * "WARUM DAS TOR AUFGEHT". The contextDecay notaus still returns every
+ * surface to exactly the payload it sent before, which is what makes this
+ * supportable in the field without a rollback release.
*
* The message-COUNT cap (capMessageCount) stays where it is on every path. It
* guards a different failure: a chat of many short turns fits every token
@@ -24,7 +25,7 @@
import { compactMessages, estimateMessageTokens } from './context-compaction'
import { ageOutImages } from './context-images'
-import { effectiveSendWindow, isPaidProvider } from './send-window'
+import { effectiveSendWindow } from './send-window'
export interface ChatSendBudgetInput {
/** Provider id of the model this payload goes to. */
@@ -41,12 +42,61 @@ export interface ChatSendBudgetInput {
* Whether a payload to this provider is capped at all, answerable before the
* model window has been looked up.
*
- * Resolving that window is an /api/show round trip on Ollama, and a local
- * backend is never capped, so it must not pay for a question whose answer
- * cannot change anything.
+ * Since 2.6.8 (Compact-Schritt 2) the answer is yes for every provider, so
+ * the only thing that switches it off is the contextDecay notaus. The window
+ * lookup behind it now goes through the Ollama context cache, so asking is
+ * one round trip per model for the life of the app instead of one per send.
+ *
+ * ── WARUM DAS TOR AUFGEHT ──────────────────────────────────────────────────
+ *
+ * The gate used to ask `isPaidProvider`, which answers a COST question: is a
+ * token sent a token billed? That is the right question for the size of the
+ * cap, and it is still what decides it — a paid step is held to
+ * codexSendWindowTokens, a local one is not. It was the wrong question for
+ * whether to cap AT ALL, because a history that outgrows the window is not a
+ * billing problem, it is a correctness problem, and a local model has it too:
+ * it truncates, silently, from the front — which is where the task is.
+ *
+ * That local chat had no cap was measurable as an inconsistency inside the app
+ * rather than a judgement call. The SAME local model in Agent and in Coding
+ * mode has been compacted all along (useAgentChat.ts, useCodex.ts, both via
+ * trimWorkingHistory). Only plain chat and compare were uncapped, and nothing
+ * about a chat turn makes a local model's window bigger than an agent turn
+ * does.
+ *
+ * ── WAS SICH DAMIT AENDERT, UND WAS NICHT ──────────────────────────────────
+ *
+ * A local payload is now held to effectiveSendWindow's base, 0.8 x the model
+ * window. Compaction runs with the A3 hysteresis on top, so it does not engage
+ * at 0.8 but at 1.15 x 0.8 = 0.92 of the window, and then drops to 0.7 x 0.8 =
+ * 0.56. So:
+ *
+ * - below 92% of the window, a local chat is byte-identical to 2.6.7;
+ * - above it, the trim engages exactly where the model was about to drop the
+ * oldest turns itself, without saying so;
+ * - the 8% left over is not spare, it is the room the ANSWER needs. num_ctx
+ * covers prompt plus completion, and a prompt filled to the brim leaves a
+ * model no space to reply in.
+ *
+ * The contextDecay notaus still returns every surface, local included, to the
+ * untouched 2.6.5 payload. That is what keeps this supportable in the field
+ * without a rollback release, and it is the reason the notaus outranks the
+ * provider question in the line above rather than sitting beside it.
*/
-export function chatBudgetApplies(providerId: string, contextDecay?: boolean): boolean {
- return contextDecay !== false && isPaidProvider(providerId)
+export function chatBudgetApplies(_providerId: string, contextDecay?: boolean): boolean {
+ // `_providerId` steht noch in der Signatur, traegt die Entscheidung aber
+ // nicht mehr — und der Unterstrich sagt das, statt es zu verschweigen.
+ //
+ // Er bleibt aus einem Grund, der KEIN Bequemlichkeitsgrund ist: die Frage
+ // "welcher Anbieter" ist an dieser Stelle richtig GESTELLT und nur falsch
+ // BEANTWORTET worden. Ein Ueberlauf ist ein Korrektheitsproblem und kein
+ // Kostenproblem, darum haengt das Kappen nicht mehr am bezahlten Anbieter.
+ // Sollte je ein Anbieter auftauchen, der wirklich anders gekappt gehoert
+ // (weil sein Fenster anders zaehlt, nicht weil er billiger ist), ist das
+ // hier die Stelle — und sie ist noch verkabelt. Ihn zu entfernen hiesse,
+ // 12 Aufrufstellen und ihre Tests umzuschreiben, um eine Frage zu loeschen,
+ // die legitim ist.
+ return contextDecay !== false
}
/**
diff --git a/src/lib/compact-run.ts b/src/lib/compact-run.ts
new file mode 100644
index 00000000..03af5d41
--- /dev/null
+++ b/src/lib/compact-run.ts
@@ -0,0 +1,239 @@
+/**
+ * The written summary — the impure half (2.6.8, Compact-Schritt 3b).
+ *
+ * compact-summary.ts builds the request and reads the answer. This module is
+ * the one round trip in between, and it exists as its own file for one reason:
+ * every hazard of an internal model call in this app is a separate, measured
+ * bug, and putting them in the same place as the prompt logic would mean every
+ * prompt test needs a fake provider.
+ *
+ * ── THE SIX THINGS THAT GO WRONG, AND WHERE EACH WAS MEASURED ──────────────
+ *
+ * 1. NO TIMEOUT. `chatWithTools` carries only `options.signal`; the no-chunk
+ * watchdog (`idleAbortGuard`) lives in `chatStream` alone. A wedged
+ * backend hangs a `chatWithTools` caller forever. So this module streams
+ * and collects — the same shape useMemory.ts uses for extraction — and
+ * puts its OWN deadline on top, because the built-in guard measures
+ * silence between chunks, not total time.
+ *
+ * 2. THINKING LEAKS INTO THE ANSWER. Qwen3's Ollama template pre-opens
+ * `<think>` in the PROMPT, so what comes back is reasoning, then a bare
+ * `</think>`, then the answer — with no opening tag for a naive stripper
+ * to find. Only `settleThinking` (via splitOrphanCloser) catches that
+ * shape. Without it the summary that goes into every future request opens
+ * with the model's private reasoning about how to summarise.
+ *
+ * 3. THE NATIVE THINKING CHANNEL. Reasoning also arrives on its own field,
+ * separate from the content. Reading only `content` is the whole fix, and
+ * it is what agents/architect.ts already does.
+ *
+ * 4. num_ctx CHURN. An Ollama call with no options makes Ollama throw away
+ * the KV allocation the chat just paid for and reload the model at its own
+ * default — measured on the ship exe, where the chat sent 32768, the
+ * extraction that follows every turn sent nothing, and `ollama ps` then
+ * reported 4096 while the UI still said 32K. Same model, same num_ctx:
+ * `resolveAgentNumCtx` is the one resolver.
+ *
+ * 5. STOP DOES NOT REACH IT. Passing `{}` as options means the abort can only
+ * be seen BETWEEN requests; the in-flight one keeps generating and keeps
+ * holding the GPU. The caller's signal is threaded through.
+ *
+ * 6. NO TOOLS, EVER. The summariser is a text call. Beyond costing nothing,
+ * this is what makes it identical on all three tool-calling strategies —
+ * native, hermes_xml and template_fix never enter the picture, so the one
+ * model class that most needs compaction is also the one this cannot
+ * break on.
+ *
+ * ── ON COST, AND WHY THIS IS NOT A "SILENT CALL" ───────────────────────────
+ *
+ * lib/silent-model-calls.ts gates hidden inference on lu-cloud behind an
+ * opt-in, because "silent model calls are silent money". That policy is right
+ * and this call is deliberately outside it, on both of its own terms:
+ *
+ * - It is not silent. Every compaction leaves a visible block in the
+ * transcript saying what it replaced. The memory extraction it was written
+ * for leaves nothing.
+ * - The consent is already explicit and specific. `/compact` is the user
+ * typing the command; auto-compact only ever runs when the user has set
+ * `autoCompactThreshold` themselves, and that setting exists for nothing
+ * else. Asking a second time through `memoryCloudOptIn` — a switch about
+ * MEMORY — would gate this feature behind an unrelated one, and would
+ * silently make a typed `/compact` do nothing at all on a default cloud
+ * profile.
+ *
+ * The model is the chat's own, not the cheap catalogue model that
+ * `pickSilentCallModel` would choose (owner decision, 2026-09-02). A summary
+ * is read by the same model on every following turn, and a small model's
+ * misreading of a long run is not cheaper than the tokens it saves.
+ *
+ * ── NEVER THROWS ───────────────────────────────────────────────────────────
+ *
+ * Every failure returns a reason and the caller falls back to the mechanical
+ * trim. Compaction may not be the end of a run — the same rule the thinking
+ * downgrade follows.
+ */
+
+import { getProviderForModel, getProviderIdFromModel } from '../api/providers'
+import { resolveAgentNumCtx } from './agent-num-ctx'
+import { settleThinking } from './thinking-stripper'
+import {
+ buildCompactPrompt,
+ parseCompactSummary,
+ summaryFromLooseText,
+ isEmptySummary,
+ isUsableSummary,
+ summaryCouldEverFit,
+ renderTranscript,
+ EMPTY_SUMMARY,
+ type CompactSummary,
+ type TranscriptTurn,
+ type UsabilityResult,
+} from './compact-summary'
+
+/**
+ * Deadline for the whole call. Generous, because a long transcript on a small
+ * local model is genuinely slow, and the cost of giving up too early is a
+ * mechanical trim the user did not need. The provider's own no-chunk guard
+ * handles a dead connection long before this fires; this one exists for the
+ * other shape — a backend that keeps dribbling tokens and never finishes.
+ */
+export const COMPACT_TIMEOUT_MS = 120_000
+
+/** Sampling for the summariser. Low temperature: this is a record, not prose. */
+export const COMPACT_TEMPERATURE = 0.2
+
+/** Output ceiling. A summary longer than this was not going to be usable. */
+export const COMPACT_MAX_TOKENS = 1200
+
+export interface CompactRunInput {
+ /** The turns about to be dropped — what the summary must stand in for. */
+ turns: TranscriptTurn[]
+ /** The prefixed model name the conversation is running on. */
+ activeModel: string
+ /** Optional steer from `/compact <focus>`. */
+ focus?: string
+ /** settings.contextWindowOverride. */
+ contextWindowOverride?: number
+ /** The turn's abort signal, so Stop reaches this call too. */
+ signal?: AbortSignal
+ /** Override the deadline (tests). */
+ timeoutMs?: number
+}
+
+export type CompactRunReason =
+ | 'ok'
+ | 'no-model' // nothing to call
+ | 'empty-input' // nothing to summarise
+ | 'aborted' // the user pressed Stop
+ | 'call-failed' // the provider errored or timed out
+ | 'unusable' // the model answered, but the answer is not a summary
+
+export interface CompactRunResult {
+ ok: boolean
+ summary: CompactSummary
+ reason: CompactRunReason
+ /** Free text for the log; never shown as-is to the user. */
+ detail?: string
+ /** Present whenever the answer was judged. */
+ usability?: UsabilityResult
+}
+
+const fail = (reason: CompactRunReason, detail?: string): CompactRunResult => ({
+ ok: false, summary: { ...EMPTY_SUMMARY }, reason, detail,
+})
+
+/**
+ * Ask the conversation's own model to summarise the turns being dropped.
+ *
+ * Resolves to a result, always. The caller checks `ok` and falls back to the
+ * mechanical trim when it is false.
+ */
+export async function runCompactSummary(input: CompactRunInput): Promise<CompactRunResult> {
+ if (!input.activeModel) return fail('no-model')
+ const turns = input.turns.filter(
+ (t) => typeof t?.content === 'string' && t.content.trim() !== '',
+ )
+ if (turns.length === 0) return fail('empty-input')
+
+ // Measured against the transcript AS THE MODEL SEES IT, capped and with any
+ // earlier summary already stripped — not against the raw turns. Judging a
+ // summary "not smaller" against material that was never sent would reject
+ // good summaries of very long histories.
+ const replacedChars = renderTranscript(turns).length
+
+ // Die Frage vor dem Aufruf, nicht danach: kann eine Zusammenfassung dieser
+ // Textmenge ueberhaupt kleiner sein als das, was sie ersetzt? Ist sie es
+ // nicht, wuerde `isUsableSummary` unten in JEDEM Fall ablehnen — nach einem
+ // vollen Roundtrip. Ein lokales Modell rechnet dann eine Sekunde fuer nichts.
+ // Der Grund ist derselbe, den die spaete Pruefung vergeben haette, also
+ // liest der Nutzer denselben Satz — nur ohne die Wartezeit davor.
+ //
+ // Das ist ein enges Tor (unter rund 538 ersetzten Zeichen, siehe die
+ // Rechnung bei summaryCouldEverFit) und faengt bewusst nur die Faelle, in
+ // denen die Ablehnung SICHER ist. Ein weiteres Tor waere geraten, und
+ // geratene Tore lehnen gute Zusammenfassungen ab.
+ if (!summaryCouldEverFit(replacedChars)) {
+ return { ok: false, summary: { ...EMPTY_SUMMARY }, reason: 'unusable', detail: 'not-smaller' }
+ }
+
+ const prompt = buildCompactPrompt(turns, { focus: input.focus })
+
+ // One deadline for the whole call, chained to the caller's signal so Stop
+ // still wins. AbortSignal.any is not assumed present — a manual link works
+ // on every runtime this app ships to.
+ const deadline = new AbortController()
+ const timer = setTimeout(() => deadline.abort(), input.timeoutMs ?? COMPACT_TIMEOUT_MS)
+ const onOuterAbort = () => deadline.abort()
+ input.signal?.addEventListener('abort', onOuterAbort)
+
+ try {
+ if (input.signal?.aborted) return fail('aborted')
+
+ const { provider, modelId } = getProviderForModel(input.activeModel)
+ const providerId = getProviderIdFromModel(input.activeModel)
+ // Same model, same num_ctx — otherwise Ollama reloads (hazard 4).
+ const contextWindow = await resolveAgentNumCtx(
+ modelId, providerId, input.contextWindowOverride, input.activeModel,
+ ).catch(() => undefined)
+
+ let raw = ''
+ // chatStream, not chatWithTools: the no-chunk watchdog only exists here
+ // (hazard 1). No `tools` field at all (hazard 6).
+ const stream = provider.chatStream(modelId, [{ role: 'user', content: prompt }], {
+ temperature: COMPACT_TEMPERATURE,
+ maxTokens: COMPACT_MAX_TOKENS,
+ contextWindow,
+ signal: deadline.signal,
+ })
+ for await (const chunk of stream) {
+ if (chunk.content) raw += chunk.content
+ if (chunk.done) break
+ }
+
+ if (input.signal?.aborted) return fail('aborted')
+ if (deadline.signal.aborted) return fail('call-failed', 'timed out')
+
+ // Hazards 2 and 3: strip the reasoning that rides inside the content, and
+ // never read the separate reasoning channel at all.
+ const content = settleThinking(raw, '', false).content.trim()
+ if (!content) return fail('unusable', 'empty answer')
+
+ // The forgiving read first; a model that ignored the headings still said
+ // something, and keeping it is the whole point of the loose fallback.
+ let summary = parseCompactSummary(content)
+ if (isEmptySummary(summary)) summary = summaryFromLooseText(content)
+
+ const usability = isUsableSummary({ summary, replacedChars })
+ if (!usability.usable) {
+ return { ok: false, summary, reason: 'unusable', detail: usability.reason, usability }
+ }
+ return { ok: true, summary, reason: 'ok', usability }
+ } catch (err) {
+ if (input.signal?.aborted) return fail('aborted')
+ const msg = err instanceof Error ? err.message : String(err)
+ return fail('call-failed', deadline.signal.aborted ? `timed out (${msg})` : msg)
+ } finally {
+ clearTimeout(timer)
+ input.signal?.removeEventListener('abort', onOuterAbort)
+ }
+}
diff --git a/src/lib/compact-summary.ts b/src/lib/compact-summary.ts
new file mode 100644
index 00000000..76e4f399
--- /dev/null
+++ b/src/lib/compact-summary.ts
@@ -0,0 +1,717 @@
+/**
+ * The written summary — the pure half (2.6.8, Compact-Schritt 3).
+ *
+ * This is what separates a compaction from a truncation. Today's mechanical
+ * path keeps a suffix window and leaves behind a list of TOOL NAMES; whatever
+ * was reasoned, decided or found in the dropped turns is simply gone. Here the
+ * model is asked to write down what happened before the drop, and that text
+ * rides along instead.
+ *
+ * ── WHY THIS MODULE HOLDS NO MODEL CALL ────────────────────────────────────
+ *
+ * Prompt building, answer parsing and the "is this usable?" judgement are the
+ * parts that decide whether compaction helps or quietly destroys a run, and
+ * they are the parts worth testing hardest. A model call in the same module
+ * would make every one of those tests need a fake provider. So the round trip
+ * lives at the call site and this module stays pure — the same split the
+ * project already uses for agent-commands.ts ("pure data + pure functions
+ * here — no React, no side effects").
+ *
+ * ── WHY PLAIN TEXT AND NOT A JSON SCHEMA ───────────────────────────────────
+ *
+ * The obvious design is to demand JSON and parse it. It is the wrong one here,
+ * because of who has to answer. This app runs models on three tool-calling
+ * strategies (native, hermes_xml, template_fix), and the two fallback
+ * strategies exist precisely BECAUSE those models cannot be relied on to emit
+ * a required structure — that is what the fallback is for. A summariser that
+ * demands valid JSON would work on the cloud models that need compaction least
+ * and fail on the small local models that need it most, and it would fail by
+ * throwing away the history it was asked to preserve.
+ *
+ * So: named sections in plain prose, and a parser that takes what it finds.
+ * A model that ignores the headings entirely still produces usable text, and
+ * `summaryFromLooseText` keeps it rather than declaring failure. Only genuinely
+ * empty or degenerate output falls through to the mechanical path.
+ *
+ * ── THE SIZE RULE ──────────────────────────────────────────────────────────
+ *
+ * A summary that is not much smaller than what it replaced has bought nothing
+ * and cost a round trip. `isUsableSummary` enforces that, so a model that
+ * "summarises" by echoing the transcript is rejected and the mechanical path
+ * runs instead — which is the honest outcome: no summary is better than a
+ * summary that is a copy.
+ */
+
+import { estimateTokens, attachNoteToUserMaterial } from './context-compaction'
+
+/** One section of the summary, in the order they are asked for and rendered. */
+export interface CompactSummary {
+ /** What the user actually wanted. Survives every later compaction. */
+ task: string
+ /**
+ * Die eigenen Worte des Nutzers, woertlich.
+ *
+ * ── WARUM WOERTLICH UND NICHT DESTILLIERT ────────────────────────────────
+ *
+ * Alle anderen Abschnitte sind Nacherzaehlung — das Modell schreibt auf,
+ * was es verstanden hat. Genau darin liegt der Verlust: eine Anweisung, die
+ * einmal falsch verstanden wurde, bleibt nach der Verdichtung fuer immer
+ * falsch, denn das Original ist weg und niemand kann nachlesen. Und
+ * Nebenbedingungen ("aber nie mehr als X", "ausser im normalen Chat")
+ * ueberleben eine Zusammenfassung fast nie, obwohl sie das sind, woran der
+ * Nutzer die Arbeit misst.
+ *
+ * Die Claude-Code-Desktop-App macht dafuer einen eigenen Abschnitt auf, und
+ * das ist der Grund: die Bitten des Nutzers sind das einzige im Verlauf, das
+ * keine zweite Quelle hat. Werkzeugausgaben lassen sich neu erzeugen, Code
+ * neu lesen — ein Satz, den der Mensch getippt hat, nicht.
+ *
+ * Der Platz dafuer ist billig: in einem Arbeitsgespraech sind die eigenen
+ * Nachrichten ein kleiner Bruchteil des Textes, den Werkzeugausgaben und
+ * Antworten fuellen. Reicht er einmal nicht, greift die Groessenpruefung
+ * (MAX_SUMMARY_SHARE) und sagt ehrlich, dass hier nichts zu holen war.
+ */
+ requests: string
+ /** What was already done, in order. */
+ progress: string
+ /** Decisions taken and the reason, so they are not re-litigated. */
+ decisions: string
+ /** Facts found that later turns still depend on (paths, names, values). */
+ facts: string
+ /** What is still open. */
+ open: string
+ /** Anything the model wrote that fitted no heading. Never dropped. */
+ rest: string
+}
+
+export const EMPTY_SUMMARY: CompactSummary = {
+ task: '', requests: '', progress: '', decisions: '', facts: '', open: '', rest: '',
+}
+
+/**
+ * The headings the prompt asks for. The parser matches these case-insensitively
+ * and tolerates markdown decoration around them, because models decorate.
+ */
+export const SECTIONS: ReadonlyArray<{ key: keyof CompactSummary; heading: string }> = [
+ { key: 'task', heading: 'TASK' },
+ { key: 'requests', heading: 'USER REQUESTS' },
+ { key: 'progress', heading: 'PROGRESS' },
+ { key: 'decisions', heading: 'DECISIONS' },
+ { key: 'facts', heading: 'FACTS' },
+ { key: 'open', heading: 'OPEN' },
+]
+
+/**
+ * Marker that wraps a rendered summary wherever it travels. It has two jobs:
+ * the UI finds a compaction block by it, and `stripCompactSummary` can remove
+ * an older one so summaries never nest — a summary of a summary of a summary
+ * is how a long run forgets everything it did.
+ */
+/**
+ * Die Ueberschrift, unter der loser Text steht — der `rest`.
+ *
+ * Sie steht NICHT in SECTIONS, weil sie kein benanntes Feld ist, sondern der
+ * Auffangeimer. Aber sie muss beiden Seiten bekannt sein, und genau daran ist
+ * die erste Fassung gescheitert: `renderCompactSummary` schrieb `NOTES`,
+ * `parseCompactSummary` kannte das Wort nicht, und die Zeile samt ihrem Text
+ * landete im Eimer der VORHERIGEN Ueberschrift. Aus `{task:'A', rest:'X'}`
+ * wurde beim Zurueckleben ein einziger TASK-Block mit dem Wort NOTES
+ * mittendrin — nachgemessen am 02.09.2026, gefunden von einem Waechter, der
+ * genau diesen Rundlauf pruefen sollte.
+ *
+ * Die Lehre steckt in der Konstante: wer eine Ueberschrift schreibt, die der
+ * Leser nicht kennt, baut eine Einbahnstrasse. Beide Richtungen lesen ab
+ * hier dieselbe Zeichenkette.
+ */
+export const REST_HEADING = 'NOTES'
+
+export const COMPACT_OPEN = '[compacted-context]'
+export const COMPACT_CLOSE = '[/compacted-context]'
+
+/** A summary must be at most this share of what it replaced, or it is refused. */
+export const MAX_SUMMARY_SHARE = 0.5
+
+/**
+ * Below this many characters of CONTENT, a summary is not a summary.
+ *
+ * Content, not rendered length: the rendered form carries a fixed preamble
+ * that explains to the model what it is looking at, and that preamble alone is
+ * longer than this floor. Measuring the rendered string would have let a
+ * one-word summary through on the strength of its own wrapper — which is
+ * exactly the case this floor exists to catch.
+ */
+export const MIN_SUMMARY_CHARS = 40
+
+export interface CompactPromptOptions {
+ /**
+ * The user's optional steer from `/compact <focus>`. Free text, appended as
+ * an emphasis instruction rather than replacing the sections — a focus must
+ * narrow what is emphasised, never license dropping the task itself.
+ */
+ focus?: string
+ /** Character budget for the transcript handed to the summariser. */
+ maxTranscriptChars?: number
+}
+
+/** Default cap for the transcript the summariser is shown. */
+export const DEFAULT_TRANSCRIPT_CHARS = 60000
+
+export interface TranscriptTurn {
+ role: string
+ content: string
+}
+
+/**
+ * Render the turns being dropped as a transcript for the summariser.
+ *
+ * Head-and-tail, not head-only: the last turns before the cut are the ones the
+ * conversation is standing on right now, and a head-only cap would summarise
+ * the beginning of a long run and lose the part that matters most.
+ */
+export function renderTranscript(turns: TranscriptTurn[], maxChars = DEFAULT_TRANSCRIPT_CHARS): string {
+ const lines = turns
+ .filter((t) => typeof t.content === 'string' && t.content.trim() !== '')
+ .map((t) => `${t.role}: ${stripCompactSummary(t.content).trim()}`)
+ const whole = lines.join('\n\n')
+ if (whole.length <= maxChars) return whole
+ const half = Math.floor(maxChars / 2)
+ const head = whole.slice(0, half)
+ const tail = whole.slice(whole.length - half)
+ const omitted = whole.length - head.length - tail.length
+ return `${head}\n\n… [${omitted} characters of the middle omitted] …\n\n${tail}`
+}
+
+/**
+ * The summarisation request.
+ *
+ * Written as ONE user message on purpose. A system message would be the
+ * natural place for instructions, but this text is sent to whatever model the
+ * chat is already using, including models whose chat template refuses a system
+ * message anywhere but position 0 — the same rule that governs where the
+ * finished summary is allowed to ride (context-compaction.ts, "System message
+ * must be at the beginning"). Keeping the whole request in one user turn means
+ * the summariser call has no template shape a model can refuse.
+ */
+export function buildCompactPrompt(
+ turns: TranscriptTurn[],
+ opts: CompactPromptOptions = {},
+): string {
+ const transcript = renderTranscript(turns, opts.maxTranscriptChars)
+ const focus = opts.focus?.trim()
+ const focusLine = focus
+ ? `\n\nThe person asked you to pay particular attention to: ${focus}\nCover it in more detail than the rest — but still fill in every section below.`
+ : ''
+ return `Below is part of a conversation that is about to be removed to free up context. Write a summary that lets the conversation continue without it.
+
+Write for the assistant that has to carry on, not for a human reader. Facts over prose. Keep names, paths, numbers and identifiers exactly as they appear — they cannot be looked up again once the original is gone. Do not add anything that is not in the transcript, and do not offer to help; this is a record, not a reply.
+
+Use exactly these six headings, each on its own line:
+
+TASK
+What the person originally asked for, in one or two sentences.
+
+USER REQUESTS
+Every instruction the person gave, in their own words, quoted exactly, one per line, in order. Do not shorten, translate or tidy them. Include the conditions and exceptions they attached ("but never more than", "except in"). This is the only part of the record that cannot be reconstructed from anywhere else.
+
+PROGRESS
+What has already been done, in order. Name the concrete results.
+
+DECISIONS
+Choices that were made and the reason for each, so they are not made again differently.
+
+FACTS
+Specific things discovered that later steps depend on: file paths, function names, values, error messages, versions.
+
+OPEN
+What is still unfinished or unanswered.
+
+Write "none" under a heading that has nothing. Never write "none" under USER REQUESTS if the person said anything at all.${focusLine}
+
+--- TRANSCRIPT ---
+${transcript}
+--- END TRANSCRIPT ---`
+}
+
+/** Escape a string for use inside a RegExp. */
+function esc(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
+
+/**
+ * Read the model's answer back into sections.
+ *
+ * Deliberately forgiving: a heading may carry markdown hashes, bold markers,
+ * a trailing colon or a leading list bullet, and may be in any case. Anything
+ * before the first recognised heading, or under none of them, is kept in
+ * `rest` — output that did not follow the format is still information, and
+ * throwing it away would be the one failure this whole module exists to avoid.
+ */
+export function parseCompactSummary(text: string): CompactSummary {
+ const src = (text || '').trim()
+ if (!src) return { ...EMPTY_SUMMARY }
+
+ // Deko auf BEIDEN Seiten. Die erste Fassung erlaubte sie nur vor dem Wort,
+ // und `- decisions -` fiel damit durch — eine Zeile, die ein Modell ohne
+ // Weiteres so schreibt. Die Klasse ist absichtlich dieselbe links wie
+ // rechts, statt rechts eine kuerzere zu fuehren: eine Ueberschrift ist an
+ // ihrem WORT erkennbar, die Zeichen drumherum sind Geschmack des Modells.
+ const deco = '[\\s>*_#:.\\-=]*'
+ // REST_HEADING steht mit in der Liste, nicht daneben: sie ist eine
+ // Ueberschrift wie die anderen, sie zeigt nur auf `rest` statt auf ein
+ // benanntes Feld. Ein Modell, das von sich aus NOTES schreibt, landet
+ // damit ebenfalls richtig — das war vorher Zufall.
+ const headingRe = new RegExp(
+ `^${deco}(${[...SECTIONS.map((s) => s.heading), REST_HEADING].map(esc).join('|')})${deco}$`,
+ 'i',
+ )
+
+ const out: CompactSummary = { ...EMPTY_SUMMARY }
+ const buckets: Record<string, string[]> = { rest: [] }
+ let current = 'rest'
+
+ for (const line of src.split('\n')) {
+ const m = line.match(headingRe)
+ if (m) {
+ const wort = m[1].toLowerCase()
+ const found = SECTIONS.find((s) => s.heading.toLowerCase() === wort)
+ if (found || wort === REST_HEADING.toLowerCase()) {
+ current = found ? found.key : 'rest'
+ if (!buckets[current]) buckets[current] = []
+ continue
+ }
+ }
+ if (!buckets[current]) buckets[current] = []
+ buckets[current].push(line)
+ }
+
+ for (const key of Object.keys(buckets)) {
+ const body = buckets[key].join('\n').trim()
+ // "none" is the prompt's own word for an empty section; keeping it would
+ // spend tokens saying nothing on every future request.
+ out[key as keyof CompactSummary] = /^none\.?$/i.test(body) ? '' : body
+ }
+ return out
+}
+
+/**
+ * A model that ignored the headings still said something useful. Rather than
+ * calling that a failure, keep the whole answer as the summary body.
+ */
+export function summaryFromLooseText(text: string): CompactSummary {
+ return { ...EMPTY_SUMMARY, rest: (text || '').trim() }
+}
+
+/** True when the summary carries nothing at all. */
+export function isEmptySummary(s: CompactSummary): boolean {
+ return SECTIONS.every((sec) => !s[sec.key].trim()) && !s.rest.trim()
+}
+
+/**
+ * Turn a parsed summary back into the text that will ride in the payload.
+ *
+ * Wrapped in the markers so it can be found and stripped later; sections that
+ * are empty are left out entirely rather than carried as a heading with
+ * nothing under it.
+ */
+/**
+ * Der Satz, der im Nutzlast-Text ueber der Zusammenfassung steht.
+ *
+ * Eine Konstante und kein Literal im Template, weil ihn ZWEI Seiten brauchen:
+ * der Aufbau schreibt ihn, die Anzeige nimmt ihn wieder weg. Stuenden beide
+ * Fassungen als Text da, waere die Anzeige beim naechsten Umformulieren
+ * stillschweigend kaputt — sie wuerde den Satz einfach als Inhalt zeigen,
+ * ohne dass ein Test das merkt.
+ */
+export const COMPACT_PREAMBLE =
+ 'Earlier turns in this conversation were summarised to free up context. This is that summary; treat it as the record of what happened, and carry on from it rather than starting over.'
+
+export function renderCompactSummary(s: CompactSummary): string {
+ const parts: string[] = []
+ for (const sec of SECTIONS) {
+ const body = s[sec.key].trim()
+ if (body) parts.push(`${sec.heading}\n${body}`)
+ }
+ const rest = s.rest.trim()
+ if (rest) parts.push(parts.length ? `${REST_HEADING}\n${rest}` : rest)
+ if (!parts.length) return ''
+ return `${COMPACT_OPEN}\n${COMPACT_PREAMBLE}\n\n${parts.join('\n\n')}\n${COMPACT_CLOSE}`
+}
+
+/**
+ * Remove a rendered summary from a piece of text.
+ *
+ * Used before a NEW summary is written, so the summariser never reads its own
+ * previous output back as if it were transcript. Without this, every
+ * compaction would fold the last one into itself and detail would decay
+ * geometrically — the same failure shape that made the mechanical path's trim
+ * notice stack until it was explicitly stripped (context-compaction.ts,
+ * stripTrimNotice).
+ */
+export function stripCompactSummary(text: string): string {
+ if (typeof text !== 'string' || !text.includes(COMPACT_OPEN)) return text
+ const re = new RegExp(`${esc(COMPACT_OPEN)}[\\s\\S]*?${esc(COMPACT_CLOSE)}\\s*`, 'g')
+ return text.replace(re, '').trim()
+}
+
+/** True when this text already carries a summary. */
+export function hasCompactSummary(text: string): boolean {
+ return typeof text === 'string' && text.includes(COMPACT_OPEN)
+}
+
+export interface UsabilityInput {
+ summary: CompactSummary
+ /** Characters of transcript the summary is meant to replace. */
+ replacedChars: number
+}
+
+export interface UsabilityResult {
+ usable: boolean
+ reason: 'ok' | 'empty' | 'too-short' | 'not-smaller'
+ /** Rendered length, so the caller can log what it rejected. */
+ renderedChars: number
+ /** Length of the summary's own words, without the wrapper. */
+ contentChars: number
+}
+
+/** The summary's own words, with no preamble and no headings. */
+export function summaryContentChars(s: CompactSummary): number {
+ return SECTIONS.reduce((n, sec) => n + s[sec.key].trim().length, 0) + s.rest.trim().length
+}
+
+/**
+ * Die kleinstmoegliche Zusammenfassung, in Zeichen — Huelle, Vorrede, eine
+ * Ueberschrift und gerade so viel Text, dass MIN_SUMMARY_CHARS erreicht ist.
+ *
+ * Nicht als Zahl hingeschrieben, sondern GERECHNET, ueber genau die Funktion,
+ * die auch die echte Fassung baut. Eine Konstante waere in dem Moment falsch,
+ * in dem jemand die Vorrede umformuliert, und niemand merkte es.
+ */
+export function minimalSummaryChars(): number {
+ return renderCompactSummary({
+ ...EMPTY_SUMMARY,
+ [SECTIONS[0].key]: 'x'.repeat(MIN_SUMMARY_CHARS),
+ }).length
+}
+
+/**
+ * Kann eine Zusammenfassung dieser Textmenge ueberhaupt kleiner sein als das,
+ * was sie ersetzt?
+ *
+ * Die Frage ist reine Arithmetik und laesst sich VOR dem Aufruf beantworten.
+ * Wer das kann und es trotzdem erst hinterher prueft, laesst ein lokales
+ * Modell umsonst rechnen — auf einem Laptop eine spuerbare Sekunde fuer nichts.
+ *
+ * Die Grenze in Zahlen (Stand 02.09.2026): die kleinste ueberhaupt baubare
+ * Fassung misst 269 Zeichen, davon 224 allein Marker und Vorrede. Bei
+ * MAX_SUMMARY_SHARE = 0.5 heisst das: unter rund 538 zu ersetzenden Zeichen
+ * kann NICHTS passen, egal wie gut das Modell arbeitet.
+ *
+ * Was diese Funktion NICHT leistet, und das gehoert hierher, weil der erste
+ * Entwurf genau das behauptete: sie faengt den gemessenen Beschwerdefall
+ * nicht. Der hatte 633 ersetzte Zeichen, liess also 316 zu, und die kleinste
+ * Fassung mit 269 haette gepasst — abgelehnt wurde erst die WIRKLICHE Antwort
+ * ueber zehn Turns. Diese Pruefung spart den aussichtslosen Aufruf, sie ersetzt
+ * die spaete Pruefung nicht. Der zweite Teil der Antwort auf jenen Fall ist
+ * die ehrliche Meldung in compactOutcomeMessage, nicht diese Rechnung.
+ */
+export function summaryCouldEverFit(replacedChars: number): boolean {
+ if (!(replacedChars > 0)) return true // ohne Bezugsgroesse greift die Regel gar nicht
+ return minimalSummaryChars() <= replacedChars * MAX_SUMMARY_SHARE
+}
+
+/**
+ * Is this summary worth using instead of the mechanical trim?
+ *
+ * Three ways to say no, and every one of them ends in the mechanical path
+ * rather than in an error. Compaction may never be the end of a run — the same
+ * rule the thinking downgrade follows (hooks/codex/thinking-downgrade.ts).
+ */
+export function isUsableSummary(input: UsabilityInput): UsabilityResult {
+ const rendered = renderCompactSummary(input.summary)
+ const renderedChars = rendered.length
+ const contentChars = summaryContentChars(input.summary)
+ if (isEmptySummary(input.summary)) {
+ return { usable: false, reason: 'empty', renderedChars, contentChars }
+ }
+ if (contentChars < MIN_SUMMARY_CHARS) {
+ return { usable: false, reason: 'too-short', renderedChars, contentChars }
+ }
+ // A "summary" the size of its source is a copy with a bill attached. This
+ // one measures the RENDERED length, because that is what every future
+ // request actually pays for.
+ if (input.replacedChars > 0 && renderedChars > input.replacedChars * MAX_SUMMARY_SHARE) {
+ return { usable: false, reason: 'not-smaller', renderedChars, contentChars }
+ }
+ return { usable: true, reason: 'ok', renderedChars, contentChars }
+}
+
+/** Estimated tokens a rendered summary will cost in every future request. */
+export function summaryTokens(s: CompactSummary): number {
+ const rendered = renderCompactSummary(s)
+ return rendered ? estimateTokens(rendered) : 0
+}
+
+// ── Anwenden ────────────────────────────────────────────────────────────────
+
+export interface ApplyCompactInput<T> {
+ /** The full outgoing history, system prompt first if there is one. */
+ messages: T[]
+ /** How many of the NEWEST messages stay verbatim behind the summary. */
+ keepRecent: number
+ summary: CompactSummary
+}
+
+export interface ApplyCompactResult<T> {
+ messages: T[]
+ /** How many messages the summary stands in for. 0 = nothing was applied. */
+ replaced: number
+ /** The summary as it went into the payload, or '' when none was applied. */
+ rendered: string
+}
+
+/** A tool RESULT, native or Hermes-shaped. A kept window may not begin with one. */
+function isToolResult(m: { role: string; content?: unknown }): boolean {
+ if (m.role === 'tool') return true
+ return (
+ m.role === 'user' && typeof m.content === 'string' && m.content.includes('<tool_response>')
+ )
+}
+
+/**
+ * Put the summary in front of the kept window.
+ *
+ * ── WHY THERE IS NO PINNED TASK HERE ───────────────────────────────────────
+ *
+ * The mechanical path pins the first user message, because its notice can only
+ * list tool NAMES and would otherwise lose what was asked (audit C5: a 30-step
+ * plan restarted at step 1 because the only thing left was the plan itself).
+ * A written summary does not need that crutch: TASK is its first section, and
+ * it is the model's own reading of what was asked rather than a verbatim turn
+ * that may itself have been superseded four times since. Pinning on top would
+ * mean sending the task twice, in two versions, and letting the model decide
+ * which one is current.
+ *
+ * ── WHY THE SUMMARY IS ANNOUNCED AS A SUMMARY ──────────────────────────────
+ *
+ * The wrapper says, in the payload, that this is a record of removed turns.
+ * That is not decoration. The lesson this codebase paid for is written at
+ * compactMessages: an 80-character slice of a file the agent had read was
+ * indistinguishable from the whole file, so the model edited against content
+ * it could no longer see. A summary carries the same danger the moment it can
+ * be mistaken for the material itself. Labelled, it cannot be.
+ */
+export function applyCompactSummary<T extends { role: string; content?: unknown }>(
+ input: ApplyCompactInput<T>,
+): ApplyCompactResult<T> {
+ const rendered = renderCompactSummary(input.summary)
+ if (!rendered) return { messages: input.messages, replaced: 0, rendered: '' }
+ const body = input.messages[0]?.role === 'system'
+ ? input.messages.length - 1
+ : input.messages.length
+ return spliceSummary(input.messages, body - Math.max(0, Math.floor(input.keepRecent)), rendered)
+}
+
+/**
+ * The half both appliers share: drop the first `dropLeading` body messages and
+ * put `rendered` in front of what is left.
+ *
+ * `dropLeading` rather than "keep the last N", because that is the quantity
+ * that stays true as the conversation grows — the fresh case converts once,
+ * the stored case derives it from its anchor, and neither has to re-derive the
+ * other's framing later.
+ */
+function spliceSummary<T extends { role: string; content?: unknown }>(
+ messages: T[],
+ dropLeading: number,
+ rendered: string,
+): ApplyCompactResult<T> {
+ const unchanged: ApplyCompactResult<T> = { messages, replaced: 0, rendered: '' }
+ if (!rendered || dropLeading <= 0) return unchanged
+
+ const hasSystem = messages[0]?.role === 'system'
+ const body = hasSystem ? messages.slice(1) : messages
+ if (dropLeading >= body.length) return unchanged
+
+ const kept = body.slice(dropLeading)
+ // A kept window may not open on a tool result whose call was dropped with
+ // the rest — strict OpenAI-compatible providers reject a result with no
+ // call in front of it. Same rule as compactMessages.
+ while (kept.length > 0 && isToolResult(kept[0])) kept.shift()
+
+ const replaced = body.length - kept.length
+ if (replaced <= 0) return unchanged
+
+ return {
+ messages: attachNoteToUserMaterial<T>({
+ system: hasSystem ? messages[0] : null,
+ pinned: null,
+ kept,
+ note: rendered,
+ strip: stripCompactSummary,
+ }),
+ replaced,
+ rendered,
+ }
+}
+
+// ── Aus einem gespeicherten Eintrag ────────────────────────────────────────
+
+/** The stored shape this module needs. Mirrors types/chat.ts CompactionRecord. */
+export interface StoredCompaction {
+ summary: string
+ upToMessageId: string
+}
+
+/** The message shape this module needs to find the cut. */
+export interface IdentifiedMessage {
+ id?: string
+ role: string
+ content?: unknown
+}
+
+/**
+ * Apply a compaction that already happened.
+ *
+ * Takes the RENDERED summary from the record rather than re-rendering, so what
+ * the transcript block shows and what the model receives are the same bytes by
+ * construction rather than by two code paths agreeing.
+ *
+ * A record whose anchor message is gone — deleted, or filtered out before this
+ * call — returns the array untouched. That is deliberate and it is the reason
+ * the anchor is an id: a stale record is detectable, and the honest answer to
+ * "I no longer know where this summary ends" is to send the real history.
+ */
+export function applyStoredCompaction<T extends IdentifiedMessage>(
+ messages: T[],
+ record: StoredCompaction | null | undefined,
+): ApplyCompactResult<T> {
+ if (!record?.summary || !record.upToMessageId) {
+ return { messages, replaced: 0, rendered: '' }
+ }
+ const body = messages[0]?.role === 'system' ? messages.slice(1) : messages
+ const cut = body.findIndex((m) => m.id === record.upToMessageId)
+ if (cut < 0) return { messages, replaced: 0, rendered: '' }
+ return spliceSummary(messages as unknown as Array<T & { role: string }>, cut + 1, record.summary) as ApplyCompactResult<T>
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Die Anzeige-Haelfte
+//
+// Der Verlauf behaelt nach einer Verdichtung ALLES. Verdichtet wird die
+// Nutzlast, nicht das Gedaechtnis des Nutzers — die alten Nachrichten stehen
+// weiter da, oben, lesbar, kopierbar. Sichtbar wird nur die SCHNITTSTELLE:
+// eine Zeile an der Stelle, ab der das Modell statt der Turns die
+// Zusammenfassung sieht.
+//
+// Diese Funktionen gehoeren hierher und nicht in die Komponente, weil sie das
+// Format kennen muessen. Eine Komponente, die `[compacted-context]` selbst
+// wegschneidet, ist beim naechsten Formatwechsel still kaputt; hier steht sie
+// neben dem Aufbau und faellt mit ihm zusammen um.
+// ───────────────────────────────────────────────────────────────────────────
+
+/** Eine Ueberschrift mit ihrem Text, so wie sie angezeigt werden soll. */
+export interface SummarySection {
+ heading: string
+ body: string
+}
+
+/**
+ * Der reine Inhalt einer gerenderten Zusammenfassung: ohne Marker, ohne
+ * Praeambel.
+ *
+ * Absichtlich nachsichtig. Ein gespeicherter Datensatz kann aus einer
+ * frueheren Fassung stammen, in der die Praeambel anders lautete oder die
+ * Marker fehlten. Beides fuehrt hier nicht zu einem Fehler, sondern nur dazu,
+ * dass etwas mehr Text stehen bleibt — das ist die richtige Richtung, denn
+ * eine alte Zusammenfassung zu ZEIGEN ist immer besser, als sie mit einer
+ * strengen Erkennung ganz zu verschlucken.
+ */
+export function compactSummaryBody(rendered: string): string {
+ let t = (rendered || '').trim()
+ if (!t) return ''
+ const open = t.indexOf(COMPACT_OPEN)
+ if (open !== -1) t = t.slice(open + COMPACT_OPEN.length)
+ const close = t.indexOf(COMPACT_CLOSE)
+ if (close !== -1) t = t.slice(0, close)
+ t = t.trim()
+ if (t.startsWith(COMPACT_PREAMBLE)) t = t.slice(COMPACT_PREAMBLE.length).trim()
+ return t
+}
+
+/**
+ * Die Abschnitte einer gespeicherten Zusammenfassung, in der Reihenfolge der
+ * Leiter, leere weggelassen.
+ *
+ * `NOTES` bekommt eine Sonderbehandlung: der Aufbau schreibt es als
+ * Ueberschrift, aber es steht nicht in SECTIONS (es IST der Rest, nicht ein
+ * benanntes Feld). Ohne diesen Schnitt zeigte die Anzeige das Wort NOTES als
+ * erste Zeile des Textes an, was wie ein Formatfehler des Modells aussieht,
+ * obwohl wir es selbst hingeschrieben haben.
+ */
+export function summarySections(rendered: string): SummarySection[] {
+ const inner = compactSummaryBody(rendered)
+ if (!inner) return []
+ const parsed = parseCompactSummary(inner)
+ const out: SummarySection[] = []
+ for (const sec of SECTIONS) {
+ const body = parsed[sec.key].trim()
+ if (body) out.push({ heading: sec.heading, body })
+ }
+ // Kein Nachschneiden mehr: seit parseCompactSummary REST_HEADING kennt,
+ // steht in `rest` der Text und nicht mehr die Ueberschrift davor. Die frueher
+ // hier stehende replace-Zeile war fuer alles, was renderCompactSummary
+ // erzeugt, ohnehin tot — sie hat einen Fehler kaschiert, statt ihn zu
+ // beheben, und genau das hat ihn so lange am Leben gehalten.
+ const rest = parsed.rest.trim()
+ if (rest) out.push({ heading: REST_HEADING, body: rest })
+ return out
+}
+
+/**
+ * Wo im sichtbaren Verlauf die Linien einer Verdichtung stehen: je sichtbarer
+ * Nachricht die Datensaetze, die NACH ihr angezeigt werden.
+ *
+ * Drei Faelle, die diese Funktion ueberhaupt noetig machen:
+ *
+ * 1. Der Schnittpunkt ist unsichtbar. `upToMessageId` kann auf eine
+ * Systemnachricht oder eine ausgeblendete zeigen; der Verlauf filtert
+ * beide weg. Die Linie wandert dann auf die letzte SICHTBARE Nachricht
+ * davor — an der richtigen Stelle, nur eine Zeile hoeher.
+ * 2. Der Schnittpunkt ist geloescht. Dann gibt es keine ehrliche Stelle mehr,
+ * und der Datensatz wird uebersprungen. Ihn ersatzweise oben oder unten
+ * anzuhaengen waere schlimmer als ihn wegzulassen: eine Linie an einer
+ * falschen Stelle behauptet etwas ueber den Verlauf, was nicht stimmt.
+ * 3. Zwei Verdichtungen landen auf derselben Zeile. Passiert, wenn zwischen
+ * ihnen nur unsichtbare Nachrichten liegen. Beide werden gezeigt, in ihrer
+ * Reihenfolge — nicht die letzte allein, denn dann verschwaende die
+ * Anzeige genau die Information, dass zweimal verdichtet wurde.
+ *
+ * Reine Rechnung ueber IDs, kein React: dieselbe Entscheidung wie beim
+ * Datensatz selbst, der eine ID und keinen Index traegt.
+ */
+export function compactionAnchors<T extends IdentifiedMessage, R extends StoredCompaction>(
+ allMessages: readonly T[],
+ visibleIds: readonly string[],
+ compactions: readonly R[] | undefined,
+): Map<string, R[]> {
+ const out = new Map<string, R[]>()
+ if (!compactions?.length || !visibleIds.length) return out
+
+ const visible = new Set(visibleIds)
+ for (const record of compactions) {
+ const cut = allMessages.findIndex((m) => m.id === record.upToMessageId)
+ if (cut === -1) continue // Fall 2: der Schnittpunkt existiert nicht mehr.
+
+ let anchor: string | undefined
+ for (let i = cut; i >= 0; i--) {
+ const id = allMessages[i]?.id
+ if (id && visible.has(id)) { anchor = id; break }
+ }
+ if (!anchor) continue // alles davor unsichtbar — es gibt keine Linie zu ziehen.
+
+ const list = out.get(anchor)
+ if (list) list.push(record)
+ else out.set(anchor, [record])
+ }
+ return out
+}
diff --git a/src/lib/compact-trigger.ts b/src/lib/compact-trigger.ts
new file mode 100644
index 00000000..2ef53bb7
--- /dev/null
+++ b/src/lib/compact-trigger.ts
@@ -0,0 +1,262 @@
+/**
+ * The auto-compact decision — one place, one answer (2.6.8, Compact step 1).
+ *
+ * Everything needed to make this call already existed and was already correct;
+ * what was missing was the call itself. `computeContextFill` (token-usage.ts)
+ * gives the numerator and says how trustworthy it is; `useActiveContextWindow`
+ * gives the denominator and says whether it is the model's real, confirmed
+ * window or a fallback. Nothing read either of those two flags. This module is
+ * the reader.
+ *
+ * Leaf module by contract: no React, no network, no store. Every input is a
+ * number or a flag the caller already holds, so the whole decision unit-tests
+ * without a renderer and without a backend — the same shape as send-window.ts
+ * and context-window.ts, which it sits beside.
+ *
+ * ── OPT-IN, AND WHY THAT IS THE WHOLE DESIGN ───────────────────────────────
+ *
+ * Owner decision, 2026-09-02: "einstellbar sonst aus". There is deliberately
+ * NO default threshold. Without one, `shouldCompact` is false forever and this
+ * module changes nothing about how the app behaves — the mechanical trim in
+ * context-compaction.ts keeps running exactly as it does today, and it stays
+ * the safety net underneath.
+ *
+ * That is not timidity, it is what makes the feature supportable: auto-compact
+ * replaces conversation history with a model's summary of it. When the summary
+ * is wrong the user loses work, and they lose it silently. A feature with that
+ * failure mode earns its default-on only after the field says it works.
+ *
+ * ── THE CONFIDENCE MARGIN ──────────────────────────────────────────────────
+ *
+ * A threshold is a claim about a ratio, and the ratio is only as good as its
+ * two halves. Both halves can be estimates, and — this is the part that
+ * matters — BOTH of their errors point the same way:
+ *
+ * - The numerator under-reads. `estimateTokens` is `chars / 4`, calibrated
+ * on English prose. Code, JSON, tool results and non-English text all
+ * tokenize denser than that, so the estimate says "less" than the truth.
+ * - The denominator over-reads. A window that is not `isTrue` is a fallback
+ * guess, and the fallbacks in useActiveContextWindow (the model's
+ * advertised max, DEFAULT_CONTEXT_CAP, 8192) are all ceilings, not floors.
+ *
+ * A ratio built from a low numerator and a high denominator is low. So on the
+ * least reliable inputs, a 0.8 threshold is really being applied at something
+ * above 0.8 of the actual window — which is the one direction that must not
+ * happen, because past the actual window there is no compaction any more,
+ * there is a truncated prompt or a 400.
+ *
+ * Hence the margin: the shakier the inputs, the earlier the effective
+ * threshold. The margins are NOT stacked. A numerator estimate and a window
+ * guess are two symptoms of the same situation (a local backend that has not
+ * reported anything yet), and adding them would put a user's 0.8 at 0.6 —
+ * far enough off the setting that the number in Settings would stop meaning
+ * anything. The worst single margin applies.
+ */
+
+/** Where the fill number came from. Mirrors ContextFill['source']. */
+export type FillSource = 'built' | 'usage' | 'estimate'
+
+/**
+ * Margin subtracted from the user's threshold, by how much the numerator can
+ * be trusted.
+ *
+ * - `built`: the number IS the payload the builder last built — decay, plan
+ * pruning and compaction included. Nothing to correct for.
+ * - `usage` + real: anchored on the model's own reported promptTokens, with
+ * only the tail since that turn estimated. A small correction covers the
+ * tail.
+ * - `usage` + estimated: anchored on a provisional usage the agent path
+ * wrote, i.e. an estimate wearing a usage's clothes.
+ * - `estimate`: chars/4 over the whole visible conversation, nothing else.
+ */
+export const MARGIN_BUILT = 0
+export const MARGIN_USAGE_REAL = 0.03
+export const MARGIN_USAGE_ESTIMATED = 0.08
+export const MARGIN_ESTIMATE = 0.12
+
+/** Margin for a denominator that is a fallback rather than the live window. */
+export const MARGIN_WINDOW_GUESSED = 0.08
+
+/**
+ * Floor for the effective threshold. A user may set a low threshold on
+ * purpose; the margin must not turn a deliberate 0.3 into a 0.18 that
+ * compacts a conversation that has barely started.
+ */
+export const MIN_EFFECTIVE_THRESHOLD = 0.25
+
+/** Bounds of a threshold the UI may hand in. Outside these it reads as off. */
+export const MIN_THRESHOLD = 0.3
+export const MAX_THRESHOLD = 0.95
+
+/**
+ * Fewer messages than this and there is nothing worth summarizing: the
+ * mechanical suffix window keeps KEEP_RECENT (4) untouched anyway, so a
+ * summary would be written about at most a handful of turns and would very
+ * likely be longer than what it replaced.
+ */
+export const MIN_MESSAGES_TO_COMPACT = 8
+
+/**
+ * Messages that must arrive after a compaction before another one may fire.
+ *
+ * Without this, a conversation whose ratio stays above the threshold even
+ * AFTER summarizing — one giant tool result is enough — compacts on every
+ * single turn: a summary of a summary of a summary, each one paid for, each
+ * one further from what actually happened. It is the same failure the
+ * mechanical path solved with COMPACT_TRIGGER_RATIO / COMPACT_TARGET_RATIO
+ * hysteresis, in the currency this decision is denominated in (messages, not
+ * tokens), because that is what the caller can count without rebuilding the
+ * request.
+ */
+export const MIN_MESSAGES_SINCE_COMPACT = 6
+
+export interface CompactTriggerInput {
+ /** computeContextFill().used — tokens the next request will carry. */
+ used: number
+ /** The honest denominator: ctx.sendWindow, else ctx.contextWindow. */
+ window: number
+ /** computeContextFill().source. */
+ source: FillSource
+ /** computeContextFill().real — the usage anchor was not itself an estimate. */
+ real: boolean
+ /** ctx.isTrue — the window is the live one, not a fallback. */
+ windowIsTrue: boolean
+ /** Messages in the conversation right now. */
+ messageCount: number
+ /**
+ * settings.autoCompactThreshold. Undefined, 0, or outside
+ * [MIN_THRESHOLD, MAX_THRESHOLD] means the feature is off.
+ */
+ threshold?: number
+ /**
+ * Messages in the conversation at the last compaction, if there was one.
+ * Undefined = never compacted.
+ */
+ lastCompactAtMessageCount?: number
+}
+
+export type CompactTriggerReason =
+ | 'off' // no usable threshold — the opt-in was never taken
+ | 'no-window' // denominator not resolved yet; a ratio would be a fiction
+ | 'too-short' // nothing worth summarizing
+ | 'cooldown' // compacted too recently
+ | 'below' // under the effective threshold
+ | 'over' // fire
+
+export interface CompactTriggerResult {
+ shouldCompact: boolean
+ /** used / window, or 0 when there is no window. Uncapped, so it may exceed 1. */
+ ratio: number
+ /** The threshold after the confidence margin — what `ratio` was compared to. */
+ effectiveThreshold: number
+ /** The margin that was applied, so the UI can explain an early trigger. */
+ margin: number
+ reason: CompactTriggerReason
+}
+
+/** The margin the numerator's provenance earns. */
+export function numeratorMargin(source: FillSource, real: boolean): number {
+ if (source === 'built') return MARGIN_BUILT
+ if (source === 'usage') return real ? MARGIN_USAGE_REAL : MARGIN_USAGE_ESTIMATED
+ return MARGIN_ESTIMATE
+}
+
+/**
+ * The single margin for this pair of inputs: the worst one, never the sum.
+ * See the module head, "THE CONFIDENCE MARGIN".
+ */
+export function confidenceMargin(input: {
+ source: FillSource
+ real: boolean
+ windowIsTrue: boolean
+}): number {
+ return Math.max(
+ numeratorMargin(input.source, input.real),
+ input.windowIsTrue ? 0 : MARGIN_WINDOW_GUESSED,
+ )
+}
+
+/** A threshold the user actually opted into, or null. */
+export function usableThreshold(threshold?: number): number | null {
+ if (typeof threshold !== 'number' || !Number.isFinite(threshold)) return null
+ if (threshold < MIN_THRESHOLD || threshold > MAX_THRESHOLD) return null
+ return threshold
+}
+
+/**
+ * Should this conversation be compacted before the next send?
+ *
+ * Pure. The caller resolves the numbers (TokenCounter already resolves both of
+ * them for its own display) and acts on the answer; nothing here reads or
+ * writes anything.
+ */
+export function shouldAutoCompact(input: CompactTriggerInput): CompactTriggerResult {
+ const threshold = usableThreshold(input.threshold)
+ const margin = confidenceMargin(input)
+ const effectiveThreshold = threshold === null
+ ? 0
+ : Math.max(MIN_EFFECTIVE_THRESHOLD, threshold - margin)
+ const ratio = input.window > 0 ? input.used / input.window : 0
+ const no = (reason: CompactTriggerReason): CompactTriggerResult => ({
+ shouldCompact: false, ratio, effectiveThreshold, margin, reason,
+ })
+
+ if (threshold === null) return no('off')
+ // A ratio over a denominator that is still being probed is not a small
+ // 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')
+ if (
+ input.lastCompactAtMessageCount !== undefined &&
+ input.messageCount - input.lastCompactAtMessageCount < MIN_MESSAGES_SINCE_COMPACT
+ ) {
+ return no('cooldown')
+ }
+ if (ratio < effectiveThreshold) return no('below')
+
+ return { shouldCompact: true, ratio, effectiveThreshold, margin, reason: 'over' }
+}
+
+
+/**
+ * Der Satz "wie weit ist es noch bis zur automatischen Kompaktierung".
+ *
+ * ── WARUM DAS HIER STEHT UND NICHT IM BAUTEIL ──────────────────────────────
+ *
+ * Erstens sammelt vitest nur Dateien unter `__tests__` mit der Endung
+ * `.test.ts`; was in einer `.tsx` steht, hat keinen Test, der es je
+ * ausfuehrt. Zweitens gehoert dieser Text zur Schwelle und nicht zum Balken: er soll spaeter auch in einer
+ * Statuszeile und im Compact-Menue auftauchen koennen, ohne dass jemand ihn
+ * ein zweites Mal formuliert.
+ *
+ * ── WARUM DIE WIRKSAME UND NICHT DIE EINGESTELLTE SCHWELLE ─────────────────
+ *
+ * `shouldAutoCompact` zieht einen Sicherheitsabschlag ab, solange der
+ * Fuellstand nur geschaetzt ist. Wer hier die eingestellte Zahl anzeigte,
+ * naennte im haeufigsten Fall — kein echter Usage-Report — eine Prozentzahl,
+ * bei der nichts passiert. Darum bekommt diese Funktion das fertige URTEIL
+ * herein und rechnet nicht selbst.
+ */
+export function autoCompactHint(verdict: CompactTriggerResult | null): string {
+ if (!verdict) return ''
+ if (verdict.shouldCompact) return 'Auto-compaction triggers on the next message'
+ switch (verdict.reason) {
+ case 'off':
+ return ''
+ case 'cooldown':
+ return 'Auto-compaction is on, paused briefly after the last summary'
+ case 'too-short':
+ return `Auto-compaction is on, but starts only from ${MIN_MESSAGES_TO_COMPACT} messages`
+ case 'no-window':
+ // Das Fenster wird noch abgefragt. Eine Prozentzahl auf einen Nenner,
+ // den niemand kennt, waere eine erfundene Zahl.
+ return 'Auto-compaction is on, waiting for the model to report its context window'
+ default: {
+ // In Prozentpunkten DES FENSTERS, nicht als Anteil der Restspanne:
+ // "noch 23 % frei" ist die Zahl, die der Nutzer am Balken wiederfindet.
+ const rest = Math.max(0, Math.round((verdict.effectiveThreshold - verdict.ratio) * 100))
+ return `${rest}% of the window left before auto-compaction`
+ }
+ }
+}
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 96633ff9..0a95c103 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -39,6 +39,10 @@ export const DEFAULT_SETTINGS: Settings = {
// surfaces in finite wall-clock.
agentMaxToolCalls: 400,
agentMaxIterations: 200,
+ // Die heutigen festen Werte aus sub-agent.ts, unveraendert uebernommen:
+ // wer nichts einstellt, bekommt exakt das Verhalten von 2.6.7.
+ subAgentMaxToolCalls: 10,
+ subAgentMaxIterations: 5,
// Unlimited by design — see the note on the type.
loopMaxPasses: 0,
hfDownloadPathOverride: '',
@@ -52,6 +56,14 @@ export const DEFAULT_SETTINGS: Settings = {
// default; the switch is the support way back without a rollback release.
contextDecay: true,
codexSendWindowTokens: 64000,
+ // 2.6.8: auto-compact is OFF until someone sets a threshold. 0 is the
+ // switch, not a tuning value — see the field's comment in types/settings.ts.
+ // No STORE_VERSION bump for this key: settingsStore's migrate merges
+ // additively ({...DEFAULT_SETTINGS, ...stored}), and a profile already at
+ // the current version simply reads `undefined` here, which usableThreshold
+ // already answers with "off". A version bump that buys nothing costs a full
+ // state loss on downgrade (lib/persist-version.ts, DOWNGRADE-KONTRAKT).
+ autoCompactThreshold: 0,
memoryCloudOptIn: false,
codexDefaultMode: 'ask' as const,
builtinEngine: {
diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.ts
index 8eb6ac58..ae43c30f 100644
--- a/src/lib/context-compaction.ts
+++ b/src/lib/context-compaction.ts
@@ -8,7 +8,7 @@
* - Token estimation via heuristic: text.length / 4
*/
-import { getModelContext } from '../api/ollama'
+import { getModelContextCached } from '../api/ollama'
import { getProviderForModel, getProviderIdFromModel } from '../api/providers'
import { useModelStore } from '../stores/modelStore'
import { truncateToolResult } from './truncate-tool-result'
@@ -67,8 +67,17 @@ export async function getModelMaxTokens(modelName: string): Promise<number> {
return await provider.getContextLength(modelId)
}
- // Ollama: use existing endpoint
- return await getModelContext(modelName)
+ // Ollama: use existing endpoint, through the cache.
+ //
+ // Uncached this was one /api/show per call, and 2.6.8 Compact-Schritt 2
+ // gives the group path a reason to ask once per model per ROUND. The
+ // value cached is the model file's trained context length, which does not
+ // change while the app runs; the user's override is a separate lever and
+ // is applied by effectiveContextWindow, downstream of this. Two other
+ // readers of exactly this number — useChat's own num_ctx resolution and
+ // useActiveContextWindow — already go through the same cache, so this
+ // removes an inconsistency rather than adding a risk.
+ return await getModelContextCached(modelName)
} catch {
return 4096
}
@@ -151,6 +160,70 @@ function isToolResultMessage(msg: OllamaChatMessage): boolean {
return false
}
+/**
+ * WHERE A CARRIED NOTE IS ALLOWED TO SIT — the one rule, one place.
+ *
+ * Anything a compaction wants to tell the model afterwards (the mechanical
+ * trim notice, and since 2.6.8 the written summary) has the same problem: it
+ * is instruction-shaped, so `role: 'system'` is the obvious home, and
+ * `role: 'system'` is exactly what it may not be. A system message anywhere
+ * but index 0 is refused outright by strict Jinja chat templates — "System
+ * message must be at the beginning" (platorius, Discord #bug-reports
+ * 2026-08-21, and the reason it only showed up in LU was that compaction only
+ * fires once a history is long).
+ *
+ * So the note rides on USER material, in this order of preference:
+ * 1. appended to the pinned task, when the pin is being re-added anyway —
+ * the note and the task belong together and cost one message instead of
+ * two;
+ * 2. else prefixed to the first kept user turn;
+ * 3. else as its own user turn.
+ *
+ * Extracted in 2.6.8 because the written summary needs the identical rule.
+ * Two copies of a placement rule whose whole purpose is "there is exactly one
+ * legal position" is how the second copy ends up in the illegal one.
+ */
+export interface CarriedNoteInput<T> {
+ /** The system prompt, if any. Always ends up at index 0 and nowhere else. */
+ system: T | null
+ /** The pinned first user turn, when it has to be re-added ahead of the window. */
+ pinned: T | null
+ /** The kept suffix, newest material, in order. */
+ kept: T[]
+ /** The note to carry, or null when there is nothing to say. */
+ note: string | null
+ /** Removes an earlier note of the same kind from a body, so notes never stack. */
+ strip?: (text: string) => string
+}
+
+export function attachNoteToUserMaterial<T extends { role: string; content?: unknown }>(
+ input: CarriedNoteInput<T>,
+): T[] {
+ const strip = input.strip ?? ((t: string) => t)
+ const out: T[] = []
+ if (input.system) out.push(input.system)
+ const kept = [...input.kept]
+ let note = input.note
+
+ if (input.pinned) {
+ out.push(
+ note
+ ? ({ ...input.pinned, content: `${String(input.pinned.content ?? '')}\n\n${note}` } as T)
+ : input.pinned,
+ )
+ note = null
+ }
+ if (note) {
+ if (kept[0]?.role === 'user' && typeof kept[0].content === 'string') {
+ kept[0] = { ...kept[0], content: `${note}\n\n${strip(kept[0].content)}` } as T
+ } else {
+ out.push({ role: 'user', content: note } as unknown as T)
+ }
+ }
+ out.push(...kept)
+ return out
+}
+
/**
* Compact a message array to fit within a token budget.
*
@@ -312,8 +385,6 @@ export function compactMessages(
const pinNeeded = pinnedTask !== null && !kept.includes(capped[firstUserIdx])
const droppedCount = capped.length - kept.length - (pinNeeded ? 1 : 0)
- const compacted: OllamaChatMessage[] = []
- if (systemMsg) compacted.push(systemMsg)
let notice: string | null = null
if (droppedCount > 0) {
// What was dropped is exactly the record of the work already done, while
@@ -344,26 +415,14 @@ export function compactMessages(
}
// The notice used to be its own role:'system' message pushed right here,
- // between the pin and the window — a system message mid conversation, which
- // strict Jinja chat templates refuse with "System message must be at the
- // beginning" (platorius, Discord #bug-reports 2026-08-21: "the problem is
- // only in LU", same prompts fine elsewhere because compaction only fires
- // once the history is long). It now rides inside user material: appended to
- // the pinned task, else prefixed to the first kept user turn, else as its
- // own user turn. After compaction, system only ever sits at index 0.
- if (pinNeeded && pinnedTask) {
- compacted.push(
- notice ? { ...pinnedTask, content: `${pinnedTask.content}\n\n${notice}` } : pinnedTask,
- )
- notice = null
- }
- if (notice) {
- if (kept[0]?.role === 'user' && typeof kept[0].content === 'string') {
- kept[0] = { ...kept[0], content: `${notice}\n\n${stripTrimNotice(kept[0].content)}` }
- } else {
- compacted.push({ role: 'user', content: notice })
- }
- }
- compacted.push(...kept)
- return compacted
+ // between the pin and the window. Why that is forbidden, and where it goes
+ // instead, is now documented once at attachNoteToUserMaterial above — the
+ // written summary of 2.6.8 obeys the identical rule through the same call.
+ return attachNoteToUserMaterial<OllamaChatMessage>({
+ system: systemMsg,
+ pinned: pinNeeded ? pinnedTask : null,
+ kept,
+ note: notice,
+ strip: stripTrimNotice,
+ })
}
diff --git a/src/lib/run-compact-command.ts b/src/lib/run-compact-command.ts
new file mode 100644
index 00000000..d8909129
--- /dev/null
+++ b/src/lib/run-compact-command.ts
@@ -0,0 +1,402 @@
+/**
+ * One compaction, from any surface (2.6.8, Compact-Schritt 4).
+ *
+ * Three hooks need this — plain chat, the agent loop and the coding loop — and
+ * the old guard in agent-commands.test.ts named the exact failure of not
+ * sharing it: "a second locally-handled command would need its own branch in
+ * three hooks and would silently no-op if it did not get one". Three branches
+ * are unavoidable (each hook owns its own transcript and its own abort), but
+ * three implementations are not. This is the one implementation; a branch is
+ * four lines.
+ *
+ * ── WHAT A COMPACTION ACTUALLY IS HERE ─────────────────────────────────────
+ *
+ * It is a RECORD, not an edit. Nothing is removed from the store, from the
+ * visible transcript, or from any export. The record says "everything up to
+ * this message is represented by this summary", and the payload builders read
+ * it when they assemble the next request. That is what makes the whole feature
+ * reversible: delete the record and the next request carries the full history
+ * again, byte for byte.
+ *
+ * It is also the reason the summary can be shown to the user without a second
+ * source of truth — the block in the transcript renders the same string the
+ * model receives.
+ */
+
+import { v4 as uuid } from 'uuid'
+import { useChatStore } from '../stores/chatStore'
+import { useSettingsStore } from '../stores/settingsStore'
+import { getProviderForModel, getProviderIdFromModel } from '../api/providers'
+import { resolveAgentNumCtxWithConfidence } from './agent-num-ctx'
+import { runCompactSummary, type CompactRunReason } from './compact-run'
+import {
+ renderCompactSummary,
+ stripCompactSummary,
+ summaryTokens,
+ type TranscriptTurn,
+} from './compact-summary'
+import { estimateTokens } from './context-compaction'
+import { computeContextFill, type FillMessage } from './token-usage'
+import { shouldAutoCompact, MIN_MESSAGES_SINCE_COMPACT } from './compact-trigger'
+import { effectiveSendWindow } from './send-window'
+import { useSendSizeStore } from '../stores/sendSizeStore'
+import type { CompactionRecord, Message } from '../types/chat'
+
+/**
+ * How many of the newest messages stay verbatim behind a summary.
+ *
+ * The mechanical path keeps KEEP_RECENT (4) as a floor under a budget-driven
+ * window. Here the summary carries everything older, so this number answers a
+ * different question: how much immediate thread does the model need in its own
+ * words? Three exchanges. Fewer, and a follow-up like "do that again but
+ * smaller" loses what "that" was; more, and the compaction stops paying for
+ * itself on exactly the short-turn conversations that trip the count cap.
+ */
+export const KEEP_AFTER_COMPACT = 6
+
+export type CompactOutcome =
+ | { ok: true; record: CompactionRecord }
+ | { ok: false; reason: CompactRunReason | 'no-conversation' | 'nothing-to-compact'; detail?: string }
+
+/** A stored message the model actually saw. App notices never reach a model. */
+export function isModelVisible(m: Message): boolean {
+ return m.role !== 'system' && typeof m.content === 'string' && m.content.trim() !== ''
+}
+
+/**
+ * Run one compaction on a conversation and record it.
+ *
+ * Never throws. On any failure the caller keeps the conversation exactly as it
+ * was — the mechanical trim is still underneath and still does its job, which
+ * is what makes a failed compaction cost a round trip and nothing else.
+ */
+export async function runCompactForConversation(opts: {
+ conversationId: string
+ /**
+ * Darf null sein. Das ist kein Nachgeben gegenueber einem Aufrufer, der es
+ * nicht besser weiss, sondern die richtige Stelle fuer die Frage: ob ein
+ * Modell aktiv ist, entscheidet ueber den Ausgang dieses Laufs, und der
+ * Ausgang gehoert hierher. Jeder Aufrufer haette sonst dieselbe Pruefung
+ * davorgesetzt — und der naechste haette sie vergessen.
+ */
+ activeModel: string | null
+ trigger: 'manual' | 'auto'
+ focus?: string
+ signal?: AbortSignal
+}): Promise<CompactOutcome> {
+ if (!opts.activeModel) return { ok: false, reason: 'no-model' }
+
+ const store = useChatStore.getState()
+ const conv = store.conversations.find((c) => c.id === opts.conversationId)
+ if (!conv) return { ok: false, reason: 'no-conversation' }
+
+ const visible = conv.messages.filter(isModelVisible)
+ const cutAt = visible.length - KEEP_AFTER_COMPACT
+ if (cutAt <= 0) return { ok: false, reason: 'nothing-to-compact' }
+
+ // Do not re-summarise material an earlier summary already covers: that is
+ // the summary-of-a-summary decay this feature is designed to avoid. The cut
+ // starts after the newest record's anchor.
+ const previous = conv.compactions?.[conv.compactions.length - 1]
+ const prevIdx = previous
+ ? visible.findIndex((m) => m.id === previous.upToMessageId)
+ : -1
+ const from = prevIdx >= 0 ? prevIdx + 1 : 0
+ // Zwei Wege enden hier, und sie bedeuten Verschiedenes. Der erste (oben)
+ // heisst „der Chat ist zu kurz". Dieser heisst „seit der letzten
+ // Verdichtung ist zu wenig dazugekommen" — und dem Nutzer zu sagen, sein
+ // Chat sei „still short enough to send whole", waehrend darueber eine
+ // Verdichtungslinie steht, ist schlicht falsch.
+ if (cutAt <= from) return { ok: false, reason: 'nothing-to-compact', detail: 'already-compacted' }
+
+ const covered = visible.slice(from, cutAt)
+ const anchor = covered[covered.length - 1]
+ const turns: TranscriptTurn[] = covered.map((m) => ({
+ role: m.role,
+ // An earlier summary riding inside a stored turn would otherwise be read
+ // back as transcript and folded into the new one.
+ content: stripCompactSummary(m.content),
+ }))
+
+ const result = await runCompactSummary({
+ turns,
+ activeModel: opts.activeModel,
+ focus: opts.focus,
+ contextWindowOverride: useSettingsStore.getState().settings.contextWindowOverride,
+ signal: opts.signal,
+ })
+ if (!result.ok) return { ok: false, reason: result.reason, detail: result.detail }
+
+ const record: CompactionRecord = {
+ id: uuid(),
+ summary: renderCompactSummary(result.summary),
+ upToMessageId: anchor.id,
+ replaced: covered.length,
+ atMessageCount: conv.messages.length,
+ tokensBefore: turns.reduce((n, t) => n + estimateTokens(t.content) + 4, 0),
+ tokensAfter: summaryTokens(result.summary),
+ trigger: opts.trigger,
+ at: Date.now(),
+ }
+ // Re-read the store: the conversation may have been deleted while the model
+ // was writing. recordCompaction is a no-op on a missing id, but reporting
+ // success for a chat that no longer exists would be a lie to the caller.
+ if (!useChatStore.getState().conversations.some((c) => c.id === opts.conversationId)) {
+ return { ok: false, reason: 'no-conversation' }
+ }
+ useChatStore.getState().recordCompaction(opts.conversationId, record)
+ return { ok: true, record }
+}
+
+/** The newest record, or undefined. Only the newest shapes a payload. */
+export function newestCompaction(
+ compactions: CompactionRecord[] | undefined,
+): CompactionRecord | undefined {
+ return compactions?.length ? compactions[compactions.length - 1] : undefined
+}
+
+/** One line for the transcript, in the user's terms rather than the code's. */
+export function compactOutcomeMessage(outcome: CompactOutcome): string {
+ if (outcome.ok) {
+ const { replaced, tokensBefore, tokensAfter } = outcome.record
+ const saved = Math.max(0, tokensBefore - tokensAfter)
+ return `Summarised ${replaced} earlier message${replaced === 1 ? '' : 's'} — about ${saved.toLocaleString()} tokens less in every following request. The full conversation is still here; only what gets sent changed.`
+ }
+ switch (outcome.reason) {
+ case 'nothing-to-compact':
+ if (outcome.detail === 'already-compacted') {
+ return 'Nothing new to summarise — everything before the last summary is already covered, and the turns since then are the ones being kept.'
+ }
+ return 'Nothing to summarise yet — this conversation is still short enough to send whole.'
+ case 'no-conversation':
+ return 'That chat is gone, so there was nothing to summarise.'
+ case 'aborted':
+ return 'Stopped before the summary was written. Nothing changed.'
+ case 'no-model':
+ return 'No model is selected, so there is nothing to write the summary.'
+ case 'unusable':
+ // 'unusable' hat drei Ursachen, und nur zwei davon liegen beim Modell.
+ // 'not-smaller' heisst: die alten Turns sind so kurz, dass die Huelle
+ // der Zusammenfassung mehr kostet als der Text, den sie ersetzt. Das
+ // dem Modell anzulasten war schlicht unwahr — gemessen am 02.09.2026 an
+ // einem Chat, in dem nach Abzug von Marker und Vorrede 92 Zeichen fuer
+ // fuenf Abschnitte uebrig blieben.
+ if (outcome.detail === 'not-smaller') {
+ return 'These turns are already short — a summary would take up more room than they do, so nothing changed.'
+ }
+ return 'The model did not produce a usable summary, so nothing changed. Older turns still get shortened automatically when the context fills up.'
+ default:
+ return 'The summary could not be written, so nothing changed. Older turns still get shortened automatically when the context fills up.'
+ }
+}
+
+// ── Der automatische Auslöser ──────────────────────────────────────────────
+
+/**
+ * Compact before this send, if the user asked for that to happen.
+ *
+ * Called from every payload builder, and does nothing at all unless
+ * `autoCompactThreshold` is set — which is the whole shape of the opt-in.
+ * Returns the record when one was written, else null; the caller re-reads the
+ * conversation afterwards so the fresh record is applied to the payload it is
+ * about to build.
+ *
+ * ── WHY THE DECISION IS NOT MADE HERE ──────────────────────────────────────
+ *
+ * Everything this function does with numbers, it delegates: the fill comes
+ * from computeContextFill (which already knows how to anchor on a real usage
+ * report and how to say when it is only guessing), and the verdict comes from
+ * shouldAutoCompact (which owns the threshold, the confidence margin and the
+ * cooldown). What is left here is plumbing — read the store, ask, act, write.
+ * That split is what lets the hard part be unit-tested without a store, a
+ * provider or a renderer.
+ */
+export async function maybeAutoCompact(opts: {
+ conversationId: string
+ /** Siehe runCompactForConversation: null ist ein Ausgang, kein Fehler. */
+ activeModel: string | null
+ /**
+ * The honest denominator: the send window, else the model window. Omit it
+ * and this resolves the same number itself through resolveAgentNumCtx.
+ *
+ * The option exists because of where the two agent loops resolve theirs:
+ * AFTER they have built the message array, while this check has to run
+ * BEFORE. Passing it would have meant restructuring two 2000-line hooks and
+ * the 38 test files pinned to them. Resolving it here is not a second
+ * source — resolveAgentNumCtx is THE resolver, and it is the same call the
+ * loop makes a few lines later, cached, so both get the same number by
+ * construction rather than by agreement.
+ */
+ window?: number
+ /** Whether that window is the live one rather than a fallback guess. */
+ windowIsTrue?: boolean
+ signal?: AbortSignal
+}): Promise<CompactionRecord | null> {
+ const threshold = useSettingsStore.getState().settings.autoCompactThreshold
+ // The cheap question first: without an opt-in there is nothing to compute,
+ // and this runs on every single send.
+ if (!threshold) return null
+ // Ohne aktives Modell gibt es niemanden, der zusammenfassen koennte. Die
+ // Pruefung steht VOR dem Fenster-Aufloesen, denn das fragt das Modell.
+ if (!opts.activeModel) return null
+
+ const conv = useChatStore.getState().conversations.find((c) => c.id === opts.conversationId)
+ if (!conv) return null
+
+ const visible = conv.messages.filter(isModelVisible)
+ const sent = useSendSizeStore.getState().byConv[opts.conversationId]
+ // ── Warum hier die UNGEFILTERTE Liste steht ──────────────────────────────
+ //
+ // `atMessageCount` wird von beiden Agentenschleifen als
+ // `conversations.messages.length` aufgezeichnet — ungefiltert, App-Hinweise
+ // eingeschlossen. `computeContextFill` prueft `atMessageCount <= länge`, und
+ // mit der gefilterten Liste war diese Bedingung falsch, sobald auch nur EIN
+ // Hinweis im Chat stand: der Anker wurde verworfen, und die Fuellstandsquelle
+ // fiel stillschweigend von 'built' auf 'estimate' zurueck — eine andere Zahl,
+ // eine andere Sicherheitsmarge, und damit ein anderes Urteil als das, was der
+ // Nutzer am Balken sah. Der Token-Zaehler uebergab immer schon ungefiltert;
+ // die beiden liefen also genau dann auseinander, wenn die App selbst geredet
+ // hatte. Dass die Hinweise nicht mitzaehlen, erledigt jetzt
+ // `computeContextFill` selbst und fuer BEIDE Aufrufer gleich.
+ const fill = computeContextFill(
+ conv.messages as unknown as FillMessage[],
+ sent ? { tokens: sent.tokens + sent.toolsTokens, atMessageCount: sent.atMessageCount } : undefined,
+ )
+
+ let window = opts.window
+ let windowIsTrue = opts.windowIsTrue ?? false
+ if (window === undefined) {
+ const { modelId } = getProviderForModel(opts.activeModel)
+ // Der Aufloeser sagt jetzt selbst, ob er gemessen oder geraten hat. Hier
+ // stand `window !== 8192` — ein Ratespiel an der Zahl, und in beide
+ // Richtungen falsch: 8192 ist Ollamas Voreinstellung UND ein legitimer
+ // Override, ein wirklich mit 8192 laufendes Modell galt also dauerhaft
+ // als unsicher und wurde acht Prozentpunkte zu frueh zusammengefasst.
+ const aufgeloest = await resolveAgentNumCtxWithConfidence(
+ modelId,
+ getProviderIdFromModel(opts.activeModel),
+ useSettingsStore.getState().settings.contextWindowOverride,
+ opts.activeModel,
+ ).catch(() => ({ ctx: 0, gemessen: false }))
+ window = aufgeloest.ctx
+ windowIsTrue = window > 0 && aufgeloest.gemessen
+
+ // ── Derselbe Nenner wie in der Nutzlast, und nicht das Modellfenster ────
+ //
+ // `resolveAgentNumCtx` liefert, was das MODELL kann. Was die Schleife
+ // gleich darauf wirklich SENDET, ist weniger: `effectiveSendWindow` nimmt
+ // einen Anteil davon und, bei bezahlten Anbietern, hoechstens die
+ // eingestellte Kappe. Genau diese Zahl ist der Nenner des Fuellbalkens
+ // (useActiveContextWindow, "meter honesty"), und genau gegen sie baut die
+ // Schleife wenige Zeilen spaeter ihre Nachrichten (useAgentChat:898).
+ //
+ // Ohne diese Umrechnung rechnete die Anzeige gegen die Kappe und der
+ // Ausloeser gegen das Modellfenster. Gemessenes Beispiel: 200k-Modell,
+ // Kappe 64k, 60k belegt, Schwelle 0.8 — der Balken steht bei 94 % und
+ // sagt "triggers on the next message", der Ausloeser rechnet 0.3, urteilt
+ // 'below' und tut nie etwas. Dauerhaft, nicht nur einmal.
+ //
+ // NUR in diesem Zweig: wer `window` selbst uebergibt (der einfache Chat
+ // mit `modelWindowTokens`), hat seinen Nenner schon gewaehlt, und die
+ // Nutzlast des einfachen Chats kennt diese Kappe nicht.
+ const st = useSettingsStore.getState().settings
+ const gekappt = effectiveSendWindow({
+ providerId: getProviderIdFromModel(opts.activeModel),
+ modelWindow: window,
+ sendWindowTokens: st.codexSendWindowTokens,
+ capEnabled: st.contextDecay !== false,
+ smallModelMode: st.smallModelMode,
+ })
+ if (gekappt > 0) window = gekappt
+ }
+
+ const verdict = shouldAutoCompact({
+ used: fill.used,
+ window,
+ source: fill.source,
+ real: fill.real,
+ windowIsTrue,
+ messageCount: visible.length,
+ threshold,
+ lastCompactAtMessageCount: newestCompaction(conv.compactions)?.atMessageCount,
+ })
+ if (!verdict.shouldCompact) return null
+
+ const outcome = await runCompactForConversation({
+ conversationId: opts.conversationId,
+ activeModel: opts.activeModel,
+ trigger: 'auto',
+ signal: opts.signal,
+ })
+ if (!outcome.ok) meldeAutoFehlschlag(opts.conversationId, outcome)
+ return outcome.ok ? outcome.record : null
+}
+
+/**
+ * Sagt es, wenn eine automatische Kompaktierung schiefging.
+ *
+ * ── WARUM UEBERHAUPT ───────────────────────────────────────────────────────
+ *
+ * Der manuelle Weg schreibt sein Ergebnis immer in den Verlauf, gelungen wie
+ * misslungen — der Nutzer hat `/compact` getippt, er wartet auf eine Antwort.
+ * Der automatische schrieb bisher NUR im Erfolgsfall. Scheiterte er, gab
+ * `maybeAutoCompact` null zurueck und der Sendevorgang lief einfach weiter.
+ * Fuer den Nutzer sah das aus wie: "Auto-Kompaktierung ist an, der Kontext ist
+ * voll, und es passiert nichts." Beim naechsten Senden dasselbe, und beim
+ * uebernaechsten. Eine Einstellung, die stumm nicht tut, was sie verspricht,
+ * ist schlimmer als keine.
+ *
+ * ── WARUM NICHT JEDER AUSGANG ──────────────────────────────────────────────
+ *
+ * Gemeldet wird nur, was der Nutzer nicht schon weiss und was ein Problem
+ * ist. 'aborted' hat er selbst ausgeloest. 'nothing-to-compact' ist kein
+ * Fehlschlag, sondern die richtige Antwort — und weil dieser Weg VOR JEDEM
+ * SENDEN laeuft, waere eine Zeile dafuer eine Zeile pro Nachricht. Uebrig
+ * bleibt der Fall, der wirklich zaehlt: es haette gehen sollen und ging nicht.
+ *
+ * ── WARUM NICHT BEI JEDEM SENDEN, ABER AUCH NICHT NUR EINMAL ───────────────
+ *
+ * Die Ursache besteht meist fort — ein Modell, das keine brauchbare
+ * Zusammenfassung schreibt, schreibt beim naechsten Versuch auch keine. Ohne
+ * Bremse stuende die Warnung nach zehn Nachrichten zehnmal da.
+ *
+ * Die erste Fassung verglich gegen den LETZTEN Hinweis im Verlauf und war in
+ * beide Richtungen falsch, gefunden am 02.09.2026:
+ *
+ * ZU OFT: schiebt sich irgendein anderer Hinweis dazwischen — und seit dem
+ * selben Tag meldet sich JEDE fertige Hintergrundaufgabe als Hinweis —, ist
+ * die Warnung nicht mehr die letzte, und dieselbe Ursache schreibt sie neu.
+ * Mit fuenf Hintergrundagenten ueber eine Sitzung fuenfmal derselbe Satz.
+ *
+ * ZU SELTEN: warnt es bei Nachricht 20 und scheitert danach sechzig Mal
+ * weiter, bleibt es sechzig Nachrichten lang still, waehrend der Zaehler
+ * daneben unbeirrt "triggers on the next message" sagt. Also genau der
+ * Zustand, gegen den diese Warnung ueberhaupt gebaut wurde.
+ *
+ * Beides behebt derselbe Wechsel: gesucht wird gezielt die letzte EIGENE
+ * Warnung (am Id-Praefix, nicht am Text — `compactOutcomeMessage` buendelt
+ * mehrere Gruende auf denselben Satz), und geschwiegen wird nur, solange sie
+ * noch in Sichtweite steht. `MIN_MESSAGES_SINCE_COMPACT` ist dafuer das
+ * richtige Mass, weil es dieselbe Frage beantwortet: wie viel Gespraech muss
+ * vergehen, bis eine Kompaktierungssache wieder erwaehnenswert ist.
+ *
+ * Der Verlauf traegt diesen Zustand und nicht ein Modul-Flag: er ist das, was
+ * der Nutzer sieht, und er ueberlebt einen Neustart.
+ */
+const AUTO_FAIL_PREFIX = 'autocompact-fail-'
+
+function meldeAutoFehlschlag(convId: string, outcome: CompactOutcome & { ok: false }): void {
+ if (outcome.reason === 'aborted' || outcome.reason === 'nothing-to-compact') return
+
+ const nachrichten = useChatStore.getState().conversations.find((c) => c.id === convId)?.messages ?? []
+ const letzteEigene = nachrichten.findLastIndex((m) => m.id.startsWith(AUTO_FAIL_PREFIX))
+ if (letzteEigene !== -1 && nachrichten.length - letzteEigene < MIN_MESSAGES_SINCE_COMPACT) return
+
+ useChatStore.getState().addMessage(convId, {
+ id: `${AUTO_FAIL_PREFIX}${Date.now()}`,
+ role: 'system',
+ notice: 'warn',
+ content: `Auto-compaction did not go through. ${compactOutcomeMessage(outcome)}`,
+ timestamp: Date.now(),
+ })
+}
diff --git a/src/lib/send-window.ts b/src/lib/send-window.ts
index d34eeb11..510816e2 100644
--- a/src/lib/send-window.ts
+++ b/src/lib/send-window.ts
@@ -8,11 +8,19 @@
* never a statement about what a step is worth paying for.
*
* So paid providers get a second, tighter ceiling: min(0.8 × model window,
- * codexSendWindowTokens), default 64k. Local backends keep exactly the
- * behaviour they had, because there is no bill on the other end and their
- * windows are small to begin with. num_ctx is untouched either way, so no
- * model is ever asked to run in a smaller allocation than before (that would
- * only trade money for a trim loop).
+ * codexSendWindowTokens), default 64k. A local backend has no bill on the
+ * other end, so it never gets that second ceiling — `effectiveSendWindow`
+ * returns the plain 0.8 × window base for it, and always has.
+ *
+ * What changed in 2.6.8 (Compact-Schritt 2) is not this function, it is who
+ * asks it. The chat surfaces used to skip it entirely on a local model; now
+ * they apply that base there too, because an overflowing window is a
+ * correctness problem and not a billing one. The reasoning sits at the one
+ * place that made the call: `chatBudgetApplies` in chat-send-budget.ts.
+ *
+ * num_ctx is untouched either way, so no model is ever asked to run in a
+ * smaller allocation than before (that would only trade money for a trim
+ * loop).
*/
/** Providers where a token sent is a token billed. */
diff --git a/src/lib/settings-reset.ts b/src/lib/settings-reset.ts
index b1f2a9fd..cdef386c 100644
--- a/src/lib/settings-reset.ts
+++ b/src/lib/settings-reset.ts
@@ -16,6 +16,7 @@ export const SETTINGS_TAB_RESET_KEYS: Record<SettingsTab, (keyof Settings)[]> =
general: [
'theme', 'userAvatarDataUrl',
'temperature', 'topP', 'topK', 'maxTokens', 'contextWindowOverride',
+ 'autoCompactThreshold',
'gpuVendor', 'gpuIndices',
'imageGenTimeoutMinutes', 'videoGenTimeoutMinutes',
],
diff --git a/src/lib/token-usage.ts b/src/lib/token-usage.ts
index a989ba3c..07a4ef88 100644
--- a/src/lib/token-usage.ts
+++ b/src/lib/token-usage.ts
@@ -65,6 +65,30 @@ function visibleTokens(m: FillMessage): number {
return t + 4 // role overhead
}
+/**
+ * Kostet diese gespeicherte Nachricht etwas in der NAECHSTEN Anfrage?
+ *
+ * `role:'system'` in einem gespeicherten Gespraech ist immer ein App-Hinweis —
+ * der echte Systemprompt steht nicht im Verlauf, sondern wird beim Bauen der
+ * Nutzlast vorangestellt. Die Nutzlast verwirft diese Zeilen; sie zu zaehlen
+ * heisst, dem Nutzer Token in Rechnung zu stellen, die nie gesendet werden.
+ *
+ * DAS WURDE ERST 2026-09-02 ZUM PROBLEM, und zwar durch die App selbst: bis
+ * dahin gab es kaum solche Zeilen. Seit `/compact` seine Ein- und Ausgabe als
+ * Hinweis ablegt, seit eine fertige Hintergrundaufgabe ihr GANZES Ergebnis als
+ * Hinweis meldet und seit die gescheiterte Auto-Kompaktierung sich meldet,
+ * sind es viele — und die Hintergrund-Notiz kann mehrere tausend Token gross
+ * sein. Der Balken sprang dann um ein Rechercheergebnis nach oben, das nie
+ * jemand verschickt.
+ *
+ * DIESELBE REGEL steht als `isModelVisible` in run-compact-command.ts, wo sie
+ * entscheidet, was zusammengefasst wird. Ein Waechter in
+ * token-usage.test.ts haelt beide auf demselben Wort.
+ */
+function kostetEtwas(m: FillMessage): boolean {
+ return m.role !== 'system'
+}
+
export function computeContextFill(
messages: FillMessage[],
built?: BuiltRequestAnchor,
@@ -83,6 +107,7 @@ export function computeContextFill(
// wrong until the next turn built a new anchor. Only what the user adds
// after the build is new context.
if (messages[i].hidden) continue
+ if (!kostetEtwas(messages[i])) continue
used += visibleTokens(messages[i])
}
return { used, real: false, source: 'built' }
@@ -99,7 +124,7 @@ export function computeContextFill(
if (anchorIdx === -1) {
// No usage anywhere yet — plain estimate over the visible conversation.
return {
- used: messages.reduce((sum, m) => sum + visibleTokens(m), 0),
+ used: messages.reduce((sum, m) => sum + (kostetEtwas(m) ? visibleTokens(m) : 0), 0),
real: false,
source: 'estimate',
}
@@ -110,6 +135,7 @@ export function computeContextFill(
// message's own visible reply + every later message joins the next prompt.
let used = anchor.promptTokens
for (let i = anchorIdx; i < messages.length; i++) {
+ if (!kostetEtwas(messages[i])) continue
used += visibleTokens(messages[i])
}
return { used, real: !anchor.estimated, source: 'usage' }
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 0792c44d..35a0302c 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -92,6 +92,38 @@ export interface Message {
unbackedLinks?: string[]
}
+/**
+ * One compaction of this conversation (2.6.8).
+ *
+ * WHY THE ANCHOR IS AN ID AND NOT AN INDEX. The cut has to survive everything
+ * that happens to the array afterwards: new turns appended, a message deleted,
+ * the payload builders filtering stored `role:'system'` notices out. An index
+ * survives none of those — it would silently start covering the wrong turns,
+ * and a summary standing in front of material it does not describe is worse
+ * than no summary. An id that is gone means the record is stale, which is a
+ * state the reader can detect and ignore.
+ *
+ * The summary itself is stored RENDERED, exactly as it goes into the payload,
+ * so what the transcript block shows and what the model receives cannot drift.
+ */
+export interface CompactionRecord {
+ id: string
+ /** The rendered summary, byte-identical to what the payload carries. */
+ summary: string
+ /** Id of the LAST message this summary stands in for — the cut point. */
+ upToMessageId: string
+ /** How many messages it stands in for. Display only. */
+ replaced: number
+ /** Messages in the conversation when it ran. The auto-compact cooldown anchor. */
+ atMessageCount: number
+ /** Estimated tokens of the replaced turns, and of the summary. */
+ tokensBefore: number
+ tokensAfter: number
+ /** Who asked: the user typing /compact, or the threshold firing. */
+ trigger: 'manual' | 'auto'
+ at: number
+}
+
export interface Conversation {
id: string
title: string
@@ -107,6 +139,16 @@ export interface Conversation {
/** Group chat v1: two to four models that answer in turn on every user
* message. Fewer than two entries means a normal single-model chat. */
groupModels?: string[]
+ /**
+ * Compactions that have happened in this chat, oldest first. Only the NEWEST
+ * one shapes the payload — each summary already covers everything before its
+ * own cut, so applying two would send the older material twice. The earlier
+ * ones are kept because the transcript shows them where they happened.
+ *
+ * Absent on every chat from before 2.6.8, and on every chat that has never
+ * been compacted. Both read as "no compaction", which is what they are.
+ */
+ compactions?: CompactionRecord[]
createdAt: number
updatedAt: number
}
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 2767bf7d..e4f22465 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -87,6 +87,22 @@ export interface Settings {
agentMaxToolCalls: number
/** Hard cap on ReAct loop iterations per user turn. 0 = unlimited. */
agentMaxIterations: number
+ /**
+ * Dieselben zwei Schranken, aber fuer einen delegierten Sub-Agenten.
+ *
+ * Getrennt von den beiden darueber, und das ist der Punkt: die Kappen des
+ * Hauptlaufs (400/200) sind grosszuegig, weil der Nutzer daneben sitzt und
+ * Stop druecken kann. Ein Sub-Agent laeuft ohne Zuschauer, in fremdem
+ * Auftrag, und seine Kappen sind darum eng (10/5). Beide aus einem Topf zu
+ * bedienen hiesse, entweder den Hauptlauf zu fesseln oder die Delegation
+ * von der Leine zu lassen.
+ *
+ * 0 heisst hier NICHT unbegrenzt, sondern "nimm die Vorgabe" — bei einer
+ * unbeaufsichtigten Schleife ist Unbegrenztheit kein Wunsch, den man aus
+ * Versehen aeussern koennen sollte.
+ */
+ subAgentMaxToolCalls: number
+ subAgentMaxIterations: number
/**
* How many passes a `/loop` may run. 0 = unlimited, which is the default:
* a loop the user asked to keep going should keep going until it is done or
@@ -128,6 +144,24 @@ export interface Settings {
* costs more. Local backends ignore it.
*/
codexSendWindowTokens: number
+ /**
+ * Auto-compact trigger, as a fraction of the send window. 2.6.8.
+ *
+ * 0 IS THE FEATURE SWITCH, not a tuning value. Owner decision 2026-09-02,
+ * "einstellbar sonst aus": auto-compact replaces conversation history with a
+ * model's summary of it, and when that summary is wrong the user loses work
+ * silently. Nothing fires until someone sets a number here.
+ *
+ * Valid range [0.3, 0.95]; anything outside — including a stored profile
+ * from before this field existed, where it arrives as `undefined` — reads as
+ * off. The range and the reading both live in lib/compact-trigger.ts
+ * (MIN_THRESHOLD / MAX_THRESHOLD / usableThreshold), so this is a value, not
+ * a second rule.
+ *
+ * The manual `/compact` command does NOT consult this. It is the user asking
+ * for one compaction on purpose; the threshold governs only the automatic one.
+ */
+ autoCompactThreshold: number
/**
* Auto memory extraction on lu-cloud only with explicit opt-in (2.6.6, plan
* A7): every extraction is a paid model call. Local and BYOK providers are