diff --git a/src/__tests__/web/hooks/useMobileSessionManagement.test.ts b/src/__tests__/web/hooks/useMobileSessionManagement.test.ts index d6c5a144..cd878ed8 100644 --- a/src/__tests__/web/hooks/useMobileSessionManagement.test.ts +++ b/src/__tests__/web/hooks/useMobileSessionManagement.test.ts @@ -3,7 +3,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { renderHook, act, waitFor } from '@testing-library/react'; +import { renderHook, act } from '@testing-library/react'; import { useMobileSessionManagement, type UseMobileSessionManagementDeps } from '../../../web/hooks/useMobileSessionManagement'; import type { Session } from '../../../web/hooks/useSessions'; @@ -82,9 +82,8 @@ describe('useMobileSessionManagement', () => { savedActiveTabId: 'tab-1', })); - await waitFor(() => { - expect(result.current.activeSessionIdRef.current).toBe('session-1'); - }); + // Refs should be initialized immediately with saved values (no race condition) + expect(result.current.activeSessionIdRef.current).toBe('session-1'); act(() => { result.current.sessionsHandlers.onSessionOutput('session-1', 'hello', 'ai', 'tab-1'); diff --git a/src/web/hooks/useMobileSessionManagement.ts b/src/web/hooks/useMobileSessionManagement.ts index bb1fbc11..8132b4a0 100644 --- a/src/web/hooks/useMobileSessionManagement.ts +++ b/src/web/hooks/useMobileSessionManagement.ts @@ -198,9 +198,11 @@ export function useMobileSessionManagement( const previousSessionStatesRef = useRef>(new Map()); // Ref to track activeSessionId for use in callbacks (avoids stale closure issues) - const activeSessionIdRef = useRef(null); + // Initialize with same value as state to avoid race condition where WebSocket + // messages arrive before useEffect syncs the ref + const activeSessionIdRef = useRef(urlSessionId || savedActiveSessionId); // Ref to track activeTabId for use in callbacks (avoids stale closure issues) - const activeTabIdRef = useRef(null); + const activeTabIdRef = useRef(urlTabId || savedActiveTabId); // Keep activeSessionIdRef in sync with state useEffect(() => {