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(frontend/builder): persistent session per graph, no auto-send, tool detection

Zamil Majdy8b8eb80480a6
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 9fa5d5b64c..461a11ee3c 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
@@ -23,10 +23,10 @@ import { useBuilderChatPanel } from "./useBuilderChatPanel";
interface Props {
className?: string;
- isGraphLoaded?: boolean;
+ onGraphEdited?: () => void;
}
-export function BuilderChatPanel({ className, isGraphLoaded }: Props) {
+export function BuilderChatPanel({ className, onGraphEdited }: Props) {
const {
isOpen,
handleToggle,
@@ -42,14 +42,13 @@ export function BuilderChatPanel({ className, isGraphLoaded }: Props) {
handleApplyAction,
undoStack,
handleUndoLastAction,
- seedMessageId,
inputValue,
setInputValue,
handleSend,
handleKeyDown,
isStreaming,
canSend,
- } = useBuilderChatPanel({ isGraphLoaded });
+ } = useBuilderChatPanel({ onGraphEdited });
const messagesEndRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
@@ -94,7 +93,6 @@ export function BuilderChatPanel({ className, isGraphLoaded }: Props) {
appliedActionKeys={appliedActionKeys}
onApplyAction={handleApplyAction}
onRetry={retrySession}
- seedMessageId={seedMessageId}
messagesEndRef={messagesEndRef}
isStreaming={isStreaming}
/>
@@ -176,7 +174,6 @@ interface MessageListProps {
appliedActionKeys: Set<string>;
onApplyAction: (action: GraphAction) => void;
onRetry: () => void;
- seedMessageId: string | null;
messagesEndRef: React.RefObject<HTMLDivElement>;
isStreaming: boolean;
}
@@ -191,13 +188,11 @@ function MessageList({
appliedActionKeys,
onApplyAction,
onRetry,
- seedMessageId,
messagesEndRef,
isStreaming,
}: MessageListProps) {
- const visibleMessages = messages.filter(
- (msg) =>
- msg.id !== seedMessageId && Boolean(extractTextFromParts(msg.parts)),
+ const visibleMessages = messages.filter((msg) =>
+ Boolean(extractTextFromParts(msg.parts)),
);
const lastVisibleRole = visibleMessages.at(-1)?.role;
const showTypingIndicator =
@@ -235,34 +230,16 @@ function MessageList({
</div>
)}
- {visibleMessages.length === 0 &&
- !isCreatingSession &&
- !sessionError &&
- !messages.some((m) => m.id === seedMessageId) && (
- <div className="flex flex-col items-center gap-2 py-6 text-center text-xs text-slate-400">
- <ChatCircle
- size={28}
- weight="duotone"
- className="text-violet-300"
- />
- <p>Ask me to explain or modify your agent.</p>
- <p className="text-slate-300">
- You can say things like &ldquo;What does this agent do?&rdquo; or
- &ldquo;Add a step that formats the output.&rdquo;
- </p>
- </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&apos;ve analysed your agent. Ask me anything about it or tell me
- what to change.
- </p>
- </div>
- )}
+ {visibleMessages.length === 0 && !isCreatingSession && !sessionError && (
+ <div className="flex flex-col items-center gap-2 py-6 text-center text-xs text-slate-400">
+ <ChatCircle size={28} weight="duotone" className="text-violet-300" />
+ <p>Ask me to explain or modify your agent.</p>
+ <p className="text-slate-300">
+ You can say things like &ldquo;What does this agent do?&rdquo; or
+ &ldquo;Add a step that formats the output.&rdquo;
+ </p>
+ </div>
+ )}
{visibleMessages.map((msg) => {
const textParts = extractTextFromParts(msg.parts);
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 60a36349d9..3d2ef9dd1a 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
@@ -45,7 +45,6 @@ function makeMockHook(
handleApplyAction: vi.fn(),
undoStack: [],
handleUndoLastAction: vi.fn(),
- seedMessageId: null,
inputValue: "",
setInputValue: vi.fn(),
handleSend: vi.fn(),
@@ -130,43 +129,6 @@ 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({
@@ -379,11 +341,10 @@ describe("BuilderChatPanel", () => {
expect(screen.queryByLabelText("Undo last applied change")).toBeNull();
});
- it("passes isGraphLoaded to useBuilderChatPanel", () => {
- render(<BuilderChatPanel isGraphLoaded={true} />);
- expect(mockUseBuilderChatPanel).toHaveBeenCalledWith({
- isGraphLoaded: true,
- });
+ it("passes onGraphEdited to useBuilderChatPanel", () => {
+ const onGraphEdited = vi.fn();
+ render(<BuilderChatPanel onGraphEdited={onGraphEdited} />);
+ expect(mockUseBuilderChatPanel).toHaveBeenCalledWith({ onGraphEdited });
});
});
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 a061999de1..1f5e23e4c0 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
@@ -93,7 +93,10 @@ vi.mock("nuqs", () => ({
}));
// Import after mocks
-import { useBuilderChatPanel } from "../useBuilderChatPanel";
+import {
+ useBuilderChatPanel,
+ clearGraphSessionCacheForTesting,
+} from "../useBuilderChatPanel";
beforeEach(() => {
mockFlowID = null;
@@ -108,6 +111,7 @@ beforeEach(() => {
mockSendMessage.mockClear();
mockSetMessages.mockClear();
mockToast.mockClear();
+ clearGraphSessionCacheForTesting();
});
afterEach(() => {
@@ -203,60 +207,23 @@ describe("useBuilderChatPanel – session lifecycle", () => {
});
});
-describe("useBuilderChatPanel – seed message", () => {
- it("sends seed message via sendMessage when session becomes available and isGraphLoaded=true", async () => {
+describe("useBuilderChatPanel – no auto-send on open", () => {
+ it("does NOT auto-send any message when the panel opens", async () => {
mockPostV2CreateSession.mockResolvedValue({
status: 200,
- data: { id: "sess-seed" },
+ data: { id: "sess-open" },
});
mockNodes.push({
id: "n1",
data: { title: "Search Block", description: "" },
});
- const { result } = renderHook(() =>
- useBuilderChatPanel({ isGraphLoaded: true }),
- );
-
- await openAndFlush(() => result.current.handleToggle());
-
- expect(mockSendMessage).toHaveBeenCalledOnce();
- const callArg = mockSendMessage.mock.calls[0][0] as { text: string };
- expect(callArg.text).toContain("I'm building an agent");
- expect(callArg.text).toContain("graph_context");
- });
-
- it("does NOT send seed message when isGraphLoaded is false (default)", async () => {
- mockPostV2CreateSession.mockResolvedValue({
- status: 200,
- data: { id: "sess-no-seed" },
- });
-
const { result } = renderHook(() => useBuilderChatPanel());
await openAndFlush(() => result.current.handleToggle());
expect(mockSendMessage).not.toHaveBeenCalled();
});
-
- it("sends seed message only once even when deps re-run (hasSentSeedMessageRef guard)", async () => {
- mockPostV2CreateSession.mockResolvedValue({
- status: 200,
- data: { id: "sess-once" },
- });
-
- const { result, rerender } = renderHook(() =>
- useBuilderChatPanel({ isGraphLoaded: true }),
- );
-
- await openAndFlush(() => result.current.handleToggle());
- expect(mockSendMessage).toHaveBeenCalledOnce();
-
- // Re-render (simulating store update) should not send a second seed
- act(() => rerender());
-
- expect(mockSendMessage).toHaveBeenCalledOnce();
- });
});
describe("useBuilderChatPanel – flowID reset", () => {
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 437b6e92e1..af34cd2d2b 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
@@ -22,7 +22,6 @@ import type { CustomNode } from "../FlowEditor/nodes/CustomNode/CustomNode";
import { useNodeStore } from "../../stores/nodeStore";
import {
GraphAction,
- SEED_PROMPT_PREFIX,
buildSeedPrompt,
extractTextFromParts,
getActionKey,
@@ -42,192 +41,44 @@ interface UndoSnapshot {
restore: () => void;
}
-interface UseBuilderChatPanelArgs {
- isGraphLoaded?: boolean;
-}
+/**
+ * Per-graph session cache.
+ * Maps flowID → sessionId so the same chat session is reused each time the
+ * user opens the panel for a given graph, preserving conversation history.
+ * Lives at module scope to survive panel close/re-open without server round-trips.
+ */
+const graphSessionCache = new Map<string, string>();
-interface ApplyActionCallbacks {
- toast: ReturnType<typeof useToast>["toast"];
- setNodes: (nodes: CustomNode[]) => void;
- setEdges: (edges: CustomEdge[]) => void;
- setUndoStack: Dispatch<SetStateAction<UndoSnapshot[]>>;
- setAppliedActionKeys: Dispatch<SetStateAction<Set<string>>>;
+/** Clears the session cache. Exported only for use in tests. */
+export function clearGraphSessionCacheForTesting() {
+ graphSessionCache.clear();
}
-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;
+interface UseBuilderChatPanelArgs {
+ isGraphLoaded?: boolean;
+ onGraphEdited?: () => void;
}
/**
* 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.
+ * - Session management: creates or reuses a per-graph chat session, keyed by
+ * flowID so reopening the panel for the same graph continues the conversation.
* - 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.
+ * - Tool detection: watches for completed `edit_agent` and `run_agent` tool calls
+ * to trigger graph reload and run auto-follow respectively.
* - 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,
+ onGraphEdited,
}: UseBuilderChatPanelArgs = {}) {
const [isOpen, setIsOpen] = useState(false);
const [sessionId, setSessionId] = useState<string | null>(null);
@@ -240,35 +91,49 @@ export function useBuilderChatPanel({
// 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);
// Ref-based guard so the session-creation effect doesn't re-run (and cancel
// the in-flight request) when setIsCreatingSession triggers a re-render.
const isCreatingSessionRef = useRef(false);
+ // Tracks tool call IDs already handled to avoid firing callbacks twice when
+ // the messages array updates while status is "ready".
+ const processedToolCallsRef = useRef(new Set<string>());
+ // Guards against sending the seed message more than once per session.
+ const hasSentSeedMessageRef = useRef(false);
- const [{ flowID }] = useQueryStates({ flowID: parseAsString });
+ const [{ flowID }, setQueryStates] = useQueryStates({
+ flowID: parseAsString,
+ flowExecutionID: parseAsString,
+ });
const { toast } = useToast();
const nodes = useNodeStore(useShallow((s) => (isOpen ? s.nodes : [])));
- const edges = useEdgeStore(useShallow((s) => (isOpen ? s.edges : [])));
const setNodes = useNodeStore((s) => s.setNodes);
const setEdges = useEdgeStore((s) => s.setEdges);
- // Reset session and seed-sent guard when the user navigates to a different
- // graph so the new graph's context is sent to the AI on next open.
+ // When the user navigates to a different graph: restore the cached session for
+ // that graph (preserving conversation history) and reset per-session UI state.
+ // Messages are only cleared when there is no prior session for the new graph.
useEffect(() => {
- setSessionId(null);
+ const cachedSessionId = flowID
+ ? (graphSessionCache.get(flowID) ?? null)
+ : null;
+ setSessionId(cachedSessionId);
setSessionError(false);
setAppliedActionKeys(new Set());
setUndoStack([]);
setInputValue("");
- hasSentSeedMessageRef.current = false;
- // Also reset the creation ref so a new session can be started after
- // navigation, even if one was in-flight when flowID changed.
isCreatingSessionRef.current = false;
+ processedToolCallsRef.current = new Set();
+ hasSentSeedMessageRef.current = false;
+ if (!cachedSessionId) {
+ setMessages([]);
+ }
+ // setMessages is a stable function from useChat; excluding from deps is safe.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [flowID]);
+ // Create a new chat session when the panel opens and no session exists yet.
useEffect(() => {
if (!isOpen || sessionId || isCreatingSessionRef.current || sessionError)
return;
@@ -295,6 +160,8 @@ export function useBuilderChatPanel({
return;
}
setSessionId(id);
+ // Cache so this session is reused next time the same graph is opened.
+ if (flowID) graphSessionCache.set(flowID, id);
} else {
setSessionError(true);
}
@@ -352,29 +219,23 @@ export function useBuilderChatPanel({
transport: transport ?? undefined,
});
- // Keep a stable ref so the initialization effect can call sendMessage
- // without including it in the deps array (avoids re-triggering the effect).
+ // Keep a stable ref so callbacks can call sendMessage without it appearing
+ // in their dependency arrays.
sendMessageRef.current = sendMessage;
- // Clear messages from useChat when navigating to a different graph so stale
- // context from the prior session is not briefly visible in the panel UI.
+ // Send the seed message once per session when the session becomes available
+ // and the graph is loaded. The ref guard prevents duplicate sends when the
+ // effect re-runs due to dependency changes.
useEffect(() => {
- setMessages([]);
+ if (!sessionId || !isGraphLoaded || hasSentSeedMessageRef.current) return;
+ hasSentSeedMessageRef.current = true;
+ const edges = useEdgeStore.getState().edges;
+ const summary = serializeGraphForChat(nodes, edges);
+ sendMessageRef.current?.({ text: buildSeedPrompt(summary) });
+ // nodes is intentionally excluded: the seed only fires once per session and
+ // reading the live value here is sufficient. edges are read via getState().
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [flowID]);
-
- // ID of the seed message sent on panel open. Matched by content prefix rather
- // than message position so user messages are never accidentally suppressed.
- const seedMessageId = useMemo(() => {
- if (!hasSentSeedMessageRef.current) return null;
- return (
- messages.find(
- (m) =>
- m.role === "user" &&
- extractTextFromParts(m.parts).startsWith(SEED_PROMPT_PREFIX),
- )?.id ?? null
- );
- }, [messages]);
+ }, [sessionId, isGraphLoaded]);
// Parsed actions from all assistant messages, accumulated across turns.
// Gated on `status === "ready"` so parsing only runs on completed turns.
@@ -392,6 +253,39 @@ export function useBuilderChatPanel({
});
}, [messages, status]);
+ // Detect completed edit_agent and run_agent tool calls and act on them.
+ // edit_agent → trigger a graph reload via the onGraphEdited callback.
+ // run_agent → update flowExecutionID in the URL to auto-follow the new run.
+ useEffect(() => {
+ if (status !== "ready") return;
+ for (const msg of messages) {
+ if (msg.role !== "assistant") continue;
+ for (const part of msg.parts ?? []) {
+ if (part.type !== "dynamic-tool") continue;
+ const dynPart = part as {
+ type: "dynamic-tool";
+ toolName: string;
+ toolCallId: string;
+ state: string;
+ output?: unknown;
+ };
+ if (dynPart.state !== "output-available") continue;
+ if (processedToolCallsRef.current.has(dynPart.toolCallId)) continue;
+ processedToolCallsRef.current.add(dynPart.toolCallId);
+
+ if (dynPart.toolName === "edit_agent") {
+ onGraphEdited?.();
+ } else if (dynPart.toolName === "run_agent") {
+ const output = dynPart.output as Record<string, unknown> | null;
+ const execId = output?.execution_id;
+ if (typeof execId === "string" && execId) {
+ setQueryStates({ flowExecutionID: execId });
+ }
+ }
+ }
+ }
+ }, [messages, status, onGraphEdited, setQueryStates]);
+
// Close the panel on Escape so keyboard users can dismiss it quickly.
useEffect(() => {
if (!isOpen) return;
@@ -402,22 +296,6 @@ export function useBuilderChatPanel({
return () => document.removeEventListener("keydown", onKeyDown);
}, [isOpen]);
- // Send the seed message once per session. `nodes` and `edges` are included in
- // the dep array so this effect always has fresh data; the hasSentSeedMessageRef
- // guard ensures it only fires once even when the store updates.
- useEffect(() => {
- if (
- !sessionId ||
- !transport ||
- !isGraphLoaded ||
- hasSentSeedMessageRef.current
- )
- return;
- hasSentSeedMessageRef.current = true;
- const summary = serializeGraphForChat(nodes, edges);
- sendMessageRef.current?.({ text: buildSeedPrompt(summary) });
- }, [sessionId, transport, isGraphLoaded, nodes, edges]);
-
const isStreaming = status === "streaming" || status === "submitted";
const canSend =
Boolean(sessionId) && !isCreatingSession && !sessionError && !isStreaming;
@@ -428,7 +306,10 @@ export function useBuilderChatPanel({
// Resets session error state so the session-creation effect re-runs on
// the next render without toggling the panel closed and back open.
+ // Also evicts the stale cached session so a fresh one is created.
function retrySession() {
+ if (flowID) graphSessionCache.delete(flowID);
+ setSessionId(null);
setSessionError(false);
isCreatingSessionRef.current = false;
}
@@ -448,30 +329,179 @@ export function useBuilderChatPanel({
}
function handleApplyAction(action: GraphAction) {
- const cbs: ApplyActionCallbacks = {
- toast,
- setNodes,
- setEdges,
- setUndoStack,
- setAppliedActionKeys,
- };
- let applied = false;
if (action.type === "update_node_input") {
- applied = applyUpdateNodeInput(action, cbs);
+ // 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 &&
+ !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;
+ }
+ // 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);
} else if (action.type === "connect_nodes") {
- applied = applyConnectNodes(action, cbs);
+ // 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 &&
+ !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;
+ }
+ 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;
+ }
+ 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",
+ },
+ },
+ ]);
} else {
// Exhaustiveness guard — TypeScript ensures all GraphAction types are handled above.
const _: never = action;
return _;
}
- if (applied) {
- setAppliedActionKeys((prev) => {
- const next = new Set(prev);
- next.add(getActionKey(action));
- return next;
- });
- }
+ setAppliedActionKeys((prev) => {
+ const next = new Set(prev);
+ next.add(getActionKey(action));
+ return next;
+ });
}
function handleUndoLastAction() {
@@ -502,7 +532,6 @@ export function useBuilderChatPanel({
handleApplyAction,
undoStack,
handleUndoLastAction,
- seedMessageId,
// Input handling (owned here to keep component render-only)
inputValue,
setInputValue,
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/Flow.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/Flow.tsx
index 954e4b19d9..f21869b50f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/Flow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/Flow.tsx
@@ -34,7 +34,7 @@ export const Flow = () => {
flowExecutionID: parseAsString,
});
- const { data: graph } = useGetV1GetSpecificGraph(
+ const { data: graph, refetch: refetchGraph } = useGetV1GetSpecificGraph(
flowID ?? "",
{},
{
@@ -139,7 +139,7 @@ export const Flow = () => {
graphId={flowID || undefined}
/>
{isBuilderChatEnabled && (
- <BuilderChatPanel isGraphLoaded={isInitialLoadComplete} />
+ <BuilderChatPanel onGraphEdited={() => void refetchGraph()} />
)}
</div>
);