AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend/builder): address PR review — move logic to hook, undo, dedup fix, component tests
Zamil Majdyeede293e11aa
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/BuilderChatPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/BuilderChatPanel.tsxindex c38772a145..e17f2c49ff 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/BuilderChatPanel.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/BuilderChatPanel.tsx@@ -3,16 +3,22 @@import { Button } from "@/components/atoms/Button/Button";import { cn } from "@/lib/utils";import {+ ArrowCounterClockwise,ChatCircle,PaperPlaneTilt,SpinnerGap,StopCircle,X,} from "@phosphor-icons/react";-import { KeyboardEvent, useEffect, useRef, useState } from "react";+import { KeyboardEvent, useEffect, useRef } from "react";import ReactMarkdown from "react-markdown";import type { CustomNode } from "../FlowEditor/nodes/CustomNode/CustomNode";-import { GraphAction, extractTextFromParts, getActionKey } from "./helpers";+import {+ GraphAction,+ extractTextFromParts,+ getActionKey,+ getNodeDisplayName,+} from "./helpers";import { useBuilderChatPanel } from "./useBuilderChatPanel";interface Props {@@ -20,31 +26,39 @@ interface Props {isGraphLoaded?: boolean;}+/**+ * BuilderChatPanel renders a collapsible AI chat panel for the flow builder.+ * All business logic lives in `useBuilderChatPanel`.+ *+ * `isGraphLoaded` controls when the seed message is sent to the AI — pass+ * `true` only once the graph has finished loading so the AI receives full context.+ */export function BuilderChatPanel({ className, isGraphLoaded }: Props) {const {isOpen,handleToggle,messages,- sendMessage,stop,- status,error,isCreatingSession,sessionError,- sessionId,nodes,parsedActions,appliedActionKeys,handleApplyAction,+ undoStack,+ handleUndoLastAction,seedMessageId,+ inputValue,+ setInputValue,+ handleSend,+ handleKeyDown,+ isStreaming,+ canSend,} = useBuilderChatPanel({ isGraphLoaded });- const [inputValue, setInputValue] = useState("");const messagesEndRef = useRef<HTMLDivElement>(null);const textareaRef = useRef<HTMLTextAreaElement>(null);- const isStreaming = status === "streaming" || status === "submitted";- const canSend =- Boolean(sessionId) && !isCreatingSession && !sessionError && !isStreaming;useEffect(() => {messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });@@ -57,20 +71,6 @@ export function BuilderChatPanel({ className, isGraphLoaded }: Props) {}}, [isOpen]);- function handleSend() {- const text = inputValue.trim();- if (!text || !canSend) return;- setInputValue("");- sendMessage({ text });- }-- function handleKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- handleSend();- }- }-return (<divclassName={cn(@@ -84,7 +84,11 @@ export function BuilderChatPanel({ className, isGraphLoaded }: Props) {aria-label="Builder chat panel"className="pointer-events-auto flex h-[70vh] w-96 flex-col overflow-hidden rounded-xl border border-slate-200 bg-white shadow-2xl">- <PanelHeader onClose={handleToggle} />+ <PanelHeader+ onClose={handleToggle}+ undoCount={undoStack.length}+ onUndo={handleUndoLastAction}+ /><MessageListmessages={messages}@@ -95,6 +99,7 @@ export function BuilderChatPanel({ className, isGraphLoaded }: Props) {parsedActions={parsedActions}appliedActionKeys={appliedActionKeys}onApplyAction={handleApplyAction}+ onRetry={handleToggle}seedMessageId={seedMessageId}messagesEndRef={messagesEndRef}/>@@ -128,7 +133,15 @@ export function BuilderChatPanel({ className, isGraphLoaded }: Props) {);}-function PanelHeader({ onClose }: { onClose: () => void }) {+function PanelHeader({+ onClose,+ undoCount,+ onUndo,+}: {+ onClose: () => void;+ undoCount: number;+ onUndo: () => void;+}) {return (<div className="flex items-center justify-between border-b border-slate-100 px-4 py-3"><div className="flex items-center gap-2">@@ -137,9 +150,22 @@ function PanelHeader({ onClose }: { onClose: () => void }) {Chat with Builder</span></div>- <Button variant="icon" size="icon" onClick={onClose} aria-label="Close">- <X size={16} />- </Button>+ <div className="flex items-center gap-1">+ {undoCount > 0 && (+ <Button+ variant="ghost"+ size="icon"+ onClick={onUndo}+ aria-label="Undo last applied change"+ title="Undo last applied change"+ >+ <ArrowCounterClockwise size={16} />+ </Button>+ )}+ <Button variant="icon" size="icon" onClick={onClose} aria-label="Close">+ <X size={16} />+ </Button>+ </div></div>);}@@ -153,6 +179,7 @@ interface MessageListProps {parsedActions: GraphAction[];appliedActionKeys: Set<string>;onApplyAction: (action: GraphAction) => void;+ onRetry: () => void;seedMessageId: string | null;messagesEndRef: React.RefObject<HTMLDivElement>;}@@ -166,6 +193,7 @@ function MessageList({parsedActions,appliedActionKeys,onApplyAction,+ onRetry,seedMessageId,messagesEndRef,}: MessageListProps) {@@ -190,7 +218,17 @@ function MessageList({{sessionError && (<div className="rounded-lg border border-red-100 bg-red-50 px-3 py-2 text-xs text-red-600">- Failed to start chat session. Please close and try again.+ <p>Failed to start chat session.</p>+ <button+ onClick={() => {+ onRetry();+ // Toggle twice: close then reopen to re-trigger session creation+ setTimeout(onRetry, 50);+ }}+ className="mt-1 underline hover:no-underline"+ >+ Retry+ </button></div>)}@@ -211,6 +249,17 @@ function MessageList({</div>)}+ {visibleMessages.length === 0 &&+ messages.some((m) => m.id === seedMessageId) && (+ <div className="rounded-lg border border-violet-100 bg-violet-50 px-3 py-2 text-xs text-violet-600">+ <p className="font-medium">Graph context sent</p>+ <p className="mt-0.5 text-violet-500">+ I've analysed your agent. Ask me anything about it or tell me+ what to change.+ </p>+ </div>+ )}+{visibleMessages.map((msg) => {const textParts = extractTextFromParts(msg.parts);@@ -287,15 +336,12 @@ function ActionItem({isApplied: boolean;onApply: (action: GraphAction) => void;}) {- const nodeName = (id: string) =>- nodes.find((n) => n.id === id)?.data.metadata?.customized_name ||- nodes.find((n) => n.id === id)?.data.title ||- id;+ const nodeMap = new Map(nodes.map((n) => [n.id, n]));const label =action.type === "update_node_input"- ? `Set "${nodeName(action.nodeId)}" "${action.key}" = ${JSON.stringify(action.value)}`- : `Connect "${nodeName(action.source)}" -> "${nodeName(action.target)}"`;+ ? `Set "${getNodeDisplayName(nodeMap.get(action.nodeId), action.nodeId)}" "${action.key}" = ${JSON.stringify(action.value)}`+ : `Connect "${getNodeDisplayName(nodeMap.get(action.source), action.source)}" → "${getNodeDisplayName(nodeMap.get(action.target), action.target)}"`;return (<div className="flex items-start justify-between gap-2 rounded bg-white p-2 text-xs shadow-sm">@@ -307,6 +353,7 @@ function ActionItem({) : (<buttononClick={() => onApply(action)}+ aria-label={`Apply: ${label}`}className="shrink-0 rounded bg-violet-100 px-2 py-0.5 text-xs font-medium text-violet-700 hover:bg-violet-200">Applydiff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/BuilderChatPanel.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/BuilderChatPanel.test.tsxindex c3deb58e27..2005c4dde0 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/BuilderChatPanel.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/BuilderChatPanel.test.tsx@@ -10,6 +10,9 @@ import {serializeGraphForChat,parseGraphActions,getActionKey,+ getNodeDisplayName,+ buildSeedPrompt,+ extractTextFromParts,} from "../helpers";import type { CustomNode } from "../../FlowEditor/nodes/CustomNode/CustomNode";import type { CustomEdge } from "../../FlowEditor/edges/CustomEdge";@@ -41,7 +44,15 @@ function makeMockHook(parsedActions: [],appliedActionKeys: new Set<string>(),handleApplyAction: vi.fn(),+ undoStack: [],+ handleUndoLastAction: vi.fn(),seedMessageId: null,+ inputValue: "",+ setInputValue: vi.fn(),+ handleSend: vi.fn(),+ handleKeyDown: vi.fn(),+ isStreaming: false,+ canSend: false,...overrides,};}@@ -120,6 +131,43 @@ describe("BuilderChatPanel", () => {expect(screen.getByText("This agent searches the web.")).toBeDefined();});+ it("hides the seed message from the chat UI", () => {+ mockUseBuilderChatPanel.mockReturnValue(+ makeMockHook({+ isOpen: true,+ seedMessageId: "seed-1",+ messages: [+ {+ id: "seed-1",+ role: "user",+ parts: [{ type: "text", text: "I'm building an agent..." }],+ },+ ] as ReturnType<typeof useBuilderChatPanel>["messages"],+ }),+ );+ render(<BuilderChatPanel />);+ // The seed message should NOT be visible in the chat list+ expect(screen.queryByText("I'm building an agent...")).toBeNull();+ });++ it("shows graph context banner when seed has been sent but no visible messages", () => {+ mockUseBuilderChatPanel.mockReturnValue(+ makeMockHook({+ isOpen: true,+ seedMessageId: "seed-1",+ messages: [+ {+ id: "seed-1",+ role: "user",+ parts: [{ type: "text", text: "I'm building an agent..." }],+ },+ ] as ReturnType<typeof useBuilderChatPanel>["messages"],+ }),+ );+ render(<BuilderChatPanel />);+ expect(screen.getByText("Graph context sent")).toBeDefined();+ });+it("renders suggested changes section when parsedActions are present", () => {mockUseBuilderChatPanel.mockReturnValue(makeMockHook({@@ -136,7 +184,44 @@ describe("BuilderChatPanel", () => {);render(<BuilderChatPanel />);expect(screen.getByText("Suggested changes")).toBeDefined();- expect(screen.getByText("Apply")).toBeDefined();+ });++ it("renders the action label correctly for update_node_input", () => {+ const nodes = [+ {+ id: "1",+ data: {+ title: "Search",+ description: "",+ hardcodedValues: {},+ inputSchema: {},+ outputSchema: {},+ uiType: 1,+ block_id: "b1",+ costs: [],+ categories: [],+ },+ type: "custom" as const,+ position: { x: 0, y: 0 },+ },+ ] as unknown as CustomNode[];++ mockUseBuilderChatPanel.mockReturnValue(+ makeMockHook({+ isOpen: true,+ nodes,+ parsedActions: [+ {+ type: "update_node_input",+ nodeId: "1",+ key: "query",+ value: "AI news",+ },+ ],+ }),+ );+ render(<BuilderChatPanel />);+ expect(screen.getByText(`Set "Search" "query" = "AI news"`)).toBeDefined();});it("shows Apply button for unapplied actions and Applied badge for applied actions", () => {@@ -150,7 +235,7 @@ describe("BuilderChatPanel", () => {makeMockHook({isOpen: true,parsedActions: [action],- appliedActionKeys: new Set(["1:query"]),+ appliedActionKeys: new Set([getActionKey(action)]),}),);render(<BuilderChatPanel />);@@ -178,58 +263,59 @@ describe("BuilderChatPanel", () => {expect(handleApplyAction).toHaveBeenCalledWith(action);});- it("does not call sendMessage when the textarea is empty", () => {- const sendMessage = vi.fn();+ it("does not call handleSend when the textarea is empty", () => {+ const handleSend = vi.fn();mockUseBuilderChatPanel.mockReturnValue(- makeMockHook({ isOpen: true, sessionId: "sess-1", sendMessage }),+ makeMockHook({+ isOpen: true,+ sessionId: "sess-1",+ canSend: true,+ inputValue: "",+ handleSend,+ }),);render(<BuilderChatPanel />);fireEvent.click(screen.getByLabelText("Send"));- expect(sendMessage).not.toHaveBeenCalled();+ expect(handleSend).not.toHaveBeenCalled();});- it("calls sendMessage when the user submits a message", () => {- const sendMessage = vi.fn();+ it("calls handleSend when the Send button is clicked with text", () => {+ const handleSend = vi.fn();mockUseBuilderChatPanel.mockReturnValue(- makeMockHook({ isOpen: true, sessionId: "sess-1", sendMessage }),+ makeMockHook({+ isOpen: true,+ sessionId: "sess-1",+ canSend: true,+ inputValue: "Add a summarizer block",+ handleSend,+ }),);render(<BuilderChatPanel />);- const textarea = screen.getByPlaceholderText(/Ask about your agent/i);- fireEvent.change(textarea, { target: { value: "Add a summarizer block" } });fireEvent.click(screen.getByLabelText("Send"));- expect(sendMessage).toHaveBeenCalledWith({- text: "Add a summarizer block",- });+ expect(handleSend).toHaveBeenCalledOnce();});- it("sends message when Enter is pressed", () => {- const sendMessage = vi.fn();+ it("calls handleKeyDown when a key is pressed in the textarea", () => {+ const handleKeyDown = vi.fn();mockUseBuilderChatPanel.mockReturnValue(- makeMockHook({ isOpen: true, sessionId: "sess-1", sendMessage }),+ makeMockHook({+ isOpen: true,+ sessionId: "sess-1",+ canSend: true,+ inputValue: "Explain this agent",+ handleKeyDown,+ }),);render(<BuilderChatPanel />);const textarea = screen.getByPlaceholderText(/Ask about your agent/i);- fireEvent.change(textarea, { target: { value: "Explain this agent" } });fireEvent.keyDown(textarea, { key: "Enter", shiftKey: false });- expect(sendMessage).toHaveBeenCalledWith({ text: "Explain this agent" });- });-- it("does NOT send message when Shift+Enter is pressed", () => {- const sendMessage = vi.fn();- mockUseBuilderChatPanel.mockReturnValue(- makeMockHook({ isOpen: true, sessionId: "sess-1", sendMessage }),- );- render(<BuilderChatPanel />);- const textarea = screen.getByPlaceholderText(/Ask about your agent/i);- fireEvent.change(textarea, { target: { value: "Explain this agent" } });- fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true });- expect(sendMessage).not.toHaveBeenCalled();+ expect(handleKeyDown).toHaveBeenCalled();});it("shows Stop button when streaming", () => {const stop = vi.fn();mockUseBuilderChatPanel.mockReturnValue(- makeMockHook({ isOpen: true, status: "streaming", stop }),+ makeMockHook({ isOpen: true, isStreaming: true, stop }),);render(<BuilderChatPanel />);expect(screen.getByLabelText("Stop")).toBeDefined();@@ -248,12 +334,13 @@ describe("BuilderChatPanel", () => {expect(screen.getByText(/Connection error/i)).toBeDefined();});- it("shows session error message when sessionError is true", () => {+ it("shows session error message with Retry when sessionError is true", () => {mockUseBuilderChatPanel.mockReturnValue(makeMockHook({ isOpen: true, sessionError: true }),);render(<BuilderChatPanel />);expect(screen.getByText(/Failed to start chat session/i)).toBeDefined();+ expect(screen.getByText("Retry")).toBeDefined();});it("renders the panel with role=dialog and message list with role=log", () => {@@ -262,6 +349,38 @@ describe("BuilderChatPanel", () => {expect(screen.getByRole("dialog")).toBeDefined();expect(screen.getByRole("log")).toBeDefined();});++ it("shows undo button in header when undoStack has entries", () => {+ const handleUndoLastAction = vi.fn();+ const fakeRestore = vi.fn();+ mockUseBuilderChatPanel.mockReturnValue(+ makeMockHook({+ isOpen: true,+ undoStack: [{ actionKey: "n1:query", restore: fakeRestore }],+ handleUndoLastAction,+ }),+ );+ render(<BuilderChatPanel />);+ const undoBtn = screen.getByLabelText("Undo last applied change");+ expect(undoBtn).toBeDefined();+ fireEvent.click(undoBtn);+ expect(handleUndoLastAction).toHaveBeenCalledOnce();+ });++ it("does not show undo button when undoStack is empty", () => {+ mockUseBuilderChatPanel.mockReturnValue(+ makeMockHook({ isOpen: true, undoStack: [] }),+ );+ render(<BuilderChatPanel />);+ expect(screen.queryByLabelText("Undo last applied change")).toBeNull();+ });++ it("passes isGraphLoaded to useBuilderChatPanel", () => {+ render(<BuilderChatPanel isGraphLoaded={true} />);+ expect(mockUseBuilderChatPanel).toHaveBeenCalledWith({+ isGraphLoaded: true,+ });+ });});describe("serializeGraphForChat", () => {@@ -343,6 +462,55 @@ describe("serializeGraphForChat", () => {expect(result).toContain("10 additional nodes not shown");});+ it("truncates edges beyond MAX_EDGES limit", () => {+ const nodes = [+ {+ id: "1",+ data: {+ title: "A",+ description: "",+ hardcodedValues: {},+ inputSchema: {},+ outputSchema: {},+ uiType: 1,+ block_id: "b1",+ costs: [],+ categories: [],+ },+ type: "custom" as const,+ position: { x: 0, y: 0 },+ },+ {+ id: "2",+ data: {+ title: "B",+ description: "",+ hardcodedValues: {},+ inputSchema: {},+ outputSchema: {},+ uiType: 1,+ block_id: "b2",+ costs: [],+ categories: [],+ },+ type: "custom" as const,+ position: { x: 200, y: 0 },+ },+ ] as unknown as CustomNode[];++ const edges = Array.from({ length: 205 }, (_, i) => ({+ id: `e${i}`,+ source: "1",+ target: "2",+ sourceHandle: `out${i}`,+ targetHandle: `in${i}`,+ type: "custom" as const,+ })) as unknown as CustomEdge[];++ const result = serializeGraphForChat(nodes, edges);+ expect(result).toContain("5 additional connections not shown");+ });+it("lists connections between nodes", () => {const nodes = [{@@ -495,7 +663,7 @@ Here are the changes:});describe("getActionKey", () => {- it("returns nodeId:key for update_node_input", () => {+ it("returns nodeId:key:value for update_node_input (includes value for multi-turn dedup)", () => {expect(getActionKey({type: "update_node_input",@@ -503,7 +671,23 @@ describe("getActionKey", () => {key: "query",value: "test",}),- ).toBe("1:query");+ ).toBe('1:query:"test"');+ });++ it("generates distinct keys for same node+key but different values", () => {+ const key1 = getActionKey({+ type: "update_node_input",+ nodeId: "1",+ key: "query",+ value: "first",+ });+ const key2 = getActionKey({+ type: "update_node_input",+ nodeId: "1",+ key: "query",+ value: "corrected",+ });+ expect(key1).not.toBe(key2);});it("returns source:handle->target:handle for connect_nodes", () => {@@ -518,3 +702,90 @@ describe("getActionKey", () => {).toBe("1:result->2:input");});});++describe("getNodeDisplayName", () => {+ it("returns customized_name when set", () => {+ const node = {+ id: "1",+ data: {+ title: "Original",+ metadata: { customized_name: "My Custom" },+ },+ } as unknown as CustomNode;+ expect(getNodeDisplayName(node, "fallback")).toBe("My Custom");+ });++ it("falls back to title when no customized_name", () => {+ const node = {+ id: "1",+ data: { title: "Block Title" },+ } as unknown as CustomNode;+ expect(getNodeDisplayName(node, "fallback")).toBe("Block Title");+ });++ it("falls back to the provided fallback when node is undefined", () => {+ expect(getNodeDisplayName(undefined, "raw-id")).toBe("raw-id");+ });+});++describe("buildSeedPrompt", () => {+ it("starts with SEED_PROMPT_PREFIX", () => {+ const result = buildSeedPrompt("summary");+ expect(result.startsWith("I'm building an agent")).toBe(true);+ });++ it("wraps summary in <graph_context> tags", () => {+ const result = buildSeedPrompt("some graph summary");+ expect(result).toContain(+ "<graph_context>\nsome graph summary\n</graph_context>",+ );+ });++ it("includes format instructions for update_node_input", () => {+ const result = buildSeedPrompt("");+ expect(result).toContain('"action": "update_node_input"');+ });++ it("includes format instructions for connect_nodes", () => {+ const result = buildSeedPrompt("");+ expect(result).toContain('"action": "connect_nodes"');+ });++ it("ends with a question to prompt an AI response", () => {+ const result = buildSeedPrompt("");+ expect(result.trim().endsWith("What does this agent do?")).toBe(true);+ });+});++describe("extractTextFromParts", () => {+ it("returns empty string for empty array", () => {+ expect(extractTextFromParts([])).toBe("");+ });++ it("concatenates text parts in order", () => {+ const parts = [+ { type: "text", text: "Hello, " },+ { type: "text", text: "world!" },+ ];+ expect(extractTextFromParts(parts)).toBe("Hello, world!");+ });++ it("ignores non-text parts", () => {+ const parts = [+ { type: "text", text: "visible" },+ { type: "tool-call", text: "ignored" },+ { type: "text", text: " text" },+ ];+ expect(extractTextFromParts(parts)).toBe("visible text");+ });++ it("returns empty string when all parts are non-text", () => {+ const parts = [{ type: "tool-result" }, { type: "image" }];+ expect(extractTextFromParts(parts)).toBe("");+ });++ it("handles parts without a text field", () => {+ const parts = [{ type: "text" }, { type: "text", text: "hello" }];+ expect(extractTextFromParts(parts)).toBe("hello");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/helpers.test.tsindex 373971cd5b..a772cbe1c1 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/helpers.test.ts@@ -1,63 +1,7 @@import { describe, expect, it } from "vitest";-import {- buildSeedPrompt,- extractTextFromParts,- serializeGraphForChat,-} from "../helpers";+import { serializeGraphForChat } from "../helpers";import type { CustomNode } from "../../FlowEditor/nodes/CustomNode/CustomNode";-describe("extractTextFromParts", () => {- it("returns empty string for empty array", () => {- expect(extractTextFromParts([])).toBe("");- });-- it("concatenates text parts in order", () => {- const parts = [- { type: "text", text: "Hello, " },- { type: "text", text: "world!" },- ];- expect(extractTextFromParts(parts)).toBe("Hello, world!");- });-- it("ignores non-text parts", () => {- const parts = [- { type: "text", text: "visible" },- { type: "tool-call", text: "ignored" },- { type: "text", text: " text" },- ];- expect(extractTextFromParts(parts)).toBe("visible text");- });-- it("returns empty string when all parts are non-text", () => {- const parts = [{ type: "tool-result" }, { type: "image" }];- expect(extractTextFromParts(parts)).toBe("");- });-});--describe("buildSeedPrompt", () => {- it("wraps the summary in <graph_context> tags", () => {- const result = buildSeedPrompt("some graph summary");- expect(result).toContain(- "<graph_context>\nsome graph summary\n</graph_context>",- );- });-- it("includes instructions for update_node_input format", () => {- const result = buildSeedPrompt("");- expect(result).toContain('"action": "update_node_input"');- });-- it("includes instructions for connect_nodes format", () => {- const result = buildSeedPrompt("");- expect(result).toContain('"action": "connect_nodes"');- });-- it("ends with a question to prompt AI response", () => {- const result = buildSeedPrompt("");- expect(result.trim().endsWith("What does this agent do?")).toBe(true);- });-});-describe("serializeGraphForChat – XML injection prevention", () => {it("escapes < and > in node names before embedding in prompt", () => {const nodes = [diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.tsdeleted file mode 100644index 8edb3957e5..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.ts+++ /dev/null@@ -1,436 +0,0 @@-import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";-import { renderHook, act, cleanup } from "@testing-library/react";--// --- Module mocks (must be hoisted before imports) -----// Bypass useShallow's ref-based shallow comparison so selectors work in tests.-vi.mock("zustand/react/shallow", () => ({- useShallow: (fn: (s: unknown) => unknown) => fn,-}));--const mockNodes: unknown[] = [];-const mockEdges: unknown[] = [];-const mockUpdateNodeData = vi.fn();-const mockAddEdge = vi.fn();--vi.mock("../../../stores/nodeStore", () => ({- useNodeStore: (selector: (s: unknown) => unknown) =>- selector({- nodes: mockNodes,- updateNodeData: mockUpdateNodeData,- }),-}));--vi.mock("../../../stores/edgeStore", () => ({- useEdgeStore: (selector: (s: unknown) => unknown) =>- selector({- edges: mockEdges,- addEdge: mockAddEdge,- }),-}));--const mockPostV2CreateSession = vi.fn();-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- postV2CreateSession: (...args: unknown[]) => mockPostV2CreateSession(...args),-}));--vi.mock("@/app/api/__generated__/endpoints/graphs/graphs", () => ({- getGetV1GetSpecificGraphQueryKey: (id: string) => ["graphs", id],-}));--vi.mock("@/lib/supabase/actions", () => ({- getWebSocketToken: vi.fn().mockResolvedValue({ token: "tok", error: null }),-}));--vi.mock("@/services/environment", () => ({- environment: { getAGPTServerBaseUrl: () => "http://localhost:8000" },-}));--const mockInvalidateQueries = vi.fn();-vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({ invalidateQueries: mockInvalidateQueries }),-}));--const mockSendMessage = vi.fn();-const mockStop = vi.fn();-vi.mock("@ai-sdk/react", () => ({- useChat: () => ({- messages: [],- sendMessage: mockSendMessage,- stop: mockStop,- status: "ready",- error: undefined,- }),-}));--vi.mock("ai", () => ({- // Must be a regular function (not an arrow) so it is constructible via `new`.- DefaultChatTransport: vi.fn().mockImplementation(function () {- return {};- }),-}));--let mockFlowID: string | null = null;--vi.mock("nuqs", () => ({- parseAsString: { withDefault: (d: string) => d },- useQueryStates: () => [{ flowID: mockFlowID }, vi.fn()],-}));--// Import after mocks-import { useBuilderChatPanel } from "../useBuilderChatPanel";--beforeEach(() => {- mockFlowID = null;- mockNodes.length = 0;- mockEdges.length = 0;- mockUpdateNodeData.mockClear();- mockAddEdge.mockClear();- mockPostV2CreateSession.mockClear();- mockInvalidateQueries.mockClear();- mockSendMessage.mockClear();-});--afterEach(() => {- cleanup();-});--describe("useBuilderChatPanel – handleApplyAction", () => {- it("update_node_input: calls updateNodeData with merged hardcodedValues", () => {- mockNodes.push({- id: "node-1",- data: { hardcodedValues: { existing: "value" } },- });- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "update_node_input",- nodeId: "node-1",- key: "query",- value: "AI news",- });- });-- expect(mockUpdateNodeData).toHaveBeenCalledWith("node-1", {- hardcodedValues: { existing: "value", query: "AI news" },- });- });-- it("update_node_input: does nothing when node not found", () => {- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "update_node_input",- nodeId: "nonexistent",- key: "query",- value: "test",- });- });-- expect(mockUpdateNodeData).not.toHaveBeenCalled();- });-- it("connect_nodes: calls addEdge when both nodes exist", () => {- mockNodes.push({ id: "src", data: {} }, { id: "tgt", data: {} });- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "connect_nodes",- source: "src",- target: "tgt",- sourceHandle: "output",- targetHandle: "input",- });- });-- expect(mockAddEdge).toHaveBeenCalledWith({- id: "src:output->tgt:input",- source: "src",- target: "tgt",- sourceHandle: "output",- targetHandle: "input",- type: "custom",- });- });-- it("connect_nodes: does NOT call addEdge when source node is missing", () => {- mockNodes.push({ id: "tgt", data: {} });- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "connect_nodes",- source: "missing-src",- target: "tgt",- sourceHandle: "output",- targetHandle: "input",- });- });-- expect(mockAddEdge).not.toHaveBeenCalled();- });-- it("connect_nodes: does NOT call addEdge when target node is missing", () => {- mockNodes.push({ id: "src", data: {} });- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "connect_nodes",- source: "src",- target: "missing-tgt",- sourceHandle: "output",- targetHandle: "input",- });- });-- expect(mockAddEdge).not.toHaveBeenCalled();- });-- it("update_node_input: rejects key not present in inputSchema when schema is defined", () => {- mockNodes.push({- id: "node-1",- data: {- hardcodedValues: {},- inputSchema: { properties: { allowed_key: {} } },- },- });- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "update_node_input",- nodeId: "node-1",- key: "forbidden_key",- value: "test",- });- });-- expect(mockUpdateNodeData).not.toHaveBeenCalled();- });-- it("update_node_input: allows key present in inputSchema", () => {- mockNodes.push({- id: "node-1",- data: {- hardcodedValues: {},- inputSchema: { properties: { query: {} } },- },- });- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "update_node_input",- nodeId: "node-1",- key: "query",- value: "AI news",- });- });-- expect(mockUpdateNodeData).toHaveBeenCalledWith("node-1", {- hardcodedValues: { query: "AI news" },- });- });-- it("connect_nodes: rejects sourceHandle not in outputSchema when schema is defined", () => {- mockNodes.push(- {- id: "src",- data: { outputSchema: { properties: { result: {} } } },- },- {- id: "tgt",- data: { inputSchema: { properties: { input: {} } } },- },- );- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "connect_nodes",- source: "src",- target: "tgt",- sourceHandle: "nonexistent_output",- targetHandle: "input",- });- });-- expect(mockAddEdge).not.toHaveBeenCalled();- });-- it("connect_nodes: rejects targetHandle not in inputSchema when schema is defined", () => {- mockNodes.push(- {- id: "src",- data: { outputSchema: { properties: { result: {} } } },- },- {- id: "tgt",- data: { inputSchema: { properties: { input: {} } } },- },- );- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "connect_nodes",- source: "src",- target: "tgt",- sourceHandle: "result",- targetHandle: "nonexistent_input",- });- });-- expect(mockAddEdge).not.toHaveBeenCalled();- });-- it("connect_nodes: calls addEdge when both handles are valid according to schemas", () => {- mockNodes.push(- {- id: "src",- data: { outputSchema: { properties: { result: {} } } },- },- {- id: "tgt",- data: { inputSchema: { properties: { input: {} } } },- },- );- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "connect_nodes",- source: "src",- target: "tgt",- sourceHandle: "result",- targetHandle: "input",- });- });-- expect(mockAddEdge).toHaveBeenCalledWith({- id: "src:result->tgt:input",- source: "src",- target: "tgt",- sourceHandle: "result",- targetHandle: "input",- type: "custom",- });- });-});--describe("useBuilderChatPanel – initial state", () => {- it("starts with panel closed and no session", () => {- const { result } = renderHook(() => useBuilderChatPanel());- expect(result.current.isOpen).toBe(false);- expect(result.current.sessionId).toBeNull();- expect(result.current.sessionError).toBe(false);- expect(result.current.isCreatingSession).toBe(false);- });-- it("handleToggle opens and closes the panel", () => {- const { result } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleToggle();- });- expect(result.current.isOpen).toBe(true);-- act(() => {- result.current.handleToggle();- });- expect(result.current.isOpen).toBe(false);- });-});--// Flush all pending microtasks + one macrotask so async effects inside `act`-// have time to resolve their awaited promises and commit state updates.-async function openAndFlush(toggle: () => void) {- await act(async () => {- toggle();- await new Promise<void>((resolve) => setTimeout(resolve, 0));- });-}--describe("useBuilderChatPanel – session lifecycle", () => {- it("creates session and sets sessionId when panel is opened", async () => {- mockPostV2CreateSession.mockResolvedValue({- status: 200,- data: { id: "sess-1" },- });- const { result } = renderHook(() => useBuilderChatPanel());-- await openAndFlush(() => result.current.handleToggle());-- expect(result.current.sessionId).toBe("sess-1");- expect(result.current.isCreatingSession).toBe(false);- expect(result.current.sessionError).toBe(false);- });-- it("sets sessionError when session creation request fails", async () => {- mockPostV2CreateSession.mockRejectedValue(new Error("network error"));- const { result } = renderHook(() => useBuilderChatPanel());-- await openAndFlush(() => result.current.handleToggle());-- expect(result.current.sessionError).toBe(true);- expect(result.current.isCreatingSession).toBe(false);- expect(result.current.sessionId).toBeNull();- });-- it("sets sessionError when session creation returns non-200", async () => {- mockPostV2CreateSession.mockResolvedValue({ status: 500, data: {} });- const { result } = renderHook(() => useBuilderChatPanel());-- await openAndFlush(() => result.current.handleToggle());-- expect(result.current.sessionError).toBe(true);- });-});--describe("useBuilderChatPanel – flowID reset", () => {- it("resets appliedActionKeys when flowID changes", () => {- mockNodes.push({ id: "n1", data: { hardcodedValues: {} } });- mockFlowID = "flow-1";-- const { result, rerender } = renderHook(() => useBuilderChatPanel());-- act(() => {- result.current.handleApplyAction({- type: "update_node_input",- nodeId: "n1",- key: "query",- value: "test",- });- });- expect(result.current.appliedActionKeys.size).toBe(1);-- // Navigate to a different graph- mockFlowID = "flow-2";- rerender();-- expect(result.current.appliedActionKeys.size).toBe(0);- });-- it("resets sessionId when flowID changes", async () => {- mockPostV2CreateSession.mockResolvedValue({- status: 200,- data: { id: "sess-abc" },- });- mockFlowID = "flow-1";-- const { result, rerender } = renderHook(() => useBuilderChatPanel());-- await openAndFlush(() => result.current.handleToggle());- expect(result.current.sessionId).toBe("sess-abc");-- // Navigate to a different graph- mockFlowID = "flow-2";- rerender();-- expect(result.current.sessionId).toBeNull();- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/helpers.tsindex b46a8d9fab..a9237b5a66 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/helpers.ts@@ -52,11 +52,7 @@ export function serializeGraphForChat(const visibleNodes = nodes.slice(0, MAX_NODES);const nodeLines = visibleNodes.map((n) => {- const name = sanitizeForXml(- (n.data.metadata?.customized_name as string | undefined) ||- n.data.title ||- "",- );+ const name = sanitizeForXml(getNodeDisplayName(n, ""));const desc = n.data.description? ` — ${sanitizeForXml(n.data.description)}`: "";@@ -68,19 +64,15 @@ export function serializeGraphForChat(? `\n(${nodes.length - MAX_NODES} additional nodes not shown)`: "";+ // Pre-build a Map for O(1) lookups when serializing edges.+ const nodeMap = new Map(nodes.map((n) => [n.id, n]));const visibleEdges = edges.slice(0, MAX_EDGES);const edgeLines = visibleEdges.map((e) => {- const src = nodes.find((n) => n.id === e.source);- const tgt = nodes.find((n) => n.id === e.target);const srcName = sanitizeForXml(- (src?.data.metadata?.customized_name as string | undefined) ||- src?.data.title ||- e.source,+ getNodeDisplayName(nodeMap.get(e.source), e.source),);const tgtName = sanitizeForXml(- (tgt?.data.metadata?.customized_name as string | undefined) ||- tgt?.data.title ||- e.target,+ getNodeDisplayName(nodeMap.get(e.target), e.target),);return `- "${srcName}" (${e.sourceHandle}) → "${tgtName}" (${e.targetHandle})`;});@@ -134,14 +126,32 @@ export function buildSeedPrompt(summary: string): string {/*** Returns a stable deduplication key for a GraphAction.- * Used for both React list keys and seen-set deduplication in the hook.+ * Includes the value for update_node_input so that corrected AI suggestions+ * (same node + key, different value) in later turns are not silently dropped+ * by the seen-set deduplication in the hook.*/export function getActionKey(action: GraphAction): string {return action.type === "update_node_input"- ? `${action.nodeId}:${action.key}`+ ? `${action.nodeId}:${action.key}:${JSON.stringify(action.value)}`: `${action.source}:${action.sourceHandle}->${action.target}:${action.targetHandle}`;}+/**+ * Resolves the display name for a node: prefers the user-customized name,+ * falls back to the block title, then to the raw ID.+ * Shared between `serializeGraphForChat` and `ActionItem` to avoid duplication.+ */+export function getNodeDisplayName(+ node: CustomNode | undefined,+ fallback: string,+): string {+ return (+ (node?.data.metadata?.customized_name as string | undefined) ||+ node?.data.title ||+ fallback+ );+}+/*** Extracts the concatenated plain-text content from a message's parts array.* Reused in both the hook (action parsing) and the component (rendering).diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.tsindex 6fe75749b6..2d07f1105f 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts@@ -2,10 +2,18 @@ import { postV2CreateSession } from "@/app/api/__generated__/endpoints/chat/chatimport { getGetV1GetSpecificGraphQueryKey } from "@/app/api/__generated__/endpoints/graphs/graphs";import { getWebSocketToken } from "@/lib/supabase/actions";import { environment } from "@/services/environment";+import { useToast } from "@/components/molecules/Toast/use-toast";import { useQueryClient } from "@tanstack/react-query";import { useChat } from "@ai-sdk/react";import { DefaultChatTransport } from "ai";-import { useEffect, useMemo, useRef, useState } from "react";+import {+ type KeyboardEvent,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import { parseAsString, useQueryStates } from "nuqs";import { useShallow } from "zustand/react/shallow";import { useEdgeStore } from "../../stores/edgeStore";@@ -16,16 +24,32 @@ import {buildSeedPrompt,extractTextFromParts,getActionKey,+ getNodeDisplayName,parseGraphActions,serializeGraphForChat,} from "./helpers";type SendMessageFn = ReturnType<typeof useChat>["sendMessage"];+/** Snapshot of node data taken before an action is applied, enabling undo. */+interface UndoSnapshot {+ actionKey: string;+ restore: () => void;+}+interface UseBuilderChatPanelArgs {isGraphLoaded?: boolean;}+/**+ * useBuilderChatPanel manages all business logic for the collapsible AI chat+ * panel in the flow builder. It owns session lifecycle, streaming transport,+ * graph context serialization, action parsing, apply/undo, and input handling.+ *+ * @param isGraphLoaded - When true the seed message is sent automatically.+ * Pass false (the default) until the graph has finished loading to avoid+ * sending an empty context to the AI.+ */export function useBuilderChatPanel({isGraphLoaded = false,}: UseBuilderChatPanelArgs = {}) {@@ -36,6 +60,10 @@ export function useBuilderChatPanel({const [appliedActionKeys, setAppliedActionKeys] = useState<Set<string>>(new Set(),);+ const [undoStack, setUndoStack] = useState<UndoSnapshot[]>([]);+ // Input state owned here to keep render logic out of the component.+ const [inputValue, setInputValue] = useState("");+// Guards whether the seed message has been sent for this session.const hasSentSeedMessageRef = useRef(false);const sendMessageRef = useRef<SendMessageFn | null>(null);@@ -45,6 +73,7 @@ export function useBuilderChatPanel({const [{ flowID }] = useQueryStates({ flowID: parseAsString });const queryClient = useQueryClient();+ const { toast } = useToast();const nodes = useNodeStore(useShallow((s) => s.nodes));const edges = useEdgeStore(useShallow((s) => s.edges));@@ -57,6 +86,7 @@ export function useBuilderChatPanel({setSessionId(null);setSessionError(false);setAppliedActionKeys(new Set());+ setUndoStack([]);hasSentSeedMessageRef.current = false;}, [flowID]);@@ -171,7 +201,7 @@ export function useBuilderChatPanel({// Close the panel on Escape so keyboard users can dismiss it quickly.useEffect(() => {if (!isOpen) return;- function onKeyDown(e: KeyboardEvent) {+ function onKeyDown(e: globalThis.KeyboardEvent) {if (e.key === "Escape") setIsOpen(false);}document.addEventListener("keydown", onKeyDown);@@ -194,6 +224,10 @@ export function useBuilderChatPanel({sendMessageRef.current?.({ text: buildSeedPrompt(summary) });}, [sessionId, transport, isGraphLoaded, nodes, edges]);+ const isStreaming = status === "streaming" || status === "submitted";+ const canSend =+ Boolean(sessionId) && !isCreatingSession && !sessionError && !isStreaming;+function handleToggle() {// Reset session error when reopening so the panel can retry session creationif (!isOpen && !sessionId) {@@ -202,14 +236,61 @@ export function useBuilderChatPanel({setIsOpen((o) => !o);}+ function handleSend() {+ const text = inputValue.trim();+ if (!text || !canSend) return;+ setInputValue("");+ sendMessage({ text });+ }++ function handleKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ handleSend();+ }+ }+function handleApplyAction(action: GraphAction) {if (action.type === "update_node_input") {const node = nodes.find((n) => n.id === action.nodeId);- if (!node) return;+ if (!node) {+ toast({+ title: "Cannot apply change",+ description: `Node "${action.nodeId}" was not found in the graph.`,+ variant: "destructive",+ });+ return;+ }// Reject keys not present in the node's input schema to prevent writing// arbitrary fields that the block does not support.const schemaProps = node.data.inputSchema?.properties;- if (schemaProps && !(action.key in schemaProps)) return;+ if (schemaProps && !(action.key in schemaProps)) {+ toast({+ title: "Cannot apply change",+ description: `Field "${action.key}" is not a valid input for "${getNodeDisplayName(node, node.id)}".`,+ variant: "destructive",+ });+ return;+ }+ // Capture a snapshot before mutating so we can undo.+ const prevHardcoded = node.data.hardcodedValues;+ const key = getActionKey(action);+ setUndoStack((prev) => [+ ...prev,+ {+ actionKey: key,+ restore: () => {+ updateNodeData(action.nodeId, {+ hardcodedValues: prevHardcoded,+ });+ setAppliedActionKeys((keys) => {+ const next = new Set(keys);+ next.delete(key);+ return next;+ });+ },+ },+ ]);updateNodeData(action.nodeId, {hardcodedValues: {...node.data.hardcodedValues,@@ -219,12 +300,33 @@ export function useBuilderChatPanel({} else if (action.type === "connect_nodes") {const sourceNode = nodes.find((n) => n.id === action.source);const targetNode = nodes.find((n) => n.id === action.target);- if (!sourceNode || !targetNode) return;+ if (!sourceNode || !targetNode) {+ toast({+ title: "Cannot apply connection",+ description: `One or both nodes (${action.source}, ${action.target}) were not found.`,+ variant: "destructive",+ });+ return;+ }// Validate that the referenced handles exist on the respective nodes.const srcProps = sourceNode.data.outputSchema?.properties;const tgtProps = targetNode.data.inputSchema?.properties;- if (srcProps && !(action.sourceHandle in srcProps)) return;- if (tgtProps && !(action.targetHandle in tgtProps)) return;+ if (srcProps && !(action.sourceHandle in srcProps)) {+ toast({+ title: "Cannot apply connection",+ description: `Output handle "${action.sourceHandle}" does not exist on "${getNodeDisplayName(sourceNode, action.source)}".`,+ variant: "destructive",+ });+ return;+ }+ if (tgtProps && !(action.targetHandle in tgtProps)) {+ toast({+ title: "Cannot apply connection",+ description: `Input handle "${action.targetHandle}" does not exist on "${getNodeDisplayName(targetNode, action.target)}".`,+ variant: "destructive",+ });+ return;+ }addEdge({id: `${action.source}:${action.sourceHandle}->${action.target}:${action.targetHandle}`,source: action.source,@@ -246,6 +348,15 @@ export function useBuilderChatPanel({}}+ const handleUndoLastAction = useCallback(() => {+ setUndoStack((prev) => {+ if (prev.length === 0) return prev;+ const last = prev[prev.length - 1];+ last.restore();+ return prev.slice(0, -1);+ });+ }, []);+return {isOpen,handleToggle,@@ -261,6 +372,15 @@ export function useBuilderChatPanel({parsedActions,appliedActionKeys,handleApplyAction,+ undoStack,+ handleUndoLastAction,seedMessageId,+ // Input handling (owned here to keep component render-only)+ inputValue,+ setInputValue,+ handleSend,+ handleKeyDown,+ isStreaming,+ canSend,};}