Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(agent): streamline page sidebar archive actions (#20002)

p0ny043bbbf9778d
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 1c84a0edf9..da34fce456 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -19,7 +19,6 @@
"title": "AI Assistant isn’t configured for this workspace"
},
"archive-chat": "Archive",
- "archive-chat-confirmation": "Archive this chat?",
"archived-only-chats": "Archived only",
"args": "Args:",
"assistant-title": "Bytebase Assistant",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 16e04d0890..cbdbd89e9f 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -19,7 +19,6 @@
"title": "El asistente de IA no está configurado para este espacio de trabajo"
},
"archive-chat": "Archivar",
- "archive-chat-confirmation": "¿Archivar este chat?",
"archived-only-chats": "Solo archivadas",
"args": "Argumentos:",
"assistant-title": "Asistente de Bytebase",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a09925cd24..8cca76c363 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -19,7 +19,6 @@
"title": "このワークスペースでは AI アシスタントが設定されていません"
},
"archive-chat": "アーカイブ",
- "archive-chat-confirmation": "このチャットをアーカイブしますか?",
"archived-only-chats": "アーカイブのみ",
"args": "引数:",
"assistant-title": "Bytebase アシスタント",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 4e5581672d..3221d7d379 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -19,7 +19,6 @@
"title": "Trợ lý AI chưa được cấu hình cho workspace này"
},
"archive-chat": "Lưu trữ",
- "archive-chat-confirmation": "Lưu trữ chat này?",
"archived-only-chats": "Chỉ lưu trữ",
"args": "Tham số:",
"assistant-title": "Trợ lý Bytebase",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index f48e354a42..42d2c45996 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -19,7 +19,6 @@
"title": "此工作空间尚未配置 AI 助手"
},
"archive-chat": "归档",
- "archive-chat-confirmation": "要归档这个聊天吗?",
"archived-only-chats": "仅显示已归档",
"args": "参数:",
"assistant-title": "Bytebase 助手",
diff --git a/frontend/src/react/components/ui/tooltip.test.tsx b/frontend/src/react/components/ui/tooltip.test.tsx
new file mode 100644
index 0000000000..ed7b31c38d
--- /dev/null
+++ b/frontend/src/react/components/ui/tooltip.test.tsx
@@ -0,0 +1,47 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { Tooltip } from "./tooltip";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("Tooltip", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ document.body.innerHTML = "";
+ });
+
+ test("applies the overlay z-layer to the tooltip positioner", async () => {
+ vi.useFakeTimers();
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <Tooltip content="Tip content">
+ <button type="button">Trigger</button>
+ </Tooltip>
+ );
+ });
+
+ const trigger = container.querySelector("button");
+ expect(trigger).toBeInstanceOf(HTMLButtonElement);
+
+ await act(async () => {
+ trigger?.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(document.body.textContent).toContain("Tip content");
+ const positioner = document.body.querySelector('[role="presentation"]');
+ expect(positioner?.className).toContain("z-50");
+
+ act(() => {
+ root.unmount();
+ });
+ });
+});
diff --git a/frontend/src/react/components/ui/tooltip.tsx b/frontend/src/react/components/ui/tooltip.tsx
index bf0c955595..cc1a608041 100644
--- a/frontend/src/react/components/ui/tooltip.tsx
+++ b/frontend/src/react/components/ui/tooltip.tsx
@@ -25,8 +25,8 @@ export function Tooltip({
{children}
</BaseTooltip.Trigger>
<BaseTooltip.Portal>
- <BaseTooltip.Positioner side={side} sideOffset={4}>
- <BaseTooltip.Popup className="z-50 max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md">
+ <BaseTooltip.Positioner side={side} sideOffset={4} className="z-50">
+ <BaseTooltip.Popup className="max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md">
{content}
<BaseTooltip.Arrow className="fill-main" />
</BaseTooltip.Popup>
@@ -59,8 +59,8 @@ export function BlockTooltip({
{children}
</BaseTooltip.Trigger>
<BaseTooltip.Portal>
- <BaseTooltip.Positioner side={side} sideOffset={4}>
- <BaseTooltip.Popup className="z-50 max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md">
+ <BaseTooltip.Positioner side={side} sideOffset={4} className="z-50">
+ <BaseTooltip.Popup className="max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md">
{content}
<BaseTooltip.Arrow className="fill-main" />
</BaseTooltip.Popup>
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index d32fd6a62a..9827c0d49c 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -15,8 +15,8 @@
"description": "AI is not configured for this workspace.",
"title": "AI Not Configured"
},
+ "archive-all-chats": "Archive all chats",
"archive-chat": "Archive chat",
- "archive-chat-confirmation": "Are you sure you want to archive this chat?",
"archived-only-chats": "Archived only",
"args": "Args",
"assistant-title": "AI Assistant",
@@ -32,6 +32,8 @@
"chat-total-tokens": "Total tokens",
"close": "Close",
"confirm": "Confirm",
+ "delete-all-chats": "Delete all chats",
+ "delete-all-chats-confirmation": "Are you sure you want to delete all archived chats? This action cannot be undone.",
"delete-chat": "Delete chat",
"delete-chat-confirmation": "Are you sure you want to delete this chat? This action cannot be undone.",
"input-placeholder": "Ask AI anything...",
@@ -60,6 +62,7 @@
"tool-prompt": "Prompt",
"tool-response-submitted": "Response submitted",
"tool-value": "Value",
+ "unarchive-all-chats": "Unarchive all chats",
"unarchive-chat": "Unarchive chat"
},
"audit-log": {
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 3ffe513b93..72c8b5a320 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -15,8 +15,8 @@
"description": "La IA no está configurada para este espacio de trabajo.",
"title": "IA no configurada"
},
+ "archive-all-chats": "Archivar todos los chats",
"archive-chat": "Archivar chat",
- "archive-chat-confirmation": "¿Está seguro de que desea archivar este chat?",
"archived-only-chats": "Solo archivados",
"args": "Argumentos",
"assistant-title": "Asistente de IA",
@@ -32,6 +32,8 @@
"chat-total-tokens": "Tokens totales",
"close": "Cerrar",
"confirm": "Confirmar",
+ "delete-all-chats": "Eliminar todos los chats",
+ "delete-all-chats-confirmation": "¿Está seguro de que desea eliminar todos los chats archivados? Esta acción no se puede deshacer.",
"delete-chat": "Eliminar chat",
"delete-chat-confirmation": "¿Está seguro de que desea eliminar este chat? Esta acción no se puede deshacer.",
"input-placeholder": "Pregunta algo a la IA...",
@@ -60,6 +62,7 @@
"tool-prompt": "Indicación",
"tool-response-submitted": "Respuesta enviada",
"tool-value": "Valor",
+ "unarchive-all-chats": "Desarchivar todos los chats",
"unarchive-chat": "Desarchivar chat"
},
"audit-log": {
@@ -236,7 +239,7 @@
"minutes": "Minutos",
"missing-required-permission": "Faltan permisos requeridos {{permissions}}",
"missing-required-permission-for-resource": "Faltan permisos requeridos para el recurso {{resource}}",
- "more": "More",
+ "more": "Más",
"n-items-selected": "{{n}} elementos seleccionados",
"n-more": "+{{n}} más",
"name": "Nombre",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index d573eb248b..8606eb67c3 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -15,8 +15,8 @@
"description": "このワークスペースでは AI が設定されていません。",
"title": "AI 未設定"
},
+ "archive-all-chats": "すべてのチャットをアーカイブ",
"archive-chat": "チャットをアーカイブ",
- "archive-chat-confirmation": "このチャットをアーカイブしますか?",
"archived-only-chats": "アーカイブ済みのみ",
"args": "引数",
"assistant-title": "AI アシスタント",
@@ -32,6 +32,8 @@
"chat-total-tokens": "合計トークン数",
"close": "閉じる",
"confirm": "確認",
+ "delete-all-chats": "すべてのチャットを削除",
+ "delete-all-chats-confirmation": "アーカイブ済みのチャットをすべて削除しますか?この操作は元に戻せません。",
"delete-chat": "チャットを削除",
"delete-chat-confirmation": "このチャットを削除しますか?この操作は元に戻せません。",
"input-placeholder": "AI に何でも聞いてください...",
@@ -60,6 +62,7 @@
"tool-prompt": "プロンプト",
"tool-response-submitted": "回答が送信されました",
"tool-value": "値",
+ "unarchive-all-chats": "すべてのチャットのアーカイブを解除",
"unarchive-chat": "アーカイブ解除"
},
"audit-log": {
@@ -236,7 +239,7 @@
"minutes": "分",
"missing-required-permission": "必要な権限がありません {{permissions}}",
"missing-required-permission-for-resource": "リソース {{resource}} に必要な権限がありません",
- "more": "More",
+ "more": "その他",
"n-items-selected": "{{n}} 件選択済み",
"n-more": "+{{n}} もっと",
"name": "名前",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 817c070184..8f87c2824b 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -15,8 +15,8 @@
"description": "AI chưa được cấu hình cho không gian làm việc này.",
"title": "AI chưa được cấu hình"
},
+ "archive-all-chats": "Lưu trữ tất cả cuộc trò chuyện",
"archive-chat": "Lưu trữ cuộc trò chuyện",
- "archive-chat-confirmation": "Bạn có chắc chắn muốn lưu trữ cuộc trò chuyện này?",
"archived-only-chats": "Chỉ đã lưu trữ",
"args": "Tham số",
"assistant-title": "Trợ lý AI",
@@ -32,6 +32,8 @@
"chat-total-tokens": "Tổng số token",
"close": "Đóng",
"confirm": "Xác nhận",
+ "delete-all-chats": "Xóa tất cả cuộc trò chuyện",
+ "delete-all-chats-confirmation": "Bạn có chắc chắn muốn xóa tất cả cuộc trò chuyện đã lưu trữ không? Hành động này không thể hoàn tác.",
"delete-chat": "Xóa cuộc trò chuyện",
"delete-chat-confirmation": "Bạn có chắc chắn muốn xóa cuộc trò chuyện này? Hành động này không thể hoàn tác.",
"input-placeholder": "Hỏi AI bất cứ điều gì...",
@@ -60,6 +62,7 @@
"tool-prompt": "Lời nhắc",
"tool-response-submitted": "Phản hồi đã được gửi",
"tool-value": "Giá trị",
+ "unarchive-all-chats": "Bỏ lưu trữ tất cả cuộc trò chuyện",
"unarchive-chat": "Bỏ lưu trữ"
},
"audit-log": {
@@ -236,7 +239,7 @@
"minutes": "Phút",
"missing-required-permission": "Thiếu quyền cần thiết {{permissions}}",
"missing-required-permission-for-resource": "Thiếu quyền cần thiết cho tài nguyên {{resource}}",
- "more": "More",
+ "more": "Thêm",
"n-items-selected": "Đã chọn {{n}} mục",
"n-more": "+{{n}} nữa",
"name": "Tên",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 9ae2db1375..ac85ba02cc 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -15,8 +15,8 @@
"description": "此工作区尚未配置 AI。",
"title": "AI 未配置"
},
+ "archive-all-chats": "归档所有对话",
"archive-chat": "归档对话",
- "archive-chat-confirmation": "确定要归档此对话吗?",
"archived-only-chats": "仅已归档",
"args": "参数",
"assistant-title": "AI 助手",
@@ -32,6 +32,8 @@
"chat-total-tokens": "总 token 数",
"close": "关闭",
"confirm": "确认",
+ "delete-all-chats": "删除所有对话",
+ "delete-all-chats-confirmation": "确定要删除所有已归档对话吗?此操作无法撤销。",
"delete-chat": "删除对话",
"delete-chat-confirmation": "确定要删除此对话吗?此操作无法撤销。",
"input-placeholder": "向 AI 提问...",
@@ -60,6 +62,7 @@
"tool-prompt": "提示",
"tool-response-submitted": "已提交回复",
"tool-value": "值",
+ "unarchive-all-chats": "取消归档所有对话",
"unarchive-chat": "取消归档"
},
"audit-log": {
@@ -236,7 +239,7 @@
"minutes": "分钟",
"missing-required-permission": "缺少必需的权限 {{permissions}}",
"missing-required-permission-for-resource": "缺少资源 {{resource}} 的必需权限",
- "more": "More",
+ "more": "更多",
"n-items-selected": "已选 {{n}} 项",
"n-more": "+{{n}} 更多",
"name": "名称",
diff --git a/frontend/src/react/plugins/agent/components/AgentWindow.test.tsx b/frontend/src/react/plugins/agent/components/AgentWindow.test.tsx
new file mode 100644
index 0000000000..1dfdd3f0cf
--- /dev/null
+++ b/frontend/src/react/plugins/agent/components/AgentWindow.test.tsx
@@ -0,0 +1,306 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { createAgentStore, useAgentStore } from "../store/agent";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ useTranslation: vi.fn(() => ({
+ t: (key: string) => key,
+ i18n: { language: "en-US" },
+ })),
+}));
+
+function createMockStorage(): Storage {
+ let store: Record<string, string> = {};
+ return {
+ get length() {
+ return Object.keys(store).length;
+ },
+ key(index: number) {
+ return Object.keys(store)[index] ?? null;
+ },
+ getItem(key: string) {
+ return store[key] ?? null;
+ },
+ setItem(key: string, value: string) {
+ store[key] = String(value);
+ },
+ removeItem(key: string) {
+ delete store[key];
+ },
+ clear() {
+ store = {};
+ },
+ };
+}
+
+vi.mock("react-i18next", () => ({
+ useTranslation: mocks.useTranslation,
+}));
+
+vi.mock("./AgentChat", () => ({
+ AgentChat: () => <div data-testid="agent-chat" />,
+}));
+
+vi.mock("./AgentInput", () => ({
+ AgentInput: () => <div data-testid="agent-input" />,
+}));
+
+let AgentWindow: typeof import("./AgentWindow").AgentWindow;
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ return {
+ container,
+ render: () => {
+ act(() => {
+ root.render(element);
+ });
+ },
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ container.remove();
+ }),
+ };
+};
+
+beforeEach(async () => {
+ vi.stubGlobal("localStorage", createMockStorage());
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ disconnect() {}
+ }
+ );
+ vi.stubGlobal("PointerEvent", MouseEvent);
+ Object.defineProperty(window, "matchMedia", {
+ configurable: true,
+ writable: true,
+ value: vi.fn().mockImplementation(() => ({
+ matches: true,
+ media: "",
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ });
+
+ const initialState = createAgentStore().getState();
+ useAgentStore.setState({
+ visible: initialState.visible,
+ position: initialState.position,
+ size: initialState.size,
+ sidebarWidth: initialState.sidebarWidth,
+ minimized: initialState.minimized,
+ chats: initialState.chats,
+ messagesByChatId: initialState.messagesByChatId,
+ pendingAskByChatId: initialState.pendingAskByChatId,
+ currentChatId: initialState.currentChatId,
+ abortControllersByChatId: {},
+ });
+ useAgentStore.setState({
+ visible: true,
+ minimized: false,
+ position: { x: 100, y: 120 },
+ size: { width: 500, height: 450 },
+ sidebarWidth: 200,
+ });
+
+ mocks.useTranslation.mockReset();
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string) => key,
+ i18n: { language: "en-US" },
+ });
+
+ ({ AgentWindow } = await import("./AgentWindow"));
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ document.body.innerHTML = "";
+});
+
+describe("AgentWindow", () => {
+ test("selects the next archived chat after deleting the current archived chat", () => {
+ const activeChatId = useAgentStore.getState().currentChatId!;
+ const firstArchivedChat = useAgentStore.getState().createChat({
+ title: "First archived",
+ archived: true,
+ select: false,
+ });
+ const secondArchivedChat = useAgentStore.getState().createChat({
+ title: "Second archived",
+ archived: true,
+ select: false,
+ });
+
+ useAgentStore.setState({
+ chats: useAgentStore.getState().chats.map((chat) => {
+ if (chat.id === activeChatId) {
+ return { ...chat, updatedTs: 3000 };
+ }
+ if (chat.id === firstArchivedChat.id) {
+ return { ...chat, updatedTs: 2000 };
+ }
+ if (chat.id === secondArchivedChat.id) {
+ return { ...chat, updatedTs: 1000 };
+ }
+ return chat;
+ }),
+ currentChatId: firstArchivedChat.id,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+
+ render();
+
+ const moreButton = document.body.querySelector(
+ "[aria-label='common.more']"
+ ) as HTMLButtonElement | null;
+
+ act(() => {
+ moreButton?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+
+ const archivedModeButton = document.body.querySelector(
+ "[data-agent-chat-list-mode]"
+ ) as HTMLDivElement | null;
+
+ act(() => {
+ archivedModeButton?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+
+ const deleteButtons = Array.from(
+ document.body.querySelectorAll("[data-agent-delete-chat]")
+ ) as HTMLButtonElement[];
+
+ expect(deleteButtons).toHaveLength(2);
+
+ act(() => {
+ deleteButtons[0]?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+
+ const confirmButton = Array.from(
+ document.body.querySelectorAll("button")
+ ).find((button) => button.textContent === "common.confirm");
+
+ act(() => {
+ confirmButton?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+
+ expect(useAgentStore.getState().getChat(firstArchivedChat.id)).toBeNull();
+ expect(useAgentStore.getState().currentChatId).toBe(secondArchivedChat.id);
+
+ unmount();
+ });
+
+ test("keeps the running chat selected when archiving it from the active list", () => {
+ const chatId = useAgentStore.getState().currentChatId!;
+ useAgentStore.getState().startChatRun(chatId, {
+ path: "/projects/demo",
+ title: "Demo",
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+
+ render();
+
+ const archiveButton = document.body.querySelector(
+ "[data-agent-archive-chat]"
+ ) as HTMLButtonElement | null;
+
+ expect(archiveButton).toBeInstanceOf(HTMLButtonElement);
+
+ act(() => {
+ archiveButton?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+
+ expect(useAgentStore.getState().getChat(chatId)?.archived).toBe(true);
+ expect(useAgentStore.getState().currentChatId).toBe(chatId);
+
+ unmount();
+ });
+
+ test("commits drag position only on pointerup", () => {
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+
+ render();
+
+ const windowEl = document.body.querySelector(
+ "[data-agent-window]"
+ ) as HTMLDivElement | null;
+ const header = windowEl?.querySelector(
+ ".cursor-move"
+ ) as HTMLDivElement | null;
+
+ expect(windowEl).toBeInstanceOf(HTMLDivElement);
+ expect(header).toBeInstanceOf(HTMLDivElement);
+
+ Object.defineProperty(windowEl, "offsetWidth", {
+ configurable: true,
+ get: () => 500,
+ });
+ Object.defineProperty(windowEl, "offsetHeight", {
+ configurable: true,
+ get: () => 450,
+ });
+
+ act(() => {
+ header?.dispatchEvent(
+ new PointerEvent("pointerdown", {
+ bubbles: true,
+ button: 0,
+ clientX: 150,
+ clientY: 150,
+ })
+ );
+ document.dispatchEvent(
+ new PointerEvent("pointermove", {
+ bubbles: true,
+ clientX: 180,
+ clientY: 190,
+ })
+ );
+ });
+
+ expect(windowEl?.style.left).toBe("130px");
+ expect(windowEl?.style.top).toBe("160px");
+ expect(useAgentStore.getState().position).toEqual({ x: 100, y: 120 });
+
+ act(() => {
+ document.dispatchEvent(
+ new PointerEvent("pointerup", {
+ bubbles: true,
+ clientX: 180,
+ clientY: 190,
+ })
+ );
+ });
+
+ expect(useAgentStore.getState().position).toEqual({ x: 130, y: 160 });
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/plugins/agent/components/AgentWindow.tsx b/frontend/src/react/plugins/agent/components/AgentWindow.tsx
index 36a1e19713..e970696982 100644
--- a/frontend/src/react/plugins/agent/components/AgentWindow.tsx
+++ b/frontend/src/react/plugins/agent/components/AgentWindow.tsx
@@ -1,8 +1,16 @@
-import { Archive, Inbox } from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Archive, EllipsisVertical, Plus, Trash2, Undo2 } from "lucide-react";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { HumanizeTs } from "@/react/components/HumanizeTs";
+import { Button } from "@/react/components/ui/button";
import {
Dialog,
DialogClose,
@@ -11,7 +19,15 @@ import {
DialogTitle,
DialogTrigger,
} from "@/react/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/react/components/ui/dropdown-menu";
import { Input } from "@/react/components/ui/input";
+import { Tooltip } from "@/react/components/ui/tooltip";
import { cn } from "@/react/lib/utils";
import type { AgentChat as AgentChatRecord } from "../logic/types";
import {
@@ -80,11 +96,16 @@ export function AgentWindow() {
const [showArchivedOnly, setShowArchivedOnly] = useState(false);
const [isRenamingCurrentChat, setIsRenamingCurrentChat] = useState(false);
+ const [
+ isDeleteAllArchivedChatsDialogOpen,
+ setIsDeleteAllArchivedChatsDialogOpen,
+ ] = useState(false);
const [renamingTitle, setRenamingTitle] = useState("");
// Refs for drag/resize intermediate values (avoid re-renders)
const isDraggingRef = useRef(false);
const dragOffsetRef = useRef({ x: 0, y: 0 });
+ const dragPositionRef = useRef<{ x: number; y: number } | null>(null);
const isResizingRef = useRef(false);
const resizeStartRef = useRef<{
x: number;
@@ -217,10 +238,13 @@ export function AgentWindow() {
() => orderedChats.filter((chat) => chat.archived === showArchivedOnly),
[orderedChats, showArchivedOnly]
);
-
- const isCurrentChatInDisplayedMode = useMemo(
- () => !!currentChat && currentChat.archived === showArchivedOnly,
- [currentChat, showArchivedOnly]
+ const activeChats = useMemo(
+ () => orderedChats.filter((chat) => !chat.archived),
+ [orderedChats]
+ );
+ const archivedChats = useMemo(
+ () => orderedChats.filter((chat) => chat.archived),
+ [orderedChats]
);
const currentChatStatusLabel = useMemo(() => {
@@ -256,6 +280,12 @@ export function AgentWindow() {
);
const isChatCreationDisabled = hasRunningChat;
+ const isArchiveAllDisabled =
+ hasRunningChat || showArchivedOnly || activeChats.length === 0;
+ const isUnarchiveAllDisabled =
+ hasRunningChat || !showArchivedOnly || archivedChats.length === 0;
+ const isDeleteAllDisabled =
+ hasRunningChat || !showArchivedOnly || archivedChats.length === 0;
const canResizeWindow = supportsFinePointer;
const syncStoreToDisplayState = useCallback(() => {
@@ -296,24 +326,36 @@ export function AgentWindow() {
);
const selectFirstDisplayedChat = useCallback(() => {
- const first = displayedChats[0];
+ const store = useAgentStore.getState();
+ const first = selectOrderedChats(store).find(
+ (chat) => chat.archived === showArchivedOnly
+ );
if (!first || !useAgentStore.getState().canSelectChat(first.id))
return false;
useAgentStore.getState().setCurrentChat(first.id);
return useAgentStore.getState().currentChatId === first.id;
- }, [displayedChats]);
+ }, [showArchivedOnly]);
const ensureCurrentChatMatchesDisplayedMode = useCallback(
- (options: { fallbackToActiveWhenEmpty?: boolean } = {}) => {
+ (
+ options: {
+ allowCreateWhenEmpty?: boolean;
+ fallbackToActiveWhenEmpty?: boolean;
+ } = {}
+ ) => {
const store = useAgentStore.getState();
const chat = store.chats.find((c) => c.id === store.currentChatId);
+ if (chat?.status === "running") return;
const isInDisplayedMode = !!chat && chat.archived === showArchivedOnly;
if (isInDisplayedMode) return;
if (selectFirstDisplayedChat()) return;
if (showArchivedOnly) {
- if (!options.fallbackToActiveWhenEmpty) return;
+ if (!options.fallbackToActiveWhenEmpty) {
+ store.clearCurrentChat();
+ return;
+ }
setShowArchivedOnly(false);
// After toggling, check again with active mode
const storeNow = useAgentStore.getState();
@@ -332,7 +374,15 @@ export function AgentWindow() {
}
}
- if (store.chats.some((c) => c.status === "running")) return;
+ if (options.allowCreateWhenEmpty !== true || showArchivedOnly) {
+ store.clearCurrentChat();
+ return;
+ }
+
+ if (store.chats.some((c) => c.status === "running")) {
+ store.clearCurrentChat();
+ return;
+ }
store.createChat({ page: getCurrentPageSnapshot() });
},
[showArchivedOnly, selectFirstDisplayedChat, getCurrentPageSnapshot]
@@ -420,31 +470,87 @@ export function AgentWindow() {
[isRenamingCurrentChat, beginRenameCurrentChat, cancelRenameCurrentChat]
);
- const toggleArchiveCurrentChat = useCallback(() => {
- const chat = useAgentStore
- .getState()
- .chats.find((c) => c.id === useAgentStore.getState().currentChatId);
- if (!chat) return;
- if (chat.archived) {
+ const archiveChat = useCallback(
+ (chatId: string) => {
+ const chat = useAgentStore.getState().chats.find((c) => c.id === chatId);
+ if (!chat || chat.archived) return;
+ useAgentStore.getState().archiveChat(chat.id);
+ ensureCurrentChatMatchesDisplayedMode({
+ allowCreateWhenEmpty: false,
+ });
+ },
+ [ensureCurrentChatMatchesDisplayedMode]
+ );
+
+ const unarchiveChat = useCallback(
+ (chatId: string) => {
+ const chat = useAgentStore.getState().chats.find((c) => c.id === chatId);
+ if (!chat?.archived) return;
useAgentStore.getState().unarchiveChat(chat.id);
ensureCurrentChatMatchesDisplayedMode({
- fallbackToActiveWhenEmpty: true,
+ allowCreateWhenEmpty: false,
});
- return;
- }
- useAgentStore.getState().archiveChat(chat.id);
- ensureCurrentChatMatchesDisplayedMode();
- }, [ensureCurrentChatMatchesDisplayedMode]);
+ },
+ [ensureCurrentChatMatchesDisplayedMode]
+ );
- const deleteCurrentChat = useCallback(() => {
- const store = useAgentStore.getState();
- const chat = store.chats.find((c) => c.id === store.currentChatId);
- if (!chat) return;
- store.deleteChat(chat.id);
+ const archiveAllChats = useCallback(() => {
+ if (isArchiveAllDisabled) return;
+ const archivedCount = useAgentStore.getState().archiveAllActiveChats();
+ if (archivedCount === 0) return;
+ cancelRenameCurrentChat();
+ ensureCurrentChatMatchesDisplayedMode({
+ allowCreateWhenEmpty: false,
+ });
+ }, [
+ cancelRenameCurrentChat,
+ ensureCurrentChatMatchesDisplayedMode,
+ isArchiveAllDisabled,
+ ]);
+
+ const unarchiveAllChats = useCallback(() => {
+ if (isUnarchiveAllDisabled) return;
+ const unarchivedCount = useAgentStore
+ .getState()
+ .unarchiveAllArchivedChats();
+ if (unarchivedCount === 0) return;
+ cancelRenameCurrentChat();
+ ensureCurrentChatMatchesDisplayedMode({
+ allowCreateWhenEmpty: false,
+ });
+ }, [
+ cancelRenameCurrentChat,
+ ensureCurrentChatMatchesDisplayedMode,
+ isUnarchiveAllDisabled,
+ ]);
+
+ const deleteAllArchivedChats = useCallback(() => {
+ if (isDeleteAllDisabled) return;
+ const deletedCount = useAgentStore.getState().deleteAllArchivedChats();
+ if (deletedCount === 0) return;
+ cancelRenameCurrentChat();
+ setIsDeleteAllArchivedChatsDialogOpen(false);
ensureCurrentChatMatchesDisplayedMode({
- fallbackToActiveWhenEmpty: true,
+ allowCreateWhenEmpty: false,
});
- }, [ensureCurrentChatMatchesDisplayedMode]);
+ }, [
+ cancelRenameCurrentChat,
+ ensureCurrentChatMatchesDisplayedMode,
+ isDeleteAllDisabled,
+ ]);
+
+ const deleteChat = useCallback(
+ (chatId: string) => {
+ const store = useAgentStore.getState();
+ const chat = store.chats.find((c) => c.id === chatId);
+ if (!chat) return;
+ store.deleteChat(chat.id);
+ ensureCurrentChatMatchesDisplayedMode({
+ allowCreateWhenEmpty: false,
+ });
+ },
+ [ensureCurrentChatMatchesDisplayedMode]
+ );
const toggleChatListMode = useCallback(() => {
setShowArchivedOnly((prev) => !prev);
@@ -491,6 +597,10 @@ export function AgentWindow() {
x: event.clientX - store.position.x,
y: event.clientY - store.position.y,
};
+ dragPositionRef.current = {
+ x: store.position.x,
+ y: store.position.y,
+ };
const onDrag = (e: PointerEvent) => {
if (!isDraggingRef.current || !windowRef.current) return;
@@ -511,7 +621,7 @@ export function AgentWindow() {
);
el.style.left = `${x}px`;
el.style.top = `${y}px`;
- useAgentStore.getState().setPosition(x, y);
+ dragPositionRef.current = { x, y };
};
const stopDrag = () => {
@@ -520,6 +630,12 @@ export function AgentWindow() {
document.removeEventListener("pointerup", stopDrag);
document.removeEventListener("pointercancel", stopDrag);
dragCleanupRef.current = null;
+ if (dragPositionRef.current) {
+ useAgentStore
+ .getState()
+ .setPosition(dragPositionRef.current.x, dragPositionRef.current.y);
+ }
+ dragPositionRef.current = null;
useAgentStore.getState().saveWindowState();
};
@@ -772,7 +888,7 @@ export function AgentWindow() {
return createPortal(
<div
data-agent-window
- className="fixed bottom-4 right-4 z-[1999] flex size-10 cursor-pointer items-center justify-center rounded-full bg-accent text-accent-text shadow-lg hover:bg-accent-hover"
+ className="fixed bottom-4 right-4 z-40 flex size-10 cursor-pointer items-center justify-center rounded-full bg-accent text-accent-text shadow-lg hover:bg-accent-hover"
onClick={() => useAgentStore.getState().restore()}
>
<svg
@@ -796,9 +912,37 @@ export function AgentWindow() {
<div
ref={windowRef}
data-agent-window
- className="fixed z-[1999] overflow-visible"
+ className="fixed z-40 overflow-visible"
style={windowStyle}
>
+ <Dialog
+ open={isDeleteAllArchivedChatsDialogOpen}
+ onOpenChange={setIsDeleteAllArchivedChatsDialogOpen}
+ >
+ <DialogContent className="max-w-sm p-6">
+ <DialogTitle className="sr-only">{t("common.confirm")}</DialogTitle>
+ <DialogDescription>
+ {t("agent.delete-all-chats-confirmation")}
+ </DialogDescription>
+ <div className="mt-6 flex justify-end gap-x-2">
+ <DialogClose
+ render={
+ <Button variant="outline" type="button">
+ {t("common.cancel")}
+ </Button>
+ }
+ />
+ <DialogClose
+ render={
+ <Button type="button" variant="destructive">
+ {t("common.confirm")}
+ </Button>
+ }
+ onClick={deleteAllArchivedChats}
+ />
+ </div>
+ </DialogContent>
+ </Dialog>
<div className="flex size-full flex-col overflow-hidden rounded-lg border border-block-border bg-background shadow-xl">
{/* Header */}
<div
@@ -860,13 +1004,87 @@ export function AgentWindow() {
{t("agent.chat-list-label")}
</h2>
</div>
- <button
- className="rounded-xs border px-2 py-1.5 text-xs font-medium text-control-light hover:bg-control-bg disabled:cursor-not-allowed disabled:bg-control-bg disabled:text-control-placeholder"
- disabled={isChatCreationDisabled}
- onClick={createChat}
+ <div
+ className="flex items-center gap-x-2"
+ data-agent-chat-sidebar-actions
>
- {t("agent.new-chat")}
- </button>
+ <Tooltip content={t("agent.new-chat")}>
+ <Button
+ variant="outline"
+ size="icon"
+ className="size-7 text-control-light"
+ aria-label={t("agent.new-chat")}
+ disabled={isChatCreationDisabled}
+ onClick={createChat}
+ >
+ <Plus className="size-4" aria-hidden="true" />
+ </Button>
+ </Tooltip>
+ <DropdownMenu>
+ <Tooltip content={t("common.more")}>
+ <DropdownMenuTrigger
+ className="inline-flex size-7 items-center justify-center rounded-xs border border-control-border bg-transparent text-control-light outline-hidden hover:bg-control-bg focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50"
+ aria-label={t("common.more")}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <EllipsisVertical
+ className="size-4"
+ aria-hidden="true"
+ />
+ </DropdownMenuTrigger>
+ </Tooltip>
+ <DropdownMenuContent>
+ {showArchivedOnly ? (
+ <>
+ <DropdownMenuItem
+ data-agent-unarchive-all-chats
+ disabled={isUnarchiveAllDisabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ unarchiveAllChats();
+ }}
+ >
+ {t("agent.unarchive-all-chats")}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ data-agent-delete-all-chats
+ className="text-error data-highlighted:bg-red-50"
+ disabled={isDeleteAllDisabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ setIsDeleteAllArchivedChatsDialogOpen(true);
+ }}
+ >
+ {t("agent.delete-all-chats")}
+ </DropdownMenuItem>
+ </>
+ ) : (
+ <DropdownMenuItem
+ data-agent-archive-all-chats
+ disabled={isArchiveAllDisabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ archiveAllChats();
+ }}
+ >
+ {t("agent.archive-all-chats")}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ data-agent-chat-list-mode
+ onClick={(event) => {
+ event.stopPropagation();
+ toggleChatListMode();
+ }}
+ >
+ {showArchivedOnly
+ ? t("agent.active-only-chats")
+ : t("agent.archived-only-chats")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
</div>
</div>
@@ -876,7 +1094,7 @@ export function AgentWindow() {
{displayedChats.map((chat) => (
<div
key={chat.id}
- className={`w-full rounded-xs px-3 py-2 text-left text-sm transition-colors ${
+ className={`group w-full rounded-xs px-3 py-2 text-left text-sm transition-colors ${
chat.id === currentChatId
? "bg-accent/10 text-accent"
: "text-control hover:bg-background"
@@ -895,101 +1113,84 @@ export function AgentWindow() {
onKeyDown={onRenameKeydown}
/>
) : (
- <button
- type="button"
- className="w-full text-left disabled:cursor-not-allowed disabled:opacity-60"
- disabled={
- !useAgentStore.getState().canSelectChat(chat.id)
- }
- aria-current={
- chat.id === currentChatId ? "true" : undefined
- }
- onClick={() => handleChatRowClick(chat.id)}
- >
- <div
- className="truncate font-medium"
- data-agent-chat-title
+ <div className="flex items-start gap-x-2">
+ <button
+ type="button"
+ className="min-w-0 flex-1 text-left disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={
+ !useAgentStore.getState().canSelectChat(chat.id)
+ }
+ aria-current={
+ chat.id === currentChatId ? "true" : undefined
+ }
+ onClick={() => handleChatRowClick(chat.id)}
>
- {getChatLabel(chat)}
+ <div
+ className="truncate font-medium"
+ data-agent-chat-title
+ >
+ {getChatLabel(chat)}
+ </div>
+ <span
+ className={`mt-1 block truncate text-xs ${
+ chat.id === currentChatId
+ ? "text-accent/80"
+ : "text-control-light"
+ }`}
+ data-agent-chat-updated-ts
+ >
+ <HumanizeTs
+ ts={Math.floor(chat.updatedTs / 1000)}
+ />
+ </span>
+ </button>
+ <div className="pointer-events-none flex shrink-0 items-center gap-x-2 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
+ {chat.archived ? (
+ <>
+ <SidebarIconButton
+ tooltip={t("agent.unarchive-chat")}
+ ariaLabel={t("agent.unarchive-chat")}
+ dataAttr="data-agent-unarchive-chat"
+ onClick={() => unarchiveChat(chat.id)}
+ >
+ <Undo2
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </SidebarIconButton>
+ <ConfirmDialog
+ message={t("agent.delete-chat-confirmation")}
+ onConfirm={() => deleteChat(chat.id)}
+ triggerLabel={t("agent.delete-chat")}
+ triggerDataAttr="data-agent-delete-chat"
+ triggerVariant="icon"
+ >
+ <Trash2
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </ConfirmDialog>
+ </>
+ ) : (
+ <SidebarIconButton
+ tooltip={t("agent.archive-chat")}
+ ariaLabel={t("agent.archive-chat")}
+ dataAttr="data-agent-archive-chat"
+ onClick={() => archiveChat(chat.id)}
+ >
+ <Archive
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </SidebarIconButton>
+ )}
</div>
- <span
- className={`mt-1 block truncate text-xs ${
- chat.id === currentChatId
- ? "text-accent/80"
- : "text-control-light"
- }`}
- data-agent-chat-updated-ts
- >
- <HumanizeTs ts={Math.floor(chat.updatedTs / 1000)} />
- </span>
- </button>
+ </div>
)}
</div>
))}
</div>
</div>
-
- {/* Sidebar footer */}
- <div className="border-t border-block-border px-3 py-3">
- <div className="flex flex-col gap-y-2">
- <div
- className="flex flex-wrap gap-x-2 gap-y-2"
- data-agent-chat-sidebar-actions
- >
- {isCurrentChatInDisplayedMode && (
- <>
- {showArchivedOnly ? (
- <button
- className="rounded-xs border px-2 py-1.5 text-xs font-medium text-control-light hover:bg-background"
- data-agent-unarchive-chat
- onClick={toggleArchiveCurrentChat}
- >
- {t("agent.unarchive-chat")}
- </button>
- ) : (
- <ConfirmDialog
- message={t("agent.archive-chat-confirmation")}
- onConfirm={toggleArchiveCurrentChat}
- triggerClassName="rounded-xs border px-2 py-1.5 text-xs font-medium text-control-light hover:bg-background"
- triggerLabel={t("agent.archive-chat")}
- triggerDataAttr="data-agent-archive-chat"
- />
- )}
- {showArchivedOnly && (
- <ConfirmDialog
- message={t("agent.delete-chat-confirmation")}
- onConfirm={deleteCurrentChat}
- triggerClassName="rounded-xs border px-2 py-1.5 text-xs font-medium text-error hover:bg-red-50"
- triggerLabel={t("agent.delete-chat")}
- triggerDataAttr="data-agent-delete-chat"
- />
- )}
- </>
- )}
- <button
- className="ml-auto inline-flex items-center rounded-xs border p-1.5 text-xs font-medium text-control-light hover:bg-background"
- aria-label={
- showArchivedOnly
- ? t("agent.archived-only-chats")
- : t("agent.active-only-chats")
- }
- title={
- showArchivedOnly
- ? t("agent.archived-only-chats")
- : t("agent.active-only-chats")
- }
- data-agent-chat-list-mode
- onClick={toggleChatListMode}
- >
- {showArchivedOnly ? (
- <Archive className="size-3.5" aria-hidden="true" />
- ) : (
- <Inbox className="size-3.5" aria-hidden="true" />
- )}
- </button>
- </div>
- </div>
- </div>
</aside>
{/* Sidebar resize handle */}
@@ -1034,17 +1235,19 @@ export function AgentWindow() {
// --- Confirmation Dialog ---
function ConfirmDialog({
+ children,
message,
onConfirm,
- triggerClassName,
triggerLabel,
triggerDataAttr,
+ triggerVariant = "text",
}: {
+ children?: ReactNode;
message: string;
onConfirm: () => void;
- triggerClassName: string;
triggerLabel: string;
triggerDataAttr?: string;
+ triggerVariant?: "icon" | "text";
}) {
const { t } = useTranslation();
const triggerProps: Record<string, unknown> = {};
@@ -1052,8 +1255,31 @@ function ConfirmDialog({
return (
<Dialog>
- <DialogTrigger className={triggerClassName} {...triggerProps}>
- {triggerLabel}
+ <DialogTrigger
+ render={
+ triggerVariant === "icon" ? (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-control-light hover:bg-background"
+ aria-label={triggerLabel}
+ onClick={(event) => event.stopPropagation()}
+ {...triggerProps}
+ />
+ ) : (
+ <button
+ className="rounded-xs border px-2 py-1.5 text-xs font-medium text-control-light hover:bg-background"
+ onClick={(event) => event.stopPropagation()}
+ {...triggerProps}
+ />
+ )
+ }
+ >
+ {triggerVariant === "icon" ? (
+ <Tooltip content={triggerLabel}>{children}</Tooltip>
+ ) : (
+ triggerLabel
+ )}
</DialogTrigger>
<DialogContent className="max-w-sm p-6">
<DialogTitle className="sr-only">{t("common.confirm")}</DialogTitle>
@@ -1081,3 +1307,40 @@ function ConfirmDialog({
</Dialog>
);
}
+
+type SidebarIconButtonProps = Readonly<{
+ ariaLabel: string;
+ children: ReactNode;
+ dataAttr?: string;
+ onClick: () => void;
+ tooltip: string;
+}>;
+
+function SidebarIconButton({
+ ariaLabel,
+ children,
+ dataAttr,
+ onClick,
+ tooltip,
+}: SidebarIconButtonProps) {
+ const dataProps: Record<string, unknown> = {};
+ if (dataAttr) dataProps[dataAttr] = true;
+
+ return (
+ <Tooltip content={tooltip}>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-control-light hover:bg-background"
+ aria-label={ariaLabel}
+ onClick={(event) => {
+ event.stopPropagation();
+ onClick();
+ }}
+ {...dataProps}
+ >
+ {children}
+ </Button>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/react/plugins/agent/store/agent.test.ts b/frontend/src/react/plugins/agent/store/agent.test.ts
index 73207f8b63..4d7a183dd8 100644
--- a/frontend/src/react/plugins/agent/store/agent.test.ts
+++ b/frontend/src/react/plugins/agent/store/agent.test.ts
@@ -227,6 +227,35 @@ describe("useAgentStore (Zustand)", () => {
});
});
+ test("preserves a cleared current chat across store reloads", () => {
+ localStorage.setItem(
+ AGENT_STATE_KEY,
+ JSON.stringify({
+ currentChatId: null,
+ chats: [
+ {
+ id: "thread-1",
+ title: "Archived thread",
+ createdTs: 10,
+ updatedTs: 20,
+ status: "idle",
+ archived: true,
+ },
+ ],
+ messagesByChatId: {
+ "thread-1": [],
+ },
+ pendingAskByChatId: {},
+ })
+ );
+
+ const store = createAgentStore();
+
+ expect(s(store).chats).toHaveLength(1);
+ expect(s(store).getChat("thread-1")).not.toBeNull();
+ expect(s(store).currentChatId).toBeNull();
+ });
+
test("increments and persists chat token totals", () => {
const store = createAgentStore();
const chatId = s(store).currentChatId!;
@@ -554,6 +583,78 @@ describe("useAgentStore (Zustand)", () => {
expect(s(store).currentChatId).toBe(firstChatId);
});
+ test("archives all active chats and clears the current selection", () => {
+ const store = createAgentStore();
+ const firstChatId = s(store).currentChatId!;
+ const secondChat = s(store).createChat({ title: "Second thread" });
+ const archivedChat = s(store).createChat({
+ title: "Archived thread",
+ archived: true,
+ select: false,
+ });
+
+ expect(s(store).currentChatId).toBe(secondChat.id);
+
+ const archivedCount = s(store).archiveAllActiveChats();
+
+ expect(archivedCount).toBe(2);
+ expect(s(store).getChat(firstChatId)?.archived).toBe(true);
+ expect(s(store).getChat(secondChat.id)?.archived).toBe(true);
+ expect(s(store).getChat(archivedChat.id)?.archived).toBe(true);
+ expect(s(store).currentChatId).toBeNull();
+ });
+
+ test("unarchives all archived chats and clears an archived current selection", () => {
+ const store = createAgentStore();
+ const activeChatId = s(store).currentChatId!;
+ const firstArchivedChat = s(store).createChat({
+ title: "Archived thread",
+ archived: true,
+ select: false,
+ });
+ const secondArchivedChat = s(store).createChat({
+ title: "Another archived thread",
+ archived: true,
+ select: false,
+ });
+
+ s(store).setCurrentChat(firstArchivedChat.id);
+
+ const unarchivedCount = s(store).unarchiveAllArchivedChats();
+
+ expect(unarchivedCount).toBe(2);
+ expect(s(store).getChat(activeChatId)?.archived).toBe(false);
+ expect(s(store).getChat(firstArchivedChat.id)?.archived).toBe(false);
+ expect(s(store).getChat(secondArchivedChat.id)?.archived).toBe(false);
+ expect(s(store).currentChatId).toBeNull();
+ });
+
+ test("deletes all archived chats without creating a replacement chat", () => {
+ const store = createAgentStore();
+ const activeChatId = s(store).currentChatId!;
+ const firstArchivedChat = s(store).createChat({
+ title: "Archived thread",
+ archived: true,
+ select: false,
+ });
+ const secondArchivedChat = s(store).createChat({
+ title: "Another archived thread",
+ archived: true,
+ select: false,
+ });
+
+ s(store).setCurrentChat(firstArchivedChat.id);
+
+ const deletedCount = s(store).deleteAllArchivedChats();
+
+ expect(deletedCount).toBe(2);
+ expect(s(store).getChat(activeChatId)).not.toBeNull();
+ expect(s(store).getChat(firstArchivedChat.id)).toBeNull();
+ expect(s(store).getChat(secondArchivedChat.id)).toBeNull();
+ expect(s(store).chats).toHaveLength(1);
+ expect(s(store).currentChatId).toBeNull();
+ });
+
test("tracks abort controllers per chat and cancels only the requested chat", () => {
const store = createAgentStore();
const firstChatId = s(store).currentChatId!;
diff --git a/frontend/src/react/plugins/agent/store/agent.ts b/frontend/src/react/plugins/agent/store/agent.ts
index 81819d4a70..49702baa6a 100644
--- a/frontend/src/react/plugins/agent/store/agent.ts
+++ b/frontend/src/react/plugins/agent/store/agent.ts
@@ -296,16 +296,26 @@ const normalizePersistedState = (raw: unknown): PersistedAgentState => {
messagesByChatId[chat.id] = messages;
}
- const savedCurrentChatId =
- typeof raw.currentChatId === "string"
- ? raw.currentChatId
- : typeof raw.currentThreadId === "string"
- ? raw.currentThreadId
- : null;
+ const hasCurrentChatId = Object.prototype.hasOwnProperty.call(
+ raw,
+ "currentChatId"
+ );
+ const hasCurrentThreadId = Object.prototype.hasOwnProperty.call(
+ raw,
+ "currentThreadId"
+ );
+ const persistedCurrentChatId = hasCurrentChatId
+ ? raw.currentChatId
+ : hasCurrentThreadId
+ ? raw.currentThreadId
+ : undefined;
const currentChatId =
- savedCurrentChatId && chats.some((chat) => chat.id === savedCurrentChatId)
- ? savedCurrentChatId
- : (chats[0]?.id ?? null);
+ persistedCurrentChatId === null
+ ? null
+ : typeof persistedCurrentChatId === "string" &&
+ chats.some((chat) => chat.id === persistedCurrentChatId)
+ ? persistedCurrentChatId
+ : (chats[0]?.id ?? null);
return {
currentChatId,
@@ -344,11 +354,15 @@ export interface AgentState {
createChat: (options?: CreateChatOptions) => AgentChat;
ensureCurrentChat: (page?: AgentChatSnapshot) => AgentChat;
setCurrentChat: (chatId: string) => void;
+ clearCurrentChat: () => void;
updateChatPage: (chatId: string, page: AgentChatSnapshot) => AgentChat | null;
renameChat: (chatId: string, title: string) => AgentChat | null;
archiveChat: (chatId: string) => AgentChat | null;
+ archiveAllActiveChats: () => number;
unarchiveChat: (chatId: string) => AgentChat | null;
+ unarchiveAllArchivedChats: () => number;
deleteChat: (chatId: string) => boolean;
+ deleteAllArchivedChats: () => number;
// Messages
addMessage: (message: AddMessageOptions) => AgentMessage;
@@ -532,8 +546,9 @@ const loadInitialState = (): {
if (
state &&
- state.currentChatId &&
- state.chats.some((c) => c.id === state!.currentChatId)
+ (state.currentChatId === null
+ ? state.chats.length > 0
+ : state.chats.some((c) => c.id === state.currentChatId))
) {
return state;
}
@@ -727,6 +742,12 @@ export const createAgentStore = () => {
}
},
+ clearCurrentChat: () => {
+ set((state) => {
+ state.currentChatId = null;
+ });
+ },
+
updateChatPage: (chatId, page) => {
if (!_getChat(chatId)) return null;
set((state) => {
@@ -766,6 +787,28 @@ export const createAgentStore = () => {
return _getChat(chatId);
},
+ archiveAllActiveChats: () => {
+ let archivedCount = 0;
+ set((state) => {
+ const activeChats = state.chats.filter((chat) => !chat.archived);
+ archivedCount = activeChats.length;
+ if (archivedCount === 0) return;
+
+ for (const chat of activeChats) {
+ chat.archived = true;
+ _touchChatInDraft(state.chats, chat.id);
+ }
+
+ if (
+ state.currentChatId &&
+ activeChats.some((chat) => chat.id === state.currentChatId)
+ ) {
+ state.currentChatId = null;
+ }
+ });
+ return archivedCount;
+ },
+
unarchiveChat: (chatId) => {
if (!_getChat(chatId)) return null;
set((state) => {
@@ -778,6 +821,28 @@ export const createAgentStore = () => {
return _getChat(chatId);
},
+ unarchiveAllArchivedChats: () => {
+ let unarchivedCount = 0;
+ set((state) => {
+ const archivedChats = state.chats.filter((chat) => chat.archived);
+ unarchivedCount = archivedChats.length;
+ if (unarchivedCount === 0) return;
+
+ for (const chat of archivedChats) {
+ chat.archived = false;
+ _touchChatInDraft(state.chats, chat.id);
+ }
+
+ if (
+ state.currentChatId &&
+ archivedChats.some((chat) => chat.id === state.currentChatId)
+ ) {
+ state.currentChatId = null;
+ }
+ });
+ return unarchivedCount;
+ },
+
deleteChat: (chatId) => {
if (!_getChat(chatId)) return false;
get().cancel(chatId);
@@ -807,6 +872,42 @@ export const createAgentStore = () => {
return true;
},
+ deleteAllArchivedChats: () => {
+ const archivedChatIds = get()
+ .chats.filter((chat) => chat.archived)
+ .map((chat) => chat.id);
+ for (const chatId of archivedChatIds) {
+ get().cancel(chatId);
+ }
+
+ let deletedCount = 0;
+ set((state) => {
+ const archivedChats = state.chats.filter((chat) => chat.archived);
+ deletedCount = archivedChats.length;
+ if (deletedCount === 0) return;
+
+ const deletedChatIds = new Set(
+ archivedChats.map((chat) => chat.id)
+ );
+ for (const chatId of deletedChatIds) {
+ delete state.messagesByChatId[chatId];
+ delete state.pendingAskByChatId[chatId];
+ delete state.abortControllersByChatId[chatId];
+ }
+
+ state.chats = state.chats.filter(
+ (chat) => !deletedChatIds.has(chat.id)
+ );
+ if (
+ state.currentChatId &&
+ deletedChatIds.has(state.currentChatId)
+ ) {
+ state.currentChatId = null;
+ }
+ });
+ return deletedCount;
+ },
+
// Messages
addMessage: (message) => {
const chatId =
@@ -1095,8 +1196,9 @@ export const createAgentStore = () => {
const s = get();
if (
- !s.currentChatId ||
- !s.chats.some((c) => c.id === s.currentChatId)
+ s.chats.length === 0 ||
+ (s.currentChatId !== null &&
+ !s.chats.some((c) => c.id === s.currentChatId))
) {
const chat = createChatRecord();
set((draft) => {