Skip to content

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

feat(frontend/copilot): shift-click selects a range in the workspace file picker (#14771)

Reinier van der Leerafe01fcf6708
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.tsx
index c9c4f5f05d..76abb2739c 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
@@ -11,15 +11,17 @@ import { Button } from "@/components/atoms/Button/Button";
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import { Text } from "@/components/atoms/Text/Text";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
+import { isKey } from "@/lib/keyboard";
import { cn } from "@/lib/utils";
-import { useEffect, useRef, useState } from "react";
+import type { SelectionModifiers } from "./helpers";
+import { type KeyboardEvent, useEffect, useRef, useState } from "react";
import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
interface Props {
files: WorkspaceFileItem[];
selectedIds: ReadonlyMap<string, WorkspaceFileItem>;
- onToggle: (item: WorkspaceFileItem) => void;
+ onSelect: (index: number, modifiers: SelectionModifiers) => void;
isLoading: boolean;
isError: boolean;
error: unknown;
@@ -31,7 +33,7 @@ interface Props {
export function WorkspaceFileList({
files,
selectedIds,
- onToggle,
+ onSelect,
isLoading,
isError,
error,
@@ -102,14 +104,20 @@ export function WorkspaceFileList({
className="max-h-[24rem] overflow-y-auto py-1"
>
<div className="grid grid-cols-2 gap-2">
- {files.map((file) => {
+ {files.map((file, index) => {
const isSelected = selectedIds.has(file.id);
const fileIcon = getFileTypeIcon(file.mime_type);
return (
<button
key={file.id}
type="button"
- onClick={() => onToggle(file)}
+ onClick={(e) =>
+ onSelect(index, {
+ shift: e.shiftKey,
+ meta: e.metaKey || e.ctrlKey,
+ })
+ }
+ onKeyDown={(e) => handleRangeKey(e, index, onSelect)}
aria-pressed={isSelected}
className={cn(
"flex w-full items-center gap-3 rounded-2xl border bg-white p-3 text-left transition-colors",
@@ -164,3 +172,19 @@ export function WorkspaceFileList({
</div>
);
}
+
+/**
+ * Firefox reports shiftKey as false on the click it synthesises from
+ * Shift+Enter/Space (Chromium reports true), so the keyboard range cannot ride
+ * that click. Handle the chord here and preventDefault, which also stops
+ * Chromium firing a second, plain selection.
+ */
+function handleRangeKey(
+ e: KeyboardEvent<HTMLButtonElement>,
+ index: number,
+ onSelect: (index: number, modifiers: SelectionModifiers) => void,
+) {
+ if (!e.shiftKey || !isKey(e, "Enter", " ")) return;
+ e.preventDefault();
+ onSelect(index, { shift: true });
+}
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.tsx
index cae6335e84..dad3e58d5e 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
@@ -70,7 +70,7 @@ export function WorkspaceFilePicker({
<WorkspaceFileList
files={picker.files}
selectedIds={picker.selectedIds}
- onToggle={picker.toggle}
+ onSelect={picker.select}
isLoading={picker.isLoading}
isError={picker.isError}
error={picker.error}
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.tsx
index 911ab1cbee..94714700e9 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
@@ -182,4 +182,122 @@ describe("WorkspaceFilePicker", () => {
await screen.findByRole("button", { name: /load more/i }),
).toBeTruthy();
});
+
+ it("shift-click selects the inclusive range from the last plain click", async () => {
+ mockPage(makeFiles(5));
+ render(
+ <WorkspaceFilePicker isOpen onClose={vi.fn()} onConfirm={vi.fn()} />,
+ );
+ await screen.findByText("f-0");
+
+ fireEvent.click(card("f-1"));
+ fireEvent.click(card("f-3"), { shiftKey: true });
+
+ expect(selectedNames()).toEqual(["f-1", "f-2", "f-3"]);
+ });
+
+ it("ranges backwards too, and confirms the whole range", async () => {
+ const files = makeFiles(5);
+ mockPage(files);
+ const onConfirm = vi.fn();
+ render(
+ <WorkspaceFilePicker isOpen onClose={vi.fn()} onConfirm={onConfirm} />,
+ );
+ await screen.findByText("f-0");
+
+ fireEvent.click(card("f-3"));
+ 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]]);
+ });
+
+ // Firefox reports shiftKey false on the click it synthesises from
+ // Shift+Enter, so the chord is handled on keydown instead.
+ it("ranges from the anchor on Shift+Enter and Shift+Space", async () => {
+ mockPage(makeFiles(5));
+ render(
+ <WorkspaceFilePicker isOpen onClose={vi.fn()} onConfirm={vi.fn()} />,
+ );
+ await screen.findByText("f-0");
+
+ fireEvent.click(card("f-0"));
+ fireEvent.keyDown(card("f-2"), { key: "Enter", shiftKey: true });
+ expect(selectedNames()).toEqual(["f-0", "f-1", "f-2"]);
+
+ fireEvent.keyDown(card("f-4"), { key: " ", shiftKey: true });
+ expect(selectedNames()).toEqual(["f-0", "f-1", "f-2", "f-3", "f-4"]);
+ });
+
+ it("leaves a plain Enter to the button's own click", async () => {
+ mockPage(makeFiles(3));
+ render(
+ <WorkspaceFilePicker isOpen onClose={vi.fn()} onConfirm={vi.fn()} />,
+ );
+ await screen.findByText("f-0");
+
+ fireEvent.keyDown(card("f-1"), { key: "Enter" });
+
+ expect(selectedNames()).toEqual([]);
+ });
+
+ it("drops the anchor when the filter changes", async () => {
+ mockPage(makeFiles(5));
+ render(
+ <WorkspaceFilePicker isOpen onClose={vi.fn()} onConfirm={vi.fn()} />,
+ );
+ await screen.findByText("f-0");
+ fireEvent.click(card("f-1"));
+
+ fireEvent.change(screen.getByLabelText(/search workspace files/i), {
+ target: { value: "f" },
+ });
+ fireEvent.click(card("f-3"), { shiftKey: true });
+
+ // Without an anchor the Shift+click is a plain toggle, not a range.
+ expect(selectedNames()).toEqual(["f-1", "f-3"]);
+ });
+
+ // No listbox role: that promises arrow-key navigation the grid lacks.
+ it("exposes each card's selection as a pressed toggle button", async () => {
+ mockPage(makeFiles(2));
+ render(
+ <WorkspaceFilePicker isOpen onClose={vi.fn()} onConfirm={vi.fn()} />,
+ );
+ await screen.findByText("f-0");
+
+ expect(screen.queryByRole("listbox")).toBeNull();
+ expect(card("f-0").getAttribute("aria-pressed")).toBe("false");
+
+ fireEvent.click(card("f-0"));
+ expect(card("f-0").getAttribute("aria-pressed")).toBe("true");
+ });
});
+
+function mockPage(files: ReturnType<typeof makeFiles>) {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files, has_more: false },
+ });
+}
+
+function card(name: string) {
+ return screen.getByRole("button", { name: new RegExp(`^${name}\\b`) });
+}
+
+function selectedNames() {
+ return screen
+ .getAllByRole("button")
+ .filter((el) => el.getAttribute("aria-pressed") === "true")
+ .map((el) => el.querySelector("[title]")?.textContent ?? "")
+ .sort();
+}
+
+function makeFiles(count: number) {
+ return Array.from({ length: count }, (_, i) => ({
+ ...FILE,
+ id: `id-${i}`,
+ name: `f-${i}`,
+ path: `/workspace/f-${i}`,
+ }));
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..a45b44d4f5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/helpers.test.ts
@@ -0,0 +1,144 @@
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { describe, expect, it } from "vitest";
+import { applySelection, orderByList, type Selection } from "../helpers";
+
+const FILES = makeFiles(6);
+
+describe("applySelection", () => {
+ it("toggles a plain click and moves the anchor to it", () => {
+ const first = applySelection(empty(), FILES, 2);
+ expect(names(first)).toEqual(["f-2"]);
+ expect(first.anchor).toBe("id-2");
+
+ const second = applySelection(first, FILES, 2);
+ expect(names(second)).toEqual([]);
+ expect(second.anchor).toBe("id-2");
+ });
+
+ it("selects the inclusive range forwards from the anchor", () => {
+ const anchored = applySelection(empty(), FILES, 1);
+
+ const ranged = applySelection(anchored, FILES, 4, { shift: true });
+
+ expect(names(ranged)).toEqual(["f-1", "f-2", "f-3", "f-4"]);
+ expect(ranged.anchor).toBe("id-1");
+ });
+
+ it("selects the inclusive range backwards from the anchor", () => {
+ const anchored = applySelection(empty(), FILES, 4);
+
+ const ranged = applySelection(anchored, FILES, 1, { shift: true });
+
+ expect(names(ranged)).toEqual(["f-1", "f-2", "f-3", "f-4"]);
+ expect(ranged.anchor).toBe("id-4");
+ });
+
+ it("treats Shift with no anchor as a plain click", () => {
+ const result = applySelection(empty(), FILES, 3, { shift: true });
+
+ expect(names(result)).toEqual(["f-3"]);
+ expect(result.anchor).toBe("id-3");
+ });
+
+ it("adds to the selection rather than replacing it", () => {
+ const withFar = applySelection(empty(), FILES, 5);
+ const anchored = applySelection(withFar, FILES, 0);
+
+ const ranged = applySelection(anchored, FILES, 2, { shift: true });
+
+ expect(names(ranged)).toEqual(["f-0", "f-1", "f-2", "f-5"]);
+ });
+
+ it("never clears a file a second range passes back over", () => {
+ const anchored = applySelection(empty(), FILES, 0);
+ const wide = applySelection(anchored, FILES, 4, { shift: true });
+
+ const narrow = applySelection(wide, FILES, 2, { shift: true });
+
+ expect(names(narrow)).toEqual(["f-0", "f-1", "f-2", "f-3", "f-4"]);
+ });
+
+ it("toggles without moving the anchor for Ctrl/Cmd", () => {
+ const anchored = applySelection(empty(), FILES, 1);
+
+ const withExtra = applySelection(anchored, FILES, 4, { meta: true });
+ expect(withExtra.anchor).toBe("id-1");
+
+ // The anchor stayed put, so the range still runs from the plain click.
+ const ranged = applySelection(withExtra, FILES, 3, { shift: true });
+ expect(names(ranged)).toEqual(["f-1", "f-2", "f-3", "f-4"]);
+ });
+
+ it("ranges from the anchor file after the list shifts under it", () => {
+ const anchored = applySelection(empty(), FILES, 1);
+ const shifted = [{ ...FILES[0], id: "id-new", name: "new" }, ...FILES];
+
+ // f-1 now sits at index 2; index 4 is f-3.
+ const ranged = applySelection(anchored, shifted, 4, { shift: true });
+
+ expect(names(ranged)).toEqual(["f-1", "f-2", "f-3"]);
+ });
+
+ it("treats Shift as a plain click once the anchor file is gone", () => {
+ const anchored = applySelection(empty(), FILES, 1);
+ const without = FILES.filter((f) => f.id !== "id-1");
+
+ const result = applySelection(anchored, without, 3, { shift: true });
+
+ expect(names(result)).toEqual(["f-1", "f-4"]);
+ expect(result.anchor).toBe("id-4");
+ });
+
+ it("ignores an index no file sits at", () => {
+ const anchored = applySelection(empty(), FILES, 1);
+
+ expect(applySelection(anchored, FILES, 99)).toBe(anchored);
+ });
+});
+
+describe("orderByList", () => {
+ it("returns the selection in the order the list shows it", () => {
+ const backwards = applySelection(
+ applySelection(empty(), FILES, 3),
+ FILES,
+ 1,
+ { shift: true },
+ );
+
+ expect(orderByList(backwards.selected, FILES).map((f) => f.name)).toEqual([
+ "f-1",
+ "f-2",
+ "f-3",
+ ]);
+ });
+
+ it("keeps a file the list no longer shows, at the end", () => {
+ const selection = applySelection(empty(), FILES, 4);
+
+ const ordered = orderByList(selection.selected, [FILES[0], FILES[1]]);
+
+ expect(ordered.map((f) => f.name)).toEqual(["f-4"]);
+ });
+});
+
+function empty(): Selection {
+ return { selected: new Map(), anchor: null };
+}
+
+function names(selection: Selection) {
+ return Array.from(selection.selected.values())
+ .map((f) => f.name)
+ .sort();
+}
+
+function makeFiles(count: number): WorkspaceFileItem[] {
+ return Array.from({ length: count }, (_, i) => ({
+ id: `id-${i}`,
+ name: `f-${i}`,
+ path: `/workspace/f-${i}`,
+ mime_type: "text/plain",
+ size_bytes: 10,
+ origin: "uploaded",
+ created_at: "2026-01-01T00:00:00Z",
+ })) as WorkspaceFileItem[];
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/helpers.ts
new file mode 100644
index 0000000000..ce3ee53a86
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/helpers.ts
@@ -0,0 +1,86 @@
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+
+export type SelectionModifiers = { shift?: boolean; meta?: boolean };
+
+export interface Selection {
+ selected: ReadonlyMap<string, WorkspaceFileItem>;
+ /** Id of the last plainly clicked file. An id, not an index, because a
+ * refetch can reorder the list under it. */
+ anchor: string | null;
+}
+
+/**
+ * Applies one click to the selection, following the range conventions people
+ * already expect from a file manager: plain click toggles and re-anchors,
+ * Shift extends from the anchor, Ctrl/Cmd toggles without moving it.
+ */
+export function applySelection(
+ current: Selection,
+ files: WorkspaceFileItem[],
+ index: number,
+ modifiers: SelectionModifiers = {},
+): Selection {
+ const file = files[index];
+ if (!file) return current;
+
+ // Shift with no anchor in the list has nothing to extend from, so it
+ // behaves as the plain click that establishes one.
+ const anchorIndex = files.findIndex((f) => f.id === current.anchor);
+ if (modifiers.shift && anchorIndex !== -1) {
+ return {
+ selected: addRange(current.selected, files, anchorIndex, index),
+ anchor: current.anchor,
+ };
+ }
+ const selected = toggleOne(current.selected, file);
+ return { selected, anchor: modifiers.meta ? current.anchor : file.id };
+}
+
+/**
+ * Selection order is insertion order, which for a backwards range is the
+ * order clicked rather than the order shown. Sort by the list so the chips —
+ * and, at the cap, the files that survive it — match what the user saw.
+ * Anything no longer in `files` (paged off, or filtered out) keeps its place
+ * at the end.
+ */
+export function orderByList(
+ selected: ReadonlyMap<string, WorkspaceFileItem>,
+ files: WorkspaceFileItem[],
+): WorkspaceFileItem[] {
+ const listed: WorkspaceFileItem[] = [];
+ const unlisted = new Map(selected);
+ for (const file of files) {
+ if (unlisted.delete(file.id)) listed.push(file);
+ }
+ return [...listed, ...unlisted.values()];
+}
+
+/** A range only ever adds, so dragging back over chosen files cannot clear
+ * them — the union is what makes repeated ranges additive. */
+function addRange(
+ selected: ReadonlyMap<string, WorkspaceFileItem>,
+ files: WorkspaceFileItem[],
+ anchor: number,
+ index: number,
+): Map<string, WorkspaceFileItem> {
+ const next = new Map(selected);
+ const from = Math.min(anchor, index);
+ const to = Math.max(anchor, index);
+ for (const file of files.slice(from, to + 1)) {
+ next.set(file.id, file);
+ }
+ return next;
+}
+
+function toggleOne(
+ selected: ReadonlyMap<string, WorkspaceFileItem>,
+ file: WorkspaceFileItem,
+): Map<string, WorkspaceFileItem> {
+ const next = new Map(selected);
+ if (next.has(file.id)) {
+ next.delete(file.id);
+ } else {
+ next.set(file.id, file);
+ }
+ return next;
+}
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.ts
index c974123b19..0225934d87 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,6 +1,12 @@
import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/workspace";
import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
+import {
+ applySelection,
+ orderByList,
+ type Selection,
+ type SelectionModifiers,
+} from "./helpers";
import { type InfiniteData, useInfiniteQuery } from "@tanstack/react-query";
import { useState } from "react";
@@ -18,10 +24,12 @@ interface Args {
export function useWorkspaceFilePicker({ enabled, expertId }: Args) {
const [searchTerm, setSearchTerm] = useState("");
// Keep the full item (not just id) so a selection survives a search that
- // pages the file off the currently-loaded list.
- const [selected, setSelected] = useState<Map<string, WorkspaceFileItem>>(
- new Map(),
- );
+ // 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.
+ const [selection, setSelection] = useState<Selection>({
+ selected: new Map(),
+ anchor: null,
+ });
const debouncedSearch = useDebouncedValue(
searchTerm.trim(),
@@ -57,38 +65,38 @@ export function useWorkspaceFilePicker({ enabled, expertId }: Args) {
enabled,
});
- function toggle(item: WorkspaceFileItem) {
- setSelected((prev) => {
- const next = new Map(prev);
- if (next.has(item.id)) {
- next.delete(item.id);
- } else {
- next.set(item.id, item);
- }
- return next;
- });
+ const files = flattenFiles(query.data);
+
+ function select(index: number, modifiers?: SelectionModifiers) {
+ setSelection((prev) => applySelection(prev, files, index, modifiers));
+ }
+
+ function search(term: string) {
+ setSearchTerm(term);
+ // A range across a changed filter would span files never shown together.
+ setSelection((prev) => ({ ...prev, anchor: null }));
}
function reset() {
- setSelected(new Map());
+ setSelection({ selected: new Map(), anchor: null });
setSearchTerm("");
}
return {
- files: flattenFiles(query.data),
+ files,
isLoading: query.isLoading,
isError: query.isError,
error: query.error,
searchTerm,
- setSearchTerm,
+ setSearchTerm: search,
hasMore: !!query.hasNextPage,
isLoadingMore: query.isFetchingNextPage,
loadMore: () => {
query.fetchNextPage();
},
- selectedIds: selected,
- selectedFiles: Array.from(selected.values()),
- toggle,
+ selectedIds: selection.selected,
+ selectedFiles: orderByList(selection.selected, files),
+ select,
reset,
};
}
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.ts
index 4750750858..0f48ff0752 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
@@ -147,6 +147,19 @@ describe("appendWithinCap", () => {
expect(prev).toHaveLength(1);
});
+
+ it("keeps the first free slots of a workspace batch and counts the rest", () => {
+ const prev = makeLocals(MAX_ATTACHMENTS - 4);
+ const picked = Array.from({ length: 9 }, (_, i) =>
+ workspaceItemToAttachment(makeWorkspaceItem({ id: `ws-${i}` })),
+ );
+
+ const { next, refused } = appendWithinCap(prev, picked);
+
+ expect(next).toHaveLength(MAX_ATTACHMENTS);
+ expect(refused).toBe(5);
+ expect(next.slice(MAX_ATTACHMENTS - 4)).toEqual(picked.slice(0, 4));
+ });
});
describe("the composer cap against the backend's own", () => {