Skip to content

Self-improving AI Employees for everyone

fix(canvas): preserve employee workflow when entering dev mode

trohitgd301da0f660e
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index 1d95f25c..2c54783d 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -5,8 +5,6 @@ import {
ReactFlow,
ReactFlowProvider,
Controls,
- useNodesState,
- useEdgesState,
useReactFlow,
ConnectionMode,
ConnectionLineType,
@@ -58,10 +56,7 @@ import {
useWebSocket,
type WorkflowStartResult,
} from './contexts/WebSocketContext';
-import {
- sanitizeNodesForComparison,
- sanitizeEdgesForComparison,
-} from './utils/workflow';
+import { useWorkflowCanvas } from './hooks/useWorkflowCanvas';
import { importWorkflowFromFile } from './utils/workflowExport';
import type { ValidationIssue } from './hooks/useWorkflowValidation';
import { buildCanvasStyles } from './styles/canvasAnimations';
@@ -158,9 +153,6 @@ const moduleEdgeTypes = {
smoothstep: StepEdge,
};
-const initialNodes: Node[] = [];
-const initialEdges: Edge[] = [];
-
// Inner component that uses useReactFlow() - must be inside ReactFlowProvider
const DashboardContent: React.FC = () => {
const theme = useAppTheme();
@@ -172,7 +164,6 @@ const DashboardContent: React.FC = () => {
const hasUnsavedChanges = useAppStore((s) => s.hasUnsavedChanges);
const sidebarVisible = useAppStore((s) => s.sidebarVisible);
const componentPaletteVisible = useAppStore((s) => s.componentPaletteVisible);
- const updateWorkflow = useAppStore((s) => s.updateWorkflow);
const loadWorkflow = useAppStore((s) => s.loadWorkflow);
const createNewWorkflow = useAppStore((s) => s.createNewWorkflow);
const deleteWorkflow = useAppStore((s) => s.deleteWorkflow);
@@ -204,8 +195,8 @@ const DashboardContent: React.FC = () => {
// run in the app shell (app/AppShell), so they hold on either screen.
// ReactFlow state management (local state for performance)
- const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
- const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
+ const { nodes, setNodes, onNodesChange, edges, setEdges, onEdgesChange } =
+ useWorkflowCanvas(theme.constants.debounceDelay.workflowUpdate);
// ReactFlow instance for viewport control (n8n pattern - per-workflow viewport)
const reactFlowInstance = useReactFlow();
@@ -1006,79 +997,24 @@ const DashboardContent: React.FC = () => {
}
}, [queryClient, currentWorkflow, loadWorkflow, createNewWorkflow, migrateCurrentWorkflow]);
- // Sync workflow state → ReactFlow state (when loading workflows or data changes)
- // Note: Database is the source of truth for parameters - node.data should NOT store parameters
- // Parameters are loaded from database when parameter panel opens (useParameterPanel hook)
- // and when backend executes nodes (NodeExecutor._prepare_parameters)
- useEffect(() => {
- if (currentWorkflow && currentWorkflow.id) {
- const workflowNodes = currentWorkflow.nodes || [];
- setNodes(workflowNodes);
- setEdges(currentWorkflow.edges || []);
- // Do NOT sync database parameters to node.data
- // Database is the single source of truth for parameters
- // This prevents dual storage issues where node.data could diverge from database
- }
- }, [currentWorkflow?.id, currentWorkflow?.lastModified, setNodes, setEdges]);
-
- // Sync ReactFlow state → workflow state (debounced for performance)
- useEffect(() => {
- if (!currentWorkflow || !currentWorkflow.id) return;
-
- const timeoutId = setTimeout(() => {
- try {
- const currentNodesStr = JSON.stringify(sanitizeNodesForComparison(nodes));
- const currentEdgesStr = JSON.stringify(sanitizeEdgesForComparison(edges));
- const workflowNodesStr = JSON.stringify(sanitizeNodesForComparison(currentWorkflow.nodes || []));
- const workflowEdgesStr = JSON.stringify(sanitizeEdgesForComparison(currentWorkflow.edges || []));
-
- if (currentNodesStr !== workflowNodesStr || currentEdgesStr !== workflowEdgesStr) {
- console.log('[Dashboard] Syncing ReactFlow -> Store', {
- reactFlowEdgeCount: edges.length,
- storeEdgeCount: (currentWorkflow.edges || []).length,
- newEdges: edges.filter(e => !(currentWorkflow.edges || []).find(we => we.id === e.id))
- });
- updateWorkflow({ nodes, edges });
- }
- } catch (error) {
- console.warn('Failed to sync workflow state:', error);
- }
- }, theme.constants.debounceDelay.workflowUpdate);
-
- return () => clearTimeout(timeoutId);
- }, [nodes, edges, currentWorkflow?.id, updateWorkflow]);
+ // Track previous workflow ID for viewport save/restore (n8n pattern)
+ const prevWorkflowIdRef = React.useRef<string | null>(null);
+ // Track if we've already restored viewport for current workflow (prevent duplicate restores)
+ const viewportRestoredForRef = React.useRef<string | null>(null);
- // Leaving the editor (switching to Normal mode) unmounts it. The last
- // canvas edits may still be inside the debounce window above, so flush
- // them into the store, and keep the viewport for the next visit.
- const latestCanvasRef = React.useRef({ nodes, edges });
- useEffect(() => {
- latestCanvasRef.current = { nodes, edges };
- }, [nodes, edges]);
+ // Save only the viewport this mounted editor actually restored. The
+ // StrictMode startup cleanup must not replace a saved viewport with the
+ // default origin, nor assign an outgoing viewport to a newly loaded graph.
useEffect(() => () => {
+ const id = prevWorkflowIdRef.current;
const store = useAppStore.getState();
- const workflow = store.currentWorkflow;
- if (!workflow?.id) return;
- const latest = latestCanvasRef.current;
- try {
- const changed =
- JSON.stringify(sanitizeNodesForComparison(latest.nodes)) !== JSON.stringify(sanitizeNodesForComparison(workflow.nodes || []))
- || JSON.stringify(sanitizeEdgesForComparison(latest.edges)) !== JSON.stringify(sanitizeEdgesForComparison(workflow.edges || []));
- if (changed) store.updateWorkflow({ nodes: latest.nodes, edges: latest.edges });
- } catch (error) {
- console.warn('Failed to flush canvas state on unmount:', error);
- }
+ if (!id || store.currentWorkflow?.id !== id || viewportRestoredForRef.current !== id) return;
try {
- store.setWorkflowViewport(workflow.id, reactFlowInstance.getViewport());
+ store.setWorkflowViewport(id, reactFlowInstance.getViewport());
} catch {
- // The viewport is a convenience; a failed read keeps the last one.
+ // Keep the last known viewport if ReactFlow is already disposed.
}
- }, []);
-
- // Track previous workflow ID for viewport save/restore (n8n pattern)
- const prevWorkflowIdRef = React.useRef<string | null>(null);
- // Track if we've already restored viewport for current workflow (prevent duplicate restores)
- const viewportRestoredForRef = React.useRef<string | null>(null);
+ }, [reactFlowInstance]);
// Save viewport when switching workflows, restore after nodes load (n8n pattern)
useEffect(() => {
diff --git a/client/src/app/__tests__/shellActions.test.ts b/client/src/app/__tests__/shellActions.test.ts
index 927cdffa..8a65c7fb 100644
--- a/client/src/app/__tests__/shellActions.test.ts
+++ b/client/src/app/__tests__/shellActions.test.ts
@@ -34,6 +34,9 @@ import { useAppStore } from '../../store/useAppStore';
import { useWorkflowSettingsStore } from '../../stores/workflowSettingsStore';
import { defaultSettings } from '../../components/ui/settingsPanel/schema';
import { enterDev, enterNormal, toggleShellMode } from '../useShellActions';
+import { useHomeStore } from '../../features/home/state/homeStore';
+import { queryClient } from '../../lib/queryClient';
+import { EMPLOYEES_QUERY_KEY } from '../../features/home/data/employees';
const workflow = (id: string, name = `Workflow ${id}`) => ({
id,
@@ -65,6 +68,8 @@ beforeEach(() => {
events.length = 0;
toastError.mockReset();
useWorkflowSettingsStore.setState({ settings: { ...defaultSettings } });
+ useHomeStore.setState({ view: { kind: 'hire' }, workspaceOpen: false, workspaceFor: null });
+ queryClient.removeQueries({ queryKey: EMPLOYEES_QUERY_KEY });
});
afterEach(() => {
@@ -72,6 +77,49 @@ afterEach(() => {
});
describe('enterDev', () => {
+ it('uses the current Home employee when the caller supplies no ID', async () => {
+ setEditor();
+ useHomeStore.getState().showEmployee('b');
+ await enterDev();
+ expect(events).toContain('load:b');
+ expect(useAppStore.getState().currentWorkflow?.id).toBe('b');
+ });
+
+ it('gives an explicit workflow priority over Home selection', async () => {
+ setEditor();
+ useHomeStore.getState().showEmployee('b');
+ await enterDev({ workflowId: 'c' });
+ expect(events).toContain('load:c');
+ expect(events).not.toContain('load:b');
+ });
+
+ it.each([['b', 'b'], [null, 'c'], ['removed', 'c']])(
+ 'follows the visible Workspace from Hire (selection %s)', async (workspaceFor, expected) => {
+ setEditor();
+ useHomeStore.setState({ workspaceOpen: true, workspaceFor });
+ queryClient.setQueryData(EMPLOYEES_QUERY_KEY, [{ workflow_id: 'c' }, { workflow_id: 'b' }]);
+ await enterDev();
+ expect(events).toContain(`load:${expected}`);
+ },
+ );
+
+ it('does not change employees because of a closed Workspace', async () => {
+ setEditor();
+ useHomeStore.setState({ workspaceFor: 'b' });
+ await enterDev();
+ expect(events).toEqual(['preload', 'transition:dev']);
+ });
+
+ it('stays in Home when the loader resolves without loading the requested employee', async () => {
+ setEditor();
+ useAppStore.setState({ loadWorkflow: vi.fn(async () => {}) });
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ await enterDev({ workflowId: 'b' });
+ expect(events).not.toContain('transition:dev');
+ expect(toastError).toHaveBeenCalledTimes(1);
+ expect(useAppStore.getState().currentWorkflow?.id).toBe('a');
+ });
+
it('warms the editor and switches, opening nothing new', async () => {
setEditor();
await enterDev();
@@ -142,6 +190,14 @@ describe('enterDev', () => {
});
describe('enterNormal and toggle', () => {
+ it('keyboard switching opens the employee selected in Home', async () => {
+ setEditor();
+ useHomeStore.getState().showEmployee('b');
+ await toggleShellMode();
+ expect(events).toContain('load:b');
+ expect(useAppStore.getState().currentWorkflow?.id).toBe('b');
+ });
+
it('switches to Normal, keeping unsaved editor work in the store', async () => {
setEditor({ unsaved: true });
useAppStore.setState({ shellMode: 'dev' });
diff --git a/client/src/app/useShellActions.ts b/client/src/app/useShellActions.ts
index 8954a9de..64c811bc 100644
--- a/client/src/app/useShellActions.ts
+++ b/client/src/app/useShellActions.ts
@@ -13,6 +13,10 @@
import { useMemo } from 'react';
import { toast } from 'sonner';
import { SPIKE, spikeOrb } from '../features/home/orb/orb';
+import { useHomeStore } from '../features/home/state/homeStore';
+import { EMPLOYEES_QUERY_KEY } from '../features/home/data/employees';
+import type { EmployeeSummary } from '../features/home/data/schemas';
+import { queryClient } from '../lib/queryClient';
import { featureFlags } from '../lib/featureFlags';
import { useAppStore } from '../store/useAppStore';
import { useWorkflowSettingsStore } from '../stores/workflowSettingsStore';
@@ -24,6 +28,17 @@ export interface EnterDevOptions {
workflowId?: string;
}
+/** Match the employee Home actually displays, including its Workspace dock. */
+function homeWorkflowId(): string | undefined {
+ if (useAppStore.getState().shellMode !== 'normal') return undefined;
+ const { view, workspaceOpen, workspaceFor } = useHomeStore.getState();
+ if (view.kind === 'employee') return view.workflowId;
+ if (!workspaceOpen) return undefined;
+ const team = queryClient.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY);
+ return team?.find((employee) => employee.workflow_id === workspaceFor)?.workflow_id
+ ?? team?.[0]?.workflow_id ?? workspaceFor ?? undefined;
+}
+
/** Keep, save, or refuse the editor's unsaved work before it is replaced.
* False means the switch must not happen. */
async function settleUnsavedWork(nextWorkflowId: string): Promise<boolean> {
@@ -48,13 +63,18 @@ async function settleUnsavedWork(nextWorkflowId: string): Promise<boolean> {
export async function enterDev(options: EnterDevOptions = {}): Promise<void> {
if (!featureFlags.normalMode) return;
- const { workflowId } = options;
+ const workflowId = options.workflowId ?? homeWorkflowId();
if (workflowId && !(await settleUnsavedWork(workflowId))) return;
const opening = workflowId && useAppStore.getState().currentWorkflow?.id !== workflowId
? useAppStore.getState().loadWorkflow(workflowId)
: Promise.resolve();
try {
await Promise.all([opening, preloadEditor()]);
+ // The store's loader also resolves on a null API response. Opening the
+ // old employee in that case would make a failed selection look successful.
+ if (workflowId && useAppStore.getState().currentWorkflow?.id !== workflowId) {
+ throw new Error('The requested employee workflow did not load');
+ }
} catch (error) {
console.error('[Shell] Could not open the editor:', error);
toast.error('Could not open the workflow. Check the connection and try again.');
diff --git a/client/src/components/shell/ModeToggle.tsx b/client/src/components/shell/ModeToggle.tsx
index 7b9f2686..a7ac99d6 100644
--- a/client/src/components/shell/ModeToggle.tsx
+++ b/client/src/components/shell/ModeToggle.tsx
@@ -4,7 +4,8 @@
* the agent role's purple, each as the soft chip tint. Switching goes
* through the shell actions, so the unsaved-work guard and the transition
* always run. `workflowId`: the workflow Dev opens (Home passes the
- * employee on screen); without one Dev shows what the editor last had.
+ * employee on screen); without one the shell resolves Home's visible employee
+ * or Workspace, then falls back to what the editor last had.
*/
import { Clock, Zap } from 'lucide-react';
diff --git a/client/src/hooks/__tests__/useWorkflowCanvas.test.tsx b/client/src/hooks/__tests__/useWorkflowCanvas.test.tsx
new file mode 100644
index 00000000..a3098a79
--- /dev/null
+++ b/client/src/hooks/__tests__/useWorkflowCanvas.test.tsx
@@ -0,0 +1,103 @@
+import { StrictMode, type ReactNode } from 'react';
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useAppStore, type WorkflowData } from '../../store/useAppStore';
+import { useWorkflowCanvas } from '../useWorkflowCanvas';
+
+function workflow(id: string, label = id): WorkflowData {
+ return {
+ id, name: label, slug: label, createdAt: new Date(0), lastModified: new Date(0),
+ nodes: [
+ { id: `${id}:agent`, type: 'aiAgent', position: { x: 100, y: 200 }, data: { label } },
+ { id: `${id}:reply`, type: 'chatReply', position: { x: 400, y: 200 }, data: {} },
+ ],
+ edges: [{ id: `${id}:edge`, source: `${id}:agent`, target: `${id}:reply` }],
+ };
+}
+
+const wrapper = ({ children }: { children: ReactNode }) => <StrictMode>{children}</StrictMode>;
+const mount = () => renderHook(() => useWorkflowCanvas(100), { wrapper });
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ useAppStore.setState({ currentWorkflow: workflow('a'), hasUnsavedChanges: false, selectedNode: null, workflowUIStates: {} });
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe('employee canvas ownership', () => {
+ it('keeps the preloaded graph through StrictMode mount, debounce, and cleanup', () => {
+ const original = useAppStore.getState().currentWorkflow;
+ const { result, unmount } = mount();
+ expect(result.current.nodes).toEqual(original!.nodes);
+ expect(result.current.edges).toEqual(original!.edges);
+ act(() => vi.advanceTimersByTime(1_000));
+ unmount();
+ expect(useAppStore.getState().currentWorkflow).toBe(original);
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(false);
+ });
+
+ it('flushes edits made just before leaving Dev and preserves them on returning', () => {
+ const first = mount();
+ act(() => first.result.current.setNodes(nodes => nodes.map(node => ({ ...node, position: { x: 900, y: 100 } }))));
+ first.unmount();
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(true);
+ const second = mount();
+ expect(second.result.current.nodes[0].position).toEqual({ x: 900, y: 100 });
+ act(() => vi.advanceTimersByTime(100));
+ expect(useAppStore.getState().currentWorkflow!.nodes[0].position).toEqual({ x: 900, y: 100 });
+ });
+
+ it('shows the next employee without flushing the previous canvas into it', () => {
+ const { result } = mount();
+ act(() => result.current.setNodes(nodes => nodes.slice(0, 1)));
+ const next = workflow('b');
+ act(() => useAppStore.setState({ currentWorkflow: next, hasUnsavedChanges: false }));
+ expect(result.current.nodes).toEqual(next.nodes);
+ expect(result.current.edges).toEqual(next.edges);
+ act(() => vi.advanceTimersByTime(1_000));
+ expect(useAppStore.getState().currentWorkflow).toBe(next);
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(false);
+ });
+
+ it.each(['a', 'b'])('does not overwrite a newer %s snapshot if it arrives immediately before unmount', (id) => {
+ const { result, unmount } = mount();
+ act(() => result.current.setNodes(nodes => nodes.slice(0, 1)));
+ const incoming = workflow(id, 'new saved graph');
+ act(() => {
+ useAppStore.setState({ currentWorkflow: incoming, hasUnsavedChanges: false });
+ unmount();
+ });
+ expect(useAppStore.getState().currentWorkflow).toBe(incoming);
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(false);
+ });
+
+ it('adopts a same-ID reload even when its modification timestamp is unchanged', () => {
+ const { result } = mount();
+ const incoming = workflow('a', 'updated');
+ act(() => useAppStore.setState({ currentWorkflow: incoming }));
+ expect(result.current.nodes[0].data.label).toBe('updated');
+ act(() => vi.advanceTimersByTime(100));
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(false);
+ });
+
+ it('persists an intentional deletion of every node', () => {
+ const { result } = mount();
+ act(() => {
+ result.current.setNodes([]);
+ result.current.setEdges([]);
+ });
+ act(() => vi.advanceTimersByTime(100));
+ expect(useAppStore.getState().currentWorkflow).toMatchObject({ nodes: [], edges: [] });
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(true);
+ });
+
+ it('does not mark a node selection as a graph edit', () => {
+ const { result } = mount();
+ act(() => result.current.onNodesChange([{ id: 'a:agent', type: 'select', selected: true }]));
+ act(() => vi.advanceTimersByTime(100));
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(false);
+ });
+});
diff --git a/client/src/hooks/useWorkflowCanvas.ts b/client/src/hooks/useWorkflowCanvas.ts
new file mode 100644
index 00000000..0d355272
--- /dev/null
+++ b/client/src/hooks/useWorkflowCanvas.ts
@@ -0,0 +1,49 @@
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { useEdgesState, useNodesState } from 'reactflow';
+import { useAppStore } from '../store/useAppStore';
+import { sanitizeEdgesForComparison, sanitizeNodesForComparison } from '../utils/workflow';
+
+/** Local ReactFlow edits belong to the exact workflow snapshot they came from. */
+export function useWorkflowCanvas(debounceMs: number) {
+ const workflow = useAppStore((state) => state.currentWorkflow);
+ const [source, setSource] = useState(workflow);
+ const [nodes, setNodes, onNodesChange] = useNodesState(workflow?.nodes ?? []);
+ const [edges, setEdges, onEdgesChange] = useEdgesState(workflow?.edges ?? []);
+
+ // Adopt a loaded/saved graph before committing a render. Hydrating in an
+ // effect leaves an empty (or previous employee's) graph available to the
+ // outgoing-state cleanup, including StrictMode's initial effect replay.
+ if (source !== workflow) {
+ setSource(workflow);
+ setNodes(workflow?.nodes ?? []);
+ setEdges(workflow?.edges ?? []);
+ }
+
+ const latest = useRef({ source, nodes, edges });
+ useLayoutEffect(() => {
+ latest.current = { source, nodes, edges };
+ }, [source, nodes, edges]);
+
+ const flush = useCallback(() => {
+ const snapshot = latest.current;
+ const store = useAppStore.getState();
+ // A load may finish just before unmount, before React commits its new
+ // graph. Never flush the outgoing editor into that newer store snapshot,
+ // even when the new snapshot has the same workflow ID.
+ if (!snapshot.source || store.currentWorkflow !== snapshot.source) return;
+ const changed =
+ JSON.stringify(sanitizeNodesForComparison(snapshot.nodes)) !== JSON.stringify(sanitizeNodesForComparison(snapshot.source.nodes))
+ || JSON.stringify(sanitizeEdgesForComparison(snapshot.edges)) !== JSON.stringify(sanitizeEdgesForComparison(snapshot.source.edges));
+ if (changed) store.updateWorkflow({ nodes: snapshot.nodes, edges: snapshot.edges });
+ }, []);
+
+ useEffect(() => {
+ const timer = setTimeout(flush, debounceMs);
+ return () => clearTimeout(timer);
+ }, [source, nodes, edges, debounceMs, flush]);
+
+ // Preserve edits made just before leaving Dev, without waiting for debounce.
+ useEffect(() => flush, [flush]);
+
+ return { nodes, setNodes, onNodesChange, edges, setEdges, onEdgesChange };
+}