Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(workflows): keep unsaved edits through Start, switching and failed saves
trohitg62ee9346307c
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 23ab3825..e3081064 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -17,6 +17,7 @@ import { featureFlags } from './lib/featureFlags';import { deriveCanvasLock } from './lib/canvasLock';import { AGENT_PHASE } from './lib/agentPhases';import { CanvasEditGuardContext } from './contexts/canvasEditGuard';+import { settleUnsavedWork } from './app/unsavedWork';import { prefetchAllNodeSpecs, listCachedNodeSpecs, cachedNodeSpecTypesKey } from './lib/nodeSpec';import AIAgentNode from './components/AIAgentNode';import SquareNode from './components/SquareNode';@@ -337,11 +338,7 @@ const DashboardContent: React.FC = () => {? authoritativeNodes.find((node) => node.id === selectedId) ?? null: null;- store.setCurrentWorkflow({- ...workflow,- nodes: authoritativeNodes,- edges: authoritativeEdges,- });+ store.adoptStartedGraph(workflowId, authoritativeNodes, authoritativeEdges);store.setSelectedNode(canonicalSelection);setNodes(authoritativeNodes);setEdges(authoritativeEdges);@@ -738,6 +735,7 @@ const DashboardContent: React.FC = () => {// deploy it so the chat trigger is live. Shared by the wizard's finish// button and the Get Started checklist.const handleRunExample = React.useCallback(async () => {+ if (!(await settleUnsavedWork())) return;const workflow = await openExampleAndChat('AI Assistant');if (!workflow) return;@@ -848,6 +846,9 @@ const DashboardContent: React.FC = () => {// backend `import_workflow` orchestrator. This UI is reduced to// file pick + user prompts + view switch.const imported = await importWorkflowFromFile(file);+ // The import opens the new workflow in place of this one, so this+ // one's unsaved changes are settled before anything is created.+ if (!(await settleUnsavedWork())) return;const proposedName = imported.name || 'Imported Workflow';let response = await sendRequest<ImportWorkflowResponse>('import_workflow', {diff --git a/client/src/app/__tests__/shellActions.test.ts b/client/src/app/__tests__/shellActions.test.tsindex 8a65c7fb..efbe702f 100644--- a/client/src/app/__tests__/shellActions.test.ts+++ b/client/src/app/__tests__/shellActions.test.ts@@ -48,7 +48,11 @@ const workflow = (id: string, name = `Workflow ${id}`) => ({lastModified: new Date(),});-function setEditor({ current = 'a', unsaved = false, saveFails = false } = {}) {+type SaveOutcome = 'saved' | 'failed' | 'changedWhileSaving';++function setEditor(+ { current = 'a', unsaved = false, save = 'saved' }: { current?: string; unsaved?: boolean; save?: SaveOutcome } = {},+) {useAppStore.setState({currentWorkflow: workflow(current),hasUnsavedChanges: unsaved,@@ -59,7 +63,14 @@ function setEditor({ current = 'a', unsaved = false, saveFails = false } = {}) {}),saveWorkflow: vi.fn(async () => {events.push('save');- if (!saveFails) useAppStore.setState({ hasUnsavedChanges: false });+ if (save === 'failed') {+ // As the store does: a save that did not happen explains itself.+ toastError('Could not save');+ return false;+ }+ // A newer edit keeps the changes marked unsaved after a good save.+ if (save === 'saved') useAppStore.setState({ hasUnsavedChanges: false });+ return true;}),});}@@ -160,14 +171,22 @@ describe('enterDev', () => {expect(events.at(-1)).toBe('transition:dev');});- it('keeps the editor on its workflow when the save fails', async () => {- setEditor({ unsaved: true, saveFails: true });+ it('keeps the editor on its workflow when the save fails, with one message', async () => {+ setEditor({ unsaved: true, save: 'failed' });await enterDev({ workflowId: 'b' });expect(events).toEqual(['save']);expect(toastError).toHaveBeenCalledTimes(1);expect(useAppStore.getState().currentWorkflow?.id).toBe('a');});+ it('keeps the editor on its workflow when it changed while saving', async () => {+ setEditor({ unsaved: true, save: 'changedWhileSaving' });+ await enterDev({ workflowId: 'b' });+ expect(events).toEqual(['save']);+ expect(toastError).toHaveBeenCalledWith(expect.stringContaining('changed while it was saving'));+ expect(useAppStore.getState().currentWorkflow?.id).toBe('a');+ });+it('does not save when reopening the workflow already in the editor', async () => {setEditor({ unsaved: true });await enterDev({ workflowId: 'a' });diff --git a/client/src/app/unsavedWork.ts b/client/src/app/unsavedWork.tsnew file mode 100644index 00000000..b97849e6--- /dev/null+++ b/client/src/app/unsavedWork.ts@@ -0,0 +1,39 @@+/**+ * The editor keeps its working copy of one workflow in the app store.+ * Everything that replaces it with another workflow (the mode switch, the+ * workflow sidebar, New) settles its unsaved changes first: they are saved+ * when the auto-save preference is on (the default) and asked about+ * otherwise.+ */++import { toast } from 'sonner';+import { useAppStore } from '../store/useAppStore';+import { useWorkflowSettingsStore } from '../stores/workflowSettingsStore';++/** Keep, save, or refuse the editor's unsaved work before another workflow+ * replaces it. False means the replacement must not happen. Pass the+ * workflow about to open; reopening the current one settles nothing. */+export async function settleUnsavedWork(nextWorkflowId?: string): Promise<boolean> {+ const { currentWorkflow, hasUnsavedChanges, saveWorkflow } = useAppStore.getState();+ if (!hasUnsavedChanges || !currentWorkflow || currentWorkflow.id === nextWorkflowId) return true;+ const autoSave = useWorkflowSettingsStore.getState().settings.autoSave;+ if (!autoSave && !window.confirm(`Save your changes to "${currentWorkflow.name}" before opening another workflow?`)) {+ return false;+ }+ let saved: boolean;+ try {+ saved = await saveWorkflow();+ } catch (error) {+ console.error('[Shell] Failed to save before switching workflows:', error);+ toast.error(`Could not save "${currentWorkflow.name}". Your changes are still open in the editor.`);+ return false;+ }+ // A save that did not happen has already told the user why.+ if (!saved) return false;+ // Edits made while the save was in flight are not in it.+ if (useAppStore.getState().hasUnsavedChanges) {+ toast.error(`"${currentWorkflow.name}" changed while it was saving. Save it again before opening another workflow.`);+ return false;+ }+ return true;+}diff --git a/client/src/app/useShellActions.ts b/client/src/app/useShellActions.tsindex 64c811bc..9048825c 100644--- a/client/src/app/useShellActions.ts+++ b/client/src/app/useShellActions.ts@@ -6,8 +6,7 @@** Unsaved changes: the editor keeps its working copy in the app store, so* leaving for Home loses nothing. Opening a different workflow would replace- * it, so `enterDev` saves it first when the auto-save preference is on (the- * default) and asks otherwise.+ * it, so `enterDev` settles it first (`unsavedWork.ts`).*/import { useMemo } from 'react';@@ -19,9 +18,9 @@ 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';import { preloadEditor, preloadHome } from './ShellModeSwitch';import { transitionShell } from './shellTransition';+import { settleUnsavedWork } from './unsavedWork';export interface EnterDevOptions {/** Open this workflow in the editor (an employee's "Open workflow"). */@@ -39,28 +38,6 @@ function homeWorkflowId(): string | undefined {?? 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> {- const { currentWorkflow, hasUnsavedChanges, saveWorkflow } = useAppStore.getState();- if (!hasUnsavedChanges || !currentWorkflow || currentWorkflow.id === nextWorkflowId) return true;- const autoSave = useWorkflowSettingsStore.getState().settings.autoSave;- if (!autoSave && !window.confirm(`Save your changes to "${currentWorkflow.name}" before opening another workflow?`)) {- return false;- }- try {- await saveWorkflow();- } catch (error) {- console.error('[Shell] Failed to save before switching workflows:', error);- }- // saveWorkflow reports failure by leaving the changes marked unsaved.- if (useAppStore.getState().hasUnsavedChanges) {- toast.error(`Could not save "${currentWorkflow.name}". Your changes are still open in the editor.`);- return false;- }- return true;-}-export async function enterDev(options: EnterDevOptions = {}): Promise<void> {if (!featureFlags.normalMode) return;const workflowId = options.workflowId ?? homeWorkflowId();diff --git a/client/src/hooks/__tests__/useWorkflowManagement.test.ts b/client/src/hooks/__tests__/useWorkflowManagement.test.tsnew file mode 100644index 00000000..f1bb1854--- /dev/null+++ b/client/src/hooks/__tests__/useWorkflowManagement.test.ts@@ -0,0 +1,73 @@+/**+ * Choosing another workflow in the sidebar, or New, replaces the editor's+ * working copy. Both used to do it without a word, so unsaved changes were+ * simply dropped; they now settle them first, as the mode switch does.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, renderHook } from '@testing-library/react';++const settle = vi.hoisted(() => vi.fn());+vi.mock('../../app/unsavedWork', () => ({ settleUnsavedWork: settle }));+vi.mock('../useWorkflowsQuery', () => ({ useWorkflowsQuery: () => ({ data: [] }) }));++import { useWorkflowManagement } from '../useWorkflowManagement';+import { useAppStore, type WorkflowData } from '../../store/useAppStore';+import type { SavedWorkflow } from '../useWorkflowsQuery';++function workflow(id: string): WorkflowData {+ return { id, name: `Workflow ${id}`, slug: `${id}_1`, nodes: [], edges: [], createdAt: new Date(), lastModified: new Date() };+}++const saved = (id: string) => ({ id, name: `Workflow ${id}` }) as SavedWorkflow;++const loadWorkflow = vi.fn(async () => {});+const createNewWorkflow = vi.fn(async () => {});++beforeEach(() => {+ settle.mockReset();+ loadWorkflow.mockClear();+ createNewWorkflow.mockClear();+ useAppStore.setState({ currentWorkflow: workflow('a'), hasUnsavedChanges: true, loadWorkflow, createNewWorkflow });+});++describe('useWorkflowManagement', () => {+ it('settles unsaved work before opening another workflow', async () => {+ settle.mockResolvedValue(true);+ const { result } = renderHook(() => useWorkflowManagement());++ await act(() => result.current.handleSelectWorkflow(saved('b')));++ expect(settle).toHaveBeenCalledWith('b');+ expect(loadWorkflow).toHaveBeenCalledWith('b');+ });++ it('opens nothing when the unsaved work is kept', async () => {+ settle.mockResolvedValue(false);+ const { result } = renderHook(() => useWorkflowManagement());++ await act(() => result.current.handleSelectWorkflow(saved('b')));++ expect(loadWorkflow).not.toHaveBeenCalled();+ });++ it('does not reload the workflow already open', async () => {+ const { result } = renderHook(() => useWorkflowManagement());++ await act(() => result.current.handleSelectWorkflow(saved('a')));++ expect(settle).not.toHaveBeenCalled();+ expect(loadWorkflow).not.toHaveBeenCalled();+ });++ it('settles unsaved work before creating a workflow', async () => {+ settle.mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const { result } = renderHook(() => useWorkflowManagement());++ await act(() => result.current.handleNew());+ expect(createNewWorkflow).not.toHaveBeenCalled();++ await act(() => result.current.handleNew());+ expect(createNewWorkflow).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/hooks/useWorkflowManagement.ts b/client/src/hooks/useWorkflowManagement.tsindex f59915db..3236f3b3 100644--- a/client/src/hooks/useWorkflowManagement.ts+++ b/client/src/hooks/useWorkflowManagement.ts@@ -1,5 +1,6 @@import { useCallback } from 'react';import { useAppStore } from '../store/useAppStore';+import { settleUnsavedWork } from '../app/unsavedWork';import { useWorkflowsQuery, type SavedWorkflow } from './useWorkflowsQuery';export const useWorkflowManagement = () => {@@ -20,7 +21,10 @@ export const useWorkflowManagement = () => {saveWorkflow();}, [saveWorkflow]);+ // New and opening another workflow replace the editor's working copy, so+ // its unsaved changes are settled first, as the mode switch does.const handleNew = useCallback(async () => {+ if (!(await settleUnsavedWork())) return;await createNewWorkflow();}, [createNewWorkflow]);@@ -28,8 +32,12 @@ export const useWorkflowManagement = () => {// Workflow selection is handled by sidebar}, []);- const handleSelectWorkflow = useCallback((workflow: SavedWorkflow) => {- loadWorkflow(workflow.id);+ const handleSelectWorkflow = useCallback(async (workflow: SavedWorkflow) => {+ // The editor already holds this workflow; reloading it would only+ // throw away its unsaved changes.+ if (useAppStore.getState().currentWorkflow?.id === workflow.id) return;+ if (!(await settleUnsavedWork(workflow.id))) return;+ await loadWorkflow(workflow.id);}, [loadWorkflow]);diff --git a/client/src/services/__tests__/workflowApi.test.ts b/client/src/services/__tests__/workflowApi.test.tsnew file mode 100644index 00000000..0835730f--- /dev/null+++ b/client/src/services/__tests__/workflowApi.test.ts@@ -0,0 +1,62 @@+/**+ * workflowApi.saveWorkflow answers null when nothing was saved and tells+ * `onFailure` why, so the store can show the reason instead of only logging+ * that the save failed.+ */++import { describe, it, expect, vi, afterEach } from 'vitest';+import { workflowApi } from '../workflowApi';++const graph = { nodes: [], edges: [] };++function answer(body: unknown) {+ vi.stubGlobal('fetch', vi.fn(async () => ({ json: async () => body })));+}++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('workflowApi.saveWorkflow', () => {+ it('passes the messages of a refused save to onFailure', async () => {+ answer({+ success: false,+ error: 'invalid_context_topology',+ validation_errors: [+ { code: 'SHARED_CONTEXT', message: 'A Context node cannot serve multiple agents' },+ { code: 'WITHOUT_MESSAGE' },+ ],+ });+ const onFailure = vi.fn();++ await expect(workflowApi.saveWorkflow('7', 'Maya', graph, onFailure)).resolves.toBeNull();++ expect(onFailure).toHaveBeenCalledWith({+ error: 'invalid_context_topology',+ messages: ['A Context node cannot serve multiple agents'],+ });+ });++ it('reports a request that never completed as unreachable', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => {+ throw new TypeError('Failed to fetch');+ }));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const onFailure = vi.fn();++ await expect(workflowApi.saveWorkflow('7', 'Maya', graph, onFailure)).resolves.toBeNull();++ expect(onFailure).toHaveBeenCalledWith({ error: 'unreachable', messages: [] });+ });++ it('reports nothing when the save succeeds', async () => {+ answer({ success: true, id: '7', slug: 'Maya_1', data: graph });+ const onFailure = vi.fn();++ const result = await workflowApi.saveWorkflow('7', 'Maya', graph, onFailure);++ expect(result?.id).toBe('7');+ expect(onFailure).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/workflowApi.ts b/client/src/services/workflowApi.tsindex b067895a..4d0a0238 100644--- a/client/src/services/workflowApi.ts+++ b/client/src/services/workflowApi.ts@@ -45,8 +45,33 @@ export interface SaveWorkflowResult {};}+/** Why a save did not happen. */+export interface SaveWorkflowFailure {+ /** The server's code (`invalid_context_topology`, `workflow_not_found`,+ * `save_failed`), or `unreachable` when no answer arrived. */+ error: string;+ /** The user-facing messages of the validation issues that refused it. */+ messages: string[];+}++function saveFailure(body: any): SaveWorkflowFailure {+ const issues: unknown[] = Array.isArray(body?.validation_errors) ? body.validation_errors : [];+ return {+ error: typeof body?.error === 'string' && body.error ? body.error : 'save_failed',+ messages: issues+ .map((issue) => (issue as { message?: unknown } | null)?.message)+ .filter((message): message is string => typeof message === 'string' && message.length > 0),+ };+}+export const workflowApi = {- async saveWorkflow(workflowId: string, name: string, data: { nodes: any[]; edges: any[] }): Promise<SaveWorkflowResult | null> {+ /** Null when the workflow was not saved; `onFailure` then hears why. */+ async saveWorkflow(+ workflowId: string,+ name: string,+ data: { nodes: any[]; edges: any[] },+ onFailure?: (failure: SaveWorkflowFailure) => void,+ ): Promise<SaveWorkflowResult | null> {try {const response = await fetch(`${getApiBase()}/workflows`, {method: 'POST',@@ -55,9 +80,15 @@ export const workflowApi = {body: JSON.stringify({ workflow_id: workflowId, name, data })});const result = await response.json();- if (!result.success) return null;+ if (!result.success) {+ onFailure?.(saveFailure(result));+ return null;+ }const canonicalId = result.id ?? result.workflow_id;- if (!canonicalId && workflowId === 'new') return null;+ if (!canonicalId && workflowId === 'new') {+ onFailure?.(saveFailure(null));+ return null;+ }return {success: true,id: canonicalId ?? workflowId,@@ -68,6 +99,7 @@ export const workflowApi = {};} catch (error) {console.error('Failed to save workflow:', error);+ onFailure?.({ error: 'unreachable', messages: [] });return null;}},diff --git a/client/src/store/__tests__/saveWorkflowFeedback.test.ts b/client/src/store/__tests__/saveWorkflowFeedback.test.tsnew file mode 100644index 00000000..369dccfd--- /dev/null+++ b/client/src/store/__tests__/saveWorkflowFeedback.test.ts@@ -0,0 +1,133 @@+/**+ * A workflow save the server refuses, or never answers, tells the user why+ * and keeps the changes marked unsaved. It used to log to the console only,+ * so the Save button just stayed lit.+ *+ * Start shows the graph it admitted without clearing `hasUnsavedChanges`.+ * Start stores that graph on the new generation, not on the workflow, so+ * clearing the flag hid edits that a reload would lose.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import type { Node } from 'reactflow';+import { toast } from 'sonner';++const saveWorkflowMock = vi.fn();+vi.mock('../../services/workflowApi', () => ({+ workflowApi: {+ getAllWorkflows: vi.fn(),+ getWorkflow: vi.fn(),+ saveWorkflow: (...args: unknown[]) => saveWorkflowMock(...args),+ deleteWorkflow: vi.fn(),+ },+}));++import { useAppStore, type WorkflowData } from '../useAppStore';+import type { SaveWorkflowFailure } from '../../services/workflowApi';++function workflow(id: string): WorkflowData {+ return { id, name: 'Maya', slug: 'Maya_1', nodes: [], edges: [], createdAt: new Date(), lastModified: new Date() };+}++/** The next save is not saved, and the API reports `failure`. */+function refuseWith(failure: SaveWorkflowFailure) {+ saveWorkflowMock.mockImplementation(+ async (_id: string, _name: string, _data: unknown, onFailure?: (reason: SaveWorkflowFailure) => void) => {+ onFailure?.(failure);+ return null;+ },+ );+}++let toastError: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ saveWorkflowMock.mockReset();+ toastError = vi.spyOn(toast, 'error').mockImplementation(() => 'toast');+ vi.spyOn(console, 'error').mockImplementation(() => {});+ useAppStore.setState({ currentWorkflow: workflow('7'), hasUnsavedChanges: true });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('saveWorkflow feedback', () => {+ it('names the first validation issue when the server refuses the graph', async () => {+ refuseWith({+ error: 'invalid_context_topology',+ messages: ['A Context node cannot serve multiple agents', 'An agent cannot be connected to multiple Context nodes'],+ });++ await expect(useAppStore.getState().saveWorkflow()).resolves.toBe(false);++ expect(toastError).toHaveBeenCalledWith(+ 'Could not save "Maya": A Context node cannot serve multiple agents (and 1 more)',+ );+ expect(useAppStore.getState().hasUnsavedChanges).toBe(true);+ });++ it('says the workflow is gone when it was deleted meanwhile', async () => {+ refuseWith({ error: 'workflow_not_found', messages: [] });++ await useAppStore.getState().saveWorkflow();++ expect(toastError).toHaveBeenCalledWith('"Maya" no longer exists, so it was not saved.');+ });++ it('says the server did not answer when the request never completed', async () => {+ refuseWith({ error: 'unreachable', messages: [] });++ await useAppStore.getState().saveWorkflow();++ expect(toastError).toHaveBeenCalledWith(+ 'Could not save "Maya": the server did not answer. Your changes are still in the editor.',+ );+ });++ it('answers true and clears the flag when the server saved it', async () => {+ saveWorkflowMock.mockResolvedValue({ success: true, id: '7', slug: 'Maya_1' });++ await expect(useAppStore.getState().saveWorkflow()).resolves.toBe(true);++ expect(useAppStore.getState().hasUnsavedChanges).toBe(false);+ expect(toastError).not.toHaveBeenCalled();+ });+});++describe('createNewWorkflow feedback', () => {+ it('tells the user when no workflow could be created', async () => {+ saveWorkflowMock.mockResolvedValue(null);++ await useAppStore.getState().createNewWorkflow();++ expect(toastError).toHaveBeenCalledTimes(1);+ expect(useAppStore.getState().currentWorkflow?.id).toBe('7');+ });+});++describe('adoptStartedGraph', () => {+ const admitted: Node[] = [{ id: '7:start:1', type: 'start', position: { x: 0, y: 0 }, data: {} }];++ it('shows the admitted graph and keeps unsaved edits marked unsaved', () => {+ useAppStore.getState().adoptStartedGraph('7', admitted, []);++ const { currentWorkflow, hasUnsavedChanges } = useAppStore.getState();+ expect(currentWorkflow?.nodes).toBe(admitted);+ expect(hasUnsavedChanges).toBe(true);+ });++ it('leaves a saved workflow saved', () => {+ useAppStore.setState({ hasUnsavedChanges: false });++ useAppStore.getState().adoptStartedGraph('7', admitted, []);++ expect(useAppStore.getState().hasUnsavedChanges).toBe(false);+ });++ it('ignores a Start answer for a workflow that is no longer open', () => {+ useAppStore.getState().adoptStartedGraph('8', admitted, []);++ expect(useAppStore.getState().currentWorkflow?.nodes).toEqual([]);+ });+});diff --git a/client/src/store/useAppStore.ts b/client/src/store/useAppStore.tsindex 31832504..5dfc4128 100644--- a/client/src/store/useAppStore.ts+++ b/client/src/store/useAppStore.ts@@ -11,7 +11,7 @@ import {sanitizeNodes,} from '../utils/workflowExport';import type { ImportedWorkflow } from '../utils/workflowExport';-import { workflowApi } from '../services/workflowApi';+import { workflowApi, type SaveWorkflowFailure } from '../services/workflowApi';import { queryClient } from '../lib/queryClient';import { addSavedEdges, addSavedNodes, type WorkflowOperation } from '../lib/workflowOps';import { BRAND_STORAGE_KEYS, readAndMigrateStorageValue } from '../lib/brandStorage';@@ -86,7 +86,9 @@ interface AppStore {setCurrentWorkflow: (workflow: WorkflowData) => void;updateWorkflow: (updates: Partial<Omit<WorkflowData, 'id' | 'createdAt'>>) => void;createNewWorkflow: () => Promise<void>;- saveWorkflow: () => Promise<void>;+ /** True when the server saved the workflow. On false it has already told+ * the user why, and the changes stay marked unsaved. */+ saveWorkflow: () => Promise<boolean>;loadWorkflow: (id: string) => Promise<void>;deleteWorkflow: (id: string) => Promise<boolean>;/** Apply a successful deletion from this tab or a lifecycle broadcast. */@@ -98,6 +100,12 @@ interface AppStore {* needs saving, and an open canvas is not reset. No-op for any other* workflow. */adoptSavedOperations: (workflowId: string, operations: WorkflowOperation[]) => void;+ /** Show the graph Start admitted (normalized, canonical ids) in the open+ * workflow. Start stores that graph on the new generation, not on the+ * workflow, so `hasUnsavedChanges` stays as it was: clearing it would+ * hide edits that exist only in the running generation. No-op for any+ * other workflow. */+ adoptStartedGraph: (workflowId: string, nodes: Node[], edges: Edge[]) => void;// UI actionssetSelectedNode: (node: Node | null) => void;@@ -174,6 +182,15 @@ const migrateNodes = (nodes: Node[]): Node[] => {});};+/** What to tell the user when a workflow was not saved. */+const saveFailureMessage = (name: string, failure: SaveWorkflowFailure | null): string => {+ if (failure?.error === 'workflow_not_found') return `"${name}" no longer exists, so it was not saved.`;+ const [first, ...rest] = failure?.messages ?? [];+ if (first) return `Could not save "${name}": ${first}${rest.length ? ` (and ${rest.length} more)` : ''}`;+ const reason = failure?.error === 'unreachable' ? ': the server did not answer' : '';+ return `Could not save "${name}"${reason}. Your changes are still in the editor.`;+};+// Storage keys for UI state persistenceconst STORAGE_KEYS = {sidebarVisible: 'ui_sidebar_visible',@@ -277,6 +294,7 @@ export const useAppStore = create<AppStore>((set, get) => ({);if (!result?.id) {console.error('Failed to allocate workflow identity');+ toast.error('Could not create a workflow. Check the connection and try again.');return;}set({@@ -295,25 +313,28 @@ export const useAppStore = create<AppStore>((set, get) => ({saveWorkflow: async () => {const { currentWorkflow } = get();- if (!currentWorkflow) return;+ if (!currentWorkflow) return false;// Save to database - sanitize node.data to only include UI fields (label, disabled, condition).// Parameters live in the DB node_parameters table, not in node.data.// The save handler returns the canonical slug (recomputed server-side// when the display name changed) so we can sync the store with it.+ let failure: SaveWorkflowFailure | null = null;const result = await workflowApi.saveWorkflow(currentWorkflow.id,currentWorkflow.name,- { nodes: sanitizeNodes(currentWorkflow.nodes), edges: currentWorkflow.edges }+ { nodes: sanitizeNodes(currentWorkflow.nodes), edges: currentWorkflow.edges },+ (reason) => { failure = reason; },);if (!result) {- console.error('Failed to save workflow to database');- return;+ console.error('Failed to save workflow to database', failure);+ toast.error(saveFailureMessage(currentWorkflow.name, failure));+ return false;}// A delete, navigation, or newer edit can finish while the save is in// flight. Its response must not restore the old graph or clear new edits.- if (get().currentWorkflow !== currentWorkflow) return;+ if (get().currentWorkflow !== currentWorkflow) return true;const aliases = result.nodeIdAliases ?? {};// Server normalization is authoritative: it creates Context companions,@@ -351,8 +372,9 @@ export const useAppStore = create<AppStore>((set, get) => ({hasUnsavedChanges: false,});invalidateWorkflowsList();+ return true;},-+loadWorkflow: async (id) => {// Use the same server-record query as other readers. Deletion cancels it,// so late responses cannot restore a removed graph. No client ID registry@@ -428,6 +450,12 @@ export const useAppStore = create<AppStore>((set, get) => ({set({ currentWorkflow: { ...workflow, nodes, edges } });},+ adoptStartedGraph: (workflowId, nodes, edges) => {+ const workflow = get().currentWorkflow;+ if (!workflow || workflow.id !== workflowId) return;+ set({ currentWorkflow: { ...workflow, nodes, edges } });+ },+migrateCurrentWorkflow: async () => {const { currentWorkflow } = get();if (!currentWorkflow || !currentWorkflow.nodes) return;