Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(ui): eliminate TanStack Query loading-in-steps regression
trohitgb523390d0631
diff --git a/client/package.json b/client/package.jsonindex f51920c1..6b892898 100644--- a/client/package.json+++ b/client/package.json@@ -19,6 +19,7 @@"@fontsource-variable/geist": "^5.2.8","@hookform/resolvers": "^5.2.2","@lobehub/icons": "^2.45.0",+ "@lukemorales/query-key-factory": "^1.3.4","@radix-ui/react-collapsible": "^1.1.12","@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-slot": "^1.2.4",@@ -78,6 +79,7 @@},"devDependencies": {"@tailwindcss/vite": "^4.2.2",+ "@tanstack/react-query-devtools": "^5.99.0","@testing-library/jest-dom": "^6.9.1","@testing-library/react": "^16.3.2","@testing-library/user-event": "^14.5.2",diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 4a47ce7a..5d195f81 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -541,18 +541,19 @@ const DashboardContent: React.FC = () => {const proOptions = React.useMemo(() => ({ hideAttribution: true }), []);- // Wave 10.D step 2: nodeTypes is rebuilt once after the NodeSpec- // prefetch lands so spec.componentKind dispatch becomes effective.- // Using `useMemo` (not a ref) so React Flow actually sees the new- // reference and re-mounts nodes with the correct components (e.g.- // `aiAgent` → AIAgentNode instead of the SquareNode fallback chosen- // when the spec cache was cold). Before `specsReady`, returns the- // module-scope map (stable identity). After prefetch: returns the- // spec-aware map (stable identity for the rest of the session).- const nodeTypes = React.useMemo(- () => (specsReady ? createNodeTypes() : moduleNodeTypes),- [specsReady],- );+ // Wave 10.D step 2: nodeTypes dispatch map. Cold cache uses the+ // module-scope fallback (agents/skills/teamMonitor already correct via+ // hardcoded guards in createNodeTypes); post-prefetch we rebuild and+ // only swap the reference if any mapping genuinely differs, so React+ // Flow doesn't remount every canvas node for a no-op rebuild.+ const nodeTypes = React.useMemo(() => {+ if (!specsReady) return moduleNodeTypes;+ const fresh = createNodeTypes();+ for (const key of Object.keys(fresh)) {+ if (fresh[key] !== moduleNodeTypes[key]) return fresh;+ }+ return moduleNodeTypes;+ }, [specsReady]);const edgeTypes = moduleEdgeTypes;// Execute entire workflow from start node to enddiff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsxindex 9dc3aea9..5dbe8369 100644--- a/client/src/components/SquareNode.tsx+++ b/client/src/components/SquareNode.tsx@@ -8,6 +8,7 @@ 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';@@ -169,10 +170,10 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab}, [definition?.credentials, type]);const apiKeyQuery = useQuery<string | null, Error>({- queryKey: ['storedApiKey', providerId],+ ...queryKeys.storedApiKey.byProvider(providerId),queryFn: () => getStoredApiKey(providerId),enabled: !!providerId && wsConnected,- staleTime: 30_000,+ staleTime: STALE_TIME.SHORT,});const hasApiKey = !!apiKeyQuery.data;const isConfigured = hasApiKey && !!data && Object.keys(data).length > 0;diff --git a/client/src/components/credentials/useCredentialPanel.ts b/client/src/components/credentials/useCredentialPanel.tsindex ead7c8cd..474d210f 100644--- a/client/src/components/credentials/useCredentialPanel.ts+++ b/client/src/components/credentials/useCredentialPanel.ts@@ -47,29 +47,31 @@ export function useCredentialPanel(config: ProviderConfig, visible: boolean) {resetFields: () => setValues({}),}).current;- // Load stored values into form when panel becomes visible+ // 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 () => {- const next: CredentialFormValues = {};- let anyStored = false;- for (const field of config.fields!) {- const storeKey = field.key === 'apiKey' ? config.id : field.key;- const has = await hasStoredKey(storeKey);- if (has) {+ const entries = await Promise.all(+ config.fields!.map(async (field) => {+ const storeKey = field.key === 'apiKey' ? config.id : field.key;+ const has = await hasStoredKey(storeKey);+ if (!has) return null;const val = await getStoredApiKey(storeKey);- if (val && !cancelled) {- next[field.key] = val;- anyStored = true;- }- }- }- if (!cancelled) {- setValues(next);- setStored(anyStored);- setError(null);+ 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]);diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxindex f9bba2ce..d896afec 100644--- a/client/src/components/parameterPanel/MiddleSection.tsx+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -33,6 +33,8 @@ import { useAppTheme } from '../../hooks/useAppTheme';import { useAppStore } from '../../store/useAppStore';import { useWebSocket, CompactionStats } from '../../contexts/WebSocketContext';import { useUserSettingsQuery } from '../../hooks/useUserSettingsQuery';+import { nodeParamsQueryKey, type NodeParametersResponse } from '../../hooks/useNodeParamsQuery';+import { queryKeys, STALE_TIME } from '../../lib/queryConfig';import { nodeDefinitions } from '../../nodeDefinitions';import { INodeTypeDescription, INodeProperties } from '../../types/INodeProperties';import { resolveIcon, resolveLibraryIcon, isImageIcon } from '../../assets/icons';@@ -84,7 +86,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({}) => {const theme = useAppTheme();const { currentWorkflow } = useAppStore();- const { clearMemory, resetSkill, sendRequest, compactionStats: contextCompactionStats, updateCompactionStats } = useWebSocket();+ const { clearMemory, resetSkill, sendRequest, getNodeParameters, compactionStats: contextCompactionStats, updateCompactionStats } = useWebSocket();const [showClearMemoryDialog, setShowClearMemoryDialog] = useState(false);const [showResetSkillDialog, setShowResetSkillDialog] = useState(false);@@ -199,24 +201,20 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({return memoryEdge?.source ?? null;}, [isAgentWithSkills, currentWorkflow, nodeId]);- const memoryParamsQuery = useQuery<Record<string, any>, Error>({- queryKey: ['nodeParameters', memoryEdgeSourceId],- queryFn: async () => {- const response = await sendRequest<{ parameters: Record<string, any> }>(- 'get_node_parameters',- { node_id: memoryEdgeSourceId },- );- return response?.parameters ?? {};- },+ const memoryParamsQuery = useQuery<NodeParametersResponse | null, Error>({+ queryKey: memoryEdgeSourceId ? nodeParamsQueryKey(memoryEdgeSourceId) : nodeParamsQueryKey('none'),+ queryFn: () => (memoryEdgeSourceId ? getNodeParameters(memoryEdgeSourceId) : Promise.resolve(null)),enabled: !!memoryEdgeSourceId,- staleTime: 30_000,+ staleTime: STALE_TIME.MEDIUM,});+ const memoryParamsData = memoryParamsQuery.data?.parameters;+const connectedMemorySessionId = useMemo<string | null>(() => {if (!memoryEdgeSourceId) return null;- const configured: string = memoryParamsQuery.data?.sessionId || '';+ const configured: string = memoryParamsData?.sessionId || '';return configured && configured !== 'default' ? configured : nodeId;- }, [memoryEdgeSourceId, memoryParamsQuery.data?.sessionId, nodeId]);+ }, [memoryEdgeSourceId, memoryParamsData?.sessionId, nodeId]);const compactionStatsQuery = useQuery<{session_id: string;@@ -225,7 +223,11 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({context_length?: number;count: number;}, Error>({- queryKey: ['compactionStats', connectedMemorySessionId, parameters.model, parameters.provider],+ ...queryKeys.compactionStats.bySession(+ connectedMemorySessionId ?? '',+ parameters.model || '',+ parameters.provider || '',+ ),queryFn: () =>sendRequest('get_compaction_stats', {session_id: connectedMemorySessionId,@@ -233,7 +235,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({provider: parameters.provider || '',}),enabled: !!connectedMemorySessionId,- staleTime: 15_000,+ staleTime: STALE_TIME.SHORT,});const compactionLoading = compactionStatsQuery.isFetching;@@ -291,15 +293,9 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({const masterSkillParamsQueries = useQueries({queries: masterSkillEdgeSources.map((id) => ({- queryKey: ['nodeParameters', id],- queryFn: async () => {- const response = await sendRequest<{ parameters: Record<string, any> }>(- 'get_node_parameters',- { node_id: id },- );- return response?.parameters ?? {};- },- staleTime: 30_000,+ queryKey: nodeParamsQueryKey(id),+ queryFn: () => getNodeParameters(id),+ staleTime: STALE_TIME.MEDIUM,})),});@@ -307,7 +303,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({const out: Record<string, any> = {};masterSkillEdgeSources.forEach((id, i) => {const data = masterSkillParamsQueries[i]?.data;- if (data) out[id] = data;+ if (data?.parameters) out[id] = data.parameters;});return out;}, [masterSkillEdgeSources, masterSkillParamsQueries]);diff --git a/client/src/components/ui/ComponentPalette.tsx b/client/src/components/ui/ComponentPalette.tsxindex 0fc9bcd2..5b3d63b6 100644--- a/client/src/components/ui/ComponentPalette.tsx+++ b/client/src/components/ui/ComponentPalette.tsx@@ -6,6 +6,7 @@ import ComponentItem from './ComponentItem';import CollapsibleSection from './CollapsibleSection';import { Badge } from '@/components/ui/badge';import { Input } from '@/components/ui/input';+import { Skeleton } from '@/components/ui/skeleton';import { Search } from 'lucide-react';import { resolveIcon, resolveLibraryIcon, isImageIcon } from '../../assets/icons';import { useNodeGroups, NodeGroupEntry } from '../../lib/nodeSpec';@@ -26,9 +27,10 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({const theme = useAppTheme();// Backend-driven group metadata via the shared WS-in-queryFn hook.- // `useNodeGroups` auto-fires on WS connect and re-renders the palette- // with proper icons once the response lands.- const groupIndex = useNodeGroups();+ // `useNodeGroups` returns the full query result so we can render a+ // loading skeleton on cold first-paint instead of masking the filter+ // or flashing an empty palette.+ const { data: groupIndex, isPending: groupsLoading } = useNodeGroups();const getCategoryConfig = React.useCallback((category: string) => {const entry = groupIndex?.[category.toLowerCase()] as NodeGroupEntry | undefined;@@ -118,7 +120,9 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({{/* Categories */}<div className="flex-1 overflow-y-auto p-3">- {Object.keys(categorizedComponents).length === 0 ? (+ {groupsLoading ? (+ <PaletteSkeleton />+ ) : Object.keys(categorizedComponents).length === 0 ? (<div className="flex flex-col items-center px-6 py-12 text-center text-muted-foreground"><Search className="mb-3 h-12 w-12 opacity-50" /><p className="text-sm">@@ -195,4 +199,30 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({);};+/**+ * Loading placeholder for the palette's categories area. Mirrors the+ * shape of three collapsed category sections + a handful of items so+ * the layout does not jump when real data arrives.+ */+const PALETTE_SKELETON_CATEGORIES = 3;+const PALETTE_SKELETON_ITEMS_PER_CATEGORY = 2;++const PaletteSkeleton: React.FC = () => (+ <div aria-busy="true" aria-label="Loading components">+ {Array.from({ length: PALETTE_SKELETON_CATEGORIES }).map((_, categoryIdx) => (+ <div key={categoryIdx} className="mb-3 space-y-2">+ <div className="flex items-center gap-2.5 px-1 py-2">+ <Skeleton className="h-7 w-7 rounded-md" />+ <Skeleton className="h-4 w-24" />+ </div>+ <div className="grid gap-2 pt-2">+ {Array.from({ length: PALETTE_SKELETON_ITEMS_PER_CATEGORY }).map((_, itemIdx) => (+ <Skeleton key={itemIdx} className="h-10 w-full rounded-md" />+ ))}+ </div>+ </div>+ ))}+ </div>+);+export default ComponentPalette;\ No newline at end of filediff --git a/client/src/components/ui/skeleton.tsx b/client/src/components/ui/skeleton.tsxnew file mode 100644index 00000000..0118624f--- /dev/null+++ b/client/src/components/ui/skeleton.tsx@@ -0,0 +1,13 @@+import { cn } from "@/lib/utils"++function Skeleton({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="skeleton"+ className={cn("animate-pulse rounded-md bg-muted", className)}+ {...props}+ />+ )+}++export { Skeleton }diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 62216941..a103d7c2 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -15,6 +15,9 @@ import { API_CONFIG } from '../config/api';import { useAppStore } from '../store/useAppStore';import { useAuth } from './AuthContext';import { queryClient } from '../lib/queryClient';+import { queryKeys } from '../lib/queryConfig';+import { CATALOGUE_QUERY_KEY } from '../hooks/useCatalogueQuery';+import { nodeParamsQueryKey } from '../hooks/useNodeParamsQuery';// Generate unique request IDconst generateRequestId = (): string => {@@ -551,7 +554,19 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiif (data.twitter) setTwitterStatus(data.twitter);if (data.google) setGoogleStatus(data.google);if (data.telegram) setTelegramStatus(data.telegram);- if (data.api_keys) setApiKeyStatuses(data.api_keys);+ if (data.api_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) {const groupedStatuses: Record<string, Record<string, NodeStatus>> = {};@@ -563,7 +578,14 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi}setAllNodeStatuses(prev => ({ ...prev, ...groupedStatuses }));}- if (data.node_parameters) setNodeParameters(data.node_parameters);+ if (data.node_parameters) {+ setNodeParameters(data.node_parameters);+ // Warm the nodeParams query cache so MiddleSection's memory /+ // master-skill queries hit immediately on first open.+ for (const [nodeId, params] of Object.entries(data.node_parameters)) {+ queryClient.setQueryData(nodeParamsQueryKey(nodeId), params);+ }+ }// Variables from initial_status - group by workflow_id (n8n pattern)if (data.variables) {// Variables may come with workflow_id or need grouping@@ -585,6 +607,9 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chistatus: data.deployment.status || 'idle'});}+ // Catalogue 'stored' flags derive from api_keys + oauth state;+ // re-sync once after the bulk status lands.+ queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });}break;@@ -594,15 +619,28 @@ 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,+ );+ queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });}break;+ case 'credential_catalogue_updated':+ // Future server emitter (per useCatalogueQuery.ts TODO). Client+ // handler is wired now so once the server pushes it, consumers+ // refresh automatically.+ queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });+ break;+case 'android_status':setAndroidStatus(data || defaultAndroidStatus);break;case 'whatsapp_status':setWhatsappStatus(data || defaultWhatsAppStatus);+ queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });break;case 'twitter_oauth_complete':@@ -615,6 +653,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiname: data.name,profile_image_url: data.profile_image_url,});+ queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });}break;@@ -627,6 +666,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiname: data.name,profile_image_url: data.profile_image_url,});+ queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });}break;@@ -638,6 +678,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiemail: data.email || null,name: data.name,});+ queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });}break;@@ -651,6 +692,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chibot_id: data.bot_id || null,owner_chat_id: data.owner_chat_id ?? null,});+ queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });}break;@@ -753,14 +795,13 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi// Node parameters broadcasts (from other clients)case 'node_parameters_updated':if (node_id) {- setNodeParameters(prev => ({- ...prev,- [node_id]: {- parameters: message.parameters,- version: message.version,- timestamp: message.timestamp- }- }));+ const nextParams = {+ parameters: message.parameters,+ version: message.version,+ timestamp: message.timestamp,+ };+ setNodeParameters(prev => ({ ...prev, [node_id]: nextParams }));+ queryClient.setQueryData(nodeParamsQueryKey(node_id), nextParams);}break;@@ -771,6 +812,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chidelete updated[node_id];return updated;});+ queryClient.removeQueries({ queryKey: nodeParamsQueryKey(node_id) });}break;@@ -1003,6 +1045,11 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi}};});+ // Session-scoped invalidation: the query key also carries+ // model + provider, which aren't in the broadcast payload, so+ // we invalidate the whole namespace and let the ~1-2 mounted+ // compaction queries refetch fresh values.+ queryClient.invalidateQueries({ queryKey: queryKeys.compactionStats._def });}break;}@@ -1027,6 +1074,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi}return updated;});+ queryClient.invalidateQueries({ queryKey: queryKeys.compactionStats._def });}break;}diff --git a/client/src/lib/nodeSpec.ts b/client/src/lib/nodeSpec.tsindex d22e3338..1da1159e 100644--- a/client/src/lib/nodeSpec.ts+++ b/client/src/lib/nodeSpec.ts@@ -12,11 +12,12 @@* See C:\\Users\\Tgroh\\.claude\\plans\\typed-splashing-crown.md.*/-import { useQuery } from '@tanstack/react-query';+import { useQuery, type UseQueryResult } from '@tanstack/react-query';import { nodeSpecToDescription, type NodeSpec } from '../adapters/nodeSpecToDescription';import type { INodeTypeDescription } from '../types/INodeProperties';import { featureFlags } from './featureFlags';import { queryClient } from './queryClient';+import { STALE_TIME } from './queryConfig';import { useWebSocket } from '../contexts/WebSocketContext';type SendRequest = (type: string, data?: any) => Promise<any>;@@ -42,7 +43,7 @@ export async function fetchNodeSpec(return null;}},- staleTime: Infinity,+ staleTime: STALE_TIME.FOREVER,});}@@ -98,29 +99,31 @@ export function useNodeSpec(nodeType: string | undefined | null): NodeSpec | nul}},enabled: !!nodeType && isConnected,- staleTime: 60_000, // 60s — short enough to pick up backend restarts in dev- refetchOnMount: 'always',+ // Node specs only change with a backend deploy; dev restarts are+ // covered by the WS reconnect handler which invalidates ['nodeSpec'].+ staleTime: STALE_TIME.FOREVER,});return data ?? null;}/*** Reactive node-groups subscription. Same WS-in-queryFn pattern as- * `useNodeSpec`. Replaces the old double-wrapped `fetchNodeGroups`- * call inside `useQuery` (which deadlocked on the shared query key).+ * `useNodeSpec`. Returns the full `UseQueryResult` so callers can+ * branch on `data` / `isPending` / `error` and render a proper loading+ * state rather than masking missing data. Matches TkDodo's recommended+ * status-check pattern: check data first, error second, loading last.*/-export function useNodeGroups(): Record<string, NodeGroupEntry> | undefined {+export function useNodeGroups(): UseQueryResult<Record<string, NodeGroupEntry>> {const { sendRequest, isConnected } = useWebSocket();- const { data } = useQuery<Record<string, NodeGroupEntry>>({+ return useQuery<Record<string, NodeGroupEntry>>({queryKey: nodeGroupsQueryKey,queryFn: async () => {const response = await sendRequest('get_node_groups', {});return (response?.groups ?? {}) as Record<string, NodeGroupEntry>;},enabled: isConnected,- staleTime: Infinity,+ staleTime: STALE_TIME.FOREVER,});- return data;}/** Wire shape for one entry in the GET /api/schemas/nodes/groups@@ -150,7 +153,7 @@ export async function fetchNodeGroups(const response = await sendRequest('get_node_groups', {});return (response?.groups ?? {}) as Record<string, NodeGroupEntry>;},- staleTime: Infinity,+ staleTime: STALE_TIME.FOREVER,});}diff --git a/client/src/lib/queryClient.ts b/client/src/lib/queryClient.tsindex 37817a5f..b2c4edc1 100644--- a/client/src/lib/queryClient.ts+++ b/client/src/lib/queryClient.ts@@ -1,4 +1,5 @@import { QueryClient } from '@tanstack/react-query';+import { GC_TIME, STALE_TIME } from './queryConfig';/*** Single app-wide QueryClient. Cache lives across route changes and modal@@ -7,16 +8,22 @@ import { QueryClient } from '@tanstack/react-query';* imperative code (Zustand actions, workflowApi mutations) can invalidate* queries without needing React context.*+ * Defaults match the WS-push architecture: data is considered fresh for+ * STALE_TIME.SHORT by default and components trust the cache on mount.+ * The broadcast bridge in WebSocketContext keeps the cache in sync with+ * server state, so refetch-on-mount is unnecessary overhead.+ ** See docs-internal/credentials_scaling/architecture.md for cache shape.*/export const queryClient = new QueryClient({defaultOptions: {queries: {- // Most server data is push-driven via WebSocket, so queries should- // stay stable unless we explicitly invalidate them.refetchOnWindowFocus: false,refetchOnReconnect: false,+ refetchOnMount: false,retry: 1,+ staleTime: STALE_TIME.SHORT,+ gcTime: GC_TIME.DEFAULT,},},});diff --git a/client/src/lib/queryConfig.ts b/client/src/lib/queryConfig.tsnew file mode 100644index 00000000..2019fdbe--- /dev/null+++ b/client/src/lib/queryConfig.ts@@ -0,0 +1,70 @@+/**+ * Centralized TanStack Query configuration.+ *+ * All cache-time constants and cross-file query keys live here. Hook-local+ * keys (those consumed in a single file) stay next to their owning hook;+ * only keys read or written from more than one module are centralized.+ *+ * Query keys are built with the community-standard+ * `@lukemorales/query-key-factory` (recommended by the TanStack Query+ * docs) so key shapes, partial-match `_def` scopes, and TypeScript+ * inference are all library-managed instead of hand-rolled.+ *+ * See:+ * docs-internal/credentials_scaling/architecture.md (cache shape)+ * docs-internal/frontend_architecture.md (WS-push model)+ * https://tanstack.com/query/v5/docs/framework/react/community/lukemorales-query-key-factory+ */++import { createQueryKeys, mergeQueryKeys } from '@lukemorales/query-key-factory';++/**+ * Stale-time buckets keyed by update cadence of the underlying data.+ * Values are milliseconds.+ */+export const STALE_TIME = {+ /** Fast-changing data; tolerates occasional refetch on mount. */+ SHORT: 30_000,+ /** Moderately stable (user settings, node parameters). */+ MEDIUM: 60_000,+ /** Stable data held across route changes and modal cycles. */+ LONG: 5 * 60_000,+ /** Data that only changes with a backend deploy or explicit invalidate. */+ FOREVER: Infinity,+} as const;++/**+ * Garbage-collection times. Longer values keep cache entries in memory+ * after the last consumer unmounts, improving warm-open latency.+ */+export const GC_TIME = {+ DEFAULT: 5 * 60_000,+ CATALOGUE: 10 * 60_000,+} as const;++/**+ * Decrypted value for a stored credential field. SquareNode reads it;+ * WebSocketContext bridges `api_key_status` broadcasts into it.+ */+const storedApiKey = createQueryKeys('storedApiKey', {+ byProvider: (provider: string) => [provider],+});++/**+ * Compaction / token-usage stats for a memory session. MiddleSection+ * reads it; WebSocketContext bridges `token_usage_update` and+ * `compaction_completed` broadcasts into it.+ */+const compactionStats = createQueryKeys('compactionStats', {+ bySession: (sessionId: string, model: string, provider: string) =>+ [sessionId, model, provider],+});++/**+ * Merged factory. Consumers call+ * queryKeys.storedApiKey.byProvider(provider).queryKey+ * for a specific key, and+ * queryKeys.storedApiKey._def+ * for partial-match invalidation across the namespace.+ */+export const queryKeys = mergeQueryKeys(storedApiKey, compactionStats);diff --git a/client/src/main.tsx b/client/src/main.tsxindex 78d5e22a..def1e44d 100644--- a/client/src/main.tsx+++ b/client/src/main.tsx@@ -1,6 +1,7 @@import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import { QueryClientProvider } from '@tanstack/react-query'+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'import './index.css'import App from './App'import { ThemeProvider } from './contexts/ThemeContext'@@ -18,6 +19,9 @@ createRoot(document.getElementById('root')!).render(</WebSocketProvider></AuthProvider></ThemeProvider>+ {import.meta.env.DEV && (+ <ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-right" />+ )}</QueryClientProvider></StrictMode>,)diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3ccc3f10..e356ab2e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -10,7 +10,7 @@ importers:dependencies:agent-browser:specifier: latest- version: 0.25.4+ version: 0.25.5concurrently:specifier: ^9.2.1version: 9.2.1@@ -41,6 +41,9 @@ importers:'@lobehub/icons':specifier: ^2.45.0version: 2.45.0(@babel/[email protected])(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))([email protected])+ '@lukemorales/query-key-factory':+ specifier: ^1.3.4'@radix-ui/react-collapsible':specifier: ^1.1.12version: 1.1.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -186,6 +189,9 @@ importers:'@tailwindcss/vite':specifier: ^4.2.2version: 4.2.2([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ '@tanstack/react-query-devtools':+ specifier: ^5.99.0'@testing-library/jest-dom':specifier: ^6.9.1version: 6.9.1@@ -1281,6 +1287,13 @@ packages:react: ^19.0.0react-dom: ^19.0.0+ '@lukemorales/[email protected]':+ resolution: {integrity: sha512-A3frRDdkmaNNQi6mxIshsDk4chRXWoXa05US8fBo4kci/H+lVmujS6QrwQLLGIkNIRFGjMqp2uKjC4XsLdydRw==}+ engines: {node: '>=14'}+ peerDependencies:+ '@tanstack/query-core': '>= 4.0.0'+ '@tanstack/react-query': '>= 4.0.0'+'@mdx-js/[email protected]':resolution: {integrity: sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ==}@@ -2390,6 +2403,15 @@ packages:'@tanstack/[email protected]':resolution: {integrity: sha512-3Jv3WQG0BCcH7G+7lf/bP8QyBfJOXeY+T08Rin3GZ1bshvwlbPt7NrDHMEzGdKIOmOzvIQmxjk28YEQX60k7pQ==}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-m4ufXaJ8FjWXw7xDtyzE/6fkZAyQFg9WrbMrUpt8ZecRJx58jiFOZ2lxZMphZdIpAnIeto/S8stbwLKLusyckQ==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-CqqX7LCU9yOfCY/vBURSx2YSD83ryfX+QkfkaKionTfg1s2Hdm572Ro99gW3QPoJjzvsj1HM4pnN4nbDy3MXKA==}+ peerDependencies:+ '@tanstack/react-query': ^5.99.0+ react: ^18 || ^19+'@tanstack/[email protected]':resolution: {integrity: sha512-OY2bCqPemT1LlqJ8Y2CUau4KELnIhhG9Ol3ZndPbdnB095pRbPo1cHuXTndg8iIwtoHTgwZjyaDnQ0xD0mYwAw==}peerDependencies:@@ -2776,8 +2798,8 @@ packages:resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}engines: {node: '>= 14'}- resolution: {integrity: sha512-vl4tzDAk5+pJ2g8eMWWzZOLJ2yevJDN3YQ1gcSdN3GKPI0RwNr+T/2PxqSxsipiREu0oid2yxFJIoQ6NMrq/fQ==}+ resolution: {integrity: sha512-i7ZHsnB0nZIfZoQj9xavTJNX9nckTVVcaaiWFAaOiEQgvGytzVjftA3PIdq0WiuGba8vsxsYH2XMHxs+9bJkIw==}hasBin: true@@ -7784,6 +7806,11 @@ snapshots:- supports-color- vue+ '@lukemorales/[email protected](@tanstack/[email protected])(@tanstack/[email protected]([email protected]))':+ dependencies:+ '@tanstack/query-core': 5.99.0+ '@tanstack/react-query': 5.99.0([email protected])+'@mdx-js/[email protected]':dependencies:'@types/estree': 1.0.8@@ -8986,6 +9013,14 @@ snapshots:'@tanstack/[email protected]': {}+ '@tanstack/[email protected]': {}++ dependencies:+ '@tanstack/query-devtools': 5.99.0+ '@tanstack/react-query': 5.99.0([email protected])+ react: 19.2.1+'@tanstack/[email protected]([email protected])':dependencies:'@tanstack/query-core': 5.99.0@@ -9466,7 +9501,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}dependencies: