Skip to content

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

feat(frontend/copilot): connect every provider a tool needs, then proceed once (#14332)

Reinier van der Leer2860d725a881
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.tsx
index 89efebc281..e72df99e46 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
@@ -57,6 +57,12 @@ export function ChainActionCard({
(request, i) =>
mcp.findIndex((other) => other.serverUrl === request.serverUrl) === i,
);
+ // Everything the chain is still waiting on, so a half-connected card says
+ // what is left instead of looking stalled.
+ const remaining = [
+ ...rows.filter((row) => !row.selected).map((row) => row.displayName),
+ ...mcpRows.filter((request) => !request.connected).map((r) => r.service),
+ ];
const hasInputs = inputs.some(
(request) => request.schema !== null || request.hasAdvanced,
);
@@ -91,6 +97,13 @@ export function ChainActionCard({
{mcpRows.map((request) => (
<McpConnectorRow key={request.id} request={request} />
))}
+ {remaining.length > 0 && rows.length + mcpRows.length > 1 && (
+ <div className="border-t border-zinc-100 px-4 py-2.5">
+ <span className="text-sm text-zinc-500">
+ Still to connect: {remaining.join(", ")}
+ </span>
+ </div>
+ )}
<div className="border-t border-zinc-100 px-4 py-3">
<span className="text-sm text-zinc-500">
Looking for something else?{" "}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx
index 40b4f0b91a..7992e8c7f9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx
@@ -35,6 +35,9 @@ export function QuestionsForm({ dockId, questions }: FormProps) {
chainActions.register({
id: dockId,
ready: allAnswered,
+ // Answers are ready on the first character of the last one; the user
+ // reviews them through the dock's own action, not an automatic send.
+ manualProceed: true,
buildMessage: () =>
allAnswered ? buildAnswersMessage(questions, answers) : null,
onSent: () => setDismissedId(dockId),
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
index adf31e03b4..e71bc2302d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
@@ -148,9 +148,11 @@ export function SetupRequirementsCard({
const requestedProviders = getRequestedProviders(credentialFields);
const alreadyConnected = useAreAllConnected(sessionID, requestedProviders);
const hasUserActionableInputs = isEditMode && needsInputs;
+ // Neither auto path may send these; the chain gives them a Proceed instead.
// A trigger card's message carries the account its webhook registers under,
- // which the backend requires the user to have picked — so neither auto path
- // may send it, and the chain gives it a Proceed instead.
+ // which the backend requires the user to have picked. A card with editable
+ // inputs reports ready on the first typed character, so sending on readiness
+ // would fire mid-word with a half-typed value.
const needsManualPick = isTriggerMode;
const canAutoDismiss =
needsCredentials &&
@@ -162,13 +164,9 @@ export function SetupRequirementsCard({
// signal; without this the chain stalls after the user connects. It must be
// the sign-in and not merely a satisfied credential: every card in the chat
// history re-mounts on load with its credential already in place.
- const canAutoProceed =
- Boolean(chainActions) &&
- justConnected &&
- isAllCredsComplete &&
- !hasUserActionableInputs &&
- !needsManualPick;
-
+ // Standalone only: inside a chain the chain owns sending, so it can wait for
+ // every card's rows before the single follow-up turn goes out.
+ //
// Auto-send when dismissing so the AI receives the run message and the
// chat doesn't hang waiting for a confirmation that the user can no longer
// provide (the Proceed button is hidden behind the early return below).
@@ -183,7 +181,7 @@ export function SetupRequirementsCard({
// (cleanup cancels the first microtask, but the claim is still held, so
// the second effect run can't re-claim and the send never fires).
useEffect(() => {
- if ((!canAutoDismiss && !canAutoProceed) || hasSent) return;
+ if (chainActions || !canAutoDismiss || hasSent) return;
if (!sessionID || requestedProviders.length === 0) return;
const claimed = useConnectedProvidersStore
.getState()
@@ -194,7 +192,7 @@ export function SetupRequirementsCard({
}
handleRun();
// eslint-disable-next-line react-hooks/exhaustive-deps -- handleRun captures latest state; claim guards re-entry
- }, [canAutoDismiss, canAutoProceed, hasSent]);
+ }, [chainActions, canAutoDismiss, hasSent]);
const canRun = checkCanRun(
needsCredentials,
@@ -205,12 +203,13 @@ export function SetupRequirementsCard({
// Inside a tool chain the card's own Proceed is replaced by the chain's
// single Proceed step — register readiness + message with the chain.
useEffect(() => {
- if (!chainActions || hasSent || canAutoDismiss || canAutoProceed) return;
+ if (!chainActions || hasSent) return;
if (!needsCredentials && !needsInputs) return;
chainActions.register({
id: actionId,
ready: canRun,
- manualProceed: needsManualPick,
+ manualProceed: needsManualPick || hasUserActionableInputs,
+ justConnected,
buildMessage: () => buildProceedMessage(),
onSent: markSent,
connectors: needsCredentials
@@ -242,8 +241,7 @@ export function SetupRequirementsCard({
}, [
chainActions,
hasSent,
- canAutoDismiss,
- canAutoProceed,
+ justConnected,
canRun,
actionId,
needsCredentials,
@@ -254,7 +252,7 @@ export function SetupRequirementsCard({
showAdvanced,
]);
- if (hasSent || canAutoDismiss || canAutoProceed) {
+ if (hasSent || (!chainActions && canAutoDismiss)) {
return <ContentMessage>Connected. Continuing…</ContentMessage>;
}
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.tsx
index 4313fcb69a..a87274dd56 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
@@ -24,6 +24,7 @@ import {
import { Button } from "@/components/atoms/Button/Button";
import { Icon } from "@/components/atoms/Icon/Icon";
import { useCopilotUIStore } from "@/app/(platform)/copilot/store";
+import { useCopilotChatActions } from "../CopilotChatActionsProvider/useCopilotChatActions";
import { ChainActionCard } from "../ChainActionCard/ChainActionCard";
import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContext";
import type { MessagePart } from "../ChatMessagesContainer/helpers";
@@ -34,6 +35,7 @@ import {
type ChainRow,
getChainHeading,
isLiftedSetupRow,
+ isToolCallPending,
markSupersededSubSessionRows,
toChainRow,
} from "./helpers";
@@ -58,11 +60,15 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {
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
@@ -100,6 +106,72 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {
[sentMessageCount, actionEntries],
);
+ const pendingActions = [...actionEntries.values()];
+ const connectorRequests = pendingActions
+ .map((entry) => entry.connectors)
+ .filter((request) => request !== undefined);
+ const mcpRequests = pendingActions
+ .map((entry) => entry.mcp)
+ .filter((request) => request !== undefined);
+ const inputRequests = pendingActions
+ .map((entry) => entry.inputs)
+ .filter((request) => request !== undefined);
+ const questionRequests = pendingActions
+ .map((entry) => entry.questions)
+ .filter((request) => request !== undefined);
+ const needsManualProceed = pendingActions.some(
+ (entry) => entry.manualProceed,
+ );
+ const hasCardWork =
+ connectorRequests.length > 0 ||
+ mcpRequests.length > 0 ||
+ inputRequests.length > 0 ||
+ questionRequests.length > 0;
+ const allActionsReady =
+ pendingActions.length > 0 && pendingActions.every((entry) => entry.ready);
+ // One tool can need several accounts. The turn goes out once, when every
+ // card in the chain is satisfied — otherwise connecting the first provider
+ // sends while the rest of the rows are still visibly unconnected.
+ const justConnectedHere = pendingActions.some((entry) => entry.justConnected);
+ // A tool still awaiting its result may yet add a card to this chain, and the
+ // send is once-only — spending it now leaves that card unsendable. A stopped
+ // stream owes no more results, however its calls ended.
+ const awaitingToolResult = isStreaming && parts.some(isToolCallPending);
+ const canAutoSend =
+ !readOnly &&
+ !awaitingToolResult &&
+ !autoSent &&
+ allActionsReady &&
+ !needsManualProceed &&
+ justConnectedHere;
+ // Nothing to sign in to and nothing to fill in: without a button this card
+ // has no way forward at all — a card that lands after the send is spent
+ // included. Only asks that build a message qualify — an MCP row builds none,
+ // so offering one there is a button that does nothing.
+ const offerProceed =
+ !readOnly &&
+ !awaitingToolResult &&
+ !canAutoSend &&
+ allActionsReady &&
+ (connectorRequests.length > 0 || inputRequests.length > 0);
+
+ useEffect(
+ function sendOnceEveryCardIsSatisfied() {
+ if (!canAutoSend || autoSentRef.current) return;
+ autoSentRef.current = true;
+ setAutoSent(true);
+ const message = pendingActions
+ .map((entry) => entry.buildMessage())
+ .filter(Boolean)
+ .join("\n\n");
+ if (!message) return;
+ pendingActions.forEach((entry) => entry.onSent?.());
+ void onSend(message);
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- pendingActions is rebuilt every render; the ref makes this once-per-chain
+ [canAutoSend],
+ );
+
const rows = useMemo(
() =>
markSupersededSubSessionRows(
@@ -152,28 +224,6 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {
// still-running chain has no such ending.
const showDone = !isStreaming && !hasError && !windowMode && panelOpen;
- const pendingActions = [...actionEntries.values()];
- const connectorRequests = pendingActions
- .map((entry) => entry.connectors)
- .filter((request) => request !== undefined);
- const mcpRequests = pendingActions
- .map((entry) => entry.mcp)
- .filter((request) => request !== undefined);
- const inputRequests = pendingActions
- .map((entry) => entry.inputs)
- .filter((request) => request !== undefined);
- const questionRequests = pendingActions
- .map((entry) => entry.questions)
- .filter((request) => request !== undefined);
- const manualProceed = pendingActions.some((entry) => entry.manualProceed);
- const hasCardWork =
- connectorRequests.length > 0 ||
- mcpRequests.length > 0 ||
- inputRequests.length > 0 ||
- questionRequests.length > 0;
- const allActionsReady =
- pendingActions.length > 0 && pendingActions.every((entry) => entry.ready);
-
// 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
@@ -344,7 +394,7 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {
mcp={mcpRequests}
inputs={inputRequests}
questions={questionRequests}
- manualProceed={manualProceed}
+ manualProceed={needsManualProceed || offerProceed}
isReady={allActionsReady}
onProceed={handleProceed}
/>
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.tsx
index 9286b07ac2..bc7ff09b0c 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,6 +1,11 @@
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { act, cleanup, render, screen } from "@/tests/integrations/test-utils";
+import {
+ act,
+ cleanup,
+ render as baseRender,
+ screen,
+} from "@/tests/integrations/test-utils";
import { useCopilotUIStore } from "@/app/(platform)/copilot/store";
import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";
import type { MessagePart } from "../../ChatMessagesContainer/helpers";
@@ -448,3 +453,22 @@ describe("ToolChain", () => {
expect(useCopilotUIStore.getState().initialPrompt).toBeNull();
});
});
+
+// ToolChain sends the chain's follow-up turn itself, so it needs the actions
+// provider its production parents always supply.
+function render(ui: React.ReactElement) {
+ const { rerender, ...rest } = baseRender(
+ <CopilotChatActionsProvider onSend={vi.fn()}>
+ {ui}
+ </CopilotChatActionsProvider>,
+ );
+ return {
+ ...rest,
+ rerender: (next: React.ReactElement) =>
+ rerender(
+ <CopilotChatActionsProvider onSend={vi.fn()}>
+ {next}
+ </CopilotChatActionsProvider>,
+ ),
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/connect-card-flow.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/connect-card-flow.test.tsx
index f6d101cddf..edbafc7c8c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/connect-card-flow.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/connect-card-flow.test.tsx
@@ -29,6 +29,8 @@ import { useConnectedProvidersStore } from "@/app/(platform)/copilot/connectedPr
import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";
import type { MessagePart } from "../../ChatMessagesContainer/helpers";
import { ToolChain } from "../ToolChain";
+import { PendingQuestionsContext } from "../../QuestionDock/PendingQuestionsContext";
+import type { PendingQuestions } from "../../QuestionDock/helpers";
// CredentialsProvider only fetches for a signed-in user; the shared setup
// signs everyone out.
@@ -248,6 +250,54 @@ describe("copilot Connect card, cards that owe more than a credential", () => {
expect(onSend).not.toHaveBeenCalled();
});
+ it("offers no Proceed for a connected MCP row, which builds no message", async () => {
+ savedCredentials = [
+ {
+ id: "cred-mcp",
+ provider: "mcp",
+ type: "oauth2",
+ title: "Notion",
+ host: "https://mcp.notion.com/mcp",
+ scopes: [],
+ },
+ ];
+ const onSend = vi.fn();
+ render(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain parts={[mcpPart()]} isStreaming={false} />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+
+ await screen.findByText("Plug in what this needs");
+ // The MCP entry's buildMessage returns null, so a Proceed here would draft
+ // an empty message and do nothing at all.
+ expect(screen.queryByRole("button", { name: "Proceed" })).toBeNull();
+ });
+
+ it("gives a Proceed to a card whose rows an earlier card already satisfied", async () => {
+ // connect_integration returns a card whether or not the user is already
+ // connected, so this lands whenever the assistant offers a provider they
+ // have. There is no sign-in to trigger the send and nothing to click.
+ savedCredentials = [oauthCredential("cred-existing", [REQUIRED_SCOPE])];
+ useConnectedProvidersStore
+ .getState()
+ .markConnected({ sessionID: SESSION_ID, providers: ["github"] });
+
+ const onSend = vi.fn();
+ render(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain parts={[setupRequirementsPart()]} isStreaming={false} />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+
+ await screen.findByRole("button", { name: "Proceed" });
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
it("gives a trigger card a Proceed when a sibling already connected its provider", async () => {
// The auto-dismiss path fires before any account is selected and sends
// `credentials={}`; the backend then re-issues the card, the re-issued one
@@ -524,6 +574,204 @@ describe("copilot Connect card, already satisfied", () => {
});
});
+describe("copilot Connect card, one tool needing several providers", () => {
+ beforeEach(mockTwoProviderBackend);
+
+ afterEach(resetStores);
+
+ it("sends once, after the second provider is connected", async () => {
+ const { onSend } = renderTwoProviderChain();
+
+ await connectRemainingProvider();
+ // The first account alone must not start the turn: the other row is still
+ // visibly unconnected, and the tool needs both.
+ await waitFor(() => expect(savedCredentials).toHaveLength(1));
+ expect(onSend).not.toHaveBeenCalled();
+
+ await connectRemainingProvider();
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ expect(onSend.mock.calls[0][0]).toContain(
+ "I've configured the required credentials.",
+ );
+ });
+
+ it("sends once whichever provider the user connects first", async () => {
+ const { onSend } = renderTwoProviderChain();
+
+ // Same assertion from the other end: the order is the user's, the single
+ // turn is not.
+ const buttons = screen.getAllByRole("button", { name: "Connect" });
+ await connectRemainingProvider(buttons.length - 1);
+ expect(onSend).not.toHaveBeenCalled();
+
+ await connectRemainingProvider();
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ });
+
+ it("does not send when the user starts typing an input", async () => {
+ const onSend = vi.fn();
+ render(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain parts={[partWithInputs()]} isStreaming={false} />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+
+ await connectRemainingProvider();
+ const user = userEvent.setup();
+ await user.type(await screen.findByRole("textbox"), "h");
+
+ // An input counts as complete on any non-empty value, so readiness alone
+ // would fire the turn mid-word with `{"url":"h"}`.
+ await waitFor(() =>
+ expect((screen.getByRole("textbox") as HTMLInputElement).value).toBe("h"),
+ );
+ expect(onSend).not.toHaveBeenCalled();
+ await screen.findByRole("button", { name: "Proceed" });
+ });
+
+ it("does not send when the user starts typing a clarifying answer", async () => {
+ const pending: PendingQuestions = {
+ dockId: "m1:call-ask_question",
+ callIds: ["call-ask_question"],
+ questions: [{ question: "Which region?", keyword: "region" }],
+ };
+ const onSend = vi.fn();
+ render(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <PendingQuestionsContext.Provider value={pending}>
+ <ToolChain
+ parts={[setupRequirementsPart(), questionPart(pending.questions)]}
+ isStreaming={false}
+ />
+ </PendingQuestionsContext.Provider>
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+
+ await completeConnectFlow();
+ const user = userEvent.setup();
+ await user.type(await screen.findByRole("textbox"), "W");
+
+ // Answers are complete on the first character too, and the dock's own
+ // "add answers" review step would never run.
+ await waitFor(() =>
+ expect((screen.getByRole("textbox") as HTMLInputElement).value).toBe("W"),
+ );
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it("offers one Proceed when a card also collects inputs", async () => {
+ const onSend = vi.fn();
+ render(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain
+ parts={[partWithInputs(), slackRequirementsPart()]}
+ isStreaming={false}
+ />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+
+ await connectRemainingProvider();
+ await connectRemainingProvider();
+
+ // Connecting every account does not finish a chain that also owes inputs;
+ // the user completes it through the chain's single Proceed.
+ await screen.findByRole("button", { name: "Proceed" });
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it("stays silent and names what is left when the user connects one and stops", async () => {
+ const { onSend } = renderTwoProviderChain();
+
+ await connectRemainingProvider();
+
+ await screen.findByText(/Still to connect:/);
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(onSend).not.toHaveBeenCalled();
+ });
+});
+
+describe("copilot Connect card, a card that arrives after the first connection", () => {
+ beforeEach(mockTwoProviderBackend);
+
+ afterEach(resetStores);
+
+ it("waits for a tool that is still running, then sends once", async () => {
+ const onSend = vi.fn();
+ const { rerender } = render(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain
+ parts={[setupRequirementsPart(), pendingSlackCallPart()]}
+ isStreaming={true}
+ />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+
+ await connectRemainingProvider();
+
+ // The running tool has not said what it needs yet, so sending here spends
+ // the chain's one turn before that card exists.
+ await screen.findByText("Connected");
+ expect(onSend).not.toHaveBeenCalled();
+
+ rerender(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain
+ parts={[setupRequirementsPart(), slackRequirementsPart()]}
+ isStreaming={false}
+ />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+ await connectRemainingProvider();
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ expect(onSend.mock.calls[0][0]).toContain(
+ "I've configured the required credentials.",
+ );
+ });
+
+ it("gives a card that lands after the send a Proceed to continue from", async () => {
+ const onSend = vi.fn();
+ const { rerender } = render(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain parts={[setupRequirementsPart()]} isStreaming={true} />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+ await connectRemainingProvider();
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+
+ rerender(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain
+ parts={[setupRequirementsPart(), slackRequirementsPart()]}
+ isStreaming={true}
+ />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+ await connectRemainingProvider();
+
+ // The chain's single send is spent, so without a button this card is
+ // connected with nothing to press.
+ await screen.findByRole("button", { name: "Proceed" });
+ expect(onSend).toHaveBeenCalledTimes(1);
+ });
+});
+
function renderChain() {
const onSend = vi.fn();
const utils = render(
@@ -668,6 +916,60 @@ function triggerPart(): MessagePart {
toolCallId: "call-setup_agent_webhook_trigger",
} as unknown as MessagePart;
}
+function renderTwoProviderChain() {
+ const onSend = vi.fn();
+ const utils = render(
+ <CredentialsProvider>
+ <CopilotChatActionsProvider onSend={onSend}>
+ <ToolChain
+ parts={[setupRequirementsPart(), slackRequirementsPart()]}
+ isStreaming={false}
+ />
+ </CopilotChatActionsProvider>
+ </CredentialsProvider>,
+ );
+ return { onSend, ...utils };
+}
+
+/** Connects one row by position. The list shrinks as rows resolve, so index 0
+ * is "the next one still unconnected". */
+async function connectRemainingProvider(index = 0) {
+ const user = userEvent.setup();
+ const buttons = await screen.findAllByRole("button", { name: "Connect" });
+ await user.click(buttons[index]);
+ await user.click(await screen.findByText("OAuth"));
+ await user.click(await screen.findByRole("button", { name: "Continue" }));
+}
+
+function questionPart(questions: PendingQuestions["questions"]): MessagePart {
+ return {
+ type: "tool-ask_question",
+ toolCallId: "call-ask_question",
+ state: "output-available",
+ input: {},
+ output: { type: "agent_builder_clarification_needed", questions },
+ } as unknown as MessagePart;
+}
+function mcpPart(): MessagePart {
+ return {
+ type: "tool-run_mcp_tool",
+ toolCallId: "call-run_mcp_tool",
+ state: "output-available",
+ input: { server_url: "https://mcp.notion.com/mcp" },
+ output: {
+ type: "setup_requirements",
+ message: "Connect Notion to continue.",
+ session_id: SESSION_ID,
+ setup_info: {
+ agent_id: "https://mcp.notion.com/mcp",
+ agent_name: "notion.com",
+ requirements: {},
+ user_readiness: { has_all_credentials: true },
+ },
+ },
+ } as unknown as MessagePart;
+}
+
function widerScopePart(): MessagePart {
const base = setupRequirementsPart() as unknown as Record<string, unknown>;
const output = base.output as Record<string, unknown>;
@@ -693,3 +995,50 @@ function widerScopePart(): MessagePart {
},
} as unknown as MessagePart;
}
+
+function mockTwoProviderBackend() {
+ savedCredentials = [];
+ server.use(
+ http.get("*/api/integrations/providers", () =>
+ HttpResponse.json([
+ { name: "github", description: "Repositories" },
+ { name: "slack", description: "Messages" },
+ ]),
+ ),
+ http.get("*/api/integrations/providers/system", () =>
+ HttpResponse.json([]),
+ ),
+ http.get("*/api/integrations/credentials", () =>
+ HttpResponse.json(savedCredentials),
+ ),
+ http.get("*/api/integrations/:provider/login", () =>
+ HttpResponse.json({
+ login_url: "https://example.com/oauth/authorize",
+ state_token: "state-token",
+ }),
+ ),
+ http.post("*/api/integrations/:provider/callback", ({ params }) => {
+ const provider = String(params.provider);
+ const stored = {
+ id: `cred-${provider}`,
+ provider,
+ type: "oauth2",
+ title: provider,
+ scopes: provider === "github" ? [REQUIRED_SCOPE] : ["chat:write"],
+ };
+ savedCredentials = [...savedCredentials, stored];
+ return HttpResponse.json(stored);
+ }),
+ );
+}
+
+/** The Slack tool call before its result arrives, under the id its setup card
+ * later lands on. */
+function pendingSlackCallPart(): MessagePart {
+ return {
+ type: "tool-run_block",
+ toolCallId: "call-run_block-slack",
+ state: "input-available",
+ input: { block_name: "SlackPostMessageBlock" },
+ } as unknown as MessagePart;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts
index a4ce7595f2..b95dd2f712 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts
@@ -8,11 +8,29 @@ import {
getChainHeading,
isChainPart,
isLiftedSetupRow,
+ isToolCallPending,
markSupersededSubSessionRows,
toChainRow,
type ChainRow,
} from "../helpers";
+function toolCallPart(
+ state:
+ | "input-streaming"
+ | "input-available"
+ | "approval-requested"
+ | "approval-responded"
+ | "output-available"
+ | "output-error"
+ | "output-denied",
+): MessagePart {
+ return {
+ type: "tool-run_block",
+ state,
+ toolCallId: "call-1",
+ } as unknown as MessagePart;
+}
+
function textPart(text: string): MessagePart {
return { type: "text", text } as MessagePart;
}
@@ -580,3 +598,24 @@ describe("markSupersededSubSessionRows", () => {
expect(marked.every((r) => !r.supersededSubSession)).toBe(true);
});
});
+
+describe("isToolCallPending", () => {
+ // A tool paused on human-in-the-loop approval has no result either — the
+ // same class of bug the chain's once-only send already guards against for
+ // input-streaming/input-available.
+ it.each([
+ "input-streaming",
+ "input-available",
+ "approval-requested",
+ "approval-responded",
+ ] as const)("treats %s as pending", (state) => {
+ expect(isToolCallPending(toolCallPart(state))).toBe(true);
+ });
+
+ it.each(["output-available", "output-error", "output-denied"] as const)(
+ "treats %s as settled",
+ (state) => {
+ expect(isToolCallPending(toolCallPart(state))).toBe(false);
+ },
+ );
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts
index 1b60148224..3caf899cb2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts
@@ -20,6 +20,9 @@ export interface ChainActionEntry {
/** This card's reply must be reviewed before it is sent, so the chain owes
* it a Proceed even when it asks for nothing but credentials. */
manualProceed?: boolean;
+ /** A sign-in completed on this card during this page life. The chain sends
+ * only when one has, so a chat reloaded from history stays silent. */
+ justConnected?: boolean;
/** Credentials this card needs. The chain merges every entry's request
* into the single connectors table it renders underneath itself. */
connectors?: ConnectorRequest;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
index abf972c1a7..0e4c8eb03d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
@@ -386,3 +386,17 @@ export function buildChainSegments(
return segments;
}
+
+/** A tool call whose result has not landed. Whatever it needs from the user
+ * has not been asked for yet. A call paused on human-in-the-loop approval
+ * is equally unresolved — only a denial or an output ends it. */
+export function isToolCallPending(part: MessagePart): boolean {
+ if (!part.type.startsWith("tool-")) return false;
+ const state = (part as ToolUIPart).state;
+ return (
+ state === "input-streaming" ||
+ state === "input-available" ||
+ state === "approval-requested" ||
+ state === "approval-responded"
+ );
+}