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): show copilot user bubble before attachments finish uploading (#14754)

Abhimanyu Yadav562bf25dc7a2
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
index 28e844d2b2..cdfcf6a8a7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
@@ -44,6 +44,7 @@ export function CopilotChatHost({
isSessionError,
isCreatingSession,
isUploadingFiles,
+ pendingSend,
hasMoreMessages,
isLoadingMore,
loadMore,
@@ -93,6 +94,7 @@ export function CopilotChatHost({
onEnqueue={onEnqueue}
queuedMessages={queuedMessages}
isUploadingFiles={isUploadingFiles}
+ pendingSend={pendingSend}
hasMoreMessages={hasMoreMessages}
isLoadingMore={isLoadingMore}
onLoadMore={loadMore}
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
new file mode 100644
index 0000000000..66bc48b230
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.tsx
@@ -0,0 +1,471 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useCopilotStreamStore } from "../copilotStreamStore";
+import { useCopilotUIStore } from "../store";
+import { useSendMessage } from "../useSendMessage";
+
+const { uploadFileDirectMock, toastMock } = vi.hoisted(() => ({
+ uploadFileDirectMock: vi.fn(),
+ toastMock: vi.fn(),
+}));
+
+vi.mock("@/lib/direct-upload", () => ({
+ uploadFileDirect: uploadFileDirectMock,
+}));
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast: toastMock,
+}));
+
+const SESSION_ID = "4f8b0f7e-9f30-4a3b-a6a1-000000000001";
+const OTHER_SESSION_ID = "4f8b0f7e-9f30-4a3b-a6a1-000000000002";
+const FILE_ID = "5f8b0f7e-9f30-4a3b-a6a1-000000000001";
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+function makeFile(name: string, type = "application/pdf") {
+ return new File(["x".repeat(2048)], name, { type });
+}
+
+function renderSendMessage(sessionId: string | null = SESSION_ID) {
+ const stream = deferred<void>();
+ const sendMessage = vi.fn(() => stream.promise);
+ const createSession = vi.fn(async () => SESSION_ID);
+ const hook = renderHook(() =>
+ useSendMessage({
+ sessionId,
+ sendMessage: sendMessage as never,
+ createSession,
+ isUserStoppingRef: { current: false },
+ }),
+ );
+ return { ...hook, sendMessage, createSession, stream };
+}
+
+beforeEach(() => {
+ uploadFileDirectMock.mockReset();
+ toastMock.mockReset();
+ useCopilotStreamStore.getState().resetAll();
+ useCopilotUIStore.getState().setInitialPrompt(null);
+});
+
+describe("useSendMessage with local attachments", () => {
+ it("publishes a placeholder for the bubble before the upload finishes", async () => {
+ const upload = deferred<{
+ file_id: string;
+ name: string;
+ mime_type: string;
+ }>();
+ uploadFileDirectMock.mockReturnValue(upload.promise);
+ const { result, sendMessage } = renderSendMessage();
+
+ let sendPromise: Promise<void> | undefined;
+ act(() => {
+ sendPromise = result.current.onSend("tell me about this", [
+ makeFile("talk.pdf"),
+ ]);
+ });
+
+ await waitFor(() => expect(result.current.pendingSend).not.toBeNull());
+ expect(result.current.pendingSend).toEqual({
+ text: "tell me about this",
+ attachments: [
+ {
+ name: "talk.pdf",
+ mediaType: "application/pdf",
+ sizeBytes: 2048,
+ isUploading: true,
+ },
+ ],
+ });
+ expect(result.current.isUploadingFiles).toBe(true);
+ expect(sendMessage).not.toHaveBeenCalled();
+
+ await act(async () => {
+ upload.resolve({
+ file_id: FILE_ID,
+ name: "talk.pdf",
+ mime_type: "application/pdf",
+ });
+ });
+
+ await waitFor(() => expect(sendMessage).toHaveBeenCalledTimes(1));
+ expect(sendMessage).toHaveBeenCalledWith({
+ text: "tell me about this",
+ files: [
+ {
+ type: "file",
+ mediaType: "application/pdf",
+ filename: "talk.pdf",
+ url: `/api/proxy/api/workspace/files/${FILE_ID}/download`,
+ },
+ ],
+ metadata: undefined,
+ });
+ // The placeholder and the upload lock both clear once the real message
+ // is handed to the SDK — not when the whole stream ends.
+ await waitFor(() => expect(result.current.pendingSend).toBeNull());
+ expect(result.current.isUploadingFiles).toBe(false);
+ expect(sendPromise).toBeDefined();
+ });
+
+ it("lists workspace references as already stored next to the uploading files", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result } = renderSendMessage();
+
+ act(() => {
+ void result.current.onSend(
+ "compare",
+ [makeFile("icon.png", "image/png")],
+ [{ fileId: FILE_ID, name: "notes.txt", mimeType: "text/plain" }],
+ );
+ });
+
+ await waitFor(() => expect(result.current.pendingSend).not.toBeNull());
+ expect(result.current.pendingSend?.attachments).toEqual([
+ { name: "notes.txt", mediaType: "text/plain", isUploading: false },
+ {
+ name: "icon.png",
+ mediaType: "image/png",
+ sizeBytes: 2048,
+ isUploading: true,
+ },
+ ]);
+ });
+
+ it("drops the placeholder and rethrows when every upload fails", async () => {
+ uploadFileDirectMock.mockRejectedValue(new Error("boom"));
+ const { result, sendMessage } = renderSendMessage();
+
+ let failure: unknown;
+ await act(async () => {
+ failure = await result.current
+ .onSend("hi", [makeFile("talk.pdf")])
+ .catch((err: unknown) => err);
+ });
+
+ expect(failure).toBeInstanceOf(Error);
+ expect(sendMessage).not.toHaveBeenCalled();
+ expect(result.current.pendingSend).toBeNull();
+ expect(result.current.isUploadingFiles).toBe(false);
+ });
+
+ it("still sends the workspace references when every local upload fails", async () => {
+ uploadFileDirectMock.mockRejectedValue(new Error("boom"));
+ const { result, sendMessage } = renderSendMessage();
+
+ act(() => {
+ void result.current.onSend(
+ "compare",
+ [makeFile("talk.pdf")],
+ [{ fileId: FILE_ID, name: "notes.txt", mimeType: "text/plain" }],
+ );
+ });
+
+ await waitFor(() => expect(sendMessage).toHaveBeenCalledTimes(1));
+ expect(sendMessage).toHaveBeenCalledWith({
+ text: "compare",
+ files: [
+ {
+ type: "file",
+ mediaType: "text/plain",
+ filename: "notes.txt",
+ url: `/api/proxy/api/workspace/files/${FILE_ID}/download`,
+ },
+ ],
+ metadata: undefined,
+ });
+ await waitFor(() => expect(result.current.pendingSend).toBeNull());
+ expect(result.current.isUploadingFiles).toBe(false);
+ });
+
+ it("does not publish a placeholder for a text-only first message", async () => {
+ const creation = deferred<string>();
+ const { result, createSession } = renderSendMessage(null);
+ createSession.mockReturnValue(creation.promise);
+
+ act(() => {
+ void result.current.onSend("just text");
+ });
+
+ await waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));
+ expect(result.current.pendingSend).toBeNull();
+ expect(useCopilotStreamStore.getState().pendingFirstSend?.text).toBe(
+ "just text",
+ );
+ });
+
+ it("shows the placeholder while the first chat's session is still being created", async () => {
+ const creation = deferred<string>();
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result, createSession } = renderSendMessage(null);
+ createSession.mockReturnValue(creation.promise);
+
+ act(() => {
+ void result.current.onSend("first", [makeFile("talk.pdf")]);
+ });
+
+ await waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));
+ expect(result.current.pendingSend).toEqual({
+ text: "first",
+ attachments: [
+ {
+ name: "talk.pdf",
+ mediaType: "application/pdf",
+ sizeBytes: 2048,
+ isUploading: true,
+ },
+ ],
+ });
+ });
+
+ it("hides a placeholder that belongs to another session", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result } = renderSendMessage(OTHER_SESSION_ID);
+
+ act(() => {
+ useCopilotStreamStore.getState().setPendingUploadSend(SESSION_ID, {
+ text: "elsewhere",
+ attachments: [],
+ });
+ });
+
+ await waitFor(() => expect(result.current.pendingSend).toBeNull());
+ expect(result.current.isUploadingFiles).toBe(false);
+ });
+});
+
+describe("useSendMessage placeholders across sessions", () => {
+ function uploadResult(name: string) {
+ return { file_id: FILE_ID, name, mime_type: "application/pdf" };
+ }
+
+ it("keeps one placeholder per session and clears only the one that settles", async () => {
+ const uploadA = deferred<ReturnType<typeof uploadResult>>();
+ const uploadB = deferred<ReturnType<typeof uploadResult>>();
+ uploadFileDirectMock.mockImplementation((file: File) =>
+ file.name === "a.pdf" ? uploadA.promise : uploadB.promise,
+ );
+ const chatA = renderSendMessage(SESSION_ID);
+ const chatB = renderSendMessage(OTHER_SESSION_ID);
+
+ act(() => {
+ void chatA.result.current.onSend("from A", [makeFile("a.pdf")]);
+ });
+ act(() => {
+ void chatB.result.current.onSend("from B", [makeFile("b.pdf")]);
+ });
+
+ await waitFor(() =>
+ expect(chatA.result.current.pendingSend?.text).toBe("from A"),
+ );
+ await waitFor(() =>
+ expect(chatB.result.current.pendingSend?.text).toBe("from B"),
+ );
+ expect(chatA.result.current.isUploadingFiles).toBe(true);
+ expect(chatB.result.current.isUploadingFiles).toBe(true);
+
+ await act(async () => {
+ uploadA.resolve(uploadResult("a.pdf"));
+ });
+
+ await waitFor(() => expect(chatA.sendMessage).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(chatA.result.current.pendingSend).toBeNull());
+ expect(chatA.result.current.isUploadingFiles).toBe(false);
+ expect(chatB.result.current.pendingSend?.text).toBe("from B");
+ expect(chatB.result.current.isUploadingFiles).toBe(true);
+ expect(chatB.sendMessage).not.toHaveBeenCalled();
+
+ await act(async () => {
+ uploadB.resolve(uploadResult("b.pdf"));
+ });
+
+ await waitFor(() => expect(chatB.sendMessage).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(chatB.result.current.pendingSend).toBeNull());
+ expect(chatB.result.current.isUploadingFiles).toBe(false);
+ });
+
+ it("keeps the placeholder and the upload lock across a remount mid-upload", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const first = renderSendMessage();
+
+ act(() => {
+ void first.result.current.onSend("hold on", [makeFile("a.pdf")]);
+ });
+ await waitFor(() =>
+ expect(first.result.current.isUploadingFiles).toBe(true),
+ );
+ first.unmount();
+
+ const second = renderSendMessage();
+ expect(second.result.current.pendingSend?.text).toBe("hold on");
+ expect(second.result.current.isUploadingFiles).toBe(true);
+ });
+
+ it("moves the first send's placeholder onto the session once it is created", async () => {
+ const upload = deferred<ReturnType<typeof uploadResult>>();
+ uploadFileDirectMock.mockReturnValue(upload.promise);
+ const creation = deferred<string>();
+ const newChat = renderSendMessage(null);
+ newChat.createSession.mockImplementation(async () => {
+ const id = await creation.promise;
+ useCopilotStreamStore.getState().bindPendingFirstSendToSession(id);
+ return id;
+ });
+
+ act(() => {
+ void newChat.result.current.onSend("first", [makeFile("a.pdf")]);
+ });
+
+ await waitFor(() => expect(newChat.createSession).toHaveBeenCalledTimes(1));
+ expect(newChat.result.current.pendingSend?.text).toBe("first");
+ expect(newChat.result.current.isUploadingFiles).toBe(true);
+
+ // An existing chat open elsewhere must not pick up the unbound send.
+ const other = renderSendMessage(OTHER_SESSION_ID);
+ expect(other.result.current.pendingSend).toBeNull();
+ expect(other.result.current.isUploadingFiles).toBe(false);
+
+ await act(async () => {
+ creation.resolve(SESSION_ID);
+ });
+ newChat.unmount();
+
+ const created = renderSendMessage(SESSION_ID);
+ expect(created.result.current.pendingSend?.text).toBe("first");
+ expect(created.result.current.isUploadingFiles).toBe(true);
+ await waitFor(() => expect(uploadFileDirectMock).toHaveBeenCalledTimes(1));
+ expect(other.result.current.pendingSend).toBeNull();
+
+ await act(async () => {
+ upload.resolve(uploadResult("a.pdf"));
+ });
+
+ await waitFor(() => expect(created.sendMessage).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(created.result.current.pendingSend).toBeNull());
+ expect(created.result.current.isUploadingFiles).toBe(false);
+ expect(other.result.current.pendingSend).toBeNull();
+ });
+});
+
+describe("useSendMessage first send failing after the session exists", () => {
+ // Creating a session remounts the chat host, so the queued first send is
+ // dispatched by a fresh hook long after `onSend` resolved. Nothing is left
+ // to catch its rejection except the hook itself.
+ async function startFirstSend(
+ text: string,
+ files: File[],
+ workspaceFiles?: { fileId: string; name: string; mimeType: string }[],
+ ) {
+ const newChat = renderSendMessage(null);
+ newChat.createSession.mockImplementation(async () => {
+ useCopilotStreamStore
+ .getState()
+ .bindPendingFirstSendToSession(SESSION_ID);
+ return SESSION_ID;
+ });
+
+ await act(async () => {
+ await newChat.result.current.onSend(text, files, workspaceFiles);
+ });
+ newChat.unmount();
+
+ return renderSendMessage(SESSION_ID);
+ }
+
+ it("restores the draft when every upload for the first send fails", async () => {
+ uploadFileDirectMock.mockRejectedValue(new Error("network down"));
+
+ const created = await startFirstSend("first", [makeFile("talk.pdf")]);
+
+ await waitFor(() =>
+ expect(useCopilotUIStore.getState().initialPrompt).toBe("first"),
+ );
+ expect(created.sendMessage).not.toHaveBeenCalled();
+ expect(created.result.current.pendingSend).toBeNull();
+ expect(created.result.current.isUploadingFiles).toBe(false);
+ expect(toastMock).toHaveBeenLastCalledWith({
+ title: "Couldn't send message",
+ description:
+ "All file uploads failed — your message is back in the composer.",
+ variant: "destructive",
+ });
+ });
+
+ it("puts the workspace references back when the first send's message fails", async () => {
+ const created = await startFirstSend(
+ "compare",
+ [],
+ [{ fileId: FILE_ID, name: "notes.txt", mimeType: "text/plain" }],
+ );
+
+ await waitFor(() => expect(created.sendMessage).toHaveBeenCalledTimes(1));
+ expect(useCopilotStreamStore.getState().pendingFileParts).toEqual([]);
+
+ await act(async () => {
+ created.stream.reject(new Error("stream died"));
+ });
+
+ await waitFor(() =>
+ expect(useCopilotStreamStore.getState().pendingFileParts).toEqual([
+ {
+ type: "file",
+ mediaType: "text/plain",
+ filename: "notes.txt",
+ url: `/api/proxy/api/workspace/files/${FILE_ID}/download`,
+ },
+ ]),
+ );
+ expect(useCopilotUIStore.getState().initialPrompt).toBe("compare");
+ });
+});
+
+describe("useSendMessage when creating the first chat's session fails", () => {
+ it("clears the placeholder so a failed first send leaves nothing behind", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result, createSession } = renderSendMessage(null);
+ createSession.mockRejectedValue(new Error("no session"));
+
+ let failure: unknown;
+ await act(async () => {
+ failure = await result.current
+ .onSend("first", [makeFile("talk.pdf")])
+ .catch((err: unknown) => err);
+ });
+
+ expect(failure).toBeInstanceOf(Error);
+ expect(result.current.pendingSend).toBeNull();
+ expect(result.current.isUploadingFiles).toBe(false);
+ expect(useCopilotStreamStore.getState().pendingUploadSends).toEqual({});
+ });
+
+ it("clears a placeholder already bound to the new session", async () => {
+ uploadFileDirectMock.mockReturnValue(new Promise(() => undefined));
+ const { result, createSession } = renderSendMessage(null);
+ createSession.mockImplementation(async () => {
+ // Binding moves the placeholder off the unbound key; failing after it
+ // must not leave the session-keyed one stranded.
+ useCopilotStreamStore
+ .getState()
+ .bindPendingFirstSendToSession(SESSION_ID);
+ throw new Error("no session");
+ });
+
+ await act(async () => {
+ await result.current
+ .onSend("first", [makeFile("talk.pdf")])
+ .catch(() => undefined);
+ });
+
+ expect(useCopilotStreamStore.getState().pendingUploadSends).toEqual({});
+ expect(renderSendMessage(SESSION_ID).result.current.pendingSend).toBeNull();
+ });
+});
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 bfde2884ec..6c082e3ebc 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
@@ -12,6 +12,7 @@ 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 type { PendingUploadSend } from "../../copilotStreamStore";
import { ChatMessagesContainer } from "../ChatMessagesContainer/ChatMessagesContainer";
import { CopilotChatActionsProvider } from "../CopilotChatActionsProvider/CopilotChatActionsProvider";
import { EmptySession } from "../EmptySession/EmptySession";
@@ -82,6 +83,9 @@ export interface ChatContainerProps {
/** Pending queued messages waiting to be injected, shown at the end of chat. */
queuedMessages?: string[];
isUploadingFiles?: boolean;
+ /** The message whose attachments are still uploading, shown as a
+ * placeholder bubble until the real one lands in `messages`. */
+ pendingSend?: PendingUploadSend | null;
hasMoreMessages?: boolean;
isLoadingMore?: boolean;
onLoadMore?: () => void;
@@ -131,6 +135,7 @@ export const ChatContainer = ({
onEnqueue,
queuedMessages,
isUploadingFiles,
+ pendingSend,
hasMoreMessages,
isLoadingMore,
onLoadMore,
@@ -315,6 +320,7 @@ export const ChatContainer = ({
onRetry={handleRetry}
turnStats={turnStats}
queuedMessages={queuedMessages}
+ pendingSend={pendingSend}
bottomContentPadding={usageCardHeight}
expertIdentity={expertIdentity}
isResolvingExpertIdentity={isResolvingExpertIdentity}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
index f0d663d031..4d25c1c3e3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
@@ -51,8 +51,13 @@ import { MessageAttachments } from "./components/MessageAttachments";
import { MessagePartRenderer } from "./components/MessagePartRenderer";
import { QueueBadge } from "./components/QueueBadge";
import { ThreadHeader } from "./components/ThreadHeader";
+import {
+ PENDING_UPLOAD_MESSAGE_ID,
+ PendingUploadMessage,
+} from "./components/PendingUploadMessage";
import { ThinkingIndicator } from "./components/ThinkingIndicator";
import { UserMessageClamp } from "./components/UserMessageClamp";
+import type { PendingUploadSend } from "../../copilotStreamStore";
import { Clock01Icon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
@@ -79,6 +84,11 @@ interface Props {
turnStats?: TurnStatsMap;
/** Pending queued messages waiting to be injected, shown at the end of chat. */
queuedMessages?: string[];
+ /** A just-sent message whose local attachments are still uploading. It is
+ * not in `messages` yet (the SDK only pushes it once `sendMessage` runs),
+ * so it renders as a placeholder bubble with an "Uploading files…"
+ * status in the thinking indicator's usual spot. */
+ pendingSend?: PendingUploadSend | null;
/** Extra bottom padding (px) applied to the scrollable message list so
* overlays pinned above the input area (e.g. the usage-limit card) can
* sit over the last message without permanently obscuring it. */
@@ -314,6 +324,7 @@ export function ChatMessagesContainer({
onRetry,
turnStats,
queuedMessages,
+ pendingSend,
bottomContentPadding,
readOnly = false,
filePattern,
@@ -353,10 +364,13 @@ export function ChatMessagesContainer({
// the underlying message stays whole. See `splitMessagesAtDrainHints`.
const renderRows = splitMessagesAtDrainHints(messages);
const lastMessage = messages[messages.length - 1];
+ const showPendingSend = !readOnly && !!pendingSend;
// Read off the rendered rows: a fallback follow-up row the split drops in
// favour of the drain-point bubble has no element to anchor the tail on.
- const lastUserMessageID =
- renderRows.findLast((row) => row.role === "user")?.id ?? null;
+ // While a send is still uploading, the placeholder is the last user row.
+ const lastUserMessageID = showPendingSend
+ ? PENDING_UPLOAD_MESSAGE_ID
+ : (renderRows.findLast((row) => row.role === "user")?.id ?? null);
const graphExecId = useMemo(() => extractGraphExecId(messages), [messages]);
// The backend appends a persisted error marker to ``session.messages`` AND
@@ -537,11 +551,14 @@ export function ChatMessagesContainer({
onLoadMore={onLoadMore}
/>
)}
- {isLoading && messages.length === 0 && !isRestoringActiveSession && (
- <div className="flex flex-1 items-center justify-center">
- <LoadingSpinner className="text-neutral-600" />
- </div>
- )}
+ {isLoading &&
+ messages.length === 0 &&
+ !isRestoringActiveSession &&
+ !showPendingSend && (
+ <div className="flex flex-1 items-center justify-center">
+ <LoadingSpinner className="text-neutral-600" />
+ </div>
+ )}
{renderRows.map((message, rowIndex) => {
// A run-post rides structured metadata — render a compact WorkCard
// instead of the raw markdown wall (legacy posts have no metadata
@@ -775,6 +792,12 @@ export function ChatMessagesContainer({
</Message>
);
})}
+ {showPendingSend && pendingSend && (
+ <PendingUploadMessage
+ pendingSend={pendingSend}
+ isCompact={isCompact}
+ />
+ )}
{showIndicator && lastMessage?.role !== "assistant" && (
<Message
from="assistant"
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
index 3bbd790589..fd6b32919b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
@@ -888,6 +888,104 @@ describe("ChatMessagesContainer — expert kickoff", () => {
});
});
+// ── pending upload placeholder ────────────────────────────────────────────
+
+describe("ChatMessagesContainer — pendingSend", () => {
+ const pendingSend = {
+ text: "tell me about this",
+ attachments: [
+ {
+ name: "talk.pdf",
+ mediaType: "application/pdf",
+ sizeBytes: 2048,
+ isUploading: true,
+ },
+ { name: "icon.png", mediaType: "image/png", isUploading: true },
+ ],
+ };
+
+ beforeEach(() => {
+ vi.stubGlobal("IntersectionObserver", MockIntersectionObserver);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("renders the sent text and attachments before the message reaches the transcript", () => {
+ render(<ChatMessagesContainer {...baseProps} pendingSend={pendingSend} />);
+
+ expect(screen.getByText("tell me about this")).toBeDefined();
+ expect(screen.getByText("talk.pdf")).toBeDefined();
+ expect(screen.getByText("icon.png")).toBeDefined();
+ });
+
+ it("narrates the upload in the thinking indicator", () => {
+ render(<ChatMessagesContainer {...baseProps} pendingSend={pendingSend} />);
+
+ expect(screen.getByTestId("thinking-indicator").textContent).toBe(
+ "Uploading 2 files…",
+ );
+ });
+
+ it("uses the singular for a single file", () => {
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ pendingSend={{
+ ...pendingSend,
+ attachments: pendingSend.attachments.slice(0, 1),
+ }}
+ />,
+ );
+
+ expect(screen.getByTestId("thinking-indicator").textContent).toBe(
+ "Uploading 1 file…",
+ );
+ });
+
+ it("does not show the history spinner while the placeholder is up", () => {
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ isLoading
+ pendingSend={pendingSend}
+ />,
+ );
+
+ expect(screen.getByText("tell me about this")).toBeDefined();
+ expect(screen.queryByTestId("loading-spinner")).toBeNull();
+ });
+
+ it("keeps the placeholder out of a read-only transcript", () => {
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ pendingSend={pendingSend}
+ readOnly
+ />,
+ );
+
+ expect(screen.queryByText("tell me about this")).toBeNull();
+ expect(screen.queryByTestId("thinking-indicator")).toBeNull();
+ });
+
+ it("still shows the history spinner in a read-only transcript", () => {
+ // The placeholder is suppressed here, so nothing stands in for the
+ // spinner — hiding it would leave the transcript blank while it loads.
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ isLoading
+ pendingSend={pendingSend}
+ readOnly
+ />,
+ );
+
+ expect(screen.getByTestId("loading-spinner")).toBeDefined();
+ });
+});
+
// ── mid-turn drain split ──────────────────────────────────────────────────
describe("ChatMessagesContainer — mid-turn follow-up", () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingUploadMessage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingUploadMessage.tsx
new file mode 100644
index 0000000000..bc5cc697ce
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingUploadMessage.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Message, MessageContent } from "@/components/ai-elements/message";
+import { cn } from "@/lib/utils";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
+import { File02Icon, Loading03Icon } from "@hugeicons/core-free-icons";
+import type {
+ PendingUploadAttachment,
+ PendingUploadSend,
+} from "../../../copilotStreamStore";
+import { classifyArtifact } from "../../ArtifactPanel/helpers";
+import { useElapsedTimer } from "../../JobStatsBar/useElapsedTimer";
+import { ThinkingIndicator } from "./ThinkingIndicator";
+
+interface Props {
+ pendingSend: PendingUploadSend;
+ isCompact?: boolean;
+}
+
+/** Stable id so the tail spacer measures the placeholder like a real user
+ * message; the bubble then keeps its spot when the persisted one lands. */
+export const PENDING_UPLOAD_MESSAGE_ID = "pending-upload-message";
+
+export function uploadStatusLabel(attachments: PendingUploadAttachment[]) {
+ const count = attachments.filter((a) => a.isUploading).length;
+ if (count === 0) return "Sending…";
+ return `Uploading ${count} ${count === 1 ? "file" : "files"}…`;
+}
+
+function formatSize(bytes?: number): string {
+ if (!bytes) return "";
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+interface CardProps {
+ attachment: PendingUploadAttachment;
+}
+
+function PendingArtifactCard({ attachment }: CardProps) {
+ const classification = classifyArtifact(
+ attachment.mediaType,
+ attachment.name,
+ attachment.sizeBytes,
+ );
+ return (
+ <div className="my-1 flex w-full min-w-0 items-center gap-3 rounded-2xl border border-zinc-200 bg-white px-3 py-2.5 text-left">
+ <Icon
+ icon={classification.icon}
+ size={20}
+ className="shrink-0 text-zinc-400"
+ />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-zinc-900">
+ {attachment.name}
+ </p>
+ <p className="text-xs text-zinc-400">
+ <span className="inline-block rounded-full bg-blue-50 px-1.5 py-0.5 text-xs font-medium text-blue-500">
+ {classification.label}
+ </span>
+ {attachment.sizeBytes ? ` • ${formatSize(attachment.sizeBytes)}` : ""}
+ </p>
+ </div>
+ {attachment.isUploading && (
+ <Icon
+ icon={Loading03Icon}
+ size={16}
+ className="shrink-0 animate-spin text-zinc-400"
+ />
+ )}
+ </div>
+ );
+}
+
+function PendingFileCard({ attachment }: CardProps) {
+ return (
+ <div className="min-w-0 rounded-lg border border-purple-300 bg-purple-100 p-3">
+ <div className="flex items-center gap-2">
+ <Icon icon={File02Icon} className="h-5 w-5 shrink-0 text-neutral-400" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-zinc-800">
+ {attachment.name}
+ </p>
+ <p className="mt-0.5 truncate font-mono text-xs text-zinc-800">
+ {attachment.mediaType || "file"}
+ </p>
+ </div>
+ {attachment.isUploading && (
+ <Icon
+ icon={Loading03Icon}
+ className="h-4 w-4 shrink-0 animate-spin text-purple-400"
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Optimistic stand-in for a user message whose local attachments are still
+ * uploading. Mirrors the real bubble and attachment cards so the swap to the
+ * persisted message is invisible, and narrates the upload in the same spot
+ * the backend's own status lines ("Preparing workspace…") appear next.
+ */
+export function PendingUploadMessage({ pendingSend, isCompact }: Props) {
+ const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS);
+ const { elapsedSeconds } = useElapsedTimer(true);
+ const label = uploadStatusLabel(pendingSend.attachments);
+
+ return (
+ <>
+ <Message
+ from="user"
+ data-testid="pending-upload-message"
+ data-message-id={PENDING_UPLOAD_MESSAGE_ID}
+ className="duration-300 animate-in fade-in slide-in-from-bottom-2 fill-mode-both"
+ >
+ {pendingSend.text && (
+ <MessageContent
+ className={cn(
+ isCompact
+ ? "text-sm leading-6 group-[.is-user]:rounded-xl"
+ : "text-[1rem] leading-relaxed group-[.is-user]:rounded-3xl",
+ "group-[.is-user]:bg-zinc-100 group-[.is-user]:px-4 group-[.is-user]:py-2.5 group-[.is-user]:text-zinc-900",
+ )}
+ >
+ <div className="whitespace-pre-wrap break-words">
+ {pendingSend.text}
+ </div>
+ </MessageContent>
+ )}
+ {pendingSend.attachments.length > 0 && (
+ <div className="mt-2 flex flex-col gap-2">
+ {pendingSend.attachments.map((attachment, i) =>
+ isArtifactsEnabled ? (
+ <PendingArtifactCard
+ key={`${attachment.name}-${i}`}
+ attachment={attachment}
+ />
+ ) : (
+ <PendingFileCard
+ key={`${attachment.name}-${i}`}
+ attachment={attachment}
+ />
+ ),
+ )}
+ </div>
+ )}
+ </Message>
+ <Message
+ from="assistant"
+ className="duration-300 animate-in fade-in slide-in-from-bottom-2 fill-mode-both"
+ >
+ <MessageContent className="text-[1rem] leading-relaxed">
+ {/* Announce the status on its own: the indicator's elapsed timer
+ ticks every second, so a live region around the whole thing
+ would re-read the upload state on every tick. */}
+ <span className="sr-only" role="status" aria-live="polite">
+ {label}
+ </span>
+ <ThinkingIndicator
+ active
+ elapsedSeconds={elapsedSeconds}
+ statusMessage={label}
+ />
+ </MessageContent>
+ </Message>
+ </>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/PendingUploadMessage.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/PendingUploadMessage.test.tsx
new file mode 100644
index 0000000000..925cc43382
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/PendingUploadMessage.test.tsx
@@ -0,0 +1,117 @@
+import { cleanup, render, screen } from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ PENDING_UPLOAD_MESSAGE_ID,
+ PendingUploadMessage,
+} from "../PendingUploadMessage";
+
+const flagState = vi.hoisted(() => ({ artifacts: false }));
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useGetFlag: (flag: string) =>
+ flag === actual.Flag.ARTIFACTS ? flagState.artifacts : false,
+ };
+});
+
+vi.mock("../ThinkingIndicator", () => ({
+ ThinkingIndicator: ({ statusMessage }: { statusMessage?: string | null }) => (
+ <div data-testid="thinking-indicator">{statusMessage}</div>
+ ),
+}));
+
+const attachments = [
+ {
+ name: "talk.pdf",
+ mediaType: "application/pdf",
+ sizeBytes: 3 * 1024 * 1024,
+ isUploading: true,
+ },
+ {
+ name: "icon.png",
+ mediaType: "image/png",
+ sizeBytes: 2048,
+ isUploading: true,
+ },
+ {
+ name: "tiny.txt",
+ mediaType: "text/plain",
+ sizeBytes: 12,
+ isUploading: true,
+ },
+ { name: "notes.md", mediaType: "text/markdown", isUploading: false },
+];
+
+afterEach(() => {
+ cleanup();
+ flagState.artifacts = false;
+});
+
+describe("PendingUploadMessage", () => {
+ it("renders artifact-style cards with kind and size when artifacts are on", () => {
+ flagState.artifacts = true;
+ render(
+ <PendingUploadMessage
+ pendingSend={{ text: "look at these", attachments }}
+ />,
+ );
+
+ expect(screen.getByText("look at these")).toBeDefined();
+ expect(screen.getByText("talk.pdf")).toBeDefined();
+ expect(screen.getByText(/3\.0 MB/)).toBeDefined();
+ expect(screen.getByText(/2\.0 KB/)).toBeDefined();
+ expect(screen.getByText(/12 B/)).toBeDefined();
+ expect(screen.getByText("notes.md")).toBeDefined();
+ expect(screen.getByTestId("thinking-indicator").textContent).toBe(
+ "Uploading 3 files…",
+ );
+ });
+
+ it("falls back to plain file cards showing the media type when artifacts are off", () => {
+ render(<PendingUploadMessage pendingSend={{ text: "", attachments }} />);
+
+ expect(screen.getByText("application/pdf")).toBeDefined();
+ expect(screen.getByText("text/markdown")).toBeDefined();
+ });
+
+ it("carries the message id the tail spacer measures", () => {
+ render(<PendingUploadMessage pendingSend={{ text: "hi", attachments }} />);
+
+ expect(
+ screen
+ .getByTestId("pending-upload-message")
+ .getAttribute("data-message-id"),
+ ).toBe(PENDING_UPLOAD_MESSAGE_ID);
+ });
+
+ it("reads Sending when nothing is left to upload", () => {
+ render(
+ <PendingUploadMessage
+ pendingSend={{
+ text: "hi",
+ attachments: attachments.filter((a) => !a.isUploading),
+ }}
+ />,
+ );
+
+ expect(screen.getByTestId("thinking-indicator").textContent).toBe(
+ "Sending…",
+ );
+ });
+
+ it("announces the upload status to screen readers", () => {
+ render(<PendingUploadMessage pendingSend={{ text: "hi", attachments }} />);
+
+ const status = screen.getByRole("status");
+ expect(status.textContent).toBe("Uploading 3 files…");
+ expect(status.getAttribute("aria-live")).toBe("polite");
+ // The elapsed timer must stay outside the live region, or every tick
+ // would re-announce the upload.
+ expect(status.textContent).not.toContain("thinking");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts
index aa00db9c88..bd5ee41053 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts
@@ -57,6 +57,40 @@ export interface PendingFirstSend {
metadata?: ExpertKickoffMetadata;
}
+export interface PendingUploadAttachment {
+ name: string;
+ mediaType: string;
+ sizeBytes?: number;
+ /** Local files upload before the send; workspace references are already stored. */
+ isUploading: boolean;
+}
+
+/**
+ * The message the user just sent, shown as a placeholder bubble while its
+ * local attachments upload. The real user message only enters `messages`
+ * once `sendMessage` runs after the uploads, which can take seconds for
+ * large files — without this the transcript stays blank for that window.
+ *
+ * Kept per session in `pendingUploadSends` so an upload started in one chat
+ * neither hides nor clears the placeholder of another chat the user switches
+ * to mid-upload. The first send of a new chat has no session yet and sits
+ * under `UNBOUND_UPLOAD_KEY` until `bindPendingFirstSendToSession` moves it
+ * onto the created session. Lives here (not in React state) for the same
+ * remount reason as `PendingFirstSend`. Never persisted: a reload mid-upload
+ * loses the `File` objects, so there is nothing left to wait for.
+ */
+export interface PendingUploadSend {
+ text: string;
+ attachments: PendingUploadAttachment[];
+}
+
+/** Key for the first send of a chat whose session does not exist yet. */
+const UNBOUND_UPLOAD_KEY = "new";
+
+export function pendingUploadKey(sessionId: string | null): string {
+ return sessionId ?? UNBOUND_UPLOAD_KEY;
+}
+
interface PersistedCopilotStreamState {
sessions: Record<string, SessionCoord>;
pendingFirstSend: Pick<PendingFirstSend, "text" | "metadata"> | null;
@@ -70,6 +104,7 @@ interface CopilotStreamStore {
pendingFirstSend: PendingFirstSend | null;
pendingFirstSendSessionId: string | null;
pendingFileParts: FileUIPart[];
+ pendingUploadSends: Record<string, PendingUploadSend>;
getCoord: (sessionId: string) => SessionCoord;
updateCoord: (sessionId: string, patch: Partial<SessionCoord>) => void;
@@ -80,6 +115,16 @@ interface CopilotStreamStore {
setPendingFirstSend: (send: PendingFirstSend | null) => void;
bindPendingFirstSendToSession: (sessionId: string) => void;
setPendingFileParts: (parts: FileUIPart[]) => void;
+ setPendingUploadSend: (
+ sessionId: string | null,
+ send: PendingUploadSend,
+ ) => void;
+ /** Clears the session's placeholder; with `send`, only if it is still the
+ * one shown, so a finished upload cannot clear a newer one. */
+ clearPendingUploadSend: (
+ sessionId: string | null,
+ send?: PendingUploadSend,
+ ) => void;
/** Read-and-clear; used by the post-session-creation flush effect. */
takePendingFirstSend: (sessionId: string) => {
send: PendingFirstSend | null;
@@ -98,6 +143,7 @@ export const useCopilotStreamStore = create<CopilotStreamStore>()(
pendingFirstSend: null,
pendingFirstSendSessionId: null,
pendingFileParts: [],
+ pendingUploadSends: {},
getCoord(sessionId) {
return { ...defaultCoord, ...get().sessions[sessionId] };
@@ -143,11 +189,36 @@ export const useCopilotStreamStore = create<CopilotStreamStore>()(
},
bindPendingFirstSendToSession(sessionId) {
if (!get().pendingFirstSend) return;
- set({ pendingFirstSendSessionId: sessionId });
+ set((state) => {
+ const unbound = state.pendingUploadSends[UNBOUND_UPLOAD_KEY];
+ if (!unbound) return { pendingFirstSendSessionId: sessionId };
+ const pendingUploadSends = { ...state.pendingUploadSends };
+ delete pendingUploadSends[UNBOUND_UPLOAD_KEY];
+ pendingUploadSends[sessionId] = unbound;
+ return { pendingFirstSendSessionId: sessionId, pendingUploadSends };
+ });
},
setPendingFileParts(parts) {
set({ pendingFileParts: parts });
},
+ setPendingUploadSend(sessionId, send) {
+ set((state) => ({
+ pendingUploadSends: {
+ ...state.pendingUploadSends,
+ [pendingUploadKey(sessionId)]: send,
+ },
+ }));
+ },
+ clearPendingUploadSend(sessionId, send) {
+ set((state) => {
+ const key = pendingUploadKey(sessionId);
+ const current = state.pendingUploadSends[key];
+ if (!current || (send && current !== send)) return {};
+ const pendingUploadSends = { ...state.pendingUploadSends };
+ delete pendingUploadSends[key];
+ return { pendingUploadSends };
+ });
+ },
takePendingFirstSend(sessionId) {
const {
pendingFirstSend,
@@ -172,6 +243,7 @@ export const useCopilotStreamStore = create<CopilotStreamStore>()(
pendingFirstSend: null,
pendingFirstSendSessionId: null,
pendingFileParts: [],
+ pendingUploadSends: {},
});
},
}),
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
index 9d4421e029..ba274ace52 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
@@ -279,6 +279,7 @@ export function useCopilotPage() {
const {
onSend: sendNewMessage,
isUploadingFiles,
+ pendingSend,
setPendingFileParts,
} = useSendMessage({
sessionId,
@@ -412,6 +413,7 @@ export function useCopilotPage() {
isSessionError,
isCreatingSession,
isUploadingFiles,
+ pendingSend,
isUserLoading,
isLoggedIn,
createSession,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
index 37db4e8847..7731c29308 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
@@ -2,14 +2,21 @@ import { toast } from "@/components/molecules/Toast/use-toast";
import { uploadFileDirect } from "@/lib/direct-upload";
import type { UseChatHelpers } from "@ai-sdk/react";
import type { FileUIPart, UIMessage } from "ai";
-import { useEffect, useRef, useState } from "react";
-import { useCopilotStreamStore } from "./copilotStreamStore";
+import { useEffect, useRef } from "react";
+import {
+ pendingUploadKey,
+ useCopilotStreamStore,
+ type PendingUploadAttachment,
+ type PendingUploadSend,
+} from "./copilotStreamStore";
+import { describeSendFailure } from "./components/ChatInput/helpers";
import type { ExpertKickoffMetadata } from "./expertKickoff";
import {
buildWorkspaceFilePart,
workspaceFileDownloadUrl,
type WorkspaceAttachment,
} from "./helpers/workspaceAttachments";
+import { useCopilotUIStore } from "./store";
const MAX_FILES = 10;
const MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024;
@@ -48,7 +55,6 @@ export function useSendMessage({
createSession,
isUserStoppingRef,
}: Args) {
- const [isUploadingFiles, setIsUploadingFiles] = useState(false);
// Synchronous concurrency guard for the "no session yet" path: rapid
// double-press / double-Enter would otherwise overwrite `pendingFirstSend`
// (losing the first message) AND fire two parallel `createSession`
@@ -122,7 +128,14 @@ export function useSendMessage({
});
return;
}
- setIsUploadingFiles(true);
+ // The bubble shows right away; the transcript reads "Uploading N files…"
+ // until the uploads land and the real message takes the placeholder's
+ // spot. The slot is re-set here (not only in onSend) because this is the
+ // one path every send with files goes through, including the flush after
+ // session creation.
+ const pending = describePendingUpload(text, files, prebuiltParts);
+ useCopilotStreamStore.getState().setPendingUploadSend(sid, pending);
+ let send: Promise<void> | undefined;
try {
const uploaded = await uploadFiles(files, sid);
if (uploaded.length === 0) {
@@ -133,23 +146,24 @@ export function useSendMessage({
});
// 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) {
- await sendMessage({ text, files: prebuiltParts, metadata });
- return;
+ if (prebuiltParts.length === 0) {
+ throw new Error("All file uploads failed");
}
- throw new Error("All file uploads failed");
+ send = sendMessage({ text, files: prebuiltParts, metadata });
+ } else {
+ // Merge already-stored workspace parts with the freshly uploaded ones so
+ // a single message can mix both kinds of attachment.
+ const allParts = [...prebuiltParts, ...buildFileParts(uploaded)];
+ send = sendMessage({ text, files: allParts, metadata });
}
- // 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)];
- await sendMessage({
- text,
- files: allParts.length > 0 ? allParts : undefined,
- metadata,
- });
} finally {
- setIsUploadingFiles(false);
+ // `sendMessage` pushes the user bubble into `messages` synchronously,
+ // so the placeholder can go in the same tick with no gap between the
+ // two. Its promise only settles when the whole stream ends, which is
+ // why the cleanup happens here and not after the await below.
+ useCopilotStreamStore.getState().clearPendingUploadSend(sid, pending);
}
+ await send;
}
// Hold dispatchToSession in a ref so the queued-send effect can fire
@@ -165,13 +179,15 @@ export function useSendMessage({
.getState()
.takePendingFirstSend(sessionId);
if (!send) return;
- void dispatchRef.current(
- sessionId,
- send.text,
- send.files,
- parts,
- send.metadata,
- );
+ // `onSend` resolved the moment the session was created, so the composer's
+ // own catch (restore draft + chips, toast) can no longer observe this
+ // dispatch failing. Recover here instead, or an all-uploads-failed first
+ // send rejects with nobody listening and the user loses their message.
+ void dispatchRef
+ .current(sessionId, send.text, send.files, parts, send.metadata)
+ .catch((error: unknown) => {
+ recoverFailedFirstSend(send.text, parts, error);
+ });
}, [sessionId]);
async function onSend(
@@ -225,6 +241,14 @@ export function useSendMessage({
if (isCreatingSessionRef.current) return;
isCreatingSessionRef.current = true;
+ if (files && files.length > 0) {
+ useCopilotStreamStore
+ .getState()
+ .setPendingUploadSend(
+ null,
+ describePendingUpload(trimmed, files, workspaceParts),
+ );
+ }
// 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.
@@ -240,10 +264,20 @@ export function useSendMessage({
expertKickoff: metadata?.kind === "expert_kickoff",
});
} catch (err) {
- const { setPendingFirstSend, setPendingFileParts } =
- useCopilotStreamStore.getState();
+ const {
+ pendingFirstSendSessionId,
+ setPendingFirstSend,
+ setPendingFileParts,
+ clearPendingUploadSend,
+ } = useCopilotStreamStore.getState();
setPendingFirstSend(null);
setPendingFileParts([]);
+ // `createSession` can fail after binding the send to the new id, which
+ // moves the placeholder off the unbound key. Clear both keys so an
+ // aborted first send never strands one on the freshly created session.
+ clearPendingUploadSend(null);
+ if (pendingFirstSendSessionId)
+ clearPendingUploadSend(pendingFirstSendSessionId);
throw err;
} finally {
isCreatingSessionRef.current = false;
@@ -254,5 +288,64 @@ export function useSendMessage({
useCopilotStreamStore.getState().setPendingFileParts(parts);
}
- return { onSend, isUploadingFiles, setPendingFileParts };
+ // A placeholder belongs to the chat it was sent from: one owned by another
+ // session (the user switched threads mid-upload) must not show up here,
+ // and the not-yet-bound first send only shows in the new-chat host.
+ const pendingSend = useCopilotStreamStore(
+ (s) => s.pendingUploadSends[pendingUploadKey(sessionId)] ?? null,
+ );
+ // Derived from the store rather than local state so the composer stays
+ // locked when the host remounts while this chat's upload is in flight.
+ const isUploadingFiles = pendingSend !== null;
+
+ return { onSend, isUploadingFiles, pendingSend, setPendingFileParts };
+}
+
+/**
+ * Failure recovery for the first send of a new chat, which is dispatched from
+ * an effect long after `onSend` returned.
+ *
+ * Everything goes through the stores because the `"new"`-keyed host that
+ * started the send is already unmounted — its draft state and chips are gone.
+ * The text comes back as the composer's initial prompt and the workspace
+ * references as pending file parts; local `File` chips cannot be restored,
+ * they only ever existed in that unmounted host.
+ */
+function recoverFailedFirstSend(
+ text: string,
+ parts: FileUIPart[],
+ error: unknown,
+) {
+ if (text) useCopilotUIStore.getState().setInitialPrompt(text);
+ if (parts.length > 0)
+ useCopilotStreamStore.getState().setPendingFileParts(parts);
+ toast({
+ title: "Couldn't send message",
+ description: describeSendFailure(
+ error,
+ text
+ ? "your message is back in the composer"
+ : "your files were not sent",
+ ),
+ variant: "destructive",
+ });
+}
+
+function describePendingUpload(
+ text: string,
+ files: File[],
+ prebuiltParts: FileUIPart[],
+): PendingUploadSend {
+ const stored: PendingUploadAttachment[] = prebuiltParts.map((part) => ({
+ name: part.filename ?? "file",
+ mediaType: part.mediaType,
+ isUploading: false,
+ }));
+ const local: PendingUploadAttachment[] = files.map((file) => ({
+ name: file.name,
+ mediaType: file.type || "application/octet-stream",
+ sizeBytes: file.size,
+ isUploading: true,
+ }));
+ return { text, attachments: [...stored, ...local] };
}