The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(chat): the plan shows no count, stays until the user writes, then leaves a folded row (CA)
purpleb4d1fba757de
diff --git a/e2e/ca-shots.spec.ts b/e2e/ca-shots.spec.tsindex ff48f55f..2b6a50a0 100644--- a/e2e/ca-shots.spec.ts+++ b/e2e/ca-shots.spec.ts@@ -178,6 +178,8 @@ const PLAN_DONE: Turn[] = [] } }],},{ text: '`median()` is implemented and the tests pass.' },+ // The user's next message: the plan leaves the chat (lib/plan-pin.ts).+ { text: 'Sure, the README now mentions `median()`.' },]test.describe('CA shots: pinned plan', () => {@@ -221,11 +223,24 @@ test.describe('CA shots: pinned plan', () => {await page.getByRole('button', { name: 'Code', exact: true }).click()await openNewChat(page)await send(page, 'median() in src/math.ts is missing, implement it and run the tests')- // David, 14.11.2026: finished is the count and the greyed list, nothing more.- await expect(page.getByTestId('plan-count')).toHaveText(/^(\d+) of \1 done$/, { timeout: 60_000 })- await expect(page.getByTestId('plan-pinned').locator('.animate-spin')).toHaveCount(0, { timeout: 60_000 })- await expect(page.getByTestId('plan-pinned')).not.toContainText(/every step done/i)+ // David, 14.11.2026: finished is the list with every tick, no count,+ // no closing line.+ const plan = page.getByTestId('plan-pinned')+ await expect(plan.locator('li[data-state="done"]')).toHaveCount(3, { timeout: 60_000 })+ await expect(plan.locator('.animate-spin')).toHaveCount(0, { timeout: 60_000 })+ await expect(plan).not.toContainText(/every step done|\d+ of \d+/i)await shot(page, `plan-${theme}-1280-5-all-done`)+ // The next message: the pinned plan leaves, a folded "Plan" row stays at+ // the answer it belonged to.+ await send(page, 'thanks, mention it in the README too')+ await expect(page.getByRole('main').getByText('the README now mentions')).toBeVisible({ timeout: 60_000 })+ await expect(page.getByTestId('plan-pinned')).toHaveCount(0)+ const row = page.getByTestId('plan-history')+ await expect(row).toHaveCount(1)+ await shot(page, `plan-${theme}-1280-6-after-next-message`)+ await row.getByTitle('Show the plan').click()+ await expect(row.locator('li[data-state="done"]')).toHaveCount(3)+ await shot(page, `plan-${theme}-1280-7-history-open`)})// The same list in the LU tab's transcript (Agent mode, MessageList).diff --git a/e2e/code-agent-runs-calls-named-function.spec.ts b/e2e/code-agent-runs-calls-named-function.spec.tsindex 4a8a845b..c8de1da9 100644--- a/e2e/code-agent-runs-calls-named-function.spec.ts+++ b/e2e/code-agent-runs-calls-named-function.spec.ts@@ -61,7 +61,7 @@ test('a call named "function" and a !function_call text both run their tool', asawait expect(main.getByText('VERIFIER_READ_DONE')).toBeVisible({ timeout: 30_000 })// The todo list landed in the plan, the file was really read.- await expect(page.getByTestId('plan-pinned').getByTestId('plan-count')).toBeVisible({ timeout: 15_000 })+ await expect(page.getByTestId('plan-pinned').getByTestId('plan-title')).toBeVisible({ timeout: 15_000 })const reads = (await toolCalls(page)).filter((c) => c.cmd === 'fs_read')expect(reads.some((c) => (c.path ?? '').replace(/\\/g, '/').endsWith('core/verifier.py'))).toBe(true)diff --git a/e2e/coding-agent.spec.ts b/e2e/coding-agent.spec.tsindex 5cd44f94..b2f10bde 100644--- a/e2e/coding-agent.spec.ts+++ b/e2e/coding-agent.spec.ts@@ -286,11 +286,13 @@ test('the plan the model writes shows up above the composer and tracks progress'// default like the Claude Code desktop app. The toggle names the state it// is in, so nothing here is assumed.const strip = page.getByTestId('plan-pinned')- await expect(strip.getByTestId('plan-count')).toHaveText('1 of 3 done', { timeout: 15_000 })+ // No count (David, 14.11.2026): the head is "Plan", the rows carry the state.+ await expect(strip.getByTestId('plan-title')).toHaveText('Plan', { timeout: 15_000 })+ await expect(strip.locator('li[data-state="done"]')).toHaveCount(1)await expect(strip.getByText('read the config')).toBeVisible()await expect(strip.getByText('run the suite')).toBeVisible()- // Folded: the counter and the step that is running right now, not the list.+ // Folded: the name and the step that is running right now, not the list.await strip.getByTitle('Collapse the plan').click()await expect(strip.getByTitle('Show every step')).toContainText('patch the parser')await expect(strip.getByText('read the config')).toHaveCount(0)diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 88991d8b..92d23c41 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -2260,6 +2260,12 @@ async function executeTodoWrite(args: ToolArgs, run?: AgentRunContext): Promise<const convId = getActiveConversationId(run)if (!convId) return 'Error: no active conversation to attach a plan to.'+ // The plan from before the user's last message keeps its row in the+ // transcript (lib/plan-pin.ts) before this one takes its place. Loaded on+ // use: plan-pin reads chatStore, and a static import closes a cycle through+ // the tool table at start-up.+ const { archiveRetiredPlan } = await import('../../lib/plan-pin')+ archiveRetiredPlan(convId)const todos = writeTodos(convId, args.todos)if (todos.length === 0 && Array.isArray(args.todos) && args.todos.length > 0) {return 'Error: every item needs a non-empty `content` string. Nothing was written.'diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex ed47a421..814fb90d 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -1,5 +1,5 @@import { registerChatSender } from '../../lib/remote-chat-senders'-import { PlanBar } from './PlanBar'+import { PlanBar, PlanHistoryRow, usePlanHistory } from './PlanBar'import { composeFileMessage } from '../../lib/chat-files'import { useCodex } from '../../hooks/useCodex'import { RequestUsageLine } from './RequestUsageLine'@@ -121,6 +121,8 @@ export function CodexView() {const conversation = conversations.find(c => c.id === activeConversationId)const messages = conversation?.messages || []+ // Plans the user has moved on from, as folded rows under their answers.+ const planRows = usePlanHistory(activeConversationId, conversation?.messages)// CA U7: Try again under the newest failed answer sends the instruction it answered.const lastAssistantId = [...messages].reverse().find((m) => m.role === 'assistant')?.idconst lastInstruction = (() => {@@ -747,6 +749,9 @@ export function CodexView() {{msg.role === 'assistant' && (<RequestUsageLine usage={msg.requestUsage} className="block px-1" />)}+ {msg.role === 'assistant' && planRows.get(msg.id)?.map((todos, k) => (+ <PlanHistoryRow key={k} todos={todos} className="px-1 pt-1" />+ ))}{/* CA U4: files back to before this instruction. */}{!readOnly && msg.role === 'user' && activeConversationId && (<div className="flex justify-end opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsxindex afc0c821..0ba3ebd8 100644--- a/src/components/chat/MessageList.tsx+++ b/src/components/chat/MessageList.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { PlanBar } from './PlanBar'+import { PlanBar, PlanHistoryRow, usePlanHistory } from './PlanBar'import type { CSSProperties } from 'react'import { useChatStore } from '../../stores/chatStore'import { useSettingsStore } from '../../stores/settingsStore'@@ -208,6 +208,8 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelconst messages = conversation?.messagesconst forks = conversation?.forksconst marks = useMemo(() => forkMarks({ messages: messages ?? [], forks }), [messages, forks])+ // Plans the user has moved on from, as folded rows under their answers.+ const planRows = usePlanHistory(conversation?.id, messages)// Decided once per visited conversation, see CONTENT_VISIBILITY_THRESHOLD.// React's documented "adjust state when a prop changes" shape: the branch@@ -347,6 +349,10 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel{!readOnly && message.greetings && message.greetings.length > 1 && message.id === lastVisibleId && !isGenerating && (<GreetingSwitcher conversationId={conversation.id} message={message} />)}+ {message.role === 'assistant' && planRows.get(message.id)?.map((todos, k) => (+ // On the answer text's left edge, like the pinned plan.+ <PlanHistoryRow key={k} todos={todos} className="pl-12 pr-3 pt-1" />+ ))}</div>)})}diff --git a/src/components/chat/PlanBar.tsx b/src/components/chat/PlanBar.tsxindex 844417ff..0ba56c73 100644--- a/src/components/chat/PlanBar.tsx+++ b/src/components/chat/PlanBar.tsx@@ -35,16 +35,22 @@// never as done (a typo must not tick off work). The model replaces the whole// list on every `todo_write`, so a changed plan replaces this list whole.//-// Collapsible to one line ("3 of 5 done · the step that runs"); the line is-// the list's own first line, so folding moves nothing sideways. When the run-// is over, a closing line sits under the list: the plan is done (and whether-// changes still wait for approval), or the run ended with steps open, with-// "Continue" and "Clear plan".+// No count anywhere (David, 14.11.2026): the head says "Plan", the ticks say+// how far it is. Collapsible to one line ("Plan · the step that runs"); the+// line is the list's own first line, so folding moves nothing sideways. When+// the run is over a closing line sits under the list only when something is+// left: changes still waiting for approval, or a run that ended with steps+// open, with "Continue" and "Clear plan". A plan that is through stays as it+// is, every step ticked, until the user writes again; then it leaves the chat+// and keeps a folded "Plan" row at its answer (PlanHistoryRow, lib/plan-pin.ts).-import { useState, type ReactNode } from 'react'+import { useMemo, useState, type ReactNode } from 'react'import { AlertCircle, Check, Circle, ChevronDown, ChevronRight, Loader2, X } from 'lucide-react'import { useTodoStore, type TodoItem } from '../../stores/todoStore'import { useCodexStore } from '../../stores/codexStore'+import { useChatStore } from '../../stores/chatStore'+import { planHistory, retiredAt } from '../../lib/plan-pin'+import type { Message } from '../../types/chat'import { useGenerationStore } from '../../stores/generationStore'import { useStagedChangesStore } from '../../stores/stagedChangesStore'import { runStatusFrom } from '../../lib/run-idle'@@ -71,11 +77,11 @@ export function planDoneLabel(pendingChanges: number): string | null {* unveraendert auf "PLAN 3/4", mit einem Kreisel, der weiterdrehte. Kein Wort* davon, dass nichts mehr laeuft. Die Schlusszeile aus `turn-summary.ts` sagt* es nur, wenn das Modell selbst nichts geschrieben hat; die Liste sagt es- * immer.+ * immer. Seit 14.11.2026 ohne Zahlen (David: kein Zaehler, nirgends); welche+ * Schritte offen sind, zeigt die Liste selbst.*/-export function planStoppedLabel(done: number, total: number): string {- const open = total - done- return `the run ended here, ${done} of ${total} steps done, ${open} still open`+export function planStoppedLabel(): string {+ return 'the run ended before every step was done'}export type PlanRowState = 'done' | 'running' | 'open'@@ -98,11 +104,9 @@ export function planRowStates(todos: TodoItem[], runActive: boolean): PlanRowSta})}-/** "3 of 5 done", the collapsed line's count. */-export function planCountLabel(todos: TodoItem[]): string {- const done = todos.filter((t) => t.status === 'completed').length- return `${done} of ${todos.length} done`-}+/** The list's own name, the only word in its head (David, 14.11.2026: no+ * count, not while it runs and not at the end; the ticks say it). */+export const PLAN_TITLE = 'Plan'/*** The three greys of the list, written as the full text colour thinned out@@ -160,9 +164,21 @@ export function PlanBar({ conversationId, onContinue }: Props) {const runActive = isActiveCodexStatus(runStatusFrom(generating, threadStatus, isRunStopped(conversationId), isRunQueued(conversationId)),)+ // Once the user writes again the plan leaves the chat and keeps a folded+ // row at its answer (lib/plan-pin.ts). A boolean, so a streaming answer does+ // not redraw the list on every token.+ const updatedAt = useTodoStore((s) => (conversationId ? s.updatedAt[conversationId] : undefined))+ const retired = useChatStore((s) => {+ if (!conversationId) return false+ const msgs = s.conversations.find((c) => c.id === conversationId)?.messages+ return msgs ? retiredAt(msgs, updatedAt) !== null : false+ })const [collapsed, setCollapsed] = useState(false)if (!conversationId || !todos || todos.length === 0) return null+ // Gone the moment the user writes, also while the new run starts; a run that+ // writes a plan again brings a new one.+ if (retired) return nullconst states = planRowStates(todos, runActive)const done = todos.filter((t) => t.status === 'completed').length@@ -193,8 +209,8 @@ export function PlanBar({ conversationId, onContinue }: Props) {><Fold size={ICON_SM} className={`shrink-0 ${GLYPH_QUIET} group-hover:text-gray-900 dark:group-hover:text-gray-50 transition-colors`} /><span className={`${LINE} min-w-0 truncate`}>- <span className={TONE.quiet} data-testid="plan-count">- {planCountLabel(todos)}+ <span className={TONE.quiet} data-testid="plan-title">+ {PLAN_TITLE}</span>{collapsed && (<span className={runningIdx >= 0 ? TONE.strong : TONE.normal} title={headline.content}>@@ -216,27 +232,7 @@ export function PlanBar({ conversationId, onContinue }: Props) {{!collapsed && (// Capped so a fifteen-step plan cannot cover the transcript it pins to.- <ul className="mt-1 space-y-0.5 max-h-56 overflow-y-auto scrollbar-thin" data-testid="plan-steps">- {todos.map((t, i) => {- const state = states[i]- const halted = !runActive && t.status === 'in_progress'- return (- <li key={`${i}-${t.content}`} className="flex items-start gap-2" data-state={state}>- {state === 'done' ? (- <Check size={ICON_SM} className={`${GLYPH} ${GLYPH_QUIET}`} />- ) : state === 'running' ? (- <Loader2 size={ICON_SM} className={`${GLYPH} ${TONE.strong} animate-spin`} />- ) : (- <Circle size={ICON_SM} className={`${GLYPH} ${halted ? HINWEIS_TEXT.ruhig : GLYPH_QUIET}`} />- )}- {/* The colour eases over when a step is ticked off; nothing else moves. */}- <span className={`${LINE} min-w-0 break-words transition-colors duration-[var(--motion-slow)] ${ROW_TEXT[state]}`}>- {t.content}- </span>- </li>- )- })}- </ul>+ <PlanSteps todos={todos} states={states} runActive={runActive} />)}{!runActive && allDone && waiting && (@@ -247,7 +243,7 @@ export function PlanBar({ conversationId, onContinue }: Props) {{stoppedShort && (<Abschluss testid="plan-run-stopped" Symbol={AlertCircle}>- {planStoppedLabel(done, todos.length)}.+ {planStoppedLabel()}.{nextOpen && <span> Next: {nextOpen.content}</span>}<div className="mt-1.5 flex flex-wrap gap-1.5">{onContinue && (@@ -275,6 +271,62 @@ export function PlanBar({ conversationId, onContinue }: Props) {)}+/** The steps, one row each: a tick when done, the spinner on the one that+ * runs, an open circle otherwise. Shared by the pinned plan and the folded+ * row it leaves in the transcript. */+function PlanSteps({ todos, states, runActive }: { todos: TodoItem[]; states: PlanRowState[]; runActive: boolean }) {+ return (+ // Capped so a fifteen-step plan cannot cover the transcript it pins to.+ <ul className="mt-1 space-y-0.5 max-h-56 overflow-y-auto scrollbar-thin" data-testid="plan-steps">+ {todos.map((t, i) => {+ const state = states[i]+ const halted = !runActive && t.status === 'in_progress'+ return (+ <li key={`${i}-${t.content}`} className="flex items-start gap-2" data-state={state}>+ {state === 'done' ? (+ <Check size={ICON_SM} className={`${GLYPH} ${GLYPH_QUIET}`} />+ ) : state === 'running' ? (+ <Loader2 size={ICON_SM} className={`${GLYPH} ${TONE.strong} animate-spin`} />+ ) : (+ <Circle size={ICON_SM} className={`${GLYPH} ${halted ? HINWEIS_TEXT.ruhig : GLYPH_QUIET}`} />+ )}+ {/* The colour eases over when a step is ticked off; nothing else moves. */}+ <span className={`${LINE} min-w-0 break-words transition-colors duration-[var(--motion-slow)] ${ROW_TEXT[state]}`}>+ {t.content}+ </span>+ </li>+ )+ })}+ </ul>+ )+}++/**+ * What a plan leaves in the transcript once the user wrote again: one folded+ * line "Plan" under the answer it belonged to, opening to the steps with their+ * ticks. Quiet, the same type and greys as the pinned list; nothing spins,+ * because that run is over.+ */+export function PlanHistoryRow({ todos, className = '' }: { todos: TodoItem[]; className?: string }) {+ const [open, setOpen] = useState(false)+ const Fold = open ? ChevronDown : ChevronRight+ return (+ <div className={`t-control ${className}`} data-testid="plan-history">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ title={open ? 'Fold the plan' : 'Show the plan'}+ className="group flex items-center gap-2 text-left"+ >+ <Fold size={ICON_SM} className={`shrink-0 ${GLYPH_QUIET} group-hover:text-gray-900 dark:group-hover:text-gray-50 transition-colors`} />+ <span className={`${LINE} ${TONE.quiet} group-hover:text-gray-900 dark:group-hover:text-gray-50 transition-colors`}>{PLAN_TITLE}</span>+ </button>+ {open && <PlanSteps todos={todos} states={planRowStates(todos, false)} runActive={false} />}+ </div>+ )+}+/*** The closing line under the list once the run is over: a run that ended with* steps open, or changes that still wait for approval. Neither is an error, so@@ -299,3 +351,17 @@ function Abschluss({</div>)}++/** Answer id -> the plans that hang under it as folded rows (lib/plan-pin.ts). */+export function usePlanHistory(+ conversationId: string | null | undefined,+ messages: readonly Pick<Message, 'id' | 'role' | 'timestamp' | 'hidden'>[] | undefined,+): Map<string, TodoItem[][]> {+ const todos = useTodoStore((s) => (conversationId ? s.byConversation[conversationId] : undefined))+ const updatedAt = useTodoStore((s) => (conversationId ? s.updatedAt[conversationId] : undefined))+ const archived = useTodoStore((s) => (conversationId ? s.archived?.[conversationId] : undefined))+ return useMemo(+ () => planHistory(messages ?? [], todos, updatedAt, archived),+ [messages, todos, updatedAt, archived],+ )+}diff --git a/src/components/chat/__tests__/plan-leaves-with-the-next-message.test.tsx b/src/components/chat/__tests__/plan-leaves-with-the-next-message.test.tsxnew file mode 100644index 00000000..3378f13a--- /dev/null+++ b/src/components/chat/__tests__/plan-leaves-with-the-next-message.test.tsx@@ -0,0 +1,137 @@+/**+ * @vitest-environment jsdom+ *+ * David, 14.11.2026: the pinned plan stays, ticks and all, until the user sends+ * the next message. Then it leaves the chat and the space is free again. The+ * transcript keeps it as a folded "Plan" row under the answer it belonged to+ * (lib/plan-pin.ts), and a run that writes a new plan does not erase it.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { act, cleanup, fireEvent, render } from '@testing-library/react'+import { PlanBar, PlanHistoryRow } from '../PlanBar'+import { useTodoStore, writeTodos, type TodoItem } from '../../../stores/todoStore'+import { useChatStore } from '../../../stores/chatStore'+import { useGenerationStore } from '../../../stores/generationStore'+import { archiveRetiredPlan, isPlanRetired, planHistory, retiredAt } from '../../../lib/plan-pin'+import type { Message } from '../../../types/chat'++const CONV = 'conv-leaves'+const DONE: TodoItem[] = [+ { content: 'Read the file', status: 'completed' },+ { content: 'Write median()', status: 'completed' },+]++const msg = (id: string, role: Message['role'], timestamp: number, extra: Partial<Message> = {}): Message =>+ ({ id, role, content: id, timestamp, ...extra }) as Message++function seedChat(messages: Message[]) {+ useChatStore.setState({ conversations: [{ id: CONV, title: 't', messages, createdAt: 0, updatedAt: 0 } as never] } as never)+}++beforeEach(() => {+ useTodoStore.setState({ byConversation: {}, updatedAt: {}, archived: {} })+ useGenerationStore.setState((s) => ({ generating: { ...s.generating, [CONV]: false } }))+})+afterEach(() => cleanup())++describe('retiredAt', () => {+ const thread = [msg('u1', 'user', 100), msg('a1', 'assistant', 110), msg('u2', 'user', 300), msg('a2', 'assistant', 310)]++ it('a plan written in the newest run is still the current one', () => {+ expect(retiredAt(thread, 320)).toBeNull()+ })++ it('a visible user message after its last update retires it, under the answer it was written in', () => {+ expect(retiredAt(thread, 150)).toEqual({ anchorId: 'a1' })+ })++ it('hidden messages (a wake, a nudge) do not count as the user writing', () => {+ const t = [msg('u1', 'user', 100), msg('a1', 'assistant', 110), msg('w', 'user', 300, { hidden: true })]+ expect(retiredAt(t, 150)).toBeNull()+ })+})++describe('the pinned plan', () => {+ it('stays with every tick after the run, until the user writes', () => {+ seedChat([msg('u1', 'user', 1), msg('a1', 'assistant', 2)])+ writeTodos(CONV, DONE)+ const v = render(<PlanBar conversationId={CONV} />)+ expect(v.getByTestId('plan-pinned')).toBeTruthy()+ expect([...v.getByTestId('plan-steps').querySelectorAll('li')].map((r) => r.getAttribute('data-state'))).toEqual(['done', 'done'])+ act(() => {+ useChatStore.getState().addMessage(CONV, msg('u2', 'user', Date.now() + 1))+ })+ expect(v.queryByTestId('plan-pinned')).toBeNull()+ expect(isPlanRetired(CONV)).toBe(true)+ })++ it('a run that ended early also stays until the user writes', () => {+ seedChat([msg('u1', 'user', 1), msg('a1', 'assistant', 2)])+ writeTodos(CONV, [{ content: 'Read the file', status: 'completed' }, { content: 'Write median()', status: 'in_progress' }])+ const v = render(<PlanBar conversationId={CONV} />)+ expect(v.getByTestId('plan-run-stopped')).toBeTruthy()+ act(() => { useChatStore.getState().addMessage(CONV, msg('u2', 'user', Date.now() + 1)) })+ expect(v.queryByTestId('plan-pinned')).toBeNull()+ })++ it('the model keeps its plan: nothing is cleared, only no longer pinned', () => {+ seedChat([msg('u1', 'user', 1), msg('a1', 'assistant', 2)])+ writeTodos(CONV, DONE)+ act(() => { useChatStore.getState().addMessage(CONV, msg('u2', 'user', Date.now() + 1)) })+ expect(useTodoStore.getState().getTodos(CONV)).toEqual(DONE)+ })+})++describe('the folded row it leaves', () => {+ it('is one line "Plan" that opens to the ticked steps, nothing spinning', () => {+ const v = render(<PlanHistoryRow todos={[...DONE, { content: 'Run the tests', status: 'in_progress' }]} />)+ expect(v.getByTestId('plan-history').textContent).toBe('Plan')+ expect(v.queryByTestId('plan-steps')).toBeNull()+ fireEvent.click(v.getByTitle('Show the plan'))+ const rows = [...v.getByTestId('plan-steps').querySelectorAll('li')]+ expect(rows.map((r) => r.getAttribute('data-state'))).toEqual(['done', 'done', 'open'])+ expect(v.container.querySelectorAll('.animate-spin')).toHaveLength(0)+ fireEvent.click(v.getByTitle('Fold the plan'))+ expect(v.queryByTestId('plan-steps')).toBeNull()+ })++ it('a new plan from the next run archives the old one under its answer first', () => {+ const t0 = Date.now()+ seedChat([msg('u1', 'user', t0 - 10), msg('a1', 'assistant', t0 - 5)])+ writeTodos(CONV, DONE)+ act(() => { useChatStore.getState().addMessage(CONV, msg('u2', 'user', Date.now() + 5)) })+ archiveRetiredPlan(CONV)+ const NEXT: TodoItem[] = [{ content: 'Update the README', status: 'in_progress' }]+ useTodoStore.setState((s) => ({ updatedAt: { ...s.updatedAt, [CONV]: Date.now() + 10 } }))+ writeTodos(CONV, NEXT)+ useTodoStore.setState((s) => ({ updatedAt: { ...s.updatedAt, [CONV]: Date.now() + 10 } }))+ const s = useTodoStore.getState()+ const messages = useChatStore.getState().conversations[0].messages+ const rows = planHistory(messages, s.byConversation[CONV], s.updatedAt[CONV], s.archived[CONV])+ expect(rows.get('a1')).toEqual([DONE])+ // The new plan is the pinned one, not a row.+ expect([...rows.values()].flat()).not.toContainEqual(NEXT)+ })++ it('todo_write archives before it writes', async () => {+ const { readFileSync } = await import('node:fs')+ const src = readFileSync('src/api/mcp/builtin-tools.ts', 'utf8')+ const at = src.indexOf('async function executeTodoWrite')+ const body = src.slice(at, src.indexOf('\n}\n', at))+ expect(body.indexOf('archiveRetiredPlan(convId)')).toBeGreaterThan(0)+ expect(body.indexOf('archiveRetiredPlan(convId)')).toBeLessThan(body.indexOf('writeTodos(convId'))+ })++ it('both transcripts draw the rows under the answers', async () => {+ const { readFileSync } = await import('node:fs')+ const read = (p: string) => readFileSync(`src/components/chat/${p.replace('../', '')}`, 'utf8')+ expect(read('../MessageList.tsx')).toMatch(/planRows\.get\(message\.id\)\?\.map/)+ expect(read('../CodexView.tsx')).toMatch(/planRows\.get\(msg\.id\)\?\.map/)+ })++ it('a deleted chat takes its archive with it', () => {+ useTodoStore.getState().archivePlan(CONV, 'a1', DONE)+ useTodoStore.getState().forgetConversation(CONV)+ expect(useTodoStore.getState().archived[CONV]).toBeUndefined()+ })+})diff --git a/src/components/chat/__tests__/plan-pinned-under-the-newest-message.test.tsx b/src/components/chat/__tests__/plan-pinned-under-the-newest-message.test.tsxindex c7ec6bef..13076bf1 100644--- a/src/components/chat/__tests__/plan-pinned-under-the-newest-message.test.tsx+++ b/src/components/chat/__tests__/plan-pinned-under-the-newest-message.test.tsx@@ -14,7 +14,7 @@*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { act, cleanup, fireEvent, render } from '@testing-library/react'-import { PlanBar, planRowStates, planCountLabel } from '../PlanBar'+import { PlanBar, planRowStates } from '../PlanBar'import { useTodoStore, writeTodos, type TodoItem } from '../../../stores/todoStore'import { useGenerationStore } from '../../../stores/generationStore'import { useStagedChangesStore } from '../../../stores/stagedChangesStore'@@ -52,9 +52,6 @@ describe('planRowStates', () => {expect(planRowStates(PLAN, false)).toEqual(['done', 'open', 'open'])})- it('counts done steps for the folded line', () => {- expect(planCountLabel(PLAN)).toBe('1 of 3 done')- })})describe('PlanBar, pinned in the transcript', () => {@@ -72,7 +69,9 @@ describe('PlanBar, pinned in the transcript', () => {expect(box.className).toMatch(/\bbottom-0\b/)const rows = [...v.getByTestId('plan-steps').querySelectorAll('li')]expect(rows.map((r) => r.getAttribute('data-state'))).toEqual(['done', 'running', 'open'])- expect(v.getByTestId('plan-count').textContent).toBe('1 of 3 done')+ // No count (David, 14.11.2026): the head is the word, the ticks say how far.+ expect(v.getByTestId('plan-title').textContent).toBe('Plan')+ expect(box.textContent).not.toMatch(/\d+\s*(?:of|\/)\s*\d+/)expect(v.container.querySelectorAll('.animate-spin')).toHaveLength(1)// No closing box while the run goes.expect(v.queryByTestId('plan-all-done')).toBeNull()@@ -128,14 +127,15 @@ describe('PlanBar, pinned in the transcript', () => {expect(v.queryByText('Write median()')).toBeNull()})- it('folds to one line with the count and the running step', () => {+ it('folds to one line with its name and the running step', () => {running(true)writeTodos(CONV, PLAN)const v = render(<PlanBar conversationId={CONV} />)fireEvent.click(v.getByTitle('Collapse the plan'))expect(v.queryByTestId('plan-steps')).toBeNull()- expect(v.getByTestId('plan-pinned').textContent).toContain('1 of 3 done')+ expect(v.getByTestId('plan-pinned').textContent).toContain('Plan')expect(v.getByTestId('plan-pinned').textContent).toContain('Write median()')+ expect(v.getByTestId('plan-pinned').textContent).not.toMatch(/of 3/)fireEvent.click(v.getByTitle('Show every step'))expect(v.getByTestId('plan-steps')).toBeTruthy()})@@ -144,7 +144,8 @@ describe('PlanBar, pinned in the transcript', () => {// David, 14.11.2026, on the live build: drop the tick and "every step done".writeTodos(CONV, PLAN.map((t) => ({ ...t, status: 'completed' as const })))const v = render(<PlanBar conversationId={CONV} />)- expect(v.getByTestId('plan-count').textContent).toBe('3 of 3 done')+ expect(v.getByTestId('plan-title').textContent).toBe('Plan')+ expect(v.getByTestId('plan-pinned').textContent).not.toMatch(/3 of 3|3\/3/)expect([...v.getByTestId('plan-steps').querySelectorAll('li')].map((r) => r.getAttribute('data-state'))).toEqual(['done', 'done', 'done'])expect(v.getByTestId('plan-pinned').textContent).not.toMatch(/every step done/i)@@ -165,7 +166,8 @@ describe('PlanBar, pinned in the transcript', () => {const onContinue = vi.fn()const v = render(<PlanBar conversationId={CONV} onContinue={onContinue} />)const box = v.getByTestId('plan-run-stopped')- expect(box.textContent).toContain('the run ended here, 1 of 3 steps done, 2 still open')+ expect(box.textContent).toContain('the run ended before every step was done')+ expect(box.textContent).not.toMatch(/of 3/)expect(box.textContent).toContain('Next: Write median()')expect(v.container.querySelectorAll('.animate-spin')).toHaveLength(0)fireEvent.click(v.getByTestId('plan-continue'))diff --git a/src/components/chat/__tests__/plan-sagt-wann-der-lauf-endete.test.ts b/src/components/chat/__tests__/plan-sagt-wann-der-lauf-endete.test.tsindex 4b9ad77b..66855a1a 100644--- a/src/components/chat/__tests__/plan-sagt-wann-der-lauf-endete.test.ts+++ b/src/components/chat/__tests__/plan-sagt-wann-der-lauf-endete.test.ts@@ -32,18 +32,12 @@ const here = dirname(fileURLToPath(import.meta.url))const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')describe('planStoppedLabel', () => {- it('nennt die Zahl UND dass nichts mehr laeuft', () => {- expect(planStoppedLabel(3, 4)).toBe('the run ended here, 3 of 4 steps done, 1 still open')- })-- it('zaehlt die offenen Schritte im Plural richtig', () => {- expect(planStoppedLabel(1, 31)).toBe('the run ended here, 1 of 31 steps done, 30 still open')- })-- it('behauptet nie ein Ende, das die Leiste gar nicht zeigt', () => {- // Ein fertiger Plan geht durch `planDoneLabel`, nicht hier durch. Die- // Zeile darf trotzdem keine negative Restzahl bilden koennen.- expect(planStoppedLabel(4, 4)).toContain('0 still open')+ it('sagt, dass nichts mehr laeuft, ohne Zahlen', () => {+ // Bis 14.11.2026 "the run ended here, 3 of 4 steps done, 1 still open".+ // David: kein Zaehler, weder waehrend der Arbeit noch am Ende; welche+ // Schritte offen sind, zeigt die Liste selbst.+ expect(planStoppedLabel()).toBe('the run ended before every step was done')+ expect(planStoppedLabel()).not.toMatch(/\d/)})})diff --git a/src/lib/plan-pin.ts b/src/lib/plan-pin.tsnew file mode 100644index 00000000..e8a1ddb6--- /dev/null+++ b/src/lib/plan-pin.ts@@ -0,0 +1,78 @@+/**+ * When the pinned plan leaves the chat, and where it stays.+ *+ * David, 14.11.2026: the plan stays pinned under the newest message while the+ * run works and after it ends, ticks and all. Once the user sends the next+ * message it leaves, and the space is free again. The transcript keeps it as a+ * folded "Plan" row under the answer it belonged to, so nothing is lost.+ *+ * Nothing is cleared to get there: the model's plan stays in the todo store,+ * because the loops read it back (resume anchor, open-plan check). "Retired"+ * is worked out from the transcript: a plan is retired once a visible user+ * message came AFTER its last update. A run that writes the plan again brings+ * it back, as a new pinned plan, and the old one goes to the archive first.+ */+import type { Message } from '../types/chat'+import { useChatStore } from '../stores/chatStore'+import { useTodoStore, type ArchivedPlan, type TodoItem } from '../stores/todoStore'++type Msg = Pick<Message, 'id' | 'role' | 'timestamp' | 'hidden'>++/**+ * The answer a plan that was last updated at `updatedAt` hangs under, once a+ * visible user message came after that update; null while it is still the+ * current plan. The answer is the last assistant message before that user+ * message (the one the plan was written in), or null when there is none.+ */+export function retiredAt(messages: readonly Msg[], updatedAt: number | undefined): { anchorId: string | null } | null {+ const since = updatedAt ?? 0+ const i = messages.findIndex((m) => m.role === 'user' && !m.hidden && m.timestamp > since)+ if (i < 0) return null+ for (let j = i - 1; j >= 0; j--) {+ if (messages[j].role === 'assistant' && !messages[j].hidden) return { anchorId: messages[j].id }+ }+ return { anchorId: null }+}++function messagesOf(conversationId: string): readonly Msg[] {+ return useChatStore.getState().conversations.find((c) => c.id === conversationId)?.messages ?? []+}++/** Is the plan of this chat still the pinned one. */+export function isPlanRetired(conversationId: string): boolean {+ const s = useTodoStore.getState()+ if (!s.byConversation[conversationId]?.length) return false+ return retiredAt(messagesOf(conversationId), s.updatedAt[conversationId]) !== null+}++/**+ * Called by todo_write before it writes: a retired plan goes to the archive+ * under its answer, so the new one does not overwrite it in the transcript.+ */+export function archiveRetiredPlan(conversationId: string): void {+ const s = useTodoStore.getState()+ const todos = s.byConversation[conversationId]+ if (!todos?.length) return+ const at = retiredAt(messagesOf(conversationId), s.updatedAt[conversationId])+ if (at?.anchorId) s.archivePlan(conversationId, at.anchorId, todos)+}++/**+ * The plans the transcript shows as folded rows: answer id -> plans under it.+ * The archive, plus the current plan once it is retired.+ */+export function planHistory(+ messages: readonly Msg[],+ todos: TodoItem[] | undefined,+ updatedAt: number | undefined,+ archived: ArchivedPlan[] | undefined,+): Map<string, TodoItem[][]> {+ const out = new Map<string, TodoItem[][]>()+ const add = (id: string, t: TodoItem[]) => out.set(id, [...(out.get(id) ?? []), t])+ for (const a of archived ?? []) add(a.anchorId, a.todos)+ if (todos?.length) {+ const at = retiredAt(messages, updatedAt)+ if (at?.anchorId) add(at.anchorId, todos)+ }+ return out+}diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 4a3b2b9d..0f7982f0 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -142,7 +142,7 @@ export function migratePersistedChat(state: unknown): unknown {export function dropConversationSideState(id: string): void {const steps: [string, () => void][] = [['rag', () => useRAGStore.getState().removeConversation(id)],- ['todos', () => useTodoStore.getState().clearTodos(id)],+ ['todos', () => useTodoStore.getState().forgetConversation(id)],['permissions', () => usePermissionStore.getState().clearConversationOverrides(id)],['staged-changes', () => useStagedChangesStore.getState().clear(id)],['codex', () => useCodexStore.getState().dropConversation(id)],diff --git a/src/stores/todoStore.ts b/src/stores/todoStore.tsindex 60ccaa9c..3f2e5145 100644--- a/src/stores/todoStore.ts+++ b/src/stores/todoStore.ts@@ -27,13 +27,30 @@ export interface TodoItem {status: TodoStatus}+export interface ArchivedPlan {+ /** The assistant message the plan hangs under in the transcript. */+ anchorId: string+ todos: TodoItem[]+}++/** Older plans of one chat that are kept; the oldest go first. */+const MAX_ARCHIVED = 30+interface TodoState {/** conversation id -> that run's plan */byConversation: Record<string, TodoItem[]>/** Wall-clock of the last write per conversation, for the "just updated" cue. */updatedAt: Record<string, number>+ /** conversation id -> earlier plans, each kept at the answer it belonged to+ * (lib/plan-pin.ts). The pinned plan leaves the chat once the user writes+ * again; the transcript keeps it as a folded "Plan" row. */+ archived: Record<string, ArchivedPlan[]>+setTodos: (conversationId: string, todos: TodoItem[]) => void+ archivePlan: (conversationId: string, anchorId: string, todos: TodoItem[]) => void+ /** Everything of a chat, its archive included: for a deleted chat. */+ forgetConversation: (conversationId: string) => voidgetTodos: (conversationId: string | null | undefined) => TodoItem[]clearTodos: (conversationId: string) => void}@@ -64,6 +81,7 @@ export const useTodoStore = create<TodoState>()((set, get) => ({byConversation: {},updatedAt: {},+ archived: {},setTodos: (conversationId, todos) =>set((s) => ({@@ -71,6 +89,24 @@ export const useTodoStore = create<TodoState>()(updatedAt: { ...s.updatedAt, [conversationId]: Date.now() },})),+ archivePlan: (conversationId, anchorId, todos) =>+ set((s) => {+ if (todos.length === 0) return {}+ const kept = (s.archived[conversationId] ?? []).filter((a) => a.anchorId !== anchorId)+ return { archived: { ...s.archived, [conversationId]: [...kept, { anchorId, todos }].slice(-MAX_ARCHIVED) } }+ }),++ forgetConversation: (conversationId) =>+ set((s) => {+ const byConversation = { ...s.byConversation }+ const updatedAt = { ...s.updatedAt }+ const archived = { ...s.archived }+ delete byConversation[conversationId]+ delete updatedAt[conversationId]+ delete archived[conversationId]+ return { byConversation, updatedAt, archived }+ }),+getTodos: (conversationId) =>(conversationId && get().byConversation[conversationId]) || [],