Skip to content

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

feat(copilot): add goal decomposition step before agent building (#12731)

An Vy Le708d81504052
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index ab2af2a3d4..7ce2df7abe 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -96,6 +96,7 @@ from backend.copilot.tools.models import (
NoResultsResponse,
SetupRequirementsResponse,
SuggestedGoalResponse,
+ TaskDecompositionResponse,
TodoWriteResponse,
UnderstandingUpdatedResponse,
)
@@ -1652,6 +1653,7 @@ ToolResponseUnion = (
| DocPageResponse
| MCPToolsDiscoveredResponse
| MCPToolOutputResponse
+ | TaskDecompositionResponse
| ScheduleListResponse
| ScheduleDeletedResponse
| MemoryStoreResponse
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index 2eec69275a..20b920fdf3 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -81,6 +81,7 @@ ToolName = Literal[
"create_feature_request",
"create_folder",
"customize_agent",
+ "decompose_goal",
"delete_folder",
"delete_schedule",
"delete_skill",
diff --git a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
index 2afedddc30..42f9cf89e0 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
+++ b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
@@ -3,6 +3,59 @@
You can create, edit, and customize agents directly. You ARE the brain —
generate the agent JSON yourself using block schemas, then validate and save.
+### Clarifying — Before or During Building
+
+Use `ask_question` whenever the user's intent is ambiguous — whether
+that's before starting or midway through the workflow. Common moments:
+
+- **Before building**: output format, delivery channel, data source, or
+ trigger is unspecified.
+- **During block discovery**: multiple blocks could fit and the user
+ should choose.
+- **During JSON generation**: a wiring decision depends on user
+ preference.
+
+Steps:
+1. Call `find_block` (or another discovery tool) to learn what the
+ platform actually supports for the ambiguous dimension.
+2. Call `ask_question` with a concrete question listing the discovered
+ options (e.g. "The platform supports Gmail, Slack, and Google Docs —
+ which should the agent use for delivery?").
+3. **Wait for the user's answer** before continuing.
+
+**Skip this** when the goal already specifies all dimensions (e.g.
+"scrape prices from Amazon and email me daily").
+
+### Before Building: Show the Plan
+
+Start agent generation by calling `decompose_goal` once to display your
+build plan to the user as a step-by-step UI card.
+
+1. Analyze the user's request and break it into plain-English steps
+ describing **what the agent will do for the user**, not which blocks
+ you will add or how they connect. For a YouTube summarizer that
+ might be: "Accept a YouTube URL from the user", "Fetch the video's
+ transcript", "Generate a timestamped summary", "Return the summary
+ to the user".
+2. Call `decompose_goal` with those steps. Do not write any text before
+ or after the tool call — the platform renders the plan UI card
+ automatically, so any extra text duplicates the display.
+3. Continue immediately with the workflow below in the same turn. The
+ plan card is informational only — there is no approval step, no
+ countdown, and no need to wait for the user.
+
+The `description` is user-facing and must read as plain English to a
+non-technical user. The platform records the block name and action on
+the same step via the separate `block_name` and `action` fields — those
+fields carry the technical detail. Do not put block class names
+("AgentInputBlock", "AgentOutputBlock", "TranscribeYoutubeVideoBlock"),
+internal types, or wiring verbs ("wire", "connect", "link") inside
+`description`.
+
+For simple goals (1-2 blocks), keep steps brief (2-3 steps).
+For complex goals, use as many steps as needed.
+
+
### Workflow for Creating/Editing Agents
1. **If creating a new agent from a user goal (REQUIRED before `create_agent`)**:
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index 7b5bf166c5..0a7a29aeb6 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -17,6 +17,7 @@ from .connect_integration import ConnectIntegrationTool
from .continue_run_block import ContinueRunBlockTool
from .create_agent import CreateAgentTool
from .customize_agent import CustomizeAgentTool
+from .decompose_goal import DecomposeGoalTool
from .edit_agent import EditAgentTool
from .feature_requests import CreateFeatureRequestTool, SearchFeatureRequestsTool
from .find_agent import FindAgentTool
@@ -70,6 +71,7 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"add_understanding": AddUnderstandingTool(),
"create_agent": CreateAgentTool(),
"customize_agent": CustomizeAgentTool(),
+ "decompose_goal": DecomposeGoalTool(),
"edit_agent": EditAgentTool(),
"find_agent": FindAgentTool(),
"find_block": FindBlockTool(),
diff --git a/autogpt_platform/backend/backend/copilot/tools/decompose_goal.py b/autogpt_platform/backend/backend/copilot/tools/decompose_goal.py
new file mode 100644
index 0000000000..018cb5137b
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/decompose_goal.py
@@ -0,0 +1,141 @@
+"""DecomposeGoalTool - Breaks agent-building goals into sub-instructions."""
+
+import logging
+from typing import Any
+
+from backend.copilot.model import ChatSession
+
+from .base import BaseTool
+from .models import (
+ DecompositionStepModel,
+ ErrorResponse,
+ TaskDecompositionResponse,
+ ToolResponseBase,
+)
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_ACTION = "add_block"
+VALID_ACTIONS = {"add_block", "connect_blocks", "configure", "add_input", "add_output"}
+
+
+class DecomposeGoalTool(BaseTool):
+ """Tool for decomposing an agent goal into sub-instructions."""
+
+ @property
+ def name(self) -> str:
+ return "decompose_goal"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Show the user a plain-English plan of what the agent will do, "
+ "as a step-by-step card before constructing it. Display-only — "
+ "the build continues in the same turn without pausing for user "
+ "input."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "goal": {
+ "type": "string",
+ "description": "The user's agent-building goal.",
+ },
+ "steps": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "description": {
+ "type": "string",
+ "description": (
+ "Plain-English description of what "
+ "this step does for the user. Do not "
+ "put block class names or wiring verbs "
+ "here — block_name and action carry "
+ "that technical detail."
+ ),
+ },
+ "action": {
+ "type": "string",
+ "description": (
+ "Action type: 'add_block', 'connect_blocks', "
+ "'configure', 'add_input', 'add_output'."
+ ),
+ "enum": list(VALID_ACTIONS),
+ },
+ "block_name": {
+ "type": "string",
+ "description": "Block name if adding a block.",
+ },
+ },
+ "required": ["description", "action"],
+ },
+ "description": "List of sub-instructions for the plan.",
+ },
+ },
+ "required": ["goal", "steps"],
+ }
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ goal: str | None = None,
+ steps: list[Any] | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id if session else None
+
+ if not goal:
+ return ErrorResponse(
+ message="Please provide a goal to decompose.",
+ error="missing_goal",
+ session_id=session_id,
+ )
+
+ if not steps:
+ return ErrorResponse(
+ message="Please provide at least one step in the plan.",
+ error="missing_steps",
+ session_id=session_id,
+ )
+
+ decomposition_steps: list[DecompositionStepModel] = []
+ for i, step in enumerate(steps):
+ if not isinstance(step, dict):
+ return ErrorResponse(
+ message=f"Step {i + 1} is malformed — expected an object.",
+ error="invalid_step",
+ session_id=session_id,
+ )
+ description = step.get("description", "")
+ if not description or not description.strip():
+ return ErrorResponse(
+ message=f"Step {i + 1} is missing a description.",
+ error="empty_description",
+ session_id=session_id,
+ )
+ action = step.get("action", DEFAULT_ACTION)
+ if action not in VALID_ACTIONS:
+ action = DEFAULT_ACTION
+ decomposition_steps.append(
+ DecompositionStepModel(
+ step_id=f"step_{i + 1}",
+ description=description,
+ action=action,
+ block_name=step.get("block_name"),
+ status="pending",
+ )
+ )
+
+ return TaskDecompositionResponse(
+ message=f"Here's the plan to build your agent ({len(decomposition_steps)} steps):",
+ goal=goal,
+ steps=decomposition_steps,
+ step_count=len(decomposition_steps),
+ session_id=session_id,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/decompose_goal_test.py b/autogpt_platform/backend/backend/copilot/tools/decompose_goal_test.py
new file mode 100644
index 0000000000..9f9dc746c4
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/decompose_goal_test.py
@@ -0,0 +1,249 @@
+"""Unit tests for DecomposeGoalTool."""
+
+import pytest
+
+from ._test_data import make_session
+from .decompose_goal import DEFAULT_ACTION, DecomposeGoalTool
+from .models import ErrorResponse, TaskDecompositionResponse
+
+_USER_ID = "test-user-decompose-goal"
+
+_VALID_STEPS = [
+ {"description": "Accept a topic from the user", "action": "add_input"},
+ {
+ "description": "Summarize the topic with AI",
+ "action": "add_block",
+ "block_name": "AI Text Generator",
+ },
+ {"description": "Hand the result back to the user", "action": "connect_blocks"},
+]
+
+
+def tool() -> DecomposeGoalTool:
+ return DecomposeGoalTool()
+
+
+def session():
+ return make_session(_USER_ID)
+
+
+# ---------------------------------------------------------------------------
+# Happy path
+# ---------------------------------------------------------------------------
+
+
+async def test_happy_path(tool: DecomposeGoalTool, session):
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build a news summarizer agent",
+ steps=_VALID_STEPS,
+ )
+
+ assert isinstance(result, TaskDecompositionResponse)
+ assert result.goal == "Build a news summarizer agent"
+ assert len(result.steps) == 3
+ assert result.step_count == 3
+ assert result.steps[0].step_id == "step_1"
+ assert result.steps[0].description == "Accept a topic from the user"
+ assert result.steps[1].block_name == "AI Text Generator"
+
+
+async def test_step_count_matches_steps(tool: DecomposeGoalTool, session):
+ """TaskDecompositionResponse.step_count must always equal len(steps)."""
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Simple agent",
+ steps=[{"description": "Only step", "action": "add_block"}],
+ )
+ assert isinstance(result, TaskDecompositionResponse)
+ assert result.step_count == len(result.steps)
+
+
+async def test_invalid_action_defaults_to_add_block(tool: DecomposeGoalTool, session):
+ """Unknown action values are coerced to DEFAULT_ACTION."""
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build agent",
+ steps=[{"description": "Do something weird", "action": "fly_to_moon"}],
+ )
+ assert isinstance(result, TaskDecompositionResponse)
+ assert result.steps[0].action == DEFAULT_ACTION
+
+
+async def test_block_name_optional(tool: DecomposeGoalTool, session):
+ """Steps without block_name should succeed with block_name=None."""
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Agent with no block name",
+ steps=[{"description": "Configure the agent", "action": "configure"}],
+ )
+ assert isinstance(result, TaskDecompositionResponse)
+ assert result.steps[0].block_name is None
+
+
+# ---------------------------------------------------------------------------
+# Validation — missing inputs
+# ---------------------------------------------------------------------------
+
+
+async def test_missing_goal_returns_error(tool: DecomposeGoalTool, session):
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal=None,
+ steps=_VALID_STEPS,
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "missing_goal"
+
+
+async def test_empty_goal_returns_error(tool: DecomposeGoalTool, session):
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="",
+ steps=_VALID_STEPS,
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "missing_goal"
+
+
+async def test_missing_steps_returns_error(tool: DecomposeGoalTool, session):
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build agent",
+ steps=None,
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "missing_steps"
+
+
+async def test_empty_steps_returns_error(tool: DecomposeGoalTool, session):
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build agent",
+ steps=[],
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "missing_steps"
+
+
+# ---------------------------------------------------------------------------
+# Validation — malformed step items
+# ---------------------------------------------------------------------------
+
+
+async def test_non_dict_step_returns_error(tool: DecomposeGoalTool, session):
+ """A step that is not a dict should return an error."""
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build agent",
+ steps=["not a dict"], # type: ignore[list-item]
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "invalid_step"
+
+
+async def test_step_with_empty_description_returns_error(
+ tool: DecomposeGoalTool, session
+):
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build agent",
+ steps=[{"description": "", "action": "add_block"}],
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "empty_description"
+
+
+async def test_step_with_missing_description_returns_error(
+ tool: DecomposeGoalTool, session
+):
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build agent",
+ steps=[{"action": "add_block"}],
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "empty_description"
+
+
+# ---------------------------------------------------------------------------
+# ID generation
+# ---------------------------------------------------------------------------
+
+
+async def test_step_ids_are_sequential(tool: DecomposeGoalTool, session):
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build agent",
+ steps=_VALID_STEPS,
+ )
+ assert isinstance(result, TaskDecompositionResponse)
+ for i, step in enumerate(result.steps):
+ assert step.step_id == f"step_{i + 1}"
+
+
+# ---------------------------------------------------------------------------
+# Description / block_name separation of concerns
+# ---------------------------------------------------------------------------
+
+
+async def test_plain_english_description_with_technical_block_name(
+ tool: DecomposeGoalTool, session
+):
+ """A plain-English description paired with a technical block_name must
+ round-trip without either field bleeding into the other.
+
+ The decomposition card is shown to non-technical users; the prompt
+ instructs the LLM to keep block class names out of ``description`` and
+ put them in ``block_name`` instead. This test pins that separation —
+ if a future refactor ever merges the two fields or starts mutating
+ ``description``, it will fail here before reaching production.
+ """
+ plain_english = "Fetch the video's transcript"
+ technical_name = "Transcribe Youtube Video"
+
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ goal="Build a YouTube summarizer",
+ steps=[
+ {
+ "description": plain_english,
+ "action": "add_block",
+ "block_name": technical_name,
+ }
+ ],
+ )
+
+ assert isinstance(result, TaskDecompositionResponse)
+ step = result.steps[0]
+ assert step.description == plain_english
+ assert step.block_name == technical_name
+ assert technical_name not in step.description
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index bbe0d23a00..77dbf5dc91 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -4,7 +4,7 @@ from datetime import datetime
from enum import Enum
from typing import Any, Literal
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, model_validator
from backend.data.graph import BaseGraph
from backend.data.model import CredentialsMetaInput
@@ -36,6 +36,9 @@ class ResponseType(str, Enum):
AGENT_BUILDER_VALIDATION_RESULT = "agent_builder_validation_result"
AGENT_BUILDER_FIX_RESULT = "agent_builder_fix_result"
+ # Task decomposition (goal → sub-instructions)
+ TASK_DECOMPOSITION = "task_decomposition"
+
# Block
BLOCK_LIST = "block_list"
BLOCK_DETAILS = "block_details"
@@ -839,6 +842,48 @@ class AgentsMovedToFolderResponse(ToolResponseBase):
count: int = 0
+# Task decomposition models
+
+
+class DecompositionStepModel(BaseModel):
+ """A single step in a decomposed agent-building plan."""
+
+ step_id: str = Field(description="Unique step identifier, e.g. 'step_1'")
+ description: str = Field(
+ description=(
+ "Plain-English description of what this step does for the user. "
+ "Do not put block class names or wiring verbs here — block_name "
+ "and action carry that technical detail."
+ )
+ )
+ action: str = Field(
+ description="Action type: 'add_block', 'connect_blocks', 'configure', etc."
+ )
+ block_name: str | None = Field(
+ default=None, description="Block being added, if applicable"
+ )
+ status: str = Field(
+ default="pending",
+ description="Step status: pending, in_progress, completed, failed",
+ )
+
+
+class TaskDecompositionResponse(ToolResponseBase):
+ """Response for decompose_goal tool — shows the plan to the user."""
+
+ type: ResponseType = ResponseType.TASK_DECOMPOSITION
+ goal: str = Field(description="The original user goal")
+ steps: list[DecompositionStepModel]
+ step_count: int = Field(
+ default=0, description="Number of steps (auto-derived from steps list)"
+ )
+
+ @model_validator(mode="after")
+ def sync_step_count(self) -> "TaskDecompositionResponse":
+ self.step_count = len(self.steps)
+ return self
+
+
# --- Graphiti memory responses ---
diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
index 97d79d08e6..d053d95fda 100644
--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
@@ -65,7 +65,12 @@ from backend.copilot.tools import TOOL_REGISTRY
# extra ~270 chars on CI (env-flagged tool registrations push CI
# higher than local) carry the LLM-decision-critical copy for
# "search the library before building new" + "user-confirmed bypass".
-_CHAR_BUDGET = 39_500
+# Bumped 39500 -> 40500 on PR #12731 for the decompose_goal tool.
+# Adds ~1k chars: step-level schema (id/description/action/block_name),
+# the require_approval gate, and the "STOP before building" caveat the
+# model needs to halt for user approval instead of rushing into
+# create_agent.
+_CHAR_BUDGET = 40_500
@pytest.fixture(scope="module")
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
index 3348be6017..e168d7fc05 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
@@ -1,9 +1,13 @@
import { describe, expect, it } from "vitest";
import {
WORKSPACE_FILE_PATTERN,
+ buildRenderSegments,
extractWorkspaceArtifacts,
filePartToArtifactRef,
+ isCompletedToolPart,
+ isInteractiveToolPart,
isReasoningToolPart,
+ parseSpecialMarkers,
resolveWorkspaceUrls,
splitReasoningAndResponse,
} from "../helpers";
@@ -21,6 +25,7 @@ function reasoningPart(text: string): MessagePart {
function toolPart(
toolName: string,
state: string = "output-available",
+ output: unknown = "{}",
): MessagePart {
return {
type: `tool-${toolName}`,
@@ -28,7 +33,7 @@ function toolPart(
toolCallId: `call-${toolName}`,
toolName,
args: {},
- output: "{}",
+ output,
} as unknown as MessagePart;
}
@@ -46,6 +51,222 @@ function interactiveToolPart(
} as unknown as MessagePart;
}
+describe("isCompletedToolPart", () => {
+ it("returns true for output-available tool part", () => {
+ const part = toolPart("some_tool", "output-available");
+ expect(isCompletedToolPart(part)).toBe(true);
+ });
+
+ it("returns true for output-error tool part", () => {
+ const part = toolPart("some_tool", "output-error");
+ expect(isCompletedToolPart(part)).toBe(true);
+ });
+
+ it("returns false for input-streaming tool part", () => {
+ const part = toolPart("some_tool", "input-streaming");
+ expect(isCompletedToolPart(part)).toBe(false);
+ });
+
+ it("returns false for text part", () => {
+ const part = textPart("hello");
+ expect(isCompletedToolPart(part)).toBe(false);
+ });
+});
+
+describe("isInteractiveToolPart", () => {
+ it("returns true for task_decomposition type", () => {
+ const part = toolPart("decompose_goal", "output-available", {
+ type: "task_decomposition",
+ message: "Plan",
+ goal: "Build agent",
+ steps: [],
+ step_count: 0,
+ });
+ expect(isInteractiveToolPart(part)).toBe(true);
+ });
+
+ it("returns true for setup_requirements type", () => {
+ const part = toolPart("run_mcp_tool", "output-available", {
+ type: "setup_requirements",
+ message: "Setup needed",
+ });
+ expect(isInteractiveToolPart(part)).toBe(true);
+ });
+
+ it("returns true for agent_details type", () => {
+ const part = toolPart("find_agent", "output-available", {
+ type: "agent_details",
+ });
+ expect(isInteractiveToolPart(part)).toBe(true);
+ });
+
+ it("returns false for non-interactive output type", () => {
+ const part = toolPart("some_tool", "output-available", {
+ type: "generic_output",
+ });
+ expect(isInteractiveToolPart(part)).toBe(false);
+ });
+
+ it("returns false when state is not output-available", () => {
+ const part = toolPart("decompose_goal", "input-streaming", {
+ type: "task_decomposition",
+ });
+ expect(isInteractiveToolPart(part)).toBe(false);
+ });
+
+ it("returns false for non-tool parts", () => {
+ const part = textPart("hello");
+ expect(isInteractiveToolPart(part)).toBe(false);
+ });
+
+ it("returns false when output is null", () => {
+ const part = toolPart("decompose_goal", "output-available", null);
+ expect(isInteractiveToolPart(part)).toBe(false);
+ });
+
+ it("handles JSON-encoded string output", () => {
+ const part = toolPart(
+ "decompose_goal",
+ "output-available",
+ JSON.stringify({ type: "task_decomposition" }),
+ );
+ expect(isInteractiveToolPart(part)).toBe(true);
+ });
+
+ it("returns false for invalid JSON string output", () => {
+ const part = toolPart(
+ "decompose_goal",
+ "output-available",
+ "not valid json",
+ );
+ expect(isInteractiveToolPart(part)).toBe(false);
+ });
+});
+
+describe("buildRenderSegments", () => {
+ it("returns individual segments for custom tool types", () => {
+ const parts = [
+ toolPart("decompose_goal", "output-available", {
+ type: "task_decomposition",
+ }),
+ ];
+ const segments = buildRenderSegments(parts);
+ expect(segments).toHaveLength(1);
+ expect(segments[0].kind).toBe("part");
+ });
+
+ it("collapses consecutive generic completed tool parts", () => {
+ const parts = [
+ toolPart("unknown_tool_a", "output-available"),
+ toolPart("unknown_tool_b", "output-available"),
+ ];
+ const segments = buildRenderSegments(parts);
+ expect(segments).toHaveLength(1);
+ expect(segments[0].kind).toBe("collapsed-group");
+ if (segments[0].kind === "collapsed-group") {
+ expect(segments[0].parts).toHaveLength(2);
+ }
+ });
+
+ it("does not collapse custom tool types into groups", () => {
+ const parts = [
+ toolPart("decompose_goal", "output-available", {
+ type: "task_decomposition",
+ }),
+ toolPart("create_agent", "output-available"),
+ ];
+ const segments = buildRenderSegments(parts);
+ expect(segments).toHaveLength(2);
+ expect(segments[0].kind).toBe("part");
+ expect(segments[1].kind).toBe("part");
+ });
+
+ it("renders text parts individually", () => {
+ const parts = [textPart("Hello"), textPart("World")];
+ const segments = buildRenderSegments(parts);
+ expect(segments).toHaveLength(2);
+ expect(segments.every((s) => s.kind === "part")).toBe(true);
+ });
+
+ it("handles mixed custom tools, generic tools, and text", () => {
+ const parts = [
+ textPart("Plan:"),
+ toolPart("decompose_goal", "output-available"),
+ toolPart("generic_a", "output-available"),
+ toolPart("generic_b", "output-available"),
+ textPart("Done"),
+ ];
+ const segments = buildRenderSegments(parts);
+
+ expect(segments[0].kind).toBe("part");
+ expect(segments[1].kind).toBe("part");
+ expect(segments[2].kind).toBe("collapsed-group");
+ expect(segments[3].kind).toBe("part");
+ });
+
+ it("does not collapse a single generic tool part", () => {
+ const parts = [toolPart("generic_a", "output-available")];
+ const segments = buildRenderSegments(parts);
+ expect(segments).toHaveLength(1);
+ expect(segments[0].kind).toBe("part");
+ });
+
+ it("preserves baseIndex offset in part segments", () => {
+ const parts = [textPart("Hello")];
+ const segments = buildRenderSegments(parts, 5);
+ expect(segments).toHaveLength(1);
+ if (segments[0].kind === "part") {
+ expect(segments[0].index).toBe(5);
+ }
+ });
+});
+
+describe("parseSpecialMarkers", () => {
+ it("returns null marker for plain text", () => {
+ const result = parseSpecialMarkers("Hello world");
+ expect(result.markerType).toBeNull();
+ expect(result.cleanText).toBe("Hello world");
+ });
+
+ it("detects error marker", () => {
+ const result = parseSpecialMarkers(
+ "Some preamble [__COPILOT_ERROR_f7a1__] Something went wrong",
+ );
+ expect(result.markerType).toBe("error");
+ expect(result.markerText).toBe("Something went wrong");
+ });
+
+ it("detects retryable error marker", () => {
+ const result = parseSpecialMarkers(
+ "[__COPILOT_RETRYABLE_ERROR_a9c2__] Timeout reached",
+ );
+ expect(result.markerType).toBe("retryable_error");
+ expect(result.markerText).toBe("Timeout reached");
+ });
+
+ it("detects system marker", () => {
+ const result = parseSpecialMarkers(
+ "[__COPILOT_SYSTEM_e3b0__] Session expired",
+ );
+ expect(result.markerType).toBe("system");
+ expect(result.markerText).toBe("Session expired");
+ });
+
+ it("retryable takes precedence over regular error when both present", () => {
+ const text =
+ "[__COPILOT_RETRYABLE_ERROR_a9c2__] Retryable issue [__COPILOT_ERROR_f7a1__] Also error";
+ const result = parseSpecialMarkers(text);
+ expect(result.markerType).toBe("retryable_error");
+ });
+
+ it("strips marker from cleanText", () => {
+ const result = parseSpecialMarkers(
+ "Preamble text [__COPILOT_SYSTEM_e3b0__] System message",
+ );
+ expect(result.cleanText).toBe("Preamble text");
+ });
+});
+
describe("extractWorkspaceArtifacts", () => {
it("extracts a single workspace:// link with its markdown title", () => {
const text =
@@ -376,6 +597,33 @@ describe("splitReasoningAndResponse", () => {
"Here's the answer",
);
});
+
+ it("keeps decompose_goal output pinned to response (interactive)", () => {
+ const parts = [
+ textPart("Thinking..."),
+ toolPart("decompose_goal", "output-available", {
+ type: "task_decomposition",
+ }),
+ ];
+ const { reasoning, response } = splitReasoningAndResponse(parts);
+ expect(reasoning).toHaveLength(0);
+ expect(response).toHaveLength(2);
+ });
+
+ it("keeps non-interactive tool parts that emit a block_list payload in reasoning", () => {
+ const genericTool = toolPart("find_block", "output-available", {
+ type: "block_list",
+ });
+ const parts = [
+ textPart("Looking for blocks..."),
+ genericTool,
+ textPart("Found them."),
+ ];
+ const { reasoning, response } = splitReasoningAndResponse(parts);
+ expect(reasoning).toHaveLength(2);
+ expect(reasoning[1]).toBe(genericTool);
+ expect(response).toHaveLength(1);
+ });
});
// ----- Custom fileUrlBuilder threading -----------------------------------
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.tsx
index 8219e06f8b..ff00d6d24f 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
@@ -7,6 +7,7 @@ import { ArtifactCard } from "../../ArtifactCard/ArtifactCard";
import { AskQuestionTool } from "../../../tools/AskQuestion/AskQuestion";
import { ConnectIntegrationTool } from "../../../tools/ConnectIntegrationTool/ConnectIntegrationTool";
import { CreateAgentTool } from "../../../tools/CreateAgent/CreateAgent";
+import { DecomposeGoalTool } from "../../../tools/DecomposeGoal/DecomposeGoal";
import { EditAgentTool } from "../../../tools/EditAgent/EditAgent";
import {
CreateFeatureRequestTool,
@@ -216,6 +217,8 @@ export function MessagePartRenderer({
case "tool-run_agent":
case "tool-schedule_agent":
return <RunAgentTool key={key} part={part as ToolUIPart} />;
+ case "tool-decompose_goal":
+ return <DecomposeGoalTool key={key} part={part as ToolUIPart} />;
case "tool-create_agent":
return <CreateAgentTool key={key} part={part as ToolUIPart} />;
case "tool-edit_agent":
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.ts
index 9fd4a7011f..672c1d2f8b 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
@@ -31,6 +31,7 @@ const CUSTOM_TOOL_TYPES = new Set([
"tool-view_agent_output",
"tool-search_feature_requests",
"tool-create_feature_request",
+ "tool-decompose_goal",
]);
const REASONING_TOOL_TYPES = new Set([
@@ -71,6 +72,7 @@ const INTERACTIVE_RESPONSE_TYPES: ReadonlySet<string> = new Set([
ResponseType.suggested_goal,
ResponseType.agent_builder_preview,
ResponseType.agent_builder_saved,
+ ResponseType.task_decomposition,
]);
export function isCompletedToolPart(part: MessagePart): part is ToolUIPart {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/DecomposeGoal.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/DecomposeGoal.tsx
new file mode 100644
index 0000000000..7f89ea7ebc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/DecomposeGoal.tsx
@@ -0,0 +1,93 @@
+"use client";
+
+import type { ToolUIPart } from "ai";
+import { useCopilotChatActions } from "../../components/CopilotChatActionsProvider/useCopilotChatActions";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import {
+ ContentGrid,
+ ContentMessage,
+} from "../../components/ToolAccordion/AccordionContent";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import { ToolErrorCard } from "../../components/ToolErrorCard/ToolErrorCard";
+import { StepItem } from "./components/StepItem";
+import {
+ AccordionIcon,
+ getAnimationText,
+ getDecomposeGoalOutput,
+ isDecompositionOutput,
+ isErrorOutput,
+ ToolIcon,
+} from "./helpers";
+
+interface Props {
+ part: ToolUIPart;
+}
+
+export function DecomposeGoalTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const { onSend } = useCopilotChatActions();
+
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+
+ const output = getDecomposeGoalOutput(part);
+ const isError =
+ part.state === "output-error" || (!!output && isErrorOutput(output));
+ const isPending = !output && !isError;
+
+ return (
+ <div className="py-2">
+ {isPending && (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+ )}
+
+ {isError && (
+ <ToolErrorCard
+ message={
+ output && isErrorOutput(output) ? (output.message ?? "") : ""
+ }
+ fallbackMessage="Failed to analyze the goal. Please try again."
+ actions={[
+ {
+ label: "Try again",
+ onClick: () => onSend("Please try decomposing the goal again."),
+ },
+ ]}
+ />
+ )}
+
+ {output && isDecompositionOutput(output) && (
+ <ToolAccordion
+ icon={<AccordionIcon />}
+ title={`Build Plan — ${output.step_count} steps`}
+ description={output.goal}
+ defaultExpanded
+ >
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+
+ <div className="rounded-lg border border-border bg-card p-3">
+ <div className="space-y-0.5">
+ {output.steps.map((step, i) => (
+ <StepItem
+ key={step.step_id}
+ index={i}
+ description={step.description}
+ blockName={step.block_name}
+ status={step.status ?? "pending"}
+ />
+ ))}
+ </div>
+ </div>
+ </ContentGrid>
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/__tests__/DecomposeGoal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/__tests__/DecomposeGoal.test.tsx
new file mode 100644
index 0000000000..cbe14c06b7
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/__tests__/DecomposeGoal.test.tsx
@@ -0,0 +1,165 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+} from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { DecomposeGoalTool } from "../DecomposeGoal";
+import type { TaskDecompositionOutput } from "../helpers";
+
+const mockOnSend = vi.fn();
+vi.mock(
+ "../../../components/CopilotChatActionsProvider/useCopilotChatActions",
+ () => ({
+ useCopilotChatActions: () => ({ onSend: mockOnSend }),
+ }),
+);
+
+const STEPS = [
+ {
+ step_id: "step_1",
+ description: "Accept a topic from the user",
+ action: "add_input",
+ block_name: null,
+ status: "pending",
+ },
+ {
+ step_id: "step_2",
+ description: "Summarize the topic with AI",
+ action: "add_block",
+ block_name: "AI Text Generator",
+ status: "pending",
+ },
+ {
+ step_id: "step_3",
+ description: "Hand the result back to the user",
+ action: "connect_blocks",
+ block_name: null,
+ status: "pending",
+ },
+];
+
+const DECOMPOSITION: TaskDecompositionOutput = {
+ type: "task_decomposition",
+ message: "Here's the plan (3 steps):",
+ goal: "Build a news summarizer",
+ steps: STEPS,
+ step_count: 3,
+ session_id: "test-session-1",
+};
+
+function makePart(
+ state: string,
+ output?: unknown,
+): {
+ type: string;
+ toolCallId: string;
+ toolName: string;
+ state: string;
+ input?: unknown;
+ output?: unknown;
+} {
+ return {
+ type: "tool-decompose_goal",
+ toolCallId: "call_1",
+ toolName: "decompose_goal",
+ state,
+ output,
+ };
+}
+
+describe("DecomposeGoalTool", () => {
+ afterEach(() => {
+ cleanup();
+ mockOnSend.mockClear();
+ });
+
+ it("renders analyzing animation during input-streaming", () => {
+ render(<DecomposeGoalTool part={makePart("input-streaming") as any} />);
+ expect(screen.getByText(/A/)).toBeDefined();
+ });
+
+ it("renders error card when state is output-error", () => {
+ render(<DecomposeGoalTool part={makePart("output-error") as any} />);
+ expect(screen.getByText(/Failed to analyze the goal/i)).toBeDefined();
+ expect(screen.getByText("Try again")).toBeDefined();
+ });
+
+ it("sends retry message when Try again is clicked on error", () => {
+ render(<DecomposeGoalTool part={makePart("output-error") as any} />);
+ fireEvent.click(screen.getByText("Try again"));
+ expect(mockOnSend).toHaveBeenCalledWith(
+ "Please try decomposing the goal again.",
+ );
+ });
+
+ it("renders error card for error output object", () => {
+ const errorOutput = {
+ type: "error",
+ error: "missing_steps",
+ message: "Please provide at least one step.",
+ };
+ render(
+ <DecomposeGoalTool
+ part={makePart("output-available", errorOutput) as any}
+ />,
+ );
+ expect(screen.getByText("Please provide at least one step.")).toBeDefined();
+ });
+
+ it("renders the build plan accordion with steps as a read-only list", () => {
+ render(
+ <DecomposeGoalTool
+ part={makePart("output-available", DECOMPOSITION) as any}
+ />,
+ );
+ expect(screen.getByText(/Build Plan — 3 steps/)).toBeDefined();
+ expect(screen.getByText("Build a news summarizer")).toBeDefined();
+ expect(screen.getByText(/Here's the plan/)).toBeDefined();
+ expect(screen.getByText(/1\. Accept a topic from the user/)).toBeDefined();
+ expect(screen.getByText(/2\. Summarize the topic with AI/)).toBeDefined();
+ expect(
+ screen.getByText(/3\. Hand the result back to the user/),
+ ).toBeDefined();
+ });
+
+ it("renders block name badges for steps that have them", () => {
+ render(
+ <DecomposeGoalTool
+ part={makePart("output-available", DECOMPOSITION) as any}
+ />,
+ );
+ expect(screen.getByText("AI Text Generator")).toBeDefined();
+ });
+
+ it("does not render approve, modify, or edit controls", () => {
+ render(
+ <DecomposeGoalTool
+ part={makePart("output-available", DECOMPOSITION) as any}
+ />,
+ );
+ expect(screen.queryByText("Modify")).toBeNull();
+ expect(screen.queryByText("Approve")).toBeNull();
+ expect(screen.queryByText(/Starting in/)).toBeNull();
+ expect(screen.queryByPlaceholderText("Step description")).toBeNull();
+ expect(screen.queryByLabelText("Remove step")).toBeNull();
+ expect(screen.queryByLabelText("Insert step here")).toBeNull();
+ });
+
+ it("does not call onSend when the plan card renders", () => {
+ render(
+ <DecomposeGoalTool
+ part={makePart("output-available", DECOMPOSITION) as any}
+ />,
+ );
+ expect(mockOnSend).not.toHaveBeenCalled();
+ });
+
+ it("renders nothing pending when output is not yet available", () => {
+ const { container } = render(
+ <DecomposeGoalTool part={makePart("input-available") as any} />,
+ );
+ expect(container.querySelector(".py-2")).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..df2d0abe19
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/__tests__/helpers.test.ts
@@ -0,0 +1,217 @@
+/**
+ * Unit tests for DecomposeGoal/helpers.tsx
+ *
+ * Covers: parseOutput / getDecomposeGoalOutput, type guards, getAnimationText
+ */
+
+import { describe, expect, it } from "vitest";
+import {
+ getAnimationText,
+ getDecomposeGoalOutput,
+ isDecompositionOutput,
+ isErrorOutput,
+ type DecomposeErrorOutput,
+ type DecomposeGoalOutput,
+ type TaskDecompositionOutput,
+} from "../helpers";
+
+// ---------------------------------------------------------------------------
+// Fixtures
+// ---------------------------------------------------------------------------
+
+const DECOMPOSITION: TaskDecompositionOutput = {
+ type: "task_decomposition",
+ message: "Here's the plan (3 steps):",
+ goal: "Build a news summarizer",
+ steps: [
+ {
+ step_id: "step_1",
+ description: "Accept a topic from the user",
+ action: "add_input",
+ block_name: null,
+ status: "pending",
+ },
+ {
+ step_id: "step_2",
+ description: "Summarize the topic with AI",
+ action: "add_block",
+ block_name: "AI Text Generator",
+ status: "pending",
+ },
+ {
+ step_id: "step_3",
+ description: "Hand the result back to the user",
+ action: "connect_blocks",
+ block_name: null,
+ status: "pending",
+ },
+ ],
+ step_count: 3,
+};
+
+const ERROR_OUTPUT: DecomposeErrorOutput = {
+ type: "error",
+ error: "missing_steps",
+ message: "Please provide at least one step.",
+};
+
+// ---------------------------------------------------------------------------
+// isDecompositionOutput
+// ---------------------------------------------------------------------------
+
+describe("isDecompositionOutput", () => {
+ it("returns true for a full decomposition output", () => {
+ expect(isDecompositionOutput(DECOMPOSITION)).toBe(true);
+ });
+
+ it("returns false for an error output", () => {
+ expect(
+ isDecompositionOutput(ERROR_OUTPUT as unknown as DecomposeGoalOutput),
+ ).toBe(false);
+ });
+
+ it("returns false when steps is not an array (type guard tightness)", () => {
+ const malformed = {
+ steps: "not-an-array",
+ goal: "test",
+ } as unknown as DecomposeGoalOutput;
+ expect(isDecompositionOutput(malformed)).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// isErrorOutput
+// ---------------------------------------------------------------------------
+
+describe("isErrorOutput", () => {
+ it("returns true for error output", () => {
+ expect(isErrorOutput(ERROR_OUTPUT as unknown as DecomposeGoalOutput)).toBe(
+ true,
+ );
+ });
+
+ it("returns false for decomposition output", () => {
+ expect(isErrorOutput(DECOMPOSITION)).toBe(false);
+ });
+
+ it("returns true for message-only error payload (no 'error' key)", () => {
+ const messageOnly: DecomposeErrorOutput = {
+ type: "error",
+ message: "Something failed",
+ };
+ expect(isErrorOutput(messageOnly as unknown as DecomposeGoalOutput)).toBe(
+ true,
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getDecomposeGoalOutput — output parsing
+// ---------------------------------------------------------------------------
+
+describe("getDecomposeGoalOutput", () => {
+ it("parses a direct object output", () => {
+ const part = { output: DECOMPOSITION };
+ const result = getDecomposeGoalOutput(part);
+ expect(result).not.toBeNull();
+ expect(isDecompositionOutput(result!)).toBe(true);
+ });
+
+ it("parses a JSON-encoded string output", () => {
+ const part = { output: JSON.stringify(DECOMPOSITION) };
+ const result = getDecomposeGoalOutput(part);
+ expect(result).not.toBeNull();
+ expect(isDecompositionOutput(result!)).toBe(true);
+ expect((result as TaskDecompositionOutput).goal).toBe(
+ "Build a news summarizer",
+ );
+ });
+
+ it("parses an error output object", () => {
+ const part = { output: ERROR_OUTPUT };
+ const result = getDecomposeGoalOutput(part);
+ expect(result).not.toBeNull();
+ expect(isErrorOutput(result!)).toBe(true);
+ });
+
+ it("returns null for falsy output", () => {
+ expect(getDecomposeGoalOutput({ output: null })).toBeNull();
+ expect(getDecomposeGoalOutput({ output: undefined })).toBeNull();
+ expect(getDecomposeGoalOutput({ output: "" })).toBeNull();
+ });
+
+ it("returns null for a plain non-JSON string", () => {
+ expect(getDecomposeGoalOutput({ output: "just text" })).toBeNull();
+ });
+
+ it("returns null for a non-object part", () => {
+ expect(getDecomposeGoalOutput(null)).toBeNull();
+ expect(getDecomposeGoalOutput("string")).toBeNull();
+ expect(getDecomposeGoalOutput(42)).toBeNull();
+ });
+
+ it("returns null for an array-type output (not a valid shape)", () => {
+ expect(
+ getDecomposeGoalOutput({ output: ["not", "an", "object"] }),
+ ).toBeNull();
+ });
+
+ it("classifies 'steps+goal' before 'error' when object has all three keys", () => {
+ // Verify type discrimination precedence: steps+goal wins
+ const mixed = { ...DECOMPOSITION, error: "some_error" };
+ const part = { output: mixed };
+ const result = getDecomposeGoalOutput(part);
+ expect(result).not.toBeNull();
+ expect(isDecompositionOutput(result!)).toBe(true);
+ });
+
+ it("returns message-only error when no error key but has message", () => {
+ const messageOnly = { type: "error", message: "Something failed" };
+ const result = getDecomposeGoalOutput({ output: messageOnly });
+ expect(result).not.toBeNull();
+ expect(isErrorOutput(result!)).toBe(true);
+ expect((result as DecomposeErrorOutput).message).toBe("Something failed");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getAnimationText
+// ---------------------------------------------------------------------------
+
+describe("getAnimationText", () => {
+ it("shows analyzing text during input-streaming", () => {
+ const text = getAnimationText({ state: "input-streaming" });
+ expect(text.toLowerCase()).toContain("analyzing");
+ });
+
+ it("shows analyzing text during input-available", () => {
+ const text = getAnimationText({ state: "input-available" });
+ expect(text.toLowerCase()).toContain("analyzing");
+ });
+
+ it("shows plan ready with step count on output-available with decomposition", () => {
+ const text = getAnimationText({
+ state: "output-available",
+ output: DECOMPOSITION,
+ });
+ expect(text).toContain("3 steps");
+ });
+
+ it("shows analyzing when output-available but output is not a decomposition", () => {
+ const text = getAnimationText({
+ state: "output-available",
+ output: null,
+ });
+ expect(text.toLowerCase()).toContain("analyzing");
+ });
+
+ it("shows error text on output-error state", () => {
+ const text = getAnimationText({ state: "output-error" });
+ expect(text.toLowerCase()).toContain("error");
+ });
+
+ it("falls back to analyzing for unknown state", () => {
+ const text = getAnimationText({ state: "result" as never });
+ expect(text.toLowerCase()).toContain("analyzing");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/components/StepItem.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/components/StepItem.tsx
new file mode 100644
index 0000000000..cb4f9810a3
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/components/StepItem.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { CubeIcon } from "@phosphor-icons/react";
+import { StepStatusIcon } from "../helpers";
+
+interface Props {
+ index: number;
+ description: string;
+ blockName?: string | null;
+ status: string;
+}
+
+export function StepItem({ index, description, blockName, status }: Props) {
+ return (
+ <div className="flex items-start gap-3 py-1.5">
+ <div className="mt-0.5 flex shrink-0 items-center">
+ <StepStatusIcon status={status} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <Text variant="body-medium" className="text-sm text-foreground">
+ {index + 1}. {description}
+ </Text>
+ {blockName && (
+ <div className="mt-0.5 flex items-center gap-1">
+ <CubeIcon size={12} className="text-muted-foreground" />
+ <Text
+ variant="small"
+ className="font-mono text-xs text-muted-foreground"
+ >
+ {blockName}
+ </Text>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/components/__tests__/StepItem.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/components/__tests__/StepItem.test.tsx
new file mode 100644
index 0000000000..fc59b3311c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/components/__tests__/StepItem.test.tsx
@@ -0,0 +1,61 @@
+import { render, screen } from "@/tests/integrations/test-utils";
+import { describe, expect, it } from "vitest";
+import { StepItem } from "../StepItem";
+
+describe("StepItem", () => {
+ it("renders step number and description", () => {
+ render(
+ <StepItem index={0} description="Add input block" status="pending" />,
+ );
+ expect(screen.getByText("1. Add input block")).toBeDefined();
+ });
+
+ it("renders block name when provided", () => {
+ render(
+ <StepItem
+ index={1}
+ description="Add AI summarizer"
+ blockName="AI Text Generator"
+ status="pending"
+ />,
+ );
+ expect(screen.getByText("AI Text Generator")).toBeDefined();
+ });
+
+ it("does not render block name when null", () => {
+ render(
+ <StepItem
+ index={0}
+ description="Connect blocks"
+ blockName={null}
+ status="pending"
+ />,
+ );
+ expect(screen.queryByText("AI Text Generator")).toBeNull();
+ });
+
+ it("renders pending icon by default", () => {
+ render(<StepItem index={0} description="Step" status="pending" />);
+ expect(screen.getByLabelText("pending")).toBeDefined();
+ });
+
+ it("renders completed icon for completed status", () => {
+ render(<StepItem index={0} description="Step" status="completed" />);
+ expect(screen.getByLabelText("completed")).toBeDefined();
+ });
+
+ it("renders in-progress icon for in_progress status", () => {
+ render(<StepItem index={0} description="Step" status="in_progress" />);
+ expect(screen.getByLabelText("in progress")).toBeDefined();
+ });
+
+ it("renders failed icon for failed status", () => {
+ render(<StepItem index={0} description="Step" status="failed" />);
+ expect(screen.getByLabelText("failed")).toBeDefined();
+ });
+
+ it("uses zero-based index to render 1-based step number", () => {
+ render(<StepItem index={4} description="Fifth step" status="pending" />);
+ expect(screen.getByText("5. Fifth step")).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/helpers.tsx
new file mode 100644
index 0000000000..fca9c5b1b2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/DecomposeGoal/helpers.tsx
@@ -0,0 +1,176 @@
+"use client";
+
+import type { DecompositionStepModel } from "@/app/api/__generated__/models/decompositionStepModel";
+import {
+ CheckCircleIcon,
+ CircleDashedIcon,
+ ListChecksIcon,
+ SpinnerGapIcon,
+ WarningDiamondIcon,
+ XCircleIcon,
+} from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { ScaleLoader } from "../../components/ScaleLoader/ScaleLoader";
+
+// Re-export generated step type for consumers that need it.
+export type DecompositionStep = DecompositionStepModel;
+
+export interface TaskDecompositionOutput {
+ type: string;
+ message: string;
+ session_id?: string | null;
+ goal: string;
+ steps: DecompositionStep[];
+ step_count: number;
+}
+
+export interface DecomposeErrorOutput {
+ type: string;
+ error?: string;
+ message?: string;
+}
+
+export type DecomposeGoalOutput =
+ | TaskDecompositionOutput
+ | DecomposeErrorOutput;
+
+function parseOutput(output: unknown): DecomposeGoalOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object" && !Array.isArray(output)) {
+ const obj = output as Record<string, unknown>;
+ if (
+ "steps" in obj &&
+ "goal" in obj &&
+ Array.isArray(obj.steps) &&
+ typeof obj.goal === "string"
+ ) {
+ return obj as unknown as TaskDecompositionOutput;
+ }
+ if ("error" in obj && typeof obj.error === "string") {
+ return obj as unknown as DecomposeErrorOutput;
+ }
+ // Message-only error payload (no 'error' key but also not a decomposition)
+ if ("message" in obj && typeof obj.message === "string") {
+ return obj as unknown as DecomposeErrorOutput;
+ }
+ }
+ return null;
+}
+
+export function getDecomposeGoalOutput(
+ part: unknown,
+): DecomposeGoalOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+export function isDecompositionOutput(
+ output: DecomposeGoalOutput,
+): output is TaskDecompositionOutput {
+ return (
+ "steps" in output &&
+ Array.isArray((output as TaskDecompositionOutput).steps) &&
+ "goal" in output
+ );
+}
+
+export function isErrorOutput(
+ output: DecomposeGoalOutput,
+): output is DecomposeErrorOutput {
+ return !isDecompositionOutput(output);
+}
+
+export function getAnimationText(part: {
+ state: ToolUIPart["state"];
+ output?: unknown;
+}): string {
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return "Analyzing your goal...";
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (output && isDecompositionOutput(output))
+ return `Plan ready (${output.step_count} steps)`;
+ return "Analyzing your goal...";
+ }
+ case "output-error":
+ return "Error analyzing goal";
+ default:
+ return "Analyzing your goal...";
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ if (isError) {
+ return (
+ <WarningDiamondIcon size={14} weight="regular" className="text-red-500" />
+ );
+ }
+ if (isStreaming) {
+ return <ScaleLoader size={14} />;
+ }
+ return (
+ <ListChecksIcon size={14} weight="regular" className="text-neutral-400" />
+ );
+}
+
+export function AccordionIcon() {
+ return <ListChecksIcon size={32} weight="light" />;
+}
+
+export function StepStatusIcon({ status }: { status: string }) {
+ switch (status) {
+ case "completed":
+ return (
+ <CheckCircleIcon
+ size={18}
+ weight="fill"
+ className="text-emerald-500"
+ aria-label="completed"
+ />
+ );
+ case "in_progress":
+ return (
+ <SpinnerGapIcon
+ size={18}
+ weight="bold"
+ className="animate-spin text-blue-500"
+ aria-label="in progress"
+ />
+ );
+ case "failed":
+ return (
+ <XCircleIcon
+ size={18}
+ weight="fill"
+ className="text-red-500"
+ aria-label="failed"
+ />
+ );
+ default:
+ return (
+ <CircleDashedIcon
+ size={18}
+ weight="regular"
+ className="text-neutral-400"
+ aria-label="pending"
+ />
+ );
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index cab6b87df7..aa1c92873e 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -2187,6 +2187,9 @@
"$ref": "#/components/schemas/MCPToolsDiscoveredResponse"
},
{ "$ref": "#/components/schemas/MCPToolOutputResponse" },
+ {
+ "$ref": "#/components/schemas/TaskDecompositionResponse"
+ },
{ "$ref": "#/components/schemas/ScheduleListResponse" },
{ "$ref": "#/components/schemas/ScheduleDeletedResponse" },
{ "$ref": "#/components/schemas/MemoryStoreResponse" },
@@ -12096,6 +12099,40 @@
],
"title": "CreditTransactionsExportResponse"
},
+ "DecompositionStepModel": {
+ "properties": {
+ "step_id": {
+ "type": "string",
+ "title": "Step Id",
+ "description": "Unique step identifier, e.g. 'step_1'"
+ },
+ "description": {
+ "type": "string",
+ "title": "Description",
+ "description": "Plain-English description of what this step does for the user. Do not put block class names or wiring verbs here — block_name and action carry that technical detail."
+ },
+ "action": {
+ "type": "string",
+ "title": "Action",
+ "description": "Action type: 'add_block', 'connect_blocks', 'configure', etc."
+ },
+ "block_name": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Block Name",
+ "description": "Block being added, if applicable"
+ },
+ "status": {
+ "type": "string",
+ "title": "Status",
+ "description": "Step status: pending, in_progress, completed, failed",
+ "default": "pending"
+ }
+ },
+ "type": "object",
+ "required": ["step_id", "description", "action"],
+ "title": "DecompositionStepModel",
+ "description": "A single step in a decomposed agent-building plan."
+ },
"DeleteFileResponse": {
"properties": { "deleted": { "type": "boolean", "title": "Deleted" } },
"type": "object",
@@ -16129,6 +16166,7 @@
"agent_builder_clarification_needed",
"agent_builder_validation_result",
"agent_builder_fix_result",
+ "task_decomposition",
"block_list",
"block_details",
"block_output",
@@ -17977,6 +18015,39 @@
"required": ["recent_searches", "providers", "top_blocks"],
"title": "SuggestionsResponse"
},
+ "TaskDecompositionResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "task_decomposition"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "goal": {
+ "type": "string",
+ "title": "Goal",
+ "description": "The original user goal"
+ },
+ "steps": {
+ "items": { "$ref": "#/components/schemas/DecompositionStepModel" },
+ "type": "array",
+ "title": "Steps"
+ },
+ "step_count": {
+ "type": "integer",
+ "title": "Step Count",
+ "description": "Number of steps (auto-derived from steps list)",
+ "default": 0
+ }
+ },
+ "type": "object",
+ "required": ["message", "goal", "steps"],
+ "title": "TaskDecompositionResponse",
+ "description": "Response for decompose_goal tool — shows the plan to the user."
+ },
"TimezoneResponse": {
"properties": {
"timezone": {