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): nested folders, folder attach, and the expert file filter in the workspace picker and the Files page (#14774)
Reinier van der Leer5233e90d3cfd
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 ebd49bc2ac..46496eb5e3 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,7 +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 { currentFolderParam, resetNavigation } from "./navigation-mock";import { http, HttpResponse } from "msw";import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";import {@@ -96,6 +96,25 @@ async function openCreateFolderDialog() {fireEvent.click(await screen.findByTestId("create-folder-button"));}+// Folder actions live behind a "…" menu, like the file rows'. Radix+// DropdownMenu opens on pointerdown, not click, under happy-dom.+async function openFolderMenu(folderName = "Reports") {+ fireEvent.pointerDown(+ await screen.findByLabelText(`Actions for ${folderName}`),+ { button: 0 },+ );+}++// The move dialog selects first and moves on confirm, so a mis-click on a+// chevron can never move anything.+async function chooseMoveTarget(name: string) {+ const rows = await screen.findAllByTestId("move-to-folder-option");+ const row = rows.find((r) => r.textContent?.includes(name));+ if (!row) throw new Error(`no move target named ${name}`);+ fireEvent.click(row);+ fireEvent.click(screen.getByTestId("confirm-move-to-folder"));+}+describe("ArtifactsPage - folders", () => {test("renders folders as rows at the root with file counts", async () => {useStorageHandler();@@ -233,7 +252,7 @@ describe("ArtifactsPage - folders", () => {button: 0,});fireEvent.click(await screen.findByTestId("artifacts-move-to-folder"));- fireEvent.click(await screen.findByTestId("move-to-folder-option"));+ await chooseMoveTarget("Reports");await waitFor(() => expect(movedTo).toBe("fld-1"));});@@ -261,7 +280,8 @@ describe("ArtifactsPage - folders", () => {render(<ArtifactsPage />);- fireEvent.click(await screen.findByLabelText("Rename folder"));+ await openFolderMenu();+ fireEvent.click(await screen.findByTestId("folder-rename-menu"));const input = await screen.findByLabelText(/folder name/i);fireEvent.change(input, { target: { value: "Invoices" } });// Submit via Enter to exercise the input's keydown handler.@@ -290,7 +310,8 @@ describe("ArtifactsPage - folders", () => {render(<ArtifactsPage />);- fireEvent.click(await screen.findByLabelText("Delete folder"));+ await openFolderMenu();+ fireEvent.click(await screen.findByTestId("folder-delete-menu"));fireEvent.click(await screen.findByTestId("confirm-delete-folder"));await waitFor(() => expect(deleted).toBe(true));@@ -324,7 +345,7 @@ describe("ArtifactsPage - folders", () => {button: 0,});fireEvent.click(await screen.findByTestId("artifacts-move-to-folder"));- fireEvent.click(await screen.findByTestId("move-to-root"));+ await chooseMoveTarget("Files (root)");await waitFor(() => expect(movedTo).toBeNull());});@@ -475,7 +496,8 @@ describe("ArtifactsPage - folders", () => {render(<ArtifactsPage />);- fireEvent.click(await screen.findByLabelText("Delete folder"));+ await openFolderMenu();+ fireEvent.click(await screen.findByTestId("folder-delete-menu"));fireEvent.click(await screen.findByRole("button", { name: /cancel/i }));await waitFor(() =>@@ -484,3 +506,311 @@ describe("ArtifactsPage - folders", () => {expect(deleteCalled).toBe(false);});});++describe("ArtifactsPage - nested folders", () => {+ // Files / Reports / 2026, with one file directly in Reports.+ function useNestedHandlers() {+ useStorageHandler();+ server.use(+ getListWorkspaceFoldersMockHandler({+ folders: [+ makeFolder({ id: "fld-1", name: "Reports", file_count: 1 }),+ makeFolder({+ id: "fld-2",+ name: "2026",+ parent_id: "fld-1",+ file_count: 0,+ }),+ makeFolder({ id: "fld-9", name: "Archive", file_count: 0 }),+ ],+ }),+ http.get(`${PROXY}/files`, ({ request }) => {+ const folderId = new URL(request.url).searchParams.get("folder_id");+ return HttpResponse.json({+ files:+ folderId === "fld-1"+ ? [makeFile({ id: "f-in", name: "q3.pdf", folder_id: "fld-1" })]+ : [],+ offset: 0,+ has_more: false,+ });+ }),+ );+ }++ test("inside a folder the rows are its children and its direct files", async () => {+ resetNavigation("folder=fld-1");+ useNestedHandlers();++ render(<ArtifactsPage />);++ expect(await screen.findByText("q3.pdf")).toBeDefined();+ expect(screen.getByText("2026")).toBeDefined();+ // A sibling of the open folder is not one of its children.+ expect(screen.queryByText("Archive")).toBeNull();+ });++ test("grid view inside a folder shows the child folders only", async () => {+ resetNavigation("folder=fld-1");+ useNestedHandlers();++ render(<ArtifactsPage />);+ fireEvent.click(await screen.findByTestId("artifacts-view-grid"));++ expect(await screen.findByText("2026")).toBeDefined();+ expect(screen.queryByText("Archive")).toBeNull();+ });++ test("a folder holding only subfolders reports them instead of 0 files", async () => {+ useStorageHandler();+ server.use(+ getListWorkspaceFilesMockHandler({+ files: [],+ offset: 0,+ has_more: false,+ }),+ getListWorkspaceFoldersMockHandler({+ folders: [+ makeFolder({ id: "fld-1", name: "Reports", file_count: 0 }),+ makeFolder({ id: "fld-2", name: "2026", parent_id: "fld-1" }),+ makeFolder({ id: "fld-9", name: "Archive", file_count: 0 }),+ ],+ }),+ );++ render(<ArtifactsPage />);++ expect(await screen.findByText("1 folder")).toBeDefined();+ expect(screen.getByText("Empty")).toBeDefined();+ });++ // The delete cascades down the whole subtree, so the dialog counts every+ // folder that goes, not the two children the folder rows summarise.+ test("the delete dialog counts the whole subtree, not the direct children", async () => {+ useStorageHandler();+ server.use(+ getListWorkspaceFilesMockHandler({+ files: [],+ offset: 0,+ has_more: false,+ }),+ getListWorkspaceFoldersMockHandler({+ folders: [+ makeFolder({ id: "fld-1", name: "Reports", file_count: 0 }),+ makeFolder({ id: "fld-2", name: "2026", parent_id: "fld-1" }),+ makeFolder({ id: "fld-3", name: "Drafts", parent_id: "fld-1" }),+ makeFolder({ id: "fld-4", name: "Q3", parent_id: "fld-2" }),+ ],+ }),+ );++ render(<ArtifactsPage />);++ await openFolderMenu();+ fireEvent.click(await screen.findByTestId("folder-delete-menu"));++ expect(await screen.findByText(/and its 3 folders\?/)).toBeDefined();+ });++ test("New folder inside a folder posts parent_id and names the destination", async () => {+ resetNavigation("folder=fld-1");+ useNestedHandlers();+ let parentId: string | null | undefined = undefined;+ server.use(+ http.post(`${PROXY}/folders`, async ({ request }) => {+ const body = (await request.json()) as { parent_id?: string | null };+ parentId = body.parent_id;+ return HttpResponse.json(makeFolder({ id: "fld-new", name: "Q4" }), {+ status: 201,+ });+ }),+ );++ render(<ArtifactsPage />);+ await screen.findByText("q3.pdf");+ await openCreateFolderDialog();++ expect(await screen.findByText(/Inside “Reports”/)).toBeDefined();+ fireEvent.change(await screen.findByLabelText(/folder name/i), {+ target: { value: "Q4" },+ });+ fireEvent.click(screen.getByTestId("folder-form-submit"));++ await waitFor(() => expect(parentId).toBe("fld-1"));+ });++ test("the delete dialog names the folders that go with it", async () => {+ useNestedHandlers();++ render(<ArtifactsPage />);+ await openFolderMenu("Reports");+ fireEvent.click(await screen.findByTestId("folder-delete-menu"));++ expect(+ await screen.findByText(/and its 1 folder\? Files inside them/),+ ).toBeDefined();+ });++ test("a folder that vanishes while open lands you in its parent, not at the root", async () => {+ resetNavigation("folder=fld-2");+ useNestedHandlers();+ server.use(+ http.post(`${PROXY}/folders`, () => {+ // Someone else removed "2026" meanwhile; the create's invalidation is+ // what makes this tab notice.+ server.use(+ getListWorkspaceFoldersMockHandler({+ folders: [makeFolder({ id: "fld-1", name: "Reports" })],+ }),+ );+ return HttpResponse.json(makeFolder({ id: "fld-new", name: "Q4" }), {+ status: 201,+ });+ }),+ );++ render(<ArtifactsPage />);+ await screen.findByText("2026");+ await openCreateFolderDialog();+ fireEvent.change(await screen.findByLabelText(/folder name/i), {+ target: { value: "Q4" },+ });+ fireEvent.click(screen.getByTestId("folder-form-submit"));++ await waitFor(() => expect(currentFolderParam()).toBe("fld-1"));+ });++ test("the folder row menu offers rename, move and delete", async () => {+ useNestedHandlers();++ render(<ArtifactsPage />);+ await openFolderMenu("Reports");++ expect(await screen.findByTestId("folder-rename-menu")).toBeDefined();+ expect(screen.getByTestId("folder-move-menu")).toBeDefined();+ expect(screen.getByTestId("folder-delete-menu")).toBeDefined();+ });++ test("moving a folder refuses itself and its descendants, and PATCHes the chosen parent", async () => {+ useNestedHandlers();+ let patched: { id: string; parentId: string | null } | null = null;+ server.use(+ http.patch(`${PROXY}/folders/:folderId`, async ({ request, params }) => {+ const body = (await request.json()) as { parent_id: string | null };+ patched = {+ id: params.folderId as string,+ parentId: body.parent_id,+ };+ return HttpResponse.json(makeFolder({ id: "fld-1" }));+ }),+ );++ render(<ArtifactsPage />);+ await openFolderMenu("Reports");+ fireEvent.click(await screen.findByTestId("folder-move-menu"));++ const rows = await screen.findAllByTestId("move-to-folder-option");+ const self = rows.find((r) => r.textContent?.includes("Reports"));+ expect(self?.getAttribute("aria-disabled")).toBe("true");+ expect(self?.textContent).toContain("Folder being moved");+ // The tree opens on the subject's own location, so its child is already+ // visible — refused too, and it says why.+ const child = rows.find((r) => r.textContent?.includes("2026"));+ expect(child?.getAttribute("aria-disabled")).toBe("true");+ expect(child?.textContent).toContain("Inside the folder being moved");++ const archive = (+ await screen.findAllByTestId("move-to-folder-option")+ ).find((r) => r.textContent?.includes("Archive"));+ fireEvent.click(archive as HTMLElement);+ fireEvent.click(screen.getByTestId("confirm-move-to-folder"));++ await waitFor(() =>+ expect(patched).toEqual({ id: "fld-1", parentId: "fld-9" }),+ );+ });++ test("Move stays disabled until a destination is selected", async () => {+ useNestedHandlers();++ render(<ArtifactsPage />);+ await openFolderMenu("Reports");+ fireEvent.click(await screen.findByTestId("folder-move-menu"));++ const confirm = await screen.findByTestId("confirm-move-to-folder");+ expect(confirm.hasAttribute("disabled")).toBe(true);++ const archive = (+ await screen.findAllByTestId("move-to-folder-option")+ ).find((r) => r.textContent?.includes("Archive"));+ fireEvent.click(archive as HTMLElement);++ await waitFor(() =>+ expect(+ screen.getByTestId("confirm-move-to-folder").hasAttribute("disabled"),+ ).toBe(false),+ );+ });++ test("a name clash keeps the move dialog open and names the folder", async () => {+ useNestedHandlers();+ server.use(+ http.patch(`${PROXY}/folders/:folderId`, () =>+ HttpResponse.json({ detail: "exists" }, { status: 409 }),+ ),+ );++ render(<ArtifactsPage />);+ await openFolderMenu("Reports");+ fireEvent.click(await screen.findByTestId("folder-move-menu"));+ const archive = (+ await screen.findAllByTestId("move-to-folder-option")+ ).find((r) => r.textContent?.includes("Archive"));+ fireEvent.click(archive as HTMLElement);+ fireEvent.click(screen.getByTestId("confirm-move-to-folder"));++ // The dialog survives the clash so another destination can be picked+ // without reopening it; the message itself is unit-tested on+ // describeFolderMoveError.+ await waitFor(() =>+ expect(+ screen.getByTestId("confirm-move-to-folder").hasAttribute("disabled"),+ ).toBe(false),+ );+ expect(+ screen.getAllByTestId("move-to-folder-option").length,+ ).toBeGreaterThan(0);+ });++ test("the tree moves focus with the arrow keys and selects with Enter", async () => {+ useNestedHandlers();++ render(<ArtifactsPage />);+ await openFolderMenu("Reports");+ fireEvent.click(await screen.findByTestId("folder-move-menu"));++ // Rows are Archive, Reports (the subject), 2026 — sorted by name, with+ // the subject's own location already expanded.+ const rows = await screen.findAllByTestId("move-to-folder-option");+ const reports = rows.findIndex((r) => r.textContent?.includes("Reports"));+ rows[reports].focus();+ fireEvent.keyDown(rows[reports], { key: "Enter" });++ // "Reports" is the folder being moved: refused, so Enter selects nothing.+ expect(+ screen.getByTestId("confirm-move-to-folder").hasAttribute("disabled"),+ ).toBe(true);++ const archive = rows.findIndex((r) => r.textContent?.includes("Archive"));+ fireEvent.keyDown(rows[reports], {+ key: archive < reports ? "ArrowUp" : "ArrowDown",+ });+ expect(document.activeElement).toBe(rows[archive]);+ fireEvent.keyDown(rows[archive], { key: "Enter" });+ await waitFor(() =>+ expect(+ screen.getByTestId("confirm-move-to-folder").hasAttribute("disabled"),+ ).toBe(false),+ );+ });+});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 18aa9e01c3..9cdf975a67 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@@ -772,10 +772,12 @@ describe("ArtifactsPage - expert filter", () => {fireEvent.click(novaTab);+ // The expert narrows where you are, so the root listing stays root-only+ // instead of flattening the whole workspace.await waitFor(() => {const last = requests[requests.length - 1];expect(last.expertId).toBe("expert-a");- expect(last.rootOnly).toBe("false");+ expect(last.rootOnly).toBe("true");});expect(novaTab.getAttribute("aria-selected")).toBe("true");});diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/selection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/selection.test.tsxindex 8bf0af2dd6..c34dbeeb42 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/selection.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/selection.test.tsx@@ -228,6 +228,7 @@ describe("ArtifactsPage - row selection", () => {fireEvent.click(await screen.findByTestId("artifacts-selection-move"));expect(await screen.findByText("Move 2 files to:")).toBeDefined();fireEvent.click(await screen.findByTestId("move-to-folder-option"));+ fireEvent.click(screen.getByTestId("confirm-move-to-folder"));await waitFor(() =>expect(body).toEqual({ file_ids: ["f1", "f2"], folder_id: "fld-1" }),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.tsxindex db9a118b93..3a859b7fb6 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/url.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/url.test.tsx@@ -150,8 +150,9 @@ describe("ArtifactsPage - folder in the URL", () => {await waitFor(() => expect(currentFolderParam()).toBeNull());});- test("filtering by an expert clears the folder from the URL", async () => {+ test("filtering by an expert narrows inside the open folder instead of leaving it", async () => {resetNavigation("folder=fld-1");+ const requests: URLSearchParams[] = [];useBaseHandlers([{id: "expert-a",@@ -161,6 +162,16 @@ describe("ArtifactsPage - folder in the URL", () => {is_archived: false,},]);+ server.use(+ http.get(`${PROXY}/files`, ({ request }) => {+ requests.push(new URL(request.url).searchParams);+ return HttpResponse.json({+ files: [{ ...baseFile, id: "f-in", name: "inside.txt" }],+ offset: 0,+ has_more: false,+ });+ }),+ );render(<ArtifactsPage />);await screen.findByTestId("folder-breadcrumb");@@ -169,7 +180,118 @@ describe("ArtifactsPage - folder in the URL", () => {await screen.findByTestId("artifacts-expert-filter-expert-a"),);- await waitFor(() => expect(currentFolderParam()).toBeNull());- expect(screen.queryByTestId("folder-breadcrumb")).toBeNull();+ await waitFor(() =>+ expect(+ requests.some(+ (params) =>+ params.get("expert_id") === "expert-a" &&+ params.get("folder_id") === "fld-1",+ ),+ ).toBe(true),+ );+ expect(currentFolderParam()).toBe("fld-1");+ expect(screen.getByTestId("folder-breadcrumb")).toBeDefined();+ // "From: Maria" keeps meaning "made in Maria's chats": widening to the+ // user's own uploads is the picker's switch, never this tab.+ expect(+ requests.every((params) => params.get("include_user_files") === null),+ ).toBe(true);+ });++ test("at the root an expert filter still asks for root-level files only", async () => {+ const requests: URLSearchParams[] = [];+ useBaseHandlers([+ {+ id: "expert-a",+ name: "Maria",+ avatar_url: null,+ role: "Analyst",+ is_archived: false,+ },+ ]);+ server.use(+ http.get(`${PROXY}/files`, ({ request }) => {+ requests.push(new URL(request.url).searchParams);+ return HttpResponse.json({+ files: [{ ...baseFile, id: "f-root", name: "root.txt" }],+ offset: 0,+ has_more: false,+ });+ }),+ );++ render(<ArtifactsPage />);+ expect(await screen.findByText("root.txt")).toBeDefined();++ fireEvent.click(+ await screen.findByTestId("artifacts-expert-filter-expert-a"),+ );++ await waitFor(() =>+ expect(+ requests.some(+ (params) =>+ params.get("expert_id") === "expert-a" &&+ params.get("root_only") === "true",+ ),+ ).toBe(true),+ );+ });++ test("an ancestor crumb pushes that ancestor onto the URL", async () => {+ resetNavigation("folder=fld-3");+ useBaseHandlers();+ server.use(+ http.get(`${PROXY}/folders`, () =>+ HttpResponse.json({ folders: NESTED_FOLDERS }),+ ),+ );++ render(<ArtifactsPage />);+ // The crumb paints with a placeholder before the folders query settles,+ // so wait for the open folder's own name rather than the nav.+ await screen.findByText("Q3");++ fireEvent.click(await screen.findByRole("button", { name: "Reports" }));++ // A push, not a replace: back returns to the folder you jumped from.+ await waitFor(() => expect(currentFolderParam()).toBe("fld-1"));+ expect(routerMock.push).toHaveBeenCalled();+ });++ test("more than four crumbs collapse into a menu of the hidden ancestors", async () => {+ resetNavigation("folder=fld-4");+ useBaseHandlers();+ server.use(+ http.get(`${PROXY}/folders`, () =>+ HttpResponse.json({ folders: NESTED_FOLDERS }),+ ),+ );++ render(<ArtifactsPage />);+ await screen.findByText("Week 1");++ // Root, the parent and the current folder stay; "Reports" hides.+ expect(screen.queryByRole("button", { name: "Reports" })).toBeNull();+ fireEvent.pointerDown(screen.getByTestId("folder-breadcrumb-overflow"), {+ button: 0,+ });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Reports" }));++ await waitFor(() => expect(currentFolderParam()).toBe("fld-1"));});});++// Files / Reports / 2026 / Q3 / Week 1+const NESTED_FOLDERS = [+ { id: "fld-1", name: "Reports", parent_id: null },+ { id: "fld-2", name: "2026", parent_id: "fld-1" },+ { id: "fld-3", name: "Q3", parent_id: "fld-2" },+ { id: "fld-4", name: "Week 1", parent_id: "fld-3" },+].map((folder) => ({+ ...folder,+ workspace_id: "ws-1",+ file_count: 0,+ created_at: "2026-05-01T00:00:00Z",+ updated_at: "2026-05-01T00:00:00Z",+}));diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsList.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsList.tsxindex 47f9030649..63da6f6c53 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsList.tsx@@ -24,6 +24,8 @@ interface Props {listKey: string;view: ArtifactsView;showFolders: boolean;+ /** Folder whose children the folder rows list; `null` is the root. */+ folderParentId: string | null;onSelectFolder: (folderId: string) => void;}@@ -40,6 +42,7 @@ export function ArtifactsList({listKey,view,showFolders,+ folderParentId,onSelectFolder,}: Props) {const [openFile, setOpenFile] = useState<WorkspaceFileItem | null>(null);@@ -60,7 +63,10 @@ export function ArtifactsList({{view === "grid" ? (<div className="flex flex-col gap-6">{showFolders ? (- <WorkspaceFolders onSelectFolder={onSelectFolder} />+ <WorkspaceFolders+ parentId={folderParentId}+ onSelectFolder={onSelectFolder}+ />) : null}<ArtifactsGridfiles={files}@@ -81,6 +87,7 @@ export function ArtifactsList({compactEmpty={compactEmpty}listKey={listKey}showFolders={showFolders}+ folderParentId={folderParentId}onSelectFolder={onSelectFolder}onOpen={setOpenFile}/>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/ArtifactsTable.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/ArtifactsTable.tsxindex 3657235e6b..27df31e49c 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/ArtifactsTable.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/ArtifactsTable.tsx@@ -22,6 +22,7 @@ interface Props {compactEmpty: boolean;listKey: string;showFolders: boolean;+ folderParentId: string | null;onSelectFolder: (folderId: string) => void;onOpen: (file: WorkspaceFileItem) => void;}@@ -40,6 +41,7 @@ export function ArtifactsTable({compactEmpty,listKey,showFolders,+ folderParentId,onSelectFolder,onOpen,}: Props) {@@ -86,7 +88,12 @@ export function ArtifactsTable({initial={reduceMotion ? false : "hidden"}animate={reduceMotion ? undefined : "show"}>- {showFolders ? <FolderRows onSelectFolder={onSelectFolder} /> : null}+ {showFolders ? (+ <FolderRows+ parentId={folderParentId}+ onSelectFolder={onSelectFolder}+ />+ ) : null}{isLoading ? (<liclassName="divide-y divide-zinc-100"diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FolderRow.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FolderRow.tsxindex f57f56fe45..a8e02346a5 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FolderRow.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FolderRow.tsx@@ -3,15 +3,13 @@import { Icon } from "@/components/atoms/Icon/Icon";import { Text } from "@/components/atoms/Text/Text";import { cn } from "@/lib/utils";-import {- Delete02Icon,- Folder01Icon,- PencilIcon,-} from "@hugeicons/core-free-icons";+import { Folder01Icon } from "@hugeicons/core-free-icons";import { motion, useReducedMotion } from "framer-motion";import { useState } from "react";import type { DragEvent } from "react";import { FILE_DRAG_MIME, readFileDragIds } from "../../WorkspaceFolders/drag";+import { FolderActionsMenu } from "../../WorkspaceFolders/FolderActionsMenu";+import { folderSummary } from "../../WorkspaceFolders/folderTree";import { FOLDER_STYLE } from "../../WorkspaceFolders/folder-constants";import { formatDayLabel, formatFullDate } from "../helpers";import {@@ -28,25 +26,26 @@ interface Props {id: string;name: string;fileCount: number;+ subfolderCount: number;updatedAt: string | Date;onOpen: () => void;onEdit: () => void;+ onMove: () => void;onDelete: () => void;onFileDrop: (fileIds: string[]) => void;/** Position in the list; drives the small entrance stagger. */index?: number;}-const ACTION_BUTTON_CLASS =- "inline-flex h-8 w-8 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100";-export function FolderRow({id,name,fileCount,+ subfolderCount,updatedAt,onOpen,onEdit,+ onMove,onDelete,onFileDrop,index = 0,@@ -130,7 +129,7 @@ export function FolderRow({as="span"className={cn(SIZE_CELL_CLASS, "text-zinc-500")}>- {fileCount} {fileCount === 1 ? "file" : "files"}+ {folderSummary(fileCount, subfolderCount)}</Text><divclassName={cn(@@ -139,22 +138,12 @@ export function FolderRow({)}onClick={(e) => e.stopPropagation()}>- <button- type="button"- aria-label="Rename folder"- onClick={onEdit}- className={cn(ACTION_BUTTON_CLASS, "hover:text-zinc-900")}- >- <Icon icon={PencilIcon} size={16} />- </button>- <button- type="button"- aria-label="Delete folder"- onClick={onDelete}- className={cn(ACTION_BUTTON_CLASS, "hover:text-red-600")}- >- <Icon icon={Delete02Icon} size={16} />- </button>+ <FolderActionsMenu+ folderName={name}+ onRename={onEdit}+ onMove={onMove}+ onDelete={onDelete}+ /></div></motion.li>);diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FolderRows.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FolderRows.tsxindex 72c88229cf..1cfa345b05 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FolderRows.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FolderRows.tsx@@ -5,17 +5,24 @@ import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";import { useState } from "react";import { useArtifactsFolders } from "../../../useArtifactsFolders";import { FolderDialogs } from "../../WorkspaceFolders/FolderDialogs";+import {+ childrenOf,+ subfolderCountOf,+} from "../../WorkspaceFolders/folderTree";import { FolderRow } from "./FolderRow";import { SkeletonRow } from "./SkeletonRow";interface Props {+ /** Folder whose children are listed; `null` is the workspace root. */+ parentId: string | null;onSelectFolder: (folderId: string) => void;}-export function FolderRows({ onSelectFolder }: Props) {+export function FolderRows({ parentId, onSelectFolder }: Props) {const { folders, isLoading, isError, error, moveFilesToFolder } =useArtifactsFolders();const [editing, setEditing] = useState<WorkspaceFolder | null>(null);+ const [moving, setMoving] = useState<WorkspaceFolder | null>(null);const [deleting, setDeleting] = useState<WorkspaceFolder | null>(null);if (isLoading) {@@ -41,16 +48,18 @@ export function FolderRows({ onSelectFolder }: Props) {return (<>- {folders.map((folder, index) => (+ {childrenOf(folders, parentId).map((folder, index) => (<FolderRowkey={folder.id}index={index}id={folder.id}name={folder.name}fileCount={folder.file_count ?? 0}+ subfolderCount={subfolderCountOf(folders, folder.id)}updatedAt={folder.updated_at}onOpen={() => onSelectFolder(folder.id)}onEdit={() => setEditing(folder)}+ onMove={() => setMoving(folder)}onDelete={() => setDeleting(folder)}onFileDrop={(fileIds) => {moveFilesToFolder({ fileIds, folderId: folder.id }).catch(() => {});@@ -59,8 +68,10 @@ export function FolderRows({ onSelectFolder }: Props) {))}<FolderDialogsediting={editing}+ moving={moving}deleting={deleting}onEditClose={() => setEditing(null)}+ onMoveClose={() => setMoving(null)}onDeleteClose={() => setDeleting(null)}/></>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileActionsMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileActionsMenu.tsxindex b39a501f03..63813c5a44 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileActionsMenu.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileActionsMenu.tsx@@ -133,9 +133,12 @@ export function FileActionsMenu({ file, className }: Props) {)}{isMoveOpen && (<MoveToFolderDialog- fileIds={[file.id]}+ move={{+ kind: "files",+ fileIds: [file.id],+ currentFolderId: file.folder_id,+ }}subject={`“${file.name}”`}- currentFolderId={file.folder_id}isOpen={isMoveOpen}setIsOpen={setIsMoveOpen}/>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/SelectionBar/SelectionBar.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/SelectionBar/SelectionBar.tsxindex f7c0323597..bf1acd3ff9 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/SelectionBar/SelectionBar.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/SelectionBar/SelectionBar.tsx@@ -88,9 +88,12 @@ export function SelectionBar({</div>{isMoveOpen && (<MoveToFolderDialog- fileIds={selectedFiles.map((file) => file.id)}+ move={{+ kind: "files",+ fileIds: selectedFiles.map((file) => file.id),+ currentFolderId: sharedFolderId,+ }}subject={moveSubject}- currentFolderId={sharedFolderId}canMoveToRoot={selectedFiles.some((file) => file.folder_id != null)}isOpen={isMoveOpen}setIsOpen={setIsMoveOpen}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.tsindex cdb5a4a834..882ab732b7 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts@@ -434,3 +434,73 @@ describe("getEmptyMessage", () => {).toBe("No files yet");});});++describe("getEmptyMessage - nested folders and the expert filter", () => {+ test("a folder with subfolders but no direct files says so", () => {+ expect(+ getEmptyMessage({+ hasSearchTerm: false,+ isInFolder: true,+ hasFolders: true,+ }),+ ).toBe("No files directly in this folder");+ });++ test("a folder with neither is simply empty", () => {+ expect(+ getEmptyMessage({+ hasSearchTerm: false,+ isInFolder: true,+ hasFolders: false,+ }),+ ).toBe("This folder is empty");+ });++ test("an expert filter inside a folder names the expert and says 'here'", () => {+ expect(+ getEmptyMessage({+ hasSearchTerm: false,+ isInFolder: true,+ hasFolders: false,+ hasExpertFilter: true,+ expertName: "Maria",+ }),+ ).toBe("No files from Maria here");+ });++ test("an expert filter at a root with folders says 'here' too", () => {+ expect(+ getEmptyMessage({+ hasSearchTerm: false,+ isInFolder: false,+ hasFolders: true,+ hasExpertFilter: true,+ expertName: "Maria",+ }),+ ).toBe("No files from Maria here");+ });++ test("an expert filter with nowhere else to look keeps 'yet'", () => {+ expect(+ getEmptyMessage({+ hasSearchTerm: false,+ isInFolder: false,+ hasFolders: false,+ hasExpertFilter: true,+ expertName: "Maria",+ }),+ ).toBe("No files from this expert yet");+ });++ test("falls back to 'this expert' when the name is unknown", () => {+ expect(+ getEmptyMessage({+ hasSearchTerm: false,+ isInFolder: true,+ hasFolders: false,+ hasExpertFilter: true,+ expertName: null,+ }),+ ).toBe("No files from this expert here");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.tsindex 5796bbeff3..224e70d4df 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts@@ -342,12 +342,23 @@ export function hasImageThumbnail(kind: PreviewKind): boolean {export function getEmptyMessage(opts: {hasSearchTerm: boolean;isInFolder: boolean;+ /** Child folders are listed above the empty files area. */hasFolders: boolean;hasExpertFilter?: boolean;+ expertName?: string | null;}): string {if (opts.hasSearchTerm) return "No files match your search";- if (opts.hasExpertFilter) return "No files from this expert yet";- if (opts.isInFolder) return "This folder is empty";+ if (opts.hasExpertFilter) {+ // "yet" is only true of a workspace with nowhere else to look; anywhere+ // with folders or inside one, the files may simply be elsewhere.+ if (!opts.isInFolder && !opts.hasFolders)+ return "No files from this expert yet";+ return `No files from ${opts.expertName ?? "this expert"} here`;+ }+ if (opts.isInFolder)+ return opts.hasFolders+ ? "No files directly in this folder"+ : "This folder is empty";if (opts.hasFolders) return "No files at the root yet";return "No files yet";}@@ -373,6 +384,7 @@ export function getEmptyState(opts: {isInFolder: opts.isInFolder,hasFolders: opts.hasFolders,hasExpertFilter: opts.expert !== null,+ expertName: opts.expert?.name,});const base: EmptyStateContent = {title,diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/MoveToFolderDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/MoveToFolderDialog.tsxindex eb4dfd3a6d..88593c9772 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/MoveToFolderDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/MoveToFolderDialog.tsx@@ -3,19 +3,18 @@ import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { Dialog } from "@/components/molecules/Dialog/Dialog";import { useArtifactsFolders } from "../../useArtifactsFolders";-import { FOLDER_STYLE } from "../WorkspaceFolders/folder-constants";-import { Folder01Icon, Home01Icon } from "@hugeicons/core-free-icons";-import { Icon } from "@/components/atoms/Icon/Icon";+import { FolderTree } from "./components/FolderTree";+import type { MoveSubject } from "./helpers";+import { useMoveToFolderDialog } from "./useMoveToFolderDialog";interface Props {- fileIds: string[];- /** What is being moved, as shown in the prompt: `“report.pdf”` or `3 files`. */+ move: MoveSubject;+ /** What is being moved, as shown in the prompt: `“report.pdf”`, `3 files`+ or `“Reports”`. */subject: string;- /** Folder every file already sits in, left out of the destinations.- `null` when the files are at the root or spread across folders. */- currentFolderId?: string | null;- /** Offer "Files (root)". Defaults to "some file is inside a folder", which- `currentFolderId` alone cannot express for a mixed selection. */+ /** Offer "Files (root)". For files it defaults to "some file is inside a+ folder", which `currentFolderId` alone cannot express for a mixed+ selection; for a folder, to "not already at the root". */canMoveToRoot?: boolean;isOpen: boolean;setIsOpen: (open: boolean) => void;@@ -23,27 +22,31 @@ interface Props {}export function MoveToFolderDialog({- fileIds,+ move,subject,- currentFolderId,- canMoveToRoot = currentFolderId != null,+ canMoveToRoot,isOpen,setIsOpen,onMoved,}: Props) {- const { folders, moveFilesToFolder } = useArtifactsFolders();- const destinationFolders = folders.filter((f) => f.id !== currentFolderId);-- function handleMove(folderId: string | null) {- // Close only on success; the hook toasts on error and we keep the dialog- // open so the user can retry without re-opening it.- moveFilesToFolder({ fileIds, folderId })- .then(() => {- setIsOpen(false);- onMoved?.();- })- .catch(() => {});- }+ const { folders } = useArtifactsFolders();+ const offerRoot = canMoveToRoot ?? defaultCanMoveToRoot(move, folders);+ const {+ rows,+ selectedKey,+ select,+ toggleExpanded,+ confirm,+ canConfirm,+ isMoving,+ } = useMoveToFolderDialog({+ move,+ canMoveToRoot: offerRoot,+ onDone: () => {+ setIsOpen(false);+ onMoved?.();+ },+ });return (<Dialog@@ -56,42 +59,52 @@ export function MoveToFolderDialog({<Text variant="small" className="mb-1 text-zinc-500">Move {subject} to:</Text>- {canMoveToRoot && (- <Button- variant="ghost"- className="w-full justify-start gap-3 px-3 py-2.5"- onClick={() => handleMove(null)}- data-testid="move-to-root"- >- <Icon icon={Home01Icon} size={18} className="text-zinc-500" />- <Text variant="small-medium">Files (root)</Text>- </Button>- )}- {destinationFolders.length === 0 ? (+ {rows.length === 0 ? (<div className="flex h-20 items-center justify-center"><Text variant="small" className="text-zinc-400">{folders.length === 0 ? "No folders yet" : "No other folders"}</Text></div>) : (- destinationFolders.map((folder) => {- const style = FOLDER_STYLE;- return (- <Button- key={folder.id}- variant="ghost"- className="w-full justify-start gap-3 px-3 py-2.5"- onClick={() => handleMove(folder.id)}- data-testid="move-to-folder-option"- >- <Icon icon={Folder01Icon} size={18} className={style.icon} />- <Text variant="small-medium">{folder.name}</Text>- </Button>- );- })+ <FolderTree+ rows={rows}+ selectedKey={selectedKey}+ onSelect={select}+ onToggleExpanded={toggleExpanded}+ />)}</div>+ <Dialog.Footer>+ <Button+ type="button"+ variant="secondary"+ size="small"+ onClick={() => setIsOpen(false)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="primary"+ size="small"+ disabled={!canConfirm}+ loading={isMoving}+ onClick={confirm}+ data-testid="confirm-move-to-folder"+ >+ Move+ </Button>+ </Dialog.Footer></Dialog.Content></Dialog>);}++function defaultCanMoveToRoot(+ move: MoveSubject,+ folders: { id: string; parent_id?: string | null }[],+): boolean {+ if (move.kind === "files") return move.currentFolderId != null;+ const self = folders.find((folder) => folder.id === move.folderId);+ return (self?.parent_id ?? null) !== null;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/__tests__/MoveToFolderDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/__tests__/MoveToFolderDialog.test.tsxnew file mode 100644index 0000000000..ab38662b08--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/__tests__/MoveToFolderDialog.test.tsx@@ -0,0 +1,128 @@+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 { MoveToFolderDialog } from "../MoveToFolderDialog";++vi.mock("framer-motion", async (importActual) => {+ const actual = await importActual<typeof import("framer-motion")>();+ return { ...actual, useReducedMotion: () => true };+});++const PROXY = "/api/proxy/api/workspace";++// Files / Reports / 2026 / Q3, plus a sibling at the root.+const FOLDERS = [+ folder("fld-1", "Reports", null),+ folder("fld-2", "2026", "fld-1"),+ folder("fld-3", "Q3", "fld-2"),+ folder("fld-9", "Archive", null),+];++beforeEach(() => {+ server.use(+ http.get(`${PROXY}/folders`, async () => {+ // The dialog mounts before the folders land — a cold cache, which is+ // what a lazy `useState` initialiser cannot see.+ await new Promise((resolve) => setTimeout(resolve, 60));+ return HttpResponse.json({ folders: FOLDERS });+ }),+ );+});++describe("MoveToFolderDialog", () => {+ test("opens on the subject's own branch even when the folders arrive late", async () => {+ render(+ <MoveToFolderDialog+ move={{ kind: "folder", folderId: "fld-2" }}+ subject="“2026”"+ isOpen+ setIsOpen={() => {}}+ />,+ );++ // "2026" is two levels down, so it is only visible if both its parent and+ // its own row were expanded once the query settled.+ expect(await screen.findByText("2026")).toBeDefined();+ await waitFor(() => expect(screen.getByText("Q3")).toBeDefined());++ const rows = screen.getAllByTestId("move-to-folder-option");+ const subject = rows.find((r) => r.textContent?.includes("2026"));+ expect(subject?.textContent).toContain("Folder being moved");+ const parent = rows.find((r) => r.textContent?.startsWith("Reports"));+ expect(parent?.textContent).toContain("Current location");+ });++ test("moves a selection spread across folders to the root", async () => {+ let movedTo: unknown = "not called";+ server.use(+ http.post(`${PROXY}/folders/files/bulk-move`, async ({ request }) => {+ movedTo = ((await request.json()) as { folder_id: unknown }).folder_id;+ return HttpResponse.json({});+ }),+ );+ // What SelectionBar passes when the selected files sit in different folders.+ render(+ <MoveToFolderDialog+ move={{ kind: "files", fileIds: ["a", "b"], currentFolderId: null }}+ canMoveToRoot+ subject="2 files"+ isOpen+ setIsOpen={() => {}}+ />,+ );++ const root = await screen.findByText("Files (root)");+ await screen.findByText("Reports");+ expect(root.closest("[role=treeitem]")?.textContent).not.toContain(+ "Current location",+ );+ fireEvent.click(root);+ fireEvent.click(screen.getByTestId("confirm-move-to-folder"));+ await waitFor(() => expect(movedTo).toBeNull());+ });++ test("moves to a selected folder after its parent row is collapsed", async () => {+ let movedTo: unknown = "not called";+ server.use(+ http.post(`${PROXY}/folders/files/bulk-move`, async ({ request }) => {+ movedTo = ((await request.json()) as { folder_id: unknown }).folder_id;+ return HttpResponse.json({});+ }),+ );+ render(+ <MoveToFolderDialog+ move={{ kind: "files", fileIds: ["file-1"], currentFolderId: "fld-2" }}+ subject="“a.txt”"+ isOpen+ setIsOpen={() => {}}+ />,+ );++ fireEvent.click(await screen.findByText("Q3"));+ fireEvent.click(screen.getByRole("button", { name: "Collapse Reports" }));+ await waitFor(() => expect(screen.queryByText("Q3")).toBeNull());++ const move = screen.getByTestId("confirm-move-to-folder");+ expect(move.hasAttribute("disabled")).toBe(false);+ fireEvent.click(move);+ await waitFor(() => expect(movedTo).toBe("fld-3"));+ });+});++function folder(id: string, name: string, parentId: string | null) {+ return {+ id,+ workspace_id: "ws-1",+ name,+ parent_id: parentId,+ file_count: 0,+ created_at: "2026-09-01T00:00:00Z",+ updated_at: "2026-09-01T00:00:00Z",+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/components/FolderTree.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/components/FolderTree.tsxnew file mode 100644index 0000000000..1faf6116f2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/components/FolderTree.tsx@@ -0,0 +1,163 @@+"use client";++import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { cn } from "@/lib/utils";+import { isKey } from "@/lib/keyboard";+import {+ ArrowRight01Icon,+ Folder01Icon,+ Home01Icon,+} from "@hugeicons/core-free-icons";+import type { KeyboardEvent } from "react";+import { useRef } from "react";+import { FOLDER_STYLE } from "../../WorkspaceFolders/folder-constants";+import { rowKey, type TreeRow } from "../helpers";++interface Props {+ rows: TreeRow[];+ selectedKey: string | null;+ onSelect: (id: string | null) => void;+ onToggleExpanded: (folderId: string) => void;+}++/**+ * WAI-ARIA tree of move destinations. A click selects rather than moves —+ * with a chevron beside every name, a mis-click must not move anything.+ */+export function FolderTree({+ rows,+ selectedKey,+ onSelect,+ onToggleExpanded,+}: Props) {+ const listRef = useRef<HTMLUListElement>(null);+ // One row in the tab order: the selected one, else the first.+ const tabbableIndex = Math.max(+ 0,+ rows.findIndex((row) => rowKey(row.id) === selectedKey),+ );++ function focusRow(index: number) {+ const clamped = Math.min(Math.max(index, 0), rows.length - 1);+ const items =+ listRef.current?.querySelectorAll<HTMLLIElement>('[role="treeitem"]');+ items?.[clamped]?.focus();+ }++ function handleKeyDown(e: KeyboardEvent<HTMLLIElement>, index: number) {+ const row = rows[index];+ if (isKey(e, "ArrowDown")) {+ e.preventDefault();+ focusRow(index + 1);+ } else if (isKey(e, "ArrowUp")) {+ e.preventDefault();+ focusRow(index - 1);+ } else if (isKey(e, "Home")) {+ e.preventDefault();+ focusRow(0);+ } else if (isKey(e, "End")) {+ e.preventDefault();+ focusRow(rows.length - 1);+ } else if (isKey(e, "ArrowRight")) {+ if (!row.hasChildren) return;+ e.preventDefault();+ if (row.isExpanded) focusRow(index + 1);+ else if (row.id) onToggleExpanded(row.id);+ } else if (isKey(e, "ArrowLeft")) {+ if (!row.isExpanded) return;+ e.preventDefault();+ if (row.id) onToggleExpanded(row.id);+ } else if (isKey(e, "Enter", " ")) {+ e.preventDefault();+ if (!row.disabledReason) onSelect(row.id);+ }+ }++ return (+ <ul+ ref={listRef}+ role="tree"+ aria-label="Destination folders"+ className="max-h-[20rem] overflow-y-auto py-1"+ >+ {rows.map((row, index) => {+ const key = rowKey(row.id);+ const isSelected = key === selectedKey;+ const isDisabled = row.disabledReason !== null;+ return (+ <li+ key={key}+ role="treeitem"+ aria-level={row.level}+ aria-selected={isSelected}+ aria-disabled={isDisabled || undefined}+ aria-expanded={row.hasChildren ? row.isExpanded : undefined}+ tabIndex={index === tabbableIndex ? 0 : -1}+ onKeyDown={(e) => handleKeyDown(e, index)}+ onClick={() => !isDisabled && onSelect(row.id)}+ style={{ paddingLeft: `${(row.level - 1) * 20 + 8}px` }}+ className={cn(+ "flex items-center gap-2 rounded-lg py-2 pr-2 outline-none",+ isDisabled+ ? "cursor-not-allowed text-zinc-400"+ : "cursor-pointer text-zinc-800 hover:bg-zinc-50",+ isSelected && "bg-zinc-100",+ "focus-visible:ring-2 focus-visible:ring-zinc-300",+ )}+ data-testid="move-to-folder-option"+ >+ {row.hasChildren && row.id ? (+ <button+ type="button"+ tabIndex={-1}+ aria-label={`${row.isExpanded ? "Collapse" : "Expand"} ${row.name}`}+ onClick={(e) => {+ e.stopPropagation();+ onToggleExpanded(row.id as string);+ }}+ className="flex h-[18px] w-[22px] shrink-0 items-center justify-center rounded text-zinc-400 hover:bg-zinc-200 hover:text-zinc-600"+ >+ <Icon+ icon={ArrowRight01Icon}+ size={14}+ className={cn(+ "transition-transform",+ row.isExpanded && "rotate-90",+ )}+ />+ </button>+ ) : (+ <span className="w-[22px] shrink-0" aria-hidden />+ )}+ <Icon+ icon={row.id === null ? Home01Icon : Folder01Icon}+ size={18}+ className={cn(+ "shrink-0",+ isDisabled ? "text-zinc-300" : FOLDER_STYLE.icon,+ )}+ />+ <Text+ variant="small-medium"+ as="span"+ className="min-w-0 truncate"+ title={row.name}+ >+ {row.name}+ </Text>+ {row.disabledReason ? (+ <Text+ variant="small"+ as="span"+ className="ml-auto shrink-0 pl-2 text-zinc-400"+ >+ {row.disabledReason}+ </Text>+ ) : null}+ </li>+ );+ })}+ </ul>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/helpers.tsnew file mode 100644index 0000000000..35dabee925--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/helpers.ts@@ -0,0 +1,124 @@+import type { WorkspaceFolder } from "@/app/api/__generated__/models/workspaceFolder";+import {+ ancestorsOf,+ childrenOf,+ descendantIdsOf,+} from "../WorkspaceFolders/folderTree";++/** What is being moved: a set of files, or one folder. */+export type MoveSubject =+ | { kind: "files"; fileIds: string[]; currentFolderId?: string | null }+ | { kind: "folder"; folderId: string };++export interface TreeRow {+ /** `null` is the workspace root. */+ id: string | null;+ name: string;+ level: number;+ hasChildren: boolean;+ isExpanded: boolean;+ /** Why this destination is refused, shown beside the name. */+ disabledReason: string | null;+}++/**+ * The rows the tree paints, in order, for the folders currently expanded.+ * Disabled rows stay in the list and stay expandable: a refused folder can+ * still hold a valid destination.+ */+export function buildTreeRows(args: {+ folders: WorkspaceFolder[];+ move: MoveSubject;+ expanded: ReadonlySet<string>;+ canMoveToRoot: boolean;+}): TreeRow[] {+ const { folders, move, expanded, canMoveToRoot } = args;+ const refused = refusedTargets(folders, move);+ const rows: TreeRow[] = [];++ if (canMoveToRoot) {+ rows.push({+ id: null,+ name: "Files (root)",+ level: 1,+ hasChildren: false,+ isExpanded: false,+ disabledReason: refused.get(ROOT_KEY) ?? null,+ });+ }++ function walk(parentId: string | null, level: number) {+ for (const folder of childrenOf(folders, parentId)) {+ const isExpanded = expanded.has(folder.id);+ const hasChildren = childrenOf(folders, folder.id).length > 0;+ rows.push({+ id: folder.id,+ name: folder.name,+ level,+ hasChildren,+ isExpanded: hasChildren && isExpanded,+ disabledReason: refused.get(folder.id) ?? null,+ });+ if (hasChildren && isExpanded) walk(folder.id, level + 1);+ }+ }+ walk(null, 1);+ return rows;+}++/** Ancestors of where the subject sits now, so the tree opens showing it. */+export function initiallyExpanded(+ folders: WorkspaceFolder[],+ move: MoveSubject,+): Set<string> {+ const from =+ move.kind === "folder" ? move.folderId : (move.currentFolderId ?? null);+ if (!from) return new Set();+ return new Set(ancestorsOf(folders, from).map((folder) => folder.id));+}++export function rowKey(id: string | null): string {+ return id ?? ROOT_KEY;+}++/**+ * The destination a selection names, or null once it is refused or gone.+ * Resolved against every folder, not the visible rows: collapsing a selected+ * row's parent must not turn Move into a silent no-op.+ */+export function selectedTarget(args: {+ folders: WorkspaceFolder[];+ move: MoveSubject;+ canMoveToRoot: boolean;+ selectedKey: string | null;+}): { id: string | null } | null {+ const { folders, move, canMoveToRoot, selectedKey } = args;+ if (selectedKey === null) return null;+ if (refusedTargets(folders, move).has(selectedKey)) return null;+ if (selectedKey === ROOT_KEY) return canMoveToRoot ? { id: null } : null;+ return folders.some((f) => f.id === selectedKey) ? { id: selectedKey } : null;+}++const ROOT_KEY = "__root__";++function refusedTargets(+ folders: WorkspaceFolder[],+ move: MoveSubject,+): Map<string, string> {+ const refused = new Map<string, string>();+ if (move.kind === "folder") {+ const self = folders.find((folder) => folder.id === move.folderId);+ refused.set(move.folderId, "Folder being moved");+ for (const id of descendantIdsOf(folders, move.folderId)) {+ refused.set(id, "Inside the folder being moved");+ }+ refused.set(rowKey(self?.parent_id ?? null), "Current location");+ return refused;+ }+ // Null means "at the root" or "spread across folders", and only the first+ // is a location; `canMoveToRoot` already hides the root row in that case.+ if (move.currentFolderId) {+ refused.set(move.currentFolderId, "Current location");+ }+ return refused;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/useMoveToFolderDialog.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/useMoveToFolderDialog.tsnew file mode 100644index 0000000000..6c65c92778--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/MoveToFolderDialog/useMoveToFolderDialog.ts@@ -0,0 +1,72 @@+import { useState } from "react";+import { useArtifactsFolders } from "../../useArtifactsFolders";+import {+ buildTreeRows,+ initiallyExpanded,+ rowKey,+ selectedTarget,+ type MoveSubject,+} from "./helpers";++interface Args {+ move: MoveSubject;+ canMoveToRoot: boolean;+ onDone: () => void;+}++export function useMoveToFolderDialog({ move, canMoveToRoot, onDone }: Args) {+ const { folders, moveFilesToFolder, moveFolder, isMovingFolder } =+ useArtifactsFolders();+ const [selectedKey, setSelectedKey] = useState<string | null>(null);+ // Seeded from the subject's own location, then owned by the user; a later+ // folders refetch must not re-collapse what they opened. The seed waits for+ // the folders query: on a cold cache the first render has nothing to walk,+ // and a lazy initialiser would leave the subject's own branch shut.+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set());+ const [isSeeded, setIsSeeded] = useState(false);+ if (!isSeeded && folders.length > 0) {+ setIsSeeded(true);+ setExpanded(initiallyExpanded(folders, move));+ }+ const [isMovingFiles, setIsMovingFiles] = useState(false);++ const rows = buildTreeRows({ folders, move, expanded, canMoveToRoot });+ const target = selectedTarget({ folders, move, canMoveToRoot, selectedKey });++ function toggleExpanded(folderId: string) {+ setExpanded((prev) => {+ const next = new Set(prev);+ if (next.has(folderId)) next.delete(folderId);+ else next.add(folderId);+ return next;+ });+ }++ function confirm() {+ if (!target) return;+ // Closes only on success; the hook toasts on error and the dialog stays+ // open so the user can pick another destination without reopening it.+ if (move.kind === "folder") {+ const name = folders.find((f) => f.id === move.folderId)?.name ?? "";+ moveFolder({ folderId: move.folderId, parentId: target.id, name })+ .then(onDone)+ .catch(() => {});+ return;+ }+ setIsMovingFiles(true);+ moveFilesToFolder({ fileIds: move.fileIds, folderId: target.id })+ .then(onDone)+ .catch(() => {})+ .finally(() => setIsMovingFiles(false));+ }++ return {+ rows,+ selectedKey,+ select: (id: string | null) => setSelectedKey(rowKey(id)),+ toggleExpanded,+ confirm,+ canConfirm: target !== null,+ isMoving: isMovingFolder || isMovingFiles,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/NewMenu/NewMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/NewMenu/NewMenu.tsxindex d41cc9f61d..5341d73d35 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/NewMenu/NewMenu.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/NewMenu/NewMenu.tsx@@ -20,9 +20,12 @@ import { useNewMenu } from "./useNewMenu";interface Props {selectedFolderId: string | null;+ /** Open folder's name, shown in the create dialog so the destination is+ * visible before the folder is made. */+ selectedFolderName?: string | null;}-export function NewMenu({ selectedFolderId }: Props) {+export function NewMenu({ selectedFolderId, selectedFolderName }: Props) {const {fileInputRef,isUploading,@@ -85,6 +88,9 @@ export function NewMenu({ selectedFolderId }: Props) {isOpen={isCreateOpen}setIsOpen={setIsCreateOpen}mode="create"+ location={+ selectedFolderId ? (selectedFolderName ?? undefined) : undefined+ }isSubmitting={isCreating}onSubmit={handleCreateFolder}/>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/NewMenu/useNewMenu.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/NewMenu/useNewMenu.tsindex 9ec2ce0622..28c1fd2ad9 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/NewMenu/useNewMenu.ts+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/NewMenu/useNewMenu.ts@@ -64,7 +64,7 @@ export function useNewMenu(selectedFolderId: string | null) {}function handleCreateFolder(values: { name: string }) {- createFolder(values)+ createFolder({ ...values, parentId: selectedFolderId }).then(() => setIsCreateOpen(false)).catch(() => {});}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/DeleteFolderDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/DeleteFolderDialog.tsxindex 1302687e42..1f7b67215b 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/DeleteFolderDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/DeleteFolderDialog.tsx@@ -8,6 +8,9 @@ interface Props {isOpen: boolean;setIsOpen: (open: boolean) => void;folderName: string;+ /** Folders that go with it. The delete cascades, so this is the whole+ * subtree, not the direct children the folder rows summarise. */+ subfolderCount: number;isDeleting: boolean;onConfirm: () => void;}@@ -16,6 +19,7 @@ export function DeleteFolderDialog({isOpen,setIsOpen,folderName,+ subfolderCount,isDeleting,onConfirm,}: Props) {@@ -29,8 +33,10 @@ export function DeleteFolderDialog({<div className="flex flex-col gap-4"><Text variant="body" className="text-zinc-600">Delete{" "}- <span className="font-medium">“{folderName}”</span>?- Files inside it will be moved back to the root, not deleted.+ <span className="font-medium">“{folderName}”</span>+ {subfolderCount > 0+ ? ` and its ${subfolderCount} ${subfolderCount === 1 ? "folder" : "folders"}? Files inside them will be moved back to the root, not deleted.`+ : "? Files inside it will be moved back to the root, not deleted."}</Text><div className="flex justify-end gap-2"><Buttondiff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderActionsMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderActionsMenu.tsxnew file mode 100644index 0000000000..7ae8345229--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderActionsMenu.tsx@@ -0,0 +1,88 @@+"use client";++import { Icon } from "@/components/atoms/Icon/Icon";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/molecules/DropdownMenu/DropdownMenu";+import { cn } from "@/lib/utils";+import {+ Delete02Icon,+ Folder01Icon,+ MoreHorizontalIcon,+ PencilEdit02Icon,+} from "@hugeicons/core-free-icons";++interface Props {+ folderName: string;+ onRename: () => void;+ onMove: () => void;+ onDelete: () => void;+ className?: string;+}++export function FolderActionsMenu({+ folderName,+ onRename,+ onMove,+ onDelete,+ className,+}: Props) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={`Actions for ${folderName}`}+ onClick={(e) => e.stopPropagation()}+ className={cn(+ "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900",+ className,+ )}+ data-testid="folder-actions-menu"+ >+ <Icon icon={MoreHorizontalIcon} size={20} />+ </button>+ </DropdownMenuTrigger>+ {/* preventDefault keeps the menu mounted while the dialog opens, so the+ menu's focus return doesn't fight the dialog for focus. */}+ <DropdownMenuContent align="end" className="w-44">+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault();+ onRename();+ }}+ data-testid="folder-rename-menu"+ >+ <Icon icon={PencilEdit02Icon} size={16} className="mr-2" />+ Rename+ </DropdownMenuItem>+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault();+ onMove();+ }}+ data-testid="folder-move-menu"+ >+ <Icon icon={Folder01Icon} size={16} className="mr-2" />+ Move to folder+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault();+ onDelete();+ }}+ className="text-red-600 focus:bg-red-50 focus:text-red-700"+ data-testid="folder-delete-menu"+ >+ <Icon icon={Delete02Icon} size={16} className="mr-2" />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderBreadcrumb.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderBreadcrumb.tsxindex a909d24fa4..1e3432b9ac 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderBreadcrumb.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderBreadcrumb.tsx@@ -1,35 +1,152 @@"use client";import { Text } from "@/components/atoms/Text/Text";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/molecules/DropdownMenu/DropdownMenu";import { ArrowRight01Icon, Home01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { cn } from "@/lib/utils";++export interface BreadcrumbItem {+ id: string;+ name: string;+}interface Props {- folderName: string;- onBack: () => void;+ /** Ancestors first, the open folder last. */+ items: BreadcrumbItem[];+ /** `null` navigates to the root. */+ onNavigate: (folderId: string | null) => void;+ /** Compact type and spacing, for the file picker inside a dialog. */+ compact?: boolean;}-export function FolderBreadcrumb({ folderName, onBack }: Props) {+// `⌂ Files › Reports › 2026 › Q3` is the widest chain shown whole; past that+// everything between the root and the parent collapses behind the "…" menu,+// so the root, the parent and the current folder always stay visible.+const MAX_CRUMBS_BESIDE_ROOT = 3;++export function FolderBreadcrumb({ items, onNavigate, compact }: Props) {+ const { hidden, visible } = splitForOverflow(items);+ const separator = (+ <Icon+ icon={ArrowRight01Icon}+ size={compact ? 12 : 14}+ className="shrink-0 text-zinc-400"+ aria-hidden+ />+ );+return (<nav- className="flex items-center gap-1.5 text-zinc-500"aria-label="Breadcrumb"data-testid="folder-breadcrumb"+ className="min-w-0">- <button- type="button"- onClick={onBack}- className="inline-flex items-center gap-1.5 rounded-md px-1.5 py-1 hover:bg-zinc-100 hover:text-zinc-800"- data-testid="folder-breadcrumb-root"+ <ol+ className={cn(+ "flex min-w-0 items-center gap-1.5 text-zinc-500",+ compact && "gap-1",+ )}>- <Icon icon={Home01Icon} size={16} />- <Text variant="small-medium" as="span">- Files- </Text>- </button>- <Icon icon={ArrowRight01Icon} size={14} className="text-zinc-400" />- <Text variant="small-medium" as="span" className="text-zinc-800">- {folderName}- </Text>+ <li className="flex shrink-0 items-center">+ <button+ type="button"+ onClick={() => onNavigate(null)}+ className={CRUMB_BUTTON_CLASS}+ data-testid="folder-breadcrumb-root"+ >+ <Icon icon={Home01Icon} size={compact ? 14 : 16} />+ <Text variant="small-medium" as="span">+ Files+ </Text>+ </button>+ </li>+ {hidden.length > 0 ? (+ <li className="flex shrink-0 items-center gap-1.5">+ {separator}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label="Show hidden folders"+ className={CRUMB_BUTTON_CLASS}+ data-testid="folder-breadcrumb-overflow"+ >+ <Text variant="small-medium" as="span">+ …+ </Text>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-48">+ {hidden.map((item) => (+ <DropdownMenuItem+ key={item.id}+ onSelect={() => onNavigate(item.id)}+ >+ <span className="truncate">{item.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </li>+ ) : null}+ {visible.map((item, index) => {+ const isCurrent = index === visible.length - 1;+ return (+ <li+ key={item.id}+ className={cn(+ "flex min-w-0 items-center gap-1.5",+ isCurrent ? "min-w-0" : "shrink-0",+ )}+ >+ {separator}+ {isCurrent ? (+ <Text+ variant="small-medium"+ as="span"+ aria-current="page"+ className="max-w-[12rem] truncate text-zinc-800"+ title={item.name}+ >+ {item.name}+ </Text>+ ) : (+ <button+ type="button"+ onClick={() => onNavigate(item.id)}+ className={CRUMB_BUTTON_CLASS}+ title={item.name}+ >+ <Text+ variant="small-medium"+ as="span"+ className="max-w-[12rem] truncate"+ >+ {item.name}+ </Text>+ </button>+ )}+ </li>+ );+ })}+ </ol></nav>);}++const CRUMB_BUTTON_CLASS =+ "inline-flex min-w-0 items-center gap-1.5 rounded-md px-1.5 py-1 hover:bg-zinc-100 hover:text-zinc-800";++function splitForOverflow(items: BreadcrumbItem[]): {+ hidden: BreadcrumbItem[];+ visible: BreadcrumbItem[];+} {+ if (items.length <= MAX_CRUMBS_BESIDE_ROOT)+ return { hidden: [], visible: items };+ return { hidden: items.slice(0, -2), visible: items.slice(-2) };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderDialogs.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderDialogs.tsxindex 3455e7ac29..dbfa962f78 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderDialogs.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderDialogs.tsx@@ -2,26 +2,36 @@import type { WorkspaceFolder } from "@/app/api/__generated__/models/workspaceFolder";import { useArtifactsFolders } from "../../useArtifactsFolders";+import { MoveToFolderDialog } from "../MoveToFolderDialog/MoveToFolderDialog";import { DeleteFolderDialog } from "./DeleteFolderDialog";import { FolderFormDialog } from "./FolderFormDialog";+import { descendantIdsOf } from "./folderTree";interface Props {editing: WorkspaceFolder | null;+ moving: WorkspaceFolder | null;deleting: WorkspaceFolder | null;onEditClose: () => void;+ onMoveClose: () => void;onDeleteClose: () => void;+ /** Called with the deleted folder once the delete succeeds, so the page can+ * leave a folder that no longer exists. */+ onDeleted?: (folder: WorkspaceFolder) => void;}-// Rename + delete dialogs shared by the folder cards (grid view) and folder-// rows (list view). Dialogs close only on success; the hook toasts on error-// so the user's input isn't lost.+// Rename + move + delete dialogs shared by the folder cards (grid view) and+// folder rows (list view). Dialogs close only on success; the hook toasts on+// error so the user's input isn't lost.export function FolderDialogs({editing,+ moving,deleting,onEditClose,+ onMoveClose,onDeleteClose,+ onDeleted,}: Props) {- const { updateFolder, isUpdating, deleteFolder, isDeleting } =+ const { folders, updateFolder, isUpdating, deleteFolder, isDeleting } =useArtifactsFolders();return (@@ -39,15 +49,29 @@ export function FolderDialogs({.catch(() => {});}}/>+ {moving && (+ <MoveToFolderDialog+ move={{ kind: "folder", folderId: moving.id }}+ subject={`“${moving.name}”`}+ isOpen+ setIsOpen={(open) => !open && onMoveClose()}+ />+ )}<DeleteFolderDialogisOpen={deleting !== null}setIsOpen={(open) => !open && onDeleteClose()}folderName={deleting?.name ?? ""}+ subfolderCount={+ deleting ? descendantIdsOf(folders, deleting.id).size : 0+ }isDeleting={isDeleting}onConfirm={() => {if (!deleting) return;deleteFolder(deleting.id)- .then(onDeleteClose)+ .then(() => {+ onDeleted?.(deleting);+ onDeleteClose();+ }).catch(() => {});}}/>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderFormDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderFormDialog.tsxindex cfd8501939..28ad8a0ba2 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderFormDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderFormDialog.tsx@@ -3,6 +3,7 @@import { useEffect, useState } from "react";import { Button } from "@/components/atoms/Button/Button";import { Input } from "@/components/atoms/Input/Input";+import { Text } from "@/components/atoms/Text/Text";import { Dialog } from "@/components/molecules/Dialog/Dialog";import { isKey } from "@/lib/keyboard";@@ -11,6 +12,8 @@ interface Props {setIsOpen: (open: boolean) => void;mode: "create" | "edit";initialName?: string;+ /** Folder the new one lands in, shown under the input. Absent at the root. */+ location?: string;isSubmitting: boolean;onSubmit: (values: { name: string }) => void;}@@ -20,6 +23,7 @@ export function FolderFormDialog({setIsOpen,mode,initialName = "",+ location,isSubmitting,onSubmit,}: Props) {@@ -60,6 +64,11 @@ export function FolderFormDialog({className="w-full"wrapperClassName="!mb-0"/>+ {location ? (+ <Text variant="small" className="text-zinc-500">+ Inside “{location}”+ </Text>+ ) : null}<Buttonvariant="primary"className="mt-2"diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolder.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolder.tsxindex 0fd71c4917..5798fdb0f0 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolder.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolder.tsx@@ -1,15 +1,12 @@"use client";import { useState } from "react";-import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { FILE_DRAG_MIME, readFileDragIds } from "./drag";+import { FolderActionsMenu } from "./FolderActionsMenu";+import { folderSummary } from "./folderTree";import { FOLDER_STYLE } from "./folder-constants";-import {- Delete02Icon,- Folder01Icon,- PencilIcon,-} from "@hugeicons/core-free-icons";+import { Folder01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";import { isKey } from "@/lib/keyboard";@@ -17,7 +14,9 @@ interface Props {id: string;name: string;fileCount: number;+ subfolderCount: number;onEdit: () => void;+ onMove: () => void;onDelete: () => void;onClick: () => void;onFileDrop: (fileIds: string[], folderId: string) => void;@@ -27,7 +26,9 @@ export function WorkspaceFolder({id,name,fileCount,+ subfolderCount,onEdit,+ onMove,onDelete,onClick,onFileDrop,@@ -92,34 +93,16 @@ export function WorkspaceFolder({{name}</Text><Text variant="small" className="text-zinc-500">- {fileCount} {fileCount === 1 ? "file" : "files"}+ {folderSummary(fileCount, subfolderCount)}</Text></div>- <div className="flex items-center gap-1 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100">- <Button- variant="icon"- size="icon"- aria-label="Rename folder"- onClick={(e) => {- e.stopPropagation();- onEdit();- }}- className="h-9 w-9 !p-2 text-zinc-500 hover:text-zinc-800"- >- <Icon icon={PencilIcon} size={16} />- </Button>- <Button- variant="icon"- size="icon"- aria-label="Delete folder"- onClick={(e) => {- e.stopPropagation();- onDelete();- }}- className="h-9 w-9 !p-2 text-zinc-500 hover:text-red-600"- >- <Icon icon={Delete02Icon} size={16} />- </Button>+ <div className="flex items-center opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100">+ <FolderActionsMenu+ folderName={name}+ onRename={onEdit}+ onMove={onMove}+ onDelete={onDelete}+ /></div></div>);diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolders.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolders.tsxindex 033f8d1e31..84bdf1cd4b 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolders.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolders.tsx@@ -7,17 +7,21 @@ import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";import type { WorkspaceFolder as WorkspaceFolderModel } from "@/app/api/__generated__/models/workspaceFolder";import { useArtifactsFolders } from "../../useArtifactsFolders";import { FolderDialogs } from "./FolderDialogs";+import { childrenOf, subfolderCountOf } from "./folderTree";import { WorkspaceFolder } from "./WorkspaceFolder";interface Props {+ /** Folder whose children are shown; `null` is the workspace root. */+ parentId: string | null;onSelectFolder: (folderId: string) => void;}-export function WorkspaceFolders({ onSelectFolder }: Props) {+export function WorkspaceFolders({ parentId, onSelectFolder }: Props) {const { folders, isLoading, isError, error, moveFilesToFolder } =useArtifactsFolders();const [editing, setEditing] = useState<WorkspaceFolderModel | null>(null);+ const [moving, setMoving] = useState<WorkspaceFolderModel | null>(null);const [deleting, setDeleting] = useState<WorkspaceFolderModel | null>(null);if (isLoading) {@@ -41,7 +45,8 @@ export function WorkspaceFolders({ onSelectFolder }: Props) {);}- if (folders.length === 0) return null;+ const children = childrenOf(folders, parentId);+ if (children.length === 0) return null;return (<div className="flex flex-col gap-3" data-testid="workspace-folders">@@ -49,14 +54,16 @@ export function WorkspaceFolders({ onSelectFolder }: Props) {Folders</Text><div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">- {folders.map((folder) => (+ {children.map((folder) => (<WorkspaceFolderkey={folder.id}id={folder.id}name={folder.name}fileCount={folder.file_count ?? 0}+ subfolderCount={subfolderCountOf(folders, folder.id)}onClick={() => onSelectFolder(folder.id)}onEdit={() => setEditing(folder)}+ onMove={() => setMoving(folder)}onDelete={() => setDeleting(folder)}onFileDrop={(fileIds, folderId) => {moveFilesToFolder({ fileIds, folderId }).catch(() => {});@@ -66,8 +73,10 @@ export function WorkspaceFolders({ onSelectFolder }: Props) {</div><FolderDialogsediting={editing}+ moving={moving}deleting={deleting}onEditClose={() => setEditing(null)}+ onMoveClose={() => setMoving(null)}onDeleteClose={() => setDeleting(null)}/></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/folderTree.test.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/folderTree.test.tsnew file mode 100644index 0000000000..ce2ed8a5fd--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/folderTree.test.ts@@ -0,0 +1,137 @@+import { describe, expect, test } from "vitest";+import type { WorkspaceFolder } from "@/app/api/__generated__/models/workspaceFolder";+import {+ ancestorsOf,+ childrenOf,+ descendantIdsOf,+ folderSummary,+ subfolderCountOf,+} from "./folderTree";++function folder(+ id: string,+ name: string,+ parentId: string | null = null,+): WorkspaceFolder {+ return {+ id,+ workspace_id: "ws-1",+ name,+ parent_id: parentId,+ created_at: new Date("2026-01-01T00:00:00Z"),+ updated_at: new Date("2026-01-01T00:00:00Z"),+ file_count: 0,+ };+}++// Files+// Reports+// 2026+// Q3+// Drafts+// Archive+const TREE = [+ folder("reports", "Reports"),+ folder("archive", "Archive"),+ folder("y2026", "2026", "reports"),+ folder("drafts", "Drafts", "reports"),+ folder("q3", "Q3", "y2026"),+];++describe("childrenOf", () => {+ test("returns root folders sorted by name for a null parent", () => {+ expect(childrenOf(TREE, null).map((f) => f.name)).toEqual([+ "Archive",+ "Reports",+ ]);+ });++ test("returns only direct children of a folder", () => {+ expect(childrenOf(TREE, "reports").map((f) => f.name)).toEqual([+ "2026",+ "Drafts",+ ]);+ });++ test("treats a missing parent_id as root", () => {+ const legacy = [{ ...folder("a", "A"), parent_id: undefined }];+ expect(childrenOf(legacy, null).map((f) => f.id)).toEqual(["a"]);+ });++ test("returns nothing for a leaf", () => {+ expect(childrenOf(TREE, "q3")).toEqual([]);+ });+});++describe("ancestorsOf", () => {+ test("returns the chain root first, the folder itself last", () => {+ expect(ancestorsOf(TREE, "q3").map((f) => f.name)).toEqual([+ "Reports",+ "2026",+ "Q3",+ ]);+ });++ test("returns just the folder when it sits at the root", () => {+ expect(ancestorsOf(TREE, "reports").map((f) => f.name)).toEqual([+ "Reports",+ ]);+ });++ test("returns nothing for an unknown id", () => {+ expect(ancestorsOf(TREE, "gone")).toEqual([]);+ });++ test("stops at a parent the list does not contain", () => {+ const orphan = [folder("child", "Child", "missing-parent")];+ expect(ancestorsOf(orphan, "child").map((f) => f.name)).toEqual(["Child"]);+ });++ test("stops on a cycle instead of looping forever", () => {+ const cyclic = [folder("a", "A", "b"), folder("b", "B", "a")];+ expect(ancestorsOf(cyclic, "a").map((f) => f.name)).toEqual(["B", "A"]);+ });+});++describe("descendantIdsOf", () => {+ test("collects the whole subtree, excluding the folder itself", () => {+ expect([...descendantIdsOf(TREE, "reports")].sort()).toEqual([+ "drafts",+ "q3",+ "y2026",+ ]);+ });++ test("is empty for a leaf", () => {+ expect(descendantIdsOf(TREE, "q3").size).toBe(0);+ });++ test("terminates on a cycle", () => {+ const cyclic = [folder("a", "A", "b"), folder("b", "B", "a")];+ expect([...descendantIdsOf(cyclic, "a")].sort()).toEqual(["a", "b"]);+ });+});++describe("subfolderCountOf", () => {+ test("counts direct children only", () => {+ expect(subfolderCountOf(TREE, "reports")).toBe(2);+ expect(subfolderCountOf(TREE, "y2026")).toBe(1);+ expect(subfolderCountOf(TREE, "q3")).toBe(0);+ });+});++describe("folderSummary", () => {+ test("prefers the direct file count", () => {+ expect(folderSummary(3, 2)).toBe("3 files");+ expect(folderSummary(1, 0)).toBe("1 file");+ });++ test("falls back to subfolders when there are no direct files", () => {+ expect(folderSummary(0, 2)).toBe("2 folders");+ expect(folderSummary(0, 1)).toBe("1 folder");+ });++ test("reads Empty when the folder holds neither", () => {+ expect(folderSummary(0, 0)).toBe("Empty");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/folderTree.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/folderTree.tsnew file mode 100644index 0000000000..4edd541ae5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/folderTree.ts@@ -0,0 +1,89 @@+import type { WorkspaceFolder } from "@/app/api/__generated__/models/workspaceFolder";++/**+ * Nesting read off the flat `GET /folders` list. Every walk is bounded by the+ * number of folders, so a `parent_id` cycle the API should never produce stops+ * instead of hanging the render.+ */++export function childrenOf(+ folders: WorkspaceFolder[],+ parentId: string | null,+): WorkspaceFolder[] {+ return folders+ .filter((folder) => (folder.parent_id ?? null) === parentId)+ .sort((a, b) => a.name.localeCompare(b.name));+}++/** Root first, the folder itself last. Empty when the id is unknown. */+export function ancestorsOf(+ folders: WorkspaceFolder[],+ folderId: string,+): WorkspaceFolder[] {+ const byId = indexById(folders);+ const chain: WorkspaceFolder[] = [];+ const seen = new Set<string>();+ let current = byId.get(folderId);+ while (current && !seen.has(current.id)) {+ seen.add(current.id);+ chain.push(current);+ const parentId = current.parent_id ?? null;+ current = parentId ? byId.get(parentId) : undefined;+ }+ return chain.reverse();+}++/** Every folder under `folderId`, excluding the folder itself. */+export function descendantIdsOf(+ folders: WorkspaceFolder[],+ folderId: string,+): Set<string> {+ const byParent = indexByParent(folders);+ const found = new Set<string>();+ const queue = [folderId];+ while (queue.length > 0) {+ const id = queue.shift() as string;+ for (const child of byParent.get(id) ?? []) {+ if (found.has(child.id)) continue;+ found.add(child.id);+ queue.push(child.id);+ }+ }+ return found;+}++export function subfolderCountOf(+ folders: WorkspaceFolder[],+ folderId: string,+): number {+ return folders.filter((folder) => (folder.parent_id ?? null) === folderId)+ .length;+}++/**+ * The one-line summary a folder gets wherever it is not being browsed —+ * direct counts only, so it never claims a subtree total it did not count.+ */+export function folderSummary(fileCount: number, subfolderCount: number) {+ if (fileCount > 0)+ return `${fileCount} ${fileCount === 1 ? "file" : "files"}`;+ if (subfolderCount > 0)+ return `${subfolderCount} ${subfolderCount === 1 ? "folder" : "folders"}`;+ return "Empty";+}++function indexById(folders: WorkspaceFolder[]) {+ return new Map(folders.map((folder) => [folder.id, folder]));+}++function indexByParent(folders: WorkspaceFolder[]) {+ const byParent = new Map<string, WorkspaceFolder[]>();+ for (const folder of folders) {+ const parentId = folder.parent_id ?? null;+ if (parentId === null) continue;+ const siblings = byParent.get(parentId);+ if (siblings) siblings.push(folder);+ else byParent.set(parentId, [folder]);+ }+ return byParent;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsxindex c9e13d7387..21ecb00ee3 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx@@ -18,6 +18,10 @@ import { OriginFilter } from "./components/OriginFilter/OriginFilter";import { StorageUsage } from "./components/StorageUsage/StorageUsage";import { ViewToggle } from "./components/ViewToggle/ViewToggle";import { FolderBreadcrumb } from "./components/WorkspaceFolders/FolderBreadcrumb";+import {+ ancestorsOf,+ childrenOf,+} from "./components/WorkspaceFolders/folderTree";import { useArtifactsFolders } from "./useArtifactsFolders";import { useArtifactsPage } from "./useArtifactsPage";@@ -82,23 +86,30 @@ export default function ArtifactsPage() {const isSearching = searchTerm.length > 0;const isInFolder = selectedFolderId !== null;- const isFilteringByExpert = expertFilter !== null;const selectedFolder = folders.find((f) => f.id === selectedFolderId);- const showFolders = !isInFolder && !isSearching && !isFilteringByExpert;- const hasFolders = showFolders && folders.length > 0;- // At the root the empty state depends on whether folders exist, so hold- // the loading state until both queries have settled.+ // Folders are the container an expert filter narrows inside, so only a+ // search — which spans every folder — replaces them with a flat list.+ const showFolders = !isSearching;+ const hasFolders =+ showFolders && childrenOf(folders, selectedFolderId).length > 0;+ // The empty state depends on whether child folders exist, so hold the+ // loading state until both queries have settled.const isListLoading = isLoading || (showFolders && isFoldersLoading);+ // Until the folders query settles the open folder's name is unknown, so the+ // crumb stands in with the generic label rather than flickering a wrong one.+ const breadcrumbItems = isInFolder+ ? selectedFolder+ ? ancestorsOf(folders, selectedFolder.id).map((folder) => ({+ id: folder.id,+ name: folder.name,+ }))+ : [{ id: selectedFolderId, name: "Folder" }]+ : [];useEffect(() => {document.title = "Files – AutoGPT Platform";}, []);- function handleExpertFilterChange(expertId: string | null) {- setExpertFilter(expertId);- if (expertId) closeFolder();- }-if (!flagReady) {return <ArtifactsPageSkeleton showNewLayout={showNewLayout} />;}@@ -149,7 +160,10 @@ export default function ArtifactsPage() {searchTerm={searchTerm}setSearchTerm={setSearchTerm}/>- <NewMenu selectedFolderId={selectedFolderId} />+ <NewMenu+ selectedFolderId={selectedFolderId}+ selectedFolderName={selectedFolder?.name}+ /></motion.div></div><div className="flex flex-wrap items-center justify-between gap-4">@@ -164,7 +178,7 @@ export default function ArtifactsPage() {<ExpertFilterexperts={activeExperts}value={expertFilter}- onChange={handleExpertFilterChange}+ onChange={setExpertFilter}/></motion.div><motion.div@@ -184,8 +198,10 @@ export default function ArtifactsPage() {transition={{ delay: reduceMotion ? 0 : 0.24 }}><FolderBreadcrumb- folderName={selectedFolder?.name ?? "Folder"}- onBack={closeFolder}+ items={breadcrumbItems}+ onNavigate={(folderId) =>+ folderId === null ? closeFolder() : openFolder(folderId)+ }/></motion.div>) : null}@@ -219,6 +235,7 @@ export default function ArtifactsPage() {listKey={`${originFilter}|${expertFilter ?? "everyone"}|${debouncedSearch}|${selectedFolderId ?? "root"}`}view={view}showFolders={showFolders}+ folderParentId={selectedFolderId}onSelectFolder={openFolder}/></motion.div>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsFolders.test.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsFolders.test.tsnew file mode 100644index 0000000000..38af2cbb79--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsFolders.test.ts@@ -0,0 +1,26 @@+import { describe, expect, test } from "vitest";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { describeFolderMoveError } from "./useArtifactsFolders";++describe("describeFolderMoveError", () => {+ test("names the folder on a clash at the destination", () => {+ expect(+ describeFolderMoveError(new ApiError("conflict", 409, null), "Q3"),+ ).toBe("A folder named “Q3” is already there");+ });++ test("explains a refused cycle", () => {+ expect(+ describeFolderMoveError(new ApiError("bad request", 400, null), "Q3"),+ ).toBe("A folder can't be moved into itself");+ });++ test("falls back for anything else, including a non-API failure", () => {+ expect(describeFolderMoveError(new ApiError("boom", 500, null), "Q3")).toBe(+ "Failed to move folder",+ );+ expect(describeFolderMoveError(new Error("offline"), "Q3")).toBe(+ "Failed to move folder",+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsFolders.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsFolders.tsindex c62dcbb330..7b6867d24b 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsFolders.ts+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsFolders.ts@@ -8,6 +8,7 @@ import {useUpdateWorkspaceFolder,} from "@/app/api/__generated__/endpoints/workspace/workspace";import { okData } from "@/app/api/helpers";+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { useToast } from "@/components/molecules/Toast/use-toast";import { ARTIFACTS_LIST_QUERY_KEY } from "./useArtifactsPage";@@ -57,6 +58,17 @@ export function useArtifactsFolders() {},});+ // Its own instance of the same endpoint: a move reports differently from a+ // rename, and the 409/400 the destination can raise have no rename analogue.+ const moveFolderMutation = useUpdateWorkspaceFolder({+ mutation: {+ onSuccess: () => {+ invalidate();+ toast({ title: "Folder moved" });+ },+ },+ });+const deleteMutation = useDeleteWorkspaceFolder({mutation: {onSuccess: () => {@@ -94,8 +106,10 @@ export function useArtifactsFolders() {isLoading: foldersQuery.isLoading,isError: foldersQuery.isError,error: foldersQuery.error,- createFolder: (args: { name: string }) =>- createMutation.mutateAsync({ data: { name: args.name } }),+ createFolder: (args: { name: string; parentId?: string | null }) =>+ createMutation.mutateAsync({+ data: { name: args.name, parent_id: args.parentId ?? null },+ }),isCreating: createMutation.isPending,updateFolder: (args: { folderId: string; name?: string }) =>updateMutation.mutateAsync({@@ -103,6 +117,28 @@ export function useArtifactsFolders() {data: { name: args.name },}),isUpdating: updateMutation.isPending,+ // `parent_id` is sent explicitly on every move, `null` meaning the root;+ // the backend reads `model_fields_set`, so omitting it would mean "stay".+ moveFolder: (args: {+ folderId: string;+ parentId: string | null;+ name: string;+ }) =>+ moveFolderMutation+ .mutateAsync({+ folderId: args.folderId,+ data: { parent_id: args.parentId },+ })+ .catch((error: unknown) => {+ // The name the 409 message needs is not in the request body —+ // sending it would rename the folder — so the toast lives here.+ toast({+ title: describeFolderMoveError(error, args.name),+ variant: "destructive",+ });+ throw error;+ }),+ isMovingFolder: moveFolderMutation.isPending,deleteFolder: (folderId: string) =>deleteMutation.mutateAsync({ folderId }),isDeleting: deleteMutation.isPending,@@ -112,3 +148,10 @@ export function useArtifactsFolders() {}),};}++export function describeFolderMoveError(error: unknown, name: string): string {+ const status = error instanceof ApiError ? error.status : null;+ if (status === 409) return `A folder named “${name}” is already there`;+ if (status === 400) return "A folder can't be moved into itself";+ return "Failed to move folder";+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.tsindex b29f659c59..6039e14f41 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts@@ -1,9 +1,10 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, 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";+import { ancestorsOf } from "./components/WorkspaceFolders/folderTree";export type OriginFilter = "all" | "uploaded" | "generated";export type ArtifactsView = "list" | "grid";@@ -47,11 +48,25 @@ export function useArtifactsPage({!folders.some((folder) => folder.id === folderParam);const selectedFolderId = isStaleFolder ? null : folderParam;+ // Remembered while the folder is live, so deleting it (or an ancestor) can+ // land the user one level up instead of back at the root.+ const ancestorIdsRef = useRef<string[]>([]);+ if (selectedFolderId !== null) {+ ancestorIdsRef.current = ancestorsOf(folders, selectedFolderId)+ .slice(0, -1)+ .map((folder) => folder.id);+ }+const currentSearch = searchParams.toString();useEffect(() => {if (!isStaleFolder) return;- router.replace(folderHref(pathname, currentSearch, null));- }, [isStaleFolder, pathname, currentSearch, router]);+ const survivingAncestor = [...ancestorIdsRef.current]+ .reverse()+ .find((id) => folders.some((folder) => folder.id === id));+ router.replace(+ folderHref(pathname, currentSearch, survivingAncestor ?? null),+ );+ }, [isStaleFolder, pathname, currentSearch, router, folders]);const debouncedSearch = useDebouncedValue(searchTerm.trim(),@@ -60,15 +75,16 @@ export function useArtifactsPage({const q = debouncedSearch || undefined;const origin = originFilter === "all" ? undefined : originFilter;- // An expert filter spans every file from that expert's conversations, so- // the folder axes are dropped: the API rejects combining them.+ // "From: <expert>" narrows the files shown where you are, the way "Type"+ // does. `include_user_files` is left unsent, so the tab keeps meaning "made+ // in this expert's chats".const expertId = expertFilter ?? undefined;// No folder selected → show only root-level files; a folder is selected →// scope the listing to that folder.- const folderId = expertId ? undefined : (selectedFolderId ?? undefined);+ const folderId = selectedFolderId ?? undefined;// While searching, span the whole workspace (including files inside folders)// so global search isn't limited to root-level files.- const rootOnly = !expertId && selectedFolderId === null && !q;+ const rootOnly = selectedFolderId === null && !q;const query = useInfiniteQuery({queryKey: [diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.tsindex 688e26b49c..8c4c56fe0f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts@@ -267,3 +267,59 @@ describe("copilotStreamTransport — expert kickoff routing", () => {expect(out.body.expert_kickoff).toBe(false);});});++describe("copilotStreamTransport - folder attachments", () => {+ async function prepare(parts: unknown[]) {+ const transport = createCopilotTransport({+ sessionId: "sess-folders",+ ...makeRefs(),+ });+ return (+ transport as unknown as {+ prepareSendMessagesRequest: (args: { messages: unknown[] }) => Promise<{+ body: { file_ids: string[] | null; folder_ids: string[] | null };+ }>;+ }+ ).prepareSendMessagesRequest({+ messages: [+ { id: "m1", role: "user" as const, parts, metadata: undefined },+ ],+ });+ }++ const FILE_PART = {+ type: "file" as const,+ mediaType: "text/plain",+ filename: "a.txt",+ url: "/api/proxy/api/workspace/files/file-1/download",+ };+ const FOLDER_PART = {+ type: "data-workspace-folder" as const,+ data: { id: "fld-1", name: "Reports", fileCount: 3 },+ };++ it("sends folder ids beside file ids", async () => {+ const { body } = await prepare([+ { type: "text", text: "look" },+ FILE_PART,+ FOLDER_PART,+ ]);+ expect(body.file_ids).toEqual(["file-1"]);+ expect(body.folder_ids).toEqual(["fld-1"]);+ });++ it("sends folder ids with no files at all", async () => {+ const { body } = await prepare([+ { type: "text", text: "look" },+ FOLDER_PART,+ ]);+ expect(body.file_ids).toBeNull();+ expect(body.folder_ids).toEqual(["fld-1"]);+ });++ it("sends null rather than an empty list when nothing is attached", async () => {+ const { body } = await prepare([{ type: "text", text: "hi" }]);+ expect(body.file_ids).toBeNull();+ expect(body.folder_ids).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.tsxindex 8367a60f48..4ef31d4238 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.tsx@@ -3,7 +3,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { useCopilotStreamStore } from "../copilotStreamStore";import { useCopilotUIStore } from "../store";import { useSendMessage } from "../useSendMessage";-import { MAX_ATTACHMENTS } from "../helpers/workspaceAttachments";+import {+ MAX_ATTACHMENTS,+ type WorkspaceAttachment,+} from "../helpers/workspaceAttachments";const { uploadFileDirectMock, toastMock } = vi.hoisted(() => ({uploadFileDirectMock: vi.fn(),@@ -126,7 +129,14 @@ describe("useSendMessage with local attachments", () => {void result.current.onSend("compare",[makeFile("icon.png", "image/png")],- [{ fileId: FILE_ID, name: "notes.txt", mimeType: "text/plain" }],+ [+ {+ kind: "workspace" as const,+ fileId: FILE_ID,+ name: "notes.txt",+ mimeType: "text/plain",+ },+ ],);});@@ -167,7 +177,14 @@ describe("useSendMessage with local attachments", () => {void result.current.onSend("compare",[makeFile("talk.pdf")],- [{ fileId: FILE_ID, name: "notes.txt", mimeType: "text/plain" }],+ [+ {+ kind: "workspace" as const,+ fileId: FILE_ID,+ name: "notes.txt",+ mimeType: "text/plain",+ },+ ],);});@@ -364,7 +381,7 @@ describe("useSendMessage first send failing after the session exists", () => {async function startFirstSend(text: string,files: File[],- workspaceFiles?: { fileId: string; name: string; mimeType: string }[],+ workspaceFiles?: WorkspaceAttachment[],) {const newChat = renderSendMessage(null);newChat.createSession.mockImplementation(async () => {@@ -405,7 +422,14 @@ describe("useSendMessage first send failing after the session exists", () => {const created = await startFirstSend("compare",[],- [{ fileId: FILE_ID, name: "notes.txt", mimeType: "text/plain" }],+ [+ {+ kind: "workspace" as const,+ fileId: FILE_ID,+ name: "notes.txt",+ mimeType: "text/plain",+ },+ ],);await waitFor(() => expect(created.sendMessage).toHaveBeenCalledTimes(1));@@ -473,6 +497,7 @@ describe("useSendMessage when creating the first chat's session fails", () => {function makeWorkspaceRefs(count: number) {return Array.from({ length: count }, (_, i) => ({+ kind: "workspace" as const,fileId: `${FILE_ID.slice(0, -1)}${i}`,name: `ws-${i}.txt`,mimeType: "text/plain",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex 81ef04cfea..69e62c2875 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -388,6 +388,7 @@ export const ChatContainer = ({hasSession={!!sessionId}sessionId={sessionId}expertId={expertIdentity?.id ?? null}+ expertName={expertIdentity?.name ?? null}voiceToggle={isVoiceModeEnabled ? (<VoiceModeButtondiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsxindex 26ec04894b..5f162eb5c4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx@@ -25,11 +25,14 @@ import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceimport {type Attachment,type WorkspaceAttachment,+ MAX_FOLDER_ATTACHMENTS,appendWithinCap,MAX_ATTACHMENTS,partitionAttachments,+ workspaceFolderToAttachment,workspaceItemToAttachment,} from "../../helpers/workspaceAttachments";+import type { PickedItem } from "./components/WorkspaceFilePicker/useWorkspaceFilePicker";import { AttachmentCapNotice } from "./components/AttachmentCapNotice";import { ComposerPlusMenu } from "./components/ComposerPlusMenu";import { DryRunToggleButton } from "./components/DryRunToggleButton";@@ -101,6 +104,8 @@ interface Props {/** Expert the chat is scoped to. Workspace-file suggestions and the picker* then only offer files from that expert's conversations. */expertId?: string | null;+ /** Names that expert in the picker's filter row. */+ expertName?: string | null;}export function ChatInput({@@ -124,6 +129,7 @@ export function ChatInput({voiceBar,variant = "default",expertId = null,+ expertName = null,}: Props) {const { isDryRun, setIsDryRun } = useCopilotUIStore();// Still the CHAT_MODE_OPTION flag, which no longer names what it gates: the@@ -174,7 +180,8 @@ export function ChatInput({handleChange: baseHandleChange,} = useChatInput({onSend: async (message: string) => {- const { localFiles, workspaceFiles } = partitionAttachments(attachments);+ const { localFiles, workspaceAttachments } =+ partitionAttachments(attachments);// Chips clear eagerly for the same reason the text does (see// useChatInput.handleSend); a failed send restores them unless the// user already attached new ones in the meantime.@@ -185,7 +192,7 @@ export function ChatInput({await onSend(message,localFiles.length > 0 ? localFiles : undefined,- workspaceFiles.length > 0 ? workspaceFiles : undefined,+ workspaceAttachments.length > 0 ? workspaceAttachments : undefined,);} catch (error) {setAttachments((prev) => (prev.length > 0 ? prev : sent));@@ -202,6 +209,8 @@ export function ChatInput({value,setValue,addWorkspaceFile: handleWorkspaceFileSelected,+ addWorkspaceFolder: (folder, subfolderCount) =>+ addAttachments([workspaceFolderToAttachment(folder, subfolderCount)]),expertId,});@@ -276,12 +285,35 @@ export function ChatInput({addAttachments(newFiles.map(toLocalAttachment));}+ function addAttachments(incoming: Attachment[]) {+ // Outside the updater: React re-invokes an updater (twice under+ // StrictMode), which would toast the refusal more than once.+ const { next, refused, refusedFolders } = appendWithinCap(+ attachments,+ incoming,+ );+ setAttachments(next);+ setRefusedCount(refused);+ if (refusedFolders > 0) {+ toast({+ title: `Up to ${MAX_FOLDER_ATTACHMENTS} folders per message`,+ description: `${refusedFolders} not added.`,+ });+ }+ }+function handleWorkspaceFileSelected(item: WorkspaceFileItem) {- handleWorkspaceFilesConfirmed([item]);+ addAttachments([workspaceItemToAttachment(item)]);}- function handleWorkspaceFilesConfirmed(items: WorkspaceFileItem[]) {- addAttachments(items.map(workspaceItemToAttachment));+ function handlePickerConfirmed(items: PickedItem[]) {+ addAttachments(+ items.map((item) =>+ item.kind === "folder"+ ? workspaceFolderToAttachment(item.folder, item.subfolderCount)+ : workspaceItemToAttachment(item.file),+ ),+ );}function handleRemoveAttachment(index: number) {@@ -290,12 +322,6 @@ export function ChatInput({setRefusedCount(0);}- function addAttachments(incoming: Attachment[]) {- const { next, refused } = appendWithinCap(attachments, incoming);- setAttachments(next);- setRefusedCount(refused);- }-const isCompact = variant === "compact";const iconButtonClass = stacked? CARD_ICON_BUTTON_CLASS@@ -312,7 +338,7 @@ export function ChatInput({<form onSubmit={handleSubmit} className={cn("relative flex-1", className)}>{mentions.isOpen && (<MentionDropdown- files={mentions.files}+ options={mentions.options}isLoading={mentions.isLoading}isError={mentions.isError}highlightedIndex={mentions.highlightedIndex}@@ -522,8 +548,9 @@ export function ChatInput({key={expertId ?? "everyone"}isOpen={isPickerOpen}onClose={() => setIsPickerOpen(false)}- onConfirm={handleWorkspaceFilesConfirmed}+ onConfirm={handlePickerConfirmed}expertId={expertId}+ expertName={expertName}/>)}</form>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsxindex fd97c82fc9..1119c25254 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsx@@ -5,8 +5,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { useChatMentions } from "../useChatMentions";const mockListWorkspaceFiles = vi.fn();+const mockFolders = vi.fn(() => ({ data: { folders: [] } }));vi.mock("@/app/api/__generated__/endpoints/workspace/workspace", () => ({listWorkspaceFiles: (...args: unknown[]) => mockListWorkspaceFiles(...args),+ useListWorkspaceFolders: () => mockFolders(),}));const FILE = {@@ -62,6 +64,7 @@ describe("useChatMentions", () => {value: "hi @al",setValue: vi.fn(),addWorkspaceFile: vi.fn(),+ addWorkspaceFolder: vi.fn(),}),{ wrapper: Wrapper },);@@ -69,7 +72,7 @@ describe("useChatMentions", () => {act(() => result.current.detect(fakeTextarea("hi @al")));expect(result.current.isOpen).toBe(true);- await waitFor(() => expect(result.current.files).toHaveLength(1));+ await waitFor(() => expect(result.current.options).toHaveLength(1));await waitFor(() =>expect(mockListWorkspaceFiles).toHaveBeenCalledWith({limit: 8,@@ -86,6 +89,7 @@ describe("useChatMentions", () => {value: "hello world",setValue: vi.fn(),addWorkspaceFile: vi.fn(),+ addWorkspaceFolder: vi.fn(),}),{ wrapper: Wrapper },);@@ -102,6 +106,7 @@ describe("useChatMentions", () => {value: "hi @al",setValue: vi.fn(),addWorkspaceFile: vi.fn(),+ addWorkspaceFolder: vi.fn(),}),{ wrapper: Wrapper },);@@ -125,12 +130,13 @@ describe("useChatMentions", () => {value: "hi @al",setValue,addWorkspaceFile,+ addWorkspaceFolder: vi.fn(),}),{ wrapper: Wrapper },);act(() => result.current.detect(fakeTextarea("hi @al")));- await waitFor(() => expect(result.current.files).toHaveLength(1));+ await waitFor(() => expect(result.current.options).toHaveLength(1));let handled = false;act(() => {@@ -157,12 +163,13 @@ describe("useChatMentions", () => {value: "hi @al",setValue: vi.fn(),addWorkspaceFile,+ addWorkspaceFolder: vi.fn(),}),{ wrapper: Wrapper },);act(() => result.current.detect(fakeTextarea("hi @al")));- await waitFor(() => expect(result.current.files).toHaveLength(1));+ await waitFor(() => expect(result.current.options).toHaveLength(1));act(() => {result.current.onKeyDown(keyEvent("Escape"));@@ -188,12 +195,13 @@ describe("useChatMentions", () => {value: "hi @",setValue: vi.fn(),addWorkspaceFile: vi.fn(),+ addWorkspaceFolder: vi.fn(),}),{ wrapper: Wrapper },);act(() => result.current.detect(fakeTextarea("hi @")));- await waitFor(() => expect(result.current.files).toHaveLength(2));+ await waitFor(() => expect(result.current.options).toHaveLength(2));act(() => {expect(result.current.onKeyDown(keyEvent("ArrowDown"))).toBe(true);@@ -226,12 +234,13 @@ describe("useChatMentions", () => {value: "hi @al",setValue,addWorkspaceFile,+ addWorkspaceFolder: vi.fn(),}),{ wrapper: Wrapper },);act(() => result.current.detect(fakeTextarea("hi @al")));- await waitFor(() => expect(result.current.files).toHaveLength(1));+ await waitFor(() => expect(result.current.options).toHaveLength(1));for (const event of [keyEvent("Enter", true),@@ -264,12 +273,13 @@ describe("useChatMentions", () => {value: "hi @al",setValue,addWorkspaceFile,+ addWorkspaceFolder: vi.fn(),}),{ wrapper: Wrapper },);act(() => result.current.detect(fakeTextarea("hi @al")));- await waitFor(() => expect(result.current.files).toHaveLength(1));+ await waitFor(() => expect(result.current.options).toHaveLength(1));// A shrinking result list can leave the highlighted index pointing past// the end before the clamp effect runs — accepting that must be a no-op,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/FileChips.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/FileChips.tsxindex f41b326bad..9cd6acae8b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/FileChips.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/FileChips.tsx@@ -4,26 +4,18 @@ import { getFileTypeIcon } from "@/app/(platform)/artifacts/components/Artifactsimport { AnimatePresence, motion, useReducedMotion } from "framer-motion";import {type Attachment,+ attachmentKey,attachmentName,} from "../../../helpers/workspaceAttachments";-import { Cancel01Icon, Loading03Icon } from "@hugeicons/core-free-icons";+import { folderSummary } from "@/app/(platform)/artifacts/components/WorkspaceFolders/folderTree";+import {+ Cancel01Icon,+ Folder01Icon,+ Loading03Icon,+} from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";import { cn } from "@/lib/utils";-function attachmentMimeType(attachment: Attachment): string {- return attachment.kind === "local"- ? attachment.file.type- : attachment.mimeType;-}--// Stable key so AnimatePresence animates the element that actually left, not-// whatever shifted into its index.-function attachmentKey(attachment: Attachment): string {- return attachment.kind === "workspace"- ? `ws-${attachment.fileId}`- : `local-${attachment.file.name}-${attachment.file.size}-${attachment.file.lastModified}`;-}-interface Props {attachments: Attachment[];onRemove: (index: number) => void;@@ -70,9 +62,20 @@ export function FileChips({<AnimatePresence initial={false} mode="popLayout">{attachments.map((attachment, index) => {const name = attachmentName(attachment);- const fileIcon = getFileTypeIcon(- attachmentMimeType(attachment),- );+ const isFolder = attachment.kind === "folder";+ const chipIcon = isFolder+ ? Folder01Icon+ : getFileTypeIcon(+ attachment.kind === "local"+ ? attachment.file.type+ : attachment.mimeType,+ );+ const count = isFolder+ ? folderSummary(+ attachment.fileCount,+ attachment.subfolderCount,+ )+ : null;// Workspace files are already stored — only local files show// the upload spinner while a send is in flight.const showSpinner = isUploading && attachment.kind === "local";@@ -102,6 +105,9 @@ export function FileChips({}transition={{ duration: DURATION, ease: EASE_OUT }}style={{ willChange: "transform, opacity, filter" }}+ aria-label={+ isFolder ? `Folder: ${name}, ${count}` : undefined+ }className={cn("inline-flex items-center gap-1 rounded-full bg-zinc-100 px-3 py-1 text-sm text-zinc-700",stacked &&@@ -109,13 +115,16 @@ export function FileChips({)}><Icon- icon={fileIcon}+ icon={chipIcon}className={cn("h-3.5 w-3.5 shrink-0 text-zinc-900",stacked && "text-zinc-400",)}/><span className="max-w-[160px] truncate">{name}</span>+ {count ? (+ <span className="shrink-0 text-zinc-500">· {count}</span>+ ) : null}{showSpinner ? (<Iconicon={Loading03Icon}@@ -124,7 +133,9 @@ export function FileChips({) : (<buttontype="button"- aria-label={`Remove ${name}`}+ aria-label={+ isFolder ? `Remove folder ${name}` : `Remove ${name}`+ }onClick={() => onRemove(index)}className={cn("ml-0.5 rounded-full p-0.5 text-zinc-400 transition-colors hover:bg-zinc-200 hover:text-zinc-600",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/MentionDropdown.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/MentionDropdown.tsxindex 969ddc16aa..1be1cc1d13 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/MentionDropdown.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/MentionDropdown.tsx@@ -1,24 +1,29 @@"use client";import { getFileTypeIcon } from "@/app/(platform)/artifacts/components/ArtifactsList/helpers";-import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import { folderSummary } from "@/app/(platform)/artifacts/components/WorkspaceFolders/folderTree";import { cn } from "@/lib/utils";import type { MutableRefObject } from "react";-import { AlertCircleIcon, Loading03Icon } from "@hugeicons/core-free-icons";+import {+ AlertCircleIcon,+ Folder01Icon,+ Loading03Icon,+} from "@hugeicons/core-free-icons";+import type { MentionOption } from "../useChatMentions";import { Icon } from "@/components/atoms/Icon/Icon";interface Props {- files: WorkspaceFileItem[];+ options: MentionOption[];isLoading: boolean;isError: boolean;highlightedIndex: number;highlightedRef: MutableRefObject<HTMLButtonElement | null>;- onSelect: (item: WorkspaceFileItem) => void;+ onSelect: (option: MentionOption) => void;onHighlight: (index: number) => void;}export function MentionDropdown({- files,+ options,isLoading,isError,highlightedIndex,@@ -26,7 +31,7 @@ export function MentionDropdown({onSelect,onHighlight,}: Props) {- const showEmpty = !isLoading && !isError && files.length === 0;+ const showEmpty = !isLoading && !isError && options.length === 0;return (<div@@ -55,21 +60,26 @@ export function MentionDropdown({{showEmpty && (<p className="px-3 py-2 text-sm text-zinc-500">No matching files.</p>)}- {files.map((file, index) => {+ {options.map((option, index) => {const isHighlighted = index === highlightedIndex;- const fileIcon = getFileTypeIcon(file.mime_type);+ const isFolder = option.kind === "folder";+ const name = isFolder ? option.folder.name : option.file.name;+ const count = isFolder+ ? folderSummary(option.folder.file_count ?? 0, option.subfolderCount)+ : null;return (<button- key={file.id}+ key={isFolder ? `folder-${option.folder.id}` : option.file.id}ref={isHighlighted ? highlightedRef : undefined}type="button"role="option"aria-selected={isHighlighted}+ aria-label={isFolder ? `Folder ${name}, ${count}` : undefined}// preventDefault on mousedown keeps focus in the textarea so the// caret/selection used to strip the @query stays valid.onMouseDown={(e) => {e.preventDefault();- onSelect(file);+ onSelect(option);}}onMouseEnter={() => onHighlight(index)}className={cn(@@ -77,8 +87,16 @@ export function MentionDropdown({isHighlighted ? "bg-zinc-100 text-zinc-900" : "text-zinc-700",)}>- <Icon icon={fileIcon} className="h-4 w-4 shrink-0 text-zinc-900" />- <span className="min-w-0 flex-1 truncate">{file.name}</span>+ <Icon+ icon={+ isFolder ? Folder01Icon : getFileTypeIcon(option.file.mime_type)+ }+ className="h-4 w-4 shrink-0 text-zinc-900"+ />+ <span className="min-w-0 flex-1 truncate">{name}</span>+ {count ? (+ <span className="shrink-0 text-xs text-zinc-500">{count}</span>+ ) : null}</button>);})}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFileList.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFileList.tsxindex 76abb2739c..91920b560b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFileList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFileList.tsx@@ -14,7 +14,13 @@ import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";import { isKey } from "@/lib/keyboard";import { cn } from "@/lib/utils";import type { SelectionModifiers } from "./helpers";-import { type KeyboardEvent, useEffect, useRef, useState } from "react";+import {+ type KeyboardEvent,+ type ReactNode,+ useEffect,+ useRef,+ useState,+} from "react";import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";@@ -28,6 +34,9 @@ interface Props {hasMore: boolean;isLoadingMore: boolean;onLoadMore: () => void;+ emptyMessage: string;+ /** Offered under the empty message, e.g. widening an expert-only listing. */+ emptyAction?: ReactNode;}export function WorkspaceFileList({@@ -40,6 +49,8 @@ export function WorkspaceFileList({hasMore,isLoadingMore,onLoadMore,+ emptyMessage,+ emptyAction,}: Props) {const scrollRef = useRef<HTMLDivElement | null>(null);// Show the top/bottom scroll-fade only when there's content hidden in that@@ -82,9 +93,10 @@ export function WorkspaceFileList({if (files.length === 0) {return (- <p className="py-8 text-center text-sm text-zinc-500">- No files in your workspace yet.- </p>+ <div className="flex flex-col items-center gap-2 py-8">+ <p className="text-center text-sm text-zinc-500">{emptyMessage}</p>+ {emptyAction}+ </div>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsxindex dad3e58d5e..63ef4e53e4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsx@@ -1,19 +1,27 @@"use client";-import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import { FolderBreadcrumb } from "@/app/(platform)/artifacts/components/WorkspaceFolders/FolderBreadcrumb";import { Button } from "@/components/atoms/Button/Button";import { Input } from "@/components/atoms/Input/Input";+import { Switch } from "@/components/atoms/Switch/Switch";+import { Text } from "@/components/atoms/Text/Text";import { Dialog } from "@/components/molecules/Dialog/Dialog";-import { useWorkspaceFilePicker } from "./useWorkspaceFilePicker";+import {+ useWorkspaceFilePicker,+ type PickedItem,+} from "./useWorkspaceFilePicker";import { WorkspaceFileList } from "./WorkspaceFileList";+import { WorkspaceFolderRows } from "./WorkspaceFolderRows";import { Search01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";interface Props {isOpen: boolean;onClose: () => void;- onConfirm: (items: WorkspaceFileItem[]) => void;+ onConfirm: (items: PickedItem[]) => void;expertId?: string | null;+ /** Names the expert in the filter row; falls back to "this expert". */+ expertName?: string | null;}export function WorkspaceFilePicker({@@ -21,6 +29,7 @@ export function WorkspaceFilePicker({onClose,onConfirm,expertId,+ expertName,}: Props) {const picker = useWorkspaceFilePicker({ enabled: isOpen, expertId });@@ -32,12 +41,13 @@ export function WorkspaceFilePicker({}function handleConfirm() {- onConfirm(picker.selectedFiles);+ onConfirm(picker.selectedItems);picker.reset();onClose();}- const selectedCount = picker.selectedFiles.length;+ const who = expertName ?? "this expert";+ const { selectedFileCount: files, selectedFolderCount: folders } = picker;return (<Dialog@@ -67,6 +77,51 @@ export function WorkspaceFilePicker({/></div>+ {expertId ? (+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <Switch+ id="picker-expert-only"+ checked={picker.expertOnly}+ onCheckedChange={picker.setExpertOnly}+ />+ <label htmlFor="picker-expert-only">+ <Text+ variant="small-medium"+ as="span"+ className="text-zinc-700"+ >+ Only {who}’s files+ </Text>+ </label>+ </div>+ <Text variant="small" className="text-zinc-500">+ {picker.expertOnly+ ? `From your chats with ${who}`+ : "Plus your own files and folders"}+ </Text>+ </div>+ ) : null}++ {picker.showFolders && picker.breadcrumb.length > 0 ? (+ <FolderBreadcrumb+ items={picker.breadcrumb}+ onNavigate={picker.openFolder}+ compact+ />+ ) : null}++ {picker.showFolders ? (+ <WorkspaceFolderRows+ folders={picker.folderRows}+ allFolders={picker.folders}+ selectedIds={picker.selectedFolderIds}+ isLoading={picker.isFoldersLoading}+ onOpen={picker.openFolder}+ onToggleAttach={picker.toggleFolder}+ />+ ) : null}+<WorkspaceFileListfiles={picker.files}selectedIds={picker.selectedIds}@@ -77,6 +132,25 @@ export function WorkspaceFilePicker({hasMore={picker.hasMore}isLoadingMore={picker.isLoadingMore}onLoadMore={picker.loadMore}+ emptyMessage={emptyMessage({+ isExpertOnly: !!expertId && picker.expertOnly,+ who,+ isSearching: picker.searchTerm.trim().length > 0,+ isInFolder: picker.folderId !== null,+ hasFolderRows: picker.folderRows.length > 0,+ })}+ emptyAction={+ expertId && picker.expertOnly ? (+ <Button+ type="button"+ variant="ghost"+ size="small"+ onClick={() => picker.setExpertOnly(false)}+ >+ Show your own files too+ </Button>+ ) : null+ }/></div>@@ -93,13 +167,40 @@ export function WorkspaceFilePicker({type="button"variant="primary"size="small"- disabled={selectedCount === 0}+ disabled={files + folders === 0}onClick={handleConfirm}>- {selectedCount > 0 ? `Add ${selectedCount} file(s)` : "Add"}+ {addLabel(files, folders)}</Button></Dialog.Footer></Dialog.Content></Dialog>);}++function addLabel(files: number, folders: number): string {+ const parts: string[] = [];+ if (files > 0) parts.push(`${files} ${files === 1 ? "file" : "files"}`);+ if (folders > 0)+ parts.push(`${folders} ${folders === 1 ? "folder" : "folders"}`);+ return parts.length > 0 ? `Add ${parts.join(" and ")}` : "Add";+}++function emptyMessage(opts: {+ isExpertOnly: boolean;+ who: string;+ isSearching: boolean;+ isInFolder: boolean;+ hasFolderRows: boolean;+}): string {+ if (opts.isExpertOnly)+ return opts.isSearching+ ? `No matching files from ${opts.who}.`+ : `No files from ${opts.who} yet.`;+ if (opts.isSearching) return "No matching files.";+ if (opts.isInFolder)+ return opts.hasFolderRows+ ? "No files directly in this folder."+ : "This folder is empty.";+ return "No files in your workspace yet.";+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFolderRows.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFolderRows.tsxnew file mode 100644index 0000000000..2b4e063b11--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFolderRows.tsx@@ -0,0 +1,130 @@+"use client";++import {+ folderSummary,+ subfolderCountOf,+} from "@/app/(platform)/artifacts/components/WorkspaceFolders/folderTree";+import { FOLDER_STYLE } from "@/app/(platform)/artifacts/components/WorkspaceFolders/folder-constants";+import type { WorkspaceFolder } from "@/app/api/__generated__/models/workspaceFolder";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { Text } from "@/components/atoms/Text/Text";+import { isKey } from "@/lib/keyboard";+import { cn } from "@/lib/utils";+import {+ ArrowRight01Icon,+ CheckmarkCircle02Icon,+ Circle,+ Folder01Icon,+} from "@hugeicons/core-free-icons";++interface Props {+ folders: WorkspaceFolder[];+ allFolders: WorkspaceFolder[];+ selectedIds: ReadonlySet<string>;+ isLoading: boolean;+ onOpen: (folderId: string) => void;+ onToggleAttach: (folder: WorkspaceFolder, subfolderCount: number) => void;+}++/**+ * Folder rows above the file cards. They sit outside the cards' listbox+ * because a listbox option may not contain interactive children, and a folder+ * row has two: open, and attach.+ */+export function WorkspaceFolderRows({+ folders,+ allFolders,+ selectedIds,+ isLoading,+ onOpen,+ onToggleAttach,+}: Props) {+ if (isLoading) return <Skeleton className="h-14 w-full rounded-2xl" />;+ if (folders.length === 0) return null;++ return (+ <ul role="list" aria-label="Folders" className="flex flex-col gap-2">+ {folders.map((folder) => {+ const isSelected = selectedIds.has(folder.id);+ const subfolderCount = subfolderCountOf(allFolders, folder.id);+ return (+ <li+ key={folder.id}+ className={cn(+ "flex w-full items-center gap-3 rounded-2xl border bg-white p-3 transition-colors",+ isSelected+ ? "border-violet-300 ring-1 ring-violet-200"+ : "border-zinc-200 hover:border-zinc-300",+ )}+ >+ <button+ type="button"+ aria-label={`Open ${folder.name}`}+ onClick={() => onOpen(folder.id)}+ onKeyDown={(e) => {+ if (!isKey(e, "Enter", " ")) return;+ e.preventDefault();+ onOpen(folder.id);+ }}+ className="flex min-w-0 flex-1 items-center gap-3 rounded-xl text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-300"+ >+ <div+ className={cn(+ "flex h-9 w-9 shrink-0 items-center justify-center rounded-xl",+ FOLDER_STYLE.surface,+ )}+ >+ <Icon+ icon={Folder01Icon}+ size={18}+ className={FOLDER_STYLE.icon}+ />+ </div>+ <div className="flex min-w-0 flex-1 flex-col">+ <Text+ variant="body-medium"+ className="truncate text-zinc-900"+ title={folder.name}+ >+ {folder.name}+ </Text>+ <Text variant="small" className="text-zinc-500">+ {folderSummary(folder.file_count ?? 0, subfolderCount)}+ </Text>+ </div>+ </button>+ <button+ type="button"+ aria-pressed={isSelected}+ aria-label={`Attach folder ${folder.name}`}+ onClick={(e) => {+ e.stopPropagation();+ onToggleAttach(folder, subfolderCount);+ }}+ className={cn(+ "flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-sm transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-300",+ isSelected+ ? "text-violet-600"+ : "text-zinc-500 hover:bg-zinc-100 hover:text-zinc-700",+ )}+ >+ Attach+ <Icon+ icon={isSelected ? CheckmarkCircle02Icon : Circle}+ className="h-4 w-4"+ />+ </button>+ <Icon+ icon={ArrowRight01Icon}+ size={16}+ className="shrink-0 text-zinc-400"+ aria-hidden+ />+ </li>+ );+ })}+ </ul>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsxindex 94714700e9..615049d254 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsx@@ -8,8 +8,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { WorkspaceFilePicker } from "../WorkspaceFilePicker";const mockListWorkspaceFiles = vi.fn();+const mockFolders = vi.fn<() => { data?: { folders: unknown[] } }>(() => ({+ data: { folders: [] },+}));vi.mock("@/app/api/__generated__/endpoints/workspace/workspace", () => ({listWorkspaceFiles: (...args: unknown[]) => mockListWorkspaceFiles(...args),+ useListWorkspaceFolders: () => mockFolders(),}));const FILE = {@@ -119,7 +123,7 @@ describe("WorkspaceFilePicker", () => {fireEvent.click(await screen.findByRole("button", { name: /add 1 file/i }));- expect(onConfirm).toHaveBeenCalledWith([FILE]);+ expect(onConfirm).toHaveBeenCalledWith([{ kind: "file", file: FILE }]);expect(onClose).toHaveBeenCalled();});@@ -209,7 +213,9 @@ describe("WorkspaceFilePicker", () => {fireEvent.click(card("f-1"), { shiftKey: true });fireEvent.click(screen.getByRole("button", { name: /add 3 file/i }));- expect(onConfirm).toHaveBeenCalledWith([files[1], files[2], files[3]]);+ expect(onConfirm).toHaveBeenCalledWith(+ [files[1], files[2], files[3]].map((file) => ({ kind: "file", file })),+ );});// Firefox reports shiftKey false on the click it synthesises from@@ -274,6 +280,245 @@ describe("WorkspaceFilePicker", () => {});});+const FOLDERS = [+ {+ id: "fld-1",+ workspace_id: "ws-1",+ name: "Reports",+ parent_id: null,+ file_count: 3,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ },+ {+ id: "fld-2",+ workspace_id: "ws-1",+ name: "2026",+ parent_id: "fld-1",+ file_count: 0,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ },+];++function renderPicker(+ props: Partial<{ expertId: string; expertName: string }> = {},+) {+ const onConfirm = vi.fn();+ render(+ <WorkspaceFilePicker+ isOpen={true}+ onClose={vi.fn()}+ onConfirm={onConfirm}+ expertId={props.expertId ?? null}+ expertName={props.expertName ?? null}+ />,+ );+ return { onConfirm };+}++function lastRequest() {+ return mockListWorkspaceFiles.mock.calls.at(-1)?.[0] as Record<+ string,+ unknown+ >;+}++describe("WorkspaceFilePicker - the expert-only filter", () => {+ it("opens ON in an expert chat and asks for that expert's conversations alone", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: { files: [FILE], has_more: false },+ });+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ renderPicker({ expertId: "expert-a", expertName: "Maria" });++ await screen.findByText("alpha.txt");+ expect(screen.getByLabelText("Only Maria’s files")).toBeTruthy();+ expect(lastRequest()).toMatchObject({+ expert_id: "expert-a",+ include_user_files: false,+ });+ // No folder axis while the filter is on: the user's folders are exactly+ // what it hides.+ expect(lastRequest().root_only).toBeUndefined();+ expect(screen.queryByRole("list", { name: "Folders" })).toBeNull();+ });++ it("switching it off widens to the user's own files and shows folder rows", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: { files: [FILE], has_more: false },+ });+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ renderPicker({ expertId: "expert-a", expertName: "Maria" });+ await screen.findByText("alpha.txt");++ fireEvent.click(screen.getByLabelText("Only Maria’s files"));++ await waitFor(() =>+ expect(lastRequest()).toMatchObject({+ expert_id: "expert-a",+ include_user_files: true,+ root_only: true,+ }),+ );+ expect(await screen.findByRole("list", { name: "Folders" })).toBeTruthy();+ expect(screen.getByText("Plus your own files and folders")).toBeTruthy();+ });++ it("renders no switch in a personal chat, and shows folders straight away", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: { files: [FILE], has_more: false },+ });+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ renderPicker();++ await screen.findByText("alpha.txt");+ expect(screen.queryByLabelText(/Only .*files/)).toBeNull();+ expect(screen.getByRole("list", { name: "Folders" })).toBeTruthy();+ expect(lastRequest().include_user_files).toBeUndefined();+ });++ it("the ON empty state offers to widen, and the button flips the switch", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: { files: [], has_more: false },+ });+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ renderPicker({ expertId: "expert-a", expertName: "Maria" });++ expect(await screen.findByText("No files from Maria yet.")).toBeTruthy();+ fireEvent.click(+ screen.getByRole("button", { name: /show your own files too/i }),+ );++ await waitFor(() =>+ expect(lastRequest()).toMatchObject({ include_user_files: true }),+ );+ });+});++describe("WorkspaceFilePicker - folders", () => {+ it("lists the root's folders and navigates into one", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: { files: [FILE], has_more: false },+ });+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ renderPicker();+ await screen.findByText("alpha.txt");++ // Only root folders at the root — "2026" is Reports' child.+ expect(screen.getByText("Reports")).toBeTruthy();+ expect(screen.queryByText("2026")).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Open Reports" }));++ await waitFor(() =>+ expect(lastRequest()).toMatchObject({ folder_id: "fld-1" }),+ );+ expect(await screen.findByText("2026")).toBeTruthy();+ expect(screen.getByTestId("folder-breadcrumb")).toBeTruthy();++ fireEvent.click(screen.getByTestId("folder-breadcrumb-root"));+ await waitFor(() =>+ expect(lastRequest()).toMatchObject({ root_only: true }),+ );+ });++ it("attaching a folder selects it without opening it, and hands it to the composer", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: { files: [FILE], has_more: false },+ });+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ const { onConfirm } = renderPicker();+ await screen.findByText("alpha.txt");++ const attach = screen.getByRole("button", {+ name: "Attach folder Reports",+ });+ fireEvent.click(attach);++ expect(attach.getAttribute("aria-pressed")).toBe("true");+ // Attaching must not navigate: the file listing is still the root's.+ expect(lastRequest().folder_id).toBeUndefined();+ expect(screen.getByRole("button", { name: "Add 1 folder" })).toBeTruthy();++ fireEvent.click(screen.getByText("alpha.txt"));+ expect(+ screen.getByRole("button", { name: "Add 1 file and 1 folder" }),+ ).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: /^Add / }));+ expect(onConfirm).toHaveBeenCalledWith([+ { kind: "folder", folder: FOLDERS[0], subfolderCount: 1 },+ { kind: "file", file: FILE },+ ]);+ });++ it("opening a folder never shows the previous folder's files while its own load", async () => {+ mockPage(makeFiles(1));+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ renderPicker();+ await screen.findByText("f-0");++ mockListWorkspaceFiles.mockReturnValue(new Promise(() => {}));+ fireEvent.click(screen.getByRole("button", { name: "Open Reports" }));+ await waitFor(() =>+ expect(lastRequest()).toMatchObject({ folder_id: "fld-1" }),+ );++ expect(screen.queryByText("f-0")).toBeNull();+ });++ it("opening a folder drops the range anchor taken in the previous listing", async () => {+ mockPage(makeFiles(3));+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ renderPicker();+ await screen.findByText("f-0");++ fireEvent.click(card("f-0"));+ fireEvent.click(screen.getByRole("button", { name: "Open Reports" }));+ await waitFor(() =>+ expect(lastRequest()).toMatchObject({ folder_id: "fld-1" }),+ );+ await screen.findByText("f-2");+ fireEvent.click(card("f-2"), { shiftKey: true });++ expect(selectedNames()).toEqual(["f-0", "f-2"]);+ });++ it("a search spans every folder and hides the folder rows", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: { files: [FILE], has_more: false },+ });+ mockFolders.mockReturnValue({ data: { folders: FOLDERS } });++ renderPicker();+ await screen.findByText("alpha.txt");++ fireEvent.change(screen.getByLabelText("Search workspace files"), {+ target: { value: "alpha" },+ });++ await waitFor(() => expect(lastRequest().q).toBe("alpha"));+ expect(lastRequest().root_only).toBeUndefined();+ expect(screen.queryByRole("list", { name: "Folders" })).toBeNull();+ });+});+function mockPage(files: ReturnType<typeof makeFiles>) {mockListWorkspaceFiles.mockResolvedValue({status: 200,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.tsindex 0225934d87..06c758b47f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.ts@@ -1,5 +1,14 @@-import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/workspace";+import {+ listWorkspaceFiles,+ useListWorkspaceFolders,+} 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 { okData } from "@/app/api/helpers";+import {+ ancestorsOf,+ childrenOf,+} from "@/app/(platform)/artifacts/components/WorkspaceFolders/folderTree";import { useDebouncedValue } from "@/hooks/useDebouncedValue";import {applySelection,@@ -15,6 +24,17 @@ const PAGE_SIZE = 50;type ListPage = Awaited<ReturnType<typeof listWorkspaceFiles>>;+/** A picked row: a file, or a folder the model will open for itself. */+export type PickedItem =+ | { kind: "file"; file: WorkspaceFileItem }+ | PickedFolder;++type PickedFolder = {+ kind: "folder";+ folder: WorkspaceFolder;+ subfolderCount: number;+};+interface Args {enabled: boolean;/** Expert the chat is scoped to; lists only files that expert can attach. */@@ -23,25 +43,55 @@ interface Args {export function useWorkspaceFilePicker({ enabled, expertId }: Args) {const [searchTerm, setSearchTerm] = useState("");+ // Deliberately outside `reset()`: the filter is a property of this chat, so+ // it survives close-and-reopen. The picker's `key={expertId}` remount is+ // what puts it back to ON when the chat's expert changes.+ const [expertOnly, setExpertOnly] = useState(true);+ const [folderId, setFolderId] = useState<string | null>(null);// Keep the full item (not just id) so a selection survives a search that- // pages the file off the currently-loaded list. The anchor travels with it- // because a range is only meaningful against the list it was taken from.+ // pages the row off the currently-loaded list. The anchor travels with the+ // files because a range is only meaningful against the list it was taken from.const [selection, setSelection] = useState<Selection>({selected: new Map(),anchor: null,});+ const [pickedFolders, setPickedFolders] = useState<Map<string, PickedFolder>>(+ new Map(),+ );const debouncedSearch = useDebouncedValue(searchTerm.trim(),SEARCH_DEBOUNCE_MS,);const q = debouncedSearch || undefined;+ // An expert chat with the filter on lists that expert's conversations flat,+ // with no folder axis: the user's own folders are exactly what it hides.+ const isExpertOnly = !!expertId && expertOnly;+ const includeUserFiles = expertId ? !expertOnly : undefined;+ const showFolders = !isExpertOnly && !q;+ // While searching, span every folder so a search never has to be repeated+ // per folder — as the Files page does.+ const rootOnly = showFolders && folderId === null;+ // One value for both the key and the request: the lint rule reads them+ // syntactically, and a key that names less than the query does goes stale.+ const listedFolderId = showFolders ? folderId : null;++ const foldersQuery = useListWorkspaceFolders({+ query: { select: okData, enabled: enabled && !isExpertOnly },+ });+ const folders = foldersQuery.data?.folders ?? [];const query = useInfiniteQuery({queryKey: ["workspace-file-picker","list",- { q: q ?? null, expertId: expertId ?? null },+ {+ q: q ?? null,+ expertId: expertId ?? null,+ includeUserFiles: includeUserFiles ?? null,+ folderId: listedFolderId,+ rootOnly,+ },] as const,queryFn: ({ pageParam }) =>listWorkspaceFiles({@@ -49,6 +99,9 @@ export function useWorkspaceFilePicker({ enabled, expertId }: Args) {offset: pageParam,q,expert_id: expertId ?? undefined,+ include_user_files: includeUserFiles,+ folder_id: listedFolderId ?? undefined,+ root_only: rootOnly || undefined,}),initialPageParam: 0,getNextPageParam: (lastPage, allPages) => {@@ -56,12 +109,24 @@ export function useWorkspaceFilePicker({ enabled, expertId }: Args) {if (!lastPage.data.has_more) return undefined;return countLoadedFiles(allPages);},- // Keep the previous page while a search refines the same expert's list,- // but never show one expert's files while another's request is pending.- placeholderData: (previousData, previousQuery) =>- previousQuery?.queryKey[2].expertId === (expertId ?? null)- ? previousData- : undefined,+ // Keep the previous page while a search refines the same listing, but+ // never show one expert's files, the other side of the filter or another+ // folder's files while its request is pending.+ placeholderData: (previousData, previousQuery) => {+ const prev = previousQuery?.queryKey[2];+ if (!prev) return undefined;+ if (prev.expertId !== (expertId ?? null)) return undefined;+ if (prev.includeUserFiles !== (includeUserFiles ?? null))+ return undefined;+ // A search refines a listing; opening a folder replaces it.+ const isBrowsing = prev.q === null && !q;+ if (+ isBrowsing &&+ (prev.folderId !== listedFolderId || prev.rootOnly !== rootOnly)+ )+ return undefined;+ return previousData;+ },enabled,});@@ -71,32 +136,84 @@ export function useWorkspaceFilePicker({ enabled, expertId }: Args) {setSelection((prev) => applySelection(prev, files, index, modifiers));}+ function toggleFolder(folder: WorkspaceFolder, subfolderCount: number) {+ setPickedFolders((prev) => {+ const next = new Map(prev);+ if (next.has(folder.id)) next.delete(folder.id);+ else next.set(folder.id, { kind: "folder", folder, subfolderCount });+ return next;+ });+ }++ // A range across a changed listing would span files never shown together.+ function dropAnchor() {+ setSelection((prev) => ({ ...prev, anchor: null }));+ }+function search(term: string) {setSearchTerm(term);- // A range across a changed filter would span files never shown together.- setSelection((prev) => ({ ...prev, anchor: null }));+ dropAnchor();+ }++ function openFolder(id: string | null) {+ setFolderId(id);+ dropAnchor();+ }++ function filterToExpert(on: boolean) {+ setExpertOnly(on);+ dropAnchor();}function reset() {setSelection({ selected: new Map(), anchor: null });setSearchTerm("");+ setPickedFolders(new Map());+ setFolderId(null);}+ // Folders first, as the picker shows them, so the chips — and at the cap,+ // what survives it — follow the order on screen.+ const selectedFiles = orderByList(selection.selected, files);+ const selectedItems: PickedItem[] = [+ ...pickedFolders.values(),+ ...selectedFiles.map((file) => ({ kind: "file" as const, file })),+ ];+return {files,+ folderRows: showFolders ? childrenOf(folders, folderId) : [],+ folders,+ breadcrumb:+ showFolders && folderId+ ? ancestorsOf(folders, folderId).map((folder) => ({+ id: folder.id,+ name: folder.name,+ }))+ : [],+ folderId,+ openFolder,+ showFolders,+ isFoldersLoading: foldersQuery.isLoading,isLoading: query.isLoading,isError: query.isError,error: query.error,searchTerm,setSearchTerm: search,+ expertOnly,+ setExpertOnly: filterToExpert,hasMore: !!query.hasNextPage,isLoadingMore: query.isFetchingNextPage,loadMore: () => {query.fetchNextPage();},selectedIds: selection.selected,- selectedFiles: orderByList(selection.selected, files),+ selectedFolderIds: new Set(pickedFolders.keys()),+ selectedItems,+ selectedFileCount: selectedFiles.length,+ selectedFolderCount: pickedFolders.size,select,+ toggleFolder,reset,};}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MentionDropdown.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MentionDropdown.test.tsxindex 34af0cec37..8f033688d1 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MentionDropdown.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MentionDropdown.test.tsx@@ -2,7 +2,9 @@ import { fireEvent, render, screen } from "@/tests/integrations/test-utils";import type { MutableRefObject } from "react";import { afterEach, describe, expect, it, vi } from "vitest";import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import type { WorkspaceFolder } from "@/app/api/__generated__/models/workspaceFolder";import { MentionDropdown } from "../MentionDropdown";+import type { MentionOption } from "../../useChatMentions";const FILE: WorkspaceFileItem = {id: "file-1",@@ -18,7 +20,7 @@ function renderDropdown(overrides: Partial<Parameters<typeof MentionDropdown>[0]> = {},) {const props = {- files: [] as WorkspaceFileItem[],+ options: [] as MentionOption[],isLoading: false,isError: false,highlightedIndex: 0,@@ -54,18 +56,58 @@ describe("MentionDropdown", () => {});it("renders a row per file and selects on mousedown", () => {- const { onSelect } = renderDropdown({ files: [FILE] });+ const { onSelect } = renderDropdown({ options: [fileOption(FILE)] });const option = screen.getByRole("option", { name: /alpha\.txt/i });fireEvent.mouseDown(option);- expect(onSelect).toHaveBeenCalledWith(FILE);+ expect(onSelect).toHaveBeenCalledWith(fileOption(FILE));});it("highlights a row on hover", () => {const { onHighlight } = renderDropdown({- files: [FILE],+ options: [fileOption(FILE)],highlightedIndex: -1,});fireEvent.mouseEnter(screen.getByRole("option", { name: /alpha\.txt/i }));expect(onHighlight).toHaveBeenCalledWith(0);});++ it("offers folders above files, with their count in the accessible name", () => {+ renderDropdown({+ options: [folderOption(FOLDER, 1), fileOption(FILE)],+ });+ const options = screen.getAllByRole("option");+ expect(options[0].getAttribute("aria-label")).toBe(+ "Folder Reports, 2 files",+ );+ expect(options[1].textContent).toContain("alpha.txt");+ });++ it("selects a folder option on mousedown", () => {+ const { onSelect } = renderDropdown({+ options: [folderOption(FOLDER, 0)],+ });+ fireEvent.mouseDown(screen.getByRole("option", { name: /Folder Reports/ }));+ expect(onSelect).toHaveBeenCalledWith(folderOption(FOLDER, 0));+ });});++const FOLDER: WorkspaceFolder = {+ id: "fld-1",+ workspace_id: "ws-1",+ name: "Reports",+ parent_id: null,+ file_count: 2,+ created_at: new Date("2026-01-01T00:00:00Z"),+ updated_at: new Date("2026-01-01T00:00:00Z"),+};++function fileOption(file: WorkspaceFileItem): MentionOption {+ return { kind: "file", file };+}++function folderOption(+ folder: WorkspaceFolder,+ subfolderCount: number,+): MentionOption {+ return { kind: "folder", folder, subfolderCount };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.tsindex 73605698d4..23a5ab895d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts@@ -1,5 +1,11 @@-import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/workspace";+import {+ listWorkspaceFiles,+ useListWorkspaceFolders,+} 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 { okData } from "@/app/api/helpers";+import { subfolderCountOf } from "@/app/(platform)/artifacts/components/WorkspaceFolders/folderTree";import { useDebouncedValue } from "@/hooks/useDebouncedValue";import { useKeyboardNav } from "@/components/organisms/SearchCommandModal/useKeyboardNav";import { useQuery } from "@tanstack/react-query";@@ -10,6 +16,7 @@ import { isKey } from "@/lib/keyboard";const MENTION_RE = /(?:^|\s)@([^\s@]*)$/;const QUERY_DEBOUNCE_MS = 200;const MENTION_RESULT_LIMIT = 8;+const MENTION_FOLDER_LIMIT = 3;interface ActiveMention {query: string;@@ -22,6 +29,7 @@ interface Args {value: string;setValue: (value: string) => void;addWorkspaceFile: (item: WorkspaceFileItem) => void;+ addWorkspaceFolder: (folder: WorkspaceFolder, subfolderCount: number) => void;/** Expert the chat is scoped to; suggests only files that expert can attach. */expertId?: string | null;}@@ -37,6 +45,7 @@ export function useChatMentions({value,setValue,addWorkspaceFile,+ addWorkspaceFolder,expertId,}: Args) {const [active, setActive] = useState<ActiveMention | null>(null);@@ -59,6 +68,9 @@ export function useChatMentions({limit: MENTION_RESULT_LIMIT,q: debouncedQuery || undefined,expert_id: expertId ?? undefined,+ // A typed name is a deliberate search, so it always spans everything+ // the chat may attach — the picker's narrower default is for browsing.+ include_user_files: expertId ? true : undefined,}),enabled: isOpen,// Keep results while the same expert's query refines; drop them when the@@ -72,12 +84,27 @@ export function useChatMentions({const files =search.data?.status === 200 ? (search.data.data.files ?? []) : [];+ const foldersQuery = useListWorkspaceFolders({+ query: { select: okData, enabled: isOpen },+ });+ const allFolders = foldersQuery.data?.folders ?? [];+ const folders = matchFolders(allFolders, debouncedQuery);+ // Folders come first, so the keyboard cursor spans both groups as one list.+ const options: MentionOption[] = [+ ...folders.map((folder) => ({+ kind: "folder" as const,+ folder,+ subfolderCount: subfolderCountOf(allFolders, folder.id),+ })),+ ...files.map((file) => ({ kind: "file" as const, file })),+ ];+const {highlightedIndex,highlightedRef,moveHighlight,setHighlightedIndex,- } = useKeyboardNav(files.length, debouncedQuery);+ } = useKeyboardNav(options.length, debouncedQuery);function detect(textarea: HTMLTextAreaElement) {if (!enabled) return;@@ -95,13 +122,15 @@ export function useChatMentions({setActive(null);}- function accept(item: WorkspaceFileItem | undefined) {+ function accept(option: MentionOption | undefined) {// The highlighted index is clamped in an effect, so a shrinking result// list can momentarily leave it pointing past the end — guard against the- // out-of-bounds `undefined` before touching the item.- if (!active || !item) return;+ // out-of-bounds `undefined` before touching the option.+ if (!active || !option) return;setValue(value.slice(0, active.start) + value.slice(active.end));- addWorkspaceFile(item);+ if (option.kind === "folder")+ addWorkspaceFolder(option.folder, option.subfolderCount);+ else addWorkspaceFile(option.file);setActive(null);}@@ -112,7 +141,7 @@ export function useChatMentions({close();return true;}- if (files.length === 0) return false;+ if (options.length === 0) return false;if (isKey(e, "ArrowDown")) {e.preventDefault();moveHighlight(1);@@ -125,7 +154,7 @@ export function useChatMentions({}if (isKey(e, "Enter", "Tab")) {e.preventDefault();- accept(files[highlightedIndex]);+ accept(options[highlightedIndex]);return true;}return false;@@ -133,7 +162,7 @@ export function useChatMentions({return {isOpen,- files,+ options,isLoading: search.isLoading,isError: search.isError,highlightedIndex,@@ -145,3 +174,18 @@ export function useChatMentions({onKeyDown,};}++export type MentionOption =+ | { kind: "file"; file: WorkspaceFileItem }+ | { kind: "folder"; folder: WorkspaceFolder; subfolderCount: number };++function matchFolders(+ folders: WorkspaceFolder[],+ query: string,+): WorkspaceFolder[] {+ const needle = query.trim().toLowerCase();+ return folders+ .filter((folder) => folder.name.toLowerCase().includes(needle))+ .sort((a, b) => a.name.localeCompare(b.name))+ .slice(0, MENTION_FOLDER_LIMIT);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex fce266a514..8514523a0a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -65,6 +65,10 @@ import {type SentFrom,} from "../../sentFrom";import type { PendingUploadSend } from "../../copilotStreamStore";+import {+ WORKSPACE_FOLDER_PART_TYPE,+ type WorkspaceFolderPartData,+} from "../../helpers/workspaceAttachments";import { Clock01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";@@ -668,6 +672,11 @@ export function ChatMessagesContainer({const fileParts = renderableParts.filter((p): p is FileUIPart => p.type === "file",);+ const folderParts = renderableParts.flatMap((p) =>+ p.type === WORKSPACE_FOLDER_PART_TYPE+ ? [(p as { data: WorkspaceFolderPartData }).data]+ : [],+ );const sentFrom = readOnly? null@@ -778,9 +787,10 @@ export function ChatMessagesContainer({/></MessageActions>)}- {fileParts.length > 0 && (+ {(fileParts.length > 0 || folderParts.length > 0) && (<MessageAttachmentsfiles={fileParts}+ folders={folderParts}isUser={message.role === "user"}filePattern={filePattern}readOnly={readOnly}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageAttachments.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageAttachments.tsxindex e594025d85..b5e02cf23b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageAttachments.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageAttachments.tsx@@ -12,11 +12,22 @@ import {} from "../../ToolAccordion/AccordionContent";import { ArtifactCard } from "../../ArtifactCard/ArtifactCard";import { filePartToArtifactRef } from "../helpers";-import { Download04Icon, File02Icon } from "@hugeicons/core-free-icons";+import {+ Download04Icon,+ File02Icon,+ Folder01Icon,+ LinkSquare01Icon,+} from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import Link from "next/link";+import { folderSummary } from "@/app/(platform)/artifacts/components/WorkspaceFolders/folderTree";+import type { WorkspaceFolderPartData } from "../../../helpers/workspaceAttachments";interface Props {files: FileUIPart[];+ /** Folders attached to the message — a pointer for the model, never+ * expanded into files, so they never take the ArtifactCard path. */+ folders?: WorkspaceFolderPartData[];isUser?: boolean;/** URL→file-ID pattern used by ``filePartToArtifactRef``. Owner* side defaults to the workspace-file URL shape; the public viewer@@ -47,14 +58,22 @@ function renderFileContent(file: FileUIPart): React.ReactNode | null {export function MessageAttachments({files,+ folders = [],isUser,filePattern,readOnly,}: Props) {- if (files.length === 0) return null;+ if (files.length === 0 && folders.length === 0) return null;return (<div className="mt-2 flex flex-col gap-2">+ {folders.map((folder) => (+ <FolderAttachmentCard+ key={folder.id}+ folder={folder}+ readOnly={readOnly}+ />+ ))}{files.map((file, i) => {const artifactRef = filePartToArtifactRef(file,@@ -166,3 +185,38 @@ export function MessageAttachments({</div>);}++function FolderAttachmentCard({+ folder,+ readOnly,+}: {+ folder: WorkspaceFolderPartData;+ readOnly?: boolean;+}) {+ return (+ <div className="flex min-w-0 items-center gap-3 rounded-lg border border-purple-300 bg-purple-100 p-3">+ <Icon icon={Folder01Icon} size={20} className="shrink-0 text-zinc-700" />+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium text-zinc-800">+ {folder.name}+ </span>+ <span className="text-xs text-zinc-600">+ {/* The part counts direct files only, so zero is not "Empty". */}+ {folder.fileCount > 0+ ? `Folder · ${folderSummary(folder.fileCount, 0)}`+ : "Folder"}+ </span>+ </div>+ {/* The share viewer has no Files page to send anyone to. */}+ {readOnly ? null : (+ <Link+ href={`/artifacts?folder=${encodeURIComponent(folder.id)}`}+ aria-label={`Open folder ${folder.name} in Files`}+ className="shrink-0 rounded-md p-1 text-zinc-500 transition-colors hover:bg-purple-200 hover:text-zinc-800"+ >+ <Icon icon={LinkSquare01Icon} size={16} />+ </Link>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessageAttachments.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessageAttachments.test.tsxindex efd65dee09..8598a8ec1e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessageAttachments.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessageAttachments.test.tsx@@ -37,6 +37,30 @@ describe("MessageAttachments", () => {expect(screen.getByTestId("artifact-card")).toBeDefined();});+ it("renders an attached folder as a chip, not an artifact card", () => {+ render(+ <MessageAttachments+ files={[]}+ folders={[{ id: "fld-1", name: "Reports", fileCount: 3 }]}+ />,+ );+ expect(screen.getByText("Reports")).toBeDefined();+ expect(screen.getByText("Folder · 3 files")).toBeDefined();+ expect(screen.queryByTestId("artifact-card")).toBeNull();+ });++ it("renders a folder-only message instead of nothing", () => {+ const { container } = render(+ <MessageAttachments+ files={[]}+ folders={[{ id: "fld-1", name: "Reports", fileCount: 0 }]}+ />,+ );+ expect(container.firstChild).not.toBeNull();+ // Zero direct files may still hold subfolders the part does not count.+ expect(screen.queryByText(/Empty/)).toBeNull();+ });+it("falls back to the file card for non-workspace files", () => {render(<MessageAttachmentsdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsxindex bc6741091b..9b6eacf4bc 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx@@ -210,6 +210,7 @@ export function EmptySession({droppedFiles={droppedFiles}onDroppedFilesConsumed={onDroppedFilesConsumed}expertId={expertId}+ expertName={expertName}recipientPicker={isExpertsEnabled ? (<RecipientChipdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.tsindex bd5ee41053..b1203ff1d3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts@@ -1,4 +1,5 @@-import type { FileUIPart, UIMessage } from "ai";+import type { UIMessage } from "ai";+import type { StoredAttachmentPart } from "./helpers/workspaceAttachments";import { create } from "zustand";import { createJSONStorage, persist } from "zustand/middleware";import type { ExpertKickoffMetadata } from "./expertKickoff";@@ -95,7 +96,7 @@ interface PersistedCopilotStreamState {sessions: Record<string, SessionCoord>;pendingFirstSend: Pick<PendingFirstSend, "text" | "metadata"> | null;pendingFirstSendSessionId: string | null;- pendingFileParts: FileUIPart[];+ pendingFileParts: StoredAttachmentPart[];}interface CopilotStreamStore {@@ -103,7 +104,7 @@ interface CopilotStreamStore {messageSnapshots: Record<string, UIMessage[]>;pendingFirstSend: PendingFirstSend | null;pendingFirstSendSessionId: string | null;- pendingFileParts: FileUIPart[];+ pendingFileParts: StoredAttachmentPart[];pendingUploadSends: Record<string, PendingUploadSend>;getCoord: (sessionId: string) => SessionCoord;@@ -114,7 +115,7 @@ interface CopilotStreamStore {setPendingFirstSend: (send: PendingFirstSend | null) => void;bindPendingFirstSendToSession: (sessionId: string) => void;- setPendingFileParts: (parts: FileUIPart[]) => void;+ setPendingFileParts: (parts: StoredAttachmentPart[]) => void;setPendingUploadSend: (sessionId: string | null,send: PendingUploadSend,@@ -128,7 +129,7 @@ interface CopilotStreamStore {/** Read-and-clear; used by the post-session-creation flush effect. */takePendingFirstSend: (sessionId: string) => {send: PendingFirstSend | null;- parts: FileUIPart[];+ parts: StoredAttachmentPart[];};/** Test-only: wipe all per-session state. */diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.tsindex cf24f439bf..6489bb0b73 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts@@ -1,3 +1,4 @@+import { WORKSPACE_FOLDER_PART_TYPE } from "./helpers/workspaceAttachments";import { environment } from "@/services/environment";import { DefaultChatTransport } from "ai";import type { ChatTransport, FileUIPart, UIMessage } from "ai";@@ -78,6 +79,11 @@ export function createCopilotTransport({return match?.[1];}).filter(Boolean) as string[] | undefined;+ // A folder is named for the model to open, never expanded into files,+ // so it travels as its own id list.+ const folderIds = last.parts?.flatMap((p) =>+ isWorkspaceFolderPart(p) ? [p.data.id] : [],+ );// ``message_id`` is the client idempotency key. The backend scopes it// to the authenticated user + session before using the result as the// persisted PK, so retransmits collide atomically without letting one@@ -99,6 +105,7 @@ export function createCopilotTransport({is_user_message: last.role === "user",context: null,file_ids: fileIds && fileIds.length > 0 ? fileIds : null,+ folder_ids: folderIds && folderIds.length > 0 ? folderIds : null,model: copilotModelRef.current ?? null,// Supplying options forces uuid's// getRandomValues path. Unlike crypto.randomUUID,@@ -130,3 +137,13 @@ export function createCopilotTransport({},});}++function isWorkspaceFolderPart(+ part: unknown,+): part is { type: string; data: { id: string } } {+ return (+ typeof part === "object" &&+ part !== null &&+ (part as { type?: unknown }).type === WORKSPACE_FOLDER_PART_TYPE+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.tsindex 012f741770..e7adb678f4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts@@ -621,3 +621,74 @@ describe("convertChatSessionMessagesToUiMessages — latest user marker", () =>});});});++// Exactly what `build_files_block` emits: the files hint first, then the+// folders hint, either or both present.+const FILE_HINT =+ "Use read_workspace_file with the file_id to access file contents.";+const FOLDER_HINT =+ "Use list_workspace_files with the folder_id to see what is in a folder.";++function userParts(content: string) {+ const { messages } = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [{ role: "user", content, sequence: 0 }],+ { isComplete: true },+ );+ return messages[0].parts;+}++describe("the [Attached files] block", () => {+ it("parses a folder-only block, leaving no raw text in the bubble", () => {+ const parts = userParts(+ `Look at this.\n\n[Attached files]\n- Reports (folder, 3 file(s) directly inside), folder_id=0fd0aaaa-1111-4222-8333-444455556666\n${FOLDER_HINT}`,+ );++ expect(parts).toEqual([+ { type: "text", text: "Look at this.", state: "done" },+ {+ type: "data-workspace-folder",+ data: {+ id: "0fd0aaaa-1111-4222-8333-444455556666",+ name: "Reports",+ fileCount: 3,+ },+ },+ ]);+ });++ it("parses a block with both a file and a folder, dropping both hint lines", () => {+ const parts = userParts(+ `Compare these.\n\n[Attached files]\n- a.txt (text/plain, 1.0 KB), file_id=0f11eeee-1111-4222-8333-444455556666\n- Reports (folder, 3 file(s) directly inside), folder_id=0fd0aaaa-1111-4222-8333-444455556666\n${FILE_HINT}\n${FOLDER_HINT}`,+ );++ const text = parts.find((p) => p.type === "text");+ expect(text).toEqual({+ type: "text",+ text: "Compare these.",+ state: "done",+ });+ expect(parts.map((p) => p.type)).toEqual([+ "text",+ "file",+ "data-workspace-folder",+ ]);+ // Neither hint may survive as prose in the user's own bubble.+ expect(JSON.stringify(parts)).not.toContain("list_workspace_files");+ expect(JSON.stringify(parts)).not.toContain("read_workspace_file");+ });++ it("still parses a legacy files-only block", () => {+ const parts = userParts(+ `Here.\n\n[Attached files]\n- a.txt (text/plain, 1.0 KB), file_id=0f11eeee-1111-4222-8333-444455556666\n${FILE_HINT}`,+ );+ expect(parts.map((p) => p.type)).toEqual(["text", "file"]);+ expect(JSON.stringify(parts)).not.toContain("[Attached files]");+ });++ it("leaves a message with no block alone", () => {+ expect(userParts("just text")).toEqual([+ { type: "text", text: "just text", state: "done" },+ ]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/workspaceAttachments.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/workspaceAttachments.test.tsindex 0f48ff0752..0f786d5858 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/workspaceAttachments.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/workspaceAttachments.test.ts@@ -3,9 +3,12 @@ import { describe, expect, it } from "vitest";import openapiSpec from "@/app/api/openapi.json";import {type Attachment,+ type WorkspaceAttachment,appendWithinCap,attachmentName,+ buildStoredAttachmentParts,buildWorkspaceFilePart,+ buildWorkspaceFolderPart,MAX_ATTACHMENTS,partitionAttachments,workspaceFileDownloadUrl,@@ -75,15 +78,115 @@ describe("workspaceAttachments", () => {workspaceItemToAttachment(makeWorkspaceItem({ id: "ws-1" })),];- const { localFiles, workspaceFiles } = partitionAttachments(attachments);+ const { localFiles, workspaceAttachments } =+ partitionAttachments(attachments);expect(localFiles).toEqual([localFile]);- expect(workspaceFiles).toEqual([- { fileId: "ws-1", name: "report.pdf", mimeType: "application/pdf" },+ expect(workspaceAttachments).toEqual([+ {+ kind: "workspace",+ fileId: "ws-1",+ name: "report.pdf",+ mimeType: "application/pdf",+ },]);});});+function makeFolderAttachment(id: string, name = "Q3"): WorkspaceAttachment {+ return {+ kind: "folder",+ folderId: id,+ name,+ fileCount: 3,+ subfolderCount: 0,+ };+}++describe("folder attachments", () => {+ it("names a folder the same way a file is named", () => {+ expect(attachmentName(makeFolderAttachment("fld-1"))).toBe("Q3");+ });++ it("builds a data part the model reads as a folder id", () => {+ expect(+ buildWorkspaceFolderPart({+ folderId: "fld-1",+ name: "Q3",+ fileCount: 3,+ subfolderCount: 1,+ }),+ ).toEqual({+ type: "data-workspace-folder",+ data: { id: "fld-1", name: "Q3", fileCount: 3 },+ });+ });++ it("partitions a folder alongside the files", () => {+ const { localFiles, workspaceAttachments } = partitionAttachments([+ makeFolderAttachment("fld-1"),+ workspaceItemToAttachment(makeWorkspaceItem({ id: "ws-1" })),+ ]);+ expect(localFiles).toEqual([]);+ expect(workspaceAttachments).toHaveLength(2);+ expect(workspaceAttachments[0].kind).toBe("folder");+ });++ it("accepts folders up to the cap and refuses the rest", () => {+ const five = Array.from({ length: 5 }, (_, i) =>+ makeFolderAttachment(`fld-${i}`, `F${i}`),+ );+ const first = appendWithinCap([], five);+ expect(first.next).toHaveLength(5);+ expect(first.refusedFolders).toBe(0);++ const sixth = appendWithinCap(first.next, [+ makeFolderAttachment("fld-5", "F5"),+ ]);+ expect(sixth.next).toHaveLength(5);+ expect(sixth.refusedFolders).toBe(1);+ });++ it("skips a re-picked folder without counting it as refused", () => {+ const held = [makeFolderAttachment("fld-1")];+ const again = appendWithinCap(held, [makeFolderAttachment("fld-1")]);+ expect(again.next).toHaveLength(1);+ expect(again.refusedFolders).toBe(0);+ });++ it("lets files past the folder cap, which only counts folders", () => {+ const five = Array.from({ length: 5 }, (_, i) =>+ makeFolderAttachment(`fld-${i}`, `F${i}`),+ );+ const withFile = appendWithinCap(five, [+ workspaceItemToAttachment(makeWorkspaceItem({ id: "ws-9" })),+ ]);+ expect(withFile.next).toHaveLength(6);+ expect(withFile.refusedFolders).toBe(0);+ });++ it("counts a folder against the attachment cap too", () => {+ const full = makeLocals(MAX_ATTACHMENTS);+ const result = appendWithinCap(full, [makeFolderAttachment("fld-1")]);+ expect(result.next).toHaveLength(MAX_ATTACHMENTS);+ expect(result.refused).toBe(1);+ expect(result.refusedFolders).toBe(0);+ });++ it("builds one part per stored attachment, folder or file", () => {+ const parts = buildStoredAttachmentParts([+ makeFolderAttachment("fld-1"),+ {+ kind: "workspace",+ fileId: "ws-1",+ name: "a.csv",+ mimeType: "text/csv",+ },+ ]);+ expect(parts.map((p) => p.type)).toEqual(["data-workspace-folder", "file"]);+ });+});+describe("appendWithinCap", () => {it("keeps exactly MAX_ATTACHMENTS and reports the rest as refused", () => {const incoming = makeLocals(MAX_ATTACHMENTS + 3);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.tsindex 819ad36498..31cefc2ae8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts@@ -1,6 +1,10 @@import { getGetWorkspaceDownloadFileByIdUrl } from "@/app/api/__generated__/endpoints/workspace/workspace";import type { FileUIPart, UIMessage, UIDataTypes, UITools } from "ai";import { toolDisplayName } from "./toolDisplay";+import {+ WORKSPACE_FOLDER_PART_TYPE,+ type WorkspaceFolderPartData,+} from "./workspaceAttachments";export interface TurnStats {durationMs?: number;@@ -84,18 +88,39 @@ function coerceSessionChatMessages(/*** Parse the `[Attached files]` block appended by the backend and return- * the cleaned text plus reconstructed FileUIPart objects.+ * the cleaned text plus the reconstructed attachment parts.*- * Backend format:+ * Backend format (`build_files_block`), with either hint line present or+ * both — a message can attach only folders, so neither may be assumed:* ```* \n\n[Attached files]* - name.jpg (image/jpeg, 191.0 KB), file_id=<uuid>+ * - Q3 (folder, 3 file(s) directly inside), folder_id=<uuid>* Use read_workspace_file with the file_id to access file contents.+ * Use list_workspace_files with the folder_id to see what is in a folder.* ```*/-const ATTACHED_FILES_RE =- /\n?\n?\[Attached files\]\n([\s\S]*?)Use read_workspace_file with the file_id to access file contents\./;+const FILE_HINT =+ "Use read_workspace_file with the file_id to access file contents.";+const FOLDER_HINT =+ "Use list_workspace_files with the folder_id to see what is in a folder.";+// Ends at the LAST hint line, so a hint the block also carries is never left+// behind as raw text in the user's bubble.+const ATTACHED_FILES_RE = new RegExp(+ `\\n?\\n?\\[Attached files\\]\\n([\\s\\S]*?)(?:${escapeRe(FILE_HINT)}|${escapeRe(FOLDER_HINT)})(?:\\n(?:${escapeRe(FILE_HINT)}|${escapeRe(FOLDER_HINT)}))*`,+);const FILE_LINE_RE = /^- (.+) \(([^,]+),\s*[\d.]+ KB\), file_id=([0-9a-f-]+)$/;+const FOLDER_LINE_RE =+ /^- (.+) \(folder, (\d+) file\(s\) directly inside\), folder_id=([0-9a-f-]+)$/;++function escapeRe(text: string): string {+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++interface WorkspaceFolderUiPart {+ type: typeof WORKSPACE_FOLDER_PART_TYPE;+ data: WorkspaceFolderPartData;+}/** Default file URL builder — routes through the authed workspace* download endpoint. Public viewers override this via the@@ -110,16 +135,28 @@ function extractFileParts(): {cleanText: string;fileParts: FileUIPart[];+ folderParts: WorkspaceFolderUiPart[];} {const match = content.match(ATTACHED_FILES_RE);- if (!match) return { cleanText: content, fileParts: [] };+ if (!match) return { cleanText: content, fileParts: [], folderParts: [] };const cleanText = content.replace(match[0], "").trim();const lines = match[1].trim().split("\n");const fileParts: FileUIPart[] = [];+ const folderParts: WorkspaceFolderUiPart[] = [];for (const line of lines) {- const m = line.trim().match(FILE_LINE_RE);+ const trimmed = line.trim();+ const folder = trimmed.match(FOLDER_LINE_RE);+ if (folder) {+ const [, name, fileCount, id] = folder;+ folderParts.push({+ type: WORKSPACE_FOLDER_PART_TYPE,+ data: { id, name, fileCount: Number(fileCount) },+ });+ continue;+ }+ const m = trimmed.match(FILE_LINE_RE);if (!m) continue;const [, filename, mimeType, fileId] = m;fileParts.push({@@ -130,7 +167,7 @@ function extractFileParts(});}- return { cleanText, fileParts };+ return { cleanText, fileParts, folderParts };}function safeJsonParse(value: string): unknown {@@ -410,7 +447,7 @@ export function convertChatSessionMessagesToUiMessages(state: "done",} as UIMessage<unknown, UIDataTypes, UITools>["parts"][number]);} else if (msg.role === "user") {- const { cleanText, fileParts } = extractFileParts(+ const { cleanText, fileParts, folderParts } = extractFileParts(msg.content,fileUrlBuilder,);@@ -420,6 +457,15 @@ export function convertChatSessionMessagesToUiMessages(for (const fp of fileParts) {parts.push(fp);}+ for (const folderPart of folderParts) {+ parts.push(+ folderPart as UIMessage<+ unknown,+ UIDataTypes,+ UITools+ >["parts"][number],+ );+ }} else {parts.push({ type: "text", text: msg.content, state: "done" });}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.tsindex 28eb28c6aa..5a374b7594 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts@@ -1,4 +1,5 @@import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import type { WorkspaceFolder } from "@/app/api/__generated__/models/workspaceFolder";import type { FileUIPart } from "ai";/**@@ -7,19 +8,53 @@ import type { FileUIPart } from "ai";* message needs no upload — we build a `FileUIPart` pointing straight at the* workspace download URL.*/-export interface WorkspaceAttachment {+export interface WorkspaceFileAttachment {fileId: string;name: string;mimeType: string;}/**- * A chat-composer attachment: either a local file awaiting upload or a- * reference to an existing workspace file.+ * A folder named for the model to open with `list_workspace_files`. It is+ * never expanded into its files, so it costs one attachment whatever it holds.*/-export type Attachment =- | { kind: "local"; file: File }- | ({ kind: "workspace" } & WorkspaceAttachment);+export interface WorkspaceFolderAttachment {+ folderId: string;+ name: string;+ fileCount: number;+ subfolderCount: number;+}++/** What crosses `onSend`: a stored file or a folder pointer. */+export type WorkspaceAttachment =+ | ({ kind: "workspace" } & WorkspaceFileAttachment)+ | ({ kind: "folder" } & WorkspaceFolderAttachment);++/**+ * A chat-composer attachment: a local file awaiting upload, a reference to an+ * existing workspace file, or a folder.+ */+export type Attachment = { kind: "local"; file: File } | WorkspaceAttachment;++/**+ * The backend caps `folder_ids` at 5 per message. Without the same ceiling+ * here the composer would build a message the send answers with a 422.+ * A folder also costs one of the `MAX_ATTACHMENTS`.+ */+export const MAX_FOLDER_ATTACHMENTS = 5;++export const WORKSPACE_FOLDER_PART_TYPE = "data-workspace-folder";++/** A message part for an attachment that needed no upload. */+export type StoredAttachmentPart =+ | FileUIPart+ | ReturnType<typeof buildWorkspaceFolderPart>;++export interface WorkspaceFolderPartData {+ id: string;+ name: string;+ fileCount: number;+}// Must equal `file_ids` max_length on StreamChatRequest/QueuePendingMessageRequest// (chat/routes.py): every attachment, uploaded or from the workspace, is one entry.@@ -38,12 +73,33 @@ export function workspaceItemToAttachment(item: WorkspaceFileItem): Attachment {};}+export function workspaceFolderToAttachment(+ folder: WorkspaceFolder,+ subfolderCount: number,+): Attachment {+ return {+ kind: "folder",+ folderId: folder.id,+ name: folder.name,+ fileCount: folder.file_count ?? 0,+ subfolderCount,+ };+}+export function attachmentName(attachment: Attachment): string {return attachment.kind === "local" ? attachment.file.name : attachment.name;}+/** Stable identity for de-duplication and for `AnimatePresence` keys. */+export function attachmentKey(attachment: Attachment): string {+ if (attachment.kind === "workspace") return `ws-${attachment.fileId}`;+ if (attachment.kind === "folder") return `folder-${attachment.folderId}`;+ const { file } = attachment;+ return `local-${file.name}-${file.size}-${file.lastModified}`;+}+export function buildWorkspaceFilePart(- attachment: WorkspaceAttachment,+ attachment: WorkspaceFileAttachment,): FileUIPart {return {type: "file",@@ -53,50 +109,80 @@ export function buildWorkspaceFilePart(};}-export function partitionAttachments(attachments: Attachment[]): {- localFiles: File[];- workspaceFiles: WorkspaceAttachment[];-} {- const localFiles: File[] = [];- const workspaceFiles: WorkspaceAttachment[] = [];- for (const attachment of attachments) {- if (attachment.kind === "local") {- localFiles.push(attachment.file);- } else {- workspaceFiles.push({- fileId: attachment.fileId,- name: attachment.name,- mimeType: attachment.mimeType,- });- }- }- return { localFiles, workspaceFiles };+export function buildWorkspaceFolderPart(+ attachment: WorkspaceFolderAttachment,+) {+ return {+ type: WORKSPACE_FOLDER_PART_TYPE,+ data: {+ id: attachment.folderId,+ name: attachment.name,+ fileCount: attachment.fileCount,+ },+ } as const;}-/** Appends what fits under `MAX_ATTACHMENTS`, skipping workspace files already- * attached — a re-picked file is not counted in `refused`. */+/**+ * Adds attachments the composer does not already hold, refusing anything past+ * `MAX_ATTACHMENTS` and folders past `MAX_FOLDER_ATTACHMENTS`. A re-picked+ * attachment is skipped without being reported as refused: the user asked for+ * it and it is there.+ */export function appendWithinCap(- prev: Attachment[],+ held: Attachment[],incoming: Attachment[],-): { next: Attachment[]; refused: number } {- const next = [...prev];+): { next: Attachment[]; refused: number; refusedFolders: number } {+ const keys = new Set(held.map(attachmentKey));+ const next = [...held];+ let folders = held.filter((a) => a.kind === "folder").length;let refused = 0;+ let refusedFolders = 0;+for (const attachment of incoming) {- if (- attachment.kind === "workspace" &&- isAttached(next, attachment.fileId)- ) {- continue;- }+ if (keys.has(attachmentKey(attachment))) continue;if (next.length >= MAX_ATTACHMENTS) {refused += 1;continue;}+ if (attachment.kind === "folder") {+ if (folders >= MAX_FOLDER_ATTACHMENTS) {+ refusedFolders += 1;+ continue;+ }+ folders += 1;+ }+ keys.add(attachmentKey(attachment));next.push(attachment);}- return { next, refused };+ return { next, refused, refusedFolders };+}++export function partitionAttachments(attachments: Attachment[]): {+ localFiles: File[];+ workspaceAttachments: WorkspaceAttachment[];+} {+ const localFiles: File[] = [];+ const workspaceAttachments: WorkspaceAttachment[] = [];+ for (const attachment of attachments) {+ if (attachment.kind === "local") localFiles.push(attachment.file);+ else workspaceAttachments.push(attachment);+ }+ return { localFiles, workspaceAttachments };+}++/** Message parts for the attachments that need no upload. */+export function buildStoredAttachmentParts(+ attachments: WorkspaceAttachment[],+): StoredAttachmentPart[] {+ return attachments.map((attachment) =>+ attachment.kind === "folder"+ ? buildWorkspaceFolderPart(attachment)+ : buildWorkspaceFilePart(attachment),+ );}-function isAttached(attachments: Attachment[], fileId: string): boolean {- return attachments.some((a) => a.kind === "workspace" && a.fileId === fileId);+export function isFolderPart(+ part: StoredAttachmentPart,+): part is ReturnType<typeof buildWorkspaceFolderPart> {+ return part.type === WORKSPACE_FOLDER_PART_TYPE;}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.tsindex e4a9ac4087..36cbcad154 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts@@ -12,9 +12,11 @@ import {import { describeSendFailure } from "./components/ChatInput/helpers";import type { ExpertKickoffMetadata } from "./expertKickoff";import {- buildWorkspaceFilePart,+ buildStoredAttachmentParts,+ isFolderPart,MAX_ATTACHMENTS,workspaceFileDownloadUrl,+ type StoredAttachmentPart,type WorkspaceAttachment,} from "./helpers/workspaceAttachments";import { useCopilotUIStore } from "./store";@@ -109,7 +111,7 @@ export function useSendMessage({sid: string,text: string,files: File[],- prebuiltParts: FileUIPart[],+ prebuiltParts: StoredAttachmentPart[],metadata?: ExpertKickoffMetadata,) {// The per-click UUID that becomes the backend's ``ChatMessage.id``@@ -121,11 +123,7 @@ export function useSendMessage({// target and break the optimistic-render path that pushes the user// bubble into ``messages`` synchronously.if (files.length === 0) {- await sendMessage({- text,- files: prebuiltParts.length > 0 ? prebuiltParts : undefined,- metadata,- });+ await sendMessage(messageInput(text, prebuiltParts, metadata));return;}// The bubble shows right away; the transcript reads "Uploading N files…"@@ -149,12 +147,12 @@ export function useSendMessage({if (prebuiltParts.length === 0) {throw new Error("All file uploads failed");}- send = sendMessage({ text, files: prebuiltParts, metadata });+ send = sendMessage(messageInput(text, prebuiltParts, metadata));} else {// Merge already-stored workspace parts with the freshly uploaded ones so// a single message can mix both kinds of attachment.const allParts = [...prebuiltParts, ...buildFileParts(uploaded)];- send = sendMessage({ text, files: allParts, metadata });+ send = sendMessage(messageInput(text, allParts, metadata));}} finally {// `sendMessage` pushes the user bubble into `messages` synchronously,@@ -166,6 +164,29 @@ export function useSendMessage({await send;}+ function messageInput(+ text: string,+ parts: StoredAttachmentPart[],+ metadata?: ExpertKickoffMetadata,+ ) {+ // `{ text, files }` only accepts FileUIParts, so a message carrying a+ // folder is built from its parts instead.+ if (!parts.some(isFolderPart)) {+ return {+ text,+ files: parts.length > 0 ? (parts as FileUIPart[]) : undefined,+ metadata,+ };+ }+ return {+ parts: [+ ...parts,+ ...(text ? [{ type: "text" as const, text }] : []),+ ] as UIMessage["parts"],+ metadata,+ };+ }+// Hold dispatchToSession in a ref so the queued-send effect can fire// exclusively on sessionId change (the real trigger) while still calling// the latest closure — which captures the refreshed `sendMessage` after@@ -230,7 +251,7 @@ export function useSendMessage({isUserStoppingRef.current = false;- const workspaceParts = (workspaceFiles ?? []).map(buildWorkspaceFilePart);+ const workspaceParts = buildStoredAttachmentParts(workspaceFiles ?? []);if (sessionId) {const { pendingFileParts, setPendingFileParts } =@@ -291,7 +312,7 @@ export function useSendMessage({}}- function setPendingFileParts(parts: FileUIPart[]) {+ function setPendingFileParts(parts: StoredAttachmentPart[]) {useCopilotStreamStore.getState().setPendingFileParts(parts);}@@ -320,7 +341,7 @@ export function useSendMessage({*/function recoverFailedFirstSend(text: string,- parts: FileUIPart[],+ parts: StoredAttachmentPart[],error: unknown,) {if (text) useCopilotUIStore.getState().setInitialPrompt(text);@@ -341,13 +362,17 @@ function recoverFailedFirstSend(function describePendingUpload(text: string,files: File[],- prebuiltParts: FileUIPart[],+ prebuiltParts: StoredAttachmentPart[],): PendingUploadSend {- const stored: PendingUploadAttachment[] = prebuiltParts.map((part) => ({- name: part.filename ?? "file",- mediaType: part.mediaType,- isUploading: false,- }));+ const stored: PendingUploadAttachment[] = prebuiltParts.map((part) =>+ isFolderPart(part)+ ? { name: part.data.name, mediaType: "folder", isUploading: false }+ : {+ name: part.filename ?? "file",+ mediaType: part.mediaType,+ isUploading: false,+ },+ );const local: PendingUploadAttachment[] = files.map((file) => ({name: file.name,mediaType: file.type || "application/octet-stream",