A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: let users delete old chat history (#11249)
Shahmir Varqha33bdee1d84fd
diff --git a/frontend/src/components/chat/__tests__/chat-history-popover.test.tsx b/frontend/src/components/chat/__tests__/chat-history-popover.test.tsxnew file mode 100644index 0000000000..b58e0ab22c--- /dev/null+++ b/frontend/src/components/chat/__tests__/chat-history-popover.test.tsx@@ -0,0 +1,157 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { act, fireEvent, render, screen } from "@testing-library/react";+import { createStore, Provider } from "jotai";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ModalProvider } from "@/components/modal/ImperativeModal";+import { TooltipProvider } from "@/components/ui/tooltip";+import { type Chat, type ChatId, chatStateAtom } from "@/core/ai/state";+import { ChatHistoryPopover } from "../chat-history-popover";++const activeId = "active" as ChatId;+const olderId = "older" as ChatId;++function chat(id: ChatId): Chat {+ return {+ id,+ title: `${id} conversation`,+ messages: [+ {+ id: `${id}-message`,+ role: "user",+ parts: [{ type: "text", text: "Hello" }],+ },+ ],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ };+}++function setup(isLoading = false) {+ const store = createStore();+ const setActiveChat = vi.fn();+ const onDeleteChats = vi.fn();++ render(+ <Provider store={store}>+ <ModalProvider>+ <TooltipProvider>+ <ChatHistoryPopover+ activeChatId={activeId}+ setActiveChat={setActiveChat}+ onDeleteChats={onDeleteChats}+ isLoading={isLoading}+ />+ </TooltipProvider>+ </ModalProvider>+ </Provider>,+ );+ act(() =>+ store.set(chatStateAtom, {+ chats: new Map([+ [activeId, chat(activeId)],+ [olderId, chat(olderId)],+ ]),+ activeChatId: activeId,+ }),+ );++ fireEvent.click(screen.getByRole("button", { name: "Previous chats" }));+ return { store, setActiveChat, onDeleteChats };+}++describe("chat history management", () => {+ beforeEach(() => window.localStorage.clear());+ afterEach(() => vi.restoreAllMocks());++ it("deletes individual chats immediately without selecting them or closing history", () => {+ const { setActiveChat, onDeleteChats } = setup();+ fireEvent.click(+ screen.getByRole("button", { name: "Delete chat: older conversation" }),+ );+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();+ expect(screen.getByPlaceholderText("Search chat history...")).toBeVisible();+ expect(onDeleteChats).toHaveBeenCalledExactlyOnceWith(olderId);+ expect(setActiveChat).not.toHaveBeenCalled();+ });++ it("deletes all chats only after confirmation", () => {+ const { onDeleteChats } = setup();+ fireEvent.change(screen.getByPlaceholderText("Search chat history..."), {+ target: { value: "older" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Delete all chats" }));+ expect(screen.getByRole("alertdialog")).toHaveTextContent("all notebooks");+ expect(onDeleteChats).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Delete all chats" }));+ expect(onDeleteChats).toHaveBeenCalledExactlyOnceWith(null);+ });++ it("keeps focus in history after deleting the focused chat", () => {+ const { store, onDeleteChats } = setup();+ onDeleteChats.mockImplementation(() => {+ store.set(chatStateAtom, (prev) => {+ const chats = new Map(prev.chats);+ chats.delete(olderId);+ return { ...prev, chats };+ });+ });+ const searchInput = screen.getByPlaceholderText("Search chat history...");+ fireEvent.change(searchInput, { target: { value: "older" } });+ const deleteButton = screen.getByRole("button", {+ name: "Delete chat: older conversation",+ });+ act(() => deleteButton.focus());+ expect(deleteButton).toHaveFocus();++ fireEvent.click(deleteButton);++ expect(deleteButton).not.toBeInTheDocument();+ expect(searchInput).toHaveFocus();+ expect(screen.getByText("No chats found")).toBeVisible();+ });++ it("prevents deleting a streaming chat while allowing cleanup of other chats", () => {+ setup(true);+ expect(+ screen.getByRole("button", { name: "Delete chat: active conversation" }),+ ).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Delete all chats" }),+ ).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Delete chat: older conversation" }),+ ).toBeEnabled();+ });++ it("warns above 50 chats and clears the warning after cleanup", () => {+ const { store } = setup();+ const chats = new Map<ChatId, Chat>(+ Array.from({ length: 51 }, (_, index) => {+ const id = `chat-${index}` as ChatId;+ return [id, chat(id)];+ }),+ );+ act(() => store.set(chatStateAtom, { chats, activeChatId: null }));+ const warning = screen.getByText(+ /Delete old chats to free up browser storage/,+ );+ expect(warning).toBeVisible();+ expect(warning).toHaveTextContent(+ "You have over 50 chats. Delete old chats to free up browser storage.",+ );++ act(() =>+ store.set(chatStateAtom, (prev) => ({+ ...prev,+ chats: new Map([...prev.chats].slice(1)),+ })),+ );+ expect(+ screen.queryByText(/Delete old chats to free up browser storage/),+ ).not.toBeInTheDocument();+ expect(+ screen.getByText("Chats are shared across notebooks."),+ ).toBeVisible();+ });+});diff --git a/frontend/src/components/chat/chat-history-popover.tsx b/frontend/src/components/chat/chat-history-popover.tsxindex 71ae53f7b8..f7611a7db4 100644--- a/frontend/src/components/chat/chat-history-popover.tsx+++ b/frontend/src/components/chat/chat-history-popover.tsx@@ -1,9 +1,16 @@/* Copyright 2026 Marimo. All rights reserved. */import { useAtomValue } from "jotai";-import { BotMessageSquareIcon, ClockIcon, SearchIcon } from "lucide-react";-import { useMemo, useState } from "react";+import {+ BotMessageSquareIcon,+ ClockIcon,+ SearchIcon,+ Trash2Icon,+} from "lucide-react";+import { useMemo, useRef, useState } from "react";import { useLocale } from "react-aria";+import { useImperativeModal } from "@/components/modal/ImperativeModal";+import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import {@@ -19,18 +26,48 @@ import { timeAgo } from "@/utils/dates";import { PanelEmptyState } from "../editor/chrome/panels/empty-state";import { groupChatsByDate } from "./chat-history-utils";+const CHAT_HISTORY_WARNING_THRESHOLD = 50;+interface ChatHistoryPopoverProps {activeChatId: ChatId | undefined;setActiveChat: (id: ChatId | null) => void;+ onDeleteChats: (id: ChatId | null) => void;+ isLoading: boolean;}export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({activeChatId,setActiveChat,+ onDeleteChats,+ isLoading,}) => {const chatState = useAtomValue(chatStateAtom);const { locale } = useLocale();const [searchQuery, setSearchQuery] = useState("");+ const searchInputRef = useRef<HTMLInputElement>(null);+ const [open, setOpen] = useState(false);+ const { openConfirm, closeModal } = useImperativeModal();++ const confirmDeleteAllChats = () => {+ // Close the popover before opening a modal so focus moves to the dialog.+ setOpen(false);+ openConfirm({+ title: "Delete all chats?",+ description:+ "This will permanently delete all chat history for all notebooks on this site in this browser. This cannot be undone.",+ variant: "destructive",+ confirmAction: (+ <AlertDialogDestructiveAction+ onClick={() => {+ onDeleteChats(null);+ closeModal();+ }}+ >+ Delete all chats+ </AlertDialogDestructiveAction>+ ),+ });+ };const chats = useMemo(() => {return [...chatState.chats.values()].toSorted(@@ -52,10 +89,10 @@ export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({}, [filteredChats]);return (- <Popover>+ <Popover open={open} onOpenChange={setOpen}><Tooltip content="Previous chats"><PopoverTrigger asChild={true}>- <Button variant="text" size="icon">+ <Button variant="text" size="icon" aria-label="Previous chats"><ClockIcon className="h-4 w-4" /></Button></PopoverTrigger>@@ -63,6 +100,7 @@ export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({<PopoverContent className="w-[480px] p-0" align="start" side="right"><div className="pt-3 px-3 w-full"><Input+ ref={searchInputRef}placeholder="Search chat history..."value={searchQuery}onChange={(e) => setSearchQuery(e.target.value)}@@ -92,25 +130,46 @@ export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({</div><div>{group.chats.map((chat) => (- <button+ <divkey={chat.id}className={cn(- "w-full p-1 rounded-md cursor-pointer text-left flex items-center justify-between",+ "w-full rounded-md flex items-center justify-between",chat.id === activeChatId && "bg-accent",chat.id !== activeChatId && "hover:bg-muted/20",)}- onClick={() => {- setActiveChat(chat.id);- }}- type="button">- <div className="flex-1 min-w-0">- <div className="text-sm truncate">{chat.title}</div>- </div>- <div className="text-xs text-muted-foreground/60 ml-2 shrink-0">- {timeAgo(chat.updatedAt, locale)}- </div>- </button>+ <button+ className="flex flex-1 min-w-0 items-center justify-between p-1 text-left cursor-pointer"+ onClick={() => setActiveChat(chat.id)}+ type="button"+ >+ <span className="text-sm truncate">{chat.title}</span>+ <span className="text-xs text-muted-foreground/60 ml-2 shrink-0">+ {timeAgo(chat.updatedAt, locale)}+ </span>+ </button>+ <Tooltip+ content={+ isLoading && chat.id === activeChatId+ ? "Stop the response before deleting this chat"+ : "Delete chat"+ }+ >+ <Button+ variant="text"+ size="icon"+ className="text-muted-foreground/90 hover:text-destructive transition-colors ml-px"+ aria-label={`Delete chat: ${chat.title}`}+ disabled={isLoading && chat.id === activeChatId}+ onClick={() => {+ searchInputRef.current?.focus();+ onDeleteChats(chat.id);+ }}+ >+ <Trash2Icon className="h-3.5 w-3.5" />+ </Button>+ </Tooltip>+ </div>))}</div>{/* If last group, don't show a divider */}@@ -119,6 +178,28 @@ export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({))}</div></ScrollArea>+ {chats.length > 0 && (+ <div className="border-t p-2 flex items-center justify-between gap-2">+ {chats.length > CHAT_HISTORY_WARNING_THRESHOLD ? (+ <p className="text-xs text-muted-foreground">+ You have over <b>{CHAT_HISTORY_WARNING_THRESHOLD}</b> chats.+ Delete old chats to free up browser storage.+ </p>+ ) : (+ <p className="text-xs text-muted-foreground">+ Chats are shared across notebooks.+ </p>+ )}+ <Button+ variant="linkDestructive"+ size="xs"+ disabled={isLoading}+ onClick={confirmDeleteAllChats}+ >+ Delete all chats+ </Button>+ </div>+ )}</PopoverContent></Popover>);diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsxindex 41c96b73d0..efbd1ac3d6 100644--- a/frontend/src/components/chat/chat-panel.tsx+++ b/frontend/src/components/chat/chat-panel.tsx@@ -150,12 +150,16 @@ interface ChatHeaderProps {onNewChat: () => void;activeChatId: ChatId | undefined;setActiveChat: (id: ChatId | null) => void;+ onDeleteChats: (id: ChatId | null) => void;+ isLoading: boolean;}const ChatHeader: React.FC<ChatHeaderProps> = ({onNewChat,activeChatId,setActiveChat,+ onDeleteChats,+ isLoading,}) => {const { handleClick } = useOpenSettingsToTab();@@ -184,6 +188,8 @@ const ChatHeader: React.FC<ChatHeaderProps> = ({<ChatHistoryPopoveractiveChatId={activeChatId}setActiveChat={setActiveChat}+ onDeleteChats={onDeleteChats}+ isLoading={isLoading}/></div></div>@@ -838,6 +844,27 @@ const ChatPanelBody = () => {clearFiles();});+ const handleDeleteChats = useEvent((id: ChatId | null) => {+ if (id === null || id === activeChatId) {+ handleNewChat();+ }+ setChatState((prev) => {+ const chats = new Map(prev.chats);+ if (id === null) {+ chats.clear();+ } else {+ chats.delete(id);+ }+ return {+ chats,+ activeChatId:+ prev.activeChatId && chats.has(prev.activeChatId)+ ? prev.activeChatId+ : null,+ };+ });+ });+const handlePairWithAgent = useEvent(() => {openModal(<PairWithAgentModal onClose={closeModal} />);});@@ -997,6 +1024,8 @@ const ChatPanelBody = () => {onNewChat={handleNewChat}activeChatId={activeChat?.id}setActiveChat={setActiveChat}+ onDeleteChats={handleDeleteChats}+ isLoading={isLoading}/></TooltipProvider>diff --git a/frontend/src/core/ai/__tests__/state.test.ts b/frontend/src/core/ai/__tests__/state.test.tsnew file mode 100644index 0000000000..c9a20c86ec--- /dev/null+++ b/frontend/src/core/ai/__tests__/state.test.ts@@ -0,0 +1,120 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { createStore } from "jotai";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { toast } from "@/components/ui/use-toast";+import { type Chat, type ChatId, chatStateAtom } from "../state";++vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));++const KEY = "marimo:ai:chatState:v5";+const chatId = "saved-chat" as ChatId;+const chat: Chat = {+ id: chatId,+ title: "Saved conversation",+ messages: [+ { id: "message", role: "user", parts: [{ type: "text", text: "Hello" }] },+ ],+ createdAt: 1,+ updatedAt: 1,+};++const unsubscribers: (() => void)[] = [];++function loadStore() {+ const store = createStore();+ unsubscribers.push(store.sub(chatStateAtom, vi.fn()));+ return store;+}++function fillStorage() {+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {+ throw new DOMException("Storage is full", "QuotaExceededError");+ });+}++describe("chat history storage", () => {+ beforeEach(() => {+ window.localStorage.clear();+ window.localStorage.setItem(+ KEY,+ JSON.stringify({+ chats: [[chatId, chat]],+ activeChatId: chatId,+ }),+ );+ });++ afterEach(() => {+ for (const unsubscribe of unsubscribers.splice(0)) {+ unsubscribe();+ }+ vi.restoreAllMocks();+ });++ it("loads saved history when storage is full", () => {+ fillStorage();+ expect(loadStore().get(chatStateAtom)).toEqual({+ chats: new Map([[chatId, chat]]),+ activeChatId: chatId,+ });+ });++ it("warns on save failure without interrupting in-memory updates", () => {+ const store = loadStore();+ const savedHistory = window.localStorage.getItem(KEY);+ fillStorage();+ const updatedChat = { ...chat, title: "Unsaved conversation" };+ expect(() =>+ store.set(chatStateAtom, {+ chats: new Map([[chatId, updatedChat]]),+ activeChatId: chatId,+ }),+ ).not.toThrow();++ expect(store.get(chatStateAtom).chats.get(chatId)).toEqual(updatedChat);+ expect(window.localStorage.getItem(KEY)).toBe(savedHistory);+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ id: "chat-storage-error",+ once: true,+ title: "Chat history couldn't be saved",+ }),+ );+ });++ it("frees storage when history is cleared even if further writes fail", () => {+ window.localStorage.setItem("unrelated-setting", "keep");+ const store = loadStore();+ fillStorage();+ store.set(chatStateAtom, { chats: new Map(), activeChatId: null });++ expect(window.localStorage.getItem(KEY)).toBeNull();+ expect(window.localStorage.getItem("unrelated-setting")).toBe("keep");+ expect(loadStore().get(chatStateAtom)).toEqual({+ chats: new Map(),+ activeChatId: null,+ });+ expect(toast).not.toHaveBeenCalled();+ });++ it("removes saved history when only an empty chat remains and writes fail", () => {+ const store = loadStore();+ const emptyChat = { ...chat, messages: [] };+ const state = {+ chats: new Map([[chatId, emptyChat]]),+ activeChatId: chatId,+ };+ fillStorage();++ store.set(chatStateAtom, state);++ expect(window.localStorage.getItem(KEY)).toBeNull();+ expect(store.get(chatStateAtom)).toEqual(state);+ expect(loadStore().get(chatStateAtom)).toEqual({+ chats: new Map(),+ activeChatId: null,+ });+ expect(toast).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.tsindex bd29897fb2..d028f45e38 100644--- a/frontend/src/core/ai/state.ts+++ b/frontend/src/core/ai/state.ts@@ -4,7 +4,9 @@ import type { UIMessage } from "@ai-sdk/react";import type { FileUIPart } from "ai";import { atom } from "jotai";import { atomWithStorage } from "jotai/utils";+import { toast } from "@/components/ui/use-toast";import { uniqueBy } from "@/utils/arrays";+import { Logger } from "@/utils/Logger";import { adaptForLocalStorage, jotaiJsonStorage } from "@/utils/storage/jotai";import type { TypedString } from "@/utils/typed";import type { CellId } from "../cells/ids";@@ -85,22 +87,46 @@ function removeEmptyChats(chatState: Map<ChatId, Chat>): Map<ChatId, Chat> {return result;}+const chatStorage = adaptForLocalStorage({+ toSerializable: (value: ChatState) => ({+ chats: [...removeEmptyChats(value.chats).entries()],+ activeChatId: value.activeChatId,+ }),+ fromSerializable: (value) => ({+ chats: new Map(value.chats),+ activeChatId: value.activeChatId,+ }),+});+export const chatStateAtom = atomWithStorage<ChatState>(KEY,{chats: new Map(),activeChatId: null,},- adaptForLocalStorage({- toSerializable: (value: ChatState) => ({- chats: [...removeEmptyChats(value.chats).entries()],- activeChatId: value.activeChatId,- }),- fromSerializable: (value) => ({- chats: new Map(value.chats),- activeChatId: value.activeChatId,- }),- }),+ {+ ...chatStorage,+ setItem: (key, value) => {+ try {+ // Removing the key frees space even when no further writes can fit.+ if (removeEmptyChats(value.chats).size === 0) {+ chatStorage.removeItem(key);+ } else {+ chatStorage.setItem(key, value);+ }+ } catch (error) {+ Logger.warn("Could not save chat history", error);+ toast({+ id: "chat-storage-error",+ once: true,+ title: "Chat history couldn't be saved",+ description:+ "Try deleting old chats. New messages may be lost when you reload.",+ variant: "danger",+ });+ }+ },+ },);export const activeChatAtom = atom(