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(platform): harden copilot setup_requirements card delivery (#13350)
Ubbe01efcc225ad0
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.pyindex a006605c2a..57bd5f9240 100644--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py@@ -94,6 +94,14 @@ SetupRequiredCallback = Callable[Awaitable[None],]+# Fired when a setup_requirements payload arrives corrupted and is dropped, so+# the adapter can surface a user-facing notice instead of leaving the user+# staring at a sign-in prompt that never renders. Args: (session_id, tool_name).+SetupDroppedCallback = Callable[+ [str, str | None],+ Awaitable[None],+]+class BotBackend:"""Bot-side linking + chat operations, routed over cluster-internal RPC."""@@ -318,6 +326,7 @@ class BotBackend:platform_server_id: Optional[str] = None,on_session_id: Optional[Callable[[str], Awaitable[None]]] = None,on_setup_required: SetupRequiredCallback | None = None,+ on_setup_dropped: SetupDroppedCallback | None = None,) -> AsyncGenerator[str, None]:"""Start a copilot turn and yield text deltas from the stream.@@ -348,6 +357,7 @@ class BotBackend:)setup_notified = False+ setup_drop_notified = Falsetry:while True:@@ -377,6 +387,18 @@ class BotBackend:setup_output,chunk.toolName,)+ elif (+ setup_output is None+ and not setup_notified+ and not setup_drop_notified+ and on_setup_dropped+ and _is_corrupted_setup_requirements(chunk.output)+ ):+ # The link was dropped (corrupted payload). Tell the+ # user once so they aren't left waiting on a sign-in+ # prompt that will never arrive.+ setup_drop_notified = True+ await on_setup_dropped(handle.session_id, chunk.toolName)elif isinstance(chunk, StreamFinish):returnelif isinstance(chunk, StreamError):@@ -395,12 +417,39 @@ class BotBackend:)+def _is_corrupted_setup_requirements(output: str | dict[str, Any]) -> bool:+ """True when *output* names setup_requirements but doesn't parse as JSON.++ This is the truncation/corruption signature: the tool intended to surface a+ sign-in card, but the payload arrived mangled, so the user gets nothing+ unless the caller surfaces a notice.+ """+ if not isinstance(output, str):+ return False+ if '"setup_requirements"' not in output:+ return False+ try:+ json.loads(output)+ except json.JSONDecodeError:+ return True+ return False++def _extract_setup_requirements(output: str | dict[str, Any]) -> dict[str, Any] | None:"""Return setup-requirements payloads from structured tool output."""if isinstance(output, str):try:parsed: Any = json.loads(output)except json.JSONDecodeError:+ if '"setup_requirements"' in output:+ # A payload that mentions setup_requirements but doesn't parse+ # is almost certainly a truncated/corrupted tool output — the+ # user never gets their sign-in link if we drop it silently.+ logger.warning(+ "Dropping unparseable setup_requirements tool output "+ "(%d chars) — sign-in link will not be sent",+ len(output),+ )return Noneelse:parsed = outputdiff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.pyindex b5f3e39c91..04dcffbc17 100644--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py@@ -1,6 +1,7 @@"""Tests for the bot's thin facade over PlatformLinkingManagerClient."""import asyncio+import loggingfrom datetime import datetime, timezonefrom unittest.mock import AsyncMock, MagicMock, patch@@ -24,7 +25,12 @@ from backend.util.exceptions import (NotFoundError,)-from .bot_backend import BotBackend, BotStreamError+from .bot_backend import (+ BotBackend,+ BotStreamError,+ _extract_setup_requirements,+ _is_corrupted_setup_requirements,+)@pytest.fixture@@ -239,6 +245,54 @@ class TestStreamChat:)]+ @pytest.mark.asyncio+ async def test_notifies_setup_dropped_on_corrupted_output(self, api: BotBackend):+ handle = ChatTurnHandle(session_id="sess", turn_id="turn", user_id="u1")+ api._client.start_chat_turn = AsyncMock(return_value=handle)++ queue: asyncio.Queue = asyncio.Queue()+ await queue.put(+ StreamToolOutputAvailable(+ toolCallId="tool-1",+ toolName="connect_integration",+ output='{"type":"setup_requirements","message":"Connect Goo',+ )+ )+ await queue.put(StreamFinish())++ setup_calls: list[tuple[str, dict, str | None]] = []+ dropped_calls: list[tuple[str, str | None]] = []++ async def on_setup(session_id: str, output: dict, tool_name: str | None):+ setup_calls.append((session_id, output, tool_name))++ async def on_dropped(session_id: str, tool_name: str | None):+ dropped_calls.append((session_id, tool_name))++ with (+ patch(+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",+ new=AsyncMock(return_value=queue),+ ),+ patch(+ "backend.copilot.bot.bot_backend.stream_registry.unsubscribe_from_session",+ new=AsyncMock(),+ ),+ ):+ async for _ in api.stream_chat(+ platform="discord",+ platform_user_id="u1",+ message="hi",+ on_setup_required=on_setup,+ on_setup_dropped=on_dropped,+ ):+ pass++ # The corrupted payload yields no card, so on_setup_required must not+ # fire — but the user is told the link was dropped.+ assert setup_calls == []+ assert dropped_calls == [("sess", "connect_integration")]+@pytest.mark.asyncioasync def test_duplicate_message_propagates(self, api: BotBackend):api._client.start_chat_turn = AsyncMock(@@ -288,3 +342,48 @@ class TestStreamChat:passassert excinfo.value.error_kind == "subscribe_failed"+++class TestExtractSetupRequirements:+ def test_extracts_from_json_string(self):+ payload = '{"type":"setup_requirements","message":"Connect GitHub"}'+ assert _extract_setup_requirements(payload) == {+ "type": "setup_requirements",+ "message": "Connect GitHub",+ }++ def test_truncated_setup_requirements_logs_warning(+ self, caplog: pytest.LogCaptureFixture+ ):+ """A corrupted setup_requirements payload must not be dropped silently —+ the user never receives their sign-in link, so we need telemetry."""+ truncated = '{"type":"setup_requirements","message":"Connect Goo'+ with caplog.at_level(logging.WARNING):+ assert _extract_setup_requirements(truncated) is None+ assert any("setup_requirements" in record.message for record in caplog.records)++ def test_non_setup_unparseable_output_stays_silent(+ self, caplog: pytest.LogCaptureFixture+ ):+ with caplog.at_level(logging.WARNING):+ assert _extract_setup_requirements("plain text tool result") is None+ assert not caplog.records+++class TestIsCorruptedSetupRequirements:+ def test_truncated_setup_requirements_is_corrupted(self):+ assert _is_corrupted_setup_requirements(+ '{"type":"setup_requirements","message":"Connect Goo'+ )++ def test_valid_setup_requirements_is_not_corrupted(self):+ assert not _is_corrupted_setup_requirements(+ '{"type":"setup_requirements","message":"Connect GitHub"}'+ )++ def test_unparseable_non_setup_output_is_not_corrupted(self):+ assert not _is_corrupted_setup_requirements('{"type":"other","x')++ def test_plain_text_and_dict_outputs_are_not_corrupted(self):+ assert not _is_corrupted_setup_requirements("plain text tool result")+ assert not _is_corrupted_setup_requirements({"type": "setup_requirements"})diff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.pyindex e6865de01c..533b0022fe 100644--- a/autogpt_platform/backend/backend/copilot/bot/handler.py+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py@@ -362,6 +362,27 @@ class MessageHandler:link_url=session_url,)+ async def _on_setup_dropped(+ session_id: str,+ _tool_name: str | None,+ ) -> None:+ nonlocal active_session_id, buffer, sent_any_content+ active_session_id = session_id+ # Drain pending text first so the notice doesn't jump ahead of the+ # message it follows.+ if buffer.strip():+ if await self._send_text_and_artifacts(+ adapter, target_id, buffer, ctx, session_id+ ):+ sent_any_content = True+ buffer = ""+ sent_any_content = True+ await adapter.send_message(+ target_id,+ _setup_dropped_message(),+ mentionable_users=ctx.mentionable_users,+ )+started_at = time.monotonic()reply_chars = 0typing_task = asyncio.create_task(_keep_typing(adapter, target_id))@@ -374,6 +395,7 @@ class MessageHandler:platform_server_id=ctx.server_id,on_session_id=_on_session_id,on_setup_required=_on_setup_required,+ on_setup_dropped=_on_setup_dropped,):buffer += chunkreply_chars += len(chunk)@@ -613,6 +635,14 @@ def _copilot_session_url(session_id: str) -> str | None:return f"{base_url}/copilot?sessionId={quote(session_id, safe='')}"+def _setup_dropped_message() -> str:+ return (+ "⚠️ AutoPilot tried to send you a sign-in link, but the data arrived "+ "corrupted so the button couldn't be shown. Please ask it to try that "+ "step again."+ )++def _setup_required_message(setup_output: dict[str, Any]) -> str:message = str(setup_output.get("message") or "").strip()if not message:diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex f150c7b8c4..ba333e3835 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -160,6 +160,7 @@ from .tool_adapter import (create_copilot_mcp_server,get_copilot_tool_names,get_sdk_disallowed_tools,+ reset_pending_tool_outputs,reset_stash_event,reset_tool_failure_counters,set_execution_context,@@ -4486,6 +4487,10 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues# Clear any stale stash signal from the previous attempt so# wait_for_stash() doesn't fire prematurely on a leftover event.reset_stash_event()+ # Drop orphaned tool outputs stashed by a rolled-back attempt —+ # the name-keyed FIFO would otherwise serve them (off-by-one) to+ # this attempt's tool calls, corrupting frontend tool payloads.+ reset_pending_tool_outputs()# Reset tool-level circuit breaker so failures from a previous# (rolled-back) attempt don't carry over to the fresh attempt.reset_tool_failure_counters()diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.pyindex ffd2dae6c7..b622610303 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py@@ -173,6 +173,21 @@ def reset_tool_failure_counters() -> None:_consecutive_tool_failures.set({})+def reset_pending_tool_outputs() -> None:+ """Drop stashed tool outputs left over from a previous stream attempt.++ The stash is a FIFO keyed by tool *name*, not tool_call_id. A rolled-back+ attempt that executed tools but never consumed their results leaves+ orphaned entries, so on the retry every ``pop_pending_tool_output`` for+ that tool name returns the stale first-attempt output — shifting all+ subsequent pops off-by-one and attaching wrong payloads to the frontend's+ ``StreamToolOutputAvailable`` events (e.g. a ``setup_requirements`` card+ silently replaced by an older result). Called at the top of each retry+ attempt, where no tool call can be in flight.+ """+ _pending_tool_outputs.set({})++def pop_pending_tool_output(tool_name: str) -> str | None:"""Pop and return the oldest stashed output for *tool_name*.diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.pyindex 99762bfa51..a432f8c032 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py@@ -25,6 +25,7 @@ from .tool_adapter import (create_copilot_mcp_server,create_tool_handler,pop_pending_tool_output,+ reset_pending_tool_outputs,reset_stash_event,set_execution_context,stash_pending_tool_output,@@ -137,6 +138,18 @@ class TestToolOutputStash:assert pop_pending_tool_output("b") == "beta"assert pop_pending_tool_output("a") == "alpha"+ def test_reset_pending_tool_outputs_drops_orphans(self):+ """A retry attempt must not inherit stashed outputs from a rolled-back+ attempt — orphaned entries shift the name-keyed FIFO off-by-one and+ attach stale payloads to the new attempt's tool calls."""+ stash_pending_tool_output("run_block", "stale-from-failed-attempt")+ reset_pending_tool_outputs()+ assert pop_pending_tool_output("run_block") is None++ # A fresh stash after the reset behaves normally.+ stash_pending_tool_output("run_block", "fresh")+ assert pop_pending_tool_output("run_block") == "fresh"+# ---------------------------------------------------------------------------# reset_stash_event / wait_for_stashdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.tsindex e168d7fc05..f24d9f7dee 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts@@ -211,6 +211,22 @@ describe("buildRenderSegments", () => {expect(segments[0].kind).toBe("part");});+ it("never collapses connect_integration into a tool group", () => {+ // The sign-in card must stay individually rendered — folding it into a+ // collapsed group hides the card behind a "N tool calls" summary.+ const parts = [+ toolPart("generic_a", "output-available"),+ toolPart("connect_integration", "output-available", {+ type: "setup_requirements",+ message: "Connect GitHub",+ }),+ toolPart("generic_b", "output-available"),+ ];+ const segments = buildRenderSegments(parts);+ expect(segments).toHaveLength(3);+ expect(segments.every((s) => s.kind === "part")).toBe(true);+ });+it("preserves baseIndex offset in part segments", () => {const parts = [textPart("Hello")];const segments = buildRenderSegments(parts, 5);@@ -541,6 +557,43 @@ describe("splitReasoningAndResponse", () => {expect(result.response[0]).toBe(askQuestion);});+ it("pins corrupted card-capable tool parts instead of hiding them", () => {+ // Truncated setup_requirements JSON: isInteractiveToolPart can't parse+ // it, but burying the part in "Show steps" would silently swallow a+ // lost sign-in card — it must stay visible so the renderer can show+ // an error.+ const corruptedRunBlock = toolPart(+ "run_block",+ "output-available",+ '{"type":"setup_requirements","message":"Connect Goo',+ );+ const parts = [+ corruptedRunBlock,+ reasoningPart("Thinking about the result..."),+ textPart("A sign-in card has appeared."),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toEqual([parts[1]]);+ expect(result.response).toHaveLength(2);+ expect(result.response[0]).toBe(corruptedRunBlock);+ });++ it("keeps card-capable tools with valid non-interactive output in reasoning", () => {+ const okRunBlock = toolPart(+ "run_block",+ "output-available",+ JSON.stringify({ type: "block_output", block_id: "b1", outputs: {} }),+ );+ const parts = [+ okRunBlock,+ reasoningPart("Reviewing output..."),+ textPart("Done"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toEqual([okRunBlock, parts[1]]);+ expect(result.response).toHaveLength(1);+ });+it("keeps non-interactive reasoning tools in reasoning", () => {const parts = [toolPart("find_block"),diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.tsindex 672c1d2f8b..f0db0ae54f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts@@ -2,6 +2,7 @@ import { getGetWorkspaceDownloadFileByIdUrl } from "@/app/api/__generated__/endpimport { ResponseType } from "@/app/api/__generated__/models/responseType";import { parseWorkspaceURI } from "@/lib/workspace-uri";import { FileUIPart, ToolUIPart, UIDataTypes, UIMessage, UITools } from "ai";+import { isCorruptedCardToolPart } from "../../helpers/toolOutput";import type { ArtifactRef } from "../../store";export type MessagePart = UIMessage<@@ -23,6 +24,7 @@ const CUSTOM_TOOL_TYPES = new Set(["tool-get_doc_page","tool-run_block","tool-continue_run_block",+ "tool-connect_integration","tool-run_mcp_tool","tool-run_agent","tool-schedule_agent",@@ -176,7 +178,11 @@ export function splitReasoningAndResponse(parts: MessagePart[]): {const pinnedParts: MessagePart[] = [];for (const part of rawReasoning) {- if (isInteractiveToolPart(part)) {+ // Corrupted card-capable parts are pinned too: their output failed to+ // parse, so isInteractiveToolPart can't recognize them, but hiding them+ // in the steps modal would silently swallow a lost sign-in/setup card.+ // Pinning lets the tool renderer surface a visible error instead.+ if (isInteractiveToolPart(part) || isCorruptedCardToolPart(part)) {pinnedParts.push(part);} else {// Reasoning / thinking parts stay inside the outer "Show steps" modaldiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/toolOutput.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/toolOutput.test.tsnew file mode 100644index 0000000000..bb7718f663--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/toolOutput.test.ts@@ -0,0 +1,89 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@sentry/nextjs", () => ({ captureMessage: vi.fn() }));++import * as Sentry from "@sentry/nextjs";+import {+ isCorruptedCardToolPart,+ isUnparseableJsonOutput,+ reportCorruptedToolOutput,+} from "../toolOutput";++beforeEach(() => {+ vi.clearAllMocks();+});++describe("isUnparseableJsonOutput", () => {+ it("returns true for truncated JSON", () => {+ expect(+ isUnparseableJsonOutput('{"type":"setup_requirements","message":"Conn'),+ ).toBe(true);+ });++ it("returns false for valid JSON", () => {+ expect(isUnparseableJsonOutput('{"type":"setup_requirements"}')).toBe(+ false,+ );+ });++ it("returns false for plain-text outputs", () => {+ expect(isUnparseableJsonOutput("Tool execution error: timeout")).toBe(+ false,+ );+ });++ it("returns false for empty and non-string outputs", () => {+ expect(isUnparseableJsonOutput("")).toBe(false);+ expect(isUnparseableJsonOutput(undefined)).toBe(false);+ expect(isUnparseableJsonOutput({ type: "setup_requirements" })).toBe(false);+ });+});++describe("isCorruptedCardToolPart", () => {+ const truncated = '{"type":"setup_requirements","message":"Conn';++ it("flags a card-capable tool with truncated JSON output", () => {+ expect(+ isCorruptedCardToolPart({+ type: "tool-run_block",+ state: "output-available",+ output: truncated,+ }),+ ).toBe(true);+ });++ it("ignores tools that never render cards", () => {+ expect(+ isCorruptedCardToolPart({+ type: "tool-search_docs",+ state: "output-available",+ output: truncated,+ }),+ ).toBe(false);+ });++ it("ignores non-completed and valid-output parts", () => {+ expect(+ isCorruptedCardToolPart({+ type: "tool-run_block",+ state: "output-error",+ output: truncated,+ }),+ ).toBe(false);+ expect(+ isCorruptedCardToolPart({+ type: "tool-run_block",+ state: "output-available",+ output: '{"type":"block_output","block_id":"b1"}',+ }),+ ).toBe(false);+ });+});++describe("reportCorruptedToolOutput", () => {+ it("reports once per toolCallId", () => {+ reportCorruptedToolOutput("call-dedupe-test", "tool-run_block");+ reportCorruptedToolOutput("call-dedupe-test", "tool-run_block");+ expect(vi.mocked(Sentry.captureMessage)).toHaveBeenCalledTimes(1);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/toolOutput.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/toolOutput.tsnew file mode 100644index 0000000000..41dd659567--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/toolOutput.ts@@ -0,0 +1,75 @@+import * as Sentry from "@sentry/nextjs";++/**+ * Tool types whose JSON output can surface interactive cards in chat+ * (setup_requirements sign-in cards, pickers, review prompts). When their+ * output arrives corrupted the user loses a card they cannot recover —+ * unlike read-only tools where a broken payload only degrades a summary.+ */+export const CARD_CAPABLE_TOOL_TYPES: ReadonlySet<string> = new Set([+ "tool-run_block",+ "tool-continue_run_block",+ "tool-connect_integration",+ "tool-run_agent",+ "tool-run_mcp_tool",+]);++/**+ * True when `output` looks like a JSON document but doesn't parse — the+ * signature of a payload truncated or mangled in transit. Plain-text+ * outputs (error strings, file-reference notes) are not flagged: only+ * strings that start as JSON and fail to parse.+ */+export function isUnparseableJsonOutput(output: unknown): boolean {+ if (typeof output !== "string") return false;+ const trimmed = output.trim();+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return false;+ try {+ JSON.parse(trimmed);+ return false;+ } catch {+ return true;+ }+}++export function isCorruptedCardToolPart(part: {+ type: string;+ state?: unknown;+ output?: unknown;+}): boolean {+ if (!CARD_CAPABLE_TOOL_TYPES.has(part.type)) return false;+ if (part.state !== "output-available") return false;+ return isUnparseableJsonOutput(part.output);+}++/**+ * Bounded so the dedupe set can't grow for the tab's lifetime and so a+ * `toolCallId` reused in a much later conversation eventually evicts its old+ * entry and gets reported again instead of being silently dropped.+ */+const MAX_REPORTED_TOOL_CALL_IDS = 500;+const reportedToolCallIds = new Set<string>();++/**+ * Report a corrupted tool output to Sentry, once per toolCallId — safe to+ * call from render since repeated invocations are no-ops.+ */+export function reportCorruptedToolOutput(+ toolCallId: string,+ toolType: string,+): void {+ if (!toolCallId || reportedToolCallIds.has(toolCallId)) return;+ if (reportedToolCallIds.size >= MAX_REPORTED_TOOL_CALL_IDS) {+ const oldest = reportedToolCallIds.values().next().value;+ if (oldest !== undefined) reportedToolCallIds.delete(oldest);+ }+ reportedToolCallIds.add(toolCallId);+ Sentry.captureMessage(+ "Copilot tool output unparseable — interactive card lost",+ {+ level: "warning",+ tags: { context: "copilot-tool-output", toolType },+ extra: { toolCallId },+ },+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsxindex 2ddd47f28b..b8898eea5e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx@@ -4,6 +4,10 @@ import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/simport type { ToolUIPart } from "ai";import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";import { SetupRequirementsCard } from "../../components/SetupRequirementsCard/SetupRequirementsCard";+import {+ isUnparseableJsonOutput,+ reportCorruptedToolOutput,+} from "../../helpers/toolOutput";type Props = {part: ToolUIPart;@@ -39,17 +43,27 @@ function parseError(raw: unknown): string | null {export function ConnectIntegrationTool({ part }: Props) {const isStreaming =part.state === "input-streaming" || part.state === "input-available";- const isError = part.state === "output-error";const output =part.state === "output-available"? parseOutput((part as { output?: unknown }).output): null;- const errorMessage = isError- ? (parseError((part as { output?: unknown }).output) ??- "Failed to connect integration")- : null;+ const isCorrupted =+ part.state === "output-available" &&+ !output &&+ isUnparseableJsonOutput((part as { output?: unknown }).output);+ if (isCorrupted) reportCorruptedToolOutput(part.toolCallId, part.type);++ const isError = part.state === "output-error" || isCorrupted;++ // Only genuine output-error states get the generic failure message; a+ // corrupted payload renders its own dedicated message below.+ const errorMessage =+ part.state === "output-error"+ ? (parseError((part as { output?: unknown }).output) ??+ "Failed to connect integration")+ : null;const rawProvider =(part as { input?: { provider?: string } }).input?.provider ?? "";@@ -80,6 +94,13 @@ export function ConnectIntegrationTool({ part }: Props) {<p className="mt-1 text-sm text-red-500">{errorMessage}</p>)}+ {isCorrupted && (+ <p className="mt-1 text-sm text-red-500">+ The sign-in card data arrived corrupted and can't be shown. Ask+ AutoPilot to retry connecting {providerName}.+ </p>+ )}+{output && (<div className="mt-2"><SetupRequirementsCarddiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/__tests__/ConnectIntegrationTool.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/__tests__/ConnectIntegrationTool.test.tsxnew file mode 100644index 0000000000..5096b6bc2c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/__tests__/ConnectIntegrationTool.test.tsx@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@sentry/nextjs", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@sentry/nextjs")>()),+ captureMessage: vi.fn(),+}));++import * as Sentry from "@sentry/nextjs";+import type { ToolUIPart } from "ai";+import { render, screen } from "@/tests/integrations/test-utils";+import { ConnectIntegrationTool } from "../ConnectIntegrationTool";++function makePart(overrides: Record<string, unknown> = {}): ToolUIPart {+ return {+ type: "tool-connect_integration",+ toolCallId: "call-connect-1",+ state: "input-streaming",+ input: { provider: "github" },+ ...overrides,+ } as ToolUIPart;+}++describe("ConnectIntegrationTool", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("styles the label as an error and reports when output is corrupted", () => {+ const { container } = render(+ <ConnectIntegrationTool+ part={makePart({+ state: "output-available",+ output: '{"setup_info":{"agent_name":"GitHub"',+ })}+ />,+ );+ expect(+ screen.getByText(/sign-in card data arrived corrupted/i),+ ).not.toBeNull();+ // isError now includes isCorrupted, so the label switches to the error+ // copy. MorphingTextAnimation splits chars and uses NBSP for spaces.+ const normalized = (container.textContent ?? "").replace(/ /g, " ");+ expect(normalized).toContain("Failed to connect");+ expect(vi.mocked(Sentry.captureMessage)).toHaveBeenCalledTimes(1);+ });++ it("shows the failure message on a genuine error without corrupted telemetry", () => {+ render(+ <ConnectIntegrationTool+ part={makePart({+ state: "output-error",+ output: '{"message":"OAuth denied"}',+ })}+ />,+ );+ expect(screen.getByText("OAuth denied")).not.toBeNull();+ expect(+ screen.queryByText(/sign-in card data arrived corrupted/i),+ ).toBeNull();+ expect(vi.mocked(Sentry.captureMessage)).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsxindex fb57637345..870174fba7 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx@@ -26,6 +26,10 @@ import { ExecutionStartedCard } from "./components/ExecutionStartedCard/Executioimport { AgentDetailsCard } from "./components/AgentDetailsCard/AgentDetailsCard";import { SetupRequirementsCard } from "../../components/SetupRequirementsCard/SetupRequirementsCard";import { ErrorCard } from "./components/ErrorCard/ErrorCard";+import {+ isUnparseableJsonOutput,+ reportCorruptedToolOutput,+} from "../../helpers/toolOutput";export interface RunAgentToolPart {type: string;@@ -45,8 +49,14 @@ export function RunAgentTool({ part }: Props) {part.state === "input-streaming" || part.state === "input-available";const output = getRunAgentToolOutput(part);+ const isCorrupted =+ part.state === "output-available" &&+ !output &&+ isUnparseableJsonOutput(part.output);+ if (isCorrupted) reportCorruptedToolOutput(part.toolCallId, part.type);const isError =part.state === "output-error" ||+ isCorrupted ||(!!output && isRunAgentErrorOutput(output));const isOutputAvailable = part.state === "output-available" && !!output;@@ -84,12 +94,19 @@ export function RunAgentTool({ part }: Props) {<div className="flex items-center gap-2 text-sm text-muted-foreground"><ToolIcon isStreaming={isStreaming} isError={isError} /><MorphingTextAnimation- text={text}+ text={isCorrupted ? "Agent result could not be displayed" : text}className={isError ? "text-red-500" : undefined}/></div>)}+ {isCorrupted && (+ <p className="mt-1 text-sm text-red-500">+ The result data arrived corrupted, so any sign-in or setup card it+ contained can't be shown. Ask AutoPilot to retry this step.+ </p>+ )}+{isStreaming && !output && (<ToolAccordionicon={<ScaleLoader size={14} />}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/__tests__/RunAgent.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/__tests__/RunAgent.test.tsxnew file mode 100644index 0000000000..75e790c047--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/__tests__/RunAgent.test.tsx@@ -0,0 +1,56 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@sentry/nextjs", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@sentry/nextjs")>()),+ captureMessage: vi.fn(),+}));++import * as Sentry from "@sentry/nextjs";+import { render, screen } from "@/tests/integrations/test-utils";+import { RunAgentTool, type RunAgentToolPart } from "../RunAgent";++function makePart(overrides: Partial<RunAgentToolPart> = {}): RunAgentToolPart {+ return {+ type: "tool-run_agent",+ toolCallId: "call-agent-1",+ state: "input-streaming",+ input: { agent_id: "a1" },+ ...overrides,+ };+}++describe("RunAgentTool corrupted output", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("shows a visible error and reports to Sentry when output is unparseable JSON", () => {+ render(+ <RunAgentTool+ part={makePart({+ state: "output-available",+ output: '{"type":"setup_requirements","message":"Connect Goo',+ })}+ />,+ );+ expect(screen.getByText(/result data arrived corrupted/i)).not.toBeNull();+ expect(vi.mocked(Sentry.captureMessage)).toHaveBeenCalledTimes(1);+ });++ it("does not flag a valid output as corrupted", () => {+ render(+ <RunAgentTool+ part={makePart({+ state: "output-available",+ output: JSON.stringify({+ type: "execution_started",+ execution_id: "e1",+ message: "Started",+ }),+ })}+ />,+ );+ expect(screen.queryByText(/result data arrived corrupted/i)).toBeNull();+ expect(vi.mocked(Sentry.captureMessage)).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsxindex 1ff238a0cf..fd83e8abb5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx@@ -8,6 +8,10 @@ import { BlockInputCard } from "./components/BlockInputCard/BlockInputCard";import { BlockOutputCard } from "./components/BlockOutputCard/BlockOutputCard";import { ErrorCard } from "./components/ErrorCard/ErrorCard";import { SetupRequirementsCard } from "../../components/SetupRequirementsCard/SetupRequirementsCard";+import {+ isUnparseableJsonOutput,+ reportCorruptedToolOutput,+} from "../../helpers/toolOutput";import {getAccordionMeta,getAnimationText,@@ -41,8 +45,14 @@ export function RunBlockTool({ part }: Props) {const output = getRunBlockToolOutput(part);const inputData = (part.input as RunBlockInput | undefined)?.input_data;const hasInputData = inputData != null && Object.keys(inputData).length > 0;+ const isCorrupted =+ part.state === "output-available" &&+ !output &&+ isUnparseableJsonOutput(part.output);+ if (isCorrupted) reportCorruptedToolOutput(part.toolCallId, part.type);const isError =part.state === "output-error" ||+ isCorrupted ||(!!output && isRunBlockErrorOutput(output));const setupRequirementsOutput =part.state === "output-available" &&@@ -69,11 +79,18 @@ export function RunBlockTool({ part }: Props) {<div className="flex items-center gap-2 text-sm text-muted-foreground"><ToolIcon isStreaming={isStreaming} isError={isError} /><MorphingTextAnimation- text={text}+ text={isCorrupted ? "Block result could not be displayed" : text}className={isError ? "text-red-500" : undefined}/></div>+ {isCorrupted && (+ <p className="mt-1 text-sm text-red-500">+ The result data arrived corrupted, so any sign-in or setup card it+ contained can't be shown. Ask AutoPilot to retry this step.+ </p>+ )}+{setupRequirementsOutput && (<div className="mt-2"><SetupRequirementsCard output={setupRequirementsOutput} />diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsxindex 2f789cae00..d0bc98b2d8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx@@ -16,6 +16,10 @@ import {serverHost,type MCPErrorOutput,} from "./helpers";+import {+ isUnparseableJsonOutput,+ reportCorruptedToolOutput,+} from "../../helpers/toolOutput";export interface RunMCPToolPart {type: string;@@ -35,8 +39,15 @@ export function RunMCPToolComponent({ part }: Props) {part.state === "input-streaming" || part.state === "input-available";const output = getRunMCPToolOutput(part);+ const isCorrupted =+ part.state === "output-available" &&+ !output &&+ isUnparseableJsonOutput(part.output);+ if (isCorrupted) reportCorruptedToolOutput(part.toolCallId, part.type);const isError =- part.state === "output-error" || (!!output && isErrorOutput(output));+ part.state === "output-error" ||+ isCorrupted ||+ (!!output && isErrorOutput(output));const setupRequirementsOutput =part.state === "output-available" &&@@ -60,11 +71,18 @@ export function RunMCPToolComponent({ part }: Props) {<div className="flex items-center gap-2 text-sm text-muted-foreground"><ToolIcon isStreaming={isStreaming} isError={isError} /><MorphingTextAnimation- text={text}+ text={isCorrupted ? "Tool result could not be displayed" : text}className={isError ? "text-red-500" : undefined}/></div>+ {isCorrupted && (+ <p className="mt-1 text-sm text-red-500">+ The result data arrived corrupted, so any sign-in or setup card it+ contained can't be shown. Ask AutoPilot to retry this step.+ </p>+ )}+{/* Error detail card */}{errorOutput && (<div className="mt-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/__tests__/RunMCPTool.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/__tests__/RunMCPTool.test.tsxnew file mode 100644index 0000000000..bafa6aa601--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/__tests__/RunMCPTool.test.tsx@@ -0,0 +1,56 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@sentry/nextjs", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@sentry/nextjs")>()),+ captureMessage: vi.fn(),+}));++import * as Sentry from "@sentry/nextjs";+import { render, screen } from "@/tests/integrations/test-utils";+import { RunMCPToolComponent, type RunMCPToolPart } from "../RunMCPTool";++function makePart(overrides: Partial<RunMCPToolPart> = {}): RunMCPToolPart {+ return {+ type: "tool-run_mcp_tool",+ toolCallId: "call-mcp-1",+ state: "input-streaming",+ input: { server_url: "https://mcp.example.com" },+ ...overrides,+ };+}++describe("RunMCPToolComponent corrupted output", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("shows a visible error and reports to Sentry when output is unparseable JSON", () => {+ render(+ <RunMCPToolComponent+ part={makePart({+ state: "output-available",+ output: '{"type":"setup_requirements","message":"Connect Goo',+ })}+ />,+ );+ expect(screen.getByText(/result data arrived corrupted/i)).not.toBeNull();+ expect(vi.mocked(Sentry.captureMessage)).toHaveBeenCalledTimes(1);+ });++ it("does not flag a valid output as corrupted", () => {+ render(+ <RunMCPToolComponent+ part={makePart({+ state: "output-available",+ output: JSON.stringify({+ tool_name: "search",+ server_url: "https://mcp.example.com",+ result: "ok",+ }),+ })}+ />,+ );+ expect(screen.queryByText(/result data arrived corrupted/i)).toBeNull();+ expect(vi.mocked(Sentry.captureMessage)).not.toHaveBeenCalled();+ });+});