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.

fix(frontend/builder): address reviewer feedback — prototype pollution, function length, textarea maxLength, and test coverage

Zamil Majdy875852be3202
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.tsx
index 7cd1954d17..9fa5d5b64c 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
@@ -447,6 +447,7 @@ function PanelInput({
onKeyDown={onKeyDown}
placeholder="Ask about your agent... (Enter to send, Shift+Enter for newline)"
rows={2}
+ maxLength={4000}
className="flex-1 resize-none rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400 focus:border-violet-400 focus:outline-none focus:ring-1 focus:ring-violet-200 disabled:opacity-50"
/>
{isStreaming ? (
diff --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.tsx
index b491d504cf..60a36349d9 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
@@ -262,7 +262,7 @@ describe("BuilderChatPanel", () => {
expect(handleApplyAction).toHaveBeenCalledWith(action);
});
- it("does not call handleSend when the textarea is empty", () => {
+ it("does not call handleSend when the textarea is empty and Send button is disabled", () => {
const handleSend = vi.fn();
mockUseBuilderChatPanel.mockReturnValue(
makeMockHook({
@@ -274,7 +274,9 @@ describe("BuilderChatPanel", () => {
}),
);
render(<BuilderChatPanel />);
- fireEvent.click(screen.getByLabelText("Send"));
+ const sendButton = screen.getByLabelText("Send");
+ expect((sendButton as HTMLButtonElement).disabled).toBe(true);
+ fireEvent.click(sendButton);
expect(handleSend).not.toHaveBeenCalled();
});
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.ts
index 53ffffdf6a..a061999de1 100644
--- 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.ts
@@ -1256,3 +1256,58 @@ describe("useBuilderChatPanel – inputValue resets on flowID change", () => {
expect(result.current.inputValue).toBe("");
});
});
+
+describe("useBuilderChatPanel – prototype pollution guard", () => {
+ it("rejects __proto__ as a key when node has an inputSchema with properties", () => {
+ mockNodes.push({
+ id: "n-proto",
+ data: {
+ hardcodedValues: {},
+ inputSchema: { properties: { query: {} } },
+ },
+ });
+ const { result } = renderHook(() => useBuilderChatPanel());
+
+ const protoBefore = Object.prototype.hasOwnProperty("injected");
+
+ act(() => {
+ result.current.handleApplyAction({
+ type: "update_node_input",
+ nodeId: "n-proto",
+ key: "__proto__",
+ value: "injected",
+ });
+ });
+
+ expect(mockSetNodes).not.toHaveBeenCalled();
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "destructive" }),
+ );
+ expect(Object.prototype.hasOwnProperty("injected")).toBe(protoBefore);
+ });
+
+ it("rejects constructor as a key when node has an inputSchema with properties", () => {
+ mockNodes.push({
+ id: "n-ctor",
+ data: {
+ hardcodedValues: {},
+ inputSchema: { properties: { query: {} } },
+ },
+ });
+ const { result } = renderHook(() => useBuilderChatPanel());
+
+ act(() => {
+ result.current.handleApplyAction({
+ type: "update_node_input",
+ nodeId: "n-ctor",
+ key: "constructor",
+ value: "injected",
+ });
+ });
+
+ expect(mockSetNodes).not.toHaveBeenCalled();
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "destructive" }),
+ );
+ });
+});
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.ts
index fccd30e26c..437b6e92e1 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
@@ -6,6 +6,8 @@ import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
import { MarkerType } from "@xyflow/react";
import {
+ type Dispatch,
+ type SetStateAction,
type KeyboardEvent,
useEffect,
useMemo,
@@ -15,6 +17,8 @@ import {
import { parseAsString, useQueryStates } from "nuqs";
import { useShallow } from "zustand/react/shallow";
import { useEdgeStore } from "../../stores/edgeStore";
+import type { CustomEdge } from "../FlowEditor/edges/CustomEdge";
+import type { CustomNode } from "../FlowEditor/nodes/CustomNode/CustomNode";
import { useNodeStore } from "../../stores/nodeStore";
import {
GraphAction,
@@ -42,6 +46,186 @@ interface UseBuilderChatPanelArgs {
isGraphLoaded?: boolean;
}
+interface ApplyActionCallbacks {
+ toast: ReturnType<typeof useToast>["toast"];
+ setNodes: (nodes: CustomNode[]) => void;
+ setEdges: (edges: CustomEdge[]) => void;
+ setUndoStack: Dispatch<SetStateAction<UndoSnapshot[]>>;
+ setAppliedActionKeys: Dispatch<SetStateAction<Set<string>>>;
+}
+
+function applyUpdateNodeInput(
+ action: Extract<GraphAction, { type: "update_node_input" }>,
+ { toast, setNodes, setUndoStack, setAppliedActionKeys }: ApplyActionCallbacks,
+): boolean {
+ const liveNodes = useNodeStore.getState().nodes;
+ const node = liveNodes.find((n) => n.id === action.nodeId);
+ if (!node) {
+ toast({
+ title: "Cannot apply change",
+ description: `Node "${action.nodeId}" was not found in the graph.`,
+ variant: "destructive",
+ });
+ return false;
+ }
+ const schemaProps = node.data.inputSchema?.properties;
+ // Use hasOwnProperty to avoid prototype-chain lookups — `in` would allow
+ // keys like `__proto__` or `constructor` that sit on Object.prototype.
+ if (
+ schemaProps &&
+ !Object.prototype.hasOwnProperty.call(schemaProps, action.key)
+ ) {
+ toast({
+ title: "Cannot apply change",
+ description: `Field "${action.key}" is not a valid input for "${getNodeDisplayName(node, node.id)}".`,
+ variant: "destructive",
+ });
+ return false;
+ }
+ const prevNodes = [...liveNodes];
+ const nextNodes = liveNodes.map((n) =>
+ n.id === action.nodeId
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ hardcodedValues: {
+ ...n.data.hardcodedValues,
+ [action.key]: action.value,
+ },
+ },
+ }
+ : n,
+ );
+ const key = getActionKey(action);
+ setUndoStack((prev) => {
+ const entry: UndoSnapshot = {
+ actionKey: key,
+ restore: () => {
+ setNodes(prevNodes);
+ setAppliedActionKeys((keys) => {
+ const next = new Set(keys);
+ next.delete(key);
+ return next;
+ });
+ },
+ };
+ const trimmed = prev.length >= MAX_UNDO ? prev.slice(1) : prev;
+ return [...trimmed, entry];
+ });
+ setNodes(nextNodes);
+ return true;
+}
+
+function applyConnectNodes(
+ action: Extract<GraphAction, { type: "connect_nodes" }>,
+ { toast, setEdges, setUndoStack, setAppliedActionKeys }: ApplyActionCallbacks,
+): boolean {
+ const liveNodes = useNodeStore.getState().nodes;
+ const sourceNode = liveNodes.find((n) => n.id === action.source);
+ const targetNode = liveNodes.find((n) => n.id === action.target);
+ if (!sourceNode || !targetNode) {
+ toast({
+ title: "Cannot apply connection",
+ description: `One or both nodes (${action.source}, ${action.target}) were not found.`,
+ variant: "destructive",
+ });
+ return false;
+ }
+ const srcProps = sourceNode.data.outputSchema?.properties;
+ const tgtProps = targetNode.data.inputSchema?.properties;
+ // Use hasOwnProperty to prevent prototype-chain bypass (e.g. `__proto__` handle names).
+ if (
+ srcProps &&
+ !Object.prototype.hasOwnProperty.call(srcProps, action.sourceHandle)
+ ) {
+ toast({
+ title: "Cannot apply connection",
+ description: `Output handle "${action.sourceHandle}" does not exist on "${getNodeDisplayName(sourceNode, action.source)}".`,
+ variant: "destructive",
+ });
+ return false;
+ }
+ if (
+ tgtProps &&
+ !Object.prototype.hasOwnProperty.call(tgtProps, action.targetHandle)
+ ) {
+ toast({
+ title: "Cannot apply connection",
+ description: `Input handle "${action.targetHandle}" does not exist on "${getNodeDisplayName(targetNode, action.target)}".`,
+ variant: "destructive",
+ });
+ return false;
+ }
+ const edgeId = `${action.source}:${action.sourceHandle}->${action.target}:${action.targetHandle}`;
+ const prevEdges = [...useEdgeStore.getState().edges];
+ const alreadyExists = prevEdges.some(
+ (e) =>
+ e.source === action.source &&
+ e.target === action.target &&
+ e.sourceHandle === action.sourceHandle &&
+ e.targetHandle === action.targetHandle,
+ );
+ if (alreadyExists) {
+ setAppliedActionKeys((prev) => {
+ const next = new Set(prev);
+ next.add(getActionKey(action));
+ return next;
+ });
+ return true;
+ }
+ const key = getActionKey(action);
+ setUndoStack((prev) => {
+ const entry: UndoSnapshot = {
+ actionKey: key,
+ restore: () => {
+ setEdges(prevEdges);
+ setAppliedActionKeys((keys) => {
+ const next = new Set(keys);
+ next.delete(key);
+ return next;
+ });
+ },
+ };
+ const trimmed = prev.length >= MAX_UNDO ? prev.slice(1) : prev;
+ return [...trimmed, entry];
+ });
+ setEdges([
+ ...prevEdges,
+ {
+ id: edgeId,
+ source: action.source,
+ target: action.target,
+ sourceHandle: action.sourceHandle,
+ targetHandle: action.targetHandle,
+ type: "custom",
+ markerEnd: {
+ type: MarkerType.ArrowClosed,
+ strokeWidth: 2,
+ color: "#555",
+ },
+ },
+ ]);
+ return true;
+}
+
+/**
+ * Manages the lifecycle and state for the builder chat panel.
+ *
+ * Responsibilities:
+ * - Session creation: creates a chat session when the panel first opens, guarded
+ * against duplicate creation and cleaned up if the component unmounts mid-flight.
+ * - Transport: builds a `DefaultChatTransport` once per session, with per-request
+ * auth token refresh via `getWebSocketToken`.
+ * - Seed message: sends the serialized graph as context once per session when the
+ * graph finishes loading.
+ * - Action parsing: extracts `update_node_input` and `connect_nodes` actions from
+ * completed assistant messages (gated on `status === "ready"`).
+ * - Action application: applies validated graph mutations to Zustand stores,
+ * bypassing the global history to keep chat changes separate from Ctrl+Z.
+ * - Undo: maintains a bounded LIFO stack (MAX_UNDO = 20) of restore callbacks.
+ * - Input: owns the textarea value and keyboard shortcuts (Enter / Shift+Enter / Escape).
+ */
export function useBuilderChatPanel({
isGraphLoaded = false,
}: UseBuilderChatPanelArgs = {}) {
@@ -264,170 +448,30 @@ export function useBuilderChatPanel({
}
function handleApplyAction(action: GraphAction) {
+ const cbs: ApplyActionCallbacks = {
+ toast,
+ setNodes,
+ setEdges,
+ setUndoStack,
+ setAppliedActionKeys,
+ };
+ let applied = false;
if (action.type === "update_node_input") {
- // Read live state for both validation and mutation so rapid successive
- // applies see the latest nodes rather than a stale render-cycle snapshot.
- const liveNodes = useNodeStore.getState().nodes;
- const node = liveNodes.find((n) => n.id === action.nodeId);
- 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)) {
- toast({
- title: "Cannot apply change",
- description: `Field "${action.key}" is not a valid input for "${getNodeDisplayName(node, node.id)}".`,
- variant: "destructive",
- });
- return;
- }
- // Capture a shallow-copied nodes snapshot before mutating. Spreading
- // ensures the undo restore references an independent array rather than
- // the same reference that the store may update in-place.
- // Both the apply and the restore use setNodes (not updateNodeData) to
- // bypass the global history store — this keeps chat-panel changes
- // completely separate from Ctrl+Z, preventing the "Applied" badge from
- // going stale after a global undo.
- const prevNodes = [...liveNodes];
- const nextNodes = liveNodes.map((n) =>
- n.id === action.nodeId
- ? {
- ...n,
- data: {
- ...n.data,
- hardcodedValues: {
- ...n.data.hardcodedValues,
- [action.key]: action.value,
- },
- },
- }
- : n,
- );
- const key = getActionKey(action);
- setUndoStack((prev) => {
- const entry: UndoSnapshot = {
- actionKey: key,
- restore: () => {
- setNodes(prevNodes);
- setAppliedActionKeys((keys) => {
- const next = new Set(keys);
- next.delete(key);
- return next;
- });
- },
- };
- const trimmed = prev.length >= MAX_UNDO ? prev.slice(1) : prev;
- return [...trimmed, entry];
- });
- setNodes(nextNodes);
+ applied = applyUpdateNodeInput(action, cbs);
} else if (action.type === "connect_nodes") {
- // Read live state so validation reflects the current graph even when
- // multiple actions are applied within the same render cycle.
- const liveNodes = useNodeStore.getState().nodes;
- const sourceNode = liveNodes.find((n) => n.id === action.source);
- const targetNode = liveNodes.find((n) => n.id === action.target);
- 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)) {
- 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;
- }
- const edgeId = `${action.source}:${action.sourceHandle}->${action.target}:${action.targetHandle}`;
- // Shallow-copy the edges snapshot so the undo restore references an
- // independent array rather than the same reference the store may update.
- // Both the apply and the restore use setEdges (not addEdge/removeEdge)
- // to bypass the global history store — keeps chat-panel changes separate.
- const prevEdges = [...useEdgeStore.getState().edges];
- // Guard against duplicate edges — the same connection may appear after an
- // undo-then-reapply or from identical suggestions across AI messages.
- const alreadyExists = prevEdges.some(
- (e) =>
- e.source === action.source &&
- e.target === action.target &&
- e.sourceHandle === action.sourceHandle &&
- e.targetHandle === action.targetHandle,
- );
- if (alreadyExists) {
- // Edge already present — mark as applied without duplicating it.
- setAppliedActionKeys((prev) => {
- const next = new Set(prev);
- next.add(getActionKey(action));
- return next;
- });
- return;
- }
- const key = getActionKey(action);
- setUndoStack((prev) => {
- const entry: UndoSnapshot = {
- actionKey: key,
- restore: () => {
- setEdges(prevEdges);
- setAppliedActionKeys((keys) => {
- const next = new Set(keys);
- next.delete(key);
- return next;
- });
- },
- };
- const trimmed = prev.length >= MAX_UNDO ? prev.slice(1) : prev;
- return [...trimmed, entry];
- });
- setEdges([
- ...prevEdges,
- {
- id: edgeId,
- source: action.source,
- target: action.target,
- sourceHandle: action.sourceHandle,
- targetHandle: action.targetHandle,
- type: "custom",
- // Match the markerEnd style used by addEdge in edgeStore so
- // chat-applied edges render with the same arrowhead as manually drawn ones.
- markerEnd: {
- type: MarkerType.ArrowClosed,
- strokeWidth: 2,
- color: "#555",
- },
- },
- ]);
+ applied = applyConnectNodes(action, cbs);
} else {
// Exhaustiveness guard — TypeScript ensures all GraphAction types are handled above.
const _: never = action;
return _;
}
- setAppliedActionKeys((prev) => {
- const next = new Set(prev);
- next.add(getActionKey(action));
- return next;
- });
+ if (applied) {
+ setAppliedActionKeys((prev) => {
+ const next = new Set(prev);
+ next.add(getActionKey(action));
+ return next;
+ });
+ }
}
function handleUndoLastAction() {