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.

context list: what fills the window, and a calm note for small local agent windows

purpled1f822c3d913
diff --git a/e2e/u5-context-shots.spec.ts b/e2e/u5-context-shots.spec.ts
new file mode 100644
index 00000000..d6bd0396
--- /dev/null
+++ b/e2e/u5-context-shots.spec.ts
@@ -0,0 +1,97 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { seedOnboardingDone } from './support/cloud-mock'
+import { openNewChat } from './support/ui'
+
+/**
+ * Pictures of the open context list in the Code tab for the CA review (U5):
+ * what fills the window, and the small window note. Not a test of anything.
+ * Runs only when LU_CA_SHOTS names a folder:
+ *
+ * LU_CA_SHOTS=/path LU_E2E_PORT=5431 npx playwright test e2e/u5-context-shots.spec.ts --project=chromium
+ */
+const OUT = process.env.LU_CA_SHOTS
+
+const MATH = 'export function median(xs: number[]): number {\n return 0 // TODO\n}\n'
+
+type Turn = { text?: string; toolCalls?: Array<{ name: string; args: Record<string, unknown> }> }
+const RUN: Turn[] = [
+ { text: 'Let me look at the file first.', toolCalls: [{ name: 'file_read', args: { path: 'src/math.ts' } }] },
+ { text: '`median` returns 0 for now. It needs a sort and the middle value.' },
+]
+
+type Theme = 'dark' | 'light'
+
+async function boot(page: Page, width: number, theme: Theme, smallWindow: boolean) {
+ await page.addInitScript(tauriMockInit, {
+ assistantReply: 'unused',
+ modelName: DEFAULT_MODEL_NAME,
+ replyChunkDelayMs: 4,
+ agentTurns: RUN,
+ toolDelayMs: 150,
+ files: { 'math.ts': MATH },
+ })
+ await seedOnboardingDone(page)
+ if (smallWindow) {
+ // The Ollama num_ctx the list itself writes, set to 8K before boot.
+ await page.addInitScript(() => {
+ const raw = window.localStorage.getItem('chat-settings')
+ const env = raw ? JSON.parse(raw) : { state: { settings: {} }, version: 10 }
+ env.state.settings = { ...env.state.settings, contextWindowOverride: 8192 }
+ window.localStorage.setItem('chat-settings', JSON.stringify(env))
+ })
+ }
+ await page.setViewportSize({ width, height: 900 })
+ await page.goto('/')
+ const isDark = await page.evaluate(() => document.documentElement.classList.contains('dark'))
+ if (isDark !== (theme === 'dark')) {
+ await page.getByRole('banner').getByTitle(/^(Light|Dark) Mode$/).click()
+ }
+}
+
+async function toCodeTab(page: Page, width: number) {
+ if (width >= 1024) await page.getByRole('button', { name: 'Code', exact: true }).click()
+ else {
+ await page.getByRole('banner').getByRole('button', { name: 'Main navigation' }).click().catch(() => {})
+ await page.getByRole('button', { name: 'Code', exact: true }).first().click().catch(() => {})
+ }
+ await openNewChat(page)
+}
+
+async function send(page: Page, text: string) {
+ const composer = page.locator('textarea').first()
+ await expect(composer).toBeEnabled({ timeout: 20_000 })
+ await composer.fill(text)
+ await composer.press('Enter')
+}
+
+async function openList(page: Page) {
+ await page.getByRole('button', { name: /^Context window/ }).first().click()
+ await expect(page.getByTestId('context-breakdown')).toBeVisible()
+ await page.waitForTimeout(400)
+}
+
+test.describe('U5 context shots', () => {
+ test.skip(!OUT, 'set LU_CA_SHOTS to a folder')
+ for (const theme of ['dark', 'light'] as const) {
+ for (const width of [1280, 375]) {
+ test(`after a run ${theme} ${width}`, async ({ page }) => {
+ await boot(page, width, theme, false)
+ await toCodeTab(page, width)
+ await send(page, 'median() in src/math.ts returns 0, have a look')
+ await page.waitForTimeout(4000)
+ await openList(page)
+ await page.screenshot({ path: `${OUT}/u5-run-${theme}-${width}.png` })
+ })
+
+ test(`small window ${theme} ${width}`, async ({ page }) => {
+ await boot(page, width, theme, true)
+ await toCodeTab(page, width)
+ await send(page, 'median() in src/math.ts returns 0, have a look')
+ await page.waitForTimeout(4000)
+ await openList(page)
+ await page.screenshot({ path: `${OUT}/u5-small-${theme}-${width}.png` })
+ })
+ }
+ }
+})
diff --git a/src/components/chat/ContextBreakdownPanel.tsx b/src/components/chat/ContextBreakdownPanel.tsx
new file mode 100644
index 00000000..43247f04
--- /dev/null
+++ b/src/components/chat/ContextBreakdownPanel.tsx
@@ -0,0 +1,127 @@
+import { useChatStore } from '../../stores/chatStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useContextBreakdownStore } from '../../stores/contextBreakdownStore'
+import { estimateNextStep, layoutBreakdown, withNewerMessages } from '../../lib/context-breakdown'
+import { resolveCompactThreshold } from '../../lib/compact-trigger'
+import { formatContextWindow } from '../../lib/formatters'
+
+/** A token count in the window's own notation, where 0 is a count, not Auto. */
+function tokensText(n: number): string {
+ return n > 0 ? formatContextWindow(n) : '0'
+}
+
+/**
+ * What fills the context window, like Claude Code's /context (U5).
+ *
+ * Rendered only while the context list is open, so its subscription to the
+ * conversation costs nothing while the user types or a run streams.
+ *
+ * The numbers come from the request the last agent step built
+ * (contextBreakdownStore). Without a step, the conversation as stored is
+ * estimated and the header says "about". Rows an estimate cannot see (the
+ * agent's system prompt, its tools, project files, memory) say so instead of
+ * showing a made-up number.
+ */
+export function ContextBreakdownPanel({
+ window,
+ modelWindow,
+ agent,
+}: {
+ /** The meter's denominator: what one step may send. */
+ window: number
+ /** The model's own window, for the auto-compact 32K rule. */
+ modelWindow: number
+ /** Code tab or Agent mode. */
+ agent: boolean
+}) {
+ const convId = useChatStore((s) => s.activeConversationId)
+ const conv = useChatStore((s) => s.conversations.find((c) => c.id === s.activeConversationId))
+ const stored = useContextBreakdownStore((s) => (convId ? s.byConv[convId] : undefined))
+ const autoCompact = useSettingsStore((s) => s.settings.autoCompact)
+ const autoCompactThreshold = useSettingsStore((s) => s.settings.autoCompactThreshold)
+
+ if (!(window > 0)) return null
+
+ const breakdown = stored
+ ? withNewerMessages(stored, conv?.messages ?? [])
+ : { ...estimateNextStep(conv?.messages ?? [], { systemPrompt: conv?.systemPrompt, agent }), since: 0 }
+ const threshold = resolveCompactThreshold(
+ { autoCompact, autoCompactThreshold },
+ window,
+ modelWindow > 0 ? modelWindow : window,
+ )
+ const lay = layoutBreakdown(breakdown, window, threshold)
+ const about = breakdown.kind === 'estimate'
+ const anyUnknown = breakdown.rows.some((r) => r.unknown)
+ const over = breakdown.total > window
+
+ return (
+ <section
+ data-testid="context-breakdown"
+ aria-label="What fills the context window"
+ className="w-60 max-w-full px-2 pt-1 pb-1.5 flex flex-col gap-1"
+ >
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="t-label text-gray-400">Context use</span>
+ <span data-testid="context-breakdown-total" className="t-micro lu-hud-num text-gray-600 dark:text-gray-300">
+ {about ? 'about ' : ''}{tokensText(breakdown.total)} of {formatContextWindow(window)}
+ </span>
+ </div>
+
+ <div className="relative h-1.5 rounded-full bg-gray-100 dark:bg-white/[0.07] overflow-hidden">
+ <div
+ className={`h-full rounded-full ${over ? 'bg-red-400' : 'bg-gray-400 dark:bg-gray-400'}`}
+ style={{ width: `${lay.usedShare * 100}%` }}
+ />
+ {lay.thresholdShare !== null && (
+ <span
+ aria-hidden
+ data-testid="context-breakdown-threshold"
+ className="absolute top-0 bottom-0 w-px bg-gray-700 dark:bg-gray-200 opacity-60"
+ style={{ left: `${lay.thresholdShare * 100}%` }}
+ />
+ )}
+ </div>
+
+ <ul className="flex flex-col gap-0.5 mt-0.5">
+ {breakdown.rows.map((r) => (
+ <li key={r.key} data-testid={`context-row-${r.key}`} className="grid grid-cols-[1fr_3rem_3.25rem] items-center gap-2 t-micro">
+ <span className="text-gray-600 dark:text-gray-300 truncate">{r.label}</span>
+ <span className="h-1 rounded-full bg-gray-100 dark:bg-white/[0.07] overflow-hidden">
+ <span
+ className="block h-full rounded-full bg-gray-400 dark:bg-gray-500"
+ style={{ width: r.tokens > 0 ? `max(2px, ${lay.share[r.key] * 100}%)` : '0' }}
+ />
+ </span>
+ <span className={`text-right lu-hud-num ${r.unknown ? 'text-gray-400' : 'text-gray-600 dark:text-gray-300'}`}>
+ {r.unknown ? 'not yet' : tokensText(r.tokens)}
+ </span>
+ </li>
+ ))}
+ <li data-testid="context-row-free" className="grid grid-cols-[1fr_3rem_3.25rem] items-center gap-2 t-micro">
+ <span className="text-gray-400">Free</span>
+ <span className="h-1 rounded-full bg-gray-100 dark:bg-white/[0.07] overflow-hidden">
+ <span
+ className="block h-full rounded-full bg-gray-200 dark:bg-white/20"
+ style={{ width: `${(lay.free / window) * 100}%` }}
+ />
+ </span>
+ <span className="text-right lu-hud-num text-gray-400">{tokensText(lay.free)}</span>
+ </li>
+ </ul>
+
+ <p className="t-micro text-gray-400 leading-snug">
+ {lay.thresholdTokens !== null
+ ? `Compacts by itself near ${formatContextWindow(lay.thresholdTokens)}. `
+ : ''}
+ {about
+ ? anyUnknown
+ ? 'Estimated from this chat. The rest shows after the first step.'
+ : 'Estimated from this chat.'
+ : breakdown.since > 0
+ ? 'From the last step that was sent, plus the chat since.'
+ : 'From the last step that was sent.'}
+ </p>
+ </section>
+ )
+}
diff --git a/src/components/chat/ContextDropdown.tsx b/src/components/chat/ContextDropdown.tsx
index 71a6a243..08e5418e 100644
--- a/src/components/chat/ContextDropdown.tsx
+++ b/src/components/chat/ContextDropdown.tsx
@@ -20,6 +20,8 @@ import { ENGINE_DEFAULT_CTX } from '../../lib/builtin-ctx'
import { SOURCE_LABEL, withStoredWindow } from '../../lib/context-source'
import { savedLmStudioContext, withLmStudioPick } from '../../lib/lmstudio-context-pick'
import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'
+import { smallWindowNote } from '../../lib/context-breakdown'
+import { ContextBreakdownPanel } from './ContextBreakdownPanel'
const PRESETS = [4096, 8192, 16384, 32768, 65536, 131072]
/** C77: what a hosted model's own window commonly is. */
@@ -87,7 +89,7 @@ export function ContextDropdown({ children }: { children?: ReactNode }) {
* andere Aufklappmenue der App.
*/
const listeRef = useRef<HTMLDivElement>(null)
- const platz = usePopoverPlatz(listeRef, open)
+ const platz = usePopoverPlatz(listeRef, open, { breiteDeckeln: true })
const [busy, setBusy] = useState(false)
// Reload failure, surfaced instead of swallowed: the engine's start error
// (out of memory for the new ctx, port held by a stranger) is actionable,
@@ -155,6 +157,16 @@ export function ContextDropdown({ children }: { children?: ReactNode }) {
// nicht (30.09.2026). Grau, kein Gelb (Regel vom 04.09.).
const raised = cloud && ctx.sendWindow > DEFAULT_SEND_WINDOW_TOKENS
+ // U5: a local model whose agent window is below 16K. Calm, grey, one line,
+ // and one click to 32K through `apply`, the same lever as the list below.
+ const smallNote = smallWindowNote({
+ provider: ctx.provider,
+ window: ctx.contextWindow,
+ modelMax: ctx.modelMax,
+ use: windowUse,
+ })
+ const meterWindow = ctx.sendWindow > 0 ? ctx.sendWindow : ctx.contextWindow
+
/*
* Die Liste endet an der Decke, und die Decke ist der groesste Eintrag.
*
@@ -343,6 +355,9 @@ export function ContextDropdown({ children }: { children?: ReactNode }) {
{busy ? <Loader2 size={9} className="animate-spin" /> : null}
{applyError && !busy ? <AlertTriangle size={9} className="text-red-400" /> : null}
{raised && !applyError && !busy ? <AlertTriangle size={9} className="text-gray-400" aria-label="Larger context costs more" /> : null}
+ {smallNote && !raised && !applyError && !busy ? (
+ <span data-testid="context-small-window-mark" title={smallNote.text} className="w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-gray-500" />
+ ) : null}
{/* Der Fuellstand IST die Beschriftung. Nur wenn es keinen gibt (leerer
Chat), steht hier wieder das Fenster allein. */}
<span id={valueId}>
@@ -378,6 +393,29 @@ export function ContextDropdown({ children }: { children?: ReactNode }) {
platz.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'
}`}
>
+ {smallNote && (
+ <div
+ data-testid="context-small-window"
+ className="w-60 max-w-full mt-0.5 mb-0.5 px-2 py-1.5 rounded-md bg-gray-50 dark:bg-white/[0.04] t-micro text-gray-600 dark:text-gray-300 leading-snug flex flex-col gap-1"
+ >
+ <span className="flex items-start gap-1.5">
+ <AlertTriangle size={10} className="shrink-0 mt-px text-gray-400" />
+ <span>{smallNote.text}{smallNote.hint ? ` ${smallNote.hint}` : ''}</span>
+ </span>
+ {smallNote.fix !== null && (
+ <button
+ type="button"
+ onClick={() => apply(smallNote.fix as number)}
+ className="self-start ml-4 px-2 py-0.5 rounded border border-gray-200 dark:border-white/10 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/[0.08] t-micro font-medium transition-colors"
+ >
+ Use {formatContextWindow(smallNote.fix)}
+ </button>
+ )}
+ </div>
+ )}
+ <ContextBreakdownPanel window={meterWindow} modelWindow={ctx.contextWindow} agent={windowUse === 'agent'} />
+ <div className="mx-1 border-t border-gray-100 dark:border-white/[0.06]" />
+ {!cloud && <div className="px-2 pt-1 t-label text-gray-400">Context window</div>}
{(!cloud || ctx.sendAdjustable !== false) && (<>
{cloud && ctx.modelWindowSettable && (
<div className="px-2 pt-0.5 t-micro uppercase tracking-wide text-gray-400">Sent per message</div>
diff --git a/src/components/chat/__tests__/u5-context-breakdown-dropdown.test.tsx b/src/components/chat/__tests__/u5-context-breakdown-dropdown.test.tsx
new file mode 100644
index 00000000..ca9b6f37
--- /dev/null
+++ b/src/components/chat/__tests__/u5-context-breakdown-dropdown.test.tsx
@@ -0,0 +1,153 @@
+// @vitest-environment jsdom
+/**
+ * U5: the context list shows what fills the window, and warns calmly when a
+ * local model's agent window is small, with one click to 32K through the
+ * same setting the list itself writes.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/u5-context-breakdown-dropdown.test.tsx
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import type { ActiveContext } from '../../../hooks/useActiveContextWindow'
+
+const reloadOllamaWithWindow = vi.fn(async (..._a: unknown[]) => undefined)
+vi.mock('../../../api/ollama', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../api/ollama')>()),
+ reloadOllamaWithWindow: (...a: unknown[]) => reloadOllamaWithWindow(...a),
+ readLoadedModels: async () => [],
+}))
+const loadLmStudioModel = vi.fn(async (..._a: unknown[]) => undefined)
+vi.mock('../../../api/lmstudio', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../api/lmstudio')>()),
+ loadLmStudioModel: (...a: unknown[]) => loadLmStudioModel(...a),
+}))
+
+let ctx: ActiveContext
+let use: 'chat' | 'agent' = 'agent'
+vi.mock('../../../hooks/useActiveContextWindow', () => ({
+ useActiveContextWindow: () => ctx,
+ useActiveWindowUse: () => use,
+}))
+
+import { ContextDropdown } from '../ContextDropdown'
+import { useModelStore } from '../../../stores/modelStore'
+import { useSettingsStore } from '../../../stores/settingsStore'
+import { useChatStore } from '../../../stores/chatStore'
+import { publishStepBreakdown, useContextBreakdownStore } from '../../../stores/contextBreakdownStore'
+
+const OLLAMA = 'qwen3:8b'
+const LMS = 'openai::gemma-4-31b-it-2'
+
+function ollama(window: number): ActiveContext {
+ return {
+ provider: 'ollama', contextWindow: window, modelMax: 131072, sendWindow: window,
+ isTrue: true, adjustable: true, source: 'probe', windowKey: '',
+ }
+}
+
+const open = () => fireEvent.click(screen.getByRole('button', { name: /^Context window/ }))
+
+let convId = ''
+beforeEach(() => {
+ cleanup()
+ reloadOllamaWithWindow.mockClear()
+ loadLmStudioModel.mockClear()
+ use = 'agent'
+ ctx = ollama(32768)
+ useModelStore.setState({ activeModel: OLLAMA })
+ useSettingsStore.getState().updateSettings({ contextWindowOverride: 0, contextWindowByModel: {}, autoCompact: true, autoCompactThreshold: 0 })
+ useContextBreakdownStore.setState({ byConv: {} })
+ convId = useChatStore.getState().createConversation(OLLAMA, '', 'codex')
+ useChatStore.getState().addMessage(convId, { id: 'u1', role: 'user', content: 'Fix the failing test in src/a.ts', timestamp: 1 })
+})
+
+describe('the breakdown', () => {
+ it('lists every kind, free space, and says "about" before the first step', () => {
+ render(<ContextDropdown />)
+ open()
+ const panel = screen.getByTestId('context-breakdown')
+ for (const label of ['System prompt', 'Tools', 'Project files', 'Memory', 'Conversation', 'Tool results', 'Free']) {
+ expect(within(panel).getByText(label)).toBeTruthy()
+ }
+ expect(screen.getByTestId('context-breakdown-total').textContent).toMatch(/^about .+ of 32K$/)
+ // The agent's own parts are not made up before it ran.
+ expect(within(screen.getByTestId('context-row-tools')).getByText('not yet')).toBeTruthy()
+ expect(within(panel).getByText(/The rest shows after the first step/)).toBeTruthy()
+ // 32K model window: auto-compact runs, and its mark is drawn.
+ expect(screen.getByTestId('context-breakdown-threshold')).toBeTruthy()
+ expect(within(panel).getByText(/Compacts by itself near/)).toBeTruthy()
+ })
+
+ it('shows the last step as sent, without "about"', () => {
+ publishStepBreakdown(convId, [
+ { role: 'system', content: 'You are the coding agent.'.repeat(40) },
+ { role: 'user', content: 'Fix it' },
+ { role: 'tool', content: 'file body '.repeat(200) },
+ ], 2048)
+ render(<ContextDropdown />)
+ open()
+ expect(screen.getByTestId('context-breakdown-total').textContent).not.toMatch(/about/)
+ expect(within(screen.getByTestId('context-row-tools')).getByText('2K')).toBeTruthy()
+ expect(within(screen.getByTestId('context-row-system')).queryByText('not yet')).toBeNull()
+ expect(screen.getByText(/From the last step that was sent\./)).toBeTruthy()
+ })
+})
+
+describe('the small window note', () => {
+ it('no note and no marker at 32K', () => {
+ render(<ContextDropdown />)
+ expect(screen.queryByTestId('context-small-window-mark')).toBeNull()
+ open()
+ expect(screen.queryByTestId('context-small-window')).toBeNull()
+ })
+
+ it('Ollama at 8K in the Code tab: marker, one line, and Use 32K sets the num_ctx override', async () => {
+ ctx = ollama(8192)
+ render(<ContextDropdown />)
+ expect(screen.getByTestId('context-small-window-mark')).toBeTruthy()
+ open()
+ const note = screen.getByTestId('context-small-window')
+ expect(note.textContent).toContain('Small window: agent runs may forget files.')
+ fireEvent.click(within(note).getByRole('button', { name: 'Use 32K' }))
+ await waitFor(() => expect(reloadOllamaWithWindow).toHaveBeenCalledWith(OLLAMA, 'agent'))
+ // The same setting the list writes, no second one.
+ expect(useSettingsStore.getState().settings.contextWindowOverride).toBe(32768)
+ })
+
+ it('LM Studio: the fix is saved per model, like a pick from the list', async () => {
+ ctx = { ...ollama(8192), provider: 'lmstudio', modelMax: 262144 }
+ useModelStore.setState({ activeModel: LMS })
+ render(<ContextDropdown />)
+ open()
+ fireEvent.click(screen.getByRole('button', { name: 'Use 32K' }))
+ await waitFor(() => expect(loadLmStudioModel).toHaveBeenCalledWith('gemma-4-31b-it-2', 32768))
+ expect(useSettingsStore.getState().settings.contextWindowOverride).toBe(0)
+ expect(Object.values(useSettingsStore.getState().settings.contextWindowByModel ?? {})).toContain(32768)
+ })
+
+ it('not in a plain chat, and never for a cloud model', () => {
+ ctx = ollama(8192)
+ use = 'chat'
+ render(<ContextDropdown />)
+ open()
+ expect(screen.queryByTestId('context-small-window')).toBeNull()
+ cleanup()
+
+ use = 'agent'
+ ctx = { ...ollama(8192), provider: 'cloud', windowKey: 'lu-cloud|m', sendAdjustable: true, modelWindow: 8192 }
+ useModelStore.setState({ activeModel: 'lu-cloud::m' })
+ render(<ContextDropdown />)
+ expect(screen.queryByTestId('context-small-window-mark')).toBeNull()
+ open()
+ expect(screen.queryByTestId('context-small-window')).toBeNull()
+ })
+
+ it('a server LU does not start gets the note without the button', () => {
+ ctx = { ...ollama(8192), provider: 'custom', windowKey: 'http://127.0.0.1:8131|m' }
+ render(<ContextDropdown />)
+ open()
+ const note = screen.getByTestId('context-small-window')
+ expect(note.textContent).toMatch(/Start the server with 32K/)
+ expect(within(note).queryByRole('button')).toBeNull()
+ })
+})
diff --git a/src/lib/__tests__/context-breakdown.test.ts b/src/lib/__tests__/context-breakdown.test.ts
new file mode 100644
index 00000000..34ae1701
--- /dev/null
+++ b/src/lib/__tests__/context-breakdown.test.ts
@@ -0,0 +1,216 @@
+/**
+ * U5: what fills the context window, split by kind, and the small window note.
+ *
+ * Run: npx vitest run src/lib/__tests__/context-breakdown.test.ts
+ */
+import { describe, expect, it } from 'vitest'
+import {
+ breakdownOf,
+ estimateNextStep,
+ layoutBreakdown,
+ smallWindowNote,
+ splitSections,
+ withNewerMessages,
+ BREAKDOWN_ORDER,
+ SMALL_WINDOW_FIX_TOKENS,
+} from '../context-breakdown'
+import { estimateTokens } from '../token-estimate'
+import { estimateMessageTokens } from '../context-compaction'
+import { computeContextFill } from '../token-usage'
+import { renderProjectFileSection } from '../project-instructions'
+import { renderRulesSection } from '../lurules'
+import { MEMORY_PREAMBLE, buildTurnContext } from '../turn-context'
+
+const BASE = 'You are the coding agent. Work in the workspace.'
+const AGENTS = renderProjectFileSection({ name: 'AGENTS.md', text: 'Use pnpm. Tabs, not spaces.', truncated: false, warnings: [] })
+const RULES = renderRulesSection({ path: '.lurules', text: 'No new dependencies.', truncated: false })
+const MEMORY = `\n\n${MEMORY_PREAMBLE}\n<remembered_context>\nThe user prefers short answers.\n</remembered_context>`
+const SYSTEM = `${BASE}${MEMORY}${AGENTS}${RULES}\n\nSkills the user approved.`
+
+const row = (b: ReturnType<typeof breakdownOf>, key: string) => b.rows.find((r) => r.key === key)!
+
+describe('splitSections', () => {
+ it('cuts project files and memory out by their own fences', () => {
+ const s = splitSections(SYSTEM)
+ expect(s.projectFiles).toContain('Use pnpm')
+ expect(s.projectFiles).toContain('No new dependencies')
+ expect(s.memory).toContain('The user prefers short answers')
+ expect(s.rest).toContain(BASE)
+ expect(s.rest).toContain('Skills the user approved')
+ expect(s.rest).not.toContain('pnpm')
+ expect(s.rest).not.toContain('short answers')
+ })
+
+ it('finds memory in the turn note behind the user message, and leaves the clock', () => {
+ const note = buildTurnContext({ memory: 'Lives in Berlin.', clock: 'Date and time: Friday 10:00' })
+ const s = splitSections(note)
+ expect(s.memory).toContain('Lives in Berlin')
+ expect(s.rest).toContain('Friday 10:00')
+ })
+
+ it('a text without fences is all rest', () => {
+ expect(splitSections('hello')).toEqual({ projectFiles: '', memory: '', rest: 'hello' })
+ })
+})
+
+describe('breakdownOf', () => {
+ const tools = [{ type: 'function', function: { name: 'file_read', description: 'Read a file', parameters: {} } }]
+ const messages = [
+ { role: 'system', content: SYSTEM },
+ { role: 'user', content: 'Fix the build.' },
+ { role: 'assistant', content: '', tool_calls: [{ function: { name: 'file_read', arguments: { path: 'a.ts' } } }] },
+ { role: 'tool', content: 'export const a = 1\n'.repeat(40) },
+ { role: 'user', content: '<tool_response>{"ok":true}</tool_response>' },
+ { role: 'assistant', content: 'Done.' },
+ ]
+
+ it('has every category in order, and the total is their sum', () => {
+ const b = breakdownOf(messages, tools)
+ expect(b.rows.map((r) => r.key)).toEqual([...BREAKDOWN_ORDER])
+ expect(b.total).toBe(b.rows.reduce((a, r) => a + r.tokens, 0))
+ expect(b.kind).toBe('step')
+ for (const r of b.rows) expect(r.unknown).toBeUndefined()
+ })
+
+ it('puts each part where it belongs', () => {
+ const b = breakdownOf(messages, tools)
+ expect(row(b, 'tools').tokens).toBe(estimateTokens(JSON.stringify(tools)))
+ expect(row(b, 'projectFiles').tokens).toBeGreaterThan(0)
+ expect(row(b, 'memory').tokens).toBeGreaterThan(0)
+ expect(row(b, 'system').tokens).toBeLessThan(estimateTokens(SYSTEM))
+ expect(row(b, 'toolResults').tokens).toBe(
+ estimateTokens('export const a = 1\n'.repeat(40)) + estimateTokens('<tool_response>{"ok":true}</tool_response>') + 8,
+ )
+ // The model's own tool call arguments are part of the conversation.
+ const noCall = breakdownOf(messages.filter((m) => !('tool_calls' in m)), tools)
+ expect(row(b, 'conversation').tokens).toBeGreaterThan(row(noCall, 'conversation').tokens)
+ })
+
+ it('adds up to what the request builder counts, so it matches the meter', () => {
+ const b = breakdownOf(messages, tools)
+ expect(b.total).toBe(
+ estimateMessageTokens(messages as never) + estimateTokens(JSON.stringify(tools)),
+ )
+ })
+
+ it('takes a token count for the tools when the loop already has one', () => {
+ expect(row(breakdownOf(messages, 1234), 'tools').tokens).toBe(1234)
+ expect(row(breakdownOf(messages, []), 'tools').tokens).toBe(0)
+ })
+
+ it('carries the message count it was measured at', () => {
+ expect(breakdownOf([], 0, { atMessageCount: 7 }).atMessageCount).toBe(7)
+ })
+})
+
+describe('estimateNextStep', () => {
+ const stored = [
+ { role: 'system', content: 'a notice the model never sees' },
+ { role: 'user', content: 'Hello there' },
+ { role: 'assistant', content: 'Hi.' },
+ { role: 'assistant', content: ' ' },
+ ]
+
+ it('is labelled an estimate', () => {
+ expect(estimateNextStep(stored, { agent: false }).kind).toBe('estimate')
+ })
+
+ it('on an agent surface it does not invent the parts assembled at run time', () => {
+ const b = estimateNextStep(stored, { agent: true, systemPrompt: 'ignored' })
+ for (const k of ['system', 'tools', 'projectFiles', 'memory']) {
+ expect(row(b, k).unknown).toBe(true)
+ expect(row(b, k).tokens).toBe(0)
+ }
+ expect(row(b, 'conversation').tokens).toBe(estimateTokens('Hello there') + estimateTokens('Hi.') + 8)
+ expect(row(b, 'conversation').unknown).toBeUndefined()
+ })
+
+ it('in a plain chat it counts the stored system prompt and has no project files', () => {
+ const b = estimateNextStep(stored, { agent: false, systemPrompt: 'You are a pirate.' })
+ expect(row(b, 'system').tokens).toBe(estimateTokens('You are a pirate.') + 4)
+ expect(row(b, 'projectFiles').unknown).toBeUndefined()
+ expect(row(b, 'tools').unknown).toBe(true)
+ expect(row(b, 'memory').unknown).toBe(true)
+ })
+})
+
+describe('layoutBreakdown', () => {
+ const b = breakdownOf([{ role: 'user', content: 'x'.repeat(4000) }], 2000)
+
+ it('free space is the window minus the total, never below zero', () => {
+ const l = layoutBreakdown(b, 32768, null)
+ expect(l.free).toBe(32768 - b.total)
+ expect(layoutBreakdown(b, 100, null).free).toBe(0)
+ expect(layoutBreakdown(b, 100, null).usedShare).toBe(1)
+ })
+
+ it('places the compaction mark on the window, or none when off', () => {
+ const l = layoutBreakdown(b, 32768, 0.75)
+ expect(l.thresholdShare).toBe(0.75)
+ expect(l.thresholdTokens).toBe(24576)
+ expect(layoutBreakdown(b, 32768, null).thresholdShare).toBeNull()
+ })
+})
+
+describe('smallWindowNote', () => {
+ const base = { provider: 'ollama' as const, window: 8192, modelMax: 131072, use: 'agent' as const }
+
+ it('warns a local model under 16K on an agent surface, with a 32K fix', () => {
+ const n = smallWindowNote(base)!
+ expect(n.text).toBe('Small window: agent runs may forget files.')
+ expect(n.fix).toBe(SMALL_WINDOW_FIX_TOKENS)
+ expect(smallWindowNote({ ...base, provider: 'lmstudio' })?.fix).toBe(32768)
+ expect(smallWindowNote({ ...base, provider: 'builtin', modelMax: 0 })?.fix).toBe(32768)
+ })
+
+ it('the threshold is 16K: 16K itself is fine', () => {
+ expect(smallWindowNote({ ...base, window: 16383 })).not.toBeNull()
+ expect(smallWindowNote({ ...base, window: 16384 })).toBeNull()
+ expect(smallWindowNote({ ...base, window: 32768 })).toBeNull()
+ })
+
+ it('never warns a cloud model, an unknown one, or a window not known yet', () => {
+ expect(smallWindowNote({ ...base, provider: 'cloud' })).toBeNull()
+ expect(smallWindowNote({ ...base, provider: 'unknown' })).toBeNull()
+ expect(smallWindowNote({ ...base, window: 0 })).toBeNull()
+ })
+
+ it('only where agent work happens', () => {
+ expect(smallWindowNote({ ...base, use: 'chat' })).toBeNull()
+ })
+
+ it('no action where LU cannot set the window', () => {
+ const custom = smallWindowNote({ ...base, provider: 'custom' })!
+ expect(custom.fix).toBeNull()
+ expect(custom.hint).toMatch(/server/)
+ const tiny = smallWindowNote({ ...base, modelMax: 8192 })!
+ expect(tiny.fix).toBeNull()
+ expect(tiny.hint).toMatch(/cannot go to 32K/)
+ })
+})
+
+describe('withNewerMessages', () => {
+ const step = breakdownOf([{ role: 'user', content: 'Fix it' }], 500, { atMessageCount: 2 })
+
+ it('adds what the chat gained after the step, the way the meter does', () => {
+ const stored = [
+ { role: 'user', content: 'Fix it' },
+ { role: 'assistant', content: '' },
+ { role: 'tool', content: 'already inside the step', hidden: true },
+ { role: 'system', content: 'an app notice' },
+ { role: 'assistant', content: 'Done, the test passes now.' },
+ ]
+ const b = withNewerMessages(step, stored)
+ const extra = estimateTokens('Done, the test passes now.') + 4
+ expect(b.since).toBe(extra)
+ expect(b.total).toBe(step.total + extra)
+ expect(row(b, 'conversation').tokens).toBe(row(step, 'conversation').tokens + extra)
+ expect(b.total).toBe(computeContextFill(stored, { tokens: step.total, atMessageCount: 2 }).used)
+ })
+
+ it('leaves an estimate and a stale anchor alone', () => {
+ expect(withNewerMessages(step, [{ role: 'user', content: 'x' }]).since).toBe(0)
+ const est = estimateNextStep([{ role: 'user', content: 'x' }], { agent: false })
+ expect(withNewerMessages(est, [{ role: 'user', content: 'x' }, { role: 'user', content: 'y' }]).since).toBe(0)
+ })
+})
diff --git a/src/lib/context-breakdown.ts b/src/lib/context-breakdown.ts
new file mode 100644
index 00000000..d7ea3247
--- /dev/null
+++ b/src/lib/context-breakdown.ts
@@ -0,0 +1,310 @@
+/**
+ * What fills the context window, split by kind (U5, like Claude Code's
+ * /context).
+ *
+ * The meter on the context button says how full the window is. It does not
+ * say WHY. A coding run on a 16K model is often half full before the first
+ * message: the tool catalogue and the system prompt alone. Without the split
+ * the user cannot tell "my chat is long" apart from "the agent setup is big",
+ * and those want different fixes (compact the chat, or a bigger window).
+ *
+ * Everything here is pure. The agent loops publish the split of the request
+ * they actually built (stores/contextBreakdownStore.ts); without a run the
+ * dropdown asks `estimateNextStep` for what the next step would roughly send.
+ *
+ * The sections are found by the fences their own renderers write:
+ * - project files: lib/project-instructions.ts (AGENTS.md, CLAUDE.md) and
+ * lib/lurules.ts (.lurules)
+ * - memory: lib/turn-context.ts MEMORY_PREAMBLE plus the
+ * <remembered_context> block from stores/memoryStore.ts
+ * Reading the fences instead of asking the loops for each piece keeps the
+ * hook side to one call per step.
+ */
+import { estimateTokens } from './token-estimate'
+import { MEMORY_PREAMBLE } from './turn-context'
+import { computeContextFill, type FillMessage } from './token-usage'
+
+export type BreakdownKey = 'system' | 'tools' | 'projectFiles' | 'memory' | 'conversation' | 'toolResults'
+
+/** In the order the dropdown lists them. */
+export const BREAKDOWN_ORDER: readonly BreakdownKey[] = [
+ 'system', 'tools', 'projectFiles', 'memory', 'conversation', 'toolResults',
+]
+
+export const BREAKDOWN_LABEL: Record<BreakdownKey, string> = {
+ system: 'System prompt',
+ tools: 'Tools',
+ projectFiles: 'Project files',
+ memory: 'Memory',
+ conversation: 'Conversation',
+ toolResults: 'Tool results',
+}
+
+export interface BreakdownRow {
+ key: BreakdownKey
+ label: string
+ tokens: number
+ /** Not known before the first step (an estimate cannot see it). */
+ unknown?: boolean
+}
+
+export interface ContextBreakdown {
+ rows: BreakdownRow[]
+ /** Sum of the rows. */
+ total: number
+ /**
+ * `step`: the request the last agent step built and sent.
+ * `estimate`: what the next step would roughly send, before any run.
+ * The dropdown says "about" for the second.
+ */
+ kind: 'step' | 'estimate'
+ /** Messages in the conversation when it was measured (step only). */
+ atMessageCount?: number
+}
+
+/** The smallest message shape both the wire format and the store share. */
+export interface BreakdownMessage {
+ role: string
+ content: string
+ tool_calls?: ReadonlyArray<{ function?: { name?: string; arguments?: unknown } }>
+ hidden?: boolean
+}
+
+// ── Sections inside one text ───────────────────────────────────────────
+
+const PROJECT_FILE_FENCE = /\n?─── Project instructions from ([^\n]+?) ───[\s\S]*?─── end \1 ───\n?/g
+const LURULES_FENCE = /\n?─── Project rules from \.lurules[\s\S]*?─── end \.lurules ─*\n?/g
+const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+const MEMORY_FENCE = new RegExp(
+ `(?:\\n\\n)?${escapeRe(MEMORY_PREAMBLE)}\\s*(?:<remembered_context>[\\s\\S]*?</remembered_context>|[^\\n]*(?:\\n(?!\\n)[^\\n]*)*)`,
+ 'g',
+)
+
+export interface SplitText {
+ projectFiles: string
+ memory: string
+ rest: string
+}
+
+/** Cut the project file and memory sections out of one text. */
+export function splitSections(text: string): SplitText {
+ let projectFiles = ''
+ let memory = ''
+ let rest = text
+ rest = rest.replace(PROJECT_FILE_FENCE, (m) => { projectFiles += m; return '' })
+ rest = rest.replace(LURULES_FENCE, (m) => { projectFiles += m; return '' })
+ rest = rest.replace(MEMORY_FENCE, (m) => { memory += m; return '' })
+ return { projectFiles, memory, rest }
+}
+
+const tok = (s: string) => (s ? estimateTokens(s) : 0)
+
+/**
+ * Counted the way the request builder counts (estimateMessageTokens in
+ * lib/context-compaction.ts): the content, the tool calls as JSON, and a few
+ * tokens for the role tag. Same arithmetic, so the split adds up to the
+ * number on the meter instead of a second, slightly different one.
+ */
+const ROLE_OVERHEAD = 4
+function toolCallTokens(m: BreakdownMessage): number {
+ return m.tool_calls?.length ? estimateTokens(JSON.stringify(m.tool_calls)) : 0
+}
+
+/** A Hermes-style result rides as a user message on the prompt transport. */
+function isToolResult(m: BreakdownMessage): boolean {
+ return m.role === 'tool' || (m.role === 'user' && m.content.trimStart().startsWith('<tool_response>'))
+}
+
+export interface BreakdownOptions {
+ kind?: ContextBreakdown['kind']
+ atMessageCount?: number
+ /** Rows an estimate cannot know; shown as "after the first step". */
+ unknown?: readonly BreakdownKey[]
+}
+
+/**
+ * The split of one request.
+ *
+ * @param messages the messages as they go on the wire (or the stored ones,
+ * for an estimate)
+ * @param tools the tool catalogue sent beside them, or its token count
+ * when the caller already estimated it
+ */
+export function breakdownOf(
+ messages: readonly BreakdownMessage[],
+ tools: readonly unknown[] | number,
+ opts: BreakdownOptions = {},
+): ContextBreakdown {
+ const sums: Record<BreakdownKey, number> = {
+ system: 0, tools: 0, projectFiles: 0, memory: 0, conversation: 0, toolResults: 0,
+ }
+ sums.tools = typeof tools === 'number'
+ ? Math.max(0, Math.round(tools))
+ : tools.length ? estimateTokens(JSON.stringify(tools)) : 0
+
+ for (const m of messages) {
+ const content = typeof m.content === 'string' ? m.content : ''
+ const whole = estimateTokens(content) + toolCallTokens(m) + ROLE_OVERHEAD
+ if (isToolResult(m)) {
+ sums.toolResults += whole
+ continue
+ }
+ // The fenced parts are estimated on their own; what remains of the
+ // message's own estimate is the rest, so the parts never add up to more
+ // than the message.
+ const parts = splitSections(content)
+ const project = Math.min(whole, tok(parts.projectFiles))
+ const memory = Math.min(whole - project, tok(parts.memory))
+ sums.projectFiles += project
+ sums.memory += memory
+ if (m.role === 'system') sums.system += whole - project - memory
+ else sums.conversation += whole - project - memory
+ }
+
+ const unknown = new Set(opts.unknown ?? [])
+ const rows = BREAKDOWN_ORDER.map((key): BreakdownRow => (
+ unknown.has(key) && sums[key] === 0
+ ? { key, label: BREAKDOWN_LABEL[key], tokens: 0, unknown: true }
+ : { key, label: BREAKDOWN_LABEL[key], tokens: sums[key] }
+ ))
+ return {
+ rows,
+ total: rows.reduce((a, r) => a + r.tokens, 0),
+ kind: opts.kind ?? 'step',
+ ...(opts.atMessageCount !== undefined ? { atMessageCount: opts.atMessageCount } : {}),
+ }
+}
+
+/**
+ * What the next step would roughly send, from the conversation as stored.
+ *
+ * On an agent surface (Code tab, Agent mode) the system prompt, the tool
+ * catalogue, the project files and the memory are assembled at run time, so
+ * before the first step they are marked unknown rather than made up. A plain
+ * chat sends its stored system prompt and never project files.
+ */
+export function estimateNextStep(
+ messages: readonly BreakdownMessage[],
+ o: { systemPrompt?: string; agent: boolean },
+): ContextBreakdown {
+ const wire: BreakdownMessage[] = []
+ if (!o.agent && o.systemPrompt?.trim()) wire.push({ role: 'system', content: o.systemPrompt })
+ for (const m of messages) {
+ if (m.role === 'system') continue
+ if (!m.content?.trim() && !m.tool_calls?.length) continue
+ wire.push(m)
+ }
+ const unknown: BreakdownKey[] = o.agent
+ ? ['system', 'tools', 'projectFiles', 'memory']
+ : ['tools', 'memory']
+ return breakdownOf(wire, 0, { kind: 'estimate', unknown })
+}
+
+/**
+ * The last step plus what the conversation gained since, so the split adds
+ * up to the meter on the button. The meter counts the messages behind the
+ * step's anchor on top of it (computeContextFill, built branch); asking that
+ * same function keeps one rule for what counts. They join the conversation
+ * row. `since` says how much was added.
+ */
+export function withNewerMessages(
+ b: ContextBreakdown,
+ messages: readonly FillMessage[],
+): ContextBreakdown & { since: number } {
+ const at = b.atMessageCount
+ if (b.kind !== 'step' || at === undefined || at > messages.length) return { ...b, since: 0 }
+ const since = computeContextFill(messages as FillMessage[], { tokens: 1, atMessageCount: at }).used - 1
+ if (since <= 0) return { ...b, since: 0 }
+ return {
+ ...b,
+ rows: b.rows.map((r) => (r.key === 'conversation' ? { ...r, tokens: r.tokens + since } : r)),
+ total: b.total + since,
+ since,
+ }
+}
+
+// ── Layout for the dropdown ────────────────────────────────────────────
+
+export interface BreakdownLayout {
+ window: number
+ used: number
+ free: number
+ /** Share of the window, 0..1, per row key. */
+ share: Record<BreakdownKey, number>
+ usedShare: number
+ /** Where auto-compaction fires, 0..1 of the window, or null when off. */
+ thresholdShare: number | null
+ thresholdTokens: number | null
+}
+
+/** Shares of the window and the free space; the window is the meter's. */
+export function layoutBreakdown(
+ b: ContextBreakdown,
+ window: number,
+ threshold: number | null,
+): BreakdownLayout {
+ const w = Math.max(0, window)
+ const share = {} as Record<BreakdownKey, number>
+ for (const r of b.rows) share[r.key] = w > 0 ? Math.min(1, r.tokens / w) : 0
+ const used = Math.min(b.total, w > 0 ? w : b.total)
+ const ok = threshold !== null && threshold > 0 && threshold < 1 && w > 0
+ return {
+ window: w,
+ used,
+ free: Math.max(0, w - b.total),
+ share,
+ usedShare: w > 0 ? Math.min(1, b.total / w) : 0,
+ thresholdShare: ok ? threshold : null,
+ thresholdTokens: ok ? Math.round(threshold * w) : null,
+ }
+}
+
+// ── Small window warning ───────────────────────────────────────────────
+
+/** Below this an agent run keeps too little of what it read. */
+export const SMALL_WINDOW_TOKENS = 16384
+/** What the one-click fix sets. */
+export const SMALL_WINDOW_FIX_TOKENS = 32768
+
+export interface SmallWindowInput {
+ /** useActiveContextWindow().provider */
+ provider: 'ollama' | 'lmstudio' | 'builtin' | 'cloud' | 'custom' | 'unknown'
+ /** The window the agent runs with (0 = not known yet). */
+ window: number
+ /** The model's ceiling, 0 = unknown. */
+ modelMax: number
+ /** The surface: only agent work is warned about. */
+ use: 'chat' | 'agent'
+}
+
+export interface SmallWindowNote {
+ window: number
+ /** The window the action sets, or null when LU cannot set one. */
+ fix: number | null
+ text: string
+ /** Second line when there is no action. */
+ hint?: string
+}
+
+/**
+ * The calm note for a local model whose agent window is small.
+ *
+ * Cloud models are never warned: their window is the model's and fixed, and
+ * the send window there is a cost choice, not a memory problem LU can solve.
+ * A server LU does not start (custom) gets the note without an action,
+ * because LU cannot change that server's window. A model whose own maximum
+ * is below 32K gets the note without the action too.
+ */
+export function smallWindowNote(i: SmallWindowInput): SmallWindowNote | null {
+ if (i.use !== 'agent') return null
+ if (i.provider === 'cloud' || i.provider === 'unknown') return null
+ if (!(i.window > 0) || i.window >= SMALL_WINDOW_TOKENS) return null
+ const text = 'Small window: agent runs may forget files.'
+ if (i.provider === 'custom') {
+ return { window: i.window, fix: null, text, hint: 'Start the server with 32K to fix it.' }
+ }
+ if (i.modelMax > 0 && i.modelMax < SMALL_WINDOW_FIX_TOKENS) {
+ return { window: i.window, fix: null, text, hint: 'This model cannot go to 32K. A larger model helps.' }
+ }
+ return { window: i.window, fix: SMALL_WINDOW_FIX_TOKENS, text }
+}
diff --git a/src/stores/__tests__/contextBreakdownStore.test.ts b/src/stores/__tests__/contextBreakdownStore.test.ts
new file mode 100644
index 00000000..58f36cf9
--- /dev/null
+++ b/src/stores/__tests__/contextBreakdownStore.test.ts
@@ -0,0 +1,48 @@
+/**
+ * U5: the store the agent loops publish their step split to.
+ *
+ * Run: npx vitest run src/stores/__tests__/contextBreakdownStore.test.ts
+ */
+import { beforeEach, describe, expect, it } from 'vitest'
+import { publishStepBreakdown, useContextBreakdownStore } from '../contextBreakdownStore'
+import { useChatStore } from '../chatStore'
+
+beforeEach(() => {
+ useContextBreakdownStore.setState({ byConv: {} })
+})
+
+describe('contextBreakdownStore', () => {
+ it('keeps one split per conversation, the newest wins', () => {
+ publishStepBreakdown('a', [{ role: 'user', content: 'one' }], 10)
+ publishStepBreakdown('b', [{ role: 'user', content: 'two two two' }], 20)
+ publishStepBreakdown('a', [{ role: 'user', content: 'three' }], 30)
+ const s = useContextBreakdownStore.getState().byConv
+ expect(Object.keys(s).sort()).toEqual(['a', 'b'])
+ expect(s.a.rows.find((r) => r.key === 'tools')!.tokens).toBe(30)
+ expect(s.a.kind).toBe('step')
+ })
+
+ it('records how many messages the conversation had', () => {
+ const id = useChatStore.getState().createConversation('m', '', 'codex')
+ useChatStore.getState().addMessage(id, { id: 'u1', role: 'user', content: 'hi', timestamp: 1 })
+ publishStepBreakdown(id, [{ role: 'user', content: 'hi' }], 0)
+ expect(useContextBreakdownStore.getState().byConv[id].atMessageCount).toBe(1)
+ })
+
+ it('ignores a missing conversation id and never throws', () => {
+ publishStepBreakdown(undefined, [], 0)
+ publishStepBreakdown(null, [], 0)
+ expect(useContextBreakdownStore.getState().byConv).toEqual({})
+ expect(() => publishStepBreakdown('x', null as never, 0)).not.toThrow()
+ })
+
+ it('clear removes only that conversation', () => {
+ publishStepBreakdown('a', [], 1)
+ publishStepBreakdown('b', [], 2)
+ useContextBreakdownStore.getState().clear('a')
+ expect(Object.keys(useContextBreakdownStore.getState().byConv)).toEqual(['b'])
+ const before = useContextBreakdownStore.getState()
+ useContextBreakdownStore.getState().clear('nope')
+ expect(useContextBreakdownStore.getState()).toBe(before)
+ })
+})
diff --git a/src/stores/contextBreakdownStore.ts b/src/stores/contextBreakdownStore.ts
new file mode 100644
index 00000000..92de0277
--- /dev/null
+++ b/src/stores/contextBreakdownStore.ts
@@ -0,0 +1,56 @@
+import { create } from 'zustand'
+import { breakdownOf, type BreakdownMessage, type ContextBreakdown } from '../lib/context-breakdown'
+import { useChatStore } from './chatStore'
+
+/**
+ * What the last agent step of a conversation sent, split by kind (U5).
+ *
+ * The context dropdown reads it to show what fills the window. Same life as
+ * sendSizeStore: it describes the run in front of the user, so it is not
+ * persisted.
+ */
+interface ContextBreakdownState {
+ byConv: Record<string, ContextBreakdown>
+ publish: (convId: string, breakdown: ContextBreakdown) => void
+ clear: (convId: string) => void
+}
+
+export const useContextBreakdownStore = create<ContextBreakdownState>((set) => ({
+ byConv: {},
+ publish: (convId, breakdown) =>
+ set((state) => ({ byConv: { ...state.byConv, [convId]: breakdown } })),
+ clear: (convId) =>
+ set((state) => {
+ if (!(convId in state.byConv)) return state
+ const next = { ...state.byConv }
+ delete next[convId]
+ return { byConv: next }
+ }),
+}))
+
+/**
+ * The one call the agent loops make per step, once the request and its tool
+ * catalogue are final:
+ *
+ * publishStepBreakdown(convId, sendMessages, tools)
+ *
+ * `tools` may be the catalogue itself or its token estimate, when the loop
+ * already has it. Never throws: a meter must not break a run.
+ */
+export function publishStepBreakdown(
+ convId: string | null | undefined,
+ messages: readonly BreakdownMessage[],
+ tools: readonly unknown[] | number,
+): void {
+ if (!convId) return
+ try {
+ const atMessageCount =
+ useChatStore.getState().conversations.find((c) => c.id === convId)?.messages.length ?? 0
+ useContextBreakdownStore.getState().publish(
+ convId,
+ breakdownOf(messages, tools, { kind: 'step', atMessageCount }),
+ )
+ } catch {
+ // The dropdown falls back to the estimate.
+ }
+}