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): attach workspace files in copilot chat via picker and @mention (#13262)

Abhimanyu Yadav4c97372d4bfd
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.tsx
index 5f997b8228..33499bde1a 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
@@ -10,6 +10,7 @@ import { UIDataTypes, UIMessage, UITools } from "ai";
import { LayoutGroup, motion } from "framer-motion";
import { useCallback, useEffect, useRef, useState } from "react";
import type { TurnStatsMap } from "../../helpers/convertChatSessionToUiMessages";
+import type { WorkspaceAttachment } from "../../helpers/workspaceAttachments";
import { ChatMessagesContainer } from "../ChatMessagesContainer/ChatMessagesContainer";
import { CopilotChatActionsProvider } from "../CopilotChatActionsProvider/CopilotChatActionsProvider";
import { EmptySession } from "../EmptySession/EmptySession";
@@ -40,7 +41,11 @@ export interface ChatContainerProps {
* flips immediately regardless of AI SDK's status timing. */
isUserStopping?: boolean;
onCreateSession: () => void | Promise<string>;
- onSend: (message: string, files?: File[]) => void | Promise<void>;
+ onSend: (
+ message: string,
+ files?: File[],
+ workspaceFiles?: WorkspaceAttachment[],
+ ) => void | Promise<void>;
onStop: () => void;
/** Called to enqueue a message while streaming (bypasses normal send flow). */
onEnqueue?: (message: string) => void | Promise<void>;
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 7808abdc47..794da91763 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
@@ -16,21 +16,35 @@ import {
import { cn } from "@/lib/utils";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { ArrowUpIcon } from "@phosphor-icons/react";
-import { ChangeEvent, useEffect, useState } from "react";
+import { ChangeEvent, KeyboardEvent, useEffect, useState } from "react";
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import {
+ type Attachment,
+ type WorkspaceAttachment,
+ partitionAttachments,
+ workspaceItemToAttachment,
+} from "../../helpers/workspaceAttachments";
import { AttachmentMenu } from "./components/AttachmentMenu";
import { BlockCaret } from "./components/BlockCaret";
import { DryRunToggleButton } from "./components/DryRunToggleButton";
import { FileChips } from "./components/FileChips";
+import { MentionDropdown } from "./components/MentionDropdown";
import { ModelToggleButton } from "./components/ModelToggleButton";
import { ModeToggleButton } from "./components/ModeToggleButton";
import { RecordingButton } from "./components/RecordingButton";
import { RecordingIndicator } from "./components/RecordingIndicator";
+import { WorkspaceFilePicker } from "./components/WorkspaceFilePicker/WorkspaceFilePicker";
import { useCopilotUIStore } from "../../store";
import { useChatInput } from "./useChatInput";
+import { useChatMentions } from "./useChatMentions";
import { useVoiceRecording } from "./useVoiceRecording";
interface Props {
- onSend: (message: string, files?: File[]) => void | Promise<void>;
+ onSend: (
+ message: string,
+ files?: File[],
+ workspaceFiles?: WorkspaceAttachment[],
+ ) => void | Promise<void>;
disabled?: boolean;
isStreaming?: boolean;
isUploadingFiles?: boolean;
@@ -72,7 +86,9 @@ export function ChatInput({
} = useCopilotUIStore();
const showModeToggle = useGetFlag(Flag.CHAT_MODE_OPTION);
const showDryRunToggle = showModeToggle;
- const [files, setFiles] = useState<File[]>([]);
+ const showWorkspaceFiles = useGetFlag(Flag.CHAT_WORKSPACE_FILES);
+ const [attachments, setAttachments] = useState<Attachment[]>([]);
+ const [isPickerOpen, setIsPickerOpen] = useState(false);
function handleToggleMode() {
const next =
@@ -119,12 +135,15 @@ export function ChatInput({
// Merge files dropped onto the chat window into internal state.
useEffect(() => {
if (droppedFiles && droppedFiles.length > 0) {
- setFiles((prev) => [...prev, ...droppedFiles]);
+ setAttachments((prev) => [
+ ...prev,
+ ...droppedFiles.map((file) => ({ kind: "local" as const, file })),
+ ]);
onDroppedFilesConsumed?.();
}
}, [droppedFiles, onDroppedFilesConsumed]);
- const hasFiles = files.length > 0;
+ const hasAttachments = attachments.length > 0;
// 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;
@@ -139,15 +158,27 @@ export function ChatInput({
handleChange: baseHandleChange,
} = useChatInput({
onSend: async (message: string) => {
- await onSend(message, hasFiles ? files : undefined);
- // Only clear files after successful send (onSend throws on failure)
- setFiles([]);
+ const { localFiles, workspaceFiles } = partitionAttachments(attachments);
+ await onSend(
+ message,
+ localFiles.length > 0 ? localFiles : undefined,
+ workspaceFiles.length > 0 ? workspaceFiles : undefined,
+ );
+ // Only clear after successful send (onSend throws on failure)
+ setAttachments([]);
},
disabled: isTextareaDisabled,
- canSendEmpty: hasFiles,
+ canSendEmpty: hasAttachments,
inputId,
});
+ const mentions = useChatMentions({
+ enabled: showWorkspaceFiles && !isBusy,
+ value,
+ setValue,
+ addWorkspaceFile: handleWorkspaceFileSelected,
+ });
+
const [isEnqueueing, setIsEnqueueing] = useState(false);
const {
@@ -155,7 +186,7 @@ export function ChatInput({
isTranscribing,
elapsedTime,
toggleRecording,
- handleKeyDown,
+ handleKeyDown: voiceHandleKeyDown,
showMicButton,
isInputDisabled,
audioStream,
@@ -170,6 +201,12 @@ export function ChatInput({
function handleChange(e: ChangeEvent<HTMLTextAreaElement>) {
if (isRecording) return;
baseHandleChange(e);
+ mentions.detect(e.currentTarget);
+ }
+
+ function handleKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {
+ if (mentions.onKeyDown(e)) return;
+ voiceHandleKeyDown(e);
}
const resolvedPlaceholder = isRecording
@@ -180,20 +217,47 @@ export function ChatInput({
const canSend =
!disabled &&
- (!!value.trim() || hasFiles) &&
+ (!!value.trim() || hasAttachments) &&
!isRecording &&
!isTranscribing;
function handleFilesSelected(newFiles: File[]) {
- setFiles((prev) => [...prev, ...newFiles]);
+ setAttachments((prev) => [
+ ...prev,
+ ...newFiles.map((file) => ({ kind: "local" as const, file })),
+ ]);
}
- function handleRemoveFile(index: number) {
- setFiles((prev) => prev.filter((_, i) => i !== index));
+ function handleWorkspaceFileSelected(item: WorkspaceFileItem) {
+ setAttachments((prev) => {
+ if (prev.some((a) => a.kind === "workspace" && a.fileId === item.id)) {
+ return prev;
+ }
+ return [...prev, workspaceItemToAttachment(item)];
+ });
+ }
+
+ function handleWorkspaceFilesConfirmed(items: WorkspaceFileItem[]) {
+ items.forEach(handleWorkspaceFileSelected);
+ }
+
+ function handleRemoveAttachment(index: number) {
+ setAttachments((prev) => prev.filter((_, i) => i !== index));
}
return (
<form onSubmit={handleSubmit} className={cn("relative flex-1", className)}>
+ {mentions.isOpen && (
+ <MentionDropdown
+ files={mentions.files}
+ isLoading={mentions.isLoading}
+ isError={mentions.isError}
+ highlightedIndex={mentions.highlightedIndex}
+ highlightedRef={mentions.highlightedRef}
+ onSelect={mentions.accept}
+ onHighlight={mentions.setHighlightedIndex}
+ />
+ )}
<InputGroup
className={cn(
"overflow-hidden has-[[data-slot=input-group-control]:focus-visible]:border-neutral-200 has-[[data-slot=input-group-control]:focus-visible]:ring-0",
@@ -202,8 +266,8 @@ export function ChatInput({
)}
>
<FileChips
- files={files}
- onRemove={handleRemoveFile}
+ attachments={attachments}
+ onRemove={handleRemoveAttachment}
isUploading={isUploadingFiles}
/>
<PromptInputBody className="relative block w-full">
@@ -213,6 +277,7 @@ export function ChatInput({
value={value}
onChange={handleChange}
onKeyDown={handleKeyDown}
+ onBlur={mentions.close}
disabled={isInputDisabled}
placeholder={resolvedPlaceholder}
className="caret-transparent placeholder:indent-3"
@@ -236,6 +301,8 @@ export function ChatInput({
<PromptInputTools>
<AttachmentMenu
onFilesSelected={handleFilesSelected}
+ onUseWorkspaceFile={() => setIsPickerOpen(true)}
+ showWorkspaceOption={showWorkspaceFiles}
disabled={isBusy}
/>
{/* Mode and model are per-message settings sent with each stream request,
@@ -312,6 +379,14 @@ export function ChatInput({
</div>
</PromptInputFooter>
</InputGroup>
+
+ {showWorkspaceFiles && (
+ <WorkspaceFilePicker
+ isOpen={isPickerOpen}
+ onClose={() => setIsPickerOpen(false)}
+ onConfirm={handleWorkspaceFilesConfirmed}
+ />
+ )}
</form>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx
index 0527ed95d2..235555b0c4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx
@@ -471,7 +471,7 @@ describe("ChatInput submit behavior", () => {
const form = textarea.closest("form")!;
fireEvent.submit(form);
await waitFor(() => {
- expect(onSend).toHaveBeenCalledWith("hello", undefined);
+ expect(onSend).toHaveBeenCalledWith("hello", undefined, undefined);
});
await waitFor(() => {
expect(textarea.value).toBe("");
@@ -534,7 +534,7 @@ describe("ChatInput submit behavior", () => {
await waitFor(() => {
expect(onSend).toHaveBeenCalledTimes(2);
});
- expect(onSend).toHaveBeenLastCalledWith("retry", undefined);
+ expect(onSend).toHaveBeenLastCalledWith("retry", undefined, undefined);
} finally {
window.removeEventListener("unhandledrejection", swallowWindow);
process.off("unhandledRejection", swallowProcess);
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.tsx
new file mode 100644
index 0000000000..b625bec9be
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsx
@@ -0,0 +1,200 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import React, { type ReactNode } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useChatMentions } from "../useChatMentions";
+
+const mockListWorkspaceFiles = vi.fn();
+vi.mock("@/app/api/__generated__/endpoints/workspace/workspace", () => ({
+ listWorkspaceFiles: (...args: unknown[]) => mockListWorkspaceFiles(...args),
+}));
+
+const FILE = {
+ id: "file-1",
+ name: "alpha.txt",
+ path: "/workspace/alpha.txt",
+ mime_type: "text/plain",
+ size_bytes: 10,
+ created_at: "2026-01-01T00:00:00Z",
+};
+
+function Wrapper({ children }: { children: ReactNode }) {
+ const [client] = React.useState(
+ () =>
+ new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ }),
+ );
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+}
+
+function fakeTextarea(value: string, caret = value.length) {
+ return { value, selectionStart: caret } as HTMLTextAreaElement;
+}
+
+function keyEvent(key: string) {
+ return {
+ key,
+ preventDefault: vi.fn(),
+ } as unknown as React.KeyboardEvent<HTMLTextAreaElement>;
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useChatMentions", () => {
+ it("opens on an @token at the caret and queries workspace files", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+
+ const { result } = renderHook(
+ () =>
+ useChatMentions({
+ enabled: true,
+ value: "hi @al",
+ setValue: vi.fn(),
+ addWorkspaceFile: vi.fn(),
+ }),
+ { wrapper: Wrapper },
+ );
+
+ act(() => result.current.detect(fakeTextarea("hi @al")));
+ expect(result.current.isOpen).toBe(true);
+
+ await waitFor(() => expect(result.current.files).toHaveLength(1));
+ await waitFor(() =>
+ expect(mockListWorkspaceFiles).toHaveBeenCalledWith({
+ limit: 8,
+ q: "al",
+ }),
+ );
+ });
+
+ it("stays closed when there is no @token before the caret", () => {
+ const { result } = renderHook(
+ () =>
+ useChatMentions({
+ enabled: true,
+ value: "hello world",
+ setValue: vi.fn(),
+ addWorkspaceFile: vi.fn(),
+ }),
+ { wrapper: Wrapper },
+ );
+
+ act(() => result.current.detect(fakeTextarea("hello world")));
+ expect(result.current.isOpen).toBe(false);
+ });
+
+ it("does not open while disabled", () => {
+ const { result } = renderHook(
+ () =>
+ useChatMentions({
+ enabled: false,
+ value: "hi @al",
+ setValue: vi.fn(),
+ addWorkspaceFile: vi.fn(),
+ }),
+ { wrapper: Wrapper },
+ );
+
+ act(() => result.current.detect(fakeTextarea("hi @al")));
+ expect(result.current.isOpen).toBe(false);
+ });
+
+ it("strips the @query and attaches the file when accepted via Enter", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+ const setValue = vi.fn();
+ const addWorkspaceFile = vi.fn();
+
+ const { result } = renderHook(
+ () =>
+ useChatMentions({
+ enabled: true,
+ value: "hi @al",
+ setValue,
+ addWorkspaceFile,
+ }),
+ { wrapper: Wrapper },
+ );
+
+ act(() => result.current.detect(fakeTextarea("hi @al")));
+ await waitFor(() => expect(result.current.files).toHaveLength(1));
+
+ let handled = false;
+ act(() => {
+ handled = result.current.onKeyDown(keyEvent("Enter"));
+ });
+
+ expect(handled).toBe(true);
+ expect(setValue).toHaveBeenCalledWith("hi ");
+ expect(addWorkspaceFile).toHaveBeenCalledWith(FILE);
+ expect(result.current.isOpen).toBe(false);
+ });
+
+ it("closes on Escape without attaching", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+ const addWorkspaceFile = vi.fn();
+
+ const { result } = renderHook(
+ () =>
+ useChatMentions({
+ enabled: true,
+ value: "hi @al",
+ setValue: vi.fn(),
+ addWorkspaceFile,
+ }),
+ { wrapper: Wrapper },
+ );
+
+ act(() => result.current.detect(fakeTextarea("hi @al")));
+ await waitFor(() => expect(result.current.files).toHaveLength(1));
+
+ act(() => {
+ result.current.onKeyDown(keyEvent("Escape"));
+ });
+
+ expect(result.current.isOpen).toBe(false);
+ expect(addWorkspaceFile).not.toHaveBeenCalled();
+ });
+
+ it("ignores accept when the highlighted item is out of bounds", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+ const setValue = vi.fn();
+ const addWorkspaceFile = vi.fn();
+
+ const { result } = renderHook(
+ () =>
+ useChatMentions({
+ enabled: true,
+ value: "hi @al",
+ setValue,
+ addWorkspaceFile,
+ }),
+ { wrapper: Wrapper },
+ );
+
+ act(() => result.current.detect(fakeTextarea("hi @al")));
+ await waitFor(() => expect(result.current.files).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,
+ // not a crash on an undefined item.
+ act(() => result.current.accept(undefined));
+
+ expect(setValue).not.toHaveBeenCalled();
+ expect(addWorkspaceFile).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AttachmentMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AttachmentMenu.tsx
index cc34e2fac1..65fbc3d6ef 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AttachmentMenu.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AttachmentMenu.tsx
@@ -1,19 +1,36 @@
"use client";
import { Button } from "@/components/atoms/Button/Button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/molecules/DropdownMenu/DropdownMenu";
import { cn } from "@/lib/utils";
-import { Plus as PlusIcon } from "@phosphor-icons/react";
+import {
+ FolderOpen as FolderOpenIcon,
+ Plus as PlusIcon,
+ UploadSimple as UploadSimpleIcon,
+} from "@phosphor-icons/react";
import { useRef } from "react";
interface Props {
onFilesSelected: (files: File[]) => void;
+ onUseWorkspaceFile?: () => void;
+ showWorkspaceOption?: boolean;
disabled?: boolean;
}
-export function AttachmentMenu({ onFilesSelected, disabled }: Props) {
+export function AttachmentMenu({
+ onFilesSelected,
+ onUseWorkspaceFile,
+ showWorkspaceOption = false,
+ disabled,
+}: Props) {
const fileInputRef = useRef<HTMLInputElement>(null);
- function handleClick() {
+ function openFilePicker() {
fileInputRef.current?.click();
}
@@ -26,6 +43,11 @@ export function AttachmentMenu({ onFilesSelected, disabled }: Props) {
e.target.value = "";
}
+ const buttonClassName = cn(
+ "border-zinc-300 bg-white text-zinc-500 hover:border-zinc-400 hover:bg-zinc-50 hover:text-zinc-700",
+ disabled && "opacity-40",
+ );
+
return (
<>
<input
@@ -36,20 +58,44 @@ export function AttachmentMenu({ onFilesSelected, disabled }: Props) {
onChange={handleFileChange}
tabIndex={-1}
/>
- <Button
- type="button"
- variant="icon"
- size="icon"
- aria-label="Attach file"
- disabled={disabled}
- onClick={handleClick}
- className={cn(
- "border-zinc-300 bg-white text-zinc-500 hover:border-zinc-400 hover:bg-zinc-50 hover:text-zinc-700",
- disabled && "opacity-40",
- )}
- >
- <PlusIcon className="h-4 w-4" weight="bold" />
- </Button>
+ {showWorkspaceOption ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="icon"
+ size="icon"
+ aria-label="Attach file"
+ disabled={disabled}
+ className={buttonClassName}
+ >
+ <PlusIcon className="h-4 w-4" weight="bold" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-[14rem]">
+ <DropdownMenuItem onSelect={openFilePicker}>
+ <UploadSimpleIcon className="mr-2 h-4 w-4" />
+ Upload from Computer
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => onUseWorkspaceFile?.()}>
+ <FolderOpenIcon className="mr-2 h-4 w-4" />
+ Use File from Workspace
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <Button
+ type="button"
+ variant="icon"
+ size="icon"
+ aria-label="Attach file"
+ disabled={disabled}
+ onClick={openFilePicker}
+ className={buttonClassName}
+ >
+ <PlusIcon className="h-4 w-4" weight="bold" />
+ </Button>
+ )}
</>
);
}
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.tsx
index ce645674d5..db7ba99d31 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
@@ -1,45 +1,116 @@
"use client";
-import { cn } from "@/lib/utils";
+import { getFileTypeIcon } from "@/app/(platform)/artifacts/components/ArtifactsList/helpers";
import {
CircleNotch as CircleNotchIcon,
X as XIcon,
} from "@phosphor-icons/react";
+import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
+import {
+ type Attachment,
+ attachmentName,
+} from "../../../helpers/workspaceAttachments";
+
+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 {
- files: File[];
+ attachments: Attachment[];
onRemove: (index: number) => void;
isUploading?: boolean;
}
-export function FileChips({ files, onRemove, isUploading }: Props) {
- if (files.length === 0) return null;
+// ease-out so chips settle naturally; kept under 300ms (Emil's timing rules).
+const EASE_OUT = [0.16, 1, 0.3, 1] as const;
+const DURATION = 0.2;
+
+export function FileChips({ attachments, onRemove, isUploading }: Props) {
+ const reduceMotion = useReducedMotion();
return (
- <div className="flex w-full flex-wrap gap-2 px-3 pb-2 pt-2">
- {files.map((file, index) => (
- <span
- key={`${file.name}-${file.size}-${index}`}
- className={cn(
- "inline-flex items-center gap-1 rounded-full bg-zinc-100 px-3 py-1 text-sm text-zinc-700",
- isUploading && "opacity-70",
- )}
+ <AnimatePresence initial={false}>
+ {attachments.length > 0 && (
+ <motion.div
+ key="file-chips-row"
+ initial={reduceMotion ? { opacity: 0 } : { opacity: 0, height: 0 }}
+ animate={
+ reduceMotion ? { opacity: 1 } : { opacity: 1, height: "auto" }
+ }
+ exit={reduceMotion ? { opacity: 0 } : { opacity: 0, height: 0 }}
+ transition={{ duration: DURATION, ease: EASE_OUT }}
+ className="w-full overflow-hidden"
>
- <span className="max-w-[160px] truncate">{file.name}</span>
- {isUploading ? (
- <CircleNotchIcon className="ml-0.5 h-3 w-3 animate-spin text-zinc-400" />
- ) : (
- <button
- type="button"
- aria-label={`Remove ${file.name}`}
- onClick={() => onRemove(index)}
- className="ml-0.5 rounded-full p-0.5 text-zinc-400 transition-colors hover:bg-zinc-200 hover:text-zinc-600"
- >
- <XIcon className="h-3 w-3" weight="bold" />
- </button>
- )}
- </span>
- ))}
- </div>
+ <div className="flex w-full flex-wrap gap-2 px-3 pb-2 pt-2">
+ <AnimatePresence initial={false} mode="popLayout">
+ {attachments.map((attachment, index) => {
+ const name = attachmentName(attachment);
+ const Icon = getFileTypeIcon(attachmentMimeType(attachment));
+ // Workspace files are already stored — only local files show
+ // the upload spinner while a send is in flight.
+ const showSpinner = isUploading && attachment.kind === "local";
+ const restOpacity = showSpinner ? 0.7 : 1;
+ return (
+ <motion.span
+ key={attachmentKey(attachment)}
+ layout
+ initial={
+ reduceMotion
+ ? { opacity: 0 }
+ : { opacity: 0, scale: 0.95, filter: "blur(4px)" }
+ }
+ animate={
+ reduceMotion
+ ? { opacity: restOpacity }
+ : {
+ opacity: restOpacity,
+ scale: 1,
+ filter: "blur(0px)",
+ }
+ }
+ exit={
+ reduceMotion
+ ? { opacity: 0 }
+ : { opacity: 0, scale: 0.95, filter: "blur(4px)" }
+ }
+ transition={{ duration: DURATION, ease: EASE_OUT }}
+ style={{ willChange: "transform, opacity, filter" }}
+ className="inline-flex items-center gap-1 rounded-full bg-zinc-100 px-3 py-1 text-sm text-zinc-700"
+ >
+ <Icon
+ weight="regular"
+ className="h-3.5 w-3.5 shrink-0 text-zinc-900"
+ />
+ <span className="max-w-[160px] truncate">{name}</span>
+ {showSpinner ? (
+ <CircleNotchIcon className="ml-0.5 h-3 w-3 animate-spin text-zinc-400" />
+ ) : (
+ <button
+ type="button"
+ aria-label={`Remove ${name}`}
+ onClick={() => onRemove(index)}
+ className="ml-0.5 rounded-full p-0.5 text-zinc-400 transition-colors hover:bg-zinc-200 hover:text-zinc-600"
+ >
+ <XIcon className="h-3 w-3" weight="bold" />
+ </button>
+ )}
+ </motion.span>
+ );
+ })}
+ </AnimatePresence>
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
);
}
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.tsx
new file mode 100644
index 0000000000..97652b182b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/MentionDropdown.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import { getFileTypeIcon } from "@/app/(platform)/artifacts/components/ArtifactsList/helpers";
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { cn } from "@/lib/utils";
+import {
+ CircleNotch as CircleNotchIcon,
+ WarningCircle as WarningCircleIcon,
+} from "@phosphor-icons/react";
+import type { MutableRefObject } from "react";
+
+interface Props {
+ files: WorkspaceFileItem[];
+ isLoading: boolean;
+ isError: boolean;
+ highlightedIndex: number;
+ highlightedRef: MutableRefObject<HTMLButtonElement | null>;
+ onSelect: (item: WorkspaceFileItem) => void;
+ onHighlight: (index: number) => void;
+}
+
+export function MentionDropdown({
+ files,
+ isLoading,
+ isError,
+ highlightedIndex,
+ highlightedRef,
+ onSelect,
+ onHighlight,
+}: Props) {
+ const showEmpty = !isLoading && !isError && files.length === 0;
+
+ return (
+ <div
+ role="listbox"
+ aria-label="Workspace files"
+ // preventDefault on mousedown keeps focus in the textarea when clicking
+ // non-interactive areas (padding, empty/loading/error states) so the
+ // textarea's onBlur doesn't close the dropdown before a selection.
+ onMouseDown={(e) => e.preventDefault()}
+ className="absolute bottom-full left-0 z-50 mb-2 max-h-60 w-72 overflow-y-auto rounded-2xl border border-zinc-200 bg-white p-1.5 shadow-md"
+ >
+ {isError ? (
+ <p className="flex items-center gap-2 px-3 py-2 text-sm text-red-600">
+ <WarningCircleIcon className="h-4 w-4 shrink-0" />
+ Couldn&apos;t load files. Try again.
+ </p>
+ ) : isLoading ? (
+ <p className="flex items-center gap-2 px-3 py-2 text-sm text-zinc-500">
+ <CircleNotchIcon className="h-4 w-4 shrink-0 animate-spin" />
+ Searching files…
+ </p>
+ ) : null}
+ {showEmpty && (
+ <p className="px-3 py-2 text-sm text-zinc-500">No matching files.</p>
+ )}
+ {files.map((file, index) => {
+ const isHighlighted = index === highlightedIndex;
+ const Icon = getFileTypeIcon(file.mime_type);
+ return (
+ <button
+ key={file.id}
+ ref={isHighlighted ? highlightedRef : undefined}
+ type="button"
+ role="option"
+ aria-selected={isHighlighted}
+ // 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);
+ }}
+ onMouseEnter={() => onHighlight(index)}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm",
+ isHighlighted ? "bg-zinc-100 text-zinc-900" : "text-zinc-700",
+ )}
+ >
+ <Icon weight="regular" className="h-4 w-4 shrink-0 text-zinc-900" />
+ <span className="min-w-0 flex-1 truncate">{file.name}</span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
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
new file mode 100644
index 0000000000..3be844f83f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFileList.tsx
@@ -0,0 +1,165 @@
+"use client";
+
+import {
+ formatFileSize,
+ formatRelativeDate,
+ getFileTypeIcon,
+ getFileTypeLabel,
+} from "@/app/(platform)/artifacts/components/ArtifactsList/helpers";
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+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 { cn } from "@/lib/utils";
+import { CheckCircle as CheckCircleIcon } from "@phosphor-icons/react";
+import { useEffect, useRef, useState } from "react";
+
+interface Props {
+ files: WorkspaceFileItem[];
+ selectedIds: ReadonlyMap<string, WorkspaceFileItem>;
+ onToggle: (item: WorkspaceFileItem) => void;
+ isLoading: boolean;
+ isError: boolean;
+ error: unknown;
+ hasMore: boolean;
+ isLoadingMore: boolean;
+ onLoadMore: () => void;
+}
+
+export function WorkspaceFileList({
+ files,
+ selectedIds,
+ onToggle,
+ isLoading,
+ isError,
+ error,
+ hasMore,
+ isLoadingMore,
+ onLoadMore,
+}: Props) {
+ const scrollRef = useRef<HTMLDivElement | null>(null);
+ // Show the top/bottom scroll-fade only when there's content hidden in that
+ // direction — no fade when pinned to the very top or bottom.
+ const [edges, setEdges] = useState({ top: false, bottom: false });
+
+ function updateEdges() {
+ const el = scrollRef.current;
+ if (!el) return;
+ setEdges({
+ top: el.scrollTop > 1,
+ bottom: el.scrollTop + el.clientHeight < el.scrollHeight - 1,
+ });
+ }
+
+ useEffect(() => {
+ updateEdges();
+ }, [files.length, isLoadingMore]);
+
+ if (isLoading) {
+ return (
+ <div className="grid grid-cols-2 gap-2 py-2">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-16 w-full rounded-2xl" />
+ ))}
+ </div>
+ );
+ }
+
+ if (isError) {
+ return (
+ <ErrorCard
+ responseError={{
+ message: error instanceof Error ? error.message : "Failed to load",
+ }}
+ context="workspace files"
+ />
+ );
+ }
+
+ if (files.length === 0) {
+ return (
+ <p className="py-8 text-center text-sm text-zinc-500">
+ No files in your workspace yet.
+ </p>
+ );
+ }
+
+ return (
+ <div className="relative">
+ {/* White scroll-fade so rows dissolve into the dialog — only on the
+ side that still has hidden content. */}
+ {edges.top && (
+ <div className="pointer-events-none absolute inset-x-0 top-0 z-10 h-6 bg-gradient-to-b from-white to-transparent" />
+ )}
+ {edges.bottom && (
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-6 bg-gradient-to-t from-white to-transparent" />
+ )}
+ <div
+ ref={scrollRef}
+ onScroll={updateEdges}
+ className="max-h-[24rem] overflow-y-auto py-1"
+ >
+ <div className="grid grid-cols-2 gap-2">
+ {files.map((file) => {
+ const isSelected = selectedIds.has(file.id);
+ const Icon = getFileTypeIcon(file.mime_type);
+ return (
+ <button
+ key={file.id}
+ type="button"
+ onClick={() => onToggle(file)}
+ aria-pressed={isSelected}
+ className={cn(
+ "flex w-full items-center gap-3 rounded-2xl border bg-white p-3 text-left transition-colors",
+ isSelected
+ ? "border-violet-300 ring-1 ring-violet-200"
+ : "border-zinc-200 hover:border-zinc-300",
+ )}
+ >
+ <Icon
+ size={20}
+ weight="bold"
+ className="shrink-0 text-zinc-500"
+ />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <Text
+ variant="body-medium"
+ className="truncate text-zinc-900"
+ title={file.name}
+ >
+ {file.name}
+ </Text>
+ <Text variant="small" className="truncate text-zinc-500">
+ {getFileTypeLabel(file.mime_type)} ·{" "}
+ {formatFileSize(file.size_bytes)} ·{" "}
+ {formatRelativeDate(file.created_at)}
+ </Text>
+ </div>
+ {isSelected && (
+ <CheckCircleIcon
+ weight="fill"
+ className="h-5 w-5 shrink-0 text-violet-600"
+ />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ {hasMore && (
+ <div className="mt-2 flex justify-center">
+ <Button
+ type="button"
+ variant="ghost"
+ size="small"
+ onClick={onLoadMore}
+ loading={isLoadingMore}
+ >
+ Load more
+ </Button>
+ </div>
+ )}
+ </div>
+ </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.tsx
new file mode 100644
index 0000000000..cc248e7080
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { Button } from "@/components/atoms/Button/Button";
+import { Input } from "@/components/atoms/Input/Input";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { MagnifyingGlassIcon } from "@phosphor-icons/react";
+import { useWorkspaceFilePicker } from "./useWorkspaceFilePicker";
+import { WorkspaceFileList } from "./WorkspaceFileList";
+
+interface Props {
+ isOpen: boolean;
+ onClose: () => void;
+ onConfirm: (items: WorkspaceFileItem[]) => void;
+}
+
+export function WorkspaceFilePicker({ isOpen, onClose, onConfirm }: Props) {
+ const picker = useWorkspaceFilePicker({ enabled: isOpen });
+
+ function handleOpenChange(open: boolean) {
+ if (!open) {
+ picker.reset();
+ onClose();
+ }
+ }
+
+ function handleConfirm() {
+ onConfirm(picker.selectedFiles);
+ picker.reset();
+ onClose();
+ }
+
+ const selectedCount = picker.selectedFiles.length;
+
+ return (
+ <Dialog
+ title="Use a file from your workspace"
+ styling={{ maxWidth: "48rem" }}
+ controlled={{ isOpen, set: handleOpenChange }}
+ >
+ <Dialog.Content>
+ <div className="flex flex-col gap-3">
+ <div className="relative flex items-center">
+ <MagnifyingGlassIcon
+ width={18}
+ height={18}
+ className="absolute left-4 top-1/2 z-20 -translate-y-1/2 text-zinc-500"
+ />
+ <Input
+ label="Search workspace files"
+ id="workspace-file-picker-search"
+ hideLabel
+ type="text"
+ value={picker.searchTerm}
+ onChange={(e) => picker.setSearchTerm(e.target.value)}
+ placeholder="Search files"
+ className="w-full pl-12"
+ wrapperClassName="!mb-0"
+ />
+ </div>
+
+ <WorkspaceFileList
+ files={picker.files}
+ selectedIds={picker.selectedIds}
+ onToggle={picker.toggle}
+ isLoading={picker.isLoading}
+ isError={picker.isError}
+ error={picker.error}
+ hasMore={picker.hasMore}
+ isLoadingMore={picker.isLoadingMore}
+ onLoadMore={picker.loadMore}
+ />
+ </div>
+
+ <Dialog.Footer>
+ <Button
+ type="button"
+ variant="secondary"
+ size="small"
+ onClick={() => handleOpenChange(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ variant="primary"
+ size="small"
+ disabled={selectedCount === 0}
+ onClick={handleConfirm}
+ >
+ {selectedCount > 0 ? `Add ${selectedCount} file(s)` : "Add"}
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
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
new file mode 100644
index 0000000000..9f5fa600a9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsx
@@ -0,0 +1,108 @@
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { WorkspaceFilePicker } from "../WorkspaceFilePicker";
+
+const mockListWorkspaceFiles = vi.fn();
+vi.mock("@/app/api/__generated__/endpoints/workspace/workspace", () => ({
+ listWorkspaceFiles: (...args: unknown[]) => mockListWorkspaceFiles(...args),
+}));
+
+const FILE = {
+ id: "file-1",
+ name: "alpha.txt",
+ path: "/workspace/alpha.txt",
+ mime_type: "text/plain",
+ size_bytes: 10,
+ created_at: "2026-01-01T00:00:00Z",
+};
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("WorkspaceFilePicker", () => {
+ it("lists workspace files and confirms the selection", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+ const onConfirm = vi.fn();
+ const onClose = vi.fn();
+
+ render(
+ <WorkspaceFilePicker
+ isOpen={true}
+ onClose={onClose}
+ onConfirm={onConfirm}
+ />,
+ );
+
+ // File appears once the query resolves.
+ fireEvent.click(await screen.findByText("alpha.txt"));
+
+ fireEvent.click(await screen.findByRole("button", { name: /add 1 file/i }));
+
+ expect(onConfirm).toHaveBeenCalledWith([FILE]);
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it("disables Add until a file is selected", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+
+ render(
+ <WorkspaceFilePicker
+ isOpen={true}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ );
+
+ await screen.findByText("alpha.txt");
+ expect(screen.getByRole("button", { name: /^add$/i })).toHaveProperty(
+ "disabled",
+ true,
+ );
+ });
+
+ it("shows an empty state when the workspace has no files", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [], has_more: false },
+ });
+
+ render(
+ <WorkspaceFilePicker
+ isOpen={true}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ );
+
+ expect(
+ await screen.findByText(/no files in your workspace yet/i),
+ ).toBeTruthy();
+ });
+
+ it("offers a Load more action when there are more pages", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: true },
+ });
+
+ render(
+ <WorkspaceFilePicker
+ isOpen={true}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ );
+
+ await screen.findByText("alpha.txt");
+ expect(
+ await screen.findByRole("button", { name: /load more/i }),
+ ).toBeTruthy();
+ });
+});
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
new file mode 100644
index 0000000000..0d379ab933
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.ts
@@ -0,0 +1,95 @@
+import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/workspace";
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { useDebouncedValue } from "@/hooks/useDebouncedValue";
+import {
+ type InfiniteData,
+ keepPreviousData,
+ useInfiniteQuery,
+} from "@tanstack/react-query";
+import { useState } from "react";
+
+const SEARCH_DEBOUNCE_MS = 250;
+const PAGE_SIZE = 50;
+
+type ListPage = Awaited<ReturnType<typeof listWorkspaceFiles>>;
+
+export function useWorkspaceFilePicker({ enabled }: { enabled: boolean }) {
+ 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(),
+ );
+
+ const debouncedSearch = useDebouncedValue(
+ searchTerm.trim(),
+ SEARCH_DEBOUNCE_MS,
+ );
+ const q = debouncedSearch || undefined;
+
+ const query = useInfiniteQuery({
+ queryKey: ["workspace-file-picker", "list", { q: q ?? null }] as const,
+ queryFn: ({ pageParam }) =>
+ listWorkspaceFiles({ limit: PAGE_SIZE, offset: pageParam, q }),
+ initialPageParam: 0,
+ getNextPageParam: (lastPage, allPages) => {
+ if (lastPage.status !== 200) return undefined;
+ if (!lastPage.data.has_more) return undefined;
+ return countLoadedFiles(allPages);
+ },
+ placeholderData: keepPreviousData,
+ 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;
+ });
+ }
+
+ function reset() {
+ setSelected(new Map());
+ setSearchTerm("");
+ }
+
+ return {
+ files: flattenFiles(query.data),
+ isLoading: query.isLoading,
+ isError: query.isError,
+ error: query.error,
+ searchTerm,
+ setSearchTerm,
+ hasMore: !!query.hasNextPage,
+ isLoadingMore: query.isFetchingNextPage,
+ loadMore: () => {
+ query.fetchNextPage();
+ },
+ selectedIds: selected,
+ selectedFiles: Array.from(selected.values()),
+ toggle,
+ reset,
+ };
+}
+
+function flattenFiles(
+ data: InfiniteData<ListPage> | undefined,
+): WorkspaceFileItem[] {
+ if (!data) return [];
+ return data.pages.flatMap((page) =>
+ page.status === 200 ? (page.data.files ?? []) : [],
+ );
+}
+
+function countLoadedFiles(pages: ListPage[]): number {
+ return pages.reduce(
+ (acc, page) =>
+ acc + (page.status === 200 ? (page.data.files?.length ?? 0) : 0),
+ 0,
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/AttachmentMenu.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/AttachmentMenu.test.tsx
new file mode 100644
index 0000000000..7dd7eb9887
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/AttachmentMenu.test.tsx
@@ -0,0 +1,53 @@
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { AttachmentMenu } from "../AttachmentMenu";
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("AttachmentMenu", () => {
+ it("renders a plain attach button when the workspace option is hidden", () => {
+ render(
+ <AttachmentMenu onFilesSelected={vi.fn()} showWorkspaceOption={false} />,
+ );
+ expect(screen.getByRole("button", { name: /attach file/i })).toBeTruthy();
+ // No dropdown menu items are exposed in the plain variant.
+ expect(screen.queryByText(/use file from workspace/i)).toBeNull();
+ });
+
+ it("exposes both upload sources when the workspace option is enabled", async () => {
+ render(
+ <AttachmentMenu onFilesSelected={vi.fn()} showWorkspaceOption={true} />,
+ );
+ fireEvent.pointerDown(
+ screen.getByRole("button", { name: /attach file/i }),
+ { button: 0 },
+ );
+ expect(
+ await screen.findByRole("menuitem", { name: /upload from computer/i }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole("menuitem", { name: /use file from workspace/i }),
+ ).toBeTruthy();
+ });
+
+ it("invokes onUseWorkspaceFile when the workspace item is chosen", async () => {
+ const onUseWorkspaceFile = vi.fn();
+ render(
+ <AttachmentMenu
+ onFilesSelected={vi.fn()}
+ onUseWorkspaceFile={onUseWorkspaceFile}
+ showWorkspaceOption={true}
+ />,
+ );
+ fireEvent.pointerDown(
+ screen.getByRole("button", { name: /attach file/i }),
+ { button: 0 },
+ );
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /use file from workspace/i }),
+ );
+ expect(onUseWorkspaceFile).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/FileChips.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/FileChips.test.tsx
new file mode 100644
index 0000000000..3e16c0b448
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/FileChips.test.tsx
@@ -0,0 +1,72 @@
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { Attachment } from "../../../../helpers/workspaceAttachments";
+import { FileChips } from "../FileChips";
+
+const localAttachment: Attachment = {
+ kind: "local",
+ file: new File(["hi"], "local.txt", { type: "text/plain" }),
+};
+
+const workspaceAttachment: Attachment = {
+ kind: "workspace",
+ fileId: "file-1",
+ name: "report.pdf",
+ mimeType: "application/pdf",
+};
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("FileChips", () => {
+ it("renders nothing when there are no attachments", () => {
+ const { container } = render(
+ <FileChips attachments={[]} onRemove={vi.fn()} />,
+ );
+ expect(container.textContent).toBe("");
+ });
+
+ it("renders a chip for each attachment", () => {
+ render(
+ <FileChips
+ attachments={[localAttachment, workspaceAttachment]}
+ onRemove={vi.fn()}
+ />,
+ );
+ expect(screen.getByText("local.txt")).toBeTruthy();
+ expect(screen.getByText("report.pdf")).toBeTruthy();
+ });
+
+ it("removes the attachment at its index when the remove button is clicked", () => {
+ const onRemove = vi.fn();
+ render(
+ <FileChips
+ attachments={[localAttachment, workspaceAttachment]}
+ onRemove={onRemove}
+ />,
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: /remove report\.pdf/i }),
+ );
+ expect(onRemove).toHaveBeenCalledWith(1);
+ });
+
+ it("shows a spinner instead of a remove button for local files while uploading", () => {
+ render(
+ <FileChips
+ attachments={[localAttachment, workspaceAttachment]}
+ onRemove={vi.fn()}
+ isUploading={true}
+ />,
+ );
+ // Local file: spinner replaces the remove button.
+ expect(
+ screen.queryByRole("button", { name: /remove local\.txt/i }),
+ ).toBeNull();
+ // Workspace file needs no upload, so it keeps its remove button.
+ expect(
+ screen.getByRole("button", { name: /remove report\.pdf/i }),
+ ).toBeTruthy();
+ });
+});
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.tsx
new file mode 100644
index 0000000000..34af0cec37
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MentionDropdown.test.tsx
@@ -0,0 +1,71 @@
+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 { MentionDropdown } from "../MentionDropdown";
+
+const FILE: WorkspaceFileItem = {
+ id: "file-1",
+ name: "alpha.txt",
+ path: "/workspace/alpha.txt",
+ mime_type: "text/plain",
+ size_bytes: 10,
+ origin: "uploaded",
+ created_at: "2026-01-01T00:00:00Z",
+};
+
+function renderDropdown(
+ overrides: Partial<Parameters<typeof MentionDropdown>[0]> = {},
+) {
+ const props = {
+ files: [] as WorkspaceFileItem[],
+ isLoading: false,
+ isError: false,
+ highlightedIndex: 0,
+ highlightedRef: {
+ current: null,
+ } as MutableRefObject<HTMLButtonElement | null>,
+ onSelect: vi.fn(),
+ onHighlight: vi.fn(),
+ ...overrides,
+ };
+ render(<MentionDropdown {...props} />);
+ return props;
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("MentionDropdown", () => {
+ it("shows an error message when loading failed", () => {
+ renderDropdown({ isError: true });
+ expect(screen.getByText(/couldn't load files/i)).toBeTruthy();
+ });
+
+ it("shows a loading message while searching", () => {
+ renderDropdown({ isLoading: true });
+ expect(screen.getByText(/searching files/i)).toBeTruthy();
+ });
+
+ it("shows an empty state when there are no matches", () => {
+ renderDropdown();
+ expect(screen.getByText(/no matching files/i)).toBeTruthy();
+ });
+
+ it("renders a row per file and selects on mousedown", () => {
+ const { onSelect } = renderDropdown({ files: [FILE] });
+ const option = screen.getByRole("option", { name: /alpha\.txt/i });
+ fireEvent.mouseDown(option);
+ expect(onSelect).toHaveBeenCalledWith(FILE);
+ });
+
+ it("highlights a row on hover", () => {
+ const { onHighlight } = renderDropdown({
+ files: [FILE],
+ highlightedIndex: -1,
+ });
+ fireEvent.mouseEnter(screen.getByRole("option", { name: /alpha\.txt/i }));
+ expect(onHighlight).toHaveBeenCalledWith(0);
+ });
+});
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.ts
new file mode 100644
index 0000000000..e60093e546
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts
@@ -0,0 +1,133 @@
+import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/workspace";
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { useDebouncedValue } from "@/hooks/useDebouncedValue";
+import { useKeyboardNav } from "@/components/organisms/SearchCommandModal/useKeyboardNav";
+import { keepPreviousData, useQuery } from "@tanstack/react-query";
+import type { KeyboardEvent } from "react";
+import { useState } from "react";
+
+const MENTION_RE = /(?:^|\s)@([^\s@]*)$/;
+const QUERY_DEBOUNCE_MS = 200;
+const MENTION_RESULT_LIMIT = 8;
+
+interface ActiveMention {
+ query: string;
+ start: number;
+ end: number;
+}
+
+interface Args {
+ enabled: boolean;
+ value: string;
+ setValue: (value: string) => void;
+ addWorkspaceFile: (item: WorkspaceFileItem) => void;
+}
+
+/**
+ * Detects an active `@token` at the textarea caret and drives a workspace-file
+ * autocomplete. Selecting a file strips the `@query` from the message and adds
+ * the file as an attachment chip. Keyboard nav stays in the textarea (focus
+ * never leaves), so this owns the highlight cursor and the key handler.
+ */
+export function useChatMentions({
+ enabled,
+ value,
+ setValue,
+ addWorkspaceFile,
+}: Args) {
+ const [active, setActive] = useState<ActiveMention | null>(null);
+ const isOpen = enabled && active !== null;
+
+ const debouncedQuery = useDebouncedValue(
+ active?.query ?? "",
+ QUERY_DEBOUNCE_MS,
+ );
+
+ const search = useQuery({
+ queryKey: ["chat-mention", "workspace-files", debouncedQuery],
+ queryFn: () =>
+ listWorkspaceFiles({
+ limit: MENTION_RESULT_LIMIT,
+ q: debouncedQuery || undefined,
+ }),
+ enabled: isOpen,
+ placeholderData: keepPreviousData,
+ });
+
+ const files =
+ search.data?.status === 200 ? (search.data.data.files ?? []) : [];
+
+ const {
+ highlightedIndex,
+ highlightedRef,
+ moveHighlight,
+ setHighlightedIndex,
+ } = useKeyboardNav(files.length, debouncedQuery);
+
+ function detect(textarea: HTMLTextAreaElement) {
+ if (!enabled) return;
+ const caret = textarea.selectionStart ?? textarea.value.length;
+ const match = textarea.value.slice(0, caret).match(MENTION_RE);
+ if (!match) {
+ setActive(null);
+ return;
+ }
+ const query = match[1];
+ setActive({ query, start: caret - query.length - 1, end: caret });
+ }
+
+ function close() {
+ setActive(null);
+ }
+
+ function accept(item: WorkspaceFileItem | 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;
+ setValue(value.slice(0, active.start) + value.slice(active.end));
+ addWorkspaceFile(item);
+ setActive(null);
+ }
+
+ function onKeyDown(e: KeyboardEvent<HTMLTextAreaElement>): boolean {
+ if (!isOpen) return false;
+ if (e.key === "Escape") {
+ e.preventDefault();
+ close();
+ return true;
+ }
+ if (files.length === 0) return false;
+ switch (e.key) {
+ case "ArrowDown":
+ e.preventDefault();
+ moveHighlight(1);
+ return true;
+ case "ArrowUp":
+ e.preventDefault();
+ moveHighlight(-1);
+ return true;
+ case "Enter":
+ case "Tab":
+ e.preventDefault();
+ accept(files[highlightedIndex]);
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ return {
+ isOpen,
+ files,
+ isLoading: search.isLoading,
+ isError: search.isError,
+ highlightedIndex,
+ highlightedRef,
+ setHighlightedIndex,
+ detect,
+ close,
+ accept,
+ onKeyDown,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
index 4b1cd1dd83..b5c9b2c7c9 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
@@ -18,13 +18,18 @@ import { SuggestionThemes } from "./components/SuggestionThemes/SuggestionThemes
import { PulseChips } from "../PulseChips/PulseChips";
import { usePulseChips } from "../PulseChips/usePulseChips";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
+import type { WorkspaceAttachment } from "../../helpers/workspaceAttachments";
import { EditNameDialog } from "./components/EditNameDialog/EditNameDialog";
interface Props {
inputLayoutId: string;
isCreatingSession: boolean;
onCreateSession: () => void | Promise<string>;
- onSend: (message: string, files?: File[]) => void | Promise<void>;
+ onSend: (
+ message: string,
+ files?: File[],
+ workspaceFiles?: WorkspaceAttachment[],
+ ) => void | Promise<void>;
isUploadingFiles?: boolean;
droppedFiles?: File[];
onDroppedFilesConsumed?: () => void;
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
new file mode 100644
index 0000000000..16205a2b6e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/workspaceAttachments.test.ts
@@ -0,0 +1,82 @@
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { describe, expect, it } from "vitest";
+import {
+ type Attachment,
+ attachmentName,
+ buildWorkspaceFilePart,
+ partitionAttachments,
+ workspaceFileDownloadUrl,
+ workspaceItemToAttachment,
+} from "../workspaceAttachments";
+
+function makeWorkspaceItem(
+ overrides: Partial<WorkspaceFileItem> = {},
+): WorkspaceFileItem {
+ return {
+ id: "file-1",
+ name: "report.pdf",
+ path: "/workspace/report.pdf",
+ mime_type: "application/pdf",
+ size_bytes: 1024,
+ origin: "uploaded",
+ created_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+describe("workspaceAttachments", () => {
+ it("builds the workspace download URL from a file id", () => {
+ expect(workspaceFileDownloadUrl("abc")).toBe(
+ "/api/proxy/api/workspace/files/abc/download",
+ );
+ });
+
+ it("maps a workspace file item to a workspace attachment", () => {
+ const attachment = workspaceItemToAttachment(makeWorkspaceItem());
+ expect(attachment).toEqual({
+ kind: "workspace",
+ fileId: "file-1",
+ name: "report.pdf",
+ mimeType: "application/pdf",
+ });
+ });
+
+ it("resolves the display name for both attachment kinds", () => {
+ const local: Attachment = {
+ kind: "local",
+ file: new File(["x"], "local.txt", { type: "text/plain" }),
+ };
+ const workspace = workspaceItemToAttachment(makeWorkspaceItem());
+ expect(attachmentName(local)).toBe("local.txt");
+ expect(attachmentName(workspace)).toBe("report.pdf");
+ });
+
+ it("builds a FileUIPart that points at the workspace download URL", () => {
+ const part = buildWorkspaceFilePart({
+ fileId: "file-9",
+ name: "data.csv",
+ mimeType: "text/csv",
+ });
+ expect(part).toEqual({
+ type: "file",
+ mediaType: "text/csv",
+ filename: "data.csv",
+ url: "/api/proxy/api/workspace/files/file-9/download",
+ });
+ });
+
+ it("partitions mixed attachments into local files and workspace refs", () => {
+ const localFile = new File(["x"], "local.txt", { type: "text/plain" });
+ const attachments: Attachment[] = [
+ { kind: "local", file: localFile },
+ workspaceItemToAttachment(makeWorkspaceItem({ id: "ws-1" })),
+ ];
+
+ const { localFiles, workspaceFiles } = partitionAttachments(attachments);
+
+ expect(localFiles).toEqual([localFile]);
+ expect(workspaceFiles).toEqual([
+ { fileId: "ws-1", name: "report.pdf", mimeType: "application/pdf" },
+ ]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts
new file mode 100644
index 0000000000..ad82b41f61
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/workspaceAttachments.ts
@@ -0,0 +1,70 @@
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import type { FileUIPart } from "ai";
+
+/**
+ * A file already stored in the user's workspace. Unlike a freshly picked
+ * local `File`, it already has an id on the backend, so attaching it to a
+ * message needs no upload — we build a `FileUIPart` pointing straight at the
+ * workspace download URL.
+ */
+export interface WorkspaceAttachment {
+ fileId: string;
+ name: string;
+ mimeType: string;
+}
+
+/**
+ * A chat-composer attachment: either a local file awaiting upload or a
+ * reference to an existing workspace file.
+ */
+export type Attachment =
+ | { kind: "local"; file: File }
+ | ({ kind: "workspace" } & WorkspaceAttachment);
+
+export function workspaceFileDownloadUrl(fileId: string): string {
+ return `/api/proxy/api/workspace/files/${encodeURIComponent(fileId)}/download`;
+}
+
+export function workspaceItemToAttachment(item: WorkspaceFileItem): Attachment {
+ return {
+ kind: "workspace",
+ fileId: item.id,
+ name: item.name,
+ mimeType: item.mime_type,
+ };
+}
+
+export function attachmentName(attachment: Attachment): string {
+ return attachment.kind === "local" ? attachment.file.name : attachment.name;
+}
+
+export function buildWorkspaceFilePart(
+ attachment: WorkspaceAttachment,
+): FileUIPart {
+ return {
+ type: "file",
+ mediaType: attachment.mimeType,
+ filename: attachment.name,
+ url: workspaceFileDownloadUrl(attachment.fileId),
+ };
+}
+
+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 };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
index 5e10632e49..6bdec30509 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
@@ -5,6 +5,7 @@ import type { UIMessage } from "ai";
import { useMemo, useRef } from "react";
import { concatWithAssistantMerge } from "./helpers/convertChatSessionToUiMessages";
import { getLatestAssistantStatusMessage } from "./helpers";
+import type { WorkspaceAttachment } from "./helpers/workspaceAttachments";
import { queueFollowUpMessage } from "./helpers/queueFollowUpMessage";
import { stripReplayPrefix } from "./helpers/stripReplayPrefix";
import { useCopilotStreamStore } from "./copilotStreamStore";
@@ -171,12 +172,18 @@ export function useCopilotPage() {
// Wrap sendNewMessage with queue-in-flight routing: if a session is active
// and a turn is already running, POST the follow-up text to the pending
// endpoint so the backend buffers it; otherwise fall through to normal send.
- async function onSend(message: string, files?: File[]) {
+ async function onSend(
+ message: string,
+ files?: File[],
+ workspaceFiles?: WorkspaceAttachment[],
+ ) {
const trimmed = message.trim();
- if (!trimmed && (!files || files.length === 0)) return;
+ const hasAttachments =
+ (files?.length ?? 0) > 0 || (workspaceFiles?.length ?? 0) > 0;
+ if (!trimmed && !hasAttachments) return;
if (sessionId && isInflightRef.current) {
- if (files && files.length > 0) {
+ if (hasAttachments) {
toast({
title: "Please wait to attach files",
description:
@@ -194,7 +201,7 @@ export function useCopilotPage() {
err instanceof Error &&
err.name === "QueueFollowUpNotActiveError"
) {
- await sendNewMessage(message, files);
+ await sendNewMessage(message, files, workspaceFiles);
return;
}
toast({
@@ -213,7 +220,7 @@ export function useCopilotPage() {
if (sessionId) {
isInflightRef.current = true;
}
- await sendNewMessage(message, files);
+ await sendNewMessage(message, files, workspaceFiles);
}
useWorkflowImportAutoSubmit({ onSend, setPendingFileParts });
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
index a57474dc03..3604dbd901 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
@@ -4,6 +4,11 @@ import type { UseChatHelpers } from "@ai-sdk/react";
import type { FileUIPart, UIMessage } from "ai";
import { useEffect, useRef, useState } from "react";
import { useCopilotStreamStore } from "./copilotStreamStore";
+import {
+ buildWorkspaceFilePart,
+ workspaceFileDownloadUrl,
+ type WorkspaceAttachment,
+} from "./helpers/workspaceAttachments";
const MAX_FILES = 10;
const MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024;
@@ -87,7 +92,7 @@ export function useSendMessage({
type: "file" as const,
mediaType: f.mime_type,
filename: f.name,
- url: `/api/proxy/api/workspace/files/${f.file_id}/download`,
+ url: workspaceFileDownloadUrl(f.file_id),
}));
}
@@ -105,12 +110,11 @@ export function useSendMessage({
// message", so passing it would put the SDK into edit-mode with no
// target and break the optimistic-render path that pushes the user
// bubble into ``messages`` synchronously.
- if (prebuiltParts.length > 0) {
- sendMessage({ text, files: prebuiltParts });
- return;
- }
if (files.length === 0) {
- sendMessage({ text });
+ sendMessage({
+ text,
+ files: prebuiltParts.length > 0 ? prebuiltParts : undefined,
+ });
return;
}
setIsUploadingFiles(true);
@@ -122,12 +126,20 @@ export function useSendMessage({
description: "Could not upload any files. Please try again.",
variant: "destructive",
});
+ // The workspace references didn't fail to upload (they need no upload),
+ // so don't discard them just because the local uploads failed.
+ if (prebuiltParts.length > 0) {
+ sendMessage({ text, files: prebuiltParts });
+ return;
+ }
throw new Error("All file uploads failed");
}
- const fileParts = buildFileParts(uploaded);
+ // 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)];
sendMessage({
text,
- files: fileParts.length > 0 ? fileParts : undefined,
+ files: allParts.length > 0 ? allParts : undefined,
});
} finally {
setIsUploadingFiles(false);
@@ -150,9 +162,15 @@ export function useSendMessage({
void dispatchRef.current(sessionId, send.text, send.files, parts);
}, [sessionId]);
- async function onSend(message: string, files?: File[]) {
+ async function onSend(
+ message: string,
+ files?: File[],
+ workspaceFiles?: WorkspaceAttachment[],
+ ) {
const trimmed = message.trim();
- if (!trimmed && (!files || files.length === 0)) return;
+ const hasWorkspaceFiles = !!workspaceFiles && workspaceFiles.length > 0;
+ if (!trimmed && (!files || files.length === 0) && !hasWorkspaceFiles)
+ return;
if (files && files.length > 0) {
if (files.length > MAX_FILES) {
@@ -176,21 +194,28 @@ export function useSendMessage({
isUserStoppingRef.current = false;
+ const workspaceParts = (workspaceFiles ?? []).map(buildWorkspaceFilePart);
+
if (sessionId) {
const { pendingFileParts, setPendingFileParts } =
useCopilotStreamStore.getState();
setPendingFileParts([]);
- await dispatchToSession(
- sessionId,
- trimmed,
- files ?? [],
- pendingFileParts,
- );
+ await dispatchToSession(sessionId, trimmed, files ?? [], [
+ ...pendingFileParts,
+ ...workspaceParts,
+ ]);
return;
}
if (isCreatingSessionRef.current) return;
isCreatingSessionRef.current = true;
+ // Workspace parts must reach the post-creation flush, which reads them
+ // from the store via `takePendingFirstSend`. Append so a pre-set part
+ // (e.g. workflow-import) isn't clobbered.
+ if (workspaceParts.length > 0) {
+ const store = useCopilotStreamStore.getState();
+ store.setPendingFileParts([...store.pendingFileParts, ...workspaceParts]);
+ }
useCopilotStreamStore
.getState()
.setPendingFirstSend({ text: trimmed, files: files ?? [] });
diff --git a/autogpt_platform/frontend/src/components/organisms/SearchCommandModal/useKeyboardNav.ts b/autogpt_platform/frontend/src/components/organisms/SearchCommandModal/useKeyboardNav.ts
index 5f6fa789fd..af843de1ce 100644
--- a/autogpt_platform/frontend/src/components/organisms/SearchCommandModal/useKeyboardNav.ts
+++ b/autogpt_platform/frontend/src/components/organisms/SearchCommandModal/useKeyboardNav.ts
@@ -17,7 +17,7 @@ export function useKeyboardNav(totalCount: number, resetKey: unknown) {
useEffect(() => {
setHighlightedIndex(0);
- }, [resetKey, totalCount]);
+ }, [resetKey]);
useEffect(() => {
if (highlightedIndex >= totalCount) {
diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
index bee48306a5..23d06b866f 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
@@ -17,6 +17,7 @@ export enum Flag {
GENERIC_TRIGGER_AGENTS = "generic-trigger-agents",
CHAT_SEARCH = "chat-search",
CHAT_SHARING = "chat-sharing",
+ CHAT_WORKSPACE_FILES = "chat-workspace-files",
// Graphiti memory + dream-system gates. Mirror of the backend
// ``Flag`` enum in ``backend/util/feature_flag.py``. Frontend reads
// them when memory/dream-related UI surfaces ship (P6+ on the
@@ -46,6 +47,7 @@ const defaultFlags = {
[Flag.GENERIC_TRIGGER_AGENTS]: false,
[Flag.CHAT_SEARCH]: false,
[Flag.CHAT_SHARING]: false,
+ [Flag.CHAT_WORKSPACE_FILES]: false,
[Flag.GRAPHITI_MEMORY]: false,
[Flag.GRAPHITI_COMMUNITIES_ENABLED]: false,
[Flag.DREAM_PASS_ENABLED]: false,
@@ -96,6 +98,8 @@ function readEnvOverride(flag: Flag): string | undefined {
return process.env.NEXT_PUBLIC_FORCE_FLAG_CHAT_SEARCH;
case Flag.CHAT_SHARING:
return process.env.NEXT_PUBLIC_FORCE_FLAG_CHAT_SHARING;
+ case Flag.CHAT_WORKSPACE_FILES:
+ return process.env.NEXT_PUBLIC_FORCE_FLAG_CHAT_WORKSPACE_FILES;
case Flag.GRAPHITI_MEMORY:
return process.env.NEXT_PUBLIC_FORCE_FLAG_GRAPHITI_MEMORY;
case Flag.GRAPHITI_COMMUNITIES_ENABLED: