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(agent): rewind to before a message, files and chat (CA U4)

purple6ba8a3da0530
diff --git a/e2e/ca-shots.spec.ts b/e2e/ca-shots.spec.ts
index f1f1e0ec..5e69667d 100644
--- a/e2e/ca-shots.spec.ts
+++ b/e2e/ca-shots.spec.ts
@@ -51,6 +51,7 @@ async function boot(page: Page, turns: Turn[], width: number, theme: Theme, hold
holdTools,
toolDelayMs: 250,
files: { 'math.ts': MATH },
+ realWriteStatus: true,
})
await seedOnboardingDone(page)
await page.setViewportSize({ width, height: 900 })
@@ -119,4 +120,27 @@ test.describe('CA shots', () => {
await page.waitForTimeout(2000)
await shot(page, 'agent-dark-1280-2-done')
})
+
+ for (const theme of ['dark', 'light'] as const) {
+ test(`rewind ${theme} 1280`, async ({ page }) => {
+ await boot(page, CODE_RUN, 1280, theme)
+ 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')
+ for (let i = 0; i < 6; i++) {
+ await page.waitForTimeout(1500)
+ const allow = page.getByRole('button', { name: /^(Approve|Apply all|Run ⏎|Run)$/ }).first()
+ if (await allow.isVisible().catch(() => false)) await allow.click()
+ }
+ await page.waitForTimeout(2000)
+ const rewind = page.getByRole('button', { name: 'Rewind' }).first()
+ await page.locator('[data-rewind]').first().hover()
+ await rewind.click()
+ await expect(page.getByRole('dialog', { name: 'Rewind to before this message' })).toBeVisible()
+ await shot(page, `rewind-${theme}-1280-menu`)
+ await page.getByRole('button', { name: 'Files and chat' }).click()
+ await page.waitForTimeout(800)
+ await shot(page, `rewind-${theme}-1280-after`)
+ })
+ }
})
diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.ts
index c8fb54d2..ceb1ea51 100644
--- a/e2e/support/tauri-mock.ts
+++ b/e2e/support/tauri-mock.ts
@@ -249,6 +249,10 @@ export interface TauriMockOptions {
holdTools?: boolean
/** Canned file contents served to fs_read, keyed by path suffix. */
files?: Record<string, string>
+ /** fs_write answers like the real bridge (`status: 'saved'`), so the file
+ * checkpoints of "Rewind to here" record (CA U4). Off by default: older
+ * specs read the historical `{ ok, path }` answer. */
+ realWriteStatus?: boolean
/**
* What Ollama's `/api/tags` reports as already installed. Omit for the
* historical EMPTY answer, which is what makes a box look brand new.
@@ -2054,7 +2058,10 @@ export function tauriMockInit(opts: TauriMockOptions) {
}
case 'fs_write':
record('__E2E_TOOL_CALLS__', { cmd, path: m?.path, content: m?.content })
- return afterToolDelay({ ok: true, path: m?.path })
+ return afterToolDelay(opts.realWriteStatus ? { status: 'saved', path: m?.path } : { ok: true, path: m?.path })
+ case 'fs_delete':
+ record('__E2E_TOOL_CALLS__', { cmd, path: m?.path })
+ return afterToolDelay({ deleted: true })
case 'fs_write_bytes':
// A chat attachment on its way into the working folder. The bytes
// themselves are not kept, only how many base64 characters arrived.
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 0c2464dd..88991d8b 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -16,6 +16,7 @@ import { v4 as uuid } from 'uuid'
import { backendCall, isTauri } from '../backend'
import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact, isReadOnlyShellTurn } from '../agent-context'
import type { AgentRunContext } from '../agent-context'
+import { readBefore, recordWrite, textBefore } from '../../lib/agent-core/checkpoints'
import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
import { WorkflowEngine, buildWorkflowApprovalGate, describeWorkflowCompletion, describeWorkflowStepFailure } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
@@ -865,7 +866,11 @@ async function executeFileWrite(args: ToolArgs, run?: AgentRunContext): Promise<
captureChatArtifact(name, content, mimeForName(name), run)
return `Created "${name}" (${formatBytes(content.length)}). It is shown to the user right here in the chat with a preview and a Download button. Nothing was written to disk. Do not call file_read on it; just tell the user it's ready.`
}
- const data = await backendCall<FsWriteResult>('fs_write', { path, content, ...chatCtx(run) })
+ // CA U4: what the file held before, for "Rewind to here".
+ const target = { path, ...chatCtx(run) }
+ const before = await readBefore(target)
+ const data = await backendCall<FsWriteResult>('fs_write', { ...target, content })
+ if (data.status === 'saved') recordWrite(getActiveConversationId(run) ?? getActiveChatId(run), target, before, data.path)
// Rust returns {status: 'saved'|'unchanged', path: <absolute>, bytes}. Surface
// the real path so the model (and the file-change event) knows WHERE the write
// landed — especially important when chatId is None and Rust routes a relative
@@ -941,6 +946,7 @@ async function executeFileEdit(args: ToolArgs, run?: AgentRunContext): Promise<s
}
const w = await backendCall<FsWriteResult>('fs_write', { path, content: res.content, ...chatCtx(run) })
+ if (w.status === 'saved') recordWrite(getActiveConversationId(run) ?? getActiveChatId(run), { path, ...chatCtx(run) }, textBefore(content), w.path)
const n = res.replacements ?? 1
const note = res.fuzzyCount ? ` ${res.fuzzyCount === 1 ? 'One edit' : `${res.fuzzyCount} edits`} matched with indentation ignored; re-read before editing the same lines again.` : ''
if (w.status === 'saved' && w.path) return `Edited ${shownToolPath(w.path)} (${n} replacement${n === 1 ? '' : 's'}).${note}`
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index ad982c45..78cfbc6c 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -19,6 +19,7 @@ import { isThinkingCompatible, isVisionCompatible, declaredVision } from '../../
import { clampEffort, effortChoices, effortLabel, nextEffort, DEFAULT_EFFORT } from '../../lib/effort'
import type { AgentToolCall } from '../../types/agent-mode'
import type { ImageAttachment } from '../../types/chat'
+import { useComposerFillStore } from '../../stores/composerFillStore'
import { loadChatDrafts, newChatKey, storeChatDrafts, type ChatDrafts } from '../../lib/chat-drafts'
import { MAX_CHAT_IMAGES, prepareChatImages } from '../../lib/chat-image-input'
import { blindModelNotice } from '../../lib/chat-attachment-input'
@@ -312,6 +313,18 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
setMention(null)
}
const textareaRef = useRef<HTMLTextAreaElement>(null)
+ // CA U4: a rewound message comes back into the field once. Decided in the
+ // render, state against state, like the draft switch above (no effect may
+ // move the draft, der-entwurf-wechselt-im-render).
+ const fill = useComposerFillStore((s) => s.fill)
+ const [fillSeen, setFillSeen] = useState(fill?.n ?? 0)
+ if (fill && fill.n !== fillSeen) {
+ setFillSeen(fill.n)
+ setInput(fill.text)
+ }
+ useEffect(() => {
+ if (fillSeen) textareaRef.current?.focus()
+ }, [fillSeen])
const fileInputRef = useRef<HTMLInputElement>(null)
// Text already in the box when dictation started. Interim + final transcripts
// are written as base + transcript, so streaming chunks REPLACE (not stack)
diff --git a/src/components/chat/ChatNotices.tsx b/src/components/chat/ChatNotices.tsx
index 8640440d..6bc9ca9f 100644
--- a/src/components/chat/ChatNotices.tsx
+++ b/src/components/chat/ChatNotices.tsx
@@ -11,7 +11,7 @@
* fuer Anmerkungen und Fehler vorschreibt: eine Zeile, kein Kasten, ruhiges
* Grau oder Rot, und ein x, das sie wegnimmt.
*/
-import { AtSign, Binary, Bot, Download, FileText, FolderOpen, ImageOff, Images, Paperclip, Scissors } from 'lucide-react'
+import { AtSign, Binary, Bot, Download, FileText, FolderOpen, ImageOff, Images, Paperclip, RotateCcw, Scissors } from 'lucide-react'
import { Hinweis } from '../ui/Hinweis'
import { useChatNoticeStore, CONVERSATION_BOUND, type ChatNoticeId } from '../../stores/chatNoticeStore'
import { COMPOSER_MAX_W } from './composer-width'
@@ -33,6 +33,7 @@ const ICON: Record<ChatNoticeId, typeof Paperclip> = {
'agent-for-local-files': Bot,
'create-save': Download,
'file-mention': AtSign,
+ rewind: RotateCcw,
}
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index ebb0ac60..c8c2800f 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -10,6 +10,7 @@ import { useBackgroundAgentWake } from '../../hooks/useBackgroundAgentWake'
import { useGenerationStore } from '../../stores/generationStore'
import { ChatInput } from './ChatInput'
import { SteerNote } from './SteerNote'
+import { RewindHere } from './RewindHere'
import { RunErrorActions } from './RunErrorActions'
import { useSteerQueue } from '../../hooks/useSteerQueue'
import { ChatFileChip } from './ChatFileChip'
@@ -488,7 +489,7 @@ export function CodexView() {
return (
<div
key={msg.id}
- className={`flex gap-2 px-3 py-1 ${msg.role === 'user' ? 'flex-row-reverse' : ''}`}
+ className={`group flex gap-2 px-3 py-1 ${msg.role === 'user' ? 'flex-row-reverse' : ''}`}
>
{/* The same avatar column as in the chat (avatar-slot.ts). */}
{msg.role === 'user' ? (
@@ -745,6 +746,12 @@ export function CodexView() {
{msg.role === 'assistant' && (
<RequestUsageLine usage={msg.requestUsage} className="block px-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">
+ <RewindHere conversationId={activeConversationId} message={msg} />
+ </div>
+ )}
{/* CA U7: the newest failed answer offers a way on. */}
{!readOnly && msg.role === 'assistant' && msg.error && !codexGenerating && msg.id === lastAssistantId && (
<RunErrorActions
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index 8ce793d4..b5aa72c0 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -10,6 +10,7 @@ import { closeOpenMarkdown } from '../../lib/streaming-markdown'
import { ThinkingBlock } from './ThinkingBlock'
import { ToolCallBand } from './ToolCallBand'
import { ReflectionBlock } from './ReflectionBlock'
+import { RewindHere } from './RewindHere'
import { SteerNote } from './SteerNote'
import { groupAgentBlocks } from '../../lib/tool-call-groups'
import { VramSwitchCard } from './VramSwitchCard'
@@ -715,6 +716,7 @@ function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, p
'flex items-center gap-0.5 ' + actionBarVisibility + ' ' +
(isUser ? 'justify-end pr-0.5' : 'justify-start pl-0.5')
}>
+ {isUser && activeConversationId && !readOnly && <RewindHere conversationId={activeConversationId} message={message} />}
{isUser && actions.edit && (
<button onClick={actions.edit} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Edit message" title="Edit"><Pencil size={12} /></button>
)}
diff --git a/src/components/chat/RewindHere.tsx b/src/components/chat/RewindHere.tsx
new file mode 100644
index 00000000..df6df94a
--- /dev/null
+++ b/src/components/chat/RewindHere.tsx
@@ -0,0 +1,143 @@
+// "Rewind" under a user message (CA U4, lib/agent-core/checkpoints.ts).
+//
+// Shown only where the agent wrote files from this message on. The menu says
+// what goes back before anything happens, names what cannot, and says plainly
+// that changes made by commands stay.
+
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { RotateCcw } from 'lucide-react'
+import {
+ dropCheckpointsFrom, planSize, rewindFiles, rewindPlan, rewindSummary, useCheckpointStore,
+} from '../../lib/agent-core/checkpoints'
+import { useChatStore } from '../../stores/chatStore'
+import { useComposerFillStore } from '../../stores/composerFillStore'
+import { CHAT_NOTICE_MS, useChatNoticeStore } from '../../stores/chatNoticeStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { HINWEIS_TEXT } from '../../lib/hinweis'
+import type { Message } from '../../types/chat'
+
+interface Props {
+ conversationId: string
+ message: Pick<Message, 'id' | 'timestamp' | 'content' | 'displayContent'>
+}
+
+const WHY: Record<'binary' | 'too-big' | 'unreadable', string> = {
+ binary: 'not a text file',
+ 'too-big': 'too large to keep',
+ unreadable: 'could not be read before the change',
+}
+
+function base(p: string): string {
+ return p.split(/[\\/]/).pop() || p
+}
+
+export function RewindHere({ conversationId, message }: Props) {
+ // A run is going: rewinding under it would fight its writes.
+ const busy = useGenerationStore((s) => !!s.generating[conversationId])
+ const list = useCheckpointStore((s) => s.byConv[conversationId])
+ const trimmed = useCheckpointStore((s) => s.trimmedBefore[conversationId])
+ const plan = useMemo(() => rewindPlan(conversationId, message.timestamp),
+ // The store slices are the inputs; rewindPlan reads them.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [conversationId, message.timestamp, list, trimmed])
+ const [open, setOpen] = useState(false)
+ const [working, setWorking] = useState(false)
+ const box = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (!open) return
+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) }
+ const onDown = (e: MouseEvent) => { if (box.current && !box.current.contains(e.target as Node)) setOpen(false) }
+ window.addEventListener('keydown', onKey)
+ window.addEventListener('mousedown', onDown)
+ return () => { window.removeEventListener('keydown', onKey); window.removeEventListener('mousedown', onDown) }
+ }, [open])
+
+ if (planSize(plan) === 0) return null
+
+ const files = [...plan.restore, ...plan.remove]
+ const go = async (withChat: boolean) => {
+ setWorking(true)
+ try {
+ const res = await rewindFiles(conversationId, message.timestamp)
+ useChatNoticeStore.getState().show('rewind', rewindSummary(res), res.failed.length ? 'fehler' : 'ruhig', CHAT_NOTICE_MS)
+ if (withChat) {
+ const text = message.displayContent ?? message.content
+ useChatStore.getState().deleteMessagesAfter(conversationId, message.id)
+ dropCheckpointsFrom(conversationId, message.timestamp)
+ useComposerFillStore.getState().put(text)
+ }
+ } finally {
+ setWorking(false)
+ setOpen(false)
+ }
+ }
+
+ return (
+ <div ref={box} className="relative" data-rewind={message.id}>
+ <button
+ type="button"
+ disabled={busy || working}
+ onClick={() => setOpen((v) => !v)}
+ title={busy ? 'Stop the run first' : 'Put the files back as they were before this message'}
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded t-micro text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/[0.06] disabled:opacity-40 disabled:pointer-events-none transition-colors"
+ >
+ <RotateCcw size={11} />
+ Rewind
+ </button>
+ {open && (
+ <div
+ role="dialog"
+ aria-label="Rewind to before this message"
+ className="absolute right-0 top-full mt-1 z-30 w-72 max-w-[calc(100vw-2rem)] rounded-lg border border-gray-200 dark:border-white/[0.1] bg-white dark:bg-[#1c1c1e] shadow-lg p-3 text-left"
+ >
+ <div className="t-body font-medium text-gray-800 dark:text-gray-100">Rewind to before this message?</div>
+ <ul className="mt-1.5 space-y-0.5 max-h-32 overflow-auto">
+ {files.slice(0, 6).map((e) => (
+ <li key={e.target.path} className="t-micro text-gray-600 dark:text-gray-300 truncate" title={e.target.path}>
+ <span className="font-mono">{base(e.target.path)}</span>
+ {e.before.kind === 'missing' ? ' is removed again' : ' goes back'}
+ </li>
+ ))}
+ {files.length > 6 && <li className="t-micro text-gray-500">and {files.length - 6} more</li>}
+ </ul>
+ {plan.unkept.length > 0 && (
+ <div className={`mt-1.5 t-micro ${HINWEIS_TEXT.ruhig}`}>
+ Stays as it is: {plan.unkept.map((u) => `${base(u.path)} (${WHY[u.why]})`).join(', ')}
+ </div>
+ )}
+ {plan.partial && (
+ <div className={`mt-1 t-micro ${HINWEIS_TEXT.ruhig}`}>Older changes were not kept, to save memory.</div>
+ )}
+ <div className="mt-1.5 t-micro text-gray-500 dark:text-gray-400">Changes made by commands stay.</div>
+ <div className="mt-2.5 flex flex-wrap gap-1.5">
+ <button
+ type="button"
+ autoFocus
+ disabled={working}
+ onClick={() => void go(true)}
+ className="lu-control lu-primary px-3 t-control font-medium"
+ >
+ Files and chat
+ </button>
+ <button
+ type="button"
+ disabled={working}
+ onClick={() => void go(false)}
+ className="lu-control px-3 t-control text-gray-800 dark:text-gray-100 border border-gray-300 dark:border-white/15 hover:bg-gray-100 dark:hover:bg-white/[0.06] transition-colors"
+ >
+ Only the files
+ </button>
+ <button
+ type="button"
+ onClick={() => setOpen(false)}
+ className="lu-control px-2 t-control text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.06] transition-colors"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/chat/__tests__/rewind-puts-files-back.test.tsx b/src/components/chat/__tests__/rewind-puts-files-back.test.tsx
new file mode 100644
index 00000000..77a0c1fb
--- /dev/null
+++ b/src/components/chat/__tests__/rewind-puts-files-back.test.tsx
@@ -0,0 +1,82 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * CA U4: "Rewind" under a user message says what goes back, puts the files
+ * back, and with "Files and chat" also takes the chat back to before the
+ * message and returns its text to the composer.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+const disk = vi.hoisted(() => new Map<string, string>())
+vi.mock('../../../api/backend', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ backendCall: vi.fn(async (cmd: string, a: { path: string; content?: string }) => {
+ if (cmd === 'fs_write') { disk.set(a.path, a.content ?? ''); return { status: 'saved', path: a.path } }
+ if (cmd === 'fs_delete') { disk.delete(a.path); return { deleted: true } }
+ throw new Error(cmd)
+ }),
+}))
+
+import { RewindHere } from '../RewindHere'
+import { ChatInput } from '../ChatInput'
+import { useChatStore } from '../../../stores/chatStore'
+import { useCheckpointStore } from '../../../lib/agent-core/checkpoints'
+import { useGenerationStore } from '../../../stores/generationStore'
+
+const MSG = { id: 'u1', role: 'user', content: 'fix median', timestamp: 100 }
+
+beforeEach(() => {
+ disk.clear()
+ disk.set('/ws/math.ts', 'edited by the agent')
+ disk.set('/ws/new.ts', 'made by the agent')
+ useChatStore.setState({ conversations: [{ id: 'c', title: 't', messages: [MSG, { id: 'a1', role: 'assistant', content: 'done', timestamp: 120 }] }] } as never)
+ useCheckpointStore.setState({
+ byConv: { c: [{ messageId: 'u1', at: 110, files: {
+ '/ws/math.ts': { target: { path: '/ws/math.ts', chatId: 'c' }, before: { kind: 'text', content: 'original' } },
+ '/ws/new.ts': { target: { path: '/ws/new.ts', chatId: 'c' }, before: { kind: 'missing' } },
+ } }] },
+ trimmedBefore: {},
+ })
+ useGenerationStore.setState({ generating: {} } as never)
+})
+afterEach(() => cleanup())
+
+describe('Rewind under a user message (CA U4)', () => {
+ it('lists what goes back and says commands stay', () => {
+ render(<RewindHere conversationId="c" message={MSG as never} />)
+ fireEvent.click(screen.getByRole('button', { name: /Rewind/ }))
+ const dlg = screen.getByRole('dialog')
+ expect(dlg.textContent).toMatch(/math\.ts goes back/)
+ expect(dlg.textContent).toMatch(/new\.ts is removed again/)
+ expect(dlg.textContent).toMatch(/Changes made by commands stay/)
+ })
+
+ it('Files and chat: files back, chat back, text in the composer', async () => {
+ render(<><RewindHere conversationId="c" message={MSG as never} /><ChatInput onSend={() => {}} onStop={() => {}} isGenerating={false} modelReady={() => true} /></>)
+ fireEvent.click(screen.getByRole('button', { name: /Rewind/ }))
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Files and chat' })) })
+ expect(disk.get('/ws/math.ts')).toBe('original')
+ expect(disk.has('/ws/new.ts')).toBe(false)
+ expect(useChatStore.getState().conversations[0].messages).toHaveLength(0)
+ expect((document.querySelector('textarea') as HTMLTextAreaElement).value).toBe('fix median')
+ })
+
+ it('Only the files leaves the chat as it is', async () => {
+ render(<RewindHere conversationId="c" message={MSG as never} />)
+ fireEvent.click(screen.getByRole('button', { name: /Rewind/ }))
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Only the files' })) })
+ expect(disk.get('/ws/math.ts')).toBe('original')
+ expect(useChatStore.getState().conversations[0].messages).toHaveLength(2)
+ })
+
+ it('is not offered while a run is going, and not where nothing was written', () => {
+ useGenerationStore.setState({ generating: { c: true } } as never)
+ const v = render(<RewindHere conversationId="c" message={MSG as never} />)
+ expect((screen.getByRole('button', { name: /Rewind/ }) as HTMLButtonElement).disabled).toBe(true)
+ v.unmount()
+ useCheckpointStore.setState({ byConv: {}, trimmedBefore: {} })
+ const w = render(<RewindHere conversationId="c" message={MSG as never} />)
+ expect(w.container.innerHTML).toBe('')
+ })
+})
diff --git a/src/lib/agent-core/__tests__/checkpoints.test.ts b/src/lib/agent-core/__tests__/checkpoints.test.ts
new file mode 100644
index 00000000..f4a0c40a
--- /dev/null
+++ b/src/lib/agent-core/__tests__/checkpoints.test.ts
@@ -0,0 +1,123 @@
+/**
+ * CA U4: "Rewind to here" puts files back the way they were before a message.
+ * A fake disk stands in for fs_read / fs_write / fs_delete.
+ */
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const disk = vi.hoisted(() => new Map<string, string>())
+vi.mock('../../../api/backend', () => ({
+ backendCall: vi.fn(async (cmd: string, a: { path: string; content?: string }) => {
+ const abs = a.path.startsWith('/') ? a.path : `/ws/${a.path}`
+ if (cmd === 'fs_read') {
+ if (!disk.has(abs)) throw new Error(`File not found: ${abs}`)
+ return { content: disk.get(abs), encoding: 'utf8' }
+ }
+ if (cmd === 'fs_write') { disk.set(abs, a.content ?? ''); return { status: 'saved', path: abs } }
+ if (cmd === 'fs_delete') { if (!disk.delete(abs)) throw new Error('File not found'); return { deleted: true } }
+ throw new Error(cmd)
+ }),
+}))
+
+import { backendCall } from '../../../api/backend'
+import { useChatStore } from '../../../stores/chatStore'
+import {
+ MAX_FILE_CHARS, planSize, readBefore, recordWrite, rewindFiles, rewindPlan, rewindSummary, textBefore, useCheckpointStore,
+} from '../checkpoints'
+
+const CONV = 'c1'
+let clock = 1000
+
+function userSays(id: string) {
+ clock += 10
+ const conv = useChatStore.getState().conversations.find((c) => c.id === CONV)!
+ conv.messages.push({ id, role: 'user', content: id, timestamp: clock } as never)
+ vi.setSystemTime(clock + 1)
+ return clock
+}
+
+/** What file_write does: read before, write, record. */
+async function agentWrites(path: string, content: string) {
+ const target = { path, chatId: CONV }
+ const before = await readBefore(target)
+ const w = await backendCall<{ status: string; path: string }>('fs_write', { ...target, content })
+ recordWrite(CONV, target, before, w.path)
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ disk.clear()
+ useCheckpointStore.setState({ byConv: {}, trimmedBefore: {} })
+ useChatStore.setState({ conversations: [{ id: CONV, title: 't', messages: [] } as never] } as never)
+})
+
+describe('rewinding files', () => {
+ it('puts an edited file back and removes a new one', async () => {
+ disk.set('/ws/a.ts', 'old a')
+ const t1 = userSays('m1')
+ await agentWrites('a.ts', 'new a')
+ await agentWrites('a.ts', 'newer a') // second write in the same turn: the first "before" counts
+ await agentWrites('b.ts', 'made up')
+ expect(planSize(rewindPlan(CONV, t1))).toBe(2)
+ const r = await rewindFiles(CONV, t1)
+ expect(disk.get('/ws/a.ts')).toBe('old a')
+ expect(disk.has('/ws/b.ts')).toBe(false)
+ expect(r).toEqual({ restored: 1, removed: 1, failed: [] })
+ expect(rewindSummary(r)).toBe('1 file put back, 1 new file removed.')
+ expect(planSize(rewindPlan(CONV, t1))).toBe(0)
+ })
+
+ it('rewinding to an earlier message undoes every later turn', async () => {
+ disk.set('/ws/a.ts', 'v0')
+ const t1 = userSays('m1')
+ await agentWrites('a.ts', 'v1')
+ const t2 = userSays('m2')
+ await agentWrites('a.ts', 'v2')
+ await agentWrites('c.ts', 'new in turn 2')
+ expect(planSize(rewindPlan(CONV, t2))).toBe(2)
+ await rewindFiles(CONV, t1)
+ expect(disk.get('/ws/a.ts')).toBe('v0')
+ expect(disk.has('/ws/c.ts')).toBe(false)
+ })
+
+ it('rewinding to a later message keeps the earlier turn', async () => {
+ disk.set('/ws/a.ts', 'v0')
+ userSays('m1')
+ await agentWrites('a.ts', 'v1')
+ const t2 = userSays('m2')
+ await agentWrites('a.ts', 'v2')
+ await rewindFiles(CONV, t2)
+ expect(disk.get('/ws/a.ts')).toBe('v1')
+ })
+
+ it('a message with no writes from it on offers nothing', async () => {
+ userSays('m1')
+ await agentWrites('a.ts', 'x')
+ const t2 = userSays('m2')
+ expect(planSize(rewindPlan(CONV, t2))).toBe(0)
+ })
+
+ it('names a file it could not keep instead of pretending', async () => {
+ const t1 = userSays('m1')
+ recordWrite(CONV, { path: '/ws/big.txt', chatId: CONV }, textBefore('x'.repeat(MAX_FILE_CHARS + 1)), '/ws/big.txt')
+ const plan = rewindPlan(CONV, t1)
+ expect(plan.unkept).toEqual([{ path: '/ws/big.txt', why: 'too-big' }])
+ expect(plan.restore).toHaveLength(0)
+ })
+
+ it('keeps nothing for a chat it does not know', async () => {
+ recordWrite('nope', { path: 'a' }, { kind: 'missing' })
+ recordWrite(null, { path: 'a' }, { kind: 'missing' })
+ expect(useCheckpointStore.getState().byConv).toEqual({})
+ })
+})
+
+describe('every write path records', () => {
+ const src = (p: string) => readFileSync(resolve(__dirname, '../../..', p), 'utf8')
+ it('file_write, file_edit and an applied Ask-mode change', () => {
+ const tools = src('api/mcp/builtin-tools.ts')
+ expect(tools.match(/recordWrite\(/g)?.length).toBe(2)
+ expect(src('lib/staged-apply.ts')).toContain('recordWrite(chatId, target, before, res.path)')
+ })
+})
diff --git a/src/lib/agent-core/checkpoints.ts b/src/lib/agent-core/checkpoints.ts
new file mode 100644
index 00000000..96ebfdad
--- /dev/null
+++ b/src/lib/agent-core/checkpoints.ts
@@ -0,0 +1,250 @@
+/**
+ * "Rewind to here" (CA U4).
+ *
+ * Claude Code, Cursor and Codex keep the files an agent touches, per user
+ * turn, so a run that went wrong can be taken back with one click. LU only had
+ * `/undo`, which asks the model to sort it out with git and does nothing
+ * outside a repository.
+ *
+ * How it works: before the FIRST write to a file after a user message, the old
+ * text of that file is kept (or the fact that it did not exist). Rewinding to a
+ * message puts every file written since then back the way it was before that
+ * message: old text written back, files that were new deleted again.
+ *
+ * What it does not cover, said in the menu: changes made by shell commands
+ * (`npm install`, `git checkout`, a script that writes files). Only the file
+ * tools (file_write, file_edit) and applied Ask-mode changes are kept. The
+ * copies live in memory for this app session, capped, and are gone after a
+ * restart.
+ */
+import { create } from 'zustand'
+import { backendCall } from '../../api/backend'
+import type { FsReadResult } from '../../types/bridge'
+
+/** The fs arguments a write went out with; a restore uses the same ones. */
+export interface FsTarget {
+ path: string
+ chatId?: string
+ workingDirectory?: string
+}
+
+export type Before =
+ | { kind: 'text'; content: string }
+ | { kind: 'missing' }
+ | { kind: 'unkept'; why: 'binary' | 'too-big' | 'unreadable' }
+
+interface Entry {
+ target: FsTarget
+ before: Before
+}
+
+export interface Checkpoint {
+ /** The user message whose turn made these writes. */
+ messageId: string
+ /** When the first write of the turn happened. */
+ at: number
+ /** Keyed by the absolute path the backend reported. */
+ files: Record<string, Entry>
+}
+
+/** One file larger than this is not kept (the menu names it). */
+export const MAX_FILE_CHARS = 2_000_000
+/** All kept text together; the oldest checkpoints go first beyond it. */
+export const MAX_TOTAL_CHARS = 64_000_000
+
+interface CheckpointState {
+ byConv: Record<string, Checkpoint[]>
+ /** Per chat: checkpoints from before this time were dropped for space. */
+ trimmedBefore: Record<string, number>
+}
+
+export const useCheckpointStore = create<CheckpointState>(() => ({ byConv: {}, trimmedBefore: {} }))
+
+function sizeOf(before: Before): number {
+ return before.kind === 'text' ? before.content.length : 0
+}
+
+function totalChars(byConv: Record<string, Checkpoint[]>): number {
+ let n = 0
+ for (const list of Object.values(byConv)) for (const cp of list) for (const e of Object.values(cp.files)) n += sizeOf(e.before)
+ return n
+}
+
+type TurnLookup = (convId: string) => { id: string; timestamp: number } | null
+let turnLookup: TurnLookup = () => null
+
+/**
+ * The chat store tells this module which user message the current turn of a
+ * chat belongs to. Registered from there instead of imported here: the file
+ * tools import this module, and the chat store importing the tools' world back
+ * made an import cycle (stores/chatStore.ts calls this at load).
+ */
+export function registerTurnLookup(fn: TurnLookup): void {
+ turnLookup = fn
+}
+
+function currentTurnMessage(convId: string): { id: string; timestamp: number } | null {
+ try { return turnLookup(convId) } catch { return null }
+}
+
+/** Read what a file holds now, before a write replaces it. */
+export async function readBefore(target: FsTarget): Promise<Before> {
+ try {
+ const r = await backendCall<FsReadResult>('fs_read', { ...target })
+ if (r.encoding !== 'utf8' || typeof r.content !== 'string') return { kind: 'unkept', why: 'binary' }
+ if (r.content.length > MAX_FILE_CHARS) return { kind: 'unkept', why: 'too-big' }
+ return { kind: 'text', content: r.content }
+ } catch (e) {
+ return beforeFromError(e)
+ }
+}
+
+/** A read that failed: the file was not there, or it could not be read. */
+export function beforeFromError(e: unknown): Before {
+ const msg = e instanceof Error ? e.message : String(e)
+ return /not found|no such file/i.test(msg) ? { kind: 'missing' } : { kind: 'unkept', why: 'unreadable' }
+}
+
+/** Text the caller already read (file_edit reads before it edits). */
+export function textBefore(content: string): Before {
+ return content.length > MAX_FILE_CHARS ? { kind: 'unkept', why: 'too-big' } : { kind: 'text', content }
+}
+
+/**
+ * Note a write that went through. Only the first write to a file per turn
+ * counts: that is the state the turn started from.
+ */
+export function recordWrite(convId: string | null | undefined, target: FsTarget, before: Before, writtenPath?: string): void {
+ if (!convId) return
+ const turn = currentTurnMessage(convId)
+ if (!turn) return
+ const key = writtenPath || `${target.workingDirectory ?? target.chatId ?? ''}::${target.path}`
+ useCheckpointStore.setState((s) => {
+ const list = [...(s.byConv[convId] ?? [])]
+ let cp = list[list.length - 1]
+ if (!cp || cp.messageId !== turn.id) {
+ cp = { messageId: turn.id, at: Date.now(), files: {} }
+ list.push(cp)
+ } else {
+ cp = { ...cp, files: { ...cp.files } }
+ list[list.length - 1] = cp
+ }
+ if (cp.files[key]) return s
+ cp.files[key] = { target: { ...target, path: writtenPath || target.path }, before }
+ const byConv = { ...s.byConv, [convId]: list }
+ return trim({ byConv, trimmedBefore: s.trimmedBefore })
+ })
+}
+
+/** Drop the oldest checkpoints, across chats, until the kept text fits. */
+function trim(s: CheckpointState): CheckpointState {
+ let total = totalChars(s.byConv)
+ if (total <= MAX_TOTAL_CHARS) return s
+ const byConv: Record<string, Checkpoint[]> = {}
+ for (const [k, v] of Object.entries(s.byConv)) byConv[k] = [...v]
+ const trimmedBefore = { ...s.trimmedBefore }
+ while (total > MAX_TOTAL_CHARS) {
+ let oldest: { conv: string; at: number } | null = null
+ for (const [conv, list] of Object.entries(byConv)) {
+ if (list.length > 1 && (!oldest || list[0].at < oldest.at)) oldest = { conv, at: list[0].at }
+ }
+ if (!oldest) break // only the current turns are left; keep them
+ const cp = byConv[oldest.conv].shift()!
+ for (const e of Object.values(cp.files)) total -= sizeOf(e.before)
+ trimmedBefore[oldest.conv] = Math.max(trimmedBefore[oldest.conv] ?? 0, (byConv[oldest.conv][0]?.at ?? Date.now()))
+ }
+ return { byConv, trimmedBefore }
+}
+
+/** Checkpoints from this user message on: its own turn and every later one. */
+function checkpointsFrom(convId: string, since: number): Checkpoint[] {
+ return (useCheckpointStore.getState().byConv[convId] ?? []).filter((cp) => cp.at >= since)
+}
+
+export interface RewindPlan {
+ /** Files that get their old text back. */
+ restore: Entry[]
+ /** Files that did not exist and are deleted again. */
+ remove: Entry[]
+ /** Files written since then that cannot be put back, with why. */
+ unkept: Array<{ path: string; why: 'binary' | 'too-big' | 'unreadable' }>
+ /** Some writes since then were dropped for space and are not in the plan. */
+ partial: boolean
+}
+
+/**
+ * What rewinding to the message with this timestamp would do. The state of a
+ * file before the turn is the "before" of its FIRST write from then on.
+ */
+export function rewindPlan(convId: string, messageTimestamp: number): RewindPlan {
+ const first = new Map<string, Entry>()
+ for (const cp of checkpointsFrom(convId, messageTimestamp)) {
+ for (const [key, e] of Object.entries(cp.files)) if (!first.has(key)) first.set(key, e)
+ }
+ const plan: RewindPlan = { restore: [], remove: [], unkept: [], partial: false }
+ for (const e of first.values()) {
+ if (e.before.kind === 'text') plan.restore.push(e)
+ else if (e.before.kind === 'missing') plan.remove.push(e)
+ else plan.unkept.push({ path: e.target.path, why: e.before.why })
+ }
+ const trimmed = useCheckpointStore.getState().trimmedBefore[convId]
+ plan.partial = trimmed !== undefined && messageTimestamp < trimmed
+ return plan
+}
+
+export function planSize(plan: RewindPlan): number {
+ return plan.restore.length + plan.remove.length + plan.unkept.length
+}
+
+export interface RewindResult {
+ restored: number
+ removed: number
+ failed: string[]
+}
+
+/** Put the files back. The checkpoints used are dropped afterwards. */
+export async function rewindFiles(convId: string, messageTimestamp: number): Promise<RewindResult> {
+ const plan = rewindPlan(convId, messageTimestamp)
+ const out: RewindResult = { restored: 0, removed: 0, failed: [] }
+ for (const e of plan.restore) {
+ try {
+ await backendCall('fs_write', { ...e.target, content: (e.before as { content: string }).content })
+ out.restored++
+ } catch {
+ out.failed.push(e.target.path)
+ }
+ }
+ for (const e of plan.remove) {
+ try {
+ await backendCall('fs_delete', { ...e.target })
+ out.removed++
+ } catch (err) {
+ // Already gone is the state we want.
+ const msg = err instanceof Error ? err.message : String(err)
+ if (/not found/i.test(msg)) out.removed++
+ else out.failed.push(e.target.path)
+ }
+ }
+ dropCheckpointsFrom(convId, messageTimestamp)
+ return out
+}
+
+/** Forget the checkpoints of this turn and every later one. */
+export function dropCheckpointsFrom(convId: string, messageTimestamp: number): void {
+ useCheckpointStore.setState((s) => {
+ const list = s.byConv[convId]
+ if (!list) return s
+ return { ...s, byConv: { ...s.byConv, [convId]: list.filter((cp) => cp.at < messageTimestamp) } }
+ })
+}
+
+/** One line for the notice after a rewind. */
+export function rewindSummary(r: RewindResult): string {
+ const parts: string[] = []
+ if (r.restored) parts.push(`${r.restored} ${r.restored === 1 ? 'file' : 'files'} put back`)
+ if (r.removed) parts.push(`${r.removed} new ${r.removed === 1 ? 'file' : 'files'} removed`)
+ if (!parts.length && !r.failed.length) return 'Nothing to put back.'
+ const head = parts.length ? parts.join(', ') + '.' : ''
+ const fail = r.failed.length ? ` Could not restore ${r.failed.map((p) => p.split('/').pop()).join(', ')}.` : ''
+ return (head + fail).trim()
+}
diff --git a/src/lib/staged-apply.ts b/src/lib/staged-apply.ts
index c9a34e90..9f210960 100644
--- a/src/lib/staged-apply.ts
+++ b/src/lib/staged-apply.ts
@@ -14,6 +14,7 @@
*/
import { backendCall } from '../api/backend'
+import { beforeFromError, recordWrite, textBefore, type Before } from './agent-core/checkpoints'
import { useStagedChangesStore, type StagedChange } from '../stores/stagedChangesStore'
import { useChatStore } from '../stores/chatStore'
import { resolveChatWorkspaceSlug } from '../api/workspace-slug'
@@ -79,7 +80,7 @@ const withEol = (text: string, eol: '\r\n' | '\n') =>
async function reconcile(
jail: string,
change: StagedChange,
-): Promise<{ content: string; merged: number }> {
+): Promise<{ content: string; merged: number; before: Before }> {
const base = change.oldContent ?? ''
let res: { content?: string; encoding?: string } | undefined
try {
@@ -88,9 +89,9 @@ async function reconcile(
chatId: jail,
workingDirectory: change.workingDirectory,
})
- } catch {
+ } catch (e) {
// gone or unreadable, the write recreates it, which is what the user asked for
- return { content: change.newContent, merged: 0 }
+ return { content: change.newContent, merged: 0, before: beforeFromError(e) }
}
// Not UTF-8 on disk (bug hunt 01.10.2026, C8): read as '' it matched an
// empty base and was overwritten without the drift check ever seeing it.
@@ -100,17 +101,18 @@ async function reconcile(
)
}
const current = res?.content ?? ''
+ const before = textBefore(current)
// The file on disk decides the form; an empty file inherits the model's.
const eol = current ? eolOf(current) : eolOf(change.newContent)
const baseLf = toLf(base)
const currentLf = toLf(current)
const newLf = toLf(change.newContent)
if (currentLf === baseLf || currentLf === newLf) {
- return { content: withEol(change.newContent, eol), merged: 0 }
+ return { content: withEol(change.newContent, eol), merged: 0, before }
}
const merged = mergeThreeWay(baseLf, currentLf, newLf)
if (merged.ok) {
- return { content: withEol(merged.content, eol), merged: merged.mergedRegions }
+ return { content: withEol(merged.content, eol), merged: merged.mergedRegions, before }
}
throw new Error(
`${change.path} changed on disk in the same ${merged.conflicts === 1 ? 'place' : 'places'} this edit touches, so applying it would drop those changes. Everything else was left alone. Reject this one and let the model read the file again.`,
@@ -182,19 +184,17 @@ async function applyStagedChangeInner(chatId: string, staged: StagedChange): Pro
const partial = contentWithDecisions(latest.oldContent ?? '', latest.newContent, latest.hunkDecisions)
const change: StagedChange = { ...latest, newContent: partial.content }
const jail = await jailFor(chatId)
- const { content, merged } = await reconcile(jail, change)
+ const { content, merged, before } = await reconcile(jail, change)
if (!stillPending(chatId, change)) return false
- const res = await backendCall<{ status?: string; path?: string }>('fs_write', {
- path: change.resolvedPath || change.path,
- content,
- chatId: jail,
- workingDirectory: change.workingDirectory,
- })
+ // CA U4: what the file held before this apply (reconcile just read it), for "Rewind to here".
+ const target = { path: change.resolvedPath || change.path, chatId: jail, workingDirectory: change.workingDirectory }
+ const res = await backendCall<{ status?: string; path?: string }>('fs_write', { ...target, content })
// 'saved' and 'unchanged' are both success ('unchanged' = the file already
// matched byte-for-byte). Anything else is a real failure worth retrying.
if (res?.status && res.status !== 'saved' && res.status !== 'unchanged') {
throw new Error(`fs_write returned status "${res.status}"`)
}
+ if (res?.status === 'saved') recordWrite(chatId, target, before, res.path)
for (const fn of appliedListeners) {
try { fn(chatId, change.id) } catch { /* a listener never stops the write */ }
}
diff --git a/src/stores/chatNoticeStore.ts b/src/stores/chatNoticeStore.ts
index 7dcccf21..8b486349 100644
--- a/src/stores/chatNoticeStore.ts
+++ b/src/stores/chatNoticeStore.ts
@@ -34,7 +34,7 @@ import { useChatStore } from './chatStore'
/** Die Zeilen, die es gibt. Kein freier Schluessel: eine Aufzaehlung laesst
* sich nachzaehlen, ein String-Schluessel waechst unbemerkt. */
-export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save' | 'file-mention'
+export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save' | 'file-mention' | 'rewind'
export interface ChatNotice {
id: ChatNoticeId
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 711c7003..4a3b2b9d 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -35,6 +35,7 @@ import { personaPromptOf } from '../lib/chat-persona'
import type { Persona } from '../types/settings'
import { copyConversation, forgetForkKey, forkFrom, forkKeyAt, restoreEmptyFork, switchFork } from '../lib/chat-forks'
import { savedUserEdit } from '../lib/message-edit'
+import { registerTurnLookup } from '../lib/agent-core/checkpoints'
/** GH #169: give each group turn of these models that carries no persona yet
* the persona its model played (model name to persona id). A turn that
@@ -1201,3 +1202,15 @@ function afterHydration(): void {
}
if (useChatStore.persist.hasHydrated()) afterHydration()
else useChatStore.persist.onFinishHydration(afterHydration)
+
+// CA U4: which user message a chat's current turn belongs to, for the file
+// checkpoints of "Rewind to here" (lib/agent-core/checkpoints.ts).
+registerTurnLookup((convId) => {
+ const conv = useChatStore.getState().conversations?.find((c) => c.id === convId)
+ if (!conv) return null
+ for (let i = conv.messages.length - 1; i >= 0; i--) {
+ const m = conv.messages[i]
+ if (m.role === 'user') return { id: m.id, timestamp: m.timestamp }
+ }
+ return null
+})
diff --git a/src/stores/composerFillStore.ts b/src/stores/composerFillStore.ts
new file mode 100644
index 00000000..f07aab5f
--- /dev/null
+++ b/src/stores/composerFillStore.ts
@@ -0,0 +1,17 @@
+import { create } from 'zustand'
+
+/**
+ * Text for the composer to take over once, from outside it (CA U4: after
+ * "Rewind to here" the rewound message goes back into the field, like the
+ * large coding tools do, so it can be changed and sent again). Not persisted:
+ * the composer has its own drafts (lib/chat-drafts.ts).
+ */
+interface ComposerFillState {
+ fill: { text: string; n: number } | null
+ put: (text: string) => void
+}
+
+export const useComposerFillStore = create<ComposerFillState>((set, get) => ({
+ fill: null,
+ put: (text) => set({ fill: { text, n: (get().fill?.n ?? 0) + 1 } }),
+}))