{"slug":"checkpoint-restore","category":"agents","job":"recover","added":"2026-11-08T13:52Z","title":"Checkpoint Restore","description":"An automatic checkpoint before each agent message, with Restore for code, conversation or both — an impact summary of files and messages, what can't be undone, and Redo afterwards.","url":"https://ai-patterns.app/patterns/agents/checkpoint-restore","markdown":"https://ai-patterns.app/patterns/agents/checkpoint-restore.md","json":"https://ai-patterns.app/api/patterns/agents/checkpoint-restore","seenIn":[{"team":"Claude","source":"https://code.claude.com/docs/en/checkpointing"},{"team":"Cursor","source":"https://docs.cursor.com/agent/chat/checkpoints"},{"team":"Replit","source":"https://docs.replit.com/core-concepts/agent/checkpoints-and-rollbacks"},{"team":"lovable","source":"https://docs.lovable.dev/features/projects/history"}],"spec":"# Checkpoint Restore\n\n## Summary\nAn automatic checkpoint before every message to an agent that edits things — code, a project, a document — with a Restore action on each one. Restoring asks what to roll back (the files, the conversation, or both), says exactly which files and messages that touches and what it can't undo, and then leaves a \"Restored to checkpoint\" marker with Redo, so going back is never a one-way trip.\n\n## When to use\n- An agent changes files or project state over many turns, and a turn can go wrong in a way that's tedious to undo by asking.\n- People experiment — \"try it green\", \"now try a sidebar\" — and want to get back to the last good state in one step.\n- Undo history in the editor doesn't cover what the agent did, or the agent touched many files at once.\n\n## When not to use\n- The agent doesn't change anything outside the chat. Editing a message and regenerating (branches) is enough.\n- Changes are already reviewed and applied one by one (accept / reject per diff). Restore adds a second, competing undo.\n- As a replacement for version control. Checkpoints are local to a session; say so, and keep commits as the durable history.\n- When most of a turn's effects can't be reverted (sent emails, payments, migrations). A restore that undoes only part of the work misleads more than it helps — gate those actions before they run instead.\n\n## Anatomy\n- Checkpoint line: a quiet divider before each user message, with a number and time. Its Restore action appears on hover and keyboard focus.\n- Restore confirmation: inline under the line, not a modal. A title (\"Restore to before this message?\"), three choices — Code and conversation, Code only, Conversation only — each with a one-line hint.\n- Impact summary: the counts that change (\"Reverts 3 files and removes 4 messages\"), the file list with how each is affected, and a plain note on what isn't covered.\n- Restored marker: a dashed row where the undone turns were, with the counts and a Redo button.\n- Reverted files: in Code only mode, the later turns stay visible with their file chips struck through and marked \"Reverted\".\n\n## Behavior\n- A checkpoint is taken automatically before each message runs — never ask people to remember to save one.\n- Restore defaults to code and conversation, the common \"start again from here\" case. The summary updates as the choice changes.\n- After a conversation restore, the rewound prompt goes back into the composer so it can be edited and resent.\n- One restore at a time: other Restore actions are disabled while a restore is in effect, until the user redoes it or sends a new message (which discards the undone turns for good).\n- Redo puts back exactly what the last restore removed — files and messages.\n- Say what isn't tracked, every time: commands run in a terminal, database writes, files changed outside the agent. Don't bury it in docs.\n\n## Content guidelines\n- Use \"Restore\" for the action and \"Restored to checkpoint\" for the result. Avoid \"Revert\", \"Rollback\" and \"Undo\" for the same thing in one product.\n- Counts beat adjectives: \"Reverts 3 files\", not \"Reverts your recent changes\".\n- Name files by path, in monospace, so people can check them against their editor.\n- The untracked note is one short sentence of fact: \"Terminal commands and database changes aren't undone.\"\n\n## Accessibility\n- Each Restore button is visible on keyboard focus, not only on hover, and its accessible name includes the message it restores to.\n- The confirmation is a labelled group with a native radio fieldset; focus moves to the first choice when it opens, and Escape cancels back to the Restore button.\n- After restoring, focus moves to the restored marker, which is a `role=\"status\"` region so the outcome is announced.\n- File-change icons carry text equivalents (\"will be deleted\", \"edits undone\"); struck-through chips also say \"Reverted\" in text.\n- Under `prefers-reduced-motion`, the confirmation fades instead of expanding.\n\n## Related patterns\n- **Conversation Branches** — Use it instead when only the reply should change, not files.\n- **Diff Summary Card** — Use it as well to show what a turn changed before deciding to restore.\n- **Plan Review** — Use it before the run, so fewer turns need restoring afterwards.\n- **Tool Approval** — Use it instead for actions a checkpoint can't undo, so they're gated before they run.\n","code":"\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { FilePen, FilePlus, FileX, History, RotateCcw, RotateCw, TriangleAlert } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport interface FileChange {\n  path: string;\n  kind: \"edit\" | \"create\" | \"delete\";\n}\n\nexport interface CheckpointTurn {\n  id: string;\n  /** The user's message. A checkpoint is taken just before it runs. */\n  prompt: string;\n  /** The agent's reply, in one or two sentences. */\n  reply: string;\n  /** Files the agent changed while answering this turn. */\n  changes: FileChange[];\n  /** When the checkpoint was taken, already formatted (\"10:42\"). */\n  time: string;\n}\n\nexport type RestoreMode = \"both\" | \"code\" | \"conversation\";\n\nexport interface RestoredState {\n  /** Index of the turn whose checkpoint was restored; it and every later turn are undone. */\n  index: number;\n  mode: RestoreMode;\n}\n\nexport interface CheckpointTimelineProps {\n  turns: CheckpointTurn[];\n  restored?: RestoredState | null;\n  onRestore: (state: RestoredState) => void;\n  /** Roll forward: put back everything the last restore undid. */\n  onRedo: () => void;\n  /** What a restore can't undo, said plainly. */\n  untrackedNote?: string;\n  className?: string;\n}\n\nconst MODES: { id: RestoreMode; label: string; hint: string }[] = [\n  { id: \"both\", label: \"Code and conversation\", hint: \"Start again from this message\" },\n  { id: \"code\", label: \"Code only\", hint: \"Keep the conversation, undo the file changes\" },\n  { id: \"conversation\", label: \"Conversation only\", hint: \"Keep the files, rewind the chat\" },\n];\n\nconst CHANGE_ICON = { edit: FilePen, create: FilePlus, delete: FileX } as const;\n\nexport function CheckpointTimeline({\n  turns,\n  restored,\n  onRestore,\n  onRedo,\n  untrackedNote = \"Terminal commands and database changes aren't undone.\",\n  className,\n}: CheckpointTimelineProps) {\n  const [confirming, setConfirming] = React.useState<number | null>(null);\n\n  const hidesConversation = restored && restored.mode !== \"code\";\n  const visible = hidesConversation ? turns.slice(0, restored.index) : turns;\n  const undone = restored ? turns.slice(restored.index) : [];\n\n  return (\n    <ol className={cn(\"flex flex-col\", className)} aria-label=\"Conversation with checkpoints\">\n      {visible.map((turn, i) => {\n        const codeReverted = restored?.mode === \"code\" && i >= restored.index;\n        return (\n          <li key={turn.id} className=\"flex flex-col\">\n            {restored?.mode === \"code\" && i === restored.index && (\n              <RestoredBanner turns={undone} mode={restored.mode} onRedo={onRedo} />\n            )}\n            <CheckpointMarker\n              turn={turn}\n              index={i}\n              disabled={Boolean(restored)}\n              open={confirming === i}\n              onOpen={() => setConfirming(confirming === i ? null : i)}\n              onCancel={() => setConfirming(null)}\n              onConfirm={(mode) => {\n                setConfirming(null);\n                onRestore({ index: i, mode });\n              }}\n              later={turns.slice(i)}\n              untrackedNote={untrackedNote}\n            />\n            <TurnBody turn={turn} reverted={codeReverted} />\n          </li>\n        );\n      })}\n      {hidesConversation && (\n        <li>\n          <RestoredBanner turns={undone} mode={restored.mode} onRedo={onRedo} />\n        </li>\n      )}\n    </ol>\n  );\n}\n\nfunction CheckpointMarker({\n  turn,\n  index,\n  disabled,\n  open,\n  onOpen,\n  onCancel,\n  onConfirm,\n  later,\n  untrackedNote,\n}: {\n  turn: CheckpointTurn;\n  index: number;\n  disabled: boolean;\n  open: boolean;\n  onOpen: () => void;\n  onCancel: () => void;\n  onConfirm: (mode: RestoreMode) => void;\n  later: CheckpointTurn[];\n  untrackedNote: string;\n}) {\n  const reduce = useReducedMotion();\n  const [mode, setMode] = React.useState<RestoreMode>(\"both\");\n  const id = React.useId();\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const firstRadioRef = React.useRef<HTMLInputElement>(null);\n\n  React.useEffect(() => {\n    if (open) firstRadioRef.current?.focus();\n  }, [open]);\n\n  const files = uniqueFiles(later);\n  const messages = later.length * 2;\n\n  function cancel() {\n    onCancel();\n    triggerRef.current?.focus();\n  }\n\n  return (\n    <div className=\"group/checkpoint py-1\">\n      <div className=\"flex items-center gap-2 text-[11px] text-muted-foreground\">\n        <span className=\"h-px flex-1 border-t border-dashed\" aria-hidden />\n        <History className=\"size-3\" aria-hidden />\n        <span>\n          Checkpoint {index + 1} · {turn.time}\n        </span>\n        <button\n          ref={triggerRef}\n          type=\"button\"\n          disabled={disabled}\n          aria-expanded={open}\n          aria-controls={open ? `${id}-confirm` : undefined}\n          onClick={onOpen}\n          className={cn(\n            \"flex items-center gap-1 rounded-md px-1.5 py-0.5 font-medium text-foreground transition-opacity hover:bg-accent disabled:hidden\",\n            // Quiet until wanted: shown on hover or keyboard focus, always while open.\n            !open && \"opacity-0 group-hover/checkpoint:opacity-100 focus-visible:opacity-100\"\n          )}\n        >\n          <RotateCcw className=\"size-3\" aria-hidden />\n          Restore\n          <span className=\"sr-only\"> to before “{turn.prompt}”</span>\n        </button>\n        <span className=\"h-px flex-1 border-t border-dashed\" aria-hidden />\n      </div>\n\n      <AnimatePresence initial={false}>\n        {open && (\n          <motion.div\n            id={`${id}-confirm`}\n            role=\"group\"\n            aria-labelledby={`${id}-title`}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}\n            animate={reduce ? { opacity: 1 } : { opacity: 1, height: \"auto\" }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}\n            transition={{ duration: 0.18, ease: \"easeOut\" }}\n            className=\"overflow-hidden\"\n            onKeyDown={(e) => {\n              if (e.key === \"Escape\") {\n                e.preventDefault();\n                cancel();\n              }\n            }}\n          >\n            <div className=\"mt-2 rounded-2xl bg-card p-3 border\">\n              <p id={`${id}-title`} className=\"text-sm font-medium\">\n                Restore to before this message?\n              </p>\n              <fieldset className=\"mt-2 space-y-1\">\n                <legend className=\"sr-only\">What to restore</legend>\n                {MODES.map((m, i) => (\n                  <label\n                    key={m.id}\n                    className={cn(\n                      \"flex cursor-pointer items-start gap-2 rounded-lg px-2 py-1.5 transition-colors hover:bg-accent/60\",\n                      mode === m.id && \"bg-accent/60\"\n                    )}\n                  >\n                    <input\n                      ref={i === 0 ? firstRadioRef : undefined}\n                      type=\"radio\"\n                      name={`${id}-mode`}\n                      value={m.id}\n                      checked={mode === m.id}\n                      onChange={() => setMode(m.id)}\n                      className=\"mt-0.5 accent-foreground\"\n                    />\n                    <span>\n                      <span className=\"block text-sm\">{m.label}</span>\n                      <span className=\"block text-xs text-muted-foreground\">{m.hint}</span>\n                    </span>\n                  </label>\n                ))}\n              </fieldset>\n\n              <div className=\"mt-2 rounded-lg bg-muted/60 px-2.5 py-2 text-xs text-muted-foreground\">\n                <p className=\"font-medium text-foreground\">\n                  {[\n                    mode !== \"conversation\" && `Reverts ${files.length} file${files.length === 1 ? \"\" : \"s\"}`,\n                    mode !== \"code\" && `removes ${messages} message${messages === 1 ? \"\" : \"s\"}`,\n                  ]\n                    .filter(Boolean)\n                    .join(\" and \")\n                    .replace(/^./, (c) => c.toUpperCase())}\n                </p>\n                {mode !== \"conversation\" && files.length > 0 && (\n                  <ul className=\"mt-1 space-y-0.5 font-mono text-[11px]\">\n                    {files.map((f) => {\n                      const Icon = CHANGE_ICON[f.kind];\n                      return (\n                        <li key={f.path} className=\"flex items-center gap-1.5\">\n                          <Icon className=\"size-3 shrink-0\" aria-hidden />\n                          <span className=\"truncate\">{f.path}</span>\n                          <span className=\"sr-only\">({f.kind === \"create\" ? \"will be deleted\" : f.kind === \"delete\" ? \"will come back\" : \"edits undone\"})</span>\n                        </li>\n                      );\n                    })}\n                  </ul>\n                )}\n                {mode !== \"conversation\" && (\n                  <p className=\"mt-1.5 flex items-start gap-1.5\">\n                    <TriangleAlert className=\"mt-px size-3 shrink-0\" aria-hidden />\n                    {untrackedNote}\n                  </p>\n                )}\n              </div>\n\n              <div className=\"mt-3 flex justify-end gap-2\">\n                <button\n                  type=\"button\"\n                  onClick={cancel}\n                  className=\"h-8 rounded-lg px-3 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground\"\n                >\n                  Cancel\n                </button>\n                <button\n                  type=\"button\"\n                  onClick={() => onConfirm(mode)}\n                  className=\"h-8 rounded-lg bg-foreground px-3 text-xs font-medium text-background\"\n                >\n                  Restore\n                </button>\n              </div>\n            </div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction TurnBody({ turn, reverted }: { turn: CheckpointTurn; reverted?: boolean }) {\n  return (\n    <div className=\"space-y-2 pb-3\">\n      <p className=\"ml-auto w-fit max-w-[85%] rounded-2xl bg-muted px-3 py-2 text-sm\">{turn.prompt}</p>\n      <p className=\"text-sm text-muted-foreground\">{turn.reply}</p>\n      {turn.changes.length > 0 && (\n        <ul className={cn(\"flex flex-wrap gap-1.5\", reverted && \"opacity-50\")}>\n          {turn.changes.map((c) => {\n            const Icon = CHANGE_ICON[c.kind];\n            return (\n              <li\n                key={c.path}\n                className={cn(\n                  \"flex items-center gap-1 rounded-lg px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground bg-muted\",\n                  reverted && \"line-through\"\n                )}\n              >\n                <Icon className=\"size-3\" aria-hidden />\n                {c.path}\n              </li>\n            );\n          })}\n          {reverted && <li className=\"self-center text-[11px] font-medium text-muted-foreground\">Reverted</li>}\n        </ul>\n      )}\n    </div>\n  );\n}\n\nfunction RestoredBanner({\n  turns,\n  mode,\n  onRedo,\n}: {\n  turns: CheckpointTurn[];\n  mode: RestoreMode;\n  onRedo: () => void;\n}) {\n  const reduce = useReducedMotion();\n  const ref = React.useRef<HTMLDivElement>(null);\n  const files = uniqueFiles(turns).length;\n  const messages = turns.length * 2;\n\n  // The button that was pressed is gone; put focus on the result instead.\n  React.useEffect(() => {\n    ref.current?.focus();\n  }, []);\n\n  const parts = [\n    mode !== \"conversation\" && `${files} file${files === 1 ? \"\" : \"s\"} reverted`,\n    mode !== \"code\" && `${messages} message${messages === 1 ? \"\" : \"s\"} removed`,\n  ].filter(Boolean);\n\n  return (\n    <motion.div\n      ref={ref}\n      tabIndex={-1}\n      role=\"status\"\n      initial={reduce ? { opacity: 0 } : { opacity: 0, y: 4 }}\n      animate={{ opacity: 1, y: 0 }}\n      className=\"my-2 flex items-center gap-3 rounded-xl border border-dashed px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-ring/50\"\n    >\n      <RotateCcw className=\"size-4 shrink-0 text-muted-foreground\" aria-hidden />\n      <div className=\"min-w-0 flex-1\">\n        <p className=\"text-sm font-medium\">Restored to checkpoint</p>\n        <p className=\"text-xs text-muted-foreground\">{parts.join(\" · \")}</p>\n      </div>\n      <button\n        type=\"button\"\n        onClick={onRedo}\n        className=\"flex h-7 shrink-0 items-center gap-1 rounded-full px-2 text-xs font-medium hover:bg-foreground/10 bg-muted\"\n      >\n        <RotateCw className=\"size-3\" aria-hidden />\n        Redo\n      </button>\n    </motion.div>\n  );\n}\n\nfunction uniqueFiles(turns: CheckpointTurn[]): FileChange[] {\n  const map = new Map<string, FileChange>();\n  for (const t of turns) for (const c of t.changes) if (!map.has(c.path)) map.set(c.path, c);\n  return [...map.values()];\n}\n","dependencies":["lucide-react","motion"],"localImports":["@/lib/utils"]}