@marimo-team/islands 0.25.2-dev93 → 0.25.2-dev97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marimo-team/islands",
3
- "version": "0.25.2-dev93",
3
+ "version": "0.25.2-dev97",
4
4
  "main": "dist/main.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
@@ -0,0 +1,157 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { act, fireEvent, render, screen } from "@testing-library/react";
4
+ import { createStore, Provider } from "jotai";
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
+ import { ModalProvider } from "@/components/modal/ImperativeModal";
7
+ import { TooltipProvider } from "@/components/ui/tooltip";
8
+ import { type Chat, type ChatId, chatStateAtom } from "@/core/ai/state";
9
+ import { ChatHistoryPopover } from "../chat-history-popover";
10
+
11
+ const activeId = "active" as ChatId;
12
+ const olderId = "older" as ChatId;
13
+
14
+ function chat(id: ChatId): Chat {
15
+ return {
16
+ id,
17
+ title: `${id} conversation`,
18
+ messages: [
19
+ {
20
+ id: `${id}-message`,
21
+ role: "user",
22
+ parts: [{ type: "text", text: "Hello" }],
23
+ },
24
+ ],
25
+ createdAt: Date.now(),
26
+ updatedAt: Date.now(),
27
+ };
28
+ }
29
+
30
+ function setup(isLoading = false) {
31
+ const store = createStore();
32
+ const setActiveChat = vi.fn();
33
+ const onDeleteChats = vi.fn();
34
+
35
+ render(
36
+ <Provider store={store}>
37
+ <ModalProvider>
38
+ <TooltipProvider>
39
+ <ChatHistoryPopover
40
+ activeChatId={activeId}
41
+ setActiveChat={setActiveChat}
42
+ onDeleteChats={onDeleteChats}
43
+ isLoading={isLoading}
44
+ />
45
+ </TooltipProvider>
46
+ </ModalProvider>
47
+ </Provider>,
48
+ );
49
+ act(() =>
50
+ store.set(chatStateAtom, {
51
+ chats: new Map([
52
+ [activeId, chat(activeId)],
53
+ [olderId, chat(olderId)],
54
+ ]),
55
+ activeChatId: activeId,
56
+ }),
57
+ );
58
+
59
+ fireEvent.click(screen.getByRole("button", { name: "Previous chats" }));
60
+ return { store, setActiveChat, onDeleteChats };
61
+ }
62
+
63
+ describe("chat history management", () => {
64
+ beforeEach(() => window.localStorage.clear());
65
+ afterEach(() => vi.restoreAllMocks());
66
+
67
+ it("deletes individual chats immediately without selecting them or closing history", () => {
68
+ const { setActiveChat, onDeleteChats } = setup();
69
+ fireEvent.click(
70
+ screen.getByRole("button", { name: "Delete chat: older conversation" }),
71
+ );
72
+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
73
+ expect(screen.getByPlaceholderText("Search chat history...")).toBeVisible();
74
+ expect(onDeleteChats).toHaveBeenCalledExactlyOnceWith(olderId);
75
+ expect(setActiveChat).not.toHaveBeenCalled();
76
+ });
77
+
78
+ it("deletes all chats only after confirmation", () => {
79
+ const { onDeleteChats } = setup();
80
+ fireEvent.change(screen.getByPlaceholderText("Search chat history..."), {
81
+ target: { value: "older" },
82
+ });
83
+ fireEvent.click(screen.getByRole("button", { name: "Delete all chats" }));
84
+ expect(screen.getByRole("alertdialog")).toHaveTextContent("all notebooks");
85
+ expect(onDeleteChats).not.toHaveBeenCalled();
86
+ fireEvent.click(screen.getByRole("button", { name: "Delete all chats" }));
87
+ expect(onDeleteChats).toHaveBeenCalledExactlyOnceWith(null);
88
+ });
89
+
90
+ it("keeps focus in history after deleting the focused chat", () => {
91
+ const { store, onDeleteChats } = setup();
92
+ onDeleteChats.mockImplementation(() => {
93
+ store.set(chatStateAtom, (prev) => {
94
+ const chats = new Map(prev.chats);
95
+ chats.delete(olderId);
96
+ return { ...prev, chats };
97
+ });
98
+ });
99
+ const searchInput = screen.getByPlaceholderText("Search chat history...");
100
+ fireEvent.change(searchInput, { target: { value: "older" } });
101
+ const deleteButton = screen.getByRole("button", {
102
+ name: "Delete chat: older conversation",
103
+ });
104
+ act(() => deleteButton.focus());
105
+ expect(deleteButton).toHaveFocus();
106
+
107
+ fireEvent.click(deleteButton);
108
+
109
+ expect(deleteButton).not.toBeInTheDocument();
110
+ expect(searchInput).toHaveFocus();
111
+ expect(screen.getByText("No chats found")).toBeVisible();
112
+ });
113
+
114
+ it("prevents deleting a streaming chat while allowing cleanup of other chats", () => {
115
+ setup(true);
116
+ expect(
117
+ screen.getByRole("button", { name: "Delete chat: active conversation" }),
118
+ ).toBeDisabled();
119
+ expect(
120
+ screen.getByRole("button", { name: "Delete all chats" }),
121
+ ).toBeDisabled();
122
+ expect(
123
+ screen.getByRole("button", { name: "Delete chat: older conversation" }),
124
+ ).toBeEnabled();
125
+ });
126
+
127
+ it("warns above 50 chats and clears the warning after cleanup", () => {
128
+ const { store } = setup();
129
+ const chats = new Map<ChatId, Chat>(
130
+ Array.from({ length: 51 }, (_, index) => {
131
+ const id = `chat-${index}` as ChatId;
132
+ return [id, chat(id)];
133
+ }),
134
+ );
135
+ act(() => store.set(chatStateAtom, { chats, activeChatId: null }));
136
+ const warning = screen.getByText(
137
+ /Delete old chats to free up browser storage/,
138
+ );
139
+ expect(warning).toBeVisible();
140
+ expect(warning).toHaveTextContent(
141
+ "You have over 50 chats. Delete old chats to free up browser storage.",
142
+ );
143
+
144
+ act(() =>
145
+ store.set(chatStateAtom, (prev) => ({
146
+ ...prev,
147
+ chats: new Map([...prev.chats].slice(1)),
148
+ })),
149
+ );
150
+ expect(
151
+ screen.queryByText(/Delete old chats to free up browser storage/),
152
+ ).not.toBeInTheDocument();
153
+ expect(
154
+ screen.getByText("Chats are shared across notebooks."),
155
+ ).toBeVisible();
156
+ });
157
+ });
@@ -1,9 +1,16 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
3
  import { useAtomValue } from "jotai";
4
- import { BotMessageSquareIcon, ClockIcon, SearchIcon } from "lucide-react";
5
- import { useMemo, useState } from "react";
4
+ import {
5
+ BotMessageSquareIcon,
6
+ ClockIcon,
7
+ SearchIcon,
8
+ Trash2Icon,
9
+ } from "lucide-react";
10
+ import { useMemo, useRef, useState } from "react";
6
11
  import { useLocale } from "react-aria";
12
+ import { useImperativeModal } from "@/components/modal/ImperativeModal";
13
+ import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";
7
14
  import { Button } from "@/components/ui/button";
8
15
  import { Input } from "@/components/ui/input";
9
16
  import {
@@ -19,18 +26,48 @@ import { timeAgo } from "@/utils/dates";
19
26
  import { PanelEmptyState } from "../editor/chrome/panels/empty-state";
20
27
  import { groupChatsByDate } from "./chat-history-utils";
21
28
 
29
+ const CHAT_HISTORY_WARNING_THRESHOLD = 50;
30
+
22
31
  interface ChatHistoryPopoverProps {
23
32
  activeChatId: ChatId | undefined;
24
33
  setActiveChat: (id: ChatId | null) => void;
34
+ onDeleteChats: (id: ChatId | null) => void;
35
+ isLoading: boolean;
25
36
  }
26
37
 
27
38
  export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({
28
39
  activeChatId,
29
40
  setActiveChat,
41
+ onDeleteChats,
42
+ isLoading,
30
43
  }) => {
31
44
  const chatState = useAtomValue(chatStateAtom);
32
45
  const { locale } = useLocale();
33
46
  const [searchQuery, setSearchQuery] = useState("");
47
+ const searchInputRef = useRef<HTMLInputElement>(null);
48
+ const [open, setOpen] = useState(false);
49
+ const { openConfirm, closeModal } = useImperativeModal();
50
+
51
+ const confirmDeleteAllChats = () => {
52
+ // Close the popover before opening a modal so focus moves to the dialog.
53
+ setOpen(false);
54
+ openConfirm({
55
+ title: "Delete all chats?",
56
+ description:
57
+ "This will permanently delete all chat history for all notebooks on this site in this browser. This cannot be undone.",
58
+ variant: "destructive",
59
+ confirmAction: (
60
+ <AlertDialogDestructiveAction
61
+ onClick={() => {
62
+ onDeleteChats(null);
63
+ closeModal();
64
+ }}
65
+ >
66
+ Delete all chats
67
+ </AlertDialogDestructiveAction>
68
+ ),
69
+ });
70
+ };
34
71
 
35
72
  const chats = useMemo(() => {
36
73
  return [...chatState.chats.values()].toSorted(
@@ -52,10 +89,10 @@ export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({
52
89
  }, [filteredChats]);
53
90
 
54
91
  return (
55
- <Popover>
92
+ <Popover open={open} onOpenChange={setOpen}>
56
93
  <Tooltip content="Previous chats">
57
94
  <PopoverTrigger asChild={true}>
58
- <Button variant="text" size="icon">
95
+ <Button variant="text" size="icon" aria-label="Previous chats">
59
96
  <ClockIcon className="h-4 w-4" />
60
97
  </Button>
61
98
  </PopoverTrigger>
@@ -63,6 +100,7 @@ export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({
63
100
  <PopoverContent className="w-[480px] p-0" align="start" side="right">
64
101
  <div className="pt-3 px-3 w-full">
65
102
  <Input
103
+ ref={searchInputRef}
66
104
  placeholder="Search chat history..."
67
105
  value={searchQuery}
68
106
  onChange={(e) => setSearchQuery(e.target.value)}
@@ -92,25 +130,46 @@ export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({
92
130
  </div>
93
131
  <div>
94
132
  {group.chats.map((chat) => (
95
- <button
133
+ <div
96
134
  key={chat.id}
97
135
  className={cn(
98
- "w-full p-1 rounded-md cursor-pointer text-left flex items-center justify-between",
136
+ "w-full rounded-md flex items-center justify-between",
99
137
  chat.id === activeChatId && "bg-accent",
100
138
  chat.id !== activeChatId && "hover:bg-muted/20",
101
139
  )}
102
- onClick={() => {
103
- setActiveChat(chat.id);
104
- }}
105
- type="button"
106
140
  >
107
- <div className="flex-1 min-w-0">
108
- <div className="text-sm truncate">{chat.title}</div>
109
- </div>
110
- <div className="text-xs text-muted-foreground/60 ml-2 shrink-0">
111
- {timeAgo(chat.updatedAt, locale)}
112
- </div>
113
- </button>
141
+ <button
142
+ className="flex flex-1 min-w-0 items-center justify-between p-1 text-left cursor-pointer"
143
+ onClick={() => setActiveChat(chat.id)}
144
+ type="button"
145
+ >
146
+ <span className="text-sm truncate">{chat.title}</span>
147
+ <span className="text-xs text-muted-foreground/60 ml-2 shrink-0">
148
+ {timeAgo(chat.updatedAt, locale)}
149
+ </span>
150
+ </button>
151
+ <Tooltip
152
+ content={
153
+ isLoading && chat.id === activeChatId
154
+ ? "Stop the response before deleting this chat"
155
+ : "Delete chat"
156
+ }
157
+ >
158
+ <Button
159
+ variant="text"
160
+ size="icon"
161
+ className="text-muted-foreground/90 hover:text-destructive transition-colors ml-px"
162
+ aria-label={`Delete chat: ${chat.title}`}
163
+ disabled={isLoading && chat.id === activeChatId}
164
+ onClick={() => {
165
+ searchInputRef.current?.focus();
166
+ onDeleteChats(chat.id);
167
+ }}
168
+ >
169
+ <Trash2Icon className="h-3.5 w-3.5" />
170
+ </Button>
171
+ </Tooltip>
172
+ </div>
114
173
  ))}
115
174
  </div>
116
175
  {/* If last group, don't show a divider */}
@@ -119,6 +178,28 @@ export const ChatHistoryPopover: React.FC<ChatHistoryPopoverProps> = ({
119
178
  ))}
120
179
  </div>
121
180
  </ScrollArea>
181
+ {chats.length > 0 && (
182
+ <div className="border-t p-2 flex items-center justify-between gap-2">
183
+ {chats.length > CHAT_HISTORY_WARNING_THRESHOLD ? (
184
+ <p className="text-xs text-muted-foreground">
185
+ You have over <b>{CHAT_HISTORY_WARNING_THRESHOLD}</b> chats.
186
+ Delete old chats to free up browser storage.
187
+ </p>
188
+ ) : (
189
+ <p className="text-xs text-muted-foreground">
190
+ Chats are shared across notebooks.
191
+ </p>
192
+ )}
193
+ <Button
194
+ variant="linkDestructive"
195
+ size="xs"
196
+ disabled={isLoading}
197
+ onClick={confirmDeleteAllChats}
198
+ >
199
+ Delete all chats
200
+ </Button>
201
+ </div>
202
+ )}
122
203
  </PopoverContent>
123
204
  </Popover>
124
205
  );
@@ -150,12 +150,16 @@ interface ChatHeaderProps {
150
150
  onNewChat: () => void;
151
151
  activeChatId: ChatId | undefined;
152
152
  setActiveChat: (id: ChatId | null) => void;
153
+ onDeleteChats: (id: ChatId | null) => void;
154
+ isLoading: boolean;
153
155
  }
154
156
 
155
157
  const ChatHeader: React.FC<ChatHeaderProps> = ({
156
158
  onNewChat,
157
159
  activeChatId,
158
160
  setActiveChat,
161
+ onDeleteChats,
162
+ isLoading,
159
163
  }) => {
160
164
  const { handleClick } = useOpenSettingsToTab();
161
165
 
@@ -184,6 +188,8 @@ const ChatHeader: React.FC<ChatHeaderProps> = ({
184
188
  <ChatHistoryPopover
185
189
  activeChatId={activeChatId}
186
190
  setActiveChat={setActiveChat}
191
+ onDeleteChats={onDeleteChats}
192
+ isLoading={isLoading}
187
193
  />
188
194
  </div>
189
195
  </div>
@@ -838,6 +844,27 @@ const ChatPanelBody = () => {
838
844
  clearFiles();
839
845
  });
840
846
 
847
+ const handleDeleteChats = useEvent((id: ChatId | null) => {
848
+ if (id === null || id === activeChatId) {
849
+ handleNewChat();
850
+ }
851
+ setChatState((prev) => {
852
+ const chats = new Map(prev.chats);
853
+ if (id === null) {
854
+ chats.clear();
855
+ } else {
856
+ chats.delete(id);
857
+ }
858
+ return {
859
+ chats,
860
+ activeChatId:
861
+ prev.activeChatId && chats.has(prev.activeChatId)
862
+ ? prev.activeChatId
863
+ : null,
864
+ };
865
+ });
866
+ });
867
+
841
868
  const handlePairWithAgent = useEvent(() => {
842
869
  openModal(<PairWithAgentModal onClose={closeModal} />);
843
870
  });
@@ -997,6 +1024,8 @@ const ChatPanelBody = () => {
997
1024
  onNewChat={handleNewChat}
998
1025
  activeChatId={activeChat?.id}
999
1026
  setActiveChat={setActiveChat}
1027
+ onDeleteChats={handleDeleteChats}
1028
+ isLoading={isLoading}
1000
1029
  />
1001
1030
  </TooltipProvider>
1002
1031
 
@@ -0,0 +1,120 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { createStore } from "jotai";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { toast } from "@/components/ui/use-toast";
6
+ import { type Chat, type ChatId, chatStateAtom } from "../state";
7
+
8
+ vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
9
+
10
+ const KEY = "marimo:ai:chatState:v5";
11
+ const chatId = "saved-chat" as ChatId;
12
+ const chat: Chat = {
13
+ id: chatId,
14
+ title: "Saved conversation",
15
+ messages: [
16
+ { id: "message", role: "user", parts: [{ type: "text", text: "Hello" }] },
17
+ ],
18
+ createdAt: 1,
19
+ updatedAt: 1,
20
+ };
21
+
22
+ const unsubscribers: (() => void)[] = [];
23
+
24
+ function loadStore() {
25
+ const store = createStore();
26
+ unsubscribers.push(store.sub(chatStateAtom, vi.fn()));
27
+ return store;
28
+ }
29
+
30
+ function fillStorage() {
31
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
32
+ throw new DOMException("Storage is full", "QuotaExceededError");
33
+ });
34
+ }
35
+
36
+ describe("chat history storage", () => {
37
+ beforeEach(() => {
38
+ window.localStorage.clear();
39
+ window.localStorage.setItem(
40
+ KEY,
41
+ JSON.stringify({
42
+ chats: [[chatId, chat]],
43
+ activeChatId: chatId,
44
+ }),
45
+ );
46
+ });
47
+
48
+ afterEach(() => {
49
+ for (const unsubscribe of unsubscribers.splice(0)) {
50
+ unsubscribe();
51
+ }
52
+ vi.restoreAllMocks();
53
+ });
54
+
55
+ it("loads saved history when storage is full", () => {
56
+ fillStorage();
57
+ expect(loadStore().get(chatStateAtom)).toEqual({
58
+ chats: new Map([[chatId, chat]]),
59
+ activeChatId: chatId,
60
+ });
61
+ });
62
+
63
+ it("warns on save failure without interrupting in-memory updates", () => {
64
+ const store = loadStore();
65
+ const savedHistory = window.localStorage.getItem(KEY);
66
+ fillStorage();
67
+ const updatedChat = { ...chat, title: "Unsaved conversation" };
68
+ expect(() =>
69
+ store.set(chatStateAtom, {
70
+ chats: new Map([[chatId, updatedChat]]),
71
+ activeChatId: chatId,
72
+ }),
73
+ ).not.toThrow();
74
+
75
+ expect(store.get(chatStateAtom).chats.get(chatId)).toEqual(updatedChat);
76
+ expect(window.localStorage.getItem(KEY)).toBe(savedHistory);
77
+ expect(toast).toHaveBeenCalledWith(
78
+ expect.objectContaining({
79
+ id: "chat-storage-error",
80
+ once: true,
81
+ title: "Chat history couldn't be saved",
82
+ }),
83
+ );
84
+ });
85
+
86
+ it("frees storage when history is cleared even if further writes fail", () => {
87
+ window.localStorage.setItem("unrelated-setting", "keep");
88
+ const store = loadStore();
89
+ fillStorage();
90
+ store.set(chatStateAtom, { chats: new Map(), activeChatId: null });
91
+
92
+ expect(window.localStorage.getItem(KEY)).toBeNull();
93
+ expect(window.localStorage.getItem("unrelated-setting")).toBe("keep");
94
+ expect(loadStore().get(chatStateAtom)).toEqual({
95
+ chats: new Map(),
96
+ activeChatId: null,
97
+ });
98
+ expect(toast).not.toHaveBeenCalled();
99
+ });
100
+
101
+ it("removes saved history when only an empty chat remains and writes fail", () => {
102
+ const store = loadStore();
103
+ const emptyChat = { ...chat, messages: [] };
104
+ const state = {
105
+ chats: new Map([[chatId, emptyChat]]),
106
+ activeChatId: chatId,
107
+ };
108
+ fillStorage();
109
+
110
+ store.set(chatStateAtom, state);
111
+
112
+ expect(window.localStorage.getItem(KEY)).toBeNull();
113
+ expect(store.get(chatStateAtom)).toEqual(state);
114
+ expect(loadStore().get(chatStateAtom)).toEqual({
115
+ chats: new Map(),
116
+ activeChatId: null,
117
+ });
118
+ expect(toast).not.toHaveBeenCalled();
119
+ });
120
+ });
@@ -4,7 +4,9 @@ import type { UIMessage } from "@ai-sdk/react";
4
4
  import type { FileUIPart } from "ai";
5
5
  import { atom } from "jotai";
6
6
  import { atomWithStorage } from "jotai/utils";
7
+ import { toast } from "@/components/ui/use-toast";
7
8
  import { uniqueBy } from "@/utils/arrays";
9
+ import { Logger } from "@/utils/Logger";
8
10
  import { adaptForLocalStorage, jotaiJsonStorage } from "@/utils/storage/jotai";
9
11
  import type { TypedString } from "@/utils/typed";
10
12
  import type { CellId } from "../cells/ids";
@@ -85,22 +87,46 @@ function removeEmptyChats(chatState: Map<ChatId, Chat>): Map<ChatId, Chat> {
85
87
  return result;
86
88
  }
87
89
 
90
+ const chatStorage = adaptForLocalStorage({
91
+ toSerializable: (value: ChatState) => ({
92
+ chats: [...removeEmptyChats(value.chats).entries()],
93
+ activeChatId: value.activeChatId,
94
+ }),
95
+ fromSerializable: (value) => ({
96
+ chats: new Map(value.chats),
97
+ activeChatId: value.activeChatId,
98
+ }),
99
+ });
100
+
88
101
  export const chatStateAtom = atomWithStorage<ChatState>(
89
102
  KEY,
90
103
  {
91
104
  chats: new Map(),
92
105
  activeChatId: null,
93
106
  },
94
- adaptForLocalStorage({
95
- toSerializable: (value: ChatState) => ({
96
- chats: [...removeEmptyChats(value.chats).entries()],
97
- activeChatId: value.activeChatId,
98
- }),
99
- fromSerializable: (value) => ({
100
- chats: new Map(value.chats),
101
- activeChatId: value.activeChatId,
102
- }),
103
- }),
107
+ {
108
+ ...chatStorage,
109
+ setItem: (key, value) => {
110
+ try {
111
+ // Removing the key frees space even when no further writes can fit.
112
+ if (removeEmptyChats(value.chats).size === 0) {
113
+ chatStorage.removeItem(key);
114
+ } else {
115
+ chatStorage.setItem(key, value);
116
+ }
117
+ } catch (error) {
118
+ Logger.warn("Could not save chat history", error);
119
+ toast({
120
+ id: "chat-storage-error",
121
+ once: true,
122
+ title: "Chat history couldn't be saved",
123
+ description:
124
+ "Try deleting old chats. New messages may be lost when you reload.",
125
+ variant: "danger",
126
+ });
127
+ }
128
+ },
129
+ },
104
130
  );
105
131
 
106
132
  export const activeChatAtom = atom(