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): add copilot tool chain UI (#13773)
Abhimanyu Yadava6df3d338131
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex ab5d6205b0..99325197de 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -83,6 +83,7 @@ from backend.copilot.response_model import (StreamHeartbeat,StreamStart,StreamStartStep,+ StreamStatus,)from backend.copilot.service import strip_injected_context_for_displayfrom backend.copilot.tools.e2b_sandbox import kill_sandbox@@ -1695,6 +1696,20 @@ async def stream_chat_post()else:log_meta["turn_id"] = turn_id+ # First chunk on the turn stream: gives the SSE subscriber an+ # immediate status to render while the turn waits for an executor+ # pickup — otherwise the user stares at a bare loader until setup+ # completes.+ try:+ await stream_registry.publish_chunk(+ turn_id,+ StreamStatus(message="Message received…"),+ session_id=session_id,+ )+ except Exception:+ logger.warning(+ "[STREAM] Failed to publish initial status chunk", exc_info=True+ )setup_time = (time.perf_counter() - stream_start_time) * 1000logger.info(diff --git a/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.py b/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.pyindex 0d1f66fea7..faf6e7d7a8 100644--- a/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.py+++ b/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.py@@ -63,8 +63,12 @@ class TestBuildAndValidatePermissions:_make_input(tools=["not_a_real_tool"])async def test_disabled_legacy_tool_is_accepted_and_removed(self):- inp = _make_input(tools=["ask_question", "run_block"])- result = await _build_and_validate_permissions(inp)+ with patch(+ "backend.blocks.autopilot.DISABLED_LEGACY_TOOL_NAMES",+ frozenset({"retired_tool"}),+ ):+ inp = _make_input(tools=["retired_tool", "run_block"])+ result = await _build_and_validate_permissions(inp)assert inp.tools == ["run_block"]assert isinstance(result, CopilotPermissions)diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.pyindex 041088788d..4132886614 100644--- a/autogpt_platform/backend/backend/copilot/executor/processor.py+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py@@ -21,7 +21,7 @@ from backend.copilot.expert_context import (EXPERT_SESSION_TEMPORARY_MESSAGE,ExpertSessionUnavailableError,)-from backend.copilot.response_model import StreamError+from backend.copilot.response_model import StreamError, StreamStatusfrom backend.copilot.sdk import service as sdk_servicefrom backend.copilot.sdk.dummy import stream_chat_completion_dummyfrom backend.copilot.stream_heartbeat import wrap_stream_with_heartbeat@@ -563,6 +563,18 @@ class CoPilotProcessor:try:from backend.copilot.model import get_chat_session+ # Executor picked the turn up — replace the route's "Message+ # received…" status while feature-flag resolution and service+ # setup run.+ try:+ await stream_registry.publish_chunk(+ entry.turn_id,+ StreamStatus(message="Setting up your environment…"),+ session_id=entry.session_id,+ )+ except Exception:+ log.warning("Failed to publish setup status chunk")+session = await get_chat_session(entry.session_id, entry.user_id)if session is None:raise RuntimeError("copilot_session_not_found")diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.pyindex ebc9dda38b..3c9755c878 100644--- a/autogpt_platform/backend/backend/copilot/permissions.py+++ b/autogpt_platform/backend/backend/copilot/permissions.py@@ -71,6 +71,7 @@ if TYPE_CHECKING:ToolName = Literal[# Platform tools (must match keys in TOOL_REGISTRY)"add_understanding",+ "ask_question","bash_exec","browser_act","browser_navigate",@@ -147,7 +148,7 @@ ToolName = Literal[# Frozen set of all valid tool names — derived from the Literal.ALL_TOOL_NAMES: frozenset[str] = frozenset(get_args(ToolName))-DISABLED_LEGACY_TOOL_NAMES: frozenset[str] = frozenset({"ask_question"})+DISABLED_LEGACY_TOOL_NAMES: frozenset[str] = frozenset()"""Tool names accepted only for backwards compatibility with saved graphs.These names are intentionally absent from ``ToolName`` anddiff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 8282152e5a..6d53d281a2 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -3579,6 +3579,9 @@ async def _run_stream_attempt(# - ValueError: ContextVar token mismatch (AUTOGPT-SERVER-8BT)# - RuntimeError: cancel scope in wrong task (AUTOGPT-SERVER-8BW)# Both are harmless — the TCP connection is already dead.+ # CLI subprocess spawn + MCP init can take seconds on cold starts —+ # narrate it so the status doesn't sit on the context-prep message.+ yield StreamStatus(message="Starting the assistant…")sdk_client = ClaudeSDKClient(options=state.options)client = await sdk_client.__aenter__()try:@@ -4233,6 +4236,16 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuescode="sdk_cwd_error",)return++ # Narrate the parallel setup below (sandbox spin-up, system prompt+ # build, CLI session restore) — it can take several seconds and the+ # generator cannot yield mid-gather.+ yield StreamStatus(+ message=(+ "Restoring your session…" if has_history else "Preparing workspace…"+ )+ )+# --- Run independent async I/O operations in parallel ---# E2B sandbox setup, system prompt build (Langfuse + DB), Graphiti# warm-context, and CLI session restore are all independent network@@ -4473,6 +4486,15 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuessdk_options = ClaudeAgentOptions(system_prompt=system_prompt_value,mcp_servers={"copilot": mcp_server},+ # Never load the host machine's ~/.claude settings (hooks,+ # skills, plugins) or filesystem MCP servers into the CoPilot+ # subprocess. On developer machines a personal Claude Code+ # setup can inject hundreds of MCP tool schemas, inflating the+ # static prompt past the autocompact threshold and causing+ # compaction thrash on the very first turn. Prod containers+ # have a clean HOME, so this is a no-op there.+ setting_sources=[],+ extra_args={"strict-mcp-config": None},allowed_tools=allowed,disallowed_tools=disallowed,hooks=security_hooks,@@ -4617,6 +4639,11 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues# persist_session_safe (routes.py has already saved the user# message at sequence N before the executor runs, so an# incremental upsert would write a second copy at N+1).+ # Narrate the context-assembly phase (pending drain, user-context+ # injection, attachment prep, query/transcript build) before the+ # SDK client spawns.+ yield StreamStatus(message="Preparing conversation context…")+pending_messages = await drain_pending_safe(session_id, log_prefix)if pending_messages:logger.info(diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.pyindex e852c1e19a..dc5f34c419 100644--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py@@ -11,6 +11,7 @@ from backend.copilot.tracking import track_tool_calledfrom .add_understanding import AddUnderstandingToolfrom .agent_browser import BrowserActTool, BrowserNavigateTool, BrowserScreenshotToolfrom .agent_output import AgentOutputTool+from .ask_question import AskQuestionToolfrom .base import BaseToolfrom .bash_exec import BashExecToolfrom .chat_platform import ListChatPlatformChannelsTool, PostToChatPlatformTool@@ -74,6 +75,7 @@ logger = logging.getLogger(__name__)# Single source of truth for all toolsTOOL_REGISTRY: dict[str, BaseTool] = {"add_understanding": AddUnderstandingTool(),+ "ask_question": AskQuestionTool(),"create_agent": CreateAgentTool(),"customize_agent": CustomizeAgentTool(),"decompose_goal": DecomposeGoalTool(),diff --git a/autogpt_platform/backend/backend/copilot/tools/find_block.py b/autogpt_platform/backend/backend/copilot/tools/find_block.pyindex 44eb88727b..e2e290d98c 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_block.py@@ -11,6 +11,7 @@ from backend.copilot.model import ChatSessionfrom backend.data.db_accessors import searchfrom .base import BaseTool, ToolResponseBase+from .helpers import get_block_providerfrom .models import (BlockInfoSummary,BlockListResponse,@@ -186,6 +187,7 @@ class FindBlockTool(BaseTool):block.optimized_description or block.description or ""),categories=[c.value for c in block.categories],+ provider=get_block_provider(block),)return BlockListResponse(message=(@@ -260,6 +262,7 @@ class FindBlockTool(BaseTool):name=block.name,description=block.optimized_description or block.description or "",categories=[c.value for c in block.categories],+ provider=get_block_provider(block),)blocks.append(summary)diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.pyindex 05f99c2c8c..97a6ac2f95 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py@@ -6,12 +6,13 @@ import loggingimport uuidfrom collections import defaultdictfrom dataclasses import dataclass+from functools import cachefrom typing import Anyfrom pydantic_core import PydanticUndefinedfrom backend.blocks import BlockType, get_block-from backend.blocks._base import AnyBlockSchema+from backend.blocks._base import AnyBlockSchema, BlockSchemaInputfrom backend.copilot.constants import (COPILOT_NODE_EXEC_ID_SEPARATOR,COPILOT_NODE_PREFIX,@@ -168,6 +169,33 @@ async def _charge_block_credits(# BILLING_LEAK log above is the signal for reconciliation.+def get_block_provider(block: AnyBlockSchema) -> str | None:+ """Sole integration provider slug for a block, or None when the block+ uses zero or multiple providers."""+ try:+ return _get_input_schema_provider(block.input_schema)+ except Exception:+ logger.debug(+ "Unable to determine integration provider for block input schema %r",+ block.input_schema,+ exc_info=True,+ )+ return None+++@cache+def _get_input_schema_provider(input_schema: type[BlockSchemaInput]) -> str | None:+ infos = input_schema.get_credentials_fields_info()+ providers = {+ ProviderName(provider).value+ for info in infos.values()+ for provider in info.provider+ }+ if len(providers) != 1:+ return None+ return next(iter(providers))++async def execute_block(*,block: AnyBlockSchema,@@ -221,6 +249,7 @@ async def execute_block(block_id=block_id,block_name=block.name,outputs=dict(outputs),+ provider=get_block_provider(block),success=True,is_dry_run=True,session_id=session_id,@@ -443,6 +472,7 @@ async def execute_block(block_id=block_id,block_name=block.name,outputs=dict(outputs),+ provider=get_block_provider(block),success=True,session_id=session_id,)diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.pyindex 1878477a1b..b3176fe51e 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py@@ -13,6 +13,7 @@ from backend.copilot.tools.helpers import (BlockPreparation,check_hitl_review,execute_block,+ get_block_provider,prepare_block_for_execution,require_library_check,)@@ -23,7 +24,11 @@ from backend.copilot.tools.models import (ReviewRequiredResponse,SetupRequirementsResponse,)-from backend.data.model import CredentialsMetaInput+from backend.data.model import (+ CredentialsFieldInfo,+ CredentialsMetaInput,+ CredentialsType,+)from backend.integrations.providers import ProviderNamefrom ._test_data import make_session@@ -32,6 +37,64 @@ _USER = "test-user-helpers"_SESSION = "test-session-helpers"+class TestGetBlockProvider:+ def test_returns_only_provider(self):+ block = MagicMock()+ info = CredentialsFieldInfo[ProviderName, CredentialsType](+ credentials_provider=frozenset({ProviderName.GOOGLE}),+ credentials_types=frozenset({"oauth2"}),+ )+ block.input_schema.get_credentials_fields_info.return_value = {+ "credentials": info+ }++ assert get_block_provider(block) == "google"++ def test_returns_none_for_multiple_providers(self):+ block = MagicMock()+ info = CredentialsFieldInfo[ProviderName, CredentialsType](+ credentials_provider=frozenset({ProviderName.GOOGLE, ProviderName.GITHUB}),+ credentials_types=frozenset({"oauth2"}),+ )+ block.input_schema.get_credentials_fields_info.return_value = {+ "credentials": info+ }++ assert get_block_provider(block) is None++ def test_returns_none_without_providers(self):+ block = MagicMock()+ block.input_schema.get_credentials_fields_info.return_value = {}++ assert get_block_provider(block) is None++ def test_returns_none_for_invalid_schema_info_shape(self):+ block = MagicMock()+ block.input_schema.get_credentials_fields_info.return_value = []++ assert get_block_provider(block) is None++ def test_returns_none_when_schema_introspection_fails(self):+ block = MagicMock()+ block.input_schema.get_credentials_fields_info.side_effect = RuntimeError++ assert get_block_provider(block) is None++ def test_retries_schema_introspection_after_transient_failure(self):+ block = MagicMock()+ info = CredentialsFieldInfo[ProviderName, CredentialsType](+ credentials_provider=frozenset({ProviderName.GOOGLE}),+ credentials_types=frozenset({"oauth2"}),+ )+ block.input_schema.get_credentials_fields_info.side_effect = [+ RuntimeError,+ {"credentials": info},+ ]++ assert get_block_provider(block) is None+ assert get_block_provider(block) == "google"++def _make_block(block_id: str = "block-1",name: str = "TestBlock",diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex 3413070415..bb96756055 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -635,6 +635,12 @@ class BlockInfoSummary(BaseModel):default_factory=list,description="List of input fields for this block",)+ provider: str | None = Field(+ default=None,+ description="Integration provider slug when the block uses exactly "+ "one provider (e.g. 'google', 'discord'); used for provider icons "+ "in the chat UI",+ )class BlockListResponse(ToolResponseBase):@@ -676,6 +682,7 @@ class BlockOutputResponse(ToolResponseBase):block_id: strblock_name: stroutputs: dict[str, list[Any]]+ provider: str | None = Nonesuccess: bool = Trueis_dry_run: bool | None = (None # only set to True on dry-run; omitted in normal runs@@ -705,6 +712,11 @@ class WebFetchResponse(ToolResponseBase):status_code: intcontent_type: strcontent: str+ title: str | None = None+ content_length: int = Field(+ default=0,+ description="Original response body size in bytes",+ )truncated: bool = Falsediff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.pyindex 93303adf22..2cb1d0f63d 100644--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py@@ -100,7 +100,11 @@ from backend.copilot.tools import TOOL_REGISTRY# Includes the two-step Soul edit flow (update_expert_soul preview +# confirm_expert_soul_update); registry measures ~52.2k chars locally, with# ~800 headroom for CI env deltas and wording tweaks.-_CHAR_BUDGET = 53_000+# Bumped 53000 -> 54_000 for the copilot tool-chain UI: ``ask_question`` is back+# in TOOL_REGISTRY as a first-class tool (docked clarifying-question flow), so+# its schema counts again on top of the Soul edit flow. Merged registry measures+# 53349 chars; ~650 headroom for CI env deltas and wording tweaks.+_CHAR_BUDGET = 54_000@pytest.fixture(scope="module")diff --git a/autogpt_platform/backend/backend/copilot/tools/web_fetch.py b/autogpt_platform/backend/backend/copilot/tools/web_fetch.pyindex 79cc05dfa6..3fc5e53781 100644--- a/autogpt_platform/backend/backend/copilot/tools/web_fetch.py+++ b/autogpt_platform/backend/backend/copilot/tools/web_fetch.py@@ -1,6 +1,8 @@"""Web fetch tool — safely retrieve public web page content."""import logging+import re+from html import unescapefrom typing import Anyimport aiohttp@@ -50,6 +52,17 @@ def _html_to_text(html: str) -> str:return h.handle(html)+_TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)+++def _extract_title(html: str) -> str | None:+ match = _TITLE_RE.search(html)+ if not match:+ return None+ title = re.sub(r"\s+", " ", unescape(match.group(1))).strip()+ return title or None++class WebFetchTool(BaseTool):"""Safely fetch content from a public URL using SSRF-protected HTTP."""@@ -130,8 +143,11 @@ class WebFetchTool(BaseTool):raw = response.content[:_MAX_CONTENT_BYTES]text = raw.decode("utf-8", errors="replace")- if extract_text and "html" in content_type.lower():- text = _html_to_text(text)+ title = None+ if "html" in content_type.lower():+ title = _extract_title(text)+ if extract_text:+ text = _html_to_text(text)return WebFetchResponse(message=f"Fetched {url}",@@ -139,6 +155,8 @@ class WebFetchTool(BaseTool):status_code=response.status,content_type=content_type.split(";")[0].strip(),content=text,- truncated=False,+ title=title,+ content_length=len(response.content),+ truncated=len(response.content) > _MAX_CONTENT_BYTES,session_id=session_id,)diff --git a/autogpt_platform/backend/backend/copilot/tools/web_fetch_test.py b/autogpt_platform/backend/backend/copilot/tools/web_fetch_test.pynew file mode 100644index 0000000000..2d77e9255f--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/web_fetch_test.py@@ -0,0 +1,68 @@+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from ._test_data import make_session+from .models import WebFetchResponse+from .web_fetch import WebFetchTool, _extract_title+++def test_extract_title_decodes_entities_and_normalizes_whitespace():+ assert (+ _extract_title("<html><title> AutoGPT &\n Friends </title></html>")+ == "AutoGPT & Friends"+ )+++def test_extract_title_returns_none_when_missing():+ assert _extract_title("<html><body>No title</body></html>") is None++[email protected](loop_scope="session")+async def test_execute_returns_page_metadata_and_truncation():+ response = MagicMock()+ response.headers = {"content-type": "text/html; charset=utf-8"}+ response.content = (+ b"<html><title>Example</title><body>Hello</body></html>" + b" " * 102_400+ )+ response.url = "https://example.com/"+ response.status = 200+ client = MagicMock()+ client.get = AsyncMock(return_value=response)++ with patch("backend.copilot.tools.web_fetch.Requests", return_value=client):+ result = await WebFetchTool()._execute(+ user_id="test-user",+ session=make_session(user_id="test-user"),+ url="https://example.com",+ )++ assert isinstance(result, WebFetchResponse)+ assert result.title == "Example"+ assert result.content_length == len(response.content)+ assert result.truncated is True++[email protected](loop_scope="session")+async def test_execute_reports_small_original_body_size_after_text_extraction():+ response = MagicMock()+ response.headers = {"content-type": "text/html; charset=utf-8"}+ response.content = b"<html><title>Example</title><body>Hello</body></html>"+ response.url = "https://example.com/"+ response.status = 200+ client = MagicMock()+ client.get = AsyncMock(return_value=response)++ with patch("backend.copilot.tools.web_fetch.Requests", return_value=client):+ result = await WebFetchTool()._execute(+ user_id="test-user",+ session=make_session(user_id="test-user"),+ url="https://example.com",+ extract_text=True,+ )++ assert isinstance(result, WebFetchResponse)+ assert "Hello" in result.content+ assert "<body>" not in result.content+ assert result.content_length == len(response.content)+ assert result.truncated is Falsediff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsxnew file mode 100644index 0000000000..2ae9a00dcc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsx@@ -0,0 +1,130 @@+"use client";++import { useGetV1ListProviders } from "@/app/api/__generated__/endpoints/integrations/integrations";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { PlugSocketIcon } from "@hugeicons/core-free-icons";+import { useCopilotModal } from "../../useCopilotModal";+import { ConnectorRow } from "./ConnectorRow";+import { InputsSection } from "./InputsSection";+import { McpConnectorRow } from "./McpConnectorRow";+import { QuestionsSection } from "./QuestionsSection";+import {+ toConnectorRows,+ type ConnectorRequest,+ type InputsRequest,+ type McpConnectorRequest,+ type QuestionRequest,+} from "./helpers";++interface Props {+ connectors: ConnectorRequest[];+ mcp: McpConnectorRequest[];+ inputs: InputsRequest[];+ questions: QuestionRequest[];+ isReady: boolean;+ onProceed: () => void;+}++/** 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+ * a connectors-only card has no button: connecting is the whole ask. */+export function ChainActionCard({+ connectors,+ mcp,+ inputs,+ questions,+ isReady,+ onProceed,+}: Props) {+ const { openModal } = useCopilotModal();+ const providersQuery = useGetV1ListProviders({+ query: {+ select: (response) => (response.status === 200 ? response.data : []),+ },+ });++ const rows = toConnectorRows(connectors, providersQuery.data ?? []);+ // Two tool calls against the same MCP server ask once — connecting it+ // satisfies both hidden cards via their live-credential re-check.+ const mcpRows = mcp.filter(+ (request, i) =>+ mcp.findIndex((other) => other.serverUrl === request.serverUrl) === i,+ );+ const hasInputs = inputs.some(+ (request) => request.schema !== null || request.hasAdvanced,+ );+ const hasQuestions = questions.some(+ (request) => request.questions.length > 0,+ );+ // The questions card's send gates on its own answers only — an unready+ // sibling (e.g. an unconnected MCP row) must not freeze it.+ const questionsReady =+ hasQuestions &&+ questions.every((request) =>+ request.questions.every(+ (q) => (request.answers[q.keyword] ?? "").trim().length > 0,+ ),+ );+ if (rows.length === 0 && mcp.length === 0 && !hasInputs && !hasQuestions)+ return null;++ return (+ <div className="my-2 flex flex-col gap-2">+ {(rows.length > 0 || mcp.length > 0) && (+ <div className="overflow-hidden rounded-3xl border border-zinc-100 bg-white">+ <div className="flex items-center gap-2.5 border-b border-zinc-100 px-4 py-3">+ <Icon icon={PlugSocketIcon} size={18} className="text-zinc-400" />+ <span className="text-sm font-medium text-zinc-900">+ Plug in what this needs+ </span>+ </div>+ {rows.map((row) => (+ <ConnectorRow key={row.provider} row={row} />+ ))}+ {mcpRows.map((request) => (+ <McpConnectorRow key={request.id} request={request} />+ ))}+ <div className="border-t border-zinc-100 px-4 py-3">+ <span className="text-sm text-zinc-500">+ Looking for something else?{" "}+ <button+ type="button"+ onClick={() => openModal("integrations")}+ className="font-medium text-zinc-900 underline underline-offset-2"+ >+ Browse all connectors+ </button>+ </span>+ </div>+ </div>+ )}++ <InputsSection requests={inputs} />++ {hasQuestions && (+ <div className="overflow-hidden rounded-3xl border border-zinc-100 bg-white">+ <QuestionsSection+ requests={questions}+ isReady={questionsReady}+ onProceed={onProceed}+ />+ </div>+ )}++ {hasInputs && !hasQuestions && (+ <Button+ variant="primary"+ size="small"+ className="w-fit"+ disabled={!isReady}+ onClick={onProceed}+ >+ Proceed+ </Button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsxnew file mode 100644index 0000000000..cc3f3e1461--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx@@ -0,0 +1,86 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { ConnectCredentialDialog } from "@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog";+import { findSavedUserCredentialByProviderAndType } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";+import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";+import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";+import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";+import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";+import { useContext, useEffect, useState } from "react";+import type { ConnectorRow as Row } from "./helpers";++interface Props {+ row: Row;+}++export function ConnectorRow({ row }: Props) {+ const [isDialogOpen, setDialogOpen] = useState(false);+ const allProviders = useContext(CredentialsProvidersContext);++ // A credential the user already had — or one they just created in the+ // dialog — satisfies this row, so pick it up as soon as the providers+ // query refreshes rather than making them choose it again.+ const savedCredential = findSavedUserCredentialByProviderAndType(+ row.schema.credentials_provider ?? [],+ row.schema.credentials_types ?? [],+ row.schema.credentials_scopes,+ allProviders,+ row.schema.discriminator_values,+ );++ useEffect(() => {+ if (row.selected || !savedCredential) return;+ row.select({+ id: savedCredential.id,+ provider: savedCredential.provider,+ type: savedCredential.type as CredentialsMetaInput["type"],+ title: savedCredential.title ?? undefined,+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps -- row.select is rebuilt each render by the card+ }, [savedCredential?.id, row.selected]);++ return (+ <div className="flex items-center gap-3 px-4 py-3">+ <span className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-zinc-100 bg-white p-1.5">+ <ProviderAvatar id={row.provider} name={row.displayName} />+ </span>++ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium text-zinc-900">+ {row.displayName}+ </span>+ {row.description && (+ <span className="truncate text-sm text-zinc-500">+ {row.description}+ </span>+ )}+ </div>++ {row.selected ? (+ <span className="flex shrink-0 items-center gap-1.5 text-sm font-medium text-zinc-500">+ <Icon icon={CheckmarkCircle02Icon} size={16} />+ Connected+ </span>+ ) : (+ <Button+ variant="primary"+ size="small"+ className="shrink-0"+ onClick={() => setDialogOpen(true)}+ >+ Connect+ </Button>+ )}++ <ConnectCredentialDialog+ schema={row.schema}+ provider={row.provider}+ displayName={row.displayName}+ open={isDialogOpen}+ onClose={() => setDialogOpen(false)}+ />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/InputsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/InputsSection.tsxnew file mode 100644index 0000000000..32d1b7f43b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/InputsSection.tsx@@ -0,0 +1,76 @@+"use client";++import { Icon } from "@/components/atoms/Icon/Icon";+import { FormRenderer } from "@/components/renderers/InputRenderer/FormRenderer";+import { PencilEdit02Icon } from "@hugeicons/core-free-icons";+import { formatInputsTitle, type InputsRequest } from "./helpers";++interface Props {+ requests: InputsRequest[];+}++/** One card per block/agent asking for inputs, titled by its name so two+ * blocks' forms never blend into one table. */+export function InputsSection({ requests }: Props) {+ const visible = requests.filter(+ (request) => request.schema !== null || request.hasAdvanced,+ );+ if (visible.length === 0) return null;++ return (+ <>+ {visible.map((request) => (+ <div+ key={request.id}+ className="overflow-hidden rounded-3xl border border-zinc-100 bg-white"+ >+ <div className="flex items-center gap-2.5 border-b border-zinc-100 px-4 py-3">+ <Icon icon={PencilEdit02Icon} size={18} className="text-zinc-400" />+ <span className="text-sm font-medium text-zinc-900">+ {request.title+ ? formatInputsTitle(request.title)+ : "Fill in the details"}+ </span>+ {request.title && (+ <span className="ml-auto text-xs text-zinc-400">+ Fill in the details+ </span>+ )}+ </div>++ {/* Each RJSF field carries an inline 16px bottom margin — the+ negative margin swallows the last field's so the card edge+ sits ~8px below the form. */}+ <div className="px-4 pb-0 pt-2">+ {request.schema && (+ <FormRenderer+ jsonSchema={request.schema}+ className="-mb-2 mt-0"+ handleChange={(v) => request.onChange(v.formData ?? {})}+ uiSchema={{+ "ui:submitButtonOptions": { norender: true },+ }}+ initialValues={request.values}+ formContext={{+ showHandles: false,+ size: "small",+ }}+ />+ )}+ {request.hasAdvanced && (+ <button+ type="button"+ className="mb-2 mt-1 text-xs text-muted-foreground underline"+ onClick={request.onToggleAdvanced}+ >+ {request.showAdvanced+ ? "Hide advanced fields"+ : "Show advanced fields"}+ </button>+ )}+ </div>+ </div>+ ))}+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsxnew file mode 100644index 0000000000..a93f6d3a4a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsx@@ -0,0 +1,99 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";+import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";+import { useState } from "react";+import type { McpConnectorRequest } from "./helpers";++function hostOf(serverUrl: string): string | null {+ try {+ return new URL(serverUrl).hostname;+ } catch {+ return null;+ }+}++/** MCP server row inside the connectors table. Visually mirrors+ * ConnectorRow but connects through the MCP OAuth/token flow the hidden+ * MCPSetupCard drives via the request callbacks. */+export function McpConnectorRow({ request }: { request: McpConnectorRequest }) {+ const [token, setToken] = useState("");+ const host = hostOf(request.serverUrl);+ // "mcp.notion.com" → "notion" so existing /integrations/*.png icons+ // resolve; unknown services fall back to the avatar's initial.+ const iconId = (host ?? request.service)+ .replace(/^mcp\./, "")+ .split(".")[0]+ .toLowerCase();++ return (+ <div className="flex flex-col">+ <div className="flex items-center gap-3 px-4 py-3">+ <span className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-zinc-100 bg-white p-1.5">+ <ProviderAvatar id={iconId} name={request.service} />+ </span>++ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium text-zinc-900">+ {request.service}+ </span>+ {host && (+ <span className="truncate text-sm text-zinc-500">{host}</span>+ )}+ </div>++ {request.connected ? (+ <span className="flex shrink-0 items-center gap-1.5 text-sm font-medium text-zinc-500">+ <Icon icon={CheckmarkCircle02Icon} size={16} />+ Connected+ </span>+ ) : (+ <Button+ variant="primary"+ size="small"+ className="shrink-0"+ disabled={request.loading}+ onClick={request.onConnect}+ >+ {request.loading ? "Connecting…" : "Connect"}+ </Button>+ )}+ </div>++ {request.error && !request.connected && (+ <div className="mx-4 mb-3 rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">+ {request.error}+ </div>+ )}++ {request.showManualToken && !request.connected && (+ <div className="mx-4 mb-3 flex gap-2">+ <input+ type="password"+ aria-label={`API token for ${request.service}`}+ placeholder="Paste API token"+ value={token}+ onChange={(e) => setToken(e.target.value)}+ onKeyDown={(e) =>+ e.key === "Enter" &&+ !request.loading &&+ token.trim() &&+ request.onUseToken(token.trim())+ }+ className="flex-1 rounded-2xl bg-zinc-50 px-3 py-2 text-sm text-zinc-800 ring-1 ring-zinc-100 transition-shadow placeholder:text-zinc-400 focus:outline-none focus:ring-zinc-300"+ />+ <Button+ variant="secondary"+ size="small"+ disabled={request.loading || !token.trim()}+ onClick={() => request.onUseToken(token.trim())}+ >+ Use Token+ </Button>+ </div>+ )}+ </div>+ );+}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.tsxnew file mode 100644index 0000000000..125b7c11fc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionsSection.tsx@@ -0,0 +1,144 @@+"use client";++import { Icon } from "@/components/atoms/Icon/Icon";+import {+ ArrowLeft01Icon,+ ArrowRight01Icon,+ Message01Icon,+ SentIcon,+} from "@hugeicons/core-free-icons";+import { m } from "framer-motion";+import { useState } from "react";+import type { QuestionRequest } from "./helpers";++interface Props {+ requests: QuestionRequest[];+ isReady: boolean;+ 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. */+export function QuestionsSection({ requests, isReady, onProceed }: Props) {+ const [step, setStep] = useState(0);+ const questions = requests.flatMap((request) =>+ request.questions.map((question) => ({ request, question })),+ );+ if (questions.length === 0) return null;++ const current = Math.min(step, questions.length - 1);+ const { request, question } = questions[current];+ const answered = (request.answers[question.keyword] ?? "").trim().length > 0;+ const isLast = current === questions.length - 1;+ const actionEnabled = isLast ? isReady : answered;++ function handleAction() {+ if (isLast) {+ if (isReady) onProceed();+ } else if (answered) {+ setStep(current + 1);+ }+ }++ return (+ <>+ <div className="flex items-center justify-between gap-2.5 border-b border-zinc-100 px-4 py-3">+ <span className="flex items-center gap-2.5">+ <Icon icon={Message01Icon} size={18} className="text-zinc-400" />+ <span className="text-sm font-medium text-zinc-900">+ Answer a few questions+ </span>+ </span>+ <button+ type="button"+ onClick={() => requests.forEach((req) => req.onSkip())}+ className="rounded-full px-2 py-0.5 text-xs text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-600"+ >+ Skip+ </button>+ </div>++ <m.div+ key={question.keyword}+ initial={{ opacity: 0, y: 8 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ duration: 0.25, ease: [0.23, 1, 0.32, 1] }}+ className="flex flex-col gap-1.5 px-4 py-3"+ >+ <label className="flex flex-col gap-1.5">+ <span className="text-sm text-zinc-700">{question.question}</span>+ <input+ type="text"+ required+ autoFocus={current > 0}+ value={request.answers[question.keyword] ?? ""}+ onChange={(e) => request.onAnswer(question.keyword, e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && handleAction()}+ placeholder={+ question.example ? `e.g. ${question.example}` : "Type your answer"+ }+ className="rounded-2xl bg-zinc-50 px-3 py-2 text-sm text-zinc-800 ring-1 ring-zinc-100 transition-shadow placeholder:text-zinc-400 focus:outline-none focus:ring-zinc-300"+ />+ </label>+ </m.div>++ <div className="flex items-center justify-between px-4 pb-3 pt-1">+ <span className="flex items-center gap-2">+ <button+ type="button"+ aria-label="Previous question"+ disabled={current === 0}+ onClick={() => setStep(current - 1)}+ className="flex size-6 items-center justify-center rounded-lg text-zinc-400 transition-colors enabled:hover:bg-zinc-100 enabled:hover:text-zinc-600 disabled:opacity-35"+ >+ <Icon icon={ArrowLeft01Icon} size={14} />+ </button>+ <span className="flex items-center gap-1.5">+ {questions.map(({ question: q }, i) => (+ <button+ key={q.keyword}+ type="button"+ aria-label={`Go to question ${i + 1}`}+ aria-current={i === current ? "step" : undefined}+ onClick={() => setStep(i)}+ className={+ "rounded-full transition-all duration-300 " ++ (i === current+ ? "size-2.5 border-2 border-zinc-800"+ : i < current+ ? "size-2 bg-zinc-400"+ : "size-2 border border-zinc-300")+ }+ />+ ))}+ </span>+ <button+ type="button"+ aria-label="Next question"+ disabled={isLast}+ onClick={() => setStep(current + 1)}+ className="flex size-6 items-center justify-center rounded-lg text-zinc-400 transition-colors enabled:hover:bg-zinc-100 enabled:hover:text-zinc-600 disabled:opacity-35"+ >+ <Icon icon={ArrowRight01Icon} size={14} />+ </button>+ </span>++ <button+ type="button"+ aria-label={isLast ? "Add answers to message" : "Next question"}+ disabled={!actionEnabled}+ onClick={handleAction}+ className={+ "flex size-8 items-center justify-center rounded-full transition-all duration-200 enabled:active:scale-95 " ++ (actionEnabled+ ? "bg-zinc-800 text-white hover:bg-zinc-900"+ : "bg-zinc-100 text-zinc-400")+ }+ >+ <Icon icon={isLast ? SentIcon : ArrowRight01Icon} size={15} />+ </button>+ </div>+ </>+ );+}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.tsxnew file mode 100644index 0000000000..cdb338b769--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx@@ -0,0 +1,527 @@+import {+ CredentialsProvidersContext,+ type CredentialsProvidersContextType,+} from "@/providers/agent-credentials/credentials-provider";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { ChainActionCard } from "../ChainActionCard";+import type {+ ConnectorRequest,+ InputsRequest,+ McpConnectorRequest,+ QuestionRequest,+} from "../helpers";++const mockOpenModal = vi.fn();+vi.mock("../../../useCopilotModal", () => ({+ useCopilotModal: () => ({ openModal: mockOpenModal }),+}));++vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({+ useGetV1ListProviders: () => ({+ data: [{ name: "github", description: "Connect your GitHub account" }],+ }),+}));++vi.mock(+ "@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog",+ () => ({+ ConnectCredentialDialog: ({+ open,+ provider,+ }: {+ open: boolean;+ provider: string;+ }) => (open ? <div data-testid={`connect-dialog-${provider}`} /> : null),+ }),+);++vi.mock("@/components/renderers/InputRenderer/FormRenderer", () => ({+ FormRenderer: ({+ handleChange,+ }: {+ handleChange: (e: { formData?: Record<string, unknown> }) => void;+ }) => (+ <div data-testid="form-renderer">+ <button+ data-testid="form-change"+ onClick={() => handleChange({ formData: { url: "https://test.com" } })}+ >+ Fill+ </button>+ </div>+ ),+}));++afterEach(() => {+ cleanup();+ mockOpenModal.mockReset();+});++function connectorRequest(+ overrides: Partial<ConnectorRequest> = {},+): ConnectorRequest {+ return {+ id: "connector-1",+ fields: [+ [+ "credentials",+ {+ credentials_provider: ["github"],+ credentials_types: ["api_key"],+ },+ ],+ ],+ selected: {},+ onChange: vi.fn(),+ ...overrides,+ };+}++function mcpRequest(+ overrides: Partial<McpConnectorRequest> = {},+): McpConnectorRequest {+ return {+ id: "mcp-1",+ service: "Notion",+ serverUrl: "https://mcp.notion.com/mcp",+ connected: false,+ loading: false,+ error: null,+ showManualToken: false,+ onConnect: vi.fn(),+ onUseToken: vi.fn(),+ ...overrides,+ };+}++function inputsRequest(overrides: Partial<InputsRequest> = {}): InputsRequest {+ return {+ id: "inputs-1",+ schema: { type: "object", properties: {} },+ values: {},+ onChange: vi.fn(),+ hasAdvanced: false,+ showAdvanced: false,+ onToggleAdvanced: vi.fn(),+ ...overrides,+ };+}++function questionRequest(+ overrides: Partial<QuestionRequest> = {},+): QuestionRequest {+ return {+ id: "questions-1",+ questions: [{ question: "Which region?", keyword: "region" }],+ answers: {},+ onAnswer: vi.fn(),+ onSkip: vi.fn(),+ ...overrides,+ };+}++function renderCard(+ overrides: Partial<React.ComponentProps<typeof ChainActionCard>> = {},+) {+ const onProceed = vi.fn();+ const utils = render(+ <ChainActionCard+ connectors={[]}+ mcp={[]}+ inputs={[]}+ questions={[]}+ isReady+ onProceed={onProceed}+ {...overrides}+ />,+ );+ return { onProceed, ...utils };+}++describe("ChainActionCard", () => {+ it("renders nothing when the chain has nothing to ask", () => {+ const { container } = renderCard();+ expect(container.firstChild).toBeNull();+ });++ it("renders nothing when every ask resolves to nothing actionable", () => {+ const { container } = renderCard({+ connectors: [+ connectorRequest({+ fields: [["credentials", { credentials_types: ["api_key"] }]],+ }),+ ],+ inputs: [inputsRequest({ schema: null, hasAdvanced: false })],+ questions: [questionRequest({ questions: [] })],+ });+ expect(container.firstChild).toBeNull();+ });++ describe("connectors table", () => {+ it("renders a row with the provider name and metadata description", () => {+ renderCard({ connectors: [connectorRequest()] });++ expect(screen.getByText("Plug in what this needs")).toBeDefined();+ expect(screen.getByText("GitHub")).toBeDefined();+ expect(screen.getByText("Connect your GitHub account")).toBeDefined();+ });++ it("opens the connect dialog when Connect is clicked", () => {+ renderCard({ connectors: [connectorRequest()] });++ expect(screen.queryByTestId("connect-dialog-github")).toBeNull();+ fireEvent.click(screen.getByText("Connect"));+ expect(screen.getByTestId("connect-dialog-github")).toBeDefined();+ });++ it("shows Connected instead of the Connect button once a credential is selected", () => {+ renderCard({+ connectors: [+ connectorRequest({+ selected: {+ credentials: {+ id: "cred-1",+ provider: "github",+ type: "api_key",+ },+ },+ }),+ ],+ });++ expect(screen.getByText("Connected")).toBeDefined();+ expect(screen.queryByText("Connect")).toBeNull();+ });++ it("auto-selects a saved credential from the providers context", async () => {+ const request = connectorRequest();+ const providers = {+ github: {+ savedCredentials: [+ {+ id: "saved-1",+ provider: "github",+ type: "api_key",+ title: "My key",+ },+ ],+ },+ } as unknown as CredentialsProvidersContextType;++ render(+ <CredentialsProvidersContext.Provider value={providers}>+ <ChainActionCard+ connectors={[request]}+ mcp={[]}+ inputs={[]}+ questions={[]}+ isReady+ onProceed={vi.fn()}+ />+ </CredentialsProvidersContext.Provider>,+ );++ await waitFor(() =>+ expect(request.onChange).toHaveBeenCalledWith("credentials", {+ id: "saved-1",+ provider: "github",+ type: "api_key",+ title: "My key",+ }),+ );+ });++ it("opens the integrations modal from Browse all connectors", () => {+ renderCard({ connectors: [connectorRequest()] });++ fireEvent.click(screen.getByText("Browse all connectors"));+ expect(mockOpenModal).toHaveBeenCalledWith("integrations");+ });+ });++ describe("MCP rows", () => {+ it("dedupes rows that point at the same server URL", () => {+ renderCard({+ mcp: [+ mcpRequest({ id: "mcp-1" }),+ mcpRequest({ id: "mcp-2", service: "Notion again" }),+ ],+ });++ expect(screen.getByText("Notion")).toBeDefined();+ expect(screen.queryByText("Notion again")).toBeNull();+ });++ it("shows the server host and calls onConnect from the Connect button", () => {+ const request = mcpRequest();+ renderCard({ mcp: [request] });++ expect(screen.getByText("mcp.notion.com")).toBeDefined();+ fireEvent.click(screen.getByText("Connect"));+ expect(request.onConnect).toHaveBeenCalledOnce();+ });++ it("omits the host line when the server URL is not parseable", () => {+ renderCard({ mcp: [mcpRequest({ serverUrl: "not-a-url" })] });++ expect(screen.getByText("Notion")).toBeDefined();+ expect(screen.queryByText("not-a-url")).toBeNull();+ });++ it("disables the button and shows Connecting… while loading", () => {+ renderCard({ mcp: [mcpRequest({ loading: true })] });++ const button = screen.getByText("Connecting…").closest("button");+ expect(button?.disabled).toBe(true);+ });++ it("shows Connected once the server is connected", () => {+ renderCard({ mcp: [mcpRequest({ connected: true })] });++ expect(screen.getByText("Connected")).toBeDefined();+ expect(screen.queryByText("Connect")).toBeNull();+ });++ it("shows the error message while disconnected", () => {+ renderCard({ mcp: [mcpRequest({ error: "OAuth failed" })] });+ expect(screen.getByText("OAuth failed")).toBeDefined();+ });++ it("submits a trimmed manual token via the Use Token button", () => {+ const request = mcpRequest({ showManualToken: true });+ renderCard({ mcp: [request] });++ const useToken = screen.getByText("Use Token").closest("button");+ expect(useToken?.disabled).toBe(true);++ fireEvent.change(screen.getByLabelText("API token for Notion"), {+ target: { value: " secret-token " },+ });+ expect(useToken?.disabled).toBe(false);++ fireEvent.click(useToken!);+ expect(request.onUseToken).toHaveBeenCalledWith("secret-token");+ });++ it("submits the manual token on Enter", () => {+ const request = mcpRequest({ showManualToken: true });+ renderCard({ mcp: [request] });++ const input = screen.getByLabelText("API token for Notion");+ fireEvent.change(input, { target: { value: "secret-token" } });+ fireEvent.keyDown(input, { key: "Enter" });++ expect(request.onUseToken).toHaveBeenCalledWith("secret-token");+ });+ });++ describe("inputs cards", () => {+ it("titles the card by the formatted block name", () => {+ renderCard({+ inputs: [inputsRequest({ title: "SendDiscordMessageBlock" })],+ });++ expect(screen.getByText("Send Discord Message")).toBeDefined();+ expect(screen.getByText("Fill in the details")).toBeDefined();+ });++ it("falls back to a generic title when the request has none", () => {+ renderCard({ inputs: [inputsRequest()] });+ expect(screen.getByText("Fill in the details")).toBeDefined();+ });++ it("forwards form changes to the request", () => {+ const request = inputsRequest();+ renderCard({ inputs: [request] });++ fireEvent.click(screen.getByTestId("form-change"));+ expect(request.onChange).toHaveBeenCalledWith({+ url: "https://test.com",+ });+ });++ it("toggles advanced fields through the request callback", () => {+ const request = inputsRequest({ hasAdvanced: true });+ renderCard({ inputs: [request] });++ fireEvent.click(screen.getByText("Show advanced fields"));+ expect(request.onToggleAdvanced).toHaveBeenCalledOnce();+ });++ it("labels the toggle Hide advanced fields when advanced fields are shown", () => {+ renderCard({+ inputs: [inputsRequest({ hasAdvanced: true, showAdvanced: true })],+ });+ expect(screen.getByText("Hide advanced fields")).toBeDefined();+ });++ it("renders a single Proceed for an inputs-only stack gated on isReady", () => {+ const { onProceed, rerender } = renderCard({+ inputs: [inputsRequest()],+ isReady: false,+ });++ const proceed = screen.getByText("Proceed").closest("button");+ expect(proceed?.disabled).toBe(true);++ rerender(+ <ChainActionCard+ connectors={[]}+ mcp={[]}+ inputs={[inputsRequest()]}+ questions={[]}+ isReady+ onProceed={onProceed}+ />,+ );+ fireEvent.click(screen.getByText("Proceed"));+ expect(onProceed).toHaveBeenCalledOnce();+ });++ it("does not render the lone Proceed when a questions card carries the footer", () => {+ renderCard({+ inputs: [inputsRequest()],+ questions: [questionRequest()],+ });+ expect(screen.queryByText("Proceed")).toBeNull();+ });+ });++ describe("questions stepper", () => {+ const twoQuestions = [+ { question: "Which region?", keyword: "region" },+ { question: "Which format?", keyword: "format", example: "CSV" },+ ];++ it("gates the action button on the current answer", () => {+ renderCard({ questions: [questionRequest({ questions: twoQuestions })] });++ expect(screen.getByText("Answer a few questions")).toBeDefined();+ expect(screen.getByText("Which region?")).toBeDefined();++ const nextButtons = screen.getAllByRole("button", {+ name: "Next question",+ }) as HTMLButtonElement[];+ // The round action is answer-gated; the pager chevron is not.+ expect(nextButtons.filter((button) => button.disabled)).toHaveLength(1);+ });++ it("advances to the next question once answered", () => {+ renderCard({+ questions: [+ questionRequest({+ questions: twoQuestions,+ answers: { region: "Europe" },+ }),+ ],+ });++ const [action] = (+ screen.getAllByRole("button", {+ name: "Next question",+ }) as HTMLButtonElement[]+ ).filter((button) => !button.disabled);+ fireEvent.click(action);++ expect(screen.getByText("Which format?")).toBeDefined();+ expect(screen.getByPlaceholderText("e.g. CSV")).toBeDefined();+ });++ it("navigates with the dots and the back chevron", () => {+ renderCard({+ questions: [+ questionRequest({+ questions: twoQuestions,+ answers: { region: "Europe", format: "CSV" },+ }),+ ],+ });++ const back = screen.getByRole("button", {+ name: "Previous question",+ }) as HTMLButtonElement;+ expect(back.disabled).toBe(true);++ fireEvent.click(screen.getByRole("button", { name: "Go to question 2" }));+ expect(screen.getByText("Which format?")).toBeDefined();++ fireEvent.click(+ screen.getByRole("button", { name: "Previous question" }),+ );+ expect(screen.getByText("Which region?")).toBeDefined();+ });++ it("skips every request from the Skip button", () => {+ const first = questionRequest({ id: "q-1" });+ const second = questionRequest({+ id: "q-2",+ questions: [{ question: "Which format?", keyword: "format" }],+ });+ renderCard({ questions: [first, second] });++ fireEvent.click(screen.getByText("Skip"));+ expect(first.onSkip).toHaveBeenCalledOnce();+ expect(second.onSkip).toHaveBeenCalledOnce();+ });++ it("forwards typing to the request's onAnswer", () => {+ const request = questionRequest();+ renderCard({ questions: [request] });++ fireEvent.change(screen.getByPlaceholderText("Type your answer"), {+ target: { value: "Europe" },+ });+ expect(request.onAnswer).toHaveBeenCalledWith("region", "Europe");+ });++ it("disables the send button until every answer is filled", () => {+ renderCard({ questions: [questionRequest()] });++ const send = screen.getByRole("button", {+ name: "Add answers to message",+ }) as HTMLButtonElement;+ expect(send.disabled).toBe(true);+ });++ it("drafts the answers on the last step when every answer is filled", () => {+ const { onProceed } = renderCard({+ questions: [questionRequest({ answers: { region: "Europe" } })],+ });++ fireEvent.click(+ screen.getByRole("button", { name: "Add answers to message" }),+ );+ expect(onProceed).toHaveBeenCalledOnce();+ });++ it("submits the last step on Enter", () => {+ const { onProceed } = renderCard({+ questions: [questionRequest({ answers: { region: "Europe" } })],+ });++ fireEvent.keyDown(screen.getByDisplayValue("Europe"), { key: "Enter" });+ expect(onProceed).toHaveBeenCalledOnce();+ });++ it("keeps the questions card sendable when an unready sibling exists", () => {+ // An unconnected MCP row must not freeze the questions footer.+ const { onProceed } = renderCard({+ mcp: [mcpRequest()],+ questions: [questionRequest({ answers: { region: "Europe" } })],+ isReady: false,+ });++ fireEvent.click(+ screen.getByRole("button", { name: "Add answers to message" }),+ );+ expect(onProceed).toHaveBeenCalledOnce();+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.test.tsnew file mode 100644index 0000000000..0e4a4d73e5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.test.ts@@ -0,0 +1,156 @@+import type { ProviderMetadata } from "@/app/api/__generated__/models/providerMetadata";+import { describe, expect, it, vi } from "vitest";+import {+ formatInputsTitle,+ toConnectorRows,+ type ConnectorRequest,+} from "../helpers";++function connectorRequest(+ overrides: Partial<ConnectorRequest> = {},+): ConnectorRequest {+ return {+ id: "req-1",+ fields: [+ [+ "credentials",+ {+ credentials_provider: ["github"],+ credentials_types: ["api_key"],+ },+ ],+ ],+ selected: {},+ onChange: vi.fn(),+ ...overrides,+ };+}++describe("formatInputsTitle", () => {+ it("converts a block class name to spaced words without the Block suffix", () => {+ expect(formatInputsTitle("SendDiscordMessageBlock")).toBe(+ "Send Discord Message",+ );+ });++ it("converts underscores to spaces", () => {+ expect(formatInputsTitle("my_agent_name")).toBe("my agent name");+ });++ it("passes agent names with regular spacing through unchanged", () => {+ expect(formatInputsTitle("Market Research Agent")).toBe(+ "Market Research Agent",+ );+ });++ it("falls back to the original name when stripping leaves nothing", () => {+ expect(formatInputsTitle("Block")).toBe("Block");+ });+});++describe("toConnectorRows", () => {+ it("merges requests asking for the same provider into one row", () => {+ const first = connectorRequest({ id: "req-1" });+ const second = connectorRequest({ id: "req-2" });++ const rows = toConnectorRows([first, second], []);++ expect(rows).toHaveLength(1);+ expect(rows[0].provider).toBe("github");+ });++ it("fans a selection out to every request asking for the provider", () => {+ const first = connectorRequest({ id: "req-1" });+ const second = connectorRequest({ id: "req-2" });+ const credential = {+ id: "cred-1",+ provider: "github",+ type: "api_key" as const,+ };++ const [row] = toConnectorRows([first, second], []);+ row.select(credential);++ expect(first.onChange).toHaveBeenCalledWith("credentials", credential);+ expect(second.onChange).toHaveBeenCalledWith("credentials", credential);+ });++ it("drops fields whose provider cannot be resolved", () => {+ const request = connectorRequest({+ fields: [["credentials", { credentials_types: ["api_key"] }]],+ });++ expect(toConnectorRows([request], [])).toHaveLength(0);+ });++ it("prefers the provider metadata description over the schema description", () => {+ const request = connectorRequest({+ fields: [+ [+ "credentials",+ {+ credentials_provider: ["github"],+ description: "From the schema",+ },+ ],+ ],+ });+ const providers: ProviderMetadata[] = [+ { name: "github", description: "From the metadata" },+ ];++ const [row] = toConnectorRows([request], providers);++ expect(row.description).toBe("From the metadata");+ expect(row.displayName).toBe("GitHub");+ });++ it("falls back to the schema description, then to null", () => {+ const withSchemaDescription = connectorRequest({+ fields: [+ [+ "credentials",+ {+ credentials_provider: ["github"],+ description: "From the schema",+ },+ ],+ ],+ });+ expect(toConnectorRows([withSchemaDescription], [])[0].description).toBe(+ "From the schema",+ );++ const withoutDescription = connectorRequest();+ expect(toConnectorRows([withoutDescription], [])[0].description).toBeNull();+ });++ it("keeps the first selected credential for the provider", () => {+ const credential = {+ id: "cred-1",+ provider: "github",+ type: "api_key" as const,+ };+ const withSelection = connectorRequest({+ id: "req-1",+ selected: { credentials: credential },+ });+ const withoutSelection = connectorRequest({ id: "req-2" });++ const [row] = toConnectorRows([withSelection, withoutSelection], []);++ expect(row.selected).toEqual(credential);+ });++ it("formats unknown provider slugs into title case display names", () => {+ const request = connectorRequest({+ fields: [+ ["credentials", { credentials_provider: ["my_custom_service"] }],+ ],+ });++ expect(toConnectorRows([request], [])[0].displayName).toBe(+ "My Custom Service",+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.tsnew file mode 100644index 0000000000..2a9375a31d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts@@ -0,0 +1,113 @@+import type { ProviderMetadata } from "@/app/api/__generated__/models/providerMetadata";+import type { CredentialField } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";+import { formatProviderName } from "@/components/contextual/IntegrationsPanel/helpers";+import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";+import type { RJSFSchema } from "@rjsf/utils";+import type { ClarifyingQuestion } from "../../tools/clarifying-questions";++/** One question card's ask. The card owns the inputs; the asking component+ * keeps the answers so it can still build its own message. */+export interface QuestionRequest {+ id: string;+ questions: ClarifyingQuestion[];+ answers: Record<string, string>;+ onAnswer: (keyword: string, value: string) => void;+ onSkip: () => void;+}++/** One setup card's editable run inputs, lifted out of the chain rows into+ * its own card below the chain — one card per block/agent, titled by it. */+export interface InputsRequest {+ id: string;+ title?: string;+ schema: RJSFSchema | null;+ values: Record<string, unknown>;+ onChange: (values: Record<string, unknown>) => void;+ hasAdvanced: boolean;+ showAdvanced: boolean;+ onToggleAdvanced: () => void;+}++/** "SendDiscordMessageBlock" → "Send Discord Message". Agent names with+ * regular spacing pass through unchanged. */+export function formatInputsTitle(name: string): string {+ const spaced = name+ .replace(/Block$/, "")+ .replace(/_/g, " ")+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .trim();+ return spaced || name;+}++/** One MCP server's ask. Unlike ConnectorRequest, MCP servers aren't+ * platform providers — the hidden MCPSetupCard keeps the OAuth/token state+ * machine and hands the table row its state + callbacks. */+export interface McpConnectorRequest {+ id: string;+ service: string;+ serverUrl: string;+ connected: boolean;+ loading: boolean;+ error: string | null;+ showManualToken: boolean;+ onConnect: () => void;+ onUseToken: (token: string) => void;+}++/** One setup card's ask, handed to the chain so every card in the chain can+ * be answered from a single connectors table. */+export interface ConnectorRequest {+ id: string;+ fields: CredentialField[];+ selected: Record<string, CredentialsMetaInput | undefined>;+ onChange: (key: string, value?: CredentialsMetaInput) => void;+}++export interface ConnectorRow {+ provider: string;+ displayName: string;+ description: string | null;+ schema: CredentialField[1];+ selected?: CredentialsMetaInput;+ select: (value?: CredentialsMetaInput) => void;+}++/** Flattens every request into one row per provider: two tools asking for+ * GitHub is one "Connect GitHub", and connecting it answers both. Fields+ * whose provider can't be resolved are dropped — nothing to connect. */+export function toConnectorRows(+ requests: ConnectorRequest[],+ providers: ProviderMetadata[],+): ConnectorRow[] {+ const byName = new Map(providers.map((p) => [p.name, p]));+ const rows = new Map<+ string,+ {+ schema: CredentialField[1];+ selected?: CredentialsMetaInput;+ targets: { request: ConnectorRequest; key: string }[];+ }+ >();++ for (const request of requests) {+ for (const [key, schema] of request.fields) {+ const provider = schema.credentials_provider?.[0];+ if (!provider) continue;+ const row = rows.get(provider) ?? { schema, targets: [] };+ row.targets.push({ request, key });+ row.selected = row.selected ?? request.selected[key];+ rows.set(provider, row);+ }+ }++ return [...rows.entries()].map(([provider, row]) => ({+ provider,+ displayName: formatProviderName(provider),+ description:+ byName.get(provider)?.description ?? row.schema.description ?? null,+ schema: row.schema,+ selected: row.selected,+ select: (value?: CredentialsMetaInput) =>+ row.targets.forEach(({ request, key }) => request.onChange(key, value)),+ }));+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex aed28c74a8..b31f51e829 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -14,6 +14,8 @@ import type { WorkspaceAttachment } from "../../helpers/workspaceAttachments";import { ChatMessagesContainer } from "../ChatMessagesContainer/ChatMessagesContainer";import { CopilotChatActionsProvider } from "../CopilotChatActionsProvider/CopilotChatActionsProvider";import { EmptySession } from "../EmptySession/EmptySession";+import { getPendingQuestions } from "../QuestionDock/helpers";+import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContext";import { UsageLimitReachedCard } from "../UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard";import { useIsUsageLimitReached } from "../UsageLimits/useIsUsageLimitReached";import { TaskProgressBar } from "../TaskProgressBar/TaskProgressBar";@@ -121,6 +123,9 @@ export const ChatContainer = ({}: ChatContainerProps) => {const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS);const isTaskBarEnabled = useGetFlag(Flag.TASK_PROGRESS_BAR);+ // Old tool UI keeps its interactive in-transcript question card; the dock+ // is the new-UI answering surface, so gate it to avoid double forms.+ const isNewToolUI = useGetFlag(Flag.NEW_TOOL_UI);useAutoOpenArtifacts({sessionId,messages,@@ -218,113 +223,118 @@ export const ChatContainer = ({return (<CopilotChatActionsProvider onSend={guardedOnSend}>- <LayoutGroup id="copilot-2-chat-layout">- <div className="flex h-full min-h-0 w-full flex-col px-2 lg:px-0">- {/* The chat column runs full width: the max-w-3xl cap lives on the- message list and the input instead, so the expert thread header- can span edge to edge while staying aligned with the messages. */}- {sessionId ? (- <div className="flex h-full min-h-0 w-full flex-col bg-[#fafafa]">- <ChatMessagesContainer- messages={messages}- status={status}- error={error}- isLoading={isLoadingSession}- isRestoringActiveSession={isRestoringActiveSession}- restoreStatusMessage={restoreStatusMessage}- activeStreamStartedAt={activeStreamStartedAt}- sessionID={sessionId}- sessionChatStatus={sessionChatStatus}- hasMoreMessages={hasMoreMessages}- isLoadingMore={isLoadingMore}- onLoadMore={onLoadMore}- onRetry={handleRetry}- turnStats={turnStats}- queuedMessages={queuedMessages}- bottomContentPadding={usageCardHeight}- expertIdentity={expertIdentity}- />- {archivedExpertIdentity ? (- <ArchivedExpertNotice- expertName={archivedExpertIdentity.name}- reason={archivedExpertIdentity.readOnlyReason ?? "fired"}+ <PendingQuestionsContext.Provider+ value={isNewToolUI ? getPendingQuestions(messages) : null}+ >+ <LayoutGroup id="copilot-2-chat-layout">+ <div className="flex h-full min-h-0 w-full flex-col px-2 lg:px-0">+ {/* The chat column runs full width: the max-w-3xl cap lives on the+ message list and the input instead, so the expert thread header+ can span edge to edge while staying aligned with the messages. */}+ {sessionId ? (+ <div className="flex h-full min-h-0 w-full flex-col bg-[#fafafa]">+ <ChatMessagesContainer+ messages={messages}+ status={status}+ error={error}+ isLoading={isLoadingSession}+ isRestoringActiveSession={isRestoringActiveSession}+ restoreStatusMessage={restoreStatusMessage}+ activeStreamStartedAt={activeStreamStartedAt}+ sessionID={sessionId}+ sessionChatStatus={sessionChatStatus}+ hasMoreMessages={hasMoreMessages}+ isLoadingMore={isLoadingMore}+ onLoadMore={onLoadMore}+ onRetry={handleRetry}+ turnStats={turnStats}+ queuedMessages={queuedMessages}+ bottomContentPadding={usageCardHeight}+ expertIdentity={expertIdentity}/>- ) : (- <motion.div- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{ duration: 0.3 }}- className="relative mx-auto w-full max-w-3xl px-3 pb-6 pt-2"- >- {isLimitReached && (- <div- ref={usageCardRef}- className="pointer-events-none absolute bottom-full left-0 right-0 z-20 mb-2.5 pb-2"- >+ {archivedExpertIdentity ? (+ <ArchivedExpertNotice+ expertName={archivedExpertIdentity.name}+ reason={archivedExpertIdentity.readOnlyReason ?? "fired"}+ />+ ) : (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{ duration: 0.3 }}+ className="relative mx-auto w-full max-w-3xl px-3 pb-6 pt-2"+ >+ {isLimitReached && (<div- aria-hidden="true"- data-testid="usage-limit-backdrop"- className="absolute -inset-x-14 -top-20 bottom-[-18px] overflow-hidden rounded-[2rem] bg-[radial-gradient(ellipse_at_center,rgba(250,250,250,0.96)_0%,rgba(250,250,250,0.9)_42%,rgba(250,250,250,0.58)_68%,rgba(250,250,250,0)_100%)] backdrop-blur-lg [mask-image:linear-gradient(to_bottom,transparent_0%,black_26%,black_100%)]"+ ref={usageCardRef}+ className="pointer-events-none absolute bottom-full left-0 right-0 z-20 mb-2.5 pb-2">- <div className="absolute inset-x-10 bottom-0 h-28 rounded-full bg-[#fafafa]/80 blur-2xl" />- <div className="absolute inset-x-16 bottom-8 h-16 rounded-full bg-white/55 blur-xl" />- </div>- <div className="pointer-events-auto relative px-3">- <UsageLimitReachedCard />+ <div+ aria-hidden="true"+ data-testid="usage-limit-backdrop"+ className="absolute -inset-x-14 -top-20 bottom-[-18px] overflow-hidden rounded-[2rem] bg-[radial-gradient(ellipse_at_center,rgba(250,250,250,0.96)_0%,rgba(250,250,250,0.9)_42%,rgba(250,250,250,0.58)_68%,rgba(250,250,250,0)_100%)] backdrop-blur-lg [mask-image:linear-gradient(to_bottom,transparent_0%,black_26%,black_100%)]"+ >+ <div className="absolute inset-x-10 bottom-0 h-28 rounded-full bg-[#fafafa]/80 blur-2xl" />+ <div className="absolute inset-x-16 bottom-8 h-16 rounded-full bg-white/55 blur-xl" />+ </div>+ <div className="pointer-events-auto relative px-3">+ <UsageLimitReachedCard />+ </div></div>- </div>- )}- <SharedChatNotice sessionId={sessionId} />- {isTaskBarEnabled && (- <div className="relative z-10">- <TaskProgressBar- todos={getLatestTaskList(messages) ?? []}- isStreaming={isStreaming}- />- </div>- )}- <Tooltip open={isLimitReached ? undefined : false}>- <TooltipTrigger asChild>- <div>- <ChatInput- inputId="chat-input-session"- onSend={guardedOnSend}- disabled={isInputDisabled}+ )}+ <SharedChatNotice sessionId={sessionId} />+ {isTaskBarEnabled && (+ <div className="relative z-10">+ <TaskProgressBar+ todos={getLatestTaskList(messages) ?? []}isStreaming={isStreaming}- isUploadingFiles={isUploadingFiles}- onStop={onStop}- onEnqueue={onEnqueue}- placeholder="What else can I help with?"- droppedFiles={droppedFiles}- onDroppedFilesConsumed={onDroppedFilesConsumed}- hasSession={!!sessionId}/></div>- </TooltipTrigger>- <TooltipContent side="top" className="max-w-sm">- You've reached your usage limit. Wait for it to- refresh or upgrade your plan to continue sending messages.- </TooltipContent>- </Tooltip>- </motion.div>- )}- </div>- ) : (- <EmptySession- inputLayoutId={inputLayoutId}- isCreatingSession={isCreatingSession}- onCreateSession={onCreateSession}- onSend={guardedOnSend}- isUploadingFiles={isUploadingFiles}- droppedFiles={droppedFiles}- onDroppedFilesConsumed={onDroppedFilesConsumed}- isInteractionLocked={isSendLocked || !!isAdoptingExpertSession}- isKickoffStarting={isKickoffStarting}- expertName={expertIdentity?.name}- />- )}- </div>- </LayoutGroup>+ )}+ <Tooltip open={isLimitReached ? undefined : false}>+ <TooltipTrigger asChild>+ <div>+ <ChatInput+ inputId="chat-input-session"+ onSend={guardedOnSend}+ disabled={isInputDisabled}+ isStreaming={isStreaming}+ isUploadingFiles={isUploadingFiles}+ onStop={onStop}+ onEnqueue={onEnqueue}+ placeholder="What else can I help with?"+ droppedFiles={droppedFiles}+ onDroppedFilesConsumed={onDroppedFilesConsumed}+ hasSession={!!sessionId}+ />+ </div>+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-sm">+ You've reached your usage limit. Wait for it to+ refresh or upgrade your plan to continue sending+ messages.+ </TooltipContent>+ </Tooltip>+ </motion.div>+ )}+ </div>+ ) : (+ <EmptySession+ inputLayoutId={inputLayoutId}+ isCreatingSession={isCreatingSession}+ onCreateSession={onCreateSession}+ onSend={guardedOnSend}+ isUploadingFiles={isUploadingFiles}+ droppedFiles={droppedFiles}+ onDroppedFilesConsumed={onDroppedFilesConsumed}+ isInteractionLocked={isSendLocked || !!isAdoptingExpertSession}+ isKickoffStarting={isKickoffStarting}+ expertName={expertIdentity?.name}+ />+ )}+ </div>+ </LayoutGroup>+ </PendingQuestionsContext.Provider></CopilotChatActionsProvider>);};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsxindex 552322648e..a78d255c47 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx@@ -80,6 +80,8 @@ vi.mock("@/app/(platform)/copilot/store", () => ({setIsDryRun: vi.fn(),initialPrompt: mockInitialPrompt,setInitialPrompt: mockSetInitialPrompt,+ sentMessageCount: 0,+ notifyMessageSent: vi.fn(),}),}));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 7d42e67dbb..c4fa218b15 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@@ -20,7 +20,8 @@ export function useChatInput({// Synchronous guard against double-submit — refs update immediately,// unlike state which batches and can leave a gap for a second call.const isSubmittingRef = useRef(false);- const { initialPrompt, setInitialPrompt } = useCopilotUIStore();+ const { initialPrompt, setInitialPrompt, notifyMessageSent } =+ useCopilotUIStore();useEffect(function consumeInitialPrompt() {@@ -67,6 +68,7 @@ export function useChatInput({try {await onSend(trimmedMessage);setValue("");+ notifyMessageSent();} finally {isSubmittingRef.current = false;setIsSending(false);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex dfc064b026..5d731ced41 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -35,6 +35,7 @@ import type { ExpertIdentity } from "../../useExpertMap";import { WorkCard } from "../WorkCard/WorkCard";import { getWorkRunMetadata, toPreview } from "../WorkCard/helpers";import { AssistantMessageActions } from "./components/AssistantMessageActions";+import { ChainMessageParts } from "./components/ChainMessageParts";import { CopyButton } from "./components/CopyButton";import { CollapsedToolGroup } from "./components/CollapsedToolGroup";import { ExpertAvatar } from "./components/ExpertAvatar/ExpertAvatar";@@ -46,6 +47,7 @@ import { ReasoningGroup } from "./components/ReasoningGroup";import { StepsCollapse } from "./components/StepsCollapse";import { TaskListNotice } from "./components/TaskListNotice";import { ThinkingIndicator } from "./components/ThinkingIndicator";+import { UserMessageClamp } from "./components/UserMessageClamp";import { getLatestTaskList } from "../TaskProgressBar/helpers";import { Clock01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";@@ -344,6 +346,7 @@ export function ChatMessagesContainer({const isContextPanelEnabled = useGetFlag(Flag.ARTIFACTS);// Bubble restyle ships with the brain-dump experience.const isBrainDumpEnabled = useGetFlag(Flag.ONBOARDING_BRAIN_DUMP);+ const isNewToolUI = useGetFlag(Flag.NEW_TOOL_UI);const isChatStreaming = status === "streaming" || status === "submitted";const hasActiveTaskList =!isTaskBarEnabled &&@@ -472,6 +475,7 @@ export function ChatMessagesContainer({active={showThinking}elapsedSeconds={elapsedSeconds}statusMessage={latestStatusMessage}+ variant={isNewToolUI ? "chain" : "legacy"}/>);const showIndicator = showThinking;@@ -637,8 +641,12 @@ export function ChatMessagesContainer({// For finalized assistant messages, split into reasoning + response.// During streaming, show everything normally with tool collapsing.+ // The new tool UI renders chains inline instead, so it skips the+ // reasoning split (and its "Show steps" modal) entirely.const isFinalized =- message.role === "assistant" && !isCurrentlyStreaming;+ !isNewToolUI &&+ message.role === "assistant" &&+ !isCurrentlyStreaming;const { reasoning, response } = isFinalized? splitReasoningAndResponse(renderableParts): { reasoning: [] as MessagePart[], response: renderableParts };@@ -669,7 +677,12 @@ export function ChatMessagesContainer({? "group-[.is-user]:rounded-3xl group-[.is-user]:bg-gradient-to-br group-[.is-user]:from-[#f3edff] group-[.is-user]:to-[#e4d4ff] group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-[#3b1e75] group-[.is-user]:[border-bottom-right-radius:0.5rem] ": "group-[.is-user]:rounded-xl group-[.is-user]:bg-purple-100 group-[.is-user]:px-3 group-[.is-user]:py-2.5 group-[.is-user]:text-slate-900 group-[.is-user]:[border-bottom-right-radius:0] ") +"group-[.is-user]:[&_h1]:text-lg group-[.is-user]:[&_h1]:font-semibold group-[.is-user]:[&_h2]:text-lg group-[.is-user]:[&_h2]:font-semibold group-[.is-user]:[&_h3]:text-lg group-[.is-user]:[&_h3]:font-semibold group-[.is-user]:[&_h4]:text-lg group-[.is-user]:[&_h4]:font-semibold group-[.is-user]:[&_h5]:text-lg group-[.is-user]:[&_h5]:font-semibold group-[.is-user]:[&_h6]:text-lg group-[.is-user]:[&_h6]:font-semibold " +- "group-[.is-assistant]:bg-transparent group-[.is-assistant]:text-slate-900"+ "group-[.is-assistant]:bg-transparent group-[.is-assistant]:text-slate-900" ++ // Chain hover pills use negative margins that the base+ // overflow-hidden would clip.+ (isNewToolUI+ ? " group-[.is-assistant]:overflow-visible"+ : "")}>{hasReasoning && reasoningSegments && (@@ -681,14 +694,26 @@ export function ChatMessagesContainer({})}</StepsCollapse>)}- {responseSegments- ? renderSegments(responseSegments, message.id, {- onRetry: isLastAssistant ? onRetry : undefined,- fileUrlBuilder,- forceArtifacts: readOnly,- readOnly,- })- : renderableParts.map((part, i) => (+ {isAssistant && isNewToolUI ? (+ <ChainMessageParts+ parts={renderableParts}+ messageID={message.id}+ isCurrentlyStreaming={isCurrentlyStreaming}+ onRetry={isLastAssistant ? onRetry : undefined}+ fileUrlBuilder={fileUrlBuilder}+ forceArtifacts={readOnly}+ readOnly={readOnly}+ />+ ) : responseSegments ? (+ renderSegments(responseSegments, message.id, {+ onRetry: isLastAssistant ? onRetry : undefined,+ fileUrlBuilder,+ forceArtifacts: readOnly,+ readOnly,+ })+ ) : (+ (() => {+ const parts = renderableParts.map((part, i) => (<MessagePartRendererkey={`${message.id}-${i}`}part={part}@@ -699,7 +724,14 @@ export function ChatMessagesContainer({forceArtifacts={readOnly}readOnly={readOnly}/>- ))}+ ));+ return isNewToolUI ? (+ <UserMessageClamp>{parts}</UserMessageClamp>+ ) : (+ parts+ );+ })()+ )}{isLastInTurn && !isCurrentlyStreaming && (<TurnStatsBarturnMessages={getTurnMessages(messages, messageIndex)}@@ -802,6 +834,7 @@ export function ChatMessagesContainer({statusMessage={restoreStatusMessage ?? "Reconnecting to live stream..."}+ variant={isNewToolUI ? "chain" : "legacy"}/><span className="pl-6 text-xs text-slate-400">Still syncing the latest progress.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsxindex 07e80df8f0..2fe818106c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx@@ -4,6 +4,20 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ChatMessagesContainer } from "../ChatMessagesContainer";import { buildKickoffMessage } from "../../../expertKickoff";+const flagState = vi.hoisted(() => ({ newToolUI: false }));++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return {+ ...actual,+ useGetFlag: (flag: string) =>+ flag === actual.Flag.NEW_TOOL_UI ? flagState.newToolUI : false,+ };+});+const mockScrollEl = {scrollHeight: 100,scrollTop: 0,@@ -58,6 +72,9 @@ vi.mock("@/components/ai-elements/message", () => ({vi.mock("../components/AssistantMessageActions", () => ({AssistantMessageActions: () => null,}));+vi.mock("../components/ChainMessageParts", () => ({+ ChainMessageParts: () => <div data-testid="chain-message-parts" />,+}));vi.mock("../components/QueueBadge", () => ({QueueBadge: ({ sessionID }: { sessionID: string | null }) => (@@ -85,6 +102,9 @@ vi.mock("../components/ThinkingIndicator", () => ({<div data-testid="thinking-indicator">{statusMessage ?? "thinking"}</div>),}));+vi.mock("../../ToolChain/ToolChain", () => ({+ ToolChain: () => <div data-testid="tool-chain" />,+}));vi.mock("../../JobStatsBar/TurnStatsBar", () => ({TurnStatsBar: () => null,}));@@ -98,6 +118,7 @@ vi.mock("../../CopilotPendingReviews/CopilotPendingReviews", () => ({vi.mock("../helpers", () => ({buildRenderSegments: () => [],getTurnMessages: () => [],+ isChainableToolPart: () => false,parseSpecialMarkers: (text: string) => {if (typeof text === "string" && text.startsWith("[__COPILOT_ERROR_")) {return { markerType: "error" };@@ -155,6 +176,37 @@ const baseProps = {onRetry: vi.fn(),};+describe("ChatMessagesContainer — tool UI dispatch", () => {+ const messages = [+ {+ id: "assistant-tools",+ role: "assistant" as const,+ parts: [{ type: "text" as const, text: "Done" }],+ },+ ];++ afterEach(() => {+ flagState.newToolUI = false;+ cleanup();+ });++ it("uses chain rendering when the new tool UI flag is enabled", () => {+ flagState.newToolUI = true;++ render(<ChatMessagesContainer {...baseProps} messages={messages} />);++ expect(screen.getByTestId("chain-message-parts")).toBeDefined();+ });++ it("keeps the legacy renderer when the flag is off", () => {+ flagState.newToolUI = false;++ render(<ChatMessagesContainer {...baseProps} messages={messages} />);++ expect(screen.queryByTestId("chain-message-parts")).toBeNull();+ });+});+// ── queued-messages rendering ─────────────────────────────────────────────describe("ChatMessagesContainer — queuedMessages", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsxnew file mode 100644index 0000000000..08237a122f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx@@ -0,0 +1,59 @@+import { isChainableToolPart, type MessagePart } from "../helpers";+import { buildChainSegments } from "../../ToolChain/helpers";+import { ToolChain } from "../../ToolChain/ToolChain";+import { MessagePartRenderer } from "./MessagePartRenderer";++interface Props {+ parts: MessagePart[];+ messageID: string;+ isCurrentlyStreaming: boolean;+ onRetry?: () => void;+ fileUrlBuilder?: (fileId: string) => string;+ forceArtifacts?: boolean;+ readOnly?: boolean;+}++export function ChainMessageParts({+ parts,+ messageID,+ isCurrentlyStreaming,+ onRetry,+ fileUrlBuilder,+ forceArtifacts,+ readOnly,+}: Props) {+ const segments = buildChainSegments(+ parts,+ isChainableToolPart,+ isCurrentlyStreaming,+ );+ const lastChainSegmentIndex = segments.findLastIndex(+ (segment) => segment.kind === "chain",+ );++ return segments.map((segment, segmentIndex) => {+ if (segment.kind === "chain") {+ return (+ <ToolChain+ key={`${messageID}-chain-${segment.index}`}+ parts={segment.parts}+ isStreaming={+ isCurrentlyStreaming && segmentIndex === lastChainSegmentIndex+ }+ />+ );+ }+ return (+ <MessagePartRenderer+ key={`${messageID}-${segment.index}`}+ part={segment.part}+ messageID={messageID}+ partIndex={segment.index}+ onRetry={onRetry}+ fileUrlBuilder={fileUrlBuilder}+ forceArtifacts={forceArtifacts}+ readOnly={readOnly}+ />+ );+ });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsxindex 3f02acc7d4..2a942f2804 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx@@ -82,26 +82,46 @@ function TextWithArtifactCards({readOnly?: boolean;}) {const isArtifactsFlagEnabled = useGetFlag(Flag.ARTIFACTS);+ const isNewToolUI = useGetFlag(Flag.NEW_TOOL_UI);const isArtifactsEnabled = forceArtifacts || isArtifactsFlagEnabled;const artifacts = extractWorkspaceArtifacts(text, fileUrlBuilder);const resolved = resolveWorkspaceUrls(text, fileUrlBuilder);- return (+ const artifactCards = isArtifactsEnabled && artifacts.length > 0 && (+ <div+ className={+ isNewToolUI ? "mt-2 flex flex-col gap-1" : "mb-2 flex flex-col gap-1"+ }+ >+ {artifacts.map((artifact) => (+ <ArtifactCard+ key={artifact.id}+ artifact={artifact}+ readOnly={readOnly}+ />+ ))}+ </div>+ );+ const response = (+ <MessageResponse+ components={STREAMDOWN_COMPONENTS}+ className={isNewToolUI ? "[&_li]:py-0" : undefined}+ >+ {resolved}+ </MessageResponse>+ );++ // New tool UI reads text-first with artifacts trailing; the legacy layout+ // leads with the artifact cards.+ return isNewToolUI ? (+ <>+ {response}+ {artifactCards}+ </>+ ) : (<>- {isArtifactsEnabled && artifacts.length > 0 && (- <div className="mb-2 flex flex-col gap-1">- {artifacts.map((artifact) => (- <ArtifactCard- key={artifact.id}- artifact={artifact}- readOnly={readOnly}- />- ))}- </div>- )}- <MessageResponse components={STREAMDOWN_COMPONENTS}>- {resolved}- </MessageResponse>+ {artifactCards}+ {response}</>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThinkingIndicator.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThinkingIndicator.tsxindex b0d31ec391..900addf5e4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThinkingIndicator.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThinkingIndicator.tsx@@ -1,6 +1,8 @@import { useEffect, useRef, useState } from "react";import { formatElapsed } from "../../JobStatsBar/formatElapsed";+import { PixelGridLoader } from "../../PixelGridLoader/PixelGridLoader";import { ScaleLoader } from "../../ScaleLoader/ScaleLoader";+import { SwapText } from "../../ToolChain/SwapText";const THINKING_PHRASES = ["Thinking...",@@ -81,18 +83,46 @@ interface Props {* Backend-emitted status message for the current silent gap (e.g.* "Reading your message…", "Analyzing result…", "Optimizing conversation* context…"). When provided, it replaces the rotating generic phrase so- * the user sees what's actually happening instead of a placeholder.+ * the user sees what's actually happening instead of a placeholder. In+ * the chain variant an absent message shows no label at all rather than+ * inventing a generic placeholder.*/statusMessage?: string | null;+ /** "chain" is the NEW_TOOL_UI pixel-loader look; "legacy" (default)+ * keeps the original rotating-phrase indicator. */+ variant?: "legacy" | "chain";}export function ThinkingIndicator({active,elapsedSeconds,statusMessage,+ variant = "legacy",}: Props) {const { phrase, visible } = useCyclingPhrase(active);const showTime = active && elapsedSeconds >= SHOW_TIME_AFTER_SECONDS;++ if (variant === "chain") {+ return (+ <span+ role="status"+ aria-live="polite"+ className="inline-flex w-fit items-center gap-2.5 text-sm text-zinc-600"+ >+ <PixelGridLoader className="text-zinc-600" />+ {statusMessage && (+ <SwapText text={statusMessage} shimmer className="text-sm" />+ )}+ {!statusMessage && <span className="sr-only">Thinking…</span>}+ {showTime && (+ <span className="font-mono text-xs tabular-nums text-zinc-400">+ {formatElapsed(elapsedSeconds)}+ </span>+ )}+ </span>+ );+ }+const displayText = statusMessage || phrase;const transitionOpacity = statusMessage ? 1 : visible ? 1 : 0;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/UserMessageClamp.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/UserMessageClamp.tsxnew file mode 100644index 0000000000..fb97b01851--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/UserMessageClamp.tsx@@ -0,0 +1,34 @@+import { useLayoutEffect, useRef, useState } from "react";++interface Props {+ children: React.ReactNode;+}++export function UserMessageClamp({ children }: Props) {+ const contentRef = useRef<HTMLDivElement>(null);+ const [isOverflowing, setIsOverflowing] = useState(false);+ const [expanded, setExpanded] = useState(false);++ useLayoutEffect(() => {+ const el = contentRef.current;+ if (!el || expanded) return;+ setIsOverflowing(el.scrollHeight > el.clientHeight + 1);+ }, [expanded, children]);++ return (+ <div>+ <div ref={contentRef} className={expanded ? undefined : "line-clamp-6"}>+ {children}+ </div>+ {(isOverflowing || expanded) && (+ <button+ type="button"+ className="mt-1 text-xs font-medium text-purple-700 hover:underline"+ onClick={() => setExpanded(!expanded)}+ >+ {expanded ? "Show less" : "Read more"}+ </button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessageParts.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessageParts.test.tsxnew file mode 100644index 0000000000..94aa58c0dc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessageParts.test.tsx@@ -0,0 +1,43 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { MessagePart } from "../../helpers";+import { ChainMessageParts } from "../ChainMessageParts";++vi.mock("../../../ToolChain/ToolChain", () => ({+ ToolChain: ({ isStreaming }: { isStreaming: boolean }) => (+ <div data-testid="tool-chain" data-streaming={String(isStreaming)} />+ ),+}));++vi.mock("../MessagePartRenderer", () => ({+ MessagePartRenderer: () => <div data-testid="message-part" />,+}));++describe("ChainMessageParts", () => {+ afterEach(cleanup);++ it("marks the final chain as streaming when a regular part follows it", () => {+ // Long text is a real answer — short text would fold into the chain+ // as progress narration while streaming.+ const parts = [+ {+ type: "tool-web_search",+ state: "input-available",+ toolCallId: "search",+ input: {},+ },+ { type: "text", text: "partial response. ".repeat(20) },+ ] as MessagePart[];++ render(+ <ChainMessageParts+ parts={parts}+ messageID="message"+ isCurrentlyStreaming+ />,+ );++ expect(screen.getByTestId("tool-chain").dataset.streaming).toBe("true");+ expect(screen.getByTestId("message-part")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/UserMessageClamp.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/UserMessageClamp.test.tsxnew file mode 100644index 0000000000..2566a93406--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/UserMessageClamp.test.tsx@@ -0,0 +1,55 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import { UserMessageClamp } from "../UserMessageClamp";++function setMeasuredHeights(args: {+ scrollHeight: number;+ clientHeight: number;+}) {+ Object.defineProperty(HTMLElement.prototype, "scrollHeight", {+ configurable: true,+ get: () => args.scrollHeight,+ });+ Object.defineProperty(HTMLElement.prototype, "clientHeight", {+ configurable: true,+ get: () => args.clientHeight,+ });+}++afterEach(() => {+ cleanup();+ delete (HTMLElement.prototype as unknown as Record<string, unknown>)+ .scrollHeight;+ delete (HTMLElement.prototype as unknown as Record<string, unknown>)+ .clientHeight;+});++describe("UserMessageClamp", () => {+ it("shows the clamped content without a Read more button when it fits", () => {+ setMeasuredHeights({ scrollHeight: 100, clientHeight: 100 });++ render(<UserMessageClamp>Short message</UserMessageClamp>);++ expect(screen.getByText("Short message")).toBeDefined();+ expect(screen.getByText("Short message").className).toContain(+ "line-clamp-6",+ );+ expect(screen.queryByRole("button")).toBeNull();+ });++ it("expands and collapses overflowing content via Read more / Show less", () => {+ setMeasuredHeights({ scrollHeight: 300, clientHeight: 120 });++ render(<UserMessageClamp>Very long message</UserMessageClamp>);++ const content = screen.getByText("Very long message");+ expect(content.className).toContain("line-clamp-6");++ fireEvent.click(screen.getByRole("button", { name: "Read more" }));+ expect(content.className).not.toContain("line-clamp-6");++ fireEvent.click(screen.getByRole("button", { name: "Show less" }));+ expect(content.className).toContain("line-clamp-6");+ expect(screen.getByRole("button", { name: "Read more" })).toBeDefined();+ });+});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 3fd5edde3e..c69aa73c0c 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@@ -32,7 +32,7 @@ export type RenderSegment =| { kind: "collapsed-group"; parts: ToolUIPart[] }| { kind: "reasoning-group"; parts: MessagePart[]; index: number };-const CUSTOM_TOOL_TYPES = new Set([+const LEGACY_CUSTOM_TOOL_TYPES = new Set(["tool-ask_question","tool-find_block","tool-find_agent",@@ -69,6 +69,13 @@ export function isReasoningToolPart(part: MessagePart): boolean {return REASONING_TOOL_TYPES.has(part.type);}+// Every assistant tool belongs to the new ToolChain. ToolResult supplies a+// compact result view for known backend tools and a structured fallback for+// SDK or future tools, so no tool can fall back to the legacy top-level UI.+export function isChainableToolPart(part: MessagePart): boolean {+ return part.type === "reasoning" || part.type.startsWith("tool-");+}+// Default workspace-file URL shape: ``/api/proxy/api/workspace/files/<uuid>/download``.// Other surfaces (e.g. public share viewer) pass their own pattern into// ``filePartToArtifactRef`` rather than loosen this one — keeping the@@ -180,7 +187,7 @@ export function buildRenderSegments(if (part.type === "step-start") return;const isGenericCompletedTool =- isCompletedToolPart(part) && !CUSTOM_TOOL_TYPES.has(part.type);+ isCompletedToolPart(part) && !LEGACY_CUSTOM_TOOL_TYPES.has(part.type);if (isGenericCompletedTool) {flushReasoning();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectMethodView.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectMethodView.tsxdeleted file mode 100644index 890d89f4c5..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectMethodView.tsx+++ /dev/null@@ -1,196 +0,0 @@-"use client";--import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";-import { Icon } from "@/components/atoms/Icon/Icon";-import { Text } from "@/components/atoms/Text/Text";-import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";-import type { ApiKeyConnectFormValues } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/schema";-import { UnsupportedNotice } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/UnsupportedNotice";-import {- AuthType,- type AuthMethod,- type ConnectableProvider,-} from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/helpers";-import type { UseFormReturn } from "react-hook-form";-import { InlineApiKeyForm } from "./InlineApiKeyForm";-import {- GlobeIcon,- Key01Icon,- SecurityCheckIcon,- UserIcon,-} from "@hugeicons/core-free-icons";-import type { IconSvgElement } from "@hugeicons/react";-import { AnimatePresence, motion } from "framer-motion";--interface Props {- provider: ConnectableProvider;- selectedMethod: AuthMethod | null;- onSelectMethod: (method: AuthMethod) => void;- apiKeyForm: UseFormReturn<ApiKeyConnectFormValues>;- onApiKeySubmit: (values: ApiKeyConnectFormValues) => void;-}--const METHOD_ORDER: AuthMethod[] = [- AuthType.oauth2,- AuthType.api_key,- AuthType.user_password,- AuthType.host_scoped,-];--const METHOD_COPY: Record<- AuthMethod,- {- label: string;- description: string;- icon: IconSvgElement;- recommended?: boolean;- }-> = {- [AuthType.oauth2]: {- label: "OAuth",- description: "One-click secure access.",- icon: SecurityCheckIcon,- recommended: true,- },- [AuthType.api_key]: {- label: "API Key",- description: "Paste your token for a custom setup.",- icon: Key01Icon,- },- [AuthType.user_password]: {- label: "Username & password",- description: "Sign in with account credentials.",- icon: UserIcon,- },- [AuthType.host_scoped]: {- label: "Host",- description: "Scope credentials to one host.",- icon: GlobeIcon,- },-};--// The connect step behind a provider click: logo pair, "Connect AutoGPT-// to X", method radio cards. Form methods expand their inputs inline as-// an accordion; OAuth is driven by the panel footer's Continue.-export function ConnectMethodView({- provider,- selectedMethod,- onSelectMethod,- apiKeyForm,- onApiKeySubmit,-}: Props) {- const methods = METHOD_ORDER.filter((method) =>- provider.supportedAuthTypes.includes(method),- );-- return (- <div className="flex flex-col gap-5 pt-2">- <div className="flex items-center justify-center gap-6">- <span className="relative flex h-20 w-20 items-center justify-center rounded-full bg-white shadow-[0_8px_24px_rgba(0,0,0,0.08)] ring-1 ring-zinc-100">- <AutoGPTLogo- hideText- className="absolute left-1/2 top-1/2 h-8 w-[4.4rem] -translate-x-[77%] -translate-y-1/2"- />- </span>- <span aria-hidden className="grid grid-cols-3 gap-1.5">- {Array.from({ length: 9 }, (_, dot) => (- <span key={dot} className="h-1 w-1 rounded-full bg-[#5b21b6]/30" />- ))}- </span>- <span className="flex h-20 w-20 items-center justify-center rounded-full bg-white shadow-[0_8px_24px_rgba(0,0,0,0.08)] ring-1 ring-zinc-100">- <ProviderAvatar id={provider.id} name={provider.name} />- </span>- </div>-- <div className="flex flex-col gap-1.5 text-center">- <Text variant="h3" className="!text-[1.25rem] text-zinc-900">- Connect AutoGPT to {provider.name}- </Text>- <Text variant="body" className="!text-zinc-500">- Choose how you'd like to connect your {provider.name} account.- </Text>- </div>-- <div className="flex flex-col gap-1 rounded-2xl bg-neutral-100 p-1.5">- {methods.map((method) => {- const copy = METHOD_COPY[method];- const isSelected = selectedMethod === method;- const hasInlineForm = method !== AuthType.oauth2;- return (- <div- key={method}- className={isSelected ? "rounded-xl bg-white shadow-sm" : ""}- >- <button- type="button"- onClick={() => onSelectMethod(method)}- className={- isSelected- ? "flex w-full items-center gap-3 rounded-xl p-3 text-left"- : "flex w-full items-center gap-3 rounded-xl p-3 text-left transition-colors hover:bg-white/60"- }- >- <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-white shadow-sm">- <Icon icon={copy.icon} size={22} className="text-zinc-700" />- </span>- <span className="flex min-w-0 flex-1 flex-col gap-0.5">- <span className="flex items-center gap-2">- <span className="text-sm font-semibold text-zinc-900">- {copy.label}- </span>- {copy.recommended && (- <span className="rounded-md bg-violet-100 px-1.5 py-0.5 text-[10px] font-semibold tracking-wide text-violet-700">- RECOMMENDED- </span>- )}- </span>- <span className="text-xs text-zinc-500">- {copy.description}- </span>- </span>- <span- aria-hidden- className={- isSelected- ? "flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 border-violet-600"- : "h-5 w-5 shrink-0 rounded-full border-2 border-zinc-200"- }- >- {isSelected && (- <span className="h-2.5 w-2.5 rounded-full bg-violet-600" />- )}- </span>- </button>- {/* Form methods open in place: the card grows to reveal the- inputs, submit included — no separate step. */}- <AnimatePresence initial={false}>- {isSelected && hasInlineForm && (- <motion.div- key="form"- initial={{ height: 0, opacity: 0 }}- animate={{ height: "auto", opacity: 1 }}- exit={{ height: 0, opacity: 0 }}- transition={{ duration: 0.25, ease: [0, 0, 0.2, 1] }}- className="overflow-hidden"- >- <div className="px-3 pb-3">- {method === AuthType.api_key ? (- <InlineApiKeyForm- form={apiKeyForm}- providerName={provider.name}- onSubmit={onApiKeySubmit}- />- ) : (- <UnsupportedNotice providerName={provider.name} />- )}- </div>- </motion.div>- )}- </AnimatePresence>- </div>- );- })}- </div>- </div>- );-}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsxindex d2ea98c4e6..2cbc557bda 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx@@ -4,7 +4,7 @@ import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { Text } from "@/components/atoms/Text/Text";-import { ConnectMethodView } from "./ConnectMethodView";+import { ConnectMethodView } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView";import { ConnectProviderRow } from "./ConnectProviderRow";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";import { Plug01Icon, Search01Icon } from "@hugeicons/core-free-icons";diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/PixelGridLoader.module.css b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/PixelGridLoader.module.cssnew file mode 100644index 0000000000..5590c3dd5c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/PixelGridLoader.module.css@@ -0,0 +1,21 @@+.cell {+ animation-name: pixel-on;+ animation-timing-function: ease-in-out;+ animation-iteration-count: infinite;+}++@keyframes pixel-on {+ 0%,+ 100% {+ opacity: 0.15;+ }+ 50% {+ opacity: 1;+ }+}++@media (prefers-reduced-motion: reduce) {+ .cell {+ animation-name: none;+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/PixelGridLoader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/PixelGridLoader.tsxnew file mode 100644index 0000000000..37fe9327c9--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/PixelGridLoader.tsx@@ -0,0 +1,67 @@+import { cn } from "@/lib/utils";+import styles from "./PixelGridLoader.module.css";++// Chevron wavefront: cells light up in diagonal bands driving left to right.+// The cycle is shorter than the sweep, so two fronts are always in flight.+const CHEVRON_DELAYS = Array.from({ length: 9 }, (_, i) => {+ const row = Math.floor(i / 3);+ const column = i % 3;+ return (column + Math.abs(row - 1)) * 90;+});++// Comet lapping the perimeter; the centre cell never lights up.+const ORBIT_ORDER = [0, 1, 2, 5, 8, 7, 6, 3];+const ORBIT_DELAYS = Array.from({ length: 9 }, (_, i) => {+ const step = ORBIT_ORDER.indexOf(i);+ return step === -1 ? null : step * 110;+});++const VARIANTS = {+ drive: { delays: CHEVRON_DELAYS, durationMs: 650, round: false },+ dots: { delays: CHEVRON_DELAYS, durationMs: 650, round: true },+ orbit: { delays: ORBIT_DELAYS, durationMs: 950, round: false },+};++interface Props {+ variant?: keyof typeof VARIANTS;+ /** Edge length of a single cell in pixels. */+ cellSize?: number;+ className?: string;+}++export function PixelGridLoader({+ variant = "drive",+ cellSize = 4,+ className,+}: Props) {+ const { delays, durationMs, round } = VARIANTS[variant];++ return (+ <span+ aria-hidden+ className={cn("grid shrink-0", className)}+ style={{+ gridTemplateColumns: `repeat(3, ${cellSize}px)`,+ gap: cellSize * 0.375,+ }}+ >+ {delays.map((delay, index) => (+ <span+ key={index}+ className={cn(+ "bg-current",+ round ? "rounded-full" : "rounded-[1px]",+ delay !== null && styles.cell,+ )}+ style={{+ width: cellSize,+ height: cellSize,+ opacity: delay === null ? 0.07 : 0.15,+ animationDuration: `${durationMs}ms`,+ animationDelay: `${delay ?? 0}ms`,+ }}+ />+ ))}+ </span>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/__tests__/PixelGridLoader.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/__tests__/PixelGridLoader.test.tsxnew file mode 100644index 0000000000..0a7c7af306--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PixelGridLoader/__tests__/PixelGridLoader.test.tsx@@ -0,0 +1,64 @@+import { cleanup, render } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import { PixelGridLoader } from "../PixelGridLoader";++function renderGrid(props: React.ComponentProps<typeof PixelGridLoader> = {}) {+ const { container } = render(<PixelGridLoader {...props} />);+ const grid = container.firstElementChild as HTMLElement;+ const cells = Array.from(grid.children) as HTMLElement[];+ return { grid, cells };+}++afterEach(cleanup);++describe("PixelGridLoader", () => {+ it("renders a hidden 3x3 grid with staggered chevron delays by default", () => {+ const { grid, cells } = renderGrid();++ expect(grid.getAttribute("aria-hidden")).toBe("true");+ expect(cells).toHaveLength(9);+ expect(grid.style.gridTemplateColumns).toBe("repeat(3, 4px)");++ // Chevron wavefront: (column + |row - 1|) * 90ms.+ expect(cells[0].style.animationDelay).toBe("90ms");+ expect(cells[4].style.animationDelay).toBe("90ms");+ expect(cells[8].style.animationDelay).toBe("270ms");+ cells.forEach((cell) => {+ expect(cell.style.opacity).toBe("0.15");+ expect(cell.style.animationDuration).toBe("650ms");+ expect(cell.className).toContain("rounded-[1px]");+ });+ });++ it("rounds the cells in the dots variant", () => {+ const { cells } = renderGrid({ variant: "dots" });+ cells.forEach((cell) => {+ expect(cell.className).toContain("rounded-full");+ });+ });++ it("keeps the centre cell dark and unanimated in the orbit variant", () => {+ const { cells } = renderGrid({ variant: "orbit" });++ expect(cells[4].style.opacity).toBe("0.07");+ expect(cells[4].style.animationDelay).toBe("0ms");++ // Comet order [0, 1, 2, 5, 8, 7, 6, 3] at 110ms per step.+ expect(cells[0].style.animationDelay).toBe("0ms");+ expect(cells[1].style.animationDelay).toBe("110ms");+ expect(cells[5].style.animationDelay).toBe("330ms");+ expect(cells[3].style.animationDelay).toBe("770ms");+ expect(cells[0].style.opacity).toBe("0.15");+ expect(cells[0].style.animationDuration).toBe("950ms");+ });++ it("scales the cells and gap with cellSize and forwards className", () => {+ const { grid, cells } = renderGrid({ cellSize: 8, className: "text-red" });++ expect(grid.className).toContain("text-red");+ expect(grid.style.gridTemplateColumns).toBe("repeat(3, 8px)");+ expect(grid.style.gap).toBe("3px");+ expect(cells[0].style.width).toBe("8px");+ expect(cells[0].style.height).toBe("8px");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/PendingQuestionsContext.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/PendingQuestionsContext.tsnew file mode 100644index 0000000000..cb670e0483--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/PendingQuestionsContext.ts@@ -0,0 +1,11 @@+"use client";++import { createContext } from "react";+import type { PendingQuestions } from "./helpers";++/** Latest unanswered clarifying questions for the session, provided by+ * ChatContainer so the tool chain can render the answer form inline on+ * the matching ask_question rows. */+export const PendingQuestionsContext = createContext<PendingQuestions | null>(+ null,+);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.tsxnew file mode 100644index 0000000000..40b4f0b91a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx@@ -0,0 +1,147 @@+"use client";++import type { UIDataTypes, UIMessage, UITools } from "ai";+import { useContext, useEffect, useRef, useState } from "react";+import { CopilotChatActionsContext } from "../CopilotChatActionsProvider/useCopilotChatActions";+import { ChainActionsContext } from "../ToolChain/chainActions";+import {+ buildAnswersMessage,+ getPendingQuestions,+ type PendingQuestions,+} from "./helpers";++interface FormProps {+ dockId: string;+ questions: PendingQuestions["questions"];+}++/** The clarifying-question answer form — rendered inline in the tool chain+ * on the ask_question row (and reused by the legacy QuestionDock). */+export function QuestionsForm({ dockId, questions }: FormProps) {+ const actions = useContext(CopilotChatActionsContext);+ const chainActions = useContext(ChainActionsContext);+ const [answers, setAnswers] = useState<Record<string, string>>({});+ const [dismissedId, setDismissedId] = useState<string | null>(null);+ const [renderedDockId, setRenderedDockId] = useState<string | null>(null);+ const inputRefs = useRef<Record<string, HTMLInputElement | null>>({});++ const dismissed = dockId === dismissedId;+ const allAnswered = questions.every((q) => answers[q.keyword]?.trim());++ // Inside a tool chain the Answer button is replaced by the chain's single+ // Proceed step — register readiness + message instead.+ useEffect(() => {+ if (!chainActions || dismissed) return;+ chainActions.register({+ id: dockId,+ ready: allAnswered,+ buildMessage: () =>+ allAnswered ? buildAnswersMessage(questions, answers) : null,+ onSent: () => setDismissedId(dockId),+ questions: {+ id: dockId,+ questions,+ answers,+ onAnswer: (keyword, value) =>+ setAnswers((prev) => ({ ...prev, [keyword]: value })),+ onSkip: () => setDismissedId(dockId),+ },+ });+ return () => chainActions.unregister(dockId);+ }, [chainActions, dismissed, dockId, allAnswered, answers, questions]);++ if (renderedDockId !== dockId) {+ setRenderedDockId(dockId);+ setAnswers({});+ }++ if (!actions || dismissed) return null;+ // Inside a chain the inputs live in the action card below it, not on the+ // row that asked.+ if (chainActions) return null;++ function handleSubmit() {+ if (chainActions) return;+ if (!actions) return;+ if (!allAnswered) {+ const unanswered = questions.find((q) => !answers[q.keyword]?.trim());+ if (unanswered) inputRefs.current[unanswered.keyword]?.focus();+ return;+ }+ actions.onSend(buildAnswersMessage(questions, answers));+ setDismissedId(dockId);+ }++ return (+ <div className="animate-fade-up rounded-2xl bg-white p-3 shadow-[0_16px_40px_-24px_rgba(0,0,0,0.25)] ring-1 ring-zinc-200/70 motion-reduce:animate-none">+ <div className="flex items-center justify-between px-0.5 pb-2">+ <span className="text-xs font-medium text-zinc-500">+ {questions.length === 1 ? "Quick question" : "Quick questions"}+ </span>+ <button+ type="button"+ onClick={() => setDismissedId(dockId)}+ className="rounded-full px-2 py-0.5 text-xs text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-600"+ >+ Skip+ </button>+ </div>+ <div className="flex flex-col gap-2.5">+ {questions.map((q) => (+ <label key={q.keyword} className="flex flex-col gap-1">+ <span className="text-[13px] text-zinc-700">{q.question}</span>+ <input+ ref={(element) => {+ inputRefs.current[q.keyword] = element;+ }}+ type="text"+ required+ value={answers[q.keyword] ?? ""}+ onChange={(e) =>+ setAnswers((prev) => ({+ ...prev,+ [q.keyword]: e.target.value,+ }))+ }+ onKeyDown={(e) => {+ if (e.key === "Enter") handleSubmit();+ }}+ placeholder={q.example ? `e.g. ${q.example}` : "Type your answer"}+ className="rounded-xl bg-zinc-50 px-2.5 py-1.5 text-[13px] text-zinc-800 ring-1 ring-zinc-200/70 transition-shadow placeholder:text-zinc-400 focus:outline-none focus:ring-zinc-400"+ />+ </label>+ ))}+ </div>+ {!chainActions && (+ <div className="flex justify-end pt-2.5">+ <button+ type="button"+ onClick={handleSubmit}+ aria-disabled={!allAnswered}+ className="rounded-full bg-zinc-900 px-3.5 py-1.5 text-xs font-medium text-white transition-opacity aria-disabled:opacity-40 hover:bg-zinc-700"+ >+ Answer+ </button>+ </div>+ )}+ </div>+ );+}++interface Props {+ messages: UIMessage<unknown, UIDataTypes, UITools>[];+}++export function QuestionDock({ messages }: Props) {+ const pending = getPendingQuestions(messages);+ if (!pending) return null;+ return (+ <div className="mb-2">+ <QuestionsForm+ key={pending.dockId}+ dockId={pending.dockId}+ questions={pending.questions}+ />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/__tests__/QuestionDock.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/__tests__/QuestionDock.test.tsxnew file mode 100644index 0000000000..75c7363028--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/__tests__/QuestionDock.test.tsx@@ -0,0 +1,107 @@+import { cleanup, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import type { UIDataTypes, UIMessage, UITools } from "ai";+import { afterEach, describe, expect, it, vi } from "vitest";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import { QuestionDock } from "../QuestionDock";++type Message = UIMessage<unknown, UIDataTypes, UITools>;++function questionMessage(questions: unknown[], id = "a1"): Message {+ return {+ id,+ role: "assistant",+ parts: [+ {+ type: "tool-ask_question",+ toolCallId: `${id}-call`,+ state: "output-available",+ input: {},+ output: { type: "agent_builder_clarification_needed", questions },+ } as Message["parts"][number],+ ],+ };+}++describe("QuestionDock", () => {+ afterEach(cleanup);++ function renderDock(messages: Message[], onSend = vi.fn()) {+ render(+ <CopilotChatActionsProvider onSend={onSend}>+ <QuestionDock messages={messages} />+ </CopilotChatActionsProvider>,+ );+ return onSend;+ }++ it("renders nothing when the last message is from the user", () => {+ renderDock([+ questionMessage([{ question: "Which region?", keyword: "region" }]),+ { id: "u1", role: "user", parts: [{ type: "text", text: "Europe" }] },+ ]);++ expect(screen.queryByRole("textbox")).toBeNull();+ });++ it("ignores malformed questions and renders valid questions", () => {+ renderDock([+ questionMessage([+ { question: 123, keyword: "invalid" },+ { question: "Which region?", keyword: "region", example: "Europe" },+ ]),+ ]);++ expect(screen.getByLabelText("Which region?")).toBeDefined();+ expect(screen.getByPlaceholderText("e.g. Europe")).toBeDefined();+ expect(screen.queryByText("123")).toBeNull();+ });++ it("focuses the first missing answer and only sends complete answers", async () => {+ const user = userEvent.setup();+ const onSend = renderDock([+ questionMessage([+ { question: "Which region?", keyword: "region" },+ { question: "Which format?", keyword: "format" },+ ]),+ ]);++ await user.click(screen.getByRole("button", { name: "Answer" }));+ expect(screen.getByLabelText("Which region?")).toBe(document.activeElement);+ expect(onSend).not.toHaveBeenCalled();++ await user.type(screen.getByLabelText("Which region?"), "Europe");+ await user.type(screen.getByLabelText("Which format?"), "CSV");+ await user.keyboard("{Enter}");++ expect(onSend).toHaveBeenCalledOnce();+ expect(onSend).toHaveBeenCalledWith(+ "**Here are my answers:**\n\n> Which region?\n\nEurope\n\n> Which format?\n\nCSV\n\nPlease proceed.",+ );+ expect(screen.queryByRole("textbox")).toBeNull();+ });++ it("hides after skipping", async () => {+ const user = userEvent.setup();+ const onSend = renderDock([+ questionMessage([{ question: "Which region?", keyword: "region" }]),+ ]);++ await user.click(screen.getByRole("button", { name: "Skip" }));++ expect(screen.queryByRole("textbox")).toBeNull();+ expect(onSend).not.toHaveBeenCalled();+ });++ it("renders nothing without chat actions", () => {+ render(+ <QuestionDock+ messages={[+ questionMessage([{ question: "Which region?", keyword: "region" }]),+ ]}+ />,+ );++ expect(screen.queryByRole("textbox")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/__tests__/helpers.test.tsnew file mode 100644index 0000000000..37c8473700--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/__tests__/helpers.test.ts@@ -0,0 +1,174 @@+import type { UIDataTypes, UIMessage, UITools } from "ai";+import { describe, expect, it } from "vitest";+import { buildAnswersMessage, getPendingQuestions } from "../helpers";++type Message = UIMessage<unknown, UIDataTypes, UITools>;+type Part = Message["parts"][number];++function toolPart(overrides: Record<string, unknown>): Part {+ return {+ type: "tool-ask_question",+ toolCallId: "call-1",+ state: "output-available",+ input: {},+ output: {+ type: "agent_builder_clarification_needed",+ questions: [{ question: "Which region?", keyword: "region" }],+ },+ ...overrides,+ } as unknown as Part;+}++function assistantMessage(parts: Part[], id = "a1"): Message {+ return { id, role: "assistant", parts };+}++describe("getPendingQuestions", () => {+ it("returns null when there are no messages", () => {+ expect(getPendingQuestions([])).toBeNull();+ });++ it("returns null when a user reply supersedes the asking message", () => {+ expect(+ getPendingQuestions([+ assistantMessage([toolPart({})]),+ { id: "u1", role: "user", parts: [{ type: "text", text: "Europe" }] },+ ]),+ ).toBeNull();+ });++ it("returns null while the tool part has no output yet", () => {+ expect(+ getPendingQuestions([+ assistantMessage([+ toolPart({ state: "input-available", output: undefined }),+ ]),+ ]),+ ).toBeNull();+ });++ it("ignores non-tool parts and unrelated tool outputs", () => {+ expect(+ getPendingQuestions([+ assistantMessage([+ { type: "text", text: "Working on it" } as unknown as Part,+ toolPart({+ type: "tool-web_search",+ output: { type: "search_results" },+ }),+ ]),+ ]),+ ).toBeNull();+ });++ it("picks up clarification outputs from tools other than ask_question", () => {+ const pending = getPendingQuestions([+ assistantMessage([toolPart({ type: "tool-create_agent" })]),+ ]);++ expect(pending?.questions).toEqual([+ { question: "Which region?", keyword: "region" },+ ]);+ });++ it("parses JSON-string outputs and ignores unparseable ones", () => {+ const pending = getPendingQuestions([+ assistantMessage([+ toolPart({+ type: "tool-create_agent",+ output: JSON.stringify({+ type: "agent_builder_clarification_needed",+ questions: [{ question: "Which region?", keyword: "region" }],+ }),+ }),+ ]),+ ]);+ expect(pending?.questions).toHaveLength(1);++ expect(+ getPendingQuestions([+ assistantMessage([+ toolPart({ type: "tool-create_agent", output: "not json {" }),+ ]),+ ]),+ ).toBeNull();+ });++ it("returns null when every question is malformed", () => {+ expect(+ getPendingQuestions([+ assistantMessage([+ toolPart({+ output: {+ type: "agent_builder_clarification_needed",+ questions: [{ question: 123, keyword: "region" }],+ },+ }),+ ]),+ ]),+ ).toBeNull();+ });++ it("merges questions across parts into one dock entry", () => {+ const pending = getPendingQuestions([+ assistantMessage(+ [+ toolPart({ toolCallId: "call-1" }),+ toolPart({+ toolCallId: "call-2",+ output: {+ type: "agent_builder_clarification_needed",+ questions: [{ question: "Which format?", keyword: "format" }],+ },+ }),+ ],+ "msg-9",+ ),+ ]);++ expect(pending).toEqual({+ dockId: "msg-9:call-1+call-2",+ questions: [+ { question: "Which region?", keyword: "region" },+ { question: "Which format?", keyword: "format" },+ ],+ callIds: ["call-1", "call-2"],+ });+ });++ it("dedupes colliding keywords across merged parts", () => {+ const pending = getPendingQuestions([+ assistantMessage([+ toolPart({ toolCallId: "call-1" }),+ toolPart({+ toolCallId: "call-2",+ output: {+ type: "agent_builder_clarification_needed",+ questions: [{ question: "Which region again?", keyword: "region" }],+ },+ }),+ ]),+ ]);++ expect(pending?.questions.map((q) => q.keyword)).toEqual([+ "region",+ "region-1",+ ]);+ });+});++describe("buildAnswersMessage", () => {+ it("quotes each question above its trimmed answer", () => {+ const message = buildAnswersMessage(+ [+ { question: "Which region?", keyword: "region" },+ { question: "Which format?", keyword: "format" },+ ],+ { region: " Europe ", format: "CSV" },+ );++ expect(message).toBe(+ "**Here are my answers:**\n\n> Which region?\n\nEurope\n\n> Which format?\n\nCSV\n\nPlease proceed.",+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/helpers.tsnew file mode 100644index 0000000000..3dd74fd150--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/helpers.ts@@ -0,0 +1,73 @@+import type { ToolUIPart, UIDataTypes, UIMessage, UITools } from "ai";+import {+ type ClarifyingQuestion,+ extractClarifyingQuestions,+ normalizeClarifyingQuestions,+} from "../../tools/clarifying-questions";++export interface PendingQuestions {+ dockId: string;+ questions: ClarifyingQuestion[];+ /** Tool-call ids of the ask_question parts the questions came from —+ * lets the tool chain render the answer form on the matching rows. */+ callIds: string[];+}++type Message = UIMessage<unknown, UIDataTypes, UITools>;++const QUESTION_RESPONSE_TYPE = "agent_builder_clarification_needed";++function outputType(output: unknown): string | null {+ if (typeof output === "string") {+ try {+ output = JSON.parse(output);+ } catch {+ return null;+ }+ }+ if (!output || typeof output !== "object") return null;+ const type = (output as Record<string, unknown>).type;+ return typeof type === "string" ? type : null;+}++// Questions are pending only while the asking assistant message is the last+// message — any user reply (answers, skip, or a fresh request) supersedes it.+export function getPendingQuestions(+ messages: Message[],+): PendingQuestions | null {+ const last = messages[messages.length - 1];+ if (!last || last.role !== "assistant") return null;++ const questions: ClarifyingQuestion[] = [];+ const callIds: string[] = [];+ for (const part of last.parts) {+ if (!part.type.startsWith("tool-")) continue;+ if (!("state" in part) || part.state !== "output-available") continue;+ const tool = part as ToolUIPart;+ const isQuestionPart =+ part.type === "tool-ask_question" ||+ outputType(tool.output) === QUESTION_RESPONSE_TYPE;+ if (!isQuestionPart) continue;+ const extracted = extractClarifyingQuestions(tool);+ if (extracted.length === 0) continue;+ questions.push(...extracted);+ callIds.push(tool.toolCallId);+ }+ if (questions.length === 0) return null;++ return {+ dockId: `${last.id}:${callIds.join("+")}`,+ questions: normalizeClarifyingQuestions(questions),+ callIds,+ };+}++export function buildAnswersMessage(+ questions: ClarifyingQuestion[],+ answers: Record<string, string>,+): string {+ const body = questions+ .map((q) => `> ${q.question}\n\n${answers[q.keyword].trim()}`)+ .join("\n\n");+ return `**Here are my answers:**\n\n${body}\n\nPlease proceed.`;+}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.tsxindex 92287fa26b..7b338c8de2 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@@ -6,7 +6,8 @@ import { Text } from "@/components/atoms/Text/Text";import { CredentialsGroupedView } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView";import { FormRenderer } from "@/components/renderers/InputRenderer/FormRenderer";import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";-import { useEffect, useMemo, useState } from "react";+import { useContext, useEffect, useId, useMemo, useState } from "react";+import { ChainActionsContext } from "../ToolChain/chainActions";import {useAreAllConnected,useConnectedProvidersStore,@@ -66,6 +67,8 @@ export function SetupRequirementsCard({onComplete,}: Props) {const { onSend } = useCopilotChatActions();+ const chainActions = useContext(ChainActionsContext);+ const actionId = useId();const [inputCredentials, setInputCredentials] = useState<Record<string, CredentialsMetaInput | undefined>@@ -173,17 +176,79 @@ export function SetupRequirementsCard({// eslint-disable-next-line react-hooks/exhaustive-deps -- handleRun captures latest state; claim guards re-entry}, [canAutoDismiss, hasSent]);- if (hasSent || canAutoDismiss) {- return <ContentMessage>Connected. Continuing…</ContentMessage>;- }-const canRun = checkCanRun(needsCredentials,isAllCredsComplete,isAllInputsDone,);- function handleRun() {+ // 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) return;+ if (!needsCredentials && !needsInputs) return;+ chainActions.register({+ id: actionId,+ ready: canRun,+ buildMessage: () => buildProceedMessage(),+ onSent: markSent,+ connectors: needsCredentials+ ? {+ id: actionId,+ fields: credentialFields,+ selected: inputCredentials,+ onChange: handleCredentialChange,+ }+ : undefined,+ inputs:+ isEditMode && needsInputs+ ? {+ id: actionId,+ title: output.setup_info.agent_name,+ schema: inputSchema,+ values: inputValues,+ onChange: (values) =>+ setInputValues((prev) => ({ ...prev, ...values })),+ hasAdvanced: hasAdvancedFields,+ showAdvanced,+ onToggleAdvanced: () => setShowAdvanced((v) => !v),+ }+ : undefined,+ });+ return () => chainActions.unregister(actionId);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- buildProceedMessage/markSent capture latest state each registration+ }, [+ chainActions,+ hasSent,+ canAutoDismiss,+ canRun,+ actionId,+ needsCredentials,+ needsInputs,+ inputCredentials,+ inputValues,+ inputsMode,+ showAdvanced,+ ]);++ if (hasSent || canAutoDismiss) {+ return <ContentMessage>Connected. Continuing…</ContentMessage>;+ }++ function buildProceedMessage() {+ return inputsMode === "trigger"+ ? buildTriggerSetupMessage(inputCredentials)+ : isEditMode+ ? buildRunMessage(+ needsCredentials,+ needsInputs,+ inputValues,+ retryInstruction,+ )+ : buildPreviewRunMessage(needsCredentials);+ }++ function markSent() {setHasSent(true);if (sessionID && requestedProviders.length > 0) {useConnectedProvidersStore@@ -191,26 +256,22 @@ export function SetupRequirementsCard({.markConnected({ sessionID, providers: requestedProviders });}onComplete?.();- const message =- inputsMode === "trigger"- ? buildTriggerSetupMessage(inputCredentials)- : isEditMode- ? buildRunMessage(- needsCredentials,- needsInputs,- inputValues,- retryInstruction,- )- : buildPreviewRunMessage(needsCredentials);- onSend(message);if (isEditMode) setInputValues({});}+ function handleRun() {+ const message = buildProceedMessage();+ markSent();+ onSend(message);+ }+return (<div className="grid gap-2"><ContentMessage>{output.message}</ContentMessage>- {needsCredentials && (+ {/* Inside a chain the connectors are lifted out and rendered as a card+ below it; standalone the card keeps the full credentials picker. */}+ {needsCredentials && !chainActions && (<div className="rounded-2xl border bg-background p-3"><Text variant="small" className="w-fit border-b text-zinc-500">{credentialsLabel ??@@ -228,7 +289,9 @@ export function SetupRequirementsCard({</div>)}- {isEditMode && (inputSchema || hasAdvancedFields) && (+ {/* Same lift-out as the connectors: inside a chain the inputs form+ renders in the card below it, not inside the accordion. */}+ {isEditMode && !chainActions && (inputSchema || hasAdvancedFields) && (<div className="rounded-2xl border bg-background p-3 pt-4"><Text variant="small" className="w-fit border-b text-zinc-500">Inputs@@ -289,7 +352,7 @@ export function SetupRequirementsCard({</div>)}- {(needsCredentials || needsInputs) && (+ {(needsCredentials || needsInputs) && !chainActions && (<Buttonvariant="primary"size="small"diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/AgentCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/AgentCards.tsxnew file mode 100644index 0000000000..b559742f55--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/AgentCards.tsx@@ -0,0 +1,203 @@+"use client";++import {+ LinkSquare01Icon,+ PlayIcon,+ Robot01Icon,+ StarIcon,+ WrenchIcon,+} from "@hugeicons/core-free-icons";+import Link from "next/link";+import { Icon } from "@/components/atoms/Icon/Icon";+import { CARD, HALF, StatusPill } from "./ResultCards";+import { inline, resultItemKey, str } from "./resultHelpers";++function agentHref(agent: Record<string, unknown>): string | null {+ const id = str(agent, "id");+ if (!id) return null;+ if (str(agent, "source") === "library")+ return `/library/agents/${encodeURIComponent(id)}`;+ const [creator, slug, ...rest] = id.split("/");+ if (!creator || !slug || rest.length > 0) return null;+ return `/marketplace/agent/${encodeURIComponent(creator)}/${encodeURIComponent(slug)}`;+}++interface CardLinkProps {+ href: string;+ label: string;+}++interface AgentListCardProps {+ agents: Record<string, unknown>[];+}++interface OutputCardProps {+ output: Record<string, unknown>;+}++function CardLink({ href, label }: CardLinkProps) {+ return (+ <Link+ href={href}+ aria-label={label}+ className="shrink-0 rounded-full p-1 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-700"+ >+ <Icon icon={LinkSquare01Icon} size={14} />+ </Link>+ );+}++export function AgentListCard({ agents }: AgentListCardProps) {+ return (+ <div className="grid gap-1.5 sm:grid-cols-2">+ {agents.map((agent, i) => {+ const href = agentHref(agent);+ const runs = typeof agent.runs === "number" ? agent.runs : null;+ const rating = typeof agent.rating === "number" ? agent.rating : null;+ const subtitle = str(agent, "description");+ return (+ <div+ key={resultItemKey(agent, i)}+ className={CARD + " flex items-start gap-2.5 p-2.5"}+ >+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={Robot01Icon} size={15} className="text-zinc-600" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <p className="min-w-0 truncate text-[13px] font-medium text-zinc-800">+ {str(agent, "name", "agent_name") ?? inline(agent)}+ </p>+ {str(agent, "creator") && (+ <span className="shrink-0 truncate text-[11px] text-zinc-400">+ by {str(agent, "creator")}+ </span>+ )}+ </div>+ {subtitle && (+ <p className="truncate text-xs text-zinc-500">{subtitle}</p>+ )}+ {(runs !== null || rating !== null) && (+ <div className="mt-1 flex items-center gap-2.5 text-[11px] text-zinc-400">+ {runs !== null && (+ <span className="flex items-center gap-1">+ <Icon icon={PlayIcon} size={10} />+ {runs.toLocaleString()} runs+ </span>+ )}+ {rating !== null && (+ <span className="flex items-center gap-1">+ <Icon+ icon={StarIcon}+ size={10}+ className="text-amber-400"+ />+ {rating.toFixed(1)}+ </span>+ )}+ </div>+ )}+ </div>+ {href && <CardLink href={href} label="Open agent" />}+ </div>+ );+ })}+ </div>+ );+}++export function AgentSavedCard({ output }: OutputCardProps) {+ const name = str(output, "agent_name", "name", "graph_name") ?? "Agent";+ const version = output.graph_version;+ const libraryLink =+ str(output, "library_agent_link") ??+ (str(output, "library_agent_id")+ ? `/library/agents/${str(output, "library_agent_id")}`+ : null);+ const builderLink = str(output, "agent_page_link");+ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2.5 p-2.5`}>+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={Robot01Icon} size={15} className="text-zinc-600" />+ </div>+ <p className="min-w-0 flex-1 truncate text-[13px] font-medium text-zinc-800">+ {name}+ </p>+ {typeof version === "number" && (+ <span className="shrink-0 rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] text-zinc-500">+ v{version}+ </span>+ )}+ {builderLink && (+ <Link+ href={builderLink}+ aria-label="Open in builder"+ className="shrink-0 rounded-full p-1 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-700"+ >+ <Icon icon={WrenchIcon} size={14} />+ </Link>+ )}+ {libraryLink && <CardLink href={libraryLink} label="Open in library" />}+ </div>+ );+}++export function AgentPreviewCard({ output }: OutputCardProps) {+ const name = str(output, "agent_name", "name") ?? "Agent preview";+ const count =+ typeof output.node_count === "number" ? output.node_count : null;+ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2.5 p-2.5`}>+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={Robot01Icon} size={15} className="text-zinc-600" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium text-zinc-800">{name}</p>+ {str(output, "description", "message") && (+ <p className="truncate text-xs text-zinc-500">+ {str(output, "description", "message")}+ </p>+ )}+ </div>+ {count !== null && (+ <span className="shrink-0 rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] text-zinc-500">+ {count} block{count === 1 ? "" : "s"}+ </span>+ )}+ </div>+ );+}++export function SubSessionCard({ output }: OutputCardProps) {+ const status = str(output, "status");+ const response = str(output, "response");+ const link = str(output, "sub_autopilot_session_link");+ const elapsed =+ typeof output.elapsed_seconds === "number" ? output.elapsed_seconds : null;+ return (+ <div className={`${CARD} ${HALF} p-2.5`}>+ <div className="flex items-center gap-2.5">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={Robot01Icon} size={15} className="text-zinc-600" />+ </div>+ <p className="min-w-0 flex-1 truncate text-[13px] font-medium text-zinc-800">+ Sub-AutoPilot+ </p>+ {elapsed !== null && (+ <span className="shrink-0 text-[11px] text-zinc-400">+ {elapsed >= 60+ ? `${Math.floor(elapsed / 60)}m ${Math.round(elapsed % 60)}s`+ : `${Math.round(elapsed)}s`}+ </span>+ )}+ {status && <StatusPill status={status} />}+ {link && <CardLink href={link} label="Open sub-session" />}+ </div>+ {response && (+ <p className="mt-1.5 line-clamp-2 pl-9 text-xs text-zinc-500">+ {response}+ </p>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/BlockCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/BlockCards.tsxnew file mode 100644index 0000000000..795c4222dd--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/BlockCards.tsx@@ -0,0 +1,154 @@+"use client";++import {+ CancelCircleIcon,+ CheckmarkCircle02Icon,+ PuzzleIcon,+} from "@hugeicons/core-free-icons";+import Image from "next/image";+import { useState } from "react";+import { Icon } from "@/components/atoms/Icon/Icon";+import { CARD, HALF } from "./ResultCards";+import {+ inline,+ integrationIconSrc,+ resultItemKey,+ str,+} from "./resultHelpers";++interface CardProviderIconProps {+ provider: string | null;+ fallback: React.ReactNode;+ size?: number;+}++interface BlockListCardProps {+ blocks: Record<string, unknown>[];+}++interface BlockOutputCardProps {+ output: Record<string, unknown>;+}++export function CardProviderIcon({+ provider,+ fallback,+ size = 15,+}: CardProviderIconProps) {+ const [failed, setFailed] = useState(false);+ if (!provider || failed) return <>{fallback}</>;+ const src = integrationIconSrc(provider);+ if (!src) return <>{fallback}</>;+ return (+ <Image+ src={src}+ alt={provider}+ width={size}+ height={size}+ className="rounded-sm object-contain"+ onError={() => setFailed(true)}+ />+ );+}++const BLOCK_ICON = (+ <Icon icon={PuzzleIcon} size={15} className="text-zinc-600" />+);++export function BlockListCard({ blocks }: BlockListCardProps) {+ return (+ <div className="grid gap-1.5 sm:grid-cols-2">+ {blocks.map((block, i) => {+ const categories = Array.isArray(block.categories)+ ? (block.categories as unknown[]).filter(+ (c): c is string => typeof c === "string",+ )+ : [];+ return (+ <div+ key={resultItemKey(block, i)}+ className={CARD + " flex items-start gap-2.5 p-2.5"}+ >+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <CardProviderIcon+ provider={str(block, "provider")}+ fallback={BLOCK_ICON}+ />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium text-zinc-800">+ {str(block, "name", "block_name") ?? inline(block)}+ </p>+ {str(block, "description") && (+ <p className="truncate text-xs text-zinc-500">+ {str(block, "description")}+ </p>+ )}+ </div>+ {categories[0] && (+ <span className="shrink-0 rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] text-zinc-500">+ {categories[0].toLowerCase()}+ </span>+ )}+ </div>+ );+ })}+ </div>+ );+}++export function BlockOutputCard({ output }: BlockOutputCardProps) {+ const name = str(output, "block_name", "block_id") ?? "Block";+ const ok = output.success !== false;+ const entries = Object.entries(+ output.outputs && typeof output.outputs === "object"+ ? (output.outputs as Record<string, unknown>)+ : {},+ );+ return (+ <div className={`${CARD} ${HALF} overflow-hidden`}>+ <div className="flex items-center gap-2.5 p-2.5">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <CardProviderIcon+ provider={str(output, "provider")}+ fallback={BLOCK_ICON}+ />+ </div>+ <p className="min-w-0 flex-1 truncate text-[13px] font-medium text-zinc-800">+ {name}+ </p>+ {ok ? (+ <Icon+ icon={CheckmarkCircle02Icon}+ size={16}+ className="shrink-0 text-green-500"+ />+ ) : (+ <Icon+ icon={CancelCircleIcon}+ size={16}+ className="shrink-0 text-red-400"+ />+ )}+ </div>+ {entries.length > 0 && (+ <div className="divide-y divide-zinc-100 border-t border-zinc-100">+ {entries.map(([key, value]) => {+ const flat =+ Array.isArray(value) && value.length === 1 ? value[0] : value;+ return (+ <div key={key} className="px-2.5 py-1.5">+ <p className="text-[11px] uppercase tracking-wide text-zinc-400">+ {key.replace(/_/g, " ")}+ </p>+ <p className="mt-0.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] text-zinc-700">+ {inline(flat)}+ </p>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsxnew file mode 100644index 0000000000..ba83764012--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx@@ -0,0 +1,152 @@+"use client";++import { ArrowDown01Icon } from "@hugeicons/core-free-icons";+import { useEffect, useRef, useState } from "react";+import { Icon } from "@/components/atoms/Icon/Icon";+import { cn } from "@/lib/utils";+import { useCopilotUIStore } from "../../store";+import { ACCORDION_PANEL, accordionState, PANEL_REVEAL } from "./accordion";+import type { ChainRow } from "./helpers";+import { ProviderIcon, RowIcon } from "./RowIcon";+import { SwapText } from "./SwapText";+import { ToolResult } from "./ToolResult";+import { ToolStatusBadge } from "./ToolStatusBadge";++interface ReasoningStreamProps {+ text: string;+ live: boolean;+}++function ReasoningStream({ text, live }: ReasoningStreamProps) {+ const viewportRef = useRef<HTMLDivElement>(null);++ // Auto-scroll pinned to the newest line while thinking streams.+ useEffect(() => {+ const el = viewportRef.current;+ if (live && el) el.scrollTop = el.scrollHeight;+ }, [text, live]);++ return (+ <div+ ref={viewportRef}+ className={cn(+ "text-[13px] leading-5 text-zinc-400",+ live+ ? "max-h-24 overflow-hidden [mask-image:linear-gradient(to_bottom,transparent_0,black_16px,black_100%)]"+ : "max-h-64 overflow-y-auto scrollbar-none",+ )}+ >+ <p className="whitespace-pre-wrap">{text}</p>+ </div>+ );+}++interface Props {+ row: ChainRow;+ isLast: boolean;+}++export function ChainRowView({ row, isLast }: Props) {+ const [open, setOpen] = useState(row.requiresAction === true);+ const isReasoning = row.category === "reasoning";+ const artifactPanelOpen = useCopilotUIStore((s) => s.artifactPanel.isOpen);++ // Browser steps carry the page screenshots the artifact panel shows —+ // auto-expand them while the panel is open so the steps are visible+ // from the start.+ useEffect(() => {+ if (row.category === "browser" && artifactPanelOpen) setOpen(true);+ }, [row.category, artifactPanelOpen]);+ const liveReasoning =+ isReasoning && row.state === "running" && !!row.reasoningText;+ const hasContent = isReasoning+ ? !!row.reasoningText+ : row.output !== undefined;+ // Action-required cards (credential setup, review, login) must stay on+ // screen until resolved — the row cannot be collapsed.+ const forcedOpen = row.requiresAction === true && hasContent;+ const showContent = liveReasoning || forcedOpen || (open && hasContent);+ const rowText = (+ <SwapText+ text={row.text}+ shimmer={row.state === "running"}+ className={cn(+ "max-w-full text-sm transition-colors duration-300",+ row.state === "error" ? "text-red-500" : "text-zinc-600",+ )}+ />+ );++ return (+ <div className="flex items-stretch gap-2.5">+ <div className="flex w-7 flex-col items-center">+ <div+ className={cn(+ "relative flex size-7 shrink-0 items-center justify-center rounded-full transition-colors duration-300",+ row.state === "error" ? "bg-red-50" : "bg-zinc-100",+ )}+ >+ <ToolStatusBadge state={row.state} label={row.text}>+ {row.state !== "error" && row.providerIconSrc ? (+ <ProviderIcon src={row.providerIconSrc} row={row} />+ ) : (+ <RowIcon row={row} />+ )}+ </ToolStatusBadge>+ </div>+ {!isLast && (+ <div className="w-px flex-1 origin-top animate-grow-line bg-zinc-200 motion-reduce:animate-none" />+ )}+ </div>+ <div className={cn("min-w-0 flex-1", isLast ? "pb-0" : "pb-3")}>+ {hasContent && !forcedOpen ? (+ <button+ type="button"+ onClick={() => setOpen(!open)}+ aria-expanded={showContent}+ className="group/row flex h-7 items-center gap-1.5"+ >+ {rowText}+ {!liveReasoning && (+ <Icon+ icon={ArrowDown01Icon}+ size={10}+ className={cn(+ "shrink-0 text-zinc-300 transition-transform duration-300 ease-out-quint group-hover/row:text-zinc-500",+ open && "rotate-180",+ )}+ />+ )}+ </button>+ ) : (+ <div className="flex h-7 items-center gap-1.5">{rowText}</div>+ )}+ {row.detail && (+ <p className="animate-fade-in truncate text-xs text-red-400 motion-reduce:animate-none">+ {row.detail}+ </p>+ )}+ <div className={ACCORDION_PANEL + " " + accordionState(showContent)}>+ <div+ aria-hidden={!showContent}+ inert={showContent ? undefined : ("" as unknown as boolean)}+ className="min-h-0 overflow-hidden"+ >+ <div+ className={cn("px-px pb-px pt-1.5", showContent && PANEL_REVEAL)}+ >+ {isReasoning ? (+ <ReasoningStream+ text={row.reasoningText ?? ""}+ live={liveReasoning}+ />+ ) : (+ <ToolResult row={row} />+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExecutionCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExecutionCard.tsxnew file mode 100644index 0000000000..d58cdfdd20--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExecutionCard.tsx@@ -0,0 +1,44 @@+"use client";++import {+ LinkSquare01Icon,+ PlayIcon,+ Robot01Icon,+} from "@hugeicons/core-free-icons";+import Link from "next/link";+import { Icon } from "@/components/atoms/Icon/Icon";+import { CARD, HALF, StatusPill } from "./ResultCards";++interface Props {+ name: string;+ status?: string;+ href?: string;+ variant?: "run" | "agent";+}++export function ExecutionCard({ name, status, href, variant = "run" }: Props) {+ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2.5 p-2.5`}>+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ {variant === "agent" ? (+ <Icon icon={Robot01Icon} size={15} className="text-zinc-600" />+ ) : (+ <Icon icon={PlayIcon} size={13} className="text-zinc-600" />+ )}+ </div>+ <p className="min-w-0 flex-1 truncate text-[13px] font-medium text-zinc-800">+ {name}+ </p>+ {status && <StatusPill status={status} />}+ {href && (+ <Link+ href={href}+ aria-label={variant === "agent" ? "Open agent" : "Open execution"}+ className="shrink-0 rounded-full p-1 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-700"+ >+ <Icon icon={LinkSquare01Icon} size={14} />+ </Link>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/FileDiff.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/FileDiff.tsxnew file mode 100644index 0000000000..710caf52e3--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/FileDiff.tsx@@ -0,0 +1,94 @@+"use client";++import { CodeIcon } from "@hugeicons/core-free-icons";+import { Icon } from "@/components/atoms/Icon/Icon";+import { MAX_RENDERED_DIFF_ROWS, parseUnifiedDiff } from "./fileDiffHelpers";++interface Props {+ file?: string;+ diff: string;+}++const LN_CLASSES = "select-none px-[7px] text-right text-[11px] leading-5";++export function FileDiff({ file, diff }: Props) {+ const { rows, added, removed, truncated } = parseUnifiedDiff(diff);++ return (+ <div className="overflow-hidden rounded-xl bg-white font-mono shadow-sm ring-1 ring-zinc-200/70">+ <div className="flex items-center gap-2 border-b border-zinc-200 py-2.5 pl-4 pr-3 text-[12.5px]">+ <span className="inline-flex items-center gap-[7px]">+ <Icon icon={CodeIcon} size={15} className="shrink-0 text-zinc-400" />+ <span className="leading-none text-zinc-900">{file ?? "file"}</span>+ </span>+ <span className="ml-auto inline-flex items-center gap-2 text-xs leading-none">+ <span className="text-green-600">+{added}</span>+ <span className="text-red-600">-{removed}</span>+ </span>+ </div>+ <div className="relative max-h-64 overflow-y-auto py-1 text-[12.5px] leading-5 scrollbar-none before:absolute before:bottom-0 before:left-16 before:top-0 before:z-10 before:w-px before:bg-zinc-200 before:content-['']">+ {rows.map((row) => (+ <div+ key={`${row.type}:${row.old ?? ""}:${row.cur ?? ""}`}+ className={+ "relative grid grid-cols-[32px_32px_18px_1fr] items-stretch " ++ (row.type === "add"+ ? "bg-green-50"+ : row.type === "del"+ ? "bg-red-50"+ : "")+ }+ >+ {row.type === "add" && (+ <span className="absolute inset-y-0 left-0 w-[3px] bg-green-600" />+ )}+ {row.type === "del" && (+ <span className="absolute inset-y-0 left-0 w-[3px] bg-red-600" />+ )}+ <span+ className={+ LN_CLASSES ++ (row.type === "del" ? " text-red-600" : " text-zinc-400")+ }+ >+ {row.old ?? ""}+ </span>+ <span+ className={+ LN_CLASSES ++ (row.type === "add" ? " text-green-600" : " text-zinc-400")+ }+ >+ {row.cur ?? ""}+ </span>+ <span+ className={+ "select-none text-center text-[11px] leading-5 " ++ (row.type === "add"+ ? "text-green-600"+ : row.type === "del"+ ? "text-red-600"+ : "text-zinc-400")+ }+ >+ {row.type === "add" ? "+" : row.type === "del" ? "-" : ""}+ </span>+ <code+ className={+ "whitespace-pre pl-2 pr-3 " ++ (row.type === "ctx" ? "text-zinc-400" : "text-zinc-900")+ }+ >+ {row.text}+ </code>+ </div>+ ))}+ {truncated && (+ <p className="px-3 py-2 text-center text-xs text-zinc-500">+ Diff preview truncated after {MAX_RENDERED_DIFF_ROWS} lines+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/InfoCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/InfoCards.tsxnew file mode 100644index 0000000000..140db56d36--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/InfoCards.tsx@@ -0,0 +1,274 @@+"use client";++import {+ AlertCircleIcon,+ BookBookmarkIcon,+ CheckmarkCircle02Icon,+ CircleIcon,+ ConnectIcon,+ MessageQuestionIcon,+} from "@hugeicons/core-free-icons";+import { Icon } from "@/components/atoms/Icon/Icon";+import { useContext } from "react";+import { CopilotChatActionsContext } from "../CopilotChatActionsProvider/useCopilotChatActions";+import { CardProviderIcon } from "./BlockCards";+import { CARD, HALF, StatusCard } from "./ResultCards";+import { asObject, inline, resultItemKey, str } from "./resultHelpers";++interface ItemsProps {+ steps: Record<string, unknown>[];+}++interface OutputProps {+ output: Record<string, unknown>;+}++interface ErrorListProps {+ errors: string[];+}++interface QuestionsCardProps {+ questions: Record<string, unknown>[];+}++interface SetupCardProps extends OutputProps {+ provider: string | null;+}++export function PlanSteps({ steps }: ItemsProps) {+ return (+ <div className={CARD + " flex flex-col gap-1.5 p-3"}>+ {steps.map((step, i) => {+ const status = str(step, "status");+ const done = status === "completed";+ const active = status === "in_progress";+ const blockName = str(step, "block_name");+ return (+ <div+ key={resultItemKey(step, i)}+ className="flex items-center gap-2 text-[13px]"+ >+ {done ? (+ <Icon+ icon={CheckmarkCircle02Icon}+ size={15}+ className="shrink-0 text-green-500"+ />+ ) : (+ <Icon+ icon={CircleIcon}+ size={15}+ className={+ "shrink-0 " + (active ? "text-purple-500" : "text-zinc-300")+ }+ />+ )}+ <span+ className={+ "min-w-0 flex-1 truncate " ++ (done+ ? "text-zinc-400 line-through"+ : active+ ? "font-medium text-zinc-800"+ : "text-zinc-600")+ }+ >+ {str(step, "description") ?? inline(step)}+ </span>+ {blockName && (+ <span className="shrink-0 rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] text-zinc-500">+ {blockName}+ </span>+ )}+ </div>+ );+ })}+ </div>+ );+}++function ErrorList({ errors }: ErrorListProps) {+ return (+ <div className={CARD + " flex flex-col gap-1.5 p-2.5"}>+ {errors.map((error) => (+ <div+ key={error}+ className="flex items-start gap-2 text-xs text-zinc-600"+ >+ <Icon+ icon={AlertCircleIcon}+ size={14}+ className="mt-px shrink-0 text-red-400"+ />+ <span className="min-w-0 break-words">{error}</span>+ </div>+ ))}+ </div>+ );+}++function strList(value: unknown): string[] {+ return Array.isArray(value)+ ? value.filter((item): item is string => typeof item === "string")+ : [];+}++export function ValidationCard({ output }: OutputProps) {+ const errors = strList(output.errors);+ if (output.valid === true) return <StatusCard ok label="Graph is valid" />;+ if (errors.length > 0) return <ErrorList errors={errors} />;+ return <StatusCard ok={false} label="Graph has errors" />;+}++export function FixResultCard({ output }: OutputProps) {+ const fixes = strList(output.fixes_applied);+ const remaining = strList(output.remaining_errors);+ return (+ <div className="flex flex-col gap-1.5">+ <StatusCard+ ok={output.valid_after_fix === true}+ label={+ output.valid_after_fix === true+ ? `Fixed — applied ${fixes.length} fix${fixes.length === 1 ? "" : "es"}`+ : `${remaining.length} error${remaining.length === 1 ? "" : "s"} remaining`+ }+ />+ {remaining.length > 0 && <ErrorList errors={remaining} />}+ </div>+ );+}++export function QuestionsCard({ questions }: QuestionsCardProps) {+ return (+ <div className={`${CARD} ${HALF} flex flex-col gap-2 p-2.5`}>+ {questions.map((entry, i) => (+ <div key={resultItemKey(entry, i)} className="flex items-start gap-2">+ <Icon+ icon={MessageQuestionIcon}+ size={14}+ className="mt-0.5 shrink-0 text-zinc-400"+ />+ <div className="min-w-0">+ <p className="text-[13px] text-zinc-700">+ {str(entry, "question") ?? inline(entry)}+ </p>+ {str(entry, "example") && (+ <p className="truncate text-xs text-zinc-400">+ e.g. {str(entry, "example")}+ </p>+ )}+ </div>+ </div>+ ))}+ </div>+ );+}++export function SetupCard({ output, provider }: SetupCardProps) {+ const setupInfo = asObject(output.setup_info);+ const name = setupInfo ? str(setupInfo, "agent_name") : null;+ if (!name) return null;+ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2.5 p-2.5`}>+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <CardProviderIcon+ provider={provider}+ fallback={+ <Icon icon={ConnectIcon} size={15} className="text-zinc-600" />+ }+ />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium text-zinc-800">{name}</p>+ <p className="truncate text-xs text-zinc-500">Connection required</p>+ </div>+ </div>+ );+}++export function SkillCard({ output }: OutputProps) {+ const name = str(output, "name");+ if (!name) return null;+ const triggers = strList(output.triggers);+ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2.5 p-2.5`}>+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={BookBookmarkIcon} size={15} className="text-zinc-600" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium text-zinc-800">{name}</p>+ {str(output, "description") && (+ <p className="truncate text-xs text-zinc-500">+ {str(output, "description")}+ </p>+ )}+ </div>+ {triggers[0] && (+ <span className="shrink-0 rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] text-zinc-500">+ {triggers[0]}+ </span>+ )}+ </div>+ );+}++export function SuggestedGoalCard({ output }: OutputProps) {+ const actions = useContext(CopilotChatActionsContext);+ const goal = str(output, "suggested_goal");+ if (!goal) return null;++ return (+ <div className={`${CARD} ${HALF} flex flex-col gap-2 p-3`}>+ <p className="text-[13px] font-medium text-zinc-800">{goal}</p>+ {str(output, "reason") && (+ <p className="text-xs text-zinc-500">{str(output, "reason")}</p>+ )}+ {actions && (+ <button+ type="button"+ className="w-fit rounded-lg bg-zinc-900 px-2.5 py-1.5 text-xs font-medium text-white transition-colors hover:bg-zinc-700"+ onClick={() =>+ actions.onSend(`Please create an agent with this goal: ${goal}`)+ }+ >+ Use this goal+ </button>+ )}+ </div>+ );+}++export function TriggerSetupCard({ output }: OutputProps) {+ const url = str(output, "webhook_url", "ingress_url");++ async function handleCopy() {+ if (!url) return;+ try {+ await navigator.clipboard.writeText(url);+ } catch {+ return;+ }+ }++ return (+ <div className={`${CARD} ${HALF} flex flex-col gap-2 p-3`}>+ <p className="text-[13px] text-zinc-700">+ {str(output, "message", "name") ?? "Trigger is ready"}+ </p>+ {url && (+ <div className="flex items-center gap-2 rounded-lg bg-zinc-50 p-2 ring-1 ring-zinc-200/70">+ <code className="min-w-0 flex-1 break-all text-xs text-zinc-600">+ {url}+ </code>+ <button+ type="button"+ onClick={handleCopy}+ className="shrink-0 rounded-md px-2 py-1 text-xs font-medium text-zinc-600 transition-colors hover:bg-zinc-200"+ >+ Copy+ </button>+ </div>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ListCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ListCards.tsxnew file mode 100644index 0000000000..3b664a6ed5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ListCards.tsx@@ -0,0 +1,242 @@+"use client";++import {+ BookOpenIcon,+ ClockIcon,+ FileIcon,+ FolderIcon,+ ImageIcon,+ LinkSquare01Icon,+ RepeatIcon,+} from "@hugeicons/core-free-icons";+import Link from "next/link";+import { Icon } from "@/components/atoms/Icon/Icon";+import { CARD, HALF } from "./ResultCards";+import {+ formatBytes,+ formatWhen,+ inline,+ resultItemKey,+ str,+} from "./resultHelpers";++interface SchedulesProps {+ schedules: Record<string, unknown>[];+}++interface OutputProps {+ output: Record<string, unknown>;+}++interface FoldersProps {+ folders: Record<string, unknown>[];+}++interface FilesProps {+ files: Record<string, unknown>[];+}++interface ResultsProps {+ results: Record<string, unknown>[];+}++export function FeatureRequestList({ results }: ResultsProps) {+ return (+ <div className="grid gap-1.5 sm:grid-cols-2">+ {results.map((request, i) => (+ <div+ key={resultItemKey(request, i)}+ className={CARD + " flex items-start gap-2.5 p-2.5"}+ >+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium text-zinc-800">+ {str(request, "title") ?? inline(request)}+ </p>+ {str(request, "description") && (+ <p className="truncate text-xs text-zinc-500">+ {str(request, "description")}+ </p>+ )}+ </div>+ {str(request, "identifier") && (+ <span className="shrink-0 rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] text-zinc-500">+ {str(request, "identifier")}+ </span>+ )}+ </div>+ ))}+ </div>+ );+}++export function ScheduleList({ schedules }: SchedulesProps) {+ return (+ <div className="grid gap-1.5 sm:grid-cols-2">+ {schedules.map((schedule, i) => {+ const next = str(schedule, "next_run_time");+ const recurring = !!str(schedule, "cron");+ return (+ <div+ key={resultItemKey(schedule, i)}+ className={CARD + " flex items-center gap-2.5 p-2.5"}+ >+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={ClockIcon} size={15} className="text-zinc-600" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium text-zinc-800">+ {str(schedule, "name", "message") ?? inline(schedule)}+ </p>+ {next && (+ <p className="flex items-center gap-1 text-xs text-zinc-500">+ {recurring && <Icon icon={RepeatIcon} size={11} />}+ {formatWhen(next)}+ </p>+ )}+ </div>+ {str(schedule, "kind") && (+ <span className="shrink-0 rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] text-zinc-500">+ {str(schedule, "kind") === "copilot_turn" ? "chat" : "agent"}+ </span>+ )}+ </div>+ );+ })}+ </div>+ );+}++export function ScheduleCreatedCard({ output }: OutputProps) {+ const next = str(output, "next_run_time");+ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2.5 p-2.5`}>+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={ClockIcon} size={15} className="text-zinc-600" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium text-zinc-800">+ Follow-up scheduled+ </p>+ {next && (+ <p className="flex items-center gap-1 text-xs text-zinc-500">+ {output.is_recurring === true && (+ <Icon icon={RepeatIcon} size={11} />+ )}+ {formatWhen(next)}+ </p>+ )}+ </div>+ </div>+ );+}++export function FolderList({ folders }: FoldersProps) {+ return (+ <div className="grid gap-1.5 sm:grid-cols-2">+ {folders.map((folder, i) => {+ const count =+ typeof folder.agent_count === "number" ? folder.agent_count : null;+ return (+ <div+ key={resultItemKey(folder, i)}+ className={CARD + " flex items-center gap-2.5 p-2.5"}+ >+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={FolderIcon} size={15} className="text-zinc-600" />+ </div>+ <p className="min-w-0 flex-1 truncate text-[13px] font-medium text-zinc-800">+ {str(folder, "name") ?? inline(folder)}+ </p>+ {count !== null && (+ <span className="shrink-0 text-xs text-zinc-400">+ {count} agent{count === 1 ? "" : "s"}+ </span>+ )}+ </div>+ );+ })}+ </div>+ );+}++export function FileList({ files }: FilesProps) {+ return (+ <div className={`${CARD} ${HALF} divide-y divide-zinc-100`}>+ {files.map((file, i) => {+ const mime = str(file, "mime_type") ?? "";+ const size =+ typeof file.size_bytes === "number" ? file.size_bytes : null;+ const fileIcon = mime.startsWith("image/") ? ImageIcon : FileIcon;+ return (+ <div+ key={resultItemKey(file, i)}+ className="flex items-center gap-2.5 px-2.5 py-2"+ >+ <Icon+ icon={fileIcon}+ size={14}+ className="shrink-0 text-zinc-400"+ />+ <p className="min-w-0 flex-1 truncate font-mono text-xs text-zinc-700">+ {str(file, "path", "name") ?? inline(file)}+ </p>+ {size !== null && (+ <span className="shrink-0 text-xs text-zinc-400">+ {formatBytes(size)}+ </span>+ )}+ </div>+ );+ })}+ </div>+ );+}++export function DocsList({ results }: ResultsProps) {+ return (+ <div className="grid gap-1.5 sm:grid-cols-2">+ {results.map((doc, i) => {+ const docUrl = str(doc, "doc_url");+ const section = str(doc, "section");+ return (+ <div+ key={resultItemKey(doc, i)}+ className={CARD + " flex items-start gap-2.5 p-2.5"}+ >+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={BookOpenIcon} size={15} className="text-zinc-600" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <p className="min-w-0 truncate text-[13px] font-medium text-zinc-800">+ {str(doc, "title", "path") ?? inline(doc)}+ </p>+ {section && (+ <span className="shrink-0 truncate text-[11px] text-zinc-400">+ {section}+ </span>+ )}+ </div>+ {str(doc, "snippet") && (+ <p className="truncate text-xs text-zinc-500">+ {str(doc, "snippet")}+ </p>+ )}+ </div>+ {docUrl && (+ <Link+ href={docUrl}+ target="_blank"+ rel="noreferrer"+ aria-label="Open doc"+ className="shrink-0 rounded-full p-1 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-700"+ >+ <Icon icon={LinkSquare01Icon} size={14} />+ </Link>+ )}+ </div>+ );+ })}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ResultCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ResultCards.tsxnew file mode 100644index 0000000000..2617a0478d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ResultCards.tsx@@ -0,0 +1,142 @@+"use client";++import {+ CancelCircleIcon,+ CheckmarkCircle02Icon,+ GlobeIcon,+ LinkSquare01Icon,+} from "@hugeicons/core-free-icons";+import Link from "next/link";+import { Icon } from "@/components/atoms/Icon/Icon";+import { safeHostname } from "./resultHelpers";++interface StatusPillProps {+ status: string;+}++interface StatusCardProps {+ label: string;+ ok: boolean;+}++interface StatCardProps {+ value: number;+ label: string;+}++interface ChipListProps {+ label: string;+ items: string[];+}++interface LinkCardProps {+ url: string;+ title?: string;+ meta?: string;+}++export const CARD = "rounded-xl bg-white ring-1 ring-zinc-200/70";+export const HALF = "w-full sm:w-1/2";++const STATUS_STYLES: Record<string, string> = {+ COMPLETED: "bg-green-50 text-green-600",+ FAILED: "bg-red-50 text-red-500",+ RUNNING: "bg-purple-50 text-purple-600",+ QUEUED: "bg-amber-50 text-amber-600",+};++export function StatusPill({ status }: StatusPillProps) {+ const normalized = status.toUpperCase();+ return (+ <span+ className={+ "shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium " ++ (STATUS_STYLES[normalized] ?? "bg-zinc-100 text-zinc-500")+ }+ >+ {normalized.toLowerCase()}+ </span>+ );+}++export function StatusCard({ label, ok }: StatusCardProps) {+ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2 p-2.5`}>+ {ok ? (+ <Icon+ icon={CheckmarkCircle02Icon}+ size={16}+ className="shrink-0 text-green-500"+ />+ ) : (+ <Icon+ icon={CancelCircleIcon}+ size={16}+ className="shrink-0 text-red-400"+ />+ )}+ <p className="min-w-0 truncate text-[13px] font-medium text-zinc-700">+ {label}+ </p>+ </div>+ );+}++export function StatCard({ value, label }: StatCardProps) {+ return (+ <div className={`${CARD} ${HALF} flex items-baseline gap-2 p-2.5`}>+ <span className="text-lg font-semibold leading-none text-zinc-800">+ {value.toLocaleString()}+ </span>+ <span className="min-w-0 truncate text-xs text-zinc-500">{label}</span>+ </div>+ );+}++export function ChipList({ label, items }: ChipListProps) {+ return (+ <div className={`${CARD} ${HALF} p-2.5`}>+ <p className="mb-1.5 text-[11px] uppercase tracking-wide text-zinc-400">+ {label}+ </p>+ <div className="flex flex-wrap gap-1">+ {Array.from(new Set(items)).map((item) => (+ <span+ key={item}+ className="max-w-full truncate rounded-full bg-zinc-100 px-2 py-0.5 text-xs text-zinc-600"+ >+ {item}+ </span>+ ))}+ </div>+ </div>+ );+}++export function LinkCard({ url, title, meta }: LinkCardProps) {+ const domain = safeHostname(url) ?? url;++ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2.5 p-2.5`}>+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={GlobeIcon} size={15} className="shrink-0 text-zinc-400" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium text-zinc-800">+ {title ?? domain}+ </p>+ <p className="truncate text-xs text-zinc-500">{title ? domain : url}</p>+ </div>+ {meta && <span className="shrink-0 text-xs text-zinc-400">{meta}</span>}+ <Link+ href={url}+ target="_blank"+ rel="noreferrer"+ aria-label="Open link"+ className="shrink-0 rounded-full p-1 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-700"+ >+ <Icon icon={LinkSquare01Icon} size={14} />+ </Link>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/RowIcon.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/RowIcon.tsxnew file mode 100644index 0000000000..82e32749bc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/RowIcon.tsx@@ -0,0 +1,132 @@+"use client";++import { useState } from "react";+import {+ AiEditingIcon,+ AlertDiamondIcon,+ BookBookmarkIcon,+ BookOpenIcon,+ BrainIcon,+ BubbleChatIcon,+ CheckListIcon,+ ClockIcon,+ ComputerIcon,+ ConnectIcon,+ DatabaseIcon,+ Delete02Icon,+ FileIcon,+ FilesIcon,+ FlashIcon,+ FolderIcon,+ Globe02Icon,+ HierarchyIcon,+ InformationCircleIcon,+ MegaphoneIcon,+ MessageQuestionIcon,+ PencilEdit01Icon,+ Plug01Icon,+ PuzzleIcon,+ RefreshIcon,+ Robot01Icon,+ Search01Icon,+ Settings01Icon,+ SlidersHorizontalIcon,+ TerminalIcon,+ WrenchIcon,+} from "@hugeicons/core-free-icons";+import Image from "next/image";+import { Icon } from "@/components/atoms/Icon/Icon";+import type { ChainRow } from "./helpers";++interface RowIconProps {+ row: ChainRow;+}++interface ProviderIconProps extends RowIconProps {+ src: string;+}++export function RowIcon({ row }: RowIconProps) {+ if (row.state === "error") {+ return <Icon icon={AlertDiamondIcon} size={16} className="text-red-500" />;+ }+ const cls = "text-zinc-600";+ switch (row.category) {+ case "narration":+ return <Icon icon={AiEditingIcon} size={16} className={cls} />;+ case "reasoning":+ return <Icon icon={BrainIcon} size={16} className={cls} />;+ case "bash":+ return <Icon icon={TerminalIcon} size={16} className={cls} />;+ case "web":+ return <Icon icon={Globe02Icon} size={16} className={cls} />;+ case "browser":+ return <Icon icon={ComputerIcon} size={16} className={cls} />;+ case "file-read":+ case "file-write":+ return <Icon icon={FileIcon} size={16} className={cls} />;+ case "file-delete":+ return <Icon icon={Delete02Icon} size={16} className={cls} />;+ case "file-list":+ return <Icon icon={FilesIcon} size={16} className={cls} />;+ case "search":+ return <Icon icon={Search01Icon} size={16} className={cls} />;+ case "edit":+ return <Icon icon={PencilEdit01Icon} size={16} className={cls} />;+ case "todo":+ return <Icon icon={CheckListIcon} size={16} className={cls} />;+ case "compaction":+ return <Icon icon={RefreshIcon} size={16} className={cls} />;+ case "agent":+ return <Icon icon={Robot01Icon} size={16} className={cls} />;+ case "agent-build":+ return <Icon icon={WrenchIcon} size={16} className={cls} />;+ case "plan":+ return <Icon icon={HierarchyIcon} size={16} className={cls} />;+ case "block":+ return <Icon icon={PuzzleIcon} size={16} className={cls} />;+ case "memory":+ return <Icon icon={DatabaseIcon} size={16} className={cls} />;+ case "folder":+ return <Icon icon={FolderIcon} size={16} className={cls} />;+ case "schedule":+ return <Icon icon={ClockIcon} size={16} className={cls} />;+ case "trigger":+ return <Icon icon={FlashIcon} size={16} className={cls} />;+ case "preset":+ return <Icon icon={SlidersHorizontalIcon} size={16} className={cls} />;+ case "chat":+ return <Icon icon={BubbleChatIcon} size={16} className={cls} />;+ case "mcp":+ return <Icon icon={Plug01Icon} size={16} className={cls} />;+ case "docs":+ return <Icon icon={BookOpenIcon} size={16} className={cls} />;+ case "skill":+ return <Icon icon={BookBookmarkIcon} size={16} className={cls} />;+ case "integration":+ return <Icon icon={ConnectIcon} size={16} className={cls} />;+ case "feature":+ return <Icon icon={MegaphoneIcon} size={16} className={cls} />;+ case "question":+ return <Icon icon={MessageQuestionIcon} size={16} className={cls} />;+ case "info":+ return <Icon icon={InformationCircleIcon} size={16} className={cls} />;+ default:+ return <Icon icon={Settings01Icon} size={16} className={cls} />;+ }+}++export function ProviderIcon({ src, row }: ProviderIconProps) {+ const [failed, setFailed] = useState(false);+ if (failed) return <RowIcon row={row} />;+ return (+ <Image+ src={src}+ alt=""+ width={16}+ height={16}+ className="rounded-sm object-contain"+ onError={() => setFailed(true)}+ />+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ShimmerText.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ShimmerText.tsxnew file mode 100644index 0000000000..a3c33a8baf--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ShimmerText.tsx@@ -0,0 +1,26 @@+"use client";++// Transitions.dev shimmer-text: ::before duplicates the string via+// content:attr(data-text) and sweeps a highlight band clipped to the glyphs.+interface Props {+ text: string;+ className?: string;+}++export function ShimmerText({ text, className }: Props) {+ return (+ <span+ data-text={text}+ className={+ "relative inline-block text-zinc-500 " ++ "before:pointer-events-none before:absolute before:inset-0 before:content-[attr(data-text)] " ++ "before:animate-shimmer-text before:bg-[linear-gradient(90deg,transparent_0%,transparent_40%,#18181b_50%,transparent_60%,transparent_100%)] " ++ "before:bg-[length:400%_100%] before:bg-clip-text before:bg-no-repeat before:text-transparent " ++ "motion-reduce:before:animate-none " ++ (className ?? "")+ }+ >+ {text}+ </span>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SwapText.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SwapText.tsxnew file mode 100644index 0000000000..2d030adc00--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SwapText.tsx@@ -0,0 +1,41 @@+"use client";++import {+ AnimatePresence,+ domAnimation,+ LazyMotion,+ m,+ useReducedMotion,+} from "framer-motion";+import { ShimmerText } from "./ShimmerText";++const EASE_OUT_CUBIC = [0.33, 1, 0.68, 1] as const;++interface SwapTextProps {+ text: string;+ className?: string;+ shimmer?: boolean;+}++// Old label slides up + fades out, new one slides in from below.+export function SwapText({ text, className, shimmer = false }: SwapTextProps) {+ const reducedMotion = useReducedMotion();+ return (+ <LazyMotion features={domAnimation} strict>+ <span className={"inline-grid overflow-hidden " + (className ?? "")}>+ <AnimatePresence mode="popLayout" initial={false}>+ <m.span+ key={text}+ initial={reducedMotion ? false : { opacity: 0, y: 8 }}+ animate={{ opacity: 1, y: 0 }}+ exit={reducedMotion ? undefined : { opacity: 0, y: -8 }}+ transition={{ duration: 0.18, ease: EASE_OUT_CUBIC }}+ className="block truncate"+ >+ {shimmer ? <ShimmerText text={text} /> : text}+ </m.span>+ </AnimatePresence>+ </span>+ </LazyMotion>+ );+}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.tsxnew file mode 100644index 0000000000..6ccd42a266--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx@@ -0,0 +1,342 @@+"use client";++import {+ ArrowDown01Icon,+ SentIcon,+ Tick02Icon,+} from "@hugeicons/core-free-icons";+import {+ AnimatePresence,+ domAnimation,+ LazyMotion,+ m,+ useReducedMotion,+} from "framer-motion";+import {+ useCallback,+ useContext,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { ChainActionCard } from "../ChainActionCard/ChainActionCard";+import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContext";+import type { MessagePart } from "../ChatMessagesContainer/helpers";+import { ACCORDION_PANEL, accordionState, PANEL_REVEAL } from "./accordion";+import { ChainActionsContext, type ChainActionEntry } from "./chainActions";+import { ChainRowView } from "./ChainRowView";+import {+ type ChainRow,+ getChainHeading,+ isLiftedSetupRow,+ toChainRow,+} from "./helpers";+import { SwapText } from "./SwapText";+import { ToolResult } from "./ToolResult";++const COLLAPSED_WINDOW = 2;++interface Props {+ parts: MessagePart[];+ isStreaming: boolean;+}++export function ToolChain({ parts, isStreaming }: Props) {+ const [manualExpanded, setManualExpanded] = useState<boolean | null>(null);+ const panelId = useId();+ const reducedMotion = useReducedMotion();++ const pendingQuestions = useContext(PendingQuestionsContext);+ const { setInitialPrompt, sentMessageCount } = useCopilotUIStore();+ // 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);++ // 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.+ const [actionEntries, setActionEntries] = useState<+ ReadonlyMap<string, ChainActionEntry>+ >(new Map());+ const register = useCallback((entry: ChainActionEntry) => {+ setActionEntries((prev) => {+ const next = new Map(prev);+ next.set(entry.id, entry);+ return next;+ });+ }, []);+ const unregister = useCallback((id: string) => {+ setActionEntries((prev) => {+ if (!prev.has(id)) return prev;+ const next = new Map(prev);+ next.delete(id);+ return next;+ });+ }, []);+ const chainActions = useMemo(+ () => ({ register, unregister }),+ [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 rows = useMemo(+ () =>+ parts+ .map((part, i) => toChainRow(part, i))+ .filter((row): row is ChainRow => row !== null)+ // Unanswered clarifying questions and setup cards render their work+ // in the card below the chain — their rows are lifted out of view.+ .map((row) =>+ pendingQuestions?.callIds.includes(row.key)+ ? { ...row, requiresAction: true, lifted: true }+ : isLiftedSetupRow(row)+ ? { ...row, lifted: true }+ : row,+ ),+ [parts, pendingQuestions],+ );+ if (rows.length === 0) return null;++ const shownRows = rows.filter((row) => !row.lifted);+ const liftedRows = rows.filter((row) => row.lifted);++ const expanded = manualExpanded === true;+ const heading = getChainHeading(rows, isStreaming && !expanded);+ const hasError = rows.some((row) => row.state === "error");+ const hasRequiredAction = shownRows.some((row) => row.requiresAction);+ // Auto-open only while streaming; once the chain finishes (or on reload)+ // it collapses back to the heading, leaving just the action rows on+ // screen. A manual toggle overrides either direction and sticks.+ const open = manualExpanded ?? isStreaming;+ const windowMode = isStreaming && !expanded && !hasRequiredAction;+ // Action-required cards (credential setup etc.) can never leave the+ // screen: collapsing the chain hides the other rows but keeps the+ // action rows visible, and the streaming window is disabled for them.+ const actionOnly = !open && hasRequiredAction;+ const panelOpen = open || actionOnly;+ // Rows stay mounted while closed so the 0fr collapse can animate.+ const visible = actionOnly+ ? shownRows.filter((row) => row.requiresAction)+ : windowMode+ ? shownRows.slice(-COLLAPSED_WINDOW)+ : shownRows;++ // A finished chain closes with a "Done" step, so the rail always ends on+ // a resolved node instead of trailing off the last tool. An errored or+ // still-running chain has no such ending.+ const showDone = !isStreaming && !hasError && !windowMode;++ 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 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+ // out instead of blocking the ready ones. Cards stay registered until+ // the message actually goes out, at which point their onSent fires.+ function handleProceed() {+ const readyActions = pendingActions.filter((entry) => entry.ready);+ const message = readyActions+ .map((entry) => entry.buildMessage())+ .filter(Boolean)+ .join("\n\n");+ if (!message) return;+ draftedRef.current = {+ ids: readyActions.map((entry) => entry.id),+ sentAt: sentMessageCount,+ };+ setInitialPrompt(message);+ }++ return (+ <LazyMotion features={domAnimation} strict>+ <div className="my-2">+ {shownRows.length > 0 && (+ <>+ <button+ type="button"+ onClick={() => setManualExpanded(!open)}+ aria-expanded={panelOpen}+ aria-controls={panelId}+ className="group/chain -mx-2 flex w-fit max-w-full items-center gap-1.5 rounded-lg px-2 py-1 text-left transition-colors duration-100 hover:bg-zinc-100"+ >+ <SwapText+ text={heading}+ shimmer={isStreaming && !expanded}+ className={+ "min-w-0 text-sm font-normal " ++ (hasError && !isStreaming ? "text-red-500" : "text-zinc-700")+ }+ />+ <Icon+ icon={ArrowDown01Icon}+ size={12}+ className={+ "shrink-0 text-zinc-400 transition-transform duration-300 ease-out-quint " ++ (open ? "rotate-180" : "")+ }+ />+ </button>+ <div className={ACCORDION_PANEL + " " + accordionState(panelOpen)}>+ <div+ id={panelId}+ aria-hidden={!panelOpen}+ inert={panelOpen ? undefined : ("" as unknown as boolean)}+ className="min-h-0 overflow-hidden"+ >+ <div+ className={+ "flex flex-col pl-0.5 pt-2.5" ++ (panelOpen && !windowMode ? " " + PANEL_REVEAL : "")+ }+ >+ <AnimatePresence mode="popLayout">+ {visible.map((row, i) => (+ <m.div+ key={row.key}+ layout={!reducedMotion}+ initial={+ reducedMotion+ ? false+ : { opacity: 0, y: 8, scale: 0.985 }+ }+ animate={{ opacity: 1, y: 0, scale: 1 }}+ exit={+ reducedMotion+ ? undefined+ : { opacity: 0, y: -6, scale: 0.985 }+ }+ transition={{+ opacity: {+ duration: reducedMotion ? 0 : 0.18,+ delay: reducedMotion ? 0 : Math.min(i, 6) * 0.035,+ ease: [0.22, 1, 0.36, 1],+ },+ y: {+ duration: reducedMotion ? 0 : 0.22,+ delay: reducedMotion ? 0 : Math.min(i, 6) * 0.035,+ ease: [0.22, 1, 0.36, 1],+ },+ scale: {+ duration: reducedMotion ? 0 : 0.22,+ delay: reducedMotion ? 0 : Math.min(i, 6) * 0.035,+ ease: [0.22, 1, 0.36, 1],+ },+ layout: {+ duration: reducedMotion ? 0 : 0.22,+ ease: [0.22, 1, 0.36, 1],+ },+ }}+ >+ <ChainActionsContext.Provider value={chainActions}>+ <ChainRowView+ row={row}+ isLast={i === visible.length - 1 && !showDone}+ />+ </ChainActionsContext.Provider>+ </m.div>+ ))}+ </AnimatePresence>+ {showDone && (+ <div className="flex items-stretch gap-2.5">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon+ icon={Tick02Icon}+ size={14}+ className="text-zinc-600"+ />+ </div>+ <div className="flex h-7 items-center text-sm text-zinc-600">+ Done+ </div>+ </div>+ )}+ </div>+ </div>+ </div>+ </>+ )}++ {/* Lifted rows render off-screen: their cards must stay mounted so+ the ChainActionCard below keeps its registrations. */}+ {liftedRows.length > 0 && (+ <div className="hidden">+ <ChainActionsContext.Provider value={chainActions}>+ {liftedRows.map((row) => (+ <ToolResult key={row.key} row={row} />+ ))}+ </ChainActionsContext.Provider>+ </div>+ )}++ {/* Lifted out of the rows: connecting, filling inputs and answering+ questions are the user's own work, so every card's asks merge into+ one card under the chain that stays put when it collapses. */}+ {hasCardWork && (+ <ChainActionCard+ connectors={connectorRequests}+ mcp={mcpRequests}+ inputs={inputRequests}+ questions={questionRequests}+ isReady={allActionsReady}+ onProceed={handleProceed}+ />+ )}++ {/* Cards with nothing to connect, fill in or answer (confirm-only)+ still need somewhere to send from. */}+ {pendingActions.length > 0 && !hasCardWork && (+ <div className="mt-1 flex flex-col items-start gap-2">+ <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"}+ </span>+ <Button+ variant="primary"+ size="small"+ disabled={!allActionsReady}+ onClick={handleProceed}+ >+ Proceed+ </Button>+ </div>+ )}+ </div>+ </LazyMotion>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsxnew file mode 100644index 0000000000..6ac7f45eb1--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx@@ -0,0 +1,429 @@+"use client";++import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";+import { useContext } from "react";+import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContext";+import { QuestionsForm } from "../QuestionDock/QuestionDock";+import { SetupRequirementsCard } from "../SetupRequirementsCard/SetupRequirementsCard";+import { MCPSetupCard } from "../../tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard";+import {+ AgentListCard,+ AgentPreviewCard,+ AgentSavedCard,+ SubSessionCard,+} from "./AgentCards";+import { BlockListCard, BlockOutputCard } from "./BlockCards";+import { ExecutionCard } from "./ExecutionCard";+import { FileDiff } from "./FileDiff";+import { isDiffText } from "./fileDiffHelpers";+import type { ChainRow } from "./helpers";+import {+ FixResultCard,+ PlanSteps,+ QuestionsCard,+ SkillCard,+ SuggestedGoalCard,+ TriggerSetupCard,+ ValidationCard,+} from "./InfoCards";+import { extractClarifyingQuestions } from "../../tools/clarifying-questions";+import {+ DocsList,+ FeatureRequestList,+ FileList,+ FolderList,+ ScheduleCreatedCard,+ ScheduleList,+} from "./ListCards";+import {+ CARD,+ ChipList,+ HALF,+ LinkCard,+ StatCard,+ StatusCard,+ StatusPill,+} from "./ResultCards";+import {+ asItems,+ asObject,+ dictToOutputItems,+ humanizeKey,+ str,+ stripBaseFields,+} from "./resultHelpers";+import {+ FileCard,+ KeyValueList,+ OutputList,+ SearchResults,+ Terminal,+ TodoList,+} from "./ToolResultViews";++const BOOLEAN_LABELS: Record<string, string> = {+ ok: "Done",+ success: "Done",+};++function shapeCard(obj: Record<string, unknown>) {+ const entries = Object.entries(obj);+ if (entries.length !== 1) return null;+ const [key, value] = entries[0];++ if (typeof value === "boolean")+ return (+ <StatusCard ok={value} label={BOOLEAN_LABELS[key] ?? humanizeKey(key)} />+ );++ if (typeof value === "number")+ return <StatCard value={value} label={humanizeKey(key).toLowerCase()} />;++ if (+ Array.isArray(value) &&+ value.length > 0 &&+ value.every((item) => typeof item === "string")+ )+ return <ChipList label={humanizeKey(key)} items={value as string[]} />;++ if (key === "status" && typeof value === "string")+ return (+ <div className={`${CARD} ${HALF} flex items-center gap-2 p-2.5`}>+ <span className="text-xs text-zinc-400">Status</span>+ <span className="ml-auto">+ <StatusPill status={value} />+ </span>+ </div>+ );++ return null;+}++function linkCard(+ output: Record<string, unknown>,+ input: Record<string, unknown> | null,+) {+ const url =+ str(output, "url", "ingress_url", "link", "webhook_url", "issue_url") ??+ (input ? str(input, "url", "server_url") : null);+ if (!url || !/^https?:\/\//.test(url)) return null;++ const { status, status_code, bytes, content_length } = output;+ const size =+ typeof bytes === "number"+ ? bytes+ : typeof content_length === "number"+ ? content_length+ : null;+ const code =+ typeof status === "number"+ ? status+ : typeof status_code === "number"+ ? status_code+ : null;+ const meta =+ size !== null+ ? `${(size / 1024).toFixed(1)} KB`+ : code !== null+ ? String(code)+ : undefined;++ return (+ <LinkCard+ url={url}+ title={str(output, "title", "issue_title") ?? undefined}+ meta={meta}+ />+ );+}++function chipStrings(value: unknown, key: string): string[] | null {+ const items = asItems(value);+ if (!items) return null;+ const labels = items+ .map((item) => str(item, key))+ .filter((label): label is string => !!label);+ return labels.length > 0 ? labels : null;+}++function setupRequirementsCard(row: ChainRow, output: Record<string, unknown>) {+ const setupInfo = asObject(output.setup_info);+ if (!setupInfo) return null;+ const setupOutput = output as unknown as SetupRequirementsResponse;++ if (row.tool === "run_mcp_tool") {+ return (+ <MCPSetupCard+ output={setupOutput}+ retryInstruction="I've connected the MCP server credentials. Please retry run_mcp_tool with the same server URL and arguments."+ />+ );+ }++ if (row.tool === "setup_agent_webhook_trigger") {+ return (+ <SetupRequirementsCard+ output={setupOutput}+ inputsMode="trigger"+ credentialsLabel="Account"+ />+ );+ }++ if (row.tool === "run_agent" || row.tool === "schedule_agent") {+ return <SetupRequirementsCard output={setupOutput} inputsMode="preview" />;+ }++ return (+ <SetupRequirementsCard+ output={setupOutput}+ credentialsLabel={+ row.tool === "connect_integration"+ ? `${str(setupInfo, "agent_name") ?? "Integration"} credentials`+ : undefined+ }+ retryInstruction={+ row.tool === "connect_integration"+ ? "I've connected my account. Please continue."+ : undefined+ }+ />+ );+}++function toolCard(row: ChainRow, output: Record<string, unknown> | null) {+ const input = asObject(row.input);++ if (output) {+ const setupCard = setupRequirementsCard(row, output);+ if (setupCard) return setupCard;+ const questions = asItems(output.questions);+ if (questions) return <QuestionsCard questions={questions} />;+ }++ switch (row.tool) {+ case "run_agent":+ case "schedule_agent": {+ const name =+ (output && str(output, "graph_name", "agent_name")) ??+ (input ? str(input, "username_agent_slug", "agent_name") : null);+ if (output && name && str(output, "execution_id")) {+ const graphID = str(output, "graph_id");+ const executionID = str(output, "execution_id");+ return (+ <ExecutionCard+ name={name}+ status={str(output, "status") ?? undefined}+ href={+ str(output, "library_agent_link") ??+ (graphID && executionID+ ? `/library/agents/${graphID}?activeTab=runs&activeItem=${executionID}`+ : undefined)+ }+ />+ );+ }+ const agent = output && asObject(output.agent);+ if (agent) return <AgentListCard agents={[agent]} />;+ const execution = output && asObject(output.execution);+ const items = execution && dictToOutputItems(execution.outputs);+ return items ? <OutputList items={items} /> : null;+ }+ case "view_agent_output": {+ const execution = output && asObject(output.execution);+ const items =+ (execution && dictToOutputItems(execution.outputs)) ??+ (output && asItems(output.outputs));+ return items ? <OutputList items={items} /> : null;+ }+ case "create_agent":+ case "customize_agent":+ case "edit_agent": {+ if (output && str(output, "suggested_goal")) {+ return <SuggestedGoalCard output={output} />;+ }+ const name = output && str(output, "agent_name", "name", "graph_name");+ if (!output || !name) return null;+ return str(output, "library_agent_link", "agent_page_link") ? (+ <AgentSavedCard output={output} />+ ) : (+ <AgentPreviewCard output={output} />+ );+ }+ case "run_sub_session":+ case "get_sub_session_result":+ return output && str(output, "status") ? (+ <SubSessionCard output={output} />+ ) : null;+ case "find_agent":+ case "find_library_agent": {+ const agents = output && asItems(output.agents);+ return agents ? <AgentListCard agents={agents} /> : null;+ }+ case "find_block": {+ const blocks = output && asItems(output.blocks);+ return blocks ? <BlockListCard blocks={blocks} /> : null;+ }+ case "run_block":+ case "continue_run_block": {+ if (!output) return null;+ const block = asObject(output.block);+ if (block) return <BlockListCard blocks={[block]} />;+ if (str(output, "block_name", "block_id"))+ return <BlockOutputCard output={output} />;+ return null;+ }+ case "connect_integration":+ return null;+ case "decompose_goal": {+ const steps = output && asItems(output.steps);+ return steps ? <PlanSteps steps={steps} /> : null;+ }+ case "validate_agent_graph":+ return output ? <ValidationCard output={output} /> : null;+ case "fix_agent_graph":+ return output ? <FixResultCard output={output} /> : null;+ // Interactive answering lives in the QuestionDock above the chat input;+ // the chain row keeps a read-only record of what was asked.+ case "ask_question": {+ const questions = extractClarifyingQuestions(row);+ return questions.length > 0 ? (+ <QuestionsCard+ questions={questions as unknown as Record<string, unknown>[]}+ />+ ) : null;+ }+ case "list_schedules": {+ const schedules = output && asItems(output.schedules);+ return schedules ? <ScheduleList schedules={schedules} /> : null;+ }+ case "schedule_followup":+ return output && str(output, "next_run_time") ? (+ <ScheduleCreatedCard output={output} />+ ) : null;+ case "list_folders": {+ const folders = output && asItems(output.folders);+ return folders ? <FolderList folders={folders} /> : null;+ }+ case "create_folder":+ case "update_folder":+ case "move_folder": {+ const folder = output && asObject(output.folder);+ return folder ? <FolderList folders={[folder]} /> : null;+ }+ case "list_workspace_files": {+ const files = output && asItems(output.files);+ return files ? <FileList files={files} /> : null;+ }+ case "search_docs": {+ const results = output && asItems(output.results);+ return results ? <DocsList results={results} /> : null;+ }+ case "get_doc_page":+ return output && str(output, "title") ? (+ <DocsList results={[output]} />+ ) : null;+ case "setup_agent_webhook_trigger":+ return output &&+ (str(output, "webhook_url", "ingress_url") ||+ output.manual_setup_required === true) ? (+ <TriggerSetupCard output={output} />+ ) : null;+ case "search_feature_requests": {+ const results = output && asItems(output.results);+ return results ? <FeatureRequestList results={results} /> : null;+ }+ case "create_feature_request":+ return output+ ? (linkCard(output, input) ?? <KeyValueList value={output} />)+ : null;+ case "run_mcp_tool":+ return output && "result" in output ? (+ <KeyValueList value={output.result} />+ ) : null;+ case "store_skill":+ case "read_skill":+ case "delete_skill":+ return output ? <SkillCard output={output} /> : null;+ case "list_skills": {+ const names = output && chipStrings(output.skills, "name");+ return names ? <ChipList label="Skills" items={names} /> : null;+ }+ case "list_chat_platform_channels": {+ const names = output && chipStrings(output.channels, "name");+ return names ? (+ <ChipList label="Channels" items={names.map((name) => `#${name}`)} />+ ) : null;+ }+ case "web_search": {+ const items = output && asItems(output.results);+ const answer = output && str(output, "answer");+ if (items) return <SearchResults items={items} answer={answer} />;+ if (answer) return <KeyValueList value={answer} />;+ return null;+ }+ case "bash_exec":+ return <Terminal row={row} />;+ case "TodoWrite":+ return <TodoList row={row} />;+ case "read_workspace_file":+ case "write_workspace_file":+ case "delete_workspace_file":+ case "Read":+ case "Write":+ return <FileCard row={row} />;+ }+ return null;+}++interface Props {+ row: ChainRow;+}++export function ToolResult({ row }: Props) {+ const output = asObject(row.output);+ const pendingQuestions = useContext(PendingQuestionsContext);++ // The latest unanswered clarifying questions render as an interactive+ // answer form right on their chain row (older ones keep the read-only+ // card from toolCard).+ if (pendingQuestions?.callIds.includes(row.key)) {+ return (+ <QuestionsForm+ key={pendingQuestions.dockId}+ dockId={pendingQuestions.dockId}+ questions={pendingQuestions.questions}+ />+ );+ }++ if (!output && isDiffText(row.output)) {+ const input = asObject(row.input);+ return (+ <FileDiff+ file={+ input ? (str(input, "file_path", "path") ?? undefined) : undefined+ }+ diff={row.output}+ />+ );+ }++ const card = toolCard(row, output);+ if (card) return card;++ if (!output) return <KeyValueList value={row.output} />;++ const data = stripBaseFields(output);++ const outputs = asItems(data.outputs) ?? dictToOutputItems(data.outputs);+ if (outputs) return <OutputList items={outputs} />;++ if (Object.keys(data).length === 0)+ return <KeyValueList value={str(output, "message") ?? ""} />;++ return (+ linkCard(data, asObject(row.input)) ??+ shapeCard(data) ?? <KeyValueList value={data} />+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResultViews.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResultViews.tsxnew file mode 100644index 0000000000..87532cb17e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResultViews.tsx@@ -0,0 +1,277 @@+"use client";++import {+ CheckmarkCircle02Icon,+ CircleIcon,+ FileIcon,+ GlobeIcon,+ ImageIcon,+} from "@hugeicons/core-free-icons";+import { Icon } from "@/components/atoms/Icon/Icon";+import { useLayoutEffect, useRef, useState } from "react";+import type { ChainRow } from "./helpers";+import { CARD, HALF } from "./ResultCards";+import {+ asItems,+ asObject,+ formatBytes,+ humanizeKey,+ inline,+ resultItemKey,+ safeHostname,+ str,+} from "./resultHelpers";++interface SearchResultsProps {+ items: Record<string, unknown>[];+ answer?: string | null;+}++interface RowProps {+ row: ChainRow;+}++interface ItemsProps {+ items: Record<string, unknown>[];+}++interface ValueProps {+ value: unknown;+}++function ResultFavicon({ domain }: { domain: string | null }) {+ const [failed, setFailed] = useState(false);+ if (!domain || failed) {+ return (+ <Icon icon={GlobeIcon} size={14} className="shrink-0 text-zinc-400" />+ );+ }+ return (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={`https://${encodeURIComponent(domain)}/favicon.ico`}+ alt=""+ width={14}+ height={14}+ className="size-3.5 shrink-0 rounded-[3px]"+ referrerPolicy="no-referrer"+ onError={() => setFailed(true)}+ />+ );+}++function ClampedAnswer({ answer }: { answer: string }) {+ const textRef = useRef<HTMLParagraphElement>(null);+ const [clamped, setClamped] = useState(false);++ useLayoutEffect(() => {+ const el = textRef.current;+ if (el) setClamped(el.scrollHeight > el.clientHeight + 1);+ }, [answer]);++ return (+ <div className="relative">+ <p+ ref={textRef}+ className="line-clamp-3 px-3 py-2 text-[13px] leading-5 text-zinc-600"+ >+ {answer}+ </p>+ {clamped && (+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-white to-transparent" />+ )}+ </div>+ );+}++export function SearchResults({ items, answer }: SearchResultsProps) {+ return (+ <div className={CARD + " divide-y divide-zinc-100"}>+ {answer && <ClampedAnswer answer={answer} />}+ {items.map((item, i) => {+ const url = str(item, "url", "link");+ const domain = url ? safeHostname(url) : null;+ const title = str(item, "title", "snippet") ?? inline(item);+ return (+ <div+ key={resultItemKey(item, i)}+ className="flex items-center gap-2.5 px-3 py-2"+ >+ <ResultFavicon domain={domain} />+ {url ? (+ <a+ href={url}+ target="_blank"+ rel="noreferrer"+ className="min-w-0 truncate text-[13px] text-zinc-700 hover:text-zinc-900 hover:underline"+ >+ {title}+ </a>+ ) : (+ <p className="min-w-0 truncate text-[13px] text-zinc-700">+ {title}+ </p>+ )}+ {domain && (+ <span className="ml-auto shrink-0 text-xs text-zinc-400">+ {domain}+ </span>+ )}+ </div>+ );+ })}+ </div>+ );+}++export function Terminal({ row }: RowProps) {+ const input = asObject(row.input);+ const output = asObject(row.output);+ const command = input ? str(input, "command") : null;+ const stdout = output ? str(output, "stdout", "stderr") : null;+ const exitCode = output?.exit_code;+ return (+ <div className="rounded-xl bg-zinc-900 p-3 font-mono text-[11px] leading-4">+ {command && (+ <p className="whitespace-pre-wrap break-words text-zinc-400">+ <span className="select-none text-zinc-500">$ </span>+ {command}+ </p>+ )}+ {stdout && (+ <pre className="mt-1.5 max-h-40 overflow-y-auto whitespace-pre-wrap break-words text-zinc-100 scrollbar-none">+ {stdout}+ </pre>+ )}+ {typeof exitCode === "number" && exitCode !== 0 && (+ <p className="mt-1.5 text-red-400">exit {exitCode}</p>+ )}+ </div>+ );+}++export function TodoList({ row }: RowProps) {+ const input = asObject(row.input);+ const todos = input ? asItems(input.todos) : null;+ if (!todos) return <KeyValueList value={row.output} />;+ return (+ <div className={CARD + " flex flex-col gap-1.5 p-3"}>+ {todos.map((todo, i) => {+ const done = todo.status === "completed";+ const active = todo.status === "in_progress";+ return (+ <div+ key={resultItemKey(todo, i)}+ className="flex items-center gap-2 text-[13px]"+ >+ {done ? (+ <Icon+ icon={CheckmarkCircle02Icon}+ size={15}+ className="shrink-0 text-green-500"+ />+ ) : (+ <Icon+ icon={CircleIcon}+ size={15}+ className={+ "shrink-0 " + (active ? "text-purple-500" : "text-zinc-300")+ }+ />+ )}+ <span+ className={+ done+ ? "text-zinc-400 line-through"+ : active+ ? "font-medium text-zinc-800"+ : "text-zinc-600"+ }+ >+ {str(todo, "content", "activeForm") ?? inline(todo)}+ </span>+ </div>+ );+ })}+ </div>+ );+}++export function FileCard({ row }: RowProps) {+ const input = asObject(row.input);+ const output = asObject(row.output);+ const path =+ (input ? str(input, "file_path", "path", "filename") : null) ??+ (output ? str(output, "path", "name") : null);+ if (!path) return <KeyValueList value={row.output} />;+ const size = output?.size ?? output?.size_bytes;+ const mime = output ? (str(output, "mime_type") ?? "") : "";+ const preview = output ? str(output, "preview", "content_preview") : null;+ const fileIcon = mime.startsWith("image/") ? ImageIcon : FileIcon;+ return (+ <div className={`${CARD} ${HALF} p-2.5`}>+ <div className="flex items-center gap-2.5">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-zinc-100">+ <Icon icon={fileIcon} size={15} className="text-zinc-600" />+ </div>+ <p className="min-w-0 flex-1 truncate font-mono text-xs text-zinc-700">+ {path}+ </p>+ {typeof size === "number" && (+ <span className="shrink-0 text-xs text-zinc-400">+ {formatBytes(size)}+ </span>+ )}+ </div>+ {preview && (+ <p className="mt-1.5 line-clamp-2 whitespace-pre-wrap pl-9 text-xs text-zinc-400">+ {preview}+ </p>+ )}+ </div>+ );+}++export function OutputList({ items }: ItemsProps) {+ return (+ <div className={`${CARD} ${HALF} divide-y divide-zinc-100`}>+ {items.map((item, i) => (+ <div key={resultItemKey(item, i)} className="p-2.5">+ <p className="text-[11px] uppercase tracking-wide text-zinc-400">+ {str(item, "name", "key", "label") ?? `Output ${i + 1}`}+ </p>+ <p className="mt-0.5 whitespace-pre-wrap break-words text-[13px] text-zinc-800">+ {inline(item.value ?? item)}+ </p>+ </div>+ ))}+ </div>+ );+}++export function KeyValueList({ value }: ValueProps) {+ const obj = asObject(value);+ if (!obj || Object.keys(obj).length === 0) {+ if (typeof value !== "string" || !value.trim()) return null;+ return (+ <pre className="max-h-40 overflow-y-auto whitespace-pre-wrap break-words rounded-xl bg-zinc-50 p-2.5 font-mono text-[11px] leading-4 text-zinc-600 scrollbar-none">+ {value}+ </pre>+ );+ }+ return (+ <div className={`${CARD} ${HALF} p-2.5`}>+ {Object.entries(obj).map(([key, entryValue]) => (+ <div+ key={key}+ className="flex items-baseline gap-3 py-1 text-xs first:pt-0 last:pb-0"+ >+ <span className="shrink-0 text-zinc-400">{humanizeKey(key)}</span>+ <span className="ml-auto min-w-0 break-words text-right font-medium text-zinc-700">+ {inline(entryValue)}+ </span>+ </div>+ ))}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolStatusBadge.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolStatusBadge.tsxnew file mode 100644index 0000000000..fd340a74a6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolStatusBadge.tsx@@ -0,0 +1,48 @@+"use client";++import { domAnimation, LazyMotion, m, useReducedMotion } from "framer-motion";+import type { ChainRowState } from "./helpers";++interface Props {+ state: ChainRowState;+ label: string;+ children: React.ReactNode;+}++export function ToolStatusBadge({ state, label, children }: Props) {+ const reducedMotion = useReducedMotion();+ const running = state === "running";++ return (+ <LazyMotion features={domAnimation} strict>+ <m.span+ data-state={running ? "spinning" : state}+ role="img"+ aria-label={label}+ className="relative flex size-[22px] shrink-0 items-center justify-center"+ >+ {/* -inset-[3px] lands the 1px ring exactly on the size-7 circle edge. */}+ <m.span+ aria-hidden="true"+ className="absolute -inset-[3px] rounded-full border border-zinc-200"+ initial={{ opacity: running ? 1 : 0 }}+ animate={{ opacity: running ? 1 : 0 }}+ transition={{ duration: reducedMotion ? 0 : 0.16 }}+ />+ <m.span+ aria-hidden="true"+ className="absolute -inset-[3px] animate-[spin_0.9s_linear_infinite] rounded-full border border-transparent border-t-zinc-500 motion-reduce:animate-none"+ initial={{ opacity: running ? 1 : 0 }}+ animate={{ opacity: running ? 1 : 0 }}+ transition={{ duration: reducedMotion ? 0 : 0.12 }}+ />+ <span+ aria-hidden="true"+ className="relative flex items-center justify-center"+ >+ {children}+ </span>+ </m.span>+ </LazyMotion>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/AgentCards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/AgentCards.test.tsxnew file mode 100644index 0000000000..a496f0c908--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/AgentCards.test.tsx@@ -0,0 +1,175 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import {+ AgentListCard,+ AgentPreviewCard,+ AgentSavedCard,+ SubSessionCard,+} from "../AgentCards";++describe("AgentListCard", () => {+ afterEach(cleanup);++ it("links library agents to the library page", () => {+ render(+ <AgentListCard+ agents={[{ id: "lib-1", source: "library", name: "Lib Agent" }]}+ />,+ );++ expect(screen.getByText("Lib Agent")).toBeDefined();+ expect(screen.getByLabelText("Open agent").getAttribute("href")).toBe(+ "/library/agents/lib-1",+ );+ });++ it("links marketplace agents by creator and slug", () => {+ render(+ <AgentListCard+ agents={[+ {+ id: "creator/scraper",+ name: "Scraper",+ creator: "creator",+ description: "Scrapes websites",+ runs: 1200,+ rating: 4.55,+ },+ ]}+ />,+ );++ expect(screen.getByText("Scraper")).toBeDefined();+ expect(screen.getByText("by creator")).toBeDefined();+ expect(screen.getByText("Scrapes websites")).toBeDefined();+ expect(screen.getByText("1,200 runs")).toBeDefined();+ expect(screen.getByText("4.5")).toBeDefined();+ expect(screen.getByLabelText("Open agent").getAttribute("href")).toBe(+ "/marketplace/agent/creator/scraper",+ );+ });++ it("omits the link for ids that are not creator/slug pairs", () => {+ render(+ <AgentListCard agents={[{ id: "a/b/c", name: "Deep Path Agent" }]} />,+ );++ expect(screen.getByText("Deep Path Agent")).toBeDefined();+ expect(screen.queryByLabelText("Open agent")).toBeNull();+ });++ it("falls back to inline JSON for unnamed agents", () => {+ render(<AgentListCard agents={[{ runs: 3 }]} />);++ expect(screen.getByText('{"runs":3}')).toBeDefined();+ });+});++describe("AgentSavedCard", () => {+ afterEach(cleanup);++ it("shows the version with builder and library links", () => {+ render(+ <AgentSavedCard+ output={{+ agent_name: "My Agent",+ graph_version: 3,+ agent_page_link: "/build?flowID=graph-1",+ library_agent_link: "/library/agents/lib-1",+ }}+ />,+ );++ expect(screen.getByText("My Agent")).toBeDefined();+ expect(screen.getByText("v3")).toBeDefined();+ expect(screen.getByLabelText("Open in builder").getAttribute("href")).toBe(+ "/build?flowID=graph-1",+ );+ expect(screen.getByLabelText("Open in library").getAttribute("href")).toBe(+ "/library/agents/lib-1",+ );+ });++ it("falls back to a default name and no links", () => {+ render(<AgentSavedCard output={{}} />);++ expect(screen.getByText("Agent")).toBeDefined();+ expect(screen.queryByLabelText("Open in library")).toBeNull();+ });++ it("builds the library link from the library agent id", () => {+ render(+ <AgentSavedCard+ output={{ name: "Fallback Agent", library_agent_id: "lib-9" }}+ />,+ );++ expect(screen.getByText("Fallback Agent")).toBeDefined();+ expect(screen.getByLabelText("Open in library").getAttribute("href")).toBe(+ "/library/agents/lib-9",+ );+ expect(screen.queryByLabelText("Open in builder")).toBeNull();+ });+});++describe("AgentPreviewCard", () => {+ afterEach(cleanup);++ it("shows the name, description and block count", () => {+ render(+ <AgentPreviewCard+ output={{+ agent_name: "Draft agent",+ description: "Not saved yet",+ node_count: 1,+ }}+ />,+ );++ expect(screen.getByText("Draft agent")).toBeDefined();+ expect(screen.getByText("Not saved yet")).toBeDefined();+ expect(screen.getByText("1 block")).toBeDefined();+ });++ it("pluralizes the block count and falls back to a default name", () => {+ render(<AgentPreviewCard output={{ node_count: 4 }} />);++ expect(screen.getByText("Agent preview")).toBeDefined();+ expect(screen.getByText("4 blocks")).toBeDefined();+ });+});++describe("SubSessionCard", () => {+ afterEach(cleanup);++ it("shows status, response, link and minute-scale elapsed time", () => {+ render(+ <SubSessionCard+ output={{+ status: "COMPLETED",+ response: "All finished",+ elapsed_seconds: 125,+ sub_autopilot_session_link: "/copilot?session=sub-1",+ }}+ />,+ );++ expect(screen.getByText("Sub-AutoPilot")).toBeDefined();+ expect(screen.getByText("completed")).toBeDefined();+ expect(screen.getByText("All finished")).toBeDefined();+ expect(screen.getByText("2m 5s")).toBeDefined();+ expect(screen.getByLabelText("Open sub-session").getAttribute("href")).toBe(+ "/copilot?session=sub-1",+ );+ });++ it("shows second-scale elapsed time without a link", () => {+ render(+ <SubSessionCard output={{ status: "RUNNING", elapsed_seconds: 45 }} />,+ );++ expect(screen.getByText("running")).toBeDefined();+ expect(screen.getByText("45s")).toBeDefined();+ expect(screen.queryByLabelText("Open sub-session")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/BlockCards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/BlockCards.test.tsxnew file mode 100644index 0000000000..45c242153e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/BlockCards.test.tsx@@ -0,0 +1,101 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import {+ BlockListCard,+ BlockOutputCard,+ CardProviderIcon,+} from "../BlockCards";++describe("CardProviderIcon", () => {+ afterEach(cleanup);++ it("renders the integration icon for a provider", () => {+ render(<CardProviderIcon provider="github" fallback={<span>fb</span>} />);++ const img = screen.getByAltText("github");+ expect(img.getAttribute("src")).toBe("/integrations/github.png");+ });++ it("renders the fallback without a provider", () => {+ render(<CardProviderIcon provider={null} fallback={<span>fb</span>} />);++ expect(screen.getByText("fb")).toBeDefined();+ });++ it("renders the fallback for providers without safe characters", () => {+ render(<CardProviderIcon provider="../../" fallback={<span>fb</span>} />);++ expect(screen.getByText("fb")).toBeDefined();+ });++ it("falls back after the image fails to load", () => {+ render(<CardProviderIcon provider="github" fallback={<span>fb</span>} />);++ fireEvent.error(screen.getByAltText("github"));++ expect(screen.getByText("fb")).toBeDefined();+ expect(screen.queryByAltText("github")).toBeNull();+ });+});++describe("BlockListCard", () => {+ afterEach(cleanup);++ it("renders block names, descriptions and lowercased category chips", () => {+ render(+ <BlockListCard+ blocks={[+ {+ name: "HTTP Request",+ description: "Makes requests",+ provider: "github",+ categories: ["NETWORK", "DATA"],+ },+ { block_name: "Send Email" },+ ]}+ />,+ );++ expect(screen.getByText("HTTP Request")).toBeDefined();+ expect(screen.getByText("Makes requests")).toBeDefined();+ expect(screen.getByText("network")).toBeDefined();+ expect(screen.queryByText("data")).toBeNull();+ expect(screen.getByText("Send Email")).toBeDefined();+ expect(screen.getByAltText("github")).toBeDefined();+ });++ it("falls back to inline JSON for unnamed blocks", () => {+ render(<BlockListCard blocks={[{ enabled: true }]} />);++ expect(screen.getByText('{"enabled":true}')).toBeDefined();+ });+});++describe("BlockOutputCard", () => {+ afterEach(cleanup);++ it("renders the block name with flattened single-value outputs", () => {+ render(+ <BlockOutputCard+ output={{+ block_name: "Send Email",+ outputs: { message_id: ["msg-1"], recipients: ["a", "b"] },+ }}+ />,+ );++ expect(screen.getByText("Send Email")).toBeDefined();+ expect(screen.getByText("message id")).toBeDefined();+ expect(screen.getByText("msg-1")).toBeDefined();+ expect(screen.getByText("recipients")).toBeDefined();+ expect(screen.getByText('["a","b"]')).toBeDefined();+ });++ it("falls back to the block id without outputs", () => {+ render(+ <BlockOutputCard output={{ block_id: "block-9", success: false }} />,+ );++ expect(screen.getByText("block-9")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/FileDiff.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/FileDiff.test.tsnew file mode 100644index 0000000000..095cb79b4c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/FileDiff.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";+import { isDiffText, parseUnifiedDiff } from "../fileDiffHelpers";++describe("isDiffText", () => {+ it("recognizes unified diffs with hunk metadata", () => {+ expect(isDiffText("@@ -1,2 +1,2 @@\n-old\n+new")).toBe(true);+ });++ it("does not classify ordinary plus/minus prose as a diff", () => {+ expect(isDiffText("- downside\n+ upside")).toBe(false);+ });+});++describe("parseUnifiedDiff", () => {+ it("skips file headers and newline markers and tracks line numbers", () => {+ const parsed = parseUnifiedDiff(+ "--- a/file.ts\n+++ b/file.ts\n@@ -3,2 +3,2 @@\n-old\n+new\n same\n\\ No newline at end of file",+ );++ expect(parsed).toEqual({+ rows: [+ { old: 3, cur: null, type: "del", text: "old" },+ { old: null, cur: 3, type: "add", text: "new" },+ { old: 4, cur: 4, type: "ctx", text: "same" },+ ],+ added: 1,+ removed: 1,+ truncated: false,+ });+ });++ it("caps very large previews while preserving totals", () => {+ const lines = Array.from({ length: 550 }, (_, index) => `+line ${index}`);+ const parsed = parseUnifiedDiff(`@@ -0,0 +1,550 @@\n${lines.join("\n")}`);++ expect(parsed.rows).toHaveLength(500);+ expect(parsed.added).toBe(550);+ expect(parsed.truncated).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/InfoCards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/InfoCards.test.tsxnew file mode 100644index 0000000000..4268fb6427--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/InfoCards.test.tsx@@ -0,0 +1,273 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { CopilotChatActionsContext } from "../../CopilotChatActionsProvider/useCopilotChatActions";+import {+ FixResultCard,+ PlanSteps,+ QuestionsCard,+ SetupCard,+ SkillCard,+ SuggestedGoalCard,+ TriggerSetupCard,+ ValidationCard,+} from "../InfoCards";++describe("PlanSteps", () => {+ afterEach(cleanup);++ it("renders step descriptions across statuses with block chips", () => {+ render(+ <PlanSteps+ steps={[+ {+ description: "Fetch data",+ status: "completed",+ block_name: "HTTP",+ },+ { description: "Summarize", status: "in_progress" },+ { description: "Send email", status: "pending" },+ ]}+ />,+ );++ expect(screen.getByText("Fetch data")).toBeDefined();+ expect(screen.getByText("Summarize")).toBeDefined();+ expect(screen.getByText("Send email")).toBeDefined();+ expect(screen.getByText("HTTP")).toBeDefined();+ });++ it("falls back to inline JSON for steps without a description", () => {+ render(<PlanSteps steps={[{ step_id: "s1" }]} />);++ expect(screen.getByText('{"step_id":"s1"}')).toBeDefined();+ });+});++describe("ValidationCard", () => {+ afterEach(cleanup);++ it("shows a valid status for valid graphs", () => {+ render(<ValidationCard output={{ valid: true }} />);++ expect(screen.getByText("Graph is valid")).toBeDefined();+ });++ it("lists validation errors when present", () => {+ render(+ <ValidationCard+ output={{ valid: false, errors: ["Missing input", "Broken link"] }}+ />,+ );++ expect(screen.getByText("Missing input")).toBeDefined();+ expect(screen.getByText("Broken link")).toBeDefined();+ });++ it("shows a generic failure when errors are absent", () => {+ render(<ValidationCard output={{ valid: false }} />);++ expect(screen.getByText("Graph has errors")).toBeDefined();+ });+});++describe("FixResultCard", () => {+ afterEach(cleanup);++ it("summarizes applied fixes when the graph is valid after fixing", () => {+ render(+ <FixResultCard+ output={{+ valid_after_fix: true,+ fixes_applied: ["Linked input", "Removed node"],+ }}+ />,+ );++ expect(screen.getByText("Fixed — applied 2 fixes")).toBeDefined();+ });++ it("lists remaining errors when the graph is still broken", () => {+ render(+ <FixResultCard+ output={{ valid_after_fix: false, remaining_errors: ["Still broken"] }}+ />,+ );++ expect(screen.getByText("1 error remaining")).toBeDefined();+ expect(screen.getByText("Still broken")).toBeDefined();+ });+});++describe("QuestionsCard", () => {+ afterEach(cleanup);++ it("renders questions with examples", () => {+ render(+ <QuestionsCard+ questions={[+ { question: "Which region?", example: "us-east" },+ { question: "What budget?" },+ ]}+ />,+ );++ expect(screen.getByText("Which region?")).toBeDefined();+ expect(screen.getByText("e.g. us-east")).toBeDefined();+ expect(screen.getByText("What budget?")).toBeDefined();+ });++ it("falls back to inline JSON for malformed entries", () => {+ render(<QuestionsCard questions={[{ keyword: "region" }]} />);++ expect(screen.getByText('{"keyword":"region"}')).toBeDefined();+ });+});++describe("SetupCard", () => {+ afterEach(cleanup);++ it("shows the integration name and connection prompt", () => {+ render(+ <SetupCard+ output={{ setup_info: { agent_name: "Notion" } }}+ provider={null}+ />,+ );++ expect(screen.getByText("Notion")).toBeDefined();+ expect(screen.getByText("Connection required")).toBeDefined();+ });++ it("renders nothing without an agent name", () => {+ const { container } = render(+ <SetupCard output={{ setup_info: {} }} provider={null} />,+ );++ expect(container.firstChild).toBeNull();+ });+});++describe("SkillCard", () => {+ afterEach(cleanup);++ it("shows the skill name, description and first trigger", () => {+ render(+ <SkillCard+ output={{+ name: "Weekly digest",+ description: "Summarizes the week",+ triggers: ["every friday", "on demand"],+ }}+ />,+ );++ expect(screen.getByText("Weekly digest")).toBeDefined();+ expect(screen.getByText("Summarizes the week")).toBeDefined();+ expect(screen.getByText("every friday")).toBeDefined();+ expect(screen.queryByText("on demand")).toBeNull();+ });++ it("renders nothing without a skill name", () => {+ const { container } = render(+ <SkillCard output={{ description: "orphan" }} />,+ );++ expect(container.firstChild).toBeNull();+ });+});++describe("SuggestedGoalCard", () => {+ afterEach(cleanup);++ it("renders the goal and reason without a send action", () => {+ render(+ <SuggestedGoalCard+ output={{ suggested_goal: "Build a scraper", reason: "You asked" }}+ />,+ );++ expect(screen.getByText("Build a scraper")).toBeDefined();+ expect(screen.getByText("You asked")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Use this goal" })).toBeNull();+ });++ it("sends the goal through chat actions when clicked", () => {+ const onSend = vi.fn();+ render(+ <CopilotChatActionsContext.Provider+ value={{ onSend, chatSurface: "copilot" }}+ >+ <SuggestedGoalCard output={{ suggested_goal: "Build a scraper" }} />+ </CopilotChatActionsContext.Provider>,+ );++ fireEvent.click(screen.getByRole("button", { name: "Use this goal" }));++ expect(onSend).toHaveBeenCalledWith(+ "Please create an agent with this goal: Build a scraper",+ );+ });++ it("renders nothing without a goal", () => {+ const { container } = render(<SuggestedGoalCard output={{}} />);++ expect(container.firstChild).toBeNull();+ });+});++describe("TriggerSetupCard", () => {+ afterEach(cleanup);++ it("shows the webhook URL and copies it", () => {+ const writeText = vi+ .spyOn(navigator.clipboard, "writeText")+ .mockResolvedValue(undefined);++ render(+ <TriggerSetupCard+ output={{+ message: "Webhook ready",+ webhook_url: "https://hooks.example.com/h1",+ }}+ />,+ );++ expect(screen.getByText("Webhook ready")).toBeDefined();+ expect(screen.getByText("https://hooks.example.com/h1")).toBeDefined();++ fireEvent.click(screen.getByRole("button", { name: "Copy" }));++ expect(writeText).toHaveBeenCalledWith("https://hooks.example.com/h1");+ });++ it("swallows clipboard failures on copy", async () => {+ const writeText = vi+ .spyOn(navigator.clipboard, "writeText")+ .mockRejectedValue(new Error("denied"));++ render(+ <TriggerSetupCard+ output={{ webhook_url: "https://hooks.example.com/h2" }}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: "Copy" }));++ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith("https://hooks.example.com/h2"),+ );+ });++ it("falls back to a default message without a URL", () => {+ render(<TriggerSetupCard output={{}} />);++ expect(screen.getByText("Trigger is ready")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Copy" })).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ListCards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ListCards.test.tsxnew file mode 100644index 0000000000..7c1f91fe4f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ListCards.test.tsx@@ -0,0 +1,162 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import {+ DocsList,+ FeatureRequestList,+ FileList,+ FolderList,+ ScheduleCreatedCard,+ ScheduleList,+} from "../ListCards";++describe("FeatureRequestList", () => {+ afterEach(cleanup);++ it("renders titles, descriptions and identifiers", () => {+ render(+ <FeatureRequestList+ results={[+ {+ title: "Dark mode",+ description: "Please add it",+ identifier: "FR-101",+ },+ { note: "untitled" },+ ]}+ />,+ );++ expect(screen.getByText("Dark mode")).toBeDefined();+ expect(screen.getByText("Please add it")).toBeDefined();+ expect(screen.getByText("FR-101")).toBeDefined();+ expect(screen.getByText('{"note":"untitled"}')).toBeDefined();+ });+});++describe("ScheduleList", () => {+ afterEach(cleanup);++ it("labels copilot turn schedules as chat", () => {+ render(+ <ScheduleList+ schedules={[+ {+ name: "Daily briefing",+ next_run_time: "2026-08-21T10:00:00Z",+ cron: "0 10 * * *",+ kind: "copilot_turn",+ },+ ]}+ />,+ );++ expect(screen.getByText("Daily briefing")).toBeDefined();+ expect(screen.getByText("chat")).toBeDefined();+ });++ it("labels other schedule kinds as agent", () => {+ render(+ <ScheduleList+ schedules={[{ message: "Run scraper", kind: "graph_execution" }]}+ />,+ );++ expect(screen.getByText("Run scraper")).toBeDefined();+ expect(screen.getByText("agent")).toBeDefined();+ });++ it("falls back to inline JSON for unnamed schedules", () => {+ render(<ScheduleList schedules={[{ enabled: true }]} />);++ expect(screen.getByText('{"enabled":true}')).toBeDefined();+ });+});++describe("ScheduleCreatedCard", () => {+ afterEach(cleanup);++ it("announces the scheduled follow-up", () => {+ render(+ <ScheduleCreatedCard+ output={{ next_run_time: "2026-08-21T10:00:00Z", is_recurring: true }}+ />,+ );++ expect(screen.getByText("Follow-up scheduled")).toBeDefined();+ });+});++describe("FolderList", () => {+ afterEach(cleanup);++ it("renders folder names with singular and plural agent counts", () => {+ render(+ <FolderList+ folders={[+ { name: "Marketing", agent_count: 1 },+ { name: "Research", agent_count: 3 },+ { name: "Empty" },+ ]}+ />,+ );++ expect(screen.getByText("Marketing")).toBeDefined();+ expect(screen.getByText("1 agent")).toBeDefined();+ expect(screen.getByText("Research")).toBeDefined();+ expect(screen.getByText("3 agents")).toBeDefined();+ expect(screen.getByText("Empty")).toBeDefined();+ });+});++describe("FileList", () => {+ afterEach(cleanup);++ it("renders file paths with sizes", () => {+ render(+ <FileList+ files={[+ { path: "chart.png", mime_type: "image/png", size_bytes: 2048 },+ { name: "notes.txt", size_bytes: 12 },+ ]}+ />,+ );++ expect(screen.getByText("chart.png")).toBeDefined();+ expect(screen.getByText("2.0 KB")).toBeDefined();+ expect(screen.getByText("notes.txt")).toBeDefined();+ expect(screen.getByText("12 B")).toBeDefined();+ });+});++describe("DocsList", () => {+ afterEach(cleanup);++ it("renders titles, sections, snippets and links", () => {+ render(+ <DocsList+ results={[+ {+ title: "Blocks",+ section: "Guide",+ snippet: "How blocks work",+ doc_url: "https://docs.agpt.co/blocks",+ },+ ]}+ />,+ );++ expect(screen.getByText("Blocks")).toBeDefined();+ expect(screen.getByText("Guide")).toBeDefined();+ expect(screen.getByText("How blocks work")).toBeDefined();+ expect(screen.getByLabelText("Open doc").getAttribute("href")).toBe(+ "https://docs.agpt.co/blocks",+ );+ });++ it("falls back to the path and omits the link without a URL", () => {+ render(<DocsList results={[{ path: "getting-started.md" }]} />);++ expect(screen.getByText("getting-started.md")).toBeDefined();+ expect(screen.queryByLabelText("Open doc")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ResultCards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ResultCards.test.tsxnew file mode 100644index 0000000000..58fd842fe5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ResultCards.test.tsx@@ -0,0 +1,98 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import {+ ChipList,+ LinkCard,+ StatCard,+ StatusCard,+ StatusPill,+} from "../ResultCards";++describe("StatusPill", () => {+ afterEach(cleanup);++ it("normalizes known statuses to lowercase text", () => {+ render(<StatusPill status="Completed" />);++ expect(screen.getByText("completed")).toBeDefined();+ });++ it("renders unknown statuses with the default style", () => {+ render(<StatusPill status="paused" />);++ expect(screen.getByText("paused")).toBeDefined();+ });+});++describe("StatusCard", () => {+ afterEach(cleanup);++ it("renders the label for successful states", () => {+ render(<StatusCard ok label="Everything worked" />);++ expect(screen.getByText("Everything worked")).toBeDefined();+ });++ it("renders the label for failed states", () => {+ render(<StatusCard ok={false} label="Something broke" />);++ expect(screen.getByText("Something broke")).toBeDefined();+ });+});++describe("StatCard", () => {+ afterEach(cleanup);++ it("renders the value and label", () => {+ render(<StatCard value={5} label="deleted items" />);++ expect(screen.getByText("5")).toBeDefined();+ expect(screen.getByText("deleted items")).toBeDefined();+ });+});++describe("ChipList", () => {+ afterEach(cleanup);++ it("renders a label with deduplicated chips", () => {+ render(<ChipList label="Tags" items={["alpha", "alpha", "beta"]} />);++ expect(screen.getByText("Tags")).toBeDefined();+ expect(screen.getAllByText("alpha")).toHaveLength(1);+ expect(screen.getByText("beta")).toBeDefined();+ });+});++describe("LinkCard", () => {+ afterEach(cleanup);++ it("shows the title above the domain with meta text", () => {+ render(+ <LinkCard+ url="https://www.example.com/page"+ title="Example page"+ meta="12.0 KB"+ />,+ );++ expect(screen.getByText("Example page")).toBeDefined();+ expect(screen.getByText("example.com")).toBeDefined();+ expect(screen.getByText("12.0 KB")).toBeDefined();+ expect(screen.getByLabelText("Open link").getAttribute("href")).toBe(+ "https://www.example.com/page",+ );+ });++ it("falls back to the domain as title and shows the raw URL", () => {+ render(<LinkCard url="https://example.com/deep/path" />);++ expect(screen.getByText("example.com")).toBeDefined();+ expect(screen.getByText("https://example.com/deep/path")).toBeDefined();+ });++ it("uses the raw URL as the display domain when it cannot be parsed", () => {+ render(<LinkCard url="not-a-url" />);++ expect(screen.getAllByText("not-a-url").length).toBeGreaterThan(0);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/RowIcon.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/RowIcon.test.tsxnew file mode 100644index 0000000000..0a7acc9e99--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/RowIcon.test.tsx@@ -0,0 +1,98 @@+import { cleanup, fireEvent, render } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import type { ChainRow } from "../helpers";+import { ProviderIcon, RowIcon } from "../RowIcon";++function row(overrides: Partial<ChainRow>): ChainRow {+ return {+ key: "row",+ category: "other",+ text: "Row",+ state: "done",+ ...overrides,+ };+}++describe("RowIcon", () => {+ afterEach(cleanup);++ it("renders the red alert icon for errored rows regardless of category", () => {+ const { container } = render(+ <RowIcon row={row({ category: "web", state: "error" })} />,+ );++ expect(container.querySelector("svg.text-red-500")).not.toBeNull();+ expect(container.querySelector("svg.text-zinc-600")).toBeNull();+ });++ it.each([+ "narration",+ "reasoning",+ "bash",+ "web",+ "browser",+ "file-read",+ "file-write",+ "file-delete",+ "file-list",+ "search",+ "edit",+ "todo",+ "compaction",+ "agent",+ "agent-build",+ "plan",+ "block",+ "memory",+ "folder",+ "schedule",+ "trigger",+ "preset",+ "chat",+ "mcp",+ "docs",+ "skill",+ "integration",+ "feature",+ "question",+ "info",+ "other",+ ] as const)("renders a themed icon for the %s category", (category) => {+ const { container } = render(<RowIcon row={row({ category })} />);++ expect(container.querySelector("svg.text-zinc-600")).not.toBeNull();+ expect(container.querySelector("svg.text-red-500")).toBeNull();+ });+});++describe("ProviderIcon", () => {+ afterEach(cleanup);++ it("renders the provider image from the given source", () => {+ const { container } = render(+ <ProviderIcon+ src="/integrations/github.png"+ row={row({ category: "integration" })}+ />,+ );++ const image = container.querySelector("img");+ expect(image?.getAttribute("src")).toContain("/integrations/github.png");+ });++ it("falls back to the category icon when the image fails to load", () => {+ const { container } = render(+ <ProviderIcon+ src="/integrations/missing.png"+ row={row({ category: "integration" })}+ />,+ );++ const image = container.querySelector("img");+ expect(image).not.toBeNull();+ if (image) fireEvent.error(image);++ expect(container.querySelector("img")).toBeNull();+ expect(container.querySelector("svg.text-zinc-600")).not.toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/SwapText.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/SwapText.test.tsxnew file mode 100644index 0000000000..ea800cb410--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/SwapText.test.tsx@@ -0,0 +1,53 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import { ShimmerText } from "../ShimmerText";+import { SwapText } from "../SwapText";++describe("ShimmerText", () => {+ afterEach(cleanup);++ it("renders the text and duplicates it for the shimmer sweep", () => {+ render(<ShimmerText text="Searching the web…" className="extra" />);++ const span = screen.getByText("Searching the web…");+ expect(span.getAttribute("data-text")).toBe("Searching the web…");+ expect(span.className).toContain("extra");+ });++ it("renders without an extra class", () => {+ render(<ShimmerText text="Thinking…" />);++ expect(screen.getByText("Thinking…").getAttribute("data-text")).toBe(+ "Thinking…",+ );+ });+});++describe("SwapText", () => {+ afterEach(cleanup);++ it("renders plain text when not shimmering", () => {+ render(<SwapText text="Updated tasks" className="text-sm" />);++ const label = screen.getByText("Updated tasks");+ expect(label).toBeDefined();+ expect(label.getAttribute("data-text")).toBeNull();+ });++ it("wraps the label in shimmer while running", () => {+ render(<SwapText text="Running command…" shimmer />);++ expect(screen.getByText("Running command…").getAttribute("data-text")).toBe(+ "Running command…",+ );+ });++ it("swaps to the new label when the text changes", () => {+ const { rerender } = render(<SwapText text="Searching…" />);+ expect(screen.getByText("Searching…")).toBeDefined();++ rerender(<SwapText text="Searched the web" />);++ expect(screen.getByText("Searched the web")).toBeDefined();+ });+});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.tsxnew file mode 100644index 0000000000..c102ffad1e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx@@ -0,0 +1,408 @@+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 { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import type { MessagePart } from "../../ChatMessagesContainer/helpers";+import type { PendingQuestions } from "../../QuestionDock/helpers";+import { PendingQuestionsContext } from "../../QuestionDock/PendingQuestionsContext";+import { ToolChain } from "../ToolChain";++vi.mock("../../SetupRequirementsCard/SetupRequirementsCard", async () => {+ const { useContext, useEffect } = await import("react");+ const { ChainActionsContext } = await import("../chainActions");++ interface MockProps {+ output: { setup_info?: { agent_name?: string } };+ }++ function SetupRequirementsCard({ output }: MockProps) {+ const chainActions = useContext(ChainActionsContext);+ const name = output.setup_info?.agent_name ?? "Integration";+ useEffect(() => {+ if (!chainActions) return;+ chainActions.register({+ id: name,+ ready: name !== "NotReady",+ buildMessage: () =>+ name === "Silent" ? null : `Connected ${name}. Please continue.`,+ });+ return () => chainActions.unregister(name);+ }, [chainActions, name]);+ return <div>{`setup-card-${name}`}</div>;+ }++ return { SetupRequirementsCard };+});++function reasoningPart(text: string): MessagePart {+ return { type: "reasoning", text, state: "done" } as MessagePart;+}++function toolPart(+ toolName: string,+ state: string,+ extras: Record<string, unknown> = {},+): MessagePart {+ return {+ type: `tool-${toolName}`,+ state,+ toolCallId: `call-${toolName}`,+ input: {},+ output: undefined,+ ...extras,+ } as MessagePart;+}++function getPanel(header: HTMLElement): HTMLElement | null {+ const panelId = header.getAttribute("aria-controls");+ return panelId ? document.getElementById(panelId) : null;+}++describe("ToolChain", () => {+ afterEach(() => {+ cleanup();+ useCopilotUIStore.setState({ initialPrompt: null, sentMessageCount: 0 });+ });++ it("renders nothing when no parts map to chain rows", () => {+ const { container } = render(<ToolChain parts={[]} isStreaming={false} />);++ expect(container.textContent).toBe("");+ });++ it("collapses a settled chain to a summary heading and expands on click", async () => {+ const user = userEvent.setup();+ render(+ <ToolChain+ parts={[+ reasoningPart("Compare the options first"),+ toolPart("web_search", "output-available", {+ input: { query: "copilot" },+ output: { results: [] },+ }),+ toolPart("bash_exec", "output-available", {+ input: { command: "ls" },+ output: "files",+ }),+ ]}+ isStreaming={false}+ />,+ );++ const header = screen.getByRole("button", {+ name: /thought it through, searched the web, ran commands/i,+ });+ expect(header.getAttribute("aria-expanded")).toBe("false");+ expect(getPanel(header)?.getAttribute("aria-hidden")).toBe("true");++ await user.click(header);++ expect(header.getAttribute("aria-expanded")).toBe("true");+ expect(getPanel(header)?.getAttribute("aria-hidden")).toBe("false");+ expect(screen.getByText("Done")).toBeDefined();+ expect(screen.getByText('Searched the web for "copilot"')).toBeDefined();++ await user.click(header);+ expect(header.getAttribute("aria-expanded")).toBe("false");+ });++ it("expands a reasoning row to reveal the thought stream", async () => {+ const user = userEvent.setup();+ render(+ <ToolChain+ parts={[reasoningPart("Compare the options first")]}+ isStreaming={false}+ />,+ );++ await user.click(+ screen.getByRole("button", { name: /thought it through/i }),+ );++ const reasoningRow = screen.getByRole("button", { name: "Thought" });+ expect(reasoningRow.getAttribute("aria-expanded")).toBe("false");++ await user.click(reasoningRow);++ expect(reasoningRow.getAttribute("aria-expanded")).toBe("true");+ expect(screen.getByText("Compare the options first")).toBeDefined();+ });++ it("shows only the sliding window of latest rows while streaming", () => {+ render(+ <ToolChain+ parts={[+ reasoningPart("Compare the options first"),+ toolPart("web_search", "output-available", {+ input: { query: "copilot" },+ output: { results: [] },+ }),+ toolPart("bash_exec", "input-available", {+ input: { command: "ls" },+ }),+ ]}+ isStreaming+ />,+ );++ expect(screen.getAllByText('Running command "ls"…').length).toBeGreaterThan(+ 0,+ );+ expect(screen.queryByText("Thought")).toBeNull();+ expect(screen.queryByText("Done")).toBeNull();++ const header = screen.getByRole("button", {+ name: /running command "ls"/i,+ });+ expect(header.getAttribute("aria-expanded")).toBe("true");+ });++ it("streams live reasoning inline without needing a click", () => {+ render(+ <ToolChain+ parts={[+ {+ type: "reasoning",+ text: "Weighing the trade-offs",+ state: "streaming",+ } as MessagePart,+ ]}+ isStreaming+ />,+ );++ expect(screen.getAllByText("Thinking…").length).toBeGreaterThan(0);+ expect(screen.getByText("Weighing the trade-offs")).toBeDefined();+ });++ it("renders the provider icon when the tool output names a provider", async () => {+ const user = userEvent.setup();+ const { container } = render(+ <ToolChain+ parts={[+ toolPart("run_block", "output-available", {+ input: { block_name: "Send Email" },+ output: { provider: "github", ok: true },+ }),+ ]}+ isStreaming={false}+ />,+ );++ await user.click(screen.getByRole("button", { name: /ran blocks/i }));++ const icon = container.querySelector('img[src*="/integrations/github"]');+ expect(icon).not.toBeNull();+ });++ 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 },+ });++ render(+ <ToolChain+ parts={[+ toolPart("browser_navigate", "output-available", {+ input: { url: "https://agpt.co" },+ output: { title: "AutoGPT" },+ }),+ ]}+ isStreaming={false}+ />,+ );++ await user.click(screen.getByRole("button", { name: /browsed the web/i }));++ const row = screen.getByRole("button", {+ 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 () => {+ const user = userEvent.setup();+ render(+ <ToolChain+ parts={[+ toolPart("web_search", "output-error", {+ input: { query: "copilot" },+ errorText: "Rate limited",+ }),+ ]}+ isStreaming={false}+ />,+ );++ expect(screen.getAllByText("Rate limited").length).toBeGreaterThan(0);++ await user.click(screen.getByRole("button", { name: /rate limited/i }));++ expect(screen.queryByText("Done")).toBeNull();+ expect(+ screen.getByText('Failed while searching the web for "copilot"'),+ ).toBeDefined();+ });++ it("keeps action-required rows visible while the chain is collapsed", () => {+ render(+ <ToolChain+ parts={[+ toolPart("web_search", "output-available", {+ input: { query: "copilot" },+ output: { results: [] },+ }),+ toolPart("run_block", "output-available", {+ output: { type: "review_required", block_name: "Send Email" },+ }),+ ]}+ isStreaming={false}+ />,+ );++ const header = screen.getByRole("button", {+ name: /review send email/i,+ });+ expect(getPanel(header)?.getAttribute("aria-hidden")).toBe("false");++ expect(screen.getAllByText("Review Send Email").length).toBeGreaterThan(1);+ expect(screen.queryByText('Searched the web for "copilot"')).toBeNull();+ expect(screen.getByText("Send Email")).toBeDefined();+ });++ it("drafts answered questions into the chat input and dismisses on send", async () => {+ const user = userEvent.setup();+ const pending: PendingQuestions = {+ dockId: "m1:call-ask_question",+ callIds: ["call-ask_question"],+ questions: [+ { question: "Which region?", keyword: "region", example: "Europe" },+ ],+ };++ render(+ <CopilotChatActionsProvider onSend={vi.fn()}>+ <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>,+ );++ expect(screen.getByText("Answer a few questions")).toBeDefined();+ expect(screen.getByText("Which region?")).toBeDefined();++ const submit = screen.getByRole("button", {+ name: "Add answers to message",+ });+ expect(submit.hasAttribute("disabled")).toBe(true);++ await user.type(+ screen.getByPlaceholderText("e.g. Europe"),+ "Western Europe",+ );+ expect(submit.hasAttribute("disabled")).toBe(false);++ await user.click(submit);++ expect(useCopilotUIStore.getState().initialPrompt).toBe(+ "**Here are my answers:**\n\n> Which region?\n\nWestern Europe\n\nPlease proceed.",+ );++ act(() => useCopilotUIStore.getState().notifyMessageSent());++ expect(screen.queryByText("Answer a few questions")).toBeNull();+ });++ it("offers a Proceed step for confirm-only setup cards", async () => {+ const user = userEvent.setup();+ render(+ <ToolChain+ parts={[+ toolPart("connect_integration", "output-available", {+ output: {+ type: "setup_requirements",+ setup_info: { agent_name: "GitHub" },+ },+ }),+ ]}+ isStreaming={false}+ />,+ );++ expect(screen.getByText("setup-card-GitHub")).toBeDefined();+ expect(+ screen.getByText("Everything's filled in — send it to continue"),+ ).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.",+ );+ });++ it("disables Proceed until every registered card is ready", () => {+ render(+ <ToolChain+ parts={[+ toolPart("connect_integration", "output-available", {+ output: {+ type: "setup_requirements",+ setup_info: { agent_name: "NotReady" },+ },+ }),+ ]}+ isStreaming={false}+ />,+ );++ expect(+ screen.getByText("Complete the steps above, then send to continue"),+ ).toBeDefined();+ expect(+ screen.getByRole("button", { name: "Proceed" }).hasAttribute("disabled"),+ ).toBe(true);+ expect(useCopilotUIStore.getState().initialPrompt).toBeNull();+ });++ it("does not draft anything when ready cards produce no message", async () => {+ const user = userEvent.setup();+ render(+ <ToolChain+ parts={[+ toolPart("connect_integration", "output-available", {+ output: {+ type: "setup_requirements",+ setup_info: { agent_name: "Silent" },+ },+ }),+ ]}+ isStreaming={false}+ />,+ );++ await user.click(screen.getByRole("button", { name: "Proceed" }));++ expect(useCopilotUIStore.getState().initialPrompt).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResult.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResult.test.tsxnew file mode 100644index 0000000000..1ce64be782--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResult.test.tsx@@ -0,0 +1,919 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { PendingQuestionsContext } from "../../QuestionDock/PendingQuestionsContext";+import type { ChainRow } from "../helpers";+import { ToolResult } from "../ToolResult";++vi.mock("../../SetupRequirementsCard/SetupRequirementsCard", () => ({+ SetupRequirementsCard: ({+ credentialsLabel,+ inputsMode,+ retryInstruction,+ }: {+ credentialsLabel?: string;+ inputsMode?: string;+ retryInstruction?: string;+ }) => (+ <div>+ <span>{credentialsLabel}</span>+ {inputsMode && <span>{`mode:${inputsMode}`}</span>}+ {retryInstruction && <span>{`retry:${retryInstruction}`}</span>}+ </div>+ ),+}));++vi.mock(+ "../../../tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard",+ () => ({+ MCPSetupCard: () => <div>mcp-setup-card</div>,+ }),+);++vi.mock("../../QuestionDock/QuestionDock", () => ({+ QuestionsForm: ({ dockId }: { dockId: string }) => (+ <div>{`questions-form:${dockId}`}</div>+ ),+}));++function row(output: unknown, tool?: string, input?: unknown): ChainRow {+ return {+ key: "tool",+ category: "other",+ text: "Tool",+ state: "done",+ output,+ tool,+ input,+ };+}++describe("ToolResult", () => {+ afterEach(cleanup);++ it("renders a real unified diff", () => {+ render(<ToolResult row={row("@@ -1 +1 @@\n-old\n+new")} />);++ expect(screen.getByText("+1")).toBeDefined();+ expect(screen.getByText("-1")).toBeDefined();+ expect(screen.getByText("old")).toBeDefined();+ expect(screen.getByText("new")).toBeDefined();+ });++ it("renders JSON containing diff-like text as structured output", () => {+ render(+ <ToolResult+ row={row(JSON.stringify({ patch: "@@ -1 +1 @@\n-old\n+new" }))}+ />,+ );++ expect(screen.getByText("Patch")).toBeDefined();+ expect(screen.queryByText("+1")).toBeNull();+ });++ it("uses a fallback credentials label when an integration name is missing", () => {+ render(+ <ToolResult+ row={row(+ {+ message: "Connect an account",+ setup_info: { agent_id: "agent-1" },+ },+ "connect_integration",+ )}+ />,+ );++ expect(screen.getByText("Integration credentials")).toBeDefined();+ expect(screen.queryByText("undefined credentials")).toBeNull();+ });++ it.each([+ [+ "run_agent",+ { graph_name: "Research Agent", execution_id: "exec-1" },+ "Research Agent",+ ],+ ["find_block", { blocks: [{ name: "Web Search" }] }, "Web Search"],+ [+ "web_search",+ { results: [{ title: "Example result", url: "https://example.com" }] },+ "Example result",+ ],+ [+ "ask_question",+ { questions: [{ question: "Which region?", keyword: "region" }] },+ "Which region?",+ ],+ [+ "search_feature_requests",+ { results: [{ identifier: "FR-101", title: "Dark mode" }] },+ "Dark mode",+ ],+ [+ "create_agent",+ { agent_name: "Draft agent", node_count: 3 },+ "Draft agent",+ ],+ ["run_mcp_tool", { result: { identifier: "OPEN-3211" } }, "OPEN-3211"],+ ])("dispatches %s to its specialized card", (tool, output, expected) => {+ render(<ToolResult row={row(output, tool)} />);++ expect(screen.getByText(expected)).toBeDefined();+ });++ describe("setup requirements routing", () => {+ it("routes run_mcp_tool setup to the MCP setup card", () => {+ render(+ <ToolResult+ row={row({ setup_info: { server_url: "url" } }, "run_mcp_tool")}+ />,+ );++ expect(screen.getByText("mcp-setup-card")).toBeDefined();+ });++ it("routes trigger setup with trigger inputs mode and Account label", () => {+ render(+ <ToolResult+ row={row(+ { setup_info: { agent_name: "Slack" } },+ "setup_agent_webhook_trigger",+ )}+ />,+ );++ expect(screen.getByText("Account")).toBeDefined();+ expect(screen.getByText("mode:trigger")).toBeDefined();+ });++ it("routes run_agent setup with preview inputs mode", () => {+ render(+ <ToolResult+ row={row({ setup_info: { agent_name: "Runner" } }, "run_agent")}+ />,+ );++ expect(screen.getByText("mode:preview")).toBeDefined();+ });++ it("labels connect_integration setup with the integration name and retry note", () => {+ render(+ <ToolResult+ row={row(+ { setup_info: { agent_name: "Notion" } },+ "connect_integration",+ )}+ />,+ );++ expect(screen.getByText("Notion credentials")).toBeDefined();+ expect(+ screen.getByText("retry:I've connected my account. Please continue."),+ ).toBeDefined();+ });+ });++ describe("pending clarifying questions", () => {+ it("renders the interactive answer form for the pending row", () => {+ render(+ <PendingQuestionsContext.Provider+ value={{+ dockId: "dock-1",+ questions: [{ question: "Which region?", keyword: "region" }],+ callIds: ["tool"],+ }}+ >+ <ToolResult+ row={row({ questions: [{ question: "Which region?" }] })}+ />+ </PendingQuestionsContext.Provider>,+ );++ expect(screen.getByText("questions-form:dock-1")).toBeDefined();+ });++ it("keeps a read-only card for ask_question rows answered from input", () => {+ render(+ <ToolResult+ row={row({ type: "clarification" }, "ask_question", {+ questions: [+ { question: "What budget?", keyword: "budget", example: "$50" },+ ],+ })}+ />,+ );++ expect(screen.getByText("What budget?")).toBeDefined();+ expect(screen.getByText("e.g. $50")).toBeDefined();+ });+ });++ describe("agent execution routing", () => {+ it("renders an execution card with the library agent link", () => {+ render(+ <ToolResult+ row={row(+ {+ graph_name: "Research Agent",+ execution_id: "exec-1",+ status: "RUNNING",+ library_agent_link: "/library/agents/lib-1",+ },+ "run_agent",+ )}+ />,+ );++ expect(screen.getByText("Research Agent")).toBeDefined();+ expect(screen.getByText("running")).toBeDefined();+ expect(screen.getByLabelText("Open execution").getAttribute("href")).toBe(+ "/library/agents/lib-1",+ );+ });++ it("builds the execution link from graph and execution ids", () => {+ render(+ <ToolResult+ row={row(+ { execution_id: "exec-2", graph_id: "graph-9" },+ "schedule_agent",+ { username_agent_slug: "creator/scraper" },+ )}+ />,+ );++ expect(screen.getByText("creator/scraper")).toBeDefined();+ expect(screen.getByLabelText("Open execution").getAttribute("href")).toBe(+ "/library/agents/graph-9?activeTab=runs&activeItem=exec-2",+ );+ });++ it("renders the agent card when run_agent returns an agent object", () => {+ render(+ <ToolResult+ row={row(+ { agent: { name: "Found Agent", description: "Scrapes" } },+ "run_agent",+ )}+ />,+ );++ expect(screen.getByText("Found Agent")).toBeDefined();+ expect(screen.getByText("Scrapes")).toBeDefined();+ });++ it("renders execution outputs when run_agent finishes with outputs", () => {+ render(+ <ToolResult+ row={row(+ { execution: { outputs: { summary: ["All good"] } } },+ "run_agent",+ )}+ />,+ );++ expect(screen.getByText("summary")).toBeDefined();+ expect(screen.getByText("All good")).toBeDefined();+ });++ it("renders view_agent_output execution outputs", () => {+ render(+ <ToolResult+ row={row(+ { execution: { outputs: { answer: [42] } } },+ "view_agent_output",+ )}+ />,+ );++ expect(screen.getByText("answer")).toBeDefined();+ expect(screen.getByText("42")).toBeDefined();+ });++ it("renders view_agent_output top-level outputs list", () => {+ render(+ <ToolResult+ row={row(+ { outputs: [{ name: "report", value: "Done" }] },+ "view_agent_output",+ )}+ />,+ );++ expect(screen.getByText("report")).toBeDefined();+ expect(screen.getByText("Done")).toBeDefined();+ });+ });++ describe("agent editing routing", () => {+ it("renders the suggested goal card", () => {+ render(+ <ToolResult+ row={row(+ { suggested_goal: "Build a scraper", reason: "You asked for it" },+ "create_agent",+ )}+ />,+ );++ expect(screen.getByText("Build a scraper")).toBeDefined();+ expect(screen.getByText("You asked for it")).toBeDefined();+ });++ it("renders the saved agent card with builder and library links", () => {+ render(+ <ToolResult+ row={row(+ {+ agent_name: "My Agent",+ graph_version: 2,+ library_agent_link: "/library/agents/lib-2",+ agent_page_link: "/build?flowID=graph-2",+ },+ "edit_agent",+ )}+ />,+ );++ expect(screen.getByText("My Agent")).toBeDefined();+ expect(screen.getByText("v2")).toBeDefined();+ expect(+ screen.getByLabelText("Open in builder").getAttribute("href"),+ ).toBe("/build?flowID=graph-2");+ expect(+ screen.getByLabelText("Open in library").getAttribute("href"),+ ).toBe("/library/agents/lib-2");+ });++ it("renders the sub-session card with status and elapsed time", () => {+ render(+ <ToolResult+ row={row(+ {+ status: "COMPLETED",+ response: "Everything worked",+ elapsed_seconds: 75,+ sub_autopilot_session_link: "/copilot?session=sub-1",+ },+ "run_sub_session",+ )}+ />,+ );++ expect(screen.getByText("Sub-AutoPilot")).toBeDefined();+ expect(screen.getByText("1m 15s")).toBeDefined();+ expect(screen.getByText("Everything worked")).toBeDefined();+ expect(+ screen.getByLabelText("Open sub-session").getAttribute("href"),+ ).toBe("/copilot?session=sub-1");+ });++ it("renders found library agents with stats", () => {+ render(+ <ToolResult+ row={row(+ {+ agents: [+ {+ id: "lib-1",+ source: "library",+ name: "Lib Agent",+ creator: "abhi",+ runs: 1200,+ rating: 4.5,+ },+ ],+ },+ "find_library_agent",+ )}+ />,+ );++ expect(screen.getByText("Lib Agent")).toBeDefined();+ expect(screen.getByText("by abhi")).toBeDefined();+ expect(screen.getByText("1,200 runs")).toBeDefined();+ expect(screen.getByText("4.5")).toBeDefined();+ expect(screen.getByLabelText("Open agent").getAttribute("href")).toBe(+ "/library/agents/lib-1",+ );+ });+ });++ describe("block routing", () => {+ it("renders a single block card for run_block block payloads", () => {+ render(+ <ToolResult+ row={row(+ {+ block: {+ name: "HTTP Request",+ description: "Makes requests",+ categories: ["NETWORK"],+ },+ },+ "run_block",+ )}+ />,+ );++ expect(screen.getByText("HTTP Request")).toBeDefined();+ expect(screen.getByText("Makes requests")).toBeDefined();+ expect(screen.getByText("network")).toBeDefined();+ });++ it("renders block outputs for continue_run_block results", () => {+ render(+ <ToolResult+ row={row(+ {+ block_name: "Send Email",+ success: false,+ outputs: { error_message: ["SMTP down"] },+ },+ "continue_run_block",+ )}+ />,+ );++ expect(screen.getByText("Send Email")).toBeDefined();+ expect(screen.getByText("error message")).toBeDefined();+ expect(screen.getByText("SMTP down")).toBeDefined();+ });+ });++ describe("plan, validation and skills routing", () => {+ it("renders decomposed goal steps", () => {+ render(+ <ToolResult+ row={row(+ {+ steps: [+ {+ description: "Fetch data",+ status: "completed",+ block_name: "HTTP",+ },+ { description: "Summarize", status: "in_progress" },+ ],+ },+ "decompose_goal",+ )}+ />,+ );++ expect(screen.getByText("Fetch data")).toBeDefined();+ expect(screen.getByText("Summarize")).toBeDefined();+ expect(screen.getByText("HTTP")).toBeDefined();+ });++ it("renders a valid graph status for validate_agent_graph", () => {+ render(<ToolResult row={row({ valid: true }, "validate_agent_graph")} />);++ expect(screen.getByText("Graph is valid")).toBeDefined();+ });++ it("renders fix results for fix_agent_graph", () => {+ render(+ <ToolResult+ row={row(+ { valid_after_fix: true, fixes_applied: ["Linked input"] },+ "fix_agent_graph",+ )}+ />,+ );++ expect(screen.getByText("Fixed — applied 1 fix")).toBeDefined();+ });++ it("renders a stored skill card", () => {+ render(+ <ToolResult+ row={row(+ {+ name: "Weekly digest",+ description: "Summarizes the week",+ triggers: ["every friday"],+ },+ "store_skill",+ )}+ />,+ );++ expect(screen.getByText("Weekly digest")).toBeDefined();+ expect(screen.getByText("Summarizes the week")).toBeDefined();+ expect(screen.getByText("every friday")).toBeDefined();+ });++ it("renders skill names as chips for list_skills", () => {+ render(+ <ToolResult+ row={row(+ { skills: [{ name: "summarize" }, { name: "draft" }] },+ "list_skills",+ )}+ />,+ );++ expect(screen.getByText("Skills")).toBeDefined();+ expect(screen.getByText("summarize")).toBeDefined();+ expect(screen.getByText("draft")).toBeDefined();+ });++ it("renders channel names with a hash prefix", () => {+ render(+ <ToolResult+ row={row(+ { channels: [{ name: "general" }] },+ "list_chat_platform_channels",+ )}+ />,+ );++ expect(screen.getByText("Channels")).toBeDefined();+ expect(screen.getByText("#general")).toBeDefined();+ });+ });++ describe("schedules, folders, files and docs routing", () => {+ it("renders the schedule list with a chat kind chip", () => {+ render(+ <ToolResult+ row={row(+ {+ schedules: [+ {+ name: "Daily run",+ next_run_time: "2026-08-21T10:00:00Z",+ cron: "0 10 * * *",+ kind: "copilot_turn",+ },+ ],+ },+ "list_schedules",+ )}+ />,+ );++ expect(screen.getByText("Daily run")).toBeDefined();+ expect(screen.getByText("chat")).toBeDefined();+ });++ it("renders the follow-up scheduled card", () => {+ render(+ <ToolResult+ row={row(+ { next_run_time: "2026-08-21T10:00:00Z", is_recurring: true },+ "schedule_followup",+ )}+ />,+ );++ expect(screen.getByText("Follow-up scheduled")).toBeDefined();+ });++ it("renders folders for list_folders", () => {+ render(+ <ToolResult+ row={row(+ { folders: [{ name: "Marketing", agent_count: 3 }] },+ "list_folders",+ )}+ />,+ );++ expect(screen.getByText("Marketing")).toBeDefined();+ expect(screen.getByText("3 agents")).toBeDefined();+ });++ it("renders the single folder returned by create_folder", () => {+ render(+ <ToolResult+ row={row({ folder: { name: "New Folder" } }, "create_folder")}+ />,+ );++ expect(screen.getByText("New Folder")).toBeDefined();+ });++ it("renders workspace files with sizes", () => {+ render(+ <ToolResult+ row={row(+ {+ files: [+ { path: "chart.png", mime_type: "image/png", size_bytes: 2048 },+ ],+ },+ "list_workspace_files",+ )}+ />,+ );++ expect(screen.getByText("chart.png")).toBeDefined();+ expect(screen.getByText("2.0 KB")).toBeDefined();+ });++ it("renders docs search results with a link", () => {+ render(+ <ToolResult+ row={row(+ {+ results: [+ {+ title: "Blocks",+ section: "Guide",+ snippet: "How blocks work",+ doc_url: "https://docs.agpt.co/blocks",+ },+ ],+ },+ "search_docs",+ )}+ />,+ );++ expect(screen.getByText("Blocks")).toBeDefined();+ expect(screen.getByText("Guide")).toBeDefined();+ expect(screen.getByText("How blocks work")).toBeDefined();+ expect(screen.getByLabelText("Open doc").getAttribute("href")).toBe(+ "https://docs.agpt.co/blocks",+ );+ });++ it("renders a single doc page as a docs card", () => {+ render(+ <ToolResult row={row({ title: "Getting Started" }, "get_doc_page")} />,+ );++ expect(screen.getByText("Getting Started")).toBeDefined();+ });+ });++ describe("trigger, feature request and web routing", () => {+ it("renders the webhook trigger setup card with the URL", () => {+ render(+ <ToolResult+ row={row(+ {+ message: "Webhook ready",+ webhook_url: "https://hooks.example.com/h1",+ },+ "setup_agent_webhook_trigger",+ )}+ />,+ );++ expect(screen.getByText("Webhook ready")).toBeDefined();+ expect(screen.getByText("https://hooks.example.com/h1")).toBeDefined();+ expect(screen.getByRole("button", { name: "Copy" })).toBeDefined();+ });++ it("renders the trigger card for manual setup without a URL", () => {+ render(+ <ToolResult+ row={row(+ { manual_setup_required: true, message: "Set it up manually" },+ "setup_agent_webhook_trigger",+ )}+ />,+ );++ expect(screen.getByText("Set it up manually")).toBeDefined();+ });++ it("renders a link card for a created feature request", () => {+ render(+ <ToolResult+ row={row(+ {+ issue_url: "https://linear.app/agpt/issue/OPEN-1",+ issue_title: "Add dark mode",+ },+ "create_feature_request",+ )}+ />,+ );++ expect(screen.getByText("Add dark mode")).toBeDefined();+ expect(screen.getByLabelText("Open link").getAttribute("href")).toBe(+ "https://linear.app/agpt/issue/OPEN-1",+ );+ });++ it("falls back to key/value output for feature requests without a URL", () => {+ render(+ <ToolResult+ row={row(+ { status: "created", identifier: "FR-9" },+ "create_feature_request",+ )}+ />,+ );++ expect(screen.getByText("Status")).toBeDefined();+ expect(screen.getByText("created")).toBeDefined();+ expect(screen.getByText("FR-9")).toBeDefined();+ });++ it("renders web search results with the clamped answer", () => {+ render(+ <ToolResult+ row={row(+ {+ answer: "Paris is the capital",+ results: [{ title: "Wiki", url: "https://en.wikipedia.org/x" }],+ },+ "web_search",+ )}+ />,+ );++ expect(screen.getByText("Paris is the capital")).toBeDefined();+ expect(screen.getByText("Wiki")).toBeDefined();+ });++ it("renders a plain answer when web search returns no results", () => {+ render(+ <ToolResult row={row({ answer: "Just an answer" }, "web_search")} />,+ );++ expect(screen.getByText("Just an answer")).toBeDefined();+ });+ });++ describe("terminal, todos and file routing", () => {+ it("renders bash executions as a terminal", () => {+ render(+ <ToolResult+ row={row({ stdout: "file.txt", exit_code: 2 }, "bash_exec", {+ command: "ls",+ })}+ />,+ );++ expect(screen.getByText("ls")).toBeDefined();+ expect(screen.getByText("file.txt")).toBeDefined();+ expect(screen.getByText("exit 2")).toBeDefined();+ });++ it("renders TodoWrite rows as a todo list", () => {+ render(+ <ToolResult+ row={row({ ok: true }, "TodoWrite", {+ todos: [+ { content: "Task A", status: "completed" },+ { content: "Task B", status: "in_progress" },+ { content: "Task C", status: "pending" },+ ],+ })}+ />,+ );++ expect(screen.getByText("Task A")).toBeDefined();+ expect(screen.getByText("Task B")).toBeDefined();+ expect(screen.getByText("Task C")).toBeDefined();+ });++ it("renders workspace file reads as a file card", () => {+ render(+ <ToolResult+ row={row(+ {+ size_bytes: 2048,+ mime_type: "text/plain",+ preview: "hello world",+ },+ "read_workspace_file",+ { path: "notes.txt" },+ )}+ />,+ );++ expect(screen.getByText("notes.txt")).toBeDefined();+ expect(screen.getByText("2.0 KB")).toBeDefined();+ expect(screen.getByText("hello world")).toBeDefined();+ });+ });++ describe("generic fallbacks", () => {+ it("renders plain string output as preformatted text", () => {+ render(<ToolResult row={row("plain text output")} />);++ expect(screen.getByText("plain text output")).toBeDefined();+ });++ it("renders the message when nothing but base fields remain", () => {+ render(+ <ToolResult row={row({ type: "done", message: "All finished" })} />,+ );++ expect(screen.getByText("All finished")).toBeDefined();+ });++ it("renders outputs arrays through the output list", () => {+ render(+ <ToolResult+ row={row({ outputs: [{ name: "summary", value: "S" }] })}+ />,+ );++ expect(screen.getByText("summary")).toBeDefined();+ expect(screen.getByText("S")).toBeDefined();+ });++ it("renders outputs dictionaries through the output list", () => {+ render(<ToolResult row={row({ outputs: { answer: ["A"] } })} />);++ expect(screen.getByText("answer")).toBeDefined();+ expect(screen.getByText("A")).toBeDefined();+ });++ it("renders a link card for outputs with a URL and status code", () => {+ render(+ <ToolResult+ row={row({+ url: "https://example.com/page",+ title: "Example page",+ status_code: 200,+ })}+ />,+ );++ expect(screen.getByText("Example page")).toBeDefined();+ expect(screen.getByText("200")).toBeDefined();+ expect(screen.getByLabelText("Open link").getAttribute("href")).toBe(+ "https://example.com/page",+ );+ });++ it("renders a size for link outputs reporting bytes", () => {+ render(+ <ToolResult+ row={row({ url: "https://example.com/file", bytes: 4096 })}+ />,+ );++ expect(screen.getByText("4.0 KB")).toBeDefined();+ });++ it("renders single boolean outputs as a status card", () => {+ render(<ToolResult row={row({ type: "done", ok: true })} />);++ expect(screen.getByText("Done")).toBeDefined();+ });++ it("renders single numeric outputs as a stat card", () => {+ render(<ToolResult row={row({ deleted_count: 5 })} />);++ expect(screen.getByText("5")).toBeDefined();+ expect(screen.getByText("deleted count")).toBeDefined();+ });++ it("renders single string-array outputs as chips", () => {+ render(<ToolResult row={row({ tags: ["alpha", "beta"] })} />);++ expect(screen.getByText("Tags")).toBeDefined();+ expect(screen.getByText("alpha")).toBeDefined();+ expect(screen.getByText("beta")).toBeDefined();+ });++ it("renders single status strings as a status pill", () => {+ render(<ToolResult row={row({ status: "RUNNING" })} />);++ expect(screen.getByText("Status")).toBeDefined();+ expect(screen.getByText("running")).toBeDefined();+ });++ it("falls back to key/value output for run_block payloads without a block", () => {+ render(<ToolResult row={row({ note: "queued" }, "run_block")} />);++ expect(screen.getByText("Note")).toBeDefined();+ expect(screen.getByText("queued")).toBeDefined();+ });++ it("falls back to the message for connect_integration without setup info", () => {+ render(+ <ToolResult+ row={row({ message: "Please connect" }, "connect_integration")}+ />,+ );++ expect(screen.getByText("Please connect")).toBeDefined();+ });++ it("falls back to key/value output for empty web search results", () => {+ render(<ToolResult row={row({ results: [] }, "web_search")} />);++ expect(screen.getByText("Results")).toBeDefined();+ });++ it("falls back to key/value pairs for multi-field outputs", () => {+ render(<ToolResult row={row({ region: "us-east", replicas: 3 })} />);++ expect(screen.getByText("Region")).toBeDefined();+ expect(screen.getByText("us-east")).toBeDefined();+ expect(screen.getByText("Replicas")).toBeDefined();+ expect(screen.getByText("3")).toBeDefined();+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResultViews.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResultViews.test.tsxnew file mode 100644index 0000000000..9a512888df--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResultViews.test.tsx@@ -0,0 +1,221 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import type { ChainRow } from "../helpers";+import {+ FileCard,+ KeyValueList,+ OutputList,+ SearchResults,+ Terminal,+ TodoList,+} from "../ToolResultViews";++function row(output: unknown, input?: unknown): ChainRow {+ return {+ key: "tool",+ category: "other",+ text: "Tool",+ state: "done",+ output,+ input,+ };+}++describe("SearchResults", () => {+ afterEach(cleanup);++ it("renders linked results with their domain and an answer", () => {+ render(+ <SearchResults+ items={[{ title: "Wiki page", url: "https://en.wikipedia.org/wiki/X" }]}+ answer="Paris is the capital"+ />,+ );++ expect(screen.getByText("Paris is the capital")).toBeDefined();+ const link = screen.getByRole("link", { name: "Wiki page" });+ expect(link.getAttribute("href")).toBe("https://en.wikipedia.org/wiki/X");+ expect(screen.getByText("en.wikipedia.org")).toBeDefined();+ });++ it("renders unlinked results as plain text", () => {+ render(<SearchResults items={[{ snippet: "Loose snippet" }]} />);++ expect(screen.getByText("Loose snippet")).toBeDefined();+ expect(screen.queryByRole("link")).toBeNull();+ });++ it("falls back to inline JSON for untitled results", () => {+ render(<SearchResults items={[{ score: 3 }]} />);++ expect(screen.getByText('{"score":3}')).toBeDefined();+ });++ it("swaps the favicon for a globe icon when it fails to load", () => {+ const { container } = render(+ <SearchResults+ items={[{ title: "Wiki page", url: "https://en.wikipedia.org/wiki/X" }]}+ />,+ );++ const favicon = container.querySelector("img");+ expect(favicon).not.toBeNull();++ fireEvent.error(favicon as HTMLImageElement);++ expect(container.querySelector("img")).toBeNull();+ });+});++describe("Terminal", () => {+ afterEach(cleanup);++ it("shows the command, stdout and a non-zero exit code", () => {+ render(+ <Terminal+ row={row({ stdout: "file.txt", exit_code: 2 }, { command: "ls" })}+ />,+ );++ expect(screen.getByText("ls")).toBeDefined();+ expect(screen.getByText("file.txt")).toBeDefined();+ expect(screen.getByText("exit 2")).toBeDefined();+ });++ it("hides the exit line for successful commands", () => {+ render(+ <Terminal+ row={row({ stdout: "ok", exit_code: 0 }, { command: "true" })}+ />,+ );++ expect(screen.getByText("ok")).toBeDefined();+ expect(screen.queryByText("exit 0")).toBeNull();+ });++ it("uses stderr when stdout is missing", () => {+ render(<Terminal row={row({ stderr: "boom" }, { command: "make" })} />);++ expect(screen.getByText("boom")).toBeDefined();+ });+});++describe("TodoList", () => {+ afterEach(cleanup);++ it("renders todos across statuses", () => {+ render(+ <TodoList+ row={row(+ { ok: true },+ {+ todos: [+ { content: "Task A", status: "completed" },+ { content: "Task B", status: "in_progress" },+ { activeForm: "Doing Task C", status: "pending" },+ ],+ },+ )}+ />,+ );++ expect(screen.getByText("Task A")).toBeDefined();+ expect(screen.getByText("Task B")).toBeDefined();+ expect(screen.getByText("Doing Task C")).toBeDefined();+ });++ it("falls back to the raw output when no todos exist", () => {+ render(<TodoList row={row({ note: "no todos" }, {})} />);++ expect(screen.getByText("Note")).toBeDefined();+ expect(screen.getByText("no todos")).toBeDefined();+ });+});++describe("FileCard", () => {+ afterEach(cleanup);++ it("shows the path, size and preview from the row", () => {+ render(+ <FileCard+ row={row(+ {+ size_bytes: 2048,+ mime_type: "image/png",+ preview: "binary preview",+ },+ { file_path: "chart.png" },+ )}+ />,+ );++ expect(screen.getByText("chart.png")).toBeDefined();+ expect(screen.getByText("2.0 KB")).toBeDefined();+ expect(screen.getByText("binary preview")).toBeDefined();+ });++ it("reads the path from the output when the input lacks one", () => {+ render(<FileCard row={row({ path: "out.txt", size: 12 })} />);++ expect(screen.getByText("out.txt")).toBeDefined();+ expect(screen.getByText("12 B")).toBeDefined();+ });++ it("falls back to key/value output without any path", () => {+ render(<FileCard row={row({ status: "deleted" })} />);++ expect(screen.getByText("Status")).toBeDefined();+ expect(screen.getByText("deleted")).toBeDefined();+ });+});++describe("OutputList", () => {+ afterEach(cleanup);++ it("labels items by name and prints values", () => {+ render(+ <OutputList+ items={[+ { name: "summary", value: "All good" },+ { value: "unnamed value" },+ ]}+ />,+ );++ expect(screen.getByText("summary")).toBeDefined();+ expect(screen.getByText("All good")).toBeDefined();+ expect(screen.getByText("Output 2")).toBeDefined();+ expect(screen.getByText("unnamed value")).toBeDefined();+ });+});++describe("KeyValueList", () => {+ afterEach(cleanup);++ it("renders humanized keys with inline values", () => {+ render(<KeyValueList value={{ status_code: 200, ok: true }} />);++ expect(screen.getByText("Status code")).toBeDefined();+ expect(screen.getByText("200")).toBeDefined();+ expect(screen.getByText("Ok")).toBeDefined();+ expect(screen.getByText("true")).toBeDefined();+ });++ it("renders plain strings as preformatted text", () => {+ render(<KeyValueList value="raw output" />);++ expect(screen.getByText("raw output")).toBeDefined();+ });++ it("renders nothing for empty strings", () => {+ const { container } = render(<KeyValueList value=" " />);++ expect(container.firstChild).toBeNull();+ });++ it("renders nothing for empty objects", () => {+ const { container } = render(<KeyValueList value={{}} />);++ expect(container.firstChild).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolStatusBadge.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolStatusBadge.test.tsxnew file mode 100644index 0000000000..6360816f71--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolStatusBadge.test.tsx@@ -0,0 +1,44 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import { ToolStatusBadge } from "../ToolStatusBadge";++describe("ToolStatusBadge", () => {+ afterEach(cleanup);++ it("keeps the tool icon when running completes", () => {+ const { rerender } = render(+ <ToolStatusBadge state="running" label="Running">+ <span>tool</span>+ </ToolStatusBadge>,+ );++ expect(screen.getByRole("img", { name: "Running" }).dataset.state).toBe(+ "spinning",+ );+ expect(screen.getByText("tool")).toBeDefined();++ rerender(+ <ToolStatusBadge state="done" label="Done">+ <span>tool</span>+ </ToolStatusBadge>,+ );++ expect(screen.getByRole("img", { name: "Done" }).dataset.state).toBe(+ "done",+ );+ expect(screen.getByText("tool")).toBeDefined();+ });++ it("keeps completed rows on their tool icon", () => {+ render(+ <ToolStatusBadge state="done" label="Connect">+ <span>integration</span>+ </ToolStatusBadge>,+ );++ expect(screen.getByRole("img", { name: "Connect" }).dataset.state).toBe(+ "done",+ );+ expect(screen.getByText("integration")).toBeDefined();+ });+});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.tsnew file mode 100644index 0000000000..924e583429--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts@@ -0,0 +1,453 @@+import { describe, expect, it } from "vitest";+import {+ isChainableToolPart,+ type MessagePart,+} from "../../ChatMessagesContainer/helpers";+import {+ buildChainSegments,+ getChainHeading,+ isChainPart,+ isLiftedSetupRow,+ toChainRow,+ type ChainRow,+} from "../helpers";++function textPart(text: string): MessagePart {+ return { type: "text", text } as MessagePart;+}++function toolPart(+ toolName: string,+ input: unknown = {},+ output: unknown = {},+): MessagePart {+ return {+ type: `tool-${toolName}`,+ state: "output-available",+ toolCallId: `call-${toolName}`,+ input,+ output,+ } as MessagePart;+}++describe("buildChainSegments", () => {+ it("groups consecutive tool and reasoning parts around long text", () => {+ // Long text is a real answer, not progress narration — it splits chains.+ const parts = [+ { type: "step-start" } as MessagePart,+ { type: "reasoning", text: "Plan", state: "done" } as MessagePart,+ toolPart("web_search"),+ textPart("Result. ".repeat(30)),+ toolPart("web_fetch"),+ ];++ expect(buildChainSegments(parts)).toEqual([+ { kind: "chain", parts: [parts[1], parts[2]], index: 1 },+ { kind: "part", part: parts[3], index: 3 },+ { kind: "chain", parts: [parts[4]], index: 4 },+ ]);+ });++ it("folds short narration between tool calls into the chain", () => {+ const parts = [+ toolPart("web_search"),+ textPart("Now fetching the page."),+ toolPart("web_fetch"),+ ];++ expect(buildChainSegments(parts)).toEqual([+ { kind: "chain", parts, index: 0 },+ ]);+ });++ it("keeps every tool family in the new chain UI", () => {+ const specializedTool = toolPart("decompose_goal");+ const genericTool = toolPart("web_search");++ expect(+ buildChainSegments([specializedTool, genericTool], isChainableToolPart),+ ).toEqual([+ {+ kind: "chain",+ parts: [specializedTool, genericTool],+ index: 0,+ },+ ]);+ });++ it.each([+ "ask_question",+ "find_block",+ "find_agent",+ "find_library_agent",+ "search_docs",+ "get_doc_page",+ "connect_integration",+ "run_block",+ "continue_run_block",+ "run_mcp_tool",+ "run_agent",+ "schedule_agent",+ "setup_agent_webhook_trigger",+ "decompose_goal",+ "create_agent",+ "edit_agent",+ "view_agent_output",+ "search_feature_requests",+ "create_feature_request",+ ])("routes legacy %s cards through ToolChain", (toolName) => {+ expect(isChainableToolPart(toolPart(toolName))).toBe(true);+ });+});++describe("toChainRow", () => {+ it("turns short text into a narration row and skips long or empty text", () => {+ const narration = toChainRow(textPart("Now searching for hotels."), 3);+ expect(narration).toEqual({+ key: "narration-3",+ category: "narration",+ text: "Now searching for hotels.",+ state: "done",+ });++ expect(toChainRow(textPart("word ".repeat(60)), 0)).toBeNull();+ expect(toChainRow(textPart(" "), 0)).toBeNull();+ expect(toChainRow({ type: "step-start" } as MessagePart, 0)).toBeNull();+ });++ it("maps streaming and settled reasoning parts", () => {+ const streaming = toChainRow(+ {+ type: "reasoning",+ text: "Weighing options",+ state: "streaming",+ } as MessagePart,+ 1,+ );+ expect(streaming).toMatchObject({+ key: "reasoning-1",+ category: "reasoning",+ text: "Thinking…",+ state: "running",+ reasoningText: "Weighing options",+ });++ const settled = toChainRow(+ {+ type: "reasoning",+ text: "Weighed options",+ state: "done",+ } as MessagePart,+ 2,+ );+ expect(settled).toMatchObject({ text: "Thought", state: "done" });+ });++ it("marks failed tool calls with their error detail", () => {+ const row = toChainRow(+ {+ type: "tool-web_search",+ state: "output-error",+ toolCallId: "call-err",+ input: { query: "hotels" },+ errorText: "Rate limited",+ } as MessagePart,+ 0,+ );++ expect(row).toMatchObject({+ state: "error",+ detail: "Rate limited",+ text: 'Failed while searching the web for "hotels"',+ });+ });++ it("ignores partial input while the input JSON is still streaming", () => {+ const row = toChainRow(+ {+ type: "tool-web_search",+ state: "input-streaming",+ toolCallId: "call-stream",+ input: { query: "par" },+ } as MessagePart,+ 0,+ );++ expect(row).toMatchObject({+ state: "running",+ text: "Searching the web for…",+ });+ });++ it("falls back to generic categorization for non-catalog tools", () => {+ const grep = toChainRow(+ toolPart("Grep", { pattern: "TODO" }, "3 matches"),+ 0,+ );+ expect(grep).toMatchObject({+ category: "search",+ text: 'Searched for "TODO"',+ state: "done",+ });++ const custom = toChainRow(toolPart("polish_widgets", {}, {}), 0);+ expect(custom).toMatchObject({+ category: "other",+ text: "Polish widgets completed",+ });+ });++ it.each([+ [+ { type: "review_required", block_name: "Send Email" },+ "Review Send Email",+ ],+ [{ type: "review_required" }, "Review this action"],+ [{ type: "suggested_goal" }, "Review the suggested goal"],+ [{ type: "need_login", message: "Log in first" }, "Log in first"],+ [{ type: "need_login" }, "Action required"],+ [{ type: "setup_requirements" }, "Complete setup to continue"],+ ])("labels action-required output %j", (output, expected) => {+ const row = toChainRow(toolPart("run_block", {}, output), 0);++ expect(row?.requiresAction).toBe(true);+ expect(row?.text).toBe(expected);+ });++ it("does not require action for plain successful output", () => {+ const row = toChainRow(toolPart("run_block", {}, { ok: true }), 0);+ expect(row?.requiresAction).toBe(false);+ });+});++describe("isLiftedSetupRow", () => {+ it("lifts only setup_requirements rows that carry setup_info", () => {+ const lifted = toChainRow(+ toolPart(+ "connect_integration",+ {},+ { type: "setup_requirements", setup_info: { agent_name: "GitHub" } },+ ),+ 0,+ );+ const notLifted = toChainRow(+ toolPart("run_block", {}, { type: "review_required" }),+ 0,+ );++ expect(lifted && isLiftedSetupRow(lifted)).toBe(true);+ expect(notLifted && isLiftedSetupRow(notLifted)).toBe(false);+ });+});++describe("isChainPart", () => {+ it("accepts reasoning and tool parts only", () => {+ expect(isChainPart({ type: "reasoning", text: "" } as MessagePart)).toBe(+ true,+ );+ expect(isChainPart(toolPart("web_search"))).toBe(true);+ expect(isChainPart(textPart("Hello"))).toBe(false);+ });+});++describe("toChainRow provider icons", () => {+ it("normalizes a provider slug from tool output into an icon path", () => {+ const row = toChainRow(+ toolPart("run_block", {}, { provider: "Google Maps" }),+ 0,+ );++ expect(row?.providerIconSrc).toBe("/integrations/google_maps.png");+ });++ it("removes unsafe characters from provider icon paths", () => {+ const row = toChainRow(+ toolPart("run_block", {}, { provider: "../../Google?<script>" }),+ 0,+ );++ expect(row?.providerIconSrc).toBe("/integrations/googlescript.png");+ });++ it("pins setup requirements open with an action-oriented label", () => {+ const setupRow = toChainRow(+ toolPart(+ "connect_integration",+ { provider: "github" },+ JSON.stringify({+ type: "setup_requirements",+ setup_info: { agent_name: "GitHub" },+ }),+ ),+ 0,+ );++ expect(setupRow?.requiresAction).toBe(true);+ expect(setupRow?.text).toBe("Connect GitHub to continue");+ });+});++describe("getChainHeading", () => {+ it("uses the last running row while streaming", () => {+ const rows: ChainRow[] = [+ {+ key: "1",+ category: "reasoning",+ text: "Earlier failure",+ state: "error",+ },+ { key: "2", category: "web", text: "Searching docs", state: "running" },+ ];++ expect(getChainHeading(rows, true)).toBe("Searching docs");+ });++ it("summarizes distinct settled categories", () => {+ const rows: ChainRow[] = [+ { key: "1", category: "web", text: "Search", state: "done" },+ { key: "2", category: "web", text: "Fetch", state: "done" },+ { key: "3", category: "bash", text: "Run", state: "done" },+ ];++ expect(getChainHeading(rows, false)).toBe("Searched the web, ran commands");+ });++ it("surfaces the latest error detail", () => {+ const rows: ChainRow[] = [+ { key: "1", category: "web", text: "Search", state: "done" },+ {+ key: "2",+ category: "bash",+ text: "Failed while running command",+ detail: "Permission denied",+ state: "error",+ },+ ];++ expect(getChainHeading(rows, false)).toBe("Permission denied");+ });++ it("surfaces required actions ahead of a settled summary", () => {+ const rows: ChainRow[] = [+ { key: "1", category: "web", text: "Searched", state: "done" },+ {+ key: "2",+ category: "integration",+ text: "Connect GitHub to continue",+ state: "done",+ requiresAction: true,+ },+ ];++ expect(getChainHeading(rows, false)).toBe("Connect GitHub to continue");+ });++ it("skips lifted action rows and falls back to the summary", () => {+ const rows: ChainRow[] = [+ { key: "1", category: "web", text: "Searched", state: "done" },+ {+ key: "2",+ category: "question",+ text: "Asked you a question",+ state: "done",+ requiresAction: true,+ lifted: true,+ },+ ];++ expect(getChainHeading(rows, false)).toBe(+ "Searched the web, asked you questions",+ );+ });++ it("falls back to Working… when there is nothing to summarize", () => {+ expect(getChainHeading([], false)).toBe("Working…");+ expect(+ getChainHeading(+ [{ key: "1", category: "narration", text: "On it", state: "done" }],+ false,+ ),+ ).toBe("Working…");+ });++ it("summarizes settled rows while streaming when nothing is running", () => {+ const rows: ChainRow[] = [+ { key: "1", category: "bash", text: "Ran command", state: "done" },+ ];++ expect(getChainHeading(rows, true)).toBe("Ran commands");+ });++ it("caps the settled summary at three distinct categories", () => {+ const rows: ChainRow[] = [+ { key: "1", category: "web", text: "a", state: "done" },+ { key: "2", category: "bash", text: "b", state: "done" },+ { key: "3", category: "todo", text: "c", state: "done" },+ { key: "4", category: "docs", text: "d", state: "done" },+ ];++ expect(getChainHeading(rows, false)).toBe(+ "Searched the web, ran commands, updated tasks",+ );+ });+});++describe("buildChainSegments edge cases", () => {+ it("folds trailing narration optimistically while streaming", () => {+ const parts = [toolPart("web_search"), textPart("Wrapping up.")];++ expect(buildChainSegments(parts, isChainPart, true)).toEqual([+ { kind: "chain", parts, index: 0 },+ ]);+ });++ it("keeps trailing narration out of a settled chain", () => {+ const parts = [toolPart("web_search"), textPart("Here you go.")];++ expect(buildChainSegments(parts, isChainPart, false)).toEqual([+ { kind: "chain", parts: [parts[0]], index: 0 },+ { kind: "part", part: parts[1], index: 1 },+ ]);+ });++ it("looks past narration and step-start when checking for tools ahead", () => {+ const parts = [+ toolPart("web_search"),+ textPart("First note."),+ { type: "step-start" } as MessagePart,+ textPart("Second note."),+ toolPart("web_fetch"),+ ];++ expect(buildChainSegments(parts)).toEqual([+ {+ kind: "chain",+ parts: [parts[0], parts[1], parts[3], parts[4]],+ index: 0,+ },+ ]);+ });++ it("keeps narration out when only a real answer follows", () => {+ const parts = [+ toolPart("web_search"),+ textPart("Almost there."),+ textPart("Answer. ".repeat(40)),+ ];++ expect(buildChainSegments(parts)).toEqual([+ { kind: "chain", parts: [parts[0]], index: 0 },+ { kind: "part", part: parts[1], index: 1 },+ { kind: "part", part: parts[2], index: 2 },+ ]);+ });++ it("emits leading text before any chain as its own part", () => {+ const parts = [textPart("Intro."), toolPart("web_search")];++ expect(buildChainSegments(parts)).toEqual([+ { kind: "part", part: parts[0], index: 0 },+ { kind: "chain", parts: [parts[1]], index: 1 },+ ]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/resultHelpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/resultHelpers.test.tsnew file mode 100644index 0000000000..43d0ffbe31--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/resultHelpers.test.ts@@ -0,0 +1,158 @@+import { describe, expect, it } from "vitest";+import {+ asItems,+ asObject,+ dictToOutputItems,+ formatBytes,+ formatWhen,+ humanizeKey,+ inline,+ integrationIconSrc,+ resultItemKey,+ safeHostname,+ str,+ stripBaseFields,+} from "../resultHelpers";++describe("asObject", () => {+ it("accepts records and JSON-encoded records", () => {+ expect(asObject({ ok: true })).toEqual({ ok: true });+ expect(asObject('{"ok":true}')).toEqual({ ok: true });+ });++ it("rejects arrays, including JSON-encoded arrays", () => {+ expect(asObject(["value"])).toBeNull();+ expect(asObject('["value"]')).toBeNull();+ });++ it("rejects malformed JSON and non-object primitives", () => {+ expect(asObject("not json")).toBeNull();+ expect(asObject(null)).toBeNull();+ expect(asObject(42)).toBeNull();+ expect(asObject("42")).toBeNull();+ });+});++describe("str", () => {+ it("returns the first non-empty string across candidate keys", () => {+ expect(str({ a: "", b: " ", c: "value" }, "a", "b", "c")).toBe("value");+ });++ it("skips non-string values and returns null when nothing matches", () => {+ expect(str({ a: 3, b: true }, "a", "b")).toBeNull();+ expect(str({}, "missing")).toBeNull();+ });+});++describe("asItems", () => {+ it("returns null for non-arrays and empty arrays", () => {+ expect(asItems({ length: 1 })).toBeNull();+ expect(asItems([])).toBeNull();+ expect(asItems("nope")).toBeNull();+ });++ it("wraps primitive entries as value records", () => {+ expect(asItems(["a", { id: "1" }])).toEqual([{ value: "a" }, { id: "1" }]);+ });+});++describe("stripBaseFields", () => {+ it("removes the response envelope fields only", () => {+ expect(+ stripBaseFields({+ type: "done",+ message: "ok",+ session_id: "s1",+ result: 5,+ }),+ ).toEqual({ result: 5 });+ });+});++describe("resultItemKey", () => {+ it("prefers the highest-priority identifying field", () => {+ expect(resultItemKey({ name: "n", id: "abc" }, 0)).toBe("id:abc");+ expect(resultItemKey({ url: "https://x", title: "t" }, 0)).toBe(+ "url:https://x",+ );+ expect(resultItemKey({ execution_id: 7 }, 0)).toBe("execution_id:7");+ });++ it("falls back to the index with inline content", () => {+ expect(resultItemKey({ other: true }, 3)).toBe('item:3:{"other":true}');+ });+});++describe("humanizeKey", () => {+ it("replaces underscores and capitalizes the first letter", () => {+ expect(humanizeKey("status_code")).toBe("Status code");+ expect(humanizeKey("ok")).toBe("Ok");+ });+});++describe("safeHostname", () => {+ it("returns a display hostname for valid URLs", () => {+ expect(safeHostname("https://www.example.com/path")).toBe("example.com");+ });++ it("returns null for invalid URLs", () => {+ expect(safeHostname("not a URL")).toBeNull();+ });+});++describe("integrationIconSrc", () => {+ it("normalizes allowed provider characters", () => {+ expect(integrationIconSrc("Google Maps")).toBe(+ "/integrations/google_maps.png",+ );+ expect(integrationIconSrc("../../Google Maps?<script>")).toBe(+ "/integrations/google_mapsscript.png",+ );+ });++ it("rejects providers without safe characters", () => {+ expect(integrationIconSrc("../../")).toBeNull();+ });+});++describe("result formatting", () => {+ it("flattens single-value block outputs", () => {+ expect(dictToOutputItems({ result: ["done"], count: [1, 2] })).toEqual([+ { name: "result", value: "done" },+ { name: "count", value: [1, 2] },+ ]);+ });++ it("truncates long inline JSON values", () => {+ expect(inline({ value: "x".repeat(150) })).toHaveLength(121);+ expect(inline({ value: "x".repeat(150) })).toMatch(/…$/);+ });++ it("formats byte units", () => {+ expect(formatBytes(12)).toBe("12 B");+ expect(formatBytes(1536)).toBe("1.5 KB");+ expect(formatBytes(1572864)).toBe("1.5 MB");+ });++ it("returns invalid date values unchanged", () => {+ expect(formatWhen("not-a-date")).toBe("not-a-date");+ });++ it("formats valid dates for display", () => {+ const formatted = formatWhen("2026-08-21T10:00:00Z");+ expect(formatted).not.toBe("2026-08-21T10:00:00Z");+ expect(formatted).toMatch(/\d/);+ });++ it("returns null for empty output dictionaries", () => {+ expect(dictToOutputItems({})).toBeNull();+ expect(dictToOutputItems(["a"])).toBeNull();+ expect(dictToOutputItems("text")).toBeNull();+ });++ it("stringifies inline primitives", () => {+ expect(inline("text")).toBe("text");+ expect(inline(3)).toBe("3");+ expect(inline(false)).toBe("false");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/toolCatalog.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/toolCatalog.test.tsnew file mode 100644index 0000000000..c7fa2cffbe--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/toolCatalog.test.ts@@ -0,0 +1,234 @@+import { describe, expect, it } from "vitest";+import { getCatalogLabel } from "../toolCatalog";++describe("getCatalogLabel", () => {+ it("returns null for tools missing from the catalog", () => {+ expect(getCatalogLabel("totally_unknown_tool", {}, "running")).toBeNull();+ });++ it("builds running, done and error labels around the subject", () => {+ const input = { query: "copilot news" };++ expect(getCatalogLabel("web_search", input, "running")).toEqual({+ category: "web",+ text: 'Searching the web for "copilot news"…',+ });+ expect(getCatalogLabel("web_search", input, "done")).toEqual({+ category: "web",+ text: 'Searched the web for "copilot news"',+ });+ expect(getCatalogLabel("web_search", input, "error")).toEqual({+ category: "web",+ text: 'Failed while searching the web for "copilot news"',+ });+ });++ it("omits the subject when input is not an object", () => {+ expect(getCatalogLabel("web_search", undefined, "running")?.text).toBe(+ "Searching the web for…",+ );+ expect(getCatalogLabel("web_search", "raw", "done")?.text).toBe(+ "Searched the web for",+ );+ });++ it("truncates long subjects with an ellipsis", () => {+ const url = `https://example.com/${"a".repeat(80)}`;+ const text = getCatalogLabel("web_fetch", { url }, "done")?.text ?? "";++ expect(text.startsWith('Fetched "https://example.com/')).toBe(true);+ expect(text.endsWith('…"')).toBe(true);+ expect(text.length).toBeLessThan(url.length);+ });++ it.each([+ ["bash_exec", { command: "ls -la" }, "done", 'Ran command "ls -la"'],+ [+ "browser_navigate",+ { url: "https://agpt.co" },+ "running",+ 'Opening "https://agpt.co"…',+ ],+ ["read_workspace_file", { path: "notes.md" }, "done", 'Read "notes.md"'],+ [+ "read_workspace_file",+ { filename: "notes.md" },+ "done",+ 'Read "notes.md"',+ ],+ [+ "write_workspace_file",+ { filename: "out.csv" },+ "running",+ 'Writing "out.csv"…',+ ],+ ["delete_workspace_file", { path: "tmp.txt" }, "done", 'Deleted "tmp.txt"'],+ [+ "delete_workspace_file",+ { filename: "tmp.txt" },+ "done",+ 'Deleted "tmp.txt"',+ ],+ [+ "post_to_chat_platform",+ { channel: "#general" },+ "done",+ 'Posted to "#general"',+ ],+ [+ "run_block",+ { block_name: "Web Search" },+ "done",+ 'Ran block "Web Search"',+ ],+ [+ "run_block",+ { block_id: "abcdefabcdefabcdefabcdef" },+ "done",+ 'Ran block "abcdefabcdefabcdefab…"',+ ],+ [+ "run_mcp_tool",+ { tool_name: "list_issues" },+ "done",+ 'Ran MCP tool "list_issues"',+ ],+ [+ "search_docs",+ { query: "webhooks" },+ "done",+ 'Searched docs for "webhooks"',+ ],+ [+ "get_doc_page",+ { path: "platform/blocks" },+ "done",+ "Read doc page platform/blocks",+ ],+ ["store_skill", { name: "scraper" }, "done", 'Saved skill "scraper"'],+ ["read_skill", { name: "scraper" }, "running", 'Reading skill "scraper"…'],+ ["delete_skill", { name: "scraper" }, "done", 'Deleted skill "scraper"'],+ [+ "connect_integration",+ { provider: "github" },+ "running",+ "Connecting github…",+ ],+ [+ "search_feature_requests",+ { query: "dark mode" },+ "done",+ 'Searched feature requests for "dark mode"',+ ],+ [+ "create_feature_request",+ { title: "Dark mode" },+ "done",+ 'Filed feature request "Dark mode"',+ ],+ ["TodoWrite", {}, "done", "Updated tasks"],+ ["TodoWrite", {}, "error", "Failed while updating tasks"],+ ["get_platform_info", {}, "running", "Checking platform info…"],+ ])("labels platform tool %s", (tool, input, state, expected) => {+ expect(+ getCatalogLabel(tool, input, state as "running" | "done" | "error")?.text,+ ).toBe(expected);+ });++ it.each([+ [+ "decompose_goal",+ { goal: "Track prices" },+ "done",+ 'Broke down the goal "Track prices"',+ ],+ ["find_block", { query: "email" }, "done", 'Found blocks for "email"'],+ [+ "find_agent",+ { query: "scraper" },+ "running",+ 'Finding agents for "scraper"…',+ ],+ [+ "find_library_agent",+ { query: "newsletter" },+ "done",+ 'Searched your library for "newsletter"',+ ],+ [+ "memory_search",+ { query: "budget" },+ "done",+ 'Searched memory for "budget"',+ ],+ [+ "memory_store",+ { name: "preferences" },+ "done",+ 'Stored memory "preferences"',+ ],+ ["create_folder", { name: "Reports" }, "done", 'Created folder "Reports"'],+ ["update_folder", { name: "Reports" }, "done", 'Updated folder "Reports"'],+ [+ "run_agent",+ { username_agent_slug: "abhi/scraper" },+ "done",+ 'Ran agent "abhi/scraper"',+ ],+ [+ "run_agent",+ { library_agent_id: "0123456789012345678901234" },+ "done",+ 'Ran agent "01234567890123456789…"',+ ],+ ["add_understanding", {}, "done", "Noted context"],+ ["enter_agent_building_mode", {}, "running", "Entering building mode…"],+ ])("labels agent tool %s", (tool, input, state, expected) => {+ expect(+ getCatalogLabel(tool, input, state as "running" | "done" | "error")?.text,+ ).toBe(expected);+ });++ it("truncates run_sub_session prompts to 45 characters", () => {+ const prompt = "Investigate every failing pipeline in the workspace today";+ const text =+ getCatalogLabel("run_sub_session", { prompt }, "running")?.text ?? "";++ expect(text.startsWith('Delegating to sub-AutoPilot: "Investigate')).toBe(+ true,+ );+ expect(text.endsWith('…"…')).toBe(true);+ });++ it("reads ask_question subjects from the direct field or the array", () => {+ expect(+ getCatalogLabel("ask_question", { question: "Which region?" }, "done")+ ?.text,+ ).toBe('Asked you a question "Which region?"');++ expect(+ getCatalogLabel(+ "ask_question",+ { questions: [{ question: "Which format?" }] },+ "done",+ )?.text,+ ).toBe('Asked you a question "Which format?"');++ expect(+ getCatalogLabel("ask_question", { questions: ["plain"] }, "done")?.text,+ ).toBe("Asked you a question");++ expect(getCatalogLabel("ask_question", {}, "done")?.text).toBe(+ "Asked you a question",+ );+ });++ it("ignores blank and non-string subject values", () => {+ expect(getCatalogLabel("web_search", { query: " " }, "done")?.text).toBe(+ "Searched the web for",+ );+ expect(getCatalogLabel("web_search", { query: 42 }, "done")?.text).toBe(+ "Searched the web for",+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/accordion.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/accordion.tsnew file mode 100644index 0000000000..cadd37cd56--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/accordion.ts@@ -0,0 +1,15 @@+// Shared expand/collapse motion for the tool accordions (chain panel + row+// result panel). Grid 0fr→1fr carries the height, opacity softens the edges,+// and easeOutQuint gives the long decelerating settle.+export const ACCORDION_PANEL =+ "grid transition-[grid-template-rows,opacity] duration-400 ease-out-quint motion-reduce:transition-none";++export function accordionState(open: boolean): string {+ return open+ ? "[grid-template-rows:1fr] opacity-100"+ : "[grid-template-rows:0fr] opacity-0";+}++// One fade for the whole panel — per-row staggering made long chains feel+// slow, and streaming rows already animate individually as they arrive.+export const PANEL_REVEAL = "animate-fade-up motion-reduce:animate-none";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.tsnew file mode 100644index 0000000000..9e70de4595--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts@@ -0,0 +1,39 @@+"use client";++import { createContext } from "react";+import type {+ ConnectorRequest,+ InputsRequest,+ McpConnectorRequest,+ QuestionRequest,+} from "../ChainActionCard/helpers";++/** One user-actionable card (credential setup, clarifying questions) inside+ * a tool chain. Cards register themselves instead of rendering their own+ * Proceed/Answer buttons; the chain renders a single Proceed that drafts+ * every card's message into the chat input in one go. */+export interface ChainActionEntry {+ id: string;+ ready: boolean;+ buildMessage: () => string | null;+ onSent?: () => void;+ /** Credentials this card needs. The chain merges every entry's request+ * into the single connectors table it renders underneath itself. */+ connectors?: ConnectorRequest;+ /** MCP server this card needs connected — rendered as a row in the same+ * connectors table, driven by the hidden MCPSetupCard's state machine. */+ mcp?: McpConnectorRequest;+ /** Editable run inputs this card collects, rendered in the same card as+ * the connectors instead of inside the chain rows. */+ inputs?: InputsRequest;+ /** Clarifying questions this card asks, rendered in the same card as the+ * connectors so everything the user owes the chain is in one place. */+ questions?: QuestionRequest;+}++export interface ChainActions {+ register: (entry: ChainActionEntry) => void;+ unregister: (id: string) => void;+}++export const ChainActionsContext = createContext<ChainActions | null>(null);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/fileDiffHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/fileDiffHelpers.tsnew file mode 100644index 0000000000..94039c28d6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/fileDiffHelpers.ts@@ -0,0 +1,65 @@+export interface DiffRow {+ old: number | null;+ cur: number | null;+ type: "ctx" | "add" | "del";+ text: string;+}++export interface ParsedDiff {+ rows: DiffRow[];+ added: number;+ removed: number;+ truncated: boolean;+}++export const MAX_RENDERED_DIFF_ROWS = 500;++export function isDiffText(value: unknown): value is string {+ if (typeof value !== "string") return false;+ return /^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@/m.test(value);+}++export function parseUnifiedDiff(diff: string): ParsedDiff {+ const rows: DiffRow[] = [];+ let added = 0;+ let removed = 0;+ let totalRows = 0;+ let inHunk = false;+ let oldLn = 1;+ let newLn = 1;+ for (const line of diff.split("\n")) {+ const hunk = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);+ if (hunk) {+ inHunk = true;+ oldLn = Number(hunk[1]);+ newLn = Number(hunk[2]);+ continue;+ }+ if (+ !inHunk ||+ line.startsWith("--- ") ||+ line.startsWith("+++ ") ||+ line === "\\ No newline at end of file"+ ) {+ continue;+ }+ let row: DiffRow;+ if (line.startsWith("-")) {+ removed++;+ row = { old: oldLn++, cur: null, type: "del", text: line.slice(1) };+ } else if (line.startsWith("+")) {+ added++;+ row = { old: null, cur: newLn++, type: "add", text: line.slice(1) };+ } else {+ row = {+ old: oldLn++,+ cur: newLn++,+ type: "ctx",+ text: line.startsWith(" ") ? line.slice(1) : line,+ };+ }+ totalRows++;+ if (rows.length < MAX_RENDERED_DIFF_ROWS) rows.push(row);+ }+ return { rows, added, removed, truncated: rows.length < totalRows };+}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.tsnew file mode 100644index 0000000000..84aadb40d8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts@@ -0,0 +1,303 @@+import type { ToolUIPart } from "ai";+import type { MessagePart } from "../ChatMessagesContainer/helpers";+import {+ extractToolName,+ getAnimationText,+ getToolCategory,+} from "../../tools/GenericTool/helpers";+import { type ChainCategory, getCatalogLabel } from "./toolCatalog";+import { asObject, integrationIconSrc } from "./resultHelpers";++export type ChainRowState = "running" | "done" | "error";++export interface ChainRow {+ key: string;+ category: ChainCategory;+ text: string;+ state: ChainRowState;+ detail?: string;+ providerIconSrc?: string;+ tool?: string;+ input?: unknown;+ output?: unknown;+ reasoningText?: string;+ requiresAction?: boolean;+ /** The row's user-facing work (connectors, inputs, questions) renders in+ * the card below the chain — the row is hidden but stays mounted so the+ * card keeps its registration. */+ lifted?: boolean;+}++const ACTION_RESPONSE_TYPES = new Set([+ "setup_requirements",+ "review_required",+ "need_login",+ "trigger_config_required",+ "suggested_goal",+]);++function actionLabel(output: unknown): string | null {+ const data = asObject(output);+ if (!data) return null;+ if (typeof data.type !== "string" || !ACTION_RESPONSE_TYPES.has(data.type)) {+ return null;+ }+ if (data.type === "setup_requirements") {+ const setup =+ data.setup_info && typeof data.setup_info === "object"+ ? (data.setup_info as Record<string, unknown>)+ : null;+ const name = setup?.agent_name;+ return typeof name === "string" && name.trim()+ ? `Connect ${name.trim()} to continue`+ : "Complete setup to continue";+ }+ if (data.type === "review_required") {+ const name = data.block_name;+ return typeof name === "string" && name.trim()+ ? `Review ${name.trim()}`+ : "Review this action";+ }+ if (data.type === "suggested_goal") return "Review the suggested goal";+ return typeof data.message === "string" && data.message.trim()+ ? data.message.trim()+ : "Action required";+}++/** Setup-requirements rows whose card registers with the chain and renders+ * outside it — including run_mcp_tool, whose hidden MCPSetupCard registers+ * an MCP row into the same connectors table. */+export function isLiftedSetupRow(row: ChainRow): boolean {+ const data = asObject(row.output);+ return (+ !!data && data.type === "setup_requirements" && !!asObject(data.setup_info)+ );+}++function getProviderIconSrc(tool: ToolUIPart): string | undefined {+ for (const source of [tool.input, tool.output]) {+ if (source && typeof source === "object" && "provider" in source) {+ const provider = (source as { provider: unknown }).provider;+ if (typeof provider === "string" && provider.trim()) {+ return integrationIconSrc(provider) ?? undefined;+ }+ }+ }+ return undefined;+}++export function isChainPart(part: MessagePart): boolean {+ return part.type === "reasoning" || part.type.startsWith("tool-");+}++// Short assistant text sandwiched between tool calls is progress narration+// ("Now searching for hotels."), not an answer — fold it into the chain so+// back-to-back tool calls collapse into one group instead of splitting on+// every sentence.+const NARRATION_MAX_CHARS = 200;++function narrationText(part: MessagePart): string | null {+ if (part.type !== "text") return null;+ const text = typeof part.text === "string" ? part.text.trim() : "";+ if (!text || text.length > NARRATION_MAX_CHARS) return null;+ return text;+}++export function toChainRow(part: MessagePart, index: number): ChainRow | null {+ const narration = narrationText(part);+ if (narration !== null) {+ return {+ key: `narration-${index}`,+ category: "narration",+ text: narration,+ state: "done",+ };+ }+ if (part.type === "reasoning") {+ const isStreaming = "state" in part && part.state === "streaming";+ return {+ key: `reasoning-${index}`,+ category: "reasoning",+ text: isStreaming ? "Thinking…" : "Thought",+ state: isStreaming ? "running" : "done",+ reasoningText:+ "text" in part && typeof part.text === "string" ? part.text : undefined,+ };+ }+ if (part.type.startsWith("tool-")) {+ const tool = part as ToolUIPart;+ const toolName = extractToolName(tool);+ const state: ChainRowState =+ tool.state === "output-error"+ ? "error"+ : tool.state === "output-available"+ ? "done"+ : "running";+ const detail =+ state === "error" && typeof tool.errorText === "string"+ ? tool.errorText+ : undefined;++ // While the input JSON is still streaming, labels/icons must not read+ // it — partial subjects re-trigger the swap animation on every delta.+ const isInputStreaming = tool.state === "input-streaming";+ const stableTool = isInputStreaming+ ? ({ ...tool, input: undefined } as ToolUIPart)+ : tool;++ const providerIconSrc = getProviderIconSrc(stableTool);+ const requiredActionLabel = actionLabel(tool.output);++ const data = {+ tool: toolName,+ input: stableTool.input,+ output: tool.output,+ };++ const catalogLabel = getCatalogLabel(toolName, stableTool.input, state);+ if (catalogLabel) {+ return {+ key: tool.toolCallId,+ ...catalogLabel,+ text: requiredActionLabel ?? catalogLabel.text,+ state,+ detail,+ providerIconSrc,+ requiresAction: requiredActionLabel !== null,+ ...data,+ };+ }++ const category = getToolCategory(toolName);+ return {+ key: tool.toolCallId,+ category,+ text: getAnimationText(stableTool, category),+ state,+ detail,+ providerIconSrc,+ requiresAction: requiredActionLabel !== null,+ ...data,+ };+ }+ return null;+}++const CATEGORY_SUMMARY: Record<ChainRow["category"], string> = {+ reasoning: "thought it through",+ bash: "ran commands",+ web: "searched the web",+ browser: "browsed the web",+ "file-read": "read files",+ "file-write": "wrote files",+ "file-delete": "deleted files",+ "file-list": "listed files",+ search: "searched files",+ edit: "edited files",+ todo: "updated tasks",+ compaction: "summarized context",+ agent: "ran agents",+ "agent-build": "built agents",+ plan: "planned the approach",+ block: "ran blocks",+ memory: "managed memory",+ folder: "organized folders",+ schedule: "managed schedules",+ trigger: "managed triggers",+ preset: "managed presets",+ chat: "posted updates",+ mcp: "used MCP tools",+ docs: "read the docs",+ skill: "used skills",+ integration: "connected integrations",+ feature: "handled feature requests",+ question: "asked you questions",+ info: "checked your account",+ narration: "",+ other: "used tools",+};++// Streaming → live label of the running row; settled → verb-chain like+// "Updated tasks, searched the web, ran commands".+export function getChainHeading(+ rows: ChainRow[],+ isStreaming: boolean,+): string {+ if (isStreaming) {+ const running = rows.findLast((r) => r.state === "running");+ if (running) return running.text;+ }+ const error = rows.findLast((row) => row.state === "error");+ if (error) return error.detail ?? error.text;+ const requiredAction = rows.findLast(+ (row) => row.requiresAction && !row.lifted,+ );+ if (requiredAction) return requiredAction.text;++ const phrases: string[] = [];+ const seenPhrases = new Set<string>();+ for (const row of rows) {+ if (row.category === "narration") continue;+ const phrase = CATEGORY_SUMMARY[row.category];+ if (!seenPhrases.has(phrase)) {+ seenPhrases.add(phrase);+ phrases.push(phrase);+ }+ if (phrases.length === 3) break;+ }+ const joined = phrases.join(", ") || "Working…";+ return joined.charAt(0).toUpperCase() + joined.slice(1);+}++export type ChainSegment =+ | { kind: "chain"; parts: MessagePart[]; index: number }+ | { kind: "part"; part: MessagePart; index: number };++export function buildChainSegments(+ parts: MessagePart[],+ isChainable: (part: MessagePart) => boolean = isChainPart,+ isStreaming = false,+): ChainSegment[] {+ const segments: ChainSegment[] = [];+ let chain: Extract<ChainSegment, { kind: "chain" }> | null = null;++ const hasChainableAhead = (from: number): boolean => {+ for (let i = from; i < parts.length; i++) {+ const part = parts[i];+ if (part.type === "step-start") continue;+ if (isChainable(part)) return true;+ if (narrationText(part) !== null) continue;+ return false;+ }+ return false;+ };++ parts.forEach((part, index) => {+ if (part.type === "step-start") return;+ if (isChainable(part)) {+ if (!chain) {+ chain = { kind: "chain", parts: [], index };+ segments.push(chain);+ }+ chain.parts.push(part);+ return;+ }+ // Fold short progress narration into the surrounding chain. While+ // streaming, fold optimistically so the text lands inside the chain+ // from the first token; once settled, keep it only when another tool+ // call follows, so the turn's final answer (even a short one) always+ // renders as regular message text.+ if (+ chain &&+ narrationText(part) !== null &&+ (isStreaming || hasChainableAhead(index + 1))+ ) {+ chain.parts.push(part);+ return;+ }+ chain = null;+ segments.push({ kind: "part", part, index });+ });++ return segments;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/resultHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/resultHelpers.tsnew file mode 100644index 0000000000..1ce02d6aeb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/resultHelpers.ts@@ -0,0 +1,140 @@+export function asObject(value: unknown): Record<string, unknown> | null {+ if (typeof value === "string") {+ try {+ const parsed = JSON.parse(value);+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)+ ? parsed+ : null;+ } catch {+ return null;+ }+ }+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++export function safeHostname(url: string): string | null {+ try {+ return new URL(url).hostname.replace(/^www\./, "");+ } catch {+ return null;+ }+}++export function integrationIconSrc(provider: string): string | null {+ const slug = provider+ .trim()+ .toLowerCase()+ .replace(/[\s-]+/g, "_")+ .replace(/[^a-z0-9_]/g, "");+ return slug ? `/integrations/${slug}.png` : null;+}++// Every backend tool response carries these envelope fields; cards read the+// domain payload, so shape detection runs on the stripped object.+const BASE_RESPONSE_KEYS = new Set(["type", "message", "session_id"]);++export function stripBaseFields(+ obj: Record<string, unknown>,+): Record<string, unknown> {+ return Object.fromEntries(+ Object.entries(obj).filter(([key]) => !BASE_RESPONSE_KEYS.has(key)),+ );+}++// Block/agent outputs arrive as {output_name: [values]}; flatten to+// {name, value} entries for OutputList.+export function dictToOutputItems(+ value: unknown,+): Record<string, unknown>[] | null {+ const obj =+ value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+ if (!obj) return null;+ const entries = Object.entries(obj);+ if (entries.length === 0) return null;+ return entries.map(([name, entryValue]) => ({+ name,+ value:+ Array.isArray(entryValue) && entryValue.length === 1+ ? entryValue[0]+ : entryValue,+ }));+}++export function asItems(value: unknown): Record<string, unknown>[] | null {+ if (!Array.isArray(value) || value.length === 0) return null;+ return value.map((item) =>+ item && typeof item === "object"+ ? (item as Record<string, unknown>)+ : { value: item },+ );+}++export function str(+ obj: Record<string, unknown>,+ ...keys: string[]+): string | null {+ for (const key of keys) {+ const value = obj[key];+ if (typeof value === "string" && value.trim()) return value;+ }+ return null;+}++export function inline(value: unknown): string {+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean")+ return String(value);+ const json = JSON.stringify(value);+ return json && json.length > 120 ? json.slice(0, 120) + "…" : (json ?? "");+}++export function resultItemKey(+ item: Record<string, unknown>,+ fallbackIndex: number,+): string {+ for (const field of [+ "id",+ "step_id",+ "keyword",+ "execution_id",+ "identifier",+ "path",+ "url",+ "name",+ "title",+ "content",+ ]) {+ const value = item[field];+ if (typeof value === "string" || typeof value === "number") {+ return `${field}:${value}`;+ }+ }+ return `item:${fallbackIndex}:${inline(item)}`;+}++export function humanizeKey(key: string): string {+ return key.replace(/_/g, " ").replace(/^\w/, (c) => c.toUpperCase());+}++const DATE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+});++export function formatWhen(iso: string): string {+ const date = new Date(iso);+ if (Number.isNaN(date.getTime())) return iso;+ return DATE_TIME_FORMATTER.format(date);+}++export function formatBytes(bytes: number): string {+ if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${bytes} B`;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.agent.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.agent.tsnew file mode 100644index 0000000000..12b5a1c787--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.agent.ts@@ -0,0 +1,146 @@+import { quoted, type ToolMeta } from "./toolCatalog.shared";++export const AGENT_TOOL_CATALOG: Record<string, ToolMeta> = {+ add_understanding: {+ category: "memory",+ running: "Noting context",+ done: "Noted context",+ },+ create_agent: {+ category: "agent-build",+ running: "Creating agent",+ done: "Created agent",+ },+ customize_agent: {+ category: "agent-build",+ running: "Customizing agent",+ done: "Customized agent",+ },+ edit_agent: {+ category: "agent-build",+ running: "Editing agent",+ done: "Edited agent",+ },+ validate_agent_graph: {+ category: "agent-build",+ running: "Validating agent",+ done: "Validated agent",+ },+ fix_agent_graph: {+ category: "agent-build",+ running: "Fixing agent",+ done: "Fixed agent",+ },+ enter_agent_building_mode: {+ category: "agent-build",+ running: "Entering building mode",+ done: "Entered building mode",+ },+ get_agent_building_guide: {+ category: "docs",+ running: "Reading the agent building guide",+ done: "Read the agent building guide",+ },+ decompose_goal: {+ category: "plan",+ running: "Breaking down the goal",+ done: "Broke down the goal",+ subject: (input) => quoted(input, "goal"),+ },+ find_block: {+ category: "block",+ running: "Finding blocks for",+ done: "Found blocks for",+ subject: (input) => quoted(input, "query"),+ },+ find_agent: {+ category: "agent",+ running: "Finding agents for",+ done: "Found agents for",+ subject: (input) => quoted(input, "query"),+ },+ find_library_agent: {+ category: "agent",+ running: "Searching your library for",+ done: "Searched your library for",+ subject: (input) => quoted(input, "query"),+ },+ memory_search: {+ category: "memory",+ running: "Searching memory for",+ done: "Searched memory for",+ subject: (input) => quoted(input, "query"),+ },+ memory_store: {+ category: "memory",+ running: "Storing memory",+ done: "Stored memory",+ subject: (input) => quoted(input, "name"),+ },+ memory_forget_search: {+ category: "memory",+ running: "Finding memories to forget",+ done: "Found memories to forget",+ },+ memory_forget_confirm: {+ category: "memory",+ running: "Forgetting memories",+ done: "Forgot memories",+ },+ create_folder: {+ category: "folder",+ running: "Creating folder",+ done: "Created folder",+ subject: (input) => quoted(input, "name"),+ },+ list_folders: {+ category: "folder",+ running: "Listing folders",+ done: "Listed folders",+ },+ update_folder: {+ category: "folder",+ running: "Updating folder",+ done: "Updated folder",+ subject: (input) => quoted(input, "name"),+ },+ move_folder: {+ category: "folder",+ running: "Moving folder",+ done: "Moved folder",+ },+ delete_folder: {+ category: "folder",+ running: "Deleting folder",+ done: "Deleted folder",+ },+ move_agents_to_folder: {+ category: "folder",+ running: "Moving agents to folder",+ done: "Moved agents to folder",+ },+ run_agent: {+ category: "agent",+ running: "Running agent",+ done: "Ran agent",+ subject: (input) =>+ quoted(input, "username_agent_slug") ??+ quoted(input, "library_agent_id", 20),+ },+ view_agent_output: {+ category: "agent",+ running: "Viewing agent output",+ done: "Viewed agent output",+ },+ run_sub_session: {+ category: "agent",+ running: "Delegating to sub-AutoPilot:",+ done: "Sub-AutoPilot handled:",+ subject: (input) => quoted(input, "prompt", 45),+ },+ get_sub_session_result: {+ category: "agent",+ running: "Checking sub-AutoPilot result",+ done: "Sub-AutoPilot result received",+ },+};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.platform.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.platform.tsnew file mode 100644index 0000000000..8ecf454fa2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.platform.ts@@ -0,0 +1,226 @@+import {+ quoted,+ str,+ type ToolInput,+ type ToolMeta,+} from "./toolCatalog.shared";++export const PLATFORM_TOOL_CATALOG: Record<string, ToolMeta> = {+ TodoWrite: {+ category: "todo",+ running: "Updating tasks",+ done: "Updated tasks",+ },+ web_search: {+ category: "web",+ running: "Searching the web for",+ done: "Searched the web for",+ subject: (input) => quoted(input, "query"),+ },+ web_fetch: {+ category: "web",+ running: "Fetching",+ done: "Fetched",+ subject: (input) => quoted(input, "url", 60),+ },+ browser_navigate: {+ category: "browser",+ running: "Opening",+ done: "Opened",+ subject: (input) => quoted(input, "url", 60),+ },+ browser_act: {+ category: "browser",+ running: "Using the browser",+ done: "Used the browser",+ },+ browser_screenshot: {+ category: "browser",+ running: "Taking a screenshot",+ done: "Took a screenshot",+ },+ bash_exec: {+ category: "bash",+ running: "Running command",+ done: "Ran command",+ subject: (input) => quoted(input, "command", 60),+ },+ list_workspace_files: {+ category: "file-list",+ running: "Listing workspace files",+ done: "Listed workspace files",+ },+ read_workspace_file: {+ category: "file-read",+ running: "Reading",+ done: "Read",+ subject: (input) =>+ quoted(input, "path", 60) ?? quoted(input, "filename", 60),+ },+ write_workspace_file: {+ category: "file-write",+ running: "Writing",+ done: "Wrote",+ subject: (input) =>+ quoted(input, "path", 60) ?? quoted(input, "filename", 60),+ },+ delete_workspace_file: {+ category: "file-delete",+ running: "Deleting",+ done: "Deleted",+ subject: (input) =>+ quoted(input, "path", 60) ?? quoted(input, "filename", 60),+ },+ list_schedules: {+ category: "schedule",+ running: "Listing schedules",+ done: "Listed schedules",+ },+ delete_schedule: {+ category: "schedule",+ running: "Deleting schedule",+ done: "Deleted schedule",+ },+ schedule_followup: {+ category: "schedule",+ running: "Scheduling a follow-up",+ done: "Scheduled a follow-up",+ },+ post_to_chat_platform: {+ category: "chat",+ running: "Posting to",+ done: "Posted to",+ subject: (input) => quoted(input, "channel"),+ },+ list_chat_platform_channels: {+ category: "chat",+ running: "Listing chat channels",+ done: "Listed chat channels",+ },+ list_agent_triggers: {+ category: "trigger",+ running: "Listing agent triggers",+ done: "Listed agent triggers",+ },+ setup_agent_webhook_trigger: {+ category: "trigger",+ running: "Setting up webhook trigger",+ done: "Set up webhook trigger",+ },+ list_presets: {+ category: "preset",+ running: "Listing presets",+ done: "Listed presets",+ },+ update_preset: {+ category: "preset",+ running: "Updating preset",+ done: "Updated preset",+ },+ delete_preset: {+ category: "preset",+ running: "Deleting preset",+ done: "Deleted preset",+ },+ run_block: {+ category: "block",+ running: "Running block",+ done: "Ran block",+ subject: (input) =>+ quoted(input, "block_name") ?? quoted(input, "block_id", 20),+ },+ schedule_agent: {+ category: "agent",+ running: "Scheduling agent",+ done: "Scheduled agent",+ },+ continue_run_block: {+ category: "block",+ running: "Continuing block run",+ done: "Continued block run",+ },+ run_mcp_tool: {+ category: "mcp",+ running: "Running MCP tool",+ done: "Ran MCP tool",+ subject: (input) => quoted(input, "tool_name"),+ },+ get_mcp_guide: {+ category: "docs",+ running: "Reading the MCP guide",+ done: "Read the MCP guide",+ },+ search_docs: {+ category: "docs",+ running: "Searching docs for",+ done: "Searched docs for",+ subject: (input) => quoted(input, "query"),+ },+ get_doc_page: {+ category: "docs",+ running: "Reading doc page",+ done: "Read doc page",+ subject: (input) => str(input, "path"),+ },+ store_skill: {+ category: "skill",+ running: "Saving skill",+ done: "Saved skill",+ subject: (input) => quoted(input, "name"),+ },+ read_skill: {+ category: "skill",+ running: "Reading skill",+ done: "Read skill",+ subject: (input) => quoted(input, "name"),+ },+ delete_skill: {+ category: "skill",+ running: "Deleting skill",+ done: "Deleted skill",+ subject: (input) => quoted(input, "name"),+ },+ list_skills: {+ category: "skill",+ running: "Listing skills",+ done: "Listed skills",+ },+ connect_integration: {+ category: "integration",+ running: "Connecting",+ done: "Connected",+ subject: (input) => str(input, "provider"),+ },+ search_feature_requests: {+ category: "feature",+ running: "Searching feature requests for",+ done: "Searched feature requests for",+ subject: (input) => quoted(input, "query"),+ },+ create_feature_request: {+ category: "feature",+ running: "Filing feature request",+ done: "Filed feature request",+ subject: (input) => quoted(input, "title"),+ },+ get_platform_info: {+ category: "info",+ running: "Checking platform info",+ done: "Checked platform info",+ },+ ask_question: {+ category: "question",+ running: "Asking you a question",+ done: "Asked you a question",+ subject: (input) => {+ const direct = quoted(input, "question", 60);+ if (direct) return direct;+ const first = Array.isArray(input.questions)+ ? (input.questions as unknown[])[0]+ : null;+ return first && typeof first === "object"+ ? quoted(first as ToolInput, "question", 60)+ : null;+ },+ },+};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.shared.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.shared.tsnew file mode 100644index 0000000000..0f244b62a4--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.shared.ts@@ -0,0 +1,45 @@+import { type ToolCategory, truncate } from "../../tools/GenericTool/helpers";++export type ChainCategory =+ | ToolCategory+ | "reasoning"+ | "agent-build"+ | "plan"+ | "block"+ | "memory"+ | "folder"+ | "schedule"+ | "trigger"+ | "preset"+ | "chat"+ | "mcp"+ | "docs"+ | "skill"+ | "integration"+ | "feature"+ | "question"+ | "info"+ | "narration";++export type ToolInput = Record<string, unknown>;++export interface ToolMeta {+ category: ChainCategory;+ running: string;+ done: string;+ subject?: (input: ToolInput) => string | null;+}++export function str(input: ToolInput, key: string): string | null {+ const value = input[key];+ return typeof value === "string" && value.trim() ? value.trim() : null;+}++export function quoted(+ input: ToolInput,+ key: string,+ maxLen = 50,+): string | null {+ const value = str(input, key);+ return value ? `"${truncate(value, maxLen)}"` : null;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.tsnew file mode 100644index 0000000000..66d0a536f0--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/toolCatalog.ts@@ -0,0 +1,31 @@+import { AGENT_TOOL_CATALOG } from "./toolCatalog.agent";+import { PLATFORM_TOOL_CATALOG } from "./toolCatalog.platform";+import type { ChainCategory, ToolInput, ToolMeta } from "./toolCatalog.shared";++export type { ChainCategory } from "./toolCatalog.shared";++export const COPILOT_TOOL_CATALOG: Record<string, ToolMeta> = {+ ...AGENT_TOOL_CATALOG,+ ...PLATFORM_TOOL_CATALOG,+};++export function getCatalogLabel(+ toolName: string,+ input: unknown,+ state: "running" | "done" | "error",+): { category: ChainCategory; text: string } | null {+ const meta = COPILOT_TOOL_CATALOG[toolName];+ if (!meta) return null;+ const subject =+ meta.subject?.(+ input && typeof input === "object" ? (input as ToolInput) : {},+ ) ?? null;+ const suffix = subject ? ` ${subject}` : "";+ const text =+ state === "running"+ ? `${meta.running}${suffix}…`+ : state === "error"+ ? `Failed while ${meta.running.charAt(0).toLowerCase()}${meta.running.slice(1)}${suffix}`+ : `${meta.done}${suffix}`;+ return { category: meta.category, text };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/store.tsindex ac9cd684c1..72548bb25d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts@@ -128,6 +128,14 @@ interface CopilotUIState {initialPrompt: string | null;setInitialPrompt: (prompt: string | null) => void;+ /**+ * Bumped every time the composer actually sends a message. Chain action+ * cards draft into the input rather than sending themselves, so this is+ * how they learn their drafted message went out.+ */+ sentMessageCount: number;+ notifyMessageSent: () => void;+/*** Expert ids whose latest thread was already adopted via a* /copilot?expertId= deep link this page load. Lives here — not in@@ -224,6 +232,10 @@ export const useCopilotUIStore = create<CopilotUIState>((set, get) => ({initialPrompt: null,setInitialPrompt: (prompt) => set({ initialPrompt: prompt }),+ sentMessageCount: 0,+ notifyMessageSent: () =>+ set((state) => ({ sentMessageCount: state.sentMessageCount + 1 })),+adoptedExpertThreads: new Set<string>(),markExpertThreadAdopted: (expertId) =>set((state) => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsxindex 888eb7de52..335fbe1623 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx@@ -10,9 +10,10 @@ import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/simport { Button } from "@/components/atoms/Button/Button";import { openOAuthPopup } from "@/lib/oauth-popup";import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";-import { useContext, useEffect, useRef, useState } from "react";+import { useContext, useEffect, useId, useRef, useState } from "react";import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";import { ContentMessage } from "../../../../components/ToolAccordion/AccordionContent";+import { ChainActionsContext } from "../../../../components/ToolChain/chainActions";function normalizeMcpUrl(url: string): string {// Mirrors backend ``normalize_mcp_url`` (helpers.py) so a stored cred@@ -41,6 +42,8 @@ interface Props {export function MCPSetupCard({ output, retryInstruction }: Props) {const { onSend } = useCopilotChatActions();const allProviders = useContext(CredentialsProvidersContext);+ const chainActions = useContext(ChainActionsContext);+ const actionId = useId();// setup_info.agent_id is set to the server_url in the backendconst serverUrl = output.setup_info.agent_id;@@ -226,12 +229,12 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {}}- async function handleManualToken() {+ async function handleManualToken(tokenArg?: string) {// Re-entrancy guard first — mirrors ``handleConnect`` so both flows// present the same shape to readers. See the comment on// ``handleConnect``'s guard for the double-click race this prevents.if (loading) return;- const token = manualToken.trim();+ const token = (tokenArg ?? manualToken).trim();if (!token) return;setLoading(true);setError(null);@@ -266,6 +269,45 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {}}+ // Inside a tool chain the card renders nothing itself — it registers an+ // MCP row with the chain's connectors table and stays mounted (hidden)+ // as the state machine driving that row's callbacks.+ useEffect(() => {+ if (!chainActions) return;+ chainActions.register({+ id: actionId,+ ready: connected,+ buildMessage: () => null,+ mcp: {+ id: actionId,+ service,+ serverUrl,+ connected,+ loading,+ error,+ showManualToken,+ onConnect: handleConnect,+ onUseToken: (token) => {+ setManualToken(token);+ void handleManualToken(token);+ },+ },+ });+ return () => chainActions.unregister(actionId);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- handleConnect/handleManualToken capture latest state each registration+ }, [+ chainActions,+ actionId,+ connected,+ loading,+ error,+ showManualToken,+ serverUrl,+ service,+ ]);++ if (chainActions) return null;+// Already-connected state. Shown when the backend reports// ``has_all_credentials=true`` (model called with// ``surface_connect_card=true`` and creds already exist), or after the@@ -329,7 +371,7 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {<Buttonvariant="secondary"size="small"- onClick={handleManualToken}+ onClick={() => handleManualToken()}disabled={loading || !manualToken.trim()}>Use Tokendiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/clarifying-questions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/clarifying-questions.tsindex 54fe5108d4..4c7c986a93 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/clarifying-questions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/clarifying-questions.ts@@ -36,6 +36,50 @@ export function normalizeClarifyingQuestions(});}+function toRecord(value: unknown): Record<string, unknown> | null {+ if (typeof value === "string") {+ try {+ value = JSON.parse(value);+ } catch {+ return null;+ }+ }+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++function questionItems(value: unknown): Record<string, unknown>[] | null {+ const raw = toRecord(value)?.questions;+ if (!Array.isArray(raw) || raw.length === 0) return null;+ const items = raw.filter(+ (item): item is Record<string, unknown> =>+ !!item && typeof item === "object" && !Array.isArray(item),+ );+ return items.length > 0 ? items : null;+}++export function extractClarifyingQuestions(source: {+ input?: unknown;+ output?: unknown;+}): ClarifyingQuestion[] {+ const raw = questionItems(source.output) ?? questionItems(source.input) ?? [];+ const valid = raw.flatMap((item) =>+ typeof item.question === "string" &&+ item.question.trim() &&+ typeof item.keyword === "string"+ ? [+ {+ question: item.question.trim(),+ keyword: item.keyword,+ example: item.example,+ },+ ]+ : [],+ );+ return normalizeClarifyingQuestions(valid);+}+/*** Formats clarification answers as a context message and sends it via onSend.*/diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex e56164c57a..906f621e90 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -15812,6 +15812,11 @@"type": "array","title": "Required Inputs","description": "List of input fields for this block"+ },+ "provider": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Provider",+ "description": "Integration provider slug when the block uses exactly one provider (e.g. 'google', 'discord'); used for provider icons in the chat UI"}},"type": "object",@@ -15887,6 +15892,10 @@"type": "object","title": "Outputs"},+ "provider": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Provider"+ },"success": { "type": "boolean", "title": "Success", "default": true },"is_dry_run": {"anyOf": [{ "type": "boolean" }, { "type": "null" }],diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsxindex 164d8ec30e..44a0d086da 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx@@ -7,7 +7,10 @@ import {} from "@/lib/autogpt-server-api/types";import { cn } from "@/lib/utils";import { toDisplayName } from "@/providers/agent-credentials/helper";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useState } from "react";import { APIKeyCredentialsModal } from "./components/APIKeyCredentialsModal/APIKeyCredentialsModal";+import { ConnectCredentialDialog } from "./components/ConnectCredentialDialog/ConnectCredentialDialog";import { CredentialsFlatView } from "./components/CredentialsFlatView/CredentialsFlatView";import { CredentialTypeSelector } from "./components/CredentialTypeSelector/CredentialTypeSelector";import { DeleteConfirmationModal } from "./components/DeleteConfirmationModal/DeleteConfirmationModal";@@ -60,6 +63,11 @@ export function CredentialsInput({readOnly,isOptional,});+ const [isConnectDialogOpen, setConnectDialogOpen] = useState(false);+ // The unified connect dialog ships with the new tool UI; off keeps the+ // legacy per-type action flow everywhere.+ const usesConnectDialog =+ useGetFlag(Flag.NEW_TOOL_UI) && variant === "default";if (!isLoaded(hookData)) {return null;@@ -120,7 +128,11 @@ export function CredentialsInput({selectedCredential={selectedCredential}onSelectCredential={handleCredentialSelect}onClearCredential={() => onSelectCredential(undefined)}- onAddCredential={handleActionButtonClick}+ onAddCredential={+ usesConnectDialog+ ? () => setConnectDialogOpen(true)+ : handleActionButtonClick+ }onDeleteCredential={readOnly ? undefined : handleDeleteCredential}actionButtonText={actionButtonText}isOptional={isOptional}@@ -131,6 +143,15 @@ export function CredentialsInput({{!readOnly && (<>+ {usesConnectDialog && (+ <ConnectCredentialDialog+ schema={schema}+ provider={provider}+ displayName={displayName}+ open={isConnectDialogOpen}+ onClose={() => setConnectDialogOpen(false)}+ />+ )}{hasMultipleCredentialTypes && (<CredentialTypeSelectorschema={schema}diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsxindex 5bcd7bd6c5..aa4195dc85 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx@@ -109,6 +109,10 @@ afterEach(() => {cleanup();});+// These cover useCredentialsInput's direct OAuth flow (pre-opened popup,+// abort/supersede handling). variant="node" wires the add-credential button+// straight to that flow; the default variant routes through+// ConnectCredentialDialog instead.describe("CredentialsInput – OAuth flow", () => {it("clears a credential retained from a different transport provider", async () => {const onSelectCredentials = vi.fn();@@ -174,6 +178,7 @@ describe("CredentialsInput – OAuth flow", () => {}}onSelectCredentials={vi.fn()}showTitle+ variant="node"/>,);@@ -209,6 +214,7 @@ describe("CredentialsInput – OAuth flow", () => {schema={baseSchema}onSelectCredentials={vi.fn()}showTitle={false}+ variant="node"/>,);@@ -257,6 +263,7 @@ describe("CredentialsInput – OAuth flow", () => {schema={baseSchema}onSelectCredentials={vi.fn()}showTitle={false}+ variant="node"/>,);@@ -293,6 +300,7 @@ describe("CredentialsInput – OAuth flow", () => {schema={baseSchema}onSelectCredentials={vi.fn()}showTitle={false}+ variant="node"/>,);@@ -329,6 +337,7 @@ describe("CredentialsInput – OAuth flow", () => {schema={baseSchema}onSelectCredentials={vi.fn()}showTitle={false}+ variant="node"/>,);@@ -367,6 +376,7 @@ describe("CredentialsInput – OAuth flow", () => {schema={baseSchema}onSelectCredentials={vi.fn()}showTitle={false}+ variant="node"/>,);@@ -429,6 +439,7 @@ describe("CredentialsInput – OAuth flow", () => {schema={baseSchema}onSelectCredentials={vi.fn()}showTitle={false}+ variant="node"/>,);diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsxnew file mode 100644index 0000000000..2b28b23f86--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx@@ -0,0 +1,102 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { ConnectMethodView } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView";+import {+ AuthType,+ type AuthMethod,+ type ConnectableProvider,+} from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/helpers";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api/types";+import { useConnectCredentialDialog } from "./useConnectCredentialDialog";++const KNOWN_AUTH_METHODS: ReadonlySet<AuthMethod> = new Set(+ Object.values(AuthType),+);++interface Props {+ schema: BlockIOCredentialsSubSchema;+ provider: string;+ displayName: string;+ open: boolean;+ onClose: () => void;+}++/** The onboarding connect flow (logo pair, "Connect AutoGPT to X",+ * method cards with the API-key form inlined) scoped to a single+ * provider — used by CredentialsInput's "Add credential" action so the+ * copilot and the onboarding funnel ask for credentials the same way. */+export function ConnectCredentialDialog({+ schema,+ provider,+ displayName,+ open,+ onClose,+}: Props) {+ const {+ selectedMethod,+ setSelectedMethod,+ apiKeyForm,+ handleApiKeySubmit,+ showContinue,+ isContinueDisabled,+ isConnecting,+ handleContinue,+ reset,+ } = useConnectCredentialDialog({ provider, onConnected: onClose });++ function handleClose() {+ reset();+ onClose();+ }++ const connectable: ConnectableProvider = {+ id: provider,+ name: displayName,+ description: null,+ supportedAuthTypes: (schema.credentials_types ?? []).filter(+ (t): t is AuthMethod => KNOWN_AUTH_METHODS.has(t as AuthMethod),+ ),+ };++ return (+ <Dialog+ styling={{ maxWidth: "30rem" }}+ controlled={{+ isOpen: open,+ set: (next) => {+ if (!next) handleClose();+ },+ }}+ >+ <Dialog.Content>+ <div className="flex flex-col gap-5 pb-2">+ <ConnectMethodView+ provider={connectable}+ selectedMethod={selectedMethod}+ onSelectMethod={setSelectedMethod}+ apiKeyForm={apiKeyForm}+ onApiKeySubmit={handleApiKeySubmit}+ />+ <div className="flex items-center justify-end gap-3">+ <Button variant="secondary" size="small" onClick={handleClose}>+ Cancel+ </Button>+ {showContinue && (+ <Button+ variant="primary"+ size="small"+ disabled={isContinueDisabled}+ loading={isConnecting}+ onClick={handleContinue}+ >+ {isConnecting ? "Connecting…" : "Continue"}+ </Button>+ )}+ </div>+ </div>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsxnew file mode 100644index 0000000000..ea2f094abf--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx@@ -0,0 +1,266 @@+import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api/types";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ConnectCredentialDialog } from "../ConnectCredentialDialog";++vi.mock(+ "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect",+ () => ({ useOAuthConnect: vi.fn() }),+);+vi.mock(+ "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm",+ () => ({ useApiKeyConnectForm: vi.fn() }),+);++vi.mock(+ "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView",+ () => ({+ ConnectMethodView: ({+ provider,+ selectedMethod,+ onSelectMethod,+ }: {+ provider: { id: string; name: string; supportedAuthTypes: string[] };+ selectedMethod: string | null;+ onSelectMethod: (method: string) => void;+ }) => (+ <div data-testid="connect-method-view">+ <span>Connect AutoGPT to {provider.name}</span>+ <span data-testid="auth-methods">+ {provider.supportedAuthTypes.join(",")}+ </span>+ <span data-testid="selected-method">{selectedMethod ?? "none"}</span>+ {provider.supportedAuthTypes.map((method) => (+ <button key={method} onClick={() => onSelectMethod(method)}>+ {`select-${method}`}+ </button>+ ))}+ </div>+ ),+ }),+);++vi.mock("@/components/molecules/Dialog/Dialog", () => {+ function MockDialog({+ children,+ controlled,+ }: {+ children: React.ReactNode;+ controlled?: { isOpen: boolean; set: (open: boolean) => void };+ }) {+ if (!controlled?.isOpen) return null;+ return (+ <div role="dialog">+ <button+ data-testid="dialog-dismiss"+ onClick={() => controlled.set(false)}+ >+ dismiss+ </button>+ {children}+ </div>+ );+ }+ MockDialog.Content = function Content({+ children,+ }: {+ children: React.ReactNode;+ }) {+ return <div>{children}</div>;+ };+ return { Dialog: MockDialog };+});++import { useApiKeyConnectForm } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm";+import { useOAuthConnect } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect";++const mockUseOAuthConnect = useOAuthConnect as unknown as ReturnType<+ typeof vi.fn+>;+const mockUseApiKeyConnectForm = useApiKeyConnectForm as unknown as ReturnType<+ typeof vi.fn+>;++function makeOAuthReturn(overrides: Partial<{ isPending: boolean }> = {}) {+ return {+ connect: vi.fn(),+ isPending: overrides.isPending ?? false,+ };+}++function makeApiKeyReturn(+ overrides: Partial<{ isValid: boolean; isPending: boolean }> = {},+) {+ return {+ form: {+ reset: vi.fn(),+ formState: { isValid: overrides.isValid ?? false },+ handleSubmit: (onValid: (values: unknown) => void) => () =>+ onValid({ title: "Key", apiKey: "sk-123", expiresAt: "" }),+ },+ handleSubmit: vi.fn(),+ isPending: overrides.isPending ?? false,+ };+}++const baseSchema = {+ credentials_provider: ["github"],+ credentials_types: ["api_key", "oauth2"],+} as BlockIOCredentialsSubSchema;++function renderDialog(+ overrides: Partial<React.ComponentProps<typeof ConnectCredentialDialog>> = {},+) {+ const onClose = vi.fn();+ const utils = render(+ <ConnectCredentialDialog+ schema={baseSchema}+ provider="github"+ displayName="GitHub"+ open+ onClose={onClose}+ {...overrides}+ />,+ );+ return { onClose, ...utils };+}++beforeEach(() => {+ vi.clearAllMocks();+ mockUseOAuthConnect.mockReturnValue(makeOAuthReturn());+ mockUseApiKeyConnectForm.mockReturnValue(makeApiKeyReturn());+});++afterEach(cleanup);++describe("ConnectCredentialDialog", () => {+ it("renders nothing while closed", () => {+ renderDialog({ open: false });+ expect(screen.queryByTestId("connect-method-view")).toBeNull();+ });++ it("renders the method view scoped to the provider's known auth methods", () => {+ renderDialog({+ schema: {+ credentials_provider: ["github"],+ credentials_types: ["api_key", "oauth2", "not_a_method"],+ } as unknown as BlockIOCredentialsSubSchema,+ });++ expect(screen.getByText("Connect AutoGPT to GitHub")).toBeDefined();+ expect(screen.getByTestId("auth-methods").textContent).toBe(+ "api_key,oauth2",+ );+ });++ it("disables Continue until a method is selected", () => {+ renderDialog();++ const cont = screen.getByText("Continue").closest("button");+ expect(cont?.disabled).toBe(true);++ fireEvent.click(screen.getByText("select-oauth2"));+ expect(screen.getByTestId("selected-method").textContent).toBe("oauth2");+ expect(screen.getByText("Continue").closest("button")?.disabled).toBe(+ false,+ );+ });++ it("starts the OAuth flow when Continue is clicked with OAuth selected", () => {+ const oauth = makeOAuthReturn();+ mockUseOAuthConnect.mockReturnValue(oauth);+ renderDialog();++ fireEvent.click(screen.getByText("select-oauth2"));+ fireEvent.click(screen.getByText("Continue"));++ expect(oauth.connect).toHaveBeenCalledOnce();+ });++ it("keeps Continue disabled for an invalid API key form", () => {+ mockUseApiKeyConnectForm.mockReturnValue(+ makeApiKeyReturn({ isValid: false }),+ );+ renderDialog();++ fireEvent.click(screen.getByText("select-api_key"));+ expect(screen.getByText("Continue").closest("button")?.disabled).toBe(true);+ });++ it("submits the API key form from Continue once valid", () => {+ const apiKey = makeApiKeyReturn({ isValid: true });+ mockUseApiKeyConnectForm.mockReturnValue(apiKey);+ renderDialog();++ fireEvent.click(screen.getByText("select-api_key"));+ fireEvent.click(screen.getByText("Continue"));++ expect(apiKey.handleSubmit).toHaveBeenCalledWith({+ title: "Key",+ apiKey: "sk-123",+ expiresAt: "",+ });+ });++ it("hides Continue for methods it cannot drive", () => {+ renderDialog({+ schema: {+ credentials_provider: ["github"],+ credentials_types: ["user_password"],+ } as BlockIOCredentialsSubSchema,+ });++ fireEvent.click(screen.getByText("select-user_password"));+ expect(screen.queryByText("Continue")).toBeNull();+ });++ it("shows the connecting state while OAuth is pending", () => {+ mockUseOAuthConnect.mockReturnValue(makeOAuthReturn({ isPending: true }));+ renderDialog();++ expect(screen.getByText("Connecting…")).toBeDefined();+ });++ it("resets the picked method and form on Cancel", () => {+ const apiKey = makeApiKeyReturn();+ mockUseApiKeyConnectForm.mockReturnValue(apiKey);+ const { onClose } = renderDialog();++ fireEvent.click(screen.getByText("select-oauth2"));+ fireEvent.click(screen.getByText("Cancel"));++ expect(onClose).toHaveBeenCalledOnce();+ expect(apiKey.form.reset).toHaveBeenCalledOnce();+ });++ it("resets and closes when the dialog itself is dismissed", () => {+ const apiKey = makeApiKeyReturn();+ mockUseApiKeyConnectForm.mockReturnValue(apiKey);+ const { onClose } = renderDialog();++ fireEvent.click(screen.getByTestId("dialog-dismiss"));++ expect(onClose).toHaveBeenCalledOnce();+ expect(apiKey.form.reset).toHaveBeenCalledOnce();+ });++ it("resets and closes once a connection succeeds", () => {+ const apiKey = makeApiKeyReturn();+ mockUseApiKeyConnectForm.mockReturnValue(apiKey);+ const { onClose } = renderDialog();++ const { onSuccess } = mockUseOAuthConnect.mock.calls[0][0] as {+ onSuccess: () => void;+ };+ act(() => onSuccess());++ expect(onClose).toHaveBeenCalledOnce();+ expect(apiKey.form.reset).toHaveBeenCalledOnce();+ });+});diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.tsnew file mode 100644index 0000000000..95c68a3be4--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts@@ -0,0 +1,62 @@+"use client";++import { useApiKeyConnectForm } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm";+import { useOAuthConnect } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect";+import {+ AuthType,+ type AuthMethod,+} from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/helpers";+import { useState } from "react";++interface Args {+ provider: string;+ onConnected: () => void;+}++export function useConnectCredentialDialog({ provider, onConnected }: Args) {+ const [selectedMethod, setSelectedMethod] = useState<AuthMethod | null>(null);++ const oauth = useOAuthConnect({ provider, onSuccess: handleConnected });+ const apiKey = useApiKeyConnectForm({ provider, onSuccess: handleConnected });++ // The dialog stays mounted while closed, so a half-filled key or a+ // picked method would still be there the next time it opens.+ function reset() {+ setSelectedMethod(null);+ apiKey.form.reset();+ }++ function handleConnected() {+ reset();+ onConnected();+ }++ function handleContinue() {+ if (selectedMethod === AuthType.oauth2) {+ oauth.connect();+ return;+ }+ if (selectedMethod === AuthType.api_key) {+ apiKey.form.handleSubmit(apiKey.handleSubmit)();+ }+ }++ return {+ selectedMethod,+ setSelectedMethod,+ apiKeyForm: apiKey.form,+ handleApiKeySubmit: apiKey.handleSubmit,+ // Continue drives OAuth and the API-key form; the remaining methods+ // only show an unsupported notice.+ showContinue:+ !selectedMethod ||+ selectedMethod === AuthType.oauth2 ||+ selectedMethod === AuthType.api_key,+ isContinueDisabled:+ !selectedMethod ||+ (selectedMethod === AuthType.api_key && !apiKey.form.formState.isValid),+ isConnecting: oauth.isPending || apiKey.isPending,+ handleContinue,+ reset,+ };+}diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/CredentialsFlatView.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/CredentialsFlatView.tsxindex 23dbfecb5c..1a76c598c0 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/CredentialsFlatView.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/CredentialsFlatView.tsx@@ -5,7 +5,9 @@ import {BlockIOCredentialsSubSchema,CredentialsMetaInput,} from "@/lib/autogpt-server-api/types";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { ExclamationTriangleIcon } from "@radix-ui/react-icons";+import { useState } from "react";import { AyrshareConnectButton } from "../AyrshareConnectButton/AyrshareConnectButton";import { CredentialRow } from "../CredentialRow/CredentialRow";import { CredentialsSelect } from "../CredentialsSelect/CredentialsSelect";@@ -19,6 +21,57 @@ type Credential = {is_managed?: boolean;};+function ProviderConnectRow({+ provider,+ displayName,+ actionButtonText,+ onAddCredential,+}: {+ provider: string;+ displayName: string;+ actionButtonText: string;+ onAddCredential: () => void;+}) {+ const src = `/integrations/${provider}.png`;+ const [broken, setBroken] = useState(false);++ return (+ <div className="flex h-14 w-full items-center gap-2.5 rounded-xl bg-neutral-100 px-3">+ {broken ? (+ <div+ aria-hidden+ className="flex size-7 shrink-0 items-center justify-center rounded-md bg-white text-[12px] font-semibold uppercase text-zinc-600"+ >+ {displayName.charAt(0)}+ </div>+ ) : (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={src}+ alt=""+ width={28}+ height={28}+ loading="lazy"+ className="size-7 shrink-0 object-contain"+ onError={() => setBroken(true)}+ />+ )}+ <span className="min-w-0 flex-1 truncate text-[14px] font-medium leading-[22px] text-zinc-800">+ {displayName}+ </span>+ <Button+ variant="primary"+ size="small"+ onClick={onAddCredential}+ className="shrink-0"+ type="button"+ >+ {actionButtonText}+ </Button>+ </div>+ );+}+type Props = {schema: BlockIOCredentialsSubSchema;provider: string;@@ -52,6 +105,7 @@ export function CredentialsFlatView({onAddCredential,onDeleteCredential,}: Props) {+ const isNewToolUI = useGetFlag(Flag.NEW_TOOL_UI);const hasCredentials = credentials.length > 0;// Ayrshare has no user-settable credential — provisioning runs on the// server after the user clicks the Connect Social Media Accounts@@ -65,22 +119,39 @@ export function CredentialsFlatView({<>{showTitle && (<div className="mb-2 flex items-center gap-2">- <Text variant="large-medium" className="flex items-center gap-2">- <span className="inline-flex items-center gap-1">- {displayName} credentials- {isOptional && (- <span className="text-sm font-normal text-gray-500">- (optional)- </span>- )}- {!isOptional && !selectedCredential && (- <span className="inline-flex items-center gap-1 text-red-600">- <ExclamationTriangleIcon className="size-4" />- <span className="text-sm font-normal">required</span>- </span>- )}- </span>- </Text>+ {isNewToolUI ? (+ <Text variant="small" className="flex items-center gap-2">+ <span className="inline-flex items-center gap-1 text-zinc-600">+ {displayName} credentials+ {isOptional && (+ <span className="font-normal text-gray-500">(optional)</span>+ )}+ {!isOptional && !selectedCredential && (+ <span className="inline-flex items-center gap-1 text-red-600">+ <ExclamationTriangleIcon className="size-3.5" />+ <span className="font-normal">required</span>+ </span>+ )}+ </span>+ </Text>+ ) : (+ <Text variant="large-medium" className="flex items-center gap-2">+ <span className="inline-flex items-center gap-1">+ {displayName} credentials+ {isOptional && (+ <span className="text-sm font-normal text-gray-500">+ (optional)+ </span>+ )}+ {!isOptional && !selectedCredential && (+ <span className="inline-flex items-center gap-1 text-red-600">+ <ExclamationTriangleIcon className="size-4" />+ <span className="text-sm font-normal">required</span>+ </span>+ )}+ </span>+ </Text>+ )}{schema.description && (<InformationTooltip description={schema.description} />)}@@ -138,15 +209,24 @@ export function CredentialsFlatView({{showAyrshareConnect && <AyrshareConnectButton className="mt-2" />}</>) : showAddAction ? (- <Button- variant="primary"- size="small"- onClick={onAddCredential}- className="w-fit"- type="button"- >- {actionButtonText}- </Button>+ isNewToolUI ? (+ <ProviderConnectRow+ provider={provider}+ displayName={displayName}+ actionButtonText={actionButtonText}+ onAddCredential={onAddCredential}+ />+ ) : (+ <Button+ variant="primary"+ size="small"+ onClick={onAddCredential}+ className="w-fit"+ type="button"+ >+ {actionButtonText}+ </Button>+ )) : showAyrshareConnect ? (<AyrshareConnectButton className="mt-2" />) : null}diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView.tsxnew file mode 100644index 0000000000..aba82f1ca9--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView.tsx@@ -0,0 +1,207 @@+"use client";++import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";+import type { ApiKeyConnectFormValues } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/schema";+import { UnsupportedNotice } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/UnsupportedNotice";+import {+ AuthType,+ type AuthMethod,+ type ConnectableProvider,+} from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/helpers";+import type { UseFormReturn } from "react-hook-form";+import { InlineApiKeyForm } from "./InlineApiKeyForm";+import {+ GlobeIcon,+ Key01Icon,+ SecurityCheckIcon,+ UserIcon,+} from "@hugeicons/core-free-icons";+import type { IconSvgElement } from "@hugeicons/react";+import { AnimatePresence, domAnimation, LazyMotion, m } from "framer-motion";++interface Props {+ provider: ConnectableProvider;+ selectedMethod: AuthMethod | null;+ onSelectMethod: (method: AuthMethod) => void;+ apiKeyForm: UseFormReturn<ApiKeyConnectFormValues>;+ onApiKeySubmit: (values: ApiKeyConnectFormValues) => void;+}++const METHOD_ORDER: AuthMethod[] = [+ AuthType.oauth2,+ AuthType.api_key,+ AuthType.user_password,+ AuthType.host_scoped,+];++const METHOD_COPY: Record<+ AuthMethod,+ {+ label: string;+ description: string;+ icon: IconSvgElement;+ recommended?: boolean;+ }+> = {+ [AuthType.oauth2]: {+ label: "OAuth",+ description: "One-click secure access.",+ icon: SecurityCheckIcon,+ recommended: true,+ },+ [AuthType.api_key]: {+ label: "API Key",+ description: "Paste your token for a custom setup.",+ icon: Key01Icon,+ },+ [AuthType.user_password]: {+ label: "Username & password",+ description: "Sign in with account credentials.",+ icon: UserIcon,+ },+ [AuthType.host_scoped]: {+ label: "Host",+ description: "Scope credentials to one host.",+ icon: GlobeIcon,+ },+};++// The connect step behind a provider click: logo pair, "Connect AutoGPT+// to X", method radio cards. Form methods expand their inputs inline as+// an accordion; OAuth is driven by the panel footer's Continue.+export function ConnectMethodView({+ provider,+ selectedMethod,+ onSelectMethod,+ apiKeyForm,+ onApiKeySubmit,+}: Props) {+ const methods = METHOD_ORDER.filter((method) =>+ provider.supportedAuthTypes.includes(method),+ );++ return (+ // `m` + a local provider, so this renders both standalone and inside+ // the copilot tool chain's strict LazyMotion, which rejects `motion`.+ <LazyMotion features={domAnimation}>+ <div className="flex flex-col gap-5 pt-2">+ <div className="flex items-center justify-center gap-6">+ <span className="relative flex h-20 w-20 items-center justify-center rounded-full bg-white shadow-[0_8px_24px_rgba(0,0,0,0.08)] ring-1 ring-zinc-100">+ <AutoGPTLogo+ hideText+ className="absolute left-1/2 top-1/2 h-8 w-[4.4rem] -translate-x-[77%] -translate-y-1/2"+ />+ </span>+ <span aria-hidden className="grid grid-cols-3 gap-1.5">+ {Array.from({ length: 9 }, (_, dot) => (+ <span+ key={dot}+ className="h-1 w-1 rounded-full bg-[#5b21b6]/30"+ />+ ))}+ </span>+ <span className="flex h-20 w-20 items-center justify-center rounded-full bg-white shadow-[0_8px_24px_rgba(0,0,0,0.08)] ring-1 ring-zinc-100">+ <ProviderAvatar id={provider.id} name={provider.name} />+ </span>+ </div>++ <div className="flex flex-col gap-1.5 text-center">+ <Text variant="h3" className="!text-[1.25rem] text-zinc-900">+ Connect AutoGPT to {provider.name}+ </Text>+ <Text variant="body" className="!text-zinc-500">+ Choose how you'd like to connect your {provider.name} account.+ </Text>+ </div>++ <div className="flex flex-col gap-1 rounded-2xl bg-neutral-100 p-1.5">+ {methods.map((method) => {+ const copy = METHOD_COPY[method];+ const isSelected = selectedMethod === method;+ const hasInlineForm = method !== AuthType.oauth2;+ return (+ <div+ key={method}+ className={isSelected ? "rounded-xl bg-white shadow-sm" : ""}+ >+ <button+ type="button"+ onClick={() => onSelectMethod(method)}+ className={+ isSelected+ ? "flex w-full items-center gap-3 rounded-xl p-3 text-left"+ : "flex w-full items-center gap-3 rounded-xl p-3 text-left transition-colors hover:bg-white/60"+ }+ >+ <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-white shadow-sm">+ <Icon+ icon={copy.icon}+ size={22}+ className="text-zinc-700"+ />+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="flex items-center gap-2">+ <span className="text-sm font-semibold text-zinc-900">+ {copy.label}+ </span>+ {copy.recommended && (+ <span className="rounded-md bg-violet-100 px-1.5 py-0.5 text-[10px] font-semibold tracking-wide text-violet-700">+ RECOMMENDED+ </span>+ )}+ </span>+ <span className="text-xs text-zinc-500">+ {copy.description}+ </span>+ </span>+ <span+ aria-hidden+ className={+ isSelected+ ? "flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 border-violet-600"+ : "h-5 w-5 shrink-0 rounded-full border-2 border-zinc-200"+ }+ >+ {isSelected && (+ <span className="h-2.5 w-2.5 rounded-full bg-violet-600" />+ )}+ </span>+ </button>+ {/* Form methods open in place: the card grows to reveal the+ inputs, submit included — no separate step. */}+ <AnimatePresence initial={false}>+ {isSelected && hasInlineForm && (+ <m.div+ key="form"+ initial={{ height: 0, opacity: 0 }}+ animate={{ height: "auto", opacity: 1 }}+ exit={{ height: 0, opacity: 0 }}+ transition={{ duration: 0.25, ease: [0, 0, 0.2, 1] }}+ className="overflow-hidden"+ >+ <div className="px-3 pb-3">+ {method === AuthType.api_key ? (+ <InlineApiKeyForm+ form={apiKeyForm}+ providerName={provider.name}+ onSubmit={onApiKeySubmit}+ />+ ) : (+ <UnsupportedNotice providerName={provider.name} />+ )}+ </div>+ </m.div>+ )}+ </AnimatePresence>+ </div>+ );+ })}+ </div>+ </div>+ </LazyMotion>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/InlineApiKeyForm.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/InlineApiKeyForm.tsxsimilarity index 100%rename from autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/InlineApiKeyForm.tsxrename to autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/InlineApiKeyForm.tsxdiff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.tsindex 528799f589..02732d5c53 100644--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts@@ -32,6 +32,7 @@ export enum Flag {// Mirror of the backend ``Flag`` enum — the endpoints 404 when off, so// both sides must agree. Off renders the pillbox flow untouched.ONBOARDING_BRAIN_DUMP = "onboarding-brain-dump",+ NEW_TOOL_UI = "new-tool-ui",// Graphiti memory + dream-system gates. Mirror of the backend// ``Flag`` enum in ``backend/util/feature_flag.py``. Frontend reads// them when memory/dream-related UI surfaces ship (P6+ on the@@ -79,6 +80,7 @@ const defaultFlags = {// brain dump for everyone — which is what the backend 404s are meant to// prevent. Use NEXT_PUBLIC_FORCE_FLAG_ONBOARDING_BRAIN_DUMP locally.[Flag.ONBOARDING_BRAIN_DUMP]: false,+ [Flag.NEW_TOOL_UI]: false,[Flag.GRAPHITI_MEMORY]: false,[Flag.GRAPHITI_COMMUNITIES_ENABLED]: false,[Flag.DREAM_PASS_ENABLED]: false,@@ -144,6 +146,8 @@ function readEnvOverride(flag: Flag): string | undefined {return process.env.NEXT_PUBLIC_FORCE_FLAG_SETTINGS_NOTIFICATIONS;case Flag.ONBOARDING_BRAIN_DUMP:return process.env.NEXT_PUBLIC_FORCE_FLAG_ONBOARDING_BRAIN_DUMP;+ case Flag.NEW_TOOL_UI:+ return process.env.NEXT_PUBLIC_FORCE_FLAG_NEW_TOOL_UI;case Flag.GRAPHITI_MEMORY:return process.env.NEXT_PUBLIC_FORCE_FLAG_GRAPHITI_MEMORY;case Flag.GRAPHITI_COMMUNITIES_ENABLED:@@ -170,12 +174,23 @@ const ARRAY_TYPED_FLAGS: ReadonlySet<Flag> = new Set([Flag.COPILOT_BOT_PLATFORMS,]);+// Master local-dev switch: ``NEXT_PUBLIC_FORCE_ALL_FLAGS=true`` turns every+// boolean flag on without listing them individually. A per-flag+// ``NEXT_PUBLIC_FORCE_FLAG_<NAME>`` still wins, so one flag can be excluded+// with ``=false`` while the rest stay forced. Array/JSON-typed flags keep+// their LaunchDarkly / default values.+const isForceAllFlags = ["1", "true", "yes", "on"].includes(+ (process.env.NEXT_PUBLIC_FORCE_ALL_FLAGS ?? "").trim().toLowerCase(),+);+export function envFlagOverride<T extends Flag>(flag: T,): FlagValues[T] | undefined {if (ARRAY_TYPED_FLAGS.has(flag)) return undefined;const raw = readEnvOverride(flag);- if (raw === undefined) return undefined;+ if (raw === undefined) {+ return isForceAllFlags ? (true as FlagValues[T]) : undefined;+ }const normalized = raw.trim().toLowerCase();if (["1", "true", "yes", "on"].includes(normalized)) {return true as FlagValues[T];@@ -183,7 +198,7 @@ export function envFlagOverride<T extends Flag>(if (["0", "false", "no", "off"].includes(normalized)) {return false as FlagValues[T];}- return undefined;+ return isForceAllFlags ? (true as FlagValues[T]) : undefined;}export function useGetFlag<T extends Flag>(flag: T): FlagValues[T] {diff --git a/autogpt_platform/frontend/tailwind.config.ts b/autogpt_platform/frontend/tailwind.config.tsindex e513f33a1e..ee1ff6a8f8 100644--- a/autogpt_platform/frontend/tailwind.config.ts+++ b/autogpt_platform/frontend/tailwind.config.ts@@ -252,6 +252,22 @@ const config = {"0%": { transform: "translateX(-100%)" },"100%": { transform: "translateX(400%)" },},+ "caret-blink": {+ "0%, 100%": { opacity: "1" },+ "50%": { opacity: "0" },+ },+ "shimmer-text": {+ "0%": { backgroundPosition: "100% 0" },+ "100%": { backgroundPosition: "0% 0" },+ },+ "fade-up": {+ from: { opacity: "0", transform: "translateY(6px)" },+ to: { opacity: "1", transform: "translateY(0)" },+ },+ "grow-line": {+ from: { transform: "scaleY(0)" },+ to: { transform: "scaleY(1)" },+ },},animation: {"accordion-down": "accordion-down 0.2s ease-out",@@ -270,10 +286,19 @@ const config = {"marquee-x": "marquee-x 40s linear infinite","progress-bar":"progress-bar 1.4s cubic-bezier(0.65, 0, 0.35, 1) infinite",+ "caret-blink": "caret-blink 1s step-end infinite",+ "shimmer-text": "shimmer-text 2s linear infinite",+ "fade-up": "fade-up 320ms cubic-bezier(0.23, 1, 0.32, 1) both",+ "grow-line": "grow-line 500ms cubic-bezier(0.23, 1, 0.32, 1) both",},transitionDuration: {+ "400": "400ms","2000": "2000ms",},+ transitionTimingFunction: {+ // easeOutQuint — long, soft settle for accordion expand/collapse.+ "out-quint": "cubic-bezier(0.23, 1, 0.32, 1)",+ },},},plugins: [diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.mdindex b53abcbbc9..31a90f0804 100644--- a/docs/integrations/block-integrations/misc.md+++ b/docs/integrations/block-integrations/misc.md@@ -58,7 +58,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run| system_context | Optional additional context prepended to the prompt. Use this to constrain autopilot behavior, provide domain context, or set output format requirements. | str | No || session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No || max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |-| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_soul_update" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "enter_agent_building_mode" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "post_to_chat_platform" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "store_skill" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_soul_update" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "enter_agent_building_mode" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "post_to_chat_platform" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "store_skill" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No || tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No || blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No || blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |