"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(web): ignore stale authenticated SSE connections
xkam7ar69ad82b4e537
diff --git a/frontend/src/hooks/__tests__/useSSE.test.ts b/frontend/src/hooks/__tests__/useSSE.test.tsindex 42c34cb37..01eeab320 100644--- a/frontend/src/hooks/__tests__/useSSE.test.ts+++ b/frontend/src/hooks/__tests__/useSSE.test.ts@@ -355,4 +355,43 @@ describe("useSSE — SSE ticket auth (VT-003)", () => {// The long-lived key must never appear in the stream URL.expect(MockEventSource.latest.url).not.toContain("remote-key");});++ it("ignores a ticket that resolves after a newer connection", async () => {+ localStorage.setItem("vibe_trading_api_auth_key", "remote-key");+ const ticketResolvers: Array<(response: Response) => void> = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(+ () =>+ new Promise<Response>((resolve) => {+ ticketResolvers.push(resolve);+ }),+ ),+ );++ const { result } = renderHook(() => useSSE());+ act(() => {+ result.current.connect("http://test/session-a/events", {});+ result.current.connect("http://test/session-b/events", {});+ });++ await act(async () => {+ ticketResolvers[1](+ new Response(JSON.stringify({ ticket: "TICKET-B" }), { status: 200 }),+ );+ await Promise.resolve();+ await Promise.resolve();+ });+ await act(async () => {+ ticketResolvers[0](+ new Response(JSON.stringify({ ticket: "TICKET-A" }), { status: 200 }),+ );+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(MockEventSource.instances).toHaveLength(1);+ expect(MockEventSource.latest.url).toContain("session-b/events");+ expect(MockEventSource.latest.url).toContain("ticket=TICKET-B");+ });});diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.tsindex 91ad7cb76..031869449 100644--- a/frontend/src/hooks/useSSE.ts+++ b/frontend/src/hooks/useSSE.ts@@ -35,6 +35,7 @@ export function useSSE(config?: SSEConfig) {const lastEventIdRef = useRef<string | null>(null);const statusRef = useRef<SSEStatus>("disconnected");const onStatusChangeRef = useRef<((s: SSEStatus) => void) | null>(null);+ const generationRef = useRef(0);// LRU dedup setconst seenIdsRef = useRef<Set<string>>(new Set());@@ -67,13 +68,16 @@ export function useSSE(config?: SSEConfig) {return baseUrl;}, []);- const attach = useCallback((url: string) => {- if (closedRef.current) return;+ const attach = useCallback((url: string, generation: number) => {+ if (closedRef.current || generation !== generationRef.current) return;const source = new EventSource(url);sourceRef.current = source;source.onopen = () => {+ if (generation !== generationRef.current || sourceRef.current !== source) {+ return;+ }retryCountRef.current = 0;setStatus("connected");};@@ -91,6 +95,9 @@ export function useSSE(config?: SSEConfig) {];const handleRaw = (eventType: string, raw: MessageEvent) => {+ if (generation !== generationRef.current || sourceRef.current !== source) {+ return;+ }if (raw.lastEventId) {lastEventIdRef.current = raw.lastEventId;}@@ -112,15 +119,21 @@ export function useSSE(config?: SSEConfig) {}source.onerror = () => {- if (closedRef.current) return;+ if (+ closedRef.current ||+ generation !== generationRef.current ||+ sourceRef.current !== source+ ) {+ return;+ }source.close();sourceRef.current = null;- scheduleReconnect();+ scheduleReconnect(generation);};}, [trackEventId, setStatus]);- const doConnect = useCallback(() => {- if (closedRef.current) return;+ const doConnect = useCallback((generation: number) => {+ if (closedRef.current || generation !== generationRef.current) return;const baseUrl = buildUrl(urlRef.current);@@ -129,18 +142,20 @@ export function useSSE(config?: SSEConfig) {// key) the backend bypasses auth, so we connect synchronously and preserve// the original zero-round-trip behavior (and the synchronous test path).if (!getApiAuthKey()) {- attach(baseUrl);+ attach(baseUrl, generation);return;}withAuthTicket(baseUrl)- .then(attach)+ .then((url) => attach(url, generation)).catch(() => {- if (!closedRef.current) scheduleReconnect();+ if (!closedRef.current && generation === generationRef.current) {+ scheduleReconnect(generation);+ }});}, [buildUrl, attach]);- const scheduleReconnect = useCallback(() => {- if (closedRef.current) return;+ const scheduleReconnect = useCallback((generation: number) => {+ if (closedRef.current || generation !== generationRef.current) return;retryCountRef.current += 1;const delay = Math.min(opts.initialRetryMs * Math.pow(opts.backoffFactor, retryCountRef.current - 1),@@ -151,11 +166,14 @@ export function useSSE(config?: SSEConfig) {retryTimerRef.current = setTimeout(() => {retryTimerRef.current = null;- doConnect();+ if (generation === generationRef.current) {+ doConnect(generation);+ }}, delay);}, [opts.initialRetryMs, opts.backoffFactor, opts.maxRetryMs, setStatus, doConnect]);const connect = useCallback((url: string, handlers: Handlers) => {+ const generation = ++generationRef.current;closedRef.current = true;sourceRef.current?.close();if (retryTimerRef.current) {@@ -171,10 +189,11 @@ export function useSSE(config?: SSEConfig) {seenIdsRef.current.clear();seenOrderRef.current.length = 0;- doConnect();+ doConnect(generation);}, [doConnect]);const disconnect = useCallback(() => {+ generationRef.current += 1;closedRef.current = true;if (retryTimerRef.current) {clearTimeout(retryTimerRef.current);