Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(canvas): keep edges, drop position and settings right on delete, drop and paste
trohitgd1cf3b03fc8d
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7cfc08b0..d7390507 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -882,7 +882,7 @@ const handleSave = useCallback(() => {#### NodeContextMenu Features- Rename (F2), Copy (Ctrl+C), Delete (Del) with keyboard shortcuts shown- Uses existing `useCopyPaste.copySelectedNodes()` for Copy-- Uses existing `onNodesDelete` for Delete+- Delete goes through `useReactFlowNodes.deleteNodeById` (React Flow's `deleteElements`), the same path as the Delete key, so the node's edges are removed too and `onEdgesDelete` reports them- Keyboard navigation (Arrow keys, Enter)- Click outside to close- Tailwind semantic tokens (no palette names)diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 44938dd8..f4687259 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -210,7 +210,7 @@ const DashboardContent: React.FC = () => {} = useWorkflowManagement();const { collapsedSections, searchQuery, setSearchQuery, toggleSection } = useComponentPalette();- const { saveNodeParameters, getAllNodeParameters, executeWorkflow, nodeStatuses, deploymentStatus, workflowControlStatuses, workflowControlPending, startWorkflow, pauseWorkflow, resumeWorkflow, resetWorkflow, getWorkflowControlStatus, workflowLock, isReady, sendRequest, clearNodeStatus } = useWebSocket();+ const { saveNodeParameters, getNodeParameters, getAllNodeParameters, executeWorkflow, nodeStatuses, deploymentStatus, workflowControlStatuses, workflowControlPending, startWorkflow, pauseWorkflow, resumeWorkflow, resetWorkflow, getWorkflowControlStatus, workflowLock, isReady, sendRequest, clearNodeStatus } = useWebSocket();// Workflows list: server-owned data, cached by TanStack Query.const queryClient = useQueryClient();@@ -257,7 +257,7 @@ const DashboardContent: React.FC = () => {return false;}, [canvasLock.locked, canvasLock.reason]);const [globalModelDefaults, setGlobalModelDefaults] = React.useState<{ provider: string; model: string } | null>(null);- const { onDragOver, onDrop, handleComponentDragStart } = useDragAndDrop({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId: currentWorkflow?.id ?? 'new' });+ const { onDragOver, onDrop, handleComponentDragStart } = useDragAndDrop({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId: currentWorkflow?.id ?? 'new', screenToFlowPosition: reactFlowInstance.screenToFlowPosition });// Palette drop creates nodes AND persists their default parameters —// an HTML5 drop that React Flow's nodesDraggable/Connectable cannot// block, so it goes through the shared guard.@@ -268,7 +268,7 @@ const DashboardContent: React.FC = () => {}onDrop(event);}, [guardCanvasEdit, onDrop]);- const { onConnect: baseOnConnect, onNodesDelete, onEdgesDelete: baseOnEdgesDelete } = useReactFlowNodes({ setNodes, setEdges, clearNodeStatus });+ const { onConnect: baseOnConnect, onNodesDelete, onEdgesDelete: baseOnEdgesDelete, deleteNodeById } = useReactFlowNodes({ setNodes, setEdges, clearNodeStatus });const { onConnect, onEdgesDelete } = useAutoSkillEdges({baseOnConnect,baseOnEdgesDelete,@@ -280,7 +280,7 @@ const DashboardContent: React.FC = () => {// Apply runtime canvas mutations pushed from the backend (e.g.,// Agent Builder tools called by the LLM mid-execution).useWorkflowOpsListener({ nodes, edges, setNodes, setEdges });- const { copySelectedNodes, pasteNodes } = useCopyPaste({ nodes, edges, setNodes, setEdges, saveNodeParameters, workflowId: currentWorkflow?.id ?? 'new' });+ const { copySelectedNodes, pasteNodes } = useCopyPaste({ nodes, edges, setNodes, setEdges, saveNodeParameters, getNodeParameters, workflowId: currentWorkflow?.id ?? 'new' });// Override all agent nodes to use the global model. Agent membership is// derived at call time from the backend-served `group` field — by the@@ -1089,10 +1089,10 @@ const DashboardContent: React.FC = () => {// The emptied deleteKeyCode only blocks the keyboard path — this// menu action bypassed the lock entirely before the shared guard.if (contextMenu && guardCanvasEdit()) {- onNodesDelete([nodes.find(n => n.id === contextMenu.nodeId)].filter(Boolean) as Node[]);+ deleteNodeById(contextMenu.nodeId);}closeContextMenu();- }, [contextMenu, guardCanvasEdit, nodes, onNodesDelete, closeContextMenu]);+ }, [contextMenu, guardCanvasEdit, deleteNodeById, closeContextMenu]);// Keyboard shortcut handler for workflow operationsuseEffect(() => {diff --git a/client/src/hooks/__tests__/useCopyPaste.test.ts b/client/src/hooks/__tests__/useCopyPaste.test.tsnew file mode 100644index 00000000..08f0caa0--- /dev/null+++ b/client/src/hooks/__tests__/useCopyPaste.test.ts@@ -0,0 +1,97 @@+/**+ * Locks what a pasted node is saved with.+ *+ * node.data holds only UI fields (the label), so it is never a node's+ * parameter row. Paste used to save node.data as the copy's parameters,+ * which left every pasted node with its configuration gone. The copy now+ * gets the original's saved parameters, read when it was copied, minus+ * runtime state (conversation, session ids, cached results).+ */++import { describe, it, expect, vi } from 'vitest';+import { act, renderHook } from '@testing-library/react';+import type { Node } from 'reactflow';+import { useCopyPaste } from '../useCopyPaste';++const original: Node = {+ id: 'wf:httpRequest:1',+ type: 'httpRequest',+ position: { x: 0, y: 0 },+ data: { label: 'Fetch Prices' },+ selected: true,+};++function setup(getNodeParameters: (id: string) => Promise<{ parameters: Record<string, any> } | null>) {+ const saveNodeParameters = vi.fn().mockResolvedValue(true);+ const setNodes = vi.fn();+ const setEdges = vi.fn();+ const hook = renderHook(() => useCopyPaste({+ nodes: [original],+ edges: [],+ setNodes,+ setEdges,+ saveNodeParameters,+ getNodeParameters,+ workflowId: 'wf',+ }));+ return { ...hook, saveNodeParameters, setNodes };+}++describe('useCopyPaste', () => {+ it("saves the original's parameters, without runtime state, under the new id", async () => {+ const getNodeParameters = vi.fn().mockResolvedValue({+ parameters: {+ url: 'https://example.com/prices',+ method: 'POST',+ label: 'Fetch Prices',+ last_result: { status: 200 },+ memory_content: 'a whole conversation',+ },+ });+ const { result, saveNodeParameters, setNodes } = setup(getNodeParameters);++ act(() => result.current.copySelectedNodes());+ await act(async () => {+ await result.current.pasteNodes();+ });++ expect(saveNodeParameters).toHaveBeenCalledTimes(1);+ const [newId, saved] = saveNodeParameters.mock.calls[0];+ expect(newId).not.toBe(original.id);+ expect(saved).toMatchObject({ url: 'https://example.com/prices', method: 'POST' });+ expect(saved).not.toHaveProperty('last_result');+ expect(saved).not.toHaveProperty('memory_content');++ // The saved label matches the pasted node's label.+ const pasted = (setNodes.mock.calls[0][0] as (nodes: Node[]) => Node[])([original]);+ const copy = pasted.find(n => n.id === newId)!;+ expect(saved.label).toBe(copy.data.label);+ });++ it('reads the parameters at copy time, not at paste time', async () => {+ const getNodeParameters = vi.fn().mockResolvedValue({ parameters: { url: 'https://a' } });+ const { result } = setup(getNodeParameters);++ act(() => result.current.copySelectedNodes());+ expect(getNodeParameters).toHaveBeenCalledWith(original.id);+ getNodeParameters.mockClear();++ await act(async () => {+ await result.current.pasteNodes();+ });+ expect(getNodeParameters).not.toHaveBeenCalled();+ });++ it('still saves a row with the label when the original could not be read', async () => {+ const { result, saveNodeParameters } = setup(vi.fn().mockResolvedValue(null));++ act(() => result.current.copySelectedNodes());+ await act(async () => {+ await result.current.pasteNodes();+ });++ const [, saved] = saveNodeParameters.mock.calls[0];+ expect(typeof saved.label).toBe('string');+ expect(saved.label.length).toBeGreaterThan(0);+ });+});diff --git a/client/src/hooks/__tests__/useDragAndDrop.test.ts b/client/src/hooks/__tests__/useDragAndDrop.test.tsnew file mode 100644index 00000000..bf2b7985--- /dev/null+++ b/client/src/hooks/__tests__/useDragAndDrop.test.ts@@ -0,0 +1,60 @@+/**+ * Locks where a palette drop places the new node.+ *+ * The position must come from React Flow's `screenToFlowPosition`, which+ * accounts for the pane's offset, pan and zoom. It used to be the pointer+ * minus the drop target's bounding rect, so a drop on a panned or zoomed+ * canvas landed somewhere else, and a drop onto an existing node measured+ * that node's rect.+ */++import { describe, it, expect, vi } from 'vitest';+import { act, renderHook } from '@testing-library/react';+import type { DragEvent } from 'react';+import type { Node } from 'reactflow';+import { useDragAndDrop } from '../useDragAndDrop';+import { snapToGrid } from '../../utils/workflow';+import { theme } from '../../styles/theme';++const existing: Node = { id: 'wf:start:1', type: 'start', position: { x: 0, y: 0 }, data: { label: 'Start' } };++function dropEvent(clientX: number, clientY: number) {+ return {+ preventDefault: vi.fn(),+ clientX,+ clientY,+ // A rect that would put the node far away if it were still used.+ target: { getBoundingClientRect: () => ({ left: 5000, top: 5000 }) },+ dataTransfer: { getData: () => JSON.stringify({ type: 'httpRequest', data: { url: '' } }) },+ } as unknown as DragEvent;+}++describe('useDragAndDrop.onDrop', () => {+ it('places the node at the canvas point under the pointer, honouring pan and zoom', async () => {+ // Pane at (100, 50), zoomed 2x, panned so canvas (500, 300) sits at the pane's corner.+ const screenToFlowPosition = vi.fn(({ x, y }: { x: number; y: number }) => ({+ x: (x - 100) / 2 + 500,+ y: (y - 50) / 2 + 300,+ }));+ const setNodes = vi.fn();+ const { result } = renderHook(() => useDragAndDrop({+ nodes: [existing],+ setNodes,+ saveNodeParameters: vi.fn().mockResolvedValue(true),+ workflowId: 'wf',+ screenToFlowPosition,+ }));++ await act(async () => {+ await result.current.onDrop(dropEvent(700, 450));+ });++ expect(screenToFlowPosition).toHaveBeenCalledWith({ x: 700, y: 450 });+ const added = (setNodes.mock.calls[0][0] as (nodes: Node[]) => Node[])([]);+ expect(added).toHaveLength(1);+ expect(added[0].position).toEqual(snapToGrid({+ x: 800 - theme.constants.dragOffset.x,+ y: 500 - theme.constants.dragOffset.y,+ }));+ });+});diff --git a/client/src/hooks/__tests__/useReactFlowNodes.test.tsx b/client/src/hooks/__tests__/useReactFlowNodes.test.tsxnew file mode 100644index 00000000..cc168ddb--- /dev/null+++ b/client/src/hooks/__tests__/useReactFlowNodes.test.tsx@@ -0,0 +1,93 @@+/**+ * Locks the node-delete path the canvas context menu uses.+ *+ * `deleteNodeById` must behave like the Delete key: remove the node AND+ * its edges, and report the removed edges through `onEdgesDelete` (which+ * is where auto-skill learns that a tool was disconnected). The context+ * menu used to call `onNodesDelete` directly, which removed only the node+ * and left its edges in the graph, where they were saved and later failed+ * Run / Start with DANGLING_EDGE.+ */++import { describe, it, expect, vi } from 'vitest';+import { act, render } from '@testing-library/react';+import ReactFlow, {+ ReactFlowProvider,+ useEdgesState,+ useNodesState,+ type Edge,+ type Node,+} from 'reactflow';+import { useReactFlowNodes } from '../useReactFlowNodes';++const initialNodes: Node[] = [+ { id: 'agent', position: { x: 0, y: 0 }, data: { label: 'Agent' } },+ { id: 'tool', position: { x: 0, y: 200 }, data: { label: 'Tool' } },+ { id: 'other', position: { x: 300, y: 0 }, data: { label: 'Other' } },+];+const initialEdges: Edge[] = [+ { id: 'tool-agent', source: 'tool', target: 'agent', targetHandle: 'input-tools' },+ { id: 'agent-other', source: 'agent', target: 'other' },+];++interface Exposed {+ deleteNodeById: (nodeId: string) => void;+ nodes: Node[];+ edges: Edge[];+}++function Harness({ exposed, onEdgesDelete }: { exposed: { current: Exposed | null }; onEdgesDelete: (edges: Edge[]) => void }) {+ const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);+ const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);+ const { onNodesDelete, deleteNodeById } = useReactFlowNodes({ setNodes, setEdges });+ exposed.current = { deleteNodeById, nodes, edges };+ return (+ <div style={{ width: 800, height: 600 }}>+ <ReactFlow+ nodes={nodes}+ edges={edges}+ onNodesChange={onNodesChange}+ onEdgesChange={onEdgesChange}+ onNodesDelete={onNodesDelete}+ onEdgesDelete={onEdgesDelete}+ />+ </div>+ );+}++describe('useReactFlowNodes.deleteNodeById', () => {+ it('removes the node together with its edges and reports the removed edges', () => {+ const exposed: { current: Exposed | null } = { current: null };+ const onEdgesDelete = vi.fn();+ render(+ <ReactFlowProvider>+ <Harness exposed={exposed} onEdgesDelete={onEdgesDelete} />+ </ReactFlowProvider>,+ );++ act(() => exposed.current!.deleteNodeById('tool'));++ expect(exposed.current!.nodes.map(n => n.id)).toEqual(['agent', 'other']);+ expect(exposed.current!.edges.map(e => e.id)).toEqual(['agent-other']);+ expect(onEdgesDelete).toHaveBeenCalledTimes(1);+ expect(onEdgesDelete.mock.calls[0][0].map((e: Edge) => e.id)).toEqual(['tool-agent']);+ });++ it('leaves no edge pointing at a deleted node with several connections', () => {+ const exposed: { current: Exposed | null } = { current: null };+ render(+ <ReactFlowProvider>+ <Harness exposed={exposed} onEdgesDelete={vi.fn()} />+ </ReactFlowProvider>,+ );++ act(() => exposed.current!.deleteNodeById('agent'));++ const ids = new Set(exposed.current!.nodes.map(n => n.id));+ expect(ids.has('agent')).toBe(false);+ for (const edge of exposed.current!.edges) {+ expect(ids.has(edge.source) && ids.has(edge.target)).toBe(true);+ }+ expect(exposed.current!.edges).toEqual([]);+ });+});diff --git a/client/src/hooks/useCopyPaste.ts b/client/src/hooks/useCopyPaste.tsindex fef412a3..f59098e5 100644--- a/client/src/hooks/useCopyPaste.ts+++ b/client/src/hooks/useCopyPaste.ts@@ -3,20 +3,52 @@ import { Node, Edge } from 'reactflow';import { generateUniqueLabel } from './useDragAndDrop';import { resolveNodeDescription } from '../lib/nodeSpec';import { nextNodeInstanceId } from '../utils/workflow';+import { withoutRuntimeKeys } from '../utils/parameterSanitizer';interface UseCopyPasteProps {nodes: Node[];edges: Edge[];setNodes: (nodes: Node[] | ((nodes: Node[]) => Node[])) => void;setEdges: (edges: Edge[] | ((edges: Edge[]) => Edge[])) => void;saveNodeParameters?: (nodeId: string, parameters: Record<string, any>) => Promise<boolean>;+ getNodeParameters?: (nodeId: string) => Promise<{ parameters: Record<string, any> } | null>;workflowId: string;}+type ParameterSnapshot = Record<string, Record<string, any> | null>;+interface ClipboardData {nodes: Node[];edges: Edge[];+ /** Saved parameters of each copied node, keyed by its id, read at copy+ * time so a later edit or delete of the original does not change what+ * gets pasted. `null` when a node's parameters could not be read. */+ parameters: Promise<ParameterSnapshot>;}+/** Spec defaults for a node type: what a fresh palette drop would save. */+const specDefaults = (nodeType: string): Record<string, any> => {+ const properties = resolveNodeDescription(nodeType)?.properties ?? [];+ return Object.fromEntries(properties.map((p) => [p.name, p.default]));+};++const snapshotParameters = async (+ nodes: Node[],+ getNodeParameters: UseCopyPasteProps['getNodeParameters'],+): Promise<ParameterSnapshot> => {+ const entries = await Promise.all(+ nodes.map(async (node): Promise<[string, Record<string, any> | null]> => {+ if (!getNodeParameters) return [node.id, null];+ try {+ const stored = await getNodeParameters(node.id);+ return [node.id, stored?.parameters ?? null];+ } catch {+ return [node.id, null];+ }+ }),+ );+ return Object.fromEntries(entries);+};+/*** Hook for copy/paste functionality with n8n-style auto-labeling.*@@ -31,6 +63,7 @@ export const useCopyPaste = ({setNodes,setEdges,saveNodeParameters,+ getNodeParameters,workflowId,}: UseCopyPasteProps) => {// In-memory clipboard (simpler than browser clipboard API)@@ -55,10 +88,11 @@ export const useCopyPaste = ({clipboardRef.current = {nodes: selectedNodes,edges: selectedEdges,+ parameters: snapshotParameters(selectedNodes, getNodeParameters),};console.log(`[CopyPaste] Copied ${selectedNodes.length} nodes and ${selectedEdges.length} edges`);- }, [nodes, edges]);+ }, [nodes, edges, getNodeParameters]);/*** Paste nodes from clipboard with offset and unique labels.@@ -70,6 +104,7 @@ export const useCopyPaste = ({}const { nodes: copiedNodes, edges: copiedEdges } = clipboardRef.current;+ const copiedParameters = await clipboardRef.current.parameters;// Generate ID mapping (old ID -> new ID)const idMap = new Map<string, string>();@@ -112,10 +147,14 @@ export const useCopyPaste = ({},};- // Save parameters for new node to database- if (saveNodeParameters && newNode.data) {+ // Save the original's configuration under the new id. node.data holds+ // only UI fields, so it is never the parameter row; when the original's+ // row could not be read, fall back to what a fresh drop would save.+ if (saveNodeParameters) {+ const source = copiedParameters[node.id];+ const parameters = source ? withoutRuntimeKeys(source) : specDefaults(node.type!);try {- await saveNodeParameters(newId, newNode.data);+ await saveNodeParameters(newId, { ...parameters, label: uniqueLabel });} catch (error) {console.error(`[CopyPaste] Failed to save parameters for ${newId}:`, error);}diff --git a/client/src/hooks/useDragAndDrop.ts b/client/src/hooks/useDragAndDrop.tsindex 501e2036..41ffbbb2 100644--- a/client/src/hooks/useDragAndDrop.ts+++ b/client/src/hooks/useDragAndDrop.ts@@ -20,6 +20,9 @@ interface UseDragAndDropProps {saveNodeParameters?: (nodeId: string, parameters: Record<string, any>) => Promise<boolean>;globalModelDefaults?: { provider: string; model: string } | null;workflowId: string;+ /** React Flow's `screenToFlowPosition`: turns a pointer position into+ * canvas coordinates, accounting for the pane's offset, pan and zoom. */+ screenToFlowPosition: (position: { x: number; y: number }) => { x: number; y: number };}/**@@ -48,7 +51,7 @@ export const generateUniqueLabel = (displayName: string, nodeType: string, existreturn `${displayName} ${suffix}`;};-export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId }: UseDragAndDropProps) => {+export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId, screenToFlowPosition }: UseDragAndDropProps) => {const onDragOver = useCallback((event: React.DragEvent) => {event.preventDefault();event.dataTransfer.dropEffect = 'move';@@ -64,11 +67,14 @@ export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModereturn;}- const reactFlowBounds = (event.target as Element).getBoundingClientRect();+ // Canvas coordinates under the pointer. The drop target's own rect+ // is not used: it ignores pan and zoom, and when the drop lands on+ // an existing node it is that node's rect, not the canvas's.+ const pointer = screenToFlowPosition({ x: event.clientX, y: event.clientY });let position = {- x: event.clientX - reactFlowBounds.left - theme.constants.dragOffset.x,- y: event.clientY - reactFlowBounds.top - theme.constants.dragOffset.y,+ x: pointer.x - theme.constants.dragOffset.x,+ y: pointer.y - theme.constants.dragOffset.y,};// Snap to grid for better alignment@@ -118,7 +124,7 @@ export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModeconsole.error('Error dropping node:', error);}},- [setNodes, nodes, saveNodeParameters, globalModelDefaults, workflowId]+ [setNodes, nodes, saveNodeParameters, globalModelDefaults, workflowId, screenToFlowPosition]);const handleComponentDragStart = useCallback((event: React.DragEvent, definition: any) => {diff --git a/client/src/hooks/useReactFlowNodes.ts b/client/src/hooks/useReactFlowNodes.tsindex 9ef0a547..a327be99 100644--- a/client/src/hooks/useReactFlowNodes.ts+++ b/client/src/hooks/useReactFlowNodes.ts@@ -1,5 +1,5 @@import { useCallback } from 'react';-import { Node, Edge, addEdge, Connection } from 'reactflow';+import { Node, Edge, addEdge, Connection, useReactFlow } from 'reactflow';import { useAppStore } from '../store/useAppStore';import { INodeInputDefinition, INodeOutputDefinition, NodeConnectionType } from '../types/INodeProperties';@@ -215,9 +215,23 @@ export const useReactFlowNodes = ({ setNodes, setEdges, clearNodeStatus }: UseRe[setEdges]);+ // Delete one node the way the Delete key does. React Flow's+ // `deleteElements` also removes the node's edges and calls both+ // `onEdgesDelete` (so auto-skill sees the disconnect) and `onNodesDelete`.+ // Calling `onNodesDelete` directly removes only the node and leaves its+ // edges behind.+ const { deleteElements } = useReactFlow();+ const deleteNodeById = useCallback(+ (nodeId: string) => {+ deleteElements({ nodes: [{ id: nodeId }] });+ },+ [deleteElements]+ );+return {onConnect,onNodesDelete,onEdgesDelete,+ deleteNodeById,};};diff --git a/client/src/utils/parameterSanitizer.ts b/client/src/utils/parameterSanitizer.tsindex a4ea0af0..da4b4581 100644--- a/client/src/utils/parameterSanitizer.ts+++ b/client/src/utils/parameterSanitizer.ts@@ -136,6 +136,17 @@ function isRuntimeKey(key: string): boolean {return RUNTIME_KEYS.has(normalizeKey(key));}+/**+ * Drop the top-level runtime keys and keep everything else, credentials+ * included. For copying a node within the same install: the copy keeps the+ * original's configuration but must not share its conversation or session.+ */+export function withoutRuntimeKeys(params: Record<string, any>): Record<string, any> {+ return Object.fromEntries(+ Object.entries(params).filter(([key]) => !isRuntimeKey(key)),+ );+}+/*** Deep-strip sensitive and runtime keys from a parameter object.* Returns a new object with sensitive values removed.