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.

fix(frontend/copilot): refuse attachments past the 20-attachment cap when they are added, not when the message is sent (#14770)

Reinier van der Leer52a83c623ccb
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.tsx
index 66bc48b230..8367a60f48 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,6 +3,7 @@ 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";
const { uploadFileDirectMock, toastMock } = vi.hoisted(() => ({
uploadFileDirectMock: vi.fn(),
@@ -469,3 +470,108 @@ describe("useSendMessage when creating the first chat's session fails", () => {
expect(renderSendMessage(SESSION_ID).result.current.pendingSend).toBeNull();
});
});
+
+function makeWorkspaceRefs(count: number) {
+ return Array.from({ length: count }, (_, i) => ({
+ fileId: `${FILE_ID.slice(0, -1)}${i}`,
+ name: `ws-${i}.txt`,
+ mimeType: "text/plain",
+ }));
+}
+
+describe("useSendMessage send-time cap backstop", () => {
+ // The composer refuses the extra file as it is added, so this path is
+ // unreachable through the UI — it stays for any caller that is not the
+ // composer, and for a state forced past the cap.
+ it("refuses a batch over the cap without uploading or sending", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result, sendMessage } = renderSendMessage();
+
+ await act(async () => {
+ await result.current.onSend(
+ "too much",
+ Array.from({ length: MAX_ATTACHMENTS + 1 }, (_, i) =>
+ makeFile(`over-${i}.pdf`),
+ ),
+ );
+ });
+
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Too many attachments" }),
+ );
+ expect(uploadFileDirectMock).not.toHaveBeenCalled();
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it("refuses a workspace-only batch over the cap", async () => {
+ const { result, sendMessage } = renderSendMessage();
+
+ await act(async () => {
+ await result.current.onSend(
+ "workspace only",
+ undefined,
+ makeWorkspaceRefs(MAX_ATTACHMENTS + 1),
+ );
+ });
+
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Too many attachments" }),
+ );
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it("counts local and workspace attachments together", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result, sendMessage } = renderSendMessage();
+
+ await act(async () => {
+ await result.current.onSend(
+ "mixed",
+ // Under the cap on its own, over it once the references are counted.
+ Array.from({ length: 6 }, (_, i) => makeFile(`local-${i}.pdf`)),
+ makeWorkspaceRefs(MAX_ATTACHMENTS - 5),
+ );
+ });
+
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Too many attachments" }),
+ );
+ expect(uploadFileDirectMock).not.toHaveBeenCalled();
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it("lets a mixed batch that exactly fills the cap through", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result } = renderSendMessage();
+
+ act(() => {
+ void result.current.onSend(
+ "mixed, but fits",
+ Array.from({ length: 6 }, (_, i) => makeFile(`local-${i}.pdf`)),
+ makeWorkspaceRefs(MAX_ATTACHMENTS - 6),
+ );
+ });
+
+ await waitFor(() => expect(uploadFileDirectMock).toHaveBeenCalledTimes(6));
+ expect(toastMock).not.toHaveBeenCalled();
+ });
+
+ it("lets exactly the cap through", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result } = renderSendMessage();
+
+ act(() => {
+ void result.current.onSend(
+ "just enough",
+ Array.from({ length: MAX_ATTACHMENTS }, (_, i) =>
+ makeFile(`ok-${i}.pdf`),
+ ),
+ );
+ });
+
+ await waitFor(() =>
+ expect(uploadFileDirectMock).toHaveBeenCalledTimes(MAX_ATTACHMENTS),
+ );
+ expect(toastMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
index fad4338fad..26ec04894b 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,9 +25,12 @@ import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspace
import {
type Attachment,
type WorkspaceAttachment,
+ appendWithinCap,
+ MAX_ATTACHMENTS,
partitionAttachments,
workspaceItemToAttachment,
} from "../../helpers/workspaceAttachments";
+import { AttachmentCapNotice } from "./components/AttachmentCapNotice";
import { ComposerPlusMenu } from "./components/ComposerPlusMenu";
import { DryRunToggleButton } from "./components/DryRunToggleButton";
import { FileChips } from "./components/FileChips";
@@ -131,6 +134,8 @@ export function ChatInput({
const showAdvancedComposerControls = useGetFlag(Flag.CHAT_MODE_OPTION);
const showWorkspaceFiles = useGetFlag(Flag.CHAT_WORKSPACE_FILES);
const [attachments, setAttachments] = useState<Attachment[]>([]);
+ // How many files the cap turned away on the last attach; 0 hides the notice.
+ const [refusedCount, setRefusedCount] = useState(0);
const [isPickerOpen, setIsPickerOpen] = useState(false);
const [isMultiline, setIsMultiline] = useState(false);
@@ -148,15 +153,13 @@ export function ChatInput({
// Merge files dropped onto the chat window into internal state.
useEffect(() => {
if (droppedFiles && droppedFiles.length > 0) {
- setAttachments((prev) => [
- ...prev,
- ...droppedFiles.map((file) => ({ kind: "local" as const, file })),
- ]);
+ addAttachments(droppedFiles.map(toLocalAttachment));
onDroppedFilesConsumed?.();
}
}, [droppedFiles, onDroppedFilesConsumed]);
const hasAttachments = attachments.length > 0;
+ const isAtCap = attachments.length >= MAX_ATTACHMENTS;
// isBusy disables non-essential interactions (attachment menu, voice recording)
// but must not disable the textarea itself — streaming allows queued messages.
const isBusy = disabled || isStreaming || isUploadingFiles;
@@ -177,6 +180,7 @@ export function ChatInput({
// user already attached new ones in the meantime.
const sent = attachments;
setAttachments([]);
+ setRefusedCount(0);
try {
await onSend(
message,
@@ -194,7 +198,7 @@ export function ChatInput({
});
const mentions = useChatMentions({
- enabled: showWorkspaceFiles && !isBusy,
+ enabled: showWorkspaceFiles && !isBusy && !isAtCap,
value,
setValue,
addWorkspaceFile: handleWorkspaceFileSelected,
@@ -269,27 +273,27 @@ export function ChatInput({
}
function handleFilesSelected(newFiles: File[]) {
- setAttachments((prev) => [
- ...prev,
- ...newFiles.map((file) => ({ kind: "local" as const, file })),
- ]);
+ addAttachments(newFiles.map(toLocalAttachment));
}
function handleWorkspaceFileSelected(item: WorkspaceFileItem) {
- setAttachments((prev) => {
- if (prev.some((a) => a.kind === "workspace" && a.fileId === item.id)) {
- return prev;
- }
- return [...prev, workspaceItemToAttachment(item)];
- });
+ handleWorkspaceFilesConfirmed([item]);
}
function handleWorkspaceFilesConfirmed(items: WorkspaceFileItem[]) {
- items.forEach(handleWorkspaceFileSelected);
+ addAttachments(items.map(workspaceItemToAttachment));
}
function handleRemoveAttachment(index: number) {
setAttachments((prev) => prev.filter((_, i) => i !== index));
+ // Removing one frees a slot, so the count the notice quotes is now stale.
+ setRefusedCount(0);
+ }
+
+ function addAttachments(incoming: Attachment[]) {
+ const { next, refused } = appendWithinCap(attachments, incoming);
+ setAttachments(next);
+ setRefusedCount(refused);
}
const isCompact = variant === "compact";
@@ -344,6 +348,13 @@ export function ChatInput({
className={stacked ? undefined : "mt-1.5"}
/>
)}
+ {refusedCount > 0 && (
+ <AttachmentCapNotice
+ refusedCount={refusedCount}
+ onDismiss={() => setRefusedCount(0)}
+ className={stacked ? undefined : "mt-1.5"}
+ />
+ )}
<FileChips
attachments={attachments}
onRemove={handleRemoveAttachment}
@@ -372,6 +383,7 @@ export function ChatInput({
onUseWorkspaceFile={() => setIsPickerOpen(true)}
onClearGuidedPrompt={handleClearGuidedPrompt}
disabled={isBusy}
+ isAtCap={isAtCap}
className={
stacked
? cn(
@@ -517,3 +529,7 @@ export function ChatInput({
</form>
);
}
+
+function toLocalAttachment(file: File): Attachment {
+ return { kind: "local", file };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInputAttachmentCap.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInputAttachmentCap.test.tsx
new file mode 100644
index 0000000000..65d9e64451
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInputAttachmentCap.test.tsx
@@ -0,0 +1,254 @@
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { MAX_ATTACHMENTS } from "../../../helpers/workspaceAttachments";
+import { ChatInput } from "../ChatInput";
+
+// Only the composer's periphery is stubbed: FileChips, ComposerPlusMenu and
+// the cap notice stay real, because the cap is a claim about what the user
+// ends up seeing and being able to click.
+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({
+ useGetV2ListChatConnections: () => ({
+ data: { status: 200, data: { offers: [] } },
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ }),
+}));
+
+vi.mock("@/app/(platform)/copilot/store", () => ({
+ useCopilotUIStore: () => ({
+ copilotLlmModel: "standard",
+ setCopilotLlmModel: vi.fn(),
+ copilotLlmAuth: { authProvider: "platform", credentialId: null },
+ setCopilotLlmAuth: vi.fn(),
+ isDryRun: false,
+ setIsDryRun: vi.fn(),
+ initialPrompt: null,
+ setInitialPrompt: vi.fn(),
+ sentMessageCount: 0,
+ notifyMessageSent: vi.fn(),
+ }),
+}));
+
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: {
+ CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
+ CHAT_WORKSPACE_FILES: "chat-workspace-files",
+ },
+ useGetFlag: () => false,
+}));
+
+vi.mock("../useVoiceRecording", () => ({
+ useVoiceRecording: () => ({
+ isRecording: false,
+ isTranscribing: false,
+ transcriptionError: null,
+ hasFailedRecording: false,
+ retryTranscription: vi.fn(),
+ downloadFailedRecording: vi.fn(),
+ dismissTranscriptionError: vi.fn(),
+ elapsedTime: 0,
+ toggleRecording: vi.fn(),
+ handleKeyDown: vi.fn(),
+ showMicButton: false,
+ isInputDisabled: false,
+ audioStream: null,
+ }),
+}));
+
+vi.mock("@/components/ai-elements/prompt-input", () => ({
+ PromptInputSubmit: ({ disabled }: { disabled?: boolean }) => (
+ <button disabled={disabled} data-testid="submit">
+ Send
+ </button>
+ ),
+ PromptInputButton: () => null,
+ PromptInputTextarea: (props: {
+ id?: string;
+ value?: string;
+ onChange?: React.ChangeEventHandler<HTMLTextAreaElement>;
+ onPaste?: React.ClipboardEventHandler<HTMLTextAreaElement>;
+ }) => (
+ <textarea
+ id={props.id}
+ value={props.value}
+ onChange={props.onChange}
+ onPaste={props.onPaste}
+ data-testid="textarea"
+ />
+ ),
+}));
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast: vi.fn(),
+ useToast: () => ({ toast: vi.fn(), dismiss: vi.fn() }),
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+const OVER = 3;
+
+describe("ChatInput attachment cap — pasting", () => {
+ it(`keeps the first ${MAX_ATTACHMENTS} and names how many it refused`, async () => {
+ const onSend = vi.fn().mockResolvedValue(undefined);
+ render(<ChatInput onSend={onSend} />);
+
+ pasteFiles(makeFiles(MAX_ATTACHMENTS + OVER));
+
+ const notice = await screen.findByRole("status");
+ expect(notice.textContent).toContain(
+ `Up to ${MAX_ATTACHMENTS} attachments per message — ${OVER} not added`,
+ );
+ expect(removeButtons()).toHaveLength(MAX_ATTACHMENTS);
+
+ fireEvent.submit(textarea().closest("form")!);
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ const [, files] = onSend.mock.calls[0];
+ expect(files).toHaveLength(MAX_ATTACHMENTS);
+ expect(files.map((f: File) => f.name)).toEqual(
+ makeFiles(MAX_ATTACHMENTS).map((f) => f.name),
+ );
+ });
+
+ it("leaves the typed message untouched when it refuses files", async () => {
+ render(<ChatInput onSend={vi.fn()} />);
+ fireEvent.change(textarea(), {
+ target: { value: "here are my quarterly notes" },
+ });
+
+ pasteFiles(makeFiles(MAX_ATTACHMENTS + OVER));
+
+ await screen.findByRole("status");
+ expect(textarea().value).toBe("here are my quarterly notes");
+ });
+
+ it("counts what is already attached, refusing only the overflow", async () => {
+ render(<ChatInput onSend={vi.fn()} />);
+
+ pasteFiles(makeFiles(MAX_ATTACHMENTS - 1));
+ expect(screen.queryByRole("status")).toBeNull();
+
+ pasteFiles(makeFiles(3, "late"));
+
+ const notice = await screen.findByRole("status");
+ expect(notice.textContent).toContain("2 not added");
+ expect(removeButtons()).toHaveLength(MAX_ATTACHMENTS);
+ });
+});
+
+describe("ChatInput attachment cap — dropping", () => {
+ it(`keeps the first ${MAX_ATTACHMENTS} of a drop and names the refusal`, async () => {
+ render(
+ <ChatInput
+ onSend={vi.fn()}
+ droppedFiles={makeFiles(MAX_ATTACHMENTS + OVER)}
+ onDroppedFilesConsumed={vi.fn()}
+ />,
+ );
+
+ const notice = await screen.findByRole("status");
+ expect(notice.textContent).toContain(`${OVER} not added`);
+ expect(removeButtons()).toHaveLength(MAX_ATTACHMENTS);
+ });
+
+ it("refuses a drop that lands on an already-full composer", async () => {
+ const { rerender } = render(
+ <ChatInput onSend={vi.fn()} onDroppedFilesConsumed={vi.fn()} />,
+ );
+ pasteFiles(makeFiles(MAX_ATTACHMENTS));
+ await waitFor(() => expect(removeButtons()).toHaveLength(MAX_ATTACHMENTS));
+
+ rerender(
+ <ChatInput
+ onSend={vi.fn()}
+ droppedFiles={makeFiles(2, "dropped")}
+ onDroppedFilesConsumed={vi.fn()}
+ />,
+ );
+
+ const notice = await screen.findByRole("status");
+ expect(notice.textContent).toContain("2 not added");
+ expect(removeButtons()).toHaveLength(MAX_ATTACHMENTS);
+ });
+});
+
+describe("ChatInput attachment cap — the notice and the affordance", () => {
+ it("dismisses the notice on request", async () => {
+ render(<ChatInput onSend={vi.fn()} />);
+ pasteFiles(makeFiles(MAX_ATTACHMENTS + OVER));
+ await screen.findByRole("status");
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /dismiss attachment limit/i }),
+ );
+
+ await waitFor(() => expect(screen.queryByRole("status")).toBeNull());
+ });
+
+ it("clears the notice once a removal frees a slot", async () => {
+ render(<ChatInput onSend={vi.fn()} />);
+ pasteFiles(makeFiles(MAX_ATTACHMENTS + OVER));
+ await screen.findByRole("status");
+
+ fireEvent.click(removeButtons()[0]);
+
+ await waitFor(() => expect(screen.queryByRole("status")).toBeNull());
+ });
+
+ it("disables the attach affordance at the cap and re-enables it below", async () => {
+ render(<ChatInput onSend={vi.fn()} />);
+ pasteFiles(makeFiles(MAX_ATTACHMENTS));
+
+ fireEvent.pointerDown(screen.getByTestId("composer-plus-button"), {
+ button: 0,
+ });
+ const attach = await screen.findByRole("menuitem", {
+ name: /attach file/i,
+ });
+ expect(attach.getAttribute("data-disabled")).not.toBeNull();
+ expect(attach.textContent).toContain(`${MAX_ATTACHMENTS} max`);
+
+ fireEvent.keyDown(attach, { key: "Escape" });
+ fireEvent.click(removeButtons()[0]);
+ fireEvent.pointerDown(screen.getByTestId("composer-plus-button"), {
+ button: 0,
+ });
+
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole("menuitem", { name: /attach file/i })
+ .getAttribute("data-disabled"),
+ ).toBeNull(),
+ );
+ });
+});
+
+function textarea() {
+ return screen.getByTestId("textarea") as HTMLTextAreaElement;
+}
+
+function removeButtons() {
+ return screen.queryAllByRole("button", { name: /^Remove / });
+}
+
+function pasteFiles(files: File[]) {
+ fireEvent.paste(textarea(), { clipboardData: { files } });
+}
+
+function makeFiles(count: number, prefix = "doc") {
+ return Array.from(
+ { length: count },
+ (_, i) =>
+ new File([`bytes-${i}`], `${prefix}-${i}.pdf`, {
+ type: "application/pdf",
+ }),
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AttachmentCapNotice.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AttachmentCapNotice.tsx
new file mode 100644
index 0000000000..4f429c4329
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AttachmentCapNotice.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { MAX_ATTACHMENTS } from "../../../helpers/workspaceAttachments";
+import { cn } from "@/lib/utils";
+import { Alert02Icon, Cancel01Icon } from "@hugeicons/core-free-icons";
+
+interface Props {
+ /** How many attachments the cap turned away on the last attach. */
+ refusedCount: number;
+ onDismiss: () => void;
+ className?: string;
+}
+
+/**
+ * Says what the cap refused, in the composer, so the draft the user is typing
+ * is never interrupted and never outlived by a toast.
+ */
+export function AttachmentCapNotice({
+ refusedCount,
+ onDismiss,
+ className,
+}: Props) {
+ return (
+ <div
+ role="status"
+ className={cn(
+ "flex w-full items-center gap-1.5 rounded-2xl bg-amber-50 px-3 py-1.5 text-sm text-amber-800",
+ className,
+ )}
+ >
+ <Icon icon={Alert02Icon} className="h-4 w-4 shrink-0" aria-hidden />
+ <span className="min-w-0 flex-1">
+ Up to {MAX_ATTACHMENTS} attachments per message — {refusedCount} not
+ added
+ </span>
+ <Button
+ type="button"
+ variant="icon"
+ size="icon-xs"
+ aria-label="Dismiss attachment limit notice"
+ onClick={onDismiss}
+ >
+ <Icon icon={Cancel01Icon} className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ComposerPlusMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ComposerPlusMenu.tsx
index d922da00a7..618f779afd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ComposerPlusMenu.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ComposerPlusMenu.tsx
@@ -8,6 +8,7 @@ import {
DropdownMenuTrigger,
} from "@/components/molecules/DropdownMenu/DropdownMenu";
import { cn } from "@/lib/utils";
+import { MAX_ATTACHMENTS } from "../../../helpers/workspaceAttachments";
import { useComposerPlusMenu } from "./useComposerPlusMenu";
import {
Attachment01Icon,
@@ -24,6 +25,9 @@ interface Props {
onUseWorkspaceFile?: () => void;
onClearGuidedPrompt?: () => void;
disabled?: boolean;
+ /** The message already holds `MAX_ATTACHMENTS` attachments: both file
+ * entries read disabled rather than letting the composer take another. */
+ isAtCap?: boolean;
className?: string;
}
@@ -32,6 +36,7 @@ export function ComposerPlusMenu({
onUseWorkspaceFile,
onClearGuidedPrompt,
disabled,
+ isAtCap = false,
className,
}: Props) {
const {
@@ -72,6 +77,7 @@ export function ComposerPlusMenu({
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-[14rem]">
<DropdownMenuItem
+ disabled={isAtCap}
onSelect={() => {
onClearGuidedPrompt?.();
openFilePicker();
@@ -79,9 +85,11 @@ export function ComposerPlusMenu({
>
<Icon icon={Attachment01Icon} className="mr-2 h-4 w-4" />
Attach file
+ {isAtCap && <CapLabel />}
</DropdownMenuItem>
{showWorkspaceOption && (
<DropdownMenuItem
+ disabled={isAtCap}
onSelect={() => {
onClearGuidedPrompt?.();
onUseWorkspaceFile?.();
@@ -89,6 +97,7 @@ export function ComposerPlusMenu({
>
<Icon icon={FolderOpenIcon} className="mr-2 h-4 w-4" />
Use File from Workspace
+ {isAtCap && <CapLabel />}
</DropdownMenuItem>
)}
<DropdownMenuItem
@@ -113,3 +122,11 @@ export function ComposerPlusMenu({
</>
);
}
+
+function CapLabel() {
+ return (
+ <span className="ml-auto pl-3 text-xs text-zinc-500">
+ {MAX_ATTACHMENTS} max
+ </span>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ComposerPlusMenu.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ComposerPlusMenu.test.tsx
index ecdfb5fb53..5fe8591338 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ComposerPlusMenu.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ComposerPlusMenu.test.tsx
@@ -1,6 +1,7 @@
import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useCopilotModal } from "../../../../useCopilotModal";
+import { MAX_ATTACHMENTS } from "../../../../helpers/workspaceAttachments";
import { ComposerPlusMenu } from "../ComposerPlusMenu";
let mockWorkspaceFilesFlag = false;
@@ -131,6 +132,43 @@ describe("ComposerPlusMenu", () => {
expect(onClearGuidedPrompt).toHaveBeenCalledTimes(2);
});
+ it("disables both file entries at the cap and says what the cap is", async () => {
+ mockWorkspaceFilesFlag = true;
+ const onFilesSelected = vi.fn();
+ const onUseWorkspaceFile = vi.fn();
+ render(
+ <ComposerPlusMenu
+ onFilesSelected={onFilesSelected}
+ onUseWorkspaceFile={onUseWorkspaceFile}
+ isAtCap
+ />,
+ );
+ openMenu();
+
+ const items = await screen.findAllByRole("menuitem");
+ const disabled = items.filter(
+ (item) => item.getAttribute("data-disabled") !== null,
+ );
+ expect(disabled.map((item) => item.textContent)).toEqual([
+ `Attach file${MAX_ATTACHMENTS} max`,
+ `Use File from Workspace${MAX_ATTACHMENTS} max`,
+ ]);
+
+ fireEvent.click(
+ screen.getByRole("menuitem", { name: /use file from workspace/i }),
+ );
+ expect(onUseWorkspaceFile).not.toHaveBeenCalled();
+ });
+
+ it("leaves the non-file entries alone at the cap", async () => {
+ render(<ComposerPlusMenu onFilesSelected={vi.fn()} isAtCap />);
+ openMenu();
+
+ fireEvent.click(await screen.findByRole("menuitem", { name: /skills/i }));
+
+ expect(screen.queryByRole("menuitem")).toBeNull();
+ });
+
it("hides the workspace option when its flag is disabled", async () => {
render(<ComposerPlusMenu onFilesSelected={vi.fn()} />);
openMenu();
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 16205a2b6e..4750750858 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
@@ -1,9 +1,12 @@
import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
import { describe, expect, it } from "vitest";
+import openapiSpec from "@/app/api/openapi.json";
import {
type Attachment,
+ appendWithinCap,
attachmentName,
buildWorkspaceFilePart,
+ MAX_ATTACHMENTS,
partitionAttachments,
workspaceFileDownloadUrl,
workspaceItemToAttachment,
@@ -80,3 +83,106 @@ describe("workspaceAttachments", () => {
]);
});
});
+
+describe("appendWithinCap", () => {
+ it("keeps exactly MAX_ATTACHMENTS and reports the rest as refused", () => {
+ const incoming = makeLocals(MAX_ATTACHMENTS + 3);
+
+ const { next, refused } = appendWithinCap([], incoming);
+
+ expect(next).toHaveLength(MAX_ATTACHMENTS);
+ expect(refused).toBe(3);
+ // The first ones in are the ones kept, so the user sees what they picked.
+ expect(next.map(attachmentName)).toEqual(
+ incoming.slice(0, MAX_ATTACHMENTS).map(attachmentName),
+ );
+ });
+
+ it("counts what is already attached against the cap", () => {
+ const prev = makeLocals(MAX_ATTACHMENTS - 2);
+
+ const { next, refused } = appendWithinCap(prev, makeLocals(5, "late"));
+
+ expect(next).toHaveLength(MAX_ATTACHMENTS);
+ expect(refused).toBe(3);
+ });
+
+ it("refuses nothing when everything fits", () => {
+ const { next, refused } = appendWithinCap(
+ makeLocals(2),
+ makeLocals(3, "b"),
+ );
+
+ expect(next).toHaveLength(5);
+ expect(refused).toBe(0);
+ });
+
+ it("skips a workspace file already attached without counting it as refused", () => {
+ const already = workspaceItemToAttachment(
+ makeWorkspaceItem({ id: "ws-1" }),
+ );
+
+ const { next, refused } = appendWithinCap([already], [already]);
+
+ expect(next).toEqual([already]);
+ expect(refused).toBe(0);
+ });
+
+ it("does not let a duplicate consume a slot a new file could have used", () => {
+ const already = workspaceItemToAttachment(
+ makeWorkspaceItem({ id: "ws-1" }),
+ );
+ const fresh = workspaceItemToAttachment(makeWorkspaceItem({ id: "ws-2" }));
+
+ const { next, refused } = appendWithinCap([already], [already, fresh]);
+
+ expect(next).toEqual([already, fresh]);
+ expect(refused).toBe(0);
+ });
+
+ it("leaves the caller's array alone", () => {
+ const prev = makeLocals(1);
+
+ appendWithinCap(prev, makeLocals(2, "b"));
+
+ expect(prev).toHaveLength(1);
+ });
+});
+
+describe("the composer cap against the backend's own", () => {
+ // The workflow-import part is sent by an autosubmit carrying no composer
+ // attachments, so the two never share a request and the caps can be equal.
+ it.each(["StreamChatRequest", "QueuePendingMessageRequest"])(
+ "equals %s.file_ids maxItems",
+ (schemaName) => {
+ expect(fileIdsMaxItems(schemaName)).toBe(MAX_ATTACHMENTS);
+ },
+ );
+});
+
+function makeLocals(count: number, prefix = "a"): Attachment[] {
+ return Array.from({ length: count }, (_, i) => ({
+ kind: "local" as const,
+ file: new File(["x"], `${prefix}-${i}.txt`, { type: "text/plain" }),
+ }));
+}
+
+function fileIdsMaxItems(schemaName: string): number {
+ const schemas = (
+ openapiSpec as unknown as {
+ components: { schemas: Record<string, SchemaWithFileIds> };
+ }
+ ).components.schemas;
+ const fileIds = schemas[schemaName]?.properties?.file_ids;
+ const arrayBranch = (fileIds?.anyOf ?? []).find(
+ (branch) => branch.type === "array",
+ );
+ expect(arrayBranch?.maxItems).toBeTypeOf("number");
+ return arrayBranch!.maxItems!;
+}
+
+interface SchemaWithFileIds {
+ properties?: {
+ file_ids?: { anyOf?: { type?: string; maxItems?: number }[] };
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts
index ad82b41f61..28eb28c6aa 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts
@@ -21,6 +21,10 @@ export type Attachment =
| { kind: "local"; file: File }
| ({ kind: "workspace" } & WorkspaceAttachment);
+// Must equal `file_ids` max_length on StreamChatRequest/QueuePendingMessageRequest
+// (chat/routes.py): every attachment, uploaded or from the workspace, is one entry.
+export const MAX_ATTACHMENTS = 20;
+
export function workspaceFileDownloadUrl(fileId: string): string {
return `/api/proxy/api/workspace/files/${encodeURIComponent(fileId)}/download`;
}
@@ -68,3 +72,31 @@ export function partitionAttachments(attachments: Attachment[]): {
}
return { localFiles, workspaceFiles };
}
+
+/** Appends what fits under `MAX_ATTACHMENTS`, skipping workspace files already
+ * attached — a re-picked file is not counted in `refused`. */
+export function appendWithinCap(
+ prev: Attachment[],
+ incoming: Attachment[],
+): { next: Attachment[]; refused: number } {
+ const next = [...prev];
+ let refused = 0;
+ for (const attachment of incoming) {
+ if (
+ attachment.kind === "workspace" &&
+ isAttached(next, attachment.fileId)
+ ) {
+ continue;
+ }
+ if (next.length >= MAX_ATTACHMENTS) {
+ refused += 1;
+ continue;
+ }
+ next.push(attachment);
+ }
+ return { next, refused };
+}
+
+function isAttached(attachments: Attachment[], fileId: string): boolean {
+ return attachments.some((a) => a.kind === "workspace" && a.fileId === fileId);
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
index 7731c29308..e4a9ac4087 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
@@ -13,12 +13,12 @@ import { describeSendFailure } from "./components/ChatInput/helpers";
import type { ExpertKickoffMetadata } from "./expertKickoff";
import {
buildWorkspaceFilePart,
+ MAX_ATTACHMENTS,
workspaceFileDownloadUrl,
type WorkspaceAttachment,
} from "./helpers/workspaceAttachments";
import { useCopilotUIStore } from "./store";
-const MAX_FILES = 10;
const MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024;
interface UploadedFile {
@@ -201,15 +201,22 @@ export function useSendMessage({
if (!trimmed && (!files || files.length === 0) && !hasWorkspaceFiles)
return;
+ // Backstop: the composer caps each attach, so the UI cannot reach this.
+ // Workspace references count too — uploaded or not, every attachment
+ // becomes one `file_ids` entry on the request the backend bounds.
+ if (
+ (files?.length ?? 0) + (workspaceFiles?.length ?? 0) >
+ MAX_ATTACHMENTS
+ ) {
+ toast({
+ title: "Too many attachments",
+ description: `You can attach up to ${MAX_ATTACHMENTS} attachments per message.`,
+ variant: "destructive",
+ });
+ return;
+ }
+
if (files && files.length > 0) {
- if (files.length > MAX_FILES) {
- toast({
- title: "Too many files",
- description: `You can attach up to ${MAX_FILES} files at once.`,
- variant: "destructive",
- });
- return;
- }
const oversized = files.filter((f) => f.size > MAX_FILE_SIZE_BYTES);
if (oversized.length > 0) {
toast({