diff --git a/components/AppStateMachine.tsx b/components/AppStateMachine.tsx index cbc1cdb..6c08a4b 100644 --- a/components/AppStateMachine.tsx +++ b/components/AppStateMachine.tsx @@ -60,12 +60,32 @@ export function AppStateMachineProvider({ children }: { children: React.ReactNod if (initialEvent) { console.log('[App Provider] Setting initial state:', initialEvent); send({ type: initialEvent as any }); + } else { + // No specific route matched, we're probably on homepage or other route + // Mark as initialized immediately so we don't interfere + isInitializedRef.current = true; } - // Mark as initialized AFTER sending the event - isInitializedRef.current = true; + // DON'T mark as initialized yet if we sent an event + // Wait for the state change to complete }, [pathname, send]); // Remove 'state' from dependencies! + // Mark as initialized once state matches the target from URL + useEffect(() => { + if (isInitializedRef.current) return; + + const targetStateForPath = + pathname === '/chat' ? 'convo' : + pathname === '/edit' ? 'edit' : + (pathname === '/galaxy' || pathname.startsWith('/galaxy/')) ? 'galaxy' : + null; + + if (targetStateForPath && state.matches(targetStateForPath)) { + console.log('[App Provider] State initialized from URL, marking as ready'); + isInitializedRef.current = true; + } + }, [pathname, state]); + // State machine is source of truth: sync state → URL only // This effect ONLY runs when state changes, not when pathname changes useEffect(() => {