Skip to content

Self-improving AI Employees for everyone

fix(parameters): never save defaults over a node's stored settings

trohitgac3c64fb68f9
diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsx
index 69caf904..bbbf96e0 100644
--- a/client/src/components/parameterPanel/MiddleSection.tsx
+++ b/client/src/components/parameterPanel/MiddleSection.tsx
@@ -41,7 +41,7 @@ import BrowserWorkspace from '../browser/BrowserWorkspace';
import { useAppStore } from '../../store/useAppStore';
import { useNodeStatus, useWebSocket, CompactionStats } from '../../contexts/WebSocketContext';
import { useUserSettingsQuery } from '../../hooks/useUserSettingsQuery';
-import { nodeParamsQueryKey, type NodeParametersResponse } from '../../hooks/useNodeParamsQuery';
+import { fetchSavedNodeParams, nodeParamsQueryKey, type NodeParametersResponse } from '../../hooks/useNodeParamsQuery';
import { fetchFolderSkills, folderSkillsQueryKey, type AvailableSkill } from '../../hooks/useFolderSkills';
import { queryKeys, STALE_TIME } from '../../lib/queryConfig';
import { INodeTypeDescription, INodeProperties } from '../../types/INodeProperties';
@@ -244,7 +244,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
const memoryParamsQuery = useQuery<NodeParametersResponse | null, Error>({
queryKey: memoryEdgeSourceId ? nodeParamsQueryKey(memoryEdgeSourceId) : nodeParamsQueryKey('none'),
- queryFn: () => (memoryEdgeSourceId ? getNodeParameters(memoryEdgeSourceId) : Promise.resolve(null)),
+ queryFn: () => (memoryEdgeSourceId ? fetchSavedNodeParams(getNodeParameters, memoryEdgeSourceId) : Promise.resolve(null)),
enabled: !!memoryEdgeSourceId,
staleTime: STALE_TIME.MEDIUM,
});
@@ -338,7 +338,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
const masterSkillParamsQueries = useQueries({
queries: masterSkillEdgeSources.map((id) => ({
queryKey: nodeParamsQueryKey(id),
- queryFn: () => getNodeParameters(id),
+ queryFn: () => fetchSavedNodeParams(getNodeParameters, id),
staleTime: STALE_TIME.MEDIUM,
})),
});
diff --git a/client/src/hooks/__tests__/useParameterPanel.test.tsx b/client/src/hooks/__tests__/useParameterPanel.test.tsx
new file mode 100644
index 00000000..dda96dd0
--- /dev/null
+++ b/client/src/hooks/__tests__/useParameterPanel.test.tsx
@@ -0,0 +1,144 @@
+/**
+ * The panel saves a node's whole parameter row, so it must not present or
+ * save defaults as the node's settings before that row has loaded. It used
+ * to: while the socket was not ready the query was disabled, TanStack
+ * reported it as not loading, and the panel seeded the buffer from defaults;
+ * a failed read resolved `null` and did the same. Either way the next Save
+ * replaced the stored settings with defaults.
+ */
+
+import React from 'react';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { QueryClientProvider } from '@tanstack/react-query';
+import type { Node } from 'reactflow';
+import { toast } from 'sonner';
+import { makeTestQueryClient } from '../../test/providers';
+
+const ws = vi.hoisted(() => ({
+ getNodeParameters: vi.fn(),
+ saveNodeParameters: vi.fn(),
+ sendRequest: vi.fn(),
+ isReady: true,
+ isConnected: true,
+}));
+
+vi.mock('../../contexts/WebSocketContext', () => ({
+ useWebSocket: () => ws,
+ useWebSocketActions: () => ws,
+}));
+
+vi.mock('../../lib/nodeSpec', () => ({
+ resolveNodeDescription: () => ({
+ properties: [
+ { name: 'prompt', default: 'Hello' },
+ { name: 'temperature', default: 0.7 },
+ ],
+ }),
+}));
+
+import { useParameterPanel } from '../useParameterPanel';
+import { fetchSavedNodeParams } from '../useNodeParamsQuery';
+import { useAppStore } from '../../store/useAppStore';
+
+const NODE_ID = 'wf:aiAgent:1';
+
+function renderPanel() {
+ const client = makeTestQueryClient();
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ return renderHook(() => useParameterPanel(), { wrapper });
+}
+
+let toastError: ReturnType<typeof vi.spyOn>;
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ ws.isReady = true;
+ toastError = vi.spyOn(toast, 'error').mockImplementation(() => 'toast');
+ useAppStore.setState({
+ selectedNode: { id: NODE_ID, type: 'aiAgent', position: { x: 0, y: 0 }, data: {} } as Node,
+ });
+});
+
+afterEach(() => {
+ toastError.mockRestore();
+ useAppStore.setState({ selectedNode: null });
+});
+
+describe('useParameterPanel loading', () => {
+ it('seeds the buffer from the defaults and the saved row', async () => {
+ ws.getNodeParameters.mockResolvedValue({ parameters: { prompt: 'Saved' }, version: 3 });
+
+ const { result } = renderPanel();
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.parameters).toEqual({ prompt: 'Saved', temperature: 0.7 });
+ expect(result.current.hasUnsavedChanges).toBe(false);
+ });
+
+ it('stays loading and saves nothing until the socket is ready', async () => {
+ ws.isReady = false;
+
+ const { result } = renderPanel();
+
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.parameters).toEqual({});
+
+ act(() => result.current.handleParameterChange('prompt', 'Typed early'));
+ await act(() => result.current.handleSave());
+
+ expect(ws.getNodeParameters).not.toHaveBeenCalled();
+ expect(ws.saveNodeParameters).not.toHaveBeenCalled();
+ expect(toastError).toHaveBeenCalledTimes(1);
+ });
+
+ it('never seeds defaults or saves over the row when the read fails', async () => {
+ ws.getNodeParameters.mockResolvedValue(null);
+
+ const { result } = renderPanel();
+
+ await waitFor(() => expect(result.current.error).toBe('Failed to load saved parameters'));
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.parameters).toEqual({});
+ expect(toastError).toHaveBeenCalledTimes(1);
+
+ act(() => result.current.handleParameterChange('prompt', 'Edited'));
+ await act(() => result.current.handleSave());
+
+ expect(ws.saveNodeParameters).not.toHaveBeenCalled();
+ });
+});
+
+describe('useParameterPanel saving', () => {
+ it('saves the loaded row with the edit and the row version', async () => {
+ ws.getNodeParameters.mockResolvedValue({ parameters: { prompt: 'Saved', extra: 'kept' }, version: 3 });
+ ws.saveNodeParameters.mockResolvedValue(true);
+
+ const { result } = renderPanel();
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ act(() => result.current.handleParameterChange('prompt', 'Edited'));
+ await act(() => result.current.handleSave());
+
+ expect(ws.saveNodeParameters).toHaveBeenCalledWith(
+ NODE_ID,
+ { prompt: 'Edited', temperature: 0.7, extra: 'kept' },
+ 3,
+ );
+ expect(result.current.hasUnsavedChanges).toBe(false);
+ expect(toastError).not.toHaveBeenCalled();
+ });
+});
+
+describe('fetchSavedNodeParams', () => {
+ it('passes a node without a saved row through as an empty row', async () => {
+ const empty = { parameters: {}, version: 0 };
+ await expect(fetchSavedNodeParams(async () => empty, NODE_ID)).resolves.toBe(empty);
+ });
+
+ it('fails a read that returned nothing, so no query caches it as a row', async () => {
+ await expect(fetchSavedNodeParams(async () => null, NODE_ID)).rejects.toThrow(NODE_ID);
+ });
+});
diff --git a/client/src/hooks/useNodeParamsQuery.ts b/client/src/hooks/useNodeParamsQuery.ts
index d28e27c3..3120b25d 100644
--- a/client/src/hooks/useNodeParamsQuery.ts
+++ b/client/src/hooks/useNodeParamsQuery.ts
@@ -23,13 +23,32 @@ export type NodeParametersResponse = NodeParameters;
export const nodeParamsQueryKey = (nodeId: string) =>
['nodeParams', nodeId] as const;
+/**
+ * Read a node's saved row for the `nodeParams` cache. Every query on that
+ * key uses this, so the cache holds real rows only.
+ *
+ * A node with no saved row comes back as `{parameters: {}}`, so `null` from
+ * `getNodeParameters` means the request failed, and this throws. The
+ * parameter panel seeds its edit buffer from the cached row and saves the
+ * whole row back; a failed read cached as an empty row would let the next
+ * Save replace the node's settings with defaults.
+ */
+export async function fetchSavedNodeParams(
+ getNodeParameters: (nodeId: string) => Promise<NodeParametersResponse | null>,
+ nodeId: string,
+): Promise<NodeParametersResponse> {
+ const stored = await getNodeParameters(nodeId);
+ if (stored === null) throw new Error(`Failed to load saved parameters for ${nodeId}`);
+ return stored;
+}
+
export function useNodeParamsQuery(
nodeId: string | null | undefined,
): UseQueryResult<NodeParametersResponse | null, Error> {
const { getNodeParameters, isReady } = useWebSocket();
return useQuery<NodeParametersResponse | null, Error>({
queryKey: nodeId ? nodeParamsQueryKey(nodeId) : ['nodeParams', 'none'],
- queryFn: () => (nodeId ? getNodeParameters(nodeId) : Promise.resolve(null)),
+ queryFn: () => (nodeId ? fetchSavedNodeParams(getNodeParameters, nodeId) : Promise.resolve(null)),
enabled: !!nodeId && isReady,
staleTime: 60_000,
});
diff --git a/client/src/hooks/useParameterPanel.ts b/client/src/hooks/useParameterPanel.ts
index c4fcb199..4620b42d 100644
--- a/client/src/hooks/useParameterPanel.ts
+++ b/client/src/hooks/useParameterPanel.ts
@@ -1,4 +1,5 @@
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
+import { toast } from 'sonner';
import { useAppStore } from '../store/useAppStore';
import { resolveNodeDescription } from '../lib/nodeSpec';
import { useWebSocket } from '../contexts/WebSocketContext';
@@ -39,13 +40,16 @@ export const useParameterPanel = () => {
const [editBuffer, setEditBuffer] = useState<Record<string, any>>({});
const [originalParameters, setOriginalParameters] = useState<Record<string, any>>({});
const [error, setError] = useState<string | null>(null);
+ // The node whose saved row seeded the buffer. Until it is the selected
+ // node the panel is still loading and Save is refused: a save replaces
+ // the node's whole row, and a buffer holding none of it would wipe it.
+ const [loadedFor, setLoadedFor] = useState<string | null>(null);
// Initialize the edit buffer once per node selection. Identity of
// sendRequest / saveMutation / paramsQuery.data churns on every render,
// so we must NOT depend on them — that would trigger an infinite loop
// because the optimistic setQueryData on save mints a fresh data object.
- // The ref guard keeps initialization bound to nodeId transitions only.
- const initializedFor = useRef<string | null>(null);
+ // The `loadedFor` guard keeps initialization bound to nodeId transitions.
// Stable refs to read-only deps the effect needs without listing them.
const sendRequestRef = useRef(sendRequest);
sendRequestRef.current = sendRequest;
@@ -54,17 +58,22 @@ export const useParameterPanel = () => {
const queryDataRef = useRef(paramsQuery.data);
queryDataRef.current = paramsQuery.data;
+ // Wait for the saved row itself, not for `isLoading` to clear: TanStack
+ // also reports not-loading while the query is disabled (socket not ready
+ // yet) and after it failed, and seeding from defaults then would let the
+ // next Save overwrite the stored settings with them.
+ const hasSavedRow = paramsQuery.data != null;
+ const loadFailed = paramsQuery.isError && !hasSavedRow;
+
useEffect(() => {
if (!nodeType || !nodeId) {
setEditBuffer({});
setOriginalParameters({});
setError(null);
- initializedFor.current = null;
+ setLoadedFor(null);
return;
}
- if (paramsQuery.isLoading) return;
- if (initializedFor.current === nodeId) return;
- initializedFor.current = nodeId;
+ if (!hasSavedRow || loadedFor === nodeId) return;
const defaults = defaultsForNodeType(nodeType);
const saved = queryDataRef.current?.parameters ?? {};
@@ -72,12 +81,19 @@ export const useParameterPanel = () => {
setEditBuffer(initial);
setOriginalParameters(initial);
- }, [nodeId, nodeType, paramsQuery.isLoading]);
+ setLoadedFor(nodeId);
+ }, [nodeId, nodeType, hasSavedRow, loadedFor]);
- // Surface query errors.
+ // Surface load failures. The panels do not render `error`, so the toast
+ // is what tells the user why the fields stay empty.
useEffect(() => {
- setError(paramsQuery.isError ? 'Failed to load saved parameters' : null);
- }, [paramsQuery.isError]);
+ if (!loadFailed) {
+ setError(null);
+ return;
+ }
+ setError('Failed to load saved parameters');
+ toast.error("Could not load this node's saved settings. Close the panel and open it again to retry.");
+ }, [nodeId, loadFailed]);
const hasUnsavedChanges = useMemo(() => {
return JSON.stringify(editBuffer) !== JSON.stringify(originalParameters);
@@ -89,6 +105,11 @@ export const useParameterPanel = () => {
const handleSave = useCallback(async () => {
if (!nodeId) return;
+ if (loadedFor !== nodeId) {
+ setError('Saved parameters have not loaded yet; nothing was saved');
+ toast.error("This node's saved settings have not loaded, so nothing was saved.");
+ return;
+ }
try {
await saveMutation.mutateAsync({
nodeId,
@@ -100,8 +121,9 @@ export const useParameterPanel = () => {
} catch (err) {
console.error('Failed to save parameters via WebSocket:', err);
setError('Failed to save parameters');
+ toast.error('Could not save these settings. Your changes are still in the panel.');
}
- }, [nodeId, editBuffer, saveMutation, paramsQuery.data?.version]);
+ }, [nodeId, loadedFor, editBuffer, saveMutation, paramsQuery.data?.version]);
const handleCancel = useCallback(() => {
setEditBuffer({ ...originalParameters });
@@ -126,7 +148,11 @@ export const useParameterPanel = () => {
handleParameterChange,
handleSave,
handleCancel,
- isLoading: paramsQuery.isLoading,
+ // True until the saved row has seeded the buffer, including after a
+ // failed load: ParameterRenderer then shows empty fields rather than
+ // defaults that look like the node's settings, and holds back its
+ // provider/model effect, which would otherwise edit the buffer.
+ isLoading: !!nodeId && loadedFor !== nodeId,
isSaving: saveMutation.isPending,
error,
isConnected,
diff --git a/docs-internal/node_panels.md b/docs-internal/node_panels.md
index 00fa25c3..8bc52ce5 100644
--- a/docs-internal/node_panels.md
+++ b/docs-internal/node_panels.md
@@ -34,7 +34,9 @@ Files:
1. User clicks a node on the canvas → `selectedNode` set in Zustand store.
2. `ParameterPanel` mounts → `useParameterPanel()` fires.
3. Hook reads defaults from `nodeDefinition.properties[].default`, then asks backend for any saved
- parameters via WebSocket `get_node_parameters`. Saved values overlay defaults.
+ parameters via WebSocket `get_node_parameters`. Saved values overlay defaults. The buffer is
+ seeded only once the saved row has arrived: until then (socket not ready yet, read failed)
+ `isLoading` stays true and Save is refused, because a save replaces the node's whole row.
4. Modal renders three sections; `MiddleSection` filters parameters via `displayOptions.show`
(see §4 invariants), then renders each visible parameter through `ParameterRenderer`.
5. User edits → `handleParameterChange(name, value)` updates local state. `hasUnsavedChanges`
@@ -175,6 +177,7 @@ NodeSpec declares `uiHints.outputMode = "terminal"` (CLI-wrapper plugins: `githu
## 7. Refactor Invariants
Locked in by the test suite at:
+- [client/src/hooks/__tests__/useParameterPanel.test.tsx](../client/src/hooks/__tests__/useParameterPanel.test.tsx)
- [client/src/hooks/__tests__/useDragVariable.test.ts](../client/src/hooks/__tests__/useDragVariable.test.ts)
- [client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx](../client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx)
- [client/src/components/parameterPanel/__tests__/InputSection.test.tsx](../client/src/components/parameterPanel/__tests__/InputSection.test.tsx)
@@ -182,6 +185,11 @@ Locked in by the test suite at:
1. **Defaults loaded** from `nodeDefinition.properties[].default`; missing default ⇒ `null`.
2. **Saved params win** over defaults when merged (DB is source of truth).
+ **No row, no seed**: `get_node_parameters` answers `{parameters: {}}` for a node without a
+ saved row, so a `null` reply is a failed read. `fetchSavedNodeParams`
+ ([useNodeParamsQuery.ts](../client/src/hooks/useNodeParamsQuery.ts)) throws on it for every
+ query on the `nodeParams` key, so the cache never holds a failed read as an empty row; the
+ panel shows the failure as a toast and Save stays refused.
3. **`hasUnsavedChanges`** is a deep-equal check against the original snapshot loaded from DB.
4. **Save** routes to `save_node_parameters` and updates the original snapshot on success.
5. **Cancel** restores the pending edits and clears `selectedNode`.