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): compaction shows as one line, earlier stretches as layers

purple8eb139633a8f
diff --git a/src/components/__tests__/compact-block.test.ts b/src/components/__tests__/compact-block.test.ts
index a6ee1022..a85ebedc 100644
--- a/src/components/__tests__/compact-block.test.ts
+++ b/src/components/__tests__/compact-block.test.ts
@@ -1,47 +1,22 @@
/**
- * Die Verdichtungslinie — und die Regel, die sie NICHT brechen darf.
+ * Die Verdichtungslinie und die Ebenen (3.0.9).
*
- * 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 ──────────────────────────────────
+ * Bis 3.0.8 stand hier der Waechter „eine Verdichtung blendet nichts aus":
+ * MessageList durfte genau zwei Filter haben, und keiner durfte eine
+ * Verdichtung lesen. Davids Wunsch vom 27.10. aendert die Regel bewusst: die
+ * aktuelle Ansicht beginnt an der neuesten Verdichtung, wie in der Claude-
+ * Code-Desktop-App, und jede fruehere liegt eine Ebene tiefer. Was der alte
+ * Waechter eigentlich schuetzte, bleibt und steht jetzt schaerfer da: KEINE
+ * Nachricht geht verloren. Jede gespeicherte Nachricht steht in mindestens
+ * einer Ebene (lib/__tests__/compact-layers.test.ts rechnet das nach), und
+ * beide Verlaufsflaechen zeigen die Ebenen-Leiste, ueber die man hinkommt.
*
* `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.
+ * ECHT durch `renderToStaticMarkup`. `MessageList` und `CodexView` lassen sich
+ * so nicht rendern (Store-Snapshot, speechSynthesis, framer-motion; gemessen
+ * am 02.09.2026), darum sind sie am Quelltext gesichert.
*
- * 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.
+ * Die Datei heisst `.test.ts`: `vitest.config.ts` sammelt nur `.test.ts`.
*
* Run: npx vitest run src/components/__tests__/compact-block.test.ts
*/
@@ -52,250 +27,113 @@ 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'
+import type { CompactCut } from '../../lib/compact-layers'
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. */
+/** Eine Zusammenfassung, wie sie wirklich im Datensatz steht. 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,
+const schnitt = (over: Partial<CompactCut> = {}): CompactCut => ({
+ key: 'c1',
+ before: 29_594,
+ after: 18_330,
trigger: 'auto',
at: 1_756_000_000_000,
+ summary: ZUSAMMENFASSUNG,
+ start: { msg: 3, block: 0 },
+ end: { msg: 9, block: 0 },
...over,
})
-const rendern = (record: CompactionRecord): string =>
- renderToStaticMarkup(createElement(CompactBlock, { record }))
+const rendern = (cut?: CompactCut): string => renderToStaticMarkup(createElement(CompactBlock, { cut }))
-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([])
+describe('Eine Zeile wie ein Werkzeugaufruf', () => {
+ it('waehrend des Laufs: "Compacting conversation…" mit dem Schimmer eines laufenden Werkzeugs', () => {
+ const html = rendern()
+ expect(html).toContain('Compacting conversation…')
+ expect(html).toContain('lu-tool-shimmer')
+ expect(html).toContain('data-testid="compact-running"')
})
- 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('danach: "Compacted, 28.9K → 17.9K", in den Einheiten des Zaehlers', () => {
+ // Davids Zahlen aus dem REA-Test: 28,9K von 32K, danach 17,9K. Der
+ // Zaehler rechnet in 1024er-K (formatContextWindow), die Zeile auch, sonst
+ // stuenden zwei verschiedene Zahlen fuer denselben Stand nebeneinander.
+ const html = rendern(schnitt())
+ expect(html).toContain('Compacted, 28.9K → 17.9K')
+ expect(html).not.toContain('lu-tool-shimmer')
})
- 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('kein Logo, kein Kasten: ein Symbol in Werkzeuggroesse und Text', () => {
+ const html = rendern(schnitt())
+ expect(html.match(/<svg/g)?.length ?? 0).toBeLessThanOrEqual(2)
+ expect(html).not.toContain('rounded-full border')
})
- 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('/compact sagt, dass der Nutzer es war; automatisch steht nichts dabei', () => {
+ expect(rendern(schnitt({ trigger: 'manual' }))).toContain('/compact')
+ expect(rendern(schnitt({ trigger: 'auto' }))).not.toContain('/compact')
})
- 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)
+ it('eine kaputte Zahl wird zu 0, nicht zu einem Minus', () => {
+ expect(rendern(schnitt({ after: -50 }))).toContain('→ 0')
})
})
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())
+ const html = rendern(schnitt())
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')
+ it('ohne gespeicherte Zusammenfassung (Mitten im Lauf) gibt es nichts aufzuklappen', () => {
+ const html = rendern(schnitt({ summary: undefined }))
+ expect(html).not.toContain('aria-expanded')
+ expect(html).toContain('Compacted, 28.9K → 17.9K')
})
})
-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/)
- })
+describe('Jede Verlaufsflaeche zeigt Linie und Ebenen', () => {
+ /** Eine Verlaufsflaeche haengt am Rollanker und zeigt den Laufanker. Beides
+ * haben heute genau MessageList (Chat, Agent) und CodexView (Code). */
+ const verlaeufe = DATEIEN
+ .filter(([, inhalt]) => inhalt.includes('useAutoScroll(') && inhalt.includes('<WorkingAnchor'))
+ .map(([name]) => name)
- 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('beide bekannten Flaechen werden gefunden', () => {
+ expect(verlaeufe).toContain('components/chat/MessageList.tsx')
+ expect(verlaeufe).toContain('components/chat/CodexView.tsx')
})
- 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('jede rendert ihre Ansicht aus den Ebenen, mit Leiste, Hinweis und laufender Zeile', () => {
+ for (const name of verlaeufe) {
+ const src = quelltext(DATEIEN, name)
+ expect(src, `${name}: Ebenen`).toContain('useCompactLayers(')
+ expect(src, `${name}: Leiste`).toContain('<CompactLayerRail view={layers} />')
+ expect(src, `${name}: Hinweis oben`).toContain('<CompactLayerBanner view={layers} />')
+ expect(src, `${name}: Linie`).toContain("if (item.kind === 'line') return <CompactBlock key={item.cut.key} cut={item.cut} />")
+ expect(src, `${name}: laufende Zeile`).toContain('{!readOnly && layers.compacting && <CompactBlock />}')
+ }
})
- 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')
+ it('eine fruehere Ebene ist nur lesbar', () => {
+ const liste = quelltext(DATEIEN, 'components/chat/MessageList.tsx')
+ expect(liste).toContain('onEdit={!readOnly &&')
+ expect(liste).toContain('onRegenerate={!readOnly &&')
+ expect(liste).toContain('onBranch={readOnly ? undefined : handleBranch}')
+ expect(liste).toContain('pendingApprovalId={readOnly ? null : pendingApprovalId}')
+ const code = quelltext(DATEIEN, 'components/chat/CodexView.tsx')
+ expect(code).toContain('{!readOnly && <CodexConfirmDialog />}')
+ expect(code).toContain('const liveId = readOnly ? undefined : lastMessage?.id')
})
})
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index 1cafef4a..a61b3de4 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -50,9 +50,9 @@ import { StagedChangesPanel } from './StagedChangesPanel'
import { PhoneWritesLine } from './PhoneWritesLine'
import { SlashStepsBlock } from './SlashStepsBlock'
import { CompactBlock } from './CompactBlock'
-import { compactionAnchors } from '../../lib/compact-summary'
+import { CompactLayerBanner, CompactLayerRail, useCompactLayers } from './CompactLayerRail'
import { User, Code, Eye, GitBranch, Download, RefreshCw, RotateCcw, Folder, FolderX, Check, AlertTriangle } from 'lucide-react'
-import { Fragment, useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
import { checkGitInstalled, openExternal, type GitStatus } from '../../api/backend'
import { CodexConfirmDialog } from './CodexConfirmDialog'
import { Hinweis } from '../ui/Hinweis'
@@ -113,15 +113,6 @@ export function CodexView() {
const conversation = conversations.find(c => c.id === activeConversationId)
const messages = conversation?.messages || []
- // Verdichtungslinien fuer den Code-Verlauf. Codex blendet nur `hidden` aus
- // (Systemhinweise bleiben stehen), aber die Rechnung laeuft trotzdem ueber
- // die volle Liste, denn der Schnittpunkt darf auf eine ausgeblendete zeigen.
- const compactAt = compactionAnchors(
- messages,
- messages.filter((m) => !m.hidden).map((m) => m.id),
- conversation?.compactions,
- )
-
// Per-conversation generating flag (2026-06-12): the typing indicator
// + realtime counter + a message's live-stream state must follow the coding
// chat that's ACTUALLY running, not every chat the user switches to. The
@@ -155,9 +146,18 @@ export function CodexView() {
// re-engages via the last user message id.
const lastMessage = messages[messages.length - 1]
const lastUserMessage = messages.filter((m) => m.role === 'user').at(-1)
+ // Compact layers (3.0.9), as in the chat list: the view starts at the
+ // newest compaction, the rail opens the stretch before each one, read only.
+ // Codex hides only `hidden` messages; app notices stay in the transcript.
+ const layers = useCompactLayers(conversation, lastUserMessage?.id)
+ const readOnly = layers.layer !== null
+ const shownItems = layers.items.filter((it) => it.kind === 'line' || !it.message.hidden)
+ // The message a run is writing into. In an earlier layer nothing streams,
+ // even where the cut runs through that very answer.
+ const liveId = readOnly ? undefined : lastMessage?.id
const { ref: scrollRef, contentRef } = useAutoScroll(
`${lastMessage?.content ?? ''}|${thread?.events?.length ?? 0}`,
- lastUserMessage?.id,
+ `${lastUserMessage?.id ?? ''}|${layers.layer ?? 'now'}`,
)
const codexReviewMode = useSettingsStore((s) => s.settings.codexReviewMode)
@@ -388,7 +388,14 @@ export function CodexView() {
<PhoneWritesLine chatId={activeConversationId} />
{/* Messages */}
- <div ref={scrollRef} className="flex-1 min-h-[10rem] overflow-y-auto scrollbar-thin" data-testid="codex-transcript">
+ <div className="relative flex-1 min-h-[10rem] flex flex-col">
+ <CompactLayerBanner view={layers} />
+ <div
+ ref={scrollRef}
+ className={`flex-1 min-h-0 overflow-y-auto scrollbar-thin ${layers.cuts.length ? 'pl-6' : ''}`}
+ data-testid="codex-transcript"
+ data-compact-layer={layers.layer ?? 'current'}
+ >
{messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-center" data-testid="codex-landing">
<Code size={28} className="text-gray-300 dark:text-gray-700 mb-2" />
@@ -417,14 +424,14 @@ export function CodexView() {
</div>
) : (
<div ref={contentRef} className="py-1">
- {messages.filter(msg => !msg.hidden).map((msg) => {
+ {shownItems.map((item) => {
+ if (item.kind === 'line') return <CompactBlock key={item.cut.key} cut={item.cut} />
+ const msg = item.message
// Der Rumpf hat mehrere Ausgaenge (Hinweiszeile, Werkzeugblock,
- // normale Blase). Statt jeden einzeln anzufassen, wandert er
- // unveraendert in eine IIFE, seine `return`s werden ihre. Die
- // Verdichtungslinie haengt danach EINMAL an, fuer alle Ausgaenge
- // gleich. Der Alternativentwurf, jeden Ausgang zu umhuellen,
- // waere dieselbe Zeile an fuenf Stellen gewesen, und die
- // sechste, die jemand spaeter dazuschreibt, haette gefehlt.
+ // normale Blase) und steht unveraendert in einer IIFE, seine
+ // `return`s werden ihre. Bis 3.0.8 hing danach die
+ // Verdichtungslinie an; seit 3.0.9 ist sie ein eigenes Element
+ // der Ebene (lib/compact-layers.ts) und steht oben drueber.
const gerendert = (() => {
// App notices (a staged change that landed on disk) are not
// model turns. They used to be written hidden, so the one line
@@ -477,11 +484,11 @@ export function CodexView() {
{msg.role === 'assistant' && msg.thinking && (
<ThinkingBlock
thinking={msg.thinking}
- streaming={codexGenerating && msg.id === messages[messages.length - 1]?.id && !cleanContent.trim()}
+ streaming={codexGenerating && msg.id === liveId && !cleanContent.trim()}
/>
)}
{(() => {
- const running = codexGenerating && msg.id === messages[messages.length - 1]?.id
+ const running = codexGenerating && msg.id === liveId
// While this message streams, an open ` or ** is closed
// for the frame (lib/streaming-markdown.ts).
const shown = (text: string) => (running ? closeOpenMarkdown(text) : text)
@@ -715,17 +722,10 @@ export function CodexView() {
</div>
)
})()
- const linien = compactAt.get(msg.id)
- if (!linien?.length) return gerendert
- return (
- <Fragment key={msg.id}>
- {gerendert}
- {linien.map((record) => (
- <CompactBlock key={record.id} record={record} />
- ))}
- </Fragment>
- )
+ return gerendert
})}
+ {/* A summary is being written: one line, where the next step will be. */}
+ {!readOnly && layers.compacting && <CompactBlock />}
{/* 3-dot indicator while THIS coding chat is mid-loop. Bound to
the per-conversation flag so switching to another (idle) chat
doesn't show its dots. 2026-06-12 ("die drei ladepunkte
@@ -734,19 +734,23 @@ export function CodexView() {
next step of the run instead of covering it (2026-07-24:
"ich hätte das gerne im chat, wie ein tool call"). Renders
nothing while no request is pending. */}
- <CodexConfirmDialog />
+ {!readOnly && <CodexConfirmDialog />}
{/* G14-6: one anchor with shimmer + clock, no dots, no floating
counter. It also names an approval wait for what it is, so a
blocked run never looks like a working one (G15b). */}
- <WorkingAnchor
- isRunning={codexGenerating}
- conversationId={activeConversationId}
- awaitingApproval={!!pendingConfirm || chatAsked}
- message={messages[messages.length - 1]?.role === 'assistant' ? messages[messages.length - 1] : undefined}
- />
+ {!readOnly && (
+ <WorkingAnchor
+ isRunning={codexGenerating}
+ conversationId={activeConversationId}
+ awaitingApproval={!!pendingConfirm || chatAsked}
+ message={messages[messages.length - 1]?.role === 'assistant' ? messages[messages.length - 1] : undefined}
+ />
+ )}
</div>
)}
</div>
+ <CompactLayerRail view={layers} />
+ </div>
{/* Die stehenden Sitzungsbaender und die Zeilen, die frueher IM
Composer standen (21.09.2026: „NICHTS im prompt fenster!").
diff --git a/src/components/chat/CompactBlock.tsx b/src/components/chat/CompactBlock.tsx
index 5f0a09f1..4facb78b 100644
--- a/src/components/chat/CompactBlock.tsx
+++ b/src/components/chat/CompactBlock.tsx
@@ -1,103 +1,85 @@
import { useState } from 'react'
import { ChevronDown, FoldVertical } from 'lucide-react'
import { summarySections } from '../../lib/compact-summary'
-import type { CompactionRecord } from '../../types/chat'
+import { formatContextWindow } from '../../lib/formatters'
+import type { CompactCut } from '../../lib/compact-layers'
-/**
- * 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 {
+ /** The compaction, or nothing while it is still being written. */
+ cut?: CompactCut
}
-interface Props {
- record: CompactionRecord
+/** Tokens the way the context counter writes them: 28.9K. */
+function tokens(n: number): string {
+ return n > 0 ? formatContextWindow(Math.round(n)) : '0'
}
/**
- * Die Schnittstelle einer Verdichtung, sichtbar im Verlauf.
+ * One compaction in the transcript, as one quiet line (3.0.9).
*
- * 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.
+ * Built like a tool-call row and not like a banner: a compaction is a step
+ * the app took, not news. While the summary is written it reads
+ * "Compacting conversation…" with the same shimmer as a running tool, after
+ * that "Compacted, 28.9K → 17.9K", the payload before and after in the
+ * counter's own units. Up to 3.0.8 it was a pill between two rules plus a
+ * sentence of its own, and in a long Agent run nobody saw either (David,
+ * REA-Test 27.10.: 28.9K/32K, then 17.9K, and nothing in the chat).
*
- * 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".
+ * Nothing is deleted or hidden for good: the messages before the line are
+ * one layer down (CompactLayerRail). Where the summary is stored (per turn,
+ * not in the middle of a run) the line opens to show what was kept, which is
+ * the question a compaction really raises.
*/
-export function CompactBlock({ record }: Props) {
+export function CompactBlock({ cut }: Props) {
const [open, setOpen] = useState(false)
- const sections = summarySections(record.summary)
+ const running = !cut
+ const sections = cut?.summary ? summarySections(cut.summary) : []
+ const canOpen = sections.length > 0
- const saved = record.tokensBefore - record.tokensAfter
- const label = `${record.replaced} ${record.replaced === 1 ? 'message' : 'messages'} summarised`
+ const label = running
+ ? 'Compacting conversation…'
+ : `Compacted, ${tokens(cut.before)} → ${tokens(cut.after)}`
return (
- <div className="my-3">
+ <div className="px-3 py-1" data-testid={running ? 'compact-running' : 'compact-line'}>
<button
- onClick={() => setOpen((o) => !o)}
- aria-expanded={open}
- className="group flex items-center gap-2 w-full text-left"
+ type="button"
+ onClick={() => canOpen && setOpen((o) => !o)}
+ aria-expanded={canOpen ? open : undefined}
+ disabled={!canOpen}
+ className="flex items-center gap-1.5 py-0.5 text-left enabled:hover:opacity-80 transition-opacity min-w-0"
>
- <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>
- )}
+ <FoldVertical size={10} className="text-gray-500 dark:text-gray-500 shrink-0" />
+ <span className={`t-micro italic pr-0.5 ${running ? 'lu-tool-shimmer' : 'text-gray-600 dark:text-gray-400'}`}>
+ {label}
+ </span>
+ {cut?.trigger === 'manual' && (
+ <span className="t-micro text-gray-400 dark:text-gray-600">/compact</span>
+ )}
+ {canOpen && (
<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.
+ {open && canOpen && (
+ <div className="ml-4 mt-1 pl-2 border-l border-gray-200 dark:border-white/10 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>
diff --git a/src/components/chat/CompactLayerRail.tsx b/src/components/chat/CompactLayerRail.tsx
new file mode 100644
index 00000000..6cb83bca
--- /dev/null
+++ b/src/components/chat/CompactLayerRail.tsx
@@ -0,0 +1,165 @@
+import { useEffect, useMemo, useState } from 'react'
+import { Layers } from 'lucide-react'
+import { compactCuts, layerItems, type CompactCut, type LayerItem } from '../../lib/compact-layers'
+import { formatContextWindow } from '../../lib/formatters'
+import { useRunActivityStore } from '../../stores/runActivityStore'
+import type { Conversation } from '../../types/chat'
+
+export interface CompactLayerView {
+ cuts: CompactCut[]
+ /** The layer on screen, null for the current one. */
+ layer: number | null
+ setLayer: (layer: number | null) => void
+ items: LayerItem[]
+ /** A summary for this chat is being written right now. */
+ compacting: boolean
+}
+
+/**
+ * The layer state of one transcript, shared by Chat/Agent (MessageList) and
+ * Code (CodexView). A layer is a reading position, not chat data: it is not
+ * stored, starts at the current view for every chat opened, and goes back
+ * there when the user sends (`resumeKey`, the newest user message).
+ */
+export function useCompactLayers(conversation: Conversation | undefined, resumeKey: unknown): CompactLayerView {
+ const messages = conversation?.messages
+ const compactions = conversation?.compactions
+ const cuts = useMemo(() => compactCuts(messages ?? [], compactions), [messages, compactions])
+
+ const [state, setState] = useState<{ id: string | undefined; key: unknown; layer: number | null }>({
+ id: conversation?.id, key: resumeKey, layer: null,
+ })
+ // Another chat, or a new message from the user: back to the current view.
+ // React's "adjust state when a prop changes" shape, as MessageList's gate.
+ if (state.id !== conversation?.id || state.key !== resumeKey) {
+ setState({ id: conversation?.id, key: resumeKey, layer: null })
+ }
+ const layer = state.layer !== null && state.layer < cuts.length ? state.layer : null
+
+ const items = useMemo(() => layerItems(messages ?? [], cuts, layer), [messages, cuts, layer])
+ const compacting = useRunActivityStore((s) =>
+ conversation ? s.activity[conversation.id]?.kind === 'compacting' : false,
+ )
+
+ return {
+ cuts,
+ layer,
+ setLayer: (next) => setState((s) => ({ ...s, layer: next })),
+ items,
+ compacting,
+ }
+}
+
+function when(at: number): string {
+ try {
+ return new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
+ } catch {
+ return ''
+ }
+}
+
+function layerTitle(cut: CompactCut, index: number): string {
+ return `Before compaction ${index + 1} · ${formatContextWindow(Math.round(cut.before))} → ${formatContextWindow(Math.round(cut.after))} · ${when(cut.at)}`
+}
+
+/**
+ * The layers, left of the transcript and vertically centred, as in the Claude
+ * Code desktop app: one bar per compaction plus the current view at the
+ * bottom. A bar opens the transcript as it stood right before that compaction,
+ * read only; the bottom bar, the icon or Esc go back.
+ */
+export function CompactLayerRail({ view }: { view: CompactLayerView }) {
+ const { cuts, layer, setLayer } = view
+
+ useEffect(() => {
+ if (layer === null) return
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') setLayer(null)
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [layer, setLayer])
+
+ if (cuts.length === 0) return null
+
+ const bar = (active: boolean) =>
+ `block h-[3px] rounded-full transition-[width,background-color] ${
+ active
+ ? 'w-4 bg-gray-700 dark:bg-gray-200'
+ : 'w-2.5 bg-gray-300 dark:bg-white/20 group-hover:w-3.5 group-hover:bg-gray-500 dark:group-hover:bg-white/50'
+ }`
+
+ return (
+ <nav
+ aria-label="Compact layers"
+ data-testid="compact-layers"
+ className="absolute left-1.5 top-1/2 -translate-y-1/2 z-10 flex flex-col items-center gap-1"
+ >
+ <button
+ type="button"
+ onClick={() => setLayer(layer === null ? cuts.length - 1 : null)}
+ title={layer === null ? 'Show the conversation before the last compaction' : 'Back to the current conversation'}
+ aria-label={layer === null ? 'Show the conversation before the last compaction' : 'Back to the current conversation'}
+ className={`p-1 rounded transition-colors ${
+ layer === null
+ ? 'text-gray-400 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200'
+ : 'text-gray-800 dark:text-gray-100'
+ }`}
+ >
+ <Layers size={13} />
+ </button>
+ {cuts.map((cut, i) => (
+ <button
+ key={cut.key}
+ type="button"
+ onClick={() => setLayer(i)}
+ title={layerTitle(cut, i)}
+ aria-label={layerTitle(cut, i)}
+ aria-current={layer === i ? 'true' : undefined}
+ data-testid="compact-layer"
+ className="group px-1 py-[3px] flex justify-center"
+ >
+ <span className={bar(layer === i)} />
+ </button>
+ ))}
+ <button
+ type="button"
+ onClick={() => setLayer(null)}
+ title="Current conversation"
+ aria-label="Current conversation"
+ aria-current={layer === null ? 'true' : undefined}
+ data-testid="compact-layer-current"
+ className="group px-1 py-[3px] flex justify-center"
+ >
+ <span className={bar(layer === null)} />
+ </button>
+ </nav>
+ )
+}
+
+/** Above a transcript showing an earlier layer: which one, and the way back.
+ * Outside the scroll area, so it stays put and the top fade does not eat it. */
+export function CompactLayerBanner({ view }: { view: CompactLayerView }) {
+ const { cuts, layer, setLayer } = view
+ if (layer === null) return null
+ const cut = cuts[layer]
+ return (
+ <div
+ data-testid="compact-layer-banner"
+ className="shrink-0 mx-auto mt-2 mb-1 w-[calc(100%-1.5rem)] max-w-xl flex items-center gap-2 rounded border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] px-2.5 py-1"
+ >
+ <Layers size={11} className="text-gray-500 shrink-0" />
+ <span className="t-micro text-gray-600 dark:text-gray-300 min-w-0 truncate">
+ Before compaction {layer + 1} of {cuts.length}
+ {cut ? ` · ${formatContextWindow(Math.round(cut.before))} · ${when(cut.at)}` : ''} · read only
+ </span>
+ <button
+ type="button"
+ onClick={() => setLayer(null)}
+ className="ml-auto t-micro text-gray-700 dark:text-gray-200 underline underline-offset-2 hover:opacity-80 shrink-0"
+ >
+ Back to current
+ </button>
+ </div>
+ )
+}
diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsx
index 407d996f..bd43dea2 100644
--- a/src/components/chat/MessageList.tsx
+++ b/src/components/chat/MessageList.tsx
@@ -9,7 +9,7 @@ import { MessageBubble } from './MessageBubble'
import { WorkingAnchor } from './WorkingAnchor'
import { useComputerStore } from '../../stores/computerStore'
import { CompactBlock } from './CompactBlock'
-import { compactionAnchors } from '../../lib/compact-summary'
+import { CompactLayerBanner, CompactLayerRail, useCompactLayers } from './CompactLayerRail'
import { Hinweis } from '../ui/Hinweis'
import { TRANSCRIPT_MAX_PX } from './composer-width'
import { useAgentModeStore } from '../../stores/agentModeStore'
@@ -113,9 +113,15 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
// covered by the hook's ResizeObserver (G33). The resumeKey is the last
// USER message: sending jumps all the way down even after scrolling away.
const lastUserMessage = conversation?.messages.filter((m) => m.role === 'user').at(-1)
+ // Compact layers (3.0.9): the view starts at the newest compaction, and the
+ // rail on the left opens the stretch before each one, read only.
+ const layers = useCompactLayers(conversation, lastUserMessage?.id)
+ const readOnly = layers.layer !== null
+ // Switching layers is a jump like sending: to the bottom of what is shown,
+ // the moment right before that compaction.
const { ref: scrollRef, contentRef } = useAutoScroll(
`${lastMessage?.content ?? ''}|${pendingApprovalId ?? ''}`,
- lastUserMessage?.id,
+ `${lastUserMessage?.id ?? ''}|${layers.layer ?? 'now'}`,
)
// MessageBubble is memoised, so its handlers have to keep the same identity
@@ -171,9 +177,11 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
// in den Verlauf. Bis 2.6.8 filterte diese Zeile jede Systemnachricht weg,
// und der Code-Verlauf zeigte sie schon; damit war `/compact` im Chat
// stumm, sobald die beiden Zeilen ehrlich als Hinweise abgelegt wurden.
- const visibleMessages = conversation.messages.filter(
- (m) => (m.role !== 'system' || !!m.notice) && !m.hidden,
- )
+ const isVisible = (m: (typeof conversation.messages)[number]) => (m.role !== 'system' || !!m.notice) && !m.hidden
+ // What this view shows: the current layer, or the one picked on the rail.
+ // Each compaction is ONE line at the top of the view after it.
+ const items = layers.items.filter((it) => it.kind === 'line' || isVisible(it.message))
+ const visibleMessages = items.flatMap((it) => (it.kind === 'message' ? [it.message] : []))
const lastVisibleId = visibleMessages[visibleMessages.length - 1]?.id
// The one answer that carries the refusal notice, if any. The answer that
// is still being written is never judged: every long answer is a short one
@@ -190,21 +198,15 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
})
}
const skipOffscreen = skipGate.id === conversation.id && skipGate.on
- const tailStart = visibleMessages.length - ALWAYS_RENDERED_TAIL
-
- // Die Verdichtungslinien. Berechnet aus der VOLLEN Nachrichtenliste, weil
- // der Schnittpunkt auf eine gefilterte Nachricht zeigen kann, aber
- // angezeigt an sichtbaren Zeilen — siehe compactionAnchors.
- const compactAt = compactionAnchors(
- conversation.messages,
- visibleMessages.map((m) => m.id),
- conversation.compactions,
- )
+ const tailStart = items.length - ALWAYS_RENDERED_TAIL
return (
+ <div className="relative flex-1 min-h-0 flex flex-col">
+ <CompactLayerBanner view={layers} />
<div
ref={scrollRef}
- className="flex-1 overflow-y-auto scrollbar-thin py-4"
+ className={`flex-1 overflow-y-auto scrollbar-thin py-4 ${layers.cuts.length ? 'pl-6' : ''}`}
+ data-compact-layer={layers.layer ?? 'current'}
style={{
// Soft top fade — chat content "blurs out" under the header.
WebkitMaskImage: 'linear-gradient(to bottom, transparent 0, #000 28px)',
@@ -224,8 +226,11 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
steht; als `style`, weil Tailwind Klassennamen scannt und eine
gerechnete Breite deshalb keine Regel bekaeme. */}
<div ref={contentRef} className="mx-auto w-full" style={{ maxWidth: TRANSCRIPT_MAX_PX }}>
- {visibleMessages
- .map((message, index) => (
+ {items
+ .map((item, index) => {
+ if (item.kind === 'line') return <CompactBlock key={item.cut.key} cut={item.cut} />
+ const message = item.message
+ return (
// The wrapper carries the skip hint so MessageBubble keeps owning
// its own root class. It is a plain block inside a plain block, so
// it adds no layout of its own.
@@ -252,40 +257,42 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
isLast={message.id === lastVisibleId}
// The live generating flag, not `message.usage`: a backend that
// never reports usage would lose the action bar for good.
- isStreaming={showTyping && message.id === lastVisibleId && message.role === 'assistant'}
- onRegenerate={message.role === 'assistant' && onRegenerate && !isGenerating && !message.greetings
+ isStreaming={!readOnly && showTyping && message.id === lastVisibleId && message.role === 'assistant'}
+ // An earlier layer is read only: no regenerate, no edit, no
+ // approval, no switching or branching of versions.
+ onRegenerate={!readOnly && message.role === 'assistant' && onRegenerate && !isGenerating && !message.greetings
? handleRegenerate
: undefined}
- onEdit={message.role === 'user' && onEdit && !isGenerating
+ onEdit={!readOnly && message.role === 'user' && onEdit && !isGenerating
? handleEdit
: undefined}
- pendingApprovalId={pendingApprovalId}
- onApprove={onApprove}
- onReject={onReject}
+ pendingApprovalId={readOnly ? null : pendingApprovalId}
+ onApprove={readOnly ? undefined : onApprove}
+ onReject={readOnly ? undefined : onReject}
forkKey={marks.get(message.id)?.key}
forkIndex={marks.get(message.id)?.index}
forkTotal={marks.get(message.id)?.total}
// Switching while a turn streams would move the bubble the
// stream writes into out of the thread.
- onSwitchFork={isGenerating ? undefined : handleSwitchFork}
- onBranch={handleBranch}
+ onSwitchFork={isGenerating || readOnly ? undefined : handleSwitchFork}
+ onBranch={readOnly ? undefined : handleBranch}
declined={message.id === declinedId}
speakerName={speakerNameOf(message, speakers, authors)}
/>
)}
- {message.greetings && message.greetings.length > 1 && message.id === lastVisibleId && !isGenerating && (
+ {!readOnly && message.greetings && message.greetings.length > 1 && message.id === lastVisibleId && !isGenerating && (
<GreetingSwitcher conversationId={conversation.id} message={message} />
)}
- {compactAt.get(message.id)?.map((record) => (
- <CompactBlock key={record.id} record={record} />
- ))}
</div>
- ))}
+ )
+ })}
+ {/* A summary is being written: one line, where the next step will be. */}
+ {!readOnly && layers.compacting && <CompactBlock />}
{/* The run anchor stays visible the entire time the agent is still
working, including between tool calls and while the final answer
streams. G14-6: one shimmering "Working" with the clock beside it,
instead of three dots here and a floating counter elsewhere. */}
- {showTyping && lastMessage?.role === 'assistant' && (
+ {!readOnly && showTyping && lastMessage?.role === 'assistant' && (
<WorkingAnchor
isRunning
conversationId={conversation?.id}
@@ -299,6 +306,8 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
)}
</div>
</div>
+ <CompactLayerRail view={layers} />
+ </div>
)
}
diff --git a/src/components/chat/__tests__/der-caret-ist-reines-css.test.ts b/src/components/chat/__tests__/der-caret-ist-reines-css.test.ts
index f35e9ab4..7e93fdc0 100644
--- a/src/components/chat/__tests__/der-caret-ist-reines-css.test.ts
+++ b/src/components/chat/__tests__/der-caret-ist-reines-css.test.ts
@@ -74,7 +74,8 @@ describe('die Bewegung liegt in CSS, nicht in React', () => {
it('die Klasse ist eine reine Funktion des vorhandenen isStreaming-Props', () => {
// Kein neuer Store, kein neuer Prop, keine neue Subscription: der Wert
// wird in MessageList schon berechnet und war schon da.
- expect(LIST).toMatch(/isStreaming=\{showTyping && message\.id === lastVisibleId/)
+ // 3.0.9: an earlier compact layer never streams, hence the leading !readOnly.
+ expect(LIST).toMatch(/isStreaming=\{!readOnly && showTyping && message\.id === lastVisibleId/)
const stellen = [...BUBBLE.matchAll(/isStreaming \? ' lu-caret' : ''|isStreaming && istSchluss \? ' lu-caret' : ''/g)]
expect(stellen).toHaveLength(2)
})
diff --git a/src/components/chat/__tests__/die-karte-bleibt-erreichbar.test.ts b/src/components/chat/__tests__/die-karte-bleibt-erreichbar.test.ts
index 66361a70..6e31f326 100644
--- a/src/components/chat/__tests__/die-karte-bleibt-erreichbar.test.ts
+++ b/src/components/chat/__tests__/die-karte-bleibt-erreichbar.test.ts
@@ -43,7 +43,10 @@ describe('the approval card stays reachable', () => {
it('gives the transcript a floor so no side panel can squeeze it to nothing', () => {
const src = read('../CodexView.tsx')
- expect(src).toMatch(/ref=\{scrollRef\} className="flex-1 min-h-\[10rem\] overflow-y-auto[^"]*" data-testid="codex-transcript"/)
+ // 3.0.9: the floor sits on the wrapper that also holds the compact
+ // layer rail and banner; the scroll area fills it.
+ expect(src).toContain('<div className="relative flex-1 min-h-[10rem] flex flex-col">')
+ expect(src).toMatch(/ref=\{scrollRef\}\s+className=\{`flex-1 min-h-0 overflow-y-auto[^`]*`\}\s+data-testid="codex-transcript"/)
})
it('scrolls the approval card into view the moment it exists', () => {
diff --git a/src/components/chat/__tests__/long-transcripts-stay-cheap.test.ts b/src/components/chat/__tests__/long-transcripts-stay-cheap.test.ts
index fcadcdde..d94e6509 100644
--- a/src/components/chat/__tests__/long-transcripts-stay-cheap.test.ts
+++ b/src/components/chat/__tests__/long-transcripts-stay-cheap.test.ts
@@ -26,7 +26,10 @@ const hook = read('../../../hooks/useAutoScroll.ts')
describe('every message stays mounted — no window, no slice', () => {
it('the whole filtered list is still mapped', () => {
- expect(list).toMatch(/visibleMessages\s*\n?\s*\.map\(\(message, index\) =>/)
+ // 3.0.9: the list maps the items of the compact layer on screen (a line
+ // per compaction, then its messages). Choosing the layer is the one cut,
+ // made in lib/compact-layers.ts; inside a layer nothing is windowed.
+ expect(list).toMatch(/items\s*\n?\s*\.map\(\(item, index\) =>/)
})
it('nothing slices, windows or paginates the message array', () => {
@@ -82,7 +85,7 @@ describe('off-screen messages skip layout and paint', () => {
// The bottom edge is what the auto-scroll pin measures against; an
// estimated height there is the one place a wrong guess shows.
expect(list).toContain('const ALWAYS_RENDERED_TAIL = 3')
- expect(list).toContain('const tailStart = visibleMessages.length - ALWAYS_RENDERED_TAIL')
+ expect(list).toContain('const tailStart = items.length - ALWAYS_RENDERED_TAIL')
expect(list).toContain('index < tailStart')
})
})
diff --git a/src/components/chat/__tests__/staged-apply-notice-reaches-the-user.test.ts b/src/components/chat/__tests__/staged-apply-notice-reaches-the-user.test.ts
index 387d987b..494d16df 100644
--- a/src/components/chat/__tests__/staged-apply-notice-reaches-the-user.test.ts
+++ b/src/components/chat/__tests__/staged-apply-notice-reaches-the-user.test.ts
@@ -56,7 +56,7 @@ describe('the notice is written to be seen', () => {
describe('the coding view renders it as a notice, not as the model talking', () => {
it('has a branch for it before the bubble branch', () => {
- const list = codexView.slice(codexView.indexOf('messages.filter(msg => !msg.hidden)'))
+ const list = codexView.slice(codexView.indexOf('shownItems.map((item) =>'))
const branch = list.indexOf("msg.role === 'system' && msg.notice")
const bubble = list.indexOf("msg.role === 'user' ? 'flex-row-reverse' : ''")
expect(branch).toBeGreaterThan(-1)
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 4a57708f..82356c9b 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -1855,6 +1855,7 @@ export function useAgentChat() {
signal: abort.signal,
state: laufVerdichtung,
decay: { enabled: decayOn },
+ onCompacted: convId ? (block) => addBlock(runState, convId, assistantMessage.id, block) : undefined,
})
if (verdichtet.compacted) agentMessages = verdichtet.messages
agentMessages = trimWorkingHistory(agentMessages, sendBudget, { enabled: decayOn, hysteresis: decayOn }).messages
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 9315aaf5..d0acfd1e 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -772,14 +772,19 @@ export function useChat() {
store.addMessage(convId, {
id: uuid(), role: 'system', notice: 'info', content, timestamp: Date.now(),
})
- // A placeholder first: writing the summary is a real round trip, and a
- // composer that just goes quiet for ten seconds reads as a hang. The
- // same reason the send path shows a streaming placeholder.
- const noticeId = uuid()
- store.addMessage(convId, {
- id: noticeId, role: 'system', notice: 'info',
- content: 'Summarising the earlier turns…', timestamp: Date.now(),
- })
+ // Writing the summary is a real round trip, and a composer that just
+ // goes quiet for ten seconds reads as a hang. Until 3.0.8 a placeholder
+ // notice said so; now runCompactForConversation shows the line
+ // "Compacting conversation…" while it runs, and the record it stores
+ // stays as "Compacted, 28.9K → 17.9K". Only a run that changed nothing
+ // still gets a sentence, because then there is no record to draw.
+ const reportUnlessDone = (outcome: Parameters<typeof compactOutcomeMessage>[0]) => {
+ if (outcome.ok) return
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'system', notice: 'info',
+ content: compactOutcomeMessage(outcome), timestamp: Date.now(),
+ })
+ }
// Runde 5 Nachtrag (review-lanes.md Runde 2, Grep-Audit dieser Runde):
// this used to call runCompactForConversation straight away, a real
// inference call that never touched run-lanes.ts. A local /compact
@@ -825,14 +830,10 @@ export function useChat() {
focus: cmd.args || undefined,
signal: compactAbort.signal,
})
- useChatStore.getState().updateMessageContent(convId, noticeId, compactOutcomeMessage(outcome))
+ reportUnlessDone(outcome)
},
)
- if (laneOutcome === 'cancelled-while-queued') {
- useChatStore.getState().updateMessageContent(
- convId, noticeId, compactOutcomeMessage({ ok: false, reason: 'aborted' }),
- )
- }
+ if (laneOutcome === 'cancelled-while-queued') reportUnlessDone({ ok: false, reason: 'aborted' })
} finally {
if (activeChatRuns.get(convId) === myRunToken) {
activeChatRuns.delete(convId)
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index c0b36e91..98858190 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -562,18 +562,21 @@ export function useCodex() {
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'system', notice: 'info', content: rawInstruction, timestamp: Date.now(),
})
- const noticeId = uuid()
- useChatStore.getState().addMessage(convId, {
- id: noticeId, role: 'system', notice: 'info',
- content: 'Summarising the earlier turns…', timestamp: Date.now(),
- })
+ // While it runs the transcript shows "Compacting conversation…", and
+ // the record stays as the line "Compacted, …" (3.0.9). Only a run that
+ // changed nothing gets a sentence.
const outcome = await runCompactForConversation({
conversationId: convId,
activeModel: activeModel || '',
trigger: 'manual',
focus: slash.args || undefined,
})
- useChatStore.getState().updateMessageContent(convId, noticeId, compactOutcomeMessage(outcome))
+ if (!outcome.ok) {
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'system', notice: 'info',
+ content: compactOutcomeMessage(outcome), timestamp: Date.now(),
+ })
+ }
activeCodexRuns.delete(convId)
return
}
@@ -1397,6 +1400,7 @@ export function useCodex() {
signal: abort.signal,
state: laufVerdichtung,
decay: { enabled: decayOn },
+ onCompacted: addBlock,
})
if (verdichtet.compacted) messages = verdichtet.messages
messages = trimWorkingHistory(messages, sendWindow, { enabled: decayOn, hysteresis: decayOn }).messages
diff --git a/src/lib/__tests__/auto-compact-wiring.test.ts b/src/lib/__tests__/auto-compact-wiring.test.ts
index 881016c3..2a95a1aa 100644
--- a/src/lib/__tests__/auto-compact-wiring.test.ts
+++ b/src/lib/__tests__/auto-compact-wiring.test.ts
@@ -55,6 +55,7 @@ vi.mock('../compact-run', async (importOriginal) => {
})
import { maybeAutoCompact, runCompactForConversation } from '../run-compact-command'
+import { compactCuts, layerItems } from '../compact-layers'
import { useRunActivityStore } from '../../stores/runActivityStore'
import { deriveRunStatus } from '../../components/status/run-status'
import { runCompactSummary } from '../compact-run'
@@ -490,24 +491,12 @@ describe('Auto-Kompaktierung, die schiefgeht, sagt es', () => {
expect(hinweise(id)).toHaveLength(0)
})
- it('meldet den Erfolg GENAU einmal — und zwar am Ende', async () => {
- // Diese Zusicherung hiess bis zum 03.09.2026 „schreibt nichts in den
- // Verlauf, wenn es geklappt hat", begruendet mit: der Erfolg habe seine
- // eigene Darstellung, den Compact-Block an der Schnittstelle, ein
- // zusaetzlicher Hinweis waere dasselbe zweimal.
- //
- // Die Praemisse stimmt zur Haelfte. Den Block gibt es wirklich
- // (CompactBlock, verankert per compactionAnchors) — aber er steht am
- // SCHNITTPUNKT, also mitten in einem Gespraech, das gerade lang genug
- // geworden ist, um verdichtet zu werden. Der Leser steht in diesem Moment
- // unten am Eingabefeld, dreissig Nachrichten weiter. Eine Persona hat
- // genau dort gestanden, den Ueberlauf komplett verpasst und ihn erst im
- // Netzwerkverkehr gefunden.
- //
- // Die Sorge des alten Tests bleibt trotzdem richtig, deshalb steht sie
- // jetzt als Zahl da: GENAU eine Notiz, nicht zwei. Der Block sagt, WO
- // geschnitten wurde; die Notiz sagt, DASS es eben passiert ist, an der
- // Stelle, auf die der Leser ohnehin schaut.
+ it('meldet den Erfolg GENAU einmal: als Linie, nicht als zweite Notiz', async () => {
+ // Bis 3.0.8 schrieb der Erfolg zusaetzlich eine Notiz ans Ende, weil die
+ // Linie am Schnittpunkt mitten im Gespraech stand und der Leser dreissig
+ // Nachrichten weiter unten (Persona 03.09.2026). Seit 3.0.9 beginnt die
+ // aktuelle Ansicht AN der Linie (lib/compact-layers.ts): sie steht damit
+ // genau dort, wo der Leser schaut, und eine Notiz waere dasselbe zweimal.
setzeSchwelle(0.5)
const id = vollesGespraech()
zusammenfassen.mockResolvedValue({
@@ -517,7 +506,7 @@ describe('Auto-Kompaktierung, die schiefgeht, sagt es', () => {
const rec = await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
expect(rec).not.toBeNull()
- expect(hinweise(id)).toHaveLength(1)
+ expect(hinweise(id)).toHaveLength(0)
})
})
@@ -624,39 +613,45 @@ describe('Auto-Kompaktierung, die klappt, sagt es auch', () => {
(useChatStore.getState().conversations.find((c) => c.id === id)?.messages ?? [])
.filter((m) => m.role === 'system' && !!m.notice)
- it('hinterlaesst eine sichtbare Notiz im Verlauf', async () => {
+ it('hinterlaesst die Linie oben in der aktuellen Ansicht, mit den Zahlen des Zaehlers', async () => {
setzeSchwelle(0.5)
const id = vollesGespraech()
zusammenfassen.mockResolvedValue({ ok: true, summary: ZUSAMMENFASSUNG } as never)
const rec = await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
expect(rec).not.toBeNull()
-
- const n = hinweise(id)
- expect(n).toHaveLength(1)
- // Kein 'warn': es ist nichts schiefgegangen, es ist etwas passiert.
- expect(n[0].notice).toBe('info')
- expect(n[0].content).toContain('Summarised')
- // Der Satz, der die Angst nimmt — der Verlauf ist nicht weg, nur die
- // Nutzlast ist kuerzer. Ohne ihn liest sich die Notiz wie ein Datenverlust.
- expect(n[0].content).toContain('The full conversation is still here')
+ // Die ganze Nutzlast vorher und nachher, nicht nur die ersetzten Zuege:
+ // das ist die Zahl, die der Zaehler zeigt (David, REA-Test 27.10.).
+ expect(rec!.contextBefore).toBeGreaterThan(0)
+ expect(rec!.contextAfter).toBeLessThan(rec!.contextBefore!)
+ expect(rec!.contextBefore! - rec!.contextAfter!).toBe(Math.max(0, rec!.tokensBefore - rec!.tokensAfter))
+
+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!
+ const jetzt = layerItems(conv.messages, compactCuts(conv.messages, conv.compactions), null)
+ expect(jetzt[0]).toMatchObject({ kind: 'line', cut: { key: rec!.id } })
+ // Und keine Notiz daneben.
+ expect(hinweise(id)).toHaveLength(0)
})
- it('die Notiz steht NACH den Nachrichten, die sie ersetzt', async () => {
+ it('die Linie steht NACH den Nachrichten, die sie ersetzt', async () => {
// Am Schnittpunkt, nicht am Anfang: sonst behauptet sie, das ganze
- // Gespraech sei zusammengefasst.
+ // Gespraech sei zusammengefasst. Was davor stand, liegt eine Ebene tiefer.
setzeSchwelle(0.5)
const id = vollesGespraech()
zusammenfassen.mockResolvedValue({ ok: true, summary: ZUSAMMENFASSUNG } as never)
- await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
- const alle = useChatStore.getState().conversations.find((c) => c.id === id)!.messages
- expect(alle[alle.length - 1].notice).toBe('info')
+ const rec = await maybeAutoCompact({ conversationId: id, activeModel: MODELL })
+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!
+ const cuts = compactCuts(conv.messages, conv.compactions)
+ const ids = (items: ReturnType<typeof layerItems>) =>
+ items.flatMap((it) => (it.kind === 'message' ? [it.message.id] : []))
+ const vorher = ids(layerItems(conv.messages, cuts, 0))
+ expect(vorher).toContain(rec!.upToMessageId)
+ expect(ids(layerItems(conv.messages, cuts, null))).not.toContain(rec!.upToMessageId)
})
- it('der manuelle Weg verdoppelt die Notiz nicht', async () => {
- // /compact zeigt sein Ergebnis selbst an. Zwei Notizen fuer einen Vorgang
- // waeren eine Falschmeldung ueber die Anzahl der Vorgaenge.
+ it('der manuelle Weg schreibt auch keine Notiz', async () => {
+ // /compact zeigt sein Ergebnis als dieselbe Linie (der Datensatz).
setzeSchwelle(0.5)
const id = vollesGespraech()
zusammenfassen.mockResolvedValue({ ok: true, summary: ZUSAMMENFASSUNG } as never)
diff --git a/src/lib/__tests__/compact-layers.test.ts b/src/lib/__tests__/compact-layers.test.ts
new file mode 100644
index 00000000..34638980
--- /dev/null
+++ b/src/lib/__tests__/compact-layers.test.ts
@@ -0,0 +1,152 @@
+/**
+ * Compact layers (3.0.9): the current view starts at the newest compaction,
+ * each earlier one is a layer, and no message is ever lost on the way.
+ *
+ * Run: npx vitest run src/lib/__tests__/compact-layers.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { AUTO_OK_PREFIX, compactCuts, layerItems, type LayerItem } from '../compact-layers'
+import type { CompactionRecord, Message } from '../../types/chat'
+import type { AgentBlock } from '../../types/agent-mode'
+
+const msg = (id: string, over: Partial<Message> = {}): Message => ({
+ id, role: id.startsWith('u') ? 'user' : 'assistant', content: `text ${id}`, timestamp: 0, ...over,
+})
+
+const record = (over: Partial<CompactionRecord>): CompactionRecord => ({
+ id: 'r1', summary: 'S', upToMessageId: 'a2', replaced: 4, atMessageCount: 6,
+ tokensBefore: 9000, tokensAfter: 500, trigger: 'auto', at: 100, ...over,
+})
+
+const step = (id: string, t: number): AgentBlock => ({ id, phase: 'tool_call', content: id, timestamp: t })
+const cutBlock = (id: string, t: number, before = 7000, after = 3000): AgentBlock => ({
+ id, phase: 'reflection', content: 'Summarised …', timestamp: t, compaction: { before, after, replaced: 5 },
+})
+
+const ids = (items: LayerItem[]): string[] =>
+ items.map((it) => (it.kind === 'line' ? `|${it.cut.key}|` : it.message.id))
+
+const blocksOf = (items: LayerItem[], id: string): string[] => {
+ const it = items.find((i) => i.kind === 'message' && i.message.id === id)
+ return it && it.kind === 'message' ? (it.message.agentBlocks ?? []).map((b) => b.id) : []
+}
+
+describe('without compaction', () => {
+ it('there is no layer and the view is the whole chat', () => {
+ const messages = [msg('u1'), msg('a1')]
+ const cuts = compactCuts(messages, undefined)
+ expect(cuts).toEqual([])
+ expect(ids(layerItems(messages, cuts, null))).toEqual(['u1', 'a1'])
+ })
+})
+
+describe('a per-turn compaction (/compact or the auto trigger)', () => {
+ const messages = [msg('u1'), msg('a1'), msg('u2'), msg('a2'), msg('u3'), msg('a3'), msg('u4'), msg('a4')]
+ const rec = record({ endMessageId: 'a3', contextBefore: 29_594, contextAfter: 18_330 })
+
+ it('the current view starts with the line, behind the cut', () => {
+ const cuts = compactCuts(messages, [rec])
+ expect(ids(layerItems(messages, cuts, null))).toEqual(['|r1|', 'u3', 'a3', 'u4', 'a4'])
+ })
+
+ it('the layer before it ends at the newest message when it ran', () => {
+ const cuts = compactCuts(messages, [rec])
+ expect(ids(layerItems(messages, cuts, 0))).toEqual(['u1', 'a1', 'u2', 'a2', 'u3', 'a3'])
+ })
+
+ it('carries the whole-payload numbers, else the old per-record ones', () => {
+ expect(compactCuts(messages, [rec])[0]).toMatchObject({ before: 29_594, after: 18_330 })
+ expect(compactCuts(messages, [record({})])[0]).toMatchObject({ before: 9000, after: 500 })
+ })
+
+ it('a record from before 3.0.9 ends its layer at atMessageCount', () => {
+ const cuts = compactCuts(messages, [record({ atMessageCount: 5 })])
+ expect(ids(layerItems(messages, cuts, 0))).toEqual(['u1', 'a1', 'u2', 'a2', 'u3'])
+ })
+
+ it('a record whose anchor is gone is no cut', () => {
+ expect(compactCuts(messages, [record({ upToMessageId: 'gone' })])).toEqual([])
+ })
+
+ it('the notice an auto-compaction wrote up to 3.0.8 is left out, the line says it', () => {
+ const old = [...messages.slice(0, 6), msg(`${AUTO_OK_PREFIX}r1`, { role: 'system', notice: 'info' }), msg('u4')]
+ const cuts = compactCuts(old, [record({ endMessageId: 'a3' })])
+ expect(ids(layerItems(old, cuts, null))).toEqual(['|r1|', 'u3', 'a3', 'u4'])
+ })
+})
+
+describe('a compaction in the middle of an Agent or Code run', () => {
+ const answer = msg('a1', {
+ content: 'final answer',
+ usage: { promptTokens: 1, completionTokens: 1, totalTokens: 2 },
+ agentBlocks: [step('s1', 1), step('s2', 2), cutBlock('k1', 3), step('s3', 4), step('s4', 5)],
+ })
+ const messages = [msg('u0'), msg('a0'), msg('u1'), answer]
+
+ it('the current view starts at the block, inside the answer', () => {
+ const cuts = compactCuts(messages, undefined)
+ expect(cuts).toHaveLength(1)
+ const now = layerItems(messages, cuts, null)
+ expect(ids(now)).toEqual(['|k1|', 'a1'])
+ expect(blocksOf(now, 'a1')).toEqual(['s3', 's4'])
+ // The answer's text and numbers came after the cut and stay with it.
+ const a1 = now[1]
+ expect(a1.kind === 'message' && a1.message.content).toBe('final answer')
+ })
+
+ it('the layer before holds the steps up to the cut, without the final text', () => {
+ const cuts = compactCuts(messages, undefined)
+ const before = layerItems(messages, cuts, 0)
+ expect(ids(before)).toEqual(['u0', 'a0', 'u1', 'a1'])
+ expect(blocksOf(before, 'a1')).toEqual(['s1', 's2'])
+ const a1 = before[3]
+ expect(a1.kind === 'message' && a1.message.content).toBe('')
+ expect(a1.kind === 'message' && a1.message.usage).toBeUndefined()
+ })
+
+ it('two cuts in one answer make two layers', () => {
+ const two = msg('a1', { agentBlocks: [step('s1', 1), cutBlock('k1', 2), step('s2', 3), cutBlock('k2', 4), step('s3', 5)] })
+ const m = [msg('u1'), two]
+ const cuts = compactCuts(m, undefined)
+ expect(cuts.map((c) => c.key)).toEqual(['k1', 'k2'])
+ expect(blocksOf(layerItems(m, cuts, 0), 'a1')).toEqual(['s1'])
+ expect(ids(layerItems(m, cuts, 1))).toEqual(['|k1|', 'a1'])
+ expect(blocksOf(layerItems(m, cuts, 1), 'a1')).toEqual(['s2'])
+ expect(blocksOf(layerItems(m, cuts, null), 'a1')).toEqual(['s3'])
+ })
+})
+
+describe('nothing is lost', () => {
+ // The rule the 2.6.8 guard protected ("a compaction takes nothing away from
+ // the transcript") in its 3.0.9 form: every stored message, and every step
+ // of every answer, is in at least one layer.
+ it('every message and every step is reachable through the layers', () => {
+ const run = msg('a3', { agentBlocks: [step('s1', 201), step('s2', 202), cutBlock('k1', 203), step('s3', 204), cutBlock('k2', 205), step('s4', 206)] })
+ const messages = [msg('u1'), msg('a1'), msg('u2'), msg('a2'), msg('u3'), run, msg('u4'), msg('a4')]
+ const records = [record({ id: 'r1', upToMessageId: 'a1', endMessageId: 'a2', at: 100 })]
+ const cuts = compactCuts(messages, records)
+ expect(cuts.map((c) => c.key)).toEqual(['r1', 'k1', 'k2'])
+
+ const seenMessages = new Set<string>()
+ const seenSteps = new Set<string>()
+ for (let layer = 0; layer <= cuts.length; layer++) {
+ for (const it of layerItems(messages, cuts, layer === cuts.length ? null : layer)) {
+ if (it.kind !== 'message') continue
+ seenMessages.add(it.message.id)
+ for (const b of it.message.agentBlocks ?? []) seenSteps.add(b.id)
+ }
+ }
+ expect([...seenMessages].sort()).toEqual(messages.map((m) => m.id).sort())
+ expect([...seenSteps].sort()).toEqual(['s1', 's2', 's3', 's4'])
+ })
+
+ it('the stored messages are not touched', () => {
+ const answer = msg('a1', { agentBlocks: [step('s1', 1), cutBlock('k1', 2), step('s2', 3)] })
+ const messages = [msg('u1'), answer]
+ const copy = JSON.parse(JSON.stringify(messages))
+ const cuts = compactCuts(messages, undefined)
+ layerItems(messages, cuts, 0)
+ layerItems(messages, cuts, null)
+ expect(messages).toEqual(copy)
+ })
+})
diff --git a/src/lib/__tests__/run-compact-midway.test.ts b/src/lib/__tests__/run-compact-midway.test.ts
index 50008050..f81e240f 100644
--- a/src/lib/__tests__/run-compact-midway.test.ts
+++ b/src/lib/__tests__/run-compact-midway.test.ts
@@ -38,6 +38,7 @@ import { useChatStore } from '../../stores/chatStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useRunActivityStore } from '../../stores/runActivityStore'
import { DEFAULT_SETTINGS } from '../constants'
+import type { AgentBlock } from '../../types/agent-mode'
const summarise = vi.mocked(runCompactSummary)
@@ -189,6 +190,40 @@ describe('compactRunMidway', () => {
expect(all.findIndex((m) => m.id === note.id)).toBe(all.findIndex((m) => m.id === assistantId) - 1)
})
+ it('with the run\'s block list it adds ONE compaction block instead of a notice (3.0.9)', async () => {
+ // David, REA-Test 27.10.: 28.9K/32K, then 17.9K, and nothing to see in the
+ // chat. The block lands among the steps of the answer, where the
+ // transcript draws it as the line "Compacted, 28.9K → 17.9K" and starts
+ // the current view (lib/compact-layers.ts).
+ const { convId, assistantId } = seedConversation()
+ const blocks: AgentBlock[] = []
+ const out = await compactRunMidway({
+ messages: run(30), budgetTokens: 16384, modelWindow: 32768, activeModel: 'ollama::qwen3:8b',
+ convId, beforeMessageId: assistantId, state: newRunCompactState(),
+ onCompacted: (b) => blocks.push(b),
+ })
+ expect(out.compacted).toBe(true)
+ expect(notices(convId)).toEqual([])
+ expect(blocks).toHaveLength(1)
+ expect(blocks[0].compaction).toEqual({ before: out.tokensBefore, after: out.tokensAfter, replaced: out.replaced })
+ // A reader that does not know the field still shows something true.
+ expect(blocks[0].phase).toBe('reflection')
+ expect(blocks[0].content).toMatch(/^Summarised \d+ earlier step messages of this run/)
+ })
+
+ it('a failed compaction adds no block, the warning stays a notice', async () => {
+ const { convId, assistantId } = seedConversation()
+ summarise.mockResolvedValue({ ok: false, summary: { ...EMPTY_SUMMARY }, reason: 'unusable' })
+ const blocks: AgentBlock[] = []
+ await compactRunMidway({
+ messages: run(30), budgetTokens: 16384, modelWindow: 32768, activeModel: 'ollama::qwen3:8b',
+ convId, beforeMessageId: assistantId, state: newRunCompactState(),
+ onCompacted: (b) => blocks.push(b),
+ })
+ expect(blocks).toEqual([])
+ expect(notices(convId).map((n) => n.notice)).toEqual(['warn'])
+ })
+
it('says Compacting while the summary is written and gives the status back after', async () => {
const { convId, assistantId } = seedConversation()
useRunActivityStore.getState().setActivity(convId, { label: 'Reading' })
diff --git a/src/lib/compact-layers.ts b/src/lib/compact-layers.ts
new file mode 100644
index 00000000..74f7b574
--- /dev/null
+++ b/src/lib/compact-layers.ts
@@ -0,0 +1,187 @@
+/**
+ * Compact layers (3.0.9): the transcript as it stood before each compaction.
+ *
+ * Every compaction of a chat is a cut. The current view starts at the newest
+ * cut, with the line "Compacted, 28.9K → 17.9K" on top, the way the Claude
+ * Code desktop app shows it. Each earlier cut opens one layer more: layer k is
+ * the stretch the model was working with right before compaction k, from the
+ * cut before it up to the moment it ran. The rail on the left of the
+ * transcript switches between them.
+ *
+ * Nothing is copied for this. Compaction never deleted a message (the store
+ * keeps every turn and every tool result, see CompactBlock and
+ * run-compact-midway), so a layer is a window onto the stored messages, made
+ * of two kinds of cut:
+ *
+ * - a CompactionRecord (per turn, /compact or the auto trigger). The view
+ * after it starts behind `upToMessageId`; the one before it ends at the
+ * newest message when it ran (`endMessageId`, else `atMessageCount`).
+ * - an agent block with `compaction` set (in the middle of an Agent or Code
+ * run). It sits inside the answer being written, so the cut runs through
+ * that answer: the steps before the block belong to the layer before, the
+ * steps from it on to the view after.
+ *
+ * A cut whose anchor is gone (the message was deleted, a fork was switched)
+ * is no cut any more and is left out, the same rule compactionAnchors follows.
+ */
+
+import type { CompactionRecord, Message } from '../types/chat'
+import type { AgentBlock } from '../types/agent-mode'
+
+/**
+ * Up to 3.0.8 a successful auto-compaction wrote the sentence of /compact as
+ * a notice with this id prefix, because success left no other trace (tester,
+ * 2026-09-03: „Ich glaube, das Werkzeug hat alles"). The record is drawn as a
+ * line now and says the same, so old chats leave those notices out.
+ */
+export const AUTO_OK_PREFIX = 'autocompact-ok-'
+
+/** Where in the stored messages: message index, block index inside it. */
+interface Pos {
+ msg: number
+ block: number
+}
+
+/** One compaction, as the transcript draws it. */
+export interface CompactCut {
+ key: string
+ /** Payload estimate before and after. */
+ before: number
+ after: number
+ trigger: 'auto' | 'manual'
+ at: number
+ /** The rendered summary, for the per-turn record (the run's summary rides
+ * in the working copy only and is not stored). */
+ summary?: string
+ /** The record itself, when this cut is one. */
+ record?: CompactionRecord
+ /** First position of the view after the cut. */
+ start: Pos
+ /** Position right after the end of the view before the cut. */
+ end: Pos
+}
+
+/** What a view is made of: the line at its top, then messages. */
+export type LayerItem =
+ | { kind: 'line'; cut: CompactCut }
+ | { kind: 'message'; message: Message }
+
+const isCompactionBlock = (b: AgentBlock): boolean => !!b.compaction
+
+const before = (a: Pos, b: Pos): boolean => a.msg < b.msg || (a.msg === b.msg && a.block < b.block)
+
+/** Every usable cut of a chat, oldest first. */
+export function compactCuts(
+ messages: readonly Message[],
+ compactions: readonly CompactionRecord[] | undefined,
+): CompactCut[] {
+ const indexOf = new Map(messages.map((m, i) => [m.id, i]))
+ const cuts: CompactCut[] = []
+
+ for (const record of compactions ?? []) {
+ const anchor = indexOf.get(record.upToMessageId)
+ if (anchor === undefined) continue
+ const endIdx = record.endMessageId !== undefined ? indexOf.get(record.endMessageId) : undefined
+ const end = endIdx !== undefined ? endIdx + 1 : Math.min(record.atMessageCount, messages.length)
+ cuts.push({
+ key: record.id,
+ before: record.contextBefore ?? record.tokensBefore,
+ after: record.contextAfter ?? record.tokensAfter,
+ trigger: record.trigger,
+ at: record.at,
+ summary: record.summary,
+ record,
+ start: { msg: anchor + 1, block: 0 },
+ end: { msg: Math.max(end, anchor + 1), block: 0 },
+ })
+ }
+
+ messages.forEach((m, msg) => {
+ m.agentBlocks?.forEach((b, block) => {
+ if (!b.compaction) return
+ cuts.push({
+ key: b.id,
+ before: b.compaction.before,
+ after: b.compaction.after,
+ trigger: 'auto',
+ at: b.timestamp,
+ start: { msg, block },
+ end: { msg, block },
+ })
+ })
+ })
+
+ // In the order they happened. A cut that would start before the one it
+ // follows (data from a hand-edited or imported chat) cannot make a layer
+ // and is dropped instead of producing a view that runs backwards.
+ cuts.sort((a, b) => a.at - b.at)
+ const out: CompactCut[] = []
+ for (const cut of cuts) {
+ const prev = out[out.length - 1]
+ if (prev && before(cut.start, prev.start)) continue
+ out.push(cut)
+ }
+ return out
+}
+
+/** The messages between two positions, an answer cut through where needed. */
+function messagesBetween(messages: readonly Message[], from: Pos, to: Pos | null): Message[] {
+ const out: Message[] = []
+ for (let i = from.msg; i < messages.length; i++) {
+ if (to && (i > to.msg || (i === to.msg && to.block === 0))) break
+ const m = messages[i]
+ const blocks = m.agentBlocks
+ const cutsHere = !!blocks?.some(isCompactionBlock)
+ const head = i === from.msg ? from.block : 0
+ const tail = to && i === to.msg ? to.block : null
+ if (!blocks || (head === 0 && tail === null && !cutsHere)) {
+ out.push(m)
+ continue
+ }
+ const kept = blocks.slice(head, tail ?? undefined).filter((b) => !isCompactionBlock(b))
+ if (tail === null) {
+ // The answer from the cut on: its text, usage and error belong to it.
+ out.push({ ...m, agentBlocks: kept })
+ } else {
+ // The answer up to the cut: only the steps it had taken by then. Its
+ // final text and numbers came later and stay with the view after.
+ out.push({
+ ...m,
+ agentBlocks: kept,
+ content: '',
+ thinking: undefined,
+ usage: undefined,
+ requestUsage: undefined,
+ error: undefined,
+ finishReason: undefined,
+ })
+ }
+ }
+ return out
+}
+
+/**
+ * The items of one view.
+ *
+ * `layer` null (or cuts.length) is the current view. 0 is the stretch before
+ * the first compaction, 1 the one before the second, and so on.
+ */
+export function layerItems(
+ messages: readonly Message[],
+ cuts: readonly CompactCut[],
+ layer: number | null,
+): LayerItem[] {
+ const k = layer === null || layer >= cuts.length ? cuts.length : Math.max(0, layer)
+ const opening = k > 0 ? cuts[k - 1] : null
+ const from = opening ? opening.start : { msg: 0, block: 0 }
+ const to = k < cuts.length ? cuts[k].end : null
+ const items: LayerItem[] = []
+ if (opening) items.push({ kind: 'line', cut: opening })
+ for (const message of messagesBetween(messages, from, to)) {
+ // The notice a successful auto-compaction wrote up to 3.0.8 says what
+ // the line says.
+ if (message.id.startsWith(AUTO_OK_PREFIX)) continue
+ items.push({ kind: 'message', message })
+ }
+ return items
+}
diff --git a/src/lib/run-compact-command.ts b/src/lib/run-compact-command.ts
index 0b57bb04..2e35365b 100644
--- a/src/lib/run-compact-command.ts
+++ b/src/lib/run-compact-command.ts
@@ -112,6 +112,15 @@ export type CompactOutcome =
| { ok: true; record: CompactionRecord }
| { ok: false; reason: CompactRunReason | 'no-conversation' | 'nothing-to-compact'; detail?: string }
+/** How full the payload of this chat is, the same reading the counter shows. */
+function contextFillOf(conv: { id: string; messages: Message[] }) {
+ const sent = useSendSizeStore.getState().byConv[conv.id]
+ return computeContextFill(
+ conv.messages as unknown as FillMessage[],
+ sent ? { tokens: sent.tokens + sent.toolsTokens, atMessageCount: sent.atMessageCount } : undefined,
+ )
+}
+
/** 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() !== ''
@@ -198,56 +207,82 @@ export async function runCompactForConversation(opts: {
const chain = prevIdx >= 0 ? chainToSend(records, records.length - 1) : []
const previousState = chain.length ? stateFromStored(chain) : undefined
- let result = await runCompactSummary({
- turns,
- activeModel: opts.activeModel,
- focus: opts.focus,
- signal: opts.signal,
- previous: previousState,
- window,
- })
- // Scheitert die Zusammenfuehrung, wird wie bisher nur der neue Abschnitt
- // zusammengefasst und als Kettenglied gespeichert. Die alten Datensaetze
- // bleiben unangetastet und gehen weiter mit, es geht also nichts verloren.
- // Abbruch und fehlendes Modell sind keine Gruende fuer einen zweiten Lauf.
- // Der Rueckfall nur, wenn er etwas sparen kann (canSave, oben) und der
- // Grund nicht beim Nutzer oder beim fehlenden Modell liegt.
- if (!result.ok && previousState && canSave
- && result.reason !== 'aborted' && result.reason !== 'no-model') {
- result = await runCompactSummary({
+ // The summary is a model call of its own and can take a while. The
+ // transcript shows "Compacting conversation…" for as long as this runs,
+ // for /compact as for the automatic trigger (3.0.9). Whatever the run said
+ // before comes back afterwards.
+ const activity = useRunActivityStore.getState()
+ const activityBefore = activity.activity[opts.conversationId] ?? null
+ activity.setActivity(opts.conversationId, COMPACTING_ACTIVITY)
+ try {
+ return await summariseAndRecord()
+ } finally {
+ useRunActivityStore.getState().setActivity(opts.conversationId, activityBefore)
+ }
+
+ async function summariseAndRecord(): Promise<CompactOutcome> {
+ if (!opts.activeModel || !conv) return { ok: false, reason: 'no-model' }
+ let result = await runCompactSummary({
turns,
activeModel: opts.activeModel,
focus: opts.focus,
signal: opts.signal,
+ previous: previousState,
window,
})
+ // Scheitert die Zusammenfuehrung, wird wie bisher nur der neue Abschnitt
+ // zusammengefasst und als Kettenglied gespeichert. Die alten Datensaetze
+ // bleiben unangetastet und gehen weiter mit, es geht also nichts verloren.
+ // Abbruch und fehlendes Modell sind keine Gruende fuer einen zweiten Lauf.
+ // Der Rueckfall nur, wenn er etwas sparen kann (canSave, oben) und der
+ // Grund nicht beim Nutzer oder beim fehlenden Modell liegt.
+ if (!result.ok && previousState && canSave
+ && result.reason !== 'aborted' && result.reason !== 'no-model') {
+ result = await runCompactSummary({
+ turns,
+ activeModel: opts.activeModel,
+ focus: opts.focus,
+ signal: opts.signal,
+ window,
+ })
+ }
+ if (!result.ok) return { ok: false, reason: result.reason, detail: result.detail }
+
+ const merged = Boolean(result.merged && previousState)
+ // Was ohne diesen Lauf mitginge: die neuen Zuege, und bei einer
+ // Zusammenfuehrung auch die Kette, die der neue Stand ersetzt.
+ const chainTokens = merged ? chain.reduce((n, r) => n + estimateTokens(r.summary), 0) : 0
+ 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) + chainTokens,
+ tokensAfter: summaryTokens(result.summary),
+ trigger: opts.trigger,
+ at: Date.now(),
+ ...(merged ? { merged: true } : {}),
+ }
+ // The whole payload, for the line in the transcript: what the counter read
+ // before, less what the summary saves. An estimate both ways, like the
+ // counter's own number between two real usage reports.
+ const contextBefore = contextFillOf(conv).used
+ if (contextBefore > 0) {
+ record.contextBefore = contextBefore
+ record.contextAfter = Math.max(0, contextBefore - Math.max(0, record.tokensBefore - record.tokensAfter))
+ }
+ const newest = conv.messages[conv.messages.length - 1]
+ if (newest) record.endMessageId = newest.id
+ // 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 }
}
- if (!result.ok) return { ok: false, reason: result.reason, detail: result.detail }
-
- const merged = Boolean(result.merged && previousState)
- // Was ohne diesen Lauf mitginge: die neuen Zuege, und bei einer
- // Zusammenfuehrung auch die Kette, die der neue Stand ersetzt.
- const chainTokens = merged ? chain.reduce((n, r) => n + estimateTokens(r.summary), 0) : 0
- 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) + chainTokens,
- tokensAfter: summaryTokens(result.summary),
- trigger: opts.trigger,
- at: Date.now(),
- ...(merged ? { merged: true } : {}),
- }
- // 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 }
}
/**
@@ -427,7 +462,6 @@ export async function maybeAutoCompact(opts: {
if (recentAutoFailure(conv.messages)) 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
@@ -441,10 +475,7 @@ export async function maybeAutoCompact(opts: {
// 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,
- )
+ const fill = contextFillOf(conv)
let window = opts.window
let windowIsTrue = opts.windowIsTrue ?? false
@@ -475,27 +506,19 @@ export async function maybeAutoCompact(opts: {
})
if (!verdict.shouldCompact) return null
- // The summary is a model call of its own and can take a while. The status
- // line of the run says so instead of "Starting".
- const { setActivity } = useRunActivityStore.getState()
- setActivity(opts.conversationId, COMPACTING_ACTIVITY)
- let outcome: Awaited<ReturnType<typeof runCompactForConversation>>
- try {
- outcome = await runCompactForConversation({
- conversationId: opts.conversationId,
- activeModel: opts.activeModel,
- trigger: 'auto',
- signal: opts.signal,
- window,
- })
- } finally {
- setActivity(opts.conversationId, null)
- }
+ // runCompactForConversation shows "Compacting conversation…" while the
+ // summary is written, and the record it stores is the line that stays.
+ const outcome = await runCompactForConversation({
+ conversationId: opts.conversationId,
+ activeModel: opts.activeModel,
+ trigger: 'auto',
+ signal: opts.signal,
+ window,
+ })
if (!outcome.ok) {
meldeAutoFehlschlag(opts.conversationId, outcome)
return null
}
- meldeAutoErfolg(opts.conversationId, outcome)
return outcome.record
}
@@ -552,34 +575,9 @@ export async function maybeAutoCompact(opts: {
*/
const AUTO_FAIL_PREFIX = 'autocompact-fail-'
-/**
- * Same prefix trick for the case that WORKED.
- *
- * The asymmetry was the bug. A failed auto-compaction has written a visible
- * notice into the transcript since it existed; a successful one wrote nothing
- * — although success is the case that changes what the model can still see.
- * The window kept showing the full conversation, the request no longer carried
- * it, and the only way to find out was to read the network traffic. A tester
- * put the cost plainly on 2026-09-03: „Ich glaube, das Werkzeug hat alles, und
- * uebernehme falsche Zahlen in einen Artikel."
- *
- * `notice: 'info'`, not 'warn': nothing went wrong. Something happened, and the
- * person it happened to gets to know. The wording is `compactOutcomeMessage`,
- * the same sentence the manual /compact has always shown — including the half
- * that takes the fright out of it: the conversation is still here, only the
- * payload got shorter.
- */
-const AUTO_OK_PREFIX = 'autocompact-ok-'
-
-function meldeAutoErfolg(convId: string, outcome: CompactOutcome & { ok: true }): void {
- useChatStore.getState().addMessage(convId, {
- id: `${AUTO_OK_PREFIX}${outcome.record.id}`,
- role: 'system',
- notice: 'info',
- content: compactOutcomeMessage(outcome),
- timestamp: Date.now(),
- })
-}
+// A successful auto-compaction wrote a notice up to 3.0.8 (prefix
+// 'autocompact-ok-'); since 3.0.9 the record itself is drawn as the line
+// "Compacted, 28.9K → 17.9K". See AUTO_OK_PREFIX in lib/compact-layers.ts.
/** True while the newest own failure notice is fewer than
* MIN_MESSAGES_SINCE_COMPACT messages back. */
diff --git a/src/lib/run-compact-midway.ts b/src/lib/run-compact-midway.ts
index be52fb7a..5f404a66 100644
--- a/src/lib/run-compact-midway.ts
+++ b/src/lib/run-compact-midway.ts
@@ -63,6 +63,7 @@ import { formatCount } from './formatters'
import { useChatStore } from '../stores/chatStore'
import { useSettingsStore } from '../stores/settingsStore'
import { COMPACTING_ACTIVITY, useRunActivityStore } from '../stores/runActivityStore'
+import type { AgentBlock } from '../types/agent-mode'
/**
* Share of the budget the newest steps may keep verbatim. The rest is for the
@@ -299,6 +300,17 @@ export function runCompactNotice(replaced: number, saved: number): string {
return `Summarised ${replaced} earlier step message${replaced === 1 ? '' : 's'} of this run to stay inside the context window, about ${formatCount(saved)} tokens less in every following step. The run goes on from the summary; every result is still here in the chat.`
}
+/** The block that marks a compaction in the middle of a run. */
+export function compactionBlock(replaced: number, before: number, after: number): AgentBlock {
+ return {
+ id: `${RUN_COMPACT_NOTICE_PREFIX}${uuid()}`,
+ phase: 'reflection',
+ content: runCompactNotice(replaced, Math.max(0, before - after)),
+ timestamp: Date.now(),
+ compaction: { before, after, replaced },
+ }
+}
+
function addNotice(convId: string, beforeMessageId: string | undefined, notice: 'info' | 'warn', content: string): void {
const store = useChatStore.getState()
const message = {
@@ -332,6 +344,13 @@ export interface RunCompactInput<T extends DecayMessage> {
signal?: AbortSignal
state: RunCompactState
decay?: DecayOptions<T>
+ /**
+ * The run's own block list (3.0.9). Given, a compaction that worked becomes
+ * a block of the answer being written, at the step where it happened, and
+ * the transcript draws it as one line. Without it the old notice message is
+ * written in front of the answer, as before.
+ */
+ onCompacted?: (block: AgentBlock) => void
}
export interface RunCompactOutcome<T> {
@@ -433,7 +452,9 @@ export async function compactRunMidway<T extends DecayMessage>(
input.state.lastLength = out.length
input.state.count++
input.state.failures = 0
- if (convId) {
+ if (input.onCompacted) {
+ input.onCompacted(compactionBlock(dropped.length, plan.tokens, tokensAfter))
+ } else if (convId) {
addNotice(convId, input.beforeMessageId, 'info',
runCompactNotice(dropped.length, Math.max(0, plan.tokens - tokensAfter)))
}
diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.ts
index afc1554e..2f736306 100644
--- a/src/types/agent-mode.ts
+++ b/src/types/agent-mode.ts
@@ -149,6 +149,14 @@ export interface AgentBlock {
/** v2.4+ — array of tool calls attached to this block (enables parallel execution). */
toolCalls?: AgentToolCall[]
timestamp: number
+ /** Set on the block that marks a compaction in the middle of this run
+ * (3.0.9): the payload estimate before and after, and how many step
+ * messages the summary stands for. The block is a cut, not content: the
+ * transcript draws it as the one line "Compacted, 28.9K → 17.9K" and
+ * starts the current view there (lib/compact-layers.ts). Its phase is
+ * 'reflection' and `content` carries the sentence, so a reader that does
+ * not know the field still shows something true. */
+ compaction?: { before: number; after: number; replaced: number }
}
// Sandbox configuration
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 480e70fb..03b999bf 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -240,6 +240,18 @@ export interface CompactionRecord {
* and on a run whose merge failed and fell back to a plain link.
*/
merged?: boolean
+ /**
+ * The whole payload before and after, estimated, for the transcript line
+ * "Compacted, 28.9K → 17.9K" (3.0.9). `tokensBefore`/`tokensAfter` above
+ * only measure the replaced turns against their summary, which is not the
+ * number the context counter shows. Absent on records from before 3.0.9.
+ */
+ contextBefore?: number
+ contextAfter?: number
+ /** Id of the newest message when it ran: where the view "before this
+ * compaction" ends (lib/compact-layers.ts). Absent on older records,
+ * which fall back to `atMessageCount`. */
+ endMessageId?: string
}
/**