@@ -102,6 +102,9 @@ export function useAIChatController(): AIChatController {
102102 const trackEvent = useTrackEvent ( ) ;
103103 const [ searchState , setSearchState ] = useSearch ( true ) ;
104104
105+ // Track if we've initialized from the URL ask parameter
106+ const hasInitializedFromUrlRef = React . useRef < boolean > ( false ) ;
107+
105108 // Open AI chat and sync with search state
106109 const onOpen = React . useCallback ( ( ) => {
107110 const { messages } = globalState . getState ( ) . state ;
@@ -248,6 +251,9 @@ export function useAIChatController(): AIChatController {
248251 error : false ,
249252 } ) ) ;
250253
254+ // Reset initialization flag so URL ask can be processed again
255+ hasInitializedFromUrlRef . current = false ;
256+
251257 // Reset ask parameter to empty string (keeps chat open but clears content)
252258 setSearchState ( ( prev ) => ( {
253259 ask : '' ,
@@ -257,7 +263,7 @@ export function useAIChatController(): AIChatController {
257263 } ) ) ;
258264 } , [ setState , setSearchState ] ) ;
259265
260- // Auto-trigger AI chat when ?ask= parameter appears in URL
266+ // Auto-trigger AI chat when ?ask= parameter appears in URL (only once)
261267 React . useEffect ( ( ) => {
262268 const hasNoAsk = searchState ?. ask === undefined || searchState ?. ask === null ;
263269 const hasQuery = searchState ?. query !== null ;
@@ -269,18 +275,29 @@ export function useAIChatController(): AIChatController {
269275 // Open the chat when ask parameter appears
270276 onOpen ( ) ;
271277
272- // Auto-post the first message if ask has content and no messages exist yet
278+ // Auto-post the message if ask has content
273279 if ( searchState ?. ask ?. trim ( ) ) {
274- const { messages } = globalState . getState ( ) . state ;
275- if (
276- // Post new message if it's different from the last user message
277- messages . filter ( ( m ) => m . role === AIMessageRole . User ) . at ( - 1 ) ?. query !==
278- searchState ?. ask ?. trim ( )
279- ) {
280- onPostMessage ( { message : searchState . ask . trim ( ) } ) ;
281- }
280+ // Don't trigger if we're already posting a message
281+ const loading = globalState . getState ( ) . state . loading ;
282+ if ( loading ) return ;
283+
284+ // Only initialize once from URL
285+ if ( hasInitializedFromUrlRef . current ) return ;
286+
287+ // Wait for messageContextRef to be defined before proceeding
288+ if ( ! messageContextRef . current ?. location ) return ;
289+
290+ hasInitializedFromUrlRef . current = true ;
291+ onPostMessage ( { message : searchState . ask . trim ( ) } ) ;
282292 }
283- } , [ searchState ?. ask , searchState ?. query , searchState ?. open , onOpen , onPostMessage ] ) ;
293+ } , [
294+ searchState ?. ask ,
295+ searchState ?. query ,
296+ searchState ?. open ,
297+ messageContextRef ,
298+ onOpen ,
299+ onPostMessage ,
300+ ] ) ;
284301
285302 return React . useMemo ( ( ) => {
286303 return {
0 commit comments