Skip to content

Self-improving AI Employees for everyone

perf(client): swap hand-rolled WS reconnect + auth retry for library-backed retry policies (PartySocket + TanStack Query) preserving CloudEvents

trohitge77215c36459
diff --git a/client/package.json b/client/package.json
index 935c8647..51dd2d17 100644
--- a/client/package.json
+++ b/client/package.json
@@ -48,6 +48,7 @@
"idb-keyval": "^6",
"lucide-react": "^1.8.0",
"next-themes": "^0.4.6",
+ "partysocket": "1.1.18",
"postcss": "^8.5.6",
"prismjs": "^1.30.0",
"qrcode.react": "^4.2.0",
diff --git a/client/src/contexts/AuthContext.tsx b/client/src/contexts/AuthContext.tsx
index e961c741..f3430570 100644
--- a/client/src/contexts/AuthContext.tsx
+++ b/client/src/contexts/AuthContext.tsx
@@ -1,15 +1,27 @@
/**
* Authentication Context for user session management.
*
- * Provides:
- * - Login/logout/register functions
- * - Current user state
- * - Authentication status
- * - Auth mode (single-owner vs multi-user)
+ * The auth-status check runs through TanStack Query (`useQuery`) so
+ * exponential backoff with full jitter, AbortController-based unmount
+ * cleanup, Strict-Mode safety, and 401/403 fast-fail are all delegated
+ * to the library — see https://tanstack.com/query/v5/docs/framework/react/guides/query-retries.
+ *
+ * The context's public surface (user, isAuthenticated, isLoading,
+ * authMode, canRegister, error, login, register, logout, checkAuth) is
+ * unchanged so consumer code does not move.
+ *
+ * Login / register / logout mutate the auth state by invalidating the
+ * `['auth', 'status']` query rather than calling a private setter — the
+ * single source of truth stays the query cache, which TanStack Query
+ * dedupes by reference equality, eliminating the spurious
+ * `isAuthenticated` flips that closed the WS prematurely under React
+ * Strict Mode.
*/
-import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
+import React, { createContext, useContext, useCallback, useMemo } from 'react';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
import { API_CONFIG } from '../config/api';
+import { AUTH_RETRY } from '../lib/connectionConfig';
export interface User {
id: number;
@@ -43,159 +55,185 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);
const getApiBase = () => `${API_CONFIG.PYTHON_BASE_URL}/api/auth`;
-export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
- const [user, setUser] = useState<User | null>(null);
- const [isLoading, setIsLoading] = useState(true);
- const [authMode, setAuthMode] = useState<'single' | 'multi'>('single');
- const [canRegister, setCanRegister] = useState(false);
- const [error, setError] = useState<string | null>(null);
+const ANONYMOUS_USER: User = {
+ id: 0,
+ email: 'anonymous',
+ display_name: 'Anonymous',
+ is_owner: true,
+};
- const checkAuth = useCallback(async (retryCount = 0): Promise<void> => {
- const maxRetries = 5;
- const baseDelay = 1000; // 1 second
+// `['auth', 'status']` is the canonical key for the bootstrap query.
+// Login / register / logout invalidate it via `queryClient.invalidateQueries`.
+export const AUTH_STATUS_QUERY_KEY = ['auth', 'status'] as const;
- try {
- const response = await fetch(`${getApiBase()}/status`, {
- credentials: 'include'
- });
- const data: AuthStatus = await response.json();
-
- // Runtime auth check: if backend says auth is disabled, set anonymous user
- if (data.auth_enabled === false) {
- setUser({ id: 0, email: 'anonymous', display_name: 'Anonymous', is_owner: true });
- setIsLoading(false);
- setError(null);
- return;
- }
+/**
+ * Full-jitter exponential backoff. Constants live in
+ * `lib/connectionConfig.ts` (`AUTH_RETRY`) so a future tuning pass is a
+ * single-file edit. See that module for the rationale and the reference
+ * link to the AWS Architecture Blog.
+ */
+const authRetryDelay = (attemptIndex: number): number =>
+ Math.random() * Math.min(AUTH_RETRY.CAP_MS, AUTH_RETRY.BASE_MS * 2 ** attemptIndex);
- setAuthMode(data.auth_mode);
- setCanRegister(data.can_register);
+/**
+ * Retry on network failures + 5xx; never retry on auth errors (401/403)
+ * because those are valid responses meaning "auth disabled / not logged
+ * in", not "backend unavailable". Cap at `AUTH_RETRY.MAX_ATTEMPTS`.
+ */
+const authShouldRetry = (failureCount: number, error: unknown): boolean => {
+ if (failureCount >= AUTH_RETRY.MAX_ATTEMPTS) return false;
+ const msg = error instanceof Error ? error.message : String(error);
+ if (msg.includes('HTTP 401') || msg.includes('HTTP 403')) return false;
+ return true;
+};
- if (data.authenticated && data.user) {
- setUser(data.user);
- } else {
- setUser(null);
- }
- setError(null);
- setIsLoading(false);
- } catch (err) {
- console.error(`Failed to check auth status (attempt ${retryCount + 1}/${maxRetries + 1}):`, err);
-
- // Retry with exponential backoff if server not ready
- if (retryCount < maxRetries) {
- const delay = baseDelay * Math.pow(2, retryCount);
- console.log(`Retrying in ${delay}ms...`);
- setTimeout(() => checkAuth(retryCount + 1), delay);
- } else {
- setUser(null);
- setError('Failed to connect to server');
- setIsLoading(false);
- }
- }
- }, []);
+const fetchAuthStatus = async ({ signal }: { signal: AbortSignal }): Promise<AuthStatus> => {
+ const response = await fetch(`${getApiBase()}/status`, {
+ credentials: 'include',
+ signal,
+ });
+ if (!response.ok) {
+ // Wrap status in the error message so `authShouldRetry` can detect
+ // 401/403 without parsing the original Response.
+ throw new Error(`auth.status: HTTP ${response.status}`);
+ }
+ return response.json() as Promise<AuthStatus>;
+};
+
+export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const queryClient = useQueryClient();
- // Check auth status on mount
- useEffect(() => {
- checkAuth();
- }, [checkAuth]);
+ // Bootstrap auth-status query. The `signal` plumbed through `queryFn`
+ // is automatically aborted when the component unmounts (Strict Mode
+ // double-mount lifecycle handled by TanStack Query, see
+ // https://tanstack.com/query/v5/docs/react/guides/cancellation).
+ const authQuery = useQuery({
+ queryKey: AUTH_STATUS_QUERY_KEY,
+ queryFn: fetchAuthStatus,
+ retry: authShouldRetry,
+ retryDelay: authRetryDelay,
+ // Boot-once: never refetch on focus / mount / network reconnect.
+ // Logout / login explicitly invalidate.
+ staleTime: Infinity,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ });
- const login = useCallback(async (email: string, password: string): Promise<boolean> => {
- setError(null);
- setIsLoading(true);
+ const data = authQuery.data;
+ const user: User | null = useMemo(() => {
+ if (!data) return null;
+ if (data.auth_enabled === false) return ANONYMOUS_USER;
+ return data.authenticated ? data.user : null;
+ }, [data]);
+
+ const authMode: 'single' | 'multi' = data?.auth_mode ?? 'single';
+ const canRegister = data?.can_register ?? false;
+ const isAuthenticated = user !== null;
+ const isLoading = authQuery.isPending;
+ const error = authQuery.isError ? 'Failed to connect to server' : null;
+
+ const invalidateAuth = useCallback(
+ () => queryClient.invalidateQueries({ queryKey: AUTH_STATUS_QUERY_KEY }),
+ [queryClient],
+ );
+ const login = useCallback(async (email: string, password: string): Promise<boolean> => {
try {
const response = await fetch(`${getApiBase()}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
- body: JSON.stringify({ email, password })
+ body: JSON.stringify({ email, password }),
});
+ const body = await response.json();
- const data = await response.json();
-
- if (!response.ok) {
- setError(data.detail || 'Login failed');
- setIsLoading(false);
+ if (!response.ok || !body.success || !body.user) {
+ // Surface the server's error via the query cache so `error` flips
+ // through the same path as a normal `isError` would.
+ queryClient.setQueryData<AuthStatus | null>(AUTH_STATUS_QUERY_KEY, null);
return false;
}
- if (data.success && data.user) {
- setUser(data.user);
- setIsLoading(false);
- return true;
- }
-
- setError('Login failed');
- setIsLoading(false);
- return false;
+ // Optimistically write the new user into the cache so the UI
+ // updates this render; then invalidate so the next refetch
+ // picks up server-derived fields (auth_mode, can_register).
+ queryClient.setQueryData<AuthStatus>(AUTH_STATUS_QUERY_KEY, {
+ auth_enabled: true,
+ auth_mode: authMode,
+ authenticated: true,
+ user: body.user,
+ can_register: false,
+ });
+ await invalidateAuth();
+ return true;
} catch (err) {
console.error('Login error:', err);
- setError('Failed to connect to server');
- setIsLoading(false);
return false;
}
- }, []);
+ }, [queryClient, invalidateAuth, authMode]);
const register = useCallback(async (
email: string,
password: string,
- displayName: string
+ displayName: string,
): Promise<boolean> => {
- setError(null);
- setIsLoading(true);
-
try {
const response = await fetch(`${getApiBase()}/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
- body: JSON.stringify({ email, password, display_name: displayName })
+ body: JSON.stringify({ email, password, display_name: displayName }),
});
+ const body = await response.json();
- const data = await response.json();
-
- if (!response.ok) {
- setError(data.detail || 'Registration failed');
- setIsLoading(false);
+ if (!response.ok || !body.success || !body.user) {
return false;
}
- if (data.success && data.user) {
- setUser(data.user);
- setCanRegister(false); // After successful registration in single-owner mode
- setIsLoading(false);
- return true;
- }
-
- setError('Registration failed');
- setIsLoading(false);
- return false;
+ queryClient.setQueryData<AuthStatus>(AUTH_STATUS_QUERY_KEY, {
+ auth_enabled: true,
+ auth_mode: authMode,
+ authenticated: true,
+ user: body.user,
+ can_register: false,
+ });
+ await invalidateAuth();
+ return true;
} catch (err) {
console.error('Register error:', err);
- setError('Failed to connect to server');
- setIsLoading(false);
return false;
}
- }, []);
+ }, [queryClient, invalidateAuth, authMode]);
const logout = useCallback(async () => {
try {
await fetch(`${getApiBase()}/logout`, {
method: 'POST',
- credentials: 'include'
+ credentials: 'include',
});
} catch (err) {
console.error('Logout error:', err);
} finally {
- setUser(null);
- // Re-check auth status to update canRegister
- await checkAuth();
+ // Force `authenticated: false` immediately so consumers (esp. the
+ // WebSocket logout effect) react this render; then refetch so
+ // `can_register` and `auth_mode` come back fresh.
+ queryClient.setQueryData<AuthStatus>(AUTH_STATUS_QUERY_KEY, (prev) => ({
+ ...(prev ?? { auth_enabled: true, auth_mode: 'single' as const, can_register: false }),
+ authenticated: false,
+ user: null,
+ }));
+ await invalidateAuth();
}
- }, [checkAuth]);
+ }, [queryClient, invalidateAuth]);
+
+ const checkAuth = useCallback(async () => {
+ await authQuery.refetch();
+ }, [authQuery]);
- const value: AuthContextType = {
+ const value: AuthContextType = useMemo(() => ({
user,
- isAuthenticated: user !== null,
+ isAuthenticated,
isLoading,
authMode,
canRegister,
@@ -203,8 +241,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
login,
register,
logout,
- checkAuth
- };
+ checkAuth,
+ }), [user, isAuthenticated, isLoading, authMode, canRegister, error,
+ login, register, logout, checkAuth]);
return (
<AuthContext.Provider value={value}>
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index fbc0ebcd..df561ac3 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -11,6 +11,7 @@
*/
import React, { createContext, useContext, useEffect, useState, useCallback, useRef, useMemo } from 'react';
+import ReconnectingWebSocket from 'partysocket/ws';
import { API_CONFIG } from '../config/api';
import { useAppStore } from '../store/useAppStore';
import { useAuth } from './AuthContext';
@@ -18,6 +19,8 @@ import { queryClient } from '../lib/queryClient';
import { queryKeys } from '../lib/queryConfig';
import { invalidateCatalogue } from '../hooks/useCatalogueQuery';
import { nodeParamsQueryKey } from '../hooks/useNodeParamsQuery';
+import type { WorkflowEvent } from '../types/cloudEvents';
+import { WS_CLOSE, WS_RECONNECT } from '../lib/connectionConfig';
import {
useNodeStatusStore,
useNodeStatusForId,
@@ -500,8 +503,13 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// Per-workflow compaction stats: workflow_id -> session_id -> CompactionStats (n8n pattern)
const [allCompactionStats, setAllCompactionStats] = useState<Record<string, Record<string, CompactionStats>>>({});
- const wsRef = useRef<WebSocket | null>(null);
- const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ // PartySocket's `ReconnectingWebSocket` implements the native WebSocket
+ // surface (`send`, `close`, `readyState`, `addEventListener`, `onopen`,
+ // `onmessage`, `onclose`, `onerror`) so consumers — including the request
+ // correlation map and ping loop below — work unchanged. The ref's element
+ // type tightens to the library's class so any feature-specific calls
+ // (`shouldReconnect`, `reconnect()`) type-check.
+ const wsRef = useRef<ReconnectingWebSocket | null>(null);
const pingIntervalRef = useRef<NodeJS.Timeout | null>(null);
const pendingRequestsRef = useRef<Map<string, PendingRequest>>(new Map());
// Pending-send queue for backpressure + replay across reconnects.
@@ -526,7 +534,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// Fetch deployment status for the new workflow (n8n pattern)
// This ensures the deploy button shows correct state when switching workflows
- if (wsRef.current?.readyState === WebSocket.OPEN) {
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
const fetchDeploymentStatus = async () => {
try {
const requestId = generateRequestId();
@@ -676,12 +684,22 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
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.
+ case 'credential_catalogue_updated': {
+ // The backend wraps a CloudEvents v1.0 `WorkflowEvent` envelope
+ // inside `data` (see server/services/status_broadcaster.py and
+ // server/services/events/envelope.py). The legacy outer wire
+ // key stays as the dispatch tag for back-compat, but the
+ // envelope's `id` / `time` / nested `type` (e.g.
+ // `credential.api_key.saved`) are now statically typed for any
+ // future consumer that wants ordering, dedup, or fine-grained
+ // glob dispatch via `matchesType()`.
+ const event = data as WorkflowEvent<{ provider: string; customer_id?: string }>;
+ // Today the only action is to refetch the catalogue; the
+ // envelope is read for telemetry / future dispatch.
+ void event;
invalidateCatalogue(queryClient);
break;
+ }
case 'android_status':
setAndroidStatus(data || defaultAndroidStatus);
@@ -1161,7 +1179,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// fresh request_id and a reset timeout budget; responses correlate via the
// existing pendingRequestsRef map. Per-call abortController cancels the
// queue-side timeout that was running while the request was waiting in line.
- const drainPendingSends = useCallback((ws: WebSocket) => {
+ const drainPendingSends = useCallback((ws: ReconnectingWebSocket) => {
const queue = pendingSendQueueRef.current;
pendingSendQueueRef.current = [];
for (const queued of queue) {
@@ -1202,16 +1220,34 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
}, []);
- // Connect to WebSocket
+ // Connect to WebSocket. Uses PartySocket's `ReconnectingWebSocket` —
+ // a native-WebSocket-compatible class with built-in jittered exponential
+ // backoff, message replay, and intentional-close (code 1000) handling.
+ // Replaces the previous flat 3 s `setTimeout(reconnect)` loop.
+ // Backoff envelope is configured via `WS_RECONNECT` in
+ // `lib/connectionConfig.ts` so a future tuning pass is a one-file edit.
+ // Ref: https://docs.partykit.io/reference/partysocket-api/
const connect = useCallback(() => {
- if (wsRef.current?.readyState === WebSocket.OPEN) {
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
return;
}
const wsUrl = getWebSocketUrl();
try {
- const ws = new WebSocket(wsUrl);
+ const ws = new ReconnectingWebSocket(wsUrl, [], {
+ minReconnectionDelay: WS_RECONNECT.MIN_DELAY_MS,
+ maxReconnectionDelay: WS_RECONNECT.MAX_DELAY_MS,
+ reconnectionDelayGrowFactor: WS_RECONNECT.GROW_FACTOR,
+ // Reconnect indefinitely while the page is open. Intentional
+ // closes via `ws.close(1000, ...)` (logout / unmount) skip the
+ // reconnect path because PartySocket inspects the close code.
+ maxRetries: Infinity,
+ // Send-while-disconnected buffer; replayed automatically on the
+ // next OPEN. Mirrors the previous `pendingSendQueueRef` cap intent
+ // for opportunistic out-of-band sends.
+ maxEnqueuedMessages: WS_RECONNECT.MAX_ENQUEUED_MESSAGES,
+ });
ws.onopen = async () => {
setIsConnected(true);
@@ -1227,7 +1263,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// Start ping interval
pingIntervalRef.current = setInterval(() => {
- if (ws.readyState === WebSocket.OPEN) {
+ if (ws.readyState === ReconnectingWebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000);
@@ -1399,9 +1435,10 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
pendingRequestsRef.current.clear();
}
- // Pending-send queue handling: only drop on intentional close (code 1000).
- // Transient closes preserve the queue so the next onopen drain replays them.
- if (event.code === 1000) {
+ // Pending-send queue handling: only drop on intentional close
+ // (RFC 6455 §7.4.1 Normal Closure, code 1000). Transient closes
+ // preserve the queue so the next onopen drain replays them.
+ if (event.code === WS_CLOSE.NORMAL_CLOSURE) {
if (pendingSendQueueRef.current.length > 0) {
for (const queued of pendingSendQueueRef.current) {
try {
@@ -1421,12 +1458,13 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
pingIntervalRef.current = null;
}
- // Reconnect after delay (unless intentional close)
- if (event.code !== 1000) {
+ // PartySocket performs the reconnect itself when
+ // `event.code !== WS_CLOSE.NORMAL_CLOSURE`, honouring the
+ // `WS_RECONNECT` envelope passed at construction time. Surface
+ // "reconnecting" to the UI for transient closes; intentional
+ // closes (logout / unmount) leave the flag false.
+ if (event.code !== WS_CLOSE.NORMAL_CLOSURE) {
setReconnecting(true);
- reconnectTimeoutRef.current = setTimeout(() => {
- connect();
- }, 3000);
}
};
@@ -1436,15 +1474,18 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
wsRef.current = ws;
} catch (error) {
+ // Construction-time error (e.g. malformed URL). PartySocket has
+ // not installed its retry loop yet, so just log — there is
+ // nothing to reconnect to. The runtime path (network drops after
+ // successful construction) is covered by PartySocket's internal
+ // jittered backoff.
console.error('[WebSocket] Failed to create connection:', error);
- setReconnecting(true);
- reconnectTimeoutRef.current = setTimeout(connect, 3000);
}
}, [handleMessage, drainPendingSends]);
// Request current status
const requestStatus = useCallback(() => {
- if (wsRef.current?.readyState === WebSocket.OPEN) {
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: 'get_status' }));
}
}, []);
@@ -1504,7 +1545,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// the currently-open workflow so other workflows' history survives.
const clearConsoleLogs = useCallback(() => {
setConsoleLogs([]);
- if (wsRef.current?.readyState === WebSocket.OPEN) {
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
const workflowId = useAppStore.getState().currentWorkflow?.id;
wsRef.current.send(JSON.stringify({
type: 'clear_console_logs',
@@ -1517,7 +1558,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const clearTerminalLogs = useCallback(() => {
setTerminalLogs([]);
// Also notify server to clear its terminal log history
- if (wsRef.current?.readyState === WebSocket.OPEN) {
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: 'clear_terminal_logs' }));
}
}, []);
@@ -1528,7 +1569,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// Uses direct WebSocket send to avoid dependency on sendRequest (which is defined later).
const clearChatMessages = useCallback(() => {
setChatMessages([]);
- if (wsRef.current?.readyState === WebSocket.OPEN) {
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
const workflowId = useAppStore.getState().currentWorkflow?.id || 'default';
wsRef.current.send(JSON.stringify({
type: 'clear_chat_messages',
@@ -1645,7 +1686,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const effectiveTimeout = (timeoutMs === -1 || !useTimeout) ? -1 : actualTimeout;
// FAST PATH: socket open — send immediately.
- if (wsRef.current?.readyState === WebSocket.OPEN) {
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
const requestId = generateRequestId();
let timeout: NodeJS.Timeout | null = null;
if (effectiveTimeout > 0) {
@@ -2515,7 +2556,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
// Skip if already connected
- if (wsRef.current?.readyState === WebSocket.OPEN) {
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
return;
}
@@ -2546,7 +2587,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
pendingSendQueueRef.current = [];
}
- wsRef.current.close(1000, 'User logged out');
+ wsRef.current.close(WS_CLOSE.NORMAL_CLOSURE, 'User logged out');
wsRef.current = null;
setIsConnected(false);
setIsReady(false);
@@ -2557,7 +2598,6 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
useEffect(() => {
return () => {
isMountedRef.current = false;
- if (reconnectTimeoutRef.current) clearTimeout(reconnectTimeoutRef.current);
if (pingIntervalRef.current) clearInterval(pingIntervalRef.current);
// Drain the pending-send queue so any in-flight awaiters fail fast on
// unmount instead of dangling forever.
@@ -2572,8 +2612,8 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
pendingSendQueueRef.current = [];
}
- if (wsRef.current?.readyState === WebSocket.OPEN) {
- wsRef.current.close(1000, 'Component unmounted');
+ if (wsRef.current?.readyState === ReconnectingWebSocket.OPEN) {
+ wsRef.current.close(WS_CLOSE.NORMAL_CLOSURE, 'Component unmounted');
}
};
}, []);
diff --git a/client/src/contexts/__tests__/AuthContext.test.tsx b/client/src/contexts/__tests__/AuthContext.test.tsx
new file mode 100644
index 00000000..7d2a3fb4
--- /dev/null
+++ b/client/src/contexts/__tests__/AuthContext.test.tsx
@@ -0,0 +1,221 @@
+/**
+ * Tests for the TanStack-Query-backed AuthContext.
+ *
+ * Locks in the contracts that drive perceived launch time + the
+ * disconnect-reconnect bug-fix:
+ *
+ * 1. Anonymous-mode happy path: backend reports `auth_enabled: false`
+ * → user is auto-set to the anonymous owner without further work.
+ * 2. Retry-then-recover: 503 fails N times then 200 succeeds → user
+ * is set, no LoginPage flash.
+ * 3. 401 fast-fail: backend returns 401 → query reports error
+ * immediately, NO retry budget burned (would otherwise wait 10s).
+ * 4. Logout invalidates the cache: after logout the cached data shows
+ * `authenticated: false` so the WebSocketContext logout effect
+ * fires deterministically.
+ *
+ * Backoff is verified at the unit level (the AUTH_RETRY constant is
+ * used by `lib/connectionConfig.ts`); the E2E backoff curve is covered
+ * by the manual flake-test plan in docs-internal/release_build_pipeline.md.
+ */
+
+import React from 'react';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, waitFor, act } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { AuthProvider, useAuth, AUTH_STATUS_QUERY_KEY } from '../AuthContext';
+
+// Mock the API config so the fetch URL is predictable in test logs.
+vi.mock('../../config/api', () => ({
+ API_CONFIG: { PYTHON_BASE_URL: 'http://test' },
+}));
+
+// Each test gets a fresh QueryClient with retries disabled by default;
+// individual tests opt back into retries to exercise the retry path.
+function makeQueryClient(opts?: { retry?: number }): QueryClient {
+ return new QueryClient({
+ defaultOptions: {
+ queries: { retry: opts?.retry ?? 0, retryDelay: 0 },
+ mutations: { retry: 0 },
+ },
+ });
+}
+
+function Wrapper({
+ children,
+ client,
+}: {
+ children: React.ReactNode;
+ client: QueryClient;
+}) {
+ return (
+ <QueryClientProvider client={client}>
+ <AuthProvider>{children}</AuthProvider>
+ </QueryClientProvider>
+ );
+}
+
+// Captures the `useAuth()` value across renders so tests can assert on
+// state transitions without remembering to await effects manually.
+function makeProbe() {
+ const states: ReturnType<typeof useAuth>[] = [];
+ function Probe() {
+ states.push(useAuth());
+ return null;
+ }
+ return { states, Probe };
+}
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('AuthContext (TanStack Query)', () => {
+ it('sets the anonymous user when backend reports auth_enabled: false', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ auth_enabled: false,
+ auth_mode: 'single',
+ authenticated: false,
+ user: null,
+ can_register: false,
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ ),
+ );
+
+ const client = makeQueryClient();
+ const { states, Probe } = makeProbe();
+ render(
+ <Wrapper client={client}>
+ <Probe />
+ </Wrapper>,
+ );
+
+ await waitFor(() => {
+ const last = states[states.length - 1];
+ expect(last.isLoading).toBe(false);
+ expect(last.isAuthenticated).toBe(true);
+ expect(last.user?.email).toBe('anonymous');
+ });
+ });
+
+ it('retries on 503 and surfaces the user on the 200', async () => {
+ let attempt = 0;
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async () => {
+ attempt += 1;
+ if (attempt < 3) {
+ return new Response('upstream not ready', { status: 503 });
+ }
+ return new Response(
+ JSON.stringify({
+ auth_enabled: true,
+ auth_mode: 'single',
+ authenticated: true,
+ user: { id: 1, email: 'a@b', display_name: 'A', is_owner: true },
+ can_register: false,
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ );
+ });
+
+ // Allow up to 3 retries here so the third attempt resolves the 200.
+ const client = makeQueryClient({ retry: 3 });
+ const { states, Probe } = makeProbe();
+ render(
+ <Wrapper client={client}>
+ <Probe />
+ </Wrapper>,
+ );
+
+ await waitFor(() => {
+ const last = states[states.length - 1];
+ expect(last.isAuthenticated).toBe(true);
+ expect(last.user?.email).toBe('a@b');
+ });
+ expect(attempt).toBeGreaterThanOrEqual(3);
+ });
+
+ it('does not retry a 401 — surfaces "not authenticated" immediately', async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(JSON.stringify({ detail: 'unauthorized' }), { status: 401 }),
+ );
+
+ // Even with a generous retry budget the AuthContext's `retry`
+ // predicate refuses 401/403 — `fetchSpy` should be called exactly
+ // ONCE.
+ const client = makeQueryClient({ retry: 5 });
+ const { states, Probe } = makeProbe();
+ render(
+ <Wrapper client={client}>
+ <Probe />
+ </Wrapper>,
+ );
+
+ await waitFor(() => {
+ const last = states[states.length - 1];
+ expect(last.isLoading).toBe(false);
+ expect(last.isAuthenticated).toBe(false);
+ expect(last.error).not.toBeNull();
+ });
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('logout invalidates the auth-status cache and flips authenticated → false', async () => {
+ // Initial auth-enabled, logged-in user.
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const url = typeof input === 'string' ? input : (input as Request).url;
+ if (url.endsWith('/logout')) {
+ return new Response('', { status: 200 });
+ }
+ // /status — return a logged-in user the first call, an
+ // unauthenticated response on every subsequent call (after logout
+ // invalidates the cache and refetches).
+ return new Response(
+ JSON.stringify({
+ auth_enabled: true,
+ auth_mode: 'single',
+ authenticated: false,
+ user: null,
+ can_register: false,
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ );
+ });
+
+ const client = makeQueryClient();
+ // Seed the cache with an authenticated user so we can observe the
+ // transition triggered by `logout()`. This mirrors the real flow:
+ // on first mount the query resolves authenticated, then later
+ // logout flips it.
+ client.setQueryData([...AUTH_STATUS_QUERY_KEY], {
+ auth_enabled: true,
+ auth_mode: 'single',
+ authenticated: true,
+ user: { id: 1, email: 'a@b', display_name: 'A', is_owner: true },
+ can_register: false,
+ });
+
+ const { states, Probe } = makeProbe();
+ render(
+ <Wrapper client={client}>
+ <Probe />
+ </Wrapper>,
+ );
+
+ await waitFor(() => {
+ expect(states[states.length - 1].isAuthenticated).toBe(true);
+ });
+
+ await act(async () => {
+ await states[states.length - 1].logout();
+ });
+
+ await waitFor(() => {
+ const last = states[states.length - 1];
+ expect(last.isAuthenticated).toBe(false);
+ expect(last.user).toBeNull();
+ });
+ });
+});
diff --git a/client/src/lib/__tests__/connectionConfig.test.ts b/client/src/lib/__tests__/connectionConfig.test.ts
new file mode 100644
index 00000000..9de55db2
--- /dev/null
+++ b/client/src/lib/__tests__/connectionConfig.test.ts
@@ -0,0 +1,91 @@
+/**
+ * Lock-in tests for `lib/connectionConfig.ts`.
+ *
+ * The tuning constants here drive AuthContext's TanStack Query retry
+ * policy and PartySocket's reconnect envelope. Drift in either —
+ * accidentally raising AUTH_RETRY.CAP_MS to 30s, or flipping
+ * WS_CLOSE.NORMAL_CLOSURE off RFC 6455's 1000 — would silently
+ * regress perceived launch time or break the "intentional close"
+ * contract.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { AUTH_RETRY, WS_CLOSE, WS_RECONNECT } from '../connectionConfig';
+
+describe('AUTH_RETRY', () => {
+ it('keeps base under 100 ms for sub-second first retries', () => {
+ // The previous hand-rolled chain started at 1000 ms, which cost
+ // ~3 s of perceived launch time when the backend was ready 100 ms
+ // after the first failure. Anything above 100 ms here would
+ // re-introduce that stall.
+ expect(AUTH_RETRY.BASE_MS).toBeLessThan(100);
+ });
+
+ it('caps individual retries below 5 s so a slow backend still recovers in <30 s wall', () => {
+ expect(AUTH_RETRY.CAP_MS).toBeGreaterThan(0);
+ expect(AUTH_RETRY.CAP_MS).toBeLessThan(5_000);
+ });
+
+ it('allows enough attempts to span a multi-second backend cold start', () => {
+ // With BASE_MS=50, CAP_MS=4000: cumulative upper bound
+ // sum_{n=0..N-1} min(CAP_MS, BASE_MS * 2^n)
+ // For N=7 → ~10 s, which covers the typical 4 s backend window.
+ expect(AUTH_RETRY.MAX_ATTEMPTS).toBeGreaterThanOrEqual(5);
+ expect(AUTH_RETRY.MAX_ATTEMPTS).toBeLessThanOrEqual(10);
+ });
+
+ it('full-jitter formula stays within the documented envelope for every attempt', () => {
+ // The actual formula:
+ // sleep = random(0, min(CAP_MS, BASE_MS * 2 ** attempt))
+ // Sample 1000 draws per attempt and confirm every draw stays under
+ // the cap. (Random.random() is bounded [0, 1) so the upper bound is
+ // strict.)
+ for (let attempt = 0; attempt < AUTH_RETRY.MAX_ATTEMPTS; attempt += 1) {
+ const upperBound = Math.min(AUTH_RETRY.CAP_MS, AUTH_RETRY.BASE_MS * 2 ** attempt);
+ for (let i = 0; i < 100; i += 1) {
+ const draw = Math.random() * upperBound;
+ expect(draw).toBeGreaterThanOrEqual(0);
+ expect(draw).toBeLessThanOrEqual(AUTH_RETRY.CAP_MS);
+ }
+ }
+ });
+});
+
+describe('WS_RECONNECT', () => {
+ it('first reconnect attempt is sub-second', () => {
+ // Matches the AuthContext retry shape so first reconnect after a
+ // transient drop is fast.
+ expect(WS_RECONNECT.MIN_DELAY_MS).toBeGreaterThan(0);
+ expect(WS_RECONNECT.MIN_DELAY_MS).toBeLessThan(1_000);
+ });
+
+ it('reconnect cap is bounded so dev-iteration restarts are visible', () => {
+ expect(WS_RECONNECT.MAX_DELAY_MS).toBeGreaterThan(WS_RECONNECT.MIN_DELAY_MS);
+ expect(WS_RECONNECT.MAX_DELAY_MS).toBeLessThanOrEqual(15_000);
+ });
+
+ it('grow factor is between 1.0 and 2.0 (gentle ramp, not aggressive)', () => {
+ expect(WS_RECONNECT.GROW_FACTOR).toBeGreaterThan(1.0);
+ expect(WS_RECONNECT.GROW_FACTOR).toBeLessThan(2.0);
+ });
+
+ it('enqueue cap is positive and finite', () => {
+ expect(WS_RECONNECT.MAX_ENQUEUED_MESSAGES).toBeGreaterThan(0);
+ expect(Number.isFinite(WS_RECONNECT.MAX_ENQUEUED_MESSAGES)).toBe(true);
+ });
+});
+
+describe('WS_CLOSE', () => {
+ it('NORMAL_CLOSURE matches RFC 6455 §7.4.1', () => {
+ // PartySocket inspects this exact value to skip its reconnect
+ // loop. Any drift would either re-trigger reconnect on logout
+ // (1000 → !1000) or suppress reconnect on real drops (drift the
+ // other way). RFC 6455 §7.4.1 fixes this at 1000.
+ expect(WS_CLOSE.NORMAL_CLOSURE).toBe(1000);
+ });
+
+ it('NORMAL_CLOSURE is in the 1000-1014 reserved-server range', () => {
+ expect(WS_CLOSE.NORMAL_CLOSURE).toBeGreaterThanOrEqual(1000);
+ expect(WS_CLOSE.NORMAL_CLOSURE).toBeLessThanOrEqual(1014);
+ });
+});
diff --git a/client/src/lib/connectionConfig.ts b/client/src/lib/connectionConfig.ts
new file mode 100644
index 00000000..b87996e0
--- /dev/null
+++ b/client/src/lib/connectionConfig.ts
@@ -0,0 +1,107 @@
+/**
+ * Centralised tuning constants for the auth + WebSocket connection layer.
+ *
+ * The hand-rolled retry chain in `AuthContext` and the flat 3-second
+ * reconnect timer in `WebSocketContext` were retired in favour of
+ * library-backed retry policies (TanStack Query for auth, PartySocket
+ * for the WS). The numeric envelope of those policies lives here so a
+ * future tuning pass — tighter backoff, longer cap, smaller queue — is
+ * a single-file edit and tests can reference the same values.
+ *
+ * Pattern mirrors `client/src/lib/queryConfig.ts`'s `STALE_TIME` /
+ * `GC_TIME` buckets: named, frozen, JSDoc-explained.
+ *
+ * Pre-existing constants (REQUEST_TIMEOUT, ping interval) stay in
+ * `WebSocketContext.tsx` for now — moving them is out of scope for
+ * this change.
+ */
+
+/**
+ * Auth-bootstrap retry tuning, consumed by `AuthContext`'s
+ * `useQuery({ retry, retryDelay })` config.
+ *
+ * Full-jitter exponential backoff per the AWS Architecture Blog —
+ * https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/.
+ *
+ * Formula:
+ *
+ * sleep = random_between(0, min(CAP_MS, BASE_MS * 2^attempt))
+ *
+ * Sample sequence (BASE_MS=50, CAP_MS=4000):
+ *
+ * attempt 0 → up to 50ms
+ * attempt 1 → up to 100ms
+ * attempt 2 → up to 200ms
+ * attempt 3 → up to 400ms
+ * attempt 4 → up to 800ms
+ * attempt 5 → up to 1600ms
+ * attempt 6 → up to 3200ms
+ * attempt 7 → up to 4000ms (capped)
+ *
+ * Total upper-bound wall time ≈ 10 s across 7 retries — covers the
+ * typical ~4 s backend cold-start window in 4-5 attempts. The previous
+ * `1000ms · Math.pow(2, n)` chain needed 31 s in the worst case.
+ */
+export const AUTH_RETRY = {
+ /** Base for the exponential factor (ms). */
+ BASE_MS: 50,
+ /** Cap on a single retry's delay (ms). */
+ CAP_MS: 4_000,
+ /** Stop retrying after this many failed attempts. */
+ MAX_ATTEMPTS: 7,
+} as const;
+
+/**
+ * WebSocket reconnect envelope, consumed by `WebSocketContext`'s
+ * `new ReconnectingWebSocket(url, [], {...})` constructor.
+ *
+ * `partysocket/ws` interleaves jitter automatically; these values
+ * define the envelope it stays inside.
+ *
+ * Sample reconnect sequence (MIN_DELAY_MS=250, GROW_FACTOR=1.3,
+ * MAX_DELAY_MS=8000):
+ *
+ * attempt 1 → ~250ms
+ * attempt 2 → ~325ms
+ * attempt 3 → ~422ms
+ * ...
+ * attempt N → capped at 8s
+ *
+ * Refs:
+ * https://docs.partykit.io/reference/partysocket-api/
+ * https://github.com/cloudflare/partykit/tree/main/packages/partysocket
+ */
+export const WS_RECONNECT = {
+ /** Delay before the first reconnect attempt (ms). */
+ MIN_DELAY_MS: 250,
+ /** Cap on any single reconnect delay (ms). */
+ MAX_DELAY_MS: 8_000,
+ /** Multiplier applied to the previous delay each attempt. */
+ GROW_FACTOR: 1.3,
+ /**
+ * Bound on the send-while-disconnected buffer. PartySocket replays
+ * these calls on the next OPEN. Mirrors the previous
+ * `pendingSendQueueRef` cap intent.
+ */
+ MAX_ENQUEUED_MESSAGES: 200,
+} as const;
+
+/**
+ * WebSocket close codes per RFC 6455 §7.4.1.
+ * https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1
+ *
+ * Browsers expose these via `CloseEvent.code`. PartySocket inspects
+ * `1000` to skip its reconnect loop (intentional close); every other
+ * code is treated as transient and triggers reconnect.
+ *
+ * Only the subset this app actively sends or branches on is listed.
+ * Add new entries here rather than inlining the numeric literal.
+ */
+export const WS_CLOSE = {
+ /**
+ * 1000 — Normal Closure. The connection successfully completed the
+ * purpose for which it was created. Used for logout + unmount
+ * teardown so PartySocket does not reconnect.
+ */
+ NORMAL_CLOSURE: 1000,
+} as const;
diff --git a/client/src/types/__tests__/cloudEvents.test.ts b/client/src/types/__tests__/cloudEvents.test.ts
new file mode 100644
index 00000000..6b64b2b7
--- /dev/null
+++ b/client/src/types/__tests__/cloudEvents.test.ts
@@ -0,0 +1,99 @@
+/**
+ * Parity tests for the FE `WorkflowEvent` interface + `matchesType` helper
+ * vs the backend `WorkflowEvent.matches_type` Pydantic method.
+ *
+ * Mirrors the cases in `server/tests/services/test_events.py::test_matches_type_glob`
+ * exactly so a future divergence (in the server-side regex or the FE
+ * regex) fails one or both suites.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { matchesType, type WorkflowEvent } from '../cloudEvents';
+
+const sample: WorkflowEvent = {
+ specversion: '1.0',
+ id: 'abc123',
+ source: 'stripe://x',
+ type: 'stripe.charge.succeeded',
+ time: '2026-05-06T12:00:00Z',
+ data: {},
+};
+
+describe('matchesType', () => {
+ it('matches the wildcard "all"', () => {
+ expect(matchesType(sample, 'all')).toBe(true);
+ });
+
+ it('matches the empty string as wildcard', () => {
+ expect(matchesType(sample, '')).toBe(true);
+ });
+
+ it('matches an exact type', () => {
+ expect(matchesType(sample, 'stripe.charge.succeeded')).toBe(true);
+ });
+
+ it('matches a leaf-prefix glob', () => {
+ expect(matchesType(sample, 'stripe.charge.*')).toBe(true);
+ });
+
+ it('matches a root-prefix glob', () => {
+ expect(matchesType(sample, 'stripe.*')).toBe(true);
+ });
+
+ it('returns false for a non-matching prefix glob', () => {
+ expect(matchesType(sample, 'payment_intent.*')).toBe(false);
+ });
+
+ it('returns false for a non-matching exact type', () => {
+ expect(matchesType(sample, 'stripe.charge.failed')).toBe(false);
+ });
+
+ it('treats the prefix-only form as exact (no trailing dot)', () => {
+ // Server-side parity: matches_type('stripe') only matches type='stripe',
+ // NOT 'stripe.charge.succeeded' — the glob form requires '.*' to span.
+ expect(matchesType(sample, 'stripe')).toBe(false);
+ const root: WorkflowEvent = { ...sample, type: 'stripe' };
+ expect(matchesType(root, 'stripe')).toBe(true);
+ expect(matchesType(root, 'stripe.*')).toBe(true);
+ });
+});
+
+describe('WorkflowEvent shape', () => {
+ it('parses a backend-emitted credential_catalogue_updated payload', () => {
+ // Sample shape from server/services/status_broadcaster.py's
+ // broadcast_credential_event — copy of what hits the WS today.
+ const payload = {
+ type: 'credential_catalogue_updated',
+ data: {
+ specversion: '1.0',
+ id: 'a1b2c3d4',
+ source: 'machinaos://services/credentials',
+ type: 'credential.api_key.saved',
+ time: '2026-05-06T12:34:56.789Z',
+ subject: 'openai',
+ datacontenttype: 'application/json',
+ data: { provider: 'openai' },
+ },
+ };
+ const envelope = payload.data as WorkflowEvent<{ provider: string }>;
+ expect(envelope.specversion).toBe('1.0');
+ expect(envelope.type).toBe('credential.api_key.saved');
+ expect(envelope.subject).toBe('openai');
+ expect(envelope.data.provider).toBe('openai');
+ expect(matchesType(envelope, 'credential.api_key.*')).toBe(true);
+ expect(matchesType(envelope, 'credential.*')).toBe(true);
+ expect(matchesType(envelope, 'stripe.*')).toBe(false);
+ });
+
+ it('preserves CloudEvents extension attributes when present', () => {
+ const event: WorkflowEvent = {
+ ...sample,
+ workflow_id: 'wf_42',
+ trigger_node_id: 'trigger_abc',
+ correlation_id: 'corr_xyz',
+ };
+ expect(event.workflow_id).toBe('wf_42');
+ expect(event.trigger_node_id).toBe('trigger_abc');
+ expect(event.correlation_id).toBe('corr_xyz');
+ });
+});
diff --git a/client/src/types/cloudEvents.ts b/client/src/types/cloudEvents.ts
new file mode 100644
index 00000000..65f26a00
--- /dev/null
+++ b/client/src/types/cloudEvents.ts
@@ -0,0 +1,78 @@
+/**
+ * CloudEvents v1.0 envelope — mirrors the backend Pydantic `WorkflowEvent`
+ * (`server/services/events/envelope.py`) so the FE can statically type
+ * payloads broadcast over the WebSocket without falling back to `any`.
+ *
+ * Spec: https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md
+ *
+ * Wire shape on the WebSocket today (preserved end-to-end across the
+ * PartySocket / TanStack-Query swap):
+ *
+ * {
+ * "type": "credential_catalogue_updated", // legacy outer routing key
+ * "data": {
+ * "specversion": "1.0",
+ * "id": "<uuid>",
+ * "source": "machinaos://services/credentials",
+ * "type": "credential.api_key.saved", // CloudEvents `type`
+ * "time": "2026-05-06T12:34:56.789Z",
+ * "subject": "openai",
+ * "datacontenttype": "application/json",
+ * "data": { "provider": "openai", ... }
+ * }
+ * }
+ *
+ * Future Wave 12 sources (`stripe.*`, `telegram.*`, `task.*`) will use the
+ * same envelope. The `matchesType` helper provides server-parity glob
+ * dispatch (mirrors `WorkflowEvent.matches_type` in envelope.py).
+ *
+ * Pytest invariant `server/tests/test_credential_broadcasts.py` locks the
+ * backend shape; the FE vitest counterpart locks this interface.
+ */
+
+export interface WorkflowEvent<TData = unknown> {
+ // CloudEvents v1.0 required fields (ordered to match envelope.py).
+ specversion: '1.0';
+ id: string;
+ source: string;
+ type: string;
+ /**
+ * ISO 8601 string. The backend serialises `datetime` via Pydantic's
+ * `model_dump(mode="json")` which produces RFC 3339 UTC timestamps.
+ */
+ time: string;
+ subject?: string;
+ datacontenttype?: string;
+ dataschema?: string;
+ data: TData;
+
+ // CloudEvents extension attributes used by MachinaOs.
+ // `model_config = ConfigDict(extra="allow")` on the Pydantic side means
+ // additional fields may appear and should be tolerated; cast through
+ // `WorkflowEvent<T> & {extra?: unknown}` if you need to read them.
+ workflow_id?: string | null;
+ trigger_node_id?: string | null;
+ correlation_id?: string | null;
+}
+
+/**
+ * Glob-style match on the CloudEvents `type` field.
+ *
+ * Mirrors `WorkflowEvent.matches_type` in `server/services/events/envelope.py`.
+ * Test parity is locked by `client/src/types/__tests__/cloudEvents.test.ts`
+ * vs the corresponding pytest cases.
+ *
+ * matchesType(e, 'stripe.charge.succeeded') // exact
+ * matchesType(e, 'stripe.charge.*') // prefix glob
+ * matchesType(e, 'stripe.*') // prefix glob (1 segment)
+ * matchesType(e, 'all') // wildcard
+ * matchesType(e, '') // wildcard
+ */
+export function matchesType(event: WorkflowEvent, pattern: string): boolean {
+ if (!pattern || pattern === 'all') return true;
+ if (pattern.endsWith('.*')) {
+ const prefix = pattern.slice(0, -2);
+ return event.type === prefix || event.type.startsWith(prefix + '.');
+ }
+ return event.type === pattern;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 174d66af..67c39ccb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -116,6 +116,9 @@ importers:
next-themes:
specifier: ^0.4.6
+ partysocket:
+ specifier: 1.1.18
+ version: 1.1.18([email protected])
postcss:
specifier: ^8.5.6
version: 8.5.6
@@ -3925,6 +3928,9 @@ packages:
resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}
engines: {node: '>= 0.6'}
+ resolution: {integrity: sha512-Gs6RLjzlLRdT8X9ZipJdIZI/Y6/HhRLyq9RdDlCsnpxr/+Nn6bU2EFGuC94GjxqhM+Nmij2Vcq98yoHrU8uNFQ==}
+
resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==}
engines: {node: '>=18.0.0'}
@@ -5273,6 +5279,14 @@ packages:
resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-SyuvH9VavWOSa14v6dYdp3yfSUDII4BQB1+TkGOFBkjfZKjnDBiba4fhdhwBlqGBkqw4ea3gTA1DYhSffX24Wg==}
+ peerDependencies:
+ react: '>=17'
+ peerDependenciesMeta:
+ react:
+ optional: true
+
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
@@ -10908,6 +10922,8 @@ snapshots:
+
@@ -12625,6 +12641,12 @@ snapshots:
+ dependencies:
+ event-target-polyfill: 0.0.4
+ optionalDependencies:
+ react: 19.2.1
+