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.
fix(frontend/artifacts): keep the open folder in the URL so reloads and links land in it (#14769)
Reinier van der Leer480c6f5509c8
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/folders.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/folders.test.tsxindex 1855f4070c..ebd49bc2ac 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/folders.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/folders.test.tsx@@ -8,6 +8,7 @@ import {} from "@/tests/integrations/test-utils";import userEvent from "@testing-library/user-event";import { server } from "@/mocks/mock-server";+import { resetNavigation } from "./navigation-mock";import { http, HttpResponse } from "msw";import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";import {@@ -28,25 +29,14 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({// The generated default answers with random experts, which would render// random filter tabs on the page under test.beforeEach(() => {+ resetNavigation();server.use(getListExpertIdentitiesMockHandler([]));});-vi.mock("next/navigation", () => ({- useRouter: () => ({- push: vi.fn(),- replace: vi.fn(),- prefetch: vi.fn(),- back: vi.fn(),- forward: vi.fn(),- refresh: vi.fn(),- }),- usePathname: () => "/artifacts",- useSearchParams: () => new URLSearchParams(),- useParams: () => ({}),- notFound: () => {- throw new Error("NEXT_NOT_FOUND");- },-}));+vi.mock("next/navigation", async () => {+ const { navigationMock } = await import("./navigation-mock");+ return navigationMock();+});vi.mock("framer-motion", async (importActual) => {const actual = await importActual<typeof import("framer-motion")>();diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/main.test.tsxindex 6b1264a6a4..18aa9e01c3 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/main.test.tsx@@ -7,6 +7,7 @@ import {waitFor,} from "@/tests/integrations/test-utils";import { server } from "@/mocks/mock-server";+import { resetNavigation } from "./navigation-mock";import { http, HttpResponse } from "msw";import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";import {@@ -35,6 +36,7 @@ afterEach(() => {// The generated default answers with random experts, which would render// random filter tabs; tests that care register their own roster.beforeEach(() => {+ resetNavigation();server.use(getListExpertIdentitiesMockHandler([]));});@@ -55,23 +57,10 @@ vi.mock("@/lib/direct-upload", () => ({}));const notFoundMock = vi.hoisted(() => vi.fn());-vi.mock("next/navigation", () => ({- useRouter: () => ({- push: vi.fn(),- replace: vi.fn(),- prefetch: vi.fn(),- back: vi.fn(),- forward: vi.fn(),- refresh: vi.fn(),- }),- usePathname: () => "/artifacts",- useSearchParams: () => new URLSearchParams(),- useParams: () => ({}),- notFound: () => {- notFoundMock();- throw new Error("NEXT_NOT_FOUND");- },-}));+vi.mock("next/navigation", async () => {+ const { navigationMock } = await import("./navigation-mock");+ return navigationMock({ onNotFound: notFoundMock });+});vi.mock("framer-motion", async (importActual) => {const actual = await importActual<typeof import("framer-motion")>();diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/navigation-mock.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/navigation-mock.tsnew file mode 100644index 0000000000..be54d20d25--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/navigation-mock.ts@@ -0,0 +1,58 @@+import { useSyncExternalStore } from "react";+import { vi } from "vitest";++// The artifacts page keeps its open folder in the URL, so a static+// `useSearchParams` mock would leave the page frozen at root whatever the+// router is told. This store replays a router call as the query string the+// next render reads, which is what the browser does.+let searchParams = new URLSearchParams();+const listeners = new Set<() => void>();++export const routerMock = {+ push: vi.fn((href: string) => navigate(href)),+ replace: vi.fn((href: string) => navigate(href)),+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+};++export function navigationMock(opts: { onNotFound?: () => void } = {}) {+ return {+ useRouter: () => routerMock,+ usePathname: () => "/artifacts",+ useSearchParams: () =>+ useSyncExternalStore(subscribe, getSearchParams, getSearchParams),+ useParams: () => ({}),+ notFound: () => {+ opts.onNotFound?.();+ throw new Error("NEXT_NOT_FOUND");+ },+ };+}++// Call from `beforeEach` — `query` is the URL the page is entered on.+export function resetNavigation(query = "") {+ searchParams = new URLSearchParams(query);+ routerMock.push.mockClear();+ routerMock.replace.mockClear();+ listeners.forEach((notify) => notify());+}++export function currentFolderParam(): string | null {+ return searchParams.get("folder");+}++function navigate(href: string) {+ searchParams = new URLSearchParams(href.split("?")[1] ?? "");+ listeners.forEach((notify) => notify());+}++function subscribe(notify: () => void) {+ listeners.add(notify);+ return () => listeners.delete(notify);+}++function getSearchParams() {+ return searchParams;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/url.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/url.test.tsxnew file mode 100644index 0000000000..db9a118b93--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/url.test.tsx@@ -0,0 +1,175 @@+import { beforeEach, describe, expect, test, vi } from "vitest";++import {+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import { server } from "@/mocks/mock-server";+import { http, HttpResponse } from "msw";+import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";+import { getGetWorkspaceStorageUsageMockHandler } from "@/app/api/__generated__/endpoints/workspace/workspace.msw";+import {+ currentFolderParam,+ resetNavigation,+ routerMock,+} from "./navigation-mock";++vi.mock("@/services/feature-flags/use-get-flag", () => ({+ Flag: { ARTIFACTS_PAGE: "artifacts-page" },+ useGetFlag: () => true,+ useFlagStatus: () => ({ enabled: true, ready: true }),+}));++vi.mock("next/navigation", async () => {+ const { navigationMock } = await import("./navigation-mock");+ return navigationMock();+});++vi.mock("framer-motion", async (importActual) => {+ const actual = await importActual<typeof import("framer-motion")>();+ return { ...actual, useReducedMotion: () => true };+});++import ArtifactsPage from "../page";++const PROXY = "/api/proxy/api/workspace";++// Root lists root.txt, the one live folder lists inside.txt — so which listing+// rendered says which folder the page opened.+function useBaseHandlers(+ experts: Parameters<typeof getListExpertIdentitiesMockHandler>[0] = [],+) {+ server.use(+ getListExpertIdentitiesMockHandler(experts),+ getGetWorkspaceStorageUsageMockHandler({+ used_bytes: 0,+ limit_bytes: 1_000_000_000,+ used_percent: 0,+ file_count: 0,+ }),+ http.get(`${PROXY}/folders`, () =>+ HttpResponse.json({+ folders: [+ {+ id: "fld-1",+ workspace_id: "ws-1",+ name: "Reports",+ file_count: 1,+ created_at: "2026-05-01T00:00:00Z",+ updated_at: "2026-05-01T00:00:00Z",+ },+ ],+ }),+ ),+ http.get(`${PROXY}/files`, ({ request }) => {+ const folderId = new URL(request.url).searchParams.get("folder_id");+ return HttpResponse.json({+ files: [+ folderId === "fld-1"+ ? {+ ...baseFile,+ id: "f-in",+ name: "inside.txt",+ folder_id: "fld-1",+ }+ : { ...baseFile, id: "f-root", name: "root.txt" },+ ],+ offset: 0,+ has_more: false,+ });+ }),+ );+}++const baseFile = {+ id: "file-base",+ name: "base.txt",+ path: "/base.txt",+ mime_type: "text/plain",+ size_bytes: 1024,+ folder_id: null,+ metadata: {},+ origin: "generated",+ created_at: "2026-05-01T00:00:00Z",+};++describe("ArtifactsPage - folder in the URL", () => {+ beforeEach(() => resetNavigation());++ test("opens the folder named by the URL on load", async () => {+ resetNavigation("folder=fld-1");+ useBaseHandlers();++ render(<ArtifactsPage />);++ expect(await screen.findByText("inside.txt")).toBeDefined();+ expect(await screen.findByTestId("folder-breadcrumb")).toBeDefined();+ expect(screen.getByText("Reports")).toBeDefined();+ // The root listing must never paint on the way in.+ expect(screen.queryByText("root.txt")).toBeNull();+ });++ test("selecting a folder pushes it into the URL", async () => {+ useBaseHandlers();++ render(<ArtifactsPage />);+ expect(await screen.findByText("root.txt")).toBeDefined();++ fireEvent.click(await screen.findByTestId("workspace-folder"));++ await waitFor(() => expect(currentFolderParam()).toBe("fld-1"));+ expect(routerMock.push).toHaveBeenCalledWith("/artifacts?folder=fld-1");+ expect(await screen.findByText("inside.txt")).toBeDefined();+ });++ test("going back to root replaces the folder out of the URL", async () => {+ resetNavigation("folder=fld-1");+ useBaseHandlers();++ render(<ArtifactsPage />);+ await screen.findByTestId("folder-breadcrumb");++ fireEvent.click(screen.getByTestId("folder-breadcrumb-root"));++ await waitFor(() => expect(currentFolderParam()).toBeNull());+ expect(routerMock.replace).toHaveBeenCalledWith("/artifacts");+ expect(await screen.findByText("root.txt")).toBeDefined();+ });++ test("a folder id that no longer exists falls back to root", async () => {+ resetNavigation("folder=deleted-folder");+ useBaseHandlers();++ render(<ArtifactsPage />);++ expect(await screen.findByText("root.txt")).toBeDefined();+ expect(screen.queryByTestId("folder-breadcrumb")).toBeNull();+ // The dead id is dropped, so re-sharing the URL does not carry it on.+ await waitFor(() => expect(currentFolderParam()).toBeNull());+ });++ test("filtering by an expert clears the folder from the URL", async () => {+ resetNavigation("folder=fld-1");+ useBaseHandlers([+ {+ id: "expert-a",+ name: "Maria",+ avatar_url: null,+ role: "Analyst",+ is_archived: false,+ },+ ]);++ render(<ArtifactsPage />);+ await screen.findByTestId("folder-breadcrumb");++ fireEvent.click(+ await screen.findByTestId("artifacts-expert-filter-expert-a"),+ );++ await waitFor(() => expect(currentFolderParam()).toBeNull());+ expect(screen.queryByTestId("folder-breadcrumb")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsxindex 2f5da7170b..c9e13d7387 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx@@ -51,6 +51,12 @@ export default function ArtifactsPage() {);const { showNewLayout } = usePlatformChrome();const reduceMotion = useReducedMotion();+ const {+ folders,+ isLoading: isFoldersLoading,+ isError: isFoldersError,+ error: foldersError,+ } = useArtifactsFolders();const {files,isLoading,@@ -62,7 +68,8 @@ export default function ArtifactsPage() {originFilter,setOriginFilter,selectedFolderId,- setSelectedFolderId,+ openFolder,+ closeFolder,expertFilter,setExpertFilter,view,@@ -70,13 +77,7 @@ export default function ArtifactsPage() {hasMore,isLoadingMore,loadMore,- } = useArtifactsPage();- const {- folders,- isLoading: isFoldersLoading,- isError: isFoldersError,- error: foldersError,- } = useArtifactsFolders();+ } = useArtifactsPage({ folders, isFoldersLoading, isFoldersError });const { activeExperts, expertsById } = useExpertMap();const isSearching = searchTerm.length > 0;@@ -95,7 +96,7 @@ export default function ArtifactsPage() {function handleExpertFilterChange(expertId: string | null) {setExpertFilter(expertId);- if (expertId) setSelectedFolderId(null);+ if (expertId) closeFolder();}if (!flagReady) {@@ -184,7 +185,7 @@ export default function ArtifactsPage() {><FolderBreadcrumbfolderName={selectedFolder?.name ?? "Folder"}- onBack={() => setSelectedFolderId(null)}+ onBack={closeFolder}/></motion.div>) : null}@@ -218,7 +219,7 @@ export default function ArtifactsPage() {listKey={`${originFilter}|${expertFilter ?? "everyone"}|${debouncedSearch}|${selectedFolderId ?? "root"}`}view={view}showFolders={showFolders}- onSelectFolder={setSelectedFolderId}+ onSelectFolder={openFolder}/></motion.div></main>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.tsindex 8fd1586dc4..b29f659c59 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts@@ -1,6 +1,8 @@import { useEffect, useState } from "react";+import { usePathname, useRouter, useSearchParams } from "next/navigation";import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/workspace";import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import type { WorkspaceFolder } from "@/app/api/__generated__/models/workspaceFolder";import { type InfiniteData, useInfiniteQuery } from "@tanstack/react-query";export type OriginFilter = "all" | "uploaded" | "generated";@@ -8,18 +10,49 @@ export type ArtifactsView = "list" | "grid";const SEARCH_DEBOUNCE_MS = 250;const ARTIFACTS_PAGE_SIZE = 50;+const FOLDER_PARAM = "folder";export const ARTIFACTS_LIST_QUERY_KEY = ["artifacts", "list"] as const;type ListPage = Awaited<ReturnType<typeof listWorkspaceFiles>>;-export function useArtifactsPage() {+interface Options {+ folders: WorkspaceFolder[];+ isFoldersLoading: boolean;+ isFoldersError: boolean;+}++export function useArtifactsPage({+ folders,+ isFoldersLoading,+ isFoldersError,+}: Options) {+ const router = useRouter();+ const pathname = usePathname();+ const searchParams = useSearchParams();const [searchTerm, setSearchTerm] = useState("");const [originFilter, setOriginFilter] = useState<OriginFilter>("all");- const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);const [expertFilter, setExpertFilter] = useState<string | null>(null);const [view, setView] = useState<ArtifactsView>("list");+ // The open folder lives in the URL so a reload, a shared link and the back+ // button land in it. Only a settled folders query can prove an id is gone,+ // so until then it is taken at face value and the files load straight away+ // rather than queueing behind the folder list.+ const folderParam = searchParams.get(FOLDER_PARAM);+ const isStaleFolder =+ folderParam !== null &&+ !isFoldersLoading &&+ !isFoldersError &&+ !folders.some((folder) => folder.id === folderParam);+ const selectedFolderId = isStaleFolder ? null : folderParam;++ const currentSearch = searchParams.toString();+ useEffect(() => {+ if (!isStaleFolder) return;+ router.replace(folderHref(pathname, currentSearch, null));+ }, [isStaleFolder, pathname, currentSearch, router]);+const debouncedSearch = useDebouncedValue(searchTerm.trim(),SEARCH_DEBOUNCE_MS,@@ -81,7 +114,14 @@ export function useArtifactsPage() {originFilter,setOriginFilter,selectedFolderId,- setSelectedFolderId,+ // Entering a folder is a step forward, so the back button leaves it;+ // leaving replaces, so back does not drop you straight back inside.+ openFolder: (folderId: string) =>+ router.push(folderHref(pathname, currentSearch, folderId)),+ closeFolder: () => {+ if (folderParam === null) return;+ router.replace(folderHref(pathname, currentSearch, null));+ },expertFilter,setExpertFilter,view,@@ -94,6 +134,18 @@ export function useArtifactsPage() {};}+function folderHref(+ pathname: string,+ search: string,+ folderId: string | null,+): string {+ const params = new URLSearchParams(search);+ if (folderId) params.set(FOLDER_PARAM, folderId);+ else params.delete(FOLDER_PARAM);+ const query = params.toString();+ return query ? `${pathname}?${query}` : pathname;+}+function flattenFiles(data: InfiniteData<ListPage> | undefined,): WorkspaceFileItem[] {