AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend/copilot): send question answers right away and advance on option pick (#14515)
Abhimanyu Yadav9d0297da781f
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsxindex e72df99e46..3a23279ef6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsx@@ -31,8 +31,8 @@ interface Props {/** Everything the chain still needs from the user, stacked below it as one* card per kind of ask — connectors, run inputs, questions. The questions- * card carries its own Skip/Add footer (Add drafts the combined reply into- * the chat input); an inputs-only stack falls back to a lone Proceed, and+ * card carries its own Skip/Send footer (Send posts the combined reply as+ * one message); an inputs-only stack falls back to a lone Proceed, and* a connectors-only card has no button: connecting is the whole ask. */export function ChainActionCard({connectors,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionAnswerField.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionAnswerField.tsxindex 83f9e0d333..ca61ca757d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionAnswerField.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionAnswerField.tsx@@ -13,6 +13,9 @@ interface Props {labelId: string;autoFocus: boolean;onChange: (value: string) => void;+ /** Only the option list can fire this — free text has no single moment+ * where the answer is done. */+ onPick: (value: string) => void;onSubmit: () => void;}@@ -27,6 +30,7 @@ export function QuestionAnswerField({labelId,autoFocus,onChange,+ onPick,onSubmit,}: Props) {const options = question.options ?? [];@@ -89,6 +93,7 @@ export function QuestionAnswerField({labelId={labelId}focusActiveOption={autoFocus || toggled}onChange={onChange}+ onPick={onPick}onSubmit={onSubmit}/><buttondiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionOptionList.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionOptionList.tsxindex 7df0f6a35b..18a93cc6c4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionOptionList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionOptionList.tsx@@ -13,6 +13,9 @@ interface Props {labelId: string;focusActiveOption: boolean;onChange: (value: string) => void;+ /** A pointer or tap choice, as opposed to `onChange`, which the arrow keys+ * fire too while the user is only browsing the group. */+ onPick: (value: string) => void;onSubmit: () => void;}@@ -25,6 +28,7 @@ export function QuestionOptionList({labelId,focusActiveOption,onChange,+ onPick,onSubmit,}: Props) {const refs = useRef<(HTMLButtonElement | null)[]>([]);@@ -45,12 +49,19 @@ export function QuestionOptionList({// tabbing past the pager to reach send. Selecting first means tabbing in// and hitting Enter can't submit an option nobody chose — and arrowing or// clicking already selects, so those reach the pager on the first Enter.+ // Space reaches the native button's click the same way, so it only selects,+ // like the arrows do, leaving a pointer click the one thing that advances.if (isKey(event, "Enter")) {event.preventDefault();if (options[index] === value.trim()) onSubmit();else onChange(options[index]);return;}+ if (isKey(event, " ")) {+ event.preventDefault();+ onChange(options[index]);+ return;+ }const step = isKey(event, "ArrowDown", "ArrowRight")? 1: isKey(event, "ArrowUp", "ArrowLeft")@@ -80,7 +91,7 @@ export function QuestionOptionList({role="radio"aria-checked={isSelected}tabIndex={index === active ? 0 : -1}- onClick={() => onChange(option)}+ onClick={() => onPick(option)}onKeyDown={(event) => handleKeyDown(event, index)}className={"flex items-center justify-between gap-2 rounded-2xl px-3 py-2 text-left text-sm leading-relaxed transition-all " +diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionsSection.tsxindex 08fbc16079..6f5680bc91 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionsSection.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionsSection.tsx@@ -18,9 +18,9 @@ interface Props {onProceed: () => void;}-/** One question per step. The footer pager (chevrons + ring dots) moves- * between questions; the round action button advances and, on the last- * step, drafts every answer into the chat input. */+/** One question per step. Picking an option advances on its own; the footer+ * pager (chevrons + ring dots) moves between questions, and the round action+ * button advances and, on the last step, sends every answer as one message. */export function QuestionsSection({ requests, isReady, onProceed }: Props) {const [step, setStep] = useState(0);const sectionId = useId();@@ -49,6 +49,13 @@ export function QuestionsSection({ requests, isReady, onProceed }: Props) {}}+ // A tap on an option is the whole answer, so the pager moves on by itself;+ // the last question keeps the send button as its explicit final step.+ function handlePick(value: string) {+ request.onAnswer(question.keyword, value);+ if (!isLast) setStep(current + 1);+ }+return (<><div className="flex items-center justify-between gap-2.5 border-b border-zinc-100 px-4 py-3">@@ -87,6 +94,7 @@ export function QuestionsSection({ requests, isReady, onProceed }: Props) {labelId={labelId}autoFocus={current > 0}onChange={(value) => request.onAnswer(question.keyword, value)}+ onPick={handlePick}onSubmit={handleAction}/></m.div>@@ -134,7 +142,7 @@ export function QuestionsSection({ requests, isReady, onProceed }: Props) {<buttontype="button"- aria-label={isLast ? "Add answers to message" : "Next question"}+ aria-label={isLast ? "Send answers" : "Next question"}disabled={!actionEnabled}onClick={handleAction}className={diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsxindex 3705b1d07f..a20a8bf83f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx@@ -635,7 +635,7 @@ describe("ChainActionCard", () => {renderCard({ questions: [questionRequest()] });const send = screen.getByRole("button", {- name: "Add answers to message",+ name: "Send answers",}) as HTMLButtonElement;expect(send.disabled).toBe(true);});@@ -645,9 +645,7 @@ describe("ChainActionCard", () => {questions: [questionRequest({ answers: { region: "Europe" } })],});- fireEvent.click(- screen.getByRole("button", { name: "Add answers to message" }),- );+ fireEvent.click(screen.getByRole("button", { name: "Send answers" }));expect(onProceed).toHaveBeenCalledOnce();});@@ -1110,7 +1108,7 @@ describe("ChainActionCard", () => {expect((screen.getByRole("button", {- name: "Add answers to message",+ name: "Send answers",}) as HTMLButtonElement).disabled,).toBe(true);@@ -1131,13 +1129,111 @@ describe("ChainActionCard", () => {);const send = screen.getByRole("button", {- name: "Add answers to message",+ name: "Send answers",}) as HTMLButtonElement;expect(send.disabled).toBe(false);fireEvent.click(send);expect(onProceed).toHaveBeenCalledOnce();});+ it("advances to the next question when an option is clicked", () => {+ const request = questionRequest({+ questions: [+ {+ question: "Which region?",+ keyword: "region",+ options: ["Europe", "Americas"],+ },+ { question: "Which format?", keyword: "format" },+ ],+ });+ renderCard({ questions: [request] });++ fireEvent.click(screen.getByRole("radio", { name: "Europe" }));+ expect(request.onAnswer).toHaveBeenCalledWith("region", "Europe");+ expect(screen.getByText("Which format?")).toBeDefined();+ });++ it("stays on the last question after an option is clicked", () => {+ const request = questionRequest({+ questions: [+ {+ question: "Which region?",+ keyword: "region",+ options: ["Europe", "Americas"],+ },+ ],+ });+ const { onProceed, rerender } = renderCard({ questions: [request] });++ fireEvent.click(screen.getByRole("radio", { name: "Europe" }));+ expect(request.onAnswer).toHaveBeenCalledWith("region", "Europe");+ expect(screen.getByText("Which region?")).toBeDefined();+ expect(onProceed).not.toHaveBeenCalled();++ rerender(+ <ChainActionCard+ connectors={[]}+ mcp={[]}+ inputs={[]}+ questions={[{ ...request, answers: { region: "Europe" } }]}+ manualProceed={false}+ isReady+ onProceed={onProceed}+ />,+ );++ expect(+ (+ screen.getByRole("button", {+ name: "Send answers",+ }) as HTMLButtonElement+ ).disabled,+ ).toBe(false);+ });++ it("does not advance when the arrow keys select an option", () => {+ const request = questionRequest({+ questions: [+ {+ question: "Which region?",+ keyword: "region",+ options: ["Europe", "Americas"],+ },+ { question: "Which format?", keyword: "format" },+ ],+ });+ renderCard({ questions: [request] });++ const europe = screen.getByRole("radio", { name: "Europe" });+ europe.focus();+ fireEvent.keyDown(europe, { key: "ArrowDown" });++ expect(request.onAnswer).toHaveBeenCalledWith("region", "Americas");+ expect(screen.getByText("Which region?")).toBeDefined();+ });++ it("selects without advancing when Space is pressed on an option", () => {+ const request = questionRequest({+ questions: [+ {+ question: "Which region?",+ keyword: "region",+ options: ["Europe", "Americas"],+ },+ { question: "Which format?", keyword: "format" },+ ],+ });+ renderCard({ questions: [request] });++ const europe = screen.getByRole("radio", { name: "Europe" });+ europe.focus();+ fireEvent.keyDown(europe, { key: " " });++ expect(request.onAnswer).toHaveBeenCalledWith("region", "Europe");+ expect(screen.getByText("Which region?")).toBeDefined();+ });+it("keeps two same-keyword questions on their own cards", () => {// Keywords are unique only within a request, so the pager keys on// position — sharing an id would stop the field remounting, leaving the@@ -1179,9 +1275,7 @@ describe("ChainActionCard", () => {isReady: false,});- fireEvent.click(- screen.getByRole("button", { name: "Add answers to message" }),- );+ fireEvent.click(screen.getByRole("button", { name: "Send answers" }));expect(onProceed).toHaveBeenCalledOnce();});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/QuestionAnswerField.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/QuestionAnswerField.test.tsxindex 8bbeab3468..23c6e8b337 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/QuestionAnswerField.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/QuestionAnswerField.test.tsx@@ -11,6 +11,7 @@ function renderField(value = "ねこ") {labelId="label-1"autoFocus={false}onChange={() => {}}+ onPick={() => {}}onSubmit={onSubmit}/>,);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/helpers.tsindex 33ca4cae78..c008ea0eda 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/helpers.ts@@ -43,3 +43,13 @@ export const COMPACT_SEND_BUTTON_CLASS =export const CARD_SEND_BUTTON_CLASS ="size-9 rounded-full border-transparent bg-zinc-950 text-white transition-[background-color,transform] hover:border-transparent hover:bg-zinc-800 active:scale-[0.98] disabled:border-transparent disabled:bg-zinc-950/[0.06] disabled:text-zinc-400";++/** Shared by every path that sends a message. `recovery` is the lowercase+ * clause telling the user where their text went, e.g. "your message is+ * back in the composer". */+export function describeSendFailure(error: unknown, recovery: string) {+ const reason = error instanceof Error ? error.message.trim() : "";+ return reason+ ? `${reason} — ${recovery}.`+ : `${recovery.charAt(0).toUpperCase()}${recovery.slice(1)}. Try again.`;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.tsindex 30d6241188..ea37a24107 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts@@ -1,4 +1,5 @@import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { describeSendFailure } from "./helpers";import { toast } from "@/components/molecules/Toast/use-toast";import { ChangeEvent, FormEvent, useEffect, useRef, useState } from "react";@@ -77,7 +78,10 @@ export function useChatInput({setValue((current) => restoreFailedDraft(current, message));toast({title: "Couldn't send message",- description: describeSendFailure(error),+ description: describeSendFailure(+ error,+ "your message is back in the composer",+ ),variant: "destructive",});} finally {@@ -115,10 +119,3 @@ function restoreFailedDraft(current: string, failed: string) {if (!current.trim() || current === failed) return failed;return `${failed}\n\n${current}`;}--function describeSendFailure(error: unknown) {- const reason = error instanceof Error ? error.message.trim() : "";- return reason- ? `${reason} — your message is back in the composer.`- : "Your message is back in the composer. Try again.";-}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsxindex e26ad3344f..5ad4f307dd 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx@@ -12,15 +12,18 @@ import {} from "@hugeicons/core-free-icons";import type { IconSvgElement } from "@hugeicons/react";import type { ToolUIPart } from "ai";-import { type ReactNode, useState } from "react";+import { type ReactNode, useContext, useState } from "react";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";+import { toast } from "@/components/molecules/Toast/use-toast";import { cn } from "@/lib/utils";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { GenericTool } from "../../tools/GenericTool/GenericTool";import { type ArtifactRef, useCopilotUIStore } from "../../store";+import { describeSendFailure } from "../ChatInput/helpers";+import { CopilotChatActionsContext } from "../CopilotChatActionsProvider/useCopilotChatActions";import { asObject, str } from "./resultHelpers";interface Props {@@ -37,7 +40,8 @@ interface Props {onDecide?: (decision: Decision) => void;/** Takes the decision back so Approve/Decline can be chosen again. */onUndo?: () => void;- /** Footer control the group adds once every proposal is decided. */+ /** Footer control the group adds once every proposal is decided, or+ * the sent note after. */action?: ReactNode;/** Which way the pager just moved — the identity block slides in from* that side while the shell (Details, pager, decision) stays put. */@@ -403,8 +407,9 @@ interface GroupProps {/** One hire/raise per call, so a new team lands as several cards in a* row. They page like the clarifying questions do, one expert at a time:* each Approve/Decline moves to the next, and once every proposal has an- * answer a single send drafts all of them into the composer — the user- * still reads and sends the message themselves. */+ * answer a single send posts all of them as one message — the user no+ * longer reviews it in the composer. A decision can be taken back up to+ * that point. */export function ExpertChangeGroup({parts,isCurrentlyStreaming = false,@@ -413,8 +418,8 @@ export function ExpertChangeGroup({const [step, setStep] = useState(0);const [direction, setDirection] = useState<StepDirection | undefined>();const [decisions, setDecisions] = useState<Record<string, Decision>>({});- const [drafted, setDrafted] = useState(false);- const setInitialPrompt = useCopilotUIStore((s) => s.setInitialPrompt);+ const [sent, setSent] = useState(false);+ const actions = useContext(CopilotChatActionsContext);const visible = parts.filter((part) =>isVisibleExpertPart(part, isCurrentlyStreaming),);@@ -446,20 +451,26 @@ export function ExpertChangeGroup({if (!currentProposal) return;const { [currentProposal.toolCallId]: _, ...rest } = decisions;setDecisions(rest);- // The draft in the composer no longer matches — offer the send again- // once every proposal has an answer.- setDrafted(false);}- function draft() {- setInitialPrompt(- proposals- .map((proposal) =>- decisionLine(proposal, decisions[proposal.toolCallId]),- )- .join("\n"),+ function send() {+ if (!actions) return;+ const message = proposals+ .map((proposal) => decisionLine(proposal, decisions[proposal.toolCallId]))+ .join("\n");+ // The card stays marked sent because the message is already in the+ // thread for Retry — the failure only needs saying.+ void Promise.resolve(actions.onSend(message)).catch((error: unknown) =>+ toast({+ title: "Couldn't send message",+ description: describeSendFailure(+ error,+ "it is still in the thread, use Retry to send it again",+ ),+ variant: "destructive",+ }),);- setDrafted(true);+ setSent(true);}const pager = visible.length > 1 && (@@ -511,25 +522,25 @@ export function ExpertChangeGroup({</div>);- const action =- !readOnly &&- allDecided &&- (drafted ? (- <span className="flex items-center gap-1 text-xs text-zinc-400">- <Icon icon={Tick02Icon} size={14} />- Added to message- </span>- ) : (- <Button- variant="primary"- size="icon"- aria-label="Add decisions to message"- onClick={draft}- className="size-8 p-0"- >- <Icon icon={SentIcon} size={15} />- </Button>- ));+ // While the turn is still streaming another proposal part can land in+ // this group, so the send waits for the stream to settle.+ const canSend = !readOnly && !!actions && allDecided && !isCurrentlyStreaming;+ const action = sent ? (+ <span className="flex items-center gap-1 text-xs text-zinc-400">+ <Icon icon={Tick02Icon} size={14} />+ Sent+ </span>+ ) : canSend ? (+ <Button+ variant="primary"+ size="icon"+ aria-label="Send decisions"+ onClick={send}+ className="size-8 p-0"+ >+ <Icon icon={SentIcon} size={15} />+ </Button>+ ) : null;// The shell (Details, pager, decision buttons) is the same from one// expert to the next, so it stays mounted; only the identity block@@ -541,8 +552,8 @@ export function ExpertChangeGroup({isCurrentlyStreaming={isCurrentlyStreaming}pager={pager || undefined}decision={decisions[part.toolCallId] ?? null}- onDecide={currentProposal ? decide : undefined}- onUndo={currentProposal ? undo : undefined}+ onDecide={currentProposal && !sent ? decide : undefined}+ onUndo={currentProposal && !sent ? undo : undefined}action={action || undefined}stepDirection={direction}/>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsxindex 48db5a050f..d9f3079c5b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx@@ -23,7 +23,8 @@ import {} from "react";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";-import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { toast } from "@/components/molecules/Toast/use-toast";+import { describeSendFailure } from "../ChatInput/helpers";import { useCopilotChatActions } from "../CopilotChatActionsProvider/useCopilotChatActions";import { ChainActionCard } from "../ChainActionCard/ChainActionCard";import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContext";@@ -49,8 +50,8 @@ interface Props {parts: MessagePart[];isStreaming: boolean;/** Public share viewer: the chain renders as the owner saw it, but setup- * cards and the Proceed draft are the owner's work — a reader gets no- * Connect prompt and no write into the composer store. */+ * cards and Proceed are the owner's work — a reader gets no Connect+ * prompt and no way to send a follow-up turn. */readOnly?: boolean;}@@ -60,20 +61,14 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {const reducedMotion = useReducedMotion();const pendingQuestions = useContext(PendingQuestionsContext);- const setInitialPrompt = useCopilotUIStore((s) => s.setInitialPrompt);const { onSend } = useCopilotChatActions();- const sentMessageCount = useCopilotUIStore((s) => s.sentMessageCount);- // Ids drafted by the last Proceed, plus the send count at that moment.- // Proceed only fills the composer, so the cards' onSent callbacks fire- // when the user actually sends — not when the draft is written.- const draftedRef = useRef<{ ids: string[]; sentAt: number } | null>(null);// The ref latches against a double effect run; the state re-renders Proceed.const autoSentRef = useRef(false);const [autoSent, setAutoSent] = useState(false);// Action cards (credential setup, clarifying questions) register here// instead of rendering their own Proceed/Answer buttons — the chain- // renders one Proceed that drafts everything into the chat input at once.+ // renders one Proceed that sends everything as a single message.const [actionEntries, setActionEntries] = useState<ReadonlyMap<string, ChainActionEntry>>(new Map());@@ -97,16 +92,6 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {[register, unregister],);- useEffect(- function notifyDraftedCardsOnSend() {- const drafted = draftedRef.current;- if (!drafted || sentMessageCount <= drafted.sentAt) return;- draftedRef.current = null;- drafted.ids.forEach((id) => actionEntries.get(id)?.onSent?.());- },- [sentMessageCount, actionEntries],- );-const pendingActions = [...actionEntries.values()];const connectorRequests = pendingActions.map((entry) => entry.connectors)@@ -167,7 +152,7 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {.join("\n\n");if (!message) return;pendingActions.forEach((entry) => entry.onSent?.());- void onSend(message);+ sendReply(message);},// eslint-disable-next-line react-hooks/exhaustive-deps -- pendingActions is rebuilt every render; the ref makes this once-per-chain[canAutoSend],@@ -227,11 +212,26 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {// still-running chain has no such ending.const showDone = !isStreaming && !hasError && !windowMode && panelOpen;- // Proceed never sends: it drafts the combined reply of every READY card- // into the chat input so the user reviews/edits and presses send- // themselves. Unready cards (e.g. an unconnected MCP server) are left- // out instead of blocking the ready ones. Cards stay registered until- // the message actually goes out, at which point their onSent fires.+ // The cards are already gone by the time a send can fail — the user's+ // message is appended optimistically and the chat's error banner offers+ // Retry — so the failure only needs to be said out loud, and the toast+ // points at the thread rather than the composer.+ function sendReply(message: string) {+ void Promise.resolve(onSend(message)).catch((error: unknown) =>+ toast({+ title: "Couldn't send message",+ description: describeSendFailure(+ error,+ "it is still in the thread, use Retry to send it again",+ ),+ variant: "destructive",+ }),+ );+ }++ // Proceed sends the combined reply of every READY card as one message,+ // and their onSent callbacks fire at that moment. Unready cards (e.g. an+ // unconnected MCP server) are left out instead of blocking the ready ones.function handleProceed() {const readyActions = pendingActions.filter((entry) => entry.ready);const message = readyActions@@ -239,11 +239,8 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {.filter(Boolean).join("\n\n");if (!message) return;- draftedRef.current = {- ids: readyActions.map((entry) => entry.id),- sentAt: sentMessageCount,- };- setInitialPrompt(message);+ readyActions.forEach((entry) => entry.onSent?.());+ sendReply(message);}return (@@ -410,8 +407,8 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {<span className="flex items-center gap-1.5 text-sm text-zinc-600"><Icon icon={SentIcon} size={16} className="text-zinc-400" />{allActionsReady- ? "Everything's filled in — send it to continue"- : "Complete the steps above, then send to continue"}+ ? "Everything's filled in"+ : "Complete the steps above to continue"}</span><Buttonvariant="primary"diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ExpertCards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ExpertCards.test.tsxindex 2bb0ef4960..526c201374 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ExpertCards.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ExpertCards.test.tsx@@ -1,8 +1,15 @@-import { cleanup, render, screen } from "@/tests/integrations/test-utils";+import {+ cleanup,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";import userEvent from "@testing-library/user-event";import type { ToolUIPart } from "ai";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { toast } from "@/components/molecules/Toast/use-toast";import { useCopilotUIStore } from "../../../store";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";import {ExpertChangeCard,ExpertChangeGroup,@@ -11,10 +18,17 @@ import {import type { ChainRow } from "../helpers";import { ToolResult } from "../ToolResult";+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: vi.fn(),+ useToast: () => ({ toast: vi.fn(), dismiss: vi.fn() }),+}));+vi.mock("../../../tools/GenericTool/GenericTool", () => ({GenericTool: () => <div data-testid="generic-tool" />,}));+const onSend = vi.fn();+const artifactsFlag = { enabled: false };vi.mock("@/services/feature-flags/use-get-flag", () => ({Flag: { ARTIFACTS: "artifacts" },@@ -36,7 +50,6 @@ describe("expert change cards", () => {afterEach(() => {artifactsFlag.enabled = false;useCopilotUIStore.getState().resetArtifactPanel();- useCopilotUIStore.getState().setInitialPrompt(null);});it("shows who the proposed expert is and nothing else", () => {@@ -391,22 +404,28 @@ describe("ExpertChangeGroup", () => {});describe("expert approval", () => {- function prompt(): string | null {- return useCopilotUIStore.getState().initialPrompt;+ beforeEach(() => {+ onSend.mockClear();+ vi.mocked(toast).mockClear();+ });++ function renderGroup(+ parts: ToolUIPart[],+ props?: { isCurrentlyStreaming?: boolean; readOnly?: boolean },+ ) {+ return render(+ <CopilotChatActionsProvider onSend={onSend}>+ <ExpertChangeGroup parts={parts} {...props} />+ </CopilotChatActionsProvider>,+ );}- it("moves to the next expert on each decision, then drafts all of them", async () => {+ it("moves to the next expert on each decision, then sends all of them", async () => {const user = userEvent.setup();- render(- <ExpertChangeGroup- parts={[proposal("Fiona", "a"), proposal("Bhaskar", "b")]}- />,- );+ renderGroup([proposal("Fiona", "a"), proposal("Bhaskar", "b")]);expect(screen.getByText("Fiona")).toBeDefined();- expect(- screen.queryByRole("button", { name: "Add decisions to message" }),- ).toBeNull();+ expect(screen.queryByRole("button", { name: "Send decisions" })).toBeNull();await user.click(screen.getByRole("button", { name: "Approve" }));expect(screen.getByText("Bhaskar")).toBeDefined();@@ -422,24 +441,52 @@ describe("expert approval", () => {).toContain("red");expect(screen.queryByRole("button", { name: "Approve" })).toBeNull();- await user.click(- screen.getByRole("button", { name: "Add decisions to message" }),+ await user.click(screen.getByRole("button", { name: "Send decisions" }));+ expect(onSend).toHaveBeenCalledTimes(1);+ expect(onSend).toHaveBeenCalledWith(+ "Approved: create Fiona (confirmation_id: c-a).\n" ++ "Not approved: do not create Bhaskar, discard that proposal (confirmation_id: c-b).",);- expect(prompt()).toContain("Approved: create Fiona");- expect(prompt()).toContain("c-a");- expect(prompt()).toContain("Not approved: do not create Bhaskar");- expect(prompt()).toContain("c-b");- expect(screen.getByText("Added to message")).toBeDefined();+ expect(screen.getByText("Sent")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Undo decline" })).toBeNull();});- it("remembers a decision when paging back", async () => {+ it("holds the send until the stream has settled", async () => {const user = userEvent.setup();- render(- <ExpertChangeGroup- parts={[proposal("Fiona", "a"), proposal("Bhaskar", "b")]}- />,+ const { rerender } = renderGroup([proposal("Otto", "a")], {+ isCurrentlyStreaming: true,+ });++ await user.click(screen.getByRole("button", { name: "Approve" }));+ expect(screen.queryByRole("button", { name: "Send decisions" })).toBeNull();++ rerender(+ <CopilotChatActionsProvider onSend={onSend}>+ <ExpertChangeGroup+ parts={[proposal("Otto", "a")]}+ isCurrentlyStreaming={false}+ />+ </CopilotChatActionsProvider>,);+ expect(+ screen.getByRole("button", { name: "Send decisions" }),+ ).toBeDefined();+ });++ it("offers no send without a chat actions provider", async () => {+ const user = userEvent.setup();+ render(<ExpertChangeGroup parts={[proposal("Otto", "a")]} />);++ await user.click(screen.getByRole("button", { name: "Approve" }));++ expect(screen.queryByRole("button", { name: "Send decisions" })).toBeNull();+ });++ it("remembers a decision when paging back", async () => {+ const user = userEvent.setup();+ renderGroup([proposal("Fiona", "a"), proposal("Bhaskar", "b")]);+await user.click(screen.getByRole("button", { name: "Approve" }));await user.click(screen.getByRole("button", { name: "Previous expert" }));@@ -453,43 +500,60 @@ describe("expert approval", () => {).not.toContain("emerald");});- it("drafts a single expert straight after its decision", async () => {+ it("sends a single expert straight after its decision", async () => {const user = userEvent.setup();- render(<ExpertChangeGroup parts={[proposal("Otto", "a")]} />);+ renderGroup([proposal("Otto", "a")]);await user.click(screen.getByRole("button", { name: "Approve" }));- await user.click(- screen.getByRole("button", { name: "Add decisions to message" }),- );+ await user.click(screen.getByRole("button", { name: "Send decisions" }));- expect(prompt()).toBe("Approved: create Otto (confirmation_id: c-a).");+ expect(onSend).toHaveBeenCalledWith(+ "Approved: create Otto (confirmation_id: c-a).",+ );});- it("drafts the verb the proposal actually asks for", async () => {+ it("reports a rejected send and keeps the card marked sent", async () => {const user = userEvent.setup();- render(- <ExpertChangeGroup- parts={[- expertPart(- "output-available",- {- type: "expert_change_proposed",- applied: false,- confirmation_id: "c-u",- preview: { kind: "update", name: "Otto", role: "Engineer" },- },- "u",- ),- ]}- />,- );+ onSend.mockRejectedValueOnce(new Error("boom"));+ renderGroup([proposal("Otto", "a")]);await user.click(screen.getByRole("button", { name: "Approve" }));- await user.click(- screen.getByRole("button", { name: "Add decisions to message" }),+ await user.click(screen.getByRole("button", { name: "Send decisions" }));++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Couldn't send message",+ description:+ "boom — it is still in the thread, use Retry to send it again.",+ variant: "destructive",+ }),+ ),);+ expect(screen.getByText("Sent")).toBeDefined();+ });- expect(prompt()).toBe("Approved: update Otto (confirmation_id: c-u).");+ it("sends the verb the proposal actually asks for", async () => {+ const user = userEvent.setup();+ renderGroup([+ expertPart(+ "output-available",+ {+ type: "expert_change_proposed",+ applied: false,+ confirmation_id: "c-u",+ preview: { kind: "update", name: "Otto", role: "Engineer" },+ },+ "u",+ ),+ ]);++ await user.click(screen.getByRole("button", { name: "Approve" }));+ await user.click(screen.getByRole("button", { name: "Send decisions" }));++ expect(onSend).toHaveBeenCalledWith(+ "Approved: update Otto (confirmation_id: c-u).",+ );});it("offers no decision once applied or on a read-only transcript", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsxindex cae092a080..7dac20f909 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx@@ -1,11 +1,11 @@import userEvent from "@testing-library/user-event";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {- act,- cleanup,render as baseRender,screen,+ waitFor,} from "@/tests/integrations/test-utils";+import { toast } from "@/components/molecules/Toast/use-toast";import { useCopilotUIStore } from "@/app/(platform)/copilot/store";import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";import type { MessagePart } from "../../ChatMessagesContainer/helpers";@@ -13,6 +13,11 @@ import type { PendingQuestions } from "../../QuestionDock/helpers";import { PendingQuestionsContext } from "../../QuestionDock/PendingQuestionsContext";import { ToolChain } from "../ToolChain";+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: vi.fn(),+ useToast: () => ({ toast: vi.fn(), dismiss: vi.fn() }),+}));+vi.mock("../../SetupRequirementsCard/SetupRequirementsCard", async () => {const { useContext, useEffect } = await import("react");const { ChainActionsContext } = await import("../chainActions");@@ -85,9 +90,15 @@ function getRowToggle(name: RegExp): HTMLElement {}describe("ToolChain", () => {+ beforeEach(() => {+ onSend.mockClear();+ vi.mocked(toast).mockClear();+ });+afterEach(() => {- cleanup();- useCopilotUIStore.setState({ initialPrompt: null, sentMessageCount: 0 });+ useCopilotUIStore.setState((state) => ({+ artifactPanel: { ...state.artifactPanel, isOpen: false },+ }));});it("renders nothing when no parts map to chain rows", () => {@@ -243,10 +254,9 @@ describe("ToolChain", () => {it("auto-expands browser rows while the artifact panel is open", async () => {const user = userEvent.setup();- const { artifactPanel } = useCopilotUIStore.getState();- useCopilotUIStore.setState({- artifactPanel: { ...artifactPanel, isOpen: true },- });+ useCopilotUIStore.setState((state) => ({+ artifactPanel: { ...state.artifactPanel, isOpen: true },+ }));render(<ToolChain@@ -266,10 +276,6 @@ describe("ToolChain", () => {name: /opened "https:\/\/agpt.co"/i,});expect(row.getAttribute("aria-expanded")).toBe("true");-- useCopilotUIStore.setState({- artifactPanel: { ...artifactPanel, isOpen: false },- });});it("surfaces the latest error in the heading and drops the Done step", async () => {@@ -344,7 +350,7 @@ describe("ToolChain", () => {).toBe("true");});- it("drafts answered questions into the chat input and dismisses on send", async () => {+ it("sends answered questions and dismisses the card", async () => {const user = userEvent.setup();const pending: PendingQuestions = {dockId: "m1:call-ask_question",@@ -355,7 +361,7 @@ describe("ToolChain", () => {};render(- <CopilotChatActionsProvider onSend={vi.fn()}>+ <CopilotChatActionsProvider onSend={onSend}><PendingQuestionsContext.Provider value={pending}><ToolChainparts={[@@ -375,9 +381,7 @@ describe("ToolChain", () => {expect(screen.getByText("Answer a few questions")).toBeDefined();expect(screen.getByText("Which region?")).toBeDefined();- const submit = screen.getByRole("button", {- name: "Add answers to message",- });+ const submit = screen.getByRole("button", { name: "Send answers" });expect(submit.hasAttribute("disabled")).toBe(true);await user.type(@@ -388,12 +392,58 @@ describe("ToolChain", () => {await user.click(submit);- expect(useCopilotUIStore.getState().initialPrompt).toBe(+ expect(onSend).toHaveBeenCalledTimes(1);+ expect(onSend).toHaveBeenCalledWith("**Here are my answers:**\n\n> Which region?\n\nWestern Europe\n\nPlease proceed.",);+ expect(screen.queryByText("Answer a few questions")).toBeNull();+ });++ it("reports a rejected send without bringing the card back", async () => {+ const user = userEvent.setup();+ onSend.mockRejectedValueOnce(new Error("boom"));+ const pending: PendingQuestions = {+ dockId: "m1:call-ask_question",+ callIds: ["call-ask_question"],+ questions: [+ { question: "Which region?", keyword: "region", example: "Europe" },+ ],+ };- act(() => useCopilotUIStore.getState().notifyMessageSent());+ render(+ <CopilotChatActionsProvider onSend={onSend}>+ <PendingQuestionsContext.Provider value={pending}>+ <ToolChain+ parts={[+ toolPart("ask_question", "output-available", {+ output: {+ type: "agent_builder_clarification_needed",+ questions: pending.questions,+ },+ }),+ ]}+ isStreaming={false}+ />+ </PendingQuestionsContext.Provider>+ </CopilotChatActionsProvider>,+ );+ await user.type(+ screen.getByPlaceholderText("e.g. Europe"),+ "Western Europe",+ );+ await user.click(screen.getByRole("button", { name: "Send answers" }));++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Couldn't send message",+ description:+ "boom — it is still in the thread, use Retry to send it again.",+ variant: "destructive",+ }),+ ),+ );expect(screen.queryByText("Answer a few questions")).toBeNull();});@@ -414,18 +464,14 @@ describe("ToolChain", () => {);expect(screen.getByText("setup-card-GitHub")).toBeDefined();- expect(- screen.getByText("Everything's filled in — send it to continue"),- ).toBeDefined();+ expect(screen.getByText("Everything's filled in")).toBeDefined();const proceed = screen.getByRole("button", { name: "Proceed" });expect(proceed.hasAttribute("disabled")).toBe(false);await user.click(proceed);- expect(useCopilotUIStore.getState().initialPrompt).toBe(- "Connected GitHub. Please continue.",- );+ expect(onSend).toHaveBeenCalledWith("Connected GitHub. Please continue.");});it("disables Proceed until every registered card is ready", () => {@@ -444,15 +490,15 @@ describe("ToolChain", () => {);expect(- screen.getByText("Complete the steps above, then send to continue"),+ screen.getByText("Complete the steps above to continue"),).toBeDefined();expect(screen.getByRole("button", { name: "Proceed" }).hasAttribute("disabled"),).toBe(true);- expect(useCopilotUIStore.getState().initialPrompt).toBeNull();+ expect(onSend).not.toHaveBeenCalled();});- it("does not draft anything when ready cards produce no message", async () => {+ it("sends nothing when ready cards produce no message", async () => {const user = userEvent.setup();render(<ToolChain@@ -470,15 +516,17 @@ describe("ToolChain", () => {await user.click(screen.getByRole("button", { name: "Proceed" }));- expect(useCopilotUIStore.getState().initialPrompt).toBeNull();+ expect(onSend).not.toHaveBeenCalled();});});// ToolChain sends the chain's follow-up turn itself, so it needs the actions// provider its production parents always supply.+const onSend = vi.fn();+function render(ui: React.ReactElement) {const { rerender, ...rest } = baseRender(- <CopilotChatActionsProvider onSend={vi.fn()}>+ <CopilotChatActionsProvider onSend={onSend}>{ui}</CopilotChatActionsProvider>,);@@ -486,7 +534,7 @@ function render(ui: React.ReactElement) {...rest,rerender: (next: React.ReactElement) =>rerender(- <CopilotChatActionsProvider onSend={vi.fn()}>+ <CopilotChatActionsProvider onSend={onSend}>{next}</CopilotChatActionsProvider>,),