Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(frontend/copilot): add chat search modal behind CHAT_SEARCH flag (#13139)

Abhimanyu Yadav29bc11acc084
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts
index 8b6f0cdd14..36a5e7aef9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts
@@ -231,6 +231,7 @@ describe("useCopilotUIStore", () => {
initialPrompt: null,
sessionToDelete: null,
isDrawerOpen: false,
+ isSearchOpen: false,
completedSessionIDs: new Set<string>(),
isNotificationsEnabled: false,
isSoundEnabled: true,
@@ -287,6 +288,20 @@ describe("useCopilotUIStore", () => {
});
});
+ describe("search", () => {
+ it("starts closed", () => {
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(false);
+ });
+
+ it("opens and closes", () => {
+ useCopilotUIStore.getState().setSearchOpen(true);
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(true);
+
+ useCopilotUIStore.getState().setSearchOpen(false);
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(false);
+ });
+ });
+
describe("completedSessionIDs", () => {
it("starts empty", () => {
expect(useCopilotUIStore.getState().completedSessionIDs.size).toBe(0);
@@ -412,6 +427,7 @@ describe("useCopilotUIStore", () => {
describe("clearCopilotLocalData", () => {
it("resets state and clears localStorage keys", () => {
+ useCopilotUIStore.getState().setSearchOpen(true);
useCopilotUIStore.getState().setCopilotChatMode("fast");
useCopilotUIStore.getState().setCopilotLlmModel("advanced");
useCopilotUIStore.getState().setNotificationsEnabled(true);
@@ -421,6 +437,7 @@ describe("useCopilotUIStore", () => {
useCopilotUIStore.getState().clearCopilotLocalData();
const state = useCopilotUIStore.getState();
+ expect(state.isSearchOpen).toBe(false);
expect(state.copilotChatMode).toBe("extended_thinking");
expect(state.copilotLlmModel).toBe("standard");
expect(state.isNotificationsEnabled).toBe(false);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/ChatSearchModal.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/ChatSearchModal.tsx
new file mode 100644
index 0000000000..0344dd00fa
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/ChatSearchModal.tsx
@@ -0,0 +1,202 @@
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Separator } from "@/components/ui/separator";
+import { cn } from "@/lib/utils";
+import { MagnifyingGlassIcon, XIcon } from "@phosphor-icons/react";
+import { useEffect, useRef } from "react";
+import type { KeyboardEvent } from "react";
+import { useCopilotChatRuntimeStore } from "../../copilotChatRegistry";
+import { useCopilotUIStore } from "../../store";
+import { ChatSearchResults } from "./ChatSearchResults";
+import type { SearchSession } from "./helpers";
+import { useChatSearch } from "./useChatSearch";
+
+interface Props {
+ sessions: SearchSession[];
+ currentSessionId: string | null;
+ onSelectSession: (id: string) => void;
+}
+
+export function ChatSearchModal({
+ sessions,
+ currentSessionId,
+ onSelectSession,
+}: Props) {
+ const inputRef = useRef<HTMLInputElement>(null);
+ const isSearchOpen = useCopilotUIStore((state) => state.isSearchOpen);
+ const setSearchOpen = useCopilotUIStore((state) => state.setSearchOpen);
+ const completedSessionIDs = useCopilotUIStore(
+ (state) => state.completedSessionIDs,
+ );
+ const sessionNeedsReload = useCopilotChatRuntimeStore(
+ (state) => state.sessionNeedsReload,
+ );
+ const {
+ query,
+ debouncedQuery,
+ setQuery,
+ clearQuery,
+ results,
+ highlightedIndex,
+ setHighlightedIndex,
+ highlightedResultRef,
+ moveHighlight,
+ isSearching,
+ } = useChatSearch(sessions, isSearchOpen);
+
+ useEffect(() => {
+ if (!isSearchOpen) return;
+ window.setTimeout(() => inputRef.current?.focus(), 0);
+ }, [isSearchOpen]);
+
+ if (!isSearchOpen) return null;
+
+ function closeSearch() {
+ setSearchOpen(false);
+ }
+
+ function selectHighlightedSession() {
+ const session = results[highlightedIndex];
+ if (!session) return;
+ onSelectSession(session.id);
+ closeSearch();
+ }
+
+ function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ closeSearch();
+ } else if (event.key === "ArrowDown") {
+ event.preventDefault();
+ moveHighlight(1);
+ } else if (event.key === "ArrowUp") {
+ event.preventDefault();
+ moveHighlight(-1);
+ } else if (event.key === "Enter") {
+ event.preventDefault();
+ selectHighlightedSession();
+ }
+ }
+
+ return (
+ <div
+ className="fixed inset-0 z-[80] flex items-start justify-center bg-black/20 px-4 pt-[18vh] backdrop-blur-sm"
+ onMouseDown={closeSearch}
+ >
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="chat-search-title"
+ className="w-full max-w-xl overflow-hidden rounded-3xl bg-white shadow-2xl ring-1 ring-zinc-200"
+ onMouseDown={(event) => event.stopPropagation()}
+ onKeyDown={handleKeyDown}
+ >
+ <div className="flex items-center gap-3 bg-zinc-50 p-3">
+ <MagnifyingGlassIcon className="h-5 w-5 shrink-0 text-zinc-800" />
+ <Input
+ ref={inputRef}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder="Search chats..."
+ aria-label="Search chats"
+ aria-controls="chat-search-results"
+ aria-activedescendant={
+ results[highlightedIndex]
+ ? `chat-search-result-${results[highlightedIndex].id}`
+ : undefined
+ }
+ autoComplete="off"
+ className="h-9 border-0 bg-transparent px-0 text-base text-zinc-950 shadow-none placeholder:text-zinc-700 focus-visible:ring-0"
+ />
+ {query ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Clear search"
+ onClick={clearQuery}
+ className="shrink-0"
+ >
+ <XIcon className="h-4 w-4" />
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ variant="outline"
+ size="icon-sm"
+ aria-label="Close search"
+ onClick={closeSearch}
+ className="shrink-0 rounded-full border-zinc-400"
+ >
+ <XIcon className="h-4 w-4" />
+ </Button>
+ </div>
+ <Separator />
+ <div className="py-2">
+ <div
+ id="chat-search-title"
+ className="px-4 pb-2 text-[11px] font-semibold uppercase tracking-wide text-zinc-700"
+ >
+ {isSearching ? "Results" : "Recent chats"}
+ </div>
+ <div
+ id="chat-search-results"
+ className={cn(
+ "max-h-[22rem] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-zinc-200",
+ results.length === 0 && "max-h-none",
+ )}
+ >
+ {results.length > 0 ? (
+ <div className="px-2">
+ <ChatSearchResults
+ results={results}
+ query={debouncedQuery}
+ highlightedIndex={highlightedIndex}
+ highlightedResultRef={highlightedResultRef}
+ currentSessionId={currentSessionId}
+ completedSessionIDs={completedSessionIDs}
+ sessionNeedsReload={sessionNeedsReload}
+ onHighlight={setHighlightedIndex}
+ onSelect={(id) => {
+ onSelectSession(id);
+ closeSearch();
+ }}
+ />
+ </div>
+ ) : (
+ <div className="px-3 py-8 text-center text-sm text-zinc-500">
+ No chats found
+ </div>
+ )}
+ </div>
+ </div>
+ <Separator />
+ <div className="flex items-center justify-between gap-4 bg-zinc-50 px-4 py-4 text-xs text-zinc-700">
+ <div className="flex items-center gap-4">
+ <div className="flex items-center gap-1.5">
+ <kbd className="inline-flex h-5 w-5 items-center justify-center rounded-md border border-zinc-200 bg-white font-sans text-[11px] text-zinc-800 shadow-[inset_0_-1px_0_rgba(15,15,20,0.04),0_1px_1px_rgba(15,15,20,0.04)]">
+ ↑
+ </kbd>
+ <kbd className="inline-flex h-5 w-5 items-center justify-center rounded-md border border-zinc-200 bg-white font-sans text-[11px] text-zinc-800 shadow-[inset_0_-1px_0_rgba(15,15,20,0.04),0_1px_1px_rgba(15,15,20,0.04)]">
+ ↓
+ </kbd>
+ <span>Navigate</span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <kbd className="inline-flex h-5 min-w-5 items-center justify-center rounded-md border border-zinc-200 bg-white px-1 font-sans text-[11px] text-zinc-800 shadow-[inset_0_-1px_0_rgba(15,15,20,0.04),0_1px_1px_rgba(15,15,20,0.04)]">
+ ↵
+ </kbd>
+ <span>Select</span>
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <kbd className="inline-flex h-5 items-center justify-center rounded-md border border-zinc-200 bg-white px-1.5 font-sans text-[11px] text-zinc-800 shadow-[inset_0_-1px_0_rgba(15,15,20,0.04),0_1px_1px_rgba(15,15,20,0.04)]">
+ esc
+ </kbd>
+ <span>Close</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/ChatSearchResults.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/ChatSearchResults.tsx
new file mode 100644
index 0000000000..3e0e50d209
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/ChatSearchResults.tsx
@@ -0,0 +1,184 @@
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import {
+ ChatCircleIcon,
+ CheckCircleIcon,
+ CircleNotchIcon,
+ HourglassIcon,
+} from "@phosphor-icons/react";
+import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
+import type { MutableRefObject } from "react";
+import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";
+import { getSessionTitle, highlightMatch, type SearchSession } from "./helpers";
+
+const indicatorTransition = {
+ type: "spring" as const,
+ damping: 30,
+ stiffness: 520,
+ mass: 0.8,
+};
+
+interface Props {
+ results: SearchSession[];
+ query: string;
+ highlightedIndex: number;
+ highlightedResultRef: MutableRefObject<HTMLButtonElement | null>;
+ currentSessionId: string | null;
+ completedSessionIDs: Set<string>;
+ sessionNeedsReload: Record<string, boolean>;
+ onHighlight: (index: number) => void;
+ onSelect: (id: string) => void;
+}
+
+export function ChatSearchResults({
+ results,
+ query,
+ highlightedIndex,
+ highlightedResultRef,
+ currentSessionId,
+ completedSessionIDs,
+ sessionNeedsReload,
+ onHighlight,
+ onSelect,
+}: Props) {
+ const reduceMotion = useReducedMotion();
+ return (
+ <div role="listbox" aria-label="Chat sessions" className="flex flex-col">
+ {results.map((session, index) => {
+ const isHighlighted = index === highlightedIndex;
+ const title = getSessionTitle(session);
+
+ return (
+ <Button
+ key={session.id}
+ ref={isHighlighted ? highlightedResultRef : undefined}
+ id={`chat-search-result-${session.id}`}
+ type="button"
+ variant="ghost"
+ role="option"
+ aria-selected={isHighlighted}
+ onMouseEnter={() => onHighlight(index)}
+ onClick={() => onSelect(session.id)}
+ className={cn(
+ "relative h-auto w-full justify-start rounded-md px-3 py-2 text-left hover:bg-transparent",
+ )}
+ >
+ {isHighlighted && (
+ <>
+ <motion.div
+ layoutId="chat-search-highlight"
+ aria-hidden="true"
+ className="absolute inset-0 z-0 rounded-md bg-zinc-100"
+ transition={
+ reduceMotion ? { duration: 0 } : indicatorTransition
+ }
+ />
+ <motion.div
+ layoutId="chat-search-highlight-bar"
+ aria-hidden="true"
+ className="absolute inset-y-0 left-0 z-[1] my-auto h-5 w-[3px] rounded-full bg-zinc-900"
+ transition={
+ reduceMotion ? { duration: 0 } : indicatorTransition
+ }
+ />
+ </>
+ )}
+ <div className="relative z-10 flex min-w-0 flex-1 items-center gap-2.5">
+ <ChatCircleIcon
+ aria-hidden="true"
+ className={cn(
+ "h-4 w-4 shrink-0 transition-colors duration-150",
+ isHighlighted ? "text-zinc-900" : "text-zinc-500",
+ )}
+ />
+ <div className="min-w-0 flex-1">
+ <div
+ className={cn(
+ "truncate text-sm font-normal transition-colors duration-150",
+ isHighlighted ? "text-zinc-950" : "text-zinc-800",
+ session.id === currentSessionId && "text-zinc-600",
+ )}
+ >
+ {highlightMatch(title, query).map((part, partIndex) => (
+ <span
+ key={`${part.text}-${partIndex}`}
+ className={part.isMatch ? "font-semibold" : undefined}
+ >
+ {part.text}
+ </span>
+ ))}
+ </div>
+ </div>
+ {session.chat_status === "running" && (
+ <span
+ aria-label="Session running"
+ className="inline-flex h-4 w-4 shrink-0 items-center justify-center"
+ >
+ <span className="h-2 w-2 animate-pulse rounded-full bg-emerald-500" />
+ </span>
+ )}
+ {session.chat_status === "queued" && (
+ <span
+ aria-label="Session queued"
+ className="inline-flex h-4 w-4 shrink-0 items-center justify-center text-purple-600"
+ >
+ <HourglassIcon className="h-3.5 w-3.5" weight="bold" />
+ </span>
+ )}
+ {session.chat_status !== "running" &&
+ session.is_processing &&
+ shouldShowSessionProcessingIndicator({
+ sessionId: session.id,
+ currentSessionId,
+ isProcessing: session.is_processing,
+ hasCompletedIndicator: completedSessionIDs.has(session.id),
+ needsReload: !!sessionNeedsReload[session.id],
+ }) && (
+ <CircleNotchIcon
+ aria-label="Session processing"
+ className="h-4 w-4 shrink-0 animate-spin text-zinc-400"
+ weight="bold"
+ />
+ )}
+ {completedSessionIDs.has(session.id) &&
+ session.id !== currentSessionId && (
+ <CheckCircleIcon
+ aria-label="Session completed"
+ className="h-4 w-4 shrink-0 text-green-500"
+ weight="fill"
+ />
+ )}
+ <AnimatePresence initial={false}>
+ {isHighlighted && (
+ <motion.span
+ aria-hidden="true"
+ initial={
+ reduceMotion
+ ? { opacity: 0 }
+ : { opacity: 0, scale: 0.95, x: 80 }
+ }
+ animate={
+ reduceMotion
+ ? { opacity: 1 }
+ : { opacity: 1, scale: 1, x: 0 }
+ }
+ exit={
+ reduceMotion
+ ? { opacity: 0 }
+ : { opacity: 0, scale: 0.95, x: 80 }
+ }
+ transition={{ duration: 0.26, ease: [0.22, 1, 0.36, 1] }}
+ style={{ willChange: "transform, opacity" }}
+ className="inline-flex h-5 min-w-5 shrink-0 items-center justify-center rounded-md border border-zinc-200 bg-white px-1 font-sans text-[11px] text-zinc-600 shadow-[inset_0_-1px_0_rgba(15,15,20,0.04),0_1px_1px_rgba(15,15,20,0.04)]"
+ >
+ ↵
+ </motion.span>
+ )}
+ </AnimatePresence>
+ </div>
+ </Button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/__tests__/ChatSearchModal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/__tests__/ChatSearchModal.test.tsx
new file mode 100644
index 0000000000..6e72b33732
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/__tests__/ChatSearchModal.test.tsx
@@ -0,0 +1,295 @@
+import {
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@/tests/integrations/test-utils";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useCopilotChatRuntimeStore } from "../../../copilotChatRegistry";
+import { useCopilotUIStore } from "../../../store";
+import { ChatSearchModal } from "../ChatSearchModal";
+import type { SearchSession } from "../helpers";
+
+function makeSession(
+ overrides: Partial<SearchSession> & { id: string },
+): SearchSession {
+ return {
+ title: `Session ${overrides.id}`,
+ updated_at: "2025-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function renderModal(props: {
+ sessions?: SearchSession[];
+ currentSessionId?: string | null;
+ onSelectSession?: (id: string) => void;
+}) {
+ const onSelectSession = props.onSelectSession ?? vi.fn();
+ return {
+ onSelectSession,
+ ...render(
+ <ChatSearchModal
+ sessions={props.sessions ?? []}
+ currentSessionId={props.currentSessionId ?? null}
+ onSelectSession={onSelectSession}
+ />,
+ ),
+ };
+}
+
+describe("ChatSearchModal", () => {
+ beforeEach(() => {
+ useCopilotUIStore.setState({
+ isSearchOpen: true,
+ completedSessionIDs: new Set<string>(),
+ });
+ useCopilotChatRuntimeStore.setState({ sessionNeedsReload: {} });
+ });
+
+ afterEach(() => {
+ useCopilotUIStore.setState({ isSearchOpen: false });
+ });
+
+ it("returns null when the search modal is closed", () => {
+ useCopilotUIStore.setState({ isSearchOpen: false });
+ renderModal({ sessions: [makeSession({ id: "a" })] });
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ it("auto-focuses the input when opened", async () => {
+ renderModal({ sessions: [makeSession({ id: "a", title: "Alpha" })] });
+ const input = await screen.findByRole("textbox", { name: /search chats/i });
+ await vi.waitFor(() => expect(document.activeElement).toBe(input));
+ });
+
+ it("shows 'No chats found' when query has no matches and hides the clear button when empty", async () => {
+ const user = userEvent.setup();
+ renderModal({ sessions: [makeSession({ id: "a", title: "Alpha" })] });
+
+ expect(screen.queryByRole("button", { name: /clear search/i })).toBeNull();
+
+ const input = screen.getByRole("textbox", { name: /search chats/i });
+ await user.type(input, "zzz");
+ expect(await screen.findByText("No chats found")).toBeDefined();
+ expect(screen.getByRole("button", { name: /clear search/i })).toBeDefined();
+ });
+
+ it("closes when the backdrop is clicked but not when the dialog body is clicked", async () => {
+ renderModal({ sessions: [makeSession({ id: "a" })] });
+ const dialog = await screen.findByRole("dialog");
+
+ fireEvent.mouseDown(dialog);
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(true);
+
+ const backdrop = dialog.parentElement!;
+ fireEvent.mouseDown(backdrop);
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(false);
+ });
+
+ it("closes when the close button is clicked", async () => {
+ renderModal({ sessions: [makeSession({ id: "a" })] });
+ fireEvent.click(
+ await screen.findByRole("button", { name: /close search/i }),
+ );
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(false);
+ });
+
+ it("closes on Escape", async () => {
+ renderModal({ sessions: [makeSession({ id: "a" })] });
+ const dialog = await screen.findByRole("dialog");
+ fireEvent.keyDown(dialog, { key: "Escape" });
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(false);
+ });
+
+ it("navigates with ArrowDown/ArrowUp, clamps at the bounds, and selects via Enter", async () => {
+ const onSelect = vi.fn();
+ const sessions = [
+ makeSession({
+ id: "a",
+ title: "Alpha",
+ updated_at: "2025-01-03T00:00:00Z",
+ }),
+ makeSession({
+ id: "b",
+ title: "Beta",
+ updated_at: "2025-01-02T00:00:00Z",
+ }),
+ makeSession({
+ id: "c",
+ title: "Gamma",
+ updated_at: "2025-01-01T00:00:00Z",
+ }),
+ ];
+ renderModal({ sessions, onSelectSession: onSelect });
+
+ const dialog = await screen.findByRole("dialog");
+ const options = within(dialog).getAllByRole("option");
+ expect(options[0].getAttribute("aria-selected")).toBe("true");
+
+ fireEvent.keyDown(dialog, { key: "ArrowUp" });
+ expect(
+ within(dialog).getAllByRole("option")[0].getAttribute("aria-selected"),
+ ).toBe("true");
+
+ fireEvent.keyDown(dialog, { key: "ArrowDown" });
+ expect(
+ within(dialog).getAllByRole("option")[1].getAttribute("aria-selected"),
+ ).toBe("true");
+
+ fireEvent.keyDown(dialog, { key: "ArrowDown" });
+ fireEvent.keyDown(dialog, { key: "ArrowDown" });
+ fireEvent.keyDown(dialog, { key: "ArrowDown" });
+ expect(
+ within(dialog).getAllByRole("option")[2].getAttribute("aria-selected"),
+ ).toBe("true");
+
+ fireEvent.keyDown(dialog, { key: "Enter" });
+ expect(onSelect).toHaveBeenCalledWith("c");
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(false);
+ });
+
+ it("Enter is a no-op when there are no results", async () => {
+ const onSelect = vi.fn();
+ renderModal({
+ sessions: [makeSession({ id: "a", title: "Alpha" })],
+ onSelectSession: onSelect,
+ });
+ const user = userEvent.setup();
+ const dialog = await screen.findByRole("dialog");
+ await user.type(
+ screen.getByRole("textbox", { name: /search chats/i }),
+ "nope",
+ );
+ await screen.findByText("No chats found");
+ fireEvent.keyDown(dialog, { key: "Enter" });
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(true);
+ });
+
+ it("highlights a session on hover and selects it on click", async () => {
+ const onSelect = vi.fn();
+ renderModal({
+ sessions: [
+ makeSession({
+ id: "a",
+ title: "Alpha",
+ updated_at: "2025-01-02T00:00:00Z",
+ }),
+ makeSession({
+ id: "b",
+ title: "Beta",
+ updated_at: "2025-01-01T00:00:00Z",
+ }),
+ ],
+ onSelectSession: onSelect,
+ });
+ const dialog = await screen.findByRole("dialog");
+ const betaOption = within(dialog).getByRole("option", { name: /beta/i });
+ fireEvent.mouseEnter(betaOption);
+ expect(betaOption.getAttribute("aria-selected")).toBe("true");
+
+ fireEvent.click(betaOption);
+ expect(onSelect).toHaveBeenCalledWith("b");
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(false);
+ });
+
+ it("clears the query when the clear button is clicked", async () => {
+ const user = userEvent.setup();
+ renderModal({ sessions: [makeSession({ id: "a", title: "Alpha" })] });
+ const input = screen.getByRole("textbox", { name: /search chats/i });
+ await user.type(input, "alp");
+ expect(await screen.findByText("Results")).toBeDefined();
+
+ fireEvent.click(screen.getByRole("button", { name: /clear search/i }));
+ expect((input as HTMLInputElement).value).toBe("");
+ expect(await screen.findByText("Recent chats")).toBeDefined();
+ });
+
+ it("renders running, queued, processing, and completed indicators", async () => {
+ useCopilotUIStore.setState({
+ isSearchOpen: true,
+ completedSessionIDs: new Set<string>(["done"]),
+ });
+ useCopilotChatRuntimeStore.setState({
+ sessionNeedsReload: { processing: false },
+ });
+
+ renderModal({
+ currentSessionId: "current",
+ sessions: [
+ makeSession({
+ id: "running",
+ title: "Running chat",
+ chat_status: "running",
+ updated_at: "2025-01-05T00:00:00Z",
+ }),
+ makeSession({
+ id: "queued",
+ title: "Queued chat",
+ chat_status: "queued",
+ updated_at: "2025-01-04T00:00:00Z",
+ }),
+ makeSession({
+ id: "processing",
+ title: "Processing chat",
+ is_processing: true,
+ updated_at: "2025-01-03T00:00:00Z",
+ }),
+ makeSession({
+ id: "done",
+ title: "Done chat",
+ updated_at: "2025-01-02T00:00:00Z",
+ }),
+ makeSession({
+ id: "current",
+ title: "Current chat",
+ updated_at: "2025-01-01T00:00:00Z",
+ }),
+ ],
+ });
+
+ expect(await screen.findByLabelText("Session running")).toBeDefined();
+ expect(screen.getByLabelText("Session queued")).toBeDefined();
+ expect(screen.getByLabelText("Session processing")).toBeDefined();
+ expect(screen.getByLabelText("Session completed")).toBeDefined();
+ });
+
+ it("hides the processing indicator when needsReload is set for that session", async () => {
+ useCopilotChatRuntimeStore.setState({
+ sessionNeedsReload: { stale: true },
+ });
+ renderModal({
+ sessions: [
+ makeSession({
+ id: "stale",
+ title: "Stale chat",
+ is_processing: true,
+ }),
+ ],
+ });
+ await screen.findByText("Stale chat");
+ expect(screen.queryByLabelText("Session processing")).toBeNull();
+ });
+
+ it("falls back to 'Untitled chat' when the session has no title", async () => {
+ renderModal({ sessions: [makeSession({ id: "a", title: null })] });
+ expect(await screen.findByText("Untitled chat")).toBeDefined();
+ });
+
+ it("debounces query changes and bolds the matched substring", async () => {
+ const user = userEvent.setup();
+ renderModal({
+ sessions: [makeSession({ id: "a", title: "Revenue forecast" })],
+ });
+ const input = screen.getByRole("textbox", { name: /search chats/i });
+ await user.type(input, "fore");
+
+ const option = await screen.findByRole("option", {
+ name: /revenue forecast/i,
+ });
+ const bold = await within(option).findByText("fore");
+ expect(bold.className).toContain("font-semibold");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..b566993b15
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/__tests__/helpers.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from "vitest";
+import {
+ filterSessions,
+ formatRelativeDate,
+ highlightMatch,
+ type SearchSession,
+} from "../helpers";
+
+const sessions: SearchSession[] = [
+ {
+ id: "older",
+ title: "Weekly update",
+ updated_at: "2025-01-01T00:00:00Z",
+ },
+ {
+ id: "newer",
+ title: "Revenue forecast",
+ updated_at: "2025-01-03T00:00:00Z",
+ },
+ {
+ id: "middle",
+ title: "Forecast follow-up",
+ updated_at: "2025-01-02T00:00:00Z",
+ },
+];
+
+describe("filterSessions", () => {
+ it("returns recent sessions sorted newest first for an empty query", () => {
+ expect(filterSessions(sessions, "").map((session) => session.id)).toEqual([
+ "newer",
+ "middle",
+ "older",
+ ]);
+ });
+
+ it("filters titles case-insensitively and keeps newest first", () => {
+ expect(
+ filterSessions(sessions, "FORECAST").map((session) => session.id),
+ ).toEqual(["newer", "middle"]);
+ });
+
+ it("limits active search results to 20 sessions", () => {
+ const manySessions = Array.from({ length: 25 }, (_, index) => ({
+ id: String(index),
+ title: `Searchable ${index}`,
+ updated_at: `2025-01-${String(index + 1).padStart(2, "0")}T00:00:00Z`,
+ }));
+
+ expect(filterSessions(manySessions, "searchable")).toHaveLength(20);
+ });
+});
+
+describe("highlightMatch", () => {
+ it("marks the matched title substring", () => {
+ expect(highlightMatch("Revenue forecast", "fore")).toEqual([
+ { text: "Revenue ", isMatch: false },
+ { text: "fore", isMatch: true },
+ { text: "cast", isMatch: false },
+ ]);
+ });
+
+ it("returns plain text when there is no query", () => {
+ expect(highlightMatch("Revenue forecast", "")).toEqual([
+ { text: "Revenue forecast", isMatch: false },
+ ]);
+ });
+});
+
+describe("formatRelativeDate", () => {
+ const baseDate = new Date("2025-01-10T12:00:00Z");
+
+ it("formats recent days", () => {
+ expect(formatRelativeDate("2025-01-10T00:00:00Z", baseDate)).toBe("Today");
+ expect(formatRelativeDate("2025-01-09T00:00:00Z", baseDate)).toBe(
+ "Yesterday",
+ );
+ expect(formatRelativeDate("2025-01-07T00:00:00Z", baseDate)).toBe(
+ "3 days ago",
+ );
+ });
+
+ it("formats older dates", () => {
+ expect(formatRelativeDate("2025-01-01T00:00:00Z", baseDate)).toBe(
+ "1st Jan 2025",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/helpers.ts
new file mode 100644
index 0000000000..a6c042eec1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/helpers.ts
@@ -0,0 +1,89 @@
+export interface SearchSession {
+ id: string;
+ title?: string | null;
+ updated_at: string;
+ is_processing?: boolean;
+ chat_status?: string | null;
+}
+
+export interface HighlightPart {
+ text: string;
+ isMatch: boolean;
+}
+
+const EMPTY_QUERY_LIMIT = 10;
+const ACTIVE_QUERY_LIMIT = 20;
+
+function getSessionTimestamp(session: SearchSession) {
+ const timestamp = new Date(session.updated_at).getTime();
+ return Number.isNaN(timestamp) ? 0 : timestamp;
+}
+
+function getTitle(session: SearchSession) {
+ return session.title || "Untitled chat";
+}
+
+export function filterSessions(
+ sessions: SearchSession[],
+ query: string,
+): SearchSession[] {
+ const normalizedQuery = query.trim().toLocaleLowerCase();
+ const sortedSessions = [...sessions].sort(
+ (a, b) => getSessionTimestamp(b) - getSessionTimestamp(a),
+ );
+
+ if (!normalizedQuery) {
+ return sortedSessions.slice(0, EMPTY_QUERY_LIMIT);
+ }
+
+ return sortedSessions
+ .filter((session) =>
+ getTitle(session).toLocaleLowerCase().includes(normalizedQuery),
+ )
+ .slice(0, ACTIVE_QUERY_LIMIT);
+}
+
+export function highlightMatch(title: string, query: string): HighlightPart[] {
+ const normalizedQuery = query.trim().toLocaleLowerCase();
+ if (!normalizedQuery) return [{ text: title, isMatch: false }];
+
+ const matchIndex = title.toLocaleLowerCase().indexOf(normalizedQuery);
+ if (matchIndex === -1) return [{ text: title, isMatch: false }];
+
+ const matchEnd = matchIndex + normalizedQuery.length;
+ return [
+ { text: title.slice(0, matchIndex), isMatch: false },
+ { text: title.slice(matchIndex, matchEnd), isMatch: true },
+ { text: title.slice(matchEnd), isMatch: false },
+ ].filter((part) => part.text.length > 0);
+}
+
+export function formatRelativeDate(dateString: string, baseDate = new Date()) {
+ const date = new Date(dateString);
+ if (Number.isNaN(date.getTime())) return "";
+
+ const diffMs = baseDate.getTime() - date.getTime();
+ const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
+
+ if (diffDays <= 0) return "Today";
+ if (diffDays === 1) return "Yesterday";
+ if (diffDays < 7) return `${diffDays} days ago`;
+
+ const day = date.getDate();
+ const ordinal =
+ day % 10 === 1 && day !== 11
+ ? "st"
+ : day % 10 === 2 && day !== 12
+ ? "nd"
+ : day % 10 === 3 && day !== 13
+ ? "rd"
+ : "th";
+ const month = date.toLocaleDateString("en-US", { month: "short" });
+ const year = date.getFullYear();
+
+ return `${day}${ordinal} ${month} ${year}`;
+}
+
+export function getSessionTitle(session: SearchSession) {
+ return getTitle(session);
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/useChatSearch.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/useChatSearch.ts
new file mode 100644
index 0000000000..087bc3d18b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSearchModal/useChatSearch.ts
@@ -0,0 +1,74 @@
+import { useEffect, useRef, useState } from "react";
+import { filterSessions, type SearchSession } from "./helpers";
+
+const DEBOUNCE_MS = 150;
+
+export function useChatSearch(sessions: SearchSession[], isOpen: boolean) {
+ const [query, setQuery] = useState("");
+ const [debouncedQuery, setDebouncedQuery] = useState("");
+ const [highlightedIndex, setHighlightedIndex] = useState(0);
+ const highlightedResultRef = useRef<HTMLButtonElement | null>(null);
+
+ useEffect(() => {
+ if (!isOpen) {
+ setQuery("");
+ setDebouncedQuery("");
+ setHighlightedIndex(0);
+ }
+ }, [isOpen]);
+
+ useEffect(() => {
+ const timeout = window.setTimeout(() => {
+ setDebouncedQuery(query);
+ }, DEBOUNCE_MS);
+
+ return () => window.clearTimeout(timeout);
+ }, [query]);
+
+ const results = filterSessions(sessions, debouncedQuery);
+
+ useEffect(() => {
+ setHighlightedIndex(0);
+ }, [debouncedQuery, sessions.length]);
+
+ useEffect(() => {
+ if (highlightedIndex >= results.length) {
+ setHighlightedIndex(Math.max(0, results.length - 1));
+ }
+ }, [highlightedIndex, results.length]);
+
+ useEffect(() => {
+ highlightedResultRef.current?.scrollIntoView({
+ block: "nearest",
+ });
+ }, [highlightedIndex]);
+
+ function moveHighlight(direction: 1 | -1) {
+ if (results.length === 0) return;
+ setHighlightedIndex((current) => {
+ const next = current + direction;
+ if (next < 0 || next >= results.length) return current;
+ return next;
+ });
+ }
+
+ function clearQuery() {
+ setQuery("");
+ setDebouncedQuery("");
+ }
+
+ const isSearching = debouncedQuery.trim().length > 0;
+
+ return {
+ query,
+ debouncedQuery,
+ setQuery,
+ clearQuery,
+ results,
+ highlightedIndex,
+ setHighlightedIndex,
+ highlightedResultRef,
+ moveHighlight,
+ isSearching,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
index 38f3cdd9de..ad7ef02a65 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
@@ -8,6 +8,7 @@ import {
import { Button } from "@/components/atoms/Button/Button";
import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
import { Text } from "@/components/atoms/Text/Text";
+import { Button as ShadcnButton } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
@@ -23,12 +24,14 @@ import {
useSidebar,
} from "@/components/ui/sidebar";
import { cn } from "@/lib/utils";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import {
CheckCircle,
CircleNotch,
DownloadSimpleIcon,
DotsThree,
HourglassIcon,
+ MagnifyingGlassIcon,
PencilSimpleIcon,
PlusCircleIcon,
PlusIcon,
@@ -45,6 +48,7 @@ import { useCopilotUIStore } from "../../store";
import { useSessionDeletion } from "../../useSessionDeletion";
import { NotificationToggle } from "./components/NotificationToggle/NotificationToggle";
import { fetchAndExportChat } from "../../helpers/exportChatAsMarkdown";
+import { ChatSearchModal } from "../ChatSearchModal/ChatSearchModal";
import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";
import { UsagePopover } from "../UsageLimits/UsagePopover/UsagePopover";
@@ -52,7 +56,9 @@ export function ChatSidebar() {
const { state } = useSidebar();
const isCollapsed = state === "collapsed";
const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);
- const { completedSessionIDs, clearCompletedSession } = useCopilotUIStore();
+ const { completedSessionIDs, clearCompletedSession, setSearchOpen } =
+ useCopilotUIStore();
+ const isChatSearchEnabled = useGetFlag(Flag.CHAT_SEARCH);
const sessionNeedsReload = useCopilotChatRuntimeStore(
(state) => state.sessionNeedsReload,
);
@@ -121,6 +127,20 @@ export function ChatSidebar() {
document.title = formatNotificationTitle(remaining);
}, [sessionId, completedSessionIDs, clearCompletedSession]);
+ useEffect(() => {
+ if (!isChatSearchEnabled) return;
+ function handleSearchShortcut(event: KeyboardEvent) {
+ if (event.repeat) return;
+ if (event.key.toLocaleLowerCase() !== "k") return;
+ if (!event.metaKey && !event.ctrlKey) return;
+ event.preventDefault();
+ setSearchOpen(!useCopilotUIStore.getState().isSearchOpen);
+ }
+
+ document.addEventListener("keydown", handleSearchShortcut);
+ return () => document.removeEventListener("keydown", handleSearchShortcut);
+ }, [isChatSearchEnabled, setSearchOpen]);
+
const sessions =
sessionsResponse?.status === 200 ? sessionsResponse.data.sessions : [];
@@ -130,6 +150,7 @@ export function ChatSidebar() {
function handleSelectSession(id: string) {
setSessionId(id);
+ setSearchOpen(false);
}
function handleRenameClick(
@@ -251,6 +272,18 @@ export function ChatSidebar() {
<span className="sr-only">New Chat</span>
</Button>
) : null}
+ {isChatSearchEnabled ? (
+ <ShadcnButton
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Search chats"
+ onClick={() => setSearchOpen(true)}
+ className="rounded-full text-zinc-600 hover:bg-zinc-100"
+ >
+ <MagnifyingGlassIcon className="!size-5" />
+ </ShadcnButton>
+ ) : null}
</div>
</motion.div>
</SidebarHeader>
@@ -268,6 +301,18 @@ export function ChatSidebar() {
Your chats
</Text>
<div className="flex items-center">
+ {isChatSearchEnabled ? (
+ <ShadcnButton
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Search chats"
+ onClick={() => setSearchOpen(true)}
+ className="rounded-full text-zinc-600 hover:bg-zinc-100"
+ >
+ <MagnifyingGlassIcon className="!size-5" />
+ </ShadcnButton>
+ ) : null}
<UsagePopover />
<NotificationToggle />
<SidebarTrigger />
@@ -509,6 +554,13 @@ export function ChatSidebar() {
onConfirm={confirmDelete}
onCancel={cancelDelete}
/>
+ {isChatSearchEnabled ? (
+ <ChatSearchModal
+ sessions={sessions}
+ currentSessionId={sessionId}
+ onSelectSession={handleSelectSession}
+ />
+ ) : null}
</>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx
index 4ab228a35c..3df51f3637 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx
@@ -11,6 +11,7 @@ import {
within,
} from "@/tests/integrations/test-utils";
import { SidebarProvider } from "@/components/ui/sidebar";
+import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useCopilotUIStore } from "../../../store";
import { ChatSidebar } from "../ChatSidebar";
@@ -27,9 +28,23 @@ vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
};
});
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useGetFlag: (flag: string) => flag === "chat-search",
+ };
+});
+
vi.mock("../../UsageLimits/UsageLimits", () => ({
UsageLimits: () => null,
}));
+vi.mock("../../UsageLimits/UsagePopover/UsagePopover", () => ({
+ UsagePopover: () => null,
+}));
vi.mock("../components/NotificationToggle/NotificationToggle", () => ({
NotificationToggle: () => null,
}));
@@ -75,7 +90,7 @@ async function openDeleteDialogFor(title: string) {
describe("ChatSidebar — delete flow", () => {
beforeEach(() => {
toastMock.mockClear();
- useCopilotUIStore.setState({ sessionToDelete: null });
+ useCopilotUIStore.setState({ sessionToDelete: null, isSearchOpen: false });
server.use(
getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),
);
@@ -157,6 +172,122 @@ describe("ChatSidebar — delete flow", () => {
});
});
+describe("ChatSidebar — search modal", () => {
+ beforeEach(() => {
+ useCopilotUIStore.setState({ isSearchOpen: false });
+ server.use(
+ getGetV2ListSessionsMockHandler200({
+ sessions: [
+ {
+ id: "older",
+ title: "Budget notes",
+ is_processing: false,
+ created_at: "2025-01-01T00:00:00Z",
+ updated_at: "2025-01-01T00:00:00Z",
+ },
+ {
+ id: "newer",
+ title: "Revenue forecast",
+ is_processing: false,
+ created_at: "2025-01-03T00:00:00Z",
+ updated_at: "2025-01-03T00:00:00Z",
+ },
+ {
+ id: "middle",
+ title: "Forecast follow-up",
+ is_processing: false,
+ created_at: "2025-01-02T00:00:00Z",
+ updated_at: "2025-01-02T00:00:00Z",
+ },
+ ],
+ total: 3,
+ }),
+ );
+ });
+
+ it("opens with the search button, focuses the input, and shows recent chats", async () => {
+ const user = userEvent.setup();
+ renderSidebar();
+
+ await user.click(
+ await screen.findByRole("button", { name: /search chats/i }),
+ );
+
+ const dialog = await screen.findByRole("dialog");
+ const input = screen.getByRole("textbox", { name: /search chats/i });
+ await vi.waitFor(() => expect(document.activeElement).toBe(input));
+ expect(within(dialog).getByText("Recent chats")).toBeDefined();
+ expect(within(dialog).getByText("Revenue forecast")).toBeDefined();
+ });
+
+ it("filters results, shows empty copy, and clears the query", async () => {
+ const user = userEvent.setup();
+ renderSidebar();
+
+ await user.click(
+ await screen.findByRole("button", { name: /search chats/i }),
+ );
+ await user.type(
+ screen.getByRole("textbox", { name: /search chats/i }),
+ "forecast",
+ );
+
+ await screen.findByText("Results");
+ const dialog = screen.getByRole("dialog");
+ expect(
+ within(dialog).getByRole("option", { name: /revenue forecast/i }),
+ ).toBeDefined();
+ expect(
+ within(dialog).getByRole("option", { name: /forecast follow-up/i }),
+ ).toBeDefined();
+ expect(
+ within(dialog).queryByRole("option", { name: /budget notes/i }),
+ ).toBeNull();
+
+ await user.clear(screen.getByRole("textbox", { name: /search chats/i }));
+ await user.type(
+ screen.getByRole("textbox", { name: /search chats/i }),
+ "missing",
+ );
+ expect(await screen.findByText("No chats found")).toBeDefined();
+
+ await user.click(screen.getByRole("button", { name: /clear search/i }));
+ expect(
+ (
+ screen.getByRole("textbox", {
+ name: /search chats/i,
+ }) as HTMLInputElement
+ ).value,
+ ).toBe("");
+ });
+
+ it("supports keyboard navigation, Enter selection, and shortcut dismissal", async () => {
+ const user = userEvent.setup();
+ renderSidebar();
+
+ fireEvent.keyDown(document, { key: "k", metaKey: true });
+ expect(await screen.findByRole("dialog")).toBeDefined();
+
+ await user.type(
+ screen.getByRole("textbox", { name: /search chats/i }),
+ "forecast",
+ );
+ await screen.findByText("Results");
+ await user.keyboard("{ArrowDown}{Enter}");
+
+ await vi.waitFor(() => {
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ fireEvent.keyDown(document, { key: "k", ctrlKey: true });
+ expect(await screen.findByRole("dialog")).toBeDefined();
+ fireEvent.keyDown(document, { key: "k", ctrlKey: true });
+ await vi.waitFor(() => {
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+ });
+});
+
describe("ChatSidebar — chat_status indicators", () => {
afterEach(() => {
server.resetHandlers();
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx
index f71b80603f..d531e92530 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx
@@ -2,11 +2,16 @@ import { useGetV2ListSessions } from "@/app/api/__generated__/endpoints/chat/cha
import { Button } from "@/components/atoms/Button/Button";
import { Text } from "@/components/atoms/Text/Text";
import { scrollbarStyles } from "@/components/styles/scrollbars";
+import { Button as ShadcnButton } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Separator } from "@/components/ui/separator";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { cn } from "@/lib/utils";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import {
CheckCircle,
CircleNotch,
+ MagnifyingGlass,
PlusIcon,
SpeakerHigh,
SpeakerSlash,
@@ -14,11 +19,14 @@ import {
X,
} from "@phosphor-icons/react";
import { parseAsString, useQueryState } from "nuqs";
+import { useEffect, useRef } from "react";
import { Drawer } from "vaul";
import { useCopilotChatRuntimeStore } from "../../copilotChatRegistry";
import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";
import { useCopilotUIStore } from "../../store";
import { useSessionDeletion } from "../../useSessionDeletion";
+import { ChatSearchResults } from "../ChatSearchModal/ChatSearchResults";
+import { useChatSearch } from "../ChatSearchModal/useChatSearch";
import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";
function formatDate(dateString: string) {
@@ -48,6 +56,7 @@ function formatDate(dateString: string) {
export function MobileDrawer() {
const { isUserLoading, isLoggedIn } = useSupabase();
+ const searchInputRef = useRef<HTMLInputElement>(null);
const [currentSessionId, setSessionId] = useQueryState(
"sessionId",
parseAsString,
@@ -59,7 +68,11 @@ export function MobileDrawer() {
toggleSound,
isDrawerOpen,
setDrawerOpen,
+ isSearchOpen,
+ setSearchOpen,
} = useCopilotUIStore();
+ const isChatSearchEnabled = useGetFlag(Flag.CHAT_SEARCH);
+ const isSearchActive = isChatSearchEnabled && isSearchOpen;
const sessionNeedsReload = useCopilotChatRuntimeStore(
(state) => state.sessionNeedsReload,
);
@@ -70,16 +83,37 @@ export function MobileDrawer() {
);
const sessions =
sessionsResponse?.status === 200 ? sessionsResponse.data.sessions : [];
+ const {
+ query,
+ debouncedQuery,
+ setQuery,
+ results,
+ highlightedIndex,
+ setHighlightedIndex,
+ highlightedResultRef,
+ } = useChatSearch(sessions, isSearchOpen);
const { sessionToDelete, isDeleting, confirmDelete, cancelDelete } =
useSessionDeletion();
+ useEffect(() => {
+ if (!isSearchActive || !isDrawerOpen) return;
+ window.setTimeout(() => searchInputRef.current?.focus(), 0);
+ }, [isSearchActive, isDrawerOpen]);
+
+ function handleDrawerOpenChange(open: boolean) {
+ setDrawerOpen(open);
+ if (!open) setSearchOpen(false);
+ }
+
function closeDrawer() {
setDrawerOpen(false);
+ setSearchOpen(false);
}
function handleSelectSession(id: string) {
setSessionId(id);
+ setSearchOpen(false);
closeDrawer();
}
@@ -92,7 +126,7 @@ export function MobileDrawer() {
<>
<Drawer.Root
open={isDrawerOpen}
- onOpenChange={setDrawerOpen}
+ onOpenChange={handleDrawerOpenChange}
direction="left"
>
<Drawer.Portal>
@@ -119,6 +153,24 @@ export function MobileDrawer() {
<SpeakerSlash className="h-4 w-4" />
)}
</button>
+ {isChatSearchEnabled ? (
+ <ShadcnButton
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={
+ isSearchOpen ? "Close search" : "Search chats"
+ }
+ onClick={() => setSearchOpen(!isSearchOpen)}
+ className="rounded-full text-zinc-600 hover:bg-zinc-100"
+ >
+ {isSearchOpen ? (
+ <X className="h-4 w-4" />
+ ) : (
+ <MagnifyingGlass className="h-4 w-4" />
+ )}
+ </ShadcnButton>
+ ) : null}
<Button
variant="icon"
size="icon"
@@ -129,7 +181,7 @@ export function MobileDrawer() {
</Button>
</div>
</div>
- {currentSessionId ? (
+ {currentSessionId && !isSearchActive ? (
<div className="mt-2">
<Button
variant="primary"
@@ -149,7 +201,50 @@ export function MobileDrawer() {
scrollbarStyles,
)}
>
- {isLoading ? (
+ {isSearchActive ? (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="px-1 pb-3">
+ <div className="relative">
+ <MagnifyingGlass className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-400" />
+ <Input
+ ref={searchInputRef}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder="Search chats..."
+ aria-label="Search chats"
+ autoComplete="off"
+ className="h-10 bg-white pl-9 text-sm"
+ />
+ </div>
+ </div>
+ <Separator className="mb-2" />
+ <div className="px-1 pb-2 text-xs font-medium uppercase tracking-wide text-zinc-400">
+ {debouncedQuery.trim() ? "Results" : "Recent chats"}
+ </div>
+ {results.length > 0 ? (
+ <ChatSearchResults
+ results={results}
+ query={debouncedQuery}
+ highlightedIndex={highlightedIndex}
+ highlightedResultRef={highlightedResultRef}
+ currentSessionId={currentSessionId}
+ completedSessionIDs={completedSessionIDs}
+ sessionNeedsReload={sessionNeedsReload}
+ onHighlight={setHighlightedIndex}
+ onSelect={(id) => {
+ handleSelectSession(id);
+ if (completedSessionIDs.has(id)) {
+ clearCompletedSession(id);
+ }
+ }}
+ />
+ ) : (
+ <p className="py-4 text-center text-sm text-neutral-500">
+ No chats found
+ </p>
+ )}
+ </div>
+ ) : isLoading ? (
<div className="flex items-center justify-center py-4">
<SpinnerGapIcon className="h-5 w-5 animate-spin text-neutral-400" />
</div>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/__tests__/MobileDrawer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/__tests__/MobileDrawer.test.tsx
new file mode 100644
index 0000000000..1f289e3a12
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/__tests__/MobileDrawer.test.tsx
@@ -0,0 +1,125 @@
+import { getGetV2ListSessionsMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";
+import { server } from "@/mocks/mock-server";
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import { useCopilotUIStore } from "../../../store";
+import { MobileDrawer } from "../MobileDrawer";
+
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({ isUserLoading: false, isLoggedIn: true }),
+}));
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useGetFlag: (flag: string) => flag === "chat-search",
+ };
+});
+
+const sessions = [
+ {
+ id: "s1",
+ title: "Budget notes",
+ is_processing: false,
+ created_at: "2025-01-01T00:00:00Z",
+ updated_at: "2025-01-01T00:00:00Z",
+ },
+ {
+ id: "s2",
+ title: "Revenue forecast",
+ is_processing: false,
+ created_at: "2025-01-02T00:00:00Z",
+ updated_at: "2025-01-02T00:00:00Z",
+ },
+];
+
+describe("MobileDrawer search", () => {
+ const originalSetPointerCapture = HTMLElement.prototype.setPointerCapture;
+ const originalReleasePointerCapture =
+ HTMLElement.prototype.releasePointerCapture;
+ const originalHasPointerCapture = HTMLElement.prototype.hasPointerCapture;
+
+ beforeAll(() => {
+ HTMLElement.prototype.setPointerCapture = vi.fn();
+ HTMLElement.prototype.releasePointerCapture = vi.fn();
+ HTMLElement.prototype.hasPointerCapture = vi.fn(() => false);
+ });
+
+ afterAll(() => {
+ HTMLElement.prototype.setPointerCapture = originalSetPointerCapture;
+ HTMLElement.prototype.releasePointerCapture = originalReleasePointerCapture;
+ HTMLElement.prototype.hasPointerCapture = originalHasPointerCapture;
+ });
+
+ beforeEach(() => {
+ useCopilotUIStore.setState({
+ isDrawerOpen: true,
+ isSearchOpen: false,
+ completedSessionIDs: new Set<string>(),
+ });
+ server.use(
+ getGetV2ListSessionsMockHandler200({
+ sessions,
+ total: sessions.length,
+ }),
+ );
+ });
+
+ it("opens and closes the inline search view", async () => {
+ render(<MobileDrawer />);
+
+ expect(await screen.findByText("Budget notes")).toBeDefined();
+
+ fireEvent.click(screen.getByRole("button", { name: /search chats/i }));
+ expect(
+ screen.getByRole("textbox", { name: /search chats/i }),
+ ).toBeDefined();
+
+ fireEvent.change(screen.getByRole("textbox", { name: /search chats/i }), {
+ target: { value: "forecast" },
+ });
+ expect(
+ await screen.findByRole("option", { name: /revenue forecast/i }),
+ ).toBeDefined();
+ await vi.waitFor(() => {
+ expect(
+ screen.queryByRole("option", { name: /budget notes/i }),
+ ).toBeNull();
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: /close search/i }));
+ expect(screen.queryByRole("textbox", { name: /search chats/i })).toBeNull();
+ expect(await screen.findByText("Budget notes")).toBeDefined();
+ });
+
+ it("selects a filtered session and closes the drawer", async () => {
+ render(<MobileDrawer />);
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: /search chats/i }),
+ );
+ fireEvent.change(screen.getByRole("textbox", { name: /search chats/i }), {
+ target: { value: "revenue" },
+ });
+ fireEvent.click(
+ await screen.findByRole("option", { name: /revenue forecast/i }),
+ );
+
+ await vi.waitFor(() => {
+ expect(useCopilotUIStore.getState().isDrawerOpen).toBe(false);
+ expect(useCopilotUIStore.getState().isSearchOpen).toBe(false);
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
index aff21824de..f5e29af8b1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
@@ -106,6 +106,9 @@ interface CopilotUIState {
isDrawerOpen: boolean;
setDrawerOpen: (open: boolean) => void;
+ isSearchOpen: boolean;
+ setSearchOpen: (open: boolean) => void;
+
completedSessionIDs: Set<string>;
addCompletedSession: (id: string) => void;
clearCompletedSession: (id: string) => void;
@@ -171,6 +174,9 @@ export const useCopilotUIStore = create<CopilotUIState>((set, get) => ({
isDrawerOpen: false,
setDrawerOpen: (open) => set({ isDrawerOpen: open }),
+ isSearchOpen: false,
+ setSearchOpen: (open) => set({ isSearchOpen: open }),
+
completedSessionIDs: isClient
? parseSessionIDs(storage.get(Key.COPILOT_COMPLETED_SESSIONS))
: new Set(),
@@ -387,6 +393,7 @@ export const useCopilotUIStore = create<CopilotUIState>((set, get) => ({
storage.clean(Key.COPILOT_MODEL);
set({
completedSessionIDs: new Set<string>(),
+ isSearchOpen: false,
isNotificationsEnabled: false,
isSoundEnabled: true,
artifactPanel: {
diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
index 2d3f082a84..217322cb81 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
@@ -13,6 +13,7 @@ export enum Flag {
BUILDER_CHAT_PANEL = "builder-chat-panel",
AGENT_BRIEFING = "agent-briefing",
GENERIC_TRIGGER_AGENTS = "generic-trigger-agents",
+ CHAT_SEARCH = "chat-search",
}
const isPwMockEnabled = process.env.NEXT_PUBLIC_PW_TEST === "true";
@@ -26,6 +27,7 @@ const defaultFlags = {
[Flag.BUILDER_CHAT_PANEL]: false,
[Flag.AGENT_BRIEFING]: false,
[Flag.GENERIC_TRIGGER_AGENTS]: false,
+ [Flag.CHAT_SEARCH]: false,
};
type FlagValues = typeof defaultFlags;