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): global Cmd+K search palette on all platform pages (#13360)

Abhimanyu Yadav07a0c02a741f
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
index 18825d5613..8e363482d6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
@@ -22,6 +22,14 @@ vi.mock("@/components/molecules/Toast/use-toast", () => ({
useToastOnFail: () => mockToast,
}));
+// test-utils wraps every render in OnboardingProvider, which asynchronously
+// redirects incomplete users via router.replace("/onboarding"). That timer can
+// fire mid-test and pollute the router.replace assertions below, so stub the
+// provider to a passthrough (same approach as the login/signup tests).
+vi.mock("@/providers/onboarding/onboarding-provider", () => ({
+ default: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+
// Strip Radix portals — happy-dom doesn't render them. The mock keeps the
// Dialog tree visible while ignoring controlled/forceOpen props.
function MockDialog({ children }: { children: React.ReactNode }) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/GlobalSearchOverlay.tsx b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/GlobalSearchOverlay.tsx
new file mode 100644
index 0000000000..931ea60c03
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/GlobalSearchOverlay.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
+import { usePathname, useRouter } from "next/navigation";
+import { useEffect, useRef } from "react";
+import { GlobalSearchModal } from "./GlobalSearchModal";
+import { selectSearchResult } from "./selectSearchResult";
+import { useGlobalSearchStore } from "./useGlobalSearchStore";
+
+// Mounted once in the platform layout so Cmd/Ctrl+K opens the search palette
+// from any page. Renders a single modal instance driven by the shared store.
+export function GlobalSearchOverlay() {
+ const isEnabled = useGetFlag(Flag.CHAT_SEARCH);
+ const router = useRouter();
+ const pathname = usePathname();
+ const isOpen = useGlobalSearchStore((state) => state.isOpen);
+ const closeSearch = useGlobalSearchStore((state) => state.closeSearch);
+
+ // Close the palette once navigation lands. The modal now lives in the
+ // platform layout (persists across pages), so route changes no longer
+ // unmount it — close on a real pathname change instead.
+ const previousPathname = useRef(pathname);
+ useEffect(() => {
+ if (previousPathname.current !== pathname) {
+ previousPathname.current = pathname;
+ useGlobalSearchStore.getState().closeSearch();
+ }
+ }, [pathname]);
+
+ useEffect(() => {
+ if (!isEnabled) return;
+ function handleSearchShortcut(event: KeyboardEvent) {
+ if (event.repeat) return;
+ if (event.key.toLocaleLowerCase() !== "k") return;
+ if (!event.metaKey && !event.ctrlKey) return;
+ event.preventDefault();
+ useGlobalSearchStore.getState().toggleSearch();
+ }
+
+ document.addEventListener("keydown", handleSearchShortcut);
+ return () => document.removeEventListener("keydown", handleSearchShortcut);
+ }, [isEnabled]);
+
+ if (!isEnabled) return null;
+
+ return (
+ <GlobalSearchModal
+ isOpen={isOpen}
+ onClose={closeSearch}
+ onSelectItem={(item) => {
+ // Close on selection directly — a chat_session selected while already
+ // on /copilot only changes the query param, so the pathname-change
+ // effect above wouldn't fire.
+ closeSearch();
+ selectSearchResult(router, item);
+ }}
+ />
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/GlobalSearchOverlay.disabled.test.tsx b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/GlobalSearchOverlay.disabled.test.tsx
new file mode 100644
index 0000000000..1db22c1edd
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/GlobalSearchOverlay.disabled.test.tsx
@@ -0,0 +1,27 @@
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import { describe, expect, it, vi } from "vitest";
+import { GlobalSearchOverlay } from "../GlobalSearchOverlay";
+import { useGlobalSearchStore } from "../useGlobalSearchStore";
+
+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: () => false,
+ };
+});
+
+describe("GlobalSearchOverlay — flag disabled", () => {
+ it("renders nothing and ignores Cmd+K when the flag is off", () => {
+ useGlobalSearchStore.setState({ isOpen: false });
+ render(<GlobalSearchOverlay />);
+
+ fireEvent.keyDown(document, { key: "k", metaKey: true });
+
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(useGlobalSearchStore.getState().isOpen).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/GlobalSearchOverlay.test.tsx b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/GlobalSearchOverlay.test.tsx
new file mode 100644
index 0000000000..34f8c15ad9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/GlobalSearchOverlay.test.tsx
@@ -0,0 +1,199 @@
+import { getGetSearchGlobalSearchMockHandler200 } from "@/app/api/__generated__/endpoints/search/search.msw";
+import type { GlobalSearchResponse } from "@/app/api/__generated__/models/globalSearchResponse";
+import { server } from "@/mocks/mock-server";
+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 { GlobalSearchOverlay } from "../GlobalSearchOverlay";
+import { useGlobalSearchStore } from "../useGlobalSearchStore";
+
+// Override the static next/navigation mock so this file can drive a pathname
+// change and assert the palette closes after navigation lands.
+let mockPathname = "/marketplace";
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ push: vi.fn(),
+ replace: vi.fn(),
+ prefetch: vi.fn(),
+ back: vi.fn(),
+ forward: vi.fn(),
+ refresh: vi.fn(),
+ }),
+ usePathname: () => mockPathname,
+ useSearchParams: () => new URLSearchParams(),
+ useParams: () => ({}),
+}));
+
+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",
+ };
+});
+
+function makeSearchResponse(
+ overrides: Partial<GlobalSearchResponse> = {},
+): GlobalSearchResponse {
+ return {
+ agents: [],
+ files: [],
+ chats: [
+ {
+ id: "newer",
+ type: "chat_session",
+ title: "Revenue forecast",
+ score: 0.9,
+ updated_at: new Date("2025-01-03T00:00:00Z"),
+ },
+ {
+ id: "middle",
+ type: "chat_session",
+ title: "Forecast follow-up",
+ score: 0.8,
+ updated_at: new Date("2025-01-02T00:00:00Z"),
+ },
+ {
+ id: "older",
+ type: "chat_session",
+ title: "Budget notes",
+ score: 0.6,
+ updated_at: new Date("2025-01-01T00:00:00Z"),
+ },
+ ],
+ ...overrides,
+ };
+}
+
+describe("GlobalSearchOverlay", () => {
+ beforeEach(() => {
+ mockPathname = "/marketplace";
+ useGlobalSearchStore.setState({ isOpen: false });
+ server.use(
+ // Search endpoint is filtered server-side by the ``q`` param. To keep
+ // the test deterministic we narrow the chat bucket here instead of
+ // relying on backend semantics.
+ getGetSearchGlobalSearchMockHandler200(({ request }) => {
+ const url = new URL(request.url);
+ const q = (url.searchParams.get("q") ?? "").trim().toLowerCase();
+ const response = makeSearchResponse();
+ if (!q) {
+ return response;
+ }
+ response.chats = (response.chats ?? []).filter((chat) =>
+ chat.title.toLowerCase().includes(q),
+ );
+ return response;
+ }),
+ );
+ });
+
+ afterEach(() => {
+ server.resetHandlers();
+ });
+
+ it("opens with Cmd+K, focuses the input, and shows recent chats", async () => {
+ render(<GlobalSearchOverlay />);
+
+ fireEvent.keyDown(document, { key: "k", metaKey: true });
+
+ const dialog = await screen.findByRole("dialog");
+ const input = screen.getByRole("textbox", { name: /global search/i });
+ await vi.waitFor(() => expect(document.activeElement).toBe(input));
+ expect(await within(dialog).findByText("Revenue forecast")).toBeDefined();
+ });
+
+ it("filters results, shows empty copy, and clears the query", async () => {
+ const user = userEvent.setup();
+ render(<GlobalSearchOverlay />);
+
+ fireEvent.keyDown(document, { key: "k", metaKey: true });
+ await user.type(
+ screen.getByRole("textbox", { name: /global search/i }),
+ "forecast",
+ );
+
+ const dialog = screen.getByRole("dialog");
+ // The hook keeps previous results visible via ``placeholderData`` to
+ // avoid a flash-of-empty on every keystroke — wait for the filtered
+ // response to land before asserting that ``Budget notes`` is gone.
+ await vi.waitFor(() => {
+ expect(
+ within(dialog).queryByRole("option", { name: /budget notes/i }),
+ ).toBeNull();
+ });
+ expect(
+ within(dialog).getByRole("option", { name: /revenue forecast/i }),
+ ).toBeDefined();
+ expect(
+ within(dialog).getByRole("option", { name: /forecast follow-up/i }),
+ ).toBeDefined();
+
+ await user.clear(screen.getByRole("textbox", { name: /global search/i }));
+ await user.type(
+ screen.getByRole("textbox", { name: /global search/i }),
+ "missing",
+ );
+ expect(await screen.findByText("No results found")).toBeDefined();
+
+ await user.click(screen.getByRole("button", { name: /clear search/i }));
+ expect(
+ (
+ screen.getByRole("textbox", {
+ name: /global search/i,
+ }) as HTMLInputElement
+ ).value,
+ ).toBe("");
+ });
+
+ it("closes the palette after navigation lands on a new route", async () => {
+ const { rerender } = render(<GlobalSearchOverlay />);
+
+ fireEvent.keyDown(document, { key: "k", metaKey: true });
+ expect(await screen.findByRole("dialog")).toBeDefined();
+
+ mockPathname = "/library";
+ rerender(<GlobalSearchOverlay />);
+
+ await vi.waitFor(() => {
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+ });
+
+ it("supports keyboard navigation, Enter selection, and shortcut dismissal", async () => {
+ const user = userEvent.setup();
+ render(<GlobalSearchOverlay />);
+
+ fireEvent.keyDown(document, { key: "k", metaKey: true });
+ const dialog = await screen.findByRole("dialog");
+
+ await user.type(
+ screen.getByRole("textbox", { name: /global search/i }),
+ "forecast",
+ );
+ // Wait for the highlighted result to settle on the top match.
+ await within(dialog).findByRole("option", { name: /revenue forecast/i });
+
+ fireEvent.keyDown(dialog, { key: "ArrowDown" });
+ fireEvent.keyDown(dialog, { key: "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();
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/selectSearchResult.test.ts b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/selectSearchResult.test.ts
new file mode 100644
index 0000000000..3ccc7399bd
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/__tests__/selectSearchResult.test.ts
@@ -0,0 +1,68 @@
+import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { SearchResultItem } from "@/app/api/__generated__/models/searchResultItem";
+import { selectSearchResult } from "../selectSearchResult";
+
+function makeRouter() {
+ const push = vi.fn();
+ const router = { push } as unknown as AppRouterInstance;
+ return { router, push };
+}
+
+function asItem(item: Partial<SearchResultItem>): SearchResultItem {
+ return item as SearchResultItem;
+}
+
+describe("selectSearchResult", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("routes a chat_session to copilot via the sessionId query param", () => {
+ const { router, push } = makeRouter();
+ selectSearchResult(router, asItem({ id: "abc 1", type: "chat_session" }));
+ expect(push).toHaveBeenCalledWith("/copilot?sessionId=abc%201");
+ });
+
+ it("routes a library_agent to its detail page", () => {
+ const { router, push } = makeRouter();
+ selectSearchResult(router, asItem({ id: "lib1", type: "library_agent" }));
+ expect(push).toHaveBeenCalledWith("/library/agents/lib1");
+ });
+
+ it("routes a store_agent to the marketplace using creator and slug", () => {
+ const { router, push } = makeRouter();
+ selectSearchResult(
+ router,
+ asItem({
+ id: "store1",
+ type: "store_agent",
+ metadata: { creator: "ac me", slug: "cool/agent" },
+ }),
+ );
+ expect(push).toHaveBeenCalledWith(
+ "/marketplace/agent/ac%20me/cool%2Fagent",
+ );
+ });
+
+ it("does not route a store_agent missing creator or slug", () => {
+ const { router, push } = makeRouter();
+ selectSearchResult(
+ router,
+ asItem({ id: "store2", type: "store_agent", metadata: {} }),
+ );
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("opens a workspace_file download in a new tab", () => {
+ const { router, push } = makeRouter();
+ const openSpy = vi.spyOn(window, "open").mockReturnValue(null);
+ selectSearchResult(router, asItem({ id: "file1", type: "workspace_file" }));
+ expect(openSpy).toHaveBeenCalledWith(
+ "/api/proxy/api/workspace/files/file1/download",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(push).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/selectSearchResult.ts b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/selectSearchResult.ts
new file mode 100644
index 0000000000..ccf0e79042
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/selectSearchResult.ts
@@ -0,0 +1,42 @@
+import type { SearchResultItem } from "@/app/api/__generated__/models/searchResultItem";
+import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
+
+// Routes a selected global-search result to its destination. Chat sessions
+// open on the copilot page via the ``sessionId`` query param so selection
+// works from any page, not just copilot.
+export function selectSearchResult(
+ router: AppRouterInstance,
+ item: SearchResultItem,
+): void {
+ switch (item.type) {
+ case "chat_session":
+ router.push(`/copilot?sessionId=${encodeURIComponent(item.id)}`);
+ return;
+ case "library_agent":
+ router.push(`/library/agents/${item.id}`);
+ return;
+ case "store_agent": {
+ // Store-agent rows carry creator + slug in ``metadata`` so we can build
+ // the marketplace URL without an extra fetch.
+ const metadata = (item.metadata ?? {}) as {
+ creator?: string;
+ slug?: string;
+ };
+ if (metadata.creator && metadata.slug) {
+ router.push(
+ `/marketplace/agent/${encodeURIComponent(metadata.creator)}/${encodeURIComponent(metadata.slug)}`,
+ );
+ }
+ return;
+ }
+ case "workspace_file":
+ // No dedicated viewer route — open the file's download URL in a new tab
+ // so the user gets the content immediately.
+ window.open(
+ `/api/proxy/api/workspace/files/${item.id}/download`,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/useGlobalSearchStore.ts b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/useGlobalSearchStore.ts
new file mode 100644
index 0000000000..f226adc89c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/useGlobalSearchStore.ts
@@ -0,0 +1,18 @@
+import { create } from "zustand";
+
+interface GlobalSearchState {
+ isOpen: boolean;
+ openSearch: () => void;
+ closeSearch: () => void;
+ toggleSearch: () => void;
+}
+
+// Platform-wide open/close state for the global search palette so any page
+// (and the Cmd/Ctrl+K shortcut mounted in the platform layout) can drive a
+// single modal instance.
+export const useGlobalSearchStore = create<GlobalSearchState>((set) => ({
+ isOpen: false,
+ openSearch: () => set({ isOpen: true }),
+ closeSearch: () => set({ isOpen: false }),
+ toggleSearch: () => set((state) => ({ isOpen: !state.isOpen })),
+}));
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 808cabe5b8..6f23c30870 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
@@ -47,8 +47,7 @@ import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";
import { useCopilotUIStore } from "../../store";
import { useSessionDeletion } from "../../useSessionDeletion";
import { SESSION_LIST_QUERY_KEY, useSessionList } from "../../useSessionList";
-import type { SearchResultItem } from "@/app/api/__generated__/models/searchResultItem";
-import { GlobalSearchModal } from "@/app/(platform)/components/GlobalSearchModal/GlobalSearchModal";
+import { useGlobalSearchStore } from "@/app/(platform)/components/GlobalSearchModal/useGlobalSearchStore";
import { useRouter } from "next/navigation";
import { ChatSessionBlock } from "../ChatSessionBlock/ChatSessionBlock";
import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";
@@ -59,12 +58,9 @@ export function ChatSidebar() {
const { state } = useSidebar();
const isCollapsed = state === "collapsed";
const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);
- const {
- completedSessionIDs,
- clearCompletedSession,
- isSearchOpen,
- setSearchOpen,
- } = useCopilotUIStore();
+ const { completedSessionIDs, clearCompletedSession } = useCopilotUIStore();
+ const openSearch = useGlobalSearchStore((state) => state.openSearch);
+ const closeSearch = useGlobalSearchStore((state) => state.closeSearch);
const isChatSearchEnabled = useGetFlag(Flag.CHAT_SEARCH);
const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS_PAGE);
const router = useRouter();
@@ -143,62 +139,13 @@ 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]);
-
function handleNewChat() {
setSessionId(null);
}
function handleSelectSession(id: string) {
setSessionId(id);
- setSearchOpen(false);
- }
-
- function handleSelectSearchItem(item: SearchResultItem) {
- if (item.type === "chat_session") {
- setSessionId(item.id);
- return;
- }
- if (item.type === "library_agent") {
- router.push(`/library/agents/${item.id}`);
- return;
- }
- if (item.type === "store_agent") {
- // Store-agent rows carry creator + slug in ``metadata`` so we can
- // build the marketplace URL without an extra fetch.
- const metadata = (item.metadata ?? {}) as {
- creator?: string;
- slug?: string;
- };
- if (metadata.creator && metadata.slug) {
- router.push(
- `/marketplace/agent/${encodeURIComponent(metadata.creator)}/${encodeURIComponent(metadata.slug)}`,
- );
- }
- return;
- }
- if (item.type === "workspace_file") {
- // No dedicated viewer route — open the file's download URL in a
- // new tab so the user gets the content immediately.
- window.open(
- `/api/proxy/api/workspace/files/${item.id}/download`,
- "_blank",
- "noopener,noreferrer",
- );
- return;
- }
+ closeSearch();
}
function handleRenameClick(
@@ -301,7 +248,7 @@ export function ChatSidebar() {
variant="ghost"
size="icon-sm"
aria-label="Search chats"
- onClick={() => setSearchOpen(true)}
+ onClick={() => openSearch()}
className="rounded-full text-zinc-600 hover:bg-zinc-100"
>
<MagnifyingGlassIcon className="!size-5" />
@@ -330,7 +277,7 @@ export function ChatSidebar() {
variant="ghost"
size="icon-sm"
aria-label="Search chats"
- onClick={() => setSearchOpen(true)}
+ onClick={() => openSearch()}
className="rounded-full text-zinc-600 hover:bg-zinc-100"
>
<MagnifyingGlassIcon className="!size-5" />
@@ -584,14 +531,6 @@ export function ChatSidebar() {
}}
/>
)}
-
- {isChatSearchEnabled ? (
- <GlobalSearchModal
- isOpen={isSearchOpen}
- onClose={() => setSearchOpen(false)}
- onSelectItem={handleSelectSearchItem}
- />
- ) : 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 083d9abeca..eb9695b4c3 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
@@ -3,8 +3,6 @@ import {
getDeleteV2DeleteSessionMockHandler422,
getGetV2ListSessionsMockHandler200,
} from "@/app/api/__generated__/endpoints/chat/chat.msw";
-import { getGetSearchGlobalSearchMockHandler200 } from "@/app/api/__generated__/endpoints/search/search.msw";
-import type { GlobalSearchResponse } from "@/app/api/__generated__/models/globalSearchResponse";
import { server } from "@/mocks/mock-server";
import {
fireEvent,
@@ -16,6 +14,7 @@ import { SidebarProvider } from "@/components/ui/sidebar";
import { http, HttpResponse } from "msw";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useGlobalSearchStore } from "@/app/(platform)/components/GlobalSearchModal/useGlobalSearchStore";
import { useCopilotUIStore } from "../../../store";
import { ChatSidebar } from "../ChatSidebar";
@@ -182,151 +181,31 @@ describe("ChatSidebar — delete flow", () => {
});
});
-describe("ChatSidebar — global search modal", () => {
- function makeSearchResponse(
- overrides: Partial<GlobalSearchResponse> = {},
- ): GlobalSearchResponse {
- return {
- agents: [],
- files: [],
- chats: [
- {
- id: "newer",
- type: "chat_session",
- title: "Revenue forecast",
- score: 0.9,
- updated_at: new Date("2025-01-03T00:00:00Z"),
- },
- {
- id: "middle",
- type: "chat_session",
- title: "Forecast follow-up",
- score: 0.8,
- updated_at: new Date("2025-01-02T00:00:00Z"),
- },
- {
- id: "older",
- type: "chat_session",
- title: "Budget notes",
- score: 0.6,
- updated_at: new Date("2025-01-01T00:00:00Z"),
- },
- ],
- ...overrides,
- };
- }
-
+describe("ChatSidebar — global search trigger", () => {
beforeEach(() => {
- useCopilotUIStore.setState({ isSearchOpen: false });
+ useGlobalSearchStore.setState({ isOpen: false });
server.use(
getGetV2ListSessionsMockHandler200({
sessions: [],
total: 0,
}),
- // Search endpoint is filtered server-side by the ``q`` param. To
- // keep the test deterministic we narrow the chat bucket here
- // instead of relying on backend semantics.
- getGetSearchGlobalSearchMockHandler200(({ request }) => {
- const url = new URL(request.url);
- const q = (url.searchParams.get("q") ?? "").trim().toLowerCase();
- const response = makeSearchResponse();
- if (!q) {
- return response;
- }
- response.chats = (response.chats ?? []).filter((chat) =>
- chat.title.toLowerCase().includes(q),
- );
- return response;
- }),
);
});
- it("opens with the search button, focuses the input, and shows recent chats", async () => {
+ // The search palette itself is mounted globally in the platform layout
+ // (see GlobalSearchOverlay) — here we only assert the sidebar button opens
+ // the shared store that drives it.
+ it("opens the global search palette from the search button", 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: /global search/i });
- await vi.waitFor(() => expect(document.activeElement).toBe(input));
- expect(await within(dialog).findByText("Revenue forecast")).toBeDefined();
- });
-
- it("filters results, shows empty copy, and clears the query", async () => {
- const user = userEvent.setup();
- renderSidebar();
+ expect(useGlobalSearchStore.getState().isOpen).toBe(false);
await user.click(
await screen.findByRole("button", { name: /search chats/i }),
);
- await user.type(
- screen.getByRole("textbox", { name: /global search/i }),
- "forecast",
- );
-
- const dialog = screen.getByRole("dialog");
- // The hook keeps previous results visible via ``placeholderData`` to
- // avoid a flash-of-empty on every keystroke — wait for the filtered
- // response to land before asserting that ``Budget notes`` is gone.
- await vi.waitFor(() => {
- expect(
- within(dialog).queryByRole("option", { name: /budget notes/i }),
- ).toBeNull();
- });
- expect(
- within(dialog).getByRole("option", { name: /revenue forecast/i }),
- ).toBeDefined();
- expect(
- within(dialog).getByRole("option", { name: /forecast follow-up/i }),
- ).toBeDefined();
-
- await user.clear(screen.getByRole("textbox", { name: /global search/i }));
- await user.type(
- screen.getByRole("textbox", { name: /global search/i }),
- "missing",
- );
- expect(await screen.findByText("No results found")).toBeDefined();
-
- await user.click(screen.getByRole("button", { name: /clear search/i }));
- expect(
- (
- screen.getByRole("textbox", {
- name: /global search/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 });
- const dialog = await screen.findByRole("dialog");
-
- await user.type(
- screen.getByRole("textbox", { name: /global search/i }),
- "forecast",
- );
- // Wait for the highlighted result to settle on the top match.
- await within(dialog).findByRole("option", { name: /revenue forecast/i });
-
- fireEvent.keyDown(dialog, { key: "ArrowDown" });
- fireEvent.keyDown(dialog, { key: "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();
- });
+ expect(useGlobalSearchStore.getState().isOpen).toBe(true);
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/layout.tsx b/autogpt_platform/frontend/src/app/(platform)/layout.tsx
index 068dd70f33..469ce83350 100644
--- a/autogpt_platform/frontend/src/app/(platform)/layout.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/layout.tsx
@@ -6,6 +6,7 @@ import { AdminImpersonationBanner } from "./admin/components/AdminImpersonationB
import { AutoPilotBridgeProvider } from "@/contexts/AutoPilotBridgeContext";
import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";
import { PaywallGate } from "./PaywallGate/PaywallGate";
+import { GlobalSearchOverlay } from "./components/GlobalSearchModal/GlobalSearchOverlay";
export default function PlatformLayout({ children }: { children: ReactNode }) {
return (
@@ -15,6 +16,7 @@ export default function PlatformLayout({ children }: { children: ReactNode }) {
<PushNotificationProvider />
<Navbar />
<AdminImpersonationBanner />
+ <GlobalSearchOverlay />
<section className="flex-1">
<TopUpPromptProvider>
<PaywallGate>{children}</PaywallGate>