Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(credentials): status indicator + unified validate dispatch
trohitg1d4cdd63e7de
diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsxindex 5dbe8369..bdcdb43b 100644--- a/client/src/components/SquareNode.tsx+++ b/client/src/components/SquareNode.tsx@@ -1,14 +1,11 @@import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';-import { useQuery } from '@tanstack/react-query';import { Handle, Position, NodeProps } from 'reactflow';import { NodeData } from '../types/NodeTypes';import { useAppStore } from '../store/useAppStore';import { nodeDefinitions } from '../nodeDefinitions';import { useAppTheme } from '../hooks/useAppTheme';import { useWebSocket, useWhatsAppStatus } from '../contexts/WebSocketContext';-import { useApiKeys } from '../hooks/useApiKeys';import { getCachedNodeSpec, isNodeInBackendGroup, resolveNodeDescription, useNodeSpec } from '../lib/nodeSpec';-import { queryKeys, STALE_TIME } from '../lib/queryConfig';import { resolveIcon, resolveLibraryIcon } from '../assets/icons';import { AI_MODEL_PROVIDER_MAP } from '../nodeDefinitions/aiModelNodes';@@ -43,7 +40,6 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab// Get Android status, node status, and API key status from WebSocket contextconst { androidStatus, getNodeStatus, getApiKeyStatus } = useWebSocket();- const { getStoredApiKey, isConnected: wsConnected } = useApiKeys();const nodeStatus = getNodeStatus(id);const executionStatus = nodeStatus?.status || 'idle';@@ -162,6 +158,9 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectabsetRenamingNodeId(id);}, [id, setRenamingNodeId]);+ // Provider id for legacy credentialed nodes (non-AI, non-maps). AI+ // model nodes route through `aiProviderId` above, Google Maps through+ // `googleMapsKeyStatus` — both read from WS-context apiKeyStatuses.const providerId = useMemo<string>(() => {const credName = definition?.credentials?.[0]?.name;if (credName && CREDENTIAL_TO_PROVIDER[credName]) return CREDENTIAL_TO_PROVIDER[credName];@@ -169,13 +168,11 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectabreturn '';}, [definition?.credentials, type]);- const apiKeyQuery = useQuery<string | null, Error>({- ...queryKeys.storedApiKey.byProvider(providerId),- queryFn: () => getStoredApiKey(providerId),- enabled: !!providerId && wsConnected,- staleTime: STALE_TIME.SHORT,- });- const hasApiKey = !!apiKeyQuery.data;+ // "Is a credential configured for this provider?" is read from the+ // WS-context apiKeyStatuses map — populated synchronously by+ // validateApiKeyAsync + the api_key_status broadcast. The canvas node+ // never fetches decrypted keys; that's the credentials modal's job.+ const hasApiKey = !!(providerId && getApiKeyStatus(providerId)?.hasKey);const isConfigured = hasApiKey && !!data && Object.keys(data).length > 0;const handleParametersClick = (e: React.MouseEvent) => {diff --git a/client/src/components/credentials/panels/ApiKeyPanel.tsx b/client/src/components/credentials/panels/ApiKeyPanel.tsxindex 54a3d969..2312c65a 100644--- a/client/src/components/credentials/panels/ApiKeyPanel.tsx+++ b/client/src/components/credentials/panels/ApiKeyPanel.tsx@@ -22,18 +22,19 @@ const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ cconst field = config.fields?.[0];const iconSize = parseInt(theme.iconSize.md);- // Local state for the controlled input. antd Form.getFieldValue/setFieldValue- // are snapshots that don't trigger re-renders — using them as a controlled- // input's value prop causes typing to be silently rejected. useState is the- // standard React pattern for controlled inputs.const [inputValue, setInputValue] = useState('');+ // Direct local flag — same pattern as main repo's validKeys[id].+ // Completely independent from useCredentialPanel's stored state.+ const [validated, setValidated] = useState(panel.stored);- // Sync from the form when stored credentials load (useCredentialPanel- // populates the form asynchronously via getStoredApiKey on mount).+ // Sync from the form when stored credentials loaduseEffect(() => {if (panel.stored && field) {const v = panel.form.getFieldValue(field.key);- if (v) setInputValue(v);+ if (v) {+ setInputValue(v);+ setValidated(true);+ }}}, [panel.stored, field, panel.form]);@@ -55,7 +56,7 @@ const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ c</div><CardTitle className="text-lg">{config.name}</CardTitle></div>- {panel.stored && (+ {validated && (<Badge variant="success" className="gap-1"><CheckCircle className="h-3 w-3" />Connected@@ -69,26 +70,27 @@ const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ conChange={(v) => {setInputValue(v);panel.form.setFieldValue(field.key, v);- panel.setStored(false);+ setValidated(false);}}onSave={() =>panel.actions.validate(config.id, inputValue.trim()).then((r) => {- if (r?.isValid) panel.setStored(true);+ if (r?.isValid) setValidated(true);})}onDelete={- panel.stored+ validated? () => {panel.actions.remove(config.id);setInputValue('');+ setValidated(false);}: undefined}placeholder={field.placeholder}loading={panel.loading === 'validate'}- isStored={panel.stored}+ isStored={validated}/>)}</CardContent>diff --git a/client/src/components/credentials/useCredentialPanel.ts b/client/src/components/credentials/useCredentialPanel.tsindex 474d210f..ba0a2434 100644--- a/client/src/components/credentials/useCredentialPanel.ts+++ b/client/src/components/credentials/useCredentialPanel.ts@@ -1,62 +1,56 @@/*** useCredentialPanel — single hook for credential panel state.*- * Plain React state (no antd Form, no react-hook-form). The credential- * panels save fields individually via `actions.save(key, value)` rather- * than submitting a single form, so a form library is overkill — the- * field values are just a key-value bag with stored/loading/error state- * around them.+ * The "what is stored on the server" source of truth is a TanStack+ * Query keyed by provider (`queryKeys.credentialValues.byProvider(id)`).+ * Visible in the React Query devtools so per-provider state can be+ * inspected at runtime.*- * Provides a generic `execute(key, fn)` that handles try/catch/loading/- * error identically to every handleTwitterSave, handleGmailLogin, etc.+ * `values` / `stored` are derived from the query data — never held in a+ * separate useState copy, so there is one source of truth.+ *+ * `loading` / `error` stay as local useState since they are transient UI+ * state for in-flight user actions (validate / save / delete), not+ * server-cached data.+ *+ * `execute(key, fn)` wraps try/catch/loading/error uniformly so every+ * panel action has the same ergonomics.*/-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useRef, useState } from 'react';+import { useQuery, useQueryClient } from '@tanstack/react-query';import { useApiKeys } from '../../hooks/useApiKeys';import { useWebSocket } from '../../contexts/WebSocketContext';+import { queryKeys, STALE_TIME } from '../../lib/queryConfig';import type { ProviderConfig } from './types';export type CredentialFormValues = Record<string, string>;+const EMPTY_VALUES: CredentialFormValues = {};+export function useCredentialPanel(config: ProviderConfig, visible: boolean) {- const [values, setValues] = useState<CredentialFormValues>({});+ const qc = useQueryClient();const [loading, setLoading] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [stored, setStored] = useState(false);- const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,- validateGoogleMapsKey, validateApifyKey, getProviderDefaults, saveProviderDefaults,+ const {+ validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,+ getProviderDefaults, saveProviderDefaults,getProviderUsageSummary, getAPIUsageSummary, getStoredModels, getModelConstraints,- isConnected } = useApiKeys();+ isConnected,+ } = useApiKeys();const { sendRequest } = useWebSocket();- // Imperative form-like API for compat with existing callers. Stable across- // renders so memoized children don't re-render.- const valuesRef = useRef(values);- valuesRef.current = values;-- const form = useRef({- getFieldValue: (key: string): string | undefined => valuesRef.current[key],- getFieldsValue: (): CredentialFormValues => ({ ...valuesRef.current }),- setFieldValue: (key: string, value: string) => {- setValues((prev) => ({ ...prev, [key]: value }));- },- setFieldsValue: (next: CredentialFormValues) => {- setValues((prev) => ({ ...prev, ...next }));- },- resetFields: () => setValues({}),- }).current;-- // Load stored values into form when panel becomes visible. Fields load- // in parallel via Promise.all so a 3-field provider takes one WS- // round-trip instead of six sequential ones (fields populate together- // instead of one-by-one on modal open).- useEffect(() => {- if (!visible || !isConnected || !config.fields) return;- let cancelled = false;- (async () => {+ // Server-cached credential values. Fields load in parallel via+ // Promise.all so a 3-field provider takes one WS round-trip instead+ // of six sequential ones.+ const credentialValuesQuery = useQuery<CredentialFormValues, Error>({+ queryKey: queryKeys.credentialValues.byProvider(config.id).queryKey,+ queryFn: async () => {+ if (!config.fields) return EMPTY_VALUES;const entries = await Promise.all(- config.fields!.map(async (field) => {+ config.fields.map(async (field) => {const storeKey = field.key === 'apiKey' ? config.id : field.key;const has = await hasStoredKey(storeKey);if (!has) return null;@@ -64,17 +58,51 @@ export function useCredentialPanel(config: ProviderConfig, visible: boolean) {return val ? ([field.key, val] as const) : null;}),);- if (cancelled) return;const next: CredentialFormValues = {};for (const entry of entries) {if (entry) next[entry[0]] = entry[1];}- setValues(next);- setStored(Object.keys(next).length > 0);- setError(null);- })();- return () => { cancelled = true; };- }, [config.id, visible, isConnected]);+ return next;+ },+ enabled: visible && isConnected && !!config.fields,+ staleTime: STALE_TIME.FOREVER,+ });++ const values = credentialValuesQuery.data ?? EMPTY_VALUES;++ // Imperative form-like API kept for compat with existing panel code.+ // Writes go through setQueryData on the provider's query so the cache+ // (and devtools) stays in sync; there's no separate useState copy.+ const valuesRef = useRef(values);+ valuesRef.current = values;++ const providerKey = config.id;+ const writeValues = useCallback(+ (updater: (prev: CredentialFormValues) => CredentialFormValues) => {+ qc.setQueryData<CredentialFormValues>(+ queryKeys.credentialValues.byProvider(providerKey).queryKey,+ (prev) => updater(prev ?? EMPTY_VALUES),+ );+ },+ [qc, providerKey],+ );++ const form = useRef({+ getFieldValue: (key: string): string | undefined => valuesRef.current[key],+ getFieldsValue: (): CredentialFormValues => ({ ...valuesRef.current }),+ setFieldValue: (key: string, value: string) => {+ writeValues((prev) => ({ ...prev, [key]: value }));+ },+ setFieldsValue: (next: CredentialFormValues) => {+ writeValues((prev) => ({ ...prev, ...next }));+ },+ resetFields: () => writeValues(() => EMPTY_VALUES),+ }).current;++ // Sync stored from query on first load — if the backend already has+ // a key, mark stored=true so the badge renders without a validate click.+ const queriedStored = Object.keys(values).length > 0;+ if (queriedStored && !stored) setStored(true);// Generic action executor — replaces 19 duplicate handler functions.const execute = useCallback(async (key: string, fn: () => Promise<any>) => {@@ -94,18 +122,38 @@ export function useCredentialPanel(config: ProviderConfig, visible: boolean) {}}, []);+ // After every mutation, invalidate the provider's credentialValues+ // query so the loader's queryFn re-runs against the backend — same+ // path as a page reload. Guarantees every observer (Connected badge,+ // Valid pill, ApiKeyInput isStored) reflects the new state.+ const invalidateValues = useCallback(() => {+ return qc.invalidateQueries({+ queryKey: queryKeys.credentialValues.byProvider(providerKey).queryKey,+ });+ }, [qc, providerKey]);+// Pre-built actions that panels call directly.const actions = {validate: (id: string, key: string) => execute('validate', async () => {- if (config.validateAs === 'google_maps') return validateGoogleMapsKey(key);- if (config.validateAs === 'apify') return validateApifyKey(key);- return validateApiKey(id, key);+ const r = await validateApiKey(id, key);+ if (r?.isValid) {+ setStored(true);+ await invalidateValues();+ }+ return r;+ }),+ save: (key: string, value: string) => execute('save', async () => {+ const r = await saveApiKey(key, value);+ if (r?.isValid) {+ setStored(true);+ await invalidateValues();+ }+ return r;}),- save: (key: string, value: string) => execute('save', () => saveApiKey(key, value)),remove: (key: string) => execute('remove', async () => {await removeApiKey(key);setStored(false);- setValues({});+ await invalidateValues();}),oauthLogin: () => execute('login', async () => {const res = await sendRequest(config.ws!.login, {});diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex a103d7c2..69dbcd97 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -555,17 +555,10 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiif (data.google) setGoogleStatus(data.google);if (data.telegram) setTelegramStatus(data.telegram);if (data.api_keys) {+ // SquareNode and the credentials modal both read from this+ // context map — no query cache to warm/invalidate for API+ // keys (the canvas never holds decrypted keys).setApiKeyStatuses(data.api_keys);- // Warm the per-provider storedApiKey query cache so SquareNode- // configured badges resolve from the broadcast without a- // separate get_stored_api_key round-trip per node.- for (const [provider, status] of Object.entries(data.api_keys)) {- const s = status as { hasKey?: boolean; api_key?: string | null };- queryClient.setQueryData(- queryKeys.storedApiKey.byProvider(provider).queryKey,- s?.hasKey ? s.api_key ?? null : null,- );- }}// Node statuses from initial_status - group by workflow_id (n8n pattern)if (data.nodes) {@@ -619,10 +612,8 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi...prev,[message.provider]: data}));- queryClient.setQueryData(- queryKeys.storedApiKey.byProvider(message.provider).queryKey,- data?.hasKey ? (data as any).api_key ?? null : null,- );+ // Sidebar catalogue's `stored` flag depends on server-side+ // api_keys + oauth state; refresh it.queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });}break;@@ -1148,7 +1139,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiws.send(JSON.stringify({ type: 'get_stored_api_key', provider, request_id: requestId }));});- if (response.has_key) {+ if (response.hasKey) {setApiKeyStatuses(prev => ({...prev,[provider]: { hasKey: true, valid: true }@@ -1834,14 +1825,21 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiprovider: string): Promise<{ hasKey: boolean; apiKey?: string; models?: string[] }> => {try {- const response = await sendRequest<any>('get_stored_api_key', { provider });+ // Backend emits camelCase (hasKey/apiKey) — same convention as the+ // update_api_key_status broadcast. No per-field adapter needed.+ const response = await sendRequest<{+ hasKey?: boolean;+ apiKey?: string;+ models?: string[];+ }>('get_stored_api_key', { provider });const result = {- hasKey: response.has_key || false,- apiKey: response.api_key,- models: response.models+ hasKey: !!response.hasKey,+ apiKey: response.apiKey,+ models: response.models,};- // Update apiKeyStatuses with stored models+ // Mirror into apiKeyStatuses so consumers reading from context+ // stay in sync without an extra round-trip.if (result.hasKey) {setApiKeyStatuses(prev => ({...prev,diff --git a/client/src/lib/queryConfig.ts b/client/src/lib/queryConfig.tsindex 2019fdbe..e01e59a8 100644--- a/client/src/lib/queryConfig.ts+++ b/client/src/lib/queryConfig.ts@@ -43,10 +43,13 @@ export const GC_TIME = {} as const;/**- * Decrypted value for a stored credential field. SquareNode reads it;- * WebSocketContext bridges `api_key_status` broadcasts into it.+ * Stored credential field values for a provider panel in the credentials+ * modal. One entry per provider. useCredentialPanel reads + updates it;+ * validate/save/remove mutations write through queryClient.setQueryData+ * so the cache always matches backend state and stays visible in+ * devtools.*/-const storedApiKey = createQueryKeys('storedApiKey', {+const credentialValues = createQueryKeys('credentialValues', {byProvider: (provider: string) => [provider],});@@ -61,10 +64,10 @@ const compactionStats = createQueryKeys('compactionStats', {});/**- * Merged factory. Consumers call- * queryKeys.storedApiKey.byProvider(provider).queryKey+ * Merged factory. Consumers call e.g.+ * queryKeys.credentialValues.byProvider(id).queryKey* for a specific key, and- * queryKeys.storedApiKey._def+ * queryKeys.credentialValues._def* for partial-match invalidation across the namespace.*/-export const queryKeys = mergeQueryKeys(storedApiKey, compactionStats);+export const queryKeys = mergeQueryKeys(credentialValues, compactionStats);diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex a223e22e..0dd6292a 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -1126,11 +1126,25 @@ async def handle_get_ai_models(data: Dict[str, Any], websocket: WebSocket) -> Di@ws_handler("provider", "api_key")async def handle_validate_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:- """Validate and store an API key."""+ """Validate and store an API key.++ Single entry point for all providers. Dispatches to provider-specific+ validators (Google Maps geocode probe, Apify /users/me probe) for+ non-LLM providers; otherwise falls through to the default LLM+ ``/v1/models`` probe via ``ai_service.fetch_models``. The frontend+ calls this one handler for every provider — no per-provider branching+ on the TypeScript side.+ """+ provider = data["provider"].lower()+ normalized = dict(data, provider=provider)++ if provider in _SPECIAL_PROVIDER_VALIDATORS:+ return await _SPECIAL_PROVIDER_VALIDATORS[provider](normalized, websocket)+ai_service = container.ai_service()auth_service = container.auth_service()broadcaster = get_status_broadcaster()- provider, api_key = data["provider"].lower(), data["api_key"].strip()+ api_key = data["api_key"].strip()# Fetch models for AI providers (any provider with a models_endpoint in llm_defaults.json)from services.ai import PROVIDER_CONFIGS@@ -1147,14 +1161,20 @@ async def handle_validate_api_key(data: Dict[str, Any], websocket: WebSocket) ->@ws_handler("provider")async def handle_get_stored_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:- """Get stored API key for a provider."""+ """Get stored API key for a provider.++ Response uses camelCase (``hasKey`` / ``apiKey``) to match the+ ``update_api_key_status`` broadcast shape — every WS payload the+ frontend receives for API key state uses the same convention, so no+ per-field adapter is needed on the TypeScript side.+ """auth_service = container.auth_service()provider = data["provider"].lower()api_key = await auth_service.get_api_key(provider, data.get("session_id", "default"))if not api_key:- return {"provider": provider, "has_key": False}+ return {"provider": provider, "hasKey": False}models = await auth_service.get_stored_models(provider, data.get("session_id", "default"))- return {"provider": provider, "has_key": True, "api_key": api_key, "models": models, "timestamp": time.time()}+ return {"provider": provider, "hasKey": True, "apiKey": api_key, "models": models, "timestamp": time.time()}@ws_handler("provider", "api_key")@@ -1864,6 +1884,15 @@ async def handle_validate_apify_key(data: Dict[str, Any], websocket: WebSocket)return {"success": False, "valid": False, "error": str(e)}+# Per-provider validation strategies. Register any non-LLM provider here+# and `handle_validate_api_key` will dispatch to it automatically, so the+# frontend only ever calls one WS message type.+_SPECIAL_PROVIDER_VALIDATORS = {+ "google_maps": handle_validate_maps_key,+ "apify": handle_validate_apify_key,+}++# ============================================================================# WhatsApp Handlers - Wrappers for services.whatsapp_service functions# ============================================================================diff --git a/server/tests/credentials/test_websocket_handlers.py b/server/tests/credentials/test_websocket_handlers.pyindex b863a160..884c8f0f 100644--- a/server/tests/credentials/test_websocket_handlers.py+++ b/server/tests/credentials/test_websocket_handlers.py@@ -6,7 +6,8 @@ LangChain / native LLM SDKs.Locks in invariants 1, 5, 6 from docs-internal/credentials_panel.md:- WebSocket message types and payload shapes- - Status responses use snake_case has_key+ - Status responses use camelCase hasKey / apiKey (matches the+ update_api_key_status broadcaster convention)- Provider Defaults uses dedicated handler, not save_api_key"""@@ -141,8 +142,8 @@ class TestGetStoredApiKey:ws_module.handle_get_stored_api_key, {"provider": "openai"}, fake_ws)assert result["success"] is True- assert result["has_key"] is False- assert "api_key" not in result+ assert result["hasKey"] is False+ assert "apiKey" not in resultasync def test_returns_key_and_models_when_present(self, patched_container, fake_ws@@ -155,8 +156,8 @@ class TestGetStoredApiKey:ws_module.handle_get_stored_api_key, {"provider": "OpenAI"}, fake_ws)- assert result["has_key"] is True- assert result["api_key"] == "sk-stored"+ assert result["hasKey"] is True+ assert result["apiKey"] == "sk-stored"assert result["models"] == ["gpt-4", "gpt-3.5"]assert result["provider"] == "openai"