@@ -102,6 +102,9 @@ export function useAIChatController(): AIChatController {
102
102
const trackEvent = useTrackEvent ( ) ;
103
103
const [ searchState , setSearchState ] = useSearch ( true ) ;
104
104
105
+ // Track if we've initialized from the URL ask parameter
106
+ const hasInitializedFromUrlRef = React . useRef < boolean > ( false ) ;
107
+
105
108
// Open AI chat and sync with search state
106
109
const onOpen = React . useCallback ( ( ) => {
107
110
const { messages } = globalState . getState ( ) . state ;
@@ -248,6 +251,9 @@ export function useAIChatController(): AIChatController {
248
251
error : false ,
249
252
} ) ) ;
250
253
254
+ // Reset initialization flag so URL ask can be processed again
255
+ hasInitializedFromUrlRef . current = false ;
256
+
251
257
// Reset ask parameter to empty string (keeps chat open but clears content)
252
258
setSearchState ( ( prev ) => ( {
253
259
ask : '' ,
@@ -257,7 +263,7 @@ export function useAIChatController(): AIChatController {
257
263
} ) ) ;
258
264
} , [ setState , setSearchState ] ) ;
259
265
260
- // Auto-trigger AI chat when ?ask= parameter appears in URL
266
+ // Auto-trigger AI chat when ?ask= parameter appears in URL (only once)
261
267
React . useEffect ( ( ) => {
262
268
const hasNoAsk = searchState ?. ask === undefined || searchState ?. ask === null ;
263
269
const hasQuery = searchState ?. query !== null ;
@@ -269,18 +275,29 @@ export function useAIChatController(): AIChatController {
269
275
// Open the chat when ask parameter appears
270
276
onOpen ( ) ;
271
277
272
- // Auto-post the first message if ask has content and no messages exist yet
278
+ // Auto-post the message if ask has content
273
279
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 ( ) } ) ;
282
292
}
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
+ ] ) ;
284
301
285
302
return React . useMemo ( ( ) => {
286
303
return {
0 commit comments