Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
fix(ui): guard error/loading surfaces and the ws reconnect tail
Sergey Kozyrenkof3972bb9d1b6
diff --git a/frontend/src/components/dashboard/chart-card.tsx b/frontend/src/components/dashboard/chart-card.tsxindex a1f122a7..f89e1771 100644--- a/frontend/src/components/dashboard/chart-card.tsx+++ b/frontend/src/components/dashboard/chart-card.tsx@@ -1,8 +1,9 @@import type { ReactNode } from 'react';-import { AlertCircle, BarChart2 } from 'lucide-react';+import { BarChart2 } from 'lucide-react';import { ResponsiveContainer } from 'recharts';+import { DashboardError } from '@/components/dashboard/dashboard-error';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';import { Spinner } from '@/components/ui/spinner';@@ -43,13 +44,10 @@ export function ChartCard({/></div>) : error ? (- <div- className="flex flex-col items-center justify-center gap-2"+ <DashboardError+ iconClassName="size-10"style={{ height }}- >- <AlertCircle className="text-muted-foreground/40 size-10" />- <p className="text-muted-foreground text-sm">Couldn't load</p>- </div>+ />) : empty ? (<divclassName="flex flex-col items-center justify-center gap-2"diff --git a/frontend/src/components/dashboard/dashboard-error.tsx b/frontend/src/components/dashboard/dashboard-error.tsxnew file mode 100644index 00000000..193bf99d--- /dev/null+++ b/frontend/src/components/dashboard/dashboard-error.tsx@@ -0,0 +1,25 @@+import type { CSSProperties } from 'react';++import { AlertCircle } from 'lucide-react';++import { cn } from '@/lib/utils';++export function DashboardError({+ className,+ iconClassName,+ style,+}: {+ className?: string;+ iconClassName?: string;+ style?: CSSProperties;+}) {+ return (+ <div+ className={cn('text-muted-foreground flex flex-col items-center justify-center gap-2', className)}+ style={style}+ >+ <AlertCircle className={cn('text-muted-foreground/40 size-6', iconClassName)} />+ <p className="text-sm">Couldn't load</p>+ </div>+ );+}diff --git a/frontend/src/components/shared/error-state.tsx b/frontend/src/components/shared/error-state.tsxindex be903bec..76901af5 100644--- a/frontend/src/components/shared/error-state.tsx+++ b/frontend/src/components/shared/error-state.tsx@@ -11,7 +11,7 @@ interface ErrorStateProps {export function ErrorState({ message, onRetry, title }: ErrorStateProps) {return (- <Empty>+ <Empty role="alert"><EmptyHeader><EmptyMedia><AlertCircle className="text-destructive size-12" />diff --git a/frontend/src/components/shared/loading-state.tsx b/frontend/src/components/shared/loading-state.tsxnew file mode 100644index 00000000..b3cc2067--- /dev/null+++ b/frontend/src/components/shared/loading-state.tsx@@ -0,0 +1,24 @@+import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';+import { Spinner } from '@/components/ui/spinner';++interface LoadingStateProps {+ description?: string;+ title: string;+}++export function LoadingState({ description, title }: LoadingStateProps) {+ return (+ <Empty>+ <EmptyHeader>+ <EmptyMedia>+ <Spinner+ className="text-muted-foreground size-10"+ variant="circle"+ />+ </EmptyMedia>+ <EmptyTitle>{title}</EmptyTitle>+ {description ? <EmptyDescription>{description}</EmptyDescription> : null}+ </EmptyHeader>+ </Empty>+ );+}diff --git a/frontend/src/components/shared/terminal/terminal.test.tsx b/frontend/src/components/shared/terminal/terminal.test.tsxindex 7d139455..a10af800 100644--- a/frontend/src/components/shared/terminal/terminal.test.tsx+++ b/frontend/src/components/shared/terminal/terminal.test.tsx@@ -39,7 +39,16 @@ vi.mock('./terminal-sanitizer', () => ({ processLog: (line: string) => line }));import Terminal from './terminal';-const visibleLines = () => xterm.visible.split('\r\n').filter(Boolean);+const visibleLines = () => {+ const lines = xterm.visible.split('\r\n');++ // Keep interior blank lines (garbling can surface as a stray \r\n); drop only the trailing terminator.+ if (lines.at(-1) === '') {+ lines.pop();+ }++ return lines;+};const reset = () => {xterm.visible = '';diff --git a/frontend/src/components/shared/terminal/use-xterm.test.ts b/frontend/src/components/shared/terminal/use-xterm.test.tsnew file mode 100644index 00000000..5522e767--- /dev/null+++ b/frontend/src/components/shared/terminal/use-xterm.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest';++import { writeWithFlowControl } from './use-xterm';++const CHUNK = 64 * 1024;++// A terminal mock that defers each chunk's flow-control callback, so a clear() can+// interleave between chunks — the exact window use-xterm's generation token closes.+const deferredTerminal = () => {+ const writes: string[] = [];+ const pending: Array<() => void> = [];++ return {+ drainNext: () => pending.shift()?.(),+ pendingCount: () => pending.length,+ terminal: {+ write: (chunk: string, callback?: () => void) => {+ writes.push(chunk);++ if (callback) {+ pending.push(callback);+ }+ },+ } as unknown as Parameters<typeof writeWithFlowControl>[0],+ writes,+ };+};++describe('writeWithFlowControl', () => {+ it('stops draining once the write goes stale (a clear cancels in-flight chunks)', () => {+ const mock = deferredTerminal();+ const data = 'a'.repeat(CHUNK * 3 + 100);++ let isStale = false;+ writeWithFlowControl(mock.terminal, data, () => isStale);++ expect(mock.writes.length).toBe(1);+ mock.drainNext();+ expect(mock.writes.length).toBe(2);++ isStale = true;+ const writtenBeforeClear = mock.writes.length;++ while (mock.pendingCount() > 0) {+ mock.drainNext();+ }++ expect(mock.writes.length).toBe(writtenBeforeClear);+ });++ it('drains the whole payload intact when never stale', () => {+ const mock = deferredTerminal();+ const data = 'b'.repeat(CHUNK * 3 + 100);++ writeWithFlowControl(mock.terminal, data, () => false);++ while (mock.pendingCount() > 0) {+ mock.drainNext();+ }++ expect(mock.writes.join('')).toBe(data);+ });+});diff --git a/frontend/src/components/shared/terminal/use-xterm.ts b/frontend/src/components/shared/terminal/use-xterm.tsindex 0ebd1f2b..072a87e5 100644--- a/frontend/src/components/shared/terminal/use-xterm.ts+++ b/frontend/src/components/shared/terminal/use-xterm.ts@@ -41,6 +41,7 @@ export interface UseXtermResult {export function useXterm({ theme }: { theme: 'dark' | 'light' | 'system' }): UseXtermResult {const containerRef = useRef<HTMLDivElement | null>(null);const terminalRef = useRef<null | Terminal>(null);+ const writeTokenRef = useRef(0);const themeRef = useRef(theme);const [isReady, setIsReady] = useState(false);const [searchAddon, setSearchAddon] = useState<null | SearchAddon>(null);@@ -57,7 +58,8 @@ export function useXterm({ theme }: { theme: 'dark' | 'light' | 'system' }): Use}try {- writeWithFlowControl(terminal, data);+ const token = writeTokenRef.current;+ writeWithFlowControl(terminal, data, () => token !== writeTokenRef.current);} catch (error: unknown) {Log.error('Terminal write failed:', error);}@@ -65,6 +67,9 @@ export function useXterm({ theme }: { theme: 'dark' | 'light' | 'system' }): Useconst clear = useCallback(() => {try {+ // Invalidate any in-flight chunked write so its trailing chunks don't land+ // after the clear and interleave with the next write.+ writeTokenRef.current += 1;terminalRef.current?.clear();} catch (error: unknown) {Log.error('Terminal clear failed:', error);@@ -257,6 +262,56 @@ export function useXterm({ theme }: { theme: 'dark' | 'light' | 'system' }): Usereturn { clear, containerRef, isReady, scrollToBottom, searchAddon, write };}+/**+ * Writes data to the terminal with chunked flow control.+ * For large payloads, splits into chunks and uses xterm's write callback+ * to avoid overwhelming the parser and blocking the UI thread.+ *+ * Chunk boundaries are adjusted to avoid splitting UTF-16 surrogate pairs:+ * if the last code unit of a chunk is a high surrogate (0xD800-0xDBFF),+ * the boundary is moved back by one so the pair stays intact.+ *+ * See: https://xtermjs.org/docs/guides/flowcontrol/+ */+export function writeWithFlowControl(terminal: Terminal, data: string, isStale: () => boolean = () => false): void {+ if (data.length <= FLOW_CONTROL_CHUNK_SIZE) {+ terminal.write(data);++ return;+ }++ let offset = 0;++ const writeNext = () => {+ // A clear() (or a superseding write) bumps the generation token; stop draining so+ // trailing chunks of this write don't land after the buffer was cleared.+ if (isStale()) {+ return;+ }++ let end = Math.min(offset + FLOW_CONTROL_CHUNK_SIZE, data.length);++ if (end < data.length) {+ const code = data.charCodeAt(end - 1);++ if (code >= 0xd800 && code <= 0xdbff) {+ end--;+ }+ }++ const chunk = data.slice(offset, end);+ offset = end;++ if (offset < data.length) {+ terminal.write(chunk, writeNext);+ } else {+ terminal.write(chunk);+ }+ };++ writeNext();+}+function removeLinkTooltip(container: HTMLElement): void {const existing = container.querySelector(`.${TOOLTIP_CLASS}`);@@ -300,47 +355,3 @@ function showLinkTooltip(container: HTMLElement, event: MouseEvent, uri: string,tooltip.style.top = `${Math.max(0, y)}px`;}--/**- * Writes data to the terminal with chunked flow control.- * For large payloads, splits into chunks and uses xterm's write callback- * to avoid overwhelming the parser and blocking the UI thread.- *- * Chunk boundaries are adjusted to avoid splitting UTF-16 surrogate pairs:- * if the last code unit of a chunk is a high surrogate (0xD800-0xDBFF),- * the boundary is moved back by one so the pair stays intact.- *- * See: https://xtermjs.org/docs/guides/flowcontrol/- */-function writeWithFlowControl(terminal: Terminal, data: string): void {- if (data.length <= FLOW_CONTROL_CHUNK_SIZE) {- terminal.write(data);-- return;- }-- let offset = 0;-- const writeNext = () => {- let end = Math.min(offset + FLOW_CONTROL_CHUNK_SIZE, data.length);-- if (end < data.length) {- const code = data.charCodeAt(end - 1);-- if (code >= 0xd800 && code <= 0xdbff) {- end--;- }- }-- const chunk = data.slice(offset, end);- offset = end;-- if (offset < data.length) {- terminal.write(chunk, writeNext);- } else {- terminal.write(chunk);- }- };-- writeNext();-}diff --git a/frontend/src/components/ui/spinner.tsx b/frontend/src/components/ui/spinner.tsxindex 1f99cf0d..bbb0a6a1 100644--- a/frontend/src/components/ui/spinner.tsx+++ b/frontend/src/components/ui/spinner.tsx@@ -8,7 +8,7 @@ export type SpinnerProps = LucideProps & {type SpinnerVariantProps = Omit<SpinnerProps, 'variant'>;-export function Spinner({ variant, ...props }: SpinnerProps) {+export function Spinner({ variant = 'circle', ...props }: SpinnerProps) {switch (variant) {case 'bars':return <Bars {...props} />;diff --git a/frontend/src/features/flows/dashboard/flow-dashboard-overview.tsx b/frontend/src/features/flows/dashboard/flow-dashboard-overview.tsxindex d9788a34..1aad799b 100644--- a/frontend/src/features/flows/dashboard/flow-dashboard-overview.tsx+++ b/frontend/src/features/flows/dashboard/flow-dashboard-overview.tsx@@ -22,7 +22,11 @@ import {import { formatCost, formatDuration, formatNumber, formatTokenCount } from '@/lib/utils/format';export function FlowDashboardOverview({ flowId }: { flowId: string }) {- const { data: usageData, loading: usageLoading } = useQuery(UsageStatsByFlowDocument, {+ const {+ data: usageData,+ error: usageError,+ loading: usageLoading,+ } = useQuery(UsageStatsByFlowDocument, {variables: { flowId },});const { data: usageByAgentData, loading: usageByAgentLoading } = useQuery(UsageStatsByAgentTypeForFlowDocument, {@@ -34,7 +38,11 @@ export function FlowDashboardOverview({ flowId }: { flowId: string }) {variables: { flowId },},);- const { data: toolcallsData, loading: toolcallsLoading } = useQuery(ToolcallsStatsByFlowDocument, {+ const {+ data: toolcallsData,+ error: toolcallsError,+ loading: toolcallsLoading,+ } = useQuery(ToolcallsStatsByFlowDocument, {variables: { flowId },});const { data: toolcallsByFunctionData, loading: toolcallsByFunctionLoading } = useQuery(@@ -43,7 +51,11 @@ export function FlowDashboardOverview({ flowId }: { flowId: string }) {variables: { flowId },},);- const { data: flowStatsData, loading: flowStatsLoading } = useQuery(FlowStatsByFlowDocument, {+ const {+ data: flowStatsData,+ error: flowStatsError,+ loading: flowStatsLoading,+ } = useQuery(FlowStatsByFlowDocument, {variables: { flowId },});@@ -112,6 +124,7 @@ export function FlowDashboardOverview({ flowId }: { flowId: string }) {<div className="grid grid-cols-2 gap-4 md:grid-cols-4"><MetricCarddescription={`Subtasks: ${flowStats?.totalSubtasksCount ?? 0} · Assistants: ${flowStats?.totalAssistantsCount ?? 0}`}+ error={!!flowStatsError}icon={<GitFork className="text-muted-foreground size-4" />}loading={anyLoading}title="Tasks"@@ -119,6 +132,7 @@ export function FlowDashboardOverview({ flowId }: { flowId: string }) {/><MetricCarddescription={`Duration: ${toolcalls ? formatDuration(toolcalls.totalDurationSeconds) : '—'}`}+ error={!!toolcallsError}icon={<Activity className="text-muted-foreground size-4" />}loading={anyLoading}title="Tool Calls"@@ -126,6 +140,7 @@ export function FlowDashboardOverview({ flowId }: { flowId: string }) {/><MetricCarddescription="Input + Output tokens"+ error={!!usageError}icon={<Cpu className="text-muted-foreground size-4" />}loading={anyLoading}title="Tokens"@@ -133,6 +148,7 @@ export function FlowDashboardOverview({ flowId }: { flowId: string }) {/><MetricCarddescription="LLM spending for this flow"+ error={!!usageError}icon={<CircleDollarSign className="text-muted-foreground size-4" />}loading={anyLoading}title="Cost"diff --git a/frontend/src/features/flows/terminal/flow-terminal.tsx b/frontend/src/features/flows/terminal/flow-terminal.tsxindex a94b2a81..af10bca2 100644--- a/frontend/src/features/flows/terminal/flow-terminal.tsx+++ b/frontend/src/features/flows/terminal/flow-terminal.tsx@@ -128,7 +128,8 @@ function FlowTerminal() {};const handleClearSearch = () => {- form.reset({ search: '' });+ // Clear only the search — form.reset would drop the task/subtask filter too.+ form.setValue('search', '');setDebouncedSearchValue('');debouncedUpdateSearch.cancel();};diff --git a/frontend/src/lib/apollo.test.ts b/frontend/src/lib/apollo.test.tsindex a7aa2943..4e320c17 100644--- a/frontend/src/lib/apollo.test.ts+++ b/frontend/src/lib/apollo.test.ts@@ -1,7 +1,7 @@import { gql, InMemoryCache, Observable } from '@apollo/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { createStreamingLink, updateCacheForSubscription } from './apollo';+import { createCache, createStreamingLink, updateCacheForSubscription } from './apollo';const TERMINAL = gql`query T($flowId: ID!) {@@ -31,20 +31,7 @@ const FLOWS = gql`}`;-// Mirrors the flow-scoped list fields in the production cache: keyed by flowId,-// query writes replace wholesale (the subscription link mutates via cache.modify).-const makeCache = () =>- new InMemoryCache({- typePolicies: {- Query: {- fields: {- flows: { merge: (_existing, incoming) => incoming },- tasks: { keyArgs: ['flowId'], merge: (_existing, incoming) => incoming },- terminalLogs: { keyArgs: ['flowId'], merge: (_existing, incoming) => incoming },- },- },- },- });+const makeCache = createCache;// The subscription payload carries `__typename` + fields; updateCacheForSubscription's// param is the minimal `{ id }` contract, so route literals through this to keepdiff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.tsindex c2015bc2..97f4d6f1 100644--- a/frontend/src/lib/apollo.ts+++ b/frontend/src/lib/apollo.ts@@ -382,6 +382,67 @@ const replaceWithIncoming = {merge: (_existing: unknown, incoming: unknown) => incoming,};+export const createCache = () =>+ new InMemoryCache({+ typePolicies: {+ APIToken: {+ keyFields: ['tokenId'],+ },+ KnowledgeDocument: {+ fields: {+ // `content` arrives empty from the list query (withContent:false,+ // to save bandwidth) but full from the detail query — both+ // normalize to this shared entity. Never let an empty incoming+ // blank out a body the detail already loaded.+ content: {+ merge: (existing: string | undefined, incoming: string) => incoming || existing || '',+ },+ },+ },+ ProviderConfig: {+ keyFields: (object) => {+ if (object.id === 0 || object.id === '0') {+ return false;+ }++ return ['id'];+ },+ },+ Query: {+ fields: {+ agentLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },+ apiTokens: { ...replaceWithIncoming },+ assistantLogs: { keyArgs: ['flowId', 'assistantId'], ...replaceWithIncoming },+ assistants: { keyArgs: ['flowId'], ...replaceWithIncoming },+ flow: {+ read(existing, { args, toReference }) {+ if (!args?.flowId) {+ return existing;+ }++ return existing ?? toReference({ __typename: 'Flow', id: args.flowId });+ },+ },+ flowFiles: { keyArgs: ['flowId'], ...replaceWithIncoming },+ flows: { ...replaceWithIncoming },+ flowTemplates: { ...replaceWithIncoming },+ knowledgeDocuments: { keyArgs: ['filter', 'withContent'], ...replaceWithIncoming },+ messageLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },+ providers: { ...replaceWithIncoming },+ resources: { keyArgs: ['path', 'recursive'], ...replaceWithIncoming },+ screenshots: { keyArgs: ['flowId'], ...replaceWithIncoming },+ searchLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },+ settingsPrompts: { ...replaceWithIncoming },+ settingsProviders: { ...replaceWithIncoming },+ settingsUser: { ...replaceWithIncoming },+ tasks: { keyArgs: ['flowId'], ...replaceWithIncoming },+ terminalLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },+ vectorStoreLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },+ },+ },+ },+ });+const createApolloClient = () => {// Holds the client for the ws `connected` handler, which is defined before the// client exists; `lazy: true` means the socket only opens on the first@@ -405,7 +466,17 @@ const createApolloClient = () => {// published while we were disconnected — so on a reconnect refetch// active queries to reconcile the cache with the backend.if (wasRetry) {- void clientRef.current?.refetchObservableQueries();+ // Unlike per-query refetch(), the aggregate promise isn't wrapped+ // in preventUnhandledRejection — a failed reconcile (e.g. a transient+ // 502 during the reconnect) would otherwise surface as an+ // unhandledrejection.+ void clientRef.current?.refetchObservableQueries().catch((error: unknown) => {+ Log.error('Reconnect cache reconcile failed:', error);+ });++ // refetchObservableQueries skips cache-only queries, so the REST-hydrated+ // resources slot isn't reconciled above — its provider re-fetches on this.+ window.dispatchEvent(new Event('ws:reconnected'));}},connecting: () => Log.debug('GraphQL WebSocket connecting...'),@@ -466,65 +537,7 @@ const createApolloClient = () => {}});- const cache = new InMemoryCache({- typePolicies: {- APIToken: {- keyFields: ['tokenId'],- },- KnowledgeDocument: {- fields: {- // `content` arrives empty from the list query (withContent:false,- // to save bandwidth) but full from the detail query — both- // normalize to this shared entity. Never let an empty incoming- // blank out a body the detail already loaded.- content: {- merge: (existing: string | undefined, incoming: string) => incoming || existing || '',- },- },- },- ProviderConfig: {- keyFields: (object) => {- if (object.id === 0 || object.id === '0') {- return false;- }-- return ['id'];- },- },- Query: {- fields: {- agentLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },- apiTokens: { ...replaceWithIncoming },- assistantLogs: { keyArgs: ['flowId', 'assistantId'], ...replaceWithIncoming },- assistants: { keyArgs: ['flowId'], ...replaceWithIncoming },- flow: {- read(existing, { args, toReference }) {- if (!args?.flowId) {- return existing;- }-- return existing ?? toReference({ __typename: 'Flow', id: args.flowId });- },- },- flowFiles: { keyArgs: ['flowId'], ...replaceWithIncoming },- flows: { ...replaceWithIncoming },- flowTemplates: { ...replaceWithIncoming },- knowledgeDocuments: { keyArgs: ['filter', 'withContent'], ...replaceWithIncoming },- messageLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },- providers: { ...replaceWithIncoming },- resources: { keyArgs: ['path', 'recursive'], ...replaceWithIncoming },- screenshots: { keyArgs: ['flowId'], ...replaceWithIncoming },- searchLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },- settingsPrompts: { ...replaceWithIncoming },- settingsProviders: { ...replaceWithIncoming },- settingsUser: { ...replaceWithIncoming },- tasks: { keyArgs: ['flowId'], ...replaceWithIncoming },- terminalLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },- vectorStoreLogs: { keyArgs: ['flowId'], ...replaceWithIncoming },- },- },- },- });+ const cache = createCache();const streamingLink = createStreamingLink();const subscriptionCacheLink = createSubscriptionCacheLink(cache);diff --git a/frontend/src/pages/dashboard/dashboard-analytics.tsx b/frontend/src/pages/dashboard/dashboard-analytics.tsxindex 9512b910..652e075f 100644--- a/frontend/src/pages/dashboard/dashboard-analytics.tsx+++ b/frontend/src/pages/dashboard/dashboard-analytics.tsx@@ -1,12 +1,13 @@import { useQuery } from '@apollo/client/react';import { format } from 'date-fns';-import { AlertCircle, ChevronRight, Clock, Wrench } from 'lucide-react';+import { ChevronRight, Clock, Wrench } from 'lucide-react';import { memo, useDeferredValue, useMemo, useRef, useState } from 'react';import { Area, AreaChart, Bar, BarChart, CartesianGrid, Tooltip, XAxis, YAxis } from 'recharts';import type { FlowFragmentFragment, UsageStatsPeriod } from '@/graphql/types';import { ChartCard, ChartTooltip } from '@/components/dashboard';+import { DashboardError } from '@/components/dashboard/dashboard-error';import { FlowStatusBadge } from '@/components/icons/flow-status-badge';import { Badge } from '@/components/ui/badge';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';@@ -386,10 +387,7 @@ export function DashboardAnalytics({ period }: { period: UsageStatsPeriod }) {/></div>) : executionStatsError ? (- <div className="text-muted-foreground flex flex-col items-center justify-center gap-2 py-8">- <AlertCircle className="text-muted-foreground/40 size-6" />- <p className="text-sm">Couldn't load</p>- </div>+ <DashboardError className="py-8" />) : !deferredExecutionStats.length ? (<p className="text-muted-foreground py-8 text-center text-sm">No flow executions in this perioddiff --git a/frontend/src/pages/dashboard/dashboard-overview.tsx b/frontend/src/pages/dashboard/dashboard-overview.tsxindex 3ebdaaba..1eb0d8a6 100644--- a/frontend/src/pages/dashboard/dashboard-overview.tsx+++ b/frontend/src/pages/dashboard/dashboard-overview.tsx@@ -1,9 +1,10 @@import { useQuery } from '@apollo/client/react';-import { Activity, AlertCircle, CircleDollarSign, Cpu, GitFork } from 'lucide-react';+import { Activity, CircleDollarSign, Cpu, GitFork } from 'lucide-react';import type { UsageStatsFragmentFragment } from '@/graphql/types';import { MetricCard } from '@/components/dashboard';+import { DashboardError } from '@/components/dashboard/dashboard-error';import { Badge } from '@/components/ui/badge';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';import { Spinner } from '@/components/ui/spinner';@@ -214,12 +215,7 @@ export function DashboardOverview() {}function ErrorTable() {- return (- <div className="text-muted-foreground flex flex-col items-center justify-center gap-2 py-8">- <AlertCircle className="text-muted-foreground/40 size-6" />- <p className="text-sm">Couldn't load</p>- </div>- );+ return <DashboardError className="py-8" />;}function LoadingTable() {diff --git a/frontend/src/pages/flows/flow.tsx b/frontend/src/pages/flows/flow.tsxindex a43fb718..b16a0ae9 100644--- a/frontend/src/pages/flows/flow.tsx+++ b/frontend/src/pages/flows/flow.tsx@@ -28,6 +28,7 @@ import {DetailNavigationSheet,DetailNavigationToolbar,} from '@/components/shared/detail-navigation';+import { ErrorState } from '@/components/shared/error-state';import { InlineEditInput, useInlineEdit } from '@/components/shared/inline-edit';import { Badge } from '@/components/ui/badge';import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';@@ -79,7 +80,7 @@ function Flow() {const { isDesktop, isMobile } = useBreakpoint();const navigate = useNavigate();- const { flowData, flowId, isLoading: isFlowLoading } = useFlow();+ const { flowData, flowId, flowLoadError, isLoading: isFlowLoading, refetchFlow } = useFlow();const { deleteFlow, finishFlow } = useFlows();const { isFavoriteFlow, toggleFavoriteFlow } = useFavorites();@@ -108,13 +109,13 @@ function Flow() {const [renameFlowMutation, { loading: isRenameLoading }] = useMutation(RenameFlowDocument);useEffect(() => {- // errorPolicy:'all' surfaces a partial error while the flow itself- // loaded; leave only when the flow is genuinely absent, not on any error- // — else a failed sibling log query bounces the user off a working flow.- if (!isFlowLoading && !flowData?.flow) {+ // Redirect only when the flow is genuinely gone (query resolved with no flow, or+ // a not-found error). A real load failure keeps the user here behind the+ // ErrorState + Retry below instead of silently bouncing to the list.+ if (!isFlowLoading && !flowData?.flow && !flowLoadError) {navigate(routes.flows, { replace: true });}- }, [flowData, isFlowLoading, navigate]);+ }, [flowData, flowLoadError, isFlowLoading, navigate]);const handleFlowRenameSave = useCallback(async () => {const newTitle = editingInputRef.current?.value.trim();@@ -190,6 +191,31 @@ function Flow() {const activeTabsTab = isDesktop ? desktopTabsTab : mobileAutoTab;const handleTabsTabChange = isDesktop ? setDesktopTabsTab : handleMobileTabChange;+ if (flowLoadError) {+ return (+ <>+ <AppHeader>+ <AppHeaderContent>+ <Breadcrumb className="min-w-0 flex-1">+ <BreadcrumbList className="min-w-0 flex-nowrap">+ <BreadcrumbItem className="min-w-0">+ <BreadcrumbPage>Flow</BreadcrumbPage>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ </AppHeaderContent>+ </AppHeader>+ <div className="flex flex-1 flex-col gap-4 p-4">+ <ErrorState+ message={flowLoadError.message}+ onRetry={refetchFlow}+ title="Error loading flow"+ />+ </div>+ </>+ );+ }+const tabsCard = (<div className="flex h-[calc(100dvh-3rem)] max-w-full flex-col rounded-none border-0"><div className="flex-1 overflow-auto py-4 pr-0 pl-4">diff --git a/frontend/src/pages/flows/flows.tsx b/frontend/src/pages/flows/flows.tsxindex e5119c07..3dbf69df 100644--- a/frontend/src/pages/flows/flows.tsx+++ b/frontend/src/pages/flows/flows.tsx@@ -19,6 +19,7 @@ import {import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { ErrorState } from '@/components/shared/error-state';import { InlineEditInput } from '@/components/shared/inline-edit';+import { LoadingState } from '@/components/shared/loading-state';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { ContextMenuItem, ContextMenuSeparator } from '@/components/ui/context-menu';@@ -591,24 +592,17 @@ function Flows() {<>{pageHeader}<div className="flex flex-1 flex-col gap-4 p-4">- <Empty>- <EmptyHeader>- <EmptyMedia>- <Spinner- className="text-muted-foreground size-10"- variant="circle"- />- </EmptyMedia>- <EmptyTitle>Loading flows...</EmptyTitle>- <EmptyDescription>Please wait while we fetch your conversation flows</EmptyDescription>- </EmptyHeader>- </Empty>+ <LoadingState+ description="Please wait while we fetch your conversation flows"+ title="Loading flows..."+ /></div></>);}- if (flowsError) {+ // Error surface only when there's no data — a failed background refetch must not blank a working list.+ if (flowsError && flows.length === 0) {return (<>{pageHeader}diff --git a/frontend/src/pages/knowledges/knowledges.tsx b/frontend/src/pages/knowledges/knowledges.tsxindex f51745d3..fdbe50a2 100644--- a/frontend/src/pages/knowledges/knowledges.tsx+++ b/frontend/src/pages/knowledges/knowledges.tsx@@ -17,6 +17,7 @@ import {import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { ErrorState } from '@/components/shared/error-state';import { InlineEditInput } from '@/components/shared/inline-edit';+import { LoadingState } from '@/components/shared/loading-state';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { ContextMenuItem, ContextMenuSeparator } from '@/components/ui/context-menu';@@ -406,24 +407,17 @@ function Knowledges() {<>{pageHeader}<div className="flex flex-1 flex-col gap-4 p-4">- <Empty>- <EmptyHeader>- <EmptyMedia>- <Spinner- className="text-muted-foreground size-10"- variant="circle"- />- </EmptyMedia>- <EmptyTitle>Loading knowledges...</EmptyTitle>- <EmptyDescription>Please wait while we fetch your knowledge documents</EmptyDescription>- </EmptyHeader>- </Empty>+ <LoadingState+ description="Please wait while we fetch your knowledge documents"+ title="Loading knowledges..."+ /></div></>);}- if (error) {+ // Error surface only when there's no data — a failed background refetch must not blank a working list.+ if (error && !knowledges.length) {return (<>{pageHeader}diff --git a/frontend/src/pages/resources/resources.tsx b/frontend/src/pages/resources/resources.tsxindex 1041bf90..1e407337 100644--- a/frontend/src/pages/resources/resources.tsx+++ b/frontend/src/pages/resources/resources.tsx@@ -433,7 +433,8 @@ function Resources() {</Empty>);- if (error) {+ // Error surface only when there's no data — a failed background refetch must not blank a working list.+ if (error && !hasResources) {return (<>{pageHeader}diff --git a/frontend/src/pages/settings/settings-api-tokens.tsx b/frontend/src/pages/settings/settings-api-tokens.tsxindex a5964161..caf87bf9 100644--- a/frontend/src/pages/settings/settings-api-tokens.tsx+++ b/frontend/src/pages/settings/settings-api-tokens.tsx@@ -20,6 +20,7 @@ import {} from '@/components/layouts/app/app-header';import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { ErrorState } from '@/components/shared/error-state';+import { LoadingState } from '@/components/shared/loading-state';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Calendar } from '@/components/ui/calendar';@@ -858,24 +859,17 @@ function SettingsAPITokens() {<>{pageHeader}<div className="flex flex-1 flex-col gap-4 p-4">- <Empty>- <EmptyHeader>- <EmptyMedia>- <Spinner- className="text-muted-foreground size-10"- variant="circle"- />- </EmptyMedia>- <EmptyTitle>Loading tokens...</EmptyTitle>- <EmptyDescription>Please wait while we fetch your API tokens</EmptyDescription>- </EmptyHeader>- </Empty>+ <LoadingState+ description="Please wait while we fetch your API tokens"+ title="Loading tokens..."+ /></div></>);}- if (error) {+ // Error surface only when there's no data — a failed background refetch must not blank a working list.+ if (error && !data) {return (<>{pageHeader}diff --git a/frontend/src/pages/settings/settings-prompt.tsx b/frontend/src/pages/settings/settings-prompt.tsxindex eb21261d..d67f7bf8 100644--- a/frontend/src/pages/settings/settings-prompt.tsx+++ b/frontend/src/pages/settings/settings-prompt.tsx@@ -57,6 +57,7 @@ import {import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { DetailSplitLayout } from '@/components/shared/detail-split-layout';import { ErrorState } from '@/components/shared/error-state';+import { LoadingState } from '@/components/shared/loading-state';import { UnsavedChangesDialog, useUnsavedChangesGuard } from '@/components/shared/unsaved-changes';import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { Badge } from '@/components/ui/badge';@@ -213,7 +214,7 @@ interface DiffContentProps {}interface VariablesContentProps {- counts: Record<string, number>;+ currentTemplate: string;onVariableClick: (variable: string) => void;variables: string[];}@@ -731,18 +732,10 @@ function SettingsPrompt() {<>{pageHeader}<div className="flex flex-1 items-center justify-center p-4">- <Empty>- <EmptyHeader>- <EmptyMedia>- <Spinner- className="text-muted-foreground size-10"- variant="circle"- />- </EmptyMedia>- <EmptyTitle>Loading prompt data...</EmptyTitle>- <EmptyDescription>Please wait while we fetch prompt information</EmptyDescription>- </EmptyHeader>- </Empty>+ <LoadingState+ description="Please wait while we fetch prompt information"+ title="Loading prompt data..."+ /></div></>);@@ -960,7 +953,7 @@ function SettingsPrompt() {{validationResult && (<div className="flex flex-col gap-4">- <Alert variant={validationResult.result ? 'default' : 'destructive'}>+ <Alert variant={validationResult.result === 'success' ? 'default' : 'destructive'}>{validationResult.result === 'success' ? (<CheckCircle className="size-4 text-green-500!" />) : (@@ -1021,7 +1014,6 @@ function SettingsPrompt() {function Variables({ currentTemplate, onVariableClick, variables }: VariablesProps) {const { isDesktop } = useBreakpoint();- const counts = useMemo(() => countVariableUses(currentTemplate, variables), [currentTemplate, variables]);if (variables.length === 0) {return null;@@ -1029,7 +1021,7 @@ function Variables({ currentTemplate, onVariableClick, variables }: VariablesProconst content = (<VariablesContent- counts={counts}+ currentTemplate={currentTemplate}onVariableClick={onVariableClick}variables={variables}/>@@ -1085,7 +1077,11 @@ function Variables({ currentTemplate, onVariableClick, variables }: VariablesPro);}-function VariablesContent({ counts, onVariableClick, variables }: VariablesContentProps) {+function VariablesContent({ currentTemplate, onVariableClick, variables }: VariablesContentProps) {+ // Computed here, not in the parent, so the narrow-width popover only runs the+ // per-variable RegExp sweep while it's open and mounted.+ const counts = useMemo(() => countVariableUses(currentTemplate, variables), [currentTemplate, variables]);+return (<div className="flex flex-wrap gap-1.5 px-4 py-3">{variables.map((variable) => {diff --git a/frontend/src/pages/settings/settings-prompts.tsx b/frontend/src/pages/settings/settings-prompts.tsxindex cfe7c021..5a6002bb 100644--- a/frontend/src/pages/settings/settings-prompts.tsx+++ b/frontend/src/pages/settings/settings-prompts.tsx@@ -27,6 +27,7 @@ type AgentPrompts = { human?: DefaultPrompt; system: DefaultPrompt };import { AppHeader, AppHeaderContent, AppHeaderTitle } from '@/components/layouts/app/app-header';import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { ErrorState } from '@/components/shared/error-state';+import { LoadingState } from '@/components/shared/loading-state';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { ContextMenuItem, ContextMenuSeparator } from '@/components/ui/context-menu';@@ -797,24 +798,17 @@ function SettingsPrompts() {{pageHeader}<div className="flex flex-1 flex-col gap-6 p-4"><SettingsPromptsHeader />- <Empty>- <EmptyHeader>- <EmptyMedia>- <Spinner- className="text-muted-foreground size-10"- variant="circle"- />- </EmptyMedia>- <EmptyTitle>Loading prompts...</EmptyTitle>- <EmptyDescription>Please wait while we fetch your prompt templates</EmptyDescription>- </EmptyHeader>- </Empty>+ <LoadingState+ description="Please wait while we fetch your prompt templates"+ title="Loading prompts..."+ /></div></>);}- if (error) {+ // Error surface only when there's no data — a failed background refetch must not blank a working list.+ if (error && !data) {return (<>{pageHeader}diff --git a/frontend/src/pages/settings/settings-provider.tsx b/frontend/src/pages/settings/settings-provider.tsxindex 1e8414bf..3a84c0a4 100644--- a/frontend/src/pages/settings/settings-provider.tsx+++ b/frontend/src/pages/settings/settings-provider.tsx@@ -38,6 +38,7 @@ import {import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { DetailSplitLayout } from '@/components/shared/detail-split-layout';import { ErrorState } from '@/components/shared/error-state';+import { LoadingState } from '@/components/shared/loading-state';import { UnsavedChangesDialog, useUnsavedChangesGuard } from '@/components/shared/unsaved-changes';import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';import { Badge } from '@/components/ui/badge';@@ -50,7 +51,6 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';-import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';import { Input } from '@/components/ui/input';import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';@@ -1560,18 +1560,10 @@ function SettingsProvider() {</AppHeaderContent></AppHeader><div className="flex flex-1 items-center justify-center p-4">- <Empty>- <EmptyHeader>- <EmptyMedia>- <Spinner- className="text-muted-foreground size-10"- variant="circle"- />- </EmptyMedia>- <EmptyTitle>Loading provider data...</EmptyTitle>- <EmptyDescription>Please wait while we fetch provider configuration</EmptyDescription>- </EmptyHeader>- </Empty>+ <LoadingState+ description="Please wait while we fetch provider configuration"+ title="Loading provider data..."+ /></div></>);@@ -1664,6 +1656,22 @@ function SettingsProvider() {event.stopPropagation();handleTestAgent(agentKey);}}+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ') {+ return;+ }++ event.preventDefault();+ event.stopPropagation();++ if (isTestLoading || isAgentTestLoading) {+ return;+ }++ handleTestAgent(agentKey);+ }}+ role="button"+ tabIndex={isTestLoading || isAgentTestLoading ? -1 : 0}>{isAgentTestLoading && currentAgentKey === agentKey ? (<Spinner variant="circle" />diff --git a/frontend/src/pages/settings/settings-providers.tsx b/frontend/src/pages/settings/settings-providers.tsxindex 2618bf3f..cfd8766e 100644--- a/frontend/src/pages/settings/settings-providers.tsx+++ b/frontend/src/pages/settings/settings-providers.tsx@@ -12,6 +12,7 @@ import { providerIcons } from '@/components/icons/provider-icon';import { AppHeader, AppHeaderActions, AppHeaderContent, AppHeaderTitle } from '@/components/layouts/app/app-header';import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { ErrorState } from '@/components/shared/error-state';+import { LoadingState } from '@/components/shared/loading-state';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { ContextMenuItem, ContextMenuSeparator } from '@/components/ui/context-menu';@@ -408,24 +409,17 @@ function SettingsProviders() {<>{pageHeader}<div className="flex flex-1 flex-col gap-4 p-4">- <Empty>- <EmptyHeader>- <EmptyMedia>- <Spinner- className="text-muted-foreground size-10"- variant="circle"- />- </EmptyMedia>- <EmptyTitle>Loading providers...</EmptyTitle>- <EmptyDescription>Please wait while we fetch your provider configurations</EmptyDescription>- </EmptyHeader>- </Empty>+ <LoadingState+ description="Please wait while we fetch your provider configurations"+ title="Loading providers..."+ /></div></>);}- if (error) {+ // Error surface only when there's no data — a failed background refetch must not blank a working list.+ if (error && !data) {return (<>{pageHeader}diff --git a/frontend/src/pages/templates/template.tsx b/frontend/src/pages/templates/template.tsxindex 01a6084b..38fe67ac 100644--- a/frontend/src/pages/templates/template.tsx+++ b/frontend/src/pages/templates/template.tsx@@ -710,7 +710,7 @@ function Template() {mode={viewMode}onBlur={field.onBlur}onChange={field.onChange}- placeholder="Describe the task, or start from a preset above"+ placeholder="Describe the task, or start from a preset"ref={field.ref}value={field.value}/>diff --git a/frontend/src/pages/templates/templates.tsx b/frontend/src/pages/templates/templates.tsxindex e1cbed00..9ba7e6ee 100644--- a/frontend/src/pages/templates/templates.tsx+++ b/frontend/src/pages/templates/templates.tsx@@ -15,6 +15,7 @@ import {import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { ErrorState } from '@/components/shared/error-state';import { InlineEditInput } from '@/components/shared/inline-edit';+import { LoadingState } from '@/components/shared/loading-state';import { Button } from '@/components/ui/button';import { ContextMenuItem, ContextMenuSeparator } from '@/components/ui/context-menu';import { DataTable, DataTableColumnHeader } from '@/components/ui/data-table';@@ -270,24 +271,17 @@ function Templates() {<>{pageHeader}<div className="flex flex-1 flex-col gap-4 p-4">- <Empty>- <EmptyHeader>- <EmptyMedia>- <Spinner- className="text-muted-foreground size-10"- variant="circle"- />- </EmptyMedia>- <EmptyTitle>Loading templates...</EmptyTitle>- <EmptyDescription>Please wait while we fetch your flow templates</EmptyDescription>- </EmptyHeader>- </Empty>+ <LoadingState+ description="Please wait while we fetch your flow templates"+ title="Loading templates..."+ /></div></>);}- if (error) {+ // Error surface only when there's no data — a failed background refetch must not blank a working list.+ if (error && !templates.length) {return (<>{pageHeader}diff --git a/frontend/src/providers/flow-provider.tsx b/frontend/src/providers/flow-provider.tsxindex 00a1a4b5..c66336ca 100644--- a/frontend/src/providers/flow-provider.tsx+++ b/frontend/src/providers/flow-provider.tsx@@ -1,3 +1,4 @@+import { NetworkStatus } from '@apollo/client';import { useMutation, useQuery, useSubscription } from '@apollo/client/react';import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';import { useParams } from 'react-router-dom';@@ -36,18 +37,21 @@ import {} from '@/graphql/types';import { Log } from '@/lib/log';+const isFlowNotFoundError = (error: Error) => /no rows in result set|not found/i.test(error.message);+interface FlowContextValue {assistantLogs: Array<AssistantLogFragmentFragment>;assistants: Array<AssistantFragmentFragment>;createAssistant: (values: FlowFormValues) => Promise<void>;deleteAssistant: (assistantId: string) => Promise<void>;flowData: FlowQuery | undefined;- flowError: Error | undefined;flowId: null | string;+ flowLoadError: Error | undefined;flowStatus: StatusType | undefined;initiateAssistantCreation: () => void;isAssistantsLoading: boolean;isLoading: boolean;+ refetchFlow: () => void;selectAssistant: (assistantId: null | string) => void;selectedAssistantId: null | string;stopAssistant: (assistantId: string) => Promise<void>;@@ -70,7 +74,9 @@ export function FlowProvider({ children }: FlowProviderProps) {const {data: flowData,error: flowError,- loading: isLoading,+ loading,+ networkStatus,+ refetch: refetchFlow,} = useQuery(FlowDocument, {errorPolicy: 'all',fetchPolicy: 'cache-first',@@ -80,6 +86,17 @@ export function FlowProvider({ children }: FlowProviderProps) {variables: { id: flowId ?? '' },});+ // Only the initial load blocks the UI and gates subscriptions. A background+ // refetch (e.g. the reconnect reconcile) stays at networkStatus `refetch`, so+ // it must NOT flip isLoading — otherwise it covers the page with the spinner+ // overlay and tears down the 14 live subscriptions mid-flight.+ const isLoading = loading && networkStatus === NetworkStatus.loading;++ // A real load failure that left nothing to show (cold cache + backend error on a+ // deep link), as opposed to a genuine not-found. The detail page renders this as an+ // in-page ErrorState + Retry instead of silently bouncing to the list.+ const flowLoadError = flowError && !flowData?.flow && !isFlowNotFoundError(flowError) ? flowError : undefined;+const { data: assistantsData, loading: isAssistantsLoading } = useQuery(AssistantsDocument, {fetchPolicy: 'cache-first',nextFetchPolicy: 'cache-first',@@ -170,19 +187,21 @@ export function FlowProvider({ children }: FlowProviderProps) {const flowStatus = useMemo(() => flowData?.flow?.status, [flowData?.flow?.status]);- // errorPolicy:'all' surfaces a partial error while the flow loaded, so gate- // on `!flow` or a partial failure toasts over a flow that rendered fine. The- // stable id keeps the invalid-id "no rows" retries from stacking.+ // errorPolicy:'all' surfaces a partial error while the flow loaded, so gate on+ // `!flow` or a partial failure toasts over a flow that rendered fine. A real load+ // failure is surfaced in-page (ErrorState via flowLoadError); only the not-found+ // redirect needs a toast to explain the bounce to the list. The stable id keeps the+ // invalid-id "no rows" retries from stacking.useEffect(() => {- if (flowError && !flowData?.flow) {- const raw = flowError.message ?? '';- const isNotFound = /no rows in result set|not found/i.test(raw);- toast.error(isNotFound ? 'Flow not found' : 'Failed to load flow', {- description: isNotFound ? undefined : raw || undefined,- id: 'flow-load-error',- });- Log.error('Error loading flow:', flowError);+ if (!flowError || flowData?.flow) {+ return;+ }++ if (isFlowNotFoundError(flowError)) {+ toast.error('Flow not found', { id: 'flow-load-error' });}++ Log.error('Error loading flow:', flowError);}, [flowError, flowData]);const submitAutomationMessage = useCallback(@@ -373,12 +392,13 @@ export function FlowProvider({ children }: FlowProviderProps) {createAssistant,deleteAssistant,flowData,- flowError,flowId: flowId ?? null,+ flowLoadError,flowStatus,initiateAssistantCreation,isAssistantsLoading,isLoading,+ refetchFlow,selectAssistant,selectedAssistantId,stopAssistant,@@ -392,12 +412,13 @@ export function FlowProvider({ children }: FlowProviderProps) {createAssistant,deleteAssistant,flowData,- flowError,flowId,+ flowLoadError,flowStatus,initiateAssistantCreation,isAssistantsLoading,isLoading,+ refetchFlow,selectAssistant,selectedAssistantId,stopAssistant,diff --git a/frontend/src/providers/flows-provider.tsx b/frontend/src/providers/flows-provider.tsxindex 5c2a0529..f95715de 100644--- a/frontend/src/providers/flows-provider.tsx+++ b/frontend/src/providers/flows-provider.tsx@@ -1,4 +1,3 @@-import { NetworkStatus } from '@apollo/client';import { useMutation, useQuery, useSubscription } from '@apollo/client/react';import { createContext, useCallback, useContext, useMemo } from 'react';import { toast } from 'sonner';@@ -43,14 +42,16 @@ export function FlowsProvider({ children }: FlowsProviderProps) {data: flowsData,error: flowsError,loading,- networkStatus,refetch,} = useQuery(FlowsDocument, {notifyOnNetworkStatusChange: true,});- const isLoading = loading && networkStatus === NetworkStatus.loading;const flows = useMemo(() => flowsData?.flows ?? [], [flowsData?.flows]);+ // Full-page spinner only while there's nothing to show yet: a background refetch+ // (reconnect sweep) keeps the rendered list, and a retry after a failed initial load+ // shows the spinner rather than flashing the "No flows found" empty state.+ const isLoading = loading && flows.length === 0;useSubscription(FlowCreatedDocument);useSubscription(FlowDeletedDocument);diff --git a/frontend/src/providers/resources-provider.tsx b/frontend/src/providers/resources-provider.tsxindex 786fdb58..ad6c5ae0 100644--- a/frontend/src/providers/resources-provider.tsx+++ b/frontend/src/providers/resources-provider.tsx@@ -115,6 +115,15 @@ export function ResourcesProvider({ children }: ResourcesProviderProps) {};}, [apolloClient, refreshTick, shouldFetchResources]);+ // Subscriptions are delta-only and the reconnect sweep skips this cache-only slot,+ // so re-hydrate from REST when the socket reconnects after an outage.+ useEffect(() => {+ const reconcile = () => setRefreshTick((tick) => tick + 1);+ window.addEventListener('ws:reconnected', reconcile);++ return () => window.removeEventListener('ws:reconnected', reconcile);+ }, []);+const { data, error: graphqlError } = useQuery(ResourcesDocument, {fetchPolicy: 'cache-only',skip: !shouldFetchResources,